pi2dsh 0.3.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/{all-Rt4K68QA.mjs → all-DSpxKvHa.mjs} +10 -10
  2. package/dist/{all-Rt4K68QA.mjs.map → all-DSpxKvHa.mjs.map} +1 -1
  3. package/dist/{anthropic-messages-Beym0_aC.mjs → anthropic-messages-BL9N1Idv.mjs} +3 -3
  4. package/dist/{anthropic-messages-Beym0_aC.mjs.map → anthropic-messages-BL9N1Idv.mjs.map} +1 -1
  5. package/dist/{azure-openai-responses-cHqZTgLD.mjs → azure-openai-responses-A67VbaZ1.mjs} +3 -3
  6. package/dist/{azure-openai-responses-cHqZTgLD.mjs.map → azure-openai-responses-A67VbaZ1.mjs.map} +1 -1
  7. package/dist/cli.mjs +1 -1
  8. package/dist/compat/pi-ai.d.mts +3 -38
  9. package/dist/compat/pi-ai.d.mts.map +1 -1
  10. package/dist/compat/pi-ai.mjs +3 -3
  11. package/dist/compat/pi-coding-agent.d.mts +71 -32
  12. package/dist/compat/pi-coding-agent.d.mts.map +1 -1
  13. package/dist/compat/pi-coding-agent.mjs +2 -2
  14. package/dist/credentials-oauth.mjs +2 -2
  15. package/dist/{dist-QBBA-dL_.mjs → dist-BYA74yh_.mjs} +2 -2
  16. package/dist/{dist-QBBA-dL_.mjs.map → dist-BYA74yh_.mjs.map} +1 -1
  17. package/dist/dist-DeonWo7m.mjs +1089 -0
  18. package/dist/dist-DeonWo7m.mjs.map +1 -0
  19. package/dist/{google-generative-ai-B7OZs5lu.mjs → google-generative-ai-DT5S8D8y.mjs} +2 -2
  20. package/dist/{google-generative-ai-B7OZs5lu.mjs.map → google-generative-ai-DT5S8D8y.mjs.map} +1 -1
  21. package/dist/{google-shared-CRsAUItF.mjs → google-shared-DYP_9cnK.mjs} +4 -4
  22. package/dist/{google-shared-CRsAUItF.mjs.map → google-shared-DYP_9cnK.mjs.map} +1 -1
  23. package/dist/{google-vertex-DmdaHQtB.mjs → google-vertex-Dpq7O7Be.mjs} +3 -3
  24. package/dist/{google-vertex-DmdaHQtB.mjs.map → google-vertex-Dpq7O7Be.mjs.map} +1 -1
  25. package/dist/host.mjs +1 -1
  26. package/dist/index.d.mts.map +1 -1
  27. package/dist/index.mjs +1 -1
  28. package/dist/{json-parse-CFyFZSLJ.mjs → json-parse-Dz5sKMTv.mjs} +2 -2
  29. package/dist/{json-parse-CFyFZSLJ.mjs.map → json-parse-Dz5sKMTv.mjs.map} +1 -1
  30. package/dist/{mcp-config-D2B3kv-Z.mjs → mcp-config-B3h5jTBb.mjs} +9 -8
  31. package/dist/mcp-config-B3h5jTBb.mjs.map +1 -0
  32. package/dist/{mistral-conversations-HHZCcFv_.mjs → mistral-conversations-BsxbCCWx.mjs} +4 -4
  33. package/dist/{mistral-conversations-HHZCcFv_.mjs.map → mistral-conversations-BsxbCCWx.mjs.map} +1 -1
  34. package/dist/{multipart-parser-CIa5BbwO.mjs → multipart-parser-woKCuALW.mjs} +3 -3
  35. package/dist/{multipart-parser-CIa5BbwO.mjs.map → multipart-parser-woKCuALW.mjs.map} +1 -1
  36. package/dist/{openai-codex-responses-vmovNu-q.mjs → openai-codex-responses-C7vviVT2.mjs} +3 -3
  37. package/dist/{openai-codex-responses-vmovNu-q.mjs.map → openai-codex-responses-C7vviVT2.mjs.map} +1 -1
  38. package/dist/{openai-completions-fXHhRolF.mjs → openai-completions-By8QNX1P.mjs} +3 -3
  39. package/dist/{openai-completions-fXHhRolF.mjs.map → openai-completions-By8QNX1P.mjs.map} +1 -1
  40. package/dist/{openai-responses-DKdCYf3h.mjs → openai-responses-DboJUcFN.mjs} +3 -3
  41. package/dist/{openai-responses-DKdCYf3h.mjs.map → openai-responses-DboJUcFN.mjs.map} +1 -1
  42. package/dist/{openai-responses-shared-D0Jq7yVP.mjs → openai-responses-shared-BDzn7nJY.mjs} +2 -2
  43. package/dist/{openai-responses-shared-D0Jq7yVP.mjs.map → openai-responses-shared-BDzn7nJY.mjs.map} +1 -1
  44. package/dist/{otel-BQSQRBLF.mjs → otel-PimLMoiV.mjs} +3 -3
  45. package/dist/{otel-BQSQRBLF.mjs.map → otel-PimLMoiV.mjs.map} +1 -1
  46. package/dist/{pi-ai-DhYGgq4Y.mjs → pi-ai-B_88Wb0r.mjs} +49 -6
  47. package/dist/{pi-ai-DhYGgq4Y.mjs.map → pi-ai-B_88Wb0r.mjs.map} +1 -1
  48. package/dist/{pi-coding-agent-fPHwKP4d.mjs → pi-coding-agent-COMX0KHL.mjs} +109 -34
  49. package/dist/pi-coding-agent-COMX0KHL.mjs.map +1 -0
  50. package/dist/{pi-messages-CV-Ts8An.mjs → pi-messages-B-7Xo_I0.mjs} +3 -3
  51. package/dist/{pi-messages-CV-Ts8An.mjs.map → pi-messages-B-7Xo_I0.mjs.map} +1 -1
  52. package/dist/pi-types-KazmR2O5.d.mts +62 -0
  53. package/dist/pi-types-KazmR2O5.d.mts.map +1 -0
  54. package/dist/pi-uuid-Db8ShZsK.mjs +47 -0
  55. package/dist/pi-uuid-Db8ShZsK.mjs.map +1 -0
  56. package/dist/{provider-env-C72pF4vP.mjs → provider-env-D-cCRWzv.mjs} +2 -2
  57. package/dist/{provider-env-C72pF4vP.mjs.map → provider-env-D-cCRWzv.mjs.map} +1 -1
  58. package/dist/{runtime-B9R7bDWT.mjs → runtime-B7mEIRf-.mjs} +1183 -52
  59. package/dist/runtime-B7mEIRf-.mjs.map +1 -0
  60. package/dist/runtime.d.mts.map +1 -1
  61. package/dist/runtime.mjs +1 -1
  62. package/dist/{src-C3WBfOks.mjs → src-BEl3QrGL.mjs} +3 -3
  63. package/dist/{src-C3WBfOks.mjs.map → src-BEl3QrGL.mjs.map} +1 -1
  64. package/package.json +2 -2
  65. package/dist/build-BG7p2Lbr.mjs +0 -4416
  66. package/dist/build-BG7p2Lbr.mjs.map +0 -1
  67. package/dist/dist-IQKOgQyt.mjs +0 -10035
  68. package/dist/dist-IQKOgQyt.mjs.map +0 -1
  69. package/dist/mcp-config-D2B3kv-Z.mjs.map +0 -1
  70. package/dist/pi-coding-agent-fPHwKP4d.mjs.map +0 -1
  71. package/dist/pi-types-BLt46jaf.d.mts +0 -2494
  72. package/dist/pi-types-BLt46jaf.d.mts.map +0 -1
  73. package/dist/rolldown-runtime-CTfmNlz1.mjs +0 -44
  74. package/dist/runtime-B9R7bDWT.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dist-DeonWo7m.mjs","names":["Type"],"sources":["../node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/providers/faux.js","../node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js","../node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/utils/retry.js","../node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/utils/text.js","../node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/utils/typebox-helpers.js","../node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/utils/validation.js"],"sourcesContent":["import { createProvider } from \"../models.js\";\nimport { createAssistantMessageEventStream } from \"../utils/event-stream.js\";\nconst DEFAULT_API = \"faux\";\nconst DEFAULT_PROVIDER = \"faux\";\nconst DEFAULT_MODEL_ID = \"faux-1\";\nconst DEFAULT_MODEL_NAME = \"Faux Model\";\nconst DEFAULT_BASE_URL = \"http://localhost:0\";\nconst DEFAULT_MIN_TOKEN_SIZE = 3;\nconst DEFAULT_MAX_TOKEN_SIZE = 5;\nconst DEFAULT_USAGE = {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\nexport function fauxText(text) {\n return { type: \"text\", text };\n}\nexport function fauxThinking(thinking) {\n return { type: \"thinking\", thinking };\n}\nexport function fauxToolCall(name, arguments_, options = {}) {\n return {\n type: \"toolCall\",\n id: options.id ?? randomId(\"tool\"),\n name,\n arguments: arguments_,\n };\n}\nfunction normalizeFauxAssistantContent(content) {\n if (typeof content === \"string\") {\n return [fauxText(content)];\n }\n return Array.isArray(content) ? content : [content];\n}\nexport function fauxAssistantMessage(content, options = {}) {\n return {\n role: \"assistant\",\n content: normalizeFauxAssistantContent(content),\n api: DEFAULT_API,\n provider: DEFAULT_PROVIDER,\n model: DEFAULT_MODEL_ID,\n usage: DEFAULT_USAGE,\n stopReason: options.stopReason ?? \"stop\",\n deferred: options.deferred,\n errorMessage: options.errorMessage,\n responseId: options.responseId,\n timestamp: options.timestamp ?? Date.now(),\n };\n}\nfunction estimateTokens(text) {\n return Math.ceil(text.length / 4);\n}\nfunction randomId(prefix) {\n return `${prefix}:${Date.now()}:${Math.random().toString(36).slice(2)}`;\n}\nfunction contentToText(content) {\n if (typeof content === \"string\") {\n return content;\n }\n return content\n .map((block) => {\n if (block.type === \"text\") {\n return block.text;\n }\n return `[image:${block.mimeType}:${block.data.length}]`;\n })\n .join(\"\\n\");\n}\nfunction assistantContentToText(content) {\n return content\n .map((block) => {\n if (block.type === \"text\") {\n return block.text;\n }\n if (block.type === \"thinking\") {\n return block.thinking;\n }\n return `${block.name}:${JSON.stringify(block.arguments)}`;\n })\n .join(\"\\n\");\n}\nfunction toolResultToText(message) {\n return [message.toolName, ...message.content.map((block) => contentToText([block]))].join(\"\\n\");\n}\nfunction messageToText(message) {\n if (message.role === \"user\") {\n return contentToText(message.content);\n }\n if (message.role === \"assistant\") {\n return assistantContentToText(message.content);\n }\n return toolResultToText(message);\n}\nfunction serializeContext(context) {\n const parts = [];\n if (context.systemPrompt) {\n parts.push(`system:${context.systemPrompt}`);\n }\n for (const message of context.messages) {\n parts.push(`${message.role}:${messageToText(message)}`);\n }\n if (context.tools?.length) {\n parts.push(`tools:${JSON.stringify(context.tools)}`);\n }\n return parts.join(\"\\n\\n\");\n}\nfunction commonPrefixLength(a, b) {\n const length = Math.min(a.length, b.length);\n let index = 0;\n while (index < length && a[index] === b[index]) {\n index++;\n }\n return index;\n}\nfunction withUsageEstimate(message, context, options, promptCache) {\n const promptText = serializeContext(context);\n const promptTokens = estimateTokens(promptText);\n const outputTokens = estimateTokens(assistantContentToText(message.content));\n let input = promptTokens;\n let cacheRead = 0;\n let cacheWrite = 0;\n const sessionId = options?.sessionId;\n if (sessionId && options?.cacheRetention !== \"none\") {\n const previousPrompt = promptCache.get(sessionId);\n if (previousPrompt) {\n const cachedChars = commonPrefixLength(previousPrompt, promptText);\n cacheRead = estimateTokens(previousPrompt.slice(0, cachedChars));\n cacheWrite = estimateTokens(promptText.slice(cachedChars));\n input = Math.max(0, promptTokens - cacheRead);\n }\n else {\n cacheWrite = promptTokens;\n }\n promptCache.set(sessionId, promptText);\n }\n return {\n ...message,\n usage: {\n input,\n output: outputTokens,\n cacheRead,\n cacheWrite,\n totalTokens: input + outputTokens + cacheRead + cacheWrite,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n },\n };\n}\nfunction splitStringByTokenSize(text, minTokenSize, maxTokenSize) {\n const chunks = [];\n let index = 0;\n while (index < text.length) {\n const tokenSize = minTokenSize + Math.floor(Math.random() * (maxTokenSize - minTokenSize + 1));\n const charSize = Math.max(1, tokenSize * 4);\n chunks.push(text.slice(index, index + charSize));\n index += charSize;\n }\n return chunks.length > 0 ? chunks : [\"\"];\n}\nfunction cloneMessage(message, api, provider, modelId) {\n const cloned = structuredClone(message);\n return {\n ...cloned,\n api,\n provider,\n model: modelId,\n timestamp: cloned.timestamp ?? Date.now(),\n usage: cloned.usage ?? DEFAULT_USAGE,\n };\n}\nfunction createDeferredMessage(model, handle) {\n return {\n role: \"assistant\",\n content: [],\n api: model.api,\n provider: model.provider,\n model: model.id,\n usage: DEFAULT_USAGE,\n stopReason: \"deferred\",\n deferred: handle,\n timestamp: Date.now(),\n };\n}\nfunction createErrorMessage(error, api, provider, modelId) {\n return {\n role: \"assistant\",\n content: [],\n api,\n provider,\n model: modelId,\n usage: DEFAULT_USAGE,\n stopReason: \"error\",\n errorMessage: error instanceof Error ? error.message : String(error),\n timestamp: Date.now(),\n };\n}\nfunction createAbortedMessage(partial) {\n return {\n ...partial,\n stopReason: \"aborted\",\n errorMessage: \"Request was aborted\",\n timestamp: Date.now(),\n };\n}\nfunction scheduleChunk(chunk, tokensPerSecond) {\n if (!tokensPerSecond || tokensPerSecond <= 0) {\n return new Promise((resolve) => queueMicrotask(resolve));\n }\n const delayMs = (estimateTokens(chunk) / tokensPerSecond) * 1000;\n return new Promise((resolve) => setTimeout(resolve, delayMs));\n}\nasync function streamWithDeltas(stream, message, minTokenSize, maxTokenSize, tokensPerSecond, signal) {\n const partial = { ...message, content: [], stopReason: \"pending\" };\n if (signal?.aborted) {\n const aborted = createAbortedMessage(partial);\n stream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n stream.end(aborted);\n return;\n }\n stream.push({ type: \"start\", partial: { ...partial } });\n for (let index = 0; index < message.content.length; index++) {\n if (signal?.aborted) {\n const aborted = createAbortedMessage(partial);\n stream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n stream.end(aborted);\n return;\n }\n const block = message.content[index];\n if (block.type === \"thinking\") {\n partial.content = [...partial.content, { type: \"thinking\", thinking: \"\" }];\n stream.push({ type: \"thinking_start\", contentIndex: index, partial: { ...partial } });\n for (const chunk of splitStringByTokenSize(block.thinking, minTokenSize, maxTokenSize)) {\n await scheduleChunk(chunk, tokensPerSecond);\n if (signal?.aborted) {\n const aborted = createAbortedMessage(partial);\n stream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n stream.end(aborted);\n return;\n }\n partial.content[index].thinking += chunk;\n stream.push({ type: \"thinking_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n }\n stream.push({\n type: \"thinking_end\",\n contentIndex: index,\n content: block.thinking,\n partial: { ...partial },\n });\n continue;\n }\n if (block.type === \"text\") {\n partial.content = [...partial.content, { type: \"text\", text: \"\" }];\n stream.push({ type: \"text_start\", contentIndex: index, partial: { ...partial } });\n for (const chunk of splitStringByTokenSize(block.text, minTokenSize, maxTokenSize)) {\n await scheduleChunk(chunk, tokensPerSecond);\n if (signal?.aborted) {\n const aborted = createAbortedMessage(partial);\n stream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n stream.end(aborted);\n return;\n }\n partial.content[index].text += chunk;\n stream.push({ type: \"text_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n }\n stream.push({ type: \"text_end\", contentIndex: index, content: block.text, partial: { ...partial } });\n continue;\n }\n partial.content = [...partial.content, { type: \"toolCall\", id: block.id, name: block.name, arguments: {} }];\n stream.push({ type: \"toolcall_start\", contentIndex: index, partial: { ...partial } });\n for (const chunk of splitStringByTokenSize(JSON.stringify(block.arguments), minTokenSize, maxTokenSize)) {\n await scheduleChunk(chunk, tokensPerSecond);\n if (signal?.aborted) {\n const aborted = createAbortedMessage(partial);\n stream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n stream.end(aborted);\n return;\n }\n stream.push({ type: \"toolcall_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n }\n partial.content[index].arguments = block.arguments;\n stream.push({ type: \"toolcall_end\", contentIndex: index, toolCall: block, partial: { ...partial } });\n }\n if (message.stopReason === \"pending\") {\n throw new Error(\"Faux response ended without a stop reason\");\n }\n if (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n stream.push({ type: \"error\", reason: message.stopReason, error: message });\n stream.end(message);\n return;\n }\n stream.push({ type: \"done\", reason: message.stopReason, message });\n stream.end(message);\n}\nexport function createFauxCore(options) {\n const api = options.api ?? randomId(DEFAULT_API);\n const provider = options.provider ?? DEFAULT_PROVIDER;\n const minTokenSize = Math.max(1, Math.min(options.tokenSize?.min ?? DEFAULT_MIN_TOKEN_SIZE, options.tokenSize?.max ?? DEFAULT_MAX_TOKEN_SIZE));\n const maxTokenSize = Math.max(minTokenSize, options.tokenSize?.max ?? DEFAULT_MAX_TOKEN_SIZE);\n let pendingResponses = [];\n const tokensPerSecond = options.tokensPerSecond;\n const state = { callCount: 0, deferredFetchCount: 0, cancelledDeferred: [] };\n const promptCache = new Map();\n const deferredResponses = new Map();\n const modelDefinitions = options.models?.length\n ? options.models\n : [\n {\n id: DEFAULT_MODEL_ID,\n name: DEFAULT_MODEL_NAME,\n reasoning: false,\n input: [\"text\", \"image\"],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: 128000,\n maxTokens: 16384,\n },\n ];\n const models = modelDefinitions.map((definition) => ({\n id: definition.id,\n name: definition.name ?? definition.id,\n api,\n provider,\n baseUrl: DEFAULT_BASE_URL,\n reasoning: definition.reasoning ?? false,\n input: definition.input ?? [\"text\", \"image\"],\n cost: definition.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: definition.contextWindow ?? 128000,\n maxTokens: definition.maxTokens ?? 16384,\n }));\n const resolveResponse = async (step, context, streamOptions, requestModel) => {\n const resolved = typeof step === \"function\" ? await step(context, streamOptions, state, requestModel) : step;\n return withUsageEstimate(cloneMessage(resolved, api, provider, requestModel.id), context, streamOptions, promptCache);\n };\n const stream = (requestModel, context, streamOptions) => {\n const outer = createAssistantMessageEventStream();\n const step = pendingResponses.shift();\n state.callCount++;\n queueMicrotask(async () => {\n try {\n await streamOptions?.onResponse?.({ status: 200, headers: {} }, requestModel);\n if (!step) {\n let message = createErrorMessage(new Error(\"No more faux responses queued\"), api, provider, requestModel.id);\n message = withUsageEstimate(message, context, streamOptions, promptCache);\n outer.push({ type: \"error\", reason: \"error\", error: message });\n outer.end(message);\n return;\n }\n if (streamOptions?.deferred) {\n const handle = {\n provider: requestModel.provider,\n modelId: requestModel.id,\n api: requestModel.api,\n id: randomId(\"deferred\"),\n ...(options.deferred?.pollAfterMs !== undefined ? { pollAfterMs: options.deferred.pollAfterMs } : {}),\n };\n deferredResponses.set(handle.id, {\n handle,\n step,\n context,\n options: streamOptions,\n model: requestModel,\n pendingFetches: Math.max(0, Math.floor(options.deferred?.pendingFetches ?? 0)),\n cancelled: false,\n });\n await streamWithDeltas(outer, createDeferredMessage(requestModel, handle), minTokenSize, maxTokenSize, tokensPerSecond, streamOptions.signal);\n return;\n }\n const message = await resolveResponse(step, context, streamOptions, requestModel);\n await streamWithDeltas(outer, message, minTokenSize, maxTokenSize, tokensPerSecond, streamOptions?.signal);\n }\n catch (error) {\n const message = createErrorMessage(error, api, provider, requestModel.id);\n outer.push({ type: \"error\", reason: \"error\", error: message });\n outer.end(message);\n }\n });\n return outer;\n };\n const streamSimple = (streamModel, context, streamOptions) => stream(streamModel, context, streamOptions);\n const fetchDeferred = (requestModel, handle, fetchOptions) => {\n const outer = createAssistantMessageEventStream();\n state.deferredFetchCount++;\n queueMicrotask(async () => {\n try {\n await fetchOptions?.onResponse?.({ status: 200, headers: {} }, requestModel);\n const entry = deferredResponses.get(handle.id);\n if (!entry ||\n entry.handle.provider !== handle.provider ||\n entry.handle.modelId !== handle.modelId ||\n entry.handle.api !== handle.api) {\n throw new Error(`Unknown faux deferred response: ${handle.id}`);\n }\n if (entry.cancelled)\n throw new Error(`Faux deferred response was cancelled: ${handle.id}`);\n if (entry.pendingFetches > 0) {\n entry.pendingFetches--;\n await streamWithDeltas(outer, createDeferredMessage(requestModel, entry.handle), minTokenSize, maxTokenSize, tokensPerSecond, fetchOptions?.signal);\n return;\n }\n if (!entry.final) {\n const { deferred: _deferred, signal: _submissionSignal, onResponse: _submissionOnResponse, ...submissionOptions } = entry.options ?? {};\n try {\n entry.final = await resolveResponse(entry.step, entry.context, submissionOptions, entry.model);\n }\n catch (error) {\n entry.final = createErrorMessage(error, api, provider, entry.model.id);\n }\n }\n await streamWithDeltas(outer, entry.final, minTokenSize, maxTokenSize, tokensPerSecond, fetchOptions?.signal);\n }\n catch (error) {\n const message = createErrorMessage(error, api, provider, requestModel.id);\n outer.push({ type: \"error\", reason: \"error\", error: message });\n outer.end(message);\n }\n });\n return outer;\n };\n const cancelDeferred = async (requestModel, handle, cancelOptions) => {\n state.cancelledDeferred.push(structuredClone(handle));\n const entry = deferredResponses.get(handle.id);\n if (entry)\n entry.cancelled = true;\n await cancelOptions?.onResponse?.({ status: 200, headers: {} }, requestModel);\n };\n function getModel(requestedModelId) {\n if (!requestedModelId) {\n return models[0];\n }\n return models.find((candidate) => candidate.id === requestedModelId);\n }\n return {\n api,\n provider,\n models,\n stream,\n streamSimple,\n fetchDeferred,\n cancelDeferred,\n getModel,\n state,\n setResponses(responses) {\n pendingResponses = [...responses];\n },\n appendResponses(responses) {\n pendingResponses.push(...responses);\n },\n getPendingResponseCount() {\n return pendingResponses.length;\n },\n };\n}\n/**\n * Faux provider for tests built on explicit `Models` collections:\n *\n * ```ts\n * const faux = fauxProvider();\n * const models = createModels();\n * models.setProvider(faux.provider);\n * faux.setResponses([fauxAssistantMessage(\"hi\")]);\n * ```\n */\nexport function fauxProvider(options = {}) {\n const core = createFauxCore(options);\n const provider = createProvider({\n id: core.provider,\n auth: { apiKey: { name: \"Faux\", resolve: async () => ({ auth: {} }) } },\n models: core.models,\n api: {\n stream: core.stream,\n streamSimple: core.streamSimple,\n fetchDeferred: core.fetchDeferred,\n cancelDeferred: core.cancelDeferred,\n },\n });\n return {\n provider,\n api: core.api,\n models: core.models,\n getModel: core.getModel,\n state: core.state,\n setResponses: core.setResponses,\n appendResponses: core.appendResponses,\n getPendingResponseCount: core.getPendingResponseCount,\n };\n}\n//# sourceMappingURL=faux.js.map","/**\n * Regex patterns to detect context overflow errors from different providers.\n *\n * These patterns match error messages returned when the input exceeds\n * the model's context window.\n *\n * Provider-specific patterns (with example error messages):\n *\n * - Anthropic: \"prompt is too long: 213462 tokens > 200000 maximum\"\n * - Anthropic: \"413 {\\\"error\\\":{\\\"type\\\":\\\"request_too_large\\\",\\\"message\\\":\\\"Request exceeds the maximum size\\\"}}\"\n * - OpenAI: \"Your input exceeds the context window of this model\"\n * - OpenAI/LiteLLM: \"Requested token count exceeds the model's maximum context length of 131072 tokens\"\n * - OpenAI-compatible: \"Input length (265330) exceeds model's maximum context length (262144).\"\n * - Google: \"The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)\"\n * - xAI: \"This model's maximum prompt length is 131072 but the request contains 537812 tokens\"\n * - Groq: \"Please reduce the length of the messages or completion\"\n * - OpenRouter: \"This endpoint's maximum context length is X tokens. However, you requested about Y tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"the request exceeds the available context size, try increasing it\"\n * - LM Studio: \"tokens to keep from the initial prompt is greater than the context length\"\n * - GitHub Copilot: \"prompt token count of X exceeds the limit of Y\"\n * - MiniMax: \"invalid params, context window exceeds limit\"\n * - Kimi For Coding: \"Your request exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - Cerebras: \"400/413 status code (no body)\"\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - z.ai: Does NOT error, accepts overflow silently - handled via usage.input > contextWindow\n * - Xiaomi MiMo: Truncates input to fill contextWindow exactly, then returns finish_reason \"length\"\n * with output=0 (no room left to generate). Detected via stopReason \"length\" + zero output +\n * input filling the context window.\n * - DashScope/Qwen: \"Range of input length should be [1, X]\" (HTTP 400 invalid_parameter_error)\n * - Ollama: Some deployments truncate silently, others return errors like \"prompt too long; exceeded max context length by X tokens\"\n */\nconst OVERFLOW_PATTERNS = [\n /prompt is too long/i, // Anthropic token overflow\n /request_too_large/i, // Anthropic request byte-size overflow (HTTP 413)\n /input is too long for requested model/i, // Amazon Bedrock\n /exceeds the context window/i, // OpenAI (Completions & Responses API)\n /exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\\d,]+ tokens?|\\s*\\([\\d,]+\\))/i, // OpenAI-compatible proxies (LiteLLM)\n /input token count.*exceeds the maximum/i, // Google (Gemini)\n /maximum prompt length is \\d+/i, // xAI (Grok)\n /reduce the length of the messages/i, // Groq\n /maximum context length is \\d+ tokens/i, // OpenRouter (most backends)\n /exceeds (?:the )?maximum allowed input length of [\\d,]+ tokens?/i, // OpenRouter/Poolside\n /input \\(\\d+ tokens\\) is longer than the model'?s context length \\(\\d+ tokens\\)/i, // Together AI\n /exceeds the limit of \\d+/i, // GitHub Copilot\n /exceeds the available context size/i, // llama.cpp server\n /greater than the context length/i, // LM Studio\n /context window exceeds limit/i, // MiniMax\n /exceeded model token limit/i, // Kimi For Coding\n /too large for model with \\d+ maximum context length/i, // Mistral\n /prompt has [\\d,]+ tokens?, but the configured context size is [\\d,]+ tokens?/i, // DS4 server\n /model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text\n /prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow error\n /range of input length should be/i, // DashScope / Qwen Token Plan\n /context[_ ]length[_ ]exceeded/i, // Generic fallback\n /too many tokens/i, // Generic fallback\n /token limit exceeded/i, // Generic fallback\n /^4(?:00|13)\\s*(?:status code)?\\s*\\(no body\\)/i, // Cerebras: 400/413 with no body\n];\n/**\n * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).\n * Error messages matching any of these are excluded from overflow detection\n * even if they also match an OVERFLOW_PATTERN.\n *\n * Example: Bedrock formats throttling errors as \"ThrottlingException: Too many tokens,\n * please wait before trying again.\" which would match the /too many tokens/i overflow\n * pattern without this exclusion.\n */\nconst NON_OVERFLOW_PATTERNS = [\n /^(Throttling error|Service unavailable):/i, // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)\n /rate limit/i, // Generic rate limiting\n /too many requests/i, // Generic HTTP 429 style\n];\n/**\n * Check if an assistant message represents a context overflow error.\n *\n * This handles three cases:\n * 1. Error-based overflow: Most providers return stopReason \"error\" with a\n * specific error message pattern.\n * 2. Silent overflow: Some providers accept overflow requests and return\n * successfully. For these, we check if usage.input exceeds the context window.\n * 3. Length-stop overflow: Xiaomi MiMo can return \"length\" with zero output when\n * the input fills the context window.\n *\n * ## Reliability by Provider\n *\n * **Reliable detection (returns error with detectable message):**\n * - Anthropic: \"prompt is too long: X tokens > Y maximum\" or \"request_too_large\"\n * - OpenAI (Completions & Responses): \"exceeds the context window\", \"exceeds the model's maximum context length of X tokens\", or \"exceeds model's maximum context length (X)\"\n * - Google Gemini: \"input token count exceeds the maximum\"\n * - xAI (Grok): \"maximum prompt length is X but request contains Y\"\n * - Groq: \"reduce the length of the messages\"\n * - Cerebras: 400/413 status code (no body)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - OpenRouter (most backends): \"maximum context length is X tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"exceeds the available context size\"\n * - LM Studio: \"greater than the context length\"\n * - Kimi For Coding: \"exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - DashScope/Qwen: \"Range of input length should be [1, X]\"\n *\n * **Unreliable detection:**\n * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),\n * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.\n * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason \"length\" with\n * output=0. Pass contextWindow param to detect via the \"filled context + zero output\" signal.\n * - Ollama: May truncate input silently for some setups, but may also return explicit\n * overflow errors that match the patterns above. Silent truncation still cannot be\n * detected here because we do not know the expected token count.\n *\n * ## Custom Providers\n *\n * If you've added custom models via settings.json, this function may not detect\n * overflow errors from those providers. To add support:\n *\n * 1. Send a request that exceeds the model's context window\n * 2. Check the errorMessage in the response\n * 3. Create a regex pattern that matches the error\n * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or\n * check the errorMessage yourself before calling this function\n *\n * @param message - The assistant message to check\n * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)\n * @returns true if the message indicates a context overflow\n */\nexport function isContextOverflow(message, contextWindow) {\n // Case 1: Check error message patterns\n if (message.stopReason === \"error\" && message.errorMessage) {\n // Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)\n const isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage));\n if (!isNonOverflow && OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage))) {\n return true;\n }\n }\n // Case 2: Silent overflow (z.ai style) - successful but usage exceeds context\n if (contextWindow && message.stopReason === \"stop\") {\n const inputTokens = message.usage.input + message.usage.cacheRead;\n if (inputTokens > contextWindow) {\n return true;\n }\n }\n // Case 3: Length-stop overflow (Xiaomi MiMo style) - server truncates oversized input\n // to fit the context window, leaving no room for output. Returns stopReason \"length\"\n // with output=0 and input+cacheRead filling the context window.\n if (contextWindow && message.stopReason === \"length\" && message.usage.output === 0) {\n const inputTokens = message.usage.input + message.usage.cacheRead;\n if (inputTokens >= contextWindow * 0.99) {\n return true;\n }\n }\n return false;\n}\n/**\n * Check whether a length stop ended below the caller or model's intended output limit.\n * Such responses may be caused by context pressure or provider-side truncation, so callers\n * can make one bounded compact-and-retry attempt. `desiredMaxOutput` must be the original\n * limit before any context-based clamping.\n */\nexport function isRecoverableLength(message, desiredMaxOutput) {\n return message.stopReason === \"length\" && desiredMaxOutput > 0 && message.usage.output < desiredMaxOutput;\n}\n/**\n * Get the overflow patterns for testing purposes.\n */\nexport function getOverflowPatterns() {\n return [...OVERFLOW_PATTERNS];\n}\n//# sourceMappingURL=overflow.js.map","function buildProviderErrorPattern(patterns) {\n return new RegExp(patterns.join(\"|\"), \"i\");\n}\nconst NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([\n // OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n // Zen API. These are subscription/account limits, not transient throttles.\n \"GoUsageLimitError\",\n \"FreeUsageLimitError\",\n // OpenCode Go subscription-limit text asks users to enable available-balance\n // usage after rolling/weekly/monthly limits are reached.\n \"Monthly usage limit reached\",\n \"available balance\",\n // Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n // quota/billing error code; the other strings cover common gateway wording.\n \"insufficient_quota\",\n \"out of budget\",\n \"quota exceeded\",\n \"billing\",\n]);\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n // Generic provider load, HTTP status, and server-side transient failures.\n \"overloaded\",\n \"rate.?limit\",\n \"too many requests\",\n \"429\",\n \"500\",\n \"502\",\n \"503\",\n \"504\",\n \"524\",\n \"service.?unavailable\",\n \"server.?error\",\n \"internal.?error\",\n // Wrapper/provider text for transient upstream failures, including OpenRouter\n // \"Provider returned error\" responses (#2264).\n \"provider.?returned.?error\",\n // Network, proxy, and fetch transport failures. This includes OpenAI Codex\n // raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n // \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n \"network.?error\",\n \"connection.?error\",\n \"connection.?refused\",\n \"connection.?lost\",\n \"other side closed\",\n \"fetch failed\",\n \"getaddrinfo\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n \"upstream.?connect\",\n \"reset before headers\",\n \"socket hang up\",\n \"socket connection was closed\",\n \"timed? out\",\n \"timeout\",\n \"terminated\",\n // WebSocket transports can report close/error text instead of HTTP/fetch text.\n \"websocket.?closed\",\n \"websocket.?error\",\n // Premature stream endings from SDKs and transports. Anthropic can throw\n // \"stream ended without ...\" and \"Anthropic stream ended before message_stop\"\n // (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).\n \"ended without\",\n \"stream ended before message_stop\",\n \"stream ended before a terminal response event\",\n \"http2 request did not get a response\",\n // Provider-requested retry delay cap failures should flow through the outer\n // retry policy so callers can surface/abort the backoff (#1123).\n \"retry delay\",\n // Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock\n // stream exceptions (#6019).\n \"you can retry your request\",\n \"try your request again\",\n \"please retry your request\",\n // gRPC based providers (e.g. NVIDIA NIM)\n \"ResourceExhausted\",\n]);\nclass RetrySleepAbortError extends Error {\n constructor() {\n super(\"Aborted\");\n }\n}\nfunction sleep(ms, signal) {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new RetrySleepAbortError());\n return;\n }\n const timeout = setTimeout(resolve, ms);\n signal?.addEventListener(\"abort\", () => {\n clearTimeout(timeout);\n reject(new RetrySleepAbortError());\n }, { once: true });\n });\n}\n/**\n * Run a single assistant-producing call with bounded retry on transient errors.\n *\n * Behavior:\n * - A successful response is returned immediately. Aborts are terminal and never\n * retried, but reported as unsuccessful if they happen after a retry was scheduled.\n * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`\n * too, so callers do not need to care when cancellation happened.\n * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/\n * billing exhaustion) is returned immediately so deterministic errors fail fast.\n * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting\n * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before\n * the retried call starts, and `onRetryFinished` once at the end (whether the loop\n * ends in success, exhausted retries, or an aborted backoff).\n *\n * When `policy` is undefined or disabled, the first response is returned unchanged\n * (equivalent to calling `produce()` directly).\n */\nexport async function retryAssistantCall(produce, policy, signal, callbacks) {\n const maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n let attempt = 0;\n let lastRetry;\n for (;;) {\n const response = await produce();\n // Abort: terminal but not successful. Never retry an aborted message.\n if (response.stopReason === \"aborted\") {\n if (lastRetry)\n await callbacks?.onRetryFinished?.(false, lastRetry.attempt);\n return response;\n }\n // Success: non-error, non-abort responses return as-is.\n if (response.stopReason !== \"error\") {\n if (lastRetry)\n await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n return response;\n }\n // Non-retryable, or budget exhausted: return the final error message.\n if (attempt >= maxAttempts || !isRetryableAssistantError(response)) {\n if (lastRetry)\n await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);\n return response;\n }\n attempt++;\n lastRetry = { attempt, errorMessage: response.errorMessage || \"Unknown error\" };\n const delayMs = policy.baseDelayMs * 2 ** (attempt - 1);\n await callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n // Normalize aborts during retry backoff to the same AssistantMessage shape as\n // provider stream aborts, so callers do not need to care when cancellation happened.\n try {\n await sleep(delayMs, signal);\n }\n catch (error) {\n await callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n if (error instanceof RetrySleepAbortError) {\n return { ...response, stopReason: \"aborted\", errorMessage: undefined };\n }\n throw error;\n }\n await callbacks?.onRetryAttemptStart?.();\n }\n}\n/**\n * Classifies whether a failed assistant message looks like a transient provider\n * or transport error, so callers can decide if the last assistant turn should be\n * restarted.\n *\n * This does not implement retry policy. Callers should first handle context\n * overflow separately, then apply their own retry budget, backoff, and reporting\n * before restarting the assistant turn.\n */\nexport function isRetryableAssistantError(message) {\n if (message.stopReason !== \"error\" || !message.errorMessage)\n return false;\n const errorMessage = message.errorMessage;\n if (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage))\n return false;\n return RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);\n}\n//# sourceMappingURL=retry.js.map","/** Extract and join text from message content. */\nexport function contentText(content, separator = \"\\n\") {\n if (typeof content === \"string\")\n return content;\n return content\n .filter((block) => block.type === \"text\")\n .map((block) => block.text)\n .join(separator);\n}\n//# sourceMappingURL=text.js.map","import { Type } from \"typebox\";\n/**\n * Creates a string enum schema compatible with Google's API and other providers\n * that don't support anyOf/const patterns.\n *\n * @example\n * const OperationSchema = StringEnum([\"add\", \"subtract\", \"multiply\", \"divide\"], {\n * description: \"The operation to perform\"\n * });\n *\n * type Operation = Static<typeof OperationSchema>; // \"add\" | \"subtract\" | \"multiply\" | \"divide\"\n */\nexport function StringEnum(values, options) {\n return Type.Unsafe({\n type: \"string\",\n enum: values,\n ...(options?.description && { description: options.description }),\n ...(options?.default && { default: options.default }),\n });\n}\n//# sourceMappingURL=typebox-helpers.js.map","import { Compile } from \"typebox/compile\";\nimport { Value } from \"typebox/value\";\nconst validatorCache = new WeakMap();\nconst TYPEBOX_KIND = Symbol.for(\"TypeBox.Kind\");\nfunction getSchemaTypes(schema) {\n if (typeof schema.type === \"string\") {\n return [schema.type];\n }\n if (Array.isArray(schema.type)) {\n return schema.type.filter((type) => typeof type === \"string\");\n }\n return [];\n}\nfunction matchesJsonType(value, type) {\n switch (type) {\n case \"number\":\n return typeof value === \"number\";\n case \"integer\":\n return typeof value === \"number\" && Number.isInteger(value);\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"string\":\n return typeof value === \"string\";\n case \"null\":\n return value === null;\n case \"array\":\n return Array.isArray(value);\n case \"object\":\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n default:\n return false;\n }\n}\nfunction getSubSchemaValidator(schema) {\n try {\n return getValidator(schema);\n }\n catch {\n return undefined;\n }\n}\nfunction coercePrimitiveByType(value, type) {\n switch (type) {\n case \"number\": {\n if (value === null) {\n return 0;\n }\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n if (typeof value === \"boolean\") {\n return value ? 1 : 0;\n }\n return value;\n }\n case \"integer\": {\n if (value === null) {\n return 0;\n }\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value);\n if (Number.isInteger(parsed)) {\n return parsed;\n }\n }\n if (typeof value === \"boolean\") {\n return value ? 1 : 0;\n }\n return value;\n }\n case \"boolean\": {\n if (value === null) {\n return false;\n }\n if (typeof value === \"string\") {\n if (value === \"true\") {\n return true;\n }\n if (value === \"false\") {\n return false;\n }\n }\n if (typeof value === \"number\") {\n if (value === 1) {\n return true;\n }\n if (value === 0) {\n return false;\n }\n }\n return value;\n }\n case \"string\": {\n if (value === null) {\n return \"\";\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n return value;\n }\n case \"null\": {\n if (value === \"\" || value === 0 || value === false) {\n return null;\n }\n return value;\n }\n default:\n return value;\n }\n}\nfunction applySchemaObjectCoercion(value, schema) {\n const properties = schema.properties;\n const definedKeys = new Set(properties ? Object.keys(properties) : []);\n if (properties) {\n for (const [key, propertySchema] of Object.entries(properties)) {\n if (!(key in value)) {\n continue;\n }\n value[key] = coerceWithJsonSchema(value[key], propertySchema);\n }\n }\n if (schema.additionalProperties && typeof schema.additionalProperties === \"object\") {\n for (const [key, propertyValue] of Object.entries(value)) {\n if (definedKeys.has(key)) {\n continue;\n }\n value[key] = coerceWithJsonSchema(propertyValue, schema.additionalProperties);\n }\n }\n}\nfunction applySchemaArrayCoercion(value, schema) {\n if (Array.isArray(schema.items)) {\n for (let index = 0; index < value.length; index++) {\n const itemSchema = schema.items[index];\n if (!itemSchema) {\n continue;\n }\n value[index] = coerceWithJsonSchema(value[index], itemSchema);\n }\n return;\n }\n if (schema.items && typeof schema.items === \"object\") {\n for (let index = 0; index < value.length; index++) {\n value[index] = coerceWithJsonSchema(value[index], schema.items);\n }\n }\n}\nfunction coerceWithUnionSchema(value, schemas) {\n for (const schema of schemas) {\n const validator = getSubSchemaValidator(schema);\n if (validator?.Check(value)) {\n return value;\n }\n }\n for (const schema of schemas) {\n const candidate = structuredClone(value);\n const coerced = coerceWithJsonSchema(candidate, schema);\n const validator = getSubSchemaValidator(schema);\n if (validator?.Check(coerced)) {\n return coerced;\n }\n }\n return value;\n}\nfunction coerceWithJsonSchema(value, schema) {\n let nextValue = value;\n if (Array.isArray(schema.allOf)) {\n for (const nested of schema.allOf) {\n nextValue = coerceWithJsonSchema(nextValue, nested);\n }\n }\n if (Array.isArray(schema.anyOf)) {\n nextValue = coerceWithUnionSchema(nextValue, schema.anyOf);\n }\n if (Array.isArray(schema.oneOf)) {\n nextValue = coerceWithUnionSchema(nextValue, schema.oneOf);\n }\n const schemaTypes = getSchemaTypes(schema);\n const matchesUnionMember = schemaTypes.length > 1 && schemaTypes.some((schemaType) => matchesJsonType(nextValue, schemaType));\n if (schemaTypes.length > 0 && !matchesUnionMember) {\n for (const schemaType of schemaTypes) {\n const candidate = coercePrimitiveByType(nextValue, schemaType);\n if (candidate !== nextValue) {\n nextValue = candidate;\n break;\n }\n }\n }\n if (schemaTypes.includes(\"object\") &&\n typeof nextValue === \"object\" &&\n nextValue !== null &&\n !Array.isArray(nextValue)) {\n applySchemaObjectCoercion(nextValue, schema);\n }\n if (schemaTypes.includes(\"array\") && Array.isArray(nextValue)) {\n applySchemaArrayCoercion(nextValue, schema);\n }\n return nextValue;\n}\nfunction getValidator(schema) {\n const key = schema;\n const cached = validatorCache.get(key);\n if (cached) {\n return cached;\n }\n const validator = Compile(schema);\n validatorCache.set(key, validator);\n return validator;\n}\nfunction formatValidationPath(error) {\n if (error.keyword === \"required\") {\n const requiredProperties = error.params.requiredProperties;\n const requiredProperty = requiredProperties?.[0];\n if (requiredProperty) {\n const basePath = error.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\");\n return basePath ? `${basePath}.${requiredProperty}` : requiredProperty;\n }\n }\n const path = error.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\");\n return path || \"root\";\n}\n/**\n * Finds a tool by name and validates the tool call arguments against its TypeBox schema\n * @param tools Array of tool definitions\n * @param toolCall The tool call from the LLM\n * @returns The validated arguments\n * @throws Error if tool is not found or validation fails\n */\nexport function validateToolCall(tools, toolCall) {\n const tool = tools.find((t) => t.name === toolCall.name);\n if (!tool) {\n throw new Error(`Tool \"${toolCall.name}\" not found`);\n }\n return validateToolArguments(tool, toolCall);\n}\n/**\n * Validates tool call arguments against the tool's TypeBox schema\n * @param tool The tool definition with TypeBox schema\n * @param toolCall The tool call from the LLM\n * @returns The validated (and potentially coerced) arguments\n * @throws Error with formatted message if validation fails\n */\nexport function validateToolArguments(tool, toolCall) {\n const args = structuredClone(toolCall.arguments);\n Value.Convert(tool.parameters, args);\n const validator = getValidator(tool.parameters);\n if (!Object.getOwnPropertySymbols(tool.parameters).includes(TYPEBOX_KIND)) {\n const coerced = coerceWithJsonSchema(args, tool.parameters);\n if (coerced !== args) {\n if (typeof args === \"object\" && args !== null && typeof coerced === \"object\" && coerced !== null) {\n for (const key of Object.keys(args)) {\n delete args[key];\n }\n Object.assign(args, coerced);\n }\n else {\n return validator.Check(coerced) ? coerced : args;\n }\n }\n }\n if (validator.Check(args)) {\n return args;\n }\n const errors = validator\n .Errors(args)\n .map((error) => ` - ${formatValidationPath(error)}: ${error.message}`)\n .join(\"\\n\") || \"Unknown validation error\";\n const errorMessage = `Validation failed for tool \"${toolCall.name}\":\\n${errors}\\n\\nReceived arguments:\\n${JSON.stringify(toolCall.arguments, null, 2)}`;\n throw new Error(errorMessage);\n}\n//# sourceMappingURL=validation.js.map"],"x_google_ignoreList":[0,1,2,3,4,5],"mappings":";;;;;;;;;AAEA,MAAM,cAAc;AACpB,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACzB,MAAM,yBAAyB;AAC/B,MAAM,yBAAyB;AAC/B,MAAM,gBAAgB;CAClB,OAAO;CACP,QAAQ;CACR,WAAW;CACX,YAAY;CACZ,aAAa;CACb,MAAM;EAAE,OAAO;EAAG,QAAQ;EAAG,WAAW;EAAG,YAAY;EAAG,OAAO;CAAE;AACvE;AACA,SAAgB,SAAS,MAAM;CAC3B,OAAO;EAAE,MAAM;EAAQ;CAAK;AAChC;AACA,SAAgB,aAAa,UAAU;CACnC,OAAO;EAAE,MAAM;EAAY;CAAS;AACxC;AACA,SAAgB,aAAa,MAAM,YAAY,UAAU,CAAC,GAAG;CACzD,OAAO;EACH,MAAM;EACN,IAAI,QAAQ,MAAM,SAAS,MAAM;EACjC;EACA,WAAW;CACf;AACJ;AACA,SAAS,8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QAAQ,KAAK,YAAY,IAAI;CACnC,MAAM,YAAY,aAAa,KAAK,UAAU;CAC9C,IAAI,CAAC,OAAO,sBAAsB,KAAK,UAAU,CAAC,CAAC,SAAS,YAAY,GAAG;EACvE,MAAM,UAAU,qBAAqB,MAAM,KAAK,UAAU;EAC1D,IAAI,YAAY,MAAM;GAClB,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,OAAO,YAAY,YAAY,YAAY,MAAM;IAC9F,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,GAC9B,OAAO,KAAK;IAEhB,OAAO,OAAO,MAAM,OAAO;GAC/B,OAEI,OAAO,UAAU,MAAM,OAAO,IAAI,UAAU;EAEpD;CACJ;CACA,IAAI,UAAU,MAAM,IAAI,GACpB,OAAO;CAEX,MAAM,SAAS,UACV,OAAO,IAAI,CAAC,CACZ,KAAK,UAAU,OAAO,qBAAqB,KAAK,EAAE,IAAI,MAAM,SAAS,CAAC,CACtE,KAAK,IAAI,KAAK;CACnB,MAAM,eAAe,+BAA+B,SAAS,KAAK,MAAM,OAAO,2BAA2B,KAAK,UAAU,SAAS,WAAW,MAAM,CAAC;CACpJ,MAAM,IAAI,MAAM,YAAY;AAChC"}
