{"version":3,"file":"adapter.mjs","names":["#baseline"],"sources":["../../../../src/batteries/llm/anthropic_messages/adapter.ts"],"sourcesContent":["/**\n * Cross-environment executor adapter for the Anthropic Messages API.\n *\n * @module @nhtio/adk/batteries/llm/anthropic_messages/adapter\n *\n * @remarks\n * Native Anthropic Messages adapter targeting `client.messages.create` from `@anthropic-ai/sdk`\n * (a hard static dependency of this battery). Node-first: an Anthropic API key in a browser\n * bundle is unacceptably exposed, so browser is deliberately not a target or gate for this\n * adapter — `dangerouslyAllowBrowser` exists only for the caller who accepts that risk knowingly.\n *\n * Structurally a sibling of the native Ollama and OpenAI Chat Completions adapters, with the\n * Anthropic-wire divergences:\n *\n * - Transport: the Anthropic SDK owns the HTTP call (`client.messages.create`), not raw `fetch`.\n *   ADK owns retry (`maxRetries: 0` on the client) and timeout (`requestTimeoutMs` fences an\n *   internal `AbortController` linked with `ctx.abortSignal`; when `requestTimeoutMs` is `0` a\n *   large explicit sentinel is set on the SDK client so the SDK's own silent 10-minute default is\n *   never silently inherited).\n * - Streaming: `Stream<RawMessageStreamEvent>` — an `AsyncIterable` the SDK already filters `ping`\n *   frames out of; a mid-stream provider error surfaces as a **thrown `APIError`** from `for\n *   await` iteration, not a discriminated event variant, so the consumption loop is wrapped in a\n *   `try`/`catch`.\n * - Content-block state machine keyed by `index`: `content_block_start` carries the ONLY\n *   occurrence of a `tool_use` block's `id`/`name` and a `redacted_thinking` block's `data`;\n *   `content_block_delta` carries five delta variants (`text_delta`, `thinking_delta`,\n *   `signature_delta`, `input_json_delta`, `citations_delta` — the last is out of scope for v1 and\n *   is a no-op); `content_block_stop` finalizes only that index. `message_stop` is not trusted to\n *   arrive; finalization is reachable from stream EOF too.\n * - Stop reasons: all seven (`end_turn`, `max_tokens`, `stop_sequence`, `tool_use`, `pause_turn`,\n *   `refusal`, `model_context_window_exceeded`) are handled explicitly — `refusal` is a real\n *   terminal HTTP-200 outcome (never mistaken for an error), `model_context_window_exceeded` maps\n *   to `E_ANTHROPIC_MESSAGES_CONTEXT_OVERFLOW`.\n * - Error translation: typed SDK error classes (`BadRequestError`, `AuthenticationError`,\n *   `PermissionDeniedError`, `NotFoundError`, `ConflictError`, `UnprocessableEntityError`,\n *   `RateLimitError`, `InternalServerError`, `APIConnectionTimeoutError`, `APIConnectionError`,\n *   `APIUserAbortError`, generic `APIError`) are narrowed and mapped to ADK exceptions. Context\n *   overflow arrives as a 400 `BadRequestError` and is detected from body text (`prompt is too\n *   long`), not status. A real upstream 529 `overloaded_error` is retriable\n *   (`E_ANTHROPIC_MESSAGES_HTTP_ERROR`) — never routed into the fatal same-numbered\n *   adapter-side exceptions, which use 529 as their own unrelated status code.\n * - Thinking persistence: signed `thinking` blocks persist as a `Thought` carrying a\n *   `{variant:'thinking', thinking, signature, prefixFingerprint}` payload; `redacted_thinking`\n *   blocks carry `{variant:'redacted_thinking', data, prefixFingerprint}`. The fingerprint is\n *   computed via the exported `fingerprintAnthropicMessagesPrefix` helper — never reimplemented.\n * - No request repair: a `tool_choice` that appears not to have been honored (forces a name the\n *   response never calls) only warns via `helpers.log.warn` — `AnthropicMessagesAdapterOptions`\n *   has no `strictToolChoice` escape hatch, consistent with the \"warn loudly, send anyway\" ethos.\n *\n * Per-iteration flow (steps 1–9 of the plan):\n * 1. Merge constructor / executor / stash options and re-validate.\n * 2. Resolve helpers, falling back to bundled `default*` for each unset field.\n * 3. Artifact-reader tools: pre-forged onto `ctx.tools` by the DispatchRunner core; read as-is.\n * 4. Pre-render every persisted tool-call result into an Anthropic tool-result content block.\n * 5. When `tokenEncoding !== null`, sum the token weight of every persisted bucket and throw\n *    {@link @nhtio/adk/batteries!E_ANTHROPIC_MESSAGES_CONTEXT_OVERFLOW} when the total exceeds `contextWindow`.\n * 6. Build the request via `buildAnthropicMessagesHistory`.\n * 7. Call `client.messages.create` with retry/timeout ownership; classify and translate errors.\n * 8. Streaming path: content-block state machine + usage latching + stop-reason handling.\n * 9. Non-streaming path: same persistence + tool-execution loop, from a single `Message`.\n */\n\nimport { DateTime } from 'luxon'\nimport { sha256 } from 'js-sha256'\nimport { v6 as uuidv6 } from 'uuid'\nimport { validateOptions } from './validation'\nimport { APIError } from '@anthropic-ai/sdk/core/error'\nimport { default as Anthropic } from '@anthropic-ai/sdk'\nimport { countAnthropicMessagesTokens } from './count_tokens'\nimport { translateAnthropicError } from './error_translation'\nimport { resolveToolCallParser } from '../chat_common/tool_parsers'\nimport { isError, isInstanceOf, isObject } from '@nhtio/adk/guards'\nimport { canonicalStringify } from '../../../lib/utils/canonical_json'\nimport { InMemorySpoolStore } from '@nhtio/adk/batteries/storage/in_memory'\nimport { looksLikeSpooledArtifact, normalizeToolName } from '../chat_common/helpers'\nimport {\n  computeBackoff,\n  sleepWithJitter,\n  parseRetryAfter,\n  linkAbortSignals,\n} from '../../../lib/utils/retry'\nimport {\n  Tokenizable,\n  ToolCall,\n  Message,\n  Thought,\n  SpooledArtifact,\n  Media,\n  ArtifactTool,\n} from '@nhtio/adk/common'\nimport {\n  E_INVALID_ANTHROPIC_MESSAGES_OPTIONS,\n  E_ANTHROPIC_MESSAGES_CONTEXT_OVERFLOW,\n  E_ANTHROPIC_MESSAGES_HTTP_ERROR,\n  E_ANTHROPIC_MESSAGES_STREAM_ERROR,\n  E_ANTHROPIC_MESSAGES_STREAM_STALLED,\n  E_ANTHROPIC_MESSAGES_REQUEST_TIMEOUT,\n  E_ANTHROPIC_MESSAGES_INVALID_TOOL_CALL_ARGS,\n} from './exceptions'\nimport {\n  defaultDescriptionToChatCompletionsJsonSchema,\n  defaultRenderUntrustedContent,\n  defaultRenderTrustedContent,\n  defaultRenderStandingInstructions,\n  defaultRenderMemories,\n  defaultRenderRetrievables,\n  defaultRenderRetrievableHandleBody,\n  defaultRenderRetrievableSafetyDirective,\n  defaultRenderFirstPartyRetrievables,\n  defaultRenderThirdPartyPublicRetrievables,\n  defaultRenderThirdPartyPrivateRetrievables,\n  defaultRenderThought,\n  defaultFilterThoughts,\n  defaultToolsToChatCompletionsTools,\n  defaultRenderChatCompletionsSystemPrompt,\n  defaultRenderAnthropicTimelineMessage,\n  defaultRenderAnthropicMediaBlocks,\n  defaultRenderAnthropicToolCallResult,\n  defaultRenderAnthropicSegmentedSystemPrompt,\n  defaultRenderAnthropicThinkingBlocks,\n  defaultRenderArtifactHandleBody,\n  defaultBuildAnthropicMessagesHistory,\n  anthropicToolsFromTools,\n  fingerprintAnthropicMessagesPrefix,\n} from './helpers'\nimport type { Tool, Memory } from '@nhtio/adk/common'\nimport type { DispatchContext } from '@nhtio/adk/types'\nimport type { TokenEncoding, TokenEncodingId } from '@nhtio/adk/types'\nimport type { AnthropicMessagesCountTokensRequestInput } from './count_tokens'\nimport type {\n  DispatchExecutorFn,\n  DispatchExecutorHelpers,\n  GenerationStats,\n} from '@nhtio/adk/dispatch_runner'\nimport type {\n  AnthropicMessagesAdapterOptions,\n  AnthropicMessagesHelpers,\n  AnthropicMessage,\n  AnthropicToolResultBlockParam,\n  AnthropicToolUseBlockParam,\n  AnthropicRawMessageStreamEvent,\n  AnthropicRawContentBlockStartEvent,\n  AnthropicRawMessageDeltaEvent,\n  AnthropicUsage,\n  AnthropicMessageDeltaUsage,\n  AnthropicThinkingReplayPayload,\n  AnthropicStopReason,\n  AnthropicMessagesCountTokensInput,\n} from './types'\n\n// ─── An assembled tool call (args kept as a JSON string; id/name arrive on content_block_start) ──\n\ninterface AssembledAnthropicToolCall {\n  id: string\n  name: string\n  args: string\n}\n\n// ─── Content-block accumulator state, keyed by block index ───────────────────\n\ninterface TextBlockState {\n  kind: 'text'\n  text: string\n}\ninterface ThinkingBlockState {\n  kind: 'thinking'\n  thinking: string\n  signature: string\n}\ninterface RedactedThinkingBlockState {\n  kind: 'redacted_thinking'\n  data: string\n}\ninterface ToolUseBlockState {\n  kind: 'tool_use'\n  id: string\n  name: string\n  args: string\n}\ninterface OtherBlockState {\n  kind: 'other'\n}\ntype BlockState =\n  | TextBlockState\n  | ThinkingBlockState\n  | RedactedThinkingBlockState\n  | ToolUseBlockState\n  | OtherBlockState\n\n// ─── Option merging ────────────────────────────────────────────────────────────\n\nconst mergeRecord = <T extends Record<string, unknown>>(\n  layers: ReadonlyArray<T | undefined>\n): T | undefined => {\n  let merged: T | undefined\n  for (const layer of layers) {\n    if (!layer) continue\n    merged = { ...(merged ?? ({} as T)), ...layer }\n  }\n  return merged\n}\n\nconst mergeOptions = (\n  baseline: AnthropicMessagesAdapterOptions,\n  exec: Partial<AnthropicMessagesAdapterOptions> | undefined,\n  stash: Partial<AnthropicMessagesAdapterOptions> | undefined\n): Partial<AnthropicMessagesAdapterOptions> => {\n  const layers = [baseline as Partial<AnthropicMessagesAdapterOptions>, exec ?? {}, stash ?? {}]\n  const out: Record<string, unknown> = {}\n  for (const layer of layers) {\n    for (const [k, v] of Object.entries(layer)) {\n      if (v === undefined) continue\n      if (k === 'headers' || k === 'helpers' || k === 'retry') continue\n      out[k] = v\n    }\n  }\n  const headers = mergeRecord(layers.map((l) => l.headers as Record<string, string> | undefined))\n  if (headers !== undefined) out.headers = headers\n  const helpers = mergeRecord(layers.map((l) => l.helpers as Record<string, unknown> | undefined))\n  if (helpers !== undefined) out.helpers = helpers\n  const retry = mergeRecord(layers.map((l) => l.retry as Record<string, unknown> | undefined))\n  if (retry !== undefined) out.retry = retry\n  return out as Partial<AnthropicMessagesAdapterOptions>\n}\n\n// ─── Helper resolution ─────────────────────────────────────────────────────────\n\nconst resolveHelpers = (\n  overrides: Partial<AnthropicMessagesHelpers> | undefined\n): AnthropicMessagesHelpers => {\n  const src = overrides ?? {}\n  return {\n    descriptionToChatCompletionsJsonSchema:\n      src.descriptionToChatCompletionsJsonSchema ?? defaultDescriptionToChatCompletionsJsonSchema,\n    renderUntrustedContent: src.renderUntrustedContent ?? defaultRenderUntrustedContent,\n    renderTrustedContent: src.renderTrustedContent ?? defaultRenderTrustedContent,\n    renderArtifactHandleBody: src.renderArtifactHandleBody ?? defaultRenderArtifactHandleBody,\n    renderRetrievableHandleBody:\n      src.renderRetrievableHandleBody ?? defaultRenderRetrievableHandleBody,\n    renderStandingInstructions: src.renderStandingInstructions ?? defaultRenderStandingInstructions,\n    renderMemories: src.renderMemories ?? defaultRenderMemories,\n    renderRetrievables: src.renderRetrievables ?? defaultRenderRetrievables,\n    renderRetrievableSafetyDirective:\n      src.renderRetrievableSafetyDirective ?? defaultRenderRetrievableSafetyDirective,\n    renderFirstPartyRetrievables:\n      src.renderFirstPartyRetrievables ?? defaultRenderFirstPartyRetrievables,\n    renderThirdPartyPublicRetrievables:\n      src.renderThirdPartyPublicRetrievables ?? defaultRenderThirdPartyPublicRetrievables,\n    renderThirdPartyPrivateRetrievables:\n      src.renderThirdPartyPrivateRetrievables ?? defaultRenderThirdPartyPrivateRetrievables,\n    renderThought: src.renderThought ?? defaultRenderThought,\n    filterThoughts: src.filterThoughts ?? defaultFilterThoughts,\n    toolsToChatCompletionsTools:\n      src.toolsToChatCompletionsTools ?? defaultToolsToChatCompletionsTools,\n    renderChatCompletionsSystemPrompt:\n      src.renderChatCompletionsSystemPrompt ?? defaultRenderChatCompletionsSystemPrompt,\n    anthropicToolsFromTools: src.anthropicToolsFromTools ?? anthropicToolsFromTools,\n    renderAnthropicTimelineMessage:\n      src.renderAnthropicTimelineMessage ?? defaultRenderAnthropicTimelineMessage,\n    renderAnthropicMediaBlocks: src.renderAnthropicMediaBlocks ?? defaultRenderAnthropicMediaBlocks,\n    renderAnthropicToolCallResult:\n      src.renderAnthropicToolCallResult ?? defaultRenderAnthropicToolCallResult,\n    renderAnthropicSegmentedSystemPrompt:\n      src.renderAnthropicSegmentedSystemPrompt ?? defaultRenderAnthropicSegmentedSystemPrompt,\n    renderAnthropicThinkingBlocks:\n      src.renderAnthropicThinkingBlocks ?? defaultRenderAnthropicThinkingBlocks,\n    buildAnthropicMessagesHistory:\n      src.buildAnthropicMessagesHistory ?? defaultBuildAnthropicMessagesHistory,\n  }\n}\n\n// ─── ID / checksum / time helpers ──────────────────────────────────────────────\n\nconst computeChecksum = (tool: string, args: unknown): string =>\n  sha256(canonicalStringify({ tool, args }))\n\nconst nowIso = (): string => DateTime.now().toISO() ?? new Date().toISOString()\n\nconst estimateTokensOf = async (\n  value: {\n    estimateTokens: (encoding: TokenEncoding) => number | Promise<number>\n  },\n  encoding: TokenEncodingId\n): Promise<number> => Promise.resolve(value.estimateTokens(encoding as TokenEncoding))\n\nconst emptyBlockState = (\n  block: AnthropicRawContentBlockStartEvent['content_block']\n): BlockState => {\n  if (block.type === 'text') return { kind: 'text', text: block.text ?? '' }\n  if (block.type === 'thinking')\n    return {\n      kind: 'thinking',\n      thinking: block.thinking ?? '',\n      signature: block.signature ?? '',\n    }\n  if (block.type === 'redacted_thinking') return { kind: 'redacted_thinking', data: block.data }\n  if (block.type === 'tool_use') {\n    // STREAMING-ONLY seed: on a real `content_block_start` event, `content_block.input` for a\n    // `tool_use` block is always the SDK's `{}` placeholder, never the real arguments — the real\n    // arguments arrive exclusively via subsequent `input_json_delta.partial_json` fragments on\n    // `content_block_delta`, which this state's `args` accumulator appends to verbatim (see the\n    // `content_block_delta` handler below). Serializing `block.input` here would seed the\n    // accumulator with the string `\"{}\"`, and every later `partial_json` fragment would then be\n    // appended onto that placeholder, producing corrupted concatenated JSON such as\n    // `{}{\"query\":\"x\"}` that fails `JSON.parse` in `executeAndPersistToolCall` for every streamed\n    // tool call. This function is reachable ONLY from the streaming path (Step 8); the\n    // non-streaming path (Step 9) is structurally separate — it reads the complete `Message`'s\n    // `content` array directly and serializes each `tool_use` block's `input` exactly once, never\n    // through this function.\n    return {\n      kind: 'tool_use',\n      id: block.id,\n      name: block.name,\n      args: '',\n    }\n  }\n  return { kind: 'other' }\n}\n\n// ─── Stop-reason handling (exhaustive over all 7 AnthropicStopReason members) ──\n\n/**\n * Logs the terminal stop reason of a completed generation. Exhaustive over every\n * {@link AnthropicStopReason} member plus an explicit `default` for any value the SDK's union does\n * not yet cover — never a silent fall-through. `model_context_window_exceeded` is included for\n * switch exhaustiveness only: both call sites throw/nack on that reason before this function is\n * reached, so its case body is unreachable in practice.\n */\nconst logAnthropicStopReason = (\n  helpers: DispatchExecutorHelpers,\n  stopReason: string | null,\n  stopDetails: unknown\n): void => {\n  switch (stopReason as AnthropicStopReason | null) {\n    case 'end_turn':\n      helpers.log.debug({\n        kind: 'anthropic-stop-reason',\n        message: 'Anthropic ended the turn normally (end_turn).',\n        payload: { stopReason },\n      })\n      break\n    case 'max_tokens':\n      helpers.log.warn({\n        kind: 'anthropic-stop-reason',\n        message: 'Anthropic stopped because max_tokens was reached; the response may be truncated.',\n        payload: { stopReason },\n      })\n      break\n    case 'stop_sequence':\n      helpers.log.debug({\n        kind: 'anthropic-stop-reason',\n        message: 'Anthropic stopped on a configured stop_sequence.',\n        payload: { stopReason },\n      })\n      break\n    case 'tool_use':\n      helpers.log.debug({\n        kind: 'anthropic-stop-reason',\n        message: 'Anthropic stopped to invoke one or more tools (tool_use).',\n        payload: { stopReason },\n      })\n      break\n    case 'pause_turn':\n      helpers.log.info({\n        kind: 'anthropic-pause-turn',\n        message: 'Anthropic paused a long-running turn; response may be continued verbatim',\n        payload: { stopReason },\n      })\n      break\n    case 'refusal':\n      helpers.log.warn({\n        kind: 'anthropic-refusal',\n        message: 'Anthropic returned a refusal stop reason',\n        payload: { stopReason, stopDetails },\n      })\n      break\n    case 'model_context_window_exceeded':\n      // Unreachable: both call sites nack E_ANTHROPIC_MESSAGES_CONTEXT_OVERFLOW and return as\n      // soon as this reason is observed, before this function runs.\n      break\n    case null:\n      break\n    default:\n      helpers.log.warn({\n        kind: 'anthropic-unrecognized-stop-reason',\n        message: `Anthropic returned an unrecognized stop_reason \"${String(stopReason)}\"; treating it as a normal terminal response.`,\n        payload: { stopReason },\n      })\n  }\n}\n\n// ─── Generation-stats extraction ───────────────────────────────────────────────\n\nconst extractGenerationStats = (input: {\n  model: string\n  usage?: AnthropicUsage | AnthropicMessageDeltaUsage\n  finishReason?: string | null\n  raw: Record<string, unknown>\n}): GenerationStats => {\n  const stats: GenerationStats = {\n    provider: 'anthropic_messages',\n    model: input.model,\n    raw: input.raw,\n  }\n  const usage = input.usage\n  if (usage) {\n    if (typeof usage.input_tokens === 'number') stats.promptTokens = usage.input_tokens\n    if (typeof usage.output_tokens === 'number') stats.completionTokens = usage.output_tokens\n    if (typeof usage.input_tokens === 'number' && typeof usage.output_tokens === 'number') {\n      stats.totalTokens = usage.input_tokens + usage.output_tokens\n    }\n  }\n  if (typeof input.finishReason === 'string') stats.finishReason = input.finishReason\n  return stats\n}\n\n// ─── Adapter class ─────────────────────────────────────────────────────────────\n\n/**\n * Opinionated cross-environment LLM adapter for the Anthropic Messages wire shape.\n *\n * @remarks\n * Construction validates options eagerly via {@link validateOptions} and throws\n * {@link @nhtio/adk/batteries/llm/anthropic_messages!E_INVALID_ANTHROPIC_MESSAGES_OPTIONS} on\n * failure. The returned instance is reusable: call {@link AnthropicMessagesAdapter.executor} once\n * per `DispatchRunner` configuration to obtain a {@link @nhtio/adk!DispatchExecutorFn} bound to\n * the baseline plus optional executor-scope overrides. Per-iteration overrides live on\n * `ctx.stash.anthropicMessages` and take highest precedence; `headers`, `helpers`, and `retry`\n * merge key-by-key across all three layers, every other field is replaced wholesale at the\n * highest layer that sets it. Node-first: browser is explicitly not a target — an Anthropic API\n * key in a browser bundle is unacceptably exposed.\n */\nexport class AnthropicMessagesAdapter {\n  /** Customary key for per-iteration overrides on `ctx.stash`. */\n  public static readonly STASH_KEY = 'anthropicMessages' as const\n\n  readonly #baseline: AnthropicMessagesAdapterOptions\n\n  /**\n   * @param options - Constructor-baseline options. Re-validated on every iteration after\n   *   per-dispatch and per-iteration overrides are layered in.\n   * @throws {@link @nhtio/adk/batteries/llm/anthropic_messages!E_INVALID_ANTHROPIC_MESSAGES_OPTIONS} when `options` does not satisfy `anthropicMessagesOptionsSchema`.\n   */\n  constructor(options: unknown) {\n    this.#baseline = validateOptions(options)\n  }\n\n  /**\n   * Returns a {@link @nhtio/adk!DispatchExecutorFn} bound to this adapter's baseline plus optional\n   * executor-scope overrides.\n   *\n   * @param overrides - Optional executor-scope overrides. Higher precedence than the baseline,\n   *   lower precedence than `ctx.stash[STASH_KEY]`.\n   */\n  executor(overrides?: Partial<AnthropicMessagesAdapterOptions>): DispatchExecutorFn {\n    const baseline = this.#baseline\n    const adapterClass = AnthropicMessagesAdapter\n    return async (ctx: DispatchContext, helpers: DispatchExecutorHelpers): Promise<void> => {\n      const localWarn = (msg: string): void => {\n        helpers.log.warn({ kind: 'helper-warning', message: msg })\n      }\n\n      // ── Step 1: merge & validate ──────────────────────────────────────────\n      const stashRaw = ctx.stash.get(adapterClass.STASH_KEY, {}) as unknown\n      const stashOverrides =\n        stashRaw && typeof stashRaw === 'object'\n          ? (stashRaw as Partial<AnthropicMessagesAdapterOptions>)\n          : {}\n      const merged = validateOptions(mergeOptions(baseline, overrides, stashOverrides))\n\n      // Cross-field invariant: tokenEncoding non-null requires contextWindow.\n      if (merged.tokenEncoding !== null && merged.contextWindow === undefined) {\n        throw new E_INVALID_ANTHROPIC_MESSAGES_OPTIONS([\n          'tokenEncoding is non-null but contextWindow is undefined',\n        ])\n      }\n\n      // ── Step 2: resolve helpers ───────────────────────────────────────────\n      const resolvedHelpers = resolveHelpers(merged.helpers)\n\n      // ── Step 3: artifact-reader tools ─────────────────────────────────────\n      // Forged by the DispatchRunner CORE into `ctx.tools` before the input pipeline runs\n      // (generation is a generic core concern; this battery owns only representation). Read the\n      // pre-forged `ctx.tools` directly — no local merge, no bindContext here.\n\n      // ── Step 4: pre-render tool-call results ──────────────────────────────\n      // Key by primitive identity: duplicate provider ids must not cross-wire results.\n      const renderedToolCallResults = new Map<ToolCall, AnthropicToolResultBlockParam>()\n      for (const tc of ctx.turnToolCalls) {\n        const rendered = await resolvedHelpers.renderAnthropicToolCallResult({\n          toolCall: tc,\n          results: tc.results as\n            | Tokenizable\n            | SpooledArtifact\n            | SpooledArtifact[]\n            | Media\n            | Media[],\n          tool: ctx.tools.get(tc.tool) as Tool | ArtifactTool | undefined,\n          renderUntrustedContent: resolvedHelpers.renderUntrustedContent,\n          renderTrustedContent: resolvedHelpers.renderTrustedContent,\n          renderAnthropicMediaBlocks: resolvedHelpers.renderAnthropicMediaBlocks,\n          renderArtifactHandleBody: resolvedHelpers.renderArtifactHandleBody,\n          unsupportedMediaPolicy: merged.unsupportedMediaPolicy ?? 'throw',\n          warn: localWarn,\n        })\n        renderedToolCallResults.set(tc, rendered)\n      }\n\n      // ── Step 5: context window enforcement ────────────────────────────────\n      if (merged.tokenEncoding !== null && merged.contextWindow !== undefined) {\n        const encoding = merged.tokenEncoding as TokenEncodingId\n        let spTokens = await estimateTokensOf(ctx.systemPrompt, encoding)\n        let siTokens = 0\n        for (const si of ctx.standingInstructions) {\n          siTokens += await estimateTokensOf(si, encoding)\n        }\n        let memTokens = 0\n        for (const mem of ctx.turnMemories as Set<Memory>) {\n          memTokens += await estimateTokensOf(mem.content, encoding)\n        }\n        let retTokens = 0\n        for (const r of ctx.turnRetrievables) {\n          retTokens +=\n            !r.inline && SpooledArtifact.isSpooledArtifact(r.content) && r.content.hasSizeHints()\n              ? r.content.estimateHandleTokens(\n                  r.id,\n                  encoding as TokenEncoding,\n                  resolvedHelpers.renderRetrievableHandleBody\n                )\n              : await estimateTokensOf(r.content, encoding)\n        }\n        let tlTokens = 0\n        for (const msg of ctx.turnMessages) {\n          if (msg.content !== undefined) {\n            tlTokens += await estimateTokensOf(msg.content, encoding)\n          }\n        }\n        for (const th of ctx.turnThoughts) {\n          tlTokens += await estimateTokensOf(th.content, encoding)\n        }\n        for (const rendered of renderedToolCallResults.values()) {\n          tlTokens += await estimateTokensOf(new Tokenizable(JSON.stringify(rendered)), encoding)\n        }\n        // Tool DECLARATIONS: Anthropic renders `tools` server-side; there is no single fixed\n        // client-side conversion to reproduce it. Tally the serialized wire `tools` JSON as an\n        // honest FLOOR. Without this the guard undercounts a tool-heavy prompt by the entire\n        // declaration block.\n        let toolTokens = 0\n        const visibleTools = ctx.tools.visible()\n        if (visibleTools.length > 0) {\n          const toolsJson = JSON.stringify(\n            resolvedHelpers.anthropicToolsFromTools(visibleTools, {\n              descriptionToChatCompletionsJsonSchema: (d) =>\n                resolvedHelpers.descriptionToChatCompletionsJsonSchema(d as never),\n            })\n          )\n          toolTokens = await estimateTokensOf(new Tokenizable(toolsJson), encoding)\n        }\n        const total = spTokens + siTokens + memTokens + retTokens + tlTokens + toolTokens\n        const perBucketObj = {\n          systemPrompt: spTokens,\n          standingInstructions: siTokens,\n          memories: memTokens,\n          retrievables: retTokens,\n          timeline: tlTokens,\n          tools: toolTokens,\n        }\n        helpers.log.debug({\n          kind: 'context-window-usage',\n          message: `Context window usage: ${total}/${merged.contextWindow} tokens`,\n          payload: {\n            total,\n            limit: merged.contextWindow,\n            encoding,\n            perBucket: perBucketObj,\n          },\n        })\n        if (total > merged.contextWindow) {\n          throw new E_ANTHROPIC_MESSAGES_CONTEXT_OVERFLOW([\n            total,\n            merged.contextWindow,\n            encoding,\n            JSON.stringify(perBucketObj),\n          ])\n        }\n      }\n\n      // ── Step 5b: tool_choice forced-tool guard (warn-only; no strictToolChoice escape) ─────\n      // Anthropic's tool_choice shape (`{type:'auto'|'any'|'tool'|'none', name?}`) has no\n      // equivalent to Chat Completions' `function`/`custom`/`allowed_tools` variants — only the\n      // `'tool'` variant names a single tool. `AnthropicMessagesAdapterOptions` carries no\n      // `strictToolChoice` field (types.ts is out of scope for this work package), so a forced\n      // name resolving to an ephemeral, forged artifact-query tool can only be warned about, never\n      // thrown on — consistent with the \"warn loudly, send anyway, no request repair\" governing\n      // constraint. Never assume forcing worked: some models 400 on a forced tool_choice, which\n      // surfaces later as a translated HTTP error, not here.\n      const toolChoice = merged.toolChoice\n      if (toolChoice && toolChoice.type === 'tool') {\n        const t = ctx.tools.get(toolChoice.name) as { ephemeral?: boolean } | undefined\n        if (t?.ephemeral === true) {\n          helpers.log.warn({\n            kind: 'tool-choice-forged-artifact',\n            message: `tool_choice forces forged ephemeral artifact-query tool \"${toolChoice.name}\"; this is almost always a misconfiguration and it may not exist on the next iteration`,\n            payload: { toolName: toolChoice.name },\n          })\n        }\n      }\n\n      // ── Step 5c: Fable-class forced-tool-use / thinking incompatibility guard (warn-only) ──\n      // \"Fable-class\" is matched via a `claude-fable-` model-name prefix — ageing data, not a hard\n      // capability table (no authoritative per-model capability source is available to this\n      // adapter). A forced `tool_choice` (`{type:'tool'}` or `{type:'any'}`) combined with either\n      // variant of `thinking` (`disabled` or `enabled`) is known to 400 upstream on this model\n      // class. Same governing principle as Step 5b: surface the footgun, never rewrite/repair the\n      // request — the caller may know something this heuristic doesn't.\n      if (merged.model.startsWith('claude-fable-')) {\n        const forcedToolChoice =\n          toolChoice !== undefined && (toolChoice.type === 'tool' || toolChoice.type === 'any')\n        const incompatibleThinking =\n          merged.thinking !== undefined &&\n          (merged.thinking.type === 'disabled' || merged.thinking.type === 'enabled')\n        if (forcedToolChoice && incompatibleThinking) {\n          helpers.log.warn({\n            kind: 'fable-forced-tool-choice-thinking-conflict',\n            message: `Model \"${merged.model}\" matches the Fable-class heuristic (claude-fable- prefix); combining a forced tool_choice (\"${toolChoice?.type}\") with thinking (\"${merged.thinking?.type}\") is known to 400 upstream on this model class. Sending the request unmodified.`,\n            payload: {\n              model: merged.model,\n              toolChoiceType: toolChoice?.type,\n              thinking: merged.thinking,\n            },\n          })\n        }\n      }\n\n      // ── Step 6: build request body ────────────────────────────────────────\n      const {\n        system,\n        messages: wireMessages,\n        tools: wireTools,\n      } = await resolvedHelpers.buildAnthropicMessagesHistory({\n        model: merged.model,\n        systemPrompt: ctx.systemPrompt,\n        standingInstructions: ctx.standingInstructions,\n        memories: ctx.turnMemories,\n        retrievables: ctx.turnRetrievables,\n        messages: ctx.turnMessages,\n        thoughts: ctx.turnThoughts,\n        toolCalls: ctx.turnToolCalls,\n        tools: ctx.tools,\n        renderedToolCallResults,\n        bucketOrder: merged.bucketOrder ?? [\n          'standingInstructions',\n          'memories',\n          'retrievables',\n          'timeline',\n        ],\n        selfIdentity: merged.selfIdentity ?? 'assistant',\n        thoughtSurfacing: merged.thoughtSurfacing ?? 'all-self',\n        replayCompatibility: merged.replayCompatibility ?? [],\n        unsupportedMediaPolicy: merged.unsupportedMediaPolicy ?? 'throw',\n        cacheBreakpoints: merged.cacheBreakpoints ?? 'auto',\n        cacheTtl: merged.cacheTtl,\n        renderAnthropicToolCallResult: resolvedHelpers.renderAnthropicToolCallResult,\n        renderChatCompletionsSystemPrompt: resolvedHelpers.renderChatCompletionsSystemPrompt,\n        renderAnthropicSegmentedSystemPrompt: resolvedHelpers.renderAnthropicSegmentedSystemPrompt,\n        renderStandingInstructions: resolvedHelpers.renderStandingInstructions,\n        renderMemories: resolvedHelpers.renderMemories,\n        renderRetrievables: resolvedHelpers.renderRetrievables,\n        renderRetrievableSafetyDirective: resolvedHelpers.renderRetrievableSafetyDirective,\n        renderFirstPartyRetrievables: resolvedHelpers.renderFirstPartyRetrievables,\n        renderThirdPartyPublicRetrievables: resolvedHelpers.renderThirdPartyPublicRetrievables,\n        renderThirdPartyPrivateRetrievables: resolvedHelpers.renderThirdPartyPrivateRetrievables,\n        renderRetrievableHandleBody: resolvedHelpers.renderRetrievableHandleBody,\n        renderAnthropicTimelineMessage: resolvedHelpers.renderAnthropicTimelineMessage,\n        renderThought: resolvedHelpers.renderThought,\n        filterThoughts: resolvedHelpers.filterThoughts,\n        renderAnthropicThinkingBlocks: resolvedHelpers.renderAnthropicThinkingBlocks,\n        renderUntrustedContent: resolvedHelpers.renderUntrustedContent,\n        renderTrustedContent: resolvedHelpers.renderTrustedContent,\n        warn: localWarn,\n      })\n\n      const stream = merged.stream ?? true\n\n      // Anthropic request surface fields are individually named on `AnthropicMessagesAdapterOptions`\n      // (unlike OpenAI's spread-minus-control-keys body assembly) — assembled explicitly, field by\n      // field, only when defined. This enumerates the request surface exhaustively rather than\n      // spreading `merged`, so no ADK-control field (spoolStore, helpers, retry, onRawGeneration,\n      // ...) can ever leak into the wire body by omission from a strip-set.\n      const params: Record<string, unknown> = {\n        model: merged.model,\n        max_tokens: merged.maxTokens,\n        messages: wireMessages,\n        stream,\n      }\n      if (system !== undefined) params.system = system\n      if (wireTools !== undefined && wireTools.length > 0) params.tools = wireTools\n      if (merged.stopSequences !== undefined) params.stop_sequences = merged.stopSequences\n      if (merged.thinking !== undefined) params.thinking = merged.thinking\n      if (merged.outputConfig !== undefined) params.output_config = merged.outputConfig\n      if (merged.toolChoice !== undefined) params.tool_choice = merged.toolChoice\n      if (merged.metadata !== undefined) params.metadata = merged.metadata\n      if (merged.serviceTier !== undefined) params.service_tier = merged.serviceTier\n      if (merged.container !== undefined) params.container = merged.container\n      if (merged.inferenceGeo !== undefined) params.inference_geo = merged.inferenceGeo\n      if (merged.userProfileId !== undefined) params.user_profile_id = merged.userProfileId\n      // Deprecated sampling parameters — never supplied unless the caller explicitly sets them.\n      if (merged.temperature !== undefined) params.temperature = merged.temperature\n      if (merged.topP !== undefined) params.top_p = merged.topP\n      if (merged.topK !== undefined) params.top_k = merged.topK\n\n      // One id for this whole generation — correlates the TO tap (onPromptAssembled) with the FROM\n      // tap (onRawGeneration) below.\n      const dispatchStreamId = uuidv6()\n\n      // Prompt-assembled observability tap: the EXACT request going TO Anthropic, the instant it is\n      // built and BEFORE the call. Mirror of onRawGeneration. Handed back AS-IS — no redaction —\n      // and swallow observer errors so it can never corrupt the generation path.\n      if (merged.onPromptAssembled) {\n        try {\n          merged.onPromptAssembled({\n            battery: 'anthropic_messages',\n            kind: 'request-body',\n            messages: wireMessages,\n            tools: wireTools,\n            requestBody: params,\n            streamed: stream,\n            streamId: dispatchStreamId,\n          })\n        } catch {\n          /* observer errors are non-fatal */\n        }\n      }\n\n      // ── Step 7: call the SDK with retry / timeout ownership ───────────────\n      const retryCfg = {\n        maxAttempts: merged.retry?.maxAttempts ?? 1,\n        baseDelayMs: merged.retry?.baseDelayMs ?? 500,\n        maxDelayMs: merged.retry?.maxDelayMs ?? 30_000,\n        retriableStatuses: merged.retry?.retriableStatuses ?? [429, 502, 503, 504, 529],\n        honorRetryAfter: merged.retry?.honorRetryAfter ?? true,\n      }\n\n      const requestTimeoutMs = merged.requestTimeoutMs ?? 0\n      // ADK owns retry (maxRetries:0) and timeout ownership. When requestTimeoutMs > 0, the SDK\n      // client timeout is set with an explicit safety margin above it so the ADK-side timer (via\n      // the linked AbortSignal below) is deterministically the one that fires first and raises\n      // E_ANTHROPIC_MESSAGES_REQUEST_TIMEOUT. When requestTimeoutMs is 0 (ADK timer disabled), a\n      // large explicit sentinel replaces the SDK's silent 10-minute default so the caller's choice\n      // to disable the ADK timer is never silently overridden by an SDK-owned ceiling.\n      const client = new Anthropic({\n        apiKey: merged.apiKey,\n        baseURL: merged.baseURL,\n        fetch: merged.fetch,\n        maxRetries: 0,\n        timeout: requestTimeoutMs > 0 ? requestTimeoutMs + 30_000 : 24 * 60 * 60 * 1000,\n        defaultHeaders: merged.headers,\n        dangerouslyAllowBrowser: merged.dangerouslyAllowBrowser ?? false,\n      })\n\n      let anthropicStream: AsyncIterable<AnthropicRawMessageStreamEvent> | undefined\n      let anthropicMessage: AnthropicMessage | undefined\n      let attempt = 1\n      const maxAttempts = retryCfg.maxAttempts\n      let disposeLink: () => void = () => {}\n\n      while (attempt <= maxAttempts) {\n        if (ctx.abortSignal.aborted) return\n\n        const internalController = new AbortController()\n        let timeoutHandle: ReturnType<typeof setTimeout> | undefined\n        if (requestTimeoutMs > 0) {\n          timeoutHandle = setTimeout(() => internalController.abort(), requestTimeoutMs)\n        }\n        disposeLink()\n        const { signal: linkedSignal, dispose: disposeCurrentLink } = linkAbortSignals([\n          ctx.abortSignal,\n          internalController.signal,\n        ])\n        disposeLink = disposeCurrentLink\n\n        try {\n          if (stream) {\n            anthropicStream = (await client.messages.create({ ...params, stream: true } as never, {\n              signal: linkedSignal,\n            })) as unknown as AsyncIterable<AnthropicRawMessageStreamEvent>\n          } else {\n            anthropicMessage = (await client.messages.create(\n              { ...params, stream: false } as never,\n              {\n                signal: linkedSignal,\n              }\n            )) as unknown as AnthropicMessage\n          }\n          if (timeoutHandle !== undefined) clearTimeout(timeoutHandle)\n          break\n        } catch (err) {\n          if (timeoutHandle !== undefined) clearTimeout(timeoutHandle)\n          if (ctx.abortSignal.aborted) return\n          const classified = translateAnthropicError(err, retryCfg.retriableStatuses, {\n            resolveErrorStatus: merged.resolveErrorStatus,\n            warn: (msg) =>\n              helpers.log.warn({ kind: 'anthropic-resolve-error-status', message: msg }),\n          })\n          if (classified.kind === 'abort') return\n          if (classified.kind === 'timeout') {\n            helpers.log.warn({\n              kind: 'request-timeout',\n              message: `Request timed out after ${requestTimeoutMs}ms on attempt ${attempt}/${maxAttempts}`,\n              payload: { requestTimeoutMs, attempt, maxAttempts },\n            })\n            if (attempt < maxAttempts) {\n              const delay = computeBackoff(attempt, retryCfg)\n              await sleepWithJitter(delay, ctx.abortSignal)\n              attempt += 1\n              continue\n            }\n            ctx.nack(new E_ANTHROPIC_MESSAGES_REQUEST_TIMEOUT([requestTimeoutMs]))\n            return\n          }\n          if (classified.kind === 'context-overflow') {\n            // Detected from body text on a 400 BadRequestError — the wire never distinguishes this\n            // from any other 400, so the adapter cannot report the exact per-bucket breakdown the\n            // pre-flight guard (Step 5) computes; that guard is the source of truth for a\n            // predictable overflow. This branch only catches what the guard could not: a case where\n            // Anthropic's own accounting disagrees with the local token estimate.\n            ctx.nack(\n              new E_ANTHROPIC_MESSAGES_CONTEXT_OVERFLOW([\n                -1,\n                merged.contextWindow ?? -1,\n                merged.tokenEncoding ?? 'unknown',\n                classified.message,\n              ])\n            )\n            return\n          }\n          if (classified.kind === 'retriable') {\n            if (attempt < maxAttempts) {\n              let delay = computeBackoff(attempt, retryCfg)\n              if (retryCfg.honorRetryAfter !== false && isInstanceOf(err, 'APIError', APIError)) {\n                const ra = err.headers?.get?.('retry-after')\n                if (ra) {\n                  const raMs = parseRetryAfter(ra)\n                  if (raMs > 0) delay = Math.min(Math.max(delay, raMs), retryCfg.maxDelayMs)\n                }\n              }\n              helpers.log.warn({\n                kind: 'retry-attempt',\n                message: `Anthropic error (status ${classified.status}) on attempt ${attempt}/${maxAttempts}; retrying in ~${delay}ms`,\n                payload: {\n                  reason: 'http-status',\n                  status: classified.status,\n                  delayMs: delay,\n                  attempt: attempt + 1,\n                  maxAttempts,\n                },\n              })\n              await sleepWithJitter(delay, ctx.abortSignal)\n              attempt += 1\n              continue\n            }\n            helpers.log.error({\n              kind: 'http-error',\n              message: `Anthropic error ${classified.status} (terminal): ${classified.message.slice(0, 256)}`,\n              payload: {\n                status: classified.status,\n                body: classified.message,\n                attempt,\n                maxAttempts,\n              },\n            })\n            ctx.nack(new E_ANTHROPIC_MESSAGES_HTTP_ERROR([classified.status, classified.message]))\n            return\n          }\n          helpers.log.error({\n            kind: 'http-error',\n            message: `Anthropic error ${classified.status} (terminal): ${classified.message.slice(0, 256)}`,\n            payload: {\n              status: classified.status,\n              body: classified.message,\n              attempt,\n              maxAttempts,\n            },\n          })\n          ctx.nack(new E_ANTHROPIC_MESSAGES_HTTP_ERROR([classified.status, classified.message]))\n          return\n        }\n      }\n\n      const spoolStore = merged.spoolStore ?? new InMemorySpoolStore()\n      const selfIdentity = merged.selfIdentity ?? 'assistant'\n\n      // ── Inner helper: persist + execute one assembled tool call ───────────\n      const executeAndPersistToolCall = async (call: AssembledAnthropicToolCall): Promise<void> => {\n        // Resolve the vendor id once at ingress so reporting, persistence, and spooling agree.\n        const callId = merged.toolCallIdFilter?.(call.id, ctx) ?? call.id\n        const tool = ctx.tools.get(call.name)\n        let args: Record<string, unknown> = {}\n        let parseError: InstanceType<typeof E_ANTHROPIC_MESSAGES_INVALID_TOOL_CALL_ARGS> | undefined\n        if (call.args && call.args.length > 0) {\n          try {\n            const parsed: unknown = JSON.parse(call.args)\n            if (isObject(parsed)) {\n              args = parsed\n            } else {\n              const receivedKind = Array.isArray(parsed)\n                ? 'array'\n                : parsed === null\n                  ? 'null'\n                  : typeof parsed\n              parseError = new E_ANTHROPIC_MESSAGES_INVALID_TOOL_CALL_ARGS([\n                `must be a JSON object; received ${receivedKind}`,\n                call.args,\n              ])\n            }\n          } catch {\n            parseError = new E_ANTHROPIC_MESSAGES_INVALID_TOOL_CALL_ARGS([\n              'are not valid JSON',\n              call.args,\n            ])\n          }\n        }\n        const completedAt = nowIso()\n        if (parseError !== undefined) {\n          const toolName = normalizeToolName(call.name)\n          const results = new Tokenizable(parseError.message)\n          helpers.reportToolCall(callId, { tool: toolName, args })\n          helpers.reportToolCall(callId, {\n            results,\n            isError: true,\n            isComplete: true,\n          })\n          await ctx.storeToolCall(\n            new ToolCall({\n              id: callId,\n              tool: toolName,\n              args,\n              checksum: computeChecksum(toolName, args),\n              isComplete: true,\n              isError: true,\n              results,\n              createdAt: completedAt,\n              updatedAt: completedAt,\n              completedAt,\n            })\n          )\n          return\n        }\n        if (!tool) {\n          const toolName = normalizeToolName(call.name)\n          const available = ctx.tools\n            .all()\n            .map((t) => t.name)\n            .sort()\n          const errText =\n            available.length > 0\n              ? `Tool not found: ${toolName}. Available tools: ${available.join(', ')}.`\n              : `Tool not found: ${toolName}. No tools are available this turn.`\n          const results = new Tokenizable(errText)\n          helpers.reportToolCall(callId, { tool: toolName, args })\n          helpers.reportToolCall(callId, {\n            results,\n            isError: true,\n            isComplete: true,\n          })\n          await ctx.storeToolCall(\n            new ToolCall({\n              id: callId,\n              tool: toolName,\n              args,\n              checksum: computeChecksum(toolName, args),\n              isComplete: true,\n              isError: true,\n              results,\n              createdAt: completedAt,\n              updatedAt: completedAt,\n              completedAt,\n            })\n          )\n          return\n        }\n        helpers.reportToolCall(callId, { tool: tool.name, args })\n        const isArtifactTool = ArtifactTool.isArtifactTool(tool)\n        let results: Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[] =\n          new Tokenizable('')\n        let toolHadError = false\n        try {\n          const raw = await tool.executor(ctx)(args)\n          if (isArtifactTool) {\n            if (Tokenizable.isTokenizable(raw)) {\n              results = raw\n            } else if (typeof raw === 'string') {\n              results = new Tokenizable(raw)\n            } else {\n              throw new Error(\n                `ArtifactTool \"${tool.name}\" returned a non-string/non-Tokenizable value`\n              )\n            }\n          } else if (Media.isMedia(raw)) {\n            results = raw\n          } else if (Array.isArray(raw) && raw.length > 0 && raw.every((m) => Media.isMedia(m))) {\n            results = raw as Media[]\n          } else if (looksLikeSpooledArtifact(raw)) {\n            results = raw as SpooledArtifact\n          } else if (typeof raw === 'string' || isInstanceOf(raw, 'Uint8Array', Uint8Array)) {\n            const reader = await spoolStore.write(callId, raw as string | Uint8Array)\n            const ArtifactCtor = (tool as Tool).artifactConstructor?.() ?? SpooledArtifact\n            results = new ArtifactCtor(reader)\n          } else {\n            const reader = await spoolStore.write(callId, String(raw))\n            const ArtifactCtor = (tool as Tool).artifactConstructor?.() ?? SpooledArtifact\n            results = new ArtifactCtor(reader)\n          }\n        } catch (err) {\n          toolHadError = true\n          let detailMsg = isError(err) ? err.message : String(err)\n          if (\n            isError(err) &&\n            isError(err.cause) &&\n            err.cause.message &&\n            err.cause.message !== err.message\n          ) {\n            detailMsg = `${detailMsg} ${err.cause.message}`\n          }\n          results = new Tokenizable(detailMsg)\n        }\n        helpers.reportToolCall(callId, {\n          results,\n          isError: toolHadError,\n          isComplete: true,\n        })\n        const completedAt2 = nowIso()\n        await ctx.storeToolCall(\n          new ToolCall({\n            id: callId,\n            tool: tool.name,\n            args,\n            checksum: computeChecksum(tool.name, args),\n            isComplete: true,\n            isError: toolHadError,\n            results,\n            fromArtifactTool: isArtifactTool,\n            // ArtifactTool results are the documented exception: they inline the slice the model\n            // queried from a prior artifact (handing back a handle to a query result would be\n            // recursion). Every other result keeps the secure default (inline:false → handle).\n            inline: isArtifactTool,\n            createdAt: completedAt2,\n            updatedAt: completedAt2,\n            completedAt: completedAt2,\n          })\n        )\n      }\n\n      // FALLBACK tool-call recovery. Native `tool_use` content blocks are authoritative; this is\n      // consulted ONLY when the response yielded zero native tool_use blocks AND the caller opted\n      // in via `localToolCallParser`. Mirrors the `ollama`/`openai_chat_completions` fallback\n      // pattern verbatim — pure parse over the accumulated text, returning assembled calls (empty\n      // when disabled or no match) so each call site can reflect them in `onRawGeneration` and then\n      // execute them exactly like native calls.\n      const parseFallbackToolCalls = (content: string): AssembledAnthropicToolCall[] => {\n        if (merged.localToolCallParser === undefined) return []\n        if (typeof content !== 'string' || content.length === 0) return []\n        const parser = resolveToolCallParser(merged.localToolCallParser)\n        const toolNames = ctx.tools.visible().map((t) => t.name)\n        return parser(content, { toolNames }).calls.map((c) => ({\n          id: uuidv6(),\n          name: c.name,\n          args: JSON.stringify(c.arguments),\n        }))\n      }\n\n      // ── Step 8: streaming path ────────────────────────────────────────────\n      if (stream) {\n        if (!anthropicStream) {\n          ctx.nack(new E_ANTHROPIC_MESSAGES_STREAM_ERROR(['no stream returned']))\n          return\n        }\n        const streamId = dispatchStreamId\n        const thoughtStreamId = `${streamId}:thought`\n\n        const blocks = new Map<number, BlockState>()\n        let sawMessageDelta = false\n        let sawThinking = false\n        let finalUsage: AnthropicUsage | AnthropicMessageDeltaUsage | undefined\n        let finalStopReason: string | null = null\n        let finalStopDetails: AnthropicRawMessageDeltaEvent['delta']['stop_details'] = null\n        let responseModel = merged.model\n        let doneSeen = false\n        const collectedToolCalls: AssembledAnthropicToolCall[] = []\n\n        const idleMs = merged.streamIdleTimeoutMs ?? 0\n        let idleTimer: ReturnType<typeof setTimeout> | undefined\n        let stalled = false\n        const idleController = new AbortController()\n        const armIdleTimer = (): void => {\n          if (idleMs <= 0) return\n          if (idleTimer) clearTimeout(idleTimer)\n          idleTimer = setTimeout(() => {\n            stalled = true\n            helpers.log.warn({\n              kind: 'stream-idle-timeout',\n              message: `Anthropic stream went idle for ${idleMs}ms; cancelling`,\n              payload: { idleMs },\n            })\n            idleController.abort()\n          }, idleMs)\n        }\n        const clearIdleTimer = (): void => {\n          if (idleTimer) {\n            clearTimeout(idleTimer)\n            idleTimer = undefined\n          }\n        }\n\n        const finalize = async (): Promise<void> => {\n          if (sawMessageDelta) {\n            const combinedText = Array.from(blocks.values())\n              .filter((b): b is TextBlockState => b.kind === 'text')\n              .map((b) => b.text)\n              .join('')\n            helpers.reportMessage(streamId, '', { isComplete: true })\n            await ctx.storeMessage(\n              new Message({\n                id: streamId,\n                role: 'assistant',\n                content: combinedText,\n                identity: selfIdentity,\n                createdAt: nowIso(),\n                updatedAt: nowIso(),\n              })\n            )\n          }\n          if (sawThinking) {\n            const thinkingBlocks = Array.from(blocks.entries()).filter(\n              (entry): entry is [number, ThinkingBlockState | RedactedThinkingBlockState] =>\n                entry[1].kind === 'thinking' || entry[1].kind === 'redacted_thinking'\n            )\n            const combinedThinking = thinkingBlocks\n              .map(([, b]) => (b.kind === 'thinking' ? b.thinking : ''))\n              .join('')\n            helpers.reportThought(thoughtStreamId, '', { isComplete: true })\n            const prefixFingerprint = await fingerprintAnthropicMessagesPrefix({\n              model: merged.model,\n              system,\n              tools: wireTools,\n              messages: wireMessages,\n            })\n            const firstThinking = thinkingBlocks.find(([, b]) => b.kind === 'thinking') as\n              | [number, ThinkingBlockState]\n              | undefined\n            const firstRedacted = thinkingBlocks.find(([, b]) => b.kind === 'redacted_thinking') as\n              | [number, RedactedThinkingBlockState]\n              | undefined\n            const payload: AnthropicThinkingReplayPayload | undefined = firstThinking\n              ? {\n                  variant: 'thinking',\n                  thinking: firstThinking[1].thinking,\n                  signature: firstThinking[1].signature,\n                  prefixFingerprint,\n                }\n              : firstRedacted\n                ? {\n                    variant: 'redacted_thinking',\n                    data: firstRedacted[1].data,\n                    prefixFingerprint,\n                  }\n                : undefined\n            await ctx.storeThought(\n              new Thought({\n                id: thoughtStreamId,\n                content: combinedThinking,\n                identity: selfIdentity,\n                payload,\n                replayCompatibility: payload ? 'anthropic-messages-thinking-v1' : undefined,\n                createdAt: nowIso(),\n                updatedAt: nowIso(),\n              })\n            )\n          }\n\n          helpers.reportGenerationStats(\n            extractGenerationStats({\n              model: responseModel,\n              usage: finalUsage,\n              finishReason: finalStopReason,\n              raw: {\n                usage: finalUsage,\n                stop_reason: finalStopReason,\n                stop_details: finalStopDetails,\n              },\n            })\n          )\n\n          const combinedText = Array.from(blocks.values())\n            .filter((b): b is TextBlockState => b.kind === 'text')\n            .map((b) => b.text)\n            .join('')\n\n          // Fallback recovery (opt-in): consulted only when no native tool_use blocks were\n          // collected, so a native call always wins over a parsed one.\n          const fallbackToolCalls =\n            collectedToolCalls.length === 0 ? parseFallbackToolCalls(combinedText) : []\n          const effectiveToolCalls =\n            collectedToolCalls.length > 0 ? collectedToolCalls : fallbackToolCalls\n\n          if (merged.onRawGeneration) {\n            try {\n              merged.onRawGeneration({\n                rawText: combinedText,\n                cleanedText: combinedText,\n                reasoning: sawThinking\n                  ? Array.from(blocks.values())\n                      .filter((b): b is ThinkingBlockState => b.kind === 'thinking')\n                      .map((b) => b.thinking)\n                  : [],\n                toolCalls: effectiveToolCalls.map((c) => ({\n                  name: c.name,\n                  arguments: c.args as never,\n                })),\n                streamed: true,\n                streamId: dispatchStreamId,\n              })\n            } catch {\n              /* observer errors are non-fatal */\n            }\n          }\n\n          logAnthropicStopReason(helpers, finalStopReason, finalStopDetails)\n\n          if (effectiveToolCalls.length === 0) {\n            if (merged.autoAck) ctx.ack()\n            return\n          }\n          for (const call of effectiveToolCalls) {\n            if (ctx.abortSignal.aborted) return\n            await executeAndPersistToolCall(call)\n          }\n        }\n\n        try {\n          armIdleTimer()\n          for await (const event of anthropicStream) {\n            armIdleTimer()\n            if (ctx.abortSignal.aborted || idleController.signal.aborted) {\n              clearIdleTimer()\n              if (stalled) {\n                ctx.nack(new E_ANTHROPIC_MESSAGES_STREAM_STALLED([idleMs]))\n              }\n              return\n            }\n            if (event.type === 'message_start') {\n              responseModel = event.message.model ?? responseModel\n              finalUsage = event.message.usage\n            } else if (event.type === 'content_block_start') {\n              blocks.set(event.index, emptyBlockState(event.content_block))\n              const b = blocks.get(event.index)!\n              if (b.kind === 'thinking' || b.kind === 'redacted_thinking') sawThinking = true\n            } else if (event.type === 'content_block_delta') {\n              const b = blocks.get(event.index)\n              const delta = event.delta\n              if (delta.type === 'text_delta') {\n                sawMessageDelta = true\n                if (b && b.kind === 'text') b.text += delta.text\n                helpers.reportMessage(streamId, delta.text)\n              } else if (delta.type === 'thinking_delta') {\n                sawThinking = true\n                if (b && b.kind === 'thinking') b.thinking += delta.thinking\n                helpers.reportThought(thoughtStreamId, delta.thinking)\n              } else if (delta.type === 'signature_delta') {\n                if (b && b.kind === 'thinking') b.signature = delta.signature\n              } else if (delta.type === 'input_json_delta') {\n                if (b && b.kind === 'tool_use') b.args += delta.partial_json\n              }\n              // citations_delta: out of scope for v1 — no ADK citation representation; no-op.\n            } else if (event.type === 'content_block_stop') {\n              const b = blocks.get(event.index)\n              if (b && b.kind === 'tool_use') {\n                collectedToolCalls.push({\n                  id: b.id,\n                  name: b.name,\n                  args: b.args || '{}',\n                })\n              }\n            } else if (event.type === 'message_delta') {\n              if (event.usage) finalUsage = event.usage\n              if (event.delta.stop_reason !== null && event.delta.stop_reason !== undefined) {\n                finalStopReason = event.delta.stop_reason\n              }\n              if (event.delta.stop_details !== null && event.delta.stop_details !== undefined) {\n                finalStopDetails = event.delta.stop_details\n              }\n              if (event.delta.stop_reason === 'model_context_window_exceeded') {\n                clearIdleTimer()\n                ctx.nack(\n                  new E_ANTHROPIC_MESSAGES_CONTEXT_OVERFLOW([\n                    -1,\n                    merged.contextWindow ?? -1,\n                    merged.tokenEncoding ?? 'unknown',\n                    JSON.stringify(event.delta),\n                  ])\n                )\n                return\n              }\n            } else if (event.type === 'message_stop') {\n              doneSeen = true\n              clearIdleTimer()\n              await finalize()\n              return\n            }\n          }\n          clearIdleTimer()\n          if (stalled) {\n            ctx.nack(new E_ANTHROPIC_MESSAGES_STREAM_STALLED([idleMs]))\n            return\n          }\n          // The SDK's own iterator does not guarantee a trailing message_stop reaches this loop in\n          // every transport edge case (e.g. the connection closes cleanly right after the final\n          // frame) — finalization must be idempotent and reachable from stream EOF too.\n          if (!doneSeen) {\n            helpers.log.warn({\n              kind: 'stream-eof-without-stop',\n              message:\n                'Anthropic stream ended without a message_stop event; draining accumulated state',\n            })\n            await finalize()\n          }\n        } catch (err) {\n          clearIdleTimer()\n          if (ctx.abortSignal.aborted) return\n          if (stalled) {\n            ctx.nack(new E_ANTHROPIC_MESSAGES_STREAM_STALLED([idleMs]))\n            return\n          }\n          const classified = translateAnthropicError(err, retryCfg.retriableStatuses, {\n            resolveErrorStatus: merged.resolveErrorStatus,\n            warn: (msg) =>\n              helpers.log.warn({ kind: 'anthropic-resolve-error-status', message: msg }),\n          })\n          if (classified.kind === 'abort') return\n          if (classified.kind === 'context-overflow') {\n            ctx.nack(\n              new E_ANTHROPIC_MESSAGES_CONTEXT_OVERFLOW([\n                -1,\n                merged.contextWindow ?? -1,\n                merged.tokenEncoding ?? 'unknown',\n                classified.message,\n              ])\n            )\n            return\n          }\n          helpers.log.error({\n            kind: 'stream-error',\n            message: `Anthropic stream failed: ${isError(err) ? err.message : String(err)}`,\n            payload: { detail: isError(err) ? err.message : String(err) },\n          })\n          ctx.nack(\n            new E_ANTHROPIC_MESSAGES_STREAM_ERROR([isError(err) ? err.message : String(err)])\n          )\n          return\n        }\n        return\n      }\n\n      // ── Step 9: non-streaming path ─────────────────────────────────────────\n      if (!anthropicMessage) return\n      const parsed = anthropicMessage\n      const responseId = uuidv6()\n\n      const textParts: string[] = []\n      const toolUseBlocks: AnthropicToolUseBlockParam[] = []\n      let thinkingPayload: AnthropicThinkingReplayPayload | undefined\n      let combinedThinking = ''\n      let hasThinking = false\n\n      if (parsed.stop_reason === 'model_context_window_exceeded') {\n        ctx.nack(\n          new E_ANTHROPIC_MESSAGES_CONTEXT_OVERFLOW([\n            -1,\n            merged.contextWindow ?? -1,\n            merged.tokenEncoding ?? 'unknown',\n            JSON.stringify({ stop_reason: parsed.stop_reason }),\n          ])\n        )\n        return\n      }\n      logAnthropicStopReason(helpers, parsed.stop_reason, parsed.stop_details)\n\n      for (const block of parsed.content) {\n        if (block.type === 'text') {\n          textParts.push(block.text)\n        } else if (block.type === 'thinking') {\n          hasThinking = true\n          combinedThinking += block.thinking\n          if (thinkingPayload === undefined) {\n            thinkingPayload = {\n              variant: 'thinking',\n              thinking: block.thinking,\n              signature: block.signature,\n              prefixFingerprint: await fingerprintAnthropicMessagesPrefix({\n                model: merged.model,\n                system,\n                tools: wireTools,\n                messages: wireMessages,\n              }),\n            }\n          }\n        } else if (block.type === 'redacted_thinking') {\n          hasThinking = true\n          if (thinkingPayload === undefined) {\n            thinkingPayload = {\n              variant: 'redacted_thinking',\n              data: block.data,\n              prefixFingerprint: await fingerprintAnthropicMessagesPrefix({\n                model: merged.model,\n                system,\n                tools: wireTools,\n                messages: wireMessages,\n              }),\n            }\n          }\n        } else if (block.type === 'tool_use') {\n          toolUseBlocks.push({\n            type: 'tool_use',\n            id: block.id,\n            name: block.name,\n            input: block.input,\n          })\n        }\n        // Server-tool-result block types (web_search_tool_result, code_execution_tool_result, ...)\n        // are out of scope for this client-tools-only adapter — no ADK-side representation.\n      }\n\n      const content = textParts.join('')\n      if (content.length > 0) {\n        const messageId = `${responseId}:message`\n        helpers.reportMessage(messageId, content, { isComplete: true })\n        await ctx.storeMessage(\n          new Message({\n            id: messageId,\n            role: 'assistant',\n            content,\n            identity: selfIdentity,\n            createdAt: nowIso(),\n            updatedAt: nowIso(),\n          })\n        )\n      }\n      if (hasThinking) {\n        const thoughtId = `${responseId}:thought`\n        helpers.reportThought(thoughtId, combinedThinking, {\n          isComplete: true,\n        })\n        await ctx.storeThought(\n          new Thought({\n            id: thoughtId,\n            content: combinedThinking,\n            identity: selfIdentity,\n            payload: thinkingPayload,\n            replayCompatibility: thinkingPayload ? 'anthropic-messages-thinking-v1' : undefined,\n            createdAt: nowIso(),\n            updatedAt: nowIso(),\n          })\n        )\n      }\n\n      helpers.reportGenerationStats(\n        extractGenerationStats({\n          model: parsed.model ?? merged.model,\n          usage: parsed.usage,\n          finishReason: parsed.stop_reason,\n          raw: { ...parsed } as unknown as Record<string, unknown>,\n        })\n      )\n\n      const nativeCalls: AssembledAnthropicToolCall[] = toolUseBlocks.map((b) => ({\n        id: b.id,\n        name: b.name,\n        args: b.input === undefined ? '{}' : JSON.stringify(b.input),\n      }))\n      // Fallback recovery (opt-in): consulted only when no native tool_use blocks are present, so\n      // a native call always wins over a parsed one.\n      const calls = nativeCalls.length > 0 ? nativeCalls : parseFallbackToolCalls(content)\n\n      if (merged.onRawGeneration) {\n        try {\n          merged.onRawGeneration({\n            rawText: content,\n            cleanedText: content,\n            reasoning: hasThinking ? [combinedThinking] : [],\n            toolCalls: calls.map((c) => ({\n              name: c.name,\n              arguments: c.args as never,\n            })),\n            streamed: false,\n            streamId: dispatchStreamId,\n          })\n        } catch {\n          /* observer errors are non-fatal */\n        }\n      }\n\n      if (calls.length === 0) {\n        if (merged.autoAck) ctx.ack()\n        return\n      }\n      for (const call of calls) {\n        if (ctx.abortSignal.aborted) return\n        await executeAndPersistToolCall(call)\n      }\n    }\n  }\n\n  /**\n   * Counts the input tokens a request would consume, without generating.\n   *\n   * Uses Anthropic's dedicated count-tokens surface (a distinct parameter shape from a create\n   * request, and one that takes no `maxTokens`), and returns a named field plus the raw upstream\n   * body rather than leaking the vendor type through this battery's public API.\n   *\n   * `input` accepts either a dispatch context — whose prompt is assembled with the same helpers the\n   * executor uses — or a pre-built Anthropic-shaped request. Option precedence, revalidation,\n   * timeout ownership, and error translation all match {@link AnthropicMessagesAdapter.executor}.\n   */\n  public async countTokens(\n    input: AnthropicMessagesCountTokensRequestInput | AnthropicMessagesCountTokensInput,\n    overrides?: Partial<AnthropicMessagesAdapterOptions>\n  ): Promise<{ inputTokens: number; raw: unknown }> {\n    return countAnthropicMessagesTokens(this.#baseline, input, overrides)\n  }\n\n  /**\n   * Returns `true` when `value` is an {@link AnthropicMessagesAdapter} instance.\n   */\n  public static isAnthropicMessagesAdapter(value: unknown): value is AnthropicMessagesAdapter {\n    return isInstanceOf(value, 'AnthropicMessagesAdapter', AnthropicMessagesAdapter)\n  }\n}\n"],"mappings":";;;;;;;;;;;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