@theokit/sdk 4.52.0 → 4.52.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +35 -17
  2. package/dist/{agent-HYQGJTIN.js → agent-RDHK6MVT.js} +6 -6
  3. package/dist/{agent-HYQGJTIN.js.map → agent-RDHK6MVT.js.map} +1 -1
  4. package/dist/{agent-C66BEJGO.cjs → agent-U2R2R5JP.cjs} +7 -7
  5. package/dist/{agent-C66BEJGO.cjs.map → agent-U2R2R5JP.cjs.map} +1 -1
  6. package/dist/auth/index.cjs +2 -2
  7. package/dist/auth/index.d.cts +15 -0
  8. package/dist/auth/index.d.ts +15 -0
  9. package/dist/auth/index.js +1 -1
  10. package/dist/{chunk-SPZZSAHV.js → chunk-42PLABFU.js} +3 -3
  11. package/dist/{chunk-SPZZSAHV.js.map → chunk-42PLABFU.js.map} +1 -1
  12. package/dist/{chunk-LLK2RS6I.cjs → chunk-6GS7JI64.cjs} +43 -43
  13. package/dist/{chunk-LLK2RS6I.cjs.map → chunk-6GS7JI64.cjs.map} +1 -1
  14. package/dist/{chunk-YARJG3GV.cjs → chunk-CY7MIMI4.cjs} +3 -3
  15. package/dist/{chunk-YARJG3GV.cjs.map → chunk-CY7MIMI4.cjs.map} +1 -1
  16. package/dist/{chunk-WVDH34LK.cjs → chunk-FRITRLZQ.cjs} +2 -2
  17. package/dist/chunk-FRITRLZQ.cjs.map +1 -0
  18. package/dist/{chunk-DU7PBCAM.js → chunk-GNPI5IWZ.js} +3 -3
  19. package/dist/{chunk-DU7PBCAM.js.map → chunk-GNPI5IWZ.js.map} +1 -1
  20. package/dist/{chunk-ZFARZBOX.js → chunk-KELIQH7K.js} +6 -6
  21. package/dist/{chunk-ZFARZBOX.js.map → chunk-KELIQH7K.js.map} +1 -1
  22. package/dist/{chunk-YBB66SZZ.js → chunk-M5EK7N6R.js} +3 -3
  23. package/dist/{chunk-YBB66SZZ.js.map → chunk-M5EK7N6R.js.map} +1 -1
  24. package/dist/{chunk-U3PAW4PL.js → chunk-NAF4L3T6.js} +2 -2
  25. package/dist/chunk-NAF4L3T6.js.map +1 -0
  26. package/dist/{chunk-ZNEYQ56O.cjs → chunk-WLESQ3ZQ.cjs} +6 -6
  27. package/dist/{chunk-ZNEYQ56O.cjs.map → chunk-WLESQ3ZQ.cjs.map} +1 -1
  28. package/dist/{chunk-2CD5XUAG.cjs → chunk-ZNEE4WWQ.cjs} +5 -5
  29. package/dist/{chunk-2CD5XUAG.cjs.map → chunk-ZNEE4WWQ.cjs.map} +1 -1
  30. package/dist/{compact-session-AXKDB6FC.cjs → compact-session-FBVWO6B3.cjs} +12 -12
  31. package/dist/{compact-session-AXKDB6FC.cjs.map → compact-session-FBVWO6B3.cjs.map} +1 -1
  32. package/dist/{compact-session-DUAUEFRR.js → compact-session-XLXC2CZN.js} +4 -4
  33. package/dist/{compact-session-DUAUEFRR.js.map → compact-session-XLXC2CZN.js.map} +1 -1
  34. package/dist/cron.cjs +6 -6
  35. package/dist/cron.js +5 -5
  36. package/dist/eval.cjs +5 -5
  37. package/dist/eval.js +4 -4
  38. package/dist/index.cjs +28 -28
  39. package/dist/index.js +7 -7
  40. package/dist/{inject-session-TASLP5FA.cjs → inject-session-UBAQ7I3G.cjs} +4 -4
  41. package/dist/{inject-session-TASLP5FA.cjs.map → inject-session-UBAQ7I3G.cjs.map} +1 -1
  42. package/dist/{inject-session-RBGOGACE.js → inject-session-UEH5MAKU.js} +3 -3
  43. package/dist/{inject-session-RBGOGACE.js.map → inject-session-UEH5MAKU.js.map} +1 -1
  44. package/dist/internal/auth/api-key-prefix.d.ts +7 -1
  45. package/package.json +1 -1
  46. package/dist/chunk-U3PAW4PL.js.map +0 -1
  47. package/dist/chunk-WVDH34LK.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/providers/discovery.ts","../src/internal/error-mappers/anthropic.ts","../src/internal/llm/finish.ts","../src/internal/llm/tool-result-content.ts","../src/internal/llm/anthropic-shared.ts","../src/internal/llm/sse.ts","../src/internal/llm/transport-error.ts","../src/internal/llm/anthropic.ts","../src/internal/error-mappers/bedrock.ts","../src/internal/llm/bedrock-token-cache.ts","../src/internal/llm/bedrock-anthropic.ts","../src/internal/llm/fault-injection.ts","../src/internal/error-mappers/ollama.ts","../src/internal/llm/ollama-native.ts","../src/internal/runtime/fixtures/fixture-mode.ts","../src/internal/http.ts","../src/internal/llm/hermes-tool-extract.ts","../src/internal/llm/openai-messages.ts","../src/internal/llm/openai.ts","../src/internal/resilience/circuit-breaker.ts","../src/internal/llm/stream-relay.ts","../src/internal/llm/pool-aware-client.ts","../src/internal/llm/responses.ts","../src/internal/llm/abort-error.ts","../src/internal/llm/retrying-client.ts","../src/internal/error-mappers/vertex.ts","../src/internal/llm/vertex-auth.ts","../src/internal/llm/vertex-anthropic.ts","../src/internal/llm/vertex-gemini.ts","../src/internal/llm/vertex-router.ts","../src/internal/llm/router.ts","../src/internal/local-agent/real-local-run-provider.ts","../src/internal/runtime/compression/compression-model-registry.ts","../src/internal/runtime/compression/compression-summarizer.ts","../src/internal/session/compact-session.ts"],"names":["body","existsSync","flush","joinTextParts","buildClient","text","abortError","parseBody","createRequire","inner","apiKey"],"mappings":";;;;;;;;;;;;;;;;;AA2BA,IAAM,cAAA,GAAiB,eAAA,CAAgB,kCAAA,EAAoC,OAAO;AAAA,EAChF,IAAA,EAAM;AACR,CAAA,CAAE,CAAA;AAEF,SAAS,WAAA,GAAsB;AAC7B,EAAA,OAAO,IAAA,CAAK,OAAA,EAAQ,EAAG,UAAA,EAAY,WAAW,iBAAiB,CAAA;AACjE;AAGA,SAAS,aAAA,GAAwB;AAC/B,EAAA,OAAO,IAAA,CAAK,OAAA,EAAQ,EAAG,UAAA,EAAY,WAAW,wBAAwB,CAAA;AACxE;AAcA,SAAS,gBAAA,GAAgC;AACvC,EAAA,MAAM,OAAA,uBAAc,GAAA,EAAY;AAChC,EAAA,MAAM,O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,IAAA,CAAK,qEAAqE,GAAG;AAAA,CAAI,CAAA;AACjF,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"chunk-YBB66SZZ.js","sourcesContent":["/**\n * Lazy provider discovery (T3.4, ADR D107).\n *\n * Scans `~/.theokit/plugins/model-providers/<name>/index.{js,mjs}` and\n * imports each as a Plugin. Plugins with `kind: \"model-provider\"` register\n * their profile. Errors per plugin are logged + skipped. Idempotent per\n * process.\n *\n * EC-9: dynamic `import()` in Node 22 needs `file://` URL for absolute\n * paths in ESM contexts. `pathToFileURL` handles both.\n *\n * @internal\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { diag } from \"../diagnostics.js\";\nimport { globalSingleton } from \"../global-singleton.js\";\nimport { registerProvider } from \"./registry.js\";\n\n// M47 review F3 — the idempotence flag lives on `globalThis` via `Symbol.for`, mirroring registry.ts's\n// M44 B1 pattern: tsup bundles each entry (`dist/index.js`, `dist/cron.js`, …) with its OWN module copy,\n// so a module-local `let discovered` would re-run discovery once per entry (duplicate I/O + spurious\n// \"Provider overridden\" WARNs). Every bundle copy shares THIS state.\nconst discoveryState = globalSingleton(\"theokit-sdk.providers.discovered\", () => ({\n done: false,\n}));\n\nfunction pluginsRoot(): string {\n return join(homedir(), \".theokit\", \"plugins\", \"model-providers\");\n}\n\n/** The explicit trust allowlist the human edits (M47). Fail-closed: missing/malformed ⇒ empty. */\nfunction trustFilePath(): string {\n return join(homedir(), \".theokit\", \"plugins\", \"trusted-providers.json\");\n}\n\n/**\n * M47 — the trust gate for the dynamic-import surface. A plugin's `index.{js,mjs}` executes arbitrary code\n * at import time, so NOTHING is imported unless the human explicitly trusted the plugin name: either in\n * `~/.theokit/plugins/trusted-providers.json` (a JSON string array — the auditable primary, mirroring the\n * approved-hooks posture) or the additive `THEOKIT_TRUSTED_PROVIDERS` env (comma-separated convenience).\n * Fail-closed: a missing or malformed trust file trusts NOTHING (a malformed file WARNs).\n */\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nfunction loadTrustedNames(): Set<string> {\n const trusted = new Set<string>();\n const path = trustFilePath();\n if (existsSync(path)) {\n try {\n const parsed: unknown = JSON.parse(readFileSync(path, \"utf-8\"));\n if (Array.isArray(parsed)) {\n let discarded = 0;\n for (const name of parsed) {\n if (typeof name === \"string\" && name.length > 0) trusted.add(name);\n else discarded += 1;\n }\n // M47 review F5 — fail-closed AND fail-clear: a valid array with wrong-shaped entries\n // (numbers, objects) silently trusting nothing would leave the user with only the generic\n // per-plugin WARN and no clue the FILE shape is wrong.\n if (discarded > 0) {\n diag(\n `[theokit-sdk] WARN: ${path} contains ${discarded} non-string entr${discarded === 1 ? \"y\" : \"ies\"} — discarded (entries must be plugin-name strings)\\n`,\n );\n }\n } else {\n diag(\n `[theokit-sdk] WARN: ${path} is not a JSON array — trusting NO provider plugins (fail-closed)\\n`,\n );\n }\n } catch {\n diag(\n `[theokit-sdk] WARN: ${path} is not valid JSON — trusting NO provider plugins (fail-closed)\\n`,\n );\n }\n }\n for (const name of (process.env.THEOKIT_TRUSTED_PROVIDERS ?? \"\").split(\",\")) {\n const trimmed = name.trim();\n if (trimmed.length > 0) trusted.add(trimmed);\n }\n return trusted;\n}\n\nexport async function discoverProviderPlugins(): Promise<void> {\n if (discoveryState.done) return;\n discoveryState.done = true;\n\n const root = pluginsRoot();\n if (!existsSync(root)) return;\n\n let entries: string[];\n try {\n entries = await readdir(root);\n } catch {\n return;\n }\n\n const trusted = loadTrustedNames();\n for (const entry of entries) {\n // M47 — the gate fires BEFORE any import(): untrusted code is never evaluated (import-time side effects\n // ARE the attack; a post-import check would be theater).\n if (!trusted.has(entry)) {\n // M47 review F4/F7 — the remedy must be complete: discovery is once-per-process (the latch above),\n // so editing the trust file only takes effect after a restart; and the env format is comma-separated.\n diag(\n `[theokit-sdk] WARN: provider plugin \"${entry}\" is present but NOT trusted — skipped. ` +\n `To trust it, add \"${entry}\" to ${trustFilePath()} (JSON array of names) or ` +\n `THEOKIT_TRUSTED_PROVIDERS (comma-separated), then restart the process.\\n`,\n );\n continue;\n }\n await loadOne(join(root, entry), entry);\n }\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: 2-extension loader (mjs / js) + plugin shape detection (default / named / direct) — inlining is clearer than 5 helper fns.\nasync function loadOne(dir: string, entryName: string): Promise<void> {\n for (const ext of [\"index.mjs\", \"index.js\"]) {\n const indexPath = join(dir, ext);\n if (!existsSync(indexPath)) continue;\n try {\n const mod = await import(pathToFileURL(indexPath).href);\n const plugin = mod.default ?? mod[entryName] ?? mod;\n if (\n plugin !== null &&\n typeof plugin === \"object\" &&\n (plugin as { kind?: unknown }).kind === \"model-provider\"\n ) {\n const profile = (plugin as { profile?: unknown }).profile;\n if (profile !== undefined && typeof profile === \"object\") {\n registerProvider(profile as Parameters<typeof registerProvider>[0]);\n }\n }\n return;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n diag(`[theokit-sdk] failed to load provider plugin \"${entryName}\": ${msg}\\n`);\n return;\n }\n }\n}\n\n/** Test-only reset. @internal */\nexport function _resetDiscovery(): void {\n discoveryState.done = false;\n}\n","/**\n * Anthropic HTTP error mapper (ADR D67).\n *\n * Translates an Anthropic API error response into a typed\n * `TheokitAgentError` subclass with full `ErrorMetadata`. Mapping rules:\n *\n * 401/403 → `AuthenticationError` (`code: \"auth_failed\"`)\n * 429 → `RateLimitError` (`code: \"rate_limit\"`)\n * 400 → `ConfigurationError` (`code: \"context_too_long\"` if body\n * mentions context length, else\n * `\"invalid_request\"`; or\n * `\"content_filtered\"` for policy.)\n * 408 → `NetworkError` (`code: \"timeout\"`)\n * 5xx → `NetworkError` (`code: \"server_error\"` — covers 529\n * overloaded_error common at peak\n * at peak)\n * other → `UnknownAgentError` (`code: \"unknown\"`)\n *\n * Never throws — caller is already in an error path.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n type ErrorCode,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../../errors.js\";\nimport { buildErrorMetadata } from \"./shared.js\";\n\ninterface MapAnthropicErrorArgs {\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\nexport function mapAnthropicError(args: MapAnthropicErrorArgs): TheokitAgentError {\n const { status, body, headers, endpoint } = args;\n const code = mapAnthropicStatusToCode(status, body);\n const message = formatMessage(status, code);\n const metadata = buildErrorMetadata({\n provider: \"anthropic\",\n endpoint,\n code,\n status,\n headers,\n body,\n });\n\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { code: \"anthropic_auth_failed\", metadata });\n }\n if (status === 429) {\n return new RateLimitError(message, { code: \"anthropic_rate_limit\", metadata });\n }\n if (status === 400) {\n return new ConfigurationError(message, {\n code: `anthropic_${code}`,\n metadata,\n });\n }\n if (status === 408) {\n return new NetworkError(message, { code: \"anthropic_timeout\", metadata });\n }\n if (status >= 500 && status < 600) {\n return new NetworkError(message, { code: \"anthropic_server_error\", metadata });\n }\n return new UnknownAgentError(message, { code: \"anthropic_unknown\", metadata });\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: explicit branch table is clearer than splitting\nfunction mapAnthropicStatusToCode(status: number, body: unknown): ErrorCode {\n if (status === 401 || status === 403) return \"auth_failed\";\n if (status === 429) return \"rate_limit\";\n if (status === 408) return \"timeout\";\n if (status === 400) {\n const text = JSON.stringify(body ?? \"\").toLowerCase();\n if (\n text.includes(\"context\") &&\n (text.includes(\"too long\") || text.includes(\"too_long\") || text.includes(\"length\"))\n ) {\n return \"context_too_long\";\n }\n if (\n text.includes(\"filtered\") ||\n text.includes(\"content policy\") ||\n text.includes(\"content_policy\")\n ) {\n return \"content_filtered\";\n }\n return \"invalid_request\";\n }\n if (status >= 500 && status < 600) return \"server_error\";\n return \"unknown\";\n}\n\nfunction formatMessage(status: number, code: ErrorCode): string {\n return `Anthropic API error: ${code} (HTTP ${status})`;\n}\n","import { isPlainObject, tryJson } from \"../../sanitize/coerce.js\";\nimport type { LlmFinish, LlmRequest, LlmStopReason, LlmToolCallPart } from \"./types.js\";\n\n/**\n * Collapse the wider `LlmRequest.system` shape (undefined | string | block[])\n * into a single string. Providers that don't support per-block prompt caching\n * join blocks with a blank-line separator.\n *\n * Shared between Ollama native and OpenAI-compatible clients.\n *\n * @internal\n */\nexport function collapseSystemText(system: LlmRequest[\"system\"]): string {\n if (system === undefined) return \"\";\n if (typeof system === \"string\") return system;\n return system.map((b) => b.text).join(\"\\n\\n\");\n}\n\n/**\n * Decode a buffered JSON-arguments string into an object. Falls back to a\n * `{ raw }` envelope so we never crash on malformed provider output.\n *\n * @internal\n */\nexport function parseToolArguments(buffered: string | undefined): Record<string, unknown> {\n if (buffered === undefined || buffered.length === 0) return {};\n try {\n return JSON.parse(buffered) as Record<string, unknown>;\n } catch {\n // M2 #61 — attempt jsonrepair (reusing the sanitize coerce helper, Rule 9)\n // before giving up, so a slightly-malformed native tool call (trailing\n // comma, unquoted key — the Kimi/K2 class) parses instead of landing in\n // `{ raw }` and bouncing to the model as an invalid_request round-trip.\n const repaired = tryJson(buffered, true);\n if (isPlainObject(repaired)) return repaired;\n return { raw: buffered };\n }\n}\n\n/**\n * Map an OpenAI-compatible `finish_reason` to the provider-agnostic stop reason.\n * Shared by the OpenAI stream accumulator. Unknown reasons fall back to `end_turn`.\n *\n * @internal\n */\nexport function mapOpenAIFinish(reason: string): LlmStopReason {\n switch (reason) {\n case \"tool_calls\":\n return \"tool_use\";\n case \"length\":\n return \"max_tokens\";\n default:\n return \"end_turn\";\n }\n}\n\n/**\n * Build the provider-agnostic `LlmFinish` shape from accumulator state.\n * Shared between the Anthropic and OpenAI stream parsers so the two\n * implementations don't drift on token-usage fields.\n *\n * @internal\n */\nexport function makeLlmFinish(state: {\n stopReason: LlmStopReason;\n text: string;\n toolCalls: LlmToolCallPart[];\n inputTokens?: number;\n outputTokens?: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n /** theokit#122 — the turn's thinking block, with its provider signature when one was issued. */\n thinking?: import(\"./types.js\").LlmThinkingPart;\n}): LlmFinish {\n const finish: LlmFinish = {\n stopReason: state.stopReason,\n text: state.text,\n toolCalls: state.toolCalls,\n };\n if (state.inputTokens !== undefined) finish.inputTokens = state.inputTokens;\n if (state.outputTokens !== undefined) finish.outputTokens = state.outputTokens;\n if (state.cacheReadTokens !== undefined) finish.cacheReadTokens = state.cacheReadTokens;\n if (state.cacheWriteTokens !== undefined) finish.cacheWriteTokens = state.cacheWriteTokens;\n if (state.reasoningTokens !== undefined) finish.reasoningTokens = state.reasoningTokens;\n if (state.thinking !== undefined) finish.thinking = state.thinking;\n return finish;\n}\n","/**\n * SE7 — provider-agnostic helpers for structured tool-result content\n * ({@link ToolResultContentBlock}). Named by CAPABILITY, not by provider:\n *\n * - `toBlockToolResultContent` — for a wire that ACCEPTS content blocks.\n * - `toStringToolResultContent` — for a string-only wire (fail-fast on an image).\n * - `renderToolResultContentText` — map the text parts through a fn (for the guard).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type { ToolResultContentBlock } from \"../../types/content-blocks.js\";\n\n/**\n * For a block-capable provider wire: pass a string through unchanged, or forward\n * the structured blocks as-is (text + image).\n *\n * This is an INTENTIONAL identity: `ToolResultContentBlock` is defined to be\n * exactly the on-wire content-block shape that block-capable providers accept\n * for a tool result — `{ type: \"text\", text }` and\n * `{ type: \"image\", source: { type: \"base64\", media_type, data } }`. Because the\n * SDK type already IS the wire shape, no transformation is needed; this function\n * names that contract at the call site (and is the single seam to add a mapping\n * later, if a block-capable wire ever diverges from this shape). Do NOT add\n * SDK-internal fields to `ToolResultContentBlock` without updating this seam —\n * they would otherwise be forwarded verbatim onto the wire.\n */\nexport function toBlockToolResultContent(\n content: string | ToolResultContentBlock[],\n): string | ToolResultContentBlock[] {\n return content;\n}\n\n/**\n * For a string-only provider wire: pass a string through; flatten text-only\n * blocks to a newline-joined string; **fail fast** with a typed\n * {@link ConfigurationError} when an image block is present — that provider\n * cannot carry an image in a tool result, and silently dropping it would hand\n * the model a lie (per error-handling policy).\n */\nexport function toStringToolResultContent(\n content: string | ToolResultContentBlock[],\n providerName: string,\n): string {\n if (typeof content === \"string\") return content;\n if (content.some((block) => block.type === \"image\")) {\n throw new ConfigurationError(\n `provider \"${providerName}\" does not support image content in tool results`,\n );\n }\n return content\n .filter(\n (block): block is Extract<ToolResultContentBlock, { type: \"text\" }> => block.type === \"text\",\n )\n .map((block) => block.text)\n .join(\"\\n\");\n}\n\n/**\n * Apply `fn` to the text of a tool-result content (both the string form and the\n * text blocks of the structured form); image blocks pass through untouched.\n * Used by the tool-result guard so redaction/delimiting still covers text.\n */\nexport function renderToolResultContentText(\n content: string | ToolResultContentBlock[],\n fn: (text: string) => string,\n): string | ToolResultContentBlock[] {\n if (typeof content === \"string\") return fn(content);\n return content.map((block) =>\n block.type === \"text\" ? { type: \"text\" as const, text: fn(block.text) } : block,\n );\n}\n","/**\n * Shared helpers for Anthropic Messages wire format across direct API\n * (anthropic.ts), Vertex (vertex-anthropic.ts), and Bedrock (bedrock-anthropic.ts)\n * clients. Extracted to remove cross-module clones flagged by jscpd.\n *\n * @internal\n */\n\nimport { parseToolArguments } from \"./finish.js\";\nimport { toBlockToolResultContent } from \"./tool-result-content.js\";\nimport type {\n LlmContentPart,\n LlmMessage,\n LlmRequest,\n LlmStopReason,\n LlmSystemBlock,\n LlmToolCallPart,\n} from \"./types.js\";\n\nexport interface AnthropicResponseLike {\n content?: Array<\n | { type: \"text\"; text: string }\n | { type: \"tool_use\"; id: string; name: string; input: Record<string, unknown> }\n >;\n stop_reason?: string | null;\n usage?: { input_tokens?: number; output_tokens?: number };\n}\n\nexport function extractAnthropicText(response: AnthropicResponseLike): string {\n return (response.content ?? [])\n .filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\");\n}\n\nexport function extractAnthropicToolCalls(response: AnthropicResponseLike): LlmToolCallPart[] {\n return (response.content ?? [])\n .filter(\n (c): c is { type: \"tool_use\"; id: string; name: string; input: Record<string, unknown> } =>\n c.type === \"tool_use\",\n )\n .map((c) => ({\n type: \"tool_use\" as const,\n id: c.id,\n name: c.name,\n input: parseToolArguments(JSON.stringify(c.input)),\n }));\n}\n\nexport function mapAnthropicStopReason(reason: string | null): LlmStopReason {\n switch (reason) {\n case \"tool_use\":\n return \"tool_use\";\n case \"max_tokens\":\n return \"max_tokens\";\n case \"stop_sequence\":\n return \"stop_sequence\";\n case \"end_turn\":\n case null:\n return \"end_turn\";\n default:\n return \"end_turn\";\n }\n}\n\n/**\n * Convert an SDK `LlmMessage` to the Anthropic Messages wire shape.\n * Identical across the three Anthropic-compatible clients (D289/D292).\n */\n/**\n * theokit#122 — replay an extended-thinking block WITH its signature.\n *\n * Anthropic verifies the signature against the text, so both must go back byte-identically or the\n * request is rejected with `400 \"thinking blocks cannot be modified\"`. A part with no signature —\n * an OpenAI-compatible provider's reasoning text, or history recorded before this shipped — is\n * dropped rather than sent unsigned: an unsigned block fails the same validation, so sending it\n * would break the whole turn instead of losing one block of context.\n */\nfunction thinkingToWireBlock(\n part: Extract<LlmContentPart, { type: \"thinking\" }>,\n): Record<string, unknown> | undefined {\n return part.signature === undefined\n ? undefined\n : { type: \"thinking\", thinking: part.text, signature: part.signature };\n}\n\n/** Map one SDK content part to its Anthropic wire block (`undefined` = do not send). */\nfunction partToWireBlock(part: LlmContentPart): Record<string, unknown> | undefined {\n if (part.type === \"text\") return { type: \"text\", text: part.text };\n if (part.type === \"tool_use\") {\n return { type: \"tool_use\", id: part.id, name: part.name, input: part.input };\n }\n // M35 — Anthropic native image block: base64 source, unchanged shape.\n if (part.type === \"image\") return { type: \"image\", source: part.source };\n if (part.type === \"thinking\") return thinkingToWireBlock(part);\n return {\n type: \"tool_result\",\n tool_use_id: part.toolUseId,\n // SE7 — this wire is block-capable: strings pass through, structured\n // text/image blocks are forwarded natively.\n content: toBlockToolResultContent(part.content),\n ...(part.isError === true ? { is_error: true } : {}),\n };\n}\n\nexport function toAnthropicWireMessage(message: LlmMessage): Record<string, unknown> {\n const role = message.role === \"system\" ? \"user\" : message.role;\n // theokit#122 — `filter` drops the blocks the mapper declined to serialize.\n const content = message.content\n .map(partToWireBlock)\n .filter((b): b is Record<string, unknown> => b !== undefined);\n return { role, content };\n}\n\n/**\n * Build the common body shape for Anthropic Messages requests. Caller\n * is responsible for adding wire-specific fields (`anthropic_version`,\n * `model`, `stream`, etc.).\n */\n/**\n * Issue a POST to an Anthropic-compatible Messages endpoint with the\n * standard auth + content-type headers. Caller maps non-2xx via its own\n * dialect-specific error mapper.\n */\nexport function postAnthropicRequest(args: {\n fetchImpl: typeof fetch;\n url: string;\n token: string;\n body: Record<string, unknown>;\n signal: AbortSignal;\n}): Promise<Response> {\n return args.fetchImpl(args.url, {\n method: \"POST\",\n signal: args.signal,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization: `Bearer ${args.token}`,\n },\n body: JSON.stringify(args.body),\n });\n}\n\n/**\n * Map non-2xx response to a typed error via the dialect mapper; consume\n * 2xx body into the Anthropic-shape result. Shared by Bedrock + Vertex\n * Anthropic clients to remove the ~15-line clone (jscpd).\n */\nexport async function handleAnthropicResponse(args: {\n response: Response;\n endpoint: string;\n errorMapper: (info: {\n status: number;\n body: unknown;\n headers: Headers;\n endpoint: string;\n }) => Error;\n}): Promise<{\n text: string;\n toolCalls: LlmToolCallPart[];\n stopReason: LlmStopReason;\n inputTokens?: number;\n outputTokens?: number;\n}> {\n if (!args.response.ok) {\n throw args.errorMapper({\n status: args.response.status,\n body: await parseHttpErrorBody(args.response),\n headers: args.response.headers,\n endpoint: args.endpoint,\n });\n }\n return consumeAnthropicResponse(args.response);\n}\n\nexport async function consumeAnthropicResponse(response: Response): Promise<{\n text: string;\n toolCalls: LlmToolCallPart[];\n stopReason: LlmStopReason;\n inputTokens?: number;\n outputTokens?: number;\n}> {\n const data = (await response.json()) as AnthropicResponseLike;\n return {\n text: extractAnthropicText(data),\n toolCalls: extractAnthropicToolCalls(data),\n stopReason: mapAnthropicStopReason(data.stop_reason ?? null),\n inputTokens: data.usage?.input_tokens,\n outputTokens: data.usage?.output_tokens,\n };\n}\n\nexport async function parseHttpErrorBody(response: Response): Promise<unknown> {\n const text = await response.text().catch(() => \"\");\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nexport interface AnthropicTextBlock {\n type: \"text\";\n text: string;\n cache_control?: { type: \"ephemeral\" };\n}\n\n/**\n * theokit#122 — map the provider-agnostic reasoning `effort` onto Anthropic's token budget.\n *\n * Anthropic does not take an effort label; it takes `budget_tokens`, and the API requires\n * `budget_tokens >= 1024` and `max_tokens > budget_tokens`. The three tiers mirror the effort\n * vocabulary the OpenAI-compatible wire uses, so a caller writes `thinking: \"low\"` once and both\n * providers do something sensible. An unrecognised effort maps to the medium tier rather than\n * failing the request — the knob is a hint, not a contract.\n */\nfunction thinkingBudgetTokens(effort: string): number {\n if (effort === \"low\" || effort === \"minimal\") return 1024;\n if (effort === \"high\" || effort === \"max\") return 16_384;\n return 4096;\n}\n\nexport function buildAnthropicCommonBody(request: LlmRequest): {\n max_tokens: number;\n messages: Array<Record<string, unknown>>;\n system?: string | AnthropicTextBlock[];\n temperature?: number;\n tools?: Array<{ name: string; description: string; input_schema: unknown }>;\n thinking?: { type: \"enabled\"; budget_tokens: number };\n} {\n const body: ReturnType<typeof buildAnthropicCommonBody> = {\n max_tokens: request.maxTokens ?? 4096,\n messages: request.messages.map(toAnthropicWireMessage),\n };\n // theokit#122 — without this the adapter never requested extended thinking, so no signature was\n // ever issued and the rest of the chain would have been dead code (the theokit#144 lesson).\n if (request.reasoning?.effort !== undefined) {\n const budget = thinkingBudgetTokens(request.reasoning.effort);\n body.thinking = { type: \"enabled\", budget_tokens: budget };\n // The API rejects `max_tokens <= budget_tokens`. Raise the ceiling rather than silently\n // shrinking the budget the caller asked for.\n if (body.max_tokens <= budget) body.max_tokens = budget + 4096;\n }\n const wireSystem = encodeAnthropicSystem(request.system);\n if (wireSystem !== undefined) body.system = wireSystem;\n if (request.temperature !== undefined) body.temperature = request.temperature;\n if (request.tools !== undefined && request.tools.length > 0) {\n body.tools = request.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n input_schema: tool.inputSchema,\n }));\n }\n return body;\n}\n\n/**\n * T3.5 — translate `LlmRequest.system` to the Anthropic wire shape.\n *\n * - `undefined` → omit (`undefined`).\n * - `string` → forward verbatim (back-compat, no caching).\n * - `LlmSystemBlock[]` → array of `{type:\"text\", text, cache_control?}`.\n * `cacheable: true` → emit `cache_control:{type:\"ephemeral\"}`.\n * Empty array short-circuits to `undefined`.\n *\n * @internal\n */\nfunction encodeAnthropicSystem(\n system: string | LlmSystemBlock[] | undefined,\n): string | AnthropicTextBlock[] | undefined {\n if (system === undefined) return undefined;\n if (typeof system === \"string\") return system;\n if (system.length === 0) return undefined;\n return system.map((block) => {\n const wire: AnthropicTextBlock = { type: \"text\", text: block.text };\n if (block.cacheable === true) wire.cache_control = { type: \"ephemeral\" };\n return wire;\n });\n}\n","/**\n * Minimal Server-Sent-Events parser. Consumes a fetch `Response` body\n * stream and yields `{ event, data }` records as they arrive. Used by\n * both the Anthropic and OpenAI streaming clients — neither vendor sends\n * binary SSE so a simple text decoder is enough.\n *\n * @internal\n */\n\nimport { NetworkError } from \"../../errors.js\";\n\nexport interface SseRecord {\n event: string;\n data: string;\n}\n\n/**\n * M2 #61 — default idle timeout (ms) between SSE reads. \"Idle\" means *no bytes\n * at all* arrive within the window — distinct from a slow-but-alive stream that\n * keeps trickling chunks. A stalled upstream that handshakes then goes silent no\n * longer hangs the AsyncGenerator forever; it rejects a typed NetworkError so\n * FallbackLlmClient / retry can route it. Pass `0` to disable.\n */\nexport const DEFAULT_SSE_IDLE_MS = 60_000;\n\ninterface ParserState {\n buffer: string;\n event: string;\n data: string;\n}\n\nexport async function* parseSseStream(\n body: ReadableStream<Uint8Array> | null,\n signal: AbortSignal,\n idleTimeoutMs: number = DEFAULT_SSE_IDLE_MS,\n): AsyncGenerator<SseRecord, void, void> {\n if (body === null) return;\n const reader = body.getReader();\n const decoder = new TextDecoder(\"utf-8\");\n const state: ParserState = { buffer: \"\", event: \"message\", data: \"\" };\n try {\n for await (const chunk of readChunks(reader, signal, idleTimeoutMs)) {\n state.buffer += decoder.decode(chunk, { stream: true });\n for (const record of drainCompleteRecords(state)) yield record;\n }\n if (state.data.length > 0) yield { event: state.event, data: state.data };\n } finally {\n // T3.2 + T3.3 — cancel the underlying body stream on EVERY exit path\n // (abort, normal close, consumer break, consumer throw). Without this\n // the upstream HTTP TCP socket stays in CLOSE_WAIT until the OS times\n // it out. cancel() on a finished stream is a no-op so always-cancel\n // is safe.\n await cancelReaderQuietly(reader);\n releaseReader(reader);\n }\n}\n\n/**\n * T3.2 — yield each chunk from `reader` until `done` OR `signal.aborted`.\n * Extracted from `parseSseStream` so its complexity stays under budget.\n *\n * @internal\n */\nasync function* readChunks(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n signal: AbortSignal,\n idleTimeoutMs: number,\n): AsyncGenerator<Uint8Array, void, void> {\n while (true) {\n if (signal.aborted) return;\n const { value, done } = await readWithIdleTimeout(reader, idleTimeoutMs);\n if (done) return;\n if (value !== undefined) yield value;\n }\n}\n\n/**\n * M2 #61 — race a single `reader.read()` against an idle timer. The timer is\n * cleared the moment the read settles (success OR error), so a healthy stream\n * never leaves a dangling timeout. When the timer wins, reject a typed\n * `NetworkError` (`code: \"stream_idle_timeout\"`); the caller's `finally` cancels\n * the body socket. `idleTimeoutMs <= 0` disables the bound (legacy behavior).\n *\n * @internal\n */\nfunction readWithIdleTimeout(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n idleTimeoutMs: number,\n): Promise<Awaited<ReturnType<ReadableStreamDefaultReader<Uint8Array>[\"read\"]>>> {\n if (idleTimeoutMs <= 0) return reader.read();\n return new Promise<Awaited<ReturnType<ReadableStreamDefaultReader<Uint8Array>[\"read\"]>>>(\n (resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new NetworkError(`SSE stream idle for ${idleTimeoutMs}ms — upstream stalled`, {\n code: \"stream_idle_timeout\",\n }),\n );\n }, idleTimeoutMs);\n reader.read().then(\n (result) => {\n clearTimeout(timer);\n resolve(result);\n },\n (err: unknown) => {\n clearTimeout(timer);\n reject(err);\n },\n );\n },\n );\n}\n\n/**\n * T3.2 + T3.3 — cancel the underlying body stream on every exit path.\n * Swallows any cancel-time error per ADR D34's safe-exporter contract\n * (cancel-time errors never propagate to caller).\n *\n * Calling cancel on a stream that already completed naturally is a no-op\n * per the WHATWG streams spec, so unconditional cancel is safe.\n *\n * @internal\n */\nasync function cancelReaderQuietly(reader: ReadableStreamDefaultReader<Uint8Array>): Promise<void> {\n try {\n await reader.cancel();\n } catch {\n // best-effort — already cancelled OR upstream closed\n }\n}\n\nfunction drainCompleteRecords(state: ParserState): SseRecord[] {\n const out: SseRecord[] = [];\n let newlineIndex = state.buffer.indexOf(\"\\n\");\n while (newlineIndex !== -1) {\n const line = state.buffer.slice(0, newlineIndex).replace(/\\r$/, \"\");\n state.buffer = state.buffer.slice(newlineIndex + 1);\n const finished = applyLine(state, line);\n if (finished !== undefined) out.push(finished);\n newlineIndex = state.buffer.indexOf(\"\\n\");\n }\n return out;\n}\n\nfunction applyLine(state: ParserState, line: string): SseRecord | undefined {\n if (line === \"\") {\n if (state.data.length === 0) {\n state.event = \"message\";\n return undefined;\n }\n const record: SseRecord = { event: state.event, data: state.data };\n state.event = \"message\";\n state.data = \"\";\n return record;\n }\n if (line.startsWith(\":\")) return undefined;\n if (line.startsWith(\"event:\")) {\n // T3.1 — HTML Living Standard § 9.2.6: strip exactly ONE leading\n // U+0020 SPACE from the value; preserve other whitespace verbatim.\n state.event = stripOneLeadingSpace(line.slice(6));\n return undefined;\n }\n if (line.startsWith(\"data:\")) {\n const piece = stripOneLeadingSpace(line.slice(5));\n state.data = state.data.length === 0 ? piece : `${state.data}\\n${piece}`;\n }\n return undefined;\n}\n\n/**\n * T3.1 — HTML Living Standard § 9.2.6 step 5 of \"Process the field\":\n * \"If the value of field starts with a U+0020 SPACE character, remove\n * it from value.\"\n *\n * Pre-T3.1 the parser called `.trim()` which destroyed legitimate trailing\n * whitespace (and any extra leading whitespace beyond the first space).\n * This helper strips at most one leading space and leaves everything else.\n *\n * @internal\n */\nfunction stripOneLeadingSpace(value: string): string {\n return value.startsWith(\" \") ? value.slice(1) : value;\n}\n\nfunction releaseReader(reader: ReadableStreamDefaultReader<Uint8Array>): void {\n try {\n reader.releaseLock();\n } catch {\n // already released\n }\n}\n","/**\n * Types the socket failure `fetch` throws **before** any response exists.\n *\n * ## The hole this closes\n *\n * `mapAnthropicError` / `mapOpenAIError` only come into play when there is a `Response` — that is, for\n * **HTTP** errors. An ECONNREFUSED / ETIMEDOUT / DNS failure blows up at `await fetch(...)`, and until\n * M93 it propagated raw: `anthropic.ts` had no `try` at all, and `openai.ts` mapped **only** Ollama and\n * rethrew the rest (`throw fetchErr`).\n *\n * This matters because `isTransientError` — the SDK's single source of truth — returns `false` for\n * a foreign error **by contract** (\"wrap a foreign error in the appropriate SDK error first\",\n * `errors.ts:429`). With the transport letting the raw error escape, M93's retry would be dead\n * exactly the most classic failure it exists to cover. The same applied to the pool's\n * `classifyAndDecide`, which predates this milestone.\n *\n * ## Cancellation is NOT a transport failure\n *\n * `AbortError` also comes out of `fetch`, and wrapping it in a `NetworkError` (which is `isRetryable: true`)\n * would make an explicit user cancellation be retried three times. It propagates intact.\n *\n * @internal\n */\nimport { NetworkError } from \"../../errors.js\";\n\n/** Did the error come from an `abort()` rather than a network failure? */\nfunction ehAbort(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) return false;\n const nome = (err as { name?: unknown }).name;\n return nome === \"AbortError\" || nome === \"TimeoutError\";\n}\n\n/**\n * Wraps a socket failure in a {@link NetworkError}, preserving the cause.\n *\n * Returns the original error — unwrapped — when it is an abort or already an SDK error.\n */\nexport function wrapTransportError(\n err: unknown,\n ctx: { providerId: string; endpoint: string },\n): unknown {\n if (ehAbort(err)) return err;\n if (err instanceof NetworkError) return err;\n const detail = err instanceof Error ? err.message : String(err);\n return new NetworkError(`${ctx.providerId} transport failure on ${ctx.endpoint}: ${detail}`, {\n code: \"transport_failure\",\n cause: err,\n });\n}\n","import { NetworkError } from \"../../errors.js\";\nimport { mapAnthropicError } from \"../error-mappers/anthropic.js\";\nimport { buildAnthropicCommonBody, mapAnthropicStopReason } from \"./anthropic-shared.js\";\nimport { makeLlmFinish, parseToolArguments } from \"./finish.js\";\nimport { parseSseStream } from \"./sse.js\";\nimport { wrapTransportError } from \"./transport-error.js\";\nimport type {\n LlmClient,\n LlmEvent,\n LlmFinish,\n LlmRequest,\n LlmStopReason,\n LlmToolCallPart,\n} from \"./types.js\";\n\n/**\n * Real Anthropic Messages client. Streams `/v1/messages` and translates the\n * vendor SSE events (`content_block_delta`, `content_block_start`,\n * `message_delta`, `message_stop`) into our provider-agnostic `LlmEvent`s.\n *\n * Uses native `fetch` only — no `@anthropic-ai/sdk` dependency.\n *\n * @internal\n */\n\nexport interface AnthropicClientOptions {\n apiKey: string;\n baseUrl?: string;\n version?: string;\n fetch?: typeof fetch;\n /**\n * M45 — extra HTTP headers merged into the request (the profile's static `extraHeaders` + a provider\n * `transform.headers(ctx)`). Assigned AFTER the base headers (mirror of the M41 OpenAIClient wiring), so\n * a provider that owns its auth CAN override them by design.\n */\n extraHeaders?: Record<string, string>;\n}\n\ninterface AnthropicTextDelta {\n type: \"content_block_delta\";\n delta: { type: \"text_delta\"; text: string };\n}\n\ninterface AnthropicToolStart {\n type: \"content_block_start\";\n index: number;\n content_block: { type: \"tool_use\"; id: string; name: string; input: Record<string, unknown> };\n}\n\n/**\n * theokit#122 — the extended-thinking wire.\n *\n * Anthropic opens a `thinking` content block, streams its text as `thinking_delta`, and then emits\n * ONE `signature_delta` carrying the cryptographic signature for that block. All three are needed:\n * replaying the text without the signature is rejected on the next turn with\n * `400 \"thinking blocks cannot be modified\"`.\n */\ninterface AnthropicThinkingStart {\n type: \"content_block_start\";\n index: number;\n content_block: { type: \"thinking\"; thinking?: string; signature?: string };\n}\n\ninterface AnthropicThinkingDelta {\n type: \"content_block_delta\";\n index: number;\n delta: { type: \"thinking_delta\"; thinking: string };\n}\n\ninterface AnthropicSignatureDelta {\n type: \"content_block_delta\";\n index: number;\n delta: { type: \"signature_delta\"; signature: string };\n}\n\ninterface AnthropicToolDelta {\n type: \"content_block_delta\";\n index: number;\n delta: { type: \"input_json_delta\"; partial_json: string };\n}\n\ninterface AnthropicMessageDelta {\n type: \"message_delta\";\n delta: { stop_reason: string | null };\n /**\n * T3.8 — Anthropic native usage shape carries the 5-bucket cache counters\n * when the request annotated system blocks with `cache_control:\n * {type:\"ephemeral\"}` (shipped in T3.5). `cache_creation_input_tokens`\n * surfaces as `LlmFinish.cacheWriteTokens` (the 1.25x billing tier);\n * `cache_read_input_tokens` surfaces as `LlmFinish.cacheReadTokens` (the\n * 0.1x billing tier). Pre-T3.8 the SDK dropped both fields silently.\n */\n usage?: {\n input_tokens?: number;\n output_tokens?: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n };\n}\n\ntype AnthropicEvent =\n | AnthropicTextDelta\n | AnthropicToolStart\n | AnthropicToolDelta\n | AnthropicThinkingStart\n | AnthropicThinkingDelta\n | AnthropicSignatureDelta\n | AnthropicMessageDelta\n | { type: \"message_stop\" }\n | { type: string };\n\nexport class AnthropicClient implements LlmClient {\n readonly name = \"anthropic\";\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: AnthropicClientOptions) {\n this.baseUrl = options.baseUrl ?? \"https://api.anthropic.com\";\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: HTTP+SSE handshake + accumulator is intentionally one block\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n const body = buildAnthropicBody(request);\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n \"x-api-key\": this.options.apiKey,\n \"anthropic-version\": this.options.version ?? \"2023-06-01\",\n };\n // M45 — merge extra/dynamic headers (assign LAST — same override semantics as the chat_completions client).\n if (this.options.extraHeaders !== undefined) Object.assign(headers, this.options.extraHeaders);\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.baseUrl}/v1/messages`, {\n method: \"POST\",\n signal,\n headers,\n body: JSON.stringify(body),\n });\n } catch (fetchErr) {\n // M93 — a socket failure has no `Response`, so `mapAnthropicError` never saw it and it\n // propagated raw. A foreign error is NON-transient per `isTransientError`'s contract, so\n // retry was switched off on exactly the ECONNREFUSED/ETIMEDOUT case.\n throw wrapTransportError(fetchErr, { providerId: this.name, endpoint: \"/v1/messages\" });\n }\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n // Parse body as JSON when possible — gives the mapper access to\n // `error.code` / `error.type` fields. Leave as string otherwise.\n let body: unknown = text;\n try {\n body = JSON.parse(text);\n } catch {\n // not JSON — keep as string\n }\n throw mapAnthropicError({\n status: response.status,\n body,\n headers: response.headers,\n endpoint: \"/v1/messages\",\n });\n }\n\n const accumulator = new AnthropicStreamAccumulator();\n for await (const record of parseSseStream(response.body, signal)) {\n if (record.event === \"ping\" || record.event === \"message_start\") continue;\n let parsed: AnthropicEvent;\n try {\n parsed = JSON.parse(record.data) as AnthropicEvent;\n } catch {\n continue;\n }\n const events = accumulator.consume(parsed);\n for (const event of events) yield event;\n }\n // M2 #61 — a stream that ended without a terminal `message_delta`\n // (stop_reason) was truncated (dropped connection / proxy hiccup); throw a\n // typed error rather than commit the partial turn as a clean `end_turn`\n // (parity with the OpenAI client's truncation guard).\n if (!accumulator.finishReasonSeen) {\n throw new NetworkError(\"Anthropic SSE stream truncated (no stop_reason)\", {\n code: \"stream_truncated\",\n });\n }\n return accumulator.finish();\n }\n}\n\nclass AnthropicStreamAccumulator {\n private text = \"\";\n private stopReason: LlmStopReason = \"end_turn\";\n /**\n * M2 #61 — whether a `message_delta` carrying a real `stop_reason` was seen.\n * A stream that closes before it is a truncation (server FIN / proxy hiccup),\n * not a clean `end_turn` — the caller throws `stream_truncated` on `false`.\n */\n private sawStopReason = false;\n private inputTokens?: number;\n private outputTokens?: number;\n private cacheReadTokens?: number;\n private cacheWriteTokens?: number;\n private readonly toolCalls = new Map<number, LlmToolCallPart>();\n private readonly toolBuffers = new Map<number, string>();\n /**\n * theokit#122 — the turn's thinking block. Text accumulates across `thinking_delta`s; the\n * signature arrives once, on a `signature_delta` for the same block. Undefined until the model\n * actually opens a thinking block, so a non-thinking turn reports nothing.\n */\n private thinking: { text: string; signature?: string } | undefined;\n\n consume(event: AnthropicEvent): LlmEvent[] {\n if (event.type === \"content_block_start\") {\n const block = (event as AnthropicToolStart | AnthropicThinkingStart).content_block;\n if (block.type === \"thinking\") this.handleThinkingStart(event as AnthropicThinkingStart);\n else this.handleToolStart(event as AnthropicToolStart);\n return [];\n }\n if (event.type === \"content_block_delta\") {\n return this.handleContentDelta(event as AnthropicTextDelta | AnthropicToolDelta);\n }\n if (event.type === \"message_delta\") {\n this.handleMessageDelta(event as AnthropicMessageDelta);\n }\n return [];\n }\n\n private handleToolStart(start: AnthropicToolStart): void {\n if (start.content_block.type !== \"tool_use\") return;\n this.toolCalls.set(start.index, {\n type: \"tool_use\",\n id: start.content_block.id,\n name: start.content_block.name,\n input: { ...start.content_block.input },\n });\n this.toolBuffers.set(start.index, \"\");\n }\n\n private handleThinkingStart(start: AnthropicThinkingStart): void {\n // A thinking block can open carrying its opening text (and, on a replayed block, a signature).\n this.thinking = {\n text: start.content_block.thinking ?? \"\",\n ...(start.content_block.signature !== undefined\n ? { signature: start.content_block.signature }\n : {}),\n };\n }\n\n private handleContentDelta(\n delta:\n | AnthropicTextDelta\n | AnthropicToolDelta\n | AnthropicThinkingDelta\n | AnthropicSignatureDelta,\n ): LlmEvent[] {\n if (delta.delta.type === \"text_delta\") {\n const text = (delta as AnthropicTextDelta).delta.text;\n this.text += text;\n return [{ type: \"text_delta\", text }];\n }\n // theokit#122 — extended thinking streams on its own channel, surfaced as `reasoning_delta`\n // exactly like the OpenAI-compatible providers, so the loop needs no provider branch.\n if (delta.delta.type === \"thinking_delta\") {\n const text = (delta as AnthropicThinkingDelta).delta.thinking;\n this.thinking = {\n ...(this.thinking ?? { text: \"\" }),\n text: (this.thinking?.text ?? \"\") + text,\n };\n return [{ type: \"reasoning_delta\", text }];\n }\n // The signature closes the block. It carries no text, so it rides an empty reasoning delta —\n // the loop's accumulator keeps the last signature it sees for the turn.\n if (delta.delta.type === \"signature_delta\") {\n const signature = (delta as AnthropicSignatureDelta).delta.signature;\n this.thinking = { text: this.thinking?.text ?? \"\", signature };\n return [{ type: \"reasoning_delta\", text: \"\", signature }];\n }\n const idx = (delta as AnthropicToolDelta).index;\n const existing = this.toolBuffers.get(idx) ?? \"\";\n this.toolBuffers.set(idx, existing + (delta as AnthropicToolDelta).delta.partial_json);\n return [];\n }\n\n /**\n * T3.8 — extract token counters from Anthropic's `message_delta` usage.\n * Public on the class so the test seam can drive it directly without\n * spinning the SSE parser.\n */\n handleMessageDelta(md: AnthropicMessageDelta): void {\n if (md.delta.stop_reason !== undefined && md.delta.stop_reason !== null) {\n this.sawStopReason = true;\n }\n this.stopReason = mapAnthropicStopReason(md.delta.stop_reason);\n if (md.usage?.input_tokens !== undefined) this.inputTokens = md.usage.input_tokens;\n if (md.usage?.output_tokens !== undefined) this.outputTokens = md.usage.output_tokens;\n // T3.8 — treat 0 as \"no cache activity\" and leave the bucket\n // unreported (mirrors usage-accumulator's filter where zero-value\n // entries are stripped from the emitted TokenUsage).\n if (\n md.usage?.cache_creation_input_tokens !== undefined &&\n md.usage.cache_creation_input_tokens > 0\n ) {\n this.cacheWriteTokens = md.usage.cache_creation_input_tokens;\n }\n if (md.usage?.cache_read_input_tokens !== undefined && md.usage.cache_read_input_tokens > 0) {\n this.cacheReadTokens = md.usage.cache_read_input_tokens;\n }\n }\n\n /** M2 #61 — whether the terminal `message_delta` (stop_reason) was seen. */\n get finishReasonSeen(): boolean {\n return this.sawStopReason;\n }\n\n finish(): LlmFinish {\n const toolCalls: LlmToolCallPart[] = [];\n for (const [index, tool] of this.toolCalls.entries()) {\n const buffered = this.toolBuffers.get(index);\n const parsed = parseToolArguments(buffered);\n if (Object.keys(parsed).length > 0) tool.input = parsed;\n toolCalls.push(tool);\n }\n return makeLlmFinish({\n stopReason: this.stopReason,\n text: this.text,\n toolCalls,\n inputTokens: this.inputTokens,\n outputTokens: this.outputTokens,\n // T3.8 — surface Anthropic native cache-token counters when the\n // request used `cache_control: {type:\"ephemeral\"}` on system blocks.\n cacheReadTokens: this.cacheReadTokens,\n cacheWriteTokens: this.cacheWriteTokens,\n // theokit#122 — carry the thinking block + its signature so the turn can be replayed.\n ...(this.thinking !== undefined\n ? { thinking: { type: \"thinking\" as const, ...this.thinking } }\n : {}),\n });\n }\n}\n\n/**\n * T3.8 — test seam: exposes the AnthropicStreamAccumulator directly so\n * unit tests can drive the message_delta path without spinning the SSE\n * parser. `@internal` — not part of the public surface.\n */\nexport const __testing__AnthropicAccumulator = AnthropicStreamAccumulator;\n\nfunction buildAnthropicBody(request: LlmRequest): Record<string, unknown> {\n return {\n model: request.model,\n stream: true,\n ...buildAnthropicCommonBody(request),\n };\n}\n","/**\n * AWS Bedrock HTTP error mapper (ADRs D67, D300).\n *\n * Bedrock returns either AWS-style `{ message, __type: \"ThrottlingException\" }`\n * or sometimes `{ Message }` (capitalized) depending on the model dialect.\n * We accept both shapes and map to canonical `TheokitAgentError` subclasses.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../../errors.js\";\nimport { buildErrorMetadata } from \"./shared.js\";\n\ninterface BedrockErrorBody {\n __type?: string;\n message?: string;\n Message?: string;\n}\n\nexport interface MapBedrockErrorArgs {\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\ntype BedrockCode =\n | \"rate_limit\"\n | \"auth_failed\"\n | \"invalid_request\"\n | \"timeout\"\n | \"server_error\"\n | \"unknown\";\n\nfunction classifyBedrockError(\n args: MapBedrockErrorArgs,\n awsType: string,\n message: string,\n): BedrockCode {\n if (\n args.status === 429 ||\n awsType.includes(\"Throttling\") ||\n awsType.includes(\"TooManyRequests\")\n ) {\n return \"rate_limit\";\n }\n if (\n args.status === 401 ||\n args.status === 403 ||\n awsType.includes(\"AccessDenied\") ||\n awsType.includes(\"UnauthorizedOperation\")\n ) {\n return \"auth_failed\";\n }\n if (\n args.status === 400 ||\n args.status === 404 ||\n awsType.includes(\"ValidationException\") ||\n awsType.includes(\"ResourceNotFound\") ||\n message.includes(\"use case details\")\n ) {\n return \"invalid_request\";\n }\n if (args.status === 408 || awsType.includes(\"Timeout\")) return \"timeout\";\n if (args.status >= 500) return \"server_error\";\n return \"unknown\";\n}\n\nfunction buildBedrockMetadata(args: MapBedrockErrorArgs, code: BedrockCode) {\n return buildErrorMetadata({\n provider: \"bedrock\",\n endpoint: args.endpoint,\n code,\n status: args.status,\n headers: args.headers,\n body: args.body,\n });\n}\n\nexport function mapBedrockError(args: MapBedrockErrorArgs): TheokitAgentError {\n const parsed = parseBody(args.body);\n const awsType = parsed.__type ?? \"\";\n const message = parsed.message ?? parsed.Message ?? \"Bedrock request failed\";\n const code = classifyBedrockError(args, awsType, message);\n const metadata = buildBedrockMetadata(args, code);\n\n switch (code) {\n case \"rate_limit\":\n return new RateLimitError(`Bedrock throttled: ${message}`, { metadata });\n case \"auth_failed\":\n return new AuthenticationError(`Bedrock auth: ${message}`, { metadata });\n case \"invalid_request\": {\n const friendly = message.includes(\"use case details\")\n ? `Bedrock account setup required: ${message} (AWS Console → Bedrock → Model access → Anthropic → Submit use case form, then retry in 15 min.)`\n : `Bedrock validation: ${message}`;\n return new ConfigurationError(friendly, { metadata });\n }\n case \"timeout\":\n return new NetworkError(`Bedrock timeout: ${message}`, { metadata });\n case \"server_error\":\n return new NetworkError(`Bedrock server error: ${message}`, { metadata });\n default:\n return new UnknownAgentError(`Bedrock unknown: ${message}`, { metadata });\n }\n}\n\nfunction parseBody(body: unknown): BedrockErrorBody {\n if (body !== null && typeof body === \"object\") return body as BedrockErrorBody;\n if (typeof body === \"string\") {\n try {\n return JSON.parse(body) as BedrockErrorBody;\n } catch {\n return {};\n }\n }\n return {};\n}\n","/**\n * Bedrock Bearer token resolution + cache (ADRs D287, D295).\n *\n * Two paths:\n * 1. Explicit env (`AWS_BEARER_TOKEN_BEDROCK`) wins; no refresh.\n * 2. Optional peer dep `@aws/bedrock-token-generator` (D287) auto-generates\n * short-term tokens from the standard AWS credential chain\n * (`@aws-sdk/credential-providers`). Cached for 1.5h.\n *\n * `resolveBedrockToken` returns `undefined` only when BOTH paths produce no\n * token. Caller (router) is responsible for throwing a helpful error\n * (D279/EC-6) — this module is auth-resolution only.\n *\n * @internal\n */\n\nimport { createRequire } from \"node:module\";\n\ninterface CachedToken {\n value: string;\n expiresAt: number;\n}\n\nlet cachedToken: CachedToken | null = null;\n\ninterface BedrockTokenGeneratorApi {\n getToken: (opts: { credentials: unknown; region: string }) => Promise<string>;\n}\n\ninterface CredentialProvidersApi {\n fromNodeProviderChain: () => () => Promise<unknown>;\n}\n\nconst CACHE_TTL_MS = 90 * 60 * 1000; // 1.5h\n\nexport async function resolveBedrockToken(region: string): Promise<string | undefined> {\n const env = process.env.AWS_BEARER_TOKEN_BEDROCK;\n if (env !== undefined && env.length > 0) return env;\n\n const now = Date.now();\n if (cachedToken !== null && cachedToken.expiresAt > now) {\n return cachedToken.value;\n }\n\n try {\n const r = createRequire(import.meta.url);\n const gen = r(\"@aws/bedrock-token-generator\") as BedrockTokenGeneratorApi;\n if (typeof gen.getToken !== \"function\") return undefined;\n\n const providers = r(\"@aws-sdk/credential-providers\") as CredentialProvidersApi;\n if (typeof providers.fromNodeProviderChain !== \"function\") return undefined;\n\n const credentialProvider = providers.fromNodeProviderChain();\n const token = await gen.getToken({ credentials: credentialProvider, region });\n cachedToken = { value: token, expiresAt: now + CACHE_TTL_MS };\n return token;\n } catch {\n return undefined;\n }\n}\n\n/** Test seam — clear cache between tests. */\nexport function __resetBedrockTokenCache(): void {\n cachedToken = null;\n}\n","/**\n * AWS Bedrock client for Anthropic Messages (Adoption Roadmap #8; ADRs\n * D286-D302).\n *\n * v1: non-streaming only (`POST /model/{id}/invoke`). D302 defers\n * `/invoke-with-response-stream` (AWS Event Stream binary format) to v1.x.\n *\n * Body massage (D289):\n * - inject `anthropic_version: \"bedrock-2023-05-31\"`\n * - strip `model` from body (goes in URL)\n * - strip `stream` from body (D302 — non-streaming only in v1)\n *\n * Uses native `fetch` only — no `@aws-sdk/client-bedrock-runtime`.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { mapBedrockError } from \"../error-mappers/bedrock.js\";\nimport {\n inferRegionFromModelId,\n resolveBedrockBaseUrl,\n stripBedrockPrefix,\n} from \"../providers/builtin/bedrock.js\";\nimport {\n buildAnthropicCommonBody,\n handleAnthropicResponse,\n postAnthropicRequest,\n} from \"./anthropic-shared.js\";\nimport { resolveBedrockToken } from \"./bedrock-token-cache.js\";\nimport { makeLlmFinish } from \"./finish.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\n\nexport interface BedrockAnthropicClientOptions {\n /**\n * AWS Bearer token. When non-empty, used as-is. When empty/undefined,\n * resolved lazily per request via `resolveBedrockToken(region)` (D287).\n */\n apiKey?: string;\n /** Override the resolved baseUrl (rarely needed; defaults derive from model id). */\n baseUrl?: string;\n /** Injected fetch impl for tests. */\n fetch?: typeof fetch;\n}\n\nexport class BedrockAnthropicClient implements LlmClient {\n readonly name = \"bedrock\";\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: BedrockAnthropicClientOptions) {\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n private async resolveTokenOrThrow(region: string): Promise<string> {\n const fromOpts = this.options.apiKey;\n if (fromOpts !== undefined && fromOpts.length > 0) return fromOpts;\n const fromEnv = await resolveBedrockToken(region);\n if (fromEnv !== undefined && fromEnv.length > 0) return fromEnv;\n throw new ConfigurationError(\n \"Bedrock requires AWS_BEARER_TOKEN_BEDROCK env var, or install `@aws/bedrock-token-generator` for auto-refresh, or pass apiKey explicitly.\",\n { code: \"auth_failed\" },\n );\n }\n\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n const region = inferRegionFromModelId(request.model) ?? process.env.AWS_REGION ?? \"us-east-1\";\n const token = await this.resolveTokenOrThrow(region);\n\n const bareModel = stripBedrockPrefix(request.model);\n const baseUrl = this.options.baseUrl ?? resolveBedrockBaseUrl(request.model);\n const endpoint = `/model/${encodeURIComponent(bareModel)}/invoke`;\n const url = `${baseUrl}${endpoint}`;\n\n const response = await postAnthropicRequest({\n fetchImpl: this.fetchImpl,\n url,\n token,\n body: buildBedrockBody(request),\n signal,\n });\n\n const consumed = await handleAnthropicResponse({\n response,\n endpoint,\n errorMapper: mapBedrockError,\n });\n if (consumed.text.length > 0) yield { type: \"text_delta\", text: consumed.text };\n return makeLlmFinish(consumed);\n }\n}\n\nfunction buildBedrockBody(request: LlmRequest): Record<string, unknown> {\n // D289: anthropic_version injected; model + stream stripped.\n return {\n anthropic_version: \"bedrock-2023-05-31\",\n ...buildAnthropicCommonBody(request),\n };\n}\n","/**\n * D14 — Fault injection via `THEOKIT_TEST_RESPONSE_OVERRIDE` env var.\n *\n * Decorator pattern (D127 inspired): wraps any `LlmClient` and short-circuits\n * the network call when:\n *\n * 1. `process.env.NODE_ENV === \"test\"` (fail-safe gate — prevents production\n * footgun), AND\n * 2. `process.env.THEOKIT_TEST_RESPONSE_OVERRIDE` is a non-empty JSON string\n * shaped as `{ \"status\": number, \"body\": object | string }`.\n *\n * On any other condition (different NODE_ENV, missing env, malformed JSON),\n * the wrapper delegates to the real client — graceful degradation.\n *\n * Use cases (FAANG-grade chaos testing):\n *\n * - `{\"status\":429,\"body\":{\"error\":{\"code\":\"rate_limit_exceeded\"}}}` →\n * deterministic RateLimitError without burning real quota\n * - `{\"status\":500,\"body\":{\"error\":{\"code\":\"internal_error\"}}}` →\n * deterministic NetworkError for retry/circuit-breaker tests\n * - `{\"status\":200,\"body\":{\"choices\":[{\"message\":{\"content\":\"fake\"}}]}}` →\n * deterministic happy-path text for snapshot tests\n *\n * Compatible with the dogfood-stranger chaos phases (12-15). Replaces the\n * flaky \"50 parallel requests to force 429\" anti-pattern.\n *\n * Wire format mirrors OpenAI Chat Completions (universal — same shape every\n * provider returns). Error mapping reuses `mapOpenAICompatibleError` so the\n * injected errors are byte-equal to what the real provider would raise.\n *\n * @internal\n */\n\nimport { diag } from \"../diagnostics.js\";\nimport { mapOpenAICompatibleError } from \"../error-mappers/openai-compatible.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\n\nconst ENV_GATE_KEY = \"NODE_ENV\";\nconst ENV_GATE_VALUE = \"test\";\nconst ENV_OVERRIDE_KEY = \"THEOKIT_TEST_RESPONSE_OVERRIDE\";\n\ninterface ParsedOverride {\n status: number;\n body: unknown;\n}\n\n/**\n * Wrap an `LlmClient` with the fault-injection decorator. Returns the\n * original client unchanged when the activation gate is not satisfied\n * (cheap noop — no allocation in the hot path of production runtime).\n */\nexport function maybeWrapWithFaultInjection(client: LlmClient): LlmClient {\n // Cheap gate first — production calls never allocate the wrapper.\n if (!isGateOn()) return client;\n return new FaultInjectingLlmClient(client);\n}\n\nexport class FaultInjectingLlmClient implements LlmClient {\n readonly name: string;\n /**\n * Inner (real) client. Exposed so layered transport assertions (router\n * pool-wiring tests, telemetry inspectors) can walk one level deep —\n * same pattern PoolAwareLlmClient uses for its inner transport.\n */\n readonly inner: LlmClient;\n constructor(inner: LlmClient) {\n this.inner = inner;\n this.name = inner.name;\n }\n\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n // Re-check gate on every call — env vars can change between calls and\n // the cost is negligible relative to a network roundtrip.\n if (!isGateOn()) {\n return yield* this.inner.stream(request, signal);\n }\n const parsed = parseOverrideOrWarnOnce();\n if (parsed === undefined) {\n return yield* this.inner.stream(request, signal);\n }\n // Active: synthesize response without calling the real client.\n if (parsed.status >= 400) {\n throw mapOpenAICompatibleError({\n providerId: this.name,\n status: parsed.status,\n body: parsed.body,\n headers: undefined,\n endpoint: \"/v1/chat/completions\",\n });\n }\n const text = extractText(parsed.body);\n yield { type: \"text_delta\", text };\n // theokit#144: no `stop` event — the reason travels on the finish value below.\n return {\n stopReason: \"end_turn\",\n text,\n toolCalls: [],\n inputTokens: 0,\n outputTokens: 0,\n };\n }\n}\n\nfunction isGateOn(): boolean {\n return process.env[ENV_GATE_KEY] === ENV_GATE_VALUE;\n}\n\nlet warnedInvalidJson = false;\n\nfunction parseOverrideOrWarnOnce(): ParsedOverride | undefined {\n const raw = process.env[ENV_OVERRIDE_KEY];\n if (raw === undefined || raw.length === 0) return undefined;\n let candidate: unknown;\n try {\n candidate = JSON.parse(raw);\n } catch (_err) {\n warnInvalidJsonOnce(raw);\n return undefined;\n }\n if (candidate === null || typeof candidate !== \"object\") {\n warnInvalidJsonOnce(raw);\n return undefined;\n }\n const obj = candidate as { status?: unknown; body?: unknown };\n if (typeof obj.status !== \"number\" || !Number.isFinite(obj.status)) {\n warnInvalidJsonOnce(raw);\n return undefined;\n }\n return { status: obj.status, body: obj.body };\n}\n\nfunction warnInvalidJsonOnce(_raw: string): void {\n if (warnedInvalidJson) return;\n warnedInvalidJson = true;\n diag(\n `[theokit-sdk] ${ENV_OVERRIDE_KEY} is set but value is not valid JSON of shape ` +\n `\\`{\"status\": number, \"body\": object | string}\\`. Falling back to real LLM call. ` +\n `This warning is shown once per process.\\n`,\n );\n}\n\n/**\n * Extract textual content from an arbitrary body. Supports:\n * - plain string: returned as-is\n * - OpenAI shape: `body.choices[0].message.content` (most common)\n * - object with `text` field: `body.text`\n * - everything else: empty string (caller can still inspect parsed.body if needed)\n */\nfunction extractText(body: unknown): string {\n if (typeof body === \"string\") return body;\n if (body === null || typeof body !== \"object\") return \"\";\n const fromOpenAi = readOpenAiContent(body);\n if (fromOpenAi !== undefined) return fromOpenAi;\n const obj = body as { text?: unknown };\n if (typeof obj.text === \"string\") return obj.text;\n return \"\";\n}\n\nfunction readOpenAiContent(body: unknown): string | undefined {\n const obj = body as { choices?: unknown };\n if (!Array.isArray(obj.choices) || obj.choices.length === 0) return undefined;\n const first = obj.choices[0] as { message?: { content?: unknown } } | undefined;\n const content = first?.message?.content;\n if (typeof content === \"string\") return content;\n return undefined;\n}\n\n/**\n * Test-only reset for the one-shot stderr warning. Mirrors the D187\n * `_resetNoAuthApiKeyWarnings` pattern.\n *\n * @internal\n */\nexport function _resetFaultInjectionWarnings(): void {\n warnedInvalidJson = false;\n}\n","/**\n * Ollama-specific HTTP/transport error mapper (T1.1, ADR D185).\n *\n * Sits ABOVE the generic OpenAI-compatible mapper for `providerId: \"ollama\"`.\n * Returns `undefined` when the error doesn't match an Ollama-specific\n * pattern — caller (OpenAIClient) then falls back to the generic mapper.\n *\n * Surfaces 3 Ollama-specific failure modes with actionable messages\n * targeted at non-technical users (CLAUDE.md primary persona):\n *\n * 1. **Transport-level `ECONNREFUSED` / `ENOTFOUND`** → \"Run `ollama serve`\"\n * 2. **HTTP 404 with `not found, try pulling`** → \"Run `ollama pull <model>`\"\n * 3. **HTTP 503 with `model is loading`** → retryable (model warming up)\n *\n * @internal\n */\n\nimport { ConfigurationError, NetworkError, type TheokitAgentError } from \"../../errors.js\";\nimport { buildErrorMetadata } from \"./shared.js\";\n\ninterface MapOllamaTransportArgs {\n providerId: string;\n cause: unknown;\n endpoint: string;\n}\n\ninterface MapOllamaHttpArgs {\n providerId: string;\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\n/**\n * Maps fetch-level failures (Node TypeError with `cause.code`). Returns\n * `undefined` for anything that isn't `ECONNREFUSED` / `ENOTFOUND` so\n * the caller can re-throw the original error untouched.\n */\nexport function mapOllamaTransportError(\n args: MapOllamaTransportArgs,\n): TheokitAgentError | undefined {\n if (args.providerId !== \"ollama\") return undefined;\n const causeCode = extractCauseCode(args.cause);\n if (causeCode !== \"ECONNREFUSED\" && causeCode !== \"ENOTFOUND\") return undefined;\n\n const metadata = buildErrorMetadata({\n provider: \"ollama\",\n endpoint: args.endpoint,\n code: \"network\",\n status: 0,\n headers: undefined,\n body: { cause: causeCode },\n });\n return new ConfigurationError(\n \"Ollama is not reachable. Run `ollama serve` to start the local runtime, \" +\n \"or set OLLAMA_HOST to point at a remote Ollama server.\",\n { code: \"ollama_unreachable\", metadata },\n );\n}\n\n/**\n * Maps HTTP-level Ollama failures. Returns `undefined` for status codes\n * that aren't Ollama-specific so the caller falls back to the generic\n * OpenAI-compatible mapper.\n */\nexport function mapOllamaHttpError(args: MapOllamaHttpArgs): TheokitAgentError | undefined {\n if (args.providerId !== \"ollama\") return undefined;\n\n const errString = extractErrorString(args.body).toLowerCase();\n\n // 404 + \"not found, try pulling\" → model not pulled.\n if (args.status === 404 && errString.includes(\"not found\") && errString.includes(\"pull\")) {\n const modelHint = extractModelName(errString);\n const metadata = buildErrorMetadata({\n provider: \"ollama\",\n endpoint: args.endpoint,\n code: \"model_unavailable\",\n status: args.status,\n headers: args.headers,\n body: args.body,\n });\n const pullCmd = modelHint !== undefined ? `ollama pull ${modelHint}` : \"ollama pull <model>\";\n return new ConfigurationError(\n `Ollama model is not pulled. Run \\`${pullCmd}\\` to download it first.`,\n { code: \"ollama_model_not_pulled\", metadata },\n );\n }\n\n // 503 + \"model is loading\" → retryable transient.\n if (args.status === 503 && errString.includes(\"model is loading\")) {\n const metadata = buildErrorMetadata({\n provider: \"ollama\",\n endpoint: args.endpoint,\n code: \"server_error\",\n status: args.status,\n headers: args.headers,\n body: args.body,\n });\n // NetworkError isRetryable: true (default per errors.ts contract).\n return new NetworkError(\n \"Ollama model is loading. Retry in a few seconds — Ollama is warming up the model into memory.\",\n { code: \"ollama_model_loading\", metadata },\n );\n }\n\n return undefined;\n}\n\nfunction extractCauseCode(cause: unknown): string | undefined {\n if (cause === null || typeof cause !== \"object\") return undefined;\n // Native fetch wraps in TypeError(\"fetch failed\") with `cause` chain.\n const directCode = (cause as { code?: unknown }).code;\n if (typeof directCode === \"string\") return directCode;\n const nested = (cause as { cause?: unknown }).cause;\n if (nested !== undefined) return extractCauseCode(nested);\n return undefined;\n}\n\nfunction extractErrorString(body: unknown): string {\n if (typeof body === \"string\") return body;\n if (body === null || typeof body !== \"object\") return \"\";\n const err = (body as { error?: unknown }).error;\n if (typeof err === \"string\") return err;\n return \"\";\n}\n\n/** Pull the model name out of e.g. `model 'llama3.2' not found, try pulling it first`. */\nfunction extractModelName(errString: string): string | undefined {\n const match = errString.match(/'([^']+)'/);\n return match?.[1];\n}\n","/**\n * Ollama native API client (T8.1 follow-up, ADR D191).\n *\n * Targets Ollama's native `/api/chat` endpoint with NDJSON streaming.\n * Critical for **tool calling** — per peer-project upstream warning, the\n * OpenAI-compat `/v1/chat/completions` endpoint BREAKS tool calling in\n * Ollama (models emit raw tool JSON as text instead of structured\n * `tool_calls` blocks). Mirrors peer-project `extensions/ollama/src/stream.ts`.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { mapOllamaHttpError, mapOllamaTransportError } from \"../error-mappers/ollama.js\";\nimport { collapseSystemText, makeLlmFinish } from \"./finish.js\";\nimport { toStringToolResultContent } from \"./tool-result-content.js\";\nimport type {\n LlmClient,\n LlmEvent,\n LlmFinish,\n LlmMessage,\n LlmRequest,\n LlmStopReason,\n LlmToolCallPart,\n} from \"./types.js\";\n\nexport interface OllamaNativeClientOptions {\n /** Optional API key for Ollama Cloud / reverse-proxy. Local Ollama ignores `Authorization`. */\n apiKey?: string;\n /** Base URL. Default `http://localhost:11434`. `/v1` suffix is stripped automatically. */\n baseUrl?: string;\n fetch?: typeof fetch;\n}\n\ninterface OllamaToolCall {\n function: {\n name: string;\n arguments: Record<string, unknown> | string;\n };\n}\n\ninterface OllamaChatChunk {\n message?: {\n role?: \"assistant\";\n content?: string;\n tool_calls?: OllamaToolCall[];\n };\n done?: boolean;\n done_reason?: string;\n prompt_eval_count?: number;\n eval_count?: number;\n}\n\ninterface OllamaChatMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string;\n tool_calls?: OllamaToolCall[];\n tool_name?: string;\n}\n\ninterface OllamaTool {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n}\n\nexport class OllamaNativeClient implements LlmClient {\n readonly name = \"ollama\";\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: OllamaNativeClientOptions) {\n // Strip `/v1` if user mistakenly included it (peer-project guard).\n const raw = (options.baseUrl ?? \"http://localhost:11434\").replace(/\\/+$/, \"\");\n this.baseUrl = raw.replace(/\\/v1$/i, \"\");\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: HTTP+NDJSON handshake + accumulator is intentionally one block (mirrors openai.ts)\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n const headers: Record<string, string> = { \"content-type\": \"application/json\" };\n if (this.options.apiKey !== undefined && this.options.apiKey.length > 0) {\n headers.authorization = `Bearer ${this.options.apiKey}`;\n }\n const body = buildOllamaChatBody(request);\n const url = `${this.baseUrl}/api/chat`;\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method: \"POST\",\n signal,\n headers,\n body: JSON.stringify(body),\n });\n } catch (fetchErr) {\n const mapped = mapOllamaTransportError({\n providerId: \"ollama\",\n cause: fetchErr,\n endpoint: \"/api/chat\",\n });\n if (mapped !== undefined) throw mapped;\n throw fetchErr;\n }\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n let bodyJson: unknown = text;\n try {\n bodyJson = JSON.parse(text);\n } catch {\n /* not JSON */\n }\n const mapped = mapOllamaHttpError({\n providerId: \"ollama\",\n status: response.status,\n body: bodyJson,\n headers: response.headers,\n endpoint: \"/api/chat\",\n });\n if (mapped !== undefined) throw mapped;\n throw new Error(`Ollama /api/chat HTTP ${response.status}: ${text.slice(0, 200)}`);\n }\n\n const accumulator = new OllamaStreamAccumulator();\n if (response.body === null) {\n return accumulator.finish();\n }\n for await (const chunk of parseNdjsonStream(response.body, signal)) {\n const events = accumulator.consume(chunk);\n for (const event of events) yield event;\n if (chunk.done === true) break;\n }\n return accumulator.finish();\n }\n}\n\nclass OllamaStreamAccumulator {\n private text = \"\";\n private stopReason: LlmStopReason = \"end_turn\";\n private inputTokens?: number;\n private outputTokens?: number;\n private readonly toolCalls: LlmToolCallPart[] = [];\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: NDJSON chunk dispatch — text delta + tool_call append + finish-reason mapping is one cohesive accumulator (mirrors openai.ts OpenAIStreamAccumulator.consume).\n consume(chunk: OllamaChatChunk): LlmEvent[] {\n const events: LlmEvent[] = [];\n if (chunk.prompt_eval_count !== undefined) this.inputTokens = chunk.prompt_eval_count;\n if (chunk.eval_count !== undefined) this.outputTokens = chunk.eval_count;\n const msg = chunk.message;\n if (msg?.content !== undefined && msg.content.length > 0) {\n this.text += msg.content;\n events.push({ type: \"text_delta\", text: msg.content });\n }\n if (msg?.tool_calls !== undefined) {\n for (const call of msg.tool_calls) {\n const input =\n typeof call.function.arguments === \"string\"\n ? parseOllamaToolArguments(call.function.arguments)\n : call.function.arguments;\n this.toolCalls.push({\n type: \"tool_use\",\n id: `ollama_call_${this.toolCalls.length + 1}`,\n name: call.function.name,\n input,\n });\n }\n }\n if (chunk.done === true && chunk.done_reason !== undefined) {\n this.stopReason = mapOllamaDoneReason(chunk.done_reason, this.toolCalls.length > 0);\n }\n return events;\n }\n\n finish(): LlmFinish {\n if (this.toolCalls.length > 0 && this.stopReason === \"end_turn\") {\n this.stopReason = \"tool_use\";\n }\n return makeLlmFinish({\n stopReason: this.stopReason,\n text: this.text,\n toolCalls: this.toolCalls,\n inputTokens: this.inputTokens,\n outputTokens: this.outputTokens,\n });\n }\n}\n\nfunction parseOllamaToolArguments(raw: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(raw);\n return typeof parsed === \"object\" && parsed !== null ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\nfunction mapOllamaDoneReason(reason: string, hasToolCalls: boolean): LlmStopReason {\n if (hasToolCalls) return \"tool_use\";\n if (reason === \"length\") return \"max_tokens\";\n if (reason === \"stop\") return \"end_turn\";\n return \"end_turn\";\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: NDJSON line buffering + JSON.parse-with-skip-malformed + signal abort + trailing-buffer flush is one cohesive parser, mirrors peer-project's parseJsonLineStream.\nasync function* parseNdjsonStream(\n body: ReadableStream<Uint8Array>,\n signal: AbortSignal,\n): AsyncGenerator<OllamaChatChunk, void, void> {\n const reader = body.getReader();\n const decoder = new TextDecoder(\"utf-8\");\n let buffer = \"\";\n try {\n while (true) {\n if (signal.aborted) return;\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length === 0) continue;\n try {\n yield JSON.parse(trimmed) as OllamaChatChunk;\n } catch {\n /* skip malformed NDJSON line */\n }\n }\n }\n const tail = buffer.trim();\n if (tail.length > 0) {\n try {\n yield JSON.parse(tail) as OllamaChatChunk;\n } catch {\n /* ignore */\n }\n }\n } finally {\n // T3.2 + T3.3 — mirror sse.ts: cancel the underlying body stream on\n // every exit path (abort, normal close, consumer break, consumer\n // throw). Without this the upstream Ollama HTTP TCP socket stays in\n // CLOSE_WAIT until the OS times it out. cancel() on a finished stream\n // is a no-op so always-cancel is safe.\n try {\n await reader.cancel();\n } catch {\n // best-effort — already cancelled OR upstream closed\n }\n reader.releaseLock();\n }\n}\n\n/**\n * T3.5 — collapse the wider `LlmRequest.system` shape into the legacy\n * single-string form Ollama expects.\n *\n * @internal\n */\nconst ollamaSystemText = collapseSystemText;\n\nfunction buildOllamaChatBody(request: LlmRequest): Record<string, unknown> {\n const messages: OllamaChatMessage[] = [];\n const systemText = ollamaSystemText(request.system);\n if (systemText.length > 0) {\n messages.push({ role: \"system\", content: systemText });\n }\n for (const message of request.messages) {\n for (const out of toOllamaMessages(message)) messages.push(out);\n }\n const tools = toOllamaTools(request.tools);\n const body: Record<string, unknown> = {\n model: request.model,\n stream: true,\n messages,\n // ADR D192: 24h keep_alive prevents Ollama from evicting the chat model\n // when other models (embeddings, judges) are loaded between turns.\n // Cuts cold-load latency from 20-30s to single-digit ms per turn.\n keep_alive: process.env.OLLAMA_KEEP_ALIVE ?? \"24h\",\n };\n if (tools.length > 0) body.tools = tools;\n const opts: Record<string, unknown> = {};\n if (request.maxTokens !== undefined) opts.num_predict = request.maxTokens;\n if (request.temperature !== undefined) opts.temperature = request.temperature;\n if (Object.keys(opts).length > 0) body.options = opts;\n return body;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: 3-role transformation (system/user/assistant) with tool_result→tool role demotion + tool_use→tool_calls promotion is one cohesive mapper; splitting hurts readability.\nfunction toOllamaMessages(message: LlmMessage): OllamaChatMessage[] {\n if (message.role === \"system\") {\n return [{ role: \"system\", content: joinTextParts(message) }];\n }\n if (message.role === \"user\") {\n // M35 — the ollama-native wire has no image content channel here. Fail fast rather than silently\n // dropping an attached image (error-handling.md: no silent drop); OpenAI/OpenRouter carries images.\n if (message.content.some((p) => p.type === \"image\")) {\n throw new ConfigurationError(\n \"image input is not supported on the ollama-native provider; use an OpenAI/OpenRouter model for multimodal turns\",\n { code: \"ollama_image_unsupported\" },\n );\n }\n const out: OllamaChatMessage[] = [];\n for (const part of message.content) {\n if (part.type === \"tool_result\") {\n out.push({\n role: \"tool\",\n // SE7 — string-only tool role: text blocks flatten; image fails fast.\n content: toStringToolResultContent(part.content, \"ollama\"),\n tool_name: part.toolUseId,\n });\n }\n }\n const userText = joinTextParts(message);\n if (userText.length > 0) out.push({ role: \"user\", content: userText });\n return out;\n }\n // assistant\n const text = joinTextParts(message);\n const toolCalls: OllamaToolCall[] = [];\n for (const part of message.content) {\n if (part.type === \"tool_use\") {\n toolCalls.push({\n function: { name: part.name, arguments: part.input },\n });\n }\n }\n const msg: OllamaChatMessage = { role: \"assistant\", content: text };\n if (toolCalls.length > 0) msg.tool_calls = toolCalls;\n return [msg];\n}\n\nfunction joinTextParts(message: LlmMessage): string {\n return message.content\n .filter((p) => p.type === \"text\")\n .map((p) => (p as { text: string }).text)\n .join(\"\\n\");\n}\n\nfunction toOllamaTools(tools: LlmRequest[\"tools\"]): OllamaTool[] {\n if (tools === undefined || tools.length === 0) return [];\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n }));\n}\n","/**\n * Fixture-mode detection.\n *\n * When `THEOKIT_API_BASE_URL` is NOT set and the API key matches the\n * `theo_test_*` pattern, the SDK runs in fixture mode — it returns\n * deterministic, baked-in responses that match the golden fixtures under\n * `tests/golden/`. This is documented behavior and part of the contract\n * (analogous to Stripe's test keys), NOT a test-side mock.\n *\n * When `THEOKIT_API_BASE_URL` is set (e.g. pointing at a test HTTP server\n * or a real Theo PaaS instance), the SDK always performs real HTTP\n * requests — fixture mode is short-circuited.\n *\n * @internal\n */\n\nimport { existsSync } from \"node:fs\";\n\nconst FIXTURE_API_KEY_PREFIX = \"theo_test_\";\n\n/**\n * Returns `true` when the given API key is a fixture-mode key.\n *\n * @internal\n */\nexport function isFixtureApiKey(apiKey: string | undefined): boolean {\n if (apiKey === undefined) return false;\n return apiKey.startsWith(FIXTURE_API_KEY_PREFIX);\n}\n\n/**\n * Returns the base URL configured via `THEOKIT_API_BASE_URL`, or `undefined`\n * when not set.\n *\n * @internal\n */\nexport function getConfiguredBaseUrl(): string | undefined {\n const value = process.env.THEOKIT_API_BASE_URL;\n if (value === undefined || value.length === 0) return undefined;\n return value;\n}\n\n/**\n * Returns `true` when the SDK should respond from baked-in fixture data\n * instead of performing a real HTTP request.\n *\n * Rule: fixture mode is on iff (no explicit base URL configured) AND\n * (API key matches the fixture-key pattern).\n *\n * @internal\n */\nexport function shouldUseFixtureMode(apiKey: string | undefined): boolean {\n if (getConfiguredBaseUrl() !== undefined) return false;\n return isFixtureApiKey(apiKey);\n}\n\n/**\n * Returns `true` when the local runtime should drive the real LLM agent\n * loop instead of the deterministic fixture responder. Real mode requires\n * a non-fixture API key AND at least one provider env credential.\n *\n * @internal\n */\nexport function shouldUseRealLocalRuntime(apiKey: string | undefined): boolean {\n if (isFixtureApiKey(apiKey)) return false;\n if (apiKey === undefined || apiKey.length === 0) return false;\n // ADR D182 / T1.2: `authType: \"none\"` providers (Ollama, LM Studio,\n // llama.cpp) do not require any provider env var. Treat their presence\n // — signaled via OLLAMA_HOST/LMSTUDIO_HOST/LLAMACPP_HOST OR the\n // implicit-localhost default — as a green-light for real runtime.\n // For zero-config Ollama, we accept the default `http://localhost:11434`\n // unconditionally; the actual call will surface a typed\n // `ollama_unreachable` if Ollama is not running.\n return (\n (typeof process.env.ANTHROPIC_API_KEY === \"string\" &&\n process.env.ANTHROPIC_API_KEY.length > 0) ||\n (typeof process.env.OPENAI_API_KEY === \"string\" && process.env.OPENAI_API_KEY.length > 0) ||\n (typeof process.env.OPENROUTER_API_KEY === \"string\" &&\n process.env.OPENROUTER_API_KEY.length > 0) ||\n isAwsBedrockAuthAvailable() ||\n isGcpVertexAuthAvailable() ||\n isLocalNoAuthProviderAvailable()\n );\n}\n\n/**\n * ADRs D286-D287: Bedrock green-lights real runtime when EITHER\n * `AWS_BEARER_TOKEN_BEDROCK` is set explicitly OR the standard AWS\n * credential chain (`AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY` /\n * `AWS_PROFILE` / instance role) can mint a Bearer via\n * `@aws/bedrock-token-generator`. We only check synchronous signals here;\n * the actual token resolution happens lazily in\n * `BedrockAnthropicClient.stream`.\n */\nfunction isAwsBedrockAuthAvailable(): boolean {\n if (\n typeof process.env.AWS_BEARER_TOKEN_BEDROCK === \"string\" &&\n process.env.AWS_BEARER_TOKEN_BEDROCK.length > 0\n ) {\n return true;\n }\n if (\n typeof process.env.AWS_ACCESS_KEY_ID === \"string\" &&\n process.env.AWS_ACCESS_KEY_ID.length > 0\n ) {\n return true;\n }\n if (typeof process.env.AWS_PROFILE === \"string\" && process.env.AWS_PROFILE.length > 0) {\n return true;\n }\n // Default profile file (~/.aws/credentials). The credential chain will\n // resolve it via fromNodeProviderChain() at stream time, or surface a\n // helpful error if neither file nor IMDS is reachable.\n return awsCredentialsFileExists();\n}\n\nfunction awsCredentialsFileExists(): boolean {\n try {\n const home = process.env.HOME ?? process.env.USERPROFILE;\n if (home === undefined || home.length === 0) return false;\n return existsSync(`${home}/.aws/credentials`) || existsSync(`${home}/.aws/config`);\n } catch {\n return false;\n }\n}\n\n/**\n * ADR D288: Vertex green-lights real runtime when EITHER\n * `GOOGLE_APPLICATION_CREDENTIALS` is set OR `GOOGLE_CLOUD_PROJECT` is set\n * (ADC will use gcloud user creds / metadata server). The actual token\n * resolution happens lazily in `VertexAnthropicClient.stream` /\n * `VertexGeminiClient.stream`.\n */\nfunction isGcpVertexAuthAvailable(): boolean {\n if (\n typeof process.env.GOOGLE_APPLICATION_CREDENTIALS === \"string\" &&\n process.env.GOOGLE_APPLICATION_CREDENTIALS.length > 0\n ) {\n return true;\n }\n if (\n typeof process.env.GOOGLE_CLOUD_PROJECT === \"string\" &&\n process.env.GOOGLE_CLOUD_PROJECT.length > 0\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * ADR D182 / T1.2: zero-config local providers (`authType: \"none\"`) are\n * always available — Ollama defaults to localhost:11434, LM Studio to\n * localhost:1234, llama.cpp to localhost:8080. We don't probe here\n * (would require async); we return `true` when ANY of the documented\n * local hosts is reachable in spirit. The first real LLM call surfaces\n * `ollama_unreachable` via the typed mapper if no daemon is up.\n */\nfunction isLocalNoAuthProviderAvailable(): boolean {\n // Always true — the SDK ships Ollama as a builtin. Caller will see a\n // typed error if it isn't actually running.\n return true;\n}\n","import {\n AuthenticationError,\n ConfigurationError,\n IntegrationNotConnectedError,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../errors.js\";\nimport { getConfiguredBaseUrl } from \"./runtime/fixtures/fixture-mode.js\";\n\n/**\n * Default base URL used when neither `THEOKIT_API_BASE_URL` nor an explicit\n * override is provided. The fixture-mode short-circuit normally bypasses this\n * for `theo_test_*` keys; consumers with real keys hit this URL.\n *\n * @internal\n */\nexport const DEFAULT_BASE_URL = \"https://api.usetheo.dev\";\n\n/**\n * HTTP request options accepted by {@link httpRequest}.\n *\n * @internal\n */\nexport interface HttpRequestOptions {\n apiKey: string;\n method?: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n body?: unknown;\n /** Override the default `fetch` (useful for tests / instrumentation). */\n fetchFn?: typeof globalThis.fetch;\n /** Extra headers merged into the default set. */\n headers?: Record<string, string>;\n}\n\n/**\n * Server-side error envelope (`{ error: { code, message, ... } }` or a flat\n * shape) parsed off non-2xx responses.\n *\n * @internal\n */\ninterface ErrorEnvelope {\n code?: string;\n message?: string;\n protoErrorCode?: string;\n provider?: string;\n helpUrl?: string;\n}\n\n/**\n * Resolve the effective base URL (explicit env > default).\n *\n * @internal\n */\nexport function resolveBaseUrl(): string {\n return getConfiguredBaseUrl() ?? DEFAULT_BASE_URL;\n}\n\n/**\n * Perform an authenticated JSON HTTP request, mapping non-2xx responses to\n * the public typed-error hierarchy. Throws subclasses of `TheokitAgentError`\n * on failure.\n *\n * @internal\n */\nexport async function httpRequest<T>(path: string, options: HttpRequestOptions): Promise<T> {\n const url = `${resolveBaseUrl()}${path}`;\n const fetchFn = options.fetchFn ?? globalThis.fetch;\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${options.apiKey}`,\n ...(options.headers ?? {}),\n };\n const body = options.body !== undefined ? JSON.stringify(options.body) : undefined;\n\n const response = await safeFetch(fetchFn, url, {\n method: options.method ?? \"GET\",\n headers,\n body,\n });\n\n if (!response.ok) {\n const parsed = await safeParseJsonResponse(response);\n throw mapHttpStatusToError(response.status, parsed);\n }\n\n return (await safeParseJsonResponse(response)) as T;\n}\n\nasync function safeFetch(\n fetchFn: typeof globalThis.fetch,\n url: string,\n init: RequestInit,\n): Promise<Response> {\n try {\n return await fetchFn(url, init);\n } catch (cause) {\n throw new NetworkError(\"HTTP request failed\", { code: \"network_error\", cause });\n }\n}\n\nasync function safeParseJsonResponse(response: Response): Promise<unknown> {\n try {\n return await response.json();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Read the body of a NON-OK response for an error mapper: JSON when it parses, the raw\n * text otherwise (never throws, never `undefined` — an unreadable stream reads as `\"\"`).\n *\n * Distinct from {@link safeParseJsonResponse}, which drops a non-JSON body to `undefined`.\n * Error mappers need the raw text preserved: it is what surfaces on the mapped error's\n * `raw` field when a provider answers with HTML or a bare string.\n *\n * @internal\n */\nexport async function readErrorResponseBody(response: Response): Promise<unknown> {\n const text = await response.text().catch(() => \"\");\n try {\n return JSON.parse(text);\n } catch {\n // not JSON — keep as string for the mapper's raw field\n return text;\n }\n}\n\n/**\n * Translate an HTTP error response into a typed `TheokitAgentError` subclass.\n *\n * @internal\n */\nexport function mapHttpStatusToError(status: number, body: unknown): TheokitAgentError {\n const envelope = extractErrorEnvelope(body);\n const message = envelope.message ?? `HTTP ${status}`;\n const errorOptions = {\n code: envelope.code,\n protoErrorCode: envelope.protoErrorCode,\n cause: body,\n };\n\n if (envelope.code === \"integration_not_connected\") {\n return new IntegrationNotConnectedError(message, {\n provider: envelope.provider ?? \"unknown\",\n helpUrl: envelope.helpUrl ?? \"\",\n code: envelope.code,\n cause: body,\n });\n }\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, errorOptions);\n }\n if (status === 429) {\n return new RateLimitError(message, errorOptions);\n }\n if (status >= 400 && status < 500) {\n return new ConfigurationError(message, errorOptions);\n }\n if (status >= 500) {\n return new NetworkError(message, errorOptions);\n }\n return new UnknownAgentError(message, errorOptions);\n}\n\nfunction extractErrorEnvelope(body: unknown): ErrorEnvelope {\n if (!body || typeof body !== \"object\") return {};\n const record = body as Record<string, unknown>;\n const inner = record.error;\n const source: unknown = inner && typeof inner === \"object\" ? inner : record;\n return readEnvelopeFields(source as Record<string, unknown>);\n}\n\nfunction readEnvelopeFields(record: Record<string, unknown>): ErrorEnvelope {\n return {\n code: pickString(record, \"code\"),\n message: pickString(record, \"message\"),\n protoErrorCode: pickString(record, \"protoErrorCode\"),\n provider: pickString(record, \"provider\"),\n helpUrl: pickString(record, \"helpUrl\"),\n };\n}\n\nfunction pickString(record: Record<string, unknown>, key: string): string | undefined {\n const value = record[key];\n return typeof value === \"string\" ? value : undefined;\n}\n","/**\n * Hermes tool-call extraction — leaked-dialect safe-parse (theokit#58 follow-up).\n *\n * Some models (qwen3-coder via OpenRouter, OpenAI-compatible API) intermittently emit their\n * Hermes tool-call dialect as assistant TEXT content instead of native `tool_calls`:\n *\n * <function=NAME><parameter=KEY>VALUE</parameter>...</function></tool_call>\n *\n * When that happens the provider sends ZERO native tool_calls, so the agent loop sees an\n * `end_turn` with no tools and the intended call is silently lost. This pure helper recovers\n * those calls from the content so the loop can execute them.\n *\n * OPT-IN only (`ProviderProfile.extractToolCallsFromContent`) and run ONLY when the provider\n * emitted no native tool_calls. A code assistant can legitimately print a literal `<function=` in a\n * fenced code block, so recovery is gated TWICE: the per-route flag is the coarse enable, and the R5\n * request-scoped `allowedToolNames` allowlist below is the precise false-positive guard — a block is\n * promoted only when its name is a real tool in the current request. The size-guard (no native call)\n * prevents double-counting a real native call.\n *\n * Fail-open like `stripThinkBlocks`: a partial/unclosed block (missing the `</tool_call>`\n * marker) is NOT matched — it stays in the residual text and yields no tool call, so a corrupted\n * stream never fabricates a call from junk.\n *\n * Accepted best-effort limit (mirrors the consumer-side stripper EC-5): if a parameter VALUE\n * contains the literal substring `</tool_call>`, the non-greedy block scanner closes at that inner\n * occurrence. This errs toward NOT over-consuming text — same class as `strip-think`'s EC-10.\n *\n * Recovered parameter values are ALWAYS strings: the text dialect carries no per-param type info, so\n * `<parameter=count>5</parameter>` yields `{ count: \"5\" }`, not `{ count: 5 }`. A downstream schema\n * (e.g. Zod) coercing/validating the tool input is the right place to type it — a mismatch there\n * fails clear (typed tool error), never silently. This differs from the native `tool_calls` path,\n * whose `arguments` is JSON and is parsed into typed values.\n *\n * @internal\n */\nimport { sanitizeToolInput } from \"../../sanitize/sanitize-tool-input.js\";\nimport type { LlmToolCallPart } from \"./types.js\";\n\n/** A full leaked block: `<function=NAME> …inner… </tool_call>`. The closing `</tool_call>` is\n * required (fail-open: a partial block at stream end is left as text). Non-greedy inner. */\nconst HERMES_BLOCK = /<function=\\s*([^>\\s]+)\\s*>([\\s\\S]*?)<\\/tool_call>/g;\n/** A single parameter inside a block: `<parameter=KEY>VALUE</parameter>`. Non-greedy value. */\nconst HERMES_PARAM = /<parameter=\\s*([^>\\s]+)\\s*>([\\s\\S]*?)<\\/parameter>/g;\n\nexport interface HermesExtractResult {\n /** Recovered tool calls (empty when none matched). */\n toolCalls: LlmToolCallPart[];\n /** Content with every PROMOTED block removed + trimmed; gated-out and unmatched blocks stay visible. */\n residualText: string;\n /** Names of well-formed leaked blocks that WERE dropped by the request-scoped allowlist (R5) — a\n * block whose name is not a tool in the current request. Empty when no allowlist was applied or\n * nothing was gated out. The caller logs these so a guard firing is observable in production. */\n droppedNames: string[];\n}\n\n/**\n * Recover Hermes-dialect tool calls leaked into assistant text. `makeId` supplies a unique id per\n * recovered call (the provider gave none). Pure — no side effects.\n *\n * @param allowedToolNames R5 request-scoped gate — when provided, only a block whose name is in the\n * set is promoted (exact, case-sensitive); an empty set promotes nothing; `undefined` recovers all\n * (back-compat). Gated-out blocks stay as visible text (they are not tool calls).\n * @internal\n */\nexport function extractHermesToolCalls(\n content: string,\n makeId: () => string,\n allowedToolNames?: ReadonlySet<string>,\n): HermesExtractResult {\n // R5 request-scoped gate: promote a block only when its name is a real tool in the current request\n // (exact, case-sensitive — peer-project payload.ts:190). `undefined` allowlist → recover-all (back-compat\n // for direct callers); an EMPTY set recovers nothing (a request with no tools has nothing legitimate\n // to recover). The name is already trimmed above, so the gate and the emitted call agree (EC-1).\n const isPromoted = (name: string): boolean =>\n name.length > 0 && (allowedToolNames === undefined || allowedToolNames.has(name));\n const toolCalls: LlmToolCallPart[] = [];\n const droppedNames: string[] = [];\n for (const block of content.matchAll(HERMES_BLOCK)) {\n const name = (block[1] ?? \"\").trim();\n if (!isPromoted(name)) {\n // A well-formed leaked block gated out by a defined allowlist — record it for observability.\n if (name.length > 0 && allowedToolNames !== undefined) droppedNames.push(name);\n continue;\n }\n toolCalls.push({\n type: \"tool_use\",\n id: makeId(),\n name,\n input: parseHermesParams(block[2] ?? \"\"),\n });\n }\n // EC-5: strip ONLY promoted blocks — a gated-out block (e.g. a `<function=example>` in a code fence\n // whose name is not a request tool) keeps its text visible instead of being silently deleted.\n const residualText =\n toolCalls.length === 0\n ? content\n : content\n .replace(HERMES_BLOCK, (full, rawName) =>\n isPromoted((rawName ?? \"\").trim()) ? \"\" : full,\n )\n .trim();\n return { toolCalls, residualText, droppedNames };\n}\n\n/** Parse the `<parameter=KEY>VALUE</parameter>` pairs inside a block's inner text into an input map.\n *\n * Value hygiene is DELEGATED to the public `sanitizeToolInput` primitive (`@theokit/sdk/sanitize`,\n * trim-only) so the internal recovery and the public sanitizer share ONE source of truth (DRY) — the\n * P0 bug (`\\n`-wrapped paths → `not_found` → stalled multi-read loops) was born from an ad-hoc,\n * un-shared trim. Keys are trimmed here (the regex already excludes whitespace from the key capture);\n * values stay strings (the doc-comment invariant), trimmed by the shared primitive. */\nfunction parseHermesParams(inner: string): Record<string, unknown> {\n const input: Record<string, unknown> = {};\n for (const param of inner.matchAll(HERMES_PARAM)) {\n const key = param[1];\n const value = param[2];\n if (key === undefined || value === undefined) continue;\n input[key.trim()] = value;\n }\n return sanitizeToolInput(input, { trim: true }).value;\n}\n\nconst STREAM_MARKER = \"<function=\";\nconst DEFAULT_STREAM_BUFFER_CAP = 8192;\n\nconst isStreamWs = (c: string | undefined): boolean =>\n c === \" \" || c === \"\\t\" || c === \"\\n\" || c === \"\\r\";\n\n/**\n * R7 stream-boundary suppression FSM. Classifies a suspicion buffer (accumulated streamed content)\n * as `\"possible\"` — it could still become a `<function=NAME>` tool call for a request tool, so the\n * caller HOLDS it (emits no text_delta) — or `\"impossible\"` — confirmed NOT a tool call, so the\n * caller FLUSHES it as visible text. The marker match is CASE-SENSITIVE, identical to `HERMES_BLOCK`\n * (no `/i`), so the FSM never holds a block `extractHermesToolCalls` would not recover (EC-1). An\n * empty allowlist promotes nothing (`\"impossible\"`); over `cap` while still tool-call-like fails open\n * to `\"impossible\"` (flush) so a never-closing marker cannot grow unbounded. Pure — never throws.\n * @internal\n */\nexport function streamToolCallBufferState(\n held: string,\n allowedToolNames: ReadonlySet<string>,\n cap: number = DEFAULT_STREAM_BUFFER_CAP,\n): \"possible\" | \"impossible\" {\n if (allowedToolNames.size === 0) return \"impossible\";\n const t = held.trimStart();\n if (t.length < STREAM_MARKER.length) {\n // Still building the marker itself (e.g. \"<fun\").\n return STREAM_MARKER.startsWith(t) ? \"possible\" : \"impossible\";\n }\n if (!t.startsWith(STREAM_MARKER)) return \"impossible\";\n const parsed = parseStreamMarkerName(t);\n if (parsed === \"building\") return \"possible\";\n if (parsed === \"invalid\") return \"impossible\";\n const nameOk = parsed.complete\n ? allowedToolNames.has(parsed.name)\n : someToolNameStartsWith(allowedToolNames, parsed.name);\n if (!nameOk) return \"impossible\";\n return held.length > cap ? \"impossible\" : \"possible\";\n}\n\n/** Read the (partial) tool name after a confirmed `<function=` marker (skipping the regex `\\s*`).\n * `\"building\"` = only the marker(+ws) so far; `\"invalid\"` = a `>`/other char with no name. */\nfunction parseStreamMarkerName(\n t: string,\n): { name: string; complete: boolean } | \"building\" | \"invalid\" {\n let cursor = STREAM_MARKER.length;\n while (cursor < t.length && isStreamWs(t[cursor])) cursor += 1;\n const nameStart = cursor;\n while (cursor < t.length && t[cursor] !== \">\" && !isStreamWs(t[cursor])) cursor += 1;\n const name = t.slice(nameStart, cursor);\n if (name.length === 0) return cursor >= t.length ? \"building\" : \"invalid\";\n return { name, complete: cursor < t.length && t[cursor] === \">\" };\n}\n\n/** True when any allowed tool name starts with `prefix` — the streaming partial-name probe (R7 D2). */\nfunction someToolNameStartsWith(allowedToolNames: ReadonlySet<string>, prefix: string): boolean {\n for (const name of allowedToolNames) {\n if (name.startsWith(prefix)) return true;\n }\n return false;\n}\n\n/**\n * R7 mixed-delta split: given a suspicion buffer that is NOT itself a possible tool call as a whole,\n * find the first `<` index whose suffix COULD still become a `<function=NAME>` tool call for a request\n * tool — so the caller flushes the definitely-prose prefix and holds only the suspicious suffix (e.g.\n * a `hello <function=read` delta flushes `hello ` and holds `<function=read`). Returns `-1` when no\n * suffix is suspicious (flush the whole buffer). Bounded: scans only `<` positions. @internal\n */\nexport function firstPossibleMarkerStart(\n held: string,\n allowedToolNames: ReadonlySet<string>,\n): number {\n for (let i = held.indexOf(\"<\"); i !== -1; i = held.indexOf(\"<\", i + 1)) {\n if (streamToolCallBufferState(held.slice(i), allowedToolNames) === \"possible\") return i;\n }\n return -1;\n}\n\n/**\n * R7 stateful stream-suppression buffer. Owns the held-content buffer for one stream: `push` feeds a\n * content delta and returns the text to emit now (or `undefined` to HOLD while it could still be a\n * `<function=NAME>` tool call for a request tool); `drain` finalizes at stream end. Extracted from the\n * OpenAI accumulator so the adapter stays thin (G8). @internal\n */\nexport class StreamSuppressionBuffer {\n #held = \"\";\n constructor(private readonly allowedToolNames: ReadonlySet<string>) {}\n\n /** Feed a content delta; returns the text to emit as a `text_delta` now, or `undefined` to hold. */\n push(content: string): string | undefined {\n this.#held += content;\n if (streamToolCallBufferState(this.#held, this.allowedToolNames) === \"possible\")\n return undefined;\n // Whole buffer is not a tool call, but a marker for a request tool may start mid-buffer (prose +\n // marker in one delta) — flush the prose prefix, hold the suspicious suffix.\n const holdStart = firstPossibleMarkerStart(this.#held, this.allowedToolNames);\n if (holdStart > 0) {\n const flush = this.#held.slice(0, holdStart);\n this.#held = this.#held.slice(holdStart);\n return flush;\n }\n const flush = this.#held;\n this.#held = \"\";\n return flush;\n }\n\n /** Drain the held buffer at stream end. `hasNativeCalls` mirrors `finish()`'s size-guard: when\n * native `tool_calls` exist, `finish()` won't strip the leaked block, so stream the held text WHOLE\n * (keeping `accumulatedText == finish.text`); otherwise strip the recoverable blocks. Idempotent. */\n drain(hasNativeCalls: boolean): string | undefined {\n if (this.#held.length === 0) return undefined;\n const held = this.#held;\n this.#held = \"\";\n if (hasNativeCalls) return held;\n const residual = extractHermesToolCalls(held, () => \"held\", this.allowedToolNames).residualText;\n return residual.length > 0 ? residual : undefined;\n }\n}\n","/**\n * Mapping from `LlmMessage` to OpenAI's message format.\n *\n * Extracted from `openai.ts` in M75 because the G8 gate (<= 400 LoC) caught it at 427 — PRE-EXISTING debt,\n * which stayed invisible while `knip` failed before the gate ran.\n *\n * The seam is not arbitrary: these five functions form ONE responsibility — translating our\n * message format into OpenAI's wire format — and none of them knows about transport, streaming or\n * request policy. The rest of `openai.ts` handles that.\n */\nimport { toStringToolResultContent } from \"./tool-result-content.js\";\nimport type { LlmMessage } from \"./types.js\";\n\nexport function toOpenAIMessages(message: LlmMessage): Array<Record<string, unknown>> {\n if (message.role === \"system\") return [systemMessage(message)];\n if (message.role === \"user\") return userOrToolMessages(message);\n return [assistantMessage(message)];\n}\n\nfunction systemMessage(message: LlmMessage): Record<string, unknown> {\n return { role: \"system\", content: joinTextParts(message) };\n}\n\nfunction joinTextParts(message: LlmMessage): string {\n return message.content\n .filter((part) => part.type === \"text\")\n .map((part) => (part as { text: string }).text)\n .join(\"\\n\");\n}\n\n/**\n * Translate a logical `user` turn. If the turn contains tool_result parts\n * they must be emitted as `role: \"tool\"` messages with matching\n * `tool_call_id` — OpenAI rejects tool_calls followed by a user message.\n * Plain text parts (and any other parts) collapse into a single user\n * message that follows the tool messages.\n */\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nfunction userOrToolMessages(message: LlmMessage): Array<Record<string, unknown>> {\n const out: Array<Record<string, unknown>> = [];\n for (const part of message.content) {\n if (part.type === \"tool_result\") {\n out.push({\n role: \"tool\",\n tool_call_id: part.toolUseId,\n // SE7 — this wire's tool role is string-only: text blocks flatten; an\n // image block fails fast (ConfigurationError).\n content: toStringToolResultContent(part.content, \"openai\"),\n });\n }\n }\n const userText = joinTextParts(message);\n // M35 — image parts turn the user message into OpenAI/OpenRouter's content-array form\n // (`[{type:\"text\"}, {type:\"image_url\", image_url:{url: data-URL}}]`); text-only stays a plain string.\n const imageParts = message.content.filter(\n (p): p is import(\"./types.js\").LlmImagePart => p.type === \"image\",\n );\n if (imageParts.length > 0) {\n const content: Array<Record<string, unknown>> = [];\n if (userText.length > 0) content.push({ type: \"text\", text: userText });\n for (const img of imageParts) {\n // OpenAI/OpenRouter `image_url` accepts BOTH a data URL (inline base64) and a real https URL.\n const url =\n img.source.type === \"base64\"\n ? `data:${img.source.media_type};base64,${img.source.data}`\n : img.source.url;\n content.push({ type: \"image_url\", image_url: { url } });\n }\n out.push({ role: \"user\", content });\n } else if (userText.length > 0) {\n out.push({ role: \"user\", content: userText });\n }\n return out;\n}\n\nfunction assistantMessage(message: LlmMessage): Record<string, unknown> {\n const text = joinTextParts(message);\n const toolCalls = message.content\n .filter((part) => part.type === \"tool_use\")\n .map((part) => {\n const tc = part as { id: string; name: string; input: Record<string, unknown> };\n return {\n id: tc.id,\n type: \"function\",\n function: { name: tc.name, arguments: JSON.stringify(tc.input) },\n };\n });\n const result: Record<string, unknown> = { role: \"assistant\", content: text };\n if (toolCalls.length > 0) result.tool_calls = toolCalls;\n return result;\n}\n","import { NetworkError } from \"../../errors.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { mapOllamaHttpError, mapOllamaTransportError } from \"../error-mappers/ollama.js\";\nimport { mapOpenAICompatibleError } from \"../error-mappers/openai-compatible.js\";\nimport { readErrorResponseBody } from \"../http.js\";\nimport {\n collapseSystemText,\n makeLlmFinish,\n mapOpenAIFinish,\n parseToolArguments,\n} from \"./finish.js\";\nimport { extractHermesToolCalls, StreamSuppressionBuffer } from \"./hermes-tool-extract.js\";\nimport { toOpenAIMessages } from \"./openai-messages.js\";\nimport { parseSseStream } from \"./sse.js\";\nimport { wrapTransportError } from \"./transport-error.js\";\nimport type {\n LlmClient,\n LlmEvent,\n LlmFinish,\n LlmRequest,\n LlmStopReason,\n LlmToolCallPart,\n} from \"./types.js\";\n\n/**\n * Real OpenAI Chat Completions client. Streams `/v1/chat/completions` and\n * translates delta chunks into our provider-agnostic `LlmEvent`s.\n *\n * Uses native `fetch` only — no `openai` SDK dependency.\n *\n * @internal\n */\n\n/**\n * M45 — derive the chat-completions path from the baseUrl: a path already carrying a version segment\n * (`/v1`, `/v1beta`, …) gets `/chat/completions`; host-only (or unparseable) baseUrls keep the legacy\n * `/v1/chat/completions`. Unparseable NEVER throws (H1) — the transport surfaces a typed error at fetch time.\n */\nfunction deriveChatPath(baseUrl: string): string {\n try {\n return /\\/v\\d+[a-z]*(\\/|$)/.test(new URL(baseUrl).pathname)\n ? \"/chat/completions\"\n : \"/v1/chat/completions\";\n } catch {\n return \"/v1/chat/completions\";\n }\n}\n\nexport interface OpenAIClientOptions {\n apiKey: string;\n baseUrl?: string;\n organization?: string;\n fetch?: typeof fetch;\n /**\n * Provider name for error mapping dispatch (T1.1, ADR D185). When set\n * to `\"ollama\"`, transport and HTTP errors go through `mapOllamaTransportError`\n * / `mapOllamaHttpError` for actionable messages before falling back to\n * the generic OpenAI-compatible mapper. Default `\"openai\"`.\n */\n providerName?: string;\n /**\n * Opt-in leaked-dialect safe-parse (theokit#58 follow-up). When `true`, a finish that carries\n * ZERO native `tool_calls` has its assistant text scanned for the Hermes `<function=…></tool_call>`\n * dialect; any recovered calls are surfaced as real `tool_calls` so the loop executes them.\n * Default `false` — a code assistant can legitimately print a literal `<function=` in code text.\n */\n extractToolCallsFromContent?: boolean;\n /**\n * M41 — extra HTTP headers merged into the request (the profile's static `extraHeaders` + a provider\n * `transform.headers(ctx)`). Spread AFTER the base `authorization`/`content-type`, so a provider that owns\n * its auth CAN override them by design (document this on `ProviderTransform.headers`).\n */\n extraHeaders?: Record<string, string>;\n /** M45 — explicit chat-completions path (from `ProviderProfile.chatCompletionsPath`). */\n chatCompletionsPath?: string;\n}\n\ninterface OpenAIDeltaChunk {\n choices?: Array<{\n index: number;\n delta?: {\n content?: string;\n /** OpenRouter unified reasoning delta (issue #47) — streamed separately from `content`. */\n reasoning?: string;\n /**\n * Sibling reasoning field used by some OpenAI-compatible providers (DeepSeek's direct API,\n * many vLLM / LMStudio reasoning parsers). Treated identically to `reasoning` (issue #47,\n * F-domain-2). OpenRouter normalizes to `reasoning`; this is the fallback for non-OpenRouter\n * compat endpoints reached via `baseUrl` override.\n */\n reasoning_content?: string;\n tool_calls?: Array<{\n index: number;\n id?: string;\n function?: { name?: string; arguments?: string };\n }>;\n };\n finish_reason?: string | null;\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n /**\n * OpenAI + OpenRouter extended usage (D376). Anthropic prompt caching\n * surfaces as `prompt_tokens_details.cached_tokens` on OpenRouter passthrough;\n * native OpenAI exposes the same field on `chatcmpl-*` responses.\n */\n prompt_tokens_details?: { cached_tokens?: number };\n completion_tokens_details?: { reasoning_tokens?: number };\n /** Anthropic-on-OpenRouter passes cache_creation_tokens top-level (a peer#10266). */\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n };\n /**\n * In-stream provider error. OpenRouter (and some OpenAI-compatible proxies)\n * report auth / quota / rate-limit failures as an HTTP 200 SSE body carrying\n * `data: {\"error\":{\"message\":\"...\",\"code\":401}}` instead of a non-2xx status.\n * Without surfacing this, the round finishes empty and the failure is silent\n * (usetheodev/theocode#31).\n */\n error?: { message?: string; code?: number | string; type?: string };\n}\n\nexport class OpenAIClient implements LlmClient {\n readonly name = \"openai\";\n private readonly baseUrl: string;\n private readonly chatPath: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: OpenAIClientOptions) {\n // M45 review M3 — strip trailing slashes so `…/v1/` (the python-openai-popularized form) joins cleanly.\n this.baseUrl = (options.baseUrl ?? \"https://api.openai.com\").replace(/\\/+$/, \"\");\n // M45 — URL-join rule (kills the /v1/v1 doubling): explicit override > version-segment detection >\n // legacy `/v1/chat/completions`. A baseUrl already carrying a version path segment (…/openai/v1,\n // …/v1beta/openai) gets only `/chat/completions`; host-only baseUrls are byte-identical to before.\n // M45 review H1 — the parse NEVER throws from the constructor: a malformed baseUrl (scheme-less host,\n // empty env var) degrades to the LEGACY path (byte-identical to pre-M45 string concat) and fails, typed,\n // at the first fetch — never poisoning the whole provider chain at construction time.\n this.chatPath = options.chatCompletionsPath ?? deriveChatPath(this.baseUrl);\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n /**\n * Whether this client recovers leaked Hermes tool-call dialect from assistant\n * text (theokit#58 follow-up). Observability for the route→client wiring of\n * `extractToolCallsFromContent`. @internal\n */\n get recoversLeakedToolCalls(): boolean {\n return this.options.extractToolCallsFromContent ?? false;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: HTTP+SSE handshake + accumulator is intentionally one block\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.options.apiKey}`,\n };\n if (this.options.organization !== undefined) {\n headers[\"openai-organization\"] = this.options.organization;\n }\n // M41 — merge extra/dynamic headers (spread last: a provider that owns its auth may override base headers).\n if (this.options.extraHeaders !== undefined) Object.assign(headers, this.options.extraHeaders);\n const providerId = this.options.providerName ?? this.name;\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.baseUrl}${this.chatPath}`, {\n method: \"POST\",\n signal,\n headers,\n body: JSON.stringify(buildOpenAIBody(request, providerId)),\n });\n } catch (fetchErr) {\n // T1.1: Ollama-specific transport error mapping (ECONNREFUSED / ENOTFOUND).\n const mapped = mapOllamaTransportError({\n providerId,\n cause: fetchErr,\n endpoint: \"/v1/chat/completions\",\n });\n if (mapped !== undefined) throw mapped;\n // M93 — before this, a raw `throw fetchErr` left here for every provider other than Ollama, and\n // a foreign error is NON-transient by contract (`errors.ts:429`): retry stayed off\n // in the most classic case.\n throw wrapTransportError(fetchErr, { providerId, endpoint: \"/v1/chat/completions\" });\n }\n if (!response.ok) {\n const body = await readErrorResponseBody(response);\n // T1.1: try Ollama-specific HTTP mapper first; falls through to generic.\n const ollamaMapped = mapOllamaHttpError({\n providerId,\n status: response.status,\n body,\n headers: response.headers,\n endpoint: \"/v1/chat/completions\",\n });\n if (ollamaMapped !== undefined) throw ollamaMapped;\n // Use the openai-compatible mapper. For OpenAI proper the providerId\n // is \"openai\"; OpenRouter is handled in its own client subclass (see\n // OpenRouterClient if/when added). Providers tagged differently via\n // wrapper clients can pass their own providerId by overriding.\n throw mapOpenAICompatibleError({\n providerId,\n status: response.status,\n body,\n headers: response.headers,\n endpoint: \"/v1/chat/completions\",\n });\n }\n\n const accumulator = new OpenAIStreamAccumulator(\n this.options.extractToolCallsFromContent ?? false,\n providerId,\n // R5: request-scoped allowlist — leaked recovery only promotes a block whose name is a tool the\n // model was actually given. Empty set (no tools) recovers nothing.\n new Set(request.tools?.map((tool) => tool.name) ?? []),\n );\n let sawDone = false;\n for await (const record of parseSseStream(response.body, signal)) {\n if (record.data === \"[DONE]\") {\n sawDone = true;\n break;\n }\n let chunk: OpenAIDeltaChunk;\n try {\n chunk = JSON.parse(record.data) as OpenAIDeltaChunk;\n } catch {\n continue;\n }\n // Fail-loud on an in-stream provider error (OpenRouter HTTP-200 error body).\n // The accumulator only reads `choices`, so an error-only chunk would finish\n // the round empty and swallow the failure (theocode#31). Map it to the same\n // typed error a non-2xx HTTP status would have produced.\n if (chunk.error !== undefined && chunk.error !== null) {\n const status = typeof chunk.error.code === \"number\" ? chunk.error.code : 502;\n throw mapOpenAICompatibleError({\n providerId,\n status,\n body: chunk,\n headers: response.headers,\n endpoint: \"/v1/chat/completions\",\n });\n }\n const events = accumulator.consume(chunk);\n for (const event of events) yield event;\n }\n // M2 #61 — a stream ending with NEITHER `[DONE]` NOR a `finish_reason` was\n // truncated (dropped connection / proxy hiccup); throw a typed error rather\n // than commit the partial turn as a clean `end_turn` (codex prior art).\n if (!sawDone && !accumulator.finishReasonSeen) {\n throw new NetworkError(\"SSE stream truncated (no finish_reason / [DONE])\", {\n code: \"stream_truncated\",\n });\n }\n // R7: drain any held buffer so leaked-dialect text is never silently dropped.\n const drainEvent = accumulator.finalizeHeldText();\n if (drainEvent !== undefined) yield drainEvent;\n return accumulator.finish();\n }\n}\n\nclass OpenAIStreamAccumulator {\n private text = \"\";\n private stopReason: LlmStopReason = \"end_turn\";\n private inputTokens?: number;\n private outputTokens?: number;\n private cacheReadTokens?: number;\n private cacheWriteTokens?: number;\n private reasoningTokens?: number;\n private readonly toolCalls = new Map<number, { id: string; name: string; args: string }>();\n /** R7: present only when recovery is enabled AND the request declares tools — holds suspected\n * leaked-dialect content back from the `text_delta` stream. `undefined` ⇒ stream immediately. */\n private readonly suppress?: StreamSuppressionBuffer;\n\n /**\n * @param extractFromContent opt-in leaked-dialect safe-parse (theokit#58). Default false.\n * @param providerName provider id, used only to label the recovery log line.\n * @param allowedToolNames R5 request-scoped allowlist — built from `request.tools` at `stream()`;\n * leaked recovery in `finish()` only promotes a block whose name is in this set. `undefined`\n * (direct construction) recovers all (back-compat); an empty set recovers nothing.\n */\n constructor(\n private readonly extractFromContent = false,\n private readonly providerName = \"openai\",\n private readonly allowedToolNames?: ReadonlySet<string>,\n ) {\n this.suppress =\n extractFromContent && allowedToolNames !== undefined && allowedToolNames.size > 0\n ? new StreamSuppressionBuffer(allowedToolNames)\n : undefined;\n }\n\n consume(chunk: OpenAIDeltaChunk): LlmEvent[] {\n const events: LlmEvent[] = [];\n this.applyUsage(chunk.usage);\n for (const choice of chunk.choices ?? []) {\n events.push(...this.applyChoice(choice));\n }\n return events;\n }\n\n private applyChoice(choice: NonNullable<OpenAIDeltaChunk[\"choices\"]>[number]): LlmEvent[] {\n const events: LlmEvent[] = [];\n // issue #47: reasoning delta precedes the visible text in arrival order. OpenRouter streams it\n // as `reasoning`; some compat providers use `reasoning_content` (F-domain-2) — accept either.\n const reasoningEvent = this.applyReasoningDelta(\n choice.delta?.reasoning ?? choice.delta?.reasoning_content,\n );\n if (reasoningEvent !== undefined) events.push(reasoningEvent);\n const textEvent = this.applyContentDelta(choice.delta?.content);\n if (textEvent !== undefined) events.push(textEvent);\n this.mergeToolCallDeltas(choice.delta?.tool_calls);\n this.applyFinishReason(choice.finish_reason);\n // R7: at the terminal chunk, flush the held buffer's residual (held minus recoverable blocks)\n // AFTER this chunk's content was appended above — so `accumulatedText == finish.text`.\n if (choice.finish_reason !== undefined && choice.finish_reason !== null) {\n const flushEvent = this.finalizeHeldText();\n if (flushEvent !== undefined) events.push(flushEvent);\n }\n return events;\n }\n\n private applyReasoningDelta(reasoning: string | undefined): LlmEvent | undefined {\n // issue #47: reasoning is NOT accumulated into `this.text` (the visible answer) — it is a\n // separate channel surfaced as `reasoning_delta` (→ thinking events at the loop layer).\n if (typeof reasoning !== \"string\" || reasoning.length === 0) return undefined;\n return { type: \"reasoning_delta\", text: reasoning };\n }\n\n private applyUsage(usage: OpenAIDeltaChunk[\"usage\"]): void {\n if (usage?.prompt_tokens !== undefined) this.inputTokens = usage.prompt_tokens;\n if (usage?.completion_tokens !== undefined) this.outputTokens = usage.completion_tokens;\n // D376: cache + reasoning buckets via OpenRouter passthrough + OpenAI native.\n const cachedDetail = usage?.prompt_tokens_details?.cached_tokens;\n if (cachedDetail !== undefined) this.cacheReadTokens = cachedDetail;\n const reasoningDetail = usage?.completion_tokens_details?.reasoning_tokens;\n if (reasoningDetail !== undefined) this.reasoningTokens = reasoningDetail;\n // a peer#10266 top-level fallback for Anthropic-on-OpenRouter.\n if (usage?.cache_read_input_tokens !== undefined) {\n this.cacheReadTokens = usage.cache_read_input_tokens;\n }\n if (usage?.cache_creation_input_tokens !== undefined) {\n this.cacheWriteTokens = usage.cache_creation_input_tokens;\n }\n }\n\n private applyContentDelta(content: string | undefined): LlmEvent | undefined {\n if (typeof content !== \"string\" || content.length === 0) return undefined;\n this.text += content;\n // R7: when suppression is active, HOLD content that could still be a leaked tool call (the buffer\n // returns the text to emit now, or `undefined` to hold). Otherwise stream immediately.\n if (this.suppress === undefined) return { type: \"text_delta\", text: content };\n const emit = this.suppress.push(content);\n return emit !== undefined ? { type: \"text_delta\", text: emit } : undefined;\n }\n\n /** R7 held-buffer finalizer, called at the `finish_reason` chunk (in `applyChoice`) AND after the\n * SSE loop in `stream()` — so a stream that omits a `finish_reason` terminal never silently drops\n * held text. `toolCalls.size > 0` (native calls present) makes `finish()` skip recovery, so the\n * buffer streams the held text whole. Idempotent once drained. */\n finalizeHeldText(): LlmEvent | undefined {\n const emit = this.suppress?.drain(this.toolCalls.size > 0);\n return emit !== undefined ? { type: \"text_delta\", text: emit } : undefined;\n }\n\n private mergeToolCallDeltas(\n deltas: NonNullable<NonNullable<OpenAIDeltaChunk[\"choices\"]>[number][\"delta\"]>[\"tool_calls\"],\n ): void {\n for (const call of deltas ?? []) {\n const existing = this.toolCalls.get(call.index) ?? { id: \"\", name: \"\", args: \"\" };\n if (call.id !== undefined) existing.id = call.id;\n if (call.function?.name !== undefined) existing.name = call.function.name;\n if (call.function?.arguments !== undefined) existing.args += call.function.arguments;\n this.toolCalls.set(call.index, existing);\n }\n }\n\n /** M2 #61 — true once any chunk carried a non-null `finish_reason` (else a\n * stream ending without `[DONE]` is a truncation, not a clean end). */\n private sawFinishReason = false;\n get finishReasonSeen(): boolean {\n return this.sawFinishReason;\n }\n\n private applyFinishReason(reason: string | null | undefined): void {\n if (reason === undefined || reason === null) return;\n this.sawFinishReason = true;\n this.stopReason = mapOpenAIFinish(reason);\n }\n\n finish(): LlmFinish {\n const toolCalls: LlmToolCallPart[] = [];\n for (const call of this.toolCalls.values()) {\n const input = parseToolArguments(call.args);\n toolCalls.push({ type: \"tool_use\", id: call.id, name: call.name, input });\n }\n let text = this.text;\n let stopReason = this.stopReason;\n // theokit#58 follow-up: leaked-dialect safe-parse. Opt-in, and ONLY when the provider sent no\n // native tool_calls (the size-guard prevents double-counting a real call). Recovered calls flip\n // the stopReason to \"tool_use\" so the agent loop dispatches them; the consumed dialect is stripped\n // from the visible text.\n if (this.extractFromContent && toolCalls.length === 0) {\n const recovered = extractHermesToolCalls(\n this.text,\n () => `hermes-${globalThis.crypto.randomUUID()}`,\n this.allowedToolNames,\n );\n if (recovered.toolCalls.length > 0) {\n toolCalls.push(...recovered.toolCalls);\n text = recovered.residualText;\n stopReason = \"tool_use\";\n // Observability (wiring triad pillar c): recovery is a model-misbehavior workaround, so make\n // it visible — a route that leaks often should be diagnosable without a debugger.\n diag(\n `[theokit-sdk] recovered ${recovered.toolCalls.length} leaked tool call(s) from assistant content ` +\n `(provider=\"${this.providerName}\", names=${recovered.toolCalls.map((c) => c.name).join(\",\")})\\n`,\n );\n }\n // R5 observability: a leaked block DROPPED by the request-scoped allowlist is the guard firing —\n // surface it too, so a model emitting `<function=NAME>` for an undeclared tool is diagnosable.\n if (recovered.droppedNames.length > 0) {\n diag(\n `[theokit-sdk] dropped ${recovered.droppedNames.length} leaked block(s) whose name is not a ` +\n `tool in the request (provider=\"${this.providerName}\", names=${recovered.droppedNames.join(\",\")})\\n`,\n );\n }\n }\n return makeLlmFinish({\n stopReason,\n text,\n toolCalls,\n inputTokens: this.inputTokens,\n outputTokens: this.outputTokens,\n cacheReadTokens: this.cacheReadTokens,\n cacheWriteTokens: this.cacheWriteTokens,\n reasoningTokens: this.reasoningTokens,\n });\n }\n}\n\n/**\n * issue #47 / F-domain-1: encode the reasoning request in the shape the target provider accepts.\n * Native OpenAI Chat Completions rejects unknown body params and expects the top-level\n * `reasoning_effort` string; OpenRouter (and OpenAI-compatible passthroughs) use the unified\n * `reasoning: { effort }` object. `stream()` always passes the resolved provider id, so a native\n * OpenAI request never 400s on the OpenRouter shape. When `providerName` is unspecified (test seam),\n * the unified object is used — the broader-compatibility default.\n */\nfunction applyReasoningRequest(\n body: Record<string, unknown>,\n effort: string,\n providerName: string | undefined,\n): void {\n if (providerName === \"openai\") {\n body.reasoning_effort = effort;\n return;\n }\n body.reasoning = { effort };\n}\n\n/**\n * Encode the `tools` array + per-request `tool_choice` gate (step-cap force-close). `tool_choice`\n * is meaningful only alongside `tools`, so both are emitted together (or neither). `\"none\"` advertises\n * the tools but forbids calling them — forcing a text answer from an agent whose tools are registered.\n */\nfunction applyToolsRequest(body: Record<string, unknown>, request: LlmRequest): void {\n if (request.tools === undefined || request.tools.length === 0) return;\n body.tools = request.tools.map((tool) => ({\n type: \"function\",\n function: { name: tool.name, description: tool.description, parameters: tool.inputSchema },\n }));\n if (request.toolChoice !== undefined) body.tool_choice = request.toolChoice;\n}\n\nfunction buildOpenAIBody(request: LlmRequest, providerName?: string): Record<string, unknown> {\n const messages: Array<Record<string, unknown>> = [];\n const systemText = openAISystemText(request.system);\n if (systemText.length > 0) {\n messages.push({ role: \"system\", content: systemText });\n }\n for (const message of request.messages) {\n for (const out of toOpenAIMessages(message)) messages.push(out);\n }\n const body: Record<string, unknown> = {\n model: request.model,\n stream: true,\n // D376: opt-in to OpenAI's final-chunk usage record (no-op for providers\n // that don't honor it; OpenRouter / OpenAI both respect it).\n stream_options: { include_usage: true },\n messages,\n };\n if (request.maxTokens !== undefined) body.max_tokens = request.maxTokens;\n if (request.temperature !== undefined) body.temperature = request.temperature;\n // issue #47: reasoning request — only when an effort was requested. Provider-specific wire shape.\n if (request.reasoning?.effort !== undefined)\n applyReasoningRequest(body, request.reasoning.effort, providerName);\n applyToolsRequest(body, request);\n const responseFormat = encodeOpenAIResponseFormat(request.responseFormat);\n if (responseFormat !== undefined) body.response_format = responseFormat;\n return body;\n}\n\n/**\n * T3.5 follow-up — collapse `LlmRequest.system` to the OpenAI wire shape\n * (single string).\n *\n * @internal\n */\nconst openAISystemText = collapseSystemText;\n\n/**\n * T3.6 — encode `LlmResponseFormat` into the OpenAI wire shape. The\n * structured-outputs path defaults `strict` to `true` (provider guarantees\n * the response matches the schema).\n *\n * @internal\n */\nfunction encodeOpenAIResponseFormat(\n rf: LlmRequest[\"responseFormat\"],\n): Record<string, unknown> | undefined {\n if (rf === undefined) return undefined;\n if (rf.type === \"json_object\") return { type: \"json_object\" };\n return {\n type: \"json_schema\",\n json_schema: {\n name: rf.jsonSchema.name,\n schema: rf.jsonSchema.schema,\n strict: rf.jsonSchema.strict ?? true,\n },\n };\n}\n\n/**\n * T3.6 — public test seam for `buildOpenAIBody`. The implementation is\n * file-local; the seam lets unit tests verify the wire shape without\n * exercising the streaming path.\n *\n * @internal\n */\nexport const __testing__buildOpenAIBody = buildOpenAIBody;\n/** issue #47 test seam — exercise reasoning-delta parsing without a live stream. */\nexport const __testing__OpenAIStreamAccumulator = OpenAIStreamAccumulator;\n","/**\n * Consecutive-failure circuit breaker — a cross-cutting resilience primitive.\n *\n * Used by Active Memory recall (timeout-driven) and the LLM credential pool\n * (429/terminal-failure-driven). Domain-neutral: it counts consecutive\n * failure events per key and trips after N, staying open for `cooldownMs`.\n *\n * Mirrors peer-project's `circuitBreakerMaxTimeouts` + `circuitBreakerCooldownMs`\n * config: after N consecutive timeouts the breaker trips and `shouldSkip`\n * returns `true` until `cooldownMs` has elapsed. A successful recall resets\n * the counter immediately.\n *\n * Per-key isolation so two agents in the same process don't share a counter.\n *\n * @internal\n */\n\nexport interface CircuitBreakerOptions {\n maxTimeouts?: number;\n cooldownMs?: number;\n /** Injectable clock for tests. */\n now?: () => number;\n}\n\ninterface KeyState {\n consecutiveTimeouts: number;\n cooldownUntilMs: number;\n}\n\nconst DEFAULT_MAX_TIMEOUTS = 3;\nconst DEFAULT_COOLDOWN_MS = 60_000;\n\nexport class CircuitBreaker {\n private readonly states = new Map<string, KeyState>();\n\n constructor(private readonly opts: CircuitBreakerOptions = {}) {}\n\n /** @returns true when the breaker is open and the call should be skipped. */\n shouldSkip(key: string): boolean {\n const state = this.states.get(key);\n if (state === undefined) return false;\n if (state.cooldownUntilMs === 0) return false;\n if (this.now() < state.cooldownUntilMs) return true;\n // Cooldown elapsed — close the breaker.\n state.cooldownUntilMs = 0;\n state.consecutiveTimeouts = 0;\n return false;\n }\n\n recordSuccess(key: string): void {\n const state = this.states.get(key);\n if (state === undefined) return;\n state.consecutiveTimeouts = 0;\n state.cooldownUntilMs = 0;\n }\n\n recordTimeout(key: string): void {\n const state = this.states.get(key) ?? { consecutiveTimeouts: 0, cooldownUntilMs: 0 };\n state.consecutiveTimeouts += 1;\n if (state.consecutiveTimeouts >= (this.opts.maxTimeouts ?? DEFAULT_MAX_TIMEOUTS)) {\n state.cooldownUntilMs = this.now() + (this.opts.cooldownMs ?? DEFAULT_COOLDOWN_MS);\n }\n this.states.set(key, state);\n }\n\n /** @internal — tests inspect counter state. */\n inspect(key: string): Readonly<KeyState> {\n return this.states.get(key) ?? { consecutiveTimeouts: 0, cooldownUntilMs: 0 };\n }\n\n private now(): number {\n return this.opts.now?.() ?? Date.now();\n }\n}\n","/**\n * Shared streaming helpers for `LlmClient` wrappers\n * (`FallbackLlmClient`, `PoolAwareLlmClient`).\n *\n * `tryFirstEvent` probes the first chunk of a stream to decide\n * whether the handshake succeeded. If it raises an\n * `AuthenticationError`/`RateLimitError`/`NetworkError`, the wrapper\n * captures the typed error for routing (rotate vs fallback) WITHOUT\n * starting the actual yield. Once the first event lands, the stream\n * is committed and partial-output cannot be reverted.\n *\n * `relay` yields the prefetched first chunk and then forwards the\n * remaining generator output verbatim.\n *\n * @internal\n */\n\nimport { AuthenticationError, NetworkError, RateLimitError } from \"../../errors.js\";\nimport { diag } from \"../diagnostics.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\n\n/**\n * Outcome of probing a client's first stream event.\n *\n * @internal\n */\nexport type StreamAttempt =\n | {\n kind: \"ok\";\n generator: AsyncGenerator<LlmEvent, LlmFinish, void>;\n firstResult: IteratorResult<LlmEvent, LlmFinish>;\n }\n | { kind: \"handshake_error\"; error: RateLimitError | AuthenticationError | NetworkError };\n\n/**\n * Try to obtain the FIRST event from `client.stream(...)`. Typed\n * provider failures surface as `kind: \"handshake_error\"`; everything\n * else propagates upward unchanged.\n *\n * Optionally writes a `[theokit-sdk] provider X failed (CODE): falling back`\n * line to stderr when `logFallback` is true — used by `FallbackLlmClient`.\n *\n * @internal\n */\nexport async function tryFirstEvent(\n client: LlmClient,\n request: LlmRequest,\n signal: AbortSignal,\n logFallback = false,\n): Promise<StreamAttempt> {\n const generator = client.stream(request, signal);\n try {\n const firstResult = await generator.next();\n return { kind: \"ok\", generator, firstResult };\n } catch (cause) {\n if (\n cause instanceof NetworkError ||\n cause instanceof RateLimitError ||\n cause instanceof AuthenticationError\n ) {\n if (logFallback) {\n const errCode = cause.metadata?.code ?? cause.code ?? \"unknown\";\n diag(`[theokit-sdk] provider ${client.name} failed (${errCode}): falling back\\n`);\n }\n return { kind: \"handshake_error\", error: cause };\n }\n throw cause;\n }\n}\n\n/**\n * Yield the prefetched first event, then forward the rest of the\n * generator. Identical to a normal `yield*` but with the lookahead\n * already in hand from `tryFirstEvent`.\n *\n * @internal\n */\nexport async function* relayStream(\n generator: AsyncGenerator<LlmEvent, LlmFinish, void>,\n firstResult: IteratorResult<LlmEvent, LlmFinish>,\n): AsyncGenerator<LlmEvent, LlmFinish, void> {\n if (firstResult.done === true) return firstResult.value;\n yield firstResult.value;\n while (true) {\n const next = await generator.next();\n if (next.done === true) return next.value;\n yield next.value;\n }\n}\n","/**\n * `LlmClient` wrapper that pools multiple API keys for the same\n * provider and rotates on HTTP 429/402/401 (ADRs D123-D133).\n *\n * Composition wrapper (D127) — wraps a builder that produces a real\n * `LlmClient` for a given API key. The wrapper picks a key via the\n * pool, instantiates the real client, attempts the stream, and on a\n * pre-stream error decides retry-vs-rotate per the decision matrix.\n *\n * Once `yield*` starts (first event received), rotation is impossible —\n * partial output would corrupt the stream. Same contract as\n * `FallbackLlmClient` (D2).\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n CredentialPoolExhaustedError,\n NetworkError,\n RateLimitError,\n} from \"../../errors.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { CircuitBreaker } from \"../resilience/circuit-breaker.js\";\nimport type { CredentialPool } from \"./credential-pool.js\";\nimport { computeBackoffMs, sleepWithAbort } from \"./retry.js\";\nimport { relayStream, tryFirstEvent } from \"./stream-relay.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\n\n/**\n * M2 #60 — optional resilience knobs. `breaker` guards the provider with a\n * consecutive-failure circuit breaker; `backoffBaseMs`/`rng` tune the\n * full-jitter sleep inserted before a same-key 429 retry (tests inject a\n * deterministic `rng` + a small base). All optional — omit for defaults.\n *\n * @internal\n */\nexport interface PoolResilienceOptions {\n breaker?: CircuitBreaker;\n backoffBaseMs?: number;\n rng?: () => number;\n /**\n * SE2 — invoked right before a 429 same-key retry backs off, so the runtime can\n * surface a `rate_limit` RunEvent. `attempt` is 1-based; `retryAfterMs` is the\n * backoff about to be waited. Best-effort observer — must not throw.\n */\n onRateLimit?: (info: { attempt: number; retryAfterMs?: number }) => void;\n}\n\n/** Decision returned by `classifyAndDecide`. */\ntype Decision = \"retry\" | \"rotate\" | \"propagate\";\n\n/**\n * Pool-aware `LlmClient`. Constructs real clients on demand via\n * `buildClient(apiKey)` — kept lazy so the pool can pick AT request\n * time (not at construction) and rotation produces a fresh client\n * each iteration.\n *\n * @internal\n */\nexport class PoolAwareLlmClient implements LlmClient {\n readonly name: string;\n\n constructor(\n private readonly pool: CredentialPool,\n private readonly buildClient: (apiKey: string) => LlmClient,\n /**\n * T3.9 — Optional override for the upper bound on how long\n * `stream()` waits for a cooldown to expire before throwing\n * `CredentialPoolExhaustedError`. Defaults to 30 s. The actual\n * wait inside `pool.waitForAvailable` is jittered (AWS Brooker\n * 2015 full-jitter), so concurrent callers stagger their\n * re-probe of the pool — preventing reconnect storms.\n *\n * Set to `0` to opt out (legacy pre-T3.9 behavior — throw on\n * first `select()`-returns-null).\n *\n * @internal\n */\n private readonly waitForAvailableMs: number = 30_000,\n resilience: PoolResilienceOptions = {},\n ) {\n this.name = `pool-aware:${pool.provider}`;\n this.breaker = resilience.breaker ?? new CircuitBreaker();\n this.backoffBaseMs = resilience.backoffBaseMs;\n this.rng = resilience.rng;\n this.onRateLimit = resilience.onRateLimit;\n }\n\n private readonly onRateLimit?: (info: { attempt: number; retryAfterMs?: number }) => void;\n\n /** M2 #60 — provider-level circuit breaker (consecutive-failure). */\n private readonly breaker: CircuitBreaker;\n private readonly backoffBaseMs: number | undefined;\n private readonly rng: (() => number) | undefined;\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: stream() must serialize pool-select → build client → first-event probe → classify → retry/rotate/propagate. Extracting helpers fragments the linear narrative; the comments above each branch keep it readable.\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n // M2 #60 — fail fast while the provider circuit is open, instead of\n // re-running the whole select→retry→rotate dance against a down provider.\n if (this.breaker.shouldSkip(this.pool.provider)) {\n throw new NetworkError(`${this.pool.provider} circuit open — failing fast`, {\n code: \"circuit_open\",\n });\n }\n let hasRetried429 = false;\n while (true) {\n if (signal.aborted) throw abortError(signal);\n\n let entry = await this.pool.select();\n if (entry === null) {\n // T3.9 — Reconnect storm prevention. Instead of throwing\n // immediately, wait (with jitter) for the earliest cooldown to\n // expire. Concurrent callers each pick a random delay within\n // the window to the earliest reset, so they wake at staggered\n // times and do not all re-hammer the upstream at the same\n // instant. `waitForAvailableMs === 0` opts out for legacy\n // callers and for unit tests that prefer the pre-T3.9\n // throw-fast contract.\n if (this.waitForAvailableMs > 0) {\n const available = await this.pool.waitForAvailable(signal, {\n maxWaitMs: this.waitForAvailableMs,\n });\n if (available) {\n entry = await this.pool.select();\n }\n }\n if (entry === null) {\n // M2 #60 — a whole-attempt terminal failure trips the breaker.\n this.breaker.recordTimeout(this.pool.provider);\n throw new CredentialPoolExhaustedError(\n `All ${this.pool.provider} credentials exhausted; next retry available at ${\n this.nextRetryHint() ?? \"unknown\"\n }`,\n { provider: this.pool.provider, nextRetryAt: this.nextRetryHint() },\n );\n }\n }\n\n // EC-D: a failure inside buildClient (e.g., invalid baseUrl) is\n // a transport-config bug, NOT a credential failure. Propagate\n // without marking the entry exhausted.\n const realClient: LlmClient = this.buildClient(entry.accessToken);\n\n const attempt = await tryFirstEvent(realClient, request, signal);\n if (attempt.kind === \"ok\") {\n // Stream started — rotation is no longer possible. A healthy start\n // closes the circuit breaker (M2 #60).\n this.breaker.recordSuccess(this.pool.provider);\n return yield* relayStream(attempt.generator, attempt.firstResult);\n }\n\n const decision = classifyAndDecide(attempt.error, hasRetried429);\n if (decision === \"retry\") {\n // D126: first 429 retries the same key. Don't mark exhausted yet.\n // M2 #60 — back off with full jitter before re-hitting the SAME key,\n // so a shared-quota thundering herd no longer burns the retry in <1ms\n // (AWS Brooker 2015). We deliberately do NOT sleep the provider's\n // `Retry-After` here: for a multi-key pool the right move on a 429 is to\n // fail this brief retry and ROTATE to a fresh key immediately (waiting\n // would defeat the pool). `Retry-After` IS honored at the pool-selection\n // level — the rotate path below sets the key's `resetAtMs` cooldown, so\n // subsequent selection skips a rate-limited key until its window passes\n // (a single-key pool then fails fast with CredentialPoolExhaustedError).\n const backoffMs = computeBackoffMs({\n attempt: 0,\n ...(this.backoffBaseMs !== undefined ? { baseMs: this.backoffBaseMs } : {}),\n ...(this.rng !== undefined ? { rng: this.rng } : {}),\n });\n // SE2 — surface a `rate_limit` RunEvent for the retry that is about to back off.\n this.onRateLimit?.({ attempt: 1, retryAfterMs: backoffMs });\n await sleepWithAbort(backoffMs, signal);\n hasRetried429 = true;\n continue;\n }\n if (decision === \"rotate\") {\n // EC-A: persistence failures during rotate must NOT abort the\n // stream. Pool state in-memory is the source of truth; disk\n // staleness self-corrects on the next successful save.\n try {\n await this.pool.markExhaustedAndRotate({\n entryId: entry.id,\n statusCode: attempt.error.metadata?.statusCode ?? inferStatusCode(attempt.error),\n ...(parseRetryAfterMs(attempt.error) !== undefined\n ? { resetAtMs: parseRetryAfterMs(attempt.error) }\n : {}),\n });\n } catch (persistErr) {\n diag(\n `[theokit-sdk] credential-pool: persist failed during rotate; continuing in-memory: ${\n persistErr instanceof Error ? persistErr.message : String(persistErr)\n }\\n`,\n );\n }\n hasRetried429 = false;\n continue;\n }\n // decision === \"propagate\" — a whole-attempt terminal failure (M2 #60).\n this.breaker.recordTimeout(this.pool.provider);\n throw attempt.error;\n }\n }\n\n /**\n * Earliest epoch ms among entries' `lastErrorResetAt` — best estimate\n * for the caller's `CredentialPoolExhaustedError.nextRetryAt`.\n */\n private nextRetryHint(): number | undefined {\n const resets = this.pool\n .list()\n .map((e) => e.lastErrorResetAt)\n .filter((v): v is number => v !== undefined);\n return resets.length === 0 ? undefined : Math.min(...resets);\n }\n}\n\n/**\n * Decision matrix per ADR D125 + D126. Pure function — testable in isolation.\n *\n * @internal\n */\nexport function classifyAndDecide(\n error: RateLimitError | AuthenticationError | NetworkError,\n hasRetried429: boolean,\n): Decision {\n // 5xx / network errors: pool doesn't help — propagate so cross-provider\n // fallback (FallbackLlmClient) can try a different provider.\n if (error instanceof NetworkError) return \"propagate\";\n\n // 401/403: rotate. No OAuth refresh in v1 (out of scope).\n if (error instanceof AuthenticationError) return \"rotate\";\n\n // RateLimitError covers 429 AND 402 (billing/quota) — distinguish via statusCode.\n const status = error.metadata?.statusCode ?? 429;\n if (status === 402) return \"rotate\"; // immediate, no retry (billing won't recover in ms)\n\n // 429: retry once, rotate on second.\n return hasRetried429 ? \"rotate\" : \"retry\";\n}\n\n/**\n * Convert provider's `retry-after` hint (seconds) into epoch ms.\n * The error mapper (D67) normalizes the header into `metadata.retryAfter`\n * (numeric seconds form only). Older formats land in `metadata.raw`.\n *\n * @internal\n */\nexport function parseRetryAfterMs(\n error: RateLimitError | AuthenticationError | NetworkError,\n): number | undefined {\n const seconds = error.metadata?.retryAfter;\n if (typeof seconds === \"number\" && seconds > 0) {\n return Date.now() + seconds * 1000;\n }\n return undefined;\n}\n\nfunction inferStatusCode(error: RateLimitError | AuthenticationError | NetworkError): number {\n if (error instanceof AuthenticationError) return 401;\n if (error instanceof RateLimitError) return 429;\n return 0;\n}\n\nfunction abortError(signal: AbortSignal): Error {\n if (signal.reason instanceof Error) return signal.reason;\n return new Error(\"AbortError\");\n}\n","/**\n * OpenAI **Responses API** transport (`apiMode: \"responses_api\"`).\n *\n * The SDK's `ApiMode` declared `\"responses_api\"` but shipped NO transport — `selectTransport` threw\n * `transport_unavailable` (whose message even names `@theokit-transport-responses_api`). This IS that\n * transport: an `LlmClient` that POSTs the Responses-API body to `${baseUrl}/responses` and translates the\n * SSE event stream into `LlmEvent`/`LlmFinish`. It powers the ChatGPT Codex backend\n * (`https://chatgpt.com/backend-api/codex/responses`) and any responses-API provider.\n *\n * The request-body shape and the SSE event names/fields are ADAPTED FROM OpenCode (MIT © 2025 opencode —\n * https://github.com/sst/opencode: `packages/llm/src/protocols/openai-responses.ts`). OpenCode's engine is\n * Effect-based with an elaborate lifecycle/tool-stream state machine; this is a faithful port of the PROTOCOL\n * shape (event names, field access, terminal/usage handling) retargeted to theokit's much smaller\n * `LlmClient` contract (`name` + `stream → AsyncGenerator<LlmEvent, LlmFinish>`). MIT permits this with attribution.\n *\n * `extraHeaders` (unused by the chat-completions transport until now) + `baseUrl` are consumed here; a `fetch`\n * override lets a host inject a refresh-aware fetch (dynamic `ChatGPT-Account-Id` / `session-id`, mid-turn\n * token refresh) — mirroring `OpenAIClient`.\n */\nimport { mapOpenAICompatibleError } from \"../error-mappers/openai-compatible.js\";\nimport { collapseSystemText, makeLlmFinish, parseToolArguments } from \"./finish.js\";\nimport { parseSseStream } from \"./sse.js\";\nimport { toStringToolResultContent } from \"./tool-result-content.js\";\nimport type {\n LlmClient,\n LlmEvent,\n LlmFinish,\n LlmMessage,\n LlmRequest,\n LlmStopReason,\n LlmToolCallPart,\n} from \"./types.js\";\n\nexport interface ResponsesApiClientOptions {\n apiKey: string;\n /** e.g. `https://chatgpt.com/backend-api/codex`; the client POSTs `${baseUrl}/responses`. */\n baseUrl?: string;\n /** Static headers the profile declares (e.g. `ChatGPT-Account-Id`, `originator`). */\n extraHeaders?: Record<string, string>;\n /** Injected fetch (refresh-aware / dynamic headers). Defaults to global `fetch`. */\n fetch?: typeof fetch;\n providerName?: string;\n}\n\n/** Translate an `LlmMessage` into the Responses-API `input[]` items it contributes. */\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nfunction messageToInputItems(message: LlmMessage): unknown[] {\n const items: unknown[] = [];\n if (message.role === \"user\") {\n const content: unknown[] = [];\n for (const part of message.content) {\n if (part.type === \"text\") {\n content.push({ type: \"input_text\", text: part.text });\n } else if (part.type === \"image\") {\n const url =\n part.source.type === \"base64\"\n ? `data:${part.source.media_type};base64,${part.source.data}`\n : part.source.url;\n content.push({ type: \"input_image\", image_url: url });\n } else if (part.type === \"tool_result\") {\n items.push({\n type: \"function_call_output\",\n call_id: part.toolUseId,\n output: toStringToolResultContent(part.content, \"openai-responses\"),\n });\n }\n }\n if (content.length > 0) items.push({ role: \"user\", content });\n return items;\n }\n if (message.role === \"assistant\") {\n const content: unknown[] = [];\n for (const part of message.content) {\n if (part.type === \"text\") {\n content.push({ type: \"output_text\", text: part.text });\n } else if (part.type === \"tool_use\") {\n items.push({\n type: \"function_call\",\n call_id: part.id,\n name: part.name,\n arguments: JSON.stringify(part.input),\n });\n }\n }\n if (content.length > 0) items.push({ role: \"assistant\", content });\n return items;\n }\n // system role rarely appears here (system travels on `request.system`); fold to text.\n const text = message.content\n .filter((p) => p.type === \"text\")\n .map((p) => (p as { text: string }).text)\n .join(\"\\n\");\n if (text.length > 0) items.push({ role: \"system\", content: text });\n return items;\n}\n\n/** Build the Responses-API request body from an `LlmRequest`. */\nexport function buildResponsesBody(request: LlmRequest): Record<string, unknown> {\n const input: unknown[] = [];\n for (const message of request.messages) {\n for (const item of messageToInputItems(message)) input.push(item);\n }\n // The Responses API wants the BARE model id (`gpt-5.4`), never a `provider/model` id. The router\n // normally strips the provider prefix before the transport; strip here too as defense-in-depth so an\n // unstripped `openai-chatgpt/gpt-5.4` can never reach the backend as a 400 (decoupled from the router's\n // provider-inference heuristics).\n const slash = request.model.lastIndexOf(\"/\");\n const model = slash >= 0 ? request.model.slice(slash + 1) : request.model;\n const body: Record<string, unknown> = { model, input, stream: true, store: false };\n const instructions = collapseSystemText(request.system);\n if (instructions.length > 0) body.instructions = instructions;\n if (request.maxTokens !== undefined) body.max_output_tokens = request.maxTokens;\n if (request.temperature !== undefined) body.temperature = request.temperature;\n const tools = (request.tools ?? []).map((tool) => ({\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n strict: false,\n }));\n if (tools.length > 0) body.tools = tools;\n if (request.reasoning !== undefined) body.reasoning = { effort: request.reasoning.effort };\n return body;\n}\n\ninterface ResponsesEvent {\n type?: string;\n delta?: string;\n item_id?: string;\n item?: {\n type?: string;\n id?: string;\n call_id?: string;\n name?: string;\n arguments?: string;\n };\n response?: {\n usage?: {\n input_tokens?: number;\n output_tokens?: number;\n output_tokens_details?: { reasoning_tokens?: number };\n };\n error?: { message?: string };\n };\n message?: string;\n}\n\nexport class ResponsesApiClient implements LlmClient {\n readonly name: string;\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: ResponsesApiClientOptions) {\n this.name = options.providerName ?? \"openai-responses\";\n this.baseUrl = (options.baseUrl ?? \"https://api.openai.com/v1\").replace(/\\/+$/, \"\");\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: the SSE dispatch (text / reasoning / tool-call add+delta+done / terminal+usage / error) is one cohesive state machine, mirroring OpenAIStreamAccumulator.consume.\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n const providerId = this.options.providerName ?? \"openai\";\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n accept: \"text/event-stream\",\n authorization: `Bearer ${this.options.apiKey}`,\n ...(this.options.extraHeaders ?? {}),\n };\n const url = `${this.baseUrl}/responses`;\n\n const response = await this.fetchImpl(url, {\n method: \"POST\",\n signal,\n headers,\n body: JSON.stringify(buildResponsesBody(request)),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n let body: unknown = text;\n try {\n body = JSON.parse(text);\n } catch {\n /* not JSON */\n }\n throw mapOpenAICompatibleError({\n providerId,\n status: response.status,\n body,\n headers: response.headers,\n endpoint: \"/responses\",\n });\n }\n\n let text = \"\";\n const toolCalls: LlmToolCallPart[] = [];\n let stopReason: LlmStopReason = \"end_turn\";\n let inputTokens: number | undefined;\n let outputTokens: number | undefined;\n let reasoningTokens: number | undefined;\n // function-call accumulation keyed by the streamed output-item id.\n const pending: Record<string, { callId: string; name: string; args: string }> = {};\n\n if (response.body !== null) {\n for await (const record of parseSseStream(response.body, signal)) {\n if (record.data === \"[DONE]\") break;\n let event: ResponsesEvent;\n try {\n event = JSON.parse(record.data) as ResponsesEvent;\n } catch {\n continue;\n }\n const t = event.type;\n if (t === \"response.output_text.delta\") {\n const d = event.delta ?? \"\";\n if (d.length > 0) {\n text += d;\n yield { type: \"text_delta\", text: d };\n }\n } else if (\n t === \"response.reasoning_summary_text.delta\" ||\n t === \"response.reasoning_text.delta\"\n ) {\n const d = event.delta ?? \"\";\n if (d.length > 0) yield { type: \"reasoning_delta\", text: d };\n } else if (t === \"response.output_item.added\" && event.item?.type === \"function_call\") {\n const id = event.item.id ?? event.item.call_id ?? \"call-0\";\n pending[id] = {\n callId: event.item.call_id ?? id,\n name: event.item.name ?? \"\",\n args: event.item.arguments ?? \"\",\n };\n } else if (t === \"response.function_call_arguments.delta\") {\n const c = event.item_id !== undefined ? pending[event.item_id] : undefined;\n if (c !== undefined) c.args += event.delta ?? \"\";\n } else if (t === \"response.output_item.done\" && event.item?.type === \"function_call\") {\n const id = event.item.id ?? event.item.call_id ?? \"call-0\";\n const c = pending[id] ?? {\n callId: event.item.call_id ?? id,\n name: event.item.name ?? \"\",\n args: event.item.arguments ?? \"\",\n };\n const rawArgs = event.item.arguments ?? c.args;\n const call: LlmToolCallPart = {\n type: \"tool_use\",\n id: c.callId,\n name: c.name.length > 0 ? c.name : (event.item.name ?? \"\"),\n input: parseToolArguments(rawArgs),\n };\n // theokit#144: the call is carried by `LlmFinish.toolCalls` below. It used to also be\n // yielded as a `tool_use` event that no consumer read — see the `LlmEvent` docblock for\n // why the live tool channel is `onDelta`, not this stream.\n toolCalls.push(call);\n delete pending[id];\n } else if (t === \"response.completed\" || t === \"response.incomplete\") {\n const usage = event.response?.usage;\n if (usage !== undefined) {\n inputTokens = usage.input_tokens;\n outputTokens = usage.output_tokens;\n reasoningTokens = usage.output_tokens_details?.reasoning_tokens;\n }\n stopReason = t === \"response.incomplete\" ? \"max_tokens\" : \"end_turn\";\n } else if (t === \"response.failed\" || t === \"error\") {\n // Never echo a raw provider body — report the message only. Map to a typed provider error.\n const msg = event.response?.error?.message ?? event.message ?? \"responses stream failed\";\n yield { type: \"error\", message: msg };\n throw mapOpenAICompatibleError({\n providerId,\n status: 502,\n body: { error: { message: msg } },\n headers: response.headers,\n endpoint: \"/responses\",\n });\n }\n }\n }\n\n if (toolCalls.length > 0 && stopReason === \"end_turn\") stopReason = \"tool_use\";\n // theokit#144: `stopReason` is returned on the finish value, not yielded as an event.\n return makeLlmFinish({\n stopReason,\n text,\n toolCalls,\n inputTokens,\n outputTokens,\n reasoningTokens,\n });\n }\n}\n","/**\n * The error to throw when an `AbortSignal` is already aborted.\n *\n * Extracted in M93 (adversarial review, L1) when this would have been the **third** copy — rule of 3.\n * `pool-aware-client.ts` and `fallback-client.ts` kept the same function with slightly different string\n * fallbacks; this version preserves the more informative of the two.\n *\n * Preferring `signal.reason` over a raw `new Error(\"aborted\")` is what `error-handling.md` § 2 asks for: a\n * cancellation carries the canceller's reason, and replacing it with generic text erases the cause.\n *\n * @internal\n */\nexport function abortError(signal: AbortSignal): Error {\n if (signal.reason instanceof Error) return signal.reason;\n return new Error(signal.reason !== undefined ? String(signal.reason) : \"aborted\");\n}\n","/**\n * M93 — retry for the **single-key** path, which had none.\n *\n * ## The defect\n *\n * `buildPoolOrSingle` returns a `PoolAwareLlmClient` — with circuit breaker, full-jitter backoff,\n * `Retry-After` handling and rotation — when there are **>= 2** keys. With **one**, it returns the\n * raw transport. A consumer resolving exactly one credential (the common case) never gets a retry:\n * a 429 after eight tool calls kills the turn.\n *\n * The asymmetry has no domain justification. **A pool of 1 key is a pool of size 1** — what changes\n * between 1 and 2 keys is whether there is somewhere to rotate to, not whether resilience exists.\n *\n * ## Why a decorator, and why it is cheap\n *\n * `computeBackoffMs`, `sleepWithAbort` and `CircuitBreaker` **are already independent modules** —\n * `PoolAwareLlmClient` imports them, it does not contain them. So this is composition, not a\n * rewrite (parsimony rung 4: reuse what is already installed). What was missing was not the logic;\n * it was the logic being reachable outside the pool path.\n *\n * A decorator rather than a branch inside the pool: an `LlmClient` wrapping another applies to\n * **both** arms without duplicating anything, and the pool gains no degenerate one-element mode.\n *\n * ## Only transient errors are retried\n *\n * `error-handling.md` § 2 is explicit: \"external-API timeout -> retry with backoff; business-rule\n * violation -> fail immediately\". A 401 retried three times delays the error by seconds without\n * changing the outcome — and hides the real cause from the user for longer.\n *\n * @internal\n */\nimport {\n CredentialPoolExhaustedError,\n isTransientError,\n RateLimitError,\n TheokitAgentError,\n} from \"../../errors.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { abortError } from \"./abort-error.js\";\nimport { computeBackoffMs, sleepWithAbort } from \"./retry.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\n\n/** Attempt ceiling. Fixed at 3 — M93's DoD names the number. */\nexport const MAX_ATTEMPTS = 3;\n\n/**\n * Is the error transient — that is, can retrying change the outcome?\n *\n * ## Delegates to `isTransientError`, and states what it subtracts\n *\n * The SDK **already** publishes `isTransientError` — documented as \"a single source of truth rather\n * than a re-derivation\", with the explicit warning that \"It never inspects `err.message`\". The first\n * version of this function ignored both: it re-derived, by regex over the message (`/\\b4\\d\\d\\b/`).\n * Adversarial review measured the cost — `connect ECONNREFUSED 127.0.0.1:443` was classified as NOT\n * transient, because the **port** matches the regex. The network errors retry exists for were\n * exactly the ones excluded.\n *\n * Reinventing here violated parsimony rung 4 with the part already at hand. What remains of this\n * function are **three subtractions** from the owner's verdict, each with a reason:\n *\n * | Subtraction | Why |\n * |---|---|\n * | `CredentialPoolExhaustedError` | the pool already spent its own attempt and rotation budget; `nextRetryAt` is tens of seconds out. Retrying would multiply the wait by `MAX_ATTEMPTS` with no chance of success. |\n * | `code === \"circuit_open\"` | the breaker exists **in order to** fail fast; wrapping it in a retry undoes from outside the decision it just made. |\n * | `RateLimitError` with 402 | a billing quota does not resolve in milliseconds — which is why the pool's `classifyAndDecide` rotates instead of waiting. |\n *\n * The first two came out of the review's measurements: with them treated as transient, the entire\n * pool was retried 3x, and a 30 s wait became ~90 s.\n */\nexport function isRetriableError(err: unknown): boolean {\n if (!isTransientError(err)) return false;\n if (err instanceof CredentialPoolExhaustedError) return false;\n if (err instanceof TheokitAgentError && err.code === \"circuit_open\") return false;\n if (err instanceof RateLimitError && err.metadata?.statusCode === 402) return false;\n return true;\n}\n\n/** The `Retry-After` normalized by the error mapper, in ms from now. */\nfunction retryAfterHintMs(err: unknown): number | undefined {\n if (!(err instanceof RateLimitError)) return undefined;\n const seconds = err.metadata?.retryAfter;\n return typeof seconds === \"number\" && seconds > 0 ? seconds * 1000 : undefined;\n}\n\n/**\n * Forwards the inner stream, flagging `state` as soon as the first event leaves.\n *\n * The flag has to live OUTSIDE the generator because the `catch` that decides about retrying is in\n * the caller — and it is that distinction (emitted or not) that separates \"a retriable failure\"\n * from \"a turn already partially delivered to the consumer\".\n */\nasync function* consume(\n gen: AsyncGenerator<LlmEvent, LlmFinish, void>,\n state: { emitted: boolean },\n): AsyncGenerator<LlmEvent, LlmFinish, void> {\n let step = await gen.next();\n while (step.done !== true) {\n state.emitted = true;\n yield step.value;\n step = await gen.next();\n }\n return step.value;\n}\n\n/** Worth retrying? Not if it already emitted, not on the last attempt, not if the error is final. */\nfunction canRetry(err: unknown, emitted: boolean, attempt: number): boolean {\n if (emitted) return false;\n if (attempt === MAX_ATTEMPTS - 1) return false;\n return isRetriableError(err);\n}\n\n/**\n * ## Why there is NO circuit breaker here\n *\n * The package's `CircuitBreaker` is **keyed by credential** (`recordSuccess(key)` /\n * `recordTimeout(key)`): it exists so the pool can mark a key unhealthy and **skip** to another.\n * With a single key there is nowhere to skip to, so a breaker here would record state nobody reads.\n *\n * Parsimony rung 1 — \"does this need to exist?\". No: it would be ceremony with resilience's name on\n * it. What protects the single-key path is the attempt ceiling and the backoff, and both are below.\n */\nexport class RetryingLlmClient implements LlmClient {\n readonly #inner: LlmClient;\n readonly #rng: (() => number) | undefined;\n\n constructor(inner: LlmClient, opts?: { rng?: () => number }) {\n this.#inner = inner;\n this.#rng = opts?.rng;\n }\n\n /**\n * The decorated client. Public by the same convention as `FaultInjectingLlmClient.inner`: the\n * router's wiring tests assert `instanceof PoolAwareLlmClient` and need to see through the\n * decorators. Without this, adding a decorator breaks tests whose intent is still valid — which is\n * exactly what M93 did to 4 pre-existing tests.\n */\n get inner(): LlmClient {\n return this.#inner;\n }\n\n get name(): string {\n return this.#inner.name;\n }\n\n /**\n * Waits out attempt `n`'s backoff, honoring the provider's `Retry-After` when one arrived.\n *\n * Its own method because `stream` is a generator with a nested loop, and inlining the conditional\n * option assembly here pushed cognitive complexity to 19 (project ceiling: 10). The body of\n * `stream` stays nothing but the attempt machine.\n */\n async #waitBackoff(err: unknown, attempt: number, signal: AbortSignal): Promise<void> {\n const hint = retryAfterHintMs(err);\n const ms = computeBackoffMs({\n attempt,\n ...(hint !== undefined ? { retryAfterMs: hint } : {}),\n ...(this.#rng !== undefined ? { rng: this.#rng } : {}),\n });\n // theokit-sdk#165 — announce the attempt BEFORE sleeping.\n //\n // Without this signal a retry is indistinguishable from no retry, and the issue shows what that\n // costs: a 429 in ~3s led to the conclusion that the retry path was never reached, when it was.\n // The backoff is full-jitter (`floor(random() * ceiling)`), so three attempts fit inside\n // milliseconds and vanish into the response latency — the only thing visible was the final error.\n //\n // It goes through the diagnostics channel, not stderr: the library does not own the host's\n // terminal (theokit#147). With no sink installed, silence.\n const cause = err instanceof Error ? err.name : typeof err;\n diag(\n `retry ${attempt + 1}/${MAX_ATTEMPTS} in ${String(ms)}ms — ${cause}` +\n (hint !== undefined ? ` (Retry-After: ${String(hint)}ms)` : \"\"),\n );\n await sleepWithAbort(ms, signal);\n }\n\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n let lastError: unknown;\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n if (signal.aborted) throw lastError ?? abortError(signal);\n // A failure AFTER the first event is NOT retriable: the consumer has already seen tokens, and\n // repeating would produce duplicated text — and, in the scenario that motivates M93 (a 429\n // after eight tool calls), duplicated `tool_use` blocks.\n //\n // Until M93's adversarial review this invariant lived only in the comment: the `yield` and the\n // following `gen.next()` both sat inside the `try`, so a failure mid-stream retried the whole\n // turn. Measured: the consumer received `[tok1, tok2]` across 2 attempts. The comment asserted\n // a guarantee the code did not provide — the rot class `adr-governance.md` § 5 residue 2\n // enumerates.\n const state = { emitted: false };\n try {\n return yield* consume(this.#inner.stream(request, signal), state);\n } catch (err) {\n lastError = err;\n if (!canRetry(err, state.emitted, attempt)) throw err;\n await this.#waitBackoff(err, attempt, signal);\n }\n }\n throw lastError ?? new Error(\"retries exhausted with no recorded error\");\n }\n}\n","/**\n * GCP Vertex AI HTTP error mapper (ADRs D67, D300).\n *\n * Vertex returns `{ error: { code, status, message, details } }` (Google\n * AIP-193 standard error shape).\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../../errors.js\";\nimport { buildErrorMetadata } from \"./shared.js\";\n\ninterface VertexErrorBody {\n error?: {\n code?: number;\n status?: string;\n message?: string;\n details?: unknown;\n };\n}\n\nexport interface MapVertexErrorArgs {\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\ntype VertexCode =\n | \"rate_limit\"\n | \"auth_unauthenticated\"\n | \"auth_permission\"\n | \"invalid_request\"\n | \"timeout\"\n | \"server_error\"\n | \"unknown\";\n\nconst VERTEX_RULES: ReadonlyArray<{ test: (s: number, e: string) => boolean; code: VertexCode }> = [\n { test: (s, e) => s === 429 || e === \"RESOURCE_EXHAUSTED\", code: \"rate_limit\" },\n { test: (s, e) => s === 401 || e === \"UNAUTHENTICATED\", code: \"auth_unauthenticated\" },\n { test: (s, e) => s === 403 || e === \"PERMISSION_DENIED\", code: \"auth_permission\" },\n {\n test: (s, e) =>\n s === 400 || e === \"INVALID_ARGUMENT\" || e === \"FAILED_PRECONDITION\" || e === \"NOT_FOUND\",\n code: \"invalid_request\",\n },\n { test: (s, e) => s === 408 || e === \"DEADLINE_EXCEEDED\", code: \"timeout\" },\n { test: (s) => s >= 500, code: \"server_error\" },\n];\n\nfunction classifyVertexError(args: MapVertexErrorArgs, errStatus: string): VertexCode {\n for (const rule of VERTEX_RULES) {\n if (rule.test(args.status, errStatus)) return rule.code;\n }\n return \"unknown\";\n}\n\nfunction vertexMetadata(args: MapVertexErrorArgs, code: string) {\n return buildErrorMetadata({\n provider: \"vertex\",\n endpoint: args.endpoint,\n code: code as Parameters<typeof buildErrorMetadata>[0][\"code\"],\n status: args.status,\n headers: args.headers,\n body: args.body,\n });\n}\n\nconst VERTEX_ERROR_BUILDERS: Record<\n VertexCode,\n (args: MapVertexErrorArgs, msg: string) => TheokitAgentError\n> = {\n rate_limit: (args, msg) =>\n new RateLimitError(`Vertex quota exhausted: ${msg}`, {\n metadata: vertexMetadata(args, \"rate_limit\"),\n }),\n auth_unauthenticated: (args, msg) =>\n new AuthenticationError(`Vertex unauthenticated: ${msg}`, {\n metadata: vertexMetadata(args, \"auth_failed\"),\n }),\n auth_permission: (args, msg) =>\n new AuthenticationError(`Vertex permission denied: ${msg}`, {\n metadata: vertexMetadata(args, \"auth_failed\"),\n }),\n invalid_request: (args, msg) =>\n new ConfigurationError(`Vertex validation: ${msg}`, {\n metadata: vertexMetadata(args, \"invalid_request\"),\n }),\n timeout: (args, msg) =>\n new NetworkError(`Vertex timeout: ${msg}`, { metadata: vertexMetadata(args, \"timeout\") }),\n server_error: (args, msg) =>\n new NetworkError(`Vertex server error: ${msg}`, {\n metadata: vertexMetadata(args, \"server_error\"),\n }),\n unknown: (args, msg) =>\n new UnknownAgentError(`Vertex unknown: ${msg}`, { metadata: vertexMetadata(args, \"unknown\") }),\n};\n\nexport function mapVertexError(args: MapVertexErrorArgs): TheokitAgentError {\n const parsed = parseBody(args.body);\n const errStatus = parsed.error?.status ?? \"\";\n const message = parsed.error?.message ?? \"Vertex request failed\";\n const code = classifyVertexError(args, errStatus);\n return VERTEX_ERROR_BUILDERS[code](args, message);\n}\n\nfunction parseBody(body: unknown): VertexErrorBody {\n if (body !== null && typeof body === \"object\") return body as VertexErrorBody;\n if (typeof body === \"string\") {\n try {\n return JSON.parse(body) as VertexErrorBody;\n } catch {\n return {};\n }\n }\n return {};\n}\n","/**\n * Vertex AI access token + config resolution (ADRs D288, D295).\n *\n * Uses `google-auth-library` (required peer dep) for ADC discovery:\n * 1. `GOOGLE_APPLICATION_CREDENTIALS` env (path to Service Account JSON)\n * 2. `gcloud auth application-default login` cached credentials\n * 3. Metadata server (GCE/GKE/Cloud Run/Cloud Functions)\n * 4. Workload Identity Federation (WIF; configured via Service Account JSON)\n *\n * EC-3 absorbed: differentiate \"peer dep missing\" (throws ConfigurationError\n * with install hint) from \"no credentials in ADC chain\" (returns undefined\n * so caller can throw a clearer downstream error).\n *\n * @internal\n */\n\nimport { createRequire } from \"node:module\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { diag } from \"../diagnostics.js\";\n\ninterface GoogleAuthClient {\n getAccessToken: () => Promise<{ token: string | null }>;\n}\n\ninterface GoogleAuthLib {\n GoogleAuth: new (opts: {\n scopes: string[];\n }) => {\n getClient: () => Promise<GoogleAuthClient>;\n };\n}\n\nlet cachedAuthClient: GoogleAuthClient | undefined;\n\nconst SCOPE_CLOUD_PLATFORM = \"https://www.googleapis.com/auth/cloud-platform\";\n\nexport async function resolveVertexAccessToken(): Promise<string | undefined> {\n if (cachedAuthClient === undefined) {\n cachedAuthClient = await getAuthClientOrThrow();\n }\n try {\n const result = await cachedAuthClient.getAccessToken();\n return result.token ?? undefined;\n } catch {\n // ADC chain exhausted — caller (router) emits the helpful error.\n return undefined;\n }\n}\n\nasync function getAuthClientOrThrow(): Promise<GoogleAuthClient> {\n let mod: GoogleAuthLib;\n try {\n const r = createRequire(import.meta.url);\n mod = r(\"google-auth-library\") as GoogleAuthLib;\n } catch (err) {\n // EC-3: differentiate module-not-found from runtime ADC failure.\n const isModuleMissing =\n err instanceof Error &&\n (err.message.includes(\"Cannot find module\") ||\n (err as { code?: string }).code === \"MODULE_NOT_FOUND\");\n if (isModuleMissing) {\n throw new ConfigurationError(\n \"Vertex provider requires `google-auth-library`. Install: `pnpm add google-auth-library`.\",\n { code: \"auth_failed\", cause: err },\n );\n }\n throw err;\n }\n try {\n const auth = new mod.GoogleAuth({ scopes: [SCOPE_CLOUD_PLATFORM] });\n return await auth.getClient();\n } catch (err) {\n // ADC chain exhausted at client construction time — return a stub that\n // forces resolveVertexAccessToken to return undefined.\n diag(\n `[theokit-sdk] Vertex ADC initialization failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n return { getAccessToken: async () => ({ token: null }) };\n }\n}\n\n/** Resolve project id via env vars (env-only in v1). */\nexport function resolveVertexProjectId(): string | undefined {\n return (\n process.env.GOOGLE_CLOUD_PROJECT ??\n process.env.GOOGLE_CLOUD_PROJECT_ID ??\n process.env.GCLOUD_PROJECT\n );\n}\n\n/** Resolve Vertex location (region) from env; defaults to `us-central1`. */\nexport function resolveVertexLocation(): string {\n return process.env.GOOGLE_CLOUD_LOCATION ?? process.env.CLOUD_ML_REGION ?? \"us-central1\";\n}\n\n/** Test seam — reset cached auth client. */\nexport function __resetVertexAuth(): void {\n cachedAuthClient = undefined;\n}\n\n/** Test seam — inject a custom client for unit tests. */\nexport function __setVertexAuthClientForTests(client: GoogleAuthClient | undefined): void {\n cachedAuthClient = client;\n}\n","/**\n * GCP Vertex AI client for Anthropic Messages (Adoption Roadmap #8; ADRs\n * D292, D293).\n *\n * v1 uses `:rawPredict` (non-streaming). Streaming via `:streamRawPredict`\n * with SSE follows the same shape but is gated behind a future iteration —\n * v1 returns the full response as a single delta to keep the streaming\n * interface contract.\n *\n * Body massage (D292):\n * - inject `anthropic_version: \"vertex-2023-10-16\"`\n * - strip `model` from body (goes in URL)\n * - strip `stream` from body\n *\n * Uses native `fetch` only — no `@anthropic-ai/vertex-sdk` (D294).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { mapVertexError } from \"../error-mappers/vertex.js\";\nimport { resolveVertexBaseUrl, stripVertexPrefix } from \"../providers/builtin/vertex.js\";\nimport {\n buildAnthropicCommonBody,\n handleAnthropicResponse,\n postAnthropicRequest,\n} from \"./anthropic-shared.js\";\nimport { makeLlmFinish } from \"./finish.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\nimport {\n resolveVertexAccessToken,\n resolveVertexLocation,\n resolveVertexProjectId,\n} from \"./vertex-auth.js\";\n\nexport interface VertexAnthropicClientOptions {\n /** When undefined, resolved lazily via `resolveVertexProjectId()`. */\n projectId?: string;\n /** When undefined, resolved lazily via `resolveVertexLocation()`. */\n location?: string;\n /**\n * OAuth access token. When provided, used as-is. When empty/undefined,\n * resolved lazily per request via `resolveVertexAccessToken()` (D288).\n */\n apiKey?: string;\n fetch?: typeof fetch;\n}\n\nexport class VertexAnthropicClient implements LlmClient {\n readonly name = \"vertex_anthropic\";\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: VertexAnthropicClientOptions) {\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n private resolveProjectOrThrow(): string {\n const projectId = this.options.projectId ?? resolveVertexProjectId();\n if (projectId !== undefined) return projectId;\n throw new ConfigurationError(\n \"Vertex requires a project id. Set GOOGLE_CLOUD_PROJECT env var or run `gcloud config set project <id>`.\",\n { code: \"auth_failed\" },\n );\n }\n\n private async resolveTokenOrThrow(): Promise<string> {\n const fromOpts = this.options.apiKey;\n if (fromOpts !== undefined && fromOpts.length > 0) return fromOpts;\n const fromAdc = await resolveVertexAccessToken();\n if (fromAdc !== undefined && fromAdc.length > 0) return fromAdc;\n throw new ConfigurationError(\n \"Vertex could not resolve an access token. Run `gcloud auth application-default login` or set GOOGLE_APPLICATION_CREDENTIALS to a service-account JSON path.\",\n { code: \"auth_failed\" },\n );\n }\n\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n const projectId = this.resolveProjectOrThrow();\n const location = this.options.location ?? resolveVertexLocation();\n const accessToken = await this.resolveTokenOrThrow();\n const baseUrl = resolveVertexBaseUrl({ projectId, location, modelDialect: \"anthropic\" });\n const bareModel = stripVertexPrefix(request.model);\n const endpoint = `/models/${encodeURIComponent(bareModel)}:rawPredict`;\n const url = `${baseUrl}${endpoint}`;\n\n const response = await postAnthropicRequest({\n fetchImpl: this.fetchImpl,\n url,\n token: accessToken,\n body: buildVertexAnthropicBody(request),\n signal,\n });\n\n const consumed = await handleAnthropicResponse({\n response,\n endpoint,\n errorMapper: mapVertexError,\n });\n if (consumed.text.length > 0) yield { type: \"text_delta\", text: consumed.text };\n return makeLlmFinish(consumed);\n }\n}\n\nfunction buildVertexAnthropicBody(request: LlmRequest): Record<string, unknown> {\n // D292: anthropic_version is REQUIRED in body (not header) and `model` is stripped.\n return {\n anthropic_version: \"vertex-2023-10-16\",\n ...buildAnthropicCommonBody(request),\n };\n}\n","/**\n * GCP Vertex AI Gemini client (Adoption Roadmap #8; ADR D291).\n *\n * Uses the **OpenAI-compat** endpoint:\n * POST https://{LOCATION}-aiplatform.googleapis.com/v1/projects/{P}/locations/{L}/endpoints/openapi/chat/completions\n *\n * Wraps `OpenAIClient` with the Vertex baseUrl + lazy OAuth token from\n * `google-auth-library` (D288). Limitation: Vertex silently drops\n * unsupported OpenAI params (D264-style trade-off).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { resolveVertexBaseUrl } from \"../providers/builtin/vertex.js\";\nimport { OpenAIClient } from \"./openai.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\nimport {\n resolveVertexAccessToken,\n resolveVertexLocation,\n resolveVertexProjectId,\n} from \"./vertex-auth.js\";\n\nexport interface VertexGeminiClientOptions {\n /** When undefined, resolved lazily via `resolveVertexProjectId()`. */\n projectId?: string;\n /** When undefined, resolved lazily via `resolveVertexLocation()`. */\n location?: string;\n /** When non-empty, used as-is. Otherwise resolved lazily via ADC. */\n apiKey?: string;\n fetch?: typeof fetch;\n}\n\nexport class VertexGeminiClient implements LlmClient {\n readonly name = \"vertex_gemini\";\n\n constructor(private readonly options: VertexGeminiClientOptions) {}\n\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n // EC-1 absorbed: helpful errors when projectId / token missing.\n const projectId = this.options.projectId ?? resolveVertexProjectId();\n if (projectId === undefined) {\n throw new ConfigurationError(\n \"Vertex requires a project id. Set GOOGLE_CLOUD_PROJECT env var or run \" +\n \"`gcloud config set project <id>`.\",\n { code: \"auth_failed\" },\n );\n }\n const location = this.options.location ?? resolveVertexLocation();\n const accessToken =\n this.options.apiKey !== undefined && this.options.apiKey.length > 0\n ? this.options.apiKey\n : await resolveVertexAccessToken();\n if (accessToken === undefined || accessToken.length === 0) {\n throw new ConfigurationError(\n \"Vertex could not resolve an access token. Run \" +\n \"`gcloud auth application-default login` or set \" +\n \"GOOGLE_APPLICATION_CREDENTIALS to a service-account JSON path.\",\n { code: \"auth_failed\" },\n );\n }\n\n // Vertex OpenAI-compat URL: baseUrl includes `.../endpoints/openapi`.\n // OpenAIClient appends `/v1/chat/completions` which gives the wrong path —\n // so we strip the `/v1/` suffix from our baseUrl construction by using\n // the parent URL and letting OpenAIClient add the suffix back.\n //\n // Resolved baseUrl (target):\n // .../endpoints/openapi/chat/completions\n // OpenAIClient builds:\n // {baseUrl}/v1/chat/completions\n // So we need baseUrl = `.../endpoints/openapi-no-suffix` such that\n // `{baseUrl}/v1/chat/completions` = `.../endpoints/openapi/chat/completions`.\n // That's not achievable via simple concat; the cleanest path is to\n // delegate directly using a custom URL — but to keep the existing\n // OpenAIClient code-path, we set baseUrl so that the suffix is correct\n // by mounting \"openapi\" as the leaf and letting `/v1/chat/completions`\n // append. Vertex's documented path is exactly:\n // .../endpoints/openapi/chat/completions (NO /v1)\n // We achieve this by providing a base ending in `/endpoints` and\n // re-mapping `/v1/chat/completions` → `/openapi/chat/completions`\n // via a custom URL builder client.\n //\n // For v1 we ship a minimal own client that targets the exact endpoint.\n const baseUrl = resolveVertexBaseUrl({ projectId, location, modelDialect: \"gemini\" });\n const url = `${baseUrl}/chat/completions`;\n\n // Reuse OpenAIClient by injecting a baseUrl that matches its `/v1/chat/completions` suffix.\n // To avoid that suffix mismatch, we bypass OpenAIClient.stream() entirely and\n // do a direct fetch — but Gemini's response shape IS OpenAI shape, so we\n // borrow OpenAIClient's accumulator via composition: pre-build the body,\n // then hand off to OpenAIClient with a synthetic baseUrl whose `/v1/chat/completions`\n // suffix lands on our actual endpoint.\n //\n // Simplest: create a wrapper fetch that rewrites the URL before delegating.\n const innerFetch = this.options.fetch ?? fetch;\n const rewriteFetch: typeof fetch = (input, init) => {\n // OpenAIClient calls `${baseUrl}/v1/chat/completions`. We rewrite that to\n // the actual Vertex URL.\n const requested =\n typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.toString()\n : (input as Request).url;\n const targetUrl = requested.endsWith(\"/v1/chat/completions\") ? url : requested;\n return innerFetch(targetUrl, init);\n };\n\n // Delegate to OpenAIClient with auth + rewrite.\n const inner = new OpenAIClient({\n apiKey: accessToken,\n baseUrl: \"https://_vertex_placeholder\",\n providerName: \"vertex\",\n fetch: rewriteFetch,\n });\n return yield* inner.stream(request, signal);\n }\n}\n","/**\n * Vertex AI dispatcher (Adoption Roadmap #8; ADRs D291, D292, D301).\n *\n * `selectTransport` doesn't see the model id (the credential resolution\n * happens before request dispatch). This client inspects `request.model`\n * at stream time and delegates to either `VertexGeminiClient` (OpenAI-compat\n * for Gemini) or `VertexAnthropicClient` (`:rawPredict` for Claude).\n *\n * @internal\n */\n\nimport { inferModelDialect } from \"../providers/builtin/vertex.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\nimport { VertexAnthropicClient } from \"./vertex-anthropic.js\";\nimport { VertexGeminiClient } from \"./vertex-gemini.js\";\n\nexport interface VertexRouterClientOptions {\n apiKey?: string;\n fetch?: typeof fetch;\n}\n\nexport class VertexRouterClient implements LlmClient {\n readonly name = \"vertex\";\n\n constructor(private readonly options: VertexRouterClientOptions) {}\n\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n const dialect = inferModelDialect(request.model);\n if (dialect === \"anthropic\") {\n const inner = new VertexAnthropicClient(this.options);\n return yield* inner.stream(request, signal);\n }\n const inner = new VertexGeminiClient(this.options);\n return yield* inner.stream(request, signal);\n }\n}\n","import { ConfigurationError } from \"../../errors.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { getProviderProfile, type ProviderProfile, registerBuiltins } from \"../providers/index.js\";\nimport { AnthropicClient } from \"./anthropic.js\";\nimport { BedrockAnthropicClient } from \"./bedrock-anthropic.js\";\nimport { CredentialPool, newPooledCredential } from \"./credential-pool.js\";\nimport { currentCredentialPool } from \"./credential-pool-context.js\";\nimport type { CredentialPoolStrategy } from \"./credential-pool-types.js\";\nimport { maybeWrapWithFaultInjection } from \"./fault-injection.js\";\nimport { OllamaNativeClient } from \"./ollama-native.js\";\nimport { OpenAIClient } from \"./openai.js\";\nimport { PoolAwareLlmClient } from \"./pool-aware-client.js\";\nimport { ResponsesApiClient } from \"./responses.js\";\nimport { RetryingLlmClient } from \"./retrying-client.js\";\nimport type { LlmClient } from \"./types.js\";\nimport { VertexRouterClient } from \"./vertex-router.js\";\n\n/**\n * Provider router (T4.3, ADRs D105-D107).\n *\n * Resolves an `LlmClient` from a `ProviderProfile`. The profile is the\n * data; the transport is selected by `apiMode`. Builtins are eagerly\n * registered on first call; user plugins in `~/.theokit/plugins/\n * model-providers/` are lazy-loaded.\n *\n * @internal\n */\n\nexport type ProviderName = \"anthropic\" | \"openai\" | \"openrouter\" | (string & {});\n\nexport interface ProviderRouterOptions {\n primary: ProviderName;\n fallback?: ProviderName[];\n /** Credential pools per provider (ADRs D123-D133). Optional. */\n apiKeys?: Record<string, string[]>;\n /** Pool rotation strategy per provider. Optional; default `\"fill_first\"`. */\n credentialPoolStrategy?: Record<string, CredentialPoolStrategy>;\n /**\n * Per-run opt-in leaked-dialect safe-parse derived from the chat route\n * (theokit#58 follow-up). When `true`, the resolved profile is cloned with\n * `extractToolCallsFromContent: true` so the OpenAI-compatible transport\n * recovers Hermes `<function=…></tool_call>` dialect leaked as text. Applied\n * to the resolved chain; fail-open, so a non-leaking provider is unaffected.\n */\n extractToolCallsFromContent?: boolean;\n /**\n * SE2 — forwarded into the pool-aware client so a 429 retry surfaces a\n * `rate_limit` RunEvent. Wired from `SendOptions.onRunEvent` at the run boundary.\n */\n onRateLimit?: (info: { attempt: number; retryAfterMs?: number }) => void;\n}\n\n/**\n * Resolves the provider chain synchronously. Builtins are eagerly registered.\n * Provider plugin discovery is expected to have run upfront (e.g., via\n * Agent.create initialization) before this is called.\n */\nexport function resolveProviderChain(options: ProviderRouterOptions): LlmClient[] {\n registerBuiltins();\n return buildChain(options);\n}\n\nfunction buildChain(options: ProviderRouterOptions): LlmClient[] {\n // EC-B: warn (once) on apiKeys entries for providers we don't recognize.\n warnUnknownProvidersInApiKeys(options.apiKeys);\n\n const seen = new Set<string>();\n const clients: LlmClient[] = [];\n const addClient = (name: ProviderName): void => {\n const lowered = name.toLowerCase();\n if (seen.has(lowered)) return;\n seen.add(lowered);\n const client = buildClient(lowered, options);\n // D14: wrap every resolved client with the fault-injection decorator.\n // The wrapper is a cheap noop unless `NODE_ENV=test` AND\n // `THEOKIT_TEST_RESPONSE_OVERRIDE` are both set — production is unaffected.\n if (client !== undefined) clients.push(maybeWrapWithFaultInjection(client));\n };\n addClient(options.primary);\n for (const fallback of options.fallback ?? []) addClient(fallback);\n if (clients.length === 0) {\n throw new ConfigurationError(\n `No provider client could be resolved (primary=${options.primary}). ` +\n `Set ANTHROPIC_API_KEY or OPENAI_API_KEY / OPENROUTER_API_KEY.`,\n { code: \"provider_unresolved\" },\n );\n }\n return clients;\n}\n\nfunction buildClient(name: string, routerOptions: ProviderRouterOptions): LlmClient | undefined {\n const baseProfile = getProviderProfile(name);\n if (baseProfile === undefined) return undefined;\n // theokit#58 follow-up: per-run route opt-in clones the resolved profile with\n // the leaked-dialect recovery flag so the OpenAI-compatible transport surfaces\n // Hermes `<function=…></tool_call>` calls leaked as text. Built-in profiles\n // ship the flag off; this is the per-run enablement path.\n const profile =\n routerOptions.extractToolCallsFromContent === true &&\n baseProfile.extractToolCallsFromContent !== true\n ? { ...baseProfile, extractToolCallsFromContent: true }\n : baseProfile;\n const resilience =\n routerOptions.onRateLimit !== undefined ? { onRateLimit: routerOptions.onRateLimit } : {};\n const ambient = currentCredentialPool(name);\n if (ambient !== undefined) {\n // M93 — the THIRD arm. Found while writing the second one's test: the ambient pool also returned\n // the client without the decorator, and leaving it out would create the same asymmetry the milestone removes,\n // only on a less visible path.\n return new RetryingLlmClient(\n new PoolAwareLlmClient(\n ambient,\n (apiKey) => selectTransport(profile, apiKey),\n undefined,\n resilience,\n ),\n );\n }\n const poolKeys = filterPoolKeys(routerOptions.apiKeys?.[name]);\n const noAuthOverride = maybeBuildNoAuthTransport(profile, poolKeys);\n if (noAuthOverride !== undefined) return noAuthOverride;\n return buildPoolOrSingle({ name, profile, poolKeys, routerOptions });\n}\n\n/**\n * EC-C MUST FIX (ADR D187): `authType: \"none\"` providers ignore apiKeys.\n * Building a CredentialPool against a runtime without auth is semantically\n * meaningless; emit one-shot warn and route to the sentinel transport.\n */\nfunction maybeBuildNoAuthTransport(\n profile: ProviderProfile,\n poolKeys: string[] | undefined,\n): LlmClient | undefined {\n if (profile.authType !== \"none\" || poolKeys === undefined || poolKeys.length === 0) {\n return undefined;\n }\n warnNoAuthApiKeysIgnoredOnce(profile.name);\n const sentinel = sentinelForNoAuth(profile);\n if (sentinel === undefined) return undefined;\n return selectTransport(profile, sentinel);\n}\n\n/** Pool path for ≥2 keys; single-key fast path otherwise; sentinel fallback. */\nfunction buildPoolOrSingle(args: {\n name: string;\n profile: ProviderProfile;\n poolKeys: string[] | undefined;\n routerOptions: ProviderRouterOptions;\n}): LlmClient | undefined {\n const { name, profile, poolKeys, routerOptions } = args;\n if (poolKeys !== undefined && poolKeys.length >= 2) {\n const strategy = routerOptions.credentialPoolStrategy?.[name] ?? \"fill_first\";\n const entries = poolKeys.map((accessToken, priority) =>\n newPooledCredential({ provider: name, accessToken, priority, source: \"manual\" }),\n );\n const pool = new CredentialPool(name, entries, strategy);\n const resilience =\n routerOptions.onRateLimit !== undefined ? { onRateLimit: routerOptions.onRateLimit } : {};\n // M93 — the pool ALREADY had retry inside; the outer decorator covers what it propagates (5xx and\n // network, which `classifyAndDecide` tells it to propagate because \"the pool does not help\"). Additive: rotation\n // behavior does not change.\n return new RetryingLlmClient(\n new PoolAwareLlmClient(\n pool,\n (apiKey) => selectTransport(profile, apiKey),\n undefined,\n resilience,\n ),\n );\n }\n // 1-entry pool / single-key fast path: prefer explicit apiKeys[name] over env.\n // D182: `authType: \"none\"` providers fall back to a sentinel placeholder\n // when no key is set — transports that ignore the Authorization header still work.\n // D286/D288: `aws_bearer` / `gcp_oauth` profiles use a lazy sentinel so the\n // client can resolve real credentials at stream time (helpful error if missing).\n const apiKey =\n poolKeys?.[0] ??\n resolveApiKey(profile.envVars) ??\n sentinelForNoAuth(profile) ??\n sentinelForLazyAuth(profile);\n if (apiKey === undefined) return undefined;\n // M93 — the ONE-key arm returned the RAW transport, with no retry at all. A pool of 1 key is a\n // pool of size 1: what changes between 1 and 2 keys is whether there is somewhere to rotate to, not\n // whether resilience exists. The typical consumer resolves exactly one credential and always landed here.\n return new RetryingLlmClient(selectTransport(profile, apiKey));\n}\n\nfunction resolveBaseUrlEnvOverride(providerName: string): string | undefined {\n switch (providerName) {\n case \"openai\":\n return process.env.OPENAI_API_BASE_URL;\n case \"openrouter\":\n return process.env.OPENROUTER_API_BASE_URL;\n case \"ollama\":\n return process.env.OLLAMA_HOST;\n case \"lmstudio\":\n return process.env.LMSTUDIO_HOST;\n case \"llamacpp\":\n return process.env.LLAMACPP_HOST;\n default:\n return undefined;\n }\n}\n\n// EC-C: one-shot warn keyed by provider name.\nconst warnedNoAuthApiKeys = new Set<string>();\nfunction warnNoAuthApiKeysIgnoredOnce(provider: string): void {\n if (warnedNoAuthApiKeys.has(provider)) return;\n warnedNoAuthApiKeys.add(provider);\n diag(\n `[theokit-sdk] provider \"${provider}\" has authType: \"none\" — apiKeys ignored (no auth required for local runtime).\\n`,\n );\n}\n\n/** Test-only reset. @internal */\nexport function _resetNoAuthApiKeyWarnings(): void {\n warnedNoAuthApiKeys.clear();\n}\n\n/**\n * D182: providers declaring `authType: \"none\"` use a placeholder credential\n * so the OpenAI-compat transport keeps working. The placeholder value is\n * never sensitive — local runtimes ignore the Authorization header.\n */\nfunction sentinelForNoAuth(profile: ProviderProfile): string | undefined {\n return profile.authType === \"none\" ? profile.name : undefined;\n}\n\n/**\n * D286 / D288: providers with lazy-resolved auth (Bedrock Bearer via\n * `@aws/bedrock-token-generator`, Vertex via `google-auth-library`) may not\n * have credentials available at construction time — the client resolves\n * them per-request and throws helpful `ConfigurationError` if missing\n * (EC-1, EC-6 absorbed). Use a placeholder so the router still builds\n * the client; the user sees the helpful error on the first `agent.send`.\n */\nfunction sentinelForLazyAuth(profile: ProviderProfile): string | undefined {\n if (profile.authType === \"aws_bearer\") return \"__bedrock_lazy_token__\";\n if (profile.authType === \"gcp_oauth\") return \"__vertex_lazy_token__\";\n // M42: an oauth provider carries no static key — build the client with a lazy placeholder so its M41\n // `transform.fetch(ctx)` (which calls `resolveCredential` to obtain a freshly-refreshed bearer) owns\n // the real Authorization at stream time. Plain (api_key/none) profiles are unaffected.\n if (profile.authType === \"oauth_device_code\" || profile.authType === \"oauth_external\") {\n return \"__oauth_lazy_token__\";\n }\n return undefined;\n}\n\nfunction filterPoolKeys(keys: string[] | undefined): string[] | undefined {\n if (keys === undefined) return undefined;\n const cleaned = keys.filter((k) => typeof k === \"string\" && k.length > 0);\n return cleaned.length === 0 ? undefined : cleaned;\n}\n\nconst warnedProviders = new Set<string>();\nfunction warnUnknownProvidersInApiKeys(apiKeys: Record<string, string[]> | undefined): void {\n if (apiKeys === undefined) return;\n for (const name of Object.keys(apiKeys)) {\n if (warnedProviders.has(name)) continue;\n const profile = getProviderProfile(name);\n if (profile === undefined) {\n warnedProviders.add(name);\n diag(\n `[theokit-sdk] credential-pool: unknown provider \"${name}\" in apiKeys (no profile registered)\\n`,\n );\n }\n }\n}\n\n/** Test-only reset. @internal */\nexport function _resetCredentialPoolWarnings(): void {\n warnedProviders.clear();\n}\n\n/**\n * EC-10: resolve API key from ordered envVars list; first non-empty wins.\n */\nfunction resolveApiKey(envVars: ReadonlyArray<string>): string | undefined {\n for (const v of envVars) {\n const value = process.env[v];\n if (value !== undefined && value.length > 0) return value;\n }\n return undefined;\n}\n\n/**\n * EC-3 fix: exhaustive switch with actionable error on unsupported apiMode.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: 4-mode transport ladder (chat_completions / anthropic_messages / responses_api / bedrock) + Ollama native dispatch (D191) + per-provider envOverride is one cohesive switch — splitting hurts readability and obscures the dispatch contract.\nfunction selectTransport(profile: ProviderProfile, apiKey: string): LlmClient {\n // M41 — the optional provider `transform` seam (refresh-aware `fetch` + dynamic `headers` from the resolved\n // bearer). Invoked LAZILY, per-branch, ONLY by the transports that consume it (chat_completions +\n // responses_api) — so a transform's side effects (e.g. a token refresh) never fire for a transport that\n // ignores it (bedrock / ollama). Absent ⇒ each branch takes its byte-for-byte static path.\n const applyTransform = (): { fetch?: typeof fetch; headers?: Record<string, string> } => {\n if (profile.transform === undefined) return {};\n const ctx = { apiKey };\n return { fetch: profile.transform.fetch?.(ctx), headers: profile.transform.headers?.(ctx) };\n };\n\n /**\n * Applies the provider's transform over `opts` and returns the constructed client.\n *\n * The `chat_completions` and `anthropic_messages` arms did this IDENTICALLY, differing only in the\n * final constructor. That is duplicated KNOWLEDGE: \"apply the transform, require OAuth to be\n * resolved, and merge the dynamic headers ON TOP of the profile's static ones\" is the same rule for\n * any provider — fixing it in one arm and forgetting the other would leave one provider with a\n * refresh-aware transport and the other without, silently.\n *\n * Generic over `O` because each arm declares its own `opts` with its constructor's type\n * (`ConstructorParameters<typeof OpenAIClient>[0]` vs Anthropic's) — that is why a\n * the first attempt with a non-generic helper, declared before the `if`s, did not compile.\n */\n const comTransform = <\n O extends { fetch?: typeof fetch; extraHeaders?: Record<string, string> },\n C,\n >(\n opts: O,\n construct: (o: O) => C,\n ): C => {\n const t = applyTransform();\n assertOAuthResolved(t);\n if (t.fetch !== undefined) opts.fetch = t.fetch;\n const merged =\n profile.extraHeaders !== undefined || t.headers !== undefined\n ? { ...profile.extraHeaders, ...t.headers }\n : undefined;\n if (merged !== undefined) opts.extraHeaders = merged;\n return construct(opts);\n };\n\n // M42 review MEDIUM-1 — mirror OpenCode's auth model (packages/llm/src/route/auth.ts): a provider's auth\n // resolves to real headers at request time or FAILS with `MissingCredentialError` — it NEVER puts a\n // placeholder on the wire. theokit builds an oauth provider's client with the `__oauth_lazy_token__`\n // placeholder (so the sync router can construct it), then the provider's `transform` (the theokit analog of\n // OpenCode's `Auth.apply`) supplies the real bearer via fetch or an authorization header. If it supplies\n // neither, fail fast here with the MissingCredentialError analog instead of POSTing the placeholder upstream.\n const assertOAuthResolved = (t: {\n fetch?: typeof fetch;\n headers?: Record<string, string>;\n }): void => {\n if (apiKey !== \"__oauth_lazy_token__\") return;\n const auth = t.headers?.authorization ?? t.headers?.Authorization;\n if (t.fetch === undefined && auth === undefined) {\n throw new ConfigurationError(\n `provider \"${profile.name}\" uses OAuth (authType: ${profile.authType}) but no credential was ` +\n `resolved. Register a ProviderProfile.transform whose fetch (or headers.authorization) supplies ` +\n `the bearer — typically via resolveCredential() from \"@theokit/sdk/auth\".`,\n );\n }\n };\n\n if (profile.apiMode === \"chat_completions\") {\n // ADR D191 (T8.1 dogfood fix): Ollama tool calling REQUIRES the native\n // `/api/chat` endpoint. OpenAI-compat `/v1/chat/completions` causes\n // models to emit raw tool JSON as plain text — confirmed via peer-project\n // upstream warning and our own dogfood of telegram-pro.\n if (profile.name === \"ollama\") {\n const ollamaBase = process.env.OLLAMA_HOST ?? profile.baseUrl;\n return new OllamaNativeClient({ apiKey, baseUrl: ollamaBase });\n }\n const opts: ConstructorParameters<typeof OpenAIClient>[0] = { apiKey };\n opts.baseUrl = profile.baseUrl;\n // T1.1 (ADR D185): forward provider name so OpenAIClient can dispatch\n // Ollama-specific error mapping for ECONNREFUSED / 404-not-pulled / 503-loading.\n opts.providerName = profile.name;\n // theokit#58 follow-up: opt-in leaked-dialect safe-parse, declared per-profile (default off).\n if (profile.extractToolCallsFromContent === true) {\n opts.extractToolCallsFromContent = true;\n }\n // M45 — explicit chat-completions path override (data-only escape for unversioned shapes).\n if (profile.chatCompletionsPath !== undefined) {\n opts.chatCompletionsPath = profile.chatCompletionsPath;\n }\n if (profile.name === \"openai\" && process.env.OPENAI_ORGANIZATION !== undefined) {\n opts.organization = process.env.OPENAI_ORGANIZATION;\n }\n // Honor explicit base URL overrides for cloud providers + the local\n // `authType: \"none\"` family (D182, D188, D189). All four `_HOST` /\n // `_API_BASE_URL` vars are intentionally separate so users can mix\n // remote-box pointing without disturbing the others.\n const envOverride = resolveBaseUrlEnvOverride(profile.name);\n if (envOverride !== undefined) opts.baseUrl = envOverride;\n // M41 — feed the provider transform: `fetch` (refresh-aware transport) + `headers` merged over the\n // profile's static `extraHeaders`. OpenAIClient now honors `extraHeaders` (was ignored) — additive-safe:\n // no builtin sets it on chat_completions.\n return comTransform(opts, (o) => new OpenAIClient(o));\n }\n if (profile.apiMode === \"anthropic_messages\") {\n // Vertex sub-dispatch (D301): when profile.name === \"vertex\", route to\n // VertexRouterClient which picks Gemini vs Anthropic at stream time.\n // apiKey is either a real Bearer token (rare — caller passed it\n // explicitly) or the lazy sentinel `__vertex_lazy_token__` — strip\n // the latter so the client falls through to ADC discovery (D288).\n if (profile.name === \"vertex\") {\n const realKey = apiKey === \"__vertex_lazy_token__\" ? undefined : apiKey;\n return new VertexRouterClient(realKey !== undefined ? { apiKey: realKey } : {});\n }\n const opts: ConstructorParameters<typeof AnthropicClient>[0] = { apiKey };\n opts.baseUrl = process.env.ANTHROPIC_API_BASE_URL ?? profile.baseUrl;\n // M45 — feed the provider transform + static extraHeaders (mirror of the M41 chat_completions wiring),\n // so anthropic_messages providers can carry headers (anthropic-beta) and refresh-aware fetches (M46).\n return comTransform(opts, (o) => new AnthropicClient(o));\n }\n if (profile.apiMode === \"bedrock_anthropic\") {\n // D301: dedicated Bedrock InvokeModel client. apiKey from env when set;\n // strip the lazy sentinel so client triggers @aws/bedrock-token-generator (D287).\n const realKey = apiKey === \"__bedrock_lazy_token__\" ? undefined : apiKey;\n return new BedrockAnthropicClient(realKey !== undefined ? { apiKey: realKey } : {});\n }\n if (profile.apiMode === \"responses_api\") {\n // M40 — the OpenAI Responses-API transport (ChatGPT Codex backend + any responses provider). Consumes\n // `baseUrl` + `extraHeaders`. M41 — feeds the provider `transform`: `headers` merge over `extraHeaders`\n // (dynamic auth headers like a live `ChatGPT-Account-Id`), and `fetch` becomes the refresh-aware fetch\n // (closes the gap where `ResponsesApiClient` accepted a `fetch?` the router never passed).\n const t = applyTransform();\n assertOAuthResolved(t);\n const mergedHeaders =\n profile.extraHeaders !== undefined || t.headers !== undefined\n ? { ...profile.extraHeaders, ...t.headers }\n : undefined;\n return new ResponsesApiClient({\n apiKey,\n ...(profile.baseUrl !== undefined ? { baseUrl: profile.baseUrl } : {}),\n ...(mergedHeaders !== undefined ? { extraHeaders: mergedHeaders } : {}),\n ...(t.fetch !== undefined ? { fetch: t.fetch } : {}),\n providerName: profile.name,\n });\n }\n throw new ConfigurationError(\n `Provider \"${profile.name}\" requires apiMode \"${profile.apiMode}\" but no transport is registered. ` +\n `Install a third-party transport plugin (@theokit-transport-${profile.apiMode}) ` +\n `or use a provider with apiMode \"chat_completions\" or \"anthropic_messages\".`,\n { code: \"transport_unavailable\" },\n );\n}\n","/**\n * Provider inference helpers for the real local run — extracted from\n * `real-local-run.ts` to keep it within the G8 LoC budget and give the two\n * pure \"which provider?\" heuristics one cohesive home.\n *\n * @internal\n */\n\nimport { providerFromApiKeyPrefix } from \"../auth/api-key-prefix.js\";\nimport { getProviderProfile } from \"../providers/index.js\";\n\n/**\n * The provider a key belongs to, **restricted to providers this runtime can construct**.\n *\n * The prefix table moved to `auth/api-key-prefix.ts` and is no longer duplicated here — it was the\n * same knowledge in two places, and the copy here relied on its entries being hand-written in\n * longest-first order to be correct at all. What stays is the part that is genuinely this path's\n * policy: the local run will not name a provider it has no profile for.\n *\n * @internal\n */\nexport function inferProviderFromApiKey(apiKey: string | undefined): string | undefined {\n const provider = providerFromApiKeyPrefix(apiKey);\n if (provider === undefined) return undefined;\n return getProviderProfile(provider) === undefined ? undefined : provider;\n}\n\n/**\n * The default primary provider from the environment: the first of\n * ANTHROPIC / OPENAI / OPENROUTER with a non-empty key, else `openai`.\n *\n * @internal\n */\nexport function detectPrimaryProvider(): string {\n if (process.env.ANTHROPIC_API_KEY !== undefined && process.env.ANTHROPIC_API_KEY.length > 0) {\n return \"anthropic\";\n }\n if (process.env.OPENAI_API_KEY !== undefined && process.env.OPENAI_API_KEY.length > 0) {\n return \"openai\";\n }\n if (process.env.OPENROUTER_API_KEY !== undefined && process.env.OPENROUTER_API_KEY.length > 0) {\n return \"openrouter\";\n }\n return \"openai\";\n}\n","/**\n * T2.2 — Provider-agnostic compression-model registry (ADR D440).\n *\n * Resolves a cheaper-tier summarization model in the SAME vendor family\n * as the agent's main model. Provider-agnostic by design: a consumer\n * running on Anthropic-only / Ollama-only / Bedrock-only never needs\n * to provision a second vendor's key for the compression aux-LLM.\n *\n * Resolution algorithm:\n *\n * 1. Exact match in `EXACT_REGISTRY` → cheaper-tier id (most cases).\n * 2. Wildcard match in `WILDCARD_REGISTRY` (`*` suffix in key) →\n * swap matched suffix (Bedrock region-prefixed variants).\n * 3. Provider in `NO_AUTH_PROVIDERS` (Ollama / LM Studio / llama.cpp)\n * → return SAME model id (local — cost N/A; running the same\n * model for summarization costs only the round-trip latency,\n * acceptable in dev/local mode).\n * 4. No match → throw `CompressionModelUnresolvedError` with the\n * actionable message naming the model + override path + the\n * registry-PR remediation hint.\n *\n * Step 1 of T2.2 (compression-helpers wire). Step 2 wires this into\n * `compression-config.ts`. Step 3 builds the OTel-instrumented aux\n * client. Step 4 wires into `loop.ts` ContextWindowExceededError catch.\n *\n * @internal\n */\n\n/**\n * Exact `agent-model → compression-model` map. Most cases land here.\n * Entries MUST keep cheaper-tier model within the SAME vendor family\n * as the key (Unbreakable Rule 9 — provider-agnostic).\n */\nconst EXACT_REGISTRY: ReadonlyMap<string, string> = new Map([\n // OpenAI family\n [\"openai/gpt-4o\", \"openai/gpt-4o-mini\"],\n [\"openai/gpt-4-turbo\", \"openai/gpt-4o-mini\"],\n [\"openai/gpt-4\", \"openai/gpt-4o-mini\"],\n [\"openai/o1-preview\", \"openai/gpt-4o-mini\"],\n [\"openai/o1\", \"openai/gpt-4o-mini\"],\n [\"openai/o3\", \"openai/gpt-4o-mini\"],\n [\"openai/o3-mini\", \"openai/gpt-4o-mini\"],\n // Anthropic family\n [\"anthropic/claude-opus-4\", \"anthropic/claude-3-5-haiku-latest\"],\n [\"anthropic/claude-sonnet-4\", \"anthropic/claude-3-5-haiku-latest\"],\n [\"anthropic/claude-3-5-sonnet\", \"anthropic/claude-3-5-haiku-latest\"],\n [\"anthropic/claude-3-5-sonnet-latest\", \"anthropic/claude-3-5-haiku-latest\"],\n [\"anthropic/claude-3-opus\", \"anthropic/claude-3-haiku\"],\n [\"anthropic/claude-3-sonnet\", \"anthropic/claude-3-haiku\"],\n // Vertex (Gemini + Anthropic-on-Vertex)\n [\"vertex/gemini-1.5-pro\", \"vertex/gemini-1.5-flash\"],\n [\"vertex/gemini-2.0-pro\", \"vertex/gemini-1.5-flash\"],\n [\"vertex/claude-3-5-sonnet\", \"vertex/claude-3-5-haiku\"],\n [\"vertex/claude-3-opus\", \"vertex/claude-3-haiku\"],\n // OpenRouter (preserve openrouter prefix, swap tier within same vendor)\n [\"openrouter/openai/gpt-4o\", \"openrouter/openai/gpt-4o-mini\"],\n [\"openrouter/openai/gpt-4-turbo\", \"openrouter/openai/gpt-4o-mini\"],\n [\"openrouter/anthropic/claude-3-5-sonnet\", \"openrouter/anthropic/claude-3-5-haiku\"],\n [\"openrouter/anthropic/claude-opus-4\", \"openrouter/anthropic/claude-3-5-haiku\"],\n]);\n\n/**\n * Wildcard `agent-model-prefix* → compression-model-prefix*` map.\n * Used for region-prefixed Bedrock variants where the registry can't\n * enumerate every region literal. Matching algorithm: the registry\n * key MUST end with `*`; the input MUST match the prefix; the input's\n * suffix after the prefix is appended to the resolved value (also\n * ending with `*` to mark the swap point).\n */\nconst WILDCARD_REGISTRY: ReadonlyArray<readonly [string, string]> = [\n // Bedrock Anthropic: us.anthropic.claude-sonnet-* → us.anthropic.claude-3-haiku-*\n [\"bedrock/anthropic.claude-sonnet*\", \"bedrock/anthropic.claude-3-haiku*\"],\n [\"bedrock/anthropic.claude-opus*\", \"bedrock/anthropic.claude-3-haiku*\"],\n [\"bedrock/anthropic.claude-3-5-sonnet*\", \"bedrock/anthropic.claude-3-5-haiku*\"],\n];\n\n/**\n * Providers declaring `authType: \"none\"` in their profile (D182, D188,\n * D189). For these, return the SAME model — local runtime has no\n * \"cheaper tier\" semantics, latency penalty of summarizing twice is\n * acceptable in dev/local mode. Keys are the provider prefix BEFORE\n * the slash.\n */\nconst NO_AUTH_PROVIDERS: ReadonlySet<string> = new Set([\"ollama\", \"lmstudio\", \"llamacpp\"]);\n\n/**\n * T2.2 — Typed error thrown when `resolveCompressionModel` cannot\n * find a same-family-cheaper-tier mapping for `agentModel`. Surfaces\n * the offending model id so operators can either (a) provide\n * `Agent.create({compression: {model: ...}})` explicitly or (b) open\n * a registry-PR adding the missing entry.\n *\n * @public\n */\nexport class CompressionModelUnresolvedError extends Error {\n override readonly name = \"CompressionModelUnresolvedError\";\n readonly agentModel: string;\n constructor(agentModel: string) {\n super(\n `Could not resolve a same-family-cheaper-tier compression model for \"${agentModel}\". ` +\n `Provide Agent.create({compression: {model: \"<your-cheaper-model>\"}}) ` +\n `OR add \"${agentModel}\" to the compression-model-registry (see ADR D440).`,\n );\n this.agentModel = agentModel;\n }\n}\n\n/**\n * T2.2 — Resolve a cheaper-tier compression model from the agent's\n * main model id. Pure function — no I/O, no mutation, deterministic.\n *\n * @throws `CompressionModelUnresolvedError` when no rule matches.\n *\n * @internal\n */\nexport function resolveCompressionModel(agentModel: string): string {\n const exact = EXACT_REGISTRY.get(agentModel);\n if (exact !== undefined) return exact;\n const wildcard = matchWildcard(agentModel);\n if (wildcard !== null) return wildcard;\n if (isNoAuthProvider(agentModel)) return agentModel;\n throw new CompressionModelUnresolvedError(agentModel);\n}\n\n/** Wildcard suffix match — Bedrock region-prefixed variants. */\nfunction matchWildcard(agentModel: string): string | null {\n for (const [pattern, replacement] of WILDCARD_REGISTRY) {\n const prefix = pattern.endsWith(\"*\") ? pattern.slice(0, -1) : pattern;\n if (!agentModel.startsWith(prefix)) continue;\n const suffix = agentModel.slice(prefix.length);\n const replPrefix = replacement.endsWith(\"*\") ? replacement.slice(0, -1) : replacement;\n return `${replPrefix}${suffix}`;\n }\n return null;\n}\n\n/** Provider declares `authType: \"none\"` — local runtime, same model. */\nfunction isNoAuthProvider(agentModel: string): boolean {\n const slashIdx = agentModel.indexOf(\"/\");\n if (slashIdx <= 0) return false;\n return NO_AUTH_PROVIDERS.has(agentModel.slice(0, slashIdx));\n}\n","/**\n * T2.2 step 3/N — Compression summarizer (ADR D440).\n *\n * Takes a conversation window (messages to compress) + a resolved\n * compression model + an injected LLM caller, and returns a single\n * system-role summary message that replaces the compressed window.\n *\n * The `callLlm` parameter is dependency-injected so:\n * - Unit tests pass a deterministic fake (no real-LLM cost)\n * - The agent-loop passes a real LLM client bound to the resolved\n * compression config (step 4 wire)\n *\n * Failure mode per ADR D440: if the LLM call fails, throws\n * `CompressionFailedError` — the caller (loop.ts) catches this,\n * logs WARN with redacted metadata, and returns the ORIGINAL\n * conversation unchanged (counter incremented toward cap 3).\n *\n * @internal\n */\n\n// Canonical origin moved to the public `compaction.ts` (leaf type — M42 DTS lesson); re-exported\n// here for the existing internal importers.\nimport type { CompressibleMessage } from \"../../../compaction.js\";\n\nexport type { CompressibleMessage };\n\n/**\n * Typed error thrown when the compression LLM call fails or returns\n * an empty/ineffective summary. The caller catches and handles per\n * ADR D440 failure mode (WARN + original conversation + counter).\n *\n * @public\n */\nexport class CompressionFailedError extends Error {\n override readonly name = \"CompressionFailedError\";\n}\n\n/**\n * Build the summarization prompt from a conversation window.\n * The prompt instructs the LLM to produce a concise summary that\n * preserves all facts, decisions, and context needed for the\n * conversation to continue.\n *\n * @internal\n */\nexport function buildCompressionPrompt(messages: readonly CompressibleMessage[]): string {\n const formatted = messages.map((m) => `[${m.role}]: ${m.content}`).join(\"\\n\\n\");\n\n return (\n `Summarize the following ${messages.length} conversation messages into a concise ` +\n `summary that preserves ALL facts, decisions, user preferences, and context ` +\n `needed for the conversation to continue naturally. The summary will replace ` +\n `these messages in the context window. Be thorough but concise.\\n\\n` +\n `--- CONVERSATION TO SUMMARIZE ---\\n${formatted}\\n--- END ---`\n );\n}\n\nconst COMPRESSION_SYSTEM =\n \"You are a conversation summarizer. Produce a concise factual summary. \" +\n \"Preserve all decisions, preferences, code snippets, and action items. \" +\n \"Do not add commentary or opinions. Output ONLY the summary text.\";\n\n/**\n * Compress a conversation window via an aux-LLM summarization call.\n *\n * @param opts.messages — the messages to compress\n * @param opts.model — resolved compression model id\n * @param opts.callLlm — injected LLM caller `(model, system, user) => Promise<string>`\n * @returns a single system-role message containing the summary\n *\n * @throws `CompressionFailedError` on LLM failure or empty summary.\n *\n * @internal\n */\nexport async function compressConversationWindow(opts: {\n messages: readonly CompressibleMessage[];\n model: string;\n callLlm: (model: string, system: string, user: string) => Promise<string>;\n}): Promise<CompressibleMessage> {\n const userPrompt = buildCompressionPrompt(opts.messages);\n\n let summary: string;\n try {\n summary = await opts.callLlm(opts.model, COMPRESSION_SYSTEM, userPrompt);\n } catch (cause) {\n throw new CompressionFailedError(\n `Compression LLM call failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n if (!summary || summary.trim().length === 0) {\n throw new CompressionFailedError(\n \"Compression LLM returned empty summary — reduction ineffective.\",\n );\n }\n\n return {\n role: \"system\",\n content: `[Compressed conversation summary]: ${summary.trim()}`,\n };\n}\n","/**\n * M50 (agent-builder) — session-transcript compaction, Codex-faithful.\n *\n * Mirrors the vendored Codex mechanism (`codex-rs/core/src/compact.rs`):\n * - the replacement history = recent USER messages verbatim (newest→oldest under a token budget;\n * prior summaries filtered by marker) + ONE summary message with a textual marker prefix,\n * injected as `role:\"user\"` (`build_compacted_history`, compact.rs:589-663);\n * - persistence is APPEND-ONLY: a `compact_boundary` record becomes the new DAG root and the\n * replacement messages are chained onto it — resume replays boundary→replacement→suffix\n * (equivalent of `CompactedItem.replacement_history`, rollout is never truncated);\n * - a failing summarizer leaves the transcript UNTOUCHED (typed error; no partial state).\n *\n * The summarizer is dependency-injected: tests pass a deterministic fake; the public\n * `Agent.compact` wires the ADR-D440 compression summarizer (its first real caller).\n */\n\nimport { type CompressibleMessage, estimateTokens } from \"../../compaction.js\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { resolveProviderChain } from \"../llm/router.js\";\nimport {\n detectPrimaryProvider,\n inferProviderFromApiKey,\n} from \"../local-agent/real-local-run-provider.js\";\nimport { reconstructMessages, SessionTranscript } from \"../persistence/session-transcript.js\";\nimport { getProviderProfile, registerBuiltins } from \"../providers/index.js\";\nimport { resolveCompressionModel } from \"../runtime/compression/compression-model-registry.js\";\nimport { compressConversationWindow } from \"../runtime/compression/compression-summarizer.js\";\nimport { invalidateSessionCache } from \"./session-cache.js\";\n\n/** Textual marker prefixing every compact summary (Codex `SUMMARY_PREFIX` analog). */\nexport const COMPACT_SUMMARY_MARKER = \"[[theokit:compact-summary]]\";\n\n/** Budget of VERBATIM user messages preserved in the replacement (Codex `COMPACT_USER_MESSAGE_MAX_TOKENS`). */\nexport const COMPACT_USER_MESSAGE_MAX_TOKENS = 20_000;\n\nexport interface CompactLocation {\n cwd: string;\n agentId: string;\n model?: string;\n}\n\nexport interface CompactResult {\n preTokens: number;\n postTokens: number;\n}\n\n/** Is this message a summary produced by a PRIOR compaction? (filtered from verbatim preservation). */\nexport function isCompactSummary(content: string): boolean {\n // M56 — goal-continuation boilerplate is loop plumbing, not user knowledge: preserving N copies of\n // the template verbatim would crowd out real user messages from the preservation budget.\n return (\n content.startsWith(COMPACT_SUMMARY_MARKER) ||\n content.startsWith(\"[[theokit:goal-continuation]]\")\n );\n}\n\n/**\n * Extract the text of an LlmMessage: content is `LlmContentPart[]` — concatenate the `text` parts\n * (tool_call / tool_result / image parts are skipped for compaction purposes).\n */\nfunction plainText(content: unknown): string | undefined {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return undefined;\n const texts = content\n .filter(\n (p): p is { type: string; text: string } =>\n p !== null &&\n typeof p === \"object\" &&\n (p as { type?: unknown }).type === \"text\" &&\n typeof (p as { text?: unknown }).text === \"string\",\n )\n .map((p) => p.text);\n return texts.length > 0 ? texts.join(\"\\n\") : undefined;\n}\n\n/**\n * Compact one session transcript: summarize the reconstructed history, then append (append-only)\n * a `compact_boundary` + the replacement chain (recent user messages verbatim + marker'd summary).\n *\n * @throws whatever `summarize` throws — with the transcript guaranteed untouched.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: pre-existing (M50) — flagged only because this file was touched by an unrelated one-line M56 change; refactor tracked separately.\nexport async function compactSessionTranscript(opts: {\n store: SessionStore;\n loc: CompactLocation;\n sessionId: string;\n trigger: \"manual\" | \"auto\";\n summarize: (messages: readonly CompressibleMessage[]) => Promise<string>;\n}): Promise<CompactResult> {\n const prior = await opts.store.readRecords(opts.loc.agentId);\n const history = reconstructMessages(prior);\n\n const compressible: CompressibleMessage[] = [];\n for (const m of history) {\n const text = plainText(m.content);\n if (\n text !== undefined &&\n (m.role === \"user\" || m.role === \"assistant\" || m.role === \"system\")\n ) {\n compressible.push({ role: m.role, content: text });\n }\n }\n const preTokens = estimateTokens(compressible.map((m) => m.content).join(\"\\n\"));\n\n // Summarize FIRST — a throwing summarizer must leave the transcript untouched (fail-safe).\n const summaryBody = await opts.summarize(compressible);\n\n // Recent user messages verbatim: newest→oldest under the budget, prior summaries filtered.\n const preserved: string[] = [];\n let budget = 0;\n for (let i = compressible.length - 1; i >= 0; i--) {\n const m = compressible[i];\n if (m === undefined || m.role !== \"user\" || isCompactSummary(m.content)) continue;\n const cost = estimateTokens(m.content);\n if (budget + cost > COMPACT_USER_MESSAGE_MAX_TOKENS) {\n // M50 review F8 — Codex TRUNCATES the overflowing message and keeps the piece\n // (compact.rs:620-629); dropping it entirely loses the most-recent context verbatim.\n const remaining = COMPACT_USER_MESSAGE_MAX_TOKENS - budget;\n if (remaining > 50) {\n preserved.unshift(`${m.content.slice(0, remaining * 4)}\\n[...truncated for compaction...]`);\n }\n break;\n }\n budget += cost;\n preserved.unshift(m.content); // chronological order in the replacement\n }\n\n const summary = `${COMPACT_SUMMARY_MARKER}\\n${summaryBody}`;\n\n // Append-only write: boundary (new root) + replacement chained onto it.\n const transcript = SessionTranscript.fromRecords(prior, {\n cwd: opts.loc.cwd,\n sessionId: opts.sessionId,\n model: opts.loc.model ?? \"unknown\",\n });\n transcript.appendCompactBoundary({ preTokens, trigger: opts.trigger });\n for (const text of preserved) transcript.appendUserTurn(text);\n transcript.appendUserTurn(summary);\n const delta = transcript.records().slice(prior.length);\n await opts.store.appendRecords(opts.loc.agentId, delta);\n\n // M50 review F1 — the live process must FEEL the compaction: drop the in-memory session cache so\n // the next send re-hydrates from disk (replacement + later turns) instead of replaying the full\n // pre-compact history until a restart.\n invalidateSessionCache(opts.loc.cwd, opts.loc.agentId);\n\n const postTokens = estimateTokens([...preserved, summary].join(\"\\n\"));\n return { preTokens, postTokens };\n}\n\n/**\n * M50 review F6 (fixed by the probe) — the summarizer's provider route, PURE and unit-tested.\n * Precedence mirrors the run's M4 rule exactly:\n * 1. an EXPLICIT credential's provider wins (an sk-or- key + `openai/…` model must summarize via\n * OpenRouter — the key is the ground truth of which endpoint gets called);\n * 2. else a model prefix with a REGISTERED profile (the oauth `openai-chatgpt` builtin owns its\n * auth; the M45 fleet resolves its own env vars) routes through that profile;\n * 3. else the ENV-detected provider (fresh process, aggregator credential in env).\n * `fullSlug` marks aggregator routes (provider ≠ prefix): the agent's slug passes unstripped.\n */\nexport function resolveSummarizerRoute(opts: {\n keyProvider: string | undefined;\n modelPrefix: string | undefined;\n prefixHasProfile: boolean;\n envProvider: string;\n}): { provider: string; fullSlug: boolean } {\n const provider =\n opts.keyProvider ??\n (opts.prefixHasProfile && opts.modelPrefix !== undefined ? opts.modelPrefix : opts.envProvider);\n return { provider, fullSlug: provider !== opts.modelPrefix };\n}\n\n// ─── Default summarizer (the ADR-D440 subsystem's first real caller) ─────────────────────────────\n\n/**\n * Build the default summarizer for `Agent.compact`: the D440 `compressConversationWindow`\n * (aux-LLM summarization with typed failure) driven by a router-resolved LLM client. The\n * compression model resolves via the D440 registry with the agent's own model as fallback.\n */\nexport function buildDefaultSummarizer(opts: {\n agentModel: string;\n apiKey?: string;\n}): (messages: readonly CompressibleMessage[]) => Promise<string> {\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: pre-existing (M50) — flagged only because this file was touched by an unrelated one-line M56 change; refactor tracked separately.\n return async (messages) => {\n // Provider resolution mirrors the RUN's own (M4 rule: the explicit API key outranks the model\n // prefix — an sk-or- key + openai/gpt model must summarize via OpenRouter too). Using anything\n // else 401s in real setups (proven live in the M50 probe).\n registerBuiltins();\n const modelPrefix = opts.agentModel.includes(\"/\")\n ? opts.agentModel.slice(0, opts.agentModel.indexOf(\"/\"))\n : undefined;\n const prefixProfile = modelPrefix !== undefined ? getProviderProfile(modelPrefix) : undefined;\n // A prefix profile is only USABLE when its credentials are actually resolvable here: oauth/none\n // profiles own their auth; api_key profiles need one of their env vars set. A profile without a\n // usable credential (e.g. `openai` builtin with only OPENROUTER_API_KEY in env) must NOT win.\n const prefixUsable =\n prefixProfile !== undefined &&\n (prefixProfile.authType !== \"api_key\" ||\n prefixProfile.envVars.some((v) => (process.env[v] ?? \"\").length > 0));\n const route = resolveSummarizerRoute({\n keyProvider: inferProviderFromApiKey(opts.apiKey),\n modelPrefix,\n prefixHasProfile: prefixUsable,\n envProvider: detectPrimaryProvider(),\n });\n const provider = route.provider;\n\n let model: string;\n if (route.fullSlug) {\n // Aggregator route (e.g. OpenRouter): pass the agent's full slug through unstripped.\n model = opts.agentModel;\n } else {\n try {\n model = resolveCompressionModel(opts.agentModel);\n } catch {\n model = opts.agentModel; // registry miss — summarize with the agent's own model\n }\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: pre-existing (M50) — flagged only because this file was touched by an unrelated one-line M56 change; refactor tracked separately.\n const callLlm = async (m: string, system: string, user: string): Promise<string> => {\n const chain = resolveProviderChain({\n primary: provider,\n ...(opts.apiKey !== undefined ? { apiKeys: { [provider]: [opts.apiKey] } } : {}),\n });\n const client = chain[0];\n if (client === undefined) throw new Error(`no LLM client for provider \"${provider}\"`);\n const controller = new AbortController();\n let text = \"\";\n const stream = client.stream(\n { model: m, system, messages: [{ role: \"user\", content: [{ type: \"text\", text: user }] }] },\n controller.signal,\n );\n for (;;) {\n const step = await stream.next();\n if (step.done === true) break;\n if (step.value.type === \"text_delta\") text += step.value.text;\n if (step.value.type === \"error\") throw new Error(step.value.message);\n }\n return text;\n };\n\n const summary = await compressConversationWindow({ messages: [...messages], model, callLlm });\n return summary.content;\n };\n}\n\n// ─── Auto-compaction (Codex formula: fire at usage_real >= (cw*9)/10) ────────────────────────────\n\n/**\n * Should auto-compaction fire? Codex parity: `token_limit_reached` when real usage crosses 90% of\n * the model's context window (`context_window.rs:74-79`; limit default `(cw*9)/10`,\n * `openai_models.rs:459-469`). Missing inputs (no usage reported / model absent from the catalog)\n * NEVER fire — fail-safe toward \"do nothing\".\n */\nexport function shouldAutoCompact(opts: {\n usageTotal?: number | undefined;\n contextWindow?: number | undefined;\n}): boolean {\n if (opts.usageTotal === undefined || opts.contextWindow === undefined) return false;\n if (opts.usageTotal <= 0 || opts.contextWindow <= 0) return false;\n return opts.usageTotal >= Math.floor((opts.contextWindow * 9) / 10);\n}\n\n/** Anti-cascade bookkeeping: last turn we ATTEMPTED an auto-compact, per agent (globalThis — M44 B1). */\nconst autoCompactAttempts = (() => {\n const g = globalThis as unknown as Record<symbol, Map<string, number>>;\n const sym = Symbol.for(\"theokit-sdk.session.auto-compact-attempts\");\n if (g[sym] === undefined) g[sym] = new Map<string, number>();\n return g[sym];\n})();\n\n/**\n * Fire auto-compaction when the threshold is crossed — at most ONE attempt per turn per agent\n * (anti-cascade: a failing summarizer or a non-reducing summary must not loop). Returns whether a\n * compaction actually happened. Failures WARN and leave the transcript untouched.\n */\nexport async function autoCompactIfNeeded(opts: {\n store: SessionStore;\n loc: CompactLocation;\n sessionId: string;\n usageTotal?: number | undefined;\n contextWindow?: number | undefined;\n turnCount: number;\n summarize: (messages: readonly CompressibleMessage[]) => Promise<string>;\n}): Promise<boolean> {\n if (!shouldAutoCompact(opts)) return false;\n const key = `${opts.loc.cwd}::${opts.loc.agentId}`;\n if (autoCompactAttempts.get(key) === opts.turnCount) return false; // already attempted this turn\n autoCompactAttempts.set(key, opts.turnCount);\n try {\n await compactSessionTranscript({\n store: opts.store,\n loc: opts.loc,\n sessionId: opts.sessionId,\n trigger: \"auto\",\n summarize: opts.summarize,\n });\n return true;\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] auto-compaction failed (left transcript untouched): ${msg}\\n`);\n return false;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/providers/discovery.ts","../src/internal/error-mappers/anthropic.ts","../src/internal/llm/finish.ts","../src/internal/llm/tool-result-content.ts","../src/internal/llm/anthropic-shared.ts","../src/internal/llm/sse.ts","../src/internal/llm/transport-error.ts","../src/internal/llm/anthropic.ts","../src/internal/error-mappers/bedrock.ts","../src/internal/llm/bedrock-token-cache.ts","../src/internal/llm/bedrock-anthropic.ts","../src/internal/llm/fault-injection.ts","../src/internal/error-mappers/ollama.ts","../src/internal/llm/ollama-native.ts","../src/internal/runtime/fixtures/fixture-mode.ts","../src/internal/http.ts","../src/internal/llm/hermes-tool-extract.ts","../src/internal/llm/openai-messages.ts","../src/internal/llm/openai.ts","../src/internal/resilience/circuit-breaker.ts","../src/internal/llm/stream-relay.ts","../src/internal/llm/pool-aware-client.ts","../src/internal/llm/responses.ts","../src/internal/llm/abort-error.ts","../src/internal/llm/retrying-client.ts","../src/internal/error-mappers/vertex.ts","../src/internal/llm/vertex-auth.ts","../src/internal/llm/vertex-anthropic.ts","../src/internal/llm/vertex-gemini.ts","../src/internal/llm/vertex-router.ts","../src/internal/llm/router.ts","../src/internal/local-agent/real-local-run-provider.ts","../src/internal/runtime/compression/compression-model-registry.ts","../src/internal/runtime/compression/compression-summarizer.ts","../src/internal/session/compact-session.ts"],"names":["body","existsSync","flush","joinTextParts","buildClient","text","abortError","parseBody","createRequire","inner","apiKey"],"mappings":";;;;;;;;;;;;;;;;;AA2BA,IAAM,cAAA,GAAiB,eAAA,CAAgB,kCAAA,EAAoC,OAAO;AAAA,EAChF,IAAA,EAAM;AACR,CAAA,CAAE,CAAA;AAEF,SAAS,WAAA,GAAsB;AAC7B,EAAA,OAAO,IAAA,CAAK,OAAA,EAAQ,EAAG,UAAA,EA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A;AAAA,MAChB,OAAA,EAAS,MAAA;AAAA,MACT,WAAW,IAAA,CAAK;AAAA,KACjB,CAAA;AACD,IAAA,OAAO,IAAA;AAAA,EACT,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,MAAM,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AACjE,IAAA,IAAA,CAAK,qEAAqE,GAAG;AAAA,CAAI,CAAA;AACjF,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"chunk-M5EK7N6R.js","sourcesContent":["/**\n * Lazy provider discovery (T3.4, ADR D107).\n *\n * Scans `~/.theokit/plugins/model-providers/<name>/index.{js,mjs}` and\n * imports each as a Plugin. Plugins with `kind: \"model-provider\"` register\n * their profile. Errors per plugin are logged + skipped. Idempotent per\n * process.\n *\n * EC-9: dynamic `import()` in Node 22 needs `file://` URL for absolute\n * paths in ESM contexts. `pathToFileURL` handles both.\n *\n * @internal\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { diag } from \"../diagnostics.js\";\nimport { globalSingleton } from \"../global-singleton.js\";\nimport { registerProvider } from \"./registry.js\";\n\n// M47 review F3 — the idempotence flag lives on `globalThis` via `Symbol.for`, mirroring registry.ts's\n// M44 B1 pattern: tsup bundles each entry (`dist/index.js`, `dist/cron.js`, …) with its OWN module copy,\n// so a module-local `let discovered` would re-run discovery once per entry (duplicate I/O + spurious\n// \"Provider overridden\" WARNs). Every bundle copy shares THIS state.\nconst discoveryState = globalSingleton(\"theokit-sdk.providers.discovered\", () => ({\n done: false,\n}));\n\nfunction pluginsRoot(): string {\n return join(homedir(), \".theokit\", \"plugins\", \"model-providers\");\n}\n\n/** The explicit trust allowlist the human edits (M47). Fail-closed: missing/malformed ⇒ empty. */\nfunction trustFilePath(): string {\n return join(homedir(), \".theokit\", \"plugins\", \"trusted-providers.json\");\n}\n\n/**\n * M47 — the trust gate for the dynamic-import surface. A plugin's `index.{js,mjs}` executes arbitrary code\n * at import time, so NOTHING is imported unless the human explicitly trusted the plugin name: either in\n * `~/.theokit/plugins/trusted-providers.json` (a JSON string array — the auditable primary, mirroring the\n * approved-hooks posture) or the additive `THEOKIT_TRUSTED_PROVIDERS` env (comma-separated convenience).\n * Fail-closed: a missing or malformed trust file trusts NOTHING (a malformed file WARNs).\n */\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nfunction loadTrustedNames(): Set<string> {\n const trusted = new Set<string>();\n const path = trustFilePath();\n if (existsSync(path)) {\n try {\n const parsed: unknown = JSON.parse(readFileSync(path, \"utf-8\"));\n if (Array.isArray(parsed)) {\n let discarded = 0;\n for (const name of parsed) {\n if (typeof name === \"string\" && name.length > 0) trusted.add(name);\n else discarded += 1;\n }\n // M47 review F5 — fail-closed AND fail-clear: a valid array with wrong-shaped entries\n // (numbers, objects) silently trusting nothing would leave the user with only the generic\n // per-plugin WARN and no clue the FILE shape is wrong.\n if (discarded > 0) {\n diag(\n `[theokit-sdk] WARN: ${path} contains ${discarded} non-string entr${discarded === 1 ? \"y\" : \"ies\"} — discarded (entries must be plugin-name strings)\\n`,\n );\n }\n } else {\n diag(\n `[theokit-sdk] WARN: ${path} is not a JSON array — trusting NO provider plugins (fail-closed)\\n`,\n );\n }\n } catch {\n diag(\n `[theokit-sdk] WARN: ${path} is not valid JSON — trusting NO provider plugins (fail-closed)\\n`,\n );\n }\n }\n for (const name of (process.env.THEOKIT_TRUSTED_PROVIDERS ?? \"\").split(\",\")) {\n const trimmed = name.trim();\n if (trimmed.length > 0) trusted.add(trimmed);\n }\n return trusted;\n}\n\nexport async function discoverProviderPlugins(): Promise<void> {\n if (discoveryState.done) return;\n discoveryState.done = true;\n\n const root = pluginsRoot();\n if (!existsSync(root)) return;\n\n let entries: string[];\n try {\n entries = await readdir(root);\n } catch {\n return;\n }\n\n const trusted = loadTrustedNames();\n for (const entry of entries) {\n // M47 — the gate fires BEFORE any import(): untrusted code is never evaluated (import-time side effects\n // ARE the attack; a post-import check would be theater).\n if (!trusted.has(entry)) {\n // M47 review F4/F7 — the remedy must be complete: discovery is once-per-process (the latch above),\n // so editing the trust file only takes effect after a restart; and the env format is comma-separated.\n diag(\n `[theokit-sdk] WARN: provider plugin \"${entry}\" is present but NOT trusted — skipped. ` +\n `To trust it, add \"${entry}\" to ${trustFilePath()} (JSON array of names) or ` +\n `THEOKIT_TRUSTED_PROVIDERS (comma-separated), then restart the process.\\n`,\n );\n continue;\n }\n await loadOne(join(root, entry), entry);\n }\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: 2-extension loader (mjs / js) + plugin shape detection (default / named / direct) — inlining is clearer than 5 helper fns.\nasync function loadOne(dir: string, entryName: string): Promise<void> {\n for (const ext of [\"index.mjs\", \"index.js\"]) {\n const indexPath = join(dir, ext);\n if (!existsSync(indexPath)) continue;\n try {\n const mod = await import(pathToFileURL(indexPath).href);\n const plugin = mod.default ?? mod[entryName] ?? mod;\n if (\n plugin !== null &&\n typeof plugin === \"object\" &&\n (plugin as { kind?: unknown }).kind === \"model-provider\"\n ) {\n const profile = (plugin as { profile?: unknown }).profile;\n if (profile !== undefined && typeof profile === \"object\") {\n registerProvider(profile as Parameters<typeof registerProvider>[0]);\n }\n }\n return;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n diag(`[theokit-sdk] failed to load provider plugin \"${entryName}\": ${msg}\\n`);\n return;\n }\n }\n}\n\n/** Test-only reset. @internal */\nexport function _resetDiscovery(): void {\n discoveryState.done = false;\n}\n","/**\n * Anthropic HTTP error mapper (ADR D67).\n *\n * Translates an Anthropic API error response into a typed\n * `TheokitAgentError` subclass with full `ErrorMetadata`. Mapping rules:\n *\n * 401/403 → `AuthenticationError` (`code: \"auth_failed\"`)\n * 429 → `RateLimitError` (`code: \"rate_limit\"`)\n * 400 → `ConfigurationError` (`code: \"context_too_long\"` if body\n * mentions context length, else\n * `\"invalid_request\"`; or\n * `\"content_filtered\"` for policy.)\n * 408 → `NetworkError` (`code: \"timeout\"`)\n * 5xx → `NetworkError` (`code: \"server_error\"` — covers 529\n * overloaded_error common at peak\n * at peak)\n * other → `UnknownAgentError` (`code: \"unknown\"`)\n *\n * Never throws — caller is already in an error path.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n type ErrorCode,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../../errors.js\";\nimport { buildErrorMetadata } from \"./shared.js\";\n\ninterface MapAnthropicErrorArgs {\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\nexport function mapAnthropicError(args: MapAnthropicErrorArgs): TheokitAgentError {\n const { status, body, headers, endpoint } = args;\n const code = mapAnthropicStatusToCode(status, body);\n const message = formatMessage(status, code);\n const metadata = buildErrorMetadata({\n provider: \"anthropic\",\n endpoint,\n code,\n status,\n headers,\n body,\n });\n\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { code: \"anthropic_auth_failed\", metadata });\n }\n if (status === 429) {\n return new RateLimitError(message, { code: \"anthropic_rate_limit\", metadata });\n }\n if (status === 400) {\n return new ConfigurationError(message, {\n code: `anthropic_${code}`,\n metadata,\n });\n }\n if (status === 408) {\n return new NetworkError(message, { code: \"anthropic_timeout\", metadata });\n }\n if (status >= 500 && status < 600) {\n return new NetworkError(message, { code: \"anthropic_server_error\", metadata });\n }\n return new UnknownAgentError(message, { code: \"anthropic_unknown\", metadata });\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: explicit branch table is clearer than splitting\nfunction mapAnthropicStatusToCode(status: number, body: unknown): ErrorCode {\n if (status === 401 || status === 403) return \"auth_failed\";\n if (status === 429) return \"rate_limit\";\n if (status === 408) return \"timeout\";\n if (status === 400) {\n const text = JSON.stringify(body ?? \"\").toLowerCase();\n if (\n text.includes(\"context\") &&\n (text.includes(\"too long\") || text.includes(\"too_long\") || text.includes(\"length\"))\n ) {\n return \"context_too_long\";\n }\n if (\n text.includes(\"filtered\") ||\n text.includes(\"content policy\") ||\n text.includes(\"content_policy\")\n ) {\n return \"content_filtered\";\n }\n return \"invalid_request\";\n }\n if (status >= 500 && status < 600) return \"server_error\";\n return \"unknown\";\n}\n\nfunction formatMessage(status: number, code: ErrorCode): string {\n return `Anthropic API error: ${code} (HTTP ${status})`;\n}\n","import { isPlainObject, tryJson } from \"../../sanitize/coerce.js\";\nimport type { LlmFinish, LlmRequest, LlmStopReason, LlmToolCallPart } from \"./types.js\";\n\n/**\n * Collapse the wider `LlmRequest.system` shape (undefined | string | block[])\n * into a single string. Providers that don't support per-block prompt caching\n * join blocks with a blank-line separator.\n *\n * Shared between Ollama native and OpenAI-compatible clients.\n *\n * @internal\n */\nexport function collapseSystemText(system: LlmRequest[\"system\"]): string {\n if (system === undefined) return \"\";\n if (typeof system === \"string\") return system;\n return system.map((b) => b.text).join(\"\\n\\n\");\n}\n\n/**\n * Decode a buffered JSON-arguments string into an object. Falls back to a\n * `{ raw }` envelope so we never crash on malformed provider output.\n *\n * @internal\n */\nexport function parseToolArguments(buffered: string | undefined): Record<string, unknown> {\n if (buffered === undefined || buffered.length === 0) return {};\n try {\n return JSON.parse(buffered) as Record<string, unknown>;\n } catch {\n // M2 #61 — attempt jsonrepair (reusing the sanitize coerce helper, Rule 9)\n // before giving up, so a slightly-malformed native tool call (trailing\n // comma, unquoted key — the Kimi/K2 class) parses instead of landing in\n // `{ raw }` and bouncing to the model as an invalid_request round-trip.\n const repaired = tryJson(buffered, true);\n if (isPlainObject(repaired)) return repaired;\n return { raw: buffered };\n }\n}\n\n/**\n * Map an OpenAI-compatible `finish_reason` to the provider-agnostic stop reason.\n * Shared by the OpenAI stream accumulator. Unknown reasons fall back to `end_turn`.\n *\n * @internal\n */\nexport function mapOpenAIFinish(reason: string): LlmStopReason {\n switch (reason) {\n case \"tool_calls\":\n return \"tool_use\";\n case \"length\":\n return \"max_tokens\";\n default:\n return \"end_turn\";\n }\n}\n\n/**\n * Build the provider-agnostic `LlmFinish` shape from accumulator state.\n * Shared between the Anthropic and OpenAI stream parsers so the two\n * implementations don't drift on token-usage fields.\n *\n * @internal\n */\nexport function makeLlmFinish(state: {\n stopReason: LlmStopReason;\n text: string;\n toolCalls: LlmToolCallPart[];\n inputTokens?: number;\n outputTokens?: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n /** theokit#122 — the turn's thinking block, with its provider signature when one was issued. */\n thinking?: import(\"./types.js\").LlmThinkingPart;\n}): LlmFinish {\n const finish: LlmFinish = {\n stopReason: state.stopReason,\n text: state.text,\n toolCalls: state.toolCalls,\n };\n if (state.inputTokens !== undefined) finish.inputTokens = state.inputTokens;\n if (state.outputTokens !== undefined) finish.outputTokens = state.outputTokens;\n if (state.cacheReadTokens !== undefined) finish.cacheReadTokens = state.cacheReadTokens;\n if (state.cacheWriteTokens !== undefined) finish.cacheWriteTokens = state.cacheWriteTokens;\n if (state.reasoningTokens !== undefined) finish.reasoningTokens = state.reasoningTokens;\n if (state.thinking !== undefined) finish.thinking = state.thinking;\n return finish;\n}\n","/**\n * SE7 — provider-agnostic helpers for structured tool-result content\n * ({@link ToolResultContentBlock}). Named by CAPABILITY, not by provider:\n *\n * - `toBlockToolResultContent` — for a wire that ACCEPTS content blocks.\n * - `toStringToolResultContent` — for a string-only wire (fail-fast on an image).\n * - `renderToolResultContentText` — map the text parts through a fn (for the guard).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type { ToolResultContentBlock } from \"../../types/content-blocks.js\";\n\n/**\n * For a block-capable provider wire: pass a string through unchanged, or forward\n * the structured blocks as-is (text + image).\n *\n * This is an INTENTIONAL identity: `ToolResultContentBlock` is defined to be\n * exactly the on-wire content-block shape that block-capable providers accept\n * for a tool result — `{ type: \"text\", text }` and\n * `{ type: \"image\", source: { type: \"base64\", media_type, data } }`. Because the\n * SDK type already IS the wire shape, no transformation is needed; this function\n * names that contract at the call site (and is the single seam to add a mapping\n * later, if a block-capable wire ever diverges from this shape). Do NOT add\n * SDK-internal fields to `ToolResultContentBlock` without updating this seam —\n * they would otherwise be forwarded verbatim onto the wire.\n */\nexport function toBlockToolResultContent(\n content: string | ToolResultContentBlock[],\n): string | ToolResultContentBlock[] {\n return content;\n}\n\n/**\n * For a string-only provider wire: pass a string through; flatten text-only\n * blocks to a newline-joined string; **fail fast** with a typed\n * {@link ConfigurationError} when an image block is present — that provider\n * cannot carry an image in a tool result, and silently dropping it would hand\n * the model a lie (per error-handling policy).\n */\nexport function toStringToolResultContent(\n content: string | ToolResultContentBlock[],\n providerName: string,\n): string {\n if (typeof content === \"string\") return content;\n if (content.some((block) => block.type === \"image\")) {\n throw new ConfigurationError(\n `provider \"${providerName}\" does not support image content in tool results`,\n );\n }\n return content\n .filter(\n (block): block is Extract<ToolResultContentBlock, { type: \"text\" }> => block.type === \"text\",\n )\n .map((block) => block.text)\n .join(\"\\n\");\n}\n\n/**\n * Apply `fn` to the text of a tool-result content (both the string form and the\n * text blocks of the structured form); image blocks pass through untouched.\n * Used by the tool-result guard so redaction/delimiting still covers text.\n */\nexport function renderToolResultContentText(\n content: string | ToolResultContentBlock[],\n fn: (text: string) => string,\n): string | ToolResultContentBlock[] {\n if (typeof content === \"string\") return fn(content);\n return content.map((block) =>\n block.type === \"text\" ? { type: \"text\" as const, text: fn(block.text) } : block,\n );\n}\n","/**\n * Shared helpers for Anthropic Messages wire format across direct API\n * (anthropic.ts), Vertex (vertex-anthropic.ts), and Bedrock (bedrock-anthropic.ts)\n * clients. Extracted to remove cross-module clones flagged by jscpd.\n *\n * @internal\n */\n\nimport { parseToolArguments } from \"./finish.js\";\nimport { toBlockToolResultContent } from \"./tool-result-content.js\";\nimport type {\n LlmContentPart,\n LlmMessage,\n LlmRequest,\n LlmStopReason,\n LlmSystemBlock,\n LlmToolCallPart,\n} from \"./types.js\";\n\nexport interface AnthropicResponseLike {\n content?: Array<\n | { type: \"text\"; text: string }\n | { type: \"tool_use\"; id: string; name: string; input: Record<string, unknown> }\n >;\n stop_reason?: string | null;\n usage?: { input_tokens?: number; output_tokens?: number };\n}\n\nexport function extractAnthropicText(response: AnthropicResponseLike): string {\n return (response.content ?? [])\n .filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\");\n}\n\nexport function extractAnthropicToolCalls(response: AnthropicResponseLike): LlmToolCallPart[] {\n return (response.content ?? [])\n .filter(\n (c): c is { type: \"tool_use\"; id: string; name: string; input: Record<string, unknown> } =>\n c.type === \"tool_use\",\n )\n .map((c) => ({\n type: \"tool_use\" as const,\n id: c.id,\n name: c.name,\n input: parseToolArguments(JSON.stringify(c.input)),\n }));\n}\n\nexport function mapAnthropicStopReason(reason: string | null): LlmStopReason {\n switch (reason) {\n case \"tool_use\":\n return \"tool_use\";\n case \"max_tokens\":\n return \"max_tokens\";\n case \"stop_sequence\":\n return \"stop_sequence\";\n case \"end_turn\":\n case null:\n return \"end_turn\";\n default:\n return \"end_turn\";\n }\n}\n\n/**\n * Convert an SDK `LlmMessage` to the Anthropic Messages wire shape.\n * Identical across the three Anthropic-compatible clients (D289/D292).\n */\n/**\n * theokit#122 — replay an extended-thinking block WITH its signature.\n *\n * Anthropic verifies the signature against the text, so both must go back byte-identically or the\n * request is rejected with `400 \"thinking blocks cannot be modified\"`. A part with no signature —\n * an OpenAI-compatible provider's reasoning text, or history recorded before this shipped — is\n * dropped rather than sent unsigned: an unsigned block fails the same validation, so sending it\n * would break the whole turn instead of losing one block of context.\n */\nfunction thinkingToWireBlock(\n part: Extract<LlmContentPart, { type: \"thinking\" }>,\n): Record<string, unknown> | undefined {\n return part.signature === undefined\n ? undefined\n : { type: \"thinking\", thinking: part.text, signature: part.signature };\n}\n\n/** Map one SDK content part to its Anthropic wire block (`undefined` = do not send). */\nfunction partToWireBlock(part: LlmContentPart): Record<string, unknown> | undefined {\n if (part.type === \"text\") return { type: \"text\", text: part.text };\n if (part.type === \"tool_use\") {\n return { type: \"tool_use\", id: part.id, name: part.name, input: part.input };\n }\n // M35 — Anthropic native image block: base64 source, unchanged shape.\n if (part.type === \"image\") return { type: \"image\", source: part.source };\n if (part.type === \"thinking\") return thinkingToWireBlock(part);\n return {\n type: \"tool_result\",\n tool_use_id: part.toolUseId,\n // SE7 — this wire is block-capable: strings pass through, structured\n // text/image blocks are forwarded natively.\n content: toBlockToolResultContent(part.content),\n ...(part.isError === true ? { is_error: true } : {}),\n };\n}\n\nexport function toAnthropicWireMessage(message: LlmMessage): Record<string, unknown> {\n const role = message.role === \"system\" ? \"user\" : message.role;\n // theokit#122 — `filter` drops the blocks the mapper declined to serialize.\n const content = message.content\n .map(partToWireBlock)\n .filter((b): b is Record<string, unknown> => b !== undefined);\n return { role, content };\n}\n\n/**\n * Build the common body shape for Anthropic Messages requests. Caller\n * is responsible for adding wire-specific fields (`anthropic_version`,\n * `model`, `stream`, etc.).\n */\n/**\n * Issue a POST to an Anthropic-compatible Messages endpoint with the\n * standard auth + content-type headers. Caller maps non-2xx via its own\n * dialect-specific error mapper.\n */\nexport function postAnthropicRequest(args: {\n fetchImpl: typeof fetch;\n url: string;\n token: string;\n body: Record<string, unknown>;\n signal: AbortSignal;\n}): Promise<Response> {\n return args.fetchImpl(args.url, {\n method: \"POST\",\n signal: args.signal,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization: `Bearer ${args.token}`,\n },\n body: JSON.stringify(args.body),\n });\n}\n\n/**\n * Map non-2xx response to a typed error via the dialect mapper; consume\n * 2xx body into the Anthropic-shape result. Shared by Bedrock + Vertex\n * Anthropic clients to remove the ~15-line clone (jscpd).\n */\nexport async function handleAnthropicResponse(args: {\n response: Response;\n endpoint: string;\n errorMapper: (info: {\n status: number;\n body: unknown;\n headers: Headers;\n endpoint: string;\n }) => Error;\n}): Promise<{\n text: string;\n toolCalls: LlmToolCallPart[];\n stopReason: LlmStopReason;\n inputTokens?: number;\n outputTokens?: number;\n}> {\n if (!args.response.ok) {\n throw args.errorMapper({\n status: args.response.status,\n body: await parseHttpErrorBody(args.response),\n headers: args.response.headers,\n endpoint: args.endpoint,\n });\n }\n return consumeAnthropicResponse(args.response);\n}\n\nexport async function consumeAnthropicResponse(response: Response): Promise<{\n text: string;\n toolCalls: LlmToolCallPart[];\n stopReason: LlmStopReason;\n inputTokens?: number;\n outputTokens?: number;\n}> {\n const data = (await response.json()) as AnthropicResponseLike;\n return {\n text: extractAnthropicText(data),\n toolCalls: extractAnthropicToolCalls(data),\n stopReason: mapAnthropicStopReason(data.stop_reason ?? null),\n inputTokens: data.usage?.input_tokens,\n outputTokens: data.usage?.output_tokens,\n };\n}\n\nexport async function parseHttpErrorBody(response: Response): Promise<unknown> {\n const text = await response.text().catch(() => \"\");\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nexport interface AnthropicTextBlock {\n type: \"text\";\n text: string;\n cache_control?: { type: \"ephemeral\" };\n}\n\n/**\n * theokit#122 — map the provider-agnostic reasoning `effort` onto Anthropic's token budget.\n *\n * Anthropic does not take an effort label; it takes `budget_tokens`, and the API requires\n * `budget_tokens >= 1024` and `max_tokens > budget_tokens`. The three tiers mirror the effort\n * vocabulary the OpenAI-compatible wire uses, so a caller writes `thinking: \"low\"` once and both\n * providers do something sensible. An unrecognised effort maps to the medium tier rather than\n * failing the request — the knob is a hint, not a contract.\n */\nfunction thinkingBudgetTokens(effort: string): number {\n if (effort === \"low\" || effort === \"minimal\") return 1024;\n if (effort === \"high\" || effort === \"max\") return 16_384;\n return 4096;\n}\n\nexport function buildAnthropicCommonBody(request: LlmRequest): {\n max_tokens: number;\n messages: Array<Record<string, unknown>>;\n system?: string | AnthropicTextBlock[];\n temperature?: number;\n tools?: Array<{ name: string; description: string; input_schema: unknown }>;\n thinking?: { type: \"enabled\"; budget_tokens: number };\n} {\n const body: ReturnType<typeof buildAnthropicCommonBody> = {\n max_tokens: request.maxTokens ?? 4096,\n messages: request.messages.map(toAnthropicWireMessage),\n };\n // theokit#122 — without this the adapter never requested extended thinking, so no signature was\n // ever issued and the rest of the chain would have been dead code (the theokit#144 lesson).\n if (request.reasoning?.effort !== undefined) {\n const budget = thinkingBudgetTokens(request.reasoning.effort);\n body.thinking = { type: \"enabled\", budget_tokens: budget };\n // The API rejects `max_tokens <= budget_tokens`. Raise the ceiling rather than silently\n // shrinking the budget the caller asked for.\n if (body.max_tokens <= budget) body.max_tokens = budget + 4096;\n }\n const wireSystem = encodeAnthropicSystem(request.system);\n if (wireSystem !== undefined) body.system = wireSystem;\n if (request.temperature !== undefined) body.temperature = request.temperature;\n if (request.tools !== undefined && request.tools.length > 0) {\n body.tools = request.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n input_schema: tool.inputSchema,\n }));\n }\n return body;\n}\n\n/**\n * T3.5 — translate `LlmRequest.system` to the Anthropic wire shape.\n *\n * - `undefined` → omit (`undefined`).\n * - `string` → forward verbatim (back-compat, no caching).\n * - `LlmSystemBlock[]` → array of `{type:\"text\", text, cache_control?}`.\n * `cacheable: true` → emit `cache_control:{type:\"ephemeral\"}`.\n * Empty array short-circuits to `undefined`.\n *\n * @internal\n */\nfunction encodeAnthropicSystem(\n system: string | LlmSystemBlock[] | undefined,\n): string | AnthropicTextBlock[] | undefined {\n if (system === undefined) return undefined;\n if (typeof system === \"string\") return system;\n if (system.length === 0) return undefined;\n return system.map((block) => {\n const wire: AnthropicTextBlock = { type: \"text\", text: block.text };\n if (block.cacheable === true) wire.cache_control = { type: \"ephemeral\" };\n return wire;\n });\n}\n","/**\n * Minimal Server-Sent-Events parser. Consumes a fetch `Response` body\n * stream and yields `{ event, data }` records as they arrive. Used by\n * both the Anthropic and OpenAI streaming clients — neither vendor sends\n * binary SSE so a simple text decoder is enough.\n *\n * @internal\n */\n\nimport { NetworkError } from \"../../errors.js\";\n\nexport interface SseRecord {\n event: string;\n data: string;\n}\n\n/**\n * M2 #61 — default idle timeout (ms) between SSE reads. \"Idle\" means *no bytes\n * at all* arrive within the window — distinct from a slow-but-alive stream that\n * keeps trickling chunks. A stalled upstream that handshakes then goes silent no\n * longer hangs the AsyncGenerator forever; it rejects a typed NetworkError so\n * FallbackLlmClient / retry can route it. Pass `0` to disable.\n */\nexport const DEFAULT_SSE_IDLE_MS = 60_000;\n\ninterface ParserState {\n buffer: string;\n event: string;\n data: string;\n}\n\nexport async function* parseSseStream(\n body: ReadableStream<Uint8Array> | null,\n signal: AbortSignal,\n idleTimeoutMs: number = DEFAULT_SSE_IDLE_MS,\n): AsyncGenerator<SseRecord, void, void> {\n if (body === null) return;\n const reader = body.getReader();\n const decoder = new TextDecoder(\"utf-8\");\n const state: ParserState = { buffer: \"\", event: \"message\", data: \"\" };\n try {\n for await (const chunk of readChunks(reader, signal, idleTimeoutMs)) {\n state.buffer += decoder.decode(chunk, { stream: true });\n for (const record of drainCompleteRecords(state)) yield record;\n }\n if (state.data.length > 0) yield { event: state.event, data: state.data };\n } finally {\n // T3.2 + T3.3 — cancel the underlying body stream on EVERY exit path\n // (abort, normal close, consumer break, consumer throw). Without this\n // the upstream HTTP TCP socket stays in CLOSE_WAIT until the OS times\n // it out. cancel() on a finished stream is a no-op so always-cancel\n // is safe.\n await cancelReaderQuietly(reader);\n releaseReader(reader);\n }\n}\n\n/**\n * T3.2 — yield each chunk from `reader` until `done` OR `signal.aborted`.\n * Extracted from `parseSseStream` so its complexity stays under budget.\n *\n * @internal\n */\nasync function* readChunks(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n signal: AbortSignal,\n idleTimeoutMs: number,\n): AsyncGenerator<Uint8Array, void, void> {\n while (true) {\n if (signal.aborted) return;\n const { value, done } = await readWithIdleTimeout(reader, idleTimeoutMs);\n if (done) return;\n if (value !== undefined) yield value;\n }\n}\n\n/**\n * M2 #61 — race a single `reader.read()` against an idle timer. The timer is\n * cleared the moment the read settles (success OR error), so a healthy stream\n * never leaves a dangling timeout. When the timer wins, reject a typed\n * `NetworkError` (`code: \"stream_idle_timeout\"`); the caller's `finally` cancels\n * the body socket. `idleTimeoutMs <= 0` disables the bound (legacy behavior).\n *\n * @internal\n */\nfunction readWithIdleTimeout(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n idleTimeoutMs: number,\n): Promise<Awaited<ReturnType<ReadableStreamDefaultReader<Uint8Array>[\"read\"]>>> {\n if (idleTimeoutMs <= 0) return reader.read();\n return new Promise<Awaited<ReturnType<ReadableStreamDefaultReader<Uint8Array>[\"read\"]>>>(\n (resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new NetworkError(`SSE stream idle for ${idleTimeoutMs}ms — upstream stalled`, {\n code: \"stream_idle_timeout\",\n }),\n );\n }, idleTimeoutMs);\n reader.read().then(\n (result) => {\n clearTimeout(timer);\n resolve(result);\n },\n (err: unknown) => {\n clearTimeout(timer);\n reject(err);\n },\n );\n },\n );\n}\n\n/**\n * T3.2 + T3.3 — cancel the underlying body stream on every exit path.\n * Swallows any cancel-time error per ADR D34's safe-exporter contract\n * (cancel-time errors never propagate to caller).\n *\n * Calling cancel on a stream that already completed naturally is a no-op\n * per the WHATWG streams spec, so unconditional cancel is safe.\n *\n * @internal\n */\nasync function cancelReaderQuietly(reader: ReadableStreamDefaultReader<Uint8Array>): Promise<void> {\n try {\n await reader.cancel();\n } catch {\n // best-effort — already cancelled OR upstream closed\n }\n}\n\nfunction drainCompleteRecords(state: ParserState): SseRecord[] {\n const out: SseRecord[] = [];\n let newlineIndex = state.buffer.indexOf(\"\\n\");\n while (newlineIndex !== -1) {\n const line = state.buffer.slice(0, newlineIndex).replace(/\\r$/, \"\");\n state.buffer = state.buffer.slice(newlineIndex + 1);\n const finished = applyLine(state, line);\n if (finished !== undefined) out.push(finished);\n newlineIndex = state.buffer.indexOf(\"\\n\");\n }\n return out;\n}\n\nfunction applyLine(state: ParserState, line: string): SseRecord | undefined {\n if (line === \"\") {\n if (state.data.length === 0) {\n state.event = \"message\";\n return undefined;\n }\n const record: SseRecord = { event: state.event, data: state.data };\n state.event = \"message\";\n state.data = \"\";\n return record;\n }\n if (line.startsWith(\":\")) return undefined;\n if (line.startsWith(\"event:\")) {\n // T3.1 — HTML Living Standard § 9.2.6: strip exactly ONE leading\n // U+0020 SPACE from the value; preserve other whitespace verbatim.\n state.event = stripOneLeadingSpace(line.slice(6));\n return undefined;\n }\n if (line.startsWith(\"data:\")) {\n const piece = stripOneLeadingSpace(line.slice(5));\n state.data = state.data.length === 0 ? piece : `${state.data}\\n${piece}`;\n }\n return undefined;\n}\n\n/**\n * T3.1 — HTML Living Standard § 9.2.6 step 5 of \"Process the field\":\n * \"If the value of field starts with a U+0020 SPACE character, remove\n * it from value.\"\n *\n * Pre-T3.1 the parser called `.trim()` which destroyed legitimate trailing\n * whitespace (and any extra leading whitespace beyond the first space).\n * This helper strips at most one leading space and leaves everything else.\n *\n * @internal\n */\nfunction stripOneLeadingSpace(value: string): string {\n return value.startsWith(\" \") ? value.slice(1) : value;\n}\n\nfunction releaseReader(reader: ReadableStreamDefaultReader<Uint8Array>): void {\n try {\n reader.releaseLock();\n } catch {\n // already released\n }\n}\n","/**\n * Types the socket failure `fetch` throws **before** any response exists.\n *\n * ## The hole this closes\n *\n * `mapAnthropicError` / `mapOpenAIError` only come into play when there is a `Response` — that is, for\n * **HTTP** errors. An ECONNREFUSED / ETIMEDOUT / DNS failure blows up at `await fetch(...)`, and until\n * M93 it propagated raw: `anthropic.ts` had no `try` at all, and `openai.ts` mapped **only** Ollama and\n * rethrew the rest (`throw fetchErr`).\n *\n * This matters because `isTransientError` — the SDK's single source of truth — returns `false` for\n * a foreign error **by contract** (\"wrap a foreign error in the appropriate SDK error first\",\n * `errors.ts:429`). With the transport letting the raw error escape, M93's retry would be dead\n * exactly the most classic failure it exists to cover. The same applied to the pool's\n * `classifyAndDecide`, which predates this milestone.\n *\n * ## Cancellation is NOT a transport failure\n *\n * `AbortError` also comes out of `fetch`, and wrapping it in a `NetworkError` (which is `isRetryable: true`)\n * would make an explicit user cancellation be retried three times. It propagates intact.\n *\n * @internal\n */\nimport { NetworkError } from \"../../errors.js\";\n\n/** Did the error come from an `abort()` rather than a network failure? */\nfunction ehAbort(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) return false;\n const nome = (err as { name?: unknown }).name;\n return nome === \"AbortError\" || nome === \"TimeoutError\";\n}\n\n/**\n * Wraps a socket failure in a {@link NetworkError}, preserving the cause.\n *\n * Returns the original error — unwrapped — when it is an abort or already an SDK error.\n */\nexport function wrapTransportError(\n err: unknown,\n ctx: { providerId: string; endpoint: string },\n): unknown {\n if (ehAbort(err)) return err;\n if (err instanceof NetworkError) return err;\n const detail = err instanceof Error ? err.message : String(err);\n return new NetworkError(`${ctx.providerId} transport failure on ${ctx.endpoint}: ${detail}`, {\n code: \"transport_failure\",\n cause: err,\n });\n}\n","import { NetworkError } from \"../../errors.js\";\nimport { mapAnthropicError } from \"../error-mappers/anthropic.js\";\nimport { buildAnthropicCommonBody, mapAnthropicStopReason } from \"./anthropic-shared.js\";\nimport { makeLlmFinish, parseToolArguments } from \"./finish.js\";\nimport { parseSseStream } from \"./sse.js\";\nimport { wrapTransportError } from \"./transport-error.js\";\nimport type {\n LlmClient,\n LlmEvent,\n LlmFinish,\n LlmRequest,\n LlmStopReason,\n LlmToolCallPart,\n} from \"./types.js\";\n\n/**\n * Real Anthropic Messages client. Streams `/v1/messages` and translates the\n * vendor SSE events (`content_block_delta`, `content_block_start`,\n * `message_delta`, `message_stop`) into our provider-agnostic `LlmEvent`s.\n *\n * Uses native `fetch` only — no `@anthropic-ai/sdk` dependency.\n *\n * @internal\n */\n\nexport interface AnthropicClientOptions {\n apiKey: string;\n baseUrl?: string;\n version?: string;\n fetch?: typeof fetch;\n /**\n * M45 — extra HTTP headers merged into the request (the profile's static `extraHeaders` + a provider\n * `transform.headers(ctx)`). Assigned AFTER the base headers (mirror of the M41 OpenAIClient wiring), so\n * a provider that owns its auth CAN override them by design.\n */\n extraHeaders?: Record<string, string>;\n}\n\ninterface AnthropicTextDelta {\n type: \"content_block_delta\";\n delta: { type: \"text_delta\"; text: string };\n}\n\ninterface AnthropicToolStart {\n type: \"content_block_start\";\n index: number;\n content_block: { type: \"tool_use\"; id: string; name: string; input: Record<string, unknown> };\n}\n\n/**\n * theokit#122 — the extended-thinking wire.\n *\n * Anthropic opens a `thinking` content block, streams its text as `thinking_delta`, and then emits\n * ONE `signature_delta` carrying the cryptographic signature for that block. All three are needed:\n * replaying the text without the signature is rejected on the next turn with\n * `400 \"thinking blocks cannot be modified\"`.\n */\ninterface AnthropicThinkingStart {\n type: \"content_block_start\";\n index: number;\n content_block: { type: \"thinking\"; thinking?: string; signature?: string };\n}\n\ninterface AnthropicThinkingDelta {\n type: \"content_block_delta\";\n index: number;\n delta: { type: \"thinking_delta\"; thinking: string };\n}\n\ninterface AnthropicSignatureDelta {\n type: \"content_block_delta\";\n index: number;\n delta: { type: \"signature_delta\"; signature: string };\n}\n\ninterface AnthropicToolDelta {\n type: \"content_block_delta\";\n index: number;\n delta: { type: \"input_json_delta\"; partial_json: string };\n}\n\ninterface AnthropicMessageDelta {\n type: \"message_delta\";\n delta: { stop_reason: string | null };\n /**\n * T3.8 — Anthropic native usage shape carries the 5-bucket cache counters\n * when the request annotated system blocks with `cache_control:\n * {type:\"ephemeral\"}` (shipped in T3.5). `cache_creation_input_tokens`\n * surfaces as `LlmFinish.cacheWriteTokens` (the 1.25x billing tier);\n * `cache_read_input_tokens` surfaces as `LlmFinish.cacheReadTokens` (the\n * 0.1x billing tier). Pre-T3.8 the SDK dropped both fields silently.\n */\n usage?: {\n input_tokens?: number;\n output_tokens?: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n };\n}\n\ntype AnthropicEvent =\n | AnthropicTextDelta\n | AnthropicToolStart\n | AnthropicToolDelta\n | AnthropicThinkingStart\n | AnthropicThinkingDelta\n | AnthropicSignatureDelta\n | AnthropicMessageDelta\n | { type: \"message_stop\" }\n | { type: string };\n\nexport class AnthropicClient implements LlmClient {\n readonly name = \"anthropic\";\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: AnthropicClientOptions) {\n this.baseUrl = options.baseUrl ?? \"https://api.anthropic.com\";\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: HTTP+SSE handshake + accumulator is intentionally one block\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n const body = buildAnthropicBody(request);\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n \"x-api-key\": this.options.apiKey,\n \"anthropic-version\": this.options.version ?? \"2023-06-01\",\n };\n // M45 — merge extra/dynamic headers (assign LAST — same override semantics as the chat_completions client).\n if (this.options.extraHeaders !== undefined) Object.assign(headers, this.options.extraHeaders);\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.baseUrl}/v1/messages`, {\n method: \"POST\",\n signal,\n headers,\n body: JSON.stringify(body),\n });\n } catch (fetchErr) {\n // M93 — a socket failure has no `Response`, so `mapAnthropicError` never saw it and it\n // propagated raw. A foreign error is NON-transient per `isTransientError`'s contract, so\n // retry was switched off on exactly the ECONNREFUSED/ETIMEDOUT case.\n throw wrapTransportError(fetchErr, { providerId: this.name, endpoint: \"/v1/messages\" });\n }\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n // Parse body as JSON when possible — gives the mapper access to\n // `error.code` / `error.type` fields. Leave as string otherwise.\n let body: unknown = text;\n try {\n body = JSON.parse(text);\n } catch {\n // not JSON — keep as string\n }\n throw mapAnthropicError({\n status: response.status,\n body,\n headers: response.headers,\n endpoint: \"/v1/messages\",\n });\n }\n\n const accumulator = new AnthropicStreamAccumulator();\n for await (const record of parseSseStream(response.body, signal)) {\n if (record.event === \"ping\" || record.event === \"message_start\") continue;\n let parsed: AnthropicEvent;\n try {\n parsed = JSON.parse(record.data) as AnthropicEvent;\n } catch {\n continue;\n }\n const events = accumulator.consume(parsed);\n for (const event of events) yield event;\n }\n // M2 #61 — a stream that ended without a terminal `message_delta`\n // (stop_reason) was truncated (dropped connection / proxy hiccup); throw a\n // typed error rather than commit the partial turn as a clean `end_turn`\n // (parity with the OpenAI client's truncation guard).\n if (!accumulator.finishReasonSeen) {\n throw new NetworkError(\"Anthropic SSE stream truncated (no stop_reason)\", {\n code: \"stream_truncated\",\n });\n }\n return accumulator.finish();\n }\n}\n\nclass AnthropicStreamAccumulator {\n private text = \"\";\n private stopReason: LlmStopReason = \"end_turn\";\n /**\n * M2 #61 — whether a `message_delta` carrying a real `stop_reason` was seen.\n * A stream that closes before it is a truncation (server FIN / proxy hiccup),\n * not a clean `end_turn` — the caller throws `stream_truncated` on `false`.\n */\n private sawStopReason = false;\n private inputTokens?: number;\n private outputTokens?: number;\n private cacheReadTokens?: number;\n private cacheWriteTokens?: number;\n private readonly toolCalls = new Map<number, LlmToolCallPart>();\n private readonly toolBuffers = new Map<number, string>();\n /**\n * theokit#122 — the turn's thinking block. Text accumulates across `thinking_delta`s; the\n * signature arrives once, on a `signature_delta` for the same block. Undefined until the model\n * actually opens a thinking block, so a non-thinking turn reports nothing.\n */\n private thinking: { text: string; signature?: string } | undefined;\n\n consume(event: AnthropicEvent): LlmEvent[] {\n if (event.type === \"content_block_start\") {\n const block = (event as AnthropicToolStart | AnthropicThinkingStart).content_block;\n if (block.type === \"thinking\") this.handleThinkingStart(event as AnthropicThinkingStart);\n else this.handleToolStart(event as AnthropicToolStart);\n return [];\n }\n if (event.type === \"content_block_delta\") {\n return this.handleContentDelta(event as AnthropicTextDelta | AnthropicToolDelta);\n }\n if (event.type === \"message_delta\") {\n this.handleMessageDelta(event as AnthropicMessageDelta);\n }\n return [];\n }\n\n private handleToolStart(start: AnthropicToolStart): void {\n if (start.content_block.type !== \"tool_use\") return;\n this.toolCalls.set(start.index, {\n type: \"tool_use\",\n id: start.content_block.id,\n name: start.content_block.name,\n input: { ...start.content_block.input },\n });\n this.toolBuffers.set(start.index, \"\");\n }\n\n private handleThinkingStart(start: AnthropicThinkingStart): void {\n // A thinking block can open carrying its opening text (and, on a replayed block, a signature).\n this.thinking = {\n text: start.content_block.thinking ?? \"\",\n ...(start.content_block.signature !== undefined\n ? { signature: start.content_block.signature }\n : {}),\n };\n }\n\n private handleContentDelta(\n delta:\n | AnthropicTextDelta\n | AnthropicToolDelta\n | AnthropicThinkingDelta\n | AnthropicSignatureDelta,\n ): LlmEvent[] {\n if (delta.delta.type === \"text_delta\") {\n const text = (delta as AnthropicTextDelta).delta.text;\n this.text += text;\n return [{ type: \"text_delta\", text }];\n }\n // theokit#122 — extended thinking streams on its own channel, surfaced as `reasoning_delta`\n // exactly like the OpenAI-compatible providers, so the loop needs no provider branch.\n if (delta.delta.type === \"thinking_delta\") {\n const text = (delta as AnthropicThinkingDelta).delta.thinking;\n this.thinking = {\n ...(this.thinking ?? { text: \"\" }),\n text: (this.thinking?.text ?? \"\") + text,\n };\n return [{ type: \"reasoning_delta\", text }];\n }\n // The signature closes the block. It carries no text, so it rides an empty reasoning delta —\n // the loop's accumulator keeps the last signature it sees for the turn.\n if (delta.delta.type === \"signature_delta\") {\n const signature = (delta as AnthropicSignatureDelta).delta.signature;\n this.thinking = { text: this.thinking?.text ?? \"\", signature };\n return [{ type: \"reasoning_delta\", text: \"\", signature }];\n }\n const idx = (delta as AnthropicToolDelta).index;\n const existing = this.toolBuffers.get(idx) ?? \"\";\n this.toolBuffers.set(idx, existing + (delta as AnthropicToolDelta).delta.partial_json);\n return [];\n }\n\n /**\n * T3.8 — extract token counters from Anthropic's `message_delta` usage.\n * Public on the class so the test seam can drive it directly without\n * spinning the SSE parser.\n */\n handleMessageDelta(md: AnthropicMessageDelta): void {\n if (md.delta.stop_reason !== undefined && md.delta.stop_reason !== null) {\n this.sawStopReason = true;\n }\n this.stopReason = mapAnthropicStopReason(md.delta.stop_reason);\n if (md.usage?.input_tokens !== undefined) this.inputTokens = md.usage.input_tokens;\n if (md.usage?.output_tokens !== undefined) this.outputTokens = md.usage.output_tokens;\n // T3.8 — treat 0 as \"no cache activity\" and leave the bucket\n // unreported (mirrors usage-accumulator's filter where zero-value\n // entries are stripped from the emitted TokenUsage).\n if (\n md.usage?.cache_creation_input_tokens !== undefined &&\n md.usage.cache_creation_input_tokens > 0\n ) {\n this.cacheWriteTokens = md.usage.cache_creation_input_tokens;\n }\n if (md.usage?.cache_read_input_tokens !== undefined && md.usage.cache_read_input_tokens > 0) {\n this.cacheReadTokens = md.usage.cache_read_input_tokens;\n }\n }\n\n /** M2 #61 — whether the terminal `message_delta` (stop_reason) was seen. */\n get finishReasonSeen(): boolean {\n return this.sawStopReason;\n }\n\n finish(): LlmFinish {\n const toolCalls: LlmToolCallPart[] = [];\n for (const [index, tool] of this.toolCalls.entries()) {\n const buffered = this.toolBuffers.get(index);\n const parsed = parseToolArguments(buffered);\n if (Object.keys(parsed).length > 0) tool.input = parsed;\n toolCalls.push(tool);\n }\n return makeLlmFinish({\n stopReason: this.stopReason,\n text: this.text,\n toolCalls,\n inputTokens: this.inputTokens,\n outputTokens: this.outputTokens,\n // T3.8 — surface Anthropic native cache-token counters when the\n // request used `cache_control: {type:\"ephemeral\"}` on system blocks.\n cacheReadTokens: this.cacheReadTokens,\n cacheWriteTokens: this.cacheWriteTokens,\n // theokit#122 — carry the thinking block + its signature so the turn can be replayed.\n ...(this.thinking !== undefined\n ? { thinking: { type: \"thinking\" as const, ...this.thinking } }\n : {}),\n });\n }\n}\n\n/**\n * T3.8 — test seam: exposes the AnthropicStreamAccumulator directly so\n * unit tests can drive the message_delta path without spinning the SSE\n * parser. `@internal` — not part of the public surface.\n */\nexport const __testing__AnthropicAccumulator = AnthropicStreamAccumulator;\n\nfunction buildAnthropicBody(request: LlmRequest): Record<string, unknown> {\n return {\n model: request.model,\n stream: true,\n ...buildAnthropicCommonBody(request),\n };\n}\n","/**\n * AWS Bedrock HTTP error mapper (ADRs D67, D300).\n *\n * Bedrock returns either AWS-style `{ message, __type: \"ThrottlingException\" }`\n * or sometimes `{ Message }` (capitalized) depending on the model dialect.\n * We accept both shapes and map to canonical `TheokitAgentError` subclasses.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../../errors.js\";\nimport { buildErrorMetadata } from \"./shared.js\";\n\ninterface BedrockErrorBody {\n __type?: string;\n message?: string;\n Message?: string;\n}\n\nexport interface MapBedrockErrorArgs {\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\ntype BedrockCode =\n | \"rate_limit\"\n | \"auth_failed\"\n | \"invalid_request\"\n | \"timeout\"\n | \"server_error\"\n | \"unknown\";\n\nfunction classifyBedrockError(\n args: MapBedrockErrorArgs,\n awsType: string,\n message: string,\n): BedrockCode {\n if (\n args.status === 429 ||\n awsType.includes(\"Throttling\") ||\n awsType.includes(\"TooManyRequests\")\n ) {\n return \"rate_limit\";\n }\n if (\n args.status === 401 ||\n args.status === 403 ||\n awsType.includes(\"AccessDenied\") ||\n awsType.includes(\"UnauthorizedOperation\")\n ) {\n return \"auth_failed\";\n }\n if (\n args.status === 400 ||\n args.status === 404 ||\n awsType.includes(\"ValidationException\") ||\n awsType.includes(\"ResourceNotFound\") ||\n message.includes(\"use case details\")\n ) {\n return \"invalid_request\";\n }\n if (args.status === 408 || awsType.includes(\"Timeout\")) return \"timeout\";\n if (args.status >= 500) return \"server_error\";\n return \"unknown\";\n}\n\nfunction buildBedrockMetadata(args: MapBedrockErrorArgs, code: BedrockCode) {\n return buildErrorMetadata({\n provider: \"bedrock\",\n endpoint: args.endpoint,\n code,\n status: args.status,\n headers: args.headers,\n body: args.body,\n });\n}\n\nexport function mapBedrockError(args: MapBedrockErrorArgs): TheokitAgentError {\n const parsed = parseBody(args.body);\n const awsType = parsed.__type ?? \"\";\n const message = parsed.message ?? parsed.Message ?? \"Bedrock request failed\";\n const code = classifyBedrockError(args, awsType, message);\n const metadata = buildBedrockMetadata(args, code);\n\n switch (code) {\n case \"rate_limit\":\n return new RateLimitError(`Bedrock throttled: ${message}`, { metadata });\n case \"auth_failed\":\n return new AuthenticationError(`Bedrock auth: ${message}`, { metadata });\n case \"invalid_request\": {\n const friendly = message.includes(\"use case details\")\n ? `Bedrock account setup required: ${message} (AWS Console → Bedrock → Model access → Anthropic → Submit use case form, then retry in 15 min.)`\n : `Bedrock validation: ${message}`;\n return new ConfigurationError(friendly, { metadata });\n }\n case \"timeout\":\n return new NetworkError(`Bedrock timeout: ${message}`, { metadata });\n case \"server_error\":\n return new NetworkError(`Bedrock server error: ${message}`, { metadata });\n default:\n return new UnknownAgentError(`Bedrock unknown: ${message}`, { metadata });\n }\n}\n\nfunction parseBody(body: unknown): BedrockErrorBody {\n if (body !== null && typeof body === \"object\") return body as BedrockErrorBody;\n if (typeof body === \"string\") {\n try {\n return JSON.parse(body) as BedrockErrorBody;\n } catch {\n return {};\n }\n }\n return {};\n}\n","/**\n * Bedrock Bearer token resolution + cache (ADRs D287, D295).\n *\n * Two paths:\n * 1. Explicit env (`AWS_BEARER_TOKEN_BEDROCK`) wins; no refresh.\n * 2. Optional peer dep `@aws/bedrock-token-generator` (D287) auto-generates\n * short-term tokens from the standard AWS credential chain\n * (`@aws-sdk/credential-providers`). Cached for 1.5h.\n *\n * `resolveBedrockToken` returns `undefined` only when BOTH paths produce no\n * token. Caller (router) is responsible for throwing a helpful error\n * (D279/EC-6) — this module is auth-resolution only.\n *\n * @internal\n */\n\nimport { createRequire } from \"node:module\";\n\ninterface CachedToken {\n value: string;\n expiresAt: number;\n}\n\nlet cachedToken: CachedToken | null = null;\n\ninterface BedrockTokenGeneratorApi {\n getToken: (opts: { credentials: unknown; region: string }) => Promise<string>;\n}\n\ninterface CredentialProvidersApi {\n fromNodeProviderChain: () => () => Promise<unknown>;\n}\n\nconst CACHE_TTL_MS = 90 * 60 * 1000; // 1.5h\n\nexport async function resolveBedrockToken(region: string): Promise<string | undefined> {\n const env = process.env.AWS_BEARER_TOKEN_BEDROCK;\n if (env !== undefined && env.length > 0) return env;\n\n const now = Date.now();\n if (cachedToken !== null && cachedToken.expiresAt > now) {\n return cachedToken.value;\n }\n\n try {\n const r = createRequire(import.meta.url);\n const gen = r(\"@aws/bedrock-token-generator\") as BedrockTokenGeneratorApi;\n if (typeof gen.getToken !== \"function\") return undefined;\n\n const providers = r(\"@aws-sdk/credential-providers\") as CredentialProvidersApi;\n if (typeof providers.fromNodeProviderChain !== \"function\") return undefined;\n\n const credentialProvider = providers.fromNodeProviderChain();\n const token = await gen.getToken({ credentials: credentialProvider, region });\n cachedToken = { value: token, expiresAt: now + CACHE_TTL_MS };\n return token;\n } catch {\n return undefined;\n }\n}\n\n/** Test seam — clear cache between tests. */\nexport function __resetBedrockTokenCache(): void {\n cachedToken = null;\n}\n","/**\n * AWS Bedrock client for Anthropic Messages (Adoption Roadmap #8; ADRs\n * D286-D302).\n *\n * v1: non-streaming only (`POST /model/{id}/invoke`). D302 defers\n * `/invoke-with-response-stream` (AWS Event Stream binary format) to v1.x.\n *\n * Body massage (D289):\n * - inject `anthropic_version: \"bedrock-2023-05-31\"`\n * - strip `model` from body (goes in URL)\n * - strip `stream` from body (D302 — non-streaming only in v1)\n *\n * Uses native `fetch` only — no `@aws-sdk/client-bedrock-runtime`.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { mapBedrockError } from \"../error-mappers/bedrock.js\";\nimport {\n inferRegionFromModelId,\n resolveBedrockBaseUrl,\n stripBedrockPrefix,\n} from \"../providers/builtin/bedrock.js\";\nimport {\n buildAnthropicCommonBody,\n handleAnthropicResponse,\n postAnthropicRequest,\n} from \"./anthropic-shared.js\";\nimport { resolveBedrockToken } from \"./bedrock-token-cache.js\";\nimport { makeLlmFinish } from \"./finish.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\n\nexport interface BedrockAnthropicClientOptions {\n /**\n * AWS Bearer token. When non-empty, used as-is. When empty/undefined,\n * resolved lazily per request via `resolveBedrockToken(region)` (D287).\n */\n apiKey?: string;\n /** Override the resolved baseUrl (rarely needed; defaults derive from model id). */\n baseUrl?: string;\n /** Injected fetch impl for tests. */\n fetch?: typeof fetch;\n}\n\nexport class BedrockAnthropicClient implements LlmClient {\n readonly name = \"bedrock\";\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: BedrockAnthropicClientOptions) {\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n private async resolveTokenOrThrow(region: string): Promise<string> {\n const fromOpts = this.options.apiKey;\n if (fromOpts !== undefined && fromOpts.length > 0) return fromOpts;\n const fromEnv = await resolveBedrockToken(region);\n if (fromEnv !== undefined && fromEnv.length > 0) return fromEnv;\n throw new ConfigurationError(\n \"Bedrock requires AWS_BEARER_TOKEN_BEDROCK env var, or install `@aws/bedrock-token-generator` for auto-refresh, or pass apiKey explicitly.\",\n { code: \"auth_failed\" },\n );\n }\n\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n const region = inferRegionFromModelId(request.model) ?? process.env.AWS_REGION ?? \"us-east-1\";\n const token = await this.resolveTokenOrThrow(region);\n\n const bareModel = stripBedrockPrefix(request.model);\n const baseUrl = this.options.baseUrl ?? resolveBedrockBaseUrl(request.model);\n const endpoint = `/model/${encodeURIComponent(bareModel)}/invoke`;\n const url = `${baseUrl}${endpoint}`;\n\n const response = await postAnthropicRequest({\n fetchImpl: this.fetchImpl,\n url,\n token,\n body: buildBedrockBody(request),\n signal,\n });\n\n const consumed = await handleAnthropicResponse({\n response,\n endpoint,\n errorMapper: mapBedrockError,\n });\n if (consumed.text.length > 0) yield { type: \"text_delta\", text: consumed.text };\n return makeLlmFinish(consumed);\n }\n}\n\nfunction buildBedrockBody(request: LlmRequest): Record<string, unknown> {\n // D289: anthropic_version injected; model + stream stripped.\n return {\n anthropic_version: \"bedrock-2023-05-31\",\n ...buildAnthropicCommonBody(request),\n };\n}\n","/**\n * D14 — Fault injection via `THEOKIT_TEST_RESPONSE_OVERRIDE` env var.\n *\n * Decorator pattern (D127 inspired): wraps any `LlmClient` and short-circuits\n * the network call when:\n *\n * 1. `process.env.NODE_ENV === \"test\"` (fail-safe gate — prevents production\n * footgun), AND\n * 2. `process.env.THEOKIT_TEST_RESPONSE_OVERRIDE` is a non-empty JSON string\n * shaped as `{ \"status\": number, \"body\": object | string }`.\n *\n * On any other condition (different NODE_ENV, missing env, malformed JSON),\n * the wrapper delegates to the real client — graceful degradation.\n *\n * Use cases (FAANG-grade chaos testing):\n *\n * - `{\"status\":429,\"body\":{\"error\":{\"code\":\"rate_limit_exceeded\"}}}` →\n * deterministic RateLimitError without burning real quota\n * - `{\"status\":500,\"body\":{\"error\":{\"code\":\"internal_error\"}}}` →\n * deterministic NetworkError for retry/circuit-breaker tests\n * - `{\"status\":200,\"body\":{\"choices\":[{\"message\":{\"content\":\"fake\"}}]}}` →\n * deterministic happy-path text for snapshot tests\n *\n * Compatible with the dogfood-stranger chaos phases (12-15). Replaces the\n * flaky \"50 parallel requests to force 429\" anti-pattern.\n *\n * Wire format mirrors OpenAI Chat Completions (universal — same shape every\n * provider returns). Error mapping reuses `mapOpenAICompatibleError` so the\n * injected errors are byte-equal to what the real provider would raise.\n *\n * @internal\n */\n\nimport { diag } from \"../diagnostics.js\";\nimport { mapOpenAICompatibleError } from \"../error-mappers/openai-compatible.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\n\nconst ENV_GATE_KEY = \"NODE_ENV\";\nconst ENV_GATE_VALUE = \"test\";\nconst ENV_OVERRIDE_KEY = \"THEOKIT_TEST_RESPONSE_OVERRIDE\";\n\ninterface ParsedOverride {\n status: number;\n body: unknown;\n}\n\n/**\n * Wrap an `LlmClient` with the fault-injection decorator. Returns the\n * original client unchanged when the activation gate is not satisfied\n * (cheap noop — no allocation in the hot path of production runtime).\n */\nexport function maybeWrapWithFaultInjection(client: LlmClient): LlmClient {\n // Cheap gate first — production calls never allocate the wrapper.\n if (!isGateOn()) return client;\n return new FaultInjectingLlmClient(client);\n}\n\nexport class FaultInjectingLlmClient implements LlmClient {\n readonly name: string;\n /**\n * Inner (real) client. Exposed so layered transport assertions (router\n * pool-wiring tests, telemetry inspectors) can walk one level deep —\n * same pattern PoolAwareLlmClient uses for its inner transport.\n */\n readonly inner: LlmClient;\n constructor(inner: LlmClient) {\n this.inner = inner;\n this.name = inner.name;\n }\n\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n // Re-check gate on every call — env vars can change between calls and\n // the cost is negligible relative to a network roundtrip.\n if (!isGateOn()) {\n return yield* this.inner.stream(request, signal);\n }\n const parsed = parseOverrideOrWarnOnce();\n if (parsed === undefined) {\n return yield* this.inner.stream(request, signal);\n }\n // Active: synthesize response without calling the real client.\n if (parsed.status >= 400) {\n throw mapOpenAICompatibleError({\n providerId: this.name,\n status: parsed.status,\n body: parsed.body,\n headers: undefined,\n endpoint: \"/v1/chat/completions\",\n });\n }\n const text = extractText(parsed.body);\n yield { type: \"text_delta\", text };\n // theokit#144: no `stop` event — the reason travels on the finish value below.\n return {\n stopReason: \"end_turn\",\n text,\n toolCalls: [],\n inputTokens: 0,\n outputTokens: 0,\n };\n }\n}\n\nfunction isGateOn(): boolean {\n return process.env[ENV_GATE_KEY] === ENV_GATE_VALUE;\n}\n\nlet warnedInvalidJson = false;\n\nfunction parseOverrideOrWarnOnce(): ParsedOverride | undefined {\n const raw = process.env[ENV_OVERRIDE_KEY];\n if (raw === undefined || raw.length === 0) return undefined;\n let candidate: unknown;\n try {\n candidate = JSON.parse(raw);\n } catch (_err) {\n warnInvalidJsonOnce(raw);\n return undefined;\n }\n if (candidate === null || typeof candidate !== \"object\") {\n warnInvalidJsonOnce(raw);\n return undefined;\n }\n const obj = candidate as { status?: unknown; body?: unknown };\n if (typeof obj.status !== \"number\" || !Number.isFinite(obj.status)) {\n warnInvalidJsonOnce(raw);\n return undefined;\n }\n return { status: obj.status, body: obj.body };\n}\n\nfunction warnInvalidJsonOnce(_raw: string): void {\n if (warnedInvalidJson) return;\n warnedInvalidJson = true;\n diag(\n `[theokit-sdk] ${ENV_OVERRIDE_KEY} is set but value is not valid JSON of shape ` +\n `\\`{\"status\": number, \"body\": object | string}\\`. Falling back to real LLM call. ` +\n `This warning is shown once per process.\\n`,\n );\n}\n\n/**\n * Extract textual content from an arbitrary body. Supports:\n * - plain string: returned as-is\n * - OpenAI shape: `body.choices[0].message.content` (most common)\n * - object with `text` field: `body.text`\n * - everything else: empty string (caller can still inspect parsed.body if needed)\n */\nfunction extractText(body: unknown): string {\n if (typeof body === \"string\") return body;\n if (body === null || typeof body !== \"object\") return \"\";\n const fromOpenAi = readOpenAiContent(body);\n if (fromOpenAi !== undefined) return fromOpenAi;\n const obj = body as { text?: unknown };\n if (typeof obj.text === \"string\") return obj.text;\n return \"\";\n}\n\nfunction readOpenAiContent(body: unknown): string | undefined {\n const obj = body as { choices?: unknown };\n if (!Array.isArray(obj.choices) || obj.choices.length === 0) return undefined;\n const first = obj.choices[0] as { message?: { content?: unknown } } | undefined;\n const content = first?.message?.content;\n if (typeof content === \"string\") return content;\n return undefined;\n}\n\n/**\n * Test-only reset for the one-shot stderr warning. Mirrors the D187\n * `_resetNoAuthApiKeyWarnings` pattern.\n *\n * @internal\n */\nexport function _resetFaultInjectionWarnings(): void {\n warnedInvalidJson = false;\n}\n","/**\n * Ollama-specific HTTP/transport error mapper (T1.1, ADR D185).\n *\n * Sits ABOVE the generic OpenAI-compatible mapper for `providerId: \"ollama\"`.\n * Returns `undefined` when the error doesn't match an Ollama-specific\n * pattern — caller (OpenAIClient) then falls back to the generic mapper.\n *\n * Surfaces 3 Ollama-specific failure modes with actionable messages\n * targeted at non-technical users (CLAUDE.md primary persona):\n *\n * 1. **Transport-level `ECONNREFUSED` / `ENOTFOUND`** → \"Run `ollama serve`\"\n * 2. **HTTP 404 with `not found, try pulling`** → \"Run `ollama pull <model>`\"\n * 3. **HTTP 503 with `model is loading`** → retryable (model warming up)\n *\n * @internal\n */\n\nimport { ConfigurationError, NetworkError, type TheokitAgentError } from \"../../errors.js\";\nimport { buildErrorMetadata } from \"./shared.js\";\n\ninterface MapOllamaTransportArgs {\n providerId: string;\n cause: unknown;\n endpoint: string;\n}\n\ninterface MapOllamaHttpArgs {\n providerId: string;\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\n/**\n * Maps fetch-level failures (Node TypeError with `cause.code`). Returns\n * `undefined` for anything that isn't `ECONNREFUSED` / `ENOTFOUND` so\n * the caller can re-throw the original error untouched.\n */\nexport function mapOllamaTransportError(\n args: MapOllamaTransportArgs,\n): TheokitAgentError | undefined {\n if (args.providerId !== \"ollama\") return undefined;\n const causeCode = extractCauseCode(args.cause);\n if (causeCode !== \"ECONNREFUSED\" && causeCode !== \"ENOTFOUND\") return undefined;\n\n const metadata = buildErrorMetadata({\n provider: \"ollama\",\n endpoint: args.endpoint,\n code: \"network\",\n status: 0,\n headers: undefined,\n body: { cause: causeCode },\n });\n return new ConfigurationError(\n \"Ollama is not reachable. Run `ollama serve` to start the local runtime, \" +\n \"or set OLLAMA_HOST to point at a remote Ollama server.\",\n { code: \"ollama_unreachable\", metadata },\n );\n}\n\n/**\n * Maps HTTP-level Ollama failures. Returns `undefined` for status codes\n * that aren't Ollama-specific so the caller falls back to the generic\n * OpenAI-compatible mapper.\n */\nexport function mapOllamaHttpError(args: MapOllamaHttpArgs): TheokitAgentError | undefined {\n if (args.providerId !== \"ollama\") return undefined;\n\n const errString = extractErrorString(args.body).toLowerCase();\n\n // 404 + \"not found, try pulling\" → model not pulled.\n if (args.status === 404 && errString.includes(\"not found\") && errString.includes(\"pull\")) {\n const modelHint = extractModelName(errString);\n const metadata = buildErrorMetadata({\n provider: \"ollama\",\n endpoint: args.endpoint,\n code: \"model_unavailable\",\n status: args.status,\n headers: args.headers,\n body: args.body,\n });\n const pullCmd = modelHint !== undefined ? `ollama pull ${modelHint}` : \"ollama pull <model>\";\n return new ConfigurationError(\n `Ollama model is not pulled. Run \\`${pullCmd}\\` to download it first.`,\n { code: \"ollama_model_not_pulled\", metadata },\n );\n }\n\n // 503 + \"model is loading\" → retryable transient.\n if (args.status === 503 && errString.includes(\"model is loading\")) {\n const metadata = buildErrorMetadata({\n provider: \"ollama\",\n endpoint: args.endpoint,\n code: \"server_error\",\n status: args.status,\n headers: args.headers,\n body: args.body,\n });\n // NetworkError isRetryable: true (default per errors.ts contract).\n return new NetworkError(\n \"Ollama model is loading. Retry in a few seconds — Ollama is warming up the model into memory.\",\n { code: \"ollama_model_loading\", metadata },\n );\n }\n\n return undefined;\n}\n\nfunction extractCauseCode(cause: unknown): string | undefined {\n if (cause === null || typeof cause !== \"object\") return undefined;\n // Native fetch wraps in TypeError(\"fetch failed\") with `cause` chain.\n const directCode = (cause as { code?: unknown }).code;\n if (typeof directCode === \"string\") return directCode;\n const nested = (cause as { cause?: unknown }).cause;\n if (nested !== undefined) return extractCauseCode(nested);\n return undefined;\n}\n\nfunction extractErrorString(body: unknown): string {\n if (typeof body === \"string\") return body;\n if (body === null || typeof body !== \"object\") return \"\";\n const err = (body as { error?: unknown }).error;\n if (typeof err === \"string\") return err;\n return \"\";\n}\n\n/** Pull the model name out of e.g. `model 'llama3.2' not found, try pulling it first`. */\nfunction extractModelName(errString: string): string | undefined {\n const match = errString.match(/'([^']+)'/);\n return match?.[1];\n}\n","/**\n * Ollama native API client (T8.1 follow-up, ADR D191).\n *\n * Targets Ollama's native `/api/chat` endpoint with NDJSON streaming.\n * Critical for **tool calling** — per peer-project upstream warning, the\n * OpenAI-compat `/v1/chat/completions` endpoint BREAKS tool calling in\n * Ollama (models emit raw tool JSON as text instead of structured\n * `tool_calls` blocks). Mirrors peer-project `extensions/ollama/src/stream.ts`.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { mapOllamaHttpError, mapOllamaTransportError } from \"../error-mappers/ollama.js\";\nimport { collapseSystemText, makeLlmFinish } from \"./finish.js\";\nimport { toStringToolResultContent } from \"./tool-result-content.js\";\nimport type {\n LlmClient,\n LlmEvent,\n LlmFinish,\n LlmMessage,\n LlmRequest,\n LlmStopReason,\n LlmToolCallPart,\n} from \"./types.js\";\n\nexport interface OllamaNativeClientOptions {\n /** Optional API key for Ollama Cloud / reverse-proxy. Local Ollama ignores `Authorization`. */\n apiKey?: string;\n /** Base URL. Default `http://localhost:11434`. `/v1` suffix is stripped automatically. */\n baseUrl?: string;\n fetch?: typeof fetch;\n}\n\ninterface OllamaToolCall {\n function: {\n name: string;\n arguments: Record<string, unknown> | string;\n };\n}\n\ninterface OllamaChatChunk {\n message?: {\n role?: \"assistant\";\n content?: string;\n tool_calls?: OllamaToolCall[];\n };\n done?: boolean;\n done_reason?: string;\n prompt_eval_count?: number;\n eval_count?: number;\n}\n\ninterface OllamaChatMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string;\n tool_calls?: OllamaToolCall[];\n tool_name?: string;\n}\n\ninterface OllamaTool {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n}\n\nexport class OllamaNativeClient implements LlmClient {\n readonly name = \"ollama\";\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: OllamaNativeClientOptions) {\n // Strip `/v1` if user mistakenly included it (peer-project guard).\n const raw = (options.baseUrl ?? \"http://localhost:11434\").replace(/\\/+$/, \"\");\n this.baseUrl = raw.replace(/\\/v1$/i, \"\");\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: HTTP+NDJSON handshake + accumulator is intentionally one block (mirrors openai.ts)\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n const headers: Record<string, string> = { \"content-type\": \"application/json\" };\n if (this.options.apiKey !== undefined && this.options.apiKey.length > 0) {\n headers.authorization = `Bearer ${this.options.apiKey}`;\n }\n const body = buildOllamaChatBody(request);\n const url = `${this.baseUrl}/api/chat`;\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method: \"POST\",\n signal,\n headers,\n body: JSON.stringify(body),\n });\n } catch (fetchErr) {\n const mapped = mapOllamaTransportError({\n providerId: \"ollama\",\n cause: fetchErr,\n endpoint: \"/api/chat\",\n });\n if (mapped !== undefined) throw mapped;\n throw fetchErr;\n }\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n let bodyJson: unknown = text;\n try {\n bodyJson = JSON.parse(text);\n } catch {\n /* not JSON */\n }\n const mapped = mapOllamaHttpError({\n providerId: \"ollama\",\n status: response.status,\n body: bodyJson,\n headers: response.headers,\n endpoint: \"/api/chat\",\n });\n if (mapped !== undefined) throw mapped;\n throw new Error(`Ollama /api/chat HTTP ${response.status}: ${text.slice(0, 200)}`);\n }\n\n const accumulator = new OllamaStreamAccumulator();\n if (response.body === null) {\n return accumulator.finish();\n }\n for await (const chunk of parseNdjsonStream(response.body, signal)) {\n const events = accumulator.consume(chunk);\n for (const event of events) yield event;\n if (chunk.done === true) break;\n }\n return accumulator.finish();\n }\n}\n\nclass OllamaStreamAccumulator {\n private text = \"\";\n private stopReason: LlmStopReason = \"end_turn\";\n private inputTokens?: number;\n private outputTokens?: number;\n private readonly toolCalls: LlmToolCallPart[] = [];\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: NDJSON chunk dispatch — text delta + tool_call append + finish-reason mapping is one cohesive accumulator (mirrors openai.ts OpenAIStreamAccumulator.consume).\n consume(chunk: OllamaChatChunk): LlmEvent[] {\n const events: LlmEvent[] = [];\n if (chunk.prompt_eval_count !== undefined) this.inputTokens = chunk.prompt_eval_count;\n if (chunk.eval_count !== undefined) this.outputTokens = chunk.eval_count;\n const msg = chunk.message;\n if (msg?.content !== undefined && msg.content.length > 0) {\n this.text += msg.content;\n events.push({ type: \"text_delta\", text: msg.content });\n }\n if (msg?.tool_calls !== undefined) {\n for (const call of msg.tool_calls) {\n const input =\n typeof call.function.arguments === \"string\"\n ? parseOllamaToolArguments(call.function.arguments)\n : call.function.arguments;\n this.toolCalls.push({\n type: \"tool_use\",\n id: `ollama_call_${this.toolCalls.length + 1}`,\n name: call.function.name,\n input,\n });\n }\n }\n if (chunk.done === true && chunk.done_reason !== undefined) {\n this.stopReason = mapOllamaDoneReason(chunk.done_reason, this.toolCalls.length > 0);\n }\n return events;\n }\n\n finish(): LlmFinish {\n if (this.toolCalls.length > 0 && this.stopReason === \"end_turn\") {\n this.stopReason = \"tool_use\";\n }\n return makeLlmFinish({\n stopReason: this.stopReason,\n text: this.text,\n toolCalls: this.toolCalls,\n inputTokens: this.inputTokens,\n outputTokens: this.outputTokens,\n });\n }\n}\n\nfunction parseOllamaToolArguments(raw: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(raw);\n return typeof parsed === \"object\" && parsed !== null ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\nfunction mapOllamaDoneReason(reason: string, hasToolCalls: boolean): LlmStopReason {\n if (hasToolCalls) return \"tool_use\";\n if (reason === \"length\") return \"max_tokens\";\n if (reason === \"stop\") return \"end_turn\";\n return \"end_turn\";\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: NDJSON line buffering + JSON.parse-with-skip-malformed + signal abort + trailing-buffer flush is one cohesive parser, mirrors peer-project's parseJsonLineStream.\nasync function* parseNdjsonStream(\n body: ReadableStream<Uint8Array>,\n signal: AbortSignal,\n): AsyncGenerator<OllamaChatChunk, void, void> {\n const reader = body.getReader();\n const decoder = new TextDecoder(\"utf-8\");\n let buffer = \"\";\n try {\n while (true) {\n if (signal.aborted) return;\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length === 0) continue;\n try {\n yield JSON.parse(trimmed) as OllamaChatChunk;\n } catch {\n /* skip malformed NDJSON line */\n }\n }\n }\n const tail = buffer.trim();\n if (tail.length > 0) {\n try {\n yield JSON.parse(tail) as OllamaChatChunk;\n } catch {\n /* ignore */\n }\n }\n } finally {\n // T3.2 + T3.3 — mirror sse.ts: cancel the underlying body stream on\n // every exit path (abort, normal close, consumer break, consumer\n // throw). Without this the upstream Ollama HTTP TCP socket stays in\n // CLOSE_WAIT until the OS times it out. cancel() on a finished stream\n // is a no-op so always-cancel is safe.\n try {\n await reader.cancel();\n } catch {\n // best-effort — already cancelled OR upstream closed\n }\n reader.releaseLock();\n }\n}\n\n/**\n * T3.5 — collapse the wider `LlmRequest.system` shape into the legacy\n * single-string form Ollama expects.\n *\n * @internal\n */\nconst ollamaSystemText = collapseSystemText;\n\nfunction buildOllamaChatBody(request: LlmRequest): Record<string, unknown> {\n const messages: OllamaChatMessage[] = [];\n const systemText = ollamaSystemText(request.system);\n if (systemText.length > 0) {\n messages.push({ role: \"system\", content: systemText });\n }\n for (const message of request.messages) {\n for (const out of toOllamaMessages(message)) messages.push(out);\n }\n const tools = toOllamaTools(request.tools);\n const body: Record<string, unknown> = {\n model: request.model,\n stream: true,\n messages,\n // ADR D192: 24h keep_alive prevents Ollama from evicting the chat model\n // when other models (embeddings, judges) are loaded between turns.\n // Cuts cold-load latency from 20-30s to single-digit ms per turn.\n keep_alive: process.env.OLLAMA_KEEP_ALIVE ?? \"24h\",\n };\n if (tools.length > 0) body.tools = tools;\n const opts: Record<string, unknown> = {};\n if (request.maxTokens !== undefined) opts.num_predict = request.maxTokens;\n if (request.temperature !== undefined) opts.temperature = request.temperature;\n if (Object.keys(opts).length > 0) body.options = opts;\n return body;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: 3-role transformation (system/user/assistant) with tool_result→tool role demotion + tool_use→tool_calls promotion is one cohesive mapper; splitting hurts readability.\nfunction toOllamaMessages(message: LlmMessage): OllamaChatMessage[] {\n if (message.role === \"system\") {\n return [{ role: \"system\", content: joinTextParts(message) }];\n }\n if (message.role === \"user\") {\n // M35 — the ollama-native wire has no image content channel here. Fail fast rather than silently\n // dropping an attached image (error-handling.md: no silent drop); OpenAI/OpenRouter carries images.\n if (message.content.some((p) => p.type === \"image\")) {\n throw new ConfigurationError(\n \"image input is not supported on the ollama-native provider; use an OpenAI/OpenRouter model for multimodal turns\",\n { code: \"ollama_image_unsupported\" },\n );\n }\n const out: OllamaChatMessage[] = [];\n for (const part of message.content) {\n if (part.type === \"tool_result\") {\n out.push({\n role: \"tool\",\n // SE7 — string-only tool role: text blocks flatten; image fails fast.\n content: toStringToolResultContent(part.content, \"ollama\"),\n tool_name: part.toolUseId,\n });\n }\n }\n const userText = joinTextParts(message);\n if (userText.length > 0) out.push({ role: \"user\", content: userText });\n return out;\n }\n // assistant\n const text = joinTextParts(message);\n const toolCalls: OllamaToolCall[] = [];\n for (const part of message.content) {\n if (part.type === \"tool_use\") {\n toolCalls.push({\n function: { name: part.name, arguments: part.input },\n });\n }\n }\n const msg: OllamaChatMessage = { role: \"assistant\", content: text };\n if (toolCalls.length > 0) msg.tool_calls = toolCalls;\n return [msg];\n}\n\nfunction joinTextParts(message: LlmMessage): string {\n return message.content\n .filter((p) => p.type === \"text\")\n .map((p) => (p as { text: string }).text)\n .join(\"\\n\");\n}\n\nfunction toOllamaTools(tools: LlmRequest[\"tools\"]): OllamaTool[] {\n if (tools === undefined || tools.length === 0) return [];\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n }));\n}\n","/**\n * Fixture-mode detection.\n *\n * When `THEOKIT_API_BASE_URL` is NOT set and the API key matches the\n * `theo_test_*` pattern, the SDK runs in fixture mode — it returns\n * deterministic, baked-in responses that match the golden fixtures under\n * `tests/golden/`. This is documented behavior and part of the contract\n * (analogous to Stripe's test keys), NOT a test-side mock.\n *\n * When `THEOKIT_API_BASE_URL` is set (e.g. pointing at a test HTTP server\n * or a real Theo PaaS instance), the SDK always performs real HTTP\n * requests — fixture mode is short-circuited.\n *\n * @internal\n */\n\nimport { existsSync } from \"node:fs\";\n\nconst FIXTURE_API_KEY_PREFIX = \"theo_test_\";\n\n/**\n * Returns `true` when the given API key is a fixture-mode key.\n *\n * @internal\n */\nexport function isFixtureApiKey(apiKey: string | undefined): boolean {\n if (apiKey === undefined) return false;\n return apiKey.startsWith(FIXTURE_API_KEY_PREFIX);\n}\n\n/**\n * Returns the base URL configured via `THEOKIT_API_BASE_URL`, or `undefined`\n * when not set.\n *\n * @internal\n */\nexport function getConfiguredBaseUrl(): string | undefined {\n const value = process.env.THEOKIT_API_BASE_URL;\n if (value === undefined || value.length === 0) return undefined;\n return value;\n}\n\n/**\n * Returns `true` when the SDK should respond from baked-in fixture data\n * instead of performing a real HTTP request.\n *\n * Rule: fixture mode is on iff (no explicit base URL configured) AND\n * (API key matches the fixture-key pattern).\n *\n * @internal\n */\nexport function shouldUseFixtureMode(apiKey: string | undefined): boolean {\n if (getConfiguredBaseUrl() !== undefined) return false;\n return isFixtureApiKey(apiKey);\n}\n\n/**\n * Returns `true` when the local runtime should drive the real LLM agent\n * loop instead of the deterministic fixture responder. Real mode requires\n * a non-fixture API key AND at least one provider env credential.\n *\n * @internal\n */\nexport function shouldUseRealLocalRuntime(apiKey: string | undefined): boolean {\n if (isFixtureApiKey(apiKey)) return false;\n if (apiKey === undefined || apiKey.length === 0) return false;\n // ADR D182 / T1.2: `authType: \"none\"` providers (Ollama, LM Studio,\n // llama.cpp) do not require any provider env var. Treat their presence\n // — signaled via OLLAMA_HOST/LMSTUDIO_HOST/LLAMACPP_HOST OR the\n // implicit-localhost default — as a green-light for real runtime.\n // For zero-config Ollama, we accept the default `http://localhost:11434`\n // unconditionally; the actual call will surface a typed\n // `ollama_unreachable` if Ollama is not running.\n return (\n (typeof process.env.ANTHROPIC_API_KEY === \"string\" &&\n process.env.ANTHROPIC_API_KEY.length > 0) ||\n (typeof process.env.OPENAI_API_KEY === \"string\" && process.env.OPENAI_API_KEY.length > 0) ||\n (typeof process.env.OPENROUTER_API_KEY === \"string\" &&\n process.env.OPENROUTER_API_KEY.length > 0) ||\n isAwsBedrockAuthAvailable() ||\n isGcpVertexAuthAvailable() ||\n isLocalNoAuthProviderAvailable()\n );\n}\n\n/**\n * ADRs D286-D287: Bedrock green-lights real runtime when EITHER\n * `AWS_BEARER_TOKEN_BEDROCK` is set explicitly OR the standard AWS\n * credential chain (`AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY` /\n * `AWS_PROFILE` / instance role) can mint a Bearer via\n * `@aws/bedrock-token-generator`. We only check synchronous signals here;\n * the actual token resolution happens lazily in\n * `BedrockAnthropicClient.stream`.\n */\nfunction isAwsBedrockAuthAvailable(): boolean {\n if (\n typeof process.env.AWS_BEARER_TOKEN_BEDROCK === \"string\" &&\n process.env.AWS_BEARER_TOKEN_BEDROCK.length > 0\n ) {\n return true;\n }\n if (\n typeof process.env.AWS_ACCESS_KEY_ID === \"string\" &&\n process.env.AWS_ACCESS_KEY_ID.length > 0\n ) {\n return true;\n }\n if (typeof process.env.AWS_PROFILE === \"string\" && process.env.AWS_PROFILE.length > 0) {\n return true;\n }\n // Default profile file (~/.aws/credentials). The credential chain will\n // resolve it via fromNodeProviderChain() at stream time, or surface a\n // helpful error if neither file nor IMDS is reachable.\n return awsCredentialsFileExists();\n}\n\nfunction awsCredentialsFileExists(): boolean {\n try {\n const home = process.env.HOME ?? process.env.USERPROFILE;\n if (home === undefined || home.length === 0) return false;\n return existsSync(`${home}/.aws/credentials`) || existsSync(`${home}/.aws/config`);\n } catch {\n return false;\n }\n}\n\n/**\n * ADR D288: Vertex green-lights real runtime when EITHER\n * `GOOGLE_APPLICATION_CREDENTIALS` is set OR `GOOGLE_CLOUD_PROJECT` is set\n * (ADC will use gcloud user creds / metadata server). The actual token\n * resolution happens lazily in `VertexAnthropicClient.stream` /\n * `VertexGeminiClient.stream`.\n */\nfunction isGcpVertexAuthAvailable(): boolean {\n if (\n typeof process.env.GOOGLE_APPLICATION_CREDENTIALS === \"string\" &&\n process.env.GOOGLE_APPLICATION_CREDENTIALS.length > 0\n ) {\n return true;\n }\n if (\n typeof process.env.GOOGLE_CLOUD_PROJECT === \"string\" &&\n process.env.GOOGLE_CLOUD_PROJECT.length > 0\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * ADR D182 / T1.2: zero-config local providers (`authType: \"none\"`) are\n * always available — Ollama defaults to localhost:11434, LM Studio to\n * localhost:1234, llama.cpp to localhost:8080. We don't probe here\n * (would require async); we return `true` when ANY of the documented\n * local hosts is reachable in spirit. The first real LLM call surfaces\n * `ollama_unreachable` via the typed mapper if no daemon is up.\n */\nfunction isLocalNoAuthProviderAvailable(): boolean {\n // Always true — the SDK ships Ollama as a builtin. Caller will see a\n // typed error if it isn't actually running.\n return true;\n}\n","import {\n AuthenticationError,\n ConfigurationError,\n IntegrationNotConnectedError,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../errors.js\";\nimport { getConfiguredBaseUrl } from \"./runtime/fixtures/fixture-mode.js\";\n\n/**\n * Default base URL used when neither `THEOKIT_API_BASE_URL` nor an explicit\n * override is provided. The fixture-mode short-circuit normally bypasses this\n * for `theo_test_*` keys; consumers with real keys hit this URL.\n *\n * @internal\n */\nexport const DEFAULT_BASE_URL = \"https://api.usetheo.dev\";\n\n/**\n * HTTP request options accepted by {@link httpRequest}.\n *\n * @internal\n */\nexport interface HttpRequestOptions {\n apiKey: string;\n method?: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n body?: unknown;\n /** Override the default `fetch` (useful for tests / instrumentation). */\n fetchFn?: typeof globalThis.fetch;\n /** Extra headers merged into the default set. */\n headers?: Record<string, string>;\n}\n\n/**\n * Server-side error envelope (`{ error: { code, message, ... } }` or a flat\n * shape) parsed off non-2xx responses.\n *\n * @internal\n */\ninterface ErrorEnvelope {\n code?: string;\n message?: string;\n protoErrorCode?: string;\n provider?: string;\n helpUrl?: string;\n}\n\n/**\n * Resolve the effective base URL (explicit env > default).\n *\n * @internal\n */\nexport function resolveBaseUrl(): string {\n return getConfiguredBaseUrl() ?? DEFAULT_BASE_URL;\n}\n\n/**\n * Perform an authenticated JSON HTTP request, mapping non-2xx responses to\n * the public typed-error hierarchy. Throws subclasses of `TheokitAgentError`\n * on failure.\n *\n * @internal\n */\nexport async function httpRequest<T>(path: string, options: HttpRequestOptions): Promise<T> {\n const url = `${resolveBaseUrl()}${path}`;\n const fetchFn = options.fetchFn ?? globalThis.fetch;\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${options.apiKey}`,\n ...(options.headers ?? {}),\n };\n const body = options.body !== undefined ? JSON.stringify(options.body) : undefined;\n\n const response = await safeFetch(fetchFn, url, {\n method: options.method ?? \"GET\",\n headers,\n body,\n });\n\n if (!response.ok) {\n const parsed = await safeParseJsonResponse(response);\n throw mapHttpStatusToError(response.status, parsed);\n }\n\n return (await safeParseJsonResponse(response)) as T;\n}\n\nasync function safeFetch(\n fetchFn: typeof globalThis.fetch,\n url: string,\n init: RequestInit,\n): Promise<Response> {\n try {\n return await fetchFn(url, init);\n } catch (cause) {\n throw new NetworkError(\"HTTP request failed\", { code: \"network_error\", cause });\n }\n}\n\nasync function safeParseJsonResponse(response: Response): Promise<unknown> {\n try {\n return await response.json();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Read the body of a NON-OK response for an error mapper: JSON when it parses, the raw\n * text otherwise (never throws, never `undefined` — an unreadable stream reads as `\"\"`).\n *\n * Distinct from {@link safeParseJsonResponse}, which drops a non-JSON body to `undefined`.\n * Error mappers need the raw text preserved: it is what surfaces on the mapped error's\n * `raw` field when a provider answers with HTML or a bare string.\n *\n * @internal\n */\nexport async function readErrorResponseBody(response: Response): Promise<unknown> {\n const text = await response.text().catch(() => \"\");\n try {\n return JSON.parse(text);\n } catch {\n // not JSON — keep as string for the mapper's raw field\n return text;\n }\n}\n\n/**\n * Translate an HTTP error response into a typed `TheokitAgentError` subclass.\n *\n * @internal\n */\nexport function mapHttpStatusToError(status: number, body: unknown): TheokitAgentError {\n const envelope = extractErrorEnvelope(body);\n const message = envelope.message ?? `HTTP ${status}`;\n const errorOptions = {\n code: envelope.code,\n protoErrorCode: envelope.protoErrorCode,\n cause: body,\n };\n\n if (envelope.code === \"integration_not_connected\") {\n return new IntegrationNotConnectedError(message, {\n provider: envelope.provider ?? \"unknown\",\n helpUrl: envelope.helpUrl ?? \"\",\n code: envelope.code,\n cause: body,\n });\n }\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, errorOptions);\n }\n if (status === 429) {\n return new RateLimitError(message, errorOptions);\n }\n if (status >= 400 && status < 500) {\n return new ConfigurationError(message, errorOptions);\n }\n if (status >= 500) {\n return new NetworkError(message, errorOptions);\n }\n return new UnknownAgentError(message, errorOptions);\n}\n\nfunction extractErrorEnvelope(body: unknown): ErrorEnvelope {\n if (!body || typeof body !== \"object\") return {};\n const record = body as Record<string, unknown>;\n const inner = record.error;\n const source: unknown = inner && typeof inner === \"object\" ? inner : record;\n return readEnvelopeFields(source as Record<string, unknown>);\n}\n\nfunction readEnvelopeFields(record: Record<string, unknown>): ErrorEnvelope {\n return {\n code: pickString(record, \"code\"),\n message: pickString(record, \"message\"),\n protoErrorCode: pickString(record, \"protoErrorCode\"),\n provider: pickString(record, \"provider\"),\n helpUrl: pickString(record, \"helpUrl\"),\n };\n}\n\nfunction pickString(record: Record<string, unknown>, key: string): string | undefined {\n const value = record[key];\n return typeof value === \"string\" ? value : undefined;\n}\n","/**\n * Hermes tool-call extraction — leaked-dialect safe-parse (theokit#58 follow-up).\n *\n * Some models (qwen3-coder via OpenRouter, OpenAI-compatible API) intermittently emit their\n * Hermes tool-call dialect as assistant TEXT content instead of native `tool_calls`:\n *\n * <function=NAME><parameter=KEY>VALUE</parameter>...</function></tool_call>\n *\n * When that happens the provider sends ZERO native tool_calls, so the agent loop sees an\n * `end_turn` with no tools and the intended call is silently lost. This pure helper recovers\n * those calls from the content so the loop can execute them.\n *\n * OPT-IN only (`ProviderProfile.extractToolCallsFromContent`) and run ONLY when the provider\n * emitted no native tool_calls. A code assistant can legitimately print a literal `<function=` in a\n * fenced code block, so recovery is gated TWICE: the per-route flag is the coarse enable, and the R5\n * request-scoped `allowedToolNames` allowlist below is the precise false-positive guard — a block is\n * promoted only when its name is a real tool in the current request. The size-guard (no native call)\n * prevents double-counting a real native call.\n *\n * Fail-open like `stripThinkBlocks`: a partial/unclosed block (missing the `</tool_call>`\n * marker) is NOT matched — it stays in the residual text and yields no tool call, so a corrupted\n * stream never fabricates a call from junk.\n *\n * Accepted best-effort limit (mirrors the consumer-side stripper EC-5): if a parameter VALUE\n * contains the literal substring `</tool_call>`, the non-greedy block scanner closes at that inner\n * occurrence. This errs toward NOT over-consuming text — same class as `strip-think`'s EC-10.\n *\n * Recovered parameter values are ALWAYS strings: the text dialect carries no per-param type info, so\n * `<parameter=count>5</parameter>` yields `{ count: \"5\" }`, not `{ count: 5 }`. A downstream schema\n * (e.g. Zod) coercing/validating the tool input is the right place to type it — a mismatch there\n * fails clear (typed tool error), never silently. This differs from the native `tool_calls` path,\n * whose `arguments` is JSON and is parsed into typed values.\n *\n * @internal\n */\nimport { sanitizeToolInput } from \"../../sanitize/sanitize-tool-input.js\";\nimport type { LlmToolCallPart } from \"./types.js\";\n\n/** A full leaked block: `<function=NAME> …inner… </tool_call>`. The closing `</tool_call>` is\n * required (fail-open: a partial block at stream end is left as text). Non-greedy inner. */\nconst HERMES_BLOCK = /<function=\\s*([^>\\s]+)\\s*>([\\s\\S]*?)<\\/tool_call>/g;\n/** A single parameter inside a block: `<parameter=KEY>VALUE</parameter>`. Non-greedy value. */\nconst HERMES_PARAM = /<parameter=\\s*([^>\\s]+)\\s*>([\\s\\S]*?)<\\/parameter>/g;\n\nexport interface HermesExtractResult {\n /** Recovered tool calls (empty when none matched). */\n toolCalls: LlmToolCallPart[];\n /** Content with every PROMOTED block removed + trimmed; gated-out and unmatched blocks stay visible. */\n residualText: string;\n /** Names of well-formed leaked blocks that WERE dropped by the request-scoped allowlist (R5) — a\n * block whose name is not a tool in the current request. Empty when no allowlist was applied or\n * nothing was gated out. The caller logs these so a guard firing is observable in production. */\n droppedNames: string[];\n}\n\n/**\n * Recover Hermes-dialect tool calls leaked into assistant text. `makeId` supplies a unique id per\n * recovered call (the provider gave none). Pure — no side effects.\n *\n * @param allowedToolNames R5 request-scoped gate — when provided, only a block whose name is in the\n * set is promoted (exact, case-sensitive); an empty set promotes nothing; `undefined` recovers all\n * (back-compat). Gated-out blocks stay as visible text (they are not tool calls).\n * @internal\n */\nexport function extractHermesToolCalls(\n content: string,\n makeId: () => string,\n allowedToolNames?: ReadonlySet<string>,\n): HermesExtractResult {\n // R5 request-scoped gate: promote a block only when its name is a real tool in the current request\n // (exact, case-sensitive — peer-project payload.ts:190). `undefined` allowlist → recover-all (back-compat\n // for direct callers); an EMPTY set recovers nothing (a request with no tools has nothing legitimate\n // to recover). The name is already trimmed above, so the gate and the emitted call agree (EC-1).\n const isPromoted = (name: string): boolean =>\n name.length > 0 && (allowedToolNames === undefined || allowedToolNames.has(name));\n const toolCalls: LlmToolCallPart[] = [];\n const droppedNames: string[] = [];\n for (const block of content.matchAll(HERMES_BLOCK)) {\n const name = (block[1] ?? \"\").trim();\n if (!isPromoted(name)) {\n // A well-formed leaked block gated out by a defined allowlist — record it for observability.\n if (name.length > 0 && allowedToolNames !== undefined) droppedNames.push(name);\n continue;\n }\n toolCalls.push({\n type: \"tool_use\",\n id: makeId(),\n name,\n input: parseHermesParams(block[2] ?? \"\"),\n });\n }\n // EC-5: strip ONLY promoted blocks — a gated-out block (e.g. a `<function=example>` in a code fence\n // whose name is not a request tool) keeps its text visible instead of being silently deleted.\n const residualText =\n toolCalls.length === 0\n ? content\n : content\n .replace(HERMES_BLOCK, (full, rawName) =>\n isPromoted((rawName ?? \"\").trim()) ? \"\" : full,\n )\n .trim();\n return { toolCalls, residualText, droppedNames };\n}\n\n/** Parse the `<parameter=KEY>VALUE</parameter>` pairs inside a block's inner text into an input map.\n *\n * Value hygiene is DELEGATED to the public `sanitizeToolInput` primitive (`@theokit/sdk/sanitize`,\n * trim-only) so the internal recovery and the public sanitizer share ONE source of truth (DRY) — the\n * P0 bug (`\\n`-wrapped paths → `not_found` → stalled multi-read loops) was born from an ad-hoc,\n * un-shared trim. Keys are trimmed here (the regex already excludes whitespace from the key capture);\n * values stay strings (the doc-comment invariant), trimmed by the shared primitive. */\nfunction parseHermesParams(inner: string): Record<string, unknown> {\n const input: Record<string, unknown> = {};\n for (const param of inner.matchAll(HERMES_PARAM)) {\n const key = param[1];\n const value = param[2];\n if (key === undefined || value === undefined) continue;\n input[key.trim()] = value;\n }\n return sanitizeToolInput(input, { trim: true }).value;\n}\n\nconst STREAM_MARKER = \"<function=\";\nconst DEFAULT_STREAM_BUFFER_CAP = 8192;\n\nconst isStreamWs = (c: string | undefined): boolean =>\n c === \" \" || c === \"\\t\" || c === \"\\n\" || c === \"\\r\";\n\n/**\n * R7 stream-boundary suppression FSM. Classifies a suspicion buffer (accumulated streamed content)\n * as `\"possible\"` — it could still become a `<function=NAME>` tool call for a request tool, so the\n * caller HOLDS it (emits no text_delta) — or `\"impossible\"` — confirmed NOT a tool call, so the\n * caller FLUSHES it as visible text. The marker match is CASE-SENSITIVE, identical to `HERMES_BLOCK`\n * (no `/i`), so the FSM never holds a block `extractHermesToolCalls` would not recover (EC-1). An\n * empty allowlist promotes nothing (`\"impossible\"`); over `cap` while still tool-call-like fails open\n * to `\"impossible\"` (flush) so a never-closing marker cannot grow unbounded. Pure — never throws.\n * @internal\n */\nexport function streamToolCallBufferState(\n held: string,\n allowedToolNames: ReadonlySet<string>,\n cap: number = DEFAULT_STREAM_BUFFER_CAP,\n): \"possible\" | \"impossible\" {\n if (allowedToolNames.size === 0) return \"impossible\";\n const t = held.trimStart();\n if (t.length < STREAM_MARKER.length) {\n // Still building the marker itself (e.g. \"<fun\").\n return STREAM_MARKER.startsWith(t) ? \"possible\" : \"impossible\";\n }\n if (!t.startsWith(STREAM_MARKER)) return \"impossible\";\n const parsed = parseStreamMarkerName(t);\n if (parsed === \"building\") return \"possible\";\n if (parsed === \"invalid\") return \"impossible\";\n const nameOk = parsed.complete\n ? allowedToolNames.has(parsed.name)\n : someToolNameStartsWith(allowedToolNames, parsed.name);\n if (!nameOk) return \"impossible\";\n return held.length > cap ? \"impossible\" : \"possible\";\n}\n\n/** Read the (partial) tool name after a confirmed `<function=` marker (skipping the regex `\\s*`).\n * `\"building\"` = only the marker(+ws) so far; `\"invalid\"` = a `>`/other char with no name. */\nfunction parseStreamMarkerName(\n t: string,\n): { name: string; complete: boolean } | \"building\" | \"invalid\" {\n let cursor = STREAM_MARKER.length;\n while (cursor < t.length && isStreamWs(t[cursor])) cursor += 1;\n const nameStart = cursor;\n while (cursor < t.length && t[cursor] !== \">\" && !isStreamWs(t[cursor])) cursor += 1;\n const name = t.slice(nameStart, cursor);\n if (name.length === 0) return cursor >= t.length ? \"building\" : \"invalid\";\n return { name, complete: cursor < t.length && t[cursor] === \">\" };\n}\n\n/** True when any allowed tool name starts with `prefix` — the streaming partial-name probe (R7 D2). */\nfunction someToolNameStartsWith(allowedToolNames: ReadonlySet<string>, prefix: string): boolean {\n for (const name of allowedToolNames) {\n if (name.startsWith(prefix)) return true;\n }\n return false;\n}\n\n/**\n * R7 mixed-delta split: given a suspicion buffer that is NOT itself a possible tool call as a whole,\n * find the first `<` index whose suffix COULD still become a `<function=NAME>` tool call for a request\n * tool — so the caller flushes the definitely-prose prefix and holds only the suspicious suffix (e.g.\n * a `hello <function=read` delta flushes `hello ` and holds `<function=read`). Returns `-1` when no\n * suffix is suspicious (flush the whole buffer). Bounded: scans only `<` positions. @internal\n */\nexport function firstPossibleMarkerStart(\n held: string,\n allowedToolNames: ReadonlySet<string>,\n): number {\n for (let i = held.indexOf(\"<\"); i !== -1; i = held.indexOf(\"<\", i + 1)) {\n if (streamToolCallBufferState(held.slice(i), allowedToolNames) === \"possible\") return i;\n }\n return -1;\n}\n\n/**\n * R7 stateful stream-suppression buffer. Owns the held-content buffer for one stream: `push` feeds a\n * content delta and returns the text to emit now (or `undefined` to HOLD while it could still be a\n * `<function=NAME>` tool call for a request tool); `drain` finalizes at stream end. Extracted from the\n * OpenAI accumulator so the adapter stays thin (G8). @internal\n */\nexport class StreamSuppressionBuffer {\n #held = \"\";\n constructor(private readonly allowedToolNames: ReadonlySet<string>) {}\n\n /** Feed a content delta; returns the text to emit as a `text_delta` now, or `undefined` to hold. */\n push(content: string): string | undefined {\n this.#held += content;\n if (streamToolCallBufferState(this.#held, this.allowedToolNames) === \"possible\")\n return undefined;\n // Whole buffer is not a tool call, but a marker for a request tool may start mid-buffer (prose +\n // marker in one delta) — flush the prose prefix, hold the suspicious suffix.\n const holdStart = firstPossibleMarkerStart(this.#held, this.allowedToolNames);\n if (holdStart > 0) {\n const flush = this.#held.slice(0, holdStart);\n this.#held = this.#held.slice(holdStart);\n return flush;\n }\n const flush = this.#held;\n this.#held = \"\";\n return flush;\n }\n\n /** Drain the held buffer at stream end. `hasNativeCalls` mirrors `finish()`'s size-guard: when\n * native `tool_calls` exist, `finish()` won't strip the leaked block, so stream the held text WHOLE\n * (keeping `accumulatedText == finish.text`); otherwise strip the recoverable blocks. Idempotent. */\n drain(hasNativeCalls: boolean): string | undefined {\n if (this.#held.length === 0) return undefined;\n const held = this.#held;\n this.#held = \"\";\n if (hasNativeCalls) return held;\n const residual = extractHermesToolCalls(held, () => \"held\", this.allowedToolNames).residualText;\n return residual.length > 0 ? residual : undefined;\n }\n}\n","/**\n * Mapping from `LlmMessage` to OpenAI's message format.\n *\n * Extracted from `openai.ts` in M75 because the G8 gate (<= 400 LoC) caught it at 427 — PRE-EXISTING debt,\n * which stayed invisible while `knip` failed before the gate ran.\n *\n * The seam is not arbitrary: these five functions form ONE responsibility — translating our\n * message format into OpenAI's wire format — and none of them knows about transport, streaming or\n * request policy. The rest of `openai.ts` handles that.\n */\nimport { toStringToolResultContent } from \"./tool-result-content.js\";\nimport type { LlmMessage } from \"./types.js\";\n\nexport function toOpenAIMessages(message: LlmMessage): Array<Record<string, unknown>> {\n if (message.role === \"system\") return [systemMessage(message)];\n if (message.role === \"user\") return userOrToolMessages(message);\n return [assistantMessage(message)];\n}\n\nfunction systemMessage(message: LlmMessage): Record<string, unknown> {\n return { role: \"system\", content: joinTextParts(message) };\n}\n\nfunction joinTextParts(message: LlmMessage): string {\n return message.content\n .filter((part) => part.type === \"text\")\n .map((part) => (part as { text: string }).text)\n .join(\"\\n\");\n}\n\n/**\n * Translate a logical `user` turn. If the turn contains tool_result parts\n * they must be emitted as `role: \"tool\"` messages with matching\n * `tool_call_id` — OpenAI rejects tool_calls followed by a user message.\n * Plain text parts (and any other parts) collapse into a single user\n * message that follows the tool messages.\n */\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nfunction userOrToolMessages(message: LlmMessage): Array<Record<string, unknown>> {\n const out: Array<Record<string, unknown>> = [];\n for (const part of message.content) {\n if (part.type === \"tool_result\") {\n out.push({\n role: \"tool\",\n tool_call_id: part.toolUseId,\n // SE7 — this wire's tool role is string-only: text blocks flatten; an\n // image block fails fast (ConfigurationError).\n content: toStringToolResultContent(part.content, \"openai\"),\n });\n }\n }\n const userText = joinTextParts(message);\n // M35 — image parts turn the user message into OpenAI/OpenRouter's content-array form\n // (`[{type:\"text\"}, {type:\"image_url\", image_url:{url: data-URL}}]`); text-only stays a plain string.\n const imageParts = message.content.filter(\n (p): p is import(\"./types.js\").LlmImagePart => p.type === \"image\",\n );\n if (imageParts.length > 0) {\n const content: Array<Record<string, unknown>> = [];\n if (userText.length > 0) content.push({ type: \"text\", text: userText });\n for (const img of imageParts) {\n // OpenAI/OpenRouter `image_url` accepts BOTH a data URL (inline base64) and a real https URL.\n const url =\n img.source.type === \"base64\"\n ? `data:${img.source.media_type};base64,${img.source.data}`\n : img.source.url;\n content.push({ type: \"image_url\", image_url: { url } });\n }\n out.push({ role: \"user\", content });\n } else if (userText.length > 0) {\n out.push({ role: \"user\", content: userText });\n }\n return out;\n}\n\nfunction assistantMessage(message: LlmMessage): Record<string, unknown> {\n const text = joinTextParts(message);\n const toolCalls = message.content\n .filter((part) => part.type === \"tool_use\")\n .map((part) => {\n const tc = part as { id: string; name: string; input: Record<string, unknown> };\n return {\n id: tc.id,\n type: \"function\",\n function: { name: tc.name, arguments: JSON.stringify(tc.input) },\n };\n });\n const result: Record<string, unknown> = { role: \"assistant\", content: text };\n if (toolCalls.length > 0) result.tool_calls = toolCalls;\n return result;\n}\n","import { NetworkError } from \"../../errors.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { mapOllamaHttpError, mapOllamaTransportError } from \"../error-mappers/ollama.js\";\nimport { mapOpenAICompatibleError } from \"../error-mappers/openai-compatible.js\";\nimport { readErrorResponseBody } from \"../http.js\";\nimport {\n collapseSystemText,\n makeLlmFinish,\n mapOpenAIFinish,\n parseToolArguments,\n} from \"./finish.js\";\nimport { extractHermesToolCalls, StreamSuppressionBuffer } from \"./hermes-tool-extract.js\";\nimport { toOpenAIMessages } from \"./openai-messages.js\";\nimport { parseSseStream } from \"./sse.js\";\nimport { wrapTransportError } from \"./transport-error.js\";\nimport type {\n LlmClient,\n LlmEvent,\n LlmFinish,\n LlmRequest,\n LlmStopReason,\n LlmToolCallPart,\n} from \"./types.js\";\n\n/**\n * Real OpenAI Chat Completions client. Streams `/v1/chat/completions` and\n * translates delta chunks into our provider-agnostic `LlmEvent`s.\n *\n * Uses native `fetch` only — no `openai` SDK dependency.\n *\n * @internal\n */\n\n/**\n * M45 — derive the chat-completions path from the baseUrl: a path already carrying a version segment\n * (`/v1`, `/v1beta`, …) gets `/chat/completions`; host-only (or unparseable) baseUrls keep the legacy\n * `/v1/chat/completions`. Unparseable NEVER throws (H1) — the transport surfaces a typed error at fetch time.\n */\nfunction deriveChatPath(baseUrl: string): string {\n try {\n return /\\/v\\d+[a-z]*(\\/|$)/.test(new URL(baseUrl).pathname)\n ? \"/chat/completions\"\n : \"/v1/chat/completions\";\n } catch {\n return \"/v1/chat/completions\";\n }\n}\n\nexport interface OpenAIClientOptions {\n apiKey: string;\n baseUrl?: string;\n organization?: string;\n fetch?: typeof fetch;\n /**\n * Provider name for error mapping dispatch (T1.1, ADR D185). When set\n * to `\"ollama\"`, transport and HTTP errors go through `mapOllamaTransportError`\n * / `mapOllamaHttpError` for actionable messages before falling back to\n * the generic OpenAI-compatible mapper. Default `\"openai\"`.\n */\n providerName?: string;\n /**\n * Opt-in leaked-dialect safe-parse (theokit#58 follow-up). When `true`, a finish that carries\n * ZERO native `tool_calls` has its assistant text scanned for the Hermes `<function=…></tool_call>`\n * dialect; any recovered calls are surfaced as real `tool_calls` so the loop executes them.\n * Default `false` — a code assistant can legitimately print a literal `<function=` in code text.\n */\n extractToolCallsFromContent?: boolean;\n /**\n * M41 — extra HTTP headers merged into the request (the profile's static `extraHeaders` + a provider\n * `transform.headers(ctx)`). Spread AFTER the base `authorization`/`content-type`, so a provider that owns\n * its auth CAN override them by design (document this on `ProviderTransform.headers`).\n */\n extraHeaders?: Record<string, string>;\n /** M45 — explicit chat-completions path (from `ProviderProfile.chatCompletionsPath`). */\n chatCompletionsPath?: string;\n}\n\ninterface OpenAIDeltaChunk {\n choices?: Array<{\n index: number;\n delta?: {\n content?: string;\n /** OpenRouter unified reasoning delta (issue #47) — streamed separately from `content`. */\n reasoning?: string;\n /**\n * Sibling reasoning field used by some OpenAI-compatible providers (DeepSeek's direct API,\n * many vLLM / LMStudio reasoning parsers). Treated identically to `reasoning` (issue #47,\n * F-domain-2). OpenRouter normalizes to `reasoning`; this is the fallback for non-OpenRouter\n * compat endpoints reached via `baseUrl` override.\n */\n reasoning_content?: string;\n tool_calls?: Array<{\n index: number;\n id?: string;\n function?: { name?: string; arguments?: string };\n }>;\n };\n finish_reason?: string | null;\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n /**\n * OpenAI + OpenRouter extended usage (D376). Anthropic prompt caching\n * surfaces as `prompt_tokens_details.cached_tokens` on OpenRouter passthrough;\n * native OpenAI exposes the same field on `chatcmpl-*` responses.\n */\n prompt_tokens_details?: { cached_tokens?: number };\n completion_tokens_details?: { reasoning_tokens?: number };\n /** Anthropic-on-OpenRouter passes cache_creation_tokens top-level (a peer#10266). */\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n };\n /**\n * In-stream provider error. OpenRouter (and some OpenAI-compatible proxies)\n * report auth / quota / rate-limit failures as an HTTP 200 SSE body carrying\n * `data: {\"error\":{\"message\":\"...\",\"code\":401}}` instead of a non-2xx status.\n * Without surfacing this, the round finishes empty and the failure is silent\n * (usetheodev/theocode#31).\n */\n error?: { message?: string; code?: number | string; type?: string };\n}\n\nexport class OpenAIClient implements LlmClient {\n readonly name = \"openai\";\n private readonly baseUrl: string;\n private readonly chatPath: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: OpenAIClientOptions) {\n // M45 review M3 — strip trailing slashes so `…/v1/` (the python-openai-popularized form) joins cleanly.\n this.baseUrl = (options.baseUrl ?? \"https://api.openai.com\").replace(/\\/+$/, \"\");\n // M45 — URL-join rule (kills the /v1/v1 doubling): explicit override > version-segment detection >\n // legacy `/v1/chat/completions`. A baseUrl already carrying a version path segment (…/openai/v1,\n // …/v1beta/openai) gets only `/chat/completions`; host-only baseUrls are byte-identical to before.\n // M45 review H1 — the parse NEVER throws from the constructor: a malformed baseUrl (scheme-less host,\n // empty env var) degrades to the LEGACY path (byte-identical to pre-M45 string concat) and fails, typed,\n // at the first fetch — never poisoning the whole provider chain at construction time.\n this.chatPath = options.chatCompletionsPath ?? deriveChatPath(this.baseUrl);\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n /**\n * Whether this client recovers leaked Hermes tool-call dialect from assistant\n * text (theokit#58 follow-up). Observability for the route→client wiring of\n * `extractToolCallsFromContent`. @internal\n */\n get recoversLeakedToolCalls(): boolean {\n return this.options.extractToolCallsFromContent ?? false;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: HTTP+SSE handshake + accumulator is intentionally one block\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.options.apiKey}`,\n };\n if (this.options.organization !== undefined) {\n headers[\"openai-organization\"] = this.options.organization;\n }\n // M41 — merge extra/dynamic headers (spread last: a provider that owns its auth may override base headers).\n if (this.options.extraHeaders !== undefined) Object.assign(headers, this.options.extraHeaders);\n const providerId = this.options.providerName ?? this.name;\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.baseUrl}${this.chatPath}`, {\n method: \"POST\",\n signal,\n headers,\n body: JSON.stringify(buildOpenAIBody(request, providerId)),\n });\n } catch (fetchErr) {\n // T1.1: Ollama-specific transport error mapping (ECONNREFUSED / ENOTFOUND).\n const mapped = mapOllamaTransportError({\n providerId,\n cause: fetchErr,\n endpoint: \"/v1/chat/completions\",\n });\n if (mapped !== undefined) throw mapped;\n // M93 — before this, a raw `throw fetchErr` left here for every provider other than Ollama, and\n // a foreign error is NON-transient by contract (`errors.ts:429`): retry stayed off\n // in the most classic case.\n throw wrapTransportError(fetchErr, { providerId, endpoint: \"/v1/chat/completions\" });\n }\n if (!response.ok) {\n const body = await readErrorResponseBody(response);\n // T1.1: try Ollama-specific HTTP mapper first; falls through to generic.\n const ollamaMapped = mapOllamaHttpError({\n providerId,\n status: response.status,\n body,\n headers: response.headers,\n endpoint: \"/v1/chat/completions\",\n });\n if (ollamaMapped !== undefined) throw ollamaMapped;\n // Use the openai-compatible mapper. For OpenAI proper the providerId\n // is \"openai\"; OpenRouter is handled in its own client subclass (see\n // OpenRouterClient if/when added). Providers tagged differently via\n // wrapper clients can pass their own providerId by overriding.\n throw mapOpenAICompatibleError({\n providerId,\n status: response.status,\n body,\n headers: response.headers,\n endpoint: \"/v1/chat/completions\",\n });\n }\n\n const accumulator = new OpenAIStreamAccumulator(\n this.options.extractToolCallsFromContent ?? false,\n providerId,\n // R5: request-scoped allowlist — leaked recovery only promotes a block whose name is a tool the\n // model was actually given. Empty set (no tools) recovers nothing.\n new Set(request.tools?.map((tool) => tool.name) ?? []),\n );\n let sawDone = false;\n for await (const record of parseSseStream(response.body, signal)) {\n if (record.data === \"[DONE]\") {\n sawDone = true;\n break;\n }\n let chunk: OpenAIDeltaChunk;\n try {\n chunk = JSON.parse(record.data) as OpenAIDeltaChunk;\n } catch {\n continue;\n }\n // Fail-loud on an in-stream provider error (OpenRouter HTTP-200 error body).\n // The accumulator only reads `choices`, so an error-only chunk would finish\n // the round empty and swallow the failure (theocode#31). Map it to the same\n // typed error a non-2xx HTTP status would have produced.\n if (chunk.error !== undefined && chunk.error !== null) {\n const status = typeof chunk.error.code === \"number\" ? chunk.error.code : 502;\n throw mapOpenAICompatibleError({\n providerId,\n status,\n body: chunk,\n headers: response.headers,\n endpoint: \"/v1/chat/completions\",\n });\n }\n const events = accumulator.consume(chunk);\n for (const event of events) yield event;\n }\n // M2 #61 — a stream ending with NEITHER `[DONE]` NOR a `finish_reason` was\n // truncated (dropped connection / proxy hiccup); throw a typed error rather\n // than commit the partial turn as a clean `end_turn` (codex prior art).\n if (!sawDone && !accumulator.finishReasonSeen) {\n throw new NetworkError(\"SSE stream truncated (no finish_reason / [DONE])\", {\n code: \"stream_truncated\",\n });\n }\n // R7: drain any held buffer so leaked-dialect text is never silently dropped.\n const drainEvent = accumulator.finalizeHeldText();\n if (drainEvent !== undefined) yield drainEvent;\n return accumulator.finish();\n }\n}\n\nclass OpenAIStreamAccumulator {\n private text = \"\";\n private stopReason: LlmStopReason = \"end_turn\";\n private inputTokens?: number;\n private outputTokens?: number;\n private cacheReadTokens?: number;\n private cacheWriteTokens?: number;\n private reasoningTokens?: number;\n private readonly toolCalls = new Map<number, { id: string; name: string; args: string }>();\n /** R7: present only when recovery is enabled AND the request declares tools — holds suspected\n * leaked-dialect content back from the `text_delta` stream. `undefined` ⇒ stream immediately. */\n private readonly suppress?: StreamSuppressionBuffer;\n\n /**\n * @param extractFromContent opt-in leaked-dialect safe-parse (theokit#58). Default false.\n * @param providerName provider id, used only to label the recovery log line.\n * @param allowedToolNames R5 request-scoped allowlist — built from `request.tools` at `stream()`;\n * leaked recovery in `finish()` only promotes a block whose name is in this set. `undefined`\n * (direct construction) recovers all (back-compat); an empty set recovers nothing.\n */\n constructor(\n private readonly extractFromContent = false,\n private readonly providerName = \"openai\",\n private readonly allowedToolNames?: ReadonlySet<string>,\n ) {\n this.suppress =\n extractFromContent && allowedToolNames !== undefined && allowedToolNames.size > 0\n ? new StreamSuppressionBuffer(allowedToolNames)\n : undefined;\n }\n\n consume(chunk: OpenAIDeltaChunk): LlmEvent[] {\n const events: LlmEvent[] = [];\n this.applyUsage(chunk.usage);\n for (const choice of chunk.choices ?? []) {\n events.push(...this.applyChoice(choice));\n }\n return events;\n }\n\n private applyChoice(choice: NonNullable<OpenAIDeltaChunk[\"choices\"]>[number]): LlmEvent[] {\n const events: LlmEvent[] = [];\n // issue #47: reasoning delta precedes the visible text in arrival order. OpenRouter streams it\n // as `reasoning`; some compat providers use `reasoning_content` (F-domain-2) — accept either.\n const reasoningEvent = this.applyReasoningDelta(\n choice.delta?.reasoning ?? choice.delta?.reasoning_content,\n );\n if (reasoningEvent !== undefined) events.push(reasoningEvent);\n const textEvent = this.applyContentDelta(choice.delta?.content);\n if (textEvent !== undefined) events.push(textEvent);\n this.mergeToolCallDeltas(choice.delta?.tool_calls);\n this.applyFinishReason(choice.finish_reason);\n // R7: at the terminal chunk, flush the held buffer's residual (held minus recoverable blocks)\n // AFTER this chunk's content was appended above — so `accumulatedText == finish.text`.\n if (choice.finish_reason !== undefined && choice.finish_reason !== null) {\n const flushEvent = this.finalizeHeldText();\n if (flushEvent !== undefined) events.push(flushEvent);\n }\n return events;\n }\n\n private applyReasoningDelta(reasoning: string | undefined): LlmEvent | undefined {\n // issue #47: reasoning is NOT accumulated into `this.text` (the visible answer) — it is a\n // separate channel surfaced as `reasoning_delta` (→ thinking events at the loop layer).\n if (typeof reasoning !== \"string\" || reasoning.length === 0) return undefined;\n return { type: \"reasoning_delta\", text: reasoning };\n }\n\n private applyUsage(usage: OpenAIDeltaChunk[\"usage\"]): void {\n if (usage?.prompt_tokens !== undefined) this.inputTokens = usage.prompt_tokens;\n if (usage?.completion_tokens !== undefined) this.outputTokens = usage.completion_tokens;\n // D376: cache + reasoning buckets via OpenRouter passthrough + OpenAI native.\n const cachedDetail = usage?.prompt_tokens_details?.cached_tokens;\n if (cachedDetail !== undefined) this.cacheReadTokens = cachedDetail;\n const reasoningDetail = usage?.completion_tokens_details?.reasoning_tokens;\n if (reasoningDetail !== undefined) this.reasoningTokens = reasoningDetail;\n // a peer#10266 top-level fallback for Anthropic-on-OpenRouter.\n if (usage?.cache_read_input_tokens !== undefined) {\n this.cacheReadTokens = usage.cache_read_input_tokens;\n }\n if (usage?.cache_creation_input_tokens !== undefined) {\n this.cacheWriteTokens = usage.cache_creation_input_tokens;\n }\n }\n\n private applyContentDelta(content: string | undefined): LlmEvent | undefined {\n if (typeof content !== \"string\" || content.length === 0) return undefined;\n this.text += content;\n // R7: when suppression is active, HOLD content that could still be a leaked tool call (the buffer\n // returns the text to emit now, or `undefined` to hold). Otherwise stream immediately.\n if (this.suppress === undefined) return { type: \"text_delta\", text: content };\n const emit = this.suppress.push(content);\n return emit !== undefined ? { type: \"text_delta\", text: emit } : undefined;\n }\n\n /** R7 held-buffer finalizer, called at the `finish_reason` chunk (in `applyChoice`) AND after the\n * SSE loop in `stream()` — so a stream that omits a `finish_reason` terminal never silently drops\n * held text. `toolCalls.size > 0` (native calls present) makes `finish()` skip recovery, so the\n * buffer streams the held text whole. Idempotent once drained. */\n finalizeHeldText(): LlmEvent | undefined {\n const emit = this.suppress?.drain(this.toolCalls.size > 0);\n return emit !== undefined ? { type: \"text_delta\", text: emit } : undefined;\n }\n\n private mergeToolCallDeltas(\n deltas: NonNullable<NonNullable<OpenAIDeltaChunk[\"choices\"]>[number][\"delta\"]>[\"tool_calls\"],\n ): void {\n for (const call of deltas ?? []) {\n const existing = this.toolCalls.get(call.index) ?? { id: \"\", name: \"\", args: \"\" };\n if (call.id !== undefined) existing.id = call.id;\n if (call.function?.name !== undefined) existing.name = call.function.name;\n if (call.function?.arguments !== undefined) existing.args += call.function.arguments;\n this.toolCalls.set(call.index, existing);\n }\n }\n\n /** M2 #61 — true once any chunk carried a non-null `finish_reason` (else a\n * stream ending without `[DONE]` is a truncation, not a clean end). */\n private sawFinishReason = false;\n get finishReasonSeen(): boolean {\n return this.sawFinishReason;\n }\n\n private applyFinishReason(reason: string | null | undefined): void {\n if (reason === undefined || reason === null) return;\n this.sawFinishReason = true;\n this.stopReason = mapOpenAIFinish(reason);\n }\n\n finish(): LlmFinish {\n const toolCalls: LlmToolCallPart[] = [];\n for (const call of this.toolCalls.values()) {\n const input = parseToolArguments(call.args);\n toolCalls.push({ type: \"tool_use\", id: call.id, name: call.name, input });\n }\n let text = this.text;\n let stopReason = this.stopReason;\n // theokit#58 follow-up: leaked-dialect safe-parse. Opt-in, and ONLY when the provider sent no\n // native tool_calls (the size-guard prevents double-counting a real call). Recovered calls flip\n // the stopReason to \"tool_use\" so the agent loop dispatches them; the consumed dialect is stripped\n // from the visible text.\n if (this.extractFromContent && toolCalls.length === 0) {\n const recovered = extractHermesToolCalls(\n this.text,\n () => `hermes-${globalThis.crypto.randomUUID()}`,\n this.allowedToolNames,\n );\n if (recovered.toolCalls.length > 0) {\n toolCalls.push(...recovered.toolCalls);\n text = recovered.residualText;\n stopReason = \"tool_use\";\n // Observability (wiring triad pillar c): recovery is a model-misbehavior workaround, so make\n // it visible — a route that leaks often should be diagnosable without a debugger.\n diag(\n `[theokit-sdk] recovered ${recovered.toolCalls.length} leaked tool call(s) from assistant content ` +\n `(provider=\"${this.providerName}\", names=${recovered.toolCalls.map((c) => c.name).join(\",\")})\\n`,\n );\n }\n // R5 observability: a leaked block DROPPED by the request-scoped allowlist is the guard firing —\n // surface it too, so a model emitting `<function=NAME>` for an undeclared tool is diagnosable.\n if (recovered.droppedNames.length > 0) {\n diag(\n `[theokit-sdk] dropped ${recovered.droppedNames.length} leaked block(s) whose name is not a ` +\n `tool in the request (provider=\"${this.providerName}\", names=${recovered.droppedNames.join(\",\")})\\n`,\n );\n }\n }\n return makeLlmFinish({\n stopReason,\n text,\n toolCalls,\n inputTokens: this.inputTokens,\n outputTokens: this.outputTokens,\n cacheReadTokens: this.cacheReadTokens,\n cacheWriteTokens: this.cacheWriteTokens,\n reasoningTokens: this.reasoningTokens,\n });\n }\n}\n\n/**\n * issue #47 / F-domain-1: encode the reasoning request in the shape the target provider accepts.\n * Native OpenAI Chat Completions rejects unknown body params and expects the top-level\n * `reasoning_effort` string; OpenRouter (and OpenAI-compatible passthroughs) use the unified\n * `reasoning: { effort }` object. `stream()` always passes the resolved provider id, so a native\n * OpenAI request never 400s on the OpenRouter shape. When `providerName` is unspecified (test seam),\n * the unified object is used — the broader-compatibility default.\n */\nfunction applyReasoningRequest(\n body: Record<string, unknown>,\n effort: string,\n providerName: string | undefined,\n): void {\n if (providerName === \"openai\") {\n body.reasoning_effort = effort;\n return;\n }\n body.reasoning = { effort };\n}\n\n/**\n * Encode the `tools` array + per-request `tool_choice` gate (step-cap force-close). `tool_choice`\n * is meaningful only alongside `tools`, so both are emitted together (or neither). `\"none\"` advertises\n * the tools but forbids calling them — forcing a text answer from an agent whose tools are registered.\n */\nfunction applyToolsRequest(body: Record<string, unknown>, request: LlmRequest): void {\n if (request.tools === undefined || request.tools.length === 0) return;\n body.tools = request.tools.map((tool) => ({\n type: \"function\",\n function: { name: tool.name, description: tool.description, parameters: tool.inputSchema },\n }));\n if (request.toolChoice !== undefined) body.tool_choice = request.toolChoice;\n}\n\nfunction buildOpenAIBody(request: LlmRequest, providerName?: string): Record<string, unknown> {\n const messages: Array<Record<string, unknown>> = [];\n const systemText = openAISystemText(request.system);\n if (systemText.length > 0) {\n messages.push({ role: \"system\", content: systemText });\n }\n for (const message of request.messages) {\n for (const out of toOpenAIMessages(message)) messages.push(out);\n }\n const body: Record<string, unknown> = {\n model: request.model,\n stream: true,\n // D376: opt-in to OpenAI's final-chunk usage record (no-op for providers\n // that don't honor it; OpenRouter / OpenAI both respect it).\n stream_options: { include_usage: true },\n messages,\n };\n if (request.maxTokens !== undefined) body.max_tokens = request.maxTokens;\n if (request.temperature !== undefined) body.temperature = request.temperature;\n // issue #47: reasoning request — only when an effort was requested. Provider-specific wire shape.\n if (request.reasoning?.effort !== undefined)\n applyReasoningRequest(body, request.reasoning.effort, providerName);\n applyToolsRequest(body, request);\n const responseFormat = encodeOpenAIResponseFormat(request.responseFormat);\n if (responseFormat !== undefined) body.response_format = responseFormat;\n return body;\n}\n\n/**\n * T3.5 follow-up — collapse `LlmRequest.system` to the OpenAI wire shape\n * (single string).\n *\n * @internal\n */\nconst openAISystemText = collapseSystemText;\n\n/**\n * T3.6 — encode `LlmResponseFormat` into the OpenAI wire shape. The\n * structured-outputs path defaults `strict` to `true` (provider guarantees\n * the response matches the schema).\n *\n * @internal\n */\nfunction encodeOpenAIResponseFormat(\n rf: LlmRequest[\"responseFormat\"],\n): Record<string, unknown> | undefined {\n if (rf === undefined) return undefined;\n if (rf.type === \"json_object\") return { type: \"json_object\" };\n return {\n type: \"json_schema\",\n json_schema: {\n name: rf.jsonSchema.name,\n schema: rf.jsonSchema.schema,\n strict: rf.jsonSchema.strict ?? true,\n },\n };\n}\n\n/**\n * T3.6 — public test seam for `buildOpenAIBody`. The implementation is\n * file-local; the seam lets unit tests verify the wire shape without\n * exercising the streaming path.\n *\n * @internal\n */\nexport const __testing__buildOpenAIBody = buildOpenAIBody;\n/** issue #47 test seam — exercise reasoning-delta parsing without a live stream. */\nexport const __testing__OpenAIStreamAccumulator = OpenAIStreamAccumulator;\n","/**\n * Consecutive-failure circuit breaker — a cross-cutting resilience primitive.\n *\n * Used by Active Memory recall (timeout-driven) and the LLM credential pool\n * (429/terminal-failure-driven). Domain-neutral: it counts consecutive\n * failure events per key and trips after N, staying open for `cooldownMs`.\n *\n * Mirrors peer-project's `circuitBreakerMaxTimeouts` + `circuitBreakerCooldownMs`\n * config: after N consecutive timeouts the breaker trips and `shouldSkip`\n * returns `true` until `cooldownMs` has elapsed. A successful recall resets\n * the counter immediately.\n *\n * Per-key isolation so two agents in the same process don't share a counter.\n *\n * @internal\n */\n\nexport interface CircuitBreakerOptions {\n maxTimeouts?: number;\n cooldownMs?: number;\n /** Injectable clock for tests. */\n now?: () => number;\n}\n\ninterface KeyState {\n consecutiveTimeouts: number;\n cooldownUntilMs: number;\n}\n\nconst DEFAULT_MAX_TIMEOUTS = 3;\nconst DEFAULT_COOLDOWN_MS = 60_000;\n\nexport class CircuitBreaker {\n private readonly states = new Map<string, KeyState>();\n\n constructor(private readonly opts: CircuitBreakerOptions = {}) {}\n\n /** @returns true when the breaker is open and the call should be skipped. */\n shouldSkip(key: string): boolean {\n const state = this.states.get(key);\n if (state === undefined) return false;\n if (state.cooldownUntilMs === 0) return false;\n if (this.now() < state.cooldownUntilMs) return true;\n // Cooldown elapsed — close the breaker.\n state.cooldownUntilMs = 0;\n state.consecutiveTimeouts = 0;\n return false;\n }\n\n recordSuccess(key: string): void {\n const state = this.states.get(key);\n if (state === undefined) return;\n state.consecutiveTimeouts = 0;\n state.cooldownUntilMs = 0;\n }\n\n recordTimeout(key: string): void {\n const state = this.states.get(key) ?? { consecutiveTimeouts: 0, cooldownUntilMs: 0 };\n state.consecutiveTimeouts += 1;\n if (state.consecutiveTimeouts >= (this.opts.maxTimeouts ?? DEFAULT_MAX_TIMEOUTS)) {\n state.cooldownUntilMs = this.now() + (this.opts.cooldownMs ?? DEFAULT_COOLDOWN_MS);\n }\n this.states.set(key, state);\n }\n\n /** @internal — tests inspect counter state. */\n inspect(key: string): Readonly<KeyState> {\n return this.states.get(key) ?? { consecutiveTimeouts: 0, cooldownUntilMs: 0 };\n }\n\n private now(): number {\n return this.opts.now?.() ?? Date.now();\n }\n}\n","/**\n * Shared streaming helpers for `LlmClient` wrappers\n * (`FallbackLlmClient`, `PoolAwareLlmClient`).\n *\n * `tryFirstEvent` probes the first chunk of a stream to decide\n * whether the handshake succeeded. If it raises an\n * `AuthenticationError`/`RateLimitError`/`NetworkError`, the wrapper\n * captures the typed error for routing (rotate vs fallback) WITHOUT\n * starting the actual yield. Once the first event lands, the stream\n * is committed and partial-output cannot be reverted.\n *\n * `relay` yields the prefetched first chunk and then forwards the\n * remaining generator output verbatim.\n *\n * @internal\n */\n\nimport { AuthenticationError, NetworkError, RateLimitError } from \"../../errors.js\";\nimport { diag } from \"../diagnostics.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\n\n/**\n * Outcome of probing a client's first stream event.\n *\n * @internal\n */\nexport type StreamAttempt =\n | {\n kind: \"ok\";\n generator: AsyncGenerator<LlmEvent, LlmFinish, void>;\n firstResult: IteratorResult<LlmEvent, LlmFinish>;\n }\n | { kind: \"handshake_error\"; error: RateLimitError | AuthenticationError | NetworkError };\n\n/**\n * Try to obtain the FIRST event from `client.stream(...)`. Typed\n * provider failures surface as `kind: \"handshake_error\"`; everything\n * else propagates upward unchanged.\n *\n * Optionally writes a `[theokit-sdk] provider X failed (CODE): falling back`\n * line to stderr when `logFallback` is true — used by `FallbackLlmClient`.\n *\n * @internal\n */\nexport async function tryFirstEvent(\n client: LlmClient,\n request: LlmRequest,\n signal: AbortSignal,\n logFallback = false,\n): Promise<StreamAttempt> {\n const generator = client.stream(request, signal);\n try {\n const firstResult = await generator.next();\n return { kind: \"ok\", generator, firstResult };\n } catch (cause) {\n if (\n cause instanceof NetworkError ||\n cause instanceof RateLimitError ||\n cause instanceof AuthenticationError\n ) {\n if (logFallback) {\n const errCode = cause.metadata?.code ?? cause.code ?? \"unknown\";\n diag(`[theokit-sdk] provider ${client.name} failed (${errCode}): falling back\\n`);\n }\n return { kind: \"handshake_error\", error: cause };\n }\n throw cause;\n }\n}\n\n/**\n * Yield the prefetched first event, then forward the rest of the\n * generator. Identical to a normal `yield*` but with the lookahead\n * already in hand from `tryFirstEvent`.\n *\n * @internal\n */\nexport async function* relayStream(\n generator: AsyncGenerator<LlmEvent, LlmFinish, void>,\n firstResult: IteratorResult<LlmEvent, LlmFinish>,\n): AsyncGenerator<LlmEvent, LlmFinish, void> {\n if (firstResult.done === true) return firstResult.value;\n yield firstResult.value;\n while (true) {\n const next = await generator.next();\n if (next.done === true) return next.value;\n yield next.value;\n }\n}\n","/**\n * `LlmClient` wrapper that pools multiple API keys for the same\n * provider and rotates on HTTP 429/402/401 (ADRs D123-D133).\n *\n * Composition wrapper (D127) — wraps a builder that produces a real\n * `LlmClient` for a given API key. The wrapper picks a key via the\n * pool, instantiates the real client, attempts the stream, and on a\n * pre-stream error decides retry-vs-rotate per the decision matrix.\n *\n * Once `yield*` starts (first event received), rotation is impossible —\n * partial output would corrupt the stream. Same contract as\n * `FallbackLlmClient` (D2).\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n CredentialPoolExhaustedError,\n NetworkError,\n RateLimitError,\n} from \"../../errors.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { CircuitBreaker } from \"../resilience/circuit-breaker.js\";\nimport type { CredentialPool } from \"./credential-pool.js\";\nimport { computeBackoffMs, sleepWithAbort } from \"./retry.js\";\nimport { relayStream, tryFirstEvent } from \"./stream-relay.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\n\n/**\n * M2 #60 — optional resilience knobs. `breaker` guards the provider with a\n * consecutive-failure circuit breaker; `backoffBaseMs`/`rng` tune the\n * full-jitter sleep inserted before a same-key 429 retry (tests inject a\n * deterministic `rng` + a small base). All optional — omit for defaults.\n *\n * @internal\n */\nexport interface PoolResilienceOptions {\n breaker?: CircuitBreaker;\n backoffBaseMs?: number;\n rng?: () => number;\n /**\n * SE2 — invoked right before a 429 same-key retry backs off, so the runtime can\n * surface a `rate_limit` RunEvent. `attempt` is 1-based; `retryAfterMs` is the\n * backoff about to be waited. Best-effort observer — must not throw.\n */\n onRateLimit?: (info: { attempt: number; retryAfterMs?: number }) => void;\n}\n\n/** Decision returned by `classifyAndDecide`. */\ntype Decision = \"retry\" | \"rotate\" | \"propagate\";\n\n/**\n * Pool-aware `LlmClient`. Constructs real clients on demand via\n * `buildClient(apiKey)` — kept lazy so the pool can pick AT request\n * time (not at construction) and rotation produces a fresh client\n * each iteration.\n *\n * @internal\n */\nexport class PoolAwareLlmClient implements LlmClient {\n readonly name: string;\n\n constructor(\n private readonly pool: CredentialPool,\n private readonly buildClient: (apiKey: string) => LlmClient,\n /**\n * T3.9 — Optional override for the upper bound on how long\n * `stream()` waits for a cooldown to expire before throwing\n * `CredentialPoolExhaustedError`. Defaults to 30 s. The actual\n * wait inside `pool.waitForAvailable` is jittered (AWS Brooker\n * 2015 full-jitter), so concurrent callers stagger their\n * re-probe of the pool — preventing reconnect storms.\n *\n * Set to `0` to opt out (legacy pre-T3.9 behavior — throw on\n * first `select()`-returns-null).\n *\n * @internal\n */\n private readonly waitForAvailableMs: number = 30_000,\n resilience: PoolResilienceOptions = {},\n ) {\n this.name = `pool-aware:${pool.provider}`;\n this.breaker = resilience.breaker ?? new CircuitBreaker();\n this.backoffBaseMs = resilience.backoffBaseMs;\n this.rng = resilience.rng;\n this.onRateLimit = resilience.onRateLimit;\n }\n\n private readonly onRateLimit?: (info: { attempt: number; retryAfterMs?: number }) => void;\n\n /** M2 #60 — provider-level circuit breaker (consecutive-failure). */\n private readonly breaker: CircuitBreaker;\n private readonly backoffBaseMs: number | undefined;\n private readonly rng: (() => number) | undefined;\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: stream() must serialize pool-select → build client → first-event probe → classify → retry/rotate/propagate. Extracting helpers fragments the linear narrative; the comments above each branch keep it readable.\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n // M2 #60 — fail fast while the provider circuit is open, instead of\n // re-running the whole select→retry→rotate dance against a down provider.\n if (this.breaker.shouldSkip(this.pool.provider)) {\n throw new NetworkError(`${this.pool.provider} circuit open — failing fast`, {\n code: \"circuit_open\",\n });\n }\n let hasRetried429 = false;\n while (true) {\n if (signal.aborted) throw abortError(signal);\n\n let entry = await this.pool.select();\n if (entry === null) {\n // T3.9 — Reconnect storm prevention. Instead of throwing\n // immediately, wait (with jitter) for the earliest cooldown to\n // expire. Concurrent callers each pick a random delay within\n // the window to the earliest reset, so they wake at staggered\n // times and do not all re-hammer the upstream at the same\n // instant. `waitForAvailableMs === 0` opts out for legacy\n // callers and for unit tests that prefer the pre-T3.9\n // throw-fast contract.\n if (this.waitForAvailableMs > 0) {\n const available = await this.pool.waitForAvailable(signal, {\n maxWaitMs: this.waitForAvailableMs,\n });\n if (available) {\n entry = await this.pool.select();\n }\n }\n if (entry === null) {\n // M2 #60 — a whole-attempt terminal failure trips the breaker.\n this.breaker.recordTimeout(this.pool.provider);\n throw new CredentialPoolExhaustedError(\n `All ${this.pool.provider} credentials exhausted; next retry available at ${\n this.nextRetryHint() ?? \"unknown\"\n }`,\n { provider: this.pool.provider, nextRetryAt: this.nextRetryHint() },\n );\n }\n }\n\n // EC-D: a failure inside buildClient (e.g., invalid baseUrl) is\n // a transport-config bug, NOT a credential failure. Propagate\n // without marking the entry exhausted.\n const realClient: LlmClient = this.buildClient(entry.accessToken);\n\n const attempt = await tryFirstEvent(realClient, request, signal);\n if (attempt.kind === \"ok\") {\n // Stream started — rotation is no longer possible. A healthy start\n // closes the circuit breaker (M2 #60).\n this.breaker.recordSuccess(this.pool.provider);\n return yield* relayStream(attempt.generator, attempt.firstResult);\n }\n\n const decision = classifyAndDecide(attempt.error, hasRetried429);\n if (decision === \"retry\") {\n // D126: first 429 retries the same key. Don't mark exhausted yet.\n // M2 #60 — back off with full jitter before re-hitting the SAME key,\n // so a shared-quota thundering herd no longer burns the retry in <1ms\n // (AWS Brooker 2015). We deliberately do NOT sleep the provider's\n // `Retry-After` here: for a multi-key pool the right move on a 429 is to\n // fail this brief retry and ROTATE to a fresh key immediately (waiting\n // would defeat the pool). `Retry-After` IS honored at the pool-selection\n // level — the rotate path below sets the key's `resetAtMs` cooldown, so\n // subsequent selection skips a rate-limited key until its window passes\n // (a single-key pool then fails fast with CredentialPoolExhaustedError).\n const backoffMs = computeBackoffMs({\n attempt: 0,\n ...(this.backoffBaseMs !== undefined ? { baseMs: this.backoffBaseMs } : {}),\n ...(this.rng !== undefined ? { rng: this.rng } : {}),\n });\n // SE2 — surface a `rate_limit` RunEvent for the retry that is about to back off.\n this.onRateLimit?.({ attempt: 1, retryAfterMs: backoffMs });\n await sleepWithAbort(backoffMs, signal);\n hasRetried429 = true;\n continue;\n }\n if (decision === \"rotate\") {\n // EC-A: persistence failures during rotate must NOT abort the\n // stream. Pool state in-memory is the source of truth; disk\n // staleness self-corrects on the next successful save.\n try {\n await this.pool.markExhaustedAndRotate({\n entryId: entry.id,\n statusCode: attempt.error.metadata?.statusCode ?? inferStatusCode(attempt.error),\n ...(parseRetryAfterMs(attempt.error) !== undefined\n ? { resetAtMs: parseRetryAfterMs(attempt.error) }\n : {}),\n });\n } catch (persistErr) {\n diag(\n `[theokit-sdk] credential-pool: persist failed during rotate; continuing in-memory: ${\n persistErr instanceof Error ? persistErr.message : String(persistErr)\n }\\n`,\n );\n }\n hasRetried429 = false;\n continue;\n }\n // decision === \"propagate\" — a whole-attempt terminal failure (M2 #60).\n this.breaker.recordTimeout(this.pool.provider);\n throw attempt.error;\n }\n }\n\n /**\n * Earliest epoch ms among entries' `lastErrorResetAt` — best estimate\n * for the caller's `CredentialPoolExhaustedError.nextRetryAt`.\n */\n private nextRetryHint(): number | undefined {\n const resets = this.pool\n .list()\n .map((e) => e.lastErrorResetAt)\n .filter((v): v is number => v !== undefined);\n return resets.length === 0 ? undefined : Math.min(...resets);\n }\n}\n\n/**\n * Decision matrix per ADR D125 + D126. Pure function — testable in isolation.\n *\n * @internal\n */\nexport function classifyAndDecide(\n error: RateLimitError | AuthenticationError | NetworkError,\n hasRetried429: boolean,\n): Decision {\n // 5xx / network errors: pool doesn't help — propagate so cross-provider\n // fallback (FallbackLlmClient) can try a different provider.\n if (error instanceof NetworkError) return \"propagate\";\n\n // 401/403: rotate. No OAuth refresh in v1 (out of scope).\n if (error instanceof AuthenticationError) return \"rotate\";\n\n // RateLimitError covers 429 AND 402 (billing/quota) — distinguish via statusCode.\n const status = error.metadata?.statusCode ?? 429;\n if (status === 402) return \"rotate\"; // immediate, no retry (billing won't recover in ms)\n\n // 429: retry once, rotate on second.\n return hasRetried429 ? \"rotate\" : \"retry\";\n}\n\n/**\n * Convert provider's `retry-after` hint (seconds) into epoch ms.\n * The error mapper (D67) normalizes the header into `metadata.retryAfter`\n * (numeric seconds form only). Older formats land in `metadata.raw`.\n *\n * @internal\n */\nexport function parseRetryAfterMs(\n error: RateLimitError | AuthenticationError | NetworkError,\n): number | undefined {\n const seconds = error.metadata?.retryAfter;\n if (typeof seconds === \"number\" && seconds > 0) {\n return Date.now() + seconds * 1000;\n }\n return undefined;\n}\n\nfunction inferStatusCode(error: RateLimitError | AuthenticationError | NetworkError): number {\n if (error instanceof AuthenticationError) return 401;\n if (error instanceof RateLimitError) return 429;\n return 0;\n}\n\nfunction abortError(signal: AbortSignal): Error {\n if (signal.reason instanceof Error) return signal.reason;\n return new Error(\"AbortError\");\n}\n","/**\n * OpenAI **Responses API** transport (`apiMode: \"responses_api\"`).\n *\n * The SDK's `ApiMode` declared `\"responses_api\"` but shipped NO transport — `selectTransport` threw\n * `transport_unavailable` (whose message even names `@theokit-transport-responses_api`). This IS that\n * transport: an `LlmClient` that POSTs the Responses-API body to `${baseUrl}/responses` and translates the\n * SSE event stream into `LlmEvent`/`LlmFinish`. It powers the ChatGPT Codex backend\n * (`https://chatgpt.com/backend-api/codex/responses`) and any responses-API provider.\n *\n * The request-body shape and the SSE event names/fields are ADAPTED FROM OpenCode (MIT © 2025 opencode —\n * https://github.com/sst/opencode: `packages/llm/src/protocols/openai-responses.ts`). OpenCode's engine is\n * Effect-based with an elaborate lifecycle/tool-stream state machine; this is a faithful port of the PROTOCOL\n * shape (event names, field access, terminal/usage handling) retargeted to theokit's much smaller\n * `LlmClient` contract (`name` + `stream → AsyncGenerator<LlmEvent, LlmFinish>`). MIT permits this with attribution.\n *\n * `extraHeaders` (unused by the chat-completions transport until now) + `baseUrl` are consumed here; a `fetch`\n * override lets a host inject a refresh-aware fetch (dynamic `ChatGPT-Account-Id` / `session-id`, mid-turn\n * token refresh) — mirroring `OpenAIClient`.\n */\nimport { mapOpenAICompatibleError } from \"../error-mappers/openai-compatible.js\";\nimport { collapseSystemText, makeLlmFinish, parseToolArguments } from \"./finish.js\";\nimport { parseSseStream } from \"./sse.js\";\nimport { toStringToolResultContent } from \"./tool-result-content.js\";\nimport type {\n LlmClient,\n LlmEvent,\n LlmFinish,\n LlmMessage,\n LlmRequest,\n LlmStopReason,\n LlmToolCallPart,\n} from \"./types.js\";\n\nexport interface ResponsesApiClientOptions {\n apiKey: string;\n /** e.g. `https://chatgpt.com/backend-api/codex`; the client POSTs `${baseUrl}/responses`. */\n baseUrl?: string;\n /** Static headers the profile declares (e.g. `ChatGPT-Account-Id`, `originator`). */\n extraHeaders?: Record<string, string>;\n /** Injected fetch (refresh-aware / dynamic headers). Defaults to global `fetch`. */\n fetch?: typeof fetch;\n providerName?: string;\n}\n\n/** Translate an `LlmMessage` into the Responses-API `input[]` items it contributes. */\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nfunction messageToInputItems(message: LlmMessage): unknown[] {\n const items: unknown[] = [];\n if (message.role === \"user\") {\n const content: unknown[] = [];\n for (const part of message.content) {\n if (part.type === \"text\") {\n content.push({ type: \"input_text\", text: part.text });\n } else if (part.type === \"image\") {\n const url =\n part.source.type === \"base64\"\n ? `data:${part.source.media_type};base64,${part.source.data}`\n : part.source.url;\n content.push({ type: \"input_image\", image_url: url });\n } else if (part.type === \"tool_result\") {\n items.push({\n type: \"function_call_output\",\n call_id: part.toolUseId,\n output: toStringToolResultContent(part.content, \"openai-responses\"),\n });\n }\n }\n if (content.length > 0) items.push({ role: \"user\", content });\n return items;\n }\n if (message.role === \"assistant\") {\n const content: unknown[] = [];\n for (const part of message.content) {\n if (part.type === \"text\") {\n content.push({ type: \"output_text\", text: part.text });\n } else if (part.type === \"tool_use\") {\n items.push({\n type: \"function_call\",\n call_id: part.id,\n name: part.name,\n arguments: JSON.stringify(part.input),\n });\n }\n }\n if (content.length > 0) items.push({ role: \"assistant\", content });\n return items;\n }\n // system role rarely appears here (system travels on `request.system`); fold to text.\n const text = message.content\n .filter((p) => p.type === \"text\")\n .map((p) => (p as { text: string }).text)\n .join(\"\\n\");\n if (text.length > 0) items.push({ role: \"system\", content: text });\n return items;\n}\n\n/** Build the Responses-API request body from an `LlmRequest`. */\nexport function buildResponsesBody(request: LlmRequest): Record<string, unknown> {\n const input: unknown[] = [];\n for (const message of request.messages) {\n for (const item of messageToInputItems(message)) input.push(item);\n }\n // The Responses API wants the BARE model id (`gpt-5.4`), never a `provider/model` id. The router\n // normally strips the provider prefix before the transport; strip here too as defense-in-depth so an\n // unstripped `openai-chatgpt/gpt-5.4` can never reach the backend as a 400 (decoupled from the router's\n // provider-inference heuristics).\n const slash = request.model.lastIndexOf(\"/\");\n const model = slash >= 0 ? request.model.slice(slash + 1) : request.model;\n const body: Record<string, unknown> = { model, input, stream: true, store: false };\n const instructions = collapseSystemText(request.system);\n if (instructions.length > 0) body.instructions = instructions;\n if (request.maxTokens !== undefined) body.max_output_tokens = request.maxTokens;\n if (request.temperature !== undefined) body.temperature = request.temperature;\n const tools = (request.tools ?? []).map((tool) => ({\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n strict: false,\n }));\n if (tools.length > 0) body.tools = tools;\n if (request.reasoning !== undefined) body.reasoning = { effort: request.reasoning.effort };\n return body;\n}\n\ninterface ResponsesEvent {\n type?: string;\n delta?: string;\n item_id?: string;\n item?: {\n type?: string;\n id?: string;\n call_id?: string;\n name?: string;\n arguments?: string;\n };\n response?: {\n usage?: {\n input_tokens?: number;\n output_tokens?: number;\n output_tokens_details?: { reasoning_tokens?: number };\n };\n error?: { message?: string };\n };\n message?: string;\n}\n\nexport class ResponsesApiClient implements LlmClient {\n readonly name: string;\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: ResponsesApiClientOptions) {\n this.name = options.providerName ?? \"openai-responses\";\n this.baseUrl = (options.baseUrl ?? \"https://api.openai.com/v1\").replace(/\\/+$/, \"\");\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: the SSE dispatch (text / reasoning / tool-call add+delta+done / terminal+usage / error) is one cohesive state machine, mirroring OpenAIStreamAccumulator.consume.\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n const providerId = this.options.providerName ?? \"openai\";\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n accept: \"text/event-stream\",\n authorization: `Bearer ${this.options.apiKey}`,\n ...(this.options.extraHeaders ?? {}),\n };\n const url = `${this.baseUrl}/responses`;\n\n const response = await this.fetchImpl(url, {\n method: \"POST\",\n signal,\n headers,\n body: JSON.stringify(buildResponsesBody(request)),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n let body: unknown = text;\n try {\n body = JSON.parse(text);\n } catch {\n /* not JSON */\n }\n throw mapOpenAICompatibleError({\n providerId,\n status: response.status,\n body,\n headers: response.headers,\n endpoint: \"/responses\",\n });\n }\n\n let text = \"\";\n const toolCalls: LlmToolCallPart[] = [];\n let stopReason: LlmStopReason = \"end_turn\";\n let inputTokens: number | undefined;\n let outputTokens: number | undefined;\n let reasoningTokens: number | undefined;\n // function-call accumulation keyed by the streamed output-item id.\n const pending: Record<string, { callId: string; name: string; args: string }> = {};\n\n if (response.body !== null) {\n for await (const record of parseSseStream(response.body, signal)) {\n if (record.data === \"[DONE]\") break;\n let event: ResponsesEvent;\n try {\n event = JSON.parse(record.data) as ResponsesEvent;\n } catch {\n continue;\n }\n const t = event.type;\n if (t === \"response.output_text.delta\") {\n const d = event.delta ?? \"\";\n if (d.length > 0) {\n text += d;\n yield { type: \"text_delta\", text: d };\n }\n } else if (\n t === \"response.reasoning_summary_text.delta\" ||\n t === \"response.reasoning_text.delta\"\n ) {\n const d = event.delta ?? \"\";\n if (d.length > 0) yield { type: \"reasoning_delta\", text: d };\n } else if (t === \"response.output_item.added\" && event.item?.type === \"function_call\") {\n const id = event.item.id ?? event.item.call_id ?? \"call-0\";\n pending[id] = {\n callId: event.item.call_id ?? id,\n name: event.item.name ?? \"\",\n args: event.item.arguments ?? \"\",\n };\n } else if (t === \"response.function_call_arguments.delta\") {\n const c = event.item_id !== undefined ? pending[event.item_id] : undefined;\n if (c !== undefined) c.args += event.delta ?? \"\";\n } else if (t === \"response.output_item.done\" && event.item?.type === \"function_call\") {\n const id = event.item.id ?? event.item.call_id ?? \"call-0\";\n const c = pending[id] ?? {\n callId: event.item.call_id ?? id,\n name: event.item.name ?? \"\",\n args: event.item.arguments ?? \"\",\n };\n const rawArgs = event.item.arguments ?? c.args;\n const call: LlmToolCallPart = {\n type: \"tool_use\",\n id: c.callId,\n name: c.name.length > 0 ? c.name : (event.item.name ?? \"\"),\n input: parseToolArguments(rawArgs),\n };\n // theokit#144: the call is carried by `LlmFinish.toolCalls` below. It used to also be\n // yielded as a `tool_use` event that no consumer read — see the `LlmEvent` docblock for\n // why the live tool channel is `onDelta`, not this stream.\n toolCalls.push(call);\n delete pending[id];\n } else if (t === \"response.completed\" || t === \"response.incomplete\") {\n const usage = event.response?.usage;\n if (usage !== undefined) {\n inputTokens = usage.input_tokens;\n outputTokens = usage.output_tokens;\n reasoningTokens = usage.output_tokens_details?.reasoning_tokens;\n }\n stopReason = t === \"response.incomplete\" ? \"max_tokens\" : \"end_turn\";\n } else if (t === \"response.failed\" || t === \"error\") {\n // Never echo a raw provider body — report the message only. Map to a typed provider error.\n const msg = event.response?.error?.message ?? event.message ?? \"responses stream failed\";\n yield { type: \"error\", message: msg };\n throw mapOpenAICompatibleError({\n providerId,\n status: 502,\n body: { error: { message: msg } },\n headers: response.headers,\n endpoint: \"/responses\",\n });\n }\n }\n }\n\n if (toolCalls.length > 0 && stopReason === \"end_turn\") stopReason = \"tool_use\";\n // theokit#144: `stopReason` is returned on the finish value, not yielded as an event.\n return makeLlmFinish({\n stopReason,\n text,\n toolCalls,\n inputTokens,\n outputTokens,\n reasoningTokens,\n });\n }\n}\n","/**\n * The error to throw when an `AbortSignal` is already aborted.\n *\n * Extracted in M93 (adversarial review, L1) when this would have been the **third** copy — rule of 3.\n * `pool-aware-client.ts` and `fallback-client.ts` kept the same function with slightly different string\n * fallbacks; this version preserves the more informative of the two.\n *\n * Preferring `signal.reason` over a raw `new Error(\"aborted\")` is what `error-handling.md` § 2 asks for: a\n * cancellation carries the canceller's reason, and replacing it with generic text erases the cause.\n *\n * @internal\n */\nexport function abortError(signal: AbortSignal): Error {\n if (signal.reason instanceof Error) return signal.reason;\n return new Error(signal.reason !== undefined ? String(signal.reason) : \"aborted\");\n}\n","/**\n * M93 — retry for the **single-key** path, which had none.\n *\n * ## The defect\n *\n * `buildPoolOrSingle` returns a `PoolAwareLlmClient` — with circuit breaker, full-jitter backoff,\n * `Retry-After` handling and rotation — when there are **>= 2** keys. With **one**, it returns the\n * raw transport. A consumer resolving exactly one credential (the common case) never gets a retry:\n * a 429 after eight tool calls kills the turn.\n *\n * The asymmetry has no domain justification. **A pool of 1 key is a pool of size 1** — what changes\n * between 1 and 2 keys is whether there is somewhere to rotate to, not whether resilience exists.\n *\n * ## Why a decorator, and why it is cheap\n *\n * `computeBackoffMs`, `sleepWithAbort` and `CircuitBreaker` **are already independent modules** —\n * `PoolAwareLlmClient` imports them, it does not contain them. So this is composition, not a\n * rewrite (parsimony rung 4: reuse what is already installed). What was missing was not the logic;\n * it was the logic being reachable outside the pool path.\n *\n * A decorator rather than a branch inside the pool: an `LlmClient` wrapping another applies to\n * **both** arms without duplicating anything, and the pool gains no degenerate one-element mode.\n *\n * ## Only transient errors are retried\n *\n * `error-handling.md` § 2 is explicit: \"external-API timeout -> retry with backoff; business-rule\n * violation -> fail immediately\". A 401 retried three times delays the error by seconds without\n * changing the outcome — and hides the real cause from the user for longer.\n *\n * @internal\n */\nimport {\n CredentialPoolExhaustedError,\n isTransientError,\n RateLimitError,\n TheokitAgentError,\n} from \"../../errors.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { abortError } from \"./abort-error.js\";\nimport { computeBackoffMs, sleepWithAbort } from \"./retry.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\n\n/** Attempt ceiling. Fixed at 3 — M93's DoD names the number. */\nexport const MAX_ATTEMPTS = 3;\n\n/**\n * Is the error transient — that is, can retrying change the outcome?\n *\n * ## Delegates to `isTransientError`, and states what it subtracts\n *\n * The SDK **already** publishes `isTransientError` — documented as \"a single source of truth rather\n * than a re-derivation\", with the explicit warning that \"It never inspects `err.message`\". The first\n * version of this function ignored both: it re-derived, by regex over the message (`/\\b4\\d\\d\\b/`).\n * Adversarial review measured the cost — `connect ECONNREFUSED 127.0.0.1:443` was classified as NOT\n * transient, because the **port** matches the regex. The network errors retry exists for were\n * exactly the ones excluded.\n *\n * Reinventing here violated parsimony rung 4 with the part already at hand. What remains of this\n * function are **three subtractions** from the owner's verdict, each with a reason:\n *\n * | Subtraction | Why |\n * |---|---|\n * | `CredentialPoolExhaustedError` | the pool already spent its own attempt and rotation budget; `nextRetryAt` is tens of seconds out. Retrying would multiply the wait by `MAX_ATTEMPTS` with no chance of success. |\n * | `code === \"circuit_open\"` | the breaker exists **in order to** fail fast; wrapping it in a retry undoes from outside the decision it just made. |\n * | `RateLimitError` with 402 | a billing quota does not resolve in milliseconds — which is why the pool's `classifyAndDecide` rotates instead of waiting. |\n *\n * The first two came out of the review's measurements: with them treated as transient, the entire\n * pool was retried 3x, and a 30 s wait became ~90 s.\n */\nexport function isRetriableError(err: unknown): boolean {\n if (!isTransientError(err)) return false;\n if (err instanceof CredentialPoolExhaustedError) return false;\n if (err instanceof TheokitAgentError && err.code === \"circuit_open\") return false;\n if (err instanceof RateLimitError && err.metadata?.statusCode === 402) return false;\n return true;\n}\n\n/** The `Retry-After` normalized by the error mapper, in ms from now. */\nfunction retryAfterHintMs(err: unknown): number | undefined {\n if (!(err instanceof RateLimitError)) return undefined;\n const seconds = err.metadata?.retryAfter;\n return typeof seconds === \"number\" && seconds > 0 ? seconds * 1000 : undefined;\n}\n\n/**\n * Forwards the inner stream, flagging `state` as soon as the first event leaves.\n *\n * The flag has to live OUTSIDE the generator because the `catch` that decides about retrying is in\n * the caller — and it is that distinction (emitted or not) that separates \"a retriable failure\"\n * from \"a turn already partially delivered to the consumer\".\n */\nasync function* consume(\n gen: AsyncGenerator<LlmEvent, LlmFinish, void>,\n state: { emitted: boolean },\n): AsyncGenerator<LlmEvent, LlmFinish, void> {\n let step = await gen.next();\n while (step.done !== true) {\n state.emitted = true;\n yield step.value;\n step = await gen.next();\n }\n return step.value;\n}\n\n/** Worth retrying? Not if it already emitted, not on the last attempt, not if the error is final. */\nfunction canRetry(err: unknown, emitted: boolean, attempt: number): boolean {\n if (emitted) return false;\n if (attempt === MAX_ATTEMPTS - 1) return false;\n return isRetriableError(err);\n}\n\n/**\n * ## Why there is NO circuit breaker here\n *\n * The package's `CircuitBreaker` is **keyed by credential** (`recordSuccess(key)` /\n * `recordTimeout(key)`): it exists so the pool can mark a key unhealthy and **skip** to another.\n * With a single key there is nowhere to skip to, so a breaker here would record state nobody reads.\n *\n * Parsimony rung 1 — \"does this need to exist?\". No: it would be ceremony with resilience's name on\n * it. What protects the single-key path is the attempt ceiling and the backoff, and both are below.\n */\nexport class RetryingLlmClient implements LlmClient {\n readonly #inner: LlmClient;\n readonly #rng: (() => number) | undefined;\n\n constructor(inner: LlmClient, opts?: { rng?: () => number }) {\n this.#inner = inner;\n this.#rng = opts?.rng;\n }\n\n /**\n * The decorated client. Public by the same convention as `FaultInjectingLlmClient.inner`: the\n * router's wiring tests assert `instanceof PoolAwareLlmClient` and need to see through the\n * decorators. Without this, adding a decorator breaks tests whose intent is still valid — which is\n * exactly what M93 did to 4 pre-existing tests.\n */\n get inner(): LlmClient {\n return this.#inner;\n }\n\n get name(): string {\n return this.#inner.name;\n }\n\n /**\n * Waits out attempt `n`'s backoff, honoring the provider's `Retry-After` when one arrived.\n *\n * Its own method because `stream` is a generator with a nested loop, and inlining the conditional\n * option assembly here pushed cognitive complexity to 19 (project ceiling: 10). The body of\n * `stream` stays nothing but the attempt machine.\n */\n async #waitBackoff(err: unknown, attempt: number, signal: AbortSignal): Promise<void> {\n const hint = retryAfterHintMs(err);\n const ms = computeBackoffMs({\n attempt,\n ...(hint !== undefined ? { retryAfterMs: hint } : {}),\n ...(this.#rng !== undefined ? { rng: this.#rng } : {}),\n });\n // theokit-sdk#165 — announce the attempt BEFORE sleeping.\n //\n // Without this signal a retry is indistinguishable from no retry, and the issue shows what that\n // costs: a 429 in ~3s led to the conclusion that the retry path was never reached, when it was.\n // The backoff is full-jitter (`floor(random() * ceiling)`), so three attempts fit inside\n // milliseconds and vanish into the response latency — the only thing visible was the final error.\n //\n // It goes through the diagnostics channel, not stderr: the library does not own the host's\n // terminal (theokit#147). With no sink installed, silence.\n const cause = err instanceof Error ? err.name : typeof err;\n diag(\n `retry ${attempt + 1}/${MAX_ATTEMPTS} in ${String(ms)}ms — ${cause}` +\n (hint !== undefined ? ` (Retry-After: ${String(hint)}ms)` : \"\"),\n );\n await sleepWithAbort(ms, signal);\n }\n\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n let lastError: unknown;\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n if (signal.aborted) throw lastError ?? abortError(signal);\n // A failure AFTER the first event is NOT retriable: the consumer has already seen tokens, and\n // repeating would produce duplicated text — and, in the scenario that motivates M93 (a 429\n // after eight tool calls), duplicated `tool_use` blocks.\n //\n // Until M93's adversarial review this invariant lived only in the comment: the `yield` and the\n // following `gen.next()` both sat inside the `try`, so a failure mid-stream retried the whole\n // turn. Measured: the consumer received `[tok1, tok2]` across 2 attempts. The comment asserted\n // a guarantee the code did not provide — the rot class `adr-governance.md` § 5 residue 2\n // enumerates.\n const state = { emitted: false };\n try {\n return yield* consume(this.#inner.stream(request, signal), state);\n } catch (err) {\n lastError = err;\n if (!canRetry(err, state.emitted, attempt)) throw err;\n await this.#waitBackoff(err, attempt, signal);\n }\n }\n throw lastError ?? new Error(\"retries exhausted with no recorded error\");\n }\n}\n","/**\n * GCP Vertex AI HTTP error mapper (ADRs D67, D300).\n *\n * Vertex returns `{ error: { code, status, message, details } }` (Google\n * AIP-193 standard error shape).\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../../errors.js\";\nimport { buildErrorMetadata } from \"./shared.js\";\n\ninterface VertexErrorBody {\n error?: {\n code?: number;\n status?: string;\n message?: string;\n details?: unknown;\n };\n}\n\nexport interface MapVertexErrorArgs {\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\ntype VertexCode =\n | \"rate_limit\"\n | \"auth_unauthenticated\"\n | \"auth_permission\"\n | \"invalid_request\"\n | \"timeout\"\n | \"server_error\"\n | \"unknown\";\n\nconst VERTEX_RULES: ReadonlyArray<{ test: (s: number, e: string) => boolean; code: VertexCode }> = [\n { test: (s, e) => s === 429 || e === \"RESOURCE_EXHAUSTED\", code: \"rate_limit\" },\n { test: (s, e) => s === 401 || e === \"UNAUTHENTICATED\", code: \"auth_unauthenticated\" },\n { test: (s, e) => s === 403 || e === \"PERMISSION_DENIED\", code: \"auth_permission\" },\n {\n test: (s, e) =>\n s === 400 || e === \"INVALID_ARGUMENT\" || e === \"FAILED_PRECONDITION\" || e === \"NOT_FOUND\",\n code: \"invalid_request\",\n },\n { test: (s, e) => s === 408 || e === \"DEADLINE_EXCEEDED\", code: \"timeout\" },\n { test: (s) => s >= 500, code: \"server_error\" },\n];\n\nfunction classifyVertexError(args: MapVertexErrorArgs, errStatus: string): VertexCode {\n for (const rule of VERTEX_RULES) {\n if (rule.test(args.status, errStatus)) return rule.code;\n }\n return \"unknown\";\n}\n\nfunction vertexMetadata(args: MapVertexErrorArgs, code: string) {\n return buildErrorMetadata({\n provider: \"vertex\",\n endpoint: args.endpoint,\n code: code as Parameters<typeof buildErrorMetadata>[0][\"code\"],\n status: args.status,\n headers: args.headers,\n body: args.body,\n });\n}\n\nconst VERTEX_ERROR_BUILDERS: Record<\n VertexCode,\n (args: MapVertexErrorArgs, msg: string) => TheokitAgentError\n> = {\n rate_limit: (args, msg) =>\n new RateLimitError(`Vertex quota exhausted: ${msg}`, {\n metadata: vertexMetadata(args, \"rate_limit\"),\n }),\n auth_unauthenticated: (args, msg) =>\n new AuthenticationError(`Vertex unauthenticated: ${msg}`, {\n metadata: vertexMetadata(args, \"auth_failed\"),\n }),\n auth_permission: (args, msg) =>\n new AuthenticationError(`Vertex permission denied: ${msg}`, {\n metadata: vertexMetadata(args, \"auth_failed\"),\n }),\n invalid_request: (args, msg) =>\n new ConfigurationError(`Vertex validation: ${msg}`, {\n metadata: vertexMetadata(args, \"invalid_request\"),\n }),\n timeout: (args, msg) =>\n new NetworkError(`Vertex timeout: ${msg}`, { metadata: vertexMetadata(args, \"timeout\") }),\n server_error: (args, msg) =>\n new NetworkError(`Vertex server error: ${msg}`, {\n metadata: vertexMetadata(args, \"server_error\"),\n }),\n unknown: (args, msg) =>\n new UnknownAgentError(`Vertex unknown: ${msg}`, { metadata: vertexMetadata(args, \"unknown\") }),\n};\n\nexport function mapVertexError(args: MapVertexErrorArgs): TheokitAgentError {\n const parsed = parseBody(args.body);\n const errStatus = parsed.error?.status ?? \"\";\n const message = parsed.error?.message ?? \"Vertex request failed\";\n const code = classifyVertexError(args, errStatus);\n return VERTEX_ERROR_BUILDERS[code](args, message);\n}\n\nfunction parseBody(body: unknown): VertexErrorBody {\n if (body !== null && typeof body === \"object\") return body as VertexErrorBody;\n if (typeof body === \"string\") {\n try {\n return JSON.parse(body) as VertexErrorBody;\n } catch {\n return {};\n }\n }\n return {};\n}\n","/**\n * Vertex AI access token + config resolution (ADRs D288, D295).\n *\n * Uses `google-auth-library` (required peer dep) for ADC discovery:\n * 1. `GOOGLE_APPLICATION_CREDENTIALS` env (path to Service Account JSON)\n * 2. `gcloud auth application-default login` cached credentials\n * 3. Metadata server (GCE/GKE/Cloud Run/Cloud Functions)\n * 4. Workload Identity Federation (WIF; configured via Service Account JSON)\n *\n * EC-3 absorbed: differentiate \"peer dep missing\" (throws ConfigurationError\n * with install hint) from \"no credentials in ADC chain\" (returns undefined\n * so caller can throw a clearer downstream error).\n *\n * @internal\n */\n\nimport { createRequire } from \"node:module\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { diag } from \"../diagnostics.js\";\n\ninterface GoogleAuthClient {\n getAccessToken: () => Promise<{ token: string | null }>;\n}\n\ninterface GoogleAuthLib {\n GoogleAuth: new (opts: {\n scopes: string[];\n }) => {\n getClient: () => Promise<GoogleAuthClient>;\n };\n}\n\nlet cachedAuthClient: GoogleAuthClient | undefined;\n\nconst SCOPE_CLOUD_PLATFORM = \"https://www.googleapis.com/auth/cloud-platform\";\n\nexport async function resolveVertexAccessToken(): Promise<string | undefined> {\n if (cachedAuthClient === undefined) {\n cachedAuthClient = await getAuthClientOrThrow();\n }\n try {\n const result = await cachedAuthClient.getAccessToken();\n return result.token ?? undefined;\n } catch {\n // ADC chain exhausted — caller (router) emits the helpful error.\n return undefined;\n }\n}\n\nasync function getAuthClientOrThrow(): Promise<GoogleAuthClient> {\n let mod: GoogleAuthLib;\n try {\n const r = createRequire(import.meta.url);\n mod = r(\"google-auth-library\") as GoogleAuthLib;\n } catch (err) {\n // EC-3: differentiate module-not-found from runtime ADC failure.\n const isModuleMissing =\n err instanceof Error &&\n (err.message.includes(\"Cannot find module\") ||\n (err as { code?: string }).code === \"MODULE_NOT_FOUND\");\n if (isModuleMissing) {\n throw new ConfigurationError(\n \"Vertex provider requires `google-auth-library`. Install: `pnpm add google-auth-library`.\",\n { code: \"auth_failed\", cause: err },\n );\n }\n throw err;\n }\n try {\n const auth = new mod.GoogleAuth({ scopes: [SCOPE_CLOUD_PLATFORM] });\n return await auth.getClient();\n } catch (err) {\n // ADC chain exhausted at client construction time — return a stub that\n // forces resolveVertexAccessToken to return undefined.\n diag(\n `[theokit-sdk] Vertex ADC initialization failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n return { getAccessToken: async () => ({ token: null }) };\n }\n}\n\n/** Resolve project id via env vars (env-only in v1). */\nexport function resolveVertexProjectId(): string | undefined {\n return (\n process.env.GOOGLE_CLOUD_PROJECT ??\n process.env.GOOGLE_CLOUD_PROJECT_ID ??\n process.env.GCLOUD_PROJECT\n );\n}\n\n/** Resolve Vertex location (region) from env; defaults to `us-central1`. */\nexport function resolveVertexLocation(): string {\n return process.env.GOOGLE_CLOUD_LOCATION ?? process.env.CLOUD_ML_REGION ?? \"us-central1\";\n}\n\n/** Test seam — reset cached auth client. */\nexport function __resetVertexAuth(): void {\n cachedAuthClient = undefined;\n}\n\n/** Test seam — inject a custom client for unit tests. */\nexport function __setVertexAuthClientForTests(client: GoogleAuthClient | undefined): void {\n cachedAuthClient = client;\n}\n","/**\n * GCP Vertex AI client for Anthropic Messages (Adoption Roadmap #8; ADRs\n * D292, D293).\n *\n * v1 uses `:rawPredict` (non-streaming). Streaming via `:streamRawPredict`\n * with SSE follows the same shape but is gated behind a future iteration —\n * v1 returns the full response as a single delta to keep the streaming\n * interface contract.\n *\n * Body massage (D292):\n * - inject `anthropic_version: \"vertex-2023-10-16\"`\n * - strip `model` from body (goes in URL)\n * - strip `stream` from body\n *\n * Uses native `fetch` only — no `@anthropic-ai/vertex-sdk` (D294).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { mapVertexError } from \"../error-mappers/vertex.js\";\nimport { resolveVertexBaseUrl, stripVertexPrefix } from \"../providers/builtin/vertex.js\";\nimport {\n buildAnthropicCommonBody,\n handleAnthropicResponse,\n postAnthropicRequest,\n} from \"./anthropic-shared.js\";\nimport { makeLlmFinish } from \"./finish.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\nimport {\n resolveVertexAccessToken,\n resolveVertexLocation,\n resolveVertexProjectId,\n} from \"./vertex-auth.js\";\n\nexport interface VertexAnthropicClientOptions {\n /** When undefined, resolved lazily via `resolveVertexProjectId()`. */\n projectId?: string;\n /** When undefined, resolved lazily via `resolveVertexLocation()`. */\n location?: string;\n /**\n * OAuth access token. When provided, used as-is. When empty/undefined,\n * resolved lazily per request via `resolveVertexAccessToken()` (D288).\n */\n apiKey?: string;\n fetch?: typeof fetch;\n}\n\nexport class VertexAnthropicClient implements LlmClient {\n readonly name = \"vertex_anthropic\";\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: VertexAnthropicClientOptions) {\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n private resolveProjectOrThrow(): string {\n const projectId = this.options.projectId ?? resolveVertexProjectId();\n if (projectId !== undefined) return projectId;\n throw new ConfigurationError(\n \"Vertex requires a project id. Set GOOGLE_CLOUD_PROJECT env var or run `gcloud config set project <id>`.\",\n { code: \"auth_failed\" },\n );\n }\n\n private async resolveTokenOrThrow(): Promise<string> {\n const fromOpts = this.options.apiKey;\n if (fromOpts !== undefined && fromOpts.length > 0) return fromOpts;\n const fromAdc = await resolveVertexAccessToken();\n if (fromAdc !== undefined && fromAdc.length > 0) return fromAdc;\n throw new ConfigurationError(\n \"Vertex could not resolve an access token. Run `gcloud auth application-default login` or set GOOGLE_APPLICATION_CREDENTIALS to a service-account JSON path.\",\n { code: \"auth_failed\" },\n );\n }\n\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n const projectId = this.resolveProjectOrThrow();\n const location = this.options.location ?? resolveVertexLocation();\n const accessToken = await this.resolveTokenOrThrow();\n const baseUrl = resolveVertexBaseUrl({ projectId, location, modelDialect: \"anthropic\" });\n const bareModel = stripVertexPrefix(request.model);\n const endpoint = `/models/${encodeURIComponent(bareModel)}:rawPredict`;\n const url = `${baseUrl}${endpoint}`;\n\n const response = await postAnthropicRequest({\n fetchImpl: this.fetchImpl,\n url,\n token: accessToken,\n body: buildVertexAnthropicBody(request),\n signal,\n });\n\n const consumed = await handleAnthropicResponse({\n response,\n endpoint,\n errorMapper: mapVertexError,\n });\n if (consumed.text.length > 0) yield { type: \"text_delta\", text: consumed.text };\n return makeLlmFinish(consumed);\n }\n}\n\nfunction buildVertexAnthropicBody(request: LlmRequest): Record<string, unknown> {\n // D292: anthropic_version is REQUIRED in body (not header) and `model` is stripped.\n return {\n anthropic_version: \"vertex-2023-10-16\",\n ...buildAnthropicCommonBody(request),\n };\n}\n","/**\n * GCP Vertex AI Gemini client (Adoption Roadmap #8; ADR D291).\n *\n * Uses the **OpenAI-compat** endpoint:\n * POST https://{LOCATION}-aiplatform.googleapis.com/v1/projects/{P}/locations/{L}/endpoints/openapi/chat/completions\n *\n * Wraps `OpenAIClient` with the Vertex baseUrl + lazy OAuth token from\n * `google-auth-library` (D288). Limitation: Vertex silently drops\n * unsupported OpenAI params (D264-style trade-off).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { resolveVertexBaseUrl } from \"../providers/builtin/vertex.js\";\nimport { OpenAIClient } from \"./openai.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\nimport {\n resolveVertexAccessToken,\n resolveVertexLocation,\n resolveVertexProjectId,\n} from \"./vertex-auth.js\";\n\nexport interface VertexGeminiClientOptions {\n /** When undefined, resolved lazily via `resolveVertexProjectId()`. */\n projectId?: string;\n /** When undefined, resolved lazily via `resolveVertexLocation()`. */\n location?: string;\n /** When non-empty, used as-is. Otherwise resolved lazily via ADC. */\n apiKey?: string;\n fetch?: typeof fetch;\n}\n\nexport class VertexGeminiClient implements LlmClient {\n readonly name = \"vertex_gemini\";\n\n constructor(private readonly options: VertexGeminiClientOptions) {}\n\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n // EC-1 absorbed: helpful errors when projectId / token missing.\n const projectId = this.options.projectId ?? resolveVertexProjectId();\n if (projectId === undefined) {\n throw new ConfigurationError(\n \"Vertex requires a project id. Set GOOGLE_CLOUD_PROJECT env var or run \" +\n \"`gcloud config set project <id>`.\",\n { code: \"auth_failed\" },\n );\n }\n const location = this.options.location ?? resolveVertexLocation();\n const accessToken =\n this.options.apiKey !== undefined && this.options.apiKey.length > 0\n ? this.options.apiKey\n : await resolveVertexAccessToken();\n if (accessToken === undefined || accessToken.length === 0) {\n throw new ConfigurationError(\n \"Vertex could not resolve an access token. Run \" +\n \"`gcloud auth application-default login` or set \" +\n \"GOOGLE_APPLICATION_CREDENTIALS to a service-account JSON path.\",\n { code: \"auth_failed\" },\n );\n }\n\n // Vertex OpenAI-compat URL: baseUrl includes `.../endpoints/openapi`.\n // OpenAIClient appends `/v1/chat/completions` which gives the wrong path —\n // so we strip the `/v1/` suffix from our baseUrl construction by using\n // the parent URL and letting OpenAIClient add the suffix back.\n //\n // Resolved baseUrl (target):\n // .../endpoints/openapi/chat/completions\n // OpenAIClient builds:\n // {baseUrl}/v1/chat/completions\n // So we need baseUrl = `.../endpoints/openapi-no-suffix` such that\n // `{baseUrl}/v1/chat/completions` = `.../endpoints/openapi/chat/completions`.\n // That's not achievable via simple concat; the cleanest path is to\n // delegate directly using a custom URL — but to keep the existing\n // OpenAIClient code-path, we set baseUrl so that the suffix is correct\n // by mounting \"openapi\" as the leaf and letting `/v1/chat/completions`\n // append. Vertex's documented path is exactly:\n // .../endpoints/openapi/chat/completions (NO /v1)\n // We achieve this by providing a base ending in `/endpoints` and\n // re-mapping `/v1/chat/completions` → `/openapi/chat/completions`\n // via a custom URL builder client.\n //\n // For v1 we ship a minimal own client that targets the exact endpoint.\n const baseUrl = resolveVertexBaseUrl({ projectId, location, modelDialect: \"gemini\" });\n const url = `${baseUrl}/chat/completions`;\n\n // Reuse OpenAIClient by injecting a baseUrl that matches its `/v1/chat/completions` suffix.\n // To avoid that suffix mismatch, we bypass OpenAIClient.stream() entirely and\n // do a direct fetch — but Gemini's response shape IS OpenAI shape, so we\n // borrow OpenAIClient's accumulator via composition: pre-build the body,\n // then hand off to OpenAIClient with a synthetic baseUrl whose `/v1/chat/completions`\n // suffix lands on our actual endpoint.\n //\n // Simplest: create a wrapper fetch that rewrites the URL before delegating.\n const innerFetch = this.options.fetch ?? fetch;\n const rewriteFetch: typeof fetch = (input, init) => {\n // OpenAIClient calls `${baseUrl}/v1/chat/completions`. We rewrite that to\n // the actual Vertex URL.\n const requested =\n typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.toString()\n : (input as Request).url;\n const targetUrl = requested.endsWith(\"/v1/chat/completions\") ? url : requested;\n return innerFetch(targetUrl, init);\n };\n\n // Delegate to OpenAIClient with auth + rewrite.\n const inner = new OpenAIClient({\n apiKey: accessToken,\n baseUrl: \"https://_vertex_placeholder\",\n providerName: \"vertex\",\n fetch: rewriteFetch,\n });\n return yield* inner.stream(request, signal);\n }\n}\n","/**\n * Vertex AI dispatcher (Adoption Roadmap #8; ADRs D291, D292, D301).\n *\n * `selectTransport` doesn't see the model id (the credential resolution\n * happens before request dispatch). This client inspects `request.model`\n * at stream time and delegates to either `VertexGeminiClient` (OpenAI-compat\n * for Gemini) or `VertexAnthropicClient` (`:rawPredict` for Claude).\n *\n * @internal\n */\n\nimport { inferModelDialect } from \"../providers/builtin/vertex.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\nimport { VertexAnthropicClient } from \"./vertex-anthropic.js\";\nimport { VertexGeminiClient } from \"./vertex-gemini.js\";\n\nexport interface VertexRouterClientOptions {\n apiKey?: string;\n fetch?: typeof fetch;\n}\n\nexport class VertexRouterClient implements LlmClient {\n readonly name = \"vertex\";\n\n constructor(private readonly options: VertexRouterClientOptions) {}\n\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n const dialect = inferModelDialect(request.model);\n if (dialect === \"anthropic\") {\n const inner = new VertexAnthropicClient(this.options);\n return yield* inner.stream(request, signal);\n }\n const inner = new VertexGeminiClient(this.options);\n return yield* inner.stream(request, signal);\n }\n}\n","import { ConfigurationError } from \"../../errors.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { getProviderProfile, type ProviderProfile, registerBuiltins } from \"../providers/index.js\";\nimport { AnthropicClient } from \"./anthropic.js\";\nimport { BedrockAnthropicClient } from \"./bedrock-anthropic.js\";\nimport { CredentialPool, newPooledCredential } from \"./credential-pool.js\";\nimport { currentCredentialPool } from \"./credential-pool-context.js\";\nimport type { CredentialPoolStrategy } from \"./credential-pool-types.js\";\nimport { maybeWrapWithFaultInjection } from \"./fault-injection.js\";\nimport { OllamaNativeClient } from \"./ollama-native.js\";\nimport { OpenAIClient } from \"./openai.js\";\nimport { PoolAwareLlmClient } from \"./pool-aware-client.js\";\nimport { ResponsesApiClient } from \"./responses.js\";\nimport { RetryingLlmClient } from \"./retrying-client.js\";\nimport type { LlmClient } from \"./types.js\";\nimport { VertexRouterClient } from \"./vertex-router.js\";\n\n/**\n * Provider router (T4.3, ADRs D105-D107).\n *\n * Resolves an `LlmClient` from a `ProviderProfile`. The profile is the\n * data; the transport is selected by `apiMode`. Builtins are eagerly\n * registered on first call; user plugins in `~/.theokit/plugins/\n * model-providers/` are lazy-loaded.\n *\n * @internal\n */\n\nexport type ProviderName = \"anthropic\" | \"openai\" | \"openrouter\" | (string & {});\n\nexport interface ProviderRouterOptions {\n primary: ProviderName;\n fallback?: ProviderName[];\n /** Credential pools per provider (ADRs D123-D133). Optional. */\n apiKeys?: Record<string, string[]>;\n /** Pool rotation strategy per provider. Optional; default `\"fill_first\"`. */\n credentialPoolStrategy?: Record<string, CredentialPoolStrategy>;\n /**\n * Per-run opt-in leaked-dialect safe-parse derived from the chat route\n * (theokit#58 follow-up). When `true`, the resolved profile is cloned with\n * `extractToolCallsFromContent: true` so the OpenAI-compatible transport\n * recovers Hermes `<function=…></tool_call>` dialect leaked as text. Applied\n * to the resolved chain; fail-open, so a non-leaking provider is unaffected.\n */\n extractToolCallsFromContent?: boolean;\n /**\n * SE2 — forwarded into the pool-aware client so a 429 retry surfaces a\n * `rate_limit` RunEvent. Wired from `SendOptions.onRunEvent` at the run boundary.\n */\n onRateLimit?: (info: { attempt: number; retryAfterMs?: number }) => void;\n}\n\n/**\n * Resolves the provider chain synchronously. Builtins are eagerly registered.\n * Provider plugin discovery is expected to have run upfront (e.g., via\n * Agent.create initialization) before this is called.\n */\nexport function resolveProviderChain(options: ProviderRouterOptions): LlmClient[] {\n registerBuiltins();\n return buildChain(options);\n}\n\nfunction buildChain(options: ProviderRouterOptions): LlmClient[] {\n // EC-B: warn (once) on apiKeys entries for providers we don't recognize.\n warnUnknownProvidersInApiKeys(options.apiKeys);\n\n const seen = new Set<string>();\n const clients: LlmClient[] = [];\n const addClient = (name: ProviderName): void => {\n const lowered = name.toLowerCase();\n if (seen.has(lowered)) return;\n seen.add(lowered);\n const client = buildClient(lowered, options);\n // D14: wrap every resolved client with the fault-injection decorator.\n // The wrapper is a cheap noop unless `NODE_ENV=test` AND\n // `THEOKIT_TEST_RESPONSE_OVERRIDE` are both set — production is unaffected.\n if (client !== undefined) clients.push(maybeWrapWithFaultInjection(client));\n };\n addClient(options.primary);\n for (const fallback of options.fallback ?? []) addClient(fallback);\n if (clients.length === 0) {\n throw new ConfigurationError(\n `No provider client could be resolved (primary=${options.primary}). ` +\n `Set ANTHROPIC_API_KEY or OPENAI_API_KEY / OPENROUTER_API_KEY.`,\n { code: \"provider_unresolved\" },\n );\n }\n return clients;\n}\n\nfunction buildClient(name: string, routerOptions: ProviderRouterOptions): LlmClient | undefined {\n const baseProfile = getProviderProfile(name);\n if (baseProfile === undefined) return undefined;\n // theokit#58 follow-up: per-run route opt-in clones the resolved profile with\n // the leaked-dialect recovery flag so the OpenAI-compatible transport surfaces\n // Hermes `<function=…></tool_call>` calls leaked as text. Built-in profiles\n // ship the flag off; this is the per-run enablement path.\n const profile =\n routerOptions.extractToolCallsFromContent === true &&\n baseProfile.extractToolCallsFromContent !== true\n ? { ...baseProfile, extractToolCallsFromContent: true }\n : baseProfile;\n const resilience =\n routerOptions.onRateLimit !== undefined ? { onRateLimit: routerOptions.onRateLimit } : {};\n const ambient = currentCredentialPool(name);\n if (ambient !== undefined) {\n // M93 — the THIRD arm. Found while writing the second one's test: the ambient pool also returned\n // the client without the decorator, and leaving it out would create the same asymmetry the milestone removes,\n // only on a less visible path.\n return new RetryingLlmClient(\n new PoolAwareLlmClient(\n ambient,\n (apiKey) => selectTransport(profile, apiKey),\n undefined,\n resilience,\n ),\n );\n }\n const poolKeys = filterPoolKeys(routerOptions.apiKeys?.[name]);\n const noAuthOverride = maybeBuildNoAuthTransport(profile, poolKeys);\n if (noAuthOverride !== undefined) return noAuthOverride;\n return buildPoolOrSingle({ name, profile, poolKeys, routerOptions });\n}\n\n/**\n * EC-C MUST FIX (ADR D187): `authType: \"none\"` providers ignore apiKeys.\n * Building a CredentialPool against a runtime without auth is semantically\n * meaningless; emit one-shot warn and route to the sentinel transport.\n */\nfunction maybeBuildNoAuthTransport(\n profile: ProviderProfile,\n poolKeys: string[] | undefined,\n): LlmClient | undefined {\n if (profile.authType !== \"none\" || poolKeys === undefined || poolKeys.length === 0) {\n return undefined;\n }\n warnNoAuthApiKeysIgnoredOnce(profile.name);\n const sentinel = sentinelForNoAuth(profile);\n if (sentinel === undefined) return undefined;\n return selectTransport(profile, sentinel);\n}\n\n/** Pool path for ≥2 keys; single-key fast path otherwise; sentinel fallback. */\nfunction buildPoolOrSingle(args: {\n name: string;\n profile: ProviderProfile;\n poolKeys: string[] | undefined;\n routerOptions: ProviderRouterOptions;\n}): LlmClient | undefined {\n const { name, profile, poolKeys, routerOptions } = args;\n if (poolKeys !== undefined && poolKeys.length >= 2) {\n const strategy = routerOptions.credentialPoolStrategy?.[name] ?? \"fill_first\";\n const entries = poolKeys.map((accessToken, priority) =>\n newPooledCredential({ provider: name, accessToken, priority, source: \"manual\" }),\n );\n const pool = new CredentialPool(name, entries, strategy);\n const resilience =\n routerOptions.onRateLimit !== undefined ? { onRateLimit: routerOptions.onRateLimit } : {};\n // M93 — the pool ALREADY had retry inside; the outer decorator covers what it propagates (5xx and\n // network, which `classifyAndDecide` tells it to propagate because \"the pool does not help\"). Additive: rotation\n // behavior does not change.\n return new RetryingLlmClient(\n new PoolAwareLlmClient(\n pool,\n (apiKey) => selectTransport(profile, apiKey),\n undefined,\n resilience,\n ),\n );\n }\n // 1-entry pool / single-key fast path: prefer explicit apiKeys[name] over env.\n // D182: `authType: \"none\"` providers fall back to a sentinel placeholder\n // when no key is set — transports that ignore the Authorization header still work.\n // D286/D288: `aws_bearer` / `gcp_oauth` profiles use a lazy sentinel so the\n // client can resolve real credentials at stream time (helpful error if missing).\n const apiKey =\n poolKeys?.[0] ??\n resolveApiKey(profile.envVars) ??\n sentinelForNoAuth(profile) ??\n sentinelForLazyAuth(profile);\n if (apiKey === undefined) return undefined;\n // M93 — the ONE-key arm returned the RAW transport, with no retry at all. A pool of 1 key is a\n // pool of size 1: what changes between 1 and 2 keys is whether there is somewhere to rotate to, not\n // whether resilience exists. The typical consumer resolves exactly one credential and always landed here.\n return new RetryingLlmClient(selectTransport(profile, apiKey));\n}\n\nfunction resolveBaseUrlEnvOverride(providerName: string): string | undefined {\n switch (providerName) {\n case \"openai\":\n return process.env.OPENAI_API_BASE_URL;\n case \"openrouter\":\n return process.env.OPENROUTER_API_BASE_URL;\n case \"ollama\":\n return process.env.OLLAMA_HOST;\n case \"lmstudio\":\n return process.env.LMSTUDIO_HOST;\n case \"llamacpp\":\n return process.env.LLAMACPP_HOST;\n default:\n return undefined;\n }\n}\n\n// EC-C: one-shot warn keyed by provider name.\nconst warnedNoAuthApiKeys = new Set<string>();\nfunction warnNoAuthApiKeysIgnoredOnce(provider: string): void {\n if (warnedNoAuthApiKeys.has(provider)) return;\n warnedNoAuthApiKeys.add(provider);\n diag(\n `[theokit-sdk] provider \"${provider}\" has authType: \"none\" — apiKeys ignored (no auth required for local runtime).\\n`,\n );\n}\n\n/** Test-only reset. @internal */\nexport function _resetNoAuthApiKeyWarnings(): void {\n warnedNoAuthApiKeys.clear();\n}\n\n/**\n * D182: providers declaring `authType: \"none\"` use a placeholder credential\n * so the OpenAI-compat transport keeps working. The placeholder value is\n * never sensitive — local runtimes ignore the Authorization header.\n */\nfunction sentinelForNoAuth(profile: ProviderProfile): string | undefined {\n return profile.authType === \"none\" ? profile.name : undefined;\n}\n\n/**\n * D286 / D288: providers with lazy-resolved auth (Bedrock Bearer via\n * `@aws/bedrock-token-generator`, Vertex via `google-auth-library`) may not\n * have credentials available at construction time — the client resolves\n * them per-request and throws helpful `ConfigurationError` if missing\n * (EC-1, EC-6 absorbed). Use a placeholder so the router still builds\n * the client; the user sees the helpful error on the first `agent.send`.\n */\nfunction sentinelForLazyAuth(profile: ProviderProfile): string | undefined {\n if (profile.authType === \"aws_bearer\") return \"__bedrock_lazy_token__\";\n if (profile.authType === \"gcp_oauth\") return \"__vertex_lazy_token__\";\n // M42: an oauth provider carries no static key — build the client with a lazy placeholder so its M41\n // `transform.fetch(ctx)` (which calls `resolveCredential` to obtain a freshly-refreshed bearer) owns\n // the real Authorization at stream time. Plain (api_key/none) profiles are unaffected.\n if (profile.authType === \"oauth_device_code\" || profile.authType === \"oauth_external\") {\n return \"__oauth_lazy_token__\";\n }\n return undefined;\n}\n\nfunction filterPoolKeys(keys: string[] | undefined): string[] | undefined {\n if (keys === undefined) return undefined;\n const cleaned = keys.filter((k) => typeof k === \"string\" && k.length > 0);\n return cleaned.length === 0 ? undefined : cleaned;\n}\n\nconst warnedProviders = new Set<string>();\nfunction warnUnknownProvidersInApiKeys(apiKeys: Record<string, string[]> | undefined): void {\n if (apiKeys === undefined) return;\n for (const name of Object.keys(apiKeys)) {\n if (warnedProviders.has(name)) continue;\n const profile = getProviderProfile(name);\n if (profile === undefined) {\n warnedProviders.add(name);\n diag(\n `[theokit-sdk] credential-pool: unknown provider \"${name}\" in apiKeys (no profile registered)\\n`,\n );\n }\n }\n}\n\n/** Test-only reset. @internal */\nexport function _resetCredentialPoolWarnings(): void {\n warnedProviders.clear();\n}\n\n/**\n * EC-10: resolve API key from ordered envVars list; first non-empty wins.\n */\nfunction resolveApiKey(envVars: ReadonlyArray<string>): string | undefined {\n for (const v of envVars) {\n const value = process.env[v];\n if (value !== undefined && value.length > 0) return value;\n }\n return undefined;\n}\n\n/**\n * EC-3 fix: exhaustive switch with actionable error on unsupported apiMode.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: 4-mode transport ladder (chat_completions / anthropic_messages / responses_api / bedrock) + Ollama native dispatch (D191) + per-provider envOverride is one cohesive switch — splitting hurts readability and obscures the dispatch contract.\nfunction selectTransport(profile: ProviderProfile, apiKey: string): LlmClient {\n // M41 — the optional provider `transform` seam (refresh-aware `fetch` + dynamic `headers` from the resolved\n // bearer). Invoked LAZILY, per-branch, ONLY by the transports that consume it (chat_completions +\n // responses_api) — so a transform's side effects (e.g. a token refresh) never fire for a transport that\n // ignores it (bedrock / ollama). Absent ⇒ each branch takes its byte-for-byte static path.\n const applyTransform = (): { fetch?: typeof fetch; headers?: Record<string, string> } => {\n if (profile.transform === undefined) return {};\n const ctx = { apiKey };\n return { fetch: profile.transform.fetch?.(ctx), headers: profile.transform.headers?.(ctx) };\n };\n\n /**\n * Applies the provider's transform over `opts` and returns the constructed client.\n *\n * The `chat_completions` and `anthropic_messages` arms did this IDENTICALLY, differing only in the\n * final constructor. That is duplicated KNOWLEDGE: \"apply the transform, require OAuth to be\n * resolved, and merge the dynamic headers ON TOP of the profile's static ones\" is the same rule for\n * any provider — fixing it in one arm and forgetting the other would leave one provider with a\n * refresh-aware transport and the other without, silently.\n *\n * Generic over `O` because each arm declares its own `opts` with its constructor's type\n * (`ConstructorParameters<typeof OpenAIClient>[0]` vs Anthropic's) — that is why a\n * the first attempt with a non-generic helper, declared before the `if`s, did not compile.\n */\n const comTransform = <\n O extends { fetch?: typeof fetch; extraHeaders?: Record<string, string> },\n C,\n >(\n opts: O,\n construct: (o: O) => C,\n ): C => {\n const t = applyTransform();\n assertOAuthResolved(t);\n if (t.fetch !== undefined) opts.fetch = t.fetch;\n const merged =\n profile.extraHeaders !== undefined || t.headers !== undefined\n ? { ...profile.extraHeaders, ...t.headers }\n : undefined;\n if (merged !== undefined) opts.extraHeaders = merged;\n return construct(opts);\n };\n\n // M42 review MEDIUM-1 — mirror OpenCode's auth model (packages/llm/src/route/auth.ts): a provider's auth\n // resolves to real headers at request time or FAILS with `MissingCredentialError` — it NEVER puts a\n // placeholder on the wire. theokit builds an oauth provider's client with the `__oauth_lazy_token__`\n // placeholder (so the sync router can construct it), then the provider's `transform` (the theokit analog of\n // OpenCode's `Auth.apply`) supplies the real bearer via fetch or an authorization header. If it supplies\n // neither, fail fast here with the MissingCredentialError analog instead of POSTing the placeholder upstream.\n const assertOAuthResolved = (t: {\n fetch?: typeof fetch;\n headers?: Record<string, string>;\n }): void => {\n if (apiKey !== \"__oauth_lazy_token__\") return;\n const auth = t.headers?.authorization ?? t.headers?.Authorization;\n if (t.fetch === undefined && auth === undefined) {\n throw new ConfigurationError(\n `provider \"${profile.name}\" uses OAuth (authType: ${profile.authType}) but no credential was ` +\n `resolved. Register a ProviderProfile.transform whose fetch (or headers.authorization) supplies ` +\n `the bearer — typically via resolveCredential() from \"@theokit/sdk/auth\".`,\n );\n }\n };\n\n if (profile.apiMode === \"chat_completions\") {\n // ADR D191 (T8.1 dogfood fix): Ollama tool calling REQUIRES the native\n // `/api/chat` endpoint. OpenAI-compat `/v1/chat/completions` causes\n // models to emit raw tool JSON as plain text — confirmed via peer-project\n // upstream warning and our own dogfood of telegram-pro.\n if (profile.name === \"ollama\") {\n const ollamaBase = process.env.OLLAMA_HOST ?? profile.baseUrl;\n return new OllamaNativeClient({ apiKey, baseUrl: ollamaBase });\n }\n const opts: ConstructorParameters<typeof OpenAIClient>[0] = { apiKey };\n opts.baseUrl = profile.baseUrl;\n // T1.1 (ADR D185): forward provider name so OpenAIClient can dispatch\n // Ollama-specific error mapping for ECONNREFUSED / 404-not-pulled / 503-loading.\n opts.providerName = profile.name;\n // theokit#58 follow-up: opt-in leaked-dialect safe-parse, declared per-profile (default off).\n if (profile.extractToolCallsFromContent === true) {\n opts.extractToolCallsFromContent = true;\n }\n // M45 — explicit chat-completions path override (data-only escape for unversioned shapes).\n if (profile.chatCompletionsPath !== undefined) {\n opts.chatCompletionsPath = profile.chatCompletionsPath;\n }\n if (profile.name === \"openai\" && process.env.OPENAI_ORGANIZATION !== undefined) {\n opts.organization = process.env.OPENAI_ORGANIZATION;\n }\n // Honor explicit base URL overrides for cloud providers + the local\n // `authType: \"none\"` family (D182, D188, D189). All four `_HOST` /\n // `_API_BASE_URL` vars are intentionally separate so users can mix\n // remote-box pointing without disturbing the others.\n const envOverride = resolveBaseUrlEnvOverride(profile.name);\n if (envOverride !== undefined) opts.baseUrl = envOverride;\n // M41 — feed the provider transform: `fetch` (refresh-aware transport) + `headers` merged over the\n // profile's static `extraHeaders`. OpenAIClient now honors `extraHeaders` (was ignored) — additive-safe:\n // no builtin sets it on chat_completions.\n return comTransform(opts, (o) => new OpenAIClient(o));\n }\n if (profile.apiMode === \"anthropic_messages\") {\n // Vertex sub-dispatch (D301): when profile.name === \"vertex\", route to\n // VertexRouterClient which picks Gemini vs Anthropic at stream time.\n // apiKey is either a real Bearer token (rare — caller passed it\n // explicitly) or the lazy sentinel `__vertex_lazy_token__` — strip\n // the latter so the client falls through to ADC discovery (D288).\n if (profile.name === \"vertex\") {\n const realKey = apiKey === \"__vertex_lazy_token__\" ? undefined : apiKey;\n return new VertexRouterClient(realKey !== undefined ? { apiKey: realKey } : {});\n }\n const opts: ConstructorParameters<typeof AnthropicClient>[0] = { apiKey };\n opts.baseUrl = process.env.ANTHROPIC_API_BASE_URL ?? profile.baseUrl;\n // M45 — feed the provider transform + static extraHeaders (mirror of the M41 chat_completions wiring),\n // so anthropic_messages providers can carry headers (anthropic-beta) and refresh-aware fetches (M46).\n return comTransform(opts, (o) => new AnthropicClient(o));\n }\n if (profile.apiMode === \"bedrock_anthropic\") {\n // D301: dedicated Bedrock InvokeModel client. apiKey from env when set;\n // strip the lazy sentinel so client triggers @aws/bedrock-token-generator (D287).\n const realKey = apiKey === \"__bedrock_lazy_token__\" ? undefined : apiKey;\n return new BedrockAnthropicClient(realKey !== undefined ? { apiKey: realKey } : {});\n }\n if (profile.apiMode === \"responses_api\") {\n // M40 — the OpenAI Responses-API transport (ChatGPT Codex backend + any responses provider). Consumes\n // `baseUrl` + `extraHeaders`. M41 — feeds the provider `transform`: `headers` merge over `extraHeaders`\n // (dynamic auth headers like a live `ChatGPT-Account-Id`), and `fetch` becomes the refresh-aware fetch\n // (closes the gap where `ResponsesApiClient` accepted a `fetch?` the router never passed).\n const t = applyTransform();\n assertOAuthResolved(t);\n const mergedHeaders =\n profile.extraHeaders !== undefined || t.headers !== undefined\n ? { ...profile.extraHeaders, ...t.headers }\n : undefined;\n return new ResponsesApiClient({\n apiKey,\n ...(profile.baseUrl !== undefined ? { baseUrl: profile.baseUrl } : {}),\n ...(mergedHeaders !== undefined ? { extraHeaders: mergedHeaders } : {}),\n ...(t.fetch !== undefined ? { fetch: t.fetch } : {}),\n providerName: profile.name,\n });\n }\n throw new ConfigurationError(\n `Provider \"${profile.name}\" requires apiMode \"${profile.apiMode}\" but no transport is registered. ` +\n `Install a third-party transport plugin (@theokit-transport-${profile.apiMode}) ` +\n `or use a provider with apiMode \"chat_completions\" or \"anthropic_messages\".`,\n { code: \"transport_unavailable\" },\n );\n}\n","/**\n * Provider inference helpers for the real local run — extracted from\n * `real-local-run.ts` to keep it within the G8 LoC budget and give the two\n * pure \"which provider?\" heuristics one cohesive home.\n *\n * @internal\n */\n\nimport { providerFromApiKeyPrefix } from \"../auth/api-key-prefix.js\";\nimport { getProviderProfile } from \"../providers/index.js\";\n\n/**\n * The provider a key belongs to, **restricted to providers this runtime can construct**.\n *\n * The prefix table moved to `auth/api-key-prefix.ts` and is no longer duplicated here — it was the\n * same knowledge in two places, and the copy here relied on its entries being hand-written in\n * longest-first order to be correct at all. What stays is the part that is genuinely this path's\n * policy: the local run will not name a provider it has no profile for.\n *\n * @internal\n */\nexport function inferProviderFromApiKey(apiKey: string | undefined): string | undefined {\n const provider = providerFromApiKeyPrefix(apiKey);\n if (provider === undefined) return undefined;\n return getProviderProfile(provider) === undefined ? undefined : provider;\n}\n\n/**\n * The default primary provider from the environment: the first of\n * ANTHROPIC / OPENAI / OPENROUTER with a non-empty key, else `openai`.\n *\n * @internal\n */\nexport function detectPrimaryProvider(): string {\n if (process.env.ANTHROPIC_API_KEY !== undefined && process.env.ANTHROPIC_API_KEY.length > 0) {\n return \"anthropic\";\n }\n if (process.env.OPENAI_API_KEY !== undefined && process.env.OPENAI_API_KEY.length > 0) {\n return \"openai\";\n }\n if (process.env.OPENROUTER_API_KEY !== undefined && process.env.OPENROUTER_API_KEY.length > 0) {\n return \"openrouter\";\n }\n return \"openai\";\n}\n","/**\n * T2.2 — Provider-agnostic compression-model registry (ADR D440).\n *\n * Resolves a cheaper-tier summarization model in the SAME vendor family\n * as the agent's main model. Provider-agnostic by design: a consumer\n * running on Anthropic-only / Ollama-only / Bedrock-only never needs\n * to provision a second vendor's key for the compression aux-LLM.\n *\n * Resolution algorithm:\n *\n * 1. Exact match in `EXACT_REGISTRY` → cheaper-tier id (most cases).\n * 2. Wildcard match in `WILDCARD_REGISTRY` (`*` suffix in key) →\n * swap matched suffix (Bedrock region-prefixed variants).\n * 3. Provider in `NO_AUTH_PROVIDERS` (Ollama / LM Studio / llama.cpp)\n * → return SAME model id (local — cost N/A; running the same\n * model for summarization costs only the round-trip latency,\n * acceptable in dev/local mode).\n * 4. No match → throw `CompressionModelUnresolvedError` with the\n * actionable message naming the model + override path + the\n * registry-PR remediation hint.\n *\n * Step 1 of T2.2 (compression-helpers wire). Step 2 wires this into\n * `compression-config.ts`. Step 3 builds the OTel-instrumented aux\n * client. Step 4 wires into `loop.ts` ContextWindowExceededError catch.\n *\n * @internal\n */\n\n/**\n * Exact `agent-model → compression-model` map. Most cases land here.\n * Entries MUST keep cheaper-tier model within the SAME vendor family\n * as the key (Unbreakable Rule 9 — provider-agnostic).\n */\nconst EXACT_REGISTRY: ReadonlyMap<string, string> = new Map([\n // OpenAI family\n [\"openai/gpt-4o\", \"openai/gpt-4o-mini\"],\n [\"openai/gpt-4-turbo\", \"openai/gpt-4o-mini\"],\n [\"openai/gpt-4\", \"openai/gpt-4o-mini\"],\n [\"openai/o1-preview\", \"openai/gpt-4o-mini\"],\n [\"openai/o1\", \"openai/gpt-4o-mini\"],\n [\"openai/o3\", \"openai/gpt-4o-mini\"],\n [\"openai/o3-mini\", \"openai/gpt-4o-mini\"],\n // Anthropic family\n [\"anthropic/claude-opus-4\", \"anthropic/claude-3-5-haiku-latest\"],\n [\"anthropic/claude-sonnet-4\", \"anthropic/claude-3-5-haiku-latest\"],\n [\"anthropic/claude-3-5-sonnet\", \"anthropic/claude-3-5-haiku-latest\"],\n [\"anthropic/claude-3-5-sonnet-latest\", \"anthropic/claude-3-5-haiku-latest\"],\n [\"anthropic/claude-3-opus\", \"anthropic/claude-3-haiku\"],\n [\"anthropic/claude-3-sonnet\", \"anthropic/claude-3-haiku\"],\n // Vertex (Gemini + Anthropic-on-Vertex)\n [\"vertex/gemini-1.5-pro\", \"vertex/gemini-1.5-flash\"],\n [\"vertex/gemini-2.0-pro\", \"vertex/gemini-1.5-flash\"],\n [\"vertex/claude-3-5-sonnet\", \"vertex/claude-3-5-haiku\"],\n [\"vertex/claude-3-opus\", \"vertex/claude-3-haiku\"],\n // OpenRouter (preserve openrouter prefix, swap tier within same vendor)\n [\"openrouter/openai/gpt-4o\", \"openrouter/openai/gpt-4o-mini\"],\n [\"openrouter/openai/gpt-4-turbo\", \"openrouter/openai/gpt-4o-mini\"],\n [\"openrouter/anthropic/claude-3-5-sonnet\", \"openrouter/anthropic/claude-3-5-haiku\"],\n [\"openrouter/anthropic/claude-opus-4\", \"openrouter/anthropic/claude-3-5-haiku\"],\n]);\n\n/**\n * Wildcard `agent-model-prefix* → compression-model-prefix*` map.\n * Used for region-prefixed Bedrock variants where the registry can't\n * enumerate every region literal. Matching algorithm: the registry\n * key MUST end with `*`; the input MUST match the prefix; the input's\n * suffix after the prefix is appended to the resolved value (also\n * ending with `*` to mark the swap point).\n */\nconst WILDCARD_REGISTRY: ReadonlyArray<readonly [string, string]> = [\n // Bedrock Anthropic: us.anthropic.claude-sonnet-* → us.anthropic.claude-3-haiku-*\n [\"bedrock/anthropic.claude-sonnet*\", \"bedrock/anthropic.claude-3-haiku*\"],\n [\"bedrock/anthropic.claude-opus*\", \"bedrock/anthropic.claude-3-haiku*\"],\n [\"bedrock/anthropic.claude-3-5-sonnet*\", \"bedrock/anthropic.claude-3-5-haiku*\"],\n];\n\n/**\n * Providers declaring `authType: \"none\"` in their profile (D182, D188,\n * D189). For these, return the SAME model — local runtime has no\n * \"cheaper tier\" semantics, latency penalty of summarizing twice is\n * acceptable in dev/local mode. Keys are the provider prefix BEFORE\n * the slash.\n */\nconst NO_AUTH_PROVIDERS: ReadonlySet<string> = new Set([\"ollama\", \"lmstudio\", \"llamacpp\"]);\n\n/**\n * T2.2 — Typed error thrown when `resolveCompressionModel` cannot\n * find a same-family-cheaper-tier mapping for `agentModel`. Surfaces\n * the offending model id so operators can either (a) provide\n * `Agent.create({compression: {model: ...}})` explicitly or (b) open\n * a registry-PR adding the missing entry.\n *\n * @public\n */\nexport class CompressionModelUnresolvedError extends Error {\n override readonly name = \"CompressionModelUnresolvedError\";\n readonly agentModel: string;\n constructor(agentModel: string) {\n super(\n `Could not resolve a same-family-cheaper-tier compression model for \"${agentModel}\". ` +\n `Provide Agent.create({compression: {model: \"<your-cheaper-model>\"}}) ` +\n `OR add \"${agentModel}\" to the compression-model-registry (see ADR D440).`,\n );\n this.agentModel = agentModel;\n }\n}\n\n/**\n * T2.2 — Resolve a cheaper-tier compression model from the agent's\n * main model id. Pure function — no I/O, no mutation, deterministic.\n *\n * @throws `CompressionModelUnresolvedError` when no rule matches.\n *\n * @internal\n */\nexport function resolveCompressionModel(agentModel: string): string {\n const exact = EXACT_REGISTRY.get(agentModel);\n if (exact !== undefined) return exact;\n const wildcard = matchWildcard(agentModel);\n if (wildcard !== null) return wildcard;\n if (isNoAuthProvider(agentModel)) return agentModel;\n throw new CompressionModelUnresolvedError(agentModel);\n}\n\n/** Wildcard suffix match — Bedrock region-prefixed variants. */\nfunction matchWildcard(agentModel: string): string | null {\n for (const [pattern, replacement] of WILDCARD_REGISTRY) {\n const prefix = pattern.endsWith(\"*\") ? pattern.slice(0, -1) : pattern;\n if (!agentModel.startsWith(prefix)) continue;\n const suffix = agentModel.slice(prefix.length);\n const replPrefix = replacement.endsWith(\"*\") ? replacement.slice(0, -1) : replacement;\n return `${replPrefix}${suffix}`;\n }\n return null;\n}\n\n/** Provider declares `authType: \"none\"` — local runtime, same model. */\nfunction isNoAuthProvider(agentModel: string): boolean {\n const slashIdx = agentModel.indexOf(\"/\");\n if (slashIdx <= 0) return false;\n return NO_AUTH_PROVIDERS.has(agentModel.slice(0, slashIdx));\n}\n","/**\n * T2.2 step 3/N — Compression summarizer (ADR D440).\n *\n * Takes a conversation window (messages to compress) + a resolved\n * compression model + an injected LLM caller, and returns a single\n * system-role summary message that replaces the compressed window.\n *\n * The `callLlm` parameter is dependency-injected so:\n * - Unit tests pass a deterministic fake (no real-LLM cost)\n * - The agent-loop passes a real LLM client bound to the resolved\n * compression config (step 4 wire)\n *\n * Failure mode per ADR D440: if the LLM call fails, throws\n * `CompressionFailedError` — the caller (loop.ts) catches this,\n * logs WARN with redacted metadata, and returns the ORIGINAL\n * conversation unchanged (counter incremented toward cap 3).\n *\n * @internal\n */\n\n// Canonical origin moved to the public `compaction.ts` (leaf type — M42 DTS lesson); re-exported\n// here for the existing internal importers.\nimport type { CompressibleMessage } from \"../../../compaction.js\";\n\nexport type { CompressibleMessage };\n\n/**\n * Typed error thrown when the compression LLM call fails or returns\n * an empty/ineffective summary. The caller catches and handles per\n * ADR D440 failure mode (WARN + original conversation + counter).\n *\n * @public\n */\nexport class CompressionFailedError extends Error {\n override readonly name = \"CompressionFailedError\";\n}\n\n/**\n * Build the summarization prompt from a conversation window.\n * The prompt instructs the LLM to produce a concise summary that\n * preserves all facts, decisions, and context needed for the\n * conversation to continue.\n *\n * @internal\n */\nexport function buildCompressionPrompt(messages: readonly CompressibleMessage[]): string {\n const formatted = messages.map((m) => `[${m.role}]: ${m.content}`).join(\"\\n\\n\");\n\n return (\n `Summarize the following ${messages.length} conversation messages into a concise ` +\n `summary that preserves ALL facts, decisions, user preferences, and context ` +\n `needed for the conversation to continue naturally. The summary will replace ` +\n `these messages in the context window. Be thorough but concise.\\n\\n` +\n `--- CONVERSATION TO SUMMARIZE ---\\n${formatted}\\n--- END ---`\n );\n}\n\nconst COMPRESSION_SYSTEM =\n \"You are a conversation summarizer. Produce a concise factual summary. \" +\n \"Preserve all decisions, preferences, code snippets, and action items. \" +\n \"Do not add commentary or opinions. Output ONLY the summary text.\";\n\n/**\n * Compress a conversation window via an aux-LLM summarization call.\n *\n * @param opts.messages — the messages to compress\n * @param opts.model — resolved compression model id\n * @param opts.callLlm — injected LLM caller `(model, system, user) => Promise<string>`\n * @returns a single system-role message containing the summary\n *\n * @throws `CompressionFailedError` on LLM failure or empty summary.\n *\n * @internal\n */\nexport async function compressConversationWindow(opts: {\n messages: readonly CompressibleMessage[];\n model: string;\n callLlm: (model: string, system: string, user: string) => Promise<string>;\n}): Promise<CompressibleMessage> {\n const userPrompt = buildCompressionPrompt(opts.messages);\n\n let summary: string;\n try {\n summary = await opts.callLlm(opts.model, COMPRESSION_SYSTEM, userPrompt);\n } catch (cause) {\n throw new CompressionFailedError(\n `Compression LLM call failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n if (!summary || summary.trim().length === 0) {\n throw new CompressionFailedError(\n \"Compression LLM returned empty summary — reduction ineffective.\",\n );\n }\n\n return {\n role: \"system\",\n content: `[Compressed conversation summary]: ${summary.trim()}`,\n };\n}\n","/**\n * M50 (agent-builder) — session-transcript compaction, Codex-faithful.\n *\n * Mirrors the vendored Codex mechanism (`codex-rs/core/src/compact.rs`):\n * - the replacement history = recent USER messages verbatim (newest→oldest under a token budget;\n * prior summaries filtered by marker) + ONE summary message with a textual marker prefix,\n * injected as `role:\"user\"` (`build_compacted_history`, compact.rs:589-663);\n * - persistence is APPEND-ONLY: a `compact_boundary` record becomes the new DAG root and the\n * replacement messages are chained onto it — resume replays boundary→replacement→suffix\n * (equivalent of `CompactedItem.replacement_history`, rollout is never truncated);\n * - a failing summarizer leaves the transcript UNTOUCHED (typed error; no partial state).\n *\n * The summarizer is dependency-injected: tests pass a deterministic fake; the public\n * `Agent.compact` wires the ADR-D440 compression summarizer (its first real caller).\n */\n\nimport { type CompressibleMessage, estimateTokens } from \"../../compaction.js\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { resolveProviderChain } from \"../llm/router.js\";\nimport {\n detectPrimaryProvider,\n inferProviderFromApiKey,\n} from \"../local-agent/real-local-run-provider.js\";\nimport { reconstructMessages, SessionTranscript } from \"../persistence/session-transcript.js\";\nimport { getProviderProfile, registerBuiltins } from \"../providers/index.js\";\nimport { resolveCompressionModel } from \"../runtime/compression/compression-model-registry.js\";\nimport { compressConversationWindow } from \"../runtime/compression/compression-summarizer.js\";\nimport { invalidateSessionCache } from \"./session-cache.js\";\n\n/** Textual marker prefixing every compact summary (Codex `SUMMARY_PREFIX` analog). */\nexport const COMPACT_SUMMARY_MARKER = \"[[theokit:compact-summary]]\";\n\n/** Budget of VERBATIM user messages preserved in the replacement (Codex `COMPACT_USER_MESSAGE_MAX_TOKENS`). */\nexport const COMPACT_USER_MESSAGE_MAX_TOKENS = 20_000;\n\nexport interface CompactLocation {\n cwd: string;\n agentId: string;\n model?: string;\n}\n\nexport interface CompactResult {\n preTokens: number;\n postTokens: number;\n}\n\n/** Is this message a summary produced by a PRIOR compaction? (filtered from verbatim preservation). */\nexport function isCompactSummary(content: string): boolean {\n // M56 — goal-continuation boilerplate is loop plumbing, not user knowledge: preserving N copies of\n // the template verbatim would crowd out real user messages from the preservation budget.\n return (\n content.startsWith(COMPACT_SUMMARY_MARKER) ||\n content.startsWith(\"[[theokit:goal-continuation]]\")\n );\n}\n\n/**\n * Extract the text of an LlmMessage: content is `LlmContentPart[]` — concatenate the `text` parts\n * (tool_call / tool_result / image parts are skipped for compaction purposes).\n */\nfunction plainText(content: unknown): string | undefined {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return undefined;\n const texts = content\n .filter(\n (p): p is { type: string; text: string } =>\n p !== null &&\n typeof p === \"object\" &&\n (p as { type?: unknown }).type === \"text\" &&\n typeof (p as { text?: unknown }).text === \"string\",\n )\n .map((p) => p.text);\n return texts.length > 0 ? texts.join(\"\\n\") : undefined;\n}\n\n/**\n * Compact one session transcript: summarize the reconstructed history, then append (append-only)\n * a `compact_boundary` + the replacement chain (recent user messages verbatim + marker'd summary).\n *\n * @throws whatever `summarize` throws — with the transcript guaranteed untouched.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: pre-existing (M50) — flagged only because this file was touched by an unrelated one-line M56 change; refactor tracked separately.\nexport async function compactSessionTranscript(opts: {\n store: SessionStore;\n loc: CompactLocation;\n sessionId: string;\n trigger: \"manual\" | \"auto\";\n summarize: (messages: readonly CompressibleMessage[]) => Promise<string>;\n}): Promise<CompactResult> {\n const prior = await opts.store.readRecords(opts.loc.agentId);\n const history = reconstructMessages(prior);\n\n const compressible: CompressibleMessage[] = [];\n for (const m of history) {\n const text = plainText(m.content);\n if (\n text !== undefined &&\n (m.role === \"user\" || m.role === \"assistant\" || m.role === \"system\")\n ) {\n compressible.push({ role: m.role, content: text });\n }\n }\n const preTokens = estimateTokens(compressible.map((m) => m.content).join(\"\\n\"));\n\n // Summarize FIRST — a throwing summarizer must leave the transcript untouched (fail-safe).\n const summaryBody = await opts.summarize(compressible);\n\n // Recent user messages verbatim: newest→oldest under the budget, prior summaries filtered.\n const preserved: string[] = [];\n let budget = 0;\n for (let i = compressible.length - 1; i >= 0; i--) {\n const m = compressible[i];\n if (m === undefined || m.role !== \"user\" || isCompactSummary(m.content)) continue;\n const cost = estimateTokens(m.content);\n if (budget + cost > COMPACT_USER_MESSAGE_MAX_TOKENS) {\n // M50 review F8 — Codex TRUNCATES the overflowing message and keeps the piece\n // (compact.rs:620-629); dropping it entirely loses the most-recent context verbatim.\n const remaining = COMPACT_USER_MESSAGE_MAX_TOKENS - budget;\n if (remaining > 50) {\n preserved.unshift(`${m.content.slice(0, remaining * 4)}\\n[...truncated for compaction...]`);\n }\n break;\n }\n budget += cost;\n preserved.unshift(m.content); // chronological order in the replacement\n }\n\n const summary = `${COMPACT_SUMMARY_MARKER}\\n${summaryBody}`;\n\n // Append-only write: boundary (new root) + replacement chained onto it.\n const transcript = SessionTranscript.fromRecords(prior, {\n cwd: opts.loc.cwd,\n sessionId: opts.sessionId,\n model: opts.loc.model ?? \"unknown\",\n });\n transcript.appendCompactBoundary({ preTokens, trigger: opts.trigger });\n for (const text of preserved) transcript.appendUserTurn(text);\n transcript.appendUserTurn(summary);\n const delta = transcript.records().slice(prior.length);\n await opts.store.appendRecords(opts.loc.agentId, delta);\n\n // M50 review F1 — the live process must FEEL the compaction: drop the in-memory session cache so\n // the next send re-hydrates from disk (replacement + later turns) instead of replaying the full\n // pre-compact history until a restart.\n invalidateSessionCache(opts.loc.cwd, opts.loc.agentId);\n\n const postTokens = estimateTokens([...preserved, summary].join(\"\\n\"));\n return { preTokens, postTokens };\n}\n\n/**\n * M50 review F6 (fixed by the probe) — the summarizer's provider route, PURE and unit-tested.\n * Precedence mirrors the run's M4 rule exactly:\n * 1. an EXPLICIT credential's provider wins (an sk-or- key + `openai/…` model must summarize via\n * OpenRouter — the key is the ground truth of which endpoint gets called);\n * 2. else a model prefix with a REGISTERED profile (the oauth `openai-chatgpt` builtin owns its\n * auth; the M45 fleet resolves its own env vars) routes through that profile;\n * 3. else the ENV-detected provider (fresh process, aggregator credential in env).\n * `fullSlug` marks aggregator routes (provider ≠ prefix): the agent's slug passes unstripped.\n */\nexport function resolveSummarizerRoute(opts: {\n keyProvider: string | undefined;\n modelPrefix: string | undefined;\n prefixHasProfile: boolean;\n envProvider: string;\n}): { provider: string; fullSlug: boolean } {\n const provider =\n opts.keyProvider ??\n (opts.prefixHasProfile && opts.modelPrefix !== undefined ? opts.modelPrefix : opts.envProvider);\n return { provider, fullSlug: provider !== opts.modelPrefix };\n}\n\n// ─── Default summarizer (the ADR-D440 subsystem's first real caller) ─────────────────────────────\n\n/**\n * Build the default summarizer for `Agent.compact`: the D440 `compressConversationWindow`\n * (aux-LLM summarization with typed failure) driven by a router-resolved LLM client. The\n * compression model resolves via the D440 registry with the agent's own model as fallback.\n */\nexport function buildDefaultSummarizer(opts: {\n agentModel: string;\n apiKey?: string;\n}): (messages: readonly CompressibleMessage[]) => Promise<string> {\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: pre-existing (M50) — flagged only because this file was touched by an unrelated one-line M56 change; refactor tracked separately.\n return async (messages) => {\n // Provider resolution mirrors the RUN's own (M4 rule: the explicit API key outranks the model\n // prefix — an sk-or- key + openai/gpt model must summarize via OpenRouter too). Using anything\n // else 401s in real setups (proven live in the M50 probe).\n registerBuiltins();\n const modelPrefix = opts.agentModel.includes(\"/\")\n ? opts.agentModel.slice(0, opts.agentModel.indexOf(\"/\"))\n : undefined;\n const prefixProfile = modelPrefix !== undefined ? getProviderProfile(modelPrefix) : undefined;\n // A prefix profile is only USABLE when its credentials are actually resolvable here: oauth/none\n // profiles own their auth; api_key profiles need one of their env vars set. A profile without a\n // usable credential (e.g. `openai` builtin with only OPENROUTER_API_KEY in env) must NOT win.\n const prefixUsable =\n prefixProfile !== undefined &&\n (prefixProfile.authType !== \"api_key\" ||\n prefixProfile.envVars.some((v) => (process.env[v] ?? \"\").length > 0));\n const route = resolveSummarizerRoute({\n keyProvider: inferProviderFromApiKey(opts.apiKey),\n modelPrefix,\n prefixHasProfile: prefixUsable,\n envProvider: detectPrimaryProvider(),\n });\n const provider = route.provider;\n\n let model: string;\n if (route.fullSlug) {\n // Aggregator route (e.g. OpenRouter): pass the agent's full slug through unstripped.\n model = opts.agentModel;\n } else {\n try {\n model = resolveCompressionModel(opts.agentModel);\n } catch {\n model = opts.agentModel; // registry miss — summarize with the agent's own model\n }\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: pre-existing (M50) — flagged only because this file was touched by an unrelated one-line M56 change; refactor tracked separately.\n const callLlm = async (m: string, system: string, user: string): Promise<string> => {\n const chain = resolveProviderChain({\n primary: provider,\n ...(opts.apiKey !== undefined ? { apiKeys: { [provider]: [opts.apiKey] } } : {}),\n });\n const client = chain[0];\n if (client === undefined) throw new Error(`no LLM client for provider \"${provider}\"`);\n const controller = new AbortController();\n let text = \"\";\n const stream = client.stream(\n { model: m, system, messages: [{ role: \"user\", content: [{ type: \"text\", text: user }] }] },\n controller.signal,\n );\n for (;;) {\n const step = await stream.next();\n if (step.done === true) break;\n if (step.value.type === \"text_delta\") text += step.value.text;\n if (step.value.type === \"error\") throw new Error(step.value.message);\n }\n return text;\n };\n\n const summary = await compressConversationWindow({ messages: [...messages], model, callLlm });\n return summary.content;\n };\n}\n\n// ─── Auto-compaction (Codex formula: fire at usage_real >= (cw*9)/10) ────────────────────────────\n\n/**\n * Should auto-compaction fire? Codex parity: `token_limit_reached` when real usage crosses 90% of\n * the model's context window (`context_window.rs:74-79`; limit default `(cw*9)/10`,\n * `openai_models.rs:459-469`). Missing inputs (no usage reported / model absent from the catalog)\n * NEVER fire — fail-safe toward \"do nothing\".\n */\nexport function shouldAutoCompact(opts: {\n usageTotal?: number | undefined;\n contextWindow?: number | undefined;\n}): boolean {\n if (opts.usageTotal === undefined || opts.contextWindow === undefined) return false;\n if (opts.usageTotal <= 0 || opts.contextWindow <= 0) return false;\n return opts.usageTotal >= Math.floor((opts.contextWindow * 9) / 10);\n}\n\n/** Anti-cascade bookkeeping: last turn we ATTEMPTED an auto-compact, per agent (globalThis — M44 B1). */\nconst autoCompactAttempts = (() => {\n const g = globalThis as unknown as Record<symbol, Map<string, number>>;\n const sym = Symbol.for(\"theokit-sdk.session.auto-compact-attempts\");\n if (g[sym] === undefined) g[sym] = new Map<string, number>();\n return g[sym];\n})();\n\n/**\n * Fire auto-compaction when the threshold is crossed — at most ONE attempt per turn per agent\n * (anti-cascade: a failing summarizer or a non-reducing summary must not loop). Returns whether a\n * compaction actually happened. Failures WARN and leave the transcript untouched.\n */\nexport async function autoCompactIfNeeded(opts: {\n store: SessionStore;\n loc: CompactLocation;\n sessionId: string;\n usageTotal?: number | undefined;\n contextWindow?: number | undefined;\n turnCount: number;\n summarize: (messages: readonly CompressibleMessage[]) => Promise<string>;\n}): Promise<boolean> {\n if (!shouldAutoCompact(opts)) return false;\n const key = `${opts.loc.cwd}::${opts.loc.agentId}`;\n if (autoCompactAttempts.get(key) === opts.turnCount) return false; // already attempted this turn\n autoCompactAttempts.set(key, opts.turnCount);\n try {\n await compactSessionTranscript({\n store: opts.store,\n loc: opts.loc,\n sessionId: opts.sessionId,\n trigger: \"auto\",\n summarize: opts.summarize,\n });\n return true;\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] auto-compaction failed (left transcript untouched): ${msg}\\n`);\n return false;\n }\n}\n"]}