{"version":3,"file":"helpers.cjs","names":[],"sources":["../../../../src/batteries/llm/bedrock_converse/helpers.ts"],"sourcesContent":["/**\n * Translation helpers for the native Bedrock Converse battery.\n *\n * @module @nhtio/adk/batteries/llm/bedrock_converse/helpers\n *\n * @remarks\n * Every function is injectable via {@link BedrockConverseAdapterOptions.helpers} and has a\n * `default*` alias. Wire-agnostic renderers are re-exported unchanged from `../chat_common/helpers`;\n * only genuinely Converse-shaped logic lives here.\n */\n\nimport { isObject } from '@nhtio/adk/guards'\nimport {\n  descriptionToChatCompletionsJsonSchema,\n  filterThoughts,\n  looksLikeSpooledArtifact,\n  neutraliseDeveloperRulesTag,\n  normalizeToolName,\n  renderChatCompletionsSystemPrompt,\n  renderFirstPartyRetrievables,\n  renderMemories,\n  renderRetrievableSafetyDirective,\n  renderRetrievables,\n  renderStandingInstructions,\n  renderThirdPartyPrivateRetrievables,\n  renderThirdPartyPublicRetrievables,\n  renderThought,\n  renderTrustedContent,\n  renderUntrustedContent,\n} from '../chat_common/helpers'\nimport type { SpooledArtifact } from '@nhtio/adk/common'\nimport type { DescriptionLike } from '../chat_common/types'\nimport type {\n  Tool,\n  ArtifactTool,\n  Media,\n  Message,\n  Thought,\n  ToolCall,\n  Tokenizable,\n} from '@nhtio/adk/common'\nimport type {\n  ConverseContentBlock,\n  ConverseImageBlock,\n  ConverseMessage,\n  ConverseRequest,\n  ConverseRequestBuildInput,\n  ConverseToolSpec,\n  JsonSchema,\n  UnsupportedMediaPolicy,\n} from './types'\n\n// ─── Re-exported wire-agnostic renderers ──────────────────────────────────────\nexport {\n  descriptionToChatCompletionsJsonSchema,\n  defaultDescriptionToChatCompletionsJsonSchema,\n  renderUntrustedContent,\n  defaultRenderUntrustedContent,\n  renderTrustedContent,\n  defaultRenderTrustedContent,\n  renderStandingInstructions,\n  defaultRenderStandingInstructions,\n  renderMemories,\n  defaultRenderMemories,\n  renderRetrievables,\n  defaultRenderRetrievables,\n  renderRetrievableSafetyDirective,\n  defaultRenderRetrievableSafetyDirective,\n  renderFirstPartyRetrievables,\n  defaultRenderFirstPartyRetrievables,\n  renderThirdPartyPublicRetrievables,\n  defaultRenderThirdPartyPublicRetrievables,\n  renderThirdPartyPrivateRetrievables,\n  defaultRenderThirdPartyPrivateRetrievables,\n  renderThought,\n  defaultRenderThought,\n  filterThoughts,\n  defaultFilterThoughts,\n  renderChatCompletionsSystemPrompt,\n  defaultRenderChatCompletionsSystemPrompt,\n  renderArtifactHandleBody,\n  defaultRenderArtifactHandleBody,\n  renderRetrievableHandleBody,\n  defaultRenderRetrievableHandleBody,\n} from '../chat_common/helpers'\n\n/** Default context-bucket order for the system blocks; matches the other chat batteries. */\nexport const DEFAULT_CONVERSE_BUCKET_ORDER = [\n  'standingInstructions',\n  'memories',\n  'retrievables',\n  'timeline',\n] as const\n\n/**\n * JSON-Schema keywords Converse's schema dialect rejects.\n *\n * @remarks\n * Sending one produces a validation error that does not name the offending keyword, so they are\n * stripped rather than forwarded. Same class of problem as Gemini's OpenAPI subset.\n */\nconst UNSUPPORTED_SCHEMA_KEYS = new Set([\n  '$schema',\n  '$id',\n  '$ref',\n  '$defs',\n  'definitions',\n  'additionalProperties',\n  'patternProperties',\n  'allOf',\n  'anyOf',\n  'oneOf',\n  'not',\n  'const',\n  'examples',\n  'default',\n  'exclusiveMinimum',\n  'exclusiveMaximum',\n  'multipleOf',\n  'uniqueItems',\n  'minProperties',\n  'maxProperties',\n  'format',\n])\n\n/** Recursively strip schema keywords Converse rejects. */\nexport const sanitizeConverseSchema = (schema: unknown): JsonSchema => {\n  if (Array.isArray(schema)) return schema.map((s) => sanitizeConverseSchema(s)) as never\n  if (schema === null || typeof schema !== 'object') return schema as never\n  const out: Record<string, unknown> = {}\n  for (const [key, value] of Object.entries(schema as Record<string, unknown>)) {\n    if (UNSUPPORTED_SCHEMA_KEYS.has(key)) continue\n    out[key] = isObject(value) ? sanitizeConverseSchema(value) : value\n  }\n  return out as never\n}\n\n/** Default implementation; alias of {@link sanitizeConverseSchema}. */\nexport const defaultSanitizeConverseSchema = sanitizeConverseSchema\n\n/**\n * Converse rejects a `toolUseId` outside `[A-Za-z0-9_-]{1,64}`.\n *\n * @remarks\n * ADK ids are UUIDv6, which is already in-charset, but a caller-supplied id may not be — and the\n * rejection names neither the field nor the offending character.\n */\nexport const sanitizeToolUseId = (id: string): string => {\n  const cleaned = id.replace(/[^A-Za-z0-9_-]/g, '_')\n  return cleaned.length > 64 ? cleaned.slice(0, 64) : cleaned || 'tool_use'\n}\n\n/** Default implementation; alias of {@link sanitizeToolUseId}. */\nexport const defaultSanitizeToolUseId = sanitizeToolUseId\n\n/** ADK tools → native `toolConfig.tools`. */\nexport const toolsToConverseTools = (tools: Iterable<Tool | ArtifactTool>): ConverseToolSpec[] => {\n  const out: ConverseToolSpec[] = []\n  for (const tool of tools) {\n    const described = tool.describe()\n    const parameters = descriptionToChatCompletionsJsonSchema(\n      described.inputSchema as unknown as DescriptionLike\n    )\n    const sanitized = sanitizeConverseSchema(parameters)\n    out.push({\n      toolSpec: {\n        name: normalizeToolName(described.name),\n        description: String(described.description ?? ''),\n        // Converse requires an OBJECT schema even for a zero-arg tool; an empty schema is\n        // rejected, so a bare `{type:'object'}` stands in.\n        inputSchema: {\n          json:\n            sanitized && Object.keys(sanitized).length > 0\n              ? sanitized\n              : ({ type: 'object', properties: {} } as never),\n        },\n      },\n    })\n  }\n  return out\n}\n\n/** Default implementation; alias of {@link toolsToConverseTools}. */\nexport const defaultToolsToConverseTools = toolsToConverseTools\n\n/** Render one tool result into `toolResult.content[]`. */\nexport const renderConverseToolResult = async (input: {\n  toolCall: ToolCall\n  results: Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[]\n  tool: Tool | ArtifactTool | undefined\n  renderUntrustedContent: typeof renderUntrustedContent\n  renderTrustedContent: typeof renderTrustedContent\n  unsupportedMediaPolicy: UnsupportedMediaPolicy | undefined\n  warn?: (message: string) => void\n}): Promise<Array<{ text?: string; json?: Record<string, unknown> }>> => {\n  const { results, toolCall } = input\n  if (looksLikeSpooledArtifact(results)) {\n    // Referenced by handle, never inlined — same contract as the other batteries.\n    return [{ text: `[artifact ${String((results as { id?: unknown }).id ?? toolCall.id)}]` }]\n  }\n  const text = String(results ?? '')\n  return [\n    {\n      text: input.renderUntrustedContent(text, {\n        nonce: toolCall.id,\n        from: toolCall.tool,\n      } as never),\n    },\n  ]\n}\n\n/** Default implementation; alias of {@link renderConverseToolResult}. */\nexport const defaultRenderConverseToolResult = renderConverseToolResult\n\n/** Decode an ADK Media into a Converse image block. */\nexport const mediaToConverseImage = async (media: Media): Promise<ConverseImageBlock> => {\n  const bytes = (await media.asBytes()) as Uint8Array\n  let binary = ''\n  const chunk = 0x8000\n  for (let i = 0; i < bytes.length; i += chunk) {\n    binary += String.fromCharCode(...bytes.subarray(i, i + chunk))\n  }\n  const subtype = media.mimeType.split('/')[1]?.toLowerCase() ?? 'png'\n  const format = (['png', 'jpeg', 'gif', 'webp'] as const).includes(subtype as never)\n    ? (subtype as 'png' | 'jpeg' | 'gif' | 'webp')\n    : 'png'\n  return {\n    format,\n    source: {\n      bytes: typeof btoa === 'function' ? btoa(binary) : Buffer.from(bytes).toString('base64'),\n    },\n  }\n}\n\n/** Default implementation; alias of {@link mediaToConverseImage}. */\nexport const defaultMediaToConverseImage = mediaToConverseImage\n\n/**\n * Apply Converse's strict `user` ↔ `assistant` alternation to an already-ordered turn list.\n *\n * @remarks\n * Exported and separately testable because it is the single most consequential transformation in\n * this battery, and the one a gateway would otherwise perform invisibly.\n *\n * - `'merge'` concatenates consecutive same-role turns' content blocks. Lossless: the same blocks\n *   in the same order, in one turn — exactly what Converse would have accepted had the caller\n *   written it that way.\n * - `'filler'` inserts a placeholder opposite-role turn. LOSSIER — it fabricates model output that\n *   never existed — and offered only for callers who need positional stability across turns.\n * - `'reject'` returns the list untouched so Converse's own error surfaces. Use this when\n *   AUDITING: a repair applied before dispatch is invisible in the response, which makes a\n *   gateway's fix indistinguishable from a vendor's tolerance.\n */\nexport const enforceConverseAlternation = (\n  messages: ConverseMessage[],\n  policy: 'merge' | 'filler' | 'reject' = 'merge'\n): ConverseMessage[] => {\n  if (policy === 'reject' || messages.length < 2) return messages\n\n  if (policy === 'filler') {\n    const out: ConverseMessage[] = [messages[0]!]\n    for (let i = 1; i < messages.length; i++) {\n      const prev = out[out.length - 1]!\n      const curr = messages[i]!\n      if (prev.role === curr.role) {\n        out.push({\n          role: prev.role === 'user' ? 'assistant' : 'user',\n          content: [{ text: '...' }],\n        })\n      }\n      out.push(curr)\n    }\n    return out\n  }\n\n  const merged: ConverseMessage[] = [{ ...messages[0]!, content: [...messages[0]!.content] }]\n  for (let i = 1; i < messages.length; i++) {\n    const prev = merged[merged.length - 1]!\n    const curr = messages[i]!\n    if (prev.role === curr.role) prev.content.push(...curr.content)\n    else merged.push({ ...curr, content: [...curr.content] })\n  }\n  return merged\n}\n\n/** Default implementation; alias of {@link enforceConverseAlternation}. */\nexport const defaultEnforceConverseAlternation = enforceConverseAlternation\n\n/**\n * Assemble the native Converse request from ADK turn state. THE ordering seam.\n *\n * @remarks\n * The translation that makes this battery different from pointing `openai_chat_completions` at a\n * Converse-backed gateway:\n *\n *  - System text becomes a top-level `system[]`, never a turn.\n *  - A `ToolCall` becomes an `assistant` turn with a `{toolUse}` block, then a **`user`** turn with\n *    a `{toolResult}` block — Converse has no `tool` role.\n *  - Blocks accumulate on the CURRENT turn where possible, so prose and a tool call emitted in the\n *    same assistant turn stay in one turn (the shape Converse is designed around).\n *  - Alternation is applied last, under {@link ConverseRequestBuildInput.alternationPolicy}.\n *  - Timeline order is `createdAt`, matching the ordering guard's view, so what the guard validated\n *    is what gets dispatched.\n */\nexport const buildConverseRequest = async (\n  input: ConverseRequestBuildInput\n): Promise<ConverseRequest> => {\n  const h = input.helpers\n  const systemText = await renderChatCompletionsSystemPrompt({\n    systemPrompt: input.systemPrompt,\n    standingInstructions: input.standingInstructions,\n    memories: input.memories,\n    retrievables: input.retrievables,\n    bucketOrder: input.bucketOrder ?? DEFAULT_CONVERSE_BUCKET_ORDER,\n    renderStandingInstructions: h.renderStandingInstructions ?? renderStandingInstructions,\n    renderMemories: h.renderMemories ?? renderMemories,\n    renderRetrievables: h.renderRetrievables ?? renderRetrievables,\n    renderRetrievableSafetyDirective:\n      h.renderRetrievableSafetyDirective ?? renderRetrievableSafetyDirective,\n    renderFirstPartyRetrievables: h.renderFirstPartyRetrievables ?? renderFirstPartyRetrievables,\n    renderThirdPartyPublicRetrievables:\n      h.renderThirdPartyPublicRetrievables ?? renderThirdPartyPublicRetrievables,\n    renderThirdPartyPrivateRetrievables:\n      h.renderThirdPartyPrivateRetrievables ?? renderThirdPartyPrivateRetrievables,\n    renderUntrustedContent: h.renderUntrustedContent ?? renderUntrustedContent,\n  } as never)\n\n  const surfaced = filterThoughts(\n    input.thoughts,\n    input.thoughtSurfacing,\n    input.selfIdentity,\n    input.replayCompatibility\n  )\n\n  type Item =\n    | { at: number; kind: 'message'; value: Message }\n    | { at: number; kind: 'thought'; value: Thought }\n    | { at: number; kind: 'toolCall'; value: ToolCall }\n  const items: Item[] = []\n  for (const m of input.messages)\n    items.push({ at: m.createdAt.toMillis(), kind: 'message', value: m })\n  for (const t of surfaced) items.push({ at: t.createdAt.toMillis(), kind: 'thought', value: t })\n  for (const c of input.toolCalls)\n    items.push({ at: c.createdAt.toMillis(), kind: 'toolCall', value: c })\n  items.sort((a, b) => a.at - b.at)\n\n  const raw: ConverseMessage[] = []\n  /**\n   * Append blocks as their OWN turn, always.\n   *\n   * This deliberately does NOT coalesce same-role turns. Coalescing here would apply the merge\n   * unconditionally, BEFORE `alternationPolicy` is consulted — which silently defeated\n   * `'reject'`: two consecutive user messages arrived as one turn with two text blocks, so there\n   * was no violation left for Converse to rule on and an audit measured our own repair. Merging is\n   * `enforceConverseAlternation`'s job and only its job, so the policy stays honest.\n   *\n   * The one case that DOES belong in a single turn is a tool call and the prose introducing it,\n   * which the toolCall branch below emits together for exactly that reason.\n   */\n  const push = (role: 'user' | 'assistant', blocks: ConverseContentBlock[]): void => {\n    if (blocks.length === 0) return\n    raw.push({ role, content: blocks })\n  }\n\n  for (const item of items) {\n    if (item.kind === 'message') {\n      const text = neutraliseDeveloperRulesTag(String(item.value.content ?? ''))\n      const blocks: ConverseContentBlock[] = []\n      if (text.length > 0) blocks.push({ text })\n      for (const media of item.value.attachments ?? []) {\n        if (input.decodeMedia === undefined) continue\n        try {\n          blocks.push({ image: await input.decodeMedia(media) })\n        } catch (err) {\n          input.warn?.(`decodeMedia failed for ${media.filename}: ${String(err)}`)\n        }\n      }\n      push(item.value.role === 'assistant' ? 'assistant' : 'user', blocks)\n      continue\n    }\n\n    if (item.kind === 'thought') {\n      const envelope = renderThought(String(item.value.content ?? ''), {\n        nonce: item.value.id,\n        kind: 'self-reasoning',\n        from: input.selfIdentity,\n      } as never)\n      push('assistant', [{ text: envelope }])\n      continue\n    }\n\n    const tc = item.value\n    const id = sanitizeToolUseId(tc.id)\n    push('assistant', [\n      {\n        toolUse: {\n          toolUseId: id,\n          name: normalizeToolName(tc.tool),\n          input: (typeof tc.args === 'string'\n            ? JSON.parse(tc.args || '{}')\n            : (tc.args ?? {})) as Record<string, unknown>,\n        },\n      },\n    ])\n    push('user', [\n      {\n        toolResult: {\n          toolUseId: id,\n          content: input.renderedToolCallResults.get(tc) ?? [{ text: '' }],\n          status: tc.isError ? 'error' : 'success',\n        },\n      },\n    ])\n  }\n\n  const messages = enforceConverseAlternation(raw, input.alternationPolicy ?? 'merge')\n  const tools = h.toolsToConverseTools(input.tools.visible())\n\n  // `toolConfig` is REQUIRED whenever any toolUse/toolResult block appears — including pure history\n  // replay where no tools are offered for THIS turn. Omitting it is a hard rejection (\"The\n  // toolConfig field must be defined when using toolUse and toolResult content blocks\").\n  //\n  // But an EMPTY `tools: []` is rejected too, with only \"The provided request is not valid\" —\n  // verified live against Converse. So a transcript that replays calls for tools we can no longer\n  // enumerate needs a declaration synthesized from the calls themselves: name plus a permissive\n  // object schema. The model is not being offered these tools (it already called them); the\n  // declaration exists solely to satisfy the correlation Converse insists on.\n  const declaredNames = new Set(tools.map((t) => t.toolSpec.name))\n  const historyToolNames = new Set<string>()\n  for (const message of messages) {\n    for (const block of message.content) {\n      if (block.toolUse) historyToolNames.add(block.toolUse.name)\n    }\n  }\n  const backfilled: ConverseToolSpec[] = [...historyToolNames]\n    .filter((name) => !declaredNames.has(name))\n    .map((name) => ({\n      toolSpec: {\n        name,\n        description: `Previously invoked tool ${name} (declaration backfilled for history replay).`,\n        inputSchema: { json: { type: 'object', properties: {} } as never },\n      },\n    }))\n  const allTools = [...tools, ...backfilled]\n  const historyHasToolBlocks = messages.some((m) =>\n    m.content.some((b) => b.toolUse !== undefined || b.toolResult !== undefined)\n  )\n\n  return {\n    messages,\n    ...(systemText.length > 0 ? { system: [{ text: systemText }] } : {}),\n    // Only emit toolConfig when it will be NON-EMPTY; an empty tools array is itself invalid.\n    ...(allTools.length > 0 && (tools.length > 0 || historyHasToolBlocks)\n      ? { toolConfig: { tools: allTools } }\n      : {}),\n  }\n}\n\n/** Default implementation; alias of {@link buildConverseRequest}. */\nexport const defaultBuildConverseRequest = buildConverseRequest\n\n/**\n * Extract text, reasoning, and tool uses from a Converse response.\n *\n * @remarks\n * `reasoningContent` blocks are NOT concatenated into visible text — doing so leaks the model's\n * scratchpad into the answer.\n */\nexport const extractConverseGeneration = (\n  response: ConverseResponseLike | undefined\n): {\n  text: string\n  reasoning: string\n  toolUses: Array<{ toolUseId: string; name: string; input: Record<string, unknown> }>\n  stopReason: string | undefined\n} => {\n  const blocks = response?.output?.message?.content ?? []\n  let text = ''\n  let reasoning = ''\n  const toolUses: Array<{ toolUseId: string; name: string; input: Record<string, unknown> }> = []\n  for (const block of blocks) {\n    if (block.toolUse) {\n      toolUses.push({\n        toolUseId: block.toolUse.toolUseId,\n        name: block.toolUse.name,\n        input: block.toolUse.input ?? {},\n      })\n      continue\n    }\n    if (block.reasoningContent?.reasoningText?.text) {\n      reasoning += block.reasoningContent.reasoningText.text\n      continue\n    }\n    if (typeof block.text === 'string') text += block.text\n  }\n  return { text, reasoning, toolUses, stopReason: response?.stopReason }\n}\n\n/** Structural minimum `extractConverseGeneration` needs, so tests can pass a literal. */\ninterface ConverseResponseLike {\n  output?: { message?: { content?: ConverseContentBlock[] } }\n  stopReason?: string\n}\n\n/** Default implementation; alias of {@link extractConverseGeneration}. */\nexport const defaultExtractConverseGeneration = extractConverseGeneration\n"],"mappings":";;;;;;;;;;;;;;;;;AAuFA,IAAa,gCAAgC;CAC3C;CACA;CACA;CACA;AACF;;;;;;;;AASA,IAAM,0BAA0B,IAAI,IAAI;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,IAAa,0BAA0B,WAAgC;CACrE,IAAI,MAAM,QAAQ,MAAM,GAAG,OAAO,OAAO,KAAK,MAAM,uBAAuB,CAAC,CAAC;CAC7E,IAAI,WAAW,QAAQ,OAAO,WAAW,UAAU,OAAO;CAC1D,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAiC,GAAG;EAC5E,IAAI,wBAAwB,IAAI,GAAG,GAAG;EACtC,IAAI,OAAO,eAAA,SAAS,KAAK,IAAI,uBAAuB,KAAK,IAAI;CAC/D;CACA,OAAO;AACT;;AAGA,IAAa,gCAAgC;;;;;;;;AAS7C,IAAa,qBAAqB,OAAuB;CACvD,MAAM,UAAU,GAAG,QAAQ,mBAAmB,GAAG;CACjD,OAAO,QAAQ,SAAS,KAAK,QAAQ,MAAM,GAAG,EAAE,IAAI,WAAW;AACjE;;AAGA,IAAa,2BAA2B;;AAGxC,IAAa,wBAAwB,UAA6D;CAChG,MAAM,MAA0B,CAAC;CACjC,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,YAAY,KAAK,SAAS;EAIhC,MAAM,YAAY,uBAHC,gBAAA,uCACj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