{"version":3,"file":"helpers.cjs","names":[],"sources":["../../../../src/batteries/llm/gemini_generate_content/helpers.ts"],"sourcesContent":["/**\n * Translation helpers for the native Gemini `generateContent` battery.\n *\n * @module @nhtio/adk/batteries/llm/gemini_generate_content/helpers\n *\n * @remarks\n * Every function is injectable via {@link GeminiGenerateContentAdapterOptions.helpers} and has a\n * `default*` alias. The wire-shape-agnostic renderers (untrusted/trusted envelopes, memories,\n * retrievables, thought envelopes, the system-prompt assembler) are re-exported unchanged from the\n * shared internal `../chat_common/helpers`; only the parts that are genuinely Gemini-shaped live\n * here.\n */\n\nimport { isObject } from '@nhtio/adk/guards'\nimport {\n  descriptionToChatCompletionsJsonSchema,\n  filterThoughts,\n  renderStandingInstructions,\n  renderMemories,\n  renderRetrievables,\n  renderRetrievableSafetyDirective,\n  renderFirstPartyRetrievables,\n  renderThirdPartyPublicRetrievables,\n  renderThirdPartyPrivateRetrievables,\n  looksLikeSpooledArtifact,\n  neutraliseDeveloperRulesTag,\n  normalizeToolName,\n  renderChatCompletionsSystemPrompt,\n  renderThought,\n  renderTrustedContent,\n  renderUntrustedContent,\n  sanitizeMimeType,\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  ToolCall,\n  Tokenizable,\n  Message,\n  Thought,\n} from '@nhtio/adk/common'\nimport type {\n  GeminiContent,\n  GeminiFunctionDeclaration,\n  GeminiInlineData,\n  GeminiPart,\n  GeminiGenerateContentRequest,\n  GeminiRequestBuildInput,\n  GeminiTool,\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/**\n * Default context-bucket order for the system instruction.\n *\n * @remarks\n * Matches the other chat batteries so a consumer switching batteries gets the same system-prompt\n * layout. Exported so a caller can reorder without reconstructing the whole list.\n */\nexport const DEFAULT_GEMINI_BUCKET_ORDER = [\n  'standingInstructions',\n  'memories',\n  'retrievables',\n  'timeline',\n] as const\n\n/**\n * JSON-Schema keywords Gemini's OpenAPI-subset parameter schema rejects.\n *\n * @remarks\n * Sending any of these produces an opaque `INVALID_ARGUMENT` with no field name, which is\n * expensive to diagnose — so they are stripped before dispatch rather than forwarded. This mirrors\n * the same problem the Bedrock translator has to solve for Converse's schema dialect.\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])\n\n/**\n * Recursively strip schema keywords Gemini rejects.\n *\n * @param schema - Any JSON-Schema-shaped value.\n * @returns The same shape with unsupported keywords removed.\n */\nexport const sanitizeGeminiSchema = (schema: unknown): JsonSchema => {\n  if (Array.isArray(schema)) return schema.map((s) => sanitizeGeminiSchema(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) ? sanitizeGeminiSchema(value) : value\n  }\n  return out as never\n}\n\n/** Default implementation; alias of {@link sanitizeGeminiSchema}. */\nexport const defaultSanitizeGeminiSchema = sanitizeGeminiSchema\n\n/**\n * ADK tools → native `functionDeclarations`.\n *\n * @remarks\n * Names are normalised through the shared `normalizeToolName` so a tool whose ADK name contains\n * characters Gemini rejects still resolves; `functionResponse.name` must later match whatever this\n * produced, which is why both sides call the same normaliser.\n */\nexport const toolsToGeminiTools = (tools: Iterable<Tool | ArtifactTool>): GeminiTool[] => {\n  const declarations: GeminiFunctionDeclaration[] = []\n  for (const tool of tools) {\n    // `describe()` is the canonical accessor — a Tool's schema is not a plain property.\n    const described = tool.describe()\n    const parameters = descriptionToChatCompletionsJsonSchema(\n      described.inputSchema as unknown as DescriptionLike\n    )\n    const sanitized = sanitizeGeminiSchema(parameters)\n    declarations.push({\n      name: normalizeToolName(described.name),\n      description: String(described.description ?? ''),\n      // Gemini rejects an EMPTY parameters object on a zero-arg tool, so omit it entirely.\n      ...(sanitized && Object.keys(sanitized).length > 0 ? { parameters: sanitized } : {}),\n    })\n  }\n  return declarations.length > 0 ? [{ functionDeclarations: declarations }] : []\n}\n\n/** Default implementation; alias of {@link toolsToGeminiTools}. */\nexport const defaultToolsToGeminiTools = toolsToGeminiTools\n\n/**\n * Render one tool result into a `functionResponse.response` object.\n *\n * @remarks\n * Gemini requires an OBJECT here, not a bare string — a string is rejected. Text is therefore\n * wrapped as `{ result: <text> }`, keeping the untrusted-content envelope the other batteries use\n * so a tool result cannot impersonate a system directive.\n */\nexport const renderGeminiToolResult = 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<Record<string, unknown>> => {\n  const { results, toolCall } = input\n  if (looksLikeSpooledArtifact(results)) {\n    // A spooled artifact is referenced by handle, never inlined — the same contract the other\n    // batteries hold, so a large result cannot blow the window.\n    return { result: `[artifact ${String((results as { id?: unknown }).id ?? toolCall.id)}]` }\n  }\n  const text = String(results ?? '')\n  return {\n    result: input.renderUntrustedContent(text, {\n      nonce: toolCall.id,\n      from: toolCall.tool,\n    } as never),\n  }\n}\n\n/** Default implementation; alias of {@link renderGeminiToolResult}. */\nexport const defaultRenderGeminiToolResult = renderGeminiToolResult\n\n/** Decode an ADK Media into Gemini's `inlineData`. */\nexport const mediaToGeminiInlineData = async (media: Media): Promise<GeminiInlineData> => {\n  const bytes = await media.asBytes()\n  let binary = ''\n  const chunk = 0x8000\n  const arr = bytes as Uint8Array\n  for (let i = 0; i < arr.length; i += chunk) {\n    binary += String.fromCharCode(...arr.subarray(i, i + chunk))\n  }\n  return {\n    mimeType: sanitizeMimeType(media.mimeType, media.kind === 'image' ? 'image' : 'audio'),\n    data: typeof btoa === 'function' ? btoa(binary) : Buffer.from(arr).toString('base64'),\n  }\n}\n\n/** Default implementation; alias of {@link mediaToGeminiInlineData}. */\nexport const defaultMediaToGeminiInlineData = mediaToGeminiInlineData\n\n/**\n * Assemble the native 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 * Gemini gateway:\n *\n *  - System text goes to `systemInstruction`, not a `contents[]` turn.\n *  - `Message.role: 'assistant'` becomes `role: 'model'`.\n *  - A `ToolCall` becomes TWO turns: a `model` turn with a `functionCall` part, then a `user` turn\n *    with a `functionResponse` part. `functionResponse.name` carries the DECLARED tool name,\n *    because Gemini has no call-id correlation.\n *  - Timeline order is `createdAt`, matching the ordering guard's own view, so what the guard\n *    validates is what gets dispatched.\n *  - The thought-signature sentinel is stamped on the FIRST `functionCall` only when no part\n *    already carries a real signature and the caller has not opted out. Preserving a genuine\n *    signature matters: it is prefix-bound, and replacing one invalidates it.\n */\nexport const buildGeminiRequest = async (\n  input: GeminiRequestBuildInput\n): Promise<GeminiGenerateContentRequest> => {\n  // The shared assembler takes its sub-renderers EXPLICITLY rather than reaching for module\n  // globals, so an override on `helpers` reaches the system prompt too.\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_GEMINI_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 contents: GeminiContent[] = []\n  // Whether history already carries a real signature. If it does, DO NOT stamp a sentinel over it.\n  let sawRealSignature = false\n  for (const item of items) {\n    if (item.kind === 'toolCall') {\n      const payload = (item.value as { payload?: unknown }).payload\n      const sig = isObject(payload)\n        ? (payload as { thoughtSignature?: unknown }).thoughtSignature\n        : undefined\n      if (typeof sig === 'string' && sig.length > 0) sawRealSignature = true\n    }\n  }\n\n  let stampedSentinel = false\n  for (const item of items) {\n    if (item.kind === 'message') {\n      const text = neutraliseDeveloperRulesTag(String(item.value.content ?? ''))\n      const parts: GeminiPart[] = []\n      if (text.length > 0) parts.push({ text })\n      for (const media of item.value.attachments ?? []) {\n        if (input.decodeMedia === undefined) continue\n        try {\n          parts.push({ inlineData: await input.decodeMedia(media) })\n        } catch (err) {\n          input.warn?.(`decodeMedia failed for ${media.filename}: ${String(err)}`)\n        }\n      }\n      if (parts.length === 0) continue\n      contents.push({ role: item.value.role === 'assistant' ? 'model' : 'user', parts })\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      // Reasoning replays as a model turn flagged `thought`, so Gemini treats it as its own\n      // prior reasoning rather than user-visible content.\n      contents.push({ role: 'model', parts: [{ text: envelope, thought: true }] })\n      continue\n    }\n\n    const tc = item.value\n    const declaredName = normalizeToolName(tc.tool)\n    const payload = (tc as { payload?: unknown }).payload\n    const existingSig = isObject(payload)\n      ? (payload as { thoughtSignature?: unknown }).thoughtSignature\n      : undefined\n\n    const callPart: GeminiPart = {\n      functionCall: {\n        name: declaredName,\n        args: (typeof tc.args === 'string'\n          ? JSON.parse(tc.args || '{}')\n          : (tc.args ?? {})) as Record<string, unknown>,\n      },\n    }\n    if (typeof existingSig === 'string' && existingSig.length > 0) {\n      callPart.thoughtSignature = existingSig\n    } else if (input.thoughtSignatureSentinel !== false && !sawRealSignature && !stampedSentinel) {\n      // Only the FIRST call in the history needs it; stamping every one is unnecessary and makes\n      // the provenance claim broader than it has to be.\n      callPart.thoughtSignature = input.thoughtSignatureSentinel\n      stampedSentinel = true\n    }\n    contents.push({ role: 'model', parts: [callPart] })\n\n    const rendered = input.renderedToolCallResults.get(tc) ?? { result: '' }\n    contents.push({\n      role: 'user',\n      parts: [{ functionResponse: { name: declaredName, response: rendered } }],\n    })\n  }\n\n  const tools = input.helpers.toolsToGeminiTools(input.tools.visible())\n  return {\n    contents,\n    ...(systemText.length > 0 ? { systemInstruction: { parts: [{ text: systemText }] } } : {}),\n    ...(tools.length > 0 ? { tools } : {}),\n  }\n}\n\n/** Default implementation; alias of {@link buildGeminiRequest}. */\nexport const defaultBuildGeminiRequest = buildGeminiRequest\n\n/**\n * Extract text, reasoning, and function calls from a response.\n *\n * @remarks\n * `thought: true` parts are reasoning and must NOT be concatenated into user-visible text — doing\n * so leaks the model's scratchpad into the answer.\n */\nexport const extractGeminiGeneration = (\n  response: { candidates?: Array<{ content?: GeminiContent; finishReason?: string }> } | undefined\n): {\n  text: string\n  reasoning: string\n  functionCalls: Array<{ name: string; args: Record<string, unknown>; thoughtSignature?: string }>\n  finishReason: string | undefined\n} => {\n  const candidate = response?.candidates?.[0]\n  const parts = candidate?.content?.parts ?? []\n  let text = ''\n  let reasoning = ''\n  const functionCalls: Array<{\n    name: string\n    args: Record<string, unknown>\n    thoughtSignature?: string\n  }> = []\n  for (const part of parts) {\n    if (part.functionCall) {\n      functionCalls.push({\n        name: part.functionCall.name,\n        args: part.functionCall.args ?? {},\n        ...(part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}),\n      })\n      continue\n    }\n    if (typeof part.text !== 'string') continue\n    if (part.thought === true) reasoning += part.text\n    else text += part.text\n  }\n  return { text, reasoning, functionCalls, finishReason: candidate?.finishReason }\n}\n\n/** Default implementation; alias of {@link extractGeminiGeneration}. */\nexport const defaultExtractGeminiGeneration = extractGeminiGeneration\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAiGA,IAAa,8BAA8B;CACzC;CACA;CACA;CACA;AACF;;;;;;;;;AAUA,IAAM,0BAA0B,IAAI,IAAI;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;AAQD,IAAa,wBAAwB,WAAgC;CACnE,IAAI,MAAM,QAAQ,MAAM,GAAG,OAAO,OAAO,KAAK,MAAM,qBAAqB,CAAC,CAAC;CAC3E,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,qBAAqB,KAAK,IAAI;CAC7D;CACA,OAAO;AACT;;AAGA,IAAa,8BAA8B;;;;;;;;;AAU3C,IAAa,sBAAsB,UAAuD;CACxF,MAAM,eAA4C,CAAC;CACnD,KAAK,MAAM,QAAQ,OAAO;EAExB,MAAM,YAAY,KAAK,SAAS;EAIhC,MAAM,YAAY,qBAHC,gBAAA,uCACjB,UAAU,WAE2B,CAAU;EACjD,aAAa,KAAK;GAChB,MAAM,gBAAA,kBAAkB,UAAU,IAAI;GACtC,aAAa,OAAO,UAAU,eAAe,EAAE;GAE/C,GAAI,aAAa,OAAO,KAAK,SAAS,EAAE,SAAS,IAAI,EAAE,YAAY,UAAU,IAAI,CAAC;EACpF,CAAC;CACH;CACA,OAAO,aAAa,SAAS,IAAI,CAAC,EAAE,sBAAsB,aAAa,CAAC,IAAI,CAAC;AAC/E;;AAGA,IAAa,4BAA4B;;;;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