{"version":3,"file":"helpers.cjs","names":[],"sources":["../../../../src/batteries/llm/claude_code_cli/helpers.ts"],"sourcesContent":["/**\n * Swappable translation helpers for rendering ADK state into the Claude Code CLI's `-p` prompt\n * string and MCP tool-result content.\n *\n * @module @nhtio/adk/batteries/llm/claude_code_cli/helpers\n *\n * @remarks\n * The wire-shape-agnostic helpers (`renderUntrustedContent`, `renderMemories`,\n * `renderChatCompletionsSystemPrompt`, `toolsToChatCompletionsTools`, …) are shared with every\n * other Chat-family battery via `../chat_common/helpers` and re-exported here under their\n * original names. Only the battery-specific helpers are defined here:\n * `renderClaudeCodeCliTimelineMessage` (plain text — no native image side-channel, unlike\n * Ollama's `images[]`), `renderClaudeCodeCliToolCallResult` (the inbound-history counterpart to\n * the outbound MCP-result rendering `adapter.ts` performs directly), and\n * `buildClaudeCodeCliPrompt` (the top-level history-to-prompt assembler — a direct structural\n * port of `buildOllamaHistory`'s ordering, collapsed to a single joined string).\n */\n\nimport { Media } from '@nhtio/adk/common'\nimport { E_CLAUDE_CODE_CLI_UNSUPPORTED_MEDIA_MODALITY } from './exceptions'\nimport {\n  escapeXmlAttribute,\n  memoryToAttrs,\n  retrievableToAttrs,\n  renderTrustedContent,\n  renderUntrustedContent,\n  neutraliseDeveloperRulesTag,\n  sanitizeMimeType,\n  sanitizeFilenameForDescription,\n  floorTrustTier,\n  looksLikeSpooledArtifact,\n  renderArtifactHandleBody,\n} from '../chat_common/helpers'\nimport type { ChatHelpersCommon } from '../chat_common/types'\nimport type {\n  ClaudeCodeCliHelpers,\n  MemoryAttrs,\n  RetrievableAttrs,\n  ChatCompletionsBucketOrder,\n  UnsupportedMediaPolicy,\n} from './types'\nimport type {\n  Tool,\n  ArtifactTool,\n  ToolRegistry,\n  Tokenizable,\n  Memory,\n  Message,\n  Thought,\n  ToolCall,\n  Retrievable,\n  SpooledArtifact,\n  MediaModalityHazard,\n  MediaStashEntry,\n} from '@nhtio/adk/common'\n\n// ─── Re-exported wire-shape-agnostic helpers (shared submodule) ───────────────\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  renderRetrievableHandleBody,\n  defaultRenderRetrievableHandleBody,\n  renderArtifactHandleBody,\n  defaultRenderArtifactHandleBody,\n  renderThought,\n  defaultRenderThought,\n  filterThoughts,\n  defaultFilterThoughts,\n  toolsToChatCompletionsTools,\n  defaultToolsToChatCompletionsTools,\n  renderChatCompletionsSystemPrompt,\n  defaultRenderChatCompletionsSystemPrompt,\n  looksLikeSpooledArtifact,\n} from '../chat_common/helpers'\n\n// ─── Media rendering (text-only — no native image channel on either wire direction) ──\n\nconst DEFAULT_STASH_FALLBACK_KEYS: ReadonlyArray<string> = [\n  'text:transcript',\n  'text:caption',\n  'text:description',\n]\n\nconst modalityHazardToAttr = (h: MediaModalityHazard): 'inert' | 'extractable' | 'opaque' => {\n  if (h === 'inert') return 'inert'\n  if (h === 'extractable-instructions') return 'extractable'\n  return 'opaque'\n}\n\nconst formatBytesHumanReadable = (bytes: number | undefined): string => {\n  if (bytes === undefined || !Number.isFinite(bytes)) return 'unknown size'\n  if (bytes < 1024) return `${bytes} B`\n  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`\n  if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`\n  return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`\n}\n\nconst isMediaTextStashEntry = (e: unknown): e is MediaStashEntry => {\n  if (!e || typeof e !== 'object') return false\n  const r = e as Record<string, unknown>\n  return typeof r.value === 'string' && typeof r.trustTier === 'string'\n}\n\nconst resolveFallbackStash = (\n  media: Media,\n  keys: ReadonlyArray<string>\n): { text: string; entryTier: MediaStashEntry['trustTier'] } | undefined => {\n  for (const key of keys) {\n    const entry = media.stash.get(key)\n    if (isMediaTextStashEntry(entry)) {\n      return { text: entry.value as string, entryTier: entry.trustTier }\n    }\n  }\n  return undefined\n}\n\nconst renderTextInEnvelope = (\n  text: string,\n  args: {\n    trustTier: MediaStashEntry['trustTier']\n    modality: 'inert' | 'extractable' | 'opaque'\n    nonce: string\n    toolName: string | undefined\n    renderTrustedContent: ChatHelpersCommon['renderTrustedContent']\n    renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n  }\n): string => {\n  if (args.trustTier === 'first-party') {\n    return args.renderTrustedContent(text, {\n      nonce: args.nonce,\n      kind: 'media-fallback',\n      tool: args.toolName,\n      modality: args.modality,\n    })\n  }\n  return args.renderUntrustedContent(text, {\n    nonce: args.nonce,\n    kind: 'media-fallback',\n    tool: args.toolName,\n    modality: args.modality,\n  })\n}\n\nconst renderSyntheticMediaDescription = (media: Media, byteLen: number | undefined): string =>\n  `[media: ${sanitizeFilenameForDescription(media.filename)}, ${sanitizeMimeType(media.mimeType, media.kind === 'image' || media.kind === 'audio' ? media.kind : undefined)}, ${formatBytesHumanReadable(byteLen)}]`\n\nconst renderMediaIdMarker = (media: Media): string =>\n  `[media id: ${media.id} | ${sanitizeFilenameForDescription(media.filename)}]`\n\n/**\n * Render a single {@link Media} to plain text for the Claude Code CLI wire — EVERY modality\n * (including image) routes through `unsupportedMediaPolicy`, since a `-p` prompt string and an\n * MCP tool-result's text content block both lack a native image side-channel, unlike Ollama's\n * `images[]` or Anthropic's native `image` content block.\n */\nconst renderMediaAsText = async (input: {\n  media: Media\n  toolName: string | undefined\n  nonce: string\n  unsupportedMediaPolicy: UnsupportedMediaPolicy\n  renderTrustedContent: ChatHelpersCommon['renderTrustedContent']\n  renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n  warn?: (msg: string) => void\n}): Promise<string> => {\n  const { media, toolName, nonce, unsupportedMediaPolicy, warn } = input\n  const modality = modalityHazardToAttr(media.modalityHazard)\n\n  const fallbackText = async (\n    keys: ReadonlyArray<string>,\n    allowSyntheticFallthrough: boolean\n  ): Promise<string> => {\n    const fallback = resolveFallbackStash(media, keys)\n    if (fallback) {\n      return renderTextInEnvelope(fallback.text, {\n        trustTier: floorTrustTier(media.trustTier, fallback.entryTier),\n        modality,\n        nonce,\n        toolName,\n        renderTrustedContent: input.renderTrustedContent,\n        renderUntrustedContent: input.renderUntrustedContent,\n      })\n    }\n    if (!allowSyntheticFallthrough) {\n      warn?.(\n        `unsupportedMediaPolicy='fallback-stash' for ${media.filename}: no matching stash entry — falling through to synthetic description.`\n      )\n    }\n    const byteLen = await media.byteLength()\n    return renderTextInEnvelope(renderSyntheticMediaDescription(media, byteLen), {\n      trustTier: media.trustTier,\n      modality,\n      nonce,\n      toolName,\n      renderTrustedContent: input.renderTrustedContent,\n      renderUntrustedContent: input.renderUntrustedContent,\n    })\n  }\n\n  if (unsupportedMediaPolicy === 'throw') {\n    throw new E_CLAUDE_CODE_CLI_UNSUPPORTED_MEDIA_MODALITY([\n      media.kind,\n      media.mimeType,\n      media.filename,\n    ])\n  }\n  if (\n    unsupportedMediaPolicy === 'fallback-stash' ||\n    (typeof unsupportedMediaPolicy === 'object' && unsupportedMediaPolicy.mode === 'fallback-stash')\n  ) {\n    const keys =\n      typeof unsupportedMediaPolicy === 'object'\n        ? unsupportedMediaPolicy.stashKeys\n        : DEFAULT_STASH_FALLBACK_KEYS\n    return fallbackText(keys, false)\n  }\n  return fallbackText([], true)\n}\n\n// ─── renderClaudeCodeCliTimelineMessage ────────────────────────────────────────\n\n/**\n * Renders a single timeline {@link @nhtio/adk!Message} into plain text for the `-p` prompt\n * string — structurally identical to `renderOllamaTimelineMessage`'s trust-envelope/identity\n * logic, except every attachment routes through `unsupportedMediaPolicy` and is appended as text\n * (the \"v1 prompt is text-only\" limitation).\n */\nexport const renderClaudeCodeCliTimelineMessage = async (input: {\n  message: Message\n  selfIdentity: string\n  unsupportedMediaPolicy: UnsupportedMediaPolicy\n  warn?: (msg: string) => void\n}): Promise<string> => {\n  const { message, selfIdentity, unsupportedMediaPolicy, warn } = input\n  const identifier =\n    message.identity?.identifier !== undefined && message.identity?.identifier !== null\n      ? String(message.identity.identifier)\n      : ''\n  const representationRaw =\n    message.identity?.representation !== undefined && message.identity?.representation !== null\n      ? message.identity.representation.toString()\n      : ''\n  const representation = representationRaw.length > 0 ? representationRaw : identifier\n  const text = neutraliseDeveloperRulesTag(\n    message.content !== undefined ? message.content.toString() : ''\n  )\n  const createdAtStr = message.createdAt.toISO?.() ?? ''\n  const createdAtAttr = createdAtStr ? ` createdAt=\"${escapeXmlAttribute(createdAtStr)}\"` : ''\n  const attachments = message.attachments\n\n  let envelopeText: string\n  if (message.role === 'user') {\n    if (identifier.length === 0) {\n      envelopeText = text\n    } else {\n      const fromAttr = escapeXmlAttribute(representation)\n      envelopeText = `<message_${message.id} from=\"${fromAttr}\" role=\"user\"${createdAtAttr}>\\n${text}\\n</message_${message.id}>`\n    }\n  } else {\n    if (identifier.length === 0 || identifier === selfIdentity) {\n      envelopeText = text\n    } else {\n      const fromAttr = escapeXmlAttribute(representation)\n      envelopeText = `<peer_agent_output_${message.id} from=\"${fromAttr}\"${createdAtAttr}>\\n${text}\\n</peer_agent_output_${message.id}>`\n    }\n  }\n\n  const extraTexts: string[] = []\n  for (const media of attachments) {\n    const rendered = await renderMediaAsText({\n      media,\n      toolName: undefined,\n      nonce: message.id,\n      unsupportedMediaPolicy,\n      renderTrustedContent,\n      renderUntrustedContent,\n      warn,\n    })\n    extraTexts.push(renderMediaIdMarker(media))\n    extraTexts.push(rendered)\n  }\n\n  const contentParts: string[] = []\n  if (envelopeText.length > 0) contentParts.push(envelopeText)\n  for (const t of extraTexts) contentParts.push(t)\n  return contentParts.join('\\n')\n}\n/** Default timeline-message renderer; alias of {@link renderClaudeCodeCliTimelineMessage}. */\nexport const defaultRenderClaudeCodeCliTimelineMessage = renderClaudeCodeCliTimelineMessage\n\n// ─── renderClaudeCodeCliToolCallResult (inbound-history direction) ─────────────\n\nconst renderArtifactHandleBodyLegacy = (\n  toolCall: ToolCall,\n  artifact: SpooledArtifact,\n  byteLength: number,\n  lineCount: number\n): string =>\n  renderArtifactHandleBody({\n    callId: toolCall.id,\n    artifact,\n    byteLength,\n    lineCount,\n  })\n\n/**\n * Render a completed {@link @nhtio/adk!ToolCall}'s result to plain text for the INBOUND history\n * direction (how a past tool call reads back into a subsequent dispatch's rendered prompt) —\n * always a string, since the `-p` prompt has no structured-content channel. Media results are\n * routed through the same text-only media renderer used by the timeline path.\n */\nexport const renderClaudeCodeCliToolCallResult = 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  unsupportedMediaPolicy: UnsupportedMediaPolicy\n  warn?: (msg: string) => void\n}): Promise<string> => {\n  const { toolCall, results, tool, warn, unsupportedMediaPolicy } = input\n  const isTrusted =\n    tool !== null && tool !== undefined && (tool as { trusted?: boolean }).trusted === true\n\n  if (tool === undefined) {\n    warn?.(\n      `Tool \"${toolCall.tool}\" is not present in the bound tool registry at render time; defaulting to untrusted envelope.`\n    )\n  }\n\n  const isMediaResult = Media.isMedia(results)\n  const isMediaArrayResult =\n    Array.isArray(results) && results.length > 0 && results.every((r) => Media.isMedia(r))\n  if (isMediaResult || isMediaArrayResult) {\n    const mediaList = isMediaResult ? [results as Media] : (results as Media[])\n    const parts: string[] = []\n    for (const media of mediaList) {\n      parts.push(renderMediaIdMarker(media))\n      parts.push(\n        await renderMediaAsText({\n          media,\n          toolName: toolCall.tool,\n          nonce: toolCall.checksum,\n          unsupportedMediaPolicy,\n          renderTrustedContent: input.renderTrustedContent,\n          renderUntrustedContent: input.renderUntrustedContent,\n          warn,\n        })\n      )\n    }\n    return parts.join('\\n')\n  }\n\n  if (Array.isArray(results)) {\n    const parts: string[] = []\n    for (const a of results) {\n      parts.push(await (a as SpooledArtifact).asString())\n    }\n    const joined = parts.join('\\n\\n')\n    return isTrusted\n      ? input.renderTrustedContent(joined, {\n          nonce: toolCall.checksum,\n          kind: 'trusted-tool-result',\n          tool: toolCall.tool,\n        })\n      : input.renderUntrustedContent(joined, {\n          nonce: toolCall.checksum,\n          kind: 'tool-result',\n          tool: toolCall.tool,\n        })\n  }\n\n  const isSpooled = looksLikeSpooledArtifact(results)\n\n  if (isSpooled && toolCall.inline === false) {\n    const artifact = 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 body = renderArtifactHandleBodyLegacy(toolCall, artifact, byteLength, lineCount)\n    return input.renderUntrustedContent(body, {\n      nonce: toolCall.checksum,\n      kind: 'artifact-handle',\n      tool: toolCall.tool,\n    })\n  }\n\n  const body = isSpooled\n    ? await (results as SpooledArtifact).asString()\n    : (results as Tokenizable).toString()\n\n  return isTrusted\n    ? input.renderTrustedContent(body, {\n        nonce: toolCall.checksum,\n        kind: 'trusted-tool-result',\n        tool: toolCall.tool,\n      })\n    : input.renderUntrustedContent(body, {\n        nonce: toolCall.checksum,\n        kind: 'tool-result',\n        tool: toolCall.tool,\n      })\n}\n/** Default tool-call-result renderer; alias of {@link renderClaudeCodeCliToolCallResult}. */\nexport const defaultRenderClaudeCodeCliToolCallResult = renderClaudeCodeCliToolCallResult\n\n// ─── buildClaudeCodeCliPrompt ───────────────────────────────────────────────────\n\ntype TimelineItem =\n  | { kind: 'message'; createdAt: number; value: Message }\n  | { kind: 'thought'; createdAt: number; value: Thought }\n  | { kind: 'toolCall'; createdAt: number; value: ToolCall }\n\n/**\n * Assembles the complete history for a dispatch into ONE joined prompt string — a direct\n * structural port of `buildOllamaHistory`'s ordering (leading system-prompt block, then the\n * timestamp-sorted timeline of messages/thoughts/tool-calls, then any trailing buckets after\n * `'timeline'` in `bucketOrder`), with the target shape collapsed from a message array to a\n * single string, since this wire has one `-p` positional argument.\n */\nexport const buildClaudeCodeCliPrompt = async (input: {\n  systemPrompt: Tokenizable\n  standingInstructions: Iterable<Tokenizable>\n  memories: Iterable<Memory>\n  retrievables: Iterable<Retrievable>\n  messages: Iterable<Message>\n  thoughts: Iterable<Thought>\n  toolCalls: Iterable<ToolCall>\n  tools: ToolRegistry\n  /** Pre-rendered results keyed by the same live ToolCall instances iterated below. */\n  renderedToolCallResults: Map<ToolCall, string>\n  bucketOrder: ChatCompletionsBucketOrder\n  selfIdentity: string\n  thoughtSurfacing: 'all-self' | 'latest-self' | 'all'\n  replayCompatibility: ReadonlyArray<string>\n  unsupportedMediaPolicy: UnsupportedMediaPolicy\n  renderCtx?: unknown\n  renderChatCompletionsSystemPrompt: ChatHelpersCommon['renderChatCompletionsSystemPrompt']\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  renderClaudeCodeCliTimelineMessage: ClaudeCodeCliHelpers['renderClaudeCodeCliTimelineMessage']\n  renderClaudeCodeCliToolCallResult: ClaudeCodeCliHelpers['renderClaudeCodeCliToolCallResult']\n  renderThought: ChatHelpersCommon['renderThought']\n  filterThoughts: ChatHelpersCommon['filterThoughts']\n  renderUntrustedContent: ChatHelpersCommon['renderUntrustedContent']\n  renderTrustedContent: ChatHelpersCommon['renderTrustedContent']\n  warn?: (msg: string) => void\n}): Promise<{\n  prompt: string\n  reasoningPayloads: Array<{ id: string; replayCompatibility: string; payload: unknown }>\n}> => {\n  const sections: string[] = []\n  const reasoningPayloads: Array<{ id: string; replayCompatibility: string; payload: unknown }> = []\n\n  const buckets = input.bucketOrder\n  const timelineIdx = buckets.indexOf('timeline')\n\n  const leadingSystem = await input.renderChatCompletionsSystemPrompt({\n    systemPrompt: input.systemPrompt,\n    renderCtx: input.renderCtx,\n    standingInstructions: input.standingInstructions,\n    memories: input.memories,\n    retrievables: input.retrievables,\n    bucketOrder: buckets,\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  if (leadingSystem.length > 0) {\n    sections.push(leadingSystem)\n  }\n\n  const includesTimeline = timelineIdx !== -1\n  if (includesTimeline) {\n    const survivingThoughts = input.filterThoughts(\n      input.thoughts,\n      input.thoughtSurfacing,\n      input.selfIdentity,\n      input.replayCompatibility\n    )\n\n    const items: TimelineItem[] = []\n    for (const m of input.messages) {\n      items.push({ kind: 'message', createdAt: m.createdAt.toMillis(), value: m })\n    }\n    for (const t of survivingThoughts) {\n      items.push({ kind: 'thought', createdAt: t.createdAt.toMillis(), value: t })\n    }\n    for (const tc of input.toolCalls) {\n      items.push({ kind: 'toolCall', createdAt: tc.createdAt.toMillis(), value: tc })\n    }\n    items.sort((a, b) => a.createdAt - b.createdAt)\n\n    const replaySet = new Set<string>([...input.replayCompatibility])\n\n    for (const item of items) {\n      if (item.kind === 'message') {\n        const rendered = await input.renderClaudeCodeCliTimelineMessage({\n          message: item.value,\n          selfIdentity: input.selfIdentity,\n          unsupportedMediaPolicy: input.unsupportedMediaPolicy,\n          warn: input.warn,\n        })\n        if (rendered.length > 0) sections.push(rendered)\n      } else if (item.kind === 'thought') {\n        const t = item.value\n        const identifier = String(t.identity?.identifier ?? '')\n        const isSelf = identifier === input.selfIdentity\n        const hasPayload = t.payload !== undefined\n        const compatTag = t.replayCompatibility\n\n        if (hasPayload && compatTag && replaySet.has(compatTag)) {\n          reasoningPayloads.push({ id: t.id, replayCompatibility: compatTag, payload: t.payload })\n          const envelope = input.renderThought(\n            t.content.toString(),\n            {\n              nonce: t.id,\n              kind: 'opaque-reasoning',\n              from: identifier,\n              createdAt: t.createdAt?.toISO?.() ?? undefined,\n              replayCompatibility: compatTag,\n            },\n            t.payload\n          )\n          sections.push(envelope)\n        } else if (!hasPayload) {\n          const envelope = input.renderThought(t.content.toString(), {\n            nonce: t.id,\n            kind: isSelf ? 'self-reasoning' : 'peer-reasoning',\n            from: identifier,\n            createdAt: t.createdAt?.toISO?.() ?? undefined,\n          })\n          sections.push(envelope)\n        }\n        // else: opaque, non-matching → elided.\n      } else {\n        const tc = item.value\n        const callHeader = `<tool_call id=\"${escapeXmlAttribute(tc.id)}\" tool=\"${escapeXmlAttribute(\n          tc.tool\n        )}\">\\n${JSON.stringify(tc.args)}\\n</tool_call>`\n        sections.push(callHeader)\n\n        // Instance identity is intentional: ids may collide across turns, while this is the same\n        // live primitive used by the producer. An id-keyed cache pairs an earlier call with the\n        // later call's result after a collision.\n        let rendered = input.renderedToolCallResults.get(tc)\n        if (rendered === undefined) {\n          const tool = input.tools.get?.(tc.tool)\n          rendered = await input.renderClaudeCodeCliToolCallResult({\n            toolCall: tc,\n            results: tc.results as\n              | Tokenizable\n              | SpooledArtifact\n              | SpooledArtifact[]\n              | Media\n              | Media[],\n            tool: tool as Tool | ArtifactTool | undefined,\n            renderUntrustedContent: input.renderUntrustedContent,\n            renderTrustedContent: input.renderTrustedContent,\n            unsupportedMediaPolicy: input.unsupportedMediaPolicy,\n            warn: input.warn,\n          })\n        }\n        sections.push(rendered)\n      }\n    }\n  }\n\n  if (includesTimeline) {\n    for (let i = timelineIdx + 1; i < buckets.length; i++) {\n      const label = buckets[i]!\n      if (label === 'standingInstructions') {\n        const block = input.renderStandingInstructions(input.standingInstructions)\n        if (block.length > 0) sections.push(block)\n      } else if (label === 'memories') {\n        const wrapped: Array<{ memory: Memory; attrs: MemoryAttrs }> = []\n        for (const m of input.memories) {\n          wrapped.push(memoryToAttrs(m))\n        }\n        const block = input.renderMemories(wrapped)\n        if (block.length > 0) sections.push(block)\n      } else if (label === 'retrievables') {\n        const wrapped: Array<{ retrievable: Retrievable; attrs: RetrievableAttrs }> = []\n        for (const r of input.retrievables) {\n          wrapped.push(retrievableToAttrs(r))\n        }\n        const block = await input.renderRetrievables(wrapped, {\n          renderRetrievableSafetyDirective: input.renderRetrievableSafetyDirective,\n          renderFirstPartyRetrievables: input.renderFirstPartyRetrievables,\n          renderThirdPartyPublicRetrievables: input.renderThirdPartyPublicRetrievables,\n          renderThirdPartyPrivateRetrievables: input.renderThirdPartyPrivateRetrievables,\n          renderUntrustedContent: input.renderUntrustedContent,\n        })\n        if (block.length > 0) sections.push(block)\n      }\n    }\n  }\n\n  return { prompt: sections.join('\\n\\n'), reasoningPayloads }\n}\n/** Default history assembler; alias of {@link buildClaudeCodeCliPrompt}. */\nexport const defaultBuildClaudeCodeCliPrompt = buildClaudeCodeCliPrompt\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA+FA,IAAM,8BAAqD;CACzD;CACA;CACA;AACF;AAEA,IAAM,wBAAwB,MAA+D;CAC3F,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