{"version":3,"file":"helpers.mjs","names":[],"sources":["../../../../src/batteries/llm/anthropic_messages/helpers.ts"],"sourcesContent":["/**\n * Anthropic Messages translation helpers.\n *\n * @module @nhtio/adk/batteries/llm/anthropic_messages/helpers\n */\n\nimport { Media } from '@nhtio/adk/common'\n\nexport {\n  descriptionToChatCompletionsJsonSchema,\n  defaultDescriptionToChatCompletionsJsonSchema,\n  renderUntrustedContent,\n  defaultRenderUntrustedContent,\n  renderTrustedContent,\n  defaultRenderTrustedContent,\n  renderStandingInstructions,\n  defaultRenderStandingInstructions,\n  renderMemories,\n  defaultRenderMemories,\n  renderRetrievableSafetyDirective,\n  defaultRenderRetrievableSafetyDirective,\n  renderFirstPartyRetrievables,\n  defaultRenderFirstPartyRetrievables,\n  renderThirdPartyPublicRetrievables,\n  defaultRenderThirdPartyPublicRetrievables,\n  renderThirdPartyPrivateRetrievables,\n  defaultRenderThirdPartyPrivateRetrievables,\n  renderRetrievables,\n  defaultRenderRetrievables,\n  renderThought,\n  defaultRenderThought,\n  filterThoughts,\n  defaultFilterThoughts,\n  toolsToChatCompletionsTools,\n  defaultToolsToChatCompletionsTools,\n  renderChatCompletionsSystemPrompt,\n  defaultRenderChatCompletionsSystemPrompt,\n  renderArtifactHandleBody,\n  defaultRenderArtifactHandleBody,\n  renderRetrievableHandleBody,\n  defaultRenderRetrievableHandleBody,\n  looksLikeSpooledArtifact,\n} from '../chat_common/helpers'\n\nimport { E_ANTHROPIC_MESSAGES_UNSUPPORTED_MEDIA_MODALITY } from './exceptions'\nimport {\n  escapeXmlAttribute,\n  floorTrustTier,\n  memoryToAttrs,\n  neutraliseDeveloperRulesTag,\n  retrievableToAttrs,\n  sanitizeFilenameForDescription,\n  sanitizeMimeType,\n} from '../chat_common/helpers'\nimport {\n  descriptionToChatCompletionsJsonSchema,\n  renderUntrustedContent,\n  renderTrustedContent,\n  defaultRenderArtifactHandleBody,\n  looksLikeSpooledArtifact,\n  canonicalFingerprint,\n} from '../chat_common/helpers'\nimport type { ChatHelpersCommon } from '../chat_common/types'\nimport type {\n  JsonSchema,\n  ChatCompletionsBucketOrder,\n  UnsupportedMediaPolicy,\n} from '../chat_common/types'\nimport type {\n  ArtifactTool,\n  Memory,\n  Message,\n  Retrievable,\n  SpooledArtifact,\n  Thought,\n  Tokenizable,\n  Tool,\n  ToolCall,\n} from '@nhtio/adk/common'\nimport type {\n  AnthropicCacheBreakpoints,\n  AnthropicContentBlockParam,\n  AnthropicDocumentBlockParam,\n  AnthropicImageBlockParam,\n  AnthropicMessagesHelpers,\n  AnthropicTextBlockParam,\n  AnthropicThinkingReplayPayload,\n  AnthropicTool,\n  AnthropicToolResultBlockParam,\n  AnthropicMessageParam,\n} from './types'\n\n/** Converts ADK tools to Anthropic's flat custom-tool definition. */\nexport const anthropicToolsFromTools = (\n  tools: ReadonlyArray<Tool | ArtifactTool>,\n  deps: { descriptionToChatCompletionsJsonSchema: (d: unknown) => JsonSchema }\n): AnthropicTool[] =>\n  tools.map((tool) => {\n    const described = tool.describe()\n    const schema = deps.descriptionToChatCompletionsJsonSchema(\n      described.inputSchema\n    ) as AnthropicTool['input_schema']\n    return {\n      name: described.name,\n      ...(described.description ? { description: described.description } : {}),\n      input_schema: Object.keys(schema).length > 0 ? schema : { type: 'object', properties: {} },\n    }\n  })\n/** Default Anthropic tool translator. */\nexport const defaultAnthropicToolsFromTools = anthropicToolsFromTools\n\nconst stashKeys = ['text:transcript', 'text:caption', 'text:description'] as const\nconst modalityAttr = (value: string): 'inert' | 'extractable' | 'opaque' =>\n  value === 'inert' ? 'inert' : value === 'extractable-instructions' ? 'extractable' : 'opaque'\nconst stashEntry = (value: unknown): { value: string; trustTier: string } | undefined => {\n  if (value === null || typeof value !== 'object') return undefined\n  const v = value as { value?: unknown; trustTier?: unknown }\n  return typeof v.value === 'string' && typeof v.trustTier === 'string'\n    ? { value: v.value, trustTier: v.trustTier }\n    : undefined\n}\nconst marker = (media: Media): string =>\n  `[media id: ${media.id} | ${sanitizeFilenameForDescription(media.filename)}]`\nconst synthetic = async (media: Media): Promise<string> =>\n  `[media: ${sanitizeFilenameForDescription(media.filename)}, ${sanitizeMimeType(media.mimeType)}, ${await media.byteLength()} B]`\n\nconst fallbackMedia = async (input: {\n  media: Media\n  unsupportedMediaPolicy: UnsupportedMediaPolicy\n  renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n  renderTrustedContent: ChatHelpersCommon['renderTrustedContent']\n  nonce: string\n  tool?: string\n  warn?: (msg: string) => void\n}): Promise<AnthropicContentBlockParam[]> => {\n  const { media, unsupportedMediaPolicy: policy } = input\n  if (policy === 'throw') {\n    throw new E_ANTHROPIC_MESSAGES_UNSUPPORTED_MEDIA_MODALITY([\n      media.kind,\n      media.mimeType,\n      media.filename,\n    ])\n  }\n  const keys =\n    typeof policy === 'object' ? policy.stashKeys : policy === 'fallback-stash' ? stashKeys : []\n  let text: string | undefined\n  for (const key of keys) {\n    const entry = stashEntry(media.stash.get(key))\n    if (entry) {\n      const tier = floorTrustTier(media.trustTier, entry.trustTier)\n      text =\n        tier === 'first-party'\n          ? input.renderTrustedContent(entry.value, {\n              nonce: input.nonce,\n              kind: 'media-fallback',\n              tool: input.tool,\n              modality: modalityAttr(media.modalityHazard),\n            })\n          : input.renderUntrustedContent(entry.value, {\n              nonce: input.nonce,\n              kind: 'media-fallback',\n              tool: input.tool,\n              modality: modalityAttr(media.modalityHazard),\n            })\n      break\n    }\n  }\n  if (text === undefined) {\n    if (policy === 'fallback-stash' || typeof policy === 'object')\n      input.warn?.(\n        `No media fallback stash entry for ${media.filename}; using synthetic description.`\n      )\n    const body = await synthetic(media)\n    text = input.renderUntrustedContent(body, {\n      nonce: input.nonce,\n      kind: 'media-fallback',\n      tool: input.tool,\n      modality: modalityAttr(media.modalityHazard),\n    })\n  }\n  return [{ type: 'text', text: `${marker(media)}\\n${text}` }]\n}\n\n/** Renders image, document, and policy-routed unsupported media blocks. */\nexport const renderAnthropicMediaBlocks = async (input: {\n  media: Media\n  unsupportedMediaPolicy: UnsupportedMediaPolicy\n  renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n  renderTrustedContent: ChatHelpersCommon['renderTrustedContent']\n  warn?: (msg: string) => void\n}): Promise<AnthropicContentBlockParam[]> => {\n  const { media } = input\n  if (media.kind === 'image') {\n    const mime = sanitizeMimeType(media.mimeType, 'image')\n    if (!['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(mime)) {\n      return fallbackMedia({ ...input, nonce: media.id })\n    }\n    const imageMime = mime as 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp'\n    const block: AnthropicImageBlockParam = {\n      type: 'image',\n      source: {\n        type: 'base64',\n        media_type: imageMime,\n        data: await media.asBase64(),\n      },\n    }\n    return [{ type: 'text', text: marker(media) }, block]\n  }\n  if (\n    media.kind === 'document' &&\n    (media.mimeType === 'application/pdf' || media.mimeType === 'text/plain')\n  ) {\n    const source =\n      media.mimeType === 'application/pdf'\n        ? {\n            type: 'base64' as const,\n            media_type: 'application/pdf' as const,\n            data: await media.asBase64(),\n          }\n        : {\n            type: 'text' as const,\n            media_type: 'text/plain' as const,\n            data: new TextDecoder().decode(await media.asBytes()),\n          }\n    const block: AnthropicDocumentBlockParam = { type: 'document', source }\n    return [{ type: 'text', text: marker(media) }, block]\n  }\n  return fallbackMedia({ ...input, nonce: media.id })\n}\n/** Default Anthropic media renderer. */\nexport const defaultRenderAnthropicMediaBlocks = renderAnthropicMediaBlocks\n\n/** Renders a tool result as Anthropic tool-result content, preserving media blocks. */\nexport const renderAnthropicToolCallResult = async (input: {\n  toolCall: ToolCall\n  results: Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[]\n  tool: Tool | ArtifactTool | undefined\n  renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n  renderTrustedContent: ChatHelpersCommon['renderTrustedContent']\n  renderAnthropicMediaBlocks: AnthropicMessagesHelpers['renderAnthropicMediaBlocks']\n  renderArtifactHandleBody?: AnthropicMessagesHelpers['renderArtifactHandleBody']\n  renderRetrievableHandleBody?: AnthropicMessagesHelpers['renderRetrievableHandleBody']\n  unsupportedMediaPolicy: UnsupportedMediaPolicy\n  warn?: (msg: string) => void\n}): Promise<AnthropicToolResultBlockParam> => {\n  const trusted = input.tool !== undefined && (input.tool as { trusted?: boolean }).trusted === true\n  const mediaList = Media.isMedia(input.results)\n    ? [input.results]\n    : Array.isArray(input.results) && input.results.every((x) => Media.isMedia(x))\n      ? input.results\n      : undefined\n  let body:\n    | string\n    | Array<AnthropicTextBlockParam | AnthropicImageBlockParam | AnthropicDocumentBlockParam>\n  if (mediaList) {\n    body = []\n    for (const media of mediaList) {\n      const rendered = await input.renderAnthropicMediaBlocks({\n        media,\n        unsupportedMediaPolicy: input.unsupportedMediaPolicy,\n        renderUntrustedContent: input.renderUntrustedContent,\n        renderTrustedContent: input.renderTrustedContent,\n        warn: input.warn,\n      })\n      body.push(\n        ...rendered.filter(\n          (\n            block\n          ): block is\n            | AnthropicImageBlockParam\n            | AnthropicDocumentBlockParam\n            | AnthropicTextBlockParam =>\n            block.type === 'text' || block.type === 'image' || block.type === 'document'\n        )\n      )\n    }\n  } else if (Array.isArray(input.results)) {\n    const resultParts = await Promise.all(\n      input.results.map((x) =>\n        'asString' in (x as object) ? (x as SpooledArtifact).asString() : x.toString()\n      )\n    )\n    body = resultParts.join('\\n\\n')\n  } else if (looksLikeSpooledArtifact(input.results) && input.toolCall.inline === false) {\n    const artifact = input.results as SpooledArtifact\n    let byteLength = 0\n    let lineCount = 0\n    try {\n      byteLength = await artifact.byteLength()\n    } catch {\n      byteLength = 0\n    }\n    try {\n      lineCount = await artifact.lineCount()\n    } catch {\n      lineCount = 0\n    }\n    const handleBody = (input.renderArtifactHandleBody ?? defaultRenderArtifactHandleBody)({\n      callId: input.toolCall.id,\n      artifact,\n      byteLength,\n      lineCount,\n    })\n    return {\n      type: 'tool_result',\n      tool_use_id: input.toolCall.id,\n      content: input.renderUntrustedContent(handleBody, {\n        nonce: input.toolCall.checksum,\n        kind: 'artifact-handle',\n        tool: input.toolCall.tool,\n      }),\n      ...(input.toolCall.isError ? { is_error: true } : {}),\n    }\n  } else if ('asString' in (input.results as object)) {\n    body = await (input.results as SpooledArtifact).asString()\n  } else body = input.results.toString()\n  if (typeof body === 'string')\n    body = trusted\n      ? input.renderTrustedContent(body, {\n          nonce: input.toolCall.checksum,\n          kind: 'trusted-tool-result',\n          tool: input.toolCall.tool,\n        })\n      : input.renderUntrustedContent(body, {\n          nonce: input.toolCall.checksum,\n          kind: 'tool-result',\n          tool: input.toolCall.tool,\n        })\n  return {\n    type: 'tool_result',\n    tool_use_id: input.toolCall.id,\n    content: body,\n    ...(input.toolCall.isError ? { is_error: true } : {}),\n  }\n}\n/** Default Anthropic tool-result renderer. */\nexport const defaultRenderAnthropicToolCallResult = renderAnthropicToolCallResult\n\n/** Renders system buckets as separate text blocks and places up to three cache breakpoints. */\nexport const renderAnthropicSegmentedSystemPrompt = async (input: {\n  systemPrompt: Tokenizable\n  standingInstructions: Iterable<Tokenizable>\n  memories: Iterable<Memory>\n  retrievables: Iterable<Retrievable>\n  bucketOrder: ChatCompletionsBucketOrder\n  cacheBreakpoints: AnthropicCacheBreakpoints\n  cacheTtl?: '5m' | '1h'\n  renderStandingInstructions: ChatHelpersCommon['renderStandingInstructions']\n  renderMemories: ChatHelpersCommon['renderMemories']\n  renderRetrievables: ChatHelpersCommon['renderRetrievables']\n  renderRetrievableSafetyDirective: ChatHelpersCommon['renderRetrievableSafetyDirective']\n  renderFirstPartyRetrievables: ChatHelpersCommon['renderFirstPartyRetrievables']\n  renderThirdPartyPublicRetrievables: ChatHelpersCommon['renderThirdPartyPublicRetrievables']\n  renderThirdPartyPrivateRetrievables: ChatHelpersCommon['renderThirdPartyPrivateRetrievables']\n  renderRetrievableHandleBody?: ChatHelpersCommon['renderRetrievableHandleBody']\n  renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n  renderCtx?: unknown\n  warn?: (msg: string) => void\n}): Promise<AnthropicTextBlockParam[]> => {\n  const parts: string[] = []\n  const base = input.systemPrompt.render(input.renderCtx as never)\n  if (base) parts.push(base)\n  for (const label of input.bucketOrder) {\n    if (label === 'timeline') break\n    if (label === 'standingInstructions') {\n      const s = input.renderStandingInstructions(input.standingInstructions)\n      if (s) parts.push(s)\n    } else if (label === 'memories') {\n      const s = input.renderMemories(Array.from(input.memories, memoryToAttrs))\n      if (s) parts.push(s)\n    } else if (label === 'retrievables') {\n      const s = await input.renderRetrievables(Array.from(input.retrievables, retrievableToAttrs), {\n        renderRetrievableSafetyDirective: input.renderRetrievableSafetyDirective,\n        renderFirstPartyRetrievables: input.renderFirstPartyRetrievables,\n        renderThirdPartyPublicRetrievables: input.renderThirdPartyPublicRetrievables,\n        renderThirdPartyPrivateRetrievables: input.renderThirdPartyPrivateRetrievables,\n        renderRetrievableHandleBody: input.renderRetrievableHandleBody,\n        renderUntrustedContent: input.renderUntrustedContent,\n      })\n      if (s) parts.push(s)\n    }\n  }\n  const blocks: AnthropicTextBlockParam[] = parts.map((text) => ({\n    type: 'text' as const,\n    text,\n  }))\n  if (\n    input.cacheBreakpoints !== 'off' &&\n    blocks.length &&\n    (input.cacheBreakpoints === 'system-only' ||\n      input.bucketOrder.indexOf('timeline') === input.bucketOrder.length - 1)\n  ) {\n    const cache = {\n      type: 'ephemeral' as const,\n      ...(input.cacheTtl ? { ttl: input.cacheTtl } : {}),\n    }\n    blocks[blocks.length - 1] = {\n      ...blocks[blocks.length - 1]!,\n      cache_control: cache,\n    }\n  } else if (\n    input.cacheBreakpoints === 'auto' &&\n    input.bucketOrder.indexOf('timeline') !== input.bucketOrder.length - 1\n  )\n    input.warn?.(\n      'Anthropic cache tail breakpoints disabled because timeline is not the last bucket.'\n    )\n  return blocks\n}\n/** Default segmented system renderer. */\nexport const defaultRenderAnthropicSegmentedSystemPrompt = renderAnthropicSegmentedSystemPrompt\n\n/**\n * Computes the SHA-256 fingerprint used for Anthropic thinking replay.\n *\n * The input is the exact assembled request prefix: model, resolved system, tools, and messages\n * through the content block immediately before the thinking block. Assembles the Anthropic-shaped\n * prefix object and delegates the canonicalisation + hashing to the shared, wire-agnostic\n * {@link canonicalFingerprint} primitive: object keys are recursively sorted; array order and block\n * boundaries are preserved.\n */\nexport const fingerprintAnthropicMessagesPrefix = async (input: {\n  model: string\n  system?: string | AnthropicTextBlockParam[]\n  tools?: AnthropicTool[]\n  messages: AnthropicMessageParam[]\n  throughBlock?: { messageIndex: number; contentIndex: number }\n}): Promise<string> => {\n  const messages =\n    input.throughBlock === undefined\n      ? input.messages\n      : input.messages.slice(0, input.throughBlock.messageIndex + 1).map((message, index) => ({\n          ...message,\n          content:\n            Array.isArray(message.content) && index === input.throughBlock!.messageIndex\n              ? message.content.slice(0, input.throughBlock!.contentIndex)\n              : message.content,\n        }))\n  return canonicalFingerprint({\n    model: input.model,\n    system: input.system,\n    tools: input.tools,\n    messages,\n  })\n}\n\n/** Converts an eligible stored Anthropic thinking payload into byte-exact wire blocks. */\nexport const renderAnthropicThinkingBlocks = (input: {\n  thought: Thought\n  model: string\n  prefixFingerprint: string\n  replayCompatibility: ReadonlyArray<string>\n  warn?: (msg: string) => void\n}): AnthropicContentBlockParam[] => {\n  if (!input.replayCompatibility.includes(input.thought.replayCompatibility ?? '')) return []\n  const payload = input.thought.payload as Partial<AnthropicThinkingReplayPayload> | undefined\n  if (!payload || payload.prefixFingerprint !== input.prefixFingerprint) {\n    input.warn?.(`Dropping stale Anthropic thinking signature for thought ${input.thought.id}.`)\n    return []\n  }\n  if (\n    payload.variant === 'thinking' &&\n    typeof payload.thinking === 'string' &&\n    typeof payload.signature === 'string'\n  )\n    return [\n      {\n        type: 'thinking',\n        thinking: payload.thinking,\n        signature: payload.signature,\n      },\n    ]\n  if (payload.variant === 'redacted_thinking' && typeof payload.data === 'string')\n    return [{ type: 'redacted_thinking', data: payload.data }]\n  return []\n}\n/** Default thinking replay renderer. */\nexport const defaultRenderAnthropicThinkingBlocks = renderAnthropicThinkingBlocks\n\n/** Renders one ADK timeline message using an identity-bearing content envelope. */\nexport const renderAnthropicTimelineMessage = async (input: {\n  message: Message\n  selfIdentity: string\n  unsupportedMediaPolicy: UnsupportedMediaPolicy\n  renderAnthropicMediaBlocks: AnthropicMessagesHelpers['renderAnthropicMediaBlocks']\n  warn?: (msg: string) => void\n}): Promise<AnthropicMessageParam | null> => {\n  const m = input.message\n  const identifier =\n    m.identity?.identifier === null || m.identity?.identifier === undefined\n      ? ''\n      : String(m.identity.identifier)\n  const representation = m.identity?.representation?.toString() || identifier\n  const text = neutraliseDeveloperRulesTag(m.content?.toString() ?? '')\n  const own = m.role === 'assistant' && identifier === input.selfIdentity\n  let rendered = text\n  if (identifier && !(m.role === 'assistant' && own)) {\n    const tag = m.role === 'user' ? 'message' : 'peer_agent_output'\n    const from = escapeXmlAttribute(representation)\n    rendered = `<${tag}_${m.id} from=\"${from}\"${m.role === 'user' ? ' role=\"user\"' : ''}>\\\\n${text}\\\\n</${tag}_${m.id}>`\n  }\n  const blocks: AnthropicContentBlockParam[] = []\n  if (rendered.length) blocks.push({ type: 'text', text: rendered })\n  for (const media of m.attachments)\n    blocks.push(\n      ...(await input.renderAnthropicMediaBlocks({\n        media,\n        unsupportedMediaPolicy: input.unsupportedMediaPolicy,\n        renderUntrustedContent,\n        renderTrustedContent,\n        warn: input.warn,\n      }))\n    )\n  if (!blocks.length) return null\n  return { role: m.role, content: blocks }\n}\n/** Default timeline renderer. */\nexport const defaultRenderAnthropicTimelineMessage = renderAnthropicTimelineMessage\n\n/** Assembles Anthropic system content, messages, tools, and safely replayable thinking. */\nexport const buildAnthropicMessagesHistory = async (\n  input: Parameters<AnthropicMessagesHelpers['buildAnthropicMessagesHistory']>[0]\n): Promise<Awaited<ReturnType<AnthropicMessagesHelpers['buildAnthropicMessagesHistory']>>> => {\n  const deps = input as typeof input & {\n    anthropicToolsFromTools?: typeof anthropicToolsFromTools\n    descriptionToChatCompletionsJsonSchema?: (d: unknown) => JsonSchema\n    renderAnthropicThinkingBlocks?: typeof renderAnthropicThinkingBlocks\n    renderAnthropicMediaBlocks?: AnthropicMessagesHelpers['renderAnthropicMediaBlocks']\n  }\n  const tools = (deps.anthropicToolsFromTools ?? anthropicToolsFromTools)(input.tools.visible(), {\n    descriptionToChatCompletionsJsonSchema: (d: unknown) =>\n      descriptionToChatCompletionsJsonSchema(d as never),\n  })\n  const segmented = await input.renderAnthropicSegmentedSystemPrompt({\n    systemPrompt: input.systemPrompt,\n    standingInstructions: input.standingInstructions,\n    memories: input.memories,\n    retrievables: input.retrievables,\n    bucketOrder: input.bucketOrder,\n    cacheBreakpoints: input.cacheBreakpoints,\n    cacheTtl: input.cacheTtl,\n    renderStandingInstructions: input.renderStandingInstructions,\n    renderMemories: input.renderMemories,\n    renderRetrievables: input.renderRetrievables,\n    renderRetrievableSafetyDirective: input.renderRetrievableSafetyDirective,\n    renderFirstPartyRetrievables: input.renderFirstPartyRetrievables,\n    renderThirdPartyPublicRetrievables: input.renderThirdPartyPublicRetrievables,\n    renderThirdPartyPrivateRetrievables: input.renderThirdPartyPrivateRetrievables,\n    renderRetrievableHandleBody: input.renderRetrievableHandleBody,\n    renderUntrustedContent: input.renderUntrustedContent,\n    warn: input.warn,\n  })\n  const system =\n    input.cacheBreakpoints === 'off'\n      ? await input.renderChatCompletionsSystemPrompt({\n          systemPrompt: input.systemPrompt,\n          standingInstructions: input.standingInstructions,\n          memories: input.memories,\n          retrievables: input.retrievables,\n          bucketOrder: input.bucketOrder,\n          renderStandingInstructions: input.renderStandingInstructions,\n          renderMemories: input.renderMemories,\n          renderRetrievables: input.renderRetrievables,\n          renderRetrievableSafetyDirective: input.renderRetrievableSafetyDirective,\n          renderFirstPartyRetrievables: input.renderFirstPartyRetrievables,\n          renderThirdPartyPublicRetrievables: input.renderThirdPartyPublicRetrievables,\n          renderThirdPartyPrivateRetrievables: input.renderThirdPartyPrivateRetrievables,\n          renderRetrievableHandleBody: input.renderRetrievableHandleBody,\n          renderUntrustedContent: input.renderUntrustedContent,\n        })\n      : segmented\n  const items: Array<\n    | { kind: 'message'; at: number; value: Message }\n    | { kind: 'thought'; at: number; value: Thought }\n    | { kind: 'tool'; at: number; value: ToolCall }\n  > = [...input.messages].map((value) => ({\n    kind: 'message',\n    at: value.createdAt.toMillis(),\n    value,\n  }))\n  const filteredThoughts = input.filterThoughts(\n    input.thoughts,\n    input.thoughtSurfacing,\n    input.selfIdentity,\n    input.replayCompatibility\n  )\n  for (const value of filteredThoughts)\n    items.push({ kind: 'thought', at: value.createdAt.toMillis(), value })\n  for (const value of input.toolCalls)\n    items.push({ kind: 'tool', at: value.createdAt.toMillis(), value })\n  items.sort((a, b) => a.at - b.at)\n  const messages: AnthropicMessageParam[] = []\n  const replayCandidates: Array<{\n    block: AnthropicContentBlockParam\n    thought: Thought\n  }> = []\n  const append = (message: AnthropicMessageParam): void => {\n    if (typeof message.content === 'string' && message.content.length === 0) return\n    const previous = messages[messages.length - 1]\n    if (previous && previous.role === message.role) {\n      const left =\n        typeof previous.content === 'string'\n          ? [{ type: 'text' as const, text: previous.content }]\n          : previous.content\n      const right =\n        typeof message.content === 'string'\n          ? [{ type: 'text' as const, text: message.content }]\n          : message.content\n      if (left.length || right.length) {\n        input.warn?.(`Merged consecutive Anthropic ${message.role} turns during history assembly.`)\n        messages[messages.length - 1] = {\n          role: message.role,\n          content: [...left, ...right],\n        }\n      }\n      return\n    }\n    if (Array.isArray(message.content) && message.content.length === 0) return\n    messages.push(message)\n  }\n  for (const item of items) {\n    if (item.kind === 'message') {\n      const rendered = await input.renderAnthropicTimelineMessage({\n        message: item.value,\n        selfIdentity: input.selfIdentity,\n        unsupportedMediaPolicy: input.unsupportedMediaPolicy,\n        renderAnthropicMediaBlocks:\n          deps.renderAnthropicMediaBlocks ?? defaultRenderAnthropicMediaBlocks,\n        warn: input.warn,\n      })\n      if (rendered) {\n        append(rendered)\n      }\n    } else if (item.kind === 'tool') {\n      const tc = item.value\n      if (!/^[a-zA-Z0-9_-]+$/.test(tc.id))\n        input.warn?.(\n          `Anthropic tool id \"${tc.id}\" violates required charset ^[a-zA-Z0-9_-]+$; sending it unchanged.`\n        )\n      const use = {\n        type: 'tool_use' as const,\n        id: tc.id,\n        name: tc.tool,\n        input: tc.args,\n      }\n      append({ role: 'assistant', content: [use] })\n      // Instance identity prevents duplicate ids from pairing a call with another call's result.\n      let result = input.renderedToolCallResults.get(tc)\n      if (!result) {\n        const tool = input.tools.get(tc.tool)\n        result = await input.renderAnthropicToolCallResult({\n          toolCall: tc,\n          results: tc.results as never,\n          tool,\n          renderUntrustedContent: input.renderUntrustedContent,\n          renderTrustedContent: input.renderTrustedContent,\n          renderAnthropicMediaBlocks:\n            deps.renderAnthropicMediaBlocks ?? defaultRenderAnthropicMediaBlocks,\n          unsupportedMediaPolicy: input.unsupportedMediaPolicy,\n          warn: input.warn,\n        })\n      }\n      append({ role: 'user', content: [result] })\n    } else {\n      const thought = item.value\n      const payload = thought.payload as Partial<AnthropicThinkingReplayPayload> | undefined\n      // Replay validation is deferred until after role merging.  Give the renderer the\n      // stored value so it can select the compatible, well-formed wire block; the\n      // canonical prefix is checked in the second pass below.  Suppress its stale\n      // warning because that decision belongs to the second pass.\n      const blocks = (deps.renderAnthropicThinkingBlocks ?? renderAnthropicThinkingBlocks)({\n        thought,\n        model: input.model,\n        prefixFingerprint:\n          typeof payload?.prefixFingerprint === 'string' ? payload.prefixFingerprint : '',\n        replayCompatibility: input.replayCompatibility,\n        warn: undefined,\n      })\n      if (blocks.length) {\n        append({ role: 'assistant', content: blocks })\n        for (const block of blocks) replayCandidates.push({ block, thought })\n      } else if (thought.payload === undefined)\n        append({\n          role: 'assistant',\n          content: input.renderThought(thought.content.toString(), {\n            nonce: thought.id,\n            kind: 'self-reasoning',\n            from: String(thought.identity?.identifier ?? ''),\n          }),\n        })\n    }\n  }\n  if (messages[0]?.role === 'assistant') {\n    input.warn?.(\n      'Dropped leading Anthropic assistant history because Messages requires a leading user turn.'\n    )\n    messages.shift()\n  }\n\n  // Candidate positions are located in the post-merge array.  Fingerprints use a\n  // zero-based message/content position, and throughBlock excludes that block itself\n  // (and everything after it).  All decisions use this unchanged pass-1 array, so\n  // dropping an earlier block cannot shift a later candidate's position.\n  const droppedBlocks = new Set<AnthropicContentBlockParam>()\n  for (const candidate of replayCandidates) {\n    const messageIndex = messages.findIndex(\n      (message) => Array.isArray(message.content) && message.content.includes(candidate.block)\n    )\n    if (messageIndex < 0) continue\n    const contentIndex = (messages[messageIndex]!.content as AnthropicContentBlockParam[]).indexOf(\n      candidate.block\n    )\n    const payload = candidate.thought.payload as Partial<AnthropicThinkingReplayPayload> | undefined\n    const prefixFingerprint = await fingerprintAnthropicMessagesPrefix({\n      model: input.model,\n      system,\n      tools,\n      messages,\n      throughBlock: { messageIndex, contentIndex },\n    })\n    if (payload?.prefixFingerprint !== prefixFingerprint) {\n      input.warn?.(\n        `Dropping stale Anthropic thinking signature for thought ${candidate.thought.id}.`\n      )\n      droppedBlocks.add(candidate.block)\n    }\n  }\n  if (droppedBlocks.size) {\n    for (let index = messages.length - 1; index >= 0; index--) {\n      const message = messages[index]!\n      if (!Array.isArray(message.content)) continue\n      const content = message.content.filter((block) => !droppedBlocks.has(block))\n      if (content.length === 0) messages.splice(index, 1)\n      else if (content.length !== message.content.length) messages[index] = { ...message, content }\n    }\n  }\n\n  // Cache message-side breakpoints only after role merging has produced the final wire messages.\n  // Anthropic accepts cache_control on text, image, document, and tool-result blocks, but not on\n  // every member of ContentBlockParam (notably thinking and tool-use blocks).\n  const cache = {\n    type: 'ephemeral' as const,\n    ...(input.cacheTtl ? { ttl: input.cacheTtl } : {}),\n  }\n  const canCacheBlock = (\n    block: AnthropicContentBlockParam\n  ): block is\n    | AnthropicTextBlockParam\n    | AnthropicImageBlockParam\n    | AnthropicDocumentBlockParam\n    | AnthropicToolResultBlockParam =>\n    block.type === 'text' ||\n    block.type === 'image' ||\n    block.type === 'document' ||\n    block.type === 'tool_result'\n  let emittedBreakpoints = Array.isArray(system)\n    ? system.filter((block) => block.cache_control !== undefined).length\n    : 0\n  if (\n    input.cacheBreakpoints === 'auto' &&\n    input.bucketOrder.indexOf('timeline') === input.bucketOrder.length - 1\n  ) {\n    const toolResultMessageIndex = messages.findLastIndex(\n      (message) =>\n        message.role === 'user' &&\n        Array.isArray(message.content) &&\n        message.content.some((block) => block.type === 'tool_result')\n    )\n    const finalUserMessageIndex = messages.findLastIndex((message) => message.role === 'user')\n    const candidates = [toolResultMessageIndex, finalUserMessageIndex]\n    let placedBlock: { messageIndex: number; contentIndex: number } | undefined\n    for (const messageIndex of candidates) {\n      if (messageIndex < 0) continue\n      const message = messages[messageIndex]!\n      if (!Array.isArray(message.content) || message.content.length === 0) continue\n      const contentIndex = message.content.length - 1\n      if (placedBlock?.messageIndex === messageIndex && placedBlock.contentIndex === contentIndex)\n        continue\n      if (emittedBreakpoints >= 4) {\n        input.warn?.(\n          'Anthropic prompt-cache breakpoint cap of 4 exceeded; message breakpoint was not placed.'\n        )\n        continue\n      }\n      const block = message.content[contentIndex]!\n      if (!canCacheBlock(block)) continue\n      const content = [...message.content]\n      content[contentIndex] = { ...block, cache_control: cache }\n      messages[messageIndex] = { ...message, content }\n      emittedBreakpoints++\n      placedBlock = { messageIndex, contentIndex }\n    }\n  }\n  return {\n    ...(system.length ? { system } : {}),\n    messages,\n    ...(tools.length ? { tools } : {}),\n  }\n}\n/** Default history assembler. */\nexport const defaultBuildAnthropicMessagesHistory = buildAnthropicMessagesHistory\n"],"mappings":";;;;;;;;;;;AA6FA,IAAa,2BACX,OACA,SAEA,MAAM,KAAK,SAAS;CAClB,MAAM,YAAY,KAAK,SAAS;CAChC,MAAM,SAAS,KAAK,uCAClB,UAAU,WACZ;CACA,OAAO;EACL,MAAM,UAAU;EAChB,GAAI,UAAU,cAAc,EAAE,aAAa,UAAU,YAAY,IAAI,CAAC;EACtE,cAAc,OAAO,KAAK,MAAM,EAAE,SAAS,IAAI,SAAS;GAAE,MAAM;GAAU,YAAY,CAAC;EAAE;CAC3F;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