@openclaw/ai 2026.11.3 → 2026.11.5-beta.2

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 (140) hide show
  1. package/README.md +11 -8
  2. package/dist/.source-module-urls/fe058cc430242ce2ab0dfbcbe153e240a52cf9c3072c3dc0a73e5f956b6ba49b.json +1 -0
  3. package/dist/anthropic-DEKgalVg.mjs +182 -0
  4. package/dist/{anthropic-payload-policy-C0ki72BT.d.mts → anthropic-payload-policy-CXCJ5Pmj.d.mts} +21 -4
  5. package/dist/{anthropic-stream-reducer-yWDb5Cct.mjs → anthropic-stream-lifecycle-DF2qVvg1.mjs} +845 -649
  6. package/dist/{anthropic-tool-projection-C2-d1eZ3.d.mts → anthropic-tool-projection-D5DyrL6C.d.mts} +6 -7
  7. package/dist/{anthropic-tool-projection-DZOKfAmL.mjs → anthropic-tool-projection-dGRfr4iT.mjs} +22 -32
  8. package/dist/{api-registry-gDt0faai.d.mts → api-registry-DY2MLUyg.d.mts} +2 -2
  9. package/dist/assistant-output-CD4kY9gu.mjs +16 -0
  10. package/dist/{azure-openai-responses-BvvXzZbi.mjs → azure-openai-responses-DbQV5RTx.mjs} +47 -53
  11. package/dist/{cloudflare-Dttf8jKq.mjs → cloudflare-BJ2_Xabx.mjs} +1 -1
  12. package/dist/{credential-redaction-XvsPf7Yi.d.mts → credential-redaction-DrgndwTJ.d.mts} +5 -3
  13. package/dist/{deferred-event-buffer-DAvyP7qA.mjs → deferred-event-buffer-tIGkTkTm.mjs} +1 -2
  14. package/dist/{diagnostics-v7oVEW59.mjs → diagnostics-CloVGQiK.mjs} +27 -20
  15. package/dist/{diagnostics-DzrF1h4J.mjs → diagnostics-o1PrVNQb.mjs} +11 -4
  16. package/dist/diagnostics.d.mts +6 -7
  17. package/dist/diagnostics.mjs +4 -4
  18. package/dist/{env-api-keys-Xd8dm_aV.mjs → env-api-keys-BuHc86ya.mjs} +1 -26
  19. package/dist/event-stream-B4ZcSvsu.d.mts +1 -0
  20. package/dist/{event-stream-CzpE1g_o.d.mts → event-stream-BYmtRe8-.d.mts} +1 -1
  21. package/dist/event-stream.d.mts +2 -2
  22. package/dist/event-stream.mjs +1 -2
  23. package/dist/expect-lbe3Hgrh.mjs +8 -0
  24. package/dist/{github-copilot-request-facts-F-EmvkpW.mjs → github-copilot-request-facts-BZ_EMo7X.mjs} +1 -1
  25. package/dist/{google-Cpi_cLKZ.mjs → google-B1g82bn4.mjs} +7 -8
  26. package/dist/{google-interactions-CGINbsjO.mjs → google-interactions-Ckr0Z99Z.mjs} +243 -269
  27. package/dist/{google-messages-DQMgG5yG.mjs → google-messages-A-9d3y5V.mjs} +52 -18
  28. package/dist/{google-provider-stream-BHd0cST9.mjs → google-provider-stream-CNVh4gpm.mjs} +19 -11
  29. package/dist/{google-shared-vtag8bj5.mjs → google-shared-WNM86ZcW.mjs} +72 -42
  30. package/dist/{google-vertex-eKoUnW7N.mjs → google-vertex-CXjleC6g.mjs} +3 -3
  31. package/dist/{google-video-slots-D8tPH8wX.mjs → google-video-slots-Bxt-OXO8.mjs} +1 -1
  32. package/dist/{host-CWt55nnF.mjs → host-DX7ORpeH.mjs} +46 -39
  33. package/dist/{host-jJOffdlW.d.mts → host-ccbwPC3A.d.mts} +17 -9
  34. package/dist/{host-policy-Dm7PM6AD.mjs → host-policy-jCZebuXx.mjs} +2 -2
  35. package/dist/index-Bczt0MnO.d.mts +17 -0
  36. package/dist/index.d.mts +8 -7
  37. package/dist/index.mjs +9 -7
  38. package/dist/internal/anthropic.d.mts +21 -26
  39. package/dist/internal/anthropic.mjs +6 -6
  40. package/dist/internal/google-model-family.mjs +1 -1
  41. package/dist/internal/google.d.mts +15 -0
  42. package/dist/internal/google.mjs +1 -0
  43. package/dist/internal/model-request-body.d.mts +37 -0
  44. package/dist/internal/model-request-body.mjs +106 -0
  45. package/dist/internal/openai-completions-compat.d.mts +1 -1
  46. package/dist/internal/openai-completions-compat.mjs +1 -1
  47. package/dist/internal/openai-responses-payload-policy.d.mts +2 -2
  48. package/dist/internal/openai-responses-payload-policy.mjs +2 -2
  49. package/dist/internal/openai.d.mts +14 -12
  50. package/dist/internal/openai.mjs +11 -10
  51. package/dist/internal/reasoning-tag-text-partitioner.d.mts +26 -0
  52. package/dist/{reasoning-tag-text-partitioner-CU9A4Lg8.mjs → internal/reasoning-tag-text-partitioner.mjs} +313 -111
  53. package/dist/internal/retry-after.d.mts +2 -2
  54. package/dist/internal/retry-after.mjs +96 -32
  55. package/dist/internal/runtime.d.mts +15 -41
  56. package/dist/internal/runtime.mjs +9 -10
  57. package/dist/internal/shared.d.mts +21 -25
  58. package/dist/internal/shared.mjs +9 -98
  59. package/dist/internal/tool-schema.d.mts +10 -10
  60. package/dist/internal/tool-schema.mjs +4 -4
  61. package/dist/{llm-request-activity-CfMuh5cC.mjs → llm-request-activity-DzaHoRAU.mjs} +2 -2
  62. package/dist/mistral-CjHkvsqR.mjs +3741 -0
  63. package/dist/{openai.LICENSE → mistral.LICENSE} +1 -1
  64. package/dist/{model-transport-url-BrsjjdjR.d.mts → model-transport-url-BdksnBqu.d.mts} +6 -8
  65. package/dist/{number-coercion-37gmNkuA.mjs → number-coercion-C7HsBgUL.mjs} +7 -2
  66. package/dist/observe-async-iterator-AlARO5wS.d.mts +178 -0
  67. package/dist/observe-async-iterator-DgmegcZR.mjs +181 -0
  68. package/dist/{openai-chatgpt-responses-BZa3SySh.mjs → openai-chatgpt-responses-CwS5JP7A.mjs} +61 -80
  69. package/dist/{openai-completions-compat-CBvb2eld.d.mts → openai-completions-compat-CJ-NsDzg.d.mts} +12 -6
  70. package/dist/{openai-completions-compat-bNQXF1y9.mjs → openai-completions-compat-CstlTQuF.mjs} +74 -50
  71. package/dist/{openai-completions-CCZ_UHCk.mjs → openai-completions-sj4S-RXQ.mjs} +5 -5
  72. package/dist/openai-completions-transport-BDAIA0_P.mjs +3406 -0
  73. package/dist/{openai-prompt-cache-DgjD-UL5.d.mts → openai-prompt-cache-BZGaIWYh.d.mts} +4 -4
  74. package/dist/{openai-prompt-cache-B9AvdoEo.mjs → openai-prompt-cache-CgDoFhO0.mjs} +5 -4
  75. package/dist/{openai-responses-compaction-replay-_sUXtcwU.d.mts → openai-responses-compaction-replay-CNHk6k53.d.mts} +4 -4
  76. package/dist/{openai-responses-contracts-B1nkeLL6.d.mts → openai-responses-contracts-BXMcvO7F.d.mts} +4 -10
  77. package/dist/{openai-responses-contracts-B5mGAbR6.mjs → openai-responses-contracts-xU-n9AJJ.mjs} +36 -37
  78. package/dist/{openai-responses-endpoint-CfKR6N5f.mjs → openai-responses-endpoint-DCkURKS0.mjs} +55 -8
  79. package/dist/openai-responses-ev_c6oTy.mjs +89 -0
  80. package/dist/{openai-responses-payload-policy-BzM52TTH.d.mts → openai-responses-payload-policy-DyE30gdD.d.mts} +7 -7
  81. package/dist/{openai-responses-request-lifecycle-CTqHc02t.mjs → openai-responses-request-lifecycle-BuOs0mwI.mjs} +12 -26
  82. package/dist/{openai-responses-shared-wx9v1MCn.mjs → openai-responses-shared-BmRQnUPP.mjs} +633 -1493
  83. package/dist/{openai-responses-terminal-usage-CpVjkqn-.d.mts → openai-responses-terminal-usage-D7IhRA6i.d.mts} +9 -3
  84. package/dist/{openai-tool-schema-BTEU2xmN.mjs → openai-tool-schema-CsoYgnWy.mjs} +97 -122
  85. package/dist/otel-Buswj0Mf.mjs +766 -0
  86. package/dist/{overflow-OF3PgPbw.mjs → overflow-CpApyjG2.mjs} +1 -1
  87. package/dist/{positive-integer-Bb4Evc7L.mjs → positive-integer-DiqE5vNi.mjs} +2 -3
  88. package/dist/{prompt-cache-stability-D_MeCQFI.mjs → prompt-cache-stability-w-ICeyOI.mjs} +1 -1
  89. package/dist/{provider-error-qtZD2inE.mjs → provider-error-DD-fo4Rz.mjs} +71 -234
  90. package/dist/{provider-options-DAzsyi49.d.mts → provider-options-Mo8NM5d1.d.mts} +16 -5
  91. package/dist/{provider-replay-context-4vxI7p4V.mjs → provider-replay-context-xyU7-CiT.mjs} +2 -2
  92. package/dist/provider-transcript-transform-DtaxNcC1.mjs +32 -0
  93. package/dist/{provider-transport-turn-state-D_GjPJHe.mjs → provider-transport-turn-state-BIS8maBK.mjs} +4 -4
  94. package/dist/{provider-types-CWl4VXvE.d.mts → provider-types-B1e98js5.d.mts} +3 -3
  95. package/dist/provider-types.d.mts +7 -6
  96. package/dist/providers.d.mts +2 -2
  97. package/dist/providers.mjs +26 -29
  98. package/dist/{record-coerce-CNDovvft.mjs → record-coerce-BQaoiN3r.mjs} +4 -1
  99. package/dist/request-headers-DO4Mqhw1.mjs +10 -0
  100. package/dist/{required-api-key-D088S4Cd.mjs → required-api-key-2zZTkmsi.mjs} +1 -1
  101. package/dist/{retry-after-BrmTv0jL.d.mts → retry-after-DnHBlFS2.d.mts} +21 -1
  102. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  103. package/dist/{sanitize-unicode-ZqVLLEKC.d.mts → sanitize-unicode-BISmUlUv.d.mts} +2 -2
  104. package/dist/{simple-options-xJkqrG_E.mjs → simple-options-tLSeECry.mjs} +108 -82
  105. package/dist/src-BUsVkrNt.mjs +105 -0
  106. package/dist/{src-CyA0zJnt.mjs → src-CQ7nH2mL.mjs} +4 -7
  107. package/dist/stable-stringify-CchQEmeA.mjs +84 -0
  108. package/dist/{stream-C4YDqhFj.mjs → stream-DrtAWu7c.mjs} +2 -6
  109. package/dist/{stream-first-event-timeout-D_TfJHRJ.mjs → stream-first-event-timeout-B7RcufAV.mjs} +16 -13
  110. package/dist/{string-coerce-Cj8sqWHx.mjs → string-coerce-BCuWMIrk.mjs} +1 -1
  111. package/dist/string-normalization-B8TDDBX_.mjs +32 -0
  112. package/dist/telemetry-CvK1yQg7.mjs +582 -0
  113. package/dist/{tool-schema-json-projection-B1sTYwfH.mjs → tool-schema-json-projection-BQpiJlXJ.mjs} +53 -69
  114. package/dist/{transport-stream-shared-lhgkTOz3.mjs → transport-stream-shared-D2uFMhMc.mjs} +177 -93
  115. package/dist/{transport-stream-shared-8ru8eX4s.d.mts → transport-stream-shared-D3IAU4jn.d.mts} +29 -15
  116. package/dist/{transport-utils-DwOpuTjL.mjs → transport-utils-Da_39MYi.mjs} +23 -38
  117. package/dist/transports.d.mts +42 -39
  118. package/dist/transports.mjs +215 -296
  119. package/dist/{types-CVYzKrMl.d.mts → types-BVdTf0YV.d.mts} +38 -3
  120. package/dist/types-Cb3-5WM9.d.mts +1 -0
  121. package/dist/{types-BXd0kI8-.mjs → types-OVEWUaDh.mjs} +3 -1
  122. package/dist/types.d.mts +7 -6
  123. package/dist/types.mjs +7 -5
  124. package/dist/{validation-9FSkE8T-.mjs → validation-DGXqfvkj.mjs} +45 -27
  125. package/dist/{validation-BQ5u20Ru.d.mts → validation-QmyD0E5A.d.mts} +1 -1
  126. package/dist/validation.d.mts +1 -1
  127. package/dist/validation.mjs +1 -2
  128. package/package.json +40 -6
  129. package/dist/anthropic-lueA8LUg.mjs +0 -221
  130. package/dist/assistant-output-BnQm3fov.mjs +0 -47
  131. package/dist/event-stream-CDpFza-M.d.mts +0 -1
  132. package/dist/index-DSprYWaz.d.mts +0 -185
  133. package/dist/mistral-CQ7aoWg2.mjs +0 -512
  134. package/dist/model-request-body-BD5vy4rP.d.mts +0 -17
  135. package/dist/openai-CiRi-nVE.mjs +0 -20077
  136. package/dist/openai-completions-transport-DFvSBbUT.mjs +0 -10881
  137. package/dist/openai-responses-DQsZKUoI.mjs +0 -87
  138. package/dist/rolldown-runtime-B4iAMlE-.mjs +0 -35
  139. package/dist/types-CBJthzJX.d.mts +0 -1
  140. package/dist/ws.LICENSE +0 -20
