@humain/humain-code 0.4.12 → 0.4.13

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 (539) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/dist/bun/sandbox-env-setup.js +1 -1
  3. package/dist/bun/sandbox-env-setup.js.map +1 -1
  4. package/dist/bundle/agent-monitor.js +1 -1
  5. package/dist/bundle/chunks/anthropic-messages-YSAHA7QM.js +67 -0
  6. package/dist/bundle/chunks/azure-openai-responses-Z5XYDPHS.js +15 -0
  7. package/dist/bundle/chunks/bedrock-converse-stream.js +393 -314
  8. package/dist/bundle/chunks/{chunk-EDKZRYWJ.js → chunk-2TTB6GIB.js} +2 -2
  9. package/dist/bundle/chunks/{chunk-HSDTSUZE.js → chunk-36Q5UVQL.js} +47 -89
  10. package/dist/bundle/chunks/chunk-4DXXZHY2.js +540 -0
  11. package/dist/bundle/chunks/{chunk-BKJU56SM.js → chunk-A7QKOI62.js} +142 -126
  12. package/dist/bundle/chunks/{chunk-UW4GMZL3.js → chunk-AIXI6RIE.js} +264 -248
  13. package/dist/bundle/chunks/{chunk-V5ZF7Q7L.js → chunk-BVHXWQLD.js} +52 -47
  14. package/dist/bundle/chunks/{chunk-I2ZWZAIV.js → chunk-COF5P635.js} +222 -148
  15. package/dist/bundle/chunks/{chunk-SCIGZFN5.js → chunk-DNGJMRJW.js} +11 -11
  16. package/dist/bundle/chunks/{chunk-XGO43DKL.js → chunk-DUSJT2W4.js} +21 -25
  17. package/dist/bundle/chunks/chunk-EYIYBQAR.js +7 -0
  18. package/dist/bundle/chunks/chunk-FRUFMISJ.js +505 -0
  19. package/dist/bundle/chunks/{chunk-R5VIAWGA.js → chunk-H2FY3PEV.js} +9 -8
  20. package/dist/bundle/chunks/{chunk-KGI4EX6R.js → chunk-JNHXXVLA.js} +126 -125
  21. package/dist/bundle/chunks/{chunk-45ZBHMQG.js → chunk-JQCWRL5K.js} +4 -4
  22. package/dist/bundle/chunks/{chunk-AS2Y2MO6.js → chunk-KK3KUUMM.js} +643 -624
  23. package/dist/bundle/chunks/{chunk-6KAMTNN3.js → chunk-L3J4P5JR.js} +1 -1
  24. package/dist/bundle/chunks/chunk-L6Z6JKKC.js +3 -0
  25. package/dist/bundle/chunks/{chunk-DZ5C66IU.js → chunk-LUL775V7.js} +33 -33
  26. package/dist/bundle/chunks/{chunk-BRXQUQSC.js → chunk-MF2NEHP4.js} +778 -775
  27. package/dist/bundle/chunks/chunk-MG5PX4KU.js +31 -0
  28. package/dist/bundle/chunks/{chunk-LCOHFEZZ.js → chunk-NNKA2PAP.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-HMWAH7ZY.js → chunk-OX2IBCCA.js} +53 -49
  30. package/dist/bundle/chunks/{chunk-WBJN6PEI.js → chunk-QYCOHSI7.js} +1 -1
  31. package/dist/bundle/chunks/{chunk-NLTW6A7G.js → chunk-TC7EANW4.js} +3730 -3353
  32. package/dist/bundle/chunks/{chunk-77EWF2NW.js → chunk-TJG52LZB.js} +1 -1
  33. package/dist/bundle/chunks/{chunk-5XD3DHYL.js → chunk-UDVC7A5S.js} +1 -1
  34. package/dist/bundle/chunks/chunk-UGXYG7HN.js +22 -0
  35. package/dist/bundle/chunks/{chunk-VYIIPF57.js → chunk-UHLW4KJ7.js} +419 -413
  36. package/dist/bundle/chunks/{chunk-FF26YENK.js → chunk-W2QRCQBX.js} +4 -3
  37. package/dist/bundle/chunks/chunk-XQRYOCHA.js +26 -0
  38. package/dist/bundle/chunks/{chunk-7Z5MWPYE.js → chunk-Y3RFGBG2.js} +1 -1
  39. package/dist/bundle/chunks/chunk-YJ3NQWES.js +9 -0
  40. package/dist/bundle/chunks/{chunk-YJBE3IGR.js → chunk-YRCLNWFV.js} +20 -20
  41. package/dist/bundle/chunks/chunk-YZMQXAJM.js +8 -0
  42. package/dist/bundle/chunks/{chunk-BHM75BJJ.js → chunk-Z74ZYQPX.js} +207 -79
  43. package/dist/bundle/chunks/{cli-5ACW3WND.js → cli-SRI4UOSL.js} +6 -6
  44. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-FZ3UQCZ7.js → cloudflare-workers-ai-system-one-JGN7NZCV.js} +1 -1
  45. package/dist/bundle/chunks/codemode-worker.js +27 -14
  46. package/dist/bundle/chunks/{compat-KXWWOFHQ.js → compat-PCHMBE76.js} +6 -6
  47. package/dist/bundle/chunks/dist-MNSGVI4C.js +7 -0
  48. package/dist/bundle/chunks/{dist-6SWVHFCS.js → dist-UWE5M6HK.js} +211 -8
  49. package/dist/bundle/chunks/{dist-cjs-RL2OCAP2.js → dist-cjs-4BMVQ74V.js} +1 -1
  50. package/dist/bundle/chunks/{easter-egg-3d-3L3IKAT6.js → easter-egg-3d-ZJ2JUFOA.js} +1 -1
  51. package/dist/bundle/chunks/es-YEFEOGR3.js +1905 -0
  52. package/dist/bundle/chunks/{esm-763X2IA7.js → esm-NCUV2DF7.js} +1 -1
  53. package/dist/bundle/chunks/{event-streams-R5OECII4.js → event-streams-NXFTZDSF.js} +1 -1
  54. package/dist/bundle/chunks/execute-LRTXH4YJ.js +553 -0
  55. package/dist/bundle/chunks/{extract-DLZ425VI.js → extract-OZW5JHG6.js} +140 -120
  56. package/dist/bundle/chunks/{google-generative-ai-JD2FVOIX.js → google-generative-ai-YXXFSTX7.js} +2 -2
  57. package/dist/bundle/chunks/{google-vertex-PFBMDCBW.js → google-vertex-3IVWLYJ5.js} +2 -2
  58. package/dist/bundle/chunks/host-2RMBOGA7.js +2 -0
  59. package/dist/bundle/chunks/{mistral-conversations-D74NZ65O.js → mistral-conversations-Y7GWO3QB.js} +14 -13
  60. package/dist/bundle/chunks/{node-W47VUEGE.js → node-ELWNZC34.js} +328 -337
  61. package/dist/bundle/chunks/{node-4GGYDW5Q.js → node-SPBTZUUS.js} +26 -25
  62. package/dist/bundle/chunks/{openai-codex-responses-JAAA7MSS.js → openai-codex-responses-NSXWHIDT.js} +3 -4
  63. package/dist/bundle/chunks/{openai-completions-PGPMGQPU.js → openai-completions-WGBQHTYA.js} +9 -8
  64. package/dist/bundle/chunks/{openai-decisions-QQ4MEABI.js → openai-decisions-QWEISDVO.js} +1 -1
  65. package/dist/bundle/chunks/{openai-responses-FG2R2M4L.js → openai-responses-OKGCSIEY.js} +6 -6
  66. package/dist/bundle/chunks/{openrouter-images-NTBP3UUE.js → openrouter-images-BMVMAROU.js} +1 -1
  67. package/dist/bundle/chunks/{pi-messages-JD4O7KIP.js → pi-messages-XNEG23NU.js} +1 -1
  68. package/dist/bundle/chunks/runtime-VGSK3QCM.js +2 -0
  69. package/dist/bundle/chunks/{typesafe-system-one-TTC7YCO3.js → typesafe-system-one-62YHYXZV.js} +1 -1
  70. package/dist/bundle/chunks/{undici-EEOUTE5F.js → undici-7EW63V4X.js} +1 -1
  71. package/dist/bundle/chunks/virtual-modules-JSGQ72M6.js +5 -0
  72. package/dist/bundle/cli-runtime.js +3 -3
  73. package/dist/bundle/flow/package.json +5 -6
  74. package/dist/bundle/index.js +6 -6
  75. package/dist/bundle/rpc-entry.js +2 -2
  76. package/dist/coordination/adapter/delivery.d.ts.map +1 -1
  77. package/dist/coordination/adapter/delivery.js +1 -0
  78. package/dist/coordination/adapter/delivery.js.map +1 -1
  79. package/dist/coordination/adapter/index.d.ts.map +1 -1
  80. package/dist/coordination/adapter/index.js +3 -1
  81. package/dist/coordination/adapter/index.js.map +1 -1
  82. package/dist/coordination/adapter/receipts.d.ts +2 -1
  83. package/dist/coordination/adapter/receipts.d.ts.map +1 -1
  84. package/dist/coordination/adapter/receipts.js +7 -4
  85. package/dist/coordination/adapter/receipts.js.map +1 -1
  86. package/dist/coordination/adapter/supervisor.d.ts.map +1 -1
  87. package/dist/coordination/adapter/supervisor.js +8 -0
  88. package/dist/coordination/adapter/supervisor.js.map +1 -1
  89. package/dist/coordination/broker/broker.d.ts +11 -0
  90. package/dist/coordination/broker/broker.d.ts.map +1 -1
  91. package/dist/coordination/broker/broker.js +195 -18
  92. package/dist/coordination/broker/broker.js.map +1 -1
  93. package/dist/coordination/client/client.d.ts +5 -0
  94. package/dist/coordination/client/client.d.ts.map +1 -1
  95. package/dist/coordination/client/client.js +23 -9
  96. package/dist/coordination/client/client.js.map +1 -1
  97. package/dist/coordination/transport/protocol.d.ts.map +1 -1
  98. package/dist/coordination/transport/protocol.js +8 -1
  99. package/dist/coordination/transport/protocol.js.map +1 -1
  100. package/dist/coordination/transport/types.d.ts +6 -0
  101. package/dist/coordination/transport/types.d.ts.map +1 -1
  102. package/dist/coordination/transport/types.js +2 -1
  103. package/dist/coordination/transport/types.js.map +1 -1
  104. package/dist/core/agent-session.d.ts +44 -2
  105. package/dist/core/agent-session.d.ts.map +1 -1
  106. package/dist/core/agent-session.js +305 -124
  107. package/dist/core/agent-session.js.map +1 -1
  108. package/dist/core/auth-storage.d.ts.map +1 -1
  109. package/dist/core/auth-storage.js +20 -13
  110. package/dist/core/auth-storage.js.map +1 -1
  111. package/dist/core/auto-effort.d.ts +16 -0
  112. package/dist/core/auto-effort.d.ts.map +1 -0
  113. package/dist/core/auto-effort.js +69 -0
  114. package/dist/core/auto-effort.js.map +1 -0
  115. package/dist/core/auto-session-namer.d.ts.map +1 -1
  116. package/dist/core/auto-session-namer.js +2 -12
  117. package/dist/core/auto-session-namer.js.map +1 -1
  118. package/dist/core/bug-report.d.ts +11 -1
  119. package/dist/core/bug-report.d.ts.map +1 -1
  120. package/dist/core/bug-report.js +2 -2
  121. package/dist/core/bug-report.js.map +1 -1
  122. package/dist/core/compaction/branch-summarization.d.ts +3 -2
  123. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  124. package/dist/core/compaction/branch-summarization.js +1 -1
  125. package/dist/core/compaction/branch-summarization.js.map +1 -1
  126. package/dist/core/compaction/compaction.d.ts +13 -4
  127. package/dist/core/compaction/compaction.d.ts.map +1 -1
  128. package/dist/core/compaction/compaction.js +94 -5
  129. package/dist/core/compaction/compaction.js.map +1 -1
  130. package/dist/core/compaction/utils.d.ts +6 -0
  131. package/dist/core/compaction/utils.d.ts.map +1 -1
  132. package/dist/core/compaction/utils.js +7 -8
  133. package/dist/core/compaction/utils.js.map +1 -1
  134. package/dist/core/extensions/index.d.ts +1 -1
  135. package/dist/core/extensions/index.d.ts.map +1 -1
  136. package/dist/core/extensions/index.js.map +1 -1
  137. package/dist/core/extensions/runner.d.ts +4 -2
  138. package/dist/core/extensions/runner.d.ts.map +1 -1
  139. package/dist/core/extensions/runner.js +6 -3
  140. package/dist/core/extensions/runner.js.map +1 -1
  141. package/dist/core/extensions/types.d.ts +33 -7
  142. package/dist/core/extensions/types.d.ts.map +1 -1
  143. package/dist/core/extensions/types.js.map +1 -1
  144. package/dist/core/key-id-schema.d.ts +6 -0
  145. package/dist/core/key-id-schema.d.ts.map +1 -0
  146. package/dist/core/key-id-schema.js +16 -0
  147. package/dist/core/key-id-schema.js.map +1 -0
  148. package/dist/core/keybindings-schema.d.ts +4 -0
  149. package/dist/core/keybindings-schema.d.ts.map +1 -0
  150. package/dist/core/keybindings-schema.js +16 -0
  151. package/dist/core/keybindings-schema.js.map +1 -0
  152. package/dist/core/keybindings.d.ts +198 -63
  153. package/dist/core/keybindings.d.ts.map +1 -1
  154. package/dist/core/keybindings.js +26 -23
  155. package/dist/core/keybindings.js.map +1 -1
  156. package/dist/core/model-config.d.ts +695 -74
  157. package/dist/core/model-config.d.ts.map +1 -1
  158. package/dist/core/model-config.js +16 -166
  159. package/dist/core/model-config.js.map +1 -1
  160. package/dist/core/model-runtime.d.ts.map +1 -1
  161. package/dist/core/model-runtime.js +39 -4
  162. package/dist/core/model-runtime.js.map +1 -1
  163. package/dist/core/package-manager.d.ts.map +1 -1
  164. package/dist/core/package-manager.js +3 -3
  165. package/dist/core/package-manager.js.map +1 -1
  166. package/dist/core/project-trust.d.ts.map +1 -1
  167. package/dist/core/project-trust.js +2 -1
  168. package/dist/core/project-trust.js.map +1 -1
  169. package/dist/core/remote-catalog-provider.d.ts +13 -1
  170. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  171. package/dist/core/remote-catalog-provider.js +110 -27
  172. package/dist/core/remote-catalog-provider.js.map +1 -1
  173. package/dist/core/resource-loader.d.ts.map +1 -1
  174. package/dist/core/resource-loader.js +5 -1
  175. package/dist/core/resource-loader.js.map +1 -1
  176. package/dist/core/session-export.d.ts.map +1 -1
  177. package/dist/core/session-export.js +2 -2
  178. package/dist/core/session-export.js.map +1 -1
  179. package/dist/core/session-manager.d.ts +36 -5
  180. package/dist/core/session-manager.d.ts.map +1 -1
  181. package/dist/core/session-manager.js +164 -40
  182. package/dist/core/session-manager.js.map +1 -1
  183. package/dist/core/settings-defaults.d.ts +65 -0
  184. package/dist/core/settings-defaults.d.ts.map +1 -0
  185. package/dist/core/settings-defaults.js +66 -0
  186. package/dist/core/settings-defaults.js.map +1 -0
  187. package/dist/core/settings-manager.d.ts +10 -175
  188. package/dist/core/settings-manager.d.ts.map +1 -1
  189. package/dist/core/settings-manager.js +64 -44
  190. package/dist/core/settings-manager.js.map +1 -1
  191. package/dist/core/settings-schema.d.ts +257 -0
  192. package/dist/core/settings-schema.d.ts.map +1 -0
  193. package/dist/core/settings-schema.js +311 -0
  194. package/dist/core/settings-schema.js.map +1 -0
  195. package/dist/core/tools/edit-diff.d.ts +4 -1
  196. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  197. package/dist/core/tools/edit-diff.js +480 -29
  198. package/dist/core/tools/edit-diff.js.map +1 -1
  199. package/dist/core/tools/render-utils.d.ts +18 -0
  200. package/dist/core/tools/render-utils.d.ts.map +1 -1
  201. package/dist/core/tools/render-utils.js +46 -0
  202. package/dist/core/tools/render-utils.js.map +1 -1
  203. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  204. package/dist/core/tools/renderers/bash.js +17 -46
  205. package/dist/core/tools/renderers/bash.js.map +1 -1
  206. package/dist/core/tools/renderers/edit.d.ts +19 -1
  207. package/dist/core/tools/renderers/edit.d.ts.map +1 -1
  208. package/dist/core/tools/renderers/edit.js +38 -7
  209. package/dist/core/tools/renderers/edit.js.map +1 -1
  210. package/dist/core/tools/renderers/find.d.ts.map +1 -1
  211. package/dist/core/tools/renderers/find.js +3 -0
  212. package/dist/core/tools/renderers/find.js.map +1 -1
  213. package/dist/core/tools/renderers/grep.d.ts.map +1 -1
  214. package/dist/core/tools/renderers/grep.js +3 -0
  215. package/dist/core/tools/renderers/grep.js.map +1 -1
  216. package/dist/core/tools/renderers/highlighting.d.ts +13 -0
  217. package/dist/core/tools/renderers/highlighting.d.ts.map +1 -0
  218. package/dist/core/tools/renderers/highlighting.js +42 -0
  219. package/dist/core/tools/renderers/highlighting.js.map +1 -0
  220. package/dist/core/tools/renderers/ls.d.ts.map +1 -1
  221. package/dist/core/tools/renderers/ls.js +3 -0
  222. package/dist/core/tools/renderers/ls.js.map +1 -1
  223. package/dist/core/tools/renderers/read.d.ts.map +1 -1
  224. package/dist/core/tools/renderers/read.js +3 -0
  225. package/dist/core/tools/renderers/read.js.map +1 -1
  226. package/dist/core/tools/renderers/write.d.ts.map +1 -1
  227. package/dist/core/tools/renderers/write.js +3 -1
  228. package/dist/core/tools/renderers/write.js.map +1 -1
  229. package/dist/core/tools/subagent.d.ts +4 -0
  230. package/dist/core/tools/subagent.d.ts.map +1 -1
  231. package/dist/core/tools/subagent.js +85 -8
  232. package/dist/core/tools/subagent.js.map +1 -1
  233. package/dist/core/tools/truncate.d.ts.map +1 -1
  234. package/dist/core/tools/truncate.js +92 -44
  235. package/dist/core/tools/truncate.js.map +1 -1
  236. package/dist/core/usage-totals.d.ts +8 -1
  237. package/dist/core/usage-totals.d.ts.map +1 -1
  238. package/dist/core/usage-totals.js +106 -10
  239. package/dist/core/usage-totals.js.map +1 -1
  240. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  241. package/dist/extensions/codemode/execute.js +64 -45
  242. package/dist/extensions/codemode/execute.js.map +1 -1
  243. package/dist/extensions/codemode/index.d.ts.map +1 -1
  244. package/dist/extensions/codemode/index.js +2 -1
  245. package/dist/extensions/codemode/index.js.map +1 -1
  246. package/dist/extensions/codemode/renderer.d.ts +2 -2
  247. package/dist/extensions/codemode/renderer.d.ts.map +1 -1
  248. package/dist/extensions/codemode/renderer.js +9 -3
  249. package/dist/extensions/codemode/renderer.js.map +1 -1
  250. package/dist/extensions/codemode/tool.d.ts +6 -12
  251. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  252. package/dist/extensions/codemode/tool.js +44 -32
  253. package/dist/extensions/codemode/tool.js.map +1 -1
  254. package/dist/extensions/mcp/cli.js +5 -8
  255. package/dist/extensions/mcp/cli.js.map +1 -1
  256. package/dist/extensions/mcp/index.d.ts.map +1 -1
  257. package/dist/extensions/mcp/index.js +26 -23
  258. package/dist/extensions/mcp/index.js.map +1 -1
  259. package/dist/extensions/mcp/resources.d.ts +0 -6
  260. package/dist/extensions/mcp/resources.d.ts.map +1 -1
  261. package/dist/extensions/mcp/resources.js +1 -1
  262. package/dist/extensions/mcp/resources.js.map +1 -1
  263. package/dist/extensions/mcp/runtime.d.ts +3 -6
  264. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  265. package/dist/extensions/mcp/runtime.js +4 -39
  266. package/dist/extensions/mcp/runtime.js.map +1 -1
  267. package/dist/extensions/mcp/tools.d.ts +2 -3
  268. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  269. package/dist/extensions/mcp/tools.js +62 -6
  270. package/dist/extensions/mcp/tools.js.map +1 -1
  271. package/dist/extensions/tool-search/tool.d.ts +0 -2
  272. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  273. package/dist/extensions/tool-search/tool.js +2 -4
  274. package/dist/extensions/tool-search/tool.js.map +1 -1
  275. package/dist/humain/adhd/index.d.ts +3 -2
  276. package/dist/humain/adhd/index.d.ts.map +1 -1
  277. package/dist/humain/adhd/index.js +22 -10
  278. package/dist/humain/adhd/index.js.map +1 -1
  279. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +306 -20
  280. package/dist/humain/caveman/index.d.ts +4 -2
  281. package/dist/humain/caveman/index.d.ts.map +1 -1
  282. package/dist/humain/caveman/index.js +51 -16
  283. package/dist/humain/caveman/index.js.map +1 -1
  284. package/dist/humain/ponytail/index.d.ts +2 -0
  285. package/dist/humain/ponytail/index.d.ts.map +1 -1
  286. package/dist/humain/ponytail/index.js +2 -0
  287. package/dist/humain/ponytail/index.js.map +1 -1
  288. package/dist/humain/ponytail/vendor/hooks/ponytail-config.d.ts.map +1 -1
  289. package/dist/humain/ponytail/vendor/hooks/ponytail-config.js +39 -9
  290. package/dist/humain/ponytail/vendor/hooks/ponytail-config.js.map +1 -1
  291. package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.js +1 -1
  292. package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.js.map +1 -1
  293. package/dist/humain/ponytail/vendor/pi-extension/index.d.ts +4 -0
  294. package/dist/humain/ponytail/vendor/pi-extension/index.d.ts.map +1 -1
  295. package/dist/humain/ponytail/vendor/pi-extension/index.js +8 -0
  296. package/dist/humain/ponytail/vendor/pi-extension/index.js.map +1 -1
  297. package/dist/humain/web-access/vendor/baizhi.js.map +1 -1
  298. package/dist/humain/web-access/vendor/brave.d.ts.map +1 -1
  299. package/dist/humain/web-access/vendor/brave.js +19 -2
  300. package/dist/humain/web-access/vendor/brave.js.map +1 -1
  301. package/dist/humain/web-access/vendor/ceramic.d.ts +4 -0
  302. package/dist/humain/web-access/vendor/ceramic.d.ts.map +1 -0
  303. package/dist/humain/web-access/vendor/ceramic.js +212 -0
  304. package/dist/humain/web-access/vendor/ceramic.js.map +1 -0
  305. package/dist/humain/web-access/vendor/content-find.d.ts.map +1 -1
  306. package/dist/humain/web-access/vendor/content-find.js +2 -1
  307. package/dist/humain/web-access/vendor/content-find.js.map +1 -1
  308. package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -1
  309. package/dist/humain/web-access/vendor/curator-page.js +3 -1
  310. package/dist/humain/web-access/vendor/curator-page.js.map +1 -1
  311. package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -1
  312. package/dist/humain/web-access/vendor/curator-server.js +2 -0
  313. package/dist/humain/web-access/vendor/curator-server.js.map +1 -1
  314. package/dist/humain/web-access/vendor/duckduckgo.d.ts.map +1 -1
  315. package/dist/humain/web-access/vendor/duckduckgo.js +5 -1
  316. package/dist/humain/web-access/vendor/duckduckgo.js.map +1 -1
  317. package/dist/humain/web-access/vendor/endpoint-pdf-extract.d.ts +23 -0
  318. package/dist/humain/web-access/vendor/endpoint-pdf-extract.d.ts.map +1 -0
  319. package/dist/humain/web-access/vendor/endpoint-pdf-extract.js +193 -0
  320. package/dist/humain/web-access/vendor/endpoint-pdf-extract.js.map +1 -0
  321. package/dist/humain/web-access/vendor/extract.d.ts +5 -1
  322. package/dist/humain/web-access/vendor/extract.d.ts.map +1 -1
  323. package/dist/humain/web-access/vendor/extract.js +49 -12
  324. package/dist/humain/web-access/vendor/extract.js.map +1 -1
  325. package/dist/humain/web-access/vendor/fetch-params.d.ts +2 -0
  326. package/dist/humain/web-access/vendor/fetch-params.d.ts.map +1 -1
  327. package/dist/humain/web-access/vendor/fetch-params.js +9 -0
  328. package/dist/humain/web-access/vendor/fetch-params.js.map +1 -1
  329. package/dist/humain/web-access/vendor/gemini-api.d.ts +5 -0
  330. package/dist/humain/web-access/vendor/gemini-api.d.ts.map +1 -1
  331. package/dist/humain/web-access/vendor/gemini-api.js +16 -0
  332. package/dist/humain/web-access/vendor/gemini-api.js.map +1 -1
  333. package/dist/humain/web-access/vendor/gemini-search.d.ts +3 -3
  334. package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -1
  335. package/dist/humain/web-access/vendor/gemini-search.js +48 -172
  336. package/dist/humain/web-access/vendor/gemini-search.js.map +1 -1
  337. package/dist/humain/web-access/vendor/github-extract.d.ts +7 -0
  338. package/dist/humain/web-access/vendor/github-extract.d.ts.map +1 -1
  339. package/dist/humain/web-access/vendor/github-extract.js +31 -2
  340. package/dist/humain/web-access/vendor/github-extract.js.map +1 -1
  341. package/dist/humain/web-access/vendor/github-issue-pr.d.ts +2 -0
  342. package/dist/humain/web-access/vendor/github-issue-pr.d.ts.map +1 -1
  343. package/dist/humain/web-access/vendor/github-issue-pr.js +86 -74
  344. package/dist/humain/web-access/vendor/github-issue-pr.js.map +1 -1
  345. package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
  346. package/dist/humain/web-access/vendor/index.js +68 -27
  347. package/dist/humain/web-access/vendor/index.js.map +1 -1
  348. package/dist/humain/web-access/vendor/openai-search.js +3 -3
  349. package/dist/humain/web-access/vendor/openai-search.js.map +1 -1
  350. package/dist/humain/web-access/vendor/page-query.d.ts.map +1 -1
  351. package/dist/humain/web-access/vendor/page-query.js +6 -9
  352. package/dist/humain/web-access/vendor/page-query.js.map +1 -1
  353. package/dist/humain/web-access/vendor/parallel-mcp.d.ts.map +1 -1
  354. package/dist/humain/web-access/vendor/parallel-mcp.js +2 -0
  355. package/dist/humain/web-access/vendor/parallel-mcp.js.map +1 -1
  356. package/dist/humain/web-access/vendor/pdf-extract.d.ts +1 -1
  357. package/dist/humain/web-access/vendor/pdf-extract.d.ts.map +1 -1
  358. package/dist/humain/web-access/vendor/pdf-extract.js +31 -1
  359. package/dist/humain/web-access/vendor/pdf-extract.js.map +1 -1
  360. package/dist/humain/web-access/vendor/perplexity.d.ts.map +1 -1
  361. package/dist/humain/web-access/vendor/perplexity.js +21 -2
  362. package/dist/humain/web-access/vendor/perplexity.js.map +1 -1
  363. package/dist/humain/web-access/vendor/query-rewrite.js +1 -1
  364. package/dist/humain/web-access/vendor/query-rewrite.js.map +1 -1
  365. package/dist/humain/web-access/vendor/ssrf-protection.d.ts +4 -0
  366. package/dist/humain/web-access/vendor/ssrf-protection.d.ts.map +1 -1
  367. package/dist/humain/web-access/vendor/ssrf-protection.js +19 -4
  368. package/dist/humain/web-access/vendor/ssrf-protection.js.map +1 -1
  369. package/dist/humain/web-access/vendor/storage.d.ts +14 -0
  370. package/dist/humain/web-access/vendor/storage.d.ts.map +1 -1
  371. package/dist/humain/web-access/vendor/storage.js +48 -0
  372. package/dist/humain/web-access/vendor/storage.js.map +1 -1
  373. package/dist/humain/web-access/vendor/summary-review.d.ts.map +1 -1
  374. package/dist/humain/web-access/vendor/summary-review.js +18 -6
  375. package/dist/humain/web-access/vendor/summary-review.js.map +1 -1
  376. package/dist/humain/web-access/vendor/tool-arguments.d.ts.map +1 -1
  377. package/dist/humain/web-access/vendor/tool-arguments.js +5 -2
  378. package/dist/humain/web-access/vendor/tool-arguments.js.map +1 -1
  379. package/dist/humain/web-access/vendor/utils.d.ts.map +1 -1
  380. package/dist/humain/web-access/vendor/utils.js +21 -6
  381. package/dist/humain/web-access/vendor/utils.js.map +1 -1
  382. package/dist/humain/web-access/vendor/video-extract.js +6 -2
  383. package/dist/humain/web-access/vendor/video-extract.js.map +1 -1
  384. package/dist/humain/web-access/vendor/web-tool-core.d.ts +2 -1
  385. package/dist/humain/web-access/vendor/web-tool-core.d.ts.map +1 -1
  386. package/dist/humain/web-access/vendor/web-tool-core.js +56 -13
  387. package/dist/humain/web-access/vendor/web-tool-core.js.map +1 -1
  388. package/dist/humain/web-access/vendor/zai.js.map +1 -1
  389. package/dist/index.d.ts +3 -3
  390. package/dist/index.d.ts.map +1 -1
  391. package/dist/index.js.map +1 -1
  392. package/dist/main.js +3 -3
  393. package/dist/main.js.map +1 -1
  394. package/dist/modes/interactive/components/assistant-message.d.ts +21 -1
  395. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  396. package/dist/modes/interactive/components/assistant-message.js +79 -10
  397. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  398. package/dist/modes/interactive/components/footer.d.ts +8 -3
  399. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  400. package/dist/modes/interactive/components/footer.js +156 -133
  401. package/dist/modes/interactive/components/footer.js.map +1 -1
  402. package/dist/modes/interactive/components/mermaid.js +1 -1
  403. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  404. package/dist/modes/interactive/components/settings-selector.d.ts +10 -1
  405. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  406. package/dist/modes/interactive/components/settings-selector.js +83 -7
  407. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  408. package/dist/modes/interactive/components/status-indicator.d.ts +1 -1
  409. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  410. package/dist/modes/interactive/components/status-indicator.js +2 -2
  411. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  412. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -1
  413. package/dist/modes/interactive/components/themed-text.js +3 -1
  414. package/dist/modes/interactive/components/themed-text.js.map +1 -1
  415. package/dist/modes/interactive/components/tool-execution.d.ts +7 -1
  416. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  417. package/dist/modes/interactive/components/tool-execution.js +36 -19
  418. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  419. package/dist/modes/interactive/components/transcript-container.d.ts +12 -0
  420. package/dist/modes/interactive/components/transcript-container.d.ts.map +1 -0
  421. package/dist/modes/interactive/components/transcript-container.js +31 -0
  422. package/dist/modes/interactive/components/transcript-container.js.map +1 -0
  423. package/dist/modes/interactive/components/user-message.d.ts +6 -1
  424. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  425. package/dist/modes/interactive/components/user-message.js +20 -5
  426. package/dist/modes/interactive/components/user-message.js.map +1 -1
  427. package/dist/modes/interactive/components/visual-truncate.d.ts +20 -5
  428. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  429. package/dist/modes/interactive/components/visual-truncate.js +42 -3
  430. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  431. package/dist/modes/interactive/interactive-mode.d.ts +2 -0
  432. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  433. package/dist/modes/interactive/interactive-mode.js +125 -19
  434. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  435. package/dist/modes/interactive/theme/theme-schema.d.ts +28 -0
  436. package/dist/modes/interactive/theme/theme-schema.d.ts.map +1 -0
  437. package/dist/modes/interactive/theme/theme-schema.js +105 -0
  438. package/dist/modes/interactive/theme/theme-schema.js.map +1 -0
  439. package/dist/modes/interactive/theme/theme-tokens.d.ts +257 -0
  440. package/dist/modes/interactive/theme/theme-tokens.d.ts.map +1 -0
  441. package/dist/modes/interactive/theme/theme-tokens.js +94 -0
  442. package/dist/modes/interactive/theme/theme-tokens.js.map +1 -0
  443. package/dist/modes/interactive/theme/theme.d.ts +15 -16
  444. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  445. package/dist/modes/interactive/theme/theme.js +26 -29
  446. package/dist/modes/interactive/theme/theme.js.map +1 -1
  447. package/dist/modes/print-mode.d.ts.map +1 -1
  448. package/dist/modes/print-mode.js +4 -0
  449. package/dist/modes/print-mode.js.map +1 -1
  450. package/dist/utils/child-process.d.ts +0 -7
  451. package/dist/utils/child-process.d.ts.map +1 -1
  452. package/dist/utils/child-process.js +12 -3
  453. package/dist/utils/child-process.js.map +1 -1
  454. package/dist/utils/clipboard.d.ts.map +1 -1
  455. package/dist/utils/clipboard.js +6 -1
  456. package/dist/utils/clipboard.js.map +1 -1
  457. package/dist/utils/image-convert.d.ts +7 -0
  458. package/dist/utils/image-convert.d.ts.map +1 -1
  459. package/dist/utils/image-convert.js +35 -3
  460. package/dist/utils/image-convert.js.map +1 -1
  461. package/dist/utils/image-resize.d.ts.map +1 -1
  462. package/dist/utils/image-resize.js +2 -2
  463. package/dist/utils/image-resize.js.map +1 -1
  464. package/dist/utils/syntax-highlight.d.ts +7 -0
  465. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  466. package/dist/utils/syntax-highlight.js +54 -3
  467. package/dist/utils/syntax-highlight.js.map +1 -1
  468. package/dist/utils/windows-path.js +1 -1
  469. package/dist/utils/windows-path.js.map +1 -1
  470. package/dist/utils/zip.d.ts.map +1 -1
  471. package/dist/utils/zip.js +3 -1
  472. package/dist/utils/zip.js.map +1 -1
  473. package/docs/auto-session-namer.md +4 -0
  474. package/docs/cli-integration.md +1 -1
  475. package/docs/cli.md +1 -1
  476. package/docs/codemode.md +1 -1
  477. package/docs/compaction.md +9 -5
  478. package/docs/coordination.md +7 -0
  479. package/docs/environment-variables.md +1 -0
  480. package/docs/extensions.md +7 -4
  481. package/docs/keybindings.md +1 -0
  482. package/docs/mcp.md +1 -1
  483. package/docs/models.md +1 -0
  484. package/docs/providers.md +20 -0
  485. package/docs/session-format.md +16 -2
  486. package/docs/settings.md +16 -1
  487. package/docs/themes.md +4 -2
  488. package/docs/tui.md +1 -1
  489. package/docs/usage.md +6 -2
  490. package/examples/extensions/custom-provider-anthropic/package-lock.json +6 -6
  491. package/examples/extensions/custom-provider-anthropic/package.json +2 -2
  492. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  493. package/examples/extensions/dynamic-resources/dynamic.json +1 -1
  494. package/examples/extensions/gondolin/package-lock.json +20 -20
  495. package/examples/extensions/gondolin/package.json +1 -1
  496. package/examples/extensions/overlay-test.ts +2 -2
  497. package/examples/extensions/plan-mode/index.ts +6 -2
  498. package/examples/extensions/sandbox/package-lock.json +8 -8
  499. package/examples/extensions/sandbox/package.json +2 -2
  500. package/examples/extensions/with-deps/package-lock.json +2 -2
  501. package/examples/extensions/with-deps/package.json +1 -1
  502. package/examples/plugins/pi-example-plugin/package.json +2 -2
  503. package/examples/plugins/pi-example-plugin/src/contract.ts +1 -1
  504. package/examples/plugins/pi-example-plugin/src/session.ts +1 -1
  505. package/examples/plugins/pi-example-plugin/src/tui.ts +1 -1
  506. package/npm-shrinkwrap.json +174 -190
  507. package/package.json +24 -23
  508. package/schemas/keybindings.schema.json +397 -0
  509. package/schemas/models.schema.json +1157 -0
  510. package/schemas/settings.schema.json +875 -0
  511. package/schemas/theme.schema.json +365 -0
  512. package/src/coordination/UPSTREAM.md +36 -3
  513. package/src/coordination/upstream.json +3 -2
  514. package/src/humain/adhd/UPSTREAM.md +21 -3
  515. package/src/humain/adhd/upstream.json +1 -1
  516. package/src/humain/caveman/UPSTREAM.md +24 -3
  517. package/src/humain/ponytail/UPSTREAM.md +51 -4
  518. package/src/humain/ponytail/upstream.json +12 -12
  519. package/src/humain/ponytail/vendor/skills/ponytail/SKILL.md +1 -1
  520. package/src/humain/ponytail/vendor/skills/ponytail-audit/SKILL.md +1 -1
  521. package/src/humain/ponytail/vendor/skills/ponytail-debt/SKILL.md +13 -10
  522. package/src/humain/ponytail/vendor/skills/ponytail-help/SKILL.md +1 -1
  523. package/src/humain/ponytail/vendor/skills/ponytail-review/SKILL.md +1 -1
  524. package/src/humain/web-access/UPSTREAM.md +55 -1
  525. package/src/humain/web-access/upstream.json +4 -4
  526. package/dist/bundle/chunks/anthropic-messages-UNHXXOD4.js +0 -70
  527. package/dist/bundle/chunks/azure-openai-responses-4QRYJCC2.js +0 -14
  528. package/dist/bundle/chunks/chunk-GVVRXZHN.js +0 -17
  529. package/dist/bundle/chunks/chunk-QMUIATLD.js +0 -209
  530. package/dist/bundle/chunks/chunk-QSPDLT2R.js +0 -160
  531. package/dist/bundle/chunks/chunk-SZRZXVVZ.js +0 -125
  532. package/dist/bundle/chunks/chunk-XMHLSV3I.js +0 -48
  533. package/dist/bundle/chunks/chunk-YKZGL4MB.js +0 -86
  534. package/dist/bundle/chunks/dist-VNSMKBZ6.js +0 -7
  535. package/dist/bundle/chunks/es-N6YFJOD7.js +0 -1901
  536. package/dist/bundle/chunks/execute-4X6G65NZ.js +0 -536
  537. package/dist/bundle/chunks/host-4J7H7KDS.js +0 -2
  538. package/dist/bundle/chunks/runtime-SI76JZNE.js +0 -2
  539. package/dist/bundle/chunks/virtual-modules-GZY3Y4GX.js +0 -5
@@ -1,13 +1,13 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{retryProviderRequest}from"./chunk-Z33NNMNB.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-5XD3DHYL.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{clampThinkingLevel,collapseSystemMessages,withoutInitialSystemMessage}from"./chunk-DZ5C66IU.js";import{__commonJS,__require,__toESM}from"./chunk-JXWJOIH4.js";var require_retry_operation=__commonJS({"node_modules/p-retry/node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=
3
- null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this.
4
- _timeout),!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2.
5
- _operationTimeoutCb&&(self2._timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&
6
- (this._timeout=setTimeout(function(){self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this.
7
- _errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/p-retry/node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,
8
- minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:
9
- 1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.
10
- call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/p-retry/node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name=
2
+ import{retryProviderRequest}from"./chunk-Z33NNMNB.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-UDVC7A5S.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{clampThinkingLevel,collapseSystemMessages,withoutInitialSystemMessage}from"./chunk-LUL775V7.js";import{__commonJS,__require,__toESM}from"./chunk-JXWJOIH4.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=
3
+ null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;
4
+ var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2.
5
+ _timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){
6
+ self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.
7
+ attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,
8
+ randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.
9
+ max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.
10
+ pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name=
11
11
  "AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(
12
12
  attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.
13
13
  mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_extend=__commonJS({"node_modules/extend/index.js"(exports,module){"use strict";var hasOwn2=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function(arr){return typeof Array.isArray=="function"?Array.isArray(arr):toStr.call(arr)==="[object Array]"},isPlainObject2=function(obj){if(!obj||toStr.call(obj)!=="[object Object]")return!1;var hasOwnConstructor=hasOwn2.call(obj,"constructor"),hasIsPrototypeOf=obj.
@@ -538,42 +538,42 @@ type,listener);break}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,
538
538
  "Unexpected end of input");end===-1&&(end=i);let token=header.slice(start,end);return extensionName===void 0?push(offers,token,params):(paramName===void 0?push(params,token,!0):mustUnescape?push(params,paramName,token.replace(/\\/g,"")):push(params,paramName,token),push(offers,extensionName,params)),offers}function format(extensions){return Object.keys(extensions).map(extension2=>{let configurations=extensions[extension2];return Array.isArray(configurations)||(configurations=[configurations]),configurations.
539
539
  map(params=>[extension2].concat(Object.keys(params).map(k=>{let values=params[k];return Array.isArray(values)||(values=[values]),values.map(v=>v===!0?k:`${k}=${v}`).join("; ")})).join("; ")).join(", ")}).join(", ")}module.exports={format,parse}}});var require_websocket=__commonJS({"node_modules/ws/lib/websocket.js"(exports,module){"use strict";var EventEmitter=__require("events"),https=__require("https"),http=__require("http"),net=__require("net"),tls=__require("tls"),{randomBytes,createHash}=__require("crypto"),{Duplex,Readable:Readable2}=__require("stream"),{URL:URL2}=__require("url"),PerMessageDeflate2=require_permessage_deflate(),Receiver2=require_receiver(),Sender2=require_sender(),{isBlob}=require_validation(),{BINARY_TYPES,CLOSE_TIMEOUT,
540
540
  EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants(),{EventTarget:{addEventListener,removeEventListener}}=require_event_target(),{format,parse}=require_extension(),{toBuffer}=require_buffer_util(),kAborted=Symbol("kAborted"),protocolVersions=[8,13],readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"],subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,WebSocket2=class _WebSocket extends EventEmitter{constructor(address,protocols,options){super(),this._binaryType=
541
- BINARY_TYPES[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=EMPTY_BUFFER,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=_WebSocket.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,address!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,protocols===void 0?protocols=[]:Array.isArray(protocols)||(typeof protocols=="object"&&protocols!==null?(options=
542
- protocols,protocols=[]):protocols=[protocols]),initAsClient(this,address,protocols,options)):(this._autoPong=options.autoPong,this._closeTimeout=options.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(type){BINARY_TYPES.includes(type)&&(this._binaryType=type,this._receiver&&(this._receiver._binaryType=type))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.
543
- keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){let receiver=new Receiver2({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,
544
- maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation}),sender=new Sender2(socket,this._extensions,options.generateMask);this._receiver=receiver,this._sender=sender,this._socket=socket,receiver[kWebSocket]=this,sender[kWebSocket]=this,socket[kWebSocket]=this,receiver.on("conclude",receiverOnConclude),receiver.on("drain",receiverOnDrain),receiver.on("error",receiverOnError),receiver.on("message",receiverOnMessage),receiver.on("ping",receiverOnPing),
545
- receiver.on("pong",receiverOnPong),sender.onerror=senderOnError,socket.setTimeout&&socket.setTimeout(0),socket.setNoDelay&&socket.setNoDelay(),head.length>0&&socket.unshift(head),socket.on("close",socketOnClose),socket.on("data",socketOnData),socket.on("end",socketOnEnd),socket.on("error",socketOnError),this._readyState=_WebSocket.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=_WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[PerMessageDeflate2.
546
- extensionName]&&this._extensions[PerMessageDeflate2.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=_WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState!==_WebSocket.CLOSED){if(this.readyState===_WebSocket.CONNECTING){abortHandshake(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===_WebSocket.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver.
547
- _writableState.errorEmitted)&&this._socket.end();return}this._readyState=_WebSocket.CLOSING,this._sender.close(code,data,!this._isServer,err=>{err||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),setCloseTimer(this)}}pause(){this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED||(this._paused=!0,this._socket.pause())}ping(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocke\
548
- t is not open: readyState 0 (CONNECTING)");if(typeof data=="function"?(cb=data,data=mask=void 0):typeof mask=="function"&&(cb=mask,mask=void 0),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}mask===void 0&&(mask=!this._isServer),this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof data=="function"?
549
- (cb=data,data=mask=void 0):typeof mask=="function"&&(cb=mask,mask=void 0),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}mask===void 0&&(mask=!this._isServer),this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(data,options,cb){if(this.readyState===_WebSocket.CONNECTING)
550
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof options=="function"&&(cb=options,options={}),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}let opts={binary:typeof data!="string",mask:!this._isServer,compress:!0,fin:!0,...options};this._extensions[PerMessageDeflate2.extensionName]||(opts.compress=!1),this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState!==_WebSocket.CLOSED){
551
- if(this.readyState===_WebSocket.CONNECTING){abortHandshake(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=_WebSocket.CLOSING,this._socket.destroy())}}};Object.defineProperty(WebSocket2,"CONNECTING",{enumerable:!0,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket2.prototype,"CONNECTING",{enumerable:!0,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket2,"OPEN",{enumerable:!0,value:readyStates.
552
- indexOf("OPEN")});Object.defineProperty(WebSocket2.prototype,"OPEN",{enumerable:!0,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket2,"CLOSING",{enumerable:!0,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket2.prototype,"CLOSING",{enumerable:!0,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket2,"CLOSED",{enumerable:!0,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket2.prototype,"CLOSED",{enumerable:!0,value:readyStates.
553
- indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(property=>{Object.defineProperty(WebSocket2.prototype,property,{enumerable:!0})});["open","error","close","message"].forEach(method=>{Object.defineProperty(WebSocket2.prototype,`on${method}`,{enumerable:!0,get(){for(let listener of this.listeners(method))if(listener[kForOnEventAttribute])return listener[kListener];return null},set(handler){for(let listener of this.listeners(method))if(listener[kForOnEventAttribute]){
554
- this.removeListener(method,listener);break}typeof handler=="function"&&this.addEventListener(method,handler,{[kForOnEventAttribute]:!0})}})});WebSocket2.prototype.addEventListener=addEventListener;WebSocket2.prototype.removeEventListener=removeEventListener;module.exports=WebSocket2;function initAsClient(websocket,address,protocols,options){let opts={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,
555
- skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...options,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(websocket._autoPong=opts.autoPong,websocket._closeTimeout=opts.closeTimeout,!protocolVersions.includes(opts.protocolVersion))throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);let parsedUrl;if(address instanceof URL2)
556
- parsedUrl=address;else try{parsedUrl=new URL2(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}parsedUrl.protocol==="http:"?parsedUrl.protocol="ws:":parsedUrl.protocol==="https:"&&(parsedUrl.protocol="wss:"),websocket._url=parsedUrl.href;let isSecure=parsedUrl.protocol==="wss:",isIpcUrl=parsedUrl.protocol==="ws+unix:",invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl?invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+u\
557
- nix:"`:isIpcUrl&&!parsedUrl.pathname?invalidUrlMessage="The URL's pathname is empty":parsedUrl.hash&&(invalidUrlMessage="The URL contains a fragment identifier"),invalidUrlMessage){let err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0)throw err;emitErrorAndClose(websocket,err);return}let defaultPort=isSecure?443:80,key=randomBytes(16).toString("base64"),request=isSecure?https.request:http.request,protocolSet=new Set,perMessageDeflate;if(opts.createConnection=opts.createConnection||
558
- (isSecure?tlsConnect:netConnect),opts.defaultPort=opts.defaultPort||defaultPort,opts.port=parsedUrl.port||defaultPort,opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname,opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"},opts.path=parsedUrl.pathname+parsedUrl.search,opts.timeout=opts.handshakeTimeout,opts.perMessageDeflate&&(perMessageDeflate=new PerMessageDeflate2(
559
- {...opts.perMessageDeflate,isServer:!1,maxPayload:opts.maxPayload}),opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate2.extensionName]:perMessageDeflate.offer()})),protocols.length){for(let protocol of protocols){if(typeof protocol!="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol))throw new SyntaxError("An invalid or duplicated subprotocol was specified");protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin&&(opts.
560
- protocolVersion<13?opts.headers["Sec-WebSocket-Origin"]=opts.origin:opts.headers.Origin=opts.origin),(parsedUrl.username||parsedUrl.password)&&(opts.auth=`${parsedUrl.username}:${parsedUrl.password}`),isIpcUrl){let parts=opts.path.split(":");opts.socketPath=parts[0],opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl,websocket._originalSecure=isSecure,websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;let headers=options&&
561
- options.headers;if(options={...options,headers:{}},headers)for(let[key2,value]of Object.entries(headers))options.headers[key2.toLowerCase()]=value}else if(websocket.listenerCount("redirect")===0){let isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:!1:websocket._originalIpc?!1:parsedUrl.host===websocket._originalHostOrSocketPath;(!isSameHost||websocket._originalSecure&&!isSecure)&&(delete opts.headers.authorization,delete opts.headers.cookie,isSameHost||
562
- delete opts.headers.host,opts.auth=void 0)}opts.auth&&!options.headers.authorization&&(options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")),req=websocket._req=request(opts),websocket._redirects&&websocket.emit("redirect",websocket.url,req)}else req=websocket._req=request(opts);opts.timeout&&req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")}),req.on("error",err=>{req===null||req[kAborted]||(req=websocket._req=null,emitErrorAndClose(
563
- websocket,err))}),req.on("response",res=>{let location=res.headers.location,statusCode=res.statusCode;if(location&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location,address)}catch{let err=new SyntaxError(`Invalid URL: ${location}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else websocket.emit(
564
- "unexpected-response",req,res)||abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}),req.on("upgrade",(res,socket,head)=>{if(websocket.emit("upgrade",res),websocket.readyState!==WebSocket2.CONNECTING)return;req=websocket._req=null;let upgrade=res.headers.upgrade;if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}let digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-web\
565
- socket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}let serverProt=res.headers["sec-websocket-protocol"],protError;if(serverProt!==void 0?protocolSet.size?protocolSet.has(serverProt)||(protError="Server sent an invalid subprotocol"):protError="Server sent a subprotocol but none was requested":protocolSet.size&&(protError="Server sent no subprotocol"),protError){abortHandshake(websocket,socket,protError);return}serverProt&&(websocket._protocol=serverProt);
566
- let secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){abortHandshake(websocket,socket,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch{abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}let extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate2.
567
- extensionName){abortHandshake(websocket,socket,"Server indicated an extension that was not requested");return}try{perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName])}catch{abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}websocket._extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,
568
- maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})}),opts.finishRequest?opts.finishRequest(req,websocket):req.end()}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket2.CLOSING,websocket._errorEmitted=!0,websocket.emit("error",err),websocket.emitClose()}function netConnect(options){return options.path=options.socketPath,net.connect(options)}function tlsConnect(options){return options.path=void 0,!options.servername&&options.
569
- servername!==""&&(options.servername=net.isIP(options.host)?"":options.host),tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket2.CLOSING;let err=new Error(message);Error.captureStackTrace(err,abortHandshake),stream.setHeader?(stream[kAborted]=!0,stream.abort(),stream.socket&&!stream.socket.destroyed&&stream.socket.destroy(),process.nextTick(emitErrorAndClose,websocket,err)):(stream.destroy(err),stream.once("error",websocket.emit.bind(websocket,
570
- "error")),stream.once("close",websocket.emitClose.bind(websocket)))}function sendAfterClose(websocket,data,cb){if(data){let length=isBlob(data)?data.size:toBuffer(data).length;websocket._socket?websocket._sender._bufferedBytes+=length:websocket._bufferedAmount+=length}if(cb){let err=new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){let websocket=this[kWebSocket];websocket.
571
- _closeFrameReceived=!0,websocket._closeMessage=reason,websocket._closeCode=code,websocket._socket[kWebSocket]!==void 0&&(websocket._socket.removeListener("data",socketOnData),process.nextTick(resume,websocket._socket),code===1005?websocket.close():websocket.close(code,reason))}function receiverOnDrain(){let websocket=this[kWebSocket];websocket.isPaused||websocket._socket.resume()}function receiverOnError(err){let websocket=this[kWebSocket];websocket._socket[kWebSocket]!==void 0&&(websocket._socket.
572
- removeListener("data",socketOnData),process.nextTick(resume,websocket._socket),websocket.close(err[kStatusCode])),websocket._errorEmitted||(websocket._errorEmitted=!0,websocket.emit("error",err))}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){let websocket=this[kWebSocket];websocket._autoPong&&websocket.pong(data,!this._isServer,NOOP),websocket.emit("ping",data)}function receiverOnPong(data){
573
- this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function senderOnError(err){let websocket=this[kWebSocket];websocket.readyState!==WebSocket2.CLOSED&&(websocket.readyState===WebSocket2.OPEN&&(websocket._readyState=WebSocket2.CLOSING,setCloseTimer(websocket)),this._socket.end(),websocket._errorEmitted||(websocket._errorEmitted=!0,websocket.emit("error",err)))}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),
574
- websocket._closeTimeout)}function socketOnClose(){let websocket=this[kWebSocket];if(this.removeListener("close",socketOnClose),this.removeListener("data",socketOnData),this.removeListener("end",socketOnEnd),websocket._readyState=WebSocket2.CLOSING,!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){let chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end(),
575
- this[kWebSocket]=void 0,clearTimeout(websocket._closeTimer),websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted?websocket.emitClose():(websocket._receiver.on("error",receiverOnFinish),websocket._receiver.on("finish",receiverOnFinish))}function socketOnData(chunk){this[kWebSocket]._receiver.write(chunk)||this.pause()}function socketOnEnd(){let websocket=this[kWebSocket];websocket._readyState=WebSocket2.CLOSING,websocket._receiver.end(),this.end()}function socketOnError(){
576
- let websocket=this[kWebSocket];this.removeListener("error",socketOnError),this.on("error",NOOP),websocket&&(websocket._readyState=WebSocket2.CLOSING,this.destroy())}}});var require_stream=__commonJS({"node_modules/ws/lib/stream.js"(exports,module){"use strict";var WebSocket2=require_websocket(),{Duplex}=__require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){!this.destroyed&&this._writableState.finished&&this.destroy()}function duplexOnError(err){this.removeListener("error",duplexOnError),this.destroy(),this.listenerCount("error")===0&&this.emit("error",err)}function createWebSocketStream2(ws,options){let terminateOnDestroy=!0,
541
+ BINARY_TYPES[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=EMPTY_BUFFER,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=_WebSocket.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,address!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,protocols===void 0?!options||options.protocols===void 0?protocols=[]:Array.isArray(options.protocols)?protocols=
542
+ options.protocols:protocols=[options.protocols]:Array.isArray(protocols)||(typeof protocols=="object"&&protocols!==null?(options=protocols,options.protocols===void 0?protocols=[]:Array.isArray(options.protocols)?protocols=options.protocols:protocols=[options.protocols]):protocols=[protocols]),initAsClient(this,address,protocols,options)):(this._autoPong=options.autoPong,this._closeTimeout=options.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(type){BINARY_TYPES.
543
+ includes(type)&&(this._binaryType=type,this._receiver&&(this._receiver._binaryType=type))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){
544
+ return this._url}setSocket(socket,head,options){let receiver=new Receiver2({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation}),sender=new Sender2(socket,this._extensions,options.generateMask);this._receiver=receiver,this._sender=sender,this._socket=socket,receiver[kWebSocket]=
545
+ this,sender[kWebSocket]=this,socket[kWebSocket]=this,receiver.on("conclude",receiverOnConclude),receiver.on("drain",receiverOnDrain),receiver.on("error",receiverOnError),receiver.on("message",receiverOnMessage),receiver.on("ping",receiverOnPing),receiver.on("pong",receiverOnPong),sender.onerror=senderOnError,socket.setTimeout&&socket.setTimeout(0),socket.setNoDelay&&socket.setNoDelay(),head.length>0&&socket.unshift(head),socket.on("close",socketOnClose),socket.on("data",socketOnData),socket.on("\
546
+ end",socketOnEnd),socket.on("error",socketOnError),this._readyState=_WebSocket.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=_WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[PerMessageDeflate2.extensionName]&&this._extensions[PerMessageDeflate2.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=_WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState!==
547
+ _WebSocket.CLOSED){if(this.readyState===_WebSocket.CONNECTING){abortHandshake(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===_WebSocket.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._sender.close(code,data,!this._isServer,err=>{err||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),this.
548
+ _readyState=_WebSocket.CLOSING,setCloseTimer(this)}}pause(){this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED||(this._paused=!0,this._socket.pause())}ping(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof data=="function"?(cb=data,data=mask=void 0):typeof mask=="function"&&(cb=mask,mask=void 0),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(
549
+ this,data,cb);return}mask===void 0&&(mask=!this._isServer),this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof data=="function"?(cb=data,data=mask=void 0):typeof mask=="function"&&(cb=mask,mask=void 0),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}mask===void 0&&(mask=!this._isServer),this._sender.
550
+ pong(data||EMPTY_BUFFER,mask,cb)}resume(){this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(data,options,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof options=="function"&&(cb=options,options={}),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}
551
+ let opts={binary:typeof data!="string",mask:!this._isServer,compress:!0,fin:!0,...options};this._extensions[PerMessageDeflate2.extensionName]||(opts.compress=!1),this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState!==_WebSocket.CLOSED){if(this.readyState===_WebSocket.CONNECTING){abortHandshake(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=_WebSocket.CLOSING,this._socket.destroy())}}};Object.defineProperty(
552
+ WebSocket2,"CONNECTING",{enumerable:!0,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket2.prototype,"CONNECTING",{enumerable:!0,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket2,"OPEN",{enumerable:!0,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket2.prototype,"OPEN",{enumerable:!0,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket2,"CLOSING",{enumerable:!0,value:readyStates.indexOf("CLOSING")});Object.defineProperty(
553
+ WebSocket2.prototype,"CLOSING",{enumerable:!0,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket2,"CLOSED",{enumerable:!0,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket2.prototype,"CLOSED",{enumerable:!0,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(property=>{Object.defineProperty(WebSocket2.prototype,property,{enumerable:!0})});["open","error","close","message"].forEach(
554
+ method=>{Object.defineProperty(WebSocket2.prototype,`on${method}`,{enumerable:!0,get(){for(let listener of this.listeners(method))if(listener[kForOnEventAttribute])return listener[kListener];return null},set(handler){for(let listener of this.listeners(method))if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}typeof handler=="function"&&this.addEventListener(method,handler,{[kForOnEventAttribute]:!0})}})});WebSocket2.prototype.addEventListener=addEventListener;WebSocket2.
555
+ prototype.removeEventListener=removeEventListener;module.exports=WebSocket2;function initAsClient(websocket,address,protocols,options){let opts={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...options,socketPath:void 0,hostname:void 0,protocol:void 0,protocols:void 0,timeout:void 0,method:"GET",host:void 0,
556
+ path:void 0,port:void 0};if(websocket._autoPong=opts.autoPong,websocket._closeTimeout=opts.closeTimeout,!protocolVersions.includes(opts.protocolVersion))throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);let parsedUrl;if(address instanceof URL2)parsedUrl=address;else try{parsedUrl=new URL2(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}parsedUrl.protocol==="http:"?parsedUrl.protocol="ws:":parsedUrl.protocol===
557
+ "https:"&&(parsedUrl.protocol="wss:"),websocket._url=parsedUrl.href;let isSecure=parsedUrl.protocol==="wss:",isIpcUrl=parsedUrl.protocol==="ws+unix:",invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl?invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:isIpcUrl&&!parsedUrl.pathname?invalidUrlMessage="The URL's pathname is empty":parsedUrl.hash&&(invalidUrlMessage="The URL contains a fragment identifier"),invalidUrlMessage){let err=new SyntaxError(
558
+ invalidUrlMessage);if(websocket._redirects===0)throw err;emitErrorAndClose(websocket,err);return}let defaultPort=isSecure?443:80,key=randomBytes(16).toString("base64"),request=isSecure?https.request:http.request,protocolSet=new Set,perMessageDeflate;if(opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect),opts.defaultPort=opts.defaultPort||defaultPort,opts.port=parsedUrl.port||defaultPort,opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.
559
+ hostname,opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"},opts.path=parsedUrl.pathname+parsedUrl.search,opts.timeout=opts.handshakeTimeout,opts.perMessageDeflate&&(perMessageDeflate=new PerMessageDeflate2({...opts.perMessageDeflate,isServer:!1,maxPayload:opts.maxPayload}),opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate2.extensionName]:perMessageDeflate.offer()})),protocols.length){for(let protocol of protocols){
560
+ if(typeof protocol!="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol))throw new SyntaxError("An invalid or duplicated subprotocol was specified");protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin&&(opts.protocolVersion<13?opts.headers["Sec-WebSocket-Origin"]=opts.origin:opts.headers.Origin=opts.origin),(parsedUrl.username||parsedUrl.password)&&(opts.auth=`${parsedUrl.username}:${parsedUrl.password}`),isIpcUrl){let parts=opts.path.
561
+ split(":");opts.socketPath=parts[0],opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl,websocket._originalSecure=isSecure,websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;let headers=options&&options.headers;if(options={...options,headers:{}},headers)for(let[key2,value]of Object.entries(headers))options.headers[key2.toLowerCase()]=value}else if(websocket.listenerCount("redirect")===0){let isSameHost=isIpcUrl?
562
+ websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:!1:websocket._originalIpc?!1:parsedUrl.host===websocket._originalHostOrSocketPath;(!isSameHost||websocket._originalSecure&&!isSecure)&&(delete opts.headers.authorization,delete opts.headers.cookie,isSameHost||delete opts.headers.host,opts.auth=void 0)}opts.auth&&!options.headers.authorization&&(options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")),req=websocket._req=request(opts),websocket._redirects&&
563
+ websocket.emit("redirect",websocket.url,req)}else req=websocket._req=request(opts);opts.timeout&&req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")}),req.on("error",err=>{req===null||req[kAborted]||(req=websocket._req=null,emitErrorAndClose(websocket,err))}),req.on("response",res=>{let location=res.headers.location,statusCode=res.statusCode;if(location&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(
564
+ websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location,address)}catch{let err=new SyntaxError(`Invalid URL: ${location}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else websocket.emit("unexpected-response",req,res)||abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}),req.on("upgrade",(res,socket,head)=>{if(websocket.emit("upgrade",res),websocket.readyState!==WebSocket2.CONNECTING)
565
+ return;req=websocket._req=null;let upgrade=res.headers.upgrade;if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}let digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}let serverProt=res.headers["sec-websocket-protocol"],protError;if(serverProt!==void 0?protocolSet.size?protocolSet.has(serverProt)||
566
+ (protError="Server sent an invalid subprotocol"):protError="Server sent a subprotocol but none was requested":protocolSet.size&&(protError="Server sent no subprotocol"),protError){abortHandshake(websocket,socket,protError);return}serverProt&&(websocket._protocol=serverProt);let secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){abortHandshake(websocket,socket,"Server sent a Sec-WebSocket-Extensions header but no extension was\
567
+ requested");return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch{abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}let extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate2.extensionName){abortHandshake(websocket,socket,"Server indicated an extension that was not requested");return}try{perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName])}catch{abortHandshake(websocket,socket,
568
+ "Invalid Sec-WebSocket-Extensions header");return}websocket._extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})}),opts.finishRequest?opts.finishRequest(req,websocket):req.end()}function emitErrorAndClose(websocket,err){websocket.
569
+ _readyState=WebSocket2.CLOSING,websocket._errorEmitted=!0,websocket.emit("error",err),websocket.emitClose()}function netConnect(options){return options.path=options.socketPath,net.connect(options)}function tlsConnect(options){return options.path=void 0,!options.servername&&options.servername!==""&&(options.servername=net.isIP(options.host)?"":options.host),tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket2.CLOSING;let err=new Error(message);Error.
570
+ captureStackTrace(err,abortHandshake),stream.setHeader?(stream[kAborted]=!0,stream.abort(),stream.socket&&!stream.socket.destroyed&&stream.socket.destroy(),process.nextTick(emitErrorAndClose,websocket,err)):(stream.destroy(err),stream.once("error",websocket.emit.bind(websocket,"error")),stream.once("close",websocket.emitClose.bind(websocket)))}function sendAfterClose(websocket,data,cb){if(data){let length=isBlob(data)?data.size:toBuffer(data).length;websocket._socket?websocket._sender._bufferedBytes+=
571
+ length:websocket._bufferedAmount+=length}if(cb){let err=new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){let websocket=this[kWebSocket];websocket._closeFrameReceived=!0,websocket._closeMessage=reason,websocket._closeCode=code,websocket._socket[kWebSocket]!==void 0&&(websocket._socket.removeListener("data",socketOnData),process.nextTick(resume,websocket._socket),code===1005?
572
+ websocket.close():websocket.close(code,reason))}function receiverOnDrain(){let websocket=this[kWebSocket];websocket.isPaused||websocket._socket.resume()}function receiverOnError(err){let websocket=this[kWebSocket];websocket._socket[kWebSocket]!==void 0&&(websocket._socket.removeListener("data",socketOnData),process.nextTick(resume,websocket._socket),websocket.close(err[kStatusCode])),websocket._errorEmitted||(websocket._errorEmitted=!0,websocket.emit("error",err))}function receiverOnFinish(){this[kWebSocket].
573
+ emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){let websocket=this[kWebSocket];websocket._autoPong&&websocket.pong(data,!this._isServer,NOOP),websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function senderOnError(err){let websocket=this[kWebSocket];websocket.readyState!==WebSocket2.CLOSED&&(websocket.readyState===WebSocket2.OPEN&&
574
+ (websocket._readyState=WebSocket2.CLOSING,setCloseTimer(websocket)),this._socket.end(),websocket._errorEmitted||(websocket._errorEmitted=!0,websocket.emit("error",err)))}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){let websocket=this[kWebSocket];if(this.removeListener("close",socketOnClose),this.removeListener("data",socketOnData),this.removeListener("end",socketOnEnd),websocket.
575
+ _readyState=WebSocket2.CLOSING,!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){let chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end(),this[kWebSocket]=void 0,clearTimeout(websocket._closeTimer),websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted?websocket.emitClose():(websocket._receiver.on("error",receiverOnFinish),
576
+ websocket._receiver.on("finish",receiverOnFinish))}function socketOnData(chunk){this[kWebSocket]._receiver.write(chunk)||this.pause()}function socketOnEnd(){let websocket=this[kWebSocket];websocket._readyState=WebSocket2.CLOSING,websocket._receiver.end(),this.end()}function socketOnError(){let websocket=this[kWebSocket];this.removeListener("error",socketOnError),this.on("error",NOOP),websocket&&(websocket._readyState=WebSocket2.CLOSING,this.destroy())}}});var require_stream=__commonJS({"node_modules/ws/lib/stream.js"(exports,module){"use strict";var WebSocket2=require_websocket(),{Duplex}=__require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){!this.destroyed&&this._writableState.finished&&this.destroy()}function duplexOnError(err){this.removeListener("error",duplexOnError),this.destroy(),this.listenerCount("error")===0&&this.emit("error",err)}function createWebSocketStream2(ws,options){let terminateOnDestroy=!0,
577
577
  duplex=new Duplex({...options,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return ws.on("message",function(msg,isBinary){let data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;duplex.push(data)||ws.pause()}),ws.once("error",function(err){duplex.destroyed||(terminateOnDestroy=!1,duplex.destroy(err))}),ws.once("close",function(){duplex.destroyed||duplex.push(null)}),duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err),process.nextTick(
578
578
  emitClose,duplex);return}let called=!1;ws.once("error",function(err2){called=!0,callback(err2)}),ws.once("close",function(){called||callback(err),process.nextTick(emitClose,duplex)}),terminateOnDestroy&&ws.terminate()},duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function(){duplex._final(callback)});return}ws._socket!==null&&(ws._socket._writableState.finished?(callback(),duplex._readableState.endEmitted&&duplex.destroy()):(ws._socket.once("finish",function(){
579
579
  callback()}),ws.close()))},duplex._read=function(){ws.isPaused&&ws.resume()},duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)},duplex.on("end",duplexOnEnd),duplex.on("error",duplexOnError),duplex}module.exports=createWebSocketStream2}});var require_subprotocol=__commonJS({"node_modules/ws/lib/subprotocol.js"(exports,module){"use strict";var{tokenChars}=require_validation();function parse(header){let protocols=new Set,start=-1,end=-1,i=0;for(i;i<header.length;i++){let code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1)start===-1&&(start=i);else if(i!==0&&(code===32||code===9))end===-1&&start!==-1&&(end=i);else if(code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i}`);end===-1&&(end=i);let protocol2=header.
@@ -624,9 +624,9 @@ tesBase64Encoded"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"]
624
624
  Outcome2.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",Outcome2.OUTCOME_OK="OUTCOME_OK",Outcome2.OUTCOME_FAILED="OUTCOME_FAILED",Outcome2.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(Outcome||(Outcome={}));var Language;(function(Language2){Language2.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",Language2.PYTHON="PYTHON"})(Language||(Language={}));var FunctionResponseScheduling;(function(FunctionResponseScheduling2){FunctionResponseScheduling2.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",
625
625
  FunctionResponseScheduling2.SILENT="SILENT",FunctionResponseScheduling2.WHEN_IDLE="WHEN_IDLE",FunctionResponseScheduling2.INTERRUPT="INTERRUPT"})(FunctionResponseScheduling||(FunctionResponseScheduling={}));var Type;(function(Type2){Type2.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",Type2.STRING="STRING",Type2.NUMBER="NUMBER",Type2.INTEGER="INTEGER",Type2.BOOLEAN="BOOLEAN",Type2.ARRAY="ARRAY",Type2.OBJECT="OBJECT",Type2.NULL="NULL"})(Type||(Type={}));var AuthType;(function(AuthType2){AuthType2.AUTH_TYPE_UNSPECIFIED=
626
626
  "AUTH_TYPE_UNSPECIFIED",AuthType2.NO_AUTH="NO_AUTH",AuthType2.API_KEY_AUTH="API_KEY_AUTH",AuthType2.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",AuthType2.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",AuthType2.OAUTH="OAUTH",AuthType2.OIDC_AUTH="OIDC_AUTH"})(AuthType||(AuthType={}));var HttpElementLocation;(function(HttpElementLocation2){HttpElementLocation2.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",HttpElementLocation2.HTTP_IN_QUERY="HTTP_IN_QUERY",HttpElementLocation2.HTTP_IN_HEADER="HTTP_IN_\
627
- HEADER",HttpElementLocation2.HTTP_IN_PATH="HTTP_IN_PATH",HttpElementLocation2.HTTP_IN_BODY="HTTP_IN_BODY",HttpElementLocation2.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(HttpElementLocation||(HttpElementLocation={}));var ApiSpec;(function(ApiSpec2){ApiSpec2.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",ApiSpec2.SIMPLE_SEARCH="SIMPLE_SEARCH",ApiSpec2.ELASTIC_SEARCH="ELASTIC_SEARCH"})(ApiSpec||(ApiSpec={}));var Environment;(function(Environment2){Environment2.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",
628
- Environment2.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",Environment2.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",Environment2.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(Environment||(Environment={}));var SafetyPolicy;(function(SafetyPolicy2){SafetyPolicy2.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",SafetyPolicy2.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",SafetyPolicy2.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",SafetyPolicy2.COMMUNICATION_TOOL="COMMUNICATION_TOOL",SafetyPolicy2.
629
- ACCOUNT_CREATION="ACCOUNT_CREATION",SafetyPolicy2.DATA_MODIFICATION="DATA_MODIFICATION",SafetyPolicy2.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",SafetyPolicy2.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"})(SafetyPolicy||(SafetyPolicy={}));var PhishBlockThreshold;(function(PhishBlockThreshold2){PhishBlockThreshold2.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",PhishBlockThreshold2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",PhishBlockThreshold2.BLOCK_MEDIUM_AND_ABOVE=
627
+ HEADER",HttpElementLocation2.HTTP_IN_PATH="HTTP_IN_PATH",HttpElementLocation2.HTTP_IN_BODY="HTTP_IN_BODY",HttpElementLocation2.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(HttpElementLocation||(HttpElementLocation={}));var ApiSpec;(function(ApiSpec2){ApiSpec2.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",ApiSpec2.SIMPLE_SEARCH="SIMPLE_SEARCH",ApiSpec2.ELASTIC_SEARCH="ELASTIC_SEARCH"})(ApiSpec||(ApiSpec={}));var SafetyPolicy;(function(SafetyPolicy2){SafetyPolicy2.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPE\
628
+ CIFIED",SafetyPolicy2.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",SafetyPolicy2.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",SafetyPolicy2.COMMUNICATION_TOOL="COMMUNICATION_TOOL",SafetyPolicy2.ACCOUNT_CREATION="ACCOUNT_CREATION",SafetyPolicy2.DATA_MODIFICATION="DATA_MODIFICATION",SafetyPolicy2.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",SafetyPolicy2.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"})(SafetyPolicy||(SafetyPolicy={}));var Environment;(function(Environment2){
629
+ Environment2.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",Environment2.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",Environment2.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",Environment2.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(Environment||(Environment={}));var PhishBlockThreshold;(function(PhishBlockThreshold2){PhishBlockThreshold2.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",PhishBlockThreshold2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",PhishBlockThreshold2.BLOCK_MEDIUM_AND_ABOVE=
630
630
  "BLOCK_MEDIUM_AND_ABOVE",PhishBlockThreshold2.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",PhishBlockThreshold2.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",PhishBlockThreshold2.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",PhishBlockThreshold2.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(PhishBlockThreshold||(PhishBlockThreshold={}));var Behavior;(function(Behavior2){Behavior2.UNSPECIFIED="UNSPECIFIED",Behavior2.BLOCKING="BLOCKING",Behavior2.NON_BLOCKING="NON_BLOCKING"})(Behavior||
631
631
  (Behavior={}));var DynamicRetrievalConfigMode;(function(DynamicRetrievalConfigMode2){DynamicRetrievalConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",DynamicRetrievalConfigMode2.MODE_DYNAMIC="MODE_DYNAMIC"})(DynamicRetrievalConfigMode||(DynamicRetrievalConfigMode={}));var ThinkingLevel;(function(ThinkingLevel2){ThinkingLevel2.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",ThinkingLevel2.MINIMAL="MINIMAL",ThinkingLevel2.LOW="LOW",ThinkingLevel2.MEDIUM="MEDIUM",ThinkingLevel2.HIGH="HIGH"})(
632
632
  ThinkingLevel||(ThinkingLevel={}));var PersonGeneration;(function(PersonGeneration2){PersonGeneration2.DONT_ALLOW="DONT_ALLOW",PersonGeneration2.ALLOW_ADULT="ALLOW_ADULT",PersonGeneration2.ALLOW_ALL="ALLOW_ALL"})(PersonGeneration||(PersonGeneration={}));var ProminentPeople;(function(ProminentPeople2){ProminentPeople2.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",ProminentPeople2.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",ProminentPeople2.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT\
@@ -678,16 +678,17 @@ END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(EndSensitivity||(EndSensitivity={}))
678
678
  TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",TurnCoverage2.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",TurnCoverage2.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(TurnCoverage||(TurnCoverage={}));var Scale;(function(Scale2){Scale2.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",Scale2.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",Scale2.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",Scale2.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",Scale2.E_FLAT_MAJOR_C_MINOR=
679
679
  "E_FLAT_MAJOR_C_MINOR",Scale2.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",Scale2.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",Scale2.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",Scale2.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",Scale2.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",Scale2.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",Scale2.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",Scale2.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(Scale||(Scale={}));var MusicGenerationMode;(function(MusicGenerationMode2){MusicGenerationMode2.
680
680
  MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",MusicGenerationMode2.QUALITY="QUALITY",MusicGenerationMode2.DIVERSITY="DIVERSITY",MusicGenerationMode2.VOCALIZATION="VOCALIZATION"})(MusicGenerationMode||(MusicGenerationMode={}));var LiveMusicPlaybackControl;(function(LiveMusicPlaybackControl2){LiveMusicPlaybackControl2.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",LiveMusicPlaybackControl2.PLAY="PLAY",LiveMusicPlaybackControl2.PAUSE="PAUSE",LiveMusicPlaybackControl2.
681
- STOP="STOP",LiveMusicPlaybackControl2.RESET_CONTEXT="RESET_CONTEXT"})(LiveMusicPlaybackControl||(LiveMusicPlaybackControl={}));var HttpResponse=class{constructor(response){let headers={};for(let pair of response.headers.entries())headers[pair[0]]=pair[1];this.headers=headers,this.responseInternal=response}json(){return this.responseInternal.json()}};var GenerateContentResponse=class{get text(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let text="",anyTextPartText=!1,nonTextParts=[];for(let part of(_h=(_g=(_f=(_e=this.candidates)===
682
- null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)!==null&&_h!==void 0?_h:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="text"&&fieldName!=="thought"&&fieldName!=="thoughtSignature"&&(fieldValue!==null||fieldValue!==void 0)&&nonTextParts.push(fieldName);if(typeof part.text=="string"){if(typeof part.thought=="boolean"&&part.thought)continue;anyTextPartText=!0,text+=part.text}}return nonTextParts.length>0&&console.warn(
683
- `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),anyTextPartText?text:void 0}get data(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there\
684
- are multiple candidates in the response, returning data from the first one.");let data="",nonDataParts=[];for(let part of(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)!==null&&_h!==void 0?_h:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="inlineData"&&(fieldValue!==null||fieldValue!==void 0)&&nonDataParts.push(fieldName);part.inlineData&&typeof part.inlineData.data=="string"&&(data+=
685
- atob(part.inlineData.data))}return nonDataParts.length>0&&console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),data.length>0?btoa(data):void 0}get functionCalls(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:
686
- _d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let functionCalls=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.functionCall).map(part=>part.functionCall).filter(functionCall=>functionCall!==void 0);if(functionCalls?.length!==0)return functionCalls}get executableCode(){
687
- var _a2,_b,_c,_d,_e,_f,_g,_h,_j;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");let executableCode=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===
688
- null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.executableCode).map(part=>part.executableCode).filter(executableCode2=>executableCode2!==void 0);if(executableCode?.length!==0)return(_j=executableCode?.[0])===null||_j===void 0?void 0:_j.code}get codeExecutionResult(){var _a2,_b,_c,_d,_e,_f,_g,_h,_j;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?
689
- void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let codeExecutionResult=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.codeExecutionResult).map(part=>part.codeExecutionResult).filter(codeExecutionResult2=>codeExecutionResult2!==
690
- void 0);if(codeExecutionResult?.length!==0)return(_j=codeExecutionResult?.[0])===null||_j===void 0?void 0:_j.output}},EmbedContentResponse=class{},GenerateImagesResponse=class{},EditImageResponse=class{},UpscaleImageResponse=class{},RecontextImageResponse=class{},SegmentImageResponse=class{},ListModelsResponse=class{},DeleteModelResponse=class{};var CountTokensResponse=class{},ComputeTokensResponse=class{};var GenerateVideosOperation=class _GenerateVideosOperation{_fromAPIResponse({apiResponse,_isVertexAI}){let operation=new _GenerateVideosOperation,response,op=apiResponse;return _isVertexAI?response=generateVideosOperationFromVertex$1(op):response=generateVideosOperationFromMldev$1(op),Object.assign(operation,response),operation}};var ListTuningJobsResponse=class{},CancelTuningJobResponse=class{},ValidateRewardResponse=class{},DeleteCachedContentResponse=class{},ListCachedContentsResponse=class{},ListDocumentsResponse=class{},ListFileSearchStoresResponse=class{},UploadToFileSearchStoreResumableResponse=class{};var ImportFileOperation=class _ImportFileOperation{_fromAPIResponse({apiResponse,_isVertexAI}){let operation=new _ImportFileOperation,response=importFileOperationFromMldev$1(apiResponse);return Object.assign(operation,response),operation}},ListFilesResponse=class{},CreateFileResponse=class{},DeleteFileResponse=class{},RegisterFilesResponse=class{};var ListBatchJobsResponse=class{};var LiveServerMessage=class{get text(){var _a2,_b,_c;let text="",anyTextPartFound=!1,nonTextParts=[];for(let part of(_c=(_b=(_a2=this.serverContent)===null||_a2===void 0?void 0:_a2.modelTurn)===null||_b===void 0?void 0:_b.parts)!==null&&_c!==void 0?_c:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="text"&&fieldName!=="thought"&&fieldValue!==null&&nonTextParts.push(fieldName);if(typeof part.text=="string"){if(typeof part.thought=="boolean"&&part.thought)continue;anyTextPartFound=
681
+ STOP="STOP",LiveMusicPlaybackControl2.RESET_CONTEXT="RESET_CONTEXT"})(LiveMusicPlaybackControl||(LiveMusicPlaybackControl={}));var HttpResponse=class{constructor(response){let headers={};for(let pair of response.headers.entries())headers[pair[0]]=pair[1];this.headers=headers,this.responseInternal=response}json(){return this.responseInternal.json()}},GenerateContentResponsePromptFeedback=class{},GenerateContentResponseUsageMetadata=class{},GenerateContentResponse=class{get text(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===
682
+ null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let text="",anyTextPartText=!1,nonTextParts=[];for(let part of(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)!==null&&_h!==void 0?_h:[]){for(let[fieldName,fieldValue]of Object.entries(
683
+ part))fieldName!=="text"&&fieldName!=="thought"&&fieldName!=="thoughtSignature"&&(fieldValue!==null||fieldValue!==void 0)&&nonTextParts.push(fieldName);if(typeof part.text=="string"){if(typeof part.thought=="boolean"&&part.thought)continue;anyTextPartText=!0,text+=part.text}}return nonTextParts.length>0&&console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),anyTextPartText?
684
+ text:void 0}get data(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let data="",nonDataParts=[];for(let part of(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===
685
+ null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)!==null&&_h!==void 0?_h:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="inlineData"&&(fieldValue!==null||fieldValue!==void 0)&&nonDataParts.push(fieldName);part.inlineData&&typeof part.inlineData.data=="string"&&(data+=atob(part.inlineData.data))}return nonDataParts.length>0&&console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer \
686
+ to the non data parts for a full response from model.`),data.length>0?btoa(data):void 0}get functionCalls(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let functionCalls=(_h=
687
+ (_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.functionCall).map(part=>part.functionCall).filter(functionCall=>functionCall!==void 0);if(functionCalls?.length!==0)return functionCalls}get executableCode(){var _a2,_b,_c,_d,_e,_f,_g,_h,_j;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===
688
+ void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");let executableCode=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.executableCode).map(part=>part.executableCode).filter(executableCode2=>executableCode2!==
689
+ void 0);if(executableCode?.length!==0)return(_j=executableCode?.[0])===null||_j===void 0?void 0:_j.code}get codeExecutionResult(){var _a2,_b,_c,_d,_e,_f,_g,_h,_j;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result fro\
690
+ m the first one.");let codeExecutionResult=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.codeExecutionResult).map(part=>part.codeExecutionResult).filter(codeExecutionResult2=>codeExecutionResult2!==void 0);if(codeExecutionResult?.length!==0)return(_j=codeExecutionResult?.[0])===null||_j===void 0?void 0:_j.output}get initialPromptTokenCount(){var _a2;if(this.
691
+ usageMetadata)return(_a2=this.usageMetadata._initialPromptTokenCount)!==null&&_a2!==void 0?_a2:this.usageMetadata.promptTokenCount}},EmbedContentResponse=class{},GenerateImagesResponse=class{},EditImageResponse=class{},UpscaleImageResponse=class{},RecontextImageResponse=class{},SegmentImageResponse=class{},ListModelsResponse=class{},DeleteModelResponse=class{};var CountTokensResponse=class{},ComputeTokensResponse=class{};var GenerateVideosOperation=class _GenerateVideosOperation{_fromAPIResponse({apiResponse,_isVertexAI}){let operation=new _GenerateVideosOperation,response,op=apiResponse;return _isVertexAI?response=generateVideosOperationFromVertex$1(op):response=generateVideosOperationFromMldev$1(op),Object.assign(operation,response),operation}};var ListTuningJobsResponse=class{},CancelTuningJobResponse=class{},ValidateRewardResponse=class{},DeleteCachedContentResponse=class{},ListCachedContentsResponse=class{},ListDocumentsResponse=class{},ListFileSearchStoresResponse=class{},UploadToFileSearchStoreResumableResponse=class{};var ImportFileOperation=class _ImportFileOperation{_fromAPIResponse({apiResponse,_isVertexAI}){let operation=new _ImportFileOperation,response=importFileOperationFromMldev$1(apiResponse);return Object.assign(operation,response),operation}},ListFilesResponse=class{},CreateFileResponse=class{},DeleteFileResponse=class{},RegisterFilesResponse=class{};var ListBatchJobsResponse=class{};var LiveServerMessage=class{get text(){var _a2,_b,_c;let text="",anyTextPartFound=!1,nonTextParts=[];for(let part of(_c=(_b=(_a2=this.serverContent)===null||_a2===void 0?void 0:_a2.modelTurn)===null||_b===void 0?void 0:_b.parts)!==null&&_c!==void 0?_c:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="text"&&fieldName!=="thought"&&fieldValue!==null&&nonTextParts.push(fieldName);if(typeof part.text=="string"){if(typeof part.thought=="boolean"&&part.thought)continue;anyTextPartFound=
691
692
  !0,text+=part.text}}return nonTextParts.length>0&&console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),anyTextPartFound?text:void 0}get data(){var _a2,_b,_c;let data="",nonDataParts=[];for(let part of(_c=(_b=(_a2=this.serverContent)===null||_a2===void 0?void 0:_a2.modelTurn)===null||_b===void 0?void 0:_b.parts)!==null&&_c!==void 0?_c:[]){for(let[fieldName,fieldValue]of Object.
692
693
  entries(part))fieldName!=="inlineData"&&fieldValue!==null&&nonDataParts.push(fieldName);part.inlineData&&typeof part.inlineData.data=="string"&&(data+=atob(part.inlineData.data))}return nonDataParts.length>0&&console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),data.length>0?btoa(data):void 0}};var LiveMusicServerMessage=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}};var UploadToFileSearchStoreOperation=class _UploadToFileSearchStoreOperation{_fromAPIResponse({apiResponse,_isVertexAI}){let operation=new _UploadToFileSearchStoreOperation,response=uploadToFileSearchStoreOperationFromMldev(apiResponse);return Object.assign(operation,response),operation}};function tModel(apiClient,model){if(!model||typeof model!="string")throw new Error("model is required and must be a string");if(model.includes("..")||model.includes("?")||model.includes("&"))throw new Error("in\
693
694
  valid model parameter");if(apiClient.isVertexAI()){if(model.startsWith("publishers/")||model.startsWith("projects/")||model.startsWith("models/"))return model;if(model.indexOf("/")>=0){let parts=model.split("/",2);return`publishers/${parts[0]}/models/${parts[1]}`}else return`publishers/google/models/${model}`}else return model.startsWith("models/")||model.startsWith("tunedModels/")?model:`models/${model}`}function tCachesModel(apiClient,model){let transformedModel=tModel(apiClient,model);return transformedModel?
@@ -830,137 +831,135 @@ headers},response2})),response.then(apiResponse=>deleteResourceJobFromVertex(api
830
831
  _d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>deleteResourceJobFromMldev(apiResponse))}}};function authConfigToMldev$3(fromObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKe\
831
832
  yConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Deve\
832
833
  loper API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig para\
833
- meter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function computerUseToVertex$3(fromObject){let toObject={},fromEnablePromptInjectionDetection=getValueByPath(fromObject,["enablePromptInjectionDetection"]);fromEnablePromptInjectionDetection!=null&&setValueByPath(toObject,["enablePromptInjectionDetection"],fromEnablePromptInjectionDetection);let fromEnvironment=getValueByPath(fromObject,["environment"]);fromEnvironment!=null&&setValueByPath(
834
- toObject,["environment"],fromEnvironment);let fromExcludedPredefinedFunctions=getValueByPath(fromObject,["excludedPredefinedFunctions"]);if(fromExcludedPredefinedFunctions!=null&&setValueByPath(toObject,["excludedPredefinedFunctions"],fromExcludedPredefinedFunctions),getValueByPath(fromObject,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function contentToMldev$3(fromObject){
835
- let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$3(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function contentToVertex$3(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=
836
- null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex$3(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createCachedContentConfigToMldev(fromObject,parentObject){let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,
837
- ["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime);let fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromContents=getValueByPath(fromObject,["contents"]);if(parentObject!==void 0&&fromContents!=null){let transformedList=tContents(fromContents);Array.
838
- isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$3(item))),setValueByPath(parentObject,["contents"],transformedList)}let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToMldev$3(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=fromTools;
839
- Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$3(item))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);if(parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToMldev$1(fromToolConfig)),getValueByPath(fromObject,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gem\
840
- ini Developer API mode.");return toObject}function createCachedContentConfigToVertex(fromObject,parentObject){let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime);let fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&
841
- fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromContents=getValueByPath(fromObject,["contents"]);if(parentObject!==void 0&&fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$3(item))),setValueByPath(parentObject,["contents"],transformedList)}let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=
842
- null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$3(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=fromTools;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex$3(item))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(
843
- parentObject,["toolConfig"],toolConfigToVertex$1(fromToolConfig));let fromKmsKeyName=getValueByPath(fromObject,["kmsKeyName"]);return parentObject!==void 0&&fromKmsKeyName!=null&&setValueByPath(parentObject,["encryption_spec","kmsKeyName"],fromKmsKeyName),toObject}function createCachedContentParametersToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["model"],tCachesModel(apiClient,fromModel));let fromConfig=getValueByPath(
844
- fromObject,["config"]);return fromConfig!=null&&createCachedContentConfigToMldev(fromConfig,toObject),toObject}function createCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["model"],tCachesModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createCachedContentConfigToVertex(fromConfig,toObject),toObject}function deleteCachedContentParametersToMldev(apiClient,fromObject){
845
- let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function deleteCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function deleteCachedContentResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(
846
- fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function deleteCachedContentResponseFromVertex(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function functionCallToMldev$3(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=
847
- null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)
848
- throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function functionCallingConfigToMldev$1(fromObject){let toObject={},fromAllowedFunctionNames=getValueByPath(fromObject,["allowedFunctionNames"]);fromAllowedFunctionNames!=null&&setValueByPath(toObject,["allowedFunctionNames"],fromAllowedFunctionNames);let fromMode=getValueByPath(fromObject,["mode"]);if(fromMode!=null&&setValueByPath(toObject,["mo\
849
- de"],fromMode),getValueByPath(fromObject,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function getCachedContentParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function getCachedContentParametersToVertex(apiClient,fromObject){
850
- let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function googleMapsToMldev$3(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$3(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,
851
- ["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev$3(fromObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API m\
852
- ode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),
853
- toObject}function listCachedContentsConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listCachedContentsConfigToVertex(fromObject,parentObject){
854
- let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listCachedContentsParametersToMldev(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=
855
- null&&listCachedContentsConfigToMldev(fromConfig,toObject),toObject}function listCachedContentsParametersToVertex(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listCachedContentsConfigToVertex(fromConfig,toObject),toObject}function listCachedContentsResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);
856
- let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromCachedContents=getValueByPath(fromObject,["cachedContents"]);if(fromCachedContents!=null){let transformedList=fromCachedContents;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["cachedContents"],transformedList)}return toObject}function listCachedContentsResponseFromVertex(fromObject){
834
+ meter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function contentToMldev$3(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$3(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(
835
+ toObject,["role"],fromRole),toObject}function contentToVertex$3(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex$3(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createCachedContentConfigToMldev(fromObject,parentObject){
836
+ let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime);let fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromContents=getValueByPath(
837
+ fromObject,["contents"]);if(parentObject!==void 0&&fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$3(item))),setValueByPath(parentObject,["contents"],transformedList)}let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToMldev$3(tContent(fromSystemInstruction)));
838
+ let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=fromTools;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$3(item))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);if(parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToMldev$1(fromToolConfig)),getValueByPath(fromObject,["kmsKeyN\
839
+ ame"])!==void 0)throw new Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function createCachedContentConfigToVertex(fromObject,parentObject){let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,
840
+ ["expireTime"],fromExpireTime);let fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromContents=getValueByPath(fromObject,["contents"]);if(parentObject!==void 0&&fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$3(item))),setValueByPath(parentObject,["contents"],transformedList)}
841
+ let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$3(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=fromTools;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex$3(item))),setValueByPath(parentObject,["tools"],transformedList)}
842
+ let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToVertex$1(fromToolConfig));let fromKmsKeyName=getValueByPath(fromObject,["kmsKeyName"]);return parentObject!==void 0&&fromKmsKeyName!=null&&setValueByPath(parentObject,["encryption_spec","kmsKeyName"],fromKmsKeyName),toObject}function createCachedContentParametersToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,
843
+ ["model"]);fromModel!=null&&setValueByPath(toObject,["model"],tCachesModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createCachedContentConfigToMldev(fromConfig,toObject),toObject}function createCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["model"],tCachesModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["c\
844
+ onfig"]);return fromConfig!=null&&createCachedContentConfigToVertex(fromConfig,toObject),toObject}function deleteCachedContentParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function deleteCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(
845
+ toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function deleteCachedContentResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function deleteCachedContentResponseFromVertex(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(
846
+ toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function functionCallToMldev$3(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("\
847
+ partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function functionCallingConfigToMldev$1(fromObject){let toObject={},fromAllowedFunctionNames=getValueByPath(fromObject,["allowedFunctionNames"]);fromAllowedFunctionNames!=null&&
848
+ setValueByPath(toObject,["allowedFunctionNames"],fromAllowedFunctionNames);let fromMode=getValueByPath(fromObject,["mode"]);if(fromMode!=null&&setValueByPath(toObject,["mode"],fromMode),getValueByPath(fromObject,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function getCachedContentParametersToMldev(apiClient,fromObject){let toObject={},
849
+ fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function getCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function googleMapsToMldev$3(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["auth\
850
+ Config"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$3(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev$3(fromObject){
851
+ let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&
852
+ setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function listCachedContentsConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(
853
+ fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listCachedContentsConfigToVertex(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&
854
+ setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listCachedContentsParametersToMldev(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listCachedContentsConfigToMldev(fromConfig,toObject),toObject}function listCachedContentsParametersToVertex(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listCachedContentsConfigToVertex(fromConfig,toObject),toObject}function listCachedContentsResponseFromMldev(fromObject){
857
855
  let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromCachedContents=getValueByPath(fromObject,["cachedContents"]);if(fromCachedContents!=null){let transformedList=fromCachedContents;Array.isArray(transformedList)&&(transformedList=
858
- transformedList.map(item=>item)),setValueByPath(toObject,["cachedContents"],transformedList)}return toObject}function mcpServerToVertex$3(fromObject){let toObject={};if(getValueByPath(fromObject,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer AP\
859
- I mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function partToMldev$3(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(
860
- toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&
861
- setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev$3(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionRes\
862
- ponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&
863
- setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);fromMediaProcessing!=null&&setValueByPath(toObject,["mediaPro\
864
- cessing"],fromMediaProcessing);let fromSpeechMetadata=getValueByPath(fromObject,["speechMetadata"]);return fromSpeechMetadata!=null&&setValueByPath(toObject,["speechMetadata"],fromSpeechMetadata),toObject}function partToVertex$3(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution),getValueByPath(fromObject,["toolCall"])!==void 0)throw new Error("toolCall parame\
865
- ter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(
866
- fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=
867
- null&&setValueByPath(toObject,["functionCall"],fromFunctionCall);let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(
868
- fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);if(fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata),getValueByPath(fromObject,["partMetadata"])!==void 0)throw new Error("partMetadata p\
869
- arameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing);let fromSpeechMetadata=getValueByPath(fromObject,["speechMetadata"]);return fromSpeechMetadata!=null&&setValueByPath(toObject,["speechMetadata"],fromSpeechMetadata),toObject}function toolConfigToMldev$1(fromObject){let toObject={},fromFunctionCallingConfig=getValueByPath(
870
- fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],functionCallingConfigToMldev$1(fromFunctionCallingConfig));let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig);let fromIncludeServerSideToolInvocations=getValueByPath(fromObject,["includeServerSideToolInvocations"]);return fromIncludeServerSideToolInvocations!=null&&setValueByPath(
871
- toObject,["includeServerSideToolInvocations"],fromIncludeServerSideToolInvocations),toObject}function toolConfigToVertex$1(fromObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],fromFunctionCallingConfig);let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);if(fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig),
872
- getValueByPath(fromObject,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function toolToMldev$3(fromObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(
873
- fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev$3(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,
874
- ["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in\
875
- Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["\
876
- googleSearch"],googleSearchToMldev$3(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlC\
877
- ontext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function toolToVertex$3(fromObject){let toObject={},fromRetrieval=getValueByPath(fromObject,["retrieval"]);fromRetrieval!=null&&setValueByPath(toObject,["retrieval"],fromRetrieval);let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&
878
- setValueByPath(toObject,["googleMaps"],fromGoogleMaps);let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>mcpServerToVertex$3(item))),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(
879
- fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],computerUseToVertex$3(fromComputerUse));let fromEnterpriseWebSearch=getValueByPath(fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(
880
- fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=
881
- null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(fromObject,["parallelAiSearch"]);fromParallelAiSearch!=null&&setValueByPath(toObject,["parallelAiSearch"],fromParallelAiSearch);let fromUrlContext=getValueByPath(fromObject,["urlContext"]);if(fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext),getValueByPath(fromObject,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported i\
882
- n Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function updateCachedContentConfigToMldev(fromObject,parentObject){let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);return parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime),toObject}function updateCachedContentConfigToVertex(fromObject,parentObject){
883
- let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);return parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime),toObject}function updateCachedContentParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url",
884
- "name"],tCachedContentName(apiClient,fromName));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateCachedContentConfigToMldev(fromConfig,toObject),toObject}function updateCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateCachedContentConfigToVertex(
885
- fromConfig,toObject),toObject}var Caches=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS,x=>this.listInternal(x),await this.listInternal(params),params)}async create(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=createCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("cachedContents",body._url),queryParams=
886
- body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}else{let body=createCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("cachedContents",body._url),queryParams=
887
- body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async get(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getCachedContentParametersToVertex(
888
- this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}else{let body=getCachedContentParametersToMldev(this.apiClient,
889
- params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};
890
- if(this.apiClient.isVertexAI()){let body=deleteCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(
891
- jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteCachedContentResponseFromVertex(apiResponse),typedResp=new DeleteCachedContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=deleteCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request(
892
- {path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteCachedContentResponseFromMldev(apiResponse),typedResp=new DeleteCachedContentResponse;
893
- return Object.assign(typedResp,resp),typedResp})}}async update(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=updateCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,
894
- abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}else{let body=updateCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=
895
- params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async listInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listCachedContentsParametersToVertex(params);return path2=formatMap("cachedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GE\
896
- T",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listCachedContentsResponseFromVertex(apiResponse),typedResp=new ListCachedContentsResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=listCachedContentsParametersToMldev(
897
- params);return path2=formatMap("cachedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.
898
- headers},response2})),response.then(apiResponse=>{let resp=listCachedContentsResponseFromMldev(apiResponse),typedResp=new ListCachedContentsResponse;return Object.assign(typedResp,resp),typedResp})}}};function __rest(s,e){var t={};for(var p in s)Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0&&(t[p]=s[p]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,p=Object.getOwnPropertySymbols(s);i<p.length;i++)e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(
899
- s,p[i])&&(t[p[i]]=s[p[i]]);return t}function __values(o){var s=typeof Symbol=="function"&&Symbol.iterator,m=s&&o[s],i=0;if(m)return m.call(o);if(o&&typeof o.length=="number")return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")}function __await(v){return this instanceof __await?(this.v=v,this):new __await(v)}function __asyncGenerator(thisArg,_arguments,generator){if(!Symbol.asyncIterator)
900
- throw new TypeError("Symbol.asyncIterator is not defined.");var g=generator.apply(thisArg,_arguments||[]),i,q=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",awaitReturn),i[Symbol.asyncIterator]=function(){return this},i;function awaitReturn(f){return function(v){return Promise.resolve(v).then(f,reject)}}function verb(n,f){g[n]&&(i[n]=function(v){return new Promise(function(a,b){q.push([n,v,a,b])>1||resume(n,v)})},
901
- f&&(i[n]=f(i[n])))}function resume(n,v){try{step(g[n](v))}catch(e){settle(q[0][3],e)}}function step(r){r.value instanceof __await?Promise.resolve(r.value.v).then(fulfill,reject):settle(q[0][2],r)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f,v){f(v),q.shift(),q.length&&resume(q[0][0],q[0][1])}}function __asyncValues(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var m=o[Symbol.asyncIterator],i;
902
- return m?m.call(o):(o=typeof __values=="function"?__values(o):o[Symbol.iterator](),i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i);function verb(n){i[n]=o[n]&&function(v){return new Promise(function(resolve,reject){v=o[n](v),settle(resolve,reject,v.done,v.value)})}}function settle(resolve,reject,d,v){Promise.resolve(v).then(function(v2){resolve({value:v2,done:d})},reject)}}function isValidResponse(response){var _a2;if(response.candidates==null||response.candidates.length===0)return!1;let content=(_a2=response.candidates[0])===null||_a2===void 0?void 0:_a2.content;return content===void 0?!1:isValidContent(content)}function isValidContent(content){if(content.parts===void 0||content.parts.length===0)return!1;for(let part of content.parts)if(part===void 0||Object.keys(part).length===0)return!1;return!0}function validateHistory(history){if(history.length!==0){for(let content of history)
856
+ transformedList.map(item=>item)),setValueByPath(toObject,["cachedContents"],transformedList)}return toObject}function listCachedContentsResponseFromVertex(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromCachedContents=getValueByPath(
857
+ fromObject,["cachedContents"]);if(fromCachedContents!=null){let transformedList=fromCachedContents;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["cachedContents"],transformedList)}return toObject}function mcpServerToVertex$3(fromObject){let toObject={};if(getValueByPath(fromObject,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(
858
+ fromObject,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function partToMldev$3(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(
859
+ toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["co\
860
+ deExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev$3(fromFunctionCall));
861
+ let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(
862
+ toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);
863
+ let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing);let fromSpeechMetadata=getValueByPath(fromObject,["speechMetadata"]);return fromSpeechMetadata!=null&&setValueByPath(toObject,["speechMetadata"],fromSpeechMetadata),toObject}function partToVertex$3(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(
864
+ toObject,["mediaResolution"],fromMediaResolution),getValueByPath(fromObject,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);
865
+ fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=
866
+ null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],fromFunctionCall);let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);
867
+ let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);if(fromVideoMetadata!=null&&setValueByPath(
868
+ toObject,["videoMetadata"],fromVideoMetadata),getValueByPath(fromObject,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing);let fromSpeechMetadata=getValueByPath(fromObject,["speechMetadata"]);return fromSpeechMetadata!=null&&
869
+ setValueByPath(toObject,["speechMetadata"],fromSpeechMetadata),toObject}function toolConfigToMldev$1(fromObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],functionCallingConfigToMldev$1(fromFunctionCallingConfig));let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig);
870
+ let fromIncludeServerSideToolInvocations=getValueByPath(fromObject,["includeServerSideToolInvocations"]);return fromIncludeServerSideToolInvocations!=null&&setValueByPath(toObject,["includeServerSideToolInvocations"],fromIncludeServerSideToolInvocations),toObject}function toolConfigToVertex$1(fromObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],fromFunctionCallingConfig);
871
+ let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);if(fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig),getValueByPath(fromObject,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function toolToMldev$3(fromObject){let toObject={};if(getValueByPath(fromObject,["retriev\
872
+ al"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev$3(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),
873
+ setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise\
874
+ Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(
875
+ toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev$3(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallel\
876
+ AiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function toolToVertex$3(fromObject){let toObject={},fromRetrieval=getValueByPath(fromObject,[
877
+ "retrieval"]);fromRetrieval!=null&&setValueByPath(toObject,["retrieval"],fromRetrieval);let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],fromGoogleMaps);let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>mcpServerToVertex$3(item))),setValueByPath(toObject,["mcpServers"],transformedList)}
878
+ let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse);let fromEnterpriseWebSearch=getValueByPath(fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(
879
+ fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=
880
+ null&&setValueByPath(toObject,["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(fromObject,["parallelAiSearch"]);fromParallelAiSearch!=null&&setValueByPath(toObject,["parallelAiSearch"],fromParallelAiSearch);let fromUrlContext=getValueByPath(fromObject,["urlContext"]);if(fromUrlContext!=
881
+ null&&setValueByPath(toObject,["urlContext"],fromUrlContext),getValueByPath(fromObject,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function updateCachedContentConfigToMldev(fromObject,parentObject){let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(
882
+ fromObject,["expireTime"]);return parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime),toObject}function updateCachedContentConfigToVertex(fromObject,parentObject){let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);return parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["\
883
+ expireTime"],fromExpireTime),toObject}function updateCachedContentParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateCachedContentConfigToMldev(fromConfig,toObject),toObject}function updateCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(
884
+ fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateCachedContentConfigToVertex(fromConfig,toObject),toObject}var Caches=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS,x=>this.listInternal(x),await this.listInternal(params),params)}async create(params){
885
+ var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=createCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("cachedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:
886
+ _b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}else{let body=createCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("cachedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.
887
+ abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async get(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===
888
+ void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}else{let body=getCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:
889
+ _c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=deleteCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.
890
+ stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteCachedContentResponseFromVertex(apiResponse),typedResp=new DeleteCachedContentResponse;return Object.assign(
891
+ typedResp,resp),typedResp})}else{let body=deleteCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{
892
+ let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteCachedContentResponseFromMldev(apiResponse),typedResp=new DeleteCachedContentResponse;return Object.assign(typedResp,resp),typedResp})}}async update(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=updateCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),
893
+ queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}else{let body=updateCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=
894
+ body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async listInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listCachedContentsParametersToVertex(
895
+ params);return path2=formatMap("cachedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.
896
+ headers},response2})),response.then(apiResponse=>{let resp=listCachedContentsResponseFromVertex(apiResponse),typedResp=new ListCachedContentsResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=listCachedContentsParametersToMldev(params);return path2=formatMap("cachedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===
897
+ null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listCachedContentsResponseFromMldev(apiResponse),typedResp=new ListCachedContentsResponse;return Object.assign(typedResp,resp),typedResp})}}};function __rest(s,e){var t={};for(var p in s)
898
+ Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0&&(t[p]=s[p]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,p=Object.getOwnPropertySymbols(s);i<p.length;i++)e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(s,p[i])&&(t[p[i]]=s[p[i]]);return t}function __values(o){var s=typeof Symbol=="function"&&Symbol.iterator,m=s&&o[s],i=0;if(m)return m.call(o);if(o&&typeof o.length=="number")return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],
899
+ done:!o}}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")}function __await(v){return this instanceof __await?(this.v=v,this):new __await(v)}function __asyncGenerator(thisArg,_arguments,generator){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var g=generator.apply(thisArg,_arguments||[]),i,q=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",
900
+ awaitReturn),i[Symbol.asyncIterator]=function(){return this},i;function awaitReturn(f){return function(v){return Promise.resolve(v).then(f,reject)}}function verb(n,f){g[n]&&(i[n]=function(v){return new Promise(function(a,b){q.push([n,v,a,b])>1||resume(n,v)})},f&&(i[n]=f(i[n])))}function resume(n,v){try{step(g[n](v))}catch(e){settle(q[0][3],e)}}function step(r){r.value instanceof __await?Promise.resolve(r.value.v).then(fulfill,reject):settle(q[0][2],r)}function fulfill(value){resume("next",value)}
901
+ function reject(value){resume("throw",value)}function settle(f,v){f(v),q.shift(),q.length&&resume(q[0][0],q[0][1])}}function __asyncValues(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var m=o[Symbol.asyncIterator],i;return m?m.call(o):(o=typeof __values=="function"?__values(o):o[Symbol.iterator](),i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i);function verb(n){i[n]=o[n]&&function(v){return new Promise(function(resolve,reject){
902
+ v=o[n](v),settle(resolve,reject,v.done,v.value)})}}function settle(resolve,reject,d,v){Promise.resolve(v).then(function(v2){resolve({value:v2,done:d})},reject)}}function isValidResponse(response){var _a2;if(response.candidates==null||response.candidates.length===0)return!1;let content=(_a2=response.candidates[0])===null||_a2===void 0?void 0:_a2.content;return content===void 0?!1:isValidContent(content)}function isValidContent(content){if(content.parts===void 0||content.parts.length===0)return!1;for(let part of content.parts)if(part===void 0||Object.keys(part).length===0)return!1;return!0}function validateHistory(history){if(history.length!==0){for(let content of history)
903
903
  if(content.role!=="user"&&content.role!=="model")throw new Error(`Role must be user or model, but got ${content.role}.`)}}function extractCuratedHistory(comprehensiveHistory){if(comprehensiveHistory===void 0||comprehensiveHistory.length===0)return[];let curatedHistory=[],length=comprehensiveHistory.length,i=0;for(;i<length;)if(comprehensiveHistory[i].role==="user")curatedHistory.push(comprehensiveHistory[i]),i++;else{let modelOutput=[],isValid=!0;for(;i<length&&comprehensiveHistory[i].role==="mo\
904
904
  del";)modelOutput.push(comprehensiveHistory[i]),isValid&&!isValidContent(comprehensiveHistory[i])&&(isValid=!1),i++;isValid?curatedHistory.push(...modelOutput):curatedHistory.pop()}return curatedHistory}var Chats=class{constructor(modelsModule,apiClient){this.modelsModule=modelsModule,this.apiClient=apiClient}create(params){return new Chat(this.apiClient,this.modelsModule,params.model,params.config,structuredClone(params.history))}},Chat=class{constructor(apiClient,modelsModule,model,config={},history=[]){
905
905
  this.apiClient=apiClient,this.modelsModule=modelsModule,this.model=model,this.config=config,this.history=history,this.sendPromise=Promise.resolve(),validateHistory(history)}async sendMessage(params){var _a2;await this.sendPromise;let inputContent=tContent(params.message),responsePromise=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(inputContent),config:(_a2=params.config)!==null&&_a2!==void 0?_a2:this.config});return this.sendPromise=(async()=>{var _a3,_b,
906
906
  _c;let response=await responsePromise,outputContent=(_b=(_a3=response.candidates)===null||_a3===void 0?void 0:_a3[0])===null||_b===void 0?void 0:_b.content,fullAutomaticFunctionCallingHistory=response.automaticFunctionCallingHistory,index=this.getHistory(!0).length,automaticFunctionCallingHistory=[];fullAutomaticFunctionCallingHistory!=null&&(automaticFunctionCallingHistory=(_c=fullAutomaticFunctionCallingHistory.slice(index))!==null&&_c!==void 0?_c:[]);let modelOutput=outputContent?[outputContent]:
907
907
  [];this.recordHistory(inputContent,modelOutput,automaticFunctionCallingHistory)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),responsePromise}async sendMessageStream(params){var _a2;await this.sendPromise;let inputContent=tContent(params.message),streamResponse=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(inputContent),config:(_a2=params.config)!==null&&_a2!==void 0?_a2:this.config});this.sendPromise=streamResponse.then(
908
- ()=>{}).catch(()=>{});let response=await streamResponse;return this.processStreamResponse(response,inputContent)}getHistory(curated=!1){let history=curated?extractCuratedHistory(this.history):this.history;return structuredClone(history)}processStreamResponse(streamResponse,inputContent){return __asyncGenerator(this,arguments,function*(){var _a2,e_1,_b,_c,_d,_e;let outputContent=[];try{for(var _f=!0,streamResponse_1=__asyncValues(streamResponse),streamResponse_1_1;streamResponse_1_1=yield __await(
909
- streamResponse_1.next()),_a2=streamResponse_1_1.done,!_a2;_f=!0){_c=streamResponse_1_1.value,_f=!1;let chunk=_c;if(isValidResponse(chunk)){let content=(_e=(_d=chunk.candidates)===null||_d===void 0?void 0:_d[0])===null||_e===void 0?void 0:_e.content;content!==void 0&&outputContent.push(content)}yield yield __await(chunk)}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_f&&!_a2&&(_b=streamResponse_1.return)&&(yield __await(_b.call(streamResponse_1)))}finally{if(e_1)throw e_1.error}}this.recordHistory(
910
- inputContent,outputContent)})}recordHistory(userInput,modelOutput,automaticFunctionCallingHistory){let outputContents=[];modelOutput.length>0&&modelOutput.every(content=>content.role!==void 0)?outputContents=modelOutput:outputContents.push({role:"model",parts:[]}),automaticFunctionCallingHistory&&automaticFunctionCallingHistory.length>0?this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)):this.history.push(userInput),this.history.push(...outputContents)}};var ApiError=class _ApiError extends Error{constructor(options){
911
- super(options.message),this.name="ApiError",this.status=options.status,Object.setPrototypeOf(this,_ApiError.prototype)}};function createFileParametersToMldev(fromObject){let toObject={},fromFile=getValueByPath(fromObject,["file"]);return fromFile!=null&&setValueByPath(toObject,["file"],fromFile),toObject}function createFileResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sd\
912
- kHttpResponse"],fromSdkHttpResponse),toObject}function deleteFileParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","file"],tFileName(fromName)),toObject}function deleteFileResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function getFileParametersToMldev(fromObject){
913
- let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","file"],tFileName(fromName)),toObject}function internalRegisterFilesParametersToMldev(fromObject){let toObject={},fromUris=getValueByPath(fromObject,["uris"]);return fromUris!=null&&setValueByPath(toObject,["uris"],fromUris),toObject}function listFilesConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=
914
- null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listFilesParametersToMldev(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listFilesConfigToMldev(fromConfig,toObject),toObject}function listFilesResponseFromMldev(fromObject){let toObject={},
915
- fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromFiles=getValueByPath(fromObject,["files"]);if(fromFiles!=null){let transformedList=fromFiles;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(
916
- toObject,["files"],transformedList)}return toObject}function registerFilesResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromFiles=getValueByPath(fromObject,["files"]);if(fromFiles!=null){let transformedList=fromFiles;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["files"],transformedList)}
917
- return toObject}var Files$1=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_FILES,x=>this.listInternal(x),await this.listInternal(params),params)}async upload(params){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(params.file,params.
918
- config).then(resp=>resp)}async download(params){await this.apiClient.downloadFile(params)}async registerFiles(params){throw new Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(params){return this.registerFilesInternal(params)}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=listFilesParametersToMldev(params);return path2=
919
- formatMap("files",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),
920
- response.then(apiResponse=>{let resp=listFilesResponseFromMldev(apiResponse),typedResp=new ListFilesResponse;return Object.assign(typedResp,resp),typedResp})}}async createInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createFileParametersToMldev(params);return path2=formatMap("upload/v1beta/files",body._url),queryParams=body._query,delete body._url,delete body.
921
- _query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=createFileResponseFromMldev(apiResponse),typedResp=new CreateFileResponse;return Object.assign(typedResp,resp),typedResp})}}async get(params){var _a2,_b;let response,
922
- path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=getFileParametersToMldev(params);return path2=formatMap("files/{file}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===
923
- void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=deleteFileParametersToMldev(params);return path2=formatMap("files/{file}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(
924
- body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteFileResponseFromMldev(apiResponse),typedResp=new DeleteFileResponse;return Object.assign(typedResp,resp),typedResp})}}async registerFilesInternal(params){
925
- var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=internalRegisterFilesParametersToMldev(params);return path2=formatMap("files:register",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,
926
- abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=registerFilesResponseFromMldev(apiResponse),typedResp=new RegisterFilesResponse;return Object.assign(typedResp,resp),typedResp})}}};function authConfigToMldev$2(fromObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==
927
- void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Plat\
928
- form mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error(
929
- "oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function computerUseToVertex$2(fromObject){let toObject={},fromEnablePromptInjectionDetection=getValueByPath(fromObject,["enablePromptInjectionDetection"]);fromEnablePromptInjectionDetection!=null&&setValueByPath(toObject,["enablePromptInjectionDetection"],fromEnablePromptInjectionDetection);let fromEnvironment=getValueByPath(fromObject,["environment"]);fromEnvironment!=
930
- null&&setValueByPath(toObject,["environment"],fromEnvironment);let fromExcludedPredefinedFunctions=getValueByPath(fromObject,["excludedPredefinedFunctions"]);if(fromExcludedPredefinedFunctions!=null&&setValueByPath(toObject,["excludedPredefinedFunctions"],fromExcludedPredefinedFunctions),getValueByPath(fromObject,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}
931
- function contentToMldev$2(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$2(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function contentToVertex$2(fromObject){let toObject={},fromParts=getValueByPath(
932
- fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex$2(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function functionCallToMldev$2(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);
933
- let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only \
934
- supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generationConfigToVertex$1(fromObject){let toObject={},fromModelSelectionConfig=getValueByPath(fromObject,["modelSelectionConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelConfig"],fromModelSelectionConfig);let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);
935
- let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCoun\
936
- t"],fromCandidateCount);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);fromEnableAffectiveDialog!=null&&setValueByPath(toObject,["enableAffectiveDialog"],fromEnableAffectiveDialog);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);
937
- let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromResponseFormat=getValueByPath(
938
- fromObject,["responseFormat"]);if(fromResponseFormat!=null){let transformedList=fromResponseFormat;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseFormat"],transformedList)}let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=
939
- null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],fromResponseSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&
940
- setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],speechConfigToVertex$1(fromSpeechConfig));let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromTemperature=getValueByPath(
941
- fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromTopP=getValueByPath(fromObject,["topP"]);if(fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP),getValueByPath(
942
- fromObject,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromTranslationConfig=getValueByPath(fromObject,["translationConfig"]);return fromTranslationConfig!=null&&setValueByPath(toObject,["translationConfig"],fromTranslationConfig),toObject}function googleMapsToMldev$2(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfi\
943
- g"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$2(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev$2(fromObject){
944
- let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&
945
- setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function liveConnectConfigToMldev$1(fromObject,parentObject){let toObject={},fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig"],fromGenerationConfig);
946
- let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);parentObject!==void 0&&fromResponseModalities!=null&&setValueByPath(parentObject,["setup","generationConfig","responseModalities"],fromResponseModalities);let fromTemperature=getValueByPath(fromObject,["temperature"]);parentObject!==void 0&&fromTemperature!=null&&setValueByPath(parentObject,["setup","generationConfig","temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);parentObject!==void 0&&
947
- fromTopP!=null&&setValueByPath(parentObject,["setup","generationConfig","topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);parentObject!==void 0&&fromTopK!=null&&setValueByPath(parentObject,["setup","generationConfig","topK"],fromTopK);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["setup","generationConfig","maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(
948
- fromObject,["mediaResolution"]);parentObject!==void 0&&fromMediaResolution!=null&&setValueByPath(parentObject,["setup","generationConfig","mediaResolution"],fromMediaResolution);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["setup","generationConfig","seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);parentObject!==void 0&&fromSpeechConfig!=null&&setValueByPath(parentObject,["setup","generation\
949
- Config","speechConfig"],tLiveSpeechConfig(fromSpeechConfig));let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);parentObject!==void 0&&fromThinkingConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","thinkingConfig"],fromThinkingConfig);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);parentObject!==void 0&&fromEnableAffectiveDialog!=null&&setValueByPath(parentObject,["setup","generationConfig","enableAffectiveDialog"],fromEnableAffectiveDialog);
950
- let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["setup","systemInstruction"],contentToMldev$2(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$2(tTool(item)))),setValueByPath(parentObject,
951
- ["setup","tools"],transformedList)}let fromSessionResumption=getValueByPath(fromObject,["sessionResumption"]);parentObject!==void 0&&fromSessionResumption!=null&&setValueByPath(parentObject,["setup","sessionResumption"],sessionResumptionConfigToMldev$1(fromSessionResumption));let fromInputAudioTranscription=getValueByPath(fromObject,["inputAudioTranscription"]);parentObject!==void 0&&fromInputAudioTranscription!=null&&setValueByPath(parentObject,["setup","inputAudioTranscription"],fromInputAudioTranscription);
952
- let fromOutputAudioTranscription=getValueByPath(fromObject,["outputAudioTranscription"]);parentObject!==void 0&&fromOutputAudioTranscription!=null&&setValueByPath(parentObject,["setup","outputAudioTranscription"],fromOutputAudioTranscription);let fromRealtimeInputConfig=getValueByPath(fromObject,["realtimeInputConfig"]);parentObject!==void 0&&fromRealtimeInputConfig!=null&&setValueByPath(parentObject,["setup","realtimeInputConfig"],fromRealtimeInputConfig);let fromContextWindowCompression=getValueByPath(
953
- fromObject,["contextWindowCompression"]);parentObject!==void 0&&fromContextWindowCompression!=null&&setValueByPath(parentObject,["setup","contextWindowCompression"],fromContextWindowCompression);let fromProactivity=getValueByPath(fromObject,["proactivity"]);if(parentObject!==void 0&&fromProactivity!=null&&setValueByPath(parentObject,["setup","proactivity"],fromProactivity),getValueByPath(fromObject,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in \
954
- Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromAvatarConfig=getValueByPath(fromObject,["avatarConfig"]);parentObject!==void 0&&fromAvatarConfig!=null&&setValueByPath(parentObject,["setup","avatarConfig"],fromAvatarConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev$2(
955
- item))),setValueByPath(parentObject,["setup","safetySettings"],transformedList)}let fromTranslationConfig=getValueByPath(fromObject,["translationConfig"]);return parentObject!==void 0&&fromTranslationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","translationConfig"],fromTranslationConfig),toObject}function liveConnectConfigToVertex(fromObject,parentObject){let toObject={},fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);parentObject!==void 0&&fromGenerationConfig!=
956
- null&&setValueByPath(parentObject,["setup","generationConfig"],generationConfigToVertex$1(fromGenerationConfig));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);parentObject!==void 0&&fromResponseModalities!=null&&setValueByPath(parentObject,["setup","generationConfig","responseModalities"],fromResponseModalities);let fromTemperature=getValueByPath(fromObject,["temperature"]);parentObject!==void 0&&fromTemperature!=null&&setValueByPath(parentObject,["setup","generati\
957
- onConfig","temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);parentObject!==void 0&&fromTopP!=null&&setValueByPath(parentObject,["setup","generationConfig","topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);parentObject!==void 0&&fromTopK!=null&&setValueByPath(parentObject,["setup","generationConfig","topK"],fromTopK);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(
958
- parentObject,["setup","generationConfig","maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);parentObject!==void 0&&fromMediaResolution!=null&&setValueByPath(parentObject,["setup","generationConfig","mediaResolution"],fromMediaResolution);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["setup","generationConfig","seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,
959
- ["speechConfig"]);parentObject!==void 0&&fromSpeechConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","speechConfig"],speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig)));let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);parentObject!==void 0&&fromThinkingConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","thinkingConfig"],fromThinkingConfig);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);parentObject!==
960
- void 0&&fromEnableAffectiveDialog!=null&&setValueByPath(parentObject,["setup","generationConfig","enableAffectiveDialog"],fromEnableAffectiveDialog);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["setup","systemInstruction"],contentToVertex$2(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(
961
- fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex$2(tTool(item)))),setValueByPath(parentObject,["setup","tools"],transformedList)}let fromSessionResumption=getValueByPath(fromObject,["sessionResumption"]);parentObject!==void 0&&fromSessionResumption!=null&&setValueByPath(parentObject,["setup","sessionResumption"],fromSessionResumption);let fromInputAudioTranscription=getValueByPath(fromObject,["inputAudioTranscription"]);parentObject!==void 0&&fromInputAudioTranscription!=
962
- null&&setValueByPath(parentObject,["setup","inputAudioTranscription"],fromInputAudioTranscription);let fromOutputAudioTranscription=getValueByPath(fromObject,["outputAudioTranscription"]);parentObject!==void 0&&fromOutputAudioTranscription!=null&&setValueByPath(parentObject,["setup","outputAudioTranscription"],fromOutputAudioTranscription);let fromRealtimeInputConfig=getValueByPath(fromObject,["realtimeInputConfig"]);parentObject!==void 0&&fromRealtimeInputConfig!=null&&setValueByPath(parentObject,
963
- ["setup","realtimeInputConfig"],fromRealtimeInputConfig);let fromContextWindowCompression=getValueByPath(fromObject,["contextWindowCompression"]);parentObject!==void 0&&fromContextWindowCompression!=null&&setValueByPath(parentObject,["setup","contextWindowCompression"],fromContextWindowCompression);let fromProactivity=getValueByPath(fromObject,["proactivity"]);parentObject!==void 0&&fromProactivity!=null&&setValueByPath(parentObject,["setup","proactivity"],fromProactivity);let fromExplicitVadSignal=getValueByPath(
908
+ ()=>{}).catch(()=>{});let response=await streamResponse;return this.processStreamResponse(response,inputContent)}getHistory(curated=!1){let history=curated?extractCuratedHistory(this.history):this.history;return structuredClone(history)}processStreamResponse(streamResponse,inputContent){return __asyncGenerator(this,arguments,function*(){var _a2,e_1,_b,_c,_d,_e,_f,_g;let outputContent=[],isValid=!0,finished2=!1;try{for(var _h=!0,streamResponse_1=__asyncValues(streamResponse),streamResponse_1_1;streamResponse_1_1=
909
+ yield __await(streamResponse_1.next()),_a2=streamResponse_1_1.done,!_a2;_h=!0){_c=streamResponse_1_1.value,_h=!1;let chunk=_c;if(isValidResponse(chunk)){let content=(_e=(_d=chunk.candidates)===null||_d===void 0?void 0:_d[0])===null||_e===void 0?void 0:_e.content;content!==void 0&&outputContent.push(content)}else isValid=!1;((_g=(_f=chunk.candidates)===null||_f===void 0?void 0:_f[0])===null||_g===void 0?void 0:_g.finishReason)!==void 0&&(finished2=!0),yield yield __await(chunk)}}catch(e_1_1){e_1=
910
+ {error:e_1_1}}finally{try{!_h&&!_a2&&(_b=streamResponse_1.return)&&(yield __await(_b.call(streamResponse_1)))}finally{if(e_1)throw e_1.error}}this.recordHistory(inputContent,isValid&&finished2?outputContent:[])})}recordHistory(userInput,modelOutput,automaticFunctionCallingHistory){let outputContents=[];modelOutput.length>0&&modelOutput.every(content=>content.role!==void 0)?outputContents=modelOutput:outputContents.push({role:"model",parts:[]}),automaticFunctionCallingHistory&&automaticFunctionCallingHistory.
911
+ length>0?this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)):this.history.push(userInput),this.history.push(...outputContents)}};var ApiError=class _ApiError extends Error{constructor(options){super(options.message),this.name="ApiError",this.status=options.status,Object.setPrototypeOf(this,_ApiError.prototype)}};function createFileParametersToMldev(fromObject){let toObject={},fromFile=getValueByPath(fromObject,["file"]);return fromFile!=null&&setValueByPath(toObject,["fi\
912
+ le"],fromFile),toObject}function createFileResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function deleteFileParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","file"],tFileName(fromName)),toObject}function deleteFileResponseFromMldev(fromObject){
913
+ let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function getFileParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","file"],tFileName(fromName)),toObject}function internalRegisterFilesParametersToMldev(fromObject){let toObject={},fromUris=getValueByPath(fromObject,
914
+ ["uris"]);return fromUris!=null&&setValueByPath(toObject,["uris"],fromUris),toObject}function listFilesConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}
915
+ function listFilesParametersToMldev(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listFilesConfigToMldev(fromConfig,toObject),toObject}function listFilesResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=
916
+ null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromFiles=getValueByPath(fromObject,["files"]);if(fromFiles!=null){let transformedList=fromFiles;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["files"],transformedList)}return toObject}function registerFilesResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,
917
+ ["sdkHttpResponse"],fromSdkHttpResponse);let fromFiles=getValueByPath(fromObject,["files"]);if(fromFiles!=null){let transformedList=fromFiles;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["files"],transformedList)}return toObject}var Files$1=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_FILES,x=>this.listInternal(x),await this.listInternal(params),
918
+ params)}async upload(params){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(params.file,params.config).then(resp=>resp)}async download(params){await this.apiClient.downloadFile(params)}async registerFiles(params){throw new Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(params){return this.
919
+ registerFilesInternal(params)}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=listFilesParametersToMldev(params);return path2=formatMap("files",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||
920
+ _a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listFilesResponseFromMldev(apiResponse),typedResp=new ListFilesResponse;return Object.assign(typedResp,resp),typedResp})}}async createInternal(params){var _a2,_b;let response,path2="",queryParams={};
921
+ if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createFileParametersToMldev(params);return path2=formatMap("upload/v1beta/files",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:
922
+ _b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=createFileResponseFromMldev(apiResponse),typedResp=new CreateFileResponse;return Object.assign(typedResp,resp),typedResp})}}async get(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=getFileParametersToMldev(params);return path2=formatMap("files/{file}",body._url),queryParams=body.
923
+ _query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only sup\
924
+ ported by the Gemini Developer API.");{let body=deleteFileParametersToMldev(params);return path2=formatMap("files/{file}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{
925
+ let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteFileResponseFromMldev(apiResponse),typedResp=new DeleteFileResponse;return Object.assign(typedResp,resp),typedResp})}}async registerFilesInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=internalRegisterFilesParametersToMldev(
926
+ params);return path2=formatMap("files:register",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=registerFilesResponseFromMldev(apiResponse),typedResp=new RegisterFilesResponse;
927
+ return Object.assign(typedResp,resp),typedResp})}}};function authConfigToMldev$2(fromObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType paramet\
928
+ er is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemi\
929
+ ni Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function contentToMldev$2(fromObject){let toObject={},fromParts=getValueByPath(fromObject,
930
+ ["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$2(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function contentToVertex$2(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&
931
+ (transformedList=transformedList.map(item=>partToVertex$2(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function functionCallToMldev$2(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);
932
+ let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}
933
+ function generationConfigToVertex$1(fromObject){let toObject={},fromModelSelectionConfig=getValueByPath(fromObject,["modelSelectionConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelConfig"],fromModelSelectionConfig);let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConf\
934
+ ig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromEnableAffectiveDialog=getValueByPath(fromObject,["e\
935
+ nableAffectiveDialog"]);fromEnableAffectiveDialog!=null&&setValueByPath(toObject,["enableAffectiveDialog"],fromEnableAffectiveDialog);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);
936
+ fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromResponseFormat=getValueByPath(fromObject,["responseFormat"]);if(fromResponseFormat!=
937
+ null){let transformedList=fromResponseFormat;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseFormat"],transformedList)}let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],
938
+ fromResponseMimeType);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],fromResponseSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);
939
+ let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],speechConfigToVertex$1(fromSpeechConfig));let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=
940
+ null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromTopP=getValueByPath(fromObject,["topP"]);if(fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP),getValueByPath(fromObject,["enableEnhancedCivicAnswers"])!==
941
+ void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromTranslationConfig=getValueByPath(fromObject,["translationConfig"]);return fromTranslationConfig!=null&&setValueByPath(toObject,["translationConfig"],fromTranslationConfig),toObject}function googleMapsToMldev$2(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,
942
+ ["authConfig"],authConfigToMldev$2(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev$2(fromObject){let toObject={};if(getValueByPath(fromObject,
943
+ ["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);
944
+ let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function liveConnectConfigToMldev$1(fromObject,parentObject){let toObject={},fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig"],fromGenerationConfig);let fromResponseModalities=getValueByPath(fromObject,
945
+ ["responseModalities"]);parentObject!==void 0&&fromResponseModalities!=null&&setValueByPath(parentObject,["setup","generationConfig","responseModalities"],fromResponseModalities);let fromTemperature=getValueByPath(fromObject,["temperature"]);parentObject!==void 0&&fromTemperature!=null&&setValueByPath(parentObject,["setup","generationConfig","temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);parentObject!==void 0&&fromTopP!=null&&setValueByPath(parentObject,["setup",
946
+ "generationConfig","topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);parentObject!==void 0&&fromTopK!=null&&setValueByPath(parentObject,["setup","generationConfig","topK"],fromTopK);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["setup","generationConfig","maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);parentObject!==
947
+ void 0&&fromMediaResolution!=null&&setValueByPath(parentObject,["setup","generationConfig","mediaResolution"],fromMediaResolution);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["setup","generationConfig","seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);parentObject!==void 0&&fromSpeechConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","speechConfig"],tLiveSpeechConfig(fromSpeechConfig));
948
+ let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);parentObject!==void 0&&fromThinkingConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","thinkingConfig"],fromThinkingConfig);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);parentObject!==void 0&&fromEnableAffectiveDialog!=null&&setValueByPath(parentObject,["setup","generationConfig","enableAffectiveDialog"],fromEnableAffectiveDialog);let fromSystemInstruction=getValueByPath(
949
+ fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["setup","systemInstruction"],contentToMldev$2(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$2(tTool(item)))),setValueByPath(parentObject,["setup","tools"],transformedList)}let fromSessionResumption=getValueByPath(
950
+ fromObject,["sessionResumption"]);parentObject!==void 0&&fromSessionResumption!=null&&setValueByPath(parentObject,["setup","sessionResumption"],sessionResumptionConfigToMldev$1(fromSessionResumption));let fromInputAudioTranscription=getValueByPath(fromObject,["inputAudioTranscription"]);parentObject!==void 0&&fromInputAudioTranscription!=null&&setValueByPath(parentObject,["setup","inputAudioTranscription"],fromInputAudioTranscription);let fromOutputAudioTranscription=getValueByPath(fromObject,["\
951
+ outputAudioTranscription"]);parentObject!==void 0&&fromOutputAudioTranscription!=null&&setValueByPath(parentObject,["setup","outputAudioTranscription"],fromOutputAudioTranscription);let fromRealtimeInputConfig=getValueByPath(fromObject,["realtimeInputConfig"]);parentObject!==void 0&&fromRealtimeInputConfig!=null&&setValueByPath(parentObject,["setup","realtimeInputConfig"],fromRealtimeInputConfig);let fromContextWindowCompression=getValueByPath(fromObject,["contextWindowCompression"]);parentObject!==
952
+ void 0&&fromContextWindowCompression!=null&&setValueByPath(parentObject,["setup","contextWindowCompression"],fromContextWindowCompression);let fromProactivity=getValueByPath(fromObject,["proactivity"]);if(parentObject!==void 0&&fromProactivity!=null&&setValueByPath(parentObject,["setup","proactivity"],fromProactivity),getValueByPath(fromObject,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Dev\
953
+ eloper API mode.");let fromAvatarConfig=getValueByPath(fromObject,["avatarConfig"]);parentObject!==void 0&&fromAvatarConfig!=null&&setValueByPath(parentObject,["setup","avatarConfig"],fromAvatarConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev$2(item))),setValueByPath(parentObject,["se\
954
+ tup","safetySettings"],transformedList)}let fromTranslationConfig=getValueByPath(fromObject,["translationConfig"]);return parentObject!==void 0&&fromTranslationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","translationConfig"],fromTranslationConfig),toObject}function liveConnectConfigToVertex(fromObject,parentObject){let toObject={},fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,
955
+ ["setup","generationConfig"],generationConfigToVertex$1(fromGenerationConfig));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);parentObject!==void 0&&fromResponseModalities!=null&&setValueByPath(parentObject,["setup","generationConfig","responseModalities"],fromResponseModalities);let fromTemperature=getValueByPath(fromObject,["temperature"]);parentObject!==void 0&&fromTemperature!=null&&setValueByPath(parentObject,["setup","generationConfig","temperature"],fromTemperature);
956
+ let fromTopP=getValueByPath(fromObject,["topP"]);parentObject!==void 0&&fromTopP!=null&&setValueByPath(parentObject,["setup","generationConfig","topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);parentObject!==void 0&&fromTopK!=null&&setValueByPath(parentObject,["setup","generationConfig","topK"],fromTopK);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["setup","generationConfig",
957
+ "maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);parentObject!==void 0&&fromMediaResolution!=null&&setValueByPath(parentObject,["setup","generationConfig","mediaResolution"],fromMediaResolution);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["setup","generationConfig","seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);parentObject!==void 0&&
958
+ fromSpeechConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","speechConfig"],speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig)));let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);parentObject!==void 0&&fromThinkingConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","thinkingConfig"],fromThinkingConfig);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);parentObject!==void 0&&fromEnableAffectiveDialog!=
959
+ null&&setValueByPath(parentObject,["setup","generationConfig","enableAffectiveDialog"],fromEnableAffectiveDialog);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["setup","systemInstruction"],contentToVertex$2(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&
960
+ (transformedList=transformedList.map(item=>toolToVertex$2(tTool(item)))),setValueByPath(parentObject,["setup","tools"],transformedList)}let fromSessionResumption=getValueByPath(fromObject,["sessionResumption"]);parentObject!==void 0&&fromSessionResumption!=null&&setValueByPath(parentObject,["setup","sessionResumption"],fromSessionResumption);let fromInputAudioTranscription=getValueByPath(fromObject,["inputAudioTranscription"]);parentObject!==void 0&&fromInputAudioTranscription!=null&&setValueByPath(
961
+ parentObject,["setup","inputAudioTranscription"],fromInputAudioTranscription);let fromOutputAudioTranscription=getValueByPath(fromObject,["outputAudioTranscription"]);parentObject!==void 0&&fromOutputAudioTranscription!=null&&setValueByPath(parentObject,["setup","outputAudioTranscription"],fromOutputAudioTranscription);let fromRealtimeInputConfig=getValueByPath(fromObject,["realtimeInputConfig"]);parentObject!==void 0&&fromRealtimeInputConfig!=null&&setValueByPath(parentObject,["setup","realtime\
962
+ InputConfig"],fromRealtimeInputConfig);let fromContextWindowCompression=getValueByPath(fromObject,["contextWindowCompression"]);parentObject!==void 0&&fromContextWindowCompression!=null&&setValueByPath(parentObject,["setup","contextWindowCompression"],fromContextWindowCompression);let fromProactivity=getValueByPath(fromObject,["proactivity"]);parentObject!==void 0&&fromProactivity!=null&&setValueByPath(parentObject,["setup","proactivity"],fromProactivity);let fromExplicitVadSignal=getValueByPath(
964
963
  fromObject,["explicitVadSignal"]);parentObject!==void 0&&fromExplicitVadSignal!=null&&setValueByPath(parentObject,["setup","explicitVadSignal"],fromExplicitVadSignal);let fromAvatarConfig=getValueByPath(fromObject,["avatarConfig"]);parentObject!==void 0&&fromAvatarConfig!=null&&setValueByPath(parentObject,["setup","avatarConfig"],fromAvatarConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;
965
964
  Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(parentObject,["setup","safetySettings"],transformedList)}let fromTranslationConfig=getValueByPath(fromObject,["translationConfig"]);return parentObject!==void 0&&fromTranslationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","translationConfig"],fromTranslationConfig),toObject}function liveConnectParametersToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,
966
965
  ["model"]);fromModel!=null&&setValueByPath(toObject,["setup","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["config"],liveConnectConfigToMldev$1(fromConfig,toObject)),toObject}function liveConnectParametersToVertex(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["setup","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(
@@ -997,9 +996,9 @@ rUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==voi
997
996
  null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev$2(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(
998
997
  toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(
999
998
  toObject,["fileSearch"],fromFileSearch),toObject}function toolToVertex$2(fromObject){let toObject={},fromRetrieval=getValueByPath(fromObject,["retrieval"]);fromRetrieval!=null&&setValueByPath(toObject,["retrieval"],fromRetrieval);let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],fromGoogleMaps);let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(
1000
- transformedList)&&(transformedList=transformedList.map(item=>mcpServerToVertex$2(item))),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],computerUseToVertex$2(fromComputerUse));let fromEnterpriseWebSearch=getValueByPath(
1001
- fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.
1002
- map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(fromObject,["parallelAiSearch"]);fromParallelAiSearch!=
999
+ transformedList)&&(transformedList=transformedList.map(item=>mcpServerToVertex$2(item))),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse);let fromEnterpriseWebSearch=getValueByPath(fromObject,["ent\
1000
+ erpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),
1001
+ setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(fromObject,["parallelAiSearch"]);fromParallelAiSearch!=
1003
1002
  null&&setValueByPath(toObject,["parallelAiSearch"],fromParallelAiSearch);let fromUrlContext=getValueByPath(fromObject,["urlContext"]);if(fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext),getValueByPath(fromObject,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function usageMetadataFromVertex(fromObject){let toObject={},fromResponseTokenCount=getValueByPath(
1004
1003
  fromObject,["candidatesTokenCount"]);fromResponseTokenCount!=null&&setValueByPath(toObject,["responseTokenCount"],fromResponseTokenCount);let fromResponseTokensDetails=getValueByPath(fromObject,["candidatesTokensDetails"]);if(fromResponseTokensDetails!=null){let transformedList=fromResponseTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseTokensDetails"],transformedList)}let fromCacheTokensDetails=getValueByPath(fromObject,
1005
1004
  ["cacheTokensDetails"]);if(fromCacheTokensDetails!=null){let transformedList=fromCacheTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["cacheTokensDetails"],transformedList)}let fromCachedContentTokenCount=getValueByPath(fromObject,["cachedContentTokenCount"]);fromCachedContentTokenCount!=null&&setValueByPath(toObject,["cachedContentTokenCount"],fromCachedContentTokenCount);let fromPromptTokenCount=getValueByPath(fromObject,
@@ -1016,116 +1015,114 @@ setValueByPath(toObject,["citationMetadata"],citationMetadataFromMldev(fromCitat
1016
1015
  ["safetyRatings"]);if(fromSafetyRatings!=null){let transformedList=fromSafetyRatings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["safetyRatings"],transformedList)}let fromUrlContextMetadata=getValueByPath(fromObject,["urlContextMetadata"]);fromUrlContextMetadata!=null&&setValueByPath(toObject,["urlContextMetadata"],fromUrlContextMetadata);let fromContinuationToken=getValueByPath(fromObject,["continuationToken"]);return fromContinuationToken!=
1017
1016
  null&&setValueByPath(toObject,["continuationToken"],fromContinuationToken),toObject}function citationMetadataFromMldev(fromObject,_rootObject){let toObject={},fromCitations=getValueByPath(fromObject,["citationSources"]);if(fromCitations!=null){let transformedList=fromCitations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["citations"],transformedList)}return toObject}function computeTokensParametersToVertex(apiClient,fromObject,rootObject){
1018
1017
  let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}return toObject}function computeTokensResponseFromVertex(fromObject,_rootObject){
1019
- let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTokensInfo=getValueByPath(fromObject,["tokensInfo"]);if(fromTokensInfo!=null){let transformedList=fromTokensInfo;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["tokensInfo"],transformedList)}return toObject}function computerUseToVertex$1(fromObject,_rootObject){
1020
- let toObject={},fromEnablePromptInjectionDetection=getValueByPath(fromObject,["enablePromptInjectionDetection"]);fromEnablePromptInjectionDetection!=null&&setValueByPath(toObject,["enablePromptInjectionDetection"],fromEnablePromptInjectionDetection);let fromEnvironment=getValueByPath(fromObject,["environment"]);fromEnvironment!=null&&setValueByPath(toObject,["environment"],fromEnvironment);let fromExcludedPredefinedFunctions=getValueByPath(fromObject,["excludedPredefinedFunctions"]);if(fromExcludedPredefinedFunctions!=
1021
- null&&setValueByPath(toObject,["excludedPredefinedFunctions"],fromExcludedPredefinedFunctions),getValueByPath(fromObject,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function contentEmbeddingFromVertex(fromObject,rootObject){let toObject={},fromValues=getValueByPath(fromObject,["values"]);fromValues!=null&&setValueByPath(toObject,["values"],fromValues);
1022
- let fromStatistics=getValueByPath(fromObject,["statistics"]);return fromStatistics!=null&&setValueByPath(toObject,["statistics"],contentEmbeddingStatisticsFromVertex(fromStatistics)),toObject}function contentEmbeddingStatisticsFromVertex(fromObject,_rootObject){let toObject={},fromTruncated=getValueByPath(fromObject,["truncated"]);fromTruncated!=null&&setValueByPath(toObject,["truncated"],fromTruncated);let fromTokenCount=getValueByPath(fromObject,["token_count"]);fromTokenCount!=null&&setValueByPath(
1023
- toObject,["tokenCount"],fromTokenCount);let fromTokensDetails=getValueByPath(fromObject,["tokensDetails"]);if(fromTokensDetails!=null){let transformedList=fromTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["tokensDetails"],transformedList)}return toObject}function contentToMldev$1(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(
1024
- transformedList)&&(transformedList=transformedList.map(item=>partToMldev$1(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function contentToVertex$1(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex$1(
1025
- item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function controlReferenceConfigToVertex(fromObject,_rootObject){let toObject={},fromControlType=getValueByPath(fromObject,["controlType"]);fromControlType!=null&&setValueByPath(toObject,["controlType"],fromControlType);let fromEnableControlImageComputation=getValueByPath(fromObject,["enableControlImageComputation"]);
1026
- return fromEnableControlImageComputation!=null&&setValueByPath(toObject,["computeControl"],fromEnableControlImageComputation),toObject}function countTokensConfigToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tools"])!==void 0)throw new Error("tools parameter is only\
1027
- supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function countTokensConfigToVertex(fromObject,parentObject,rootObject){let toObject={},fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=
1028
- null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$1(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=fromTools;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex$1(item))),setValueByPath(parentObject,["tools"],transformedList)}let fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);return parentObject!==void 0&&fromGenerationConfig!=
1029
- null&&setValueByPath(parentObject,["generationConfig"],generationConfigToVertex(fromGenerationConfig)),toObject}function countTokensParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=
1030
- transformedList.map(item=>contentToMldev$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&countTokensConfigToMldev(fromConfig),toObject}function countTokensParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["cont\
1031
- ents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&countTokensConfigToVertex(fromConfig,toObject),toObject}function countTokensResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpRes\
1032
- ponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTotalTokens=getValueByPath(fromObject,["totalTokens"]);fromTotalTokens!=null&&setValueByPath(toObject,["totalTokens"],fromTotalTokens);let fromCachedContentTokenCount=getValueByPath(fromObject,["cachedContentTokenCount"]);return fromCachedContentTokenCount!=null&&setValueByPath(toObject,["cachedContentTokenCount"],fromCachedContentTokenCount),toObject}function countTokensResponseFromVertex(fromObject,_rootObject){
1033
- let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTotalTokens=getValueByPath(fromObject,["totalTokens"]);return fromTotalTokens!=null&&setValueByPath(toObject,["totalTokens"],fromTotalTokens),toObject}function deleteModelParametersToMldev(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(
1034
- toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function deleteModelParametersToVertex(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function deleteModelResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,
1035
- ["sdkHttpResponse"],fromSdkHttpResponse),toObject}function deleteModelResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function editImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(
1036
- parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromAspectRatio=getValueByPath(fromObject,["\
1037
- aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromGuidanceScale=getValueByPath(fromObject,["guidanceScale"]);parentObject!==void 0&&fromGuidanceScale!=null&&setValueByPath(parentObject,["parameters","guidanceScale"],fromGuidanceScale);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(
1038
- fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeSafetyAttributes=getValueByPath(fromObject,["includeSafetyAttributes"]);parentObject!==void 0&&fromIncludeSafetyAttributes!=
1039
- null&&setValueByPath(parentObject,["parameters","includeSafetyAttributes"],fromIncludeSafetyAttributes);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromLanguage=getValueByPath(fromObject,["language"]);parentObject!==void 0&&fromLanguage!=null&&setValueByPath(parentObject,["parameters","language"],fromLanguage);let fromOutputMimeType=getValueByPath(
1040
- fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==
1041
- void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromEditMode=getValueByPath(fromObject,["editMode"]);parentObject!==void 0&&fromEditMode!=null&&setValueByPath(parentObject,["parameters","editMode"],fromEditMode);let fromBaseSteps=getValueByPath(fromObject,["baseSteps"]);return parentObject!==
1042
- void 0&&fromBaseSteps!=null&&setValueByPath(parentObject,["parameters","editConfig","baseSteps"],fromBaseSteps),toObject}function editImageParametersInternalToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromReferenceImages=getValueByPath(
1043
- fromObject,["referenceImages"]);if(fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>referenceImageAPIInternalToVertex(item))),setValueByPath(toObject,["instances[0]","referenceImages"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&editImageConfigToVertex(fromConfig,toObject),toObject}function editImageResponseFromVertex(fromObject,rootObject){let toObject={},
1044
- fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function embedContentConfigToMldev(fromObject,parentObject,_rootObject){
1045
- let toObject={},fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["requests[]","taskType"],fromTaskType);let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["requests[]","title"],fromTitle);let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);if(parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,
1046
- ["requests[]","outputDimensionality"],fromOutputDimensionality),getValueByPath(fromObject,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["documentOcr"])!==void 0)throw new Error(
1047
- "documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function embedContentConfigToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorTaskType=getValueByPath(rootObject,["embeddingApiType"]);
1048
- if(discriminatorTaskType===void 0&&(discriminatorTaskType="PREDICT"),discriminatorTaskType==="PREDICT"){let fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["instances[]","task_type"],fromTaskType)}else if(discriminatorTaskType==="EMBED_CONTENT"){let fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["embedContentConfig","taskType"],fromTaskType)}let discriminatorTitle=getValueByPath(
1049
- rootObject,["embeddingApiType"]);if(discriminatorTitle===void 0&&(discriminatorTitle="PREDICT"),discriminatorTitle==="PREDICT"){let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["instances[]","title"],fromTitle)}else if(discriminatorTitle==="EMBED_CONTENT"){let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["embedContentConfig","title"],fromTitle)}let discriminatorOutputDimensionality=getValueByPath(
1050
- rootObject,["embeddingApiType"]);if(discriminatorOutputDimensionality===void 0&&(discriminatorOutputDimensionality="PREDICT"),discriminatorOutputDimensionality==="PREDICT"){let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["parameters","outputDimensionality"],fromOutputDimensionality)}else if(discriminatorOutputDimensionality==="EMBED_CONTENT"){let fromOutputDimensionality=getValueByPath(
1051
- fromObject,["outputDimensionality"]);parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["embedContentConfig","outputDimensionality"],fromOutputDimensionality)}let discriminatorMimeType=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorMimeType===void 0&&(discriminatorMimeType="PREDICT"),discriminatorMimeType==="PREDICT"){let fromMimeType=getValueByPath(fromObject,["mimeType"]);parentObject!==void 0&&fromMimeType!=null&&setValueByPath(parentObject,["\
1052
- instances[]","mimeType"],fromMimeType)}let discriminatorAutoTruncate=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorAutoTruncate===void 0&&(discriminatorAutoTruncate="PREDICT"),discriminatorAutoTruncate==="PREDICT"){let fromAutoTruncate=getValueByPath(fromObject,["autoTruncate"]);parentObject!==void 0&&fromAutoTruncate!=null&&setValueByPath(parentObject,["parameters","autoTruncate"],fromAutoTruncate)}else if(discriminatorAutoTruncate==="EMBED_CONTENT"){let fromAutoTruncate=getValueByPath(
1053
- fromObject,["autoTruncate"]);parentObject!==void 0&&fromAutoTruncate!=null&&setValueByPath(parentObject,["embedContentConfig","autoTruncate"],fromAutoTruncate)}let discriminatorDocumentOcr=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorDocumentOcr===void 0&&(discriminatorDocumentOcr="PREDICT"),discriminatorDocumentOcr==="EMBED_CONTENT"){let fromDocumentOcr=getValueByPath(fromObject,["documentOcr"]);parentObject!==void 0&&fromDocumentOcr!=null&&setValueByPath(parentObject,["embed\
1054
- ContentConfig","documentOcr"],fromDocumentOcr)}let discriminatorAudioTrackExtraction=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorAudioTrackExtraction===void 0&&(discriminatorAudioTrackExtraction="PREDICT"),discriminatorAudioTrackExtraction==="EMBED_CONTENT"){let fromAudioTrackExtraction=getValueByPath(fromObject,["audioTrackExtraction"]);parentObject!==void 0&&fromAudioTrackExtraction!=null&&setValueByPath(parentObject,["embedContentConfig","audioTrackExtraction"],fromAudioTrackExtraction)}
1055
- return toObject}function embedContentParametersPrivateToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContentsForEmbed(apiClient,fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["reque\
1056
- sts[]","content"],transformedList)}let fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&contentToMldev$1(tContent(fromContent));let fromConfig=getValueByPath(fromObject,["config"]);fromConfig!=null&&embedContentConfigToMldev(fromConfig,toObject);let fromModelForEmbedContent=getValueByPath(fromObject,["model"]);return fromModelForEmbedContent!==void 0&&setValueByPath(toObject,["requests[]","model"],tModel(apiClient,fromModelForEmbedContent)),toObject}function embedContentParametersPrivateToVertex(apiClient,fromObject,rootObject){
1057
- let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let discriminatorContents=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorContents===void 0&&(discriminatorContents="PREDICT"),discriminatorContents==="PREDICT"){let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContentsForEmbed(apiClient,fromContents);Array.isArray(transformedList)&&
1058
- (transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["instances[]","content"],transformedList)}}let discriminatorContent=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorContent===void 0&&(discriminatorContent="PREDICT"),discriminatorContent==="EMBED_CONTENT"){let fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&setValueByPath(toObject,["content"],contentToVertex$1(tContent(fromContent)))}let fromConfig=getValueByPath(fromObject,["config"]);
1059
- return fromConfig!=null&&embedContentConfigToVertex(fromConfig,toObject,rootObject),toObject}function embedContentResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromEmbeddings=getValueByPath(fromObject,["embeddings"]);if(fromEmbeddings!=null){let transformedList=fromEmbeddings;Array.isArray(transformedList)&&(transformedList=
1060
- transformedList.map(item=>item)),setValueByPath(toObject,["embeddings"],transformedList)}let fromMetadata=getValueByPath(fromObject,["metadata"]);return fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata),toObject}function embedContentResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromEmbeddings=getValueByPath(
1061
- fromObject,["predictions[]","embeddings"]);if(fromEmbeddings!=null){let transformedList=fromEmbeddings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentEmbeddingFromVertex(item))),setValueByPath(toObject,["embeddings"],transformedList)}let fromMetadata=getValueByPath(fromObject,["metadata"]);if(fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata),rootObject&&getValueByPath(rootObject,["embeddingApiType"])==="EMBED_CONTENT"){let embedding=getValueByPath(
1062
- fromObject,["embedding"]),usageMetadata=getValueByPath(fromObject,["usageMetadata"]),truncated=getValueByPath(fromObject,["truncated"]);if(embedding){let stats={};usageMetadata&&usageMetadata.promptTokenCount&&(stats.tokenCount=usageMetadata.promptTokenCount),usageMetadata&&usageMetadata.promptTokensDetails&&(stats.tokensDetails=usageMetadata.promptTokensDetails),truncated&&(stats.truncated=truncated),embedding.statistics=stats,setValueByPath(toObject,["embeddings"],[embedding])}}return toObject}
1063
- function endpointFromVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["endpoint"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDeployedModelId=getValueByPath(fromObject,["deployedModelId"]);return fromDeployedModelId!=null&&setValueByPath(toObject,["deployedModelId"],fromDeployedModelId),toObject}function functionCallToMldev$1(fromObject,_rootObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(
1064
- toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("wil\
1065
- lContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function functionCallingConfigToMldev(fromObject,_rootObject){let toObject={},fromAllowedFunctionNames=getValueByPath(fromObject,["allowedFunctionNames"]);fromAllowedFunctionNames!=null&&setValueByPath(toObject,["allowedFunctionNames"],fromAllowedFunctionNames);let fromMode=getValueByPath(fromObject,["mode"]);if(fromMode!=null&&setValueByPath(toObject,["mode"],fromMode),
1066
- getValueByPath(fromObject,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateContentConfigToMldev(apiClient,fromObject,parentObject,rootObject){let toObject={},fromServiceTier=getValueByPath(fromObject,["serviceTier"]);parentObject!==void 0&&fromServiceTier!=null&&setValueByPath(parentObject,["serviceTier"],fromServiceTier);
1067
- let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToMldev$1(tContent(fromSystemInstruction)));let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(
1068
- fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(
1069
- toObject,["stopSequences"],fromStopSequences);let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);
1070
- let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseSchema=getValueByPath(fromObject,["respo\
1071
- nseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],tSchema(fromResponseSchema));let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);if(fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema),getValueByPath(fromObject,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(
1072
- fromObject,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev$1(item))),setValueByPath(parentObject,["safetySettings"],
1073
- transformedList)}let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$1(tTool(item)))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToMldev(fromToolConfig));let fromLabels=getValueByPath(
1074
- fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromCachedContent=getValueByPath(fromObject,["cachedContent"]);parentObject!==void 0&&fromCachedContent!=null&&setValueByPath(parentObject,["cachedContent"],tCachedContentName(apiClient,fromCachedContent));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);
1075
- let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);if(fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],tSpeechConfig(fromSpeechConfig)),getValueByPath(fromObject,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini \
1076
- Developer API mode.");let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromImageConfig=getValueByPath(fromObject,["imageConfig"]);fromImageConfig!=null&&setValueByPath(toObject,["\
1077
- imageConfig"],imageConfigToMldev(fromImageConfig));let fromEnableEnhancedCivicAnswers=getValueByPath(fromObject,["enableEnhancedCivicAnswers"]);if(fromEnableEnhancedCivicAnswers!=null&&setValueByPath(toObject,["enableEnhancedCivicAnswers"],fromEnableEnhancedCivicAnswers),getValueByPath(fromObject,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromContinuationToken=getValueByPath(
1078
- fromObject,["continuationToken"]);return parentObject!==void 0&&fromContinuationToken!=null&&setValueByPath(parentObject,["continuationToken"],fromContinuationToken),toObject}function generateContentConfigToVertex(apiClient,fromObject,parentObject,rootObject){let toObject={},fromServiceTier=getValueByPath(fromObject,["serviceTier"]);parentObject!==void 0&&fromServiceTier!=null&&setValueByPath(parentObject,["serviceTier"],fromServiceTier);let fromSystemInstruction=getValueByPath(fromObject,["syst\
1079
- emInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$1(tContent(fromSystemInstruction)));let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(
1080
- toObject,["topK"],fromTopK);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);
1081
- let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromFrequencyPenalty=getValueByPath(fromObject,
1082
- ["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(
1083
- toObject,["responseSchema"],tSchema(fromResponseSchema));let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromModelSelectionConfig=getValueByPath(fromObject,["modelSelectionConfig"]);fromModelSelectionConfig!=null&&
1084
- setValueByPath(toObject,["modelConfig"],fromModelSelectionConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(parentObject,["safetySettings"],transformedList)}let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);
1085
- Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex$1(tTool(item)))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToVertex(fromToolConfig));let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromCachedContent=getValueByPath(
1086
- fromObject,["cachedContent"]);parentObject!==void 0&&fromCachedContent!=null&&setValueByPath(parentObject,["cachedContent"],tCachedContentName(apiClient,fromCachedContent));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);
1087
- let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],speechConfigToVertex(tSpeechConfig(fromSpeechConfig)));let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);
1088
- let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromImageConfig=getValueByPath(fromObject,["imageConfig"]);if(fromImageConfig!=null&&setValueByPath(toObject,["imageConfig"],imageConfigToVertex(fromImageConfig)),getValueByPath(fromObject,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is o\
1089
- nly supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromModelArmorConfig=getValueByPath(fromObject,["modelArmorConfig"]);parentObject!==void 0&&fromModelArmorConfig!=null&&setValueByPath(parentObject,["modelArmorConfig"],fromModelArmorConfig);let fromContinuationToken=getValueByPath(fromObject,["continuationToken"]);return parentObject!==void 0&&fromContinuationToken!=null&&setValueByPath(parentObject,["continuationToken"],fromContinuationToken),toObject}
1090
- function generateContentParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$1(item))),setValueByPath(toObject,["contents"],transformedList)}
1091
- let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["generationConfig"],generateContentConfigToMldev(apiClient,fromConfig,toObject)),toObject}function generateContentParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(
1092
- fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["generationConfig"],generateContentConfigToVertex(apiClient,fromConfig,toObject)),toObject}function generateContentResponseFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpR\
1093
- esponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromCandidates=getValueByPath(fromObject,["candidates"]);if(fromCandidates!=null){let transformedList=fromCandidates;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>candidateFromMldev(item))),setValueByPath(toObject,["candidates"],transformedList)}let fromModelVersion=getValueByPath(fromObject,["modelVersion"]);fromModelVersion!=null&&setValueByPath(toObject,["mod\
1094
- elVersion"],fromModelVersion);let fromPromptFeedback=getValueByPath(fromObject,["promptFeedback"]);fromPromptFeedback!=null&&setValueByPath(toObject,["promptFeedback"],fromPromptFeedback);let fromResponseId=getValueByPath(fromObject,["responseId"]);fromResponseId!=null&&setValueByPath(toObject,["responseId"],fromResponseId);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],fromUsageMetadata);let fromModelStatus=getValueByPath(
1095
- fromObject,["modelStatus"]);return fromModelStatus!=null&&setValueByPath(toObject,["modelStatus"],fromModelStatus),toObject}function generateContentResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromCandidates=getValueByPath(fromObject,["candidates"]);if(fromCandidates!=null){let transformedList=fromCandidates;Array.isArray(
1096
- transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["candidates"],transformedList)}let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromModelVersion=getValueByPath(fromObject,["modelVersion"]);fromModelVersion!=null&&setValueByPath(toObject,["modelVersion"],fromModelVersion);let fromPromptFeedback=getValueByPath(fromObject,["promptFeedback"]);fromPromptFeedback!=null&&
1097
- setValueByPath(toObject,["promptFeedback"],fromPromptFeedback);let fromResponseId=getValueByPath(fromObject,["responseId"]);fromResponseId!=null&&setValueByPath(toObject,["responseId"],fromResponseId);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);return fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],fromUsageMetadata),toObject}function generateImagesConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,
1098
- ["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sa\
1099
- mpleCount"],fromNumberOfImages);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromGuidanceScale=getValueByPath(fromObject,["guidanceScale"]);parentObject!==void 0&&fromGuidanceScale!=null&&setValueByPath(parentObject,["parameters","guidanceScale"],fromGuidanceScale);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(
1100
- parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeSafetyAttributes=getValueByPath(
1018
+ let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTokensInfo=getValueByPath(fromObject,["tokensInfo"]);if(fromTokensInfo!=null){let transformedList=fromTokensInfo;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["tokensInfo"],transformedList)}return toObject}function contentEmbeddingFromVertex(fromObject,rootObject){
1019
+ let toObject={},fromValues=getValueByPath(fromObject,["values"]);fromValues!=null&&setValueByPath(toObject,["values"],fromValues);let fromStatistics=getValueByPath(fromObject,["statistics"]);return fromStatistics!=null&&setValueByPath(toObject,["statistics"],contentEmbeddingStatisticsFromVertex(fromStatistics)),toObject}function contentEmbeddingStatisticsFromVertex(fromObject,_rootObject){let toObject={},fromTruncated=getValueByPath(fromObject,["truncated"]);fromTruncated!=null&&setValueByPath(toObject,
1020
+ ["truncated"],fromTruncated);let fromTokenCount=getValueByPath(fromObject,["token_count"]);fromTokenCount!=null&&setValueByPath(toObject,["tokenCount"],fromTokenCount);let fromTokensDetails=getValueByPath(fromObject,["tokensDetails"]);if(fromTokensDetails!=null){let transformedList=fromTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["tokensDetails"],transformedList)}return toObject}function contentToMldev$1(fromObject,rootObject){
1021
+ let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$1(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function contentToVertex$1(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=
1022
+ null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex$1(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function controlReferenceConfigToVertex(fromObject,_rootObject){let toObject={},fromControlType=getValueByPath(fromObject,["controlType"]);fromControlType!=null&&setValueByPath(toObject,["con\
1023
+ trolType"],fromControlType);let fromEnableControlImageComputation=getValueByPath(fromObject,["enableControlImageComputation"]);return fromEnableControlImageComputation!=null&&setValueByPath(toObject,["computeControl"],fromEnableControlImageComputation),toObject}function countTokensConfigToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode\
1024
+ , not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tools"])!==void 0)throw new Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function countTokensConfigToVertex(fromObject,parentObject,rootObject){
1025
+ let toObject={},fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$1(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=fromTools;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex$1(item))),setValueByPath(parentObject,["tools"],
1026
+ transformedList)}let fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);return parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["generationConfig"],generationConfigToVertex(fromGenerationConfig)),toObject}function countTokensParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(
1027
+ fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&countTokensConfigToMldev(fromConfig),toObject}function countTokensParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["mode\
1028
+ l"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&countTokensConfigToVertex(fromConfig,toObject),toObject}
1029
+ function countTokensResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTotalTokens=getValueByPath(fromObject,["totalTokens"]);fromTotalTokens!=null&&setValueByPath(toObject,["totalTokens"],fromTotalTokens);let fromCachedContentTokenCount=getValueByPath(fromObject,["cachedContentTokenCount"]);return fromCachedContentTokenCount!=
1030
+ null&&setValueByPath(toObject,["cachedContentTokenCount"],fromCachedContentTokenCount),toObject}function countTokensResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTotalTokens=getValueByPath(fromObject,["totalTokens"]);return fromTotalTokens!=null&&setValueByPath(toObject,["totalTokens"],fromTotalTokens),toObject}function deleteModelParametersToMldev(apiClient,fromObject,_rootObject){
1031
+ let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function deleteModelParametersToVertex(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function deleteModelResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(
1032
+ fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function deleteModelResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function editImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(
1033
+ fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["para\
1034
+ meters","sampleCount"],fromNumberOfImages);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromGuidanceScale=getValueByPath(fromObject,["guidanceScale"]);parentObject!==void 0&&fromGuidanceScale!=null&&setValueByPath(parentObject,["parameters","guidanceScale"],fromGuidanceScale);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=
1035
+ null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeSafetyAttributes=getValueByPath(
1101
1036
  fromObject,["includeSafetyAttributes"]);parentObject!==void 0&&fromIncludeSafetyAttributes!=null&&setValueByPath(parentObject,["parameters","includeSafetyAttributes"],fromIncludeSafetyAttributes);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromLanguage=getValueByPath(fromObject,["language"]);parentObject!==void 0&&fromLanguage!=null&&
1102
1037
  setValueByPath(parentObject,["parameters","language"],fromLanguage);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQualit\
1103
- y"],fromOutputCompressionQuality);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromImageSize=getValueByPath(fromObject,["imageSize"]);parentObject!==void 0&&fromImageSize!=null&&setValueByPath(parentObject,["\
1104
- parameters","sampleImageSize"],fromImageSize);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);return parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt),toObject}function generateImagesParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(
1105
- fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateImagesConfigToVertex(fromConfig,toObject),toObject}function generateImagesResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(
1106
- fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}let fromPositivePromptSafetyAttributes=getValueByPath(fromObject,["positivePromptSafetyAttributes"]);return fromPositivePromptSafetyAttributes!=null&&setValueByPath(toObject,["positivePromptSafetyAttributes"],safetyAttributesFromVertex(
1107
- fromPositivePromptSafetyAttributes)),toObject}function generateVideosConfigToMldev(fromObject,parentObject,rootObject){let toObject={},fromNumberOfVideos=getValueByPath(fromObject,["numberOfVideos"]);if(parentObject!==void 0&&fromNumberOfVideos!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfVideos),getValueByPath(fromObject,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Deve\
1108
- loper API mode.");if(getValueByPath(fromObject,["fps"])!==void 0)throw new Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromDurationSeconds=getValueByPath(fromObject,["durationSeconds"]);if(parentObject!==void 0&&fromDurationSeconds!=null&&setValueByPath(parentObject,["parameters","durationSeconds"],fromDurationSeconds),getValueByPath(fromObject,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemi\
1109
- ni Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromResolution=getValueByPath(fromObject,["resolution"]);parentObject!==void 0&&fromResolution!=null&&setValueByPath(parentObject,["parameters","resolution"],fromResolution);let fromPersonGeneration=getValueByPath(fromObject,["personGeneratio\
1110
- n"]);if(parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration),getValueByPath(fromObject,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativeP\
1111
- rompt"],fromNegativePrompt);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);if(parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt),getValueByPath(fromObject,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromLastFrame=getValueByPath(fromObject,["lastFrame"]);parentObject!==void 0&&fromLastFrame!=
1112
- null&&setValueByPath(parentObject,["instances[0]","lastFrame"],imageToMldev(fromLastFrame));let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(parentObject!==void 0&&fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>videoGenerationReferenceImageToMldev(item))),setValueByPath(parentObject,["instances[0]","referenceImages"],transformedList)}if(getValueByPath(fromObject,["mask"])!==void 0)
1113
- throw new Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer \
1114
- API mode.");let fromWebhookConfig=getValueByPath(fromObject,["webhookConfig"]);if(parentObject!==void 0&&fromWebhookConfig!=null&&setValueByPath(parentObject,["webhookConfig"],fromWebhookConfig),getValueByPath(fromObject,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateVideosConfigToVertex(fromObject,parentObject,rootObject){let toObject={},fromNumberOfVideos=getValueByPath(
1115
- fromObject,["numberOfVideos"]);parentObject!==void 0&&fromNumberOfVideos!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfVideos);let fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromFps=getValueByPath(fromObject,["fps"]);parentObject!==void 0&&fromFps!=null&&setValueByPath(parentObject,["parameters","fps"],fromFps);let fromDurationSeconds=getValueByPath(
1116
- fromObject,["durationSeconds"]);parentObject!==void 0&&fromDurationSeconds!=null&&setValueByPath(parentObject,["parameters","durationSeconds"],fromDurationSeconds);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromResolution=getValueByPath(
1117
- fromObject,["resolution"]);parentObject!==void 0&&fromResolution!=null&&setValueByPath(parentObject,["parameters","resolution"],fromResolution);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromPubsubTopic=getValueByPath(fromObject,["pubsubTopic"]);parentObject!==void 0&&fromPubsubTopic!=null&&setValueByPath(parentObject,["parameter\
1118
- s","pubsubTopic"],fromPubsubTopic);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt);let fromGenerateAudio=getValueByPath(fromObject,["generateAudio"]);parentObject!==
1119
- void 0&&fromGenerateAudio!=null&&setValueByPath(parentObject,["parameters","generateAudio"],fromGenerateAudio);let fromLastFrame=getValueByPath(fromObject,["lastFrame"]);parentObject!==void 0&&fromLastFrame!=null&&setValueByPath(parentObject,["instances[0]","lastFrame"],imageToVertex(fromLastFrame));let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(parentObject!==void 0&&fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=
1120
- transformedList.map(item=>videoGenerationReferenceImageToVertex(item))),setValueByPath(parentObject,["instances[0]","referenceImages"],transformedList)}let fromMask=getValueByPath(fromObject,["mask"]);parentObject!==void 0&&fromMask!=null&&setValueByPath(parentObject,["instances[0]","mask"],videoGenerationMaskToVertex(fromMask));let fromCompressionQuality=getValueByPath(fromObject,["compressionQuality"]);parentObject!==void 0&&fromCompressionQuality!=null&&setValueByPath(parentObject,["parameter\
1121
- s","compressionQuality"],fromCompressionQuality);let fromLabels=getValueByPath(fromObject,["labels"]);if(parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),getValueByPath(fromObject,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromResizeMode=getValueByPath(fromObject,["resizeMode"]);return parentObject!==void 0&&fromResizeMode!=null&&
1122
- setValueByPath(parentObject,["parameters","resizeMode"],fromResizeMode),toObject}function generateVideosOperationFromMldev(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);
1123
- let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response","generateVideoResponse"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromMldev(fromResponse)),toObject}function generateVideosOperationFromVertex(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);
1124
- let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromVertex(
1125
- fromResponse)),toObject}function generateVideosParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToMldev(
1126
- fromImage));let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,["instances[0]","video"],videoToMldev(fromVideo));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&generateVideosSourceToMldev(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateVideosConfigToMldev(fromConfig,toObject),toObject}function generateVideosParametersToVertex(apiClient,fromObject,rootObject){let toObject={},
1127
- fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToVertex(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,
1128
- ["instances[0]","video"],videoToVertex(fromVideo));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&generateVideosSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateVideosConfigToVertex(fromConfig,toObject),toObject}function generateVideosResponseFromMldev(fromObject,rootObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["generatedSamples"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;
1038
+ y"],fromOutputCompressionQuality);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromEditMode=getValueByPath(fromObject,["editMode"]);parentObject!==void 0&&fromEditMode!=null&&setValueByPath(parentObject,["par\
1039
+ ameters","editMode"],fromEditMode);let fromBaseSteps=getValueByPath(fromObject,["baseSteps"]);return parentObject!==void 0&&fromBaseSteps!=null&&setValueByPath(parentObject,["parameters","editConfig","baseSteps"],fromBaseSteps),toObject}function editImageParametersInternalToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,
1040
+ ["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>referenceImageAPIInternalToVertex(item))),setValueByPath(toObject,["instances[0]","referenceImages"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&
1041
+ editImageConfigToVertex(fromConfig,toObject),toObject}function editImageResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(
1042
+ item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function embedContentConfigToMldev(fromObject,parentObject,_rootObject){let toObject={},fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["requests[]","taskType"],fromTaskType);let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["requests[]","title"],fromTitle);let fromOutputDimensionality=getValueByPath(
1043
+ fromObject,["outputDimensionality"]);if(parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["requests[]","outputDimensionality"],fromOutputDimensionality),getValueByPath(fromObject,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterpri\
1044
+ se Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function embedContentConfigToVertex(fromObject,parentObject,rootObject){
1045
+ let toObject={},discriminatorTaskType=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorTaskType===void 0&&(discriminatorTaskType="PREDICT"),discriminatorTaskType==="PREDICT"){let fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["instances[]","task_type"],fromTaskType)}else if(discriminatorTaskType==="EMBED_CONTENT"){let fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=
1046
+ null&&setValueByPath(parentObject,["embedContentConfig","taskType"],fromTaskType)}let discriminatorTitle=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorTitle===void 0&&(discriminatorTitle="PREDICT"),discriminatorTitle==="PREDICT"){let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["instances[]","title"],fromTitle)}else if(discriminatorTitle==="EMBED_CONTENT"){let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==
1047
+ void 0&&fromTitle!=null&&setValueByPath(parentObject,["embedContentConfig","title"],fromTitle)}let discriminatorOutputDimensionality=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorOutputDimensionality===void 0&&(discriminatorOutputDimensionality="PREDICT"),discriminatorOutputDimensionality==="PREDICT"){let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["parameters","\
1048
+ outputDimensionality"],fromOutputDimensionality)}else if(discriminatorOutputDimensionality==="EMBED_CONTENT"){let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["embedContentConfig","outputDimensionality"],fromOutputDimensionality)}let discriminatorMimeType=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorMimeType===void 0&&(discriminatorMimeType="PREDICT"),discriminatorMimeType===
1049
+ "PREDICT"){let fromMimeType=getValueByPath(fromObject,["mimeType"]);parentObject!==void 0&&fromMimeType!=null&&setValueByPath(parentObject,["instances[]","mimeType"],fromMimeType)}let discriminatorAutoTruncate=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorAutoTruncate===void 0&&(discriminatorAutoTruncate="PREDICT"),discriminatorAutoTruncate==="PREDICT"){let fromAutoTruncate=getValueByPath(fromObject,["autoTruncate"]);parentObject!==void 0&&fromAutoTruncate!=null&&setValueByPath(
1050
+ parentObject,["parameters","autoTruncate"],fromAutoTruncate)}else if(discriminatorAutoTruncate==="EMBED_CONTENT"){let fromAutoTruncate=getValueByPath(fromObject,["autoTruncate"]);parentObject!==void 0&&fromAutoTruncate!=null&&setValueByPath(parentObject,["embedContentConfig","autoTruncate"],fromAutoTruncate)}let discriminatorDocumentOcr=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorDocumentOcr===void 0&&(discriminatorDocumentOcr="PREDICT"),discriminatorDocumentOcr==="EMBED_CONT\
1051
+ ENT"){let fromDocumentOcr=getValueByPath(fromObject,["documentOcr"]);parentObject!==void 0&&fromDocumentOcr!=null&&setValueByPath(parentObject,["embedContentConfig","documentOcr"],fromDocumentOcr)}let discriminatorAudioTrackExtraction=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorAudioTrackExtraction===void 0&&(discriminatorAudioTrackExtraction="PREDICT"),discriminatorAudioTrackExtraction==="EMBED_CONTENT"){let fromAudioTrackExtraction=getValueByPath(fromObject,["audioTrackExtr\
1052
+ action"]);parentObject!==void 0&&fromAudioTrackExtraction!=null&&setValueByPath(parentObject,["embedContentConfig","audioTrackExtraction"],fromAudioTrackExtraction)}return toObject}function embedContentParametersPrivateToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContentsForEmbed(
1053
+ apiClient,fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["requests[]","content"],transformedList)}let fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&contentToMldev$1(tContent(fromContent));let fromConfig=getValueByPath(fromObject,["config"]);fromConfig!=null&&embedContentConfigToMldev(fromConfig,toObject);let fromModelForEmbedContent=getValueByPath(fromObject,["model"]);return fromModelForEmbedContent!==
1054
+ void 0&&setValueByPath(toObject,["requests[]","model"],tModel(apiClient,fromModelForEmbedContent)),toObject}function embedContentParametersPrivateToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let discriminatorContents=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorContents===void 0&&(discriminatorContents="PREDICT"),discriminatorContents===
1055
+ "PREDICT"){let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContentsForEmbed(apiClient,fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["instances[]","content"],transformedList)}}let discriminatorContent=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorContent===void 0&&(discriminatorContent="PREDICT"),discriminatorContent==="EMBED_CONTENT"){let fromContent=getValueByPath(
1056
+ fromObject,["content"]);fromContent!=null&&setValueByPath(toObject,["content"],contentToVertex$1(tContent(fromContent)))}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&embedContentConfigToVertex(fromConfig,toObject,rootObject),toObject}function embedContentResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);
1057
+ let fromEmbeddings=getValueByPath(fromObject,["embeddings"]);if(fromEmbeddings!=null){let transformedList=fromEmbeddings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["embeddings"],transformedList)}let fromMetadata=getValueByPath(fromObject,["metadata"]);return fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata),toObject}function embedContentResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(
1058
+ fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromEmbeddings=getValueByPath(fromObject,["predictions[]","embeddings"]);if(fromEmbeddings!=null){let transformedList=fromEmbeddings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentEmbeddingFromVertex(item))),setValueByPath(toObject,["embeddings"],transformedList)}let fromMetadata=getValueByPath(fromObject,["metadata"]);if(fromMetadata!=
1059
+ null&&setValueByPath(toObject,["metadata"],fromMetadata),rootObject&&getValueByPath(rootObject,["embeddingApiType"])==="EMBED_CONTENT"){let embedding=getValueByPath(fromObject,["embedding"]),usageMetadata=getValueByPath(fromObject,["usageMetadata"]),truncated=getValueByPath(fromObject,["truncated"]);if(embedding){let stats={};usageMetadata&&usageMetadata.promptTokenCount&&(stats.tokenCount=usageMetadata.promptTokenCount),usageMetadata&&usageMetadata.promptTokensDetails&&(stats.tokensDetails=usageMetadata.
1060
+ promptTokensDetails),truncated&&(stats.truncated=truncated),embedding.statistics=stats,setValueByPath(toObject,["embeddings"],[embedding])}}return toObject}function endpointFromVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["endpoint"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDeployedModelId=getValueByPath(fromObject,["deployedModelId"]);return fromDeployedModelId!=null&&setValueByPath(toObject,["deployedModelId"],fromDeployedModelId),
1061
+ toObject}function functionCallToMldev$1(fromObject,_rootObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supporte\
1062
+ d in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function functionCallingConfigToMldev(fromObject,_rootObject){let toObject={},fromAllowedFunctionNames=getValueByPath(fromObject,["allowedFunctionNames"]);fromAllowedFunctionNames!=null&&setValueByPath(toObject,[
1063
+ "allowedFunctionNames"],fromAllowedFunctionNames);let fromMode=getValueByPath(fromObject,["mode"]);if(fromMode!=null&&setValueByPath(toObject,["mode"],fromMode),getValueByPath(fromObject,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateContentConfigToMldev(apiClient,fromObject,parentObject,rootObject){let toObject={},fromServiceTier=getValueByPath(
1064
+ fromObject,["serviceTier"]);parentObject!==void 0&&fromServiceTier!=null&&setValueByPath(parentObject,["serviceTier"],fromServiceTier);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToMldev$1(tContent(fromSystemInstruction)));let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);
1065
+ let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["ma\
1066
+ xOutputTokens"],fromMaxOutputTokens);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromPresencePenalty=getValueByPath(
1067
+ fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&
1068
+ setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],tSchema(fromResponseSchema));let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);if(fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema),getValueByPath(fromObject,["routingConfig"])!==void 0)throw new Error("routingConfig \
1069
+ parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&
1070
+ (transformedList=transformedList.map(item=>safetySettingToMldev$1(item))),setValueByPath(parentObject,["safetySettings"],transformedList)}let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$1(tTool(item)))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);parentObject!==
1071
+ void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToMldev(fromToolConfig));let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromCachedContent=getValueByPath(fromObject,["cachedContent"]);parentObject!==void 0&&fromCachedContent!=null&&setValueByPath(parentObject,["cachedContent"],tCachedContentName(apiClient,fromCachedContent));let fromResponseModalities=getValueByPath(
1072
+ fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);if(fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],tSpeechConfig(fromSpeechConfig)),getValueByPath(fromObject,["audioTi\
1073
+ mestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);
1074
+ let fromImageConfig=getValueByPath(fromObject,["imageConfig"]);fromImageConfig!=null&&setValueByPath(toObject,["imageConfig"],imageConfigToMldev(fromImageConfig));let fromEnableEnhancedCivicAnswers=getValueByPath(fromObject,["enableEnhancedCivicAnswers"]);if(fromEnableEnhancedCivicAnswers!=null&&setValueByPath(toObject,["enableEnhancedCivicAnswers"],fromEnableEnhancedCivicAnswers),getValueByPath(fromObject,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only support\
1075
+ ed in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromContinuationToken=getValueByPath(fromObject,["continuationToken"]);return parentObject!==void 0&&fromContinuationToken!=null&&setValueByPath(parentObject,["continuationToken"],fromContinuationToken),toObject}function generateContentConfigToVertex(apiClient,fromObject,parentObject,rootObject){let toObject={},fromServiceTier=getValueByPath(fromObject,["serviceTier"]);parentObject!==void 0&&fromServiceTier!=null&&
1076
+ setValueByPath(parentObject,["serviceTier"],fromServiceTier);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$1(tContent(fromSystemInstruction)));let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(
1077
+ toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromStopSequences=getValueByPath(fromObject,
1078
+ ["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(
1079
+ toObject,["presencePenalty"],fromPresencePenalty);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseSchema=getValueByPath(
1080
+ fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],tSchema(fromResponseSchema));let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromModelSelectionConfig=getValueByPath(
1081
+ fromObject,["modelSelectionConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelConfig"],fromModelSelectionConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(parentObject,["safetySettings"],transformedList)}let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==
1082
+ void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex$1(tTool(item)))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToVertex(fromToolConfig));let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&
1083
+ setValueByPath(parentObject,["labels"],fromLabels);let fromCachedContent=getValueByPath(fromObject,["cachedContent"]);parentObject!==void 0&&fromCachedContent!=null&&setValueByPath(parentObject,["cachedContent"],tCachedContentName(apiClient,fromCachedContent));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromMediaResolution=getValueByPath(fromObject,["mediaReso\
1084
+ lution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],speechConfigToVertex(tSpeechConfig(fromSpeechConfig)));let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromThinkingConfig=getValueByPath(fromObject,["thin\
1085
+ kingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromImageConfig=getValueByPath(fromObject,["imageConfig"]);if(fromImageConfig!=null&&setValueByPath(toObject,["imageConfig"],imageConfigToVertex(fromImageConfig)),getValueByPath(fromObject,
1086
+ ["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromModelArmorConfig=getValueByPath(fromObject,["modelArmorConfig"]);parentObject!==void 0&&fromModelArmorConfig!=null&&setValueByPath(parentObject,["modelArmorConfig"],fromModelArmorConfig);let fromContinuationToken=getValueByPath(fromObject,["continuationToken"]);return parentObject!==void 0&&fromContinuationToken!=
1087
+ null&&setValueByPath(parentObject,["continuationToken"],fromContinuationToken),toObject}function generateContentParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.
1088
+ map(item=>contentToMldev$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["generationConfig"],generateContentConfigToMldev(apiClient,fromConfig,toObject)),toObject}function generateContentParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));
1089
+ let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["generationConfig"],generateContentConfigToVertex(apiClient,fromConfig,toObject)),toObject}function generateContentResponseFromMldev(fromObject,rootObject){
1090
+ let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromCandidates=getValueByPath(fromObject,["candidates"]);if(fromCandidates!=null){let transformedList=fromCandidates;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>candidateFromMldev(item))),setValueByPath(toObject,["candidates"],transformedList)}let fromModelVersion=getValueByPath(fromObject,
1091
+ ["modelVersion"]);fromModelVersion!=null&&setValueByPath(toObject,["modelVersion"],fromModelVersion);let fromPromptFeedback=getValueByPath(fromObject,["promptFeedback"]);fromPromptFeedback!=null&&setValueByPath(toObject,["promptFeedback"],fromPromptFeedback);let fromResponseId=getValueByPath(fromObject,["responseId"]);fromResponseId!=null&&setValueByPath(toObject,["responseId"],fromResponseId);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);fromUsageMetadata!=null&&setValueByPath(
1092
+ toObject,["usageMetadata"],fromUsageMetadata);let fromModelStatus=getValueByPath(fromObject,["modelStatus"]);return fromModelStatus!=null&&setValueByPath(toObject,["modelStatus"],fromModelStatus),toObject}function generateContentResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromCandidates=getValueByPath(fromObject,["candid\
1093
+ ates"]);if(fromCandidates!=null){let transformedList=fromCandidates;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["candidates"],transformedList)}let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromModelVersion=getValueByPath(fromObject,["modelVersion"]);fromModelVersion!=null&&setValueByPath(toObject,["modelVersion"],fromModelVersion);let fromPromptFeedback=getValueByPath(
1094
+ fromObject,["promptFeedback"]);fromPromptFeedback!=null&&setValueByPath(toObject,["promptFeedback"],fromPromptFeedback);let fromResponseId=getValueByPath(fromObject,["responseId"]);fromResponseId!=null&&setValueByPath(toObject,["responseId"],fromResponseId);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);return fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],fromUsageMetadata),toObject}function generateImagesConfigToVertex(fromObject,parentObject,_rootObject){
1095
+ let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=
1096
+ null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromGuidanceScale=getValueByPath(fromObject,["guidanceScale"]);parentObject!==void 0&&fromGuidanceScale!=null&&setValueByPath(parentObject,["parameters","guidanceScale"],fromGuidanceScale);let fromSeed=getValueByPath(fromObject,["\
1097
+ seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],
1098
+ fromPersonGeneration);let fromIncludeSafetyAttributes=getValueByPath(fromObject,["includeSafetyAttributes"]);parentObject!==void 0&&fromIncludeSafetyAttributes!=null&&setValueByPath(parentObject,["parameters","includeSafetyAttributes"],fromIncludeSafetyAttributes);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromLanguage=getValueByPath(
1099
+ fromObject,["language"]);parentObject!==void 0&&fromLanguage!=null&&setValueByPath(parentObject,["parameters","language"],fromLanguage);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(
1100
+ parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromImageSize=getValueByPath(fromObject,["imageSize"]);parentObject!==
1101
+ void 0&&fromImageSize!=null&&setValueByPath(parentObject,["parameters","sampleImageSize"],fromImageSize);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);return parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt),toObject}function generateImagesParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url",
1102
+ "model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateImagesConfigToVertex(fromConfig,toObject),toObject}function generateImagesResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,
1103
+ ["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}let fromPositivePromptSafetyAttributes=getValueByPath(fromObject,["positivePromptSafetyAttributes"]);return fromPositivePromptSafetyAttributes!=null&&setValueByPath(
1104
+ toObject,["positivePromptSafetyAttributes"],safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)),toObject}function generateVideosConfigToMldev(fromObject,parentObject,rootObject){let toObject={},fromNumberOfVideos=getValueByPath(fromObject,["numberOfVideos"]);if(parentObject!==void 0&&fromNumberOfVideos!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfVideos),getValueByPath(fromObject,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only\
1105
+ supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["fps"])!==void 0)throw new Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromDurationSeconds=getValueByPath(fromObject,["durationSeconds"]);if(parentObject!==void 0&&fromDurationSeconds!=null&&setValueByPath(parentObject,["parameters","durationSeconds"],fromDurationSeconds),getValueByPath(fromObject,["see\
1106
+ d"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromResolution=getValueByPath(fromObject,["resolution"]);parentObject!==void 0&&fromResolution!=null&&setValueByPath(parentObject,["parameters","resolution"],fromResolution);
1107
+ let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);if(parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration),getValueByPath(fromObject,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=
1108
+ null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);if(parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt),getValueByPath(fromObject,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromLastFrame=getValueByPath(
1109
+ fromObject,["lastFrame"]);parentObject!==void 0&&fromLastFrame!=null&&setValueByPath(parentObject,["instances[0]","lastFrame"],imageToMldev(fromLastFrame));let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(parentObject!==void 0&&fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>videoGenerationReferenceImageToMldev(item))),setValueByPath(parentObject,["instances[0]","referenceImages"],
1110
+ transformedList)}if(getValueByPath(fromObject,["mask"])!==void 0)throw new Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported i\
1111
+ n Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromWebhookConfig=getValueByPath(fromObject,["webhookConfig"]);if(parentObject!==void 0&&fromWebhookConfig!=null&&setValueByPath(parentObject,["webhookConfig"],fromWebhookConfig),getValueByPath(fromObject,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateVideosConfigToVertex(fromObject,parentObject,rootObject){
1112
+ let toObject={},fromNumberOfVideos=getValueByPath(fromObject,["numberOfVideos"]);parentObject!==void 0&&fromNumberOfVideos!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfVideos);let fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromFps=getValueByPath(fromObject,["fps"]);parentObject!==void 0&&fromFps!=null&&setValueByPath(parentObject,
1113
+ ["parameters","fps"],fromFps);let fromDurationSeconds=getValueByPath(fromObject,["durationSeconds"]);parentObject!==void 0&&fromDurationSeconds!=null&&setValueByPath(parentObject,["parameters","durationSeconds"],fromDurationSeconds);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(
1114
+ parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromResolution=getValueByPath(fromObject,["resolution"]);parentObject!==void 0&&fromResolution!=null&&setValueByPath(parentObject,["parameters","resolution"],fromResolution);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromPubsubTopic=getValueByPath(fromObject,["pubsubT\
1115
+ opic"]);parentObject!==void 0&&fromPubsubTopic!=null&&setValueByPath(parentObject,["parameters","pubsubTopic"],fromPubsubTopic);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],
1116
+ fromEnhancePrompt);let fromGenerateAudio=getValueByPath(fromObject,["generateAudio"]);parentObject!==void 0&&fromGenerateAudio!=null&&setValueByPath(parentObject,["parameters","generateAudio"],fromGenerateAudio);let fromLastFrame=getValueByPath(fromObject,["lastFrame"]);parentObject!==void 0&&fromLastFrame!=null&&setValueByPath(parentObject,["instances[0]","lastFrame"],imageToVertex(fromLastFrame));let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(parentObject!==void 0&&fromReferenceImages!=
1117
+ null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>videoGenerationReferenceImageToVertex(item))),setValueByPath(parentObject,["instances[0]","referenceImages"],transformedList)}let fromMask=getValueByPath(fromObject,["mask"]);parentObject!==void 0&&fromMask!=null&&setValueByPath(parentObject,["instances[0]","mask"],videoGenerationMaskToVertex(fromMask));let fromCompressionQuality=getValueByPath(fromObject,["compressionQuality"]);
1118
+ parentObject!==void 0&&fromCompressionQuality!=null&&setValueByPath(parentObject,["parameters","compressionQuality"],fromCompressionQuality);let fromLabels=getValueByPath(fromObject,["labels"]);if(parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),getValueByPath(fromObject,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromResizeMode=getValueByPath(
1119
+ fromObject,["resizeMode"]);return parentObject!==void 0&&fromResizeMode!=null&&setValueByPath(parentObject,["parameters","resizeMode"],fromResizeMode),toObject}function generateVideosOperationFromMldev(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(
1120
+ fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response","generateVideoResponse"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromMldev(fromResponse)),toObject}function generateVideosOperationFromVertex(fromObject,rootObject){let toObject={},fromName=getValueByPath(
1121
+ fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=
1122
+ null&&setValueByPath(toObject,["response"],generateVideosResponseFromVertex(fromResponse)),toObject}function generateVideosParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["i\
1123
+ mage"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToMldev(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,["instances[0]","video"],videoToMldev(fromVideo));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&generateVideosSourceToMldev(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateVideosConfigToMldev(fromConfig,toObject),toObject}function generateVideosParametersToVertex(apiClient,fromObject,rootObject){
1124
+ let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToVertex(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(
1125
+ toObject,["instances[0]","video"],videoToVertex(fromVideo));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&generateVideosSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateVideosConfigToVertex(fromConfig,toObject),toObject}function generateVideosResponseFromMldev(fromObject,rootObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["generatedSamples"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;
1129
1126
  Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromMldev(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(
1130
1127
  toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["videos"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromVertex(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,
1131
1128
  ["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosSourceToMldev(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==
@@ -1213,12 +1210,12 @@ t in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!
1213
1210
  nDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev$1(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter\
1214
1211
  is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function toolToVertex$1(fromObject,rootObject){let toObject={},fromRetrieval=getValueByPath(fromObject,["retrie\
1215
1212
  val"]);fromRetrieval!=null&&setValueByPath(toObject,["retrieval"],fromRetrieval);let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],fromGoogleMaps);let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>mcpServerToVertex$1(item))),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(
1216
- fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],computerUseToVertex$1(fromComputerUse));let fromEnterpriseWebSearch=getValueByPath(fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(
1217
- fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=
1218
- null&&setValueByPath(toObject,["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(fromObject,["parallelAiSearch"]);fromParallelAiSearch!=null&&setValueByPath(toObject,["parallelAiSearch"],fromParallelAiSearch);let fromUrlContext=getValueByPath(fromObject,["urlContext"]);if(fromUrlContext!=
1219
- null&&setValueByPath(toObject,["urlContext"],fromUrlContext),getValueByPath(fromObject,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function tunedModelInfoFromMldev(fromObject,_rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromCreateTime=getValueByPath(fromObject,
1220
- ["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);return fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime),toObject}function tunedModelInfoFromVertex(fromObject,_rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["labels","google-vertex-llm-tuning-base-model-id"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromCreateTime=getValueByPath(
1221
- fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);return fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime),toObject}function updateModelConfigToMldev(fromObject,parentObject,_rootObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);
1213
+ fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse);let fromEnterpriseWebSearch=getValueByPath(fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(fromObject,["exaAiSearc\
1214
+ h"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,
1215
+ ["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(fromObject,["parallelAiSearch"]);fromParallelAiSearch!=null&&setValueByPath(toObject,["parallelAiSearch"],fromParallelAiSearch);let fromUrlContext=getValueByPath(fromObject,["urlContext"]);if(fromUrlContext!=null&&setValueByPath(toObject,
1216
+ ["urlContext"],fromUrlContext),getValueByPath(fromObject,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function tunedModelInfoFromMldev(fromObject,_rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=
1217
+ null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);return fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime),toObject}function tunedModelInfoFromVertex(fromObject,_rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["labels","google-vertex-llm-tuning-base-model-id"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromCreateTime=getValueByPath(fromObject,
1218
+ ["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);return fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime),toObject}function updateModelConfigToMldev(fromObject,parentObject,_rootObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);
1222
1219
  let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);return parentObject!==void 0&&fromDefaultCheckpointId!=null&&setValueByPath(parentObject,["defaultCheckpointId"],fromDefaultCheckpointId),toObject}function updateModelConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromDisplayName=getValueByPath(
1223
1220
  fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);return parentObject!==void 0&&fromDefaultCheckpointId!=null&&setValueByPath(parentObject,["defaultCheckpointId"],fromDefaultCheckpointId),
1224
1221
  toObject}function updateModelParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateModelConfigToMldev(fromConfig,toObject),toObject}function updateModelParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=
@@ -1249,24 +1246,25 @@ null&&listFileSearchStoresConfigToMldev(fromConfig,toObject),toObject}function l
1249
1246
  ["fileSearchStores"]);if(fromFileSearchStores!=null){let transformedList=fromFileSearchStores;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["fileSearchStores"],transformedList)}return toObject}function uploadToFileSearchStoreConfigToMldev(fromObject,parentObject){let toObject={},fromMimeType=getValueByPath(fromObject,["mimeType"]);parentObject!==void 0&&fromMimeType!=null&&setValueByPath(parentObject,["mimeType"],fromMimeType);let fromDisplayName=getValueByPath(
1250
1247
  fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromCustomMetadata=getValueByPath(fromObject,["customMetadata"]);if(parentObject!==void 0&&fromCustomMetadata!=null){let transformedList=fromCustomMetadata;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(parentObject,["customMetadata"],transformedList)}let fromChunkingConfig=getValueByPath(fromObject,["chunking\
1251
1248
  Config"]);return parentObject!==void 0&&fromChunkingConfig!=null&&setValueByPath(parentObject,["chunkingConfig"],fromChunkingConfig),toObject}function uploadToFileSearchStoreParametersToMldev(fromObject){let toObject={},fromFileSearchStoreName=getValueByPath(fromObject,["fileSearchStoreName"]);fromFileSearchStoreName!=null&&setValueByPath(toObject,["_url","file_search_store_name"],fromFileSearchStoreName);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&uploadToFileSearchStoreConfigToMldev(
1252
- fromConfig,toObject),toObject}function uploadToFileSearchStoreResumableResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}var CONTENT_TYPE_HEADER="Content-Type",SERVER_TIMEOUT_HEADER="X-Server-Timeout",USER_AGENT_HEADER="User-Agent",GOOGLE_API_CLIENT_HEADER="x-goog-api-client",SDK_VERSION="2.27.0",LIBRARY_LABEL=`google-genai-sdk\
1253
- /${SDK_VERSION}`,VERTEX_AI_API_DEFAULT_VERSION="v1beta1",GOOGLE_AI_API_DEFAULT_VERSION="v1beta",MULTI_REGIONAL_LOCATIONS=new Set(["us","eu"]);function raiseUndiciTimeouts(timeout){let globalDispatcher=globalThis[Symbol.for("undici.globalDispatcher.1")];if(globalDispatcher)for(let sym of Object.getOwnPropertySymbols(globalDispatcher)){let desc=sym.description;if(desc?.includes("headers timeout")||desc?.includes("body timeout")){let currentTimeout=globalDispatcher[sym];typeof currentTimeout=="numb\
1254
- er"&&(globalDispatcher[sym]=Math.max(currentTimeout,timeout))}}}function createAttemptSignal(timeout,callerSignal){let noop=()=>{};if(!(timeout&&timeout>0)&&!callerSignal)return{signal:void 0,dispose:noop};let controller=new AbortController,timeoutHandle;timeout&&timeout>0&&(timeoutHandle=setTimeout(()=>controller.abort(),timeout),timeoutHandle&&typeof timeoutHandle.unref=="function"&&timeoutHandle.unref());let onCallerAbort=()=>controller.abort();return callerSignal&&(callerSignal.aborted?controller.
1255
- abort():callerSignal.addEventListener("abort",onCallerAbort)),{signal:controller.signal,dispose:()=>{timeoutHandle!==void 0&&clearTimeout(timeoutHandle),callerSignal?.removeEventListener("abort",onCallerAbort)}}}var DEFAULT_RETRY_ATTEMPTS=5,DEFAULT_RETRY_INITIAL_DELAY=1,DEFAULT_RETRY_MAX_DELAY=60,DEFAULT_RETRY_EXP_BASE=2,DEFAULT_RETRY_JITTER=1,DEFAULT_RETRY_HTTP_STATUS_CODES=[408,429,500,502,503,504],ApiClient=class{constructor(opts){var _a2,_b,_c;this.clientOptions=Object.assign({},opts),this.customBaseUrl=
1256
- (_a2=opts.httpOptions)===null||_a2===void 0?void 0:_a2.baseUrl;let initHttpOptions={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");let hasConstructorAuth=opts.
1257
- project&&opts.location||!!opts.apiKey;this.customBaseUrl&&!hasConstructorAuth?(initHttpOptions.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||this.clientOptions.location==="global"?initHttpOptions.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&MULTI_REGIONAL_LOCATIONS.has(this.clientOptions.location)?initHttpOptions.baseUrl=`https://aipl\
1258
- atform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(initHttpOptions.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),initHttpOptions.apiVersion=(_b=this.clientOptions.apiVersion)!==null&&_b!==void 0?_b:VERTEX_AI_API_DEFAULT_VERSION}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),initHttpOptions.apiVersion=(_c=this.clientOptions.apiVersion)!==null&&_c!==void 0?
1259
- _c:GOOGLE_AI_API_DEFAULT_VERSION,initHttpOptions.baseUrl="https://generativelanguage.googleapis.com/";initHttpOptions.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=initHttpOptions,opts.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(initHttpOptions,opts.httpOptions))}isVertexAI(){var _a2;return(_a2=this.clientOptions.vertexai)!==null&&_a2!==void 0?_a2:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){
1260
- return this.customBaseUrl}async getAuthHeaders(){let headers=new Headers;return await this.clientOptions.auth.addAuthHeaders(headers),headers}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base \
1261
- URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getFetch(){var _a2;return(_a2=this.clientOptions.httpOptions)===null||_a2===void 0?void 0:_a2.fetch}getRequestUrlInternal(httpOptions){if(!httpOptions||httpOptions.baseUrl===void 0||httpOptions.apiVersion===void 0)throw new Error(
1262
- "HTTP options are not correctly set.");let urlElement=[httpOptions.baseUrl.endsWith("/")?httpOptions.baseUrl.slice(0,-1):httpOptions.baseUrl];return httpOptions.apiVersion&&httpOptions.apiVersion!==""&&urlElement.push(httpOptions.apiVersion),urlElement.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let baseUrl=this.getBaseUrl(),urlParts=new URL(baseUrl);return urlParts.
1263
- protocol=urlParts.protocol=="http:"?"ws":"wss",urlParts.toString()}setBaseUrl(url){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=url;else throw new Error("HTTP options are not correctly set.")}constructUrl(path2,httpOptions,prependProjectLocation){let urlElement=[this.getRequestUrlInternal(httpOptions)];return prependProjectLocation&&urlElement.push(this.getBaseResourcePath()),path2!==""&&urlElement.push(path2),new URL(`${urlElement.join("/")}`)}shouldPrependVertexProjectPath(request,httpOptions){
1264
- return!(httpOptions.baseUrl&&httpOptions.baseUrlResourceScope===ResourceScope.COLLECTION||!this.clientOptions.vertexai||!this.clientOptions.project||!this.clientOptions.location||request.path.startsWith("projects/")||request.httpMethod==="GET"&&request.path.startsWith("publishers/google/models"))}async request(request){let patchedHttpOptions=this.clientOptions.httpOptions;request.httpOptions&&(patchedHttpOptions=this.patchHttpOptions(this.clientOptions.httpOptions,request.httpOptions));let prependProjectLocation=this.
1265
- shouldPrependVertexProjectPath(request,patchedHttpOptions),url=this.constructUrl(request.path,patchedHttpOptions,prependProjectLocation);if(request.queryParams)for(let[key,value]of Object.entries(request.queryParams))url.searchParams.append(key,String(value));let requestInit={};if(request.httpMethod==="GET"){if(request.body&&request.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else requestInit.body=request.body;return requestInit=await this.
1266
- includeExtraHttpOptionsToRequestInit(requestInit,patchedHttpOptions,url.toString()),this.unaryApiCall(url,requestInit,request.httpMethod,patchedHttpOptions.retryOptions,patchedHttpOptions.timeout,request.abortSignal,patchedHttpOptions.fetch)}patchHttpOptions(baseHttpOptions,requestHttpOptions){let patchedHttpOptions=JSON.parse(JSON.stringify(baseHttpOptions));baseHttpOptions.fetch&&(patchedHttpOptions.fetch=baseHttpOptions.fetch);for(let[key,value]of Object.entries(requestHttpOptions))typeof value==
1267
- "object"?patchedHttpOptions[key]=Object.assign(Object.assign({},patchedHttpOptions[key]),value):value!==void 0&&(patchedHttpOptions[key]=value);return patchedHttpOptions}async requestStream(request){let patchedHttpOptions=this.clientOptions.httpOptions;request.httpOptions&&(patchedHttpOptions=this.patchHttpOptions(this.clientOptions.httpOptions,request.httpOptions));let prependProjectLocation=this.shouldPrependVertexProjectPath(request,patchedHttpOptions),url=this.constructUrl(request.path,patchedHttpOptions,
1268
- prependProjectLocation);(!url.searchParams.has("alt")||url.searchParams.get("alt")!=="sse")&&url.searchParams.set("alt","sse");let requestInit={};return requestInit.body=request.body,requestInit=await this.includeExtraHttpOptionsToRequestInit(requestInit,patchedHttpOptions,url.toString()),this.streamApiCall(url,requestInit,request.httpMethod,patchedHttpOptions.retryOptions,patchedHttpOptions.timeout,request.abortSignal,patchedHttpOptions.fetch)}async includeExtraHttpOptionsToRequestInit(requestInit,httpOptions,url){
1269
- return httpOptions?.timeout&&httpOptions.timeout>0&&raiseUndiciTimeouts(httpOptions.timeout),httpOptions&&httpOptions.extraBody!==null&&includeExtraBodyToRequestInit(requestInit,httpOptions.extraBody),requestInit.headers=await this.getHeadersInternal(httpOptions,url),requestInit}async unaryApiCall(url,requestInit,httpMethod,retryOptions,timeout,abortSignal,fetchFn){return this.apiCall(url.toString(),Object.assign(Object.assign({},requestInit),{method:httpMethod}),retryOptions,timeout,abortSignal,
1249
+ fromConfig,toObject),toObject}function uploadToFileSearchStoreResumableResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}var CONTENT_TYPE_HEADER="Content-Type",SERVER_TIMEOUT_HEADER="X-Server-Timeout",USER_AGENT_HEADER="User-Agent",GOOGLE_API_CLIENT_HEADER="x-goog-api-client",SDK_VERSION="2.29.0",LIBRARY_LABEL=`google-genai-sdk\
1250
+ /${SDK_VERSION}`,VERTEX_AI_API_DEFAULT_VERSION="v1beta1",GOOGLE_AI_API_DEFAULT_VERSION="v1beta",MULTI_REGIONAL_LOCATIONS=new Set(["us","eu"]),UNDICI_GLOBAL_DISPATCHER_SYMBOL$1=Symbol.for("undici.globalDispatcher.1");function isNodeRuntime$1(){var _a2,_b;return typeof((_b=(_a2=globalThis.process)===null||_a2===void 0?void 0:_a2.versions)===null||_b===void 0?void 0:_b.node)=="string"}function createUndiciNoTimeoutDispatcher$1(){return{dispatch(opts,handler){let globalDispatcher=globalThis[UNDICI_GLOBAL_DISPATCHER_SYMBOL$1];
1251
+ if(!globalDispatcher&&typeof Headers<"u"&&(new Headers,globalDispatcher=globalThis[UNDICI_GLOBAL_DISPATCHER_SYMBOL$1]),!globalDispatcher||typeof globalDispatcher.dispatch!="function")throw new Error("Undici globalDispatcher is not available.");return globalDispatcher.dispatch(Object.assign(Object.assign({},opts),{headersTimeout:0,bodyTimeout:0}),handler)}}}function createAttemptSignal(timeout,callerSignal){let noop=()=>{};if(!(timeout&&timeout>0)&&!callerSignal)return{signal:void 0,dispose:noop};
1252
+ let controller=new AbortController,timeoutHandle;timeout&&timeout>0&&(timeoutHandle=setTimeout(()=>controller.abort(),timeout),timeoutHandle&&typeof timeoutHandle.unref=="function"&&timeoutHandle.unref());let onCallerAbort=()=>controller.abort();return callerSignal&&(callerSignal.aborted?controller.abort():callerSignal.addEventListener("abort",onCallerAbort)),{signal:controller.signal,dispose:()=>{timeoutHandle!==void 0&&clearTimeout(timeoutHandle),callerSignal?.removeEventListener("abort",onCallerAbort)}}}
1253
+ var DEFAULT_RETRY_ATTEMPTS=5,DEFAULT_RETRY_INITIAL_DELAY=1,DEFAULT_RETRY_MAX_DELAY=60,DEFAULT_RETRY_EXP_BASE=2,DEFAULT_RETRY_JITTER=1,DEFAULT_RETRY_HTTP_STATUS_CODES=[408,429,500,502,503,504],ApiClient=class{constructor(opts){var _a2,_b,_c;this.clientOptions=Object.assign({},opts),this.customBaseUrl=(_a2=opts.httpOptions)===null||_a2===void 0?void 0:_a2.baseUrl;let initHttpOptions={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&
1254
+ (this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");let hasConstructorAuth=opts.project&&opts.location||!!opts.apiKey;this.customBaseUrl&&!hasConstructorAuth?(initHttpOptions.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.
1255
+ clientOptions.apiKey&&!this.clientOptions.project||this.clientOptions.location==="global"?initHttpOptions.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&MULTI_REGIONAL_LOCATIONS.has(this.clientOptions.location)?initHttpOptions.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(initHttpOptions.baseUrl=`https://${this.clientOptions.location}-aiplatform.googl\
1256
+ eapis.com/`),initHttpOptions.apiVersion=(_b=this.clientOptions.apiVersion)!==null&&_b!==void 0?_b:VERTEX_AI_API_DEFAULT_VERSION}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),initHttpOptions.apiVersion=(_c=this.clientOptions.apiVersion)!==null&&_c!==void 0?_c:GOOGLE_AI_API_DEFAULT_VERSION,initHttpOptions.baseUrl="https://generativelanguage.googleapis.com/";initHttpOptions.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=initHttpOptions,
1257
+ opts.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(initHttpOptions,opts.httpOptions))}isVertexAI(){var _a2;return(_a2=this.clientOptions.vertexai)!==null&&_a2!==void 0?_a2:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){let headers=new Headers;return await this.clientOptions.auth.addAuthHeaders(headers),headers}getApiVersion(){if(this.clientOptions.httpOptions&&
1258
+ this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)
1259
+ return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getFetch(){var _a2;return(_a2=this.clientOptions.httpOptions)===null||_a2===void 0?void 0:_a2.fetch}getTimeout(){var _a2;return(_a2=this.clientOptions.httpOptions)===null||_a2===void 0?void 0:_a2.timeout}getRequestUrlInternal(httpOptions){if(!httpOptions||httpOptions.baseUrl===void 0||httpOptions.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");let urlElement=[httpOptions.baseUrl.endsWith(
1260
+ "/")?httpOptions.baseUrl.slice(0,-1):httpOptions.baseUrl];return httpOptions.apiVersion&&httpOptions.apiVersion!==""&&urlElement.push(httpOptions.apiVersion),urlElement.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let baseUrl=this.getBaseUrl(),urlParts=new URL(baseUrl);return urlParts.protocol=urlParts.protocol=="http:"?"ws":"wss",urlParts.toString()}setBaseUrl(url){
1261
+ if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=url;else throw new Error("HTTP options are not correctly set.")}constructUrl(path2,httpOptions,prependProjectLocation){let urlElement=[this.getRequestUrlInternal(httpOptions)];return prependProjectLocation&&urlElement.push(this.getBaseResourcePath()),path2!==""&&urlElement.push(path2),new URL(`${urlElement.join("/")}`)}shouldPrependVertexProjectPath(request,httpOptions){return!(httpOptions.baseUrl&&httpOptions.baseUrlResourceScope===
1262
+ ResourceScope.COLLECTION||!this.clientOptions.vertexai||!this.clientOptions.project||!this.clientOptions.location||request.path.startsWith("projects/")||request.httpMethod==="GET"&&request.path.startsWith("publishers/google/models"))}async request(request){let patchedHttpOptions=this.clientOptions.httpOptions;request.httpOptions&&(patchedHttpOptions=this.patchHttpOptions(this.clientOptions.httpOptions,request.httpOptions));let prependProjectLocation=this.shouldPrependVertexProjectPath(request,patchedHttpOptions),
1263
+ url=this.constructUrl(request.path,patchedHttpOptions,prependProjectLocation);if(request.queryParams)for(let[key,value]of Object.entries(request.queryParams))url.searchParams.append(key,String(value));let requestInit={};if(request.httpMethod==="GET"){if(request.body&&request.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else requestInit.body=request.body;return requestInit=await this.includeExtraHttpOptionsToRequestInit(requestInit,patchedHttpOptions,
1264
+ url.toString()),this.unaryApiCall(url,requestInit,request.httpMethod,patchedHttpOptions.retryOptions,patchedHttpOptions.timeout,request.abortSignal,patchedHttpOptions.fetch)}patchHttpOptions(baseHttpOptions,requestHttpOptions){let patchedHttpOptions=JSON.parse(JSON.stringify(baseHttpOptions));baseHttpOptions.fetch&&(patchedHttpOptions.fetch=baseHttpOptions.fetch);for(let[key,value]of Object.entries(requestHttpOptions))typeof value=="object"?patchedHttpOptions[key]=Object.assign(Object.assign({},
1265
+ patchedHttpOptions[key]),value):value!==void 0&&(patchedHttpOptions[key]=value);return patchedHttpOptions}async requestStream(request){let patchedHttpOptions=this.clientOptions.httpOptions;request.httpOptions&&(patchedHttpOptions=this.patchHttpOptions(this.clientOptions.httpOptions,request.httpOptions));let prependProjectLocation=this.shouldPrependVertexProjectPath(request,patchedHttpOptions),url=this.constructUrl(request.path,patchedHttpOptions,prependProjectLocation);(!url.searchParams.has("al\
1266
+ t")||url.searchParams.get("alt")!=="sse")&&url.searchParams.set("alt","sse");let requestInit={};return requestInit.body=request.body,requestInit=await this.includeExtraHttpOptionsToRequestInit(requestInit,patchedHttpOptions,url.toString()),this.streamApiCall(url,requestInit,request.httpMethod,patchedHttpOptions.retryOptions,patchedHttpOptions.timeout,request.abortSignal,patchedHttpOptions.fetch)}async includeExtraHttpOptionsToRequestInit(requestInit,httpOptions,url){return isNodeRuntime$1()&&!httpOptions?.
1267
+ fetch&&!("dispatcher"in requestInit)&&(requestInit.dispatcher=createUndiciNoTimeoutDispatcher$1()),httpOptions&&httpOptions.extraBody!==null&&includeExtraBodyToRequestInit(requestInit,httpOptions.extraBody),requestInit.headers=await this.getHeadersInternal(httpOptions,url),requestInit}async unaryApiCall(url,requestInit,httpMethod,retryOptions,timeout,abortSignal,fetchFn){return this.apiCall(url.toString(),Object.assign(Object.assign({},requestInit),{method:httpMethod}),retryOptions,timeout,abortSignal,
1270
1268
  fetchFn).then(async response=>(await throwErrorIfNotOK(response),new HttpResponse(response))).catch(e=>{throw e instanceof Error?e:new Error(`exception ${e} sending request`,{cause:e})})}async streamApiCall(url,requestInit,httpMethod,retryOptions,timeout,abortSignal,fetchFn){return this.apiCall(url.toString(),Object.assign(Object.assign({},requestInit),{method:httpMethod}),retryOptions,timeout,abortSignal,fetchFn).then(async response=>(await throwErrorIfNotOK(response),this.processStreamResponse(
1271
1269
  response))).catch(e=>{throw e instanceof Error?e:new Error(`exception ${e} sending request`,{cause:e})})}processStreamResponse(response){return __asyncGenerator(this,arguments,function*(){var _a2;let reader=(_a2=response?.body)===null||_a2===void 0?void 0:_a2.getReader(),decoder=new TextDecoder("utf-8");if(!reader)throw new Error("Response body is empty");try{let buffer="",dataPrefix="data:",delimiters=[`
1272
1270
 
@@ -1316,206 +1314,228 @@ this.apiClient,params);this.conn.send(JSON.stringify(clientMessage))}sendRealtim
1316
1314
  this.apiClient,params);this.conn.send(JSON.stringify(clientMessage))}close(){this.conn.close()}};function headersToMap(headers){let headerMap={};return headers.forEach((value,key)=>{headerMap[key]=value}),headerMap}function mapToHeaders(map){let headers=new Headers;for(let[key,value]of Object.entries(map))headers.append(key,value);return headers}var DEFAULT_MAX_REMOTE_CALLS=10;function shouldDisableAfc(config){var _a2,_b,_c;if(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.disable)
1317
1315
  return!0;let callableToolsPresent=!1;for(let tool of(_b=config?.tools)!==null&&_b!==void 0?_b:[])if(isCallableTool(tool)){callableToolsPresent=!0;break}if(!callableToolsPresent)return!0;let maxCalls=(_c=config?.automaticFunctionCalling)===null||_c===void 0?void 0:_c.maximumRemoteCalls;return maxCalls&&(maxCalls<0||!Number.isInteger(maxCalls))||maxCalls==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a\
1318
1316
  valid integer value greater than 0. maximumRemoteCalls provided:",maxCalls),!0):!1}function isCallableTool(tool){return"callTool"in tool&&typeof tool.callTool=="function"}function hasCallableTools(params){var _a2,_b,_c;return(_c=(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools)===null||_b===void 0?void 0:_b.some(tool=>isCallableTool(tool)))!==null&&_c!==void 0?_c:!1}function findAfcIncompatibleToolIndexes(params){var _a2;let afcIncompatibleToolIndexes=[];return!((_a2=params?.config)===
1319
- null||_a2===void 0)&&_a2.tools&&params.config.tools.forEach((tool,index)=>{if(isCallableTool(tool))return;let geminiTool=tool;geminiTool.functionDeclarations&&geminiTool.functionDeclarations.length>0&&afcIncompatibleToolIndexes.push(index)}),afcIncompatibleToolIndexes}function shouldAppendAfcHistory(config){var _a2;return!(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.ignoreCallHistory)}var Models=class _Models extends BaseModule{constructor(apiClient){super(),this.apiClient=
1320
- apiClient,this.embedContent=async params=>{if(!this.apiClient.isVertexAI())return params.model.includes("gemini-embedding-2")&&(params.contents=tContents(params.contents)),await this.embedContentInternal(params);if(params.model.includes("gemini")&&params.model!=="gemini-embedding-001"||params.model.includes("maas")){let contents=tContents(params.contents);if(contents.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");let paramsPrivate=Object.assign(
1321
- Object.assign({},params),{content:contents[0],embeddingApiType:EmbeddingApiType.EMBED_CONTENT});return await this.embedContentInternal(paramsPrivate)}else{let paramsPrivate=Object.assign(Object.assign({},params),{embeddingApiType:EmbeddingApiType.PREDICT});return await this.embedContentInternal(paramsPrivate)}},this.generateContent=async params=>{var _a2,_b,_c,_d,_e;let transformedParams=await this.processParamsMaybeAddMcpUsage(params);if(this.maybeMoveToResponseJsonSchema(params),!hasCallableTools(
1322
- params)||shouldDisableAfc(params.config))return await this.generateContentInternal(transformedParams);let incompatibleToolIndexes=findAfcIncompatibleToolIndexes(params);if(incompatibleToolIndexes.length>0){let formattedIndexes=incompatibleToolIndexes.map(index=>`tools[${index}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${formattedIndexes}.`)}let response,functionResponseContent,
1323
- automaticFunctionCallingHistory=tContents(transformedParams.contents),maxRemoteCalls=(_c=(_b=(_a2=transformedParams.config)===null||_a2===void 0?void 0:_a2.automaticFunctionCalling)===null||_b===void 0?void 0:_b.maximumRemoteCalls)!==null&&_c!==void 0?_c:DEFAULT_MAX_REMOTE_CALLS,remoteCalls=0;for(;remoteCalls<maxRemoteCalls&&(response=await this.generateContentInternal(transformedParams),!(!response.functionCalls||response.functionCalls.length===0));){let responseContent=response.candidates[0].content,
1324
- functionResponseParts=[];for(let tool of(_e=(_d=params.config)===null||_d===void 0?void 0:_d.tools)!==null&&_e!==void 0?_e:[])if(isCallableTool(tool)){let parts=await tool.callTool(response.functionCalls);functionResponseParts.push(...parts)}remoteCalls++,functionResponseContent={role:"user",parts:functionResponseParts},transformedParams.contents=tContents(transformedParams.contents),transformedParams.contents.push(responseContent),transformedParams.contents.push(functionResponseContent),shouldAppendAfcHistory(
1325
- transformedParams.config)&&(automaticFunctionCallingHistory.push(responseContent),automaticFunctionCallingHistory.push(functionResponseContent))}return shouldAppendAfcHistory(transformedParams.config)&&(response.automaticFunctionCallingHistory=automaticFunctionCallingHistory),response},this.generateContentStream=async params=>{var _a2,_b,_c,_d,_e;if(this.maybeMoveToResponseJsonSchema(params),shouldDisableAfc(params.config)){let transformedParams=await this.processParamsMaybeAddMcpUsage(params);return await this.
1326
- generateContentStreamInternal(transformedParams)}let incompatibleToolIndexes=findAfcIncompatibleToolIndexes(params);if(incompatibleToolIndexes.length>0){let formattedIndexes=incompatibleToolIndexes.map(index=>`tools[${index}]`).join(", ");throw new Error(`Incompatible tools found at ${formattedIndexes}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let streamFunctionCall=(_c=(_b=(_a2=params?.config)===null||_a2===void 0?void 0:
1327
- _a2.toolConfig)===null||_b===void 0?void 0:_b.functionCallingConfig)===null||_c===void 0?void 0:_c.streamFunctionCallArguments,disableAfc=(_e=(_d=params?.config)===null||_d===void 0?void 0:_d.automaticFunctionCalling)===null||_e===void 0?void 0:_e.disable;if(streamFunctionCall&&!disableAfc)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable'\
1328
- to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(params)},this.generateImages=async params=>(_Models.loggedGenerateImagesWarning||(_Models.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateCont\
1329
- ent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images")),await this.generateImagesInternal(params).then(apiResponse=>{var _a2;let positivePromptSafetyAttributes,generatedImages=[];if(apiResponse?.generatedImages)for(let generatedImage of apiResponse.generatedImages)generatedImage&&generatedImage?.safetyAttributes&&((_a2=generatedImage?.
1330
- safetyAttributes)===null||_a2===void 0?void 0:_a2.contentType)==="Positive Prompt"?positivePromptSafetyAttributes=generatedImage?.safetyAttributes:generatedImages.push(generatedImage);let response;return positivePromptSafetyAttributes?response={generatedImages,positivePromptSafetyAttributes,sdkHttpResponse:apiResponse.sdkHttpResponse}:response={generatedImages,sdkHttpResponse:apiResponse.sdkHttpResponse},response})),this.list=async params=>{var _a2;let actualParams={config:Object.assign(Object.assign(
1331
- {},{queryBase:!0}),params?.config)};if(this.apiClient.isVertexAI()&&!actualParams.config.queryBase){if(!((_a2=actualParams.config)===null||_a2===void 0)&&_a2.filter)throw new Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");actualParams.config.filter="labels.tune-type:*"}return new Pager(PagedItem.PAGED_ITEM_MODELS,x=>this.listInternal(x),await this.listInternal(actualParams),actualParams)},this.editImage=async params=>{
1332
- _Models.loggedEditImageWarning||(_Models.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image"));let paramsInternal={model:params.model,prompt:params.prompt,
1333
- referenceImages:[],config:params.config};return params.referenceImages&&params.referenceImages&&(paramsInternal.referenceImages=params.referenceImages.map(img=>img.toReferenceImageAPI())),await this.editImageInternal(paramsInternal)},this.upscaleImage=async params=>{let apiConfig={numberOfImages:1,mode:"upscale"};params.config&&(apiConfig=Object.assign(Object.assign({},apiConfig),params.config));let apiParams={model:params.model,image:params.image,upscaleFactor:params.upscaleFactor,config:apiConfig};
1334
- return await this.upscaleImageInternal(apiParams)},this.generateVideos=async params=>{var _a2,_b,_c,_d,_e,_f;if((params.prompt||params.image||params.video)&&params.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return(params.prompt||params.image||params.video)&&(_Models.loggedGenerateVideosWarning||(_Models.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be rem\
1335
- oved in a future major release (not before 2026-07-31). Please use the source argument instead."))),this.apiClient.isVertexAI()||(!((_a2=params.video)===null||_a2===void 0)&&_a2.uri&&(!((_b=params.video)===null||_b===void 0)&&_b.videoBytes)?params.video={uri:params.video.uri,mimeType:params.video.mimeType}:!((_d=(_c=params.source)===null||_c===void 0?void 0:_c.video)===null||_d===void 0)&&_d.uri&&(!((_f=(_e=params.source)===null||_e===void 0?void 0:_e.video)===null||_f===void 0)&&_f.videoBytes)&&
1336
- (params.source.video={uri:params.source.video.uri,mimeType:params.source.video.mimeType})),await this.generateVideosInternal(params)}}maybeMoveToResponseJsonSchema(params){params.config&&params.config.responseSchema&&(params.config.responseJsonSchema||Object.keys(params.config.responseSchema).includes("$schema")&&(params.config.responseJsonSchema=params.config.responseSchema,delete params.config.responseSchema))}async processParamsMaybeAddMcpUsage(params){var _a2,_b,_c;let tools=(_a2=params.config)===
1337
- null||_a2===void 0?void 0:_a2.tools;if(!tools)return params;let transformedTools=await Promise.all(tools.map(async tool=>isCallableTool(tool)?await tool.tool():tool)),newParams={model:params.model,contents:params.contents,config:Object.assign(Object.assign({},params.config),{tools:transformedTools})};if(newParams.config.tools=transformedTools,params.config&&params.config.tools&&hasMcpToolUsage(params.config.tools)){let headers=(_c=(_b=params.config.httpOptions)===null||_b===void 0?void 0:_b.headers)!==
1338
- null&&_c!==void 0?_c:{},newHeaders=Object.assign({},headers);Object.keys(newHeaders).length===0&&(newHeaders=this.apiClient.getDefaultHeaders()),setMcpUsageHeader(newHeaders),newParams.config.httpOptions=Object.assign(Object.assign({},params.config.httpOptions),{headers:newHeaders})}return newParams}async initAfcToolsMap(params){var _a2,_b,_c;let afcTools=new Map;for(let tool of(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools)!==null&&_b!==void 0?_b:[])if(isCallableTool(tool)){let callableTool=tool,
1339
- toolDeclaration=await callableTool.tool();for(let declaration of(_c=toolDeclaration.functionDeclarations)!==null&&_c!==void 0?_c:[]){if(!declaration.name)throw new Error("Function declaration name is required.");if(afcTools.has(declaration.name))throw new Error(`Duplicate tool declaration name: ${declaration.name}`);afcTools.set(declaration.name,callableTool)}}return afcTools}async processAfcStream(params){var _a2,_b,_c;let maxRemoteCalls=(_c=(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.
1340
- automaticFunctionCalling)===null||_b===void 0?void 0:_b.maximumRemoteCalls)!==null&&_c!==void 0?_c:DEFAULT_MAX_REMOTE_CALLS,wereFunctionsCalled=!1,remoteCallCount=0,afcToolsMap=await this.initAfcToolsMap(params);return(function(models,afcTools,params2){return __asyncGenerator(this,arguments,function*(){for(var _a3,e_1,_b2,_c2,_d,_e;remoteCallCount<maxRemoteCalls;){wereFunctionsCalled&&(remoteCallCount++,wereFunctionsCalled=!1);let transformedParams=yield __await(models.processParamsMaybeAddMcpUsage(
1341
- params2)),response=yield __await(models.generateContentStreamInternal(transformedParams)),functionResponses=[],responseContents=[];try{for(var _f=!0,response_1=(e_1=void 0,__asyncValues(response)),response_1_1;response_1_1=yield __await(response_1.next()),_a3=response_1_1.done,!_a3;_f=!0){_c2=response_1_1.value,_f=!1;let chunk=_c2;if(yield yield __await(chunk),chunk.candidates&&(!((_d=chunk.candidates[0])===null||_d===void 0)&&_d.content)){responseContents.push(chunk.candidates[0].content);for(let part of(_e=
1342
- chunk.candidates[0].content.parts)!==null&&_e!==void 0?_e:[])if(remoteCallCount<maxRemoteCalls&&part.functionCall){if(!part.functionCall.name)throw new Error("Function call name was not returned by the model.");if(afcTools.has(part.functionCall.name)){let responseParts=yield __await(afcTools.get(part.functionCall.name).callTool([part.functionCall]));functionResponses.push(...responseParts)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implem\
1343
- ent the CallableTool interface. Available tools: ${afcTools.keys()}, missing tool: ${part.functionCall.name}`)}}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_f&&!_a3&&(_b2=response_1.return)&&(yield __await(_b2.call(response_1)))}finally{if(e_1)throw e_1.error}}if(functionResponses.length>0){wereFunctionsCalled=!0;let typedResponseChunk=new GenerateContentResponse;typedResponseChunk.candidates=[{content:{role:"user",parts:functionResponses}}],yield yield __await(typedResponseChunk);let newContents=[];
1344
- newContents.push(...responseContents),newContents.push({role:"user",parts:functionResponses});let updatedContents=tContents(params2.contents).concat(newContents);params2.contents=updatedContents}else break}})})(this,afcToolsMap,params)}async generateContentInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:generateContent",body._url),queryParams=body.
1345
- _query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateContentResponseFromVertex(
1346
- apiResponse),typedResp=new GenerateContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=generateContentParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||
1347
- _d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateContentResponseFromMldev(apiResponse),typedResp=new GenerateContentResponse;return Object.assign(typedResp,resp),typedResp})}}async generateContentStreamInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){
1348
- let body=generateContentParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}),response.then(function(apiResponse){return __asyncGenerator(
1349
- this,arguments,function*(){var _a3,e_2,_b2,_c2;try{for(var _d2=!0,apiResponse_1=__asyncValues(apiResponse),apiResponse_1_1;apiResponse_1_1=yield __await(apiResponse_1.next()),_a3=apiResponse_1_1.done,!_a3;_d2=!0){_c2=apiResponse_1_1.value,_d2=!1;let chunk=_c2,resp=generateContentResponseFromVertex(yield __await(chunk.json()),params);resp.sdkHttpResponse={headers:chunk.headers};let typedResp=new GenerateContentResponse;Object.assign(typedResp,resp),yield yield __await(typedResp)}}catch(e_2_1){e_2=
1350
- {error:e_2_1}}finally{try{!_d2&&!_a3&&(_b2=apiResponse_1.return)&&(yield __await(_b2.call(apiResponse_1)))}finally{if(e_2)throw e_2.error}}})})}else{let body=generateContentParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?
1351
- void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}),response.then(function(apiResponse){return __asyncGenerator(this,arguments,function*(){var _a3,e_3,_b2,_c2;try{for(var _d2=!0,apiResponse_2=__asyncValues(apiResponse),apiResponse_2_1;apiResponse_2_1=yield __await(apiResponse_2.next()),_a3=apiResponse_2_1.done,!_a3;_d2=!0){_c2=apiResponse_2_1.value,_d2=!1;let chunk=_c2,resp=generateContentResponseFromMldev(yield __await(chunk.json()),params);resp.sdkHttpResponse=
1352
- {headers:chunk.headers};let typedResp=new GenerateContentResponse;Object.assign(typedResp,resp),yield yield __await(typedResp)}}catch(e_3_1){e_3={error:e_3_1}}finally{try{!_d2&&!_a3&&(_b2=apiResponse_2.return)&&(yield __await(_b2.call(apiResponse_2)))}finally{if(e_3)throw e_3.error}}})})}}async embedContentInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=embedContentParametersPrivateToVertex(this.apiClient,params,params),endpointUrl=tIsVertexEmbedContentModel(
1353
- params.model)?"{model}:embedContent":"{model}:predict";return path2=formatMap(endpointUrl,body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.
1354
- sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=embedContentResponseFromVertex(apiResponse,params),typedResp=new EmbedContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=embedContentParametersPrivateToMldev(this.apiClient,params);return path2=formatMap("{model}:batchEmbedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(
1355
- body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=embedContentResponseFromMldev(apiResponse),typedResp=new EmbedContentResponse;return Object.assign(typedResp,resp),typedResp})}}async generateImagesInternal(params){
1356
- var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateImagesParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).
1357
- then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateImagesResponseFromVertex(apiResponse),typedResp=new GenerateImagesResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async editImageInternal(params){var _a2,_b;
1358
- let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=editImageParametersInternalToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).
1359
- then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=editImageResponseFromVertex(apiResponse),typedResp=new EditImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(params){var _a2,_b;let response,
1360
- path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=upscaleImageAPIParametersInternalToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.
1361
- json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=upscaleImageResponseFromVertex(apiResponse),typedResp=new UpscaleImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(params){var _a2,_b;let response,path2="",queryParams={};
1362
- if(this.apiClient.isVertexAI()){let body=recontextImageParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),
1363
- response.then(apiResponse=>{let resp=recontextImageResponseFromVertex(apiResponse),typedResp=new RecontextImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=segmentImageParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:pr\
1364
- edict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=segmentImageResponseFromVertex(apiResponse),typedResp=new SegmentImageResponse;return Object.assign(
1365
- typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getModelParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),
1366
- httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromVertex(apiResponse))}else{let body=getModelParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(
1367
- body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromMldev(apiResponse))}}async listInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listModelsParametersToVertex(this.apiClient,params);return path2=formatMap("{models_url}",body._url),queryParams=
1368
- body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listModelsResponseFromVertex(
1369
- apiResponse),typedResp=new ListModelsResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=listModelsParametersToMldev(this.apiClient,params);return path2=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.
1370
- abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listModelsResponseFromMldev(apiResponse),typedResp=new ListModelsResponse;return Object.assign(typedResp,resp),typedResp})}}async update(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=updateModelParametersToVertex(this.apiClient,params);
1371
- return path2=formatMap("{model}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromVertex(apiResponse))}else{let body=updateModelParametersToMldev(this.
1372
- apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromMldev(apiResponse))}}async delete(params){var _a2,_b,_c,
1373
- _d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=deleteModelParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.
1374
- json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteModelResponseFromVertex(apiResponse),typedResp=new DeleteModelResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=deleteModelParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,
1375
- queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteModelResponseFromMldev(apiResponse),typedResp=new DeleteModelResponse;return Object.assign(
1376
- typedResp,resp),typedResp})}}async countTokens(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=countTokensParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=
1377
- params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=countTokensResponseFromVertex(apiResponse),typedResp=new CountTokensResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=countTokensParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:countTokens",body.
1378
- _url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{
1379
- let resp=countTokensResponseFromMldev(apiResponse),typedResp=new CountTokensResponse;return Object.assign(typedResp,resp),typedResp})}}async computeTokens(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=computeTokensParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:computeTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(
1380
- body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=computeTokensResponseFromVertex(apiResponse),typedResp=new ComputeTokensResponse;return Object.assign(typedResp,resp),typedResp})}else
1381
- throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateVideosParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(
1382
- body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=generateVideosOperationFromVertex(apiResponse),typedResp=new GenerateVideosOperation;return Object.assign(typedResp,resp),typedResp})}else{let body=generateVideosParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:predictLongRu\
1383
- nning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=generateVideosOperationFromMldev(apiResponse),typedResp=new GenerateVideosOperation;return Object.
1384
- assign(typedResp,resp),typedResp})}}};Models.loggedGenerateImagesWarning=!1;Models.loggedEditImageWarning=!1;Models.loggedGenerateVideosWarning=!1;var Operations=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient}async getVideosOperation(parameters){let operation=parameters.operation,config=parameters.config;if(operation.name===void 0||operation.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let resourceName2=operation.name.
1385
- split("/operations/")[0],httpOptions;config&&"httpOptions"in config&&(httpOptions=config.httpOptions);let rawOperation=await this.fetchPredictVideosOperationInternal({operationName:operation.name,resourceName:resourceName2,config:{httpOptions}});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!0})}else{let rawOperation=await this.getVideosOperationInternal({operationName:operation.name,config});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!1})}}async get(parameters){
1386
- let operation=parameters.operation,config=parameters.config;if(operation.name===void 0||operation.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let resourceName2=operation.name.split("/operations/")[0],httpOptions;config&&"httpOptions"in config&&(httpOptions=config.httpOptions);let rawOperation=await this.fetchPredictVideosOperationInternal({operationName:operation.name,resourceName:resourceName2,config:{httpOptions}});return operation._fromAPIResponse(
1387
- {apiResponse:rawOperation,_isVertexAI:!0})}else{let rawOperation=await this.getVideosOperationInternal({operationName:operation.name,config});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!1})}}async getVideosOperationInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getOperationParametersToVertex(params);return path2=formatMap("{operationName}",body._url),queryParams=body._query,delete body._url,delete body.
1388
- _query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response}else{let body=getOperationParametersToMldev(params);return path2=formatMap("{operationName}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request(
1389
- {path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response}}async fetchPredictVideosOperationInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=fetchPredictOperationParametersToVertex(params);return path2=formatMap("{resourceName}:fetchPred\
1390
- ictOperation",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Ve\
1391
- rtex AI).")}};function authConfigToMldev(fromObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterpris\
1392
- e Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(
1393
- fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function contentToMldev(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;
1394
- Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createAuthTokenConfigToMldev(apiClient,fromObject,parentObject){let toObject={},fromExpireTime=getValueByPath(fromObject,["expireTime"]);parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTim\
1395
- e"],fromExpireTime);let fromNewSessionExpireTime=getValueByPath(fromObject,["newSessionExpireTime"]);parentObject!==void 0&&fromNewSessionExpireTime!=null&&setValueByPath(parentObject,["newSessionExpireTime"],fromNewSessionExpireTime);let fromUses=getValueByPath(fromObject,["uses"]);parentObject!==void 0&&fromUses!=null&&setValueByPath(parentObject,["uses"],fromUses);let fromLiveConnectConstraints=getValueByPath(fromObject,["liveConnectConstraints"]);parentObject!==void 0&&fromLiveConnectConstraints!=
1396
- null&&setValueByPath(parentObject,["bidiGenerateContentSetup"],liveConnectConstraintsToMldev(apiClient,fromLiveConnectConstraints));let fromLockAdditionalFields=getValueByPath(fromObject,["lockAdditionalFields"]);return parentObject!==void 0&&fromLockAdditionalFields!=null&&setValueByPath(parentObject,["fieldMask"],fromLockAdditionalFields),toObject}function createAuthTokenParametersToMldev(apiClient,fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=
1397
- null&&setValueByPath(toObject,["config"],createAuthTokenConfigToMldev(apiClient,fromConfig,toObject)),toObject}function functionCallToMldev(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,
1398
- ["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleMapsToMldev(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&
1399
- setValueByPath(toObject,["authConfig"],authConfigToMldev(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev(fromObject){let toObject={};if(getValueByPath(
1400
- fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["search\
1401
- Types"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function liveConnectConfigToMldev(fromObject,parentObject){let toObject={},fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig"],fromGenerationConfig);let fromResponseModalities=getValueByPath(
1402
- fromObject,["responseModalities"]);parentObject!==void 0&&fromResponseModalities!=null&&setValueByPath(parentObject,["setup","generationConfig","responseModalities"],fromResponseModalities);let fromTemperature=getValueByPath(fromObject,["temperature"]);parentObject!==void 0&&fromTemperature!=null&&setValueByPath(parentObject,["setup","generationConfig","temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);parentObject!==void 0&&fromTopP!=null&&setValueByPath(parentObject,
1403
- ["setup","generationConfig","topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);parentObject!==void 0&&fromTopK!=null&&setValueByPath(parentObject,["setup","generationConfig","topK"],fromTopK);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["setup","generationConfig","maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);parentObject!==
1404
- void 0&&fromMediaResolution!=null&&setValueByPath(parentObject,["setup","generationConfig","mediaResolution"],fromMediaResolution);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["setup","generationConfig","seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);parentObject!==void 0&&fromSpeechConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","speechConfig"],tLiveSpeechConfig(fromSpeechConfig));
1405
- let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);parentObject!==void 0&&fromThinkingConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","thinkingConfig"],fromThinkingConfig);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);parentObject!==void 0&&fromEnableAffectiveDialog!=null&&setValueByPath(parentObject,["setup","generationConfig","enableAffectiveDialog"],fromEnableAffectiveDialog);let fromSystemInstruction=getValueByPath(
1406
- fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["setup","systemInstruction"],contentToMldev(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev(tTool(item)))),setValueByPath(parentObject,["setup","tools"],transformedList)}let fromSessionResumption=getValueByPath(
1407
- fromObject,["sessionResumption"]);parentObject!==void 0&&fromSessionResumption!=null&&setValueByPath(parentObject,["setup","sessionResumption"],sessionResumptionConfigToMldev(fromSessionResumption));let fromInputAudioTranscription=getValueByPath(fromObject,["inputAudioTranscription"]);parentObject!==void 0&&fromInputAudioTranscription!=null&&setValueByPath(parentObject,["setup","inputAudioTranscription"],fromInputAudioTranscription);let fromOutputAudioTranscription=getValueByPath(fromObject,["ou\
1408
- tputAudioTranscription"]);parentObject!==void 0&&fromOutputAudioTranscription!=null&&setValueByPath(parentObject,["setup","outputAudioTranscription"],fromOutputAudioTranscription);let fromRealtimeInputConfig=getValueByPath(fromObject,["realtimeInputConfig"]);parentObject!==void 0&&fromRealtimeInputConfig!=null&&setValueByPath(parentObject,["setup","realtimeInputConfig"],fromRealtimeInputConfig);let fromContextWindowCompression=getValueByPath(fromObject,["contextWindowCompression"]);parentObject!==
1409
- void 0&&fromContextWindowCompression!=null&&setValueByPath(parentObject,["setup","contextWindowCompression"],fromContextWindowCompression);let fromProactivity=getValueByPath(fromObject,["proactivity"]);if(parentObject!==void 0&&fromProactivity!=null&&setValueByPath(parentObject,["setup","proactivity"],fromProactivity),getValueByPath(fromObject,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Dev\
1410
- eloper API mode.");let fromAvatarConfig=getValueByPath(fromObject,["avatarConfig"]);parentObject!==void 0&&fromAvatarConfig!=null&&setValueByPath(parentObject,["setup","avatarConfig"],fromAvatarConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev(item))),setValueByPath(parentObject,["setu\
1411
- p","safetySettings"],transformedList)}let fromTranslationConfig=getValueByPath(fromObject,["translationConfig"]);return parentObject!==void 0&&fromTranslationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","translationConfig"],fromTranslationConfig),toObject}function liveConnectConstraintsToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["setup","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(
1412
- fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["config"],liveConnectConfigToMldev(fromConfig,toObject)),toObject}function partToMldev(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(
1413
- fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(
1414
- fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=
1415
- null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoug\
1416
- htSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);fromMediaProcessing!=
1417
- null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing);let fromSpeechMetadata=getValueByPath(fromObject,["speechMetadata"]);return fromSpeechMetadata!=null&&setValueByPath(toObject,["speechMetadata"],fromSpeechMetadata),toObject}function safetySettingToMldev(fromObject){let toObject={},fromCategory=getValueByPath(fromObject,["category"]);if(fromCategory!=null&&setValueByPath(toObject,["category"],fromCategory),getValueByPath(fromObject,["method"])!==void 0)throw new Error("method\
1418
- parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThreshold=getValueByPath(fromObject,["threshold"]);return fromThreshold!=null&&setValueByPath(toObject,["threshold"],fromThreshold),toObject}function sessionResumptionConfigToMldev(fromObject){let toObject={},fromHandle=getValueByPath(fromObject,["handle"]);if(fromHandle!=null&&setValueByPath(toObject,["handle"],fromHandle),getValueByPath(fromObject,["transparent"])!==void 0)throw new Error(
1419
- "transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function toolToMldev(fromObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev(
1420
- fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=
1421
- null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(
1422
- fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSe\
1423
- archRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,
1424
- ["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function getFieldMasks(setup){let fields=[];for(let key in setup)if(Object.prototype.hasOwnProperty.call(setup,key)){let value=setup[key];if(typeof value=="object"&&value!=null&&Object.keys(value).length>0){let field=Object.keys(value).map(kk=>`${key}.${kk}`);fields.push(...field)}else fields.push(key)}return fields.join(",")}function convertBidiSetupToTokenSetup(requestDict,config){let setupForMaskGeneration=null,
1425
- bidiGenerateContentSetupValue=requestDict.bidiGenerateContentSetup;if(typeof bidiGenerateContentSetupValue=="object"&&bidiGenerateContentSetupValue!==null&&"setup"in bidiGenerateContentSetupValue){let innerSetup=bidiGenerateContentSetupValue.setup;typeof innerSetup=="object"&&innerSetup!==null?(requestDict.bidiGenerateContentSetup=innerSetup,setupForMaskGeneration=innerSetup):delete requestDict.bidiGenerateContentSetup}else bidiGenerateContentSetupValue!==void 0&&delete requestDict.bidiGenerateContentSetup;
1426
- let preExistingFieldMask=requestDict.fieldMask;if(setupForMaskGeneration){let generatedMaskFromBidi=getFieldMasks(setupForMaskGeneration);if(Array.isArray(config?.lockAdditionalFields)&&config?.lockAdditionalFields.length===0)generatedMaskFromBidi?requestDict.fieldMask=generatedMaskFromBidi:delete requestDict.fieldMask;else if(config?.lockAdditionalFields&&config.lockAdditionalFields.length>0&&preExistingFieldMask!==null&&Array.isArray(preExistingFieldMask)&&preExistingFieldMask.length>0){let generationConfigFields=[
1427
- "temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],mappedFieldsFromPreExisting=[];preExistingFieldMask.length>0&&(mappedFieldsFromPreExisting=preExistingFieldMask.map(field=>generationConfigFields.includes(field)?`generationConfig.${field}`:field));let finalMaskParts=[];generatedMaskFromBidi&&finalMaskParts.push(generatedMaskFromBidi),mappedFieldsFromPreExisting.length>0&&finalMaskParts.push(...mappedFieldsFromPreExisting),finalMaskParts.length>0?requestDict.
1428
- fieldMask=finalMaskParts.join(","):delete requestDict.fieldMask}else delete requestDict.fieldMask}else preExistingFieldMask!==null&&Array.isArray(preExistingFieldMask)&&preExistingFieldMask.length>0?requestDict.fieldMask=preExistingFieldMask.join(","):delete requestDict.fieldMask;return requestDict}var Tokens=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient}async create(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error(
1429
- "The client.tokens.create method is only supported by the Gemini Developer API.");{let body=createAuthTokenParametersToMldev(this.apiClient,params);path2=formatMap("auth_tokens",body._url),queryParams=body._query,delete body.config,delete body._url,delete body._query;let transformedBody=convertBidiSetupToTokenSetup(body,params.config);return response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(transformedBody),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===
1430
- void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}};function deleteDocumentConfigToMldev(fromObject,parentObject){let toObject={},fromForce=getValueByPath(fromObject,["force"]);return parentObject!==void 0&&fromForce!=null&&setValueByPath(parentObject,["_query","force"],fromForce),toObject}function deleteDocumentParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(
1431
- fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url","name"],fromName);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&deleteDocumentConfigToMldev(fromConfig,toObject),toObject}function getDocumentParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function listDocumentsConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(
1432
- fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listDocumentsParametersToMldev(fromObject){let toObject={},fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["_url","parent"],fromParent);
1433
- let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listDocumentsConfigToMldev(fromConfig,toObject),toObject}function listDocumentsResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);
1434
- let fromDocuments=getValueByPath(fromObject,["documents"]);if(fromDocuments!=null){let transformedList=fromDocuments;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["documents"],transformedList)}return toObject}var Documents=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async params=>new Pager(PagedItem.PAGED_ITEM_DOCUMENTS,x=>this.listInternal({parent:params.parent,config:x.config}),await this.
1435
- listInternal(params),params)}async get(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=getDocumentParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?
1436
- void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b;let path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=deleteDocumentParametersToMldev(params);path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,await this.apiClient.
1437
- request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal})}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=listDocumentsParametersToMldev(params);return path2=formatMap("{parent}/docu\
1438
- ments",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=listDocumentsResponseFromMldev(apiResponse),typedResp=new ListDocumentsResponse;return Object.assign(
1439
- typedResp,resp),typedResp})}}};var FileSearchStores=class extends BaseModule{constructor(apiClient,documents=new Documents(apiClient)){super(),this.apiClient=apiClient,this.documents=documents,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_FILE_SEARCH_STORES,x=>this.listInternal(x),await this.listInternal(params),params)}async uploadToFileSearchStore(params){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not suppo\
1440
- rt uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(params.fileSearchStoreName,params.file,params.config)}async downloadMedia(uri,config){if(this.apiClient.isVertexAI())throw new Error("This method is only supported in the Gemini Developer client.");let parsedUri=new URL(uri,"http://dummy.com"),pathname=parsedUri.pathname;if(pathname.startsWith("/")&&(pathname=pathname.slice(1)),!pathname.includes("/media/"))throw new Error(`Invalid uri format: ${uri}. \
1441
- Expected to contain /media/`);let queryParams={};parsedUri.searchParams.forEach((value,key)=>{queryParams[key]=value}),queryParams.alt="media";let httpOptions=Object.assign({},config?.httpOptions),response=await this.apiClient.request({path:pathname,httpMethod:"GET",queryParams,httpOptions});if(response instanceof HttpResponse){let arrayBuffer=await response.responseInternal.arrayBuffer();return new Uint8Array(arrayBuffer)}else throw new Error("Unexpected response type from downloadMedia")}async create(params){
1442
- var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createFileSearchStoreParametersToMldev(this.apiClient,params);return path2=formatMap("fileSearchStores",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:
1443
- _a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async get(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=getFileSearchStoreParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.
1444
- apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b;let path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=deleteFileSearchStoreParametersToMldev(
1445
- params);path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,await this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal})}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only su\
1446
- pported by the Gemini Developer API.");{let body=listFileSearchStoresParametersToMldev(params);return path2=formatMap("fileSearchStores",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.
1447
- then(apiResponse=>{let resp=listFileSearchStoresResponseFromMldev(apiResponse),typedResp=new ListFileSearchStoresResponse;return Object.assign(typedResp,resp),typedResp})}}async uploadToFileSearchStoreInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=uploadToFileSearchStoreParametersToMldev(params);return path2=formatMap("upload/v1beta/{file_search_store_name}:upl\
1448
- oadToFileSearchStore",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=uploadToFileSearchStoreResumableResponseFromMldev(apiResponse),typedResp=new UploadToFileSearchStoreResumableResponse;
1449
- return Object.assign(typedResp,resp),typedResp})}}async importFile(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=importFileParametersToMldev(params);return path2=formatMap("{file_search_store_name}:importFile",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"\
1450
- POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=importFileOperationFromMldev(apiResponse),typedResp=new ImportFileOperation;return Object.assign(typedResp,resp),typedResp})}}};function isDeno(){return"Deno"in globalThis}var envMemo;function env(){var _a2,_b,_c,_d,_e,_f;if(envMemo)return envMemo;let globals=globalThis,
1451
- envObject={};return isDeno()?envObject=(_d=(_c=(_b=(_a2=globals.Deno)===null||_a2===void 0?void 0:_a2.env)===null||_b===void 0?void 0:_b.toObject)===null||_c===void 0?void 0:_c.call(_b))!==null&&_d!==void 0?_d:{}:envObject=(_f=(_e=globals.process)===null||_e===void 0?void 0:_e.env)!==null&&_f!==void 0?_f:{},envMemo=envObject,envMemo}function fillGlobals(options){var _a2,_b;let clone=Object.assign({},options),envVars=env();return typeof envVars.GOOGLE_GENAI_API_VERSION<"u"&&((_a2=clone.api_version)!==
1452
- null&&_a2!==void 0||(clone.api_version=envVars.GOOGLE_GENAI_API_VERSION)),typeof envVars.GOOGLE_GENAI_USER_PROJECT<"u"&&((_b=clone.user_project)!==null&&_b!==void 0||(clone.user_project=envVars.GOOGLE_GENAI_USER_PROJECT)),clone}var GoogleGenAISecurityProvider=class{constructor(options){this.options=options}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(url){return securityFromHeaders(await this.options.getAuthHeaders(url))}},GoogleGenAIAuthHook=class{beforeCreateRequest(_hookCtx,input){
1453
- return Object.assign(Object.assign({},input),{url:decodeSDKLevelAPIVersionPath(input.url)})}async beforeRequest(hookCtx,request){if(applyDefaultHeaders(request.headers,getStaticDefaultHeaders(hookCtx.security_source)),applyUserProject(hookCtx,request.headers),hasAuthHeaders(request.headers))return request;let security=await resolveSecurity$1(hookCtx.security_source,request.url);return applyDefaultHeaders(request.headers,security?.default_headers),applyAuth(request.headers,security),request}};function decodeSDKLevelAPIVersionPath(url){
1454
- let[,apiVersion,...rest]=url.pathname.split("/");if(!apiVersion)return url;let decodedAPIVersion=decodeURIComponent(apiVersion);if(!decodedAPIVersion.includes("/"))return url;let nextURL=new URL(url);return nextURL.pathname=`/${decodedAPIVersion}/${rest.join("/")}`,nextURL}async function resolveSecurity$1(securitySource,requestURL){if(isSecurityResolver(securitySource))return securitySource.resolveGoogleGenAISecurity(requestURL);let security=typeof securitySource=="function"?await securitySource():
1455
- securitySource;return isSecurity(security)?withEnvSecurity(security):withEnvSecurity(void 0)}function getStaticDefaultHeaders(securitySource){var _a2,_b;if(isSecurityResolver(securitySource))return(_b=(_a2=securitySource.getDefaultHeaders)===null||_a2===void 0?void 0:_a2.call(securitySource))!==null&&_b!==void 0?_b:securitySource.defaultHeaders;if(isSecurity(securitySource))return securitySource.default_headers}function withEnvSecurity(security){var _a2,_b;let envVars=env(),nextSecurity=Object.assign(
1456
- Object.assign({},security),{api_key:(_a2=security?.api_key)!==null&&_a2!==void 0?_a2:envVars.GOOGLE_GENAI_API_KEY,access_token:(_b=security?.access_token)!==null&&_b!==void 0?_b:envVars.GOOGLE_GENAI_ACCESS_TOKEN});return hasSecurityValue(nextSecurity)?nextSecurity:void 0}function securityFromHeaders(headers){var _a2,_b;let defaultHeaders={};for(let[key,value]of headers){let lowerKey=key.toLowerCase();lowerKey!=="authorization"&&lowerKey!=="x-goog-api-key"&&(defaultHeaders[key]=value)}let security={
1457
- access_token:(_a2=headers.get("authorization"))!==null&&_a2!==void 0?_a2:void 0,api_key:(_b=headers.get("x-goog-api-key"))!==null&&_b!==void 0?_b:void 0,default_headers:Object.keys(defaultHeaders).length?defaultHeaders:void 0};return hasSecurityValue(security)?security:void 0}function applyDefaultHeaders(target,source){if(source)for(let[key,value]of new Headers(source))target.get(key)===null&&target.set(key,value)}function applyUserProject(hookCtx,headers){hookCtx.options.user_project!==void 0&&
1458
- headers.get("x-goog-user-project")===null&&headers.set("x-goog-user-project",hookCtx.options.user_project)}function applyAuth(headers,security){if(security){if(security.api_key){headers.set("x-goog-api-key",security.api_key);return}security.access_token&&headers.set("Authorization",bearer(security.access_token))}}function hasAuthHeaders(headers){return headers.get("authorization")!==null||headers.get("x-goog-api-key")!==null}function bearer(token){return token.slice(0,7).toLowerCase()==="bearer "?
1459
- token:`Bearer ${token}`}function isSecurity(value){return typeof value=="object"&&value!==null}function isSecurityResolver(value){return typeof value=="object"&&value!==null&&"resolveGoogleGenAISecurity"in value&&typeof value.resolveGoogleGenAISecurity=="function"}function hasSecurityValue(security){return security.api_key!==void 0||security.access_token!==void 0||security.default_headers!==void 0}var HTTPClientError=class extends Error{constructor(message,opts){let msg=message;opts?.cause&&(msg+=
1460
- `: ${opts.cause}`),super(msg,opts),this.name="HTTPClientError",typeof this.cause>"u"&&(this.cause=opts?.cause)}},UnexpectedClientError=class extends HTTPClientError{constructor(){super(...arguments),this.name="UnexpectedClientError"}},InvalidRequestError=class extends HTTPClientError{constructor(){super(...arguments),this.name="InvalidRequestError"}},RequestAbortedError=class extends HTTPClientError{constructor(){super(...arguments),this.name="RequestAbortedError"}},RequestTimeoutError=class extends HTTPClientError{constructor(){
1461
- super(...arguments),this.name="RequestTimeoutError"}},ConnectionError=class extends HTTPClientError{constructor(){super(...arguments),this.name="ConnectionError"}};var GoogleGenAiError=class extends Error{constructor(message,httpMeta){var _a2,_b,_c,_d;super(message),this.statusCode=(_a2=httpMeta?.response)===null||_a2===void 0?void 0:_a2.status,this.body=(_b=httpMeta?.body)!==null&&_b!==void 0?_b:"",this.headers=(_c=httpMeta?.response)===null||_c===void 0?void 0:_c.headers,this.contentType=((_d=
1462
- httpMeta?.response)===null||_d===void 0?void 0:_d.headers.get("content-type"))||"",this.rawResponse=httpMeta?.response,this.name="GoogleGenAiError"}};var GeminiNextGenAPIClientError=class extends Error{},APIError=class _APIError extends GeminiNextGenAPIClientError{constructor(status,error,message,headers){super(_APIError.makeMessage(status,error,message)),this.status=status,this.headers=headers,this.error=error,this.statusCode=status,this.body=stringifyErrorBody(error),this.contentType=headers?.
1463
- get("content-type")||"",this.rawResponse=void 0,this.cause=void 0,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}static makeMessage(status,error,message){var _a2;let errorMessage=error&&isPlainObject$2(error)&&typeof error.message=="string"?error.message:void 0,errorBody=stringifyErrorBody(error),msg=(_a2=errorMessage??message)!==null&&_a2!==void 0?_a2:errorBody||"An error occurred";return`${status?`${status} `:""}${msg}`}static generate(status,errorResponse,message,headers){
1464
- return!status||!headers?new APIConnectionError({message,cause:errorResponse instanceof Error?errorResponse:void 0}):status===400?new BadRequestError(status,errorResponse,message,headers):status===401?new AuthenticationError(status,errorResponse,message,headers):status===403?new PermissionDeniedError(status,errorResponse,message,headers):status===404?new NotFoundError(status,errorResponse,message,headers):status===409?new ConflictError(status,errorResponse,message,headers):status===422?new UnprocessableEntityError(
1465
- status,errorResponse,message,headers):status===429?new RateLimitError(status,errorResponse,message,headers):status>=500?new InternalServerError(status,errorResponse,message,headers):new _APIError(status,errorResponse,message,headers)}},APIUserAbortError=class extends APIError{constructor({message}={}){super(void 0,void 0,message||"Request was aborted.",void 0)}},APIConnectionError=class extends APIError{constructor({message,cause}){super(void 0,void 0,message||"Connection error.",void 0),this.cause=
1466
- cause}},APIConnectionTimeoutError=class extends APIConnectionError{constructor({message}={}){super({message:message||"Request timed out. This is a client-side timeout. You can increase the timeout by setting the `timeout` argument in your request or client http options."})}},BadRequestError=class extends APIError{},AuthenticationError=class extends APIError{},PermissionDeniedError=class extends APIError{},NotFoundError=class extends APIError{},ConflictError=class extends APIError{},UnprocessableEntityError=class extends APIError{},
1467
- RateLimitError=class extends APIError{},InternalServerError=class extends APIError{};function wrapSDKError(error){return isCompatAPIErrorInstance(error)?error:error instanceof GoogleGenAiError?wrapAPIError(error):error instanceof HTTPClientError?wrapHTTPClientError(error):error}function wrapAPIError(error){let errorPayload=getErrorPayload(error),wrapped=APIError.generate(error.statusCode,errorPayload,error.message,error.headers);return defineReadonly(wrapped,"body",error.body),defineReadonly(wrapped,
1468
- "contentType",error.contentType),defineReadonly(wrapped,"rawResponse",error.rawResponse),defineReadonly(wrapped,"statusCode",error.statusCode),defineReadonly(wrapped,"cause",error),wrapped}function wrapHTTPClientError(error){return error instanceof RequestTimeoutError?new APIConnectionTimeoutError({message:error.message}):error instanceof RequestAbortedError?new APIUserAbortError({message:error.message}):error instanceof ConnectionError?new APIConnectionError({message:error.message,cause:error}):
1469
- new APIConnectionError({message:error.message,cause:error})}function getErrorPayload(error){let data=getObjectProperty(error,"data$");if(data&&typeof data=="object")return data;try{let parsed=JSON.parse(error.body);if(parsed&&typeof parsed=="object")return parsed}catch{}let dataError=getObjectProperty(error,"error");return dataError&&typeof dataError=="object"?dataError:void 0}function getObjectProperty(value,key){return value&&typeof value=="object"?value[key]:void 0}function stringifyErrorBody(error){
1470
- if(!error)return"";try{return JSON.stringify(error)}catch{return String(error)}}function isPlainObject$2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isCompatAPIErrorInstance(value){return typeof value=="object"&&value!==null?APIError.prototype.isPrototypeOf(value):!1}function defineReadonly(target,key,value){Object.defineProperty(target,key,{configurable:!0,enumerable:!0,value,writable:!1})}var DEFAULT_FETCHER=(input,init)=>init==null?fetch(input):fetch(input,
1471
- init),HTTPClient=class _HTTPClient{constructor(options={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=options,this.fetcher=options.fetcher||DEFAULT_FETCHER}async request(request){let req=request;for(let hook of this.requestHooks){let nextRequest=await hook(req);nextRequest&&(req=nextRequest)}try{let res=await this.fetcher(req);for(let hook of this.responseHooks)await hook(res,req);return res}catch(err){for(let hook of this.requestErrorHooks)await hook(err,req);
1472
- throw err}}addHook(...args){if(args[0]==="beforeRequest")this.requestHooks.push(args[1]);else if(args[0]==="requestError")this.requestErrorHooks.push(args[1]);else if(args[0]==="response")this.responseHooks.push(args[1]);else throw new Error(`Invalid hook type: ${args[0]}`);return this}removeHook(...args){let target;if(args[0]==="beforeRequest")target=this.requestHooks;else if(args[0]==="requestError")target=this.requestErrorHooks;else if(args[0]==="response")target=this.responseHooks;else throw new Error(
1473
- `Invalid hook type: ${args[0]}`);let index=target.findIndex(v=>v===args[1]);return index>=0&&target.splice(index,1),this}clone(){let child=new _HTTPClient(this.options);return child.requestHooks=this.requestHooks.slice(),child.requestErrorHooks=this.requestErrorHooks.slice(),child.responseHooks=this.responseHooks.slice(),child}},mediaParamSeparator=/\s*;\s*/g;function matchContentType(response,pattern){var _a2;if(pattern==="*")return!0;let contentType=((_a2=response.headers.get("content-type"))===
1474
- null||_a2===void 0?void 0:_a2.trim())||"application/octet-stream";contentType=contentType.toLowerCase();let wantParts=pattern.toLowerCase().trim().split(mediaParamSeparator),[wantType="",...wantParams]=wantParts;if(wantType.split("/").length!==2)return!1;let gotParts=contentType.split(mediaParamSeparator),[gotType="",...gotParams]=gotParts,[type="",subtype=""]=gotType.split("/");if(!type||!subtype||wantType!=="*/*"&&gotType!==wantType&&`${type}/*`!==wantType&&`*/${subtype}`!==wantType||gotParams.
1475
- length<wantParams.length)return!1;let params=new Set(gotParams);for(let wantParam of wantParams)if(!params.has(wantParam))return!1;return!0}var codeRangeRE$1=new RegExp("^[0-9]xx$","i");function matchStatusCode(response,codes){let actual=`${response.status}`,expectedCodes=Array.isArray(codes)?codes:[codes];return expectedCodes.length?expectedCodes.some(ec=>{let code=`${ec}`;if(code==="default")return!0;if(!codeRangeRE$1.test(`${code}`))return code===actual;let expectFamily=code.charAt(0);if(!expectFamily)
1476
- throw new Error("Invalid status code range");let actualFamily=actual.charAt(0);if(!actualFamily)throw new Error(`Invalid response status code: ${actual}`);return actualFamily===expectFamily}):!1}function matchResponse(response,code,contentTypePattern){return matchStatusCode(response,code)&&matchContentType(response,contentTypePattern)}function isConnectionError(err){if(typeof err!="object"||err==null)return!1;let isBrowserErr=err instanceof TypeError&&err.message.toLowerCase().startsWith("failed\
1477
- to fetch"),isNodeErr=err instanceof TypeError&&err.message.toLowerCase().startsWith("fetch failed"),isBunErr="name"in err&&err.name==="ConnectionError",isGenericErr="code"in err&&typeof err.code=="string"&&err.code.toLowerCase()==="econnreset";return isBrowserErr||isNodeErr||isGenericErr||isBunErr}function isTimeoutError(err){if(typeof err!="object"||err==null)return!1;let isNative="name"in err&&err.name==="TimeoutError",isLegacyNative="code"in err&&err.code===23,isGenericErr="code"in err&&typeof err.
1478
- code=="string"&&err.code.toLowerCase()==="econnaborted";return isNative||isLegacyNative||isGenericErr}function isAbortError(err){if(typeof err!="object"||err==null)return!1;let isNative="name"in err&&err.name==="AbortError",isLegacyNative="code"in err&&err.code===20,isGenericErr="code"in err&&typeof err.code=="string"&&err.code.toLowerCase()==="econnaborted";return isNative||isLegacyNative||isGenericErr}function initHooks(hooks){let googleGenAIAuthHook=new GoogleGenAIAuthHook;hooks.registerBeforeCreateRequestHook(
1479
- googleGenAIAuthHook),hooks.registerBeforeRequestHook(googleGenAIAuthHook)}var SDKHooks=class{constructor(){this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[];let presetHooks=[];for(let hook of presetHooks)"sdkInit"in hook&&this.registerSDKInitHook(hook),"beforeCreateRequest"in hook&&this.registerBeforeCreateRequestHook(hook),"beforeRequest"in hook&&this.registerBeforeRequestHook(hook),"afterSuccess"in hook&&this.registerAfterSuccessHook(
1480
- hook),"afterError"in hook&&this.registerAfterErrorHook(hook);initHooks(this)}registerSDKInitHook(hook){this.sdkInitHooks.push(hook)}registerBeforeCreateRequestHook(hook){this.beforeCreateRequestHooks.push(hook)}registerBeforeRequestHook(hook){this.beforeRequestHooks.push(hook)}registerAfterSuccessHook(hook){this.afterSuccessHooks.push(hook)}registerAfterErrorHook(hook){this.afterErrorHooks.push(hook)}sdkInit(opts){return this.sdkInitHooks.reduce((opts2,hook)=>hook.sdkInit(opts2),opts)}beforeCreateRequest(hookCtx,input){
1481
- let inp=input;for(let hook of this.beforeCreateRequestHooks)inp=hook.beforeCreateRequest(hookCtx,inp);return inp}async beforeRequest(hookCtx,request){let req=request;for(let hook of this.beforeRequestHooks)req=await hook.beforeRequest(hookCtx,req);return req}async afterSuccess(hookCtx,response){let res=response;for(let hook of this.afterSuccessHooks)res=await hook.afterSuccess(hookCtx,res);return res}async afterError(hookCtx,response,error){let res=response,err=error;for(let hook of this.afterErrorHooks){
1482
- let result=await hook.afterError(hookCtx,res,err);res=result.response,err=result.error}return{response:res,error:err}}};function OK(value){return{ok:!0,value}}function ERR(error){return{ok:!1,error}}function bytesToBase64(u8arr){return btoa(String.fromCodePoint(...u8arr))}function stringToBytes(str){return new TextEncoder().encode(str)}function stringToBase64(str){return bytesToBase64(stringToBytes(str))}var hasOwn=Object.prototype.hasOwnProperty;function pathToFunc(pathPattern,options){let paramRE=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;
1483
- return function(params={}){return pathPattern.replace(paramRE,function(_,placeholder){if(!hasOwn.call(params,placeholder))throw new Error(`Parameter '${placeholder}' is required`);let value=params[placeholder];if(typeof value!="string"&&typeof value!="number")throw new Error(`Parameter '${placeholder}' must be a string or number`);return`${value}`}).replace(/^\/+/,"")}}var ServerList=["https://generativelanguage.googleapis.com"];function serverURLFromOptions(options){var _a2;let serverURL=options.
1484
- server_url,params={};if(!serverURL){let serverIdx=(_a2=options.server_idx)!==null&&_a2!==void 0?_a2:0;if(serverIdx<0||serverIdx>=ServerList.length)throw new Error(`Invalid server index ${serverIdx}`);serverURL=ServerList[serverIdx]||""}let u=pathToFunc(serverURL)(params);return new URL(u)}var SDK_METADATA={userAgent:"speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai"};function combineSignals(...signals){let filtered=[];for(let signal of signals)signal&&filtered.push(signal);
1485
- switch(filtered.length){case 0:case 1:return filtered[0]||null;default:return"any"in AbortSignal&&typeof AbortSignal.any=="function"?AbortSignal.any(filtered):abortSignalAny(filtered)}}function abortSignalAny(signals){let controller=new AbortController,result=controller.signal;if(!signals.length)return controller.signal;if(signals.length===1)return signals[0]||controller.signal;for(let signal of signals)if(signal.aborted)return signal;function abort(){controller.abort(this.reason),clean()}let signalRefs=[];
1486
- function clean(){for(let signalRef of signalRefs){let signal=signalRef.deref();signal&&signal.removeEventListener("abort",abort)}}for(let signal of signals)signalRefs.push(new WeakRef(signal)),signal.addEventListener("abort",abort);return result}function compactMap(values){let out={};for(let[k,v]of Object.entries(values))typeof v<"u"&&(out[k]=v);return out}function isPlainObject$1(value){if(value===null||typeof value!="object"||Object.prototype.toString.call(value)!=="[object Object]")return!1;let proto=Object.
1487
- getPrototypeOf(value);if(proto===null||proto===Object.prototype)return!0;try{return Object.getPrototypeOf(proto)===null}catch{return!1}}var reservedEscapes=/%(2[346bcf]|3[abdf]|40|5[bd])/gi;function encodeKeyChars(v,charEncoding){return encodeChars(v,charEncoding==="percentExceptReserved"?"percent":charEncoding)}function encodeChars(v,charEncoding){switch(charEncoding){case"percent":return encodeURIComponent(v);case"percentExceptReserved":return encodeURIComponent(v).replace(reservedEscapes,m=>decodeURIComponent(
1488
- m));default:return v}}function formEncoder(sep){return(key,value,options)=>{let out="",pairs=options?.explode?explode(key,value):[[key,value]];if(pairs.every(([_,v])=>v==null))return;let encodeString=v=>encodeChars(v,options?.charEncoding),encodeValue=v=>encodeString(serializeValue(v)),encodedSep=encodeString(sep);return pairs.forEach(([pk,pv])=>{var _a2,_b;let tmp="",encValue=null;pv!=null&&(Array.isArray(pv)?encValue=(_a2=mapDefined(pv,v=>`${encodeValue(v)}`))===null||_a2===void 0?void 0:_a2.join(
1489
- encodedSep):isPlainObject$1(pv)?encValue=(_b=mapDefinedEntries(Object.entries(pv),([k,v])=>`${encodeString(k)}${encodedSep}${encodeValue(v)}`))===null||_b===void 0?void 0:_b.join(encodedSep):encValue=`${encodeValue(pv)}`,encValue!=null&&(tmp=`${encodeKeyChars(pk,options?.charEncoding)}=${encValue}`,!(!tmp||tmp==="=")&&(out+=`&${tmp}`)))}),out.slice(1)}}var encodeForm=formEncoder(",");function encodeJSON(key,value,options){if(typeof value>"u")return;let encVal=(v=>encodeChars(v,options?.charEncoding))(
1490
- JSON.stringify(value,jsonReplacer));return options?.explode?encVal:`${encodeKeyChars(key,options?.charEncoding)}=${encVal}`}var encodeSimple=(key,value,options)=>{let out="",pairs=options?.explode?explode(key,value):[[key,value]];if(pairs.every(([_,v])=>v==null))return;let encodeString=v=>encodeChars(v,options?.charEncoding),encodeValue=v=>encodeString(serializeValue(v));return pairs.forEach(([pk,pv])=>{var _a2;let tmp="";if(pv!=null){if(Array.isArray(pv))tmp=(_a2=mapDefined(pv,v=>`${encodeValue(
1491
- v)}`))===null||_a2===void 0?void 0:_a2.join(",");else if(isPlainObject$1(pv)){let mapped=mapDefinedEntries(Object.entries(pv),([k,v])=>`,${encodeString(k)},${encodeValue(v)}`);tmp=mapped?.join("").slice(1)}else tmp=`${options?.explode&&isPlainObject$1(value)?`${pk}=`:""}${encodeValue(pv)}`;out+=tmp?`,${tmp}`:""}}),out.slice(1)};function explode(key,value){return Array.isArray(value)?value.map(v=>[key,v]):isPlainObject$1(value)?Object.entries(value??{}).map(([k,v])=>[k,v]):[[key,value]]}function serializeValue(value){
1492
- return value==null?"":value instanceof Date?value.toISOString():value instanceof Uint8Array?bytesToBase64(value):typeof value=="object"?JSON.stringify(value,jsonReplacer):`${value}`}function jsonReplacer(_,value){return value instanceof Uint8Array?bytesToBase64(value):value}function mapDefined(inp,mapper){let res=inp.reduce((acc,v)=>{if(v==null)return acc;let m=mapper(v);return m==null||acc.push(m),acc},[]);return res.length?res:null}function mapDefinedEntries(inp,mapper){let acc=[];for(let[k,v]of inp){
1493
- if(v==null)continue;let m=mapper([k,v]);m!=null&&acc.push(m)}return acc.length?acc:null}function queryJoin(...args){return args.filter(Boolean).join("&")}function queryEncoder(f){return function(values,options){var _a2,_b,_c;let opts=Object.assign(Object.assign({},options),{explode:(_a2=options?.explode)!==null&&_a2!==void 0?_a2:!0,charEncoding:(_b=options?.charEncoding)!==null&&_b!==void 0?_b:"percent"}),allowEmptySet=new Set((_c=options?.allowEmptyValue)!==null&&_c!==void 0?_c:[]),encoded=Object.
1494
- entries(values).map(([key,value])=>allowEmptySet.has(key)&&(value==null||value===""||Array.isArray(value)&&value.length===0)?`${encodeURIComponent(key)}=`:f(key,value,opts));return queryJoin(...encoded)}}var encodeFormQuery=queryEncoder(encodeForm);var defaultBackoff={initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5},PermanentError=class _PermanentError extends Error{constructor(message,options){let msg=message;options?.cause&&(msg+=`: ${options.cause}`),super(msg,options),this.
1495
- name="PermanentError",typeof this.cause>"u"&&(this.cause=options?.cause),Object.setPrototypeOf(this,_PermanentError.prototype)}},TemporaryError=class _TemporaryError extends Error{constructor(message,response){super(message),this.response=response,this.name="TemporaryError",Object.setPrototypeOf(this,_TemporaryError.prototype)}};async function retry(fetchFn,options){var _a2;switch(options.config.strategy){case"backoff":return retryBackoff(wrapFetcher(fetchFn,{statusCodes:options.statusCodes,retryConnectionErrors:!!options.
1496
- config.retryConnectionErrors}),(_a2=options.config.backoff)!==null&&_a2!==void 0?_a2:defaultBackoff);case"attempt-count-backoff":return retryAttemptCountBackoff(wrapFetcher(fetchFn,{statusCodes:options.statusCodes,retryConnectionErrors:!!options.config.retryConnectionErrors}),Object.assign(Object.assign({},defaultBackoff),options.config.backoff),options.config);default:return await fetchFn(0)}}function wrapFetcher(fn,options){return async attempt=>{try{let res=await fn(attempt);if(isRetryableResponse(
1497
- res,options.statusCodes))throw new TemporaryError("Response failed with retryable status code",res);return res}catch(err){throw err instanceof TemporaryError||options.retryConnectionErrors&&(isTimeoutError(err)||isConnectionError(err))?err:new PermanentError("Permanent error",{cause:err})}}}var codeRangeRE=new RegExp("^[0-9]xx$","i");function isRetryableResponse(res,statusCodes){let actual=`${res.status}`;return statusCodes.some(code=>{if(!codeRangeRE.test(code))return code===actual;let expectFamily=code.
1498
- charAt(0);if(!expectFamily)throw new Error("Invalid status code range");let actualFamily=actual.charAt(0);if(!actualFamily)throw new Error(`Invalid response status code: ${actual}`);return actualFamily===expectFamily})}async function retryBackoff(fn,strategy){let{maxElapsedTime,initialInterval,exponent,maxInterval}=strategy,start=Date.now(),x=0;for(;;)try{return await fn(x)}catch(err){if(err instanceof PermanentError)throw err.cause;if(Date.now()-start>maxElapsedTime){if(err instanceof TemporaryError)
1499
- return err.response;throw err}let retryInterval=0;err instanceof TemporaryError&&(retryInterval=retryIntervalFromResponse(err.response)),retryInterval<=0&&(retryInterval=initialInterval*Math.pow(x,exponent)+Math.random()*1e3);let d=Math.min(retryInterval,maxInterval);await delay(d),x++}}async function retryAttemptCountBackoff(fn,strategy,config){let attempt=0;for(;;)try{return await fn(attempt)}catch(err){if(err instanceof PermanentError)throw err.cause;if(attempt>=config.maxRetries){if(err instanceof
1500
- TemporaryError)return err.response;throw err}let retryInterval=0;err instanceof TemporaryError&&(retryInterval=retryIntervalFromResponse(err.response)),retryInterval<=0&&(retryInterval=strategy.initialInterval*Math.pow(strategy.exponent,attempt)*(1-Math.random()*.25));let d=Math.min(retryInterval,strategy.maxInterval);await delay(d),attempt++}}function retryIntervalFromResponse(res){let retryAfterMsVal=res.headers.get("retry-after-ms");if(retryAfterMsVal){let parsedMs=Number(retryAfterMsVal);if(Number.
1501
- isFinite(parsedMs)&&parsedMs>=0)return parsedMs}let retryVal=res.headers.get("retry-after")||"";if(!retryVal)return 0;let parsedNumber=Number(retryVal);if(Number.isInteger(parsedNumber))return parsedNumber*1e3;let parsedDate=Date.parse(retryVal);if(Number.isInteger(parsedDate)){let deltaMS=parsedDate-Date.now();return deltaMS>0?Math.ceil(deltaMS):0}return 0}async function delay(delay2){return new Promise(resolve=>setTimeout(resolve,delay2))}var gt=typeof globalThis>"u"?null:globalThis,webWorkerLike=typeof gt==
1502
- "object"&&gt!=null&&"importScripts"in gt&&typeof gt.importScripts=="function",isBrowserLike=webWorkerLike||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u",ClientSDK=class{constructor(options={}){let opt=options;typeof opt=="object"&&opt!=null&&"hooks"in opt&&opt.hooks instanceof SDKHooks?this._hooks=opt.hooks:this._hooks=new SDKHooks;let defaultHttpClient=new HTTPClient;options.http_client=options.http_client||defaultHttpClient,options=this.
1503
- _hooks.sdkInit(options);let url=serverURLFromOptions(options);url&&(url.pathname=url.pathname.replace(/\/+$/,"")+"/"),this._baseURL=url,this._httpClient=options.http_client||defaultHttpClient,this._options=Object.assign(Object.assign({},fillGlobals(options)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&env().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(context,conf,options){var _a2,_b,_c,_d,_e;let{method,path:path2,query,headers:opHeaders,security}=conf,
1504
- base=(_a2=conf.baseURL)!==null&&_a2!==void 0?_a2:this._baseURL;if(!base)return ERR(new InvalidRequestError("No base URL provided for operation"));let baseURL=new URL(base),reqURL;path2?(baseURL.pathname=baseURL.pathname.replace(/\/+$/,"")+"/",reqURL=new URL(path2,baseURL),!reqURL.search&&baseURL.search&&(reqURL.search=baseURL.search)):reqURL=baseURL,reqURL.hash="";let mergeQuery=(current,additions)=>{if(!additions)return current;let additionKeys=new Set(additions.split("&").filter(pair=>pair!=="").
1505
- map(pair=>{var _a3;return(_a3=pair.split("=")[0])!==null&&_a3!==void 0?_a3:""}));return[...current.split("&").filter(pair=>{var _a3;return pair!==""&&!additionKeys.has((_a3=pair.split("=")[0])!==null&&_a3!==void 0?_a3:"")}),additions].join("&")},encodeQueryRecord=record=>Object.entries(record).map(([k,v])=>{if(v==null)return;let value=isPlainObject$1(v)?JSON.stringify(v):v;return encodeForm(k,value,{explode:Array.isArray(value),charEncoding:"percent"})}).filter(pair=>typeof pair<"u").join("&"),finalQuery=[
1506
- query||"",encodeQueryRecord(options?.extra_query||{}),encodeQueryRecord(security?.queryParams||{})].reduce(mergeQuery,reqURL.search.slice(1));finalQuery&&(reqURL.search=`?${finalQuery}`);let headers=new Headers(opHeaders),username=security?.basic.username,password=security?.basic.password;if(username!=null||password!=null){let encoded=stringToBase64([username||"",password||""].join(":"));headers.set("Authorization",`Basic ${encoded}`)}let securityHeaders=new Headers(security?.headers||{});for(let[
1507
- k,v]of securityHeaders)headers.set(k,v);let cookie=headers.get("cookie")||"";for(let[k,v]of Object.entries(security?.cookies||{}))cookie+=`; ${k}=${v}`;cookie=cookie.startsWith("; ")?cookie.slice(2):cookie,headers.set("cookie",cookie);let userHeaders=new Headers((_b=options?.headers)!==null&&_b!==void 0?_b:(_c=options?.fetch_options)===null||_c===void 0?void 0:_c.headers);for(let[k,v]of userHeaders)headers.set(k,v);isBrowserLike||headers.set((_d=conf.uaHeader)!==null&&_d!==void 0?_d:"user-agent",
1508
- (_e=conf.userAgent)!==null&&_e!==void 0?_e:SDK_METADATA.userAgent);let reqBody=conf.body,extraBody=Object.fromEntries(Object.entries(options?.extra_body||{}).filter(([,v])=>typeof v<"u"));if(Object.keys(extraBody).length>0){let contentType=new Headers(opHeaders).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(contentType)||typeof reqBody!="string"&&reqBody!=null)return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies"));let parsedBody;
1509
- try{parsedBody=reqBody?JSON.parse(reqBody):{}}catch(err){return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies",{cause:err}))}if(!isPlainObject$1(parsedBody))return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies"));reqBody=JSON.stringify(Object.assign(Object.assign({},parsedBody),extraBody)),headers.delete("content-length")}let fetchOptions=Object.assign(Object.assign({},options?.fetch_options),options);!fetchOptions?.
1510
- signal&&conf.timeout_ms!=null&&conf.timeout_ms>0&&(context.timeout_ms=conf.timeout_ms),conf.body instanceof ReadableStream&&Object.assign(fetchOptions,{duplex:"half"});let input;try{input=this._hooks.beforeCreateRequest(context,{url:reqURL,options:Object.assign(Object.assign({},fetchOptions),{body:reqBody??null,headers,method})})}catch(err){return ERR(new UnexpectedClientError("Create request hook failed to execute",{cause:err}))}return OK(new Request(input.url,input.options))}async _do(request,options){
1511
- let{context,isErrorStatusCode}=options,timeout_ms=context.timeout_ms;return retry(async()=>{var _a2;let cloned=request.clone(),attempt=cloned;if(timeout_ms!=null&&timeout_ms>0){let timeoutSignal=AbortSignal.timeout(timeout_ms),combined=(_a2=combineSignals(cloned.signal,timeoutSignal))!==null&&_a2!==void 0?_a2:timeoutSignal;attempt=new Request(cloned,{signal:combined})}let req=await this._hooks.beforeRequest(context,attempt);await logRequest(this._logger,req).catch(e=>{var _a3;return(_a3=this._logger)===
1512
- null||_a3===void 0?void 0:_a3.log("Failed to log request:",e)});let response=await this._httpClient.request(req);try{if(isErrorStatusCode(response.status)){let result=await this._hooks.afterError(context,response,null);if(result.error)throw result.error;response=result.response||response}else response=await this._hooks.afterSuccess(context,response)}finally{await logResponse(this._logger,response,req).catch(e=>{var _a3;return(_a3=this._logger)===null||_a3===void 0?void 0:_a3.log("Failed to log r\
1513
- esponse:",e)})}return response},{config:options.retryConfig,statusCodes:options.retryCodes}).then(r=>OK(r),err=>{switch(!0){case isAbortError(err):return ERR(new RequestAbortedError("Request aborted by client",{cause:err}));case isTimeoutError(err):return ERR(new RequestTimeoutError("Request timed out",{cause:err}));case isConnectionError(err):return ERR(new ConnectionError("Unable to make request",{cause:err}));default:return ERR(new UnexpectedClientError("Unexpected HTTP client error",{cause:err}))}})}},
1514
- jsonLikeContentTypeRE=/^(application|text)\/([^+]+\+)*json.*/,jsonlLikeContentTypeRE=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;async function logRequest(logger,req){if(!logger)return;let contentType=req.headers.get("content-type"),ct=contentType?.split(";")[0]||"";logger.group(`> Request: ${req.method} ${req.url}`),logger.group("Headers:");for(let[k,v]of req.headers.entries())logger.log(`${k}: ${v}`);switch(logger.groupEnd(),logger.group("Body:"),!0){case jsonLikeContentTypeRE.test(ct):
1515
- logger.log(await req.clone().json());break;case ct.startsWith("text/"):logger.log(await req.clone().text());break;case ct==="multipart/form-data":{let body=await req.clone().formData();for(let[k,v]of body){let vlabel=v instanceof Blob?"<Blob>":v;logger.log(`${k}: ${vlabel}`)}break}default:logger.log(`<${contentType}>`);break}logger.groupEnd(),logger.groupEnd()}async function logResponse(logger,res,req){if(!logger)return;let contentType=res.headers.get("content-type"),ct=contentType?.split(";")[0]||
1516
- "";logger.group(`< Response: ${req.method} ${req.url}`),logger.log("Status Code:",res.status,res.statusText),logger.group("Headers:");for(let[k,v]of res.headers.entries())logger.log(`${k}: ${v}`);switch(logger.groupEnd(),logger.group("Body:"),!0){case(matchContentType(res,"application/json")||jsonLikeContentTypeRE.test(ct)&&!jsonlLikeContentTypeRE.test(ct)):logger.log(await res.clone().json());break;case(matchContentType(res,"application/jsonl")||jsonlLikeContentTypeRE.test(ct)):case matchContentType(
1517
- res,"text/event-stream"):logger.log(`<${contentType}>`);break;case matchContentType(res,"text/*"):logger.log(await res.clone().text());break;case matchContentType(res,"multipart/form-data"):{let body=await res.clone().formData();for(let[k,v]of body){let vlabel=v instanceof Blob?"<Blob>":v;logger.log(`${k}: ${vlabel}`)}break}default:logger.log(`<${contentType}>`);break}logger.groupEnd(),logger.groupEnd()}var GoogleGenAiDefaultError=class extends GoogleGenAiError{constructor(message,httpMeta){message&&
1518
- (message+=": "),message+=`Status ${httpMeta.response.status}`;let contentType=httpMeta.response.headers.get("content-type")||'""';contentType!=="application/json"&&(message+=` Content-Type ${contentType.includes(" ")?`"${contentType}"`:contentType}`);let body=httpMeta.body||'""';message+=body.length>100?`
1317
+ null||_a2===void 0)&&_a2.tools&&params.config.tools.forEach((tool,index)=>{if(isCallableTool(tool))return;let geminiTool=tool;geminiTool.functionDeclarations&&geminiTool.functionDeclarations.length>0&&afcIncompatibleToolIndexes.push(index)}),afcIncompatibleToolIndexes}function shouldAppendAfcHistory(config){var _a2;return!(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.ignoreCallHistory)}function shouldEnableAutomaticContinuation(config,defaultEnabled=!0){return!config||config.
1318
+ automaticContinuation===void 0||config.automaticContinuation===null?defaultEnabled:!!config.automaticContinuation}function isResumableFinishReason(finishReason){return finishReason===void 0||finishReason===FinishReason.CONTINUATION}function canResumeStream(enableContinuation,continuationToken,finishReason){return enableContinuation&&!!continuationToken&&isResumableFinishReason(finishReason)}function clearIntermediateFinishReason(chunk,enableContinuation,continuationToken){var _a2;let firstCandidate=(_a2=
1319
+ chunk.candidates)===null||_a2===void 0?void 0:_a2[0];firstCandidate?.finishReason!==void 0&&canResumeStream(enableContinuation,continuationToken,firstCandidate.finishReason)&&(firstCandidate.finishReason=void 0)}function processContinuationStreamChunk(chunk,enableContinuation,accumulatedUsage,hopState){var _a2;if(chunk.usageMetadata)if(accumulatedUsage){let mergedUsage=mergeUsageMetadata(accumulatedUsage,chunk.usageMetadata);chunk=Object.assign(new GenerateContentResponse,chunk,{usageMetadata:mergedUsage}),
1320
+ hopState.hopUsage=mergedUsage}else attachInitialPromptTokenCount(chunk.usageMetadata),hopState.hopUsage=chunk.usageMetadata;let firstCandidate=(_a2=chunk.candidates)===null||_a2===void 0?void 0:_a2[0];return firstCandidate&&(firstCandidate.finishReason!==void 0&&(hopState.hopFinishReason=firstCandidate.finishReason),firstCandidate.continuationToken?hopState.continuationToken=firstCandidate.continuationToken:firstCandidate.finishReason!==void 0&&!isResumableFinishReason(firstCandidate.finishReason)&&
1321
+ (hopState.continuationToken=void 0),clearIntermediateFinishReason(chunk,enableContinuation,hopState.continuationToken)),chunk}function shouldRethrowStreamError(err,config,enableContinuation,hopState){var _a2;return!!(!((_a2=config?.abortSignal)===null||_a2===void 0)&&_a2.aborted)||err instanceof Error&&err.name==="AbortError"||!canResumeStream(enableContinuation,hopState.continuationToken,hopState.hopFinishReason)}function shouldContinueGeneration(response){var _a2;let candidate=(_a2=response?.candidates)===
1322
+ null||_a2===void 0?void 0:_a2[0];if(candidate?.continuationToken&&isResumableFinishReason(candidate.finishReason))return candidate.continuationToken}function prepareContinuationConfig(baseConfig,continuationToken,clearAutomaticContinuation=!1){let hasAutoCont=baseConfig?.automaticContinuation!==void 0&&baseConfig?.automaticContinuation!==null,needClearAutoCont=clearAutomaticContinuation&&hasAutoCont;if(!continuationToken&&!needClearAutoCont)return baseConfig;if(!baseConfig)return continuationToken?
1323
+ {continuationToken}:void 0;let copied=Object.assign({},baseConfig);return continuationToken&&(copied.continuationToken=continuationToken),needClearAutoCont&&delete copied.automaticContinuation,copied}function mergeModalityTokenCounts(prevList,currList){var _a2,_b;let countsByModality=new Map,order=[];for(let item of[...prevList,...currList]){let modality=item.modality;countsByModality.has(modality)||(countsByModality.set(modality,0),order.push(modality)),countsByModality.set(modality,((_a2=countsByModality.
1324
+ get(modality))!==null&&_a2!==void 0?_a2:0)+((_b=item.tokenCount)!==null&&_b!==void 0?_b:0))}return order.map(modality=>{var _a3;return{modality,tokenCount:(_a3=countsByModality.get(modality))!==null&&_a3!==void 0?_a3:0}})}function mergeSafetyRatings(prevList,currList){let byCategory=new Map,order=[];for(let rating of[...prevList,...currList]){let category=rating.category;byCategory.has(category)||order.push(category),byCategory.set(category,rating)}return order.map(cat=>byCategory.get(cat))}function isMergeableObject(val){
1325
+ if(typeof val!="object"||val===null||Array.isArray(val)||val instanceof HttpResponse)return!1;let proto=Object.getPrototypeOf(val);return proto===null||proto===Object.prototype||val instanceof GenerateContentResponse||val instanceof GenerateContentResponsePromptFeedback||val instanceof GenerateContentResponseUsageMetadata}function isModalityTokenCountArray(fieldName,arr){return fieldName.endsWith("TokensDetails")?!0:arr.length>0&&typeof arr[0]=="object"&&arr[0]!==null&&"modality"in arr[0]}function mergeCandidates(prevCandidates,currCandidates){
1326
+ if(prevCandidates.length===0)return currCandidates;if(currCandidates.length===0)return prevCandidates;let merged=[],minLen=Math.min(prevCandidates.length,currCandidates.length);for(let i=0;i<minLen;i++)merged.push(mergeResponseObjects(prevCandidates[i],currCandidates[i],!0,!1));return prevCandidates.length>minLen&&merged.push(...prevCandidates.slice(minLen)),currCandidates.length>minLen&&merged.push(...currCandidates.slice(minLen)),merged}function getInitialPromptTokenCount(usage){var _a2;if(usage)
1327
+ return(_a2=usage._initialPromptTokenCount)!==null&&_a2!==void 0?_a2:usage.promptTokenCount}function attachInitialPromptTokenCount(usage,initialPromptTokenCount){let resolved=initialPromptTokenCount??getInitialPromptTokenCount(usage);return resolved!==void 0&&Object.defineProperty(usage,"_initialPromptTokenCount",{value:resolved,enumerable:!1,configurable:!0,writable:!0}),!(usage instanceof GenerateContentResponseUsageMetadata)&&!Object.prototype.hasOwnProperty.call(usage,"initialPromptTokenCount")&&
1328
+ Object.defineProperty(usage,"initialPromptTokenCount",{get(){return getInitialPromptTokenCount(this)},enumerable:!1,configurable:!0}),usage}function mergeUsageMetadata(prev,curr){var _a2;if(!curr)return prev&&attachInitialPromptTokenCount(prev);if(!prev)return attachInitialPromptTokenCount(curr);let initialPrompt=(_a2=getInitialPromptTokenCount(prev))!==null&&_a2!==void 0?_a2:getInitialPromptTokenCount(curr),merged=mergeResponseObjects(prev,curr,!1,!0);return attachInitialPromptTokenCount(merged,
1329
+ initialPrompt)}function mergeResponseObjects(prev,curr,isCandidate=!1,isUsageMetadata=!1){let mergedData={},keys=new Set([...Object.keys(prev),...Object.keys(curr)]);for(let fieldName of keys){let prevVal=prev[fieldName],currVal=curr[fieldName];if(isCandidate&&(fieldName==="continuationToken"||fieldName==="finishReason"||fieldName==="finishMessage")){currVal!==void 0&&(mergedData[fieldName]=currVal);continue}if(fieldName==="usageMetadata"){let mergedUsage=mergeUsageMetadata(prevVal,currVal);mergedUsage!==
1330
+ void 0&&(mergedData[fieldName]=mergedUsage);continue}currVal==null?prevVal!==void 0&&(mergedData[fieldName]=prevVal):prevVal==null?mergedData[fieldName]=currVal:typeof prevVal=="number"&&typeof currVal=="number"&&(isUsageMetadata||fieldName==="tokenCount"||fieldName.endsWith("TokenCount")||fieldName.endsWith("Count")||fieldName.endsWith("Sum"))?mergedData[fieldName]=prevVal+currVal:Array.isArray(prevVal)&&Array.isArray(currVal)?fieldName==="candidates"?mergedData[fieldName]=mergeCandidates(prevVal,
1331
+ currVal):isModalityTokenCountArray(fieldName,prevVal)||isModalityTokenCountArray(fieldName,currVal)?mergedData[fieldName]=mergeModalityTokenCounts(prevVal,currVal):fieldName==="safetyRatings"?mergedData[fieldName]=mergeSafetyRatings(prevVal,currVal):mergedData[fieldName]=[...prevVal,...currVal]:isMergeableObject(prevVal)&&isMergeableObject(currVal)?mergedData[fieldName]=mergeResponseObjects(prevVal,currVal,!1,fieldName==="usageMetadata"||isUsageMetadata):mergedData[fieldName]=currVal}return mergedData}
1332
+ function mergeContinuationResponses(responses){if(responses.length===0)return new GenerateContentResponse;if(responses.length===1)return responses[0].usageMetadata&&attachInitialPromptTokenCount(responses[0].usageMetadata),responses[0];let mergedRecord=responses[0];for(let i=1;i<responses.length;i++)mergedRecord=mergeResponseObjects(mergedRecord,responses[i],!1,!1);let mergedResponse=new GenerateContentResponse;return Object.assign(mergedResponse,mergedRecord),mergedResponse}var Models=class _Models extends BaseModule{constructor(apiClient){
1333
+ super(),this.apiClient=apiClient,this.embedContent=async params=>{if(!this.apiClient.isVertexAI())return params.model.includes("gemini-embedding-2")&&(params.contents=tContents(params.contents)),await this.embedContentInternal(params);if(params.model.includes("gemini")&&params.model!=="gemini-embedding-001"||params.model.includes("maas")){let contents=tContents(params.contents);if(contents.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");let paramsPrivate=Object.
1334
+ assign(Object.assign({},params),{content:contents[0],embeddingApiType:EmbeddingApiType.EMBED_CONTENT});return await this.embedContentInternal(paramsPrivate)}else{let paramsPrivate=Object.assign(Object.assign({},params),{embeddingApiType:EmbeddingApiType.PREDICT});return await this.embedContentInternal(paramsPrivate)}},this.generateContent=async params=>{var _a2,_b,_c,_d,_e;let transformedParams=await this.processParamsMaybeAddMcpUsage(params);if(this.maybeMoveToResponseJsonSchema(params),!hasCallableTools(
1335
+ params)||shouldDisableAfc(params.config))return shouldEnableAutomaticContinuation(params.config,!0)?await this.generateContentWithContinuation(transformedParams):await this.generateContentInternal(transformedParams);let incompatibleToolIndexes=findAfcIncompatibleToolIndexes(params);if(incompatibleToolIndexes.length>0){let formattedIndexes=incompatibleToolIndexes.map(index=>`tools[${index}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic Func\
1336
+ tionDeclarations is not yet supported. Incompatible tools found at ${formattedIndexes}.`)}let response,functionResponseContent,automaticFunctionCallingHistory=tContents(transformedParams.contents),maxRemoteCalls=(_c=(_b=(_a2=transformedParams.config)===null||_a2===void 0?void 0:_a2.automaticFunctionCalling)===null||_b===void 0?void 0:_b.maximumRemoteCalls)!==null&&_c!==void 0?_c:DEFAULT_MAX_REMOTE_CALLS,remoteCalls=0;for(;remoteCalls<maxRemoteCalls&&(response=await this.generateContentWithContinuation(
1337
+ transformedParams),!(!response.functionCalls||response.functionCalls.length===0));){let responseContent=response.candidates[0].content,functionResponseParts=[];for(let tool of(_e=(_d=params.config)===null||_d===void 0?void 0:_d.tools)!==null&&_e!==void 0?_e:[])if(isCallableTool(tool)){let parts=await tool.callTool(response.functionCalls);functionResponseParts.push(...parts)}remoteCalls++,functionResponseContent={role:"user",parts:functionResponseParts},transformedParams.contents=tContents(transformedParams.
1338
+ contents),transformedParams.contents.push(responseContent),transformedParams.contents.push(functionResponseContent),shouldAppendAfcHistory(transformedParams.config)&&(automaticFunctionCallingHistory.push(responseContent),automaticFunctionCallingHistory.push(functionResponseContent))}return shouldAppendAfcHistory(transformedParams.config)&&(response.automaticFunctionCallingHistory=automaticFunctionCallingHistory),response},this.generateContentStream=async params=>{var _a2,_b,_c,_d,_e;if(this.maybeMoveToResponseJsonSchema(
1339
+ params),shouldDisableAfc(params.config)){let transformedParams=await this.processParamsMaybeAddMcpUsage(params);return shouldEnableAutomaticContinuation(params.config,!0)?await this.generateContentStreamWithContinuation(transformedParams):await this.generateContentStreamInternal(transformedParams)}let incompatibleToolIndexes=findAfcIncompatibleToolIndexes(params);if(incompatibleToolIndexes.length>0){let formattedIndexes=incompatibleToolIndexes.map(index=>`tools[${index}]`).join(", ");throw new Error(
1340
+ `Incompatible tools found at ${formattedIndexes}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let streamFunctionCall=(_c=(_b=(_a2=params?.config)===null||_a2===void 0?void 0:_a2.toolConfig)===null||_b===void 0?void 0:_b.functionCallingConfig)===null||_c===void 0?void 0:_c.streamFunctionCallArguments,disableAfc=(_e=(_d=params?.config)===null||_d===void 0?void 0:_d.automaticFunctionCalling)===null||_e===void 0?void 0:_e.disable;
1341
+ if(streamFunctionCall&&!disableAfc)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(params)},this.generateImages=async params=>(_Models.
1342
+ loggedGenerateImagesWarning||(_Models.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images")),await this.generateImagesInternal(params).then(apiResponse=>{
1343
+ var _a2;let positivePromptSafetyAttributes,generatedImages=[];if(apiResponse?.generatedImages)for(let generatedImage of apiResponse.generatedImages)generatedImage&&generatedImage?.safetyAttributes&&((_a2=generatedImage?.safetyAttributes)===null||_a2===void 0?void 0:_a2.contentType)==="Positive Prompt"?positivePromptSafetyAttributes=generatedImage?.safetyAttributes:generatedImages.push(generatedImage);let response;return positivePromptSafetyAttributes?response={generatedImages,positivePromptSafetyAttributes,
1344
+ sdkHttpResponse:apiResponse.sdkHttpResponse}:response={generatedImages,sdkHttpResponse:apiResponse.sdkHttpResponse},response})),this.list=async params=>{var _a2;let actualParams={config:Object.assign(Object.assign({},{queryBase:!0}),params?.config)};if(this.apiClient.isVertexAI()&&!actualParams.config.queryBase){if(!((_a2=actualParams.config)===null||_a2===void 0)&&_a2.filter)throw new Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Age\
1345
+ nt Platform mode.");actualParams.config.filter="labels.tune-type:*"}return new Pager(PagedItem.PAGED_ITEM_MODELS,x=>this.listInternal(x),await this.listInternal(actualParams),actualParams)},this.editImage=async params=>{_Models.loggedEditImageWarning||(_Models.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/g\
1346
+ emini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image"));let paramsInternal={model:params.model,prompt:params.prompt,referenceImages:[],config:params.config};return params.referenceImages&&params.referenceImages&&(paramsInternal.referenceImages=params.referenceImages.map(img=>img.toReferenceImageAPI())),await this.editImageInternal(paramsInternal)},this.upscaleImage=async params=>{let apiConfig={
1347
+ numberOfImages:1,mode:"upscale"};params.config&&(apiConfig=Object.assign(Object.assign({},apiConfig),params.config));let apiParams={model:params.model,image:params.image,upscaleFactor:params.upscaleFactor,config:apiConfig};return await this.upscaleImageInternal(apiParams)},this.generateVideos=async params=>{var _a2,_b,_c,_d,_e,_f;if((params.prompt||params.image||params.video)&&params.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return(params.
1348
+ prompt||params.image||params.video)&&(_Models.loggedGenerateVideosWarning||(_Models.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead."))),this.apiClient.isVertexAI()||(!((_a2=params.video)===null||_a2===void 0)&&_a2.uri&&(!((_b=params.video)===null||_b===void 0)&&_b.videoBytes)?params.video={uri:params.video.uri,mimeType:params.
1349
+ video.mimeType}:!((_d=(_c=params.source)===null||_c===void 0?void 0:_c.video)===null||_d===void 0)&&_d.uri&&(!((_f=(_e=params.source)===null||_e===void 0?void 0:_e.video)===null||_f===void 0)&&_f.videoBytes)&&(params.source.video={uri:params.source.video.uri,mimeType:params.source.video.mimeType})),await this.generateVideosInternal(params)}}async generateContentWithContinuation(params){let enableContinuation=shouldEnableAutomaticContinuation(params.config,!0),continuationToken,responses=[];for(;responses.
1350
+ length===0||enableContinuation&&continuationToken;){let callConfig=prepareContinuationConfig(params.config,continuationToken),callParams=callConfig===params.config?params:Object.assign(Object.assign({},params),{config:callConfig}),response=await this.generateContentInternal(callParams);responses.push(response),continuationToken=shouldContinueGeneration(response)}return mergeContinuationResponses(responses)}async generateContentStreamWithContinuation(params){let enableContinuation=shouldEnableAutomaticContinuation(
1351
+ params.config,!0),firstStream=await this.generateContentStreamInternal(params);return(function(models,initialParams,initialStream){return __asyncGenerator(this,arguments,function*(){var _a2,e_1,_b,_c;let currentStream=initialStream,hopState={},accumulatedUsage,isFirstHop=!0;for(;isFirstHop||canResumeStream(enableContinuation,hopState.continuationToken,hopState.hopFinishReason);){if(!isFirstHop){let callConfig=prepareContinuationConfig(initialParams.config,hopState.continuationToken),callParams=Object.
1352
+ assign(Object.assign({},initialParams),{config:callConfig});currentStream=yield __await(models.generateContentStreamInternal(callParams))}isFirstHop=!1,hopState={};try{try{for(var _d=!0,currentStream_1=(e_1=void 0,__asyncValues(currentStream)),currentStream_1_1;currentStream_1_1=yield __await(currentStream_1.next()),_a2=currentStream_1_1.done,!_a2;_d=!0){_c=currentStream_1_1.value,_d=!1;let chunk=_c;chunk=processContinuationStreamChunk(chunk,enableContinuation,accumulatedUsage,hopState),yield yield __await(
1353
+ chunk)}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_d&&!_a2&&(_b=currentStream_1.return)&&(yield __await(_b.call(currentStream_1)))}finally{if(e_1)throw e_1.error}}}catch(err){if(shouldRethrowStreamError(err,params.config,enableContinuation,hopState))throw err}hopState.hopUsage&&(accumulatedUsage=hopState.hopUsage)}})})(this,params,firstStream)}maybeMoveToResponseJsonSchema(params){params.config&&params.config.responseSchema&&(params.config.responseJsonSchema||Object.keys(params.config.responseSchema).
1354
+ includes("$schema")&&(params.config.responseJsonSchema=params.config.responseSchema,delete params.config.responseSchema))}async processParamsMaybeAddMcpUsage(params){var _a2,_b,_c;let tools=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools;if(!tools)return params;let transformedTools=await Promise.all(tools.map(async tool=>isCallableTool(tool)?await tool.tool():tool)),newParams={model:params.model,contents:params.contents,config:Object.assign(Object.assign({},params.config),{tools:transformedTools})};
1355
+ if(newParams.config.tools=transformedTools,params.config&&params.config.tools&&hasMcpToolUsage(params.config.tools)){let headers=(_c=(_b=params.config.httpOptions)===null||_b===void 0?void 0:_b.headers)!==null&&_c!==void 0?_c:{},newHeaders=Object.assign({},headers);Object.keys(newHeaders).length===0&&(newHeaders=this.apiClient.getDefaultHeaders()),setMcpUsageHeader(newHeaders),newParams.config.httpOptions=Object.assign(Object.assign({},params.config.httpOptions),{headers:newHeaders})}return newParams}async initAfcToolsMap(params){
1356
+ var _a2,_b,_c;let afcTools=new Map;for(let tool of(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools)!==null&&_b!==void 0?_b:[])if(isCallableTool(tool)){let callableTool=tool,toolDeclaration=await callableTool.tool();for(let declaration of(_c=toolDeclaration.functionDeclarations)!==null&&_c!==void 0?_c:[]){if(!declaration.name)throw new Error("Function declaration name is required.");if(afcTools.has(declaration.name))throw new Error(`Duplicate tool declaration name: ${declaration.name}`);
1357
+ afcTools.set(declaration.name,callableTool)}}return afcTools}async processAfcStream(params){var _a2,_b,_c;let maxRemoteCalls=(_c=(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.automaticFunctionCalling)===null||_b===void 0?void 0:_b.maximumRemoteCalls)!==null&&_c!==void 0?_c:DEFAULT_MAX_REMOTE_CALLS,wereFunctionsCalled=!1,remoteCallCount=0,afcToolsMap=await this.initAfcToolsMap(params);return(function(models,afcTools,params2){return __asyncGenerator(this,arguments,function*(){for(var _a3,
1358
+ e_2,_b2,_c2,_d,_e;remoteCallCount<maxRemoteCalls;){wereFunctionsCalled&&(remoteCallCount++,wereFunctionsCalled=!1);let transformedParams=yield __await(models.processParamsMaybeAddMcpUsage(params2)),response=yield __await(models.generateContentStreamWithContinuation(transformedParams)),functionResponses=[],responseContents=[];try{for(var _f=!0,response_1=(e_2=void 0,__asyncValues(response)),response_1_1;response_1_1=yield __await(response_1.next()),_a3=response_1_1.done,!_a3;_f=!0){_c2=response_1_1.
1359
+ value,_f=!1;let chunk=_c2;if(yield yield __await(chunk),chunk.candidates&&(!((_d=chunk.candidates[0])===null||_d===void 0)&&_d.content)){responseContents.push(chunk.candidates[0].content);for(let part of(_e=chunk.candidates[0].content.parts)!==null&&_e!==void 0?_e:[])if(remoteCallCount<maxRemoteCalls&&part.functionCall){if(!part.functionCall.name)throw new Error("Function call name was not returned by the model.");if(afcTools.has(part.functionCall.name)){let responseParts=yield __await(afcTools.
1360
+ get(part.functionCall.name).callTool([part.functionCall]));functionResponses.push(...responseParts)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, missing tool: ${part.functionCall.name}`)}}}}catch(e_2_1){e_2={error:e_2_1}}finally{try{!_f&&!_a3&&(_b2=response_1.return)&&(yield __await(_b2.call(response_1)))}finally{if(e_2)throw e_2.error}}if(functionResponses.length>0){
1361
+ wereFunctionsCalled=!0;let typedResponseChunk=new GenerateContentResponse;typedResponseChunk.candidates=[{content:{role:"user",parts:functionResponses}}],yield yield __await(typedResponseChunk);let newContents=[];newContents.push(...responseContents),newContents.push({role:"user",parts:functionResponses});let updatedContents=tContents(params2.contents).concat(newContents);params2.contents=updatedContents}else break}})})(this,afcToolsMap,params)}async generateContentInternal(params){var _a2,_b,_c,
1362
+ _d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).
1363
+ then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateContentResponseFromVertex(apiResponse),typedResp=new GenerateContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=generateContentParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body.
1364
+ _url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateContentResponseFromMldev(
1365
+ apiResponse),typedResp=new GenerateContentResponse;return Object.assign(typedResp,resp),typedResp})}}async generateContentStreamInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path:path2,queryParams,body:JSON.
1366
+ stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}),response.then(function(apiResponse){return __asyncGenerator(this,arguments,function*(){var _a3,e_3,_b2,_c2;try{for(var _d2=!0,apiResponse_1=__asyncValues(apiResponse),apiResponse_1_1;apiResponse_1_1=yield __await(apiResponse_1.next()),_a3=apiResponse_1_1.done,!_a3;_d2=!0){_c2=apiResponse_1_1.value,_d2=!1;let chunk=_c2,
1367
+ resp=generateContentResponseFromVertex(yield __await(chunk.json()),params);resp.sdkHttpResponse={headers:chunk.headers};let typedResp=new GenerateContentResponse;Object.assign(typedResp,resp),yield yield __await(typedResp)}}catch(e_3_1){e_3={error:e_3_1}}finally{try{!_d2&&!_a3&&(_b2=apiResponse_1.return)&&(yield __await(_b2.call(apiResponse_1)))}finally{if(e_3)throw e_3.error}}})})}else{let body=generateContentParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:streamGenerat\
1368
+ eContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}),response.then(function(apiResponse){return __asyncGenerator(this,arguments,function*(){var _a3,e_4,_b2,_c2;try{for(var _d2=!0,apiResponse_2=__asyncValues(apiResponse),
1369
+ apiResponse_2_1;apiResponse_2_1=yield __await(apiResponse_2.next()),_a3=apiResponse_2_1.done,!_a3;_d2=!0){_c2=apiResponse_2_1.value,_d2=!1;let chunk=_c2,resp=generateContentResponseFromMldev(yield __await(chunk.json()),params);resp.sdkHttpResponse={headers:chunk.headers};let typedResp=new GenerateContentResponse;Object.assign(typedResp,resp),yield yield __await(typedResp)}}catch(e_4_1){e_4={error:e_4_1}}finally{try{!_d2&&!_a3&&(_b2=apiResponse_2.return)&&(yield __await(_b2.call(apiResponse_2)))}finally{
1370
+ if(e_4)throw e_4.error}}})})}}async embedContentInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=embedContentParametersPrivateToVertex(this.apiClient,params,params),endpointUrl=tIsVertexEmbedContentModel(params.model)?"{model}:embedContent":"{model}:predict";return path2=formatMap(endpointUrl,body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(
1371
+ body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=embedContentResponseFromVertex(apiResponse,params),typedResp=new EmbedContentResponse;return Object.assign(typedResp,resp),typedResp})}else{
1372
+ let body=embedContentParametersPrivateToMldev(this.apiClient,params);return path2=formatMap("{model}:batchEmbedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;
1373
+ return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=embedContentResponseFromMldev(apiResponse),typedResp=new EmbedContentResponse;return Object.assign(typedResp,resp),typedResp})}}async generateImagesInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateImagesParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,
1374
+ delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateImagesResponseFromVertex(
1375
+ apiResponse),typedResp=new GenerateImagesResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async editImageInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=editImageParametersInternalToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body.
1376
+ _query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=editImageResponseFromVertex(apiResponse),typedResp=new EditImageResponse;
1377
+ return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=upscaleImageAPIParametersInternalToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.
1378
+ request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=upscaleImageResponseFromVertex(apiResponse),typedResp=new UpscaleImageResponse;
1379
+ return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=recontextImageParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,
1380
+ queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=recontextImageResponseFromVertex(apiResponse),typedResp=new RecontextImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent P\
1381
+ latform (previously known as Vertex AI).")}async segmentImage(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=segmentImageParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,
1382
+ abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=segmentImageResponseFromVertex(apiResponse),typedResp=new SegmentImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){
1383
+ let body=getModelParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromVertex(apiResponse))}else{
1384
+ let body=getModelParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromMldev(apiResponse))}}async listInternal(params){
1385
+ var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listModelsParametersToVertex(this.apiClient,params);return path2=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).
1386
+ then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listModelsResponseFromVertex(apiResponse),typedResp=new ListModelsResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=listModelsParametersToMldev(this.apiClient,params);return path2=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=
1387
+ this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listModelsResponseFromMldev(apiResponse),typedResp=new ListModelsResponse;
1388
+ return Object.assign(typedResp,resp),typedResp})}}async update(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=updateModelParametersToVertex(this.apiClient,params);return path2=formatMap("{model}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,
1389
+ abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromVertex(apiResponse))}else{let body=updateModelParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_c=params.config)===null||_c===void 0?void 0:
1390
+ _c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromMldev(apiResponse))}}async delete(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=deleteModelParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,
1391
+ queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteModelResponseFromVertex(apiResponse),typedResp=new DeleteModelResponse;return Object.
1392
+ assign(typedResp,resp),typedResp})}else{let body=deleteModelParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{
1393
+ let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteModelResponseFromMldev(apiResponse),typedResp=new DeleteModelResponse;return Object.assign(typedResp,resp),typedResp})}}async countTokens(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=countTokensParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:countTokens",body._url),queryParams=
1394
+ body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=countTokensResponseFromVertex(
1395
+ apiResponse),typedResp=new CountTokensResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=countTokensParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?
1396
+ void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=countTokensResponseFromMldev(apiResponse),typedResp=new CountTokensResponse;return Object.assign(typedResp,resp),typedResp})}}async computeTokens(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=computeTokensParametersToVertex(this.
1397
+ apiClient,params);return path2=formatMap("{model}:computeTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse=
1398
+ {headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=computeTokensResponseFromVertex(apiResponse),typedResp=new ComputeTokensResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateVideosParametersToVertex(
1399
+ this.apiClient,params);return path2=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=generateVideosOperationFromVertex(
1400
+ apiResponse),typedResp=new GenerateVideosOperation;return Object.assign(typedResp,resp),typedResp})}else{let body=generateVideosParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||
1401
+ _d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=generateVideosOperationFromMldev(apiResponse),typedResp=new GenerateVideosOperation;return Object.assign(typedResp,resp),typedResp})}}};Models.loggedGenerateImagesWarning=!1;Models.loggedEditImageWarning=!1;Models.loggedGenerateVideosWarning=!1;var Operations=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient}async getVideosOperation(parameters){let operation=parameters.
1402
+ operation,config=parameters.config;if(operation.name===void 0||operation.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let resourceName2=operation.name.split("/operations/")[0],httpOptions;config&&"httpOptions"in config&&(httpOptions=config.httpOptions);let rawOperation=await this.fetchPredictVideosOperationInternal({operationName:operation.name,resourceName:resourceName2,config:{httpOptions}});return operation._fromAPIResponse({apiResponse:rawOperation,
1403
+ _isVertexAI:!0})}else{let rawOperation=await this.getVideosOperationInternal({operationName:operation.name,config});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!1})}}async get(parameters){let operation=parameters.operation,config=parameters.config;if(operation.name===void 0||operation.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let resourceName2=operation.name.split("/operations/")[0],httpOptions;config&&"httpOptions"in config&&
1404
+ (httpOptions=config.httpOptions);let rawOperation=await this.fetchPredictVideosOperationInternal({operationName:operation.name,resourceName:resourceName2,config:{httpOptions}});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!0})}else{let rawOperation=await this.getVideosOperationInternal({operationName:operation.name,config});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!1})}}async getVideosOperationInternal(params){var _a2,_b,_c,_d;let response,
1405
+ path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getOperationParametersToVertex(params);return path2=formatMap("{operationName}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),
1406
+ response}else{let body=getOperationParametersToMldev(params);return path2=formatMap("{operationName}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response}}async fetchPredictVideosOperationInternal(params){
1407
+ var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=fetchPredictOperationParametersToVertex(params);return path2=formatMap("{resourceName}:fetchPredictOperation",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:
1408
+ _b.abortSignal}).then(httpResponse=>httpResponse.json()),response}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};function authConfigToMldev(fromObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise A\
1409
+ gent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasic\
1410
+ AuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platfor\
1411
+ m mode, not in Gemini Developer API mode.");return toObject}function contentToMldev(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createAuthTokenConfigToMldev(apiClient,fromObject,parentObject){
1412
+ let toObject={},fromExpireTime=getValueByPath(fromObject,["expireTime"]);parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime);let fromNewSessionExpireTime=getValueByPath(fromObject,["newSessionExpireTime"]);parentObject!==void 0&&fromNewSessionExpireTime!=null&&setValueByPath(parentObject,["newSessionExpireTime"],fromNewSessionExpireTime);let fromUses=getValueByPath(fromObject,["uses"]);parentObject!==void 0&&fromUses!=null&&setValueByPath(parentObject,
1413
+ ["uses"],fromUses);let fromLiveConnectConstraints=getValueByPath(fromObject,["liveConnectConstraints"]);parentObject!==void 0&&fromLiveConnectConstraints!=null&&setValueByPath(parentObject,["bidiGenerateContentSetup"],liveConnectConstraintsToMldev(apiClient,fromLiveConnectConstraints));let fromLockAdditionalFields=getValueByPath(fromObject,["lockAdditionalFields"]);return parentObject!==void 0&&fromLockAdditionalFields!=null&&setValueByPath(parentObject,["fieldMask"],fromLockAdditionalFields),toObject}
1414
+ function createAuthTokenParametersToMldev(apiClient,fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["config"],createAuthTokenConfigToMldev(apiClient,fromConfig,toObject)),toObject}function functionCallToMldev(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,
1415
+ ["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mod\
1416
+ e.");return toObject}function googleMapsToMldev(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Ge\
1417
+ mini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev(fromObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platf\
1418
+ orm mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function liveConnectConfigToMldev(fromObject,parentObject){let toObject={},fromGenerationConfig=getValueByPath(fromObject,["generati\
1419
+ onConfig"]);parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig"],fromGenerationConfig);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);parentObject!==void 0&&fromResponseModalities!=null&&setValueByPath(parentObject,["setup","generationConfig","responseModalities"],fromResponseModalities);let fromTemperature=getValueByPath(fromObject,["temperature"]);parentObject!==void 0&&fromTemperature!=null&&setValueByPath(parentObject,
1420
+ ["setup","generationConfig","temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);parentObject!==void 0&&fromTopP!=null&&setValueByPath(parentObject,["setup","generationConfig","topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);parentObject!==void 0&&fromTopK!=null&&setValueByPath(parentObject,["setup","generationConfig","topK"],fromTopK);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&
1421
+ setValueByPath(parentObject,["setup","generationConfig","maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);parentObject!==void 0&&fromMediaResolution!=null&&setValueByPath(parentObject,["setup","generationConfig","mediaResolution"],fromMediaResolution);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["setup","generationConfig","seed"],fromSeed);let fromSpeechConfig=getValueByPath(
1422
+ fromObject,["speechConfig"]);parentObject!==void 0&&fromSpeechConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","speechConfig"],tLiveSpeechConfig(fromSpeechConfig));let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);parentObject!==void 0&&fromThinkingConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","thinkingConfig"],fromThinkingConfig);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);parentObject!==void 0&&
1423
+ fromEnableAffectiveDialog!=null&&setValueByPath(parentObject,["setup","generationConfig","enableAffectiveDialog"],fromEnableAffectiveDialog);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["setup","systemInstruction"],contentToMldev(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);
1424
+ Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev(tTool(item)))),setValueByPath(parentObject,["setup","tools"],transformedList)}let fromSessionResumption=getValueByPath(fromObject,["sessionResumption"]);parentObject!==void 0&&fromSessionResumption!=null&&setValueByPath(parentObject,["setup","sessionResumption"],sessionResumptionConfigToMldev(fromSessionResumption));let fromInputAudioTranscription=getValueByPath(fromObject,["inputAudioTranscription"]);parentObject!==
1425
+ void 0&&fromInputAudioTranscription!=null&&setValueByPath(parentObject,["setup","inputAudioTranscription"],fromInputAudioTranscription);let fromOutputAudioTranscription=getValueByPath(fromObject,["outputAudioTranscription"]);parentObject!==void 0&&fromOutputAudioTranscription!=null&&setValueByPath(parentObject,["setup","outputAudioTranscription"],fromOutputAudioTranscription);let fromRealtimeInputConfig=getValueByPath(fromObject,["realtimeInputConfig"]);parentObject!==void 0&&fromRealtimeInputConfig!=
1426
+ null&&setValueByPath(parentObject,["setup","realtimeInputConfig"],fromRealtimeInputConfig);let fromContextWindowCompression=getValueByPath(fromObject,["contextWindowCompression"]);parentObject!==void 0&&fromContextWindowCompression!=null&&setValueByPath(parentObject,["setup","contextWindowCompression"],fromContextWindowCompression);let fromProactivity=getValueByPath(fromObject,["proactivity"]);if(parentObject!==void 0&&fromProactivity!=null&&setValueByPath(parentObject,["setup","proactivity"],fromProactivity),
1427
+ getValueByPath(fromObject,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromAvatarConfig=getValueByPath(fromObject,["avatarConfig"]);parentObject!==void 0&&fromAvatarConfig!=null&&setValueByPath(parentObject,["setup","avatarConfig"],fromAvatarConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){
1428
+ let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev(item))),setValueByPath(parentObject,["setup","safetySettings"],transformedList)}let fromTranslationConfig=getValueByPath(fromObject,["translationConfig"]);return parentObject!==void 0&&fromTranslationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","translationConfig"],fromTranslationConfig),toObject}function liveConnectConstraintsToMldev(apiClient,fromObject){
1429
+ let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["setup","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["config"],liveConnectConfigToMldev(fromConfig,toObject)),toObject}function partToMldev(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolu\
1430
+ tion"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(
1431
+ fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=
1432
+ null&&setValueByPath(toObject,["functionCall"],functionCallToMldev(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);
1433
+ let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMet\
1434
+ adata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing);let fromSpeechMetadata=getValueByPath(fromObject,["speechMetadata"]);return fromSpeechMetadata!=null&&setValueByPath(toObject,["speechMetadata"],fromSpeechMetadata),toObject}function safetySettingToMldev(fromObject){let toObject={},fromCategory=getValueByPath(
1435
+ fromObject,["category"]);if(fromCategory!=null&&setValueByPath(toObject,["category"],fromCategory),getValueByPath(fromObject,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThreshold=getValueByPath(fromObject,["threshold"]);return fromThreshold!=null&&setValueByPath(toObject,["threshold"],fromThreshold),toObject}function sessionResumptionConfigToMldev(fromObject){let toObject={},fromHandle=getValueByPath(
1436
+ fromObject,["handle"]);if(fromHandle!=null&&setValueByPath(toObject,["handle"],fromHandle),getValueByPath(fromObject,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function toolToMldev(fromObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in \
1437
+ Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeE\
1438
+ xecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)
1439
+ throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleS\
1440
+ earch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mo\
1441
+ de.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function getFieldMasks(setup){let fields=[];for(let key in setup)if(Object.prototype.hasOwnProperty.call(setup,key)){let value=setup[key];if(typeof value=="object"&&value!=null&&Object.keys(value).length>
1442
+ 0){let field=Object.keys(value).map(kk=>`${key}.${kk}`);fields.push(...field)}else fields.push(key)}return fields.join(",")}function convertBidiSetupToTokenSetup(requestDict,config){let setupForMaskGeneration=null,bidiGenerateContentSetupValue=requestDict.bidiGenerateContentSetup;if(typeof bidiGenerateContentSetupValue=="object"&&bidiGenerateContentSetupValue!==null&&"setup"in bidiGenerateContentSetupValue){let innerSetup=bidiGenerateContentSetupValue.setup;typeof innerSetup=="object"&&innerSetup!==
1443
+ null?(requestDict.bidiGenerateContentSetup=innerSetup,setupForMaskGeneration=innerSetup):delete requestDict.bidiGenerateContentSetup}else bidiGenerateContentSetupValue!==void 0&&delete requestDict.bidiGenerateContentSetup;let preExistingFieldMask=requestDict.fieldMask;if(setupForMaskGeneration){let generatedMaskFromBidi=getFieldMasks(setupForMaskGeneration);if(Array.isArray(config?.lockAdditionalFields)&&config?.lockAdditionalFields.length===0)generatedMaskFromBidi?requestDict.fieldMask=generatedMaskFromBidi:
1444
+ delete requestDict.fieldMask;else if(config?.lockAdditionalFields&&config.lockAdditionalFields.length>0&&preExistingFieldMask!==null&&Array.isArray(preExistingFieldMask)&&preExistingFieldMask.length>0){let generationConfigFields=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],mappedFieldsFromPreExisting=[];preExistingFieldMask.length>0&&(mappedFieldsFromPreExisting=preExistingFieldMask.map(field=>generationConfigFields.includes(field)?`generationConfig.${field}`:
1445
+ field));let finalMaskParts=[];generatedMaskFromBidi&&finalMaskParts.push(generatedMaskFromBidi),mappedFieldsFromPreExisting.length>0&&finalMaskParts.push(...mappedFieldsFromPreExisting),finalMaskParts.length>0?requestDict.fieldMask=finalMaskParts.join(","):delete requestDict.fieldMask}else delete requestDict.fieldMask}else preExistingFieldMask!==null&&Array.isArray(preExistingFieldMask)&&preExistingFieldMask.length>0?requestDict.fieldMask=preExistingFieldMask.join(","):delete requestDict.fieldMask;
1446
+ return requestDict}var Tokens=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient}async create(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let body=createAuthTokenParametersToMldev(this.apiClient,params);path2=formatMap("auth_tokens",body._url),queryParams=body._query,delete body.config,delete body._url,delete body._query;let transformedBody=convertBidiSetupToTokenSetup(
1447
+ body,params.config);return response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(transformedBody),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}};function deleteDocumentConfigToMldev(fromObject,parentObject){let toObject={},fromForce=getValueByPath(fromObject,["force"]);return parentObject!==
1448
+ void 0&&fromForce!=null&&setValueByPath(parentObject,["_query","force"],fromForce),toObject}function deleteDocumentParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url","name"],fromName);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&deleteDocumentConfigToMldev(fromConfig,toObject),toObject}function getDocumentParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,
1449
+ ["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function listDocumentsConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),
1450
+ toObject}function listDocumentsParametersToMldev(fromObject){let toObject={},fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["_url","parent"],fromParent);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listDocumentsConfigToMldev(fromConfig,toObject),toObject}function listDocumentsResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(
1451
+ toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromDocuments=getValueByPath(fromObject,["documents"]);if(fromDocuments!=null){let transformedList=fromDocuments;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["documents"],transformedList)}return toObject}var Documents=class extends BaseModule{constructor(apiClient){
1452
+ super(),this.apiClient=apiClient,this.list=async params=>new Pager(PagedItem.PAGED_ITEM_DOCUMENTS,x=>this.listInternal({parent:params.parent,config:x.config}),await this.listInternal(params),params)}async get(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=getDocumentParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body.
1453
+ _url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b;let path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Develop\
1454
+ er API.");{let body=deleteDocumentParametersToMldev(params);path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,await this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal})}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.
1455
+ isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=listDocumentsParametersToMldev(params);return path2=formatMap("{parent}/documents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).
1456
+ then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=listDocumentsResponseFromMldev(apiResponse),typedResp=new ListDocumentsResponse;return Object.assign(typedResp,resp),typedResp})}}};var FileSearchStores=class extends BaseModule{constructor(apiClient,documents=new Documents(apiClient)){super(),this.apiClient=apiClient,this.documents=documents,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_FILE_SEARCH_STORES,x=>this.listInternal(x),await this.listInternal(params),
1457
+ params)}async uploadToFileSearchStore(params){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(params.fileSearchStoreName,params.file,params.config)}async downloadMedia(uri,config){if(this.apiClient.isVertexAI())throw new Error("This method is only supported in the Gemini Developer client.");let parsedUri=new URL(uri,"http://\
1458
+ dummy.com"),pathname=parsedUri.pathname;if(pathname.startsWith("/")&&(pathname=pathname.slice(1)),!pathname.includes("/media/"))throw new Error(`Invalid uri format: ${uri}. Expected to contain /media/`);let queryParams={};parsedUri.searchParams.forEach((value,key)=>{queryParams[key]=value}),queryParams.alt="media";let httpOptions=Object.assign({},config?.httpOptions),response=await this.apiClient.request({path:pathname,httpMethod:"GET",queryParams,httpOptions});if(response instanceof HttpResponse){
1459
+ let arrayBuffer=await response.responseInternal.arrayBuffer();return new Uint8Array(arrayBuffer)}else throw new Error("Unexpected response type from downloadMedia")}async create(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createFileSearchStoreParametersToMldev(this.apiClient,params);return path2=formatMap("fileSearchStores",body._url),queryParams=body._query,delete body.
1460
+ _url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async get(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini \
1461
+ Developer API.");{let body=getFileSearchStoreParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){
1462
+ var _a2,_b;let path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=deleteFileSearchStoreParametersToMldev(params);path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,await this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===
1463
+ null||_b===void 0?void 0:_b.abortSignal})}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=listFileSearchStoresParametersToMldev(params);return path2=formatMap("fileSearchStores",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=
1464
+ params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=listFileSearchStoresResponseFromMldev(apiResponse),typedResp=new ListFileSearchStoresResponse;return Object.assign(typedResp,resp),typedResp})}}async uploadToFileSearchStoreInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("Thi\
1465
+ s method is only supported by the Gemini Developer API.");{let body=uploadToFileSearchStoreParametersToMldev(params);return path2=formatMap("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?
1466
+ void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=uploadToFileSearchStoreResumableResponseFromMldev(apiResponse),typedResp=new UploadToFileSearchStoreResumableResponse;return Object.assign(typedResp,resp),typedResp})}}async importFile(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=importFileParametersToMldev(params);return path2=
1467
+ formatMap("{file_search_store_name}:importFile",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=importFileOperationFromMldev(apiResponse),typedResp=new ImportFileOperation;
1468
+ return Object.assign(typedResp,resp),typedResp})}}};function isDeno(){return"Deno"in globalThis}var envMemo;function env(){var _a2,_b,_c,_d,_e,_f;if(envMemo)return envMemo;let globals=globalThis,envObject={};return isDeno()?envObject=(_d=(_c=(_b=(_a2=globals.Deno)===null||_a2===void 0?void 0:_a2.env)===null||_b===void 0?void 0:_b.toObject)===null||_c===void 0?void 0:_c.call(_b))!==null&&_d!==void 0?_d:{}:envObject=(_f=(_e=globals.process)===null||_e===void 0?void 0:_e.env)!==null&&_f!==void 0?_f:
1469
+ {},envMemo=envObject,envMemo}function fillGlobals(options){var _a2,_b;let clone=Object.assign({},options),envVars=env();return typeof envVars.GOOGLE_GENAI_API_VERSION<"u"&&((_a2=clone.api_version)!==null&&_a2!==void 0||(clone.api_version=envVars.GOOGLE_GENAI_API_VERSION)),typeof envVars.GOOGLE_GENAI_USER_PROJECT<"u"&&((_b=clone.user_project)!==null&&_b!==void 0||(clone.user_project=envVars.GOOGLE_GENAI_USER_PROJECT)),clone}var UNDICI_GLOBAL_DISPATCHER_SYMBOL=Symbol.for("undici.globalDispatcher.1"),
1470
+ GoogleGenAISecurityProvider=class{constructor(options){this.options=options}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(url){return securityFromHeaders(await this.options.getAuthHeaders(url))}},GoogleGenAIAuthHook=class{beforeCreateRequest(hookCtx,input){var _a2;let options=Object.assign({},(_a2=input.options)!==null&&_a2!==void 0?_a2:{});return isNodeRuntime()&&!hasCustomHttpClient(hookCtx.options.http_client)&&!("dispatcher"in options)&&(options.dispatcher=
1471
+ createUndiciNoTimeoutDispatcher()),Object.assign(Object.assign({},input),{url:decodeSDKLevelAPIVersionPath(input.url),options})}async beforeRequest(hookCtx,request){if(applyDefaultHeaders(request.headers,getStaticDefaultHeaders(hookCtx.security_source)),applyUserProject(hookCtx,request.headers),hasAuthHeaders(request.headers))return request;let security=await resolveSecurity$1(hookCtx.security_source,request.url);return applyDefaultHeaders(request.headers,security?.default_headers),applyAuth(request.
1472
+ headers,security),request}};function decodeSDKLevelAPIVersionPath(url){let[,apiVersion,...rest]=url.pathname.split("/");if(!apiVersion)return url;let decodedAPIVersion=decodeURIComponent(apiVersion);if(!decodedAPIVersion.includes("/"))return url;let nextURL=new URL(url);return nextURL.pathname=`/${decodedAPIVersion}/${rest.join("/")}`,nextURL}async function resolveSecurity$1(securitySource,requestURL){if(isSecurityResolver(securitySource))return securitySource.resolveGoogleGenAISecurity(requestURL);
1473
+ let security=typeof securitySource=="function"?await securitySource():securitySource;return isSecurity(security)?withEnvSecurity(security):withEnvSecurity(void 0)}function getStaticDefaultHeaders(securitySource){var _a2,_b;if(isSecurityResolver(securitySource))return(_b=(_a2=securitySource.getDefaultHeaders)===null||_a2===void 0?void 0:_a2.call(securitySource))!==null&&_b!==void 0?_b:securitySource.defaultHeaders;if(isSecurity(securitySource))return securitySource.default_headers}function withEnvSecurity(security){
1474
+ var _a2,_b;let envVars=env(),nextSecurity=Object.assign(Object.assign({},security),{api_key:(_a2=security?.api_key)!==null&&_a2!==void 0?_a2:envVars.GOOGLE_GENAI_API_KEY,access_token:(_b=security?.access_token)!==null&&_b!==void 0?_b:envVars.GOOGLE_GENAI_ACCESS_TOKEN});return hasSecurityValue(nextSecurity)?nextSecurity:void 0}function securityFromHeaders(headers){var _a2,_b;let defaultHeaders={};for(let[key,value]of headers){let lowerKey=key.toLowerCase();lowerKey!=="authorization"&&lowerKey!=="\
1475
+ x-goog-api-key"&&(defaultHeaders[key]=value)}let security={access_token:(_a2=headers.get("authorization"))!==null&&_a2!==void 0?_a2:void 0,api_key:(_b=headers.get("x-goog-api-key"))!==null&&_b!==void 0?_b:void 0,default_headers:Object.keys(defaultHeaders).length?defaultHeaders:void 0};return hasSecurityValue(security)?security:void 0}function applyDefaultHeaders(target,source){if(source)for(let[key,value]of new Headers(source))target.get(key)===null&&target.set(key,value)}function applyUserProject(hookCtx,headers){
1476
+ hookCtx.options.user_project!==void 0&&headers.get("x-goog-user-project")===null&&headers.set("x-goog-user-project",hookCtx.options.user_project)}function applyAuth(headers,security){if(security){if(security.api_key){headers.set("x-goog-api-key",security.api_key);return}security.access_token&&headers.set("Authorization",bearer(security.access_token))}}function hasAuthHeaders(headers){return headers.get("authorization")!==null||headers.get("x-goog-api-key")!==null}function bearer(token){return token.
1477
+ slice(0,7).toLowerCase()==="bearer "?token:`Bearer ${token}`}function isSecurity(value){return typeof value=="object"&&value!==null}function isSecurityResolver(value){return typeof value=="object"&&value!==null&&"resolveGoogleGenAISecurity"in value&&typeof value.resolveGoogleGenAISecurity=="function"}function hasSecurityValue(security){return security.api_key!==void 0||security.access_token!==void 0||security.default_headers!==void 0}function isNodeRuntime(){var _a2,_b;return typeof((_b=(_a2=globalThis.
1478
+ process)===null||_a2===void 0?void 0:_a2.versions)===null||_b===void 0?void 0:_b.node)=="string"}function hasCustomHttpClient(httpClient){if(!httpClient||typeof httpClient!="object")return!1;if("options"in httpClient){let opts=httpClient.options;return!!opts?.fetcher}return!0}function createUndiciNoTimeoutDispatcher(){return{dispatch(opts,handler){let globalDispatcher=globalThis[UNDICI_GLOBAL_DISPATCHER_SYMBOL];if(!globalDispatcher||typeof globalDispatcher.dispatch!="function")throw new TypeError(
1479
+ "Undici globalDispatcher is not available in this Node.js runtime.");return globalDispatcher.dispatch(Object.assign(Object.assign({},opts),{headersTimeout:0,bodyTimeout:0}),handler)}}}var HTTPClientError=class extends Error{constructor(message,opts){let msg=message;opts?.cause&&(msg+=`: ${opts.cause}`),super(msg,opts),this.name="HTTPClientError",typeof this.cause>"u"&&(this.cause=opts?.cause)}},UnexpectedClientError=class extends HTTPClientError{constructor(){super(...arguments),this.name="Unexp\
1480
+ ectedClientError"}},InvalidRequestError=class extends HTTPClientError{constructor(){super(...arguments),this.name="InvalidRequestError"}},RequestAbortedError=class extends HTTPClientError{constructor(){super(...arguments),this.name="RequestAbortedError"}},RequestTimeoutError=class extends HTTPClientError{constructor(){super(...arguments),this.name="RequestTimeoutError"}},ConnectionError=class extends HTTPClientError{constructor(){super(...arguments),this.name="ConnectionError"}};var GoogleGenAiError=class extends Error{constructor(message,httpMeta){
1481
+ var _a2,_b,_c,_d;super(message),this.statusCode=(_a2=httpMeta?.response)===null||_a2===void 0?void 0:_a2.status,this.body=(_b=httpMeta?.body)!==null&&_b!==void 0?_b:"",this.headers=(_c=httpMeta?.response)===null||_c===void 0?void 0:_c.headers,this.contentType=((_d=httpMeta?.response)===null||_d===void 0?void 0:_d.headers.get("content-type"))||"",this.rawResponse=httpMeta?.response,this.name="GoogleGenAiError"}};var GeminiNextGenAPIClientError=class extends Error{},APIError=class _APIError extends GeminiNextGenAPIClientError{constructor(status,error,message,headers){
1482
+ super(_APIError.makeMessage(status,error,message)),this.status=status,this.headers=headers,this.error=error,this.statusCode=status,this.body=stringifyErrorBody(error),this.contentType=headers?.get("content-type")||"",this.rawResponse=void 0,this.cause=void 0,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}static makeMessage(status,error,message){var _a2;let errorMessage=error&&isPlainObject$2(error)&&typeof error.message=="string"?error.message:void 0,errorBody=stringifyErrorBody(
1483
+ error),msg=(_a2=errorMessage??message)!==null&&_a2!==void 0?_a2:errorBody||"An error occurred";return`${status?`${status} `:""}${msg}`}static generate(status,errorResponse,message,headers){return!status||!headers?new APIConnectionError({message,cause:errorResponse instanceof Error?errorResponse:void 0}):status===400?new BadRequestError(status,errorResponse,message,headers):status===401?new AuthenticationError(status,errorResponse,message,headers):status===403?new PermissionDeniedError(status,errorResponse,
1484
+ message,headers):status===404?new NotFoundError(status,errorResponse,message,headers):status===409?new ConflictError(status,errorResponse,message,headers):status===422?new UnprocessableEntityError(status,errorResponse,message,headers):status===429?new RateLimitError(status,errorResponse,message,headers):status>=500?new InternalServerError(status,errorResponse,message,headers):new _APIError(status,errorResponse,message,headers)}},APIUserAbortError=class extends APIError{constructor({message}={}){
1485
+ super(void 0,void 0,message||"Request was aborted.",void 0)}},APIConnectionError=class extends APIError{constructor({message,cause}){super(void 0,void 0,message||"Connection error.",void 0),this.cause=cause}},APIConnectionTimeoutError=class extends APIConnectionError{constructor({message}={}){super({message:message||"Request timed out. This is a client-side timeout. You can increase the timeout by setting the `timeout` argument in your request or client http options."})}},BadRequestError=class extends APIError{},
1486
+ AuthenticationError=class extends APIError{},PermissionDeniedError=class extends APIError{},NotFoundError=class extends APIError{},ConflictError=class extends APIError{},UnprocessableEntityError=class extends APIError{},RateLimitError=class extends APIError{},InternalServerError=class extends APIError{};function wrapSDKError(error){return isCompatAPIErrorInstance(error)?error:error instanceof GoogleGenAiError?wrapAPIError(error):error instanceof HTTPClientError?wrapHTTPClientError(error):error}function wrapAPIError(error){
1487
+ let errorPayload=getErrorPayload(error),wrapped=APIError.generate(error.statusCode,errorPayload,error.message,error.headers);return defineReadonly(wrapped,"body",error.body),defineReadonly(wrapped,"contentType",error.contentType),defineReadonly(wrapped,"rawResponse",error.rawResponse),defineReadonly(wrapped,"statusCode",error.statusCode),defineReadonly(wrapped,"cause",error),wrapped}function wrapHTTPClientError(error){return error instanceof RequestTimeoutError?new APIConnectionTimeoutError({message:error.
1488
+ message}):error instanceof RequestAbortedError?new APIUserAbortError({message:error.message}):error instanceof ConnectionError?new APIConnectionError({message:error.message,cause:error}):new APIConnectionError({message:error.message,cause:error})}function getErrorPayload(error){let data=getObjectProperty(error,"data$");if(data&&typeof data=="object")return data;try{let parsed=JSON.parse(error.body);if(parsed&&typeof parsed=="object")return parsed}catch{}let dataError=getObjectProperty(error,"err\
1489
+ or");return dataError&&typeof dataError=="object"?dataError:void 0}function getObjectProperty(value,key){return value&&typeof value=="object"?value[key]:void 0}function stringifyErrorBody(error){if(!error)return"";try{return JSON.stringify(error)}catch{return String(error)}}function isPlainObject$2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isCompatAPIErrorInstance(value){return typeof value=="object"&&value!==null?APIError.prototype.isPrototypeOf(value):!1}
1490
+ function defineReadonly(target,key,value){Object.defineProperty(target,key,{configurable:!0,enumerable:!0,value,writable:!1})}var DEFAULT_FETCHER=(input,init)=>init==null?fetch(input):fetch(input,init),HTTPClient=class _HTTPClient{constructor(options={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=options,this.fetcher=options.fetcher||DEFAULT_FETCHER}async request(request){let req=request;for(let hook of this.requestHooks){let nextRequest=await hook(req);nextRequest&&
1491
+ (req=nextRequest)}try{let res=await this.fetcher(req);for(let hook of this.responseHooks)await hook(res,req);return res}catch(err){for(let hook of this.requestErrorHooks)await hook(err,req);throw err}}addHook(...args){if(args[0]==="beforeRequest")this.requestHooks.push(args[1]);else if(args[0]==="requestError")this.requestErrorHooks.push(args[1]);else if(args[0]==="response")this.responseHooks.push(args[1]);else throw new Error(`Invalid hook type: ${args[0]}`);return this}removeHook(...args){let target;
1492
+ if(args[0]==="beforeRequest")target=this.requestHooks;else if(args[0]==="requestError")target=this.requestErrorHooks;else if(args[0]==="response")target=this.responseHooks;else throw new Error(`Invalid hook type: ${args[0]}`);let index=target.findIndex(v=>v===args[1]);return index>=0&&target.splice(index,1),this}clone(){let child=new _HTTPClient(this.options);return child.requestHooks=this.requestHooks.slice(),child.requestErrorHooks=this.requestErrorHooks.slice(),child.responseHooks=this.responseHooks.
1493
+ slice(),child}},mediaParamSeparator=/\s*;\s*/g;function matchContentType(response,pattern){var _a2;if(pattern==="*")return!0;let contentType=((_a2=response.headers.get("content-type"))===null||_a2===void 0?void 0:_a2.trim())||"application/octet-stream";contentType=contentType.toLowerCase();let wantParts=pattern.toLowerCase().trim().split(mediaParamSeparator),[wantType="",...wantParams]=wantParts;if(wantType.split("/").length!==2)return!1;let gotParts=contentType.split(mediaParamSeparator),[gotType="",
1494
+ ...gotParams]=gotParts,[type="",subtype=""]=gotType.split("/");if(!type||!subtype||wantType!=="*/*"&&gotType!==wantType&&`${type}/*`!==wantType&&`*/${subtype}`!==wantType||gotParams.length<wantParams.length)return!1;let params=new Set(gotParams);for(let wantParam of wantParams)if(!params.has(wantParam))return!1;return!0}var codeRangeRE$1=new RegExp("^[0-9]xx$","i");function matchStatusCode(response,codes){let actual=`${response.status}`,expectedCodes=Array.isArray(codes)?codes:[codes];return expectedCodes.
1495
+ length?expectedCodes.some(ec=>{let code=`${ec}`;if(code==="default")return!0;if(!codeRangeRE$1.test(`${code}`))return code===actual;let expectFamily=code.charAt(0);if(!expectFamily)throw new Error("Invalid status code range");let actualFamily=actual.charAt(0);if(!actualFamily)throw new Error(`Invalid response status code: ${actual}`);return actualFamily===expectFamily}):!1}function matchResponse(response,code,contentTypePattern){return matchStatusCode(response,code)&&matchContentType(response,contentTypePattern)}
1496
+ function isConnectionError(err){if(typeof err!="object"||err==null)return!1;let isBrowserErr=err instanceof TypeError&&err.message.toLowerCase().startsWith("failed to fetch"),isNodeErr=err instanceof TypeError&&err.message.toLowerCase().startsWith("fetch failed"),isBunErr="name"in err&&err.name==="ConnectionError",isGenericErr="code"in err&&typeof err.code=="string"&&err.code.toLowerCase()==="econnreset";return isBrowserErr||isNodeErr||isGenericErr||isBunErr}function isTimeoutError(err){if(typeof err!=
1497
+ "object"||err==null)return!1;let isNative="name"in err&&err.name==="TimeoutError",isLegacyNative="code"in err&&err.code===23,isGenericErr="code"in err&&typeof err.code=="string"&&err.code.toLowerCase()==="econnaborted";return isNative||isLegacyNative||isGenericErr}function isAbortError(err){if(typeof err!="object"||err==null)return!1;let isNative="name"in err&&err.name==="AbortError",isLegacyNative="code"in err&&err.code===20,isGenericErr="code"in err&&typeof err.code=="string"&&err.code.toLowerCase()===
1498
+ "econnaborted";return isNative||isLegacyNative||isGenericErr}function initHooks(hooks){let googleGenAIAuthHook=new GoogleGenAIAuthHook;hooks.registerBeforeCreateRequestHook(googleGenAIAuthHook),hooks.registerBeforeRequestHook(googleGenAIAuthHook)}var SDKHooks=class{constructor(){this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[];let presetHooks=[];for(let hook of presetHooks)"sdkInit"in hook&&this.registerSDKInitHook(
1499
+ hook),"beforeCreateRequest"in hook&&this.registerBeforeCreateRequestHook(hook),"beforeRequest"in hook&&this.registerBeforeRequestHook(hook),"afterSuccess"in hook&&this.registerAfterSuccessHook(hook),"afterError"in hook&&this.registerAfterErrorHook(hook);initHooks(this)}registerSDKInitHook(hook){this.sdkInitHooks.push(hook)}registerBeforeCreateRequestHook(hook){this.beforeCreateRequestHooks.push(hook)}registerBeforeRequestHook(hook){this.beforeRequestHooks.push(hook)}registerAfterSuccessHook(hook){
1500
+ this.afterSuccessHooks.push(hook)}registerAfterErrorHook(hook){this.afterErrorHooks.push(hook)}sdkInit(opts){return this.sdkInitHooks.reduce((opts2,hook)=>hook.sdkInit(opts2),opts)}beforeCreateRequest(hookCtx,input){let inp=input;for(let hook of this.beforeCreateRequestHooks)inp=hook.beforeCreateRequest(hookCtx,inp);return inp}async beforeRequest(hookCtx,request){let req=request;for(let hook of this.beforeRequestHooks)req=await hook.beforeRequest(hookCtx,req);return req}async afterSuccess(hookCtx,response){
1501
+ let res=response;for(let hook of this.afterSuccessHooks)res=await hook.afterSuccess(hookCtx,res);return res}async afterError(hookCtx,response,error){let res=response,err=error;for(let hook of this.afterErrorHooks){let result=await hook.afterError(hookCtx,res,err);res=result.response,err=result.error}return{response:res,error:err}}};function OK(value){return{ok:!0,value}}function ERR(error){return{ok:!1,error}}function bytesToBase64(u8arr){return btoa(String.fromCodePoint(...u8arr))}function stringToBytes(str){
1502
+ return new TextEncoder().encode(str)}function stringToBase64(str){return bytesToBase64(stringToBytes(str))}var hasOwn=Object.prototype.hasOwnProperty;function pathToFunc(pathPattern,options){let paramRE=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(params={}){return pathPattern.replace(paramRE,function(_,placeholder){if(!hasOwn.call(params,placeholder))throw new Error(`Parameter '${placeholder}' is required`);let value=params[placeholder];if(typeof value!="string"&&typeof value!="number")
1503
+ throw new Error(`Parameter '${placeholder}' must be a string or number`);return`${value}`}).replace(/^\/+/,"")}}var ServerList=["https://generativelanguage.googleapis.com"];function serverURLFromOptions(options){var _a2;let serverURL=options.server_url,params={};if(!serverURL){let serverIdx=(_a2=options.server_idx)!==null&&_a2!==void 0?_a2:0;if(serverIdx<0||serverIdx>=ServerList.length)throw new Error(`Invalid server index ${serverIdx}`);serverURL=ServerList[serverIdx]||""}let u=pathToFunc(serverURL)(
1504
+ params);return new URL(u)}var SDK_METADATA={userAgent:"speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai"};function combineSignals(...signals){let filtered=[];for(let signal of signals)signal&&filtered.push(signal);switch(filtered.length){case 0:case 1:return filtered[0]||null;default:return"any"in AbortSignal&&typeof AbortSignal.any=="function"?AbortSignal.any(filtered):abortSignalAny(filtered)}}function abortSignalAny(signals){let controller=new AbortController,result=controller.
1505
+ signal;if(!signals.length)return controller.signal;if(signals.length===1)return signals[0]||controller.signal;for(let signal of signals)if(signal.aborted)return signal;function abort(){controller.abort(this.reason),clean()}let signalRefs=[];function clean(){for(let signalRef of signalRefs){let signal=signalRef.deref();signal&&signal.removeEventListener("abort",abort)}}for(let signal of signals)signalRefs.push(new WeakRef(signal)),signal.addEventListener("abort",abort);return result}function compactMap(values){
1506
+ let out={};for(let[k,v]of Object.entries(values))typeof v<"u"&&(out[k]=v);return out}function isPlainObject$1(value){if(value===null||typeof value!="object"||Object.prototype.toString.call(value)!=="[object Object]")return!1;let proto=Object.getPrototypeOf(value);if(proto===null||proto===Object.prototype)return!0;try{return Object.getPrototypeOf(proto)===null}catch{return!1}}var reservedEscapes=/%(2[346bcf]|3[abdf]|40|5[bd])/gi;function encodeKeyChars(v,charEncoding){return encodeChars(v,charEncoding===
1507
+ "percentExceptReserved"?"percent":charEncoding)}function encodeChars(v,charEncoding){switch(charEncoding){case"percent":return encodeURIComponent(v);case"percentExceptReserved":return encodeURIComponent(v).replace(reservedEscapes,m=>decodeURIComponent(m));default:return v}}function formEncoder(sep){return(key,value,options)=>{let out="",pairs=options?.explode?explode(key,value):[[key,value]];if(pairs.every(([_,v])=>v==null))return;let encodeString=v=>encodeChars(v,options?.charEncoding),encodeValue=v=>encodeString(
1508
+ serializeValue(v)),encodedSep=encodeString(sep);return pairs.forEach(([pk,pv])=>{var _a2,_b;let tmp="",encValue=null;pv!=null&&(Array.isArray(pv)?encValue=(_a2=mapDefined(pv,v=>`${encodeValue(v)}`))===null||_a2===void 0?void 0:_a2.join(encodedSep):isPlainObject$1(pv)?encValue=(_b=mapDefinedEntries(Object.entries(pv),([k,v])=>`${encodeString(k)}${encodedSep}${encodeValue(v)}`))===null||_b===void 0?void 0:_b.join(encodedSep):encValue=`${encodeValue(pv)}`,encValue!=null&&(tmp=`${encodeKeyChars(pk,options?.
1509
+ charEncoding)}=${encValue}`,!(!tmp||tmp==="=")&&(out+=`&${tmp}`)))}),out.slice(1)}}var encodeForm=formEncoder(",");function encodeJSON(key,value,options){if(typeof value>"u")return;let encVal=(v=>encodeChars(v,options?.charEncoding))(JSON.stringify(value,jsonReplacer));return options?.explode?encVal:`${encodeKeyChars(key,options?.charEncoding)}=${encVal}`}var encodeSimple=(key,value,options)=>{let out="",pairs=options?.explode?explode(key,value):[[key,value]];if(pairs.every(([_,v])=>v==null))return;
1510
+ let encodeString=v=>encodeChars(v,options?.charEncoding),encodeValue=v=>encodeString(serializeValue(v));return pairs.forEach(([pk,pv])=>{var _a2;let tmp="";if(pv!=null){if(Array.isArray(pv))tmp=(_a2=mapDefined(pv,v=>`${encodeValue(v)}`))===null||_a2===void 0?void 0:_a2.join(",");else if(isPlainObject$1(pv)){let mapped=mapDefinedEntries(Object.entries(pv),([k,v])=>`,${encodeString(k)},${encodeValue(v)}`);tmp=mapped?.join("").slice(1)}else tmp=`${options?.explode&&isPlainObject$1(value)?`${pk}=`:""}${encodeValue(
1511
+ pv)}`;out+=tmp?`,${tmp}`:""}}),out.slice(1)};function explode(key,value){return Array.isArray(value)?value.map(v=>[key,v]):isPlainObject$1(value)?Object.entries(value??{}).map(([k,v])=>[k,v]):[[key,value]]}function serializeValue(value){return value==null?"":value instanceof Date?value.toISOString():value instanceof Uint8Array?bytesToBase64(value):typeof value=="object"?JSON.stringify(value,jsonReplacer):`${value}`}function jsonReplacer(_,value){return value instanceof Uint8Array?bytesToBase64(value):
1512
+ value}function mapDefined(inp,mapper){let res=inp.reduce((acc,v)=>{if(v==null)return acc;let m=mapper(v);return m==null||acc.push(m),acc},[]);return res.length?res:null}function mapDefinedEntries(inp,mapper){let acc=[];for(let[k,v]of inp){if(v==null)continue;let m=mapper([k,v]);m!=null&&acc.push(m)}return acc.length?acc:null}function queryJoin(...args){return args.filter(Boolean).join("&")}function queryEncoder(f){return function(values,options){var _a2,_b,_c;let opts=Object.assign(Object.assign(
1513
+ {},options),{explode:(_a2=options?.explode)!==null&&_a2!==void 0?_a2:!0,charEncoding:(_b=options?.charEncoding)!==null&&_b!==void 0?_b:"percent"}),allowEmptySet=new Set((_c=options?.allowEmptyValue)!==null&&_c!==void 0?_c:[]),encoded=Object.entries(values).map(([key,value])=>allowEmptySet.has(key)&&(value==null||value===""||Array.isArray(value)&&value.length===0)?`${encodeURIComponent(key)}=`:f(key,value,opts));return queryJoin(...encoded)}}var encodeFormQuery=queryEncoder(encodeForm);var defaultBackoff={
1514
+ initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5},PermanentError=class _PermanentError extends Error{constructor(message,options){let msg=message;options?.cause&&(msg+=`: ${options.cause}`),super(msg,options),this.name="PermanentError",typeof this.cause>"u"&&(this.cause=options?.cause),Object.setPrototypeOf(this,_PermanentError.prototype)}},TemporaryError=class _TemporaryError extends Error{constructor(message,response){super(message),this.response=response,this.name="Tempora\
1515
+ ryError",Object.setPrototypeOf(this,_TemporaryError.prototype)}};async function retry(fetchFn,options){var _a2;switch(options.config.strategy){case"backoff":return retryBackoff(wrapFetcher(fetchFn,{statusCodes:options.statusCodes,retryConnectionErrors:!!options.config.retryConnectionErrors}),(_a2=options.config.backoff)!==null&&_a2!==void 0?_a2:defaultBackoff);case"attempt-count-backoff":return retryAttemptCountBackoff(wrapFetcher(fetchFn,{statusCodes:options.statusCodes,retryConnectionErrors:!!options.
1516
+ config.retryConnectionErrors}),Object.assign(Object.assign({},defaultBackoff),options.config.backoff),options.config);default:return await fetchFn(0)}}function wrapFetcher(fn,options){return async attempt=>{try{let res=await fn(attempt);if(isRetryableResponse(res,options.statusCodes))throw new TemporaryError("Response failed with retryable status code",res);return res}catch(err){throw err instanceof TemporaryError||options.retryConnectionErrors&&(isTimeoutError(err)||isConnectionError(err))?err:
1517
+ new PermanentError("Permanent error",{cause:err})}}}var codeRangeRE=new RegExp("^[0-9]xx$","i");function isRetryableResponse(res,statusCodes){let actual=`${res.status}`;return statusCodes.some(code=>{if(!codeRangeRE.test(code))return code===actual;let expectFamily=code.charAt(0);if(!expectFamily)throw new Error("Invalid status code range");let actualFamily=actual.charAt(0);if(!actualFamily)throw new Error(`Invalid response status code: ${actual}`);return actualFamily===expectFamily})}async function retryBackoff(fn,strategy){
1518
+ let{maxElapsedTime,initialInterval,exponent,maxInterval}=strategy,start=Date.now(),x=0;for(;;)try{return await fn(x)}catch(err){if(err instanceof PermanentError)throw err.cause;if(Date.now()-start>maxElapsedTime){if(err instanceof TemporaryError)return err.response;throw err}let retryInterval=0;err instanceof TemporaryError&&(retryInterval=retryIntervalFromResponse(err.response)),retryInterval<=0&&(retryInterval=initialInterval*Math.pow(x,exponent)+Math.random()*1e3);let d=Math.min(retryInterval,
1519
+ maxInterval);await delay(d),x++}}async function retryAttemptCountBackoff(fn,strategy,config){let attempt=0;for(;;)try{return await fn(attempt)}catch(err){if(err instanceof PermanentError)throw err.cause;if(attempt>=config.maxRetries){if(err instanceof TemporaryError)return err.response;throw err}let retryInterval=0;err instanceof TemporaryError&&(retryInterval=retryIntervalFromResponse(err.response)),retryInterval<=0&&(retryInterval=strategy.initialInterval*Math.pow(strategy.exponent,attempt)*(1-
1520
+ Math.random()*.25));let d=Math.min(retryInterval,strategy.maxInterval);await delay(d),attempt++}}function retryIntervalFromResponse(res){let retryAfterMsVal=res.headers.get("retry-after-ms");if(retryAfterMsVal){let parsedMs=Number(retryAfterMsVal);if(Number.isFinite(parsedMs)&&parsedMs>=0)return parsedMs}let retryVal=res.headers.get("retry-after")||"";if(!retryVal)return 0;let parsedNumber=Number(retryVal);if(Number.isInteger(parsedNumber))return parsedNumber*1e3;let parsedDate=Date.parse(retryVal);
1521
+ if(Number.isInteger(parsedDate)){let deltaMS=parsedDate-Date.now();return deltaMS>0?Math.ceil(deltaMS):0}return 0}async function delay(delay2){return new Promise(resolve=>setTimeout(resolve,delay2))}var gt=typeof globalThis>"u"?null:globalThis,webWorkerLike=typeof gt=="object"&&gt!=null&&"importScripts"in gt&&typeof gt.importScripts=="function",isBrowserLike=webWorkerLike||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u",ClientSDK=class{constructor(options={}){
1522
+ let opt=options;typeof opt=="object"&&opt!=null&&"hooks"in opt&&opt.hooks instanceof SDKHooks?this._hooks=opt.hooks:this._hooks=new SDKHooks;let defaultHttpClient=new HTTPClient;options.http_client=options.http_client||defaultHttpClient,options=this._hooks.sdkInit(options);let url=serverURLFromOptions(options);url&&(url.pathname=url.pathname.replace(/\/+$/,"")+"/"),this._baseURL=url,this._httpClient=options.http_client||defaultHttpClient,this._options=Object.assign(Object.assign({},fillGlobals(options)),
1523
+ {hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&env().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(context,conf,options){var _a2,_b,_c,_d,_e;let{method,path:path2,query,headers:opHeaders,security}=conf,base=(_a2=conf.baseURL)!==null&&_a2!==void 0?_a2:this._baseURL;if(!base)return ERR(new InvalidRequestError("No base URL provided for operation"));let baseURL=new URL(base),reqURL;path2?(baseURL.pathname=baseURL.pathname.replace(/\/+$/,"")+"/",reqURL=new URL(
1524
+ path2,baseURL),!reqURL.search&&baseURL.search&&(reqURL.search=baseURL.search)):reqURL=baseURL,reqURL.hash="";let mergeQuery=(current,additions)=>{if(!additions)return current;let additionKeys=new Set(additions.split("&").filter(pair=>pair!=="").map(pair=>{var _a3;return(_a3=pair.split("=")[0])!==null&&_a3!==void 0?_a3:""}));return[...current.split("&").filter(pair=>{var _a3;return pair!==""&&!additionKeys.has((_a3=pair.split("=")[0])!==null&&_a3!==void 0?_a3:"")}),additions].join("&")},encodeQueryRecord=record=>Object.
1525
+ entries(record).map(([k,v])=>{if(v==null)return;let value=isPlainObject$1(v)?JSON.stringify(v):v;return encodeForm(k,value,{explode:Array.isArray(value),charEncoding:"percent"})}).filter(pair=>typeof pair<"u").join("&"),finalQuery=[query||"",encodeQueryRecord(options?.extra_query||{}),encodeQueryRecord(security?.queryParams||{})].reduce(mergeQuery,reqURL.search.slice(1));finalQuery&&(reqURL.search=`?${finalQuery}`);let headers=new Headers(opHeaders),username=security?.basic.username,password=security?.
1526
+ basic.password;if(username!=null||password!=null){let encoded=stringToBase64([username||"",password||""].join(":"));headers.set("Authorization",`Basic ${encoded}`)}let securityHeaders=new Headers(security?.headers||{});for(let[k,v]of securityHeaders)headers.set(k,v);let cookie=headers.get("cookie")||"";for(let[k,v]of Object.entries(security?.cookies||{}))cookie+=`; ${k}=${v}`;cookie=cookie.startsWith("; ")?cookie.slice(2):cookie,headers.set("cookie",cookie);let userHeaders=new Headers((_b=options?.
1527
+ headers)!==null&&_b!==void 0?_b:(_c=options?.fetch_options)===null||_c===void 0?void 0:_c.headers);for(let[k,v]of userHeaders)headers.set(k,v);isBrowserLike||headers.set((_d=conf.uaHeader)!==null&&_d!==void 0?_d:"user-agent",(_e=conf.userAgent)!==null&&_e!==void 0?_e:SDK_METADATA.userAgent);let reqBody=conf.body,extraBody=Object.fromEntries(Object.entries(options?.extra_body||{}).filter(([,v])=>typeof v<"u"));if(Object.keys(extraBody).length>0){let contentType=new Headers(opHeaders).get("content\
1528
+ -type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(contentType)||typeof reqBody!="string"&&reqBody!=null)return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies"));let parsedBody;try{parsedBody=reqBody?JSON.parse(reqBody):{}}catch(err){return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies",{cause:err}))}if(!isPlainObject$1(parsedBody))return ERR(new InvalidRequestError("extra_body can only be merged int\
1529
+ o JSON object request bodies"));reqBody=JSON.stringify(Object.assign(Object.assign({},parsedBody),extraBody)),headers.delete("content-length")}let fetchOptions=Object.assign(Object.assign({},options?.fetch_options),options);!fetchOptions?.signal&&conf.timeout_ms!=null&&conf.timeout_ms>0&&(context.timeout_ms=conf.timeout_ms),conf.body instanceof ReadableStream&&Object.assign(fetchOptions,{duplex:"half"});let input;try{input=this._hooks.beforeCreateRequest(context,{url:reqURL,options:Object.assign(
1530
+ Object.assign({},fetchOptions),{body:reqBody??null,headers,method})})}catch(err){return ERR(new UnexpectedClientError("Create request hook failed to execute",{cause:err}))}return OK(new Request(input.url,input.options))}async _do(request,options){let{context,isErrorStatusCode}=options,timeout_ms=context.timeout_ms;return retry(async()=>{var _a2;let cloned=request.clone(),attempt=cloned;if(timeout_ms!=null&&timeout_ms>0){let timeoutSignal=AbortSignal.timeout(timeout_ms),combined=(_a2=combineSignals(
1531
+ cloned.signal,timeoutSignal))!==null&&_a2!==void 0?_a2:timeoutSignal;attempt=new Request(cloned,{signal:combined})}let req=await this._hooks.beforeRequest(context,attempt);await logRequest(this._logger,req).catch(e=>{var _a3;return(_a3=this._logger)===null||_a3===void 0?void 0:_a3.log("Failed to log request:",e)});let response=await this._httpClient.request(req);try{if(isErrorStatusCode(response.status)){let result=await this._hooks.afterError(context,response,null);if(result.error)throw result.
1532
+ error;response=result.response||response}else response=await this._hooks.afterSuccess(context,response)}finally{await logResponse(this._logger,response,req).catch(e=>{var _a3;return(_a3=this._logger)===null||_a3===void 0?void 0:_a3.log("Failed to log response:",e)})}return response},{config:options.retryConfig,statusCodes:options.retryCodes}).then(r=>OK(r),err=>{switch(!0){case isAbortError(err):return ERR(new RequestAbortedError("Request aborted by client",{cause:err}));case isTimeoutError(err):
1533
+ return ERR(new RequestTimeoutError("Request timed out",{cause:err}));case isConnectionError(err):return ERR(new ConnectionError("Unable to make request",{cause:err}));default:return ERR(new UnexpectedClientError("Unexpected HTTP client error",{cause:err}))}})}},jsonLikeContentTypeRE=/^(application|text)\/([^+]+\+)*json.*/,jsonlLikeContentTypeRE=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;async function logRequest(logger,req){if(!logger)return;let contentType=req.headers.get("content-ty\
1534
+ pe"),ct=contentType?.split(";")[0]||"";logger.group(`> Request: ${req.method} ${req.url}`),logger.group("Headers:");for(let[k,v]of req.headers.entries())logger.log(`${k}: ${v}`);switch(logger.groupEnd(),logger.group("Body:"),!0){case jsonLikeContentTypeRE.test(ct):logger.log(await req.clone().json());break;case ct.startsWith("text/"):logger.log(await req.clone().text());break;case ct==="multipart/form-data":{let body=await req.clone().formData();for(let[k,v]of body){let vlabel=v instanceof Blob?
1535
+ "<Blob>":v;logger.log(`${k}: ${vlabel}`)}break}default:logger.log(`<${contentType}>`);break}logger.groupEnd(),logger.groupEnd()}async function logResponse(logger,res,req){if(!logger)return;let contentType=res.headers.get("content-type"),ct=contentType?.split(";")[0]||"";logger.group(`< Response: ${req.method} ${req.url}`),logger.log("Status Code:",res.status,res.statusText),logger.group("Headers:");for(let[k,v]of res.headers.entries())logger.log(`${k}: ${v}`);switch(logger.groupEnd(),logger.group(
1536
+ "Body:"),!0){case(matchContentType(res,"application/json")||jsonLikeContentTypeRE.test(ct)&&!jsonlLikeContentTypeRE.test(ct)):logger.log(await res.clone().json());break;case(matchContentType(res,"application/jsonl")||jsonlLikeContentTypeRE.test(ct)):case matchContentType(res,"text/event-stream"):logger.log(`<${contentType}>`);break;case matchContentType(res,"text/*"):logger.log(await res.clone().text());break;case matchContentType(res,"multipart/form-data"):{let body=await res.clone().formData();
1537
+ for(let[k,v]of body){let vlabel=v instanceof Blob?"<Blob>":v;logger.log(`${k}: ${vlabel}`)}break}default:logger.log(`<${contentType}>`);break}logger.groupEnd(),logger.groupEnd()}var GoogleGenAiDefaultError=class extends GoogleGenAiError{constructor(message,httpMeta){message&&(message+=": "),message+=`Status ${httpMeta.response.status}`;let contentType=httpMeta.response.headers.get("content-type")||'""';contentType!=="application/json"&&(message+=` Content-Type ${contentType.includes(" ")?`"${contentType}\
1538
+ "`:contentType}`);let body=httpMeta.body||'""';message+=body.length>100?`
1519
1539
  `:". ";let bodyDisplay=body;if(body.length>1e4){let truncated=body.substring(0,1e4),remaining=body.length-1e4;bodyDisplay=`${truncated}...and ${remaining} more chars`}message+=`Body: ${bodyDisplay}`,message=message.trim(),super(message,httpMeta),this.name="GoogleGenAiDefaultError"}};function tryParseJson(s){try{return JSON.parse(s)}catch{return s}}function wrapEventStreamResponse(body,opts={}){var _a2,_b;let flattened=opts.flattened===!0,sentinel=(_a2=opts.sentinel)!==null&&_a2!==void 0?_a2:"";return new Stream(
1520
1540
  body,rawEvent=>sentinel!==""&&rawEvent.data===sentinel?{done:!0,value:void 0}:flattened?{done:!1,value:rawEvent.data==null?void 0:tryParseJson(rawEvent.data)}:{done:!1,value:Object.assign(Object.assign({},rawEvent),{data:rawEvent.data==null?rawEvent.data:tryParseJson(rawEvent.data)})},{dataRequired:(_b=opts.dataRequired)!==null&&_b!==void 0?_b:!0})}var Stream=class extends ReadableStream{constructor(responseBody,parse,opts){var _a2;let upstream=responseBody.getReader(),buffer=new Uint8Array(4096),
1521
1541
  bufferLen=0,searchStart=0,state={eventId:void 0},dataRequired=(_a2=opts?.dataRequired)!==null&&_a2!==void 0?_a2:!0;super({async pull(downstream){try{for(;;){let match2=findBoundary(buffer,bufferLen,searchStart);if(!match2){searchStart=Math.max(0,bufferLen-MAX_BOUNDARY_LEN+1);let chunk=await upstream.read();if(chunk.done)return downstream.close();if(bufferLen+chunk.value.length>buffer.length){let grown=new Uint8Array(Math.max(buffer.length*2,bufferLen+chunk.value.length));grown.set(buffer.subarray(
@@ -1699,120 +1719,119 @@ complete",request:req,response}]:[result,{status:"complete",request:req,response
1699
1719
  {explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"\
1700
1720
  ListWebhooks",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,
1701
1721
  query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(
1702
- fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksPing(client,id,api_version,body,options){return new APIPromise($do$2(client,id,api_version,body,options))}async function $do$2(client,id,api_version,body,options){var _a2,_b,_c;let payload={id,api_version,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",
1722
+ fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksPing(client,id,body,api_version,options){return new APIPromise($do$2(client,id,body,api_version,options))}async function $do$2(client,id,body,api_version,options){var _a2,_b,_c;let payload={id,body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",
1703
1723
  (_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}:ping")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=
1704
1724
  (_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client.
1705
1725
  _createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.
1706
- ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksRotateSigningSecret(client,id,api_version,body,options){return new APIPromise($do$1(client,id,api_version,body,options))}async function $do$1(client,id,api_version,body,options){var _a2,_b,_c;let payload={
1707
- id,api_version,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}:rotateSigningSecret")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(
1726
+ ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksRotateSigningSecret(client,id,body,api_version,options){return new APIPromise($do$1(client,id,body,api_version,options))}async function $do$1(client,id,body,api_version,options){var _a2,_b,_c;let payload={
1727
+ id,body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}:rotateSigningSecret")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(
1708
1728
  client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},
1709
1729
  retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode(
1710
- {status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksUpdate(client,id,api_version,update_mask,body,options){return new APIPromise($do(client,id,
1711
- api_version,update_mask,body,options))}async function $do(client,id,api_version,update_mask,body,options){var _a2,_b,_c;let payload={id,api_version,update_mask,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(
1730
+ {status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksUpdate(client,id,body,api_version,update_mask,options){return new APIPromise($do(client,id,
1731
+ body,api_version,update_mask,options))}async function $do(client,id,body,api_version,update_mask,options){var _a2,_b,_c;let payload={id,body,api_version,update_mask},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(
1712
1732
  pathParams),query=encodeFormQuery({update_mask:payload.update_mask}),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client.
1713
1733
  _options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"PATCH",baseURL:options?.server_url,path:path2,headers,query,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||
1714
1734
  client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[
1715
1735
  result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Webhooks=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(webhooksList(this,params?.api_version,params?.page_size,params?.page_token,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(webhooksCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(webhooksDelete(this,id,params?.
1716
- api_version,options))}get(id,params,options){return unwrapAsAPIPromise(webhooksGet(this,id,params?.api_version,options))}update(id,params,options){let _a2=params??{},{api_version,update_mask}=_a2,body$body=__rest(_a2,["api_version","update_mask"]),body=params===void 0||Object.keys(body$body).length===0?void 0:body$body;return unwrapAsAPIPromise(webhooksUpdate(this,id,api_version,update_mask,body,options))}ping(id,api_version,body,options){return unwrapAsAPIPromise(webhooksPing(this,id,api_version,
1717
- body,options))}rotateSigningSecret(id,api_version,body,options){return unwrapAsAPIPromise(webhooksRotateSigningSecret(this,id,api_version,body,options))}};var GoogleGenAI$1=class extends ClientSDK{get environments(){var _a2;return(_a2=this._environments)!==null&&_a2!==void 0?_a2:this._environments=new Environments(this._options)}get agents(){var _a2;return(_a2=this._agents)!==null&&_a2!==void 0?_a2:this._agents=new Agents(this._options)}get credentials(){var _a2;return(_a2=this._credentials)!==null&&
1718
- _a2!==void 0?_a2:this._credentials=new Credentials(this._options)}get interactions(){var _a2;return(_a2=this._interactions)!==null&&_a2!==void 0?_a2:this._interactions=new Interactions(this._options)}get triggers(){var _a2;return(_a2=this._triggers)!==null&&_a2!==void 0?_a2:this._triggers=new Triggers(this._options)}get voices(){var _a2;return(_a2=this._voices)!==null&&_a2!==void 0?_a2:this._voices=new Voices(this._options)}get webhooks(){var _a2;return(_a2=this._webhooks)!==null&&_a2!==void 0?_a2:
1719
- this._webhooks=new Webhooks(this._options)}};var LEGACY_LYRIA_MODELS=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function getGoogleGenAIServerURL(parentClient){let serverURL=parentClient.getBaseUrl();if(!serverURL)throw new Error("Base URL must be set.");return serverURL.replace(/\/+$/,"")}function getGoogleGenAIAPIVersion(parentClient){let apiVersion=trimSlashes(parentClient.getApiVersion()),project=parentClient.getProject(),location=parentClient.getLocation();return parentClient.isVertexAI()&&
1720
- apiVersion&&project&&location?`${apiVersion}/projects/${encodeURIComponent(project)}/locations/${encodeURIComponent(location)}`:apiVersion}function buildGoogleGenAIClient(parentClient,options={}){var _a2,_b,_c,_d,_e,_f,_g;let fetchFn=options.http_client||(_a2=parentClient.getFetch)===null||_a2===void 0?void 0:_a2.call(parentClient),httpClient=(_b=options.http_client)!==null&&_b!==void 0?_b:fetchFn?new HTTPClient({fetcher:fetchFn}):void 0;return new GoogleGenAI$1(Object.assign(Object.assign({},options),
1721
- {http_client:httpClient,api_version:(_c=options.api_version)!==null&&_c!==void 0?_c:getGoogleGenAIAPIVersion(parentClient),security:(_d=options.security)!==null&&_d!==void 0?_d:new GoogleGenAISecurityProvider({defaultHeaders:Object.assign(Object.assign({},(_e=parentClient.getDefaultHeaders)===null||_e===void 0?void 0:_e.call(parentClient)),(_f=parentClient.getHeaders)===null||_f===void 0?void 0:_f.call(parentClient)),getAuthHeaders:url=>parentClient.getAuthHeaders(url)}),server_url:(_g=options.server_url)!==
1722
- null&&_g!==void 0?_g:getGoogleGenAIServerURL(parentClient)}))}var GeminiNextGenInteractions=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,request=__rest(params,["api_version"]);if(request.stream===!0){let response2=await wrapSDKCall(()=>this.getClient(api_version).interactions.create(Object.assign(Object.assign({},request),{stream:!0,api_version}),toGoogleGenAIRequestOptions(options,!0)));return wrapStreamErrors(response2)}let response=await unwrapWithSdkHttpResponse(
1723
- interactionsCreate(this.getClient(api_version),request,api_version,toGoogleGenAIRequestOptions(options)));return addOutputPropertiesIfInteraction(response)}async get(id,params={},options){let{api_version,stream=!1,last_event_id,include_input}=params??{};if(stream===!0){let response2=await wrapSDKCall(()=>this.getClient(api_version).interactions.get(id,{stream,last_event_id,include_input,api_version},toGoogleGenAIRequestOptions(options,!0)));return wrapStreamErrors(response2)}let response=await unwrapWithSdkHttpResponse(
1724
- interactionsGet(this.getClient(api_version),id,api_version,include_input,last_event_id,stream,toGoogleGenAIRequestOptions(options)));return addOutputPropertiesIfInteraction(response)}async delete(id,params={},options){return wrapSDKCall(()=>this.getClient(params?.api_version).interactions.delete(id,{api_version:params?.api_version},toGoogleGenAIRequestOptions(options)))}async cancel(id,params={},options){return addOutputPropertiesIfInteraction(await unwrapWithSdkHttpResponse(interactionsCancel(this.
1725
- getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options))))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenAgents=class{constructor(parentClient){this.parentClient=parentClient}async create(params={},options){let _a2=params??{},{api_version}=_a2,body=__rest(_a2,["api_version"]);return unwrapWithSdkHttpResponse(
1726
- agentsCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token,parent}=params??{};return unwrapWithSdkHttpResponse(agentsList(this.getClient(api_version),api_version,page_size,page_token,parent,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(agentsGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){
1727
- return unwrapWithSdkHttpResponse(agentsDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenWebhooks=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,
1728
- body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(webhooksCreate(this.getClient(),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(webhooksList(this.getClient(),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(webhooksGet(this.getClient(),id,params?.api_version,toGoogleGenAIRequestOptions(
1729
- options)))}async update(id,params={},options){let _a2=params??{},{api_version,update_mask}=_a2,body=__rest(_a2,["api_version","update_mask"]);return unwrapWithSdkHttpResponse(webhooksUpdate(this.getClient(),id,api_version,update_mask,body,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(webhooksDelete(this.getClient(),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async rotateSigningSecret(id,params={},options){let _a2=params??
1730
- {},{api_version}=_a2,body=__rest(_a2,["api_version"]);return unwrapWithSdkHttpResponse(webhooksRotateSigningSecret(this.getClient(),id,api_version,body,toGoogleGenAIRequestOptions(options)))}async ping(id,params=void 0,options){let{api_version,body}=params??{};return unwrapWithSdkHttpResponse(webhooksPing(this.getClient(),id,api_version,body,toGoogleGenAIRequestOptions(options)))}getClient(){var _a2;return(_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.
1731
- sdk}},GeminiNextGenTriggers=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(triggersCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,filter,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(triggersList(this.getClient(api_version),api_version,filter,page_size,
1732
- page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(triggersGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(triggersUpdate(this.getClient(api_version),id,body,api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(
1733
- triggersDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async run(trigger_id,params={},options){return unwrapWithSdkHttpResponse(triggersRun(this.getClient(params?.api_version),trigger_id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async listExecutions(trigger_id,params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(triggersListExecutions(this.getClient(api_version),trigger_id,api_version,
1734
- page_size,page_token,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}};function trimSlashes(value){return value.replace(/^\/+|\/+$/g,"")}function toGoogleGenAIRequestOptions(options,streaming=!1){var _a2,_b,_c,_d;if(!options&&!streaming)return;let _e=options??{},{timeout,maxRetries,defaultBaseURL,
1735
- query,body,fetchOptions}=_e,rest=__rest(_e,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),nextOptions=Object.assign({},rest);isPlainObject(query)?nextOptions.extra_query=query:warnIgnoredOption("query",query),isPlainObject(body)?nextOptions.extra_body=body:warnIgnoredOption("body",body);let fetch_options=(_a2=rest.fetch_options)!==null&&_a2!==void 0?_a2:fetchOptions;fetch_options&&(nextOptions.fetch_options=fetch_options);let server_url=(_b=rest.server_url)!==null&&_b!==
1736
- void 0?_b:defaultBaseURL;server_url&&(nextOptions.server_url=server_url);let timeout_ms=(_c=rest.timeout_ms)!==null&&_c!==void 0?_c:timeout;if(timeout_ms!==void 0&&(nextOptions.timeout_ms=timeout_ms),maxRetries!==void 0&&(nextOptions.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries}),streaming){let headers=new Headers((_d=nextOptions.headers)!==null&&_d!==void 0?_d:fetch_options?.headers);headers.set("Accept","text/event-stream"),nextOptions.headers=headers}return nextOptions}
1737
- function warnIgnoredOption(name,value){value!=null&&console.warn(`GoogleGenAI.interactions: request option ${name} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function unwrapWithSdkHttpResponse(promise){let[result,call]=await promise.$inspect();if(!result.ok)throw wrapSDKError(result.error);return attachSdkHttpResponse(result.value,call)}async function wrapSDKCall(operation){try{return await operation()}catch(error){throw wrapSDKError(error)}}function wrapStreamErrors(stream){
1738
- let asyncIterable=stream;return new Proxy(stream,{get(target,property){if(property!==Symbol.asyncIterator){let value=Reflect.get(target,property,target);return typeof value=="function"?value.bind(target):value}return function(){let iterator=asyncIterable[Symbol.asyncIterator]();return{async next(...args){try{return await iterator.next(...args)}catch(error){throw wrapSDKError(error)}},async return(value){if(!iterator.return)return{done:!0,value};try{return await iterator.return(value)}catch(error){
1739
- throw wrapSDKError(error)}},async throw(error){if(!iterator.throw)throw wrapSDKError(error);try{return await iterator.throw(error)}catch(caught){throw wrapSDKError(caught)}},[Symbol.asyncIterator](){return this}}}}})}function attachSdkHttpResponse(value,call){return!isPlainObject(value)||call.status!=="complete"?value:Object.assign(Object.assign({},value),{sdkHttpResponse:createSdkHttpResponse(call.response,value)})}function createSdkHttpResponse(response,parsedBody){let headers={};for(let[key,value]of response.
1740
- headers.entries())headers[key]=value;return{headers,responseInternal:response,json:async()=>parsedBody}}function addOutputPropertiesIfInteraction(value){let interaction=normalizeInteractionShape(value);return interaction?addOutputProperties(interaction):value}function normalizeInteractionShape(value){if(isPlainObject(value)){if(Array.isArray(value.steps))return value;if(isLegacyLyriaInteraction(value)){let outputs=value.outputs;if(Array.isArray(outputs)){let{outputs:_outputs}=value,rest=__rest(value,
1741
- ["outputs"]);return Object.assign(Object.assign({},rest),{steps:[{type:"model_output",content:outputs}]})}}return Object.assign(Object.assign({},value),{steps:[]})}}function isLegacyLyriaInteraction(value){let model=value.model;return typeof model=="string"&&LEGACY_LYRIA_MODELS.has(model)}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function addOutputProperties(interaction){var _a2,_b;let normalized=normalizeInteractionDates(interaction),steps=(_a2=
1742
- normalized.steps)!==null&&_a2!==void 0?_a2:[],textParts=[],collecting=!1;outer:for(let i=steps.length-1;i>=0;i--){let step=steps[i];if(step.type==="user_input")break;if(step.type!=="model_output"||!step.content){if(collecting)break;continue}let content=step.content;for(let j=content.length-1;j>=0;j--){let item=content[j];if(item.type==="text")collecting=!0,textParts.push((_b=item.text)!==null&&_b!==void 0?_b:"");else if(collecting)break outer}}let output_image,output_audio,output_video;for(let i=steps.
1743
- length-1;i>=0;i--){let step=steps[i];if(step.type==="user_input")break;if(step.type==="model_output"&&step.content)for(let j=step.content.length-1;j>=0;j--){let content=step.content[j];content.type==="image"&&!output_image&&(output_image=content),content.type==="audio"&&!output_audio&&(output_audio=content),content.type==="video"&&!output_video&&(output_video=content)}}let output_text=textParts.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},normalized),
1744
- output_text&&{output_text}),output_image?{output_image}:{}),output_audio?{output_audio}:{}),output_video?{output_video}:{})}function normalizeInteractionDates(interaction){return Object.assign(Object.assign({},interaction),{created:normalizeDateLike(interaction.created),updated:normalizeDateLike(interaction.updated)})}function normalizeDateLike(value){return value instanceof Date?value.toISOString():value}function inferMimeType(filePath){let ext=filePath.slice(filePath.lastIndexOf(".")+1).toLowerCase();
1745
- return{txt:"text/plain",json:"application/json",js:"text/javascript",mjs:"text/javascript",ts:"text/plain",py:"text/x-python",html:"text/html",htm:"text/html",css:"text/css",csv:"text/csv",xml:"application/xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[ext]}var GeminiNextGenEnvironmentFiles=class{constructor(resolveClient,parentClient){this.resolveClient=
1746
- resolveClient,this.parentClient=parentClient}async list(params,options){return unwrapWithSdkHttpResponse(environmentsFilesList(this.resolveClient(params.api_version),params.environment,params.path,params.api_version,params.page_size,params.page_token,params.recursive,toGoogleGenAIRequestOptions(options)))}async download(params,options){var _a2,_b;let targetEnv=params.environment;if(!targetEnv)throw new Error("environment is required.");let envName=targetEnv.startsWith("environments/")?targetEnv:
1747
- `environments/${targetEnv}`,cleanPath=params.path.replace(/^\/+/,""),downloadPath=`${envName}/files/${cleanPath}`,apiClient=this.parentClient;if(!apiClient||typeof apiClient.request!="function")throw new Error("apiClient is required to download files.");let response=await apiClient.request({path:downloadPath,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:Object.assign(Object.assign({},options?.httpOptions),{apiVersion:(_a2=params.api_version)!==null&&_a2!==void 0?_a2:(_b=options?.httpOptions)===
1748
- null||_b===void 0?void 0:_b.apiVersion})});if(response&&response.responseInternal&&typeof response.responseInternal.arrayBuffer=="function"){let arrayBuffer=await response.responseInternal.arrayBuffer();return new Uint8Array(arrayBuffer)}throw new Error("Unexpected response type from download")}async upload(params,options){var _a2,_b,_c,_d,_e,_f,_g,_h;let targetEnv=params.environment;if(!targetEnv)throw new Error("environment is required.");targetEnv.startsWith("environments/")||`${targetEnv}`;let cleanPath=params.
1749
- path.replace(/^\/+/,""),apiClient=this.parentClient;if(!apiClient||typeof apiClient.request!="function")throw new Error("apiClient is required to upload files.");let fileData,sizeBytes=0,mimeType=params.mime_type;if(typeof params.file=="string"){let buffer;try{let req=globalThis.require;req&&(buffer=req("fs").readFileSync(params.file))}catch{}if(!buffer&&typeof globalThis.process<"u")try{let mod=(_b=(_a2=globalThis.process.mainModule)===null||_a2===void 0?void 0:_a2.require)!==null&&_b!==void 0?
1750
- _b:globalThis.require;mod&&(buffer=mod("fs").readFileSync(params.file))}catch{}if(buffer)fileData=new Uint8Array(buffer.buffer,buffer.byteOffset,buffer.byteLength),sizeBytes=fileData.byteLength;else throw new Error(`Unable to read file from path "${params.file}". File path string inputs are only supported in Node.js environments.`);mimeType||(mimeType=inferMimeType(params.file))}else if(typeof Blob<"u"&&params.file instanceof Blob)fileData=params.file,sizeBytes=params.file.size,!mimeType&&params.
1751
- file.type&&(mimeType=params.file.type);else if(params.file instanceof Uint8Array||params.file instanceof ArrayBuffer)fileData=params.file instanceof ArrayBuffer?new Uint8Array(params.file):params.file,sizeBytes=fileData.byteLength;else if(typeof globalThis.Buffer<"u"&&typeof globalThis.Buffer.isBuffer=="function"&&globalThis.Buffer.isBuffer(params.file)){let buf=params.file;fileData=new Uint8Array(buf.buffer,buf.byteOffset,buf.byteLength),sizeBytes=fileData.byteLength}else throw new Error("Unsup\
1752
- ported file type for upload.");mimeType||(mimeType="application/octet-stream");let cleanEnv=targetEnv.startsWith("environments/")?targetEnv.replace(/^environments\//,""):targetEnv,[result,call]=await environmentsInternalStartUpload(this.resolveClient(params.api_version),cleanEnv,cleanPath,"start",sizeBytes,mimeType,"resumable",params.api_version,params.extract,params.overwrite,toGoogleGenAIRequestOptions(options)).$inspect();if(!result.ok)throw wrapSDKError(result.error);let uploadUrl=call.status===
1753
- "complete"?(_e=(_d=(_c=call.response)===null||_c===void 0?void 0:_c.headers)===null||_d===void 0?void 0:_d.get("x-goog-upload-url"))!==null&&_e!==void 0?_e:(_g=(_f=call.response)===null||_f===void 0?void 0:_f.headers)===null||_g===void 0?void 0:_g.get("X-Goog-Upload-URL"):void 0;if(!uploadUrl)throw new Error("Failed to get upload URL from upload handshake response.");let CHUNK_SIZE=8*1024*1024,offset=0,uploadResponse,blob=fileData instanceof Blob?fileData:new Blob([fileData]);for(;offset<sizeBytes||
1754
- sizeBytes===0&&offset===0;){let end=Math.min(offset+CHUNK_SIZE,sizeBytes),chunk=blob.slice(offset,end),isFinal=end>=sizeBytes,uploadCommand=isFinal?"upload, finalize":"upload";if(uploadResponse=await apiClient.request({path:"",body:chunk,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},options?.httpOptions),{apiVersion:"",baseUrl:uploadUrl,headers:Object.assign(Object.assign({},((_h=options?.httpOptions)===null||_h===void 0?void 0:_h.headers)||{}),{"X-Goog-Upload-Command":uploadCommand,
1755
- "X-Goog-Upload-Offset":`${offset}`})})}),offset=end,isFinal)break}let resJson;if(uploadResponse&&typeof uploadResponse.json=="function"?resJson=await uploadResponse.json():uploadResponse&&uploadResponse.responseInternal&&typeof uploadResponse.responseInternal.json=="function"&&(resJson=await uploadResponse.responseInternal.json()),resJson&&typeof resJson=="object"){if(Array.isArray(resJson.files))return resJson;if(resJson.name||resJson.path)return{files:[resJson]};if(resJson.file&&typeof resJson.
1756
- file=="object")return{files:[resJson.file]}}return resJson}},GeminiNextGenEnvironments=class{constructor(parentClient){this.parentClient=parentClient,this.files=new GeminiNextGenEnvironmentFiles(apiVersion=>this.getClient(apiVersion),this.parentClient)}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(environmentsCreateEnvironment(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){
1757
- let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(environmentsListEnvironments(this.getClient(api_version),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(environmentsGetEnvironment(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(environmentsDeleteEnvironment(this.
1758
- getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenCredentials=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(
1759
- credentialsCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(credentialsList(this.getClient(api_version),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(credentialsGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params,options){
1760
- let{api_version,update_mask}=params,body=__rest(params,["api_version","update_mask"]);return unwrapWithSdkHttpResponse(credentialsUpdate(this.getClient(api_version),id,body,api_version,update_mask,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(credentialsDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,
1761
- {api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenVoices=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(voicesCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,accent,contexts,gender,
1762
- language_code,page_size,page_token,persona,pitch,region_code,search,type}=params??{};return unwrapWithSdkHttpResponse(voicesList(this.getClient(api_version),api_version,accent,contexts,gender,language_code,page_size,page_token,persona,pitch,region_code,search,type,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(voicesGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){
1763
- return unwrapWithSdkHttpResponse(voicesDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}};var GOOGLE_API_KEY_HEADER="x-goog-api-key",REQUIRED_VERTEX_AI_SCOPE="https://www.googleapis.com/auth/cloud-platform",NodeAuth=class{constructor(opts){
1764
- if(opts.apiKey!==void 0){this.apiKey=opts.apiKey;return}let vertexAuthOptions=buildGoogleAuthOptions(opts.googleAuthOptions);this.googleAuth=new import_google_auth_library.GoogleAuth(vertexAuthOptions)}async addAuthHeaders(headers,url){if(this.apiKey!==void 0){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(headers);return}return this.addGoogleAuthHeaders(headers,url)}addKeyHeader(headers){if(headers.get(GOOGLE_API_KEY_HEADER)===
1765
- null){if(this.apiKey===void 0)throw new Error("Trying to set API key header but apiKey is not set");headers.append(GOOGLE_API_KEY_HEADER,this.apiKey)}}async addGoogleAuthHeaders(headers,url){if(this.googleAuth===void 0)throw new Error("Trying to set google-auth headers but googleAuth is unset");let authHeaders=await this.googleAuth.getRequestHeaders(url);for(let[key,value]of authHeaders)headers.get(key)===null&&headers.append(key,value)}};function buildGoogleAuthOptions(googleAuthOptions){let authOptions;
1766
- if(googleAuthOptions){if(authOptions=googleAuthOptions,authOptions.scopes){if(typeof authOptions.scopes=="string"&&authOptions.scopes!==REQUIRED_VERTEX_AI_SCOPE||Array.isArray(authOptions.scopes)&&authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE)<0)throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`)}else return authOptions.scopes=[REQUIRED_VERTEX_AI_SCOPE],authOptions;return authOptions}else return authOptions={scopes:[REQUIRED_VERTEX_AI_SCOPE]},authOptions}
1767
- var NodeDownloader=class{async download(params,apiClient){if(params.downloadPath){let response=await downloadFile(params,apiClient);if(response instanceof HttpResponse){let writer=createWriteStream(params.downloadPath);Readable.fromWeb(response.responseInternal.body).pipe(writer),await finished(writer)}else try{await writeFile(params.downloadPath,response,{encoding:"base64"})}catch(error){throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`)}}}};async function downloadFile(params,apiClient){
1768
- var _a2,_b,_c;let name=tFileName(params.file);if(name!==void 0)return await apiClient.request({path:`files/${name}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal});if(isGeneratedVideo(params.file)){let videoBytes=(_c=params.file.video)===null||_c===void 0?void 0:_c.videoBytes;if(typeof videoBytes=="string")return videoBytes;throw new Error("Fa\
1769
- iled to download generated video, Uri or videoBytes not found.")}else if(isVideo(params.file)){let videoBytes=params.file.videoBytes;if(typeof videoBytes=="string")return videoBytes;throw new Error("Failed to download video, Uri or videoBytes not found.")}else throw new Error("Unsupported file type")}var NodeWebSocketFactory=class{create(url,headers,callbacks){return new NodeWebSocket(url,headers,callbacks)}},NodeWebSocket=class{constructor(url,headers,callbacks){this.url=url,this.headers=headers,
1770
- this.callbacks=callbacks}connect(){this.ws=new import_websocket.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(message){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(message)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}};function cancelTuningJobParametersToMldev(fromObject,_rootObject){
1771
- let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function cancelTuningJobParametersToVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function cancelTuningJobResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);
1772
- return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function cancelTuningJobResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function computerUseToVertex(fromObject,_rootObject){let toObject={},fromEnablePromptInjectionDetection=getValueByPath(fromObject,["en\
1773
- ablePromptInjectionDetection"]);fromEnablePromptInjectionDetection!=null&&setValueByPath(toObject,["enablePromptInjectionDetection"],fromEnablePromptInjectionDetection);let fromEnvironment=getValueByPath(fromObject,["environment"]);fromEnvironment!=null&&setValueByPath(toObject,["environment"],fromEnvironment);let fromExcludedPredefinedFunctions=getValueByPath(fromObject,["excludedPredefinedFunctions"]);if(fromExcludedPredefinedFunctions!=null&&setValueByPath(toObject,["excludedPredefinedFunctio\
1774
- ns"],fromExcludedPredefinedFunctions),getValueByPath(fromObject,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function contentToVertex(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex(
1775
- item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createTuningJobConfigToMldev(fromObject,parentObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromTunedModelDisplayName=getValueByPath(
1776
- fromObject,["tunedModelDisplayName"]);if(parentObject!==void 0&&fromTunedModelDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromTunedModelDisplayName),getValueByPath(fromObject,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["tuningTas\
1777
- k","hyperparameters","epochCount"],fromEpochCount);let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);if(fromLearningRateMultiplier!=null&&setValueByPath(toObject,["tuningTask","hyperparameters","learningRateMultiplier"],fromLearningRateMultiplier),getValueByPath(fromObject,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(
1778
- fromObject,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is only supported \
1779
- in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","batchSize"],fromBatchSize);let fromLearningRate=getValueByPath(
1780
- fromObject,["learningRate"]);if(parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","learningRate"],fromLearningRate),getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["beta"])!==void 0)throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gem\
1781
- ini Developer API mode.");if(getValueByPath(fromObject,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["sftLossWeightMultiplier"])!==
1782
- void 0)throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputUri"])!==void 0)throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["rewardConfig"])!==void 0)throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not \
1783
- in Gemini Developer API mode.");if(getValueByPath(fromObject,["compositeRewardConfig"])!==void 0)throw new Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["samplesPerPrompt"])!==void 0)throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["evaluateInterval"])!==void 0)
1784
- throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["checkpointInterval"])!==void 0)throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["maxOutputTokens"])!==void 0)throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform \
1785
- mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["thinkingLevel"])!==void 0)throw new Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["validationDatasetUri"])!==void 0)throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["encryptionSpec"])!==void 0)
1786
- throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function createTuningJobConfigToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorValidationDataset=getValueByPath(rootObject,["config","method"]);if(discriminatorValidationDataset===void 0&&(discriminatorValidationDataset="SUPERVISED_FINE_TUNING"),discriminatorValidationDataset==="SUPERVISED_FINE_TUNING"){let fromValidationDataset=getValueByPath(
1787
- fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["supervisedTuningSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="PREFERENCE_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset===
1788
- "DISTILLATION"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["distillationSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="REINFORCEMENT_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["reinforcementTuningSpec"],tuningValidationDatasetToVertex(
1789
- fromValidationDataset))}let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);parentObject!==void 0&&fromTunedModelDisplayName!=null&&setValueByPath(parentObject,["tunedModelDisplayName"],fromTunedModelDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let discriminatorEpochCount=getValueByPath(rootObject,["config","method"]);if(discriminatorEpochCount===
1790
- void 0&&(discriminatorEpochCount="SUPERVISED_FINE_TUNING"),discriminatorEpochCount==="SUPERVISED_FINE_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="PREFERENCE_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,
1791
- ["preferenceOptimizationSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="DISTILLATION"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="REINFORCEMENT_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(
1792
- parentObject,["reinforcementTuningSpec","hyperParameters","epochCount"],fromEpochCount)}let discriminatorLearningRateMultiplier=getValueByPath(rootObject,["config","method"]);if(discriminatorLearningRateMultiplier===void 0&&(discriminatorLearningRateMultiplier="SUPERVISED_FINE_TUNING"),discriminatorLearningRateMultiplier==="SUPERVISED_FINE_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(
1793
- parentObject,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="PREFERENCE_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="DISTI\
1794
- LLATION"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="REINFORCEMENT_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,
1795
- ["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}let discriminatorExportLastCheckpointOnly=getValueByPath(rootObject,["config","method"]);if(discriminatorExportLastCheckpointOnly===void 0&&(discriminatorExportLastCheckpointOnly="SUPERVISED_FINE_TUNING"),discriminatorExportLastCheckpointOnly==="SUPERVISED_FINE_TUNING"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=
1796
- null&&setValueByPath(parentObject,["supervisedTuningSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}else if(discriminatorExportLastCheckpointOnly==="PREFERENCE_TUNING"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}else if(discriminatorExportLastCheckpointOnly==="DI\
1797
- STILLATION"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["distillationSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}let discriminatorAdapterSize=getValueByPath(rootObject,["config","method"]);if(discriminatorAdapterSize===void 0&&(discriminatorAdapterSize="SUPERVISED_FINE_TUNING"),discriminatorAdapterSize==="SUPERVISED_FINE_TUNING"){let fromAdapterSize=getValueByPath(
1798
- fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="PREFERENCE_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="DISTILLATION"){
1799
- let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="REINFORCEMENT_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","adapterSize"],fromAdapterSize)}let discriminatorTuningMode=getValueByPath(
1800
- rootObject,["config","method"]);if(discriminatorTuningMode===void 0&&(discriminatorTuningMode="SUPERVISED_FINE_TUNING"),discriminatorTuningMode==="SUPERVISED_FINE_TUNING"){let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);parentObject!==void 0&&fromTuningMode!=null&&setValueByPath(parentObject,["supervisedTuningSpec","tuningMode"],fromTuningMode)}else if(discriminatorTuningMode==="DISTILLATION"){let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);parentObject!==void 0&&fromTuningMode!=
1801
- null&&setValueByPath(parentObject,["distillationSpec","tuningMode"],fromTuningMode)}let fromCustomBaseModel=getValueByPath(fromObject,["customBaseModel"]);parentObject!==void 0&&fromCustomBaseModel!=null&&setValueByPath(parentObject,["customBaseModel"],fromCustomBaseModel);let discriminatorBatchSize=getValueByPath(rootObject,["config","method"]);if(discriminatorBatchSize===void 0&&(discriminatorBatchSize="SUPERVISED_FINE_TUNING"),discriminatorBatchSize==="SUPERVISED_FINE_TUNING"){let fromBatchSize=getValueByPath(
1802
- fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","batchSize"],fromBatchSize)}else if(discriminatorBatchSize==="DISTILLATION"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","batchSize"],fromBatchSize)}else if(discriminatorBatchSize==="REINFORCEMENT_TUNING"){let fromBatchSize=getValueByPath(
1803
- fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","batchSize"],fromBatchSize)}let discriminatorLearningRate=getValueByPath(rootObject,["config","method"]);if(discriminatorLearningRate===void 0&&(discriminatorLearningRate="SUPERVISED_FINE_TUNING"),discriminatorLearningRate==="SUPERVISED_FINE_TUNING"){let fromLearningRate=getValueByPath(fromObject,["learningRate"]);parentObject!==void 0&&fromLearningRate!=
1804
- null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","learningRate"],fromLearningRate)}else if(discriminatorLearningRate==="DISTILLATION"){let fromLearningRate=getValueByPath(fromObject,["learningRate"]);parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","learningRate"],fromLearningRate)}let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["la\
1805
- bels"],fromLabels);let fromBeta=getValueByPath(fromObject,["beta"]);parentObject!==void 0&&fromBeta!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","beta"],fromBeta);let fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);parentObject!==void 0&&fromBaseTeacherModel!=null&&setValueByPath(parentObject,["distillationSpec","baseTeacherModel"],fromBaseTeacherModel);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);
1806
- parentObject!==void 0&&fromTunedTeacherModelSource!=null&&setValueByPath(parentObject,["distillationSpec","tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromSftLossWeightMultiplier=getValueByPath(fromObject,["sftLossWeightMultiplier"]);parentObject!==void 0&&fromSftLossWeightMultiplier!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],fromSftLossWeightMultiplier);let fromOutputUri=getValueByPath(fromObject,["outputUri"]);parentObject!==
1807
- void 0&&fromOutputUri!=null&&setValueByPath(parentObject,["outputUri"],fromOutputUri);let fromRewardConfig=getValueByPath(fromObject,["rewardConfig"]);parentObject!==void 0&&fromRewardConfig!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","singleRewardConfig"],fromRewardConfig);let fromCompositeRewardConfig=getValueByPath(fromObject,["compositeRewardConfig"]);parentObject!==void 0&&fromCompositeRewardConfig!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","compositeRew\
1808
- ardConfig"],fromCompositeRewardConfig);let fromSamplesPerPrompt=getValueByPath(fromObject,["samplesPerPrompt"]);parentObject!==void 0&&fromSamplesPerPrompt!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],fromSamplesPerPrompt);let fromEvaluateInterval=getValueByPath(fromObject,["evaluateInterval"]);parentObject!==void 0&&fromEvaluateInterval!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],fromEvaluateInterval);
1809
- let fromCheckpointInterval=getValueByPath(fromObject,["checkpointInterval"]);parentObject!==void 0&&fromCheckpointInterval!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],fromCheckpointInterval);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],fromMaxOutputTokens);let fromThinkingLevel=getValueByPath(
1810
- fromObject,["thinkingLevel"]);parentObject!==void 0&&fromThinkingLevel!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],fromThinkingLevel);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);parentObject!==void 0&&fromValidationDatasetUri!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","validationDatasetUri"],fromValidationDatasetUri);let fromEncryptionSpec=getValueByPath(fromObject,["encryptionSpec"]);return parentObject!==
1811
- void 0&&fromEncryptionSpec!=null&&setValueByPath(parentObject,["encryptionSpec"],fromEncryptionSpec),toObject}function createTuningJobParametersPrivateToMldev(fromObject,rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromTrainingDataset=getValueByPath(
1812
- fromObject,["trainingDataset"]);fromTrainingDataset!=null&&tuningDatasetToMldev(fromTrainingDataset);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createTuningJobConfigToMldev(fromConfig,toObject),toObject}function createTuningJobParametersPrivateToVertex(fromObject,rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromPreTunedModel=getValueByPath(fromObject,
1813
- ["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromTrainingDataset=getValueByPath(fromObject,["trainingDataset"]);fromTrainingDataset!=null&&tuningDatasetToVertex(fromTrainingDataset,toObject,rootObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createTuningJobConfigToVertex(fromConfig,toObject,rootObject),toObject}function distillationHyperParametersFromVertex(fromObject,rootObject){let toObject={},
1814
- fromEpochCount=getValueByPath(fromObject,["epochCount"]);fromEpochCount!=null&&setValueByPath(toObject,["epochCount"],fromEpochCount);let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);fromLearningRateMultiplier!=null&&setValueByPath(toObject,["learningRateMultiplier"],fromLearningRateMultiplier);let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);fromAdapterSize!=null&&setValueByPath(toObject,["adapterSize"],fromAdapterSize);let fromBatchSize=getValueByPath(
1815
- fromObject,["batchSize"]);fromBatchSize!=null&&setValueByPath(toObject,["batchSize"],fromBatchSize);let fromLearningRate=getValueByPath(fromObject,["learningRate"]);fromLearningRate!=null&&setValueByPath(toObject,["learningRate"],fromLearningRate);let fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);return fromGenerationConfig!=null&&setValueByPath(toObject,["generationConfig"],generationConfigFromVertex(fromGenerationConfig)),toObject}function distillationSamplingSpecFromVertex(fromObject,rootObject){
1736
+ api_version,options))}get(id,params,options){return unwrapAsAPIPromise(webhooksGet(this,id,params?.api_version,options))}update(id,params,options){let{api_version,update_mask}=params,body=__rest(params,["api_version","update_mask"]);return unwrapAsAPIPromise(webhooksUpdate(this,id,body,api_version,update_mask,options))}ping(id,body,api_version,options){return unwrapAsAPIPromise(webhooksPing(this,id,body,api_version,options))}rotateSigningSecret(id,body,api_version,options){return unwrapAsAPIPromise(
1737
+ webhooksRotateSigningSecret(this,id,body,api_version,options))}};var GoogleGenAI$1=class extends ClientSDK{get environments(){var _a2;return(_a2=this._environments)!==null&&_a2!==void 0?_a2:this._environments=new Environments(this._options)}get agents(){var _a2;return(_a2=this._agents)!==null&&_a2!==void 0?_a2:this._agents=new Agents(this._options)}get credentials(){var _a2;return(_a2=this._credentials)!==null&&_a2!==void 0?_a2:this._credentials=new Credentials(this._options)}get interactions(){
1738
+ var _a2;return(_a2=this._interactions)!==null&&_a2!==void 0?_a2:this._interactions=new Interactions(this._options)}get triggers(){var _a2;return(_a2=this._triggers)!==null&&_a2!==void 0?_a2:this._triggers=new Triggers(this._options)}get voices(){var _a2;return(_a2=this._voices)!==null&&_a2!==void 0?_a2:this._voices=new Voices(this._options)}get webhooks(){var _a2;return(_a2=this._webhooks)!==null&&_a2!==void 0?_a2:this._webhooks=new Webhooks(this._options)}};var LEGACY_LYRIA_MODELS=new Set(["lyr\
1739
+ ia-3-pro-preview","lyria-3-clip-preview"]);function getGoogleGenAIServerURL(parentClient){let serverURL=parentClient.getBaseUrl();if(!serverURL)throw new Error("Base URL must be set.");return serverURL.replace(/\/+$/,"")}function getGoogleGenAIAPIVersion(parentClient){let apiVersion=trimSlashes(parentClient.getApiVersion()),project=parentClient.getProject(),location=parentClient.getLocation();return parentClient.isVertexAI()&&apiVersion&&project&&location?`${apiVersion}/projects/${encodeURIComponent(
1740
+ project)}/locations/${encodeURIComponent(location)}`:apiVersion}function buildGoogleGenAIClient(parentClient,options={}){var _a2,_b,_c,_d,_e,_f,_g,_h,_j,_k;let{timeout}=options,rest=__rest(options,["timeout"]),fetchFn=rest.http_client||(_a2=parentClient.getFetch)===null||_a2===void 0?void 0:_a2.call(parentClient),httpClient=(_b=rest.http_client)!==null&&_b!==void 0?_b:fetchFn?new HTTPClient({fetcher:fetchFn}):void 0,timeout_ms=(_d=(_c=rest.timeout_ms)!==null&&_c!==void 0?_c:timeout)!==null&&_d!==
1741
+ void 0?_d:(_e=parentClient.getTimeout)===null||_e===void 0?void 0:_e.call(parentClient);return new GoogleGenAI$1(Object.assign(Object.assign({},rest),{http_client:httpClient,api_version:(_f=rest.api_version)!==null&&_f!==void 0?_f:getGoogleGenAIAPIVersion(parentClient),security:(_g=rest.security)!==null&&_g!==void 0?_g:new GoogleGenAISecurityProvider({defaultHeaders:Object.assign(Object.assign({},(_h=parentClient.getDefaultHeaders)===null||_h===void 0?void 0:_h.call(parentClient)),(_j=parentClient.
1742
+ getHeaders)===null||_j===void 0?void 0:_j.call(parentClient)),getAuthHeaders:url=>parentClient.getAuthHeaders(url)}),server_url:(_k=rest.server_url)!==null&&_k!==void 0?_k:getGoogleGenAIServerURL(parentClient),timeout_ms}))}var GeminiNextGenInteractions=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,request=__rest(params,["api_version"]);if(request.stream===!0){let response2=await wrapSDKCall(()=>this.getClient(api_version).interactions.
1743
+ create(Object.assign(Object.assign({},request),{stream:!0,api_version}),toGoogleGenAIRequestOptions(options,!0)));return wrapStreamErrors(response2)}let response=await unwrapWithSdkHttpResponse(interactionsCreate(this.getClient(api_version),request,api_version,toGoogleGenAIRequestOptions(options)));return addOutputPropertiesIfInteraction(response)}async get(id,params={},options){let{api_version,stream=!1,last_event_id,include_input}=params??{};if(stream===!0){let response2=await wrapSDKCall(()=>this.
1744
+ getClient(api_version).interactions.get(id,{stream,last_event_id,include_input,api_version},toGoogleGenAIRequestOptions(options,!0)));return wrapStreamErrors(response2)}let response=await unwrapWithSdkHttpResponse(interactionsGet(this.getClient(api_version),id,api_version,include_input,last_event_id,stream,toGoogleGenAIRequestOptions(options)));return addOutputPropertiesIfInteraction(response)}async delete(id,params={},options){return wrapSDKCall(()=>this.getClient(params?.api_version).interactions.
1745
+ delete(id,{api_version:params?.api_version},toGoogleGenAIRequestOptions(options)))}async cancel(id,params={},options){return addOutputPropertiesIfInteraction(await unwrapWithSdkHttpResponse(interactionsCancel(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options))))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),
1746
+ this.sdk)}},GeminiNextGenAgents=class{constructor(parentClient){this.parentClient=parentClient}async create(params={},options){let _a2=params??{},{api_version}=_a2,body=__rest(_a2,["api_version"]);return unwrapWithSdkHttpResponse(agentsCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token,parent}=params??{};return unwrapWithSdkHttpResponse(agentsList(this.getClient(api_version),api_version,page_size,
1747
+ page_token,parent,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(agentsGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(agentsDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):
1748
+ ((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenWebhooks=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(webhooksCreate(this.getClient(),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(
1749
+ webhooksList(this.getClient(),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(webhooksGet(this.getClient(),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params={},options){let _a2=params??{},{api_version,update_mask}=_a2,body=__rest(_a2,["api_version","update_mask"]);return unwrapWithSdkHttpResponse(webhooksUpdate(this.getClient(),id,body,api_version,update_mask,toGoogleGenAIRequestOptions(
1750
+ options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(webhooksDelete(this.getClient(),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async rotateSigningSecret(id,params={},options){let _a2=params??{},{api_version}=_a2,body=__rest(_a2,["api_version"]);return unwrapWithSdkHttpResponse(webhooksRotateSigningSecret(this.getClient(),id,body,api_version,toGoogleGenAIRequestOptions(options)))}async ping(id,params=void 0,options){let{api_version,body}=params??{};return unwrapWithSdkHttpResponse(
1751
+ webhooksPing(this.getClient(),id,body??{},api_version,toGoogleGenAIRequestOptions(options)))}getClient(){var _a2;return(_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk}},GeminiNextGenTriggers=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(triggersCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(
1752
+ options)))}async list(params={},options){let{api_version,filter,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(triggersList(this.getClient(api_version),api_version,filter,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(triggersGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params,options){let{api_version}=params,body=__rest(params,
1753
+ ["api_version"]);return unwrapWithSdkHttpResponse(triggersUpdate(this.getClient(api_version),id,body,api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(triggersDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async run(trigger_id,params={},options){return unwrapWithSdkHttpResponse(triggersRun(this.getClient(params?.api_version),trigger_id,params?.api_version,toGoogleGenAIRequestOptions(
1754
+ options)))}async listExecutions(trigger_id,params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(triggersListExecutions(this.getClient(api_version),trigger_id,api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}};function trimSlashes(value){
1755
+ return value.replace(/^\/+|\/+$/g,"")}function toGoogleGenAIRequestOptions(options,streaming=!1){var _a2,_b,_c,_d;if(!options&&!streaming)return;let _e=options??{},{timeout,maxRetries,defaultBaseURL,query,body,fetchOptions}=_e,rest=__rest(_e,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),nextOptions=Object.assign({},rest);isPlainObject(query)?nextOptions.extra_query=query:warnIgnoredOption("query",query),isPlainObject(body)?nextOptions.extra_body=body:warnIgnoredOption(
1756
+ "body",body);let fetch_options=(_a2=rest.fetch_options)!==null&&_a2!==void 0?_a2:fetchOptions;fetch_options&&(nextOptions.fetch_options=fetch_options);let server_url=(_b=rest.server_url)!==null&&_b!==void 0?_b:defaultBaseURL;server_url&&(nextOptions.server_url=server_url);let timeout_ms=(_c=rest.timeout_ms)!==null&&_c!==void 0?_c:timeout;if(timeout_ms!==void 0&&(nextOptions.timeout_ms=timeout_ms),maxRetries!==void 0&&(nextOptions.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,
1757
+ maxRetries}),streaming){let headers=new Headers((_d=nextOptions.headers)!==null&&_d!==void 0?_d:fetch_options?.headers);headers.set("Accept","text/event-stream"),nextOptions.headers=headers}return nextOptions}function warnIgnoredOption(name,value){value!=null&&console.warn(`GoogleGenAI.interactions: request option ${name} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function unwrapWithSdkHttpResponse(promise){let[result,call]=await promise.$inspect();if(!result.
1758
+ ok)throw wrapSDKError(result.error);return attachSdkHttpResponse(result.value,call)}async function wrapSDKCall(operation){try{return await operation()}catch(error){throw wrapSDKError(error)}}function wrapStreamErrors(stream){let asyncIterable=stream;return new Proxy(stream,{get(target,property){if(property!==Symbol.asyncIterator){let value=Reflect.get(target,property,target);return typeof value=="function"?value.bind(target):value}return function(){let iterator=asyncIterable[Symbol.asyncIterator]();
1759
+ return{async next(...args){try{return await iterator.next(...args)}catch(error){throw wrapSDKError(error)}},async return(value){if(!iterator.return)return{done:!0,value};try{return await iterator.return(value)}catch(error){throw wrapSDKError(error)}},async throw(error){if(!iterator.throw)throw wrapSDKError(error);try{return await iterator.throw(error)}catch(caught){throw wrapSDKError(caught)}},[Symbol.asyncIterator](){return this}}}}})}function attachSdkHttpResponse(value,call){return!isPlainObject(
1760
+ value)||call.status!=="complete"?value:Object.assign(Object.assign({},value),{sdkHttpResponse:createSdkHttpResponse(call.response,value)})}function createSdkHttpResponse(response,parsedBody){let headers={};for(let[key,value]of response.headers.entries())headers[key]=value;return{headers,responseInternal:response,json:async()=>parsedBody}}function addOutputPropertiesIfInteraction(value){let interaction=normalizeInteractionShape(value);return interaction?addOutputProperties(interaction):value}function normalizeInteractionShape(value){
1761
+ if(isPlainObject(value)){if(Array.isArray(value.steps))return value;if(isLegacyLyriaInteraction(value)){let outputs=value.outputs;if(Array.isArray(outputs)){let{outputs:_outputs}=value,rest=__rest(value,["outputs"]);return Object.assign(Object.assign({},rest),{steps:[{type:"model_output",content:outputs}]})}}return Object.assign(Object.assign({},value),{steps:[]})}}function isLegacyLyriaInteraction(value){let model=value.model;return typeof model=="string"&&LEGACY_LYRIA_MODELS.has(model)}function isPlainObject(value){
1762
+ return typeof value=="object"&&value!==null&&!Array.isArray(value)}function addOutputProperties(interaction){var _a2,_b;let normalized=normalizeInteractionDates(interaction),steps=(_a2=normalized.steps)!==null&&_a2!==void 0?_a2:[],textParts=[],collecting=!1;outer:for(let i=steps.length-1;i>=0;i--){let step=steps[i];if(step.type==="user_input")break;if(step.type!=="model_output"||!step.content){if(collecting)break;continue}let content=step.content;for(let j=content.length-1;j>=0;j--){let item=content[j];
1763
+ if(item.type==="text")collecting=!0,textParts.push((_b=item.text)!==null&&_b!==void 0?_b:"");else if(collecting)break outer}}let output_image,output_audio,output_video;for(let i=steps.length-1;i>=0;i--){let step=steps[i];if(step.type==="user_input")break;if(step.type==="model_output"&&step.content)for(let j=step.content.length-1;j>=0;j--){let content=step.content[j];content.type==="image"&&!output_image&&(output_image=content),content.type==="audio"&&!output_audio&&(output_audio=content),content.
1764
+ type==="video"&&!output_video&&(output_video=content)}}let output_text=textParts.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},normalized),output_text&&{output_text}),output_image?{output_image}:{}),output_audio?{output_audio}:{}),output_video?{output_video}:{})}function normalizeInteractionDates(interaction){return Object.assign(Object.assign({},interaction),{created:normalizeDateLike(interaction.created),updated:normalizeDateLike(interaction.
1765
+ updated)})}function normalizeDateLike(value){return value instanceof Date?value.toISOString():value}function inferMimeType(filePath){let ext=filePath.slice(filePath.lastIndexOf(".")+1).toLowerCase();return{txt:"text/plain",json:"application/json",js:"text/javascript",mjs:"text/javascript",ts:"text/plain",py:"text/x-python",html:"text/html",htm:"text/html",css:"text/css",csv:"text/csv",xml:"application/xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"\
1766
+ image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[ext]}var GeminiNextGenEnvironmentFiles=class{constructor(resolveClient,parentClient){this.resolveClient=resolveClient,this.parentClient=parentClient}async list(params,options){return unwrapWithSdkHttpResponse(environmentsFilesList(this.resolveClient(params.api_version),params.environment,params.path,params.api_version,params.page_size,params.page_token,params.recursive,toGoogleGenAIRequestOptions(
1767
+ options)))}async download(params,options){var _a2,_b;let targetEnv=params.environment;if(!targetEnv)throw new Error("environment is required.");let envName=targetEnv.startsWith("environments/")?targetEnv:`environments/${targetEnv}`,cleanPath=params.path.replace(/^\/+/,""),downloadPath=`${envName}/files/${cleanPath}`,apiClient=this.parentClient;if(!apiClient||typeof apiClient.request!="function")throw new Error("apiClient is required to download files.");let response=await apiClient.request({path:downloadPath,
1768
+ httpMethod:"GET",queryParams:{alt:"media"},httpOptions:Object.assign(Object.assign({},options?.httpOptions),{apiVersion:(_a2=params.api_version)!==null&&_a2!==void 0?_a2:(_b=options?.httpOptions)===null||_b===void 0?void 0:_b.apiVersion})});if(response&&response.responseInternal&&typeof response.responseInternal.arrayBuffer=="function"){let arrayBuffer=await response.responseInternal.arrayBuffer();return new Uint8Array(arrayBuffer)}throw new Error("Unexpected response type from download")}async upload(params,options){
1769
+ var _a2,_b,_c,_d,_e,_f,_g,_h;let targetEnv=params.environment;if(!targetEnv)throw new Error("environment is required.");targetEnv.startsWith("environments/")||`${targetEnv}`;let cleanPath=params.path.replace(/^\/+/,""),apiClient=this.parentClient;if(!apiClient||typeof apiClient.request!="function")throw new Error("apiClient is required to upload files.");let fileData,sizeBytes=0,mimeType=params.mime_type;if(typeof params.file=="string"){let buffer;try{let req=globalThis.require;req&&(buffer=req(
1770
+ "fs").readFileSync(params.file))}catch{}if(!buffer&&typeof globalThis.process<"u")try{let mod=(_b=(_a2=globalThis.process.mainModule)===null||_a2===void 0?void 0:_a2.require)!==null&&_b!==void 0?_b:globalThis.require;mod&&(buffer=mod("fs").readFileSync(params.file))}catch{}if(buffer)fileData=new Uint8Array(buffer.buffer,buffer.byteOffset,buffer.byteLength),sizeBytes=fileData.byteLength;else throw new Error(`Unable to read file from path "${params.file}". File path string inputs are only supporte\
1771
+ d in Node.js environments.`);mimeType||(mimeType=inferMimeType(params.file))}else if(typeof Blob<"u"&&params.file instanceof Blob)fileData=params.file,sizeBytes=params.file.size,!mimeType&&params.file.type&&(mimeType=params.file.type);else if(params.file instanceof Uint8Array||params.file instanceof ArrayBuffer)fileData=params.file instanceof ArrayBuffer?new Uint8Array(params.file):params.file,sizeBytes=fileData.byteLength;else if(typeof globalThis.Buffer<"u"&&typeof globalThis.Buffer.isBuffer==
1772
+ "function"&&globalThis.Buffer.isBuffer(params.file)){let buf=params.file;fileData=new Uint8Array(buf.buffer,buf.byteOffset,buf.byteLength),sizeBytes=fileData.byteLength}else throw new Error("Unsupported file type for upload.");mimeType||(mimeType="application/octet-stream");let cleanEnv=targetEnv.startsWith("environments/")?targetEnv.replace(/^environments\//,""):targetEnv,[result,call]=await environmentsInternalStartUpload(this.resolveClient(params.api_version),cleanEnv,cleanPath,"start",sizeBytes,
1773
+ mimeType,"resumable",params.api_version,params.extract,params.overwrite,toGoogleGenAIRequestOptions(options)).$inspect();if(!result.ok)throw wrapSDKError(result.error);let uploadUrl=call.status==="complete"?(_e=(_d=(_c=call.response)===null||_c===void 0?void 0:_c.headers)===null||_d===void 0?void 0:_d.get("x-goog-upload-url"))!==null&&_e!==void 0?_e:(_g=(_f=call.response)===null||_f===void 0?void 0:_f.headers)===null||_g===void 0?void 0:_g.get("X-Goog-Upload-URL"):void 0;if(!uploadUrl)throw new Error(
1774
+ "Failed to get upload URL from upload handshake response.");let CHUNK_SIZE=8*1024*1024,offset=0,uploadResponse,blob=fileData instanceof Blob?fileData:new Blob([fileData]);for(;offset<sizeBytes||sizeBytes===0&&offset===0;){let end=Math.min(offset+CHUNK_SIZE,sizeBytes),chunk=blob.slice(offset,end),isFinal=end>=sizeBytes,uploadCommand=isFinal?"upload, finalize":"upload";if(uploadResponse=await apiClient.request({path:"",body:chunk,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},options?.
1775
+ httpOptions),{apiVersion:"",baseUrl:uploadUrl,headers:Object.assign(Object.assign({},((_h=options?.httpOptions)===null||_h===void 0?void 0:_h.headers)||{}),{"X-Goog-Upload-Command":uploadCommand,"X-Goog-Upload-Offset":`${offset}`})})}),offset=end,isFinal)break}let resJson;if(uploadResponse&&typeof uploadResponse.json=="function"?resJson=await uploadResponse.json():uploadResponse&&uploadResponse.responseInternal&&typeof uploadResponse.responseInternal.json=="function"&&(resJson=await uploadResponse.
1776
+ responseInternal.json()),resJson&&typeof resJson=="object"){if(Array.isArray(resJson.files))return resJson;if(resJson.name||resJson.path)return{files:[resJson]};if(resJson.file&&typeof resJson.file=="object")return{files:[resJson.file]}}return resJson}},GeminiNextGenEnvironments=class{constructor(parentClient){this.parentClient=parentClient,this.files=new GeminiNextGenEnvironmentFiles(apiVersion=>this.getClient(apiVersion),this.parentClient)}async create(params,options){let{api_version}=params,body=__rest(
1777
+ params,["api_version"]);return unwrapWithSdkHttpResponse(environmentsCreateEnvironment(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(environmentsListEnvironments(this.getClient(api_version),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(environmentsGetEnvironment(
1778
+ this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(environmentsDeleteEnvironment(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),
1779
+ this.sdk)}},GeminiNextGenCredentials=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(credentialsCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(credentialsList(this.getClient(api_version),api_version,page_size,
1780
+ page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(credentialsGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params,options){let{api_version,update_mask}=params,body=__rest(params,["api_version","update_mask"]);return unwrapWithSdkHttpResponse(credentialsUpdate(this.getClient(api_version),id,body,api_version,update_mask,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){
1781
+ return unwrapWithSdkHttpResponse(credentialsDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenVoices=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,
1782
+ body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(voicesCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,accent,contexts,gender,language_code,page_size,page_token,persona,pitch,region_code,search,type}=params??{};return unwrapWithSdkHttpResponse(voicesList(this.getClient(api_version),api_version,accent,contexts,gender,language_code,page_size,page_token,persona,pitch,region_code,search,type,
1783
+ toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(voicesGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(voicesDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):
1784
+ ((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}};var GOOGLE_API_KEY_HEADER="x-goog-api-key",REQUIRED_VERTEX_AI_SCOPE="https://www.googleapis.com/auth/cloud-platform",NodeAuth=class{constructor(opts){if(opts.apiKey!==void 0){this.apiKey=opts.apiKey;return}let vertexAuthOptions=buildGoogleAuthOptions(opts.googleAuthOptions);this.googleAuth=new import_google_auth_library.GoogleAuth(vertexAuthOptions)}async addAuthHeaders(headers,url){if(this.apiKey!==
1785
+ void 0){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(headers);return}return this.addGoogleAuthHeaders(headers,url)}addKeyHeader(headers){if(headers.get(GOOGLE_API_KEY_HEADER)===null){if(this.apiKey===void 0)throw new Error("Trying to set API key header but apiKey is not set");headers.append(GOOGLE_API_KEY_HEADER,this.apiKey)}}async addGoogleAuthHeaders(headers,url){if(this.googleAuth===void 0)throw new Error("\
1786
+ Trying to set google-auth headers but googleAuth is unset");let authHeaders=await this.googleAuth.getRequestHeaders(url);for(let[key,value]of authHeaders)headers.get(key)===null&&headers.append(key,value)}};function buildGoogleAuthOptions(googleAuthOptions){let authOptions;if(googleAuthOptions){if(authOptions=googleAuthOptions,authOptions.scopes){if(typeof authOptions.scopes=="string"&&authOptions.scopes!==REQUIRED_VERTEX_AI_SCOPE||Array.isArray(authOptions.scopes)&&authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE)<
1787
+ 0)throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`)}else return authOptions.scopes=[REQUIRED_VERTEX_AI_SCOPE],authOptions;return authOptions}else return authOptions={scopes:[REQUIRED_VERTEX_AI_SCOPE]},authOptions}var NodeDownloader=class{async download(params,apiClient){if(params.downloadPath){let response=await downloadFile(params,apiClient);if(response instanceof HttpResponse){let writer=createWriteStream(params.downloadPath);Readable.fromWeb(response.responseInternal.
1788
+ body).pipe(writer),await finished(writer)}else try{await writeFile(params.downloadPath,response,{encoding:"base64"})}catch(error){throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`)}}}};async function downloadFile(params,apiClient){var _a2,_b,_c;let name=tFileName(params.file);if(name!==void 0)return await apiClient.request({path:`files/${name}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,
1789
+ abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal});if(isGeneratedVideo(params.file)){let videoBytes=(_c=params.file.video)===null||_c===void 0?void 0:_c.videoBytes;if(typeof videoBytes=="string")return videoBytes;throw new Error("Failed to download generated video, Uri or videoBytes not found.")}else if(isVideo(params.file)){let videoBytes=params.file.videoBytes;if(typeof videoBytes=="string")return videoBytes;throw new Error("Failed to download video, Uri or videoBytes n\
1790
+ ot found.")}else throw new Error("Unsupported file type")}var NodeWebSocketFactory=class{create(url,headers,callbacks){return new NodeWebSocket(url,headers,callbacks)}},NodeWebSocket=class{constructor(url,headers,callbacks){this.url=url,this.headers=headers,this.callbacks=callbacks}connect(){this.ws=new import_websocket.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.
1791
+ callbacks.onmessage}send(message){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(message)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}};function cancelTuningJobParametersToMldev(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function cancelTuningJobParametersToVertex(fromObject,_rootObject){let toObject={},
1792
+ fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function cancelTuningJobResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function cancelTuningJobResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(
1793
+ fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function contentToVertex(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=
1794
+ null&&setValueByPath(toObject,["role"],fromRole),toObject}function createTuningJobConfigToMldev(fromObject,parentObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);if(parentObject!==void 0&&fromTunedModelDisplayName!=null&&setValueByPath(
1795
+ parentObject,["displayName"],fromTunedModelDisplayName),getValueByPath(fromObject,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","epochCount"],fromEpochCount);let fromLearningRateMultiplier=getValueByPath(fromObject,["le\
1796
+ arningRateMultiplier"]);if(fromLearningRateMultiplier!=null&&setValueByPath(toObject,["tuningTask","hyperparameters","learningRateMultiplier"],fromLearningRateMultiplier),getValueByPath(fromObject,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId para\
1797
+ meter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,
1798
+ ["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","batchSize"],fromBatchSize);let fromLearningRate=getValueByPath(fromObject,["learningRate"]);if(parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,
1799
+ ["tuningTask","hyperparameters","learningRate"],fromLearningRate),getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["beta"])!==void 0)throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["baseTeacherModel"])!==void 0)throw new Error("base\
1800
+ TeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Plat\
1801
+ form mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputUri"])!==void 0)throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["rewardConfig"])!==void 0)throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["compositeRewardConfig"])!==void 0)throw new Error(
1802
+ "compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["samplesPerPrompt"])!==void 0)throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["evaluateInterval"])!==void 0)throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in \
1803
+ Gemini Developer API mode.");if(getValueByPath(fromObject,["checkpointInterval"])!==void 0)throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["maxOutputTokens"])!==void 0)throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["thinkingLevel"])!==void 0)throw new Error(
1804
+ "thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["validationDatasetUri"])!==void 0)throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemi\
1805
+ ni Developer API mode.");return toObject}function createTuningJobConfigToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorValidationDataset=getValueByPath(rootObject,["config","method"]);if(discriminatorValidationDataset===void 0&&(discriminatorValidationDataset="SUPERVISED_FINE_TUNING"),discriminatorValidationDataset==="SUPERVISED_FINE_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(
1806
+ parentObject,["supervisedTuningSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="PREFERENCE_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="DISTILLATION"){let fromValidationDataset=getValueByPath(fromObject,
1807
+ ["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["distillationSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="REINFORCEMENT_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["reinforcementTuningSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}let fromTunedModelDisplayName=getValueByPath(
1808
+ fromObject,["tunedModelDisplayName"]);parentObject!==void 0&&fromTunedModelDisplayName!=null&&setValueByPath(parentObject,["tunedModelDisplayName"],fromTunedModelDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let discriminatorEpochCount=getValueByPath(rootObject,["config","method"]);if(discriminatorEpochCount===void 0&&(discriminatorEpochCount="SUPERVISED_FINE_T\
1809
+ UNING"),discriminatorEpochCount==="SUPERVISED_FINE_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="PREFERENCE_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameter\
1810
+ s","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="DISTILLATION"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="REINFORCEMENT_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["reinforcementTuningSp\
1811
+ ec","hyperParameters","epochCount"],fromEpochCount)}let discriminatorLearningRateMultiplier=getValueByPath(rootObject,["config","method"]);if(discriminatorLearningRateMultiplier===void 0&&(discriminatorLearningRateMultiplier="SUPERVISED_FINE_TUNING"),discriminatorLearningRateMultiplier==="SUPERVISED_FINE_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["supervisedTun\
1812
+ ingSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="PREFERENCE_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="DISTILLATION"){let fromLearningRateMultiplier=getValueByPath(
1813
+ fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="REINFORCEMENT_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters",
1814
+ "learningRateMultiplier"],fromLearningRateMultiplier)}let discriminatorExportLastCheckpointOnly=getValueByPath(rootObject,["config","method"]);if(discriminatorExportLastCheckpointOnly===void 0&&(discriminatorExportLastCheckpointOnly="SUPERVISED_FINE_TUNING"),discriminatorExportLastCheckpointOnly==="SUPERVISED_FINE_TUNING"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,
1815
+ ["supervisedTuningSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}else if(discriminatorExportLastCheckpointOnly==="PREFERENCE_TUNING"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}else if(discriminatorExportLastCheckpointOnly==="DISTILLATION"){let fromExportLastCheckpointOnly=getValueByPath(
1816
+ fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["distillationSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}let discriminatorAdapterSize=getValueByPath(rootObject,["config","method"]);if(discriminatorAdapterSize===void 0&&(discriminatorAdapterSize="SUPERVISED_FINE_TUNING"),discriminatorAdapterSize==="SUPERVISED_FINE_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==
1817
+ void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="PREFERENCE_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="DISTILLATION"){let fromAdapterSize=getValueByPath(fromObject,
1818
+ ["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="REINFORCEMENT_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","adapterSize"],fromAdapterSize)}let discriminatorTuningMode=getValueByPath(rootObject,["config","m\
1819
+ ethod"]);if(discriminatorTuningMode===void 0&&(discriminatorTuningMode="SUPERVISED_FINE_TUNING"),discriminatorTuningMode==="SUPERVISED_FINE_TUNING"){let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);parentObject!==void 0&&fromTuningMode!=null&&setValueByPath(parentObject,["supervisedTuningSpec","tuningMode"],fromTuningMode)}else if(discriminatorTuningMode==="DISTILLATION"){let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);parentObject!==void 0&&fromTuningMode!=null&&setValueByPath(
1820
+ parentObject,["distillationSpec","tuningMode"],fromTuningMode)}let fromCustomBaseModel=getValueByPath(fromObject,["customBaseModel"]);parentObject!==void 0&&fromCustomBaseModel!=null&&setValueByPath(parentObject,["customBaseModel"],fromCustomBaseModel);let discriminatorBatchSize=getValueByPath(rootObject,["config","method"]);if(discriminatorBatchSize===void 0&&(discriminatorBatchSize="SUPERVISED_FINE_TUNING"),discriminatorBatchSize==="SUPERVISED_FINE_TUNING"){let fromBatchSize=getValueByPath(fromObject,
1821
+ ["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","batchSize"],fromBatchSize)}else if(discriminatorBatchSize==="DISTILLATION"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","batchSize"],fromBatchSize)}else if(discriminatorBatchSize==="REINFORCEMENT_TUNING"){let fromBatchSize=getValueByPath(fromObject,
1822
+ ["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","batchSize"],fromBatchSize)}let discriminatorLearningRate=getValueByPath(rootObject,["config","method"]);if(discriminatorLearningRate===void 0&&(discriminatorLearningRate="SUPERVISED_FINE_TUNING"),discriminatorLearningRate==="SUPERVISED_FINE_TUNING"){let fromLearningRate=getValueByPath(fromObject,["learningRate"]);parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(
1823
+ parentObject,["supervisedTuningSpec","hyperParameters","learningRate"],fromLearningRate)}else if(discriminatorLearningRate==="DISTILLATION"){let fromLearningRate=getValueByPath(fromObject,["learningRate"]);parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","learningRate"],fromLearningRate)}let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromBeta=getValueByPath(
1824
+ fromObject,["beta"]);parentObject!==void 0&&fromBeta!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","beta"],fromBeta);let fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);parentObject!==void 0&&fromBaseTeacherModel!=null&&setValueByPath(parentObject,["distillationSpec","baseTeacherModel"],fromBaseTeacherModel);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);parentObject!==void 0&&fromTunedTeacherModelSource!=
1825
+ null&&setValueByPath(parentObject,["distillationSpec","tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromSftLossWeightMultiplier=getValueByPath(fromObject,["sftLossWeightMultiplier"]);parentObject!==void 0&&fromSftLossWeightMultiplier!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],fromSftLossWeightMultiplier);let fromOutputUri=getValueByPath(fromObject,["outputUri"]);parentObject!==void 0&&fromOutputUri!=null&&setValueByPath(parentObject,
1826
+ ["outputUri"],fromOutputUri);let fromRewardConfig=getValueByPath(fromObject,["rewardConfig"]);parentObject!==void 0&&fromRewardConfig!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","singleRewardConfig"],fromRewardConfig);let fromCompositeRewardConfig=getValueByPath(fromObject,["compositeRewardConfig"]);parentObject!==void 0&&fromCompositeRewardConfig!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","compositeRewardConfig"],fromCompositeRewardConfig);let fromSamplesPerPrompt=getValueByPath(
1827
+ fromObject,["samplesPerPrompt"]);parentObject!==void 0&&fromSamplesPerPrompt!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],fromSamplesPerPrompt);let fromEvaluateInterval=getValueByPath(fromObject,["evaluateInterval"]);parentObject!==void 0&&fromEvaluateInterval!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],fromEvaluateInterval);let fromCheckpointInterval=getValueByPath(fromObject,["checkpo\
1828
+ intInterval"]);parentObject!==void 0&&fromCheckpointInterval!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],fromCheckpointInterval);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],fromMaxOutputTokens);let fromThinkingLevel=getValueByPath(fromObject,["thinkingLevel"]);parentObject!==
1829
+ void 0&&fromThinkingLevel!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],fromThinkingLevel);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);parentObject!==void 0&&fromValidationDatasetUri!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","validationDatasetUri"],fromValidationDatasetUri);let fromEncryptionSpec=getValueByPath(fromObject,["encryptionSpec"]);return parentObject!==void 0&&fromEncryptionSpec!=
1830
+ null&&setValueByPath(parentObject,["encryptionSpec"],fromEncryptionSpec),toObject}function createTuningJobParametersPrivateToMldev(fromObject,rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromTrainingDataset=getValueByPath(fromObject,
1831
+ ["trainingDataset"]);fromTrainingDataset!=null&&tuningDatasetToMldev(fromTrainingDataset);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createTuningJobConfigToMldev(fromConfig,toObject),toObject}function createTuningJobParametersPrivateToVertex(fromObject,rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromPreTunedModel=getValueByPath(fromObject,["preTu\
1832
+ nedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromTrainingDataset=getValueByPath(fromObject,["trainingDataset"]);fromTrainingDataset!=null&&tuningDatasetToVertex(fromTrainingDataset,toObject,rootObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createTuningJobConfigToVertex(fromConfig,toObject,rootObject),toObject}function distillationHyperParametersFromVertex(fromObject,rootObject){let toObject={},fromEpochCount=getValueByPath(
1833
+ fromObject,["epochCount"]);fromEpochCount!=null&&setValueByPath(toObject,["epochCount"],fromEpochCount);let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);fromLearningRateMultiplier!=null&&setValueByPath(toObject,["learningRateMultiplier"],fromLearningRateMultiplier);let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);fromAdapterSize!=null&&setValueByPath(toObject,["adapterSize"],fromAdapterSize);let fromBatchSize=getValueByPath(fromObject,["batchSize"]);
1834
+ fromBatchSize!=null&&setValueByPath(toObject,["batchSize"],fromBatchSize);let fromLearningRate=getValueByPath(fromObject,["learningRate"]);fromLearningRate!=null&&setValueByPath(toObject,["learningRate"],fromLearningRate);let fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);return fromGenerationConfig!=null&&setValueByPath(toObject,["generationConfig"],generationConfigFromVertex(fromGenerationConfig)),toObject}function distillationSamplingSpecFromVertex(fromObject,rootObject){
1816
1835
  let toObject={},fromPromptDatasetUri=getValueByPath(fromObject,["promptDatasetUri"]);fromPromptDatasetUri!=null&&setValueByPath(toObject,["promptDatasetUri"],fromPromptDatasetUri);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);fromValidationDatasetUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromValidationDatasetUri);let fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);fromBaseTeacherModel!=null&&setValueByPath(toObject,["baseT\
1817
1836
  eacherModel"],fromBaseTeacherModel);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);fromTunedTeacherModelSource!=null&&setValueByPath(toObject,["tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromHyperparameters=getValueByPath(fromObject,["hyperparameters"]);return fromHyperparameters!=null&&setValueByPath(toObject,["hyperparameters"],distillationHyperParametersFromVertex(fromHyperparameters)),toObject}function distillationSpecFromVertex(fromObject,rootObject){
1818
1837
  let toObject={},fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);fromBaseTeacherModel!=null&&setValueByPath(toObject,["baseTeacherModel"],fromBaseTeacherModel);let fromHyperParameters=getValueByPath(fromObject,["hyperParameters"]);fromHyperParameters!=null&&setValueByPath(toObject,["hyperParameters"],distillationHyperParametersFromVertex(fromHyperParameters));let fromPipelineRootDirectory=getValueByPath(fromObject,["pipelineRootDirectory"]);fromPipelineRootDirectory!=null&&setValueByPath(
@@ -1840,7 +1859,7 @@ null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing);let fromS
1840
1859
  ["contents"]);if(fromContents!=null){let transformedList=fromContents;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex(item))),setValueByPath(toObject,["contents"],transformedList)}let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);fromSystemInstruction!=null&&setValueByPath(toObject,["systemInstruction"],contentToVertex(fromSystemInstruction));let fromTools=getValueByPath(fromObject,["tools"]);if(fromTools!=null){let transformedList=fromTools;
1841
1860
  Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex(item))),setValueByPath(toObject,["tools"],transformedList)}return toObject}function toolToVertex(fromObject,rootObject){let toObject={},fromRetrieval=getValueByPath(fromObject,["retrieval"]);fromRetrieval!=null&&setValueByPath(toObject,["retrieval"],fromRetrieval);let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],fromGoogleMaps);let fromMcpServers=getValueByPath(
1842
1861
  fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>mcpServerToVertex(item))),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,
1843
- ["computerUse"],computerUseToVertex(fromComputerUse));let fromEnterpriseWebSearch=getValueByPath(fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;
1862
+ ["computerUse"],fromComputerUse);let fromEnterpriseWebSearch=getValueByPath(fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;
1844
1863
  Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(
1845
1864
  fromObject,["parallelAiSearch"]);fromParallelAiSearch!=null&&setValueByPath(toObject,["parallelAiSearch"],fromParallelAiSearch);let fromUrlContext=getValueByPath(fromObject,["urlContext"]);if(fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext),getValueByPath(fromObject,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function tunedModelFromMldev(fromObject,_rootObject){
1846
1865
  let toObject={},fromModel=getValueByPath(fromObject,["name"]);fromModel!=null&&setValueByPath(toObject,["model"],fromModel);let fromEndpoint=getValueByPath(fromObject,["name"]);return fromEndpoint!=null&&setValueByPath(toObject,["endpoint"],fromEndpoint),toObject}function tuningDatasetToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Develope\