@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
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-WVXVPMMO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{clampThinkingLevel,collapseSystemMessages,withoutInitialSystemMessage}from"./chunk-D3OXAPLU.js";import{__commonJS,__require,__toESM}from"./chunk-JXWJOIH4.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2._timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name="AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_extend=__commonJS({"node_modules/extend/index.js"(exports,module){"use strict";var hasOwn2=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function(arr){return typeof Array.isArray=="function"?Array.isArray(arr):toStr.call(arr)==="[object Array]"},isPlainObject2=function(obj){if(!obj||toStr.call(obj)!=="[object Object]")return!1;var hasOwnConstructor=hasOwn2.call(obj,"constructor"),hasIsPrototypeOf=obj.constructor&&obj.constructor.prototype&&hasOwn2.call(obj.constructor.prototype,"isPrototypeOf");if(obj.constructor&&!hasOwnConstructor&&!hasIsPrototypeOf)return!1;var key;for(key in obj);return typeof key>"u"||hasOwn2.call(obj,key)},setProperty=function(target,options){defineProperty&&options.name==="__proto__"?defineProperty(target,options.name,{enumerable:!0,configurable:!0,value:options.newValue,writable:!0}):target[options.name]=options.newValue},getProperty=function(obj,name){if(name==="__proto__")if(hasOwn2.call(obj,name)){if(gOPD)return gOPD(obj,name).value}else return;return obj[name]};module.exports=function extend(){var options,name,src,copy,copyIsArray,clone,target=arguments[0],i=1,length=arguments.length,deep=!1;for(typeof target=="boolean"&&(deep=target,target=arguments[1]||{},i=2),(target==null||typeof target!="object"&&typeof target!="function")&&(target={});i<length;++i)if(options=arguments[i],options!=null)for(name in options)src=getProperty(target,name),copy=getProperty(options,name),target!==copy&&(deep&©&&(isPlainObject2(copy)||(copyIsArray=isArray(copy)))?(copyIsArray?(copyIsArray=!1,clone=src&&isArray(src)?src:[]):clone=src&&isPlainObject2(src)?src:{},setProperty(target,{name,newValue:extend(deep,clone,copy)})):typeof copy<"u"&&setProperty(target,{name,newValue:copy}));return target}}});var require_package=__commonJS({"node_modules/gaxios/package.json"(exports,module){module.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}});var require_util=__commonJS({"node_modules/gaxios/build/cjs/src/util.cjs"(exports,module){"use strict";var pkg=require_package();module.exports={pkg}}});var require_common=__commonJS({"node_modules/gaxios/build/cjs/src/common.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosError=exports.GAXIOS_ERROR_SYMBOL=void 0;exports.defaultErrorRedactor=defaultErrorRedactor;var extend_1=__importDefault(require_extend()),util_cjs_1=__importDefault(require_util()),pkg=util_cjs_1.default.pkg;exports.GAXIOS_ERROR_SYMBOL=Symbol.for(`${pkg.name}-gaxios-error`);var GaxiosError=class _GaxiosError extends Error{config;response;code;status;error;[exports.GAXIOS_ERROR_SYMBOL]=pkg.version;static[Symbol.hasInstance](instance){return instance&&typeof instance=="object"&&exports.GAXIOS_ERROR_SYMBOL in instance&&instance[exports.GAXIOS_ERROR_SYMBOL]===pkg.version?!0:Function.prototype[Symbol.hasInstance].call(_GaxiosError,instance)}constructor(message,config,response,cause){if(super(message,{cause}),this.config=config,this.response=response,this.error=cause instanceof Error?cause:void 0,this.config=(0,extend_1.default)(!0,{},config),this.response&&(this.response.config=(0,extend_1.default)(!0,{},this.response.config)),this.response){try{this.response.data=translateData(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}cause instanceof DOMException?this.code=cause.name:cause&&typeof cause=="object"&&"code"in cause&&(typeof cause.code=="string"||typeof cause.code=="number")&&(this.code=cause.code)}static extractAPIErrorFromResponse(res,defaultErrorMessage="The request failed"){let message=defaultErrorMessage;if(typeof res.data=="string"&&(message=res.data),res.data&&typeof res.data=="object"&&"error"in res.data&&res.data.error&&!res.ok){if(typeof res.data.error=="string")return{message:res.data.error,code:res.status,status:res.statusText};if(typeof res.data.error=="object"){message="message"in res.data.error&&typeof res.data.error.message=="string"?res.data.error.message:message;let status="status"in res.data.error&&typeof res.data.error.status=="string"?res.data.error.status:res.statusText,code="code"in res.data.error&&typeof res.data.error.code=="number"?res.data.error.code:res.status;if("errors"in res.data.error&&Array.isArray(res.data.error.errors)){let errorMessages=[];for(let e of res.data.error.errors)typeof e=="object"&&"message"in e&&typeof e.message=="string"&&errorMessages.push(e.message);return Object.assign({message:errorMessages.join(`
|
|
2
|
+
import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-4RKLODCT.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{clampThinkingLevel,collapseSystemMessages,withoutInitialSystemMessage}from"./chunk-G23G7KNC.js";import{__commonJS,__require,__toESM}from"./chunk-JXWJOIH4.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2._timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name="AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_extend=__commonJS({"node_modules/extend/index.js"(exports,module){"use strict";var hasOwn2=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function(arr){return typeof Array.isArray=="function"?Array.isArray(arr):toStr.call(arr)==="[object Array]"},isPlainObject2=function(obj){if(!obj||toStr.call(obj)!=="[object Object]")return!1;var hasOwnConstructor=hasOwn2.call(obj,"constructor"),hasIsPrototypeOf=obj.constructor&&obj.constructor.prototype&&hasOwn2.call(obj.constructor.prototype,"isPrototypeOf");if(obj.constructor&&!hasOwnConstructor&&!hasIsPrototypeOf)return!1;var key;for(key in obj);return typeof key>"u"||hasOwn2.call(obj,key)},setProperty=function(target,options){defineProperty&&options.name==="__proto__"?defineProperty(target,options.name,{enumerable:!0,configurable:!0,value:options.newValue,writable:!0}):target[options.name]=options.newValue},getProperty=function(obj,name){if(name==="__proto__")if(hasOwn2.call(obj,name)){if(gOPD)return gOPD(obj,name).value}else return;return obj[name]};module.exports=function extend(){var options,name,src,copy,copyIsArray,clone,target=arguments[0],i=1,length=arguments.length,deep=!1;for(typeof target=="boolean"&&(deep=target,target=arguments[1]||{},i=2),(target==null||typeof target!="object"&&typeof target!="function")&&(target={});i<length;++i)if(options=arguments[i],options!=null)for(name in options)src=getProperty(target,name),copy=getProperty(options,name),target!==copy&&(deep&©&&(isPlainObject2(copy)||(copyIsArray=isArray(copy)))?(copyIsArray?(copyIsArray=!1,clone=src&&isArray(src)?src:[]):clone=src&&isPlainObject2(src)?src:{},setProperty(target,{name,newValue:extend(deep,clone,copy)})):typeof copy<"u"&&setProperty(target,{name,newValue:copy}));return target}}});var require_package=__commonJS({"node_modules/gaxios/package.json"(exports,module){module.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}});var require_util=__commonJS({"node_modules/gaxios/build/cjs/src/util.cjs"(exports,module){"use strict";var pkg=require_package();module.exports={pkg}}});var require_common=__commonJS({"node_modules/gaxios/build/cjs/src/common.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosError=exports.GAXIOS_ERROR_SYMBOL=void 0;exports.defaultErrorRedactor=defaultErrorRedactor;var extend_1=__importDefault(require_extend()),util_cjs_1=__importDefault(require_util()),pkg=util_cjs_1.default.pkg;exports.GAXIOS_ERROR_SYMBOL=Symbol.for(`${pkg.name}-gaxios-error`);var GaxiosError=class _GaxiosError extends Error{config;response;code;status;error;[exports.GAXIOS_ERROR_SYMBOL]=pkg.version;static[Symbol.hasInstance](instance){return instance&&typeof instance=="object"&&exports.GAXIOS_ERROR_SYMBOL in instance&&instance[exports.GAXIOS_ERROR_SYMBOL]===pkg.version?!0:Function.prototype[Symbol.hasInstance].call(_GaxiosError,instance)}constructor(message,config,response,cause){if(super(message,{cause}),this.config=config,this.response=response,this.error=cause instanceof Error?cause:void 0,this.config=(0,extend_1.default)(!0,{},config),this.response&&(this.response.config=(0,extend_1.default)(!0,{},this.response.config)),this.response){try{this.response.data=translateData(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}cause instanceof DOMException?this.code=cause.name:cause&&typeof cause=="object"&&"code"in cause&&(typeof cause.code=="string"||typeof cause.code=="number")&&(this.code=cause.code)}static extractAPIErrorFromResponse(res,defaultErrorMessage="The request failed"){let message=defaultErrorMessage;if(typeof res.data=="string"&&(message=res.data),res.data&&typeof res.data=="object"&&"error"in res.data&&res.data.error&&!res.ok){if(typeof res.data.error=="string")return{message:res.data.error,code:res.status,status:res.statusText};if(typeof res.data.error=="object"){message="message"in res.data.error&&typeof res.data.error.message=="string"?res.data.error.message:message;let status="status"in res.data.error&&typeof res.data.error.status=="string"?res.data.error.status:res.statusText,code="code"in res.data.error&&typeof res.data.error.code=="number"?res.data.error.code:res.status;if("errors"in res.data.error&&Array.isArray(res.data.error.errors)){let errorMessages=[];for(let e of res.data.error.errors)typeof e=="object"&&"message"in e&&typeof e.message=="string"&&errorMessages.push(e.message);return Object.assign({message:errorMessages.join(`
|
|
3
3
|
`)||message,code,status},res.data.error)}return Object.assign({message,code,status},res.data.error)}}return{message,code:res.status,status:res.statusText}}};exports.GaxiosError=GaxiosError;function translateData(responseType,data){switch(responseType){case"stream":return data;case"json":return JSON.parse(JSON.stringify(data));case"arraybuffer":return JSON.parse(Buffer.from(data).toString("utf8"));case"blob":return JSON.parse(data.text());default:return data}}function defaultErrorRedactor(data){let REDACT="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function redactHeaders(headers){headers&&headers.forEach((_,key)=>{(/^authentication$/i.test(key)||/^authorization$/i.test(key)||/secret/i.test(key))&&headers.set(key,REDACT)})}function redactString(obj,key){if(typeof obj=="object"&&obj!==null&&typeof obj[key]=="string"){let text=obj[key];(/grant_type=/i.test(text)||/assertion=/i.test(text)||/secret/i.test(text))&&(obj[key]=REDACT)}}function redactObject(obj){!obj||typeof obj!="object"||(obj instanceof FormData||obj instanceof URLSearchParams||"forEach"in obj&&"set"in obj?obj.forEach((_,key)=>{(["grant_type","assertion"].includes(key)||/secret/.test(key))&&obj.set(key,REDACT)}):("grant_type"in obj&&(obj.grant_type=REDACT),"assertion"in obj&&(obj.assertion=REDACT),"client_secret"in obj&&(obj.client_secret=REDACT)))}return data.config&&(redactHeaders(data.config.headers),redactString(data.config,"data"),redactObject(data.config.data),redactString(data.config,"body"),redactObject(data.config.body),data.config.url.searchParams.has("token")&&data.config.url.searchParams.set("token",REDACT),data.config.url.searchParams.has("client_secret")&&data.config.url.searchParams.set("client_secret",REDACT)),data.response&&(defaultErrorRedactor({config:data.response.config}),redactHeaders(data.response.headers),data.response.bodyUsed&&(redactString(data.response,"data"),redactObject(data.response.data))),data}}});var require_retry3=__commonJS({"node_modules/gaxios/build/cjs/src/retry.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getRetryConfig=getRetryConfig;async function getRetryConfig(err){let config=getConfig(err);if(!err||!err.config||!config&&!err.config.retry)return{shouldRetry:!1};config=config||{},config.currentRetryAttempt=config.currentRetryAttempt||0,config.retry=config.retry===void 0||config.retry===null?3:config.retry,config.httpMethodsToRetry=config.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],config.noResponseRetries=config.noResponseRetries===void 0||config.noResponseRetries===null?2:config.noResponseRetries,config.retryDelayMultiplier=config.retryDelayMultiplier?config.retryDelayMultiplier:2,config.timeOfFirstRequest=config.timeOfFirstRequest?config.timeOfFirstRequest:Date.now(),config.totalTimeout=config.totalTimeout?config.totalTimeout:Number.MAX_SAFE_INTEGER,config.maxRetryDelay=config.maxRetryDelay?config.maxRetryDelay:Number.MAX_SAFE_INTEGER;let retryRanges=[[100,199],[408,408],[429,429],[500,599]];if(config.statusCodesToRetry=config.statusCodesToRetry||retryRanges,err.config.retryConfig=config,!await(config.shouldRetry||shouldRetryRequest)(err))return{shouldRetry:!1,config:err.config};let delay2=getNextRetryDelay(config);err.config.retryConfig.currentRetryAttempt+=1;let backoff=config.retryBackoff?config.retryBackoff(err,delay2):new Promise(resolve=>{setTimeout(resolve,delay2)});return config.onRetryAttempt&&await config.onRetryAttempt(err),await backoff,{shouldRetry:!0,config:err.config}}function shouldRetryRequest(err){let config=getConfig(err);if(err.config.signal?.aborted&&err.code!=="TimeoutError"||err.code==="AbortError"||!config||config.retry===0||!err.response&&(config.currentRetryAttempt||0)>=config.noResponseRetries||!config.httpMethodsToRetry||!config.httpMethodsToRetry.includes(err.config.method?.toUpperCase()||"GET"))return!1;if(err.response&&err.response.status){let isInRange=!1;for(let[min,max]of config.statusCodesToRetry){let status=err.response.status;if(status>=min&&status<=max){isInRange=!0;break}}if(!isInRange)return!1}return config.currentRetryAttempt=config.currentRetryAttempt||0,!(config.currentRetryAttempt>=config.retry)}function getConfig(err){if(err&&err.config&&err.config.retryConfig)return err.config.retryConfig}function getNextRetryDelay(config){let calculatedDelay=(config.currentRetryAttempt?0:config.retryDelay??100)+(Math.pow(config.retryDelayMultiplier,config.currentRetryAttempt)-1)/2*1e3,maxAllowableDelay=config.totalTimeout-(Date.now()-config.timeOfFirstRequest);return Math.min(calculatedDelay,maxAllowableDelay,config.maxRetryDelay)}}});var require_interceptor=__commonJS({"node_modules/gaxios/build/cjs/src/interceptor.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosInterceptorManager=void 0;var GaxiosInterceptorManager=class extends Set{};exports.GaxiosInterceptorManager=GaxiosInterceptorManager}});var require_gaxios=__commonJS({"node_modules/gaxios/build/cjs/src/gaxios.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}},_a2;Object.defineProperty(exports,"__esModule",{value:!0});exports.Gaxios=void 0;var extend_1=__importDefault(require_extend()),https_1=__require("https"),common_js_1=require_common(),retry_js_1=require_retry3(),stream_1=__require("stream"),interceptor_js_1=require_interceptor(),randomUUID=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),HTTP_STATUS_NO_CONTENT=204,Gaxios=class{agentCache=new Map;defaults;interceptors;constructor(defaults){this.defaults=defaults||{},this.interceptors={request:new interceptor_js_1.GaxiosInterceptorManager,response:new interceptor_js_1.GaxiosInterceptorManager}}fetch(...args){let input=args[0],init=args[1],url,headers=new Headers;return typeof input=="string"?url=new URL(input):input instanceof URL?url=input:input&&input.url&&(url=new URL(input.url)),input&&typeof input=="object"&&"headers"in input&&_a2.mergeHeaders(headers,input.headers),init&&_a2.mergeHeaders(headers,new Headers(init.headers)),typeof input=="object"&&!(input instanceof URL)?this.request({...init,...input,headers,url}):this.request({...init,headers,url})}async request(opts={}){let prepared=await this.#prepareRequest(opts);return prepared=await this.#applyRequestInterceptors(prepared),this.#applyResponseInterceptors(this._request(prepared))}async _defaultAdapter(config){let fetchImpl=config.fetchImplementation||this.defaults.fetchImplementation||await _a2.#getFetch(),preparedOpts={...config};delete preparedOpts.data;let res=await fetchImpl(config.url,preparedOpts),data=await this.getResponseData(config,res);return Object.getOwnPropertyDescriptor(res,"data")?.configurable||Object.defineProperties(res,{data:{configurable:!0,writable:!0,enumerable:!0,value:data}}),Object.assign(res,{config,data})}async _request(opts){try{let translatedResponse;if(opts.adapter?translatedResponse=await opts.adapter(opts,this._defaultAdapter.bind(this)):translatedResponse=await this._defaultAdapter(opts),!opts.validateStatus(translatedResponse.status)){if(opts.responseType==="stream"){let response=[];for await(let chunk of translatedResponse.data)response.push(chunk);translatedResponse.data=response.toString()}let errorInfo=common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse,`Request failed with status code ${translatedResponse.status}`);throw new common_js_1.GaxiosError(errorInfo?.message,opts,translatedResponse,errorInfo)}return translatedResponse}catch(e){let err;e instanceof common_js_1.GaxiosError?err=e:e instanceof Error?err=new common_js_1.GaxiosError(e.message,opts,void 0,e):err=new common_js_1.GaxiosError("Unexpected Gaxios Error",opts,void 0,e);let{shouldRetry,config}=await(0,retry_js_1.getRetryConfig)(err);if(shouldRetry&&config)return err.config.retryConfig.currentRetryAttempt=config.retryConfig.currentRetryAttempt,opts.retryConfig=err.config?.retryConfig,this.#appendTimeoutToSignal(opts),this._request(opts);throw opts.errorRedactor&&opts.errorRedactor(err),err}}async getResponseData(opts,res){if(res.status===HTTP_STATUS_NO_CONTENT)return"";if(opts.maxContentLength&&res.headers.has("content-length")&&opts.maxContentLength<Number.parseInt(res.headers?.get("content-length")||""))throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.",opts,Object.assign(res,{config:opts}));switch(opts.responseType){case"stream":return res.body;case"json":{let data=await res.text();try{return JSON.parse(data)}catch{return data}}case"arraybuffer":return res.arrayBuffer();case"blob":return res.blob();case"text":return res.text();default:return this.getResponseDataFromContentType(res)}}#urlMayUseProxy(url,noProxy=[]){let candidate=new URL(url),noProxyList=[...noProxy],noProxyEnvList=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let rule of noProxyEnvList)noProxyList.push(rule.trim());for(let rule of noProxyList)if(rule instanceof RegExp){if(rule.test(candidate.toString()))return!1}else if(rule instanceof URL){if(rule.origin===candidate.origin)return!1}else if(rule.startsWith("*.")||rule.startsWith(".")){let cleanedRule=rule.replace(/^\*\./,".");if(candidate.hostname.endsWith(cleanedRule))return!1}else if(rule===candidate.origin||rule===candidate.hostname||rule===candidate.href)return!1;return!0}async#applyRequestInterceptors(options){let promiseChain=Promise.resolve(options);for(let interceptor of this.interceptors.request.values())interceptor&&(promiseChain=promiseChain.then(interceptor.resolved,interceptor.rejected));return promiseChain}async#applyResponseInterceptors(response){let promiseChain=Promise.resolve(response);for(let interceptor of this.interceptors.response.values())interceptor&&(promiseChain=promiseChain.then(interceptor.resolved,interceptor.rejected));return promiseChain}async#prepareRequest(options){let preparedHeaders=new Headers(this.defaults.headers);_a2.mergeHeaders(preparedHeaders,options.headers);let opts=(0,extend_1.default)(!0,{},this.defaults,options);if(!opts.url)throw new Error("URL is required.");if(opts.baseURL&&(opts.url=new URL(opts.url,opts.baseURL)),opts.url=new URL(opts.url),opts.params)if(opts.paramsSerializer){let additionalQueryParams=opts.paramsSerializer(opts.params);additionalQueryParams.startsWith("?")&&(additionalQueryParams=additionalQueryParams.slice(1));let prefix=opts.url.toString().includes("?")?"&":"?";opts.url=opts.url+prefix+additionalQueryParams}else{let url=opts.url instanceof URL?opts.url:new URL(opts.url);for(let[key,value]of new URLSearchParams(opts.params))url.searchParams.append(key,value);opts.url=url}typeof options.maxContentLength=="number"&&(opts.size=options.maxContentLength),typeof options.maxRedirects=="number"&&(opts.follow=options.maxRedirects);let shouldDirectlyPassData=typeof opts.data=="string"||opts.data instanceof ArrayBuffer||opts.data instanceof Blob||globalThis.File&&opts.data instanceof File||opts.data instanceof FormData||opts.data instanceof stream_1.Readable||opts.data instanceof ReadableStream||opts.data instanceof String||opts.data instanceof URLSearchParams||ArrayBuffer.isView(opts.data)||["Blob","File","FormData"].includes(opts.data?.constructor?.name||"");if(opts.multipart?.length){let boundary=await randomUUID();preparedHeaders.set("content-type",`multipart/related; boundary=${boundary}`),opts.body=stream_1.Readable.from(this.getMultipartRequest(opts.multipart,boundary))}else shouldDirectlyPassData?opts.body=opts.data:typeof opts.data=="object"?preparedHeaders.get("Content-Type")==="application/x-www-form-urlencoded"?opts.body=opts.paramsSerializer?opts.paramsSerializer(opts.data):new URLSearchParams(opts.data):(preparedHeaders.has("content-type")||preparedHeaders.set("content-type","application/json"),opts.body=JSON.stringify(opts.data)):opts.data&&(opts.body=opts.data);opts.validateStatus=opts.validateStatus||this.validateStatus,opts.responseType=opts.responseType||"unknown",!preparedHeaders.has("accept")&&opts.responseType==="json"&&preparedHeaders.set("accept","application/json");let proxy=opts.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!opts.agent)if(proxy&&this.#urlMayUseProxy(opts.url,opts.noProxy)){let HttpsProxyAgent=await _a2.#getProxyAgent();this.agentCache.has(proxy)?opts.agent=this.agentCache.get(proxy):(opts.agent=new HttpsProxyAgent(proxy,{cert:opts.cert,key:opts.key}),this.agentCache.set(proxy,opts.agent))}else opts.cert&&opts.key&&(this.agentCache.has(opts.key)?opts.agent=this.agentCache.get(opts.key):(opts.agent=new https_1.Agent({cert:opts.cert,key:opts.key}),this.agentCache.set(opts.key,opts.agent)));return typeof opts.errorRedactor!="function"&&opts.errorRedactor!==!1&&(opts.errorRedactor=common_js_1.defaultErrorRedactor),opts.body&&!("duplex"in opts)&&(opts.duplex="half"),this.#appendTimeoutToSignal(opts),Object.assign(opts,{headers:preparedHeaders,url:opts.url instanceof URL?opts.url:new URL(opts.url)})}#appendTimeoutToSignal(opts){if(opts.timeout){let timeoutSignal=AbortSignal.timeout(opts.timeout);opts.signal&&!opts.signal.aborted?opts.signal=AbortSignal.any([opts.signal,timeoutSignal]):opts.signal=timeoutSignal}}validateStatus(status){return status>=200&&status<300}async getResponseDataFromContentType(response){let contentType=response.headers.get("Content-Type");if(contentType===null)return response.text();if(contentType=contentType.toLowerCase(),contentType.includes("application/json")){let data=await response.text();try{data=JSON.parse(data)}catch{}return data}else return contentType.match(/^text\//)?response.text():response.blob()}async*getMultipartRequest(multipartOptions,boundary){let finale=`--${boundary}--`;for(let currentPart of multipartOptions){let partContentType=currentPart.headers.get("Content-Type")||"application/octet-stream";yield`--${boundary}\r
|
|
4
4
|
Content-Type: ${partContentType}\r
|
|
5
5
|
\r
|
|
@@ -42,4 +42,4 @@ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Go
|
|
|
42
42
|
`:". ";let bodyDisplay=body;if(body.length>1e4){let truncated=body.substring(0,1e4),remaining=body.length-1e4;bodyDisplay=`${truncated}...and ${remaining} more chars`}message+=`Body: ${bodyDisplay}`,message=message.trim(),super(message,httpMeta),this.name="GoogleGenAiDefaultError"}};function tryParseJson(s){try{return JSON.parse(s)}catch{return s}}function wrapEventStreamResponse(body,opts={}){var _a2,_b;let flattened=opts.flattened===!0,sentinel=(_a2=opts.sentinel)!==null&&_a2!==void 0?_a2:"";return new Stream(body,rawEvent=>sentinel!==""&&rawEvent.data===sentinel?{done:!0,value:void 0}:flattened?{done:!1,value:rawEvent.data==null?void 0:tryParseJson(rawEvent.data)}:{done:!1,value:Object.assign(Object.assign({},rawEvent),{data:rawEvent.data==null?rawEvent.data:tryParseJson(rawEvent.data)})},{dataRequired:(_b=opts.dataRequired)!==null&&_b!==void 0?_b:!0})}var Stream=class extends ReadableStream{constructor(responseBody,parse,opts){var _a2;let upstream=responseBody.getReader(),buffer=new Uint8Array(4096),bufferLen=0,searchStart=0,state={eventId:void 0},dataRequired=(_a2=opts?.dataRequired)!==null&&_a2!==void 0?_a2:!0;super({async pull(downstream){try{for(;;){let match2=findBoundary(buffer,bufferLen,searchStart);if(!match2){searchStart=Math.max(0,bufferLen-MAX_BOUNDARY_LEN+1);let chunk=await upstream.read();if(chunk.done)return downstream.close();if(bufferLen+chunk.value.length>buffer.length){let grown=new Uint8Array(Math.max(buffer.length*2,bufferLen+chunk.value.length));grown.set(buffer.subarray(0,bufferLen)),buffer=grown}buffer.set(chunk.value,bufferLen),bufferLen+=chunk.value.length;continue}let message=buffer.slice(0,match2.index);if(buffer.copyWithin(0,match2.index+match2.length,bufferLen),bufferLen-=match2.index+match2.length,buffer.length>4096&&bufferLen<=buffer.length>>2){let shrunk=new Uint8Array(Math.max(4096,bufferLen*2));shrunk.set(buffer.subarray(0,bufferLen)),buffer=shrunk}searchStart=0;let item=parseMessage(message,parse,state,dataRequired);if(item&&!item.done)return downstream.enqueue(item.value);if(item?.done)return await upstream.cancel("done"),downstream.close()}}catch(e){downstream.error(e),await upstream.cancel(e)}},cancel:reason=>upstream.cancel(reason)})}[Symbol.asyncIterator](options){let fn=ReadableStream.prototype[Symbol.asyncIterator];if(typeof fn=="function")return fn.call(this,options);let reader=this.getReader(),iterator={next:async()=>{let r=await reader.read();return r.done?(reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:r.value}},throw:async e=>(await reader.cancel(e),reader.releaseLock(),{done:!0,value:void 0}),return:async()=>(await reader.cancel("done"),reader.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},asyncDispose=Symbol.asyncDispose;return asyncDispose&&(iterator[asyncDispose]=async()=>{var _a2;await((_a2=iterator.return)===null||_a2===void 0?void 0:_a2.call(iterator))}),iterator}values(options){return this[Symbol.asyncIterator](options)}},CR=13,LF=10,BOUNDARIES=[[CR,LF,CR,LF],[CR,LF,CR],[CR,LF,LF],[CR,CR,LF],[LF,CR,LF],[CR,CR],[LF,CR],[LF,LF]],MAX_BOUNDARY_LEN=BOUNDARIES.reduce((m,b)=>Math.max(m,b.length),0);function findBoundary(buf,len,from){for(let i=from;i<len;i++)if(!(buf[i]!==CR&&buf[i]!==LF))for(let boundary of BOUNDARIES){if(i+boundary.length>len)continue;let match2=!0;for(let j=0;j<boundary.length;j++)if(buf[i+j]!==boundary[j]){match2=!1;break}if(match2)return{index:i,length:boundary.length}}return null}function parseMessage(chunk,parse,state,dataRequired){let lines=new TextDecoder().decode(chunk).split(/\r\n|\r|\n/),dataLines=[],ret={},ignore=!0;for(let line of lines){if(!line||line.startsWith(":"))continue;ignore=!1;let i=line.indexOf(":"),field=line,value="";i>0&&(field=line.slice(0,i),value=line[i+1]===" "?line.slice(i+2):line.slice(i+1)),field==="data"?dataLines.push(value):field==="event"?ret.event=value:field==="id"&&!value.includes("\0")?state.eventId=value:field==="retry"&&/^\d+$/.test(value)&&(ret.retry=Number(value))}if(!ignore){if(ret.id=state.eventId,dataLines.length)ret.data=dataLines.join(`
|
|
43
43
|
`);else if(dataRequired)return;return parse(ret)}}var DEFAULT_CONTENT_TYPES={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function jsonErr(codes,errorClass,options){return Object.assign(Object.assign({},options),{err:!0,enc:"json",codes,errorClass})}function json(codes,options){return Object.assign(Object.assign({},options),{enc:"json",codes})}function sse(codes,sse2,options){return Object.assign(Object.assign(Object.assign({},options),{enc:"sse",codes}),sse2?{sse:sse2}:{})}function nil(codes,options){return Object.assign(Object.assign({},options),{enc:"nil",codes})}function fail(codes){return{enc:"fail",codes}}function match(...matchers){return async function(response,request,options){let raw,matcher;for(let match2 of matchers){let{codes}=match2,ctpattern="ctype"in match2?match2.ctype:DEFAULT_CONTENT_TYPES[match2.enc];if(ctpattern&&matchResponse(response,codes,ctpattern)){matcher=match2;break}else if(!ctpattern&&matchStatusCode(response,codes)){matcher=match2;break}}if(!matcher)return[{ok:!1,error:new GoogleGenAiDefaultError("Unexpected Status or Content-Type",{response,request,body:await response.text().catch(()=>"")})},raw];let encoding=matcher.enc,body="";switch(encoding){case"json":body=await response.text();try{raw=JSON.parse(body)}catch(err){if(!("err"in matcher))throw err;raw=body}break;case"jsonl":raw=response.body;break;case"bytes":raw=new Uint8Array(await response.arrayBuffer());break;case"stream":raw=response.body;break;case"text":body=await response.text(),raw=body;break;case"sse":if(response.body){let sseOpts="sse"in matcher&&matcher.sse||{};raw=wrapEventStreamResponse(response.body,sseOpts)}else raw=null;break;case"nil":body=await response.text(),raw=void 0;break;case"fail":body=await response.text(),raw=body;break;default:throw new Error(`Unsupported response type: ${encoding}`)}if(matcher.enc==="fail")return[{ok:!1,error:new GoogleGenAiDefaultError("API error occurred",{request,response,body})},raw];let resultKey=matcher.key||options?.resultKey,data,headersField=matcher.hdrs?{headers:unpackHeaders(response.headers)}:null;return"err"in matcher?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),isPlainObject$1(raw)?raw:null):resultKey?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),{[resultKey]:raw}):matcher.hdrs?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),isPlainObject$1(raw)?raw:null):data=raw,"err"in matcher?[{ok:!1,error:matcher.errorClass?new matcher.errorClass(data,{request,response,body}):data},raw]:[{ok:!0,value:data},raw]}}var headerValRE=/, */;function unpackHeaders(headers){let out={};for(let[k,v]of headers.entries())out[k]=v.split(headerValRE);return out}var SecurityErrorCode={Incomplete:"incomplete",UnrecognisedSecurityType:"unrecognized_security_type"},SecurityError=class _SecurityError extends Error{constructor(code,message){super(message),this.code=code,this.name="SecurityError"}static incomplete(){return new _SecurityError(SecurityErrorCode.Incomplete,"Security requirements not met in order to perform the operation")}static unrecognizedType(type){return new _SecurityError(SecurityErrorCode.UnrecognisedSecurityType,`Unrecognised security type: ${type}`)}};function resolveSecurity(...options){let state={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},option=options.find(opts=>opts.every(o=>{if(o.value==null)return!1;if(o.type==="http:basic")return o.value.username!=null||o.value.password!=null;if(o.type==="http:custom")return null;if(o.type==="oauth2:password")return typeof o.value=="string"&&!!o.value;if(o.type==="oauth2:client_credentials")return typeof o.value=="string"?!!o.value:o.value.client_id!=null||o.value.client_secret!=null;if(typeof o.value=="string")return!!o.value;throw new Error(`Unrecognized security type: ${o.type} (value type: ${typeof o.value})`)}));return option==null?null:(option.forEach(spec=>{if(spec.value==null)return;let{type}=spec;switch(type){case"apiKey:header":state.headers[spec.fieldName]=spec.value;break;case"apiKey:query":state.queryParams[spec.fieldName]=spec.value;break;case"apiKey:cookie":state.cookies[spec.fieldName]=spec.value;break;case"http:basic":applyBasic(state,spec);break;case"http:custom":break;case"http:bearer":applyBearer(state,spec);break;case"oauth2":applyBearer(state,spec);break;case"oauth2:password":applyBearer(state,spec);break;case"oauth2:client_credentials":break;case"openIdConnect":applyBearer(state,spec);break;default:throw SecurityError.unrecognizedType(type)}}),state)}function applyBasic(state,spec){spec.value!=null&&(state.basic=spec.value)}function applyBearer(state,spec){if(typeof spec.value!="string"||!spec.value)return;let value=spec.value;value.slice(0,7).toLowerCase()!=="bearer "&&(value=`Bearer ${value}`),spec.fieldName!==void 0&&(state.headers[spec.fieldName]=value)}function resolveGlobalSecurity(security,allowedFields){var _a2,_b;let inputs=[[{fieldName:"accessToken",type:"http:custom",value:(_a2=security?.access_token)!==null&&_a2!==void 0?_a2:env().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:(_b=security?.api_key)!==null&&_b!==void 0?_b:env().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:security?.default_headers}]];return resolveSecurity(...inputs)}async function extractSecurity(sec){if(sec!=null)return typeof sec=="function"?sec():sec}var _a,APIPromise=class _APIPromise{constructor(p,callSource){this[_a]="APIPromise",this._promise=p instanceof Promise?p:Promise.resolve(p),this._unwrapped=p instanceof Promise?null:Promise.resolve(p[0]),this._callSource=callSource??null}_getUnwrapped(){var _b;return(_b=this._unwrapped)!==null&&_b!==void 0?_b:this._unwrapped=this._promise.then(([value])=>value)}then(onfulfilled,onrejected){return this._promise.then(onfulfilled?([value])=>onfulfilled(value):void 0,onrejected)}catch(onrejected){return this._getUnwrapped().catch(onrejected)}finally(onfinally){return this._getUnwrapped().finally(onfinally)}$inspect(){return this._promise}asResponse(){var _b;return((_b=this._callSource)!==null&&_b!==void 0?_b:this._callSource=this._promise.then(([,call])=>call)).then(call=>{if(!call.response)throw new Error("APIPromise.asResponse: response unavailable");return call.response})}async withResponse(){let[[data],response]=await Promise.all([this._promise,this.asResponse()]);return{data,response}}_thenUnwrap(transform){var _b;let data=this._promise.then(([value,call])=>[transform(value),call]);return data.catch(()=>{}),new _APIPromise(data,(_b=this._callSource)!==null&&_b!==void 0?_b:void 0)}};_a=Symbol.toStringTag;function unwrapAsAPIPromise(p){let inner=p.$inspect(),data=inner.then(([r,call])=>{if(!r.ok)throw r.error;return[r.value,call]}),callSource=inner.then(([r,call])=>{var _b;if(!r.ok&&!(!((_b=call.response)===null||_b===void 0)&&_b.ok))throw r.error;return call});return data.catch(()=>{}),callSource.catch(()=>{}),new APIPromise(data,callSource)}function agentsCreate(client,body,api_version,options){return new APIPromise($do$q(client,body,api_version,options))}async function $do$q(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsDelete(client,id,api_version,options){return new APIPromise($do$p(client,id,api_version,options))}async function $do$p(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsGet(client,id,api_version,options){return new APIPromise($do$o(client,id,api_version,options))}async function $do$o(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsList(client,api_version,page_size,page_token,parent,options){return new APIPromise($do$n(client,api_version,page_size,page_token,parent,options))}async function $do$n(client,api_version,page_size,page_token,parent,options){var _a2,_b,_c;let payload={api_version,page_size,page_token,parent},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token,parent:payload?.parent}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Agents=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(agentsList(this,params?.api_version,params?.page_size,params?.page_token,params?.parent,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(agentsCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(agentsDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(agentsGet(this,id,params?.api_version,options))}};function environmentsCreateEnvironment(client,body,api_version,options){return new APIPromise($do$m(client,body,api_version,options))}async function $do$m(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsDeleteEnvironment(client,id,api_version,options){return new APIPromise($do$l(client,id,api_version,options))}async function $do$l(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsGetEnvironment(client,id,api_version,options){return new APIPromise($do$k(client,id,api_version,options))}async function $do$k(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsListEnvironments(client,api_version,page_size,page_token,options){return new APIPromise($do$j(client,api_version,page_size,page_token,options))}async function $do$j(client,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsFilesList(client,environment,path2,api_version,page_size,page_token,recursive,options){return new APIPromise($do$i(client,environment,path2,api_version,page_size,page_token,recursive,options))}async function $do$i(client,environment,path2,api_version,page_size,page_token,recursive,options){var _a2,_b,_c;let payload={environment,path:path2,api_version,page_size,page_token,recursive},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),environment:encodeSimple("environment",payload.environment,{explode:!1,charEncoding:"percent"}),path:encodeSimple("path",payload.path,{explode:!1,charEncoding:"percent"})},path$=pathToFunc("/{api_version}/environments/{environment}/files/{path}")(pathParams),query=encodeFormQuery({page_size:payload.page_size,page_token:payload.page_token,recursive:payload.recursive}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path$,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Files2=class extends ClientSDK{list(environment,path2,params,options){return unwrapAsAPIPromise(environmentsFilesList(this,environment,path2,params?.api_version,params?.page_size,params?.page_token,params?.recursive,options))}};var Environments=class extends ClientSDK{get files(){var _a2;return(_a2=this._files)!==null&&_a2!==void 0?_a2:this._files=new Files2(this._options)}listEnvironments(params,options){return unwrapAsAPIPromise(environmentsListEnvironments(this,params?.api_version,params?.page_size,params?.page_token,options))}createEnvironment(body,api_version,options){return unwrapAsAPIPromise(environmentsCreateEnvironment(this,body,api_version,options))}deleteEnvironment(id,params,options){return unwrapAsAPIPromise(environmentsDeleteEnvironment(this,id,params?.api_version,options))}getEnvironment(id,params,options){return unwrapAsAPIPromise(environmentsGetEnvironment(this,id,params?.api_version,options))}};var CancelInteractionByIdServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CancelInteractionByIdServerError"}},CancelInteractionByIdClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CancelInteractionByIdClientError"}};var CreateInteractionServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CreateInteractionServerError"}},CreateInteractionClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CreateInteractionClientError"}};var DeleteInteractionServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="DeleteInteractionServerError"}},DeleteInteractionClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="DeleteInteractionClientError"}};var GetInteractionByIdServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="GetInteractionByIdServerError"}},GetInteractionByIdClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="GetInteractionByIdClientError"}};function interactionsCancel(client,id,api_version,options){return new APIPromise($do$h(client,id,api_version,options))}async function $do$h(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}/cancel")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),jsonErr("4XX",CancelInteractionByIdClientError),jsonErr("5XX",CancelInteractionByIdServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsCreate(client,body,api_version,options){return new APIPromise($do$g(client,body,api_version,options))}async function $do$g(client,body,api_version,options){var _a2,_b,_c,_d;let input={body,api_version},payload=input,body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:!((_b=input?.body)===null||_b===void 0)&&_b.stream?"text/event-stream":"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_d=(_c=options?.server_url)!==null&&_c!==void 0?_c:client._baseURL)!==null&&_d!==void 0?_d:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),sse(200,{sentinel:"[DONE]",flattened:!0}),jsonErr("4XX",CreateInteractionClientError),jsonErr("5XX",CreateInteractionServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsDelete(client,id,api_version,options){return new APIPromise($do$f(client,id,api_version,options))}async function $do$f(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(nil(200),jsonErr("4XX",DeleteInteractionClientError),jsonErr("5XX",DeleteInteractionServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsGet(client,id,api_version,include_input,last_event_id,stream,options){return new APIPromise($do$e(client,id,api_version,include_input,last_event_id,stream,options))}async function $do$e(client,id,api_version,include_input,last_event_id,stream,options){var _a2,_b,_c;let input={id,api_version,include_input,last_event_id,stream},payload=input,body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}")(pathParams),query=encodeFormQuery({include_input:payload.include_input,last_event_id:payload.last_event_id,stream:payload.stream}),headers=new Headers(compactMap({Accept:input?.stream?"text/event-stream":"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),sse(200,{sentinel:"[DONE]",flattened:!0}),jsonErr("4XX",GetInteractionByIdClientError),jsonErr("5XX",GetInteractionByIdServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Interactions=class extends ClientSDK{create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(interactionsCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(interactionsDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(interactionsGet(this,id,params?.api_version,params?.include_input,params?.last_event_id,params?.stream,options))}cancel(id,params,options){return unwrapAsAPIPromise(interactionsCancel(this,id,params?.api_version,options))}};function triggersCreate(client,body,api_version,options){return new APIPromise($do$d(client,body,api_version,options))}async function $do$d(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersDelete(client,id,api_version,options){return new APIPromise($do$c(client,id,api_version,options))}async function $do$c(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersGet(client,id,api_version,options){return new APIPromise($do$b(client,id,api_version,options))}async function $do$b(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersListExecutions(client,trigger_id,api_version,page_size,page_token,options){return new APIPromise($do$a(client,trigger_id,api_version,page_size,page_token,options))}async function $do$a(client,trigger_id,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={trigger_id,api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:encodeSimple("trigger_id",payload.trigger_id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{trigger_id}/executions")(pathParams),query=encodeFormQuery({page_size:payload.page_size,page_token:payload.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersList(client,api_version,filter,page_size,page_token,options){return new APIPromise($do$9(client,api_version,filter,page_size,page_token,options))}async function $do$9(client,api_version,filter,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,filter,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers")(pathParams),query=encodeFormQuery({filter:payload?.filter,page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersRun(client,trigger_id,api_version,options){return new APIPromise($do$8(client,trigger_id,api_version,options))}async function $do$8(client,trigger_id,api_version,options){var _a2,_b,_c;let payload={trigger_id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:encodeSimple("trigger_id",payload.trigger_id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{trigger_id}/executions")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersUpdate(client,id,body,api_version,options){return new APIPromise($do$7(client,id,body,api_version,options))}async function $do$7(client,id,body,api_version,options){var _a2,_b,_c;let payload={id,body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"PATCH",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Triggers=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(triggersList(this,params?.api_version,params?.filter,params?.page_size,params?.page_token,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(triggersCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(triggersDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(triggersGet(this,id,params?.api_version,options))}update(id,params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(triggersUpdate(this,id,body,api_version,options))}listExecutions(trigger_id,params,options){return unwrapAsAPIPromise(triggersListExecutions(this,trigger_id,params?.api_version,params?.page_size,params?.page_token,options))}run(trigger_id,params,options){return unwrapAsAPIPromise(triggersRun(this,trigger_id,params?.api_version,options))}};function webhooksCreate(client,body,api_version,options){return new APIPromise($do$6(client,body,api_version,options))}async function $do$6(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksDelete(client,id,api_version,options){return new APIPromise($do$5(client,id,api_version,options))}async function $do$5(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksGet(client,id,api_version,options){return new APIPromise($do$4(client,id,api_version,options))}async function $do$4(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksList(client,api_version,page_size,page_token,options){return new APIPromise($do$3(client,api_version,page_size,page_token,options))}async function $do$3(client,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksPing(client,id,api_version,body,options){return new APIPromise($do$2(client,id,api_version,body,options))}async function $do$2(client,id,api_version,body,options){var _a2,_b,_c;let payload={id,api_version,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}:ping")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksRotateSigningSecret(client,id,api_version,body,options){return new APIPromise($do$1(client,id,api_version,body,options))}async function $do$1(client,id,api_version,body,options){var _a2,_b,_c;let payload={id,api_version,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}:rotateSigningSecret")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksUpdate(client,id,api_version,update_mask,body,options){return new APIPromise($do(client,id,api_version,update_mask,body,options))}async function $do(client,id,api_version,update_mask,body,options){var _a2,_b,_c;let payload={id,api_version,update_mask,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),query=encodeFormQuery({update_mask:payload.update_mask}),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"PATCH",baseURL:options?.server_url,path:path2,headers,query,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Webhooks=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(webhooksList(this,params?.api_version,params?.page_size,params?.page_token,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(webhooksCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(webhooksDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(webhooksGet(this,id,params?.api_version,options))}update(id,params,options){let _a2=params??{},{api_version,update_mask}=_a2,body$body=__rest(_a2,["api_version","update_mask"]),body=params===void 0||Object.keys(body$body).length===0?void 0:body$body;return unwrapAsAPIPromise(webhooksUpdate(this,id,api_version,update_mask,body,options))}ping(id,api_version,body,options){return unwrapAsAPIPromise(webhooksPing(this,id,api_version,body,options))}rotateSigningSecret(id,api_version,body,options){return unwrapAsAPIPromise(webhooksRotateSigningSecret(this,id,api_version,body,options))}};var GoogleGenAI$1=class extends ClientSDK{get agents(){var _a2;return(_a2=this._agents)!==null&&_a2!==void 0?_a2:this._agents=new Agents(this._options)}get environments(){var _a2;return(_a2=this._environments)!==null&&_a2!==void 0?_a2:this._environments=new Environments(this._options)}get interactions(){var _a2;return(_a2=this._interactions)!==null&&_a2!==void 0?_a2:this._interactions=new Interactions(this._options)}get triggers(){var _a2;return(_a2=this._triggers)!==null&&_a2!==void 0?_a2:this._triggers=new Triggers(this._options)}get webhooks(){var _a2;return(_a2=this._webhooks)!==null&&_a2!==void 0?_a2:this._webhooks=new Webhooks(this._options)}};var LEGACY_LYRIA_MODELS=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function getGoogleGenAIServerURL(parentClient){let serverURL=parentClient.getBaseUrl();if(!serverURL)throw new Error("Base URL must be set.");return serverURL.replace(/\/+$/,"")}function getGoogleGenAIAPIVersion(parentClient){let apiVersion=trimSlashes(parentClient.getApiVersion()),project=parentClient.getProject(),location=parentClient.getLocation();return parentClient.isVertexAI()&&apiVersion&&project&&location?`${apiVersion}/projects/${encodeURIComponent(project)}/locations/${encodeURIComponent(location)}`:apiVersion}function buildGoogleGenAIClient(parentClient,options={}){var _a2,_b,_c,_d,_e;return new GoogleGenAI$1(Object.assign(Object.assign({},options),{api_version:(_a2=options.api_version)!==null&&_a2!==void 0?_a2:getGoogleGenAIAPIVersion(parentClient),security:(_b=options.security)!==null&&_b!==void 0?_b:new GoogleGenAISecurityProvider({defaultHeaders:Object.assign(Object.assign({},(_c=parentClient.getDefaultHeaders)===null||_c===void 0?void 0:_c.call(parentClient)),(_d=parentClient.getHeaders)===null||_d===void 0?void 0:_d.call(parentClient)),getAuthHeaders:url=>parentClient.getAuthHeaders(url)}),server_url:(_e=options.server_url)!==null&&_e!==void 0?_e:getGoogleGenAIServerURL(parentClient)}))}var GeminiNextGenInteractions=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,request=__rest(params,["api_version"]);if(request.stream===!0){let response2=await wrapSDKCall(()=>this.getClient(api_version).interactions.create(Object.assign(Object.assign({},request),{stream:!0,api_version}),toGoogleGenAIRequestOptions(options,!0)));return wrapStreamErrors(response2)}let response=await unwrapWithSdkHttpResponse(interactionsCreate(this.getClient(api_version),request,api_version,toGoogleGenAIRequestOptions(options)));return addOutputPropertiesIfInteraction(response)}async get(id,params={},options){let{api_version,stream=!1,last_event_id,include_input}=params??{};if(stream===!0){let response2=await wrapSDKCall(()=>this.getClient(api_version).interactions.get(id,{stream,last_event_id,include_input,api_version},toGoogleGenAIRequestOptions(options,!0)));return wrapStreamErrors(response2)}let response=await unwrapWithSdkHttpResponse(interactionsGet(this.getClient(api_version),id,api_version,include_input,last_event_id,stream,toGoogleGenAIRequestOptions(options)));return addOutputPropertiesIfInteraction(response)}async delete(id,params={},options){return wrapSDKCall(()=>this.getClient(params?.api_version).interactions.delete(id,{api_version:params?.api_version},toGoogleGenAIRequestOptions(options)))}async cancel(id,params={},options){return addOutputPropertiesIfInteraction(await unwrapWithSdkHttpResponse(interactionsCancel(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options))))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenAgents=class{constructor(parentClient){this.parentClient=parentClient}async create(params={},options){let _a2=params??{},{api_version}=_a2,body=__rest(_a2,["api_version"]);return unwrapWithSdkHttpResponse(agentsCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,pageSize,pageToken,parent}=params??{};return unwrapWithSdkHttpResponse(agentsList(this.getClient(api_version),api_version,pageSize,pageToken,parent,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(agentsGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(agentsDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenWebhooks=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(webhooksCreate(this.getClient(),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(webhooksList(this.getClient(),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(webhooksGet(this.getClient(),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params={},options){let _a2=params??{},{api_version,update_mask}=_a2,body=__rest(_a2,["api_version","update_mask"]);return unwrapWithSdkHttpResponse(webhooksUpdate(this.getClient(),id,api_version,update_mask,body,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(webhooksDelete(this.getClient(),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async rotateSigningSecret(id,params={},options){let _a2=params??{},{api_version}=_a2,body=__rest(_a2,["api_version"]);return unwrapWithSdkHttpResponse(webhooksRotateSigningSecret(this.getClient(),id,api_version,body,toGoogleGenAIRequestOptions(options)))}async ping(id,params=void 0,options){let{api_version,body}=params??{};return unwrapWithSdkHttpResponse(webhooksPing(this.getClient(),id,api_version,body,toGoogleGenAIRequestOptions(options)))}getClient(){var _a2;return(_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk}},GeminiNextGenTriggers=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(triggersCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,filter,pageSize,pageToken}=params??{};return unwrapWithSdkHttpResponse(triggersList(this.getClient(api_version),api_version,filter,pageSize,pageToken,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(triggersGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(triggersUpdate(this.getClient(api_version),id,body,api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(triggersDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async run(trigger_id,params={},options){return unwrapWithSdkHttpResponse(triggersRun(this.getClient(params?.api_version),trigger_id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async listExecutions(trigger_id,params={},options){let{api_version,pageSize,pageToken}=params??{};return unwrapWithSdkHttpResponse(triggersListExecutions(this.getClient(api_version),trigger_id,api_version,pageSize,pageToken,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}};function trimSlashes(value){return value.replace(/^\/+|\/+$/g,"")}function toGoogleGenAIRequestOptions(options,streaming=!1){var _a2,_b,_c,_d;if(!options&&!streaming)return;let _e=options??{},{timeout,maxRetries,defaultBaseURL,query,body,fetchOptions}=_e,rest=__rest(_e,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),nextOptions=Object.assign({},rest);isPlainObject(query)?nextOptions.extra_query=query:warnIgnoredOption("query",query),isPlainObject(body)?nextOptions.extra_body=body:warnIgnoredOption("body",body);let fetch_options=(_a2=rest.fetch_options)!==null&&_a2!==void 0?_a2:fetchOptions;fetch_options&&(nextOptions.fetch_options=fetch_options);let server_url=(_b=rest.server_url)!==null&&_b!==void 0?_b:defaultBaseURL;server_url&&(nextOptions.server_url=server_url);let timeout_ms=(_c=rest.timeout_ms)!==null&&_c!==void 0?_c:timeout;if(timeout_ms!==void 0&&(nextOptions.timeout_ms=timeout_ms),maxRetries!==void 0&&(nextOptions.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries}),streaming){let headers=new Headers((_d=nextOptions.headers)!==null&&_d!==void 0?_d:fetch_options?.headers);headers.set("Accept","text/event-stream"),nextOptions.headers=headers}return nextOptions}function warnIgnoredOption(name,value){value!=null&&console.warn(`GoogleGenAI.interactions: request option ${name} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function unwrapWithSdkHttpResponse(promise){let[result,call]=await promise.$inspect();if(!result.ok)throw wrapSDKError(result.error);return attachSdkHttpResponse(result.value,call)}async function wrapSDKCall(operation){try{return await operation()}catch(error){throw wrapSDKError(error)}}function wrapStreamErrors(stream){let asyncIterable=stream;return new Proxy(stream,{get(target,property){if(property!==Symbol.asyncIterator){let value=Reflect.get(target,property,target);return typeof value=="function"?value.bind(target):value}return function(){let iterator=asyncIterable[Symbol.asyncIterator]();return{async next(...args){try{return await iterator.next(...args)}catch(error){throw wrapSDKError(error)}},async return(value){if(!iterator.return)return{done:!0,value};try{return await iterator.return(value)}catch(error){throw wrapSDKError(error)}},async throw(error){if(!iterator.throw)throw wrapSDKError(error);try{return await iterator.throw(error)}catch(caught){throw wrapSDKError(caught)}},[Symbol.asyncIterator](){return this}}}}})}function attachSdkHttpResponse(value,call){return!isPlainObject(value)||call.status!=="complete"?value:Object.assign(Object.assign({},value),{sdkHttpResponse:createSdkHttpResponse(call.response,value)})}function createSdkHttpResponse(response,parsedBody){let headers={};for(let[key,value]of response.headers.entries())headers[key]=value;return{headers,responseInternal:response,json:async()=>parsedBody}}function addOutputPropertiesIfInteraction(value){let interaction=normalizeInteractionShape(value);return interaction?addOutputProperties(interaction):value}function normalizeInteractionShape(value){if(isPlainObject(value)){if(Array.isArray(value.steps))return value;if(isLegacyLyriaInteraction(value)){let outputs=value.outputs;if(Array.isArray(outputs)){let{outputs:_outputs}=value,rest=__rest(value,["outputs"]);return Object.assign(Object.assign({},rest),{steps:[{type:"model_output",content:outputs}]})}}return Object.assign(Object.assign({},value),{steps:[]})}}function isLegacyLyriaInteraction(value){let model=value.model;return typeof model=="string"&&LEGACY_LYRIA_MODELS.has(model)}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function addOutputProperties(interaction){var _a2,_b;let normalized=normalizeInteractionDates(interaction),steps=(_a2=normalized.steps)!==null&&_a2!==void 0?_a2:[],textParts=[],collecting=!1;outer:for(let i=steps.length-1;i>=0;i--){let step=steps[i];if(step.type==="user_input")break;if(step.type!=="model_output"||!step.content){if(collecting)break;continue}let content=step.content;for(let j=content.length-1;j>=0;j--){let item=content[j];if(item.type==="text")collecting=!0,textParts.push((_b=item.text)!==null&&_b!==void 0?_b:"");else if(collecting)break outer}}let output_image,output_audio,output_video;for(let i=steps.length-1;i>=0;i--){let step=steps[i];if(step.type==="user_input")break;if(step.type==="model_output"&&step.content)for(let j=step.content.length-1;j>=0;j--){let content=step.content[j];content.type==="image"&&!output_image&&(output_image=content),content.type==="audio"&&!output_audio&&(output_audio=content),content.type==="video"&&!output_video&&(output_video=content)}}let output_text=textParts.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},normalized),output_text&&{output_text}),output_image?{output_image}:{}),output_audio?{output_audio}:{}),output_video?{output_video}:{})}function normalizeInteractionDates(interaction){return Object.assign(Object.assign({},interaction),{created:normalizeDateLike(interaction.created),updated:normalizeDateLike(interaction.updated)})}function normalizeDateLike(value){return value instanceof Date?value.toISOString():value}var GeminiNextGenEnvironmentFiles=class{constructor(resolveClient){this.resolveClient=resolveClient}async list(params,options){let{environment,path:path2,page_size,page_token,recursive,api_version}=params;return unwrapWithSdkHttpResponse(environmentsFilesList(this.resolveClient(api_version),environment,path2,api_version,page_size,page_token,recursive,toGoogleGenAIRequestOptions(options)))}},GeminiNextGenEnvironments=class{constructor(parentClient){this.parentClient=parentClient,this.files=new GeminiNextGenEnvironmentFiles(apiVersion=>this.getClient(apiVersion))}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(environmentsCreateEnvironment(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(environmentsListEnvironments(this.getClient(api_version),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(environmentsGetEnvironment(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(environmentsDeleteEnvironment(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}};var GOOGLE_API_KEY_HEADER="x-goog-api-key",REQUIRED_VERTEX_AI_SCOPE="https://www.googleapis.com/auth/cloud-platform",NodeAuth=class{constructor(opts){if(opts.apiKey!==void 0){this.apiKey=opts.apiKey;return}let vertexAuthOptions=buildGoogleAuthOptions(opts.googleAuthOptions);this.googleAuth=new import_google_auth_library.GoogleAuth(vertexAuthOptions)}async addAuthHeaders(headers,url){if(this.apiKey!==void 0){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(headers);return}return this.addGoogleAuthHeaders(headers,url)}addKeyHeader(headers){if(headers.get(GOOGLE_API_KEY_HEADER)===null){if(this.apiKey===void 0)throw new Error("Trying to set API key header but apiKey is not set");headers.append(GOOGLE_API_KEY_HEADER,this.apiKey)}}async addGoogleAuthHeaders(headers,url){if(this.googleAuth===void 0)throw new Error("Trying to set google-auth headers but googleAuth is unset");let authHeaders=await this.googleAuth.getRequestHeaders(url);for(let[key,value]of authHeaders)headers.get(key)===null&&headers.append(key,value)}};function buildGoogleAuthOptions(googleAuthOptions){let authOptions;if(googleAuthOptions){if(authOptions=googleAuthOptions,authOptions.scopes){if(typeof authOptions.scopes=="string"&&authOptions.scopes!==REQUIRED_VERTEX_AI_SCOPE||Array.isArray(authOptions.scopes)&&authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE)<0)throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`)}else return authOptions.scopes=[REQUIRED_VERTEX_AI_SCOPE],authOptions;return authOptions}else return authOptions={scopes:[REQUIRED_VERTEX_AI_SCOPE]},authOptions}var NodeDownloader=class{async download(params,apiClient){if(params.downloadPath){let response=await downloadFile(params,apiClient);if(response instanceof HttpResponse){let writer=createWriteStream(params.downloadPath);Readable.fromWeb(response.responseInternal.body).pipe(writer),await finished(writer)}else try{await writeFile(params.downloadPath,response,{encoding:"base64"})}catch(error){throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`)}}}};async function downloadFile(params,apiClient){var _a2,_b,_c;let name=tFileName(params.file);if(name!==void 0)return await apiClient.request({path:`files/${name}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal});if(isGeneratedVideo(params.file)){let videoBytes=(_c=params.file.video)===null||_c===void 0?void 0:_c.videoBytes;if(typeof videoBytes=="string")return videoBytes;throw new Error("Failed to download generated video, Uri or videoBytes not found.")}else if(isVideo(params.file)){let videoBytes=params.file.videoBytes;if(typeof videoBytes=="string")return videoBytes;throw new Error("Failed to download video, Uri or videoBytes not found.")}else throw new Error("Unsupported file type")}var NodeWebSocketFactory=class{create(url,headers,callbacks){return new NodeWebSocket(url,headers,callbacks)}},NodeWebSocket=class{constructor(url,headers,callbacks){this.url=url,this.headers=headers,this.callbacks=callbacks}connect(){this.ws=new import_websocket.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(message){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(message)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}};function cancelTuningJobParametersToMldev(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function cancelTuningJobParametersToVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function cancelTuningJobResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function cancelTuningJobResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function contentToVertex(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createTuningJobConfigToMldev(fromObject,parentObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);if(parentObject!==void 0&&fromTunedModelDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromTunedModelDisplayName),getValueByPath(fromObject,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","epochCount"],fromEpochCount);let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);if(fromLearningRateMultiplier!=null&&setValueByPath(toObject,["tuningTask","hyperparameters","learningRateMultiplier"],fromLearningRateMultiplier),getValueByPath(fromObject,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","batchSize"],fromBatchSize);let fromLearningRate=getValueByPath(fromObject,["learningRate"]);if(parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","learningRate"],fromLearningRate),getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["beta"])!==void 0)throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputUri"])!==void 0)throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["rewardConfig"])!==void 0)throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["compositeRewardConfig"])!==void 0)throw new Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["samplesPerPrompt"])!==void 0)throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["evaluateInterval"])!==void 0)throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["checkpointInterval"])!==void 0)throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["maxOutputTokens"])!==void 0)throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["thinkingLevel"])!==void 0)throw new Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["validationDatasetUri"])!==void 0)throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function createTuningJobConfigToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorValidationDataset=getValueByPath(rootObject,["config","method"]);if(discriminatorValidationDataset===void 0&&(discriminatorValidationDataset="SUPERVISED_FINE_TUNING"),discriminatorValidationDataset==="SUPERVISED_FINE_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["supervisedTuningSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="PREFERENCE_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="DISTILLATION"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["distillationSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="REINFORCEMENT_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["reinforcementTuningSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);parentObject!==void 0&&fromTunedModelDisplayName!=null&&setValueByPath(parentObject,["tunedModelDisplayName"],fromTunedModelDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let discriminatorEpochCount=getValueByPath(rootObject,["config","method"]);if(discriminatorEpochCount===void 0&&(discriminatorEpochCount="SUPERVISED_FINE_TUNING"),discriminatorEpochCount==="SUPERVISED_FINE_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="PREFERENCE_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="DISTILLATION"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="REINFORCEMENT_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","epochCount"],fromEpochCount)}let discriminatorLearningRateMultiplier=getValueByPath(rootObject,["config","method"]);if(discriminatorLearningRateMultiplier===void 0&&(discriminatorLearningRateMultiplier="SUPERVISED_FINE_TUNING"),discriminatorLearningRateMultiplier==="SUPERVISED_FINE_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="PREFERENCE_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="DISTILLATION"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="REINFORCEMENT_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}let discriminatorExportLastCheckpointOnly=getValueByPath(rootObject,["config","method"]);if(discriminatorExportLastCheckpointOnly===void 0&&(discriminatorExportLastCheckpointOnly="SUPERVISED_FINE_TUNING"),discriminatorExportLastCheckpointOnly==="SUPERVISED_FINE_TUNING"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["supervisedTuningSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}else if(discriminatorExportLastCheckpointOnly==="PREFERENCE_TUNING"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}else if(discriminatorExportLastCheckpointOnly==="DISTILLATION"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["distillationSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}let discriminatorAdapterSize=getValueByPath(rootObject,["config","method"]);if(discriminatorAdapterSize===void 0&&(discriminatorAdapterSize="SUPERVISED_FINE_TUNING"),discriminatorAdapterSize==="SUPERVISED_FINE_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="PREFERENCE_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="DISTILLATION"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="REINFORCEMENT_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","adapterSize"],fromAdapterSize)}let discriminatorTuningMode=getValueByPath(rootObject,["config","method"]);if(discriminatorTuningMode===void 0&&(discriminatorTuningMode="SUPERVISED_FINE_TUNING"),discriminatorTuningMode==="SUPERVISED_FINE_TUNING"){let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);parentObject!==void 0&&fromTuningMode!=null&&setValueByPath(parentObject,["supervisedTuningSpec","tuningMode"],fromTuningMode)}else if(discriminatorTuningMode==="DISTILLATION"){let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);parentObject!==void 0&&fromTuningMode!=null&&setValueByPath(parentObject,["distillationSpec","tuningMode"],fromTuningMode)}let fromCustomBaseModel=getValueByPath(fromObject,["customBaseModel"]);parentObject!==void 0&&fromCustomBaseModel!=null&&setValueByPath(parentObject,["customBaseModel"],fromCustomBaseModel);let discriminatorBatchSize=getValueByPath(rootObject,["config","method"]);if(discriminatorBatchSize===void 0&&(discriminatorBatchSize="SUPERVISED_FINE_TUNING"),discriminatorBatchSize==="SUPERVISED_FINE_TUNING"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","batchSize"],fromBatchSize)}else if(discriminatorBatchSize==="DISTILLATION"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","batchSize"],fromBatchSize)}else if(discriminatorBatchSize==="REINFORCEMENT_TUNING"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","batchSize"],fromBatchSize)}let discriminatorLearningRate=getValueByPath(rootObject,["config","method"]);if(discriminatorLearningRate===void 0&&(discriminatorLearningRate="SUPERVISED_FINE_TUNING"),discriminatorLearningRate==="SUPERVISED_FINE_TUNING"){let fromLearningRate=getValueByPath(fromObject,["learningRate"]);parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","learningRate"],fromLearningRate)}else if(discriminatorLearningRate==="DISTILLATION"){let fromLearningRate=getValueByPath(fromObject,["learningRate"]);parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","learningRate"],fromLearningRate)}let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromBeta=getValueByPath(fromObject,["beta"]);parentObject!==void 0&&fromBeta!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","beta"],fromBeta);let fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);parentObject!==void 0&&fromBaseTeacherModel!=null&&setValueByPath(parentObject,["distillationSpec","baseTeacherModel"],fromBaseTeacherModel);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);parentObject!==void 0&&fromTunedTeacherModelSource!=null&&setValueByPath(parentObject,["distillationSpec","tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromSftLossWeightMultiplier=getValueByPath(fromObject,["sftLossWeightMultiplier"]);parentObject!==void 0&&fromSftLossWeightMultiplier!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],fromSftLossWeightMultiplier);let fromOutputUri=getValueByPath(fromObject,["outputUri"]);parentObject!==void 0&&fromOutputUri!=null&&setValueByPath(parentObject,["outputUri"],fromOutputUri);let fromRewardConfig=getValueByPath(fromObject,["rewardConfig"]);parentObject!==void 0&&fromRewardConfig!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","singleRewardConfig"],fromRewardConfig);let fromCompositeRewardConfig=getValueByPath(fromObject,["compositeRewardConfig"]);parentObject!==void 0&&fromCompositeRewardConfig!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","compositeRewardConfig"],fromCompositeRewardConfig);let fromSamplesPerPrompt=getValueByPath(fromObject,["samplesPerPrompt"]);parentObject!==void 0&&fromSamplesPerPrompt!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],fromSamplesPerPrompt);let fromEvaluateInterval=getValueByPath(fromObject,["evaluateInterval"]);parentObject!==void 0&&fromEvaluateInterval!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],fromEvaluateInterval);let fromCheckpointInterval=getValueByPath(fromObject,["checkpointInterval"]);parentObject!==void 0&&fromCheckpointInterval!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],fromCheckpointInterval);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],fromMaxOutputTokens);let fromThinkingLevel=getValueByPath(fromObject,["thinkingLevel"]);parentObject!==void 0&&fromThinkingLevel!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],fromThinkingLevel);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);parentObject!==void 0&&fromValidationDatasetUri!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","validationDatasetUri"],fromValidationDatasetUri);let fromEncryptionSpec=getValueByPath(fromObject,["encryptionSpec"]);return parentObject!==void 0&&fromEncryptionSpec!=null&&setValueByPath(parentObject,["encryptionSpec"],fromEncryptionSpec),toObject}function createTuningJobParametersPrivateToMldev(fromObject,rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromTrainingDataset=getValueByPath(fromObject,["trainingDataset"]);fromTrainingDataset!=null&&tuningDatasetToMldev(fromTrainingDataset);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createTuningJobConfigToMldev(fromConfig,toObject),toObject}function createTuningJobParametersPrivateToVertex(fromObject,rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromTrainingDataset=getValueByPath(fromObject,["trainingDataset"]);fromTrainingDataset!=null&&tuningDatasetToVertex(fromTrainingDataset,toObject,rootObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createTuningJobConfigToVertex(fromConfig,toObject,rootObject),toObject}function distillationHyperParametersFromVertex(fromObject,rootObject){let toObject={},fromEpochCount=getValueByPath(fromObject,["epochCount"]);fromEpochCount!=null&&setValueByPath(toObject,["epochCount"],fromEpochCount);let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);fromLearningRateMultiplier!=null&&setValueByPath(toObject,["learningRateMultiplier"],fromLearningRateMultiplier);let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);fromAdapterSize!=null&&setValueByPath(toObject,["adapterSize"],fromAdapterSize);let fromBatchSize=getValueByPath(fromObject,["batchSize"]);fromBatchSize!=null&&setValueByPath(toObject,["batchSize"],fromBatchSize);let fromLearningRate=getValueByPath(fromObject,["learningRate"]);fromLearningRate!=null&&setValueByPath(toObject,["learningRate"],fromLearningRate);let fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);return fromGenerationConfig!=null&&setValueByPath(toObject,["generationConfig"],generationConfigFromVertex(fromGenerationConfig)),toObject}function distillationSamplingSpecFromVertex(fromObject,rootObject){let toObject={},fromPromptDatasetUri=getValueByPath(fromObject,["promptDatasetUri"]);fromPromptDatasetUri!=null&&setValueByPath(toObject,["promptDatasetUri"],fromPromptDatasetUri);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);fromValidationDatasetUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromValidationDatasetUri);let fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);fromBaseTeacherModel!=null&&setValueByPath(toObject,["baseTeacherModel"],fromBaseTeacherModel);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);fromTunedTeacherModelSource!=null&&setValueByPath(toObject,["tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromHyperparameters=getValueByPath(fromObject,["hyperparameters"]);return fromHyperparameters!=null&&setValueByPath(toObject,["hyperparameters"],distillationHyperParametersFromVertex(fromHyperparameters)),toObject}function distillationSpecFromVertex(fromObject,rootObject){let toObject={},fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);fromBaseTeacherModel!=null&&setValueByPath(toObject,["baseTeacherModel"],fromBaseTeacherModel);let fromHyperParameters=getValueByPath(fromObject,["hyperParameters"]);fromHyperParameters!=null&&setValueByPath(toObject,["hyperParameters"],distillationHyperParametersFromVertex(fromHyperParameters));let fromPipelineRootDirectory=getValueByPath(fromObject,["pipelineRootDirectory"]);fromPipelineRootDirectory!=null&&setValueByPath(toObject,["pipelineRootDirectory"],fromPipelineRootDirectory);let fromPromptDatasetUri=getValueByPath(fromObject,["promptDatasetUri"]);fromPromptDatasetUri!=null&&setValueByPath(toObject,["promptDatasetUri"],fromPromptDatasetUri);let fromStudentModel=getValueByPath(fromObject,["studentModel"]);fromStudentModel!=null&&setValueByPath(toObject,["studentModel"],fromStudentModel);let fromTrainingDatasetUri=getValueByPath(fromObject,["trainingDatasetUri"]);fromTrainingDatasetUri!=null&&setValueByPath(toObject,["trainingDatasetUri"],fromTrainingDatasetUri);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);fromTunedTeacherModelSource!=null&&setValueByPath(toObject,["tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);fromTuningMode!=null&&setValueByPath(toObject,["tuningMode"],fromTuningMode);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);return fromValidationDatasetUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromValidationDatasetUri),toObject}function generationConfigFromVertex(fromObject,_rootObject){let toObject={},fromModelSelectionConfig=getValueByPath(fromObject,["modelConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelSelectionConfig"],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"],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"]);return fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP),toObject}function getTuningJobParametersToMldev(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function getTuningJobParametersToVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function listTuningJobsConfigToVertex(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"]);return parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter),toObject}function listTuningJobsParametersToVertex(fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listTuningJobsConfigToVertex(fromConfig,toObject),toObject}function listTuningJobsResponseFromVertex(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 fromTuningJobs=getValueByPath(fromObject,["tuningJobs"]);if(fromTuningJobs!=null){let transformedList=fromTuningJobs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>tuningJobFromVertex(item))),setValueByPath(toObject,["tuningJobs"],transformedList)}return toObject}function partToVertex(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 reinforcementTuningExampleToVertex(fromObject,rootObject){let toObject={},fromReferences=getValueByPath(fromObject,["references"]);fromReferences!=null&&setValueByPath(toObject,["references"],fromReferences);let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=fromContents;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex(item))),setValueByPath(toObject,["contents"],transformedList)}let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);return fromSystemInstruction!=null&&setValueByPath(toObject,["systemInstruction"],contentToVertex(fromSystemInstruction)),toObject}function tunedModelFromMldev(fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["name"]);fromModel!=null&&setValueByPath(toObject,["model"],fromModel);let fromEndpoint=getValueByPath(fromObject,["name"]);return fromEndpoint!=null&&setValueByPath(toObject,["endpoint"],fromEndpoint),toObject}function tuningDatasetToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromExamples=getValueByPath(fromObject,["examples"]);if(fromExamples!=null){let transformedList=fromExamples;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["examples","examples"],transformedList)}return toObject}function tuningDatasetToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorGcsUri=getValueByPath(rootObject,["config","method"]);if(discriminatorGcsUri===void 0&&(discriminatorGcsUri="SUPERVISED_FINE_TUNING"),discriminatorGcsUri==="SUPERVISED_FINE_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["supervisedTuningSpec","trainingDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="PREFERENCE_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","trainingDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="DISTILLATION"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["distillationSpec","promptDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="REINFORCEMENT_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","trainingDatasetUri"],fromGcsUri)}let discriminatorVertexDatasetResource=getValueByPath(rootObject,["config","method"]);if(discriminatorVertexDatasetResource===void 0&&(discriminatorVertexDatasetResource="SUPERVISED_FINE_TUNING"),discriminatorVertexDatasetResource==="SUPERVISED_FINE_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["supervisedTuningSpec","trainingDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="PREFERENCE_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","trainingDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="DISTILLATION"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["distillationSpec","promptDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="REINFORCEMENT_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","trainingDatasetUri"],fromVertexDatasetResource)}if(getValueByPath(fromObject,["examples"])!==void 0)throw new Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function tuningJobFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromState=getValueByPath(fromObject,["state"]);fromState!=null&&setValueByPath(toObject,["state"],tTuningJobStatus(fromState));let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromStartTime=getValueByPath(fromObject,["tuningTask","startTime"]);fromStartTime!=null&&setValueByPath(toObject,["startTime"],fromStartTime);let fromEndTime=getValueByPath(fromObject,["tuningTask","completeTime"]);fromEndTime!=null&&setValueByPath(toObject,["endTime"],fromEndTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromTunedModel=getValueByPath(fromObject,["_self"]);return fromTunedModel!=null&&setValueByPath(toObject,["tunedModel"],tunedModelFromMldev(fromTunedModel)),toObject}function tuningJobFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromState=getValueByPath(fromObject,["state"]);fromState!=null&&setValueByPath(toObject,["state"],tTuningJobStatus(fromState));let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromStartTime=getValueByPath(fromObject,["startTime"]);fromStartTime!=null&&setValueByPath(toObject,["startTime"],fromStartTime);let fromEndTime=getValueByPath(fromObject,["endTime"]);fromEndTime!=null&&setValueByPath(toObject,["endTime"],fromEndTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromTunedModel=getValueByPath(fromObject,["tunedModel"]);fromTunedModel!=null&&setValueByPath(toObject,["tunedModel"],fromTunedModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromSupervisedTuningSpec=getValueByPath(fromObject,["supervisedTuningSpec"]);fromSupervisedTuningSpec!=null&&setValueByPath(toObject,["supervisedTuningSpec"],fromSupervisedTuningSpec);let fromPreferenceOptimizationSpec=getValueByPath(fromObject,["preferenceOptimizationSpec"]);fromPreferenceOptimizationSpec!=null&&setValueByPath(toObject,["preferenceOptimizationSpec"],fromPreferenceOptimizationSpec);let fromDistillationSamplingSpec=getValueByPath(fromObject,["distillationSamplingSpec"]);fromDistillationSamplingSpec!=null&&setValueByPath(toObject,["distillationSamplingSpec"],distillationSamplingSpecFromVertex(fromDistillationSamplingSpec));let fromDistillationSpec=getValueByPath(fromObject,["distillationSpec"]);fromDistillationSpec!=null&&setValueByPath(toObject,["distillationSpec"],distillationSpecFromVertex(fromDistillationSpec));let fromReinforcementTuningSpec=getValueByPath(fromObject,["reinforcementTuningSpec"]);fromReinforcementTuningSpec!=null&&setValueByPath(toObject,["reinforcementTuningSpec"],fromReinforcementTuningSpec);let fromTuningDataStats=getValueByPath(fromObject,["tuningDataStats"]);fromTuningDataStats!=null&&setValueByPath(toObject,["tuningDataStats"],fromTuningDataStats);let fromEncryptionSpec=getValueByPath(fromObject,["encryptionSpec"]);fromEncryptionSpec!=null&&setValueByPath(toObject,["encryptionSpec"],fromEncryptionSpec);let fromPartnerModelTuningSpec=getValueByPath(fromObject,["partnerModelTuningSpec"]);fromPartnerModelTuningSpec!=null&&setValueByPath(toObject,["partnerModelTuningSpec"],fromPartnerModelTuningSpec);let fromCustomBaseModel=getValueByPath(fromObject,["customBaseModel"]);fromCustomBaseModel!=null&&setValueByPath(toObject,["customBaseModel"],fromCustomBaseModel);let fromEvaluateDatasetRuns=getValueByPath(fromObject,["evaluateDatasetRuns"]);if(fromEvaluateDatasetRuns!=null){let transformedList=fromEvaluateDatasetRuns;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["evaluateDatasetRuns"],transformedList)}let fromExperiment=getValueByPath(fromObject,["experiment"]);fromExperiment!=null&&setValueByPath(toObject,["experiment"],fromExperiment);let fromFullFineTuningSpec=getValueByPath(fromObject,["fullFineTuningSpec"]);fromFullFineTuningSpec!=null&&setValueByPath(toObject,["fullFineTuningSpec"],fromFullFineTuningSpec);let fromLabels=getValueByPath(fromObject,["labels"]);fromLabels!=null&&setValueByPath(toObject,["labels"],fromLabels);let fromOutputUri=getValueByPath(fromObject,["outputUri"]);fromOutputUri!=null&&setValueByPath(toObject,["outputUri"],fromOutputUri);let fromPipelineJob=getValueByPath(fromObject,["pipelineJob"]);fromPipelineJob!=null&&setValueByPath(toObject,["pipelineJob"],fromPipelineJob);let fromServiceAccount=getValueByPath(fromObject,["serviceAccount"]);fromServiceAccount!=null&&setValueByPath(toObject,["serviceAccount"],fromServiceAccount);let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);fromTunedModelDisplayName!=null&&setValueByPath(toObject,["tunedModelDisplayName"],fromTunedModelDisplayName);let fromTuningJobMetadata=getValueByPath(fromObject,["tuningJobMetadata"]);fromTuningJobMetadata!=null&&setValueByPath(toObject,["tuningJobMetadata"],fromTuningJobMetadata);let fromTuningJobState=getValueByPath(fromObject,["tuningJobState"]);fromTuningJobState!=null&&setValueByPath(toObject,["tuningJobState"],fromTuningJobState);let fromVeoLoraTuningSpec=getValueByPath(fromObject,["veoLoraTuningSpec"]);fromVeoLoraTuningSpec!=null&&setValueByPath(toObject,["veoLoraTuningSpec"],fromVeoLoraTuningSpec);let fromVeoTuningSpec=getValueByPath(fromObject,["veoTuningSpec"]);return fromVeoTuningSpec!=null&&setValueByPath(toObject,["veoTuningSpec"],fromVeoTuningSpec),toObject}function tuningOperationFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let 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"]);return fromError!=null&&setValueByPath(toObject,["error"],fromError),toObject}function tuningValidationDatasetToVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromGcsUri);let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);return fromVertexDatasetResource!=null&&setValueByPath(toObject,["validationDatasetUri"],fromVertexDatasetResource),toObject}function validateRewardParametersToVertex(fromObject,rootObject){let toObject={},fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["_url","parent"],fromParent);let fromSampleResponse=getValueByPath(fromObject,["sampleResponse"]);fromSampleResponse!=null&&setValueByPath(toObject,["sampleResponse"],contentToVertex(fromSampleResponse));let fromExample=getValueByPath(fromObject,["example"]);fromExample!=null&&setValueByPath(toObject,["example"],reinforcementTuningExampleToVertex(fromExample));let fromSingleRewardConfig=getValueByPath(fromObject,["singleRewardConfig"]);fromSingleRewardConfig!=null&&setValueByPath(toObject,["singleRewardConfig"],fromSingleRewardConfig);let fromCompositeRewardConfig=getValueByPath(fromObject,["compositeRewardConfig"]);return fromCompositeRewardConfig!=null&&setValueByPath(toObject,["compositeRewardConfig"],fromCompositeRewardConfig),toObject}function validateRewardResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromOverallReward=getValueByPath(fromObject,["overallReward"]);fromOverallReward!=null&&setValueByPath(toObject,["overallReward"],fromOverallReward);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromRewardInfoDetails=getValueByPath(fromObject,["rewardInfoDetails"]);return fromRewardInfoDetails!=null&&setValueByPath(toObject,["rewardInfoDetails"],fromRewardInfoDetails),toObject}var Tunings=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS,x=>this.listInternal(x),await this.listInternal(params),params),this.get=async params=>await this.getInternal(params),this.tune=async params=>{var _a2;if(this.apiClient.isVertexAI())if(params.baseModel.startsWith("projects/")){let preTunedModel={tunedModelName:params.baseModel};!((_a2=params.config)===null||_a2===void 0)&&_a2.preTunedModelCheckpointId&&(preTunedModel.checkpointId=params.config.preTunedModelCheckpointId);let paramsPrivate=Object.assign(Object.assign({},params),{preTunedModel});return paramsPrivate.baseModel=void 0,await this.tuneInternal(paramsPrivate)}else{let paramsPrivate=Object.assign({},params);return await this.tuneInternal(paramsPrivate)}else{let paramsPrivate=Object.assign({},params),operation=await this.tuneMldevInternal(paramsPrivate),tunedModelName="";return operation.metadata!==void 0&&operation.metadata.tunedModel!==void 0?tunedModelName=operation.metadata.tunedModel:operation.name!==void 0&&operation.name.includes("/operations/")&&(tunedModelName=operation.name.split("/operations/")[0]),{name:tunedModelName,state:JobState.JOB_STATE_QUEUED}}}}async getInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getTuningJobParametersToVertex(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromVertex(apiResponse))}else{let body=getTuningJobParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromMldev(apiResponse))}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listTuningJobsParametersToVertex(params);return path2=formatMap("tuningJobs",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listTuningJobsResponseFromVertex(apiResponse),typedResp=new ListTuningJobsResponse;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 cancel(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=cancelTuningJobParametersToVertex(params);return path2=formatMap("{name}:cancel",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=cancelTuningJobResponseFromVertex(apiResponse),typedResp=new CancelTuningJobResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=cancelTuningJobParametersToMldev(params);return path2=formatMap("{name}:cancel",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=cancelTuningJobResponseFromMldev(apiResponse),typedResp=new CancelTuningJobResponse;return Object.assign(typedResp,resp),typedResp})}}async tuneInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=createTuningJobParametersPrivateToVertex(params,params);return path2=formatMap("tuningJobs",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromVertex(apiResponse))}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createTuningJobParametersPrivateToMldev(params);return path2=formatMap("tunedModels",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningOperationFromMldev(apiResponse))}}async validateReward(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=validateRewardParametersToVertex(params);return path2=formatMap("{parent}/tuningJobs:validateReinforcementTuningReward",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=validateRewardResponseFromVertex(apiResponse),typedResp=new ValidateRewardResponse;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).")}},MAX_CHUNK_SIZE=1024*1024*8,MAX_RETRY_COUNT=3,INITIAL_RETRY_DELAY_MS=1e3,DELAY_MULTIPLIER=2,X_GOOG_UPLOAD_STATUS_HEADER_FIELD="x-goog-upload-status";async function uploadBlob(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await uploadBlobInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return responseJson.file}async function uploadBlobToFileSearchStore(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await uploadBlobInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let resp=uploadToFileSearchStoreOperationFromMldev(responseJson),typedResp=new UploadToFileSearchStoreOperation;return Object.assign(typedResp,resp),typedResp}async function uploadBlobInternal(file,uploadUrl,apiClient,httpOptions){var _a2,_b,_c;let finalUrl=uploadUrl,effectiveBaseUrl=httpOptions?.baseUrl||((_a2=apiClient.clientOptions.httpOptions)===null||_a2===void 0?void 0:_a2.baseUrl);if(effectiveBaseUrl){let baseUri=new URL(effectiveBaseUrl),uploadUri=new URL(uploadUrl);uploadUri.protocol=baseUri.protocol,uploadUri.host=baseUri.host,uploadUri.port=baseUri.port,finalUrl=uploadUri.toString()}let fileSize=0,offset=0,response=new HttpResponse(new Response),uploadCommand="upload";for(fileSize=file.size;offset<fileSize;){let chunkSize=Math.min(MAX_CHUNK_SIZE,fileSize-offset),chunk=file.slice(offset,offset+chunkSize);offset+chunkSize>=fileSize&&(uploadCommand+=", finalize");let retryCount=0,currentDelayMs=INITIAL_RETRY_DELAY_MS;for(;retryCount<MAX_RETRY_COUNT;){let mergedHeaders=Object.assign(Object.assign({},httpOptions?.headers||{}),{"X-Goog-Upload-Command":uploadCommand,"X-Goog-Upload-Offset":String(offset)});if(response=await apiClient.request({path:"",body:chunk,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},httpOptions),{apiVersion:"",baseUrl:finalUrl,headers:mergedHeaders})}),!((_b=response?.headers)===null||_b===void 0)&&_b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])break;retryCount++,await sleep(currentDelayMs),currentDelayMs=currentDelayMs*DELAY_MULTIPLIER}if(offset+=chunkSize,((_c=response?.headers)===null||_c===void 0?void 0:_c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="active")break;if(fileSize<=offset)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return response}async function getBlobStat(file){return{size:file.size,type:file.type}}function sleep(ms){return new Promise(resolvePromise=>setTimeout(resolvePromise,ms))}var NodeUploader=class{async stat(file){let fileStat={size:0,type:void 0};if(typeof file=="string"){let originalStat=await fs.stat(file);return fileStat.size=originalStat.size,fileStat.type=this.inferMimeType(file),fileStat}else return await getBlobStat(file)}async upload(file,uploadUrl,apiClient,httpOptions){return typeof file=="string"?await this.uploadFileFromPath(file,uploadUrl,apiClient,httpOptions):uploadBlob(file,uploadUrl,apiClient,httpOptions)}async uploadToFileSearchStore(file,uploadUrl,apiClient,httpOptions){return typeof file=="string"?await this.uploadFileToFileSearchStoreFromPath(file,uploadUrl,apiClient,httpOptions):uploadBlobToFileSearchStore(file,uploadUrl,apiClient,httpOptions)}inferMimeType(filePath){let fileExtension=filePath.slice(filePath.lastIndexOf(".")+1);return{aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"}[fileExtension.toLowerCase()]}async uploadFileFromPath(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await this.uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return responseJson.file}async uploadFileToFileSearchStoreFromPath(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await this.uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let resp=uploadToFileSearchStoreOperationFromMldev(responseJson),typedResp=new UploadToFileSearchStoreOperation;return Object.assign(typedResp,resp),typedResp}async uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions){var _a2,_b,_c;let finalUrl=uploadUrl,effectiveBaseUrl=httpOptions?.baseUrl||((_a2=apiClient.clientOptions.httpOptions)===null||_a2===void 0?void 0:_a2.baseUrl);if(effectiveBaseUrl){let baseUri=new URL(effectiveBaseUrl),uploadUri=new URL(uploadUrl);uploadUri.protocol=baseUri.protocol,uploadUri.host=baseUri.host,uploadUri.port=baseUri.port,finalUrl=uploadUri.toString()}let fileSize=0,offset=0,response=new HttpResponse(new Response),uploadCommand="upload",fileHandle,fileName=path.basename(file);try{if(fileHandle=await fs.open(file,"r"),!fileHandle)throw new Error("Failed to open file");for(fileSize=(await fileHandle.stat()).size;offset<fileSize;){let chunkSize=Math.min(MAX_CHUNK_SIZE,fileSize-offset);offset+chunkSize>=fileSize&&(uploadCommand+=", finalize");let buffer=new Uint8Array(chunkSize),{bytesRead}=await fileHandle.read(buffer,0,chunkSize,offset);if(bytesRead!==chunkSize)throw new Error(`Failed to read ${chunkSize} bytes from file at offset ${offset}. bytes actually read: ${bytesRead}`);let chunk=new Blob([buffer]),retryCount=0,currentDelayMs=INITIAL_RETRY_DELAY_MS;for(;retryCount<MAX_RETRY_COUNT;){let mergedHeaders=Object.assign(Object.assign({},httpOptions?.headers||{}),{"X-Goog-Upload-Command":uploadCommand,"X-Goog-Upload-Offset":String(offset),"X-Goog-Upload-File-Name":fileName});if(response=await apiClient.request({path:"",body:chunk,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},httpOptions),{apiVersion:"",baseUrl:finalUrl,headers:mergedHeaders})}),!((_b=response?.headers)===null||_b===void 0)&&_b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])break;retryCount++,await sleep(currentDelayMs),currentDelayMs=currentDelayMs*DELAY_MULTIPLIER}if(offset+=bytesRead,((_c=response?.headers)===null||_c===void 0?void 0:_c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="active")break;if(fileSize<=offset)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return response}finally{fileHandle&&await fileHandle.close()}}};var NodeFiles=class extends Files$1{async registerFiles(params){if(typeof process>"u"||!process.versions||!process.versions.node)throw new Error("registerFiles is only supported in Node.js environments.");let authHeaders=await params.auth.getRequestHeaders(),config=params.config||{},httpOptions=config.httpOptions||{},headers=Object.assign({},httpOptions.headers||{});if(authHeaders)if(typeof authHeaders[Symbol.iterator]=="function")for(let[key,value]of authHeaders)headers[key]=value;else for(let[key,value]of Object.entries(authHeaders))headers[key]=value;return this._registerFiles({uris:params.uris,config:Object.assign(Object.assign({},config),{httpOptions:Object.assign(Object.assign({},httpOptions),{headers})})})}};var LANGUAGE_LABEL_PREFIX="gl-node/";function resolveCloudFlag(options){var _a2;if(options&&(options.enterprise!==void 0||options.vertexai!==void 0)){if(options.enterprise!==void 0&&options.vertexai!==void 0&&options.enterprise!==options.vertexai)throw new Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return(_a2=options.enterprise)!==null&&_a2!==void 0?_a2:options.vertexai}let envEnterpriseStr=getEnv("GOOGLE_GENAI_USE_ENTERPRISE"),envVertexaiStr=getEnv("GOOGLE_GENAI_USE_VERTEXAI"),useEnterpriseEnv=stringToBoolean(envEnterpriseStr),useVertexaiEnv=stringToBoolean(envVertexaiStr);return envEnterpriseStr!==void 0&&envVertexaiStr!==void 0&&useEnterpriseEnv!==useVertexaiEnv&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),envEnterpriseStr!==void 0?useEnterpriseEnv:envVertexaiStr!==void 0?useVertexaiEnv:!1}var GoogleGenAI2=class{getNextGenClient(){let httpOpts=this.httpOptions;return this._nextGenClient===void 0&&(this._nextGenClient=buildGoogleGenAIClient(this.apiClient,{timeout_ms:httpOpts?.timeout})),httpOpts?.extraBody&&console.warn("GoogleGenAI: Client level httpOptions.extraBody is not supported by the Gemini NextGen client and will be ignored."),this._nextGenClient}get interactions(){return this._interactions!==void 0?this._interactions:(this._interactions=new GeminiNextGenInteractions(this.apiClient),this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=new GeminiNextGenWebhooks(this.apiClient),this._webhooks)}get agents(){return this._agents!==void 0?this._agents:(console.warn("GoogleGenAI.agents: Agents usage is experimental and may change in future versions."),this._agents=new GeminiNextGenAgents(this.apiClient),this._agents)}get triggers(){return this._triggers!==void 0?this._triggers:(console.warn("GoogleGenAI.triggers: Triggers usage is experimental and may change in future versions."),this._triggers=new GeminiNextGenTriggers(this.apiClient),this._triggers)}get environments(){return this._environments!==void 0?this._environments:(console.warn("GoogleGenAI.environments: Environments usage is experimental and may change in future versions."),this._environments=new GeminiNextGenEnvironments(this.apiClient),this._environments)}constructor(options={}){var _a2,_b,_c,_d;if(this.vertexai=resolveCloudFlag(options),(options.project||options.location)&&!this.vertexai)throw new Error("Project and location are not supported for Gemini API backend.");let envApiKey=getApiKeyFromEnv(),envProject=getEnv("GOOGLE_CLOUD_PROJECT"),envLocation=getEnv("GOOGLE_CLOUD_LOCATION");this.apiKey=(_a2=options.apiKey)!==null&&_a2!==void 0?_a2:envApiKey,this.project=(_b=options.project)!==null&&_b!==void 0?_b:envProject,this.location=(_c=options.location)!==null&&_c!==void 0?_c:envLocation,!this.vertexai&&!this.apiKey&&console.warn("API key should be set when using the Gemini API."),this.vertexai&&(!((_d=options.googleAuthOptions)===null||_d===void 0)&&_d.credentials&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),!options.project&&!options.location&&(envProject||envLocation)&&options.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(options.project||options.location)&&!options.apiKey&&envApiKey?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):!options.project&&!options.location&&!options.apiKey&&(envProject||envLocation)&&envApiKey&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),!this.location&&!this.apiKey&&(this.location="global"));let baseUrl=getBaseUrl(options.httpOptions,this.vertexai,getEnv("GOOGLE_VERTEX_BASE_URL"),getEnv("GOOGLE_GEMINI_BASE_URL"));baseUrl&&(options.httpOptions?options.httpOptions.baseUrl=baseUrl:options.httpOptions={baseUrl}),this.apiVersion=options.apiVersion,this.httpOptions=options.httpOptions;let auth=new NodeAuth({apiKey:this.apiKey,googleAuthOptions:options.googleAuthOptions});this.apiClient=new ApiClient({auth,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:LANGUAGE_LABEL_PREFIX+process.version,uploader:new NodeUploader,downloader:new NodeDownloader}),this.models=new Models(this.apiClient),this.live=new Live(this.apiClient,auth,new NodeWebSocketFactory),this.batches=new Batches(this.apiClient),this.chats=new Chats(this.models,this.apiClient),this.caches=new Caches(this.apiClient),this.files=new NodeFiles(this.apiClient),this.operations=new Operations(this.apiClient),this.authTokens=new Tokens(this.apiClient),this.tunings=new Tunings(this.apiClient),this.fileSearchStores=new FileSearchStores(this.apiClient)}};function getEnv(env2){var _a2,_b,_c;return(_c=(_b=(_a2=process==null?void 0:process.env)===null||_a2===void 0?void 0:_a2[env2])===null||_b===void 0?void 0:_b.trim())!==null&&_c!==void 0?_c:void 0}function stringToBoolean(str){return str===void 0?!1:str.toLowerCase()==="true"}function getApiKeyFromEnv(){let envGoogleApiKey=getEnv("GOOGLE_API_KEY"),envGeminiApiKey=getEnv("GEMINI_API_KEY");return envGoogleApiKey&&envGeminiApiKey&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),envGoogleApiKey||envGeminiApiKey||void 0}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 match2=modelId.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(match2)return Number.parseInt(match2[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(`
|
|
44
44
|
`),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}
|
|
45
|
-
${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 mapStopReason(reason){switch(reason){case FinishReason.STOP:return"stop";case FinishReason.MAX_TOKENS:return"length";case FinishReason.BLOCKLIST:case FinishReason.PROHIBITED_CONTENT:case FinishReason.SPII:case FinishReason.SAFETY:case FinishReason.IMAGE_SAFETY:case FinishReason.IMAGE_PROHIBITED_CONTENT:case FinishReason.IMAGE_RECITATION:case FinishReason.IMAGE_OTHER:case FinishReason.RECITATION:case FinishReason.FINISH_REASON_UNSPECIFIED:case FinishReason.OTHER:case FinishReason.LANGUAGE:case FinishReason.MALFORMED_FUNCTION_CALL:case FinishReason.UNEXPECTED_TOOL_CALL:case FinishReason.TOO_MANY_TOOL_CALLS:case FinishReason.NO_IMAGE:return"error";default:{let _exhaustive=reason;throw new Error(`Unhandled stop reason: ${_exhaustive}`)}}}function retryGoogleRequest(request,options){return retryProviderRequest(async()=>{try{return await request()}catch(error){throw error instanceof Error&&"status"in error&&!("headers"in error)&&(error.headers=void 0),error}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal})}export{ResourceScope,GoogleGenAI2 as GoogleGenAI,resolveGoogleThinkingLevel,usesGoogleThinkingLevel,toGoogleThinkingLevel,toGoogleSdkThinkingLevel,getDisabledGoogleThinkingConfig,isThinkingPart,retainThoughtSignature,convertMessages,convertTools,supportsGoogleStrictToolSampling,resolveGoogleFunctionCallingMode,mapStopReason,retryGoogleRequest};
|
|
45
|
+
${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 mapStopReason(reason){switch(reason){case FinishReason.STOP:return"stop";case FinishReason.MAX_TOKENS:return"length";case FinishReason.BLOCKLIST:case FinishReason.PROHIBITED_CONTENT:case FinishReason.SPII:case FinishReason.SAFETY:case FinishReason.IMAGE_SAFETY:case FinishReason.IMAGE_PROHIBITED_CONTENT:case FinishReason.IMAGE_RECITATION:case FinishReason.IMAGE_OTHER:case FinishReason.RECITATION:case FinishReason.FINISH_REASON_UNSPECIFIED:case FinishReason.OTHER:case FinishReason.LANGUAGE:case FinishReason.MALFORMED_FUNCTION_CALL:case FinishReason.UNEXPECTED_TOOL_CALL:case FinishReason.TOO_MANY_TOOL_CALLS:case FinishReason.NO_IMAGE:return"error";default:{let _exhaustive=reason;throw new Error(`Unhandled stop reason: ${_exhaustive}`)}}}function retryGoogleRequest(request,options){return retryProviderRequest(async()=>{try{return await request()}catch(error){throw error instanceof Error&&"status"in error&&!("headers"in error)&&(error.headers=void 0),error}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal})}export{ResourceScope,GoogleGenAI2 as GoogleGenAI,resolveGoogleThinkingLevel,usesGoogleThinkingLevel,toGoogleThinkingLevel,toGoogleSdkThinkingLevel,getDisabledGoogleThinkingConfig,isThinkingPart,retainThoughtSignature,convertMessages,convertTools,supportsGoogleStrictToolSampling,resolveGoogleFunctionCallingMode,mapStopReason,retryGoogleRequest};
|