@qqbrowser/qbot-dsh 0.0.1 → 0.0.2
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/node_modules/@deepseek-ai/cordis-plugin-hmr/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-agent/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-agent-default-model/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-agent-instructions/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-agent-loop/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-agent-presets/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-agent-tool-presentation/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-anonymous-user-id/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-api-gateway/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-api-remotes/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-app-boot/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-atomic-write/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-attachment/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-attachment-local/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-attachment-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-base/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-bash-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-bash-sandbox/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-brand/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-connection/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-connection/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-hmr/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-locale/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-modules/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-runtime/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-schema-form/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-agent-preset/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-attachment/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-commands/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-conversation/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-cordis/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-deliverables/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-directory-picker-browse/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-directory-picker-native/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-goal/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-input-trigger/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-jobs/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-layout/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-message-feedback/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-model-selection/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-permission-presets/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-plan/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-primitives/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-settings/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-settings-general/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-settings-models/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-settings-plugin-inventory/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-settings-plugins/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-sidebar/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-skill/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-slots/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-subagent/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-theme/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-tool/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-trajectory/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-user-questions/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-workflow-run/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-workspace/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-web/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-web-react/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-cmdline/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-code-runtime/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-code-runtime-worker-thread/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-command-compact/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-command-feedback/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-command-goal/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-commands/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-compaction/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-compaction-basic/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-compaction-tool-result-pruner/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-cordis-client-runner/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-cordis-host-runner/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-credentials/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-credentials-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-fs/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-fs-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-fs-observation-policy/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-fs-sandbox/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-goal/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-goal-round-driver/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-headless/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-home-paths/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-apiproxy/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-directory-picker/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-directory-picker-auto/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-directory-picker-browse/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-directory-picker-native/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-frontend-static/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-plugin-inventory/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-webserver/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-invariants/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-jobs/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-jobs-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-launch-environment/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-llm/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-llm-deepseek/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-llm-pi-ai/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-llm-pi-ai/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-llm-retry/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-mcp-client/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-message-feedback/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-native-command/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-output-retention/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-permission-presets/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-persona/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-plan-mode/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-pwsh-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-pwsh-sandbox/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-repeat-tool-reminder/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-sandbox/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-sandbox-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-sandbox-policy/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-schedule/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-scope/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-checkpoint-policy/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-log-export/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-persistence/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-persistence-jsonl/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-projection/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-projection-cache/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-query/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-query-sqlite/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-reference/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-stats/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-telemetry/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-telemetry-otel/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-title/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-title-first-prompt-llm/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-title-llm/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-settings/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-settings-file/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-shell/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-shell-env/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-skill/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-skill-badge/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-skill-filesystem/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-spill/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-spill-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-spill-policy/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-storage/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-storage-domain/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-storage-json/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-subagent/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-subagent-fork-in-process/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-subagent-in-process-driver/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-subagent-spawn-in-process/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-subprocess/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-subprocess-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-system-prompt/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-terminal/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-terminal-bash/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-time-context/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-timeout/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tmux-context/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-token-meter/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-ask-user/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-bash/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-bash-persistent/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-call-timeout-policy/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-cordis/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-fs/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-fs-search/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-goal/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-jobs/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-pwsh/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-ralph/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-skill/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-str-replace-editor/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-subagent/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-subagent-control/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-subagent-report/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-todo/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-web/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-workflow/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tools/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-tools/lib/types/py-types.js +1 -1
- package/node_modules/@deepseek-ai/dsh-tools/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-typert-loader/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-typert-protocol/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-typert-registry/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-user-approval/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-user-questions/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-web/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-web-app/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-web-frontend/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-web-search-deepseek/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-workflow/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-workflow-worker-thread/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-workspace/package.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +5 -5
- package/node_modules/@earendil-works/pi-ai/dist/api/azure-openai-responses.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/google-vertex.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js +3 -3
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +4 -4
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +5 -5
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +6 -6
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openrouter-images.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/pi-messages.js +2 -2
- package/node_modules/@earendil-works/pi-ai/dist/api/simple-options.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/openrouter.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/all.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/amazon-bedrock.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/ant-ling.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/anthropic.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/cerebras.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/cloudflare-ai-gateway.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/cloudflare-workers-ai.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.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/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/huggingface.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/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/together.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/providers/deepseek.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/faux.js +5 -5
- package/node_modules/@earendil-works/pi-ai/dist/providers/fireworks.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/github-copilot.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/google-vertex.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/google.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/groq.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/huggingface.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/minimax-cn.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/minimax.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/mistral.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/moonshotai-cn.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/moonshotai.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/nvidia.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/openai-codex.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/openai.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/opencode-go.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/opencode.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/openrouter.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/qwen-token-plan-cn.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/qwen-token-plan.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/together.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/vercel-ai-gateway.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/xai.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/xiaomi-token-plan-ams.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/xiaomi-token-plan-cn.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/xiaomi-token-plan-sgp.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/xiaomi.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/zai-coding-cn.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/zai.models.js +1 -1
- package/node_modules/@earendil-works/pi-ai/package.json +1 -1
- package/node_modules/mdast-util-gfm-autolink-literal/lib/index.js +1 -1
- package/node_modules/micromark-util-character/dev/index.js +1 -1
- package/node_modules/micromark-util-character/index.js +1 -1
- package/node_modules/oniguruma-parser/dist/oniguruma-parser.min.js +1 -1
- package/node_modules/oniguruma-parser/dist/tokenizer/tokenize.js +1 -1
- package/node_modules/oniguruma-to-es/dist/cjs/index.js +2 -2
- package/node_modules/oniguruma-to-es/dist/esm/index.js +1 -1
- package/node_modules/oniguruma-to-es/dist/index.min.js +2 -2
- package/node_modules/sharp/dist/libvips.mjs +1 -1
- package/node_modules/sharp/dist/sharp.mjs +1 -1
- package/node_modules/sharp/dist/utility.mjs +1 -1
- package/node_modules/typebox/build/compile/validator.mjs +1 -1
- package/node_modules/typebox/build/format/_idna.mjs +1 -1
- package/node_modules/typebox/build/format/_puny.mjs +1 -1
- package/node_modules/typebox/build/format/uuid.mjs +1 -1
- package/node_modules/typebox/build/guard/emit.mjs +1 -1
- package/node_modules/typebox/build/guard/guard.mjs +1 -1
- package/node_modules/typebox/build/guard/string.mjs +1 -1
- package/node_modules/typebox/build/schema/engine/_functions.mjs +1 -1
- package/node_modules/typebox/build/schema/engine/boolean.mjs +1 -1
- package/node_modules/typebox/build/schema/engine/index.mjs +1 -1
- package/node_modules/typebox/build/schema/engine/schema.mjs +1 -1
- package/node_modules/typebox/build/schema/engine/type.mjs +1 -1
- package/node_modules/typebox/build/schema/types/index.mjs +1 -1
- package/node_modules/typebox/build/schema/types/schema.mjs +1 -1
- package/node_modules/typebox/build/system/locale/ar_001.mjs +1 -1
- package/node_modules/typebox/build/system/locale/bn_BD.mjs +1 -1
- package/node_modules/typebox/build/system/locale/cs_CZ.mjs +1 -1
- package/node_modules/typebox/build/system/locale/de_DE.mjs +1 -1
- package/node_modules/typebox/build/system/locale/el_GR.mjs +1 -1
- package/node_modules/typebox/build/system/locale/en_US.mjs +1 -1
- package/node_modules/typebox/build/system/locale/es_419.mjs +1 -1
- package/node_modules/typebox/build/system/locale/es_AR.mjs +1 -1
- package/node_modules/typebox/build/system/locale/es_ES.mjs +1 -1
- package/node_modules/typebox/build/system/locale/es_MX.mjs +1 -1
- package/node_modules/typebox/build/system/locale/fa_IR.mjs +1 -1
- package/node_modules/typebox/build/system/locale/fil_PH.mjs +1 -1
- package/node_modules/typebox/build/system/locale/fr_CA.mjs +1 -1
- package/node_modules/typebox/build/system/locale/fr_FR.mjs +1 -1
- package/node_modules/typebox/build/system/locale/ha_NG.mjs +1 -1
- package/node_modules/typebox/build/system/locale/hi_IN.mjs +1 -1
- package/node_modules/typebox/build/system/locale/hu_HU.mjs +1 -1
- package/node_modules/typebox/build/system/locale/id_ID.mjs +1 -1
- package/node_modules/typebox/build/system/locale/it_IT.mjs +1 -1
- package/node_modules/typebox/build/system/locale/ja_JP.mjs +1 -1
- package/node_modules/typebox/build/system/locale/ko_KR.mjs +1 -1
- package/node_modules/typebox/build/system/locale/ms_MY.mjs +1 -1
- package/node_modules/typebox/build/system/locale/nl_NL.mjs +1 -1
- package/node_modules/typebox/build/system/locale/pl_PL.mjs +1 -1
- package/node_modules/typebox/build/system/locale/pt_BR.mjs +1 -1
- package/node_modules/typebox/build/system/locale/pt_PT.mjs +1 -1
- package/node_modules/typebox/build/system/locale/ro_RO.mjs +1 -1
- package/node_modules/typebox/build/system/locale/ru_RU.mjs +1 -1
- package/node_modules/typebox/build/system/locale/sv_SE.mjs +1 -1
- package/node_modules/typebox/build/system/locale/sw_TZ.mjs +1 -1
- package/node_modules/typebox/build/system/locale/th_TH.mjs +1 -1
- package/node_modules/typebox/build/system/locale/tr_TR.mjs +1 -1
- package/node_modules/typebox/build/system/locale/uk_UA.mjs +1 -1
- package/node_modules/typebox/build/system/locale/ur_PK.mjs +1 -1
- package/node_modules/typebox/build/system/locale/vi_VN.mjs +1 -1
- package/node_modules/typebox/build/system/locale/yo_NG.mjs +1 -1
- package/node_modules/typebox/build/system/locale/zh_Hans.mjs +1 -1
- package/node_modules/typebox/build/system/locale/zh_Hant.mjs +1 -1
- package/node_modules/typebox/build/system/memory/clone.mjs +1 -1
- package/node_modules/typebox/build/system/settings/settings.mjs +1 -1
- package/node_modules/typebox/build/type/action/_add_immutable.mjs +1 -0
- package/node_modules/typebox/build/type/action/_add_optional.mjs +1 -0
- package/node_modules/typebox/build/type/action/_add_readonly.mjs +1 -0
- package/node_modules/typebox/build/type/action/_remove_immutable.mjs +1 -0
- package/node_modules/typebox/build/type/action/_remove_optional.mjs +1 -0
- package/node_modules/typebox/build/type/action/_remove_readonly.mjs +1 -0
- package/node_modules/typebox/build/type/action/conditional.mjs +1 -1
- package/node_modules/typebox/build/type/action/index.mjs +1 -1
- package/node_modules/typebox/build/type/action/mapped.mjs +1 -1
- package/node_modules/typebox/build/type/action/module.mjs +1 -1
- package/node_modules/typebox/build/type/action/with.mjs +1 -0
- package/node_modules/typebox/build/type/engine/call/distribute_arguments.mjs +1 -1
- package/node_modules/typebox/build/type/engine/call/instantiate.mjs +1 -1
- package/node_modules/typebox/build/type/engine/call/resolve_arguments.mjs +1 -1
- package/node_modules/typebox/build/type/engine/constructor_parameters/instantiate.mjs +1 -1
- package/node_modules/typebox/build/type/engine/cyclic/candidates.mjs +1 -1
- package/node_modules/typebox/build/type/engine/cyclic/check.mjs +1 -1
- package/node_modules/typebox/build/type/engine/cyclic/dependencies.mjs +1 -1
- package/node_modules/typebox/build/type/engine/cyclic/extends.mjs +1 -1
- package/node_modules/typebox/build/type/engine/cyclic/instantiate.mjs +1 -1
- package/node_modules/typebox/build/type/engine/enum/index.mjs +1 -1
- package/node_modules/typebox/build/type/engine/evaluate/broaden.mjs +1 -1
- package/node_modules/typebox/build/type/engine/evaluate/composite.mjs +1 -1
- package/node_modules/typebox/build/type/engine/evaluate/distribute.mjs +1 -1
- package/node_modules/typebox/build/type/engine/evaluate/evaluate.mjs +1 -1
- package/node_modules/typebox/build/type/engine/exclude/operation.mjs +1 -1
- package/node_modules/typebox/build/type/engine/extract/operation.mjs +1 -1
- package/node_modules/typebox/build/type/engine/immutable/instantiate_add.mjs +1 -0
- package/node_modules/typebox/build/type/engine/immutable/instantiate_remove.mjs +1 -0
- package/node_modules/typebox/build/type/engine/index.mjs +1 -1
- package/node_modules/typebox/build/type/engine/indexable/from_dependent.mjs +1 -0
- package/node_modules/typebox/build/type/engine/indexable/from_enum.mjs +1 -1
- package/node_modules/typebox/build/type/engine/indexable/from_template_literal.mjs +1 -1
- package/node_modules/typebox/build/type/engine/indexable/from_type.mjs +1 -1
- package/node_modules/typebox/build/type/engine/indexed/instantiate.mjs +1 -1
- package/node_modules/typebox/build/type/engine/instantiate.mjs +1 -1
- package/node_modules/typebox/build/type/engine/intrinsics/from_template_literal.mjs +1 -1
- package/node_modules/typebox/build/type/engine/keyof/instantiate.mjs +1 -1
- package/node_modules/typebox/build/type/engine/mapped/mapped_operation.mjs +1 -1
- package/node_modules/typebox/build/type/engine/mapped/mapped_variants.mjs +1 -1
- package/node_modules/typebox/build/type/engine/module/instantiate.mjs +1 -1
- package/node_modules/typebox/build/type/engine/object/from_dependent.mjs +1 -0
- package/node_modules/typebox/build/type/engine/object/from_type.mjs +1 -1
- package/node_modules/typebox/build/type/engine/object/from_union.mjs +1 -1
- package/node_modules/typebox/build/type/engine/optional/instantiate_add.mjs +1 -0
- package/node_modules/typebox/build/type/engine/optional/instantiate_remove.mjs +1 -0
- package/node_modules/typebox/build/type/engine/parameters/instantiate.mjs +1 -1
- package/node_modules/typebox/build/type/engine/partial/from_dependent.mjs +1 -0
- package/node_modules/typebox/build/type/engine/partial/from_intersect.mjs +1 -1
- package/node_modules/typebox/build/type/engine/partial/from_object.mjs +1 -1
- package/node_modules/typebox/build/type/engine/partial/from_type.mjs +1 -1
- package/node_modules/typebox/build/type/engine/priority/index.mjs +1 -0
- package/node_modules/typebox/build/type/engine/priority/priority.mjs +1 -0
- package/node_modules/typebox/build/type/engine/readonly/instantiate_add.mjs +1 -0
- package/node_modules/typebox/build/type/engine/readonly/instantiate_remove.mjs +1 -0
- package/node_modules/typebox/build/type/engine/readonly_object/from_array.mjs +1 -1
- package/node_modules/typebox/build/type/engine/readonly_object/from_dependent.mjs +1 -0
- package/node_modules/typebox/build/type/engine/readonly_object/from_intersect.mjs +1 -1
- package/node_modules/typebox/build/type/engine/readonly_object/from_object.mjs +1 -1
- package/node_modules/typebox/build/type/engine/readonly_object/from_tuple.mjs +1 -1
- package/node_modules/typebox/build/type/engine/readonly_object/from_type.mjs +1 -1
- package/node_modules/typebox/build/type/engine/record/from_key_enum.mjs +1 -1
- package/node_modules/typebox/build/type/engine/record/from_key_template_literal.mjs +1 -1
- package/node_modules/typebox/build/type/engine/ref/instantiate.mjs +1 -1
- package/node_modules/typebox/build/type/engine/required/from_dependent.mjs +1 -0
- package/node_modules/typebox/build/type/engine/required/from_intersect.mjs +1 -1
- package/node_modules/typebox/build/type/engine/required/from_object.mjs +1 -1
- package/node_modules/typebox/build/type/engine/required/from_type.mjs +1 -1
- package/node_modules/typebox/build/type/engine/template_literal/decode.mjs +1 -1
- package/node_modules/typebox/build/type/engine/template_literal/encode.mjs +1 -1
- package/node_modules/typebox/build/type/engine/template_literal/is_finite.mjs +1 -1
- package/node_modules/typebox/build/type/engine/this/expand_this.mjs +1 -1
- package/node_modules/typebox/build/type/engine/with/instantiate.mjs +1 -0
- package/node_modules/typebox/build/type/extends/dependent.mjs +1 -0
- package/node_modules/typebox/build/type/extends/enum.mjs +1 -1
- package/node_modules/typebox/build/type/extends/extends_left.mjs +1 -1
- package/node_modules/typebox/build/type/extends/extends_right.mjs +1 -1
- package/node_modules/typebox/build/type/extends/inference.mjs +1 -1
- package/node_modules/typebox/build/type/extends/object.mjs +1 -1
- package/node_modules/typebox/build/type/extends/parameters.mjs +1 -1
- package/node_modules/typebox/build/type/extends/record.mjs +1 -0
- package/node_modules/typebox/build/type/extends/template_literal.mjs +1 -1
- package/node_modules/typebox/build/type/extends/tuple.mjs +1 -1
- package/node_modules/typebox/build/type/extends/union.mjs +1 -1
- package/node_modules/typebox/build/type/script/mapping.mjs +1 -1
- package/node_modules/typebox/build/type/script/parser.mjs +6 -6
- package/node_modules/typebox/build/type/script/script.mjs +1 -1
- package/node_modules/typebox/build/type/script/token/internal/guard.mjs +1 -1
- package/node_modules/typebox/build/type/script/token/until.mjs +1 -1
- package/node_modules/typebox/build/type/types/_immutable.mjs +1 -1
- package/node_modules/typebox/build/type/types/_optional.mjs +1 -1
- package/node_modules/typebox/build/type/types/_readonly.mjs +1 -1
- package/node_modules/typebox/build/type/types/_refine.mjs +1 -1
- package/node_modules/typebox/build/type/types/call.mjs +1 -1
- package/node_modules/typebox/build/type/types/deferred.mjs +1 -1
- package/node_modules/typebox/build/type/types/dependent.mjs +1 -0
- package/node_modules/typebox/build/type/types/enum.mjs +1 -1
- package/node_modules/typebox/build/type/types/index.mjs +1 -1
- package/node_modules/typebox/build/type/types/number.mjs +1 -1
- package/node_modules/typebox/build/type/types/record.mjs +1 -1
- package/node_modules/typebox/build/typebox.mjs +1 -1
- package/node_modules/typebox/build/value/clean/clean.mjs +1 -1
- package/node_modules/typebox/build/value/clean/from_intersect.mjs +1 -1
- package/node_modules/typebox/build/value/clean/from_type.mjs +1 -1
- package/node_modules/typebox/build/value/clean/from_union.mjs +1 -1
- package/node_modules/typebox/build/value/clone/clone.mjs +1 -1
- package/node_modules/typebox/build/value/codec/decode.mjs +1 -1
- package/node_modules/typebox/build/value/codec/encode.mjs +1 -1
- package/node_modules/typebox/build/value/codec/from_array.mjs +1 -1
- package/node_modules/typebox/build/value/codec/from_object.mjs +1 -1
- package/node_modules/typebox/build/value/codec/from_record.mjs +1 -1
- package/node_modules/typebox/build/value/codec/from_tuple.mjs +1 -1
- package/node_modules/typebox/build/value/codec/from_union.mjs +1 -1
- package/node_modules/typebox/build/value/convert/from_enum.mjs +1 -1
- package/node_modules/typebox/build/value/convert/from_template_literal.mjs +1 -1
- package/node_modules/typebox/build/value/convert/from_type.mjs +1 -1
- package/node_modules/typebox/build/value/create/from_enum.mjs +1 -1
- package/node_modules/typebox/build/value/create/from_type.mjs +1 -1
- package/node_modules/typebox/build/value/default/from_object.mjs +1 -1
- package/node_modules/typebox/build/value/default/from_type.mjs +1 -1
- package/node_modules/typebox/build/value/index.mjs +1 -1
- package/node_modules/typebox/build/value/repair/from_enum.mjs +1 -1
- package/node_modules/typebox/build/value/repair/from_type.mjs +1 -1
- package/node_modules/typebox/build/value/shared/union_priority_sort.mjs +1 -1
- package/node_modules/typebox/build/value/value.mjs +1 -1
- package/node_modules/typebox/package.json +1 -1
- package/package.json +1 -1
- package/node_modules/typebox/build/schema/engine/_guard.mjs +0 -1
- package/node_modules/typebox/build/schema/types/_guard.mjs +0 -1
- package/node_modules/typebox/build/type/action/_optional.mjs +0 -1
- package/node_modules/typebox/build/type/action/_readonly.mjs +0 -1
- package/node_modules/typebox/build/type/action/awaited.mjs +0 -1
- package/node_modules/typebox/build/type/action/options.mjs +0 -1
- package/node_modules/typebox/build/type/engine/awaited/instantiate.mjs +0 -1
- package/node_modules/typebox/build/type/engine/enum/enum_to_union.mjs +0 -1
- package/node_modules/typebox/build/type/engine/options/index.mjs +0 -1
- package/node_modules/typebox/build/type/engine/options/instantiate.mjs +0 -1
- package/node_modules/typebox/build/type/extends/async_iterator.mjs +0 -1
- package/node_modules/typebox/build/type/extends/iterator.mjs +0 -1
- package/node_modules/typebox/build/type/extends/promise.mjs +0 -1
- package/node_modules/typebox/build/type/types/async_iterator.mjs +0 -1
- package/node_modules/typebox/build/type/types/base.mjs +0 -1
- package/node_modules/typebox/build/type/types/iterator.mjs +0 -1
- package/node_modules/typebox/build/type/types/promise.mjs +0 -1
- package/node_modules/typebox/build/value/clean/from_base.mjs +0 -1
- package/node_modules/typebox/build/value/convert/from_base.mjs +0 -1
- package/node_modules/typebox/build/value/create/from_async_iterator.mjs +0 -1
- package/node_modules/typebox/build/value/create/from_base.mjs +0 -1
- package/node_modules/typebox/build/value/create/from_iterator.mjs +0 -1
- package/node_modules/typebox/build/value/create/from_promise.mjs +0 -1
- package/node_modules/typebox/build/value/default/from_base.mjs +0 -1
- package/node_modules/typebox/build/value/mutate/error.mjs +0 -1
- package/node_modules/typebox/build/value/mutate/from_array.mjs +0 -1
- package/node_modules/typebox/build/value/mutate/from_object.mjs +0 -1
- package/node_modules/typebox/build/value/mutate/from_unknown.mjs +0 -1
- package/node_modules/typebox/build/value/mutate/from_value.mjs +0 -1
- package/node_modules/typebox/build/value/mutate/index.mjs +0 -1
- package/node_modules/typebox/build/value/mutate/mutate.mjs +0 -1
- package/node_modules/typebox/build/value/repair/from_base.mjs +0 -1
- /package/node_modules/typebox/build/type/engine/{awaited → with}/index.mjs +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var pe=Object.defineProperty;var o=(e,r)=>pe(e,"name",{value:r,configurable:!0});function me(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:os")??null}o(me,"loadNodeOs");const q=me();import{clampThinkingLevel as ye}from"../models.js";import{registerSessionResourceCleanup as be}from"../session-resources.js";import{combineAbortSignals as we}from"../utils/abort-signals.js";import{splitDeferredTools as he}from"../utils/deferred-tools.js";import{appendAssistantMessageDiagnostic as Ee,createAssistantMessageDiagnostic as Se,formatThrownValue as $}from"../utils/diagnostics.js";import{formatProviderError as ge,normalizeProviderError as _e}from"../utils/error-body.js";import{AssistantMessageEventStream as ke}from"../utils/event-stream.js";import{headersToRecord as K}from"../utils/headers.js";import{resolveHttpProxyUrlForTarget as Te}from"../utils/node-http-proxy.js";import{uuidv7 as Re}from"../utils/uuid.js";import{createGrammarToolInputProperties as G}from"./constrained-sampling.js";import{clampOpenAIPromptCacheKey as xe}from"./openai-prompt-cache.js";import{convertResponsesMessages as j,convertResponsesTools as Ce,processResponsesStream as V}from"./openai-responses-shared.js";import{buildBaseOptions as ve}from"./simple-options.js";const Oe="https://chatgpt.com/backend-api",Ae="https://api.openai.com/auth",We=0,X=1e3,Le=6e4,De=15e3,Me=3,Y=new Set(["openai","openai-codex","opencode"]),Ne=1009,Ie="websocket_connection_limit_reached",qe="previous_response_not_found",Be=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function Pe(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}o(Pe,"isTerminalRateLimitError");function Fe(e,r){return e===429&&Pe(r)?!1:e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(r)}o(Fe,"isRetryableError");function $e(e){const r=e.get("retry-after-ms");if(r!==null){const s=Number(r);if(Number.isFinite(s))return Math.max(0,s)}const t=e.get("retry-after");if(!t)return;const n=Number(t);if(Number.isFinite(n))return Math.max(0,n*1e3);const a=Date.parse(t);if(!Number.isNaN(a))return Math.max(0,a-Date.now())}o($e,"getRetryAfterDelayMs");class Z extends Error{static{o(this,"RetryDelayExceededError")}}function Ue(e,r){const t=r?.maxRetryDelayMs??Le;if(t>0&&e>t)throw new Z(`Server requested ${Math.ceil(e/1e3)}s retry delay (max: ${Math.ceil(t/1e3)}s)`);return e}o(Ue,"validateRetryDelayMs");function Q(e,r){return new Promise((t,n)=>{if(r?.aborted){n(new Error("Request was aborted"));return}const a=setTimeout(t,e);r?.addEventListener("abort",()=>{clearTimeout(a),n(new Error("Request was aborted"))})})}o(Q,"sleep");function ee(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}o(ee,"normalizeTimeoutMs");function Je(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:zlib")??null}o(Je,"loadNodeZlib");function ze(e){const r=Je();if(!r||typeof r.zstdCompressSync!="function")return null;try{const t=r.zstdCompressSync(e,{params:{[r.constants.ZSTD_c_compressionLevel]:Me}});return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}catch{return null}}o(ze,"compressRequestBodyZstd");export const stream=o((e,r,t)=>{const n=new ke;return(async()=>{const a={role:"assistant",content:[],api:"openai-codex-responses",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const s=t?.apiKey;if(!s)throw new Error(`No API key for provider: ${e.provider}`);const i=Et(s),f=G(r.tools,e.compat?.supportsOpenAIGrammarTools??!1),c=t?.cacheRetention==="none"?void 0:t?.sessionId,u=xe(c);let p=He(e,r,t,u,f);const d=await t?.onPayload?.(p,e);d!==void 0&&(p=d);const S=u||Re(),l=St(e.headers,t?.headers,i,s,u),g=gt(e.headers,t?.headers,i,s,S),y=JSON.stringify(p),m=ee(t?.timeoutMs),C=ee(t?.websocketConnectTimeoutMs),b=t?.transport||"auto";let h=!1;const w=b!=="sse"&&se(c);if(w&&ae(c),b!=="sse"&&!w){let E=!1,k=!1,O=!1;for(;;){E=!1;try{if(await wt(Ge(e.baseUrl),p,g,a,n,e,()=>{E=!0,h||(h=!0,n.push({type:"start",partial:a}))},m,C,c,f,t),t?.signal?.aborted)throw new Error("Request was aborted");n.push({type:"done",reason:a.stopReason,message:a}),n.end();return}catch(R){const D=t?.signal?.aborted,M=!E&&Xe(R),W=Ye(R);if(!D&&W&&!O){O=!0;continue}if(!D&&M&&!k){k=!0;continue}if(D||Ve(R)&&!M||(Ee(a,Se("provider_transport_failure",R,{configuredTransport:b,fallbackTransport:E?void 0:"sse",eventsEmitted:E,phase:E?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(y).byteLength})),ot(c,R),E))throw R;ae(c);break}}}const v=ze(y);v&&l.set("content-encoding","zstd");const A=v??y;let _,L;const F=t?.maxRetries??We;for(let E=0;E<=F;E++){if(t?.signal?.aborted)throw new Error("Request was aborted");try{const k=m!==void 0&&m>0?AbortSignal.timeout(m):void 0,O=we([t?.signal,k]);try{_=await fetch(ne(e.baseUrl),{method:"POST",headers:l,body:A,signal:O.signal})}catch(W){throw k?.aborted&&!t?.signal?.aborted?new Error(`Codex SSE response headers timed out after ${m}ms`):W}finally{O.cleanup()}if(await t?.onResponse?.({status:_.status,headers:K(_.headers)},e),_.ok)break;const R=await _.text();if(E<F&&Fe(_.status,R)){const W=$e(_.headers),fe=W===void 0?X*2**E:Ue(W,t);await Q(fe,t?.signal);continue}const D=new Response(R,{status:_.status,statusText:_.statusText}),M=await ht(D);throw new Error(M.friendlyMessage||M.message)}catch(k){if(k instanceof Error&&(k.name==="AbortError"||k.message==="Request was aborted"))throw new Error("Request was aborted");if(L=k instanceof Error?k:new Error(String(k)),E<F&&!(L instanceof Z)&&!L.message.includes("usage limit")){const O=X*2**E;await Q(O,t?.signal);continue}throw L}}if(!_?.ok)throw L??new Error("Failed after retries");if(!_.body)throw new Error("No response body");if(h||(h=!0,n.push({type:"start",partial:a})),await je(_,a,n,e,f,t),t?.signal?.aborted)throw new Error("Request was aborted");n.push({type:"done",reason:a.stopReason,message:a}),n.end()}catch(s){for(const i of a.content)delete i.partialJson,delete i.customInput;a.stopReason=t?.signal?.aborted?"aborted":"error",a.errorMessage=ge(_e(s)),n.push({type:"error",reason:a.stopReason,error:a}),n.end()}})(),n},"stream"),streamSimple=o((e,r,t)=>{const n=t?.apiKey;if(!n)throw new Error(`No API key for provider: ${e.provider}`);const a=ve(e,r,t,n),s=t?.reasoning?ye(e,t.reasoning):void 0;return stream(e,r,{...a,reasoningEffort:s==="off"?void 0:s})},"streamSimple");function He(e,r,t,n,a=G(r.tools,e.compat?.supportsOpenAIGrammarTools??!1)){const s=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,f=he(r,e.compat?.supportsToolSearch??!1),c=j(e,r,Y,{includeSystemPrompt:!1,grammarToolInputProperties:a,deferredTools:f.deferred,toolOptions:{strict:null,supportsStrictMode:s,supportsOpenAIGrammarTools:i}}),u={model:e.id,store:!1,stream:!0,instructions:r.systemPrompt||"You are a helpful assistant.",input:c,text:{verbosity:t?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:t?.toolChoice??"auto",parallel_tool_calls:!0};if(t?.temperature!==void 0&&(u.temperature=t.temperature),t?.serviceTier!==void 0&&(u.service_tier=t.serviceTier),f.immediate.length>0&&(u.tools=Ce(f.immediate,{strict:null,supportsStrictMode:s,supportsOpenAIGrammarTools:i})),t?.reasoningEffort!==void 0){const p=t.reasoningEffort==="none"?e.thinkingLevelMap?.off??"none":e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;p!==null&&(u.reasoning={effort:p,summary:t.reasoningSummary??"auto"})}return u}o(He,"buildRequestBody");function Ke(e,r){switch(r){case"flex":return .5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}o(Ke,"getServiceTierCostMultiplier");function te(e,r,t){const n=Ke(t,r);n!==1&&(e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}o(te,"applyServiceTierPricing");function re(e,r){return e==="default"&&(r==="flex"||r==="priority")?r:e??r}o(re,"resolveCodexServiceTier");function ne(e){const t=(e&&e.trim().length>0?e:Oe).replace(/\/+$/,"");return t.endsWith("/codex/responses")?t:t.endsWith("/codex")?`${t}/responses`:`${t}/codex/responses`}o(ne,"resolveCodexUrl");function Ge(e){const r=new URL(ne(e));return r.protocol==="https:"&&(r.protocol="wss:"),r.protocol==="http:"&&(r.protocol="ws:"),r.toString()}o(Ge,"resolveCodexWebSocketUrl");async function je(e,r,t,n,a,s){await V(oe(et(e,s?.signal)),r,t,n,{serviceTier:s?.serviceTier,grammarToolInputProperties:a,resolveServiceTier:re,applyServiceTierPricing:o((i,f)=>te(i,f,n),"applyServiceTierPricing")})}o(je,"processStream");class N extends Error{static{o(this,"CodexApiError")}code;payload;constructor(r,t){super(r),this.name="CodexApiError",this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}}class U extends Error{static{o(this,"CodexProtocolError")}payload;constructor(r,t){super(r),this.name="CodexProtocolError",this.payload=t?.payload,this.cause=t?.cause}}function Ve(e){return e instanceof N||e instanceof U}o(Ve,"isCodexNonTransportError");function Xe(e){return e instanceof N&&e.code===Ie}o(Xe,"isWebSocketConnectionLimitReachedError");function Ye(e){return e instanceof N&&e.code===qe}o(Ye,"isPreviousResponseNotFoundError");function Ze(e){const r=e.error&&typeof e.error=="object"?e.error:void 0;return{code:typeof e.code=="string"?e.code:typeof r?.code=="string"?r.code:void 0,message:typeof e.message=="string"?e.message:typeof r?.message=="string"?r.message:void 0}}o(Ze,"extractCodexEventError");async function*oe(e){for await(const r of e){const t=typeof r.type=="string"?r.type:void 0;if(t){if(t==="error"){const{code:n,message:a}=Ze(r);throw new N(`Codex error: ${a||n||JSON.stringify(r)}`,{code:n,payload:r})}if(t==="response.failed"){const n=r.response,a=n?.error?.code,s=n?.error?.message;throw new N(s||"Codex response failed",{code:a,payload:r})}if(t==="response.done"||t==="response.completed"||t==="response.incomplete"){const n=r.response,a=n&&{...n,status:Qe(n.status)};yield{...r,type:"response.completed",response:a};return}yield r}}}o(oe,"mapCodexEvents");function Qe(e){if(typeof e=="string")return Be.has(e)?e:void 0}o(Qe,"normalizeCodexStatus");async function*et(e,r){if(!e.body)return;const t=e.body.getReader(),n=new TextDecoder;let a="";const s=o(()=>{t.cancel().catch(()=>{})},"onAbort");r?.addEventListener("abort",s,{once:!0});try{for(;;){if(r?.aborted)throw new Error("Request was aborted");const{done:i,value:f}=await t.read();if(r?.aborted)throw new Error("Request was aborted");if(i)break;a+=n.decode(f,{stream:!0});let c=a.indexOf(`
|
|
1
|
+
var me=Object.defineProperty;var o=(e,r)=>me(e,"name",{value:r,configurable:!0});function ye(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:os")??null}o(ye,"loadNodeOs");const q=ye();import{clampThinkingLevel as be}from"../models.js";import{registerSessionResourceCleanup as we}from"../session-resources.js";import{combineAbortSignals as he}from"../utils/abort-signals.js";import{splitDeferredTools as Ee}from"../utils/deferred-tools.js";import{appendAssistantMessageDiagnostic as Se,createAssistantMessageDiagnostic as ge,formatThrownValue as $}from"../utils/diagnostics.js";import{formatProviderError as _e,normalizeProviderError as ke}from"../utils/error-body.js";import{AssistantMessageEventStream as Te}from"../utils/event-stream.js";import{headersToRecord as K}from"../utils/headers.js";import{resolveHttpProxyUrlForTarget as Re}from"../utils/node-http-proxy.js";import{uuidv7 as xe}from"../utils/uuid.js";import{createGrammarToolInputProperties as G}from"./constrained-sampling.js";import{clampOpenAIPromptCacheKey as Ce}from"./openai-prompt-cache.js";import{convertResponsesMessages as j,convertResponsesTools as ve,processResponsesStream as V}from"./openai-responses-shared.js";import{buildBaseOptions as Oe}from"./simple-options.js";const Ae="https://chatgpt.com/backend-api",We="https://api.openai.com/auth",Le=0,X=1e3,Me=6e4,De=15e3,Ne=3,Y=new Set(["openai","openai-codex","opencode"]),Ie=1009,qe="websocket_connection_limit_reached",Be="previous_response_not_found",Pe=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function Z(e){if(e.stopReason==="pending")throw new Error("Codex stream ended without a stop reason");if(e.stopReason==="error"||e.stopReason==="aborted")throw new Error(e.errorMessage||"An unknown error occurred")}o(Z,"assertSuccessfulOutput");function Fe(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}o(Fe,"isTerminalRateLimitError");function $e(e,r){return e===429&&Fe(r)?!1:e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(r)}o($e,"isRetryableError");function Ue(e){const r=e.get("retry-after-ms");if(r!==null){const a=Number(r);if(Number.isFinite(a))return Math.max(0,a)}const t=e.get("retry-after");if(!t)return;const n=Number(t);if(Number.isFinite(n))return Math.max(0,n*1e3);const s=Date.parse(t);if(!Number.isNaN(s))return Math.max(0,s-Date.now())}o(Ue,"getRetryAfterDelayMs");class Q extends Error{static{o(this,"RetryDelayExceededError")}}function Je(e,r){const t=r?.maxRetryDelayMs??Me;if(t>0&&e>t)throw new Q(`Server requested ${Math.ceil(e/1e3)}s retry delay (max: ${Math.ceil(t/1e3)}s)`);return e}o(Je,"validateRetryDelayMs");function ee(e,r){return new Promise((t,n)=>{if(r?.aborted){n(new Error("Request was aborted"));return}const s=setTimeout(t,e);r?.addEventListener("abort",()=>{clearTimeout(s),n(new Error("Request was aborted"))})})}o(ee,"sleep");function te(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}o(te,"normalizeTimeoutMs");function ze(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:zlib")??null}o(ze,"loadNodeZlib");function He(e){const r=ze();if(!r||typeof r.zstdCompressSync!="function")return null;try{const t=r.zstdCompressSync(e,{params:{[r.constants.ZSTD_c_compressionLevel]:Ne}});return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}catch{return null}}o(He,"compressRequestBodyZstd");export const stream=o((e,r,t)=>{const n=new Te;return(async()=>{const s={role:"assistant",content:[],api:"openai-codex-responses",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{const a=t?.apiKey;if(!a)throw new Error(`No API key for provider: ${e.provider}`);const i=St(a),f=G(r.tools,e.compat?.supportsOpenAIGrammarTools??!1),c=t?.cacheRetention==="none"?void 0:t?.sessionId,u=Ce(c);let p=Ke(e,r,t,u,f);const d=await t?.onPayload?.(p,e);d!==void 0&&(p=d);const S=u||xe(),l=gt(e.headers,t?.headers,i,a,u),g=_t(e.headers,t?.headers,i,a,S),y=JSON.stringify(p),m=te(t?.timeoutMs),C=te(t?.websocketConnectTimeoutMs),b=t?.transport||"auto";let h=!1;const w=b!=="sse"&&ae(c);if(w&&ie(c),b!=="sse"&&!w){let E=!1,k=!1,O=!1;for(;;){E=!1;try{if(await ht(je(e.baseUrl),p,g,s,n,e,()=>{E=!0,h||(h=!0,n.push({type:"start",partial:s}))},m,C,c,f,t),t?.signal?.aborted)throw new Error("Request was aborted");Z(s),n.push({type:"done",reason:s.stopReason,message:s}),n.end();return}catch(R){const M=t?.signal?.aborted,D=!E&&Ye(R),W=Ze(R);if(!M&&W&&!O){O=!0;continue}if(!M&&D&&!k){k=!0;continue}if(M||Xe(R)&&!D||(Se(s,ge("provider_transport_failure",R,{configuredTransport:b,fallbackTransport:E?void 0:"sse",eventsEmitted:E,phase:E?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(y).byteLength})),st(c,R),E))throw R;ie(c);break}}}const v=He(y);v&&l.set("content-encoding","zstd");const A=v??y;let _,L;const F=t?.maxRetries??Le;for(let E=0;E<=F;E++){if(t?.signal?.aborted)throw new Error("Request was aborted");try{const k=m!==void 0&&m>0?AbortSignal.timeout(m):void 0,O=he([t?.signal,k]);try{_=await(t?.fetch??globalThis.fetch)(oe(e.baseUrl),{method:"POST",headers:l,body:A,signal:O.signal})}catch(W){throw k?.aborted&&!t?.signal?.aborted?new Error(`Codex SSE response headers timed out after ${m}ms`):W}finally{O.cleanup()}if(await t?.onResponse?.({status:_.status,headers:K(_.headers)},e),_.ok)break;const R=await _.text();if(E<F&&$e(_.status,R)){const W=Ue(_.headers),pe=W===void 0?X*2**E:Je(W,t);await ee(pe,t?.signal);continue}const M=new Response(R,{status:_.status,statusText:_.statusText}),D=await Et(M);throw new Error(D.friendlyMessage||D.message)}catch(k){if(k instanceof Error&&(k.name==="AbortError"||k.message==="Request was aborted"))throw new Error("Request was aborted");if(L=k instanceof Error?k:new Error(String(k)),E<F&&!(L instanceof Q)&&!L.message.includes("usage limit")){const O=X*2**E;await ee(O,t?.signal);continue}throw L}}if(!_?.ok)throw L??new Error("Failed after retries");if(!_.body)throw new Error("No response body");if(h||(h=!0,n.push({type:"start",partial:s})),await Ve(_,s,n,e,f,t),t?.signal?.aborted)throw new Error("Request was aborted");Z(s),n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(a){for(const i of s.content)delete i.partialJson,delete i.customInput;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=_e(ke(a)),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},"stream"),streamSimple=o((e,r,t)=>{const n=t?.apiKey;if(!n)throw new Error(`No API key for provider: ${e.provider}`);const s=Oe(e,r,t,n),a=t?.reasoning?be(e,t.reasoning):void 0;return stream(e,r,{...s,reasoningEffort:a==="off"?void 0:a})},"streamSimple");function Ke(e,r,t,n,s=G(r.tools,e.compat?.supportsOpenAIGrammarTools??!1)){const a=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,f=Ee(r,e.compat?.supportsToolSearch??!1),c=j(e,r,Y,{includeSystemPrompt:!1,grammarToolInputProperties:s,deferredTools:f.deferred,toolOptions:{strict:null,supportsStrictMode:a,supportsOpenAIGrammarTools:i}}),u={model:e.id,store:!1,stream:!0,instructions:r.systemPrompt||"You are a helpful assistant.",input:c,text:{verbosity:t?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:t?.toolChoice??"auto",parallel_tool_calls:!0};if(t?.temperature!==void 0&&(u.temperature=t.temperature),t?.serviceTier!==void 0&&(u.service_tier=t.serviceTier),f.immediate.length>0&&(u.tools=ve(f.immediate,{strict:null,supportsStrictMode:a,supportsOpenAIGrammarTools:i})),t?.reasoningEffort!==void 0){const p=t.reasoningEffort==="none"?e.thinkingLevelMap?.off??"none":e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;p!==null&&(u.reasoning={effort:p,summary:t.reasoningSummary??"auto"})}return u}o(Ke,"buildRequestBody");function Ge(e,r){switch(r){case"flex":return .5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}o(Ge,"getServiceTierCostMultiplier");function re(e,r,t){const n=Ge(t,r);n!==1&&(e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}o(re,"applyServiceTierPricing");function ne(e,r){return e==="default"&&(r==="flex"||r==="priority")?r:e??r}o(ne,"resolveCodexServiceTier");function oe(e){const t=(e&&e.trim().length>0?e:Ae).replace(/\/+$/,"");return t.endsWith("/codex/responses")?t:t.endsWith("/codex")?`${t}/responses`:`${t}/codex/responses`}o(oe,"resolveCodexUrl");function je(e){const r=new URL(oe(e));return r.protocol==="https:"&&(r.protocol="wss:"),r.protocol==="http:"&&(r.protocol="ws:"),r.toString()}o(je,"resolveCodexWebSocketUrl");async function Ve(e,r,t,n,s,a){await V(se(tt(e,a?.signal)),r,t,n,{serviceTier:a?.serviceTier,grammarToolInputProperties:s,resolveServiceTier:ne,applyServiceTierPricing:o((i,f)=>re(i,f,n),"applyServiceTierPricing")})}o(Ve,"processStream");class N extends Error{static{o(this,"CodexApiError")}code;payload;constructor(r,t){super(r),this.name="CodexApiError",this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}}class U extends Error{static{o(this,"CodexProtocolError")}payload;constructor(r,t){super(r),this.name="CodexProtocolError",this.payload=t?.payload,this.cause=t?.cause}}function Xe(e){return e instanceof N||e instanceof U}o(Xe,"isCodexNonTransportError");function Ye(e){return e instanceof N&&e.code===qe}o(Ye,"isWebSocketConnectionLimitReachedError");function Ze(e){return e instanceof N&&e.code===Be}o(Ze,"isPreviousResponseNotFoundError");function Qe(e){const r=e.error&&typeof e.error=="object"?e.error:void 0;return{code:typeof e.code=="string"?e.code:typeof r?.code=="string"?r.code:void 0,message:typeof e.message=="string"?e.message:typeof r?.message=="string"?r.message:void 0}}o(Qe,"extractCodexEventError");async function*se(e){for await(const r of e){const t=typeof r.type=="string"?r.type:void 0;if(t){if(t==="error"){const{code:n,message:s}=Qe(r);throw new N(`Codex error: ${s||n||JSON.stringify(r)}`,{code:n,payload:r})}if(t==="response.failed"){const n=r.response,s=n?.error?.code,a=n?.error?.message;throw new N(a||"Codex response failed",{code:s,payload:r})}if(t==="response.done"||t==="response.completed"||t==="response.incomplete"){const n=r.response,s=n&&{...n,status:et(n.status)};yield{...r,type:"response.completed",response:s};return}yield r}}}o(se,"mapCodexEvents");function et(e){if(typeof e=="string")return Pe.has(e)?e:void 0}o(et,"normalizeCodexStatus");async function*tt(e,r){if(!e.body)return;const t=e.body.getReader(),n=new TextDecoder;let s="";const a=o(()=>{t.cancel().catch(()=>{})},"onAbort");r?.addEventListener("abort",a,{once:!0});try{for(;;){if(r?.aborted)throw new Error("Request was aborted");const{done:i,value:f}=await t.read();if(r?.aborted)throw new Error("Request was aborted");if(i)break;s+=n.decode(f,{stream:!0});let c=s.indexOf(`
|
|
2
2
|
|
|
3
|
-
`);for(;c!==-1;){const u=
|
|
3
|
+
`);for(;c!==-1;){const u=s.slice(0,c);s=s.slice(c+2);const p=u.split(`
|
|
4
4
|
`).filter(d=>d.startsWith("data:")).map(d=>d.slice(5).trim());if(p.length>0){const d=p.join(`
|
|
5
|
-
`).trim();if(d&&d!=="[DONE]")try{yield JSON.parse(d)}catch(S){throw new U(`Invalid Codex SSE JSON: ${$(S)}`,{cause:S,payload:d})}}c=
|
|
5
|
+
`).trim();if(d&&d!=="[DONE]")try{yield JSON.parse(d)}catch(S){throw new U(`Invalid Codex SSE JSON: ${$(S)}`,{cause:S,payload:d})}}c=s.indexOf(`
|
|
6
6
|
|
|
7
|
-
`)}}}finally{r?.removeEventListener("abort",s);try{await t.cancel()}catch{}try{t.releaseLock()}catch{}}}o(et,"parseSSE");const tt="responses_websockets=2026-02-06",rt=300*1e3,nt=3300*1e3,T=new Map,I=new Map,B=new Set;function J(e){let r=I.get(e);return r||(r={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},I.set(e,r)),r}o(J,"getOrCreateWebSocketDebugStats");export function getOpenAICodexWebSocketDebugStats(e){const r=I.get(e);return r?{...r}:void 0}o(getOpenAICodexWebSocketDebugStats,"getOpenAICodexWebSocketDebugStats");export function resetOpenAICodexWebSocketDebugStats(e){if(e){I.delete(e),B.delete(e);return}I.clear(),B.clear()}o(resetOpenAICodexWebSocketDebugStats,"resetOpenAICodexWebSocketDebugStats");export function closeOpenAICodexWebSocketSessions(e){const r=o(t=>{t.idleTimer&&clearTimeout(t.idleTimer),x(t.socket,1e3,"debug_close")},"closeEntry");if(e){const t=T.get(e);t&&r(t),T.delete(e);return}for(const t of T.values())r(t);T.clear()}o(closeOpenAICodexWebSocketSessions,"closeOpenAICodexWebSocketSessions"),be(closeOpenAICodexWebSocketSessions);function se(e){return e?B.has(e):!1}o(se,"isWebSocketSseFallbackActive");function ae(e){if(!e)return;const r=J(e);r.sseFallbacks++,r.websocketFallbackActive=se(e)}o(ae,"recordWebSocketSseFallback");function ot(e,r){if(!e)return;B.add(e);const t=J(e);t.websocketFailures++,t.lastWebSocketError=$(r),t.websocketFallbackActive=!0}o(ot,"recordWebSocketFailure");let z=null;async function st(e){if(!e&&z)return z;if(typeof process<"u"&&process.versions?.bun){const t=class extends WebSocket{static{o(this,"WebSocketWithProxy")}constructor(n,a){let s={};Array.isArray(a)||typeof a=="string"?s={protocols:a}:s={...a};const i=Te(n.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),e);super(n,{...s,...i?{proxy:i.toString()}:{}})}};return e||(z=t),t}const r=globalThis.WebSocket;return typeof r!="function"?null:r}o(st,"getWebSocketConstructor");class at extends Error{static{o(this,"WebSocketCloseError")}code;reason;wasClean;constructor(r,t){super(r),this.name="WebSocketCloseError",this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}}function it(e){const r=e.readyState;return typeof r=="number"?r:void 0}o(it,"getWebSocketReadyState");function P(e){const r=it(e);return r===void 0||r===1}o(P,"isWebSocketReusable");function ct(e){return Date.now()-e.createdAt>=nt}o(ct,"isWebSocketSessionExpired");function x(e,r=1e3,t="done"){try{e.close(r,t)}catch{}}o(x,"closeWebSocketSilently");function ie(e,r){r.idleTimer&&clearTimeout(r.idleTimer),r.idleTimer=setTimeout(()=>{r.busy||(x(r.socket,1e3,"idle_timeout"),T.delete(e))},rt)}o(ie,"scheduleSessionWebSocketExpiry");async function H(e,r,t,n=De,a){const s=await st(a);if(!s)throw new Error("WebSocket transport is not available in this runtime");const i=K(r);return delete i["OpenAI-Beta"],new Promise((f,c)=>{let u=!1,p,d;try{d=new s(e,{headers:i})}catch(b){c(b instanceof Error?b:new Error(String(b)));return}const S=o(()=>{p&&(clearTimeout(p),p=void 0),d.removeEventListener("open",g),d.removeEventListener("error",y),d.removeEventListener("close",m),t?.removeEventListener("abort",C)},"cleanup"),l=o((b,h)=>{u||(u=!0,S(),h&&x(d,1e3,h),c(b))},"fail"),g=o(()=>{u||(u=!0,S(),f(d))},"onOpen"),y=o(b=>{l(ce(b))},"onError"),m=o(b=>{l(ue(b))},"onClose"),C=o(()=>{l(new Error("Request was aborted"),"aborted")},"onAbort");d.addEventListener("open",g),d.addEventListener("error",y),d.addEventListener("close",m),t?.addEventListener("abort",C),n>0&&(p=setTimeout(()=>{l(new Error(`WebSocket connect timeout after ${n}ms`),"connect_timeout")},n)),t?.aborted&&C()})}o(H,"connectWebSocket");async function ut(e,r,t,n,a,s){if(!t){const u=await H(e,r,n,a,s);return{socket:u,reused:!1,release:o(()=>x(u),"release")}}const i=T.get(t);if(i){if(i.idleTimer&&(clearTimeout(i.idleTimer),i.idleTimer=void 0),!i.busy&&ct(i))x(i.socket,1e3,"connection_age_limit"),T.delete(t);else if(!i.busy&&P(i.socket))return i.busy=!0,{socket:i.socket,entry:i,reused:!0,release:o(({keep:u}={})=>{if(!u||!P(i.socket)){x(i.socket),T.delete(t);return}i.busy=!1,ie(t,i)},"release")};if(i.busy){const u=await H(e,r,n,a,s);return{socket:u,reused:!1,release:o(()=>{x(u)},"release")}}P(i.socket)||(x(i.socket),T.delete(t))}const f=await H(e,r,n,a,s),c={socket:f,busy:!0,createdAt:Date.now()};return T.set(t,c),{socket:f,entry:c,reused:!1,release:o(({keep:u}={})=>{if(!u||!P(c.socket)){x(c.socket),c.idleTimer&&clearTimeout(c.idleTimer),T.get(t)===c&&T.delete(t);return}c.busy=!1,ie(t,c)},"release")}}o(ut,"acquireWebSocket");function ce(e){if(e&&typeof e=="object"){const r="message"in e?e.message:void 0;if(typeof r=="string"&&r.length>0)return new Error(r);const t="error"in e?e.error:void 0;if(t instanceof Error&&t.message.length>0)return t;if(t&&typeof t=="object"&&"message"in t){const n=t.message;if(typeof n=="string"&&n.length>0)return new Error(n)}}return new Error("WebSocket error")}o(ce,"extractWebSocketError");function ue(e){if(e&&typeof e=="object"){const r="code"in e?e.code:void 0,t="reason"in e?e.reason:void 0,n="wasClean"in e?e.wasClean:void 0,a=typeof r=="number"?` ${r}`:"";let s=typeof t=="string"&&t.length>0?` ${t}`:"";return!s&&r===Ne&&(s=" message too big"),new at(`WebSocket closed${a}${s}`.trim(),{code:typeof r=="number"?r:void 0,reason:typeof t=="string"&&t.length>0?t:void 0,wasClean:typeof n=="boolean"?n:void 0})}return new Error("WebSocket closed")}o(ue,"extractWebSocketCloseError");async function dt(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){const r=e;return new TextDecoder().decode(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}if(e&&typeof e=="object"&&"arrayBuffer"in e){const t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}o(dt,"decodeWebSocketData");async function*lt(e,r,t){const n=[];let a=null,s=!1,i=null,f=!1;const c=o(()=>{if(!a)return;const l=a;a=null,l()},"wake"),u=o(l=>{(async()=>{let g=null;try{if(!l||typeof l!="object"||!("data"in l)||(g=await dt(l.data),!g))return;const y=JSON.parse(g),m=typeof y.type=="string"?y.type:"";(m==="response.completed"||m==="response.done"||m==="response.incomplete")&&(f=!0,s=!0),n.push(y),c()}catch(y){i=new U(`Invalid Codex WebSocket JSON: ${$(y)}`,{cause:y,payload:g}),s=!0,c()}})()},"onMessage"),p=o(l=>{i=ce(l),s=!0,c()},"onError"),d=o(l=>{if(f){s=!0,c();return}i||(i=ue(l)),s=!0,c()},"onClose"),S=o(()=>{i=new Error("Request was aborted"),s=!0,c()},"onAbort");e.addEventListener("message",u),e.addEventListener("error",p),e.addEventListener("close",d),r?.addEventListener("abort",S);try{for(;;){if(r?.aborted)throw new Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(s)break;let l;await new Promise((g,y)=>{a=g,t!==void 0&&t>0&&(l=setTimeout(()=>{const m=new Error(`WebSocket idle timeout after ${t}ms`);i=m,s=!0,a=null,x(e,1e3,"idle_timeout"),y(m)},t))}).finally(()=>{l&&clearTimeout(l)})}if(i)throw i;if(!f)throw new Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",u),e.removeEventListener("error",p),e.removeEventListener("close",d),r?.removeEventListener("abort",S)}}o(lt,"parseWebSocket");function de(e){const{input:r,previous_response_id:t,...n}=e;return n}o(de,"requestBodyWithoutInput");function ft(e,r){return JSON.stringify(e??[])===JSON.stringify(r??[])}o(ft,"responseInputsEqual");function pt(e,r){return JSON.stringify(de(e))===JSON.stringify(de(r))}o(pt,"requestBodiesMatchExceptInput");function mt(e,r){if(!pt(e,r.lastRequestBody))return;const t=e.input??[],n=[...r.lastRequestBody.input??[],...r.lastResponseItems];if(t.length<n.length)return;const a=t.slice(0,n.length);if(ft(a,n))return t.slice(n.length)}o(mt,"getCachedWebSocketInputDelta");function yt(e,r){const t=e.continuation;if(!t)return r;const n=mt(r,t);return!n||!t.lastResponseId?(e.continuation=void 0,r):{...r,previous_response_id:t.lastResponseId,input:n}}o(yt,"buildCachedWebSocketRequestBody");async function*bt(e,r){let t=!1;for await(const n of e)t||(t=!0,r()),yield n}o(bt,"startWebSocketOutputOnFirstEvent");async function wt(e,r,t,n,a,s,i,f,c,u,p,d){const{socket:S,entry:l,reused:g,release:y}=await ut(e,t,u,d?.signal,c,d?.env);let m=!0;const C=d?.transport==="websocket-cached"||d?.transport==="auto",b=r,h=C&&l?yt(l,b):b,w=u?J(u):void 0;w&&(w.requests++,g?w.connectionsReused++:w.connectionsCreated++,C&&w.cachedContextRequests++,h.store===!0&&w.storeTrueRequests++,w.lastInputItems=h.input?.length??0,h.previous_response_id?(w.deltaRequests++,w.lastDeltaInputItems=h.input?.length??0,w.lastPreviousResponseId=h.previous_response_id):(w.fullContextRequests++,w.lastDeltaInputItems=void 0,w.lastPreviousResponseId=void 0));try{if(S.send(JSON.stringify({type:"response.create",...h})),await V(bt(oe(lt(S,d?.signal,f)),i),n,a,s,{serviceTier:d?.serviceTier,grammarToolInputProperties:p,resolveServiceTier:re,applyServiceTierPricing:o((v,A)=>te(v,A,s),"applyServiceTierPricing")}),d?.signal?.aborted)m=!1;else if(C&&l&&n.responseId){const v=j(s,{messages:[n]},Y,{includeSystemPrompt:!1,grammarToolInputProperties:p}).filter(A=>A.type!=="function_call_output"&&A.type!=="custom_tool_call_output");l.continuation={lastRequestBody:b,lastResponseId:n.responseId,lastResponseItems:v}}}catch(v){throw l&&(l.continuation=void 0),m=!1,v}finally{y({keep:m})}}o(wt,"processWebSocketStream");async function ht(e){const r=await e.text();let t=r||e.statusText||"Request failed",n;try{const s=JSON.parse(r)?.error;if(s){const i=s.code||s.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(i)||e.status===429){const f=s.plan_type?` (${s.plan_type.toLowerCase()} plan)`:"",c=s.resets_at?Math.max(0,Math.round((s.resets_at*1e3-Date.now())/6e4)):void 0,u=c!==void 0?` Try again in ~${c} min.`:"";n=`You have hit your ChatGPT usage limit${f}.${u}`.trim()}t=s.message||n||t}}catch{}return{message:t,friendlyMessage:n}}o(ht,"parseErrorResponse");function Et(e){try{const r=e.split(".");if(r.length!==3)throw new Error("Invalid token");const n=JSON.parse(atob(r[1]))?.[Ae]?.chatgpt_account_id;if(!n)throw new Error("No account ID in token");return n}catch{throw new Error("Failed to extract accountId from token")}}o(Et,"extractAccountId");function le(e,r,t,n){const a=new Headers(e);for(const[i,f]of Object.entries(r||{}))f===null?a.delete(i):a.set(i,f);a.set("Authorization",`Bearer ${n}`),a.set("chatgpt-account-id",t),a.set("originator","pi");const s=q?`pi (${q.platform()} ${q.release()}; ${q.arch()})`:"pi (browser)";return a.set("User-Agent",s),a}o(le,"buildBaseCodexHeaders");function St(e,r,t,n,a){const s=le(e,r,t,n);return s.set("OpenAI-Beta","responses=experimental"),s.set("accept","text/event-stream"),s.set("content-type","application/json"),a&&(s.set("session-id",a),s.set("x-client-request-id",a)),s}o(St,"buildSSEHeaders");function gt(e,r,t,n,a){const s=le(e,r,t,n);return s.delete("accept"),s.delete("content-type"),s.delete("OpenAI-Beta"),s.delete("openai-beta"),s.set("OpenAI-Beta",tt),s.set("x-client-request-id",a),s.set("session-id",a),s}o(gt,"buildWebSocketHeaders");
|
|
7
|
+
`)}}}finally{r?.removeEventListener("abort",a);try{await t.cancel()}catch{}try{t.releaseLock()}catch{}}}o(tt,"parseSSE");const rt="responses_websockets=2026-02-06",nt=300*1e3,ot=3300*1e3,T=new Map,I=new Map,B=new Set;function J(e){let r=I.get(e);return r||(r={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},I.set(e,r)),r}o(J,"getOrCreateWebSocketDebugStats");export function getOpenAICodexWebSocketDebugStats(e){const r=I.get(e);return r?{...r}:void 0}o(getOpenAICodexWebSocketDebugStats,"getOpenAICodexWebSocketDebugStats");export function resetOpenAICodexWebSocketDebugStats(e){if(e){I.delete(e),B.delete(e);return}I.clear(),B.clear()}o(resetOpenAICodexWebSocketDebugStats,"resetOpenAICodexWebSocketDebugStats");export function closeOpenAICodexWebSocketSessions(e){const r=o(t=>{t.idleTimer&&clearTimeout(t.idleTimer),x(t.socket,1e3,"debug_close")},"closeEntry");if(e){const t=T.get(e);t&&r(t),T.delete(e);return}for(const t of T.values())r(t);T.clear()}o(closeOpenAICodexWebSocketSessions,"closeOpenAICodexWebSocketSessions"),we(closeOpenAICodexWebSocketSessions);function ae(e){return e?B.has(e):!1}o(ae,"isWebSocketSseFallbackActive");function ie(e){if(!e)return;const r=J(e);r.sseFallbacks++,r.websocketFallbackActive=ae(e)}o(ie,"recordWebSocketSseFallback");function st(e,r){if(!e)return;B.add(e);const t=J(e);t.websocketFailures++,t.lastWebSocketError=$(r),t.websocketFallbackActive=!0}o(st,"recordWebSocketFailure");let z=null;async function at(e){if(!e&&z)return z;if(typeof process<"u"&&process.versions?.bun){const t=class extends WebSocket{static{o(this,"WebSocketWithProxy")}constructor(n,s){let a={};Array.isArray(s)||typeof s=="string"?a={protocols:s}:a={...s};const i=Re(n.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),e);super(n,{...a,...i?{proxy:i.toString()}:{}})}};return e||(z=t),t}const r=globalThis.WebSocket;return typeof r!="function"?null:r}o(at,"getWebSocketConstructor");class it extends Error{static{o(this,"WebSocketCloseError")}code;reason;wasClean;constructor(r,t){super(r),this.name="WebSocketCloseError",this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}}function ct(e){const r=e.readyState;return typeof r=="number"?r:void 0}o(ct,"getWebSocketReadyState");function P(e){const r=ct(e);return r===void 0||r===1}o(P,"isWebSocketReusable");function ut(e){return Date.now()-e.createdAt>=ot}o(ut,"isWebSocketSessionExpired");function x(e,r=1e3,t="done"){try{e.close(r,t)}catch{}}o(x,"closeWebSocketSilently");function ce(e,r){r.idleTimer&&clearTimeout(r.idleTimer),r.idleTimer=setTimeout(()=>{r.busy||(x(r.socket,1e3,"idle_timeout"),T.delete(e))},nt)}o(ce,"scheduleSessionWebSocketExpiry");async function H(e,r,t,n=De,s){const a=await at(s);if(!a)throw new Error("WebSocket transport is not available in this runtime");const i=K(r);return delete i["OpenAI-Beta"],new Promise((f,c)=>{let u=!1,p,d;try{d=new a(e,{headers:i})}catch(b){c(b instanceof Error?b:new Error(String(b)));return}const S=o(()=>{p&&(clearTimeout(p),p=void 0),d.removeEventListener("open",g),d.removeEventListener("error",y),d.removeEventListener("close",m),t?.removeEventListener("abort",C)},"cleanup"),l=o((b,h)=>{u||(u=!0,S(),h&&x(d,1e3,h),c(b))},"fail"),g=o(()=>{u||(u=!0,S(),f(d))},"onOpen"),y=o(b=>{l(ue(b))},"onError"),m=o(b=>{l(de(b))},"onClose"),C=o(()=>{l(new Error("Request was aborted"),"aborted")},"onAbort");d.addEventListener("open",g),d.addEventListener("error",y),d.addEventListener("close",m),t?.addEventListener("abort",C),n>0&&(p=setTimeout(()=>{l(new Error(`WebSocket connect timeout after ${n}ms`),"connect_timeout")},n)),t?.aborted&&C()})}o(H,"connectWebSocket");async function dt(e,r,t,n,s,a){if(!t){const u=await H(e,r,n,s,a);return{socket:u,reused:!1,release:o(()=>x(u),"release")}}const i=T.get(t);if(i){if(i.idleTimer&&(clearTimeout(i.idleTimer),i.idleTimer=void 0),!i.busy&&ut(i))x(i.socket,1e3,"connection_age_limit"),T.delete(t);else if(!i.busy&&P(i.socket))return i.busy=!0,{socket:i.socket,entry:i,reused:!0,release:o(({keep:u}={})=>{if(!u||!P(i.socket)){x(i.socket),T.delete(t);return}i.busy=!1,ce(t,i)},"release")};if(i.busy){const u=await H(e,r,n,s,a);return{socket:u,reused:!1,release:o(()=>{x(u)},"release")}}P(i.socket)||(x(i.socket),T.delete(t))}const f=await H(e,r,n,s,a),c={socket:f,busy:!0,createdAt:Date.now()};return T.set(t,c),{socket:f,entry:c,reused:!1,release:o(({keep:u}={})=>{if(!u||!P(c.socket)){x(c.socket),c.idleTimer&&clearTimeout(c.idleTimer),T.get(t)===c&&T.delete(t);return}c.busy=!1,ce(t,c)},"release")}}o(dt,"acquireWebSocket");function ue(e){if(e&&typeof e=="object"){const r="message"in e?e.message:void 0;if(typeof r=="string"&&r.length>0)return new Error(r);const t="error"in e?e.error:void 0;if(t instanceof Error&&t.message.length>0)return t;if(t&&typeof t=="object"&&"message"in t){const n=t.message;if(typeof n=="string"&&n.length>0)return new Error(n)}}return new Error("WebSocket error")}o(ue,"extractWebSocketError");function de(e){if(e&&typeof e=="object"){const r="code"in e?e.code:void 0,t="reason"in e?e.reason:void 0,n="wasClean"in e?e.wasClean:void 0,s=typeof r=="number"?` ${r}`:"";let a=typeof t=="string"&&t.length>0?` ${t}`:"";return!a&&r===Ie&&(a=" message too big"),new it(`WebSocket closed${s}${a}`.trim(),{code:typeof r=="number"?r:void 0,reason:typeof t=="string"&&t.length>0?t:void 0,wasClean:typeof n=="boolean"?n:void 0})}return new Error("WebSocket closed")}o(de,"extractWebSocketCloseError");async function lt(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){const r=e;return new TextDecoder().decode(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}if(e&&typeof e=="object"&&"arrayBuffer"in e){const t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}o(lt,"decodeWebSocketData");async function*ft(e,r,t){const n=[];let s=null,a=!1,i=null,f=!1;const c=o(()=>{if(!s)return;const l=s;s=null,l()},"wake"),u=o(l=>{(async()=>{let g=null;try{if(!l||typeof l!="object"||!("data"in l)||(g=await lt(l.data),!g))return;const y=JSON.parse(g),m=typeof y.type=="string"?y.type:"";(m==="response.completed"||m==="response.done"||m==="response.incomplete")&&(f=!0,a=!0),n.push(y),c()}catch(y){i=new U(`Invalid Codex WebSocket JSON: ${$(y)}`,{cause:y,payload:g}),a=!0,c()}})()},"onMessage"),p=o(l=>{i=ue(l),a=!0,c()},"onError"),d=o(l=>{if(f){a=!0,c();return}i||(i=de(l)),a=!0,c()},"onClose"),S=o(()=>{i=new Error("Request was aborted"),a=!0,c()},"onAbort");e.addEventListener("message",u),e.addEventListener("error",p),e.addEventListener("close",d),r?.addEventListener("abort",S);try{for(;;){if(r?.aborted)throw new Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(a)break;let l;await new Promise((g,y)=>{s=g,t!==void 0&&t>0&&(l=setTimeout(()=>{const m=new Error(`WebSocket idle timeout after ${t}ms`);i=m,a=!0,s=null,x(e,1e3,"idle_timeout"),y(m)},t))}).finally(()=>{l&&clearTimeout(l)})}if(i)throw i;if(!f)throw new Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",u),e.removeEventListener("error",p),e.removeEventListener("close",d),r?.removeEventListener("abort",S)}}o(ft,"parseWebSocket");function le(e){const{input:r,previous_response_id:t,...n}=e;return n}o(le,"requestBodyWithoutInput");function pt(e,r){return JSON.stringify(e??[])===JSON.stringify(r??[])}o(pt,"responseInputsEqual");function mt(e,r){return JSON.stringify(le(e))===JSON.stringify(le(r))}o(mt,"requestBodiesMatchExceptInput");function yt(e,r){if(!mt(e,r.lastRequestBody))return;const t=e.input??[],n=[...r.lastRequestBody.input??[],...r.lastResponseItems];if(t.length<n.length)return;const s=t.slice(0,n.length);if(pt(s,n))return t.slice(n.length)}o(yt,"getCachedWebSocketInputDelta");function bt(e,r){const t=e.continuation;if(!t)return r;const n=yt(r,t);return!n||!t.lastResponseId?(e.continuation=void 0,r):{...r,previous_response_id:t.lastResponseId,input:n}}o(bt,"buildCachedWebSocketRequestBody");async function*wt(e,r){let t=!1;for await(const n of e)t||(t=!0,r()),yield n}o(wt,"startWebSocketOutputOnFirstEvent");async function ht(e,r,t,n,s,a,i,f,c,u,p,d){const{socket:S,entry:l,reused:g,release:y}=await dt(e,t,u,d?.signal,c,d?.env);let m=!0;const C=d?.transport==="websocket-cached"||d?.transport==="auto",b=r,h=C&&l?bt(l,b):b,w=u?J(u):void 0;w&&(w.requests++,g?w.connectionsReused++:w.connectionsCreated++,C&&w.cachedContextRequests++,h.store===!0&&w.storeTrueRequests++,w.lastInputItems=h.input?.length??0,h.previous_response_id?(w.deltaRequests++,w.lastDeltaInputItems=h.input?.length??0,w.lastPreviousResponseId=h.previous_response_id):(w.fullContextRequests++,w.lastDeltaInputItems=void 0,w.lastPreviousResponseId=void 0));try{if(S.send(JSON.stringify({type:"response.create",...h})),await V(wt(se(ft(S,d?.signal,f)),i),n,s,a,{serviceTier:d?.serviceTier,grammarToolInputProperties:p,resolveServiceTier:ne,applyServiceTierPricing:o((v,A)=>re(v,A,a),"applyServiceTierPricing")}),d?.signal?.aborted)m=!1;else if(C&&l&&n.responseId){const v=j(a,{messages:[n]},Y,{includeSystemPrompt:!1,grammarToolInputProperties:p}).filter(A=>A.type!=="function_call_output"&&A.type!=="custom_tool_call_output");l.continuation={lastRequestBody:b,lastResponseId:n.responseId,lastResponseItems:v}}}catch(v){throw l&&(l.continuation=void 0),m=!1,v}finally{y({keep:m})}}o(ht,"processWebSocketStream");async function Et(e){const r=await e.text();let t=r||e.statusText||"Request failed",n;try{const a=JSON.parse(r)?.error;if(a){const i=a.code||a.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(i)||e.status===429){const f=a.plan_type?` (${a.plan_type.toLowerCase()} plan)`:"",c=a.resets_at?Math.max(0,Math.round((a.resets_at*1e3-Date.now())/6e4)):void 0,u=c!==void 0?` Try again in ~${c} min.`:"";n=`You have hit your ChatGPT usage limit${f}.${u}`.trim()}t=a.message||n||t}}catch{}return{message:t,friendlyMessage:n}}o(Et,"parseErrorResponse");function St(e){try{const r=e.split(".");if(r.length!==3)throw new Error("Invalid token");const n=JSON.parse(atob(r[1]))?.[We]?.chatgpt_account_id;if(!n)throw new Error("No account ID in token");return n}catch{throw new Error("Failed to extract accountId from token")}}o(St,"extractAccountId");function fe(e,r,t,n){const s=new Headers(e);for(const[i,f]of Object.entries(r||{}))f===null?s.delete(i):s.set(i,f);s.set("Authorization",`Bearer ${n}`),s.set("chatgpt-account-id",t),s.set("originator","pi");const a=q?`pi (${q.platform()} ${q.release()}; ${q.arch()})`:"pi (browser)";return s.set("User-Agent",a),s}o(fe,"buildBaseCodexHeaders");function gt(e,r,t,n,s){const a=fe(e,r,t,n);return a.set("OpenAI-Beta","responses=experimental"),a.set("accept","text/event-stream"),a.set("content-type","application/json"),s&&(a.set("session-id",s),a.set("x-client-request-id",s)),a}o(gt,"buildSSEHeaders");function _t(e,r,t,n,s){const a=fe(e,r,t,n);return a.delete("accept"),a.delete("content-type"),a.delete("OpenAI-Beta"),a.delete("openai-beta"),a.set("OpenAI-Beta",rt),a.set("x-client-request-id",s),a.set("session-id",s),a}o(_t,"buildWebSocketHeaders");
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var ee=Object.defineProperty;var
|
|
2
|
-
${
|
|
1
|
+
var ee=Object.defineProperty;var f=(e,n)=>ee(e,"name",{value:n,configurable:!0});import te from"openai";import{calculateCost as ne,clampThinkingLevel as re}from"../models.js";import{formatProviderError as se,normalizeProviderError as oe}from"../utils/error-body.js";import{AssistantMessageEventStream as ie}from"../utils/event-stream.js";import{shortHash as ae}from"../utils/hash.js";import{headersToRecord as fe}from"../utils/headers.js";import{parseStreamingJson as N}from"../utils/json-parse.js";import{getProviderEnvValue as ue}from"../utils/provider-env.js";import{retryProviderRequest as le}from"../utils/provider-retry.js";import{sanitizeSurrogates as S}from"../utils/sanitize-unicode.js";import{appendGrammarToolInputJsonDelta as ce,createGrammarToolInputProperties as z,getGrammarToolInput as pe,resolveGrammarConstrainedSampling as ge,resolveJsonSchemaStrictSampling as de}from"./constrained-sampling.js";import{buildCopilotDynamicHeaders as he,hasCopilotVisionInput as me}from"./github-copilot-headers.js";import{clampOpenAIPromptCacheKey as ye}from"./openai-prompt-cache.js";import{buildBaseOptions as ke}from"./simple-options.js";import{transformMessages as Re}from"./transform-messages.js";function G(e,n){if(!e)return!1;const t=n.toLowerCase();for(const[r,s]of Object.entries(e))if(r.toLowerCase()===t&&s!==null&&s.trim().length>0)return!0;return!1}f(G,"hasHeader");function j(e,n,t){if(n)return n;if(G(t,"authorization")||G(t,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${e}`)}f(j,"getClientApiKey");function Te(e){for(const n of e)if(n.role==="toolResult"||n.role==="assistant"&&n.content.some(t=>t.type==="toolCall"))return!0;return!1}f(Te,"hasToolHistory");function _e(e){const n=new Set;for(const t of e)if(t.role==="toolResult")for(const r of t.addedToolNames??[])n.add(r);return n}f(_e,"getDeferredToolNames");function xe(e,n){if(!e)return[];const t=new Map(e.map(r=>[r.name,r]));return Array.from(n).map(r=>t.get(r)).filter(r=>r!==void 0)}f(xe,"getToolsByName");function K(e){return e.type==="text"}f(K,"isTextContentBlock");function ve(e){return e.type==="thinking"}f(ve,"isThinkingContentBlock");function Ae(e){return e.type==="toolCall"}f(Ae,"isToolCallBlock");function Ce(e){return e.type==="image"}f(Ce,"isImageContentBlock");function Me(e){if(typeof e!="object"||e===null)return!1;const n=e;return n.type==="reasoning.encrypted"&&typeof n.id=="string"&&n.id.length>0&&typeof n.data=="string"&&n.data.length>0}f(Me,"isEncryptedReasoningDetail");function $(e,n){return e||(ue("PI_CACHE_RETENTION",n)==="long"?"long":"short")}f($,"resolveCacheRetention");export const stream=f((e,n,t)=>{const r=new ie;return(async()=>{const s={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{const d=j(e.provider,t?.apiKey,t?.headers),c=q(e),p=z(n.tools,c.supportsOpenAIGrammarTools),i=$(t?.cacheRetention,t?.env),h=i==="none"?void 0:t?.sessionId,l=Ie(e,n,d,t?.headers,t?.fetch,h,c);let a=we(e,n,t,c,i,p);const k=await t?.onPayload?.(a,e);k!==void 0&&(a=k);const R={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:A,response:M}=await le(()=>l.chat.completions.create(a,R).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:M.status,headers:fe(M.headers)},e),r.push({type:"start",partial:s});let I=null,y=null,T=!1;const v=new Map,O=new Map,L=new Map,b=s.content,E=f(o=>b.indexOf(o),"getContentIndex"),B=f(o=>{const u=o.customInput?.property;if(u===void 0)return"";const x=o.arguments[u];return typeof x=="string"?x:""},"getCustomToolCallInput"),D=f((o,u,x)=>{const g=o.customInput;if(!g)return;const C=ce(g.jsonBuffer,g.property,u,x);return o.arguments={[g.property]:u},C},"appendCustomToolCallInput"),J=f(o=>{const u=E(o);if(u!==-1){if(o.type==="text")r.push({type:"text_end",contentIndex:u,content:o.text,partial:s});else if(o.type==="thinking")r.push({type:"thinking_end",contentIndex:u,content:o.thinking,partial:s});else if(o.type==="toolCall"){if(o.customInput){const x=D(o,B(o),!0);x!==void 0&&r.push({type:"toolcall_delta",contentIndex:u,delta:x,partial:s})}else o.arguments=N(o.partialArgs);delete o.partialArgs,delete o.customInput,delete o.streamIndex,r.push({type:"toolcall_end",contentIndex:u,toolCall:o,partial:s})}}},"finishBlock"),V=f(()=>(I||(I={type:"text",text:""},b.push(I),r.push({type:"text_start",contentIndex:E(I),partial:s})),I),"ensureTextBlock"),Z=f(o=>(y||(y={type:"thinking",thinking:"",thinkingSignature:o},b.push(y),r.push({type:"thinking_start",contentIndex:E(y),partial:s})),y),"ensureThinkingBlock"),Q=f(o=>{if(!o.id)return;const u=L.get(o.id);u&&(o.thoughtSignature=u,L.delete(o.id))},"applyPendingReasoningDetail"),X=f(o=>{const u=typeof o.index=="number"?o.index:void 0,x=o.function?.name??o.custom?.name??"";let g=u!==void 0?v.get(u):void 0;if(!g&&o.id&&(g=O.get(o.id)),!g){const C=o.custom&&!o.function?p.get(x)??"input":void 0,F=C!==void 0;g={type:"toolCall",id:o.id||"",name:x,arguments:F?{[C]:""}:{},partialArgs:F?void 0:"",customInput:F?{property:C,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex:u},u!==void 0&&v.set(u,g),o.id&&O.set(o.id,g),b.push(g),r.push({type:"toolcall_start",contentIndex:E(g),partial:s})}if(u!==void 0&&g.streamIndex===void 0&&(g.streamIndex=u,v.set(u,g)),o.id&&O.set(o.id,g),!g.name&&x&&(g.name=x),o.custom&&!o.function&&!g.customInput){const C=p.get(g.name)??"input";g.arguments={[C]:""},g.customInput={property:C,jsonBuffer:{input:"",started:!1,closed:!1}},delete g.partialArgs}return Q(g),g},"ensureToolCallBlock");for await(const o of A){if(!o||typeof o!="object")continue;s.responseId||=o.id,typeof o.model=="string"&&o.model.length>0&&o.model!==e.id&&(s.responseModel||=o.model),o.usage&&(s.usage=U(o.usage,e));const u=Array.isArray(o.choices)?o.choices[0]:void 0;if(u){if(!o.usage&&u.usage&&(s.usage=U(u.usage,e)),u.finish_reason){s.rawStopReason=u.finish_reason;const x=De(u.finish_reason);s.stopReason=x.stopReason,x.errorMessage&&(s.errorMessage=x.errorMessage),T=!0}if(u.delta){if(u.delta.content!==null&&u.delta.content!==void 0&&u.delta.content.length>0){const m=V();m.text+=u.delta.content,r.push({type:"text_delta",contentIndex:E(m),delta:u.delta.content,partial:s})}const x=["reasoning_content","reasoning","reasoning_text"],g=u.delta;let C=null;for(const m of x){const _=g[m];if(typeof _=="string"&&_.length>0){C=m;break}}if(C){const m=g[C];if(typeof m=="string"&&m.length>0){const _=e.provider==="opencode-go"&&C==="reasoning"?"reasoning_content":C,w=Z(_);w.thinking+=m,r.push({type:"thinking_delta",contentIndex:E(w),delta:m,partial:s})}}if(u?.delta?.tool_calls)for(const m of u.delta.tool_calls){const _=X(m);!_.id&&m.id&&(_.id=m.id,O.set(m.id,_));const w=m.function?.name??m.custom?.name;!_.name&&w&&(_.name=w);let P="";if(m.function?.arguments)P=m.function.arguments,_.partialArgs=(_.partialArgs??"")+m.function.arguments,_.arguments=N(_.partialArgs);else if(m.custom?.input){const Y=B(_)+m.custom.input;P=D(_,Y,!1)??""}r.push({type:"toolcall_delta",contentIndex:E(_),delta:P,partial:s})}const F=u.delta.reasoning_details;if(Array.isArray(F)){for(const m of F)if(Me(m)){const _=JSON.stringify(m),w=O.get(m.id);w?w.thoughtSignature=_:L.set(m.id,_)}}}}}for(const o of b)J(o);if(t?.signal?.aborted)throw new Error("Request was aborted");if(s.stopReason==="aborted")throw new Error("Request was aborted");if(s.stopReason==="error")throw new Error(s.errorMessage||"Provider returned an error stop reason");if(!T||s.stopReason==="pending")throw new Error("Stream ended without finish_reason");r.push({type:"done",reason:s.stopReason,message:s}),r.end()}catch(d){for(const p of s.content)delete p.index,delete p.partialArgs,delete p.customInput,delete p.streamIndex;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=se(oe(d));const c=d?.error?.metadata?.raw;c&&!s.errorMessage.includes(String(c))&&(s.errorMessage+=`
|
|
2
|
+
${c}`),r.push({type:"error",reason:s.stopReason,error:s}),r.end()}})(),r},"stream"),streamSimple=f((e,n,t)=>{j(e.provider,t?.apiKey,t?.headers);const r=ke(e,n,t,t?.apiKey),s=t?.reasoning?re(e,t.reasoning):void 0,d=s==="off"?void 0:s,c=t?.toolChoice;return stream(e,n,{...r,reasoningEffort:d,toolChoice:c})},"streamSimple");function Ie(e,n,t,r,s,d,c=q(e)){const p={...e.headers};if(e.provider==="github-copilot"){const i=me(n.messages),h=he({messages:n.messages,hasImages:i});Object.assign(p,h)}return d&&c.sendSessionAffinityHeaders&&(c.sessionAffinityFormat==="openrouter"?p["x-session-id"]=d:(c.sessionAffinityFormat==="openai"&&(p.session_id=d),p["x-client-request-id"]=d,p["x-session-affinity"]=d)),r&&Object.assign(p,r),new te({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:s,defaultHeaders:p})}f(Ie,"createClient");function we(e,n,t,r=q(e),s=$(t?.cacheRetention,t?.env),d=z(n.tools,r.supportsOpenAIGrammarTools)){const c=convertMessages(e,n,r,{grammarToolInputProperties:d}),p=Fe(r,s),i={model:e.id,messages:c,stream:!0,prompt_cache_key:e.baseUrl.includes("api.openai.com")&&s!=="none"||s==="long"&&r.supportsLongCacheRetention?ye(t?.sessionId):void 0,prompt_cache_retention:s==="long"&&r.supportsLongCacheRetention?"24h":void 0};r.supportsUsageInStreaming!==!1&&(i.stream_options={include_usage:!0}),r.supportsStore&&(i.store=!1),t?.maxTokens&&(r.maxTokensField==="max_tokens"?i.max_tokens=t.maxTokens:i.max_completion_tokens=t.maxTokens),t?.temperature!==void 0&&(i.temperature=t.temperature);const h=r.deferredToolsMode==="kimi"?_e(n.messages):new Set,l=n.tools?.filter(a=>!h.has(a.name));if(l&&l.length>0?(i.tools=W(l,r),r.zaiToolStream&&(i.tool_stream=!0)):Te(n.messages)&&(i.tools=[]),p&&Oe(c,i.tools,p),t?.toolChoice&&(i.tool_choice=t.toolChoice),r.thinkingFormat==="zai"&&e.reasoning){const a=i;if(a.thinking=t?.reasoningEffort?{type:"enabled",clear_thinking:!1}:{type:"disabled"},t?.reasoningEffort&&r.supportsReasoningEffort){const k=e.thinkingLevelMap?.[t.reasoningEffort],R=k===void 0?t.reasoningEffort:k;typeof R=="string"&&(a.reasoning_effort=R)}}else if(r.thinkingFormat==="qwen"&&e.reasoning){if(i.enable_thinking=!!t?.reasoningEffort,t?.reasoningEffort&&r.supportsReasoningEffort){const a=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;typeof a=="string"&&(i.reasoning_effort=a)}}else if(r.thinkingFormat==="qwen-chat-template"&&e.reasoning)i.chat_template_kwargs={enable_thinking:!!t?.reasoningEffort,preserve_thinking:!0};else if(r.thinkingFormat==="chat-template"&&e.reasoning){const a=Ee(e,t,r);a&&(i.chat_template_kwargs=a)}else if(r.thinkingFormat==="deepseek"&&e.reasoning)t?.reasoningEffort?i.thinking={type:"enabled"}:e.thinkingLevelMap?.off!==null&&(i.thinking={type:"disabled"}),t?.reasoningEffort&&r.supportsReasoningEffort&&(i.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort);else if(r.thinkingFormat==="openrouter"&&e.reasoning){const a=i;t?.reasoningEffort?a.reasoning={effort:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}:e.thinkingLevelMap?.off!==null&&(a.reasoning={effort:e.thinkingLevelMap?.off??"none"})}else if(r.thinkingFormat==="ant-ling"&&e.reasoning&&t?.reasoningEffort){const a=e.thinkingLevelMap?.[t.reasoningEffort];typeof a=="string"&&(i.reasoning={effort:a})}else if(r.thinkingFormat==="together"&&e.reasoning){const a=i;a.reasoning={enabled:!!t?.reasoningEffort},t?.reasoningEffort&&r.supportsReasoningEffort&&(a.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort)}else if(r.thinkingFormat==="string-thinking"&&e.reasoning){const a=i;t?.reasoningEffort?a.thinking=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort:e.thinkingLevelMap?.off!==null&&(a.thinking=e.thinkingLevelMap?.off??"none")}else if(t?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort)i.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;else if(!t?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort){const a=e.thinkingLevelMap?.off;typeof a=="string"&&(i.reasoning_effort=a)}if(e.compat?.openRouterRouting&&(i.provider=e.compat.openRouterRouting),e.compat?.vercelGatewayRouting){const a=e.compat.vercelGatewayRouting;if(a.only||a.order){const k={};a.only&&(k.only=a.only),a.order&&(k.order=a.order),i.providerOptions={gateway:k}}}return i}f(we,"buildParams");function Ee(e,n,t){const r={};for(const[s,d]of Object.entries(t.chatTemplateKwargs)){const c=Se(e,n,d);c!==void 0&&(r[s]=c)}return Object.keys(r).length>0?r:void 0}f(Ee,"buildChatTemplateKwargs");function Se(e,n,t){if(typeof t!="object"||t===null)return t;const r=n?.reasoningEffort;if(!r&&t.omitWhenOff)return;if(t.$var==="thinking.enabled")return!!r;const s=r?e.thinkingLevelMap?.[r]:e.thinkingLevelMap?.off;return s===void 0?r:typeof s=="string"?s:void 0}f(Se,"resolveChatTemplateKwargValue");function Fe(e,n){if(e.cacheControlFormat!=="anthropic"||n==="none")return;const t=n==="long"&&e.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...t?{ttl:t}:{}}}f(Fe,"getCompatCacheControl");function Oe(e,n,t){be(e,t),Pe(n,t),Le(e,t)}f(Oe,"applyAnthropicCacheControl");function be(e,n){for(const t of e)if(t.role==="system"||t.role==="developer"){qe(t,n);return}}f(be,"addCacheControlToSystemPrompt");function Le(e,n){for(let t=e.length-1;t>=0;t--){const r=e[t];if((r.role==="user"||r.role==="assistant"||r.role==="tool")&&Be(r,n))return}}f(Le,"addCacheControlToLastConversationMessage");function Pe(e,n){if(!e||e.length===0)return;const t=e[e.length-1];t.cache_control=n}f(Pe,"addCacheControlToLastTool");function qe(e,n){return H(e,n)}f(qe,"addCacheControlToInstructionMessage");function Be(e,n){return e.role==="user"||e.role==="assistant"||e.role==="tool"?H(e,n):!1}f(Be,"addCacheControlToMessage");function H(e,n){const t=e.content;if(typeof t=="string")return t.length===0?!1:(e.content=[{type:"text",text:t,cache_control:n}],!0);if(!Array.isArray(t))return!1;for(let r=t.length-1;r>=0;r--){const s=t[r];if(s?.type==="text"){const d=s;return d.cache_control=n,!0}}return!1}f(H,"addCacheControlToTextContent");export function convertMessages(e,n,t,r){const s=[],d=f(i=>{if(i.includes("|")){const h=i.indexOf("|"),l=i.slice(0,h).replace(/[^a-zA-Z0-9_-]/g,"_"),a=i.slice(h+1).replace(/[^a-zA-Z0-9_-]/g,"_"),k=a.length>0?`${l}_${a}`:l;if(k.length<=40)return k;const R=ae(i).slice(0,8);return`${l.slice(0,Math.max(1,40-R.length-1))}_${R}`}return e.provider==="openai"&&i.length>40?i.slice(0,40):i},"normalizeToolCallId"),c=Re(n.messages,e,i=>d(i));if(n.systemPrompt){const h=e.reasoning&&t.supportsDeveloperRole?"developer":"system";s.push({role:h,content:S(n.systemPrompt)})}let p=null;for(let i=0;i<c.length;i++){const h=c[i];if(t.requiresAssistantAfterToolResult&&p==="toolResult"&&h.role==="user"&&s.push({role:"assistant",content:"I have processed the tool results."}),h.role==="user")if(typeof h.content=="string")s.push({role:"user",content:S(h.content)});else{const l=h.content.map(a=>a.type==="text"?{type:"text",text:S(a.text)}:{type:"image_url",image_url:{url:`data:${a.mimeType};base64,${a.data}`}});if(l.length===0)continue;s.push({role:"user",content:l})}else if(h.role==="assistant"){const l={role:"assistant",content:t.requiresAssistantAfterToolResult?"":null},a=h.content.filter(K).filter(y=>y.text.trim().length>0).map(y=>({type:"text",text:S(y.text)})),k=a.map(y=>y.text).join(""),R=h.content.filter(ve).filter(y=>y.thinking.trim().length>0);if(R.length>0)if(t.requiresThinkingAsText){const y=R.map(T=>S(T.thinking)).join(`
|
|
3
3
|
|
|
4
|
-
`);
|
|
5
|
-
`))}else
|
|
6
|
-
`),M=
|
|
4
|
+
`);l.content=[{type:"text",text:y},...a]}else{k.length>0&&(l.content=k);let y=R[0].thinkingSignature;e.provider==="opencode-go"&&y==="reasoning"&&(y="reasoning_content"),y&&y.length>0&&(l[y]=R.map(T=>T.thinking).join(`
|
|
5
|
+
`))}else k.length>0&&(l.content=k);const A=h.content.filter(Ae);if(A.length>0){l.tool_calls=A.map(T=>{const v=r?.grammarToolInputProperties?.get(T.name);return v!==void 0?{id:T.id,type:"custom",custom:{name:T.name,input:S(pe(T.name,T.arguments,v))}}:{id:T.id,type:"function",function:{name:T.name,arguments:JSON.stringify(T.arguments)}}});const y=A.filter(T=>T.thoughtSignature).map(T=>{try{return JSON.parse(T.thoughtSignature)}catch{return null}}).filter(Boolean);y.length>0&&(l.reasoning_details=y)}t.requiresReasoningContentOnAssistantMessages&&e.reasoning&&l.reasoning_content===void 0&&(l.reasoning_content="");const M=l.content;if(!(M!=null&&M.length>0)&&!l.tool_calls)continue;s.push(l)}else if(h.role==="toolResult"){const l=[],a=new Set;let k=i;for(;k<c.length&&c[k].role==="toolResult";k++){const R=c[k],A=R.content.filter(K).map(v=>v.text).join(`
|
|
6
|
+
`),M=R.content.some(v=>v.type==="image"),y=A.length>0?A:M?"(see attached image)":"(no tool output)",T={role:"tool",content:S(y),tool_call_id:R.toolCallId};if(t.requiresToolResultName&&R.toolName&&(T.name=R.toolName),s.push(T),t.deferredToolsMode==="kimi")for(const v of R.addedToolNames??[])a.add(v);if(M&&e.input.includes("image"))for(const v of R.content)Ce(v)&&l.push({type:"image_url",image_url:{url:`data:${v.mimeType};base64,${v.data}`}})}if(i=k-1,l.length>0?(t.requiresAssistantAfterToolResult&&s.push({role:"assistant",content:"I have processed the tool results."}),s.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...l]}),p="user"):p="toolResult",a.size>0){const R=xe(n.tools,a);if(R.length>0){const A={role:"system",tools:W(R,t)};s.push(A)}}continue}p=h.role}return s}f(convertMessages,"convertMessages");function W(e,n){return e.map(t=>{const r=ge(t,n.supportsOpenAIGrammarTools);if(r)return{type:"custom",custom:{name:t.name,description:t.description,format:{type:"grammar",grammar:{syntax:r.format,definition:r.definition}}}};const s=de(t,n.supportsStrictMode!==!1);return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters,...n.supportsStrictMode!==!1&&{strict:s??!1}}}})}f(W,"convertTools");function U(e,n){const t=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??0,s=e.prompt_tokens_details?.cache_write_tokens||0,d=Math.max(0,t-r-s),c=e.completion_tokens||0,p={input:d,output:c,cacheRead:r,cacheWrite:s,reasoning:e.completion_tokens_details?.reasoning_tokens||0,totalTokens:d+c+r+s,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return ne(n,p),p}f(U,"parseChunkUsage");function De(e){if(e===null)return{stopReason:"stop"};switch(e){case"stop":case"end":return{stopReason:"stop"};case"length":return{stopReason:"length"};case"function_call":case"tool_calls":return{stopReason:"toolUse"};case"content_filter":return{stopReason:"error",errorMessage:"Provider finish_reason: content_filter"};case"network_error":return{stopReason:"error",errorMessage:"Provider finish_reason: network_error"};default:return{stopReason:"error",errorMessage:`Provider finish_reason: ${e}`}}}f(De,"mapStopReason");function Ne(e){const n=e.provider,t=e.baseUrl,r=n==="zai"||n==="zai-coding-cn"||t.includes("api.z.ai")||t.includes("open.bigmodel.cn"),s=n==="together"||t.includes("api.together.ai")||t.includes("api.together.xyz"),d=n==="moonshotai"||n==="moonshotai-cn"||t.includes("api.moonshot."),c=n==="openrouter"||t.includes("openrouter.ai"),p=n==="cloudflare-workers-ai"||t.includes("api.cloudflare.com"),i=n==="cloudflare-ai-gateway"||t.includes("gateway.ai.cloudflare.com"),h=n==="nvidia"||t.includes("integrate.api.nvidia.com"),l=n==="ant-ling"||t.includes("api.ant-ling.com"),a=h||n==="cerebras"||t.includes("cerebras.ai")||n==="xai"||t.includes("api.x.ai")||s||t.includes("chutes.ai")||t.includes("deepseek.com")||r||d||n==="opencode"||t.includes("opencode.ai")||p||i||l,k=t.includes("chutes.ai")||d||i||s||h||l||r,R=n==="xai"||t.includes("api.x.ai"),A=n==="deepseek"||t.includes("deepseek.com"),M=c&&(e.id.startsWith("anthropic/")||e.id.startsWith("openai/")),I=n==="openrouter"&&e.id.startsWith("anthropic/")?"anthropic":void 0;return{supportsStore:!a,supportsDeveloperRole:M||!a&&!c,supportsReasoningEffort:!R&&!r&&!d&&!s&&!i&&!h&&!l,supportsUsageInStreaming:!0,maxTokensField:k?"max_tokens":"max_completion_tokens",requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:A,thinkingFormat:A?"deepseek":r?"zai":s?"together":l?"ant-ling":c?"openrouter":"openai",openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},zaiToolStream:!1,supportsStrictMode:!d&&!s&&!i&&!h,supportsOpenAIGrammarTools:!1,cacheControlFormat:I,sendSessionAffinityHeaders:!1,deferredToolsMode:void 0,sessionAffinityFormat:c?"openrouter":"openai",supportsLongCacheRetention:!(s||p||i||h||l)}}f(Ne,"detectCompat");function q(e){const n=Ne(e);return e.compat?{supportsStore:e.compat.supportsStore??n.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??n.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??n.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??n.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??n.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??n.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??n.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??n.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??n.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??n.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??n.vercelGatewayRouting,chatTemplateKwargs:e.compat.chatTemplateKwargs??n.chatTemplateKwargs,zaiToolStream:e.compat.zaiToolStream??n.zaiToolStream,supportsStrictMode:e.compat.supportsStrictMode??n.supportsStrictMode,supportsOpenAIGrammarTools:e.compat.supportsOpenAIGrammarTools??n.supportsOpenAIGrammarTools,cacheControlFormat:e.compat.cacheControlFormat??n.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??n.sendSessionAffinityHeaders,deferredToolsMode:e.compat.deferredToolsMode??n.deferredToolsMode,sessionAffinityFormat:e.compat.sessionAffinityFormat??n.sessionAffinityFormat,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??n.supportsLongCacheRetention}:n}f(q,"getCompat");
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),u=o.filter(l=>l.type==="image"),p=
|
|
1
|
+
var R=Object.defineProperty;var d=(a,o)=>R(a,"name",{value:o,configurable:!0});import{calculateCost as J}from"../models.js";import{shortHash as v}from"../utils/hash.js";import{parseStreamingJson as C}from"../utils/json-parse.js";import{sanitizeSurrogates as k}from"../utils/sanitize-unicode.js";import{appendGrammarToolInputJsonDelta as P,getGrammarToolInput as M,resolveGrammarConstrainedSampling as O,resolveJsonSchemaStrictSampling as z}from"./constrained-sampling.js";import{transformMessages as N}from"./transform-messages.js";function j(a,o){const i={v:1,id:a};return o&&(i.phase=o),JSON.stringify(i)}d(j,"encodeTextSignatureV1");function W(a){if(a){if(a.startsWith("{"))try{const o=JSON.parse(a);if(o.v===1&&typeof o.id=="string")return o.phase==="commentary"||o.phase==="final_answer"?{id:o.id,phase:o.phase}:{id:o.id}}catch{}return{id:a}}}d(W,"parseTextSignature");function B(a,o){const i=o.filter(l=>l.type==="text").map(l=>l.text).join(`
|
|
2
|
+
`),u=o.filter(l=>l.type==="image"),p=i.length>0;if(u.length===0||!a.input.includes("image"))return k(p?i:u.length>0?"(see attached image)":"(no tool output)");const f=[];p&&f.push({type:"input_text",text:k(i)});for(const l of u)f.push({type:"input_image",detail:"auto",image_url:`data:${l.mimeType};base64,${l.data}`});return f}d(B,"convertToolResultOutput");export function convertResponsesMessages(a,o,i,u){const p=[],f=new Set,l=d(r=>{const c=r.replace(/[^a-zA-Z0-9_-]/g,"_");return(c.length>64?c.slice(0,64):c).replace(/_+$/,"")},"normalizeIdPart"),I=d(r=>{const c=`fc_${v(r)}`;return c.length>64?c.slice(0,64):c},"buildForeignResponsesItemId"),x=d((r,c,m)=>{if(!i.has(a.provider)||!r.includes("|"))return l(r);const[t,e]=r.split("|"),n=l(t);let g=m.provider!==a.provider||m.api!==a.api?I(e):l(e);return g.startsWith("fc_")||(g=l(`fc_${g}`)),`${n}|${g}`},"normalizeToolCallId"),_=N(o.messages,a,x);if((u?.includeSystemPrompt??!0)&&o.systemPrompt){const r=a.compat,c=a.reasoning&&r?.supportsDeveloperRole!==!1?"developer":"system";p.push({role:c,content:k(o.systemPrompt)})}let S=0;for(const r of _){if(r.role==="user")if(typeof r.content=="string")p.push({role:"user",content:[{type:"input_text",text:k(r.content)}]});else{const c=r.content.map(m=>m.type==="text"?{type:"input_text",text:k(m.text)}:{type:"input_image",detail:"auto",image_url:`data:${m.mimeType};base64,${m.data}`});if(c.length===0)continue;p.push({role:"user",content:c})}else if(r.role==="assistant"){const c=[],m=r,t=m.model!==a.id&&m.provider===a.provider&&m.api===a.api;let e=0;for(const n of r.content)if(n.type==="thinking"){if(n.thinkingSignature){const s=JSON.parse(n.thinkingSignature);c.push(s)}}else if(n.type==="text"){const s=n,g=W(s.textSignature),h=e===0?`msg_pi_${S}`:`msg_pi_${S}_${e}`;e++;let y=g?.id;y?y.length>64&&(y=`msg_${v(y)}`):y=h,c.push({type:"message",role:"assistant",content:[{type:"output_text",text:k(s.text),annotations:[]}],status:"completed",id:y,phase:g?.phase})}else if(n.type==="toolCall"){const s=n,[g,h]=s.id.split("|"),y=u?.grammarToolInputProperties?.get(s.name);let T=h;(t&&T?.startsWith("fc_")||y===void 0&&!T?.startsWith("fc_"))&&(T=void 0),y!==void 0?c.push({type:"custom_tool_call",id:T,call_id:g,name:s.name,input:k(M(s.name,s.arguments,y))}):c.push({type:"function_call",id:T,call_id:g,name:s.name,arguments:JSON.stringify(s.arguments)})}if(c.length===0)continue;p.push(...c)}else if(r.role==="toolResult"){const[c]=r.toolCallId.split("|"),m=B(a,r.content);u?.grammarToolInputProperties?.has(r.toolName)?p.push({type:"custom_tool_call_output",call_id:c,output:m}):p.push({type:"function_call_output",call_id:c,output:m});const t=[];for(const e of r.addedToolNames??[]){const n=u?.deferredTools?.get(e);!n||f.has(e)||(f.add(e),t.push(n))}if(t.length>0){const e=t.map(s=>s.name),n=`pi_tool_load_${v(`${r.toolCallId}:${e.join(",")}`)}`;p.push({type:"tool_search_call",call_id:n,execution:"client",status:"completed",arguments:{query:e.join(" "),limit:e.length}}),p.push({type:"tool_search_output",call_id:n,execution:"client",status:"completed",tools:convertResponsesTools(t,{...u?.toolOptions,deferLoading:!0})})}}S++}return p}d(convertResponsesMessages,"convertResponsesMessages");export function convertResponsesTools(a,o){const i=o?.strict===void 0?!1:o.strict,u=o?.supportsStrictMode??!0,p=o?.supportsOpenAIGrammarTools??!1;return a.map(f=>{const l=O(f,p);if(l)return{type:"custom",name:f.name,description:f.description,format:{type:"grammar",syntax:l.format,definition:l.definition},...o?.deferLoading?{defer_loading:!0}:{}};const I=z(f,u),x={type:"function",name:f.name,description:f.description,parameters:f.parameters,...o?.deferLoading?{defer_loading:!0}:{}};return u&&(x.strict=I??i),x})}d(convertResponsesTools,"convertResponsesTools");function w(a){const o=a.customInput?.property;if(o===void 0)return"";const i=a.arguments[o];return typeof i=="string"?i:""}d(w,"getCustomToolCallInput");function $(a,o,i){const u=a.customInput;if(!u)return;const p=P(u.jsonBuffer,u.property,o,i);return a.arguments={[u.property]:o},p}d($,"appendCustomToolCallInput");export async function processResponsesStream(a,o,i,u,p){let f=!1;const l=new Map,I=new Map,x=d(t=>{t.type==="message"&&t.phase==="final_answer"&&(o.stopReason="stop")},"applyMessagePhaseStopReason"),_=d((t,e)=>{const n=l.get(t);return n?.type===e?n:void 0},"getSlot"),b=d((t,e)=>{e!==void 0&&i.push({type:"toolcall_delta",contentIndex:t.contentIndex,delta:e,partial:o})},"pushToolCallDelta"),S=d((t,e)=>{if(e.type==="reasoning"){const n={type:"thinking",thinking:""};o.content.push(n);const s={type:"thinking",block:n,contentIndex:o.content.length-1};return l.set(t,s),i.push({type:"thinking_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="message"){x(e);const n={type:"text",text:""};o.content.push(n);const s={type:"text",block:n,contentIndex:o.content.length-1};return l.set(t,s),i.push({type:"text_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="function_call"){const n={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{},partialJson:e.arguments||""};o.content.push(n);const s={type:"toolCall",block:n,contentIndex:o.content.length-1};return l.set(t,s),i.push({type:"toolcall_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="custom_tool_call"){const n=p?.grammarToolInputProperties?.get(e.name)??"input",s=e.input||"",g={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{[n]:s},customInput:{property:n,jsonBuffer:{input:"",started:!1,closed:!1}}};o.content.push(g);const h={type:"toolCall",block:g,contentIndex:o.content.length-1};return l.set(t,h),i.push({type:"toolcall_start",contentIndex:h.contentIndex,partial:o}),h}},"createSlot"),r=d((t,e)=>l.get(t)??S(t,e),"getOrCreateSlot"),c=d(t=>{for(const e of t){if(e.type!=="reasoning"||!e.encrypted_content)continue;const n=I.get(e.id);if(!n?.thinkingSignature)continue;const s=JSON.parse(n.thinkingSignature);s.encrypted_content||(n.thinkingSignature=JSON.stringify({...s,encrypted_content:e.encrypted_content}))}},"backfillReasoningSignatures"),m=d(t=>{if(f=!0,c(t.output??[]),t?.id&&(o.responseId=t.id),t?.usage){const n=t.usage.input_tokens_details,s=n?.cached_tokens||0,g=n?.cache_write_tokens||0;o.usage={input:Math.max(0,(t.usage.input_tokens||0)-s-g),output:t.usage.output_tokens||0,cacheRead:s,cacheWrite:g,reasoning:t.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(J(u,o.usage),p?.applyServiceTierPricing){const n=p.resolveServiceTier?p.resolveServiceTier(t?.service_tier,p.serviceTier):t?.service_tier??p.serviceTier;p.applyServiceTierPricing(o.usage,n)}const e=t?.status;o.rawStopReason=e,o.stopReason=E(e),o.content.some(n=>n.type==="toolCall")&&o.stopReason==="stop"&&(o.stopReason="toolUse")},"finalizeResponse");for await(const t of a)if(t.type==="response.created")o.responseId=t.response.id;else if(t.type==="response.output_item.added")S(t.output_index,t.item);else if(t.type==="response.reasoning_summary_text.delta"){const e=_(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,i.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.reasoning_summary_part.done"){const e=_(t.output_index,"thinking");if(!e)continue;e.block.thinking+=`
|
|
3
3
|
|
|
4
|
-
`,
|
|
4
|
+
`,i.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:`
|
|
5
5
|
|
|
6
|
-
`,partial:o})}else if(t.type==="response.reasoning_text.delta"){const e=_(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,
|
|
6
|
+
`,partial:o})}else if(t.type==="response.reasoning_text.delta"){const e=_(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,i.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.output_text.delta"){const e=_(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,i.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.refusal.delta"){const e=_(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,i.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.function_call_arguments.delta"){const e=_(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;e.block.partialJson+=t.delta,e.block.arguments=C(e.block.partialJson),b(e,t.delta)}else if(t.type==="response.function_call_arguments.done"){const e=_(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;const n=e.block.partialJson;if(e.block.partialJson=t.arguments,e.block.arguments=C(e.block.partialJson),t.arguments.startsWith(n)){const s=t.arguments.slice(n.length);s.length>0&&b(e,s)}}else if(t.type==="response.custom_tool_call_input.delta"){const e=_(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;b(e,$(e.block,w(e.block)+t.delta,!1))}else if(t.type==="response.custom_tool_call_input.done"){const e=_(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;b(e,$(e.block,t.input,!0))}else if(t.type==="response.output_item.done"){const e=t.item;x(e);const n=r(t.output_index,e);if(e.type==="reasoning"&&n?.type==="thinking"){const s=e.summary?.map(h=>h.text).join(`
|
|
7
7
|
|
|
8
|
-
`)||"",
|
|
8
|
+
`)||"",g=e.content?.map(h=>h.text).join(`
|
|
9
9
|
|
|
10
|
-
`)||"";n.block.thinking=s||
|
|
10
|
+
`)||"";n.block.thinking=s||g||n.block.thinking,n.block.thinkingSignature=JSON.stringify(e),I.set(e.id,n.block),i.push({type:"thinking_end",contentIndex:n.contentIndex,content:n.block.thinking,partial:o}),l.delete(t.output_index)}else e.type==="message"&&n?.type==="text"?(n.block.text=e.content?.map(s=>s.type==="output_text"?s.text:s.refusal).join("")||"",n.block.textSignature=j(e.id,e.phase??void 0),i.push({type:"text_end",contentIndex:n.contentIndex,content:n.block.text,partial:o}),l.delete(t.output_index)):e.type==="function_call"&&n?.type==="toolCall"&&n.block.partialJson!==void 0?(n.block.arguments=C(e.arguments||n.block.partialJson||"{}"),delete n.block.partialJson,i.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),l.delete(t.output_index)):e.type==="custom_tool_call"&&n?.type==="toolCall"&&n.block.customInput&&(b(n,$(n.block,e.input??w(n.block),!0)),delete n.block.customInput,i.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),l.delete(t.output_index))}else if(t.type==="response.completed"||t.type==="response.incomplete")m(t.response);else{if(t.type==="error")throw new Error(`Error Code ${t.code}: ${t.message}`||"Unknown error");if(t.type==="response.failed"){f=!0,o.rawStopReason=t.response?.status;const e=t.response?.error,n=t.response?.incomplete_details,s=e?`${e.code||"unknown"}: ${e.message||"no message"}`:n?.reason?`incomplete: ${n.reason}`:"Unknown error (no error details in response)";throw new Error(s)}}if(!f)throw new Error("OpenAI Responses stream ended before a terminal response event")}d(processResponsesStream,"processResponsesStream");function E(a){if(!a)return"stop";switch(a){case"completed":return"stop";case"incomplete":return"length";case"failed":case"cancelled":return"error";case"in_progress":case"queued":return"stop";default:{const o=a;throw new Error(`Unhandled stop reason: ${o}`)}}}d(E,"mapStopReason");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var I=Object.defineProperty;var
|
|
1
|
+
var I=Object.defineProperty;var a=(e,o)=>I(e,"name",{value:o,configurable:!0});import P from"openai";import{clampThinkingLevel as S}from"../models.js";import{splitDeferredTools as w}from"../utils/deferred-tools.js";import{formatProviderError as C,normalizeProviderError as M}from"../utils/error-body.js";import{AssistantMessageEventStream as _}from"../utils/event-stream.js";import{headersToRecord as b}from"../utils/headers.js";import{getProviderEnvValue as x}from"../utils/provider-env.js";import{retryProviderRequest as k}from"../utils/provider-retry.js";import{createGrammarToolInputProperties as g}from"./constrained-sampling.js";import{buildCopilotDynamicHeaders as L,hasCopilotVisionInput as G}from"./github-copilot-headers.js";import{clampOpenAIPromptCacheKey as D}from"./openai-prompt-cache.js";import{convertResponsesMessages as N,convertResponsesTools as K,processResponsesStream as F}from"./openai-responses-shared.js";import{buildBaseOptions as U}from"./simple-options.js";const q=new Set(["openai","openai-codex","opencode"]),H=16;function R(e,o){if(!e)return!1;const r=o.toLowerCase();for(const[t,n]of Object.entries(e))if(t.toLowerCase()===r&&n!==null&&n.trim().length>0)return!0;return!1}a(R,"hasHeader");function v(e,o,r){if(o)return o;if(R(r,"authorization")||R(r,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${e}`)}a(v,"getClientApiKey");function W(e){return e.provider==="openrouter"||e.baseUrl.includes("openrouter.ai")?"openrouter":"openai"}a(W,"detectSessionAffinityFormat");function y(e,o){return e||(x("PI_CACHE_RETENTION",o)==="long"?"long":"short")}a(y,"resolveCacheRetention");function l(e){return{supportsDeveloperRole:e.compat?.supportsDeveloperRole??!0,sessionAffinityFormat:e.compat?.sessionAffinityFormat??W(e),supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,supportsStrictMode:e.compat?.supportsStrictMode??!1,supportsOpenAIGrammarTools:e.compat?.supportsOpenAIGrammarTools??!1,supportsToolSearch:e.compat?.supportsToolSearch??!1,supportsExplicitPromptCacheMode:e.compat?.supportsExplicitPromptCacheMode??!1}}a(l,"getCompat");function j(e,o){return o==="long"&&e.supportsLongCacheRetention?"24h":void 0}a(j,"getPromptCacheRetention");function z(e){return C(M(e),"OpenAI API error")}a(z,"formatOpenAIResponsesError");export const stream=a((e,o,r)=>{const t=new _;return(async()=>{const n={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{const i=v(e.provider,r?.apiKey,r?.headers),c=y(r?.cacheRetention,r?.env)==="none"?void 0:r?.sessionId,u=l(e),s=g(o.tools,u.supportsOpenAIGrammarTools),f=V(e,o,i,r?.headers,r?.fetch,c);let m=B(e,o,r,u,s);const d=await r?.onPayload?.(m,e);d!==void 0&&(m=d);const T={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs!==void 0?{timeout:r.timeoutMs}:{},maxRetries:0},{data:A,response:h}=await k(()=>f.responses.create(m,T).withResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});if(await r?.onResponse?.({status:h.status,headers:b(h.headers)},e),t.push({type:"start",partial:n}),await F(A,n,t,e,{serviceTier:r?.serviceTier,grammarToolInputProperties:s,applyServiceTierPricing:a((O,E)=>$(O,E,e),"applyServiceTierPricing")}),r?.signal?.aborted)throw new Error("Request was aborted");if(n.stopReason==="pending")throw new Error("OpenAI Responses stream ended without a stop reason");if(n.stopReason==="aborted"||n.stopReason==="error")throw new Error("An unknown error occurred");t.push({type:"done",reason:n.stopReason,message:n}),t.end()}catch(i){for(const p of n.content)delete p.index,delete p.partialJson,delete p.customInput;n.stopReason=r?.signal?.aborted?"aborted":"error",n.errorMessage=z(i),t.push({type:"error",reason:n.stopReason,error:n}),t.end()}})(),t},"stream"),streamSimple=a((e,o,r)=>{v(e.provider,r?.apiKey,r?.headers);const t=U(e,o,r,r?.apiKey),n=r?.reasoning?S(e,r.reasoning):void 0;return stream(e,o,{...t,reasoningEffort:n==="off"?void 0:n})},"streamSimple");function V(e,o,r,t,n,i){const p=l(e),c={...e.headers};if(e.provider==="github-copilot"){const u=G(o.messages),s=L({messages:o.messages,hasImages:u});Object.assign(c,s)}return i&&(p.sessionAffinityFormat==="openrouter"?c["x-session-id"]=i:(p.sessionAffinityFormat==="openai"&&(c.session_id=i),c["x-client-request-id"]=i)),t&&Object.assign(c,t),new P({apiKey:r,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:n,defaultHeaders:c})}a(V,"createClient");function B(e,o,r,t=l(e),n=g(o.tools,t.supportsOpenAIGrammarTools)){const i=w(o,t.supportsToolSearch),p=N(e,o,q,{grammarToolInputProperties:n,deferredTools:i.deferred,toolOptions:{supportsStrictMode:t.supportsStrictMode,supportsOpenAIGrammarTools:t.supportsOpenAIGrammarTools}}),c=y(r?.cacheRetention,r?.env),u=c==="none"&&t.supportsExplicitPromptCacheMode,s={model:e.id,input:p,stream:!0,prompt_cache_key:c==="none"?void 0:D(r?.sessionId),prompt_cache_retention:j(t,c),prompt_cache_options:u?{mode:"explicit"}:void 0,store:!1};if(r?.maxTokens&&(s.max_output_tokens=Math.max(r.maxTokens,H)),r?.temperature!==void 0&&(s.temperature=r?.temperature),r?.serviceTier!==void 0&&(s.service_tier=r.serviceTier),i.immediate.length>0&&(s.tools=K(i.immediate,{supportsStrictMode:t.supportsStrictMode,supportsOpenAIGrammarTools:t.supportsOpenAIGrammarTools})),r?.toolChoice!==void 0&&(s.tool_choice=r.toolChoice),e.reasoning){if(r?.reasoningEffort||r?.reasoningSummary){const f=r?.reasoningEffort?e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort:"medium";s.reasoning={effort:f,summary:r?.reasoningSummary||"auto"},s.include=["reasoning.encrypted_content"]}else e.provider!=="github-copilot"&&e.thinkingLevelMap?.off!==null&&(s.reasoning={effort:e.thinkingLevelMap?.off??"none"});e.provider==="xai"&&(s.include=["reasoning.encrypted_content"])}return s}a(B,"buildParams");function J(e,o){switch(o){case"flex":return .5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}a(J,"getServiceTierCostMultiplier");function $(e,o,r){const t=J(r,o);t!==1&&(e.cost.input*=t,e.cost.output*=t,e.cost.cacheRead*=t,e.cost.cacheWrite*=t,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}a($,"applyServiceTierPricing");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var R=Object.defineProperty;var u=(e,r)=>R(e,"name",{value:r,configurable:!0});import x from"openai";import{formatProviderError as _,normalizeProviderError as k}from"../utils/error-body.js";import{headersToRecord as w,providerHeadersToRecord as T}from"../utils/headers.js";import{retryProviderRequest as v}from"../utils/provider-retry.js";import{sanitizeSurrogates as b}from"../utils/sanitize-unicode.js";export const generateImages=u(async(e,r,t)=>{const a={api:e.api,provider:e.provider,model:e.id,output:[],stopReason:"stop",timestamp:Date.now()};try{const s=t?.apiKey;if(!s)throw new Error(`No API key for provider: ${e.provider}`);const c=M(e,s,t?.headers);let n=P(e,r);const i=await t?.onPayload?.(n,e);i!==void 0&&(n=i);const o={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:y,response:l}=await v(()=>c.chat.completions.create(n,o).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:l.status,headers:w(l.headers)},e);const p=y;a.responseId=p.id,p.usage&&(a.usage=W(p.usage,e));const m=p.choices[0];if(m){const d=m.message.content;typeof d=="string"&&d.length>0&&a.output.push({type:"text",text:d});for(const h of m.message.images??[]){const f=typeof h.image_url=="string"?h.image_url:h.image_url?.url;if(!f?.startsWith("data:"))continue;const g=f.match(/^data:([^;]+);base64,(.+)$/);g&&a.output.push({type:"image",mimeType:g[1],data:g[2]})}}return a}catch(s){return a.stopReason=t?.signal?.aborted?"aborted":"error",a.errorMessage=_(k(s)),a}},"generateImages");function M(e,r,t){return new x({apiKey:r,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:T({...e.headers,...t})})}u(M,"createClient");function P(e,r){const t=r.input.map(a=>a.type==="text"?{type:"text",text:b(a.text)}:{type:"image_url",image_url:{url:`data:${a.mimeType};base64,${a.data}`}});return{model:e.id,messages:[{role:"user",content:t}],stream:!1,modalities:e.output.includes("text")?["image","text"]:["image"]}}u(P,"buildParams");function W(e,r){const t=e.prompt_tokens||0,a=e.prompt_tokens_details?.cached_tokens||0,s=e.prompt_tokens_details?.cache_write_tokens||0,c=s>0?Math.max(0,a-s):a,n=Math.max(0,t-c-s),i=e.completion_tokens||0,o={input:n,output:i,cacheRead:c,cacheWrite:s,totalTokens:n+i+c+s,cost:{input:r.cost.input/1e6*n,output:r.cost.output/1e6*i,cacheRead:r.cost.cacheRead/1e6*c,cacheWrite:r.cost.cacheWrite/1e6*s,total:0}};return o.cost.total=o.cost.input+o.cost.output+o.cost.cacheRead+o.cost.cacheWrite,o}u(W,"parseUsage");
|
|
1
|
+
var R=Object.defineProperty;var u=(e,r)=>R(e,"name",{value:r,configurable:!0});import x from"openai";import{formatProviderError as _,normalizeProviderError as k}from"../utils/error-body.js";import{headersToRecord as w,providerHeadersToRecord as T}from"../utils/headers.js";import{retryProviderRequest as v}from"../utils/provider-retry.js";import{sanitizeSurrogates as b}from"../utils/sanitize-unicode.js";export const generateImages=u(async(e,r,t)=>{const a={api:e.api,provider:e.provider,model:e.id,output:[],stopReason:"stop",timestamp:Date.now()};try{const s=t?.apiKey;if(!s)throw new Error(`No API key for provider: ${e.provider}`);const c=M(e,s,t?.headers,t?.fetch);let n=P(e,r);const i=await t?.onPayload?.(n,e);i!==void 0&&(n=i);const o={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:y,response:l}=await v(()=>c.chat.completions.create(n,o).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:l.status,headers:w(l.headers)},e);const p=y;a.responseId=p.id,p.usage&&(a.usage=W(p.usage,e));const m=p.choices[0];if(m){const d=m.message.content;typeof d=="string"&&d.length>0&&a.output.push({type:"text",text:d});for(const h of m.message.images??[]){const f=typeof h.image_url=="string"?h.image_url:h.image_url?.url;if(!f?.startsWith("data:"))continue;const g=f.match(/^data:([^;]+);base64,(.+)$/);g&&a.output.push({type:"image",mimeType:g[1],data:g[2]})}}return a}catch(s){return a.stopReason=t?.signal?.aborted?"aborted":"error",a.errorMessage=_(k(s)),a}},"generateImages");function M(e,r,t,a){return new x({apiKey:r,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:a,defaultHeaders:T({...e.headers,...t})})}u(M,"createClient");function P(e,r){const t=r.input.map(a=>a.type==="text"?{type:"text",text:b(a.text)}:{type:"image_url",image_url:{url:`data:${a.mimeType};base64,${a.data}`}});return{model:e.id,messages:[{role:"user",content:t}],stream:!1,modalities:e.output.includes("text")?["image","text"]:["image"]}}u(P,"buildParams");function W(e,r){const t=e.prompt_tokens||0,a=e.prompt_tokens_details?.cached_tokens||0,s=e.prompt_tokens_details?.cache_write_tokens||0,c=s>0?Math.max(0,a-s):a,n=Math.max(0,t-c-s),i=e.completion_tokens||0,o={input:n,output:i,cacheRead:c,cacheWrite:s,totalTokens:n+i+c+s,cost:{input:r.cost.input/1e6*n,output:r.cost.output/1e6*i,cacheRead:r.cost.cacheRead/1e6*c,cacheWrite:r.cost.cacheWrite/1e6*s,total:0}};return o.cost.total=o.cost.input+o.cost.output+o.cost.cacheRead+o.cost.cacheWrite,o}u(W,"parseUsage");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var m=Object.defineProperty;var a=(r,t)=>m(r,"name",{value:t,configurable:!0});import{appendAssistantMessageDiagnostic as l,createAssistantMessageDiagnostic as y}from"../utils/diagnostics.js";import{AssistantMessageEventStream as w}from"../utils/event-stream.js";import{headersToRecord as b,providerHeadersToRecord as I}from"../utils/headers.js";import{parseStreamingJson as k}from"../utils/json-parse.js";import{getProviderEnvValue as E}from"../utils/provider-env.js";export class PiMessagesResponseError extends Error{static{a(this,"PiMessagesResponseError")}code;diagnosticDetails;constructor(t,n,e){super(t),this.name="PiMessagesResponseError",this.code=n,this.diagnosticDetails=e}}function R(r){try{const t=JSON.parse(r),n=t?.error;return t&&typeof n=="object"&&n!==null&&!Array.isArray(n)?t:void 0}catch{return}}a(R,"parsePiMessagesErrorBody");function _(r){return r.length>8192?`${r.slice(0,8192)}…`:r}a(_,"truncateDiagnosticString");function M(r,t,n){const e=typeof n?.error?.message=="string"?n.error.message:void 0,s=typeof n?.error?.code=="string"?n.error.code:void 0,o=e??t,i=s?` (${s})`:"";return`${r.status} ${r.statusText}: ${o}${i}`}a(M,"formatPiMessagesResponseError");function S(r,t,n,e){const s=R(e),o=typeof s?.error?.code=="string"?s.error.code:void 0;return new PiMessagesResponseError(M(n,e,s),o,{version:1,provider:r.provider,model:r.id,url:t.toString(),status:n.status,statusText:n.statusText,error:s?.error,body:s?void 0:_(e),timestampMs:Date.now()})}a(S,"createPiMessagesResponseError");function f(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}a(f,"createEmptyUsage");function h(r,t){t&&l(r,{type:"pi_messages_rewrite",timestamp:Date.now(),details:{...t}})}a(h,"appendRewriteDiagnostic");function P(r){const t={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:f(),stopReason:"
|
|
1
|
+
var m=Object.defineProperty;var a=(r,t)=>m(r,"name",{value:t,configurable:!0});import{appendAssistantMessageDiagnostic as l,createAssistantMessageDiagnostic as y}from"../utils/diagnostics.js";import{AssistantMessageEventStream as w}from"../utils/event-stream.js";import{headersToRecord as b,providerHeadersToRecord as I}from"../utils/headers.js";import{parseStreamingJson as k}from"../utils/json-parse.js";import{getProviderEnvValue as E}from"../utils/provider-env.js";export class PiMessagesResponseError extends Error{static{a(this,"PiMessagesResponseError")}code;diagnosticDetails;constructor(t,n,e){super(t),this.name="PiMessagesResponseError",this.code=n,this.diagnosticDetails=e}}function R(r){try{const t=JSON.parse(r),n=t?.error;return t&&typeof n=="object"&&n!==null&&!Array.isArray(n)?t:void 0}catch{return}}a(R,"parsePiMessagesErrorBody");function _(r){return r.length>8192?`${r.slice(0,8192)}…`:r}a(_,"truncateDiagnosticString");function M(r,t,n){const e=typeof n?.error?.message=="string"?n.error.message:void 0,s=typeof n?.error?.code=="string"?n.error.code:void 0,o=e??t,i=s?` (${s})`:"";return`${r.status} ${r.statusText}: ${o}${i}`}a(M,"formatPiMessagesResponseError");function S(r,t,n,e){const s=R(e),o=typeof s?.error?.code=="string"?s.error.code:void 0;return new PiMessagesResponseError(M(n,e,s),o,{version:1,provider:r.provider,model:r.id,url:t.toString(),status:n.status,statusText:n.statusText,error:s?.error,body:s?void 0:_(e),timestampMs:Date.now()})}a(S,"createPiMessagesResponseError");function f(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}a(f,"createEmptyUsage");function h(r,t){t&&l(r,{type:"pi_messages_rewrite",timestamp:Date.now(),details:{...t}})}a(h,"appendRewriteDiagnostic");function P(r){const t={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:f(),stopReason:"pending",timestamp:Date.now()},n=new Map;return e=>{switch(e.type){case"done":return Object.assign(t,{stopReason:e.reason,usage:e.usage,responseId:e.responseId}),h(t,e.rewrite),{type:"done",reason:e.reason,message:t};case"error":return Object.assign(t,{stopReason:e.reason,usage:e.usage,errorMessage:e.errorMessage,responseId:e.responseId}),h(t,e.rewrite),{type:"error",reason:e.reason,error:t};case"start":break;case"text_start":t.content[e.contentIndex]={type:"text",text:""};break;case"text_delta":t.content[e.contentIndex].text+=e.delta;break;case"text_end":Object.assign(t.content[e.contentIndex],{text:e.content,textSignature:e.contentSignature});break;case"thinking_start":t.content[e.contentIndex]={type:"thinking",thinking:""};break;case"thinking_delta":t.content[e.contentIndex].thinking+=e.delta;break;case"thinking_end":Object.assign(t.content[e.contentIndex],{thinking:e.content,thinkingSignature:e.contentSignature,redacted:e.redacted});break;case"toolcall_start":t.content[e.contentIndex]={type:"toolCall",id:e.id,name:e.toolName,arguments:{}},n.set(e.contentIndex,"");break;case"toolcall_delta":{const s=`${n.get(e.contentIndex)??""}${e.delta}`;n.set(e.contentIndex,s),t.content[e.contentIndex].arguments=k(s);break}case"toolcall_end":return Object.assign(t.content[e.contentIndex],e.toolCall),n.delete(e.contentIndex),{type:"toolcall_end",contentIndex:e.contentIndex,toolCall:t.content[e.contentIndex],partial:t}}return{...e,partial:t}}}a(P,"createEventConverter");async function*$(r){const t=new TextDecoder,n=r.getReader();let e="";try{for(;;){const{done:s,value:o}=await n.read();e+=s?t.decode():t.decode(o,{stream:!0}),e=e.replace(/\r\n/g,`
|
|
2
2
|
`);let i=e.indexOf(`
|
|
3
3
|
|
|
4
4
|
`);for(;i!==-1;){const d=x(e.slice(0,i));d&&(yield d),e=e.slice(i+2),i=e.indexOf(`
|
|
5
5
|
|
|
6
6
|
`)}if(s)break}if(e.trim()){const s=x(e);s&&(yield s)}}finally{n.releaseLock()}}a($,"readPiMessagesEvents");function x(r){const t=r.split(`
|
|
7
|
-
`).find(n=>n.startsWith("data:"))?.slice(5).trim();return t&&t!=="[DONE]"?JSON.parse(t):void 0}a(x,"parsePiMessagesEvent");function D(r,t,n){const e=n?"aborted":"error",s={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:f(),stopReason:e,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()};return!n&&t instanceof PiMessagesResponseError&&l(s,y("pi_messages_response_failure",t,t.diagnosticDetails)),{type:"error",reason:e,error:s}}a(D,"createErrorEvent");function O(r,t){return r||(E("PI_CACHE_RETENTION",t)==="long"?"long":void 0)}a(O,"resolveCacheRetention");export const stream=a((r,t,n)=>{const e=new w,s=P(r);return(async()=>{try{const o=n?.apiKey;if(!o)throw new Error(`No API key provided for provider "${r.provider}"`);const i=new URL(`${r.baseUrl.replace(/\/+$/u,"")}/messages`);n?.debug&&i.searchParams.set("debug","1");let d={model:r.id,context:t,options:{temperature:n?.temperature,maxTokens:n?.maxTokens,reasoning:n?.reasoning,cacheRetention:O(n?.cacheRetention,n?.env),sessionId:n?.sessionId,toolChoice:n?.toolChoice}};const p=await n?.onPayload?.(d,r);p!==void 0&&(d=p);const c=await
|
|
7
|
+
`).find(n=>n.startsWith("data:"))?.slice(5).trim();return t&&t!=="[DONE]"?JSON.parse(t):void 0}a(x,"parsePiMessagesEvent");function D(r,t,n){const e=n?"aborted":"error",s={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:f(),stopReason:e,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()};return!n&&t instanceof PiMessagesResponseError&&l(s,y("pi_messages_response_failure",t,t.diagnosticDetails)),{type:"error",reason:e,error:s}}a(D,"createErrorEvent");function O(r,t){return r||(E("PI_CACHE_RETENTION",t)==="long"?"long":void 0)}a(O,"resolveCacheRetention");export const stream=a((r,t,n)=>{const e=new w,s=P(r);return(async()=>{try{const o=n?.apiKey;if(!o)throw new Error(`No API key provided for provider "${r.provider}"`);const i=new URL(`${r.baseUrl.replace(/\/+$/u,"")}/messages`);n?.debug&&i.searchParams.set("debug","1");let d={model:r.id,context:t,options:{temperature:n?.temperature,maxTokens:n?.maxTokens,reasoning:n?.reasoning,cacheRetention:O(n?.cacheRetention,n?.env),sessionId:n?.sessionId,toolChoice:n?.toolChoice}};const p=await n?.onPayload?.(d,r);p!==void 0&&(d=p);const c=await(n?.fetch??globalThis.fetch)(i,{method:"POST",headers:{authorization:`Bearer ${o}`,accept:"text/event-stream","content-type":"application/json",...I(n?.headers)},body:JSON.stringify(d),signal:n?.signal});if(await n?.onResponse?.({status:c.status,headers:b(c.headers)},r),!c.ok){const u=await c.text();throw S(r,i,c,u)}if(!c.body)throw new Error(`${r.provider} response has no body`);for await(const u of $(c.body)){const g=s(u);if(e.push(g),g.type==="done"||g.type==="error")return}throw new Error(`${r.provider} stream ended without a terminal event`)}catch(o){e.push(D(r,o,n?.signal?.aborted??!1))}})(),e},"stream"),streamSimple=a((r,t,n)=>{const e=n;return stream(r,t,{...n,reasoning:n?.reasoning,toolChoice:e?.toolChoice,debug:e?.debug})},"streamSimple");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var x=Object.defineProperty;var s=(t,n)=>x(t,"name",{value:n,configurable:!0});import{estimateContextTokens as
|
|
1
|
+
var x=Object.defineProperty;var s=(t,n)=>x(t,"name",{value:n,configurable:!0});import{estimateContextTokens as h}from"../utils/estimate.js";const d=4096,u=1;export function clampMaxTokensToContext(t,n,e){if(t.contextWindow<=0)return Math.max(u,e);const a=t.contextWindow-h(n).tokens-d;return Math.min(e,Math.max(u,a))}s(clampMaxTokensToContext,"clampMaxTokensToContext");export function buildBaseOptions(t,n,e,a){return{temperature:e?.temperature,maxTokens:clampMaxTokensToContext(t,n,e?.maxTokens??t.maxTokens),signal:e?.signal,apiKey:a||e?.apiKey,fetch:e?.fetch,transport:e?.transport,cacheRetention:e?.cacheRetention,sessionId:e?.sessionId,headers:e?.headers,onPayload:e?.onPayload,onResponse:e?.onResponse,timeoutMs:e?.timeoutMs,websocketConnectTimeoutMs:e?.websocketConnectTimeoutMs,maxRetries:e?.maxRetries,maxRetryDelayMs:e?.maxRetryDelayMs,metadata:e?.metadata,env:e?.env}}s(buildBaseOptions,"buildBaseOptions");export function clampReasoning(t){return t==="xhigh"||t==="max"?"high":t}s(clampReasoning,"clampReasoning");export function adjustMaxTokensForThinking(t,n,e,a){const c={...{minimal:1024,low:2048,medium:8192,high:16384},...a},i=1024,o=clampReasoning(e);let r=c[o];const m=t===void 0?n:Math.min(t+r,n);return m<=r&&(r=Math.max(0,m-i)),{maxTokens:m,thinkingBudget:r}}s(adjustMaxTokensForThinking,"adjustMaxTokensForThinking");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var L=Object.defineProperty;var n=(e,r)=>L(e,"name",{value:r,configurable:!0});import{createServer as U}from"node:http";import{getProviderEnvValue as v}from"../../utils/provider-env.js";import{oauthErrorHtml as E,oauthSuccessHtml as S}from"./oauth-page.js";import{generatePKCE as T}from"./pkce.js";const C="https://openrouter.ai/auth",P="https://openrouter.ai/api/v1/auth/keys",H=300*1e3,I=3e4;function x(){return v("PI_OAUTH_CALLBACK_HOST")||"127.0.0.1"}n(x,"getCallbackHost");function w(e,r,a){e.statusCode=r,e.setHeader("content-type","text/html; charset=utf-8"),e.setHeader("cache-control","no-store"),e.end(a)}n(w,"sendHtml");function $(e){const r=e.trim();if(r){try{return new URL(r).searchParams.get("code")??void 0}catch{}return r.includes("code=")?new URLSearchParams(r).get("code")??void 0:r}}n($,"parseAuthorizationInput");function z(e){if(typeof e.error_description=="string")return e.error_description;if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;if(e.error&&typeof e.error=="object"&&!Array.isArray(e.error)){const r=e.error.message;if(typeof r=="string")return r}}n(z,"errorDetail");async function _(e,r,a){if(a?.aborted)throw new Error("Login cancelled");const u=new AbortController,i=n(()=>u.abort(a?.reason),"onAbort");a?.addEventListener("abort",i,{once:!0});const f=setTimeout(()=>u.abort(new Error("OpenRouter OAuth token exchange timed out")),I);let s,t={};try{s=await fetch(P,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({code:e,code_verifier:r,code_challenge_method:"S256"}),signal:u.signal});try{const o=await s.json();o&&typeof o=="object"&&!Array.isArray(o)&&(t=o)}catch{if(s.ok)throw new Error("OpenRouter OAuth returned invalid JSON")}}catch(o){throw a?.aborted?new Error("Login cancelled"):u.signal.aborted?new Error("OpenRouter OAuth token exchange timed out"):o}finally{clearTimeout(f),a?.removeEventListener("abort",i)}if(!s.ok){const o=z(t);throw new Error(`OpenRouter OAuth key exchange failed (HTTP ${s.status})${o?`: ${o}`:""}`)}if(typeof t.key!="string"||t.key.length===0)throw new Error('OpenRouter OAuth response carries no "key"');return{type:"oauth",access:t.key,refresh:"",expires:Number.MAX_SAFE_INTEGER}}n(_,"exchangeAuthorizationCode");async function N(e,r,a){if(a?.aborted)throw new Error("Login cancelled");const u=x();let i=n(()=>{},"resolveCredential"),f=n(()=>{},"rejectCredential");const s=new Promise((c,l)=>{i=c,f=l});let t,o=!1,y=!1,g,p;const h=n(()=>{g&&clearTimeout(g),p&&a?.removeEventListener("abort",p),t.close()},"close"),m=n(c=>{y||(y=!0,h(),"credential"in c?i(c.credential):f(c.error))},"finish");if(t=U((c,l)=>{(async()=>{const O=new URL(c.url??"/",`http://${u}`);if(c.method!=="GET"||O.pathname!==e){w(l,404,E("OAuth callback route not found."));return}if(o||y){w(l,409,E("This OAuth callback has already been used."));return}const A=O.searchParams.get("error");if(A){const d=O.searchParams.get("error_description")??A;w(l,400,E("OpenRouter authorization was denied.",d)),m({error:new Error(`OpenRouter authorization failed: ${d}`)});return}const k=O.searchParams.get("code");if(!k){w(l,400,E("OpenRouter returned no authorization code."));return}o=!0;try{const d=await _(k,r,a);w(l,200,S("Signed in to OpenRouter. You may now close this page.")),m({credential:d})}catch(d){const R=d instanceof Error?d.message:"Unknown token exchange error";w(l,502,E("OpenRouter key exchange failed.",R)),m({error:d instanceof Error?d:new Error(R)})}})()}),await new Promise((c,l)=>{t.once("error",l),t.listen(0,u,()=>{t.removeListener("error",l),c()})}),t.on("error",c=>m({error:c})),p=n(()=>m({error:new Error("Login cancelled")}),"onAbort"),a?.addEventListener("abort",p,{once:!0}),a?.aborted)throw h(),new Error("Login cancelled");g=setTimeout(()=>m({error:new Error("OpenRouter OAuth login timed out")}),H);const b=t.address();if(!b||typeof b=="string")throw h(),new Error("Could not determine the OpenRouter OAuth callback port");return{callbackUrl:`http://${u}:${b.port}${e}`,close:h,cancelWait:n(()=>{o||m({credential:null})},"cancelWait"),waitForCredential:n(()=>s,"waitForCredential")}}n(N,"startCallbackServer");async function M(e){const{verifier:r,challenge:a}=await T(),u=`/oauth/callback/${crypto.randomUUID()}`,i=await N(u,r,e.signal),f=new AbortController;let s,t;try{const o=new URL(C);o.search=new URLSearchParams({callback_url:i.callbackUrl,code_challenge:a,code_challenge_method:"S256"}).toString(),e.notify({type:"progress",message:`Listening for OpenRouter OAuth callback on ${i.callbackUrl}`}),e.notify({type:"auth_url",url:o.toString(),instructions:"Complete sign-in in your browser. If the browser is on another machine, paste the final redirect URL here."});const y=e.prompt({type:"manual_code",message:"Complete sign-in in your browser, or paste the authorization code / redirect URL here:",placeholder:i.callbackUrl,signal:f.signal}).then(h=>{s=h,i.cancelWait()}).catch(h=>{t=h instanceof Error?h:new Error(String(h)),i.cancelWait()}),g=await i.waitForCredential();if(t)throw t;if(g)return g;if(await y,t)throw t;const p=s?$(s):void 0;if(!p)throw new Error("Missing authorization code");return e.notify({type:"progress",message:"Exchanging authorization code for an API key..."}),await _(p,r,e.signal)}finally{f.abort(),i.close()}}n(M,"loginOpenRouter");export const openRouterOAuth={name:"OpenRouter OAuth",loginLabel:"Sign in with OpenRouter",login:M,async refresh(e){return e},async toAuth(e){return{apiKey:e.access}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var l=Object.defineProperty;var u=(t,e)=>l(t,"name",{value:e,configurable:!0});import{formatThrownValue as w}from"../utils/diagnostics.js";export class ModelsError extends Error{static{u(this,"ModelsError")}code;constructor(e,n,a){super(d(n,a?.cause),a),this.name="ModelsError",this.code=e}}function d(t,e){if(e==null)return t;const n=w(e).trim();return!n||t.includes(n)?t:`${t}: ${n}`}u(d,"withCauseDetail");export async function resolveProviderAuth(t,e,n,a){const i=a?.env?A(n,a.env):n;if(a?.apiKey!==void 0&&t.auth.apiKey)return s(i,t.auth.apiKey,t.id,{type:"api_key",key:a.apiKey,env:a.env});const r=await M(e,t.id);if(r){if(r.type==="oauth"&&t.auth.oauth)return K(e,t.id,t.auth.oauth,r,a?.minOAuthValidityMs);if(r.type==="api_key"&&t.auth.apiKey){const f=a?.env?{...r,env:{...r.env,...a.env}}:r;return s(i,t.auth.apiKey,t.id,f)}return}return t.auth.apiKey?s(i,t.auth.apiKey,t.id,void 0):void 0}u(resolveProviderAuth,"resolveProviderAuth");function A(t,e){return{env:u(async n=>e[n]||await t.env(n),"env"),fileExists:u(n=>t.fileExists(n),"fileExists")}}u(A,"overlayEnvAuthContext");const x=300*1e3;async function K(t,e,n,a,i){const r=Math.max(x,i??0),f=u(o=>Date.now()+r>=o.expires,"expiresSoon");let c=a;if(f(c)){let o;try{o=await t.modify(e,async h=>{if(h?.type==="oauth"&&f(h))try{return await n.refresh(h)}catch(y){throw new ModelsError("oauth",`OAuth refresh failed for ${e}`,{cause:y})}})}catch(h){throw h instanceof ModelsError?h:new ModelsError("auth",`Credential store modify failed for ${e}`,{cause:h})}if(o?.type!=="oauth")return;if(c=o,i!==void 0&&f(c))throw new ModelsError("oauth",`OAuth refresh returned a token that expires too soon for ${e}`)}try{return{auth:await n.toAuth(c),source:"OAuth"}}catch(o){throw new ModelsError("oauth",`OAuth auth derivation failed for ${e}`,{cause:o})}}u(K,"resolveStoredOAuth");async function s(t,e,n,a){try{return await e.resolve({ctx:t,credential:a})}catch(i){throw new ModelsError("auth",`API key auth failed for provider ${n}`,{cause:i})}}u(s,"resolveApiKey");async function M(t,e){try{return await t.read(e)}catch(n){throw new ModelsError("auth",`Credential store read failed for ${e}`,{cause:n})}}u(M,"readCredential");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var n=Object.defineProperty;var e=(r,o)=>n(r,"name",{value:o,configurable:!0});import{createImagesModels as d}from"../images-models.js";import{MODELS as t}from"../models.generated.js";import{createModels as p}from"../models.js";import{amazonBedrockProvider as f}from"./amazon-bedrock.js";import{antLingProvider as a}from"./ant-ling.js";import{anthropicProvider as v}from"./anthropic.js";import{azureOpenAIResponsesProvider as P}from"./azure-openai-responses.js";import{cerebrasProvider as s}from"./cerebras.js";import{cloudflareAIGatewayProvider as l}from"./cloudflare-ai-gateway.js";import{cloudflareWorkersAIProvider as u}from"./cloudflare-workers-ai.js";import c from"./data/.manifest.json";import{deepseekProvider as g}from"./deepseek.js";import{fireworksProvider as x}from"./fireworks.js";import{githubCopilotProvider as k}from"./github-copilot.js";import{googleProvider as b}from"./google.js";import{googleVertexProvider as C}from"./google-vertex.js";import{groqProvider as M}from"./groq.js";import{huggingfaceProvider as A}from"./huggingface.js";import{kimiCodingProvider as I}from"./kimi-coding.js";import{minimaxProvider as h}from"./minimax.js";import{minimaxCnProvider as w}from"./minimax-cn.js";import{mistralProvider as B}from"./mistral.js";import{moonshotaiProvider as T}from"./moonshotai.js";import{moonshotaiCnProvider as y}from"./moonshotai-cn.js";import{nvidiaProvider as z}from"./nvidia.js";import{openaiProvider as D}from"./openai.js";import{openaiCodexProvider as G}from"./openai-codex.js";import{opencodeProvider as O}from"./opencode.js";import{opencodeGoProvider as j}from"./opencode-go.js";import{openrouterProvider as q}from"./openrouter.js";import{openrouterImagesProvider as N}from"./openrouter-images.js";import{qwenTokenPlanProvider as L}from"./qwen-token-plan.js";import{qwenTokenPlanCnProvider as S}from"./qwen-token-plan-cn.js";import{radiusProvider as m}from"./radius.js";import{togetherProvider as E}from"./together.js";import{vercelAIGatewayProvider as R}from"./vercel-ai-gateway.js";import{xaiProvider as V}from"./xai.js";import{xiaomiProvider as W}from"./xiaomi.js";import{xiaomiTokenPlanAmsProvider as F}from"./xiaomi-token-plan-ams.js";import{xiaomiTokenPlanCnProvider as H}from"./xiaomi-token-plan-cn.js";import{xiaomiTokenPlanSgpProvider as J}from"./xiaomi-token-plan-sgp.js";import{zaiProvider as K}from"./zai.js";import{zaiCodingCnProvider as Q}from"./zai-coding-cn.js";export{m as radiusProvider};export function getBuiltinModel(r,o){return t[r]?.[o]}e(getBuiltinModel,"getBuiltinModel");export function getBuiltinProviders(){return Object.keys(t)}e(getBuiltinProviders,"getBuiltinProviders");export function getBuiltinModelDataGeneratedAt(){const r=Date.parse(c.generatedAt);return Number.isNaN(r)?void 0:r}e(getBuiltinModelDataGeneratedAt,"getBuiltinModelDataGeneratedAt");export function getBuiltinModels(r){const o=t[r];return o?Object.values(o):[]}e(getBuiltinModels,"getBuiltinModels");export function builtinProviders(){return[f(),a(),v(),P(),s(),l(),u(),g(),x(),k(),b(),C(),M(),A(),I(),h(),w(),B(),T(),y(),z(),D(),G(),O(),j(),q(),L(),S(),m(),E(),R(),V(),W(),F(),H(),J(),K(),Q()]}e(builtinProviders,"builtinProviders");export function builtinModels(r){const o=p(r);for(const i of builtinProviders())o.setProvider(i);return o}e(builtinModels,"builtinModels");export function builtinImagesProviders(){return[N()]}e(builtinImagesProviders,"builtinImagesProviders");export function builtinImagesModels(r){const o=d(r);for(const i of builtinImagesProviders())o.setProvider(i);return o}e(builtinImagesModels,"builtinImagesModels");
|
|
1
|
+
var n=Object.defineProperty;var e=(r,o)=>n(r,"name",{value:o,configurable:!0});import{createImagesModels as d}from"../images-models.js";import{MODELS as t}from"../models.generated.js";import{createModels as p}from"../models.js";import{amazonBedrockProvider as f}from"./amazon-bedrock.js";import{antLingProvider as a}from"./ant-ling.js";import{anthropicProvider as v}from"./anthropic.js";import{azureOpenAIResponsesProvider as P}from"./azure-openai-responses.js";import{cerebrasProvider as s}from"./cerebras.js";import{cloudflareAIGatewayProvider as l}from"./cloudflare-ai-gateway.js";import{cloudflareWorkersAIProvider as u}from"./cloudflare-workers-ai.js";import c from"./data/.manifest.json"with{type:"json"};import{deepseekProvider as g}from"./deepseek.js";import{fireworksProvider as x}from"./fireworks.js";import{githubCopilotProvider as k}from"./github-copilot.js";import{googleProvider as b}from"./google.js";import{googleVertexProvider as C}from"./google-vertex.js";import{groqProvider as M}from"./groq.js";import{huggingfaceProvider as A}from"./huggingface.js";import{kimiCodingProvider as I}from"./kimi-coding.js";import{minimaxProvider as h}from"./minimax.js";import{minimaxCnProvider as w}from"./minimax-cn.js";import{mistralProvider as B}from"./mistral.js";import{moonshotaiProvider as T}from"./moonshotai.js";import{moonshotaiCnProvider as y}from"./moonshotai-cn.js";import{nvidiaProvider as z}from"./nvidia.js";import{openaiProvider as D}from"./openai.js";import{openaiCodexProvider as G}from"./openai-codex.js";import{opencodeProvider as O}from"./opencode.js";import{opencodeGoProvider as j}from"./opencode-go.js";import{openrouterProvider as q}from"./openrouter.js";import{openrouterImagesProvider as N}from"./openrouter-images.js";import{qwenTokenPlanProvider as L}from"./qwen-token-plan.js";import{qwenTokenPlanCnProvider as S}from"./qwen-token-plan-cn.js";import{radiusProvider as m}from"./radius.js";import{togetherProvider as E}from"./together.js";import{vercelAIGatewayProvider as R}from"./vercel-ai-gateway.js";import{xaiProvider as V}from"./xai.js";import{xiaomiProvider as W}from"./xiaomi.js";import{xiaomiTokenPlanAmsProvider as F}from"./xiaomi-token-plan-ams.js";import{xiaomiTokenPlanCnProvider as H}from"./xiaomi-token-plan-cn.js";import{xiaomiTokenPlanSgpProvider as J}from"./xiaomi-token-plan-sgp.js";import{zaiProvider as K}from"./zai.js";import{zaiCodingCnProvider as Q}from"./zai-coding-cn.js";export{m as radiusProvider};export function getBuiltinModel(r,o){return t[r]?.[o]}e(getBuiltinModel,"getBuiltinModel");export function getBuiltinProviders(){return Object.keys(t)}e(getBuiltinProviders,"getBuiltinProviders");export function getBuiltinModelDataGeneratedAt(){const r=Date.parse(c.generatedAt);return Number.isNaN(r)?void 0:r}e(getBuiltinModelDataGeneratedAt,"getBuiltinModelDataGeneratedAt");export function getBuiltinModels(r){const o=t[r];return o?Object.values(o):[]}e(getBuiltinModels,"getBuiltinModels");export function builtinProviders(){return[f(),a(),v(),P(),s(),l(),u(),g(),x(),k(),b(),C(),M(),A(),I(),h(),w(),B(),T(),y(),z(),D(),G(),O(),j(),q(),L(),S(),m(),E(),R(),V(),W(),F(),H(),J(),K(),Q()]}e(builtinProviders,"builtinProviders");export function builtinModels(r){const o=p(r);for(const i of builtinProviders())o.setProvider(i);return o}e(builtinModels,"builtinModels");export function builtinImagesProviders(){return[N()]}e(builtinImagesProviders,"builtinImagesProviders");export function builtinImagesModels(r){const o=d(r);for(const i of builtinImagesProviders())o.setProvider(i);return o}e(builtinImagesModels,"builtinImagesModels");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import o from"./data/amazon-bedrock.json";import{flattenModelCatalog as t}from"../model-catalog.js";export const AMAZON_BEDROCK_MODELS=t("amazon-bedrock",o);
|
|
1
|
+
import o from"./data/amazon-bedrock.json"with{type:"json"};import{flattenModelCatalog as t}from"../model-catalog.js";export const AMAZON_BEDROCK_MODELS=t("amazon-bedrock",o);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"./data/ant-ling.json";import{flattenModelCatalog as o}from"../model-catalog.js";export const ANT_LING_MODELS=o("ant-ling",t);
|
|
1
|
+
import t from"./data/ant-ling.json"with{type:"json"};import{flattenModelCatalog as o}from"../model-catalog.js";export const ANT_LING_MODELS=o("ant-ling",t);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import o from"./data/anthropic.json";import{flattenModelCatalog as t}from"../model-catalog.js";export const ANTHROPIC_MODELS=t("anthropic",o);
|
|
1
|
+
import o from"./data/anthropic.json"with{type:"json"};import{flattenModelCatalog as t}from"../model-catalog.js";export const ANTHROPIC_MODELS=t("anthropic",o);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import o from"./data/azure-openai-responses.json";import{flattenModelCatalog as e}from"../model-catalog.js";export const AZURE_OPENAI_RESPONSES_MODELS=e("azure-openai-responses",o);
|
|
1
|
+
import o from"./data/azure-openai-responses.json"with{type:"json"};import{flattenModelCatalog as e}from"../model-catalog.js";export const AZURE_OPENAI_RESPONSES_MODELS=e("azure-openai-responses",o);
|