@code-yeongyu/senpi 2026.8.18-3 → 2026.8.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/dist/cli/args.d.ts +1 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +4 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session.d.ts +33 -4
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +293 -55
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +3 -0
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +20 -3
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +182 -52
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/index.d.ts +3 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/index.js +18 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/index.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/oauth-login.d.ts +1 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/oauth-login.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/oauth-login.js +7 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/oauth-login.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/settings.d.ts +8 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/settings.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/settings.js +18 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/settings.js.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/guardrails.d.ts +7 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/guardrails.d.ts.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/guardrails.js +10 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/guardrails.js.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/index.js +12 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/index.js.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/oauth-login.d.ts +12 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/oauth-login.d.ts.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/oauth-login.js +20 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/oauth-login.js.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/settings.d.ts +11 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/settings.d.ts.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/settings.js +7 -2
- package/dist/core/extensions/builtin/cursor-cli-oauth/settings.js.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/stream.d.ts.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/stream.js +7 -2
- package/dist/core/extensions/builtin/cursor-cli-oauth/stream.js.map +1 -1
- package/dist/core/extensions/builtin/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/index.js +2 -0
- package/dist/core/extensions/builtin/index.js.map +1 -1
- package/dist/core/extensions/builtin/loop/command-registration.d.ts +7 -0
- package/dist/core/extensions/builtin/loop/command-registration.d.ts.map +1 -0
- package/dist/core/extensions/builtin/loop/command-registration.js +13 -0
- package/dist/core/extensions/builtin/loop/command-registration.js.map +1 -0
- package/dist/core/extensions/builtin/loop/command.d.ts +41 -0
- package/dist/core/extensions/builtin/loop/command.d.ts.map +1 -0
- package/dist/core/extensions/builtin/loop/command.js +281 -0
- package/dist/core/extensions/builtin/loop/command.js.map +1 -0
- package/dist/core/extensions/builtin/loop/cron-planner.d.ts +23 -0
- package/dist/core/extensions/builtin/loop/cron-planner.d.ts.map +1 -0
- package/dist/core/extensions/builtin/loop/cron-planner.js +88 -0
- package/dist/core/extensions/builtin/loop/cron-planner.js.map +1 -0
- package/dist/core/extensions/builtin/loop/index.d.ts +134 -0
- package/dist/core/extensions/builtin/loop/index.d.ts.map +1 -0
- package/dist/core/extensions/builtin/loop/index.js +742 -0
- package/dist/core/extensions/builtin/loop/index.js.map +1 -0
- package/dist/core/extensions/builtin/loop/loopfile.d.ts +40 -0
- package/dist/core/extensions/builtin/loop/loopfile.d.ts.map +1 -0
- package/dist/core/extensions/builtin/loop/loopfile.js +102 -0
- package/dist/core/extensions/builtin/loop/loopfile.js.map +1 -0
- package/dist/core/extensions/builtin/loop/parse.d.ts +45 -0
- package/dist/core/extensions/builtin/loop/parse.d.ts.map +1 -0
- package/dist/core/extensions/builtin/loop/parse.js +92 -0
- package/dist/core/extensions/builtin/loop/parse.js.map +1 -0
- package/dist/core/extensions/builtin/loop/scheduler.d.ts +225 -0
- package/dist/core/extensions/builtin/loop/scheduler.d.ts.map +1 -0
- package/dist/core/extensions/builtin/loop/scheduler.js +708 -0
- package/dist/core/extensions/builtin/loop/scheduler.js.map +1 -0
- package/dist/core/extensions/builtin/loop/status.d.ts +24 -0
- package/dist/core/extensions/builtin/loop/status.d.ts.map +1 -0
- package/dist/core/extensions/builtin/loop/status.js +113 -0
- package/dist/core/extensions/builtin/loop/status.js.map +1 -0
- package/dist/core/extensions/builtin/loop/store.d.ts +49 -0
- package/dist/core/extensions/builtin/loop/store.d.ts.map +1 -0
- package/dist/core/extensions/builtin/loop/store.js +424 -0
- package/dist/core/extensions/builtin/loop/store.js.map +1 -0
- package/dist/core/extensions/builtin/loop/tick-prompt.d.ts +64 -0
- package/dist/core/extensions/builtin/loop/tick-prompt.d.ts.map +1 -0
- package/dist/core/extensions/builtin/loop/tick-prompt.js +183 -0
- package/dist/core/extensions/builtin/loop/tick-prompt.js.map +1 -0
- package/dist/core/extensions/builtin/loop/tools.d.ts +122 -0
- package/dist/core/extensions/builtin/loop/tools.d.ts.map +1 -0
- package/dist/core/extensions/builtin/loop/tools.js +155 -0
- package/dist/core/extensions/builtin/loop/tools.js.map +1 -0
- package/dist/core/extensions/builtin/loop/types.d.ts +206 -0
- package/dist/core/extensions/builtin/loop/types.d.ts.map +1 -0
- package/dist/core/extensions/builtin/loop/types.js +37 -0
- package/dist/core/extensions/builtin/loop/types.js.map +1 -0
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +10 -5
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/types.d.ts +30 -3
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +5 -10
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/model-registry.d.ts +2 -0
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +4 -0
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-runtime.d.ts +7 -0
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +17 -0
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +8 -4
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/provider-composer.d.ts +8 -0
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +2 -1
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/retry-fallback/chains.d.ts +1 -0
- package/dist/core/retry-fallback/chains.d.ts.map +1 -1
- package/dist/core/retry-fallback/chains.js +3 -0
- package/dist/core/retry-fallback/chains.js.map +1 -1
- package/dist/core/retry-fallback/controller.d.ts +2 -0
- package/dist/core/retry-fallback/controller.d.ts.map +1 -1
- package/dist/core/retry-fallback/controller.js.map +1 -1
- package/dist/core/retry-fallback/expansion.d.ts +8 -0
- package/dist/core/retry-fallback/expansion.d.ts.map +1 -1
- package/dist/core/retry-fallback/expansion.js +2 -0
- package/dist/core/retry-fallback/expansion.js.map +1 -1
- package/dist/core/settings-manager.d.ts +1 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +14 -3
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +51 -33
- package/dist/core/skills.js.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +17 -2
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/extensions/llama/index.d.ts.map +1 -1
- package/dist/extensions/llama/index.js +2 -0
- package/dist/extensions/llama/index.js.map +1 -1
- package/dist/extensions/llama/provider.d.ts.map +1 -1
- package/dist/extensions/llama/provider.js +6 -6
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +4 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +4 -4
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +1 -1
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/editor-paste-transfer.d.ts +10 -1
- package/dist/modes/interactive/editor-paste-transfer.d.ts.map +1 -1
- package/dist/modes/interactive/editor-paste-transfer.js +27 -2
- package/dist/modes/interactive/editor-paste-transfer.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +69 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +434 -63
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/tips/catalog/dag-tips.d.ts +7 -0
- package/dist/modes/interactive/tips/catalog/dag-tips.d.ts.map +1 -0
- package/dist/modes/interactive/tips/catalog/dag-tips.js +57 -0
- package/dist/modes/interactive/tips/catalog/dag-tips.js.map +1 -0
- package/dist/modes/interactive/tips/catalog/memory-tips.d.ts +7 -0
- package/dist/modes/interactive/tips/catalog/memory-tips.d.ts.map +1 -0
- package/dist/modes/interactive/tips/catalog/memory-tips.js +100 -0
- package/dist/modes/interactive/tips/catalog/memory-tips.js.map +1 -0
- package/dist/modes/interactive/tips/registry.d.ts.map +1 -1
- package/dist/modes/interactive/tips/registry.js +4 -0
- package/dist/modes/interactive/tips/registry.js.map +1 -1
- package/dist/utils/management-http.d.ts +5 -3
- package/dist/utils/management-http.d.ts.map +1 -1
- package/dist/utils/management-http.js +14 -10
- package/dist/utils/management-http.js.map +1 -1
- package/docs/compaction.md +17 -0
- package/docs/custom-provider.md +5 -2
- package/docs/extensions.md +11 -2
- package/docs/llama-cpp.md +2 -0
- package/docs/models.md +8 -2
- package/docs/providers.md +5 -3
- package/docs/settings.md +22 -2
- package/docs/skills.md +4 -3
- package/examples/extensions/border-status-editor.ts +1 -1
- package/examples/extensions/git-checkpoint.ts +2 -2
- package/examples/extensions/notify.ts +3 -1
- package/examples/extensions/subagent/index.ts +6 -1
- package/examples/extensions/titlebar-spinner.ts +1 -1
- package/examples/rpc-extension-ui.ts +1 -1
- package/examples/sdk/06-extensions.ts +1 -1
- package/examples/sdk/README.md +1 -1
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +12 -0
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts +3 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +51 -17
- package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/agent.d.ts +4 -2
- package/node_modules/@earendil-works/pi-agent-core/dist/agent.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/agent.js +5 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/agent.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/skills.d.ts +3 -2
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/skills.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/skills.js +13 -3
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/skills.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js +14 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/node_modules/@earendil-works/pi-ai/README.md +5 -3
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.d.ts +7 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +21 -4
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/azure-openai-responses.d.ts +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/azure-openai-responses.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/azure-openai-responses.js +7 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/azure-openai-responses.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.js +39 -2
- package/node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent/gen/agent_pb.d.ts +22 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent/gen/agent_pb.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent/gen/agent_pb.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent/gen/agent_pb.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.d.ts +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js +51 -2
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.d.ts +2 -2
- package/node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.js +14 -11
- package/node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/google-shared.d.ts +5 -2
- package/node_modules/@earendil-works/pi-ai/dist/api/google-shared.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/google-shared.js +16 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/google-shared.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/google-vertex.d.ts +2 -2
- package/node_modules/@earendil-works/pi-ai/dist/api/google-vertex.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/google-vertex.js +13 -10
- package/node_modules/@earendil-works/pi-ai/dist/api/google-vertex.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js +4 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +4 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.d.ts +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +45 -29
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +8 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/pi-messages.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/pi-messages.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/simple-options.d.ts +4 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/simple-options.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/simple-options.js +18 -9
- package/node_modules/@earendil-works/pi-ai/dist/api/simple-options.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/device-code.d.ts +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/device-code.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/device-code.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/device-code.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot.js +22 -9
- package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/github-copilot.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/index.d.ts +2 -1
- package/node_modules/@earendil-works/pi-ai/dist/index.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/index.js +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/index.js.map +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/anthropic.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan-individual.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/xai.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-ams.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-cn.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-sgp.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi.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/xai.d.ts +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/xai.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/xai.js +1 -5
- package/node_modules/@earendil-works/pi-ai/dist/providers/xai.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/types.d.ts +28 -4
- package/node_modules/@earendil-works/pi-ai/dist/types.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/types.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +15 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.d.ts +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.js +7 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/prompt-cache-ttl.d.ts +2 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/prompt-cache-ttl.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/prompt-cache-ttl.js +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/prompt-cache-ttl.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/package.json +2 -3
- package/node_modules/@earendil-works/pi-pty/dist/loader.d.ts +6 -0
- package/node_modules/@earendil-works/pi-pty/dist/loader.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-pty/dist/loader.js +11 -0
- package/node_modules/@earendil-works/pi-pty/dist/loader.js.map +1 -1
- package/node_modules/@earendil-works/pi-pty/dist/quarantine.d.ts +15 -0
- package/node_modules/@earendil-works/pi-pty/dist/quarantine.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-pty/dist/quarantine.js +27 -0
- package/node_modules/@earendil-works/pi-pty/dist/quarantine.js.map +1 -0
- package/node_modules/@earendil-works/pi-pty/package.json +1 -1
- package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/components/editor.d.ts +73 -1
- package/node_modules/@earendil-works/pi-tui/dist/components/editor.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/components/editor.js +173 -17
- package/node_modules/@earendil-works/pi-tui/dist/components/editor.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/components/text.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/components/text.js +5 -4
- package/node_modules/@earendil-works/pi-tui/dist/components/text.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/editor-component.d.ts +69 -0
- package/node_modules/@earendil-works/pi-tui/dist/editor-component.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/editor-component.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/image-markers.d.ts +46 -0
- package/node_modules/@earendil-works/pi-tui/dist/image-markers.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-tui/dist/image-markers.js +130 -0
- package/node_modules/@earendil-works/pi-tui/dist/image-markers.js.map +1 -0
- package/node_modules/@earendil-works/pi-tui/dist/index.d.ts +1 -0
- package/node_modules/@earendil-works/pi-tui/dist/index.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/index.js +2 -0
- package/node_modules/@earendil-works/pi-tui/dist/index.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/paste-markers.d.ts +3 -0
- package/node_modules/@earendil-works/pi-tui/dist/paste-markers.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/paste-markers.js +23 -7
- package/node_modules/@earendil-works/pi-tui/dist/paste-markers.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +5 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/package.json +7 -7
|
@@ -75,6 +75,16 @@ const NON_OVERFLOW_PATTERNS = [
|
|
|
75
75
|
/rate limit/i, // Generic rate limiting
|
|
76
76
|
/too many requests/i, // Generic HTTP 429 style
|
|
77
77
|
];
|
|
78
|
+
/**
|
|
79
|
+
* Cursor's api2.cursor.sh surfaces a context overflow as a bare gRPC
|
|
80
|
+
* `resource_exhausted` end-stream — the same wording its backend uses for
|
|
81
|
+
* quota and poisoned-conversation rejections. Token evidence disambiguates:
|
|
82
|
+
* a request that already streamed or billed tokens overflowed mid-flight,
|
|
83
|
+
* while a zero-token rejection is a quota/conversation failure that must stay
|
|
84
|
+
* on the rate-limit path (the cursor client rotates the conversation id for
|
|
85
|
+
* those and retry handling supplies the backoff).
|
|
86
|
+
*/
|
|
87
|
+
const RESOURCE_EXHAUSTED_PATTERN = /resource.?exhausted/i;
|
|
78
88
|
/**
|
|
79
89
|
* Check if an assistant message represents a context overflow error.
|
|
80
90
|
*
|
|
@@ -137,6 +147,11 @@ export function isContextOverflow(message, contextWindow) {
|
|
|
137
147
|
if (!isNonOverflow && OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage))) {
|
|
138
148
|
return true;
|
|
139
149
|
}
|
|
150
|
+
const usage = message.usage;
|
|
151
|
+
const hasTokenEvidence = (usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite) > 0;
|
|
152
|
+
if (!isNonOverflow && hasTokenEvidence && RESOURCE_EXHAUSTED_PATTERN.test(message.errorMessage)) {
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
140
155
|
}
|
|
141
156
|
// Case 2: Silent overflow (z.ai style) - successful but usage exceeds context
|
|
142
157
|
if (contextWindow && message.stopReason === "stop") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"overflow.js","sourceRoot":"","sources":["../../src/utils/overflow.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAM,iBAAiB,GAAG;IACzB,qBAAqB,EAAE,2BAA2B;IAClD,oBAAoB,EAAE,kDAAkD;IACxE,wCAAwC,EAAE,iBAAiB;IAC3D,6BAA6B,EAAE,uCAAuC;IACtE,4FAA4F,EAAE,sCAAsC;IACpI,yCAAyC,EAAE,kBAAkB;IAC7D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C,CAAC,EAAE,CAAC;YACpF,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAED,8EAA8E;IAC9E,IAAI,aAAa,IAAI,OAAO,CAAC,UAAU,KAAK,MAAM,EAAE,CAAC;QACpD,MAAM,WAAW,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;QAClE,IAAI,WAAW,GAAG,aAAa,EAAE,CAAC;YACjC,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAED,sFAAsF;IACtF,qFAAqF;IACrF,gEAAgE;IAChE,IAAI,aAAa,IAAI,OAAO,CAAC,UAAU,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACpF,MAAM,WAAW,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;QAClE,IAAI,WAAW,IAAI,aAAa,GAAG,IAAI,EAAE,CAAC;YACzC,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC;AACd,CAAC;AACD;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAyB,EAAE,gBAAwB;IACtF,OAAO,OAAO,CAAC,UAAU,KAAK,QAAQ,IAAI,gBAAgB,GAAG,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,GAAG,gBAAgB,CAAC;AAC3G,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB;IAClC,OAAO,CAAC,GAAG,iBAAiB,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\n\n/**\n * Regex patterns to detect context overflow errors from different providers.\n *\n * These patterns match error messages returned when the input exceeds\n * the model's context window.\n *\n * Provider-specific patterns (with example error messages):\n *\n * - Anthropic: \"prompt is too long: 213462 tokens > 200000 maximum\"\n * - Anthropic: \"413 {\\\"error\\\":{\\\"type\\\":\\\"request_too_large\\\",\\\"message\\\":\\\"Request exceeds the maximum size\\\"}}\"\n * - OpenAI: \"Your input exceeds the context window of this model\"\n * - OpenAI/LiteLLM: \"Requested token count exceeds the model's maximum context length of 131072 tokens\"\n * - OpenAI-compatible: \"Input length (265330) exceeds model's maximum context length (262144).\"\n * - Google: \"The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)\"\n * - xAI: \"This model's maximum prompt length is 131072 but the request contains 537812 tokens\"\n * - Groq: \"Please reduce the length of the messages or completion\"\n * - OpenRouter: \"This endpoint's maximum context length is X tokens. However, you requested about Y tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"the request exceeds the available context size, try increasing it\"\n * - LM Studio: \"tokens to keep from the initial prompt is greater than the context length\"\n * - GitHub Copilot: \"prompt token count of X exceeds the limit of Y\"\n * - MiniMax: \"invalid params, context window exceeds limit\"\n * - Kimi For Coding: \"Your request exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - Cerebras: \"400/413 status code (no body)\"\n * - Gateways: \"413 Request body too large\" / \"Request Entity Too Large\" / \"Payload Too Large\" (byte-size overflow)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - z.ai: Does NOT error, accepts overflow silently - handled via usage.input > contextWindow\n * - Xiaomi MiMo: Truncates input to fill contextWindow exactly, then returns finish_reason \"length\"\n * with output=0 (no room left to generate). Detected via stopReason \"length\" + zero output +\n * input filling the context window.\n * - DashScope/Qwen: \"Range of input length should be [1, X]\" (HTTP 400 invalid_parameter_error)\n * - Ollama: Some deployments truncate silently, others return errors like \"prompt too long; exceeded max context length by X tokens\"\n */\nconst OVERFLOW_PATTERNS = [\n\t/prompt is too long/i, // Anthropic token overflow\n\t/request_too_large/i, // Anthropic request byte-size overflow (HTTP 413)\n\t/input is too long for requested model/i, // Amazon Bedrock\n\t/exceeds the context window/i, // OpenAI (Completions & Responses API)\n\t/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\\d,]+ tokens?|\\s*\\([\\d,]+\\))/i, // OpenAI-compatible proxies (LiteLLM)\n\t/input token count.*exceeds the maximum/i, // Google (Gemini)\n\t/maximum prompt length is \\d+/i, // xAI (Grok)\n\t/reduce the length of the messages/i, // Groq\n\t/maximum context length is \\d+ tokens/i, // OpenRouter (most backends)\n\t/exceeds (?:the )?maximum allowed input length of [\\d,]+ tokens?/i, // OpenRouter/Poolside\n\t/input \\(\\d+ tokens\\) is longer than the model'?s context length \\(\\d+ tokens\\)/i, // Together AI\n\t/exceeds the limit of \\d+/i, // GitHub Copilot\n\t/exceeds the available context size/i, // llama.cpp server\n\t/greater than the context length/i, // LM Studio\n\t/context window exceeds limit/i, // MiniMax\n\t/exceeded model token limit/i, // Kimi For Coding\n\t/too large for model with \\d+ maximum context length/i, // Mistral\n\t/prompt has [\\d,]+ tokens?, but the configured context size is [\\d,]+ tokens?/i, // DS4 server\n\t/model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text\n\t/prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow error\n\t/range of input length should be/i, // DashScope / Qwen Token Plan\n\t/context[_ ]length[_ ]exceeded/i, // Generic fallback\n\t/too many tokens/i, // Generic fallback\n\t/token limit exceeded/i, // Generic fallback\n\t/^4(?:00|13)\\s*(?:status code)?\\s*\\(no body\\)/i, // Cerebras: 400/413 with no body\n\t/(?:request[ _])?(?:body|entity|payload)[_ ]too[_ ]large/i, // Gateway HTTP 413 byte-size rejections (\"Request body too large\", \"Request Entity Too Large\", \"body_too_large\", \"Payload Too Large\"). Substring-anchored by design (JSON bodies lack an adjacent status code); a non-context size rejection (e.g. an oversized image) can over-match, which costs one bounded shrink-retry, never a wedge.\n];\n\n/**\n * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).\n * Error messages matching any of these are excluded from overflow detection\n * even if they also match an OVERFLOW_PATTERN.\n *\n * Example: Bedrock formats throttling errors as \"ThrottlingException: Too many tokens,\n * please wait before trying again.\" which would match the /too many tokens/i overflow\n * pattern without this exclusion.\n */\nconst NON_OVERFLOW_PATTERNS = [\n\t/^(Throttling error|Service unavailable):/i, // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)\n\t/rate limit/i, // Generic rate limiting\n\t/too many requests/i, // Generic HTTP 429 style\n];\n\n/**\n * Check if an assistant message represents a context overflow error.\n *\n * This handles three cases:\n * 1. Error-based overflow: Most providers return stopReason \"error\" with a\n * specific error message pattern.\n * 2. Silent overflow: Some providers accept overflow requests and return\n * successfully. For these, we check if usage.input exceeds the context window.\n * 3. Length-stop overflow: Xiaomi MiMo can return \"length\" with zero output when\n * the input fills the context window.\n *\n * ## Reliability by Provider\n *\n * **Reliable detection (returns error with detectable message):**\n * - Anthropic: \"prompt is too long: X tokens > Y maximum\" or \"request_too_large\"\n * - OpenAI (Completions & Responses): \"exceeds the context window\", \"exceeds the model's maximum context length of X tokens\", or \"exceeds model's maximum context length (X)\"\n * - Google Gemini: \"input token count exceeds the maximum\"\n * - xAI (Grok): \"maximum prompt length is X but request contains Y\"\n * - Groq: \"reduce the length of the messages\"\n * - Cerebras: 400/413 status code (no body)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - OpenRouter (most backends): \"maximum context length is X tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"exceeds the available context size\"\n * - LM Studio: \"greater than the context length\"\n * - Kimi For Coding: \"exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - DashScope/Qwen: \"Range of input length should be [1, X]\"\n *\n * **Unreliable detection:**\n * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),\n * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.\n * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason \"length\" with\n * output=0. Pass contextWindow param to detect via the \"filled context + zero output\" signal.\n * - Ollama: May truncate input silently for some setups, but may also return explicit\n * overflow errors that match the patterns above. Silent truncation still cannot be\n * detected here because we do not know the expected token count.\n *\n * ## Custom Providers\n *\n * If you've added custom models via settings.json, this function may not detect\n * overflow errors from those providers. To add support:\n *\n * 1. Send a request that exceeds the model's context window\n * 2. Check the errorMessage in the response\n * 3. Create a regex pattern that matches the error\n * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or\n * check the errorMessage yourself before calling this function\n *\n * @param message - The assistant message to check\n * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)\n * @returns true if the message indicates a context overflow\n */\nexport function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean {\n\t// Case 1: Check error message patterns\n\tif (message.stopReason === \"error\" && message.errorMessage) {\n\t\t// Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)\n\t\tconst isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!));\n\t\tif (!isNonOverflow && OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!))) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 2: Silent overflow (z.ai style) - successful but usage exceeds context\n\tif (contextWindow && message.stopReason === \"stop\") {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens > contextWindow) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 3: Length-stop overflow (Xiaomi MiMo style) - server truncates oversized input\n\t// to fit the context window, leaving no room for output. Returns stopReason \"length\"\n\t// with output=0 and input+cacheRead filling the context window.\n\tif (contextWindow && message.stopReason === \"length\" && message.usage.output === 0) {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens >= contextWindow * 0.99) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n/**\n * Check whether a length stop ended below the caller or model's intended output limit.\n * Such responses may be caused by context pressure or provider-side truncation, so callers\n * can make one bounded compact-and-retry attempt. `desiredMaxOutput` must be the original\n * limit before any context-based clamping.\n */\nexport function isRecoverableLength(message: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn message.stopReason === \"length\" && desiredMaxOutput > 0 && message.usage.output < desiredMaxOutput;\n}\n\n/**\n * Get the overflow patterns for testing purposes.\n */\nexport function getOverflowPatterns(): RegExp[] {\n\treturn [...OVERFLOW_PATTERNS];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"overflow.js","sourceRoot":"","sources":["../../src/utils/overflow.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAM,iBAAiB,GAAG;IACzB,qBAAqB,EAAE,2BAA2B;IAClD,oBAAoB,EAAE,kDAAkD;IACxE,wCAAwC,EAAE,iBAAiB;IAC3D,6BAA6B,EAAE,uCAAuC;IACtE,4FAA4F,EAAE,sCAAsC;IACpI,yCAAyC,EAAE,kBAAkB;IAC7D,+BAA+B,EAAE,aAAa;IAC9C,oCAAoC,EAAE,OAAO;IAC7C,uCAAuC,EAAE,6BAA6B;IACtE,kEAAkE,EAAE,sBAAsB;IAC1F,iFAAiF,EAAE,cAAc;IACjG,2BAA2B,EAAE,iBAAiB;IAC9C,qCAAqC,EAAE,mBAAmB;IAC1D,kCAAkC,EAAE,YAAY;IAChD,+BAA+B,EAAE,UAAU;IAC3C,6BAA6B,EAAE,kBAAkB;IACjD,sDAAsD,EAAE,UAAU;IAClE,+EAA+E,EAAE,aAAa;IAC9F,gCAAgC,EAAE,yDAAyD;IAC3F,oDAAoD,EAAE,iCAAiC;IACvF,kCAAkC,EAAE,8BAA8B;IAClE,gCAAgC,EAAE,mBAAmB;IACrD,kBAAkB,EAAE,mBAAmB;IACvC,uBAAuB,EAAE,mBAAmB;IAC5C,+CAA+C,EAAE,iCAAiC;IAClF,0DAA0D,EAAE,4UAA4U;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AC;QACpD,MAAM,WAAW,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;QAClE,IAAI,WAAW,GAAG,aAAa,EAAE,CAAC;YACjC,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAED,sFAAsF;IACtF,qFAAqF;IACrF,gEAAgE;IAChE,IAAI,aAAa,IAAI,OAAO,CAAC,UAAU,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACpF,MAAM,WAAW,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;QAClE,IAAI,WAAW,IAAI,aAAa,GAAG,IAAI,EAAE,CAAC;YACzC,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC;AACd,CAAC;AACD;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAyB,EAAE,gBAAwB;IACtF,OAAO,OAAO,CAAC,UAAU,KAAK,QAAQ,IAAI,gBAAgB,GAAG,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,GAAG,gBAAgB,CAAC;AAC3G,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB;IAClC,OAAO,CAAC,GAAG,iBAAiB,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\n\n/**\n * Regex patterns to detect context overflow errors from different providers.\n *\n * These patterns match error messages returned when the input exceeds\n * the model's context window.\n *\n * Provider-specific patterns (with example error messages):\n *\n * - Anthropic: \"prompt is too long: 213462 tokens > 200000 maximum\"\n * - Anthropic: \"413 {\\\"error\\\":{\\\"type\\\":\\\"request_too_large\\\",\\\"message\\\":\\\"Request exceeds the maximum size\\\"}}\"\n * - OpenAI: \"Your input exceeds the context window of this model\"\n * - OpenAI/LiteLLM: \"Requested token count exceeds the model's maximum context length of 131072 tokens\"\n * - OpenAI-compatible: \"Input length (265330) exceeds model's maximum context length (262144).\"\n * - Google: \"The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)\"\n * - xAI: \"This model's maximum prompt length is 131072 but the request contains 537812 tokens\"\n * - Groq: \"Please reduce the length of the messages or completion\"\n * - OpenRouter: \"This endpoint's maximum context length is X tokens. However, you requested about Y tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"the request exceeds the available context size, try increasing it\"\n * - LM Studio: \"tokens to keep from the initial prompt is greater than the context length\"\n * - GitHub Copilot: \"prompt token count of X exceeds the limit of Y\"\n * - MiniMax: \"invalid params, context window exceeds limit\"\n * - Kimi For Coding: \"Your request exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - Cerebras: \"400/413 status code (no body)\"\n * - Gateways: \"413 Request body too large\" / \"Request Entity Too Large\" / \"Payload Too Large\" (byte-size overflow)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - z.ai: Does NOT error, accepts overflow silently - handled via usage.input > contextWindow\n * - Xiaomi MiMo: Truncates input to fill contextWindow exactly, then returns finish_reason \"length\"\n * with output=0 (no room left to generate). Detected via stopReason \"length\" + zero output +\n * input filling the context window.\n * - DashScope/Qwen: \"Range of input length should be [1, X]\" (HTTP 400 invalid_parameter_error)\n * - Ollama: Some deployments truncate silently, others return errors like \"prompt too long; exceeded max context length by X tokens\"\n */\nconst OVERFLOW_PATTERNS = [\n\t/prompt is too long/i, // Anthropic token overflow\n\t/request_too_large/i, // Anthropic request byte-size overflow (HTTP 413)\n\t/input is too long for requested model/i, // Amazon Bedrock\n\t/exceeds the context window/i, // OpenAI (Completions & Responses API)\n\t/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\\d,]+ tokens?|\\s*\\([\\d,]+\\))/i, // OpenAI-compatible proxies (LiteLLM)\n\t/input token count.*exceeds the maximum/i, // Google (Gemini)\n\t/maximum prompt length is \\d+/i, // xAI (Grok)\n\t/reduce the length of the messages/i, // Groq\n\t/maximum context length is \\d+ tokens/i, // OpenRouter (most backends)\n\t/exceeds (?:the )?maximum allowed input length of [\\d,]+ tokens?/i, // OpenRouter/Poolside\n\t/input \\(\\d+ tokens\\) is longer than the model'?s context length \\(\\d+ tokens\\)/i, // Together AI\n\t/exceeds the limit of \\d+/i, // GitHub Copilot\n\t/exceeds the available context size/i, // llama.cpp server\n\t/greater than the context length/i, // LM Studio\n\t/context window exceeds limit/i, // MiniMax\n\t/exceeded model token limit/i, // Kimi For Coding\n\t/too large for model with \\d+ maximum context length/i, // Mistral\n\t/prompt has [\\d,]+ tokens?, but the configured context size is [\\d,]+ tokens?/i, // DS4 server\n\t/model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text\n\t/prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow error\n\t/range of input length should be/i, // DashScope / Qwen Token Plan\n\t/context[_ ]length[_ ]exceeded/i, // Generic fallback\n\t/too many tokens/i, // Generic fallback\n\t/token limit exceeded/i, // Generic fallback\n\t/^4(?:00|13)\\s*(?:status code)?\\s*\\(no body\\)/i, // Cerebras: 400/413 with no body\n\t/(?:request[ _])?(?:body|entity|payload)[_ ]too[_ ]large/i, // Gateway HTTP 413 byte-size rejections (\"Request body too large\", \"Request Entity Too Large\", \"body_too_large\", \"Payload Too Large\"). Substring-anchored by design (JSON bodies lack an adjacent status code); a non-context size rejection (e.g. an oversized image) can over-match, which costs one bounded shrink-retry, never a wedge.\n];\n\n/**\n * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).\n * Error messages matching any of these are excluded from overflow detection\n * even if they also match an OVERFLOW_PATTERN.\n *\n * Example: Bedrock formats throttling errors as \"ThrottlingException: Too many tokens,\n * please wait before trying again.\" which would match the /too many tokens/i overflow\n * pattern without this exclusion.\n */\nconst NON_OVERFLOW_PATTERNS = [\n\t/^(Throttling error|Service unavailable):/i, // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)\n\t/rate limit/i, // Generic rate limiting\n\t/too many requests/i, // Generic HTTP 429 style\n];\n\n/**\n * Cursor's api2.cursor.sh surfaces a context overflow as a bare gRPC\n * `resource_exhausted` end-stream — the same wording its backend uses for\n * quota and poisoned-conversation rejections. Token evidence disambiguates:\n * a request that already streamed or billed tokens overflowed mid-flight,\n * while a zero-token rejection is a quota/conversation failure that must stay\n * on the rate-limit path (the cursor client rotates the conversation id for\n * those and retry handling supplies the backoff).\n */\nconst RESOURCE_EXHAUSTED_PATTERN = /resource.?exhausted/i;\n\n/**\n * Check if an assistant message represents a context overflow error.\n *\n * This handles three cases:\n * 1. Error-based overflow: Most providers return stopReason \"error\" with a\n * specific error message pattern.\n * 2. Silent overflow: Some providers accept overflow requests and return\n * successfully. For these, we check if usage.input exceeds the context window.\n * 3. Length-stop overflow: Xiaomi MiMo can return \"length\" with zero output when\n * the input fills the context window.\n *\n * ## Reliability by Provider\n *\n * **Reliable detection (returns error with detectable message):**\n * - Anthropic: \"prompt is too long: X tokens > Y maximum\" or \"request_too_large\"\n * - OpenAI (Completions & Responses): \"exceeds the context window\", \"exceeds the model's maximum context length of X tokens\", or \"exceeds model's maximum context length (X)\"\n * - Google Gemini: \"input token count exceeds the maximum\"\n * - xAI (Grok): \"maximum prompt length is X but request contains Y\"\n * - Groq: \"reduce the length of the messages\"\n * - Cerebras: 400/413 status code (no body)\n * - Mistral: \"Prompt contains X tokens ... too large for model with Y maximum context length\"\n * - OpenRouter (most backends): \"maximum context length is X tokens\"\n * - OpenRouter/Poolside: \"Input length X exceeds the maximum allowed input length of Y tokens.\"\n * - Together AI: \"The input (X tokens) is longer than the model's context length (Y tokens).\"\n * - llama.cpp: \"exceeds the available context size\"\n * - LM Studio: \"greater than the context length\"\n * - Kimi For Coding: \"exceeded model token limit: X (requested: Y)\"\n * - DS4: \"Prompt has X tokens, but the configured context size is Y tokens\"\n * - DashScope/Qwen: \"Range of input length should be [1, X]\"\n *\n * **Unreliable detection:**\n * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),\n * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow.\n * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason \"length\" with\n * output=0. Pass contextWindow param to detect via the \"filled context + zero output\" signal.\n * - Ollama: May truncate input silently for some setups, but may also return explicit\n * overflow errors that match the patterns above. Silent truncation still cannot be\n * detected here because we do not know the expected token count.\n *\n * ## Custom Providers\n *\n * If you've added custom models via settings.json, this function may not detect\n * overflow errors from those providers. To add support:\n *\n * 1. Send a request that exceeds the model's context window\n * 2. Check the errorMessage in the response\n * 3. Create a regex pattern that matches the error\n * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or\n * check the errorMessage yourself before calling this function\n *\n * @param message - The assistant message to check\n * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)\n * @returns true if the message indicates a context overflow\n */\nexport function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean {\n\t// Case 1: Check error message patterns\n\tif (message.stopReason === \"error\" && message.errorMessage) {\n\t\t// Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)\n\t\tconst isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!));\n\t\tif (!isNonOverflow && OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!))) {\n\t\t\treturn true;\n\t\t}\n\t\tconst usage = message.usage;\n\t\tconst hasTokenEvidence =\n\t\t\t(usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite) > 0;\n\t\tif (!isNonOverflow && hasTokenEvidence && RESOURCE_EXHAUSTED_PATTERN.test(message.errorMessage)) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 2: Silent overflow (z.ai style) - successful but usage exceeds context\n\tif (contextWindow && message.stopReason === \"stop\") {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens > contextWindow) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// Case 3: Length-stop overflow (Xiaomi MiMo style) - server truncates oversized input\n\t// to fit the context window, leaving no room for output. Returns stopReason \"length\"\n\t// with output=0 and input+cacheRead filling the context window.\n\tif (contextWindow && message.stopReason === \"length\" && message.usage.output === 0) {\n\t\tconst inputTokens = message.usage.input + message.usage.cacheRead;\n\t\tif (inputTokens >= contextWindow * 0.99) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n/**\n * Check whether a length stop ended below the caller or model's intended output limit.\n * Such responses may be caused by context pressure or provider-side truncation, so callers\n * can make one bounded compact-and-retry attempt. `desiredMaxOutput` must be the original\n * limit before any context-based clamping.\n */\nexport function isRecoverableLength(message: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn message.stopReason === \"length\" && desiredMaxOutput > 0 && message.usage.output < desiredMaxOutput;\n}\n\n/**\n * Get the overflow patterns for testing purposes.\n */\nexport function getOverflowPatterns(): RegExp[] {\n\treturn [...OVERFLOW_PATTERNS];\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pi-user-agent.d.ts","sourceRoot":"","sources":["../../src/utils/pi-user-agent.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"pi-user-agent.d.ts","sourceRoot":"","sources":["../../src/utils/pi-user-agent.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAgBnD,wBAAgB,cAAc,IAAI,MAAM,CAEvC;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,eAAe,GAAG,IAAI,CAK/D"}
|
|
@@ -9,4 +9,11 @@ const nodeOs = loadNodeOs();
|
|
|
9
9
|
export function getPiUserAgent() {
|
|
10
10
|
return nodeOs ? `pi (${nodeOs.platform()} ${nodeOs.release()}; ${nodeOs.arch()})` : "pi (browser)";
|
|
11
11
|
}
|
|
12
|
+
export function forcePiUserAgent(headers) {
|
|
13
|
+
for (const name of Object.keys(headers)) {
|
|
14
|
+
if (name.toLowerCase() === "user-agent")
|
|
15
|
+
delete headers[name];
|
|
16
|
+
}
|
|
17
|
+
headers["User-Agent"] = getPiUserAgent();
|
|
18
|
+
}
|
|
12
19
|
//# sourceMappingURL=pi-user-agent.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pi-user-agent.js","sourceRoot":"","sources":["../../src/utils/pi-user-agent.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"pi-user-agent.js","sourceRoot":"","sources":["../../src/utils/pi-user-agent.ts"],"names":[],"mappings":"AAOA,SAAS,UAAU;IAClB,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,IAAI,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,EAAE,CAAC;QAC1F,OAAO,IAAI,CAAC;IACb,CAAC;IACD,OAAQ,OAAsC,CAAC,gBAAgB,EAAE,CAAC,SAAS,CAAC,IAAI,IAAI,CAAC;AACtF,CAAC;AAED,0GAA0G;AAC1G,MAAM,MAAM,GAAG,UAAU,EAAE,CAAC;AAE5B,MAAM,UAAU,cAAc;IAC7B,OAAO,MAAM,CAAC,CAAC,CAAC,OAAO,MAAM,CAAC,QAAQ,EAAE,IAAI,MAAM,CAAC,OAAO,EAAE,KAAK,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,cAAc,CAAC;AACpG,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,OAAwB;IACxD,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACzC,IAAI,IAAI,CAAC,WAAW,EAAE,KAAK,YAAY;YAAE,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,CAAC,YAAY,CAAC,GAAG,cAAc,EAAE,CAAC;AAC1C,CAAC","sourcesContent":["import type * as NodeOs from \"node:os\";\nimport type { ProviderHeaders } from \"../types.ts\";\n\ntype ProcessWithOsBuiltinModule = typeof process & {\n\tgetBuiltinModule?: (id: \"node:os\") => typeof NodeOs;\n};\n\nfunction loadNodeOs(): typeof NodeOs | null {\n\tif (typeof process === \"undefined\" || !(process.versions?.node || process.versions?.bun)) {\n\t\treturn null;\n\t}\n\treturn (process as ProcessWithOsBuiltinModule).getBuiltinModule?.(\"node:os\") ?? null;\n}\n\n// Keep runtime OS loading browser-safe. A top-level runtime import of node:os breaks browser/Vite builds.\nconst nodeOs = loadNodeOs();\n\nexport function getPiUserAgent(): string {\n\treturn nodeOs ? `pi (${nodeOs.platform()} ${nodeOs.release()}; ${nodeOs.arch()})` : \"pi (browser)\";\n}\n\nexport function forcePiUserAgent(headers: ProviderHeaders): void {\n\tfor (const name of Object.keys(headers)) {\n\t\tif (name.toLowerCase() === \"user-agent\") delete headers[name];\n\t}\n\theaders[\"User-Agent\"] = getPiUserAgent();\n}\n"]}
|
|
@@ -3,7 +3,7 @@ export declare const PROMPT_CACHE_TTL_SHORT_SECONDS = 300;
|
|
|
3
3
|
export declare const PROMPT_CACHE_TTL_LONG_SECONDS = 3600;
|
|
4
4
|
export declare function isAnthropicApiBaseUrl(baseUrl: string): boolean;
|
|
5
5
|
export declare function getAnthropicCompat(model: Model<"anthropic-messages">): Required<Omit<AnthropicMessagesCompat, "forceAdaptiveThinking">>;
|
|
6
|
-
export type ResolvedOpenAICompletionsCompat = Omit<Required<OpenAICompletionsCompat>, "cacheControlFormat" | "toolCallFormat" | "deferredToolsMode" | "toolSchemaFlavor" | "supportsPromptCacheKey" | "chatTemplateArgs" | "supportsThinkingTokenBudget"> & {
|
|
6
|
+
export type ResolvedOpenAICompletionsCompat = Omit<Required<OpenAICompletionsCompat>, "cacheControlFormat" | "toolCallFormat" | "deferredToolsMode" | "toolSchemaFlavor" | "supportsPromptCacheKey" | "chatTemplateArgs" | "supportsThinkingTokenBudget" | "thinkingTokenBudgetField"> & {
|
|
7
7
|
cacheControlFormat?: OpenAICompletionsCompat["cacheControlFormat"];
|
|
8
8
|
supportsPromptCacheKey?: OpenAICompletionsCompat["supportsPromptCacheKey"];
|
|
9
9
|
toolCallFormat?: OpenAICompletionsCompat["toolCallFormat"];
|
|
@@ -11,6 +11,7 @@ export type ResolvedOpenAICompletionsCompat = Omit<Required<OpenAICompletionsCom
|
|
|
11
11
|
toolSchemaFlavor?: OpenAICompletionsCompat["toolSchemaFlavor"];
|
|
12
12
|
chatTemplateArgs?: OpenAICompletionsCompat["chatTemplateArgs"];
|
|
13
13
|
supportsThinkingTokenBudget?: OpenAICompletionsCompat["supportsThinkingTokenBudget"];
|
|
14
|
+
thinkingTokenBudgetField?: OpenAICompletionsCompat["thinkingTokenBudgetField"];
|
|
14
15
|
};
|
|
15
16
|
/**
|
|
16
17
|
* Get resolved compatibility settings for a model.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt-cache-ttl.d.ts","sourceRoot":"","sources":["../../src/utils/prompt-cache-ttl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,uBAAuB,EACvB,GAAG,EAEH,KAAK,EACL,uBAAuB,EACvB,WAAW,EACX,MAAM,aAAa,CAAC;AAGrB,eAAO,MAAM,8BAA8B,MAAM,CAAC;AAClD,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAM9D;AAkBD,wBAAgB,kBAAkB,CACjC,KAAK,EAAE,KAAK,CAAC,oBAAoB,CAAC,GAChC,QAAQ,CAAC,IAAI,CAAC,uBAAuB,EAAE,uBAAuB,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"prompt-cache-ttl.d.ts","sourceRoot":"","sources":["../../src/utils/prompt-cache-ttl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,uBAAuB,EACvB,GAAG,EAEH,KAAK,EACL,uBAAuB,EACvB,WAAW,E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gB,uBAAuB,CAAC,KAAK,EAAE,KAAK,CAAC,yBAAyB,CAAC,GAAG,OAAO,CAKxF;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,KAAK,CAAC,yBAAyB,CAAC,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,OAAO,CAmBzG;AAiDD,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,GAAG,SAAS,CA4CrG"}
|
|
@@ -41,6 +41,7 @@ export function getAnthropicCompat(model) {
|
|
|
41
41
|
supportsForcedToolChoice: model.compat?.supportsForcedToolChoice ?? !CLAUDE_FABLE_OR_MYTHOS_MODEL_ID.test(model.id),
|
|
42
42
|
allowEmptySignature: model.compat?.allowEmptySignature ?? false,
|
|
43
43
|
unsignedThinkingReplay: model.compat?.unsignedThinkingReplay ?? (model.compat?.allowEmptySignature ? "empty-signature" : "text"),
|
|
44
|
+
allowedFallbackModels: model.compat?.allowedFallbackModels ?? [],
|
|
44
45
|
supportsStrictTools: model.compat?.supportsStrictTools ?? false,
|
|
45
46
|
supportsToolReferences: model.compat?.supportsToolReferences ?? defaultSupportsToolReferences(model),
|
|
46
47
|
// Default: first-party Anthropic only. Anthropic-compatible providers
|
|
@@ -171,6 +172,7 @@ export function getOpenAICompletionsCompat(model) {
|
|
|
171
172
|
chatTemplateArgs: model.compat.chatTemplateArgs ?? detected.chatTemplateArgs,
|
|
172
173
|
zaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,
|
|
173
174
|
supportsThinkingTokenBudget: model.compat.supportsThinkingTokenBudget ?? detected.supportsThinkingTokenBudget,
|
|
175
|
+
thinkingTokenBudgetField: model.compat.thinkingTokenBudgetField ?? detected.thinkingTokenBudgetField,
|
|
174
176
|
supportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,
|
|
175
177
|
toolSchemaFlavor: model.compat.toolSchemaFlavor ?? detected.toolSchemaFlavor,
|
|
176
178
|
toolCallFormat: model.compat.toolCallFormat ?? detected.toolCallFormat,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt-cache-ttl.js","sourceRoot":"","sources":["../../src/utils/prompt-cache-ttl.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAExD,MAAM,CAAC,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAClD,MAAM,CAAC,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAElD,MAAM,UAAU,qBAAqB,CAAC,OAAe;IACpD,IAAI,CAAC;QACJ,OAAO,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,QAAQ,KAAK,mBAAmB,CAAC;IAC1D,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;AACF,CAAC;AAED,MAAM,+BAA+B,GAAG,kCAAkC,CAAC;AAE3E;;;;GAIG;AACH,SAAS,6BAA6B,CAAC,KAAkC;IACxE,IAAI,KAAK,CAAC,QAAQ,KAAK,WAAW,IAAI,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC;QAAE,OAAO,KAAK,CAAC;IAC/E,MAAM,OAAO,GAAG,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,uDAAuD,CAAC,CAAC;IACxF,IAAI,CAAC,OAAO;QAAE,OAAO,KAAK,CAAC;IAC3B,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IACjC,MAAM,KAAK,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3E,OAAO,KAAK,GAAG,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,I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AM;gBAAE,OAAO,SAAS,CAAC;YAC3C,MAAM,MAAM,GAAG,0BAA0B,CAAC,gBAAgB,CAAC,CAAC;YAC5D,IAAI,MAAM,CAAC,kBAAkB,KAAK,WAAW,EAAE,CAAC;gBAC/C,OAAO,SAAS,KAAK,MAAM,IAAI,MAAM,CAAC,0BAA0B;oBAC/D,CAAC,CAAC,6BAA6B;oBAC/B,CAAC,CAAC,8BAA8B,CAAC;YACnC,CAAC;YACD,OAAO,8BAA8B,CAAC;QACvC,CAAC;QACD,KAAK,kBAAkB,CAAC;QACxB,KAAK,wBAAwB,CAAC;QAC9B,KAAK,wBAAwB,CAAC,CAAC,CAAC;YAC/B,MAAM,SAAS,GAAG,oCAAoC,CAAC,KAAK,CAAC,cAAc,EAAE,GAAG,CAAC,CAAC;YAClF,OAAO,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,8BAA8B,CAAC;QAC1E,CAAC;QACD;YACC,OAAO,SAAS,CAAC;IACnB,CAAC;AACF,CAAC","sourcesContent":["import type {\n\tAnthropicMessagesCompat,\n\tApi,\n\tCacheRetention,\n\tModel,\n\tOpenAICompletionsCompat,\n\tProviderEnv,\n} from \"../types.ts\";\nimport { getProviderEnvValue } from \"./provider-env.ts\";\n\nexport const PROMPT_CACHE_TTL_SHORT_SECONDS = 300;\nexport const PROMPT_CACHE_TTL_LONG_SECONDS = 3600;\n\nexport function isAnthropicApiBaseUrl(baseUrl: string): boolean {\n\ttry {\n\t\treturn new URL(baseUrl).hostname === \"api.anthropic.com\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nconst CLAUDE_FABLE_OR_MYTHOS_MODEL_ID = /^claude-(?:fable|mythos)(?:-|$)/i;\n\n/**\n * Default for `supportsToolReferences`: first-party Anthropic models except\n * Haiku (rejects client-side tool_reference blocks) and models that predate\n * tool search (Claude 3.x, Opus/Sonnet 4.0, Opus 4.1).\n */\nfunction defaultSupportsToolReferences(model: Model<\"anthropic-messages\">): boolean {\n\tif (model.provider !== \"anthropic\" || model.id.includes(\"haiku\")) return false;\n\tconst version = model.id.match(/^claude-(?:opus|sonnet|fable)-(\\d+)(?:-(\\d+))?(?:-|$)/);\n\tif (!version) return false;\n\tconst major = Number(version[1]);\n\tconst minor = version[2] && version[2].length < 8 ? Number(version[2]) : 0;\n\treturn major > 4 || (major === 4 && minor >= 5);\n}\n\nexport function getAnthropicCompat(\n\tmodel: Model<\"anthropic-messages\">,\n): Required<Omit<AnthropicMessagesCompat, \"forceAdaptiveThinking\">> {\n\t// Auto-detect session affinity and cache control support from provider\n\tconst isFireworks = model.provider === \"fireworks\";\n\tconst isCloudflareAiGatewayAnthropic =\n\t\tmodel.provider === \"cloudflare-ai-gateway\" && model.baseUrl.includes(\"anthropic\");\n\tconst isXiaomi = model.provider === \"xiaomi\" || model.provider.startsWith(\"xiaomi-token-plan-\");\n\treturn {\n\t\tsupportsEagerToolInputStreaming: model.compat?.supportsEagerToolInputStreaming ?? !isFireworks,\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? !isFireworks,\n\t\tsendSessionAffinityHeaders:\n\t\t\tmodel.compat?.sendSessionAffinityHeaders ?? !!(isFireworks || isCloudflareAiGatewayAnthropic),\n\t\tsupportsCacheControlOnTools: model.compat?.supportsCacheControlOnTools ?? !isFireworks,\n\t\tsupportsDisabledThinking: model.compat?.supportsDisabledThinking ?? !isXiaomi,\n\t\tsupportsTemperature: model.compat?.supportsTemperature ?? true,\n\t\tsupportsToolChoice: model.compat?.supportsToolChoice ?? true,\n\t\tsupportsForcedToolChoice:\n\t\t\tmodel.compat?.supportsForcedToolChoice ?? !CLAUDE_FABLE_OR_MYTHOS_MODEL_ID.test(model.id),\n\t\tallowEmptySignature: model.compat?.allowEmptySignature ?? false,\n\t\tunsignedThinkingReplay:\n\t\t\tmodel.compat?.unsignedThinkingReplay ?? (model.compat?.allowEmptySignature ? \"empty-signature\" : \"text\"),\n\t\tsupportsStrictTools: model.compat?.supportsStrictTools ?? false,\n\t\tsupportsToolReferences: model.compat?.supportsToolReferences ?? defaultSupportsToolReferences(model),\n\t\t// Default: first-party Anthropic only. Anthropic-compatible providers\n\t\t// (kimi-coding, fireworks, copilot, gateways) may execute the server-side\n\t\t// search but reject the replayed server_tool_use / web_search_tool_result\n\t\t// blocks on the next request (kimi-coding 400s with `tool_call_id is not\n\t\t// found`).\n\t\tsupportsWebSearch: model.compat?.supportsWebSearch ?? isAnthropicApiBaseUrl(model.baseUrl),\n\t};\n}\n\nexport type ResolvedOpenAICompletionsCompat = Omit<\n\tRequired<OpenAICompletionsCompat>,\n\t| \"cacheControlFormat\"\n\t| \"toolCallFormat\"\n\t| \"deferredToolsMode\"\n\t| \"toolSchemaFlavor\"\n\t| \"supportsPromptCacheKey\"\n\t| \"chatTemplateArgs\"\n\t| \"supportsThinkingTokenBudget\"\n> & {\n\tcacheControlFormat?: OpenAICompletionsCompat[\"cacheControlFormat\"];\n\tsupportsPromptCacheKey?: OpenAICompletionsCompat[\"supportsPromptCacheKey\"];\n\ttoolCallFormat?: OpenAICompletionsCompat[\"toolCallFormat\"];\n\tdeferredToolsMode?: OpenAICompletionsCompat[\"deferredToolsMode\"];\n\ttoolSchemaFlavor?: OpenAICompletionsCompat[\"toolSchemaFlavor\"];\n\tchatTemplateArgs?: OpenAICompletionsCompat[\"chatTemplateArgs\"];\n\tsupportsThinkingTokenBudget?: OpenAICompletionsCompat[\"supportsThinkingTokenBudget\"];\n};\n\n/**\n * Detect compatibility settings from provider and baseUrl for known providers.\n * Provider takes precedence over URL-based detection since it's explicitly configured.\n * Returns a fully resolved OpenAICompletionsCompat object with all fields set.\n */\nfunction detectOpenAICompletionsCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst provider = model.provider;\n\tconst baseUrl = model.baseUrl;\n\n\tconst isZai =\n\t\tprovider === \"zai\" ||\n\t\tprovider === \"zai-coding-cn\" ||\n\t\tbaseUrl.includes(\"api.z.ai\") ||\n\t\tbaseUrl.includes(\"open.bigmodel.cn\");\n\tconst isTogether =\n\t\tprovider === \"together\" || baseUrl.includes(\"api.together.ai\") || baseUrl.includes(\"api.together.xyz\");\n\tconst isMoonshot = provider === \"moonshotai\" || provider === \"moonshotai-cn\" || baseUrl.includes(\"api.moonshot.\");\n\tconst isOpenRouter = provider === \"openrouter\" || baseUrl.includes(\"openrouter.ai\");\n\tconst isCloudflareWorkersAI = provider === \"cloudflare-workers-ai\" || baseUrl.includes(\"api.cloudflare.com\");\n\tconst isCloudflareAiGateway = provider === \"cloudflare-ai-gateway\" || baseUrl.includes(\"gateway.ai.cloudflare.com\");\n\tconst isNvidia = provider === \"nvidia\" || baseUrl.includes(\"integrate.api.nvidia.com\");\n\tconst isAntLing = provider === \"ant-ling\" || baseUrl.includes(\"api.ant-ling.com\");\n\tconst isDeepSeek = provider === \"deepseek\" || baseUrl.toLowerCase().includes(\"deepseek.com\");\n\n\tconst isNonStandard =\n\t\tisNvidia ||\n\t\tprovider === \"cerebras\" ||\n\t\tbaseUrl.includes(\"cerebras.ai\") ||\n\t\tprovider === \"xai\" ||\n\t\tbaseUrl.includes(\"api.x.ai\") ||\n\t\tisTogether ||\n\t\tbaseUrl.includes(\"chutes.ai\") ||\n\t\tisDeepSeek ||\n\t\tisZai ||\n\t\tisMoonshot ||\n\t\tprovider === \"opencode\" ||\n\t\tbaseUrl.includes(\"opencode.ai\") ||\n\t\tisCloudflareWorkersAI ||\n\t\tisCloudflareAiGateway ||\n\t\tisAntLing;\n\n\tconst useMaxTokens =\n\t\tbaseUrl.includes(\"chutes.ai\") ||\n\t\tisDeepSeek ||\n\t\tisMoonshot ||\n\t\tisCloudflareAiGateway ||\n\t\tisTogether ||\n\t\tisNvidia ||\n\t\tisAntLing ||\n\t\tisZai;\n\n\tconst isGrok = provider === \"xai\" || baseUrl.includes(\"api.x.ai\");\n\tconst isOpenRouterDeveloperRoleModel =\n\t\tisOpenRouter && (model.id.startsWith(\"anthropic/\") || model.id.startsWith(\"openai/\"));\n\tconst openRouterCacheControlPrefixes = [\"anthropic/\", \"qwen/\", \"google/\"];\n\tconst cacheControlModelId = model.id.startsWith(\"~\") ? model.id.slice(1) : model.id;\n\tconst supportsOpenRouterCacheControl = openRouterCacheControlPrefixes.some((prefix) =>\n\t\tcacheControlModelId.startsWith(prefix),\n\t);\n\tconst cacheControlFormat = provider === \"openrouter\" && supportsOpenRouterCacheControl ? \"anthropic\" : undefined;\n\n\treturn {\n\t\tsupportsStore: !isNonStandard,\n\t\tsupportsDeveloperRole: isOpenRouterDeveloperRoleModel || (!isNonStandard && !isOpenRouter),\n\t\tsupportsReasoningEffort:\n\t\t\t!isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia && !isAntLing,\n\t\tsupportsUsageInStreaming: true,\n\t\tsupportsFinishReason: true,\n\t\tmaxTokensField: useMaxTokens ? \"max_tokens\" : \"max_completion_tokens\",\n\t\trequiresToolResultName: false,\n\t\trequiresAssistantAfterToolResult: false,\n\t\trequiresThinkingAsText: false,\n\t\trequiresReasoningContentOnAssistantMessages: isDeepSeek,\n\t\tthinkingFormat: isDeepSeek\n\t\t\t? \"deepseek\"\n\t\t\t: isZai\n\t\t\t\t? \"zai\"\n\t\t\t\t: isTogether\n\t\t\t\t\t? \"together\"\n\t\t\t\t\t: isAntLing\n\t\t\t\t\t\t? \"ant-ling\"\n\t\t\t\t\t\t: isOpenRouter\n\t\t\t\t\t\t\t? \"openrouter\"\n\t\t\t\t\t\t\t: \"openai\",\n\t\topenRouterRouting: {},\n\t\tvercelGatewayRouting: {},\n\t\tchatTemplateKwargs: {},\n\t\tzaiToolStream: false,\n\t\tsupportsStrictMode: !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia,\n\t\ttoolSchemaFlavor: isMoonshot ? \"moonshot-mfjs\" : undefined,\n\t\tsupportsDisabledThinking: true,\n\t\ttoolCallFormat: undefined,\n\t\tsupportsOpenAIGrammarTools: false,\n\t\tcacheControlFormat,\n\t\tsendSessionAffinityHeaders: isOpenRouter,\n\t\tdeferredToolsMode: undefined,\n\t\tsessionAffinityFormat: isOpenRouter ? \"openrouter\" : \"openai\",\n\t\tsupportsPromptCacheKey: isMoonshot || baseUrl.includes(\"api.openai.com\"),\n\t\tsupportsLongCacheRetention: !(\n\t\t\tisTogether ||\n\t\t\tisCloudflareWorkersAI ||\n\t\t\tisCloudflareAiGateway ||\n\t\t\tisNvidia ||\n\t\t\tisAntLing\n\t\t),\n\t};\n}\n\n/**\n * Get resolved compatibility settings for a model.\n * Auto-detects from provider/URL then overrides with explicit model.compat.\n */\nexport function getOpenAICompletionsCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst detected = detectOpenAICompletionsCompat(model);\n\tif (!model.compat) return detected;\n\n\treturn {\n\t\tsupportsStore: model.compat.supportsStore ?? detected.supportsStore,\n\t\tsupportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,\n\t\tsupportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,\n\t\tsupportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,\n\t\tsupportsFinishReason: model.compat.supportsFinishReason ?? detected.supportsFinishReason,\n\t\tmaxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,\n\t\trequiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,\n\t\trequiresAssistantAfterToolResult:\n\t\t\tmodel.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,\n\t\trequiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,\n\t\trequiresReasoningContentOnAssistantMessages:\n\t\t\tmodel.compat.requiresReasoningContentOnAssistantMessages ??\n\t\t\tdetected.requiresReasoningContentOnAssistantMessages,\n\t\tthinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,\n\t\tsupportsDisabledThinking: model.compat.supportsDisabledThinking ?? detected.supportsDisabledThinking,\n\t\topenRouterRouting: model.compat.openRouterRouting ?? detected.openRouterRouting,\n\t\tvercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,\n\t\tchatTemplateKwargs: model.compat.chatTemplateKwargs ?? detected.chatTemplateKwargs,\n\t\tchatTemplateArgs: model.compat.chatTemplateArgs ?? detected.chatTemplateArgs,\n\t\tzaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,\n\t\tsupportsThinkingTokenBudget: model.compat.supportsThinkingTokenBudget ?? detected.supportsThinkingTokenBudget,\n\t\tsupportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,\n\t\ttoolSchemaFlavor: model.compat.toolSchemaFlavor ?? detected.toolSchemaFlavor,\n\t\ttoolCallFormat: model.compat.toolCallFormat ?? detected.toolCallFormat,\n\t\tsupportsOpenAIGrammarTools: model.compat.supportsOpenAIGrammarTools ?? detected.supportsOpenAIGrammarTools,\n\t\tcacheControlFormat: model.compat.cacheControlFormat ?? detected.cacheControlFormat,\n\t\tsendSessionAffinityHeaders: model.compat.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,\n\t\tdeferredToolsMode: model.compat.deferredToolsMode ?? detected.deferredToolsMode,\n\t\tsessionAffinityFormat: model.compat.sessionAffinityFormat ?? detected.sessionAffinityFormat,\n\t\tsupportsPromptCacheKey: model.compat.supportsPromptCacheKey ?? detected.supportsPromptCacheKey,\n\t\tsupportsLongCacheRetention: model.compat.supportsLongCacheRetention ?? detected.supportsLongCacheRetention,\n\t};\n}\n\nexport function getBedrockModelMatchCandidates(modelId: string, modelName?: string): string[] {\n\tconst values = modelName ? [modelId, modelName] : [modelId];\n\treturn values.flatMap((value) => {\n\t\tconst lower = value.toLowerCase();\n\t\treturn [lower, lower.replace(/[\\s_.:]+/g, \"-\")];\n\t});\n}\n\nexport function supportsOneHourCacheTtl(model: Model<\"bedrock-converse-stream\">): boolean {\n\tconst candidates = getBedrockModelMatchCandidates(model.id, model.name);\n\treturn candidates.some((candidate) =>\n\t\t[\"opus-4-5\", \"sonnet-4-5\", \"haiku-4-5\"].some((modelVersion) => candidate.includes(modelVersion)),\n\t);\n}\n\n/**\n * Check if the model supports prompt caching.\n * Supported: Claude 3.5 Haiku, Claude 3.7 Sonnet, Claude 4.x models, Claude 5 models\n *\n * For base models and system-defined inference profiles the model ID / ARN\n * contains the model name, so we can decide locally.\n *\n * For application inference profiles (whose ARNs don't contain the model name),\n * also checks model.name which is user-controlled via models.json or registerProvider.\n * As a last resort, set AWS_BEDROCK_FORCE_CACHE=1 to enable cache points.\n * Amazon Nova models have automatic caching and don't need explicit cache points.\n */\nexport function supportsPromptCaching(model: Model<\"bedrock-converse-stream\">, env?: ProviderEnv): boolean {\n\tconst candidates = getBedrockModelMatchCandidates(model.id, model.name);\n\n\tconst hasClaudeRef = candidates.some((s) => s.includes(\"claude\"));\n\tif (!hasClaudeRef) {\n\t\t// Application inference profiles don't contain the model name in the ARN.\n\t\t// Allow users to force cache points via environment variable.\n\t\tif (getProviderEnvValue(\"AWS_BEDROCK_FORCE_CACHE\", env) === \"1\") return true;\n\t\treturn false;\n\t}\n\t// Claude 5 models (fable-5, opus-5, sonnet-5)\n\tif (candidates.some((s) => s.includes(\"fable-5\") || s.includes(\"opus-5\") || s.includes(\"sonnet-5\"))) return true;\n\t// Claude 4.x models (opus-4, sonnet-4, haiku-4)\n\tif (candidates.some((s) => s.includes(\"-4-\"))) return true;\n\t// Claude 3.7 Sonnet\n\tif (candidates.some((s) => s.includes(\"claude-3-7-sonnet\"))) return true;\n\t// Claude 3.5 Haiku\n\tif (candidates.some((s) => s.includes(\"claude-3-5-haiku\"))) return true;\n\treturn false;\n}\n\nfunction resolveAnthropicCacheRetention(\n\tcacheRetention?: CacheRetention,\n\tenv?: ProviderEnv,\n\tfallback: CacheRetention = \"short\",\n): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION !== undefined) {\n\t\treturn \"short\";\n\t}\n\treturn fallback;\n}\n\nfunction resolveOpenAICompletionsCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction resolveBedrockCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction resolveOpenAIResponsesCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nexport function resolvePromptCacheTtlSeconds(model: Model<Api>, env?: ProviderEnv): number | undefined {\n\tswitch (model.api) {\n\t\tcase \"claude-sdk-oauth\":\n\t\t\t// The Claude SDK owns prompt caching for this lane and uses Anthropic's default 5m TTL.\n\t\t\treturn PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\tcase \"anthropic-messages\": {\n\t\t\tconst anthropicModel = model as Model<\"anthropic-messages\">;\n\t\t\tconst retention = resolveAnthropicCacheRetention(anthropicModel.cacheRetention, env, \"short\");\n\t\t\tif (retention === \"none\") return undefined;\n\t\t\treturn retention === \"long\" &&\n\t\t\t\tisAnthropicApiBaseUrl(anthropicModel.baseUrl) &&\n\t\t\t\tgetAnthropicCompat(anthropicModel).supportsLongCacheRetention\n\t\t\t\t? PROMPT_CACHE_TTL_LONG_SECONDS\n\t\t\t\t: PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tcase \"bedrock-converse-stream\": {\n\t\t\tconst bedrockModel = model as Model<\"bedrock-converse-stream\">;\n\t\t\tconst retention = resolveBedrockCacheRetention(bedrockModel.cacheRetention, env);\n\t\t\tif (retention === \"none\" || !supportsPromptCaching(bedrockModel, env)) return undefined;\n\t\t\treturn retention === \"long\" && supportsOneHourCacheTtl(bedrockModel)\n\t\t\t\t? PROMPT_CACHE_TTL_LONG_SECONDS\n\t\t\t\t: PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tcase \"openai-completions\": {\n\t\t\tconst completionsModel = model as Model<\"openai-completions\">;\n\t\t\tconst retention = resolveOpenAICompletionsCacheRetention(completionsModel.cacheRetention, env);\n\t\t\tif (retention === \"none\") return undefined;\n\t\t\tconst compat = getOpenAICompletionsCompat(completionsModel);\n\t\t\tif (compat.cacheControlFormat === \"anthropic\") {\n\t\t\t\treturn retention === \"long\" && compat.supportsLongCacheRetention\n\t\t\t\t\t? PROMPT_CACHE_TTL_LONG_SECONDS\n\t\t\t\t\t: PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t\t}\n\t\t\treturn PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tcase \"openai-responses\":\n\t\tcase \"openai-codex-responses\":\n\t\tcase \"azure-openai-responses\": {\n\t\t\tconst retention = resolveOpenAIResponsesCacheRetention(model.cacheRetention, env);\n\t\t\treturn retention === \"none\" ? undefined : PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"prompt-cache-ttl.js","sourceRoot":"","sources":["../../src/utils/prompt-cache-ttl.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAExD,MAAM,CAAC,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAClD,MAAM,CAAC,MAAM,6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I,MAAM,CAAC,0BAA0B;oBAC/D,CAAC,CAAC,6BAA6B;oBAC/B,CAAC,CAAC,8BAA8B,CAAC;YACnC,CAAC;YACD,OAAO,8BAA8B,CAAC;QACvC,CAAC;QACD,KAAK,kBAAkB,CAAC;QACxB,KAAK,wBAAwB,CAAC;QAC9B,KAAK,wBAAwB,CAAC,CAAC,CAAC;YAC/B,MAAM,SAAS,GAAG,oCAAoC,CAAC,KAAK,CAAC,cAAc,EAAE,GAAG,CAAC,CAAC;YAClF,OAAO,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,8BAA8B,CAAC;QAC1E,CAAC;QACD;YACC,OAAO,SAAS,CAAC;IACnB,CAAC;AACF,CAAC","sourcesContent":["import type {\n\tAnthropicMessagesCompat,\n\tApi,\n\tCacheRetention,\n\tModel,\n\tOpenAICompletionsCompat,\n\tProviderEnv,\n} from \"../types.ts\";\nimport { getProviderEnvValue } from \"./provider-env.ts\";\n\nexport const PROMPT_CACHE_TTL_SHORT_SECONDS = 300;\nexport const PROMPT_CACHE_TTL_LONG_SECONDS = 3600;\n\nexport function isAnthropicApiBaseUrl(baseUrl: string): boolean {\n\ttry {\n\t\treturn new URL(baseUrl).hostname === \"api.anthropic.com\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nconst CLAUDE_FABLE_OR_MYTHOS_MODEL_ID = /^claude-(?:fable|mythos)(?:-|$)/i;\n\n/**\n * Default for `supportsToolReferences`: first-party Anthropic models except\n * Haiku (rejects client-side tool_reference blocks) and models that predate\n * tool search (Claude 3.x, Opus/Sonnet 4.0, Opus 4.1).\n */\nfunction defaultSupportsToolReferences(model: Model<\"anthropic-messages\">): boolean {\n\tif (model.provider !== \"anthropic\" || model.id.includes(\"haiku\")) return false;\n\tconst version = model.id.match(/^claude-(?:opus|sonnet|fable)-(\\d+)(?:-(\\d+))?(?:-|$)/);\n\tif (!version) return false;\n\tconst major = Number(version[1]);\n\tconst minor = version[2] && version[2].length < 8 ? Number(version[2]) : 0;\n\treturn major > 4 || (major === 4 && minor >= 5);\n}\n\nexport function getAnthropicCompat(\n\tmodel: Model<\"anthropic-messages\">,\n): Required<Omit<AnthropicMessagesCompat, \"forceAdaptiveThinking\">> {\n\t// Auto-detect session affinity and cache control support from provider\n\tconst isFireworks = model.provider === \"fireworks\";\n\tconst isCloudflareAiGatewayAnthropic =\n\t\tmodel.provider === \"cloudflare-ai-gateway\" && model.baseUrl.includes(\"anthropic\");\n\tconst isXiaomi = model.provider === \"xiaomi\" || model.provider.startsWith(\"xiaomi-token-plan-\");\n\treturn {\n\t\tsupportsEagerToolInputStreaming: model.compat?.supportsEagerToolInputStreaming ?? !isFireworks,\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? !isFireworks,\n\t\tsendSessionAffinityHeaders:\n\t\t\tmodel.compat?.sendSessionAffinityHeaders ?? !!(isFireworks || isCloudflareAiGatewayAnthropic),\n\t\tsupportsCacheControlOnTools: model.compat?.supportsCacheControlOnTools ?? !isFireworks,\n\t\tsupportsDisabledThinking: model.compat?.supportsDisabledThinking ?? !isXiaomi,\n\t\tsupportsTemperature: model.compat?.supportsTemperature ?? true,\n\t\tsupportsToolChoice: model.compat?.supportsToolChoice ?? true,\n\t\tsupportsForcedToolChoice:\n\t\t\tmodel.compat?.supportsForcedToolChoice ?? !CLAUDE_FABLE_OR_MYTHOS_MODEL_ID.test(model.id),\n\t\tallowEmptySignature: model.compat?.allowEmptySignature ?? false,\n\t\tunsignedThinkingReplay:\n\t\t\tmodel.compat?.unsignedThinkingReplay ?? (model.compat?.allowEmptySignature ? \"empty-signature\" : \"text\"),\n\t\tallowedFallbackModels: model.compat?.allowedFallbackModels ?? [],\n\t\tsupportsStrictTools: model.compat?.supportsStrictTools ?? false,\n\t\tsupportsToolReferences: model.compat?.supportsToolReferences ?? defaultSupportsToolReferences(model),\n\t\t// Default: first-party Anthropic only. Anthropic-compatible providers\n\t\t// (kimi-coding, fireworks, copilot, gateways) may execute the server-side\n\t\t// search but reject the replayed server_tool_use / web_search_tool_result\n\t\t// blocks on the next request (kimi-coding 400s with `tool_call_id is not\n\t\t// found`).\n\t\tsupportsWebSearch: model.compat?.supportsWebSearch ?? isAnthropicApiBaseUrl(model.baseUrl),\n\t};\n}\n\nexport type ResolvedOpenAICompletionsCompat = Omit<\n\tRequired<OpenAICompletionsCompat>,\n\t| \"cacheControlFormat\"\n\t| \"toolCallFormat\"\n\t| \"deferredToolsMode\"\n\t| \"toolSchemaFlavor\"\n\t| \"supportsPromptCacheKey\"\n\t| \"chatTemplateArgs\"\n\t| \"supportsThinkingTokenBudget\"\n\t| \"thinkingTokenBudgetField\"\n> & {\n\tcacheControlFormat?: OpenAICompletionsCompat[\"cacheControlFormat\"];\n\tsupportsPromptCacheKey?: OpenAICompletionsCompat[\"supportsPromptCacheKey\"];\n\ttoolCallFormat?: OpenAICompletionsCompat[\"toolCallFormat\"];\n\tdeferredToolsMode?: OpenAICompletionsCompat[\"deferredToolsMode\"];\n\ttoolSchemaFlavor?: OpenAICompletionsCompat[\"toolSchemaFlavor\"];\n\tchatTemplateArgs?: OpenAICompletionsCompat[\"chatTemplateArgs\"];\n\tsupportsThinkingTokenBudget?: OpenAICompletionsCompat[\"supportsThinkingTokenBudget\"];\n\tthinkingTokenBudgetField?: OpenAICompletionsCompat[\"thinkingTokenBudgetField\"];\n};\n\n/**\n * Detect compatibility settings from provider and baseUrl for known providers.\n * Provider takes precedence over URL-based detection since it's explicitly configured.\n * Returns a fully resolved OpenAICompletionsCompat object with all fields set.\n */\nfunction detectOpenAICompletionsCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst provider = model.provider;\n\tconst baseUrl = model.baseUrl;\n\n\tconst isZai =\n\t\tprovider === \"zai\" ||\n\t\tprovider === \"zai-coding-cn\" ||\n\t\tbaseUrl.includes(\"api.z.ai\") ||\n\t\tbaseUrl.includes(\"open.bigmodel.cn\");\n\tconst isTogether =\n\t\tprovider === \"together\" || baseUrl.includes(\"api.together.ai\") || baseUrl.includes(\"api.together.xyz\");\n\tconst isMoonshot = provider === \"moonshotai\" || provider === \"moonshotai-cn\" || baseUrl.includes(\"api.moonshot.\");\n\tconst isOpenRouter = provider === \"openrouter\" || baseUrl.includes(\"openrouter.ai\");\n\tconst isCloudflareWorkersAI = provider === \"cloudflare-workers-ai\" || baseUrl.includes(\"api.cloudflare.com\");\n\tconst isCloudflareAiGateway = provider === \"cloudflare-ai-gateway\" || baseUrl.includes(\"gateway.ai.cloudflare.com\");\n\tconst isNvidia = provider === \"nvidia\" || baseUrl.includes(\"integrate.api.nvidia.com\");\n\tconst isAntLing = provider === \"ant-ling\" || baseUrl.includes(\"api.ant-ling.com\");\n\tconst isDeepSeek = provider === \"deepseek\" || baseUrl.toLowerCase().includes(\"deepseek.com\");\n\n\tconst isNonStandard =\n\t\tisNvidia ||\n\t\tprovider === \"cerebras\" ||\n\t\tbaseUrl.includes(\"cerebras.ai\") ||\n\t\tprovider === \"xai\" ||\n\t\tbaseUrl.includes(\"api.x.ai\") ||\n\t\tisTogether ||\n\t\tbaseUrl.includes(\"chutes.ai\") ||\n\t\tisDeepSeek ||\n\t\tisZai ||\n\t\tisMoonshot ||\n\t\tprovider === \"opencode\" ||\n\t\tbaseUrl.includes(\"opencode.ai\") ||\n\t\tisCloudflareWorkersAI ||\n\t\tisCloudflareAiGateway ||\n\t\tisAntLing;\n\n\tconst useMaxTokens =\n\t\tbaseUrl.includes(\"chutes.ai\") ||\n\t\tisDeepSeek ||\n\t\tisMoonshot ||\n\t\tisCloudflareAiGateway ||\n\t\tisTogether ||\n\t\tisNvidia ||\n\t\tisAntLing ||\n\t\tisZai;\n\n\tconst isGrok = provider === \"xai\" || baseUrl.includes(\"api.x.ai\");\n\tconst isOpenRouterDeveloperRoleModel =\n\t\tisOpenRouter && (model.id.startsWith(\"anthropic/\") || model.id.startsWith(\"openai/\"));\n\tconst openRouterCacheControlPrefixes = [\"anthropic/\", \"qwen/\", \"google/\"];\n\tconst cacheControlModelId = model.id.startsWith(\"~\") ? model.id.slice(1) : model.id;\n\tconst supportsOpenRouterCacheControl = openRouterCacheControlPrefixes.some((prefix) =>\n\t\tcacheControlModelId.startsWith(prefix),\n\t);\n\tconst cacheControlFormat = provider === \"openrouter\" && supportsOpenRouterCacheControl ? \"anthropic\" : undefined;\n\n\treturn {\n\t\tsupportsStore: !isNonStandard,\n\t\tsupportsDeveloperRole: isOpenRouterDeveloperRoleModel || (!isNonStandard && !isOpenRouter),\n\t\tsupportsReasoningEffort:\n\t\t\t!isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia && !isAntLing,\n\t\tsupportsUsageInStreaming: true,\n\t\tsupportsFinishReason: true,\n\t\tmaxTokensField: useMaxTokens ? \"max_tokens\" : \"max_completion_tokens\",\n\t\trequiresToolResultName: false,\n\t\trequiresAssistantAfterToolResult: false,\n\t\trequiresThinkingAsText: false,\n\t\trequiresReasoningContentOnAssistantMessages: isDeepSeek,\n\t\tthinkingFormat: isDeepSeek\n\t\t\t? \"deepseek\"\n\t\t\t: isZai\n\t\t\t\t? \"zai\"\n\t\t\t\t: isTogether\n\t\t\t\t\t? \"together\"\n\t\t\t\t\t: isAntLing\n\t\t\t\t\t\t? \"ant-ling\"\n\t\t\t\t\t\t: isOpenRouter\n\t\t\t\t\t\t\t? \"openrouter\"\n\t\t\t\t\t\t\t: \"openai\",\n\t\topenRouterRouting: {},\n\t\tvercelGatewayRouting: {},\n\t\tchatTemplateKwargs: {},\n\t\tzaiToolStream: false,\n\t\tsupportsStrictMode: !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia,\n\t\ttoolSchemaFlavor: isMoonshot ? \"moonshot-mfjs\" : undefined,\n\t\tsupportsDisabledThinking: true,\n\t\ttoolCallFormat: undefined,\n\t\tsupportsOpenAIGrammarTools: false,\n\t\tcacheControlFormat,\n\t\tsendSessionAffinityHeaders: isOpenRouter,\n\t\tdeferredToolsMode: undefined,\n\t\tsessionAffinityFormat: isOpenRouter ? \"openrouter\" : \"openai\",\n\t\tsupportsPromptCacheKey: isMoonshot || baseUrl.includes(\"api.openai.com\"),\n\t\tsupportsLongCacheRetention: !(\n\t\t\tisTogether ||\n\t\t\tisCloudflareWorkersAI ||\n\t\t\tisCloudflareAiGateway ||\n\t\t\tisNvidia ||\n\t\t\tisAntLing\n\t\t),\n\t};\n}\n\n/**\n * Get resolved compatibility settings for a model.\n * Auto-detects from provider/URL then overrides with explicit model.compat.\n */\nexport function getOpenAICompletionsCompat(model: Model<\"openai-completions\">): ResolvedOpenAICompletionsCompat {\n\tconst detected = detectOpenAICompletionsCompat(model);\n\tif (!model.compat) return detected;\n\n\treturn {\n\t\tsupportsStore: model.compat.supportsStore ?? detected.supportsStore,\n\t\tsupportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,\n\t\tsupportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,\n\t\tsupportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,\n\t\tsupportsFinishReason: model.compat.supportsFinishReason ?? detected.supportsFinishReason,\n\t\tmaxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,\n\t\trequiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,\n\t\trequiresAssistantAfterToolResult:\n\t\t\tmodel.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,\n\t\trequiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,\n\t\trequiresReasoningContentOnAssistantMessages:\n\t\t\tmodel.compat.requiresReasoningContentOnAssistantMessages ??\n\t\t\tdetected.requiresReasoningContentOnAssistantMessages,\n\t\tthinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,\n\t\tsupportsDisabledThinking: model.compat.supportsDisabledThinking ?? detected.supportsDisabledThinking,\n\t\topenRouterRouting: model.compat.openRouterRouting ?? detected.openRouterRouting,\n\t\tvercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,\n\t\tchatTemplateKwargs: model.compat.chatTemplateKwargs ?? detected.chatTemplateKwargs,\n\t\tchatTemplateArgs: model.compat.chatTemplateArgs ?? detected.chatTemplateArgs,\n\t\tzaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,\n\t\tsupportsThinkingTokenBudget: model.compat.supportsThinkingTokenBudget ?? detected.supportsThinkingTokenBudget,\n\t\tthinkingTokenBudgetField: model.compat.thinkingTokenBudgetField ?? detected.thinkingTokenBudgetField,\n\t\tsupportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,\n\t\ttoolSchemaFlavor: model.compat.toolSchemaFlavor ?? detected.toolSchemaFlavor,\n\t\ttoolCallFormat: model.compat.toolCallFormat ?? detected.toolCallFormat,\n\t\tsupportsOpenAIGrammarTools: model.compat.supportsOpenAIGrammarTools ?? detected.supportsOpenAIGrammarTools,\n\t\tcacheControlFormat: model.compat.cacheControlFormat ?? detected.cacheControlFormat,\n\t\tsendSessionAffinityHeaders: model.compat.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,\n\t\tdeferredToolsMode: model.compat.deferredToolsMode ?? detected.deferredToolsMode,\n\t\tsessionAffinityFormat: model.compat.sessionAffinityFormat ?? detected.sessionAffinityFormat,\n\t\tsupportsPromptCacheKey: model.compat.supportsPromptCacheKey ?? detected.supportsPromptCacheKey,\n\t\tsupportsLongCacheRetention: model.compat.supportsLongCacheRetention ?? detected.supportsLongCacheRetention,\n\t};\n}\n\nexport function getBedrockModelMatchCandidates(modelId: string, modelName?: string): string[] {\n\tconst values = modelName ? [modelId, modelName] : [modelId];\n\treturn values.flatMap((value) => {\n\t\tconst lower = value.toLowerCase();\n\t\treturn [lower, lower.replace(/[\\s_.:]+/g, \"-\")];\n\t});\n}\n\nexport function supportsOneHourCacheTtl(model: Model<\"bedrock-converse-stream\">): boolean {\n\tconst candidates = getBedrockModelMatchCandidates(model.id, model.name);\n\treturn candidates.some((candidate) =>\n\t\t[\"opus-4-5\", \"sonnet-4-5\", \"haiku-4-5\"].some((modelVersion) => candidate.includes(modelVersion)),\n\t);\n}\n\n/**\n * Check if the model supports prompt caching.\n * Supported: Claude 3.5 Haiku, Claude 3.7 Sonnet, Claude 4.x models, Claude 5 models\n *\n * For base models and system-defined inference profiles the model ID / ARN\n * contains the model name, so we can decide locally.\n *\n * For application inference profiles (whose ARNs don't contain the model name),\n * also checks model.name which is user-controlled via models.json or registerProvider.\n * As a last resort, set AWS_BEDROCK_FORCE_CACHE=1 to enable cache points.\n * Amazon Nova models have automatic caching and don't need explicit cache points.\n */\nexport function supportsPromptCaching(model: Model<\"bedrock-converse-stream\">, env?: ProviderEnv): boolean {\n\tconst candidates = getBedrockModelMatchCandidates(model.id, model.name);\n\n\tconst hasClaudeRef = candidates.some((s) => s.includes(\"claude\"));\n\tif (!hasClaudeRef) {\n\t\t// Application inference profiles don't contain the model name in the ARN.\n\t\t// Allow users to force cache points via environment variable.\n\t\tif (getProviderEnvValue(\"AWS_BEDROCK_FORCE_CACHE\", env) === \"1\") return true;\n\t\treturn false;\n\t}\n\t// Claude 5 models (fable-5, opus-5, sonnet-5)\n\tif (candidates.some((s) => s.includes(\"fable-5\") || s.includes(\"opus-5\") || s.includes(\"sonnet-5\"))) return true;\n\t// Claude 4.x models (opus-4, sonnet-4, haiku-4)\n\tif (candidates.some((s) => s.includes(\"-4-\"))) return true;\n\t// Claude 3.7 Sonnet\n\tif (candidates.some((s) => s.includes(\"claude-3-7-sonnet\"))) return true;\n\t// Claude 3.5 Haiku\n\tif (candidates.some((s) => s.includes(\"claude-3-5-haiku\"))) return true;\n\treturn false;\n}\n\nfunction resolveAnthropicCacheRetention(\n\tcacheRetention?: CacheRetention,\n\tenv?: ProviderEnv,\n\tfallback: CacheRetention = \"short\",\n): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION !== undefined) {\n\t\treturn \"short\";\n\t}\n\treturn fallback;\n}\n\nfunction resolveOpenAICompletionsCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction resolveBedrockCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction resolveOpenAIResponsesCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (getProviderEnvValue(\"PI_CACHE_RETENTION\", env) === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nexport function resolvePromptCacheTtlSeconds(model: Model<Api>, env?: ProviderEnv): number | undefined {\n\tswitch (model.api) {\n\t\tcase \"claude-sdk-oauth\":\n\t\t\t// The Claude SDK owns prompt caching for this lane and uses Anthropic's default 5m TTL.\n\t\t\treturn PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\tcase \"anthropic-messages\": {\n\t\t\tconst anthropicModel = model as Model<\"anthropic-messages\">;\n\t\t\tconst retention = resolveAnthropicCacheRetention(anthropicModel.cacheRetention, env, \"short\");\n\t\t\tif (retention === \"none\") return undefined;\n\t\t\treturn retention === \"long\" &&\n\t\t\t\tisAnthropicApiBaseUrl(anthropicModel.baseUrl) &&\n\t\t\t\tgetAnthropicCompat(anthropicModel).supportsLongCacheRetention\n\t\t\t\t? PROMPT_CACHE_TTL_LONG_SECONDS\n\t\t\t\t: PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tcase \"bedrock-converse-stream\": {\n\t\t\tconst bedrockModel = model as Model<\"bedrock-converse-stream\">;\n\t\t\tconst retention = resolveBedrockCacheRetention(bedrockModel.cacheRetention, env);\n\t\t\tif (retention === \"none\" || !supportsPromptCaching(bedrockModel, env)) return undefined;\n\t\t\treturn retention === \"long\" && supportsOneHourCacheTtl(bedrockModel)\n\t\t\t\t? PROMPT_CACHE_TTL_LONG_SECONDS\n\t\t\t\t: PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tcase \"openai-completions\": {\n\t\t\tconst completionsModel = model as Model<\"openai-completions\">;\n\t\t\tconst retention = resolveOpenAICompletionsCacheRetention(completionsModel.cacheRetention, env);\n\t\t\tif (retention === \"none\") return undefined;\n\t\t\tconst compat = getOpenAICompletionsCompat(completionsModel);\n\t\t\tif (compat.cacheControlFormat === \"anthropic\") {\n\t\t\t\treturn retention === \"long\" && compat.supportsLongCacheRetention\n\t\t\t\t\t? PROMPT_CACHE_TTL_LONG_SECONDS\n\t\t\t\t\t: PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t\t}\n\t\t\treturn PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tcase \"openai-responses\":\n\t\tcase \"openai-codex-responses\":\n\t\tcase \"azure-openai-responses\": {\n\t\t\tconst retention = resolveOpenAIResponsesCacheRetention(model.cacheRetention, env);\n\t\t\treturn retention === \"none\" ? undefined : PROMPT_CACHE_TTL_SHORT_SECONDS;\n\t\t}\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@earendil-works/pi-ai",
|
|
3
3
|
"private": true,
|
|
4
|
-
"version": "2026.8.
|
|
4
|
+
"version": "2026.8.19",
|
|
5
5
|
"description": "Unified LLM API with automatic model discovery and provider configuration",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "./dist/index.js",
|
|
@@ -74,10 +74,9 @@
|
|
|
74
74
|
"@anthropic-ai/sdk": "0.91.1",
|
|
75
75
|
"@aws-sdk/client-bedrock-runtime": "3.1095.0",
|
|
76
76
|
"@bufbuild/protobuf": "2.13.0",
|
|
77
|
-
"@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.8.
|
|
77
|
+
"@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.8.19",
|
|
78
78
|
"@google/genai": "2.13.0",
|
|
79
79
|
"@mistralai/mistralai": "2.5.0",
|
|
80
|
-
"@opentelemetry/api": "1.9.1",
|
|
81
80
|
"@smithy/node-http-handler": "4.9.11",
|
|
82
81
|
"@smithy/types": "4.16.1",
|
|
83
82
|
"chalk": "6.0.0",
|
|
@@ -34,8 +34,14 @@ export interface NativePtyCandidatePathOptions {
|
|
|
34
34
|
readonly execDir?: string;
|
|
35
35
|
}
|
|
36
36
|
export type NativePtyRequireBinding = (modulePath: string) => unknown;
|
|
37
|
+
/**
|
|
38
|
+
* Reports whether a candidate prebuild carries macOS `com.apple.quarantine`.
|
|
39
|
+
* Injectable so tests can exercise the guard without a quarantined artifact.
|
|
40
|
+
*/
|
|
41
|
+
export type NativePtyQuarantineProbe = (modulePath: string) => boolean;
|
|
37
42
|
export interface NativePtyLoaderOptions extends NativePtyCandidatePathOptions {
|
|
38
43
|
readonly requireBinding?: NativePtyRequireBinding;
|
|
44
|
+
readonly isQuarantined?: NativePtyQuarantineProbe;
|
|
39
45
|
}
|
|
40
46
|
export declare const NATIVE_PTY_PACKAGE_VERSION: string;
|
|
41
47
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../src/loader.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../src/loader.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,gBAAgB,GAAG,MAAM,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B,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,MAAM,uBAAuB,GAAG,CAAC,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC;AAEtE;;;GAGG;AACH,MAAM,MAAM,wBAAwB,GAAG,CAAC,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC;AAEvE,MAAM,WAAW,sBAAuB,SAAQ,6BAA6B;IAC5E,QAAQ,CAAC,cAAc,CAAC,EAAE,uBAAuB,CAAC;IAClD,QAAQ,CAAC,aAAa,CAAC,EAAE,wBAAwB,CAAC;CAClD;AAGD,eAAO,MAAM,0BAA0B,QAAuB,CAAC;AAC/D;;;;;;GAMG;AACH,eAAO,MAAM,sBAAsB,MAAM,CAAC;AAyB1C,wBAAgB,0BAA0B,CAAC,UAAU,GAAE,MAA+B,GAAG,MAAM,CAE9F;AAED,wBAAgB,sBAAsB,CACrC,QAAQ,GAAE,MAAM,CAAC,eAAe,GAAG;IAAE,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO,CAAA;CAAqB,GAC9E,gBAAgB,CAElB;AAED,wBAAgB,gBAAgB,CAAC,QAAQ,GAAE,MAAyB,EAAE,IAAI,GAAE,MAAqB,GAAG,MAAM,CAEzG;AAED,wBAAgB,0BAA0B,CAAC,OAAO,GAAE,6BAAkC,GAAG,SAAS,MAAM,EAAE,CAOzG;AAED,wBAAgB,aAAa,CAAC,OAAO,GAAE,sBAA2B,GAAG,mBAAmB,CA2CvF"}
|
|
@@ -2,6 +2,7 @@ import { readFileSync } from "node:fs";
|
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { isQuarantinedNativeFile } from "./quarantine.js";
|
|
5
6
|
export class NativePtySentinelMismatchError extends Error {
|
|
6
7
|
constructor(modulePath, expectedExport, actualExports) {
|
|
7
8
|
super(`@earendil-works/pi-pty native sentinel mismatch: expected ${expectedExport}() in ${modulePath}, exports=${actualExports.join(",") || "<none>"}`);
|
|
@@ -67,8 +68,18 @@ export function loadNativePty(options = {}) {
|
|
|
67
68
|
const host = getNativePtyHost(options.platform, options.arch);
|
|
68
69
|
const attemptedPaths = getNativePtyCandidatePaths({ ...options, runtime });
|
|
69
70
|
const requireBinding = options.requireBinding ?? cjsRequire;
|
|
71
|
+
const platform = options.platform ?? process.platform;
|
|
72
|
+
const isQuarantined = options.isQuarantined ?? (platform === "darwin" ? isQuarantinedNativeFile : undefined);
|
|
70
73
|
const causes = [];
|
|
71
74
|
for (const modulePath of attemptedPaths) {
|
|
75
|
+
// `dlopen()` on a quarantined, non-notarized addon hands control to Gatekeeper,
|
|
76
|
+
// which blocks the process behind a "could not verify ... free of malware" dialog
|
|
77
|
+
// instead of returning an error. Detect that state first and keep the diagnostic
|
|
78
|
+
// path, so the caller degrades to the pipe fallback rather than hanging.
|
|
79
|
+
if (isQuarantined?.(modulePath) === true) {
|
|
80
|
+
causes.push(`${modulePath}: blocked because com.apple.quarantine is present (macOS Gatekeeper)`);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
72
83
|
try {
|
|
73
84
|
const native = requireBinding(modulePath);
|
|
74
85
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader.js","sourceRoot":"","sources":["../src/loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AA6BzC,MAAM,OAAO,8BAA+B,SAAQ,KAAK;IAMxD,YAAY,UAAkB,EAAE,cAAsB,EAAE,aAAgC;QACvF,KAAK,CACJ,6DAA6D,cAAc,SAAS,UA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nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nexport type NativePtyRuntime = \"node\" | \"bun\";\n\nexport interface NativePtyBinding {\n\treadonly PtySession: unknown;\n\treadonly [exportName: string]: unknown;\n}\n\nexport interface NativePtyUnavailableDiagnostic {\n\treadonly code: \"native-unavailable\";\n\treadonly runtime: NativePtyRuntime;\n\treadonly host: string;\n\treadonly attemptedPath: string;\n\treadonly attemptedPaths: readonly string[];\n\treadonly message: string;\n\treadonly cause?: string;\n}\n\nexport type NativePtyLoadResult =\n\t| {\n\t\t\treadonly native: NativePtyBinding;\n\t\t\treadonly diagnostic: null;\n\t }\n\t| {\n\t\t\treadonly native: null;\n\t\t\treadonly diagnostic: NativePtyUnavailableDiagnostic;\n\t };\n\nexport class NativePtySentinelMismatchError extends Error {\n\treadonly code = \"native-sentinel-mismatch\";\n\treadonly modulePath: string;\n\treadonly expectedExport: string;\n\treadonly actualExports: readonly string[];\n\n\tconstructor(modulePath: string, expectedExport: string, actualExports: readonly string[]) {\n\t\tsuper(\n\t\t\t`@earendil-works/pi-pty native sentinel mismatch: expected ${expectedExport}() in ${modulePath}, exports=${actualExports.join(\",\") || \"<none>\"}`,\n\t\t);\n\t\tthis.name = \"NativePtySentinelMismatchError\";\n\t\tthis.modulePath = modulePath;\n\t\tthis.expectedExport = expectedExport;\n\t\tthis.actualExports = actualExports;\n\t}\n}\n\nexport interface NativePtyCandidatePathOptions {\n\treadonly runtime?: NativePtyRuntime;\n\treadonly platform?: string;\n\treadonly arch?: string;\n\treadonly moduleDir?: string;\n\treadonly execDir?: string;\n}\n\nexport type NativePtyRequireBinding = (modulePath: string) => unknown;\n\nexport interface NativePtyLoaderOptions extends NativePtyCandidatePathOptions {\n\treadonly requireBinding?: NativePtyRequireBinding;\n}\n\nconst cjsRequire = createRequire(import.meta.url);\nexport const NATIVE_PTY_PACKAGE_VERSION = readPackageVersion();\n/**\n * Native ABI version. INTENTIONALLY decoupled from the package/CalVer version: it\n * identifies the native surface (exports + signatures) this loader requires. Must\n * match `NATIVE_PTY_ABI_VERSION` and the `__senpiPtyAbi<N>` export in\n * `crates/senpi-pty/src/lib.rs`. Bump ONLY on a backward-incompatible native change\n * (and rebuild the vendored prebuilds); a CalVer release must NOT change it.\n */\nexport const NATIVE_PTY_ABI_VERSION = \"1\";\n\nfunction readPackageVersion(): string {\n\t// node/tsx/tarball layouts: the sibling `../package.json` resolves normally.\n\ttry {\n\t\tconst packageMetadata = cjsRequire(\"../package.json\");\n\t\tif (isRecord(packageMetadata) && typeof packageMetadata.version === \"string\") {\n\t\t\treturn packageMetadata.version;\n\t\t}\n\t} catch {\n\t\t// Compiled Bun binary: `../package.json` is not in the embedded FS. Fall through.\n\t}\n\t// Compiled Bun binary: the release ships package.json beside the executable. All\n\t// workspace packages are lockstep-versioned, so the sibling version matches pty's.\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(readFileSync(join(dirname(process.execPath), \"package.json\"), \"utf-8\"));\n\t\tif (isRecord(parsed) && typeof parsed.version === \"string\") {\n\t\t\treturn parsed.version;\n\t\t}\n\t} catch {\n\t\t// No readable sibling package.json either.\n\t}\n\tthrow new Error(\"@earendil-works/pi-pty package.json is missing a string version\");\n}\n\nexport function getNativePtySentinelExport(abiVersion: string = NATIVE_PTY_ABI_VERSION): string {\n\treturn `__senpiPtyAbi${abiVersion}`;\n}\n\nexport function detectNativePtyRuntime(\n\tversions: NodeJS.ProcessVersions & { readonly bun?: unknown } = process.versions,\n): NativePtyRuntime {\n\treturn typeof versions.bun === \"string\" ? \"bun\" : \"node\";\n}\n\nexport function getNativePtyHost(platform: string = process.platform, arch: string = process.arch): string {\n\treturn `${platform}-${arch}`;\n}\n\nexport function getNativePtyCandidatePaths(options: NativePtyCandidatePathOptions = {}): readonly string[] {\n\tconst host = getNativePtyHost(options.platform, options.arch);\n\tconst moduleDir = options.moduleDir ?? dirname(fileURLToPath(import.meta.url));\n\tconst execDir = options.execDir ?? dirname(process.execPath);\n\tconst nativePath = join(\"native\", \"prebuilds\", host, `senpi_pty.${host}.node`);\n\n\treturn [join(moduleDir, \"..\", nativePath), join(moduleDir, nativePath), join(execDir, nativePath)];\n}\n\nexport function loadNativePty(options: NativePtyLoaderOptions = {}): NativePtyLoadResult {\n\tconst runtime = options.runtime ?? detectNativePtyRuntime();\n\tconst host = getNativePtyHost(options.platform, options.arch);\n\tconst attemptedPaths = getNativePtyCandidatePaths({ ...options, runtime });\n\tconst requireBinding = options.requireBinding ?? cjsRequire;\n\tconst causes: string[] = [];\n\n\tfor (const modulePath of attemptedPaths) {\n\t\ttry {\n\t\t\tconst native = requireBinding(modulePath);\n\t\t\treturn {\n\t\t\t\tnative: assertNativePtyBinding(native, modulePath),\n\t\t\t\tdiagnostic: null,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (error instanceof NativePtySentinelMismatchError) throw error;\n\t\t\tcauses.push(formatErrorCause(modulePath, error));\n\t\t}\n\t}\n\n\treturn {\n\t\tnative: null,\n\t\tdiagnostic: {\n\t\t\tcode: \"native-unavailable\",\n\t\t\truntime,\n\t\t\thost,\n\t\t\tattemptedPath: attemptedPaths[0] ?? \"\",\n\t\t\tattemptedPaths,\n\t\t\tmessage: `No @earendil-works/pi-pty ${runtime} native prebuild is available for ${host}.`,\n\t\t\tcause: causes.join(\"; \"),\n\t\t},\n\t};\n}\n\nfunction assertNativePtyBinding(value: unknown, modulePath: string): NativePtyBinding {\n\tif (!isNativePtyBinding(value)) {\n\t\tthrow new NativePtySentinelMismatchError(modulePath, getNativePtySentinelExport(), []);\n\t}\n\n\tconst actualExports = Object.keys(value).sort();\n\tif (typeof value.PtySession !== \"function\") {\n\t\tthrow new NativePtySentinelMismatchError(modulePath, \"PtySession\", actualExports);\n\t}\n\n\tconst sentinelExport = getNativePtySentinelExport();\n\tconst sentinel = value[sentinelExport];\n\tif (!isUnknownFunction(sentinel)) {\n\t\tthrow new NativePtySentinelMismatchError(modulePath, sentinelExport, actualExports);\n\t}\n\n\tconst sentinelValue = sentinel();\n\tif (sentinelValue !== NATIVE_PTY_ABI_VERSION) {\n\t\tthrow new NativePtySentinelMismatchError(modulePath, sentinelExport, actualExports);\n\t}\n\n\treturn value;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction isNativePtyBinding(value: unknown): value is NativePtyBinding {\n\treturn isRecord(value) && typeof value.PtySession === \"function\";\n}\n\nfunction isUnknownFunction(value: unknown): value is () => unknown {\n\treturn typeof value === \"function\";\n}\n\nfunction formatErrorCause(modulePath: string, error: unknown): string {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn `${modulePath}: ${message}`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"loader.js","sourceRoot":"","sources":["../src/loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AA6B1D,MAAM,OAAO,8BAA+B,SAAQ,KAAK;IAMxD,YAAY,UAAkB,EAAE,cAAsB,EAAE,aAAgC;QACvF,KAAK,CACJ,6DAA6D,cAAc,SAAS,UAAU,aAAa,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,QAAQ,EAAE,CAChJ,CAAC;QARM,SAAI,GAAG,0BAA0B,CAAC;QAS1C,IAAI,CAAC,IAAI,GAAG,gCAAgC,CAAC;QAC7C,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;QACrC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACpC,CAAC;CACD;AAuBD,MAAM,UAAU,GAAG,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CAAC;IACvE,OAAO,GAAG,UAAU,KAAK,OAAO,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { isQuarantinedNativeFile } from \"./quarantine.ts\";\n\nexport type NativePtyRuntime = \"node\" | \"bun\";\n\nexport interface NativePtyBinding {\n\treadonly PtySession: unknown;\n\treadonly [exportName: string]: unknown;\n}\n\nexport interface NativePtyUnavailableDiagnostic {\n\treadonly code: \"native-unavailable\";\n\treadonly runtime: NativePtyRuntime;\n\treadonly host: string;\n\treadonly attemptedPath: string;\n\treadonly attemptedPaths: readonly string[];\n\treadonly message: string;\n\treadonly cause?: string;\n}\n\nexport type NativePtyLoadResult =\n\t| {\n\t\t\treadonly native: NativePtyBinding;\n\t\t\treadonly diagnostic: null;\n\t }\n\t| {\n\t\t\treadonly native: null;\n\t\t\treadonly diagnostic: NativePtyUnavailableDiagnostic;\n\t };\n\nexport class NativePtySentinelMismatchError extends Error {\n\treadonly code = \"native-sentinel-mismatch\";\n\treadonly modulePath: string;\n\treadonly expectedExport: string;\n\treadonly actualExports: readonly string[];\n\n\tconstructor(modulePath: string, expectedExport: string, actualExports: readonly string[]) {\n\t\tsuper(\n\t\t\t`@earendil-works/pi-pty native sentinel mismatch: expected ${expectedExport}() in ${modulePath}, exports=${actualExports.join(\",\") || \"<none>\"}`,\n\t\t);\n\t\tthis.name = \"NativePtySentinelMismatchError\";\n\t\tthis.modulePath = modulePath;\n\t\tthis.expectedExport = expectedExport;\n\t\tthis.actualExports = actualExports;\n\t}\n}\n\nexport interface NativePtyCandidatePathOptions {\n\treadonly runtime?: NativePtyRuntime;\n\treadonly platform?: string;\n\treadonly arch?: string;\n\treadonly moduleDir?: string;\n\treadonly execDir?: string;\n}\n\nexport type NativePtyRequireBinding = (modulePath: string) => unknown;\n\n/**\n * Reports whether a candidate prebuild carries macOS `com.apple.quarantine`.\n * Injectable so tests can exercise the guard without a quarantined artifact.\n */\nexport type NativePtyQuarantineProbe = (modulePath: string) => boolean;\n\nexport interface NativePtyLoaderOptions extends NativePtyCandidatePathOptions {\n\treadonly requireBinding?: NativePtyRequireBinding;\n\treadonly isQuarantined?: NativePtyQuarantineProbe;\n}\n\nconst cjsRequire = createRequire(import.meta.url);\nexport const NATIVE_PTY_PACKAGE_VERSION = readPackageVersion();\n/**\n * Native ABI version. INTENTIONALLY decoupled from the package/CalVer version: it\n * identifies the native surface (exports + signatures) this loader requires. Must\n * match `NATIVE_PTY_ABI_VERSION` and the `__senpiPtyAbi<N>` export in\n * `crates/senpi-pty/src/lib.rs`. Bump ONLY on a backward-incompatible native change\n * (and rebuild the vendored prebuilds); a CalVer release must NOT change it.\n */\nexport const NATIVE_PTY_ABI_VERSION = \"1\";\n\nfunction readPackageVersion(): string {\n\t// node/tsx/tarball layouts: the sibling `../package.json` resolves normally.\n\ttry {\n\t\tconst packageMetadata = cjsRequire(\"../package.json\");\n\t\tif (isRecord(packageMetadata) && typeof packageMetadata.version === \"string\") {\n\t\t\treturn packageMetadata.version;\n\t\t}\n\t} catch {\n\t\t// Compiled Bun binary: `../package.json` is not in the embedded FS. Fall through.\n\t}\n\t// Compiled Bun binary: the release ships package.json beside the executable. All\n\t// workspace packages are lockstep-versioned, so the sibling version matches pty's.\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(readFileSync(join(dirname(process.execPath), \"package.json\"), \"utf-8\"));\n\t\tif (isRecord(parsed) && typeof parsed.version === \"string\") {\n\t\t\treturn parsed.version;\n\t\t}\n\t} catch {\n\t\t// No readable sibling package.json either.\n\t}\n\tthrow new Error(\"@earendil-works/pi-pty package.json is missing a string version\");\n}\n\nexport function getNativePtySentinelExport(abiVersion: string = NATIVE_PTY_ABI_VERSION): string {\n\treturn `__senpiPtyAbi${abiVersion}`;\n}\n\nexport function detectNativePtyRuntime(\n\tversions: NodeJS.ProcessVersions & { readonly bun?: unknown } = process.versions,\n): NativePtyRuntime {\n\treturn typeof versions.bun === \"string\" ? \"bun\" : \"node\";\n}\n\nexport function getNativePtyHost(platform: string = process.platform, arch: string = process.arch): string {\n\treturn `${platform}-${arch}`;\n}\n\nexport function getNativePtyCandidatePaths(options: NativePtyCandidatePathOptions = {}): readonly string[] {\n\tconst host = getNativePtyHost(options.platform, options.arch);\n\tconst moduleDir = options.moduleDir ?? dirname(fileURLToPath(import.meta.url));\n\tconst execDir = options.execDir ?? dirname(process.execPath);\n\tconst nativePath = join(\"native\", \"prebuilds\", host, `senpi_pty.${host}.node`);\n\n\treturn [join(moduleDir, \"..\", nativePath), join(moduleDir, nativePath), join(execDir, nativePath)];\n}\n\nexport function loadNativePty(options: NativePtyLoaderOptions = {}): NativePtyLoadResult {\n\tconst runtime = options.runtime ?? detectNativePtyRuntime();\n\tconst host = getNativePtyHost(options.platform, options.arch);\n\tconst attemptedPaths = getNativePtyCandidatePaths({ ...options, runtime });\n\tconst requireBinding = options.requireBinding ?? cjsRequire;\n\tconst platform = options.platform ?? process.platform;\n\tconst isQuarantined = options.isQuarantined ?? (platform === \"darwin\" ? isQuarantinedNativeFile : undefined);\n\tconst causes: string[] = [];\n\n\tfor (const modulePath of attemptedPaths) {\n\t\t// `dlopen()` on a quarantined, non-notarized addon hands control to Gatekeeper,\n\t\t// which blocks the process behind a \"could not verify ... free of malware\" dialog\n\t\t// instead of returning an error. Detect that state first and keep the diagnostic\n\t\t// path, so the caller degrades to the pipe fallback rather than hanging.\n\t\tif (isQuarantined?.(modulePath) === true) {\n\t\t\tcauses.push(`${modulePath}: blocked because com.apple.quarantine is present (macOS Gatekeeper)`);\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst native = requireBinding(modulePath);\n\t\t\treturn {\n\t\t\t\tnative: assertNativePtyBinding(native, modulePath),\n\t\t\t\tdiagnostic: null,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (error instanceof NativePtySentinelMismatchError) throw error;\n\t\t\tcauses.push(formatErrorCause(modulePath, error));\n\t\t}\n\t}\n\n\treturn {\n\t\tnative: null,\n\t\tdiagnostic: {\n\t\t\tcode: \"native-unavailable\",\n\t\t\truntime,\n\t\t\thost,\n\t\t\tattemptedPath: attemptedPaths[0] ?? \"\",\n\t\t\tattemptedPaths,\n\t\t\tmessage: `No @earendil-works/pi-pty ${runtime} native prebuild is available for ${host}.`,\n\t\t\tcause: causes.join(\"; \"),\n\t\t},\n\t};\n}\n\nfunction assertNativePtyBinding(value: unknown, modulePath: string): NativePtyBinding {\n\tif (!isNativePtyBinding(value)) {\n\t\tthrow new NativePtySentinelMismatchError(modulePath, getNativePtySentinelExport(), []);\n\t}\n\n\tconst actualExports = Object.keys(value).sort();\n\tif (typeof value.PtySession !== \"function\") {\n\t\tthrow new NativePtySentinelMismatchError(modulePath, \"PtySession\", actualExports);\n\t}\n\n\tconst sentinelExport = getNativePtySentinelExport();\n\tconst sentinel = value[sentinelExport];\n\tif (!isUnknownFunction(sentinel)) {\n\t\tthrow new NativePtySentinelMismatchError(modulePath, sentinelExport, actualExports);\n\t}\n\n\tconst sentinelValue = sentinel();\n\tif (sentinelValue !== NATIVE_PTY_ABI_VERSION) {\n\t\tthrow new NativePtySentinelMismatchError(modulePath, sentinelExport, actualExports);\n\t}\n\n\treturn value;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction isNativePtyBinding(value: unknown): value is NativePtyBinding {\n\treturn isRecord(value) && typeof value.PtySession === \"function\";\n}\n\nfunction isUnknownFunction(value: unknown): value is () => unknown {\n\treturn typeof value === \"function\";\n}\n\nfunction formatErrorCause(modulePath: string, error: unknown): string {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn `${modulePath}: ${message}`;\n}\n"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export declare const QUARANTINE_ATTRIBUTE = "com.apple.quarantine";
|
|
2
|
+
/**
|
|
3
|
+
* SECURITY: `dlopen()` on a quarantined, non-notarized addon hands control to
|
|
4
|
+
* Gatekeeper, which suspends the process behind an "Apple could not verify ... is
|
|
5
|
+
* free of malware" dialog instead of returning an error. Senpi's prebuilds carry
|
|
6
|
+
* only a linker ad-hoc signature, so a quarantined prebuild is never auto-approved.
|
|
7
|
+
* Detection MUST NOT become removal: clearing the attribute would silently defeat
|
|
8
|
+
* the user's malware protection.
|
|
9
|
+
*
|
|
10
|
+
* Node exposes no `getxattr` binding, so `xattr -p` is the only available channel;
|
|
11
|
+
* it exits 0 only when the attribute is present. Any spawn failure returns `false`
|
|
12
|
+
* so an unreadable attribute never rejects an otherwise loadable prebuild.
|
|
13
|
+
*/
|
|
14
|
+
export declare function isQuarantinedNativeFile(modulePath: string, platform?: string): boolean;
|
|
15
|
+
//# sourceMappingURL=quarantine.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"quarantine.d.ts","sourceRoot":"","sources":["../src/quarantine.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,oBAAoB,yBAAyB,CAAC;AAE3D;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,GAAE,MAAyB,GAAG,OAAO,CAUxG"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
export const QUARANTINE_ATTRIBUTE = "com.apple.quarantine";
|
|
4
|
+
/**
|
|
5
|
+
* SECURITY: `dlopen()` on a quarantined, non-notarized addon hands control to
|
|
6
|
+
* Gatekeeper, which suspends the process behind an "Apple could not verify ... is
|
|
7
|
+
* free of malware" dialog instead of returning an error. Senpi's prebuilds carry
|
|
8
|
+
* only a linker ad-hoc signature, so a quarantined prebuild is never auto-approved.
|
|
9
|
+
* Detection MUST NOT become removal: clearing the attribute would silently defeat
|
|
10
|
+
* the user's malware protection.
|
|
11
|
+
*
|
|
12
|
+
* Node exposes no `getxattr` binding, so `xattr -p` is the only available channel;
|
|
13
|
+
* it exits 0 only when the attribute is present. Any spawn failure returns `false`
|
|
14
|
+
* so an unreadable attribute never rejects an otherwise loadable prebuild.
|
|
15
|
+
*/
|
|
16
|
+
export function isQuarantinedNativeFile(modulePath, platform = process.platform) {
|
|
17
|
+
if (platform !== "darwin")
|
|
18
|
+
return false;
|
|
19
|
+
if (!existsSync(modulePath))
|
|
20
|
+
return false;
|
|
21
|
+
const probe = spawnSync("/usr/bin/xattr", ["-p", QUARANTINE_ATTRIBUTE, modulePath], {
|
|
22
|
+
stdio: ["ignore", "ignore", "ignore"],
|
|
23
|
+
timeout: 2000,
|
|
24
|
+
});
|
|
25
|
+
return probe.error === undefined && probe.status === 0;
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=quarantine.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"quarantine.js","sourceRoot":"","sources":["../src/quarantine.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAErC,MAAM,CAAC,MAAM,oBAAoB,GAAG,sBAAsB,CAAC;AAE3D;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,uBAAuB,CAAC,UAAkB,EAAE,WAAmB,OAAO,CAAC,QAAQ;IAC9F,IAAI,QAAQ,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACxC,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC;QAAE,OAAO,KAAK,CAAC;IAE1C,MAAM,KAAK,GAAG,SAAS,CAAC,gBAAgB,EAAE,CAAC,IAAI,EAAE,oBAAoB,EAAE,UAAU,CAAC,EAAE;QACnF,KAAK,EAAE,CAAC,QAAQ,EAAE,QAAQ,EAAE,QAAQ,CAAC;QACrC,OAAO,EAAE,IAAI;KACb,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC,KAAK,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC;AACxD,CAAC","sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\n\nexport const QUARANTINE_ATTRIBUTE = \"com.apple.quarantine\";\n\n/**\n * SECURITY: `dlopen()` on a quarantined, non-notarized addon hands control to\n * Gatekeeper, which suspends the process behind an \"Apple could not verify ... is\n * free of malware\" dialog instead of returning an error. Senpi's prebuilds carry\n * only a linker ad-hoc signature, so a quarantined prebuild is never auto-approved.\n * Detection MUST NOT become removal: clearing the attribute would silently defeat\n * the user's malware protection.\n *\n * Node exposes no `getxattr` binding, so `xattr -p` is the only available channel;\n * it exits 0 only when the attribute is present. Any spawn failure returns `false`\n * so an unreadable attribute never rejects an otherwise loadable prebuild.\n */\nexport function isQuarantinedNativeFile(modulePath: string, platform: string = process.platform): boolean {\n\tif (platform !== \"darwin\") return false;\n\tif (!existsSync(modulePath)) return false;\n\n\tconst probe = spawnSync(\"/usr/bin/xattr\", [\"-p\", QUARANTINE_ATTRIBUTE, modulePath], {\n\t\tstdio: [\"ignore\", \"ignore\", \"ignore\"],\n\t\ttimeout: 2000,\n\t});\n\n\treturn probe.error === undefined && probe.status === 0;\n}\n"]}
|