@@ -1,37 +1,36 @@
1
+ import "./src-CQ7nH2mL.mjs";
2
+ import { t as omitNullRequestHeaders } from "./request-headers-DO4Mqhw1.mjs";
1
3
  import { t as AssistantMessageEventStream } from "./event-stream-X2gmsUWv.mjs";
2
- import { a as asRecord, i as asOptionalRecord, s as readStringField } from "./record-coerce-CNDovvft.mjs";
3
- import { O as calculateCost, a as resolveAiTransportHeaderSentinels, r as getAiTransportHost } from "./host-CWt55nnF.mjs";
4
- import { s as streamFragmentError } from "./transport-utils-DwOpuTjL.mjs";
5
- import { t as buildGuardedModelFetch } from "./host-policy-Dm7PM6AD.mjs";
4
+ import { a as asRecord, c as readStringField, i as asOptionalRecord } from "./record-coerce-BQaoiN3r.mjs";
5
+ import { O as calculateCost, a as resolveAiTransportHeaderSentinels, r as getAiTransportHost } from "./host-DX7ORpeH.mjs";
6
+ import { a as streamFragmentError } from "./transport-utils-Da_39MYi.mjs";
7
+ import { t as buildGuardedModelFetch } from "./host-policy-jCZebuXx.mjs";
6
8
  import { t as sanitizeSurrogates } from "./sanitize-unicode-CRGuMONI.mjs";
7
- import { n as buildBaseOptions, w as stripSystemPromptCacheBoundary } from "./simple-options-xJkqrG_E.mjs";
8
- import { b as transportAbortError, c as failTransportStream, f as mergeTransportHeaders, g as parseTerminalToolCallArguments, h as notifyProviderStreamOpened, m as notifyProviderHttpResponse, w as parseJsonPreservingUnsafeIntegers } from "./transport-stream-shared-lhgkTOz3.mjs";
9
- import { n as getEnvApiKey } from "./env-api-keys-Xd8dm_aV.mjs";
10
- import { n as transformProviderMessages, t as createAssistantOutput } from "./assistant-output-BnQm3fov.mjs";
11
- import { n as createGoogleVideoPlaceholder, r as materializeGoogleVideoSlots, t as GOOGLE_VIDEO_SLOT_OMISSION } from "./google-video-slots-D8tPH8wX.mjs";
12
- import { PROVIDER_CONTEXT_HANDOFF, PROVIDER_MODEL_INPUT, resolveProviderContext } from "./provider-types.mjs";
13
- import { n as buildGoogleInteractionsSimpleThinking } from "./google-shared-vtag8bj5.mjs";
9
+ import { C as stripSystemPromptCacheBoundary, n as buildBaseOptions } from "./simple-options-tLSeECry.mjs";
10
+ import { T as parseJsonPreservingUnsafeIntegers, _ as parseTerminalToolCallArguments, c as failTransportStream, f as iterateSseFrames, g as notifyProviderStreamOpened, h as notifyProviderHttpResponse, x as transportAbortError } from "./transport-stream-shared-D2uFMhMc.mjs";
11
+ import { n as getEnvApiKey } from "./env-api-keys-BuHc86ya.mjs";
12
+ import { t as transformProviderMessages } from "./provider-transcript-transform-DtaxNcC1.mjs";
13
+ import { PROVIDER_MODEL_INPUT, resolveProviderContext } from "./provider-types.mjs";
14
+ import { t as createAssistantOutput } from "./assistant-output-CD4kY9gu.mjs";
15
+ import { a as googleToolParameters, o as mapGoogleToolArguments } from "./google-messages-A-9d3y5V.mjs";
16
+ import { n as createGoogleVideoPlaceholder, r as materializeGoogleVideoSlots, t as GOOGLE_VIDEO_SLOT_OMISSION } from "./google-video-slots-Bxt-OXO8.mjs";
17
+ import { r as buildGoogleInteractionsSimpleThinking } from "./google-shared-WNM86ZcW.mjs";
14
18
  //#region packages/ai/package.json
15
- var version = "2026.11.3";
19
+ var version = "2026.11.5-beta.2";
16
20
  //#endregion
17
21
  //#region packages/ai/src/providers/google-interactions-request.ts
18
- const DEFAULT_GOOGLE_API_BASE_URL = "https://generativelanguage.googleapis.com";
19
22
  let packageVersionMemo;
20
- function resolvePackageVersion() {
21
- if (!packageVersionMemo) packageVersionMemo = typeof process !== "undefined" && process.env?.OPENCLAW_VERSION || version;
22
- return packageVersionMemo;
23
- }
24
23
  function resolveGoogleApiClientHeaders(params) {
25
24
  const hostHeaders = getAiTransportHost().resolveProviderRequestHeaders({
26
25
  provider: "google",
27
- api: params?.api ?? params?.model?.api ?? "google-generative-ai",
28
- baseUrl: params?.baseUrl ?? DEFAULT_GOOGLE_API_BASE_URL,
29
- model: params?.model
26
+ api: "google-generative-ai",
27
+ baseUrl: params.baseUrl,
28
+ model: params.model
30
29
  });
31
30
  if (hostHeaders?.["x-goog-api-client"]) return hostHeaders;
32
31
  return {
33
32
  ...hostHeaders,
34
- "x-goog-api-client": `openclaw/${resolvePackageVersion()}`
33
+ "x-goog-api-client": `openclaw/${packageVersionMemo ||= typeof process !== "undefined" && process.env?.OPENCLAW_VERSION || version}`
35
34
  };
36
35
  }
37
36
  function convertMessages(model, context, videoSlots) {
@@ -124,7 +123,7 @@ function convertMessages(model, context, videoSlots) {
124
123
  type: "function_call",
125
124
  id: block.id,
126
125
  name: block.name,
127
- arguments: block.arguments
126
+ arguments: mapGoogleToolArguments(context.tools, block.name, block.arguments, "encode")
128
127
  });
129
128
  }
130
129
  flushText();
@@ -157,7 +156,7 @@ function buildGoogleInteractionsParams(model, context, options = {}, videoSlots)
157
156
  type: "function",
158
157
  name: tool.name,
159
158
  description: tool.description || "",
160
- parameters: asRecord(tool.parameters)
159
+ parameters: googleToolParameters(tool.parameters)
161
160
  }));
162
161
  return {
163
162
  model: model.id,
@@ -173,11 +172,12 @@ function buildGoogleInteractionsParams(model, context, options = {}, videoSlots)
173
172
  };
174
173
  }
175
174
  //#endregion
176
- //#region packages/ai/src/providers/google-interactions-shared.ts
175
+ //#region packages/ai/src/providers/google-interactions.ts
177
176
  /**
178
177
  * Gemini Interactions API adapter and lifecycle for OpenClaw.
179
178
  * POST /v1beta/interactions
180
179
  */
180
+ let toolCallCounter = 0;
181
181
  function resolveGoogleInteractionsApiKey(model, options) {
182
182
  return options?.apiKey || getEnvApiKey(model.provider) || process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY || "";
183
183
  }
@@ -195,217 +195,205 @@ function isGoogleInteractionsRequestBody(value) {
195
195
  if (!record) return false;
196
196
  return typeof record.model === "string" && Array.isArray(record.input) && typeof record.store === "boolean" && typeof record.stream === "boolean";
197
197
  }
198
- async function runGoogleInteractionsLifecycle(params) {
199
- const { stream, model, output, options, context, nextToolCallId } = params;
200
- let reader;
201
- try {
202
- const host = getAiTransportHost();
203
- const unresolvedApiKey = resolveGoogleInteractionsApiKey(model, options);
204
- const apiKey = host.resolveSecretSentinel(unresolvedApiKey);
205
- if (!apiKey.trim()) throw new Error(`No API key for provider: ${model.provider}`);
206
- const providerContext = (options?.[PROVIDER_MODEL_INPUT] ?? model.input).includes("video") ? await resolveProviderContext(context, options) : context;
207
- const videoSlots = /* @__PURE__ */ new Map();
208
- let body = buildGoogleInteractionsParams(model, providerContext, options, videoSlots);
209
- const nextBody = await options?.onPayload?.(body, model);
210
- if (nextBody !== void 0) {
211
- if (!isGoogleInteractionsRequestBody(nextBody)) throw new Error("Google Interactions onPayload returned an invalid request body");
212
- body = nextBody;
213
- }
214
- const optionRecord = asRecord(options);
215
- const metadata = asRecord(optionRecord.videoMetadata ?? optionRecord.video_metadata);
216
- const processing = {};
217
- for (const [camel, snake] of [
218
- ["startOffset", "start_offset"],
219
- ["endOffset", "end_offset"],
220
- ["fps", "fps"]
221
- ]) {
222
- const value = metadata[camel] ?? metadata[snake];
223
- if (value !== void 0) processing[snake] = value;
224
- }
225
- materializeGoogleVideoSlots(body, videoSlots, (slot, video) => {
226
- Object.assign(slot, {
227
- type: "video",
228
- mime_type: video.mimeType,
229
- data: video.data,
230
- ...Object.keys(processing).length > 0 ? { processing: {
231
- type: "static",
232
- ...processing
233
- } } : {}
234
- });
235
- }, (part) => {
236
- if (part.type === "video") {
237
- Object.keys(part).forEach((key) => Reflect.deleteProperty(part, key));
238
- Object.assign(part, {
239
- type: "text",
240
- text: GOOGLE_VIDEO_SLOT_OMISSION
241
- });
198
+ const streamGoogleInteractions = (model, context, options) => {
199
+ const stream = new AssistantMessageEventStream();
200
+ const output = createAssistantOutput(model, "google-interactions");
201
+ (async () => {
202
+ let reader;
203
+ try {
204
+ const host = getAiTransportHost();
205
+ const unresolvedApiKey = resolveGoogleInteractionsApiKey(model, options);
206
+ const apiKey = host.resolveSecretSentinel(unresolvedApiKey);
207
+ if (!apiKey.trim()) throw new Error(`No API key for provider: ${model.provider}`);
208
+ const providerContext = (options?.[PROVIDER_MODEL_INPUT] ?? model.input).includes("video") ? await resolveProviderContext(context, options) : context;
209
+ const videoSlots = /* @__PURE__ */ new Map();
210
+ let body = buildGoogleInteractionsParams(model, providerContext, options, videoSlots);
211
+ const nextBody = await options?.onPayload?.(body, model);
212
+ if (nextBody !== void 0) {
213
+ if (!isGoogleInteractionsRequestBody(nextBody)) throw new Error("Google Interactions onPayload returned an invalid request body");
214
+ body = nextBody;
242
215
  }
243
- });
244
- let baseUrl = (model.baseUrl || "https://generativelanguage.googleapis.com/v1beta").trim().replace(/\/+$/, "");
245
- if (/^https:\/\/generativelanguage\.googleapis\.com$/i.test(baseUrl)) baseUrl = "https://generativelanguage.googleapis.com/v1beta";
246
- const url = `${baseUrl}/interactions?alt=sse`;
247
- const googleClientHeaders = resolveGoogleApiClientHeaders({
248
- baseUrl,
249
- api: "google-generative-ai",
250
- model
251
- });
252
- const headers = resolveAiTransportHeaderSentinels(mergeTransportHeaders({
253
- "Content-Type": "application/json",
254
- ...apiKey.trimStart().startsWith("{") && Object.keys({
216
+ const optionRecord = asRecord(options);
217
+ const metadata = asRecord(optionRecord.videoMetadata ?? optionRecord.video_metadata);
218
+ const processing = {};
219
+ for (const [camel, snake] of [
220
+ ["startOffset", "start_offset"],
221
+ ["endOffset", "end_offset"],
222
+ ["fps", "fps"]
223
+ ]) {
224
+ const value = metadata[camel] ?? metadata[snake];
225
+ if (value !== void 0) processing[snake] = value;
226
+ }
227
+ materializeGoogleVideoSlots(body, videoSlots, (slot, video) => {
228
+ Object.assign(slot, {
229
+ type: "video",
230
+ mime_type: video.mimeType,
231
+ data: video.data,
232
+ ...Object.keys(processing).length > 0 ? { processing: {
233
+ type: "static",
234
+ ...processing
235
+ } } : {}
236
+ });
237
+ }, (part) => {
238
+ if (part.type === "video") {
239
+ Object.keys(part).forEach((key) => Reflect.deleteProperty(part, key));
240
+ Object.assign(part, {
241
+ type: "text",
242
+ text: GOOGLE_VIDEO_SLOT_OMISSION
243
+ });
244
+ }
245
+ });
246
+ let baseUrl = (model.baseUrl || "https://generativelanguage.googleapis.com/v1beta").trim().replace(/\/+$/, "");
247
+ if (/^https:\/\/generativelanguage\.googleapis\.com$/i.test(baseUrl)) baseUrl = "https://generativelanguage.googleapis.com/v1beta";
248
+ const url = `${baseUrl}/interactions?alt=sse`;
249
+ const googleClientHeaders = resolveGoogleApiClientHeaders({
250
+ baseUrl,
251
+ model
252
+ });
253
+ const headers = resolveAiTransportHeaderSentinels({
254
+ "Content-Type": "application/json",
255
+ "x-goog-api-key": apiKey,
256
+ "Api-Revision": "2026-05-20",
257
+ ...googleClientHeaders,
255
258
  ...model.headers,
256
259
  ...options?.headers
257
- }).some((name) => name.toLowerCase() === "authorization") ? {} : { "x-goog-api-key": apiKey },
258
- "Api-Revision": "2026-05-20"
259
- }, googleClientHeaders, model.headers, options?.headers)) ?? {
260
- "Content-Type": "application/json",
261
- "x-goog-api-key": apiKey
262
- };
263
- logGoogleInteractionsDebug("request", {
264
- method: "POST",
265
- url,
266
- model: model.id,
267
- inputSteps: body.input.length,
268
- tools: body.tools?.length ?? 0
269
- });
270
- const response = await buildGuardedModelFetch({
271
- ...model,
272
- baseUrl
273
- }, options?.timeoutMs, { sanitizeSse: true })(url, {
274
- method: "POST",
275
- headers,
276
- body: JSON.stringify(body),
277
- signal: options?.signal
278
- });
279
- await notifyProviderHttpResponse({
280
- options,
281
- response,
282
- model
283
- });
284
- logGoogleInteractionsDebug("response", {
285
- status: response.status,
286
- statusText: response.statusText
287
- });
288
- if (!response.ok) {
289
- const errorText = await response.text();
290
- logGoogleInteractionsDebug("request failed", { status: response.status });
291
- throw new Error(`Google Interactions API error HTTP ${response.status}: ${errorText}`);
292
- }
293
- if (!response.body) throw new Error("Google Interactions API returned empty response body");
294
- reader = response.body.getReader();
295
- await notifyProviderStreamOpened({
296
- options,
297
- cancelStream: () => reader?.cancel()
298
- });
299
- stream.push({
300
- type: "start",
301
- partial: output
302
- });
303
- const decoder = new TextDecoder();
304
- let buffer = "";
305
- let currentBlock = null;
306
- let currentBlockIndex = -1;
307
- let latestThoughtSignature;
308
- let latestUsage;
309
- const endCurrentBlock = () => {
310
- if (!currentBlock) return;
311
- if (currentBlock.type === "toolCall") {
312
- if (currentBlock.partialJson?.trim()) currentBlock.arguments = parseTerminalToolCallArguments(currentBlock.partialJson);
313
- delete currentBlock.partialJson;
260
+ }) ?? {
261
+ "Content-Type": "application/json",
262
+ "x-goog-api-key": apiKey
263
+ };
264
+ logGoogleInteractionsDebug("request", {
265
+ method: "POST",
266
+ url,
267
+ model: model.id,
268
+ inputSteps: body.input.length,
269
+ tools: body.tools?.length ?? 0
270
+ });
271
+ const response = await buildGuardedModelFetch({
272
+ ...model,
273
+ baseUrl
274
+ }, options?.timeoutMs, { sanitizeSse: true })(url, {
275
+ method: "POST",
276
+ headers: omitNullRequestHeaders(headers),
277
+ body: JSON.stringify(body),
278
+ signal: options?.signal
279
+ });
280
+ await notifyProviderHttpResponse({
281
+ options,
282
+ response,
283
+ model
284
+ });
285
+ logGoogleInteractionsDebug("response", {
286
+ status: response.status,
287
+ statusText: response.statusText
288
+ });
289
+ if (!response.ok) {
290
+ const errorText = await response.text();
291
+ logGoogleInteractionsDebug("request failed", { status: response.status });
292
+ throw new Error(`Google Interactions API error HTTP ${response.status}: ${errorText}`);
293
+ }
294
+ if (!response.body) throw new Error("Google Interactions API returned empty response body");
295
+ reader = response.body.getReader();
296
+ await notifyProviderStreamOpened({
297
+ options,
298
+ cancelStream: () => reader?.cancel()
299
+ });
300
+ stream.push({
301
+ type: "start",
302
+ partial: output
303
+ });
304
+ let currentBlock = null;
305
+ let currentBlockIndex = -1;
306
+ let latestThoughtSignature;
307
+ let latestUsage;
308
+ const endCurrentBlock = () => {
309
+ if (!currentBlock) return;
310
+ if (currentBlock.type === "toolCall") {
311
+ if (currentBlock.partialJson?.trim()) currentBlock.arguments = parseTerminalToolCallArguments(currentBlock.partialJson);
312
+ currentBlock.arguments = mapGoogleToolArguments(providerContext.tools, currentBlock.name, currentBlock.arguments, "decode");
313
+ delete currentBlock.partialJson;
314
+ stream.push({
315
+ type: "toolcall_end",
316
+ contentIndex: currentBlockIndex,
317
+ toolCall: currentBlock,
318
+ partial: output
319
+ });
320
+ } else {
321
+ if (currentBlock.type === "thinking") {
322
+ if (!currentBlock.thinkingSignature && latestThoughtSignature) currentBlock.thinkingSignature = latestThoughtSignature;
323
+ latestThoughtSignature = void 0;
324
+ }
325
+ stream.push({
326
+ type: currentBlock.type === "text" ? "text_end" : "thinking_end",
327
+ contentIndex: currentBlockIndex,
328
+ content: currentBlock.type === "text" ? currentBlock.text : currentBlock.thinking,
329
+ partial: output
330
+ });
331
+ }
332
+ currentBlock = null;
333
+ };
334
+ const startTextBlock = (type, text = "") => {
335
+ endCurrentBlock();
336
+ currentBlockIndex = output.content.length;
337
+ const block = type === "text" ? {
338
+ type,
339
+ text
340
+ } : {
341
+ type,
342
+ thinking: text,
343
+ ...latestThoughtSignature ? { thinkingSignature: latestThoughtSignature } : {}
344
+ };
345
+ output.content.push(block);
314
346
  stream.push({
315
- type: "toolcall_end",
347
+ type: type === "text" ? "text_start" : "thinking_start",
316
348
  contentIndex: currentBlockIndex,
317
- toolCall: currentBlock,
318
349
  partial: output
319
350
  });
320
- } else {
321
- if (currentBlock.type === "thinking") {
322
- if (!currentBlock.thinkingSignature && latestThoughtSignature) currentBlock.thinkingSignature = latestThoughtSignature;
323
- latestThoughtSignature = void 0;
324
- }
351
+ if (text) stream.push({
352
+ type: type === "text" ? "text_delta" : "thinking_delta",
353
+ contentIndex: currentBlockIndex,
354
+ delta: text,
355
+ partial: output
356
+ });
357
+ return block;
358
+ };
359
+ const appendTextDelta = (type, text) => {
360
+ if (!text) return;
361
+ const block = currentBlock?.type === type ? currentBlock : startTextBlock(type);
362
+ currentBlock = block;
363
+ if (block.type === "text") block.text += text;
364
+ else block.thinking += text;
325
365
  stream.push({
326
- type: currentBlock.type === "text" ? "text_end" : "thinking_end",
366
+ type: type === "text" ? "text_delta" : "thinking_delta",
327
367
  contentIndex: currentBlockIndex,
328
- content: currentBlock.type === "text" ? currentBlock.text : currentBlock.thinking,
368
+ delta: text,
329
369
  partial: output
330
370
  });
331
- }
332
- currentBlock = null;
333
- };
334
- const startTextBlock = (type, text = "") => {
335
- endCurrentBlock();
336
- currentBlockIndex = output.content.length;
337
- const block = type === "text" ? {
338
- type,
339
- text
340
- } : {
341
- type,
342
- thinking: text,
343
- ...latestThoughtSignature ? { thinkingSignature: latestThoughtSignature } : {}
344
371
  };
345
- output.content.push(block);
346
- stream.push({
347
- type: type === "text" ? "text_start" : "thinking_start",
348
- contentIndex: currentBlockIndex,
349
- partial: output
350
- });
351
- if (text) stream.push({
352
- type: type === "text" ? "text_delta" : "thinking_delta",
353
- contentIndex: currentBlockIndex,
354
- delta: text,
355
- partial: output
356
- });
357
- return block;
358
- };
359
- const appendTextDelta = (type, text) => {
360
- if (!text) return;
361
- const block = currentBlock?.type === type ? currentBlock : startTextBlock(type);
362
- currentBlock = block;
363
- if (block.type === "text") block.text += text;
364
- else block.thinking += text;
365
- stream.push({
366
- type: type === "text" ? "text_delta" : "thinking_delta",
367
- contentIndex: currentBlockIndex,
368
- delta: text,
369
- partial: output
370
- });
371
- };
372
- const startToolCallBlock = (source, args = {}) => {
373
- endCurrentBlock();
374
- currentBlockIndex = output.content.length;
375
- const name = readStringField(source, "name") ?? "tool";
376
- const toolCall = {
377
- type: "toolCall",
378
- id: readStringField(source, "id") ?? nextToolCallId(name),
379
- name,
380
- arguments: args,
381
- partialJson: Object.keys(args).length > 0 ? JSON.stringify(args) : ""
372
+ const startToolCallBlock = (source, args = {}) => {
373
+ endCurrentBlock();
374
+ currentBlockIndex = output.content.length;
375
+ const name = readStringField(source, "name") ?? "tool";
376
+ const toolCall = {
377
+ type: "toolCall",
378
+ id: readStringField(source, "id") ?? `${name}_${Date.now()}_${++toolCallCounter}`,
379
+ name,
380
+ arguments: args,
381
+ partialJson: Object.keys(args).length > 0 ? JSON.stringify(args) : ""
382
+ };
383
+ output.content.push(toolCall);
384
+ stream.push({
385
+ type: "toolcall_start",
386
+ contentIndex: currentBlockIndex,
387
+ partial: output
388
+ });
389
+ return toolCall;
382
390
  };
383
- output.content.push(toolCall);
384
- stream.push({
385
- type: "toolcall_start",
386
- contentIndex: currentBlockIndex,
387
- partial: output
388
- });
389
- return toolCall;
390
- };
391
- let streamDone = false;
392
- let sawCompletion = false;
393
- while (!streamDone) {
394
- const { done, value } = await reader.read();
395
- buffer += decoder.decode(value, { stream: !done });
396
- const frames = buffer.split(/(?:\r\n|\r(?!\n)|\n)(?:\r\n|\r(?!\n)|\n)/);
397
- buffer = frames.pop() ?? "";
398
- if (done) {
399
- if (/[\r\n]$/.test(buffer)) frames.push(buffer);
400
- streamDone = true;
401
- }
402
- for (const frame of frames) {
391
+ let sawCompletion = false;
392
+ for await (const { frame, terminated } of iterateSseFrames(reader.read.bind(reader))) {
393
+ if (!terminated && !/[\r\n]$/.test(frame)) continue;
403
394
  const dataStr = frame.split(/\r\n|\r|\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5)).join("\n").trim();
404
395
  if (!dataStr) continue;
405
- if (dataStr === "[DONE]") {
406
- streamDone = true;
407
- break;
408
- }
396
+ if (dataStr === "[DONE]") break;
409
397
  let event;
410
398
  try {
411
399
  event = asRecord(parseJsonPreservingUnsafeIntegers(dataStr));
@@ -505,70 +493,56 @@ async function runGoogleInteractionsLifecycle(params) {
505
493
  const status = typeof interaction.status === "string" ? interaction.status : "completed";
506
494
  if (status === "failed" || status === "cancelled" || status === "budget_exceeded") throw new Error(`Google Interactions API completed with status: ${status}`);
507
495
  if (status === "incomplete") output.stopReason = "length";
508
- else output.stopReason = output.content.some((b) => b.type === "toolCall") ? "toolUse" : "stop";
496
+ else {
497
+ const hasToolCalls = output.content.some((b) => b.type === "toolCall");
498
+ output.stopReason = hasToolCalls ? "toolUse" : "stop";
499
+ }
509
500
  }
510
501
  }
502
+ endCurrentBlock();
503
+ if (!sawCompletion) throw Object.assign(/* @__PURE__ */ new Error("Google Interactions stream ended before a terminal event"), {
504
+ code: "STREAM_INCOMPLETE",
505
+ type: "google_incomplete_stream"
506
+ });
507
+ if (latestThoughtSignature) {
508
+ for (const block of output.content) if (block.type === "thinking" && !block.thinkingSignature) block.thinkingSignature = latestThoughtSignature;
509
+ }
510
+ if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error("An unknown error occurred");
511
+ stream.push({
512
+ type: "done",
513
+ reason: output.stopReason,
514
+ message: output
515
+ });
516
+ stream.end();
517
+ } catch (error) {
518
+ const failure = options?.signal?.aborted ? transportAbortError(options.signal) : error;
519
+ for (const block of output.content) if (block.type === "toolCall") delete block.partialJson;
520
+ failTransportStream({
521
+ stream,
522
+ output,
523
+ signal: options?.signal,
524
+ error: failure
525
+ });
526
+ } finally {
527
+ if (reader) {
528
+ const cancellation = reader.cancel().catch(() => void 0);
529
+ reader.releaseLock();
530
+ getAiTransportHost().observePendingProviderWork?.(cancellation);
531
+ }
511
532
  }
512
- endCurrentBlock();
513
- if (!sawCompletion) throw Object.assign(/* @__PURE__ */ new Error("Google Interactions stream ended before a terminal event"), {
514
- code: "STREAM_INCOMPLETE",
515
- type: "google_incomplete_stream"
516
- });
517
- if (latestThoughtSignature) {
518
- for (const block of output.content) if (block.type === "thinking" && !block.thinkingSignature) block.thinkingSignature = latestThoughtSignature;
519
- }
520
- if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error("An unknown error occurred");
521
- stream.push({
522
- type: "done",
523
- reason: output.stopReason,
524
- message: output
525
- });
526
- stream.end();
527
- } catch (error) {
528
- const failure = options?.signal?.aborted ? transportAbortError(options.signal) : error;
529
- for (const block of output.content) if (block.type === "toolCall") delete block.partialJson;
530
- failTransportStream({
531
- stream,
532
- output,
533
- signal: options?.signal,
534
- error: failure
535
- });
536
- } finally {
537
- if (reader) {
538
- const cancellation = reader.cancel().catch(() => void 0);
539
- reader.releaseLock();
540
- getAiTransportHost().observePendingProviderWork?.(cancellation);
541
- }
542
- }
543
- }
544
- //#endregion
545
- //#region packages/ai/src/providers/google-interactions.ts
546
- let toolCallCounter = 0;
547
- const streamGoogleInteractions = (model, context, options) => {
548
- const stream = new AssistantMessageEventStream();
549
- runGoogleInteractionsLifecycle({
550
- stream,
551
- model,
552
- output: createAssistantOutput(model, "google-interactions"),
553
- options,
554
- context,
555
- nextToolCallId: (name) => `${name}_${Date.now()}_${++toolCallCounter}`
556
- });
533
+ })();
557
534
  return stream;
558
535
  };
559
536
  const streamSimpleGoogleInteractions = (model, context, options) => {
560
537
  const apiKey = resolveGoogleInteractionsApiKey(model, options);
561
538
  if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
562
539
  const base = buildBaseOptions(model, options, apiKey);
563
- const providerOptions = options;
564
540
  const record = asRecord(options);
565
541
  const toolChoice = normalizeGoogleInteractionsToolChoice(record.toolChoice);
566
542
  const videoMetadata = record.videoMetadata ?? record.video_metadata;
567
543
  return streamGoogleInteractions(model, context, {
568
544
  ...base,
569
545
  ...typeof record.topP === "number" ? { topP: record.topP } : {},
570
- [PROVIDER_MODEL_INPUT]: providerOptions?.[PROVIDER_MODEL_INPUT],
571
- [PROVIDER_CONTEXT_HANDOFF]: providerOptions?.[PROVIDER_CONTEXT_HANDOFF],
572
546
  thinking: buildGoogleInteractionsSimpleThinking(model, options),
573
547
  ...toolChoice ? { toolChoice } : {},
574
548
  ...videoMetadata !== void 0 ? { videoMetadata } : {}