@averyyy/pi-coding-agent 1.4.0-piclient.9 → 1.5.0-piclient.1
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.
- package/CHANGELOG.md +122 -4
- package/dist/bundle/chunks/anthropic-messages-WU4RRDFO.js +6 -0
- package/dist/bundle/chunks/azure-openai-responses-M725JFGO.js +2 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +7 -4
- package/dist/bundle/chunks/chunk-3UW3IQIY.js +16 -0
- package/dist/bundle/chunks/chunk-4RKLODCT.js +2 -0
- package/dist/bundle/chunks/{chunk-3LTMO2WY.js → chunk-75IISYAM.js} +2 -2
- package/dist/bundle/chunks/{chunk-CF5GWZHW.js → chunk-A3Y7H47A.js} +1 -1
- package/dist/bundle/chunks/chunk-FFMDRXC4.js +10 -0
- package/dist/bundle/chunks/{chunk-D3OXAPLU.js → chunk-G23G7KNC.js} +2 -9
- package/dist/bundle/chunks/chunk-GJFZM2RZ.js +129 -0
- package/dist/bundle/chunks/chunk-GO33PKBT.js +9 -0
- package/dist/bundle/chunks/{chunk-H2AI7MFJ.js → chunk-JM6XUN2B.js} +2 -2
- package/dist/bundle/chunks/{chunk-BRYV63PL.js → chunk-LTLKVIE2.js} +8 -7
- package/dist/bundle/chunks/chunk-LXHWY6K4.js +1592 -0
- package/dist/bundle/chunks/{chunk-MKWEYCNF.js → chunk-N4CTF6DK.js} +2 -2
- package/dist/bundle/chunks/chunk-O5CTLHDX.js +82 -0
- package/dist/bundle/chunks/chunk-OV4EHN3Q.js +2 -0
- package/dist/bundle/chunks/{chunk-3EGEEHMN.js → chunk-OW4KH7CI.js} +1 -1
- package/dist/bundle/chunks/{chunk-HZG4C6GI.js → chunk-OXKIVFVM.js} +1 -1
- package/dist/bundle/chunks/chunk-P7FPUEYA.js +2 -0
- package/dist/bundle/chunks/chunk-PWQUNMKT.js +4 -0
- package/dist/bundle/chunks/{chunk-3NEJV7UG.js → chunk-ULTM5Q67.js} +1 -1
- package/dist/bundle/chunks/{chunk-VHUVVKJM.js → chunk-WATJAG5U.js} +1 -1
- package/dist/bundle/chunks/{chunk-VYYRESZJ.js → chunk-YH5RGRHQ.js} +3 -3
- package/dist/bundle/chunks/{cli-QUNA6INU.js → cli-2Q4CKMZK.js} +11 -9
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-QIIM6OB4.js → cloudflare-workers-ai-system-one-JEJELFEJ.js} +1 -1
- package/dist/bundle/chunks/devin.js +1 -1
- package/dist/bundle/chunks/{easter-egg-3d-4L2AVJKX.js → easter-egg-3d-UEH5CVEM.js} +1 -1
- package/dist/bundle/chunks/{execute-UNST3ORJ.js → execute-BOGNP5CQ.js} +1 -1
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/google-antigravity-runtime.js +3 -3
- package/dist/bundle/chunks/google-antigravity.js +1 -1
- package/dist/bundle/chunks/{google-generative-ai-PNRT4EAN.js → google-generative-ai-UTHMOBSC.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-ZLSXUSEM.js → google-vertex-MKY2BEE7.js} +1 -1
- package/dist/bundle/chunks/image-resize-worker.js +1 -1
- package/dist/bundle/chunks/kimi-coding.js +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-U4EH6TAM.js → llama-cpp-classify-CYHVVBOQ.js} +1 -1
- package/dist/bundle/chunks/meta.js +1 -1
- package/dist/bundle/chunks/mistral-conversations-U2CRJEWX.js +5 -0
- package/dist/bundle/chunks/{openai-codex-responses-UIB63WGM.js → openai-codex-responses-DK2NKO47.js} +1 -1
- package/dist/bundle/chunks/openai-completions-VPNLDI5K.js +7 -0
- package/dist/bundle/chunks/{openai-decisions-Q46R33J3.js → openai-decisions-UZ6HF7LF.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-FGTD6NDJ.js → openai-responses-S5QT5K5D.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-WBAVKHHY.js → openrouter-images-P5CYCO4P.js} +1 -1
- package/dist/bundle/chunks/pi-messages-XPX326L5.js +8 -0
- package/dist/bundle/chunks/radius.js +1 -1
- package/dist/bundle/chunks/{runtime-SITSZTHV.js → runtime-2Z3FBQRD.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-DFEHTLK5.js → typesafe-system-one-NKVLMGFF.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-CR5DUKA3.js +2 -0
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +8 -7
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/auth-check.d.ts.map +1 -1
- package/dist/cli/auth-check.js +12 -1
- package/dist/cli/auth-check.js.map +1 -1
- package/dist/cli/credential-print.d.ts.map +1 -1
- package/dist/cli/credential-print.js +6 -0
- package/dist/cli/credential-print.js.map +1 -1
- package/dist/config.d.ts +10 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +24 -5
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-runtime.js +3 -3
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session.d.ts +6 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +35 -7
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/bug-report.d.ts +4 -4
- package/dist/core/compaction/branch-summarization.d.ts +4 -2
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +14 -5
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/exec.d.ts +9 -1
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +79 -15
- package/dist/core/exec.js.map +1 -1
- package/dist/core/export-html/template.css +9 -0
- package/dist/core/export-html/template.js +165 -45
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +3 -0
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +7 -6
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/pi-ai-extension-view.d.ts +19 -0
- package/dist/core/extensions/pi-ai-extension-view.d.ts.map +1 -0
- package/dist/core/extensions/pi-ai-extension-view.js +22 -0
- package/dist/core/extensions/pi-ai-extension-view.js.map +1 -0
- package/dist/core/extensions/types.d.ts +27 -4
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/virtual-modules.js +8 -7
- package/dist/core/extensions/virtual-modules.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +11 -4
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +15 -5
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-config.d.ts +1678 -2029
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +2 -3
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +5 -0
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +17 -11
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts +11 -14
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +167 -198
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/package-manager.d.ts +14 -0
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +160 -46
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/pi-ai-schemas.d.ts +163 -0
- package/dist/core/pi-ai-schemas.d.ts.map +1 -0
- package/dist/core/pi-ai-schemas.js +21 -0
- package/dist/core/pi-ai-schemas.js.map +1 -0
- package/dist/core/pi-manifest.d.ts +1 -0
- package/dist/core/pi-manifest.d.ts.map +1 -1
- package/dist/core/pi-manifest.js +4 -0
- package/dist/core/pi-manifest.js.map +1 -1
- package/dist/core/pi-server-accounts.d.ts +22 -0
- package/dist/core/pi-server-accounts.d.ts.map +1 -0
- package/dist/core/pi-server-accounts.js +137 -0
- package/dist/core/pi-server-accounts.js.map +1 -0
- package/dist/core/pi-server-client.d.ts +15 -7
- package/dist/core/pi-server-client.d.ts.map +1 -1
- package/dist/core/pi-server-client.js +85 -4
- package/dist/core/pi-server-client.js.map +1 -1
- package/dist/core/pi-server-observer.d.ts +4 -0
- package/dist/core/pi-server-observer.d.ts.map +1 -1
- package/dist/core/pi-server-observer.js +24 -0
- package/dist/core/pi-server-observer.js.map +1 -1
- package/dist/core/pi-server-request.d.ts +1 -1
- package/dist/core/pi-server-request.d.ts.map +1 -1
- package/dist/core/pi-server-request.js +2 -2
- package/dist/core/pi-server-request.js.map +1 -1
- package/dist/core/pi-server-subagents.d.ts +26 -0
- package/dist/core/pi-server-subagents.d.ts.map +1 -0
- package/dist/core/pi-server-subagents.js +112 -0
- package/dist/core/pi-server-subagents.js.map +1 -0
- package/dist/core/project-trust.js +1 -1
- package/dist/core/project-trust.js.map +1 -1
- package/dist/core/provider-composer.d.ts +1 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +1 -0
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts +3 -2
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +32 -16
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/resource-loader.d.ts +6 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +42 -24
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +61 -18
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts +7 -0
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +32 -13
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +2 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +11 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +4 -2
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +8 -1
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +6 -14
- package/dist/core/skills.js.map +1 -1
- package/dist/core/slash-commands.js +2 -2
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/source-info.d.ts +9 -0
- package/dist/core/source-info.d.ts.map +1 -1
- package/dist/core/source-info.js +13 -0
- package/dist/core/source-info.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +5 -6
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/bash.d.ts +2 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit.d.ts +3 -3
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +2 -4
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts +2 -2
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +2 -2
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +1 -1
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/ls.d.ts +2 -2
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/read.d.ts +2 -2
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/render-utils.js +2 -2
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/renderers/write.d.ts.map +1 -1
- package/dist/core/tools/renderers/write.js +19 -19
- package/dist/core/tools/renderers/write.js.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts +11 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/write.d.ts +2 -2
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +14 -8
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js +2 -0
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/extensions/codemode/renderer.d.ts.map +1 -1
- package/dist/extensions/codemode/renderer.js +6 -2
- package/dist/extensions/codemode/renderer.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +2 -1
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +33 -8
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/llama/ui.d.ts.map +1 -1
- package/dist/extensions/llama/ui.js +16 -4
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts.map +1 -1
- package/dist/extensions/mcp/cli.js +34 -8
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +1 -1
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +36 -13
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/ui.d.ts +1 -0
- package/dist/extensions/mcp/ui.d.ts.map +1 -1
- package/dist/extensions/mcp/ui.js +33 -24
- package/dist/extensions/mcp/ui.js.map +1 -1
- package/dist/extensions/tool-search/tool.d.ts +21 -6
- package/dist/extensions/tool-search/tool.d.ts.map +1 -1
- package/dist/extensions/tool-search/tool.js +104 -36
- package/dist/extensions/tool-search/tool.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +30 -7
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts +4 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +45 -21
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +4 -17
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js +7 -0
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-entry.js +2 -1
- package/dist/modes/interactive/components/custom-entry.js.map +1 -1
- package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-message.js +2 -1
- package/dist/modes/interactive/components/custom-message.js.map +1 -1
- package/dist/modes/interactive/components/extension-editor.d.ts +2 -0
- package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-editor.js +4 -0
- package/dist/modes/interactive/components/extension-editor.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +5 -0
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +105 -10
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/markdown-transform.d.ts +2 -1
- package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -1
- package/dist/modes/interactive/components/markdown-transform.js +3 -2
- package/dist/modes/interactive/components/markdown-transform.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +1 -0
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +17 -6
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +1 -0
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +13 -4
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -0
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +14 -3
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector-search.d.ts +4 -0
- package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-search.js +86 -22
- package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +2 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +16 -24
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.js +2 -0
- package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +6 -0
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +14 -2
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts +1 -0
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js +5 -6
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.d.ts +1 -0
- package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.js +9 -1
- package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message.d.ts +3 -1
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js +6 -2
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/external-editor.d.ts +1 -0
- package/dist/modes/interactive/external-editor.d.ts.map +1 -1
- package/dist/modes/interactive/external-editor.js +10 -4
- package/dist/modes/interactive/external-editor.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +5 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +179 -58
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/model-search.d.ts +10 -0
- package/dist/modes/interactive/model-search.d.ts.map +1 -1
- package/dist/modes/interactive/model-search.js +21 -0
- package/dist/modes/interactive/model-search.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts +10 -0
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +31 -23
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +55 -4
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/ansi.d.ts.map +1 -1
- package/dist/utils/ansi.js +5 -2
- package/dist/utils/ansi.js.map +1 -1
- package/dist/utils/clipboard-command.d.ts.map +1 -1
- package/dist/utils/clipboard-command.js +4 -0
- package/dist/utils/clipboard-command.js.map +1 -1
- package/dist/utils/git.d.ts +1 -1
- package/dist/utils/git.d.ts.map +1 -1
- package/dist/utils/git.js.map +1 -1
- package/dist/utils/image-resize-core.d.ts.map +1 -1
- package/dist/utils/image-resize-core.js +5 -3
- package/dist/utils/image-resize-core.js.map +1 -1
- package/dist/utils/open-browser.d.ts.map +1 -1
- package/dist/utils/open-browser.js +4 -1
- package/dist/utils/open-browser.js.map +1 -1
- package/dist/utils/paths.d.ts +17 -0
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +42 -1
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +14 -0
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts +5 -0
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +7 -0
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +30 -35
- package/dist/utils/tools-manager.js.map +1 -1
- package/docs/cli.md +21 -11
- package/docs/custom-provider.md +2 -0
- package/docs/environment-variables.md +2 -0
- package/docs/extensions.md +3173 -225
- package/docs/keybindings.md +1 -1
- package/docs/llama-cpp.md +23 -12
- package/docs/mcp.md +6 -4
- package/docs/message-types.md +1 -1
- package/docs/packages.md +24 -0
- package/docs/quickstart.md +7 -3
- package/docs/sessions.md +11 -3
- package/docs/settings.md +5 -4
- package/docs/slash-commands.md +3 -2
- package/docs/terminal-setup.md +3 -1
- package/docs/tmux.md +6 -0
- package/docs/tui.md +2 -0
- package/docs/windows.md +27 -0
- package/examples/extensions/README.md +2 -1
- package/examples/extensions/custom-provider-anthropic/index.ts +27 -31
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/debug-provider.ts +2 -2
- package/examples/extensions/gondolin/package-lock.json +19 -29
- package/examples/extensions/gondolin/package.json +2 -2
- package/examples/extensions/preset.ts +2 -0
- package/examples/extensions/reload-runtime.ts +17 -5
- package/examples/extensions/todo.ts +7 -0
- package/examples/extensions/tools.ts +2 -0
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/tsconfig.json +180 -0
- package/package.json +13 -14
- package/schemas/models.schema.json +36 -36
- package/schemas/settings.schema.json +17 -0
- package/dist/bundle/chunks/anthropic-messages-3TZAX2CL.js +0 -6
- package/dist/bundle/chunks/azure-openai-responses-5OV6AS44.js +0 -2
- package/dist/bundle/chunks/chunk-3V45WARH.js +0 -7
- package/dist/bundle/chunks/chunk-GA3MDGH3.js +0 -82
- package/dist/bundle/chunks/chunk-H2UJDH5M.js +0 -131
- package/dist/bundle/chunks/chunk-H76KZMOI.js +0 -2
- package/dist/bundle/chunks/chunk-K47GPRYD.js +0 -1577
- package/dist/bundle/chunks/chunk-PG7P2LUM.js +0 -4
- package/dist/bundle/chunks/chunk-TEPMHNKQ.js +0 -2
- package/dist/bundle/chunks/chunk-TLSZ4DWU.js +0 -16
- package/dist/bundle/chunks/chunk-WVXVPMMO.js +0 -2
- package/dist/bundle/chunks/mistral-conversations-OJFHLO4F.js +0 -5
- package/dist/bundle/chunks/openai-completions-T5JB7LUM.js +0 -7
- package/dist/bundle/chunks/pi-messages-S7RKCD5K.js +0 -8
- package/dist/bundle/chunks/virtual-modules-2WW4BVZM.js +0 -2
- package/examples/extensions/sandbox/index.ts +0 -321
- package/examples/extensions/sandbox/package-lock.json +0 -92
- package/examples/extensions/sandbox/package.json +0 -19
|
@@ -61,11 +61,11 @@ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Go
|
|
|
61
61
|
`+message)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message,headers){if(server.listenerCount("wsClientError")){let err=new Error(message);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError),server.emit("wsClientError",err,socket,req)}else abortHandshake(socket,code,message,headers)}}});var FifoQueue=class{incoming=[];outgoing=[];get length(){return this.incoming.length+this.outgoing.length}enqueue(value){this.incoming.push(value)}dequeue(){if(this.outgoing.length===0)for(;this.incoming.length>0;)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}},EventStream=class{queue=new FifoQueue;waiting=new FifoQueue;done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(isComplete,extractResult){this.isComplete=isComplete,this.extractResult=extractResult,this.finalResultPromise=new Promise(resolve=>{this.resolveFinalResult=resolve})}push(event){if(this.done)return;this.isComplete(event)&&(this.done=!0,this.resolveFinalResult(this.extractResult(event)));let waiter=this.waiting.dequeue();waiter?waiter({value:event,done:!1}):this.queue.enqueue(event)}end(result){for(this.done=!0,result!==void 0&&this.resolveFinalResult(result);this.waiting.length>0;)this.waiting.dequeue()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.dequeue();else{if(this.done)return;{let result=await new Promise(resolve=>this.waiting.enqueue(resolve));if(result.done)return;yield result.value}}}result(){return this.finalResultPromise}},AssistantMessageEventStream=class extends EventStream{#startedAt=Date.now();#startedAtMonotonic=performance.now();constructor(){super(event=>event.type==="done"||event.type==="error",event=>{if(event.type==="done")return event.message;if(event.type==="error")return event.error;throw new Error("Unexpected event type for final result")})}push(event){event.type==="done"?this.#time(event.message):event.type==="error"&&this.#time(event.error),super.push(event)}end(result){result!==void 0&&this.#time(result),super.end(result)}#time(message){this.done||message.durationMs!==void 0||message.timestamp<this.#startedAt||(message.durationMs=Math.max(0,Math.round(performance.now()-this.#startedAtMonotonic)))}};function contentText(content,separator=`
|
|
62
62
|
`){return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(separator)}function getSystemMessageText(message){let parts=[contentText(message.content)];for(let text of Object.values(message.sections??{}))text!==null&&parts.push(text);return parts.filter(part=>part.length>0).join(`
|
|
63
63
|
|
|
64
|
-
`)}function isSystemMessage(message){return message.role==="system"}function getInitialSystemMessage(messages){let first=messages[0];return first&&isSystemMessage(first)?first:void 0}function withoutInitialSystemMessage(messages){return getInitialSystemMessage(messages)?messages.slice(1):messages}function getCurrentTools(messages){let tools=new Map;for(let message of messages)if(isSystemMessage(message)){for(let tool of message.toolsRemoved??[])tools.delete(tool.name);for(let tool of message.toolsAdded??[])tools.set(tool.name,tool)}return[...tools.values()]}function getCurrentSystemMessage(messages){let content=[],sections=new Map,timestamp;for(let message of messages){if(!isSystemMessage(message))continue;timestamp??=message.timestamp;let text=contentText(message.content);text.length>0&&content.push(text);for(let[name,value]of Object.entries(message.sections??{}))value===null?sections.delete(name):sections.set(name,value)}let tools=getCurrentTools(messages);if(!(timestamp===void 0&&tools.length===0))return{role:"system",content:content.join(`
|
|
64
|
+
`)}function ownedSlice(text,start,end=text.length){return`${text.slice(start,end)} `.slice(0,-1)}function isSystemMessage(message){return message.role==="system"}function getInitialSystemMessage(messages){let first=messages[0];return first&&isSystemMessage(first)?first:void 0}function withoutInitialSystemMessage(messages){return getInitialSystemMessage(messages)?messages.slice(1):messages}function getCurrentTools(messages){let tools=new Map;for(let message of messages)if(isSystemMessage(message)){for(let tool of message.toolsRemoved??[])tools.delete(tool.name);for(let tool of message.toolsAdded??[])tools.set(tool.name,tool)}return[...tools.values()]}function getCurrentSystemMessage(messages){let content=[],sections=new Map,timestamp;for(let message of messages){if(!isSystemMessage(message))continue;timestamp??=message.timestamp;let text=contentText(message.content);text.length>0&&content.push(text);for(let[name,value]of Object.entries(message.sections??{}))value===null?sections.delete(name):sections.set(name,value)}let tools=getCurrentTools(messages);if(!(timestamp===void 0&&tools.length===0))return{role:"system",content:content.join(`
|
|
65
65
|
|
|
66
|
-
`),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function getCurrentSystemPrompt(messages){let message=getCurrentSystemMessage(messages);return message?getSystemMessageText(message):""}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}function calculateCost(model,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model.cost,matchedThreshold=-1;for(let tier of model.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model){return model.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==void 0:!0}):["off"]}function clampThinkingLevel(model,level){let availableLevels=getSupportedThinkingLevels(model);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i2=requestedIndex;i2<EXTENDED_THINKING_LEVELS.length;i2++){let candidate=EXTENDED_THINKING_LEVELS[i2];if(availableLevels.includes(candidate))return candidate}for(let i2=requestedIndex-1;i2>=0;i2--){let candidate=EXTENDED_THINKING_LEVELS[i2];if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}function normalizeProviderError(error){if(!(error instanceof Error))return{message:safeJsonStringify(error),messageCarriesBody:!1};let sdkError=error,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error.message.includes(body);return{status,body,message:error.message,messageCarriesBody}}function extractStatus(error){if(typeof error.statusCode=="number")return error.statusCode;if(typeof error.status=="number")return error.status;if(typeof error.$metadata?.httpStatusCode=="number")return error.$metadata.httpStatusCode;if(typeof error.$response?.statusCode=="number")return error.$response.statusCode}function extractBody(error){let bodyText=pickBodyText(error);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,4e3)}function pickBodyText(error){if(typeof error.body=="string")return error.body;if(isPlainNonEmptyObject(error.error))return safeJsonStringify(error.error);let responseBody=error.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function formatProviderError(norm,prefix){return norm.messageCarriesBody||norm.status===void 0||norm.body===void 0?prefix!==void 0&&norm.status!==void 0?`${prefix} (${norm.status}): ${norm.message}`:norm.message:prefix!==void 0?`${prefix} (${norm.status}): ${norm.body}`:`${norm.status}: ${norm.body}`}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}function headersToRecord(headers){let result={};for(let[key,value]of headers.entries())result[key]=value;return result}function providerHeadersToRecord(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}return merged.size>0?Object.fromEntries(merged.values()):void 0}function isProviderError(error){return!(error instanceof Error)||!("status"in error)||!("headers"in error)?!1:(error.status===void 0||typeof error.status=="number")&&(error.headers===void 0||error.headers instanceof Headers)}function isRetryableProviderError(error){let shouldRetry=error.headers?.get("x-should-retry");return shouldRetry==="true"?!0:shouldRetry==="false"?!1:error.status===void 0?!0:error.status===408||error.status===409||error.status===429||typeof error.status=="number"&&error.status>=500}function validateServerRetryDelayMs(delayMs,maxRetryDelayMs,providerErrorMessage){let maxDelayMs=maxRetryDelayMs??6e4;if(maxDelayMs>0&&delayMs>maxDelayMs)throw new Error(`Server requested ${Math.ceil(delayMs/1e3)}s retry delay (max: ${Math.ceil(maxDelayMs/1e3)}s). ${providerErrorMessage}`);return delayMs}function getRetryDelayMs(error,retryIndex,maxRetryDelayMs){let retryAfterMs=error.headers?.get("retry-after-ms");if(retryAfterMs){let value=Number.parseFloat(retryAfterMs);if(Number.isFinite(value))return validateServerRetryDelayMs(value,maxRetryDelayMs,error.message)}let retryAfter=error.headers?.get("retry-after");if(retryAfter){let seconds=Number.parseFloat(retryAfter),delayMs=Number.isNaN(seconds)?Date.parse(retryAfter)-Date.now():seconds*1e3;if(Number.isFinite(delayMs))return validateServerRetryDelayMs(delayMs,maxRetryDelayMs,error.message)}return Math.min(.5*2**retryIndex,8)*1e3*(1-Math.random()*.25)}function createAbortError(){let error=new Error("Request aborted");return error.name="AbortError",error}function abortableSleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(createAbortError());return}let onAbort=()=>{clearTimeout(timeout),reject(createAbortError())},timeout=setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},Math.max(0,ms));signal?.addEventListener("abort",onAbort,{once:!0})})}async function retryProviderRequest(request,options={}){let maxRetries=options.maxRetries??0,retriesRemaining=maxRetries;for(;;)try{return await request()}catch(error){if(options.signal?.aborted)throw createAbortError();if(retriesRemaining<=0||!isProviderError(error)||!isRetryableProviderError(error)||error.status!==void 0&&options.noRetryStatuses?.includes(error.status))throw error;let retryIndex=maxRetries-retriesRemaining;retriesRemaining--,await abortableSleep(getRetryDelayMs(error,retryIndex,options.maxRetryDelayMs),options.signal)}}function sanitizeSurrogates(text){return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}var import_p_retry=__toESM(require_p_retry(),1),import_google_auth_library=__toESM(require_src5(),1);var import_stream=__toESM(require_stream(),1),import_extension=__toESM(require_extension(),1),import_permessage_deflate=__toESM(require_permessage_deflate(),1),import_receiver=__toESM(require_receiver(),1),import_sender=__toESM(require_sender(),1),import_subprotocol=__toESM(require_subprotocol(),1),import_websocket=__toESM(require_websocket(),1),import_websocket_server=__toESM(require_websocket_server(),1);var BaseModule=class{};function formatMap(templateString,valueMap){let regex=/\{([^}]+)\}/g;return templateString.replace(regex,(match,key)=>{if(Object.prototype.hasOwnProperty.call(valueMap,key)){let value=valueMap[key];return value!=null?String(value):""}else throw new Error(`Key '${key}' not found in valueMap.`)})}function setValueByPath(data,keys,value){for(let i2=0;i2<keys.length-1;i2++){let key=keys[i2];if(key.endsWith("[]")){let keyName=key.slice(0,-2);if(!(keyName in data))if(Array.isArray(value))data[keyName]=Array.from({length:value.length},()=>({}));else throw new Error(`Value must be a list given an array path ${key}`);if(Array.isArray(data[keyName])){let arrayData=data[keyName];if(Array.isArray(value))for(let j=0;j<arrayData.length;j++){let entry=arrayData[j];setValueByPath(entry,keys.slice(i2+1),value[j])}else for(let d of arrayData)setValueByPath(d,keys.slice(i2+1),value)}return}else if(key.endsWith("[0]")){let keyName=key.slice(0,-3);keyName in data||(data[keyName]=[{}]);let arrayData=data[keyName];setValueByPath(arrayData[0],keys.slice(i2+1),value);return}(!data[key]||typeof data[key]!="object")&&(data[key]={}),data=data[key]}let keyToSet=keys[keys.length-1],existingData=data[keyToSet];if(existingData!==void 0){if(!value||typeof value=="object"&&Object.keys(value).length===0||value===existingData)return;if(typeof existingData=="object"&&typeof value=="object"&&existingData!==null&&value!==null)Object.assign(existingData,value);else throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`)}else keyToSet==="_self"&&typeof value=="object"&&value!==null&&!Array.isArray(value)?Object.assign(data,value):data[keyToSet]=value}function getValueByPath(data,keys,defaultValue=void 0){try{if(keys.length===1&&keys[0]==="_self")return data;for(let i2=0;i2<keys.length;i2++){if(typeof data!="object"||data===null)return defaultValue;let key=keys[i2];if(key.endsWith("[]")){let keyName=key.slice(0,-2);if(keyName in data){let arrayData=data[keyName];return Array.isArray(arrayData)?arrayData.map(d=>getValueByPath(d,keys.slice(i2+1),defaultValue)):defaultValue}else return defaultValue}else data=data[key]}return data}catch(error){if(error instanceof TypeError)return defaultValue;throw error}}function tBytes$1(fromBytes){if(typeof fromBytes!="string")throw new Error("fromImageBytes must be a string");return fromBytes}function generateVideosOperationFromMldev$1(fromObject){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);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response","generateVideoResponse"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromMldev$1(fromResponse)),toObject}function generateVideosOperationFromVertex$1(fromObject){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);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromVertex$1(fromResponse)),toObject}function generateVideosResponseFromMldev$1(fromObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["generatedSamples"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromMldev$1(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(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosResponseFromVertex$1(fromObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["videos"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromVertex$1(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(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generatedVideoFromMldev$1(fromObject){let toObject={},fromVideo=getValueByPath(fromObject,["video"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromMldev$1(fromVideo)),toObject}function generatedVideoFromVertex$1(fromObject){let toObject={},fromVideo=getValueByPath(fromObject,["_self"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromVertex$1(fromVideo)),toObject}function videoFromMldev$1(fromObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["encodedVideo"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes$1(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["encoding"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoFromVertex$1(fromObject){let toObject={},fromUri=getValueByPath(fromObject,["gcsUri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes$1(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}var Outcome;(function(Outcome2){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",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="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_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",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.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="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||(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"})(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_PEOPLE"})(ProminentPeople||(ProminentPeople={}));var HarmCategory;(function(HarmCategory2){HarmCategory2.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",HarmCategory2.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",HarmCategory2.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",HarmCategory2.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",HarmCategory2.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",HarmCategory2.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",HarmCategory2.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",HarmCategory2.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",HarmCategory2.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",HarmCategory2.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",HarmCategory2.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"})(HarmCategory||(HarmCategory={}));var HarmBlockMethod;(function(HarmBlockMethod2){HarmBlockMethod2.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",HarmBlockMethod2.SEVERITY="SEVERITY",HarmBlockMethod2.PROBABILITY="PROBABILITY"})(HarmBlockMethod||(HarmBlockMethod={}));var HarmBlockThreshold;(function(HarmBlockThreshold2){HarmBlockThreshold2.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",HarmBlockThreshold2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",HarmBlockThreshold2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",HarmBlockThreshold2.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",HarmBlockThreshold2.BLOCK_NONE="BLOCK_NONE",HarmBlockThreshold2.OFF="OFF"})(HarmBlockThreshold||(HarmBlockThreshold={}));var FunctionCallingConfigMode;(function(FunctionCallingConfigMode2){FunctionCallingConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",FunctionCallingConfigMode2.AUTO="AUTO",FunctionCallingConfigMode2.ANY="ANY",FunctionCallingConfigMode2.NONE="NONE",FunctionCallingConfigMode2.VALIDATED="VALIDATED"})(FunctionCallingConfigMode||(FunctionCallingConfigMode={}));var FinishReason;(function(FinishReason2){FinishReason2.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",FinishReason2.STOP="STOP",FinishReason2.MAX_TOKENS="MAX_TOKENS",FinishReason2.SAFETY="SAFETY",FinishReason2.RECITATION="RECITATION",FinishReason2.LANGUAGE="LANGUAGE",FinishReason2.OTHER="OTHER",FinishReason2.BLOCKLIST="BLOCKLIST",FinishReason2.PROHIBITED_CONTENT="PROHIBITED_CONTENT",FinishReason2.SPII="SPII",FinishReason2.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",FinishReason2.IMAGE_SAFETY="IMAGE_SAFETY",FinishReason2.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",FinishReason2.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",FinishReason2.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",FinishReason2.NO_IMAGE="NO_IMAGE",FinishReason2.IMAGE_RECITATION="IMAGE_RECITATION",FinishReason2.IMAGE_OTHER="IMAGE_OTHER"})(FinishReason||(FinishReason={}));var HarmProbability;(function(HarmProbability2){HarmProbability2.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",HarmProbability2.NEGLIGIBLE="NEGLIGIBLE",HarmProbability2.LOW="LOW",HarmProbability2.MEDIUM="MEDIUM",HarmProbability2.HIGH="HIGH"})(HarmProbability||(HarmProbability={}));var HarmSeverity;(function(HarmSeverity2){HarmSeverity2.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",HarmSeverity2.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",HarmSeverity2.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",HarmSeverity2.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",HarmSeverity2.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(HarmSeverity||(HarmSeverity={}));var UrlRetrievalStatus;(function(UrlRetrievalStatus2){UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(UrlRetrievalStatus||(UrlRetrievalStatus={}));var BlockedReason;(function(BlockedReason2){BlockedReason2.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",BlockedReason2.SAFETY="SAFETY",BlockedReason2.OTHER="OTHER",BlockedReason2.BLOCKLIST="BLOCKLIST",BlockedReason2.PROHIBITED_CONTENT="PROHIBITED_CONTENT",BlockedReason2.IMAGE_SAFETY="IMAGE_SAFETY",BlockedReason2.MODEL_ARMOR="MODEL_ARMOR",BlockedReason2.JAILBREAK="JAILBREAK"})(BlockedReason||(BlockedReason={}));var TrafficType;(function(TrafficType2){TrafficType2.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",TrafficType2.ON_DEMAND="ON_DEMAND",TrafficType2.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",TrafficType2.ON_DEMAND_FLEX="ON_DEMAND_FLEX",TrafficType2.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(TrafficType||(TrafficType={}));var MediaModality;(function(MediaModality2){MediaModality2.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",MediaModality2.TEXT="TEXT",MediaModality2.IMAGE="IMAGE",MediaModality2.VIDEO="VIDEO",MediaModality2.AUDIO="AUDIO",MediaModality2.DOCUMENT="DOCUMENT"})(MediaModality||(MediaModality={}));var ModelStage;(function(ModelStage2){ModelStage2.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",ModelStage2.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",ModelStage2.EXPERIMENTAL="EXPERIMENTAL",ModelStage2.PREVIEW="PREVIEW",ModelStage2.STABLE="STABLE",ModelStage2.LEGACY="LEGACY",ModelStage2.DEPRECATED="DEPRECATED",ModelStage2.RETIRED="RETIRED"})(ModelStage||(ModelStage={}));var MediaResolution;(function(MediaResolution2){MediaResolution2.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",MediaResolution2.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",MediaResolution2.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",MediaResolution2.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(MediaResolution||(MediaResolution={}));var Modality;(function(Modality2){Modality2.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",Modality2.TEXT="TEXT",Modality2.IMAGE="IMAGE",Modality2.AUDIO="AUDIO",Modality2.VIDEO="VIDEO"})(Modality||(Modality={}));var Delivery;(function(Delivery2){Delivery2.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",Delivery2.INLINE="INLINE",Delivery2.URI="URI"})(Delivery||(Delivery={}));var AspectRatio;(function(AspectRatio2){AspectRatio2.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",AspectRatio2.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",AspectRatio2.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",AspectRatio2.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",AspectRatio2.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",AspectRatio2.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",AspectRatio2.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",AspectRatio2.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",AspectRatio2.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",AspectRatio2.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",AspectRatio2.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",AspectRatio2.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",AspectRatio2.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",AspectRatio2.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",AspectRatio2.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"})(AspectRatio||(AspectRatio={}));var ImageSize;(function(ImageSize2){ImageSize2.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",ImageSize2.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",ImageSize2.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",ImageSize2.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",ImageSize2.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"})(ImageSize||(ImageSize={}));var TuningMode;(function(TuningMode2){TuningMode2.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",TuningMode2.TUNING_MODE_FULL="TUNING_MODE_FULL",TuningMode2.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(TuningMode||(TuningMode={}));var AdapterSize;(function(AdapterSize2){AdapterSize2.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",AdapterSize2.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",AdapterSize2.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",AdapterSize2.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",AdapterSize2.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",AdapterSize2.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",AdapterSize2.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(AdapterSize||(AdapterSize={}));var ResponseParseType;(function(ResponseParseType2){ResponseParseType2.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",ResponseParseType2.IDENTITY="IDENTITY",ResponseParseType2.REGEX_EXTRACT="REGEX_EXTRACT"})(ResponseParseType||(ResponseParseType={}));var MatchOperation;(function(MatchOperation2){MatchOperation2.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",MatchOperation2.REGEX_CONTAINS="REGEX_CONTAINS",MatchOperation2.PARTIAL_MATCH="PARTIAL_MATCH",MatchOperation2.EXACT_MATCH="EXACT_MATCH"})(MatchOperation||(MatchOperation={}));var ReinforcementTuningThinkingLevel;(function(ReinforcementTuningThinkingLevel2){ReinforcementTuningThinkingLevel2.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",ReinforcementTuningThinkingLevel2.MINIMAL="MINIMAL",ReinforcementTuningThinkingLevel2.HIGH="HIGH"})(ReinforcementTuningThinkingLevel||(ReinforcementTuningThinkingLevel={}));var JobState;(function(JobState2){JobState2.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",JobState2.JOB_STATE_QUEUED="JOB_STATE_QUEUED",JobState2.JOB_STATE_PENDING="JOB_STATE_PENDING",JobState2.JOB_STATE_RUNNING="JOB_STATE_RUNNING",JobState2.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",JobState2.JOB_STATE_FAILED="JOB_STATE_FAILED",JobState2.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",JobState2.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",JobState2.JOB_STATE_PAUSED="JOB_STATE_PAUSED",JobState2.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",JobState2.JOB_STATE_UPDATING="JOB_STATE_UPDATING",JobState2.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(JobState||(JobState={}));var TuningJobState;(function(TuningJobState2){TuningJobState2.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",TuningJobState2.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",TuningJobState2.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",TuningJobState2.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",TuningJobState2.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",TuningJobState2.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(TuningJobState||(TuningJobState={}));var AggregationMetric;(function(AggregationMetric2){AggregationMetric2.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",AggregationMetric2.AVERAGE="AVERAGE",AggregationMetric2.MODE="MODE",AggregationMetric2.STANDARD_DEVIATION="STANDARD_DEVIATION",AggregationMetric2.VARIANCE="VARIANCE",AggregationMetric2.MINIMUM="MINIMUM",AggregationMetric2.MAXIMUM="MAXIMUM",AggregationMetric2.MEDIAN="MEDIAN",AggregationMetric2.PERCENTILE_P90="PERCENTILE_P90",AggregationMetric2.PERCENTILE_P95="PERCENTILE_P95",AggregationMetric2.PERCENTILE_P99="PERCENTILE_P99"})(AggregationMetric||(AggregationMetric={}));var PairwiseChoice;(function(PairwiseChoice2){PairwiseChoice2.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",PairwiseChoice2.BASELINE="BASELINE",PairwiseChoice2.CANDIDATE="CANDIDATE",PairwiseChoice2.TIE="TIE"})(PairwiseChoice||(PairwiseChoice={}));var VideoOrientation;(function(VideoOrientation2){VideoOrientation2.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",VideoOrientation2.LANDSCAPE="LANDSCAPE",VideoOrientation2.PORTRAIT="PORTRAIT"})(VideoOrientation||(VideoOrientation={}));var TuningSpeed;(function(TuningSpeed2){TuningSpeed2.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",TuningSpeed2.REGULAR="REGULAR",TuningSpeed2.FAST="FAST"})(TuningSpeed||(TuningSpeed={}));var TuningTask;(function(TuningTask2){TuningTask2.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",TuningTask2.TUNING_TASK_I2V="TUNING_TASK_I2V",TuningTask2.TUNING_TASK_T2V="TUNING_TASK_T2V",TuningTask2.TUNING_TASK_R2V="TUNING_TASK_R2V"})(TuningTask||(TuningTask={}));var DocumentState;(function(DocumentState2){DocumentState2.STATE_UNSPECIFIED="STATE_UNSPECIFIED",DocumentState2.STATE_PENDING="STATE_PENDING",DocumentState2.STATE_ACTIVE="STATE_ACTIVE",DocumentState2.STATE_FAILED="STATE_FAILED"})(DocumentState||(DocumentState={}));var ServiceTier;(function(ServiceTier2){ServiceTier2.UNSPECIFIED="unspecified",ServiceTier2.FLEX="flex",ServiceTier2.STANDARD="standard",ServiceTier2.PRIORITY="priority"})(ServiceTier||(ServiceTier={}));var MediaProcessing;(function(MediaProcessing2){MediaProcessing2.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",MediaProcessing2.STATIC="STATIC",MediaProcessing2.AGENTIC="AGENTIC"})(MediaProcessing||(MediaProcessing={}));var PartMediaResolutionLevel;(function(PartMediaResolutionLevel2){PartMediaResolutionLevel2.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",PartMediaResolutionLevel2.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",PartMediaResolutionLevel2.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",PartMediaResolutionLevel2.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",PartMediaResolutionLevel2.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(PartMediaResolutionLevel||(PartMediaResolutionLevel={}));var ToolType;(function(ToolType2){ToolType2.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",ToolType2.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",ToolType2.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",ToolType2.URL_CONTEXT="URL_CONTEXT",ToolType2.GOOGLE_MAPS="GOOGLE_MAPS",ToolType2.FILE_SEARCH="FILE_SEARCH",ToolType2.MEDIA_PROCESSING="MEDIA_PROCESSING"})(ToolType||(ToolType={}));var ResourceScope;(function(ResourceScope2){ResourceScope2.COLLECTION="COLLECTION"})(ResourceScope||(ResourceScope={}));var FeatureSelectionPreference;(function(FeatureSelectionPreference2){FeatureSelectionPreference2.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",FeatureSelectionPreference2.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",FeatureSelectionPreference2.BALANCED="BALANCED",FeatureSelectionPreference2.PRIORITIZE_COST="PRIORITIZE_COST"})(FeatureSelectionPreference||(FeatureSelectionPreference={}));var EmbeddingApiType;(function(EmbeddingApiType2){EmbeddingApiType2.PREDICT="PREDICT",EmbeddingApiType2.EMBED_CONTENT="EMBED_CONTENT"})(EmbeddingApiType||(EmbeddingApiType={}));var SafetyFilterLevel;(function(SafetyFilterLevel2){SafetyFilterLevel2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",SafetyFilterLevel2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",SafetyFilterLevel2.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",SafetyFilterLevel2.BLOCK_NONE="BLOCK_NONE"})(SafetyFilterLevel||(SafetyFilterLevel={}));var ImagePromptLanguage;(function(ImagePromptLanguage2){ImagePromptLanguage2.auto="auto",ImagePromptLanguage2.en="en",ImagePromptLanguage2.ja="ja",ImagePromptLanguage2.ko="ko",ImagePromptLanguage2.hi="hi",ImagePromptLanguage2.zh="zh",ImagePromptLanguage2.pt="pt",ImagePromptLanguage2.es="es"})(ImagePromptLanguage||(ImagePromptLanguage={}));var MaskReferenceMode;(function(MaskReferenceMode2){MaskReferenceMode2.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",MaskReferenceMode2.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",MaskReferenceMode2.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",MaskReferenceMode2.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",MaskReferenceMode2.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(MaskReferenceMode||(MaskReferenceMode={}));var ControlReferenceType;(function(ControlReferenceType2){ControlReferenceType2.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",ControlReferenceType2.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",ControlReferenceType2.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",ControlReferenceType2.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(ControlReferenceType||(ControlReferenceType={}));var SubjectReferenceType;(function(SubjectReferenceType2){SubjectReferenceType2.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",SubjectReferenceType2.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",SubjectReferenceType2.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",SubjectReferenceType2.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(SubjectReferenceType||(SubjectReferenceType={}));var EditMode;(function(EditMode2){EditMode2.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",EditMode2.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",EditMode2.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",EditMode2.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",EditMode2.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",EditMode2.EDIT_MODE_STYLE="EDIT_MODE_STYLE",EditMode2.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",EditMode2.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(EditMode||(EditMode={}));var SegmentMode;(function(SegmentMode2){SegmentMode2.FOREGROUND="FOREGROUND",SegmentMode2.BACKGROUND="BACKGROUND",SegmentMode2.PROMPT="PROMPT",SegmentMode2.SEMANTIC="SEMANTIC",SegmentMode2.INTERACTIVE="INTERACTIVE"})(SegmentMode||(SegmentMode={}));var VideoGenerationReferenceType;(function(VideoGenerationReferenceType2){VideoGenerationReferenceType2.ASSET="ASSET",VideoGenerationReferenceType2.STYLE="STYLE"})(VideoGenerationReferenceType||(VideoGenerationReferenceType={}));var VideoGenerationMaskMode;(function(VideoGenerationMaskMode2){VideoGenerationMaskMode2.INSERT="INSERT",VideoGenerationMaskMode2.REMOVE="REMOVE",VideoGenerationMaskMode2.REMOVE_STATIC="REMOVE_STATIC",VideoGenerationMaskMode2.OUTPAINT="OUTPAINT"})(VideoGenerationMaskMode||(VideoGenerationMaskMode={}));var VideoCompressionQuality;(function(VideoCompressionQuality2){VideoCompressionQuality2.OPTIMIZED="OPTIMIZED",VideoCompressionQuality2.LOSSLESS="LOSSLESS"})(VideoCompressionQuality||(VideoCompressionQuality={}));var ImageResizeMode;(function(ImageResizeMode2){ImageResizeMode2.CROP="CROP",ImageResizeMode2.PAD="PAD"})(ImageResizeMode||(ImageResizeMode={}));var TuningMethod;(function(TuningMethod2){TuningMethod2.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",TuningMethod2.PREFERENCE_TUNING="PREFERENCE_TUNING",TuningMethod2.DISTILLATION="DISTILLATION",TuningMethod2.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(TuningMethod||(TuningMethod={}));var FileState;(function(FileState2){FileState2.STATE_UNSPECIFIED="STATE_UNSPECIFIED",FileState2.PROCESSING="PROCESSING",FileState2.ACTIVE="ACTIVE",FileState2.FAILED="FAILED"})(FileState||(FileState={}));var FileSource;(function(FileSource2){FileSource2.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",FileSource2.UPLOADED="UPLOADED",FileSource2.GENERATED="GENERATED",FileSource2.REGISTERED="REGISTERED"})(FileSource||(FileSource={}));var TurnCompleteReason;(function(TurnCompleteReason2){TurnCompleteReason2.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",TurnCompleteReason2.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",TurnCompleteReason2.RESPONSE_REJECTED="RESPONSE_REJECTED",TurnCompleteReason2.NEED_MORE_INPUT="NEED_MORE_INPUT",TurnCompleteReason2.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",TurnCompleteReason2.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",TurnCompleteReason2.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",TurnCompleteReason2.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",TurnCompleteReason2.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",TurnCompleteReason2.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",TurnCompleteReason2.INPUT_OTHER="INPUT_OTHER",TurnCompleteReason2.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",TurnCompleteReason2.BLOCKLIST="BLOCKLIST",TurnCompleteReason2.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",TurnCompleteReason2.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",TurnCompleteReason2.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",TurnCompleteReason2.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",TurnCompleteReason2.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",TurnCompleteReason2.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",TurnCompleteReason2.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",TurnCompleteReason2.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",TurnCompleteReason2.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",TurnCompleteReason2.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",TurnCompleteReason2.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",TurnCompleteReason2.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",TurnCompleteReason2.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",TurnCompleteReason2.GENERATED_OTHER="GENERATED_OTHER",TurnCompleteReason2.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(TurnCompleteReason||(TurnCompleteReason={}));var InteractionStatus;(function(InteractionStatus2){InteractionStatus2.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",InteractionStatus2.IN_PROGRESS="IN_PROGRESS",InteractionStatus2.REQUIRES_ACTION="REQUIRES_ACTION",InteractionStatus2.IDLE="IDLE"})(InteractionStatus||(InteractionStatus={}));var VadSignalType;(function(VadSignalType2){VadSignalType2.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",VadSignalType2.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",VadSignalType2.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(VadSignalType||(VadSignalType={}));var VoiceActivityType;(function(VoiceActivityType2){VoiceActivityType2.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",VoiceActivityType2.ACTIVITY_START="ACTIVITY_START",VoiceActivityType2.ACTIVITY_END="ACTIVITY_END"})(VoiceActivityType||(VoiceActivityType={}));var StartSensitivity;(function(StartSensitivity2){StartSensitivity2.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",StartSensitivity2.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",StartSensitivity2.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(StartSensitivity||(StartSensitivity={}));var EndSensitivity;(function(EndSensitivity2){EndSensitivity2.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",EndSensitivity2.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",EndSensitivity2.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(EndSensitivity||(EndSensitivity={}));var ActivityHandling;(function(ActivityHandling2){ActivityHandling2.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",ActivityHandling2.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",ActivityHandling2.NO_INTERRUPTION="NO_INTERRUPTION"})(ActivityHandling||(ActivityHandling={}));var TurnCoverage;(function(TurnCoverage2){TurnCoverage2.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",TurnCoverage2.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 AudioTranscriptionConfigMode;(function(AudioTranscriptionConfigMode2){AudioTranscriptionConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",AudioTranscriptionConfigMode2.VERBATIM="VERBATIM",AudioTranscriptionConfigMode2.SMART="SMART"})(AudioTranscriptionConfigMode||(AudioTranscriptionConfigMode={}));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="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.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.STOP="STOP",LiveMusicPlaybackControl2.RESET_CONTEXT="RESET_CONTEXT"})(LiveMusicPlaybackControl||(LiveMusicPlaybackControl={}));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)===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(`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 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+=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:_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(){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)===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?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!==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}};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("invalid 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 tPart(origin){if(origin==null)throw new Error("PartUnion is required");if(typeof origin=="object")return origin;if(typeof origin=="string")return{text:origin};throw new Error(`Unsupported part type: ${typeof origin}`)}function tParts(origin){if(origin==null||Array.isArray(origin)&&origin.length===0)throw new Error("PartListUnion is required");return Array.isArray(origin)?origin.map(item=>tPart(item)):[tPart(origin)]}function _isContent(origin){return origin!=null&&typeof origin=="object"&&"parts"in origin&&Array.isArray(origin.parts)}function _isFunctionCallPart(origin){return origin!=null&&typeof origin=="object"&&"functionCall"in origin}function _isFunctionResponsePart(origin){return origin!=null&&typeof origin=="object"&&"functionResponse"in origin}function tContent(origin){if(origin==null)throw new Error("ContentUnion is required");return _isContent(origin)?origin:{role:"user",parts:tParts(origin)}}function tContentsForEmbed(apiClient,origin){if(!origin)return[];if(apiClient.isVertexAI()&&Array.isArray(origin))return origin.flatMap(item=>{let content=tContent(item);return content.parts&&content.parts.length>0&&content.parts[0].text!==void 0?[content.parts[0].text]:[]});if(apiClient.isVertexAI()){let content=tContent(origin);return content.parts&&content.parts.length>0&&content.parts[0].text!==void 0?[content.parts[0].text]:[]}return Array.isArray(origin)?origin.map(item=>tContent(item)):[tContent(origin)]}function tContents(origin){if(origin==null||Array.isArray(origin)&&origin.length===0)throw new Error("contents are required");if(!Array.isArray(origin)){if(_isFunctionCallPart(origin)||_isFunctionResponsePart(origin))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[tContent(origin)]}let result=[],accumulatedParts=[],isContentArray=_isContent(origin[0]);for(let item of origin){let isContent=_isContent(item);if(isContent!=isContentArray)throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(isContent)result.push(item);else{if(_isFunctionCallPart(item)||_isFunctionResponsePart(item))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");accumulatedParts.push(item)}}return isContentArray||result.push({role:"user",parts:tParts(accumulatedParts)}),result}function flattenTypeArrayToAnyOf(typeList,resultingSchema){typeList.includes("null")&&(resultingSchema.nullable=!0);let listWithoutNull=typeList.filter(type=>type!=="null");if(listWithoutNull.length===1)resultingSchema.type=Object.values(Type).includes(listWithoutNull[0].toUpperCase())?listWithoutNull[0].toUpperCase():Type.TYPE_UNSPECIFIED;else{resultingSchema.anyOf=[];for(let i2 of listWithoutNull)resultingSchema.anyOf.push({type:Object.values(Type).includes(i2.toUpperCase())?i2.toUpperCase():Type.TYPE_UNSPECIFIED})}}function processJsonSchema(_jsonSchema){let genAISchema={},schemaFieldNames=["items"],listSchemaFieldNames=["anyOf"],dictSchemaFieldNames=["properties"];if(_jsonSchema.type&&_jsonSchema.anyOf)throw new Error("type and anyOf cannot be both populated.");let incomingAnyOf=_jsonSchema.anyOf;incomingAnyOf!=null&&incomingAnyOf.length==2&&(incomingAnyOf[0].type==="null"?(genAISchema.nullable=!0,_jsonSchema=incomingAnyOf[1]):incomingAnyOf[1].type==="null"&&(genAISchema.nullable=!0,_jsonSchema=incomingAnyOf[0])),_jsonSchema.type instanceof Array&&flattenTypeArrayToAnyOf(_jsonSchema.type,genAISchema);for(let[fieldName,fieldValue]of Object.entries(_jsonSchema))if(fieldValue!=null)if(fieldName=="type"){if(fieldValue==="null")throw new Error("type: null can not be the only possible type for the field.");if(fieldValue instanceof Array)continue;genAISchema.type=Object.values(Type).includes(fieldValue.toUpperCase())?fieldValue.toUpperCase():Type.TYPE_UNSPECIFIED}else if(schemaFieldNames.includes(fieldName))genAISchema[fieldName]=processJsonSchema(fieldValue);else if(listSchemaFieldNames.includes(fieldName)){let listSchemaFieldValue=[];for(let item of fieldValue){if(item.type=="null"){genAISchema.nullable=!0;continue}listSchemaFieldValue.push(processJsonSchema(item))}genAISchema[fieldName]=listSchemaFieldValue}else if(dictSchemaFieldNames.includes(fieldName)){let dictSchemaFieldValue={};for(let[key,value]of Object.entries(fieldValue))dictSchemaFieldValue[key]=processJsonSchema(value);genAISchema[fieldName]=dictSchemaFieldValue}else{if(fieldName==="additionalProperties")continue;genAISchema[fieldName]=fieldValue}return genAISchema}function tSchema(schema){return processJsonSchema(schema)}function tSpeechConfig(speechConfig){if(typeof speechConfig=="object")return speechConfig;if(typeof speechConfig=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:speechConfig}}};throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`)}function tTool(tool){if(tool.functionDeclarations)for(let functionDeclaration of tool.functionDeclarations)functionDeclaration.parameters&&(Object.keys(functionDeclaration.parameters).includes("$schema")?functionDeclaration.parametersJsonSchema||(functionDeclaration.parametersJsonSchema=functionDeclaration.parameters,delete functionDeclaration.parameters):functionDeclaration.parameters=processJsonSchema(functionDeclaration.parameters)),functionDeclaration.response&&(Object.keys(functionDeclaration.response).includes("$schema")?functionDeclaration.responseJsonSchema||(functionDeclaration.responseJsonSchema=functionDeclaration.response,delete functionDeclaration.response):functionDeclaration.response=processJsonSchema(functionDeclaration.response));return tool}function tTools(tools){if(tools==null)throw new Error("tools is required");if(!Array.isArray(tools))throw new Error("tools is required and must be an array of Tools");let result=[];for(let tool of tools)result.push(tool);return result}function resourceName(client,resourceName2,resourcePrefix,splitsAfterPrefix=1){let shouldAppendPrefix=!resourceName2.startsWith(`${resourcePrefix}/`)&&resourceName2.split("/").length===splitsAfterPrefix;return client.isVertexAI()?resourceName2.startsWith("projects/")?resourceName2:resourceName2.startsWith("locations/")?`projects/${client.getProject()}/${resourceName2}`:resourceName2.startsWith(`${resourcePrefix}/`)?`projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName2}`:shouldAppendPrefix?`projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName2}`:resourceName2:shouldAppendPrefix?`${resourcePrefix}/${resourceName2}`:resourceName2}function tCachedContentName(apiClient,name){if(typeof name!="string")throw new Error("name must be a string");return resourceName(apiClient,name,"cachedContents")}function tBytes(fromImageBytes){return tBytes$1(fromImageBytes)}function tModelsUrl(apiClient,baseModels){let res;return apiClient.isVertexAI()?res=baseModels?"publishers/google/models":"models":res=baseModels?"models":"tunedModels",res}function tExtractModels(response){for(let key of["models","tunedModels","publisherModels"])if(hasField(response,key))return response[key];return[]}function hasField(data,fieldName){return data!==null&&typeof data=="object"&&fieldName in data}function mcpToGeminiTool(mcpTool,config={}){let mcpToolSchema=mcpTool,functionDeclaration={name:mcpToolSchema.name,description:mcpToolSchema.description,parametersJsonSchema:mcpToolSchema.inputSchema};return mcpToolSchema.outputSchema&&(functionDeclaration.responseJsonSchema=mcpToolSchema.outputSchema),config.behavior&&(functionDeclaration.behavior=config.behavior),{functionDeclarations:[functionDeclaration]}}function mcpToolsToGeminiTool(mcpTools,config={}){let functionDeclarations=[],toolNames=new Set;for(let mcpTool of mcpTools){let mcpToolName=mcpTool.name;if(toolNames.has(mcpToolName))throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);toolNames.add(mcpToolName);let geminiTool=mcpToGeminiTool(mcpTool,config);geminiTool.functionDeclarations&&functionDeclarations.push(...geminiTool.functionDeclarations)}return{functionDeclarations}}function tIsVertexEmbedContentModel(model){return model.includes("gemini")&&model!=="gemini-embedding-001"||model.includes("maas")}var PagedItem;(function(PagedItem2){PagedItem2.PAGED_ITEM_BATCH_JOBS="batchJobs",PagedItem2.PAGED_ITEM_MODELS="models",PagedItem2.PAGED_ITEM_TUNING_JOBS="tuningJobs",PagedItem2.PAGED_ITEM_FILES="files",PagedItem2.PAGED_ITEM_CACHED_CONTENTS="cachedContents",PagedItem2.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",PagedItem2.PAGED_ITEM_DOCUMENTS="documents",PagedItem2.PAGED_ITEM_SKILLS="skills"})(PagedItem||(PagedItem={}));var Pager=class{constructor(name,request,response,params){this.pageInternal=[],this.paramsInternal={},this.requestInternal=request,this.init(name,response,params)}init(name,response,params){var _a2,_b;this.nameInternal=name,this.pageInternal=response[this.nameInternal]||[],this.sdkHttpResponseInternal=response?.sdkHttpResponse,this.idxInternal=0;let requestParams={config:{}};!params||Object.keys(params).length===0?requestParams={config:{}}:typeof params=="object"?requestParams=Object.assign({},params):requestParams=params,requestParams.config&&(requestParams.config.pageToken=response.nextPageToken),this.paramsInternal=requestParams,this.pageInternalSize=(_b=(_a2=requestParams.config)===null||_a2===void 0?void 0:_a2.pageSize)!==null&&_b!==void 0?_b:this.pageInternal.length}initNextPage(response){this.init(this.nameInternal,response,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(index){return this.pageInternal[index]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};let item=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:item,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");let response=await this.requestInternal(this.params);return this.initNextPage(response),this.page}hasNextPage(){var _a2;return((_a2=this.params.config)===null||_a2===void 0?void 0:_a2.pageToken)!==void 0}};function __values(o){var s2=typeof Symbol=="function"&&Symbol.iterator,m2=s2&&o[s2],i2=0;if(m2)return m2.call(o);if(o&&typeof o.length=="number")return{next:function(){return o&&i2>=o.length&&(o=void 0),{value:o&&o[i2++],done:!o}}};throw new TypeError(s2?"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||[]),i2,q=[];return i2=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",awaitReturn),i2[Symbol.asyncIterator]=function(){return this},i2;function awaitReturn(f3){return function(v){return Promise.resolve(v).then(f3,reject)}}function verb(n,f3){g[n]&&(i2[n]=function(v){return new Promise(function(a,b){q.push([n,v,a,b])>1||resume(n,v)})},f3&&(i2[n]=f3(i2[n])))}function resume(n,v){try{step(g[n](v))}catch(e2){settle(q[0][3],e2)}}function step(r2){r2.value instanceof __await?Promise.resolve(r2.value.v).then(fulfill,reject):settle(q[0][2],r2)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f3,v){f3(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 m2=o[Symbol.asyncIterator],i2;return m2?m2.call(o):(o=typeof __values=="function"?__values(o):o[Symbol.iterator](),i2={},verb("next"),verb("throw"),verb("return"),i2[Symbol.asyncIterator]=function(){return this},i2);function verb(n){i2[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 authConfigToMldev$1(fromObject,_rootObject){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 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 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 Platform mode, not in Gemini Developer API mode.");return toObject}function blobToMldev$1(fromObject,_rootObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function candidateFromMldev(fromObject,rootObject){let toObject={},fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&setValueByPath(toObject,["content"],fromContent);let fromCitationMetadata=getValueByPath(fromObject,["citationMetadata"]);fromCitationMetadata!=null&&setValueByPath(toObject,["citationMetadata"],citationMetadataFromMldev(fromCitationMetadata));let fromTokenCount=getValueByPath(fromObject,["tokenCount"]);fromTokenCount!=null&&setValueByPath(toObject,["tokenCount"],fromTokenCount);let fromFinishReason=getValueByPath(fromObject,["finishReason"]);fromFinishReason!=null&&setValueByPath(toObject,["finishReason"],fromFinishReason);let fromGroundingMetadata=getValueByPath(fromObject,["groundingMetadata"]);fromGroundingMetadata!=null&&setValueByPath(toObject,["groundingMetadata"],fromGroundingMetadata);let fromAvgLogprobs=getValueByPath(fromObject,["avgLogprobs"]);fromAvgLogprobs!=null&&setValueByPath(toObject,["avgLogprobs"],fromAvgLogprobs);let fromIndex=getValueByPath(fromObject,["index"]);fromIndex!=null&&setValueByPath(toObject,["index"],fromIndex);let fromLogprobsResult=getValueByPath(fromObject,["logprobsResult"]);fromLogprobsResult!=null&&setValueByPath(toObject,["logprobsResult"],fromLogprobsResult);let fromSafetyRatings=getValueByPath(fromObject,["safetyRatings"]);if(fromSafetyRatings!=null){let transformedList=fromSafetyRatings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["safetyRatings"],transformedList)}let fromUrlContextMetadata=getValueByPath(fromObject,["urlContextMetadata"]);return fromUrlContextMetadata!=null&&setValueByPath(toObject,["urlContextMetadata"],fromUrlContextMetadata),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){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){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(fromObject,_rootObject){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!=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);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(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(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(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"]);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 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!=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(item))),setValueByPath(parentObject,["tools"],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(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,["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)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&countTokensConfigToVertex(fromConfig,toObject),toObject}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!=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){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(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(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,["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,["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"],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(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(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 fromEditMode=getValueByPath(fromObject,["editMode"]);parentObject!==void 0&&fromEditMode!=null&&setValueByPath(parentObject,["parameters","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,["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&&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(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(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 Enterprise 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){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!=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!==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","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==="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(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_CONTENT"){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,["audioTrackExtraction"]);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(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!==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==="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(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);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(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!=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.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),toObject}function fileDataToMldev$1(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),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 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(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),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);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(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(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);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,["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 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)&&(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"]);if(parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToMldev(fromToolConfig)),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.");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,["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 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,["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.");return 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,["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(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,["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(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(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(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!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex(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(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);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);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 only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromModelArmorConfig=getValueByPath(fromObject,["modelArmorConfig"]);return parentObject!==void 0&&fromModelArmorConfig!=null&&setValueByPath(parentObject,["modelArmorConfig"],fromModelArmorConfig),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.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));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){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,["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(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,["candidates"]);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(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){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!=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,["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"],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(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(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!==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","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,["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(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 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,["seed"])!==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);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!=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(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"],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 in 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){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,["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(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,["pubsubTopic"]);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"],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!=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"]);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(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(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(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!=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,["image"]);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){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(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;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(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,["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!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToMldev(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);return parentObject!==void 0&&fromVideo!=null&&setValueByPath(parentObject,["instances[0]","video"],videoToMldev(fromVideo)),toObject}function generateVideosSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToVertex(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);return parentObject!==void 0&&fromVideo!=null&&setValueByPath(parentObject,["instances[0]","video"],videoToVertex(fromVideo)),toObject}function generatedImageFromVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["_self"]);fromImage!=null&&setValueByPath(toObject,["image"],imageFromVertex(fromImage));let fromRaiFilteredReason=getValueByPath(fromObject,["raiFilteredReason"]);fromRaiFilteredReason!=null&&setValueByPath(toObject,["raiFilteredReason"],fromRaiFilteredReason);let fromSafetyAttributes=getValueByPath(fromObject,["_self"]);fromSafetyAttributes!=null&&setValueByPath(toObject,["safetyAttributes"],safetyAttributesFromVertex(fromSafetyAttributes));let fromEnhancedPrompt=getValueByPath(fromObject,["prompt"]);return fromEnhancedPrompt!=null&&setValueByPath(toObject,["enhancedPrompt"],fromEnhancedPrompt),toObject}function generatedImageMaskFromVertex(fromObject,rootObject){let toObject={},fromMask=getValueByPath(fromObject,["_self"]);fromMask!=null&&setValueByPath(toObject,["mask"],imageFromVertex(fromMask));let fromLabels=getValueByPath(fromObject,["labels"]);if(fromLabels!=null){let transformedList=fromLabels;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["labels"],transformedList)}return toObject}function generatedVideoFromMldev(fromObject,rootObject){let toObject={},fromVideo=getValueByPath(fromObject,["video"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromMldev(fromVideo)),toObject}function generatedVideoFromVertex(fromObject,rootObject){let toObject={},fromVideo=getValueByPath(fromObject,["_self"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromVertex(fromVideo)),toObject}function generationConfigToVertex(fromObject,rootObject){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,["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,["candidateCount"],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);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(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!=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&&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(fromSpeechConfig));let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromTemperature=getValueByPath(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(fromObject,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function getModelParametersToMldev(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function getModelParametersToVertex(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function googleMapsToMldev$1(fromObject,rootObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$1(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$1(fromObject,_rootObject){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&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function imageConfigToMldev(fromObject,_rootObject){let toObject={},fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);fromAspectRatio!=null&&setValueByPath(toObject,["aspectRatio"],fromAspectRatio);let fromImageSize=getValueByPath(fromObject,["imageSize"]);if(fromImageSize!=null&&setValueByPath(toObject,["imageSize"],fromImageSize),getValueByPath(fromObject,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function imageConfigToVertex(fromObject,_rootObject){let toObject={},fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);fromAspectRatio!=null&&setValueByPath(toObject,["aspectRatio"],fromAspectRatio);let fromImageSize=getValueByPath(fromObject,["imageSize"]);fromImageSize!=null&&setValueByPath(toObject,["imageSize"],fromImageSize);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);fromPersonGeneration!=null&&setValueByPath(toObject,["personGeneration"],fromPersonGeneration);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);fromOutputMimeType!=null&&setValueByPath(toObject,["imageOutputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);fromOutputCompressionQuality!=null&&setValueByPath(toObject,["imageOutputOptions","compressionQuality"],fromOutputCompressionQuality);let fromImageOutputOptions=getValueByPath(fromObject,["imageOutputOptions"]);fromImageOutputOptions!=null&&setValueByPath(toObject,["imageOutputOptions"],fromImageOutputOptions);let fromProminentPeople=getValueByPath(fromObject,["prominentPeople"]);return fromProminentPeople!=null&&setValueByPath(toObject,["prominentPeople"],fromProminentPeople),toObject}function imageFromVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromImageBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromImageBytes!=null&&setValueByPath(toObject,["imageBytes"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function imageToMldev(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 Developer API mode.");let fromImageBytes=getValueByPath(fromObject,["imageBytes"]);fromImageBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function imageToVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromImageBytes=getValueByPath(fromObject,["imageBytes"]);fromImageBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function listModelsConfigToMldev(apiClient,fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter);let fromQueryBase=getValueByPath(fromObject,["queryBase"]);return parentObject!==void 0&&fromQueryBase!=null&&setValueByPath(parentObject,["_url","models_url"],tModelsUrl(apiClient,fromQueryBase)),toObject}function listModelsConfigToVertex(apiClient,fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter);let fromQueryBase=getValueByPath(fromObject,["queryBase"]);return parentObject!==void 0&&fromQueryBase!=null&&setValueByPath(parentObject,["_url","models_url"],tModelsUrl(apiClient,fromQueryBase)),toObject}function listModelsParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listModelsConfigToMldev(apiClient,fromConfig,toObject),toObject}function listModelsParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listModelsConfigToVertex(apiClient,fromConfig,toObject),toObject}function listModelsResponseFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromModels=getValueByPath(fromObject,["_self"]);if(fromModels!=null){let transformedList=tExtractModels(fromModels);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>modelFromMldev(item))),setValueByPath(toObject,["models"],transformedList)}return toObject}function listModelsResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromModels=getValueByPath(fromObject,["_self"]);if(fromModels!=null){let transformedList=tExtractModels(fromModels);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>modelFromVertex(item))),setValueByPath(toObject,["models"],transformedList)}return toObject}function maskReferenceConfigToVertex(fromObject,_rootObject){let toObject={},fromMaskMode=getValueByPath(fromObject,["maskMode"]);fromMaskMode!=null&&setValueByPath(toObject,["maskMode"],fromMaskMode);let fromSegmentationClasses=getValueByPath(fromObject,["segmentationClasses"]);fromSegmentationClasses!=null&&setValueByPath(toObject,["maskClasses"],fromSegmentationClasses);let fromMaskDilation=getValueByPath(fromObject,["maskDilation"]);return fromMaskDilation!=null&&setValueByPath(toObject,["dilation"],fromMaskDilation),toObject}function mcpServerToVertex(fromObject,_rootObject){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 API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function modelFromMldev(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromVersion=getValueByPath(fromObject,["version"]);fromVersion!=null&&setValueByPath(toObject,["version"],fromVersion);let fromTunedModelInfo=getValueByPath(fromObject,["_self"]);fromTunedModelInfo!=null&&setValueByPath(toObject,["tunedModelInfo"],tunedModelInfoFromMldev(fromTunedModelInfo));let fromInputTokenLimit=getValueByPath(fromObject,["inputTokenLimit"]);fromInputTokenLimit!=null&&setValueByPath(toObject,["inputTokenLimit"],fromInputTokenLimit);let fromOutputTokenLimit=getValueByPath(fromObject,["outputTokenLimit"]);fromOutputTokenLimit!=null&&setValueByPath(toObject,["outputTokenLimit"],fromOutputTokenLimit);let fromSupportedActions=getValueByPath(fromObject,["supportedGenerationMethods"]);fromSupportedActions!=null&&setValueByPath(toObject,["supportedActions"],fromSupportedActions);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromMaxTemperature=getValueByPath(fromObject,["maxTemperature"]);fromMaxTemperature!=null&&setValueByPath(toObject,["maxTemperature"],fromMaxTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromThinking=getValueByPath(fromObject,["thinking"]);return fromThinking!=null&&setValueByPath(toObject,["thinking"],fromThinking),toObject}function modelFromVertex(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromVersion=getValueByPath(fromObject,["versionId"]);fromVersion!=null&&setValueByPath(toObject,["version"],fromVersion);let fromEndpoints=getValueByPath(fromObject,["deployedModels"]);if(fromEndpoints!=null){let transformedList=fromEndpoints;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>endpointFromVertex(item))),setValueByPath(toObject,["endpoints"],transformedList)}let fromLabels=getValueByPath(fromObject,["labels"]);fromLabels!=null&&setValueByPath(toObject,["labels"],fromLabels);let fromTunedModelInfo=getValueByPath(fromObject,["_self"]);fromTunedModelInfo!=null&&setValueByPath(toObject,["tunedModelInfo"],tunedModelInfoFromVertex(fromTunedModelInfo));let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);fromDefaultCheckpointId!=null&&setValueByPath(toObject,["defaultCheckpointId"],fromDefaultCheckpointId);let fromCheckpoints=getValueByPath(fromObject,["checkpoints"]);if(fromCheckpoints!=null){let transformedList=fromCheckpoints;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["checkpoints"],transformedList)}return toObject}function multiSpeakerVoiceConfigToVertex(fromObject,rootObject){let toObject={},fromSpeakerVoiceConfigs=getValueByPath(fromObject,["speakerVoiceConfigs"]);if(fromSpeakerVoiceConfigs!=null){let transformedList=fromSpeakerVoiceConfigs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>speakerVoiceConfigToVertex(item))),setValueByPath(toObject,["speakerVoiceConfigs"],transformedList)}return toObject}function partToMldev$1(fromObject,rootObject){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(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&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev$1(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev$1(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev$1(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&&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"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function partToVertex$1(fromObject,_rootObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(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"]);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!=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);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(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"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function productImageToVertex(fromObject,rootObject){let toObject={},fromProductImage=getValueByPath(fromObject,["productImage"]);return fromProductImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromProductImage)),toObject}function recontextImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromBaseSteps=getValueByPath(fromObject,["baseSteps"]);parentObject!==void 0&&fromBaseSteps!=null&&setValueByPath(parentObject,["parameters","baseSteps"],fromBaseSteps);let fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromSeed=getValueByPath(fromObject,["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"],fromPersonGeneration);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);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","compressionQuality"],fromOutputCompressionQuality);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt);let fromLabels=getValueByPath(fromObject,["labels"]);return parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),toObject}function recontextImageParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&recontextImageSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&recontextImageConfigToVertex(fromConfig,toObject),toObject}function recontextImageResponseFromVertex(fromObject,rootObject){let toObject={},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 recontextImageSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromPersonImage=getValueByPath(fromObject,["personImage"]);parentObject!==void 0&&fromPersonImage!=null&&setValueByPath(parentObject,["instances[0]","personImage","image"],imageToVertex(fromPersonImage));let fromProductImages=getValueByPath(fromObject,["productImages"]);if(parentObject!==void 0&&fromProductImages!=null){let transformedList=fromProductImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>productImageToVertex(item))),setValueByPath(parentObject,["instances[0]","productImages"],transformedList)}return toObject}function referenceImageAPIInternalToVertex(fromObject,rootObject){let toObject={},fromReferenceImage=getValueByPath(fromObject,["referenceImage"]);fromReferenceImage!=null&&setValueByPath(toObject,["referenceImage"],imageToVertex(fromReferenceImage));let fromReferenceId=getValueByPath(fromObject,["referenceId"]);fromReferenceId!=null&&setValueByPath(toObject,["referenceId"],fromReferenceId);let fromReferenceType=getValueByPath(fromObject,["referenceType"]);fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType);let fromMaskImageConfig=getValueByPath(fromObject,["maskImageConfig"]);fromMaskImageConfig!=null&&setValueByPath(toObject,["maskImageConfig"],maskReferenceConfigToVertex(fromMaskImageConfig));let fromControlImageConfig=getValueByPath(fromObject,["controlImageConfig"]);fromControlImageConfig!=null&&setValueByPath(toObject,["controlImageConfig"],controlReferenceConfigToVertex(fromControlImageConfig));let fromStyleImageConfig=getValueByPath(fromObject,["styleImageConfig"]);fromStyleImageConfig!=null&&setValueByPath(toObject,["styleImageConfig"],fromStyleImageConfig);let fromSubjectImageConfig=getValueByPath(fromObject,["subjectImageConfig"]);return fromSubjectImageConfig!=null&&setValueByPath(toObject,["subjectImageConfig"],fromSubjectImageConfig),toObject}function replicatedVoiceConfigToVertex(fromObject,_rootObject){let toObject={},fromMimeType=getValueByPath(fromObject,["mimeType"]);fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType);let fromVoiceSampleAudio=getValueByPath(fromObject,["voiceSampleAudio"]);if(fromVoiceSampleAudio!=null&&setValueByPath(toObject,["voiceSampleAudio"],fromVoiceSampleAudio),getValueByPath(fromObject,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function safetyAttributesFromVertex(fromObject,_rootObject){let toObject={},fromCategories=getValueByPath(fromObject,["safetyAttributes","categories"]);fromCategories!=null&&setValueByPath(toObject,["categories"],fromCategories);let fromScores=getValueByPath(fromObject,["safetyAttributes","scores"]);fromScores!=null&&setValueByPath(toObject,["scores"],fromScores);let fromContentType=getValueByPath(fromObject,["contentType"]);return fromContentType!=null&&setValueByPath(toObject,["contentType"],fromContentType),toObject}function safetySettingToMldev$1(fromObject,_rootObject){let toObject={},fromCategory=getValueByPath(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 scribbleImageToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);return fromImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromImage)),toObject}function segmentImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromMode=getValueByPath(fromObject,["mode"]);parentObject!==void 0&&fromMode!=null&&setValueByPath(parentObject,["parameters","mode"],fromMode);let fromMaxPredictions=getValueByPath(fromObject,["maxPredictions"]);parentObject!==void 0&&fromMaxPredictions!=null&&setValueByPath(parentObject,["parameters","maxPredictions"],fromMaxPredictions);let fromConfidenceThreshold=getValueByPath(fromObject,["confidenceThreshold"]);parentObject!==void 0&&fromConfidenceThreshold!=null&&setValueByPath(parentObject,["parameters","confidenceThreshold"],fromConfidenceThreshold);let fromMaskDilation=getValueByPath(fromObject,["maskDilation"]);parentObject!==void 0&&fromMaskDilation!=null&&setValueByPath(parentObject,["parameters","maskDilation"],fromMaskDilation);let fromBinaryColorThreshold=getValueByPath(fromObject,["binaryColorThreshold"]);parentObject!==void 0&&fromBinaryColorThreshold!=null&&setValueByPath(parentObject,["parameters","binaryColorThreshold"],fromBinaryColorThreshold);let fromLabels=getValueByPath(fromObject,["labels"]);return parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),toObject}function segmentImageParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&segmentImageSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&segmentImageConfigToVertex(fromConfig,toObject),toObject}function segmentImageResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedMasks=getValueByPath(fromObject,["predictions"]);if(fromGeneratedMasks!=null){let transformedList=fromGeneratedMasks;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageMaskFromVertex(item))),setValueByPath(toObject,["generatedMasks"],transformedList)}return toObject}function segmentImageSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToVertex(fromImage));let fromScribbleImage=getValueByPath(fromObject,["scribbleImage"]);return parentObject!==void 0&&fromScribbleImage!=null&&setValueByPath(parentObject,["instances[0]","scribble"],scribbleImageToVertex(fromScribbleImage)),toObject}function speakerVoiceConfigToVertex(fromObject,rootObject){let toObject={},fromSpeaker=getValueByPath(fromObject,["speaker"]);fromSpeaker!=null&&setValueByPath(toObject,["speaker"],fromSpeaker);let fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);return fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex(fromVoiceConfig)),toObject}function speechConfigToVertex(fromObject,rootObject){let toObject={},fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex(fromVoiceConfig));let fromLanguageCode=getValueByPath(fromObject,["languageCode"]);fromLanguageCode!=null&&setValueByPath(toObject,["languageCode"],fromLanguageCode);let fromMultiSpeakerVoiceConfig=getValueByPath(fromObject,["multiSpeakerVoiceConfig"]);return fromMultiSpeakerVoiceConfig!=null&&setValueByPath(toObject,["multiSpeakerVoiceConfig"],multiSpeakerVoiceConfigToVertex(fromMultiSpeakerVoiceConfig)),toObject}function toolConfigToMldev(fromObject,rootObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],functionCallingConfigToMldev(fromFunctionCallingConfig));let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig);let fromIncludeServerSideToolInvocations=getValueByPath(fromObject,["includeServerSideToolInvocations"]);return fromIncludeServerSideToolInvocations!=null&&setValueByPath(toObject,["includeServerSideToolInvocations"],fromIncludeServerSideToolInvocations),toObject}function toolConfigToVertex(fromObject,_rootObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],fromFunctionCallingConfig);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$1(fromObject,rootObject){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$1(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!=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(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$1(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,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),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(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,["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;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(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 tunedModelInfoFromMldev(fromObject,_rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromCreateTime=getValueByPath(fromObject,["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(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);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(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),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!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateModelConfigToVertex(fromConfig,toObject),toObject}function upscaleImageAPIConfigInternalToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);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 fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);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","compressionQuality"],fromOutputCompressionQuality);let fromEnhanceInputImage=getValueByPath(fromObject,["enhanceInputImage"]);parentObject!==void 0&&fromEnhanceInputImage!=null&&setValueByPath(parentObject,["parameters","upscaleConfig","enhanceInputImage"],fromEnhanceInputImage);let fromImagePreservationFactor=getValueByPath(fromObject,["imagePreservationFactor"]);parentObject!==void 0&&fromImagePreservationFactor!=null&&setValueByPath(parentObject,["parameters","upscaleConfig","imagePreservationFactor"],fromImagePreservationFactor);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromMode=getValueByPath(fromObject,["mode"]);return parentObject!==void 0&&fromMode!=null&&setValueByPath(parentObject,["parameters","mode"],fromMode),toObject}function upscaleImageAPIParametersInternalToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToVertex(fromImage));let fromUpscaleFactor=getValueByPath(fromObject,["upscaleFactor"]);fromUpscaleFactor!=null&&setValueByPath(toObject,["parameters","upscaleConfig","upscaleFactor"],fromUpscaleFactor);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&upscaleImageAPIConfigInternalToVertex(fromConfig,toObject),toObject}function upscaleImageResponseFromVertex(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(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function videoFromMldev(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["encodedVideo"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["encoding"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoFromVertex(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["gcsUri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoGenerationMaskToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["_self"],imageToVertex(fromImage));let fromMaskMode=getValueByPath(fromObject,["maskMode"]);return fromMaskMode!=null&&setValueByPath(toObject,["maskMode"],fromMaskMode),toObject}function videoGenerationReferenceImageToMldev(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["image"],imageToMldev(fromImage));let fromReferenceType=getValueByPath(fromObject,["referenceType"]);return fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType),toObject}function videoGenerationReferenceImageToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromImage));let fromReferenceType=getValueByPath(fromObject,["referenceType"]);return fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType),toObject}function videoToMldev(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["videoBytes"]);fromVideoBytes!=null&&setValueByPath(toObject,["encodedVideo"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["encoding"],fromMimeType),toObject}function videoToVertex(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["gcsUri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["videoBytes"]);fromVideoBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function voiceConfigToVertex(fromObject,rootObject){let toObject={},fromReplicatedVoiceConfig=getValueByPath(fromObject,["replicatedVoiceConfig"]);fromReplicatedVoiceConfig!=null&&setValueByPath(toObject,["replicatedVoiceConfig"],replicatedVoiceConfigToVertex(fromReplicatedVoiceConfig));let fromPrebuiltVoiceConfig=getValueByPath(fromObject,["prebuiltVoiceConfig"]);return fromPrebuiltVoiceConfig!=null&&setValueByPath(toObject,["prebuiltVoiceConfig"],fromPrebuiltVoiceConfig),toObject}var GOOGLE_API_CLIENT_HEADER="x-goog-api-client",SDK_VERSION="2.21.0",LIBRARY_LABEL=`google-genai-sdk/${SDK_VERSION}`;var MCP_LABEL="mcp_used/unknown",hasMcpToolUsageFromMcpToTool=!1;function hasMcpToolUsage(tools){for(let tool of tools)if(isMcpCallableTool(tool)||typeof tool=="object"&&"inputSchema"in tool)return!0;return hasMcpToolUsageFromMcpToTool}function setMcpUsageHeader(headers){var _a2;let existingHeader=(_a2=headers[GOOGLE_API_CLIENT_HEADER])!==null&&_a2!==void 0?_a2:"";headers[GOOGLE_API_CLIENT_HEADER]=(existingHeader+` ${MCP_LABEL}`).trimStart()}function isMcpCallableTool(object){return object!==null&&typeof object=="object"&&object instanceof McpCallableTool}function listAllTools(mcpClient_1){return __asyncGenerator(this,arguments,function*(mcpClient,maxTools=100){let cursor,numTools=0;for(;numTools<maxTools;){let t2=yield __await(mcpClient.listTools({cursor}));for(let tool of t2.tools)yield yield __await(tool),numTools++;if(!t2.nextCursor)break;cursor=t2.nextCursor}})}var McpCallableTool=class _McpCallableTool{constructor(mcpClients=[],config){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=mcpClients,this.config=config}static create(mcpClients,config){return new _McpCallableTool(mcpClients,config)}async initialize(){var _a2,e_1,_b,_c;if(this.mcpTools.length>0)return;let functionMap={},mcpTools=[];for(let mcpClient of this.mcpClients)try{for(var _d=!0,_e=(e_1=void 0,__asyncValues(listAllTools(mcpClient))),_f;_f=await _e.next(),_a2=_f.done,!_a2;_d=!0){_c=_f.value,_d=!1;let mcpTool=_c;mcpTools.push(mcpTool);let mcpToolName=mcpTool.name;if(functionMap[mcpToolName])throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);functionMap[mcpToolName]=mcpClient}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_d&&!_a2&&(_b=_e.return)&&await _b.call(_e)}finally{if(e_1)throw e_1.error}}this.mcpTools=mcpTools,this.functionNameToMcpClient=functionMap}async tool(){return await this.initialize(),mcpToolsToGeminiTool(this.mcpTools,this.config)}async callTool(functionCalls){await this.initialize();let functionCallResponseParts=[];for(let functionCall of functionCalls)if(functionCall.name in this.functionNameToMcpClient){let mcpClient=this.functionNameToMcpClient[functionCall.name],requestOptions;this.config.timeout&&(requestOptions={timeout:this.config.timeout});let callToolResponse=await mcpClient.callTool({name:functionCall.name,arguments:functionCall.args},void 0,requestOptions);functionCallResponseParts.push({functionResponse:{name:functionCall.name,response:callToolResponse.isError?{error:callToolResponse}:callToolResponse}})}return functionCallResponseParts}};var DEFAULT_MAX_REMOTE_CALLS=10;function shouldDisableAfc(config){var _a2,_b,_c;if(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.disable)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 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)===null||_a2===void 0)&&_a2.tools&¶ms.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=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")&¶ms.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(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(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,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,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(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.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:_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' 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 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=>{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,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 Agent Platform mode.");actualParams.config.filter="labels.tune-type:*"}return new Pager(PagedItem.PAGED_ITEM_MODELS,x2=>this.listInternal(x2),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/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,referenceImages:[],config:params.config};return params.referenceImages&¶ms.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};return await this.upscaleImageInternal(apiParams)},this.generateVideos=async params=>{var _a2,_b,_c,_d,_e,_f;if((params.prompt||params.image||params.video)&¶ms.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 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.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)}}maybeMoveToResponseJsonSchema(params){params.config&¶ms.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)===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&¶ms.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){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}`);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,e_1,_b2,_c2,_d,_e;remoteCallCount<maxRemoteCalls;){wereFunctionsCalled&&(remoteCallCount++,wereFunctionsCalled=!1);let transformedParams=yield __await(models.processParamsMaybeAddMcpUsage(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=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 implement 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=[];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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(apiResponse),typedResp=new GenerateContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=generateContentParametersToMldev(this.apiClient,params);return path=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(apiResponse),typedResp=new GenerateContentResponse;return Object.assign(typedResp,resp),typedResp})}}async generateContentStreamInternal(params){var _a2,_b,_c,_d;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path,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(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={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 path=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path,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_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={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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=embedContentParametersPrivateToVertex(this.apiClient,params,params),endpointUrl=tIsVertexEmbedContentModel(params.model)?"{model}:embedContent":"{model}:predict";return path=formatMap(endpointUrl,body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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=embedContentResponseFromVertex(apiResponse,params),typedResp=new EmbedContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=embedContentParametersPrivateToMldev(this.apiClient,params);return path=formatMap("{model}:batchEmbedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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=embedContentResponseFromMldev(apiResponse),typedResp=new EmbedContentResponse;return Object.assign(typedResp,resp),typedResp})}}async generateImagesInternal(params){var _a2,_b;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateImagesParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=editImageParametersInternalToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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;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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=upscaleImageAPIParametersInternalToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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;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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=recontextImageParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 Platform (previously known as Vertex AI).")}async segmentImage(params){var _a2,_b;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=segmentImageParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=getModelParametersToVertex(this.apiClient,params);return path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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{let body=getModelParametersToMldev(this.apiClient,params);return path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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){var _a2,_b,_c,_d;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=listModelsParametersToVertex(this.apiClient,params);return path=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(apiResponse),typedResp=new ListModelsResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=listModelsParametersToMldev(this.apiClient,params);return path=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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;return Object.assign(typedResp,resp),typedResp})}}async update(params){var _a2,_b,_c,_d;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=updateModelParametersToVertex(this.apiClient,params);return path=formatMap("{model}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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.apiClient,params);return path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,_d;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=deleteModelParametersToVertex(this.apiClient,params);return path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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.assign(typedResp,resp),typedResp})}else{let body=deleteModelParametersToMldev(this.apiClient,params);return path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(typedResp,resp),typedResp})}}async countTokens(params){var _a2,_b,_c,_d;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=countTokensParametersToVertex(this.apiClient,params);return path=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(apiResponse),typedResp=new CountTokensResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=countTokensParametersToMldev(this.apiClient,params);return path=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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=countTokensResponseFromMldev(apiResponse),typedResp=new CountTokensResponse;return Object.assign(typedResp,resp),typedResp})}}async computeTokens(params){var _a2,_b;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=computeTokensParametersToVertex(this.apiClient,params);return path=formatMap("{model}:computeTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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=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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateVideosParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(apiResponse),typedResp=new GenerateVideosOperation;return Object.assign(typedResp,resp),typedResp})}else{let body=generateVideosParametersToMldev(this.apiClient,params);return path=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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.assign(typedResp,resp),typedResp})}}};Models.loggedGenerateImagesWarning=!1;Models.loggedEditImageWarning=!1;Models.loggedGenerateVideosWarning=!1;function bytesToBase64(u8arr){return btoa(String.fromCodePoint(...u8arr))}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}}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=>options?.charEncoding==="percent"?encodeURIComponent(v):v,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(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=`${encodeString(pk)}=${encValue}`,!(!tmp||tmp==="=")&&(out+=`&${tmp}`)))}),out.slice(1)}}var encodeForm=formEncoder(",");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):value}function mapDefined(inp,mapper){let res=inp.reduce((acc,v)=>{if(v==null)return acc;let m2=mapper(v);return m2==null||acc.push(m2),acc},[]);return res.length?res:null}function mapDefinedEntries(inp,mapper){let acc=[];for(let[k,v]of inp){if(v==null)continue;let m2=mapper([k,v]);m2!=null&&acc.push(m2)}return acc.length?acc:null}function queryJoin(...args){return args.filter(Boolean).join("&")}function queryEncoder(f3){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.entries(values).map(([key,value])=>allowEmptySet.has(key)&&(value==null||value===""||Array.isArray(value)&&value.length===0)?`${encodeURIComponent(key)}=`:f3(key,value,opts));return queryJoin(...encoded)}}var encodeFormQuery=queryEncoder(encodeForm);var codeRangeRE$1=new RegExp("^[0-9]xx$","i");var codeRangeRE=new RegExp("^[0-9]xx$","i");var gt=typeof globalThis>"u"?null:globalThis,webWorkerLike=typeof gt=="object"&>!=null&&"importScripts"in gt&&typeof gt.importScripts=="function",isBrowserLike=webWorkerLike||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u";var CR2=13,LF2=10,BOUNDARIES=[[CR2,LF2,CR2,LF2],[CR2,LF2,CR2],[CR2,LF2,LF2],[CR2,CR2,LF2],[LF2,CR2,LF2],[CR2,CR2],[LF2,CR2],[LF2,LF2]],MAX_BOUNDARY_LEN=BOUNDARIES.reduce((m2,b)=>Math.max(m2,b.length),0);var _a;_a=Symbol.toStringTag;var MAX_CHUNK_SIZE=1024*1024*8;var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types3=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types3.includes("object")||types3.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(!config||config.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error){if(!(error instanceof UnsupportedStrictJsonSchemaError))throw error;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)";function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return isSameModel?block.redacted||block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:block:[];if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&normalizeToolCallId){let normalizedId=normalizeToolCallId(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i2=0;i2<transformed.length;i2++){let msg=transformed[i2];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b=>b.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}var GOOGLE_SDK_THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH};function resolveGoogleThinkingLevel(model,level){let mapped=model.thinkingLevelMap?.[level],resolvedLevel=typeof mapped=="string"?mapped.toLowerCase():level;switch(resolvedLevel){case"minimal":case"low":case"medium":case"high":return resolvedLevel;default:throw new Error(`Unsupported Google thinking level mapping for ${model.provider}/${model.id}: ${level} -> ${String(mapped)}`)}}function usesGoogleThinkingLevel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-(?:pro|flash)/.test(id)||/gemini-(?:[4-9]|[1-9]\d)/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"||/gemma-?4/.test(id)}function toGoogleThinkingLevel(level){switch(level){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function toGoogleSdkThinkingLevel(level){return GOOGLE_SDK_THINKING_LEVEL_MAP[level]}function getDisabledGoogleThinkingConfig(model){if(!usesGoogleThinkingLevel(model))return{thinkingBudget:0};let fallback=clampThinkingLevel(model,"off");if(fallback==="off")return{thinkingBudget:0};let resolvedLevel=resolveGoogleThinkingLevel(model,fallback),apiLevel=toGoogleThinkingLevel(resolvedLevel);return{thinkingLevel:toGoogleSdkThinkingLevel(apiLevel)}}function isThinkingPart(part){return part.thought===!0}function retainThoughtSignature(existing,incoming){return typeof incoming=="string"&&incoming.length>0?incoming:existing}var base64SignaturePattern=/^[A-Za-z0-9+/]+={0,2}$/;function isValidThoughtSignature(signature){return!signature||signature.length%4!==0?!1:base64SignaturePattern.test(signature)}function resolveThoughtSignature(isSameProviderAndModel,signature){return isSameProviderAndModel&&isValidThoughtSignature(signature)?signature:void 0}function requiresToolCallId(modelId){let geminiMajorVersion=getGeminiMajorVersion(modelId);return modelId.startsWith("claude-")||modelId.startsWith("gpt-oss-")||geminiMajorVersion!==void 0&&geminiMajorVersion>=3}function getGeminiMajorVersion(modelId){let match=modelId.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(match)return Number.parseInt(match[1],10)}function supportsMultimodalFunctionResponse(modelId){let geminiMajorVersion=getGeminiMajorVersion(modelId);return geminiMajorVersion!==void 0?geminiMajorVersion>=3:!0}function convertMessages(model,context){let conversation=withoutInitialSystemMessage(collapseSystemMessages(context).messages),contents=[],transformedMessages=transformMessages(conversation,model,id=>requiresToolCallId(model.id)?id.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64):id);for(let msg of transformedMessages)if(msg.role==="user")if(typeof msg.content=="string")contents.push({role:"user",parts:[{text:sanitizeSurrogates(msg.content)}]});else{let parts=msg.content.map(item=>item.type==="text"?{text:sanitizeSurrogates(item.text)}:{inlineData:{mimeType:item.mimeType,data:item.data}});if(parts.length===0)continue;contents.push({role:"user",parts})}else if(msg.role==="assistant"){let parts=[],isSameProviderAndModel=msg.provider===model.provider&&msg.model===model.id;for(let block of msg.content)if(block.type==="text"){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.textSignature);if((!block.text||block.text.trim()==="")&&!thoughtSignature)continue;parts.push({text:sanitizeSurrogates(block.text),...thoughtSignature&&{thoughtSignature}})}else if(block.type==="thinking")if(isSameProviderAndModel){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.thinkingSignature);if((!block.thinking||block.thinking.trim()==="")&&!thoughtSignature)continue;parts.push({thought:!0,text:sanitizeSurrogates(block.thinking),...thoughtSignature&&{thoughtSignature}})}else{if(!block.thinking||block.thinking.trim()==="")continue;parts.push({text:sanitizeSurrogates(block.thinking)})}else if(block.type==="toolCall"){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.thoughtSignature),part={functionCall:{name:block.name,args:block.arguments??{},...requiresToolCallId(model.id)?{id:block.id}:{}},...thoughtSignature&&{thoughtSignature}};parts.push(part)}if(parts.length===0)continue;contents.push({role:"model",parts})}else if(msg.role==="toolResult"){let textResult=msg.content.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
66
|
+
`),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function getCurrentSystemPrompt(messages){let message=getCurrentSystemMessage(messages);return message?getSystemMessageText(message):""}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}function calculateCost(model,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model.cost,matchedThreshold=-1;for(let tier of model.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost.totalFromProvider=!1,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model){return model.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==void 0:!0}):["off"]}function clampThinkingLevel(model,level){let availableLevels=getSupportedThinkingLevels(model);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i2=requestedIndex;i2<EXTENDED_THINKING_LEVELS.length;i2++){let candidate=EXTENDED_THINKING_LEVELS[i2];if(availableLevels.includes(candidate))return candidate}for(let i2=requestedIndex-1;i2>=0;i2--){let candidate=EXTENDED_THINKING_LEVELS[i2];if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}var MAX_PROVIDER_ERROR_BODY_CHARS=4e3;function normalizeProviderError(error){if(!(error instanceof Error))return{message:safeJsonStringify(error),messageCarriesBody:!1};let sdkError=error,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error.message.includes(body);return{status,body,message:error.message,messageCarriesBody}}function extractStatus(error){if(typeof error.statusCode=="number")return error.statusCode;if(typeof error.status=="number")return error.status;if(typeof error.$metadata?.httpStatusCode=="number")return error.$metadata.httpStatusCode;if(typeof error.$response?.statusCode=="number")return error.$response.statusCode}function extractBody(error){let bodyText=pickBodyText(error);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,MAX_PROVIDER_ERROR_BODY_CHARS)}function pickBodyText(error){if(typeof error.body=="string")return error.body;if(isPlainNonEmptyObject(error.error))return safeJsonStringify(error.error);let responseBody=error.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function formatProviderError(norm,prefix){return norm.messageCarriesBody||norm.status===void 0||norm.body===void 0?prefix!==void 0&&norm.status!==void 0?`${prefix} (${norm.status}): ${norm.message}`:norm.message:prefix!==void 0?`${prefix} (${norm.status}): ${norm.body}`:`${norm.status}: ${norm.body}`}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${ownedSlice(text,0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}function headersToRecord(headers){let result={};for(let[key,value]of headers.entries())result[key]=value;return result}function providerHeadersToRecord(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}return merged.size>0?Object.fromEntries(merged.values()):void 0}function isProviderError(error){return!(error instanceof Error)||!("status"in error)||!("headers"in error)?!1:(error.status===void 0||typeof error.status=="number")&&(error.headers===void 0||error.headers instanceof Headers)}function isRetryableProviderError(error){let shouldRetry=error.headers?.get("x-should-retry");return shouldRetry==="true"?!0:shouldRetry==="false"?!1:error.status===void 0?!0:error.status===408||error.status===409||error.status===429||typeof error.status=="number"&&error.status>=500}function validateServerRetryDelayMs(delayMs,maxRetryDelayMs,providerErrorMessage){let maxDelayMs=maxRetryDelayMs??6e4;if(maxDelayMs>0&&delayMs>maxDelayMs)throw new Error(`Server requested ${Math.ceil(delayMs/1e3)}s retry delay (max: ${Math.ceil(maxDelayMs/1e3)}s). ${providerErrorMessage}`);return delayMs}function getRetryDelayMs(error,retryIndex,maxRetryDelayMs){let retryAfterMs=error.headers?.get("retry-after-ms");if(retryAfterMs){let value=Number.parseFloat(retryAfterMs);if(Number.isFinite(value))return validateServerRetryDelayMs(value,maxRetryDelayMs,error.message)}let retryAfter=error.headers?.get("retry-after");if(retryAfter){let seconds=Number.parseFloat(retryAfter),delayMs=Number.isNaN(seconds)?Date.parse(retryAfter)-Date.now():seconds*1e3;if(Number.isFinite(delayMs))return validateServerRetryDelayMs(delayMs,maxRetryDelayMs,error.message)}return Math.min(.5*2**retryIndex,8)*1e3*(1-Math.random()*.25)}function createAbortError(){let error=new Error("Request aborted");return error.name="AbortError",error}function abortableSleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(createAbortError());return}let onAbort=()=>{clearTimeout(timeout),reject(createAbortError())},timeout=setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},Math.max(0,ms));signal?.addEventListener("abort",onAbort,{once:!0})})}async function retryProviderRequest(request,options={}){let maxRetries=options.maxRetries??0,retriesRemaining=maxRetries;for(;;)try{return await request()}catch(error){if(options.signal?.aborted)throw createAbortError();if(retriesRemaining<=0||!isProviderError(error)||!isRetryableProviderError(error)||error.status!==void 0&&options.noRetryStatuses?.includes(error.status))throw error;let retryIndex=maxRetries-retriesRemaining;retriesRemaining--,await abortableSleep(getRetryDelayMs(error,retryIndex,options.maxRetryDelayMs),options.signal)}}function sanitizeSurrogates(text){return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}var import_p_retry=__toESM(require_p_retry(),1),import_google_auth_library=__toESM(require_src5(),1);var import_stream=__toESM(require_stream(),1),import_extension=__toESM(require_extension(),1),import_permessage_deflate=__toESM(require_permessage_deflate(),1),import_receiver=__toESM(require_receiver(),1),import_sender=__toESM(require_sender(),1),import_subprotocol=__toESM(require_subprotocol(),1),import_websocket=__toESM(require_websocket(),1),import_websocket_server=__toESM(require_websocket_server(),1);var BaseModule=class{};function formatMap(templateString,valueMap){let regex=/\{([^}]+)\}/g;return templateString.replace(regex,(match,key)=>{if(Object.prototype.hasOwnProperty.call(valueMap,key)){let value=valueMap[key];return value!=null?String(value):""}else throw new Error(`Key '${key}' not found in valueMap.`)})}function setValueByPath(data,keys,value){for(let i2=0;i2<keys.length-1;i2++){let key=keys[i2];if(key.endsWith("[]")){let keyName=key.slice(0,-2);if(!(keyName in data))if(Array.isArray(value))data[keyName]=Array.from({length:value.length},()=>({}));else throw new Error(`Value must be a list given an array path ${key}`);if(Array.isArray(data[keyName])){let arrayData=data[keyName];if(Array.isArray(value))for(let j=0;j<arrayData.length;j++){let entry=arrayData[j];setValueByPath(entry,keys.slice(i2+1),value[j])}else for(let d of arrayData)setValueByPath(d,keys.slice(i2+1),value)}return}else if(key.endsWith("[0]")){let keyName=key.slice(0,-3);keyName in data||(data[keyName]=[{}]);let arrayData=data[keyName];setValueByPath(arrayData[0],keys.slice(i2+1),value);return}(!data[key]||typeof data[key]!="object")&&(data[key]={}),data=data[key]}let keyToSet=keys[keys.length-1],existingData=data[keyToSet];if(existingData!==void 0){if(!value||typeof value=="object"&&Object.keys(value).length===0||value===existingData)return;if(typeof existingData=="object"&&typeof value=="object"&&existingData!==null&&value!==null)Object.assign(existingData,value);else throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`)}else keyToSet==="_self"&&typeof value=="object"&&value!==null&&!Array.isArray(value)?Object.assign(data,value):data[keyToSet]=value}function getValueByPath(data,keys,defaultValue=void 0){try{if(keys.length===1&&keys[0]==="_self")return data;for(let i2=0;i2<keys.length;i2++){if(typeof data!="object"||data===null)return defaultValue;let key=keys[i2];if(key.endsWith("[]")){let keyName=key.slice(0,-2);if(keyName in data){let arrayData=data[keyName];return Array.isArray(arrayData)?arrayData.map(d=>getValueByPath(d,keys.slice(i2+1),defaultValue)):defaultValue}else return defaultValue}else data=data[key]}return data}catch(error){if(error instanceof TypeError)return defaultValue;throw error}}function tBytes$1(fromBytes){if(typeof fromBytes!="string")throw new Error("fromImageBytes must be a string");return fromBytes}function generateVideosOperationFromMldev$1(fromObject){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);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response","generateVideoResponse"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromMldev$1(fromResponse)),toObject}function generateVideosOperationFromVertex$1(fromObject){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);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromVertex$1(fromResponse)),toObject}function generateVideosResponseFromMldev$1(fromObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["generatedSamples"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromMldev$1(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(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosResponseFromVertex$1(fromObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["videos"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromVertex$1(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(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generatedVideoFromMldev$1(fromObject){let toObject={},fromVideo=getValueByPath(fromObject,["video"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromMldev$1(fromVideo)),toObject}function generatedVideoFromVertex$1(fromObject){let toObject={},fromVideo=getValueByPath(fromObject,["_self"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromVertex$1(fromVideo)),toObject}function videoFromMldev$1(fromObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["encodedVideo"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes$1(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["encoding"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoFromVertex$1(fromObject){let toObject={},fromUri=getValueByPath(fromObject,["gcsUri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes$1(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}var Outcome;(function(Outcome2){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",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="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_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",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.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="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||(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"})(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_PEOPLE"})(ProminentPeople||(ProminentPeople={}));var HarmCategory;(function(HarmCategory2){HarmCategory2.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",HarmCategory2.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",HarmCategory2.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",HarmCategory2.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",HarmCategory2.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",HarmCategory2.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",HarmCategory2.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",HarmCategory2.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",HarmCategory2.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",HarmCategory2.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",HarmCategory2.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"})(HarmCategory||(HarmCategory={}));var HarmBlockMethod;(function(HarmBlockMethod2){HarmBlockMethod2.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",HarmBlockMethod2.SEVERITY="SEVERITY",HarmBlockMethod2.PROBABILITY="PROBABILITY"})(HarmBlockMethod||(HarmBlockMethod={}));var HarmBlockThreshold;(function(HarmBlockThreshold2){HarmBlockThreshold2.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",HarmBlockThreshold2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",HarmBlockThreshold2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",HarmBlockThreshold2.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",HarmBlockThreshold2.BLOCK_NONE="BLOCK_NONE",HarmBlockThreshold2.OFF="OFF"})(HarmBlockThreshold||(HarmBlockThreshold={}));var FunctionCallingConfigMode;(function(FunctionCallingConfigMode2){FunctionCallingConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",FunctionCallingConfigMode2.AUTO="AUTO",FunctionCallingConfigMode2.ANY="ANY",FunctionCallingConfigMode2.NONE="NONE",FunctionCallingConfigMode2.VALIDATED="VALIDATED"})(FunctionCallingConfigMode||(FunctionCallingConfigMode={}));var FinishReason;(function(FinishReason2){FinishReason2.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",FinishReason2.STOP="STOP",FinishReason2.MAX_TOKENS="MAX_TOKENS",FinishReason2.SAFETY="SAFETY",FinishReason2.RECITATION="RECITATION",FinishReason2.LANGUAGE="LANGUAGE",FinishReason2.OTHER="OTHER",FinishReason2.BLOCKLIST="BLOCKLIST",FinishReason2.PROHIBITED_CONTENT="PROHIBITED_CONTENT",FinishReason2.SPII="SPII",FinishReason2.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",FinishReason2.IMAGE_SAFETY="IMAGE_SAFETY",FinishReason2.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",FinishReason2.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",FinishReason2.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",FinishReason2.NO_IMAGE="NO_IMAGE",FinishReason2.IMAGE_RECITATION="IMAGE_RECITATION",FinishReason2.IMAGE_OTHER="IMAGE_OTHER"})(FinishReason||(FinishReason={}));var HarmProbability;(function(HarmProbability2){HarmProbability2.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",HarmProbability2.NEGLIGIBLE="NEGLIGIBLE",HarmProbability2.LOW="LOW",HarmProbability2.MEDIUM="MEDIUM",HarmProbability2.HIGH="HIGH"})(HarmProbability||(HarmProbability={}));var HarmSeverity;(function(HarmSeverity2){HarmSeverity2.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",HarmSeverity2.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",HarmSeverity2.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",HarmSeverity2.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",HarmSeverity2.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(HarmSeverity||(HarmSeverity={}));var UrlRetrievalStatus;(function(UrlRetrievalStatus2){UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(UrlRetrievalStatus||(UrlRetrievalStatus={}));var BlockedReason;(function(BlockedReason2){BlockedReason2.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",BlockedReason2.SAFETY="SAFETY",BlockedReason2.OTHER="OTHER",BlockedReason2.BLOCKLIST="BLOCKLIST",BlockedReason2.PROHIBITED_CONTENT="PROHIBITED_CONTENT",BlockedReason2.IMAGE_SAFETY="IMAGE_SAFETY",BlockedReason2.MODEL_ARMOR="MODEL_ARMOR",BlockedReason2.JAILBREAK="JAILBREAK"})(BlockedReason||(BlockedReason={}));var TrafficType;(function(TrafficType2){TrafficType2.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",TrafficType2.ON_DEMAND="ON_DEMAND",TrafficType2.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",TrafficType2.ON_DEMAND_FLEX="ON_DEMAND_FLEX",TrafficType2.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(TrafficType||(TrafficType={}));var MediaModality;(function(MediaModality2){MediaModality2.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",MediaModality2.TEXT="TEXT",MediaModality2.IMAGE="IMAGE",MediaModality2.VIDEO="VIDEO",MediaModality2.AUDIO="AUDIO",MediaModality2.DOCUMENT="DOCUMENT"})(MediaModality||(MediaModality={}));var ModelStage;(function(ModelStage2){ModelStage2.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",ModelStage2.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",ModelStage2.EXPERIMENTAL="EXPERIMENTAL",ModelStage2.PREVIEW="PREVIEW",ModelStage2.STABLE="STABLE",ModelStage2.LEGACY="LEGACY",ModelStage2.DEPRECATED="DEPRECATED",ModelStage2.RETIRED="RETIRED"})(ModelStage||(ModelStage={}));var MediaResolution;(function(MediaResolution2){MediaResolution2.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",MediaResolution2.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",MediaResolution2.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",MediaResolution2.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(MediaResolution||(MediaResolution={}));var Modality;(function(Modality2){Modality2.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",Modality2.TEXT="TEXT",Modality2.IMAGE="IMAGE",Modality2.AUDIO="AUDIO",Modality2.VIDEO="VIDEO"})(Modality||(Modality={}));var Delivery;(function(Delivery2){Delivery2.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",Delivery2.INLINE="INLINE",Delivery2.URI="URI"})(Delivery||(Delivery={}));var AspectRatio;(function(AspectRatio2){AspectRatio2.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",AspectRatio2.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",AspectRatio2.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",AspectRatio2.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",AspectRatio2.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",AspectRatio2.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",AspectRatio2.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",AspectRatio2.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",AspectRatio2.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",AspectRatio2.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",AspectRatio2.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",AspectRatio2.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",AspectRatio2.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",AspectRatio2.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",AspectRatio2.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"})(AspectRatio||(AspectRatio={}));var ImageSize;(function(ImageSize2){ImageSize2.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",ImageSize2.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",ImageSize2.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",ImageSize2.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",ImageSize2.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"})(ImageSize||(ImageSize={}));var TuningMode;(function(TuningMode2){TuningMode2.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",TuningMode2.TUNING_MODE_FULL="TUNING_MODE_FULL",TuningMode2.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(TuningMode||(TuningMode={}));var AdapterSize;(function(AdapterSize2){AdapterSize2.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",AdapterSize2.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",AdapterSize2.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",AdapterSize2.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",AdapterSize2.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",AdapterSize2.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",AdapterSize2.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(AdapterSize||(AdapterSize={}));var ResponseParseType;(function(ResponseParseType2){ResponseParseType2.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",ResponseParseType2.IDENTITY="IDENTITY",ResponseParseType2.REGEX_EXTRACT="REGEX_EXTRACT"})(ResponseParseType||(ResponseParseType={}));var MatchOperation;(function(MatchOperation2){MatchOperation2.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",MatchOperation2.REGEX_CONTAINS="REGEX_CONTAINS",MatchOperation2.PARTIAL_MATCH="PARTIAL_MATCH",MatchOperation2.EXACT_MATCH="EXACT_MATCH"})(MatchOperation||(MatchOperation={}));var ReinforcementTuningThinkingLevel;(function(ReinforcementTuningThinkingLevel2){ReinforcementTuningThinkingLevel2.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",ReinforcementTuningThinkingLevel2.MINIMAL="MINIMAL",ReinforcementTuningThinkingLevel2.HIGH="HIGH"})(ReinforcementTuningThinkingLevel||(ReinforcementTuningThinkingLevel={}));var JobState;(function(JobState2){JobState2.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",JobState2.JOB_STATE_QUEUED="JOB_STATE_QUEUED",JobState2.JOB_STATE_PENDING="JOB_STATE_PENDING",JobState2.JOB_STATE_RUNNING="JOB_STATE_RUNNING",JobState2.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",JobState2.JOB_STATE_FAILED="JOB_STATE_FAILED",JobState2.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",JobState2.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",JobState2.JOB_STATE_PAUSED="JOB_STATE_PAUSED",JobState2.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",JobState2.JOB_STATE_UPDATING="JOB_STATE_UPDATING",JobState2.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(JobState||(JobState={}));var TuningJobState;(function(TuningJobState2){TuningJobState2.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",TuningJobState2.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",TuningJobState2.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",TuningJobState2.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",TuningJobState2.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",TuningJobState2.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(TuningJobState||(TuningJobState={}));var AggregationMetric;(function(AggregationMetric2){AggregationMetric2.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",AggregationMetric2.AVERAGE="AVERAGE",AggregationMetric2.MODE="MODE",AggregationMetric2.STANDARD_DEVIATION="STANDARD_DEVIATION",AggregationMetric2.VARIANCE="VARIANCE",AggregationMetric2.MINIMUM="MINIMUM",AggregationMetric2.MAXIMUM="MAXIMUM",AggregationMetric2.MEDIAN="MEDIAN",AggregationMetric2.PERCENTILE_P90="PERCENTILE_P90",AggregationMetric2.PERCENTILE_P95="PERCENTILE_P95",AggregationMetric2.PERCENTILE_P99="PERCENTILE_P99"})(AggregationMetric||(AggregationMetric={}));var PairwiseChoice;(function(PairwiseChoice2){PairwiseChoice2.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",PairwiseChoice2.BASELINE="BASELINE",PairwiseChoice2.CANDIDATE="CANDIDATE",PairwiseChoice2.TIE="TIE"})(PairwiseChoice||(PairwiseChoice={}));var VideoOrientation;(function(VideoOrientation2){VideoOrientation2.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",VideoOrientation2.LANDSCAPE="LANDSCAPE",VideoOrientation2.PORTRAIT="PORTRAIT"})(VideoOrientation||(VideoOrientation={}));var TuningSpeed;(function(TuningSpeed2){TuningSpeed2.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",TuningSpeed2.REGULAR="REGULAR",TuningSpeed2.FAST="FAST"})(TuningSpeed||(TuningSpeed={}));var TuningTask;(function(TuningTask2){TuningTask2.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",TuningTask2.TUNING_TASK_I2V="TUNING_TASK_I2V",TuningTask2.TUNING_TASK_T2V="TUNING_TASK_T2V",TuningTask2.TUNING_TASK_R2V="TUNING_TASK_R2V"})(TuningTask||(TuningTask={}));var DocumentState;(function(DocumentState2){DocumentState2.STATE_UNSPECIFIED="STATE_UNSPECIFIED",DocumentState2.STATE_PENDING="STATE_PENDING",DocumentState2.STATE_ACTIVE="STATE_ACTIVE",DocumentState2.STATE_FAILED="STATE_FAILED"})(DocumentState||(DocumentState={}));var ServiceTier;(function(ServiceTier2){ServiceTier2.UNSPECIFIED="unspecified",ServiceTier2.FLEX="flex",ServiceTier2.STANDARD="standard",ServiceTier2.PRIORITY="priority"})(ServiceTier||(ServiceTier={}));var MediaProcessing;(function(MediaProcessing2){MediaProcessing2.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",MediaProcessing2.STATIC="STATIC",MediaProcessing2.AGENTIC="AGENTIC"})(MediaProcessing||(MediaProcessing={}));var PartMediaResolutionLevel;(function(PartMediaResolutionLevel2){PartMediaResolutionLevel2.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",PartMediaResolutionLevel2.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",PartMediaResolutionLevel2.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",PartMediaResolutionLevel2.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",PartMediaResolutionLevel2.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(PartMediaResolutionLevel||(PartMediaResolutionLevel={}));var ToolType;(function(ToolType2){ToolType2.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",ToolType2.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",ToolType2.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",ToolType2.URL_CONTEXT="URL_CONTEXT",ToolType2.GOOGLE_MAPS="GOOGLE_MAPS",ToolType2.FILE_SEARCH="FILE_SEARCH",ToolType2.MEDIA_PROCESSING="MEDIA_PROCESSING"})(ToolType||(ToolType={}));var ResourceScope;(function(ResourceScope2){ResourceScope2.COLLECTION="COLLECTION"})(ResourceScope||(ResourceScope={}));var FeatureSelectionPreference;(function(FeatureSelectionPreference2){FeatureSelectionPreference2.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",FeatureSelectionPreference2.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",FeatureSelectionPreference2.BALANCED="BALANCED",FeatureSelectionPreference2.PRIORITIZE_COST="PRIORITIZE_COST"})(FeatureSelectionPreference||(FeatureSelectionPreference={}));var EmbeddingApiType;(function(EmbeddingApiType2){EmbeddingApiType2.PREDICT="PREDICT",EmbeddingApiType2.EMBED_CONTENT="EMBED_CONTENT"})(EmbeddingApiType||(EmbeddingApiType={}));var SafetyFilterLevel;(function(SafetyFilterLevel2){SafetyFilterLevel2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",SafetyFilterLevel2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",SafetyFilterLevel2.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",SafetyFilterLevel2.BLOCK_NONE="BLOCK_NONE"})(SafetyFilterLevel||(SafetyFilterLevel={}));var ImagePromptLanguage;(function(ImagePromptLanguage2){ImagePromptLanguage2.auto="auto",ImagePromptLanguage2.en="en",ImagePromptLanguage2.ja="ja",ImagePromptLanguage2.ko="ko",ImagePromptLanguage2.hi="hi",ImagePromptLanguage2.zh="zh",ImagePromptLanguage2.pt="pt",ImagePromptLanguage2.es="es"})(ImagePromptLanguage||(ImagePromptLanguage={}));var MaskReferenceMode;(function(MaskReferenceMode2){MaskReferenceMode2.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",MaskReferenceMode2.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",MaskReferenceMode2.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",MaskReferenceMode2.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",MaskReferenceMode2.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(MaskReferenceMode||(MaskReferenceMode={}));var ControlReferenceType;(function(ControlReferenceType2){ControlReferenceType2.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",ControlReferenceType2.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",ControlReferenceType2.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",ControlReferenceType2.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(ControlReferenceType||(ControlReferenceType={}));var SubjectReferenceType;(function(SubjectReferenceType2){SubjectReferenceType2.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",SubjectReferenceType2.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",SubjectReferenceType2.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",SubjectReferenceType2.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(SubjectReferenceType||(SubjectReferenceType={}));var EditMode;(function(EditMode2){EditMode2.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",EditMode2.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",EditMode2.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",EditMode2.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",EditMode2.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",EditMode2.EDIT_MODE_STYLE="EDIT_MODE_STYLE",EditMode2.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",EditMode2.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(EditMode||(EditMode={}));var SegmentMode;(function(SegmentMode2){SegmentMode2.FOREGROUND="FOREGROUND",SegmentMode2.BACKGROUND="BACKGROUND",SegmentMode2.PROMPT="PROMPT",SegmentMode2.SEMANTIC="SEMANTIC",SegmentMode2.INTERACTIVE="INTERACTIVE"})(SegmentMode||(SegmentMode={}));var VideoGenerationReferenceType;(function(VideoGenerationReferenceType2){VideoGenerationReferenceType2.ASSET="ASSET",VideoGenerationReferenceType2.STYLE="STYLE"})(VideoGenerationReferenceType||(VideoGenerationReferenceType={}));var VideoGenerationMaskMode;(function(VideoGenerationMaskMode2){VideoGenerationMaskMode2.INSERT="INSERT",VideoGenerationMaskMode2.REMOVE="REMOVE",VideoGenerationMaskMode2.REMOVE_STATIC="REMOVE_STATIC",VideoGenerationMaskMode2.OUTPAINT="OUTPAINT"})(VideoGenerationMaskMode||(VideoGenerationMaskMode={}));var VideoCompressionQuality;(function(VideoCompressionQuality2){VideoCompressionQuality2.OPTIMIZED="OPTIMIZED",VideoCompressionQuality2.LOSSLESS="LOSSLESS"})(VideoCompressionQuality||(VideoCompressionQuality={}));var ImageResizeMode;(function(ImageResizeMode2){ImageResizeMode2.CROP="CROP",ImageResizeMode2.PAD="PAD"})(ImageResizeMode||(ImageResizeMode={}));var TuningMethod;(function(TuningMethod2){TuningMethod2.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",TuningMethod2.PREFERENCE_TUNING="PREFERENCE_TUNING",TuningMethod2.DISTILLATION="DISTILLATION",TuningMethod2.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(TuningMethod||(TuningMethod={}));var FileState;(function(FileState2){FileState2.STATE_UNSPECIFIED="STATE_UNSPECIFIED",FileState2.PROCESSING="PROCESSING",FileState2.ACTIVE="ACTIVE",FileState2.FAILED="FAILED"})(FileState||(FileState={}));var FileSource;(function(FileSource2){FileSource2.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",FileSource2.UPLOADED="UPLOADED",FileSource2.GENERATED="GENERATED",FileSource2.REGISTERED="REGISTERED"})(FileSource||(FileSource={}));var TurnCompleteReason;(function(TurnCompleteReason2){TurnCompleteReason2.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",TurnCompleteReason2.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",TurnCompleteReason2.RESPONSE_REJECTED="RESPONSE_REJECTED",TurnCompleteReason2.NEED_MORE_INPUT="NEED_MORE_INPUT",TurnCompleteReason2.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",TurnCompleteReason2.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",TurnCompleteReason2.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",TurnCompleteReason2.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",TurnCompleteReason2.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",TurnCompleteReason2.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",TurnCompleteReason2.INPUT_OTHER="INPUT_OTHER",TurnCompleteReason2.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",TurnCompleteReason2.BLOCKLIST="BLOCKLIST",TurnCompleteReason2.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",TurnCompleteReason2.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",TurnCompleteReason2.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",TurnCompleteReason2.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",TurnCompleteReason2.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",TurnCompleteReason2.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",TurnCompleteReason2.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",TurnCompleteReason2.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",TurnCompleteReason2.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",TurnCompleteReason2.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",TurnCompleteReason2.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",TurnCompleteReason2.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",TurnCompleteReason2.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",TurnCompleteReason2.GENERATED_OTHER="GENERATED_OTHER",TurnCompleteReason2.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(TurnCompleteReason||(TurnCompleteReason={}));var InteractionStatus;(function(InteractionStatus2){InteractionStatus2.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",InteractionStatus2.IN_PROGRESS="IN_PROGRESS",InteractionStatus2.REQUIRES_ACTION="REQUIRES_ACTION",InteractionStatus2.IDLE="IDLE"})(InteractionStatus||(InteractionStatus={}));var VadSignalType;(function(VadSignalType2){VadSignalType2.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",VadSignalType2.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",VadSignalType2.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(VadSignalType||(VadSignalType={}));var VoiceActivityType;(function(VoiceActivityType2){VoiceActivityType2.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",VoiceActivityType2.ACTIVITY_START="ACTIVITY_START",VoiceActivityType2.ACTIVITY_END="ACTIVITY_END"})(VoiceActivityType||(VoiceActivityType={}));var StartSensitivity;(function(StartSensitivity2){StartSensitivity2.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",StartSensitivity2.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",StartSensitivity2.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(StartSensitivity||(StartSensitivity={}));var EndSensitivity;(function(EndSensitivity2){EndSensitivity2.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",EndSensitivity2.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",EndSensitivity2.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(EndSensitivity||(EndSensitivity={}));var ActivityHandling;(function(ActivityHandling2){ActivityHandling2.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",ActivityHandling2.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",ActivityHandling2.NO_INTERRUPTION="NO_INTERRUPTION"})(ActivityHandling||(ActivityHandling={}));var TurnCoverage;(function(TurnCoverage2){TurnCoverage2.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",TurnCoverage2.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 AudioTranscriptionConfigMode;(function(AudioTranscriptionConfigMode2){AudioTranscriptionConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",AudioTranscriptionConfigMode2.VERBATIM="VERBATIM",AudioTranscriptionConfigMode2.SMART="SMART"})(AudioTranscriptionConfigMode||(AudioTranscriptionConfigMode={}));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="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.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.STOP="STOP",LiveMusicPlaybackControl2.RESET_CONTEXT="RESET_CONTEXT"})(LiveMusicPlaybackControl||(LiveMusicPlaybackControl={}));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)===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(`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 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+=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:_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(){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)===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?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!==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}};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("invalid 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 tPart(origin){if(origin==null)throw new Error("PartUnion is required");if(typeof origin=="object")return origin;if(typeof origin=="string")return{text:origin};throw new Error(`Unsupported part type: ${typeof origin}`)}function tParts(origin){if(origin==null||Array.isArray(origin)&&origin.length===0)throw new Error("PartListUnion is required");return Array.isArray(origin)?origin.map(item=>tPart(item)):[tPart(origin)]}function _isContent(origin){return origin!=null&&typeof origin=="object"&&"parts"in origin&&Array.isArray(origin.parts)}function _isFunctionCallPart(origin){return origin!=null&&typeof origin=="object"&&"functionCall"in origin}function _isFunctionResponsePart(origin){return origin!=null&&typeof origin=="object"&&"functionResponse"in origin}function tContent(origin){if(origin==null)throw new Error("ContentUnion is required");return _isContent(origin)?origin:{role:"user",parts:tParts(origin)}}function tContentsForEmbed(apiClient,origin){if(!origin)return[];if(apiClient.isVertexAI()&&Array.isArray(origin))return origin.flatMap(item=>{let content=tContent(item);return content.parts&&content.parts.length>0&&content.parts[0].text!==void 0?[content.parts[0].text]:[]});if(apiClient.isVertexAI()){let content=tContent(origin);return content.parts&&content.parts.length>0&&content.parts[0].text!==void 0?[content.parts[0].text]:[]}return Array.isArray(origin)?origin.map(item=>tContent(item)):[tContent(origin)]}function tContents(origin){if(origin==null||Array.isArray(origin)&&origin.length===0)throw new Error("contents are required");if(!Array.isArray(origin)){if(_isFunctionCallPart(origin)||_isFunctionResponsePart(origin))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[tContent(origin)]}let result=[],accumulatedParts=[],isContentArray=_isContent(origin[0]);for(let item of origin){let isContent=_isContent(item);if(isContent!=isContentArray)throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(isContent)result.push(item);else{if(_isFunctionCallPart(item)||_isFunctionResponsePart(item))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");accumulatedParts.push(item)}}return isContentArray||result.push({role:"user",parts:tParts(accumulatedParts)}),result}function flattenTypeArrayToAnyOf(typeList,resultingSchema){typeList.includes("null")&&(resultingSchema.nullable=!0);let listWithoutNull=typeList.filter(type=>type!=="null");if(listWithoutNull.length===1)resultingSchema.type=Object.values(Type).includes(listWithoutNull[0].toUpperCase())?listWithoutNull[0].toUpperCase():Type.TYPE_UNSPECIFIED;else{resultingSchema.anyOf=[];for(let i2 of listWithoutNull)resultingSchema.anyOf.push({type:Object.values(Type).includes(i2.toUpperCase())?i2.toUpperCase():Type.TYPE_UNSPECIFIED})}}function processJsonSchema(_jsonSchema){let genAISchema={},schemaFieldNames=["items"],listSchemaFieldNames=["anyOf"],dictSchemaFieldNames=["properties"];if(_jsonSchema.type&&_jsonSchema.anyOf)throw new Error("type and anyOf cannot be both populated.");let incomingAnyOf=_jsonSchema.anyOf;incomingAnyOf!=null&&incomingAnyOf.length==2&&(incomingAnyOf[0].type==="null"?(genAISchema.nullable=!0,_jsonSchema=incomingAnyOf[1]):incomingAnyOf[1].type==="null"&&(genAISchema.nullable=!0,_jsonSchema=incomingAnyOf[0])),_jsonSchema.type instanceof Array&&flattenTypeArrayToAnyOf(_jsonSchema.type,genAISchema);for(let[fieldName,fieldValue]of Object.entries(_jsonSchema))if(fieldValue!=null)if(fieldName=="type"){if(fieldValue==="null")throw new Error("type: null can not be the only possible type for the field.");if(fieldValue instanceof Array)continue;genAISchema.type=Object.values(Type).includes(fieldValue.toUpperCase())?fieldValue.toUpperCase():Type.TYPE_UNSPECIFIED}else if(schemaFieldNames.includes(fieldName))genAISchema[fieldName]=processJsonSchema(fieldValue);else if(listSchemaFieldNames.includes(fieldName)){let listSchemaFieldValue=[];for(let item of fieldValue){if(item.type=="null"){genAISchema.nullable=!0;continue}listSchemaFieldValue.push(processJsonSchema(item))}genAISchema[fieldName]=listSchemaFieldValue}else if(dictSchemaFieldNames.includes(fieldName)){let dictSchemaFieldValue={};for(let[key,value]of Object.entries(fieldValue))dictSchemaFieldValue[key]=processJsonSchema(value);genAISchema[fieldName]=dictSchemaFieldValue}else{if(fieldName==="additionalProperties")continue;genAISchema[fieldName]=fieldValue}return genAISchema}function tSchema(schema){return processJsonSchema(schema)}function tSpeechConfig(speechConfig){if(typeof speechConfig=="object")return speechConfig;if(typeof speechConfig=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:speechConfig}}};throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`)}function tTool(tool){if(tool.functionDeclarations)for(let functionDeclaration of tool.functionDeclarations)functionDeclaration.parameters&&(Object.keys(functionDeclaration.parameters).includes("$schema")?functionDeclaration.parametersJsonSchema||(functionDeclaration.parametersJsonSchema=functionDeclaration.parameters,delete functionDeclaration.parameters):functionDeclaration.parameters=processJsonSchema(functionDeclaration.parameters)),functionDeclaration.response&&(Object.keys(functionDeclaration.response).includes("$schema")?functionDeclaration.responseJsonSchema||(functionDeclaration.responseJsonSchema=functionDeclaration.response,delete functionDeclaration.response):functionDeclaration.response=processJsonSchema(functionDeclaration.response));return tool}function tTools(tools){if(tools==null)throw new Error("tools is required");if(!Array.isArray(tools))throw new Error("tools is required and must be an array of Tools");let result=[];for(let tool of tools)result.push(tool);return result}function resourceName(client,resourceName2,resourcePrefix,splitsAfterPrefix=1){let shouldAppendPrefix=!resourceName2.startsWith(`${resourcePrefix}/`)&&resourceName2.split("/").length===splitsAfterPrefix;return client.isVertexAI()?resourceName2.startsWith("projects/")?resourceName2:resourceName2.startsWith("locations/")?`projects/${client.getProject()}/${resourceName2}`:resourceName2.startsWith(`${resourcePrefix}/`)?`projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName2}`:shouldAppendPrefix?`projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName2}`:resourceName2:shouldAppendPrefix?`${resourcePrefix}/${resourceName2}`:resourceName2}function tCachedContentName(apiClient,name){if(typeof name!="string")throw new Error("name must be a string");return resourceName(apiClient,name,"cachedContents")}function tBytes(fromImageBytes){return tBytes$1(fromImageBytes)}function tModelsUrl(apiClient,baseModels){let res;return apiClient.isVertexAI()?res=baseModels?"publishers/google/models":"models":res=baseModels?"models":"tunedModels",res}function tExtractModels(response){for(let key of["models","tunedModels","publisherModels"])if(hasField(response,key))return response[key];return[]}function hasField(data,fieldName){return data!==null&&typeof data=="object"&&fieldName in data}function mcpToGeminiTool(mcpTool,config={}){let mcpToolSchema=mcpTool,functionDeclaration={name:mcpToolSchema.name,description:mcpToolSchema.description,parametersJsonSchema:mcpToolSchema.inputSchema};return mcpToolSchema.outputSchema&&(functionDeclaration.responseJsonSchema=mcpToolSchema.outputSchema),config.behavior&&(functionDeclaration.behavior=config.behavior),{functionDeclarations:[functionDeclaration]}}function mcpToolsToGeminiTool(mcpTools,config={}){let functionDeclarations=[],toolNames=new Set;for(let mcpTool of mcpTools){let mcpToolName=mcpTool.name;if(toolNames.has(mcpToolName))throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);toolNames.add(mcpToolName);let geminiTool=mcpToGeminiTool(mcpTool,config);geminiTool.functionDeclarations&&functionDeclarations.push(...geminiTool.functionDeclarations)}return{functionDeclarations}}function tIsVertexEmbedContentModel(model){return model.includes("gemini")&&model!=="gemini-embedding-001"||model.includes("maas")}var PagedItem;(function(PagedItem2){PagedItem2.PAGED_ITEM_BATCH_JOBS="batchJobs",PagedItem2.PAGED_ITEM_MODELS="models",PagedItem2.PAGED_ITEM_TUNING_JOBS="tuningJobs",PagedItem2.PAGED_ITEM_FILES="files",PagedItem2.PAGED_ITEM_CACHED_CONTENTS="cachedContents",PagedItem2.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",PagedItem2.PAGED_ITEM_DOCUMENTS="documents",PagedItem2.PAGED_ITEM_SKILLS="skills"})(PagedItem||(PagedItem={}));var Pager=class{constructor(name,request,response,params){this.pageInternal=[],this.paramsInternal={},this.requestInternal=request,this.init(name,response,params)}init(name,response,params){var _a2,_b;this.nameInternal=name,this.pageInternal=response[this.nameInternal]||[],this.sdkHttpResponseInternal=response?.sdkHttpResponse,this.idxInternal=0;let requestParams={config:{}};!params||Object.keys(params).length===0?requestParams={config:{}}:typeof params=="object"?requestParams=Object.assign({},params):requestParams=params,requestParams.config&&(requestParams.config.pageToken=response.nextPageToken),this.paramsInternal=requestParams,this.pageInternalSize=(_b=(_a2=requestParams.config)===null||_a2===void 0?void 0:_a2.pageSize)!==null&&_b!==void 0?_b:this.pageInternal.length}initNextPage(response){this.init(this.nameInternal,response,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(index){return this.pageInternal[index]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};let item=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:item,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");let response=await this.requestInternal(this.params);return this.initNextPage(response),this.page}hasNextPage(){var _a2;return((_a2=this.params.config)===null||_a2===void 0?void 0:_a2.pageToken)!==void 0}};function __values(o){var s2=typeof Symbol=="function"&&Symbol.iterator,m2=s2&&o[s2],i2=0;if(m2)return m2.call(o);if(o&&typeof o.length=="number")return{next:function(){return o&&i2>=o.length&&(o=void 0),{value:o&&o[i2++],done:!o}}};throw new TypeError(s2?"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||[]),i2,q=[];return i2=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",awaitReturn),i2[Symbol.asyncIterator]=function(){return this},i2;function awaitReturn(f3){return function(v){return Promise.resolve(v).then(f3,reject)}}function verb(n,f3){g[n]&&(i2[n]=function(v){return new Promise(function(a,b){q.push([n,v,a,b])>1||resume(n,v)})},f3&&(i2[n]=f3(i2[n])))}function resume(n,v){try{step(g[n](v))}catch(e2){settle(q[0][3],e2)}}function step(r2){r2.value instanceof __await?Promise.resolve(r2.value.v).then(fulfill,reject):settle(q[0][2],r2)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f3,v){f3(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 m2=o[Symbol.asyncIterator],i2;return m2?m2.call(o):(o=typeof __values=="function"?__values(o):o[Symbol.iterator](),i2={},verb("next"),verb("throw"),verb("return"),i2[Symbol.asyncIterator]=function(){return this},i2);function verb(n){i2[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 authConfigToMldev$1(fromObject,_rootObject){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 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 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 Platform mode, not in Gemini Developer API mode.");return toObject}function blobToMldev$1(fromObject,_rootObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function candidateFromMldev(fromObject,rootObject){let toObject={},fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&setValueByPath(toObject,["content"],fromContent);let fromCitationMetadata=getValueByPath(fromObject,["citationMetadata"]);fromCitationMetadata!=null&&setValueByPath(toObject,["citationMetadata"],citationMetadataFromMldev(fromCitationMetadata));let fromTokenCount=getValueByPath(fromObject,["tokenCount"]);fromTokenCount!=null&&setValueByPath(toObject,["tokenCount"],fromTokenCount);let fromFinishReason=getValueByPath(fromObject,["finishReason"]);fromFinishReason!=null&&setValueByPath(toObject,["finishReason"],fromFinishReason);let fromGroundingMetadata=getValueByPath(fromObject,["groundingMetadata"]);fromGroundingMetadata!=null&&setValueByPath(toObject,["groundingMetadata"],fromGroundingMetadata);let fromAvgLogprobs=getValueByPath(fromObject,["avgLogprobs"]);fromAvgLogprobs!=null&&setValueByPath(toObject,["avgLogprobs"],fromAvgLogprobs);let fromIndex=getValueByPath(fromObject,["index"]);fromIndex!=null&&setValueByPath(toObject,["index"],fromIndex);let fromLogprobsResult=getValueByPath(fromObject,["logprobsResult"]);fromLogprobsResult!=null&&setValueByPath(toObject,["logprobsResult"],fromLogprobsResult);let fromSafetyRatings=getValueByPath(fromObject,["safetyRatings"]);if(fromSafetyRatings!=null){let transformedList=fromSafetyRatings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["safetyRatings"],transformedList)}let fromUrlContextMetadata=getValueByPath(fromObject,["urlContextMetadata"]);return fromUrlContextMetadata!=null&&setValueByPath(toObject,["urlContextMetadata"],fromUrlContextMetadata),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){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){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(fromObject,_rootObject){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!=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);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(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(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(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"]);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 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!=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(item))),setValueByPath(parentObject,["tools"],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(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,["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)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&countTokensConfigToVertex(fromConfig,toObject),toObject}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!=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){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(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(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,["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,["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"],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(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(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 fromEditMode=getValueByPath(fromObject,["editMode"]);parentObject!==void 0&&fromEditMode!=null&&setValueByPath(parentObject,["parameters","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,["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&&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(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(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 Enterprise 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){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!=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!==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","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==="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(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_CONTENT"){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,["audioTrackExtraction"]);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(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!==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==="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(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);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(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!=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.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),toObject}function fileDataToMldev$1(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),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 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(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),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);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(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(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);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,["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 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)&&(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"]);if(parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToMldev(fromToolConfig)),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.");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,["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 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,["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.");return 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,["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(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,["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(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(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(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!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex(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(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);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);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 only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromModelArmorConfig=getValueByPath(fromObject,["modelArmorConfig"]);return parentObject!==void 0&&fromModelArmorConfig!=null&&setValueByPath(parentObject,["modelArmorConfig"],fromModelArmorConfig),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.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));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){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,["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(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,["candidates"]);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(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){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!=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,["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"],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(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(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!==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","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,["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(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 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,["seed"])!==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);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!=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(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"],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 in 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){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,["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(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,["pubsubTopic"]);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"],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!=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"]);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(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(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(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!=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,["image"]);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){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(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;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(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,["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!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToMldev(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);return parentObject!==void 0&&fromVideo!=null&&setValueByPath(parentObject,["instances[0]","video"],videoToMldev(fromVideo)),toObject}function generateVideosSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToVertex(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);return parentObject!==void 0&&fromVideo!=null&&setValueByPath(parentObject,["instances[0]","video"],videoToVertex(fromVideo)),toObject}function generatedImageFromVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["_self"]);fromImage!=null&&setValueByPath(toObject,["image"],imageFromVertex(fromImage));let fromRaiFilteredReason=getValueByPath(fromObject,["raiFilteredReason"]);fromRaiFilteredReason!=null&&setValueByPath(toObject,["raiFilteredReason"],fromRaiFilteredReason);let fromSafetyAttributes=getValueByPath(fromObject,["_self"]);fromSafetyAttributes!=null&&setValueByPath(toObject,["safetyAttributes"],safetyAttributesFromVertex(fromSafetyAttributes));let fromEnhancedPrompt=getValueByPath(fromObject,["prompt"]);return fromEnhancedPrompt!=null&&setValueByPath(toObject,["enhancedPrompt"],fromEnhancedPrompt),toObject}function generatedImageMaskFromVertex(fromObject,rootObject){let toObject={},fromMask=getValueByPath(fromObject,["_self"]);fromMask!=null&&setValueByPath(toObject,["mask"],imageFromVertex(fromMask));let fromLabels=getValueByPath(fromObject,["labels"]);if(fromLabels!=null){let transformedList=fromLabels;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["labels"],transformedList)}return toObject}function generatedVideoFromMldev(fromObject,rootObject){let toObject={},fromVideo=getValueByPath(fromObject,["video"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromMldev(fromVideo)),toObject}function generatedVideoFromVertex(fromObject,rootObject){let toObject={},fromVideo=getValueByPath(fromObject,["_self"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromVertex(fromVideo)),toObject}function generationConfigToVertex(fromObject,rootObject){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,["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,["candidateCount"],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);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(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!=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&&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(fromSpeechConfig));let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromTemperature=getValueByPath(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(fromObject,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function getModelParametersToMldev(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function getModelParametersToVertex(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function googleMapsToMldev$1(fromObject,rootObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$1(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$1(fromObject,_rootObject){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&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function imageConfigToMldev(fromObject,_rootObject){let toObject={},fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);fromAspectRatio!=null&&setValueByPath(toObject,["aspectRatio"],fromAspectRatio);let fromImageSize=getValueByPath(fromObject,["imageSize"]);if(fromImageSize!=null&&setValueByPath(toObject,["imageSize"],fromImageSize),getValueByPath(fromObject,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function imageConfigToVertex(fromObject,_rootObject){let toObject={},fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);fromAspectRatio!=null&&setValueByPath(toObject,["aspectRatio"],fromAspectRatio);let fromImageSize=getValueByPath(fromObject,["imageSize"]);fromImageSize!=null&&setValueByPath(toObject,["imageSize"],fromImageSize);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);fromPersonGeneration!=null&&setValueByPath(toObject,["personGeneration"],fromPersonGeneration);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);fromOutputMimeType!=null&&setValueByPath(toObject,["imageOutputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);fromOutputCompressionQuality!=null&&setValueByPath(toObject,["imageOutputOptions","compressionQuality"],fromOutputCompressionQuality);let fromImageOutputOptions=getValueByPath(fromObject,["imageOutputOptions"]);fromImageOutputOptions!=null&&setValueByPath(toObject,["imageOutputOptions"],fromImageOutputOptions);let fromProminentPeople=getValueByPath(fromObject,["prominentPeople"]);return fromProminentPeople!=null&&setValueByPath(toObject,["prominentPeople"],fromProminentPeople),toObject}function imageFromVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromImageBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromImageBytes!=null&&setValueByPath(toObject,["imageBytes"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function imageToMldev(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 Developer API mode.");let fromImageBytes=getValueByPath(fromObject,["imageBytes"]);fromImageBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function imageToVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromImageBytes=getValueByPath(fromObject,["imageBytes"]);fromImageBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function listModelsConfigToMldev(apiClient,fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter);let fromQueryBase=getValueByPath(fromObject,["queryBase"]);return parentObject!==void 0&&fromQueryBase!=null&&setValueByPath(parentObject,["_url","models_url"],tModelsUrl(apiClient,fromQueryBase)),toObject}function listModelsConfigToVertex(apiClient,fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter);let fromQueryBase=getValueByPath(fromObject,["queryBase"]);return parentObject!==void 0&&fromQueryBase!=null&&setValueByPath(parentObject,["_url","models_url"],tModelsUrl(apiClient,fromQueryBase)),toObject}function listModelsParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listModelsConfigToMldev(apiClient,fromConfig,toObject),toObject}function listModelsParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listModelsConfigToVertex(apiClient,fromConfig,toObject),toObject}function listModelsResponseFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromModels=getValueByPath(fromObject,["_self"]);if(fromModels!=null){let transformedList=tExtractModels(fromModels);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>modelFromMldev(item))),setValueByPath(toObject,["models"],transformedList)}return toObject}function listModelsResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromModels=getValueByPath(fromObject,["_self"]);if(fromModels!=null){let transformedList=tExtractModels(fromModels);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>modelFromVertex(item))),setValueByPath(toObject,["models"],transformedList)}return toObject}function maskReferenceConfigToVertex(fromObject,_rootObject){let toObject={},fromMaskMode=getValueByPath(fromObject,["maskMode"]);fromMaskMode!=null&&setValueByPath(toObject,["maskMode"],fromMaskMode);let fromSegmentationClasses=getValueByPath(fromObject,["segmentationClasses"]);fromSegmentationClasses!=null&&setValueByPath(toObject,["maskClasses"],fromSegmentationClasses);let fromMaskDilation=getValueByPath(fromObject,["maskDilation"]);return fromMaskDilation!=null&&setValueByPath(toObject,["dilation"],fromMaskDilation),toObject}function mcpServerToVertex(fromObject,_rootObject){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 API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function modelFromMldev(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromVersion=getValueByPath(fromObject,["version"]);fromVersion!=null&&setValueByPath(toObject,["version"],fromVersion);let fromTunedModelInfo=getValueByPath(fromObject,["_self"]);fromTunedModelInfo!=null&&setValueByPath(toObject,["tunedModelInfo"],tunedModelInfoFromMldev(fromTunedModelInfo));let fromInputTokenLimit=getValueByPath(fromObject,["inputTokenLimit"]);fromInputTokenLimit!=null&&setValueByPath(toObject,["inputTokenLimit"],fromInputTokenLimit);let fromOutputTokenLimit=getValueByPath(fromObject,["outputTokenLimit"]);fromOutputTokenLimit!=null&&setValueByPath(toObject,["outputTokenLimit"],fromOutputTokenLimit);let fromSupportedActions=getValueByPath(fromObject,["supportedGenerationMethods"]);fromSupportedActions!=null&&setValueByPath(toObject,["supportedActions"],fromSupportedActions);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromMaxTemperature=getValueByPath(fromObject,["maxTemperature"]);fromMaxTemperature!=null&&setValueByPath(toObject,["maxTemperature"],fromMaxTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromThinking=getValueByPath(fromObject,["thinking"]);return fromThinking!=null&&setValueByPath(toObject,["thinking"],fromThinking),toObject}function modelFromVertex(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromVersion=getValueByPath(fromObject,["versionId"]);fromVersion!=null&&setValueByPath(toObject,["version"],fromVersion);let fromEndpoints=getValueByPath(fromObject,["deployedModels"]);if(fromEndpoints!=null){let transformedList=fromEndpoints;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>endpointFromVertex(item))),setValueByPath(toObject,["endpoints"],transformedList)}let fromLabels=getValueByPath(fromObject,["labels"]);fromLabels!=null&&setValueByPath(toObject,["labels"],fromLabels);let fromTunedModelInfo=getValueByPath(fromObject,["_self"]);fromTunedModelInfo!=null&&setValueByPath(toObject,["tunedModelInfo"],tunedModelInfoFromVertex(fromTunedModelInfo));let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);fromDefaultCheckpointId!=null&&setValueByPath(toObject,["defaultCheckpointId"],fromDefaultCheckpointId);let fromCheckpoints=getValueByPath(fromObject,["checkpoints"]);if(fromCheckpoints!=null){let transformedList=fromCheckpoints;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["checkpoints"],transformedList)}return toObject}function multiSpeakerVoiceConfigToVertex(fromObject,rootObject){let toObject={},fromSpeakerVoiceConfigs=getValueByPath(fromObject,["speakerVoiceConfigs"]);if(fromSpeakerVoiceConfigs!=null){let transformedList=fromSpeakerVoiceConfigs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>speakerVoiceConfigToVertex(item))),setValueByPath(toObject,["speakerVoiceConfigs"],transformedList)}return toObject}function partToMldev$1(fromObject,rootObject){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(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&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev$1(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev$1(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev$1(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&&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"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function partToVertex$1(fromObject,_rootObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(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"]);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!=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);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(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"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function productImageToVertex(fromObject,rootObject){let toObject={},fromProductImage=getValueByPath(fromObject,["productImage"]);return fromProductImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromProductImage)),toObject}function recontextImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromBaseSteps=getValueByPath(fromObject,["baseSteps"]);parentObject!==void 0&&fromBaseSteps!=null&&setValueByPath(parentObject,["parameters","baseSteps"],fromBaseSteps);let fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromSeed=getValueByPath(fromObject,["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"],fromPersonGeneration);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);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","compressionQuality"],fromOutputCompressionQuality);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt);let fromLabels=getValueByPath(fromObject,["labels"]);return parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),toObject}function recontextImageParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&recontextImageSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&recontextImageConfigToVertex(fromConfig,toObject),toObject}function recontextImageResponseFromVertex(fromObject,rootObject){let toObject={},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 recontextImageSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromPersonImage=getValueByPath(fromObject,["personImage"]);parentObject!==void 0&&fromPersonImage!=null&&setValueByPath(parentObject,["instances[0]","personImage","image"],imageToVertex(fromPersonImage));let fromProductImages=getValueByPath(fromObject,["productImages"]);if(parentObject!==void 0&&fromProductImages!=null){let transformedList=fromProductImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>productImageToVertex(item))),setValueByPath(parentObject,["instances[0]","productImages"],transformedList)}return toObject}function referenceImageAPIInternalToVertex(fromObject,rootObject){let toObject={},fromReferenceImage=getValueByPath(fromObject,["referenceImage"]);fromReferenceImage!=null&&setValueByPath(toObject,["referenceImage"],imageToVertex(fromReferenceImage));let fromReferenceId=getValueByPath(fromObject,["referenceId"]);fromReferenceId!=null&&setValueByPath(toObject,["referenceId"],fromReferenceId);let fromReferenceType=getValueByPath(fromObject,["referenceType"]);fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType);let fromMaskImageConfig=getValueByPath(fromObject,["maskImageConfig"]);fromMaskImageConfig!=null&&setValueByPath(toObject,["maskImageConfig"],maskReferenceConfigToVertex(fromMaskImageConfig));let fromControlImageConfig=getValueByPath(fromObject,["controlImageConfig"]);fromControlImageConfig!=null&&setValueByPath(toObject,["controlImageConfig"],controlReferenceConfigToVertex(fromControlImageConfig));let fromStyleImageConfig=getValueByPath(fromObject,["styleImageConfig"]);fromStyleImageConfig!=null&&setValueByPath(toObject,["styleImageConfig"],fromStyleImageConfig);let fromSubjectImageConfig=getValueByPath(fromObject,["subjectImageConfig"]);return fromSubjectImageConfig!=null&&setValueByPath(toObject,["subjectImageConfig"],fromSubjectImageConfig),toObject}function replicatedVoiceConfigToVertex(fromObject,_rootObject){let toObject={},fromMimeType=getValueByPath(fromObject,["mimeType"]);fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType);let fromVoiceSampleAudio=getValueByPath(fromObject,["voiceSampleAudio"]);if(fromVoiceSampleAudio!=null&&setValueByPath(toObject,["voiceSampleAudio"],fromVoiceSampleAudio),getValueByPath(fromObject,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function safetyAttributesFromVertex(fromObject,_rootObject){let toObject={},fromCategories=getValueByPath(fromObject,["safetyAttributes","categories"]);fromCategories!=null&&setValueByPath(toObject,["categories"],fromCategories);let fromScores=getValueByPath(fromObject,["safetyAttributes","scores"]);fromScores!=null&&setValueByPath(toObject,["scores"],fromScores);let fromContentType=getValueByPath(fromObject,["contentType"]);return fromContentType!=null&&setValueByPath(toObject,["contentType"],fromContentType),toObject}function safetySettingToMldev$1(fromObject,_rootObject){let toObject={},fromCategory=getValueByPath(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 scribbleImageToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);return fromImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromImage)),toObject}function segmentImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromMode=getValueByPath(fromObject,["mode"]);parentObject!==void 0&&fromMode!=null&&setValueByPath(parentObject,["parameters","mode"],fromMode);let fromMaxPredictions=getValueByPath(fromObject,["maxPredictions"]);parentObject!==void 0&&fromMaxPredictions!=null&&setValueByPath(parentObject,["parameters","maxPredictions"],fromMaxPredictions);let fromConfidenceThreshold=getValueByPath(fromObject,["confidenceThreshold"]);parentObject!==void 0&&fromConfidenceThreshold!=null&&setValueByPath(parentObject,["parameters","confidenceThreshold"],fromConfidenceThreshold);let fromMaskDilation=getValueByPath(fromObject,["maskDilation"]);parentObject!==void 0&&fromMaskDilation!=null&&setValueByPath(parentObject,["parameters","maskDilation"],fromMaskDilation);let fromBinaryColorThreshold=getValueByPath(fromObject,["binaryColorThreshold"]);parentObject!==void 0&&fromBinaryColorThreshold!=null&&setValueByPath(parentObject,["parameters","binaryColorThreshold"],fromBinaryColorThreshold);let fromLabels=getValueByPath(fromObject,["labels"]);return parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),toObject}function segmentImageParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&segmentImageSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&segmentImageConfigToVertex(fromConfig,toObject),toObject}function segmentImageResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedMasks=getValueByPath(fromObject,["predictions"]);if(fromGeneratedMasks!=null){let transformedList=fromGeneratedMasks;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageMaskFromVertex(item))),setValueByPath(toObject,["generatedMasks"],transformedList)}return toObject}function segmentImageSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToVertex(fromImage));let fromScribbleImage=getValueByPath(fromObject,["scribbleImage"]);return parentObject!==void 0&&fromScribbleImage!=null&&setValueByPath(parentObject,["instances[0]","scribble"],scribbleImageToVertex(fromScribbleImage)),toObject}function speakerVoiceConfigToVertex(fromObject,rootObject){let toObject={},fromSpeaker=getValueByPath(fromObject,["speaker"]);fromSpeaker!=null&&setValueByPath(toObject,["speaker"],fromSpeaker);let fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);return fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex(fromVoiceConfig)),toObject}function speechConfigToVertex(fromObject,rootObject){let toObject={},fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex(fromVoiceConfig));let fromLanguageCode=getValueByPath(fromObject,["languageCode"]);fromLanguageCode!=null&&setValueByPath(toObject,["languageCode"],fromLanguageCode);let fromMultiSpeakerVoiceConfig=getValueByPath(fromObject,["multiSpeakerVoiceConfig"]);return fromMultiSpeakerVoiceConfig!=null&&setValueByPath(toObject,["multiSpeakerVoiceConfig"],multiSpeakerVoiceConfigToVertex(fromMultiSpeakerVoiceConfig)),toObject}function toolConfigToMldev(fromObject,rootObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],functionCallingConfigToMldev(fromFunctionCallingConfig));let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig);let fromIncludeServerSideToolInvocations=getValueByPath(fromObject,["includeServerSideToolInvocations"]);return fromIncludeServerSideToolInvocations!=null&&setValueByPath(toObject,["includeServerSideToolInvocations"],fromIncludeServerSideToolInvocations),toObject}function toolConfigToVertex(fromObject,_rootObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],fromFunctionCallingConfig);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$1(fromObject,rootObject){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$1(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!=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(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$1(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,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),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(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,["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;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(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 tunedModelInfoFromMldev(fromObject,_rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromCreateTime=getValueByPath(fromObject,["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(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);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(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),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!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateModelConfigToVertex(fromConfig,toObject),toObject}function upscaleImageAPIConfigInternalToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);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 fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);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","compressionQuality"],fromOutputCompressionQuality);let fromEnhanceInputImage=getValueByPath(fromObject,["enhanceInputImage"]);parentObject!==void 0&&fromEnhanceInputImage!=null&&setValueByPath(parentObject,["parameters","upscaleConfig","enhanceInputImage"],fromEnhanceInputImage);let fromImagePreservationFactor=getValueByPath(fromObject,["imagePreservationFactor"]);parentObject!==void 0&&fromImagePreservationFactor!=null&&setValueByPath(parentObject,["parameters","upscaleConfig","imagePreservationFactor"],fromImagePreservationFactor);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromMode=getValueByPath(fromObject,["mode"]);return parentObject!==void 0&&fromMode!=null&&setValueByPath(parentObject,["parameters","mode"],fromMode),toObject}function upscaleImageAPIParametersInternalToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToVertex(fromImage));let fromUpscaleFactor=getValueByPath(fromObject,["upscaleFactor"]);fromUpscaleFactor!=null&&setValueByPath(toObject,["parameters","upscaleConfig","upscaleFactor"],fromUpscaleFactor);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&upscaleImageAPIConfigInternalToVertex(fromConfig,toObject),toObject}function upscaleImageResponseFromVertex(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(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function videoFromMldev(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["encodedVideo"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["encoding"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoFromVertex(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["gcsUri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoGenerationMaskToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["_self"],imageToVertex(fromImage));let fromMaskMode=getValueByPath(fromObject,["maskMode"]);return fromMaskMode!=null&&setValueByPath(toObject,["maskMode"],fromMaskMode),toObject}function videoGenerationReferenceImageToMldev(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["image"],imageToMldev(fromImage));let fromReferenceType=getValueByPath(fromObject,["referenceType"]);return fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType),toObject}function videoGenerationReferenceImageToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromImage));let fromReferenceType=getValueByPath(fromObject,["referenceType"]);return fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType),toObject}function videoToMldev(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["videoBytes"]);fromVideoBytes!=null&&setValueByPath(toObject,["encodedVideo"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["encoding"],fromMimeType),toObject}function videoToVertex(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["gcsUri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["videoBytes"]);fromVideoBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function voiceConfigToVertex(fromObject,rootObject){let toObject={},fromReplicatedVoiceConfig=getValueByPath(fromObject,["replicatedVoiceConfig"]);fromReplicatedVoiceConfig!=null&&setValueByPath(toObject,["replicatedVoiceConfig"],replicatedVoiceConfigToVertex(fromReplicatedVoiceConfig));let fromPrebuiltVoiceConfig=getValueByPath(fromObject,["prebuiltVoiceConfig"]);return fromPrebuiltVoiceConfig!=null&&setValueByPath(toObject,["prebuiltVoiceConfig"],fromPrebuiltVoiceConfig),toObject}var GOOGLE_API_CLIENT_HEADER="x-goog-api-client",SDK_VERSION="2.21.0",LIBRARY_LABEL=`google-genai-sdk/${SDK_VERSION}`;var MCP_LABEL="mcp_used/unknown",hasMcpToolUsageFromMcpToTool=!1;function hasMcpToolUsage(tools){for(let tool of tools)if(isMcpCallableTool(tool)||typeof tool=="object"&&"inputSchema"in tool)return!0;return hasMcpToolUsageFromMcpToTool}function setMcpUsageHeader(headers){var _a2;let existingHeader=(_a2=headers[GOOGLE_API_CLIENT_HEADER])!==null&&_a2!==void 0?_a2:"";headers[GOOGLE_API_CLIENT_HEADER]=(existingHeader+` ${MCP_LABEL}`).trimStart()}function isMcpCallableTool(object){return object!==null&&typeof object=="object"&&object instanceof McpCallableTool}function listAllTools(mcpClient_1){return __asyncGenerator(this,arguments,function*(mcpClient,maxTools=100){let cursor,numTools=0;for(;numTools<maxTools;){let t2=yield __await(mcpClient.listTools({cursor}));for(let tool of t2.tools)yield yield __await(tool),numTools++;if(!t2.nextCursor)break;cursor=t2.nextCursor}})}var McpCallableTool=class _McpCallableTool{constructor(mcpClients=[],config){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=mcpClients,this.config=config}static create(mcpClients,config){return new _McpCallableTool(mcpClients,config)}async initialize(){var _a2,e_1,_b,_c;if(this.mcpTools.length>0)return;let functionMap={},mcpTools=[];for(let mcpClient of this.mcpClients)try{for(var _d=!0,_e=(e_1=void 0,__asyncValues(listAllTools(mcpClient))),_f;_f=await _e.next(),_a2=_f.done,!_a2;_d=!0){_c=_f.value,_d=!1;let mcpTool=_c;mcpTools.push(mcpTool);let mcpToolName=mcpTool.name;if(functionMap[mcpToolName])throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);functionMap[mcpToolName]=mcpClient}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_d&&!_a2&&(_b=_e.return)&&await _b.call(_e)}finally{if(e_1)throw e_1.error}}this.mcpTools=mcpTools,this.functionNameToMcpClient=functionMap}async tool(){return await this.initialize(),mcpToolsToGeminiTool(this.mcpTools,this.config)}async callTool(functionCalls){await this.initialize();let functionCallResponseParts=[];for(let functionCall of functionCalls)if(functionCall.name in this.functionNameToMcpClient){let mcpClient=this.functionNameToMcpClient[functionCall.name],requestOptions;this.config.timeout&&(requestOptions={timeout:this.config.timeout});let callToolResponse=await mcpClient.callTool({name:functionCall.name,arguments:functionCall.args},void 0,requestOptions);functionCallResponseParts.push({functionResponse:{name:functionCall.name,response:callToolResponse.isError?{error:callToolResponse}:callToolResponse}})}return functionCallResponseParts}};var DEFAULT_MAX_REMOTE_CALLS=10;function shouldDisableAfc(config){var _a2,_b,_c;if(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.disable)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 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)===null||_a2===void 0)&&_a2.tools&¶ms.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=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")&¶ms.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(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(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,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,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(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.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:_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' 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 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=>{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,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 Agent Platform mode.");actualParams.config.filter="labels.tune-type:*"}return new Pager(PagedItem.PAGED_ITEM_MODELS,x2=>this.listInternal(x2),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/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,referenceImages:[],config:params.config};return params.referenceImages&¶ms.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};return await this.upscaleImageInternal(apiParams)},this.generateVideos=async params=>{var _a2,_b,_c,_d,_e,_f;if((params.prompt||params.image||params.video)&¶ms.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 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.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)}}maybeMoveToResponseJsonSchema(params){params.config&¶ms.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)===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&¶ms.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){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}`);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,e_1,_b2,_c2,_d,_e;remoteCallCount<maxRemoteCalls;){wereFunctionsCalled&&(remoteCallCount++,wereFunctionsCalled=!1);let transformedParams=yield __await(models.processParamsMaybeAddMcpUsage(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=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 implement 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=[];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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(apiResponse),typedResp=new GenerateContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=generateContentParametersToMldev(this.apiClient,params);return path=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(apiResponse),typedResp=new GenerateContentResponse;return Object.assign(typedResp,resp),typedResp})}}async generateContentStreamInternal(params){var _a2,_b,_c,_d;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path,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(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={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 path=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path,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_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={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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=embedContentParametersPrivateToVertex(this.apiClient,params,params),endpointUrl=tIsVertexEmbedContentModel(params.model)?"{model}:embedContent":"{model}:predict";return path=formatMap(endpointUrl,body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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=embedContentResponseFromVertex(apiResponse,params),typedResp=new EmbedContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=embedContentParametersPrivateToMldev(this.apiClient,params);return path=formatMap("{model}:batchEmbedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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=embedContentResponseFromMldev(apiResponse),typedResp=new EmbedContentResponse;return Object.assign(typedResp,resp),typedResp})}}async generateImagesInternal(params){var _a2,_b;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateImagesParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=editImageParametersInternalToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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;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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=upscaleImageAPIParametersInternalToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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;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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=recontextImageParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 Platform (previously known as Vertex AI).")}async segmentImage(params){var _a2,_b;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=segmentImageParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=getModelParametersToVertex(this.apiClient,params);return path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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{let body=getModelParametersToMldev(this.apiClient,params);return path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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){var _a2,_b,_c,_d;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=listModelsParametersToVertex(this.apiClient,params);return path=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(apiResponse),typedResp=new ListModelsResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=listModelsParametersToMldev(this.apiClient,params);return path=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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;return Object.assign(typedResp,resp),typedResp})}}async update(params){var _a2,_b,_c,_d;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=updateModelParametersToVertex(this.apiClient,params);return path=formatMap("{model}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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.apiClient,params);return path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,_d;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=deleteModelParametersToVertex(this.apiClient,params);return path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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.assign(typedResp,resp),typedResp})}else{let body=deleteModelParametersToMldev(this.apiClient,params);return path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(typedResp,resp),typedResp})}}async countTokens(params){var _a2,_b,_c,_d;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=countTokensParametersToVertex(this.apiClient,params);return path=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(apiResponse),typedResp=new CountTokensResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=countTokensParametersToMldev(this.apiClient,params);return path=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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=countTokensResponseFromMldev(apiResponse),typedResp=new CountTokensResponse;return Object.assign(typedResp,resp),typedResp})}}async computeTokens(params){var _a2,_b;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=computeTokensParametersToVertex(this.apiClient,params);return path=formatMap("{model}:computeTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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=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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateVideosParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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(apiResponse),typedResp=new GenerateVideosOperation;return Object.assign(typedResp,resp),typedResp})}else{let body=generateVideosParametersToMldev(this.apiClient,params);return path=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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.assign(typedResp,resp),typedResp})}}};Models.loggedGenerateImagesWarning=!1;Models.loggedEditImageWarning=!1;Models.loggedGenerateVideosWarning=!1;function bytesToBase64(u8arr){return btoa(String.fromCodePoint(...u8arr))}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}}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=>options?.charEncoding==="percent"?encodeURIComponent(v):v,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(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=`${encodeString(pk)}=${encValue}`,!(!tmp||tmp==="=")&&(out+=`&${tmp}`)))}),out.slice(1)}}var encodeForm=formEncoder(",");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):value}function mapDefined(inp,mapper){let res=inp.reduce((acc,v)=>{if(v==null)return acc;let m2=mapper(v);return m2==null||acc.push(m2),acc},[]);return res.length?res:null}function mapDefinedEntries(inp,mapper){let acc=[];for(let[k,v]of inp){if(v==null)continue;let m2=mapper([k,v]);m2!=null&&acc.push(m2)}return acc.length?acc:null}function queryJoin(...args){return args.filter(Boolean).join("&")}function queryEncoder(f3){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.entries(values).map(([key,value])=>allowEmptySet.has(key)&&(value==null||value===""||Array.isArray(value)&&value.length===0)?`${encodeURIComponent(key)}=`:f3(key,value,opts));return queryJoin(...encoded)}}var encodeFormQuery=queryEncoder(encodeForm);var codeRangeRE$1=new RegExp("^[0-9]xx$","i");var codeRangeRE=new RegExp("^[0-9]xx$","i");var gt=typeof globalThis>"u"?null:globalThis,webWorkerLike=typeof gt=="object"&>!=null&&"importScripts"in gt&&typeof gt.importScripts=="function",isBrowserLike=webWorkerLike||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u";var CR2=13,LF2=10,BOUNDARIES=[[CR2,LF2,CR2,LF2],[CR2,LF2,CR2],[CR2,LF2,LF2],[CR2,CR2,LF2],[LF2,CR2,LF2],[CR2,CR2],[LF2,CR2],[LF2,LF2]],MAX_BOUNDARY_LEN=BOUNDARIES.reduce((m2,b)=>Math.max(m2,b.length),0);var _a;_a=Symbol.toStringTag;var MAX_CHUNK_SIZE=1024*1024*8;var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types3=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types3.includes("object")||types3.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(!config||config.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error){if(!(error instanceof UnsupportedStrictJsonSchemaError))throw error;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)";function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return isSameModel?block.redacted||block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:block:[];if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&normalizeToolCallId){let normalizedId=normalizeToolCallId(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i2=0;i2<transformed.length;i2++){let msg=transformed[i2];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b=>b.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}var GOOGLE_SDK_THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH};function resolveGoogleThinkingLevel(model,level){let mapped=model.thinkingLevelMap?.[level],resolvedLevel=typeof mapped=="string"?mapped.toLowerCase():level;switch(resolvedLevel){case"minimal":case"low":case"medium":case"high":return resolvedLevel;default:throw new Error(`Unsupported Google thinking level mapping for ${model.provider}/${model.id}: ${level} -> ${String(mapped)}`)}}function usesGoogleThinkingLevel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-(?:pro|flash)/.test(id)||/gemini-(?:[4-9]|[1-9]\d)/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"||/gemma-?4/.test(id)}function toGoogleThinkingLevel(level){switch(level){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function toGoogleSdkThinkingLevel(level){return GOOGLE_SDK_THINKING_LEVEL_MAP[level]}function getDisabledGoogleThinkingConfig(model){if(!usesGoogleThinkingLevel(model))return{thinkingBudget:0};let fallback=clampThinkingLevel(model,"off");if(fallback==="off")return{thinkingBudget:0};let resolvedLevel=resolveGoogleThinkingLevel(model,fallback),apiLevel=toGoogleThinkingLevel(resolvedLevel);return{thinkingLevel:toGoogleSdkThinkingLevel(apiLevel)}}function isThinkingPart(part){return part.thought===!0}function retainThoughtSignature(existing,incoming){return typeof incoming=="string"&&incoming.length>0?incoming:existing}var base64SignaturePattern=/^[A-Za-z0-9+/]+={0,2}$/;function isValidThoughtSignature(signature){return!signature||signature.length%4!==0?!1:base64SignaturePattern.test(signature)}function resolveThoughtSignature(isSameProviderAndModel,signature){return isSameProviderAndModel&&isValidThoughtSignature(signature)?signature:void 0}function requiresToolCallId(modelId){let geminiMajorVersion=getGeminiMajorVersion(modelId);return modelId.startsWith("claude-")||modelId.startsWith("gpt-oss-")||geminiMajorVersion!==void 0&&geminiMajorVersion>=3}function getGeminiMajorVersion(modelId){let match=modelId.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(match)return Number.parseInt(match[1],10)}function supportsMultimodalFunctionResponse(modelId){let geminiMajorVersion=getGeminiMajorVersion(modelId);return geminiMajorVersion!==void 0?geminiMajorVersion>=3:!0}function convertMessages(model,context){let conversation=withoutInitialSystemMessage(collapseSystemMessages(context).messages),contents=[],transformedMessages=transformMessages(conversation,model,id=>requiresToolCallId(model.id)?id.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64):id);for(let msg of transformedMessages)if(msg.role==="user")if(typeof msg.content=="string")contents.push({role:"user",parts:[{text:sanitizeSurrogates(msg.content)}]});else{let parts=msg.content.map(item=>item.type==="text"?{text:sanitizeSurrogates(item.text)}:{inlineData:{mimeType:item.mimeType,data:item.data}});if(parts.length===0)continue;contents.push({role:"user",parts})}else if(msg.role==="assistant"){let parts=[],isSameProviderAndModel=msg.provider===model.provider&&msg.model===model.id;for(let block of msg.content)if(block.type==="text"){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.textSignature);if((!block.text||block.text.trim()==="")&&!thoughtSignature)continue;parts.push({text:sanitizeSurrogates(block.text),...thoughtSignature&&{thoughtSignature}})}else if(block.type==="thinking")if(isSameProviderAndModel){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.thinkingSignature);if((!block.thinking||block.thinking.trim()==="")&&!thoughtSignature)continue;parts.push({thought:!0,text:sanitizeSurrogates(block.thinking),...thoughtSignature&&{thoughtSignature}})}else{if(!block.thinking||block.thinking.trim()==="")continue;parts.push({text:sanitizeSurrogates(block.thinking)})}else if(block.type==="toolCall"){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.thoughtSignature),part={functionCall:{name:block.name,args:block.arguments??{},...requiresToolCallId(model.id)?{id:block.id}:{}},...thoughtSignature&&{thoughtSignature}};parts.push(part)}if(parts.length===0)continue;contents.push({role:"model",parts})}else if(msg.role==="toolResult"){let textResult=msg.content.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
67
67
|
`),imageContent=model.input.includes("image")?msg.content.filter(c=>c.type==="image"):[],hasText=textResult.trim().length>0,hasImages=imageContent.length>0,modelSupportsMultimodalFunctionResponse=supportsMultimodalFunctionResponse(model.id),responseValue=hasText?sanitizeSurrogates(textResult):hasImages?"(see attached image)":"",imageParts=imageContent.map(imageBlock=>({inlineData:{mimeType:imageBlock.mimeType,data:imageBlock.data}})),includeId=requiresToolCallId(model.id),functionResponsePart={functionResponse:{name:msg.toolName,response:msg.isError?{error:responseValue}:{output:responseValue},...hasImages&&modelSupportsMultimodalFunctionResponse&&{parts:imageParts},...includeId?{id:msg.toolCallId}:{}}},lastContent=contents[contents.length-1];lastContent?.role==="user"&&lastContent.parts?.some(p=>p.functionResponse)?lastContent.parts.push(functionResponsePart):contents.push({role:"user",parts:[functionResponsePart]}),hasImages&&!modelSupportsMultimodalFunctionResponse&&contents.push({role:"user",parts:[{text:"Tool result image:"},...imageParts]})}return contents}var JSON_SCHEMA_META_DECLARATIONS=new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"]);function sanitizeForOpenApi(schema){if(typeof schema!="object"||schema===null||Array.isArray(schema))return schema;let result={},constraints={},stringConstant;for(let[key,value]of Object.entries(schema))JSON_SCHEMA_META_DECLARATIONS.has(key)||(key==="const"?typeof value=="string"?stringConstant=value:constraints[key]=value:key==="exclusiveMinimum"||key==="exclusiveMaximum"||key==="patternProperties"?constraints[key]=value:key==="properties"?result[key]=Object.fromEntries(Object.entries(value).map(([name,property])=>[name,sanitizeForOpenApi(property)])):key==="items"?result[key]=sanitizeForOpenApi(value):key==="anyOf"?result[key]=value.map(sanitizeForOpenApi):result[key]=value);if(stringConstant!==void 0&&(result.enum=[stringConstant]),(result.type===void 0||result.type==="string")&&result.enum===void 0&&Array.isArray(result.anyOf)&&result.anyOf.length>0&&result.anyOf.every(variant=>variant.type==="string"&&Array.isArray(variant.enum)&&variant.enum.every(value=>typeof value=="string")&&Object.keys(variant).every(key=>key==="type"||key==="enum"))&&(result.type="string",result.enum=[...new Set(result.anyOf.flatMap(variant=>variant.enum))],delete result.anyOf),Object.keys(constraints).length>0){let instruction=`Must satisfy JSON Schema constraints: ${JSON.stringify(constraints)}`;result.description=result.description?`${result.description}
|
|
68
|
-
${instruction}`:instruction}return result}function convertTools(tools,useParameters=!1,supportsStrictMode=!0){if(tools.length!==0)return[{functionDeclarations:tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode),parameters=getJsonSchemaToolParameters(tool,strict);return{name:tool.name,description:tool.description,...useParameters?{parameters:sanitizeForOpenApi(parameters)}:{parametersJsonSchema:parameters}}})}]}function supportsGoogleStrictToolSampling(modelId){let majorVersion=getGeminiMajorVersion(modelId);return majorVersion!==void 0&&majorVersion>=3}function mapToolChoice(choice){switch(choice){case"auto":return FunctionCallingConfigMode.AUTO;case"none":return FunctionCallingConfigMode.NONE;case"any":return FunctionCallingConfigMode.ANY;default:return FunctionCallingConfigMode.AUTO}}function resolveGoogleFunctionCallingMode(tools,toolChoice,supportsStrictMode){let useStrictMode=tools.some(tool=>resolveJsonSchemaStrictSampling(tool,supportsStrictMode)===!0);return toolChoice==="none"||toolChoice==="any"?mapToolChoice(toolChoice):useStrictMode?FunctionCallingConfigMode.VALIDATED:toolChoice?mapToolChoice(toolChoice):void 0}function mapStopReasonString(reason){switch(reason){case"STOP":return"stop";case"MAX_TOKENS":return"length";default:return"error"}}var CHARS_PER_TOKEN=3.5,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify2(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)chars+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:chars+=block.name.length+safeJsonStringify2(block.arguments).length;return Math.ceil(chars/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i2=0;i2<messages.length;i2++){let message=messages[i2];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i2})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i2=usageInfo.index+1;i2<messages.length;i2++)trailingTokens+=estimateMessageTokens(messages[i2]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify2(tools))}var CONTEXT_SAFETY_TOKENS=4096,MIN_MAX_TOKENS=1;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let available=model.contextWindow-estimateContextTokens(context).tokens-CONTEXT_SAFETY_TOKENS;return Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,available))}function resolveSamplingParams(model,thinkingLevel,requestParams){let effectiveThinkingLevel=clampThinkingLevel(model,thinkingLevel),thinkingLevelParams=model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];return model.samplingParams||thinkingLevelParams||requestParams?{...model.samplingParams,...thinkingLevelParams,...requestParams}:void 0}function buildBaseOptions(model,context,options,apiKey){let samplingParams=resolveSamplingParams(model,options?.reasoning??"off",options?.samplingParams);return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,telemetry:options?.telemetry,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,headers:options?.headers,identity:options?.identity,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var MIN_ANSWER_TOKENS=1024,DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}var DEFAULT_ENDPOINT="https://daily-cloudcode-pa.googleapis.com",stream=(model,context,options)=>{let events=new AssistantMessageEventStream,output={role:"assistant",content:[],api:"google-antigravity",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};return(async()=>{try{if(typeof process<"u"&&process.env.PI_SERVER_MODE==="true")throw new Error("Google Antigravity inference must use pi-server in PI_SERVER_MODE");if(!options?.apiKey)throw new Error("Google Antigravity requires OAuth authentication. Use /login.");let credential=JSON.parse(options.apiKey);if(!credential||typeof credential.token!="string"||typeof credential.projectId!="string")throw new Error("Invalid Google Antigravity credentials. Use /login to authenticate.");let payload=buildRequest(model,context,credential.projectId,options),transformed=await options.onPayload?.(payload,model);transformed!==void 0&&(payload=transformed);let headers=providerHeadersToRecord({Authorization:`Bearer ${credential.token}`,"Content-Type":"application/json",Accept:"text/event-stream","User-Agent":"antigravity/hub/2.23.0 darwin/arm64",...model.id.startsWith("claude-")&&model.reasoning?{"anthropic-beta":"interleaved-thinking-2025-05-14"}:{}},model.headers,options.headers),body=JSON.stringify(payload),{response,signal}=await retryProviderRequest(async()=>{let timeout=AbortSignal.timeout(options.timeoutMs??6e5),signal2=options.signal?AbortSignal.any([options.signal,timeout]):timeout;signal2.throwIfAborted();let response2;try{response2=await(options.fetch??globalThis.fetch)(`${(model.baseUrl||DEFAULT_ENDPOINT).replace(/\/$/,"")}/v1internal:streamGenerateContent?alt=sse`,{method:"POST",headers,body,signal:signal2})}catch(error){throw Object.assign(error instanceof Error?error:new Error(String(error)),{status:void 0,headers:void 0})}if(await options.onResponse?.({status:response2.status,headers:headersToRecord(response2.headers)},model),!response2.ok)throw Object.assign(new Error("Google Antigravity request failed"),{status:response2.status,headers:response2.headers,body:await response2.text()});return{response:response2,signal:signal2}},{maxRetries:options.maxRetries??2,maxRetryDelayMs:options.maxRetryDelayMs,signal:options.signal});events.push({type:"start",partial:output});let current,endBlock=()=>{if(!current)return;let contentIndex=output.content.length-1;current.type==="text"?events.push({type:"text_end",contentIndex,content:current.text,partial:output}):events.push({type:"thinking_end",contentIndex,content:current.thinking,partial:output}),current=void 0};for await(let chunk of parseStream(response,signal)){if(await options.onProviderStreamEvent?.(chunk,model),chunk.error)throw new Error(chunk.error.message??JSON.stringify(chunk.error));if(!chunk.response)throw new Error("Google Antigravity stream event has no response");let data=chunk.response;output.responseId||=data.responseId,output.responseModel||=data.modelVersion;let candidate=data.candidates?.[0];for(let part of candidate?.content?.parts??[]){if(part.text!==void 0||part.thoughtSignature&&!part.functionCall){let thinking=isThinkingPart(part),signature=current?.type==="thinking"?current.thinkingSignature:current?.textSignature;(!current||(thinking?current.type!=="thinking":current.type!=="text")||signature&&part.thoughtSignature&&signature!==part.thoughtSignature)&&(endBlock(),current=thinking?{type:"thinking",thinking:""}:{type:"text",text:""},output.content.push(current),events.push({type:thinking?"thinking_start":"text_start",contentIndex:output.content.length-1,partial:output}));let delta=part.text??"",contentIndex=output.content.length-1;current.type==="thinking"?(current.thinking+=delta,current.thinkingSignature=retainThoughtSignature(current.thinkingSignature,part.thoughtSignature),events.push({type:"thinking_delta",contentIndex,delta,partial:output})):(current.text+=delta,current.textSignature=retainThoughtSignature(current.textSignature,part.thoughtSignature),events.push({type:"text_delta",contentIndex,delta,partial:output}))}if(part.functionCall){endBlock();let call=part.functionCall;if(!call.name||call.args!==void 0&&(call.args===null||Array.isArray(call.args)||typeof call.args!="object"))throw new Error("Google Antigravity returned an invalid function call");let toolCall={type:"toolCall",id:call.id??`call_${crypto.randomUUID()}`,name:call.name,arguments:call.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}},contentIndex=output.content.length;output.content.push(toolCall),events.push({type:"toolcall_start",contentIndex,partial:output}),events.push({type:"toolcall_delta",contentIndex,delta:JSON.stringify(toolCall.arguments),partial:output}),events.push({type:"toolcall_end",contentIndex,toolCall,partial:output})}}if(candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReasonString(candidate.finishReason),output.stopReason==="stop"&&output.content.some(part=>part.type==="toolCall")&&(output.stopReason="toolUse")),data.usageMetadata){let usage=data.usageMetadata;output.usage.input=(usage.promptTokenCount??0)-(usage.cachedContentTokenCount??0),output.usage.output=(usage.candidatesTokenCount??0)+(usage.thoughtsTokenCount??0),output.usage.cacheRead=usage.cachedContentTokenCount??0,output.usage.reasoning=usage.thoughtsTokenCount??0,output.usage.totalTokens=output.usage.input+output.usage.output+output.usage.cacheRead,calculateCost(model,output.usage)}}if(endBlock(),signal.throwIfAborted(),output.stopReason==="pending")throw new Error("Google Antigravity stream ended without a finish reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(`Google Antigravity stopped with: ${output.rawStopReason}`);events.push({type:"done",reason:output.stopReason,message:output})}catch(error){output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),events.push({type:"error",reason:output.stopReason,error:output})}events.end()})(),events},streamSimple=(model,context,options)=>{if(!options?.apiKey)throw new Error("Google Antigravity requires OAuth authentication. Use /login.");let base={...buildBaseOptions(model,context,options),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let level=clampThinkingLevel(model,options.reasoning);if(level==="off")return stream(model,context,{...base,thinking:{enabled:!1}});if(usesGoogleThinkingLevel(model))return stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolveGoogleThinkingLevel(model,level))}});let{maxTokens,thinkingBudget}=adjustMaxTokensForThinking(base.maxTokens,model.maxTokens,level,options?.thinkingBudgets);return stream(model,context,{...base,maxTokens,thinking:{enabled:!0,budgetTokens:thinkingBudget}})};function buildRequest(model,context,projectId,options){let tools=getCurrentTools(context.messages),systemPrompt=getCurrentSystemPrompt(context.messages),strict=supportsGoogleStrictToolSampling(model.id),mode=tools.length>0?resolveGoogleFunctionCallingMode(tools,options.toolChoice,strict):void 0,generationConfig={temperature:options.temperature,maxOutputTokens:options.maxTokens};return model.reasoning&&options.thinking&&(generationConfig.thinkingConfig=options.thinking.enabled?{includeThoughts:!0,...options.thinking.level!==void 0?{thinkingLevel:toGoogleSdkThinkingLevel(options.thinking.level)}:{thinkingBudget:options.thinking.budgetTokens}}:getDisabledGoogleThinkingConfig(model)),{project:projectId,model:model.id,requestType:"agent",userAgent:"antigravity",requestId:`agent-${crypto.randomUUID()}`,request:{contents:convertMessages(model,context),sessionId:options.sessionId,generationConfig,...systemPrompt&&{systemInstruction:{parts:[{text:sanitizeSurrogates(systemPrompt)}]}},...tools.length>0&&{tools:convertTools(tools,model.id.startsWith("claude-"),strict)},...mode!==void 0&&{toolConfig:{functionCallingConfig:{mode}}}}}}async function*parseStream(response,signal){if(!response.body)throw new Error("Google Antigravity response has no body");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",data=[],abort=()=>{reader.cancel(signal.reason)};signal.addEventListener("abort",abort,{once:!0});try{for(;;){signal.throwIfAborted();let{value,done}=await reader.read();signal.throwIfAborted(),buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),done&&buffer.length>0&&(buffer+=`
|
|
68
|
+
${instruction}`:instruction}return result}var JSON_SCHEMA_NAME_MAPS=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]),JSON_SCHEMA_SUBSCHEMAS=new Set(["additionalProperties","unevaluatedProperties","propertyNames","items","prefixItems","additionalItems","unevaluatedItems","contains","allOf","anyOf","oneOf","not","if","then","else","contentSchema"]);function rewriteConstAsEnum(schema,isNameMap=!1){if(Array.isArray(schema))return schema.map(item=>rewriteConstAsEnum(item));if(typeof schema!="object"||schema===null)return schema;let result=Object.fromEntries(Object.entries(schema).map(([key,value])=>isNameMap||JSON_SCHEMA_SUBSCHEMAS.has(key)?[key,rewriteConstAsEnum(value)]:JSON_SCHEMA_NAME_MAPS.has(key)?[key,rewriteConstAsEnum(value,!0)]:[key,value]));if(!isNameMap&&"const"in result&&result.enum===void 0){let value=result.const;(typeof value=="string"||typeof value=="number")&&(delete result.const,result.enum=[value])}return result}function convertTools(tools,useParameters=!1,supportsStrictMode=!0){if(tools.length!==0)return[{functionDeclarations:tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode),parameters=getJsonSchemaToolParameters(tool,strict);return{name:tool.name,description:tool.description,...useParameters?{parameters:sanitizeForOpenApi(parameters)}:{parametersJsonSchema:rewriteConstAsEnum(parameters)}}})}]}function supportsGoogleStrictToolSampling(modelId){let majorVersion=getGeminiMajorVersion(modelId);return majorVersion!==void 0&&majorVersion>=3}function mapToolChoice(choice){switch(choice){case"auto":return FunctionCallingConfigMode.AUTO;case"none":return FunctionCallingConfigMode.NONE;case"any":return FunctionCallingConfigMode.ANY;default:return FunctionCallingConfigMode.AUTO}}function resolveGoogleFunctionCallingMode(tools,toolChoice,supportsStrictMode){let useStrictMode=tools.some(tool=>resolveJsonSchemaStrictSampling(tool,supportsStrictMode)===!0);return toolChoice==="none"||toolChoice==="any"?mapToolChoice(toolChoice):useStrictMode?FunctionCallingConfigMode.VALIDATED:toolChoice?mapToolChoice(toolChoice):void 0}function mapStopReasonString(reason){switch(reason){case"STOP":return"stop";case"MAX_TOKENS":return"length";default:return"error"}}var CHARS_PER_TOKEN=3.5,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify2(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)chars+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:chars+=block.name.length+safeJsonStringify2(block.arguments).length;return Math.ceil(chars/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i2=0;i2<messages.length;i2++){let message=messages[i2];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i2})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i2=usageInfo.index+1;i2<messages.length;i2++)trailingTokens+=estimateMessageTokens(messages[i2]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify2(tools))}var CONTEXT_SAFETY_TOKENS=4096,MIN_MAX_TOKENS=1;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let available=model.contextWindow-estimateContextTokens(context).tokens-CONTEXT_SAFETY_TOKENS;return Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,available))}function resolveSamplingParams(model,thinkingLevel,requestParams){let effectiveThinkingLevel=clampThinkingLevel(model,thinkingLevel),thinkingLevelParams=model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];return model.samplingParams||thinkingLevelParams||requestParams?{...model.samplingParams,...thinkingLevelParams,...requestParams}:void 0}function buildBaseOptions(model,context,options,apiKey){let samplingParams=resolveSamplingParams(model,options?.reasoning??"off",options?.samplingParams);return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,telemetry:options?.telemetry,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,headers:options?.headers,identity:options?.identity,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var MIN_ANSWER_TOKENS=1024,DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}var DEFAULT_ENDPOINT="https://daily-cloudcode-pa.googleapis.com",stream=(model,context,options)=>{let events=new AssistantMessageEventStream,output={role:"assistant",content:[],api:"google-antigravity",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};return(async()=>{try{if(typeof process<"u"&&process.env.PI_SERVER_MODE==="true")throw new Error("Google Antigravity inference must use pi-server in PI_SERVER_MODE");if(!options?.apiKey)throw new Error("Google Antigravity requires OAuth authentication. Use /login.");let credential=JSON.parse(options.apiKey);if(!credential||typeof credential.token!="string"||typeof credential.projectId!="string")throw new Error("Invalid Google Antigravity credentials. Use /login to authenticate.");let payload=buildRequest(model,context,credential.projectId,options),transformed=await options.onPayload?.(payload,model);transformed!==void 0&&(payload=transformed);let headers=providerHeadersToRecord({Authorization:`Bearer ${credential.token}`,"Content-Type":"application/json",Accept:"text/event-stream","User-Agent":"antigravity/hub/2.23.0 darwin/arm64",...model.id.startsWith("claude-")&&model.reasoning?{"anthropic-beta":"interleaved-thinking-2025-05-14"}:{}},model.headers,options.headers),body=JSON.stringify(payload),{response,signal}=await retryProviderRequest(async()=>{let timeout=AbortSignal.timeout(options.timeoutMs??6e5),signal2=options.signal?AbortSignal.any([options.signal,timeout]):timeout;signal2.throwIfAborted();let response2;try{response2=await(options.fetch??globalThis.fetch)(`${(model.baseUrl||DEFAULT_ENDPOINT).replace(/\/$/,"")}/v1internal:streamGenerateContent?alt=sse`,{method:"POST",headers,body,signal:signal2})}catch(error){throw Object.assign(error instanceof Error?error:new Error(String(error)),{status:void 0,headers:void 0})}if(await options.onResponse?.({status:response2.status,headers:headersToRecord(response2.headers)},model),!response2.ok)throw Object.assign(new Error("Google Antigravity request failed"),{status:response2.status,headers:response2.headers,body:await response2.text()});return{response:response2,signal:signal2}},{maxRetries:options.maxRetries??2,maxRetryDelayMs:options.maxRetryDelayMs,signal:options.signal});events.push({type:"start",partial:output});let current,endBlock=()=>{if(!current)return;let contentIndex=output.content.length-1;current.type==="text"?events.push({type:"text_end",contentIndex,content:current.text,partial:output}):events.push({type:"thinking_end",contentIndex,content:current.thinking,partial:output}),current=void 0};for await(let chunk of parseStream(response,signal)){if(await options.onProviderStreamEvent?.(chunk,model),chunk.error)throw new Error(chunk.error.message??JSON.stringify(chunk.error));if(!chunk.response)throw new Error("Google Antigravity stream event has no response");let data=chunk.response;output.responseId||=data.responseId,output.responseModel||=data.modelVersion;let candidate=data.candidates?.[0];for(let part of candidate?.content?.parts??[]){if(part.text!==void 0||part.thoughtSignature&&!part.functionCall){let thinking=isThinkingPart(part),signature=current?.type==="thinking"?current.thinkingSignature:current?.textSignature;(!current||(thinking?current.type!=="thinking":current.type!=="text")||signature&&part.thoughtSignature&&signature!==part.thoughtSignature)&&(endBlock(),current=thinking?{type:"thinking",thinking:""}:{type:"text",text:""},output.content.push(current),events.push({type:thinking?"thinking_start":"text_start",contentIndex:output.content.length-1,partial:output}));let delta=part.text??"",contentIndex=output.content.length-1;current.type==="thinking"?(current.thinking+=delta,current.thinkingSignature=retainThoughtSignature(current.thinkingSignature,part.thoughtSignature),events.push({type:"thinking_delta",contentIndex,delta,partial:output})):(current.text+=delta,current.textSignature=retainThoughtSignature(current.textSignature,part.thoughtSignature),events.push({type:"text_delta",contentIndex,delta,partial:output}))}if(part.functionCall){endBlock();let call=part.functionCall;if(!call.name||call.args!==void 0&&(call.args===null||Array.isArray(call.args)||typeof call.args!="object"))throw new Error("Google Antigravity returned an invalid function call");let toolCall={type:"toolCall",id:call.id??`call_${crypto.randomUUID()}`,name:call.name,arguments:call.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}},contentIndex=output.content.length;output.content.push(toolCall),events.push({type:"toolcall_start",contentIndex,partial:output}),events.push({type:"toolcall_delta",contentIndex,delta:JSON.stringify(toolCall.arguments),partial:output}),events.push({type:"toolcall_end",contentIndex,toolCall,partial:output})}}if(candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReasonString(candidate.finishReason),output.stopReason==="stop"&&output.content.some(part=>part.type==="toolCall")&&(output.stopReason="toolUse")),data.usageMetadata){let usage=data.usageMetadata;output.usage.input=(usage.promptTokenCount??0)-(usage.cachedContentTokenCount??0),output.usage.output=(usage.candidatesTokenCount??0)+(usage.thoughtsTokenCount??0),output.usage.cacheRead=usage.cachedContentTokenCount??0,output.usage.reasoning=usage.thoughtsTokenCount??0,output.usage.totalTokens=output.usage.input+output.usage.output+output.usage.cacheRead,calculateCost(model,output.usage)}}if(endBlock(),signal.throwIfAborted(),output.stopReason==="pending")throw new Error("Google Antigravity stream ended without a finish reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(`Google Antigravity stopped with: ${output.rawStopReason}`);events.push({type:"done",reason:output.stopReason,message:output})}catch(error){output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),events.push({type:"error",reason:output.stopReason,error:output})}events.end()})(),events},streamSimple=(model,context,options)=>{if(!options?.apiKey)throw new Error("Google Antigravity requires OAuth authentication. Use /login.");let base={...buildBaseOptions(model,context,options),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let level=clampThinkingLevel(model,options.reasoning);if(level==="off")return stream(model,context,{...base,thinking:{enabled:!1}});if(usesGoogleThinkingLevel(model))return stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolveGoogleThinkingLevel(model,level))}});let{maxTokens,thinkingBudget}=adjustMaxTokensForThinking(base.maxTokens,model.maxTokens,level,options?.thinkingBudgets);return stream(model,context,{...base,maxTokens,thinking:{enabled:!0,budgetTokens:thinkingBudget}})};function buildRequest(model,context,projectId,options){let tools=getCurrentTools(context.messages),systemPrompt=getCurrentSystemPrompt(context.messages),strict=supportsGoogleStrictToolSampling(model.id),mode=tools.length>0?resolveGoogleFunctionCallingMode(tools,options.toolChoice,strict):void 0,generationConfig={temperature:options.temperature,maxOutputTokens:options.maxTokens};return model.reasoning&&options.thinking&&(generationConfig.thinkingConfig=options.thinking.enabled?{includeThoughts:!0,...options.thinking.level!==void 0?{thinkingLevel:toGoogleSdkThinkingLevel(options.thinking.level)}:{thinkingBudget:options.thinking.budgetTokens}}:getDisabledGoogleThinkingConfig(model)),{project:projectId,model:model.id,requestType:"agent",userAgent:"antigravity",requestId:`agent-${crypto.randomUUID()}`,request:{contents:convertMessages(model,context),sessionId:options.sessionId,generationConfig,...systemPrompt&&{systemInstruction:{parts:[{text:sanitizeSurrogates(systemPrompt)}]}},...tools.length>0&&{tools:convertTools(tools,model.id.startsWith("claude-"),strict)},...mode!==void 0&&{toolConfig:{functionCallingConfig:{mode}}}}}}async function*parseStream(response,signal){if(!response.body)throw new Error("Google Antigravity response has no body");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",data=[],abort=()=>{reader.cancel(signal.reason)};signal.addEventListener("abort",abort,{once:!0});try{for(;;){signal.throwIfAborted();let{value,done}=await reader.read();signal.throwIfAborted(),buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),done&&buffer.length>0&&(buffer+=`
|
|
69
69
|
`);let end=buffer.indexOf(`
|
|
70
70
|
`);for(;end!==-1;){let line=buffer.slice(0,end).replace(/\r$/,"");buffer=buffer.slice(end+1),line.startsWith("data:")&&data.push(line.slice(5).trimStart()),line===""&&data.length>0&&(yield JSON.parse(data.join(`
|
|
71
71
|
`)),data.length=0),end=buffer.indexOf(`
|