@@ -5,7 +5,7 @@ import { n as providerHeadersToRecord } from "./headers-CPzZhJQn.mjs";
5
5
  import { t as sanitizeSurrogates } from "./sanitize-unicode-wLA11KvZ.mjs";
6
6
  import { i as buildBaseOptions } from "./transform-messages-DGq9mvhA.mjs";
7
7
  import { n as normalizeProviderError, t as formatProviderError } from "./error-body-DKA3lknR.mjs";
8
- import { a as resolveGoogleFunctionCallingMode, c as supportsGoogleStrictToolSampling, i as mapStopReason, l as GoogleGenAI, n as convertTools, o as retainThoughtSignature, r as isThinkingPart, s as retryGoogleRequest, t as convertMessages } from "./google-shared-CRsAUItF.mjs";
8
+ import { a as resolveGoogleFunctionCallingMode, c as supportsGoogleStrictToolSampling, i as mapStopReason, l as GoogleGenAI, n as convertTools, o as retainThoughtSignature, r as isThinkingPart, s as retryGoogleRequest, t as convertMessages } from "./google-shared-DYP_9cnK.mjs";
9
9
  //#region node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.js
10
10
  let toolCallCounter = 0;
11
11
  const stream = (model, context, options) => {
@@ -355,4 +355,4 @@ function getGoogleBudget(model, effort, customBudgets) {
355
355
  //#endregion
356
356
  export { stream, streamSimple };
357
357
 
358
- //# sourceMappingURL=google-generative-ai-B7OZs5lu.mjs.map
358
+ //# sourceMappingURL=google-generative-ai-DT5S8D8y.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"google-generative-ai-B7OZs5lu.mjs","names":[],"sources":["../node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.js"],"sourcesContent":["import { GoogleGenAI, } from \"@google/genai\";\nimport { calculateCost, clampThinkingLevel } from \"../models.js\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { providerHeadersToRecord } from \"../utils/headers.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { convertMessages, convertTools, isThinkingPart, mapStopReason, resolveGoogleFunctionCallingMode, retainThoughtSignature, retryGoogleRequest, supportsGoogleStrictToolSampling, } from \"./google-shared.js\";\nimport { buildBaseOptions } from \"./simple-options.js\";\n// Counter for generating unique tool call IDs\nlet toolCallCounter = 0;\nexport const stream = (model, context, options) => {\n const stream = new AssistantMessageEventStream();\n (async () => {\n const output = {\n role: \"assistant\",\n content: [],\n api: \"google-generative-ai\",\n provider: model.provider,\n model: model.id,\n usage: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n },\n stopReason: \"pending\",\n timestamp: Date.now(),\n };\n try {\n if (options?.fetch && options.fetch !== globalThis.fetch) {\n throw new Error(\"Custom fetch is not supported by the Google Generative AI adapter\");\n }\n const apiKey = options?.apiKey;\n if (!apiKey) {\n throw new Error(`No API key for provider: ${model.provider}`);\n }\n const client = createClient(model, apiKey, options?.headers);\n let params = buildParams(model, context, options);\n const nextParams = await options?.onPayload?.(params, model);\n if (nextParams !== undefined) {\n params = nextParams;\n }\n const googleStream = await retryGoogleRequest(() => client.models.generateContentStream(params), options);\n stream.push({ type: \"start\", partial: output });\n let currentBlock = null;\n const blocks = output.content;\n const blockIndex = () => blocks.length - 1;\n for await (const chunk of googleStream) {\n // @google/genai documents GenerateContentResponse.responseId as an output-only field\n // used to identify each response. Keep the first non-empty one from the stream.\n output.responseId ||= chunk.responseId;\n const candidate = chunk.candidates?.[0];\n if (candidate?.content?.parts) {\n for (const part of candidate.content.parts) {\n if (part.text !== undefined) {\n const isThinking = isThinkingPart(part);\n if (!currentBlock ||\n (isThinking && currentBlock.type !== \"thinking\") ||\n (!isThinking && currentBlock.type !== \"text\")) {\n if (currentBlock) {\n if (currentBlock.type === \"text\") {\n stream.push({\n type: \"text_end\",\n contentIndex: blocks.length - 1,\n content: currentBlock.text,\n partial: output,\n });\n }\n else {\n stream.push({\n type: \"thinking_end\",\n contentIndex: blockIndex(),\n content: currentBlock.thinking,\n partial: output,\n });\n }\n }\n if (isThinking) {\n currentBlock = { type: \"thinking\", thinking: \"\", thinkingSignature: undefined };\n output.content.push(currentBlock);\n stream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n }\n else {\n currentBlock = { type: \"text\", text: \"\" };\n output.content.push(currentBlock);\n stream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n }\n }\n if (currentBlock.type === \"thinking\") {\n currentBlock.thinking += part.text;\n currentBlock.thinkingSignature = retainThoughtSignature(currentBlock.thinkingSignature, part.thoughtSignature);\n stream.push({\n type: \"thinking_delta\",\n contentIndex: blockIndex(),\n delta: part.text,\n partial: output,\n });\n }\n else {\n currentBlock.text += part.text;\n currentBlock.textSignature = retainThoughtSignature(currentBlock.textSignature, part.thoughtSignature);\n stream.push({\n type: \"text_delta\",\n contentIndex: blockIndex(),\n delta: part.text,\n partial: output,\n });\n }\n }\n if (part.functionCall) {\n if (currentBlock) {\n if (currentBlock.type === \"text\") {\n stream.push({\n type: \"text_end\",\n contentIndex: blockIndex(),\n content: currentBlock.text,\n partial: output,\n });\n }\n else {\n stream.push({\n type: \"thinking_end\",\n contentIndex: blockIndex(),\n content: currentBlock.thinking,\n partial: output,\n });\n }\n currentBlock = null;\n }\n // Generate unique ID if not provided or if it's a duplicate\n const providedId = part.functionCall.id;\n const needsNewId = !providedId || output.content.some((b) => b.type === \"toolCall\" && b.id === providedId);\n const toolCallId = needsNewId\n ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`\n : providedId;\n const toolCall = {\n type: \"toolCall\",\n id: toolCallId,\n name: part.functionCall.name || \"\",\n arguments: part.functionCall.args ?? {},\n ...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }),\n };\n output.content.push(toolCall);\n stream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n stream.push({\n type: \"toolcall_delta\",\n contentIndex: blockIndex(),\n delta: JSON.stringify(toolCall.arguments),\n partial: output,\n });\n stream.push({ type: \"toolcall_end\", contentIndex: blockIndex(), toolCall, partial: output });\n }\n }\n }\n if (candidate?.finishReason) {\n output.rawStopReason = candidate.finishReason;\n output.stopReason = mapStopReason(candidate.finishReason);\n if (output.content.some((b) => b.type === \"toolCall\")) {\n output.stopReason = \"toolUse\";\n }\n }\n if (chunk.usageMetadata) {\n output.usage = {\n input: (chunk.usageMetadata.promptTokenCount || 0) - (chunk.usageMetadata.cachedContentTokenCount || 0),\n output: (chunk.usageMetadata.candidatesTokenCount || 0) + (chunk.usageMetadata.thoughtsTokenCount || 0),\n cacheRead: chunk.usageMetadata.cachedContentTokenCount || 0,\n cacheWrite: 0,\n reasoning: chunk.usageMetadata.thoughtsTokenCount || 0,\n totalTokens: chunk.usageMetadata.totalTokenCount || 0,\n cost: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n total: 0,\n },\n };\n calculateCost(model, output.usage);\n }\n }\n if (currentBlock) {\n if (currentBlock.type === \"text\") {\n stream.push({\n type: \"text_end\",\n contentIndex: blockIndex(),\n content: currentBlock.text,\n partial: output,\n });\n }\n else {\n stream.push({\n type: \"thinking_end\",\n contentIndex: blockIndex(),\n content: currentBlock.thinking,\n partial: output,\n });\n }\n }\n if (options?.signal?.aborted) {\n throw new Error(\"Request was aborted\");\n }\n if (output.stopReason === \"pending\") {\n throw new Error(\"Google stream ended without a finish reason\");\n }\n if (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n const errorMessage = output.rawStopReason\n ? `Provider stopped with: ${output.rawStopReason}`\n : \"An unknown error occurred\";\n throw new Error(errorMessage);\n }\n stream.push({ type: \"done\", reason: output.stopReason, message: output });\n stream.end();\n }\n catch (error) {\n // Remove internal index property used during streaming\n for (const block of output.content) {\n if (\"index\" in block) {\n delete block.index;\n }\n }\n output.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n output.errorMessage = formatProviderError(normalizeProviderError(error));\n stream.push({ type: \"error\", reason: output.stopReason, error: output });\n stream.end();\n }\n })();\n return stream;\n};\nexport const streamSimple = (model, context, options) => {\n const apiKey = options?.apiKey;\n if (!apiKey) {\n throw new Error(`No API key for provider: ${model.provider}`);\n }\n const base = buildBaseOptions(model, context, options, apiKey);\n if (!options?.reasoning) {\n return stream(model, context, { ...base, thinking: { enabled: false } });\n }\n const clampedReasoning = clampThinkingLevel(model, options.reasoning);\n const effort = (clampedReasoning === \"off\" ? \"high\" : clampedReasoning);\n const googleModel = model;\n if (isGemini3ProModel(googleModel) || isGemini3FlashModel(googleModel) || isGemma4Model(googleModel)) {\n return stream(model, context, {\n ...base,\n thinking: {\n enabled: true,\n level: getThinkingLevel(effort, googleModel),\n },\n });\n }\n return stream(model, context, {\n ...base,\n thinking: {\n enabled: true,\n budgetTokens: getGoogleBudget(googleModel, effort, options.thinkingBudgets),\n },\n });\n};\nfunction createClient(model, apiKey, optionsHeaders) {\n const httpOptions = {};\n if (model.baseUrl) {\n httpOptions.baseUrl = model.baseUrl;\n httpOptions.apiVersion = \"\"; // baseUrl already includes version path, don't append\n }\n const headers = providerHeadersToRecord({ ...model.headers, ...optionsHeaders });\n if (headers) {\n httpOptions.headers = headers;\n }\n return new GoogleGenAI({\n apiKey,\n httpOptions: Object.keys(httpOptions).length > 0 ? httpOptions : undefined,\n });\n}\nfunction buildParams(model, context, options = {}) {\n const contents = convertMessages(model, context);\n const generationConfig = {};\n if (options.temperature !== undefined) {\n generationConfig.temperature = options.temperature;\n }\n if (options.maxTokens !== undefined) {\n generationConfig.maxOutputTokens = options.maxTokens;\n }\n const functionCallingMode = context.tools?.length\n ? resolveGoogleFunctionCallingMode(context.tools, options.toolChoice, supportsGoogleStrictToolSampling(model.id))\n : undefined;\n const config = {\n ...(Object.keys(generationConfig).length > 0 && generationConfig),\n ...(context.systemPrompt && { systemInstruction: sanitizeSurrogates(context.systemPrompt) }),\n ...(context.tools && context.tools.length > 0 && { tools: convertTools(context.tools) }),\n ...(functionCallingMode !== undefined && {\n toolConfig: { functionCallingConfig: { mode: functionCallingMode } },\n }),\n };\n if (options.thinking?.enabled && model.reasoning) {\n const thinkingConfig = { includeThoughts: true };\n if (options.thinking.level !== undefined) {\n // Cast to any since our GoogleThinkingLevel mirrors Google's ThinkingLevel enum values\n thinkingConfig.thinkingLevel = options.thinking.level;\n }\n else if (options.thinking.budgetTokens !== undefined) {\n thinkingConfig.thinkingBudget = options.thinking.budgetTokens;\n }\n config.thinkingConfig = thinkingConfig;\n }\n else if (model.reasoning && options.thinking && !options.thinking.enabled) {\n config.thinkingConfig = getDisabledThinkingConfig(model);\n }\n if (options.signal) {\n if (options.signal.aborted) {\n throw new Error(\"Request aborted\");\n }\n config.abortSignal = options.signal;\n }\n const params = {\n model: model.id,\n contents,\n config,\n };\n return params;\n}\nfunction isGemma4Model(model) {\n return /gemma-?4/.test(model.id.toLowerCase());\n}\nfunction isGemini3ProModel(model) {\n return /gemini-3(?:\\.\\d+)?-pro/.test(model.id.toLowerCase());\n}\nfunction isGemini3FlashModel(model) {\n const id = model.id.toLowerCase();\n return /gemini-3(?:\\.\\d+)?-flash/.test(id) || id === \"gemini-flash-latest\" || id === \"gemini-flash-lite-latest\";\n}\nfunction getDisabledThinkingConfig(model) {\n // Google docs: Gemini 3.1 Pro cannot disable thinking, and Gemini 3 Flash / Flash-Lite\n // do not support full thinking-off either. For Gemini 3 models, use the lowest supported\n // thinkingLevel without includeThoughts so hidden thinking remains invisible to pi.\n if (isGemini3ProModel(model)) {\n return { thinkingLevel: \"LOW\" };\n }\n if (isGemini3FlashModel(model)) {\n return { thinkingLevel: \"MINIMAL\" };\n }\n if (isGemma4Model(model)) {\n return { thinkingLevel: \"MINIMAL\" };\n }\n // Gemini 2.x supports disabling via thinkingBudget = 0.\n return { thinkingBudget: 0 };\n}\nfunction getThinkingLevel(effort, model) {\n if (isGemini3ProModel(model)) {\n switch (effort) {\n case \"minimal\":\n case \"low\":\n return \"LOW\";\n case \"medium\":\n case \"high\":\n return \"HIGH\";\n }\n }\n if (isGemma4Model(model)) {\n switch (effort) {\n case \"minimal\":\n case \"low\":\n return \"MINIMAL\";\n case \"medium\":\n case \"high\":\n return \"HIGH\";\n }\n }\n switch (effort) {\n case \"minimal\":\n return \"MINIMAL\";\n case \"low\":\n return \"LOW\";\n case \"medium\":\n return \"MEDIUM\";\n case \"high\":\n return \"HIGH\";\n }\n}\nfunction getGoogleBudget(model, effort, customBudgets) {\n if (customBudgets?.[effort] !== undefined) {\n return customBudgets[effort];\n }\n if (model.id.includes(\"2.5-pro\")) {\n const budgets = {\n minimal: 128,\n low: 2048,\n medium: 8192,\n high: 32768,\n };\n return budgets[effort];\n }\n if (model.id.includes(\"2.5-flash-lite\")) {\n const budgets = {\n minimal: 512,\n low: 2048,\n medium: 8192,\n high: 24576,\n };\n return budgets[effort];\n }\n if (model.id.includes(\"2.5-flash\")) {\n const budgets = {\n minimal: 128,\n low: 2048,\n medium: 8192,\n high: 24576,\n };\n return budgets[effort];\n }\n return -1;\n}\n//# sourceMappingURL=google-generative-ai.js.map"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;AASA,IAAI,kBAAkB;AACtB,MAAa,UAAU,OAAO,SAAS,YAAY;CAC/C,MAAM,SAAS,IAAI,4BAA4B;CAC/C,CAAC,YAAY;EACT,MAAM,SAAS;GACX,MAAM;GACN,SAAS,CAAC;GACV,KAAK;GACL,UAAU,MAAM;GAChB,OAAO,MAAM;GACb,OAAO;IACH,OAAO;IACP,QAAQ;IACR,WAAW;IACX,YAAY;IACZ,aAAa;IACb,MAAM;KAAE,OAAO;KAAG,QAAQ;KAAG,WAAW;KAAG,YAAY;KAAG,OAAO;IAAE;GACvE;GACA,YAAY;GACZ,WAAW,KAAK,IAAI;EACxB;EACA,IAAI;GACA,IAAI,SAAS,SAAS,QAAQ,UAAU,WAAW,OAC/C,MAAM,IAAI,MAAM,mEAAmE;GAEvF,MAAM,SAAS,SAAS;GACxB,IAAI,CAAC,QACD,MAAM,IAAI,MAAM,4BAA4B,MAAM,UAAU;GAEhE,MAAM,SAAS,aAAa,OAAO,QAAQ,SAAS,OAAO;GAC3D,IAAI,SAAS,YAAY,OAAO,SAAS,OAAO;GAChD,MAAM,aAAa,MAAM,SAAS,YAAY,QAAQ,KAAK;GAC3D,IAAI,eAAe,KAAA,GACf,SAAS;GAEb,MAAM,eAAe,MAAM,yBAAyB,OAAO,OAAO,sBAAsB,MAAM,GAAG,OAAO;GACxG,OAAO,KAAK;IAAE,MAAM;IAAS,SAAS;GAAO,CAAC;GAC9C,IAAI,eAAe;GACnB,MAAM,SAAS,OAAO;GACtB,MAAM,mBAAmB,OAAO,SAAS;GACzC,WAAW,MAAM,SAAS,cAAc;IAGpC,OAAO,eAAe,MA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E,eAAe,MAAM;CAElC,IAAI,oBAAoB,KAAK,GACzB,OAAO,EAAE,eAAe,UAAU;CAEtC,IAAI,cAAc,KAAK,GACnB,OAAO,EAAE,eAAe,UAAU;CAGtC,OAAO,EAAE,gBAAgB,EAAE;AAC/B;AACA,SAAS,iBAAiB,QAAQ,OAAO;CACrC,IAAI,kBAAkB,KAAK,GACvB,QAAQ,QAAR;EACI,KAAK;EACL,KAAK,OACD,OAAO;EACX,KAAK;EACL,KAAK,QACD,OAAO;CACf;CAEJ,IAAI,cAAc,KAAK,GACnB,QAAQ,QAAR;EACI,KAAK;EACL,KAAK,OACD,OAAO;EACX,KAAK;EACL,KAAK,QACD,OAAO;CACf;CAEJ,QAAQ,QAAR;EACI,KAAK,WACD,OAAO;EACX,KAAK,OACD,OAAO;EACX,KAAK,UACD,OAAO;EACX,KAAK,QACD,OAAO;CACf;AACJ;AACA,SAAS,gBAAgB,OAAO,QAAQ,eAAe;CACnD,IAAI,gBAAgB,YAAY,KAAA,GAC5B,OAAO,cAAc;CAEzB,IAAI,MAAM,GAAG,SAAS,SAAS,GAO3B,OAAO;EALH,SAAS;EACT,KAAK;EACL,QAAQ;EACR,MAAM;CAEG,EAAE;CAEnB,IAAI,MAAM,GAAG,SAAS,gBAAgB,GAOlC,OAAO;EALH,SAAS;EACT,KAAK;EACL,QAAQ;EACR,MAAM;CAEG,EAAE;CAEnB,IAAI,MAAM,GAAG,SAAS,WAAW,GAO7B,OAAO;EALH,SAAS;EACT,KAAK;EACL,QAAQ;EACR,MAAM;CAEG,EAAE;CAEnB,OAAO;AACX"}
1
+ {"version":3,"file":"google-generative-ai-DT5S8D8y.mjs","names":[],"sources":["../node_modules/.pnpm/@earendil-works+pi-ai@0.84.1_ws@8.21.3_zod@4.4.3/node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.js"],"sourcesContent":["import { GoogleGenAI, } from \"@google/genai\";\nimport { calculateCost, clampThinkingLevel } from \"../models.js\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { providerHeadersToRecord } from \"../utils/headers.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { convertMessages, convertTools, isThinkingPart, mapStopReason, resolveGoogleFunctionCallingMode, retainThoughtSignature, retryGoogleRequest, supportsGoogleStrictToolSampling, } from \"./google-shared.js\";\nimport { buildBaseOptions } from \"./simple-options.js\";\n// Counter for generating unique tool call IDs\nlet toolCallCounter = 0;\nexport const stream = (model, context, options) => {\n const stream = new AssistantMessageEventStream();\n (async () => {\n const output = {\n role: \"assistant\",\n content: [],\n api: \"google-generative-ai\",\n provider: model.provider,\n model: model.id,\n usage: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n },\n stopReason: \"pending\",\n timestamp: Date.now(),\n };\n try {\n if (options?.fetch && options.fetch !== globalThis.fetch) {\n throw new Error(\"Custom fetch is not supported by the Google Generative AI adapter\");\n }\n const apiKey = options?.apiKey;\n if (!apiKey) {\n throw new Error(`No API key for provider: ${model.provider}`);\n }\n const client = createClient(model, apiKey, options?.headers);\n let params = buildParams(model, context, options);\n const nextParams = await options?.onPayload?.(params, model);\n if (nextParams !== undefined) {\n params = nextParams;\n }\n const googleStream = await retryGoogleRequest(() => client.models.generateContentStream(params), options);\n stream.push({ type: \"start\", partial: output });\n let currentBlock = null;\n const blocks = output.content;\n const blockIndex = () => blocks.length - 1;\n for await (const chunk of googleStream) {\n // @google/genai documents GenerateContentResponse.responseId as an output-only field\n // used to identify each response. Keep the first non-empty one from the stream.\n output.responseId ||= chunk.responseId;\n const candidate = chunk.candidates?.[0];\n if (candidate?.content?.parts) {\n for (const part of candidate.content.parts) {\n if (part.text !== undefined) {\n const isThinking = isThinkingPart(part);\n if (!currentBlock ||\n (isThinking && currentBlock.type !== \"thinking\") ||\n (!isThinking && currentBlock.type !== \"text\")) {\n if (currentBlock) {\n if (currentBlock.type === \"text\") {\n stream.push({\n type: \"text_end\",\n contentIndex: blocks.length - 1,\n content: currentBlock.text,\n partial: output,\n });\n }\n else {\n stream.push({\n type: \"thinking_end\",\n contentIndex: blockIndex(),\n content: currentBlock.thinking,\n partial: output,\n });\n }\n }\n if (isThinking) {\n currentBlock = { type: \"thinking\", thinking: \"\", thinkingSignature: undefined };\n output.content.push(currentBlock);\n stream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n }\n else {\n currentBlock = { type: \"text\", text: \"\" };\n output.content.push(currentBlock);\n stream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n }\n }\n if (currentBlock.type === \"thinking\") {\n currentBlock.thinking += part.text;\n currentBlock.thinkingSignature = retainThoughtSignature(currentBlock.thinkingSignature, part.thoughtSignature);\n stream.push({\n type: \"thinking_delta\",\n contentIndex: blockIndex(),\n delta: part.text,\n partial: output,\n });\n }\n else {\n currentBlock.text += part.text;\n currentBlock.textSignature = retainThoughtSignature(currentBlock.textSignature, part.thoughtSignature);\n stream.push({\n type: \"text_delta\",\n contentIndex: blockIndex(),\n delta: part.text,\n partial: output,\n });\n }\n }\n if (part.functionCall) {\n if (currentBlock) {\n if (currentBlock.type === \"text\") {\n stream.push({\n type: \"text_end\",\n contentIndex: blockIndex(),\n content: currentBlock.text,\n partial: output,\n });\n }\n else {\n stream.push({\n type: \"thinking_end\",\n contentIndex: blockIndex(),\n content: currentBlock.thinking,\n partial: output,\n });\n }\n currentBlock = null;\n }\n // Generate unique ID if not provided or if it's a duplicate\n const providedId = part.functionCall.id;\n const needsNewId = !providedId || output.content.some((b) => b.type === \"toolCall\" && b.id === providedId);\n const toolCallId = needsNewId\n ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`\n : providedId;\n const toolCall = {\n type: \"toolCall\",\n id: toolCallId,\n name: part.functionCall.name || \"\",\n arguments: part.functionCall.args ?? {},\n ...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }),\n };\n output.content.push(toolCall);\n stream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n stream.push({\n type: \"toolcall_delta\",\n contentIndex: blockIndex(),\n delta: JSON.stringify(toolCall.arguments),\n partial: output,\n });\n stream.push({ type: \"toolcall_end\", contentIndex: blockIndex(), toolCall, partial: output });\n }\n }\n }\n if (candidate?.finishReason) {\n output.rawStopReason = candidate.finishReason;\n output.stopReason = mapStopReason(candidate.finishReason);\n if (output.content.some((b) => b.type === \"toolCall\")) {\n output.stopReason = \"toolUse\";\n }\n }\n if (chunk.usageMetadata) {\n output.usage = {\n input: (chunk.usageMetadata.promptTokenCount || 0) - (chunk.usageMetadata.cachedContentTokenCount || 0),\n output: (chunk.usageMetadata.candidatesTokenCount || 0) + (chunk.usageMetadata.thoughtsTokenCount || 0),\n cacheRead: chunk.usageMetadata.cachedContentTokenCount || 0,\n cacheWrite: 0,\n reasoning: chunk.usageMetadata.thoughtsTokenCount || 0,\n totalTokens: chunk.usageMetadata.totalTokenCount || 0,\n cost: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n total: 0,\n },\n };\n calculateCost(model, output.usage);\n }\n }\n if (currentBlock) {\n if (currentBlock.type === \"text\") {\n stream.push({\n type: \"text_end\",\n contentIndex: blockIndex(),\n content: currentBlock.text,\n partial: output,\n });\n }\n else {\n stream.push({\n type: \"thinking_end\",\n contentIndex: blockIndex(),\n content: currentBlock.thinking,\n partial: output,\n });\n }\n }\n if (options?.signal?.aborted) {\n throw new Error(\"Request was aborted\");\n }\n if (output.stopReason === \"pending\") {\n throw new Error(\"Google stream ended without a finish reason\");\n }\n if (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n const errorMessage = output.rawStopReason\n ? `Provider stopped with: ${output.rawStopReason}`\n : \"An unknown error occurred\";\n throw new Error(errorMessage);\n }\n stream.push({ type: \"done\", reason: output.stopReason, message: output });\n stream.end();\n }\n catch (error) {\n // Remove internal index property used during streaming\n for (const block of output.content) {\n if (\"index\" in block) {\n delete block.index;\n }\n }\n output.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n output.errorMessage = formatProviderError(normalizeProviderError(error));\n stream.push({ type: \"error\", reason: output.stopReason, error: output });\n stream.end();\n }\n })();\n return stream;\n};\nexport const streamSimple = (model, context, options) => {\n const apiKey = options?.apiKey;\n if (!apiKey) {\n throw new Error(`No API key for provider: ${model.provider}`);\n }\n const base = buildBaseOptions(model, context, options, apiKey);\n if (!options?.reasoning) {\n return stream(model, context, { ...base, thinking: { enabled: false } });\n }\n const clampedReasoning = clampThinkingLevel(model, options.reasoning);\n const effort = (clampedReasoning === \"off\" ? \"high\" : clampedReasoning);\n const googleModel = model;\n if (isGemini3ProModel(googleModel) || isGemini3FlashModel(googleModel) || isGemma4Model(googleModel)) {\n return stream(model, context, {\n ...base,\n thinking: {\n enabled: true,\n level: getThinkingLevel(effort, googleModel),\n },\n });\n }\n return stream(model, context, {\n ...base,\n thinking: {\n enabled: true,\n budgetTokens: getGoogleBudget(googleModel, effort, options.thinkingBudgets),\n },\n });\n};\nfunction createClient(model, apiKey, optionsHeaders) {\n const httpOptions = {};\n if (model.baseUrl) {\n httpOptions.baseUrl = model.baseUrl;\n httpOptions.apiVersion = \"\"; // baseUrl already includes version path, don't append\n }\n const headers = providerHeadersToRecord({ ...model.headers, ...optionsHeaders });\n if (headers) {\n httpOptions.headers = headers;\n }\n return new GoogleGenAI({\n apiKey,\n httpOptions: Object.keys(httpOptions).length > 0 ? httpOptions : undefined,\n });\n}\nfunction buildParams(model, context, options = {}) {\n const contents = convertMessages(model, context);\n const generationConfig = {};\n if (options.temperature !== undefined) {\n generationConfig.temperature = options.temperature;\n }\n if (options.maxTokens !== undefined) {\n generationConfig.maxOutputTokens = options.maxTokens;\n }\n const functionCallingMode = context.tools?.length\n ? resolveGoogleFunctionCallingMode(context.tools, options.toolChoice, supportsGoogleStrictToolSampling(model.id))\n : undefined;\n const config = {\n ...(Object.keys(generationConfig).length > 0 && generationConfig),\n ...(context.systemPrompt && { systemInstruction: sanitizeSurrogates(context.systemPrompt) }),\n ...(context.tools && context.tools.length > 0 && { tools: convertTools(context.tools) }),\n ...(functionCallingMode !== undefined && {\n toolConfig: { functionCallingConfig: { mode: functionCallingMode } },\n }),\n };\n if (options.thinking?.enabled && model.reasoning) {\n const thinkingConfig = { includeThoughts: true };\n if (options.thinking.level !== undefined) {\n // Cast to any since our GoogleThinkingLevel mirrors Google's ThinkingLevel enum values\n thinkingConfig.thinkingLevel = options.thinking.level;\n }\n else if (options.thinking.budgetTokens !== undefined) {\n thinkingConfig.thinkingBudget = options.thinking.budgetTokens;\n }\n config.thinkingConfig = thinkingConfig;\n }\n else if (model.reasoning && options.thinking && !options.thinking.enabled) {\n config.thinkingConfig = getDisabledThinkingConfig(model);\n }\n if (options.signal) {\n if (options.signal.aborted) {\n throw new Error(\"Request aborted\");\n }\n config.abortSignal = options.signal;\n }\n const params = {\n model: model.id,\n contents,\n config,\n };\n return params;\n}\nfunction isGemma4Model(model) {\n return /gemma-?4/.test(model.id.toLowerCase());\n}\nfunction isGemini3ProModel(model) {\n return /gemini-3(?:\\.\\d+)?-pro/.test(model.id.toLowerCase());\n}\nfunction isGemini3FlashModel(model) {\n const id = model.id.toLowerCase();\n return /gemini-3(?:\\.\\d+)?-flash/.test(id) || id === \"gemini-flash-latest\" || id === \"gemini-flash-lite-latest\";\n}\nfunction getDisabledThinkingConfig(model) {\n // Google docs: Gemini 3.1 Pro cannot disable thinking, and Gemini 3 Flash / Flash-Lite\n // do not support full thinking-off either. For Gemini 3 models, use the lowest supported\n // thinkingLevel without includeThoughts so hidden thinking remains invisible to pi.\n if (isGemini3ProModel(model)) {\n return { thinkingLevel: \"LOW\" };\n }\n if (isGemini3FlashModel(model)) {\n return { thinkingLevel: \"MINIMAL\" };\n }\n if (isGemma4Model(model)) {\n return { thinkingLevel: \"MINIMAL\" };\n }\n // Gemini 2.x supports disabling via thinkingBudget = 0.\n return { thinkingBudget: 0 };\n}\nfunction getThinkingLevel(effort, model) {\n if (isGemini3ProModel(model)) {\n switch (effort) {\n case \"minimal\":\n case \"low\":\n return \"LOW\";\n case \"medium\":\n case \"high\":\n return \"HIGH\";\n }\n }\n if (isGemma4Model(model)) {\n switch (effort) {\n case \"minimal\":\n case \"low\":\n return \"MINIMAL\";\n case \"medium\":\n case \"high\":\n return \"HIGH\";\n }\n }\n switch (effort) {\n case \"minimal\":\n return \"MINIMAL\";\n case \"low\":\n return \"LOW\";\n case \"medium\":\n return \"MEDIUM\";\n case \"high\":\n return \"HIGH\";\n }\n}\nfunction getGoogleBudget(model, effort, customBudgets) {\n if (customBudgets?.[effort] !== undefined) {\n return customBudgets[effort];\n }\n if (model.id.includes(\"2.5-pro\")) {\n const budgets = {\n minimal: 128,\n low: 2048,\n medium: 8192,\n high: 32768,\n };\n return budgets[effort];\n }\n if (model.id.includes(\"2.5-flash-lite\")) {\n const budgets = {\n minimal: 512,\n low: 2048,\n medium: 8192,\n high: 24576,\n };\n return budgets[effort];\n }\n if (model.id.includes(\"2.5-flash\")) {\n const budgets = {\n minimal: 128,\n low: 2048,\n medium: 8192,\n high: 24576,\n };\n return budgets[effort];\n }\n return -1;\n}\n//# sourceMappingURL=google-generative-ai.js.map"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;AASA,IAAI,kBAAkB;AACtB,MAAa,UAAU,OAAO,SAAS,YAAY;CAC/C,MAAM,SAAS,IAAI,4BAA4B;CAC/C,CAAC,YAAY;EACT,MAAM,SAAS;GACX,MAAM;GACN,SAAS,CAAC;GACV,KAAK;GACL,UAAU,MAAM;GAChB,OAAO,MAAM;GACb,OAAO;IACH,OAAO;IACP,QAAQ;IACR,WAAW;IACX,YAAY;IACZ,aAAa;IACb,MAAM;KAAE,OAAO;KAAG,QAAQ;KAAG,WAAW;KAAG,YAAY;KAAG,OAAO;IAAE;GACvE;GACA,YAAY;GACZ,WAAW,KAAK,IAAI;EACxB;EACA,IAAI;GACA,IAAI,S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,MAAM,GAAG,SAAS,SAAS,GAO3B,OAAO;EALH,SAAS;EACT,KAAK;EACL,QAAQ;EACR,MAAM;CAEG,EAAE;CAEnB,IAAI,MAAM,GAAG,SAAS,gBAAgB,GAOlC,OAAO;EALH,SAAS;EACT,KAAK;EACL,QAAQ;EACR,MAAM;CAEG,EAAE;CAEnB,IAAI,MAAM,GAAG,SAAS,WAAW,GAO7B,OAAO;EALH,SAAS;EACT,KAAK;EACL,QAAQ;EACR,MAAM;CAEG,EAAE;CAEnB,OAAO;AACX"}
@@ -1,5 +1,5 @@
1
1
 
2
- import { a as __toESM, i as __require, t as __commonJSMin } from "./rolldown-runtime-CTfmNlz1.mjs";
2
+ import { G as __require, H as __commonJSMin, K as __toESM } from "./pi-ai-B_88Wb0r.mjs";
3
3
  import { t as retryProviderRequest } from "./provider-retry-Cw6YJ4cr.mjs";
4
4
  import { t as sanitizeSurrogates } from "./sanitize-unicode-wLA11KvZ.mjs";
5
5
  import { d as resolveJsonSchemaStrictSampling, t as transformMessages } from "./transform-messages-DGq9mvhA.mjs";
@@ -1089,12 +1089,12 @@ var require_gaxios = /* @__PURE__ */ __commonJSMin(((exports) => {
1089
1089
  * @returns A proxy agent
1090
1090
  */
1091
1091
  static async #getProxyAgent() {
1092
- this.#proxyAgent ||= (await import("./dist-QBBA-dL_.mjs").then((m) => /* @__PURE__ */ __toESM(m.default))).HttpsProxyAgent;
1092
+ this.#proxyAgent ||= (await import("./dist-BYA74yh_.mjs").then((m) => /* @__PURE__ */ __toESM(m.default))).HttpsProxyAgent;
1093
1093
  return this.#proxyAgent;
1094
1094
  }
1095
1095
  static async #getFetch() {
1096
1096
  const hasWindow = typeof window !== "undefined" && !!window;
1097
- this.#fetch ||= hasWindow ? window.fetch : (await import("./src-C3WBfOks.mjs")).default;
1097
+ this.#fetch ||= hasWindow ? window.fetch : (await import("./src-BEl3QrGL.mjs")).default;
1098
1098
  return this.#fetch;
1099
1099
  }
1100
1100
  /**
@@ -29039,4 +29039,4 @@ function retryGoogleRequest(request, options) {
29039
29039
  //#endregion
29040
29040
  export { resolveGoogleFunctionCallingMode as a, supportsGoogleStrictToolSampling as c, ThinkingLevel as d, mapStopReason as i, GoogleGenAI as l, convertTools as n, retainThoughtSignature as o, isThinkingPart as r, retryGoogleRequest as s, convertMessages as t, ResourceScope as u };
29041
29041
 
29042
- //# sourceMappingURL=google-shared-CRsAUItF.mjs.map
29042
+ //# sourceMappingURL=google-shared-DYP_9cnK.mjs.map