Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Heuristic:2aronS Duel Agents Shared Transport Layer

From Leeroopedia
Knowledge Sources
Domains Optimization, Architecture
Last Updated 2026-10-27 00:00 GMT

Overview

Factor the common HTTP concerns (fetch, timeout, auth header, error mapping) into one private `request()` method, and expose protocol-specific public methods that only differ in the path, the body shape, and one header set.

Description

`DuelClient` speaks two wire protocols — OpenAI chat completions and Anthropic messages — but both run over the same transport. The class has a single private `request<T>(path, body, protocol)` that builds headers, applies `AbortSignal.timeout(this.timeoutMs)`, performs the `fetch`, parses the body, and maps non-2xx responses to typed errors. The public methods (`createChatCompletion`, `createMessage`) are thin: they validate protocol-specific preconditions (e.g. `stream` is unsupported) and call `request` with a path and a protocol tag. The only protocol-specific header logic is one branch in `request` that adds `anthropic-version` and `x-api-key` when `protocol === "anthropic"`. This keeps the transport concerns (timeout, fetch injection, error shape) in exactly one place.

Usage

Use this heuristic when a client must speak multiple wire protocols over the same transport — for example, an OpenAI-compatible proxy that also exposes an Anthropic-compatible endpoint. It also applies whenever two API methods share the same base URL, auth scheme, and error model.

The Insight (Rule of Thumb)

  • Action: Extract one private `request(path, body, protocol)` method; keep public methods as thin wrappers that only add protocol-specific preconditions and the path.
  • Value: A `protocol` tag (e.g. `"openai" | "anthropic"`) drives the only protocol-specific branch inside `request` (header set). Everything else — fetch, timeout, body parse, error mapping — is shared.
  • Trade-off: A single `request` method is less readable than two self-contained methods, but the payoff is that a fix to timeout, retry, or error mapping applies to both protocols at once.
  • Compatibility: Allow an injectable `fetch` (`opts.fetch ?? fetch`) so the shared transport is testable and runs in non-Node runtimes (edge, workers).

Reasoning

Duplicating the fetch/timeout/error logic across two methods means every transport fix must be applied twice and the two copies can drift. By centralizing, the class guarantees that both protocols share the same timeout, the same `AbortSignal` behavior, and the same 401/403 → `DuelAuthError` mapping. The `protocol` tag is the only axis of variation, and it lives in one `if` block, so adding a third protocol is a new wrapper method plus one branch — not a new copy of the transport. The injectable `fetch` (`opts.fetch ?? fetch`) is what makes this safe: tests stub `fetch` once and both protocols are covered.

Code Evidence

Shared private transport in `packages/sdk/src/client.ts:120-165`:

private async request<T>(
  path: string,
  body: unknown,
  protocol: "openai" | "anthropic",
): Promise<T> {
  const headers: Record<string, string> = {
    Authorization: `Bearer ${this.apiKey}`,
    "Content-Type": "application/json",
  };
  if (protocol === "anthropic") {
    headers["anthropic-version"] = "2023-06-01";
    headers["x-api-key"] = this.apiKey;
  }
  const res = await this.fetchFn(`${this.baseUrl}${path}`, {
    method: "POST",
    headers,
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(this.timeoutMs),
  });
  // ... shared body parse + 401/403 → DuelAuthError, non-2xx → DuelApiError
}

Thin public wrappers from `packages/sdk/src/client.ts:102-118`:

async createChatCompletion(params): Promise<ChatCompletion> {
  if (params.stream) {
    throw new DuelApiError("Streaming is not supported yet...", 400, null);
  }
  return this.request<ChatCompletion>("/chat/completions", params, "openai");
}

async createMessage(params): Promise<MessagesResponse> {
  return this.request<MessagesResponse>("/messages", params, "anthropic");
}

Injectable fetch from `packages/sdk/src/client.ts:68-77`:

this.fetchFn = opts.fetch ?? fetch;
this.timeoutMs = opts.timeoutMs ?? 60_000;

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment