experimental-ash 0.30.1 → 0.31.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 (180) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/src/cli/run.d.ts +0 -1
  3. package/dist/src/cli/run.js +2 -2
  4. package/dist/src/compiled/.vendor-stamp.json +6 -6
  5. package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +2 -2
  6. package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
  7. package/dist/src/compiled/@ai-sdk/anthropic/package.json +1 -1
  8. package/dist/src/compiled/@ai-sdk/google/index.d.ts +14 -1
  9. package/dist/src/compiled/@ai-sdk/google/index.js +6 -6
  10. package/dist/src/compiled/@ai-sdk/google/package.json +1 -1
  11. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  12. package/dist/src/compiled/@ai-sdk/mcp/package.json +1 -1
  13. package/dist/src/compiled/@ai-sdk/openai/index.js +2 -2
  14. package/dist/src/compiled/@ai-sdk/openai/package.json +1 -1
  15. package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
  16. package/dist/src/compiled/@ai-sdk/otel/package.json +1 -1
  17. package/dist/src/compiled/@vercel/sandbox/index.d.ts +34 -11
  18. package/dist/src/compiled/_chunks/workflow/{dist-DZZY3Zyp.js → dist-Dl-X5RB3.js} +1 -1
  19. package/dist/src/compiled/just-bash/index.d.ts +48 -0
  20. package/dist/src/execution/await-authorization-orchestrator.d.ts +2 -0
  21. package/dist/src/execution/await-authorization-orchestrator.js +1 -1
  22. package/dist/src/execution/code-mode-authorization-lifecycle.d.ts +15 -0
  23. package/dist/src/execution/code-mode-authorization-lifecycle.js +1 -0
  24. package/dist/src/execution/connection-auth-steps.d.ts +15 -0
  25. package/dist/src/execution/connection-auth-steps.js +1 -1
  26. package/dist/src/execution/connection-auth-tool-result.d.ts +2 -0
  27. package/dist/src/execution/connection-auth-tool-result.js +1 -0
  28. package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
  29. package/dist/src/execution/node-step.d.ts +12 -1
  30. package/dist/src/execution/node-step.js +1 -1
  31. package/dist/src/execution/sandbox/bash-tool.js +1 -1
  32. package/dist/src/execution/sandbox/bindings/local.js +1 -1
  33. package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
  34. package/dist/src/execution/sandbox/glob-tool.js +1 -1
  35. package/dist/src/execution/sandbox/grep-tool.js +1 -1
  36. package/dist/src/execution/sandbox/ripgrep-probe.js +1 -1
  37. package/dist/src/execution/sandbox/session.d.ts +3 -1
  38. package/dist/src/execution/sandbox/session.js +1 -1
  39. package/dist/src/execution/sandbox/shell-quote.d.ts +1 -1
  40. package/dist/src/execution/turn-workflow.js +1 -1
  41. package/dist/src/execution/workflow-entry.js +1 -1
  42. package/dist/src/execution/workflow-steps.d.ts +2 -0
  43. package/dist/src/execution/workflow-steps.js +1 -1
  44. package/dist/src/harness/code-mode-approval.d.ts +22 -0
  45. package/dist/src/harness/code-mode-approval.js +1 -0
  46. package/dist/src/harness/code-mode.d.ts +31 -0
  47. package/dist/src/harness/code-mode.js +1 -0
  48. package/dist/src/harness/input-extraction.js +1 -1
  49. package/dist/src/harness/step-hooks.js +1 -1
  50. package/dist/src/harness/tool-loop.js +1 -1
  51. package/dist/src/internal/application/package.js +1 -1
  52. package/dist/src/internal/nitro/host/build-application.js +1 -1
  53. package/dist/src/internal/nitro/host/code-mode-worker-asset.d.ts +18 -0
  54. package/dist/src/internal/nitro/host/code-mode-worker-asset.js +1 -0
  55. package/dist/src/internal/nitro/host/configure-nitro-routes.js +3 -3
  56. package/dist/src/internal/nitro/host/create-application-nitro.d.ts +0 -1
  57. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  58. package/dist/src/internal/nitro/host/dev-authored-source-watcher.d.ts +0 -1
  59. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  60. package/dist/src/internal/nitro/host/dispatch-schedule-in-dev.d.ts +41 -0
  61. package/dist/src/internal/nitro/host/dispatch-schedule-in-dev.js +1 -0
  62. package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
  63. package/dist/src/internal/nitro/host/start-development-server.d.ts +6 -1
  64. package/dist/src/internal/nitro/host/start-development-server.js +1 -1
  65. package/dist/src/internal/nitro/routes/dev-schedule-dispatch.d.ts +15 -0
  66. package/dist/src/internal/nitro/routes/dev-schedule-dispatch.js +1 -0
  67. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/approval-continuation.js +1 -0
  68. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/approval-response.js +1 -0
  69. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/code-mode-tool.js +1 -0
  70. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/continuation-capability.js +1 -0
  71. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/errors.js +1 -0
  72. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/fetch-policy.js +1 -0
  73. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/host-interrupt.js +1 -0
  74. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/index.js +1 -0
  75. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/interrupt-continuation.js +1 -0
  76. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/options.js +1 -0
  77. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/run-code-mode.js +1 -0
  78. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/runtime/manager.js +1 -0
  79. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/runtime/max-workers.js +1 -0
  80. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/runtime-assets.js +1 -0
  81. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/serialization.js +1 -0
  82. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/source-cache.js +4 -0
  83. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/telemetry.js +1 -0
  84. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/tool-invocation.js +1 -0
  85. package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/tool-prompt.js +9 -0
  86. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/index.js +1 -0
  87. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js +1 -0
  88. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js +1 -0
  89. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js +1 -0
  90. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js +1 -0
  91. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +1 -0
  92. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js +1 -0
  93. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js +1 -0
  94. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js +1 -0
  95. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +1 -0
  96. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js +1 -0
  97. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js +1 -0
  98. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js +1 -0
  99. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js +3 -0
  100. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js +2 -0
  101. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js +1 -0
  102. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js +1 -0
  103. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js +1 -0
  104. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js +1 -0
  105. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js +1 -0
  106. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js +1 -0
  107. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js +1 -0
  108. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js +60 -0
  109. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js +3 -0
  110. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js +1 -0
  111. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js +1 -0
  112. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js +1 -0
  113. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js +1 -0
  114. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js +1 -0
  115. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js +1 -0
  116. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js +1 -0
  117. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js +1 -0
  118. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js +1 -0
  119. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js +1 -0
  120. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js +1 -0
  121. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js +1 -0
  122. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js +1 -0
  123. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js +1 -0
  124. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js +1 -0
  125. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js +1 -0
  126. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js +1 -0
  127. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js +1 -0
  128. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js +1 -0
  129. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js +1 -0
  130. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js +1 -0
  131. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js +1 -0
  132. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js +1 -0
  133. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js +1 -0
  134. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js +1 -0
  135. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js +1 -0
  136. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js +1 -0
  137. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js +1 -0
  138. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/kh.js +1 -0
  139. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js +1 -0
  140. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js +1 -0
  141. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js +1 -0
  142. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js +1 -0
  143. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js +1 -0
  144. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js +1 -0
  145. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js +1 -0
  146. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js +1 -0
  147. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js +1 -0
  148. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js +1 -0
  149. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js +1 -0
  150. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js +1 -0
  151. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js +1 -0
  152. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js +1 -0
  153. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js +1 -0
  154. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ta.js +1 -0
  155. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js +1 -0
  156. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js +1 -0
  157. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ua.js +1 -0
  158. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js +1 -0
  159. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js +1 -0
  160. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js +1 -0
  161. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js +1 -0
  162. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js +1 -0
  163. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js +1 -0
  164. package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js +1 -0
  165. package/dist/src/protocol/routes.d.ts +20 -0
  166. package/dist/src/protocol/routes.js +1 -1
  167. package/dist/src/public/definitions/sandbox.d.ts +1 -1
  168. package/dist/src/public/sandbox/index.d.ts +1 -1
  169. package/dist/src/runtime/agent/mock-model-adapter.js +4 -3
  170. package/dist/src/runtime/framework-tools/code-mode-connection-auth.d.ts +32 -0
  171. package/dist/src/runtime/framework-tools/code-mode-connection-auth.js +1 -0
  172. package/dist/src/runtime/framework-tools/connection-search.d.ts +3 -0
  173. package/dist/src/runtime/framework-tools/connection-search.js +1 -1
  174. package/dist/src/runtime/framework-tools/connection-tools.d.ts +18 -1
  175. package/dist/src/runtime/framework-tools/connection-tools.js +1 -1
  176. package/dist/src/runtime/resolve-agent-graph.js +1 -1
  177. package/dist/src/shared/code-mode.d.ts +2 -0
  178. package/dist/src/shared/code-mode.js +1 -0
  179. package/dist/src/shared/sandbox-session.d.ts +38 -10
  180. package/package.json +9 -8
@@ -1,11 +1,11 @@
1
- import{AISDKError as e,TooManyEmbeddingValuesForCallError as t,UnsupportedFunctionalityError as n}from"../provider/index.js";import{At as r,Et as i,Nn as a,Rn as o,Tn as s,Xn as c,Zn as l,dn as u,wn as d,yt as f}from"../../_chunks/workflow/schemas-DmgDnhW3.js";import{A as p,B as m,C as h,E as g,I as _,J as v,M as y,N as b,R as x,S,T as C,V as w,W as T,X as E,Y as D,Z as O,_ as k,a as ee,b as A,c as te,d as ne,f as j,h as M,k as N,o as P,q as re,r as F,u as I,w as L,x as R,z}from"../../_chunks/workflow/dist-DZZY3Zyp.js";var ie=`4.0.0-canary.69`,B=ne({errorSchema:N(()=>D(s({error:s({code:d().nullable(),message:o(),status:o()})}))),errorToMessage:e=>e.error.message}),ae=c([s({text:o()}),s({inlineData:s({mimeType:o(),data:o()})}),s({fileData:s({fileUri:o(),mimeType:o()})})]),oe=N(()=>D(s({outputDimensionality:d().optional(),taskType:f([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional(),content:i(i(ae).min(1).nullable()).optional()}))),se=class e{constructor(e,t){this.specificationVersion=`v4`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}static[O](e){return T({modelId:e.modelId,config:e.config})}static[E](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async doEmbed({values:e,headers:n,abortSignal:r,providerOptions:i}){let a=await _({provider:`google`,providerOptions:i,schema:oe});if(e.length>this.maxEmbeddingsPerCall)throw new t({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=F(this.config.headers?await z(this.config.headers):void 0,n),s=a?.content;if(s!=null&&s.length!==e.length)throw Error(`The number of multimodal content entries (${s.length}) must match the number of values (${e.length}).`);if(e.length===1){let t=s?.[0],n=e[0]?[{text:e[0]}]:[],i=t==null?[{text:e[0]}]:[...n,...t],{responseHeaders:c,value:l,rawValue:u}=await x({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:i},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:B,successfulResponseHandler:j(le),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:[l.embedding.values],usage:void 0,response:{headers:c,body:u}}}let{responseHeaders:c,value:l,rawValue:u}=await x({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map((e,t)=>{let n=s?.[t],r=e?[{text:e}]:[];return{model:`models/${this.modelId}`,content:{role:`user`,parts:n==null?[{text:e}]:[...r,...n]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}})},failedResponseHandler:B,successfulResponseHandler:j(ce),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.embeddings.map(e=>e.values),usage:void 0,response:{headers:c,body:u}}}},ce=N(()=>D(s({embeddings:i(s({values:i(d())}))}))),le=N(()=>D(s({embedding:s({values:i(d())})})));function ue(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.promptTokenCount??0,n=e.candidatesTokenCount??0,r=e.cachedContentTokenCount??0,i=e.thoughtsTokenCount??0;return{inputTokens:{total:t,noCache:t-r,cacheRead:r,cacheWrite:void 0},outputTokens:{total:n+i,text:n,reasoning:i},raw:e}}function V(e,t=!0){if(e==null)return;if(de(e))return t?void 0:typeof e==`object`&&e.description?{type:`object`,description:e.description}:{type:`object`};if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:n,description:r,required:i,properties:a,items:o,allOf:s,anyOf:c,oneOf:l,format:u,const:d,minLength:f,enum:p}=e,m={};if(r&&(m.description=r),i&&(m.required=i),u&&(m.format=u),d!==void 0&&(m.enum=[d]),n)if(Array.isArray(n)){let e=n.includes(`null`),t=n.filter(e=>e!==`null`);t.length===0?m.type=`null`:(m.anyOf=t.map(e=>({type:e})),e&&(m.nullable=!0))}else m.type=n;if(p!==void 0&&(m.enum=p),a!=null&&(m.properties=Object.entries(a).reduce((e,[t,n])=>(e[t]=V(n,!1),e),{})),o&&(m.items=Array.isArray(o)?o.map(e=>V(e,!1)):V(o,!1)),s&&(m.allOf=s.map(e=>V(e,!1))),c)if(c.some(e=>typeof e==`object`&&e?.type===`null`)){let e=c.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=V(e[0],!1);typeof t==`object`&&(m.nullable=!0,Object.assign(m,t))}else m.anyOf=e.map(e=>V(e,!1)),m.nullable=!0}else m.anyOf=c.map(e=>V(e,!1));return l&&(m.oneOf=l.map(e=>V(e,!1))),f!==void 0&&(m.minLength=f),m}function de(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}var fe=/^data:([^;,]+);base64,(.+)$/s;function pe(e){let t=fe.exec(e);if(t!=null)return{mediaType:t[1],data:t[2]}}function me(e){let t=pe(e);if(t!=null)return{inlineData:{mimeType:t.mediaType,data:t.data}}}function he(e,t,n,r){let i=[],a=[];for(let e of n)switch(e.type){case`text`:a.push(e.text);break;case`file`:if(e.data.type===`data`)i.push({inlineData:{mimeType:m({part:e}),data:P(e.data.data)}});else if(e.data.type===`url`){let t=me(e.data.url.toString());t==null?a.push(JSON.stringify(e)):i.push(t)}else a.push(JSON.stringify(e));break;default:a.push(JSON.stringify(e));break}e.push({functionResponse:{...r==null?{}:{id:r},name:t,response:{name:t,content:a.length>0?a.join(`
2
- `):`Tool executed successfully.`},...i.length>0?{parts:i}:{}}})}function ge(e,t,n,r){for(let i of n)switch(i.type){case`text`:e.push({functionResponse:{...r==null?{}:{id:r},name:t,response:{name:t,content:i.text}}});break;case`file`:i.data.type===`data`&&h(i.mediaType)===`image`?e.push({inlineData:{mimeType:m({part:i}),data:P(i.data.data)}},{text:`Tool executed successfully and returned this image as a response`}):e.push({text:JSON.stringify(i)});break;default:e.push({text:JSON.stringify(i)});break}}function _e(e,t){let r=[],i=[],a=!0,o=t?.isGemmaModel??!1,s=t?.providerOptionsNames??[`google`],c=!s.includes(`google`),l=t?.supportsFunctionResponseParts??!0,u=e=>{for(let t of s){let n=e.providerOptions?.[t];if(n!=null)return n}return c?e.providerOptions?.google:e.providerOptions?.googleVertex??e.providerOptions?.vertex};for(let{role:t,content:o}of e)switch(t){case`system`:if(!a)throw new n({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let t of o)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:switch(t.data.type){case`url`:e.push({fileData:{mimeType:m({part:t}),fileUri:t.data.url.toString()}});break;case`reference`:if(c)throw new n({functionality:`file parts with provider references`});e.push({fileData:{mimeType:m({part:t}),fileUri:w({reference:t.data.reference,provider:`google`})}});break;case`text`:e.push({inlineData:{mimeType:g(t.mediaType)?t.mediaType:`text/plain`,data:P(new TextEncoder().encode(t.data.text))}});break;case`data`:e.push({inlineData:{mimeType:m({part:t}),data:P(t.data.data)}});break}break}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.map(e=>{let t=u(e),r=t?.thoughtSignature==null?void 0:String(t.thoughtSignature);switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:r};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:r};case`reasoning-file`:switch(e.data.type){case`url`:throw new n({functionality:`File data URLs in assistant messages are not supported`});case`data`:return{inlineData:{mimeType:e.mediaType,data:P(e.data.data)},thought:!0,thoughtSignature:r}}break;case`file`:switch(e.data.type){case`url`:throw new n({functionality:`File data URLs in assistant messages are not supported`});case`reference`:if(c)throw new n({functionality:`file parts with provider references`});return{fileData:{mimeType:e.mediaType,fileUri:w({reference:e.data.reference,provider:`google`})},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`text`:return{inlineData:{mimeType:g(e.mediaType)?e.mediaType:`text/plain`,data:P(new TextEncoder().encode(e.data.text))},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`data`:return{inlineData:{mimeType:e.mediaType,data:P(e.data.data)},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r}}break;case`tool-call`:{let n=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType);return n&&i?{toolCall:{toolType:i,args:typeof e.input==`string`?JSON.parse(e.input):e.input,id:n},thoughtSignature:r}:{functionCall:{...e.toolCallId==null?{}:{id:e.toolCallId},name:e.toolName,args:e.input},thoughtSignature:r}}case`tool-result`:{let n=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType);return n&&i?{toolResponse:{toolType:i,response:e.output.type===`json`?e.output.value:{},id:n},thoughtSignature:r}:void 0}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of o){if(t.type===`tool-approval-response`)continue;let n=u(t),r=n?.serverToolCallId==null?void 0:String(n.serverToolCallId),a=n?.serverToolType==null?void 0:String(n.serverToolType);if(r&&a){let e=n?.thoughtSignature==null?void 0:String(n.thoughtSignature);if(i.length>0){let n=i[i.length-1];if(n.role===`model`){n.parts.push({toolResponse:{toolType:a,response:t.output.type===`json`?t.output.value:{},id:r},thoughtSignature:e});continue}}}let o=t.output;o.type===`content`?l?he(e,t.toolName,o.value,t.toolCallId):ge(e,t.toolName,o.value,t.toolCallId):e.push({functionResponse:{...t.toolCallId==null?{}:{id:t.toolCallId},name:t.toolName,response:{name:t.toolName,content:o.type===`execution-denied`?o.reason??`Tool call execution denied.`:o.value}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
1
+ import{AISDKError as e,TooManyEmbeddingValuesForCallError as t,UnsupportedFunctionalityError as n}from"../provider/index.js";import{At as r,Et as i,Nn as a,Rn as o,Tn as s,Xn as c,Zn as l,dn as u,wn as d,yt as f}from"../../_chunks/workflow/schemas-DmgDnhW3.js";import{A as p,B as m,C as h,E as g,I as _,J as v,M as y,N as b,R as x,S,T as C,V as w,W as T,X as E,Y as D,Z as O,_ as k,a as A,b as j,c as ee,d as te,f as M,h as N,k as P,o as F,q as ne,r as I,u as L,w as R,x as z,z as B}from"../../_chunks/workflow/dist-Dl-X5RB3.js";var re=`4.0.0-canary.73`,V=te({errorSchema:P(()=>D(s({error:s({code:d().nullable(),message:o(),status:o()})}))),errorToMessage:e=>e.error.message}),ie=c([s({text:o()}),s({inlineData:s({mimeType:o(),data:o()})}),s({fileData:s({fileUri:o(),mimeType:o()})})]),ae=P(()=>D(s({outputDimensionality:d().optional(),taskType:f([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional(),content:i(i(ie).min(1).nullable()).optional()}))),oe=class e{constructor(e,t){this.specificationVersion=`v4`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}static[O](e){return T({modelId:e.modelId,config:e.config})}static[E](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async doEmbed({values:e,headers:n,abortSignal:r,providerOptions:i}){let a=await _({provider:`google`,providerOptions:i,schema:ae});if(e.length>this.maxEmbeddingsPerCall)throw new t({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=I(this.config.headers?await B(this.config.headers):void 0,n),s=a?.content;if(s!=null&&s.length!==e.length)throw Error(`The number of multimodal content entries (${s.length}) must match the number of values (${e.length}).`);if(e.length===1){let t=s?.[0],n=e[0]?[{text:e[0]}]:[],i=t==null?[{text:e[0]}]:[...n,...t],{responseHeaders:c,value:l,rawValue:u}=await x({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:i},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:V,successfulResponseHandler:M(ce),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:[l.embedding.values],usage:void 0,response:{headers:c,body:u}}}let{responseHeaders:c,value:l,rawValue:u}=await x({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map((e,t)=>{let n=s?.[t],r=e?[{text:e}]:[];return{model:`models/${this.modelId}`,content:{role:`user`,parts:n==null?[{text:e}]:[...r,...n]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}})},failedResponseHandler:V,successfulResponseHandler:M(se),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.embeddings.map(e=>e.values),usage:void 0,response:{headers:c,body:u}}}},se=P(()=>D(s({embeddings:i(s({values:i(d())}))}))),ce=P(()=>D(s({embedding:s({values:i(d())})})));function le(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.promptTokenCount??0,n=e.candidatesTokenCount??0,r=e.cachedContentTokenCount??0,i=e.thoughtsTokenCount??0;return{inputTokens:{total:t,noCache:t-r,cacheRead:r,cacheWrite:void 0},outputTokens:{total:n+i,text:n,reasoning:i},raw:e}}function H(e,t=!0){if(e==null)return;if(ue(e))return t?void 0:typeof e==`object`&&e.description?{type:`object`,description:e.description}:{type:`object`};if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:n,description:r,required:i,properties:a,items:o,allOf:s,anyOf:c,oneOf:l,format:u,const:d,minLength:f,enum:p}=e,m={};if(r&&(m.description=r),i&&(m.required=i),u&&(m.format=u),d!==void 0&&(m.enum=[d]),n)if(Array.isArray(n)){let e=n.includes(`null`),t=n.filter(e=>e!==`null`);t.length===0?m.type=`null`:(m.anyOf=t.map(e=>({type:e})),e&&(m.nullable=!0))}else m.type=n;if(p!==void 0&&(m.enum=p),a!=null&&(m.properties=Object.entries(a).reduce((e,[t,n])=>(e[t]=H(n,!1),e),{})),o&&(m.items=Array.isArray(o)?o.map(e=>H(e,!1)):H(o,!1)),s&&(m.allOf=s.map(e=>H(e,!1))),c)if(c.some(e=>typeof e==`object`&&e?.type===`null`)){let e=c.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=H(e[0],!1);typeof t==`object`&&(m.nullable=!0,Object.assign(m,t))}else m.anyOf=e.map(e=>H(e,!1)),m.nullable=!0}else m.anyOf=c.map(e=>H(e,!1));return l&&(m.oneOf=l.map(e=>H(e,!1))),f!==void 0&&(m.minLength=f),m}function ue(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}var de=/^data:([^;,]+);base64,(.+)$/s;function fe(e){let t=de.exec(e);if(t!=null)return{mediaType:t[1],data:t[2]}}function pe(e){let t=fe(e);if(t!=null)return{inlineData:{mimeType:t.mediaType,data:t.data}}}function me(e,t,n,r){let i=[],a=[];for(let e of n)switch(e.type){case`text`:a.push(e.text);break;case`file`:if(e.data.type===`data`)i.push({inlineData:{mimeType:m({part:e}),data:F(e.data.data)}});else if(e.data.type===`url`){let t=pe(e.data.url.toString());t==null?a.push(JSON.stringify(e)):i.push(t)}else a.push(JSON.stringify(e));break;default:a.push(JSON.stringify(e));break}e.push({functionResponse:{...r==null?{}:{id:r},name:t,response:{name:t,content:a.length>0?a.join(`
2
+ `):`Tool executed successfully.`},...i.length>0?{parts:i}:{}}})}function he(e,t,n,r){for(let i of n)switch(i.type){case`text`:e.push({functionResponse:{...r==null?{}:{id:r},name:t,response:{name:t,content:i.text}}});break;case`file`:i.data.type===`data`&&h(i.mediaType)===`image`?e.push({inlineData:{mimeType:m({part:i}),data:F(i.data.data)}},{text:`Tool executed successfully and returned this image as a response`}):e.push({text:JSON.stringify(i)});break;default:e.push({text:JSON.stringify(i)});break}}function ge(e,t){let r=[],i=[],a=!0,o=t?.isGemmaModel??!1,s=t?.providerOptionsNames??[`google`],c=!s.includes(`google`),l=t?.supportsFunctionResponseParts??!0,u=e=>{for(let t of s){let n=e.providerOptions?.[t];if(n!=null)return n}return c?e.providerOptions?.google:e.providerOptions?.googleVertex??e.providerOptions?.vertex};for(let{role:t,content:o}of e)switch(t){case`system`:if(!a)throw new n({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let t of o)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:switch(t.data.type){case`url`:e.push({fileData:{mimeType:m({part:t}),fileUri:t.data.url.toString()}});break;case`reference`:if(c)throw new n({functionality:`file parts with provider references`});e.push({fileData:{mimeType:m({part:t}),fileUri:w({reference:t.data.reference,provider:`google`})}});break;case`text`:e.push({inlineData:{mimeType:g(t.mediaType)?t.mediaType:`text/plain`,data:F(new TextEncoder().encode(t.data.text))}});break;case`data`:e.push({inlineData:{mimeType:m({part:t}),data:F(t.data.data)}});break}break}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.map(e=>{let t=u(e),r=t?.thoughtSignature==null?void 0:String(t.thoughtSignature);switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:r};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:r};case`reasoning-file`:switch(e.data.type){case`url`:throw new n({functionality:`File data URLs in assistant messages are not supported`});case`data`:return{inlineData:{mimeType:e.mediaType,data:F(e.data.data)},thought:!0,thoughtSignature:r}}break;case`file`:switch(e.data.type){case`url`:throw new n({functionality:`File data URLs in assistant messages are not supported`});case`reference`:if(c)throw new n({functionality:`file parts with provider references`});return{fileData:{mimeType:e.mediaType,fileUri:w({reference:e.data.reference,provider:`google`})},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`text`:return{inlineData:{mimeType:g(e.mediaType)?e.mediaType:`text/plain`,data:F(new TextEncoder().encode(e.data.text))},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`data`:return{inlineData:{mimeType:e.mediaType,data:F(e.data.data)},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r}}break;case`tool-call`:{let n=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType);return n&&i?{toolCall:{toolType:i,args:typeof e.input==`string`?JSON.parse(e.input):e.input,id:n},thoughtSignature:r}:{functionCall:{...e.toolCallId==null?{}:{id:e.toolCallId},name:e.toolName,args:e.input},thoughtSignature:r}}case`tool-result`:{let n=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType);return n&&i?{toolResponse:{toolType:i,response:e.output.type===`json`?e.output.value:{},id:n},thoughtSignature:r}:void 0}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of o){if(t.type===`tool-approval-response`)continue;let n=u(t),r=n?.serverToolCallId==null?void 0:String(n.serverToolCallId),a=n?.serverToolType==null?void 0:String(n.serverToolType);if(r&&a){let e=n?.thoughtSignature==null?void 0:String(n.thoughtSignature);if(i.length>0){let n=i[i.length-1];if(n.role===`model`){n.parts.push({toolResponse:{toolType:a,response:t.output.type===`json`?t.output.value:{},id:r},thoughtSignature:e});continue}}}let o=t.output;o.type===`content`?l?me(e,t.toolName,o.value,t.toolCallId):he(e,t.toolName,o.value,t.toolCallId):e.push({functionResponse:{...t.toolCallId==null?{}:{id:t.toolCallId},name:t.toolName,response:{name:t.toolName,content:o.type===`execution-denied`?o.reason??`Tool call execution denied.`:o.value}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
3
3
 
4
4
  `);i[0].parts.unshift({text:e+`
5
5
 
6
- `})}return{systemInstruction:r.length>0&&!o?{parts:r}:void 0,contents:i}}function ve(e){return e.includes(`/`)?e:`models/${e}`}var ye=N(()=>D(s({responseModalities:i(f([`TEXT`,`IMAGE`])).optional(),thinkingConfig:s({thinkingBudget:d().optional(),includeThoughts:r().optional(),thinkingLevel:f([`minimal`,`low`,`medium`,`high`]).optional()}).optional(),cachedContent:o().optional(),structuredOutputs:r().optional(),safetySettings:i(s({category:f([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:f([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:f([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:r().optional(),labels:a(o(),o()).optional(),mediaResolution:f([`MEDIA_RESOLUTION_UNSPECIFIED`,`MEDIA_RESOLUTION_LOW`,`MEDIA_RESOLUTION_MEDIUM`,`MEDIA_RESOLUTION_HIGH`]).optional(),imageConfig:s({aspectRatio:f([`1:1`,`2:3`,`3:2`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`,`1:8`,`8:1`,`1:4`,`4:1`]).optional(),imageSize:f([`1K`,`2K`,`4K`,`512`]).optional()}).optional(),retrievalConfig:s({latLng:s({latitude:d(),longitude:d()}).optional()}).optional(),streamFunctionCallArguments:r().optional(),serviceTier:f([`standard`,`flex`,`priority`]).optional()}))),be={standard:`SERVICE_TIER_STANDARD`,flex:`SERVICE_TIER_FLEX`,priority:`SERVICE_TIER_PRIORITY`};function xe({tools:e,toolChoice:t,modelId:r,isVertexProvider:i=!1}){e=e?.length?e:void 0;let a=[],o=[`gemini-flash-latest`,`gemini-flash-lite-latest`,`gemini-pro-latest`].some(e=>e===r),s=r.includes(`gemini-2`)||r.includes(`gemini-3`)||r.includes(`nano-banana`)||o,c=r.includes(`gemini-3`),l=r.includes(`gemini-2.5`)||r.includes(`gemini-3`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:a};let u=e.some(e=>e.type===`function`),d=e.some(e=>e.type===`provider`);if(u&&d&&!c&&a.push({type:`unsupported`,feature:`combination of function and provider-defined tools`}),d){let n=[];if(e.filter(e=>e.type===`provider`).forEach(e=>{switch(e.id){case`google.google_search`:s?n.push({googleSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Google Search requires Gemini 2.0 or newer.`});break;case`google.enterprise_web_search`:s?n.push({enterpriseWebSearch:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Enterprise Web Search requires Gemini 2.0 or newer.`});break;case`google.url_context`:s?n.push({urlContext:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:s?n.push({codeExecution:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The code execution tool is not supported with other Gemini models than Gemini 2.`});break;case`google.file_search`:l?n.push({fileSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The file search tool is only supported with Gemini 2.5 models and Gemini 3 models.`});break;case`google.vertex_rag_store`:s?n.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:e.args.ragCorpus},similarity_top_k:e.args.topK}}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The RAG store tool is not supported with other Gemini models than Gemini 2.`});break;case`google.google_maps`:s?n.push({googleMaps:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer.`});break;default:a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`});break}}),u&&c&&n.length>0){let r=[];for(let t of e)t.type===`function`&&r.push({name:t.name,description:t.description??``,parameters:V(t.inputSchema)});let o={functionCallingConfig:{mode:`VALIDATED`},...!i&&{includeServerSideToolInvocations:!0}};if(t!=null)switch(t.type){case`auto`:break;case`none`:o.functionCallingConfig={mode:`NONE`};break;case`required`:o.functionCallingConfig={mode:`ANY`};break;case`tool`:o.functionCallingConfig={mode:`ANY`,allowedFunctionNames:[t.toolName]};break}return{tools:[...n,{functionDeclarations:r}],toolConfig:o,toolWarnings:a}}return{tools:n.length>0?n:void 0,toolConfig:void 0,toolWarnings:a}}let f=[],p=!1;for(let t of e)switch(t.type){case`function`:f.push({name:t.name,description:t.description??``,parameters:V(t.inputSchema)}),t.strict===!0&&(p=!0);break;default:a.push({type:`unsupported`,feature:`function tool ${t.name}`});break}if(t==null)return{tools:[{functionDeclarations:f}],toolConfig:p?{functionCallingConfig:{mode:`VALIDATED`}}:void 0,toolWarnings:a};let m=t.type;switch(m){case`auto`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`AUTO`}},toolWarnings:a};case`none`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:a};case`required`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`}},toolWarnings:a};case`tool`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:a};default:throw new n({functionality:`tool choice type: ${m}`})}}var Se=class{constructor(){this.accumulatedArgs={},this.jsonText=``,this.pathStack=[],this.stringOpen=!1}processPartialArgs(e){let t=``;for(let n of e){let e=n.jsonPath.replace(/^\$\./,``);if(!e)continue;let r=Ce(e),i=we(this.accumulatedArgs,r);if(n.stringValue!=null&&i!==void 0){let e=JSON.stringify(n.stringValue).slice(1,-1);Te(this.accumulatedArgs,r,i+n.stringValue),t+=e;continue}let a=Ee(n);a!=null&&(Te(this.accumulatedArgs,r,a.value),t+=this.emitNavigationTo(r,n,a.json))}return this.jsonText+=t,{currentJSON:this.accumulatedArgs,textDelta:t}}finalize(){let e=JSON.stringify(this.accumulatedArgs);return{finalJSON:e,closingDelta:e.slice(this.jsonText.length)}}ensureRoot(){return this.pathStack.length===0?(this.pathStack.push({segment:``,isArray:!1,childCount:0}),`{`):``}emitNavigationTo(e,t,n){let r=``;this.stringOpen&&=(r+=`"`,!1),r+=this.ensureRoot();let i=e.slice(0,-1),a=e[e.length-1],o=this.findCommonStackDepth(i);return r+=this.closeDownTo(o),r+=this.openDownTo(i,a),r+=this.emitLeaf(a,t,n),r}findCommonStackDepth(e){let t=Math.min(this.pathStack.length-1,e.length),n=0;for(let r=0;r<t&&this.pathStack[r+1].segment===e[r];r++)n++;return n+1}closeDownTo(e){let t=``;for(;this.pathStack.length>e;){let e=this.pathStack.pop();t+=e.isArray?`]`:`}`}return t}openDownTo(e,t){let n=``,r=this.pathStack.length-1;for(let i=r;i<e.length;i++){let r=e[i],a=this.pathStack[this.pathStack.length-1];a.childCount>0&&(n+=`,`),a.childCount++,typeof r==`string`&&(n+=`${JSON.stringify(r)}:`);let o=typeof(i+1<e.length?e[i+1]:t)==`number`;n+=o?`[`:`{`,this.pathStack.push({segment:r,isArray:o,childCount:0})}return n}emitLeaf(e,t,n){let r=``,i=this.pathStack[this.pathStack.length-1];return i.childCount>0&&(r+=`,`),i.childCount++,typeof e==`string`&&(r+=`${JSON.stringify(e)}:`),t.stringValue!=null&&t.willContinue?(r+=n.slice(0,-1),this.stringOpen=!0):r+=n,r}};function Ce(e){let t=[];for(let n of e.split(`.`)){let e=n.indexOf(`[`);if(e===-1)t.push(n);else{e>0&&t.push(n.slice(0,e));for(let e of n.matchAll(/\[(\d+)\]/g))t.push(parseInt(e[1],10))}}return t}function we(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}function Te(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e],i=t[e+1];r[n]??(r[n]=typeof i==`number`?[]:{}),r=r[n]}r[t[t.length-1]]=n}function Ee(e){let t=e.stringValue??e.numberValue??e.boolValue;if(t!=null)return{value:t,json:JSON.stringify(t)};if(`nullValue`in e)return{value:null,json:`null`}}function De({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`tool-calls`:`stop`;case`MAX_TOKENS`:return`length`;case`IMAGE_SAFETY`:case`RECITATION`:case`SAFETY`:case`BLOCKLIST`:case`PROHIBITED_CONTENT`:case`SPII`:return`content-filter`;case`MALFORMED_FUNCTION_CALL`:return`error`;default:return`other`}}var Oe=class e{constructor(e,t){this.specificationVersion=`v4`,this.modelId=e,this.config=t,this.generateId=t.generateId??A}static[O](e){return T({modelId:e.modelId,config:e.config})}static[E](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,reasoning:f,providerOptions:p},{isStreaming:m=!1}={}){let h=[],g=this.config.provider.includes(`vertex`)?[`googleVertex`,`vertex`]:[`google`],v;for(let e of g)if(v=await _({provider:e,providerOptions:p,schema:ye}),v!=null)break;v==null&&!g.includes(`google`)&&(v=await _({provider:`google`,providerOptions:p,schema:ye}));let y=this.config.provider.startsWith(`google.vertex.`);u?.some(e=>e.type===`provider`&&e.id===`google.vertex_rag_store`)&&!y&&h.push({type:`other`,message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`}),v?.streamFunctionCallArguments&&!y&&h.push({type:`other`,message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`});let b=v?.serviceTier;v?.serviceTier&&y&&(b=be[v.serviceTier]);let x=this.modelId.toLowerCase().startsWith(`gemma-`),{contents:S,systemInstruction:C}=_e(e,{isGemmaModel:x,providerOptionsNames:g,supportsFunctionResponseParts:this.modelId.startsWith(`gemini-3`)}),{tools:w,toolConfig:T,toolWarnings:E}=xe({tools:u,toolChoice:d,modelId:this.modelId,isVertexProvider:y}),D=Me({reasoning:f,modelId:this.modelId,warnings:h}),O=v?.thinkingConfig||D?{...D,...v?.thinkingConfig}:void 0,k=m&&y?v?.streamFunctionCallArguments??!1:void 0,ee=T||k||v?.retrievalConfig?{...T,...k&&{functionCallingConfig:{...T?.functionCallingConfig,streamFunctionCallArguments:!0}},...v?.retrievalConfig&&{retrievalConfig:v.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&(v?.structuredOutputs??!0)?V(c.schema):void 0,...v?.audioTimestamp&&{audioTimestamp:v.audioTimestamp},responseModalities:v?.responseModalities,thinkingConfig:O,...v?.mediaResolution&&{mediaResolution:v.mediaResolution},...v?.imageConfig&&{imageConfig:v.imageConfig}},contents:S,systemInstruction:x?void 0:C,safetySettings:v?.safetySettings,tools:w,toolConfig:ee,cachedContent:v?.cachedContent,labels:v?.labels,serviceTier:b},warnings:[...h,...E],providerOptionsNames:g}}async doGenerate(e){let{args:t,warnings:n,providerOptionsNames:r}=await this.getArgs(e),i=e=>Object.fromEntries(r.map(t=>[t,e])),a=F(this.config.headers?await z(this.config.headers):void 0,e.headers),{responseHeaders:o,value:s,rawValue:c}=await x({url:`${this.config.baseURL}/${ve(this.modelId)}:generateContent`,headers:a,body:t,failedResponseHandler:B,successfulResponseHandler:j(Ve),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=s.candidates[0],u=[],d=l.content?.parts??[],f=s.usageMetadata,p,m;for(let e of d)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();p=t,u.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in e&&e.codeExecutionResult)u.push({type:`tool-result`,toolCallId:p,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output??``}}),p=void 0;else if(`text`in e&&e.text!=null){let t=e.thoughtSignature?i({thoughtSignature:e.thoughtSignature}):void 0;if(e.text.length===0){if(t!=null&&u.length>0){let e=u[u.length-1];e.providerMetadata=t}}else u.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:t})}else if(`functionCall`in e&&e.functionCall.name!=null)u.push({type:`tool-call`,toolCallId:e.functionCall.id??this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args??{}),providerMetadata:e.thoughtSignature?i({thoughtSignature:e.thoughtSignature}):void 0});else if(`inlineData`in e){let t=e.thought===!0,n=!!e.thoughtSignature;u.push({type:t?`reasoning-file`:`file`,data:{type:`data`,data:e.inlineData.data},mediaType:e.inlineData.mimeType,providerMetadata:n?i({thoughtSignature:e.thoughtSignature}):void 0})}else if(`toolCall`in e&&e.toolCall){let t=e.toolCall.id??this.config.generateId();m=t,u.push({type:`tool-call`,toolCallId:t,toolName:`server:${e.toolCall.toolType}`,input:JSON.stringify(e.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:e.thoughtSignature?i({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolCall.toolType}):i({serverToolCallId:t,serverToolType:e.toolCall.toolType})})}else if(`toolResponse`in e&&e.toolResponse){let t=m??e.toolResponse.id??this.config.generateId();u.push({type:`tool-result`,toolCallId:t,toolName:`server:${e.toolResponse.toolType}`,result:e.toolResponse.response??{},providerMetadata:e.thoughtSignature?i({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolResponse.toolType}):i({serverToolCallId:t,serverToolType:e.toolResponse.toolType})}),m=void 0}let h=Fe({groundingMetadata:l.groundingMetadata,generateId:this.config.generateId})??[];for(let e of h)u.push(e);return{content:u,finishReason:{unified:De({finishReason:l.finishReason,hasToolCalls:u.some(e=>e.type===`tool-call`&&!e.providerExecuted)}),raw:l.finishReason??void 0},usage:ue(f),warnings:n,providerMetadata:i({promptFeedback:s.promptFeedback??null,groundingMetadata:l.groundingMetadata??null,urlContextMetadata:l.urlContextMetadata??null,safetyRatings:l.safetyRatings??null,usageMetadata:f??null,finishMessage:l.finishMessage??null,serviceTier:s.serviceTier??null}),request:{body:t},response:{headers:o,body:c}}}async doStream(e){let{args:t,warnings:n,providerOptionsNames:r}=await this.getArgs(e,{isStreaming:!0}),i=e=>Object.fromEntries(r.map(t=>[t,e])),a=F(this.config.headers?await z(this.config.headers):void 0,e.headers),{responseHeaders:o,value:s}=await x({url:`${this.config.baseURL}/${ve(this.modelId)}:streamGenerateContent?alt=sse`,headers:a,body:t,failedResponseHandler:B,successfulResponseHandler:I(He),abortSignal:e.abortSignal,fetch:this.config.fetch}),c={unified:`other`,raw:void 0},l,u,d=null,f=null,p=null,m=this.config.generateId,h=!1,g=null,_=null,v=0,y=new Set,b,S,C=[],w=e=>{let t=C.pop();if(t==null)return;let{finalJSON:n,closingDelta:r}=t.accumulator.finalize();r.length>0&&e.enqueue({type:`tool-input-delta`,id:t.toolCallId,delta:r,providerMetadata:t.providerMetadata}),e.enqueue({type:`tool-input-end`,id:t.toolCallId,providerMetadata:t.providerMetadata}),e.enqueue({type:`tool-call`,toolCallId:t.toolCallId,toolName:t.toolName,input:n,providerMetadata:t.providerMetadata}),h=!0};return{stream:s.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value,a=r.usageMetadata;a!=null&&(l=a),r.serviceTier!=null&&(p=r.serviceTier);let o=r.candidates?.[0];if(o==null)return;let s=o.content;o.groundingMetadata!=null&&(d=o.groundingMetadata),o.urlContextMetadata!=null&&(f=o.urlContextMetadata);let x=Fe({groundingMetadata:o.groundingMetadata,generateId:m});if(x!=null)for(let e of x)e.sourceType===`url`&&!y.has(e.url)&&(y.add(e.url),n.enqueue(e));if(s!=null){let e=s.parts??[];for(let t of e)if(`executableCode`in t&&t.executableCode?.code){let e=m();b=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=b;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output??``}}),b=void 0)}else if(`text`in t&&t.text!=null){let e=t.thoughtSignature?i({thoughtSignature:t.thoughtSignature}):void 0;t.text.length===0?e!=null&&g!==null&&n.enqueue({type:`text-delta`,id:g,delta:``,providerMetadata:e}):t.thought===!0?(g!==null&&(n.enqueue({type:`text-end`,id:g}),g=null),_===null&&(_=String(v++),n.enqueue({type:`reasoning-start`,id:_,providerMetadata:e})),n.enqueue({type:`reasoning-delta`,id:_,delta:t.text,providerMetadata:e})):(_!==null&&(n.enqueue({type:`reasoning-end`,id:_}),_=null),g===null&&(g=String(v++),n.enqueue({type:`text-start`,id:g,providerMetadata:e})),n.enqueue({type:`text-delta`,id:g,delta:t.text,providerMetadata:e}))}else if(`inlineData`in t){g!==null&&(n.enqueue({type:`text-end`,id:g}),g=null),_!==null&&(n.enqueue({type:`reasoning-end`,id:_}),_=null);let e=t.thought===!0,r=t.thoughtSignature?i({thoughtSignature:t.thoughtSignature}):void 0;n.enqueue({type:e?`reasoning-file`:`file`,mediaType:t.inlineData.mimeType,data:{type:`data`,data:t.inlineData.data},providerMetadata:r})}else if(`toolCall`in t&&t.toolCall){let e=t.toolCall.id??m();S=e;let r=i({...t.thoughtSignature?{thoughtSignature:t.thoughtSignature}:{},serverToolCallId:e,serverToolType:t.toolCall.toolType});n.enqueue({type:`tool-call`,toolCallId:e,toolName:`server:${t.toolCall.toolType}`,input:JSON.stringify(t.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:r})}else if(`toolResponse`in t&&t.toolResponse){let e=S??t.toolResponse.id??m(),r=i({...t.thoughtSignature?{thoughtSignature:t.thoughtSignature}:{},serverToolCallId:e,serverToolType:t.toolResponse.toolType});n.enqueue({type:`tool-result`,toolCallId:e,toolName:`server:${t.toolResponse.toolType}`,result:t.toolResponse.response??{},providerMetadata:r}),S=void 0}for(let t of e){if(!(`functionCall`in t))continue;let e=t.thoughtSignature?i({thoughtSignature:t.thoughtSignature}):void 0,r=t.functionCall.partialArgs!=null||t.functionCall.name!=null&&t.functionCall.willContinue===!0,a=t.functionCall.name==null&&t.functionCall.args==null&&t.functionCall.partialArgs==null&&t.functionCall.willContinue==null,o=t.functionCall.name!=null&&t.functionCall.args!=null&&t.functionCall.partialArgs==null,s=t.functionCall.name!=null&&t.functionCall.args==null&&t.functionCall.partialArgs==null&&t.functionCall.willContinue!==!0;if(r){if(t.functionCall.name!=null){let r=t.functionCall.id??m(),i=new Se;if(C.push({toolCallId:r,toolName:t.functionCall.name,accumulator:i,providerMetadata:e}),n.enqueue({type:`tool-input-start`,id:r,toolName:t.functionCall.name,providerMetadata:e}),t.functionCall.partialArgs!=null){let a=t.functionCall.partialArgs,{textDelta:o}=i.processPartialArgs(a);o.length>0&&n.enqueue({type:`tool-input-delta`,id:r,delta:o,providerMetadata:e}),t.functionCall.willContinue!==!0&&a.every(e=>e.willContinue!==!0)&&w(n)}}else if(t.functionCall.partialArgs!=null&&C.length>0){let r=C[C.length-1],i=t.functionCall.partialArgs,{textDelta:a}=r.accumulator.processPartialArgs(i);a.length>0&&n.enqueue({type:`tool-input-delta`,id:r.toolCallId,delta:a,providerMetadata:e}),t.functionCall.willContinue!==!0&&i.every(e=>e.willContinue!==!0)&&w(n)}}else if(a&&C.length>0)w(n);else if(o){let r=t.functionCall.id??m(),i=t.functionCall.name,a=typeof t.functionCall.args==`string`?t.functionCall.args:JSON.stringify(t.functionCall.args??{});n.enqueue({type:`tool-input-start`,id:r,toolName:i,providerMetadata:e}),n.enqueue({type:`tool-input-delta`,id:r,delta:a,providerMetadata:e}),n.enqueue({type:`tool-input-end`,id:r,providerMetadata:e}),n.enqueue({type:`tool-call`,toolCallId:r,toolName:i,input:a,providerMetadata:e}),h=!0}else if(s){let r=t.functionCall.id??m(),i=t.functionCall.name;n.enqueue({type:`tool-input-start`,id:r,toolName:i,providerMetadata:e}),n.enqueue({type:`tool-input-end`,id:r,providerMetadata:e}),n.enqueue({type:`tool-call`,toolCallId:r,toolName:i,input:`{}`,providerMetadata:e}),h=!0}}}o.finishReason!=null&&(c={unified:De({finishReason:o.finishReason,hasToolCalls:h}),raw:o.finishReason},u=i({promptFeedback:r.promptFeedback??null,groundingMetadata:d,urlContextMetadata:f,safetyRatings:o.safetyRatings??null,usageMetadata:a??null,finishMessage:o.finishMessage??null,serviceTier:p}))},flush(e){g!==null&&e.enqueue({type:`text-end`,id:g}),_!==null&&e.enqueue({type:`reasoning-end`,id:_}),e.enqueue({type:`finish`,finishReason:c,usage:ue(l),providerMetadata:u})}})),response:{headers:o},request:{body:t}}}};function ke(e){return/gemini-3[\.\-]/i.test(e)||/gemini-3$/i.test(e)}function Ae(){return 65536}function je(e){let t=e.toLowerCase();return t.includes(`2.5-pro`)||t.includes(`gemini-3-pro-image`)?32768:24576}function Me({reasoning:e,modelId:t,warnings:n}){if(C(e))return ke(t)&&!t.includes(`gemini-3-pro-image`)?Ne({reasoning:e,warnings:n}):Pe({reasoning:e,modelId:t,warnings:n})}function Ne({reasoning:e,warnings:t}){if(e===`none`)return{thinkingLevel:`minimal`};let n=b({reasoning:e,effortMap:{minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,xhigh:`high`},warnings:t});if(n!=null)return{thinkingLevel:n}}function Pe({reasoning:e,modelId:t,warnings:n}){if(e===`none`)return{thinkingBudget:0};let r=y({reasoning:e,maxOutputTokens:Ae(),maxReasoningBudget:je(t),minReasoningBudget:0,warnings:n});if(r!=null)return{thinkingBudget:r}}function Fe({groundingMetadata:e,generateId:t}){if(!e?.groundingChunks)return;let n=[];for(let r of e.groundingChunks)if(r.web!=null)n.push({type:`source`,sourceType:`url`,id:t(),url:r.web.uri,title:r.web.title??void 0});else if(r.image!=null)n.push({type:`source`,sourceType:`url`,id:t(),url:r.image.sourceUri,title:r.image.title??void 0});else if(r.retrievedContext!=null){let e=r.retrievedContext.uri,i=r.retrievedContext.fileSearchStore;if(e&&(e.startsWith(`http://`)||e.startsWith(`https://`)))n.push({type:`source`,sourceType:`url`,id:t(),url:e,title:r.retrievedContext.title??void 0});else if(e){let i=r.retrievedContext.title??`Unknown Document`,a=`application/octet-stream`,o;e.endsWith(`.pdf`)?(a=`application/pdf`,o=e.split(`/`).pop()):e.endsWith(`.txt`)?(a=`text/plain`,o=e.split(`/`).pop()):e.endsWith(`.docx`)?(a=`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,o=e.split(`/`).pop()):e.endsWith(`.doc`)?(a=`application/msword`,o=e.split(`/`).pop()):(e.match(/\.(md|markdown)$/)&&(a=`text/markdown`),o=e.split(`/`).pop()),n.push({type:`source`,sourceType:`document`,id:t(),mediaType:a,title:i,filename:o})}else if(i){let e=r.retrievedContext.title??`Unknown Document`;n.push({type:`source`,sourceType:`document`,id:t(),mediaType:`application/octet-stream`,title:e,filename:i.split(`/`).pop()})}}else r.maps!=null&&r.maps.uri&&n.push({type:`source`,sourceType:`url`,id:t(),url:r.maps.uri,title:r.maps.title??void 0});return n.length>0?n:void 0}var Ie=()=>s({webSearchQueries:i(o()).nullish(),imageSearchQueries:i(o()).nullish(),retrievalQueries:i(o()).nullish(),searchEntryPoint:s({renderedContent:o()}).nullish(),groundingChunks:i(s({web:s({uri:o(),title:o().nullish()}).nullish(),image:s({sourceUri:o(),imageUri:o(),title:o().nullish(),domain:o().nullish()}).nullish(),retrievedContext:s({uri:o().nullish(),title:o().nullish(),text:o().nullish(),fileSearchStore:o().nullish()}).nullish(),maps:s({uri:o().nullish(),title:o().nullish(),text:o().nullish(),placeId:o().nullish()}).nullish()})).nullish(),groundingSupports:i(s({segment:s({startIndex:d().nullish(),endIndex:d().nullish(),text:o().nullish()}).nullish(),segment_text:o().nullish(),groundingChunkIndices:i(d()).nullish(),supportChunkIndices:i(d()).nullish(),confidenceScores:i(d()).nullish(),confidenceScore:i(d()).nullish()})).nullish(),retrievalMetadata:c([s({webDynamicRetrievalScore:d()}),s({})]).nullish()}),Le=s({jsonPath:o(),stringValue:o().nullish(),numberValue:d().nullish(),boolValue:r().nullish(),nullValue:l().nullish(),willContinue:r().nullish()}),Re=()=>s({parts:i(c([s({functionCall:s({id:o().nullish(),name:o().nullish(),args:l().nullish(),partialArgs:i(Le).nullish(),willContinue:r().nullish()}),thoughtSignature:o().nullish()}),s({inlineData:s({mimeType:o(),data:o()}),thought:r().nullish(),thoughtSignature:o().nullish()}),s({toolCall:s({toolType:o(),args:l().nullish(),id:o()}),thoughtSignature:o().nullish()}),s({toolResponse:s({toolType:o(),response:l().nullish(),id:o()}),thoughtSignature:o().nullish()}),s({executableCode:s({language:o(),code:o()}).nullish(),codeExecutionResult:s({outcome:o(),output:o().nullish()}).nullish(),text:o().nullish(),thought:r().nullish(),thoughtSignature:o().nullish()})])).nullish()}),H=()=>s({category:o().nullish(),probability:o().nullish(),probabilityScore:d().nullish(),severity:o().nullish(),severityScore:d().nullish(),blocked:r().nullish()}),U=i(s({modality:o(),tokenCount:d()})).nullish(),ze=s({cachedContentTokenCount:d().nullish(),thoughtsTokenCount:d().nullish(),promptTokenCount:d().nullish(),candidatesTokenCount:d().nullish(),totalTokenCount:d().nullish(),trafficType:o().nullish(),promptTokensDetails:U,candidatesTokensDetails:U}),Be=()=>s({urlMetadata:i(s({retrievedUrl:o(),urlRetrievalStatus:o()})).nullish()}),Ve=N(()=>D(s({candidates:i(s({content:Re().nullish().or(s({}).strict()),finishReason:o().nullish(),finishMessage:o().nullish(),safetyRatings:i(H()).nullish(),groundingMetadata:Ie().nullish(),urlContextMetadata:Be().nullish()})),usageMetadata:ze.nullish(),promptFeedback:s({blockReason:o().nullish(),safetyRatings:i(H()).nullish()}).nullish(),serviceTier:o().nullish()}))),He=N(()=>D(s({candidates:i(s({content:Re().nullish(),finishReason:o().nullish(),finishMessage:o().nullish(),safetyRatings:i(H()).nullish(),groundingMetadata:Ie().nullish(),urlContextMetadata:Be().nullish()})).nullish(),usageMetadata:ze.nullish(),promptFeedback:s({blockReason:o().nullish(),safetyRatings:i(H()).nullish()}).nullish(),serviceTier:o().nullish()}))),Ue=M({id:`google.code_execution`,inputSchema:s({language:o().describe(`The programming language of the code.`),code:o().describe(`The code to be executed.`)}),outputSchema:s({outcome:o().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:o().describe(`The output from the code execution.`)})}),We=M({id:`google.enterprise_web_search`,inputSchema:N(()=>D(s({}))),outputSchema:N(()=>D(s({})))});s({fileSearchStoreNames:i(o()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:d().int().positive().describe(`The number of file search retrieval chunks to retrieve.`).optional(),metadataFilter:o().describe(`Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.`).optional()}).passthrough();var Ge=M({id:`google.file_search`,inputSchema:N(()=>D(s({}))),outputSchema:N(()=>D(s({})))}),Ke=M({id:`google.google_maps`,inputSchema:N(()=>D(s({}))),outputSchema:N(()=>D(s({})))});s({searchTypes:s({webSearch:s({}).optional(),imageSearch:s({}).optional()}).optional(),timeRangeFilter:s({startTime:o(),endTime:o()}).optional()}).passthrough();var qe={googleSearch:M({id:`google.google_search`,inputSchema:N(()=>D(s({}))),outputSchema:N(()=>D(s({})))}),enterpriseWebSearch:We,googleMaps:Ke,urlContext:M({id:`google.url_context`,inputSchema:N(()=>D(s({}))),outputSchema:N(()=>D(s({})))}),fileSearch:Ge,codeExecution:Ue,vertexRagStore:M({id:`google.vertex_rag_store`,inputSchema:N(()=>D(s({}))),outputSchema:N(()=>D(s({})))})},Je=N(()=>D(s({personGeneration:f([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:f([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish()}))),Ye=class e{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v4`}static[O](e){return T({modelId:e.modelId,config:e.config})}static[E](t){return new e(t.modelId,{},t.config)}get maxImagesPerCall(){return this.settings.maxImagesPerCall==null?W(this.modelId)?10:4:this.settings.maxImagesPerCall}get provider(){return this.config.provider}async doGenerate(e){return W(this.modelId)?this.doGenerateGemini(e):this.doGenerateImagen(e)}async doGenerateImagen(e){var t;let{prompt:n,n:r=1,size:i,aspectRatio:a=`1:1`,seed:o,providerOptions:s,headers:c,abortSignal:l,files:u,mask:d}=e,f=[];if(u!=null&&u.length>0)throw Error(`Google Gemini API does not support image editing with Imagen models. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.`);if(d!=null)throw Error(`Google Gemini API does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.`);i!=null&&f.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),o!=null&&f.push({type:`unsupported`,feature:`seed`,details:"This model does not support the `seed` option through this provider."});let p=await _({provider:`google`,providerOptions:s,schema:Je}),m=((t=this.config._internal)?.currentDate)?.call(t)??new Date,h={sampleCount:r};a!=null&&(h.aspectRatio=a),p&&Object.assign(h,p);let g={instances:[{prompt:n}],parameters:h},{responseHeaders:v,value:y}=await x({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:F(this.config.headers?await z(this.config.headers):void 0,c),body:g,failedResponseHandler:B,successfulResponseHandler:j(Xe),abortSignal:l,fetch:this.config.fetch});return{images:y.predictions.map(e=>e.bytesBase64Encoded),warnings:f,providerMetadata:{google:{images:y.predictions.map(()=>({}))}},response:{timestamp:m,modelId:this.modelId,headers:v}}}async doGenerateGemini(e){var t;let{prompt:n,n:r,size:i,aspectRatio:a,seed:o,providerOptions:s,headers:c,abortSignal:l,files:u,mask:d}=e,f=[];if(d!=null)throw Error(`Gemini image models do not support mask-based image editing.`);if(r!=null&&r>1)throw Error(`Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter.`);i!=null&&f.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."});let p=[];if(n!=null&&p.push({type:`text`,text:n}),u!=null&&u.length>0)for(let e of u)e.type===`url`?p.push({type:`file`,data:{type:`url`,url:new URL(e.url)},mediaType:`image/*`}):p.push({type:`file`,data:{type:`data`,data:typeof e.data==`string`?e.data:new Uint8Array(e.data)},mediaType:e.mediaType});let m=[{role:`user`,content:p}],h=await new Oe(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??A}).doGenerate({prompt:m,seed:o,providerOptions:{google:{responseModalities:[`IMAGE`],imageConfig:a?{aspectRatio:a}:void 0,...s?.google??{}}},headers:c,abortSignal:l}),g=((t=this.config._internal)?.currentDate)?.call(t)??new Date,_=[];for(let e of h.content)e.type===`file`&&e.mediaType.startsWith(`image/`)&&e.data.type===`data`&&_.push(P(e.data.data));return{images:_,warnings:f,providerMetadata:{google:{images:_.map(()=>({}))}},response:{timestamp:g,modelId:this.modelId,headers:h.response?.headers},usage:h.usage?{inputTokens:h.usage.inputTokens.total,outputTokens:h.usage.outputTokens.total,totalTokens:(h.usage.inputTokens.total??0)+(h.usage.outputTokens.total??0)}:void 0}}};function W(e){return e.startsWith(`gemini-`)}var Xe=N(()=>D(s({predictions:i(s({bytesBase64Encoded:o()})).default([])}))),Ze=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadFile(t){let n=await _({provider:`google`,providerOptions:t.providerOptions,schema:$e}),r=this.config.headers(),i=this.config.fetch??globalThis.fetch,a=[];t.filename!=null&&a.push({type:`unsupported`,feature:`filename`});let o=ee(t.data),s=t.mediaType,c=n?.displayName,l=await i(`${this.config.baseURL.replace(/\/v1beta$/,``)}/upload/v1beta/files`,{method:`POST`,headers:{...r,"X-Goog-Upload-Protocol":`resumable`,"X-Goog-Upload-Command":`start`,"X-Goog-Upload-Header-Content-Length":String(o.length),"X-Goog-Upload-Header-Content-Type":s,"Content-Type":`application/json`},body:JSON.stringify({file:{...c==null?{}:{display_name:c}}})});if(!l.ok){let t=await l.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to initiate resumable upload: ${l.status} ${t}`})}let u=l.headers.get(`x-goog-upload-url`);if(!u)throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`No upload URL returned from initiation request`});let d=await i(u,{method:`POST`,headers:{"Content-Length":String(o.length),"X-Goog-Upload-Offset":`0`,"X-Goog-Upload-Command":`upload, finalize`},body:o});if(!d.ok){let t=await d.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to upload file data: ${d.status} ${t}`})}let f=(await d.json()).file,p=n?.pollIntervalMs??2e3,m=n?.pollTimeoutMs??3e5,h=Date.now();for(;f.state===`PROCESSING`;){if(Date.now()-h>m)throw new e({name:`GOOGLE_FILES_UPLOAD_TIMEOUT`,message:`File processing timed out after ${m}ms`});await k(p);let{value:t}=await R({url:`${this.config.baseURL}/${f.name}`,headers:F(r),successfulResponseHandler:j(Qe),failedResponseHandler:B,fetch:this.config.fetch});f=t}if(f.state===`FAILED`)throw new e({name:`GOOGLE_FILES_UPLOAD_FAILED`,message:`File processing failed for ${f.name}`});return{warnings:a,providerReference:{google:f.uri},mediaType:f.mimeType??t.mediaType,providerMetadata:{google:{name:f.name,displayName:f.displayName,mimeType:f.mimeType,sizeBytes:f.sizeBytes,state:f.state,uri:f.uri,...f.createTime==null?{}:{createTime:f.createTime},...f.updateTime==null?{}:{updateTime:f.updateTime},...f.expirationTime==null?{}:{expirationTime:f.expirationTime},...f.sha256Hash==null?{}:{sha256Hash:f.sha256Hash}}}}}},Qe=N(()=>D(s({name:o(),displayName:o().nullish(),mimeType:o(),sizeBytes:o().nullish(),createTime:o().nullish(),updateTime:o().nullish(),expirationTime:o().nullish(),sha256Hash:o().nullish(),uri:o(),state:o()}))),$e=N(()=>D(s({displayName:o().nullish(),pollIntervalMs:d().positive().nullish(),pollTimeoutMs:d().positive().nullish()}).passthrough())),et=N(()=>D(s({pollIntervalMs:d().positive().nullish(),pollTimeoutMs:d().positive().nullish(),personGeneration:f([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),negativePrompt:o().nullish(),referenceImages:i(s({bytesBase64Encoded:o().nullish(),gcsUri:o().nullish()})).nullish()}).passthrough())),tt=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}get provider(){return this.config.provider}get maxVideosPerCall(){return 4}async doGenerate(t){var n;let r=((n=this.config._internal)?.currentDate)?.call(n)??new Date,i=[],a=await _({provider:`google`,providerOptions:t.providerOptions,schema:et}),o=[{}],s=o[0];if(t.prompt!=null&&(s.prompt=t.prompt),t.image!=null)if(t.image.type===`url`)i.push({type:`unsupported`,feature:`URL-based image input`,details:`Google Generative AI video models require base64-encoded images. URL will be ignored.`});else{let e=typeof t.image.data==`string`?t.image.data:te(t.image.data);s.image={inlineData:{mimeType:t.image.mediaType||`image/png`,data:e}}}a?.referenceImages!=null&&(s.referenceImages=a.referenceImages.map(e=>e.bytesBase64Encoded?{inlineData:{mimeType:`image/png`,data:e.bytesBase64Encoded}}:e.gcsUri?{gcsUri:e.gcsUri}:e));let c={sampleCount:t.n};if(t.aspectRatio&&(c.aspectRatio=t.aspectRatio),t.resolution&&(c.resolution={"1280x720":`720p`,"1920x1080":`1080p`,"3840x2160":`4k`}[t.resolution]||t.resolution),t.duration&&(c.durationSeconds=t.duration),t.seed&&(c.seed=t.seed),a!=null){let e=a;e.personGeneration!==void 0&&e.personGeneration!==null&&(c.personGeneration=e.personGeneration),e.negativePrompt!==void 0&&e.negativePrompt!==null&&(c.negativePrompt=e.negativePrompt);for(let[t,n]of Object.entries(e))[`pollIntervalMs`,`pollTimeoutMs`,`personGeneration`,`negativePrompt`,`referenceImages`].includes(t)||(c[t]=n)}let{value:l}=await x({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:F(await z(this.config.headers),t.headers),body:{instances:o,parameters:c},successfulResponseHandler:j(nt),failedResponseHandler:B,abortSignal:t.abortSignal,fetch:this.config.fetch}),u=l.name;if(!u)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No operation name returned from API`});let d=a?.pollIntervalMs??1e4,f=a?.pollTimeoutMs??6e5,p=Date.now(),m=l,h;for(;!m.done;){if(Date.now()-p>f)throw new e({name:`GOOGLE_VIDEO_GENERATION_TIMEOUT`,message:`Video generation timed out after ${f}ms`});if(await k(d),t.abortSignal?.aborted)throw new e({name:`GOOGLE_VIDEO_GENERATION_ABORTED`,message:`Video generation request was aborted`});let{value:n,responseHeaders:r}=await R({url:`${this.config.baseURL}/${u}`,headers:F(await z(this.config.headers),t.headers),successfulResponseHandler:j(nt),failedResponseHandler:B,abortSignal:t.abortSignal,fetch:this.config.fetch});m=n,h=r}if(m.error)throw new e({name:`GOOGLE_VIDEO_GENERATION_FAILED`,message:`Video generation failed: ${m.error.message}`});let g=m.response;if(!g?.generateVideoResponse?.generatedSamples||g.generateVideoResponse.generatedSamples.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No videos in response. Response: ${JSON.stringify(m)}`});let v=[],y=[],b=(await z(this.config.headers))?.[`x-goog-api-key`];for(let e of g.generateVideoResponse.generatedSamples)if(e.video?.uri){let t=b?`${e.video.uri}${e.video.uri.includes(`?`)?`&`:`?`}key=${b}`:e.video.uri;v.push({type:`url`,url:t,mediaType:`video/mp4`}),y.push({uri:e.video.uri})}if(v.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No valid videos in response`});return{videos:v,warnings:i,response:{timestamp:r,modelId:this.modelId,headers:h},providerMetadata:{google:{videos:y}}}}},nt=s({name:o().nullish(),done:r().nullish(),error:s({code:d().nullish(),message:o(),status:o().nullish()}).nullish(),response:s({generateVideoResponse:s({generatedSamples:i(s({video:s({uri:o().nullish()}).nullish()})).nullish()}).nullish()}).nullish()});function G(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.total_input_tokens??0,n=e.total_output_tokens??0,r=e.total_thought_tokens??0,i=e.total_cached_tokens??0;return{inputTokens:{total:e.total_input_tokens??void 0,noCache:e.total_input_tokens==null?void 0:t-i,cacheRead:e.total_cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:e.total_output_tokens==null&&e.total_thought_tokens==null?void 0:n+r,text:e.total_output_tokens??void 0,reasoning:e.total_thought_tokens??void 0},raw:e}}var rt={pdf:`application/pdf`,txt:`text/plain`,md:`text/markdown`,markdown:`text/markdown`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};function it(e){let t=e.toLowerCase();for(let[e,n]of Object.entries(rt))if(t.endsWith(`.${e}`))return n;return`application/octet-stream`}function at(e){let t=e.split(`/`),n=t[t.length-1];return n&&n.length>0?n:void 0}function ot({annotation:e,generateId:t}){switch(e.type){case`url_citation`:{let n=e;return n.url==null||n.url.length===0?void 0:{type:`source`,sourceType:`url`,id:t(),url:n.url,...n.title==null?{}:{title:n.title}}}case`file_citation`:{let n=e,r=n.url??n.document_uri??n.file_name;if(r==null||r.length===0)return;if(r.startsWith(`http://`)||r.startsWith(`https://`))return{type:`source`,sourceType:`url`,id:t(),url:r,...n.file_name==null?{}:{title:n.file_name}};let i=n.file_name??at(r),a=it(r);return{type:`source`,sourceType:`document`,id:t(),mediaType:a,title:n.file_name??i??r,...i==null?{}:{filename:i}}}case`place_citation`:{let n=e;return n.url==null||n.url.length===0?void 0:{type:`source`,sourceType:`url`,id:t(),url:n.url,...n.name==null?{}:{title:n.name}}}default:return}}function st({block:e,generateId:t}){let n=[];switch(e.type){case`url_context_result`:{let r=e.result??[];for(let e of r)e?.url==null||e.url.length===0||e.status!=null&&e.status!==`success`||n.push({type:`source`,sourceType:`url`,id:t(),url:e.url});break}case`google_search_result`:{let r=e.result??[];for(let e of r){let r=e?.url;r==null||r.length===0||n.push({type:`source`,sourceType:`url`,id:t(),url:r,...e.title==null?{}:{title:e.title}})}break}case`google_maps_result`:{let r=e.result??[];for(let e of r)for(let r of e.places??[])r.url==null||r.url.length===0||n.push({type:`source`,sourceType:`url`,id:t(),url:r.url,...r.name==null?{}:{title:r.name}});break}case`file_search_result`:{let r=e.result??[];for(let e of r){if(typeof e!=`object`||!e)continue;let r=e,i=r.url??r.document_uri??r.file_name;if(i==null||i.length===0)continue;if(i.startsWith(`http://`)||i.startsWith(`https://`)){n.push({type:`source`,sourceType:`url`,id:t(),url:i,...r.title==null?{}:{title:r.title}});continue}let a=r.file_name??at(i),o=it(i);n.push({type:`source`,sourceType:`document`,id:t(),mediaType:o,title:r.title??r.file_name??a??i,...a==null?{}:{filename:a}})}break}default:break}return n}function K({annotations:e,generateId:t}){if(e==null)return[];let n=new Set,r=[];for(let i of e){let e=ot({annotation:i,generateId:t});if(e==null)continue;let a=e.sourceType===`url`?`url:${e.url}`:`doc:${e.filename??e.title}`;n.has(a)||(n.add(a),r.push(e))}return r}function q({status:e,hasFunctionCall:t}){switch(e){case`completed`:return t?`tool-calls`:`stop`;case`requires_action`:return`tool-calls`;case`failed`:return`error`;case`incomplete`:return`length`;case`cancelled`:return`other`;default:return`other`}}var ct=new Set([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),lt=new Set([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]);function ut(e){return e.replace(/_call$/,``)}function dt(e){return e.replace(/_result$/,``)}function ft({warnings:e,generateId:t,includeRawChunks:n,serviceTier:r}){let i,a,o=r,s,c=!1,l=new Map,u=new Set;function d(e){return e.sourceType===`url`?`url:${e.url}`:`doc:${e.filename??e.title}`}return new TransformStream({start(t){t.enqueue({type:`stream-start`,warnings:e})},transform(e,r){if(n&&r.enqueue({type:`raw`,rawValue:e.rawValue}),!e.success){s=`failed`,r.enqueue({type:`error`,error:e.error});return}let f=e.value,p=f.event_type;switch(p){case`interaction.created`:{let e=f.interaction;i=e?.id!=null&&e.id.length>0?e.id:void 0;let t=e?.created,n;if(typeof t==`string`){let e=new Date(t);Number.isNaN(e.getTime())||(n=e)}r.enqueue({type:`response-metadata`,...i==null?{}:{id:i},modelId:e?.model,...n?{timestamp:n}:{}});break}case`step.start`:{let e=f,n=e.step,a=e.index,o=`${i??`interaction`}:${a}`,s=n?.type;if(s===`model_output`){let e=n?.content?.[0];if(e?.type===`text`){l.set(a,{kind:`text`,id:o,emittedSourceKeys:new Set}),r.enqueue({type:`text-start`,id:o});let n=K({annotations:e.annotations,generateId:t});for(let e of n){let t=d(e);u.has(t)||(u.add(t),r.enqueue(e))}}else e?.type===`image`?l.set(a,{kind:`image`,id:o,...e.data==null?{}:{data:e.data},...e.mime_type==null?{}:{mimeType:e.mime_type},...e.uri==null?{}:{uri:e.uri}}):l.set(a,{kind:`pending_model_output`,id:o})}else if(s===`thought`){let e=n?.signature;if(l.set(a,{kind:`reasoning`,id:o,...e==null?{}:{signature:e}}),r.enqueue({type:`reasoning-start`,id:o}),Array.isArray(n?.summary))for(let e of n.summary)e?.type===`text`&&typeof e.text==`string`&&r.enqueue({type:`reasoning-delta`,id:o,delta:e.text})}else if(s===`function_call`){let e=n?.id??o,t=n?.name??`unknown`;c=!0;let i={kind:`function_call`,id:o,toolCallId:e,toolName:t,argumentsAccum:``,...n?.signature==null?{}:{signature:n.signature}};l.set(a,i),r.enqueue({type:`tool-input-start`,id:e,toolName:t})}else if(s!=null&&ct.has(s)){let e=s===`mcp_server_tool_call`?n?.name??`mcp_server_tool`:ut(s),t={kind:`builtin_tool_call`,id:o,blockType:s,toolCallId:n?.id??o,toolName:e,arguments:n?.arguments??{},callEmitted:!1};l.set(a,t)}else if(s!=null&&lt.has(s)){let e=s===`mcp_server_tool_result`?n?.name??`mcp_server_tool`:dt(s),t={kind:`builtin_tool_result`,id:o,blockType:s,callId:n?.call_id??o,toolName:e,result:n?.result??null,...n?.is_error==null?{}:{isError:n.is_error},resultEmitted:!1};l.set(a,t)}else l.set(a,{kind:`unknown`,id:o});break}case`step.delta`:{let e=f,n=l.get(e.index);if(n==null)break;let a=e.delta?.type;if(n.kind===`pending_model_output`&&(a===`text`||a===`text_annotation`||a===`text_annotation_delta`)){let t={kind:`text`,id:n.id,emittedSourceKeys:new Set};l.set(e.index,t),n=t,r.enqueue({type:`text-start`,id:t.id})}if(a===`image`&&(n.kind===`pending_model_output`||n.kind===`text`||n.kind===`image`)){let t=e.delta,a={};i!=null&&(a.interactionId=i);let o=Object.keys(a).length>0?{google:a}:void 0;t?.data!=null&&t.data.length>0?r.enqueue({type:`file`,mediaType:t.mime_type??`image/png`,data:{type:`data`,data:t.data},...o?{providerMetadata:o}:{}}):t?.uri!=null&&t.uri.length>0&&r.enqueue({type:`file`,mediaType:t.mime_type??`image/png`,data:{type:`url`,url:new URL(t.uri)},...o?{providerMetadata:o}:{}}),n.kind===`image`&&(n.data=void 0,n.uri=void 0);break}let o=e.delta;if(n.kind===`text`&&o?.type===`text`){let e=o.text??``;e.length>0&&r.enqueue({type:`text-delta`,id:n.id,delta:e})}else if(n.kind===`text`&&(o?.type===`text_annotation`||o?.type===`text_annotation_delta`)){let e=K({annotations:o.annotations,generateId:t});for(let t of e){let e=d(t);u.has(e)||(u.add(e),n.emittedSourceKeys.add(e),r.enqueue(t))}}else if(n.kind===`image`&&o?.type===`image`)o.data!=null&&(n.data=o.data),o.mime_type!=null&&(n.mimeType=o.mime_type),o.uri!=null&&(n.uri=o.uri);else if(n.kind===`reasoning`){if(o?.type===`thought_summary`){let e=o.content;e?.type===`text`&&typeof e.text==`string`&&r.enqueue({type:`reasoning-delta`,id:n.id,delta:e.text})}else if(o?.type===`thought_signature`){let e=o.signature;e!=null&&(n.signature=e)}}else if(n.kind===`function_call`&&o?.type===`arguments_delta`){let e=typeof o.arguments==`string`?o.arguments:``;e.length>0&&(n.argumentsAccum+=e,r.enqueue({type:`tool-input-delta`,id:n.toolCallId,delta:e})),o.id!=null&&(n.toolCallId=o.id),o.signature!=null&&(n.signature=o.signature),c=!0}else n.kind===`builtin_tool_call`&&o?.type===n.blockType?(o.id!=null&&(n.toolCallId=o.id),o.arguments!=null&&typeof o.arguments==`object`&&(n.arguments=o.arguments),o.name!=null&&n.blockType===`mcp_server_tool_call`&&(n.toolName=o.name)):n.kind===`builtin_tool_result`&&o?.type===n.blockType&&(o.call_id!=null&&(n.callId=o.call_id),o.result!==void 0&&(n.result=o.result),o.is_error!=null&&(n.isError=o.is_error),o.name!=null&&n.blockType===`mcp_server_tool_result`&&(n.toolName=o.name));break}case`step.stop`:{let e=f,n=l.get(e.index);if(n==null)break;if(n.kind===`text`){let e=i==null?void 0:{google:{interactionId:i}};r.enqueue({type:`text-end`,id:n.id,...e?{providerMetadata:e}:{}})}else if(n.kind===`reasoning`){let e={};n.signature!=null&&(e.signature=n.signature),i!=null&&(e.interactionId=i);let t=Object.keys(e).length>0?{google:e}:void 0;r.enqueue({type:`reasoning-end`,id:n.id,...t?{providerMetadata:t}:{}})}else if(n.kind===`image`){let e={};i!=null&&(e.interactionId=i);let t=Object.keys(e).length>0?{google:e}:void 0;n.data!=null&&n.data.length>0?r.enqueue({type:`file`,mediaType:n.mimeType??`image/png`,data:{type:`data`,data:n.data},...t?{providerMetadata:t}:{}}):n.uri!=null&&n.uri.length>0&&r.enqueue({type:`file`,mediaType:n.mimeType??`image/png`,data:{type:`url`,url:new URL(n.uri)},...t?{providerMetadata:t}:{}})}else if(n.kind===`function_call`){let e=n.argumentsAccum.length>0?n.argumentsAccum:`{}`;r.enqueue({type:`tool-input-end`,id:n.toolCallId});let t={};n.signature!=null&&(t.signature=n.signature),i!=null&&(t.interactionId=i);let a=Object.keys(t).length>0?{google:t}:void 0;r.enqueue({type:`tool-call`,toolCallId:n.toolCallId,toolName:n.toolName,input:e,...a?{providerMetadata:a}:{}})}else if(n.kind===`builtin_tool_call`&&!n.callEmitted)r.enqueue({type:`tool-call`,toolCallId:n.toolCallId,toolName:n.toolName,input:JSON.stringify(n.arguments??{}),providerExecuted:!0}),n.callEmitted=!0;else if(n.kind===`builtin_tool_result`&&!n.resultEmitted){r.enqueue({type:`tool-result`,toolCallId:n.callId,toolName:n.toolName,result:n.result??null}),n.resultEmitted=!0;let e=st({block:{type:n.blockType,call_id:n.callId,result:n.result},generateId:t});for(let t of e){let e=d(t);u.has(e)||(u.add(e),r.enqueue(t))}}l.delete(e.index);break}case`interaction.status_update`:case`interaction.in_progress`:case`interaction.requires_action`:{let e=f;s=e.status==null?p===`interaction.requires_action`?`requires_action`:`in_progress`:e.status;break}case`interaction.completed`:{let e=f.interaction;e?.id!=null&&e.id.length>0&&(i=e.id),e?.status!=null&&(s=e.status),e?.usage!=null&&(a=e.usage),e?.service_tier!=null&&(o=e.service_tier);break}case`error`:{let e=f;s=`failed`;let t=e.error??{message:`Unknown interaction error`};r.enqueue({type:`error`,error:t});break}default:break}},flush(e){let t={unified:q({status:s,hasFunctionCall:c}),raw:s},n={google:{...i==null?{}:{interactionId:i},...o==null?{}:{serviceTier:o}}};e.enqueue({type:`finish`,finishReason:t,usage:G(a),providerMetadata:n})}})}function pt({prompt:e,previousInteractionId:t,store:n,mediaResolution:r}){let i=[],a=t!=null&&n===!1,o=t!=null&&n!==!1;a&&i.push({type:`other`,message:`google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted.`});let s=o?ht({prompt:e,previousInteractionId:t}):e,c=[],l=[];for(let e of s)switch(e.role){case`system`:c.push(e.content);break;case`user`:{let t=[];for(let n of e.content)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`file`){let e=mt({part:n,warnings:i,mediaResolution:r});e!=null&&t.push(e)}let n=yt(t);n.length>0&&l.push({type:`user_input`,content:n});break}case`assistant`:{let t=[],n=()=>{t.length>0&&(l.push({type:`model_output`,content:t}),t=[])};for(let a of e.content)if(a.type===`text`)t.push({type:`text`,text:a.text});else if(a.type===`reasoning`){n();let e=a.providerOptions?.google?.signature;l.push({type:`thought`,...e==null?{}:{signature:e},summary:a.text.length>0?[{type:`text`,text:a.text}]:void 0})}else if(a.type===`file`){let e=mt({part:a,warnings:i,mediaResolution:r});e!=null&&t.push(e)}else if(a.type===`tool-call`){n();let e=a.providerOptions?.google?.signature,t=typeof a.input==`string`?gt(a.input):a.input??{};l.push({type:`function_call`,id:a.toolCallId,name:a.toolName,arguments:t,...e==null?{}:{signature:e}})}else i.push({type:`other`,message:`google.interactions: unsupported assistant content part type "${a.type}"; part dropped.`});n();break}case`tool`:{let t=[];for(let n of e.content){if(n.type!==`tool-result`){i.push({type:`other`,message:`google.interactions: unsupported tool message part type "${n.type}"; part dropped.`});continue}let e=_t({toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,signature:n.providerOptions?.google?.signature,warnings:i});t.push(e)}t.length>0&&l.push({type:`user_input`,content:t});break}}return{input:l,systemInstruction:c.length>0?c.join(`
6
+ `})}return{systemInstruction:r.length>0&&!o?{parts:r}:void 0,contents:i}}function _e(e){return e.includes(`/`)?e:`models/${e}`}var ve=P(()=>D(s({responseModalities:i(f([`TEXT`,`IMAGE`])).optional(),thinkingConfig:s({thinkingBudget:d().optional(),includeThoughts:r().optional(),thinkingLevel:f([`minimal`,`low`,`medium`,`high`]).optional()}).optional(),cachedContent:o().optional(),structuredOutputs:r().optional(),safetySettings:i(s({category:f([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:f([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:f([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:r().optional(),labels:a(o(),o()).optional(),mediaResolution:f([`MEDIA_RESOLUTION_UNSPECIFIED`,`MEDIA_RESOLUTION_LOW`,`MEDIA_RESOLUTION_MEDIUM`,`MEDIA_RESOLUTION_HIGH`]).optional(),imageConfig:s({aspectRatio:f([`1:1`,`2:3`,`3:2`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`,`1:8`,`8:1`,`1:4`,`4:1`]).optional(),imageSize:f([`1K`,`2K`,`4K`,`512`]).optional()}).optional(),retrievalConfig:s({latLng:s({latitude:d(),longitude:d()}).optional()}).optional(),streamFunctionCallArguments:r().optional(),serviceTier:f([`standard`,`flex`,`priority`]).optional(),sharedRequestType:f([`priority`,`flex`,`standard`]).optional(),requestType:f([`shared`]).optional()})));function ye({tools:e,toolChoice:t,modelId:r,isVertexProvider:i=!1}){e=e?.length?e:void 0;let a=[],o=[`gemini-flash-latest`,`gemini-flash-lite-latest`,`gemini-pro-latest`].some(e=>e===r),s=r.includes(`gemini-2`)||r.includes(`gemini-3`)||r.includes(`nano-banana`)||o,c=r.includes(`gemini-3`),l=r.includes(`gemini-2.5`)||r.includes(`gemini-3`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:a};let u=e.some(e=>e.type===`function`),d=e.some(e=>e.type===`provider`);if(u&&d&&!c&&a.push({type:`unsupported`,feature:`combination of function and provider-defined tools`}),d){let n=[];if(e.filter(e=>e.type===`provider`).forEach(e=>{switch(e.id){case`google.google_search`:s?n.push({googleSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Google Search requires Gemini 2.0 or newer.`});break;case`google.enterprise_web_search`:s?n.push({enterpriseWebSearch:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Enterprise Web Search requires Gemini 2.0 or newer.`});break;case`google.url_context`:s?n.push({urlContext:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:s?n.push({codeExecution:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The code execution tool is not supported with other Gemini models than Gemini 2.`});break;case`google.file_search`:l?n.push({fileSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The file search tool is only supported with Gemini 2.5 models and Gemini 3 models.`});break;case`google.vertex_rag_store`:s?n.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:e.args.ragCorpus},similarity_top_k:e.args.topK}}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The RAG store tool is not supported with other Gemini models than Gemini 2.`});break;case`google.google_maps`:s?n.push({googleMaps:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer.`});break;default:a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`});break}}),u&&c&&n.length>0){let r=[];for(let t of e)t.type===`function`&&r.push({name:t.name,description:t.description??``,parameters:H(t.inputSchema)});let o={functionCallingConfig:{mode:`VALIDATED`},...!i&&{includeServerSideToolInvocations:!0}};if(t!=null)switch(t.type){case`auto`:break;case`none`:o.functionCallingConfig={mode:`NONE`};break;case`required`:o.functionCallingConfig={mode:`ANY`};break;case`tool`:o.functionCallingConfig={mode:`ANY`,allowedFunctionNames:[t.toolName]};break}return{tools:[...n,{functionDeclarations:r}],toolConfig:o,toolWarnings:a}}return{tools:n.length>0?n:void 0,toolConfig:void 0,toolWarnings:a}}let f=[],p=!1;for(let t of e)switch(t.type){case`function`:f.push({name:t.name,description:t.description??``,parameters:H(t.inputSchema)}),t.strict===!0&&(p=!0);break;default:a.push({type:`unsupported`,feature:`function tool ${t.name}`});break}if(t==null)return{tools:[{functionDeclarations:f}],toolConfig:p?{functionCallingConfig:{mode:`VALIDATED`}}:void 0,toolWarnings:a};let m=t.type;switch(m){case`auto`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`AUTO`}},toolWarnings:a};case`none`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:a};case`required`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`}},toolWarnings:a};case`tool`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:a};default:throw new n({functionality:`tool choice type: ${m}`})}}var be=class{constructor(){this.accumulatedArgs={},this.jsonText=``,this.pathStack=[],this.stringOpen=!1}processPartialArgs(e){let t=``;for(let n of e){let e=n.jsonPath.replace(/^\$\./,``);if(!e)continue;let r=xe(e),i=Se(this.accumulatedArgs,r);if(n.stringValue!=null&&i!==void 0){let e=JSON.stringify(n.stringValue).slice(1,-1);Ce(this.accumulatedArgs,r,i+n.stringValue),t+=e;continue}let a=we(n);a!=null&&(Ce(this.accumulatedArgs,r,a.value),t+=this.emitNavigationTo(r,n,a.json))}return this.jsonText+=t,{currentJSON:this.accumulatedArgs,textDelta:t}}finalize(){let e=JSON.stringify(this.accumulatedArgs);return{finalJSON:e,closingDelta:e.slice(this.jsonText.length)}}ensureRoot(){return this.pathStack.length===0?(this.pathStack.push({segment:``,isArray:!1,childCount:0}),`{`):``}emitNavigationTo(e,t,n){let r=``;this.stringOpen&&=(r+=`"`,!1),r+=this.ensureRoot();let i=e.slice(0,-1),a=e[e.length-1],o=this.findCommonStackDepth(i);return r+=this.closeDownTo(o),r+=this.openDownTo(i,a),r+=this.emitLeaf(a,t,n),r}findCommonStackDepth(e){let t=Math.min(this.pathStack.length-1,e.length),n=0;for(let r=0;r<t&&this.pathStack[r+1].segment===e[r];r++)n++;return n+1}closeDownTo(e){let t=``;for(;this.pathStack.length>e;){let e=this.pathStack.pop();t+=e.isArray?`]`:`}`}return t}openDownTo(e,t){let n=``,r=this.pathStack.length-1;for(let i=r;i<e.length;i++){let r=e[i],a=this.pathStack[this.pathStack.length-1];a.childCount>0&&(n+=`,`),a.childCount++,typeof r==`string`&&(n+=`${JSON.stringify(r)}:`);let o=typeof(i+1<e.length?e[i+1]:t)==`number`;n+=o?`[`:`{`,this.pathStack.push({segment:r,isArray:o,childCount:0})}return n}emitLeaf(e,t,n){let r=``,i=this.pathStack[this.pathStack.length-1];return i.childCount>0&&(r+=`,`),i.childCount++,typeof e==`string`&&(r+=`${JSON.stringify(e)}:`),t.stringValue!=null&&t.willContinue?(r+=n.slice(0,-1),this.stringOpen=!0):r+=n,r}};function xe(e){let t=[];for(let n of e.split(`.`)){let e=n.indexOf(`[`);if(e===-1)t.push(n);else{e>0&&t.push(n.slice(0,e));for(let e of n.matchAll(/\[(\d+)\]/g))t.push(parseInt(e[1],10))}}return t}function Se(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}function Ce(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e],i=t[e+1];r[n]??(r[n]=typeof i==`number`?[]:{}),r=r[n]}r[t[t.length-1]]=n}function we(e){let t=e.stringValue??e.numberValue??e.boolValue;if(t!=null)return{value:t,json:JSON.stringify(t)};if(`nullValue`in e)return{value:null,json:`null`}}function Te({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`tool-calls`:`stop`;case`MAX_TOKENS`:return`length`;case`IMAGE_SAFETY`:case`RECITATION`:case`SAFETY`:case`BLOCKLIST`:case`PROHIBITED_CONTENT`:case`SPII`:return`content-filter`;case`MALFORMED_FUNCTION_CALL`:return`error`;default:return`other`}}var Ee=class e{constructor(e,t){this.specificationVersion=`v4`,this.modelId=e,this.config=t,this.generateId=t.generateId??j}static[O](e){return T({modelId:e.modelId,config:e.config})}static[E](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,reasoning:f,providerOptions:p},{isStreaming:m=!1}={}){let h=[],g=this.config.provider.includes(`vertex`)?[`googleVertex`,`vertex`]:[`google`],v;for(let e of g)if(v=await _({provider:e,providerOptions:p,schema:ve}),v!=null)break;v==null&&!g.includes(`google`)&&(v=await _({provider:`google`,providerOptions:p,schema:ve}));let y=this.config.provider.startsWith(`google.vertex.`);u?.some(e=>e.type===`provider`&&e.id===`google.vertex_rag_store`)&&!y&&h.push({type:`other`,message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`}),v?.streamFunctionCallArguments&&!y&&h.push({type:`other`,message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`}),v?.serviceTier&&y&&h.push({type:`other`,message:`'serviceTier' is a Gemini API option and is not supported on Vertex AI. Use 'sharedRequestType' (and optionally 'requestType') instead. See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/priority-paygo`}),(v?.sharedRequestType||v?.requestType)&&!y&&h.push({type:`other`,message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${this.config.provider}).`});let b=y&&(v?.sharedRequestType||v?.requestType)?{...v.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":v.sharedRequestType},...v.requestType&&{"X-Vertex-AI-LLM-Request-Type":v.requestType}}:void 0,x=y?void 0:v?.serviceTier,S=this.modelId.toLowerCase().startsWith(`gemma-`),{contents:C,systemInstruction:w}=ge(e,{isGemmaModel:S,providerOptionsNames:g,supportsFunctionResponseParts:this.modelId.startsWith(`gemini-3`)}),{tools:T,toolConfig:E,toolWarnings:D}=ye({tools:u,toolChoice:d,modelId:this.modelId,isVertexProvider:y}),O=Ae({reasoning:f,modelId:this.modelId,warnings:h}),k=v?.thinkingConfig||O?{...O,...v?.thinkingConfig}:void 0,A=m&&y?v?.streamFunctionCallArguments??!1:void 0,j=E||A||v?.retrievalConfig?{...E,...A&&{functionCallingConfig:{...E?.functionCallingConfig,streamFunctionCallArguments:!0}},...v?.retrievalConfig&&{retrievalConfig:v.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&(v?.structuredOutputs??!0)?H(c.schema):void 0,...v?.audioTimestamp&&{audioTimestamp:v.audioTimestamp},responseModalities:v?.responseModalities,thinkingConfig:k,...v?.mediaResolution&&{mediaResolution:v.mediaResolution},...v?.imageConfig&&{imageConfig:v.imageConfig}},contents:C,systemInstruction:S?void 0:w,safetySettings:v?.safetySettings,tools:T,toolConfig:j,cachedContent:v?.cachedContent,labels:v?.labels,serviceTier:x},warnings:[...h,...D],providerOptionsNames:g,extraHeaders:b}}async doGenerate(e){let{args:t,warnings:n,providerOptionsNames:r,extraHeaders:i}=await this.getArgs(e),a=e=>Object.fromEntries(r.map(t=>[t,e])),o=I(this.config.headers?await B(this.config.headers):void 0,e.headers,i),{responseHeaders:s,value:c,rawValue:l}=await x({url:`${this.config.baseURL}/${_e(this.modelId)}:generateContent`,headers:o,body:t,failedResponseHandler:V,successfulResponseHandler:M(Be),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=c.candidates[0],d=[],f=u.content?.parts??[],p=c.usageMetadata,m,h;for(let e of f)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();m=t,d.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in e&&e.codeExecutionResult)d.push({type:`tool-result`,toolCallId:m,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output??``}}),m=void 0;else if(`text`in e&&e.text!=null){let t=e.thoughtSignature?a({thoughtSignature:e.thoughtSignature}):void 0;if(e.text.length===0){if(t!=null&&d.length>0){let e=d[d.length-1];e.providerMetadata=t}}else d.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:t})}else if(`functionCall`in e&&e.functionCall.name!=null)d.push({type:`tool-call`,toolCallId:e.functionCall.id??this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args??{}),providerMetadata:e.thoughtSignature?a({thoughtSignature:e.thoughtSignature}):void 0});else if(`inlineData`in e){let t=e.thought===!0,n=!!e.thoughtSignature;d.push({type:t?`reasoning-file`:`file`,data:{type:`data`,data:e.inlineData.data},mediaType:e.inlineData.mimeType,providerMetadata:n?a({thoughtSignature:e.thoughtSignature}):void 0})}else if(`toolCall`in e&&e.toolCall){let t=e.toolCall.id??this.config.generateId();h=t,d.push({type:`tool-call`,toolCallId:t,toolName:`server:${e.toolCall.toolType}`,input:JSON.stringify(e.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:e.thoughtSignature?a({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolCall.toolType}):a({serverToolCallId:t,serverToolType:e.toolCall.toolType})})}else if(`toolResponse`in e&&e.toolResponse){let t=h??e.toolResponse.id??this.config.generateId();d.push({type:`tool-result`,toolCallId:t,toolName:`server:${e.toolResponse.toolType}`,result:e.toolResponse.response??{},providerMetadata:e.thoughtSignature?a({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolResponse.toolType}):a({serverToolCallId:t,serverToolType:e.toolResponse.toolType})}),h=void 0}let g=Ne({groundingMetadata:u.groundingMetadata,generateId:this.config.generateId})??[];for(let e of g)d.push(e);return{content:d,finishReason:{unified:Te({finishReason:u.finishReason,hasToolCalls:d.some(e=>e.type===`tool-call`&&!e.providerExecuted)}),raw:u.finishReason??void 0},usage:le(p),warnings:n,providerMetadata:a({promptFeedback:c.promptFeedback??null,groundingMetadata:u.groundingMetadata??null,urlContextMetadata:u.urlContextMetadata??null,safetyRatings:u.safetyRatings??null,usageMetadata:p??null,finishMessage:u.finishMessage??null,serviceTier:p?.serviceTier??null}),request:{body:t},response:{headers:s,body:l}}}async doStream(e){let{args:t,warnings:n,providerOptionsNames:r,extraHeaders:i}=await this.getArgs(e,{isStreaming:!0}),a=e=>Object.fromEntries(r.map(t=>[t,e])),o=I(this.config.headers?await B(this.config.headers):void 0,e.headers,i),{responseHeaders:s,value:c}=await x({url:`${this.config.baseURL}/${_e(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:t,failedResponseHandler:V,successfulResponseHandler:L(Ve),abortSignal:e.abortSignal,fetch:this.config.fetch}),l={unified:`other`,raw:void 0},u,d,f=null,p=null,m=this.config.generateId,h=!1,g=null,_=null,v=0,y=new Set,b,S,C=[],w=e=>{let t=C.pop();if(t==null)return;let{finalJSON:n,closingDelta:r}=t.accumulator.finalize();r.length>0&&e.enqueue({type:`tool-input-delta`,id:t.toolCallId,delta:r,providerMetadata:t.providerMetadata}),e.enqueue({type:`tool-input-end`,id:t.toolCallId,providerMetadata:t.providerMetadata}),e.enqueue({type:`tool-call`,toolCallId:t.toolCallId,toolName:t.toolName,input:n,providerMetadata:t.providerMetadata}),h=!0};return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value,i=r.usageMetadata;i!=null&&(u=i);let o=r.candidates?.[0];if(o==null)return;let s=o.content;o.groundingMetadata!=null&&(f=o.groundingMetadata),o.urlContextMetadata!=null&&(p=o.urlContextMetadata);let c=Ne({groundingMetadata:o.groundingMetadata,generateId:m});if(c!=null)for(let e of c)e.sourceType===`url`&&!y.has(e.url)&&(y.add(e.url),n.enqueue(e));if(s!=null){let e=s.parts??[];for(let t of e)if(`executableCode`in t&&t.executableCode?.code){let e=m();b=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=b;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output??``}}),b=void 0)}else if(`text`in t&&t.text!=null){let e=t.thoughtSignature?a({thoughtSignature:t.thoughtSignature}):void 0;t.text.length===0?e!=null&&g!==null&&n.enqueue({type:`text-delta`,id:g,delta:``,providerMetadata:e}):t.thought===!0?(g!==null&&(n.enqueue({type:`text-end`,id:g}),g=null),_===null&&(_=String(v++),n.enqueue({type:`reasoning-start`,id:_,providerMetadata:e})),n.enqueue({type:`reasoning-delta`,id:_,delta:t.text,providerMetadata:e})):(_!==null&&(n.enqueue({type:`reasoning-end`,id:_}),_=null),g===null&&(g=String(v++),n.enqueue({type:`text-start`,id:g,providerMetadata:e})),n.enqueue({type:`text-delta`,id:g,delta:t.text,providerMetadata:e}))}else if(`inlineData`in t){g!==null&&(n.enqueue({type:`text-end`,id:g}),g=null),_!==null&&(n.enqueue({type:`reasoning-end`,id:_}),_=null);let e=t.thought===!0,r=t.thoughtSignature?a({thoughtSignature:t.thoughtSignature}):void 0;n.enqueue({type:e?`reasoning-file`:`file`,mediaType:t.inlineData.mimeType,data:{type:`data`,data:t.inlineData.data},providerMetadata:r})}else if(`toolCall`in t&&t.toolCall){let e=t.toolCall.id??m();S=e;let r=a({...t.thoughtSignature?{thoughtSignature:t.thoughtSignature}:{},serverToolCallId:e,serverToolType:t.toolCall.toolType});n.enqueue({type:`tool-call`,toolCallId:e,toolName:`server:${t.toolCall.toolType}`,input:JSON.stringify(t.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:r})}else if(`toolResponse`in t&&t.toolResponse){let e=S??t.toolResponse.id??m(),r=a({...t.thoughtSignature?{thoughtSignature:t.thoughtSignature}:{},serverToolCallId:e,serverToolType:t.toolResponse.toolType});n.enqueue({type:`tool-result`,toolCallId:e,toolName:`server:${t.toolResponse.toolType}`,result:t.toolResponse.response??{},providerMetadata:r}),S=void 0}for(let t of e){if(!(`functionCall`in t))continue;let e=t.thoughtSignature?a({thoughtSignature:t.thoughtSignature}):void 0,r=t.functionCall.partialArgs!=null||t.functionCall.name!=null&&t.functionCall.willContinue===!0,i=t.functionCall.name==null&&t.functionCall.args==null&&t.functionCall.partialArgs==null&&t.functionCall.willContinue==null,o=t.functionCall.name!=null&&t.functionCall.args!=null&&t.functionCall.partialArgs==null,s=t.functionCall.name!=null&&t.functionCall.args==null&&t.functionCall.partialArgs==null&&t.functionCall.willContinue!==!0;if(r){if(t.functionCall.name!=null){let r=t.functionCall.id??m(),i=new be;if(C.push({toolCallId:r,toolName:t.functionCall.name,accumulator:i,providerMetadata:e}),n.enqueue({type:`tool-input-start`,id:r,toolName:t.functionCall.name,providerMetadata:e}),t.functionCall.partialArgs!=null){let a=t.functionCall.partialArgs,{textDelta:o}=i.processPartialArgs(a);o.length>0&&n.enqueue({type:`tool-input-delta`,id:r,delta:o,providerMetadata:e}),t.functionCall.willContinue!==!0&&a.every(e=>e.willContinue!==!0)&&w(n)}}else if(t.functionCall.partialArgs!=null&&C.length>0){let r=C[C.length-1],i=t.functionCall.partialArgs,{textDelta:a}=r.accumulator.processPartialArgs(i);a.length>0&&n.enqueue({type:`tool-input-delta`,id:r.toolCallId,delta:a,providerMetadata:e}),t.functionCall.willContinue!==!0&&i.every(e=>e.willContinue!==!0)&&w(n)}}else if(i&&C.length>0)w(n);else if(o){let r=t.functionCall.id??m(),i=t.functionCall.name,a=typeof t.functionCall.args==`string`?t.functionCall.args:JSON.stringify(t.functionCall.args??{});n.enqueue({type:`tool-input-start`,id:r,toolName:i,providerMetadata:e}),n.enqueue({type:`tool-input-delta`,id:r,delta:a,providerMetadata:e}),n.enqueue({type:`tool-input-end`,id:r,providerMetadata:e}),n.enqueue({type:`tool-call`,toolCallId:r,toolName:i,input:a,providerMetadata:e}),h=!0}else if(s){let r=t.functionCall.id??m(),i=t.functionCall.name;n.enqueue({type:`tool-input-start`,id:r,toolName:i,providerMetadata:e}),n.enqueue({type:`tool-input-end`,id:r,providerMetadata:e}),n.enqueue({type:`tool-call`,toolCallId:r,toolName:i,input:`{}`,providerMetadata:e}),h=!0}}}o.finishReason!=null&&(l={unified:Te({finishReason:o.finishReason,hasToolCalls:h}),raw:o.finishReason},d=a({promptFeedback:r.promptFeedback??null,groundingMetadata:f,urlContextMetadata:p,safetyRatings:o.safetyRatings??null,usageMetadata:i??null,finishMessage:o.finishMessage??null,serviceTier:u?.serviceTier??null}))},flush(e){g!==null&&e.enqueue({type:`text-end`,id:g}),_!==null&&e.enqueue({type:`reasoning-end`,id:_}),e.enqueue({type:`finish`,finishReason:l,usage:le(u),providerMetadata:d})}})),response:{headers:s},request:{body:t}}}};function De(e){return/gemini-3[\.\-]/i.test(e)||/gemini-3$/i.test(e)}function Oe(){return 65536}function ke(e){let t=e.toLowerCase();return t.includes(`2.5-pro`)||t.includes(`gemini-3-pro-image`)?32768:24576}function Ae({reasoning:e,modelId:t,warnings:n}){if(C(e))return De(t)&&!t.includes(`gemini-3-pro-image`)?je({reasoning:e,warnings:n}):Me({reasoning:e,modelId:t,warnings:n})}function je({reasoning:e,warnings:t}){if(e===`none`)return{thinkingLevel:`minimal`};let n=b({reasoning:e,effortMap:{minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,xhigh:`high`},warnings:t});if(n!=null)return{thinkingLevel:n}}function Me({reasoning:e,modelId:t,warnings:n}){if(e===`none`)return{thinkingBudget:0};let r=y({reasoning:e,maxOutputTokens:Oe(),maxReasoningBudget:ke(t),minReasoningBudget:0,warnings:n});if(r!=null)return{thinkingBudget:r}}function Ne({groundingMetadata:e,generateId:t}){if(!e?.groundingChunks)return;let n=[];for(let r of e.groundingChunks)if(r.web!=null)n.push({type:`source`,sourceType:`url`,id:t(),url:r.web.uri,title:r.web.title??void 0});else if(r.image!=null)n.push({type:`source`,sourceType:`url`,id:t(),url:r.image.sourceUri,title:r.image.title??void 0});else if(r.retrievedContext!=null){let e=r.retrievedContext.uri,i=r.retrievedContext.fileSearchStore;if(e&&(e.startsWith(`http://`)||e.startsWith(`https://`)))n.push({type:`source`,sourceType:`url`,id:t(),url:e,title:r.retrievedContext.title??void 0});else if(e){let i=r.retrievedContext.title??`Unknown Document`,a=`application/octet-stream`,o;e.endsWith(`.pdf`)?(a=`application/pdf`,o=e.split(`/`).pop()):e.endsWith(`.txt`)?(a=`text/plain`,o=e.split(`/`).pop()):e.endsWith(`.docx`)?(a=`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,o=e.split(`/`).pop()):e.endsWith(`.doc`)?(a=`application/msword`,o=e.split(`/`).pop()):(e.match(/\.(md|markdown)$/)&&(a=`text/markdown`),o=e.split(`/`).pop()),n.push({type:`source`,sourceType:`document`,id:t(),mediaType:a,title:i,filename:o})}else if(i){let e=r.retrievedContext.title??`Unknown Document`;n.push({type:`source`,sourceType:`document`,id:t(),mediaType:`application/octet-stream`,title:e,filename:i.split(`/`).pop()})}}else r.maps!=null&&r.maps.uri&&n.push({type:`source`,sourceType:`url`,id:t(),url:r.maps.uri,title:r.maps.title??void 0});return n.length>0?n:void 0}var Pe=()=>s({webSearchQueries:i(o()).nullish(),imageSearchQueries:i(o()).nullish(),retrievalQueries:i(o()).nullish(),searchEntryPoint:s({renderedContent:o()}).nullish(),groundingChunks:i(s({web:s({uri:o(),title:o().nullish()}).nullish(),image:s({sourceUri:o(),imageUri:o(),title:o().nullish(),domain:o().nullish()}).nullish(),retrievedContext:s({uri:o().nullish(),title:o().nullish(),text:o().nullish(),fileSearchStore:o().nullish()}).nullish(),maps:s({uri:o().nullish(),title:o().nullish(),text:o().nullish(),placeId:o().nullish()}).nullish()})).nullish(),groundingSupports:i(s({segment:s({startIndex:d().nullish(),endIndex:d().nullish(),text:o().nullish()}).nullish(),segment_text:o().nullish(),groundingChunkIndices:i(d()).nullish(),supportChunkIndices:i(d()).nullish(),confidenceScores:i(d()).nullish(),confidenceScore:i(d()).nullish()})).nullish(),retrievalMetadata:c([s({webDynamicRetrievalScore:d()}),s({})]).nullish()}),Fe=s({jsonPath:o(),stringValue:o().nullish(),numberValue:d().nullish(),boolValue:r().nullish(),nullValue:l().nullish(),willContinue:r().nullish()}),Ie=()=>s({parts:i(c([s({functionCall:s({id:o().nullish(),name:o().nullish(),args:l().nullish(),partialArgs:i(Fe).nullish(),willContinue:r().nullish()}),thoughtSignature:o().nullish()}),s({inlineData:s({mimeType:o(),data:o()}),thought:r().nullish(),thoughtSignature:o().nullish()}),s({toolCall:s({toolType:o(),args:l().nullish(),id:o()}),thoughtSignature:o().nullish()}),s({toolResponse:s({toolType:o(),response:l().nullish(),id:o()}),thoughtSignature:o().nullish()}),s({executableCode:s({language:o(),code:o()}).nullish(),codeExecutionResult:s({outcome:o(),output:o().nullish()}).nullish(),text:o().nullish(),thought:r().nullish(),thoughtSignature:o().nullish()})])).nullish()}),U=()=>s({category:o().nullish(),probability:o().nullish(),probabilityScore:d().nullish(),severity:o().nullish(),severityScore:d().nullish(),blocked:r().nullish()}),Le=i(s({modality:o(),tokenCount:d()})).nullish(),Re=s({cachedContentTokenCount:d().nullish(),thoughtsTokenCount:d().nullish(),promptTokenCount:d().nullish(),candidatesTokenCount:d().nullish(),totalTokenCount:d().nullish(),trafficType:o().nullish(),serviceTier:o().nullish(),promptTokensDetails:Le,candidatesTokensDetails:Le}),ze=()=>s({urlMetadata:i(s({retrievedUrl:o(),urlRetrievalStatus:o()})).nullish()}),Be=P(()=>D(s({candidates:i(s({content:Ie().nullish().or(s({}).strict()),finishReason:o().nullish(),finishMessage:o().nullish(),safetyRatings:i(U()).nullish(),groundingMetadata:Pe().nullish(),urlContextMetadata:ze().nullish()})),usageMetadata:Re.nullish(),promptFeedback:s({blockReason:o().nullish(),safetyRatings:i(U()).nullish()}).nullish()}))),Ve=P(()=>D(s({candidates:i(s({content:Ie().nullish(),finishReason:o().nullish(),finishMessage:o().nullish(),safetyRatings:i(U()).nullish(),groundingMetadata:Pe().nullish(),urlContextMetadata:ze().nullish()})).nullish(),usageMetadata:Re.nullish(),promptFeedback:s({blockReason:o().nullish(),safetyRatings:i(U()).nullish()}).nullish()}))),He=N({id:`google.code_execution`,inputSchema:s({language:o().describe(`The programming language of the code.`),code:o().describe(`The code to be executed.`)}),outputSchema:s({outcome:o().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:o().describe(`The output from the code execution.`)})}),Ue=N({id:`google.enterprise_web_search`,inputSchema:P(()=>D(s({}))),outputSchema:P(()=>D(s({})))});s({fileSearchStoreNames:i(o()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:d().int().positive().describe(`The number of file search retrieval chunks to retrieve.`).optional(),metadataFilter:o().describe(`Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.`).optional()}).passthrough();var We=N({id:`google.file_search`,inputSchema:P(()=>D(s({}))),outputSchema:P(()=>D(s({})))}),Ge=N({id:`google.google_maps`,inputSchema:P(()=>D(s({}))),outputSchema:P(()=>D(s({})))}),Ke=s({searchTypes:s({webSearch:s({}).optional(),imageSearch:s({}).optional()}).optional(),timeRangeFilter:s({startTime:o(),endTime:o()}).optional()}).passthrough(),qe={googleSearch:N({id:`google.google_search`,inputSchema:P(()=>D(s({}))),outputSchema:P(()=>D(s({})))}),enterpriseWebSearch:Ue,googleMaps:Ge,urlContext:N({id:`google.url_context`,inputSchema:P(()=>D(s({}))),outputSchema:P(()=>D(s({})))}),fileSearch:We,codeExecution:He,vertexRagStore:N({id:`google.vertex_rag_store`,inputSchema:P(()=>D(s({}))),outputSchema:P(()=>D(s({})))})},Je=P(()=>D(s({personGeneration:f([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:f([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish(),googleSearch:Ke.optional()}))),Ye=class e{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v4`}static[O](e){return T({modelId:e.modelId,config:e.config})}static[E](t){return new e(t.modelId,{},t.config)}get maxImagesPerCall(){return this.settings.maxImagesPerCall==null?Xe(this.modelId)?10:4:this.settings.maxImagesPerCall}get provider(){return this.config.provider}async doGenerate(e){return Xe(this.modelId)?this.doGenerateGemini(e):this.doGenerateImagen(e)}async doGenerateImagen(e){var t;let{prompt:n,n:r=1,size:i,aspectRatio:a=`1:1`,seed:o,providerOptions:s,headers:c,abortSignal:l,files:u,mask:d}=e,f=[];if(u!=null&&u.length>0)throw Error(`Google Gemini API does not support image editing with Imagen models. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.`);if(d!=null)throw Error(`Google Gemini API does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.`);i!=null&&f.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),o!=null&&f.push({type:`unsupported`,feature:`seed`,details:"This model does not support the `seed` option through this provider."});let p=await _({provider:`google`,providerOptions:s,schema:Je}),m=((t=this.config._internal)?.currentDate)?.call(t)??new Date,h={sampleCount:r};if(a!=null&&(h.aspectRatio=a),p){let{googleSearch:e,...t}=p;e!=null&&f.push({type:`unsupported`,feature:`googleSearch`,details:`Google Search grounding is only supported on Gemini image models.`}),Object.assign(h,t)}let g={instances:[{prompt:n}],parameters:h},{responseHeaders:v,value:y}=await x({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:I(this.config.headers?await B(this.config.headers):void 0,c),body:g,failedResponseHandler:V,successfulResponseHandler:M(Ze),abortSignal:l,fetch:this.config.fetch});return{images:y.predictions.map(e=>e.bytesBase64Encoded),warnings:f,providerMetadata:{google:{images:y.predictions.map(()=>({}))}},response:{timestamp:m,modelId:this.modelId,headers:v}}}async doGenerateGemini(e){var t;let{prompt:n,n:r,size:i,aspectRatio:a,seed:o,providerOptions:s,headers:c,abortSignal:l,files:u,mask:d}=e,f=[];if(d!=null)throw Error(`Gemini image models do not support mask-based image editing.`);if(r!=null&&r>1)throw Error(`Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter.`);i!=null&&f.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."});let p=[];if(n!=null&&p.push({type:`text`,text:n}),u!=null&&u.length>0)for(let e of u)e.type===`url`?p.push({type:`file`,data:{type:`url`,url:new URL(e.url)},mediaType:`image/*`}):p.push({type:`file`,data:{type:`data`,data:typeof e.data==`string`?e.data:new Uint8Array(e.data)},mediaType:e.mediaType});let m=[{role:`user`,content:p}],h=await _({provider:`google`,providerOptions:s,schema:Je}),{googleSearch:g,...v}=s?.google??{},y=await new Ee(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??j}).doGenerate({prompt:m,seed:o,providerOptions:{google:{responseModalities:[`IMAGE`],imageConfig:a?{aspectRatio:a}:void 0,...v}},tools:h?.googleSearch==null?void 0:[{type:`provider`,id:`google.google_search`,name:`google_search`,args:h.googleSearch}],headers:c,abortSignal:l}),b=((t=this.config._internal)?.currentDate)?.call(t)??new Date,x=[];for(let e of y.content)e.type===`file`&&e.mediaType.startsWith(`image/`)&&e.data.type===`data`&&x.push(F(e.data.data));return{images:x,warnings:f,providerMetadata:{google:{...y.providerMetadata?.google??{},images:x.map(()=>({}))}},response:{timestamp:b,modelId:this.modelId,headers:y.response?.headers},usage:y.usage?{inputTokens:y.usage.inputTokens.total,outputTokens:y.usage.outputTokens.total,totalTokens:(y.usage.inputTokens.total??0)+(y.usage.outputTokens.total??0)}:void 0}}};function Xe(e){return e.startsWith(`gemini-`)}var Ze=P(()=>D(s({predictions:i(s({bytesBase64Encoded:o()})).default([])}))),Qe=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadFile(t){let n=await _({provider:`google`,providerOptions:t.providerOptions,schema:et}),r=this.config.headers(),i=this.config.fetch??globalThis.fetch,a=[];t.filename!=null&&a.push({type:`unsupported`,feature:`filename`});let o=A(t.data),s=t.mediaType,c=n?.displayName,l=await i(`${this.config.baseURL.replace(/\/v1beta$/,``)}/upload/v1beta/files`,{method:`POST`,headers:{...r,"X-Goog-Upload-Protocol":`resumable`,"X-Goog-Upload-Command":`start`,"X-Goog-Upload-Header-Content-Length":String(o.length),"X-Goog-Upload-Header-Content-Type":s,"Content-Type":`application/json`},body:JSON.stringify({file:{...c==null?{}:{display_name:c}}})});if(!l.ok){let t=await l.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to initiate resumable upload: ${l.status} ${t}`})}let u=l.headers.get(`x-goog-upload-url`);if(!u)throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`No upload URL returned from initiation request`});let d=await i(u,{method:`POST`,headers:{"Content-Length":String(o.length),"X-Goog-Upload-Offset":`0`,"X-Goog-Upload-Command":`upload, finalize`},body:o});if(!d.ok){let t=await d.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to upload file data: ${d.status} ${t}`})}let f=(await d.json()).file,p=n?.pollIntervalMs??2e3,m=n?.pollTimeoutMs??3e5,h=Date.now();for(;f.state===`PROCESSING`;){if(Date.now()-h>m)throw new e({name:`GOOGLE_FILES_UPLOAD_TIMEOUT`,message:`File processing timed out after ${m}ms`});await k(p);let{value:t}=await z({url:`${this.config.baseURL}/${f.name}`,headers:I(r),successfulResponseHandler:M($e),failedResponseHandler:V,fetch:this.config.fetch});f=t}if(f.state===`FAILED`)throw new e({name:`GOOGLE_FILES_UPLOAD_FAILED`,message:`File processing failed for ${f.name}`});return{warnings:a,providerReference:{google:f.uri},mediaType:f.mimeType??t.mediaType,providerMetadata:{google:{name:f.name,displayName:f.displayName,mimeType:f.mimeType,sizeBytes:f.sizeBytes,state:f.state,uri:f.uri,...f.createTime==null?{}:{createTime:f.createTime},...f.updateTime==null?{}:{updateTime:f.updateTime},...f.expirationTime==null?{}:{expirationTime:f.expirationTime},...f.sha256Hash==null?{}:{sha256Hash:f.sha256Hash}}}}}},$e=P(()=>D(s({name:o(),displayName:o().nullish(),mimeType:o(),sizeBytes:o().nullish(),createTime:o().nullish(),updateTime:o().nullish(),expirationTime:o().nullish(),sha256Hash:o().nullish(),uri:o(),state:o()}))),et=P(()=>D(s({displayName:o().nullish(),pollIntervalMs:d().positive().nullish(),pollTimeoutMs:d().positive().nullish()}).passthrough())),tt=P(()=>D(s({pollIntervalMs:d().positive().nullish(),pollTimeoutMs:d().positive().nullish(),personGeneration:f([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),negativePrompt:o().nullish(),referenceImages:i(s({bytesBase64Encoded:o().nullish(),gcsUri:o().nullish()})).nullish()}).passthrough())),nt=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}get provider(){return this.config.provider}get maxVideosPerCall(){return 4}async doGenerate(t){var n;let r=((n=this.config._internal)?.currentDate)?.call(n)??new Date,i=[],a=await _({provider:`google`,providerOptions:t.providerOptions,schema:tt}),o=[{}],s=o[0];if(t.prompt!=null&&(s.prompt=t.prompt),t.image!=null)if(t.image.type===`url`)i.push({type:`unsupported`,feature:`URL-based image input`,details:`Google Generative AI video models require base64-encoded images. URL will be ignored.`});else{let e=typeof t.image.data==`string`?t.image.data:ee(t.image.data);s.image={inlineData:{mimeType:t.image.mediaType||`image/png`,data:e}}}a?.referenceImages!=null&&(s.referenceImages=a.referenceImages.map(e=>e.bytesBase64Encoded?{inlineData:{mimeType:`image/png`,data:e.bytesBase64Encoded}}:e.gcsUri?{gcsUri:e.gcsUri}:e));let c={sampleCount:t.n};if(t.aspectRatio&&(c.aspectRatio=t.aspectRatio),t.resolution&&(c.resolution={"1280x720":`720p`,"1920x1080":`1080p`,"3840x2160":`4k`}[t.resolution]||t.resolution),t.duration&&(c.durationSeconds=t.duration),t.seed&&(c.seed=t.seed),a!=null){let e=a;e.personGeneration!==void 0&&e.personGeneration!==null&&(c.personGeneration=e.personGeneration),e.negativePrompt!==void 0&&e.negativePrompt!==null&&(c.negativePrompt=e.negativePrompt);for(let[t,n]of Object.entries(e))[`pollIntervalMs`,`pollTimeoutMs`,`personGeneration`,`negativePrompt`,`referenceImages`].includes(t)||(c[t]=n)}let{value:l}=await x({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:I(await B(this.config.headers),t.headers),body:{instances:o,parameters:c},successfulResponseHandler:M(rt),failedResponseHandler:V,abortSignal:t.abortSignal,fetch:this.config.fetch}),u=l.name;if(!u)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No operation name returned from API`});let d=a?.pollIntervalMs??1e4,f=a?.pollTimeoutMs??6e5,p=Date.now(),m=l,h;for(;!m.done;){if(Date.now()-p>f)throw new e({name:`GOOGLE_VIDEO_GENERATION_TIMEOUT`,message:`Video generation timed out after ${f}ms`});if(await k(d),t.abortSignal?.aborted)throw new e({name:`GOOGLE_VIDEO_GENERATION_ABORTED`,message:`Video generation request was aborted`});let{value:n,responseHeaders:r}=await z({url:`${this.config.baseURL}/${u}`,headers:I(await B(this.config.headers),t.headers),successfulResponseHandler:M(rt),failedResponseHandler:V,abortSignal:t.abortSignal,fetch:this.config.fetch});m=n,h=r}if(m.error)throw new e({name:`GOOGLE_VIDEO_GENERATION_FAILED`,message:`Video generation failed: ${m.error.message}`});let g=m.response;if(!g?.generateVideoResponse?.generatedSamples||g.generateVideoResponse.generatedSamples.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No videos in response. Response: ${JSON.stringify(m)}`});let v=[],y=[],b=(await B(this.config.headers))?.[`x-goog-api-key`];for(let e of g.generateVideoResponse.generatedSamples)if(e.video?.uri){let t=b?`${e.video.uri}${e.video.uri.includes(`?`)?`&`:`?`}key=${b}`:e.video.uri;v.push({type:`url`,url:t,mediaType:`video/mp4`}),y.push({uri:e.video.uri})}if(v.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No valid videos in response`});return{videos:v,warnings:i,response:{timestamp:r,modelId:this.modelId,headers:h},providerMetadata:{google:{videos:y}}}}},rt=s({name:o().nullish(),done:r().nullish(),error:s({code:d().nullish(),message:o(),status:o().nullish()}).nullish(),response:s({generateVideoResponse:s({generatedSamples:i(s({video:s({uri:o().nullish()}).nullish()})).nullish()}).nullish()}).nullish()});function W(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.total_input_tokens??0,n=e.total_output_tokens??0,r=e.total_thought_tokens??0,i=e.total_cached_tokens??0;return{inputTokens:{total:e.total_input_tokens??void 0,noCache:e.total_input_tokens==null?void 0:t-i,cacheRead:e.total_cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:e.total_output_tokens==null&&e.total_thought_tokens==null?void 0:n+r,text:e.total_output_tokens??void 0,reasoning:e.total_thought_tokens??void 0},raw:e}}var it={pdf:`application/pdf`,txt:`text/plain`,md:`text/markdown`,markdown:`text/markdown`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};function at(e){let t=e.toLowerCase();for(let[e,n]of Object.entries(it))if(t.endsWith(`.${e}`))return n;return`application/octet-stream`}function ot(e){let t=e.split(`/`),n=t[t.length-1];return n&&n.length>0?n:void 0}function st({annotation:e,generateId:t}){switch(e.type){case`url_citation`:{let n=e;return n.url==null||n.url.length===0?void 0:{type:`source`,sourceType:`url`,id:t(),url:n.url,...n.title==null?{}:{title:n.title}}}case`file_citation`:{let n=e,r=n.url??n.document_uri??n.file_name;if(r==null||r.length===0)return;if(r.startsWith(`http://`)||r.startsWith(`https://`))return{type:`source`,sourceType:`url`,id:t(),url:r,...n.file_name==null?{}:{title:n.file_name}};let i=n.file_name??ot(r),a=at(r);return{type:`source`,sourceType:`document`,id:t(),mediaType:a,title:n.file_name??i??r,...i==null?{}:{filename:i}}}case`place_citation`:{let n=e;return n.url==null||n.url.length===0?void 0:{type:`source`,sourceType:`url`,id:t(),url:n.url,...n.name==null?{}:{title:n.name}}}default:return}}function ct({block:e,generateId:t}){let n=[];switch(e.type){case`url_context_result`:{let r=e.result??[];for(let e of r)e?.url==null||e.url.length===0||e.status!=null&&e.status!==`success`||n.push({type:`source`,sourceType:`url`,id:t(),url:e.url});break}case`google_search_result`:{let r=e.result??[];for(let e of r){let r=e?.url;r==null||r.length===0||n.push({type:`source`,sourceType:`url`,id:t(),url:r,...e.title==null?{}:{title:e.title}})}break}case`google_maps_result`:{let r=e.result??[];for(let e of r)for(let r of e.places??[])r.url==null||r.url.length===0||n.push({type:`source`,sourceType:`url`,id:t(),url:r.url,...r.name==null?{}:{title:r.name}});break}case`file_search_result`:{let r=e.result??[];for(let e of r){if(typeof e!=`object`||!e)continue;let r=e,i=r.url??r.document_uri??r.file_name;if(i==null||i.length===0)continue;if(i.startsWith(`http://`)||i.startsWith(`https://`)){n.push({type:`source`,sourceType:`url`,id:t(),url:i,...r.title==null?{}:{title:r.title}});continue}let a=r.file_name??ot(i),o=at(i);n.push({type:`source`,sourceType:`document`,id:t(),mediaType:o,title:r.title??r.file_name??a??i,...a==null?{}:{filename:a}})}break}default:break}return n}function G({annotations:e,generateId:t}){if(e==null)return[];let n=new Set,r=[];for(let i of e){let e=st({annotation:i,generateId:t});if(e==null)continue;let a=e.sourceType===`url`?`url:${e.url}`:`doc:${e.filename??e.title}`;n.has(a)||(n.add(a),r.push(e))}return r}function K({status:e,hasFunctionCall:t}){switch(e){case`completed`:return t?`tool-calls`:`stop`;case`requires_action`:return`tool-calls`;case`failed`:return`error`;case`incomplete`:return`length`;case`cancelled`:return`other`;default:return`other`}}var lt=new Set([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),ut=new Set([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]);function dt(e){return e.replace(/_call$/,``)}function ft(e){return e.replace(/_result$/,``)}function pt({warnings:e,generateId:t,includeRawChunks:n,serviceTier:r}){let i,a,o=r,s,c=!1,l=new Map,u=new Set;function d(e){return e.sourceType===`url`?`url:${e.url}`:`doc:${e.filename??e.title}`}return new TransformStream({start(t){t.enqueue({type:`stream-start`,warnings:e})},transform(e,r){if(n&&r.enqueue({type:`raw`,rawValue:e.rawValue}),!e.success){s=`failed`,r.enqueue({type:`error`,error:e.error});return}let f=e.value,p=f.event_type;switch(p){case`interaction.created`:{let e=f.interaction;i=e?.id!=null&&e.id.length>0?e.id:void 0;let t=e?.created,n;if(typeof t==`string`){let e=new Date(t);Number.isNaN(e.getTime())||(n=e)}r.enqueue({type:`response-metadata`,...i==null?{}:{id:i},modelId:e?.model,...n?{timestamp:n}:{}});break}case`step.start`:{let e=f,n=e.step,a=e.index,o=`${i??`interaction`}:${a}`,s=n?.type;if(s===`model_output`){let e=n?.content?.[0];if(e?.type===`text`){l.set(a,{kind:`text`,id:o,emittedSourceKeys:new Set}),r.enqueue({type:`text-start`,id:o});let n=G({annotations:e.annotations,generateId:t});for(let e of n){let t=d(e);u.has(t)||(u.add(t),r.enqueue(e))}}else e?.type===`image`?l.set(a,{kind:`image`,id:o,...e.data==null?{}:{data:e.data},...e.mime_type==null?{}:{mimeType:e.mime_type},...e.uri==null?{}:{uri:e.uri}}):l.set(a,{kind:`pending_model_output`,id:o})}else if(s===`thought`){let e=n?.signature;if(l.set(a,{kind:`reasoning`,id:o,...e==null?{}:{signature:e}}),r.enqueue({type:`reasoning-start`,id:o}),Array.isArray(n?.summary))for(let e of n.summary)e?.type===`text`&&typeof e.text==`string`&&r.enqueue({type:`reasoning-delta`,id:o,delta:e.text})}else if(s===`function_call`){let e=n?.id??o,t=n?.name??`unknown`;c=!0;let i={kind:`function_call`,id:o,toolCallId:e,toolName:t,argumentsAccum:``,...n?.signature==null?{}:{signature:n.signature}};l.set(a,i),r.enqueue({type:`tool-input-start`,id:e,toolName:t})}else if(s!=null&&lt.has(s)){let e=s===`mcp_server_tool_call`?n?.name??`mcp_server_tool`:dt(s),t={kind:`builtin_tool_call`,id:o,blockType:s,toolCallId:n?.id??o,toolName:e,arguments:n?.arguments??{},callEmitted:!1};l.set(a,t)}else if(s!=null&&ut.has(s)){let e=s===`mcp_server_tool_result`?n?.name??`mcp_server_tool`:ft(s),t={kind:`builtin_tool_result`,id:o,blockType:s,callId:n?.call_id??o,toolName:e,result:n?.result??null,...n?.is_error==null?{}:{isError:n.is_error},resultEmitted:!1};l.set(a,t)}else l.set(a,{kind:`unknown`,id:o});break}case`step.delta`:{let e=f,n=l.get(e.index);if(n==null)break;let a=e.delta?.type;if(n.kind===`pending_model_output`&&(a===`text`||a===`text_annotation`||a===`text_annotation_delta`)){let t={kind:`text`,id:n.id,emittedSourceKeys:new Set};l.set(e.index,t),n=t,r.enqueue({type:`text-start`,id:t.id})}if(a===`image`&&(n.kind===`pending_model_output`||n.kind===`text`||n.kind===`image`)){let t=e.delta,a={};i!=null&&(a.interactionId=i);let o=Object.keys(a).length>0?{google:a}:void 0;t?.data!=null&&t.data.length>0?r.enqueue({type:`file`,mediaType:t.mime_type??`image/png`,data:{type:`data`,data:t.data},...o?{providerMetadata:o}:{}}):t?.uri!=null&&t.uri.length>0&&r.enqueue({type:`file`,mediaType:t.mime_type??`image/png`,data:{type:`url`,url:new URL(t.uri)},...o?{providerMetadata:o}:{}}),n.kind===`image`&&(n.data=void 0,n.uri=void 0);break}let o=e.delta;if(n.kind===`text`&&o?.type===`text`){let e=o.text??``;e.length>0&&r.enqueue({type:`text-delta`,id:n.id,delta:e})}else if(n.kind===`text`&&(o?.type===`text_annotation`||o?.type===`text_annotation_delta`)){let e=G({annotations:o.annotations,generateId:t});for(let t of e){let e=d(t);u.has(e)||(u.add(e),n.emittedSourceKeys.add(e),r.enqueue(t))}}else if(n.kind===`image`&&o?.type===`image`)o.data!=null&&(n.data=o.data),o.mime_type!=null&&(n.mimeType=o.mime_type),o.uri!=null&&(n.uri=o.uri);else if(n.kind===`reasoning`){if(o?.type===`thought_summary`){let e=o.content;e?.type===`text`&&typeof e.text==`string`&&r.enqueue({type:`reasoning-delta`,id:n.id,delta:e.text})}else if(o?.type===`thought_signature`){let e=o.signature;e!=null&&(n.signature=e)}}else if(n.kind===`function_call`&&o?.type===`arguments_delta`){let e=typeof o.arguments==`string`?o.arguments:``;e.length>0&&(n.argumentsAccum+=e,r.enqueue({type:`tool-input-delta`,id:n.toolCallId,delta:e})),o.id!=null&&(n.toolCallId=o.id),o.signature!=null&&(n.signature=o.signature),c=!0}else n.kind===`builtin_tool_call`&&o?.type===n.blockType?(o.id!=null&&(n.toolCallId=o.id),o.arguments!=null&&typeof o.arguments==`object`&&(n.arguments=o.arguments),o.name!=null&&n.blockType===`mcp_server_tool_call`&&(n.toolName=o.name)):n.kind===`builtin_tool_result`&&o?.type===n.blockType&&(o.call_id!=null&&(n.callId=o.call_id),o.result!==void 0&&(n.result=o.result),o.is_error!=null&&(n.isError=o.is_error),o.name!=null&&n.blockType===`mcp_server_tool_result`&&(n.toolName=o.name));break}case`step.stop`:{let e=f,n=l.get(e.index);if(n==null)break;if(n.kind===`text`){let e=i==null?void 0:{google:{interactionId:i}};r.enqueue({type:`text-end`,id:n.id,...e?{providerMetadata:e}:{}})}else if(n.kind===`reasoning`){let e={};n.signature!=null&&(e.signature=n.signature),i!=null&&(e.interactionId=i);let t=Object.keys(e).length>0?{google:e}:void 0;r.enqueue({type:`reasoning-end`,id:n.id,...t?{providerMetadata:t}:{}})}else if(n.kind===`image`){let e={};i!=null&&(e.interactionId=i);let t=Object.keys(e).length>0?{google:e}:void 0;n.data!=null&&n.data.length>0?r.enqueue({type:`file`,mediaType:n.mimeType??`image/png`,data:{type:`data`,data:n.data},...t?{providerMetadata:t}:{}}):n.uri!=null&&n.uri.length>0&&r.enqueue({type:`file`,mediaType:n.mimeType??`image/png`,data:{type:`url`,url:new URL(n.uri)},...t?{providerMetadata:t}:{}})}else if(n.kind===`function_call`){let e=n.argumentsAccum.length>0?n.argumentsAccum:`{}`;r.enqueue({type:`tool-input-end`,id:n.toolCallId});let t={};n.signature!=null&&(t.signature=n.signature),i!=null&&(t.interactionId=i);let a=Object.keys(t).length>0?{google:t}:void 0;r.enqueue({type:`tool-call`,toolCallId:n.toolCallId,toolName:n.toolName,input:e,...a?{providerMetadata:a}:{}})}else if(n.kind===`builtin_tool_call`&&!n.callEmitted)r.enqueue({type:`tool-call`,toolCallId:n.toolCallId,toolName:n.toolName,input:JSON.stringify(n.arguments??{}),providerExecuted:!0}),n.callEmitted=!0;else if(n.kind===`builtin_tool_result`&&!n.resultEmitted){r.enqueue({type:`tool-result`,toolCallId:n.callId,toolName:n.toolName,result:n.result??null}),n.resultEmitted=!0;let e=ct({block:{type:n.blockType,call_id:n.callId,result:n.result},generateId:t});for(let t of e){let e=d(t);u.has(e)||(u.add(e),r.enqueue(t))}}l.delete(e.index);break}case`interaction.status_update`:case`interaction.in_progress`:case`interaction.requires_action`:{let e=f;s=e.status==null?p===`interaction.requires_action`?`requires_action`:`in_progress`:e.status;break}case`interaction.completed`:{let e=f.interaction;e?.id!=null&&e.id.length>0&&(i=e.id),e?.status!=null&&(s=e.status),e?.usage!=null&&(a=e.usage),e?.service_tier!=null&&(o=e.service_tier);break}case`error`:{let e=f;s=`failed`;let t=e.error??{message:`Unknown interaction error`};r.enqueue({type:`error`,error:t});break}default:break}},flush(e){let t={unified:K({status:s,hasFunctionCall:c}),raw:s},n={google:{...i==null?{}:{interactionId:i},...o==null?{}:{serviceTier:o}}};e.enqueue({type:`finish`,finishReason:t,usage:W(a),providerMetadata:n})}})}function mt({prompt:e,previousInteractionId:t,store:n,mediaResolution:r}){let i=[],a=t!=null&&n===!1,o=t!=null&&n!==!1;a&&i.push({type:`other`,message:`google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted.`});let s=o?gt({prompt:e,previousInteractionId:t}):e,c=[],l=[];for(let e of s)switch(e.role){case`system`:c.push(e.content);break;case`user`:{let t=[];for(let n of e.content)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`file`){let e=ht({part:n,warnings:i,mediaResolution:r});e!=null&&t.push(e)}let n=bt(t);n.length>0&&l.push({type:`user_input`,content:n});break}case`assistant`:{let t=[],n=()=>{t.length>0&&(l.push({type:`model_output`,content:t}),t=[])};for(let a of e.content)if(a.type===`text`)t.push({type:`text`,text:a.text});else if(a.type===`reasoning`){n();let e=a.providerOptions?.google?.signature;l.push({type:`thought`,...e==null?{}:{signature:e},summary:a.text.length>0?[{type:`text`,text:a.text}]:void 0})}else if(a.type===`file`){let e=ht({part:a,warnings:i,mediaResolution:r});e!=null&&t.push(e)}else if(a.type===`tool-call`){n();let e=a.providerOptions?.google?.signature,t=typeof a.input==`string`?_t(a.input):a.input??{};l.push({type:`function_call`,id:a.toolCallId,name:a.toolName,arguments:t,...e==null?{}:{signature:e}})}else i.push({type:`other`,message:`google.interactions: unsupported assistant content part type "${a.type}"; part dropped.`});n();break}case`tool`:{let t=[];for(let n of e.content){if(n.type!==`tool-result`){i.push({type:`other`,message:`google.interactions: unsupported tool message part type "${n.type}"; part dropped.`});continue}let e=vt({toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,signature:n.providerOptions?.google?.signature,warnings:i});t.push(e)}t.length>0&&l.push({type:`user_input`,content:t});break}}return{input:l,systemInstruction:c.length>0?c.join(`
7
7
 
8
- `):void 0,warnings:i}}function mt({part:e,warnings:t,mediaResolution:n}){if(e.data.type===`text`)return{type:`text`,text:e.data.text};let r=h(e.mediaType),i;switch(r){case`image`:i=`image`;break;case`audio`:i=`audio`;break;case`video`:i=`video`;break;case`application`:i=`document`;break;default:i=void 0}if(i==null){t.push({type:`other`,message:`google.interactions: unsupported file media type "${e.mediaType}"; part dropped.`});return}let a=n!=null&&(i===`image`||i===`video`)?{resolution:n}:{};switch(e.data.type){case`data`:{let t=m({part:e});return{type:i,data:P(e.data.data),mime_type:t,...a}}case`url`:return{type:i,uri:e.data.url.toString(),...g(e.mediaType)?{mime_type:e.mediaType}:{},...a};case`reference`:{let t=w({reference:e.data.reference,provider:`google`});return{type:i,uri:t,...g(e.mediaType)?{mime_type:e.mediaType}:{},...a}}}}function ht({prompt:e,previousInteractionId:t}){let n=[],r=new Set;for(let i of e){if(i.role===`assistant`){if(i.content.some(e=>e.providerOptions?.google?.interactionId===t)){for(let e of i.content)e.type===`tool-call`&&r.add(e.toolCallId);continue}n.push(i);continue}if(i.role===`tool`){let e=i.content.filter(e=>e.type===`tool-result`?!r.has(e.toolCallId):!0);if(e.length===0)continue;n.push({...i,content:e});continue}n.push(i)}return n}function gt(e){try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{value:t}}catch{return{value:e}}}function _t({toolCallId:e,toolName:t,output:n,signature:r,warnings:i}){let a={type:`function_result`,call_id:e,name:t,...r==null?{}:{signature:r}};switch(n.type){case`text`:return{...a,result:n.value};case`json`:return{...a,result:JSON.stringify(n.value)};case`error-text`:return{...a,is_error:!0,result:n.value};case`error-json`:return{...a,is_error:!0,result:JSON.stringify(n.value)};case`execution-denied`:return{...a,is_error:!0,result:n.reason??`Tool execution denied by user.`};case`content`:{let e=[];for(let t of n.value)if(t.type===`text`)e.push({type:`text`,text:t.text});else if(t.type===`file`){if(h(t.mediaType)!==`image`){i.push({type:`other`,message:`google.interactions: tool-result file with mediaType "${t.mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`});continue}let n=vt({part:t,warnings:i});n!=null&&e.push(n)}else i.push({type:`other`,message:`google.interactions: tool-result content part type "${t.type}" is not supported; part dropped.`});return{...a,result:e}}}}function vt({part:e,warnings:t}){switch(e.data.type){case`data`:{let t=g(e.mediaType)?e.mediaType:m({part:{type:`file`,mediaType:e.mediaType,data:e.data}});return{type:`image`,data:P(e.data.data),mime_type:t}}case`url`:return{type:`image`,uri:e.data.url.toString(),...g(e.mediaType)?{mime_type:e.mediaType}:{}};case`reference`:return{type:`image`,uri:w({reference:e.data.reference,provider:`google`}),...g(e.mediaType)?{mime_type:e.mediaType}:{}};case`text`:t.push({type:`other`,message:'google.interactions: tool-result image part with `data.type === "text"` is not representable as an image; part dropped.'});return}}function yt(e){if(e.length<2)return e;let t=[];for(let n of e){let e=t[t.length-1];if(n.type===`text`&&e!=null&&e.type===`text`&&e.annotations==null&&n.annotations==null){let r={type:`text`,text:`${e.text}
8
+ `):void 0,warnings:i}}function ht({part:e,warnings:t,mediaResolution:n}){if(e.data.type===`text`)return{type:`text`,text:e.data.text};let r=h(e.mediaType),i;switch(r){case`image`:i=`image`;break;case`audio`:i=`audio`;break;case`video`:i=`video`;break;case`application`:i=`document`;break;default:i=void 0}if(i==null){t.push({type:`other`,message:`google.interactions: unsupported file media type "${e.mediaType}"; part dropped.`});return}let a=n!=null&&(i===`image`||i===`video`)?{resolution:n}:{};switch(e.data.type){case`data`:{let t=m({part:e});return{type:i,data:F(e.data.data),mime_type:t,...a}}case`url`:return{type:i,uri:e.data.url.toString(),...g(e.mediaType)?{mime_type:e.mediaType}:{},...a};case`reference`:{let t=w({reference:e.data.reference,provider:`google`});return{type:i,uri:t,...g(e.mediaType)?{mime_type:e.mediaType}:{},...a}}}}function gt({prompt:e,previousInteractionId:t}){let n=[],r=new Set;for(let i of e){if(i.role===`assistant`){if(i.content.some(e=>e.providerOptions?.google?.interactionId===t)){for(let e of i.content)e.type===`tool-call`&&r.add(e.toolCallId);continue}n.push(i);continue}if(i.role===`tool`){let e=i.content.filter(e=>e.type===`tool-result`?!r.has(e.toolCallId):!0);if(e.length===0)continue;n.push({...i,content:e});continue}n.push(i)}return n}function _t(e){try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{value:t}}catch{return{value:e}}}function vt({toolCallId:e,toolName:t,output:n,signature:r,warnings:i}){let a={type:`function_result`,call_id:e,name:t,...r==null?{}:{signature:r}};switch(n.type){case`text`:return{...a,result:n.value};case`json`:return{...a,result:JSON.stringify(n.value)};case`error-text`:return{...a,is_error:!0,result:n.value};case`error-json`:return{...a,is_error:!0,result:JSON.stringify(n.value)};case`execution-denied`:return{...a,is_error:!0,result:n.reason??`Tool execution denied by user.`};case`content`:{let e=[];for(let t of n.value)if(t.type===`text`)e.push({type:`text`,text:t.text});else if(t.type===`file`){if(h(t.mediaType)!==`image`){i.push({type:`other`,message:`google.interactions: tool-result file with mediaType "${t.mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`});continue}let n=yt({part:t,warnings:i});n!=null&&e.push(n)}else i.push({type:`other`,message:`google.interactions: tool-result content part type "${t.type}" is not supported; part dropped.`});return{...a,result:e}}}}function yt({part:e,warnings:t}){switch(e.data.type){case`data`:{let t=g(e.mediaType)?e.mediaType:m({part:{type:`file`,mediaType:e.mediaType,data:e.data}});return{type:`image`,data:F(e.data.data),mime_type:t}}case`url`:return{type:`image`,uri:e.data.url.toString(),...g(e.mediaType)?{mime_type:e.mediaType}:{}};case`reference`:return{type:`image`,uri:w({reference:e.data.reference,provider:`google`}),...g(e.mediaType)?{mime_type:e.mediaType}:{}};case`text`:t.push({type:`other`,message:'google.interactions: tool-result image part with `data.type === "text"` is not representable as an image; part dropped.'});return}}function bt(e){if(e.length<2)return e;let t=[];for(let n of e){let e=t[t.length-1];if(n.type===`text`&&e!=null&&e.type===`text`&&e.annotations==null&&n.annotations==null){let r={type:`text`,text:`${e.text}
9
9
 
10
- ${n.text}`};t[t.length-1]=r;continue}t.push(n)}return t}var J=()=>s({modality:o().nullish(),tokens:d().nullish()}).loose(),bt=()=>s({total_input_tokens:d().nullish(),total_output_tokens:d().nullish(),total_thought_tokens:d().nullish(),total_cached_tokens:d().nullish(),total_tool_use_tokens:d().nullish(),total_tokens:d().nullish(),input_tokens_by_modality:i(J()).nullish(),output_tokens_by_modality:i(J()).nullish(),cached_tokens_by_modality:i(J()).nullish(),tool_use_tokens_by_modality:i(J()).nullish(),grounding_tool_count:i(s({type:o().nullish(),count:d().nullish()}).loose()).nullish()}).loose(),xt=()=>f([`in_progress`,`requires_action`,`completed`,`failed`,`cancelled`,`incomplete`]),St=()=>c([s({type:u(`url_citation`),url:o().nullish(),title:o().nullish(),start_index:d().nullish(),end_index:d().nullish()}).loose(),s({type:u(`file_citation`),file_name:o().nullish(),document_uri:o().nullish(),url:o().nullish(),page_number:d().nullish(),media_id:o().nullish(),start_index:d().nullish(),end_index:d().nullish(),custom_metadata:a(o(),l()).nullish()}).loose(),s({type:u(`place_citation`),name:o().nullish(),url:o().nullish(),place_id:o().nullish(),start_index:d().nullish(),end_index:d().nullish()}).loose(),s({type:o()}).loose()]),Ct=()=>s({type:o(),text:o().nullish(),data:o().nullish(),mime_type:o().nullish()}).loose(),wt=()=>c([s({type:u(`text`),text:o(),annotations:i(St()).nullish()}).loose(),s({type:u(`image`),data:o().nullish(),mime_type:o().nullish(),resolution:f([`low`,`medium`,`high`,`ultra_high`]).nullish(),uri:o().nullish()}).loose(),s({type:o()}).loose()]),Tt=[`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`],Et=[`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`],Dt=()=>c([s({type:u(`user_input`),content:i(wt()).nullish()}).loose(),s({type:u(`model_output`),content:i(wt()).nullish()}).loose(),s({type:u(`function_call`),id:o(),name:o(),arguments:a(o(),l()).nullish(),signature:o().nullish()}).loose(),s({type:u(`thought`),signature:o().nullish(),summary:i(Ct()).nullish()}).loose(),s({type:f(Tt),id:o(),arguments:a(o(),l()).nullish(),name:o().nullish(),server_name:o().nullish(),search_type:o().nullish(),signature:o().nullish()}).loose(),s({type:f(Et),call_id:o(),result:l().nullish(),is_error:r().nullish(),name:o().nullish(),server_name:o().nullish(),signature:o().nullish()}).loose(),s({type:o()}).loose()]),Y=N(()=>D(s({id:o().nullish(),created:o().nullish(),updated:o().nullish(),status:xt(),model:o().nullish(),agent:o().nullish(),steps:i(Dt()).nullish(),usage:bt().nullish(),service_tier:o().nullish(),previous_interaction_id:o().nullish(),response_modalities:i(o()).nullish()}).loose())),Ot=N(()=>D((()=>{let e=xt(),t=St(),n=Ct(),p=s({event_type:u(`interaction.created`),event_id:o().nullish(),interaction:s({id:o().nullish(),created:o().nullish(),model:o().nullish(),agent:o().nullish(),status:e.nullish()}).loose()}).loose(),m=s({event_type:u(`step.start`),event_id:o().nullish(),index:d(),step:Dt()}).loose(),h=s({type:u(`text`),text:o()}).loose(),g=s({type:u(`thought_summary`),content:n.nullish()}).loose(),_=s({type:u(`thought_signature`),signature:o().nullish()}).loose(),v=s({type:u(`arguments_delta`),arguments:o().nullish(),id:o().nullish(),signature:o().nullish()}).loose(),y=s({type:f([`text_annotation_delta`,`text_annotation`]),annotations:i(t).nullish()}).loose(),b=c([h,s({type:u(`image`),data:o().nullish(),mime_type:o().nullish(),resolution:f([`low`,`medium`,`high`,`ultra_high`]).nullish(),uri:o().nullish()}).loose(),g,_,v,y,s({type:f(Tt),id:o().nullish(),arguments:a(o(),l()).nullish(),name:o().nullish(),server_name:o().nullish(),search_type:o().nullish(),signature:o().nullish()}).loose(),s({type:f(Et),call_id:o().nullish(),result:l().nullish(),is_error:r().nullish(),name:o().nullish(),server_name:o().nullish(),signature:o().nullish()}).loose(),s({type:o()}).loose()]);return c([p,m,s({event_type:u(`step.delta`),event_id:o().nullish(),index:d(),delta:b}).loose(),s({event_type:u(`step.stop`),event_id:o().nullish(),index:d()}).loose(),s({event_type:u(`interaction.status_update`),event_id:o().nullish(),interaction_id:o().nullish(),status:e.nullish()}).loose(),s({event_type:u(`interaction.in_progress`),event_id:o().nullish(),interaction_id:o().nullish(),status:e.nullish()}).loose(),s({event_type:u(`interaction.requires_action`),event_id:o().nullish(),interaction_id:o().nullish(),status:e.nullish()}).loose(),s({event_type:u(`interaction.completed`),event_id:o().nullish(),interaction:s({id:o().nullish(),status:e.nullish(),usage:bt().nullish(),service_tier:o().nullish()}).loose()}).loose(),s({event_type:u(`error`),event_id:o().nullish(),error:s({code:o().nullish(),message:o().nullish()}).loose().nullish()}).loose(),s({event_type:o()}).loose()])})())),kt=N(()=>D(s({previousInteractionId:o().nullish(),store:r().nullish(),agent:o().nullish(),agentConfig:c([s({type:u(`dynamic`)}).loose(),s({type:u(`deep-research`),thinkingSummaries:f([`auto`,`none`]).nullish(),visualization:f([`off`,`auto`]).nullish(),collaborativePlanning:r().nullish()})]).nullish(),thinkingLevel:f([`minimal`,`low`,`medium`,`high`]).nullish(),thinkingSummaries:f([`auto`,`none`]).nullish(),responseFormat:i(c([s({type:u(`text`),mimeType:o().nullish(),schema:l().nullish()}).loose(),s({type:u(`image`),mimeType:o().nullish(),aspectRatio:f([`1:1`,`2:3`,`3:2`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`,`1:8`,`8:1`,`1:4`,`4:1`]).nullish(),imageSize:f([`1K`,`2K`,`4K`,`512`]).nullish()}).loose(),s({type:u(`audio`),mimeType:o().nullish()}).loose()])).nullish(),imageConfig:s({aspectRatio:f([`1:1`,`2:3`,`3:2`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`,`1:8`,`8:1`,`1:4`,`4:1`]).nullish(),imageSize:f([`1K`,`2K`,`4K`,`512`]).nullish()}).nullish(),mediaResolution:f([`low`,`medium`,`high`,`ultra_high`]).nullish(),responseModalities:i(f([`text`,`image`,`audio`,`video`,`document`])).nullish(),serviceTier:f([`flex`,`standard`,`priority`]).nullish(),systemInstruction:o().nullish(),signature:o().nullish(),interactionId:o().nullish(),pollingTimeoutMs:d().int().positive().nullish(),background:r().nullish(),environment:c([o(),s({type:u(`remote`),sources:i(c([s({type:u(`gcs`),source:o(),target:o().nullish()}),s({type:u(`repository`),source:o(),target:o().nullish()}),s({type:u(`inline`),content:o(),target:o()})])).nullish(),network:c([u(`disabled`),s({allowlist:i(s({domain:o(),transform:i(a(o(),o())).nullish()}))})]).nullish()})]).nullish()})));function X({signature:e,interactionId:t}){let n={};return e!=null&&(n.signature=e),t!=null&&(n.interactionId=t),Object.keys(n).length>0?{providerMetadata:{google:n}}:{}}var At=new Set([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),jt=new Set([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]);function Mt(e){return e.replace(/_call$/,``)}function Nt(e){return e.replace(/_result$/,``)}function Pt({steps:e,generateId:t,interactionId:n}){let r=[],i=!1;if(e==null)return{content:r,hasFunctionCall:i};for(let a of e){if(typeof a!=`object`||!a)continue;let e=a.type;if(typeof e==`string`)switch(e){case`user_input`:break;case`model_output`:{let e=a.content??[];for(let i of e){if(typeof i!=`object`||!i)continue;let e=i.type;if(e===`text`){let e=i.text??``,a=i.annotations;r.push({type:`text`,text:e,...X({interactionId:n})});let o=K({annotations:a,generateId:t});for(let e of o)r.push(e)}else if(e===`image`){let e=i;e.data!=null&&e.data.length>0?r.push({type:`file`,mediaType:e.mime_type??`image/png`,data:{type:`data`,data:e.data},...X({interactionId:n})}):e.uri!=null&&e.uri.length>0&&r.push({type:`file`,mediaType:e.mime_type??`image/png`,data:{type:`url`,url:new URL(e.uri)},...X({interactionId:n})})}}break}case`thought`:{let e=a,t=(Array.isArray(e.summary)?e.summary:[]).filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
11
- `);r.push({type:`reasoning`,text:t,...X({signature:e.signature,interactionId:n})});break}case`function_call`:{i=!0;let e=a;r.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.arguments??{}),...X({signature:e.signature,interactionId:n})});break}default:if(At.has(e)){let n=a,i=e===`mcp_server_tool_call`?n.name??`mcp_server_tool`:Mt(e),o=JSON.stringify(n.arguments??{});r.push({type:`tool-call`,toolCallId:n.id??t(),toolName:i,input:o,providerExecuted:!0})}else if(jt.has(e)){let n=a,i=e===`mcp_server_tool_result`?n.name??`mcp_server_tool`:Nt(e);r.push({type:`tool-result`,toolCallId:n.call_id??t(),toolName:i,result:n.result??null});let o=st({block:a,generateId:t});for(let e of o)r.push(e)}break}}return{content:r,hasFunctionCall:i}}var Ft=()=>globalThis.fetch;async function It({baseURL:e,interactionId:t,headers:n,fetch:r=Ft()}){if(t==null||t.length===0)return;let i=`${e}/interactions/${encodeURIComponent(t)}/cancel`;try{let e=await r(i,{method:`POST`,headers:re(F({"Content-Type":`application/json`},n),S()),body:`{}`});try{await e.text()}catch{}}catch{}}var Lt=new Set([`completed`,`failed`,`cancelled`,`incomplete`]);function Z(e){return e!=null&&Lt.has(e)}var Rt=1e3,zt=1e4,Bt=1800*1e3;async function Vt({baseURL:e,interactionId:t,headers:n,fetch:r,abortSignal:i,initialDelayMs:a=Rt,maxDelayMs:o=zt,timeoutMs:s=Bt}){if(t==null||t.length===0)throw Error(`google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.`);let c=Date.now(),l=a,u=`${e}/interactions/${encodeURIComponent(t)}`,d=()=>It({baseURL:e,interactionId:t,headers:n,fetch:r});try{for(;;){if(i?.aborted)throw await d(),new DOMException(`Polling was aborted`,`AbortError`);if(Date.now()-c>s)throw Error(`google.interactions: timed out polling interaction ${t} after ${s}ms.`);await k(l,{abortSignal:i});let{value:e,rawValue:a,responseHeaders:f}=await R({url:u,headers:n,failedResponseHandler:B,successfulResponseHandler:j(Y),abortSignal:i,fetch:r});if(Z(e.status))return{response:e,rawResponse:a,responseHeaders:f};l=Math.min(l*2,o)}}catch(e){throw L(e)&&await d(),e}}function Ht({tools:e,toolChoice:t}){let n=[],r=e?.length?e:void 0;if(r==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let i=[];for(let e of r){if(e.type===`function`){i.push({type:`function`,name:e.name,description:e.description??``,parameters:e.inputSchema});continue}if(e.type===`provider`){let t=e.args??{};switch(e.id){case`google.google_search`:{let e=t.searchTypes,n;if(typeof e==`object`&&e){let t=[];e.webSearch!=null&&t.push(`web_search`),e.imageSearch!=null&&t.push(`image_search`),t.length>0&&(n=t)}i.push({type:`google_search`,...n==null?{}:{search_types:n}});break}case`google.code_execution`:i.push({type:`code_execution`});break;case`google.url_context`:i.push({type:`url_context`});break;case`google.file_search`:i.push({type:`file_search`,...t.fileSearchStoreNames==null?{}:{file_search_store_names:t.fileSearchStoreNames},...t.topK==null?{}:{top_k:t.topK},...t.metadataFilter==null?{}:{metadata_filter:t.metadataFilter}});break;case`google.google_maps`:i.push({type:`google_maps`,...t.latitude==null?{}:{latitude:t.latitude},...t.longitude==null?{}:{longitude:t.longitude},...t.enableWidget==null?{}:{enable_widget:t.enableWidget}});break;case`google.computer_use`:i.push({type:`computer_use`,environment:t.environment??`browser`,...t.excludedPredefinedFunctions==null?{}:{excludedPredefinedFunctions:t.excludedPredefinedFunctions}});break;case`google.mcp_server`:i.push({type:`mcp_server`,...t.name==null?{}:{name:t.name},...t.url==null?{}:{url:t.url},...t.headers==null?{}:{headers:t.headers},...t.allowedTools==null?{}:{allowed_tools:t.allowedTools}});break;case`google.retrieval`:{let e=t.vertexAiSearchConfig??void 0;i.push({type:`retrieval`,...t.retrievalTypes==null?{retrieval_types:[`vertex_ai_search`]}:{retrieval_types:t.retrievalTypes},...e==null?{}:{vertex_ai_search_config:e}});break}default:n.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`provider-defined tool ${e.id} is not supported by google.interactions; tool dropped.`});break}continue}n.push({type:`unsupported`,feature:`tool of type ${e.type}`,details:`Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped.`})}let a=i.some(e=>e.type===`function`),o;if(t!=null&&a)switch(t.type){case`auto`:o=`auto`;break;case`required`:o=`any`;break;case`none`:o=`none`;break;case`tool`:o={allowed_tools:{mode:`validated`,tools:[t.toolName]}};break}return{tools:i.length>0?i:void 0,toolChoice:o,toolWarnings:n}}var Ut=3,Wt=500;function Gt({baseURL:e,interactionId:t,headers:n,fetch:r,abortSignal:i,maxRetries:a=Ut,retryDelayMs:o=Wt}){if(t.length===0)throw Error(`google.interactions: cannot stream a background interaction without an id.`);let s={...n,accept:`text/event-stream`},c,l=!1,u=0,d=!1,f,p=new AbortController,m=()=>p.abort();i!=null&&(i.aborted?p.abort():i.addEventListener(`abort`,m,{once:!0}));let h=p.signal;function g(){let n=`${e}/interactions/${encodeURIComponent(t)}`,r=new URLSearchParams({stream:`true`});return c!=null&&r.set(`last_event_id`,c),`${n}?${r.toString()}`}async function _(){let{value:e}=await R({url:g(),headers:s,failedResponseHandler:B,successfulResponseHandler:I(Ot),abortSignal:h,fetch:r});return e.getReader()}return new ReadableStream({async start(s){try{for(;!l&&!h.aborted;){if(f==null)try{f=await _(),d=!1}catch(e){if(L(e)||h.aborted){s.error(e);return}if(u++,u>=a){s.error(e);return}await k(o*u,{abortSignal:h});continue}try{let{done:e,value:t}=await f.read();if(e){if(f=void 0,l)break;if(d)u=0;else{if(u++,u>=a){s.error(Error(`google.interactions: SSE stream closed without producing any events.`));return}await k(o*u,{abortSignal:h})}continue}if(d=!0,t.success){let e=t.value;typeof e.event_id==`string`&&e.event_id.length>0&&(c=e.event_id),(e.event_type===`interaction.completed`||e.event_type===`error`)&&(l=!0)}s.enqueue(t)}catch(e){if(L(e)||h.aborted){s.error(e);return}if(f=void 0,u++,u>=a){s.error(e);return}await k(o*u,{abortSignal:h})}}s.close()}catch(e){s.error(e)}finally{i?.removeEventListener(`abort`,m),f?.cancel().catch(()=>{}),f=void 0,h.aborted&&!l&&await It({baseURL:e,interactionId:t,headers:n,fetch:r})}},cancel(){p.abort(),f?.cancel().catch(()=>{}),f=void 0}})}function Kt({response:e,warnings:t,generateId:n,includeRawChunks:r,headerServiceTier:i}){return new ReadableStream({start(a){a.enqueue({type:`stream-start`,warnings:t});let o=typeof e.id==`string`&&e.id.length>0?e.id:void 0,s,c=e.created;if(typeof c==`string`){let e=new Date(c);Number.isNaN(e.getTime())||(s=e)}a.enqueue({type:`response-metadata`,...o==null?{}:{id:o},modelId:e.model??void 0,...s?{timestamp:s}:{}}),r&&a.enqueue({type:`raw`,rawValue:e});let{content:l,hasFunctionCall:u}=Pt({steps:e.steps??null,generateId:n,interactionId:o}),d=0,f=()=>`${o??`agent`}:${d++}`;for(let e of l)switch(e.type){case`text`:{let t=f(),n=e.providerMetadata;a.enqueue({type:`text-start`,id:t}),e.text.length>0&&a.enqueue({type:`text-delta`,id:t,delta:e.text}),a.enqueue({type:`text-end`,id:t,...n?{providerMetadata:n}:{}});break}case`reasoning`:{let t=f(),n=e.providerMetadata;a.enqueue({type:`reasoning-start`,id:t}),e.text.length>0&&a.enqueue({type:`reasoning-delta`,id:t,delta:e.text}),a.enqueue({type:`reasoning-end`,id:t,...n?{providerMetadata:n}:{}});break}case`tool-call`:{let t=e.providerMetadata;a.enqueue({type:`tool-input-start`,id:e.toolCallId,toolName:e.toolName,...e.providerExecuted?{providerExecuted:e.providerExecuted}:{}}),a.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:e.input}),a.enqueue({type:`tool-input-end`,id:e.toolCallId}),a.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,...e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...t?{providerMetadata:t}:{}});break}case`tool-result`:a.enqueue({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,result:e.result});break;case`source`:case`file`:a.enqueue(e);break;default:break}let p=e.service_tier??i,m={unified:q({status:e.status,hasFunctionCall:u}),raw:e.status},h={google:{...o==null?{}:{interactionId:o},...p==null?{}:{serviceTier:p}}};a.enqueue({type:`finish`,finishReason:m,usage:G(e.usage),providerMetadata:h}),a.close()}})}var qt=class e{constructor(e,t){this.specificationVersion=`v4`,typeof e==`string`?(this.modelId=e,this.agent=void 0):`managedAgent`in e?(this.modelId=e.managedAgent,this.agent=e.managedAgent):(this.modelId=e.agent,this.agent=e.agent),this.config=t}static[O](e){return{...T({modelId:e.modelId,config:e.config}),agent:e.agent}}static[E](t){return new e(t.agent==null?t.modelId:{agent:t.agent},t.config)}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?this.config.supportedUrls():{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(e){let t=[],n=await _({provider:`google`,providerOptions:e.providerOptions,schema:kt}),r=this.agent!=null,i=e.tools!=null&&e.tools.length>0,a,o;if(i&&r)t.push({type:`other`,message:`google.interactions: tools are not supported when an agent is set; tools will be omitted from the request body.`});else if(i){let n=Ht({tools:e.tools,toolChoice:e.toolChoice});a=n.tools,o=n.toolChoice,t.push(...n.toolWarnings)}let s=[];if(e.responseFormat?.type===`json`)if(r)t.push({type:`other`,message:`google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored.`});else{let t={type:`text`,mime_type:`application/json`,...e.responseFormat.schema==null?{}:{schema:e.responseFormat.schema}};s.push(t)}if(n?.responseFormat!=null)for(let e of n.responseFormat)e.type===`text`?s.push(Q({type:`text`,mime_type:e.mimeType??void 0,schema:e.schema??void 0})):e.type===`image`?s.push(Q({type:`image`,mime_type:e.mimeType??void 0,aspect_ratio:e.aspectRatio??void 0,image_size:e.imageSize??void 0})):e.type===`audio`&&s.push(Q({type:`audio`,mime_type:e.mimeType??void 0}));let{input:c,systemInstruction:l,warnings:u}=pt({prompt:e.prompt,previousInteractionId:n?.previousInteractionId??void 0,store:n?.store??void 0,mediaResolution:n?.mediaResolution??void 0});t.push(...u);let d=l,f=n?.systemInstruction??void 0;d!=null&&f!=null?t.push({type:`other`,message:`google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message.`}):d==null&&f!=null&&(d=f);let p;if(r){let r=[];e.temperature!=null&&r.push(`temperature`),e.topP!=null&&r.push(`topP`),e.seed!=null&&r.push(`seed`),e.stopSequences!=null&&e.stopSequences.length>0&&r.push(`stopSequences`),e.maxOutputTokens!=null&&r.push(`maxOutputTokens`),n?.thinkingLevel!=null&&r.push(`thinkingLevel`),n?.thinkingSummaries!=null&&r.push(`thinkingSummaries`),n?.imageConfig!=null&&r.push(`imageConfig`),r.length>0&&t.push({type:`other`,message:`google.interactions: ${r.join(`, `)} ${r.length===1?`is`:`are`} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`}),p=void 0}else if(p=Q({temperature:e.temperature??void 0,top_p:e.topP??void 0,seed:e.seed??void 0,stop_sequences:e.stopSequences!=null&&e.stopSequences.length>0?e.stopSequences:void 0,max_output_tokens:e.maxOutputTokens??void 0,thinking_level:n?.thinkingLevel??void 0,thinking_summaries:n?.thinkingSummaries??void 0,tool_choice:o}),n?.imageConfig!=null){let e=s.some(e=>e.type===`image`);t.push({type:`other`,message:e?`google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively.`:`google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: "image", ... } entry instead.`}),e||s.push({type:`image`,mime_type:`image/png`,...n.imageConfig.aspectRatio==null?{}:{aspect_ratio:n.imageConfig.aspectRatio},...n.imageConfig.imageSize==null?{}:{image_size:n.imageConfig.imageSize}})}let m;if(r&&n?.agentConfig!=null){let e=n.agentConfig;e.type===`deep-research`?m=Q({type:`deep-research`,thinking_summaries:e.thinkingSummaries??void 0,visualization:e.visualization??void 0,collaborative_planning:e.collaborativePlanning??void 0}):e.type===`dynamic`&&(m={type:`dynamic`})}let h;if(n?.environment!=null)if(!r)t.push({type:`other`,message:`google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body.`});else if(typeof n.environment==`string`)h=n.environment;else{let e=n.environment,t=e.sources?.map(e=>e.type===`inline`?{type:`inline`,content:e.content,target:e.target}:Q({type:e.type,source:e.source,target:e.target??void 0})),r;e.network===`disabled`?r=`disabled`:e.network!=null&&(r={allowlist:e.network.allowlist.map(e=>Q({domain:e.domain,transform:e.transform??void 0}))}),h=Q({type:`remote`,sources:t!=null&&t.length>0?t:void 0,network:r})}return{args:Q({...r?{agent:this.agent}:{model:this.modelId},input:c,system_instruction:d,tools:a,response_format:s.length>0?s:void 0,response_modalities:n?.responseModalities==null?void 0:n.responseModalities,previous_interaction_id:n?.previousInteractionId??void 0,service_tier:n?.serviceTier??void 0,store:n?.store??void 0,generation_config:p!=null&&Object.keys(p).length>0?p:void 0,agent_config:m,environment:h,background:n?.background??void 0}),warnings:t,isAgent:r,isBackground:n?.background===!0,pollingTimeoutMs:n?.pollingTimeoutMs??void 0}}async doGenerate(e){let{args:t,warnings:n,isAgent:r,pollingTimeoutMs:i}=await this.getArgs(e),a=`${this.config.baseURL}/interactions`,o=F(Jt,this.config.headers?await z(this.config.headers):void 0,e.headers),{responseHeaders:s,value:c,rawValue:l}=await x({url:a,headers:o,body:t,failedResponseHandler:B,successfulResponseHandler:j(Y),abortSignal:e.abortSignal,fetch:this.config.fetch});if(r&&!Z(c.status)){let t=await Vt({baseURL:this.config.baseURL,interactionId:c.id,headers:o,fetch:this.config.fetch,abortSignal:e.abortSignal,timeoutMs:i});c=t.response,l=t.rawResponse,s=t.responseHeaders??s}let u=typeof c.id==`string`&&c.id.length>0?c.id:void 0,{content:d,hasFunctionCall:f}=Pt({steps:c.steps??null,generateId:this.config.generateId??A,interactionId:u}),p={unified:q({status:c.status,hasFunctionCall:f}),raw:c.status},m=c.service_tier??s?.[`x-gemini-service-tier`]??void 0,h={google:{...u==null?{}:{interactionId:u},...m==null?{}:{serviceTier:m}}},g;if(typeof c.created==`string`){let e=new Date(c.created);Number.isNaN(e.getTime())||(g=e)}return{content:d,finishReason:p,usage:G(c.usage),warnings:n,providerMetadata:h,request:{body:t},response:{headers:s,body:l,...u==null?{}:{id:u},...g?{timestamp:g}:{},modelId:c.model??void 0}}}async doStream(e){let{args:t,warnings:n,isBackground:r,pollingTimeoutMs:i}=await this.getArgs(e),a=`${this.config.baseURL}/interactions`,o=F(Jt,this.config.headers?await z(this.config.headers):void 0,e.headers);if(r)return this.doStreamBackground({args:t,warnings:n,url:a,mergedHeaders:o,options:e,pollingTimeoutMs:i});let s={...t,stream:!0},{responseHeaders:c,value:l}=await x({url:a,headers:o,body:s,failedResponseHandler:B,successfulResponseHandler:I(Ot),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=c?.[`x-gemini-service-tier`],d=ft({warnings:n,generateId:this.config.generateId??A,includeRawChunks:e.includeRawChunks,serviceTier:u});return{stream:l.pipeThrough(d),request:{body:s},response:{headers:c}}}async doStreamBackground({args:e,warnings:t,url:n,mergedHeaders:r,options:i,pollingTimeoutMs:a}){let{responseHeaders:o,value:s}=await x({url:n,headers:r,body:e,failedResponseHandler:B,successfulResponseHandler:j(Y),abortSignal:i.abortSignal,fetch:this.config.fetch}),c=s.id;if(c==null||c.length===0)throw Error(`google.interactions: background POST response did not include an interaction id; cannot stream the result.`);let l=o?.[`x-gemini-service-tier`];if(Z(s.status))return{stream:Kt({response:s,warnings:t,generateId:this.config.generateId??A,includeRawChunks:i.includeRawChunks,headerServiceTier:l}),request:{body:e},response:{headers:o}};let u=Gt({baseURL:this.config.baseURL,interactionId:c,headers:r,fetch:this.config.fetch,abortSignal:i.abortSignal}),d=ft({warnings:t,generateId:this.config.generateId??A,includeRawChunks:i.includeRawChunks,serviceTier:l});return{stream:u.pipeThrough(d),request:{body:e},response:{headers:o}}}},Jt={"Api-Revision":`2026-05-20`};function Q(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function $(e={}){let t=v(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=e.name??`google.generative-ai`,r=()=>re({"x-goog-api-key":p({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${ie}`),i=i=>new Oe(i,{provider:n,baseURL:t,headers:r,generateId:e.generateId??A,supportedUrls:()=>({"*":[RegExp(`^${t}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)]}),fetch:e.fetch}),a=i=>new se(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),o=(i,a={})=>new Ye(i,a,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),s=()=>new Ze({provider:n,baseURL:t,headers:r,fetch:e.fetch}),c=i=>new tt(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch,generateId:e.generateId??A}),l=i=>new qt(i,{provider:`${n}.interactions`,baseURL:t,headers:r,generateId:e.generateId??A,fetch:e.fetch}),u=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return i(e)};return u.specificationVersion=`v4`,u.languageModel=i,u.chat=i,u.generativeAI=i,u.embedding=a,u.embeddingModel=a,u.textEmbedding=a,u.textEmbeddingModel=a,u.image=o,u.imageModel=o,u.video=c,u.videoModel=c,u.files=s,u.interactions=l,u.tools=qe,u}var Yt=$();export{ie as VERSION,$ as createGoogle,$ as createGoogleGenerativeAI,Yt as google};
10
+ ${n.text}`};t[t.length-1]=r;continue}t.push(n)}return t}var q=()=>s({modality:o().nullish(),tokens:d().nullish()}).loose(),xt=()=>s({total_input_tokens:d().nullish(),total_output_tokens:d().nullish(),total_thought_tokens:d().nullish(),total_cached_tokens:d().nullish(),total_tool_use_tokens:d().nullish(),total_tokens:d().nullish(),input_tokens_by_modality:i(q()).nullish(),output_tokens_by_modality:i(q()).nullish(),cached_tokens_by_modality:i(q()).nullish(),tool_use_tokens_by_modality:i(q()).nullish(),grounding_tool_count:i(s({type:o().nullish(),count:d().nullish()}).loose()).nullish()}).loose(),St=()=>f([`in_progress`,`requires_action`,`completed`,`failed`,`cancelled`,`incomplete`]),Ct=()=>c([s({type:u(`url_citation`),url:o().nullish(),title:o().nullish(),start_index:d().nullish(),end_index:d().nullish()}).loose(),s({type:u(`file_citation`),file_name:o().nullish(),document_uri:o().nullish(),url:o().nullish(),page_number:d().nullish(),media_id:o().nullish(),start_index:d().nullish(),end_index:d().nullish(),custom_metadata:a(o(),l()).nullish()}).loose(),s({type:u(`place_citation`),name:o().nullish(),url:o().nullish(),place_id:o().nullish(),start_index:d().nullish(),end_index:d().nullish()}).loose(),s({type:o()}).loose()]),wt=()=>s({type:o(),text:o().nullish(),data:o().nullish(),mime_type:o().nullish()}).loose(),Tt=()=>c([s({type:u(`text`),text:o(),annotations:i(Ct()).nullish()}).loose(),s({type:u(`image`),data:o().nullish(),mime_type:o().nullish(),resolution:f([`low`,`medium`,`high`,`ultra_high`]).nullish(),uri:o().nullish()}).loose(),s({type:o()}).loose()]),Et=[`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`],J=[`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`],Dt=()=>c([s({type:u(`user_input`),content:i(Tt()).nullish()}).loose(),s({type:u(`model_output`),content:i(Tt()).nullish()}).loose(),s({type:u(`function_call`),id:o(),name:o(),arguments:a(o(),l()).nullish(),signature:o().nullish()}).loose(),s({type:u(`thought`),signature:o().nullish(),summary:i(wt()).nullish()}).loose(),s({type:f(Et),id:o(),arguments:a(o(),l()).nullish(),name:o().nullish(),server_name:o().nullish(),search_type:o().nullish(),signature:o().nullish()}).loose(),s({type:f(J),call_id:o(),result:l().nullish(),is_error:r().nullish(),name:o().nullish(),server_name:o().nullish(),signature:o().nullish()}).loose(),s({type:o()}).loose()]),Y=P(()=>D(s({id:o().nullish(),created:o().nullish(),updated:o().nullish(),status:St(),model:o().nullish(),agent:o().nullish(),steps:i(Dt()).nullish(),usage:xt().nullish(),service_tier:o().nullish(),previous_interaction_id:o().nullish(),response_modalities:i(o()).nullish()}).loose())),Ot=P(()=>D((()=>{let e=St(),t=Ct(),n=wt(),p=s({event_type:u(`interaction.created`),event_id:o().nullish(),interaction:s({id:o().nullish(),created:o().nullish(),model:o().nullish(),agent:o().nullish(),status:e.nullish()}).loose()}).loose(),m=s({event_type:u(`step.start`),event_id:o().nullish(),index:d(),step:Dt()}).loose(),h=s({type:u(`text`),text:o()}).loose(),g=s({type:u(`thought_summary`),content:n.nullish()}).loose(),_=s({type:u(`thought_signature`),signature:o().nullish()}).loose(),v=s({type:u(`arguments_delta`),arguments:o().nullish(),id:o().nullish(),signature:o().nullish()}).loose(),y=s({type:f([`text_annotation_delta`,`text_annotation`]),annotations:i(t).nullish()}).loose(),b=c([h,s({type:u(`image`),data:o().nullish(),mime_type:o().nullish(),resolution:f([`low`,`medium`,`high`,`ultra_high`]).nullish(),uri:o().nullish()}).loose(),g,_,v,y,s({type:f(Et),id:o().nullish(),arguments:a(o(),l()).nullish(),name:o().nullish(),server_name:o().nullish(),search_type:o().nullish(),signature:o().nullish()}).loose(),s({type:f(J),call_id:o().nullish(),result:l().nullish(),is_error:r().nullish(),name:o().nullish(),server_name:o().nullish(),signature:o().nullish()}).loose(),s({type:o()}).loose()]);return c([p,m,s({event_type:u(`step.delta`),event_id:o().nullish(),index:d(),delta:b}).loose(),s({event_type:u(`step.stop`),event_id:o().nullish(),index:d()}).loose(),s({event_type:u(`interaction.status_update`),event_id:o().nullish(),interaction_id:o().nullish(),status:e.nullish()}).loose(),s({event_type:u(`interaction.in_progress`),event_id:o().nullish(),interaction_id:o().nullish(),status:e.nullish()}).loose(),s({event_type:u(`interaction.requires_action`),event_id:o().nullish(),interaction_id:o().nullish(),status:e.nullish()}).loose(),s({event_type:u(`interaction.completed`),event_id:o().nullish(),interaction:s({id:o().nullish(),status:e.nullish(),usage:xt().nullish(),service_tier:o().nullish()}).loose()}).loose(),s({event_type:u(`error`),event_id:o().nullish(),error:s({code:o().nullish(),message:o().nullish()}).loose().nullish()}).loose(),s({event_type:o()}).loose()])})())),kt=P(()=>D(s({previousInteractionId:o().nullish(),store:r().nullish(),agent:o().nullish(),agentConfig:c([s({type:u(`dynamic`)}).loose(),s({type:u(`deep-research`),thinkingSummaries:f([`auto`,`none`]).nullish(),visualization:f([`off`,`auto`]).nullish(),collaborativePlanning:r().nullish()})]).nullish(),thinkingLevel:f([`minimal`,`low`,`medium`,`high`]).nullish(),thinkingSummaries:f([`auto`,`none`]).nullish(),responseFormat:i(c([s({type:u(`text`),mimeType:o().nullish(),schema:l().nullish()}).loose(),s({type:u(`image`),mimeType:o().nullish(),aspectRatio:f([`1:1`,`2:3`,`3:2`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`,`1:8`,`8:1`,`1:4`,`4:1`]).nullish(),imageSize:f([`1K`,`2K`,`4K`,`512`]).nullish()}).loose(),s({type:u(`audio`),mimeType:o().nullish()}).loose()])).nullish(),imageConfig:s({aspectRatio:f([`1:1`,`2:3`,`3:2`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`,`1:8`,`8:1`,`1:4`,`4:1`]).nullish(),imageSize:f([`1K`,`2K`,`4K`,`512`]).nullish()}).nullish(),mediaResolution:f([`low`,`medium`,`high`,`ultra_high`]).nullish(),responseModalities:i(f([`text`,`image`,`audio`,`video`,`document`])).nullish(),serviceTier:f([`flex`,`standard`,`priority`]).nullish(),systemInstruction:o().nullish(),signature:o().nullish(),interactionId:o().nullish(),pollingTimeoutMs:d().int().positive().nullish(),background:r().nullish(),environment:c([o(),s({type:u(`remote`),sources:i(c([s({type:u(`gcs`),source:o(),target:o().nullish()}),s({type:u(`repository`),source:o(),target:o().nullish()}),s({type:u(`inline`),content:o(),target:o()})])).nullish(),network:c([u(`disabled`),s({allowlist:i(s({domain:o(),transform:i(a(o(),o())).nullish()}))})]).nullish()})]).nullish()})));function X({signature:e,interactionId:t}){let n={};return e!=null&&(n.signature=e),t!=null&&(n.interactionId=t),Object.keys(n).length>0?{providerMetadata:{google:n}}:{}}var At=new Set([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),jt=new Set([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]);function Mt(e){return e.replace(/_call$/,``)}function Nt(e){return e.replace(/_result$/,``)}function Pt({steps:e,generateId:t,interactionId:n}){let r=[],i=!1;if(e==null)return{content:r,hasFunctionCall:i};for(let a of e){if(typeof a!=`object`||!a)continue;let e=a.type;if(typeof e==`string`)switch(e){case`user_input`:break;case`model_output`:{let e=a.content??[];for(let i of e){if(typeof i!=`object`||!i)continue;let e=i.type;if(e===`text`){let e=i.text??``,a=i.annotations;r.push({type:`text`,text:e,...X({interactionId:n})});let o=G({annotations:a,generateId:t});for(let e of o)r.push(e)}else if(e===`image`){let e=i;e.data!=null&&e.data.length>0?r.push({type:`file`,mediaType:e.mime_type??`image/png`,data:{type:`data`,data:e.data},...X({interactionId:n})}):e.uri!=null&&e.uri.length>0&&r.push({type:`file`,mediaType:e.mime_type??`image/png`,data:{type:`url`,url:new URL(e.uri)},...X({interactionId:n})})}}break}case`thought`:{let e=a,t=(Array.isArray(e.summary)?e.summary:[]).filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
11
+ `);r.push({type:`reasoning`,text:t,...X({signature:e.signature,interactionId:n})});break}case`function_call`:{i=!0;let e=a;r.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.arguments??{}),...X({signature:e.signature,interactionId:n})});break}default:if(At.has(e)){let n=a,i=e===`mcp_server_tool_call`?n.name??`mcp_server_tool`:Mt(e),o=JSON.stringify(n.arguments??{});r.push({type:`tool-call`,toolCallId:n.id??t(),toolName:i,input:o,providerExecuted:!0})}else if(jt.has(e)){let n=a,i=e===`mcp_server_tool_result`?n.name??`mcp_server_tool`:Nt(e);r.push({type:`tool-result`,toolCallId:n.call_id??t(),toolName:i,result:n.result??null});let o=ct({block:a,generateId:t});for(let e of o)r.push(e)}break}}return{content:r,hasFunctionCall:i}}var Ft=()=>globalThis.fetch;async function It({baseURL:e,interactionId:t,headers:n,fetch:r=Ft()}){if(t==null||t.length===0)return;let i=`${e}/interactions/${encodeURIComponent(t)}/cancel`;try{let e=await r(i,{method:`POST`,headers:ne(I({"Content-Type":`application/json`},n),S()),body:`{}`});try{await e.text()}catch{}}catch{}}var Lt=new Set([`completed`,`failed`,`cancelled`,`incomplete`]);function Z(e){return e!=null&&Lt.has(e)}var Rt=1e3,zt=1e4,Bt=1800*1e3;async function Vt({baseURL:e,interactionId:t,headers:n,fetch:r,abortSignal:i,initialDelayMs:a=Rt,maxDelayMs:o=zt,timeoutMs:s=Bt}){if(t==null||t.length===0)throw Error(`google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.`);let c=Date.now(),l=a,u=`${e}/interactions/${encodeURIComponent(t)}`,d=()=>It({baseURL:e,interactionId:t,headers:n,fetch:r});try{for(;;){if(i?.aborted)throw await d(),new DOMException(`Polling was aborted`,`AbortError`);if(Date.now()-c>s)throw Error(`google.interactions: timed out polling interaction ${t} after ${s}ms.`);await k(l,{abortSignal:i});let{value:e,rawValue:a,responseHeaders:f}=await z({url:u,headers:n,failedResponseHandler:V,successfulResponseHandler:M(Y),abortSignal:i,fetch:r});if(Z(e.status))return{response:e,rawResponse:a,responseHeaders:f};l=Math.min(l*2,o)}}catch(e){throw R(e)&&await d(),e}}function Ht({tools:e,toolChoice:t}){let n=[],r=e?.length?e:void 0;if(r==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let i=[];for(let e of r){if(e.type===`function`){i.push({type:`function`,name:e.name,description:e.description??``,parameters:e.inputSchema});continue}if(e.type===`provider`){let t=e.args??{};switch(e.id){case`google.google_search`:{let e=t.searchTypes,n;if(typeof e==`object`&&e){let t=[];e.webSearch!=null&&t.push(`web_search`),e.imageSearch!=null&&t.push(`image_search`),t.length>0&&(n=t)}i.push({type:`google_search`,...n==null?{}:{search_types:n}});break}case`google.code_execution`:i.push({type:`code_execution`});break;case`google.url_context`:i.push({type:`url_context`});break;case`google.file_search`:i.push({type:`file_search`,...t.fileSearchStoreNames==null?{}:{file_search_store_names:t.fileSearchStoreNames},...t.topK==null?{}:{top_k:t.topK},...t.metadataFilter==null?{}:{metadata_filter:t.metadataFilter}});break;case`google.google_maps`:i.push({type:`google_maps`,...t.latitude==null?{}:{latitude:t.latitude},...t.longitude==null?{}:{longitude:t.longitude},...t.enableWidget==null?{}:{enable_widget:t.enableWidget}});break;case`google.computer_use`:i.push({type:`computer_use`,environment:t.environment??`browser`,...t.excludedPredefinedFunctions==null?{}:{excludedPredefinedFunctions:t.excludedPredefinedFunctions}});break;case`google.mcp_server`:i.push({type:`mcp_server`,...t.name==null?{}:{name:t.name},...t.url==null?{}:{url:t.url},...t.headers==null?{}:{headers:t.headers},...t.allowedTools==null?{}:{allowed_tools:t.allowedTools}});break;case`google.retrieval`:{let e=t.vertexAiSearchConfig??void 0;i.push({type:`retrieval`,...t.retrievalTypes==null?{retrieval_types:[`vertex_ai_search`]}:{retrieval_types:t.retrievalTypes},...e==null?{}:{vertex_ai_search_config:e}});break}default:n.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`provider-defined tool ${e.id} is not supported by google.interactions; tool dropped.`});break}continue}n.push({type:`unsupported`,feature:`tool of type ${e.type}`,details:`Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped.`})}let a=i.some(e=>e.type===`function`),o;if(t!=null&&a)switch(t.type){case`auto`:o=`auto`;break;case`required`:o=`any`;break;case`none`:o=`none`;break;case`tool`:o={allowed_tools:{mode:`validated`,tools:[t.toolName]}};break}return{tools:i.length>0?i:void 0,toolChoice:o,toolWarnings:n}}var Ut=3,Wt=500;function Gt({baseURL:e,interactionId:t,headers:n,fetch:r,abortSignal:i,maxRetries:a=Ut,retryDelayMs:o=Wt}){if(t.length===0)throw Error(`google.interactions: cannot stream a background interaction without an id.`);let s={...n,accept:`text/event-stream`},c,l=!1,u=0,d=!1,f,p=new AbortController,m=()=>p.abort();i!=null&&(i.aborted?p.abort():i.addEventListener(`abort`,m,{once:!0}));let h=p.signal;function g(){let n=`${e}/interactions/${encodeURIComponent(t)}`,r=new URLSearchParams({stream:`true`});return c!=null&&r.set(`last_event_id`,c),`${n}?${r.toString()}`}async function _(){let{value:e}=await z({url:g(),headers:s,failedResponseHandler:V,successfulResponseHandler:L(Ot),abortSignal:h,fetch:r});return e.getReader()}return new ReadableStream({async start(s){try{for(;!l&&!h.aborted;){if(f==null)try{f=await _(),d=!1}catch(e){if(R(e)||h.aborted){s.error(e);return}if(u++,u>=a){s.error(e);return}await k(o*u,{abortSignal:h});continue}try{let{done:e,value:t}=await f.read();if(e){if(f=void 0,l)break;if(d)u=0;else{if(u++,u>=a){s.error(Error(`google.interactions: SSE stream closed without producing any events.`));return}await k(o*u,{abortSignal:h})}continue}if(d=!0,t.success){let e=t.value;typeof e.event_id==`string`&&e.event_id.length>0&&(c=e.event_id),(e.event_type===`interaction.completed`||e.event_type===`error`)&&(l=!0)}s.enqueue(t)}catch(e){if(R(e)||h.aborted){s.error(e);return}if(f=void 0,u++,u>=a){s.error(e);return}await k(o*u,{abortSignal:h})}}s.close()}catch(e){s.error(e)}finally{i?.removeEventListener(`abort`,m),f?.cancel().catch(()=>{}),f=void 0,h.aborted&&!l&&await It({baseURL:e,interactionId:t,headers:n,fetch:r})}},cancel(){p.abort(),f?.cancel().catch(()=>{}),f=void 0}})}function Kt({response:e,warnings:t,generateId:n,includeRawChunks:r,headerServiceTier:i}){return new ReadableStream({start(a){a.enqueue({type:`stream-start`,warnings:t});let o=typeof e.id==`string`&&e.id.length>0?e.id:void 0,s,c=e.created;if(typeof c==`string`){let e=new Date(c);Number.isNaN(e.getTime())||(s=e)}a.enqueue({type:`response-metadata`,...o==null?{}:{id:o},modelId:e.model??void 0,...s?{timestamp:s}:{}}),r&&a.enqueue({type:`raw`,rawValue:e});let{content:l,hasFunctionCall:u}=Pt({steps:e.steps??null,generateId:n,interactionId:o}),d=0,f=()=>`${o??`agent`}:${d++}`;for(let e of l)switch(e.type){case`text`:{let t=f(),n=e.providerMetadata;a.enqueue({type:`text-start`,id:t}),e.text.length>0&&a.enqueue({type:`text-delta`,id:t,delta:e.text}),a.enqueue({type:`text-end`,id:t,...n?{providerMetadata:n}:{}});break}case`reasoning`:{let t=f(),n=e.providerMetadata;a.enqueue({type:`reasoning-start`,id:t}),e.text.length>0&&a.enqueue({type:`reasoning-delta`,id:t,delta:e.text}),a.enqueue({type:`reasoning-end`,id:t,...n?{providerMetadata:n}:{}});break}case`tool-call`:{let t=e.providerMetadata;a.enqueue({type:`tool-input-start`,id:e.toolCallId,toolName:e.toolName,...e.providerExecuted?{providerExecuted:e.providerExecuted}:{}}),a.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:e.input}),a.enqueue({type:`tool-input-end`,id:e.toolCallId}),a.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,...e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...t?{providerMetadata:t}:{}});break}case`tool-result`:a.enqueue({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,result:e.result});break;case`source`:case`file`:a.enqueue(e);break;default:break}let p=e.service_tier??i,m={unified:K({status:e.status,hasFunctionCall:u}),raw:e.status},h={google:{...o==null?{}:{interactionId:o},...p==null?{}:{serviceTier:p}}};a.enqueue({type:`finish`,finishReason:m,usage:W(e.usage),providerMetadata:h}),a.close()}})}var qt=class e{constructor(e,t){this.specificationVersion=`v4`,typeof e==`string`?(this.modelId=e,this.agent=void 0):`managedAgent`in e?(this.modelId=e.managedAgent,this.agent=e.managedAgent):(this.modelId=e.agent,this.agent=e.agent),this.config=t}static[O](e){return{...T({modelId:e.modelId,config:e.config}),agent:e.agent}}static[E](t){return new e(t.agent==null?t.modelId:{agent:t.agent},t.config)}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?this.config.supportedUrls():{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(e){let t=[],n=await _({provider:`google`,providerOptions:e.providerOptions,schema:kt}),r=this.agent!=null,i=e.tools!=null&&e.tools.length>0,a,o;if(i&&r)t.push({type:`other`,message:`google.interactions: tools are not supported when an agent is set; tools will be omitted from the request body.`});else if(i){let n=Ht({tools:e.tools,toolChoice:e.toolChoice});a=n.tools,o=n.toolChoice,t.push(...n.toolWarnings)}let s=[];if(e.responseFormat?.type===`json`)if(r)t.push({type:`other`,message:`google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored.`});else{let t={type:`text`,mime_type:`application/json`,...e.responseFormat.schema==null?{}:{schema:e.responseFormat.schema}};s.push(t)}if(n?.responseFormat!=null)for(let e of n.responseFormat)e.type===`text`?s.push(Q({type:`text`,mime_type:e.mimeType??void 0,schema:e.schema??void 0})):e.type===`image`?s.push(Q({type:`image`,mime_type:e.mimeType??void 0,aspect_ratio:e.aspectRatio??void 0,image_size:e.imageSize??void 0})):e.type===`audio`&&s.push(Q({type:`audio`,mime_type:e.mimeType??void 0}));let{input:c,systemInstruction:l,warnings:u}=mt({prompt:e.prompt,previousInteractionId:n?.previousInteractionId??void 0,store:n?.store??void 0,mediaResolution:n?.mediaResolution??void 0});t.push(...u);let d=l,f=n?.systemInstruction??void 0;d!=null&&f!=null?t.push({type:`other`,message:`google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message.`}):d==null&&f!=null&&(d=f);let p;if(r){let r=[];e.temperature!=null&&r.push(`temperature`),e.topP!=null&&r.push(`topP`),e.seed!=null&&r.push(`seed`),e.stopSequences!=null&&e.stopSequences.length>0&&r.push(`stopSequences`),e.maxOutputTokens!=null&&r.push(`maxOutputTokens`),n?.thinkingLevel!=null&&r.push(`thinkingLevel`),n?.thinkingSummaries!=null&&r.push(`thinkingSummaries`),n?.imageConfig!=null&&r.push(`imageConfig`),r.length>0&&t.push({type:`other`,message:`google.interactions: ${r.join(`, `)} ${r.length===1?`is`:`are`} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`}),p=void 0}else if(p=Q({temperature:e.temperature??void 0,top_p:e.topP??void 0,seed:e.seed??void 0,stop_sequences:e.stopSequences!=null&&e.stopSequences.length>0?e.stopSequences:void 0,max_output_tokens:e.maxOutputTokens??void 0,thinking_level:n?.thinkingLevel??void 0,thinking_summaries:n?.thinkingSummaries??void 0,tool_choice:o}),n?.imageConfig!=null){let e=s.some(e=>e.type===`image`);t.push({type:`other`,message:e?`google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively.`:`google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: "image", ... } entry instead.`}),e||s.push({type:`image`,mime_type:`image/png`,...n.imageConfig.aspectRatio==null?{}:{aspect_ratio:n.imageConfig.aspectRatio},...n.imageConfig.imageSize==null?{}:{image_size:n.imageConfig.imageSize}})}let m;if(r&&n?.agentConfig!=null){let e=n.agentConfig;e.type===`deep-research`?m=Q({type:`deep-research`,thinking_summaries:e.thinkingSummaries??void 0,visualization:e.visualization??void 0,collaborative_planning:e.collaborativePlanning??void 0}):e.type===`dynamic`&&(m={type:`dynamic`})}let h;if(n?.environment!=null)if(!r)t.push({type:`other`,message:`google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body.`});else if(typeof n.environment==`string`)h=n.environment;else{let e=n.environment,t=e.sources?.map(e=>e.type===`inline`?{type:`inline`,content:e.content,target:e.target}:Q({type:e.type,source:e.source,target:e.target??void 0})),r;e.network===`disabled`?r=`disabled`:e.network!=null&&(r={allowlist:e.network.allowlist.map(e=>Q({domain:e.domain,transform:e.transform??void 0}))}),h=Q({type:`remote`,sources:t!=null&&t.length>0?t:void 0,network:r})}return{args:Q({...r?{agent:this.agent}:{model:this.modelId},input:c,system_instruction:d,tools:a,response_format:s.length>0?s:void 0,response_modalities:n?.responseModalities==null?void 0:n.responseModalities,previous_interaction_id:n?.previousInteractionId??void 0,service_tier:n?.serviceTier??void 0,store:n?.store??void 0,generation_config:p!=null&&Object.keys(p).length>0?p:void 0,agent_config:m,environment:h,background:n?.background??void 0}),warnings:t,isAgent:r,isBackground:n?.background===!0,pollingTimeoutMs:n?.pollingTimeoutMs??void 0}}async doGenerate(e){let{args:t,warnings:n,isAgent:r,pollingTimeoutMs:i}=await this.getArgs(e),a=`${this.config.baseURL}/interactions`,o=I(Jt,this.config.headers?await B(this.config.headers):void 0,e.headers),{responseHeaders:s,value:c,rawValue:l}=await x({url:a,headers:o,body:t,failedResponseHandler:V,successfulResponseHandler:M(Y),abortSignal:e.abortSignal,fetch:this.config.fetch});if(r&&!Z(c.status)){let t=await Vt({baseURL:this.config.baseURL,interactionId:c.id,headers:o,fetch:this.config.fetch,abortSignal:e.abortSignal,timeoutMs:i});c=t.response,l=t.rawResponse,s=t.responseHeaders??s}let u=typeof c.id==`string`&&c.id.length>0?c.id:void 0,{content:d,hasFunctionCall:f}=Pt({steps:c.steps??null,generateId:this.config.generateId??j,interactionId:u}),p={unified:K({status:c.status,hasFunctionCall:f}),raw:c.status},m=c.service_tier??s?.[`x-gemini-service-tier`]??void 0,h={google:{...u==null?{}:{interactionId:u},...m==null?{}:{serviceTier:m}}},g;if(typeof c.created==`string`){let e=new Date(c.created);Number.isNaN(e.getTime())||(g=e)}return{content:d,finishReason:p,usage:W(c.usage),warnings:n,providerMetadata:h,request:{body:t},response:{headers:s,body:l,...u==null?{}:{id:u},...g?{timestamp:g}:{},modelId:c.model??void 0}}}async doStream(e){let{args:t,warnings:n,isBackground:r,pollingTimeoutMs:i}=await this.getArgs(e),a=`${this.config.baseURL}/interactions`,o=I(Jt,this.config.headers?await B(this.config.headers):void 0,e.headers);if(r)return this.doStreamBackground({args:t,warnings:n,url:a,mergedHeaders:o,options:e,pollingTimeoutMs:i});let s={...t,stream:!0},{responseHeaders:c,value:l}=await x({url:a,headers:o,body:s,failedResponseHandler:V,successfulResponseHandler:L(Ot),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=c?.[`x-gemini-service-tier`],d=pt({warnings:n,generateId:this.config.generateId??j,includeRawChunks:e.includeRawChunks,serviceTier:u});return{stream:l.pipeThrough(d),request:{body:s},response:{headers:c}}}async doStreamBackground({args:e,warnings:t,url:n,mergedHeaders:r,options:i,pollingTimeoutMs:a}){let{responseHeaders:o,value:s}=await x({url:n,headers:r,body:e,failedResponseHandler:V,successfulResponseHandler:M(Y),abortSignal:i.abortSignal,fetch:this.config.fetch}),c=s.id;if(c==null||c.length===0)throw Error(`google.interactions: background POST response did not include an interaction id; cannot stream the result.`);let l=o?.[`x-gemini-service-tier`];if(Z(s.status))return{stream:Kt({response:s,warnings:t,generateId:this.config.generateId??j,includeRawChunks:i.includeRawChunks,headerServiceTier:l}),request:{body:e},response:{headers:o}};let u=Gt({baseURL:this.config.baseURL,interactionId:c,headers:r,fetch:this.config.fetch,abortSignal:i.abortSignal}),d=pt({warnings:t,generateId:this.config.generateId??j,includeRawChunks:i.includeRawChunks,serviceTier:l});return{stream:u.pipeThrough(d),request:{body:e},response:{headers:o}}}},Jt={"Api-Revision":`2026-05-20`};function Q(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function $(e={}){let t=v(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=e.name??`google.generative-ai`,r=()=>ne({"x-goog-api-key":p({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${re}`),i=i=>new Ee(i,{provider:n,baseURL:t,headers:r,generateId:e.generateId??j,supportedUrls:()=>({"*":[RegExp(`^${t}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)]}),fetch:e.fetch}),a=i=>new oe(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),o=(i,a={})=>new Ye(i,a,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),s=()=>new Qe({provider:n,baseURL:t,headers:r,fetch:e.fetch}),c=i=>new nt(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch,generateId:e.generateId??j}),l=i=>new qt(i,{provider:`${n}.interactions`,baseURL:t,headers:r,generateId:e.generateId??j,fetch:e.fetch}),u=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return i(e)};return u.specificationVersion=`v4`,u.languageModel=i,u.chat=i,u.generativeAI=i,u.embedding=a,u.embeddingModel=a,u.textEmbedding=a,u.textEmbeddingModel=a,u.image=o,u.imageModel=o,u.video=c,u.videoModel=c,u.files=s,u.interactions=l,u.tools=qe,u}var Yt=$();export{re as VERSION,$ as createGoogle,$ as createGoogleGenerativeAI,Yt as google};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "experimental-ash-compiled-ai-sdk-google",
3
- "version": "4.0.0-canary.69",
3
+ "version": "4.0.0-canary.73",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "license": "Apache-2.0"