@code-yeongyu/senpi 2026.8.13 → 2026.8.16
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 +142 -0
- package/README.md +1 -0
- package/dist/cli/args.d.ts +1 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +14 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/auth-command.d.ts.map +1 -1
- package/dist/cli/auth-command.js +5 -4
- package/dist/cli/auth-command.js.map +1 -1
- package/dist/core/agent-session.d.ts +80 -8
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +206 -31
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +19 -8
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/experimental.d.ts +4 -0
- package/dist/core/experimental.d.ts.map +1 -1
- package/dist/core/experimental.js +4 -0
- package/dist/core/experimental.js.map +1 -1
- package/dist/core/export-html/template.js +31 -9
- package/dist/core/extensions/builtin/claude-sdk-oauth/auth-environment.d.ts +4 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/auth-environment.d.ts.map +1 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/auth-environment.js +30 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/auth-environment.js.map +1 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/auth-lane.d.ts +2 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/auth-lane.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/auth-lane.js +13 -47
- package/dist/core/extensions/builtin/claude-sdk-oauth/auth-lane.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/availability.d.ts +18 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/availability.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/availability.js +64 -2
- package/dist/core/extensions/builtin/claude-sdk-oauth/availability.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/config-dir-credentials.d.ts +3 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/config-dir-credentials.d.ts.map +1 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/config-dir-credentials.js +27 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/config-dir-credentials.js.map +1 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/oauth-login.d.ts +15 -2
- package/dist/core/extensions/builtin/claude-sdk-oauth/oauth-login.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/oauth-login.js +45 -11
- package/dist/core/extensions/builtin/claude-sdk-oauth/oauth-login.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/options.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/options.js +1 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/options.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry-wiring.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry-wiring.js +3 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry-wiring.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-stream.js +1 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-stream.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-sync.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-sync.js +17 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-sync.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/stream.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/stream.js +1 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/stream.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/index.js +225 -75
- package/dist/core/extensions/builtin/compaction/index.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/lane-policy.d.ts +2 -3
- package/dist/core/extensions/builtin/compaction/lane-policy.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/lane-policy.js +2 -3
- package/dist/core/extensions/builtin/compaction/lane-policy.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/log.d.ts +1 -1
- package/dist/core/extensions/builtin/compaction/log.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/log.js +2 -0
- package/dist/core/extensions/builtin/compaction/log.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/overflow-retry.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/overflow-retry.js +38 -4
- package/dist/core/extensions/builtin/compaction/overflow-retry.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/speculative.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/speculative.js +2 -1
- package/dist/core/extensions/builtin/compaction/speculative.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/summarization-turn-order.d.ts +33 -0
- package/dist/core/extensions/builtin/compaction/summarization-turn-order.d.ts.map +1 -0
- package/dist/core/extensions/builtin/compaction/summarization-turn-order.js +67 -0
- package/dist/core/extensions/builtin/compaction/summarization-turn-order.js.map +1 -0
- package/dist/core/extensions/builtin/config-reload/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/config-reload/index.js +31 -8
- package/dist/core/extensions/builtin/config-reload/index.js.map +1 -1
- package/dist/core/extensions/builtin/config-reload/routine-settings.d.ts.map +1 -1
- package/dist/core/extensions/builtin/config-reload/routine-settings.js +11 -12
- package/dist/core/extensions/builtin/config-reload/routine-settings.js.map +1 -1
- package/dist/core/extensions/builtin/goal/terminal-provider-error.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/terminal-provider-error.js +16 -0
- package/dist/core/extensions/builtin/goal/terminal-provider-error.js.map +1 -1
- package/dist/core/extensions/builtin/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/index.js +4 -0
- package/dist/core/extensions/builtin/index.js.map +1 -1
- package/dist/core/extensions/builtin/mcp/process-tree.js +6 -1
- package/dist/core/extensions/builtin/mcp/process-tree.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/glm-5-3.d.ts +3 -0
- package/dist/core/extensions/builtin/prompt-preset/glm-5-3.d.ts.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset/glm-5-3.js +14 -0
- package/dist/core/extensions/builtin/prompt-preset/glm-5-3.js.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset/grok-4.6.d.ts +3 -0
- package/dist/core/extensions/builtin/prompt-preset/grok-4.6.d.ts.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset/grok-4.6.js +91 -0
- package/dist/core/extensions/builtin/prompt-preset/grok-4.6.js.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/index.js +22 -2
- package/dist/core/extensions/builtin/prompt-preset/index.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/presets.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/presets.js +25 -0
- package/dist/core/extensions/builtin/prompt-preset/presets.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/settings.d.ts +1 -1
- package/dist/core/extensions/builtin/prompt-preset/settings.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/settings.js +2 -0
- package/dist/core/extensions/builtin/prompt-preset/settings.js.map +1 -1
- package/dist/core/extensions/builtin/reasoning/index.d.ts +3 -0
- package/dist/core/extensions/builtin/reasoning/index.d.ts.map +1 -0
- package/dist/core/extensions/builtin/reasoning/index.js +211 -0
- package/dist/core/extensions/builtin/reasoning/index.js.map +1 -0
- package/dist/core/extensions/builtin/service-tier.d.ts +44 -1
- package/dist/core/extensions/builtin/service-tier.d.ts.map +1 -1
- package/dist/core/extensions/builtin/service-tier.js +176 -24
- package/dist/core/extensions/builtin/service-tier.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +4 -4
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +13 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/keybindings.d.ts +24 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/lockfile-policy.d.ts +15 -0
- package/dist/core/lockfile-policy.d.ts.map +1 -0
- package/dist/core/lockfile-policy.js +15 -0
- package/dist/core/lockfile-policy.js.map +1 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +1 -0
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-resolver.d.ts +34 -7
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +115 -27
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +5 -3
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/provider-api-key-auth.d.ts.map +1 -1
- package/dist/core/provider-api-key-auth.js +45 -2
- package/dist/core/provider-api-key-auth.js.map +1 -1
- package/dist/core/provider-composer.d.ts +12 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/provider-display-names.d.ts.map +1 -1
- package/dist/core/provider-display-names.js +1 -0
- package/dist/core/provider-display-names.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts +13 -0
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +15 -0
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/retry-fallback/controller.d.ts +1 -1
- package/dist/core/retry-fallback/controller.d.ts.map +1 -1
- package/dist/core/retry-fallback/controller.js +5 -3
- package/dist/core/retry-fallback/controller.js.map +1 -1
- package/dist/core/retry-fallback/settings.d.ts.map +1 -1
- package/dist/core/retry-fallback/settings.js +4 -1
- package/dist/core/retry-fallback/settings.js.map +1 -1
- package/dist/core/sdk.d.ts +5 -3
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +14 -8
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +20 -4
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +50 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +258 -15
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt.js +1 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/thinking-levels.d.ts +22 -0
- package/dist/core/thinking-levels.d.ts.map +1 -1
- package/dist/core/thinking-levels.js +29 -0
- package/dist/core/thinking-levels.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +2 -0
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +2 -0
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.js +1 -1
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.js +1 -1
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +2 -0
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +2 -0
- package/dist/core/tools/write.js.map +1 -1
- package/dist/index.d.ts +1 -1
- 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 +18 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/extension-selector.d.ts +2 -0
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-selector.js +17 -1
- package/dist/modes/interactive/components/extension-selector.js.map +1 -1
- package/dist/modes/interactive/components/model-favorites.d.ts +2 -1
- package/dist/modes/interactive/components/model-favorites.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-favorites.js +72 -6
- package/dist/modes/interactive/components/model-favorites.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +5 -1
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +10 -6
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +3 -1
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +10 -0
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +22 -1
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +14 -4
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +109 -50
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/model-catalog-refresh.d.ts +7 -0
- package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -0
- package/dist/modes/interactive/model-catalog-refresh.js +36 -0
- package/dist/modes/interactive/model-catalog-refresh.js.map +1 -0
- package/dist/modes/interactive/theme/dark.json +2 -0
- package/dist/modes/interactive/theme/grok-day.json +2 -0
- package/dist/modes/interactive/theme/grok-night.json +2 -0
- package/dist/modes/interactive/theme/light.json +2 -0
- package/dist/modes/interactive/theme/theme-controller.d.ts +10 -2
- package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme-controller.js +23 -10
- package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
- package/dist/modes/interactive/theme/theme-schema.json +9 -1
- package/dist/modes/interactive/theme/theme.d.ts +5 -3
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +12 -2
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/json-event.d.ts +4 -1
- package/dist/modes/json-event.d.ts.map +1 -1
- package/dist/modes/json-event.js +5 -2
- package/dist/modes/json-event.js.map +1 -1
- package/dist/modes/rpc/connection-handler.d.ts +10 -0
- package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
- package/dist/modes/rpc/connection-handler.js +87 -19
- package/dist/modes/rpc/connection-handler.js.map +1 -1
- package/dist/modes/rpc/multi-session-host.js +3 -3
- package/dist/modes/rpc/multi-session-host.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +26 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +25 -2
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +60 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
- package/dist/modes/rpc/session-command-router.js +2 -14
- package/dist/modes/rpc/session-command-router.js.map +1 -1
- package/dist/modes/rpc/session-event-writer.d.ts +29 -10
- package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
- package/dist/modes/rpc/session-event-writer.js +229 -50
- package/dist/modes/rpc/session-event-writer.js.map +1 -1
- package/dist/server/create-harness.d.ts.map +1 -1
- package/dist/server/create-harness.js +2 -0
- package/dist/server/create-harness.js.map +1 -1
- package/dist/utils/shell.d.ts +27 -0
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +79 -13
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/tools-manager.d.ts +10 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +14 -19
- package/dist/utils/tools-manager.js.map +1 -1
- package/docs/compaction.md +3 -3
- package/docs/custom-provider.md +1 -1
- package/docs/environment-variables.md +8 -2
- package/docs/extensions.md +13 -1
- package/docs/json.md +9 -5
- package/docs/keybindings.md +8 -2
- package/docs/providers.md +9 -1
- package/docs/rpc.md +128 -6
- package/docs/sdk.md +9 -0
- package/docs/settings.md +93 -1
- package/docs/terminal-setup.md +23 -2
- package/docs/themes.md +24 -3
- package/docs/tui.md +2 -2
- package/docs/usage.md +24 -4
- package/examples/extensions/subagent/agents.ts +40 -9
- package/examples/extensions/subagent/index.ts +26 -3
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +38 -0
- package/node_modules/@code-yeongyu/senpi-codemode/README.md +5 -0
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +5 -4
- package/node_modules/@code-yeongyu/senpi-codemode/src/index.ts +14 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/call-capture.ts +64 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/cell-handler.ts +45 -61
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/cell-runtime.ts +6 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-execution-event.ts +201 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool-options.ts +2 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool.ts +22 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.d.ts +25 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.js +77 -12
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/events.d.ts +43 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/events.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/events.js +67 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/events.js.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.d.ts +4 -2
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.js +127 -88
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/errors.d.ts +5 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/errors.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/errors.js +9 -2
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/errors.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/repo.d.ts +12 -3
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/repo.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/repo.js +88 -45
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/repo.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/storage.d.ts +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/storage.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/storage.js +28 -19
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/storage.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/types.d.ts +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/types.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/types.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory.d.ts +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.d.ts +6 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.js +7 -2
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/state.d.ts +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/state.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/state.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance.js +19 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.d.ts +18 -5
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/index.d.ts +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/index.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/index.js +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/index.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/proxy.d.ts +4 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/proxy.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/proxy.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/search/index.d.ts +21 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/search/index.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/search/index.js +2 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/search/index.js.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/search/scanning.d.ts +29 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/search/scanning.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/search/scanning.js +103 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/search/scanning.js.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/node_modules/@earendil-works/pi-ai/README.md +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +40 -14
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.js +16 -4
- package/node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-gateway-binding.d.ts +69 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-gateway-binding.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-gateway-binding.js +159 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-gateway-binding.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/constrained-sampling.d.ts +3 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/constrained-sampling.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/constrained-sampling.js +125 -5
- package/node_modules/@earendil-works/pi-ai/dist/api/constrained-sampling.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.js +7 -3
- package/node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/google-shared.d.ts +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/google-shared.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/google-shared.js +13 -9
- package/node_modules/@earendil-works/pi-ai/dist/api/google-shared.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/google-vertex.js +7 -3
- package/node_modules/@earendil-works/pi-ai/dist/api/google-vertex.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.d.ts +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js +208 -42
- package/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +13 -4
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +10 -7
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.d.ts +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +31 -7
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +8 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/cursor.d.ts +16 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/cursor.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/cursor.js +234 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/cursor.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot.js +6 -3
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/load.d.ts +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/load.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/load.js +5 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/load.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js +44 -9
- package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/types.d.ts +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/types.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/types.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/bun-oauth.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/bun-oauth.js +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/bun-oauth.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts +15 -0
- package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +15 -0
- package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/all.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/all.js +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/all.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/cursor.d.ts +15 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/cursor.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/cursor.js +32 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/cursor.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/alibaba-token-plan.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/deepseek.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/google-vertex.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/google.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/kimi-coding.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai-codex.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan-cn.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai-coding-cn.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/types.d.ts +14 -3
- package/node_modules/@earendil-works/pi-ai/dist/types.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/types.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.d.ts +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.js +12 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/prompt-cache-ttl.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/prompt-cache-ttl.js +3 -2
- package/node_modules/@earendil-works/pi-ai/dist/utils/prompt-cache-ttl.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/validation.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/validation.js +34 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/validation.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/node_modules/@earendil-works/pi-pty/package.json +1 -1
- package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/node_modules/@earendil-works/pi-tui/README.md +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/alt-screen-search.d.ts +26 -0
- package/node_modules/@earendil-works/pi-tui/dist/alt-screen-search.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-tui/dist/alt-screen-search.js +121 -0
- package/node_modules/@earendil-works/pi-tui/dist/alt-screen-search.js.map +1 -0
- package/node_modules/@earendil-works/pi-tui/dist/components/scroll-view.d.ts +6 -1
- package/node_modules/@earendil-works/pi-tui/dist/components/scroll-view.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/components/scroll-view.js +23 -7
- package/node_modules/@earendil-works/pi-tui/dist/components/scroll-view.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/index.d.ts +4 -1
- package/node_modules/@earendil-works/pi-tui/dist/index.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/index.js +7 -1
- package/node_modules/@earendil-works/pi-tui/dist/index.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/keybindings.d.ts +30 -0
- package/node_modules/@earendil-works/pi-tui/dist/keybindings.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/keybindings.js +24 -0
- package/node_modules/@earendil-works/pi-tui/dist/keybindings.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/layout.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/layout.js +9 -2
- package/node_modules/@earendil-works/pi-tui/dist/layout.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts +8 -2
- package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js +6 -2
- package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts +6 -0
- package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/terminal.js +18 -1
- package/node_modules/@earendil-works/pi-tui/dist/terminal.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts +21 -0
- package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +243 -5
- package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +2 -0
- package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui.js +33 -8
- package/node_modules/@earendil-works/pi-tui/dist/tui.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/package.json +7 -7
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/search.d.ts +0 -19
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/search.d.ts.map +0 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/search.js +0 -41
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/search.js.map +0 -1
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI Gateway transport over the Workers AI binding.
|
|
3
|
+
*
|
|
4
|
+
* pi's Cloudflare AI Gateway support speaks HTTPS
|
|
5
|
+
* (`gateway.ai.cloudflare.com/v1/{account}/{gateway}/{provider}/...`, see `api/cloudflare.ts`),
|
|
6
|
+
* which needs a Cloudflare API token even when the caller is a Worker in the gateway's own
|
|
7
|
+
* account.
|
|
8
|
+
*
|
|
9
|
+
* In order to solve for this problem, `createGatewayBindingFetch` returns a {@link FetchFunction}
|
|
10
|
+
* that translates requests under a gateway HTTPS prefix into calls to the Workers AI binding's
|
|
11
|
+
* universal endpoint, `env.AI.gateway(id).run({provider, endpoint, headers, query})`.
|
|
12
|
+
* Binding calls are pre-authenticated in-account and return the provider's native wire format as a
|
|
13
|
+
* regular (streaming) `Response`, so API implementations behave identically over either
|
|
14
|
+
* transport.
|
|
15
|
+
*
|
|
16
|
+
* The result is the transport for one gateway-bound client, not a general-purpose fetch:
|
|
17
|
+
* requests it cannot serve — URLs outside the prefix, or in-prefix requests the universal
|
|
18
|
+
* endpoint cannot express (non-POST, non-JSON body) — reject with a descriptive error.
|
|
19
|
+
* Transport selection is the caller's job, per client: route such traffic over HTTPS with
|
|
20
|
+
* real gateway auth instead of through this shim.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* Placeholder value for auth headers on binding-routed requests. API implementations
|
|
24
|
+
* require an API key or a recognized auth header (`authorization`, `x-api-key`,
|
|
25
|
+
* `cf-aig-authorization`) before dispatch; binding calls are pre-authenticated, so pass
|
|
26
|
+
* `cf-aig-authorization: Bearer ${CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL}` to satisfy
|
|
27
|
+
* the check. The shim strips `cf-aig-authorization` before calling the binding. Pair it with
|
|
28
|
+
* `Authorization: null` / `x-api-key: null` so the SDKs' placeholder auth headers never reach
|
|
29
|
+
* the gateway, which would treat a request-supplied auth header as a BYOK provider key that
|
|
30
|
+
* overrides its stored keys — the same as it would over HTTPS.
|
|
31
|
+
*/
|
|
32
|
+
export const CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL = "cloudflare-gateway-binding";
|
|
33
|
+
// Never forwarded to the binding: hop-by-hop/derived headers, and gateway auth
|
|
34
|
+
// (binding calls are pre-authenticated; the sentinel must not reach the wire).
|
|
35
|
+
const STRIP_HEADERS = new Set(["content-length", "host", "cf-aig-authorization"]);
|
|
36
|
+
/**
|
|
37
|
+
* Create a `fetch` that routes AI Gateway requests through the Workers AI binding.
|
|
38
|
+
* See the module docs for behavior and composition notes.
|
|
39
|
+
*/
|
|
40
|
+
export function createGatewayBindingFetch(options) {
|
|
41
|
+
const { binding, gateway } = options;
|
|
42
|
+
// Prefix matching runs on URL-normalized components (origin + pathname), not raw strings:
|
|
43
|
+
// dot segments resolve away and fragments drop, matching what real fetch would put on the
|
|
44
|
+
// wire, so a lexical variant can't split provider/endpoint differently than HTTPS would.
|
|
45
|
+
const base = new URL(options.baseUrl);
|
|
46
|
+
const basePath = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
|
|
47
|
+
return async (input, init) => {
|
|
48
|
+
const request = input instanceof Request ? input : undefined;
|
|
49
|
+
const url = request ? request.url : input.toString();
|
|
50
|
+
const method = (init?.method ?? request?.method ?? "GET").toUpperCase();
|
|
51
|
+
let parsed;
|
|
52
|
+
try {
|
|
53
|
+
parsed = new URL(url);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
parsed = undefined;
|
|
57
|
+
}
|
|
58
|
+
// Out-of-prefix URLs are a configuration bug, not passthrough traffic: silently
|
|
59
|
+
// forwarding would ship the auth sentinel to whatever host the URL names.
|
|
60
|
+
if (parsed === undefined || parsed.origin !== base.origin || !parsed.pathname.startsWith(basePath)) {
|
|
61
|
+
throw new Error(`createGatewayBindingFetch: ${method} ${url} is outside the configured gateway ` +
|
|
62
|
+
`prefix (${base.origin}${basePath}); this fetch only serves its gateway-bound client`);
|
|
63
|
+
}
|
|
64
|
+
// In-prefix requests the universal endpoint cannot express always reject: forwarding
|
|
65
|
+
// them over HTTPS would send the sentinel to the gateway and fail with a misleading
|
|
66
|
+
// auth error instead of naming the real problem. Callers that need such endpoints
|
|
67
|
+
// route them over HTTPS with real gateway auth themselves.
|
|
68
|
+
const unexpressible = (reason) => {
|
|
69
|
+
throw new Error(`createGatewayBindingFetch: cannot express ${method} ${url} as a universal ` +
|
|
70
|
+
`gateway request (${reason}); route it over HTTPS with gateway auth instead`);
|
|
71
|
+
};
|
|
72
|
+
if (method !== "POST")
|
|
73
|
+
return unexpressible("only POST is supported");
|
|
74
|
+
const rest = parsed.pathname.slice(basePath.length);
|
|
75
|
+
const slash = rest.indexOf("/");
|
|
76
|
+
if (slash <= 0) {
|
|
77
|
+
return unexpressible("missing provider/endpoint path");
|
|
78
|
+
}
|
|
79
|
+
const provider = rest.slice(0, slash);
|
|
80
|
+
// Keep the query string on the endpoint — it's part of what HTTPS would have sent.
|
|
81
|
+
const endpoint = rest.slice(slash + 1) + parsed.search;
|
|
82
|
+
const bodyText = await readBodyText(request, init);
|
|
83
|
+
let query;
|
|
84
|
+
try {
|
|
85
|
+
query = bodyText === undefined ? undefined : JSON.parse(bodyText);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return unexpressible("non-JSON body");
|
|
89
|
+
}
|
|
90
|
+
if (query === undefined) {
|
|
91
|
+
return unexpressible("missing body");
|
|
92
|
+
}
|
|
93
|
+
const headers = collectHeaders(request, init);
|
|
94
|
+
// Per the fetch spec an explicit `signal: null` in init clears a Request input's signal.
|
|
95
|
+
const signal = init?.signal ?? (init && "signal" in init && init.signal === null ? undefined : request?.signal);
|
|
96
|
+
return binding.gateway(gateway).run({ provider, endpoint, headers, query }, signal ? { signal } : {});
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
async function readBodyText(request, init) {
|
|
100
|
+
const body = init?.body;
|
|
101
|
+
if (body === undefined || body === null) {
|
|
102
|
+
// Per the fetch spec an explicit `body: null` in init clears a Request input's body.
|
|
103
|
+
if (init && "body" in init && body === null)
|
|
104
|
+
return undefined;
|
|
105
|
+
if (request && request.body !== null)
|
|
106
|
+
return request.clone().text();
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
if (typeof body === "string")
|
|
110
|
+
return body;
|
|
111
|
+
if (body instanceof Uint8Array)
|
|
112
|
+
return new TextDecoder().decode(body);
|
|
113
|
+
if (body instanceof ArrayBuffer)
|
|
114
|
+
return new TextDecoder().decode(new Uint8Array(body));
|
|
115
|
+
// URLSearchParams, FormData, Blob, ReadableStream in init: read via a Request wrapper.
|
|
116
|
+
// Consuming a one-shot stream here is fine — unexpressible requests reject rather than
|
|
117
|
+
// replay, so nothing downstream needs the body again.
|
|
118
|
+
return new Request("http://body.local", {
|
|
119
|
+
method: "POST",
|
|
120
|
+
body,
|
|
121
|
+
// The fetch spec requires `duplex: "half"` to construct a Request with a stream body
|
|
122
|
+
// (Node's undici enforces it; it is ignored for the replayable body types). TypeScript's
|
|
123
|
+
// RequestInit does not declare the field yet, hence the cast.
|
|
124
|
+
duplex: "half",
|
|
125
|
+
}).text();
|
|
126
|
+
}
|
|
127
|
+
// Entry header names are lowercased so case-variant duplicates collapse and stripping is
|
|
128
|
+
// uniform. Per the fetch spec, `init.headers` replaces a Request input's headers entirely.
|
|
129
|
+
function collectHeaders(request, init) {
|
|
130
|
+
const result = {};
|
|
131
|
+
const add = (key, value) => {
|
|
132
|
+
const name = key.toLowerCase();
|
|
133
|
+
if (!STRIP_HEADERS.has(name))
|
|
134
|
+
result[name] = value;
|
|
135
|
+
};
|
|
136
|
+
const headers = init?.headers;
|
|
137
|
+
if (headers === undefined) {
|
|
138
|
+
if (request) {
|
|
139
|
+
for (const [key, value] of request.headers)
|
|
140
|
+
add(key, value);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
else if (headers instanceof Headers) {
|
|
144
|
+
for (const [key, value] of headers)
|
|
145
|
+
add(key, value);
|
|
146
|
+
}
|
|
147
|
+
else if (Array.isArray(headers)) {
|
|
148
|
+
for (const [key, value] of headers)
|
|
149
|
+
add(key, value);
|
|
150
|
+
}
|
|
151
|
+
else {
|
|
152
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
153
|
+
if (value !== undefined)
|
|
154
|
+
add(key, String(value));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return result;
|
|
158
|
+
}
|
|
159
|
+
//# sourceMappingURL=cloudflare-gateway-binding.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloudflare-gateway-binding.js","sourceRoot":"","sources":["../../src/api/cloudflare-gateway-binding.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAwBH;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,wCAAwC,GAAG,4BAA4B,CAAC;AAcrF,+EAA+E;AAC/E,+EAA+E;AAC/E,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,gBAAgB,EAAE,MAAM,EAAE,sBAAsB,CAAC,CAAC,CAAC;AAIlF;;;GAGG;AACH,MA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C,OAAO,CAAC,EAAE,CAAC;YACpD,IAAI,KAAK,KAAK,SAAS;gBAAE,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QAClD,CAAC;IACF,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["/**\n * AI Gateway transport over the Workers AI binding.\n *\n * pi's Cloudflare AI Gateway support speaks HTTPS\n * (`gateway.ai.cloudflare.com/v1/{account}/{gateway}/{provider}/...`, see `api/cloudflare.ts`),\n * which needs a Cloudflare API token even when the caller is a Worker in the gateway's own\n * account.\n *\n * In order to solve for this problem, `createGatewayBindingFetch` returns a {@link FetchFunction}\n * that translates requests under a gateway HTTPS prefix into calls to the Workers AI binding's\n * universal endpoint, `env.AI.gateway(id).run({provider, endpoint, headers, query})`.\n * Binding calls are pre-authenticated in-account and return the provider's native wire format as a\n * regular (streaming) `Response`, so API implementations behave identically over either\n * transport.\n *\n * The result is the transport for one gateway-bound client, not a general-purpose fetch:\n * requests it cannot serve — URLs outside the prefix, or in-prefix requests the universal\n * endpoint cannot express (non-POST, non-JSON body) — reject with a descriptive error.\n * Transport selection is the caller's job, per client: route such traffic over HTTPS with\n * real gateway auth instead of through this shim.\n */\n\nimport type { FetchFunction } from \"../types.ts\";\n\n/**\n * Structural type for the Workers AI binding's gateway surface (`env.AI`), so this\n * module does not depend on `@cloudflare/workers-types`. Any real `Ai` binding satisfies it.\n */\nexport interface AiGatewayBinding {\n\tgateway(id: string): AiGatewayBindingGateway;\n}\n\nexport interface AiGatewayBindingGateway {\n\trun(data: AiGatewayUniversalRequestLike, options?: { signal?: AbortSignal }): Promise<Response>;\n}\n\n/** One universal-endpoint request entry, as accepted by `AiGateway.run()`. */\nexport interface AiGatewayUniversalRequestLike {\n\tprovider: string;\n\tendpoint: string;\n\theaders: Record<string, string>;\n\tquery: unknown;\n}\n\n/**\n * Placeholder value for auth headers on binding-routed requests. API implementations\n * require an API key or a recognized auth header (`authorization`, `x-api-key`,\n * `cf-aig-authorization`) before dispatch; binding calls are pre-authenticated, so pass\n * `cf-aig-authorization: Bearer ${CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL}` to satisfy\n * the check. The shim strips `cf-aig-authorization` before calling the binding. Pair it with\n * `Authorization: null` / `x-api-key: null` so the SDKs' placeholder auth headers never reach\n * the gateway, which would treat a request-supplied auth header as a BYOK provider key that\n * overrides its stored keys — the same as it would over HTTPS.\n */\nexport const CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL = \"cloudflare-gateway-binding\";\n\nexport interface GatewayBindingFetchOptions {\n\t/** The Workers AI binding (e.g. `env.AI`). */\n\tbinding: AiGatewayBinding;\n\t/**\n\t * Gateway HTTPS prefix every request must fall under, without a trailing slash:\n\t * `https://gateway.ai.cloudflare.com/v1/{accountId}/{gatewayName}`.\n\t */\n\tbaseUrl: string;\n\t/** Gateway name passed to `binding.gateway()`. Must match the `baseUrl` gateway. */\n\tgateway: string;\n}\n\n// Never forwarded to the binding: hop-by-hop/derived headers, and gateway auth\n// (binding calls are pre-authenticated; the sentinel must not reach the wire).\nconst STRIP_HEADERS = new Set([\"content-length\", \"host\", \"cf-aig-authorization\"]);\n\ntype FetchInput = Parameters<FetchFunction>[0];\n\n/**\n * Create a `fetch` that routes AI Gateway requests through the Workers AI binding.\n * See the module docs for behavior and composition notes.\n */\nexport function createGatewayBindingFetch(options: GatewayBindingFetchOptions): FetchFunction {\n\tconst { binding, gateway } = options;\n\t// Prefix matching runs on URL-normalized components (origin + pathname), not raw strings:\n\t// dot segments resolve away and fragments drop, matching what real fetch would put on the\n\t// wire, so a lexical variant can't split provider/endpoint differently than HTTPS would.\n\tconst base = new URL(options.baseUrl);\n\tconst basePath = base.pathname.endsWith(\"/\") ? base.pathname : `${base.pathname}/`;\n\n\treturn async (input: FetchInput, init?: RequestInit): Promise<Response> => {\n\t\tconst request = input instanceof Request ? input : undefined;\n\t\tconst url = request ? request.url : input.toString();\n\t\tconst method = (init?.method ?? request?.method ?? \"GET\").toUpperCase();\n\t\tlet parsed: URL | undefined;\n\t\ttry {\n\t\t\tparsed = new URL(url);\n\t\t} catch {\n\t\t\tparsed = undefined;\n\t\t}\n\t\t// Out-of-prefix URLs are a configuration bug, not passthrough traffic: silently\n\t\t// forwarding would ship the auth sentinel to whatever host the URL names.\n\t\tif (parsed === undefined || parsed.origin !== base.origin || !parsed.pathname.startsWith(basePath)) {\n\t\t\tthrow new Error(\n\t\t\t\t`createGatewayBindingFetch: ${method} ${url} is outside the configured gateway ` +\n\t\t\t\t\t`prefix (${base.origin}${basePath}); this fetch only serves its gateway-bound client`,\n\t\t\t);\n\t\t}\n\n\t\t// In-prefix requests the universal endpoint cannot express always reject: forwarding\n\t\t// them over HTTPS would send the sentinel to the gateway and fail with a misleading\n\t\t// auth error instead of naming the real problem. Callers that need such endpoints\n\t\t// route them over HTTPS with real gateway auth themselves.\n\t\tconst unexpressible = (reason: string): never => {\n\t\t\tthrow new Error(\n\t\t\t\t`createGatewayBindingFetch: cannot express ${method} ${url} as a universal ` +\n\t\t\t\t\t`gateway request (${reason}); route it over HTTPS with gateway auth instead`,\n\t\t\t);\n\t\t};\n\t\tif (method !== \"POST\") return unexpressible(\"only POST is supported\");\n\n\t\tconst rest = parsed.pathname.slice(basePath.length);\n\t\tconst slash = rest.indexOf(\"/\");\n\t\tif (slash <= 0) {\n\t\t\treturn unexpressible(\"missing provider/endpoint path\");\n\t\t}\n\t\tconst provider = rest.slice(0, slash);\n\t\t// Keep the query string on the endpoint — it's part of what HTTPS would have sent.\n\t\tconst endpoint = rest.slice(slash + 1) + parsed.search;\n\n\t\tconst bodyText = await readBodyText(request, init);\n\t\tlet query: unknown;\n\t\ttry {\n\t\t\tquery = bodyText === undefined ? undefined : JSON.parse(bodyText);\n\t\t} catch {\n\t\t\treturn unexpressible(\"non-JSON body\");\n\t\t}\n\t\tif (query === undefined) {\n\t\t\treturn unexpressible(\"missing body\");\n\t\t}\n\n\t\tconst headers = collectHeaders(request, init);\n\t\t// Per the fetch spec an explicit `signal: null` in init clears a Request input's signal.\n\t\tconst signal = init?.signal ?? (init && \"signal\" in init && init.signal === null ? undefined : request?.signal);\n\t\treturn binding.gateway(gateway).run({ provider, endpoint, headers, query }, signal ? { signal } : {});\n\t};\n}\n\nasync function readBodyText(request: Request | undefined, init?: RequestInit): Promise<string | undefined> {\n\tconst body = init?.body;\n\tif (body === undefined || body === null) {\n\t\t// Per the fetch spec an explicit `body: null` in init clears a Request input's body.\n\t\tif (init && \"body\" in init && body === null) return undefined;\n\t\tif (request && request.body !== null) return request.clone().text();\n\t\treturn undefined;\n\t}\n\tif (typeof body === \"string\") return body;\n\tif (body instanceof Uint8Array) return new TextDecoder().decode(body);\n\tif (body instanceof ArrayBuffer) return new TextDecoder().decode(new Uint8Array(body));\n\t// URLSearchParams, FormData, Blob, ReadableStream in init: read via a Request wrapper.\n\t// Consuming a one-shot stream here is fine — unexpressible requests reject rather than\n\t// replay, so nothing downstream needs the body again.\n\treturn new Request(\"http://body.local\", {\n\t\tmethod: \"POST\",\n\t\tbody,\n\t\t// The fetch spec requires `duplex: \"half\"` to construct a Request with a stream body\n\t\t// (Node's undici enforces it; it is ignored for the replayable body types). TypeScript's\n\t\t// RequestInit does not declare the field yet, hence the cast.\n\t\tduplex: \"half\",\n\t} as RequestInit).text();\n}\n\n// Entry header names are lowercased so case-variant duplicates collapse and stripping is\n// uniform. Per the fetch spec, `init.headers` replaces a Request input's headers entirely.\nfunction collectHeaders(request: Request | undefined, init?: RequestInit): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\tconst add = (key: string, value: string) => {\n\t\tconst name = key.toLowerCase();\n\t\tif (!STRIP_HEADERS.has(name)) result[name] = value;\n\t};\n\tconst headers = init?.headers;\n\tif (headers === undefined) {\n\t\tif (request) {\n\t\t\tfor (const [key, value] of request.headers) add(key, value);\n\t\t}\n\t} else if (headers instanceof Headers) {\n\t\tfor (const [key, value] of headers) add(key, value);\n\t} else if (Array.isArray(headers)) {\n\t\tfor (const [key, value] of headers) add(key, value);\n\t} else {\n\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\tif (value !== undefined) add(key, String(value));\n\t\t}\n\t}\n\treturn result;\n}\n"]}
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import type { Tool } from "../types.ts";
|
|
2
|
+
/** Convert a tool schema to the strict subset expected by provider constrained sampling. */
|
|
3
|
+
export declare function makeStrictJsonSchema(schema: Tool["parameters"]): Record<string, unknown>;
|
|
4
|
+
export declare function getJsonSchemaToolParameters(tool: Tool, strict: boolean | undefined): Tool["parameters"];
|
|
2
5
|
export interface GrammarConstrainedSampling {
|
|
3
6
|
format: "lark" | "regex";
|
|
4
7
|
definition: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constrained-sampling.d.ts","sourceRoot":"","sources":["../../src/api/constrained-sampling.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"constrained-sampling.d.ts","sourceRoot":"","sources":["../../src/api/constrained-sampling.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAmHxC,4FAA4F;AAC5F,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,IAAI,CAAC,YAAY,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAUxF;AAED,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,GAAG,SAAS,GAAG,IAAI,CAAC,YAAY,CAAC,CAEvG;AAED,MAAM,WAAW,0BAA0B;IAC1C,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IACzB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,0BAA0B;IAC1C,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,OAAO,CAAC;CAChB;AAED,wBAAgB,mBAAmB,CAClC,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACnC,aAAa,EAAE,MAAM,GACnB,MAAM,CAMR;AAED,wBAAgB,+BAA+B,CAC9C,MAAM,EAAE,0BAA0B,EAClC,aAAa,EAAE,MAAM,EACrB,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,OAAO,GACZ,MAAM,GAAG,SAAS,CAyBpB;AAqBD,wBAAgB,+BAA+B,CAAC,IAAI,EAAE,IAAI,EAAE,kBAAkB,EAAE,OAAO,GAAG,OAAO,GAAG,SAAS,CAoB5G;AAED,wBAAgB,iCAAiC,CAChD,IAAI,EAAE,IAAI,EACV,0BAA0B,EAAE,OAAO,GACjC,0BAA0B,GAAG,SAAS,CA+BxC;AAED,wBAAgB,gCAAgC,CAC/C,KAAK,EAAE,IAAI,EAAE,GAAG,SAAS,EACzB,0BAA0B,EAAE,OAAO,GACjC,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAS7B"}
|
|
@@ -1,3 +1,116 @@
|
|
|
1
|
+
class UnsupportedStrictJsonSchemaError extends Error {
|
|
2
|
+
}
|
|
3
|
+
const UNSUPPORTED_STRICT_SCHEMA_KEYS = [
|
|
4
|
+
"$ref",
|
|
5
|
+
"$defs",
|
|
6
|
+
"definitions",
|
|
7
|
+
"allOf",
|
|
8
|
+
"oneOf",
|
|
9
|
+
"patternProperties",
|
|
10
|
+
"dependentSchemas",
|
|
11
|
+
"dependencies",
|
|
12
|
+
"unevaluatedProperties",
|
|
13
|
+
"propertyNames",
|
|
14
|
+
"contains",
|
|
15
|
+
"prefixItems",
|
|
16
|
+
"not",
|
|
17
|
+
"if",
|
|
18
|
+
"then",
|
|
19
|
+
"else",
|
|
20
|
+
];
|
|
21
|
+
function isJsonSchemaObject(value) {
|
|
22
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
23
|
+
}
|
|
24
|
+
function isStructuredSchema(schema) {
|
|
25
|
+
if (!isJsonSchemaObject(schema))
|
|
26
|
+
return false;
|
|
27
|
+
const types = typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : [];
|
|
28
|
+
return (types.includes("object") ||
|
|
29
|
+
types.includes("array") ||
|
|
30
|
+
schema.properties !== undefined ||
|
|
31
|
+
schema.items !== undefined);
|
|
32
|
+
}
|
|
33
|
+
function schemaAllowsNull(schema) {
|
|
34
|
+
if (!isJsonSchemaObject(schema))
|
|
35
|
+
return false;
|
|
36
|
+
if (schema.type === "null" || (Array.isArray(schema.type) && schema.type.includes("null")))
|
|
37
|
+
return true;
|
|
38
|
+
if (schema.const === null || (Array.isArray(schema.enum) && schema.enum.includes(null)))
|
|
39
|
+
return true;
|
|
40
|
+
return Array.isArray(schema.anyOf) && schema.anyOf.some((variant) => schemaAllowsNull(variant));
|
|
41
|
+
}
|
|
42
|
+
function makeJsonSchemaNodeStrict(schema) {
|
|
43
|
+
if (!isJsonSchemaObject(schema)) {
|
|
44
|
+
throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");
|
|
45
|
+
}
|
|
46
|
+
for (const key of UNSUPPORTED_STRICT_SCHEMA_KEYS) {
|
|
47
|
+
if (schema[key] !== undefined) {
|
|
48
|
+
throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (schema.anyOf !== undefined) {
|
|
52
|
+
if (!Array.isArray(schema.anyOf) || schema.anyOf.length === 0) {
|
|
53
|
+
throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");
|
|
54
|
+
}
|
|
55
|
+
for (const variant of schema.anyOf) {
|
|
56
|
+
if (isStructuredSchema(variant)) {
|
|
57
|
+
throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");
|
|
58
|
+
}
|
|
59
|
+
makeJsonSchemaNodeStrict(variant);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (schema.items !== undefined) {
|
|
63
|
+
if (Array.isArray(schema.items)) {
|
|
64
|
+
throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");
|
|
65
|
+
}
|
|
66
|
+
makeJsonSchemaNodeStrict(schema.items);
|
|
67
|
+
}
|
|
68
|
+
const isObjectSchema = schema.type === "object";
|
|
69
|
+
if (schema.properties !== undefined && !isObjectSchema) {
|
|
70
|
+
throw new UnsupportedStrictJsonSchemaError("properties require type object");
|
|
71
|
+
}
|
|
72
|
+
if (!isObjectSchema)
|
|
73
|
+
return;
|
|
74
|
+
if (schema.additionalProperties !== undefined && schema.additionalProperties !== false) {
|
|
75
|
+
throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");
|
|
76
|
+
}
|
|
77
|
+
if (schema.properties !== undefined && !isJsonSchemaObject(schema.properties)) {
|
|
78
|
+
throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");
|
|
79
|
+
}
|
|
80
|
+
if (schema.required !== undefined &&
|
|
81
|
+
(!Array.isArray(schema.required) || schema.required.some((key) => typeof key !== "string"))) {
|
|
82
|
+
throw new UnsupportedStrictJsonSchemaError("object required must be a string array");
|
|
83
|
+
}
|
|
84
|
+
const properties = schema.properties ?? {};
|
|
85
|
+
const propertyNames = Object.keys(properties);
|
|
86
|
+
const required = new Set(Array.isArray(schema.required) ? schema.required : []);
|
|
87
|
+
if ([...required].some((key) => !propertyNames.includes(key))) {
|
|
88
|
+
throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");
|
|
89
|
+
}
|
|
90
|
+
for (const [key, property] of Object.entries(properties)) {
|
|
91
|
+
makeJsonSchemaNodeStrict(property);
|
|
92
|
+
if (!required.has(key) && !schemaAllowsNull(property)) {
|
|
93
|
+
properties[key] = { anyOf: [property, { type: "null" }] };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
schema.required = propertyNames;
|
|
97
|
+
schema.additionalProperties = false;
|
|
98
|
+
}
|
|
99
|
+
/** Convert a tool schema to the strict subset expected by provider constrained sampling. */
|
|
100
|
+
export function makeStrictJsonSchema(schema) {
|
|
101
|
+
const cloned = structuredClone(schema);
|
|
102
|
+
if (!isJsonSchemaObject(cloned)) {
|
|
103
|
+
throw new UnsupportedStrictJsonSchemaError("root schema must have type object");
|
|
104
|
+
}
|
|
105
|
+
makeJsonSchemaNodeStrict(cloned);
|
|
106
|
+
if (cloned.type !== "object") {
|
|
107
|
+
throw new UnsupportedStrictJsonSchemaError("root schema must have type object");
|
|
108
|
+
}
|
|
109
|
+
return cloned;
|
|
110
|
+
}
|
|
111
|
+
export function getJsonSchemaToolParameters(tool, strict) {
|
|
112
|
+
return (strict === true ? makeStrictJsonSchema(tool.parameters) : tool.parameters);
|
|
113
|
+
}
|
|
1
114
|
export function getGrammarToolInput(toolName, arguments_, inputProperty) {
|
|
2
115
|
const input = arguments_[inputProperty];
|
|
3
116
|
if (typeof input !== "string") {
|
|
@@ -49,13 +162,20 @@ function inferGrammarInputProperty(tool) {
|
|
|
49
162
|
}
|
|
50
163
|
export function resolveJsonSchemaStrictSampling(tool, supportsStrictMode) {
|
|
51
164
|
const config = tool.constrainedSampling;
|
|
52
|
-
if (
|
|
53
|
-
return undefined;
|
|
54
|
-
if (config.type !== "json_schema") {
|
|
165
|
+
if (config === false || config?.type !== "json_schema")
|
|
55
166
|
return undefined;
|
|
56
|
-
}
|
|
57
167
|
if (supportsStrictMode) {
|
|
58
|
-
|
|
168
|
+
try {
|
|
169
|
+
makeStrictJsonSchema(tool.parameters);
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
if (!(error instanceof UnsupportedStrictJsonSchemaError))
|
|
174
|
+
throw error;
|
|
175
|
+
if (config.strict !== "require")
|
|
176
|
+
return undefined;
|
|
177
|
+
throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`);
|
|
178
|
+
}
|
|
59
179
|
}
|
|
60
180
|
if (config.strict === "require") {
|
|
61
181
|
throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constrained-sampling.js","sourceRoot":"","sources":["../../src/api/constrained-sampling.ts"],"names":[],"mappings":"AAoBA,MAAM,UAAU,mBAAmB,CAClC,QAAgB,EAChB,UAAmC,EACnC,aAAqB;IAErB,MAAM,KAAK,GAAG,UAAU,CAAC,aAAa,CAAC,CAAC;IACxC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC/B,MAAM,IAAI,KAAK,CAAC,sBAAsB,QAAQ,wBAAwB,aAAa,mBAAmB,CAAC,CAAC;IACzG,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC;AAED,MAAM,UAAU,+BAA+B,CAC9C,MAAkC,EAClC,aAAqB,EACrB,SAAiB,EACjB,KAAc;IAEd,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;QACnB,IAAI,KAAK,IAAI,SAAS,KAAK,MAAM,CAAC,KAAK;YAAE,OAAO,SAAS,CAAC;QAC1D,MAAM,IAAI,KAAK,CAAC,oCAAoC,aAAa,+BAA+B,CAAC,CAAC;IACnG,CAAC;IACD,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QACzC,MAAM,IAAI,KAAK,CAAC,oCAAoC,aAAa,6BAA6B,CAAC,CAAC;IACjG,CAAC;IAED,MAAM,UAAU,GAAG,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACxD,IAAI,CAAC,KAAK,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAExD,IAAI,KAAK,GAAG,EAAE,CAAC;IACf,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACrB,KAAK,IAAI,IAAI,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,IAAI,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,CAAC,IAAI,uFAAuF,CACzG,CAAC;IACH,CAAC;IAED,IAAI,CAAC;QACJ,OAAO;YACN,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO;YAC5C,UAAU,EAAE,iBAAiB,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,eAAgB;YACjE,aAAa,EAAE,yBAAyB,CAAC,IAAI,CAAC;SAC9C,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACvE,MAAM,IAAI,KAAK,CAAC,SAAS,IAAI,CAAC,IAAI,8CAA8C,OAAO,GAAG,CAAC,CAAC;IAC7F,CAAC;AACF,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC/C,KAAyB,EACzB,0BAAmC;IAEnC,MAAM,UAAU,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC7C,KAAK,MAAM,IAAI,IAAI,KAAK,IAAI,EAAE,EAAE,CAAC;QAChC,MAAM,OAAO,GAAG,iCAAiC,CAAC,IAAI,EAAE,0BAA0B,CAAC,CAAC;QACpF,IAAI,OAAO,EAAE,CAAC;YACb,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;QAClD,CAAC;IACF,CAAC;IACD,OAAO,UAAU,CAAC;AACnB,CAAC","sourcesContent":["import type { Tool } from \"../types.ts\";\n\ninterface JsonSchemaObject {\n\ttype?: unknown;\n\tproperties?: Record<string, JsonSchemaObject | undefined>;\n\trequired?: unknown;\n}\n\nexport interface GrammarConstrainedSampling {\n\tformat: \"lark\" | \"regex\";\n\tdefinition: string;\n\tinputProperty: string;\n}\n\nexport interface GrammarToolInputJsonBuffer {\n\tinput: string;\n\tstarted: boolean;\n\tclosed: boolean;\n}\n\nexport function getGrammarToolInput(\n\ttoolName: string,\n\targuments_: Record<string, unknown>,\n\tinputProperty: string,\n): string {\n\tconst input = arguments_[inputProperty];\n\tif (typeof input !== \"string\") {\n\t\tthrow new Error(`Grammar tool call \"${toolName}\" requires argument \"${inputProperty}\" to be a string.`);\n\t}\n\treturn input;\n}\n\nexport function appendGrammarToolInputJsonDelta(\n\tbuffer: GrammarToolInputJsonBuffer,\n\tinputProperty: string,\n\tnextInput: string,\n\tclose: boolean,\n): string | undefined {\n\tif (buffer.closed) {\n\t\tif (close && nextInput === buffer.input) return undefined;\n\t\tthrow new Error(`grammar tool input for property \"${inputProperty}\" changed after it was closed`);\n\t}\n\tif (!nextInput.startsWith(buffer.input)) {\n\t\tthrow new Error(`grammar tool input for property \"${inputProperty}\" changed non-monotonically`);\n\t}\n\n\tconst inputDelta = nextInput.slice(buffer.input.length);\n\tif (!close && inputDelta.length === 0) return undefined;\n\n\tlet delta = \"\";\n\tif (!buffer.started) {\n\t\tdelta += `{${JSON.stringify(inputProperty)}:\"`;\n\t\tbuffer.started = true;\n\t}\n\tdelta += JSON.stringify(inputDelta).slice(1, -1);\n\tbuffer.input = nextInput;\n\n\tif (close) {\n\t\tdelta += '\"}';\n\t\tbuffer.closed = true;\n\t}\n\treturn delta;\n}\n\nfunction inferGrammarInputProperty(tool: Tool): string {\n\tconst schema = tool.parameters as JsonSchemaObject;\n\tif (schema.type !== \"object\") {\n\t\tthrow new Error(\"grammar constrained sampling requires an object parameter schema\");\n\t}\n\tif (!Array.isArray(schema.required) || schema.required.length !== 1 || typeof schema.required[0] !== \"string\") {\n\t\tthrow new Error(\"grammar constrained sampling requires exactly one required string property\");\n\t}\n\n\tconst inputProperty = schema.required[0];\n\tif (!schema.properties?.[inputProperty]) {\n\t\tthrow new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);\n\t}\n\tif (schema.properties[inputProperty]?.type !== \"string\") {\n\t\tthrow new Error(`grammar constrained sampling property ${inputProperty} must have type string`);\n\t}\n\treturn inputProperty;\n}\n\nexport function resolveJsonSchemaStrictSampling(tool: Tool, supportsStrictMode: boolean): boolean | undefined {\n\tconst config = tool.constrainedSampling;\n\tif (!config) return undefined;\n\tif (config.type !== \"json_schema\") {\n\t\treturn undefined;\n\t}\n\n\tif (supportsStrictMode) {\n\t\treturn true;\n\t}\n\tif (config.strict === \"require\") {\n\t\tthrow new Error(\n\t\t\t`Tool \"${tool.name}\" requires JSON-schema constrained sampling, but strict tools are unsupported.`,\n\t\t);\n\t}\n\treturn undefined;\n}\n\nexport function resolveGrammarConstrainedSampling(\n\ttool: Tool,\n\tsupportsOpenAIGrammarTools: boolean,\n): GrammarConstrainedSampling | undefined {\n\tconst config = tool.constrainedSampling;\n\tif (!config) return undefined;\n\tif (config.type !== \"grammar\") {\n\t\treturn undefined;\n\t}\n\n\tif (!supportsOpenAIGrammarTools) {\n\t\treturn undefined;\n\t}\n\n\tconst larkDefinition = config.variants.openai_lark;\n\tconst regexDefinition = config.variants.openai_regex;\n\tconst hasLarkDefinition = typeof larkDefinition === \"string\" && larkDefinition.trim().length > 0;\n\tconst hasRegexDefinition = typeof regexDefinition === \"string\" && regexDefinition.trim().length > 0;\n\tif (!hasLarkDefinition && !hasRegexDefinition) {\n\t\tthrow new Error(\n\t\t\t`Tool \"${tool.name}\" cannot use grammar constrained sampling: no supported grammar variant was provided.`,\n\t\t);\n\t}\n\n\ttry {\n\t\treturn {\n\t\t\tformat: hasLarkDefinition ? \"lark\" : \"regex\",\n\t\t\tdefinition: hasLarkDefinition ? larkDefinition : regexDefinition!,\n\t\t\tinputProperty: inferGrammarInputProperty(tool),\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`Tool \"${tool.name}\" cannot use grammar constrained sampling: ${message}.`);\n\t}\n}\n\nexport function createGrammarToolInputProperties(\n\ttools: Tool[] | undefined,\n\tsupportsOpenAIGrammarTools: boolean,\n): ReadonlyMap<string, string> {\n\tconst properties = new Map<string, string>();\n\tfor (const tool of tools ?? []) {\n\t\tconst grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);\n\t\tif (grammar) {\n\t\t\tproperties.set(tool.name, grammar.inputProperty);\n\t\t}\n\t}\n\treturn properties;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"constrained-sampling.js","sourceRoot":"","sources":["../../src/api/constrained-sampling.ts"],"names":[],"mappings":"AASA,MAAM,gCAAiC,SAAQ,KAAK;CAAG;AAEvD,MAAM,8BAA8B,GAAG;IACtC,MAAM;IACN,OAAO;IACP,aAAa;IACb,OAAO;IACP,OAAO;IACP,mBAAmB;IACnB,kBAAkB;IAClB,cAAc;IACd,uBAAuB;IACvB,eAAe;IACf,UAAU;IACV,aAAa;IACb,KAAK;IACL,IAAI;IACJ,MAAM;IACN,MAAM;CACG,CAAC;AAEX,SAAS,kBAAkB,CAAC,KAAc;IACzC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,kBAAkB,CAAC,MAAe;IAC1C,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9C,MAAM,KAAK,GAAG,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;IAC9G,OAAO,CACN,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC;QACxB,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC;QACvB,MAAM,CAAC,UAAU,KAAK,SAAS;QAC/B,MAAM,CAAC,KAAK,KAAK,SAAS,CAC1B,CAAC;AACH,CAAC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CAAC;AAED,MAAM,UAAU,gCAAgC,CAC/C,KAAyB,EACzB,0BAAmC;IAEnC,MAAM,UAAU,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC7C,KAAK,MAAM,IAAI,IAAI,KAAK,IAAI,EAAE,EAAE,CAAC;QAChC,MAAM,OAAO,GAAG,iCAAiC,CAAC,IAAI,EAAE,0BAA0B,CAAC,CAAC;QACpF,IAAI,OAAO,EAAE,CAAC;YACb,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;QAClD,CAAC;IACF,CAAC;IACD,OAAO,UAAU,CAAC;AACnB,CAAC","sourcesContent":["import type { Tool } from \"../types.ts\";\n\ninterface JsonSchemaObject {\n\t[key: string]: unknown;\n\ttype?: unknown;\n\tproperties?: Record<string, JsonSchemaObject | undefined>;\n\trequired?: unknown;\n}\n\nclass UnsupportedStrictJsonSchemaError extends Error {}\n\nconst UNSUPPORTED_STRICT_SCHEMA_KEYS = [\n\t\"$ref\",\n\t\"$defs\",\n\t\"definitions\",\n\t\"allOf\",\n\t\"oneOf\",\n\t\"patternProperties\",\n\t\"dependentSchemas\",\n\t\"dependencies\",\n\t\"unevaluatedProperties\",\n\t\"propertyNames\",\n\t\"contains\",\n\t\"prefixItems\",\n\t\"not\",\n\t\"if\",\n\t\"then\",\n\t\"else\",\n] as const;\n\nfunction isJsonSchemaObject(value: unknown): value is JsonSchemaObject {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isStructuredSchema(schema: unknown): boolean {\n\tif (!isJsonSchemaObject(schema)) return false;\n\tconst types = typeof schema.type === \"string\" ? [schema.type] : Array.isArray(schema.type) ? schema.type : [];\n\treturn (\n\t\ttypes.includes(\"object\") ||\n\t\ttypes.includes(\"array\") ||\n\t\tschema.properties !== undefined ||\n\t\tschema.items !== undefined\n\t);\n}\n\nfunction schemaAllowsNull(schema: unknown): boolean {\n\tif (!isJsonSchemaObject(schema)) return false;\n\tif (schema.type === \"null\" || (Array.isArray(schema.type) && schema.type.includes(\"null\"))) return true;\n\tif (schema.const === null || (Array.isArray(schema.enum) && schema.enum.includes(null))) return true;\n\treturn Array.isArray(schema.anyOf) && schema.anyOf.some((variant) => schemaAllowsNull(variant));\n}\n\nfunction makeJsonSchemaNodeStrict(schema: unknown): void {\n\tif (!isJsonSchemaObject(schema)) {\n\t\tthrow new UnsupportedStrictJsonSchemaError(\"boolean schemas are unsupported\");\n\t}\n\tfor (const key of UNSUPPORTED_STRICT_SCHEMA_KEYS) {\n\t\tif (schema[key] !== undefined) {\n\t\t\tthrow new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);\n\t\t}\n\t}\n\n\tif (schema.anyOf !== undefined) {\n\t\tif (!Array.isArray(schema.anyOf) || schema.anyOf.length === 0) {\n\t\t\tthrow new UnsupportedStrictJsonSchemaError(\"anyOf must contain at least one schema\");\n\t\t}\n\t\tfor (const variant of schema.anyOf) {\n\t\t\tif (isStructuredSchema(variant)) {\n\t\t\t\tthrow new UnsupportedStrictJsonSchemaError(\"object and array unions are unsupported\");\n\t\t\t}\n\t\t\tmakeJsonSchemaNodeStrict(variant);\n\t\t}\n\t}\n\n\tif (schema.items !== undefined) {\n\t\tif (Array.isArray(schema.items)) {\n\t\t\tthrow new UnsupportedStrictJsonSchemaError(\"tuple schemas are unsupported\");\n\t\t}\n\t\tmakeJsonSchemaNodeStrict(schema.items);\n\t}\n\n\tconst isObjectSchema = schema.type === \"object\";\n\tif (schema.properties !== undefined && !isObjectSchema) {\n\t\tthrow new UnsupportedStrictJsonSchemaError(\"properties require type object\");\n\t}\n\tif (!isObjectSchema) return;\n\tif (schema.additionalProperties !== undefined && schema.additionalProperties !== false) {\n\t\tthrow new UnsupportedStrictJsonSchemaError(\"schema-valued or true additionalProperties is unsupported\");\n\t}\n\tif (schema.properties !== undefined && !isJsonSchemaObject(schema.properties)) {\n\t\tthrow new UnsupportedStrictJsonSchemaError(\"object properties must be a schema map\");\n\t}\n\tif (\n\t\tschema.required !== undefined &&\n\t\t(!Array.isArray(schema.required) || schema.required.some((key) => typeof key !== \"string\"))\n\t) {\n\t\tthrow new UnsupportedStrictJsonSchemaError(\"object required must be a string array\");\n\t}\n\n\tconst properties = schema.properties ?? {};\n\tconst propertyNames = Object.keys(properties);\n\tconst required = new Set(Array.isArray(schema.required) ? schema.required : []);\n\tif ([...required].some((key) => !propertyNames.includes(key))) {\n\t\tthrow new UnsupportedStrictJsonSchemaError(\"required contains an unknown property\");\n\t}\n\tfor (const [key, property] of Object.entries(properties)) {\n\t\tmakeJsonSchemaNodeStrict(property);\n\t\tif (!required.has(key) && !schemaAllowsNull(property)) {\n\t\t\tproperties[key] = { anyOf: [property, { type: \"null\" }] };\n\t\t}\n\t}\n\tschema.required = propertyNames;\n\tschema.additionalProperties = false;\n}\n\n/** Convert a tool schema to the strict subset expected by provider constrained sampling. */\nexport function makeStrictJsonSchema(schema: Tool[\"parameters\"]): Record<string, unknown> {\n\tconst cloned: unknown = structuredClone(schema);\n\tif (!isJsonSchemaObject(cloned)) {\n\t\tthrow new UnsupportedStrictJsonSchemaError(\"root schema must have type object\");\n\t}\n\tmakeJsonSchemaNodeStrict(cloned);\n\tif (cloned.type !== \"object\") {\n\t\tthrow new UnsupportedStrictJsonSchemaError(\"root schema must have type object\");\n\t}\n\treturn cloned;\n}\n\nexport function getJsonSchemaToolParameters(tool: Tool, strict: boolean | undefined): Tool[\"parameters\"] {\n\treturn (strict === true ? makeStrictJsonSchema(tool.parameters) : tool.parameters) as Tool[\"parameters\"];\n}\n\nexport interface GrammarConstrainedSampling {\n\tformat: \"lark\" | \"regex\";\n\tdefinition: string;\n\tinputProperty: string;\n}\n\nexport interface GrammarToolInputJsonBuffer {\n\tinput: string;\n\tstarted: boolean;\n\tclosed: boolean;\n}\n\nexport function getGrammarToolInput(\n\ttoolName: string,\n\targuments_: Record<string, unknown>,\n\tinputProperty: string,\n): string {\n\tconst input = arguments_[inputProperty];\n\tif (typeof input !== \"string\") {\n\t\tthrow new Error(`Grammar tool call \"${toolName}\" requires argument \"${inputProperty}\" to be a string.`);\n\t}\n\treturn input;\n}\n\nexport function appendGrammarToolInputJsonDelta(\n\tbuffer: GrammarToolInputJsonBuffer,\n\tinputProperty: string,\n\tnextInput: string,\n\tclose: boolean,\n): string | undefined {\n\tif (buffer.closed) {\n\t\tif (close && nextInput === buffer.input) return undefined;\n\t\tthrow new Error(`grammar tool input for property \"${inputProperty}\" changed after it was closed`);\n\t}\n\tif (!nextInput.startsWith(buffer.input)) {\n\t\tthrow new Error(`grammar tool input for property \"${inputProperty}\" changed non-monotonically`);\n\t}\n\n\tconst inputDelta = nextInput.slice(buffer.input.length);\n\tif (!close && inputDelta.length === 0) return undefined;\n\n\tlet delta = \"\";\n\tif (!buffer.started) {\n\t\tdelta += `{${JSON.stringify(inputProperty)}:\"`;\n\t\tbuffer.started = true;\n\t}\n\tdelta += JSON.stringify(inputDelta).slice(1, -1);\n\tbuffer.input = nextInput;\n\n\tif (close) {\n\t\tdelta += '\"}';\n\t\tbuffer.closed = true;\n\t}\n\treturn delta;\n}\n\nfunction inferGrammarInputProperty(tool: Tool): string {\n\tconst schema = tool.parameters as JsonSchemaObject;\n\tif (schema.type !== \"object\") {\n\t\tthrow new Error(\"grammar constrained sampling requires an object parameter schema\");\n\t}\n\tif (!Array.isArray(schema.required) || schema.required.length !== 1 || typeof schema.required[0] !== \"string\") {\n\t\tthrow new Error(\"grammar constrained sampling requires exactly one required string property\");\n\t}\n\n\tconst inputProperty = schema.required[0];\n\tif (!schema.properties?.[inputProperty]) {\n\t\tthrow new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);\n\t}\n\tif (schema.properties[inputProperty]?.type !== \"string\") {\n\t\tthrow new Error(`grammar constrained sampling property ${inputProperty} must have type string`);\n\t}\n\treturn inputProperty;\n}\n\nexport function resolveJsonSchemaStrictSampling(tool: Tool, supportsStrictMode: boolean): boolean | undefined {\n\tconst config = tool.constrainedSampling;\n\tif (config === false || config?.type !== \"json_schema\") return undefined;\n\n\tif (supportsStrictMode) {\n\t\ttry {\n\t\t\tmakeStrictJsonSchema(tool.parameters);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof UnsupportedStrictJsonSchemaError)) throw error;\n\t\t\tif (config.strict !== \"require\") return undefined;\n\t\t\tthrow new Error(`Tool \"${tool.name}\" requires JSON-schema constrained sampling, but ${error.message}.`);\n\t\t}\n\t}\n\tif (config.strict === \"require\") {\n\t\tthrow new Error(\n\t\t\t`Tool \"${tool.name}\" requires JSON-schema constrained sampling, but strict tools are unsupported.`,\n\t\t);\n\t}\n\treturn undefined;\n}\n\nexport function resolveGrammarConstrainedSampling(\n\ttool: Tool,\n\tsupportsOpenAIGrammarTools: boolean,\n): GrammarConstrainedSampling | undefined {\n\tconst config = tool.constrainedSampling;\n\tif (!config) return undefined;\n\tif (config.type !== \"grammar\") {\n\t\treturn undefined;\n\t}\n\n\tif (!supportsOpenAIGrammarTools) {\n\t\treturn undefined;\n\t}\n\n\tconst larkDefinition = config.variants.openai_lark;\n\tconst regexDefinition = config.variants.openai_regex;\n\tconst hasLarkDefinition = typeof larkDefinition === \"string\" && larkDefinition.trim().length > 0;\n\tconst hasRegexDefinition = typeof regexDefinition === \"string\" && regexDefinition.trim().length > 0;\n\tif (!hasLarkDefinition && !hasRegexDefinition) {\n\t\tthrow new Error(\n\t\t\t`Tool \"${tool.name}\" cannot use grammar constrained sampling: no supported grammar variant was provided.`,\n\t\t);\n\t}\n\n\ttry {\n\t\treturn {\n\t\t\tformat: hasLarkDefinition ? \"lark\" : \"regex\",\n\t\t\tdefinition: hasLarkDefinition ? larkDefinition : regexDefinition!,\n\t\t\tinputProperty: inferGrammarInputProperty(tool),\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`Tool \"${tool.name}\" cannot use grammar constrained sampling: ${message}.`);\n\t}\n}\n\nexport function createGrammarToolInputProperties(\n\ttools: Tool[] | undefined,\n\tsupportsOpenAIGrammarTools: boolean,\n): ReadonlyMap<string, string> {\n\tconst properties = new Map<string, string>();\n\tfor (const tool of tools ?? []) {\n\t\tconst grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);\n\t\tif (grammar) {\n\t\t\tproperties.set(tool.name, grammar.inputProperty);\n\t\t}\n\t}\n\treturn properties;\n}\n"]}
|
|
@@ -188,7 +188,7 @@ export const stream = (model, context, options) => {
|
|
|
188
188
|
if (candidate?.finishReason) {
|
|
189
189
|
output.rawStopReason = candidate.finishReason;
|
|
190
190
|
output.stopReason = mapStopReason(candidate.finishReason);
|
|
191
|
-
if (output.content.some((b) => b.type === "toolCall")) {
|
|
191
|
+
if (output.content.some((b) => b.type === "toolCall") && output.stopReason === "stop") {
|
|
192
192
|
output.stopReason = "toolUse";
|
|
193
193
|
}
|
|
194
194
|
}
|
|
@@ -318,13 +318,17 @@ function buildParams(model, context, options = {}) {
|
|
|
318
318
|
if (options.maxTokens !== undefined) {
|
|
319
319
|
generationConfig.maxOutputTokens = options.maxTokens;
|
|
320
320
|
}
|
|
321
|
+
const supportsStrictMode = supportsGoogleStrictToolSampling(model.id);
|
|
321
322
|
const functionCallingMode = context.tools?.length
|
|
322
|
-
? resolveGoogleFunctionCallingMode(context.tools, options.toolChoice,
|
|
323
|
+
? resolveGoogleFunctionCallingMode(context.tools, options.toolChoice, supportsStrictMode)
|
|
323
324
|
: undefined;
|
|
324
325
|
const config = {
|
|
325
326
|
...(Object.keys(generationConfig).length > 0 && generationConfig),
|
|
326
327
|
...(context.systemPrompt && { systemInstruction: sanitizeSurrogates(context.systemPrompt) }),
|
|
327
|
-
...(context.tools &&
|
|
328
|
+
...(context.tools &&
|
|
329
|
+
context.tools.length > 0 && {
|
|
330
|
+
tools: convertTools(context.tools, false, supportsStrictMode),
|
|
331
|
+
}),
|
|
328
332
|
...(functionCallingMode !== undefined && {
|
|
329
333
|
toolConfig: { functionCallingConfig: { mode: functionCallingMode } },
|
|
330
334
|
}),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"google-generative-ai.js","sourceRoot":"","sources":["../../src/api/google-generative-ai.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,WAAW,EACX,aAAa,IAAI,wBAAwB,GAEzC,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAgBjE,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACrF,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,OAAO,EACN,eAAe,EACf,YAAY,EACZ,cAAc,EACd,aAAa,EACb,gCAAgC,EAChC,sBAAsB,EACtB,kBAAkB,EAClB,gCAAgC,EAChC,uBAAuB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAElG,MAAM,kBAAkB,GAA0D;IACjF,0BAA0B,EAAE,wBAAwB,CAAC,0BAA0B;IAC/E,OAAO,EAAE,wBAAwB,CAAC,OAAO;IACzC,GAAG,EAAE,wBAAwB,CAAC,GAAG;IACjC,MAAM,EAAE,wBAAwB,CAAC,MAAM;IACvC,IAAI,EAAE,wBAAwB,CAAC,IAAI;CACnC,CAAC;AAWF,8CAA8C;AAC9C,IAAI,eAAe,GAAG,CAAC,CAAC;AAExB,MAAM,CAAC,MAAM,MAAM,GAA0D,CAC5E,KAAoC,EACpC,OAAgB,EAChB,OAAuB,EACO,EAAE;IAChC,MAAM,MAAM,GAAG,IAAI,2BAA2B,EAAE,CAAC;IAEjD,CAAC,KAAK,IAAI,EAAE;QACX,MAAM,MAAM,GAAqB;YAChC,IAAI,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Level,\n\ttype ThinkingConfig,\n} from \"@google/genai\";\nimport { calculateCost, clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tModelThinkingLevel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingBudgets,\n\tThinkingContent,\n\tThinkingLevel,\n\tToolCall,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { providerHeadersToRecord } from \"../utils/headers.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport type { GoogleThinkingLevel } from \"./google-shared.ts\";\nimport {\n\tconvertMessages,\n\tconvertTools,\n\tisThinkingPart,\n\tmapStopReason,\n\tresolveGoogleFunctionCallingMode,\n\tretainThoughtSignature,\n\tretryGoogleRequest,\n\tsupportsGoogleStrictToolSampling,\n\ttoProviderNativeContent,\n} from \"./google-shared.ts\";\nimport { applyExtraBody, buildBaseOptions, GOOGLE_RESERVED_BODY_KEYS } from \"./simple-options.ts\";\n\nconst THINKING_LEVEL_MAP: Record<GoogleThinkingLevel, GoogleGenAIThinkingLevel> = {\n\tTHINKING_LEVEL_UNSPECIFIED: GoogleGenAIThinkingLevel.THINKING_LEVEL_UNSPECIFIED,\n\tMINIMAL: GoogleGenAIThinkingLevel.MINIMAL,\n\tLOW: GoogleGenAIThinkingLevel.LOW,\n\tMEDIUM: GoogleGenAIThinkingLevel.MEDIUM,\n\tHIGH: GoogleGenAIThinkingLevel.HIGH,\n};\n\nexport interface GoogleOptions extends StreamOptions {\n\ttoolChoice?: \"auto\" | \"none\" | \"any\";\n\tthinking?: {\n\t\tenabled: boolean;\n\t\tbudgetTokens?: number; // -1 for dynamic, 0 to disable\n\t\tlevel?: GoogleThinkingLevel;\n\t};\n}\n\n// Counter for generating unique tool call IDs\nlet toolCallCounter = 0;\n\nexport const stream: StreamFunction<\"google-generative-ai\", GoogleOptions> = (\n\tmodel: Model<\"google-generative-ai\">,\n\tcontext: Context,\n\toptions?: GoogleOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: \"google-generative-ai\" as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"pending\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\tif (options?.fetch && options.fetch !== globalThis.fetch) {\n\t\t\t\tthrow new Error(\"Custom fetch is not supported by the Google Generative AI adapter\");\n\t\t\t}\n\t\t\tconst apiKey = options?.apiKey;\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t\t\t}\n\t\t\tconst client = createClient(model, apiKey, providerHeadersToRecord(options?.headers));\n\t\t\tlet params = buildParams(model, context, options);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as GenerateContentParameters;\n\t\t\t}\n\t\t\tconst googleStream = await retryGoogleRequest(() => client.models.generateContentStream(params), options);\n\n\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\tlet currentBlock: TextContent | ThinkingContent | null = null;\n\t\t\tlet groundingMetadataEmitted = false;\n\t\t\tlet urlContextMetadataEmitted = false;\n\t\t\tconst blocks = output.content;\n\t\t\tconst blockIndex = () => blocks.length - 1;\n\t\t\tfor await (const chunk of googleStream) {\n\t\t\t\t// @google/genai documents GenerateContentResponse.responseId as an output-only field\n\t\t\t\t// used to identify each response. Keep the first non-empty one from the stream.\n\t\t\t\toutput.responseId ||= chunk.responseId;\n\t\t\t\tconst candidate = chunk.candidates?.[0];\n\t\t\t\tif (candidate?.content?.parts) {\n\t\t\t\t\tfor (const part of candidate.content.parts) {\n\t\t\t\t\t\tlet handledAsKnownPart = false;\n\t\t\t\t\t\tif (part.text !== undefined) {\n\t\t\t\t\t\t\thandledAsKnownPart = true;\n\t\t\t\t\t\t\tconst isThinking = isThinkingPart(part);\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!currentBlock ||\n\t\t\t\t\t\t\t\t(isThinking && currentBlock.type !== \"thinking\") ||\n\t\t\t\t\t\t\t\t(!isThinking && currentBlock.type !== \"text\")\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tif (currentBlock) {\n\t\t\t\t\t\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blocks.length - 1,\n\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (isThinking) {\n\t\t\t\t\t\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\", thinkingSignature: undefined };\n\t\t\t\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (currentBlock.type === \"thinking\") {\n\t\t\t\t\t\t\t\tcurrentBlock.thinking += part.text;\n\t\t\t\t\t\t\t\tcurrentBlock.thinkingSignature = retainThoughtSignature(\n\t\t\t\t\t\t\t\t\tcurrentBlock.thinkingSignature,\n\t\t\t\t\t\t\t\t\tpart.thoughtSignature,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcurrentBlock.text += part.text;\n\t\t\t\t\t\t\t\tcurrentBlock.textSignature = retainThoughtSignature(\n\t\t\t\t\t\t\t\t\tcurrentBlock.textSignature,\n\t\t\t\t\t\t\t\t\tpart.thoughtSignature,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (part.functionCall) {\n\t\t\t\t\t\t\thandledAsKnownPart = true;\n\t\t\t\t\t\t\tif (currentBlock) {\n\t\t\t\t\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcurrentBlock = null;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Generate unique ID if not provided or if it's a duplicate\n\t\t\t\t\t\t\tconst providedId = part.functionCall.id;\n\t\t\t\t\t\t\tconst needsNewId =\n\t\t\t\t\t\t\t\t!providedId || output.content.some((b) => b.type === \"toolCall\" && b.id === providedId);\n\t\t\t\t\t\t\tconst toolCallId = needsNewId\n\t\t\t\t\t\t\t\t? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`\n\t\t\t\t\t\t\t\t: providedId;\n\n\t\t\t\t\t\t\tconst toolCall: ToolCall = {\n\t\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\t\tid: toolCallId,\n\t\t\t\t\t\t\t\tname: part.functionCall.name || \"\",\n\t\t\t\t\t\t\t\targuments: (part.functionCall.args as Record<string, any>) ?? {},\n\t\t\t\t\t\t\t\t...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }),\n\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\toutput.content.push(toolCall);\n\t\t\t\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\tdelta: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tstream.push({ type: \"toolcall_end\", contentIndex: blockIndex(), toolCall, partial: output });\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!handledAsKnownPart) {\n\t\t\t\t\t\t\toutput.content.push(toProviderNativeContent(part));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (candidate?.groundingMetadata && !groundingMetadataEmitted) {\n\t\t\t\t\toutput.content.push({\n\t\t\t\t\t\ttype: \"providerNative\",\n\t\t\t\t\t\tsubtype: \"groundingMetadata\",\n\t\t\t\t\t\traw: candidate.groundingMetadata,\n\t\t\t\t\t});\n\t\t\t\t\tgroundingMetadataEmitted = true;\n\t\t\t\t}\n\n\t\t\t\tif (candidate?.urlContextMetadata && !urlContextMetadataEmitted) {\n\t\t\t\t\toutput.content.push({\n\t\t\t\t\t\ttype: \"providerNative\",\n\t\t\t\t\t\tsubtype: \"urlContextMetadata\",\n\t\t\t\t\t\traw: candidate.urlContextMetadata,\n\t\t\t\t\t});\n\t\t\t\t\turlContextMetadataEmitted = true;\n\t\t\t\t}\n\n\t\t\t\tif (candidate?.finishReason) {\n\t\t\t\t\toutput.rawStopReason = candidate.finishReason;\n\t\t\t\t\toutput.stopReason = mapStopReason(candidate.finishReason);\n\t\t\t\t\tif (output.content.some((b) => b.type === \"toolCall\")) {\n\t\t\t\t\t\toutput.stopReason = \"toolUse\";\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (chunk.usageMetadata) {\n\t\t\t\t\toutput.usage = {\n\t\t\t\t\t\tinput:\n\t\t\t\t\t\t\t(chunk.usageMetadata.promptTokenCount || 0) - (chunk.usageMetadata.cachedContentTokenCount || 0),\n\t\t\t\t\t\toutput:\n\t\t\t\t\t\t\t(chunk.usageMetadata.candidatesTokenCount || 0) + (chunk.usageMetadata.thoughtsTokenCount || 0),\n\t\t\t\t\t\tcacheRead: chunk.usageMetadata.cachedContentTokenCount || 0,\n\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\treasoning: chunk.usageMetadata.thoughtsTokenCount || 0,\n\t\t\t\t\t\ttotalTokens: chunk.usageMetadata.totalTokenCount || 0,\n\t\t\t\t\t\tcost: {\n\t\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\ttotal: 0,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t\tcalculateCost(model, output.usage);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (currentBlock) {\n\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"pending\") {\n\t\t\t\tthrow new Error(\"Google stream ended without a finish reason\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tconst errorMessage = output.rawStopReason\n\t\t\t\t\t? `Provider stopped with: ${output.rawStopReason}`\n\t\t\t\t\t: \"An unknown error occurred\";\n\t\t\t\tthrow new Error(errorMessage);\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\t// Remove internal index property used during streaming\n\t\t\tfor (const block of output.content) {\n\t\t\t\tif (\"index\" in block) {\n\t\t\t\t\tdelete (block as { index?: number }).index;\n\t\t\t\t}\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatProviderError(normalizeProviderError(error));\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\nexport const streamSimple: StreamFunction<\"google-generative-ai\", SimpleStreamOptions> = (\n\tmodel: Model<\"google-generative-ai\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey;\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = buildBaseOptions(model, context, options, apiKey);\n\t// `reasoning` is typed as ThinkingLevel, but runtime callers can hand \"off\"\n\t// through, and Gemini 3 maps null \"off\" so a post-clamp check cannot see it.\n\t// Thinking-off takes the disabled wire form, never an enabled one.\n\tif (!options?.reasoning || (options.reasoning as ModelThinkingLevel) === \"off\") {\n\t\treturn stream(model, context, { ...base, thinking: { enabled: false } } satisfies GoogleOptions);\n\t}\n\n\tconst clampedReasoning = clampThinkingLevel(model, options.reasoning);\n\tif (clampedReasoning === \"off\") {\n\t\t// Only non-reasoning models clamp every request to \"off\".\n\t\treturn stream(model, context, { ...base, thinking: { enabled: false } } satisfies GoogleOptions);\n\t}\n\tconst effort = clampedReasoning as ClampedThinkingLevel;\n\tconst googleModel = model as Model<\"google-generative-ai\">;\n\n\tif (isGemini3ProModel(googleModel) || isGemini3FlashModel(googleModel) || isGemma4Model(googleModel)) {\n\t\treturn stream(model, context, {\n\t\t\t...base,\n\t\t\tthinking: {\n\t\t\t\tenabled: true,\n\t\t\t\tlevel: getThinkingLevel(effort, googleModel),\n\t\t\t},\n\t\t} satisfies GoogleOptions);\n\t}\n\n\treturn stream(model, context, {\n\t\t...base,\n\t\tthinking: {\n\t\t\tenabled: true,\n\t\t\tbudgetTokens: getGoogleBudget(googleModel, effort, options.thinkingBudgets),\n\t\t},\n\t} satisfies GoogleOptions);\n};\n\nfunction createClient(\n\tmodel: Model<\"google-generative-ai\">,\n\tapiKey?: string,\n\toptionsHeaders?: Record<string, string>,\n): GoogleGenAI {\n\tconst httpOptions: { baseUrl?: string; apiVersion?: string; headers?: Record<string, string> } = {};\n\tif (model.baseUrl) {\n\t\thttpOptions.baseUrl = model.baseUrl;\n\t\thttpOptions.apiVersion = \"\"; // baseUrl already includes version path, don't append\n\t}\n\tif (model.headers || optionsHeaders) {\n\t\thttpOptions.headers = { ...model.headers, ...optionsHeaders };\n\t}\n\n\treturn new GoogleGenAI({\n\t\tapiKey,\n\t\thttpOptions: Object.keys(httpOptions).length > 0 ? httpOptions : undefined,\n\t});\n}\n\nfunction buildParams(\n\tmodel: Model<\"google-generative-ai\">,\n\tcontext: Context,\n\toptions: GoogleOptions = {},\n): GenerateContentParameters {\n\tconst contents = convertMessages(model, context, { preserveThinking: options.thinking?.enabled === true });\n\n\tconst generationConfig: GenerateContentConfig = {};\n\tif (options.temperature !== undefined) {\n\t\tgenerationConfig.temperature = options.temperature;\n\t}\n\tif (options.maxTokens !== undefined) {\n\t\tgenerationConfig.maxOutputTokens = options.maxTokens;\n\t}\n\n\tconst functionCallingMode = context.tools?.length\n\t\t? resolveGoogleFunctionCallingMode(context.tools, options.toolChoice, supportsGoogleStrictToolSampling(model.id))\n\t\t: undefined;\n\tconst config: GenerateContentConfig = {\n\t\t...(Object.keys(generationConfig).length > 0 && generationConfig),\n\t\t...(context.systemPrompt && { systemInstruction: sanitizeSurrogates(context.systemPrompt) }),\n\t\t...(context.tools && context.tools.length > 0 && { tools: convertTools(context.tools) }),\n\t\t...(functionCallingMode !== undefined && {\n\t\t\ttoolConfig: { functionCallingConfig: { mode: functionCallingMode } },\n\t\t}),\n\t};\n\n\tif (options.thinking?.enabled && model.reasoning) {\n\t\tconst thinkingConfig: ThinkingConfig = { includeThoughts: true };\n\t\tif (options.thinking.level !== undefined) {\n\t\t\tthinkingConfig.thinkingLevel = THINKING_LEVEL_MAP[options.thinking.level];\n\t\t} else if (options.thinking.budgetTokens !== undefined) {\n\t\t\tthinkingConfig.thinkingBudget = options.thinking.budgetTokens;\n\t\t}\n\t\tconfig.thinkingConfig = thinkingConfig;\n\t} else if (model.reasoning && options.thinking && !options.thinking.enabled) {\n\t\tconfig.thinkingConfig = getDisabledThinkingConfig(model);\n\t}\n\n\tif (options.signal) {\n\t\tif (options.signal.aborted) {\n\t\t\tthrow new Error(\"Request aborted\");\n\t\t}\n\t\tconfig.abortSignal = options.signal;\n\t}\n\n\tapplyExtraBody(config, options?.extraBody, GOOGLE_RESERVED_BODY_KEYS);\n\n\tconst params: GenerateContentParameters = {\n\t\tmodel: model.id,\n\t\tcontents,\n\t\tconfig,\n\t};\n\n\treturn params;\n}\n\ntype ClampedThinkingLevel = Exclude<ThinkingLevel, \"xhigh\" | \"max\">;\n\nfunction isGemma4Model(model: Model<\"google-generative-ai\">): boolean {\n\treturn /gemma-?4/.test(model.id.toLowerCase());\n}\n\nfunction isGemini3ProModel(model: Model<\"google-generative-ai\">): boolean {\n\treturn /gemini-3(?:\\.\\d+)?-pro/.test(model.id.toLowerCase());\n}\n\nfunction isGemini3FlashModel(model: Model<\"google-generative-ai\">): boolean {\n\tconst id = model.id.toLowerCase();\n\treturn /gemini-3(?:\\.\\d+)?-flash/.test(id) || id === \"gemini-flash-latest\" || id === \"gemini-flash-lite-latest\";\n}\n\nfunction getDisabledThinkingConfig(model: Model<\"google-generative-ai\">): ThinkingConfig {\n\t// Google docs: Gemini 3.1 Pro cannot disable thinking, and Gemini 3 Flash / Flash-Lite\n\t// do not support full thinking-off either. For Gemini 3 models, use the lowest supported\n\t// thinkingLevel without includeThoughts so hidden thinking remains invisible to pi.\n\tif (isGemini3ProModel(model)) {\n\t\treturn { thinkingLevel: GoogleGenAIThinkingLevel.LOW };\n\t}\n\tif (isGemini3FlashModel(model)) {\n\t\treturn { thinkingLevel: GoogleGenAIThinkingLevel.MINIMAL };\n\t}\n\tif (isGemma4Model(model)) {\n\t\treturn { thinkingLevel: GoogleGenAIThinkingLevel.MINIMAL };\n\t}\n\n\t// Gemini 2.x supports disabling via thinkingBudget = 0.\n\treturn { thinkingBudget: 0 };\n}\n\nfunction getThinkingLevel(effort: ClampedThinkingLevel, model: Model<\"google-generative-ai\">): GoogleThinkingLevel {\n\tif (isGemini3ProModel(model)) {\n\t\tswitch (effort) {\n\t\t\tcase \"minimal\":\n\t\t\tcase \"low\":\n\t\t\t\treturn \"LOW\";\n\t\t\tcase \"medium\":\n\t\t\tcase \"high\":\n\t\t\t\treturn \"HIGH\";\n\t\t}\n\t}\n\tif (isGemma4Model(model)) {\n\t\tswitch (effort) {\n\t\t\tcase \"minimal\":\n\t\t\tcase \"low\":\n\t\t\t\treturn \"MINIMAL\";\n\t\t\tcase \"medium\":\n\t\t\tcase \"high\":\n\t\t\t\treturn \"HIGH\";\n\t\t}\n\t}\n\tswitch (effort) {\n\t\tcase \"minimal\":\n\t\t\treturn \"MINIMAL\";\n\t\tcase \"low\":\n\t\t\treturn \"LOW\";\n\t\tcase \"medium\":\n\t\t\treturn \"MEDIUM\";\n\t\tcase \"high\":\n\t\t\treturn \"HIGH\";\n\t}\n}\n\nfunction getGoogleBudget(\n\tmodel: Model<\"google-generative-ai\">,\n\teffort: ClampedThinkingLevel,\n\tcustomBudgets?: ThinkingBudgets,\n): number {\n\tif (customBudgets?.[effort] !== undefined) {\n\t\treturn customBudgets[effort]!;\n\t}\n\n\tif (model.id.includes(\"2.5-pro\")) {\n\t\tconst budgets: Record<ClampedThinkingLevel, number> = {\n\t\t\tminimal: 128,\n\t\t\tlow: 2048,\n\t\t\tmedium: 8192,\n\t\t\thigh: 32768,\n\t\t};\n\t\treturn budgets[effort];\n\t}\n\n\tif (model.id.includes(\"2.5-flash-lite\")) {\n\t\tconst budgets: Record<ClampedThinkingLevel, number> = {\n\t\t\tminimal: 512,\n\t\t\tlow: 2048,\n\t\t\tmedium: 8192,\n\t\t\thigh: 24576,\n\t\t};\n\t\treturn budgets[effort];\n\t}\n\n\tif (model.id.includes(\"2.5-flash\")) {\n\t\tconst budgets: Record<ClampedThinkingLevel, number> = {\n\t\t\tminimal: 128,\n\t\t\tlow: 2048,\n\t\t\tmedium: 8192,\n\t\t\thigh: 24576,\n\t\t};\n\t\treturn budgets[effort];\n\t}\n\n\treturn -1;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"google-generative-ai.js","sourceRoot":"","sources":["../../src/api/google-generative-ai.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,WAAW,EACX,aAAa,IAAI,wBAAwB,GAEzC,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAgBjE,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACrF,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,OAAO,EACN,eAAe,EACf,YAAY,EACZ,cAAc,EACd,aAAa,EACb,gCAAgC,EAChC,sBAAsB,EACtB,kBAAkB,EAClB,gCAAgC,EAChC,uBAAuB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,MAAM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C,QAAQ,CAAC,gBAAgB,CAAC,EAAE,CAAC;QACzC,MAAM,OAAO,GAAyC;YACrD,OAAO,EAAE,GAAG;YACZ,GAAG,EAAE,IAAI;YACT,MAAM,EAAE,IAAI;YACZ,IAAI,EAAE,KAAK;SACX,CAAC;QACF,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC;IACxB,CAAC;IAED,IAAI,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC;QACpC,MAAM,OAAO,GAAyC;YACrD,OAAO,EAAE,GAAG;YACZ,GAAG,EAAE,IAAI;YACT,MAAM,EAAE,IAAI;YACZ,IAAI,EAAE,KAAK;SACX,CAAC;QACF,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC;IACxB,CAAC;IAED,OAAO,CAAC,CAAC,CAAC;AACX,CAAC","sourcesContent":["import {\n\ttype GenerateContentConfig,\n\ttype GenerateContentParameters,\n\tGoogleGenAI,\n\tThinkingLevel as GoogleGenAIThinkingLevel,\n\ttype ThinkingConfig,\n} from \"@google/genai\";\nimport { calculateCost, clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tModelThinkingLevel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingBudgets,\n\tThinkingContent,\n\tThinkingLevel,\n\tToolCall,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { providerHeadersToRecord } from \"../utils/headers.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport type { GoogleThinkingLevel } from \"./google-shared.ts\";\nimport {\n\tconvertMessages,\n\tconvertTools,\n\tisThinkingPart,\n\tmapStopReason,\n\tresolveGoogleFunctionCallingMode,\n\tretainThoughtSignature,\n\tretryGoogleRequest,\n\tsupportsGoogleStrictToolSampling,\n\ttoProviderNativeContent,\n} from \"./google-shared.ts\";\nimport { applyExtraBody, buildBaseOptions, GOOGLE_RESERVED_BODY_KEYS } from \"./simple-options.ts\";\n\nconst THINKING_LEVEL_MAP: Record<GoogleThinkingLevel, GoogleGenAIThinkingLevel> = {\n\tTHINKING_LEVEL_UNSPECIFIED: GoogleGenAIThinkingLevel.THINKING_LEVEL_UNSPECIFIED,\n\tMINIMAL: GoogleGenAIThinkingLevel.MINIMAL,\n\tLOW: GoogleGenAIThinkingLevel.LOW,\n\tMEDIUM: GoogleGenAIThinkingLevel.MEDIUM,\n\tHIGH: GoogleGenAIThinkingLevel.HIGH,\n};\n\nexport interface GoogleOptions extends StreamOptions {\n\ttoolChoice?: \"auto\" | \"none\" | \"any\";\n\tthinking?: {\n\t\tenabled: boolean;\n\t\tbudgetTokens?: number; // -1 for dynamic, 0 to disable\n\t\tlevel?: GoogleThinkingLevel;\n\t};\n}\n\n// Counter for generating unique tool call IDs\nlet toolCallCounter = 0;\n\nexport const stream: StreamFunction<\"google-generative-ai\", GoogleOptions> = (\n\tmodel: Model<\"google-generative-ai\">,\n\tcontext: Context,\n\toptions?: GoogleOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: \"google-generative-ai\" as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"pending\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\tif (options?.fetch && options.fetch !== globalThis.fetch) {\n\t\t\t\tthrow new Error(\"Custom fetch is not supported by the Google Generative AI adapter\");\n\t\t\t}\n\t\t\tconst apiKey = options?.apiKey;\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t\t\t}\n\t\t\tconst client = createClient(model, apiKey, providerHeadersToRecord(options?.headers));\n\t\t\tlet params = buildParams(model, context, options);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as GenerateContentParameters;\n\t\t\t}\n\t\t\tconst googleStream = await retryGoogleRequest(() => client.models.generateContentStream(params), options);\n\n\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\tlet currentBlock: TextContent | ThinkingContent | null = null;\n\t\t\tlet groundingMetadataEmitted = false;\n\t\t\tlet urlContextMetadataEmitted = false;\n\t\t\tconst blocks = output.content;\n\t\t\tconst blockIndex = () => blocks.length - 1;\n\t\t\tfor await (const chunk of googleStream) {\n\t\t\t\t// @google/genai documents GenerateContentResponse.responseId as an output-only field\n\t\t\t\t// used to identify each response. Keep the first non-empty one from the stream.\n\t\t\t\toutput.responseId ||= chunk.responseId;\n\t\t\t\tconst candidate = chunk.candidates?.[0];\n\t\t\t\tif (candidate?.content?.parts) {\n\t\t\t\t\tfor (const part of candidate.content.parts) {\n\t\t\t\t\t\tlet handledAsKnownPart = false;\n\t\t\t\t\t\tif (part.text !== undefined) {\n\t\t\t\t\t\t\thandledAsKnownPart = true;\n\t\t\t\t\t\t\tconst isThinking = isThinkingPart(part);\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!currentBlock ||\n\t\t\t\t\t\t\t\t(isThinking && currentBlock.type !== \"thinking\") ||\n\t\t\t\t\t\t\t\t(!isThinking && currentBlock.type !== \"text\")\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tif (currentBlock) {\n\t\t\t\t\t\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blocks.length - 1,\n\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (isThinking) {\n\t\t\t\t\t\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\", thinkingSignature: undefined };\n\t\t\t\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (currentBlock.type === \"thinking\") {\n\t\t\t\t\t\t\t\tcurrentBlock.thinking += part.text;\n\t\t\t\t\t\t\t\tcurrentBlock.thinkingSignature = retainThoughtSignature(\n\t\t\t\t\t\t\t\t\tcurrentBlock.thinkingSignature,\n\t\t\t\t\t\t\t\t\tpart.thoughtSignature,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcurrentBlock.text += part.text;\n\t\t\t\t\t\t\t\tcurrentBlock.textSignature = retainThoughtSignature(\n\t\t\t\t\t\t\t\t\tcurrentBlock.textSignature,\n\t\t\t\t\t\t\t\t\tpart.thoughtSignature,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (part.functionCall) {\n\t\t\t\t\t\t\thandledAsKnownPart = true;\n\t\t\t\t\t\t\tif (currentBlock) {\n\t\t\t\t\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcurrentBlock = null;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Generate unique ID if not provided or if it's a duplicate\n\t\t\t\t\t\t\tconst providedId = part.functionCall.id;\n\t\t\t\t\t\t\tconst needsNewId =\n\t\t\t\t\t\t\t\t!providedId || output.content.some((b) => b.type === \"toolCall\" && b.id === providedId);\n\t\t\t\t\t\t\tconst toolCallId = needsNewId\n\t\t\t\t\t\t\t\t? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`\n\t\t\t\t\t\t\t\t: providedId;\n\n\t\t\t\t\t\t\tconst toolCall: ToolCall = {\n\t\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\t\tid: toolCallId,\n\t\t\t\t\t\t\t\tname: part.functionCall.name || \"\",\n\t\t\t\t\t\t\t\targuments: (part.functionCall.args as Record<string, any>) ?? {},\n\t\t\t\t\t\t\t\t...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }),\n\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\toutput.content.push(toolCall);\n\t\t\t\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\t\tdelta: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tstream.push({ type: \"toolcall_end\", contentIndex: blockIndex(), toolCall, partial: output });\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!handledAsKnownPart) {\n\t\t\t\t\t\t\toutput.content.push(toProviderNativeContent(part));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (candidate?.groundingMetadata && !groundingMetadataEmitted) {\n\t\t\t\t\toutput.content.push({\n\t\t\t\t\t\ttype: \"providerNative\",\n\t\t\t\t\t\tsubtype: \"groundingMetadata\",\n\t\t\t\t\t\traw: candidate.groundingMetadata,\n\t\t\t\t\t});\n\t\t\t\t\tgroundingMetadataEmitted = true;\n\t\t\t\t}\n\n\t\t\t\tif (candidate?.urlContextMetadata && !urlContextMetadataEmitted) {\n\t\t\t\t\toutput.content.push({\n\t\t\t\t\t\ttype: \"providerNative\",\n\t\t\t\t\t\tsubtype: \"urlContextMetadata\",\n\t\t\t\t\t\traw: candidate.urlContextMetadata,\n\t\t\t\t\t});\n\t\t\t\t\turlContextMetadataEmitted = true;\n\t\t\t\t}\n\n\t\t\t\tif (candidate?.finishReason) {\n\t\t\t\t\toutput.rawStopReason = candidate.finishReason;\n\t\t\t\t\toutput.stopReason = mapStopReason(candidate.finishReason);\n\t\t\t\t\tif (output.content.some((b) => b.type === \"toolCall\") && output.stopReason === \"stop\") {\n\t\t\t\t\t\toutput.stopReason = \"toolUse\";\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (chunk.usageMetadata) {\n\t\t\t\t\toutput.usage = {\n\t\t\t\t\t\tinput:\n\t\t\t\t\t\t\t(chunk.usageMetadata.promptTokenCount || 0) - (chunk.usageMetadata.cachedContentTokenCount || 0),\n\t\t\t\t\t\toutput:\n\t\t\t\t\t\t\t(chunk.usageMetadata.candidatesTokenCount || 0) + (chunk.usageMetadata.thoughtsTokenCount || 0),\n\t\t\t\t\t\tcacheRead: chunk.usageMetadata.cachedContentTokenCount || 0,\n\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\treasoning: chunk.usageMetadata.thoughtsTokenCount || 0,\n\t\t\t\t\t\ttotalTokens: chunk.usageMetadata.totalTokenCount || 0,\n\t\t\t\t\t\tcost: {\n\t\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\ttotal: 0,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t\tcalculateCost(model, output.usage);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (currentBlock) {\n\t\t\t\tif (currentBlock.type === \"text\") {\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"pending\") {\n\t\t\t\tthrow new Error(\"Google stream ended without a finish reason\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tconst errorMessage = output.rawStopReason\n\t\t\t\t\t? `Provider stopped with: ${output.rawStopReason}`\n\t\t\t\t\t: \"An unknown error occurred\";\n\t\t\t\tthrow new Error(errorMessage);\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\t// Remove internal index property used during streaming\n\t\t\tfor (const block of output.content) {\n\t\t\t\tif (\"index\" in block) {\n\t\t\t\t\tdelete (block as { index?: number }).index;\n\t\t\t\t}\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatProviderError(normalizeProviderError(error));\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\nexport const streamSimple: StreamFunction<\"google-generative-ai\", SimpleStreamOptions> = (\n\tmodel: Model<\"google-generative-ai\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey;\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = buildBaseOptions(model, context, options, apiKey);\n\t// `reasoning` is typed as ThinkingLevel, but runtime callers can hand \"off\"\n\t// through, and Gemini 3 maps null \"off\" so a post-clamp check cannot see it.\n\t// Thinking-off takes the disabled wire form, never an enabled one.\n\tif (!options?.reasoning || (options.reasoning as ModelThinkingLevel) === \"off\") {\n\t\treturn stream(model, context, { ...base, thinking: { enabled: false } } satisfies GoogleOptions);\n\t}\n\n\tconst clampedReasoning = clampThinkingLevel(model, options.reasoning);\n\tif (clampedReasoning === \"off\") {\n\t\t// Only non-reasoning models clamp every request to \"off\".\n\t\treturn stream(model, context, { ...base, thinking: { enabled: false } } satisfies GoogleOptions);\n\t}\n\tconst effort = clampedReasoning as ClampedThinkingLevel;\n\tconst googleModel = model as Model<\"google-generative-ai\">;\n\n\tif (isGemini3ProModel(googleModel) || isGemini3FlashModel(googleModel) || isGemma4Model(googleModel)) {\n\t\treturn stream(model, context, {\n\t\t\t...base,\n\t\t\tthinking: {\n\t\t\t\tenabled: true,\n\t\t\t\tlevel: getThinkingLevel(effort, googleModel),\n\t\t\t},\n\t\t} satisfies GoogleOptions);\n\t}\n\n\treturn stream(model, context, {\n\t\t...base,\n\t\tthinking: {\n\t\t\tenabled: true,\n\t\t\tbudgetTokens: getGoogleBudget(googleModel, effort, options.thinkingBudgets),\n\t\t},\n\t} satisfies GoogleOptions);\n};\n\nfunction createClient(\n\tmodel: Model<\"google-generative-ai\">,\n\tapiKey?: string,\n\toptionsHeaders?: Record<string, string>,\n): GoogleGenAI {\n\tconst httpOptions: { baseUrl?: string; apiVersion?: string; headers?: Record<string, string> } = {};\n\tif (model.baseUrl) {\n\t\thttpOptions.baseUrl = model.baseUrl;\n\t\thttpOptions.apiVersion = \"\"; // baseUrl already includes version path, don't append\n\t}\n\tif (model.headers || optionsHeaders) {\n\t\thttpOptions.headers = { ...model.headers, ...optionsHeaders };\n\t}\n\n\treturn new GoogleGenAI({\n\t\tapiKey,\n\t\thttpOptions: Object.keys(httpOptions).length > 0 ? httpOptions : undefined,\n\t});\n}\n\nfunction buildParams(\n\tmodel: Model<\"google-generative-ai\">,\n\tcontext: Context,\n\toptions: GoogleOptions = {},\n): GenerateContentParameters {\n\tconst contents = convertMessages(model, context, { preserveThinking: options.thinking?.enabled === true });\n\n\tconst generationConfig: GenerateContentConfig = {};\n\tif (options.temperature !== undefined) {\n\t\tgenerationConfig.temperature = options.temperature;\n\t}\n\tif (options.maxTokens !== undefined) {\n\t\tgenerationConfig.maxOutputTokens = options.maxTokens;\n\t}\n\n\tconst supportsStrictMode = supportsGoogleStrictToolSampling(model.id);\n\tconst functionCallingMode = context.tools?.length\n\t\t? resolveGoogleFunctionCallingMode(context.tools, options.toolChoice, supportsStrictMode)\n\t\t: undefined;\n\tconst config: GenerateContentConfig = {\n\t\t...(Object.keys(generationConfig).length > 0 && generationConfig),\n\t\t...(context.systemPrompt && { systemInstruction: sanitizeSurrogates(context.systemPrompt) }),\n\t\t...(context.tools &&\n\t\t\tcontext.tools.length > 0 && {\n\t\t\t\ttools: convertTools(context.tools, false, supportsStrictMode),\n\t\t\t}),\n\t\t...(functionCallingMode !== undefined && {\n\t\t\ttoolConfig: { functionCallingConfig: { mode: functionCallingMode } },\n\t\t}),\n\t};\n\n\tif (options.thinking?.enabled && model.reasoning) {\n\t\tconst thinkingConfig: ThinkingConfig = { includeThoughts: true };\n\t\tif (options.thinking.level !== undefined) {\n\t\t\tthinkingConfig.thinkingLevel = THINKING_LEVEL_MAP[options.thinking.level];\n\t\t} else if (options.thinking.budgetTokens !== undefined) {\n\t\t\tthinkingConfig.thinkingBudget = options.thinking.budgetTokens;\n\t\t}\n\t\tconfig.thinkingConfig = thinkingConfig;\n\t} else if (model.reasoning && options.thinking && !options.thinking.enabled) {\n\t\tconfig.thinkingConfig = getDisabledThinkingConfig(model);\n\t}\n\n\tif (options.signal) {\n\t\tif (options.signal.aborted) {\n\t\t\tthrow new Error(\"Request aborted\");\n\t\t}\n\t\tconfig.abortSignal = options.signal;\n\t}\n\n\tapplyExtraBody(config, options?.extraBody, GOOGLE_RESERVED_BODY_KEYS);\n\n\tconst params: GenerateContentParameters = {\n\t\tmodel: model.id,\n\t\tcontents,\n\t\tconfig,\n\t};\n\n\treturn params;\n}\n\ntype ClampedThinkingLevel = Exclude<ThinkingLevel, \"xhigh\" | \"max\">;\n\nfunction isGemma4Model(model: Model<\"google-generative-ai\">): boolean {\n\treturn /gemma-?4/.test(model.id.toLowerCase());\n}\n\nfunction isGemini3ProModel(model: Model<\"google-generative-ai\">): boolean {\n\treturn /gemini-3(?:\\.\\d+)?-pro/.test(model.id.toLowerCase());\n}\n\nfunction isGemini3FlashModel(model: Model<\"google-generative-ai\">): boolean {\n\tconst id = model.id.toLowerCase();\n\treturn /gemini-3(?:\\.\\d+)?-flash/.test(id) || id === \"gemini-flash-latest\" || id === \"gemini-flash-lite-latest\";\n}\n\nfunction getDisabledThinkingConfig(model: Model<\"google-generative-ai\">): ThinkingConfig {\n\t// Google docs: Gemini 3.1 Pro cannot disable thinking, and Gemini 3 Flash / Flash-Lite\n\t// do not support full thinking-off either. For Gemini 3 models, use the lowest supported\n\t// thinkingLevel without includeThoughts so hidden thinking remains invisible to pi.\n\tif (isGemini3ProModel(model)) {\n\t\treturn { thinkingLevel: GoogleGenAIThinkingLevel.LOW };\n\t}\n\tif (isGemini3FlashModel(model)) {\n\t\treturn { thinkingLevel: GoogleGenAIThinkingLevel.MINIMAL };\n\t}\n\tif (isGemma4Model(model)) {\n\t\treturn { thinkingLevel: GoogleGenAIThinkingLevel.MINIMAL };\n\t}\n\n\t// Gemini 2.x supports disabling via thinkingBudget = 0.\n\treturn { thinkingBudget: 0 };\n}\n\nfunction getThinkingLevel(effort: ClampedThinkingLevel, model: Model<\"google-generative-ai\">): GoogleThinkingLevel {\n\tif (isGemini3ProModel(model)) {\n\t\tswitch (effort) {\n\t\t\tcase \"minimal\":\n\t\t\tcase \"low\":\n\t\t\t\treturn \"LOW\";\n\t\t\tcase \"medium\":\n\t\t\tcase \"high\":\n\t\t\t\treturn \"HIGH\";\n\t\t}\n\t}\n\tif (isGemma4Model(model)) {\n\t\tswitch (effort) {\n\t\t\tcase \"minimal\":\n\t\t\tcase \"low\":\n\t\t\t\treturn \"MINIMAL\";\n\t\t\tcase \"medium\":\n\t\t\tcase \"high\":\n\t\t\t\treturn \"HIGH\";\n\t\t}\n\t}\n\tswitch (effort) {\n\t\tcase \"minimal\":\n\t\t\treturn \"MINIMAL\";\n\t\tcase \"low\":\n\t\t\treturn \"LOW\";\n\t\tcase \"medium\":\n\t\t\treturn \"MEDIUM\";\n\t\tcase \"high\":\n\t\t\treturn \"HIGH\";\n\t}\n}\n\nfunction getGoogleBudget(\n\tmodel: Model<\"google-generative-ai\">,\n\teffort: ClampedThinkingLevel,\n\tcustomBudgets?: ThinkingBudgets,\n): number {\n\tif (customBudgets?.[effort] !== undefined) {\n\t\treturn customBudgets[effort]!;\n\t}\n\n\tif (model.id.includes(\"2.5-pro\")) {\n\t\tconst budgets: Record<ClampedThinkingLevel, number> = {\n\t\t\tminimal: 128,\n\t\t\tlow: 2048,\n\t\t\tmedium: 8192,\n\t\t\thigh: 32768,\n\t\t};\n\t\treturn budgets[effort];\n\t}\n\n\tif (model.id.includes(\"2.5-flash-lite\")) {\n\t\tconst budgets: Record<ClampedThinkingLevel, number> = {\n\t\t\tminimal: 512,\n\t\t\tlow: 2048,\n\t\t\tmedium: 8192,\n\t\t\thigh: 24576,\n\t\t};\n\t\treturn budgets[effort];\n\t}\n\n\tif (model.id.includes(\"2.5-flash\")) {\n\t\tconst budgets: Record<ClampedThinkingLevel, number> = {\n\t\t\tminimal: 128,\n\t\t\tlow: 2048,\n\t\t\tmedium: 8192,\n\t\t\thigh: 24576,\n\t\t};\n\t\treturn budgets[effort];\n\t}\n\n\treturn -1;\n}\n"]}
|