@psnext/slingcli 2.4.20260507-3 → 2.4.20260509-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +1 -1
- package/bin/sling.js +12 -12
- package/node_modules/@aws-sdk/client-bedrock-runtime/package.json +2 -2
- package/node_modules/@aws-sdk/token-providers/package.json +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-agent-core/dist/agent-loop.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-agent-core/dist/agent.js +4 -3
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.js +526 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.js +243 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.js +616 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.js +348 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/execution-env.js +3 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/factory.js +9 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.js +102 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/prompt-templates.js +194 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/repo/jsonl.js +92 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/repo/memory.js +42 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/repo/shared.js +31 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.js +196 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/storage/jsonl.js +170 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/storage/memory.js +90 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/skills.js +258 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/system-prompt.js +30 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/types.js +16 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/shell-output.js +97 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/index.js +26 -0
- package/node_modules/{@mariozechner → @earendil-works}/pi-agent-core/dist/proxy.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-agent-core/package.json +7 -5
- package/node_modules/{@mariozechner → @earendil-works}/pi-ai/dist/cli.js +6 -6
- package/node_modules/{@mariozechner → @earendil-works}/pi-ai/dist/env-api-keys.js +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +307 -0
- package/node_modules/@earendil-works/pi-ai/dist/image-models.js +23 -0
- package/node_modules/@earendil-works/pi-ai/dist/images-api-registry.js +22 -0
- package/node_modules/@earendil-works/pi-ai/dist/images.js +14 -0
- package/node_modules/{@mariozechner → @earendil-works}/pi-ai/dist/index.js +4 -0
- package/node_modules/{@mariozechner → @earendil-works}/pi-ai/dist/models.generated.js +427 -122
- package/node_modules/@earendil-works/pi-ai/dist/providers/images/openrouter.js +129 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/images/register-builtins.js +34 -0
- package/node_modules/{@mariozechner → @earendil-works}/pi-ai/dist/providers/openai-codex-responses.js +1 -1
- package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/providers/openai-completions.js +150 -122
- package/node_modules/{@mariozechner → @earendil-works}/pi-ai/dist/providers/openai-responses-shared.js +14 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-ai/dist/utils/oauth/openai-codex.js +25 -14
- package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/utils/overflow.js +3 -0
- package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/package.json +5 -4
- package/node_modules/@earendil-works/pi-coding-agent/dist/bun/register-bedrock.js +4 -0
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/cli/args.js +1 -0
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/cli/config-selector.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/cli/list-models.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/cli/session-picker.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/config.js +52 -30
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/agent-session.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/auth-storage.js +2 -2
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/compaction/branch-summarization.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/compaction/compaction.js +1 -1
- package/node_modules/@earendil-works/pi-coding-agent/dist/core/compaction/utils.js +153 -0
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/export-html/template.css +45 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/export-html/template.js +68 -4
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/extensions/loader.js +26 -12
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/keybindings.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/model-registry.js +3 -2
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/model-resolver.js +2 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/package-manager.js +22 -5
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/provider-display-names.js +1 -0
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/sdk.js +3 -3
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/tools/bash.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/tools/edit.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/tools/find.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/tools/grep.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/tools/ls.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/tools/read.js +3 -2
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/tools/render-utils.js +1 -1
- package/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/truncate.js +205 -0
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/tools/write.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/main.js +2 -2
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/migrations.js +3 -3
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/assistant-message.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/bash-execution.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/bordered-loader.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/branch-summary-message.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/compaction-summary-message.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/config-selector.js +25 -3
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/custom-editor.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/custom-message.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/earendil-announcement.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/extension-editor.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/extension-input.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/extension-selector.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/footer.js +1 -1
- package/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/keybinding-hints.js +36 -0
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/login-dialog.js +4 -3
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/model-selector.js +2 -2
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/oauth-selector.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/scoped-models-selector.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/session-selector-search.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/session-selector.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/settings-selector.js +4 -2
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/show-images-selector.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/skill-invocation-message.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/theme-selector.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/thinking-selector.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/tool-execution.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/tree-selector.js +3 -2
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/user-message-selector.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/user-message.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/visual-truncate.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/interactive-mode.js +47 -32
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/theme/dark.json +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/theme/light.json +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/theme/theme.js +1 -1
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/package-manager-cli.js +42 -39
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/clipboard.js +9 -2
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/paths.js +16 -0
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/version-check.js +9 -2
- package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/package.json +9 -8
- package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/components/image.js +14 -7
- package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/components/markdown.js +24 -84
- package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/terminal-image.js +10 -4
- package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/tui.js +73 -4
- package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/utils.js +33 -7
- package/node_modules/{@mariozechner → @earendil-works}/pi-tui/package.json +3 -3
- package/node_modules/@mariozechner/clipboard/README.md +58 -0
- package/node_modules/@mariozechner/clipboard/index.d.ts +23 -0
- package/node_modules/@mariozechner/clipboard-linux-x64-gnu/README.md +3 -0
- package/node_modules/@types/node/README.md +1 -1
- package/node_modules/@types/node/http2.d.ts +4 -1
- package/node_modules/@types/node/package.json +2 -2
- package/node_modules/@types/node/stream/web.d.ts +4 -0
- package/node_modules/brace-expansion/dist/commonjs/index.js +1 -1
- package/node_modules/brace-expansion/dist/commonjs/index.js.map +1 -1
- package/node_modules/brace-expansion/dist/esm/index.js +1 -1
- package/node_modules/brace-expansion/dist/esm/index.js.map +1 -1
- package/node_modules/brace-expansion/package.json +1 -1
- package/node_modules/fast-xml-builder/CHANGELOG.md +4 -0
- package/node_modules/fast-xml-builder/lib/fxb.cjs +1 -1
- package/node_modules/fast-xml-builder/lib/fxb.d.cts +91 -1
- package/node_modules/fast-xml-builder/lib/fxb.min.js +1 -1
- package/node_modules/fast-xml-builder/lib/fxb.min.js.map +1 -1
- package/node_modules/fast-xml-builder/package.json +3 -2
- package/node_modules/fast-xml-builder/src/fxb.d.ts +92 -3
- package/node_modules/fast-xml-builder/src/fxb.js +92 -31
- package/node_modules/fast-xml-builder/src/orderedJs2Xml.js +87 -33
- package/node_modules/get-east-asian-width/lookup-data.js +15 -12
- package/node_modules/get-east-asian-width/lookup.js +25 -22
- package/node_modules/get-east-asian-width/package.json +1 -1
- package/node_modules/jiti/README.md +258 -0
- package/node_modules/jiti/dist/babel.cjs +257 -0
- package/node_modules/jiti/dist/jiti.cjs +1 -0
- package/node_modules/jiti/lib/jiti.mjs +29 -0
- package/node_modules/jiti/lib/types.d.ts +420 -0
- package/node_modules/jiti/package.json +146 -0
- package/node_modules/protobufjs/dist/light/protobuf.js +5 -3
- package/node_modules/protobufjs/dist/light/protobuf.js.map +1 -1
- package/node_modules/protobufjs/dist/light/protobuf.min.js +3 -3
- package/node_modules/protobufjs/dist/light/protobuf.min.js.map +1 -1
- package/node_modules/protobufjs/dist/minimal/protobuf.js +2 -2
- package/node_modules/protobufjs/dist/minimal/protobuf.min.js +2 -2
- package/node_modules/protobufjs/dist/protobuf.js +5 -3
- package/node_modules/protobufjs/dist/protobuf.js.map +1 -1
- package/node_modules/protobufjs/dist/protobuf.min.js +3 -3
- package/node_modules/protobufjs/dist/protobuf.min.js.map +1 -1
- package/node_modules/protobufjs/package.json +1 -1
- package/node_modules/protobufjs/src/namespace.js +3 -1
- package/node_modules/semver/README.md +19 -4
- package/node_modules/semver/bin/semver.js +14 -10
- package/node_modules/semver/functions/truncate.js +48 -0
- package/node_modules/semver/index.js +2 -0
- package/node_modules/semver/internal/re.js +1 -1
- package/node_modules/semver/package.json +3 -3
- package/node_modules/semver/range.bnf +5 -4
- package/node_modules/socks/package.json +2 -2
- package/node_modules/xml-naming/README.md +189 -0
- package/node_modules/xml-naming/package.json +54 -0
- package/node_modules/xml-naming/src/index.d.ts +74 -0
- package/node_modules/xml-naming/src/index.js +270 -0
- package/package.json +6 -6
- package/sling-default-packages.json +2 -1
- package/slingshot/index.js +442 -23
- package/node_modules/@mariozechner/jiti/dist/babel.cjs +0 -246
- package/node_modules/@mariozechner/jiti/dist/jiti.cjs +0 -1
- package/node_modules/@mariozechner/jiti/package.json +0 -96
- package/node_modules/@mariozechner/pi-agent-core/dist/index.js +0 -9
- package/node_modules/@mariozechner/pi-agent-core/node_modules/@mariozechner/pi-ai/dist/cli.js +0 -116
- package/node_modules/@mariozechner/pi-agent-core/node_modules/@mariozechner/pi-ai/dist/env-api-keys.js +0 -166
- package/node_modules/@mariozechner/pi-agent-core/node_modules/@mariozechner/pi-ai/dist/index.js +0 -15
- package/node_modules/@mariozechner/pi-agent-core/node_modules/@mariozechner/pi-ai/dist/models.generated.js +0 -16568
- package/node_modules/@mariozechner/pi-agent-core/node_modules/@mariozechner/pi-ai/dist/providers/amazon-bedrock.js +0 -753
- package/node_modules/@mariozechner/pi-agent-core/node_modules/@mariozechner/pi-ai/dist/providers/openai-codex-responses.js +0 -909
- package/node_modules/@mariozechner/pi-agent-core/node_modules/@mariozechner/pi-ai/dist/providers/openai-responses-shared.js +0 -479
- package/node_modules/@mariozechner/pi-agent-core/node_modules/@mariozechner/pi-ai/dist/utils/oauth/openai-codex.js +0 -374
- package/node_modules/@mariozechner/pi-ai/dist/api-registry.js +0 -44
- package/node_modules/@mariozechner/pi-ai/dist/bedrock-provider.js +0 -6
- package/node_modules/@mariozechner/pi-ai/dist/models.js +0 -71
- package/node_modules/@mariozechner/pi-ai/dist/oauth.js +0 -2
- package/node_modules/@mariozechner/pi-ai/dist/providers/anthropic.js +0 -951
- package/node_modules/@mariozechner/pi-ai/dist/providers/azure-openai-responses.js +0 -208
- package/node_modules/@mariozechner/pi-ai/dist/providers/cloudflare.js +0 -26
- package/node_modules/@mariozechner/pi-ai/dist/providers/faux.js +0 -368
- package/node_modules/@mariozechner/pi-ai/dist/providers/github-copilot-headers.js +0 -29
- package/node_modules/@mariozechner/pi-ai/dist/providers/google-shared.js +0 -329
- package/node_modules/@mariozechner/pi-ai/dist/providers/google-vertex.js +0 -442
- package/node_modules/@mariozechner/pi-ai/dist/providers/google.js +0 -400
- package/node_modules/@mariozechner/pi-ai/dist/providers/mistral.js +0 -535
- package/node_modules/@mariozechner/pi-ai/dist/providers/openai-completions.js +0 -908
- package/node_modules/@mariozechner/pi-ai/dist/providers/openai-responses.js +0 -220
- package/node_modules/@mariozechner/pi-ai/dist/providers/register-builtins.js +0 -243
- package/node_modules/@mariozechner/pi-ai/dist/providers/simple-options.js +0 -39
- package/node_modules/@mariozechner/pi-ai/dist/providers/transform-messages.js +0 -184
- package/node_modules/@mariozechner/pi-ai/dist/stream.js +0 -27
- package/node_modules/@mariozechner/pi-ai/dist/types.js +0 -2
- package/node_modules/@mariozechner/pi-ai/dist/utils/event-stream.js +0 -81
- package/node_modules/@mariozechner/pi-ai/dist/utils/hash.js +0 -14
- package/node_modules/@mariozechner/pi-ai/dist/utils/headers.js +0 -8
- package/node_modules/@mariozechner/pi-ai/dist/utils/json-parse.js +0 -113
- package/node_modules/@mariozechner/pi-ai/dist/utils/oauth/anthropic.js +0 -335
- package/node_modules/@mariozechner/pi-ai/dist/utils/oauth/github-copilot.js +0 -292
- package/node_modules/@mariozechner/pi-ai/dist/utils/oauth/index.js +0 -121
- package/node_modules/@mariozechner/pi-ai/dist/utils/oauth/oauth-page.js +0 -105
- package/node_modules/@mariozechner/pi-ai/dist/utils/oauth/pkce.js +0 -31
- package/node_modules/@mariozechner/pi-ai/dist/utils/oauth/types.js +0 -2
- package/node_modules/@mariozechner/pi-ai/dist/utils/overflow.js +0 -146
- package/node_modules/@mariozechner/pi-ai/dist/utils/sanitize-unicode.js +0 -26
- package/node_modules/@mariozechner/pi-ai/dist/utils/typebox-helpers.js +0 -21
- package/node_modules/@mariozechner/pi-ai/dist/utils/validation.js +0 -281
- package/node_modules/@mariozechner/pi-ai/package.json +0 -108
- package/node_modules/@mariozechner/pi-coding-agent/dist/bun/register-bedrock.js +0 -4
- package/node_modules/@mariozechner/pi-coding-agent/dist/modes/interactive/components/keybinding-hints.js +0 -22
- package/node_modules/@mariozechner/pi-coding-agent/node_modules/@mariozechner/pi-agent-core/dist/agent-loop.js +0 -458
- package/node_modules/@mariozechner/pi-coding-agent/node_modules/@mariozechner/pi-agent-core/dist/agent.js +0 -398
- package/node_modules/@mariozechner/pi-coding-agent/node_modules/@mariozechner/pi-agent-core/dist/index.js +0 -9
- package/node_modules/@mariozechner/pi-coding-agent/node_modules/@mariozechner/pi-agent-core/dist/proxy.js +0 -278
- package/node_modules/@mariozechner/pi-coding-agent/node_modules/@mariozechner/pi-agent-core/dist/types.js +0 -2
- package/node_modules/@mariozechner/pi-coding-agent/node_modules/@mariozechner/pi-agent-core/package.json +0 -45
- package/node_modules/socks/.claude/settings.local.json +0 -26
- package/node_modules/std-env/LICENCE +0 -22
- package/node_modules/std-env/README.md +0 -118
- package/node_modules/std-env/dist/index.cjs +0 -1
- package/node_modules/std-env/dist/index.d.cts +0 -92
- package/node_modules/std-env/dist/index.d.mts +0 -92
- package/node_modules/std-env/dist/index.d.ts +0 -92
- package/node_modules/std-env/dist/index.mjs +0 -1
- package/node_modules/std-env/package.json +0 -46
- package/node_modules/yoctocolors/base.d.ts +0 -47
- package/node_modules/yoctocolors/base.js +0 -94
- package/node_modules/yoctocolors/index.d.ts +0 -2
- package/node_modules/yoctocolors/index.js +0 -2
- package/node_modules/yoctocolors/license +0 -9
- package/node_modules/yoctocolors/package.json +0 -69
- package/node_modules/yoctocolors/readme.md +0 -138
- /package/node_modules/{@mariozechner/pi-coding-agent/dist/core → @earendil-works/pi-agent-core/dist/harness}/compaction/utils.js +0 -0
- /package/node_modules/{@mariozechner/pi-coding-agent/dist/core/tools → @earendil-works/pi-agent-core/dist/harness/utils}/truncate.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-agent-core/dist/types.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/api-registry.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/bedrock-provider.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/models.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/oauth.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-ai/dist/providers/amazon-bedrock.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/providers/anthropic.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/providers/azure-openai-responses.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/providers/cloudflare.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/providers/faux.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/providers/github-copilot-headers.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/providers/google-shared.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/providers/google-vertex.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/providers/google.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/providers/mistral.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/providers/openai-responses.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/providers/register-builtins.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/providers/simple-options.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/providers/transform-messages.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-ai/dist/session-resources.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/stream.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/types.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-ai/dist/utils/diagnostics.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/utils/event-stream.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/utils/hash.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/utils/headers.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/utils/json-parse.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/utils/oauth/anthropic.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/utils/oauth/github-copilot.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/utils/oauth/index.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/utils/oauth/oauth-page.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/utils/oauth/pkce.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/utils/oauth/types.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/utils/sanitize-unicode.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/utils/typebox-helpers.js +0 -0
- /package/node_modules/{@mariozechner/pi-agent-core/node_modules/@mariozechner → @earendil-works}/pi-ai/dist/utils/validation.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/bun/cli.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/bun/restore-sandbox-env.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/cli/file-processor.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/cli/initial-message.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/cli.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/agent-session-runtime.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/agent-session-services.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/auth-guidance.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/bash-executor.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/compaction/index.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/defaults.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/diagnostics.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/event-bus.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/exec.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/export-html/ansi-to-html.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/export-html/index.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/export-html/template.html +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/export-html/tool-renderer.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/export-html/vendor/highlight.min.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/export-html/vendor/marked.min.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/extensions/index.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/extensions/runner.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/extensions/types.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/extensions/wrapper.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/footer-data-provider.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/index.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/messages.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/output-guard.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/prompt-templates.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/resolve-config-value.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/resource-loader.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/session-cwd.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/session-manager.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/settings-manager.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/skills.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/slash-commands.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/source-info.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/system-prompt.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/telemetry.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/timings.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/tools/edit-diff.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/tools/file-mutation-queue.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/tools/index.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/tools/output-accumulator.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/tools/path-utils.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/core/tools/tool-definition-wrapper.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/index.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/index.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/assets/clankolas.png +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/armin.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/countdown-timer.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/daxnuts.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/diff.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/dynamic-border.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/components/index.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/interactive/theme/theme-schema.json +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/print-mode.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/rpc/jsonl.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/rpc/rpc-client.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/rpc/rpc-mode.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/modes/rpc/rpc-types.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/changelog.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/child-process.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/clipboard-image.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/clipboard-native.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/exif-orientation.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/frontmatter.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/fs-watch.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/git.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/image-convert.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/image-resize.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/mime.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/photon.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/pi-user-agent.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/shell.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/sleep.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-coding-agent/dist/utils/tools-manager.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/autocomplete.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/components/box.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/components/cancellable-loader.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/components/editor.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/components/input.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/components/loader.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/components/select-list.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/components/settings-list.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/components/spacer.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/components/text.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/components/truncated-text.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/editor-component.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/fuzzy.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/index.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/keybindings.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/keys.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/kill-ring.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/stdin-buffer.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/terminal.js +0 -0
- /package/node_modules/{@mariozechner → @earendil-works}/pi-tui/dist/undo-stack.js +0 -0
- /package/node_modules/{@mariozechner/jiti → jiti}/LICENSE +0 -0
- /package/node_modules/{@mariozechner/jiti → jiti}/lib/jiti-cli.mjs +0 -0
- /package/node_modules/{@mariozechner/jiti → jiti}/lib/jiti-hooks.mjs +0 -0
- /package/node_modules/{@mariozechner/jiti → jiti}/lib/jiti-native.mjs +0 -0
- /package/node_modules/{@mariozechner/jiti → jiti}/lib/jiti-register.d.mts +0 -0
- /package/node_modules/{@mariozechner/jiti → jiti}/lib/jiti-register.mjs +0 -0
- /package/node_modules/{@mariozechner/jiti/lib/jiti.mjs → jiti/lib/jiti-static.mjs} +0 -0
- /package/node_modules/{@mariozechner/jiti → jiti}/lib/jiti.cjs +0 -0
- /package/node_modules/{@mariozechner/jiti → jiti}/lib/jiti.d.cts +0 -0
- /package/node_modules/{@mariozechner/jiti → jiti}/lib/jiti.d.mts +0 -0
package/slingshot/index.js
CHANGED
|
@@ -1,38 +1,457 @@
|
|
|
1
|
-
var Ie=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(s,t)=>(typeof require<"u"?require:s)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{eastAsianWidth as Je}from"get-east-asian-width";var U=new Intl.Segmenter(void 0,{granularity:"grapheme"});function de(){return U}function Tt(e){let s=e.codePointAt(0);return s>=126976&&s<=130047||s>=8960&&s<=9215||s>=9728&&s<=10175||s>=11088&&s<=11093||e.includes("\uFE0F")||e.length>2}var At=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),Mt=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),Pt=new RegExp("^\\p{RGI_Emoji}$","v"),Rt=512,ee=new Map;function Me(e){for(let s=0;s<e.length;s++){let t=e.charCodeAt(s);if(t<32||t>126)return!1}return!0}function Et(e,s){if(s<=0||e.length===0)return{text:"",width:0};if(Me(e)){let n=e.slice(0,s);return{text:n,width:n.length}}let t=e.includes("\x1B"),i=e.includes(" ");if(!t&&!i){let n="",l=0;for(let{segment:h}of U.segment(e)){let u=z(h);if(l+u>s)break;n+=h,l+=u}return{text:n,width:l}}let o="",r=0,a=0,c="";for(;a<e.length;){let n=F(e,a);if(n){c+=n.code,a+=n.length;continue}if(e[a]===" "){if(r+3>s)break;c&&(o+=c,c=""),o+=" ",r+=3,a++;continue}let l=a;for(;l<e.length&&e[l]!==" "&&!F(e,l);)l++;for(let{segment:h}of U.segment(e.slice(a,l))){let u=z(h);if(r+u>s)return{text:o,width:r};c&&(o+=c,c=""),o+=h,r+=u}a=l}return{text:o,width:r}}function ke(e,s,t,i,o,r){let a="\x1B[0m",c=s+i,n;return t.length>0?n=`${e}${a}${t}${a}`:n=`${e}${a}`,r?n+" ".repeat(Math.max(0,o-c)):n}function z(e){if(At.test(e))return 0;if(Tt(e)&&Pt.test(e))return 2;let t=e.replace(Mt,"").codePointAt(0);if(t===void 0)return 0;if(t>=127462&&t<=127487)return 2;let i=Je(t);if(e.length>1)for(let o of e.slice(1)){let r=o.codePointAt(0);r>=65280&&r<=65519?i+=Je(r):(r===3635||r===3763)&&(i+=1)}return i}function _(e){if(e.length===0)return 0;if(Me(e))return e.length;let s=ee.get(e);if(s!==void 0)return s;let t=e;if(e.includes(" ")&&(t=t.replace(/\t/g," ")),t.includes("\x1B")){let o="",r=0;for(;r<t.length;){let a=F(t,r);if(a){r+=a.length;continue}o+=t[r],r++}t=o}let i=0;for(let{segment:o}of U.segment(t))i+=z(o);if(ee.size>=Rt){let o=ee.keys().next().value;o!==void 0&&ee.delete(o)}return ee.set(e,i),i}var $t=/[\u0e33\u0eb3]/,Ot=/[\u0e33\u0eb3]/g;function Ze(e){return $t.test(e)?e.replace(Ot,s=>s==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2"):e}function F(e,s){if(s>=e.length||e[s]!=="\x1B")return null;let t=e[s+1];if(t==="["){let i=s+2;for(;i<e.length&&!/[mGKHJ]/.test(e[i]);)i++;return i<e.length?{code:e.substring(s,i+1),length:i+1-s}:null}if(t==="]"){let i=s+2;for(;i<e.length;){if(e[i]==="\x07")return{code:e.substring(s,i+1),length:i+1-s};if(e[i]==="\x1B"&&e[i+1]==="\\")return{code:e.substring(s,i+2),length:i+2-s};i++}return null}if(t==="_"){let i=s+2;for(;i<e.length;){if(e[i]==="\x07")return{code:e.substring(s,i+1),length:i+1-s};if(e[i]==="\x1B"&&e[i+1]==="\\")return{code:e.substring(s,i+2),length:i+2-s};i++}return null}return null}var Ae=class{constructor(){this.bold=!1;this.dim=!1;this.italic=!1;this.underline=!1;this.blink=!1;this.inverse=!1;this.hidden=!1;this.strikethrough=!1;this.fgColor=null;this.bgColor=null;this.activeHyperlink=null}process(s){if(s.startsWith("\x1B]8;")){let a=s.match(/^\x1b\]8;[^;]*;([^\x1b\x07]*)/);this.activeHyperlink=a?.[1]?a[1]:null;return}if(!s.endsWith("m"))return;let t=s.match(/\x1b\[([\d;]*)m/);if(!t)return;let i=t[1];if(i===""||i==="0"){this.reset();return}let o=i.split(";"),r=0;for(;r<o.length;){let a=Number.parseInt(o[r],10);if(a===38||a===48){if(o[r+1]==="5"&&o[r+2]!==void 0){let c=`${o[r]};${o[r+1]};${o[r+2]}`;a===38?this.fgColor=c:this.bgColor=c,r+=3;continue}else if(o[r+1]==="2"&&o[r+4]!==void 0){let c=`${o[r]};${o[r+1]};${o[r+2]};${o[r+3]};${o[r+4]}`;a===38?this.fgColor=c:this.bgColor=c,r+=5;continue}}switch(a){case 0:this.reset();break;case 1:this.bold=!0;break;case 2:this.dim=!0;break;case 3:this.italic=!0;break;case 4:this.underline=!0;break;case 5:this.blink=!0;break;case 7:this.inverse=!0;break;case 8:this.hidden=!0;break;case 9:this.strikethrough=!0;break;case 21:this.bold=!1;break;case 22:this.bold=!1,this.dim=!1;break;case 23:this.italic=!1;break;case 24:this.underline=!1;break;case 25:this.blink=!1;break;case 27:this.inverse=!1;break;case 28:this.hidden=!1;break;case 29:this.strikethrough=!1;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:a>=30&&a<=37||a>=90&&a<=97?this.fgColor=String(a):(a>=40&&a<=47||a>=100&&a<=107)&&(this.bgColor=String(a));break}r++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let s=[];this.bold&&s.push("1"),this.dim&&s.push("2"),this.italic&&s.push("3"),this.underline&&s.push("4"),this.blink&&s.push("5"),this.inverse&&s.push("7"),this.hidden&&s.push("8"),this.strikethrough&&s.push("9"),this.fgColor&&s.push(this.fgColor),this.bgColor&&s.push(this.bgColor);let t=s.length>0?`\x1B[${s.join(";")}m`:"";return this.activeHyperlink&&(t+=`\x1B]8;;${this.activeHyperlink}\x1B\\`),t}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let s="";return this.underline&&(s+="\x1B[24m"),this.activeHyperlink&&(s+="\x1B]8;;\x1B\\"),s}};function G(e,s,t="...",i=!1){if(s<=0)return"";if(e.length===0)return i?" ".repeat(s):"";let o=_(t);if(o>=s){let d=_(e);if(d<=s)return i?e+" ".repeat(s-d):e;let f=Et(t,s);return f.width===0?i?" ".repeat(s):"":ke("",0,f.text,f.width,s,i)}if(Me(e)){if(e.length<=s)return i?e+" ".repeat(s-e.length):e;let d=s-o;return ke(e.slice(0,d),d,t,o,s,i)}let r=s-o,a="",c="",n=0,l=0,h=!0,u=!1,g=!1,x=e.includes("\x1B"),b=e.includes(" ");if(!x&&!b){for(let{segment:d}of U.segment(e)){let f=z(d);if(h&&l+f<=r?(a+=d,l+=f):h=!1,n+=f,n>s){u=!0;break}}g=!u}else{let d=0;for(;d<e.length;){let f=F(e,d);if(f){c+=f.code,d+=f.length;continue}if(e[d]===" "){if(h&&l+3<=r?(c&&(a+=c,c=""),a+=" ",l+=3):(h=!1,c=""),n+=3,n>s){u=!0;break}d++;continue}let v=d;for(;v<e.length&&e[v]!==" "&&!F(e,v);)v++;for(let{segment:L}of U.segment(e.slice(d,v))){let k=z(L);if(h&&l+k<=r?(c&&(a+=c,c=""),a+=L,l+=k):(h=!1,c=""),n+=k,n>s){u=!0;break}}if(u)break;d=v}g=d>=e.length}return!u&&g?i?e+" ".repeat(Math.max(0,s-n)):e:ke(a,l,t,o,s,i)}function pe(e,s,t,i=!1){return Pe(e,s,t,i).text}function Pe(e,s,t,i=!1){if(t<=0)return{text:"",width:0};let o=s+t,r="",a=0,c=0,n=0,l="";for(;n<e.length;){let h=F(e,n);if(h){c>=s&&c<o?r+=h.code:c<s&&(l+=h.code),n+=h.length;continue}let u=n;for(;u<e.length&&!F(e,u);)u++;for(let{segment:g}of U.segment(e.slice(n,u))){let x=z(g),b=c>=s&&c<o,d=!i||c+x<=o;if(b&&d&&(l&&(r+=l,l=""),r+=g,a+=x),c+=x,c>=o)break}if(n=u,c>=o)break}return{text:r,width:a}}var Te=new Ae;function et(e,s,t,i,o=!1){let r="",a=0,c="",n=0,l=0,h=0,u="",g=!1,x=t+i;for(Te.clear();h<e.length;){let b=F(e,h);if(b){Te.process(b.code),l<s?u+=b.code:l>=t&&l<x&&g&&(c+=b.code),h+=b.length;continue}let d=h;for(;d<e.length&&!F(e,d);)d++;for(let{segment:f}of U.segment(e.slice(h,d))){let v=z(f);if(l<s?(u&&(r+=u,u=""),r+=f,a+=v):l>=t&&l<x&&(!o||l+v<=x)&&(g||(c+=Te.getActiveCodes(),g=!0),c+=f,n+=v),l+=v,i<=0?l>=s:l>=x)break}if(h=d,i<=0?l>=s:l>=x)break}return{before:r,beforeWidth:a,after:c,afterWidth:n}}var V=!1;var rt=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),p={shift:1,alt:2,ctrl:4,super:8},be=192,S={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},A={up:-1,down:-2,right:-3,left:-4},w={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},Kt=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,A.left],[57418,A.right],[57419,A.up],[57420,A.down],[57421,w.pageUp],[57422,w.pageDown],[57423,w.home],[57424,w.end],[57425,w.insert],[57426,w.delete]]);function st(e){return Kt.get(e)??e}function xe(e,s){return(s&~be&p.shift)!==0&&e>=65&&e<=90?e+32:e}var O={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},Wt={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},Dt={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]};var R=(e,s)=>s.includes(e),$=(e,s,t)=>t===p.shift?R(e,Wt[s]):t===p.ctrl?R(e,Dt[s]):!1,fe="press";function Re(e){return e.includes("\x1B[200~")?!1:!!(e.includes(":3u")||e.includes(":3~")||e.includes(":3A")||e.includes(":3B")||e.includes(":3C")||e.includes(":3D")||e.includes(":3H")||e.includes(":3F"))}function ge(e){if(!e)return"press";let s=parseInt(e,10);return s===2?"repeat":s===3?"release":"press"}function Bt(e){let s=e.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(s){let r=parseInt(s[1],10),a=s[2]&&s[2].length>0?parseInt(s[2],10):void 0,c=s[3]?parseInt(s[3],10):void 0,n=s[4]?parseInt(s[4],10):1,l=ge(s[5]);return fe=l,{codepoint:r,shiftedKey:a,baseLayoutKey:c,modifier:n-1,eventType:l}}let t=e.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(t){let r=parseInt(t[1],10),a=ge(t[2]),c={A:-1,B:-2,C:-3,D:-4};return fe=a,{codepoint:c[t[3]],modifier:r-1,eventType:a}}let i=e.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(i){let r=parseInt(i[1],10),a=i[2]?parseInt(i[2],10):1,c=ge(i[3]),l={2:w.insert,3:w.delete,5:w.pageUp,6:w.pageDown,7:w.home,8:w.end}[r];if(l!==void 0)return fe=c,{codepoint:l,modifier:a-1,eventType:c}}let o=e.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(o){let r=parseInt(o[1],10),a=ge(o[2]),c=o[3]==="H"?w.home:w.end;return fe=a,{codepoint:c,modifier:r-1,eventType:a}}return null}function m(e,s,t){let i=Bt(e);if(!i)return!1;let o=i.modifier&~be,r=t&~be;if(o!==r)return!1;let a=xe(st(i.codepoint),i.modifier),c=xe(st(s),t);if(a===c)return!0;if(i.baseLayoutKey!==void 0&&i.baseLayoutKey===s){let n=a,l=n>=97&&n<=122,h=rt.has(String.fromCharCode(n));if(!l&&!h)return!0}return!1}function ot(e){let s=e.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!s)return null;let t=parseInt(s[1],10);return{codepoint:parseInt(s[2],10),modifier:t-1}}function K(e,s,t){let i=ot(e);return i?i.codepoint===s&&i.modifier===t:!1}function Ft(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function it(e,s){return e==="\x7F"?s===0:e!=="\b"?!1:Ft()?s===p.ctrl:s===0}function Nt(e){let s=e.toLowerCase(),t=s.charCodeAt(0);return t>=97&&t<=122||s==="["||s==="\\"||s==="]"||s==="_"?String.fromCharCode(t&31):s==="-"?"":null}function nt(e){return e>="0"&&e<="9"}function me(e,s,t){if(t===0)return!1;let i=ot(e);return!i||i.modifier!==t?!1:xe(i.codepoint,i.modifier)===xe(s,t)}function Ut(e){let s=e.toLowerCase().split("+"),t=s[s.length-1];return t?{key:t,ctrl:s.includes("ctrl"),shift:s.includes("shift"),alt:s.includes("alt"),super:s.includes("super")}:null}function te(e,s){let t=Ut(s);if(!t)return!1;let{key:i,ctrl:o,shift:r,alt:a,super:c}=t,n=0;switch(r&&(n|=p.shift),a&&(n|=p.alt),o&&(n|=p.ctrl),c&&(n|=p.super),i){case"escape":case"esc":return n!==0?!1:e==="\x1B"||m(e,S.escape,0)||K(e,S.escape,0);case"space":return!V&&(n===p.ctrl&&e==="\0"||n===p.alt&&e==="\x1B ")?!0:n===0?e===" "||m(e,S.space,0)||K(e,S.space,0):m(e,S.space,n)||K(e,S.space,n);case"tab":return n===p.shift?e==="\x1B[Z"||m(e,S.tab,p.shift)||K(e,S.tab,p.shift):n===0?e===" "||m(e,S.tab,0):m(e,S.tab,n)||K(e,S.tab,n);case"enter":case"return":return n===p.shift?m(e,S.enter,p.shift)||m(e,S.kpEnter,p.shift)||K(e,S.enter,p.shift)?!0:V?e==="\x1B\r"||e===`
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
`)
|
|
5
|
-
`)
|
|
6
|
-
`;H.appendFileSync(C,T)};if(this.previousLines.length===0&&!o&&!r){d("first render"),x(!1);return}if(o){d(`terminal width changed (${this.previousWidth} -> ${t})`),x(!0);return}if(r&&!qt()){d(`terminal height changed (${this.previousHeight} -> ${i})`),x(!0);return}if(this.clearOnShrink&&u.length<this.maxLinesRendered&&this.overlayStack.length===0){d(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),x(!0);return}let f=-1,v=-1,L=Math.max(u.length,this.previousLines.length);for(let y=0;y<L;y++){let C=y<this.previousLines.length?this.previousLines[y]:"",T=y<u.length?u[y]:"";C!==T&&(f===-1&&(f=y),v=y)}let k=u.length>this.previousLines.length;k&&(f===-1&&(f=this.previousLines.length),v=u.length-1);let D=k&&f===this.previousLines.length&&f>0;if(f===-1){this.positionHardwareCursor(g,u.length),this.previousViewportTop=c,this.previousHeight=i;return}if(f>=u.length){if(this.previousLines.length>u.length){let y="\x1B[?2026h",C=Math.max(0,u.length-1);if(C<c){d(`deleted lines moved viewport up (${C} < ${c})`),x(!0);return}let T=h(C);T>0?y+=`\x1B[${T}B`:T<0&&(y+=`\x1B[${-T}A`),y+="\r";let M=this.previousLines.length-u.length;if(M>i){d(`extraLines > height (${M} > ${i})`),x(!0);return}M>0&&(y+="\x1B[1B");for(let Z=0;Z<M;Z++)y+="\r\x1B[2K",Z<M-1&&(y+="\x1B[1B");M>0&&(y+=`\x1B[${M}A`),y+="\x1B[?2026l",this.terminal.write(y),this.cursorRow=C,this.hardwareCursorRow=C}this.positionHardwareCursor(g,u.length),this.previousLines=u,this.previousWidth=t,this.previousHeight=i,this.previousViewportTop=c;return}if(f<c){d(`firstChanged < viewportTop (${f} < ${c})`),x(!0);return}let I="\x1B[?2026h",J=c+i-1,X=D?f-1:f;if(X>J){let y=Math.max(0,Math.min(i-1,l-c)),C=i-1-y;C>0&&(I+=`\x1B[${C}B`);let T=X-J;I+=`\r
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
1
|
+
var Pg=Object.defineProperty;var Qs=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var te=(i,e)=>()=>(i&&(e=i(i=0)),e);var Et=(i,e)=>{for(var t in e)Pg(i,t,{get:e[t],enumerable:!0})};function ze(i){if(process.versions?.bun&&!(typeof process>"u")&&!(Object.keys(process.env).length>0)){if(wo===null){wo=new Map;try{let{readFileSync:e}=Qs("node:fs"),t=e("/proc/self/environ","utf-8");for(let n of t.split("\0")){let s=n.indexOf("=");s>0&&wo.set(n.slice(0,s),n.slice(s+1))}}catch{}}return wo.get(i)}}function Xf(){if(as===null){if(!ko||!Ta||!Ca)return typeof process<"u"&&(process.versions?.node||process.versions?.bun)||(as=!1),!1;let i=process.env.GOOGLE_APPLICATION_CREDENTIALS||ze("GOOGLE_APPLICATION_CREDENTIALS");i?as=ko(i):as=ko(Ca(Ta(),".config","gcloud","application_default_credentials.json"))}return as}function Zf(i){if(i==="github-copilot")return["COPILOT_GITHUB_TOKEN","GH_TOKEN","GITHUB_TOKEN"];if(i==="anthropic")return["ANTHROPIC_OAUTH_TOKEN","ANTHROPIC_API_KEY"];let t={openai:"OPENAI_API_KEY","azure-openai-responses":"AZURE_OPENAI_API_KEY",deepseek:"DEEPSEEK_API_KEY",google:"GEMINI_API_KEY","google-vertex":"GOOGLE_CLOUD_API_KEY",groq:"GROQ_API_KEY",cerebras:"CEREBRAS_API_KEY",xai:"XAI_API_KEY",openrouter:"OPENROUTER_API_KEY","vercel-ai-gateway":"AI_GATEWAY_API_KEY",zai:"ZAI_API_KEY",mistral:"MISTRAL_API_KEY",minimax:"MINIMAX_API_KEY","minimax-cn":"MINIMAX_CN_API_KEY",moonshotai:"MOONSHOT_API_KEY","moonshotai-cn":"MOONSHOT_API_KEY",huggingface:"HF_TOKEN",fireworks:"FIREWORKS_API_KEY",together:"TOGETHER_API_KEY",opencode:"OPENCODE_API_KEY","opencode-go":"OPENCODE_API_KEY","kimi-coding":"KIMI_API_KEY","cloudflare-workers-ai":"CLOUDFLARE_API_KEY","cloudflare-ai-gateway":"CLOUDFLARE_API_KEY",xiaomi:"XIAOMI_API_KEY","xiaomi-token-plan-cn":"XIAOMI_TOKEN_PLAN_CN_API_KEY","xiaomi-token-plan-ams":"XIAOMI_TOKEN_PLAN_AMS_API_KEY","xiaomi-token-plan-sgp":"XIAOMI_TOKEN_PLAN_SGP_API_KEY"}[i];return t?[t]:void 0}function Jp(i){let e=Zf(i);if(!e)return;let t=e.filter(n=>!!process.env[n]||!!ze(n));return t.length>0?t:void 0}function ne(i){let e=Jp(i);if(e?.[0])return process.env[e[0]]||ze(e[0]);if(i==="google-vertex"){let t=Xf(),n=!!(process.env.GOOGLE_CLOUD_PROJECT||process.env.GCLOUD_PROJECT||ze("GOOGLE_CLOUD_PROJECT")||ze("GCLOUD_PROJECT")),s=!!(process.env.GOOGLE_CLOUD_LOCATION||ze("GOOGLE_CLOUD_LOCATION"));if(t&&n&&s)return"<authenticated>"}if(i==="amazon-bedrock"&&(process.env.AWS_PROFILE||process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY||process.env.AWS_BEARER_TOKEN_BEDROCK||process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI||process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI||process.env.AWS_WEB_IDENTITY_TOKEN_FILE||ze("AWS_PROFILE")||ze("AWS_ACCESS_KEY_ID")&&ze("AWS_SECRET_ACCESS_KEY")||ze("AWS_BEARER_TOKEN_BEDROCK")||ze("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")||ze("AWS_CONTAINER_CREDENTIALS_FULL_URI")||ze("AWS_WEB_IDENTITY_TOKEN_FILE")))return"<authenticated>"}var ko,Ta,Ca,Sa,Qf,Jf,Yf,wo,as,pt=te(()=>{"use strict";ko=null,Ta=null,Ca=null,Sa=i=>import(i),Qf="node:fs",Jf="node:os",Yf="node:path";typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(Sa(Qf).then(i=>{ko=i.existsSync}),Sa(Jf).then(i=>{Ta=i.homedir}),Sa(Yf).then(i=>{Ca=i.join}));wo=null;as=null});function He(i){let e={};for(let[t,n]of i.entries())e[t]=n;return e}var gn=te(()=>{"use strict"});function H(i){return i.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}var Wt=te(()=>{"use strict"});var Zp={};Et(Zp,{generateImagesOpenRouter:()=>s0});import i0 from"openai";function o0(i,e,t){return new i0({apiKey:e,baseURL:i.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:{...i.headers,...t}})}function r0(i,e){let t=e.input.map(n=>n.type==="text"?{type:"text",text:H(n.text)}:{type:"image_url",image_url:{url:`data:${n.mimeType};base64,${n.data}`}});return{model:i.id,messages:[{role:"user",content:t}],stream:!1,modalities:i.output.includes("text")?["image","text"]:["image"]}}function a0(i,e){let t=i.prompt_tokens||0,n=i.prompt_tokens_details?.cached_tokens||0,s=i.prompt_tokens_details?.cache_write_tokens||0,o=s>0?Math.max(0,n-s):n,r=Math.max(0,t-o-s),a=i.completion_tokens||0,l={input:r,output:a,cacheRead:o,cacheWrite:s,totalTokens:r+a+o+s,cost:{input:e.cost.input/1e6*r,output:e.cost.output/1e6*a,cacheRead:e.cost.cacheRead/1e6*o,cacheWrite:e.cost.cacheWrite/1e6*s,total:0}};return l.cost.total=l.cost.input+l.cost.output+l.cost.cacheRead+l.cost.cacheWrite,l}var s0,ed=te(()=>{"use strict";pt();gn();Wt();s0=async(i,e,t)=>{let n={api:i.api,provider:i.provider,model:i.id,output:[],stopReason:"stop",timestamp:Date.now()};try{let s=t?.apiKey||ne(i.provider);if(!s)throw new Error(`No API key available for provider: ${i.provider}`);let o=o0(i,s,t?.headers),r=r0(i,e),a=await t?.onPayload?.(r,i);a!==void 0&&(r=a);let l={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},...t?.maxRetries!==void 0?{maxRetries:t.maxRetries}:{}},{data:c,response:d}=await o.chat.completions.create(r,l).withResponse();await t?.onResponse?.({status:d.status,headers:He(d.headers)},i);let p=c;n.responseId=p.id,p.usage&&(n.usage=a0(p.usage,i));let u=p.choices[0];if(u){let h=u.message.content;typeof h=="string"&&h.length>0&&n.output.push({type:"text",text:h});for(let m of u.message.images??[]){let g=typeof m.image_url=="string"?m.image_url:m.image_url?.url;if(!g?.startsWith("data:"))continue;let x=g.match(/^data:([^;]+);base64,(.+)$/);x&&n.output.push({type:"image",mimeType:x[1],data:x[2]})}}return n}catch(s){return n.stopReason=t?.signal?.aborted?"aborted":"error",n.errorMessage=s instanceof Error?s.message:JSON.stringify(s),n}}});var nd,id=te(()=>{"use strict";nd={"amazon-bedrock":{"amazon.nova-2-lite-v1:0":{id:"amazon.nova-2-lite-v1:0",name:"Nova 2 Lite",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.33,output:2.75,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"amazon.nova-lite-v1:0":{id:"amazon.nova-lite-v1:0",name:"Nova Lite",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.06,output:.24,cacheRead:.015,cacheWrite:0},contextWindow:3e5,maxTokens:8192},"amazon.nova-micro-v1:0":{id:"amazon.nova-micro-v1:0",name:"Nova Micro",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.035,output:.14,cacheRead:.00875,cacheWrite:0},contextWindow:128e3,maxTokens:8192},"amazon.nova-premier-v1:0":{id:"amazon.nova-premier-v1:0",name:"Nova Premier",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:2.5,output:12.5,cacheRead:0,cacheWrite:0},contextWindow:1e6,maxTokens:16384},"amazon.nova-pro-v1:0":{id:"amazon.nova-pro-v1:0",name:"Nova Pro",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.8,output:3.2,cacheRead:.2,cacheWrite:0},contextWindow:3e5,maxTokens:8192},"anthropic.claude-3-5-haiku-20241022-v1:0":{id:"anthropic.claude-3-5-haiku-20241022-v1:0",name:"Claude Haiku 3.5",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.8,output:4,cacheRead:.08,cacheWrite:1},contextWindow:2e5,maxTokens:8192},"anthropic.claude-3-5-sonnet-20240620-v1:0":{id:"anthropic.claude-3-5-sonnet-20240620-v1:0",name:"Claude Sonnet 3.5",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:8192},"anthropic.claude-3-5-sonnet-20241022-v2:0":{id:"anthropic.claude-3-5-sonnet-20241022-v2:0",name:"Claude Sonnet 3.5 v2",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:8192},"anthropic.claude-3-7-sonnet-20250219-v1:0":{id:"anthropic.claude-3-7-sonnet-20250219-v1:0",name:"Claude Sonnet 3.7",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:8192},"anthropic.claude-3-haiku-20240307-v1:0":{id:"anthropic.claude-3-haiku-20240307-v1:0",name:"Claude Haiku 3",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.25,output:1.25,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:4096},"anthropic.claude-haiku-4-5-20251001-v1:0":{id:"anthropic.claude-haiku-4-5-20251001-v1:0",name:"Claude Haiku 4.5",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3},"anthropic.claude-opus-4-1-20250805-v1:0":{id:"anthropic.claude-opus-4-1-20250805-v1:0",name:"Claude Opus 4.1",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"anthropic.claude-opus-4-20250514-v1:0":{id:"anthropic.claude-opus-4-20250514-v1:0",name:"Claude Opus 4",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"anthropic.claude-opus-4-5-20251101-v1:0":{id:"anthropic.claude-opus-4-5-20251101-v1:0",name:"Claude Opus 4.5",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:2e5,maxTokens:64e3},"anthropic.claude-opus-4-6-v1":{id:"anthropic.claude-opus-4-6-v1",name:"Claude Opus 4.6",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,thinkingLevelMap:{xhigh:"max"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"anthropic.claude-opus-4-7":{id:"anthropic.claude-opus-4-7",name:"Claude Opus 4.7",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"anthropic.claude-sonnet-4-20250514-v1:0":{id:"anthropic.claude-sonnet-4-20250514-v1:0",name:"Claude Sonnet 4",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"anthropic.claude-sonnet-4-5-20250929-v1:0":{id:"anthropic.claude-sonnet-4-5-20250929-v1:0",name:"Claude Sonnet 4.5",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"anthropic.claude-sonnet-4-6":{id:"anthropic.claude-sonnet-4-6",name:"Claude Sonnet 4.6",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3},"au.anthropic.claude-opus-4-6-v1":{id:"au.anthropic.claude-opus-4-6-v1",name:"AU Anthropic Claude Opus 4.6",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,thinkingLevelMap:{xhigh:"max"},input:["text","image"],cost:{input:16.5,output:82.5,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"au.anthropic.claude-sonnet-4-6":{id:"au.anthropic.claude-sonnet-4-6",name:"AU Anthropic Claude Sonnet 4.6",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:3.3,output:16.5,cacheRead:.33,cacheWrite:4.125},contextWindow:1e6,maxTokens:128e3},"deepseek.r1-v1:0":{id:"deepseek.r1-v1:0",name:"DeepSeek-R1",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:1.35,output:5.4,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:32768},"deepseek.v3-v1:0":{id:"deepseek.v3-v1:0",name:"DeepSeek-V3.1",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:.58,output:1.68,cacheRead:0,cacheWrite:0},contextWindow:163840,maxTokens:81920},"deepseek.v3.2":{id:"deepseek.v3.2",name:"DeepSeek-V3.2",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:.62,output:1.85,cacheRead:0,cacheWrite:0},contextWindow:163840,maxTokens:81920},"eu.anthropic.claude-haiku-4-5-20251001-v1:0":{id:"eu.anthropic.claude-haiku-4-5-20251001-v1:0",name:"Claude Haiku 4.5 (EU)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.eu-central-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3},"eu.anthropic.claude-opus-4-5-20251101-v1:0":{id:"eu.anthropic.claude-opus-4-5-20251101-v1:0",name:"Claude Opus 4.5 (EU)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.eu-central-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:2e5,maxTokens:64e3},"eu.anthropic.claude-opus-4-6-v1":{id:"eu.anthropic.claude-opus-4-6-v1",name:"Claude Opus 4.6 (EU)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.eu-central-1.amazonaws.com",reasoning:!0,thinkingLevelMap:{xhigh:"max"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"eu.anthropic.claude-opus-4-7":{id:"eu.anthropic.claude-opus-4-7",name:"Claude Opus 4.7 (EU)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.eu-central-1.amazonaws.com",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"eu.anthropic.claude-sonnet-4-20250514-v1:0":{id:"eu.anthropic.claude-sonnet-4-20250514-v1:0",name:"Claude Sonnet 4 (EU)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.eu-central-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"eu.anthropic.claude-sonnet-4-5-20250929-v1:0":{id:"eu.anthropic.claude-sonnet-4-5-20250929-v1:0",name:"Claude Sonnet 4.5 (EU)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.eu-central-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"eu.anthropic.claude-sonnet-4-6":{id:"eu.anthropic.claude-sonnet-4-6",name:"Claude Sonnet 4.6 (EU)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.eu-central-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3},"global.anthropic.claude-haiku-4-5-20251001-v1:0":{id:"global.anthropic.claude-haiku-4-5-20251001-v1:0",name:"Claude Haiku 4.5 (Global)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3},"global.anthropic.claude-opus-4-5-20251101-v1:0":{id:"global.anthropic.claude-opus-4-5-20251101-v1:0",name:"Claude Opus 4.5 (Global)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:2e5,maxTokens:64e3},"global.anthropic.claude-opus-4-6-v1":{id:"global.anthropic.claude-opus-4-6-v1",name:"Claude Opus 4.6 (Global)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,thinkingLevelMap:{xhigh:"max"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"global.anthropic.claude-opus-4-7":{id:"global.anthropic.claude-opus-4-7",name:"Claude Opus 4.7 (Global)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"global.anthropic.claude-sonnet-4-20250514-v1:0":{id:"global.anthropic.claude-sonnet-4-20250514-v1:0",name:"Claude Sonnet 4 (Global)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"global.anthropic.claude-sonnet-4-5-20250929-v1:0":{id:"global.anthropic.claude-sonnet-4-5-20250929-v1:0",name:"Claude Sonnet 4.5 (Global)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"global.anthropic.claude-sonnet-4-6":{id:"global.anthropic.claude-sonnet-4-6",name:"Claude Sonnet 4.6 (Global)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3},"google.gemma-3-27b-it":{id:"google.gemma-3-27b-it",name:"Google Gemma 3 27B Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.12,output:.2,cacheRead:0,cacheWrite:0},contextWindow:202752,maxTokens:8192},"google.gemma-3-4b-it":{id:"google.gemma-3-4b-it",name:"Gemma 3 4B IT",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.04,output:.08,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"meta.llama3-1-405b-instruct-v1:0":{id:"meta.llama3-1-405b-instruct-v1:0",name:"Llama 3.1 405B Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:2.4,output:2.4,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"meta.llama3-1-70b-instruct-v1:0":{id:"meta.llama3-1-70b-instruct-v1:0",name:"Llama 3.1 70B Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.72,output:.72,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"meta.llama3-1-8b-instruct-v1:0":{id:"meta.llama3-1-8b-instruct-v1:0",name:"Llama 3.1 8B Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.22,output:.22,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"meta.llama3-2-11b-instruct-v1:0":{id:"meta.llama3-2-11b-instruct-v1:0",name:"Llama 3.2 11B Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.16,output:.16,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"meta.llama3-2-1b-instruct-v1:0":{id:"meta.llama3-2-1b-instruct-v1:0",name:"Llama 3.2 1B Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.1,output:.1,cacheRead:0,cacheWrite:0},contextWindow:131e3,maxTokens:4096},"meta.llama3-2-3b-instruct-v1:0":{id:"meta.llama3-2-3b-instruct-v1:0",name:"Llama 3.2 3B Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.15,output:.15,cacheRead:0,cacheWrite:0},contextWindow:131e3,maxTokens:4096},"meta.llama3-2-90b-instruct-v1:0":{id:"meta.llama3-2-90b-instruct-v1:0",name:"Llama 3.2 90B Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.72,output:.72,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"meta.llama3-3-70b-instruct-v1:0":{id:"meta.llama3-3-70b-instruct-v1:0",name:"Llama 3.3 70B Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.72,output:.72,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"meta.llama4-maverick-17b-instruct-v1:0":{id:"meta.llama4-maverick-17b-instruct-v1:0",name:"Llama 4 Maverick 17B Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.24,output:.97,cacheRead:0,cacheWrite:0},contextWindow:1e6,maxTokens:16384},"meta.llama4-scout-17b-instruct-v1:0":{id:"meta.llama4-scout-17b-instruct-v1:0",name:"Llama 4 Scout 17B Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.17,output:.66,cacheRead:0,cacheWrite:0},contextWindow:35e5,maxTokens:16384},"minimax.minimax-m2":{id:"minimax.minimax-m2",name:"MiniMax M2",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:0,cacheWrite:0},contextWindow:204608,maxTokens:128e3},"minimax.minimax-m2.1":{id:"minimax.minimax-m2.1",name:"MiniMax M2.1",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:0,cacheWrite:0},contextWindow:204800,maxTokens:131072},"minimax.minimax-m2.5":{id:"minimax.minimax-m2.5",name:"MiniMax M2.5",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:0,cacheWrite:0},contextWindow:196608,maxTokens:98304},"mistral.devstral-2-123b":{id:"mistral.devstral-2-123b",name:"Devstral 2 123B",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.4,output:2,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:8192},"mistral.magistral-small-2509":{id:"mistral.magistral-small-2509",name:"Magistral Small 1.2",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:.5,output:1.5,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4e4},"mistral.ministral-3-14b-instruct":{id:"mistral.ministral-3-14b-instruct",name:"Ministral 14B 3.0",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.2,output:.2,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"mistral.ministral-3-3b-instruct":{id:"mistral.ministral-3-3b-instruct",name:"Ministral 3 3B",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.1,output:.1,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:8192},"mistral.ministral-3-8b-instruct":{id:"mistral.ministral-3-8b-instruct",name:"Ministral 3 8B",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.15,output:.15,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"mistral.mistral-large-3-675b-instruct":{id:"mistral.mistral-large-3-675b-instruct",name:"Mistral Large 3",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.5,output:1.5,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:8192},"mistral.pixtral-large-2502-v1:0":{id:"mistral.pixtral-large-2502-v1:0",name:"Pixtral Large (25.02)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:2,output:6,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192},"mistral.voxtral-mini-3b-2507":{id:"mistral.voxtral-mini-3b-2507",name:"Voxtral Mini 3B 2507",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.04,output:.04,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"mistral.voxtral-small-24b-2507":{id:"mistral.voxtral-small-24b-2507",name:"Voxtral Small 24B 2507",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.15,output:.35,cacheRead:0,cacheWrite:0},contextWindow:32e3,maxTokens:8192},"moonshot.kimi-k2-thinking":{id:"moonshot.kimi-k2-thinking",name:"Kimi K2 Thinking",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:.6,output:2.5,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"moonshotai.kimi-k2.5":{id:"moonshotai.kimi-k2.5",name:"Kimi K2.5",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:.6,output:3,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"nvidia.nemotron-nano-12b-v2":{id:"nvidia.nemotron-nano-12b-v2",name:"NVIDIA Nemotron Nano 12B v2 VL BF16",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.2,output:.6,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"nvidia.nemotron-nano-3-30b":{id:"nvidia.nemotron-nano-3-30b",name:"NVIDIA Nemotron Nano 3 30B",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:.06,output:.24,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"nvidia.nemotron-nano-9b-v2":{id:"nvidia.nemotron-nano-9b-v2",name:"NVIDIA Nemotron Nano 9B v2",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.06,output:.23,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"nvidia.nemotron-super-3-120b":{id:"nvidia.nemotron-super-3-120b",name:"NVIDIA Nemotron 3 Super 120B A12B",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:.15,output:.65,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:131072},"openai.gpt-oss-120b-1:0":{id:"openai.gpt-oss-120b-1:0",name:"gpt-oss-120b",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.15,output:.6,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"openai.gpt-oss-20b-1:0":{id:"openai.gpt-oss-20b-1:0",name:"gpt-oss-20b",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.07,output:.3,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"openai.gpt-oss-safeguard-120b":{id:"openai.gpt-oss-safeguard-120b",name:"GPT OSS Safeguard 120B",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.15,output:.6,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"openai.gpt-oss-safeguard-20b":{id:"openai.gpt-oss-safeguard-20b",name:"GPT OSS Safeguard 20B",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.07,output:.2,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"qwen.qwen3-235b-a22b-2507-v1:0":{id:"qwen.qwen3-235b-a22b-2507-v1:0",name:"Qwen3 235B A22B 2507",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.22,output:.88,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:131072},"qwen.qwen3-32b-v1:0":{id:"qwen.qwen3-32b-v1:0",name:"Qwen3 32B (dense)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:.15,output:.6,cacheRead:0,cacheWrite:0},contextWindow:16384,maxTokens:16384},"qwen.qwen3-coder-30b-a3b-v1:0":{id:"qwen.qwen3-coder-30b-a3b-v1:0",name:"Qwen3 Coder 30B A3B Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.15,output:.6,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:131072},"qwen.qwen3-coder-480b-a35b-v1:0":{id:"qwen.qwen3-coder-480b-a35b-v1:0",name:"Qwen3 Coder 480B A35B Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.22,output:1.8,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:65536},"qwen.qwen3-coder-next":{id:"qwen.qwen3-coder-next",name:"Qwen3 Coder Next",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:.22,output:1.8,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:65536},"qwen.qwen3-next-80b-a3b":{id:"qwen.qwen3-next-80b-a3b",name:"Qwen/Qwen3-Next-80B-A3B-Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text"],cost:{input:.14,output:1.4,cacheRead:0,cacheWrite:0},contextWindow:262e3,maxTokens:262e3},"qwen.qwen3-vl-235b-a22b":{id:"qwen.qwen3-vl-235b-a22b",name:"Qwen/Qwen3-VL-235B-A22B-Instruct",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!1,input:["text","image"],cost:{input:.3,output:1.5,cacheRead:0,cacheWrite:0},contextWindow:262e3,maxTokens:262e3},"us.anthropic.claude-haiku-4-5-20251001-v1:0":{id:"us.anthropic.claude-haiku-4-5-20251001-v1:0",name:"Claude Haiku 4.5 (US)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3},"us.anthropic.claude-opus-4-1-20250805-v1:0":{id:"us.anthropic.claude-opus-4-1-20250805-v1:0",name:"Claude Opus 4.1 (US)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"us.anthropic.claude-opus-4-20250514-v1:0":{id:"us.anthropic.claude-opus-4-20250514-v1:0",name:"Claude Opus 4 (US)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"us.anthropic.claude-opus-4-5-20251101-v1:0":{id:"us.anthropic.claude-opus-4-5-20251101-v1:0",name:"Claude Opus 4.5 (US)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:2e5,maxTokens:64e3},"us.anthropic.claude-opus-4-6-v1":{id:"us.anthropic.claude-opus-4-6-v1",name:"Claude Opus 4.6 (US)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,thinkingLevelMap:{xhigh:"max"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"us.anthropic.claude-opus-4-7":{id:"us.anthropic.claude-opus-4-7",name:"Claude Opus 4.7 (US)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"us.anthropic.claude-sonnet-4-20250514-v1:0":{id:"us.anthropic.claude-sonnet-4-20250514-v1:0",name:"Claude Sonnet 4 (US)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"us.anthropic.claude-sonnet-4-5-20250929-v1:0":{id:"us.anthropic.claude-sonnet-4-5-20250929-v1:0",name:"Claude Sonnet 4.5 (US)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"us.anthropic.claude-sonnet-4-6":{id:"us.anthropic.claude-sonnet-4-6",name:"Claude Sonnet 4.6 (US)",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3},"writer.palmyra-x4-v1:0":{id:"writer.palmyra-x4-v1:0",name:"Palmyra X4",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:2.5,output:10,cacheRead:0,cacheWrite:0},contextWindow:122880,maxTokens:8192},"writer.palmyra-x5-v1:0":{id:"writer.palmyra-x5-v1:0",name:"Palmyra X5",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:.6,output:6,cacheRead:0,cacheWrite:0},contextWindow:104e4,maxTokens:8192},"zai.glm-4.7":{id:"zai.glm-4.7",name:"GLM-4.7",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:.6,output:2.2,cacheRead:0,cacheWrite:0},contextWindow:204800,maxTokens:131072},"zai.glm-4.7-flash":{id:"zai.glm-4.7-flash",name:"GLM-4.7-Flash",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:.07,output:.4,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:131072},"zai.glm-5":{id:"zai.glm-5",name:"GLM-5",api:"bedrock-converse-stream",provider:"amazon-bedrock",baseUrl:"https://bedrock-runtime.us-east-1.amazonaws.com",reasoning:!0,input:["text"],cost:{input:1,output:3.2,cacheRead:0,cacheWrite:0},contextWindow:202752,maxTokens:101376}},anthropic:{"claude-3-5-haiku-20241022":{id:"claude-3-5-haiku-20241022",name:"Claude Haiku 3.5",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!1,input:["text","image"],cost:{input:.8,output:4,cacheRead:.08,cacheWrite:1},contextWindow:2e5,maxTokens:8192},"claude-3-5-haiku-latest":{id:"claude-3-5-haiku-latest",name:"Claude Haiku 3.5 (latest)",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!1,input:["text","image"],cost:{input:.8,output:4,cacheRead:.08,cacheWrite:1},contextWindow:2e5,maxTokens:8192},"claude-3-5-sonnet-20240620":{id:"claude-3-5-sonnet-20240620",name:"Claude Sonnet 3.5",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!1,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:8192},"claude-3-5-sonnet-20241022":{id:"claude-3-5-sonnet-20241022",name:"Claude Sonnet 3.5 v2",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!1,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:8192},"claude-3-7-sonnet-20250219":{id:"claude-3-7-sonnet-20250219",name:"Claude Sonnet 3.7",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"claude-3-haiku-20240307":{id:"claude-3-haiku-20240307",name:"Claude Haiku 3",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!1,input:["text","image"],cost:{input:.25,output:1.25,cacheRead:.03,cacheWrite:.3},contextWindow:2e5,maxTokens:4096},"claude-3-opus-20240229":{id:"claude-3-opus-20240229",name:"Claude Opus 3",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!1,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:4096},"claude-3-sonnet-20240229":{id:"claude-3-sonnet-20240229",name:"Claude Sonnet 3",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!1,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:.3},contextWindow:2e5,maxTokens:4096},"claude-haiku-4-5":{id:"claude-haiku-4-5",name:"Claude Haiku 4.5 (latest)",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3},"claude-haiku-4-5-20251001":{id:"claude-haiku-4-5-20251001",name:"Claude Haiku 4.5",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3},"claude-opus-4-0":{id:"claude-opus-4-0",name:"Claude Opus 4 (latest)",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"claude-opus-4-1":{id:"claude-opus-4-1",name:"Claude Opus 4.1 (latest)",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"claude-opus-4-1-20250805":{id:"claude-opus-4-1-20250805",name:"Claude Opus 4.1",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"claude-opus-4-20250514":{id:"claude-opus-4-20250514",name:"Claude Opus 4",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"claude-opus-4-5":{id:"claude-opus-4-5",name:"Claude Opus 4.5 (latest)",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:2e5,maxTokens:64e3},"claude-opus-4-5-20251101":{id:"claude-opus-4-5-20251101",name:"Claude Opus 4.5",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:2e5,maxTokens:64e3},"claude-opus-4-6":{id:"claude-opus-4-6",name:"Claude Opus 4.6",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,thinkingLevelMap:{xhigh:"max"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"claude-opus-4-7":{id:"claude-opus-4-7",name:"Claude Opus 4.7",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"claude-sonnet-4-0":{id:"claude-sonnet-4-0",name:"Claude Sonnet 4 (latest)",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"claude-sonnet-4-20250514":{id:"claude-sonnet-4-20250514",name:"Claude Sonnet 4",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"claude-sonnet-4-5":{id:"claude-sonnet-4-5",name:"Claude Sonnet 4.5 (latest)",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"claude-sonnet-4-5-20250929":{id:"claude-sonnet-4-5-20250929",name:"Claude Sonnet 4.5",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"claude-sonnet-4-6":{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"anthropic",baseUrl:"https://api.anthropic.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3}},"azure-openai-responses":{"gpt-4":{id:"gpt-4",name:"GPT-4",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!1,input:["text"],cost:{input:30,output:60,cacheRead:0,cacheWrite:0},contextWindow:8192,maxTokens:8192},"gpt-4-turbo":{id:"gpt-4-turbo",name:"GPT-4 Turbo",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!1,input:["text","image"],cost:{input:10,output:30,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!1,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:1047576,maxTokens:32768},"gpt-4.1-mini":{id:"gpt-4.1-mini",name:"GPT-4.1 mini",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!1,input:["text","image"],cost:{input:.4,output:1.6,cacheRead:.1,cacheWrite:0},contextWindow:1047576,maxTokens:32768},"gpt-4.1-nano":{id:"gpt-4.1-nano",name:"GPT-4.1 nano",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!1,input:["text","image"],cost:{input:.1,output:.4,cacheRead:.03,cacheWrite:0},contextWindow:1047576,maxTokens:32768},"gpt-4o":{id:"gpt-4o",name:"GPT-4o",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!1,input:["text","image"],cost:{input:2.5,output:10,cacheRead:1.25,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-4o-2024-05-13":{id:"gpt-4o-2024-05-13",name:"GPT-4o (2024-05-13)",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!1,input:["text","image"],cost:{input:5,output:15,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"gpt-4o-2024-08-06":{id:"gpt-4o-2024-08-06",name:"GPT-4o (2024-08-06)",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!1,input:["text","image"],cost:{input:2.5,output:10,cacheRead:1.25,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-4o-2024-11-20":{id:"gpt-4o-2024-11-20",name:"GPT-4o (2024-11-20)",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!1,input:["text","image"],cost:{input:2.5,output:10,cacheRead:1.25,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-4o-mini":{id:"gpt-4o-mini",name:"GPT-4o mini",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!1,input:["text","image"],cost:{input:.15,output:.6,cacheRead:.08,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-5":{id:"gpt-5",name:"GPT-5",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5-chat-latest":{id:"gpt-5-chat-latest",name:"GPT-5 Chat Latest",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!1,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-5-codex":{id:"gpt-5-codex",name:"GPT-5-Codex",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5-mini":{id:"gpt-5-mini",name:"GPT-5 Mini",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5-nano":{id:"gpt-5-nano",name:"GPT-5 Nano",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:.05,output:.4,cacheRead:.005,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5-pro":{id:"gpt-5-pro",name:"GPT-5 Pro",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:15,output:120,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:272e3},"gpt-5.1":{id:"gpt-5.1",name:"GPT-5.1",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.13,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.1-chat-latest":{id:"gpt-5.1-chat-latest",name:"GPT-5.1 Chat",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-5.1-codex":{id:"gpt-5.1-codex",name:"GPT-5.1 Codex",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.1-codex-max":{id:"gpt-5.1-codex-max",name:"GPT-5.1 Codex Max",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.1-codex-mini":{id:"gpt-5.1-codex-mini",name:"GPT-5.1 Codex mini",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.2":{id:"gpt-5.2",name:"GPT-5.2",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.2-chat-latest":{id:"gpt-5.2-chat-latest",name:"GPT-5.2 Chat",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-5.2-codex":{id:"gpt-5.2-codex",name:"GPT-5.2 Codex",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.2-pro":{id:"gpt-5.2-pro",name:"GPT-5.2 Pro",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:21,output:168,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.3-chat-latest":{id:"gpt-5.3-chat-latest",name:"GPT-5.3 Chat (latest)",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!1,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.3-codex-spark":{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:128e3,maxTokens:32e3},"gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0},contextWindow:272e3,maxTokens:128e3},"gpt-5.4-mini":{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.4-nano":{id:"gpt-5.4-nano",name:"GPT-5.4 nano",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.4-pro":{id:"gpt-5.4-pro",name:"GPT-5.4 Pro",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:30,output:180,cacheRead:0,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},"gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0},contextWindow:272e3,maxTokens:128e3},"gpt-5.5-pro":{id:"gpt-5.5-pro",name:"GPT-5.5 Pro",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:30,output:180,cacheRead:0,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},o1:{id:"o1",name:"o1",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,input:["text","image"],cost:{input:15,output:60,cacheRead:7.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o1-pro":{id:"o1-pro",name:"o1-pro",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,input:["text","image"],cost:{input:150,output:600,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},o3:{id:"o3",name:"o3",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o3-deep-research":{id:"o3-deep-research",name:"o3-deep-research",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,input:["text","image"],cost:{input:10,output:40,cacheRead:2.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o3-mini":{id:"o3-mini",name:"o3-mini",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.55,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o3-pro":{id:"o3-pro",name:"o3-pro",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,input:["text","image"],cost:{input:20,output:80,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o4-mini":{id:"o4-mini",name:"o4-mini",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,input:["text","image"],cost:{input:1.1,output:4.4,cacheRead:.28,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o4-mini-deep-research":{id:"o4-mini-deep-research",name:"o4-mini-deep-research",api:"azure-openai-responses",provider:"azure-openai-responses",baseUrl:"",reasoning:!0,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5}},cerebras:{"gpt-oss-120b":{id:"gpt-oss-120b",name:"GPT OSS 120B",api:"openai-completions",provider:"cerebras",baseUrl:"https://api.cerebras.ai/v1",reasoning:!0,input:["text"],cost:{input:.25,output:.69,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"llama3.1-8b":{id:"llama3.1-8b",name:"Llama 3.1 8B",api:"openai-completions",provider:"cerebras",baseUrl:"https://api.cerebras.ai/v1",reasoning:!1,input:["text"],cost:{input:.1,output:.1,cacheRead:0,cacheWrite:0},contextWindow:32e3,maxTokens:8e3},"qwen-3-235b-a22b-instruct-2507":{id:"qwen-3-235b-a22b-instruct-2507",name:"Qwen 3 235B Instruct",api:"openai-completions",provider:"cerebras",baseUrl:"https://api.cerebras.ai/v1",reasoning:!1,input:["text"],cost:{input:.6,output:1.2,cacheRead:0,cacheWrite:0},contextWindow:131e3,maxTokens:32e3},"zai-glm-4.7":{id:"zai-glm-4.7",name:"Z.AI GLM-4.7",api:"openai-completions",provider:"cerebras",baseUrl:"https://api.cerebras.ai/v1",reasoning:!1,input:["text"],cost:{input:2.25,output:2.75,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:4e4}},"cloudflare-ai-gateway":{"claude-3-5-haiku":{id:"claude-3-5-haiku",name:"Claude Haiku 3.5 (latest)",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!1,input:["text","image"],cost:{input:.8,output:4,cacheRead:.08,cacheWrite:1},contextWindow:2e5,maxTokens:8192},"claude-3-haiku":{id:"claude-3-haiku",name:"Claude Haiku 3",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!1,input:["text","image"],cost:{input:.25,output:1.25,cacheRead:.03,cacheWrite:.3},contextWindow:2e5,maxTokens:4096},"claude-3-opus":{id:"claude-3-opus",name:"Claude Opus 3",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!1,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:4096},"claude-3-sonnet":{id:"claude-3-sonnet",name:"Claude Sonnet 3",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!1,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:.3},contextWindow:2e5,maxTokens:4096},"claude-3.5-haiku":{id:"claude-3.5-haiku",name:"Claude Haiku 3.5 (latest)",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!1,input:["text","image"],cost:{input:.8,output:4,cacheRead:.08,cacheWrite:1},contextWindow:2e5,maxTokens:8192},"claude-3.5-sonnet":{id:"claude-3.5-sonnet",name:"Claude Sonnet 3.5 v2",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!1,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:8192},"claude-haiku-4-5":{id:"claude-haiku-4-5",name:"Claude Haiku 4.5 (latest)",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3},"claude-opus-4":{id:"claude-opus-4",name:"Claude Opus 4 (latest)",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"claude-opus-4-1":{id:"claude-opus-4-1",name:"Claude Opus 4.1 (latest)",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"claude-opus-4-5":{id:"claude-opus-4-5",name:"Claude Opus 4.5 (latest)",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:2e5,maxTokens:64e3},"claude-opus-4-6":{id:"claude-opus-4-6",name:"Claude Opus 4.6 (latest)",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!0,thinkingLevelMap:{xhigh:"max"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"claude-opus-4-7":{id:"claude-opus-4-7",name:"Claude Opus 4.7",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"claude-sonnet-4":{id:"claude-sonnet-4",name:"Claude Sonnet 4 (latest)",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"claude-sonnet-4-5":{id:"claude-sonnet-4-5",name:"Claude Sonnet 4.5 (latest)",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"claude-sonnet-4-6":{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3},"gpt-4":{id:"gpt-4",name:"GPT-4",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!1,input:["text"],cost:{input:30,output:60,cacheRead:0,cacheWrite:0},contextWindow:8192,maxTokens:8192},"gpt-4-turbo":{id:"gpt-4-turbo",name:"GPT-4 Turbo",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!1,input:["text","image"],cost:{input:10,output:30,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"gpt-4o":{id:"gpt-4o",name:"GPT-4o",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!1,input:["text","image"],cost:{input:2.5,output:10,cacheRead:1.25,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-4o-mini":{id:"gpt-4o-mini",name:"GPT-4o mini",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!1,input:["text","image"],cost:{input:.15,output:.6,cacheRead:.08,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-5.1":{id:"gpt-5.1",name:"GPT-5.1",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.13,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.1-codex":{id:"gpt-5.1-codex",name:"GPT-5.1 Codex",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.2":{id:"gpt-5.2",name:"GPT-5.2",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.2-codex":{id:"gpt-5.2-codex",name:"GPT-5.2 Codex",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},"gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},o1:{id:"o1",name:"o1",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!0,input:["text","image"],cost:{input:15,output:60,cacheRead:7.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},o3:{id:"o3",name:"o3",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!0,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o3-mini":{id:"o3-mini",name:"o3-mini",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.55,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o3-pro":{id:"o3-pro",name:"o3-pro",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!0,input:["text","image"],cost:{input:20,output:80,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o4-mini":{id:"o4-mini",name:"o4-mini",api:"openai-responses",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai",reasoning:!0,input:["text","image"],cost:{input:1.1,output:4.4,cacheRead:.28,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"workers-ai/@cf/moonshotai/kimi-k2.5":{id:"workers-ai/@cf/moonshotai/kimi-k2.5",name:"Kimi K2.5",api:"openai-completions",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/compat",compat:{sendSessionAffinityHeaders:!0},reasoning:!0,input:["text","image"],cost:{input:.6,output:3,cacheRead:.1,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"workers-ai/@cf/moonshotai/kimi-k2.6":{id:"workers-ai/@cf/moonshotai/kimi-k2.6",name:"Kimi K2.6",api:"openai-completions",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/compat",compat:{sendSessionAffinityHeaders:!0},reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.16,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"workers-ai/@cf/nvidia/nemotron-3-120b-a12b":{id:"workers-ai/@cf/nvidia/nemotron-3-120b-a12b",name:"Nemotron 3 Super 120B",api:"openai-completions",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/compat",compat:{sendSessionAffinityHeaders:!0},reasoning:!0,input:["text"],cost:{input:.5,output:1.5,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"workers-ai/@cf/zai-org/glm-4.7-flash":{id:"workers-ai/@cf/zai-org/glm-4.7-flash",name:"GLM-4.7-Flash",api:"openai-completions",provider:"cloudflare-ai-gateway",baseUrl:"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/compat",compat:{sendSessionAffinityHeaders:!0},reasoning:!0,input:["text"],cost:{input:.06,output:.4,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072}},"cloudflare-workers-ai":{"@cf/google/gemma-4-26b-a4b-it":{id:"@cf/google/gemma-4-26b-a4b-it",name:"Gemma 4 26B A4B IT",api:"openai-completions",provider:"cloudflare-workers-ai",baseUrl:"https://api.cloudflare.com/client/v4/accounts/{CLOUDFLARE_ACCOUNT_ID}/ai/v1",compat:{sendSessionAffinityHeaders:!0},reasoning:!0,input:["text","image"],cost:{input:.1,output:.3,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:16384},"@cf/meta/llama-4-scout-17b-16e-instruct":{id:"@cf/meta/llama-4-scout-17b-16e-instruct",name:"Llama 4 Scout 17B 16E Instruct",api:"openai-completions",provider:"cloudflare-workers-ai",baseUrl:"https://api.cloudflare.com/client/v4/accounts/{CLOUDFLARE_ACCOUNT_ID}/ai/v1",compat:{sendSessionAffinityHeaders:!0},reasoning:!1,input:["text","image"],cost:{input:.27,output:.85,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"@cf/moonshotai/kimi-k2.5":{id:"@cf/moonshotai/kimi-k2.5",name:"Kimi K2.5",api:"openai-completions",provider:"cloudflare-workers-ai",baseUrl:"https://api.cloudflare.com/client/v4/accounts/{CLOUDFLARE_ACCOUNT_ID}/ai/v1",compat:{sendSessionAffinityHeaders:!0},reasoning:!0,input:["text","image"],cost:{input:.6,output:3,cacheRead:.1,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"@cf/moonshotai/kimi-k2.6":{id:"@cf/moonshotai/kimi-k2.6",name:"Kimi K2.6",api:"openai-completions",provider:"cloudflare-workers-ai",baseUrl:"https://api.cloudflare.com/client/v4/accounts/{CLOUDFLARE_ACCOUNT_ID}/ai/v1",compat:{sendSessionAffinityHeaders:!0},reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.16,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"@cf/nvidia/nemotron-3-120b-a12b":{id:"@cf/nvidia/nemotron-3-120b-a12b",name:"Nemotron 3 Super 120B",api:"openai-completions",provider:"cloudflare-workers-ai",baseUrl:"https://api.cloudflare.com/client/v4/accounts/{CLOUDFLARE_ACCOUNT_ID}/ai/v1",compat:{sendSessionAffinityHeaders:!0},reasoning:!0,input:["text"],cost:{input:.5,output:1.5,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"@cf/openai/gpt-oss-120b":{id:"@cf/openai/gpt-oss-120b",name:"GPT OSS 120B",api:"openai-completions",provider:"cloudflare-workers-ai",baseUrl:"https://api.cloudflare.com/client/v4/accounts/{CLOUDFLARE_ACCOUNT_ID}/ai/v1",compat:{sendSessionAffinityHeaders:!0},reasoning:!0,input:["text"],cost:{input:.35,output:.75,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"@cf/openai/gpt-oss-20b":{id:"@cf/openai/gpt-oss-20b",name:"GPT OSS 20B",api:"openai-completions",provider:"cloudflare-workers-ai",baseUrl:"https://api.cloudflare.com/client/v4/accounts/{CLOUDFLARE_ACCOUNT_ID}/ai/v1",compat:{sendSessionAffinityHeaders:!0},reasoning:!0,input:["text"],cost:{input:.2,output:.3,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"@cf/zai-org/glm-4.7-flash":{id:"@cf/zai-org/glm-4.7-flash",name:"GLM-4.7-Flash",api:"openai-completions",provider:"cloudflare-workers-ai",baseUrl:"https://api.cloudflare.com/client/v4/accounts/{CLOUDFLARE_ACCOUNT_ID}/ai/v1",compat:{sendSessionAffinityHeaders:!0},reasoning:!0,input:["text"],cost:{input:.06,output:.4,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072}},deepseek:{"deepseek-v4-flash":{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",api:"openai-completions",provider:"deepseek",baseUrl:"https://api.deepseek.com",compat:{requiresReasoningContentOnAssistantMessages:!0,thinkingFormat:"deepseek"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null,high:"high",xhigh:"max"},input:["text"],cost:{input:.14,output:.28,cacheRead:.0028,cacheWrite:0},contextWindow:1e6,maxTokens:384e3},"deepseek-v4-pro":{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",api:"openai-completions",provider:"deepseek",baseUrl:"https://api.deepseek.com",compat:{requiresReasoningContentOnAssistantMessages:!0,thinkingFormat:"deepseek"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null,high:"high",xhigh:"max"},input:["text"],cost:{input:.435,output:.87,cacheRead:.003625,cacheWrite:0},contextWindow:1e6,maxTokens:384e3}},fireworks:{"accounts/fireworks/models/deepseek-v3p1":{id:"accounts/fireworks/models/deepseek-v3p1",name:"DeepSeek V3.1",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text"],cost:{input:.56,output:1.68,cacheRead:0,cacheWrite:0},contextWindow:163840,maxTokens:163840},"accounts/fireworks/models/deepseek-v3p2":{id:"accounts/fireworks/models/deepseek-v3p2",name:"DeepSeek V3.2",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text"],cost:{input:.56,output:1.68,cacheRead:.28,cacheWrite:0},contextWindow:16e4,maxTokens:16e4},"accounts/fireworks/models/deepseek-v4-pro":{id:"accounts/fireworks/models/deepseek-v4-pro",name:"DeepSeek V4 Pro",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text"],cost:{input:1.74,output:3.48,cacheRead:.15,cacheWrite:0},contextWindow:1e6,maxTokens:384e3},"accounts/fireworks/models/glm-4p5":{id:"accounts/fireworks/models/glm-4p5",name:"GLM 4.5",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text"],cost:{input:.55,output:2.19,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"accounts/fireworks/models/glm-4p5-air":{id:"accounts/fireworks/models/glm-4p5-air",name:"GLM 4.5 Air",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text"],cost:{input:.22,output:.88,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"accounts/fireworks/models/glm-4p7":{id:"accounts/fireworks/models/glm-4p7",name:"GLM 4.7",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text"],cost:{input:.6,output:2.2,cacheRead:.3,cacheWrite:0},contextWindow:198e3,maxTokens:198e3},"accounts/fireworks/models/glm-5":{id:"accounts/fireworks/models/glm-5",name:"GLM 5",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text"],cost:{input:1,output:3.2,cacheRead:.5,cacheWrite:0},contextWindow:202752,maxTokens:131072},"accounts/fireworks/models/glm-5p1":{id:"accounts/fireworks/models/glm-5p1",name:"GLM 5.1",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text"],cost:{input:1.4,output:4.4,cacheRead:.26,cacheWrite:0},contextWindow:202800,maxTokens:131072},"accounts/fireworks/models/gpt-oss-120b":{id:"accounts/fireworks/models/gpt-oss-120b",name:"GPT OSS 120B",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text"],cost:{input:.15,output:.6,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"accounts/fireworks/models/gpt-oss-20b":{id:"accounts/fireworks/models/gpt-oss-20b",name:"GPT OSS 20B",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text"],cost:{input:.05,output:.2,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"accounts/fireworks/models/kimi-k2-instruct":{id:"accounts/fireworks/models/kimi-k2-instruct",name:"Kimi K2 Instruct",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!1,input:["text"],cost:{input:1,output:3,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"accounts/fireworks/models/kimi-k2-thinking":{id:"accounts/fireworks/models/kimi-k2-thinking",name:"Kimi K2 Thinking",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text"],cost:{input:.6,output:2.5,cacheRead:.3,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"accounts/fireworks/models/kimi-k2p5":{id:"accounts/fireworks/models/kimi-k2p5",name:"Kimi K2.5",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text","image"],cost:{input:.6,output:3,cacheRead:.1,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"accounts/fireworks/models/kimi-k2p6":{id:"accounts/fireworks/models/kimi-k2p6",name:"Kimi K2.6",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.16,cacheWrite:0},contextWindow:262e3,maxTokens:262e3},"accounts/fireworks/models/minimax-m2p1":{id:"accounts/fireworks/models/minimax-m2p1",name:"MiniMax-M2.1",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.03,cacheWrite:0},contextWindow:2e5,maxTokens:2e5},"accounts/fireworks/models/minimax-m2p5":{id:"accounts/fireworks/models/minimax-m2p5",name:"MiniMax-M2.5",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.03,cacheWrite:0},contextWindow:196608,maxTokens:196608},"accounts/fireworks/models/minimax-m2p7":{id:"accounts/fireworks/models/minimax-m2p7",name:"MiniMax-M2.7",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.03,cacheWrite:0},contextWindow:196608,maxTokens:196608},"accounts/fireworks/models/qwen3p6-plus":{id:"accounts/fireworks/models/qwen3p6-plus",name:"Qwen 3.6 Plus",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text","image"],cost:{input:.5,output:3,cacheRead:.1,cacheWrite:0},contextWindow:128e3,maxTokens:8192},"accounts/fireworks/routers/kimi-k2p5-turbo":{id:"accounts/fireworks/routers/kimi-k2p5-turbo",name:"Kimi K2.5 Turbo",api:"anthropic-messages",provider:"fireworks",baseUrl:"https://api.fireworks.ai/inference",reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:256e3}},"github-copilot":{"claude-haiku-4.5":{id:"claude-haiku-4.5",name:"Claude Haiku 4.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1},reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:144e3,maxTokens:32e3},"claude-opus-4.5":{id:"claude-opus-4.5",name:"Claude Opus 4.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:16e4,maxTokens:32e3},"claude-opus-4.6":{id:"claude-opus-4.6",name:"Claude Opus 4.6",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,thinkingLevelMap:{xhigh:"max"},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:1e6,maxTokens:64e3},"claude-opus-4.7":{id:"claude-opus-4.7",name:"Claude Opus 4.7",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:144e3,maxTokens:64e3},"claude-sonnet-4":{id:"claude-sonnet-4",name:"Claude Sonnet 4",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1},reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:216e3,maxTokens:16e3},"claude-sonnet-4.5":{id:"claude-sonnet-4.5",name:"Claude Sonnet 4.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1},reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:144e3,maxTokens:32e3},"claude-sonnet-4.6":{id:"claude-sonnet-4.6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:1e6,maxTokens:32e3},"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:64e3},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:64e3},"gemini-3-pro-preview":{id:"gemini-3-pro-preview",name:"Gemini 3 Pro Preview",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:64e3},"gemini-3.1-pro-preview":{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:64e3},"gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-4o":{id:"gpt-4o",name:"GPT-4o",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"gpt-5":{id:"gpt-5",name:"GPT-5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:128e3},"gpt-5-mini":{id:"gpt-5-mini",name:"GPT-5-mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:264e3,maxTokens:64e3},"gpt-5.1":{id:"gpt-5.1",name:"GPT-5.1",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:264e3,maxTokens:64e3},"gpt-5.1-codex":{id:"gpt-5.1-codex",name:"GPT-5.1-Codex",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.1-codex-max":{id:"gpt-5.1-codex-max",name:"GPT-5.1-Codex-max",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.1-codex-mini":{id:"gpt-5.1-codex-mini",name:"GPT-5.1-Codex-mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.2":{id:"gpt-5.2",name:"GPT-5.2",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:264e3,maxTokens:64e3},"gpt-5.2-codex":{id:"gpt-5.2-codex",name:"GPT-5.2-Codex",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3-Codex",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.4-mini":{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"grok-code-fast-1":{id:"grok-code-fast-1",name:"Grok Code Fast 1",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:64e3}},google:{"gemini-1.5-flash":{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!1,input:["text","image"],cost:{input:.075,output:.3,cacheRead:.01875,cacheWrite:0},contextWindow:1e6,maxTokens:8192},"gemini-1.5-flash-8b":{id:"gemini-1.5-flash-8b",name:"Gemini 1.5 Flash-8B",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!1,input:["text","image"],cost:{input:.0375,output:.15,cacheRead:.01,cacheWrite:0},contextWindow:1e6,maxTokens:8192},"gemini-1.5-pro":{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!1,input:["text","image"],cost:{input:1.25,output:5,cacheRead:.3125,cacheWrite:0},contextWindow:1e6,maxTokens:8192},"gemini-2.0-flash":{id:"gemini-2.0-flash",name:"Gemini 2.0 Flash",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!1,input:["text","image"],cost:{input:.1,output:.4,cacheRead:.025,cacheWrite:0},contextWindow:1048576,maxTokens:8192},"gemini-2.0-flash-lite":{id:"gemini-2.0-flash-lite",name:"Gemini 2.0 Flash Lite",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!1,input:["text","image"],cost:{input:.075,output:.3,cacheRead:0,cacheWrite:0},contextWindow:1048576,maxTokens:8192},"gemini-2.5-flash":{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,input:["text","image"],cost:{input:.3,output:2.5,cacheRead:.03,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-2.5-flash-lite":{id:"gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,input:["text","image"],cost:{input:.1,output:.4,cacheRead:.025,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-2.5-flash-lite-preview-06-17":{id:"gemini-2.5-flash-lite-preview-06-17",name:"Gemini 2.5 Flash Lite Preview 06-17",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,input:["text","image"],cost:{input:.1,output:.4,cacheRead:.025,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-2.5-flash-lite-preview-09-2025":{id:"gemini-2.5-flash-lite-preview-09-2025",name:"Gemini 2.5 Flash Lite Preview 09-25",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,input:["text","image"],cost:{input:.1,output:.4,cacheRead:.025,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-2.5-flash-preview-04-17":{id:"gemini-2.5-flash-preview-04-17",name:"Gemini 2.5 Flash Preview 04-17",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,input:["text","image"],cost:{input:.15,output:.6,cacheRead:.0375,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-2.5-flash-preview-05-20":{id:"gemini-2.5-flash-preview-05-20",name:"Gemini 2.5 Flash Preview 05-20",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,input:["text","image"],cost:{input:.15,output:.6,cacheRead:.0375,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-2.5-flash-preview-09-2025":{id:"gemini-2.5-flash-preview-09-2025",name:"Gemini 2.5 Flash Preview 09-25",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,input:["text","image"],cost:{input:.3,output:2.5,cacheRead:.075,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-2.5-pro-preview-05-06":{id:"gemini-2.5-pro-preview-05-06",name:"Gemini 2.5 Pro Preview 05-06",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.31,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-2.5-pro-preview-06-05":{id:"gemini-2.5-pro-preview-06-05",name:"Gemini 2.5 Pro Preview 06-05",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.31,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:.5,output:3,cacheRead:.05,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-3-pro-preview":{id:"gemini-3-pro-preview",name:"Gemini 3 Pro Preview",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:"LOW",medium:null,high:"HIGH"},input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:0},contextWindow:1e6,maxTokens:64e3},"gemini-3.1-flash-lite":{id:"gemini-3.1-flash-lite",name:"Gemini 3.1 Flash Lite",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:.25,output:1.5,cacheRead:.025,cacheWrite:1},contextWindow:1048576,maxTokens:65536},"gemini-3.1-flash-lite-preview":{id:"gemini-3.1-flash-lite-preview",name:"Gemini 3.1 Flash Lite Preview",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:.25,output:1.5,cacheRead:.025,cacheWrite:1},contextWindow:1048576,maxTokens:65536},"gemini-3.1-pro-preview":{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:"LOW",medium:null,high:"HIGH"},input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-3.1-pro-preview-customtools":{id:"gemini-3.1-pro-preview-customtools",name:"Gemini 3.1 Pro Preview Custom Tools",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:"LOW",medium:null,high:"HIGH"},input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-flash-latest":{id:"gemini-flash-latest",name:"Gemini Flash Latest",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,input:["text","image"],cost:{input:.3,output:2.5,cacheRead:.075,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-flash-lite-latest":{id:"gemini-flash-lite-latest",name:"Gemini Flash-Lite Latest",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,input:["text","image"],cost:{input:.1,output:.4,cacheRead:.025,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-live-2.5-flash":{id:"gemini-live-2.5-flash",name:"Gemini Live 2.5 Flash",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,input:["text","image"],cost:{input:.5,output:2,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8e3},"gemini-live-2.5-flash-preview-native-audio":{id:"gemini-live-2.5-flash-preview-native-audio",name:"Gemini Live 2.5 Flash Preview Native Audio",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,input:["text"],cost:{input:.5,output:2,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:65536},"gemma-3-27b-it":{id:"gemma-3-27b-it",name:"Gemma 3 27B",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:8192},"gemma-4-26b-a4b-it":{id:"gemma-4-26b-a4b-it",name:"Gemma 4 26B",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,thinkingLevelMap:{off:null,minimal:"MINIMAL",low:null,medium:null,high:"HIGH"},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:8192},"gemma-4-31b-it":{id:"gemma-4-31b-it",name:"Gemma 4 31B",api:"google-generative-ai",provider:"google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",reasoning:!0,thinkingLevelMap:{off:null,minimal:"MINIMAL",low:null,medium:null,high:"HIGH"},input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:8192}},"google-vertex":{"gemini-1.5-flash":{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash (Vertex)",api:"google-vertex",provider:"google-vertex",baseUrl:"https://{location}-aiplatform.googleapis.com",reasoning:!1,input:["text","image"],cost:{input:.075,output:.3,cacheRead:.01875,cacheWrite:0},contextWindow:1e6,maxTokens:8192},"gemini-1.5-flash-8b":{id:"gemini-1.5-flash-8b",name:"Gemini 1.5 Flash-8B (Vertex)",api:"google-vertex",provider:"google-vertex",baseUrl:"https://{location}-aiplatform.googleapis.com",reasoning:!1,input:["text","image"],cost:{input:.0375,output:.15,cacheRead:.01,cacheWrite:0},contextWindow:1e6,maxTokens:8192},"gemini-1.5-pro":{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro (Vertex)",api:"google-vertex",provider:"google-vertex",baseUrl:"https://{location}-aiplatform.googleapis.com",reasoning:!1,input:["text","image"],cost:{input:1.25,output:5,cacheRead:.3125,cacheWrite:0},contextWindow:1e6,maxTokens:8192},"gemini-2.0-flash":{id:"gemini-2.0-flash",name:"Gemini 2.0 Flash (Vertex)",api:"google-vertex",provider:"google-vertex",baseUrl:"https://{location}-aiplatform.googleapis.com",reasoning:!1,input:["text","image"],cost:{input:.15,output:.6,cacheRead:.0375,cacheWrite:0},contextWindow:1048576,maxTokens:8192},"gemini-2.0-flash-lite":{id:"gemini-2.0-flash-lite",name:"Gemini 2.0 Flash Lite (Vertex)",api:"google-vertex",provider:"google-vertex",baseUrl:"https://{location}-aiplatform.googleapis.com",reasoning:!0,input:["text","image"],cost:{input:.075,output:.3,cacheRead:.01875,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-2.5-flash":{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash (Vertex)",api:"google-vertex",provider:"google-vertex",baseUrl:"https://{location}-aiplatform.googleapis.com",reasoning:!0,input:["text","image"],cost:{input:.3,output:2.5,cacheRead:.03,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-2.5-flash-lite":{id:"gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite (Vertex)",api:"google-vertex",provider:"google-vertex",baseUrl:"https://{location}-aiplatform.googleapis.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.4,cacheRead:.01,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-2.5-flash-lite-preview-09-2025":{id:"gemini-2.5-flash-lite-preview-09-2025",name:"Gemini 2.5 Flash Lite Preview 09-25 (Vertex)",api:"google-vertex",provider:"google-vertex",baseUrl:"https://{location}-aiplatform.googleapis.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.4,cacheRead:.01,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro (Vertex)",api:"google-vertex",provider:"google-vertex",baseUrl:"https://{location}-aiplatform.googleapis.com",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview (Vertex)",api:"google-vertex",provider:"google-vertex",baseUrl:"https://{location}-aiplatform.googleapis.com",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:.5,output:3,cacheRead:.05,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-3-pro-preview":{id:"gemini-3-pro-preview",name:"Gemini 3 Pro Preview (Vertex)",api:"google-vertex",provider:"google-vertex",baseUrl:"https://{location}-aiplatform.googleapis.com",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:"LOW",medium:null,high:"HIGH"},input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:0},contextWindow:1e6,maxTokens:64e3},"gemini-3.1-pro-preview":{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview (Vertex)",api:"google-vertex",provider:"google-vertex",baseUrl:"https://{location}-aiplatform.googleapis.com",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:"LOW",medium:null,high:"HIGH"},input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-3.1-pro-preview-customtools":{id:"gemini-3.1-pro-preview-customtools",name:"Gemini 3.1 Pro Preview Custom Tools (Vertex)",api:"google-vertex",provider:"google-vertex",baseUrl:"https://{location}-aiplatform.googleapis.com",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:"LOW",medium:null,high:"HIGH"},input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:0},contextWindow:1048576,maxTokens:65536}},groq:{"deepseek-r1-distill-llama-70b":{id:"deepseek-r1-distill-llama-70b",name:"DeepSeek R1 Distill Llama 70B",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!0,input:["text"],cost:{input:.75,output:.99,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:8192},"gemma2-9b-it":{id:"gemma2-9b-it",name:"Gemma 2 9B",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!1,input:["text"],cost:{input:.2,output:.2,cacheRead:0,cacheWrite:0},contextWindow:8192,maxTokens:8192},"groq/compound":{id:"groq/compound",name:"Compound",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:8192},"groq/compound-mini":{id:"groq/compound-mini",name:"Compound Mini",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:8192},"llama-3.1-8b-instant":{id:"llama-3.1-8b-instant",name:"Llama 3.1 8B Instant",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!1,input:["text"],cost:{input:.05,output:.08,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"llama-3.3-70b-versatile":{id:"llama-3.3-70b-versatile",name:"Llama 3.3 70B Versatile",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!1,input:["text"],cost:{input:.59,output:.79,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"llama3-70b-8192":{id:"llama3-70b-8192",name:"Llama 3 70B",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!1,input:["text"],cost:{input:.59,output:.79,cacheRead:0,cacheWrite:0},contextWindow:8192,maxTokens:8192},"llama3-8b-8192":{id:"llama3-8b-8192",name:"Llama 3 8B",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!1,input:["text"],cost:{input:.05,output:.08,cacheRead:0,cacheWrite:0},contextWindow:8192,maxTokens:8192},"meta-llama/llama-4-maverick-17b-128e-instruct":{id:"meta-llama/llama-4-maverick-17b-128e-instruct",name:"Llama 4 Maverick 17B",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!1,input:["text","image"],cost:{input:.2,output:.6,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:8192},"meta-llama/llama-4-scout-17b-16e-instruct":{id:"meta-llama/llama-4-scout-17b-16e-instruct",name:"Llama 4 Scout 17B",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!1,input:["text","image"],cost:{input:.11,output:.34,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:8192},"mistral-saba-24b":{id:"mistral-saba-24b",name:"Mistral Saba 24B",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!1,input:["text"],cost:{input:.79,output:.79,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:32768},"moonshotai/kimi-k2-instruct":{id:"moonshotai/kimi-k2-instruct",name:"Kimi K2 Instruct",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!1,input:["text"],cost:{input:1,output:3,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:16384},"moonshotai/kimi-k2-instruct-0905":{id:"moonshotai/kimi-k2-instruct-0905",name:"Kimi K2 Instruct 0905",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!1,input:["text"],cost:{input:1,output:3,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:16384},"openai/gpt-oss-120b":{id:"openai/gpt-oss-120b",name:"GPT OSS 120B",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!0,input:["text"],cost:{input:.15,output:.6,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:65536},"openai/gpt-oss-20b":{id:"openai/gpt-oss-20b",name:"GPT OSS 20B",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!0,input:["text"],cost:{input:.075,output:.3,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:65536},"openai/gpt-oss-safeguard-20b":{id:"openai/gpt-oss-safeguard-20b",name:"Safety GPT OSS 20B",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!0,input:["text"],cost:{input:.075,output:.3,cacheRead:.037,cacheWrite:0},contextWindow:131072,maxTokens:65536},"qwen-qwq-32b":{id:"qwen-qwq-32b",name:"Qwen QwQ 32B",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!0,input:["text"],cost:{input:.29,output:.39,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:16384},"qwen/qwen3-32b":{id:"qwen/qwen3-32b",name:"Qwen3 32B",api:"openai-completions",provider:"groq",baseUrl:"https://api.groq.com/openai/v1",reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null,high:"default"},input:["text"],cost:{input:.29,output:.59,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:40960}},huggingface:{"MiniMaxAI/MiniMax-M2.1":{id:"MiniMaxAI/MiniMax-M2.1",name:"MiniMax-M2.1",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:0,cacheWrite:0},contextWindow:204800,maxTokens:131072},"MiniMaxAI/MiniMax-M2.5":{id:"MiniMaxAI/MiniMax-M2.5",name:"MiniMax-M2.5",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.03,cacheWrite:0},contextWindow:204800,maxTokens:131072},"MiniMaxAI/MiniMax-M2.7":{id:"MiniMaxAI/MiniMax-M2.7",name:"MiniMax-M2.7",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.06,cacheWrite:0},contextWindow:204800,maxTokens:131072},"Qwen/Qwen3-235B-A22B-Thinking-2507":{id:"Qwen/Qwen3-235B-A22B-Thinking-2507",name:"Qwen3-235B-A22B-Thinking-2507",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text"],cost:{input:.3,output:3,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:131072},"Qwen/Qwen3-Coder-480B-A35B-Instruct":{id:"Qwen/Qwen3-Coder-480B-A35B-Instruct",name:"Qwen3-Coder-480B-A35B-Instruct",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!1,input:["text"],cost:{input:2,output:2,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:66536},"Qwen/Qwen3-Coder-Next":{id:"Qwen/Qwen3-Coder-Next",name:"Qwen3-Coder-Next",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!1,input:["text"],cost:{input:.2,output:1.5,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:65536},"Qwen/Qwen3-Next-80B-A3B-Instruct":{id:"Qwen/Qwen3-Next-80B-A3B-Instruct",name:"Qwen3-Next-80B-A3B-Instruct",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!1,input:["text"],cost:{input:.25,output:1,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:66536},"Qwen/Qwen3-Next-80B-A3B-Thinking":{id:"Qwen/Qwen3-Next-80B-A3B-Thinking",name:"Qwen3-Next-80B-A3B-Thinking",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!1,input:["text"],cost:{input:.3,output:2,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:131072},"Qwen/Qwen3.5-397B-A17B":{id:"Qwen/Qwen3.5-397B-A17B",name:"Qwen3.5-397B-A17B",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text","image"],cost:{input:.6,output:3.6,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:32768},"XiaomiMiMo/MiMo-V2-Flash":{id:"XiaomiMiMo/MiMo-V2-Flash",name:"MiMo-V2-Flash",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text"],cost:{input:.1,output:.3,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:4096},"deepseek-ai/DeepSeek-R1-0528":{id:"deepseek-ai/DeepSeek-R1-0528",name:"DeepSeek-R1-0528",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text"],cost:{input:3,output:5,cacheRead:0,cacheWrite:0},contextWindow:163840,maxTokens:163840},"deepseek-ai/DeepSeek-V3.2":{id:"deepseek-ai/DeepSeek-V3.2",name:"DeepSeek-V3.2",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text"],cost:{input:.28,output:.4,cacheRead:0,cacheWrite:0},contextWindow:163840,maxTokens:65536},"deepseek-ai/DeepSeek-V4-Pro":{id:"deepseek-ai/DeepSeek-V4-Pro",name:"DeepSeek V4 Pro",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text"],cost:{input:1.74,output:3.48,cacheRead:.145,cacheWrite:0},contextWindow:1048576,maxTokens:393216},"moonshotai/Kimi-K2-Instruct":{id:"moonshotai/Kimi-K2-Instruct",name:"Kimi-K2-Instruct",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!1,input:["text"],cost:{input:1,output:3,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:16384},"moonshotai/Kimi-K2-Instruct-0905":{id:"moonshotai/Kimi-K2-Instruct-0905",name:"Kimi-K2-Instruct-0905",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!1,input:["text"],cost:{input:1,output:3,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:16384},"moonshotai/Kimi-K2-Thinking":{id:"moonshotai/Kimi-K2-Thinking",name:"Kimi-K2-Thinking",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text"],cost:{input:.6,output:2.5,cacheRead:.15,cacheWrite:0},contextWindow:262144,maxTokens:262144},"moonshotai/Kimi-K2.5":{id:"moonshotai/Kimi-K2.5",name:"Kimi-K2.5",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text","image"],cost:{input:.6,output:3,cacheRead:.1,cacheWrite:0},contextWindow:262144,maxTokens:262144},"moonshotai/Kimi-K2.6":{id:"moonshotai/Kimi-K2.6",name:"Kimi-K2.6",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.16,cacheWrite:0},contextWindow:262144,maxTokens:262144},"zai-org/GLM-4.7":{id:"zai-org/GLM-4.7",name:"GLM-4.7",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text"],cost:{input:.6,output:2.2,cacheRead:.11,cacheWrite:0},contextWindow:204800,maxTokens:131072},"zai-org/GLM-4.7-Flash":{id:"zai-org/GLM-4.7-Flash",name:"GLM-4.7-Flash",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:128e3},"zai-org/GLM-5":{id:"zai-org/GLM-5",name:"GLM-5",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text"],cost:{input:1,output:3.2,cacheRead:.2,cacheWrite:0},contextWindow:202752,maxTokens:131072},"zai-org/GLM-5.1":{id:"zai-org/GLM-5.1",name:"GLM-5.1",api:"openai-completions",provider:"huggingface",baseUrl:"https://router.huggingface.co/v1",compat:{supportsDeveloperRole:!1},reasoning:!0,input:["text"],cost:{input:1,output:3.2,cacheRead:.2,cacheWrite:0},contextWindow:202752,maxTokens:131072}},"kimi-coding":{"kimi-for-coding":{id:"kimi-for-coding",name:"Kimi For Coding",api:"anthropic-messages",provider:"kimi-coding",baseUrl:"https://api.kimi.com/coding",headers:{"User-Agent":"KimiCLI/1.5"},reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:32768},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",api:"anthropic-messages",provider:"kimi-coding",baseUrl:"https://api.kimi.com/coding",headers:{"User-Agent":"KimiCLI/1.5"},reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:32768}},minimax:{"MiniMax-M2.7":{id:"MiniMax-M2.7",name:"MiniMax-M2.7",api:"anthropic-messages",provider:"minimax",baseUrl:"https://api.minimax.io/anthropic",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.06,cacheWrite:.375},contextWindow:204800,maxTokens:131072},"MiniMax-M2.7-highspeed":{id:"MiniMax-M2.7-highspeed",name:"MiniMax-M2.7-highspeed",api:"anthropic-messages",provider:"minimax",baseUrl:"https://api.minimax.io/anthropic",reasoning:!0,input:["text"],cost:{input:.6,output:2.4,cacheRead:.06,cacheWrite:.375},contextWindow:204800,maxTokens:131072}},"minimax-cn":{"MiniMax-M2.7":{id:"MiniMax-M2.7",name:"MiniMax-M2.7",api:"anthropic-messages",provider:"minimax-cn",baseUrl:"https://api.minimaxi.com/anthropic",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.06,cacheWrite:.375},contextWindow:204800,maxTokens:131072},"MiniMax-M2.7-highspeed":{id:"MiniMax-M2.7-highspeed",name:"MiniMax-M2.7-highspeed",api:"anthropic-messages",provider:"minimax-cn",baseUrl:"https://api.minimaxi.com/anthropic",reasoning:!0,input:["text"],cost:{input:.6,output:2.4,cacheRead:.06,cacheWrite:.375},contextWindow:204800,maxTokens:131072}},mistral:{"codestral-latest":{id:"codestral-latest",name:"Codestral (latest)",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text"],cost:{input:.3,output:.9,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:4096},"devstral-2512":{id:"devstral-2512",name:"Devstral 2",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text"],cost:{input:.4,output:2,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"devstral-medium-2507":{id:"devstral-medium-2507",name:"Devstral Medium",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text"],cost:{input:.4,output:2,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:128e3},"devstral-medium-latest":{id:"devstral-medium-latest",name:"Devstral 2 (latest)",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text"],cost:{input:.4,output:2,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"devstral-small-2505":{id:"devstral-small-2505",name:"Devstral Small 2505",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text"],cost:{input:.1,output:.3,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:128e3},"devstral-small-2507":{id:"devstral-small-2507",name:"Devstral Small",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text"],cost:{input:.1,output:.3,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:128e3},"labs-devstral-small-2512":{id:"labs-devstral-small-2512",name:"Devstral Small 2",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"magistral-medium-latest":{id:"magistral-medium-latest",name:"Magistral Medium (latest)",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!0,input:["text"],cost:{input:2,output:5,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"magistral-small":{id:"magistral-small",name:"Magistral Small",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!0,input:["text"],cost:{input:.5,output:1.5,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:128e3},"ministral-3b-latest":{id:"ministral-3b-latest",name:"Ministral 3B (latest)",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text"],cost:{input:.04,output:.04,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:128e3},"ministral-8b-latest":{id:"ministral-8b-latest",name:"Ministral 8B (latest)",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text"],cost:{input:.1,output:.1,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:128e3},"mistral-large-2411":{id:"mistral-large-2411",name:"Mistral Large 2.1",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text"],cost:{input:2,output:6,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:16384},"mistral-large-2512":{id:"mistral-large-2512",name:"Mistral Large 3",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text","image"],cost:{input:.5,output:1.5,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"mistral-large-latest":{id:"mistral-large-latest",name:"Mistral Large (latest)",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text","image"],cost:{input:.5,output:1.5,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"mistral-medium-2505":{id:"mistral-medium-2505",name:"Mistral Medium 3",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text","image"],cost:{input:.4,output:2,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"mistral-medium-2508":{id:"mistral-medium-2508",name:"Mistral Medium 3.1",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text","image"],cost:{input:.4,output:2,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"mistral-medium-2604":{id:"mistral-medium-2604",name:"Mistral Medium 3.5",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!0,input:["text","image"],cost:{input:1.5,output:7.5,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"mistral-medium-3.5":{id:"mistral-medium-3.5",name:"Mistral Medium 3.5",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!0,input:["text","image"],cost:{input:1.5,output:7.5,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"mistral-medium-latest":{id:"mistral-medium-latest",name:"Mistral Medium (latest)",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!0,input:["text","image"],cost:{input:1.5,output:7.5,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"mistral-nemo":{id:"mistral-nemo",name:"Mistral Nemo",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text"],cost:{input:.15,output:.15,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:128e3},"mistral-small-2506":{id:"mistral-small-2506",name:"Mistral Small 3.2",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text","image"],cost:{input:.1,output:.3,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"mistral-small-2603":{id:"mistral-small-2603",name:"Mistral Small 4",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!0,input:["text","image"],cost:{input:.15,output:.6,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"mistral-small-latest":{id:"mistral-small-latest",name:"Mistral Small (latest)",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!0,input:["text","image"],cost:{input:.15,output:.6,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"open-mistral-7b":{id:"open-mistral-7b",name:"Mistral 7B",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text"],cost:{input:.25,output:.25,cacheRead:0,cacheWrite:0},contextWindow:8e3,maxTokens:8e3},"open-mixtral-8x22b":{id:"open-mixtral-8x22b",name:"Mixtral 8x22B",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text"],cost:{input:2,output:6,cacheRead:0,cacheWrite:0},contextWindow:64e3,maxTokens:64e3},"open-mixtral-8x7b":{id:"open-mixtral-8x7b",name:"Mixtral 8x7B",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text"],cost:{input:.7,output:.7,cacheRead:0,cacheWrite:0},contextWindow:32e3,maxTokens:32e3},"pixtral-12b":{id:"pixtral-12b",name:"Pixtral 12B",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text","image"],cost:{input:.15,output:.15,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:128e3},"pixtral-large-latest":{id:"pixtral-large-latest",name:"Pixtral Large (latest)",api:"mistral-conversations",provider:"mistral",baseUrl:"https://api.mistral.ai",reasoning:!1,input:["text","image"],cost:{input:2,output:6,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:128e3}},moonshotai:{"kimi-k2-0711-preview":{id:"kimi-k2-0711-preview",name:"Kimi K2 0711",api:"openai-completions",provider:"moonshotai",baseUrl:"https://api.moonshot.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1},reasoning:!1,input:["text"],cost:{input:.6,output:2.5,cacheRead:.15,cacheWrite:0},contextWindow:131072,maxTokens:16384},"kimi-k2-0905-preview":{id:"kimi-k2-0905-preview",name:"Kimi K2 0905",api:"openai-completions",provider:"moonshotai",baseUrl:"https://api.moonshot.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1},reasoning:!1,input:["text"],cost:{input:.6,output:2.5,cacheRead:.15,cacheWrite:0},contextWindow:262144,maxTokens:262144},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",api:"openai-completions",provider:"moonshotai",baseUrl:"https://api.moonshot.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1},reasoning:!0,input:["text"],cost:{input:.6,output:2.5,cacheRead:.15,cacheWrite:0},contextWindow:262144,maxTokens:262144},"kimi-k2-thinking-turbo":{id:"kimi-k2-thinking-turbo",name:"Kimi K2 Thinking Turbo",api:"openai-completions",provider:"moonshotai",baseUrl:"https://api.moonshot.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1},reasoning:!0,input:["text"],cost:{input:1.15,output:8,cacheRead:.15,cacheWrite:0},contextWindow:262144,maxTokens:262144},"kimi-k2-turbo-preview":{id:"kimi-k2-turbo-preview",name:"Kimi K2 Turbo",api:"openai-completions",provider:"moonshotai",baseUrl:"https://api.moonshot.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1},reasoning:!1,input:["text"],cost:{input:2.4,output:10,cacheRead:.6,cacheWrite:0},contextWindow:262144,maxTokens:262144},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",api:"openai-completions",provider:"moonshotai",baseUrl:"https://api.moonshot.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1},reasoning:!0,input:["text","image"],cost:{input:.6,output:3,cacheRead:.1,cacheWrite:0},contextWindow:262144,maxTokens:262144},"kimi-k2.6":{id:"kimi-k2.6",name:"Kimi K2.6",api:"openai-completions",provider:"moonshotai",baseUrl:"https://api.moonshot.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1},reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.16,cacheWrite:0},contextWindow:262144,maxTokens:262144}},"moonshotai-cn":{"kimi-k2-0711-preview":{id:"kimi-k2-0711-preview",name:"Kimi K2 0711",api:"openai-completions",provider:"moonshotai-cn",baseUrl:"https://api.moonshot.cn/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1},reasoning:!1,input:["text"],cost:{input:.6,output:2.5,cacheRead:.15,cacheWrite:0},contextWindow:131072,maxTokens:16384},"kimi-k2-0905-preview":{id:"kimi-k2-0905-preview",name:"Kimi K2 0905",api:"openai-completions",provider:"moonshotai-cn",baseUrl:"https://api.moonshot.cn/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1},reasoning:!1,input:["text"],cost:{input:.6,output:2.5,cacheRead:.15,cacheWrite:0},contextWindow:262144,maxTokens:262144},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",api:"openai-completions",provider:"moonshotai-cn",baseUrl:"https://api.moonshot.cn/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1},reasoning:!0,input:["text"],cost:{input:.6,output:2.5,cacheRead:.15,cacheWrite:0},contextWindow:262144,maxTokens:262144},"kimi-k2-thinking-turbo":{id:"kimi-k2-thinking-turbo",name:"Kimi K2 Thinking Turbo",api:"openai-completions",provider:"moonshotai-cn",baseUrl:"https://api.moonshot.cn/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1},reasoning:!0,input:["text"],cost:{input:1.15,output:8,cacheRead:.15,cacheWrite:0},contextWindow:262144,maxTokens:262144},"kimi-k2-turbo-preview":{id:"kimi-k2-turbo-preview",name:"Kimi K2 Turbo",api:"openai-completions",provider:"moonshotai-cn",baseUrl:"https://api.moonshot.cn/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1},reasoning:!1,input:["text"],cost:{input:2.4,output:10,cacheRead:.6,cacheWrite:0},contextWindow:262144,maxTokens:262144},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",api:"openai-completions",provider:"moonshotai-cn",baseUrl:"https://api.moonshot.cn/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1},reasoning:!0,input:["text","image"],cost:{input:.6,output:3,cacheRead:.1,cacheWrite:0},contextWindow:262144,maxTokens:262144},"kimi-k2.6":{id:"kimi-k2.6",name:"Kimi K2.6",api:"openai-completions",provider:"moonshotai-cn",baseUrl:"https://api.moonshot.cn/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1},reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.16,cacheWrite:0},contextWindow:262144,maxTokens:262144}},openai:{"gpt-4":{id:"gpt-4",name:"GPT-4",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text"],cost:{input:30,output:60,cacheRead:0,cacheWrite:0},contextWindow:8192,maxTokens:8192},"gpt-4-turbo":{id:"gpt-4-turbo",name:"GPT-4 Turbo",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:10,output:30,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:1047576,maxTokens:32768},"gpt-4.1-mini":{id:"gpt-4.1-mini",name:"GPT-4.1 mini",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:.4,output:1.6,cacheRead:.1,cacheWrite:0},contextWindow:1047576,maxTokens:32768},"gpt-4.1-nano":{id:"gpt-4.1-nano",name:"GPT-4.1 nano",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:.1,output:.4,cacheRead:.03,cacheWrite:0},contextWindow:1047576,maxTokens:32768},"gpt-4o":{id:"gpt-4o",name:"GPT-4o",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:2.5,output:10,cacheRead:1.25,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-4o-2024-05-13":{id:"gpt-4o-2024-05-13",name:"GPT-4o (2024-05-13)",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:5,output:15,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"gpt-4o-2024-08-06":{id:"gpt-4o-2024-08-06",name:"GPT-4o (2024-08-06)",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:2.5,output:10,cacheRead:1.25,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-4o-2024-11-20":{id:"gpt-4o-2024-11-20",name:"GPT-4o (2024-11-20)",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:2.5,output:10,cacheRead:1.25,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-4o-mini":{id:"gpt-4o-mini",name:"GPT-4o mini",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:.15,output:.6,cacheRead:.08,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-5":{id:"gpt-5",name:"GPT-5",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5-chat-latest":{id:"gpt-5-chat-latest",name:"GPT-5 Chat Latest",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-5-codex":{id:"gpt-5-codex",name:"GPT-5-Codex",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5-mini":{id:"gpt-5-mini",name:"GPT-5 Mini",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5-nano":{id:"gpt-5-nano",name:"GPT-5 Nano",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:.05,output:.4,cacheRead:.005,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5-pro":{id:"gpt-5-pro",name:"GPT-5 Pro",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:15,output:120,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:272e3},"gpt-5.1":{id:"gpt-5.1",name:"GPT-5.1",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:"none"},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.13,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.1-chat-latest":{id:"gpt-5.1-chat-latest",name:"GPT-5.1 Chat",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-5.1-codex":{id:"gpt-5.1-codex",name:"GPT-5.1 Codex",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.1-codex-max":{id:"gpt-5.1-codex-max",name:"GPT-5.1 Codex Max",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.1-codex-mini":{id:"gpt-5.1-codex-mini",name:"GPT-5.1 Codex mini",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.2":{id:"gpt-5.2",name:"GPT-5.2",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:"none",xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.2-chat-latest":{id:"gpt-5.2-chat-latest",name:"GPT-5.2 Chat",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-5.2-codex":{id:"gpt-5.2-codex",name:"GPT-5.2 Codex",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.2-pro":{id:"gpt-5.2-pro",name:"GPT-5.2 Pro",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:21,output:168,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.3-chat-latest":{id:"gpt-5.3-chat-latest",name:"GPT-5.3 Chat (latest)",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:"none",xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.3-codex-spark":{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:128e3,maxTokens:32e3},"gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:"none",xhigh:"xhigh"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0},contextWindow:272e3,maxTokens:128e3},"gpt-5.4-mini":{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:"none",xhigh:"xhigh"},input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.4-nano":{id:"gpt-5.4-nano",name:"GPT-5.4 nano",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:"none",xhigh:"xhigh"},input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.4-pro":{id:"gpt-5.4-pro",name:"GPT-5.4 Pro",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:30,output:180,cacheRead:0,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},"gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:"none",xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0},contextWindow:272e3,maxTokens:128e3},"gpt-5.5-pro":{id:"gpt-5.5-pro",name:"GPT-5.5 Pro",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:30,output:180,cacheRead:0,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},o1:{id:"o1",name:"o1",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:15,output:60,cacheRead:7.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o1-pro":{id:"o1-pro",name:"o1-pro",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:150,output:600,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},o3:{id:"o3",name:"o3",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o3-deep-research":{id:"o3-deep-research",name:"o3-deep-research",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:10,output:40,cacheRead:2.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o3-mini":{id:"o3-mini",name:"o3-mini",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.55,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o3-pro":{id:"o3-pro",name:"o3-pro",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:20,output:80,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o4-mini":{id:"o4-mini",name:"o4-mini",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:1.1,output:4.4,cacheRead:.28,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"o4-mini-deep-research":{id:"o4-mini-deep-research",name:"o4-mini-deep-research",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5}},"openai-codex":{"gpt-5.1":{id:"gpt-5.1",name:"GPT-5.1",api:"openai-codex-responses",provider:"openai-codex",baseUrl:"https://chatgpt.com/backend-api",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:272e3,maxTokens:128e3},"gpt-5.1-codex-max":{id:"gpt-5.1-codex-max",name:"GPT-5.1 Codex Max",api:"openai-codex-responses",provider:"openai-codex",baseUrl:"https://chatgpt.com/backend-api",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:272e3,maxTokens:128e3},"gpt-5.1-codex-mini":{id:"gpt-5.1-codex-mini",name:"GPT-5.1 Codex Mini",api:"openai-codex-responses",provider:"openai-codex",baseUrl:"https://chatgpt.com/backend-api",reasoning:!0,thinkingLevelMap:{minimal:"medium",low:"medium",medium:"medium",high:"high"},input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:272e3,maxTokens:128e3},"gpt-5.2":{id:"gpt-5.2",name:"GPT-5.2",api:"openai-codex-responses",provider:"openai-codex",baseUrl:"https://chatgpt.com/backend-api",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:272e3,maxTokens:128e3},"gpt-5.2-codex":{id:"gpt-5.2-codex",name:"GPT-5.2 Codex",api:"openai-codex-responses",provider:"openai-codex",baseUrl:"https://chatgpt.com/backend-api",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:272e3,maxTokens:128e3},"gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-codex-responses",provider:"openai-codex",baseUrl:"https://chatgpt.com/backend-api",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:272e3,maxTokens:128e3},"gpt-5.3-codex-spark":{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",api:"openai-codex-responses",provider:"openai-codex",baseUrl:"https://chatgpt.com/backend-api",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:128e3},"gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"openai-codex-responses",provider:"openai-codex",baseUrl:"https://chatgpt.com/backend-api",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0},contextWindow:272e3,maxTokens:128e3},"gpt-5.4-mini":{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",api:"openai-codex-responses",provider:"openai-codex",baseUrl:"https://chatgpt.com/backend-api",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:272e3,maxTokens:128e3},"gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"openai-codex-responses",provider:"openai-codex",baseUrl:"https://chatgpt.com/backend-api",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0},contextWindow:272e3,maxTokens:128e3}},opencode:{"big-pickle":{id:"big-pickle",name:"Big Pickle",api:"openai-completions",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:128e3},"claude-haiku-4-5":{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",api:"anthropic-messages",provider:"opencode",baseUrl:"https://opencode.ai/zen",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3},"claude-opus-4-1":{id:"claude-opus-4-1",name:"Claude Opus 4.1",api:"anthropic-messages",provider:"opencode",baseUrl:"https://opencode.ai/zen",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"claude-opus-4-5":{id:"claude-opus-4-5",name:"Claude Opus 4.5",api:"anthropic-messages",provider:"opencode",baseUrl:"https://opencode.ai/zen",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:2e5,maxTokens:64e3},"claude-opus-4-6":{id:"claude-opus-4-6",name:"Claude Opus 4.6",api:"anthropic-messages",provider:"opencode",baseUrl:"https://opencode.ai/zen",reasoning:!0,thinkingLevelMap:{xhigh:"max"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"claude-opus-4-7":{id:"claude-opus-4-7",name:"Claude Opus 4.7",api:"anthropic-messages",provider:"opencode",baseUrl:"https://opencode.ai/zen",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"claude-sonnet-4":{id:"claude-sonnet-4",name:"Claude Sonnet 4",api:"anthropic-messages",provider:"opencode",baseUrl:"https://opencode.ai/zen",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"claude-sonnet-4-5":{id:"claude-sonnet-4-5",name:"Claude Sonnet 4.5",api:"anthropic-messages",provider:"opencode",baseUrl:"https://opencode.ai/zen",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"claude-sonnet-4-6":{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"opencode",baseUrl:"https://opencode.ai/zen",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3},"gemini-3-flash":{id:"gemini-3-flash",name:"Gemini 3 Flash",api:"google-generative-ai",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:.5,output:3,cacheRead:.05,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"gemini-3.1-pro":{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro Preview",api:"google-generative-ai",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:"LOW",medium:null,high:"HIGH"},input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"glm-5":{id:"glm-5",name:"GLM-5",api:"openai-completions",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,input:["text"],cost:{input:1,output:3.2,cacheRead:.2,cacheWrite:0},contextWindow:204800,maxTokens:131072},"glm-5.1":{id:"glm-5.1",name:"GLM-5.1",api:"openai-completions",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,input:["text"],cost:{input:1.4,output:4.4,cacheRead:.26,cacheWrite:0},contextWindow:204800,maxTokens:131072},"gpt-5":{id:"gpt-5",name:"GPT-5",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.07,output:8.5,cacheRead:.107,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5-codex":{id:"gpt-5-codex",name:"GPT-5 Codex",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.07,output:8.5,cacheRead:.107,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5-nano":{id:"gpt-5-nano",name:"GPT-5 Nano",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:.05,output:.4,cacheRead:.005,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.1":{id:"gpt-5.1",name:"GPT-5.1",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.07,output:8.5,cacheRead:.107,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.1-codex":{id:"gpt-5.1-codex",name:"GPT-5.1 Codex",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.07,output:8.5,cacheRead:.107,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.1-codex-max":{id:"gpt-5.1-codex-max",name:"GPT-5.1 Codex Max",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.1-codex-mini":{id:"gpt-5.1-codex-mini",name:"GPT-5.1 Codex Mini",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null},input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.2":{id:"gpt-5.2",name:"GPT-5.2",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.2-codex":{id:"gpt-5.2-codex",name:"GPT-5.2 Codex",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0},contextWindow:272e3,maxTokens:128e3},"gpt-5.4-mini":{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.4-nano":{id:"gpt-5.4-nano",name:"GPT-5.4 Nano",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"gpt-5.4-pro":{id:"gpt-5.4-pro",name:"GPT-5.4 Pro",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:30,output:180,cacheRead:30,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},"gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},"gpt-5.5-pro":{id:"gpt-5.5-pro",name:"GPT-5.5 Pro",api:"openai-responses",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,thinkingLevelMap:{off:null,xhigh:"xhigh"},input:["text","image"],cost:{input:30,output:180,cacheRead:30,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",api:"openai-completions",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,input:["text","image"],cost:{input:.6,output:3,cacheRead:.08,cacheWrite:0},contextWindow:262144,maxTokens:65536},"kimi-k2.6":{id:"kimi-k2.6",name:"Kimi K2.6",api:"openai-completions",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.16,cacheWrite:0},contextWindow:262144,maxTokens:65536},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",api:"openai-completions",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.06,cacheWrite:0},contextWindow:204800,maxTokens:131072},"minimax-m2.5-free":{id:"minimax-m2.5-free",name:"MiniMax M2.5 Free",api:"anthropic-messages",provider:"opencode",baseUrl:"https://opencode.ai/zen",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:204800,maxTokens:131072},"minimax-m2.7":{id:"minimax-m2.7",name:"MiniMax M2.7",api:"openai-completions",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.06,cacheWrite:0},contextWindow:204800,maxTokens:131072},"nemotron-3-super-free":{id:"nemotron-3-super-free",name:"Nemotron 3 Super Free",api:"openai-completions",provider:"opencode",baseUrl:"https://opencode.ai/zen/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:204800,maxTokens:128e3},"qwen3.5-plus":{id:"qwen3.5-plus",name:"Qwen3.5 Plus",api:"anthropic-messages",provider:"opencode",baseUrl:"https://opencode.ai/zen",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:.25},contextWindow:262144,maxTokens:65536},"qwen3.6-plus":{id:"qwen3.6-plus",name:"Qwen3.6 Plus",api:"anthropic-messages",provider:"opencode",baseUrl:"https://opencode.ai/zen",reasoning:!0,input:["text","image"],cost:{input:.5,output:3,cacheRead:.05,cacheWrite:.625},contextWindow:262144,maxTokens:65536}},"opencode-go":{"deepseek-v4-flash":{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",api:"openai-completions",provider:"opencode-go",baseUrl:"https://opencode.ai/zen/go/v1",compat:{requiresReasoningContentOnAssistantMessages:!0,thinkingFormat:"deepseek"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null,high:"high",xhigh:"max"},input:["text"],cost:{input:.14,output:.28,cacheRead:.0028,cacheWrite:0},contextWindow:1e6,maxTokens:384e3},"deepseek-v4-pro":{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",api:"openai-completions",provider:"opencode-go",baseUrl:"https://opencode.ai/zen/go/v1",compat:{requiresReasoningContentOnAssistantMessages:!0,thinkingFormat:"deepseek"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null,high:"high",xhigh:"max"},input:["text"],cost:{input:1.74,output:3.48,cacheRead:.0145,cacheWrite:0},contextWindow:1e6,maxTokens:384e3},"glm-5":{id:"glm-5",name:"GLM-5",api:"openai-completions",provider:"opencode-go",baseUrl:"https://opencode.ai/zen/go/v1",reasoning:!0,input:["text"],cost:{input:1,output:3.2,cacheRead:.2,cacheWrite:0},contextWindow:202752,maxTokens:32768},"glm-5.1":{id:"glm-5.1",name:"GLM-5.1",api:"openai-completions",provider:"opencode-go",baseUrl:"https://opencode.ai/zen/go/v1",reasoning:!0,input:["text"],cost:{input:1.4,output:4.4,cacheRead:.26,cacheWrite:0},contextWindow:202752,maxTokens:32768},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",api:"openai-completions",provider:"opencode-go",baseUrl:"https://opencode.ai/zen/go/v1",reasoning:!0,input:["text","image"],cost:{input:.6,output:3,cacheRead:.1,cacheWrite:0},contextWindow:262144,maxTokens:65536},"kimi-k2.6":{id:"kimi-k2.6",name:"Kimi K2.6",api:"openai-completions",provider:"opencode-go",baseUrl:"https://opencode.ai/zen/go/v1",reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.16,cacheWrite:0},contextWindow:262144,maxTokens:65536},"mimo-v2.5":{id:"mimo-v2.5",name:"MiMo V2.5",api:"openai-completions",provider:"opencode-go",baseUrl:"https://opencode.ai/zen/go/v1",reasoning:!0,input:["text","image"],cost:{input:.4,output:2,cacheRead:.08,cacheWrite:0},contextWindow:1e6,maxTokens:128e3},"mimo-v2.5-pro":{id:"mimo-v2.5-pro",name:"MiMo V2.5 Pro",api:"openai-completions",provider:"opencode-go",baseUrl:"https://opencode.ai/zen/go/v1",reasoning:!0,input:["text"],cost:{input:1,output:3,cacheRead:.2,cacheWrite:0},contextWindow:1048576,maxTokens:128e3},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",api:"openai-completions",provider:"opencode-go",baseUrl:"https://opencode.ai/zen/go/v1",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.03,cacheWrite:0},contextWindow:204800,maxTokens:65536},"minimax-m2.7":{id:"minimax-m2.7",name:"MiniMax M2.7",api:"openai-completions",provider:"opencode-go",baseUrl:"https://opencode.ai/zen/go/v1",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.06,cacheWrite:0},contextWindow:204800,maxTokens:131072},"qwen3.5-plus":{id:"qwen3.5-plus",name:"Qwen3.5 Plus",api:"openai-completions",provider:"opencode-go",baseUrl:"https://opencode.ai/zen/go/v1",compat:{thinkingFormat:"qwen"},reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:.25},contextWindow:262144,maxTokens:65536},"qwen3.6-plus":{id:"qwen3.6-plus",name:"Qwen3.6 Plus",api:"openai-completions",provider:"opencode-go",baseUrl:"https://opencode.ai/zen/go/v1",compat:{thinkingFormat:"qwen"},reasoning:!0,input:["text","image"],cost:{input:.5,output:3,cacheRead:.05,cacheWrite:.625},contextWindow:262144,maxTokens:65536}},openrouter:{"ai21/jamba-large-1.7":{id:"ai21/jamba-large-1.7",name:"AI21: Jamba Large 1.7",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:2,output:8,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:4096},"alibaba/tongyi-deepresearch-30b-a3b":{id:"alibaba/tongyi-deepresearch-30b-a3b",name:"Tongyi DeepResearch 30B A3B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.09,output:.44999999999999996,cacheRead:.09,cacheWrite:0},contextWindow:131072,maxTokens:131072},"amazon/nova-2-lite-v1":{id:"amazon/nova-2-lite-v1",name:"Amazon: Nova 2 Lite",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.3,output:2.5,cacheRead:0,cacheWrite:0},contextWindow:1e6,maxTokens:65535},"amazon/nova-lite-v1":{id:"amazon/nova-lite-v1",name:"Amazon: Nova Lite 1.0",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.06,output:.24,cacheRead:0,cacheWrite:0},contextWindow:3e5,maxTokens:5120},"amazon/nova-micro-v1":{id:"amazon/nova-micro-v1",name:"Amazon: Nova Micro 1.0",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.035,output:.14,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:5120},"amazon/nova-premier-v1":{id:"amazon/nova-premier-v1",name:"Amazon: Nova Premier 1.0",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:2.5,output:12.5,cacheRead:.625,cacheWrite:0},contextWindow:1e6,maxTokens:32e3},"amazon/nova-pro-v1":{id:"amazon/nova-pro-v1",name:"Amazon: Nova Pro 1.0",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.7999999999999999,output:3.1999999999999997,cacheRead:0,cacheWrite:0},contextWindow:3e5,maxTokens:5120},"anthropic/claude-3-haiku":{id:"anthropic/claude-3-haiku",name:"Anthropic: Claude 3 Haiku",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.25,output:1.25,cacheRead:.03,cacheWrite:.3},contextWindow:2e5,maxTokens:4096},"anthropic/claude-3.5-haiku":{id:"anthropic/claude-3.5-haiku",name:"Anthropic: Claude 3.5 Haiku",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.7999999999999999,output:4,cacheRead:.08,cacheWrite:1},contextWindow:2e5,maxTokens:8192},"anthropic/claude-3.7-sonnet":{id:"anthropic/claude-3.7-sonnet",name:"Anthropic: Claude 3.7 Sonnet",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"anthropic/claude-3.7-sonnet:thinking":{id:"anthropic/claude-3.7-sonnet:thinking",name:"Anthropic: Claude 3.7 Sonnet (thinking)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},"anthropic/claude-haiku-4.5":{id:"anthropic/claude-haiku-4.5",name:"Anthropic: Claude Haiku 4.5",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.09999999999999999,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3},"anthropic/claude-opus-4":{id:"anthropic/claude-opus-4",name:"Anthropic: Claude Opus 4",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"anthropic/claude-opus-4.1":{id:"anthropic/claude-opus-4.1",name:"Anthropic: Claude Opus 4.1",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"anthropic/claude-opus-4.5":{id:"anthropic/claude-opus-4.5",name:"Anthropic: Claude Opus 4.5",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:2e5,maxTokens:64e3},"anthropic/claude-opus-4.6":{id:"anthropic/claude-opus-4.6",name:"Anthropic: Claude Opus 4.6",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,thinkingLevelMap:{xhigh:"max"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"anthropic/claude-opus-4.6-fast":{id:"anthropic/claude-opus-4.6-fast",name:"Anthropic: Claude Opus 4.6 (Fast)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,thinkingLevelMap:{xhigh:"max"},input:["text","image"],cost:{input:30,output:150,cacheRead:3,cacheWrite:37.5},contextWindow:1e6,maxTokens:128e3},"anthropic/claude-opus-4.7":{id:"anthropic/claude-opus-4.7",name:"Anthropic: Claude Opus 4.7",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"anthropic/claude-sonnet-4":{id:"anthropic/claude-sonnet-4",name:"Anthropic: Claude Sonnet 4",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3},"anthropic/claude-sonnet-4.5":{id:"anthropic/claude-sonnet-4.5",name:"Anthropic: Claude Sonnet 4.5",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3},"anthropic/claude-sonnet-4.6":{id:"anthropic/claude-sonnet-4.6",name:"Anthropic: Claude Sonnet 4.6",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:128e3},"arcee-ai/trinity-large-preview":{id:"arcee-ai/trinity-large-preview",name:"Arcee AI: Trinity Large Preview",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.15,output:.44999999999999996,cacheRead:0,cacheWrite:0},contextWindow:131e3,maxTokens:4096},"arcee-ai/trinity-large-thinking":{id:"arcee-ai/trinity-large-thinking",name:"Arcee AI: Trinity Large Thinking",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.22,output:.85,cacheRead:.06,cacheWrite:0},contextWindow:262144,maxTokens:262144},"arcee-ai/trinity-mini":{id:"arcee-ai/trinity-mini",name:"Arcee AI: Trinity Mini",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.045,output:.15,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"arcee-ai/virtuoso-large":{id:"arcee-ai/virtuoso-large",name:"Arcee AI: Virtuoso Large",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.75,output:1.2,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:64e3},auto:{id:"auto",name:"Auto",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:2e6,maxTokens:3e4},"baidu/cobuddy:free":{id:"baidu/cobuddy:free",name:"Baidu Qianfan: CoBuddy (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:65536},"baidu/ernie-4.5-21b-a3b":{id:"baidu/ernie-4.5-21b-a3b",name:"Baidu: ERNIE 4.5 21B A3B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.07,output:.28,cacheRead:0,cacheWrite:0},contextWindow:12e4,maxTokens:8e3},"baidu/ernie-4.5-vl-28b-a3b":{id:"baidu/ernie-4.5-vl-28b-a3b",name:"Baidu: ERNIE 4.5 VL 28B A3B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.14,output:.56,cacheRead:0,cacheWrite:0},contextWindow:3e4,maxTokens:8e3},"bytedance-seed/seed-1.6":{id:"bytedance-seed/seed-1.6",name:"ByteDance Seed: Seed 1.6",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:32768},"bytedance-seed/seed-1.6-flash":{id:"bytedance-seed/seed-1.6-flash",name:"ByteDance Seed: Seed 1.6 Flash",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.075,output:.3,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:32768},"bytedance-seed/seed-2.0-lite":{id:"bytedance-seed/seed-2.0-lite",name:"ByteDance Seed: Seed-2.0-Lite",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:131072},"bytedance-seed/seed-2.0-mini":{id:"bytedance-seed/seed-2.0-mini",name:"ByteDance Seed: Seed-2.0-Mini",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.09999999999999999,output:.39999999999999997,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:131072},"cohere/command-r-08-2024":{id:"cohere/command-r-08-2024",name:"Cohere: Command R (08-2024)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.15,output:.6,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4e3},"cohere/command-r-plus-08-2024":{id:"cohere/command-r-plus-08-2024",name:"Cohere: Command R+ (08-2024)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:2.5,output:10,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4e3},"deepseek/deepseek-chat":{id:"deepseek/deepseek-chat",name:"DeepSeek: DeepSeek V3",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.32,output:.8899999999999999,cacheRead:0,cacheWrite:0},contextWindow:163840,maxTokens:16384},"deepseek/deepseek-chat-v3-0324":{id:"deepseek/deepseek-chat-v3-0324",name:"DeepSeek: DeepSeek V3 0324",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.19999999999999998,output:.77,cacheRead:.135,cacheWrite:0},contextWindow:163840,maxTokens:16384},"deepseek/deepseek-chat-v3.1":{id:"deepseek/deepseek-chat-v3.1",name:"DeepSeek: DeepSeek V3.1",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.15,output:.75,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:7168},"deepseek/deepseek-r1":{id:"deepseek/deepseek-r1",name:"DeepSeek: R1",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.7,output:2.5,cacheRead:0,cacheWrite:0},contextWindow:64e3,maxTokens:16e3},"deepseek/deepseek-r1-0528":{id:"deepseek/deepseek-r1-0528",name:"DeepSeek: R1 0528",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.5,output:2.1500000000000004,cacheRead:.35,cacheWrite:0},contextWindow:163840,maxTokens:32768},"deepseek/deepseek-v3.1-terminus":{id:"deepseek/deepseek-v3.1-terminus",name:"DeepSeek: DeepSeek V3.1 Terminus",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.27,output:.95,cacheRead:.13,cacheWrite:0},contextWindow:163840,maxTokens:32768},"deepseek/deepseek-v3.2":{id:"deepseek/deepseek-v3.2",name:"DeepSeek: DeepSeek V3.2",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.252,output:.378,cacheRead:.0252,cacheWrite:0},contextWindow:131072,maxTokens:65536},"deepseek/deepseek-v3.2-exp":{id:"deepseek/deepseek-v3.2-exp",name:"DeepSeek: DeepSeek V3.2 Exp",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.27,output:.41,cacheRead:0,cacheWrite:0},contextWindow:163840,maxTokens:65536},"deepseek/deepseek-v4-flash":{id:"deepseek/deepseek-v4-flash",name:"DeepSeek: DeepSeek V4 Flash",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",compat:{requiresReasoningContentOnAssistantMessages:!0,thinkingFormat:"deepseek"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null,high:"high",xhigh:"max"},input:["text"],cost:{input:.14,output:.28,cacheRead:.0028,cacheWrite:0},contextWindow:1048576,maxTokens:384e3},"deepseek/deepseek-v4-pro":{id:"deepseek/deepseek-v4-pro",name:"DeepSeek: DeepSeek V4 Pro",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",compat:{requiresReasoningContentOnAssistantMessages:!0,thinkingFormat:"deepseek"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null,high:"high",xhigh:"max"},input:["text"],cost:{input:.435,output:.87,cacheRead:.003625,cacheWrite:0},contextWindow:1048576,maxTokens:384e3},"essentialai/rnj-1-instruct":{id:"essentialai/rnj-1-instruct",name:"EssentialAI: Rnj 1 Instruct",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.15,output:.15,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:4096},"google/gemini-2.0-flash-001":{id:"google/gemini-2.0-flash-001",name:"Google: Gemini 2.0 Flash",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.09999999999999999,output:.39999999999999997,cacheRead:.024999999999999998,cacheWrite:.08333333333333334},contextWindow:1e6,maxTokens:8192},"google/gemini-2.0-flash-lite-001":{id:"google/gemini-2.0-flash-lite-001",name:"Google: Gemini 2.0 Flash Lite",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.075,output:.3,cacheRead:0,cacheWrite:0},contextWindow:1048576,maxTokens:8192},"google/gemini-2.5-flash":{id:"google/gemini-2.5-flash",name:"Google: Gemini 2.5 Flash",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.3,output:2.5,cacheRead:.03,cacheWrite:.08333333333333334},contextWindow:1048576,maxTokens:65535},"google/gemini-2.5-flash-lite":{id:"google/gemini-2.5-flash-lite",name:"Google: Gemini 2.5 Flash Lite",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.09999999999999999,output:.39999999999999997,cacheRead:.01,cacheWrite:.08333333333333334},contextWindow:1048576,maxTokens:65535},"google/gemini-2.5-flash-lite-preview-09-2025":{id:"google/gemini-2.5-flash-lite-preview-09-2025",name:"Google: Gemini 2.5 Flash Lite Preview 09-2025",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.09999999999999999,output:.39999999999999997,cacheRead:.01,cacheWrite:.08333333333333334},contextWindow:1048576,maxTokens:65535},"google/gemini-2.5-pro":{id:"google/gemini-2.5-pro",name:"Google: Gemini 2.5 Pro",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:.375},contextWindow:1048576,maxTokens:65536},"google/gemini-2.5-pro-preview":{id:"google/gemini-2.5-pro-preview",name:"Google: Gemini 2.5 Pro Preview 06-05",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:.375},contextWindow:1048576,maxTokens:65536},"google/gemini-2.5-pro-preview-05-06":{id:"google/gemini-2.5-pro-preview-05-06",name:"Google: Gemini 2.5 Pro Preview 05-06",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:.375},contextWindow:1048576,maxTokens:65535},"google/gemini-3-flash-preview":{id:"google/gemini-3-flash-preview",name:"Google: Gemini 3 Flash Preview",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.5,output:3,cacheRead:.049999999999999996,cacheWrite:.08333333333333334},contextWindow:1048576,maxTokens:65536},"google/gemini-3.1-flash-lite":{id:"google/gemini-3.1-flash-lite",name:"Google: Gemini 3.1 Flash Lite",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.25,output:1.5,cacheRead:.024999999999999998,cacheWrite:.08333333333333334},contextWindow:1048576,maxTokens:65536},"google/gemini-3.1-flash-lite-preview":{id:"google/gemini-3.1-flash-lite-preview",name:"Google: Gemini 3.1 Flash Lite Preview",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.25,output:1.5,cacheRead:.024999999999999998,cacheWrite:.08333333333333334},contextWindow:1048576,maxTokens:65536},"google/gemini-3.1-pro-preview":{id:"google/gemini-3.1-pro-preview",name:"Google: Gemini 3.1 Pro Preview",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.19999999999999998,cacheWrite:.375},contextWindow:1048576,maxTokens:65536},"google/gemini-3.1-pro-preview-customtools":{id:"google/gemini-3.1-pro-preview-customtools",name:"Google: Gemini 3.1 Pro Preview Custom Tools",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.19999999999999998,cacheWrite:.375},contextWindow:1048576,maxTokens:65536},"google/gemma-3-12b-it":{id:"google/gemma-3-12b-it",name:"Google: Gemma 3 12B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.04,output:.13,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:16384},"google/gemma-3-27b-it":{id:"google/gemma-3-27b-it",name:"Google: Gemma 3 27B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.08,output:.16,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:16384},"google/gemma-4-26b-a4b-it":{id:"google/gemma-4-26b-a4b-it",name:"Google: Gemma 4 26B A4B ",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.06,output:.33,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:4096},"google/gemma-4-26b-a4b-it:free":{id:"google/gemma-4-26b-a4b-it:free",name:"Google: Gemma 4 26B A4B (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:32768},"google/gemma-4-31b-it":{id:"google/gemma-4-31b-it",name:"Google: Gemma 4 31B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.13,output:.38,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:16384},"google/gemma-4-31b-it:free":{id:"google/gemma-4-31b-it:free",name:"Google: Gemma 4 31B (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:32768},"ibm-granite/granite-4.1-8b":{id:"ibm-granite/granite-4.1-8b",name:"IBM: Granite 4.1 8B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.049999999999999996,output:.09999999999999999,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:131072,maxTokens:131072},"inception/mercury-2":{id:"inception/mercury-2",name:"Inception: Mercury 2",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.25,output:.75,cacheRead:.024999999999999998,cacheWrite:0},contextWindow:128e3,maxTokens:5e4},"inclusionai/ling-2.6-1t":{id:"inclusionai/ling-2.6-1t",name:"inclusionAI: Ling-2.6-1T",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.3,output:2.5,cacheRead:.06,cacheWrite:0},contextWindow:262144,maxTokens:32768},"inclusionai/ling-2.6-flash":{id:"inclusionai/ling-2.6-flash",name:"inclusionAI: Ling-2.6-flash",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.08,output:.24,cacheRead:.016,cacheWrite:0},contextWindow:262144,maxTokens:32768},"inclusionai/ring-2.6-1t:free":{id:"inclusionai/ring-2.6-1t:free",name:"inclusionAI: Ring-2.6-1T (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:65536},"kwaipilot/kat-coder-pro-v2":{id:"kwaipilot/kat-coder-pro-v2",name:"Kwaipilot: KAT-Coder-Pro V2",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.3,output:1.2,cacheRead:.06,cacheWrite:0},contextWindow:256e3,maxTokens:8e4},"meta-llama/llama-3.1-70b-instruct":{id:"meta-llama/llama-3.1-70b-instruct",name:"Meta: Llama 3.1 70B Instruct",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.39999999999999997,output:.39999999999999997,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:16384},"meta-llama/llama-3.1-8b-instruct":{id:"meta-llama/llama-3.1-8b-instruct",name:"Meta: Llama 3.1 8B Instruct",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.02,output:.049999999999999996,cacheRead:0,cacheWrite:0},contextWindow:16384,maxTokens:16384},"meta-llama/llama-3.3-70b-instruct":{id:"meta-llama/llama-3.3-70b-instruct",name:"Meta: Llama 3.3 70B Instruct",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.09999999999999999,output:.32,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:16384},"meta-llama/llama-3.3-70b-instruct:free":{id:"meta-llama/llama-3.3-70b-instruct:free",name:"Meta: Llama 3.3 70B Instruct (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:65536,maxTokens:4096},"meta-llama/llama-4-scout":{id:"meta-llama/llama-4-scout",name:"Meta: Llama 4 Scout",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.08,output:.3,cacheRead:0,cacheWrite:0},contextWindow:327680,maxTokens:16384},"minimax/minimax-m1":{id:"minimax/minimax-m1",name:"MiniMax: MiniMax M1",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.39999999999999997,output:2.2,cacheRead:0,cacheWrite:0},contextWindow:1e6,maxTokens:4e4},"minimax/minimax-m2":{id:"minimax/minimax-m2",name:"MiniMax: MiniMax M2",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.255,output:1,cacheRead:.03,cacheWrite:0},contextWindow:196608,maxTokens:196608},"minimax/minimax-m2.1":{id:"minimax/minimax-m2.1",name:"MiniMax: MiniMax M2.1",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.29,output:.95,cacheRead:.03,cacheWrite:0},contextWindow:196608,maxTokens:196608},"minimax/minimax-m2.5":{id:"minimax/minimax-m2.5",name:"MiniMax: MiniMax M2.5",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.15,output:1.15,cacheRead:0,cacheWrite:0},contextWindow:196608,maxTokens:196608},"minimax/minimax-m2.5:free":{id:"minimax/minimax-m2.5:free",name:"MiniMax: MiniMax M2.5 (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:196608,maxTokens:8192},"minimax/minimax-m2.7":{id:"minimax/minimax-m2.7",name:"MiniMax: MiniMax M2.7",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.29900000000000004,output:1.2,cacheRead:0,cacheWrite:0},contextWindow:196608,maxTokens:131072},"mistralai/codestral-2508":{id:"mistralai/codestral-2508",name:"Mistral: Codestral 2508",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.3,output:.8999999999999999,cacheRead:.03,cacheWrite:0},contextWindow:256e3,maxTokens:4096},"mistralai/devstral-2512":{id:"mistralai/devstral-2512",name:"Mistral: Devstral 2 2512",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.39999999999999997,output:2,cacheRead:.04,cacheWrite:0},contextWindow:262144,maxTokens:4096},"mistralai/devstral-medium":{id:"mistralai/devstral-medium",name:"Mistral: Devstral Medium",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.39999999999999997,output:2,cacheRead:.04,cacheWrite:0},contextWindow:131072,maxTokens:4096},"mistralai/devstral-small":{id:"mistralai/devstral-small",name:"Mistral: Devstral Small 1.1",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.09999999999999999,output:.3,cacheRead:.01,cacheWrite:0},contextWindow:131072,maxTokens:4096},"mistralai/ministral-14b-2512":{id:"mistralai/ministral-14b-2512",name:"Mistral: Ministral 3 14B 2512",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.19999999999999998,output:.19999999999999998,cacheRead:.02,cacheWrite:0},contextWindow:262144,maxTokens:4096},"mistralai/ministral-3b-2512":{id:"mistralai/ministral-3b-2512",name:"Mistral: Ministral 3 3B 2512",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.09999999999999999,output:.09999999999999999,cacheRead:.01,cacheWrite:0},contextWindow:131072,maxTokens:4096},"mistralai/ministral-8b-2512":{id:"mistralai/ministral-8b-2512",name:"Mistral: Ministral 3 8B 2512",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.15,output:.15,cacheRead:.015,cacheWrite:0},contextWindow:262144,maxTokens:4096},"mistralai/mistral-large":{id:"mistralai/mistral-large",name:"Mistral Large",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:2,output:6,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"mistralai/mistral-large-2407":{id:"mistralai/mistral-large-2407",name:"Mistral Large 2407",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:2,output:6,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:131072,maxTokens:4096},"mistralai/mistral-large-2411":{id:"mistralai/mistral-large-2411",name:"Mistral Large 2411",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:2,output:6,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:131072,maxTokens:4096},"mistralai/mistral-large-2512":{id:"mistralai/mistral-large-2512",name:"Mistral: Mistral Large 3 2512",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.5,output:1.5,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:262144,maxTokens:4096},"mistralai/mistral-medium-3":{id:"mistralai/mistral-medium-3",name:"Mistral: Mistral Medium 3",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.39999999999999997,output:2,cacheRead:.04,cacheWrite:0},contextWindow:131072,maxTokens:4096},"mistralai/mistral-medium-3-5":{id:"mistralai/mistral-medium-3-5",name:"Mistral: Mistral Medium 3.5",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1.5,output:7.5,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:4096},"mistralai/mistral-medium-3.1":{id:"mistralai/mistral-medium-3.1",name:"Mistral: Mistral Medium 3.1",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.39999999999999997,output:2,cacheRead:.04,cacheWrite:0},contextWindow:131072,maxTokens:4096},"mistralai/mistral-nemo":{id:"mistralai/mistral-nemo",name:"Mistral: Mistral Nemo",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.02,output:.03,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:4096},"mistralai/mistral-saba":{id:"mistralai/mistral-saba",name:"Mistral: Saba",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.19999999999999998,output:.6,cacheRead:.02,cacheWrite:0},contextWindow:32768,maxTokens:4096},"mistralai/mistral-small-2603":{id:"mistralai/mistral-small-2603",name:"Mistral: Mistral Small 4",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.15,output:.6,cacheRead:.015,cacheWrite:0},contextWindow:262144,maxTokens:4096},"mistralai/mistral-small-3.2-24b-instruct":{id:"mistralai/mistral-small-3.2-24b-instruct",name:"Mistral: Mistral Small 3.2 24B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.075,output:.19999999999999998,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"mistralai/mixtral-8x22b-instruct":{id:"mistralai/mixtral-8x22b-instruct",name:"Mistral: Mixtral 8x22B Instruct",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:2,output:6,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:65536,maxTokens:4096},"mistralai/pixtral-large-2411":{id:"mistralai/pixtral-large-2411",name:"Mistral: Pixtral Large 2411",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:2,output:6,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:131072,maxTokens:4096},"mistralai/voxtral-small-24b-2507":{id:"mistralai/voxtral-small-24b-2507",name:"Mistral: Voxtral Small 24B 2507",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.09999999999999999,output:.3,cacheRead:.01,cacheWrite:0},contextWindow:32e3,maxTokens:4096},"moonshotai/kimi-k2":{id:"moonshotai/kimi-k2",name:"MoonshotAI: Kimi K2 0711",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.5700000000000001,output:2.3,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"moonshotai/kimi-k2-0905":{id:"moonshotai/kimi-k2-0905",name:"MoonshotAI: Kimi K2 0905",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.39999999999999997,output:2,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"moonshotai/kimi-k2-thinking":{id:"moonshotai/kimi-k2-thinking",name:"MoonshotAI: Kimi K2 Thinking",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.6,output:2.5,cacheRead:.15,cacheWrite:0},contextWindow:262144,maxTokens:262144},"moonshotai/kimi-k2.5":{id:"moonshotai/kimi-k2.5",name:"MoonshotAI: Kimi K2.5",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.41,output:2.06,cacheRead:.07,cacheWrite:0},contextWindow:262144,maxTokens:4096},"moonshotai/kimi-k2.6":{id:"moonshotai/kimi-k2.6",name:"MoonshotAI: Kimi K2.6",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.5,cacheRead:.15,cacheWrite:0},contextWindow:262144,maxTokens:16384},"nex-agi/deepseek-v3.1-nex-n1":{id:"nex-agi/deepseek-v3.1-nex-n1",name:"Nex AGI: DeepSeek V3.1 Nex N1",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.135,output:.5,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:163840},"nvidia/llama-3.3-nemotron-super-49b-v1.5":{id:"nvidia/llama-3.3-nemotron-super-49b-v1.5",name:"NVIDIA: Llama 3.3 Nemotron Super 49B V1.5",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.09999999999999999,output:.39999999999999997,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:16384},"nvidia/nemotron-3-nano-30b-a3b":{id:"nvidia/nemotron-3-nano-30b-a3b",name:"NVIDIA: Nemotron 3 Nano 30B A3B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.049999999999999996,output:.19999999999999998,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:228e3},"nvidia/nemotron-3-nano-30b-a3b:free":{id:"nvidia/nemotron-3-nano-30b-a3b:free",name:"NVIDIA: Nemotron 3 Nano 30B A3B (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:4096},"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free":{id:"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free",name:"NVIDIA: Nemotron 3 Nano Omni (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:65536},"nvidia/nemotron-3-super-120b-a12b":{id:"nvidia/nemotron-3-super-120b-a12b",name:"NVIDIA: Nemotron 3 Super",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.09,output:.44999999999999996,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:4096},"nvidia/nemotron-3-super-120b-a12b:free":{id:"nvidia/nemotron-3-super-120b-a12b:free",name:"NVIDIA: Nemotron 3 Super (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"nvidia/nemotron-nano-12b-v2-vl:free":{id:"nvidia/nemotron-nano-12b-v2-vl:free",name:"NVIDIA: Nemotron Nano 12B 2 VL (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:128e3},"nvidia/nemotron-nano-9b-v2":{id:"nvidia/nemotron-nano-9b-v2",name:"NVIDIA: Nemotron Nano 9B V2",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.04,output:.16,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:16384},"nvidia/nemotron-nano-9b-v2:free":{id:"nvidia/nemotron-nano-9b-v2:free",name:"NVIDIA: Nemotron Nano 9B V2 (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"openai/gpt-3.5-turbo":{id:"openai/gpt-3.5-turbo",name:"OpenAI: GPT-3.5 Turbo",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.5,output:1.5,cacheRead:0,cacheWrite:0},contextWindow:16385,maxTokens:4096},"openai/gpt-3.5-turbo-0613":{id:"openai/gpt-3.5-turbo-0613",name:"OpenAI: GPT-3.5 Turbo (older v0613)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:1,output:2,cacheRead:0,cacheWrite:0},contextWindow:4095,maxTokens:4096},"openai/gpt-3.5-turbo-16k":{id:"openai/gpt-3.5-turbo-16k",name:"OpenAI: GPT-3.5 Turbo 16k",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:3,output:4,cacheRead:0,cacheWrite:0},contextWindow:16385,maxTokens:4096},"openai/gpt-4":{id:"openai/gpt-4",name:"OpenAI: GPT-4",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:30,output:60,cacheRead:0,cacheWrite:0},contextWindow:8191,maxTokens:4096},"openai/gpt-4-0314":{id:"openai/gpt-4-0314",name:"OpenAI: GPT-4 (older v0314)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:30,output:60,cacheRead:0,cacheWrite:0},contextWindow:8191,maxTokens:4096},"openai/gpt-4-1106-preview":{id:"openai/gpt-4-1106-preview",name:"OpenAI: GPT-4 Turbo (older v1106)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:10,output:30,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"openai/gpt-4-turbo":{id:"openai/gpt-4-turbo",name:"OpenAI: GPT-4 Turbo",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:10,output:30,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"openai/gpt-4-turbo-preview":{id:"openai/gpt-4-turbo-preview",name:"OpenAI: GPT-4 Turbo Preview",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:10,output:30,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"openai/gpt-4.1":{id:"openai/gpt-4.1",name:"OpenAI: GPT-4.1",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:1047576,maxTokens:4096},"openai/gpt-4.1-mini":{id:"openai/gpt-4.1-mini",name:"OpenAI: GPT-4.1 Mini",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.39999999999999997,output:1.5999999999999999,cacheRead:.09999999999999999,cacheWrite:0},contextWindow:1047576,maxTokens:32768},"openai/gpt-4.1-nano":{id:"openai/gpt-4.1-nano",name:"OpenAI: GPT-4.1 Nano",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.09999999999999999,output:.39999999999999997,cacheRead:.024999999999999998,cacheWrite:0},contextWindow:1047576,maxTokens:32768},"openai/gpt-4o":{id:"openai/gpt-4o",name:"OpenAI: GPT-4o",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:2.5,output:10,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-4o-2024-05-13":{id:"openai/gpt-4o-2024-05-13",name:"OpenAI: GPT-4o (2024-05-13)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:5,output:15,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"openai/gpt-4o-2024-08-06":{id:"openai/gpt-4o-2024-08-06",name:"OpenAI: GPT-4o (2024-08-06)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:2.5,output:10,cacheRead:1.25,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-4o-2024-11-20":{id:"openai/gpt-4o-2024-11-20",name:"OpenAI: GPT-4o (2024-11-20)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:2.5,output:10,cacheRead:1.25,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-4o-audio-preview":{id:"openai/gpt-4o-audio-preview",name:"OpenAI: GPT-4o Audio",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:2.5,output:10,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-4o-mini":{id:"openai/gpt-4o-mini",name:"OpenAI: GPT-4o-mini",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.15,output:.6,cacheRead:.075,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-4o-mini-2024-07-18":{id:"openai/gpt-4o-mini-2024-07-18",name:"OpenAI: GPT-4o-mini (2024-07-18)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.15,output:.6,cacheRead:.075,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-5":{id:"openai/gpt-5",name:"OpenAI: GPT-5",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5-codex":{id:"openai/gpt-5-codex",name:"OpenAI: GPT-5 Codex",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5-mini":{id:"openai/gpt-5-mini",name:"OpenAI: GPT-5 Mini",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.024999999999999998,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5-nano":{id:"openai/gpt-5-nano",name:"OpenAI: GPT-5 Nano",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.049999999999999996,output:.39999999999999997,cacheRead:.01,cacheWrite:0},contextWindow:4e5,maxTokens:4096},"openai/gpt-5-pro":{id:"openai/gpt-5-pro",name:"OpenAI: GPT-5 Pro",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:15,output:120,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.1":{id:"openai/gpt-5.1",name:"OpenAI: GPT-5.1",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.13,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.1-chat":{id:"openai/gpt-5.1-chat",name:"OpenAI: GPT-5.1 Chat",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-5.1-codex":{id:"openai/gpt-5.1-codex",name:"OpenAI: GPT-5.1-Codex",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.1-codex-max":{id:"openai/gpt-5.1-codex-max",name:"OpenAI: GPT-5.1-Codex-Max",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.1-codex-mini":{id:"openai/gpt-5.1-codex-mini",name:"OpenAI: GPT-5.1-Codex-Mini",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.03,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.2":{id:"openai/gpt-5.2",name:"OpenAI: GPT-5.2",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.2-chat":{id:"openai/gpt-5.2-chat",name:"OpenAI: GPT-5.2 Chat",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:128e3,maxTokens:32e3},"openai/gpt-5.2-codex":{id:"openai/gpt-5.2-codex",name:"OpenAI: GPT-5.2-Codex",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.2-pro":{id:"openai/gpt-5.2-pro",name:"OpenAI: GPT-5.2 Pro",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:21,output:168,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.3-chat":{id:"openai/gpt-5.3-chat",name:"OpenAI: GPT-5.3 Chat",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-5.3-codex":{id:"openai/gpt-5.3-codex",name:"OpenAI: GPT-5.3-Codex",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.4":{id:"openai/gpt-5.4",name:"OpenAI: GPT-5.4",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},"openai/gpt-5.4-mini":{id:"openai/gpt-5.4-mini",name:"OpenAI: GPT-5.4 Mini",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.4-nano":{id:"openai/gpt-5.4-nano",name:"OpenAI: GPT-5.4 Nano",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:.19999999999999998,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.4-pro":{id:"openai/gpt-5.4-pro",name:"OpenAI: GPT-5.4 Pro",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:30,output:180,cacheRead:0,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},"openai/gpt-5.5":{id:"openai/gpt-5.5",name:"OpenAI: GPT-5.5",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},"openai/gpt-5.5-pro":{id:"openai/gpt-5.5-pro",name:"OpenAI: GPT-5.5 Pro",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:30,output:180,cacheRead:0,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},"openai/gpt-audio":{id:"openai/gpt-audio",name:"OpenAI: GPT Audio",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:2.5,output:10,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-audio-mini":{id:"openai/gpt-audio-mini",name:"OpenAI: GPT Audio Mini",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.6,output:2.4,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-chat-latest":{id:"openai/gpt-chat-latest",name:"OpenAI: GPT Chat Latest",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-oss-120b":{id:"openai/gpt-oss-120b",name:"OpenAI: gpt-oss-120b",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.039,output:.18,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:4096},"openai/gpt-oss-120b:free":{id:"openai/gpt-oss-120b:free",name:"OpenAI: gpt-oss-120b (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"openai/gpt-oss-20b":{id:"openai/gpt-oss-20b",name:"OpenAI: gpt-oss-20b",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.03,output:.14,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"openai/gpt-oss-20b:free":{id:"openai/gpt-oss-20b:free",name:"OpenAI: gpt-oss-20b (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:8192},"openai/gpt-oss-safeguard-20b":{id:"openai/gpt-oss-safeguard-20b",name:"OpenAI: gpt-oss-safeguard-20b",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.075,output:.3,cacheRead:.037,cacheWrite:0},contextWindow:131072,maxTokens:65536},"openai/o1":{id:"openai/o1",name:"OpenAI: o1",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:15,output:60,cacheRead:7.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"openai/o3":{id:"openai/o3",name:"OpenAI: o3",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"openai/o3-deep-research":{id:"openai/o3-deep-research",name:"OpenAI: o3 Deep Research",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:10,output:40,cacheRead:2.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"openai/o3-mini":{id:"openai/o3-mini",name:"OpenAI: o3 Mini",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.55,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"openai/o3-mini-high":{id:"openai/o3-mini-high",name:"OpenAI: o3 Mini High",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.55,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"openai/o3-pro":{id:"openai/o3-pro",name:"OpenAI: o3 Pro",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:20,output:80,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"openai/o4-mini":{id:"openai/o4-mini",name:"OpenAI: o4 Mini",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1.1,output:4.4,cacheRead:.275,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"openai/o4-mini-deep-research":{id:"openai/o4-mini-deep-research",name:"OpenAI: o4 Mini Deep Research",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"openai/o4-mini-high":{id:"openai/o4-mini-high",name:"OpenAI: o4 Mini High",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1.1,output:4.4,cacheRead:.275,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"openrouter/auto":{id:"openrouter/auto",name:"Auto Router",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:-1e6,output:-1e6,cacheRead:0,cacheWrite:0},contextWindow:2e6,maxTokens:4096},"openrouter/free":{id:"openrouter/free",name:"Free Models Router",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:4096},"openrouter/owl-alpha":{id:"openrouter/owl-alpha",name:"Owl Alpha",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:1048756,maxTokens:262144},"poolside/laguna-m.1:free":{id:"poolside/laguna-m.1:free",name:"Poolside: Laguna M.1 (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:8192},"poolside/laguna-xs.2:free":{id:"poolside/laguna-xs.2:free",name:"Poolside: Laguna XS.2 (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:8192},"prime-intellect/intellect-3":{id:"prime-intellect/intellect-3",name:"Prime Intellect: INTELLECT-3",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.19999999999999998,output:1.1,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"qwen/qwen-2.5-72b-instruct":{id:"qwen/qwen-2.5-72b-instruct",name:"Qwen2.5 72B Instruct",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.36,output:.39999999999999997,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:16384},"qwen/qwen-2.5-7b-instruct":{id:"qwen/qwen-2.5-7b-instruct",name:"Qwen: Qwen2.5 7B Instruct",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.04,output:.09999999999999999,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:32768},"qwen/qwen-max":{id:"qwen/qwen-max",name:"Qwen: Qwen-Max ",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:1.04,output:4.16,cacheRead:.20800000000000002,cacheWrite:0},contextWindow:32768,maxTokens:8192},"qwen/qwen-plus":{id:"qwen/qwen-plus",name:"Qwen: Qwen-Plus",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.26,output:.78,cacheRead:.052000000000000005,cacheWrite:.325},contextWindow:1e6,maxTokens:32768},"qwen/qwen-plus-2025-07-28":{id:"qwen/qwen-plus-2025-07-28",name:"Qwen: Qwen Plus 0728",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.26,output:.78,cacheRead:0,cacheWrite:.325},contextWindow:1e6,maxTokens:32768},"qwen/qwen-plus-2025-07-28:thinking":{id:"qwen/qwen-plus-2025-07-28:thinking",name:"Qwen: Qwen Plus 0728 (thinking)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.26,output:.78,cacheRead:0,cacheWrite:.325},contextWindow:1e6,maxTokens:32768},"qwen/qwen-turbo":{id:"qwen/qwen-turbo",name:"Qwen: Qwen-Turbo",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.0325,output:.13,cacheRead:.006500000000000001,cacheWrite:0},contextWindow:131072,maxTokens:8192},"qwen/qwen-vl-max":{id:"qwen/qwen-vl-max",name:"Qwen: Qwen VL Max",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.52,output:2.08,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"qwen/qwen3-14b":{id:"qwen/qwen3-14b",name:"Qwen: Qwen3 14B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.06,output:.24,cacheRead:0,cacheWrite:0},contextWindow:40960,maxTokens:40960},"qwen/qwen3-235b-a22b":{id:"qwen/qwen3-235b-a22b",name:"Qwen: Qwen3 235B A22B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.45499999999999996,output:1.8199999999999998,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:8192},"qwen/qwen3-235b-a22b-2507":{id:"qwen/qwen3-235b-a22b-2507",name:"Qwen: Qwen3 235B A22B Instruct 2507",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.071,output:.09999999999999999,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:16384},"qwen/qwen3-235b-a22b-thinking-2507":{id:"qwen/qwen3-235b-a22b-thinking-2507",name:"Qwen: Qwen3 235B A22B Thinking 2507",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.14950000000000002,output:1.495,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:4096},"qwen/qwen3-30b-a3b":{id:"qwen/qwen3-30b-a3b",name:"Qwen: Qwen3 30B A3B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.09,output:.44999999999999996,cacheRead:0,cacheWrite:0},contextWindow:40960,maxTokens:2e4},"qwen/qwen3-30b-a3b-instruct-2507":{id:"qwen/qwen3-30b-a3b-instruct-2507",name:"Qwen: Qwen3 30B A3B Instruct 2507",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.09,output:.3,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"qwen/qwen3-30b-a3b-thinking-2507":{id:"qwen/qwen3-30b-a3b-thinking-2507",name:"Qwen: Qwen3 30B A3B Thinking 2507",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.08,output:.39999999999999997,cacheRead:.08,cacheWrite:0},contextWindow:131072,maxTokens:131072},"qwen/qwen3-32b":{id:"qwen/qwen3-32b",name:"Qwen: Qwen3 32B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.08,output:.28,cacheRead:0,cacheWrite:0},contextWindow:40960,maxTokens:16384},"qwen/qwen3-8b":{id:"qwen/qwen3-8b",name:"Qwen: Qwen3 8B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.049999999999999996,output:.39999999999999997,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:40960,maxTokens:8192},"qwen/qwen3-coder":{id:"qwen/qwen3-coder",name:"Qwen: Qwen3 Coder 480B A35B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.22,output:1.7999999999999998,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:65536},"qwen/qwen3-coder-30b-a3b-instruct":{id:"qwen/qwen3-coder-30b-a3b-instruct",name:"Qwen: Qwen3 Coder 30B A3B Instruct",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.07,output:.27,cacheRead:0,cacheWrite:0},contextWindow:16e4,maxTokens:32768},"qwen/qwen3-coder-flash":{id:"qwen/qwen3-coder-flash",name:"Qwen: Qwen3 Coder Flash",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.195,output:.975,cacheRead:.039,cacheWrite:.24375},contextWindow:1e6,maxTokens:65536},"qwen/qwen3-coder-next":{id:"qwen/qwen3-coder-next",name:"Qwen: Qwen3 Coder Next",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.11,output:.7999999999999999,cacheRead:.07,cacheWrite:0},contextWindow:262144,maxTokens:262144},"qwen/qwen3-coder-plus":{id:"qwen/qwen3-coder-plus",name:"Qwen: Qwen3 Coder Plus",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.65,output:3.25,cacheRead:.13,cacheWrite:.8125},contextWindow:1e6,maxTokens:65536},"qwen/qwen3-coder:free":{id:"qwen/qwen3-coder:free",name:"Qwen: Qwen3 Coder 480B A35B (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:262e3,maxTokens:262e3},"qwen/qwen3-max":{id:"qwen/qwen3-max",name:"Qwen: Qwen3 Max",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.78,output:3.9,cacheRead:.156,cacheWrite:.975},contextWindow:262144,maxTokens:32768},"qwen/qwen3-max-thinking":{id:"qwen/qwen3-max-thinking",name:"Qwen: Qwen3 Max Thinking",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.78,output:3.9,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:32768},"qwen/qwen3-next-80b-a3b-instruct":{id:"qwen/qwen3-next-80b-a3b-instruct",name:"Qwen: Qwen3 Next 80B A3B Instruct",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.09,output:1.1,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:16384},"qwen/qwen3-next-80b-a3b-instruct:free":{id:"qwen/qwen3-next-80b-a3b-instruct:free",name:"Qwen: Qwen3 Next 80B A3B Instruct (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:4096},"qwen/qwen3-next-80b-a3b-thinking":{id:"qwen/qwen3-next-80b-a3b-thinking",name:"Qwen: Qwen3 Next 80B A3B Thinking",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.0975,output:.78,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"qwen/qwen3-vl-235b-a22b-instruct":{id:"qwen/qwen3-vl-235b-a22b-instruct",name:"Qwen: Qwen3 VL 235B A22B Instruct",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.19999999999999998,output:.88,cacheRead:.11,cacheWrite:0},contextWindow:262144,maxTokens:16384},"qwen/qwen3-vl-235b-a22b-thinking":{id:"qwen/qwen3-vl-235b-a22b-thinking",name:"Qwen: Qwen3 VL 235B A22B Thinking",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.26,output:2.6,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"qwen/qwen3-vl-30b-a3b-instruct":{id:"qwen/qwen3-vl-30b-a3b-instruct",name:"Qwen: Qwen3 VL 30B A3B Instruct",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.13,output:.52,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"qwen/qwen3-vl-30b-a3b-thinking":{id:"qwen/qwen3-vl-30b-a3b-thinking",name:"Qwen: Qwen3 VL 30B A3B Thinking",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.13,output:1.56,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"qwen/qwen3-vl-32b-instruct":{id:"qwen/qwen3-vl-32b-instruct",name:"Qwen: Qwen3 VL 32B Instruct",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.10400000000000001,output:.41600000000000004,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"qwen/qwen3-vl-8b-instruct":{id:"qwen/qwen3-vl-8b-instruct",name:"Qwen: Qwen3 VL 8B Instruct",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.08,output:.5,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"qwen/qwen3-vl-8b-thinking":{id:"qwen/qwen3-vl-8b-thinking",name:"Qwen: Qwen3 VL 8B Thinking",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.117,output:1.365,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"qwen/qwen3.5-122b-a10b":{id:"qwen/qwen3.5-122b-a10b",name:"Qwen: Qwen3.5-122B-A10B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.26,output:2.08,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:65536},"qwen/qwen3.5-27b":{id:"qwen/qwen3.5-27b",name:"Qwen: Qwen3.5-27B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.195,output:1.56,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:65536},"qwen/qwen3.5-35b-a3b":{id:"qwen/qwen3.5-35b-a3b",name:"Qwen: Qwen3.5-35B-A3B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.14,output:1,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:262144,maxTokens:81920},"qwen/qwen3.5-397b-a17b":{id:"qwen/qwen3.5-397b-a17b",name:"Qwen: Qwen3.5 397B A17B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.39,output:2.34,cacheRead:.195,cacheWrite:0},contextWindow:262144,maxTokens:65536},"qwen/qwen3.5-9b":{id:"qwen/qwen3.5-9b",name:"Qwen: Qwen3.5-9B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.04,output:.15,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:81920},"qwen/qwen3.5-flash-02-23":{id:"qwen/qwen3.5-flash-02-23",name:"Qwen: Qwen3.5-Flash",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.065,output:.26,cacheRead:0,cacheWrite:.08125},contextWindow:1e6,maxTokens:65536},"qwen/qwen3.5-plus-02-15":{id:"qwen/qwen3.5-plus-02-15",name:"Qwen: Qwen3.5 Plus 2026-02-15",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.26,output:1.56,cacheRead:0,cacheWrite:.325},contextWindow:1e6,maxTokens:65536},"qwen/qwen3.5-plus-20260420":{id:"qwen/qwen3.5-plus-20260420",name:"Qwen: Qwen3.5 Plus 2026-04-20",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.39999999999999997,output:2.4,cacheRead:0,cacheWrite:0},contextWindow:1e6,maxTokens:65536},"qwen/qwen3.6-27b":{id:"qwen/qwen3.6-27b",name:"Qwen: Qwen3.6 27B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.32,output:3.1999999999999997,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:81920},"qwen/qwen3.6-35b-a3b":{id:"qwen/qwen3.6-35b-a3b",name:"Qwen: Qwen3.6 35B A3B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.15,output:1,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:262144,maxTokens:262144},"qwen/qwen3.6-flash":{id:"qwen/qwen3.6-flash",name:"Qwen: Qwen3.6 Flash",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.25,output:1.5,cacheRead:0,cacheWrite:.3125},contextWindow:1e6,maxTokens:65536},"qwen/qwen3.6-max-preview":{id:"qwen/qwen3.6-max-preview",name:"Qwen: Qwen3.6 Max Preview",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:1.04,output:6.24,cacheRead:0,cacheWrite:1.3},contextWindow:262144,maxTokens:65536},"qwen/qwen3.6-plus":{id:"qwen/qwen3.6-plus",name:"Qwen: Qwen3.6 Plus",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.325,output:1.95,cacheRead:0,cacheWrite:.40625},contextWindow:1e6,maxTokens:65536},"rekaai/reka-edge":{id:"rekaai/reka-edge",name:"Reka Edge",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text","image"],cost:{input:.09999999999999999,output:.09999999999999999,cacheRead:0,cacheWrite:0},contextWindow:16384,maxTokens:16384},"relace/relace-search":{id:"relace/relace-search",name:"Relace: Relace Search",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:1,output:3,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:128e3},"sao10k/l3-euryale-70b":{id:"sao10k/l3-euryale-70b",name:"Sao10k: Llama 3 Euryale 70B v2.1",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:1.48,output:1.48,cacheRead:0,cacheWrite:0},contextWindow:8192,maxTokens:8192},"sao10k/l3.1-euryale-70b":{id:"sao10k/l3.1-euryale-70b",name:"Sao10K: Llama 3.1 Euryale 70B v2.2",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.85,output:.85,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:16384},"stepfun/step-3.5-flash":{id:"stepfun/step-3.5-flash",name:"StepFun: Step 3.5 Flash",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.09999999999999999,output:.3,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:65536},"tencent/hy3-preview":{id:"tencent/hy3-preview",name:"Tencent: Hy3 preview",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.06599999999999999,output:.26,cacheRead:.029,cacheWrite:0},contextWindow:262144,maxTokens:262144},"thedrummer/rocinante-12b":{id:"thedrummer/rocinante-12b",name:"TheDrummer: Rocinante 12B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.16999999999999998,output:.43,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:32768},"thedrummer/unslopnemo-12b":{id:"thedrummer/unslopnemo-12b",name:"TheDrummer: UnslopNemo 12B",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.39999999999999997,output:.39999999999999997,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:32768},"upstage/solar-pro-3":{id:"upstage/solar-pro-3",name:"Upstage: Solar Pro 3",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.15,output:.6,cacheRead:.015,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"x-ai/grok-3":{id:"x-ai/grok-3",name:"xAI: Grok 3",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:3,output:15,cacheRead:.75,cacheWrite:0},contextWindow:131072,maxTokens:4096},"x-ai/grok-3-beta":{id:"x-ai/grok-3-beta",name:"xAI: Grok 3 Beta",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:3,output:15,cacheRead:.75,cacheWrite:0},contextWindow:131072,maxTokens:4096},"x-ai/grok-3-mini":{id:"x-ai/grok-3-mini",name:"xAI: Grok 3 Mini",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.3,output:.5,cacheRead:.075,cacheWrite:0},contextWindow:131072,maxTokens:4096},"x-ai/grok-3-mini-beta":{id:"x-ai/grok-3-mini-beta",name:"xAI: Grok 3 Mini Beta",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.3,output:.5,cacheRead:.075,cacheWrite:0},contextWindow:131072,maxTokens:4096},"x-ai/grok-4":{id:"x-ai/grok-4",name:"xAI: Grok 4",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.75,cacheWrite:0},contextWindow:256e3,maxTokens:4096},"x-ai/grok-4-fast":{id:"x-ai/grok-4-fast",name:"xAI: Grok 4 Fast",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.19999999999999998,output:.5,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:2e6,maxTokens:3e4},"x-ai/grok-4.1-fast":{id:"x-ai/grok-4.1-fast",name:"xAI: Grok 4.1 Fast",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.19999999999999998,output:.5,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:2e6,maxTokens:3e4},"x-ai/grok-4.20":{id:"x-ai/grok-4.20",name:"xAI: Grok 4.20",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:2.5,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:2e6,maxTokens:4096},"x-ai/grok-4.3":{id:"x-ai/grok-4.3",name:"xAI: Grok 4.3",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:2.5,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:1e6,maxTokens:4096},"x-ai/grok-code-fast-1":{id:"x-ai/grok-code-fast-1",name:"xAI: Grok Code Fast 1",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.19999999999999998,output:1.5,cacheRead:.02,cacheWrite:0},contextWindow:256e3,maxTokens:1e4},"xiaomi/mimo-v2-flash":{id:"xiaomi/mimo-v2-flash",name:"Xiaomi: MiMo-V2-Flash",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.09999999999999999,output:.3,cacheRead:.01,cacheWrite:0},contextWindow:262144,maxTokens:65536},"xiaomi/mimo-v2-omni":{id:"xiaomi/mimo-v2-omni",name:"Xiaomi: MiMo-V2-Omni",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.39999999999999997,output:2,cacheRead:.08,cacheWrite:0},contextWindow:262144,maxTokens:65536},"xiaomi/mimo-v2-pro":{id:"xiaomi/mimo-v2-pro",name:"Xiaomi: MiMo-V2-Pro",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:1,output:3,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:1048576,maxTokens:131072},"xiaomi/mimo-v2.5":{id:"xiaomi/mimo-v2.5",name:"Xiaomi: MiMo-V2.5",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.39999999999999997,output:2,cacheRead:.08,cacheWrite:0},contextWindow:1048576,maxTokens:131072},"xiaomi/mimo-v2.5-pro":{id:"xiaomi/mimo-v2.5-pro",name:"Xiaomi: MiMo-V2.5-Pro",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:1,output:3,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:1048576,maxTokens:16384},"z-ai/glm-4-32b":{id:"z-ai/glm-4-32b",name:"Z.ai: GLM 4 32B ",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!1,input:["text"],cost:{input:.09999999999999999,output:.09999999999999999,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"z-ai/glm-4.5":{id:"z-ai/glm-4.5",name:"Z.ai: GLM 4.5",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.6,output:2.2,cacheRead:.11,cacheWrite:0},contextWindow:131072,maxTokens:98304},"z-ai/glm-4.5-air":{id:"z-ai/glm-4.5-air",name:"Z.ai: GLM 4.5 Air",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.13,output:.85,cacheRead:.024999999999999998,cacheWrite:0},contextWindow:131072,maxTokens:98304},"z-ai/glm-4.5-air:free":{id:"z-ai/glm-4.5-air:free",name:"Z.ai: GLM 4.5 Air (free)",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:96e3},"z-ai/glm-4.5v":{id:"z-ai/glm-4.5v",name:"Z.ai: GLM 4.5V",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.6,output:1.7999999999999998,cacheRead:.11,cacheWrite:0},contextWindow:65536,maxTokens:16384},"z-ai/glm-4.6":{id:"z-ai/glm-4.6",name:"Z.ai: GLM 4.6",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.39,output:1.9,cacheRead:0,cacheWrite:0},contextWindow:204800,maxTokens:204800},"z-ai/glm-4.6v":{id:"z-ai/glm-4.6v",name:"Z.ai: GLM 4.6V",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.3,output:.8999999999999999,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:131072,maxTokens:24e3},"z-ai/glm-4.7":{id:"z-ai/glm-4.7",name:"Z.ai: GLM 4.7",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.39999999999999997,output:1.75,cacheRead:.08,cacheWrite:0},contextWindow:202752,maxTokens:131072},"z-ai/glm-4.7-flash":{id:"z-ai/glm-4.7-flash",name:"Z.ai: GLM 4.7 Flash",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.06,output:.39999999999999997,cacheRead:.01,cacheWrite:0},contextWindow:202752,maxTokens:16384},"z-ai/glm-5":{id:"z-ai/glm-5",name:"Z.ai: GLM 5",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:.6,output:1.9,cacheRead:.119,cacheWrite:0},contextWindow:202752,maxTokens:4096},"z-ai/glm-5-turbo":{id:"z-ai/glm-5-turbo",name:"Z.ai: GLM 5 Turbo",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:1.2,output:4,cacheRead:.24,cacheWrite:0},contextWindow:202752,maxTokens:131072},"z-ai/glm-5.1":{id:"z-ai/glm-5.1",name:"Z.ai: GLM 5.1",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text"],cost:{input:1.0499999999999998,output:3.5,cacheRead:.5249999999999999,cacheWrite:0},contextWindow:202752,maxTokens:65535},"z-ai/glm-5v-turbo":{id:"z-ai/glm-5v-turbo",name:"Z.ai: GLM 5V Turbo",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1.2,output:4,cacheRead:.24,cacheWrite:0},contextWindow:202752,maxTokens:131072},"~anthropic/claude-haiku-latest":{id:"~anthropic/claude-haiku-latest",name:"Anthropic Claude Haiku Latest",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.09999999999999999,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3},"~anthropic/claude-opus-latest":{id:"~anthropic/claude-opus-latest",name:"Anthropic: Claude Opus Latest",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"~anthropic/claude-sonnet-latest":{id:"~anthropic/claude-sonnet-latest",name:"Anthropic Claude Sonnet Latest",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:128e3},"~google/gemini-flash-latest":{id:"~google/gemini-flash-latest",name:"Google Gemini Flash Latest",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.5,output:3,cacheRead:.049999999999999996,cacheWrite:.08333333333333334},contextWindow:1048576,maxTokens:65536},"~google/gemini-pro-latest":{id:"~google/gemini-pro-latest",name:"Google Gemini Pro Latest",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.19999999999999998,cacheWrite:.375},contextWindow:1048576,maxTokens:65536},"~moonshotai/kimi-latest":{id:"~moonshotai/kimi-latest",name:"MoonshotAI Kimi Latest",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.5,cacheRead:.15,cacheWrite:0},contextWindow:262144,maxTokens:16384},"~openai/gpt-latest":{id:"~openai/gpt-latest",name:"OpenAI GPT Latest",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},"~openai/gpt-mini-latest":{id:"~openai/gpt-mini-latest",name:"OpenAI GPT Mini Latest",api:"openai-completions",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",reasoning:!0,input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:4e5,maxTokens:128e3}},together:{"MiniMaxAI/MiniMax-M2.5":{id:"MiniMaxAI/MiniMax-M2.5",name:"MiniMax-M2.5",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1},reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null},input:["text"],cost:{input:.3,output:1.2,cacheRead:.06,cacheWrite:0},contextWindow:204800,maxTokens:131072},"MiniMaxAI/MiniMax-M2.7":{id:"MiniMaxAI/MiniMax-M2.7",name:"MiniMax-M2.7",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1},reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null},input:["text"],cost:{input:.3,output:1.2,cacheRead:.06,cacheWrite:0},contextWindow:202752,maxTokens:131072},"Qwen/Qwen3-235B-A22B-Instruct-2507-tput":{id:"Qwen/Qwen3-235B-A22B-Instruct-2507-tput",name:"Qwen3 235B A22B Instruct 2507 FP8",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1,thinkingFormat:"together"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null},input:["text"],cost:{input:.2,output:.6,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8":{id:"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8",name:"Qwen3 Coder 480B A35B Instruct",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1},reasoning:!1,input:["text"],cost:{input:2,output:2,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"Qwen/Qwen3-Coder-Next-FP8":{id:"Qwen/Qwen3-Coder-Next-FP8",name:"Qwen3 Coder Next FP8",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1,thinkingFormat:"together"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null},input:["text"],cost:{input:.5,output:1.2,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"Qwen/Qwen3.5-397B-A17B":{id:"Qwen/Qwen3.5-397B-A17B",name:"Qwen3.5 397B A17B",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1,thinkingFormat:"together"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null},input:["text","image"],cost:{input:.6,output:3.6,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:13e4},"Qwen/Qwen3.6-Plus":{id:"Qwen/Qwen3.6-Plus",name:"Qwen3.6 Plus",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1,thinkingFormat:"together"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null},input:["text"],cost:{input:.5,output:3,cacheRead:0,cacheWrite:0},contextWindow:1e6,maxTokens:5e5},"deepseek-ai/DeepSeek-V3":{id:"deepseek-ai/DeepSeek-V3",name:"DeepSeek V3",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1,thinkingFormat:"together"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null},input:["text"],cost:{input:1.25,output:1.25,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"deepseek-ai/DeepSeek-V3-1":{id:"deepseek-ai/DeepSeek-V3-1",name:"DeepSeek V3.1",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1,thinkingFormat:"together"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null},input:["text"],cost:{input:.6,output:1.7,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"deepseek-ai/DeepSeek-V4-Pro":{id:"deepseek-ai/DeepSeek-V4-Pro",name:"DeepSeek V4 Pro",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!0,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1,thinkingFormat:"together"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null,high:"high",xhigh:null},input:["text"],cost:{input:2.1,output:4.4,cacheRead:.2,cacheWrite:0},contextWindow:512e3,maxTokens:384e3},"essentialai/Rnj-1-Instruct":{id:"essentialai/Rnj-1-Instruct",name:"Rnj-1 Instruct",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1},reasoning:!1,input:["text"],cost:{input:.15,output:.15,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:32768},"google/gemma-4-31B-it":{id:"google/gemma-4-31B-it",name:"Gemma 4 31B Instruct",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1,thinkingFormat:"together"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null},input:["text","image"],cost:{input:.2,output:.5,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:131072},"meta-llama/Llama-3.3-70B-Instruct-Turbo":{id:"meta-llama/Llama-3.3-70B-Instruct-Turbo",name:"Llama 3.3 70B",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1},reasoning:!1,input:["text"],cost:{input:.88,output:.88,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"moonshotai/Kimi-K2.5":{id:"moonshotai/Kimi-K2.5",name:"Kimi K2.5",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1,thinkingFormat:"together"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null},input:["text","image"],cost:{input:.5,output:2.8,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:262144},"moonshotai/Kimi-K2.6":{id:"moonshotai/Kimi-K2.6",name:"Kimi K2.6",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1,thinkingFormat:"together"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null},input:["text","image"],cost:{input:1.2,output:4.5,cacheRead:.2,cacheWrite:0},contextWindow:262144,maxTokens:131e3},"openai/gpt-oss-120b":{id:"openai/gpt-oss-120b",name:"GPT OSS 120B",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!0,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1,thinkingFormat:"openai"},reasoning:!0,thinkingLevelMap:{off:null,minimal:null},input:["text"],cost:{input:.15,output:.6,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"zai-org/GLM-5.1":{id:"zai-org/GLM-5.1",name:"GLM-5.1",api:"openai-completions",provider:"together",baseUrl:"https://api.together.ai/v1",compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",supportsStrictMode:!1,supportsLongCacheRetention:!1,thinkingFormat:"together"},reasoning:!0,thinkingLevelMap:{minimal:null,low:null,medium:null},input:["text"],cost:{input:1.4,output:4.4,cacheRead:0,cacheWrite:0},contextWindow:202752,maxTokens:131072}},"vercel-ai-gateway":{"alibaba/qwen-3-14b":{id:"alibaba/qwen-3-14b",name:"Qwen3-14B",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.12,output:.24,cacheRead:0,cacheWrite:0},contextWindow:40960,maxTokens:16384},"alibaba/qwen-3-235b":{id:"alibaba/qwen-3-235b",name:"Qwen3 235B A22b Instruct 2507",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.6,output:1.2,cacheRead:.6,cacheWrite:0},contextWindow:131e3,maxTokens:4e4},"alibaba/qwen-3-30b":{id:"alibaba/qwen-3-30b",name:"Qwen3-30B-A3B",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.08,output:.29,cacheRead:0,cacheWrite:0},contextWindow:40960,maxTokens:16384},"alibaba/qwen-3-32b":{id:"alibaba/qwen-3-32b",name:"Qwen 3 32B",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.16,output:.64,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192},"alibaba/qwen-3.6-max-preview":{id:"alibaba/qwen-3.6-max-preview",name:"Qwen 3.6 Max Preview",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.3,output:7.8,cacheRead:.26,cacheWrite:1.625},contextWindow:24e4,maxTokens:64e3},"alibaba/qwen3-235b-a22b-thinking":{id:"alibaba/qwen3-235b-a22b-thinking",name:"Qwen3 VL 235B A22B Thinking",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.39999999999999997,output:4,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"alibaba/qwen3-coder":{id:"alibaba/qwen3-coder",name:"Qwen3 Coder 480B A35B Instruct",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:1.5,output:7.5,cacheRead:.3,cacheWrite:0},contextWindow:262144,maxTokens:65536},"alibaba/qwen3-coder-30b-a3b":{id:"alibaba/qwen3-coder-30b-a3b",name:"Qwen 3 Coder 30B A3B Instruct",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.15,output:.6,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:8192},"alibaba/qwen3-coder-next":{id:"alibaba/qwen3-coder-next",name:"Qwen3 Coder Next",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.5,output:1.2,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"alibaba/qwen3-coder-plus":{id:"alibaba/qwen3-coder-plus",name:"Qwen3 Coder Plus",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:1,output:5,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:1e6,maxTokens:65536},"alibaba/qwen3-max":{id:"alibaba/qwen3-max",name:"Qwen3 Max",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:1.2,output:6,cacheRead:.24,cacheWrite:0},contextWindow:262144,maxTokens:32768},"alibaba/qwen3-max-preview":{id:"alibaba/qwen3-max-preview",name:"Qwen3 Max Preview",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:1.2,output:6,cacheRead:.24,cacheWrite:0},contextWindow:262144,maxTokens:32768},"alibaba/qwen3-max-thinking":{id:"alibaba/qwen3-max-thinking",name:"Qwen 3 Max Thinking",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:1.2,output:6,cacheRead:.24,cacheWrite:0},contextWindow:256e3,maxTokens:65536},"alibaba/qwen3-vl-thinking":{id:"alibaba/qwen3-vl-thinking",name:"Qwen3 VL 235B A22B Thinking",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.39999999999999997,output:4,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:32768},"alibaba/qwen3.5-flash":{id:"alibaba/qwen3.5-flash",name:"Qwen 3.5 Flash",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.09999999999999999,output:.39999999999999997,cacheRead:.001,cacheWrite:.125},contextWindow:1e6,maxTokens:64e3},"alibaba/qwen3.5-plus":{id:"alibaba/qwen3.5-plus",name:"Qwen 3.5 Plus",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.39999999999999997,output:2.4,cacheRead:.04,cacheWrite:.5},contextWindow:1e6,maxTokens:64e3},"alibaba/qwen3.6-27b":{id:"alibaba/qwen3.6-27b",name:"Qwen 3.6 27B",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.6,output:3.5999999999999996,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"alibaba/qwen3.6-plus":{id:"alibaba/qwen3.6-plus",name:"Qwen 3.6 Plus",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.5,output:3,cacheRead:.09999999999999999,cacheWrite:.625},contextWindow:1e6,maxTokens:64e3},"anthropic/claude-3-haiku":{id:"anthropic/claude-3-haiku",name:"Claude 3 Haiku",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.25,output:1.25,cacheRead:.03,cacheWrite:.3},contextWindow:2e5,maxTokens:4096},"anthropic/claude-3.5-haiku":{id:"anthropic/claude-3.5-haiku",name:"Claude 3.5 Haiku",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.7999999999999999,output:4,cacheRead:.08,cacheWrite:1},contextWindow:2e5,maxTokens:8192},"anthropic/claude-3.7-sonnet":{id:"anthropic/claude-3.7-sonnet",name:"Claude 3.7 Sonnet",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:8192},"anthropic/claude-haiku-4.5":{id:"anthropic/claude-haiku-4.5",name:"Claude Haiku 4.5",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.09999999999999999,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3},"anthropic/claude-opus-4":{id:"anthropic/claude-opus-4",name:"Claude Opus 4",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"anthropic/claude-opus-4.1":{id:"anthropic/claude-opus-4.1",name:"Claude Opus 4.1",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},"anthropic/claude-opus-4.5":{id:"anthropic/claude-opus-4.5",name:"Claude Opus 4.5",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:2e5,maxTokens:64e3},"anthropic/claude-opus-4.6":{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,thinkingLevelMap:{xhigh:"max"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"anthropic/claude-opus-4.7":{id:"anthropic/claude-opus-4.7",name:"Claude Opus 4.7",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},"anthropic/claude-sonnet-4":{id:"anthropic/claude-sonnet-4",name:"Claude Sonnet 4",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3},"anthropic/claude-sonnet-4.5":{id:"anthropic/claude-sonnet-4.5",name:"Claude Sonnet 4.5",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3},"anthropic/claude-sonnet-4.6":{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:128e3},"arcee-ai/trinity-large-preview":{id:"arcee-ai/trinity-large-preview",name:"Trinity Large Preview",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.25,output:1,cacheRead:0,cacheWrite:0},contextWindow:131e3,maxTokens:131e3},"arcee-ai/trinity-large-thinking":{id:"arcee-ai/trinity-large-thinking",name:"Trinity Large Thinking",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.25,output:.8999999999999999,cacheRead:0,cacheWrite:0},contextWindow:262100,maxTokens:8e4},"bytedance/seed-1.6":{id:"bytedance/seed-1.6",name:"Seed 1.6",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.25,output:2,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:256e3,maxTokens:32e3},"cohere/command-a":{id:"cohere/command-a",name:"Command A",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:2.5,output:10,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:8e3},"deepseek/deepseek-r1":{id:"deepseek/deepseek-r1",name:"DeepSeek-R1",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:1.35,output:5.4,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192},"deepseek/deepseek-v3":{id:"deepseek/deepseek-v3",name:"DeepSeek V3 0324",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.77,output:.77,cacheRead:0,cacheWrite:0},contextWindow:163840,maxTokens:16384},"deepseek/deepseek-v3.1":{id:"deepseek/deepseek-v3.1",name:"DeepSeek-V3.1",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.56,output:1.68,cacheRead:.28,cacheWrite:0},contextWindow:163840,maxTokens:8192},"deepseek/deepseek-v3.1-terminus":{id:"deepseek/deepseek-v3.1-terminus",name:"DeepSeek V3.1 Terminus",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.27,output:1,cacheRead:.135,cacheWrite:0},contextWindow:131072,maxTokens:65536},"deepseek/deepseek-v3.2":{id:"deepseek/deepseek-v3.2",name:"DeepSeek V3.2",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.28,output:.42,cacheRead:.028,cacheWrite:0},contextWindow:128e3,maxTokens:8e3},"deepseek/deepseek-v3.2-thinking":{id:"deepseek/deepseek-v3.2-thinking",name:"DeepSeek V3.2 Thinking",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.62,output:1.85,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8e3},"deepseek/deepseek-v4-flash":{id:"deepseek/deepseek-v4-flash",name:"DeepSeek V4 Flash",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.14,output:.28,cacheRead:.0028,cacheWrite:0},contextWindow:1e6,maxTokens:384e3},"deepseek/deepseek-v4-pro":{id:"deepseek/deepseek-v4-pro",name:"DeepSeek V4 Pro",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.435,output:.87,cacheRead:.0036,cacheWrite:0},contextWindow:1e6,maxTokens:384e3},"google/gemini-2.0-flash":{id:"google/gemini-2.0-flash",name:"Gemini 2.0 Flash",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.15,output:.6,cacheRead:.024999999999999998,cacheWrite:0},contextWindow:1048576,maxTokens:8192},"google/gemini-2.0-flash-lite":{id:"google/gemini-2.0-flash-lite",name:"Gemini 2.0 Flash Lite",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.075,output:.3,cacheRead:.02,cacheWrite:0},contextWindow:1048576,maxTokens:8192},"google/gemini-2.5-flash":{id:"google/gemini-2.5-flash",name:"Gemini 2.5 Flash",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.3,output:2.5,cacheRead:.03,cacheWrite:0},contextWindow:1e6,maxTokens:65536},"google/gemini-2.5-flash-lite":{id:"google/gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.09999999999999999,output:.39999999999999997,cacheRead:.01,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"google/gemini-2.5-pro":{id:"google/gemini-2.5-pro",name:"Gemini 2.5 Pro",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:1048576,maxTokens:65536},"google/gemini-3-flash":{id:"google/gemini-3-flash",name:"Gemini 3 Flash",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.5,output:3,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:1e6,maxTokens:65e3},"google/gemini-3-pro-preview":{id:"google/gemini-3-pro-preview",name:"Gemini 3 Pro Preview",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:1e6,maxTokens:64e3},"google/gemini-3.1-flash-lite":{id:"google/gemini-3.1-flash-lite",name:"Gemini 3.1 Flash Lite",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.25,output:1.5,cacheRead:.03,cacheWrite:0},contextWindow:1e6,maxTokens:65e3},"google/gemini-3.1-flash-lite-preview":{id:"google/gemini-3.1-flash-lite-preview",name:"Gemini 3.1 Flash Lite Preview",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.25,output:1.5,cacheRead:.03,cacheWrite:0},contextWindow:1e6,maxTokens:65e3},"google/gemini-3.1-pro-preview":{id:"google/gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:1e6,maxTokens:64e3},"google/gemma-4-26b-a4b-it":{id:"google/gemma-4-26b-a4b-it",name:"Gemma 4 26B A4B IT",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.13,output:.39999999999999997,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:131072},"google/gemma-4-31b-it":{id:"google/gemma-4-31b-it",name:"Gemma 4 31B IT",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.14,output:.39999999999999997,cacheRead:0,cacheWrite:0},contextWindow:262144,maxTokens:131072},"inception/mercury-2":{id:"inception/mercury-2",name:"Mercury 2",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.25,output:.75,cacheRead:.024999999999999998,cacheWrite:0},contextWindow:128e3,maxTokens:128e3},"inception/mercury-coder-small":{id:"inception/mercury-coder-small",name:"Mercury Coder Small Beta",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.25,output:1,cacheRead:0,cacheWrite:0},contextWindow:32e3,maxTokens:16384},"kwaipilot/kat-coder-pro-v2":{id:"kwaipilot/kat-coder-pro-v2",name:"Kat Coder Pro V2",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.06,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"meituan/longcat-flash-chat":{id:"meituan/longcat-flash-chat",name:"LongCat Flash Chat",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:1e5},"meta/llama-3.1-70b":{id:"meta/llama-3.1-70b",name:"Llama 3.1 70B Instruct",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.72,output:.72,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192},"meta/llama-3.1-8b":{id:"meta/llama-3.1-8b",name:"Llama 3.1 8B Instruct",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.22,output:.22,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192},"meta/llama-3.2-11b":{id:"meta/llama-3.2-11b",name:"Llama 3.2 11B Vision Instruct",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.16,output:.16,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192},"meta/llama-3.2-90b":{id:"meta/llama-3.2-90b",name:"Llama 3.2 90B Vision Instruct",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.72,output:.72,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192},"meta/llama-3.3-70b":{id:"meta/llama-3.3-70b",name:"Llama 3.3 70B Instruct",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.72,output:.72,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192},"meta/llama-4-maverick":{id:"meta/llama-4-maverick",name:"Llama 4 Maverick 17B Instruct",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.24,output:.9700000000000001,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192},"meta/llama-4-scout":{id:"meta/llama-4-scout",name:"Llama 4 Scout 17B Instruct",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.16999999999999998,output:.66,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192},"minimax/minimax-m2":{id:"minimax/minimax-m2",name:"MiniMax M2",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.03,cacheWrite:.375},contextWindow:205e3,maxTokens:205e3},"minimax/minimax-m2.1":{id:"minimax/minimax-m2.1",name:"MiniMax M2.1",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.03,cacheWrite:.375},contextWindow:204800,maxTokens:131072},"minimax/minimax-m2.1-lightning":{id:"minimax/minimax-m2.1-lightning",name:"MiniMax M2.1 Lightning",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.3,output:2.4,cacheRead:.03,cacheWrite:.375},contextWindow:204800,maxTokens:131072},"minimax/minimax-m2.5":{id:"minimax/minimax-m2.5",name:"MiniMax M2.5",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.3,output:1.2,cacheRead:.03,cacheWrite:.375},contextWindow:204800,maxTokens:131e3},"minimax/minimax-m2.5-highspeed":{id:"minimax/minimax-m2.5-highspeed",name:"MiniMax M2.5 High Speed",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.6,output:2.4,cacheRead:.03,cacheWrite:.375},contextWindow:204800,maxTokens:131e3},"minimax/minimax-m2.7":{id:"minimax/minimax-m2.7",name:"Minimax M2.7",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.3,output:1.2,cacheRead:.06,cacheWrite:.375},contextWindow:204800,maxTokens:131e3},"minimax/minimax-m2.7-highspeed":{id:"minimax/minimax-m2.7-highspeed",name:"MiniMax M2.7 High Speed",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.6,output:2.4,cacheRead:.06,cacheWrite:.375},contextWindow:204800,maxTokens:131100},"mistral/codestral":{id:"mistral/codestral",name:"Mistral Codestral",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.3,output:.8999999999999999,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4e3},"mistral/devstral-2":{id:"mistral/devstral-2",name:"Devstral 2",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.39999999999999997,output:2,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"mistral/devstral-small":{id:"mistral/devstral-small",name:"Devstral Small 1.1",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.09999999999999999,output:.3,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:64e3},"mistral/devstral-small-2":{id:"mistral/devstral-small-2",name:"Devstral Small 2",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.09999999999999999,output:.3,cacheRead:0,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"mistral/ministral-3b":{id:"mistral/ministral-3b",name:"Ministral 3B",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.09999999999999999,output:.09999999999999999,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4e3},"mistral/ministral-8b":{id:"mistral/ministral-8b",name:"Ministral 8B",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.15,output:.15,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4e3},"mistral/mistral-medium":{id:"mistral/mistral-medium",name:"Mistral Medium 3.1",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.39999999999999997,output:2,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:64e3},"mistral/mistral-small":{id:"mistral/mistral-small",name:"Mistral Small",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.09999999999999999,output:.3,cacheRead:0,cacheWrite:0},contextWindow:32e3,maxTokens:4e3},"mistral/pixtral-12b":{id:"mistral/pixtral-12b",name:"Pixtral 12B 2409",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.15,output:.15,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4e3},"mistral/pixtral-large":{id:"mistral/pixtral-large",name:"Pixtral Large",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:2,output:6,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4e3},"moonshotai/kimi-k2":{id:"moonshotai/kimi-k2",name:"Kimi K2 Instruct",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.5700000000000001,output:2.3,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"moonshotai/kimi-k2-thinking":{id:"moonshotai/kimi-k2-thinking",name:"Kimi K2 Thinking",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.6,output:2.5,cacheRead:.15,cacheWrite:0},contextWindow:262114,maxTokens:262114},"moonshotai/kimi-k2-thinking-turbo":{id:"moonshotai/kimi-k2-thinking-turbo",name:"Kimi K2 Thinking Turbo",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:1.15,output:8,cacheRead:.15,cacheWrite:0},contextWindow:262114,maxTokens:262114},"moonshotai/kimi-k2-turbo":{id:"moonshotai/kimi-k2-turbo",name:"Kimi K2 Turbo",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:1.15,output:8,cacheRead:.15,cacheWrite:0},contextWindow:256e3,maxTokens:16384},"moonshotai/kimi-k2.5":{id:"moonshotai/kimi-k2.5",name:"Kimi K2.5",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.6,output:3,cacheRead:.09999999999999999,cacheWrite:0},contextWindow:262114,maxTokens:262114},"moonshotai/kimi-k2.6":{id:"moonshotai/kimi-k2.6",name:"Kimi K2.6",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.16,cacheWrite:0},contextWindow:262e3,maxTokens:262e3},"nvidia/nemotron-nano-12b-v2-vl":{id:"nvidia/nemotron-nano-12b-v2-vl",name:"Nvidia Nemotron Nano 12B V2 VL",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.19999999999999998,output:.6,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"nvidia/nemotron-nano-9b-v2":{id:"nvidia/nemotron-nano-9b-v2",name:"Nvidia Nemotron Nano 9B V2",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.06,output:.22999999999999998,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"openai/gpt-4-turbo":{id:"openai/gpt-4-turbo",name:"GPT-4 Turbo",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:10,output:30,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:4096},"openai/gpt-4.1":{id:"openai/gpt-4.1",name:"GPT-4.1",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:1047576,maxTokens:32768},"openai/gpt-4.1-mini":{id:"openai/gpt-4.1-mini",name:"GPT-4.1 mini",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.39999999999999997,output:1.5999999999999999,cacheRead:.09999999999999999,cacheWrite:0},contextWindow:1047576,maxTokens:32768},"openai/gpt-4.1-nano":{id:"openai/gpt-4.1-nano",name:"GPT-4.1 nano",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.09999999999999999,output:.39999999999999997,cacheRead:.024999999999999998,cacheWrite:0},contextWindow:1047576,maxTokens:32768},"openai/gpt-4o":{id:"openai/gpt-4o",name:"GPT-4o",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:2.5,output:10,cacheRead:1.25,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-4o-mini":{id:"openai/gpt-4o-mini",name:"GPT-4o mini",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.15,output:.6,cacheRead:.075,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-5":{id:"openai/gpt-5",name:"GPT-5",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5-chat":{id:"openai/gpt-5-chat",name:"GPT 5 Chat",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-5-codex":{id:"openai/gpt-5-codex",name:"GPT-5-Codex",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5-mini":{id:"openai/gpt-5-mini",name:"GPT-5 mini",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.024999999999999998,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5-nano":{id:"openai/gpt-5-nano",name:"GPT-5 nano",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.049999999999999996,output:.39999999999999997,cacheRead:.005,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5-pro":{id:"openai/gpt-5-pro",name:"GPT-5 pro",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:15,output:120,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:272e3},"openai/gpt-5.1-codex":{id:"openai/gpt-5.1-codex",name:"GPT-5.1-Codex",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.1-codex-max":{id:"openai/gpt-5.1-codex-max",name:"GPT 5.1 Codex Max",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.1-codex-mini":{id:"openai/gpt-5.1-codex-mini",name:"GPT 5.1 Codex Mini",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.024999999999999998,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.1-instant":{id:"openai/gpt-5.1-instant",name:"GPT-5.1 Instant",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-5.1-thinking":{id:"openai/gpt-5.1-thinking",name:"GPT 5.1 Thinking",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.2":{id:"openai/gpt-5.2",name:"GPT 5.2",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.2-chat":{id:"openai/gpt-5.2-chat",name:"GPT 5.2 Chat",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-5.2-codex":{id:"openai/gpt-5.2-codex",name:"GPT 5.2 Codex",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.2-pro":{id:"openai/gpt-5.2-pro",name:"GPT 5.2 ",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:21,output:168,cacheRead:0,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.3-chat":{id:"openai/gpt-5.3-chat",name:"GPT-5.3 Chat",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:128e3,maxTokens:16384},"openai/gpt-5.3-codex":{id:"openai/gpt-5.3-codex",name:"GPT 5.3 Codex",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.4":{id:"openai/gpt-5.4",name:"GPT 5.4",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},"openai/gpt-5.4-mini":{id:"openai/gpt-5.4-mini",name:"GPT 5.4 Mini",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.4-nano":{id:"openai/gpt-5.4-nano",name:"GPT 5.4 Nano",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:.19999999999999998,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},"openai/gpt-5.4-pro":{id:"openai/gpt-5.4-pro",name:"GPT 5.4 Pro",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:30,output:180,cacheRead:0,cacheWrite:0},contextWindow:105e4,maxTokens:128e3},"openai/gpt-5.5":{id:"openai/gpt-5.5",name:"GPT 5.5",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0},contextWindow:1e6,maxTokens:128e3},"openai/gpt-5.5-pro":{id:"openai/gpt-5.5-pro",name:"GPT 5.5 Pro",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,thinkingLevelMap:{xhigh:"xhigh"},input:["text","image"],cost:{input:30,output:180,cacheRead:0,cacheWrite:0},contextWindow:1e6,maxTokens:128e3},"openai/gpt-oss-20b":{id:"openai/gpt-oss-20b",name:"GPT OSS 120B",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.049999999999999996,output:.19999999999999998,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:8192},"openai/gpt-oss-safeguard-20b":{id:"openai/gpt-oss-safeguard-20b",name:"GPT OSS Safeguard 20B",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.075,output:.3,cacheRead:.037,cacheWrite:0},contextWindow:131072,maxTokens:65536},"openai/o1":{id:"openai/o1",name:"o1",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:15,output:60,cacheRead:7.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"openai/o3":{id:"openai/o3",name:"o3",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"openai/o3-deep-research":{id:"openai/o3-deep-research",name:"o3-deep-research",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:10,output:40,cacheRead:2.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"openai/o3-mini":{id:"openai/o3-mini",name:"o3-mini",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.55,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"openai/o3-pro":{id:"openai/o3-pro",name:"o3 Pro",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:20,output:80,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"openai/o4-mini":{id:"openai/o4-mini",name:"o4-mini",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.1,output:4.4,cacheRead:.275,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},"perplexity/sonar":{id:"perplexity/sonar",name:"Sonar",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:127e3,maxTokens:8e3},"perplexity/sonar-pro":{id:"perplexity/sonar-pro",name:"Sonar Pro",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:8e3},"xai/grok-3":{id:"xai/grok-3",name:"Grok 3 Beta",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:3,output:15,cacheRead:.75,cacheWrite:0},contextWindow:131072,maxTokens:131072},"xai/grok-3-fast":{id:"xai/grok-3-fast",name:"Grok 3 Fast Beta",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:5,output:25,cacheRead:1.25,cacheWrite:0},contextWindow:131072,maxTokens:131072},"xai/grok-3-mini":{id:"xai/grok-3-mini",name:"Grok 3 Mini Beta",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.3,output:.5,cacheRead:.075,cacheWrite:0},contextWindow:131072,maxTokens:131072},"xai/grok-3-mini-fast":{id:"xai/grok-3-mini-fast",name:"Grok 3 Mini Fast Beta",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text"],cost:{input:.6,output:4,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:131072},"xai/grok-4":{id:"xai/grok-4",name:"Grok 4",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.75,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"xai/grok-4-fast-non-reasoning":{id:"xai/grok-4-fast-non-reasoning",name:"Grok 4 Fast Non-Reasoning",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.19999999999999998,output:.5,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:2e6,maxTokens:256e3},"xai/grok-4-fast-reasoning":{id:"xai/grok-4-fast-reasoning",name:"Grok 4 Fast Reasoning",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.19999999999999998,output:.5,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:2e6,maxTokens:256e3},"xai/grok-4.1-fast-non-reasoning":{id:"xai/grok-4.1-fast-non-reasoning",name:"Grok 4.1 Fast Non-Reasoning",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.19999999999999998,output:.5,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:2e6,maxTokens:3e4},"xai/grok-4.1-fast-reasoning":{id:"xai/grok-4.1-fast-reasoning",name:"Grok 4.1 Fast Reasoning",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.19999999999999998,output:.5,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:2e6,maxTokens:3e4},"xai/grok-4.20-multi-agent":{id:"xai/grok-4.20-multi-agent",name:"Grok 4.20 Multi-Agent",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.25,output:2.5,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:2e6,maxTokens:2e6},"xai/grok-4.20-multi-agent-beta":{id:"xai/grok-4.20-multi-agent-beta",name:"Grok 4.20 Multi Agent Beta",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.25,output:2.5,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:2e6,maxTokens:2e6},"xai/grok-4.20-non-reasoning":{id:"xai/grok-4.20-non-reasoning",name:"Grok 4.20 Non-Reasoning",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:1.25,output:2.5,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:2e6,maxTokens:2e6},"xai/grok-4.20-non-reasoning-beta":{id:"xai/grok-4.20-non-reasoning-beta",name:"Grok 4.20 Beta Non-Reasoning",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:1.25,output:2.5,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:2e6,maxTokens:2e6},"xai/grok-4.20-reasoning":{id:"xai/grok-4.20-reasoning",name:"Grok 4.20 Reasoning",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.25,output:2.5,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:2e6,maxTokens:2e6},"xai/grok-4.20-reasoning-beta":{id:"xai/grok-4.20-reasoning-beta",name:"Grok 4.20 Beta Reasoning",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.25,output:2.5,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:2e6,maxTokens:2e6},"xai/grok-4.3":{id:"xai/grok-4.3",name:"Grok 4.3",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.25,output:2.5,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:1e6,maxTokens:1e6},"xai/grok-code-fast-1":{id:"xai/grok-code-fast-1",name:"Grok Code Fast 1",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.19999999999999998,output:1.5,cacheRead:.02,cacheWrite:0},contextWindow:256e3,maxTokens:256e3},"xiaomi/mimo-v2-flash":{id:"xiaomi/mimo-v2-flash",name:"MiMo V2 Flash",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.09999999999999999,output:.3,cacheRead:.01,cacheWrite:0},contextWindow:262144,maxTokens:32e3},"xiaomi/mimo-v2-pro":{id:"xiaomi/mimo-v2-pro",name:"MiMo V2 Pro",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:1,output:3,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:1e6,maxTokens:128e3},"xiaomi/mimo-v2.5":{id:"xiaomi/mimo-v2.5",name:"MiMo M2.5",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.39999999999999997,output:2,cacheRead:.08,cacheWrite:0},contextWindow:105e4,maxTokens:131100},"xiaomi/mimo-v2.5-pro":{id:"xiaomi/mimo-v2.5-pro",name:"MiMo V2.5 Pro",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1,output:3,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:105e4,maxTokens:131e3},"zai/glm-4.5":{id:"zai/glm-4.5",name:"GLM-4.5",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.6,output:2.2,cacheRead:.11,cacheWrite:0},contextWindow:128e3,maxTokens:96e3},"zai/glm-4.5-air":{id:"zai/glm-4.5-air",name:"GLM 4.5 Air",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.19999999999999998,output:1.1,cacheRead:.03,cacheWrite:0},contextWindow:128e3,maxTokens:96e3},"zai/glm-4.5v":{id:"zai/glm-4.5v",name:"GLM 4.5V",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!1,input:["text","image"],cost:{input:.6,output:1.7999999999999998,cacheRead:.11,cacheWrite:0},contextWindow:66e3,maxTokens:16e3},"zai/glm-4.6":{id:"zai/glm-4.6",name:"GLM 4.6",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.6,output:2.2,cacheRead:.11,cacheWrite:0},contextWindow:2e5,maxTokens:96e3},"zai/glm-4.6v":{id:"zai/glm-4.6v",name:"GLM-4.6V",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:.3,output:.8999999999999999,cacheRead:.049999999999999996,cacheWrite:0},contextWindow:128e3,maxTokens:24e3},"zai/glm-4.6v-flash":{id:"zai/glm-4.6v-flash",name:"GLM-4.6V-Flash",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:24e3},"zai/glm-4.7":{id:"zai/glm-4.7",name:"GLM 4.7",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:2.25,output:2.75,cacheRead:2.25,cacheWrite:0},contextWindow:131e3,maxTokens:4e4},"zai/glm-4.7-flash":{id:"zai/glm-4.7-flash",name:"GLM 4.7 Flash",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.07,output:.39999999999999997,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:131e3},"zai/glm-4.7-flashx":{id:"zai/glm-4.7-flashx",name:"GLM 4.7 FlashX",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:.06,output:.39999999999999997,cacheRead:.01,cacheWrite:0},contextWindow:2e5,maxTokens:128e3},"zai/glm-5":{id:"zai/glm-5",name:"GLM 5",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:1,output:3.1999999999999997,cacheRead:.19999999999999998,cacheWrite:0},contextWindow:202800,maxTokens:131100},"zai/glm-5-turbo":{id:"zai/glm-5-turbo",name:"GLM 5 Turbo",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:1.2,output:4,cacheRead:.24,cacheWrite:0},contextWindow:202800,maxTokens:131100},"zai/glm-5.1":{id:"zai/glm-5.1",name:"GLM 5.1",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text"],cost:{input:1.4,output:4.4,cacheRead:.26,cacheWrite:0},contextWindow:202800,maxTokens:64e3},"zai/glm-5v-turbo":{id:"zai/glm-5v-turbo",name:"GLM 5V Turbo",api:"anthropic-messages",provider:"vercel-ai-gateway",baseUrl:"https://ai-gateway.vercel.sh",reasoning:!0,input:["text","image"],cost:{input:1.2,output:4,cacheRead:.24,cacheWrite:0},contextWindow:2e5,maxTokens:128e3}},xai:{"grok-2":{id:"grok-2",name:"Grok 2",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text"],cost:{input:2,output:10,cacheRead:2,cacheWrite:0},contextWindow:131072,maxTokens:8192},"grok-2-1212":{id:"grok-2-1212",name:"Grok 2 (1212)",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text"],cost:{input:2,output:10,cacheRead:2,cacheWrite:0},contextWindow:131072,maxTokens:8192},"grok-2-latest":{id:"grok-2-latest",name:"Grok 2 Latest",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text"],cost:{input:2,output:10,cacheRead:2,cacheWrite:0},contextWindow:131072,maxTokens:8192},"grok-2-vision":{id:"grok-2-vision",name:"Grok 2 Vision",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text","image"],cost:{input:2,output:10,cacheRead:2,cacheWrite:0},contextWindow:8192,maxTokens:4096},"grok-2-vision-1212":{id:"grok-2-vision-1212",name:"Grok 2 Vision (1212)",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text","image"],cost:{input:2,output:10,cacheRead:2,cacheWrite:0},contextWindow:8192,maxTokens:4096},"grok-2-vision-latest":{id:"grok-2-vision-latest",name:"Grok 2 Vision Latest",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text","image"],cost:{input:2,output:10,cacheRead:2,cacheWrite:0},contextWindow:8192,maxTokens:4096},"grok-3":{id:"grok-3",name:"Grok 3",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text"],cost:{input:3,output:15,cacheRead:.75,cacheWrite:0},contextWindow:131072,maxTokens:8192},"grok-3-fast":{id:"grok-3-fast",name:"Grok 3 Fast",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text"],cost:{input:5,output:25,cacheRead:1.25,cacheWrite:0},contextWindow:131072,maxTokens:8192},"grok-3-fast-latest":{id:"grok-3-fast-latest",name:"Grok 3 Fast Latest",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text"],cost:{input:5,output:25,cacheRead:1.25,cacheWrite:0},contextWindow:131072,maxTokens:8192},"grok-3-latest":{id:"grok-3-latest",name:"Grok 3 Latest",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text"],cost:{input:3,output:15,cacheRead:.75,cacheWrite:0},contextWindow:131072,maxTokens:8192},"grok-3-mini":{id:"grok-3-mini",name:"Grok 3 Mini",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!0,input:["text"],cost:{input:.3,output:.5,cacheRead:.075,cacheWrite:0},contextWindow:131072,maxTokens:8192},"grok-3-mini-fast":{id:"grok-3-mini-fast",name:"Grok 3 Mini Fast",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!0,input:["text"],cost:{input:.6,output:4,cacheRead:.15,cacheWrite:0},contextWindow:131072,maxTokens:8192},"grok-3-mini-fast-latest":{id:"grok-3-mini-fast-latest",name:"Grok 3 Mini Fast Latest",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!0,input:["text"],cost:{input:.6,output:4,cacheRead:.15,cacheWrite:0},contextWindow:131072,maxTokens:8192},"grok-3-mini-latest":{id:"grok-3-mini-latest",name:"Grok 3 Mini Latest",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!0,input:["text"],cost:{input:.3,output:.5,cacheRead:.075,cacheWrite:0},contextWindow:131072,maxTokens:8192},"grok-4":{id:"grok-4",name:"Grok 4",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!0,input:["text"],cost:{input:3,output:15,cacheRead:.75,cacheWrite:0},contextWindow:256e3,maxTokens:64e3},"grok-4-1-fast":{id:"grok-4-1-fast",name:"Grok 4.1 Fast",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!0,input:["text","image"],cost:{input:.2,output:.5,cacheRead:.05,cacheWrite:0},contextWindow:2e6,maxTokens:3e4},"grok-4-1-fast-non-reasoning":{id:"grok-4-1-fast-non-reasoning",name:"Grok 4.1 Fast (Non-Reasoning)",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text","image"],cost:{input:.2,output:.5,cacheRead:.05,cacheWrite:0},contextWindow:2e6,maxTokens:3e4},"grok-4-fast":{id:"grok-4-fast",name:"Grok 4 Fast",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!0,input:["text","image"],cost:{input:.2,output:.5,cacheRead:.05,cacheWrite:0},contextWindow:2e6,maxTokens:3e4},"grok-4-fast-non-reasoning":{id:"grok-4-fast-non-reasoning",name:"Grok 4 Fast (Non-Reasoning)",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text","image"],cost:{input:.2,output:.5,cacheRead:.05,cacheWrite:0},contextWindow:2e6,maxTokens:3e4},"grok-4.20-0309-non-reasoning":{id:"grok-4.20-0309-non-reasoning",name:"Grok 4.20 (Non-Reasoning)",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text","image"],cost:{input:2,output:6,cacheRead:.2,cacheWrite:0},contextWindow:2e6,maxTokens:3e4},"grok-4.20-0309-reasoning":{id:"grok-4.20-0309-reasoning",name:"Grok 4.20 (Reasoning)",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.2,cacheWrite:0},contextWindow:2e6,maxTokens:3e4},"grok-4.3":{id:"grok-4.3",name:"Grok 4.3",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:2.5,cacheRead:.2,cacheWrite:0},contextWindow:1e6,maxTokens:3e4},"grok-beta":{id:"grok-beta",name:"Grok Beta",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text"],cost:{input:5,output:15,cacheRead:5,cacheWrite:0},contextWindow:131072,maxTokens:4096},"grok-code-fast-1":{id:"grok-code-fast-1",name:"Grok Code Fast 1",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!0,input:["text"],cost:{input:.2,output:1.5,cacheRead:.02,cacheWrite:0},contextWindow:256e3,maxTokens:1e4},"grok-vision-beta":{id:"grok-vision-beta",name:"Grok Vision Beta",api:"openai-completions",provider:"xai",baseUrl:"https://api.x.ai/v1",reasoning:!1,input:["text","image"],cost:{input:5,output:15,cacheRead:5,cacheWrite:0},contextWindow:8192,maxTokens:4096}},xiaomi:{"mimo-v2-flash":{id:"mimo-v2-flash",name:"MiMo-V2-Flash",api:"anthropic-messages",provider:"xiaomi",baseUrl:"https://api.xiaomimimo.com/anthropic",reasoning:!0,input:["text"],cost:{input:.1,output:.3,cacheRead:.01,cacheWrite:0},contextWindow:262144,maxTokens:65536},"mimo-v2-omni":{id:"mimo-v2-omni",name:"MiMo-V2-Omni",api:"anthropic-messages",provider:"xiaomi",baseUrl:"https://api.xiaomimimo.com/anthropic",reasoning:!0,input:["text","image"],cost:{input:.4,output:2,cacheRead:.08,cacheWrite:0},contextWindow:262144,maxTokens:131072},"mimo-v2-pro":{id:"mimo-v2-pro",name:"MiMo-V2-Pro",api:"anthropic-messages",provider:"xiaomi",baseUrl:"https://api.xiaomimimo.com/anthropic",reasoning:!0,input:["text"],cost:{input:1,output:3,cacheRead:.2,cacheWrite:0},contextWindow:1048576,maxTokens:131072},"mimo-v2.5":{id:"mimo-v2.5",name:"MiMo-V2.5",api:"anthropic-messages",provider:"xiaomi",baseUrl:"https://api.xiaomimimo.com/anthropic",reasoning:!0,input:["text","image"],cost:{input:.4,output:2,cacheRead:.08,cacheWrite:0},contextWindow:1048576,maxTokens:131072},"mimo-v2.5-pro":{id:"mimo-v2.5-pro",name:"MiMo-V2.5-Pro",api:"anthropic-messages",provider:"xiaomi",baseUrl:"https://api.xiaomimimo.com/anthropic",reasoning:!0,input:["text"],cost:{input:1,output:3,cacheRead:.2,cacheWrite:0},contextWindow:1048576,maxTokens:131072}},"xiaomi-token-plan-ams":{"mimo-v2-flash":{id:"mimo-v2-flash",name:"MiMo-V2-Flash",api:"anthropic-messages",provider:"xiaomi-token-plan-ams",baseUrl:"https://token-plan-ams.xiaomimimo.com/anthropic",reasoning:!0,input:["text"],cost:{input:.1,output:.3,cacheRead:.01,cacheWrite:0},contextWindow:262144,maxTokens:65536},"mimo-v2-omni":{id:"mimo-v2-omni",name:"MiMo-V2-Omni",api:"anthropic-messages",provider:"xiaomi-token-plan-ams",baseUrl:"https://token-plan-ams.xiaomimimo.com/anthropic",reasoning:!0,input:["text","image"],cost:{input:.4,output:2,cacheRead:.08,cacheWrite:0},contextWindow:262144,maxTokens:131072},"mimo-v2-pro":{id:"mimo-v2-pro",name:"MiMo-V2-Pro",api:"anthropic-messages",provider:"xiaomi-token-plan-ams",baseUrl:"https://token-plan-ams.xiaomimimo.com/anthropic",reasoning:!0,input:["text"],cost:{input:1,output:3,cacheRead:.2,cacheWrite:0},contextWindow:1048576,maxTokens:131072},"mimo-v2.5":{id:"mimo-v2.5",name:"MiMo-V2.5",api:"anthropic-messages",provider:"xiaomi-token-plan-ams",baseUrl:"https://token-plan-ams.xiaomimimo.com/anthropic",reasoning:!0,input:["text","image"],cost:{input:.4,output:2,cacheRead:.08,cacheWrite:0},contextWindow:1048576,maxTokens:131072},"mimo-v2.5-pro":{id:"mimo-v2.5-pro",name:"MiMo-V2.5-Pro",api:"anthropic-messages",provider:"xiaomi-token-plan-ams",baseUrl:"https://token-plan-ams.xiaomimimo.com/anthropic",reasoning:!0,input:["text"],cost:{input:1,output:3,cacheRead:.2,cacheWrite:0},contextWindow:1048576,maxTokens:131072}},"xiaomi-token-plan-cn":{"mimo-v2-flash":{id:"mimo-v2-flash",name:"MiMo-V2-Flash",api:"anthropic-messages",provider:"xiaomi-token-plan-cn",baseUrl:"https://token-plan-cn.xiaomimimo.com/anthropic",reasoning:!0,input:["text"],cost:{input:.1,output:.3,cacheRead:.01,cacheWrite:0},contextWindow:262144,maxTokens:65536},"mimo-v2-omni":{id:"mimo-v2-omni",name:"MiMo-V2-Omni",api:"anthropic-messages",provider:"xiaomi-token-plan-cn",baseUrl:"https://token-plan-cn.xiaomimimo.com/anthropic",reasoning:!0,input:["text","image"],cost:{input:.4,output:2,cacheRead:.08,cacheWrite:0},contextWindow:262144,maxTokens:131072},"mimo-v2-pro":{id:"mimo-v2-pro",name:"MiMo-V2-Pro",api:"anthropic-messages",provider:"xiaomi-token-plan-cn",baseUrl:"https://token-plan-cn.xiaomimimo.com/anthropic",reasoning:!0,input:["text"],cost:{input:1,output:3,cacheRead:.2,cacheWrite:0},contextWindow:1048576,maxTokens:131072},"mimo-v2.5":{id:"mimo-v2.5",name:"MiMo-V2.5",api:"anthropic-messages",provider:"xiaomi-token-plan-cn",baseUrl:"https://token-plan-cn.xiaomimimo.com/anthropic",reasoning:!0,input:["text","image"],cost:{input:.4,output:2,cacheRead:.08,cacheWrite:0},contextWindow:1048576,maxTokens:131072},"mimo-v2.5-pro":{id:"mimo-v2.5-pro",name:"MiMo-V2.5-Pro",api:"anthropic-messages",provider:"xiaomi-token-plan-cn",baseUrl:"https://token-plan-cn.xiaomimimo.com/anthropic",reasoning:!0,input:["text"],cost:{input:1,output:3,cacheRead:.2,cacheWrite:0},contextWindow:1048576,maxTokens:131072}},"xiaomi-token-plan-sgp":{"mimo-v2-flash":{id:"mimo-v2-flash",name:"MiMo-V2-Flash",api:"anthropic-messages",provider:"xiaomi-token-plan-sgp",baseUrl:"https://token-plan-sgp.xiaomimimo.com/anthropic",reasoning:!0,input:["text"],cost:{input:.1,output:.3,cacheRead:.01,cacheWrite:0},contextWindow:262144,maxTokens:65536},"mimo-v2-omni":{id:"mimo-v2-omni",name:"MiMo-V2-Omni",api:"anthropic-messages",provider:"xiaomi-token-plan-sgp",baseUrl:"https://token-plan-sgp.xiaomimimo.com/anthropic",reasoning:!0,input:["text","image"],cost:{input:.4,output:2,cacheRead:.08,cacheWrite:0},contextWindow:262144,maxTokens:131072},"mimo-v2-pro":{id:"mimo-v2-pro",name:"MiMo-V2-Pro",api:"anthropic-messages",provider:"xiaomi-token-plan-sgp",baseUrl:"https://token-plan-sgp.xiaomimimo.com/anthropic",reasoning:!0,input:["text"],cost:{input:1,output:3,cacheRead:.2,cacheWrite:0},contextWindow:1048576,maxTokens:131072},"mimo-v2.5":{id:"mimo-v2.5",name:"MiMo-V2.5",api:"anthropic-messages",provider:"xiaomi-token-plan-sgp",baseUrl:"https://token-plan-sgp.xiaomimimo.com/anthropic",reasoning:!0,input:["text","image"],cost:{input:.4,output:2,cacheRead:.08,cacheWrite:0},contextWindow:1048576,maxTokens:131072},"mimo-v2.5-pro":{id:"mimo-v2.5-pro",name:"MiMo-V2.5-Pro",api:"anthropic-messages",provider:"xiaomi-token-plan-sgp",baseUrl:"https://token-plan-sgp.xiaomimimo.com/anthropic",reasoning:!0,input:["text"],cost:{input:1,output:3,cacheRead:.2,cacheWrite:0},contextWindow:1048576,maxTokens:131072}},zai:{"glm-4.5-air":{id:"glm-4.5-air",name:"GLM-4.5-Air",api:"openai-completions",provider:"zai",baseUrl:"https://api.z.ai/api/coding/paas/v4",compat:{supportsDeveloperRole:!1,thinkingFormat:"zai"},reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:131072,maxTokens:98304},"glm-4.7":{id:"glm-4.7",name:"GLM-4.7",api:"openai-completions",provider:"zai",baseUrl:"https://api.z.ai/api/coding/paas/v4",compat:{supportsDeveloperRole:!1,thinkingFormat:"zai",zaiToolStream:!0},reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:204800,maxTokens:131072},"glm-5-turbo":{id:"glm-5-turbo",name:"GLM-5-Turbo",api:"openai-completions",provider:"zai",baseUrl:"https://api.z.ai/api/coding/paas/v4",compat:{supportsDeveloperRole:!1,thinkingFormat:"zai",zaiToolStream:!0},reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:131072},"glm-5.1":{id:"glm-5.1",name:"GLM-5.1",api:"openai-completions",provider:"zai",baseUrl:"https://api.z.ai/api/coding/paas/v4",compat:{supportsDeveloperRole:!1,thinkingFormat:"zai",zaiToolStream:!0},reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:131072},"glm-5v-turbo":{id:"glm-5v-turbo",name:"GLM-5V-Turbo",api:"openai-completions",provider:"zai",baseUrl:"https://api.z.ai/api/coding/paas/v4",compat:{supportsDeveloperRole:!1,thinkingFormat:"zai",zaiToolStream:!0},reasoning:!0,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:2e5,maxTokens:131072}}}});function Ra(){return Array.from(Ma.keys())}function Ea(i){let e=Ma.get(i);return e?Array.from(e.values()):[]}function je(i,e){return e.cost.input=i.cost.input/1e6*e.input,e.cost.output=i.cost.output/1e6*e.output,e.cost.cacheRead=i.cost.cacheRead/1e6*e.cacheRead,e.cost.cacheWrite=i.cost.cacheWrite/1e6*e.cacheWrite,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite,e.cost}function sd(i){return i.reasoning?ls.filter(e=>{let t=i.thinkingLevelMap?.[e];return t===null?!1:e==="xhigh"?t!==void 0:!0}):["off"]}function Ce(i,e){let t=sd(i);if(t.includes(e))return e;let n=ls.indexOf(e);if(n===-1)return t[0]??"off";for(let s=n;s<ls.length;s++){let o=ls[s];if(t.includes(o))return o}for(let s=n-1;s>=0;s--){let o=ls[s];if(t.includes(o))return o}return t[0]??"off"}function dt(i,e){return!i||!e?!1:i.id===e.id&&i.provider===e.provider}var Ma,ls,Ze=te(()=>{"use strict";id();Ma=new Map;for(let[i,e]of Object.entries(nd)){let t=new Map;for(let[n,s]of Object.entries(e))t.set(n,s);Ma.set(i,t)}ls=["off","minimal","low","medium","high","xhigh"]});var cs,de,et=te(()=>{"use strict";cs=class{constructor(e,t){this.isComplete=e;this.extractResult=t;this.queue=[];this.waiting=[];this.done=!1;this.finalResultPromise=new Promise(n=>{this.resolveFinalResult=n})}push(e){if(this.done)return;this.isComplete(e)&&(this.done=!0,this.resolveFinalResult(this.extractResult(e)));let t=this.waiting.shift();t?t({value:e,done:!1}):this.queue.push(e)}end(e){for(this.done=!0,e!==void 0&&this.resolveFinalResult(e);this.waiting.length>0;)this.waiting.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.shift();else{if(this.done)return;{let e=await new Promise(t=>this.waiting.push(t));if(e.done)return;yield e.value}}}result(){return this.finalResultPromise}},de=class extends cs{constructor(){super(e=>e.type==="done"||e.type==="error",e=>{if(e.type==="done")return e.message;if(e.type==="error")return e.error;throw new Error("Unexpected event type for final result")})}}});import{parse as od}from"partial-json";function m0(i){let e=i.codePointAt(0);return e!==void 0&&e>=0&&e<=31}function h0(i){switch(i){case"\b":return"\\b";case"\f":return"\\f";case`
|
|
2
|
+
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return`\\u${i.codePointAt(0)?.toString(16).padStart(4,"0")??"0000"}`}}function rd(i){let e="",t=!1;for(let n=0;n<i.length;n++){let s=i[n];if(!t){e+=s,s==='"'&&(t=!0);continue}if(s==='"'){e+=s,t=!1;continue}if(s==="\\"){let o=i[n+1];if(o===void 0){e+="\\\\";continue}if(o==="u"){let r=i.slice(n+2,n+6);if(/^[0-9a-fA-F]{4}$/.test(r)){e+=`\\u${r}`,n+=5;continue}}if(u0.has(o)){e+=`\\${o}`,n+=1;continue}e+="\\\\";continue}e+=m0(s)?h0(s):s}return e}function Ia(i){try{return JSON.parse(i)}catch(e){let t=rd(i);if(t!==i)return JSON.parse(t);throw e}}function Pe(i){if(!i||i.trim()==="")return{};try{return Ia(i)}catch{try{return od(i)??{}}catch{try{return od(rd(i))??{}}catch{return{}}}}}var u0,jn=te(()=>{"use strict";u0=new Set(['"',"\\","/","b","f","n","r","t","u"])});function So(i){return i==="cloudflare-workers-ai"||i==="cloudflare-ai-gateway"}function qn(i){let e=i.baseUrl;return e.includes("{")?e.replace(/\{([A-Z_][A-Z0-9_]*)\}/g,(n,s)=>{let o=process.env[s];if(!o)throw new Error(`${s} is required for provider ${i.provider} but is not set.`);return o}):e}var To=te(()=>{"use strict"});function g0(i){let e=i[i.length-1];return e&&e.role!=="user"?"agent":"user"}function Vn(i){return i.some(e=>e.role==="user"&&Array.isArray(e.content)?e.content.some(t=>t.type==="image"):e.role==="toolResult"&&Array.isArray(e.content)?e.content.some(t=>t.type==="image"):!1)}function Qn(i){let e={"X-Initiator":g0(i.messages),"Openai-Intent":"conversation-edits"};return i.hasImages&&(e["Copilot-Vision-Request"]="true"),e}var Co=te(()=>{"use strict"});function Me(i,e,t){return{temperature:e?.temperature,maxTokens:e?.maxTokens??(i.maxTokens>0?Math.min(i.maxTokens,32e3):void 0),signal:e?.signal,apiKey:t||e?.apiKey,transport:e?.transport,cacheRetention:e?.cacheRetention,sessionId:e?.sessionId,headers:e?.headers,onPayload:e?.onPayload,onResponse:e?.onResponse,timeoutMs:e?.timeoutMs,maxRetries:e?.maxRetries,maxRetryDelayMs:e?.maxRetryDelayMs,metadata:e?.metadata}}function f0(i){return i==="xhigh"?"high":i}function ad(i,e,t,n){let o={...{minimal:1024,low:2048,medium:8192,high:16384},...n},r=1024,a=f0(t),l=o[a],c=Math.min(i+l,e);return c<=l&&(l=Math.max(0,c-r)),{maxTokens:c,thinkingBudget:l}}var Ot=te(()=>{"use strict"});function ld(i,e){let t=[],n=!1;for(let s of i){if(s.type==="image"){n||t.push({type:"text",text:e}),n=!0;continue}t.push(s),n=s.text===e}return t}function v0(i,e){return e.input.includes("image")?i:i.map(t=>t.role==="user"&&Array.isArray(t.content)?{...t,content:ld(t.content,x0)}:t.role==="toolResult"?{...t,content:ld(t.content,b0)}:t)}function wt(i,e,t){let n=new Map,o=v0(i,e).map(d=>{if(d.role==="user")return d;if(d.role==="toolResult"){let p=n.get(d.toolCallId);return p&&p!==d.toolCallId?{...d,toolCallId:p}:d}if(d.role==="assistant"){let p=d,u=p.provider===e.provider&&p.api===e.api&&p.model===e.id,h=p.content.flatMap(m=>{if(m.type==="thinking")return m.redacted?u?m:[]:u&&m.thinkingSignature?m:!m.thinking||m.thinking.trim()===""?[]:u?m:{type:"text",text:m.thinking};if(m.type==="text")return u?m:{type:"text",text:m.text};if(m.type==="toolCall"){let g=m,x=g;if(!u&&g.thoughtSignature&&(x={...g},delete x.thoughtSignature),!u&&t){let b=t(g.id,e,p);b!==g.id&&(n.set(g.id,b),x={...x,id:b})}return x}return m});return{...p,content:h}}return d}),r=[],a=[],l=new Set,c=()=>{if(a.length>0){for(let d of a)l.has(d.id)||r.push({role:"toolResult",toolCallId:d.id,toolName:d.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});a=[],l=new Set}};for(let d=0;d<o.length;d++){let p=o[d];if(p.role==="assistant"){c();let u=p;if(u.stopReason==="error"||u.stopReason==="aborted")continue;let h=u.content.filter(m=>m.type==="toolCall");h.length>0&&(a=h,l=new Set),r.push(p)}else p.role==="toolResult"?(l.add(p.toolCallId),r.push(p)):(p.role==="user"&&c(),r.push(p))}return c(),r}var x0,b0,Jn=te(()=>{"use strict";x0="(image omitted: model does not support images)",b0="(tool image omitted: model does not support images)"});var ud={};Et(ud,{streamAnthropic:()=>Io,streamSimpleAnthropic:()=>L0});import Mo from"@anthropic-ai/sdk";function y0(i){return i||(typeof process<"u"&&process.env.PI_CACHE_RETENTION==="long"?"long":"short")}function w0(i,e){let t=y0(e);if(t==="none")return{retention:t};let n=t==="long"&&Pa(i).supportsLongCacheRetention?"1h":void 0;return{retention:t,cacheControl:{type:"ephemeral",...n&&{ttl:n}}}}function cd(i){if(!i.some(s=>s.type==="image"))return H(i.map(s=>s.text).join(`
|
|
3
|
+
`));let t=i.map(s=>s.type==="text"?{type:"text",text:H(s.text)}:{type:"image",source:{type:"base64",media_type:s.mimeType,data:s.data}});return t.some(s=>s.type==="text")||t.unshift({type:"text",text:"(see attached image)"}),t}function Pa(i){return{supportsEagerToolInputStreaming:i.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:i.compat?.supportsLongCacheRetention??!0}}function Ro(...i){let e={};for(let t of i)t&&Object.assign(e,t);return e}function dd(i){if(!i.event&&i.data.length===0)return null;let e={event:i.event,data:i.data.join(`
|
|
4
|
+
`),raw:[...i.raw]};return i.event=null,i.data=[],i.raw=[],e}function Aa(i,e){if(i==="")return dd(e);if(e.raw.push(i),i.startsWith(":"))return null;let t=i.indexOf(":"),n=t===-1?i:i.slice(0,t),s=t===-1?"":i.slice(t+1);return s.startsWith(" ")&&(s=s.slice(1)),n==="event"?e.event=s:n==="data"&&e.data.push(s),null}function I0(i){let e=i.indexOf("\r"),t=i.indexOf(`
|
|
5
|
+
`);return e===-1?t:t===-1?e:Math.min(e,t)}function Eo(i){let e=I0(i);if(e===-1)return null;let t=e+1;return i[e]==="\r"&&i[t]===`
|
|
6
|
+
`&&(t+=1),{line:i.slice(0,e),rest:i.slice(t)}}async function*A0(i,e){let t=i.getReader(),n=new TextDecoder,s={event:null,data:[],raw:[]},o="";try{for(;;){if(e?.aborted)throw new Error("Request was aborted");let{value:l,done:c}=await t.read();if(c)break;o+=n.decode(l,{stream:!0});let d=Eo(o);for(;d;){o=d.rest;let p=Aa(d.line,s);p&&(yield p),d=Eo(o)}}o+=n.decode();let r=Eo(o);for(;r;){o=r.rest;let l=Aa(r.line,s);l&&(yield l),r=Eo(o)}if(o.length>0){let l=Aa(o,s);l&&(yield l)}let a=dd(s);a&&(yield a)}finally{t.releaseLock()}}async function*P0(i,e){if(!i.body)throw new Error("Attempted to iterate over an Anthropic response with no body");let t=!1,n=!1;for await(let s of A0(i.body,e)){if(s.event==="error")throw new Error(s.data);if(E0.has(s.event??""))try{let o=Ia(s.data);o.type==="message_start"?t=!0:o.type==="message_stop"&&(n=!0),yield o}catch(o){let r=o instanceof Error?o.message:String(o);throw new Error(`Could not parse Anthropic SSE event ${s.event}: ${r}; data=${s.data}; raw=${s.raw.join("\\n")}`)}}if(t&&!n)throw new Error("Anthropic stream ended before message_stop")}function _a(i){return i.includes("opus-4-6")||i.includes("opus-4.6")||i.includes("opus-4-7")||i.includes("opus-4.7")||i.includes("sonnet-4-6")||i.includes("sonnet-4.6")}function _0(i,e){let t=e?i.thinkingLevelMap?.[e]:void 0;if(typeof t=="string")return t;switch(e){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"high"}}function W0(i){return i.includes("sk-ant-oat")}function O0(i,e,t,n,s,o){let r=t&&!_a(i.id),a=[];return n&&a.push(M0),r&&a.push(R0),i.provider==="cloudflare-ai-gateway"?{client:new Mo({apiKey:null,authToken:null,baseURL:qn(i),dangerouslyAllowBrowser:!0,defaultHeaders:Ro({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","cf-aig-authorization":`Bearer ${e}`,"x-api-key":null,Authorization:null,...a.length>0?{"anthropic-beta":a.join(",")}:{}},i.headers,s)}),isOAuthToken:!1}:i.provider==="github-copilot"?{client:new Mo({apiKey:null,authToken:e,baseURL:i.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Ro({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...a.length>0?{"anthropic-beta":a.join(",")}:{}},i.headers,o,s)}),isOAuthToken:!1}:W0(e)?{client:new Mo({apiKey:null,authToken:e,baseURL:i.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Ro({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":["claude-code-20250219","oauth-2025-04-20",...a].join(","),"user-agent":`claude-cli/${k0}`,"x-app":"cli"},i.headers,s)}),isOAuthToken:!0}:{client:new Mo({apiKey:e,baseURL:i.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Ro({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...a.length>0?{"anthropic-beta":a.join(",")}:{}},i.headers,s)}),isOAuthToken:!1}}function U0(i,e,t,n){let{cacheControl:s}=w0(i,n?.cacheRetention),o={model:i.id,messages:F0(e.messages,i,t,s),max_tokens:n?.maxTokens||i.maxTokens/3|0,stream:!0};if(t?(o.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...s?{cache_control:s}:{}}],e.systemPrompt&&o.system.push({type:"text",text:H(e.systemPrompt),...s?{cache_control:s}:{}})):e.systemPrompt&&(o.system=[{type:"text",text:H(e.systemPrompt),...s?{cache_control:s}:{}}]),n?.temperature!==void 0&&!n?.thinkingEnabled&&(o.temperature=n.temperature),e.tools&&e.tools.length>0&&(o.tools=B0(e.tools,t,Pa(i).supportsEagerToolInputStreaming,s)),i.reasoning)if(n?.thinkingEnabled){let r=n.thinkingDisplay??"summarized";_a(i.id)?(o.thinking={type:"adaptive",display:r},n.effort&&(o.output_config=n.effort==="xhigh"?{effort:n.effort}:{effort:n.effort})):o.thinking={type:"enabled",budget_tokens:n.thinkingBudgetTokens||1024,display:r}}else n?.thinkingEnabled===!1&&(o.thinking={type:"disabled"});if(n?.metadata){let r=n.metadata.user_id;typeof r=="string"&&(o.metadata={user_id:r})}return n?.toolChoice&&(typeof n.toolChoice=="string"?o.tool_choice={type:n.toolChoice}:o.tool_choice=n.toolChoice),o}function D0(i){return i.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function F0(i,e,t,n){let s=[],o=wt(i,e,D0);for(let r=0;r<o.length;r++){let a=o[r];if(a.role==="user")if(typeof a.content=="string")a.content.trim().length>0&&s.push({role:"user",content:H(a.content)});else{let c=a.content.map(d=>d.type==="text"?{type:"text",text:H(d.text)}:{type:"image",source:{type:"base64",media_type:d.mimeType,data:d.data}}).filter(d=>d.type==="text"?d.text.trim().length>0:!0);if(c.length===0)continue;s.push({role:"user",content:c})}else if(a.role==="assistant"){let l=[];for(let c of a.content)if(c.type==="text"){if(c.text.trim().length===0)continue;l.push({type:"text",text:H(c.text)})}else if(c.type==="thinking"){if(c.redacted){l.push({type:"redacted_thinking",data:c.thinkingSignature});continue}if(c.thinking.trim().length===0)continue;!c.thinkingSignature||c.thinkingSignature.trim().length===0?l.push({type:"text",text:H(c.thinking)}):l.push({type:"thinking",thinking:H(c.thinking),signature:c.thinkingSignature})}else c.type==="toolCall"&&l.push({type:"tool_use",id:c.id,name:t?pd(c.name):c.name,input:c.arguments??{}});if(l.length===0)continue;s.push({role:"assistant",content:l})}else if(a.role==="toolResult"){let l=[];l.push({type:"tool_result",tool_use_id:a.toolCallId,content:cd(a.content),is_error:a.isError});let c=r+1;for(;c<o.length&&o[c].role==="toolResult";){let d=o[c];l.push({type:"tool_result",tool_use_id:d.toolCallId,content:cd(d.content),is_error:d.isError}),c++}r=c-1,s.push({role:"user",content:l})}}if(n&&s.length>0){let r=s[s.length-1];if(r.role==="user")if(Array.isArray(r.content)){let a=r.content[r.content.length-1];a&&(a.type==="text"||a.type==="image"||a.type==="tool_result")&&(a.cache_control=n)}else typeof r.content=="string"&&(r.content=[{type:"text",text:r.content,cache_control:n}])}return s}function $0(i,e){return!!e.tools?.length&&!Pa(i).supportsEagerToolInputStreaming}function B0(i,e,t,n){return i?i.map((s,o)=>{let r=s.parameters;return{name:e?pd(s.name):s.name,description:s.description,...t?{eager_input_streaming:!0}:{},input_schema:{type:"object",properties:r.properties??{},required:r.required??[]},...n&&o===i.length-1?{cache_control:n}:{}}}):[]}function N0(i){switch(i){case"end_turn":return"stop";case"max_tokens":return"length";case"tool_use":return"toolUse";case"refusal":return"error";case"pause_turn":return"stop";case"stop_sequence":return"stop";case"sensitive":return"error";default:throw new Error(`Unhandled stop reason: ${i}`)}}var k0,S0,T0,pd,C0,M0,R0,E0,Io,L0,md=te(()=>{"use strict";pt();Ze();et();gn();jn();Wt();To();Co();Ot();Jn();k0="2.1.75",S0=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],T0=new Map(S0.map(i=>[i.toLowerCase(),i])),pd=i=>T0.get(i.toLowerCase())??i,C0=(i,e)=>{if(e&&e.length>0){let t=i.toLowerCase(),n=e.find(s=>s.name.toLowerCase()===t);if(n)return n.name}return i};M0="fine-grained-tool-streaming-2025-05-14",R0="interleaved-thinking-2025-05-14";E0=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);Io=(i,e,t)=>{let n=new de;return(async()=>{let s={role:"assistant",content:[],api:i.api,provider:i.provider,model:i.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o,r;if(t?.client)o=t.client,r=!1;else{let u=t?.apiKey??ne(i.provider)??"",h;if(i.provider==="github-copilot"){let g=Vn(e.messages);h=Qn({messages:e.messages,hasImages:g})}let m=O0(i,u,t?.interleavedThinking??!0,$0(i,e),t?.headers,h);o=m.client,r=m.isOAuthToken}let a=U0(i,e,r,t),l=await t?.onPayload?.(a,i);l!==void 0&&(a=l);let c={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},...t?.maxRetries!==void 0?{maxRetries:t.maxRetries}:{}},d=await o.messages.create({...a,stream:!0},c).asResponse();await t?.onResponse?.({status:d.status,headers:He(d.headers)},i),n.push({type:"start",partial:s});let p=s.content;for await(let u of P0(d,t?.signal))if(u.type==="message_start")s.responseId=u.message.id,s.usage.input=u.message.usage.input_tokens||0,s.usage.output=u.message.usage.output_tokens||0,s.usage.cacheRead=u.message.usage.cache_read_input_tokens||0,s.usage.cacheWrite=u.message.usage.cache_creation_input_tokens||0,s.usage.totalTokens=s.usage.input+s.usage.output+s.usage.cacheRead+s.usage.cacheWrite,je(i,s.usage);else if(u.type==="content_block_start"){if(u.content_block.type==="text"){let h={type:"text",text:"",index:u.index};s.content.push(h),n.push({type:"text_start",contentIndex:s.content.length-1,partial:s})}else if(u.content_block.type==="thinking"){let h={type:"thinking",thinking:"",thinkingSignature:"",index:u.index};s.content.push(h),n.push({type:"thinking_start",contentIndex:s.content.length-1,partial:s})}else if(u.content_block.type==="redacted_thinking"){let h={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:u.content_block.data,redacted:!0,index:u.index};s.content.push(h),n.push({type:"thinking_start",contentIndex:s.content.length-1,partial:s})}else if(u.content_block.type==="tool_use"){let h={type:"toolCall",id:u.content_block.id,name:r?C0(u.content_block.name,e.tools):u.content_block.name,arguments:u.content_block.input??{},partialJson:"",index:u.index};s.content.push(h),n.push({type:"toolcall_start",contentIndex:s.content.length-1,partial:s})}}else if(u.type==="content_block_delta"){if(u.delta.type==="text_delta"){let h=p.findIndex(g=>g.index===u.index),m=p[h];m&&m.type==="text"&&(m.text+=u.delta.text,n.push({type:"text_delta",contentIndex:h,delta:u.delta.text,partial:s}))}else if(u.delta.type==="thinking_delta"){let h=p.findIndex(g=>g.index===u.index),m=p[h];m&&m.type==="thinking"&&(m.thinking+=u.delta.thinking,n.push({type:"thinking_delta",contentIndex:h,delta:u.delta.thinking,partial:s}))}else if(u.delta.type==="input_json_delta"){let h=p.findIndex(g=>g.index===u.index),m=p[h];m&&m.type==="toolCall"&&(m.partialJson+=u.delta.partial_json,m.arguments=Pe(m.partialJson),n.push({type:"toolcall_delta",contentIndex:h,delta:u.delta.partial_json,partial:s}))}else if(u.delta.type==="signature_delta"){let h=p.findIndex(g=>g.index===u.index),m=p[h];m&&m.type==="thinking"&&(m.thinkingSignature=m.thinkingSignature||"",m.thinkingSignature+=u.delta.signature)}}else if(u.type==="content_block_stop"){let h=p.findIndex(g=>g.index===u.index),m=p[h];m&&(delete m.index,m.type==="text"?n.push({type:"text_end",contentIndex:h,content:m.text,partial:s}):m.type==="thinking"?n.push({type:"thinking_end",contentIndex:h,content:m.thinking,partial:s}):m.type==="toolCall"&&(m.arguments=Pe(m.partialJson),delete m.partialJson,n.push({type:"toolcall_end",contentIndex:h,toolCall:m,partial:s})))}else u.type==="message_delta"&&(u.delta.stop_reason&&(s.stopReason=N0(u.delta.stop_reason)),u.usage.input_tokens!=null&&(s.usage.input=u.usage.input_tokens),u.usage.output_tokens!=null&&(s.usage.output=u.usage.output_tokens),u.usage.cache_read_input_tokens!=null&&(s.usage.cacheRead=u.usage.cache_read_input_tokens),u.usage.cache_creation_input_tokens!=null&&(s.usage.cacheWrite=u.usage.cache_creation_input_tokens),s.usage.totalTokens=s.usage.input+s.usage.output+s.usage.cacheRead+s.usage.cacheWrite,je(i,s.usage));if(t?.signal?.aborted)throw new Error("Request was aborted");if(s.stopReason==="aborted"||s.stopReason==="error")throw new Error("An unknown error occurred");n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let r of s.content)delete r.index,delete r.partialJson;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=o instanceof Error?o.message:JSON.stringify(o),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n};L0=(i,e,t)=>{let n=t?.apiKey||ne(i.provider);if(!n)throw new Error(`No API key for provider: ${i.provider}`);let s=Me(i,t,n);if(!t?.reasoning)return Io(i,e,{...s,thinkingEnabled:!1});if(_a(i.id)){let r=_0(i,t.reasoning);return Io(i,e,{...s,thinkingEnabled:!0,effort:r})}let o=ad(s.maxTokens||0,i.maxTokens,t.reasoning,t.thinkingBudgets);return Io(i,e,{...s,maxTokens:o.maxTokens,thinkingEnabled:!0,thinkingBudgetTokens:o.thinkingBudget})}});function ps(i){let e=3735928559,t=1103547991;for(let n=0;n<i.length;n++){let s=i.charCodeAt(n);e=Math.imul(e^s,2654435761),t=Math.imul(t^s,1597334677)}return e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),(t>>>0).toString(36)+(e>>>0).toString(36)}var La=te(()=>{"use strict"});function G0(i,e){let t={v:1,id:i};return e&&(t.phase=e),JSON.stringify(t)}function K0(i){if(i){if(i.startsWith("{"))try{let e=JSON.parse(i);if(e.v===1&&typeof e.id=="string")return e.phase==="commentary"||e.phase==="final_answer"?{id:e.id,phase:e.phase}:{id:e.id}}catch{}return{id:i}}}function fn(i,e,t,n){let s=[],o=p=>{let u=p.replace(/[^a-zA-Z0-9_-]/g,"_");return(u.length>64?u.slice(0,64):u).replace(/_+$/,"")},r=p=>{let u=`fc_${ps(p)}`;return u.length>64?u.slice(0,64):u},a=(p,u,h)=>{if(!t.has(i.provider)||!p.includes("|"))return o(p);let[m,g]=p.split("|"),x=o(m),v=h.provider!==i.provider||h.api!==i.api?r(g):o(g);return v.startsWith("fc_")||(v=o(`fc_${v}`)),`${x}|${v}`},l=wt(e.messages,i,a);if((n?.includeSystemPrompt??!0)&&e.systemPrompt){let p=i.reasoning?"developer":"system";s.push({role:p,content:H(e.systemPrompt)})}let d=0;for(let p of l){if(p.role==="user")if(typeof p.content=="string")s.push({role:"user",content:[{type:"input_text",text:H(p.content)}]});else{let u=p.content.map(h=>h.type==="text"?{type:"input_text",text:H(h.text)}:{type:"input_image",detail:"auto",image_url:`data:${h.mimeType};base64,${h.data}`});if(u.length===0)continue;s.push({role:"user",content:u})}else if(p.role==="assistant"){let u=[],h=p,m=h.model!==i.id&&h.provider===i.provider&&h.api===i.api;for(let g of p.content)if(g.type==="thinking"){if(g.thinkingSignature){let x=JSON.parse(g.thinkingSignature);u.push(x)}}else if(g.type==="text"){let x=g,b=K0(x.textSignature),v=b?.id;v?v.length>64&&(v=`msg_${ps(v)}`):v=`msg_${d}`,u.push({type:"message",role:"assistant",content:[{type:"output_text",text:H(x.text),annotations:[]}],status:"completed",id:v,phase:b?.phase})}else if(g.type==="toolCall"){let x=g,[b,v]=x.id.split("|"),w=v;m&&w?.startsWith("fc_")&&(w=void 0),u.push({type:"function_call",id:w,call_id:b,name:x.name,arguments:JSON.stringify(x.arguments)})}if(u.length===0)continue;s.push(...u)}else if(p.role==="toolResult"){let u=p.content.filter(b=>b.type==="text").map(b=>b.text).join(`
|
|
7
|
+
`),h=p.content.some(b=>b.type==="image"),m=u.length>0,[g]=p.toolCallId.split("|"),x;if(h&&i.input.includes("image")){let b=[];m&&b.push({type:"input_text",text:H(u)});for(let v of p.content)v.type==="image"&&b.push({type:"input_image",detail:"auto",image_url:`data:${v.mimeType};base64,${v.data}`});x=b}else x=H(m?u:"(see attached image)");s.push({type:"function_call_output",call_id:g,output:x})}d++}return s}function Yn(i,e){let t=e?.strict===void 0?!1:e.strict;return i.map(n=>({type:"function",name:n.name,description:n.description,parameters:n.parameters,strict:t}))}async function xn(i,e,t,n,s){let o=null,r=null,a=e.content,l=()=>a.length-1;for await(let c of i)if(c.type==="response.created")e.responseId=c.response.id;else if(c.type==="response.output_item.added"){let d=c.item;d.type==="reasoning"?(o=d,r={type:"thinking",thinking:""},e.content.push(r),t.push({type:"thinking_start",contentIndex:l(),partial:e})):d.type==="message"?(o=d,r={type:"text",text:""},e.content.push(r),t.push({type:"text_start",contentIndex:l(),partial:e})):d.type==="function_call"&&(o=d,r={type:"toolCall",id:`${d.call_id}|${d.id}`,name:d.name,arguments:{},partialJson:d.arguments||""},e.content.push(r),t.push({type:"toolcall_start",contentIndex:l(),partial:e}))}else if(c.type==="response.reasoning_summary_part.added")o&&o.type==="reasoning"&&(o.summary=o.summary||[],o.summary.push(c.part));else if(c.type==="response.reasoning_summary_text.delta"){if(o?.type==="reasoning"&&r?.type==="thinking"){o.summary=o.summary||[];let d=o.summary[o.summary.length-1];d&&(r.thinking+=c.delta,d.text+=c.delta,t.push({type:"thinking_delta",contentIndex:l(),delta:c.delta,partial:e}))}}else if(c.type==="response.reasoning_summary_part.done"){if(o?.type==="reasoning"&&r?.type==="thinking"){o.summary=o.summary||[];let d=o.summary[o.summary.length-1];d&&(r.thinking+=`
|
|
8
|
+
|
|
9
|
+
`,d.text+=`
|
|
10
|
+
|
|
11
|
+
`,t.push({type:"thinking_delta",contentIndex:l(),delta:`
|
|
12
|
+
|
|
13
|
+
`,partial:e}))}}else if(c.type==="response.reasoning_text.delta")o?.type==="reasoning"&&r?.type==="thinking"&&(r.thinking+=c.delta,t.push({type:"thinking_delta",contentIndex:l(),delta:c.delta,partial:e}));else if(c.type==="response.content_part.added")o?.type==="message"&&(o.content=o.content||[],(c.part.type==="output_text"||c.part.type==="refusal")&&o.content.push(c.part));else if(c.type==="response.output_text.delta"){if(o?.type==="message"&&r?.type==="text"){if(!o.content||o.content.length===0)continue;let d=o.content[o.content.length-1];d?.type==="output_text"&&(r.text+=c.delta,d.text+=c.delta,t.push({type:"text_delta",contentIndex:l(),delta:c.delta,partial:e}))}}else if(c.type==="response.refusal.delta"){if(o?.type==="message"&&r?.type==="text"){if(!o.content||o.content.length===0)continue;let d=o.content[o.content.length-1];d?.type==="refusal"&&(r.text+=c.delta,d.refusal+=c.delta,t.push({type:"text_delta",contentIndex:l(),delta:c.delta,partial:e}))}}else if(c.type==="response.function_call_arguments.delta")o?.type==="function_call"&&r?.type==="toolCall"&&(r.partialJson+=c.delta,r.arguments=Pe(r.partialJson),t.push({type:"toolcall_delta",contentIndex:l(),delta:c.delta,partial:e}));else if(c.type==="response.function_call_arguments.done"){if(o?.type==="function_call"&&r?.type==="toolCall"){let d=r.partialJson;if(r.partialJson=c.arguments,r.arguments=Pe(r.partialJson),c.arguments.startsWith(d)){let p=c.arguments.slice(d.length);p.length>0&&t.push({type:"toolcall_delta",contentIndex:l(),delta:p,partial:e})}}}else if(c.type==="response.output_item.done"){let d=c.item;if(d.type==="reasoning"&&r?.type==="thinking"){let p=d.summary?.map(h=>h.text).join(`
|
|
14
|
+
|
|
15
|
+
`)||"",u=d.content?.map(h=>h.text).join(`
|
|
16
|
+
|
|
17
|
+
`)||"";r.thinking=p||u||r.thinking,r.thinkingSignature=JSON.stringify(d),t.push({type:"thinking_end",contentIndex:l(),content:r.thinking,partial:e}),r=null}else if(d.type==="message"&&r?.type==="text")r.text=d.content.map(p=>p.type==="output_text"?p.text:p.refusal).join(""),r.textSignature=G0(d.id,d.phase??void 0),t.push({type:"text_end",contentIndex:l(),content:r.text,partial:e}),r=null;else if(d.type==="function_call"){let p=r?.type==="toolCall"&&r.partialJson?Pe(r.partialJson):Pe(d.arguments||"{}"),u;r?.type==="toolCall"?(r.arguments=p,delete r.partialJson,u=r):u={type:"toolCall",id:`${d.call_id}|${d.id}`,name:d.name,arguments:p},r=null,t.push({type:"toolcall_end",contentIndex:l(),toolCall:u,partial:e})}}else if(c.type==="response.completed"){let d=c.response;if(d?.id&&(e.responseId=d.id),d?.usage){let p=d.usage.input_tokens_details?.cached_tokens||0;e.usage={input:(d.usage.input_tokens||0)-p,output:d.usage.output_tokens||0,cacheRead:p,cacheWrite:0,totalTokens:d.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(je(n,e.usage),s?.applyServiceTierPricing){let p=s.resolveServiceTier?s.resolveServiceTier(d?.service_tier,s.serviceTier):d?.service_tier??s.serviceTier;s.applyServiceTierPricing(e.usage,p)}e.stopReason=z0(d?.status),e.content.some(p=>p.type==="toolCall")&&e.stopReason==="stop"&&(e.stopReason="toolUse")}else{if(c.type==="error")throw new Error(`Error Code ${c.code}: ${c.message}`||"Unknown error");if(c.type==="response.failed"){let d=c.response?.error,p=c.response?.incomplete_details,u=d?`${d.code||"unknown"}: ${d.message||"no message"}`:p?.reason?`incomplete: ${p.reason}`:"Unknown error (no error details in response)";throw new Error(u)}}}function z0(i){if(!i)return"stop";switch(i){case"completed":return"stop";case"incomplete":return"length";case"failed":case"cancelled":return"error";case"in_progress":case"queued":return"stop";default:{let e=i;throw new Error(`Unhandled stop reason: ${e}`)}}}var Ao=te(()=>{"use strict";Ze();La();jn();Wt();Jn()});var gd={};Et(gd,{streamAzureOpenAIResponses:()=>hd,streamSimpleAzureOpenAIResponses:()=>J0});import{AzureOpenAI as H0}from"openai";function V0(i){let e=new Map;if(!i)return e;for(let t of i.split(",")){let n=t.trim();if(!n)continue;let[s,o]=n.split("=",2);!s||!o||e.set(s.trim(),o.trim())}return e}function Q0(i,e){return e?.azureDeploymentName?e.azureDeploymentName:V0(process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(i.id)||i.id}function Y0(i){let e=i.trim().replace(/\/+$/,""),t;try{t=new URL(e)}catch{throw new Error(`Invalid Azure OpenAI base URL: ${i}`)}let n=t.hostname.endsWith(".openai.azure.com")||t.hostname.endsWith(".cognitiveservices.azure.com"),s=t.pathname.replace(/\/+$/,"");return n&&(s===""||s==="/"||s==="/openai")&&(t.pathname="/openai/v1",t.search=""),t.toString().replace(/\/+$/,"")}function X0(i){return`https://${i}.openai.azure.com/openai/v1`}function Z0(i,e){let t=e?.azureApiVersion||process.env.AZURE_OPENAI_API_VERSION||j0,n=e?.azureBaseUrl?.trim()||process.env.AZURE_OPENAI_BASE_URL?.trim()||void 0,s=e?.azureResourceName||process.env.AZURE_OPENAI_RESOURCE_NAME,o=n;if(!o&&s&&(o=X0(s)),!o&&i.baseUrl&&(o=i.baseUrl),!o)throw new Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.");return{baseUrl:Y0(o),apiVersion:t}}function ex(i,e,t){if(!e){if(!process.env.AZURE_OPENAI_API_KEY)throw new Error("Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.");e=process.env.AZURE_OPENAI_API_KEY}let n={...i.headers};t?.headers&&Object.assign(n,t.headers);let{baseUrl:s,apiVersion:o}=Z0(i,t);return new H0({apiKey:e,apiVersion:o,dangerouslyAllowBrowser:!0,defaultHeaders:n,baseURL:s})}function tx(i,e,t,n){let s=fn(i,e,q0),o={model:n,input:s,stream:!0,prompt_cache_key:t?.sessionId};if(t?.maxTokens&&(o.max_output_tokens=t?.maxTokens),t?.temperature!==void 0&&(o.temperature=t?.temperature),e.tools&&e.tools.length>0&&(o.tools=Yn(e.tools)),i.reasoning)if(t?.reasoningEffort||t?.reasoningSummary){let r=t?.reasoningEffort?i.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort:"medium";o.reasoning={effort:r,summary:t?.reasoningSummary||"auto"},o.include=["reasoning.encrypted_content"]}else i.thinkingLevelMap?.off!==null&&(o.reasoning={effort:i.thinkingLevelMap?.off??"none"});return o}var j0,q0,hd,J0,fd=te(()=>{"use strict";pt();Ze();et();gn();Ao();Ot();j0="v1",q0=new Set(["openai","openai-codex","opencode","azure-openai-responses"]);hd=(i,e,t)=>{let n=new de;return(async()=>{let s=Q0(i,t),o={role:"assistant",content:[],api:"azure-openai-responses",provider:i.provider,model:i.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let r=t?.apiKey||ne(i.provider)||"",a=ex(i,r,t),l=tx(i,e,t,s),c=await t?.onPayload?.(l,i);c!==void 0&&(l=c);let d={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},...t?.maxRetries!==void 0?{maxRetries:t.maxRetries}:{}},{data:p,response:u}=await a.responses.create(l,d).withResponse();if(await t?.onResponse?.({status:u.status,headers:He(u.headers)},i),n.push({type:"start",partial:o}),await xn(p,o,n,i),t?.signal?.aborted)throw new Error("Request was aborted");if(o.stopReason==="aborted"||o.stopReason==="error")throw new Error("An unknown error occurred");n.push({type:"done",reason:o.stopReason,message:o}),n.end()}catch(r){for(let a of o.content)delete a.index,delete a.partialJson;o.stopReason=t?.signal?.aborted?"aborted":"error",o.errorMessage=r instanceof Error?r.message:JSON.stringify(r),n.push({type:"error",reason:o.stopReason,error:o}),n.end()}})(),n},J0=(i,e,t)=>{let n=t?.apiKey||ne(i.provider);if(!n)throw new Error(`No API key for provider: ${i.provider}`);let s=Me(i,t,n),o=t?.reasoning?Ce(i,t.reasoning):void 0;return hd(i,e,{...s,reasoningEffort:o==="off"?void 0:o})}});import{FinishReason as ye,FunctionCallingConfigMode as Po}from"@google/genai";function _o(i){return i.thought===!0}function Xn(i,e){return typeof e=="string"&&e.length>0?e:i}function ix(i){return!i||i.length%4!==0?!1:nx.test(i)}function Wa(i,e){return i&&ix(e)?e:void 0}function Oa(i){return i.startsWith("claude-")||i.startsWith("gpt-oss-")}function sx(i){let e=i.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(e)return Number.parseInt(e[1],10)}function ox(i){let e=sx(i);return e!==void 0?e>=3:!0}function Lo(i,e){let t=[],n=o=>Oa(i.id)?o.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64):o,s=wt(e.messages,i,n);for(let o of s)if(o.role==="user")if(typeof o.content=="string")t.push({role:"user",parts:[{text:H(o.content)}]});else{let r=o.content.map(a=>a.type==="text"?{text:H(a.text)}:{inlineData:{mimeType:a.mimeType,data:a.data}});if(r.length===0)continue;t.push({role:"user",parts:r})}else if(o.role==="assistant"){let r=[],a=o.provider===i.provider&&o.model===i.id;for(let l of o.content)if(l.type==="text"){if(!l.text||l.text.trim()==="")continue;let c=Wa(a,l.textSignature);r.push({text:H(l.text),...c&&{thoughtSignature:c}})}else if(l.type==="thinking"){if(!l.thinking||l.thinking.trim()==="")continue;if(a){let c=Wa(a,l.thinkingSignature);r.push({thought:!0,text:H(l.thinking),...c&&{thoughtSignature:c}})}else r.push({text:H(l.thinking)})}else if(l.type==="toolCall"){let c=Wa(a,l.thoughtSignature),d={functionCall:{name:l.name,args:l.arguments??{},...Oa(i.id)?{id:l.id}:{}},...c&&{thoughtSignature:c}};r.push(d)}if(r.length===0)continue;t.push({role:"model",parts:r})}else if(o.role==="toolResult"){let a=o.content.filter(b=>b.type==="text").map(b=>b.text).join(`
|
|
18
|
+
`),l=i.input.includes("image")?o.content.filter(b=>b.type==="image"):[],c=a.length>0,d=l.length>0,p=ox(i.id),u=c?H(a):d?"(see attached image)":"",h=l.map(b=>({inlineData:{mimeType:b.mimeType,data:b.data}})),m=Oa(i.id),g={functionResponse:{name:o.toolName,response:o.isError?{error:u}:{output:u},...d&&p&&{parts:h},...m?{id:o.toolCallId}:{}}},x=t[t.length-1];x?.role==="user"&&x.parts?.some(b=>b.functionResponse)?x.parts.push(g):t.push({role:"user",parts:[g]}),d&&!p&&t.push({role:"user",parts:[{text:"Tool result image:"},...h]})}return t}function xd(i){if(typeof i!="object"||i===null||Array.isArray(i))return i;let e={};for(let[t,n]of Object.entries(i))rx.has(t)||(e[t]=xd(n));return e}function Wo(i,e=!1){if(i.length!==0)return[{functionDeclarations:i.map(t=>({name:t.name,description:t.description,...e?{parameters:xd(t.parameters)}:{parametersJsonSchema:t.parameters}}))}]}function Oo(i){switch(i){case"auto":return Po.AUTO;case"none":return Po.NONE;case"any":return Po.ANY;default:return Po.AUTO}}function Uo(i){switch(i){case ye.STOP:return"stop";case ye.MAX_TOKENS:return"length";case ye.BLOCKLIST:case ye.PROHIBITED_CONTENT:case ye.SPII:case ye.SAFETY:case ye.IMAGE_SAFETY:case ye.IMAGE_PROHIBITED_CONTENT:case ye.IMAGE_RECITATION:case ye.IMAGE_OTHER:case ye.RECITATION:case ye.FINISH_REASON_UNSPECIFIED:case ye.OTHER:case ye.LANGUAGE:case ye.MALFORMED_FUNCTION_CALL:case ye.UNEXPECTED_TOOL_CALL:case ye.NO_IMAGE:return"error";default:{let e=i;throw new Error(`Unhandled stop reason: ${e}`)}}}var nx,rx,Ua=te(()=>{"use strict";Wt();Jn();nx=/^[A-Za-z0-9+/]+={0,2}$/;rx=new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"])});var vd={};Et(vd,{streamGoogle:()=>Do,streamSimpleGoogle:()=>cx});import{GoogleGenAI as ax}from"@google/genai";function px(i,e,t){let n={};return i.baseUrl&&(n.baseUrl=i.baseUrl,n.apiVersion=""),(i.headers||t)&&(n.headers={...i.headers,...t}),new ax({apiKey:e,httpOptions:Object.keys(n).length>0?n:void 0})}function dx(i,e,t={}){let n=Lo(i,e),s={};t.temperature!==void 0&&(s.temperature=t.temperature),t.maxTokens!==void 0&&(s.maxOutputTokens=t.maxTokens);let o={...Object.keys(s).length>0&&s,...e.systemPrompt&&{systemInstruction:H(e.systemPrompt)},...e.tools&&e.tools.length>0&&{tools:Wo(e.tools)}};if(e.tools&&e.tools.length>0&&t.toolChoice?o.toolConfig={functionCallingConfig:{mode:Oo(t.toolChoice)}}:o.toolConfig=void 0,t.thinking?.enabled&&i.reasoning){let a={includeThoughts:!0};t.thinking.level!==void 0?a.thinkingLevel=t.thinking.level:t.thinking.budgetTokens!==void 0&&(a.thinkingBudget=t.thinking.budgetTokens),o.thinkingConfig=a}else i.reasoning&&t.thinking&&!t.thinking.enabled&&(o.thinkingConfig=ux(i));if(t.signal){if(t.signal.aborted)throw new Error("Request aborted");o.abortSignal=t.signal}return{model:i.id,contents:n,config:o}}function Da(i){return/gemma-?4/.test(i.id.toLowerCase())}function Fa(i){return/gemini-3(?:\.\d+)?-pro/.test(i.id.toLowerCase())}function bd(i){return/gemini-3(?:\.\d+)?-flash/.test(i.id.toLowerCase())}function ux(i){return Fa(i)?{thinkingLevel:"LOW"}:bd(i)?{thinkingLevel:"MINIMAL"}:Da(i)?{thinkingLevel:"MINIMAL"}:{thinkingBudget:0}}function mx(i,e){if(Fa(e))switch(i){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}if(Da(e))switch(i){case"minimal":case"low":return"MINIMAL";case"medium":case"high":return"HIGH"}switch(i){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function hx(i,e,t){return t?.[e]!==void 0?t[e]:i.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[e]:i.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[e]:i.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[e]:-1}var lx,Do,cx,yd=te(()=>{"use strict";pt();Ze();et();Wt();Ua();Ot();lx=0,Do=(i,e,t)=>{let n=new de;return(async()=>{let s={role:"assistant",content:[],api:"google-generative-ai",provider:i.provider,model:i.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o=t?.apiKey||ne(i.provider)||"",r=px(i,o,t?.headers),a=dx(i,e,t),l=await t?.onPayload?.(a,i);l!==void 0&&(a=l);let c=await r.models.generateContentStream(a);n.push({type:"start",partial:s});let d=null,p=s.content,u=()=>p.length-1;for await(let h of c){s.responseId||=h.responseId;let m=h.candidates?.[0];if(m?.content?.parts)for(let g of m.content.parts){if(g.text!==void 0){let x=_o(g);(!d||x&&d.type!=="thinking"||!x&&d.type!=="text")&&(d&&(d.type==="text"?n.push({type:"text_end",contentIndex:p.length-1,content:d.text,partial:s}):n.push({type:"thinking_end",contentIndex:u(),content:d.thinking,partial:s})),x?(d={type:"thinking",thinking:"",thinkingSignature:void 0},s.content.push(d),n.push({type:"thinking_start",contentIndex:u(),partial:s})):(d={type:"text",text:""},s.content.push(d),n.push({type:"text_start",contentIndex:u(),partial:s}))),d.type==="thinking"?(d.thinking+=g.text,d.thinkingSignature=Xn(d.thinkingSignature,g.thoughtSignature),n.push({type:"thinking_delta",contentIndex:u(),delta:g.text,partial:s})):(d.text+=g.text,d.textSignature=Xn(d.textSignature,g.thoughtSignature),n.push({type:"text_delta",contentIndex:u(),delta:g.text,partial:s}))}if(g.functionCall){d&&(d.type==="text"?n.push({type:"text_end",contentIndex:u(),content:d.text,partial:s}):n.push({type:"thinking_end",contentIndex:u(),content:d.thinking,partial:s}),d=null);let x=g.functionCall.id,w={type:"toolCall",id:!x||s.content.some(C=>C.type==="toolCall"&&C.id===x)?`${g.functionCall.name}_${Date.now()}_${++lx}`:x,name:g.functionCall.name||"",arguments:g.functionCall.args??{},...g.thoughtSignature&&{thoughtSignature:g.thoughtSignature}};s.content.push(w),n.push({type:"toolcall_start",contentIndex:u(),partial:s}),n.push({type:"toolcall_delta",contentIndex:u(),delta:JSON.stringify(w.arguments),partial:s}),n.push({type:"toolcall_end",contentIndex:u(),toolCall:w,partial:s})}}m?.finishReason&&(s.stopReason=Uo(m.finishReason),s.content.some(g=>g.type==="toolCall")&&(s.stopReason="toolUse")),h.usageMetadata&&(s.usage={input:(h.usageMetadata.promptTokenCount||0)-(h.usageMetadata.cachedContentTokenCount||0),output:(h.usageMetadata.candidatesTokenCount||0)+(h.usageMetadata.thoughtsTokenCount||0),cacheRead:h.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,totalTokens:h.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},je(i,s.usage))}if(d&&(d.type==="text"?n.push({type:"text_end",contentIndex:u(),content:d.text,partial:s}):n.push({type:"thinking_end",contentIndex:u(),content:d.thinking,partial:s})),t?.signal?.aborted)throw new Error("Request was aborted");if(s.stopReason==="aborted"||s.stopReason==="error")throw new Error("An unknown error occurred");n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let r of s.content)"index"in r&&delete r.index;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=o instanceof Error?o.message:JSON.stringify(o),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},cx=(i,e,t)=>{let n=t?.apiKey||ne(i.provider);if(!n)throw new Error(`No API key for provider: ${i.provider}`);let s=Me(i,t,n);if(!t?.reasoning)return Do(i,e,{...s,thinking:{enabled:!1}});let o=Ce(i,t.reasoning),r=o==="off"?"high":o,a=i;return Fa(a)||bd(a)||Da(a)?Do(i,e,{...s,thinking:{enabled:!0,level:mx(r,a)}}):Do(i,e,{...s,thinking:{enabled:!0,budgetTokens:hx(a,r,t.thinkingBudgets)}})}});var Cd={};Et(Cd,{streamGoogleVertex:()=>Fo,streamSimpleGoogleVertex:()=>vx});import{GoogleGenAI as wd,ResourceScope as gx,ThinkingLevel as bn}from"@google/genai";function yx(i,e,t,n){return new wd({vertexai:!0,project:e,location:t,apiVersion:kd,httpOptions:Sd(i,n)})}function wx(i,e,t){return new wd({vertexai:!0,apiKey:e,apiVersion:kd,httpOptions:Sd(i,t)})}function Sd(i,e){let t={},n=kx(i.baseUrl);return n&&(t.baseUrl=n,t.baseUrlResourceScope=gx.COLLECTION,Sx(n)&&(t.apiVersion="")),(i.headers||e)&&(t.headers={...i.headers,...e}),Object.keys(t).length>0?t:void 0}function kx(i){let e=i.trim();if(!(!e||e.includes("{location}")))return e}function Sx(i){try{return new URL(i).pathname.split("/").some(t=>/^v\d+(?:beta\d*)?$/.test(t))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(i)}}function Tx(i){let e=i?.apiKey?.trim()||process.env.GOOGLE_CLOUD_API_KEY?.trim();if(!(!e||e===fx||Cx(e)))return e}function Cx(i){return/^<[^>]+>$/.test(i)}function Mx(i){let e=i?.project||process.env.GOOGLE_CLOUD_PROJECT||process.env.GCLOUD_PROJECT;if(!e)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return e}function Rx(i){let e=i?.location||process.env.GOOGLE_CLOUD_LOCATION;if(!e)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return e}function Ex(i,e,t={}){let n=Lo(i,e),s={};t.temperature!==void 0&&(s.temperature=t.temperature),t.maxTokens!==void 0&&(s.maxOutputTokens=t.maxTokens);let o={...Object.keys(s).length>0&&s,...e.systemPrompt&&{systemInstruction:H(e.systemPrompt)},...e.tools&&e.tools.length>0&&{tools:Wo(e.tools)}};if(e.tools&&e.tools.length>0&&t.toolChoice?o.toolConfig={functionCallingConfig:{mode:Oo(t.toolChoice)}}:o.toolConfig=void 0,t.thinking?.enabled&&i.reasoning){let a={includeThoughts:!0};t.thinking.level!==void 0?a.thinkingLevel=xx[t.thinking.level]:t.thinking.budgetTokens!==void 0&&(a.thinkingBudget=t.thinking.budgetTokens),o.thinkingConfig=a}else i.reasoning&&t.thinking&&!t.thinking.enabled&&(o.thinkingConfig=Ix(i));if(t.signal){if(t.signal.aborted)throw new Error("Request aborted");o.abortSignal=t.signal}return{model:i.id,contents:n,config:o}}function $a(i){return/gemini-3(?:\.\d+)?-pro/.test(i.id.toLowerCase())}function Td(i){return/gemini-3(?:\.\d+)?-flash/.test(i.id.toLowerCase())}function Ix(i){let e=i;return $a(e)?{thinkingLevel:bn.LOW}:Td(e)?{thinkingLevel:bn.MINIMAL}:{thinkingBudget:0}}function Ax(i,e){if($a(e))switch(i){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(i){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function Px(i,e,t){return t?.[e]!==void 0?t[e]:i.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[e]:i.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[e]:-1}var kd,fx,xx,bx,Fo,vx,Md=te(()=>{"use strict";Ze();et();Wt();Ua();Ot();kd="v1",fx="gcp-vertex-credentials",xx={THINKING_LEVEL_UNSPECIFIED:bn.THINKING_LEVEL_UNSPECIFIED,MINIMAL:bn.MINIMAL,LOW:bn.LOW,MEDIUM:bn.MEDIUM,HIGH:bn.HIGH},bx=0,Fo=(i,e,t)=>{let n=new de;return(async()=>{let s={role:"assistant",content:[],api:"google-vertex",provider:i.provider,model:i.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o=Tx(t),r=o?wx(i,o,t?.headers):yx(i,Mx(t),Rx(t),t?.headers),a=Ex(i,e,t),l=await t?.onPayload?.(a,i);l!==void 0&&(a=l);let c=await r.models.generateContentStream(a);n.push({type:"start",partial:s});let d=null,p=s.content,u=()=>p.length-1;for await(let h of c){s.responseId||=h.responseId;let m=h.candidates?.[0];if(m?.content?.parts)for(let g of m.content.parts){if(g.text!==void 0){let x=_o(g);(!d||x&&d.type!=="thinking"||!x&&d.type!=="text")&&(d&&(d.type==="text"?n.push({type:"text_end",contentIndex:p.length-1,content:d.text,partial:s}):n.push({type:"thinking_end",contentIndex:u(),content:d.thinking,partial:s})),x?(d={type:"thinking",thinking:"",thinkingSignature:void 0},s.content.push(d),n.push({type:"thinking_start",contentIndex:u(),partial:s})):(d={type:"text",text:""},s.content.push(d),n.push({type:"text_start",contentIndex:u(),partial:s}))),d.type==="thinking"?(d.thinking+=g.text,d.thinkingSignature=Xn(d.thinkingSignature,g.thoughtSignature),n.push({type:"thinking_delta",contentIndex:u(),delta:g.text,partial:s})):(d.text+=g.text,d.textSignature=Xn(d.textSignature,g.thoughtSignature),n.push({type:"text_delta",contentIndex:u(),delta:g.text,partial:s}))}if(g.functionCall){d&&(d.type==="text"?n.push({type:"text_end",contentIndex:u(),content:d.text,partial:s}):n.push({type:"thinking_end",contentIndex:u(),content:d.thinking,partial:s}),d=null);let x=g.functionCall.id,w={type:"toolCall",id:!x||s.content.some(C=>C.type==="toolCall"&&C.id===x)?`${g.functionCall.name}_${Date.now()}_${++bx}`:x,name:g.functionCall.name||"",arguments:g.functionCall.args??{},...g.thoughtSignature&&{thoughtSignature:g.thoughtSignature}};s.content.push(w),n.push({type:"toolcall_start",contentIndex:u(),partial:s}),n.push({type:"toolcall_delta",contentIndex:u(),delta:JSON.stringify(w.arguments),partial:s}),n.push({type:"toolcall_end",contentIndex:u(),toolCall:w,partial:s})}}m?.finishReason&&(s.stopReason=Uo(m.finishReason),s.content.some(g=>g.type==="toolCall")&&(s.stopReason="toolUse")),h.usageMetadata&&(s.usage={input:(h.usageMetadata.promptTokenCount||0)-(h.usageMetadata.cachedContentTokenCount||0),output:(h.usageMetadata.candidatesTokenCount||0)+(h.usageMetadata.thoughtsTokenCount||0),cacheRead:h.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,totalTokens:h.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},je(i,s.usage))}if(d&&(d.type==="text"?n.push({type:"text_end",contentIndex:u(),content:d.text,partial:s}):n.push({type:"thinking_end",contentIndex:u(),content:d.thinking,partial:s})),t?.signal?.aborted)throw new Error("Request was aborted");if(s.stopReason==="aborted"||s.stopReason==="error")throw new Error("An unknown error occurred");n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let r of s.content)"index"in r&&delete r.index;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=o instanceof Error?o.message:JSON.stringify(o),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},vx=(i,e,t)=>{let n=Me(i,t,void 0);if(!t?.reasoning)return Fo(i,e,{...n,thinking:{enabled:!1}});let s=Ce(i,t.reasoning),o=s==="off"?"high":s,r=i;return $a(r)||Td(r)?Fo(i,e,{...n,thinking:{enabled:!0,level:Ax(o,r)}}):Fo(i,e,{...n,thinking:{enabled:!0,budgetTokens:Px(r,o,t.thinkingBudgets)}})}});var Pd={};Et(Pd,{streamMistral:()=>Ed,streamSimpleMistral:()=>Wx});import{Mistral as _x}from"@mistralai/mistralai";function Ox(i){return{role:"assistant",content:[],api:i.api,provider:i.provider,model:i.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()}}function Ux(){let i=new Map,e=new Map;return t=>{let n=i.get(t);if(n)return n;let s=0;for(;;){let o=Id(t,s),r=e.get(o);if(!r||r===t)return i.set(t,o),e.set(o,t),o;s++}}}function Id(i,e){let t=i.replace(/[^a-zA-Z0-9]/g,"");if(e===0&&t.length===Rd)return t;let n=t||i,s=e===0?n:`${n}:${e}`;return ps(s).replace(/[^a-zA-Z0-9]/g,"").slice(0,Rd)}function Dx(i){if(i instanceof Error){let e=i,t=typeof e.statusCode=="number"?e.statusCode:void 0,n=typeof e.body=="string"?e.body.trim():void 0;return t!==void 0&&n?`Mistral API error (${t}): ${Fx(n,Lx)}`:t!==void 0?`Mistral API error (${t}): ${i.message}`:i.message}return $x(i)}function Fx(i,e){return i.length<=e?i:`${i.slice(0,e)}... [truncated ${i.length-e} chars]`}function $x(i){try{let e=JSON.stringify(i);return e===void 0?String(i):e}catch{return String(i)}}function Bx(i,e){let t={retries:{strategy:"none"}};e?.signal&&(t.signal=e.signal);let n={};return i.headers&&Object.assign(n,i.headers),e?.headers&&Object.assign(n,e.headers),e?.sessionId&&!n["x-affinity"]&&(n["x-affinity"]=e.sessionId),Object.keys(n).length>0&&(t.headers=n),t}function Nx(i,e,t,n){let s={model:i.id,stream:!0,messages:zx(t,i.input.includes("image"))};return e.tools?.length&&(s.tools=Kx(e.tools)),n?.temperature!==void 0&&(s.temperature=n.temperature),n?.maxTokens!==void 0&&(s.maxTokens=n.maxTokens),n?.toolChoice&&(s.toolChoice=Vx(n.toolChoice)),n?.promptMode&&(s.promptMode=n.promptMode),n?.reasoningEffort&&(s.reasoningEffort=n.reasoningEffort),e.systemPrompt&&s.messages.unshift({role:"system",content:H(e.systemPrompt)}),s}async function Gx(i,e,t,n){let s=null,o=e.content,r=()=>o.length-1,a=new Map,l=c=>{if(c){if(c.type==="text"){t.push({type:"text_end",contentIndex:r(),content:c.text,partial:e});return}c.type==="thinking"&&t.push({type:"thinking_end",contentIndex:r(),content:c.thinking,partial:e})}};for await(let c of n){let d=c.data;e.responseId||=d.id,d.usage&&(e.usage.input=d.usage.promptTokens||0,e.usage.output=d.usage.completionTokens||0,e.usage.cacheRead=0,e.usage.cacheWrite=0,e.usage.totalTokens=d.usage.totalTokens||e.usage.input+e.usage.output,je(i,e.usage));let p=d.choices[0];if(!p)continue;p.finishReason&&(e.stopReason=Qx(p.finishReason));let u=p.delta;if(u.content!==null&&u.content!==void 0){let m=typeof u.content=="string"?[u.content]:u.content;for(let g of m){if(typeof g=="string"){let x=H(g);(!s||s.type!=="text")&&(l(s),s={type:"text",text:""},e.content.push(s),t.push({type:"text_start",contentIndex:r(),partial:e})),s.text+=x,t.push({type:"text_delta",contentIndex:r(),delta:x,partial:e});continue}if(g.type==="thinking"){let x=g.thinking.map(v=>"text"in v?v.text:"").filter(v=>v.length>0).join(""),b=H(x);if(!b)continue;(!s||s.type!=="thinking")&&(l(s),s={type:"thinking",thinking:""},e.content.push(s),t.push({type:"thinking_start",contentIndex:r(),partial:e})),s.thinking+=b,t.push({type:"thinking_delta",contentIndex:r(),delta:b,partial:e});continue}if(g.type==="text"){let x=H(g.text);(!s||s.type!=="text")&&(l(s),s={type:"text",text:""},e.content.push(s),t.push({type:"text_start",contentIndex:r(),partial:e})),s.text+=x,t.push({type:"text_delta",contentIndex:r(),delta:x,partial:e})}}}let h=u.toolCalls||[];for(let m of h){s&&(l(s),s=null);let g=m.id&&m.id!=="null"?m.id:Id(`toolcall:${m.index??0}`,0),x=`${g}:${m.index||0}`,b=a.get(x),v;if(b!==void 0){let C=e.content[b];C?.type==="toolCall"&&(v=C)}v||(v={type:"toolCall",id:g,name:m.function.name,arguments:{},partialArgs:""},e.content.push(v),a.set(x,e.content.length-1),t.push({type:"toolcall_start",contentIndex:e.content.length-1,partial:e}));let w=typeof m.function.arguments=="string"?m.function.arguments:JSON.stringify(m.function.arguments||{});v.partialArgs=(v.partialArgs||"")+w,v.arguments=Pe(v.partialArgs),t.push({type:"toolcall_delta",contentIndex:a.get(x),delta:w,partial:e})}}l(s);for(let c of a.values()){let d=e.content[c];if(d.type!=="toolCall")continue;let p=d;p.arguments=Pe(p.partialArgs),delete p.partialArgs,t.push({type:"toolcall_end",contentIndex:c,toolCall:p,partial:e})}}function Kx(i){return i.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:Ba(e.parameters),strict:!1}}))}function Ba(i){if(Array.isArray(i))return i.map(e=>Ba(e));if(i&&typeof i=="object"){let e={};for(let[t,n]of Object.entries(i))e[t]=Ba(n);return e}return i}function zx(i,e){let t=[];for(let n of i){if(n.role==="user"){if(typeof n.content=="string"){t.push({role:"user",content:H(n.content)});continue}let l=n.content.some(d=>d.type==="image"),c=n.content.filter(d=>d.type==="text"||e).map(d=>d.type==="text"?{type:"text",text:H(d.text)}:{type:"image_url",imageUrl:`data:${d.mimeType};base64,${d.data}`});if(c.length>0){t.push({role:"user",content:c});continue}l&&!e&&t.push({role:"user",content:"(image omitted: model does not support images)"});continue}if(n.role==="assistant"){let l=[],c=[];for(let p of n.content){if(p.type==="text"){p.text.trim().length>0&&l.push({type:"text",text:H(p.text)});continue}if(p.type==="thinking"){p.thinking.trim().length>0&&l.push({type:"thinking",thinking:[{type:"text",text:H(p.thinking)}]});continue}c.push({id:p.id,type:"function",function:{name:p.name,arguments:JSON.stringify(p.arguments||{})}})}let d={role:"assistant"};l.length>0&&(d.content=l),c.length>0&&(d.toolCalls=c),(l.length>0||c.length>0)&&t.push(d);continue}let s=[],o=n.content.filter(l=>l.type==="text").map(l=>l.type==="text"?H(l.text):"").join(`
|
|
19
|
+
`),r=n.content.some(l=>l.type==="image"),a=Hx(o,r,e,n.isError);s.push({type:"text",text:a});for(let l of n.content)e&&l.type==="image"&&s.push({type:"image_url",imageUrl:`data:${l.mimeType};base64,${l.data}`});t.push({role:"tool",toolCallId:n.toolCallId,name:n.toolName,content:s})}return t}function Hx(i,e,t,n){let s=i.trim(),o=n?"[tool error] ":"";return s.length>0?`${o}${s}${e&&!t?`
|
|
20
|
+
[tool image omitted: model does not support images]`:""}`:e?t?n?"[tool error] (see attached image)":"(see attached image)":n?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)":n?"[tool error] (no tool output)":"(no tool output)"}function Ad(i){return i.id==="mistral-small-2603"||i.id==="mistral-small-latest"||i.id==="mistral-medium-3.5"}function jx(i){return i.reasoning&&!Ad(i)}function qx(i,e){return i.thinkingLevelMap?.[e]??"high"}function Vx(i){if(i)return i==="auto"||i==="none"||i==="any"||i==="required"?i:{type:"function",function:{name:i.function.name}}}function Qx(i){if(i===null)return"stop";switch(i){case"stop":return"stop";case"length":case"model_length":return"length";case"tool_calls":return"toolUse";case"error":return"error";default:return"stop"}}var Rd,Lx,Ed,Wx,_d=te(()=>{"use strict";pt();Ze();et();La();jn();Wt();Ot();Jn();Rd=9,Lx=4e3,Ed=(i,e,t)=>{let n=new de;return(async()=>{let s=Ox(i);try{let o=t?.apiKey||ne(i.provider);if(!o)throw new Error(`No API key for provider: ${i.provider}`);let r=new _x({apiKey:o,serverURL:i.baseUrl}),a=Ux(),l=wt(e.messages,i,u=>a(u)),c=Nx(i,e,l,t),d=await t?.onPayload?.(c,i);d!==void 0&&(c=d);let p=await r.chat.stream(c,Bx(i,t));if(n.push({type:"start",partial:s}),await Gx(i,s,n,p),t?.signal?.aborted)throw new Error("Request was aborted");if(s.stopReason==="aborted"||s.stopReason==="error")throw new Error("An unknown error occurred");n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let r of s.content)delete r.partialArgs;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=Dx(o),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},Wx=(i,e,t)=>{let n=t?.apiKey||ne(i.provider);if(!n)throw new Error(`No API key for provider: ${i.provider}`);let s=Me(i,t,n),o=t?.reasoning?Ce(i,t.reasoning):void 0,r=o==="off"?void 0:o,a=i.reasoning&&r!==void 0;return Ed(i,e,{...s,promptMode:a&&jx(i)?"reasoning":void 0,reasoningEffort:a&&Ad(i)?qx(i,r):void 0})}});function Wd(i){return Ld.add(i),()=>{Ld.delete(i)}}var Ld,Na=te(()=>{"use strict";Ld=new Set});function ds(i){return i instanceof Error?i.message||i.name:typeof i=="string"?i:String(i)}function Jx(i){if(!(i instanceof Error))return{name:"ThrownValue",message:ds(i)};let e=i.code;return{name:i.name||void 0,message:i.message||i.name,stack:i.stack,code:typeof e=="string"||typeof e=="number"?e:void 0}}function Od(i,e,t){return{type:i,timestamp:Date.now(),error:Jx(e),details:t}}function Ud(i,e){i.diagnostics=[...i.diagnostics??[],e]}var Ga=te(()=>{"use strict"});var Zd={};Et(Zd,{closeOpenAICodexWebSocketSessions:()=>Vd,getOpenAICodexWebSocketDebugStats:()=>hb,resetOpenAICodexWebSocketDebugStats:()=>gb,streamOpenAICodexResponses:()=>Kd,streamSimpleOpenAICodexResponses:()=>sb});function ib(i,e){return i===429||i===500||i===502||i===503||i===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(e)}function Fd(i,e){return new Promise((t,n)=>{if(e?.aborted){n(new Error("Request was aborted"));return}let s=setTimeout(t,i);e?.addEventListener("abort",()=>{clearTimeout(s),n(new Error("Request was aborted"))})})}function ob(i,e,t){let n=fn(i,e,Gd,{includeSystemPrompt:!1}),s={model:i.id,store:!1,stream:!0,instructions:e.systemPrompt||"You are a helpful assistant.",input:n,text:{verbosity:t?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:t?.sessionId,tool_choice:"auto",parallel_tool_calls:!0};if(t?.temperature!==void 0&&(s.temperature=t.temperature),t?.serviceTier!==void 0&&(s.service_tier=t.serviceTier),e.tools&&e.tools.length>0&&(s.tools=Yn(e.tools,{strict:null})),t?.reasoningEffort!==void 0){let o=t.reasoningEffort==="none"?i.thinkingLevelMap?.off??"none":i.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;o!==null&&(s.reasoning={effort:o,summary:t.reasoningSummary??"auto"})}return s}function rb(i,e){switch(e){case"flex":return .5;case"priority":return i.id==="gpt-5.5"?2.5:2;default:return 1}}function zd(i,e,t){let n=rb(t,e);n!==1&&(i.cost.input*=n,i.cost.output*=n,i.cost.cacheRead*=n,i.cost.cacheWrite*=n,i.cost.total=i.cost.input+i.cost.output+i.cost.cacheRead+i.cost.cacheWrite)}function Hd(i,e){return i==="default"&&(e==="flex"||e==="priority")?e:i??e}function jd(i){let t=(i&&i.trim().length>0?i:Zx).replace(/\/+$/,"");return t.endsWith("/codex/responses")?t:t.endsWith("/codex")?`${t}/responses`:`${t}/codex/responses`}function ab(i){let e=new URL(jd(i));return e.protocol==="https:"&&(e.protocol="wss:"),e.protocol==="http:"&&(e.protocol="ws:"),e.toString()}async function lb(i,e,t,n,s){await xn(qd(db(i)),e,t,n,{serviceTier:s?.serviceTier,resolveServiceTier:Hd,applyServiceTierPricing:(o,r)=>zd(o,r,n)})}function cb(i){return i instanceof ms||i instanceof hs}async function*qd(i){for await(let e of i){let t=typeof e.type=="string"?e.type:void 0;if(t){if(t==="error"){let n=e.code||"",s=e.message||"";throw new ms(`Codex error: ${s||n||JSON.stringify(e)}`,{code:n||void 0,payload:e})}if(t==="response.failed"){let n=e.response,s=n?.error?.code,o=n?.error?.message;throw new ms(o||"Codex response failed",{code:s,payload:e})}if(t==="response.done"||t==="response.completed"||t==="response.incomplete"){let n=e.response,s=n&&{...n,status:pb(n.status)};yield{...e,type:"response.completed",response:s};return}yield e}}}function pb(i){if(typeof i=="string")return nb.has(i)?i:void 0}async function*db(i){if(!i.body)return;let e=i.body.getReader(),t=new TextDecoder,n="";try{for(;;){let{done:s,value:o}=await e.read();if(s)break;n+=t.decode(o,{stream:!0});let r=n.indexOf(`
|
|
21
|
+
|
|
22
|
+
`);for(;r!==-1;){let a=n.slice(0,r);n=n.slice(r+2);let l=a.split(`
|
|
23
|
+
`).filter(c=>c.startsWith("data:")).map(c=>c.slice(5).trim());if(l.length>0){let c=l.join(`
|
|
24
|
+
`).trim();if(c&&c!=="[DONE]")try{yield JSON.parse(c)}catch(d){throw new hs(`Invalid Codex SSE JSON: ${ds(d)}`,{cause:d,payload:c})}}r=n.indexOf(`
|
|
25
|
+
|
|
26
|
+
`)}}}finally{try{await e.cancel()}catch{}try{e.releaseLock()}catch{}}}function ja(i){let e=gs.get(i);return e||(e={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},gs.set(i,e)),e}function hb(i){let e=gs.get(i);return e?{...e}:void 0}function gb(i){if(i){gs.delete(i),Bo.delete(i);return}gs.clear(),Bo.clear()}function Vd(i){let e=t=>{t.idleTimer&&clearTimeout(t.idleTimer),Qt(t.socket,1e3,"debug_close")};if(i){let t=ut.get(i);t&&e(t),ut.delete(i);return}for(let t of ut.values())e(t);ut.clear()}function Qd(i){return i?Bo.has(i):!1}function $d(i){if(!i)return;let e=ja(i);e.sseFallbacks++,e.websocketFallbackActive=Qd(i)}function fb(i,e){if(!i)return;Bo.add(i);let t=ja(i);t.websocketFailures++,t.lastWebSocketError=ds(e),t.websocketFallbackActive=!0}function xb(){let i=globalThis.WebSocket;return typeof i!="function"?null:i}function bb(i){let e=i.readyState;return typeof e=="number"?e:void 0}function $o(i){let e=bb(i);return e===void 0||e===1}function Qt(i,e=1e3,t="done"){try{i.close(e,t)}catch{}}function Bd(i,e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{e.busy||(Qt(e.socket,1e3,"idle_timeout"),ut.delete(i))},mb)}async function za(i,e,t){let n=xb();if(!n)throw new Error("WebSocket transport is not available in this runtime");let s=He(e);return delete s["OpenAI-Beta"],new Promise((o,r)=>{let a=!1,l;try{l=new n(i,{headers:s})}catch(m){r(m instanceof Error?m:new Error(String(m)));return}let c=()=>{a||(a=!0,h(),o(l))},d=m=>{let g=Jd(m);a||(a=!0,h(),r(g))},p=m=>{let g=Yd(m);a||(a=!0,h(),r(g))},u=()=>{a||(a=!0,h(),l.close(1e3,"aborted"),r(new Error("Request was aborted")))},h=()=>{l.removeEventListener("open",c),l.removeEventListener("error",d),l.removeEventListener("close",p),t?.removeEventListener("abort",u)};l.addEventListener("open",c),l.addEventListener("error",d),l.addEventListener("close",p),t?.addEventListener("abort",u)})}async function vb(i,e,t,n){if(!t){let a=await za(i,e,n);return{socket:a,reused:!1,release:({keep:l}={})=>{if(l===!1){Qt(a);return}Qt(a)}}}let s=ut.get(t);if(s){if(s.idleTimer&&(clearTimeout(s.idleTimer),s.idleTimer=void 0),!s.busy&&$o(s.socket))return s.busy=!0,{socket:s.socket,entry:s,reused:!0,release:({keep:a}={})=>{if(!a||!$o(s.socket)){Qt(s.socket),ut.delete(t);return}s.busy=!1,Bd(t,s)}};if(s.busy){let a=await za(i,e,n);return{socket:a,reused:!1,release:()=>{Qt(a)}}}$o(s.socket)||(Qt(s.socket),ut.delete(t))}let o=await za(i,e,n),r={socket:o,busy:!0};return ut.set(t,r),{socket:o,entry:r,reused:!1,release:({keep:a}={})=>{if(!a||!$o(r.socket)){Qt(r.socket),r.idleTimer&&clearTimeout(r.idleTimer),ut.get(t)===r&&ut.delete(t);return}r.busy=!1,Bd(t,r)}}}function Jd(i){if(i&&typeof i=="object"){let e="message"in i?i.message:void 0;if(typeof e=="string"&&e.length>0)return new Error(e);let t="error"in i?i.error:void 0;if(t instanceof Error&&t.message.length>0)return t;if(t&&typeof t=="object"&&"message"in t){let n=t.message;if(typeof n=="string"&&n.length>0)return new Error(n)}}return new Error("WebSocket error")}function Yd(i){if(i&&typeof i=="object"){let e="code"in i?i.code:void 0,t="reason"in i?i.reason:void 0,n="wasClean"in i?i.wasClean:void 0,s=typeof e=="number"?` ${e}`:"",o=typeof t=="string"&&t.length>0?` ${t}`:"";return!o&&e===tb&&(o=" message too big"),new Ha(`WebSocket closed${s}${o}`.trim(),{code:typeof e=="number"?e:void 0,reason:typeof t=="string"&&t.length>0?t:void 0,wasClean:typeof n=="boolean"?n:void 0})}return new Error("WebSocket closed")}async function yb(i){if(typeof i=="string")return i;if(i instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(i));if(ArrayBuffer.isView(i)){let e=i;return new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}if(i&&typeof i=="object"&&"arrayBuffer"in i){let t=await i.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*wb(i,e){let t=[],n=null,s=!1,o=null,r=!1,a=()=>{if(!n)return;let u=n;n=null,u()},l=u=>{(async()=>{let h=null;try{if(!u||typeof u!="object"||!("data"in u)||(h=await yb(u.data),!h))return;let m=JSON.parse(h),g=typeof m.type=="string"?m.type:"";(g==="response.completed"||g==="response.done"||g==="response.incomplete")&&(r=!0,s=!0),t.push(m),a()}catch(m){o=new hs(`Invalid Codex WebSocket JSON: ${ds(m)}`,{cause:m,payload:h}),s=!0,a()}})()},c=u=>{o=Jd(u),s=!0,a()},d=u=>{if(r){s=!0,a();return}o||(o=Yd(u)),s=!0,a()},p=()=>{o=new Error("Request was aborted"),s=!0,a()};i.addEventListener("message",l),i.addEventListener("error",c),i.addEventListener("close",d),e?.addEventListener("abort",p);try{for(;;){if(e?.aborted)throw new Error("Request was aborted");if(t.length>0){yield t.shift();continue}if(s)break;await new Promise(u=>{n=u})}if(o)throw o;if(!r)throw new Error("WebSocket stream closed before response.completed")}finally{i.removeEventListener("message",l),i.removeEventListener("error",c),i.removeEventListener("close",d),e?.removeEventListener("abort",p)}}function Nd(i){let{input:e,previous_response_id:t,...n}=i;return n}function kb(i,e){return JSON.stringify(i??[])===JSON.stringify(e??[])}function Sb(i,e){return JSON.stringify(Nd(i))===JSON.stringify(Nd(e))}function Tb(i,e){if(!Sb(i,e.lastRequestBody))return;let t=i.input??[],n=[...e.lastRequestBody.input??[],...e.lastResponseItems];if(t.length<n.length)return;let s=t.slice(0,n.length);if(kb(s,n))return t.slice(n.length)}function Cb(i,e){let t=i.continuation;if(!t)return e;let n=Tb(e,t);return!n||!t.lastResponseId?(i.continuation=void 0,e):{...e,previous_response_id:t.lastResponseId,input:n}}async function*Mb(i,e,t,n){let s=!1;for await(let o of i)s||(s=!0,n(),t.push({type:"start",partial:e})),yield o}async function Rb(i,e,t,n,s,o,r,a){let{socket:l,entry:c,reused:d,release:p}=await vb(i,t,a?.sessionId,a?.signal),u=!0,h=a?.transport==="websocket-cached"||a?.transport==="auto",m=e,g=h&&c?Cb(c,m):m,x=a?.sessionId?ja(a.sessionId):void 0;x&&(x.requests++,d?x.connectionsReused++:x.connectionsCreated++,h&&x.cachedContextRequests++,g.store===!0&&x.storeTrueRequests++,x.lastInputItems=g.input?.length??0,g.previous_response_id?(x.deltaRequests++,x.lastDeltaInputItems=g.input?.length??0,x.lastPreviousResponseId=g.previous_response_id):(x.fullContextRequests++,x.lastDeltaInputItems=void 0,x.lastPreviousResponseId=void 0));try{if(l.send(JSON.stringify({type:"response.create",...g})),await xn(Mb(qd(wb(l,a?.signal)),n,s,r),n,s,o,{serviceTier:a?.serviceTier,resolveServiceTier:Hd,applyServiceTierPricing:(b,v)=>zd(b,v,o)}),a?.signal?.aborted)u=!1;else if(h&&c&&n.responseId){let b=fn(o,{messages:[n]},Gd,{includeSystemPrompt:!1}).filter(v=>v.type!=="function_call_output");c.continuation={lastRequestBody:m,lastResponseId:n.responseId,lastResponseItems:b}}}catch(b){throw c&&(c.continuation=void 0),u=!1,b}finally{p({keep:u})}}async function Eb(i){let e=await i.text(),t=e||i.statusText||"Request failed",n;try{let o=JSON.parse(e)?.error;if(o){let r=o.code||o.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(r)||i.status===429){let a=o.plan_type?` (${o.plan_type.toLowerCase()} plan)`:"",l=o.resets_at?Math.max(0,Math.round((o.resets_at*1e3-Date.now())/6e4)):void 0,c=l!==void 0?` Try again in ~${l} min.`:"";n=`You have hit your ChatGPT usage limit${a}.${c}`.trim()}t=o.message||n||t}}catch{}return{message:t,friendlyMessage:n}}function Ib(i){try{let e=i.split(".");if(e.length!==3)throw new Error("Invalid token");let n=JSON.parse(atob(e[1]))?.[eb]?.chatgpt_account_id;if(!n)throw new Error("No account ID in token");return n}catch{throw new Error("Failed to extract accountId from token")}}function Ab(){return typeof globalThis.crypto?.randomUUID=="function"?globalThis.crypto.randomUUID():`codex_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function Xd(i,e,t,n){let s=new Headers(i);for(let[r,a]of Object.entries(e||{}))s.set(r,a);s.set("Authorization",`Bearer ${n}`),s.set("chatgpt-account-id",t),s.set("originator","pi");let o=us?`pi (${us.platform()} ${us.release()}; ${us.arch()})`:"pi (browser)";return s.set("User-Agent",o),s}function Pb(i,e,t,n,s){let o=Xd(i,e,t,n);return o.set("OpenAI-Beta","responses=experimental"),o.set("accept","text/event-stream"),o.set("content-type","application/json"),s&&(o.set("session_id",s),o.set("x-client-request-id",s)),o}function _b(i,e,t,n,s){let o=Xd(i,e,t,n);return o.delete("accept"),o.delete("content-type"),o.delete("OpenAI-Beta"),o.delete("openai-beta"),o.set("OpenAI-Beta",ub),o.set("x-client-request-id",s),o.set("session_id",s),o}var us,Yx,Xx,Zx,eb,Ka,Dd,Gd,tb,nb,Kd,sb,ms,hs,ub,mb,ut,gs,Bo,Ha,eu=te(()=>{"use strict";pt();Ze();Na();Ga();et();gn();Ao();Ot();us=null,Yx=i=>import(i),Xx="node:os";typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&Yx(Xx).then(i=>{us=i});Zx="https://chatgpt.com/backend-api",eb="https://api.openai.com/auth",Ka=3,Dd=1e3,Gd=new Set(["openai","openai-codex","opencode"]),tb=1009,nb=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);Kd=(i,e,t)=>{let n=new de;return(async()=>{let s={role:"assistant",content:[],api:"openai-codex-responses",provider:i.provider,model:i.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o=t?.apiKey||ne(i.provider)||"";if(!o)throw new Error(`No API key for provider: ${i.provider}`);let r=Ib(o),a=ob(i,e,t),l=await t?.onPayload?.(a,i);l!==void 0&&(a=l);let c=t?.sessionId||Ab(),d=Pb(i.headers,t?.headers,r,o,t?.sessionId),p=_b(i.headers,t?.headers,r,o,c),u=JSON.stringify(a),h=t?.transport||"auto",m=h!=="sse"&&Qd(t?.sessionId);if(m&&$d(t?.sessionId),h!=="sse"&&!m){let b=!1;try{if(await Rb(ab(i.baseUrl),a,p,s,n,i,()=>{b=!0},t),t?.signal?.aborted)throw new Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end();return}catch(v){if(t?.signal?.aborted||cb(v)||(Ud(s,Od("provider_transport_failure",v,{configuredTransport:h,fallbackTransport:b?void 0:"sse",eventsEmitted:b,phase:b?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(u).byteLength})),fb(t?.sessionId,v),b))throw v;$d(t?.sessionId)}}let g,x;for(let b=0;b<=Ka;b++){if(t?.signal?.aborted)throw new Error("Request was aborted");try{if(g=await fetch(jd(i.baseUrl),{method:"POST",headers:d,body:u,signal:t?.signal}),await t?.onResponse?.({status:g.status,headers:He(g.headers)},i),g.ok)break;let v=await g.text();if(b<Ka&&ib(g.status,v)){let R=Dd*2**b;await Fd(R,t?.signal);continue}let w=new Response(v,{status:g.status,statusText:g.statusText}),C=await Eb(w);throw new Error(C.friendlyMessage||C.message)}catch(v){if(v instanceof Error&&(v.name==="AbortError"||v.message==="Request was aborted"))throw new Error("Request was aborted");if(x=v instanceof Error?v:new Error(String(v)),b<Ka&&!x.message.includes("usage limit")){let w=Dd*2**b;await Fd(w,t?.signal);continue}throw x}}if(!g?.ok)throw x??new Error("Failed after retries");if(!g.body)throw new Error("No response body");if(n.push({type:"start",partial:s}),await lb(g,s,n,i,t),t?.signal?.aborted)throw new Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let r of s.content)delete r.partialJson;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=o instanceof Error?o.message:String(o),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},sb=(i,e,t)=>{let n=t?.apiKey||ne(i.provider);if(!n)throw new Error(`No API key for provider: ${i.provider}`);let s=Me(i,t,n),o=t?.reasoning?Ce(i,t.reasoning):void 0;return Kd(i,e,{...s,reasoningEffort:o==="off"?void 0:o})};ms=class extends Error{constructor(e,t){super(e),this.name="CodexApiError",this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}},hs=class extends Error{constructor(e,t){super(e),this.name="CodexProtocolError",this.payload=t?.payload,this.cause=t?.cause}};ub="responses_websockets=2026-02-06",mb=300*1e3,ut=new Map,gs=new Map,Bo=new Set;Wd(Vd);Ha=class extends Error{constructor(e,t){super(e),this.name="WebSocketCloseError",this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}}});var au={};Et(au,{convertMessages:()=>ru,streamOpenAICompletions:()=>su,streamSimpleOpenAICompletions:()=>Fb});import Lb from"openai";function Wb(i){for(let e of i)if(e.role==="toolResult"||e.role==="assistant"&&e.content.some(t=>t.type==="toolCall"))return!0;return!1}function tu(i){return i.type==="text"}function Ob(i){return i.type==="thinking"}function Ub(i){return i.type==="toolCall"}function Db(i){return i.type==="image"}function iu(i){return i||(typeof process<"u"&&process.env.PI_CACHE_RETENTION==="long"?"long":"short")}function $b(i,e,t,n,s,o=qa(i)){if(!t){if(!process.env.OPENAI_API_KEY)throw new Error("OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.");t=process.env.OPENAI_API_KEY}let r={...i.headers};if(i.provider==="github-copilot"){let l=Vn(e.messages),c=Qn({messages:e.messages,hasImages:l});Object.assign(r,c)}s&&o.sendSessionAffinityHeaders&&(r.session_id=s,r["x-client-request-id"]=s,r["x-session-affinity"]=s),n&&Object.assign(r,n);let a=i.provider==="cloudflare-ai-gateway"?{...r,Authorization:r.Authorization??null,"cf-aig-authorization":`Bearer ${t}`}:r;return new Lb({apiKey:t,baseURL:So(i.provider)?qn(i):i.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:a})}function Bb(i,e,t,n=qa(i),s=iu(t?.cacheRetention)){let o=ru(i,e,n),r=Nb(n,s),a={model:i.id,messages:o,stream:!0,prompt_cache_key:i.baseUrl.includes("api.openai.com")&&s!=="none"||s==="long"&&n.supportsLongCacheRetention?t?.sessionId:void 0,prompt_cache_retention:s==="long"&&n.supportsLongCacheRetention?"24h":void 0};if(n.supportsUsageInStreaming!==!1&&(a.stream_options={include_usage:!0}),n.supportsStore&&(a.store=!1),t?.maxTokens&&(n.maxTokensField==="max_tokens"?a.max_tokens=t.maxTokens:a.max_completion_tokens=t.maxTokens),t?.temperature!==void 0&&(a.temperature=t.temperature),e.tools&&e.tools.length>0?(a.tools=Vb(e.tools,n),n.zaiToolStream&&(a.tool_stream=!0)):Wb(e.messages)&&(a.tools=[]),r&&Gb(o,a.tools,r),t?.toolChoice&&(a.tool_choice=t.toolChoice),n.thinkingFormat==="zai"&&i.reasoning)a.enable_thinking=!!t?.reasoningEffort;else if(n.thinkingFormat==="qwen"&&i.reasoning)a.enable_thinking=!!t?.reasoningEffort;else if(n.thinkingFormat==="qwen-chat-template"&&i.reasoning)a.chat_template_kwargs={enable_thinking:!!t?.reasoningEffort,preserve_thinking:!0};else if(n.thinkingFormat==="deepseek"&&i.reasoning)a.thinking={type:t?.reasoningEffort?"enabled":"disabled"},t?.reasoningEffort&&(a.reasoning_effort=i.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort);else if(n.thinkingFormat==="openrouter"&&i.reasoning){let l=a;t?.reasoningEffort?l.reasoning={effort:i.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}:i.thinkingLevelMap?.off!==null&&(l.reasoning={effort:i.thinkingLevelMap?.off??"none"})}else if(n.thinkingFormat==="together"&&i.reasoning){let l=a;l.reasoning={enabled:!!t?.reasoningEffort},t?.reasoningEffort&&n.supportsReasoningEffort&&(l.reasoning_effort=i.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort)}else if(t?.reasoningEffort&&i.reasoning&&n.supportsReasoningEffort)a.reasoning_effort=i.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;else if(!t?.reasoningEffort&&i.reasoning&&n.supportsReasoningEffort){let l=i.thinkingLevelMap?.off;typeof l=="string"&&(a.reasoning_effort=l)}if(i.baseUrl.includes("openrouter.ai")&&i.compat?.openRouterRouting&&(a.provider=i.compat.openRouterRouting),i.baseUrl.includes("ai-gateway.vercel.sh")&&i.compat?.vercelGatewayRouting){let l=i.compat.vercelGatewayRouting;if(l.only||l.order){let c={};l.only&&(c.only=l.only),l.order&&(c.order=l.order),a.providerOptions={gateway:c}}}return a}function Nb(i,e){if(i.cacheControlFormat!=="anthropic"||e==="none")return;let t=e==="long"&&i.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...t?{ttl:t}:{}}}function Gb(i,e,t){Kb(i,t),Hb(e,t),zb(i,t)}function Kb(i,e){for(let t of i)if(t.role==="system"||t.role==="developer"){jb(t,e);return}}function zb(i,e){for(let t=i.length-1;t>=0;t--){let n=i[t];if((n.role==="user"||n.role==="assistant")&&qb(n,e))return}}function Hb(i,e){if(!i||i.length===0)return;let t=i[i.length-1];t.cache_control=e}function jb(i,e){return ou(i,e)}function qb(i,e){return i.role==="user"||i.role==="assistant"?ou(i,e):!1}function ou(i,e){let t=i.content;if(typeof t=="string")return t.length===0?!1:(i.content=[{type:"text",text:t,cache_control:e}],!0);if(!Array.isArray(t))return!1;for(let n=t.length-1;n>=0;n--){let s=t[n];if(s?.type==="text"){let o=s;return o.cache_control=e,!0}}return!1}function ru(i,e,t){let n=[],s=a=>{if(a.includes("|")){let[l]=a.split("|");return l.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,40)}return i.provider==="openai"&&a.length>40?a.slice(0,40):a},o=wt(e.messages,i,a=>s(a));if(e.systemPrompt){let l=i.reasoning&&t.supportsDeveloperRole?"developer":"system";n.push({role:l,content:H(e.systemPrompt)})}let r=null;for(let a=0;a<o.length;a++){let l=o[a];if(t.requiresAssistantAfterToolResult&&r==="toolResult"&&l.role==="user"&&n.push({role:"assistant",content:"I have processed the tool results."}),l.role==="user")if(typeof l.content=="string")n.push({role:"user",content:H(l.content)});else{let c=l.content.map(d=>d.type==="text"?{type:"text",text:H(d.text)}:{type:"image_url",image_url:{url:`data:${d.mimeType};base64,${d.data}`}});if(c.length===0)continue;n.push({role:"user",content:c})}else if(l.role==="assistant"){let c={role:"assistant",content:t.requiresAssistantAfterToolResult?"":null},d=l.content.filter(tu).filter(x=>x.text.trim().length>0).map(x=>({type:"text",text:H(x.text)})),p=d.map(x=>x.text).join(""),u=l.content.filter(Ob).filter(x=>x.thinking.trim().length>0);if(u.length>0)if(t.requiresThinkingAsText){let x=u.map(b=>H(b.thinking)).join(`
|
|
27
|
+
|
|
28
|
+
`);c.content=[{type:"text",text:x},...d]}else{p.length>0&&(c.content=p);let x=u[0].thinkingSignature;x&&x.length>0&&(c[x]=u.map(b=>b.thinking).join(`
|
|
29
|
+
`))}else p.length>0&&(c.content=p);let h=l.content.filter(Ub);if(h.length>0){c.tool_calls=h.map(b=>({id:b.id,type:"function",function:{name:b.name,arguments:JSON.stringify(b.arguments)}}));let x=h.filter(b=>b.thoughtSignature).map(b=>{try{return JSON.parse(b.thoughtSignature)}catch{return null}}).filter(Boolean);x.length>0&&(c.reasoning_details=x)}t.requiresReasoningContentOnAssistantMessages&&i.reasoning&&c.reasoning_content===void 0&&(c.reasoning_content="");let m=c.content;if(!(m!=null&&m.length>0)&&!c.tool_calls)continue;n.push(c)}else if(l.role==="toolResult"){let c=[],d=a;for(;d<o.length&&o[d].role==="toolResult";d++){let p=o[d],u=p.content.filter(tu).map(x=>x.text).join(`
|
|
30
|
+
`),h=p.content.some(x=>x.type==="image"),m=u.length>0,g={role:"tool",content:H(m?u:"(see attached image)"),tool_call_id:p.toolCallId};if(t.requiresToolResultName&&p.toolName&&(g.name=p.toolName),n.push(g),h&&i.input.includes("image"))for(let x of p.content)Db(x)&&c.push({type:"image_url",image_url:{url:`data:${x.mimeType};base64,${x.data}`}})}a=d-1,c.length>0?(t.requiresAssistantAfterToolResult&&n.push({role:"assistant",content:"I have processed the tool results."}),n.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...c]}),r="user"):r="toolResult";continue}r=l.role}return n}function Vb(i,e){return i.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters,...e.supportsStrictMode!==!1&&{strict:!1}}}))}function nu(i,e){let t=i.prompt_tokens||0,n=i.prompt_tokens_details?.cached_tokens??i.prompt_cache_hit_tokens??0,s=i.prompt_tokens_details?.cache_write_tokens||0,o=s>0?Math.max(0,n-s):n,r=Math.max(0,t-o-s),a=i.completion_tokens||0,l={input:r,output:a,cacheRead:o,cacheWrite:s,totalTokens:r+a+o+s,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return je(e,l),l}function Qb(i){if(i===null)return{stopReason:"stop"};switch(i){case"stop":case"end":return{stopReason:"stop"};case"length":return{stopReason:"length"};case"function_call":case"tool_calls":return{stopReason:"toolUse"};case"content_filter":return{stopReason:"error",errorMessage:"Provider finish_reason: content_filter"};case"network_error":return{stopReason:"error",errorMessage:"Provider finish_reason: network_error"};default:return{stopReason:"error",errorMessage:`Provider finish_reason: ${i}`}}}function Jb(i){let e=i.provider,t=i.baseUrl,n=e==="zai"||t.includes("api.z.ai"),s=e==="together"||t.includes("api.together.ai")||t.includes("api.together.xyz"),o=e==="moonshotai"||e==="moonshotai-cn"||t.includes("api.moonshot."),r=e==="cloudflare-workers-ai"||t.includes("api.cloudflare.com"),a=e==="cloudflare-ai-gateway"||t.includes("gateway.ai.cloudflare.com"),l=e==="cerebras"||t.includes("cerebras.ai")||e==="xai"||t.includes("api.x.ai")||s||t.includes("chutes.ai")||t.includes("deepseek.com")||n||o||e==="opencode"||t.includes("opencode.ai")||r||a,c=t.includes("chutes.ai")||o||a||s,d=e==="xai"||t.includes("api.x.ai"),p=e==="deepseek"||t.includes("deepseek.com"),u=e==="openrouter"&&i.id.startsWith("anthropic/")?"anthropic":void 0;return{supportsStore:!l,supportsDeveloperRole:!l,supportsReasoningEffort:!d&&!n&&!o&&!s&&!a,supportsUsageInStreaming:!0,maxTokensField:c?"max_tokens":"max_completion_tokens",requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:p,thinkingFormat:p?"deepseek":n?"zai":s?"together":e==="openrouter"||t.includes("openrouter.ai")?"openrouter":"openai",openRouterRouting:{},vercelGatewayRouting:{},zaiToolStream:!1,supportsStrictMode:!o&&!s&&!a,cacheControlFormat:u,sendSessionAffinityHeaders:!1,supportsLongCacheRetention:!(s||r||a)}}function qa(i){let e=Jb(i);return i.compat?{supportsStore:i.compat.supportsStore??e.supportsStore,supportsDeveloperRole:i.compat.supportsDeveloperRole??e.supportsDeveloperRole,supportsReasoningEffort:i.compat.supportsReasoningEffort??e.supportsReasoningEffort,supportsUsageInStreaming:i.compat.supportsUsageInStreaming??e.supportsUsageInStreaming,maxTokensField:i.compat.maxTokensField??e.maxTokensField,requiresToolResultName:i.compat.requiresToolResultName??e.requiresToolResultName,requiresAssistantAfterToolResult:i.compat.requiresAssistantAfterToolResult??e.requiresAssistantAfterToolResult,requiresThinkingAsText:i.compat.requiresThinkingAsText??e.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:i.compat.requiresReasoningContentOnAssistantMessages??e.requiresReasoningContentOnAssistantMessages,thinkingFormat:i.compat.thinkingFormat??e.thinkingFormat,openRouterRouting:i.compat.openRouterRouting??{},vercelGatewayRouting:i.compat.vercelGatewayRouting??e.vercelGatewayRouting,zaiToolStream:i.compat.zaiToolStream??e.zaiToolStream,supportsStrictMode:i.compat.supportsStrictMode??e.supportsStrictMode,cacheControlFormat:i.compat.cacheControlFormat??e.cacheControlFormat,sendSessionAffinityHeaders:i.compat.sendSessionAffinityHeaders??e.sendSessionAffinityHeaders,supportsLongCacheRetention:i.compat.supportsLongCacheRetention??e.supportsLongCacheRetention}:e}var su,Fb,lu=te(()=>{"use strict";pt();Ze();et();gn();jn();Wt();To();Co();Ot();Jn();su=(i,e,t)=>{let n=new de;return(async()=>{let s={role:"assistant",content:[],api:i.api,provider:i.provider,model:i.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o=t?.apiKey||ne(i.provider)||"",r=qa(i),a=iu(t?.cacheRetention),l=a==="none"?void 0:t?.sessionId,c=$b(i,e,o,t?.headers,l,r),d=Bb(i,e,t,r,a),p=await t?.onPayload?.(d,i);p!==void 0&&(d=p);let u={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},...t?.maxRetries!==void 0?{maxRetries:t.maxRetries}:{}},{data:h,response:m}=await c.chat.completions.create(d,u).withResponse();await t?.onResponse?.({status:m.status,headers:He(m.headers)},i),n.push({type:"start",partial:s});let g=null,x=null,b=new Map,v=new Map,w=s.content,C=I=>w.indexOf(I),R=I=>{let P=C(I);P!==-1&&(I.type==="text"?n.push({type:"text_end",contentIndex:P,content:I.text,partial:s}):I.type==="thinking"?n.push({type:"thinking_end",contentIndex:P,content:I.thinking,partial:s}):I.type==="toolCall"&&(I.arguments=Pe(I.partialArgs),delete I.partialArgs,delete I.streamIndex,n.push({type:"toolcall_end",contentIndex:P,toolCall:I,partial:s})))},k=()=>(g||(g={type:"text",text:""},w.push(g),n.push({type:"text_start",contentIndex:C(g),partial:s})),g),A=I=>(x||(x={type:"thinking",thinking:"",thinkingSignature:I},w.push(x),n.push({type:"thinking_start",contentIndex:C(x),partial:s})),x),S=I=>{let P=typeof I.index=="number"?I.index:void 0,M=P!==void 0?b.get(P):void 0;return!M&&I.id&&(M=v.get(I.id)),M||(M={type:"toolCall",id:I.id||"",name:I.function?.name||"",arguments:{},partialArgs:"",streamIndex:P},P!==void 0&&b.set(P,M),I.id&&v.set(I.id,M),w.push(M),n.push({type:"toolcall_start",contentIndex:C(M),partial:s})),P!==void 0&&M.streamIndex===void 0&&(M.streamIndex=P,b.set(P,M)),I.id&&v.set(I.id,M),M};for await(let I of h){if(!I||typeof I!="object")continue;s.responseId||=I.id,typeof I.model=="string"&&I.model.length>0&&I.model!==i.id&&(s.responseModel||=I.model),I.usage&&(s.usage=nu(I.usage,i));let P=Array.isArray(I.choices)?I.choices[0]:void 0;if(P){if(!I.usage&&P.usage&&(s.usage=nu(P.usage,i)),P.finish_reason){let M=Qb(P.finish_reason);s.stopReason=M.stopReason,M.errorMessage&&(s.errorMessage=M.errorMessage)}if(P.delta){if(P.delta.content!==null&&P.delta.content!==void 0&&P.delta.content.length>0){let $=k();$.text+=P.delta.content,n.push({type:"text_delta",contentIndex:C($),delta:P.delta.content,partial:s})}let M=["reasoning_content","reasoning","reasoning_text"],_=P.delta,U=null;for(let $ of M){let Q=_[$];if(typeof Q=="string"&&Q.length>0){U=$;break}}if(U){let $=_[U];if(typeof $=="string"&&$.length>0){let Q=A(U);Q.thinking+=$,n.push({type:"thinking_delta",contentIndex:C(Q),delta:$,partial:s})}}if(P?.delta?.tool_calls)for(let $ of P.delta.tool_calls){let Q=S($);!Q.id&&$.id&&(Q.id=$.id,v.set($.id,Q)),!Q.name&&$.function?.name&&(Q.name=$.function.name);let oe="";$.function?.arguments&&(oe=$.function.arguments,Q.partialArgs=(Q.partialArgs??"")+$.function.arguments,Q.arguments=Pe(Q.partialArgs)),n.push({type:"toolcall_delta",contentIndex:C(Q),delta:oe,partial:s})}let F=P.delta.reasoning_details;if(F&&Array.isArray(F)){for(let $ of F)if($.type==="reasoning.encrypted"&&$.id&&$.data){let Q=s.content.find(oe=>oe.type==="toolCall"&&oe.id===$.id);Q&&(Q.thoughtSignature=JSON.stringify($))}}}}}for(let I of w)R(I);if(t?.signal?.aborted)throw new Error("Request was aborted");if(s.stopReason==="aborted")throw new Error("Request was aborted");if(s.stopReason==="error")throw new Error(s.errorMessage||"Provider returned an error stop reason");n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let a of s.content)delete a.index,delete a.partialArgs,delete a.streamIndex;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=o instanceof Error?o.message:JSON.stringify(o);let r=o?.error?.metadata?.raw;r&&(s.errorMessage+=`
|
|
31
|
+
${r}`),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},Fb=(i,e,t)=>{let n=t?.apiKey||ne(i.provider);if(!n)throw new Error(`No API key for provider: ${i.provider}`);let s=Me(i,t,n),o=t?.reasoning?Ce(i,t.reasoning):void 0,r=o==="off"?void 0:o,a=t?.toolChoice;return su(i,e,{...s,reasoningEffort:r,toolChoice:a})}});var uu={};Et(uu,{streamOpenAIResponses:()=>du,streamSimpleOpenAIResponses:()=>ev});import Yb from"openai";function cu(i){return i||(typeof process<"u"&&process.env.PI_CACHE_RETENTION==="long"?"long":"short")}function pu(i){return{sendSessionIdHeader:i.compat?.sendSessionIdHeader??!0,supportsLongCacheRetention:i.compat?.supportsLongCacheRetention??!0}}function Zb(i,e){return e==="long"&&i.supportsLongCacheRetention?"24h":void 0}function tv(i,e,t,n,s){if(!t){if(!process.env.OPENAI_API_KEY)throw new Error("OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.");t=process.env.OPENAI_API_KEY}let o=pu(i),r={...i.headers};if(i.provider==="github-copilot"){let l=Vn(e.messages),c=Qn({messages:e.messages,hasImages:l});Object.assign(r,c)}s&&(o.sendSessionIdHeader&&(r.session_id=s),r["x-client-request-id"]=s),n&&Object.assign(r,n);let a=i.provider==="cloudflare-ai-gateway"?{...r,Authorization:r.Authorization??null,"cf-aig-authorization":`Bearer ${t}`}:r;return new Yb({apiKey:t,baseURL:So(i.provider)?qn(i):i.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:a})}function nv(i,e,t){let n=fn(i,e,Xb),s=cu(t?.cacheRetention),o=pu(i),r={model:i.id,input:n,stream:!0,prompt_cache_key:s==="none"?void 0:t?.sessionId,prompt_cache_retention:Zb(o,s),store:!1};if(t?.maxTokens&&(r.max_output_tokens=t?.maxTokens),t?.temperature!==void 0&&(r.temperature=t?.temperature),t?.serviceTier!==void 0&&(r.service_tier=t.serviceTier),e.tools&&e.tools.length>0&&(r.tools=Yn(e.tools)),i.reasoning)if(t?.reasoningEffort||t?.reasoningSummary){let a=t?.reasoningEffort?i.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort:"medium";r.reasoning={effort:a,summary:t?.reasoningSummary||"auto"},r.include=["reasoning.encrypted_content"]}else i.provider!=="github-copilot"&&i.thinkingLevelMap?.off!==null&&(r.reasoning={effort:i.thinkingLevelMap?.off??"none"});return r}function iv(i,e){switch(e){case"flex":return .5;case"priority":return i.id==="gpt-5.5"?2.5:2;default:return 1}}function sv(i,e,t){let n=iv(t,e);n!==1&&(i.cost.input*=n,i.cost.output*=n,i.cost.cacheRead*=n,i.cost.cacheWrite*=n,i.cost.total=i.cost.input+i.cost.output+i.cost.cacheRead+i.cost.cacheWrite)}var Xb,du,ev,mu=te(()=>{"use strict";pt();Ze();et();gn();To();Co();Ao();Ot();Xb=new Set(["openai","openai-codex","opencode"]);du=(i,e,t)=>{let n=new de;return(async()=>{let s={role:"assistant",content:[],api:i.api,provider:i.provider,model:i.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o=t?.apiKey||ne(i.provider)||"",a=cu(t?.cacheRetention)==="none"?void 0:t?.sessionId,l=tv(i,e,o,t?.headers,a),c=nv(i,e,t),d=await t?.onPayload?.(c,i);d!==void 0&&(c=d);let p={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},...t?.maxRetries!==void 0?{maxRetries:t.maxRetries}:{}},{data:u,response:h}=await l.responses.create(c,p).withResponse();if(await t?.onResponse?.({status:h.status,headers:He(h.headers)},i),n.push({type:"start",partial:s}),await xn(u,s,n,i,{serviceTier:t?.serviceTier,applyServiceTierPricing:(m,g)=>sv(m,g,i)}),t?.signal?.aborted)throw new Error("Request was aborted");if(s.stopReason==="aborted"||s.stopReason==="error")throw new Error("An unknown error occurred");n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let r of s.content)delete r.index,delete r.partialJson;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=o instanceof Error?o.message:JSON.stringify(o),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},ev=(i,e,t)=>{let n=t?.apiKey||ne(i.provider);if(!n)throw new Error(`No API key for provider: ${i.provider}`);let s=Me(i,t,n),o=t?.reasoning?Ce(i,t.reasoning):void 0;return du(i,e,{...s,reasoningEffort:o==="off"?void 0:o})}});import{spawn as _g}from"child_process";import{readdirSync as Lg,statSync as Kc}from"fs";import{homedir as zc}from"os";import{basename as Nr,dirname as Ys,join as Gt}from"path";function Js(i,e){let t=i.toLowerCase(),n=e.toLowerCase(),s=d=>{if(d.length===0)return{matches:!0,score:0};if(d.length>n.length)return{matches:!1,score:0};let p=0,u=0,h=-1,m=0;for(let g=0;g<n.length&&p<d.length;g++)if(n[g]===d[p]){let x=g===0||/[\s\-_./:]/.test(n[g-1]);h===g-1?(m++,u-=m*5):(m=0,h>=0&&(u+=(g-h-1)*2)),x&&(u-=10),u+=g*.1,h=g,p++}return p<d.length?{matches:!1,score:0}:(d===n&&(u-=100),{matches:!0,score:u})},o=s(t);if(o.matches)return o;let r=t.match(/^(?<letters>[a-z]+)(?<digits>[0-9]+)$/),a=t.match(/^(?<digits>[0-9]+)(?<letters>[a-z]+)$/),l=r?`${r.groups?.digits??""}${r.groups?.letters??""}`:a?`${a.groups?.letters??""}${a.groups?.digits??""}`:"";if(!l)return o;let c=s(l);return c.matches?{matches:!0,score:c.score+5}:o}function We(i,e,t){if(!e.trim())return i;let n=e.trim().split(/\s+/).filter(o=>o.length>0);if(n.length===0)return i;let s=[];for(let o of i){let r=t(o),a=0,l=!0;for(let c of n){let d=Js(c,r);if(d.matches)a+=d.score;else{l=!1;break}}l&&s.push({item:o,totalScore:a})}return s.sort((o,r)=>o.totalScore-r.totalScore),s.map(o=>o.item)}var Jc=new Set([" "," ",'"',"'","="]);function an(i){return i.replace(/\\/g,"/")}function Wg(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Og(i){let e=an(i);if(!e.includes("/"))return e;let t=e.endsWith("/"),n=e.replace(/^\/+|\/+$/g,"");if(!n)return e;let s="[\\\\/]",o=n.split("/").filter(Boolean).map(a=>Wg(a));if(o.length===0)return e;let r=o.join(s);return t&&(r+=s),r}function Hc(i){for(let e=i.length-1;e>=0;e-=1)if(Jc.has(i[e]??""))return e;return-1}function Ug(i){let e=!1,t=-1;for(let n=0;n<i.length;n+=1)i[n]==='"'&&(e=!e,e&&(t=n));return e?t:null}function jc(i,e){return e===0||Jc.has(i[e-1]??"")}function qc(i){let e=Ug(i);return e===null?null:e>0&&i[e-1]==="@"?jc(i,e-1)?i.slice(e-1):null:jc(i,e)?i.slice(e):null}function Vc(i){return i.startsWith('@"')?{rawPrefix:i.slice(2),isAtPrefix:!0,isQuotedPrefix:!0}:i.startsWith('"')?{rawPrefix:i.slice(1),isAtPrefix:!1,isQuotedPrefix:!0}:i.startsWith("@")?{rawPrefix:i.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:i,isAtPrefix:!1,isQuotedPrefix:!1}}function Qc(i,e){let t=e.isQuotedPrefix||i.includes(" "),n=e.isAtPrefix?"@":"";return t?`${`${n}"`}${i}"`:`${n}${i}`}async function Dg(i,e,t,n,s){let o=["--base-directory",i,"--max-results",String(n),"--type","f","--type","d","--follow","--hidden","--exclude",".git","--exclude",".git/*","--exclude",".git/**"];return an(t).includes("/")&&o.push("--full-path"),t&&o.push(Og(t)),await new Promise(r=>{if(s.aborted){r([]);return}let a=_g(e,o,{stdio:["ignore","pipe","pipe"]}),l="",c=!1,d=u=>{c||(c=!0,s.removeEventListener("abort",p),r(u))},p=()=>{a.exitCode===null&&a.kill("SIGKILL")};s.addEventListener("abort",p,{once:!0}),a.stdout.setEncoding("utf-8"),a.stdout.on("data",u=>{l+=u}),a.on("error",()=>{d([])}),a.on("close",u=>{if(s.aborted||u!==0||!l){d([]);return}let h=l.trim().split(`
|
|
32
|
+
`).filter(Boolean),m=[];for(let g of h){let x=an(g),b=x.endsWith("/"),v=b?x.slice(0,-1):x;v===".git"||v.startsWith(".git/")||v.includes("/.git/")||m.push({path:x,isDirectory:b})}d(m)})})}var zi=class{constructor(e=[],t,n=null){this.commands=e,this.basePath=t,this.fdPath=n}async getSuggestions(e,t,n,s){let r=(e[t]||"").slice(0,n),a=this.extractAtPrefix(r);if(a){let{rawPrefix:d,isQuotedPrefix:p}=Vc(a),u=await this.getFuzzyFileSuggestions(d,{isQuotedPrefix:p,signal:s.signal});return u.length===0?null:{items:u,prefix:a}}if(!s.force&&r.startsWith("/")){let d=r.indexOf(" ");if(d===-1){let g=r.slice(1),x=this.commands.map(v=>{let w="name"in v?v.name:v.value,C="argumentHint"in v&&v.argumentHint?v.argumentHint:void 0,R=v.description??"",k=C?R?`${C} \u2014 ${R}`:C:R;return{name:w,label:w,description:k||void 0}}),b=We(x,g,v=>v.name).map(v=>({value:v.name,label:v.label,...v.description&&{description:v.description}}));return b.length===0?null:{items:b,prefix:r}}let p=r.slice(1,d),u=r.slice(d+1),h=this.commands.find(g=>("name"in g?g.name:g.value)===p);if(!h||!("getArgumentCompletions"in h)||!h.getArgumentCompletions)return null;let m=await h.getArgumentCompletions(u);return!Array.isArray(m)||m.length===0?null:{items:m,prefix:u}}let l=this.extractPathPrefix(r,s.force??!1);if(l===null)return null;let c=this.getFileSuggestions(l);return c.length===0?null:{items:c,prefix:l}}applyCompletion(e,t,n,s,o){let r=e[t]||"",a=r.slice(0,n-o.length),l=r.slice(n),c=o.startsWith('"')||o.startsWith('@"'),d=l.startsWith('"'),p=s.value.endsWith('"'),u=c&&p&&d?l.slice(1):l;if(o.startsWith("/")&&a.trim()===""&&!o.slice(1).includes("/")){let C=`${a}/${s.value} ${u}`,R=[...e];return R[t]=C,{lines:R,cursorLine:t,cursorCol:a.length+s.value.length+2}}if(o.startsWith("@")){let C=s.label.endsWith("/"),R=C?"":" ",k=`${a+s.value}${R}${u}`,A=[...e];A[t]=k;let S=s.value.endsWith('"'),I=C&&S?s.value.length-1:s.value.length;return{lines:A,cursorLine:t,cursorCol:a.length+I+R.length}}let m=r.slice(0,n);if(m.includes("/")&&m.includes(" ")){let C=a+s.value+u,R=[...e];R[t]=C;let k=s.label.endsWith("/"),A=s.value.endsWith('"'),S=k&&A?s.value.length-1:s.value.length;return{lines:R,cursorLine:t,cursorCol:a.length+S}}let g=a+s.value+u,x=[...e];x[t]=g;let b=s.label.endsWith("/"),v=s.value.endsWith('"'),w=b&&v?s.value.length-1:s.value.length;return{lines:x,cursorLine:t,cursorCol:a.length+w}}extractAtPrefix(e){let t=qc(e);if(t?.startsWith('@"'))return t;let n=Hc(e),s=n===-1?0:n+1;return e[s]==="@"?e.slice(s):null}extractPathPrefix(e,t=!1){let n=qc(e);if(n)return n;let s=Hc(e),o=s===-1?e:e.slice(s+1);return t||o.includes("/")||o.startsWith(".")||o.startsWith("~/")||o===""&&e.endsWith(" ")?o:null}expandHomePath(e){if(e.startsWith("~/")){let t=Gt(zc(),e.slice(2));return e.endsWith("/")&&!t.endsWith("/")?`${t}/`:t}else if(e==="~")return zc();return e}resolveScopedFuzzyQuery(e){let t=an(e),n=t.lastIndexOf("/");if(n===-1)return null;let s=t.slice(0,n+1),o=t.slice(n+1),r;s.startsWith("~/")?r=this.expandHomePath(s):s.startsWith("/")?r=s:r=Gt(this.basePath,s);try{if(!Kc(r).isDirectory())return null}catch{return null}return{baseDir:r,query:o,displayBase:s}}scopedPathForDisplay(e,t){let n=an(t);return e==="/"?`/${n}`:`${an(e)}${n}`}getFileSuggestions(e){try{let t,n,{rawPrefix:s,isAtPrefix:o,isQuotedPrefix:r}=Vc(e),a=s;if(a.startsWith("~")&&(a=this.expandHomePath(a)),s===""||s==="./"||s==="../"||s==="~"||s==="~/"||s==="/"||o&&s==="")s.startsWith("~")||a.startsWith("/")?t=a:t=Gt(this.basePath,a),n="";else if(s.endsWith("/"))s.startsWith("~")||a.startsWith("/")?t=a:t=Gt(this.basePath,a),n="";else{let p=Ys(a),u=Nr(a);s.startsWith("~")||a.startsWith("/")?t=p:t=Gt(this.basePath,p),n=u}let c=Lg(t,{withFileTypes:!0}),d=[];for(let p of c){if(!p.name.toLowerCase().startsWith(n.toLowerCase()))continue;let u=p.isDirectory();if(!u&&p.isSymbolicLink())try{let v=Gt(t,p.name);u=Kc(v).isDirectory()}catch{}let h,m=p.name,g=s;if(g.endsWith("/"))h=g+m;else if(g.includes("/")||g.includes("\\"))if(g.startsWith("~/")){let v=g.slice(2),w=Ys(v);h=`~/${w==="."?m:Gt(w,m)}`}else if(g.startsWith("/")){let v=Ys(g);v==="/"?h=`/${m}`:h=`${v}/${m}`}else h=Gt(Ys(g),m),g.startsWith("./")&&!h.startsWith("./")&&(h=`./${h}`);else g.startsWith("~")?h=`~/${m}`:h=m;h=an(h);let x=u?`${h}/`:h,b=Qc(x,{isDirectory:u,isAtPrefix:o,isQuotedPrefix:r});d.push({value:b,label:m+(u?"/":"")})}return d.sort((p,u)=>{let h=p.value.endsWith("/"),m=u.value.endsWith("/");return h&&!m?-1:!h&&m?1:p.label.localeCompare(u.label)}),d}catch{return[]}}scoreEntry(e,t,n){let o=Nr(e).toLowerCase(),r=t.toLowerCase(),a=0;return o===r?a=100:o.startsWith(r)?a=80:o.includes(r)?a=50:e.toLowerCase().includes(r)&&(a=30),n&&a>0&&(a+=10),a}async getFuzzyFileSuggestions(e,t){if(!this.fdPath||t.signal.aborted)return[];try{let n=this.resolveScopedFuzzyQuery(e),s=n?.baseDir??this.basePath,o=n?.query??e,r=await Dg(s,this.fdPath,o,100,t.signal);if(t.signal.aborted)return[];let a=r.map(d=>({...d,score:o?this.scoreEntry(d.path,o,d.isDirectory):1})).filter(d=>d.score>0);a.sort((d,p)=>p.score-d.score);let l=a.slice(0,20),c=[];for(let{path:d,isDirectory:p}of l){let u=p?d.slice(0,-1):d,h=n?this.scopedPathForDisplay(n.displayBase,u):u,m=Nr(u),g=p?`${h}/`:h,x=Qc(g,{isDirectory:p,isAtPrefix:!0,isQuotedPrefix:t.isQuotedPrefix});c.push({value:x,label:m+(p?"/":""),description:h})}return c}catch{return[]}}shouldTriggerFileCompletion(e,t,n){let o=(e[t]||"").slice(0,n);return!(o.trim().startsWith("/")&&!o.trim().includes(" "))}};import{eastAsianWidth as Yc}from"get-east-asian-width";var It=new Intl.Segmenter(void 0,{granularity:"grapheme"});function Xs(){return It}function Fg(i){let e=i.codePointAt(0);return e>=126976&&e<=130047||e>=8960&&e<=9215||e>=9728&&e<=10175||e>=11088&&e<=11093||i.includes("\uFE0F")||i.length>2}var $g=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),Bg=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),Ng=new RegExp("^\\p{RGI_Emoji}$","v"),Gg=512,Hi=new Map;function zr(i){for(let e=0;e<i.length;e++){let t=i.charCodeAt(e);if(t<32||t>126)return!1}return!0}function Kg(i,e){if(e<=0||i.length===0)return{text:"",width:0};if(zr(i)){let l=i.slice(0,e);return{text:l,width:l.length}}let t=i.includes("\x1B"),n=i.includes(" ");if(!t&&!n){let l="",c=0;for(let{segment:d}of It.segment(i)){let p=ln(d);if(c+p>e)break;l+=d,c+=p}return{text:l,width:c}}let s="",o=0,r=0,a="";for(;r<i.length;){let l=Ge(i,r);if(l){a+=l.code,r+=l.length;continue}if(i[r]===" "){if(o+3>e)break;a&&(s+=a,a=""),s+=" ",o+=3,r++;continue}let c=r;for(;c<i.length&&i[c]!==" "&&!Ge(i,c);)c++;for(let{segment:d}of It.segment(i.slice(r,c))){let p=ln(d);if(o+p>e)return{text:s,width:o};a&&(s+=a,a=""),s+=d,o+=p}r=c}return{text:s,width:o}}function Gr(i,e,t,n,s,o){let r="\x1B[0m",a=e+n,l;return t.length>0?l=`${i}${r}${t}${r}`:l=`${i}${r}`,o?l+" ".repeat(Math.max(0,s-a)):l}function ln(i){if($g.test(i))return 0;if(Fg(i)&&Ng.test(i))return 2;let t=i.replace(Bg,"").codePointAt(0);if(t===void 0)return 0;if(t>=127462&&t<=127487)return 2;let n=Yc(t);if(i.length>1)for(let s of i.slice(1)){let o=s.codePointAt(0);o>=65280&&o<=65519?n+=Yc(o):(o===3635||o===3763)&&(n+=1)}return n}function W(i){if(i.length===0)return 0;if(zr(i))return i.length;let e=Hi.get(i);if(e!==void 0)return e;let t=i;if(i.includes(" ")&&(t=t.replace(/\t/g," ")),t.includes("\x1B")){let s="",o=0;for(;o<t.length;){let r=Ge(t,o);if(r){o+=r.length;continue}s+=t[o],o++}t=s}let n=0;for(let{segment:s}of It.segment(t))n+=ln(s);if(Hi.size>=Gg){let s=Hi.keys().next().value;s!==void 0&&Hi.delete(s)}return Hi.set(i,n),n}var zg=/[\u0e33\u0eb3]/,Hg=/[\u0e33\u0eb3]/g;function Xc(i){return zg.test(i)?i.replace(Hg,e=>e==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2"):i}function Ge(i,e){if(e>=i.length||i[e]!=="\x1B")return null;let t=i[e+1];if(t==="["){let n=e+2;for(;n<i.length&&!/[mGKHJ]/.test(i[n]);)n++;return n<i.length?{code:i.substring(e,n+1),length:n+1-e}:null}if(t==="]"){let n=e+2;for(;n<i.length;){if(i[n]==="\x07")return{code:i.substring(e,n+1),length:n+1-e};if(i[n]==="\x1B"&&i[n+1]==="\\")return{code:i.substring(e,n+2),length:n+2-e};n++}return null}if(t==="_"){let n=e+2;for(;n<i.length;){if(i[n]==="\x07")return{code:i.substring(e,n+1),length:n+1-e};if(i[n]==="\x1B"&&i[n+1]==="\\")return{code:i.substring(e,n+2),length:n+2-e};n++}return null}return null}function jg(i){if(!i.startsWith("\x1B]8;"))return;let e=i.endsWith("\x07")?"\x07":"\x1B\\",t=i.slice(4,e==="\x07"?-1:-2),n=t.indexOf(";");if(n===-1)return;let s=t.slice(0,n),o=t.slice(n+1);return o?{params:s,url:o,terminator:e}:null}function qg(i){return`\x1B]8;${i.params};${i.url}${i.terminator}`}function Vg(i){return`\x1B]8;;${i}`}var ji=class{constructor(){this.bold=!1;this.dim=!1;this.italic=!1;this.underline=!1;this.blink=!1;this.inverse=!1;this.hidden=!1;this.strikethrough=!1;this.fgColor=null;this.bgColor=null;this.activeHyperlink=null}process(e){let t=jg(e);if(t!==void 0){this.activeHyperlink=t;return}if(!e.endsWith("m"))return;let n=e.match(/\x1b\[([\d;]*)m/);if(!n)return;let s=n[1];if(s===""||s==="0"){this.reset();return}let o=s.split(";"),r=0;for(;r<o.length;){let a=Number.parseInt(o[r],10);if(a===38||a===48){if(o[r+1]==="5"&&o[r+2]!==void 0){let l=`${o[r]};${o[r+1]};${o[r+2]}`;a===38?this.fgColor=l:this.bgColor=l,r+=3;continue}else if(o[r+1]==="2"&&o[r+4]!==void 0){let l=`${o[r]};${o[r+1]};${o[r+2]};${o[r+3]};${o[r+4]}`;a===38?this.fgColor=l:this.bgColor=l,r+=5;continue}}switch(a){case 0:this.reset();break;case 1:this.bold=!0;break;case 2:this.dim=!0;break;case 3:this.italic=!0;break;case 4:this.underline=!0;break;case 5:this.blink=!0;break;case 7:this.inverse=!0;break;case 8:this.hidden=!0;break;case 9:this.strikethrough=!0;break;case 21:this.bold=!1;break;case 22:this.bold=!1,this.dim=!1;break;case 23:this.italic=!1;break;case 24:this.underline=!1;break;case 25:this.blink=!1;break;case 27:this.inverse=!1;break;case 28:this.hidden=!1;break;case 29:this.strikethrough=!1;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:a>=30&&a<=37||a>=90&&a<=97?this.fgColor=String(a):(a>=40&&a<=47||a>=100&&a<=107)&&(this.bgColor=String(a));break}r++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let e=[];this.bold&&e.push("1"),this.dim&&e.push("2"),this.italic&&e.push("3"),this.underline&&e.push("4"),this.blink&&e.push("5"),this.inverse&&e.push("7"),this.hidden&&e.push("8"),this.strikethrough&&e.push("9"),this.fgColor&&e.push(this.fgColor),this.bgColor&&e.push(this.bgColor);let t=e.length>0?`\x1B[${e.join(";")}m`:"";return this.activeHyperlink&&(t+=qg(this.activeHyperlink)),t}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let e="";return this.underline&&(e+="\x1B[24m"),this.activeHyperlink&&(e+=Vg(this.activeHyperlink.terminator)),e}};function Zc(i,e){let t=0;for(;t<i.length;){let n=Ge(i,t);n?(e.process(n.code),t+=n.length):t++}}function Qg(i){let e=[],t="",n="",s=!1,o=0;for(;o<i.length;){let r=Ge(i,o);if(r){n+=r.code,o+=r.length;continue}let a=i[o],l=a===" ";l!==s&&t&&(e.push(t),t=""),n&&(t+=n,n=""),s=l,t+=a,o++}return n&&(t+=n),t&&e.push(t),e}function ct(i,e){if(!i)return[""];let t=i.split(`
|
|
33
|
+
`),n=[],s=new ji;for(let o of t){let r=n.length>0?s.getActiveCodes():"";n.push(...Jg(r+o,e)),Zc(o,s)}return n.length>0?n:[""]}function Jg(i,e){if(!i)return[""];if(W(i)<=e)return[i];let n=[],s=new ji,o=Qg(i),r="",a=0;for(let l of o){let c=W(l),d=l.trim()==="";if(c>e&&!d){if(r){let h=s.getLineEndReset();h&&(r+=h),n.push(r),r="",a=0}let u=Xg(l,e,s);n.push(...u.slice(0,-1)),r=u[u.length-1],a=W(r);continue}if(a+c>e&&a>0){let u=r.trimEnd(),h=s.getLineEndReset();h&&(u+=h),n.push(u),d?(r=s.getActiveCodes(),a=0):(r=s.getActiveCodes()+l,a=c)}else r+=l,a+=c;Zc(l,s)}return r&&n.push(r),n.length>0?n.map(l=>l.trimEnd()):[""]}var Yg=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function Oe(i){return/\s/.test(i)}function Ue(i){return Yg.test(i)}function Xg(i,e,t){let n=[],s=t.getActiveCodes(),o=0,r=0,a=[];for(;r<i.length;){let l=Ge(i,r);if(l)a.push({type:"ansi",value:l.code}),r+=l.length;else{let c=r;for(;c<i.length&&!Ge(i,c);)c++;let d=i.slice(r,c);for(let p of It.segment(d))a.push({type:"grapheme",value:p.segment});r=c}}for(let l of a){if(l.type==="ansi"){s+=l.value,t.process(l.value);continue}let c=l.value;if(!c)continue;let d=W(c);if(o+d>e){let p=t.getLineEndReset();p&&(s+=p),n.push(s),s=t.getActiveCodes(),o=0}s+=c,o+=d}return s&&n.push(s),n.length>0?n:[""]}function Kt(i,e,t){let n=W(i),s=Math.max(0,e-n),o=" ".repeat(s),r=i+o;return t(r)}function G(i,e,t="...",n=!1){if(e<=0)return"";if(i.length===0)return n?" ".repeat(e):"";let s=W(t);if(s>=e){let g=W(i);if(g<=e)return n?i+" ".repeat(e-g):i;let x=Kg(t,e);return x.width===0?n?" ".repeat(e):"":Gr("",0,x.text,x.width,e,n)}if(zr(i)){if(i.length<=e)return n?i+" ".repeat(e-i.length):i;let g=e-s;return Gr(i.slice(0,g),g,t,s,e,n)}let o=e-s,r="",a="",l=0,c=0,d=!0,p=!1,u=!1,h=i.includes("\x1B"),m=i.includes(" ");if(!h&&!m){for(let{segment:g}of It.segment(i)){let x=ln(g);if(d&&c+x<=o?(r+=g,c+=x):d=!1,l+=x,l>e){p=!0;break}}u=!p}else{let g=0;for(;g<i.length;){let x=Ge(i,g);if(x){a+=x.code,g+=x.length;continue}if(i[g]===" "){if(d&&c+3<=o?(a&&(r+=a,a=""),r+=" ",c+=3):(d=!1,a=""),l+=3,l>e){p=!0;break}g++;continue}let b=g;for(;b<i.length&&i[b]!==" "&&!Ge(i,b);)b++;for(let{segment:v}of It.segment(i.slice(g,b))){let w=ln(v);if(d&&c+w<=o?(a&&(r+=a,a=""),r+=v,c+=w):(d=!1,a=""),l+=w,l>e){p=!0;break}}if(p)break;g=b}u=g>=i.length}return!p&&u?n?i+" ".repeat(Math.max(0,e-l)):i:Gr(r,c,t,s,e,n)}function Fn(i,e,t,n=!1){return Hr(i,e,t,n).text}function Hr(i,e,t,n=!1){if(t<=0)return{text:"",width:0};let s=e+t,o="",r=0,a=0,l=0,c="";for(;l<i.length;){let d=Ge(i,l);if(d){a>=e&&a<s?o+=d.code:a<e&&(c+=d.code),l+=d.length;continue}let p=l;for(;p<i.length&&!Ge(i,p);)p++;for(let{segment:u}of It.segment(i.slice(l,p))){let h=ln(u),m=a>=e&&a<s,g=!n||a+h<=s;if(m&&g&&(c&&(o+=c,c=""),o+=u,r+=h),a+=h,a>=s)break}if(l=p,a>=s)break}return{text:o,width:r}}var Kr=new ji;function ep(i,e,t,n,s=!1){let o="",r=0,a="",l=0,c=0,d=0,p="",u=!1,h=t+n;for(Kr.clear();d<i.length;){let m=Ge(i,d);if(m){Kr.process(m.code),c<e?p+=m.code:c>=t&&c<h&&u&&(a+=m.code),d+=m.length;continue}let g=d;for(;g<i.length&&!Ge(i,g);)g++;for(let{segment:x}of It.segment(i.slice(d,g))){let b=ln(x);if(c<e?(p&&(o+=p,p=""),o+=x,r+=b):c>=t&&c<h&&(!s||c+b<=h)&&(u||(a+=Kr.getActiveCodes(),u=!0),a+=x,l+=b),c+=b,n<=0?c>=e:c>=h)break}if(d=g,n<=0?c>=e:c>=h)break}return{before:o,beforeWidth:r,after:a,afterWidth:l}}var he=class{constructor(e=1,t=1,n){this.children=[];this.paddingX=e,this.paddingY=t,this.bgFn=n}addChild(e){this.children.push(e),this.invalidateCache()}removeChild(e){let t=this.children.indexOf(e);t!==-1&&(this.children.splice(t,1),this.invalidateCache())}clear(){this.children=[],this.invalidateCache()}setBgFn(e){this.bgFn=e}invalidateCache(){this.cache=void 0}matchCache(e,t,n){let s=this.cache;return!!s&&s.width===e&&s.bgSample===n&&s.childLines.length===t.length&&s.childLines.every((o,r)=>o===t[r])}invalidate(){this.invalidateCache();for(let e of this.children)e.invalidate?.()}render(e){if(this.children.length===0)return[];let t=Math.max(1,e-this.paddingX*2),n=" ".repeat(this.paddingX),s=[];for(let a of this.children){let l=a.render(t);for(let c of l)s.push(n+c)}if(s.length===0)return[];let o=this.bgFn?this.bgFn("test"):void 0;if(this.matchCache(e,s,o))return this.cache.lines;let r=[];for(let a=0;a<this.paddingY;a++)r.push(this.applyBg("",e));for(let a of s)r.push(this.applyBg(a,e));for(let a=0;a<this.paddingY;a++)r.push(this.applyBg("",e));return this.cache={childLines:s,width:e,bgSample:o,lines:r},r}applyBg(e,t){let n=W(e),s=Math.max(0,t-n),o=e+" ".repeat(s);return this.bgFn?Kt(o,t,this.bgFn):o}};var At=!1;function Vi(i){At=i}var cn={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:i=>`ctrl+${i}`,shift:i=>`shift+${i}`,alt:i=>`alt+${i}`,super:i=>`super+${i}`,ctrlShift:i=>`ctrl+shift+${i}`,shiftCtrl:i=>`shift+ctrl+${i}`,ctrlAlt:i=>`ctrl+alt+${i}`,altCtrl:i=>`alt+ctrl+${i}`,shiftAlt:i=>`shift+alt+${i}`,altShift:i=>`alt+shift+${i}`,ctrlSuper:i=>`ctrl+super+${i}`,superCtrl:i=>`super+ctrl+${i}`,shiftSuper:i=>`shift+super+${i}`,superShift:i=>`super+shift+${i}`,altSuper:i=>`alt+super+${i}`,superAlt:i=>`super+alt+${i}`,ctrlShiftAlt:i=>`ctrl+shift+alt+${i}`,ctrlShiftSuper:i=>`ctrl+shift+super+${i}`},ip=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),D={shift:1,alt:2,ctrl:4,super:8},qi=192,J={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},fe={up:-1,down:-2,right:-3,left:-4},ee={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},Zg=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,fe.left],[57418,fe.right],[57419,fe.up],[57420,fe.down],[57421,ee.pageUp],[57422,ee.pageDown],[57423,ee.home],[57424,ee.end],[57425,ee.insert],[57426,ee.delete]]);function jr(i){return Zg.get(i)??i}function no(i,e){return(e&~qi&D.shift)!==0&&i>=65&&i<=90?i+32:i}var Qe={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},ef={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},tf={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]};var De=(i,e)=>e.includes(i),Ke=(i,e,t)=>t===D.shift?De(i,ef[e]):t===D.ctrl?De(i,tf[e]):!1,Zs="press";function qr(i){return i.includes("\x1B[200~")?!1:!!(i.includes(":3u")||i.includes(":3~")||i.includes(":3A")||i.includes(":3B")||i.includes(":3C")||i.includes(":3D")||i.includes(":3H")||i.includes(":3F"))}function eo(i){if(!i)return"press";let e=parseInt(i,10);return e===2?"repeat":e===3?"release":"press"}function nf(i){let e=i.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(e){let o=parseInt(e[1],10),r=e[2]&&e[2].length>0?parseInt(e[2],10):void 0,a=e[3]?parseInt(e[3],10):void 0,l=e[4]?parseInt(e[4],10):1,c=eo(e[5]);return Zs=c,{codepoint:o,shiftedKey:r,baseLayoutKey:a,modifier:l-1,eventType:c}}let t=i.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(t){let o=parseInt(t[1],10),r=eo(t[2]),a={A:-1,B:-2,C:-3,D:-4};return Zs=r,{codepoint:a[t[3]],modifier:o-1,eventType:r}}let n=i.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(n){let o=parseInt(n[1],10),r=n[2]?parseInt(n[2],10):1,a=eo(n[3]),c={2:ee.insert,3:ee.delete,5:ee.pageUp,6:ee.pageDown,7:ee.home,8:ee.end}[o];if(c!==void 0)return Zs=a,{codepoint:c,modifier:r-1,eventType:a}}let s=i.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(s){let o=parseInt(s[1],10),r=eo(s[2]),a=s[3]==="H"?ee.home:ee.end;return Zs=r,{codepoint:a,modifier:o-1,eventType:r}}return null}function K(i,e,t){let n=nf(i);if(!n)return!1;let s=n.modifier&~qi,o=t&~qi;if(s!==o)return!1;let r=no(jr(n.codepoint),n.modifier),a=no(jr(e),t);if(r===a)return!0;if(n.baseLayoutKey!==void 0&&n.baseLayoutKey===e){let l=r,c=l>=97&&l<=122,d=ip.has(String.fromCharCode(l));if(!c&&!d)return!0}return!1}function Vr(i){let e=i.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!e)return null;let t=parseInt(e[1],10);return{codepoint:parseInt(e[2],10),modifier:t-1}}function Je(i,e,t){let n=Vr(i);return n?n.codepoint===e&&n.modifier===t:!1}function sf(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function tp(i,e){return i==="\x7F"?e===0:i!=="\b"?!1:sf()?e===D.ctrl:e===0}function of(i){let e=i.toLowerCase(),t=e.charCodeAt(0);return t>=97&&t<=122||e==="["||e==="\\"||e==="]"||e==="_"?String.fromCharCode(t&31):e==="-"?"":null}function np(i){return i>="0"&&i<="9"}function to(i,e,t){if(t===0)return!1;let n=Vr(i);return!n||n.modifier!==t?!1:no(n.codepoint,n.modifier)===no(e,t)}function rf(i){let e=i.toLowerCase().split("+"),t=e[e.length-1];return t?{key:t,ctrl:e.includes("ctrl"),shift:e.includes("shift"),alt:e.includes("alt"),super:e.includes("super")}:null}function ge(i,e){let t=rf(e);if(!t)return!1;let{key:n,ctrl:s,shift:o,alt:r,super:a}=t,l=0;switch(o&&(l|=D.shift),r&&(l|=D.alt),s&&(l|=D.ctrl),a&&(l|=D.super),n){case"escape":case"esc":return l!==0?!1:i==="\x1B"||K(i,J.escape,0)||Je(i,J.escape,0);case"space":return!At&&(l===D.ctrl&&i==="\0"||l===D.alt&&i==="\x1B ")?!0:l===0?i===" "||K(i,J.space,0)||Je(i,J.space,0):K(i,J.space,l)||Je(i,J.space,l);case"tab":return l===D.shift?i==="\x1B[Z"||K(i,J.tab,D.shift)||Je(i,J.tab,D.shift):l===0?i===" "||K(i,J.tab,0):K(i,J.tab,l)||Je(i,J.tab,l);case"enter":case"return":return l===D.shift?K(i,J.enter,D.shift)||K(i,J.kpEnter,D.shift)||Je(i,J.enter,D.shift)?!0:At?i==="\x1B\r"||i===`
|
|
34
|
+
`:!1:l===D.alt?K(i,J.enter,D.alt)||K(i,J.kpEnter,D.alt)||Je(i,J.enter,D.alt)?!0:At?!1:i==="\x1B\r":l===0?i==="\r"||!At&&i===`
|
|
35
|
+
`||i==="\x1BOM"||K(i,J.enter,0)||K(i,J.kpEnter,0):K(i,J.enter,l)||K(i,J.kpEnter,l)||Je(i,J.enter,l);case"backspace":return l===D.alt?i==="\x1B\x7F"||i==="\x1B\b"?!0:K(i,J.backspace,D.alt)||Je(i,J.backspace,D.alt):l===D.ctrl?tp(i,D.ctrl)?!0:K(i,J.backspace,D.ctrl)||Je(i,J.backspace,D.ctrl):l===0?tp(i,0)||K(i,J.backspace,0)||Je(i,J.backspace,0):K(i,J.backspace,l)||Je(i,J.backspace,l);case"insert":return l===0?De(i,Qe.insert)||K(i,ee.insert,0):Ke(i,"insert",l)?!0:K(i,ee.insert,l);case"delete":return l===0?De(i,Qe.delete)||K(i,ee.delete,0):Ke(i,"delete",l)?!0:K(i,ee.delete,l);case"clear":return l===0?De(i,Qe.clear):Ke(i,"clear",l);case"home":return l===0?De(i,Qe.home)||K(i,ee.home,0):Ke(i,"home",l)?!0:K(i,ee.home,l);case"end":return l===0?De(i,Qe.end)||K(i,ee.end,0):Ke(i,"end",l)?!0:K(i,ee.end,l);case"pageup":return l===0?De(i,Qe.pageUp)||K(i,ee.pageUp,0):Ke(i,"pageUp",l)?!0:K(i,ee.pageUp,l);case"pagedown":return l===0?De(i,Qe.pageDown)||K(i,ee.pageDown,0):Ke(i,"pageDown",l)?!0:K(i,ee.pageDown,l);case"up":return l===D.alt?i==="\x1Bp"||K(i,fe.up,D.alt):l===0?De(i,Qe.up)||K(i,fe.up,0):Ke(i,"up",l)?!0:K(i,fe.up,l);case"down":return l===D.alt?i==="\x1Bn"||K(i,fe.down,D.alt):l===0?De(i,Qe.down)||K(i,fe.down,0):Ke(i,"down",l)?!0:K(i,fe.down,l);case"left":return l===D.alt?i==="\x1B[1;3D"||!At&&i==="\x1BB"||i==="\x1Bb"||K(i,fe.left,D.alt):l===D.ctrl?i==="\x1B[1;5D"||Ke(i,"left",D.ctrl)||K(i,fe.left,D.ctrl):l===0?De(i,Qe.left)||K(i,fe.left,0):Ke(i,"left",l)?!0:K(i,fe.left,l);case"right":return l===D.alt?i==="\x1B[1;3C"||!At&&i==="\x1BF"||i==="\x1Bf"||K(i,fe.right,D.alt):l===D.ctrl?i==="\x1B[1;5C"||Ke(i,"right",D.ctrl)||K(i,fe.right,D.ctrl):l===0?De(i,Qe.right)||K(i,fe.right,0):Ke(i,"right",l)?!0:K(i,fe.right,l);case"f1":case"f2":case"f3":case"f4":case"f5":case"f6":case"f7":case"f8":case"f9":case"f10":case"f11":case"f12":return l!==0?!1:De(i,Qe[n])}if(n.length===1&&(n>="a"&&n<="z"||np(n)||ip.has(n))){let c=n.charCodeAt(0),d=of(n),p=n>="a"&&n<="z",u=np(n);return l===D.ctrl+D.alt&&!At&&d&&i===`\x1B${d}`||l===D.alt&&!At&&(p||u)&&i===`\x1B${n}`?!0:l===D.ctrl?d&&i===d?!0:K(i,c,D.ctrl)||to(i,c,D.ctrl):l===D.shift+D.ctrl?K(i,c,D.shift+D.ctrl)||to(i,c,D.shift+D.ctrl):l===D.shift?p&&i===n.toUpperCase()?!0:K(i,c,D.shift)||to(i,c,D.shift):l!==0?K(i,c,l)||to(i,c,l):i===n||K(i,c,0)}return!1}var af=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,lf=D.shift|qi;function io(i){let e=i.match(af);if(!e)return;let t=Number.parseInt(e[1]??"",10);if(!Number.isFinite(t))return;let n=e[2]&&e[2].length>0?Number.parseInt(e[2],10):void 0,s=e[4]?Number.parseInt(e[4],10):1,o=Number.isFinite(s)?s-1:0;if((o&~lf)!==0||o&(D.alt|D.ctrl))return;let r=t;if(o&D.shift&&typeof n=="number"&&(r=n),r=jr(r),!(!Number.isFinite(r)||r<32))try{return String.fromCodePoint(r)}catch{return}}function cf(i){let e=Vr(i);if(!(!e||(e.modifier&~qi&~D.shift)!==0)&&!(!Number.isFinite(e.codepoint)||e.codepoint<32))try{return String.fromCodePoint(e.codepoint)}catch{return}}function Qr(i){return io(i)??cf(i)}var oo={"tui.editor.cursorUp":{defaultKeys:"up",description:"Move cursor up"},"tui.editor.cursorDown":{defaultKeys:"down",description:"Move cursor down"},"tui.editor.cursorLeft":{defaultKeys:["left","ctrl+b"],description:"Move cursor left"},"tui.editor.cursorRight":{defaultKeys:["right","ctrl+f"],description:"Move cursor right"},"tui.editor.cursorWordLeft":{defaultKeys:["alt+left","ctrl+left","alt+b"],description:"Move cursor word left"},"tui.editor.cursorWordRight":{defaultKeys:["alt+right","ctrl+right","alt+f"],description:"Move cursor word right"},"tui.editor.cursorLineStart":{defaultKeys:["home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+e"],description:"Move to line end"},"tui.editor.jumpForward":{defaultKeys:"ctrl+]",description:"Jump forward to character"},"tui.editor.jumpBackward":{defaultKeys:"ctrl+alt+]",description:"Jump backward to character"},"tui.editor.pageUp":{defaultKeys:"pageUp",description:"Page up"},"tui.editor.pageDown":{defaultKeys:"pageDown",description:"Page down"},"tui.editor.deleteCharBackward":{defaultKeys:"backspace",description:"Delete character backward"},"tui.editor.deleteCharForward":{defaultKeys:["delete","ctrl+d"],description:"Delete character forward"},"tui.editor.deleteWordBackward":{defaultKeys:["ctrl+w","alt+backspace"],description:"Delete word backward"},"tui.editor.deleteWordForward":{defaultKeys:["alt+d","alt+delete"],description:"Delete word forward"},"tui.editor.deleteToLineStart":{defaultKeys:"ctrl+u",description:"Delete to line start"},"tui.editor.deleteToLineEnd":{defaultKeys:"ctrl+k",description:"Delete to line end"},"tui.editor.yank":{defaultKeys:"ctrl+y",description:"Yank"},"tui.editor.yankPop":{defaultKeys:"alt+y",description:"Yank pop"},"tui.editor.undo":{defaultKeys:"ctrl+-",description:"Undo"},"tui.input.newLine":{defaultKeys:"shift+enter",description:"Insert newline"},"tui.input.submit":{defaultKeys:"enter",description:"Submit input"},"tui.input.tab":{defaultKeys:"tab",description:"Tab / autocomplete"},"tui.input.copy":{defaultKeys:"ctrl+c",description:"Copy selection"},"tui.select.up":{defaultKeys:"up",description:"Move selection up"},"tui.select.down":{defaultKeys:"down",description:"Move selection down"},"tui.select.pageUp":{defaultKeys:"pageUp",description:"Selection page up"},"tui.select.pageDown":{defaultKeys:"pageDown",description:"Selection page down"},"tui.select.confirm":{defaultKeys:"enter",description:"Confirm selection"},"tui.select.cancel":{defaultKeys:["escape","ctrl+c"],description:"Cancel selection"}};function Jr(i){if(i===void 0)return[];let e=Array.isArray(i)?i:[i],t=new Set,n=[];for(let s of e)t.has(s)||(t.add(s),n.push(s));return n}var $n=class{constructor(e,t={}){this.keysById=new Map;this.conflicts=[];this.definitions=e,this.userBindings=t,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let e=new Map;for(let[t,n]of Object.entries(this.userBindings))if(t in this.definitions)for(let s of Jr(n)){let o=e.get(s)??new Set;o.add(t),e.set(s,o)}for(let[t,n]of e)n.size>1&&this.conflicts.push({key:t,keybindings:[...n]});for(let[t,n]of Object.entries(this.definitions)){let s=this.userBindings[t],o=Jr(s===void 0?n.defaultKeys:s);this.keysById.set(t,o)}}matches(e,t){let n=this.keysById.get(t)??[];for(let s of n)if(ge(e,s))return!0;return!1}getKeys(e){return[...this.keysById.get(e)??[]]}getDefinition(e){return this.definitions[e]}getConflicts(){return this.conflicts.map(e=>({...e,keybindings:[...e.keybindings]}))}setUserBindings(e){this.userBindings=e,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let e={};for(let t of Object.keys(this.definitions)){let n=this.keysById.get(t)??[];e[t]=n.length===1?n[0]:[...n]}return e}},so=null;function Qi(i){so=i}function V(){return so||(so=new $n(oo)),so}var T=class{constructor(e="",t=1,n=1,s){this.text=e,this.paddingX=t,this.paddingY=n,this.customBgFn=s}setText(e){this.text=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setCustomBgFn(e){this.customBgFn=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;if(!this.text||this.text.trim()===""){let p=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=p,p}let t=this.text.replace(/\t/g," "),n=Math.max(1,e-this.paddingX*2),s=ct(t,n),o=" ".repeat(this.paddingX),r=" ".repeat(this.paddingX),a=[];for(let p of s){let u=o+p+r;if(this.customBgFn)a.push(Kt(u,e,this.customBgFn));else{let h=W(u),m=Math.max(0,e-h);a.push(u+" ".repeat(m))}}let l=" ".repeat(e),c=[];for(let p=0;p<this.paddingY;p++){let u=this.customBgFn?Kt(l,e,this.customBgFn):l;c.push(u)}let d=[...c,...a,...c];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=d,d.length>0?d:[""]}};var sp=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],op=80,Fe=class extends T{constructor(t,n,s,o="Loading...",r){super("",1,0);this.spinnerColorFn=n;this.messageColorFn=s;this.message=o;this.frames=[...sp];this.intervalMs=op;this.currentFrame=0;this.intervalId=null;this.ui=null;this.renderIndicatorVerbatim=!1;this.ui=t,this.setIndicator(r)}render(t){return["",...super.render(t)]}start(){this.updateDisplay(),this.restartAnimation()}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}setMessage(t){this.message=t,this.updateDisplay()}setIndicator(t){this.renderIndicatorVerbatim=t!==void 0,this.frames=t?.frames!==void 0?[...t.frames]:[...sp],this.intervalMs=t?.intervalMs&&t.intervalMs>0?t.intervalMs:op,this.currentFrame=0,this.start()}restartAnimation(){this.stop(),!(this.frames.length<=1)&&(this.intervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay()},this.intervalMs))}updateDisplay(){let t=this.frames[this.currentFrame]??"",n=this.renderIndicatorVerbatim?t:this.spinnerColorFn(t),s=t.length>0?`${n} `:"";this.setText(`${s}${this.messageColorFn(this.message)}`),this.ui&&this.ui.requestRender()}};var Ji=class extends Fe{constructor(){super(...arguments);this.abortController=new AbortController}get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(t){V().matches(t,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}};var Bn=class{constructor(){this.ring=[]}push(e,t){if(e)if(t.accumulate&&this.ring.length>0){let n=this.ring.pop();this.ring.push(t.prepend?e+n:n+e)}else this.ring.push(e)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let e=this.ring.pop();this.ring.unshift(e)}}get length(){return this.ring.length}};import*as zt from"node:fs";import*as sa from"node:os";import*as Gn from"node:path";import{performance as na}from"node:perf_hooks";var Yr=null,lp={widthPx:9,heightPx:18};function cp(){return lp}function Xr(i){lp=i}function pp(){let i=process.env.TERM_PROGRAM?.toLowerCase()||"",e=process.env.TERM?.toLowerCase()||"",t=process.env.COLORTERM?.toLowerCase()||"";return!!process.env.TMUX||e.startsWith("tmux")||e.startsWith("screen")?{images:null,trueColor:t==="truecolor"||t==="24bit",hyperlinks:!1}:process.env.KITTY_WINDOW_ID||i==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:i==="ghostty"||e.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||i==="wezterm"?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||i==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:i==="vscode"?{images:null,trueColor:!0,hyperlinks:!0}:i==="alacritty"?{images:null,trueColor:!0,hyperlinks:!0}:{images:null,trueColor:t==="truecolor"||t==="24bit",hyperlinks:!1}}function ve(){return Yr||(Yr=pp()),Yr}var rp="\x1B_G",ap="\x1B]1337;File=";function pn(i){return i.startsWith(rp)||i.startsWith(ap)?!0:i.includes(rp)||i.includes(ap)}function Zr(){return Math.floor(Math.random()*4294967294)+1}function dp(i,e={}){let n=["a=T","f=100","q=2"];if(e.moveCursor===!1&&n.push("C=1"),e.columns&&n.push(`c=${e.columns}`),e.rows&&n.push(`r=${e.rows}`),e.imageId&&n.push(`i=${e.imageId}`),i.length<=4096)return`\x1B_G${n.join(",")};${i}\x1B\\`;let s=[],o=0,r=!0;for(;o<i.length;){let a=i.slice(o,o+4096),l=o+4096>=i.length;r?(s.push(`\x1B_G${n.join(",")},m=1;${a}\x1B\\`),r=!1):l?s.push(`\x1B_Gm=0;${a}\x1B\\`):s.push(`\x1B_Gm=1;${a}\x1B\\`),o+=4096}return s.join("")}function ea(i){return`\x1B_Ga=d,d=I,i=${i},q=2\x1B\\`}function up(i,e={}){let t=[`inline=${e.inline!==!1?1:0}`];if(e.width!==void 0&&t.push(`width=${e.width}`),e.height!==void 0&&t.push(`height=${e.height}`),e.name){let n=Buffer.from(e.name).toString("base64");t.push(`name=${n}`)}return e.preserveAspectRatio===!1&&t.push("preserveAspectRatio=0"),`\x1B]1337;File=${t.join(";")}:${i}\x07`}function mp(i,e,t={widthPx:9,heightPx:18}){let s=e*t.widthPx/i.widthPx,o=i.heightPx*s,r=Math.ceil(o/t.heightPx);return Math.max(1,r)}function hp(i){try{let e=Buffer.from(i,"base64");if(e.length<24||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return null;let t=e.readUInt32BE(16),n=e.readUInt32BE(20);return{widthPx:t,heightPx:n}}catch{return null}}function gp(i){try{let e=Buffer.from(i,"base64");if(e.length<2||e[0]!==255||e[1]!==216)return null;let t=2;for(;t<e.length-9;){if(e[t]!==255){t++;continue}let n=e[t+1];if(n>=192&&n<=194){let o=e.readUInt16BE(t+5);return{widthPx:e.readUInt16BE(t+7),heightPx:o}}if(t+3>=e.length)return null;let s=e.readUInt16BE(t+2);if(s<2)return null;t+=2+s}return null}catch{return null}}function fp(i){try{let e=Buffer.from(i,"base64");if(e.length<10)return null;let t=e.slice(0,6).toString("ascii");if(t!=="GIF87a"&&t!=="GIF89a")return null;let n=e.readUInt16LE(6),s=e.readUInt16LE(8);return{widthPx:n,heightPx:s}}catch{return null}}function xp(i){try{let e=Buffer.from(i,"base64");if(e.length<30)return null;let t=e.slice(0,4).toString("ascii"),n=e.slice(8,12).toString("ascii");if(t!=="RIFF"||n!=="WEBP")return null;let s=e.slice(12,16).toString("ascii");if(s==="VP8 "){if(e.length<30)return null;let o=e.readUInt16LE(26)&16383,r=e.readUInt16LE(28)&16383;return{widthPx:o,heightPx:r}}else if(s==="VP8L"){if(e.length<25)return null;let o=e.readUInt32LE(21),r=(o&16383)+1,a=(o>>14&16383)+1;return{widthPx:r,heightPx:a}}else if(s==="VP8X"){if(e.length<30)return null;let o=(e[24]|e[25]<<8|e[26]<<16)+1,r=(e[27]|e[28]<<8|e[29]<<16)+1;return{widthPx:o,heightPx:r}}return null}catch{return null}}function Yi(i,e){return e==="image/png"?hp(i):e==="image/jpeg"?gp(i):e==="image/gif"?fp(i):e==="image/webp"?xp(i):null}function ta(i,e,t={}){let n=ve();if(!n.images)return null;let s=t.maxWidthCells??80,o=mp(e,s,cp());return n.images==="kitty"?{sequence:dp(i,{columns:s,rows:o,imageId:t.imageId,moveCursor:t.moveCursor}),rows:o,imageId:t.imageId}:n.images==="iterm2"?{sequence:up(i,{width:s,height:"auto",preserveAspectRatio:t.preserveAspectRatio??!0}),rows:o}:null}function Xi(i,e){return`\x1B]8;;${e}\x1B\\${i}\x1B]8;;\x1B\\`}function Nn(i,e,t){let n=[];return t&&n.push(t),n.push(`[${i}]`),e&&n.push(`${e.widthPx}x${e.heightPx}`),`[Image: ${n.join(" ")}]`}var bp="\x1B_G";function ia(i){let e=i.indexOf(bp);if(e===-1)return[];let t=e+bp.length,n=i.indexOf(";",t);if(n===-1)return[];let s=i.slice(t,n);for(let o of s.split(",")){let[r,a]=o.split("=",2);if(r!=="i"||a===void 0)continue;let l=Number(a);if(Number.isInteger(l)&&l>0&&l<=4294967295)return[l]}return[]}function oa(i){return i!==null&&"focused"in i}var dn="\x1B_pi:c\x07";function vp(i,e){if(i===void 0)return;if(typeof i=="number")return i;let t=i.match(/^(\d+(?:\.\d+)?)%$/);if(t)return Math.floor(e*parseFloat(t[1])/100)}function pf(){return!!process.env.TERMUX_VERSION}var L=class{constructor(){this.children=[]}addChild(e){this.children.push(e)}removeChild(e){let t=this.children.indexOf(e);t!==-1&&this.children.splice(t,1)}clear(){this.children=[]}invalidate(){for(let e of this.children)e.invalidate?.()}render(e){let t=[];for(let n of this.children){let s=n.render(e);for(let o of s)t.push(o)}return t}},Ht=class i extends L{constructor(t,n){super();this.previousLines=[];this.previousKittyImageIds=new Set;this.previousWidth=0;this.previousHeight=0;this.focusedComponent=null;this.inputListeners=new Set;this.renderRequested=!1;this.lastRenderAt=0;this.cursorRow=0;this.hardwareCursorRow=0;this.showHardwareCursor=process.env.PI_HARDWARE_CURSOR==="1";this.clearOnShrink=process.env.PI_CLEAR_ON_SHRINK==="1";this.maxLinesRendered=0;this.previousViewportTop=0;this.fullRedrawCount=0;this.stopped=!1;this.focusOrderCounter=0;this.overlayStack=[];this.terminal=t,n!==void 0&&(this.showHardwareCursor=n)}static{this.MIN_RENDER_INTERVAL_MS=16}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(t){this.showHardwareCursor!==t&&(this.showHardwareCursor=t,t||this.terminal.hideCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(t){this.clearOnShrink=t}setFocus(t){oa(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=t,oa(t)&&(t.focused=!0)}showOverlay(t,n){let s={component:t,options:n,preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(s),!n?.nonCapturing&&this.isOverlayVisible(s)&&this.setFocus(t),this.terminal.hideCursor(),this.requestRender(),{hide:()=>{let o=this.overlayStack.indexOf(s);if(o!==-1){if(this.overlayStack.splice(o,1),this.focusedComponent===t){let r=this.getTopmostVisibleOverlay();this.setFocus(r?.component??s.preFocus)}this.overlayStack.length===0&&this.terminal.hideCursor(),this.requestRender()}},setHidden:o=>{if(s.hidden!==o){if(s.hidden=o,o){if(this.focusedComponent===t){let r=this.getTopmostVisibleOverlay();this.setFocus(r?.component??s.preFocus)}}else!n?.nonCapturing&&this.isOverlayVisible(s)&&(s.focusOrder=++this.focusOrderCounter,this.setFocus(t));this.requestRender()}},isHidden:()=>s.hidden,focus:()=>{!this.overlayStack.includes(s)||!this.isOverlayVisible(s)||(this.focusedComponent!==t&&this.setFocus(t),s.focusOrder=++this.focusOrderCounter,this.requestRender())},unfocus:()=>{if(this.focusedComponent!==t)return;let o=this.getTopmostVisibleOverlay();this.setFocus(o&&o!==s?o.component:s.preFocus),this.requestRender()},isFocused:()=>this.focusedComponent===t}}hideOverlay(){let t=this.overlayStack.pop();if(t){if(this.focusedComponent===t.component){let n=this.getTopmostVisibleOverlay();this.setFocus(n?.component??t.preFocus)}this.overlayStack.length===0&&this.terminal.hideCursor(),this.requestRender()}}hasOverlay(){return this.overlayStack.some(t=>this.isOverlayVisible(t))}isOverlayVisible(t){return t.hidden?!1:t.options?.visible?t.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){for(let t=this.overlayStack.length-1;t>=0;t--)if(!this.overlayStack[t].options?.nonCapturing&&this.isOverlayVisible(this.overlayStack[t]))return this.overlayStack[t]}invalidate(){super.invalidate();for(let t of this.overlayStack)t.component.invalidate?.()}start(){this.stopped=!1,this.terminal.start(t=>this.handleInput(t),()=>this.requestRender()),this.terminal.hideCursor(),this.queryCellSize(),this.requestRender()}addInputListener(t){return this.inputListeners.add(t),()=>{this.inputListeners.delete(t)}}removeInputListener(t){this.inputListeners.delete(t)}queryCellSize(){ve().images&&this.terminal.write("\x1B[16t")}stop(){if(this.stopped=!0,this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0),this.previousLines.length>0){let n=this.previousLines.length-this.hardwareCursorRow;n>0?this.terminal.write(`\x1B[${n}B`):n<0&&this.terminal.write(`\x1B[${-n}A`),this.terminal.write(`\r
|
|
36
|
+
`)}this.terminal.showCursor(),this.terminal.stop()}requestRender(t=!1){if(t){this.previousLines=[],this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0,this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0),this.renderRequested=!0,process.nextTick(()=>{this.stopped||!this.renderRequested||(this.renderRequested=!1,this.lastRenderAt=na.now(),this.doRender())});return}this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let t=na.now()-this.lastRenderAt,n=Math.max(0,i.MIN_RENDER_INTERVAL_MS-t);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=na.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},n)}handleInput(t){if(this.inputListeners.size>0){let s=t;for(let o of this.inputListeners){let r=o(s);if(r?.consume)return;r?.data!==void 0&&(s=r.data)}if(s.length===0)return;t=s}if(this.consumeCellSizeResponse(t))return;if(ge(t,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let n=this.overlayStack.find(s=>s.component===this.focusedComponent);if(n&&!this.isOverlayVisible(n)){let s=this.getTopmostVisibleOverlay();s?this.setFocus(s.component):this.setFocus(n.preFocus)}if(this.focusedComponent?.handleInput){if(qr(t)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(t),this.requestRender()}}consumeCellSizeResponse(t){let n=t.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!n)return!1;let s=parseInt(n[1],10),o=parseInt(n[2],10);return s<=0||o<=0||(Xr({widthPx:o,heightPx:s}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(t,n,s,o){let r=t??{},a=typeof r.margin=="number"?{top:r.margin,right:r.margin,bottom:r.margin,left:r.margin}:r.margin??{},l=Math.max(0,a.top??0),c=Math.max(0,a.right??0),d=Math.max(0,a.bottom??0),p=Math.max(0,a.left??0),u=Math.max(1,s-p-c),h=Math.max(1,o-l-d),m=vp(r.width,s)??Math.min(80,u);r.minWidth!==void 0&&(m=Math.max(m,r.minWidth)),m=Math.max(1,Math.min(m,u));let g=vp(r.maxHeight,o);g!==void 0&&(g=Math.max(1,Math.min(g,h)));let x=g!==void 0?Math.min(n,g):n,b,v;if(r.row!==void 0)if(typeof r.row=="string"){let w=r.row.match(/^(\d+(?:\.\d+)?)%$/);if(w){let C=Math.max(0,h-x),R=parseFloat(w[1])/100;b=l+Math.floor(C*R)}else b=this.resolveAnchorRow("center",x,h,l)}else b=r.row;else{let w=r.anchor??"center";b=this.resolveAnchorRow(w,x,h,l)}if(r.col!==void 0)if(typeof r.col=="string"){let w=r.col.match(/^(\d+(?:\.\d+)?)%$/);if(w){let C=Math.max(0,u-m),R=parseFloat(w[1])/100;v=p+Math.floor(C*R)}else v=this.resolveAnchorCol("center",m,u,p)}else v=r.col;else{let w=r.anchor??"center";v=this.resolveAnchorCol(w,m,u,p)}return r.offsetY!==void 0&&(b+=r.offsetY),r.offsetX!==void 0&&(v+=r.offsetX),b=Math.max(l,Math.min(b,o-d-x)),v=Math.max(p,Math.min(v,s-c-m)),{width:m,row:b,col:v,maxHeight:g}}resolveAnchorRow(t,n,s,o){switch(t){case"top-left":case"top-center":case"top-right":return o;case"bottom-left":case"bottom-center":case"bottom-right":return o+s-n;case"left-center":case"center":case"right-center":return o+Math.floor((s-n)/2)}}resolveAnchorCol(t,n,s,o){switch(t){case"top-left":case"left-center":case"bottom-left":return o;case"top-right":case"right-center":case"bottom-right":return o+s-n;case"top-center":case"center":case"bottom-center":return o+Math.floor((s-n)/2)}}compositeOverlays(t,n,s){if(this.overlayStack.length===0)return t;let o=[...t],r=[],a=o.length,l=this.overlayStack.filter(p=>this.isOverlayVisible(p));l.sort((p,u)=>p.focusOrder-u.focusOrder);for(let p of l){let{component:u,options:h}=p,{width:m,maxHeight:g}=this.resolveOverlayLayout(h,0,n,s),x=u.render(m);g!==void 0&&x.length>g&&(x=x.slice(0,g));let{row:b,col:v}=this.resolveOverlayLayout(h,x.length,n,s);r.push({overlayLines:x,row:b,col:v,w:m}),a=Math.max(a,b+x.length)}let c=Math.max(o.length,s,a);for(;o.length<c;)o.push("");let d=Math.max(0,c-s);for(let{overlayLines:p,row:u,col:h,w:m}of r)for(let g=0;g<p.length;g++){let x=d+u+g;if(x>=0&&x<o.length){let b=W(p[g])>m?Fn(p[g],0,m,!0):p[g];o[x]=this.compositeLineAt(o[x],b,h,m,n)}}return o}static{this.SEGMENT_RESET="\x1B[0m\x1B]8;;\x07"}applyLineResets(t){let n=i.SEGMENT_RESET;for(let s=0;s<t.length;s++){let o=t[s];pn(o)||(t[s]=Xc(o)+n)}return t}collectKittyImageIds(t){let n=new Set;for(let s of t)for(let o of ia(s))n.add(o);return n}deleteKittyImages(t){let n="";for(let s of t)n+=ea(s);return n}expandLastChangedForKittyImages(t,n){let s=n;for(let o=t;o<this.previousLines.length;o++)ia(this.previousLines[o]).length>0&&(s=Math.max(s,o));return s}deleteChangedKittyImages(t,n){if(t<0||n<t)return"";let s=new Set,o=Math.min(n,this.previousLines.length-1);for(let r=t;r<=o;r++)for(let a of ia(this.previousLines[r]??""))s.add(a);return this.deleteKittyImages(s)}compositeLineAt(t,n,s,o,r){if(pn(t))return t;let a=s+o,l=ep(t,s,a,r-a,!0),c=Hr(n,0,o,!0),d=Math.max(0,s-l.beforeWidth),p=Math.max(0,o-c.width),u=Math.max(s,l.beforeWidth),h=Math.max(o,c.width),m=Math.max(0,r-u-h),g=Math.max(0,m-l.afterWidth),x=i.SEGMENT_RESET,b=l.before+" ".repeat(d)+x+c.text+" ".repeat(p)+x+l.after+" ".repeat(g);return W(b)<=r?b:Fn(b,0,r,!0)}extractCursorPosition(t,n){let s=Math.max(0,t.length-n);for(let o=t.length-1;o>=s;o--){let r=t[o],a=r.indexOf(dn);if(a!==-1){let l=r.slice(0,a),c=W(l);return t[o]=r.slice(0,a)+r.slice(a+dn.length),{row:o,col:c}}}return null}doRender(){if(this.stopped)return;let t=this.terminal.columns,n=this.terminal.rows,s=this.previousWidth!==0&&this.previousWidth!==t,o=this.previousHeight!==0&&this.previousHeight!==n,r=this.previousHeight>0?this.previousViewportTop+this.previousHeight:n,a=o?Math.max(0,r-n):this.previousViewportTop,l=a,c=this.hardwareCursorRow,d=M=>{let _=c-a;return M-l-_},p=this.render(t);this.overlayStack.length>0&&(p=this.compositeOverlays(p,t,n));let u=this.extractCursorPosition(p,n);p=this.applyLineResets(p);let h=M=>{this.fullRedrawCount+=1;let _="\x1B[?2026h";M&&(_+=this.deleteKittyImages(this.previousKittyImageIds),_+="\x1B[2J\x1B[H\x1B[3J");for(let F=0;F<p.length;F++)F>0&&(_+=`\r
|
|
37
|
+
`),_+=p[F];_+="\x1B[?2026l",this.terminal.write(_),this.cursorRow=Math.max(0,p.length-1),this.hardwareCursorRow=this.cursorRow,M?this.maxLinesRendered=p.length:this.maxLinesRendered=Math.max(this.maxLinesRendered,p.length);let U=Math.max(n,p.length);this.previousViewportTop=Math.max(0,U-n),this.positionHardwareCursor(u,p.length),this.previousLines=p,this.previousKittyImageIds=this.collectKittyImageIds(p),this.previousWidth=t,this.previousHeight=n},m=process.env.PI_DEBUG_REDRAW==="1",g=M=>{if(!m)return;let _=Gn.join(sa.homedir(),".pi","agent","pi-debug.log"),U=`[${new Date().toISOString()}] fullRender: ${M} (prev=${this.previousLines.length}, new=${p.length}, height=${n})
|
|
38
|
+
`;zt.appendFileSync(_,U)};if(this.previousLines.length===0&&!s&&!o){g("first render"),h(!1);return}if(s){g(`terminal width changed (${this.previousWidth} -> ${t})`),h(!0);return}if(o&&!pf()){g(`terminal height changed (${this.previousHeight} -> ${n})`),h(!0);return}if(this.clearOnShrink&&p.length<this.maxLinesRendered&&this.overlayStack.length===0){g(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),h(!0);return}let x=-1,b=-1,v=Math.max(p.length,this.previousLines.length);for(let M=0;M<v;M++){let _=M<this.previousLines.length?this.previousLines[M]:"",U=M<p.length?p[M]:"";_!==U&&(x===-1&&(x=M),b=M)}let w=p.length>this.previousLines.length;w&&(x===-1&&(x=this.previousLines.length),b=p.length-1),x!==-1&&(b=this.expandLastChangedForKittyImages(x,b));let C=w&&x===this.previousLines.length&&x>0;if(x===-1){this.positionHardwareCursor(u,p.length),this.previousViewportTop=a,this.previousHeight=n;return}if(x>=p.length){if(this.previousLines.length>p.length){let M="\x1B[?2026h";M+=this.deleteChangedKittyImages(x,b);let _=Math.max(0,p.length-1);if(_<a){g(`deleted lines moved viewport up (${_} < ${a})`),h(!0);return}let U=d(_);U>0?M+=`\x1B[${U}B`:U<0&&(M+=`\x1B[${-U}A`),M+="\r";let F=this.previousLines.length-p.length;if(F>n){g(`extraLines > height (${F} > ${n})`),h(!0);return}F>0&&(M+="\x1B[1B");for(let $=0;$<F;$++)M+="\r\x1B[2K",$<F-1&&(M+="\x1B[1B");F>0&&(M+=`\x1B[${F}A`),M+="\x1B[?2026l",this.terminal.write(M),this.cursorRow=_,this.hardwareCursorRow=_}this.positionHardwareCursor(u,p.length),this.previousLines=p,this.previousKittyImageIds=this.collectKittyImageIds(p),this.previousWidth=t,this.previousHeight=n,this.previousViewportTop=a;return}if(x<a){g(`firstChanged < viewportTop (${x} < ${a})`),h(!0);return}let R="\x1B[?2026h";R+=this.deleteChangedKittyImages(x,b);let k=a+n-1,A=C?x-1:x;if(A>k){let M=Math.max(0,Math.min(n-1,c-a)),_=n-1-M;_>0&&(R+=`\x1B[${_}B`);let U=A-k;R+=`\r
|
|
39
|
+
`.repeat(U),a+=U,l+=U,c=A}let S=d(A);S>0?R+=`\x1B[${S}B`:S<0&&(R+=`\x1B[${-S}A`),R+=C?`\r
|
|
40
|
+
`:"\r";let I=Math.min(b,p.length-1);for(let M=x;M<=I;M++){M>x&&(R+=`\r
|
|
41
|
+
`),R+="\x1B[2K";let _=p[M];if(!pn(_)&&W(_)>t){let F=Gn.join(sa.homedir(),".pi","agent","pi-crash.log"),$=[`Crash at ${new Date().toISOString()}`,`Terminal width: ${t}`,`Line ${M} visible width: ${W(_)}`,"","=== All rendered lines ===",...p.map((oe,ue)=>`[${ue}] (w=${W(oe)}) ${oe}`),""].join(`
|
|
42
|
+
`);zt.mkdirSync(Gn.dirname(F),{recursive:!0}),zt.writeFileSync(F,$),this.stop();let Q=[`Rendered line ${M} exceeds terminal width (${W(_)} > ${t}).`,"","This is likely caused by a custom TUI component not truncating its output.","Use visibleWidth() to measure and truncateToWidth() to truncate lines.","",`Debug log written to: ${F}`].join(`
|
|
43
|
+
`);throw new Error(Q)}R+=_}let P=I;if(this.previousLines.length>p.length){if(I<p.length-1){let _=p.length-1-I;R+=`\x1B[${_}B`,P=p.length-1}let M=this.previousLines.length-p.length;for(let _=p.length;_<this.previousLines.length;_++)R+=`\r
|
|
44
|
+
\x1B[2K`;R+=`\x1B[${M}A`}if(R+="\x1B[?2026l",process.env.PI_TUI_DEBUG==="1"){let M="/tmp/tui";zt.mkdirSync(M,{recursive:!0});let _=Gn.join(M,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),U=[`firstChanged: ${x}`,`viewportTop: ${l}`,`cursorRow: ${this.cursorRow}`,`height: ${n}`,`lineDiff: ${S}`,`hardwareCursorRow: ${c}`,`renderEnd: ${I}`,`finalCursorRow: ${P}`,`cursorPos: ${JSON.stringify(u)}`,`newLines.length: ${p.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(p,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",JSON.stringify(R)].join(`
|
|
45
|
+
`);zt.writeFileSync(_,U)}this.terminal.write(R),this.cursorRow=Math.max(0,p.length-1),this.hardwareCursorRow=P,this.maxLinesRendered=Math.max(this.maxLinesRendered,p.length),this.previousViewportTop=Math.max(a,P-n+1),this.positionHardwareCursor(u,p.length),this.previousLines=p,this.previousKittyImageIds=this.collectKittyImageIds(p),this.previousWidth=t,this.previousHeight=n}positionHardwareCursor(t,n){if(!t||n<=0){this.terminal.hideCursor();return}let s=Math.max(0,Math.min(t.row,n-1)),o=Math.max(0,t.col),r=s-this.hardwareCursorRow,a="";r>0?a+=`\x1B[${r}B`:r<0&&(a+=`\x1B[${-r}A`),a+=`\x1B[${o+1}G`,a&&this.terminal.write(a),this.hardwareCursorRow=s,this.showHardwareCursor?this.terminal.showCursor():this.terminal.hideCursor()}};var Kn=class{constructor(){this.stack=[]}push(e){this.stack.push(structuredClone(e))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}};var yp=32,wp=2,df=10,uf=i=>i.replace(/[\r\n]+/g," ").trim(),mf=(i,e,t)=>Math.max(e,Math.min(i,t)),Ye=class{constructor(e,t,n,s={}){this.items=[];this.filteredItems=[];this.selectedIndex=0;this.maxVisible=5;this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=n,this.layout=s}setFilter(e){this.filteredItems=this.items.filter(t=>t.value.toLowerCase().startsWith(e.toLowerCase())),this.selectedIndex=0}setSelectedIndex(e){this.selectedIndex=Math.max(0,Math.min(e,this.filteredItems.length-1))}invalidate(){}render(e){let t=[];if(this.filteredItems.length===0)return t.push(this.theme.noMatch(" No matching commands")),t;let n=this.getPrimaryColumnWidth(),s=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible)),o=Math.min(s+this.maxVisible,this.filteredItems.length);for(let r=s;r<o;r++){let a=this.filteredItems[r];if(!a)continue;let l=r===this.selectedIndex,c=a.description?uf(a.description):void 0;t.push(this.renderItem(a,l,e,c,n))}if(s>0||o<this.filteredItems.length){let r=` (${this.selectedIndex+1}/${this.filteredItems.length})`;t.push(this.theme.scrollInfo(G(r,e-2,"")))}return t}handleInput(e){let t=V();if(t.matches(e,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(t.matches(e,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(t.matches(e,"tui.select.confirm")){let n=this.filteredItems[this.selectedIndex];n&&this.onSelect&&this.onSelect(n)}else t.matches(e,"tui.select.cancel")&&this.onCancel&&this.onCancel()}renderItem(e,t,n,s,o){let r=t?"\u2192 ":" ",a=W(r);if(s&&n>40){let d=Math.max(1,Math.min(o,n-a-4)),p=Math.max(1,d-wp),u=this.truncatePrimary(e,t,p,d),h=W(u),m=" ".repeat(Math.max(1,d-h)),g=a+h+m.length,x=n-g-2;if(x>df){let b=G(s,x,"");if(t)return this.theme.selectedText(`${r}${u}${m}${b}`);let v=this.theme.description(m+b);return r+u+v}}let l=n-a-2,c=this.truncatePrimary(e,t,l,l);return t?this.theme.selectedText(`${r}${c}`):r+c}getPrimaryColumnWidth(){let{min:e,max:t}=this.getPrimaryColumnBounds(),n=this.filteredItems.reduce((s,o)=>Math.max(s,W(this.getDisplayValue(o))+wp),0);return mf(n,e,t)}getPrimaryColumnBounds(){let e=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??yp,t=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??yp;return{min:Math.max(1,Math.min(e,t)),max:Math.max(1,Math.max(e,t))}}truncatePrimary(e,t,n,s){let o=this.getDisplayValue(e),r=this.layout.truncatePrimary?this.layout.truncatePrimary({text:o,maxWidth:n,columnWidth:s,item:e,isSelected:t}):G(o,n,"");return G(r,n,"")}getDisplayValue(e){return e.label||e.value}notifySelectionChange(){let e=this.filteredItems[this.selectedIndex];e&&this.onSelectionChange&&this.onSelectionChange(e)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};var ro=Xs(),hf=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,gf=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function vt(i){return i.length>=10&&gf.test(i)}function ff(i,e){if(e.size===0||!i.includes("[paste #"))return ro.segment(i);let t=[];for(let r of i.matchAll(hf)){let a=Number.parseInt(r[1],10);e.has(a)&&t.push({start:r.index,end:r.index+r[0].length})}if(t.length===0)return ro.segment(i);let n=ro.segment(i),s=[],o=0;for(let r of n){for(;o<t.length&&t[o].end<=r.index;)o++;let a=o<t.length?t[o]:null;if(a&&r.index>=a.start&&r.index<a.end){if(r.index===a.start){let l=i.slice(a.start,a.end);s.push({segment:l,index:a.start,input:i})}}else s.push(r)}return s}function ra(i,e,t){if(!i||e<=0)return[{text:"",startIndex:0,endIndex:0}];if(W(i)<=e)return[{text:i,startIndex:0,endIndex:i.length}];let s=[],o=t??[...ro.segment(i)],r=0,a=0,l=-1,c=0;for(let d=0;d<o.length;d++){let p=o[d],u=p.segment,h=W(u),m=p.index,g=!vt(u)&&Oe(u);if(r+h>e&&(l>=0&&r-c+h<=e?(s.push({text:i.slice(a,l),startIndex:a,endIndex:l}),a=l,r-=c):a<m&&(s.push({text:i.slice(a,m),startIndex:a,endIndex:m}),a=m,r=0),l=-1),h>e){let b=ra(u,e);for(let w=0;w<b.length-1;w++){let C=b[w];s.push({text:C.text,startIndex:m+C.startIndex,endIndex:m+C.endIndex})}let v=b[b.length-1];a=m+v.startIndex,r=W(v.text),l=-1;continue}r+=h;let x=o[d+1];g&&x&&(vt(x.segment)||!Oe(x.segment))&&(l=x.index,c=r)}return s.push({text:i.slice(a),startIndex:a,endIndex:i.length}),s}var xf={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},bf=20,un=class{constructor(e,t,n={}){this.state={lines:[""],cursorLine:0,cursorCol:0};this.focused=!1;this.paddingX=0;this.lastWidth=80;this.scrollOffset=0;this.autocompleteState=null;this.autocompletePrefix="";this.autocompleteMaxVisible=5;this.autocompleteRequestTask=Promise.resolve();this.autocompleteStartToken=0;this.autocompleteRequestId=0;this.pastes=new Map;this.pasteCounter=0;this.pasteBuffer="";this.isInPaste=!1;this.history=[];this.historyIndex=-1;this.killRing=new Bn;this.lastAction=null;this.jumpMode=null;this.preferredVisualCol=null;this.snappedFromCursorCol=null;this.undoStack=new Kn;this.disableSubmit=!1;this.tui=e,this.theme=t,this.borderColor=t.borderColor;let s=n.paddingX??0;this.paddingX=Number.isFinite(s)?Math.max(0,Math.floor(s)):0;let o=n.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(o)?Math.max(3,Math.min(20,Math.floor(o))):5}validPasteIds(){return new Set(this.pastes.keys())}segment(e){return ff(e,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;this.paddingX!==t&&(this.paddingX=t,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(e){let t=Number.isFinite(e)?Math.max(3,Math.min(20,Math.floor(e))):5;this.autocompleteMaxVisible!==t&&(this.autocompleteMaxVisible=t,this.tui.requestRender())}setAutocompleteProvider(e){this.cancelAutocomplete(),this.autocompleteProvider=e}addToHistory(e){let t=e.trim();t&&(this.history.length>0&&this.history[0]===t||(this.history.unshift(t),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===0}isOnLastVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===e.length-1}navigateHistory(e){if(this.lastAction=null,this.history.length===0)return;let t=this.historyIndex-e;t<-1||t>=this.history.length||(this.historyIndex===-1&&t>=0&&this.pushUndoSnapshot(),this.historyIndex=t,this.historyIndex===-1?this.setTextInternal(""):this.setTextInternal(this.history[this.historyIndex]||""))}setTextInternal(e){let t=e.split(`
|
|
46
|
+
`);this.state.lines=t.length===0?[""]:t,this.state.cursorLine=this.state.lines.length-1,this.setCursorCol(this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){}render(e){let t=Math.max(0,Math.floor((e-1)/2)),n=Math.min(this.paddingX,t),s=Math.max(1,e-n*2),o=Math.max(1,s-(n?0:1));this.lastWidth=o;let r=this.borderColor("\u2500"),a=this.layoutText(o),l=this.tui.terminal.rows,c=Math.max(5,Math.floor(l*.3)),d=a.findIndex(v=>v.hasCursor);d===-1&&(d=0),d<this.scrollOffset?this.scrollOffset=d:d>=this.scrollOffset+c&&(this.scrollOffset=d-c+1);let p=Math.max(0,a.length-c);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,p));let u=a.slice(this.scrollOffset,this.scrollOffset+c),h=[],m=" ".repeat(n),g=m;if(this.scrollOffset>0){let v=`\u2500\u2500\u2500 \u2191 ${this.scrollOffset} more `,w=e-W(v);w>=0?h.push(this.borderColor(v+"\u2500".repeat(w))):h.push(this.borderColor(G(v,e)))}else h.push(r.repeat(e));let x=this.focused&&!this.autocompleteState;for(let v of u){let w=v.text,C=W(v.text),R=!1;if(v.hasCursor&&v.cursorPos!==void 0){let S=w.slice(0,v.cursorPos),I=w.slice(v.cursorPos),P=x?dn:"";if(I.length>0){let _=[...this.segment(I)][0]?.segment||"",U=I.slice(_.length),F=`\x1B[7m${_}\x1B[0m`;w=S+P+F+U}else w=S+P+"\x1B[7m \x1B[0m",C=C+1,C>s&&n>0&&(R=!0)}let k=" ".repeat(Math.max(0,s-C)),A=R?g.slice(1):g;h.push(`${m}${w}${k}${A}`)}let b=a.length-(this.scrollOffset+u.length);if(b>0){let v=`\u2500\u2500\u2500 \u2193 ${b} more `,w=e-W(v);h.push(this.borderColor(v+"\u2500".repeat(Math.max(0,w))))}else h.push(r.repeat(e));if(this.autocompleteState&&this.autocompleteList){let v=this.autocompleteList.render(s);for(let w of v){let C=W(w),R=" ".repeat(Math.max(0,s-C));h.push(`${m}${w}${R}${g}`)}}return h}handleInput(e){let t=V();if(this.jumpMode!==null){if(t.matches(e,"tui.editor.jumpForward")||t.matches(e,"tui.editor.jumpBackward")){this.jumpMode=null;return}let s=Qr(e)??(e.charCodeAt(0)>=32?e:void 0);if(s!==void 0){let o=this.jumpMode;this.jumpMode=null,this.jumpToChar(s,o);return}this.jumpMode=null}if(e.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",e=e.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=e;let s=this.pasteBuffer.indexOf("\x1B[201~");if(s!==-1){let o=this.pasteBuffer.substring(0,s);o.length>0&&this.handlePaste(o),this.isInPaste=!1;let r=this.pasteBuffer.substring(s+6);this.pasteBuffer="",r.length>0&&this.handleInput(r);return}return}if(t.matches(e,"tui.input.copy"))return;if(t.matches(e,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(t.matches(e,"tui.select.cancel")){this.cancelAutocomplete();return}if(t.matches(e,"tui.select.up")||t.matches(e,"tui.select.down")){this.autocompleteList.handleInput(e);return}if(t.matches(e,"tui.input.tab")){let s=this.autocompleteList.getSelectedItem();if(s&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let o=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,s,this.autocompletePrefix);this.state.lines=o.lines,this.state.cursorLine=o.cursorLine,this.setCursorCol(o.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText())}return}if(t.matches(e,"tui.select.confirm")){let s=this.autocompleteList.getSelectedItem();if(s&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let o=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,s,this.autocompletePrefix);if(this.state.lines=o.lines,this.state.cursorLine=o.cursorLine,this.setCursorCol(o.cursorCol),this.autocompletePrefix.startsWith("/"))this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(t.matches(e,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(t.matches(e,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(t.matches(e,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();return}if(t.matches(e,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(t.matches(e,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(t.matches(e,"tui.editor.deleteCharBackward")||ge(e,"shift+backspace")){this.handleBackspace();return}if(t.matches(e,"tui.editor.deleteCharForward")||ge(e,"shift+delete")){this.handleForwardDelete();return}if(t.matches(e,"tui.editor.yank")){this.yank();return}if(t.matches(e,"tui.editor.yankPop")){this.yankPop();return}if(t.matches(e,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(t.matches(e,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(t.matches(e,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(t.matches(e,"tui.editor.cursorWordRight")){this.moveWordForwards();return}if(t.matches(e,"tui.input.newLine")||e.charCodeAt(0)===10&&e.length>1||e==="\x1B\r"||e==="\x1B[13;2~"||e.length>1&&e.includes("\x1B")&&e.includes("\r")||e===`
|
|
47
|
+
`&&e.length===1){if(this.shouldSubmitOnBackslashEnter(e,t)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(t.matches(e,"tui.input.submit")){if(this.disableSubmit)return;let s=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&&s[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(t.matches(e,"tui.editor.cursorUp")){this.isEditorEmpty()?this.navigateHistory(-1):this.historyIndex>-1&&this.isOnFirstVisualLine()?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(t.matches(e,"tui.editor.cursorDown")){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(t.matches(e,"tui.editor.cursorRight")){this.moveCursor(0,1);return}if(t.matches(e,"tui.editor.cursorLeft")){this.moveCursor(0,-1);return}if(t.matches(e,"tui.editor.pageUp")){this.pageScroll(-1);return}if(t.matches(e,"tui.editor.pageDown")){this.pageScroll(1);return}if(t.matches(e,"tui.editor.jumpForward")){this.jumpMode="forward";return}if(t.matches(e,"tui.editor.jumpBackward")){this.jumpMode="backward";return}if(ge(e,"shift+space")){this.insertCharacter(" ");return}let n=Qr(e);if(n!==void 0){this.insertCharacter(n);return}e.charCodeAt(0)>=32&&this.insertCharacter(e)}layoutText(e){let t=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return t.push({text:"",hasCursor:!0,cursorPos:0}),t;for(let n=0;n<this.state.lines.length;n++){let s=this.state.lines[n]||"",o=n===this.state.cursorLine;if(W(s)<=e)o?t.push({text:s,hasCursor:!0,cursorPos:this.state.cursorCol}):t.push({text:s,hasCursor:!1});else{let a=ra(s,e,[...this.segment(s)]);for(let l=0;l<a.length;l++){let c=a[l];if(!c)continue;let d=this.state.cursorCol,p=l===a.length-1,u=!1,h=0;o&&(p?(u=d>=c.startIndex,h=d-c.startIndex):(u=d>=c.startIndex&&d<c.endIndex,u&&(h=d-c.startIndex,h>c.text.length&&(h=c.text.length)))),u?t.push({text:c.text,hasCursor:!0,cursorPos:h}):t.push({text:c.text,hasCursor:!1})}}}return t}getText(){return this.state.lines.join(`
|
|
48
|
+
`)}expandPasteMarkers(e){let t=e;for(let[n,s]of this.pastes){let o=new RegExp(`\\[paste #${n}( (\\+\\d+ lines|\\d+ chars))?\\]`,"g");t=t.replace(o,()=>s)}return t}getExpandedText(){return this.expandPasteMarkers(this.state.lines.join(`
|
|
49
|
+
`))}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(e){this.cancelAutocomplete(),this.lastAction=null,this.historyIndex=-1;let t=this.normalizeText(e);this.getText()!==t&&this.pushUndoSnapshot(),this.setTextInternal(t)}insertTextAtCursor(e){e&&(this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.historyIndex=-1,this.insertTextAtCursorInternal(e))}normalizeText(e){return e.replace(/\r\n/g,`
|
|
50
|
+
`).replace(/\r/g,`
|
|
51
|
+
`).replace(/\t/g," ")}insertTextAtCursorInternal(e){if(!e)return;let t=this.normalizeText(e),n=t.split(`
|
|
52
|
+
`),s=this.state.lines[this.state.cursorLine]||"",o=s.slice(0,this.state.cursorCol),r=s.slice(this.state.cursorCol);n.length===1?(this.state.lines[this.state.cursorLine]=o+t+r,this.setCursorCol(this.state.cursorCol+t.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),o+n[0],...n.slice(1,-1),n[n.length-1]+r,...this.state.lines.slice(this.state.cursorLine+1)],this.state.cursorLine+=n.length-1,this.setCursorCol((n[n.length-1]||"").length)),this.onChange&&this.onChange(this.getText())}insertCharacter(e,t){this.historyIndex=-1,t||((Oe(e)||this.lastAction!=="type-word")&&this.pushUndoSnapshot(),this.lastAction="type-word");let n=this.state.lines[this.state.cursorLine]||"",s=n.slice(0,this.state.cursorCol),o=n.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=s+e+o,this.setCursorCol(this.state.cursorCol+e.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(e==="/"&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(e==="@"||e==="#"){let a=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol),l=a[a.length-2];(a.length===1||l===" "||l===" ")&&this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(e)){let a=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(a)?this.tryTriggerAutocomplete():a.match(/(?:^|[\s])[@#][^\s]*$/)&&this.tryTriggerAutocomplete()}}handlePaste(e){this.cancelAutocomplete(),this.historyIndex=-1,this.lastAction=null,this.pushUndoSnapshot();let t=e.replace(/\x1b\[(\d+);5u/g,(a,l)=>{let c=Number(l);return c>=97&&c<=122?String.fromCharCode(c-96):c>=65&&c<=90?String.fromCharCode(c-64):a}),s=this.normalizeText(t).split("").filter(a=>a===`
|
|
53
|
+
`||a.charCodeAt(0)>=32).join("");if(/^[/~.]/.test(s)){let a=this.state.lines[this.state.cursorLine]||"",l=this.state.cursorCol>0?a[this.state.cursorCol-1]:"";l&&/\w/.test(l)&&(s=` ${s}`)}let o=s.split(`
|
|
54
|
+
`),r=s.length;if(o.length>10||r>1e3){this.pasteCounter++;let a=this.pasteCounter;this.pastes.set(a,s);let l=o.length>10?`[paste #${a} +${o.length} lines]`:`[paste #${a} ${r} chars]`;this.insertTextAtCursorInternal(l);return}if(o.length===1){this.insertTextAtCursorInternal(s);return}this.insertTextAtCursorInternal(s)}addNewLine(){this.cancelAutocomplete(),this.historyIndex=-1,this.lastAction=null,this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",t=e.slice(0,this.state.cursorCol),n=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=t,this.state.lines.splice(this.state.cursorLine+1,0,n),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(e,t){if(this.disableSubmit||!ge(e,"enter"))return!1;let n=t.getKeys("tui.input.submit");if(!(n.includes("shift+enter")||n.includes("shift+return")))return!1;let o=this.state.lines[this.state.cursorLine]||"";return this.state.cursorCol>0&&o[this.state.cursorCol-1]==="\\"}submitValue(){this.cancelAutocomplete();let e=this.expandPasteMarkers(this.state.lines.join(`
|
|
55
|
+
`)).trim();this.state={lines:[""],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.historyIndex=-1,this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(""),this.onSubmit&&this.onSubmit(e)}handleBackspace(){if(this.historyIndex=-1,this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",t=e.slice(0,this.state.cursorCol),n=[...this.segment(t)],s=n[n.length-1],o=s?s.segment.length:1,r=e.slice(0,this.state.cursorCol-o),a=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=r+a,this.setCursorCol(this.state.cursorCol-o)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",t=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(t)?this.tryTriggerAutocomplete():t.match(/(?:^|[\s])[@#][^\s]*$/)&&this.tryTriggerAutocomplete()}}setCursorCol(e){this.state.cursorCol=e,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(e,t,n){let s=e[t],o=e[n];if(!(s&&o))return;let r;if(this.snappedFromCursorCol!==null){let g=this.findVisualLineAt(e,s.logicalLine,this.snappedFromCursorCol);r=this.snappedFromCursorCol-e[g].startCol}else r=this.state.cursorCol-s.startCol;let l=t===e.length-1||e[t+1]?.logicalLine!==s.logicalLine?s.length:Math.max(0,s.length-1),d=n===e.length-1||e[n+1]?.logicalLine!==o.logicalLine?o.length:Math.max(0,o.length-1),p=this.computeVerticalMoveColumn(r,l,d);this.state.cursorLine=o.logicalLine;let u=o.startCol+p,h=this.state.lines[o.logicalLine]||"";this.state.cursorCol=Math.min(u,h.length);let m=[...this.segment(h)];for(let g of m){if(g.index>this.state.cursorCol)break;if(!(g.segment.length<=1)&&this.state.cursorCol<g.index+g.segment.length){let x=g.index<o.startCol,b=n>t;if(x&&b){let v=g.index+g.segment.length,w=n+1;for(;w<e.length&&e[w].logicalLine===o.logicalLine&&e[w].startCol<v;)w++;if(w<e.length){this.moveToVisualLine(e,t,w);return}}this.snappedFromCursorCol=this.state.cursorCol,this.state.cursorCol=g.index;return}}this.snappedFromCursorCol=null}computeVerticalMoveColumn(e,t,n){let s=this.preferredVisualCol!==null,o=e<t,r=n<e;if(!s||o)return r?(this.preferredVisualCol=e,n):(this.preferredVisualCol=null,e);let a=n<this.preferredVisualCol;if(r||a)return n;let l=this.preferredVisualCol;return this.preferredVisualCol=null,l}moveToLineStart(){this.lastAction=null,this.setCursorCol(0)}moveToLineEnd(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(e.length)}deleteToStartOfLine(){this.historyIndex=-1;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){this.pushUndoSnapshot();let t=e.slice(0,this.state.cursorCol);this.killRing.push(t,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
|
|
56
|
+
`,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}this.onChange&&this.onChange(this.getText())}deleteToEndOfLine(){this.historyIndex=-1;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<e.length){this.pushUndoSnapshot();let t=e.slice(this.state.cursorCol);this.killRing.push(t,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(0,this.state.cursorCol)}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
|
|
57
|
+
`,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}this.onChange&&this.onChange(this.getText())}deleteWordBackwards(){this.historyIndex=-1;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
|
|
58
|
+
`,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}}else{this.pushUndoSnapshot();let t=this.lastAction==="kill",n=this.state.cursorCol;this.moveWordBackwards();let s=this.state.cursorCol;this.setCursorCol(n);let o=e.slice(s,this.state.cursorCol);this.killRing.push(o,{prepend:!0,accumulate:t}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(0,s)+e.slice(this.state.cursorCol),this.setCursorCol(s)}this.onChange&&this.onChange(this.getText())}deleteWordForward(){this.historyIndex=-1;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=e.length){if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
|
|
59
|
+
`,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}}else{this.pushUndoSnapshot();let t=this.lastAction==="kill",n=this.state.cursorCol;this.moveWordForwards();let s=this.state.cursorCol;this.setCursorCol(n);let o=e.slice(this.state.cursorCol,s);this.killRing.push(o,{prepend:!1,accumulate:t}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(0,this.state.cursorCol)+e.slice(s)}this.onChange&&this.onChange(this.getText())}handleForwardDelete(){this.historyIndex=-1,this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<e.length){this.pushUndoSnapshot();let t=e.slice(this.state.cursorCol),s=[...this.segment(t)][0],o=s?s.segment.length:1,r=e.slice(0,this.state.cursorCol),a=e.slice(this.state.cursorCol+o);this.state.lines[this.state.cursorLine]=r+a}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let t=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let n=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(n)?this.tryTriggerAutocomplete():n.match(/(?:^|[\s])[@#][^\s]*$/)&&this.tryTriggerAutocomplete()}}buildVisualLineMap(e){let t=[];for(let n=0;n<this.state.lines.length;n++){let s=this.state.lines[n]||"",o=W(s);if(s.length===0)t.push({logicalLine:n,startCol:0,length:0});else if(o<=e)t.push({logicalLine:n,startCol:0,length:s.length});else{let r=ra(s,e,[...this.segment(s)]);for(let a of r)t.push({logicalLine:n,startCol:a.startIndex,length:a.endIndex-a.startIndex})}}return t}findVisualLineAt(e,t,n){for(let s=0;s<e.length;s++){let o=e[s];if(!o||o.logicalLine!==t)continue;let r=n-o.startCol,a=s===e.length-1||e[s+1]?.logicalLine!==o.logicalLine;if(r>=0&&(r<o.length||a&&r===o.length))return s}return e.length-1}findCurrentVisualLine(e){return this.findVisualLineAt(e,this.state.cursorLine,this.state.cursorCol)}moveCursor(e,t){this.lastAction=null;let n=this.buildVisualLineMap(this.lastWidth),s=this.findCurrentVisualLine(n);if(e!==0){let o=s+e;o>=0&&o<n.length&&this.moveToVisualLine(n,s,o)}if(t!==0){let o=this.state.lines[this.state.cursorLine]||"";if(t>0)if(this.state.cursorCol<o.length){let r=o.slice(this.state.cursorCol),l=[...this.segment(r)][0];this.setCursorCol(this.state.cursorCol+(l?l.segment.length:1))}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else{let r=n[s];r&&(this.preferredVisualCol=this.state.cursorCol-r.startCol)}else if(this.state.cursorCol>0){let r=o.slice(0,this.state.cursorCol),a=[...this.segment(r)],l=a[a.length-1];this.setCursorCol(this.state.cursorCol-(l?l.segment.length:1))}else if(this.state.cursorLine>0){this.state.cursorLine--;let r=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(r.length)}}}pageScroll(e){this.lastAction=null;let t=this.tui.terminal.rows,n=Math.max(5,Math.floor(t*.3)),s=this.buildVisualLineMap(this.lastWidth),o=this.findCurrentVisualLine(s),r=Math.max(0,Math.min(s.length-1,o+e*n));this.moveToVisualLine(s,o,r)}moveWordBackwards(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let o=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(o.length)}return}let t=e.slice(0,this.state.cursorCol),n=[...this.segment(t)],s=this.state.cursorCol;for(;n.length>0&&!vt(n[n.length-1]?.segment||"")&&Oe(n[n.length-1]?.segment||"");)s-=n.pop()?.segment.length||0;if(n.length>0){let o=n[n.length-1]?.segment||"";if(vt(o))s-=n.pop()?.segment.length||0;else if(Ue(o))for(;n.length>0&&Ue(n[n.length-1]?.segment||"")&&!vt(n[n.length-1]?.segment||"");)s-=n.pop()?.segment.length||0;else for(;n.length>0&&!Oe(n[n.length-1]?.segment||"")&&!Ue(n[n.length-1]?.segment||"")&&!vt(n[n.length-1]?.segment||"");)s-=n.pop()?.segment.length||0}this.setCursorCol(s)}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let e=this.killRing.peek();this.insertYankedText(e),this.lastAction="yank"}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let e=this.killRing.peek();this.insertYankedText(e),this.lastAction="yank"}insertYankedText(e){this.historyIndex=-1;let t=e.split(`
|
|
60
|
+
`);if(t.length===1){let n=this.state.lines[this.state.cursorLine]||"",s=n.slice(0,this.state.cursorCol),o=n.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=s+e+o,this.setCursorCol(this.state.cursorCol+e.length)}else{let n=this.state.lines[this.state.cursorLine]||"",s=n.slice(0,this.state.cursorCol),o=n.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=s+(t[0]||"");for(let a=1;a<t.length-1;a++)this.state.lines.splice(this.state.cursorLine+a,0,t[a]||"");let r=this.state.cursorLine+t.length-1;this.state.lines.splice(r,0,(t[t.length-1]||"")+o),this.state.cursorLine=r,this.setCursorCol((t[t.length-1]||"").length)}this.onChange&&this.onChange(this.getText())}deleteYankedText(){let e=this.killRing.peek();if(!e)return;let t=e.split(`
|
|
61
|
+
`);if(t.length===1){let n=this.state.lines[this.state.cursorLine]||"",s=e.length,o=n.slice(0,this.state.cursorCol-s),r=n.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=o+r,this.setCursorCol(this.state.cursorCol-s)}else{let n=this.state.cursorLine-(t.length-1),s=(this.state.lines[n]||"").length-(t[0]||"").length,o=(this.state.lines[this.state.cursorLine]||"").slice(this.state.cursorCol),r=(this.state.lines[n]||"").slice(0,s);this.state.lines.splice(n,t.length,r+o),this.state.cursorLine=n,this.setCursorCol(s)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push(this.state)}undo(){this.historyIndex=-1;let e=this.undoStack.pop();e&&(Object.assign(this.state,e),this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()))}jumpToChar(e,t){this.lastAction=null;let n=t==="forward",s=this.state.lines,o=n?s.length:-1,r=n?1:-1;for(let a=this.state.cursorLine;a!==o;a+=r){let l=s[a]||"",d=a===this.state.cursorLine?n?this.state.cursorCol+1:this.state.cursorCol-1:void 0,p=n?l.indexOf(e,d):l.lastIndexOf(e,d);if(p!==-1){this.state.cursorLine=a,this.setCursorCol(p);return}}}moveWordForwards(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=e.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}let t=e.slice(this.state.cursorCol),s=this.segment(t)[Symbol.iterator](),o=s.next(),r=this.state.cursorCol;for(;!o.done&&!vt(o.value.segment)&&Oe(o.value.segment);)r+=o.value.segment.length,o=s.next();if(!o.done){let a=o.value.segment;if(vt(a))r+=a.length;else if(Ue(a))for(;!o.done&&Ue(o.value.segment)&&!vt(o.value.segment);)r+=o.value.segment.length,o=s.next();else for(;!o.done&&!Oe(o.value.segment)&&!Ue(o.value.segment)&&!vt(o.value.segment);)r+=o.value.segment.length,o=s.next()}this.setCursorCol(r)}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return t.trim()===""||t.trim()==="/"}isInSlashCommandContext(e){return this.isSlashMenuAllowed()&&e.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(e,t){if(!t)return-1;let n=-1;for(let s=0;s<e.length;s++){let o=e[s].value;if(o===t)return s;n===-1&&o.startsWith(t)&&(n=s)}return n}createAutocompleteList(e,t){let n=e.startsWith("/")?xf:void 0;return new Ye(t,this.autocompleteMaxVisible,this.theme.selectList,n)}tryTriggerAutocomplete(e=!1){this.requestAutocomplete({force:!1,explicitTab:e})}handleTabCompletion(){if(!this.autocompleteProvider)return;let t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(t)&&!t.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(e=!1){this.requestAutocomplete({force:!0,explicitTab:e})}requestAutocomplete(e){if(!this.autocompleteProvider||e.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let t=++this.autocompleteStartToken,n=this.getAutocompleteDebounceMs(e);if(n>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(t,e)},n);return}this.startAutocompleteRequest(t,e)}async startAutocompleteRequest(e,t){let n=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await n,e!==this.autocompleteStartToken||!this.autocompleteProvider)return;let s=new AbortController;this.autocompleteAbort=s;let o=++this.autocompleteRequestId,r=this.getText(),a=this.state.cursorLine,l=this.state.cursorCol;await this.runAutocompleteRequest(o,s,r,a,l,t)})(),await this.autocompleteRequestTask}getAutocompleteDebounceMs(e){if(e.explicitTab||e.force)return 0;let n=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return/(?:^|[ \t])(?:@(?:"[^"]*|[^\s]*)|#[^\s]*)$/.test(n)?bf:0}async runAutocompleteRequest(e,t,n,s,o,r){if(!this.autocompleteProvider)return;let a=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:t.signal,force:r.force});if(this.isAutocompleteRequestCurrent(e,t,n,s,o)){if(this.autocompleteAbort=void 0,!a||!Array.isArray(a.items)||a.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(r.force&&r.explicitTab&&a.items.length===1){let l=a.items[0];this.pushUndoSnapshot(),this.lastAction=null;let c=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,l,a.prefix);this.state.lines=c.lines,this.state.cursorLine=c.cursorLine,this.setCursorCol(c.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(a,r.force?"force":"regular"),this.tui.requestRender()}}isAutocompleteRequestCurrent(e,t,n,s,o){return!t.signal.aborted&&e===this.autocompleteRequestId&&this.getText()===n&&this.state.cursorLine===s&&this.state.cursorCol===o}applyAutocompleteSuggestions(e,t){this.autocompletePrefix=e.prefix,this.autocompleteList=this.createAutocompleteList(e.prefix,e.items);let n=this.getBestAutocompleteMatchIndex(e.items,e.prefix);n>=0&&this.autocompleteList.setSelectedIndex(n),this.autocompleteState=t}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&(clearTimeout(this.autocompleteDebounceTimer),this.autocompleteDebounceTimer=void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=""}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var mn=class{constructor(e,t,n,s={},o){this.base64Data=e,this.mimeType=t,this.theme=n,this.options=s,this.dimensions=o||Yi(e,t)||{widthPx:800,heightPx:600},this.imageId=s.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(e){if(this.cachedLines&&this.cachedWidth===e)return this.cachedLines;let t=Math.min(e-2,this.options.maxWidthCells??60),n=ve(),s;if(n.images){n.images==="kitty"&&this.imageId===void 0&&(this.imageId=Zr());let o=ta(this.base64Data,this.dimensions,{maxWidthCells:t,imageId:this.imageId,moveCursor:!1});if(o){o.imageId&&(this.imageId=o.imageId),s=[];for(let c=0;c<o.rows-1;c++)s.push("");let r=o.rows-1,a=r>0?`\x1B[${r}A`:"",l=n.images==="kitty"&&r>0?`\x1B[${r}B`:"";s.push(a+o.sequence+l)}else{let r=Nn(this.mimeType,this.dimensions,this.options.filename);s=[this.theme.fallbackColor(r)]}}else{let o=Nn(this.mimeType,this.dimensions,this.options.filename);s=[this.theme.fallbackColor(o)]}return this.cachedLines=s,this.cachedWidth=e,s}};var hn=Xs(),pe=class{constructor(){this.value="";this.cursor=0;this.focused=!1;this.pasteBuffer="";this.isInPaste=!1;this.killRing=new Bn;this.lastAction=null;this.undoStack=new Kn}getValue(){return this.value}setValue(e){this.value=e,this.cursor=Math.min(this.cursor,e.length)}handleInput(e){if(e.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",e=e.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=e;let o=this.pasteBuffer.indexOf("\x1B[201~");if(o!==-1){let r=this.pasteBuffer.substring(0,o);this.handlePaste(r),this.isInPaste=!1;let a=this.pasteBuffer.substring(o+6);this.pasteBuffer="",a&&this.handleInput(a)}return}let t=V();if(t.matches(e,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(t.matches(e,"tui.editor.undo")){this.undo();return}if(t.matches(e,"tui.input.submit")||e===`
|
|
62
|
+
`){this.onSubmit&&this.onSubmit(this.value);return}if(t.matches(e,"tui.editor.deleteCharBackward")){this.handleBackspace();return}if(t.matches(e,"tui.editor.deleteCharForward")){this.handleForwardDelete();return}if(t.matches(e,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(t.matches(e,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(t.matches(e,"tui.editor.deleteToLineStart")){this.deleteToLineStart();return}if(t.matches(e,"tui.editor.deleteToLineEnd")){this.deleteToLineEnd();return}if(t.matches(e,"tui.editor.yank")){this.yank();return}if(t.matches(e,"tui.editor.yankPop")){this.yankPop();return}if(t.matches(e,"tui.editor.cursorLeft")){if(this.lastAction=null,this.cursor>0){let o=this.value.slice(0,this.cursor),r=[...hn.segment(o)],a=r[r.length-1];this.cursor-=a?a.segment.length:1}return}if(t.matches(e,"tui.editor.cursorRight")){if(this.lastAction=null,this.cursor<this.value.length){let o=this.value.slice(this.cursor),a=[...hn.segment(o)][0];this.cursor+=a?a.segment.length:1}return}if(t.matches(e,"tui.editor.cursorLineStart")){this.lastAction=null,this.cursor=0;return}if(t.matches(e,"tui.editor.cursorLineEnd")){this.lastAction=null,this.cursor=this.value.length;return}if(t.matches(e,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(t.matches(e,"tui.editor.cursorWordRight")){this.moveWordForwards();return}let n=io(e);if(n!==void 0){this.insertCharacter(n);return}[...e].some(o=>{let r=o.charCodeAt(0);return r<32||r===127||r>=128&&r<=159})||this.insertCharacter(e)}insertCharacter(e){(Oe(e)||this.lastAction!=="type-word")&&this.pushUndo(),this.lastAction="type-word",this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let e=this.value.slice(0,this.cursor),t=[...hn.segment(e)],n=t[t.length-1],s=n?n.segment.length:1;this.value=this.value.slice(0,this.cursor-s)+this.value.slice(this.cursor),this.cursor-=s}}handleForwardDelete(){if(this.lastAction=null,this.cursor<this.value.length){this.pushUndo();let e=this.value.slice(this.cursor),n=[...hn.segment(e)][0],s=n?n.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+s)}}deleteToLineStart(){if(this.cursor===0)return;this.pushUndo();let e=this.value.slice(0,this.cursor);this.killRing.push(e,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(this.cursor),this.cursor=0}deleteToLineEnd(){if(this.cursor>=this.value.length)return;this.pushUndo();let e=this.value.slice(this.cursor);this.killRing.push(e,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(this.cursor===0)return;let e=this.lastAction==="kill";this.pushUndo();let t=this.cursor;this.moveWordBackwards();let n=this.cursor;this.cursor=t;let s=this.value.slice(n,this.cursor);this.killRing.push(s,{prepend:!0,accumulate:e}),this.lastAction="kill",this.value=this.value.slice(0,n)+this.value.slice(this.cursor),this.cursor=n}deleteWordForward(){if(this.cursor>=this.value.length)return;let e=this.lastAction==="kill";this.pushUndo();let t=this.cursor;this.moveWordForwards();let n=this.cursor;this.cursor=t;let s=this.value.slice(this.cursor,n);this.killRing.push(s,{prepend:!1,accumulate:e}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)+this.value.slice(n)}yank(){let e=this.killRing.peek();e&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length,this.lastAction="yank")}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndo();let e=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor-e.length)+this.value.slice(this.cursor),this.cursor-=e.length,this.killRing.rotate();let t=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length,this.lastAction="yank"}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){let e=this.undoStack.pop();e&&(this.value=e.value,this.cursor=e.cursor,this.lastAction=null)}moveWordBackwards(){if(this.cursor===0)return;this.lastAction=null;let e=this.value.slice(0,this.cursor),t=[...hn.segment(e)];for(;t.length>0&&Oe(t[t.length-1]?.segment||"");)this.cursor-=t.pop()?.segment.length||0;if(t.length>0){let n=t[t.length-1]?.segment||"";if(Ue(n))for(;t.length>0&&Ue(t[t.length-1]?.segment||"");)this.cursor-=t.pop()?.segment.length||0;else for(;t.length>0&&!Oe(t[t.length-1]?.segment||"")&&!Ue(t[t.length-1]?.segment||"");)this.cursor-=t.pop()?.segment.length||0}}moveWordForwards(){if(this.cursor>=this.value.length)return;this.lastAction=null;let e=this.value.slice(this.cursor),n=hn.segment(e)[Symbol.iterator](),s=n.next();for(;!s.done&&Oe(s.value.segment);)this.cursor+=s.value.segment.length,s=n.next();if(!s.done){let o=s.value.segment;if(Ue(o))for(;!s.done&&Ue(s.value.segment);)this.cursor+=s.value.segment.length,s=n.next();else for(;!s.done&&!Oe(s.value.segment)&&!Ue(s.value.segment);)this.cursor+=s.value.segment.length,s=n.next()}}handlePaste(e){this.lastAction=null,this.pushUndo();let t=e.replace(/\r\n/g,"").replace(/\r/g,"").replace(/\n/g,"").replace(/\t/g," ");this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length}invalidate(){}render(e){let n=e-2;if(n<=0)return["> "];let s="",o=this.cursor,r=W(this.value);if(r<n)s=this.value;else{let v=this.cursor===this.value.length?n-1:n,w=W(this.value.slice(0,this.cursor));if(v>0){let C=Math.floor(v/2),R=0;w<C?R=0:w>r-C?R=Math.max(0,r-v):R=Math.max(0,w-C),s=Fn(this.value,R,v,!0),o=Fn(this.value,R,Math.max(0,w-R),!0).length}else s="",o=0}let l=[...hn.segment(s.slice(o))][0],c=s.slice(0,o),d=l?.segment??" ",p=s.slice(o+d.length),u=this.focused?dn:"",h=`\x1B[7m${d}\x1B[27m`,m=c+u+h+p,g=W(m),x=" ".repeat(Math.max(0,n-g));return["> "+m+x]}};import{Marked as vf,Tokenizer as yf}from"marked";var wf=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,aa=class extends yf{del(e){let t=wf.exec(e);if(!t)return;let n=t[2];return{type:"del",raw:t[0],text:n,tokens:this.lexer.inlineTokens(n)}}},kp=new vf;kp.setOptions({tokenizer:new aa});var le=class{constructor(e,t,n,s,o){this.text=e,this.paddingX=t,this.paddingY=n,this.theme=s,this.defaultTextStyle=o}setText(e){this.text=e,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;let t=Math.max(1,e-this.paddingX*2);if(!this.text||this.text.trim()===""){let m=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=m,m}let n=this.text.replace(/\t/g," "),s=kp.lexer(n),o=[];for(let m=0;m<s.length;m++){let g=s[m],x=s[m+1],b=this.renderToken(g,t,x?.type);o.push(...b)}let r=[];for(let m of o)pn(m)?r.push(m):r.push(...ct(m,t));let a=" ".repeat(this.paddingX),l=" ".repeat(this.paddingX),c=this.defaultTextStyle?.bgColor,d=[];for(let m of r){if(pn(m)){d.push(m);continue}let g=a+m+l;if(c)d.push(Kt(g,e,c));else{let x=W(g),b=Math.max(0,e-x);d.push(g+" ".repeat(b))}}let p=" ".repeat(e),u=[];for(let m=0;m<this.paddingY;m++){let g=c?Kt(p,e,c):p;u.push(g)}let h=[...u,...d,...u];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=h,h.length>0?h:[""]}applyDefaultStyle(e){if(!this.defaultTextStyle)return e;let t=e;return this.defaultTextStyle.color&&(t=this.defaultTextStyle.color(t)),this.defaultTextStyle.bold&&(t=this.theme.bold(t)),this.defaultTextStyle.italic&&(t=this.theme.italic(t)),this.defaultTextStyle.strikethrough&&(t=this.theme.strikethrough(t)),this.defaultTextStyle.underline&&(t=this.theme.underline(t)),t}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let e="\0",t=e;this.defaultTextStyle.color&&(t=this.defaultTextStyle.color(t)),this.defaultTextStyle.bold&&(t=this.theme.bold(t)),this.defaultTextStyle.italic&&(t=this.theme.italic(t)),this.defaultTextStyle.strikethrough&&(t=this.theme.strikethrough(t)),this.defaultTextStyle.underline&&(t=this.theme.underline(t));let n=t.indexOf(e);return this.defaultStylePrefix=n>=0?t.slice(0,n):"",this.defaultStylePrefix}getStylePrefix(e){let n=e("\0"),s=n.indexOf("\0");return s>=0?n.slice(0,s):""}getDefaultInlineStyleContext(){return{applyText:e=>this.applyDefaultStyle(e),stylePrefix:this.getDefaultStylePrefix()}}renderToken(e,t,n,s){let o=[];switch(e.type){case"heading":{let r=e.depth,a=`${"#".repeat(r)} `,l;r===1?l=u=>this.theme.heading(this.theme.bold(this.theme.underline(u))):l=u=>this.theme.heading(this.theme.bold(u));let c={applyText:l,stylePrefix:this.getStylePrefix(l)},d=this.renderInlineTokens(e.tokens||[],c),p=r>=3?l(a)+d:d;o.push(p),n&&n!=="space"&&o.push("");break}case"paragraph":{let r=this.renderInlineTokens(e.tokens||[],s);o.push(r),n&&n!=="list"&&n!=="space"&&o.push("");break}case"text":o.push(this.renderInlineTokens([e],s));break;case"code":{let r=this.theme.codeBlockIndent??" ";if(o.push(this.theme.codeBlockBorder(`\`\`\`${e.lang||""}`)),this.theme.highlightCode){let a=this.theme.highlightCode(e.text,e.lang);for(let l of a)o.push(`${r}${l}`)}else{let a=e.text.split(`
|
|
63
|
+
`);for(let l of a)o.push(`${r}${this.theme.codeBlock(l)}`)}o.push(this.theme.codeBlockBorder("```")),n&&n!=="space"&&o.push("");break}case"list":{let r=this.renderList(e,0,t,s);o.push(...r);break}case"table":{let r=this.renderTable(e,t,n,s);o.push(...r);break}case"blockquote":{let r=h=>this.theme.quote(this.theme.italic(h)),a=this.getStylePrefix(r),l=h=>{if(!a)return r(h);let m=h.replace(/\x1b\[0m/g,`\x1B[0m${a}`);return r(m)},c=Math.max(1,t-2),d={applyText:h=>h,stylePrefix:a},p=e.tokens||[],u=[];for(let h=0;h<p.length;h++){let m=p[h],g=p[h+1];u.push(...this.renderToken(m,c,g?.type,d))}for(;u.length>0&&u[u.length-1]==="";)u.pop();for(let h of u){let m=l(h),g=ct(m,c);for(let x of g)o.push(this.theme.quoteBorder("\u2502 ")+x)}n&&n!=="space"&&o.push("");break}case"hr":o.push(this.theme.hr("\u2500".repeat(Math.min(t,80)))),n&&n!=="space"&&o.push("");break;case"html":"raw"in e&&typeof e.raw=="string"&&o.push(this.applyDefaultStyle(e.raw.trim()));break;case"space":o.push("");break;default:"text"in e&&typeof e.text=="string"&&o.push(e.text)}return o}renderInlineTokens(e,t){let n="",s=t??this.getDefaultInlineStyleContext(),{applyText:o,stylePrefix:r}=s,a=l=>l.split(`
|
|
64
|
+
`).map(d=>o(d)).join(`
|
|
65
|
+
`);for(let l of e)switch(l.type){case"text":l.tokens&&l.tokens.length>0?n+=this.renderInlineTokens(l.tokens,s):n+=a(l.text);break;case"paragraph":n+=this.renderInlineTokens(l.tokens||[],s);break;case"strong":{let c=this.renderInlineTokens(l.tokens||[],s);n+=this.theme.bold(c)+r;break}case"em":{let c=this.renderInlineTokens(l.tokens||[],s);n+=this.theme.italic(c)+r;break}case"codespan":n+=this.theme.code(l.text)+r;break;case"link":{let c=this.renderInlineTokens(l.tokens||[],s),d=this.theme.link(this.theme.underline(c));if(ve().hyperlinks)n+=Xi(d,l.href)+r;else{let p=l.href.startsWith("mailto:")?l.href.slice(7):l.href;l.text===l.href||l.text===p?n+=d+r:n+=d+this.theme.linkUrl(` (${l.href})`)+r}break}case"br":n+=`
|
|
66
|
+
`;break;case"del":{let c=this.renderInlineTokens(l.tokens||[],s);n+=this.theme.strikethrough(c)+r;break}case"html":"raw"in l&&typeof l.raw=="string"&&(n+=a(l.raw));break;default:"text"in l&&typeof l.text=="string"&&(n+=a(l.text))}for(;r&&n.endsWith(r);)n=n.slice(0,-r.length);return n}renderList(e,t,n,s){let o=[],r=" ".repeat(t),a=typeof e.start=="number"?e.start:1;for(let l=0;l<e.items.length;l++){let c=e.items[l],d=e.ordered?`${a+l}. `:"- ",p=r+this.theme.listBullet(d),u=r+" ".repeat(W(d)),h=Math.max(1,n-W(p)),m=!1;for(let g of c.tokens){if(g.type==="list"){o.push(...this.renderList(g,t+1,n,s)),m=!0;continue}let x=this.renderToken(g,h,void 0,s);for(let b of x)for(let v of ct(b,h)){let w=m?u:p;o.push(w+v),m=!0}}m||o.push(p)}return o}getLongestWordWidth(e,t){let n=e.split(/\s+/).filter(o=>o.length>0),s=0;for(let o of n)s=Math.max(s,W(o));return t===void 0?s:Math.min(s,t)}wrapCellText(e,t){return ct(e,Math.max(1,t))}renderTable(e,t,n,s){let o=[],r=e.header.length;if(r===0)return o;let a=3*r+1,l=t-a;if(l<r){let k=e.raw?ct(e.raw,t):[];return n&&n!=="space"&&k.push(""),k}let c=30,d=[],p=[];for(let k=0;k<r;k++){let A=this.renderInlineTokens(e.header[k].tokens||[],s);d[k]=W(A),p[k]=Math.max(1,this.getLongestWordWidth(A,c))}for(let k of e.rows)for(let A=0;A<k.length;A++){let S=this.renderInlineTokens(k[A].tokens||[],s);d[A]=Math.max(d[A]||0,W(S)),p[A]=Math.max(p[A]||1,this.getLongestWordWidth(S,c))}let u=p,h=u.reduce((k,A)=>k+A,0);if(h>l){u=new Array(r).fill(1);let k=l-r;if(k>0){let A=p.reduce((M,_)=>M+Math.max(0,_-1),0),S=p.map(M=>{let _=Math.max(0,M-1);return A>0?Math.floor(_/A*k):0});for(let M=0;M<r;M++)u[M]+=S[M]??0;let I=S.reduce((M,_)=>M+_,0),P=k-I;for(let M=0;P>0&&M<r;M++)u[M]++,P--}h=u.reduce((A,S)=>A+S,0)}let m=d.reduce((k,A)=>k+A,0)+a,g;if(m<=t)g=d.map((k,A)=>Math.max(k,u[A]));else{let k=d.reduce((P,M,_)=>P+Math.max(0,M-u[_]),0),A=Math.max(0,l-h);g=u.map((P,M)=>{let _=d[M],U=Math.max(0,_-P),F=0;return k>0&&(F=Math.floor(U/k*A)),P+F});let S=g.reduce((P,M)=>P+M,0),I=l-S;for(;I>0;){let P=!1;for(let M=0;M<r&&I>0;M++)g[M]<d[M]&&(g[M]++,I--,P=!0);if(!P)break}}let x=g.map(k=>"\u2500".repeat(k));o.push(`\u250C\u2500${x.join("\u2500\u252C\u2500")}\u2500\u2510`);let b=e.header.map((k,A)=>{let S=this.renderInlineTokens(k.tokens||[],s);return this.wrapCellText(S,g[A])}),v=Math.max(...b.map(k=>k.length));for(let k=0;k<v;k++){let A=b.map((S,I)=>{let P=S[k]||"",M=P+" ".repeat(Math.max(0,g[I]-W(P)));return this.theme.bold(M)});o.push(`\u2502 ${A.join(" \u2502 ")} \u2502`)}let C=`\u251C\u2500${g.map(k=>"\u2500".repeat(k)).join("\u2500\u253C\u2500")}\u2500\u2524`;o.push(C);for(let k=0;k<e.rows.length;k++){let S=e.rows[k].map((P,M)=>{let _=this.renderInlineTokens(P.tokens||[],s);return this.wrapCellText(_,g[M])}),I=Math.max(...S.map(P=>P.length));for(let P=0;P<I;P++){let M=S.map((_,U)=>{let F=_[P]||"";return F+" ".repeat(Math.max(0,g[U]-W(F)))});o.push(`\u2502 ${M.join(" \u2502 ")} \u2502`)}k<e.rows.length-1&&o.push(C)}let R=g.map(k=>"\u2500".repeat(k));return o.push(`\u2514\u2500${R.join("\u2500\u2534\u2500")}\u2500\u2518`),n&&n!=="space"&&o.push(""),o}};var zn=class{constructor(e,t,n,s,o,r={}){this.selectedIndex=0;this.submenuComponent=null;this.submenuItemIndex=null;this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=n,this.onChange=s,this.onCancel=o,this.searchEnabled=r.enableSearch??!1,this.searchEnabled&&(this.searchInput=new pe)}updateValue(e,t){let n=this.items.find(s=>s.id===e);n&&(n.currentValue=t)}invalidate(){this.submenuComponent?.invalidate?.()}render(e){return this.submenuComponent?this.submenuComponent.render(e):this.renderMainList(e)}renderMainList(e){let t=[];if(this.searchEnabled&&this.searchInput&&(t.push(...this.searchInput.render(e)),t.push("")),this.items.length===0)return t.push(this.theme.hint(" No settings available")),this.searchEnabled&&this.addHintLine(t,e),t;let n=this.searchEnabled?this.filteredItems:this.items;if(n.length===0)return t.push(G(this.theme.hint(" No matching settings"),e)),this.addHintLine(t,e),t;let s=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),n.length-this.maxVisible)),o=Math.min(s+this.maxVisible,n.length),r=Math.min(30,Math.max(...this.items.map(l=>W(l.label))));for(let l=s;l<o;l++){let c=n[l];if(!c)continue;let d=l===this.selectedIndex,p=d?this.theme.cursor:" ",u=W(p),h=c.label+" ".repeat(Math.max(0,r-W(c.label))),m=this.theme.label(h,d),g=" ",x=u+r+W(g),b=e-x-2,v=this.theme.value(G(c.currentValue,b,""),d);t.push(G(p+m+g+v,e))}if(s>0||o<n.length){let l=` (${this.selectedIndex+1}/${n.length})`;t.push(this.theme.hint(G(l,e-2,"")))}let a=n[this.selectedIndex];if(a?.description){t.push("");let l=ct(a.description,e-4);for(let c of l)t.push(this.theme.description(` ${c}`))}return this.addHintLine(t,e),t}handleInput(e){if(this.submenuComponent){this.submenuComponent.handleInput?.(e);return}let t=V(),n=this.searchEnabled?this.filteredItems:this.items;if(t.matches(e,"tui.select.up")){if(n.length===0)return;this.selectedIndex=this.selectedIndex===0?n.length-1:this.selectedIndex-1}else if(t.matches(e,"tui.select.down")){if(n.length===0)return;this.selectedIndex=this.selectedIndex===n.length-1?0:this.selectedIndex+1}else if(t.matches(e,"tui.select.confirm")||e===" ")this.activateItem();else if(t.matches(e,"tui.select.cancel"))this.onCancel();else if(this.searchEnabled&&this.searchInput){let s=e.replace(/ /g,"");if(!s)return;this.searchInput.handleInput(s),this.applyFilter(this.searchInput.getValue())}}activateItem(){let e=this.searchEnabled?this.filteredItems[this.selectedIndex]:this.items[this.selectedIndex];if(e){if(e.submenu)this.submenuItemIndex=this.selectedIndex,this.submenuComponent=e.submenu(e.currentValue,t=>{t!==void 0&&(e.currentValue=t,this.onChange(e.id,t)),this.closeSubmenu()});else if(e.values&&e.values.length>0){let n=(e.values.indexOf(e.currentValue)+1)%e.values.length,s=e.values[n];e.currentValue=s,this.onChange(e.id,s)}}}closeSubmenu(){this.submenuComponent=null,this.submenuItemIndex!==null&&(this.selectedIndex=this.submenuItemIndex,this.submenuItemIndex=null)}applyFilter(e){this.filteredItems=We(this.items,e,t=>t.label),this.selectedIndex=0}addHintLine(e,t){e.push(""),e.push(G(this.theme.hint(this.searchEnabled?" Type to search \xB7 Enter/Space to change \xB7 Esc to cancel":" Enter/Space to change \xB7 Esc to cancel"),t))}};var E=class{constructor(e=1){this.lines=e}setLines(e){this.lines=e}invalidate(){}render(e){let t=[];for(let n=0;n<this.lines;n++)t.push("");return t}};var $e=class{constructor(e,t=0,n=0){this.text=e,this.paddingX=t,this.paddingY=n}invalidate(){}render(e){let t=[],n=" ".repeat(e);for(let m=0;m<this.paddingY;m++)t.push(n);let s=Math.max(1,e-this.paddingX*2),o=this.text,r=this.text.indexOf(`
|
|
67
|
+
`);r!==-1&&(o=this.text.substring(0,r));let a=G(o,s),l=" ".repeat(this.paddingX),c=" ".repeat(this.paddingX),d=l+a+c,p=W(d),u=Math.max(0,e-p),h=d+" ".repeat(u);t.push(h);for(let m=0;m<this.paddingY;m++)t.push(n);return t}};import{EventEmitter as kf}from"events";var Pt="\x1B",Sp="\x1B[200~",ao="\x1B[201~";function Sf(i){if(!i.startsWith(Pt))return"not-escape";if(i.length===1)return"incomplete";let e=i.slice(1);return e.startsWith("[")?e.startsWith("[M")?i.length>=6?"complete":"incomplete":Tf(i):e.startsWith("]")?Cf(i):e.startsWith("P")?Mf(i):e.startsWith("_")?Rf(i):e.startsWith("O")?e.length>=2?"complete":"incomplete":(e.length===1,"complete")}function Tf(i){if(!i.startsWith(`${Pt}[`))return"complete";if(i.length<3)return"incomplete";let e=i.slice(2),t=e[e.length-1],n=t.charCodeAt(0);if(n>=64&&n<=126){if(e.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(e))return"complete";if(t==="M"||t==="m"){let o=e.slice(1,-1).split(";");if(o.length===3&&o.every(r=>/^\d+$/.test(r)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function Cf(i){return!i.startsWith(`${Pt}]`)||i.endsWith(`${Pt}\\`)||i.endsWith("\x07")?"complete":"incomplete"}function Mf(i){return!i.startsWith(`${Pt}P`)||i.endsWith(`${Pt}\\`)?"complete":"incomplete"}function Rf(i){return!i.startsWith(`${Pt}_`)||i.endsWith(`${Pt}\\`)?"complete":"incomplete"}function Ef(i){let e=i.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!e)return;let t=parseInt(e[1],10);return t>=32?t:void 0}function Tp(i){let e=[],t=0;for(;t<i.length;){let n=i.slice(t);if(n.startsWith(Pt)){let s=1;for(;s<=n.length;){let o=n.slice(0,s),r=Sf(o);if(r==="complete"){e.push(o),t+=s;break}else if(r==="incomplete")s++;else{e.push(o),t+=s;break}}if(s>n.length)return{sequences:e,remainder:n}}else e.push(n[0]),t++}return{sequences:e,remainder:""}}var Zi=class extends kf{constructor(t={}){super();this.buffer="";this.timeout=null;this.pasteMode=!1;this.pasteBuffer="";this.timeoutMs=t.timeout??10}process(t){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let n;if(Buffer.isBuffer(t))if(t.length===1&&t[0]>127){let r=t[0]-128;n=`\x1B${String.fromCharCode(r)}`}else n=t.toString();else n=t;if(n.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=n,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let r=this.pasteBuffer.indexOf(ao);if(r!==-1){let a=this.pasteBuffer.slice(0,r),l=this.pasteBuffer.slice(r+ao.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",a),l.length>0&&this.process(l)}return}let s=this.buffer.indexOf(Sp);if(s!==-1){if(s>0){let a=this.buffer.slice(0,s),l=Tp(a);for(let c of l.sequences)this.emitDataSequence(c)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(s+Sp.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let r=this.pasteBuffer.indexOf(ao);if(r!==-1){let a=this.pasteBuffer.slice(0,r),l=this.pasteBuffer.slice(r+ao.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",a),l.length>0&&this.process(l)}return}let o=Tp(this.buffer);this.buffer=o.remainder;for(let r of o.sequences)this.emitDataSequence(r);this.buffer.length>0&&(this.timeout=setTimeout(()=>{let r=this.flush();for(let a of r)this.emitDataSequence(a)},this.timeoutMs))}emitDataSequence(t){let n=t.length===1?t.codePointAt(0):void 0;if(n!==void 0&&n===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=Ef(t),this.emit("data",t)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return[];let t=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,t}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}};import*as lo from"node:fs";import{createRequire as If}from"node:module";import*as Rp from"node:path";var Af=If(import.meta.url),Pf=1e3,Cp="\x1B]9;4;3\x07",Mp="\x1B]9;4;0;\x07",jt=class{constructor(){this.wasRaw=!1;this._kittyProtocolActive=!1;this._modifyOtherKeysActive=!1;this.writeLogPath=(()=>{let e=process.env.PI_TUI_WRITE_LOG||"";if(!e)return"";try{if(lo.statSync(e).isDirectory()){let t=new Date,n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}_${String(t.getHours()).padStart(2,"0")}-${String(t.getMinutes()).padStart(2,"0")}-${String(t.getSeconds()).padStart(2,"0")}`;return Rp.join(e,`tui-${n}-${process.pid}.log`)}}catch{}return e})()}get kittyProtocolActive(){return this._kittyProtocolActive}start(e,t){this.inputHandler=e,this.resizeHandler=t,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdout.write("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),process.platform!=="win32"&&process.kill(process.pid,"SIGWINCH"),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new Zi({timeout:10});let e=/^\x1b\[\?(\d+)u$/;this.stdinBuffer.on("data",t=>{if(!this._kittyProtocolActive&&t.match(e)){this._kittyProtocolActive=!0,Vi(!0),process.stdout.write("\x1B[>7u");return}this.inputHandler&&this.inputHandler(t)}),this.stdinBuffer.on("paste",t=>{this.inputHandler&&this.inputHandler(`\x1B[200~${t}\x1B[201~`)}),this.stdinDataHandler=t=>{this.stdinBuffer.process(t)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),process.stdout.write("\x1B[?u"),setTimeout(()=>{!this._kittyProtocolActive&&!this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)},150)}enableWindowsVTInput(){if(process.platform==="win32")try{let t=Af("koffi").load("kernel32.dll"),n=t.func("void* __stdcall GetStdHandle(int)"),s=t.func("bool __stdcall GetConsoleMode(void*, _Out_ uint32_t*)"),o=t.func("bool __stdcall SetConsoleMode(void*, uint32_t)"),r=-10,a=512,l=n(r),c=new Uint32Array(1);s(l,c),o(l,c[0]|a)}catch{}}async drainInput(e=1e3,t=50){this._kittyProtocolActive&&(process.stdout.write("\x1B[<u"),this._kittyProtocolActive=!1,Vi(!1)),this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=!1);let n=this.inputHandler;this.inputHandler=void 0;let s=Date.now(),o=()=>{s=Date.now()};process.stdin.on("data",o);let r=Date.now()+e;try{for(;;){let a=Date.now(),l=r-a;if(l<=0||a-s>=t)break;await new Promise(c=>setTimeout(c,Math.min(t,l)))}}finally{process.stdin.removeListener("data",o),this.inputHandler=n}}stop(){this.clearProgressInterval()&&process.stdout.write(Mp),process.stdout.write("\x1B[?2004l"),this._kittyProtocolActive&&(process.stdout.write("\x1B[<u"),this._kittyProtocolActive=!1,Vi(!1)),this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=!1),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode&&process.stdin.setRawMode(this.wasRaw)}write(e){if(process.stdout.write(e),this.writeLogPath)try{lo.appendFileSync(this.writeLogPath,e,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(e){e>0?process.stdout.write(`\x1B[${e}B`):e<0&&process.stdout.write(`\x1B[${-e}A`)}hideCursor(){process.stdout.write("\x1B[?25l")}showCursor(){process.stdout.write("\x1B[?25h")}clearLine(){process.stdout.write("\x1B[K")}clearFromCursor(){process.stdout.write("\x1B[J")}clearScreen(){process.stdout.write("\x1B[2J\x1B[H")}setTitle(e){process.stdout.write(`\x1B]0;${e}\x07`)}setProgress(e){e?(process.stdout.write(Cp),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(Cp)},Pf))):(this.clearProgressInterval(),process.stdout.write(Mp))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var Ep="https://slingshot.sapientaiproducts.com/web/ai-auth-ui/login?client=desktop&source=publicis-groupe-msft&app_name=aipp&redirect_url=http://localhost:3269/callback",Ip="https://slingshot.sapientaiproducts.com/api/v1/ai-auth/auth/user/refreshtoken?client=desktop&source=publicis-groupe-msft&app_name=aipp",Ap="https://sapientaiproducts.com/api/v1/llm",Pp="https://slingshot.sapientaiproducts.com/api/v1/ai-portal/sage_events";var _p="fa8121c4-e2fc-48f1-9478-8949c04e13cc",Lp="6e5756eb-d7e2-4d80-ad07-9d7a51600d85",Wp="b97fbef7-cad9-4e56-9850-39e86c8fdf61";function es(i){try{let e=i.split(".");if(e.length!==3)return 0;let t=JSON.parse(atob(e[1]));return t.exp?t.exp*1e3:0}catch{return 0}}function co(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}function Op(){return`user_${co()}`}var ts=null,ca=null;typeof process<"u"&&process.versions?.node&&(ca=import("node:http").then(i=>{ts=i.createServer}));async function Lf(){if(ts||(ca&&await ca,ts))return ts;throw new Error("Slingshot OAuth requires Node.js")}async function Up(i){let e=await Lf();return new Promise((t,n)=>{let s=!1,o=e((a,l)=>{let c=new URL(a.url||"",`http://localhost:${3269}`);if(c.pathname!=="/callback"){l.writeHead(404,{"Content-Type":"text/plain"}),l.end("Not found");return}let d=c.searchParams.get("at")||c.searchParams.get("token")||c.searchParams.get("access_token"),p=c.searchParams.get("rt")||c.searchParams.get("refresh_token"),u=c.searchParams.get("error"),h=c.searchParams.get("error_description"),m=c.searchParams.get("x-project-id")||void 0,g=c.searchParams.get("x-workspace-id")||void 0;if(u){l.writeHead(400,{"Content-Type":"text/html"}),l.end(`<html><body><h1>Login Failed</h1><p>${h||u}</p><p>You can close this window.</p></body></html>`),s||(s=!0,o.close(),n(new Error(`Login failed: ${h||u}`)));return}if(!d){l.writeHead(400,{"Content-Type":"text/html"}),l.end("<html><body><h1>Login Failed</h1><p>No token received.</p><p>You can close this window.</p></body></html>"),s||(s=!0,o.close(),n(new Error("No access token received")));return}l.writeHead(200,{"Content-Type":"text/html"}),l.end("<html><body><h1>Login Successful</h1><p>You can close this window and return to your terminal.</p><script>setTimeout(()=>window.close(),3000)</script></body></html>"),s||(s=!0,o.close(),t({accessToken:d,refreshToken:p||"",projectId:m,workspaceId:g}))});o.listen(3269,()=>{}),o.on("error",a=>{s||(s=!0,n(a.code==="EADDRINUSE"?new Error(`Port ${3269} is already in use`):a))});let r=setTimeout(()=>{s||(s=!0,o.close(),n(new Error("Login timeout - no callback received within 5 minutes")))},300*1e3);i&&i.addEventListener("abort",()=>{clearTimeout(r),s||(s=!0,o.close(),n(new Error("Login cancelled")))}),o.on("close",()=>clearTimeout(r))})}async function pa(i){let e=process.env.SLINGSHOT_TOKEN;if(e){let o=es(e);return console.log("Using Slingshot token from SLINGSHOT_TOKEN environment variable"),{refresh:"",access:e,expires:o>0?o-3e5:Date.now()+10800*1e3,projectId:process.env.SLINGSHOT_PROJECT_ID,workspaceId:process.env.SLINGSHOT_WORKSPACE_ID}}let t=Up(i.signal);i.onAuth({url:Ep});let n;if(i.onManualCodeInput){let o=i.onManualCodeInput().then(r=>{let a=new URL(r),l=a.searchParams.get("at")||a.searchParams.get("token")||a.searchParams.get("access_token"),c=a.searchParams.get("rt")||a.searchParams.get("refresh_token");if(!l)throw new Error("No access token found in pasted URL");return{accessToken:l,refreshToken:c||"",projectId:a.searchParams.get("x-project-id")||void 0,workspaceId:a.searchParams.get("x-workspace-id")||void 0}});n=await Promise.race([t,o])}else n=await t;let s=es(n.accessToken);return{refresh:n.refreshToken,access:n.accessToken,expires:s>0?s-3e5:Date.now()+10800*1e3,projectId:n.projectId,workspaceId:n.workspaceId}}import{randomUUID as Wf}from"node:crypto";async function uo(i){if(!i.refresh)throw new Error("No refresh token available. Please login again.");let e=!1,t=Wf(),n={accept:"application/json",rt:i.refresh,"trace-id":t};e&&process.env.APP_KEY&&(n["app-key"]=process.env.APP_KEY);let s;try{s=await fetch(Ip,{headers:n})}catch(a){let l=a instanceof Error?a.message:String(a);throw new Error(`Cannot reach Slingshot server: ${l}`)}if(!s.ok){let a=`${s.status} ${s.statusText}`;try{let l=await s.json();l.message?a=String(l.message):l.error&&(a=String(l.error))}catch{}throw new Error(`Token refresh failed: ${a}`)}let o=await s.json();if(!o.accessToken)throw new Error("No access token in refresh response");let r=es(o.accessToken);return{refresh:o.refreshToken||i.refresh,access:o.accessToken,expires:r>0?r-3e5:Date.now()+10800*1e3,projectId:i.projectId,workspaceId:i.workspaceId}}var Dp=[{id:"claude-opus-4@20250514",name:"Claude Opus 4",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3},{id:"claude-sonnet-4@20250514",name:"Claude Sonnet 4",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},{id:"claude-sonnet-4-5@20250929",name:"Claude Sonnet 4.5",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3},{id:"claude-opus-4-6",name:"Claude Opus 4.6",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3},{id:"gpt-5",name:"GPT-5",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},{id:"gpt-5-mini",name:"GPT-5 Mini",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},{id:"gpt-5-nano",name:"GPT-5 Nano",reasoning:!0,input:["text","image"],cost:{input:.05,output:.4,cacheRead:.005,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},{id:"gpt-5.1",name:"GPT-5.1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.13,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},{id:"gpt-5.2",name:"GPT-5.2",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3},{id:"gpt-4.1",name:"GPT-4.1",reasoning:!1,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:1047576,maxTokens:32768},{id:"o3",name:"O3",reasoning:!0,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},{id:"o3-mini",name:"o3-mini",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.55,cacheWrite:0},contextWindow:2e5,maxTokens:1e5},{id:"o4-mini",name:"o4-mini",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.28,cacheWrite:0},contextWindow:2e5,maxTokens:1e5}];var _t=null,qt=null,da=process.env.SLINGSHOT_DEBUG==="true";function yt(){return da}function Fp(i){da=i,i?ua():_t=null}function $p(){return _t}function ua(){if(da)try{if(typeof process<"u"&&process.versions?.node){qt=Qs("fs");let i=Qs("path"),e=Qs("os"),t=process.env.SLINGSHOT_LOG_DIR||i.join(e.homedir(),".sling"),n=i.join(t,"logs","analytics");qt.existsSync(n)||qt.mkdirSync(n,{recursive:!0});let s=new Date().toISOString().replace(/[:.]/g,"-").slice(0,-5);_t=i.join(n,`${s}.log`);let o=`
|
|
14
68
|
\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
|
|
15
69
|
\u2551 SLINGSHOT ANALYTICS DEBUG LOG \u2551
|
|
16
70
|
\u2551 Started: ${new Date().toISOString()} \u2551
|
|
17
71
|
\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
|
|
18
72
|
|
|
19
|
-
Log file: ${
|
|
73
|
+
Log file: ${_t}
|
|
20
74
|
|
|
21
|
-
`;
|
|
22
|
-
`;
|
|
23
|
-
${JSON.stringify(
|
|
75
|
+
`;qt.writeFileSync(_t,o)}}catch(i){console.warn("[Slingshot Analytics] Could not initialize file logging:",i)}}function Ie(i){if(!(!_t||!qt))try{let t=`[${new Date().toISOString()}] ${i}
|
|
76
|
+
`;qt.appendFileSync(_t,t)}catch{}}function mo(i,e){if(!(!_t||!qt))try{let n=`[${new Date().toISOString()}] ${i}:
|
|
77
|
+
${JSON.stringify(e,null,2)}
|
|
24
78
|
|
|
25
|
-
`;
|
|
79
|
+
`;qt.appendFileSync(_t,n)}catch{}}var ns={name:"slingshot.cli",private:!0,type:"module",workspaces:["packages/*","packages/web-ui/example","packages/coding-agent/examples/extensions/with-deps","packages/coding-agent/examples/extensions/custom-provider-anthropic","packages/coding-agent/examples/extensions/custom-provider-gitlab-duo","packages/coding-agent/examples/extensions/custom-provider-qwen-cli"],scripts:{clean:"npm run clean --workspaces",build:"cd packages/tui && npm run build && cd ../ai && npm run build && cd ../agent && npm run build && cd ../coding-agent && npm run build && cd ../mom && npm run build && cd ../web-ui && npm run build && cd ../pods && npm run build",dev:'concurrently --names "ai,agent,coding-agent,mom,web-ui,tui" --prefix-colors "cyan,yellow,red,white,green,magenta" "cd packages/ai && npm run dev" "cd packages/agent && npm run dev" "cd packages/coding-agent && npm run dev" "cd packages/mom && npm run dev" "cd packages/web-ui && npm run dev" "cd packages/tui && npm run dev"',"dev:tsc":'concurrently --names "ai,web-ui" --prefix-colors "cyan,green" "cd packages/ai && npm run dev:tsc" "cd packages/web-ui && npm run dev:tsc"',check:"","check:browser-smoke":"","profile:tui":"node scripts/profile-coding-agent-node.mjs --mode tui","profile:rpc":"node scripts/profile-coding-agent-node.mjs --mode rpc",test:"npm run test --workspaces --if-present","version:patch":"npm version patch -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:minor":"npm version minor -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:major":"npm version major -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:set":"npm version -ws",prepublishOnly:"npm run clean && npm run build && npm run check",publish:"npm run prepublishOnly && npm publish -ws --access public","publish:dry":"npm run prepublishOnly && npm publish -ws --access public --dry-run","release:patch":"node scripts/release.mjs patch","release:minor":"node scripts/release.mjs minor","release:major":"node scripts/release.mjs major",prepare:"husky"},devDependencies:{esbuild:"^0.25.0","@anthropic-ai/sandbox-runtime":"^0.0.26","@biomejs/biome":"2.3.5","@types/node":"^22.10.5","@typescript/native-preview":"7.0.0-dev.20260120.1",concurrently:"^9.2.1",husky:"^9.1.7",jiti:"^2.7.0",tsx:"^4.20.3",typescript:"^5.9.2",shx:"^0.4.0"},engines:{node:">=20.0.0"},slingVersion:"2.4.20260509-1",overrides:{rimraf:"6.1.3","fast-xml-parser":"5.7.2",gaxios:{rimraf:"6.1.3"}},dependencies:{"compound-engineering-pi":"^0.2.4","get-east-asian-width":"^1.4.0"}};async function ho(i,e,t,n){let s=Op(),o=await e.modelRegistry.getApiKeyForProvider(e.model?.provider||"slingshot");if(!o){yt()&&Ie("ERROR: No API key found");return}let r=o.startsWith("Bearer ")?o:`Bearer ${o}`,a=process.env.SLINGSHOT_PROJECT_ID||t?.projectId||_p,l=process.env.SLINGSHOT_WORKSPACE_ID||t?.workspaceId||Lp,c=process.env.CLIENT_ID||Wp,d={"Content-Type":"application/json",accept:"application/json","access-token":r,"x-project-id":a,"x-workspace-id":l,"x-client-id":c,"sage-trace-id":s,"User-Agent":"pi-slingshot/1.0.0"},p=parseFloat(process.env.SLINGSHOT_TEMPERATURE||"0.2"),u=parseFloat(process.env.SLINGSHOT_TOP_P||"0.8"),h={source:ns.name||"sling",ai_model_info:{ai_provider_name:e.model?.provider||"slingshot",sage_modl_name:e.model?.id||"unknown",sage_modl_option:{temperature:String(p),max_token_size:String(e.model?.maxTokens||16834),top_p:String(u)}},rag_info:{type:null,account_name:"dummy",project_names:[],repository_names:[],programming_language:null},tab_data:{tab_count:"1"},tags:null,slingshot_version:ns.slingVersion||"2.3.2",chat_type:"agent",...n||{}};return{headers:d,sageCommonData:h}}async function go(i,e,t,n){let s={eventName:i,sageCommonData:t,eventData:n};try{let o=await fetch(Pp,{method:"POST",headers:e,body:JSON.stringify(s)});if(o.ok){let r=await o.json().catch(()=>{});if(r.error_code)throw new Error(`Analytics API error: ${r.error_code} - ${r.error_message||"No message"}`);yt()&&(Ie(`'SUCCESS: Event sent: ${i}`),Ie(`Response: ${JSON.stringify(r)}`),Ie("\u2500".repeat(66)))}else{let r=await o.text().catch(()=>""),a={status:o.status,statusText:o.statusText,responseBody:r,requestHeaders:e};throw yt()&&(Ie(`ERROR: ${o.status} ${o.statusText}`),mo("Error Details",a),mo("Failed Request Body",s)),new Error(`Analytics API error: ${o.status} ${o.statusText}`)}}catch(o){let r=o instanceof Error?o.message:String(o);console.warn("[Slingshot Analytics] Request that caused error:",r),yt()&&(Ie(`EXCEPTION: ${r}`),o instanceof Error&&o.stack&&Ie(`Stack trace: ${o.stack}`),mo("Request that caused exception",s))}}import is from"chalk";function Bp(i,e){return{render(t){let n=` \u26AC _______. __ __ .__ __. _______
|
|
26
80
|
\u274D \xB7 \u274D / || | | | | \\ | | / _____|
|
|
27
81
|
\u2726 \u26AC \u2726 | (----\`| | | | | \\| | | | __
|
|
28
82
|
\u26AC \xB7 \u26AC \u26AC \xB7 \u26AC \\ \\ | | | | | . \` | | | |_ |
|
|
29
83
|
\u2726 \u26AC \u2726 .----) | | \`----.| | | |\\ | | |__| |
|
|
30
84
|
\u274D \xB7 \u274D |_______/ |_______||__| |__| \\__| \\______/
|
|
31
85
|
\u26AC `.split(`
|
|
32
|
-
`).map(r=>ce.bold(ce.white(ce.bgRed((r+" ".repeat(t)).substring(0,t))))),o=` Slingshot coding agent v${le.slingVersion}`;return[...i,ce.bgGray(ce.dim(o+" ".repeat(t)).substring(0,t))]},invalidate(){}}}import fs from"chalk";var qe=["Accomplishing","Actioning","Actualizing","Architecting","Baking","Beaming","Beboppin'","Befuddling","Billowing","Blanching","Bloviating","Boogieing","Boondoggling","Booping","Bootstrapping","Brewing","Bunning","Burrowing","Calculating","Canoodling","Caramelizing","Cascading","Catapulting","Cerebrating","Channeling","Channelling","Choreographing","Churning","Clauding","Coalescing","Cogitating","Combobulating","Composing","Computing","Concocting","Considering","Contemplating","Cooking","Crafting","Creating","Crunching","Crystallizing","Cultivating","Deciphering","Deliberating","Determining","Dilly-dallying","Discombobulating","Doing","Doodling","Drizzling","Ebbing","Effecting","Elucidating","Embellishing","Enchanting","Envisioning","Evaporating","Fermenting","Fiddle-faddling","Finagling","Flamb\xE9ing","Flibbertigibbeting","Flowing","Flummoxing","Fluttering","Forging","Forming","Frolicking","Frosting","Gallivanting","Galloping","Garnishing","Generating","Gesticulating","Germinating","Gitifying","Grooving","Gusting","Harmonizing","Hashing","Hatching","Herding","Honking","Hullaballooing","Hyperspacing","Ideating","Imagining","Improvising","Incubating","Inferring","Infusing","Ionizing","Jitterbugging","Julienning","Kneading","Leavening","Levitating","Lollygagging","Manifesting","Marinating","Meandering","Metamorphosing","Misting","Moonwalking","Moseying","Mulling","Mustering","Musing","Nebulizing","Nesting","Newspapering","Noodling","Nucleating","Orbiting","Orchestrating","Osmosing","Perambulating","Percolating","Perusing","Philosophising","Photosynthesizing","Pollinating","Pondering","Pontificating","Pouncing","Precipitating","Prestidigitating","Processing","Proofing","Propagating","Puttering","Puzzling","Quantumizing","Razzle-dazzling","Razzmatazzing","Recombobulating","Reticulating","Roosting","Ruminating","Saut\xE9ing","Scampering","Schlepping","Scurrying","Seasoning","Shenaniganing","Shimmying","Simmering","Skedaddling","Sketching","Slithering","Smooshing","Sock-hopping","Spelunking","Spinning","Sprouting","Stewing","Sublimating","Swirling","Swooping","Symbioting","Synthesizing","Tempering","Thinking","Thundering","Tinkering","Tomfoolering","Topsy-turvying","Transfiguring","Transmuting","Twisting","Undulating","Unfurling","Unravelling","Vibing","Waddling","Wandering","Warping","Whatchamacalliting","Whirlpooling","Whirring","Whisking","Wibbling","Working","Wrangling","Zesting","Zigzagging"];import q from"node:path";import{existsSync as Ye}from"node:fs";import{homedir as Lt}from"node:os";function Ge(e,s){s==="random"&&(s=Object.keys(ze)[Math.floor(Math.random()*Object.keys(ze).length)]);let t=ze[s||"dots"];e.ui.setWorkingIndicator(t)}var ze={dots:{intervalMs:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]},dots2:{intervalMs:80,frames:["\u28FE","\u28FD","\u28FB","\u28BF","\u287F","\u28DF","\u28EF","\u28F7"]},dots3:{intervalMs:80,frames:["\u280B","\u2819","\u281A","\u281E","\u2816","\u2826","\u2834","\u2832","\u2833","\u2813"]},dots4:{intervalMs:80,frames:["\u2804","\u2806","\u2807","\u280B","\u2819","\u2838","\u2830","\u2820","\u2830","\u2838","\u2819","\u280B","\u2807","\u2806"]},dots5:{intervalMs:80,frames:["\u280B","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B"]},dots6:{intervalMs:80,frames:["\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2834","\u2832","\u2812","\u2802","\u2802","\u2812","\u281A","\u2819","\u2809","\u2801"]},dots7:{intervalMs:80,frames:["\u2808","\u2809","\u280B","\u2813","\u2812","\u2810","\u2810","\u2812","\u2816","\u2826","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808"]},dots8:{intervalMs:80,frames:["\u2801","\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808","\u2808"]},dots9:{intervalMs:80,frames:["\u28B9","\u28BA","\u28BC","\u28F8","\u28C7","\u2867","\u2857","\u284F"]},dots10:{intervalMs:80,frames:["\u2884","\u2882","\u2881","\u2841","\u2848","\u2850","\u2860"]},dots11:{intervalMs:100,frames:["\u2801","\u2802","\u2804","\u2840","\u2880","\u2820","\u2810","\u2808"]},dots12:{intervalMs:80,frames:["\u2880\u2800","\u2840\u2800","\u2804\u2800","\u2882\u2800","\u2842\u2800","\u2805\u2800","\u2883\u2800","\u2843\u2800","\u280D\u2800","\u288B\u2800","\u284B\u2800","\u280D\u2801","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2888\u2829","\u2840\u2899","\u2804\u2859","\u2882\u2829","\u2842\u2898","\u2805\u2858","\u2883\u2828","\u2843\u2890","\u280D\u2850","\u288B\u2820","\u284B\u2880","\u280D\u2841","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2808\u2829","\u2800\u2899","\u2800\u2859","\u2800\u2829","\u2800\u2898","\u2800\u2858","\u2800\u2828","\u2800\u2890","\u2800\u2850","\u2800\u2820","\u2800\u2880","\u2800\u2840"]},dots13:{intervalMs:80,frames:["\u28FC","\u28F9","\u28BB","\u283F","\u285F","\u28CF","\u28E7","\u28F6"]},dots14:{intervalMs:80,frames:["\u2809\u2809","\u2808\u2819","\u2800\u2839","\u2800\u28B8","\u2800\u28F0","\u2880\u28E0","\u28C0\u28C0","\u28C4\u2840","\u28C6\u2800","\u2847\u2800","\u280F\u2800","\u280B\u2801"]},dots8Bit:{intervalMs:80,frames:["\u2800","\u2801","\u2802","\u2803","\u2804","\u2805","\u2806","\u2807","\u2840","\u2841","\u2842","\u2843","\u2844","\u2845","\u2846","\u2847","\u2808","\u2809","\u280A","\u280B","\u280C","\u280D","\u280E","\u280F","\u2848","\u2849","\u284A","\u284B","\u284C","\u284D","\u284E","\u284F","\u2810","\u2811","\u2812","\u2813","\u2814","\u2815","\u2816","\u2817","\u2850","\u2851","\u2852","\u2853","\u2854","\u2855","\u2856","\u2857","\u2818","\u2819","\u281A","\u281B","\u281C","\u281D","\u281E","\u281F","\u2858","\u2859","\u285A","\u285B","\u285C","\u285D","\u285E","\u285F","\u2820","\u2821","\u2822","\u2823","\u2824","\u2825","\u2826","\u2827","\u2860","\u2861","\u2862","\u2863","\u2864","\u2865","\u2866","\u2867","\u2828","\u2829","\u282A","\u282B","\u282C","\u282D","\u282E","\u282F","\u2868","\u2869","\u286A","\u286B","\u286C","\u286D","\u286E","\u286F","\u2830","\u2831","\u2832","\u2833","\u2834","\u2835","\u2836","\u2837","\u2870","\u2871","\u2872","\u2873","\u2874","\u2875","\u2876","\u2877","\u2838","\u2839","\u283A","\u283B","\u283C","\u283D","\u283E","\u283F","\u2878","\u2879","\u287A","\u287B","\u287C","\u287D","\u287E","\u287F","\u2880","\u2881","\u2882","\u2883","\u2884","\u2885","\u2886","\u2887","\u28C0","\u28C1","\u28C2","\u28C3","\u28C4","\u28C5","\u28C6","\u28C7","\u2888","\u2889","\u288A","\u288B","\u288C","\u288D","\u288E","\u288F","\u28C8","\u28C9","\u28CA","\u28CB","\u28CC","\u28CD","\u28CE","\u28CF","\u2890","\u2891","\u2892","\u2893","\u2894","\u2895","\u2896","\u2897","\u28D0","\u28D1","\u28D2","\u28D3","\u28D4","\u28D5","\u28D6","\u28D7","\u2898","\u2899","\u289A","\u289B","\u289C","\u289D","\u289E","\u289F","\u28D8","\u28D9","\u28DA","\u28DB","\u28DC","\u28DD","\u28DE","\u28DF","\u28A0","\u28A1","\u28A2","\u28A3","\u28A4","\u28A5","\u28A6","\u28A7","\u28E0","\u28E1","\u28E2","\u28E3","\u28E4","\u28E5","\u28E6","\u28E7","\u28A8","\u28A9","\u28AA","\u28AB","\u28AC","\u28AD","\u28AE","\u28AF","\u28E8","\u28E9","\u28EA","\u28EB","\u28EC","\u28ED","\u28EE","\u28EF","\u28B0","\u28B1","\u28B2","\u28B3","\u28B4","\u28B5","\u28B6","\u28B7","\u28F0","\u28F1","\u28F2","\u28F3","\u28F4","\u28F5","\u28F6","\u28F7","\u28B8","\u28B9","\u28BA","\u28BB","\u28BC","\u28BD","\u28BE","\u28BF","\u28F8","\u28F9","\u28FA","\u28FB","\u28FC","\u28FD","\u28FE","\u28FF"]},dotsCircle:{intervalMs:80,frames:["\u288E ","\u280E\u2801","\u280A\u2811","\u2808\u2831"," \u2871","\u2880\u2870","\u2884\u2860","\u2886\u2840"]},sand:{intervalMs:80,frames:["\u2801","\u2802","\u2804","\u2840","\u2848","\u2850","\u2860","\u28C0","\u28C1","\u28C2","\u28C4","\u28CC","\u28D4","\u28E4","\u28E5","\u28E6","\u28EE","\u28F6","\u28F7","\u28FF","\u287F","\u283F","\u289F","\u281F","\u285B","\u281B","\u282B","\u288B","\u280B","\u280D","\u2849","\u2809","\u2811","\u2821","\u2881"]},line:{intervalMs:130,frames:["-","\\","|","/"]},line2:{intervalMs:100,frames:["\u2802","-","\u2013","\u2014","\u2013","-"]},rollingLine:{intervalMs:80,frames:["/ "," - "," "," |"," |"," "," - ","/ "]},pipe:{intervalMs:100,frames:["\u2524","\u2518","\u2534","\u2514","\u251C","\u250C","\u252C","\u2510"]},simpleDots:{intervalMs:400,frames:[". ",".. ","..."," "]},simpleDotsScrolling:{intervalMs:200,frames:[". ",".. ","..."," .."," ."," "]},star:{intervalMs:70,frames:["\u2736","\u2738","\u2739","\u273A","\u2739","\u2737"]},star2:{intervalMs:80,frames:["+","x","*"]},flip:{intervalMs:70,frames:["_","_","_","-","`","`","'","\xB4","-","_","_","_"]},hamburger:{intervalMs:100,frames:["\u2631","\u2632","\u2634"]},growVertical:{intervalMs:120,frames:["\u2581","\u2583","\u2584","\u2585","\u2586","\u2587","\u2586","\u2585","\u2584","\u2583"]},growHorizontal:{intervalMs:120,frames:["\u258F","\u258E","\u258D","\u258C","\u258B","\u258A","\u2589","\u258A","\u258B","\u258C","\u258D","\u258E"]},balloon:{intervalMs:140,frames:[" ",".","o","O","@","*"," "]},balloon2:{intervalMs:120,frames:[".","o","O","\xB0","O","o","."]},noise:{intervalMs:100,frames:["\u2593","\u2592","\u2591"]},bounce:{intervalMs:120,frames:["\u2801","\u2802","\u2804","\u2802"]},boxBounce:{intervalMs:120,frames:["\u2596","\u2598","\u259D","\u2597"]},boxBounce2:{intervalMs:100,frames:["\u258C","\u2580","\u2590","\u2584"]},triangle:{intervalMs:50,frames:["\u25E2","\u25E3","\u25E4","\u25E5"]},binary:{intervalMs:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},arc:{intervalMs:100,frames:["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"]},circle:{intervalMs:120,frames:["\u25E1","\u2299","\u25E0"]},squareCorners:{intervalMs:180,frames:["\u25F0","\u25F3","\u25F2","\u25F1"]},circleQuarters:{intervalMs:120,frames:["\u25F4","\u25F7","\u25F6","\u25F5"]},circleHalves:{intervalMs:50,frames:["\u25D0","\u25D3","\u25D1","\u25D2"]},squish:{intervalMs:100,frames:["\u256B","\u256A"]},toggle:{intervalMs:250,frames:["\u22B6","\u22B7"]},toggle2:{intervalMs:80,frames:["\u25AB","\u25AA"]},toggle3:{intervalMs:120,frames:["\u25A1","\u25A0"]},toggle4:{intervalMs:100,frames:["\u25A0","\u25A1","\u25AA","\u25AB"]},toggle5:{intervalMs:100,frames:["\u25AE","\u25AF"]},toggle6:{intervalMs:300,frames:["\u101D","\u1040"]},toggle7:{intervalMs:80,frames:["\u29BE","\u29BF"]},toggle8:{intervalMs:100,frames:["\u25CD","\u25CC"]},toggle9:{intervalMs:100,frames:["\u25C9","\u25CE"]},toggle10:{intervalMs:100,frames:["\u3282","\u3280","\u3281"]},toggle11:{intervalMs:50,frames:["\u29C7","\u29C6"]},toggle12:{intervalMs:120,frames:["\u2617","\u2616"]},toggle13:{intervalMs:80,frames:["=","*","-"]},arrow:{intervalMs:100,frames:["\u2190","\u2196","\u2191","\u2197","\u2192","\u2198","\u2193","\u2199"]},arrow2:{intervalMs:80,frames:["\u2B06\uFE0F ","\u2197\uFE0F ","\u27A1\uFE0F ","\u2198\uFE0F ","\u2B07\uFE0F ","\u2199\uFE0F ","\u2B05\uFE0F ","\u2196\uFE0F "]},arrow3:{intervalMs:120,frames:["\u25B9\u25B9\u25B9\u25B9\u25B9","\u25B8\u25B9\u25B9\u25B9\u25B9","\u25B9\u25B8\u25B9\u25B9\u25B9","\u25B9\u25B9\u25B8\u25B9\u25B9","\u25B9\u25B9\u25B9\u25B8\u25B9","\u25B9\u25B9\u25B9\u25B9\u25B8"]},bouncingBar:{intervalMs:80,frames:["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},bouncingBall:{intervalMs:80,frames:["( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF)","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","(\u25CF )"]},smiley:{intervalMs:200,frames:["\u{1F604} ","\u{1F61D} "]},monkey:{intervalMs:300,frames:["\u{1F648} ","\u{1F648} ","\u{1F649} ","\u{1F64A} "]},hearts:{intervalMs:100,frames:["\u{1F49B} ","\u{1F499} ","\u{1F49C} ","\u{1F49A} ","\u{1F497} "]},clock:{intervalMs:100,frames:["\u{1F55B} ","\u{1F550} ","\u{1F551} ","\u{1F552} ","\u{1F553} ","\u{1F554} ","\u{1F555} ","\u{1F556} ","\u{1F557} ","\u{1F558} ","\u{1F559} ","\u{1F55A} "]},earth:{intervalMs:180,frames:["\u{1F30D} ","\u{1F30E} ","\u{1F30F} "]},material:{intervalMs:17,frames:["\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581"]},moon:{intervalMs:80,frames:["\u{1F311} ","\u{1F312} ","\u{1F313} ","\u{1F314} ","\u{1F315} ","\u{1F316} ","\u{1F317} ","\u{1F318} "]},runner:{intervalMs:140,frames:["\u{1F6B6} ","\u{1F3C3} "]},pong:{intervalMs:80,frames:["\u2590\u2802 \u258C","\u2590\u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802\u258C","\u2590 \u2820\u258C","\u2590 \u2840\u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590\u2820 \u258C"]},shark:{intervalMs:120,frames:["\u2590|____________\u258C","\u2590_|___________\u258C","\u2590__|__________\u258C","\u2590___|_________\u258C","\u2590____|________\u258C","\u2590_____|_______\u258C","\u2590______|______\u258C","\u2590_______|_____\u258C","\u2590________|____\u258C","\u2590_________|___\u258C","\u2590__________|__\u258C","\u2590___________|_\u258C","\u2590____________|\u258C","\u2590____________/|\u258C","\u2590___________/|_\u258C","\u2590__________/|__\u258C","\u2590_________/|___\u258C","\u2590________/|____\u258C","\u2590_______/|_____\u258C","\u2590______/|______\u258C","\u2590_____/|_______\u258C","\u2590____/|________\u258C","\u2590___/|_________\u258C","\u2590__/|__________\u258C","\u2590_/|___________\u258C","\u2590/|____________\u258C"]},dqpb:{intervalMs:100,frames:["d","q","p","b"]},weather:{intervalMs:100,frames:["\u2600\uFE0F ","\u2600\uFE0F ","\u2600\uFE0F ","\u{1F324} ","\u26C5\uFE0F ","\u{1F325} ","\u2601\uFE0F ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u26C8 ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u2601\uFE0F ","\u{1F325} ","\u26C5\uFE0F ","\u{1F324} ","\u2600\uFE0F ","\u2600\uFE0F "]},christmas:{intervalMs:400,frames:["\u{1F332}","\u{1F384}"]},grenade:{intervalMs:80,frames:["\u060C ","\u2032 "," \xB4 "," \u203E "," \u2E0C"," \u2E0A"," |"," \u204E"," \u2055"," \u0DF4 "," \u2053"," "," "," "]},point:{intervalMs:125,frames:["\u2219\u2219\u2219","\u25CF\u2219\u2219","\u2219\u25CF\u2219","\u2219\u2219\u25CF","\u2219\u2219\u2219"]},layer:{intervalMs:150,frames:["-","=","\u2261"]},betaWave:{intervalMs:80,frames:["\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1"]},fingerDance:{intervalMs:160,frames:["\u{1F918} ","\u{1F91F} ","\u{1F596} ","\u270B ","\u{1F91A} ","\u{1F446} "]},fistBump:{intervalMs:80,frames:["\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u3000\u{1F91C}\u3000\u3000\u{1F91B}\u3000 ","\u3000\u3000\u{1F91C}\u{1F91B}\u3000\u3000 ","\u3000\u{1F91C}\u2728\u{1F91B}\u3000\u3000 ","\u{1F91C}\u3000\u2728\u3000\u{1F91B}\u3000 "]},soccerHeader:{intervalMs:80,frames:[" \u{1F9D1}\u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F\u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} "]},mindblown:{intervalMs:160,frames:["\u{1F610} ","\u{1F610} ","\u{1F62E} ","\u{1F62E} ","\u{1F626} ","\u{1F626} ","\u{1F627} ","\u{1F627} ","\u{1F92F} ","\u{1F4A5} ","\u2728 ","\u3000 ","\u3000 ","\u3000 "]},speaker:{intervalMs:160,frames:["\u{1F508} ","\u{1F509} ","\u{1F50A} ","\u{1F509} "]},orangePulse:{intervalMs:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} "]},bluePulse:{intervalMs:100,frames:["\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},orangeBluePulse:{intervalMs:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} ","\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},timeTravel:{intervalMs:100,frames:["\u{1F55B} ","\u{1F55A} ","\u{1F559} ","\u{1F558} ","\u{1F557} ","\u{1F556} ","\u{1F555} ","\u{1F554} ","\u{1F553} ","\u{1F552} ","\u{1F551} ","\u{1F550} "]},aesthetic:{intervalMs:80,frames:["\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0","\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1"]},dwarfFortress:{intervalMs:80,frames:[" \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A \u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A \xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A \xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\u2593\xA3 "," \u263A\u2593\xA3 "," \u263A\u2592\xA3 "," \u263A\u2592\xA3 "," \u263A\u2591\xA3 "," \u263A\u2591\xA3 "," \u263A \xA3 "," \u263A\xA3 "," \u263A\xA3 "," \u263A\u2593 "," \u263A\u2593 "," \u263A\u2592 "," \u263A\u2592 "," \u263A\u2591 "," \u263A\u2591 "," \u263A "," \u263A &"," \u263A \u263C&"," \u263A \u263C &"," \u263A\u263C &"," \u263A\u263C & "," \u203C & "," \u263A & "," \u203C & "," \u263A & "," \u203C & "," \u263A & ","\u203C & "," & "," & "," & \u2591 "," & \u2592 "," & \u2593 "," & \xA3 "," & \u2591\xA3 "," & \u2592\xA3 "," & \u2593\xA3 "," & \xA3\xA3 "," & \u2591\xA3\xA3 "," & \u2592\xA3\xA3 ","& \u2593\xA3\xA3 ","& \xA3\xA3\xA3 "," \u2591\xA3\xA3\xA3 "," \u2592\xA3\xA3\xA3 "," \u2593\xA3\xA3\xA3 "," \u2588\xA3\xA3\xA3 "," \u2591\u2588\xA3\xA3\xA3 "," \u2592\u2588\xA3\xA3\xA3 "," \u2593\u2588\xA3\xA3\xA3 "," \u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "]},fish:{intervalMs:80,frames:["~~~~~~~~~~~~~~~~~~~~","> ~~~~~~~~~~~~~~~~~~","\xBA> ~~~~~~~~~~~~~~~~~","(\xBA> ~~~~~~~~~~~~~~~~","((\xBA> ~~~~~~~~~~~~~~~","<((\xBA> ~~~~~~~~~~~~~~","><((\xBA> ~~~~~~~~~~~~~"," ><((\xBA> ~~~~~~~~~~~~","~ ><((\xBA> ~~~~~~~~~~~","~~ <>((\xBA> ~~~~~~~~~~","~~~ ><((\xBA> ~~~~~~~~~","~~~~ <>((\xBA> ~~~~~~~~","~~~~~ ><((\xBA> ~~~~~~~","~~~~~~ <>((\xBA> ~~~~~~","~~~~~~~ ><((\xBA> ~~~~~","~~~~~~~~ <>((\xBA> ~~~~","~~~~~~~~~ ><((\xBA> ~~~","~~~~~~~~~~ <>((\xBA> ~~","~~~~~~~~~~~ ><((\xBA> ~","~~~~~~~~~~~~ <>((\xBA> ","~~~~~~~~~~~~~ ><((\xBA>","~~~~~~~~~~~~~~ <>((\xBA","~~~~~~~~~~~~~~~ ><((","~~~~~~~~~~~~~~~~ <>(","~~~~~~~~~~~~~~~~~ ><","~~~~~~~~~~~~~~~~~~ <","~~~~~~~~~~~~~~~~~~~~"]}};var gs=q.join(Lt(),".pi","agent"),ms=q.join(Lt(),".agents"),ue=null,_t=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function bs(e){let s=q.basename(process.cwd()),t=e.getSessionName();return t?`\u03C0 - ${t} - ${s}`:`\u03C0 - ${s}`}function Y(e){e.ui.setWorkingMessage(fs.magenta(qe[Math.floor(Math.random()*qe.length)]+"..."))}function xs(e){let s=null,t=0;function i(n){s&&(clearInterval(s),s=null),t=0,n.ui.setTitle(bs(e))}function o(n){i(n),s=setInterval(()=>{let l=_t[t%_t.length],h=q.basename(process.cwd()),u=e.getSessionName(),g=u?`${l} \u03C0 - ${u} - ${h}`:`${l} \u03C0 - ${h}`;n.ui.setTitle(g),t++},80)}je(),e.on("resources_discover",async n=>{let h=[q.join(n.cwd,".sling","agent"),ms,gs],u=[],g=[],x=[];for(let b of h){let d=q.join(b,"skills");Ye(d)&&u.push(d);let f=q.join(b,"prompts");Ye(f)&&g.push(f);let v=q.join(b,"themes");Ye(v)&&x.push(v)}return{skillPaths:u,promptPaths:g,themePaths:x}});let r=new WeakSet;e.on("session_start",async(n,l)=>{let h=l.modelRegistry.authStorage;if(!r.has(h)){let u=h.getOAuthProviders.bind(h);h.getOAuthProviders=()=>u().filter(g=>g.id==="slingshot"),r.add(h)}l.hasUI&&l.ui.setHeader(wt)});let a=!1;e.registerCommand("footer",{description:"Toggle custom footer",handler:async(n,l)=>{a=!a,a?(l.ui.setFooter((h,u,g)=>({dispose:g.onBranchChange(()=>h.requestRender()),invalidate(){},render(b){let d=0,f=0,v=0;for(let E of l.sessionManager.getBranch())if(E.type==="message"&&E.message.role==="assistant"){let B=E.message;d+=B.usage.input,f+=B.usage.output,v+=B.usage.cost.total}let L=g.getGitBranch(),k=E=>E<1e3?`${E}`:`${(E/1e3).toFixed(1)}k`,D=u.fg("dim",`\u2191${k(d)} \u2193${k(f)} $${v.toFixed(3)}`),I=L?` (${L})`:"",J=u.fg("dim",`${l.model?.id||"no-model"}${I}`),X=" ".repeat(Math.max(1,b-_(D)-_(J)));return[G(D+X+J,b)]}})),l.ui.notify("Custom footer enabled","info")):(l.ui.setFooter(void 0),l.ui.notify("Default footer restored","info"))}}),e.registerProvider("slingshot",{baseUrl:pt,api:"openai-completions",apiKey:"SLINGSHOT_API_KEY",models:yt,oauth:{name:"Slingshot",login:Ve,refreshToken:Se,getApiKey:n=>(ue=n,n.access)}}),e.registerCommand("slingshot-debug",{description:"Toggle Slingshot analytics debug logging",handler:async(n,l)=>{let h=!W();if(Ct(h),h){let u="Slingshot Analytics Debug: ENABLED \u2705",g=St();g&&(u+=`
|
|
86
|
+
`).map(o=>is.bold(is.white(is.bgRed((o+" ".repeat(t)).substring(0,t))))),s=` Slingshot coding agent v${ns.slingVersion}`;return[...n,is.bgGray(is.dim(s+" ".repeat(t)).substring(0,t))]},invalidate(){}}}import zM from"chalk";var ma=["Accomplishing","Actioning","Actualizing","Architecting","Baking","Beaming","Beboppin'","Befuddling","Billowing","Blanching","Bloviating","Boogieing","Boondoggling","Booping","Bootstrapping","Brewing","Bunning","Burrowing","Calculating","Canoodling","Caramelizing","Cascading","Catapulting","Cerebrating","Channeling","Channelling","Choreographing","Churning","Clauding","Coalescing","Cogitating","Combobulating","Composing","Computing","Concocting","Considering","Contemplating","Cooking","Crafting","Creating","Crunching","Crystallizing","Cultivating","Deciphering","Deliberating","Determining","Dilly-dallying","Discombobulating","Doing","Doodling","Drizzling","Ebbing","Effecting","Elucidating","Embellishing","Enchanting","Envisioning","Evaporating","Fermenting","Fiddle-faddling","Finagling","Flamb\xE9ing","Flibbertigibbeting","Flowing","Flummoxing","Fluttering","Forging","Forming","Frolicking","Frosting","Gallivanting","Galloping","Garnishing","Generating","Gesticulating","Germinating","Gitifying","Grooving","Gusting","Harmonizing","Hashing","Hatching","Herding","Honking","Hullaballooing","Hyperspacing","Ideating","Imagining","Improvising","Incubating","Inferring","Infusing","Ionizing","Jitterbugging","Julienning","Kneading","Leavening","Levitating","Lollygagging","Manifesting","Marinating","Meandering","Metamorphosing","Misting","Moonwalking","Moseying","Mulling","Mustering","Musing","Nebulizing","Nesting","Newspapering","Noodling","Nucleating","Orbiting","Orchestrating","Osmosing","Perambulating","Percolating","Perusing","Philosophising","Photosynthesizing","Pollinating","Pondering","Pontificating","Pouncing","Precipitating","Prestidigitating","Processing","Proofing","Propagating","Puttering","Puzzling","Quantumizing","Razzle-dazzling","Razzmatazzing","Recombobulating","Reticulating","Roosting","Ruminating","Saut\xE9ing","Scampering","Schlepping","Scurrying","Seasoning","Shenaniganing","Shimmying","Simmering","Skedaddling","Sketching","Slithering","Smooshing","Sock-hopping","Spelunking","Spinning","Sprouting","Stewing","Sublimating","Swirling","Swooping","Symbioting","Synthesizing","Tempering","Thinking","Thundering","Tinkering","Tomfoolering","Topsy-turvying","Transfiguring","Transmuting","Twisting","Undulating","Unfurling","Unravelling","Vibing","Waddling","Wandering","Warping","Whatchamacalliting","Whirlpooling","Whirring","Whisking","Wibbling","Working","Wrangling","Zesting","Zigzagging"];import on from"node:path";import{existsSync as Bc}from"node:fs";import{homedir as Ig}from"node:os";function ga(i,e){e==="random"&&(e=Object.keys(ha)[Math.floor(Math.random()*Object.keys(ha).length)]);let t=ha[e||"dots"];i.ui.setWorkingIndicator(t)}var ha={dots:{intervalMs:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]},dots2:{intervalMs:80,frames:["\u28FE","\u28FD","\u28FB","\u28BF","\u287F","\u28DF","\u28EF","\u28F7"]},dots3:{intervalMs:80,frames:["\u280B","\u2819","\u281A","\u281E","\u2816","\u2826","\u2834","\u2832","\u2833","\u2813"]},dots4:{intervalMs:80,frames:["\u2804","\u2806","\u2807","\u280B","\u2819","\u2838","\u2830","\u2820","\u2830","\u2838","\u2819","\u280B","\u2807","\u2806"]},dots5:{intervalMs:80,frames:["\u280B","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B"]},dots6:{intervalMs:80,frames:["\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2834","\u2832","\u2812","\u2802","\u2802","\u2812","\u281A","\u2819","\u2809","\u2801"]},dots7:{intervalMs:80,frames:["\u2808","\u2809","\u280B","\u2813","\u2812","\u2810","\u2810","\u2812","\u2816","\u2826","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808"]},dots8:{intervalMs:80,frames:["\u2801","\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808","\u2808"]},dots9:{intervalMs:80,frames:["\u28B9","\u28BA","\u28BC","\u28F8","\u28C7","\u2867","\u2857","\u284F"]},dots10:{intervalMs:80,frames:["\u2884","\u2882","\u2881","\u2841","\u2848","\u2850","\u2860"]},dots11:{intervalMs:100,frames:["\u2801","\u2802","\u2804","\u2840","\u2880","\u2820","\u2810","\u2808"]},dots12:{intervalMs:80,frames:["\u2880\u2800","\u2840\u2800","\u2804\u2800","\u2882\u2800","\u2842\u2800","\u2805\u2800","\u2883\u2800","\u2843\u2800","\u280D\u2800","\u288B\u2800","\u284B\u2800","\u280D\u2801","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2888\u2829","\u2840\u2899","\u2804\u2859","\u2882\u2829","\u2842\u2898","\u2805\u2858","\u2883\u2828","\u2843\u2890","\u280D\u2850","\u288B\u2820","\u284B\u2880","\u280D\u2841","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2808\u2829","\u2800\u2899","\u2800\u2859","\u2800\u2829","\u2800\u2898","\u2800\u2858","\u2800\u2828","\u2800\u2890","\u2800\u2850","\u2800\u2820","\u2800\u2880","\u2800\u2840"]},dots13:{intervalMs:80,frames:["\u28FC","\u28F9","\u28BB","\u283F","\u285F","\u28CF","\u28E7","\u28F6"]},dots14:{intervalMs:80,frames:["\u2809\u2809","\u2808\u2819","\u2800\u2839","\u2800\u28B8","\u2800\u28F0","\u2880\u28E0","\u28C0\u28C0","\u28C4\u2840","\u28C6\u2800","\u2847\u2800","\u280F\u2800","\u280B\u2801"]},dots8Bit:{intervalMs:80,frames:["\u2800","\u2801","\u2802","\u2803","\u2804","\u2805","\u2806","\u2807","\u2840","\u2841","\u2842","\u2843","\u2844","\u2845","\u2846","\u2847","\u2808","\u2809","\u280A","\u280B","\u280C","\u280D","\u280E","\u280F","\u2848","\u2849","\u284A","\u284B","\u284C","\u284D","\u284E","\u284F","\u2810","\u2811","\u2812","\u2813","\u2814","\u2815","\u2816","\u2817","\u2850","\u2851","\u2852","\u2853","\u2854","\u2855","\u2856","\u2857","\u2818","\u2819","\u281A","\u281B","\u281C","\u281D","\u281E","\u281F","\u2858","\u2859","\u285A","\u285B","\u285C","\u285D","\u285E","\u285F","\u2820","\u2821","\u2822","\u2823","\u2824","\u2825","\u2826","\u2827","\u2860","\u2861","\u2862","\u2863","\u2864","\u2865","\u2866","\u2867","\u2828","\u2829","\u282A","\u282B","\u282C","\u282D","\u282E","\u282F","\u2868","\u2869","\u286A","\u286B","\u286C","\u286D","\u286E","\u286F","\u2830","\u2831","\u2832","\u2833","\u2834","\u2835","\u2836","\u2837","\u2870","\u2871","\u2872","\u2873","\u2874","\u2875","\u2876","\u2877","\u2838","\u2839","\u283A","\u283B","\u283C","\u283D","\u283E","\u283F","\u2878","\u2879","\u287A","\u287B","\u287C","\u287D","\u287E","\u287F","\u2880","\u2881","\u2882","\u2883","\u2884","\u2885","\u2886","\u2887","\u28C0","\u28C1","\u28C2","\u28C3","\u28C4","\u28C5","\u28C6","\u28C7","\u2888","\u2889","\u288A","\u288B","\u288C","\u288D","\u288E","\u288F","\u28C8","\u28C9","\u28CA","\u28CB","\u28CC","\u28CD","\u28CE","\u28CF","\u2890","\u2891","\u2892","\u2893","\u2894","\u2895","\u2896","\u2897","\u28D0","\u28D1","\u28D2","\u28D3","\u28D4","\u28D5","\u28D6","\u28D7","\u2898","\u2899","\u289A","\u289B","\u289C","\u289D","\u289E","\u289F","\u28D8","\u28D9","\u28DA","\u28DB","\u28DC","\u28DD","\u28DE","\u28DF","\u28A0","\u28A1","\u28A2","\u28A3","\u28A4","\u28A5","\u28A6","\u28A7","\u28E0","\u28E1","\u28E2","\u28E3","\u28E4","\u28E5","\u28E6","\u28E7","\u28A8","\u28A9","\u28AA","\u28AB","\u28AC","\u28AD","\u28AE","\u28AF","\u28E8","\u28E9","\u28EA","\u28EB","\u28EC","\u28ED","\u28EE","\u28EF","\u28B0","\u28B1","\u28B2","\u28B3","\u28B4","\u28B5","\u28B6","\u28B7","\u28F0","\u28F1","\u28F2","\u28F3","\u28F4","\u28F5","\u28F6","\u28F7","\u28B8","\u28B9","\u28BA","\u28BB","\u28BC","\u28BD","\u28BE","\u28BF","\u28F8","\u28F9","\u28FA","\u28FB","\u28FC","\u28FD","\u28FE","\u28FF"]},dotsCircle:{intervalMs:80,frames:["\u288E ","\u280E\u2801","\u280A\u2811","\u2808\u2831"," \u2871","\u2880\u2870","\u2884\u2860","\u2886\u2840"]},sand:{intervalMs:80,frames:["\u2801","\u2802","\u2804","\u2840","\u2848","\u2850","\u2860","\u28C0","\u28C1","\u28C2","\u28C4","\u28CC","\u28D4","\u28E4","\u28E5","\u28E6","\u28EE","\u28F6","\u28F7","\u28FF","\u287F","\u283F","\u289F","\u281F","\u285B","\u281B","\u282B","\u288B","\u280B","\u280D","\u2849","\u2809","\u2811","\u2821","\u2881"]},line:{intervalMs:130,frames:["-","\\","|","/"]},line2:{intervalMs:100,frames:["\u2802","-","\u2013","\u2014","\u2013","-"]},rollingLine:{intervalMs:80,frames:["/ "," - "," "," |"," |"," "," - ","/ "]},pipe:{intervalMs:100,frames:["\u2524","\u2518","\u2534","\u2514","\u251C","\u250C","\u252C","\u2510"]},simpleDots:{intervalMs:400,frames:[". ",".. ","..."," "]},simpleDotsScrolling:{intervalMs:200,frames:[". ",".. ","..."," .."," ."," "]},star:{intervalMs:70,frames:["\u2736","\u2738","\u2739","\u273A","\u2739","\u2737"]},star2:{intervalMs:80,frames:["+","x","*"]},flip:{intervalMs:70,frames:["_","_","_","-","`","`","'","\xB4","-","_","_","_"]},hamburger:{intervalMs:100,frames:["\u2631","\u2632","\u2634"]},growVertical:{intervalMs:120,frames:["\u2581","\u2583","\u2584","\u2585","\u2586","\u2587","\u2586","\u2585","\u2584","\u2583"]},growHorizontal:{intervalMs:120,frames:["\u258F","\u258E","\u258D","\u258C","\u258B","\u258A","\u2589","\u258A","\u258B","\u258C","\u258D","\u258E"]},balloon:{intervalMs:140,frames:[" ",".","o","O","@","*"," "]},balloon2:{intervalMs:120,frames:[".","o","O","\xB0","O","o","."]},noise:{intervalMs:100,frames:["\u2593","\u2592","\u2591"]},bounce:{intervalMs:120,frames:["\u2801","\u2802","\u2804","\u2802"]},boxBounce:{intervalMs:120,frames:["\u2596","\u2598","\u259D","\u2597"]},boxBounce2:{intervalMs:100,frames:["\u258C","\u2580","\u2590","\u2584"]},triangle:{intervalMs:50,frames:["\u25E2","\u25E3","\u25E4","\u25E5"]},binary:{intervalMs:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},arc:{intervalMs:100,frames:["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"]},circle:{intervalMs:120,frames:["\u25E1","\u2299","\u25E0"]},squareCorners:{intervalMs:180,frames:["\u25F0","\u25F3","\u25F2","\u25F1"]},circleQuarters:{intervalMs:120,frames:["\u25F4","\u25F7","\u25F6","\u25F5"]},circleHalves:{intervalMs:50,frames:["\u25D0","\u25D3","\u25D1","\u25D2"]},squish:{intervalMs:100,frames:["\u256B","\u256A"]},toggle:{intervalMs:250,frames:["\u22B6","\u22B7"]},toggle2:{intervalMs:80,frames:["\u25AB","\u25AA"]},toggle3:{intervalMs:120,frames:["\u25A1","\u25A0"]},toggle4:{intervalMs:100,frames:["\u25A0","\u25A1","\u25AA","\u25AB"]},toggle5:{intervalMs:100,frames:["\u25AE","\u25AF"]},toggle6:{intervalMs:300,frames:["\u101D","\u1040"]},toggle7:{intervalMs:80,frames:["\u29BE","\u29BF"]},toggle8:{intervalMs:100,frames:["\u25CD","\u25CC"]},toggle9:{intervalMs:100,frames:["\u25C9","\u25CE"]},toggle10:{intervalMs:100,frames:["\u3282","\u3280","\u3281"]},toggle11:{intervalMs:50,frames:["\u29C7","\u29C6"]},toggle12:{intervalMs:120,frames:["\u2617","\u2616"]},toggle13:{intervalMs:80,frames:["=","*","-"]},arrow:{intervalMs:100,frames:["\u2190","\u2196","\u2191","\u2197","\u2192","\u2198","\u2193","\u2199"]},arrow2:{intervalMs:80,frames:["\u2B06\uFE0F ","\u2197\uFE0F ","\u27A1\uFE0F ","\u2198\uFE0F ","\u2B07\uFE0F ","\u2199\uFE0F ","\u2B05\uFE0F ","\u2196\uFE0F "]},arrow3:{intervalMs:120,frames:["\u25B9\u25B9\u25B9\u25B9\u25B9","\u25B8\u25B9\u25B9\u25B9\u25B9","\u25B9\u25B8\u25B9\u25B9\u25B9","\u25B9\u25B9\u25B8\u25B9\u25B9","\u25B9\u25B9\u25B9\u25B8\u25B9","\u25B9\u25B9\u25B9\u25B9\u25B8"]},bouncingBar:{intervalMs:80,frames:["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},bouncingBall:{intervalMs:80,frames:["( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF)","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","(\u25CF )"]},smiley:{intervalMs:200,frames:["\u{1F604} ","\u{1F61D} "]},monkey:{intervalMs:300,frames:["\u{1F648} ","\u{1F648} ","\u{1F649} ","\u{1F64A} "]},hearts:{intervalMs:100,frames:["\u{1F49B} ","\u{1F499} ","\u{1F49C} ","\u{1F49A} ","\u{1F497} "]},clock:{intervalMs:100,frames:["\u{1F55B} ","\u{1F550} ","\u{1F551} ","\u{1F552} ","\u{1F553} ","\u{1F554} ","\u{1F555} ","\u{1F556} ","\u{1F557} ","\u{1F558} ","\u{1F559} ","\u{1F55A} "]},earth:{intervalMs:180,frames:["\u{1F30D} ","\u{1F30E} ","\u{1F30F} "]},material:{intervalMs:17,frames:["\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581"]},moon:{intervalMs:80,frames:["\u{1F311} ","\u{1F312} ","\u{1F313} ","\u{1F314} ","\u{1F315} ","\u{1F316} ","\u{1F317} ","\u{1F318} "]},runner:{intervalMs:140,frames:["\u{1F6B6} ","\u{1F3C3} "]},pong:{intervalMs:80,frames:["\u2590\u2802 \u258C","\u2590\u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802\u258C","\u2590 \u2820\u258C","\u2590 \u2840\u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590\u2820 \u258C"]},shark:{intervalMs:120,frames:["\u2590|____________\u258C","\u2590_|___________\u258C","\u2590__|__________\u258C","\u2590___|_________\u258C","\u2590____|________\u258C","\u2590_____|_______\u258C","\u2590______|______\u258C","\u2590_______|_____\u258C","\u2590________|____\u258C","\u2590_________|___\u258C","\u2590__________|__\u258C","\u2590___________|_\u258C","\u2590____________|\u258C","\u2590____________/|\u258C","\u2590___________/|_\u258C","\u2590__________/|__\u258C","\u2590_________/|___\u258C","\u2590________/|____\u258C","\u2590_______/|_____\u258C","\u2590______/|______\u258C","\u2590_____/|_______\u258C","\u2590____/|________\u258C","\u2590___/|_________\u258C","\u2590__/|__________\u258C","\u2590_/|___________\u258C","\u2590/|____________\u258C"]},dqpb:{intervalMs:100,frames:["d","q","p","b"]},weather:{intervalMs:100,frames:["\u2600\uFE0F ","\u2600\uFE0F ","\u2600\uFE0F ","\u{1F324} ","\u26C5\uFE0F ","\u{1F325} ","\u2601\uFE0F ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u26C8 ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u2601\uFE0F ","\u{1F325} ","\u26C5\uFE0F ","\u{1F324} ","\u2600\uFE0F ","\u2600\uFE0F "]},christmas:{intervalMs:400,frames:["\u{1F332}","\u{1F384}"]},grenade:{intervalMs:80,frames:["\u060C ","\u2032 "," \xB4 "," \u203E "," \u2E0C"," \u2E0A"," |"," \u204E"," \u2055"," \u0DF4 "," \u2053"," "," "," "]},point:{intervalMs:125,frames:["\u2219\u2219\u2219","\u25CF\u2219\u2219","\u2219\u25CF\u2219","\u2219\u2219\u25CF","\u2219\u2219\u2219"]},layer:{intervalMs:150,frames:["-","=","\u2261"]},betaWave:{intervalMs:80,frames:["\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1"]},fingerDance:{intervalMs:160,frames:["\u{1F918} ","\u{1F91F} ","\u{1F596} ","\u270B ","\u{1F91A} ","\u{1F446} "]},fistBump:{intervalMs:80,frames:["\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u3000\u{1F91C}\u3000\u3000\u{1F91B}\u3000 ","\u3000\u3000\u{1F91C}\u{1F91B}\u3000\u3000 ","\u3000\u{1F91C}\u2728\u{1F91B}\u3000\u3000 ","\u{1F91C}\u3000\u2728\u3000\u{1F91B}\u3000 "]},soccerHeader:{intervalMs:80,frames:[" \u{1F9D1}\u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F\u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} "]},mindblown:{intervalMs:160,frames:["\u{1F610} ","\u{1F610} ","\u{1F62E} ","\u{1F62E} ","\u{1F626} ","\u{1F626} ","\u{1F627} ","\u{1F627} ","\u{1F92F} ","\u{1F4A5} ","\u2728 ","\u3000 ","\u3000 ","\u3000 "]},speaker:{intervalMs:160,frames:["\u{1F508} ","\u{1F509} ","\u{1F50A} ","\u{1F509} "]},orangePulse:{intervalMs:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} "]},bluePulse:{intervalMs:100,frames:["\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},orangeBluePulse:{intervalMs:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} ","\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},timeTravel:{intervalMs:100,frames:["\u{1F55B} ","\u{1F55A} ","\u{1F559} ","\u{1F558} ","\u{1F557} ","\u{1F556} ","\u{1F555} ","\u{1F554} ","\u{1F553} ","\u{1F552} ","\u{1F551} ","\u{1F550} "]},aesthetic:{intervalMs:80,frames:["\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0","\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1"]},dwarfFortress:{intervalMs:80,frames:[" \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A \u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A \xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A \xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\u2593\xA3 "," \u263A\u2593\xA3 "," \u263A\u2592\xA3 "," \u263A\u2592\xA3 "," \u263A\u2591\xA3 "," \u263A\u2591\xA3 "," \u263A \xA3 "," \u263A\xA3 "," \u263A\xA3 "," \u263A\u2593 "," \u263A\u2593 "," \u263A\u2592 "," \u263A\u2592 "," \u263A\u2591 "," \u263A\u2591 "," \u263A "," \u263A &"," \u263A \u263C&"," \u263A \u263C &"," \u263A\u263C &"," \u263A\u263C & "," \u203C & "," \u263A & "," \u203C & "," \u263A & "," \u203C & "," \u263A & ","\u203C & "," & "," & "," & \u2591 "," & \u2592 "," & \u2593 "," & \xA3 "," & \u2591\xA3 "," & \u2592\xA3 "," & \u2593\xA3 "," & \xA3\xA3 "," & \u2591\xA3\xA3 "," & \u2592\xA3\xA3 ","& \u2593\xA3\xA3 ","& \xA3\xA3\xA3 "," \u2591\xA3\xA3\xA3 "," \u2592\xA3\xA3\xA3 "," \u2593\xA3\xA3\xA3 "," \u2588\xA3\xA3\xA3 "," \u2591\u2588\xA3\xA3\xA3 "," \u2592\u2588\xA3\xA3\xA3 "," \u2593\u2588\xA3\xA3\xA3 "," \u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "]},fish:{intervalMs:80,frames:["~~~~~~~~~~~~~~~~~~~~","> ~~~~~~~~~~~~~~~~~~","\xBA> ~~~~~~~~~~~~~~~~~","(\xBA> ~~~~~~~~~~~~~~~~","((\xBA> ~~~~~~~~~~~~~~~","<((\xBA> ~~~~~~~~~~~~~~","><((\xBA> ~~~~~~~~~~~~~"," ><((\xBA> ~~~~~~~~~~~~","~ ><((\xBA> ~~~~~~~~~~~","~~ <>((\xBA> ~~~~~~~~~~","~~~ ><((\xBA> ~~~~~~~~~","~~~~ <>((\xBA> ~~~~~~~~","~~~~~ ><((\xBA> ~~~~~~~","~~~~~~ <>((\xBA> ~~~~~~","~~~~~~~ ><((\xBA> ~~~~~","~~~~~~~~ <>((\xBA> ~~~~","~~~~~~~~~ ><((\xBA> ~~~","~~~~~~~~~~ <>((\xBA> ~~","~~~~~~~~~~~ ><((\xBA> ~","~~~~~~~~~~~~ <>((\xBA> ","~~~~~~~~~~~~~ ><((\xBA>","~~~~~~~~~~~~~~ <>((\xBA","~~~~~~~~~~~~~~~ ><((","~~~~~~~~~~~~~~~~ <>(","~~~~~~~~~~~~~~~~~ ><","~~~~~~~~~~~~~~~~~~ <","~~~~~~~~~~~~~~~~~~~~"]}};import{accessSync as vE,constants as yE,existsSync as xa,readFileSync as $f,realpathSync as wE}from"fs";import{homedir as ss}from"os";import{basename as TE,dirname as fo,join as xe,resolve as ba,sep as CE,win32 as ME}from"path";import{fileURLToPath as Bf}from"url";import{basename as Uf}from"node:path";var Df=100,Ff=new Set(["npm","npx","pnpm","yarn","yarnpkg","corepack"]);function Hn(i){if(process.platform!=="win32")return!1;let e=Uf(i).toLowerCase();return e.endsWith(".cmd")||e.endsWith(".bat")||Ff.has(e)}function fa(i){return new Promise((e,t)=>{let n=!1,s=!1,o=null,r,a=i.stdout===null,l=i.stderr===null,c=()=>{r&&(clearTimeout(r),r=void 0),i.removeListener("error",m),i.removeListener("exit",g),i.removeListener("close",x),i.stdout?.removeListener("end",u),i.stderr?.removeListener("end",h)},d=b=>{n||(n=!0,c(),i.stdout?.destroy(),i.stderr?.destroy(),e(b))},p=()=>{!s||n||a&&l&&d(o)},u=()=>{a=!0,p()},h=()=>{l=!0,p()},m=b=>{n||(n=!0,c(),t(b))},g=b=>{s=!0,o=b,p(),n||(r=setTimeout(()=>d(b),Df))},x=b=>{d(b)};i.stdout?.once("end",u),i.stderr?.once("end",h),i.once("error",m),i.once("exit",g),i.once("close",x)})}var Nf=Bf(import.meta.url),Np=fo(Nf),xo=import.meta.url.includes("$bunfs")||import.meta.url.includes("~BUN")||import.meta.url.includes("%7EBUN"),IE=!!process.versions.bun;function Vt(){let i=process.env.PI_PACKAGE_DIR;if(i)return i==="~"?ss():i.startsWith("~/")?ss()+i.slice(1):i;if(xo)return fo(process.execPath);let e=Np;for(;e!==fo(e);){if(xa(xe(e,"package.json")))return e;e=fo(e)}return Np}function va(){if(xo)return xe(Vt(),"theme");let i=Vt(),e=xa(xe(i,"src"))?"src":"dist";return xe(i,e,"modes","interactive","theme")}function Gf(){return xe(Vt(),"package.json")}function ya(){return ba(xe(Vt(),"README.md"))}function bo(){return ba(xe(Vt(),"docs"))}function vo(){return ba(xe(Vt(),"CHANGELOG.md"))}function Kf(){if(xo)return xe(Vt(),"assets");let i=Vt(),e=xa(xe(i,"src"))?"src":"dist";return xe(i,e,"modes","interactive","assets")}function Gp(i){return xe(Kf(),i)}var yo=JSON.parse($f(Gf(),"utf-8")),Kp=yo.piConfig?.name,zf=yo.name||"@earendil-works/pi-coding-agent",Ae=Kp||"pi",wa=Kp?Ae:"\u03C0",Te=yo.piConfig?.configDir||".pi",Lt=yo.version||"0.0.0",zp=`${Ae.toUpperCase()}_CODING_AGENT_DIR`,Hp=`${Ae.toUpperCase()}_CODING_AGENT_SESSION_DIR`;function jp(i){return i==="~"?ss():i.startsWith("~/")?ss()+i.slice(1):i}var Hf="https://pi.dev/session/";function qp(i){return`${process.env.PI_SHARE_VIEWER_URL||Hf}#${i}`}function ce(){let i=process.env[zp];return i?jp(i):xe(ss(),Te,"agent")}function os(){return xe(ce(),"themes")}function ka(){return xe(ce(),"auth.json")}function rs(){return xe(ce(),"bin")}function Vp(){return xe(ce(),"sessions")}function Qp(){return xe(ce(),`${Ae}-debug.log`)}import{Type as iP}from"typebox";var jf=new Map;function qf(i,e){return(t,n,s)=>{if(t.api!==i)throw new Error(`Mismatched api: ${t.api} expected ${i}`);return e(t,n,s)}}function Vf(i,e){return(t,n,s)=>{if(t.api!==i)throw new Error(`Mismatched api: ${t.api} expected ${i}`);return e(t,n,s)}}function Xe(i,e){jf.set(i.api,{provider:{api:i.api,stream:qf(i.api,i.stream),streamSimple:Vf(i.api,i.streamSimple)},sourceId:e})}pt();var Yp={openrouter:{"black-forest-labs/flux.2-flex":{id:"black-forest-labs/flux.2-flex",name:"Black Forest Labs: FLUX.2 Flex",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"black-forest-labs/flux.2-klein-4b":{id:"black-forest-labs/flux.2-klein-4b",name:"Black Forest Labs: FLUX.2 Klein 4B",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"black-forest-labs/flux.2-max":{id:"black-forest-labs/flux.2-max",name:"Black Forest Labs: FLUX.2 Max",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"black-forest-labs/flux.2-pro":{id:"black-forest-labs/flux.2-pro",name:"Black Forest Labs: FLUX.2 Pro",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"bytedance-seed/seedream-4.5":{id:"bytedance-seed/seedream-4.5",name:"ByteDance Seed: Seedream 4.5",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"google/gemini-2.5-flash-image":{id:"google/gemini-2.5-flash-image",name:"Google: Nano Banana (Gemini 2.5 Flash Image)",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:.3,output:2.5,cacheRead:.03,cacheWrite:.08333333333333334}},"google/gemini-3-pro-image-preview":{id:"google/gemini-3-pro-image-preview",name:"Google: Nano Banana Pro (Gemini 3 Pro Image Preview)",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:2,output:12,cacheRead:.19999999999999998,cacheWrite:.375}},"google/gemini-3.1-flash-image-preview":{id:"google/gemini-3.1-flash-image-preview",name:"Google: Nano Banana 2 (Gemini 3.1 Flash Image Preview)",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:.5,output:3,cacheRead:0,cacheWrite:0}},"openai/gpt-5-image":{id:"openai/gpt-5-image",name:"OpenAI: GPT-5 Image",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:10,output:10,cacheRead:1.25,cacheWrite:0}},"openai/gpt-5-image-mini":{id:"openai/gpt-5-image-mini",name:"OpenAI: GPT-5 Image Mini",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:2.5,output:2,cacheRead:.25,cacheWrite:0}},"openai/gpt-5.4-image-2":{id:"openai/gpt-5.4-image-2",name:"OpenAI: GPT-5.4 Image 2",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["image","text"],output:["image","text"],cost:{input:8,output:15,cacheRead:2,cacheWrite:0}},"openrouter/auto":{id:"openrouter/auto",name:"Auto Router",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["text","image"],cost:{input:-1e6,output:-1e6,cacheRead:0,cacheWrite:0}},"recraft/recraft-v3":{id:"recraft/recraft-v3",name:"Recraft: Recraft V3",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4":{id:"recraft/recraft-v4",name:"Recraft: Recraft V4",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"recraft/recraft-v4-pro":{id:"recraft/recraft-v4-pro",name:"Recraft: Recraft V4 Pro",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-fast":{id:"sourceful/riverflow-v2-fast",name:"Sourceful: Riverflow V2 Fast",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-fast-preview":{id:"sourceful/riverflow-v2-fast-preview",name:"Sourceful: Riverflow V2 Fast Preview",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-max-preview":{id:"sourceful/riverflow-v2-max-preview",name:"Sourceful: Riverflow V2 Max Preview",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-pro":{id:"sourceful/riverflow-v2-pro",name:"Sourceful: Riverflow V2 Pro",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}},"sourceful/riverflow-v2-standard-preview":{id:"sourceful/riverflow-v2-standard-preview",name:"Sourceful: Riverflow V2 Standard Preview",api:"openrouter-images",provider:"openrouter",baseUrl:"https://openrouter.ai/api/v1",input:["text","image"],output:["image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}}}};var e0=new Map;for(let[i,e]of Object.entries(Yp)){let t=new Map;for(let[n,s]of Object.entries(e))t.set(n,s);e0.set(i,t)}var t0=new Map;function n0(i,e){return(t,n,s)=>{if(t.api!==i)throw new Error(`Mismatched api: ${t.api} expected ${i}`);return e(t,n,s)}}function Xp(i,e){t0.set(i.api,{provider:{api:i.api,generateImages:n0(i.api,i.generateImages)},sourceId:e})}var td;function l0(i,e){return{api:i.api,provider:i.provider,model:i.id,output:[],stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function c0(){return td||=Promise.resolve().then(()=>(ed(),Zp)).then(i=>i),td}var p0=async(i,e,t)=>{try{return await(await c0()).generateImagesOpenRouter(i,e,t)}catch(n){return l0(i,n)}};function d0(){Xp({api:"openrouter-images",generateImages:p0})}d0();Ze();et();et();var ov=i=>import(i),hu,gu,fu,xu,bu,vu,yu,wu,ku,Su;function Tu(i,e){(async()=>{for await(let t of e)i.push(t);i.end()})()}function Cu(i,e){return{role:"assistant",content:[],api:i.api,provider:i.provider,model:i.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function Ut(i){return(e,t,n)=>{let s=new de;return i().then(o=>{let r=o.stream(e,t,n);Tu(s,r)}).catch(o=>{let r=Cu(e,o);s.push({type:"error",reason:"error",error:r}),s.end(r)}),s}}function Dt(i){return(e,t,n)=>{let s=new de;return i().then(o=>{let r=o.streamSimple(e,t,n);Tu(s,r)}).catch(o=>{let r=Cu(e,o);s.push({type:"error",reason:"error",error:r}),s.end(r)}),s}}function Mu(){return hu||=Promise.resolve().then(()=>(md(),ud)).then(i=>{let e=i;return{stream:e.streamAnthropic,streamSimple:e.streamSimpleAnthropic}}),hu}function Ru(){return gu||=Promise.resolve().then(()=>(fd(),gd)).then(i=>{let e=i;return{stream:e.streamAzureOpenAIResponses,streamSimple:e.streamSimpleAzureOpenAIResponses}}),gu}function Eu(){return fu||=Promise.resolve().then(()=>(yd(),vd)).then(i=>{let e=i;return{stream:e.streamGoogle,streamSimple:e.streamSimpleGoogle}}),fu}function Iu(){return xu||=Promise.resolve().then(()=>(Md(),Cd)).then(i=>{let e=i;return{stream:e.streamGoogleVertex,streamSimple:e.streamSimpleGoogleVertex}}),xu}function Au(){return bu||=Promise.resolve().then(()=>(_d(),Pd)).then(i=>{let e=i;return{stream:e.streamMistral,streamSimple:e.streamSimpleMistral}}),bu}function Pu(){return vu||=Promise.resolve().then(()=>(eu(),Zd)).then(i=>{let e=i;return{stream:e.streamOpenAICodexResponses,streamSimple:e.streamSimpleOpenAICodexResponses}}),vu}function _u(){return yu||=Promise.resolve().then(()=>(lu(),au)).then(i=>{let e=i;return{stream:e.streamOpenAICompletions,streamSimple:e.streamSimpleOpenAICompletions}}),yu}function Lu(){return wu||=Promise.resolve().then(()=>(mu(),uu)).then(i=>{let e=i;return{stream:e.streamOpenAIResponses,streamSimple:e.streamSimpleOpenAIResponses}}),wu}function Wu(){return ku?Promise.resolve(ku):(Su||=ov("./amazon-bedrock.js").then(i=>{let e=i;return{stream:e.streamBedrock,streamSimple:e.streamSimpleBedrock}}),Su)}var rv=Ut(Mu),av=Dt(Mu),lv=Ut(Ru),cv=Dt(Ru),pv=Ut(Eu),dv=Dt(Eu),uv=Ut(Iu),mv=Dt(Iu),hv=Ut(Au),gv=Dt(Au),fv=Ut(Pu),xv=Dt(Pu),bv=Ut(_u),vv=Dt(_u),yv=Ut(Lu),wv=Dt(Lu),kv=Ut(Wu),Sv=Dt(Wu);function Tv(){Xe({api:"anthropic-messages",stream:rv,streamSimple:av}),Xe({api:"openai-completions",stream:bv,streamSimple:vv}),Xe({api:"mistral-conversations",stream:hv,streamSimple:gv}),Xe({api:"openai-responses",stream:yv,streamSimple:wv}),Xe({api:"azure-openai-responses",stream:lv,streamSimple:cv}),Xe({api:"openai-codex-responses",stream:fv,streamSimple:xv}),Xe({api:"google-generative-ai",stream:pv,streamSimple:dv}),Xe({api:"google-vertex",stream:uv,streamSimple:mv}),Xe({api:"bedrock-converse-stream",stream:kv,streamSimple:Sv})}Tv();Na();pt();Ga();et();jn();import{Type as VA}from"typebox";import{Compile as YA}from"typebox/compile";import{Value as ZA}from"typebox/value";var eP=Symbol.for("TypeBox.Kind");import*as _e from"node:fs";import*as wn from"node:path";import ei from"chalk";import{highlight as $u,supportsLanguage as Bu}from"cli-highlight";import{Type as Re}from"typebox";import{Compile as Rv}from"typebox/compile";import{watch as Mv}from"node:fs";var Ou=5e3;function vn(i){if(i)try{i.close()}catch{}}function Zn(i,e,t){try{let n=Mv(i,e);return n.on("error",t),n}catch{return t(),null}}var B=Re.Union([Re.String(),Re.Integer({minimum:0,maximum:255})]),Ev=Re.Object({$schema:Re.Optional(Re.String()),name:Re.String(),vars:Re.Optional(Re.Record(Re.String(),B)),colors:Re.Object({accent:B,border:B,borderAccent:B,borderMuted:B,success:B,error:B,warning:B,muted:B,dim:B,text:B,thinkingText:B,selectedBg:B,userMessageBg:B,userMessageText:B,customMessageBg:B,customMessageText:B,customMessageLabel:B,toolPendingBg:B,toolSuccessBg:B,toolErrorBg:B,toolTitle:B,toolOutput:B,mdHeading:B,mdLink:B,mdLinkUrl:B,mdCode:B,mdCodeBlock:B,mdCodeBlockBorder:B,mdQuote:B,mdQuoteBorder:B,mdHr:B,mdListBullet:B,toolDiffAdded:B,toolDiffRemoved:B,toolDiffContext:B,syntaxComment:B,syntaxKeyword:B,syntaxFunction:B,syntaxVariable:B,syntaxString:B,syntaxNumber:B,syntaxType:B,syntaxOperator:B,syntaxPunctuation:B,thinkingOff:B,thinkingMinimal:B,thinkingLow:B,thinkingMedium:B,thinkingHigh:B,thinkingXhigh:B,bashMode:B}),export:Re.Optional(Re.Object({pageBg:Re.Optional(B),cardBg:Re.Optional(B),infoBg:Re.Optional(B)}))}),Uu=Rv(Ev);function Iv(){let i=process.env.COLORTERM;if(i==="truecolor"||i==="24bit"||process.env.WT_SESSION)return"truecolor";let e=process.env.TERM||"";return e==="dumb"||e===""||e==="linux"||process.env.TERM_PROGRAM==="Apple_Terminal"||e==="screen"||e.startsWith("screen-")||e.startsWith("screen.")?"256color":"truecolor"}function Za(i){let e=i.replace("#","");if(e.length!==6)throw new Error(`Invalid hex color: ${i}`);let t=parseInt(e.substring(0,2),16),n=parseInt(e.substring(2,4),16),s=parseInt(e.substring(4,6),16);if(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(s))throw new Error(`Invalid hex color: ${i}`);return{r:t,g:n,b:s}}var fs=[0,95,135,175,215,255],Ya=Array.from({length:24},(i,e)=>8+e*10);function Va(i){let e=1/0,t=0;for(let n=0;n<fs.length;n++){let s=Math.abs(i-fs[n]);s<e&&(e=s,t=n)}return t}function Av(i){let e=1/0,t=0;for(let n=0;n<Ya.length;n++){let s=Math.abs(i-Ya[n]);s<e&&(e=s,t=n)}return t}function Du(i,e,t,n,s,o){let r=i-n,a=e-s,l=t-o;return r*r*.299+a*a*.587+l*l*.114}function Pv(i,e,t){let n=Va(i),s=Va(e),o=Va(t),r=fs[n],a=fs[s],l=fs[o],c=16+36*n+6*s+o,d=Du(i,e,t,r,a,l),p=Math.round(.299*i+.587*e+.114*t),u=Av(p),h=Ya[u],m=232+u,g=Du(i,e,t,h,h,h),x=Math.max(i,e,t),b=Math.min(i,e,t);return x-b<10&&g<d?m:c}function Nu(i){let{r:e,g:t,b:n}=Za(i);return Pv(e,t,n)}function _v(i,e){if(i==="")return"\x1B[39m";if(typeof i=="number")return`\x1B[38;5;${i}m`;if(i.startsWith("#"))if(e==="truecolor"){let{r:t,g:n,b:s}=Za(i);return`\x1B[38;2;${t};${n};${s}m`}else return`\x1B[38;5;${Nu(i)}m`;throw new Error(`Invalid color value: ${i}`)}function Lv(i,e){if(i==="")return"\x1B[49m";if(typeof i=="number")return`\x1B[48;5;${i}m`;if(i.startsWith("#"))if(e==="truecolor"){let{r:t,g:n,b:s}=Za(i);return`\x1B[48;2;${t};${n};${s}m`}else return`\x1B[48;5;${Nu(i)}m`;throw new Error(`Invalid color value: ${i}`)}function Gu(i,e,t=new Set){if(typeof i=="number"||i===""||i.startsWith("#"))return i;if(t.has(i))throw new Error(`Circular variable reference detected: ${i}`);if(!(i in e))throw new Error(`Variable reference not found: ${i}`);return t.add(i),Gu(e[i],e,t)}function Wv(i,e={}){let t={};for(let[n,s]of Object.entries(i))t[n]=Gu(s,e);return t}var ti=class{constructor(e,t,n,s={}){this.name=s.name,this.sourcePath=s.sourcePath,this.sourceInfo=s.sourceInfo,this.mode=n,this.fgColors=new Map;for(let[o,r]of Object.entries(e))this.fgColors.set(o,_v(r,n));this.bgColors=new Map;for(let[o,r]of Object.entries(t))this.bgColors.set(o,Lv(r,n))}fg(e,t){let n=this.fgColors.get(e);if(!n)throw new Error(`Unknown theme color: ${e}`);return`${n}${t}\x1B[39m`}bg(e,t){let n=this.bgColors.get(e);if(!n)throw new Error(`Unknown theme background color: ${e}`);return`${n}${t}\x1B[49m`}bold(e){return ei.bold(e)}italic(e){return ei.italic(e)}underline(e){return ei.underline(e)}inverse(e){return ei.inverse(e)}strikethrough(e){return ei.strikethrough(e)}getFgAnsi(e){let t=this.fgColors.get(e);if(!t)throw new Error(`Unknown theme color: ${e}`);return t}getBgAnsi(e){let t=this.bgColors.get(e);if(!t)throw new Error(`Unknown theme background color: ${e}`);return t}getColorMode(){return this.mode}getThinkingBorderColor(e){switch(e){case"off":return t=>this.fg("thinkingOff",t);case"minimal":return t=>this.fg("thinkingMinimal",t);case"low":return t=>this.fg("thinkingLow",t);case"medium":return t=>this.fg("thinkingMedium",t);case"high":return t=>this.fg("thinkingHigh",t);case"xhigh":return t=>this.fg("thinkingXhigh",t);default:return t=>this.fg("thinkingOff",t)}}getBashModeBorderColor(){return e=>this.fg("bashMode",e)}},Qa;function el(){if(!Qa){let i=va(),e=wn.join(i,"dark.json"),t=wn.join(i,"light.json");Qa={dark:JSON.parse(_e.readFileSync(e,"utf-8")),light:JSON.parse(_e.readFileSync(t,"utf-8"))}}return Qa}function tl(){let i=new Set(Object.keys(el())),e=os();if(_e.existsSync(e)){let t=_e.readdirSync(e);for(let n of t)n.endsWith(".json")&&i.add(n.slice(0,-5))}for(let t of Sn.keys())i.add(t);return Array.from(i).sort()}function Ku(){let i=va(),e=os(),t=[];for(let n of Object.keys(el()))t.push({name:n,path:wn.join(i,`${n}.json`)});if(_e.existsSync(e)){for(let n of _e.readdirSync(e))if(n.endsWith(".json")){let s=n.slice(0,-5);t.some(o=>o.name===s)||t.push({name:s,path:wn.join(e,n)})}}for(let[n,s]of Sn.entries())t.some(o=>o.name===n)||t.push({name:n,path:s.sourcePath});return t.sort((n,s)=>n.name.localeCompare(s.name))}function Ov(i,e){if(!Uu.Check(e)){let t=Array.from(Uu.Errors(e)),n=new Set,s=[];for(let r of t){if(r.keyword==="required"&&r.instancePath==="/colors"){let l=r.params.requiredProperties;for(let c of l??[])n.add(c);continue}let a=r.instancePath||"/";s.push(` - ${a}: ${r.message}`)}let o=`Invalid theme "${i}":
|
|
87
|
+
`;throw n.size>0&&(o+=`
|
|
88
|
+
Missing required color tokens:
|
|
89
|
+
`,o+=Array.from(n).sort().map(r=>` - ${r}`).join(`
|
|
90
|
+
`),o+=`
|
|
91
|
+
|
|
92
|
+
Please add these colors to your theme's "colors" object.`,o+=`
|
|
93
|
+
See the built-in themes (dark.json, light.json) for reference values.`),s.length>0&&(o+=`
|
|
94
|
+
|
|
95
|
+
Other errors:
|
|
96
|
+
${s.join(`
|
|
97
|
+
`)}`),new Error(o)}return e}function Xa(i,e){let t;try{t=JSON.parse(e)}catch(n){throw new Error(`Failed to parse theme ${i}: ${n}`)}return Ov(i,t)}function Uv(i){let e=el();if(i in e)return e[i];let t=Sn.get(i);if(t?.sourcePath){let r=_e.readFileSync(t.sourcePath,"utf-8");return Xa(t.sourcePath,r)}if(t)throw new Error(`Theme "${i}" does not have a source path for export`);let n=os(),s=wn.join(n,`${i}.json`);if(!_e.existsSync(s))throw new Error(`Theme not found: ${i}`);let o=_e.readFileSync(s,"utf-8");return Xa(i,o)}function zu(i,e,t){let n=e??Iv(),s=Wv(i.colors,i.vars),o={},r={},a=new Set(["selectedBg","userMessageBg","customMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg"]);for(let[l,c]of Object.entries(s))a.has(l)?r[l]=c:o[l]=c;return new ti(o,r,n,{name:i.name,sourcePath:t})}function Hu(i,e){let t=_e.readFileSync(i,"utf-8"),n=Xa(i,t);return zu(n,e,i)}function bs(i,e){let t=Sn.get(i);if(t)return t;let n=Uv(i);return zu(n,e)}function ju(i){try{return bs(i)}catch{return}}function Dv(){let i=process.env.COLORFGBG||"";if(i){let e=i.split(";");if(e.length>=2){let t=parseInt(e[1],10);if(!Number.isNaN(t))return t<8?"dark":"light"}}return"dark"}function Fv(){return Dv()}var qu=Symbol.for("@earendil-works/pi-coding-agent:theme"),f=new Proxy({},{get(i,e){let t=globalThis[qu];if(!t)throw new Error("Theme not initialized. Call initTheme() first.");return t[e]}});function ni(i){globalThis[qu]=i}var mt,xs,yn,kn,Sn=new Map;function No(i){Sn.clear();for(let e of i)e.name&&Sn.set(e.name,e)}function vs(i,e=!1){let t=i??Fv();mt=t;try{ni(bs(t)),e&&Ju()}catch{mt="dark",ni(bs("dark"))}}function ys(i,e=!1){mt=i;try{return ni(bs(i)),e&&Ju(),kn&&kn(),{success:!0}}catch(t){return mt="dark",ni(bs("dark")),{success:!1,error:t instanceof Error?t.message:String(t)}}}function Vu(i){ni(i),mt="<in-memory>",ii(),kn&&kn()}function Qu(i){kn=i}function Ju(){if(ii(),!mt||mt==="dark"||mt==="light")return;let i=os(),e=mt,t=`${e}.json`,n=wn.join(i,t);if(!_e.existsSync(n))return;let s=()=>{yn&&clearTimeout(yn),yn=setTimeout(()=>{if(yn=void 0,mt===e&&_e.existsSync(n))try{let o=Hu(n);Sn.set(e,o),ni(o),kn&&kn()}catch{}},100)};xs=Zn(i,(o,r)=>{if(mt===e){if(!r){s();return}r===t&&s()}},()=>{vn(xs),xs=void 0})??void 0}function ii(){yn&&(clearTimeout(yn),yn=void 0),vn(xs),xs=void 0}var Fu,Ja;function $v(i){return{keyword:e=>i.fg("syntaxKeyword",e),built_in:e=>i.fg("syntaxType",e),literal:e=>i.fg("syntaxNumber",e),number:e=>i.fg("syntaxNumber",e),string:e=>i.fg("syntaxString",e),comment:e=>i.fg("syntaxComment",e),function:e=>i.fg("syntaxFunction",e),title:e=>i.fg("syntaxFunction",e),class:e=>i.fg("syntaxType",e),type:e=>i.fg("syntaxType",e),attr:e=>i.fg("syntaxVariable",e),variable:e=>i.fg("syntaxVariable",e),params:e=>i.fg("syntaxVariable",e),operator:e=>i.fg("syntaxOperator",e),punctuation:e=>i.fg("syntaxPunctuation",e)}}function Yu(i){return(Fu!==i||!Ja)&&(Fu=i,Ja=$v(i)),Ja}function Jt(i,e){let t=e&&Bu(e)?e:void 0;if(!t)return i.split(`
|
|
98
|
+
`).map(s=>f.fg("mdCodeBlock",s));let n={language:t,ignoreIllegals:!0,theme:Yu(f)};try{return $u(i,n).split(`
|
|
99
|
+
`)}catch{return i.split(`
|
|
100
|
+
`)}}function Tn(i){let e=i.split(".").pop()?.toLowerCase();return e?{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",rb:"ruby",rs:"rust",go:"go",java:"java",kt:"kotlin",swift:"swift",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",fish:"fish",ps1:"powershell",sql:"sql",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",md:"markdown",markdown:"markdown",dockerfile:"dockerfile",makefile:"makefile",cmake:"cmake",lua:"lua",perl:"perl",r:"r",scala:"scala",clj:"clojure",ex:"elixir",exs:"elixir",erl:"erlang",hs:"haskell",ml:"ocaml",vim:"vim",graphql:"graphql",proto:"protobuf",tf:"hcl",hcl:"hcl"}[e]:void 0}function we(){return{heading:i=>f.fg("mdHeading",i),link:i=>f.fg("mdLink",i),linkUrl:i=>f.fg("mdLinkUrl",i),code:i=>f.fg("mdCode",i),codeBlock:i=>f.fg("mdCodeBlock",i),codeBlockBorder:i=>f.fg("mdCodeBlockBorder",i),quote:i=>f.fg("mdQuote",i),quoteBorder:i=>f.fg("mdQuoteBorder",i),hr:i=>f.fg("mdHr",i),listBullet:i=>f.fg("mdListBullet",i),bold:i=>f.bold(i),italic:i=>f.italic(i),underline:i=>f.underline(i),strikethrough:i=>ei.strikethrough(i),highlightCode:(i,e)=>{let t=e&&Bu(e)?e:void 0;if(!t)return i.split(`
|
|
101
|
+
`).map(s=>f.fg("mdCodeBlock",s));let n={language:t,ignoreIllegals:!0,theme:Yu(f)};try{return $u(i,n).split(`
|
|
102
|
+
`)}catch{return i.split(`
|
|
103
|
+
`).map(s=>f.fg("mdCodeBlock",s))}}}}function Cn(){return{selectedPrefix:i=>f.fg("accent",i),selectedText:i=>f.fg("accent",i),description:i=>f.fg("muted",i),scrollInfo:i=>f.fg("muted",i),noMatch:i=>f.fg("muted",i)}}function ws(){return{borderColor:i=>f.fg("borderMuted",i),selectList:Cn()}}function Go(){return{label:(i,e)=>e?f.fg("accent",i):i,value:(i,e)=>e?f.fg("accent",i):f.fg("muted",i),description:i=>f.fg("dim",i),cursor:f.fg("accent","\u2192 "),hint:i=>f.fg("dim",i)}}import{parse as _P}from"yaml";import zP from"strip-ansi";import{existsSync as Ko}from"node:fs";import{delimiter as Xu}from"node:path";import{spawn as Bv,spawnSync as Zu}from"child_process";function em(){if(process.platform==="win32"){try{let i=Zu("where",["bash.exe"],{encoding:"utf-8",timeout:5e3});if(i.status===0&&i.stdout){let e=i.stdout.trim().split(/\r?\n/)[0];if(e&&Ko(e))return e}}catch{}return null}try{let i=Zu("which",["bash"],{encoding:"utf-8",timeout:5e3});if(i.status===0&&i.stdout){let e=i.stdout.trim().split(/\r?\n/)[0];if(e)return e}}catch{}return null}function Ho(i){if(i){if(Ko(i))return{shell:i,args:["-c"]};throw new Error(`Custom shell path not found: ${i}`)}if(process.platform==="win32"){let t=[],n=process.env.ProgramFiles;n&&t.push(`${n}\\Git\\bin\\bash.exe`);let s=process.env["ProgramFiles(x86)"];s&&t.push(`${s}\\Git\\bin\\bash.exe`);for(let r of t)if(Ko(r))return{shell:r,args:["-c"]};let o=em();if(o)return{shell:o,args:["-c"]};throw new Error(`No bash shell found. Options:
|
|
104
|
+
1. Install Git for Windows: https://git-scm.com/download/win
|
|
105
|
+
2. Add your bash to PATH (Cygwin, MSYS2, etc.)
|
|
106
|
+
3. Set shellPath in settings.json
|
|
107
|
+
|
|
108
|
+
Searched Git Bash in:
|
|
109
|
+
${t.map(r=>` ${r}`).join(`
|
|
110
|
+
`)}`)}if(Ko("/bin/bash"))return{shell:"/bin/bash",args:["-c"]};let e=em();return e?{shell:e,args:["-c"]}:{shell:"sh",args:["-c"]}}function nl(){let i=rs(),e=Object.keys(process.env).find(r=>r.toLowerCase()==="path")??"PATH",t=process.env[e]??"",o=t.split(Xu).filter(Boolean).includes(i)?t:[i,t].filter(Boolean).join(Xu);return{...process.env,[e]:o}}function il(i){return Array.from(i).filter(e=>{let t=e.codePointAt(0);return t===void 0?!1:t===9||t===10||t===13?!0:!(t<=31||t>=65529&&t<=65531)}).join("")}var zo=new Set;function tm(i){zo.add(i)}function sl(i){zo.delete(i)}function ks(){for(let i of zo)jo(i);zo.clear()}function jo(i){if(process.platform==="win32")try{Bv("taskkill",["/F","/T","/PID",String(i)],{stdio:"ignore",detached:!0})}catch{}else try{process.kill(-i,"SIGKILL")}catch{try{process.kill(i,"SIGKILL")}catch{}}}function re(i){return i<1024?`${i}B`:i<1024*1024?`${(i/1024).toFixed(1)}KB`:`${(i/(1024*1024)).toFixed(1)}MB`}function ht(i,e={}){let t=e.maxLines??2e3,n=e.maxBytes??51200,s=Buffer.byteLength(i,"utf-8"),o=i.split(`
|
|
111
|
+
`),r=o.length;if(r<=t&&s<=n)return{content:i,truncated:!1,truncatedBy:null,totalLines:r,totalBytes:s,outputLines:r,outputBytes:s,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:t,maxBytes:n};if(Buffer.byteLength(o[0],"utf-8")>n)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines:r,totalBytes:s,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:t,maxBytes:n};let l=[],c=0,d="lines";for(let h=0;h<o.length&&h<t;h++){let m=o[h],g=Buffer.byteLength(m,"utf-8")+(h>0?1:0);if(c+g>n){d="bytes";break}l.push(m),c+=g}l.length>=t&&c<=n&&(d="lines");let p=l.join(`
|
|
112
|
+
`),u=Buffer.byteLength(p,"utf-8");return{content:p,truncated:!0,truncatedBy:d,totalLines:r,totalBytes:s,outputLines:l.length,outputBytes:u,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:t,maxBytes:n}}function Mn(i,e={}){let t=e.maxLines??2e3,n=e.maxBytes??51200,s=Buffer.byteLength(i,"utf-8"),o=i.split(`
|
|
113
|
+
`),r=o.length;if(r<=t&&s<=n)return{content:i,truncated:!1,truncatedBy:null,totalLines:r,totalBytes:s,outputLines:r,outputBytes:s,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:t,maxBytes:n};let a=[],l=0,c="lines",d=!1;for(let h=o.length-1;h>=0&&a.length<t;h--){let m=o[h],g=Buffer.byteLength(m,"utf-8")+(a.length>0?1:0);if(l+g>n){if(c="bytes",a.length===0){let x=Nv(m,n);a.unshift(x),l=Buffer.byteLength(x,"utf-8"),d=!0}break}a.unshift(m),l+=g}a.length>=t&&l<=n&&(c="lines");let p=a.join(`
|
|
114
|
+
`),u=Buffer.byteLength(p,"utf-8");return{content:p,truncated:!0,truncatedBy:c,totalLines:r,totalBytes:s,outputLines:a.length,outputBytes:u,lastLinePartial:d,firstLineExceedsLimit:!1,maxLines:t,maxBytes:n}}function Nv(i,e){let t=Buffer.from(i,"utf-8");if(t.length<=e)return i;let n=t.length-e;for(;n<t.length&&(t[n]&192)===128;)n++;return t.slice(n).toString("utf-8")}function Ss(i,e=500){return i.length<=e?{text:i,wasTruncated:!1}:{text:`${i.slice(0,e)}... [truncated]`,wasTruncated:!0}}function qo(i,e,t){return{role:"branchSummary",summary:i,fromId:e,timestamp:new Date(t).getTime()}}function si(i,e,t){return{role:"compactionSummary",summary:i,tokensBefore:e,timestamp:new Date(t).getTime()}}function Vo(i,e,t,n,s){return{role:"custom",customType:i,content:e,display:t,details:n,timestamp:new Date(s).getTime()}}import{randomUUID as nm}from"crypto";import{appendFileSync as Qo,closeSync as Gv,existsSync as Rn,mkdirSync as rl,openSync as Kv,readdirSync as zv,readFileSync as Hv,readSync as jv,statSync as qv,writeFileSync as Vv}from"fs";import{readdir as al,readFile as Qv,stat as Jv}from"fs/promises";import{join as Yt,resolve as im}from"path";import{v7 as Yv}from"uuid";var oi=3;function Jo(){return Yv()}function tt(i){for(let e=0;e<100;e++){let t=nm().slice(0,8);if(!i.has(t))return t}return nm()}function Xv(i){let e=new Set,t=null;for(let n of i){if(n.type==="session"){n.version=2;continue}if(n.id=tt(e),n.parentId=t,t=n.id,n.type==="compaction"){let s=n;if(typeof s.firstKeptEntryIndex=="number"){let o=i[s.firstKeptEntryIndex];o&&o.type!=="session"&&(s.firstKeptEntryId=o.id),delete s.firstKeptEntryIndex}}}}function Zv(i){for(let e of i){if(e.type==="session"){e.version=3;continue}if(e.type==="message"){let t=e;t.message&&t.message.role==="hookMessage"&&(t.message.role="custom")}}}function ey(i){let t=i.find(n=>n.type==="session")?.version??1;return t>=oi?!1:(t<2&&Xv(i),t<3&&Zv(i),!0)}function ll(i,e,t){if(!t){t=new Map;for(let p of i)t.set(p.id,p)}let n;if(e===null)return{messages:[],thinkingLevel:"off",model:null};if(e&&(n=t.get(e)),n||(n=i[i.length-1]),!n)return{messages:[],thinkingLevel:"off",model:null};let s=[],o=n;for(;o;)s.unshift(o),o=o.parentId?t.get(o.parentId):void 0;let r="off",a=null,l=null;for(let p of s)p.type==="thinking_level_change"?r=p.thinkingLevel:p.type==="model_change"?a={provider:p.provider,modelId:p.modelId}:p.type==="message"&&p.message.role==="assistant"?a={provider:p.message.provider,modelId:p.message.model}:p.type==="compaction"&&(l=p);let c=[],d=p=>{p.type==="message"?c.push(p.message):p.type==="custom_message"?c.push(Vo(p.customType,p.content,p.display,p.details,p.timestamp)):p.type==="branch_summary"&&p.summary&&c.push(qo(p.summary,p.fromId,p.timestamp))};if(l){c.push(si(l.summary,l.tokensBefore,l.timestamp));let p=s.findIndex(h=>h.type==="compaction"&&h.id===l.id),u=!1;for(let h=0;h<p;h++){let m=s[h];m.id===l.firstKeptEntryId&&(u=!0),u&&d(m)}for(let h=p+1;h<s.length;h++){let m=s[h];d(m)}}else for(let p of s)d(p);return{messages:c,thinkingLevel:r,model:a}}function Ts(i,e=ce()){let t=`--${i.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`,n=Yt(e,"sessions",t);return Rn(n)||rl(n,{recursive:!0}),n}function ol(i){if(!Rn(i))return[];let e=Hv(i,"utf8"),t=[],n=e.trim().split(`
|
|
115
|
+
`);for(let o of n)if(o.trim())try{let r=JSON.parse(o);t.push(r)}catch{}if(t.length===0)return t;let s=t[0];return s.type!=="session"||typeof s.id!="string"?[]:t}function ty(i){try{let e=Kv(i,"r"),t=Buffer.alloc(512),n=jv(e,t,0,512,0);Gv(e);let s=t.toString("utf8",0,n).split(`
|
|
116
|
+
`)[0];if(!s)return!1;let o=JSON.parse(s);return o.type==="session"&&typeof o.id=="string"}catch{return!1}}function ny(i){try{return zv(i).filter(t=>t.endsWith(".jsonl")).map(t=>Yt(i,t)).filter(ty).map(t=>({path:t,mtime:qv(t).mtime})).sort((t,n)=>n.mtime.getTime()-t.mtime.getTime())[0]?.path||null}catch{return null}}function sm(i){return typeof i.role=="string"&&"content"in i}function iy(i){let e=i.content;return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(" ")}function sy(i){let e;for(let t of i){if(t.type!=="message")continue;let n=t.message;if(!sm(n)||n.role!=="user"&&n.role!=="assistant")continue;let s=n.timestamp;if(typeof s=="number"){e=Math.max(e??0,s);continue}let o=t.timestamp;if(typeof o=="string"){let r=new Date(o).getTime();Number.isNaN(r)||(e=Math.max(e??0,r))}}return e}function oy(i,e,t){let n=sy(i);if(typeof n=="number"&&n>0)return new Date(n);let s=typeof e.timestamp=="string"?new Date(e.timestamp).getTime():NaN;return Number.isNaN(s)?t:new Date(s)}async function om(i){try{let e=await Qv(i,"utf8"),t=[],n=e.trim().split(`
|
|
117
|
+
`);for(let h of n)if(h.trim())try{t.push(JSON.parse(h))}catch{}if(t.length===0)return null;let s=t[0];if(s.type!=="session")return null;let o=await Jv(i),r=0,a="",l=[],c;for(let h of t){if(h.type==="session_info"&&(c=h.name?.trim()||void 0),h.type!=="message")continue;r++;let m=h.message;if(!sm(m)||m.role!=="user"&&m.role!=="assistant")continue;let g=iy(m);g&&(l.push(g),!a&&m.role==="user"&&(a=g))}let d=typeof s.cwd=="string"?s.cwd:"",p=s.parentSession,u=oy(t,s,o.mtime);return{path:i,id:s.id,cwd:d,name:c,parentSessionPath:p,created:new Date(s.timestamp),modified:u,messageCount:r,firstMessage:a||"(no messages)",allMessagesText:l.join(" ")}}catch{return null}}async function ry(i,e,t=0,n){let s=[];if(!Rn(i))return s;try{let r=(await al(i)).filter(d=>d.endsWith(".jsonl")).map(d=>Yt(i,d)),a=n??r.length,l=0,c=await Promise.all(r.map(async d=>{let p=await om(d);return l++,e?.(t+l,a),p}));for(let d of c)d&&s.push(d)}catch{}return s}var gt=class i{constructor(e,t,n,s){this.sessionId="";this.flushed=!1;this.fileEntries=[];this.byId=new Map;this.labelsById=new Map;this.labelTimestampsById=new Map;this.leafId=null;this.cwd=e,this.sessionDir=t,this.persist=s,s&&t&&!Rn(t)&&rl(t,{recursive:!0}),n?this.setSessionFile(n):this.newSession()}setSessionFile(e){if(this.sessionFile=im(e),Rn(this.sessionFile)){if(this.fileEntries=ol(this.sessionFile),this.fileEntries.length===0){let n=this.sessionFile;this.newSession(),this.sessionFile=n,this._rewriteFile(),this.flushed=!0;return}let t=this.fileEntries.find(n=>n.type==="session");this.sessionId=t?.id??Jo(),ey(this.fileEntries)&&this._rewriteFile(),this._buildIndex(),this.flushed=!0}else{let t=this.sessionFile;this.newSession(),this.sessionFile=t}}newSession(e){this.sessionId=e?.id??Jo();let t=new Date().toISOString(),n={type:"session",version:oi,id:this.sessionId,timestamp:t,cwd:this.cwd,parentSession:e?.parentSession};if(this.fileEntries=[n],this.byId.clear(),this.labelsById.clear(),this.leafId=null,this.flushed=!1,this.persist){let s=t.replace(/[:.]/g,"-");this.sessionFile=Yt(this.getSessionDir(),`${s}_${this.sessionId}.jsonl`)}return this.sessionFile}_buildIndex(){this.byId.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null;for(let e of this.fileEntries)e.type!=="session"&&(this.byId.set(e.id,e),this.leafId=e.id,e.type==="label"&&(e.label?(this.labelsById.set(e.targetId,e.label),this.labelTimestampsById.set(e.targetId,e.timestamp)):(this.labelsById.delete(e.targetId),this.labelTimestampsById.delete(e.targetId))))}_rewriteFile(){if(!this.persist||!this.sessionFile)return;let e=`${this.fileEntries.map(t=>JSON.stringify(t)).join(`
|
|
118
|
+
`)}
|
|
119
|
+
`;Vv(this.sessionFile,e)}isPersisted(){return this.persist}getCwd(){return this.cwd}getSessionDir(){return this.sessionDir}getSessionId(){return this.sessionId}getSessionFile(){return this.sessionFile}_persist(e){if(!this.persist||!this.sessionFile)return;if(!this.fileEntries.some(n=>n.type==="message"&&n.message.role==="assistant")){this.flushed=!1;return}if(this.flushed)Qo(this.sessionFile,`${JSON.stringify(e)}
|
|
120
|
+
`);else{for(let n of this.fileEntries)Qo(this.sessionFile,`${JSON.stringify(n)}
|
|
121
|
+
`);this.flushed=!0}}_appendEntry(e){this.fileEntries.push(e),this.byId.set(e.id,e),this.leafId=e.id,this._persist(e)}appendMessage(e){let t={type:"message",id:tt(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),message:e};return this._appendEntry(t),t.id}appendThinkingLevelChange(e){let t={type:"thinking_level_change",id:tt(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),thinkingLevel:e};return this._appendEntry(t),t.id}appendModelChange(e,t){let n={type:"model_change",id:tt(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),provider:e,modelId:t};return this._appendEntry(n),n.id}appendCompaction(e,t,n,s,o){let r={type:"compaction",id:tt(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),summary:e,firstKeptEntryId:t,tokensBefore:n,details:s,fromHook:o};return this._appendEntry(r),r.id}appendCustomEntry(e,t){let n={type:"custom",customType:e,data:t,id:tt(this.byId),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(n),n.id}appendSessionInfo(e){let t={type:"session_info",id:tt(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),name:e.trim()};return this._appendEntry(t),t.id}getSessionName(){let e=this.getEntries();for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type==="session_info")return n.name?.trim()||void 0}}appendCustomMessageEntry(e,t,n,s){let o={type:"custom_message",customType:e,content:t,display:n,details:s,id:tt(this.byId),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(o),o.id}getLeafId(){return this.leafId}getLeafEntry(){return this.leafId?this.byId.get(this.leafId):void 0}getEntry(e){return this.byId.get(e)}getChildren(e){let t=[];for(let n of this.byId.values())n.parentId===e&&t.push(n);return t}getLabel(e){return this.labelsById.get(e)}appendLabelChange(e,t){if(!this.byId.has(e))throw new Error(`Entry ${e} not found`);let n={type:"label",id:tt(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),targetId:e,label:t};return this._appendEntry(n),t?(this.labelsById.set(e,t),this.labelTimestampsById.set(e,n.timestamp)):(this.labelsById.delete(e),this.labelTimestampsById.delete(e)),n.id}getBranch(e){let t=[],n=e??this.leafId,s=n?this.byId.get(n):void 0;for(;s;)t.unshift(s),s=s.parentId?this.byId.get(s.parentId):void 0;return t}buildSessionContext(){return ll(this.getEntries(),this.leafId,this.byId)}getHeader(){let e=this.fileEntries.find(t=>t.type==="session");return e||null}getEntries(){return this.fileEntries.filter(e=>e.type!=="session")}getTree(){let e=this.getEntries(),t=new Map,n=[];for(let o of e){let r=this.labelsById.get(o.id),a=this.labelTimestampsById.get(o.id);t.set(o.id,{entry:o,children:[],label:r,labelTimestamp:a})}for(let o of e){let r=t.get(o.id);if(o.parentId===null||o.parentId===o.id)n.push(r);else{let a=t.get(o.parentId);a?a.children.push(r):n.push(r)}}let s=[...n];for(;s.length>0;){let o=s.pop();o.children.sort((r,a)=>new Date(r.entry.timestamp).getTime()-new Date(a.entry.timestamp).getTime()),s.push(...o.children)}return n}branch(e){if(!this.byId.has(e))throw new Error(`Entry ${e} not found`);this.leafId=e}resetLeaf(){this.leafId=null}branchWithSummary(e,t,n,s){if(e!==null&&!this.byId.has(e))throw new Error(`Entry ${e} not found`);this.leafId=e;let o={type:"branch_summary",id:tt(this.byId),parentId:e,timestamp:new Date().toISOString(),fromId:e??"root",summary:t,details:n,fromHook:s};return this._appendEntry(o),o.id}createBranchedSession(e){let t=this.sessionFile,n=this.getBranch(e);if(n.length===0)throw new Error(`Entry ${e} not found`);let s=n.filter(m=>m.type!=="label"),o=Jo(),r=new Date().toISOString(),a=r.replace(/[:.]/g,"-"),l=Yt(this.getSessionDir(),`${a}_${o}.jsonl`),c={type:"session",version:oi,id:o,timestamp:r,cwd:this.cwd,parentSession:this.persist?t:void 0},d=new Set(s.map(m=>m.id)),p=[];for(let[m,g]of this.labelsById)d.has(m)&&p.push({targetId:m,label:g,timestamp:this.labelTimestampsById.get(m)});if(this.persist){let g=s[s.length-1]?.id||null,x=[];for(let{targetId:v,label:w,timestamp:C}of p){let R={type:"label",id:tt(new Set(d)),parentId:g,timestamp:C,targetId:v,label:w};d.add(R.id),x.push(R),g=R.id}return this.fileEntries=[c,...s,...x],this.sessionId=o,this.sessionFile=l,this._buildIndex(),this.fileEntries.some(v=>v.type==="message"&&v.message.role==="assistant")?(this._rewriteFile(),this.flushed=!0):this.flushed=!1,l}let u=[],h=s[s.length-1]?.id||null;for(let{targetId:m,label:g,timestamp:x}of p){let b={type:"label",id:tt(new Set([...d,...u.map(v=>v.id)])),parentId:h,timestamp:x,targetId:m,label:g};u.push(b),h=b.id}this.fileEntries=[c,...s,...u],this.sessionId=o,this._buildIndex()}static create(e,t){let n=t??Ts(e);return new i(e,n,void 0,!0)}static open(e,t,n){let o=ol(e).find(l=>l.type==="session"),r=n??o?.cwd??process.cwd(),a=t??im(e,"..");return new i(r,a,e,!0)}static continueRecent(e,t){let n=t??Ts(e),s=ny(n);return s?new i(e,n,s,!0):new i(e,n,void 0,!0)}static inMemory(e=process.cwd()){return new i(e,"",void 0,!1)}static forkFrom(e,t,n){let s=ol(e);if(s.length===0)throw new Error(`Cannot fork: source session file is empty or invalid: ${e}`);if(!s.find(u=>u.type==="session"))throw new Error(`Cannot fork: source session has no header: ${e}`);let r=n??Ts(t);Rn(r)||rl(r,{recursive:!0});let a=Jo(),l=new Date().toISOString(),c=l.replace(/[:.]/g,"-"),d=Yt(r,`${c}_${a}.jsonl`);Qo(d,`${JSON.stringify({type:"session",version:oi,id:a,timestamp:l,cwd:t,parentSession:e})}
|
|
122
|
+
`);for(let u of s)u.type!=="session"&&Qo(d,`${JSON.stringify(u)}
|
|
123
|
+
`);return new i(t,r,d,!0)}static async list(e,t,n){let s=t??Ts(e),o=await ry(s,n);return o.sort((r,a)=>a.modified.getTime()-r.modified.getTime()),o}static async listAll(e){let t=Vp();try{if(!Rn(t))return[];let s=(await al(t,{withFileTypes:!0})).filter(p=>p.isDirectory()).map(p=>Yt(t,p.name)),o=0,r=[];for(let p of s)try{let u=(await al(p)).filter(h=>h.endsWith(".jsonl"));r.push(u.map(h=>Yt(p,h))),o+=u.length}catch{r.push([])}let a=0,l=[],c=r.flat(),d=await Promise.all(c.map(async p=>{let u=await om(p);return a++,e?.(a,o),u}));for(let p of d)p&&l.push(p);return l.sort((p,u)=>u.modified.getTime()-p.modified.getTime()),l}catch{return[]}}};import{createRequire as cw}from"node:module";import{parse as t_}from"yaml";import s_ from"ignore";import{parse as r_}from"yaml";import{v7 as I_}from"uuid";import{v7 as F_}from"uuid";var Ly='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#fff" fill-rule="evenodd" d="M165.29 165.29 H517.36 V400 H400 V517.36 H282.65 V634.72 H165.29 Z M282.65 282.65 V400 H400 V282.65 Z"/><path fill="#fff" d="M517.36 400 H634.72 V634.72 H517.36 Z"/></svg>';function Yo(i){return i.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function dm(i){let e=Yo(i.title),t=Yo(i.heading),n=Yo(i.message),s=i.details?Yo(i.details):void 0;return`<!doctype html>
|
|
124
|
+
<html lang="en">
|
|
125
|
+
<head>
|
|
126
|
+
<meta charset="utf-8" />
|
|
127
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
128
|
+
<title>${e}</title>
|
|
129
|
+
<style>
|
|
130
|
+
:root {
|
|
131
|
+
--text: #fafafa;
|
|
132
|
+
--text-dim: #a1a1aa;
|
|
133
|
+
--page-bg: #09090b;
|
|
134
|
+
--font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
|
135
|
+
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
|
136
|
+
}
|
|
137
|
+
* { box-sizing: border-box; }
|
|
138
|
+
html { color-scheme: dark; }
|
|
139
|
+
body {
|
|
140
|
+
margin: 0;
|
|
141
|
+
min-height: 100vh;
|
|
142
|
+
display: flex;
|
|
143
|
+
align-items: center;
|
|
144
|
+
justify-content: center;
|
|
145
|
+
padding: 24px;
|
|
146
|
+
background: var(--page-bg);
|
|
147
|
+
color: var(--text);
|
|
148
|
+
font-family: var(--font-sans);
|
|
149
|
+
text-align: center;
|
|
150
|
+
}
|
|
151
|
+
main {
|
|
152
|
+
width: 100%;
|
|
153
|
+
max-width: 560px;
|
|
154
|
+
display: flex;
|
|
155
|
+
flex-direction: column;
|
|
156
|
+
align-items: center;
|
|
157
|
+
justify-content: center;
|
|
158
|
+
}
|
|
159
|
+
.logo {
|
|
160
|
+
width: 72px;
|
|
161
|
+
height: 72px;
|
|
162
|
+
display: block;
|
|
163
|
+
margin-bottom: 24px;
|
|
164
|
+
}
|
|
165
|
+
h1 {
|
|
166
|
+
margin: 0 0 10px;
|
|
167
|
+
font-size: 28px;
|
|
168
|
+
line-height: 1.15;
|
|
169
|
+
font-weight: 650;
|
|
170
|
+
color: var(--text);
|
|
171
|
+
}
|
|
172
|
+
p {
|
|
173
|
+
margin: 0;
|
|
174
|
+
line-height: 1.7;
|
|
175
|
+
color: var(--text-dim);
|
|
176
|
+
font-size: 15px;
|
|
177
|
+
}
|
|
178
|
+
.details {
|
|
179
|
+
margin-top: 16px;
|
|
180
|
+
font-family: var(--font-mono);
|
|
181
|
+
font-size: 13px;
|
|
182
|
+
color: var(--text-dim);
|
|
183
|
+
white-space: pre-wrap;
|
|
184
|
+
word-break: break-word;
|
|
185
|
+
}
|
|
186
|
+
</style>
|
|
187
|
+
</head>
|
|
188
|
+
<body>
|
|
189
|
+
<main>
|
|
190
|
+
<div class="logo">${Ly}</div>
|
|
191
|
+
<h1>${t}</h1>
|
|
192
|
+
<p>${n}</p>
|
|
193
|
+
${s?`<div class="details">${s}</div>`:""}
|
|
194
|
+
</main>
|
|
195
|
+
</body>
|
|
196
|
+
</html>`}function Xo(i){return dm({title:"Authentication successful",heading:"Authentication successful",message:i})}function kt(i,e){return dm({title:"Authentication failed",heading:"Authentication failed",message:i,details:e})}function um(i){let e="";for(let t of i)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function Zo(){let i=new Uint8Array(32);crypto.getRandomValues(i);let e=um(i),n=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",n),o=um(new Uint8Array(s));return{verifier:e,challenge:o}}var er=null,ul=null,Wy=i=>atob(i),hl=Wy("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl"),Oy="https://claude.ai/oauth/authorize",ai="https://platform.claude.com/v1/oauth/token",Uy=process.env.PI_OAUTH_CALLBACK_HOST||"127.0.0.1",mm=53692,hm="/callback",ri=`http://localhost:${mm}${hm}`,Dy="org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";async function Fy(){if(er)return er;if(!ul){if(typeof process>"u"||!process.versions?.node&&!process.versions?.bun)throw new Error("Anthropic OAuth is only available in Node.js environments");ul=import("node:http").then(i=>({createServer:i.createServer}))}return er=await ul,er}function ml(i){let e=i.trim();if(!e)return{};try{let t=new URL(e);return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0}}catch{}if(e.includes("#")){let[t,n]=e.split("#",2);return{code:t,state:n}}if(e.includes("code=")){let t=new URLSearchParams(e);return{code:t.get("code")??void 0,state:t.get("state")??void 0}}return{code:e}}function Cs(i){if(i instanceof Error){let e=[`${i.name}: ${i.message}`],t=i;return t.code&&e.push(`code=${t.code}`),typeof t.errno<"u"&&e.push(`errno=${String(t.errno)}`),typeof i.cause<"u"&&e.push(`cause=${Cs(i.cause)}`),i.stack&&e.push(`stack=${i.stack}`),e.join("; ")}return String(i)}async function $y(i){let{createServer:e}=await Fy();return new Promise((t,n)=>{let s,o=new Promise(a=>{let l=!1;s=c=>{l||(l=!0,a(c))}}),r=e((a,l)=>{try{let c=new URL(a.url||"","http://localhost");if(c.pathname!==hm){l.writeHead(404,{"Content-Type":"text/html; charset=utf-8"}),l.end(kt("Callback route not found."));return}let d=c.searchParams.get("code"),p=c.searchParams.get("state"),u=c.searchParams.get("error");if(u){l.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),l.end(kt("Anthropic authentication did not complete.",`Error: ${u}`));return}if(!d||!p){l.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),l.end(kt("Missing code or state parameter."));return}if(p!==i){l.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),l.end(kt("State mismatch."));return}l.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),l.end(Xo("Anthropic authentication completed. You can close this window.")),s?.({code:d,state:p})}catch{l.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),l.end("Internal error")}});r.on("error",a=>{n(a)}),r.listen(mm,Uy,()=>{t({server:r,redirectUri:ri,cancelWait:()=>{s?.(null)},waitForCode:()=>o})})})}async function gm(i,e){let t=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(3e4)}),n=await t.text();if(!t.ok)throw new Error(`HTTP request failed. status=${t.status}; url=${i}; body=${n}`);return n}async function By(i,e,t,n){let s;try{s=await gm(ai,{grant_type:"authorization_code",client_id:hl,code:i,state:e,redirect_uri:n,code_verifier:t})}catch(r){throw new Error(`Token exchange request failed. url=${ai}; redirect_uri=${n}; response_type=authorization_code; details=${Cs(r)}`)}let o;try{o=JSON.parse(s)}catch(r){throw new Error(`Token exchange returned invalid JSON. url=${ai}; body=${s}; details=${Cs(r)}`)}return{refresh:o.refresh_token,access:o.access_token,expires:Date.now()+o.expires_in*1e3-300*1e3}}async function fm(i){let{verifier:e,challenge:t}=await Zo(),n=await $y(e),s,o,r=ri;try{let a=new URLSearchParams({code:"true",client_id:hl,response_type:"code",redirect_uri:ri,scope:Dy,code_challenge:t,code_challenge_method:"S256",state:e});if(i.onAuth({url:`${Oy}?${a.toString()}`,instructions:"Complete login in your browser. If the browser is on another machine, paste the final redirect URL here."}),i.onManualCodeInput){let l,c,d=i.onManualCodeInput().then(u=>{l=u,n.cancelWait()}).catch(u=>{c=u instanceof Error?u:new Error(String(u)),n.cancelWait()}),p=await n.waitForCode();if(c)throw c;if(p?.code)s=p.code,o=p.state,r=ri;else if(l){let u=ml(l);if(u.state&&u.state!==e)throw new Error("OAuth state mismatch");s=u.code,o=u.state??e}if(!s){if(await d,c)throw c;if(l){let u=ml(l);if(u.state&&u.state!==e)throw new Error("OAuth state mismatch");s=u.code,o=u.state??e}}}else{let l=await n.waitForCode();l?.code&&(s=l.code,o=l.state,r=ri)}if(!s){let l=await i.onPrompt({message:"Paste the authorization code or full redirect URL:",placeholder:ri}),c=ml(l);if(c.state&&c.state!==e)throw new Error("OAuth state mismatch");s=c.code,o=c.state??e}if(!s)throw new Error("Missing authorization code");if(!o)throw new Error("Missing OAuth state");return i.onProgress?.("Exchanging authorization code for tokens..."),By(s,o,e,r)}finally{n.server.close()}}async function xm(i){let e;try{e=await gm(ai,{grant_type:"refresh_token",client_id:hl,refresh_token:i})}catch(n){throw new Error(`Anthropic token refresh request failed. url=${ai}; details=${Cs(n)}`)}let t;try{t=JSON.parse(e)}catch(n){throw new Error(`Anthropic token refresh returned invalid JSON. url=${ai}; body=${e}; details=${Cs(n)}`)}return{refresh:t.refresh_token,access:t.access_token,expires:Date.now()+t.expires_in*1e3-300*1e3}}var gl={id:"anthropic",name:"Anthropic (Claude Pro/Max)",usesCallbackServer:!0,async login(i){return fm({onAuth:i.onAuth,onPrompt:i.onPrompt,onProgress:i.onProgress,onManualCodeInput:i.onManualCodeInput})},async refreshToken(i){return xm(i.refresh)},getApiKey(i){return i.access}};Ze();var Ny=i=>atob(i),bm=Ny("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),vm={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},Gy=1.2,Ky=1.4;function fl(i){let e=i.trim();if(!e)return null;try{return(e.includes("://")?new URL(e):new URL(`https://${e}`)).hostname}catch{return null}}function xl(i){return{deviceCodeUrl:`https://${i}/login/device/code`,accessTokenUrl:`https://${i}/login/oauth/access_token`,copilotTokenUrl:`https://api.${i}/copilot_internal/v2/token`}}function zy(i){let e=i.match(/proxy-ep=([^;]+)/);return e?`https://${e[1].replace(/^proxy\./,"api.")}`:null}function bl(i,e){if(i){let t=zy(i);if(t)return t}return e?`https://copilot-api.${e}`:"https://api.individual.githubcopilot.com"}async function vl(i,e){let t=await fetch(i,e);if(!t.ok){let n=await t.text();throw new Error(`${t.status} ${t.statusText}: ${n}`)}return t.json()}async function Hy(i){let e=xl(i),t=await vl(e.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:bm,scope:"read:user"})});if(!t||typeof t!="object")throw new Error("Invalid device code response");let n=t.device_code,s=t.user_code,o=t.verification_uri,r=t.interval,a=t.expires_in;if(typeof n!="string"||typeof s!="string"||typeof o!="string"||typeof r!="number"||typeof a!="number")throw new Error("Invalid device code response fields");return{device_code:n,user_code:s,verification_uri:o,interval:r,expires_in:a}}function jy(i,e){return new Promise((t,n)=>{if(e?.aborted){n(new Error("Login cancelled"));return}let s=setTimeout(t,i);e?.addEventListener("abort",()=>{clearTimeout(s),n(new Error("Login cancelled"))},{once:!0})})}async function qy(i,e,t,n,s){let o=xl(i),r=Date.now()+n*1e3,a=Math.max(1e3,Math.floor(t*1e3)),l=Gy,c=0;for(;Date.now()<r;){if(s?.aborted)throw new Error("Login cancelled");let d=r-Date.now(),p=Math.min(Math.ceil(a*l),d);await jy(p,s);let u=await vl(o.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:bm,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(u&&typeof u=="object"&&typeof u.access_token=="string")return u.access_token;if(u&&typeof u=="object"&&typeof u.error=="string"){let{error:h,error_description:m,interval:g}=u;if(h==="authorization_pending")continue;if(h==="slow_down"){c+=1,a=typeof g=="number"&&g>0?g*1e3:Math.max(1e3,a+5e3),l=Ky;continue}let x=m?`: ${m}`:"";throw new Error(`Device flow failed: ${h}${x}`)}}throw c>0?new Error("Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again."):new Error("Device flow timed out")}async function yl(i,e){let n=xl(e||"github.com"),s=await vl(n.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${i}`,...vm}});if(!s||typeof s!="object")throw new Error("Invalid Copilot token response");let o=s.token,r=s.expires_at;if(typeof o!="string"||typeof r!="number")throw new Error("Invalid Copilot token response fields");return{refresh:i,access:o,expires:r*1e3-300*1e3,enterpriseUrl:e}}async function Vy(i,e,t){let s=`${bl(i,t)}/models/${e}/policy`;try{return(await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`,...vm,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})})).ok}catch{return!1}}async function Qy(i,e,t){let n=Ea("github-copilot");await Promise.all(n.map(async s=>{let o=await Vy(i,s.id,e);t?.(s.id,o)}))}async function ym(i){let e=await i.onPrompt({message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com",allowEmpty:!0});if(i.signal?.aborted)throw new Error("Login cancelled");let t=e.trim(),n=fl(e);if(t&&!n)throw new Error("Invalid GitHub Enterprise URL/domain");let s=n||"github.com",o=await Hy(s);i.onAuth(o.verification_uri,`Enter code: ${o.user_code}`);let r=await qy(s,o.device_code,o.interval,o.expires_in,i.signal),a=await yl(r,n??void 0);return i.onProgress?.("Enabling models..."),await Qy(a.access,n??void 0),a}var wl={id:"github-copilot",name:"GitHub Copilot",async login(i){return ym({onAuth:(e,t)=>i.onAuth({url:e,instructions:t}),onPrompt:i.onPrompt,onProgress:i.onProgress,signal:i.signal})},async refreshToken(i){let e=i;return yl(e.refresh,e.enterpriseUrl)},getApiKey(i){return i.access},modifyModels(i,e){let t=e,n=t.enterpriseUrl?fl(t.enterpriseUrl)??void 0:void 0,s=bl(t.access,n);return i.map(o=>o.provider==="github-copilot"?{...o,baseUrl:s}:o)}};var Sl=null,Tl=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(import("node:crypto").then(i=>{Sl=i.randomBytes}),import("node:http").then(i=>{Tl=i}));var Jy=process.env.PI_OAUTH_CALLBACK_HOST||"127.0.0.1",Cl="app_EMoamEEZ73f0CkXaXp7hrann",Yy="https://auth.openai.com/oauth/authorize",wm="https://auth.openai.com/oauth/token",km="http://localhost:1455/auth/callback",Xy="openid profile email offline_access",Zy="https://api.openai.com/auth";function ew(){if(!Sl)throw new Error("OpenAI Codex OAuth is only available in Node.js environments");return Sl(16).toString("hex")}function kl(i){let e=i.trim();if(!e)return{};try{let t=new URL(e);return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0}}catch{}if(e.includes("#")){let[t,n]=e.split("#",2);return{code:t,state:n}}if(e.includes("code=")){let t=new URLSearchParams(e);return{code:t.get("code")??void 0,state:t.get("state")??void 0}}return{code:e}}function tw(i){try{let e=i.split(".");if(e.length!==3)return null;let t=e[1]??"",n=atob(t);return JSON.parse(n)}catch{return null}}async function nw(i,e,t=km){let n=await fetch(wm,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:Cl,code:i,code_verifier:e,redirect_uri:t})});if(!n.ok){let o=await n.text().catch(()=>"");return{type:"failed",status:n.status,message:`OpenAI Codex token exchange failed (${n.status}): ${o||n.statusText}`}}let s=await n.json();return!s.access_token||!s.refresh_token||typeof s.expires_in!="number"?{type:"failed",message:`OpenAI Codex token exchange response missing fields: ${JSON.stringify(s)}`}:{type:"success",access:s.access_token,refresh:s.refresh_token,expires:Date.now()+s.expires_in*1e3}}async function iw(i){try{let e=await fetch(wm,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:i,client_id:Cl})});if(!e.ok){let n=await e.text().catch(()=>"");return{type:"failed",status:e.status,message:`OpenAI Codex token refresh failed (${e.status}): ${n||e.statusText}`}}let t=await e.json();return!t.access_token||!t.refresh_token||typeof t.expires_in!="number"?{type:"failed",message:`OpenAI Codex token refresh response missing fields: ${JSON.stringify(t)}`}:{type:"success",access:t.access_token,refresh:t.refresh_token,expires:Date.now()+t.expires_in*1e3}}catch(e){return{type:"failed",message:`OpenAI Codex token refresh error: ${e instanceof Error?e.message:String(e)}`}}}async function sw(i="pi"){let{verifier:e,challenge:t}=await Zo(),n=ew(),s=new URL(Yy);return s.searchParams.set("response_type","code"),s.searchParams.set("client_id",Cl),s.searchParams.set("redirect_uri",km),s.searchParams.set("scope",Xy),s.searchParams.set("code_challenge",t),s.searchParams.set("code_challenge_method","S256"),s.searchParams.set("state",n),s.searchParams.set("id_token_add_organizations","true"),s.searchParams.set("codex_cli_simplified_flow","true"),s.searchParams.set("originator",i),{verifier:e,state:n,url:s.toString()}}function ow(i){if(!Tl)throw new Error("OpenAI Codex OAuth is only available in Node.js environments");let e,t=new Promise(s=>{let o=!1;e=r=>{o||(o=!0,s(r))}}),n=Tl.createServer((s,o)=>{try{let r=new URL(s.url||"","http://localhost");if(r.pathname!=="/auth/callback"){o.statusCode=404,o.setHeader("Content-Type","text/html; charset=utf-8"),o.end(kt("Callback route not found."));return}if(r.searchParams.get("state")!==i){o.statusCode=400,o.setHeader("Content-Type","text/html; charset=utf-8"),o.end(kt("State mismatch."));return}let a=r.searchParams.get("code");if(!a){o.statusCode=400,o.setHeader("Content-Type","text/html; charset=utf-8"),o.end(kt("Missing authorization code."));return}o.statusCode=200,o.setHeader("Content-Type","text/html; charset=utf-8"),o.end(Xo("OpenAI authentication completed. You can close this window.")),e?.({code:a})}catch{o.statusCode=500,o.setHeader("Content-Type","text/html; charset=utf-8"),o.end(kt("Internal error while processing OAuth callback."))}});return new Promise(s=>{n.listen(1455,Jy,()=>{s({close:()=>n.close(),cancelWait:()=>{e?.(null)},waitForCode:()=>t})}).on("error",o=>{e?.(null),s({close:()=>{try{n.close()}catch{}},cancelWait:()=>{},waitForCode:async()=>null})})})}function Sm(i){let n=tw(i)?.[Zy]?.chatgpt_account_id;return typeof n=="string"&&n.length>0?n:null}async function Tm(i){let{verifier:e,state:t,url:n}=await sw(i.originator),s=await ow(t);i.onAuth({url:n,instructions:"A browser window should open. Complete login to finish."});let o;try{if(i.onManualCodeInput){let l,c,d=i.onManualCodeInput().then(u=>{l=u,s.cancelWait()}).catch(u=>{c=u instanceof Error?u:new Error(String(u)),s.cancelWait()}),p=await s.waitForCode();if(c)throw c;if(p?.code)o=p.code;else if(l){let u=kl(l);if(u.state&&u.state!==t)throw new Error("State mismatch");o=u.code}if(!o){if(await d,c)throw c;if(l){let u=kl(l);if(u.state&&u.state!==t)throw new Error("State mismatch");o=u.code}}}else{let l=await s.waitForCode();l?.code&&(o=l.code)}if(!o){let l=await i.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),c=kl(l);if(c.state&&c.state!==t)throw new Error("State mismatch");o=c.code}if(!o)throw new Error("Missing authorization code");let r=await nw(o,e);if(r.type!=="success")throw new Error(r.message);let a=Sm(r.access);if(!a)throw new Error("Failed to extract accountId from token");return{access:r.access,refresh:r.refresh,expires:r.expires,accountId:a}}finally{s.close()}}async function Cm(i){let e=await iw(i);if(e.type!=="success")throw new Error(e.message);let t=Sm(e.access);if(!t)throw new Error("Failed to extract accountId from token");return{access:e.access,refresh:e.refresh,expires:e.expires,accountId:t}}var Ml={id:"openai-codex",name:"ChatGPT Plus/Pro (Codex Subscription)",usesCallbackServer:!0,async login(i){return Tm({onAuth:i.onAuth,onPrompt:i.onPrompt,onProgress:i.onProgress,onManualCodeInput:i.onManualCodeInput})},async refreshToken(i){return Cm(i.refresh)},getApiKey(i){return i.access}};var rw=[gl,wl,Ml],aw=new Map(rw.map(i=>[i.id,i]));function Rl(){return Array.from(aw.values())}import{createJiti as XL}from"jiti/static";import*as ZL from"typebox";import*as e9 from"typebox/compile";import*as t9 from"typebox/value";var r9=cw(import.meta.url);function nr(i){return i.toolName==="edit"}function ir(i){return i.toolName==="write"}function Ms(i,e){return e.toolName===i}import E9 from"ignore";import{realpathSync as ww}from"node:fs";import{isAbsolute as Pm,relative as kw,resolve as El,sep as _m}from"node:path";function li(i){try{return ww(i)}catch{return i}}function sr(i){let e=i.trim();return!(e.startsWith("npm:")||e.startsWith("git:")||e.startsWith("github:")||e.startsWith("http:")||e.startsWith("https:")||e.startsWith("ssh:"))}function Lm(i,e){return Pm(i)?El(i):El(e,i)}function Il(i,e){let t=El(e),n=Lm(i,t),s=kw(t,n);return s===""||s!==".."&&!s.startsWith(`..${_m}`)&&!Pm(s)?s||".":void 0}function Wm(i,e){let t=Lm(i,e);return(Il(t,e)??t).split(_m).join("/")}import{existsSync as Pw}from"node:fs";import{spawn as _w}from"child_process";import{Type as ar}from"typebox";function Tw(i,e){let t=process.platform==="darwin"&&i.toLowerCase()==="alt"?"option":i;return e.capitalize?t.charAt(0).toUpperCase()+t.slice(1):t}function or(i,e={}){return i.split("/").map(t=>t.split("+").map(n=>Tw(n,e)).join("+")).join("/")}function Om(i,e={}){return i.length===0?"":or(i.join("/"),e)}function z(i){return Om(V().getKeys(i))}function Rs(i){return Om(V().getKeys(i),{capitalize:!0})}function N(i,e){return f.fg("dim",z(i))+f.fg("muted",` ${e}`)}function Le(i,e){return f.fg("dim",or(i))+f.fg("muted",` ${e}`)}function ci(i,e,t,n=0){if(!i)return{visualLines:[],skippedCount:0};let o=new T(i,n,0).render(t);if(o.length<=e)return{visualLines:o,skippedCount:0};let r=o.slice(-e),a=o.length-e;return{visualLines:r,skippedCount:a}}import{randomBytes as Cw}from"node:crypto";import{createWriteStream as Mw}from"node:fs";import{tmpdir as Rw}from"node:os";import{join as Ew}from"node:path";function Iw(i){let e=Cw(8).toString("hex");return Ew(Rw(),`${i}-${e}.log`)}function Al(i){return Buffer.byteLength(i,"utf-8")}var rr=class{constructor(e={}){this.decoder=new TextDecoder;this.rawChunks=[];this.tailText="";this.tailBytes=0;this.tailStartsAtLineBoundary=!0;this.totalRawBytes=0;this.totalDecodedBytes=0;this.totalLines=1;this.currentLineBytes=0;this.finished=!1;this.maxLines=e.maxLines??2e3,this.maxBytes=e.maxBytes??51200,this.maxRollingBytes=Math.max(this.maxBytes*2,1),this.tempFilePrefix=e.tempFilePrefix??"pi-output"}append(e){if(this.finished)throw new Error("Cannot append to a finished output accumulator");this.totalRawBytes+=e.length,this.appendDecodedText(this.decoder.decode(e,{stream:!0})),this.tempFileStream||this.shouldUseTempFile()?(this.ensureTempFile(),this.tempFileStream?.write(e)):e.length>0&&this.rawChunks.push(e)}finish(){this.finished||(this.finished=!0,this.appendDecodedText(this.decoder.decode()),this.shouldUseTempFile()&&this.ensureTempFile())}snapshot(e={}){let t=Mn(this.getSnapshotText(),{maxLines:this.maxLines,maxBytes:this.maxBytes}),n=this.totalLines>this.maxLines||this.totalDecodedBytes>this.maxBytes,s=n?t.truncatedBy??(this.totalDecodedBytes>this.maxBytes?"bytes":"lines"):null,o={...t,truncated:n,truncatedBy:s,totalLines:this.totalLines,totalBytes:this.totalDecodedBytes,maxLines:this.maxLines,maxBytes:this.maxBytes};return e.persistIfTruncated&&o.truncated&&this.ensureTempFile(),{content:o.content,truncation:o,fullOutputPath:this.tempFilePath}}async closeTempFile(){if(!this.tempFileStream)return;let e=this.tempFileStream;this.tempFileStream=void 0,await new Promise((t,n)=>{let s=r=>{e.off("finish",o),n(r)},o=()=>{e.off("error",s),t()};e.once("error",s),e.once("finish",o),e.end()})}getLastLineBytes(){return this.currentLineBytes}appendDecodedText(e){if(e.length===0)return;let t=Al(e);this.totalDecodedBytes+=t,this.tailText+=e,this.tailBytes+=t,this.tailBytes>this.maxRollingBytes*2&&this.trimTail();let n=0,s=-1;for(let o=e.indexOf(`
|
|
197
|
+
`);o!==-1;o=e.indexOf(`
|
|
198
|
+
`,o+1))n++,s=o;n===0?this.currentLineBytes+=t:(this.totalLines+=n,this.currentLineBytes=Al(e.slice(s+1)))}trimTail(){let e=Buffer.from(this.tailText,"utf-8");if(e.length<=this.maxRollingBytes){this.tailBytes=e.length;return}let t=e.length-this.maxRollingBytes;for(;t<e.length&&(e[t]&192)===128;)t++;this.tailStartsAtLineBoundary=t===0?this.tailStartsAtLineBoundary:e[t-1]===10,this.tailText=e.subarray(t).toString("utf-8"),this.tailBytes=Al(this.tailText)}getSnapshotText(){if(this.tailStartsAtLineBoundary)return this.tailText;let e=this.tailText.indexOf(`
|
|
199
|
+
`);return e===-1?this.tailText:this.tailText.slice(e+1)}shouldUseTempFile(){return this.totalRawBytes>this.maxBytes||this.totalDecodedBytes>this.maxBytes||this.totalLines>this.maxLines}ensureTempFile(){if(!this.tempFilePath){this.tempFilePath=Iw(this.tempFilePrefix),this.tempFileStream=Mw(this.tempFilePath);for(let e of this.rawChunks)this.tempFileStream.write(e);this.rawChunks=[]}}};import*as Um from"node:os";import Aw from"strip-ansi";function nt(i){if(typeof i!="string")return"";let e=Um.homedir();return i.startsWith(e)?`~${i.slice(e.length)}`:i}function ae(i){return typeof i=="string"?i:i==null?"":null}function Ft(i){return i.replace(/\t/g," ")}function Es(i){return i.replace(/\r/g,"")}function it(i,e){if(!i)return"";let t=i.content.filter(r=>r.type==="text"),n=i.content.filter(r=>r.type==="image"),s=t.map(r=>il(Aw(r.text||"")).replace(/\r/g,"")).join(`
|
|
200
|
+
`),o=ve();if(n.length>0&&(!o.images||!e)){let r=n.map(a=>{let l=a.mimeType??"image/unknown",c=a.data&&a.mimeType?Yi(a.data,a.mimeType)??void 0:void 0;return Nn(l,c)}).join(`
|
|
201
|
+
`);s=s?`${s}
|
|
202
|
+
${r}`:r}return s}function Be(i){return i.fg("error","[invalid arg]")}var Lw=ar.Object({command:ar.String({description:"Bash command to execute"}),timeout:ar.Optional(ar.Number({description:"Timeout in seconds (optional, no default timeout)"}))});function lr(i){return{exec:(e,t,{onData:n,signal:s,timeout:o,env:r})=>new Promise((a,l)=>{let{shell:c,args:d}=Ho(i?.shellPath);if(!Pw(t)){l(new Error(`Working directory does not exist: ${t}
|
|
203
|
+
Cannot execute bash commands.`));return}let p=_w(c,[...d,e],{cwd:t,detached:process.platform!=="win32",env:r??nl(),stdio:["ignore","pipe","pipe"]});p.pid&&tm(p.pid);let u=!1,h;o!==void 0&&o>0&&(h=setTimeout(()=>{u=!0,p.pid&&jo(p.pid)},o*1e3)),p.stdout?.on("data",n),p.stderr?.on("data",n);let m=()=>{p.pid&&jo(p.pid)};s&&(s.aborted?m():s.addEventListener("abort",m,{once:!0})),fa(p).then(g=>{if(p.pid&&sl(p.pid),h&&clearTimeout(h),s&&s.removeEventListener("abort",m),s?.aborted){l(new Error("aborted"));return}if(u){l(new Error(`timeout:${o}`));return}a({exitCode:g})}).catch(g=>{p.pid&&sl(p.pid),h&&clearTimeout(h),s&&s.removeEventListener("abort",m),l(g)})})}}function Ww(i,e,t){let n={command:i,cwd:e,env:{...nl()}};return t?t(n):n}var Ow=5,Uw=100,Pl=class extends L{constructor(){super(...arguments);this.state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}};function Dw(i){return`${(i/1e3).toFixed(1)}s`}function Fw(i){let e=ae(i?.command),t=i?.timeout,n=t?f.fg("muted",` (timeout ${t}s)`):"",s=e===null?Be(f):e||f.fg("toolOutput","...");return f.fg("toolTitle",f.bold(`$ ${s}`))+n}function $w(i,e,t,n,s,o){let r=i.state;i.clear();let a=it(e,n).trim();if(a){let d=a.split(`
|
|
204
|
+
`).map(p=>f.fg("toolOutput",p)).join(`
|
|
205
|
+
`);t.expanded?i.addChild(new T(`
|
|
206
|
+
${d}`,0,0)):i.addChild({render:p=>{if(r.cachedLines===void 0||r.cachedWidth!==p){let u=ci(d,Ow,p);r.cachedLines=u.visualLines,r.cachedSkipped=u.skippedCount,r.cachedWidth=p}if(r.cachedSkipped&&r.cachedSkipped>0){let u=f.fg("muted",`... (${r.cachedSkipped} earlier lines,`)+` ${N("app.tools.expand","to expand")})`;return["",G(u,p,"..."),...r.cachedLines??[]]}return["",...r.cachedLines??[]]},invalidate:()=>{r.cachedWidth=void 0,r.cachedLines=void 0,r.cachedSkipped=void 0}})}let l=e.details?.truncation,c=e.details?.fullOutputPath;if(l?.truncated||c){let d=[];c&&d.push(`Full output: ${c}`),l?.truncated&&(l.truncatedBy==="lines"?d.push(`Truncated: showing ${l.outputLines} of ${l.totalLines} lines`):d.push(`Truncated: ${l.outputLines} lines shown (${re(l.maxBytes??51200)} limit)`)),i.addChild(new T(`
|
|
207
|
+
${f.fg("warning",`[${d.join(". ")}]`)}`,0,0))}if(s!==void 0){let d=t.isPartial?"Elapsed":"Took",p=o??Date.now();i.addChild(new T(`
|
|
208
|
+
${f.fg("muted",`${d} ${Dw(p-s)}`)}`,0,0))}}function cr(i,e){let t=e?.operations??lr({shellPath:e?.shellPath}),n=e?.commandPrefix,s=e?.spawnHook;return{name:"bash",label:"bash",description:`Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${2e3} lines or ${51200/1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,promptSnippet:"Execute bash commands (ls, grep, find, etc.)",parameters:Lw,async execute(o,{command:r,timeout:a},l,c,d){let p=n?`${n}
|
|
209
|
+
${r}`:r,u=Ww(p,i,s),h=new rr({tempFilePrefix:"pi-bash"}),m,g=!1,x=0,b=()=>{if(!c||!g)return;g=!1,x=Date.now();let S=h.snapshot({persistIfTruncated:!0});c({content:[{type:"text",text:S.content||""}],details:{truncation:S.truncation.truncated?S.truncation:void 0,fullOutputPath:S.fullOutputPath}})},v=()=>{m&&(clearTimeout(m),m=void 0)},w=()=>{if(!c)return;g=!0;let S=Uw-(Date.now()-x);if(S<=0){v(),b();return}m??=setTimeout(()=>{m=void 0,b()},S)};c&&c({content:[],details:void 0});let C=S=>{h.append(S),w()},R=async()=>{h.finish(),v(),b();let S=h.snapshot({persistIfTruncated:!0});return await h.closeTempFile(),S},k=(S,I="(no output)")=>{let P=S.truncation,M=S.content||I,_;if(P.truncated){_={truncation:P,fullOutputPath:S.fullOutputPath};let U=P.totalLines-P.outputLines+1,F=P.totalLines;if(P.lastLinePartial){let $=re(h.getLastLineBytes());M+=`
|
|
210
|
+
|
|
211
|
+
[Showing last ${re(P.outputBytes)} of line ${F} (line is ${$}). Full output: ${S.fullOutputPath}]`}else P.truncatedBy==="lines"?M+=`
|
|
212
|
+
|
|
213
|
+
[Showing lines ${U}-${F} of ${P.totalLines}. Full output: ${S.fullOutputPath}]`:M+=`
|
|
214
|
+
|
|
215
|
+
[Showing lines ${U}-${F} of ${P.totalLines} (${re(51200)} limit). Full output: ${S.fullOutputPath}]`}return{text:M,details:_}},A=(S,I)=>`${S?`${S}
|
|
216
|
+
|
|
217
|
+
`:""}${I}`;try{let S;try{S=(await t.exec(u.command,u.cwd,{onData:C,signal:l,timeout:a,env:u.env})).exitCode}catch(_){let U=await R(),{text:F}=k(U,"");if(_ instanceof Error&&_.message==="aborted")throw new Error(A(F,"Command aborted"));if(_ instanceof Error&&_.message.startsWith("timeout:")){let $=_.message.split(":")[1];throw new Error(A(F,`Command timed out after ${$} seconds`))}throw _}let I=await R(),{text:P,details:M}=k(I);if(S!==0&&S!==null)throw new Error(A(P,`Command exited with code ${S}`));return{content:[{type:"text",text:P}],details:M}}finally{v()}},renderCall(o,r,a){let l=a.state;a.executionStarted&&l.startedAt===void 0&&(l.startedAt=Date.now(),l.endedAt=void 0);let c=a.lastComponent??new T("",0,0);return c.setText(Fw(o)),c},renderResult(o,r,a,l){let c=l.state;c.startedAt!==void 0&&r.isPartial&&!c.interval&&(c.interval=setInterval(()=>l.invalidate(),1e3)),(!r.isPartial||l.isError)&&(c.endedAt??=Date.now(),c.interval&&(clearInterval(c.interval),c.interval=void 0));let d=l.lastComponent??new Pl;return $w(d,o,r,l.showImages,c.startedAt,c.endedAt),d.invalidate(),d}}}import{constants as zm}from"fs";import{access as ck,readFile as pk,writeFile as dk}from"fs/promises";import{Type as di}from"typebox";import*as Dm from"diff";function _l(i){let e=i.match(/^([+-\s])(\s*\d*)\s(.*)$/);return e?{prefix:e[1],lineNum:e[2],content:e[3]}:null}function pi(i){return i.replace(/\t/g," ")}function Bw(i,e){let t=Dm.diffWords(i,e),n="",s="",o=!0,r=!0;for(let a of t)if(a.removed){let l=a.value;if(o){let c=l.match(/^(\s*)/)?.[1]||"";l=l.slice(c.length),n+=c,o=!1}l&&(n+=f.inverse(l))}else if(a.added){let l=a.value;if(r){let c=l.match(/^(\s*)/)?.[1]||"";l=l.slice(c.length),s+=c,r=!1}l&&(s+=f.inverse(l))}else n+=a.value,s+=a.value;return{removedLine:n,addedLine:s}}function Is(i,e={}){let t=i.split(`
|
|
218
|
+
`),n=[],s=0;for(;s<t.length;){let o=t[s],r=_l(o);if(!r){n.push(f.fg("toolDiffContext",o)),s++;continue}if(r.prefix==="-"){let a=[];for(;s<t.length;){let c=_l(t[s]);if(!c||c.prefix!=="-")break;a.push({lineNum:c.lineNum,content:c.content}),s++}let l=[];for(;s<t.length;){let c=_l(t[s]);if(!c||c.prefix!=="+")break;l.push({lineNum:c.lineNum,content:c.content}),s++}if(a.length===1&&l.length===1){let c=a[0],d=l[0],{removedLine:p,addedLine:u}=Bw(pi(c.content),pi(d.content));n.push(f.fg("toolDiffRemoved",`-${c.lineNum} ${p}`)),n.push(f.fg("toolDiffAdded",`+${d.lineNum} ${u}`))}else{for(let c of a)n.push(f.fg("toolDiffRemoved",`-${c.lineNum} ${pi(c.content)}`));for(let c of l)n.push(f.fg("toolDiffAdded",`+${c.lineNum} ${pi(c.content)}`))}}else r.prefix==="+"?(n.push(f.fg("toolDiffAdded",`+${r.lineNum} ${pi(r.content)}`)),s++):(n.push(f.fg("toolDiffContext",` ${r.lineNum} ${pi(r.content)}`)),s++)}return n.join(`
|
|
219
|
+
`)}import*as Bm from"diff";import{constants as Xw}from"fs";import{access as Zw,readFile as ek}from"fs/promises";import{accessSync as Nw,constants as Gw}from"node:fs";import*as Ll from"node:os";import{isAbsolute as Kw,resolve as zw}from"node:path";var Hw=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g,jw="\u202F";function qw(i){return i.replace(Hw," ")}function Vw(i){return i.replace(/ (AM|PM)\./gi,`${jw}$1.`)}function Qw(i){return i.normalize("NFD")}function Fm(i){return i.replace(/'/g,"\u2019")}function As(i){try{return Nw(i,Gw.F_OK),!0}catch{return!1}}function Jw(i){return i.startsWith("@")?i.slice(1):i}function Yw(i){let e=qw(Jw(i));return e==="~"?Ll.homedir():e.startsWith("~/")?Ll.homedir()+e.slice(1):e}function qe(i,e){let t=Yw(i);return Kw(t)?t:zw(e,t)}function pr(i,e){let t=qe(i,e);if(As(t))return t;let n=Vw(t);if(n!==t&&As(n))return n;let s=Qw(t);if(s!==t&&As(s))return s;let o=Fm(t);if(o!==t&&As(o))return o;let r=Fm(s);return r!==t&&As(r)?r:t}function Nm(i){let e=i.indexOf(`\r
|
|
220
|
+
`),t=i.indexOf(`
|
|
221
|
+
`);return t===-1||e===-1?`
|
|
222
|
+
`:e<t?`\r
|
|
223
|
+
`:`
|
|
224
|
+
`}function Ps(i){return i.replace(/\r\n/g,`
|
|
225
|
+
`).replace(/\r/g,`
|
|
226
|
+
`)}function Gm(i,e){return e===`\r
|
|
227
|
+
`?i.replace(/\n/g,`\r
|
|
228
|
+
`):i}function _s(i){return i.normalize("NFKC").split(`
|
|
229
|
+
`).map(e=>e.trimEnd()).join(`
|
|
230
|
+
`).replace(/[\u2018\u2019\u201A\u201B]/g,"'").replace(/[\u201C\u201D\u201E\u201F]/g,'"').replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g,"-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g," ")}function $m(i,e){let t=i.indexOf(e);if(t!==-1)return{found:!0,index:t,matchLength:e.length,usedFuzzyMatch:!1,contentForReplacement:i};let n=_s(i),s=_s(e),o=n.indexOf(s);return o===-1?{found:!1,index:-1,matchLength:0,usedFuzzyMatch:!1,contentForReplacement:i}:{found:!0,index:o,matchLength:s.length,usedFuzzyMatch:!0,contentForReplacement:n}}function Wl(i){return i.startsWith("\uFEFF")?{bom:"\uFEFF",text:i.slice(1)}:{bom:"",text:i}}function tk(i,e){let t=_s(i),n=_s(e);return t.split(n).length-1}function nk(i,e,t){return t===1?new Error(`Could not find the exact text in ${i}. The old text must match exactly including all whitespace and newlines.`):new Error(`Could not find edits[${e}] in ${i}. The oldText must match exactly including all whitespace and newlines.`)}function ik(i,e,t,n){return t===1?new Error(`Found ${n} occurrences of the text in ${i}. The text must be unique. Please provide more context to make it unique.`):new Error(`Found ${n} occurrences of edits[${e}] in ${i}. Each oldText must be unique. Please provide more context to make it unique.`)}function sk(i,e,t){return t===1?new Error(`oldText must not be empty in ${i}.`):new Error(`edits[${e}].oldText must not be empty in ${i}.`)}function ok(i,e){return e===1?new Error(`No changes made to ${i}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`):new Error(`No changes made to ${i}. The replacements produced identical content.`)}function Ol(i,e,t){let n=e.map(l=>({oldText:Ps(l.oldText),newText:Ps(l.newText)}));for(let l=0;l<n.length;l++)if(n[l].oldText.length===0)throw sk(t,l,n.length);let o=n.map(l=>$m(i,l.oldText)).some(l=>l.usedFuzzyMatch)?_s(i):i,r=[];for(let l=0;l<n.length;l++){let c=n[l],d=$m(o,c.oldText);if(!d.found)throw nk(t,l,n.length);let p=tk(o,c.oldText);if(p>1)throw ik(t,l,n.length,p);r.push({editIndex:l,matchIndex:d.index,matchLength:d.matchLength,newText:c.newText})}r.sort((l,c)=>l.matchIndex-c.matchIndex);for(let l=1;l<r.length;l++){let c=r[l-1],d=r[l];if(c.matchIndex+c.matchLength>d.matchIndex)throw new Error(`edits[${c.editIndex}] and edits[${d.editIndex}] overlap in ${t}. Merge them into one edit or target disjoint regions.`)}let a=o;for(let l=r.length-1;l>=0;l--){let c=r[l];a=a.substring(0,c.matchIndex)+c.newText+a.substring(c.matchIndex+c.matchLength)}if(o===a)throw ok(t,n.length);return{baseContent:o,newContent:a}}function Ul(i,e,t=4){let n=Bm.diffLines(i,e),s=[],o=i.split(`
|
|
231
|
+
`),r=e.split(`
|
|
232
|
+
`),a=Math.max(o.length,r.length),l=String(a).length,c=1,d=1,p=!1,u;for(let h=0;h<n.length;h++){let m=n[h],g=m.value.split(`
|
|
233
|
+
`);if(g[g.length-1]===""&&g.pop(),m.added||m.removed){u===void 0&&(u=d);for(let x of g)if(m.added){let b=String(d).padStart(l," ");s.push(`+${b} ${x}`),d++}else{let b=String(c).padStart(l," ");s.push(`-${b} ${x}`),c++}p=!0}else{let x=h<n.length-1&&(n[h+1].added||n[h+1].removed),b=p,v=x;if(b&&v)if(g.length<=t*2)for(let w of g){let C=String(c).padStart(l," ");s.push(` ${C} ${w}`),c++,d++}else{let w=g.slice(0,t),C=g.slice(g.length-t),R=g.length-w.length-C.length;for(let k of w){let A=String(c).padStart(l," ");s.push(` ${A} ${k}`),c++,d++}s.push(` ${"".padStart(l," ")} ...`),c+=R,d+=R;for(let k of C){let A=String(c).padStart(l," ");s.push(` ${A} ${k}`),c++,d++}}else if(b){let w=g.slice(0,t),C=g.length-w.length;for(let R of w){let k=String(c).padStart(l," ");s.push(` ${k} ${R}`),c++,d++}C>0&&(s.push(` ${"".padStart(l," ")} ...`),c+=C,d+=C)}else if(v){let w=Math.max(0,g.length-t);w>0&&(s.push(` ${"".padStart(l," ")} ...`),c+=w,d+=w);for(let C of g.slice(w)){let R=String(c).padStart(l," ");s.push(` ${R} ${C}`),c++,d++}}else c+=g.length,d+=g.length;p=!1}}return{diff:s.join(`
|
|
234
|
+
`),firstChangedLine:u}}async function Km(i,e,t){let n=qe(i,t);try{try{await Zw(n,Xw.R_OK)}catch(c){let d=c instanceof Error&&"code"in c?`Error code: ${c.code}`:String(c);return{error:`Could not edit file: ${i}. ${d}.`}}let s=await ek(n,"utf-8"),{text:o}=Wl(s),r=Ps(o),{baseContent:a,newContent:l}=Ol(r,e,i);return Ul(a,l)}catch(s){return{error:s instanceof Error?s.message:String(s)}}}import{realpathSync as rk}from"node:fs";import{resolve as ak}from"node:path";var dr=new Map;function lk(i){let e=ak(i);try{return rk.native(e)}catch{return e}}async function In(i,e){let t=lk(i),n=dr.get(t)??Promise.resolve(),s,o=new Promise(a=>{s=a}),r=n.then(()=>o);dr.set(t,r),await n;try{return await e()}finally{s(),dr.get(t)===r&&dr.delete(t)}}var uk=di.Object({oldText:di.String({description:"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."}),newText:di.String({description:"Replacement text for this targeted edit."})},{additionalProperties:!1}),mk=di.Object({path:di.String({description:"Path to the file to edit (relative or absolute)"}),edits:di.Array(uk,{description:"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."})},{additionalProperties:!1}),hk={readFile:i=>pk(i),writeFile:(i,e)=>dk(i,e,"utf-8"),access:i=>ck(i,zm.R_OK|zm.W_OK)};function gk(i){if(!i||typeof i!="object")return i;let e=i;if(typeof e.edits=="string")try{let a=JSON.parse(e.edits);Array.isArray(a)&&(e.edits=a)}catch{}let t=e;if(typeof t.oldText!="string"||typeof t.newText!="string")return e;let n=Array.isArray(t.edits)?[...t.edits]:[];n.push({oldText:t.oldText,newText:t.newText});let{oldText:s,newText:o,...r}=t;return{...r,edits:n}}function fk(i){if(!Array.isArray(i.edits)||i.edits.length===0)throw new Error("Edit tool input is invalid. edits must contain at least one replacement.");return{path:i.path,edits:i.edits}}function xk(){return Object.assign(new he(1,1,i=>i),{preview:void 0,previewArgsKey:void 0,previewPending:!1,settledError:!1})}function bk(i,e){if(e instanceof he){let n=e;return i.callComponent=n,n}if(i.callComponent)return i.callComponent;let t=xk();return i.callComponent=t,t}function Hm(i){if(!i)return null;let e=typeof i.path=="string"?i.path:typeof i.file_path=="string"?i.file_path:null;return e?Array.isArray(i.edits)&&i.edits.length>0&&i.edits.every(t=>typeof t?.oldText=="string"&&typeof t?.newText=="string")?{path:e,edits:i.edits}:typeof i.oldText=="string"&&typeof i.newText=="string"?{path:e,edits:[{oldText:i.oldText,newText:i.newText}]}:null:null}function vk(i,e){let t=Be(e),n=ae(i?.file_path??i?.path),s=n!==null?nt(n):null,o=s===null?t:s?e.fg("accent",s):e.fg("toolOutput","...");return`${e.fg("toolTitle",e.bold("edit"))} ${o}`}function yk(i,e,t,n,s){let o=ae(i?.file_path??i?.path),r=e&&!("error"in e)?e.diff:void 0,a=e&&"error"in e?e.error:void 0;if(s){let c=t.content.filter(d=>d.type==="text").map(d=>d.text||"").join(`
|
|
235
|
+
`);return!c||c===a?void 0:n.fg("error",c)}let l=t.details?.diff;if(l&&l!==r)return Is(l,{filePath:o??void 0})}function wk(i,e,t){return i?"error"in i?n=>t.bg("toolErrorBg",n):n=>t.bg("toolSuccessBg",n):e?n=>t.bg("toolErrorBg",n):n=>t.bg("toolPendingBg",n)}function jm(i,e,t){if(i.setBgFn(wk(i.preview,i.settledError,t)),i.clear(),i.addChild(new T(vk(e,t),0,0)),!i.preview)return i;let n="error"in i.preview?t.fg("error",i.preview.error):Is(i.preview.diff);return i.addChild(new E(1)),i.addChild(new T(n,0,0)),i}function qm(i,e,t){let n=i.preview,s=n===void 0||("error"in n&&"error"in e?n.error!==e.error:"error"in n!="error"in e)||!("error"in n)&&!("error"in e)&&(n.diff!==e.diff||n.firstChangedLine!==e.firstChangedLine);return i.preview=e,i.previewArgsKey=t,i.previewPending=!1,s}function ur(i,e){let t=e?.operations??hk;return{name:"edit",label:"edit",description:"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.",promptSnippet:"Make precise file edits with exact text replacement, including multiple disjoint edits in one call",promptGuidelines:["Use edit for precise changes (edits[].oldText must match exactly)","When changing multiple separate locations in one file, use one edit call with multiple entries in edits[] instead of multiple edit calls","Each edits[].oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits. Merge nearby changes into one edit.","Keep edits[].oldText as small as possible while still being unique in the file. Do not pad with large unchanged regions."],parameters:mk,renderShell:"self",prepareArguments:gk,async execute(n,s,o,r,a){let{path:l,edits:c}=fk(s),d=qe(l,i);return In(d,()=>new Promise((p,u)=>{if(o?.aborted){u(new Error("Operation aborted"));return}let h=!1,m=()=>{h=!0,u(new Error("Operation aborted"))};o&&o.addEventListener("abort",m,{once:!0}),(async()=>{try{try{await t.access(d)}catch(I){let P=I instanceof Error&&"code"in I?`Error code: ${I.code}`:String(I);o&&o.removeEventListener("abort",m),u(new Error(`Could not edit file: ${l}. ${P}.`));return}if(h)return;let x=(await t.readFile(d)).toString("utf-8");if(h)return;let{bom:b,text:v}=Wl(x),w=Nm(v),C=Ps(v),{baseContent:R,newContent:k}=Ol(C,c,l);if(h)return;let A=b+Gm(k,w);if(await t.writeFile(d,A),h)return;o&&o.removeEventListener("abort",m);let S=Ul(R,k);p({content:[{type:"text",text:`Successfully replaced ${c.length} block(s) in ${l}.`}],details:{diff:S.diff,firstChangedLine:S.firstChangedLine}})}catch(g){o&&o.removeEventListener("abort",m),h||u(g instanceof Error?g:new Error(String(g)))}})()}))},renderCall(n,s,o){let r=bk(o.state,o.lastComponent),a=Hm(n),l=a?JSON.stringify({path:a.path,edits:a.edits}):void 0;if(r.previewArgsKey!==l&&(r.preview=void 0,r.previewArgsKey=l,r.previewPending=!1,r.settledError=!1),o.argsComplete&&a&&!r.preview&&!r.previewPending){r.previewPending=!0;let c=l;Km(a.path,a.edits,o.cwd).then(d=>{r.previewArgsKey===c&&(qm(r,d,c),o.invalidate())})}return jm(r,n,s)},renderResult(n,s,o,r){let a=r.state.callComponent,l=Hm(r.args),c=l?JSON.stringify({path:l.path,edits:l.edits}):void 0,d=n,p=r.isError?void 0:d.details?.diff,u=!1;a&&(typeof p=="string"&&(u=qm(a,{diff:p,firstChangedLine:d.details?.firstChangedLine},c)||u),a.settledError!==r.isError&&(a.settledError=r.isError,u=!0),u&&jm(a,r.args,o));let h=yk(r.args,a?.preview,d,o,r.isError),m=r.lastComponent??new L;return m.clear(),h&&(m.addChild(new E(1)),m.addChild(new T(h,1,0))),m}}}import{createInterface as Bk}from"node:readline";import{spawn as Nk}from"child_process";import{existsSync as Gk}from"fs";import Bl from"path";import{Type as ui}from"typebox";import Ls from"chalk";import{spawnSync as Jm}from"child_process";import kk from"extract-zip";import{chmodSync as Sk,createWriteStream as Tk,existsSync as Ym,mkdirSync as Vm,readdirSync as Ck,renameSync as Mk,rmSync as Qm}from"fs";import{arch as Rk,platform as Dl}from"os";import{join as Xt}from"path";import{Readable as Ek}from"stream";import{pipeline as Ik}from"stream/promises";var Ws=rs(),Ak=1e4,Pk=12e4;function _k(){let i=process.env.PI_OFFLINE;return i?i==="1"||i.toLowerCase()==="true"||i.toLowerCase()==="yes":!1}var Fl={fd:{name:"fd",repo:"sharkdp/fd",binaryName:"fd",systemBinaryNames:["fd","fdfind"],tagPrefix:"v",getAssetName:(i,e,t)=>e==="darwin"?`fd-v${i}-${t==="arm64"?"aarch64":"x86_64"}-apple-darwin.tar.gz`:e==="linux"?`fd-v${i}-${t==="arm64"?"aarch64":"x86_64"}-unknown-linux-gnu.tar.gz`:e==="win32"?`fd-v${i}-${t==="arm64"?"aarch64":"x86_64"}-pc-windows-msvc.zip`:null},rg:{name:"ripgrep",repo:"BurntSushi/ripgrep",binaryName:"rg",tagPrefix:"",getAssetName:(i,e,t)=>e==="darwin"?`ripgrep-${i}-${t==="arm64"?"aarch64":"x86_64"}-apple-darwin.tar.gz`:e==="linux"?t==="arm64"?`ripgrep-${i}-aarch64-unknown-linux-gnu.tar.gz`:`ripgrep-${i}-x86_64-unknown-linux-musl.tar.gz`:e==="win32"?`ripgrep-${i}-${t==="arm64"?"aarch64":"x86_64"}-pc-windows-msvc.zip`:null}};function Lk(i){try{let e=Jm(i,["--version"],{stdio:"pipe"});return e.error===void 0||e.error===null}catch{return!1}}function Wk(i){let e=Fl[i];if(!e)return null;let t=Xt(Ws,e.binaryName+(Dl()==="win32"?".exe":""));if(Ym(t))return t;let n=e.systemBinaryNames??[e.binaryName];for(let s of n)if(Lk(s))return s;return null}async function Ok(i){let e=await fetch(`https://api.github.com/repos/${i}/releases/latest`,{headers:{"User-Agent":`${Ae}-coding-agent`},signal:AbortSignal.timeout(Ak)});if(!e.ok)throw new Error(`GitHub API error: ${e.status}`);return(await e.json()).tag_name.replace(/^v/,"")}async function Uk(i,e){let t=await fetch(i,{signal:AbortSignal.timeout(Pk)});if(!t.ok)throw new Error(`Failed to download: ${t.status}`);if(!t.body)throw new Error("No response body");let n=Tk(e);await Ik(Ek.fromWeb(t.body),n)}function Dk(i,e){let t=[i];for(;t.length>0;){let n=t.pop();if(!n)continue;let s=Ck(n,{withFileTypes:!0});for(let o of s){let r=Xt(n,o.name);if(o.isFile()&&o.name===e)return r;o.isDirectory()&&t.push(r)}}return null}async function Fk(i){let e=Fl[i];if(!e)throw new Error(`Unknown tool: ${i}`);let t=Dl(),n=Rk(),s=await Ok(e.repo),o=e.getAssetName(s,t,n);if(!o)throw new Error(`Unsupported platform: ${t}/${n}`);Vm(Ws,{recursive:!0});let r=`https://github.com/${e.repo}/releases/download/${e.tagPrefix}${s}/${o}`,a=Xt(Ws,o),l=t==="win32"?".exe":"",c=Xt(Ws,e.binaryName+l);await Uk(r,a);let d=Xt(Ws,`extract_tmp_${e.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2,10)}`);Vm(d,{recursive:!0});try{if(o.endsWith(".tar.gz")){let g=Jm("tar",["xzf",a,"-C",d],{stdio:"pipe"});if(g.error||g.status!==0){let x=g.error?.message??g.stderr?.toString().trim()??"unknown error";throw new Error(`Failed to extract ${o}: ${x}`)}}else if(o.endsWith(".zip"))await kk(a,{dir:d});else throw new Error(`Unsupported archive format: ${o}`);let p=e.binaryName+l,u=Xt(d,o.replace(/\.(tar\.gz|zip)$/,"")),m=[Xt(u,p),Xt(d,p)].find(g=>Ym(g));if(m||(m=Dk(d,p)??void 0),m)Mk(m,c);else throw new Error(`Binary not found in archive: expected ${p} under ${d}`);t!=="win32"&&Sk(c,493)}finally{Qm(a,{force:!0}),Qm(d,{recursive:!0,force:!0})}return c}var $k={fd:"fd",rg:"ripgrep"};async function An(i,e=!1){let t=Wk(i);if(t)return t;let n=Fl[i];if(n){if(_k()){e||console.log(Ls.yellow(`${n.name} not found. Offline mode enabled, skipping download.`));return}if(Dl()==="android"){let s=$k[i]??i;e||console.log(Ls.yellow(`${n.name} not found. Install with: pkg install ${s}`));return}e||console.log(Ls.dim(`${n.name} not found. Downloading...`));try{let s=await Fk(i);return e||console.log(Ls.dim(`${n.name} installed to ${s}`)),s}catch(s){e||console.log(Ls.yellow(`Failed to download ${n.name}: ${s instanceof Error?s.message:s}`));return}}}function $l(i){return i.split(Bl.sep).join("/")}var Kk=ui.Object({pattern:ui.String({description:"Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'"}),path:ui.Optional(ui.String({description:"Directory to search in (default: current directory)"})),limit:ui.Optional(ui.Number({description:"Maximum number of results (default: 1000)"}))}),Xm=1e3,zk={exists:Gk,glob:()=>[]};function Hk(i,e){let t=ae(i?.pattern),n=ae(i?.path),s=n!==null?nt(n||"."):null,o=i?.limit,r=Be(e),a=e.fg("toolTitle",e.bold("find"))+" "+(t===null?r:e.fg("accent",t||""))+e.fg("toolOutput",` in ${s===null?r:s}`);return o!==void 0&&(a+=e.fg("toolOutput",` (limit ${o})`)),a}function jk(i,e,t,n){let s=it(i,n).trim(),o="";if(s){let l=s.split(`
|
|
236
|
+
`),c=e.expanded?l.length:20,d=l.slice(0,c),p=l.length-c;o+=`
|
|
237
|
+
${d.map(u=>t.fg("toolOutput",u)).join(`
|
|
238
|
+
`)}`,p>0&&(o+=`${t.fg("muted",`
|
|
239
|
+
... (${p} more lines,`)} ${N("app.tools.expand","to expand")})`)}let r=i.details?.resultLimitReached,a=i.details?.truncation;if(r||a?.truncated){let l=[];r&&l.push(`${r} results limit`),a?.truncated&&l.push(`${re(a.maxBytes??51200)} limit`),o+=`
|
|
240
|
+
${t.fg("warning",`[Truncated: ${l.join(", ")}]`)}`}return o}function mr(i,e){let t=e?.operations;return{name:"find",label:"find",description:`Search for files by glob pattern. Returns matching file paths relative to the search directory. Respects .gitignore. Output is truncated to ${Xm} results or ${51200/1024}KB (whichever is hit first).`,promptSnippet:"Find files by glob pattern (respects .gitignore)",parameters:Kk,async execute(n,{pattern:s,path:o,limit:r},a,l,c){return new Promise((d,p)=>{if(a?.aborted){p(new Error("Operation aborted"));return}let u=!1,h,m=x=>{u||(u=!0,a?.removeEventListener("abort",g),h=void 0,x())},g=()=>{h?.(),m(()=>p(new Error("Operation aborted")))};a?.addEventListener("abort",g,{once:!0}),(async()=>{try{let x=qe(o||".",i),b=r??Xm,v=t??zk;if(t?.glob){if(!await v.exists(x)){m(()=>p(new Error(`Path not found: ${x}`)));return}if(a?.aborted){m(()=>p(new Error("Operation aborted")));return}let M=await v.glob(s,x,{ignore:["**/node_modules/**","**/.git/**"],limit:b});if(a?.aborted){m(()=>p(new Error("Operation aborted")));return}if(M.length===0){m(()=>d({content:[{type:"text",text:"No files found matching pattern"}],details:void 0}));return}let _=M.map(Se=>Se.startsWith(x)?$l(Se.slice(x.length+1)):$l(Bl.relative(x,Se))),U=_.length>=b,F=_.join(`
|
|
241
|
+
`),$=ht(F,{maxLines:Number.MAX_SAFE_INTEGER}),Q=$.content,oe={},ue=[];U&&(ue.push(`${b} results limit reached`),oe.resultLimitReached=b),$.truncated&&(ue.push(`${re(51200)} limit reached`),oe.truncation=$),ue.length>0&&(Q+=`
|
|
242
|
+
|
|
243
|
+
[${ue.join(". ")}]`),m(()=>d({content:[{type:"text",text:Q}],details:Object.keys(oe).length>0?oe:void 0}));return}let w=await An("fd",!0);if(a?.aborted){m(()=>p(new Error("Operation aborted")));return}if(!w){m(()=>p(new Error("fd is not available and could not be downloaded")));return}let C=["--glob","--color=never","--hidden","--no-require-git","--max-results",String(b)],R=s;s.includes("/")&&(C.push("--full-path"),!s.startsWith("/")&&!s.startsWith("**/")&&s!=="**"&&(R=`**/${s}`)),C.push("--",R,x);let k=Nk(w,C,{stdio:["ignore","pipe","pipe"]}),A=Bk({input:k.stdout}),S="",I=[];h=()=>{k.killed||k.kill()};let P=()=>{A.close()};k.stderr?.on("data",M=>{S+=M.toString()}),A.on("line",M=>{I.push(M)}),k.on("error",M=>{P(),m(()=>p(new Error(`Failed to run fd: ${M.message}`)))}),k.on("close",M=>{if(P(),a?.aborted){m(()=>p(new Error("Operation aborted")));return}let _=I.join(`
|
|
244
|
+
`);if(M!==0){let X=S.trim()||`fd exited with code ${M}`;if(!_){m(()=>p(new Error(X)));return}}if(!_){m(()=>d({content:[{type:"text",text:"No files found matching pattern"}],details:void 0}));return}let U=[];for(let X of I){let me=X.replace(/\r$/,"").trim();if(!me)continue;let rt=me.endsWith("/")||me.endsWith("\\"),Ee=me;me.startsWith(x)?Ee=me.slice(x.length+1):Ee=Bl.relative(x,me),rt&&!Ee.endsWith("/")&&(Ee+="/"),U.push($l(Ee))}let F=U.length>=b,$=U.join(`
|
|
245
|
+
`),Q=ht($,{maxLines:Number.MAX_SAFE_INTEGER}),oe=Q.content,ue={},Se=[];F&&(Se.push(`${b} results limit reached. Use limit=${b*2} for more, or refine pattern`),ue.resultLimitReached=b),Q.truncated&&(Se.push(`${re(51200)} limit reached`),ue.truncation=Q),Se.length>0&&(oe+=`
|
|
246
|
+
|
|
247
|
+
[${Se.join(". ")}]`),m(()=>d({content:[{type:"text",text:oe}],details:Object.keys(ue).length>0?ue:void 0}))})}catch(x){if(a?.aborted){m(()=>p(new Error("Operation aborted")));return}let b=x instanceof Error?x:new Error(String(x));m(()=>p(b))}})()})},renderCall(n,s,o){let r=o.lastComponent??new T("",0,0);return r.setText(Hk(n,s)),r},renderResult(n,s,o,r){let a=r.lastComponent??new T("",0,0);return a.setText(jk(n,s,o,r.showImages)),a}}}import{createInterface as qk}from"node:readline";import{spawn as Vk}from"child_process";import{readFileSync as Qk,statSync as Jk}from"fs";import eh from"path";import{Type as Ne}from"typebox";var Yk=Ne.Object({pattern:Ne.String({description:"Search pattern (regex or literal string)"}),path:Ne.Optional(Ne.String({description:"Directory or file to search (default: current directory)"})),glob:Ne.Optional(Ne.String({description:"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'"})),ignoreCase:Ne.Optional(Ne.Boolean({description:"Case-insensitive search (default: false)"})),literal:Ne.Optional(Ne.Boolean({description:"Treat pattern as literal string instead of regex (default: false)"})),context:Ne.Optional(Ne.Number({description:"Number of lines to show before and after each match (default: 0)"})),limit:Ne.Optional(Ne.Number({description:"Maximum number of matches to return (default: 100)"}))}),th=100,Xk={isDirectory:i=>Jk(i).isDirectory(),readFile:i=>Qk(i,"utf-8")};function Zk(i,e){let t=ae(i?.pattern),n=ae(i?.path),s=n!==null?nt(n||"."):null,o=ae(i?.glob),r=i?.limit,a=Be(e),l=e.fg("toolTitle",e.bold("grep"))+" "+(t===null?a:e.fg("accent",`/${t||""}/`))+e.fg("toolOutput",` in ${s===null?a:s}`);return o&&(l+=e.fg("toolOutput",` (${o})`)),r!==void 0&&(l+=e.fg("toolOutput",` limit ${r}`)),l}function eS(i,e,t,n){let s=it(i,n).trim(),o="";if(s){let c=s.split(`
|
|
248
|
+
`),d=e.expanded?c.length:15,p=c.slice(0,d),u=c.length-d;o+=`
|
|
249
|
+
${p.map(h=>t.fg("toolOutput",h)).join(`
|
|
250
|
+
`)}`,u>0&&(o+=`${t.fg("muted",`
|
|
251
|
+
... (${u} more lines,`)} ${N("app.tools.expand","to expand")})`)}let r=i.details?.matchLimitReached,a=i.details?.truncation,l=i.details?.linesTruncated;if(r||a?.truncated||l){let c=[];r&&c.push(`${r} matches limit`),a?.truncated&&c.push(`${re(a.maxBytes??51200)} limit`),l&&c.push("some lines truncated"),o+=`
|
|
252
|
+
${t.fg("warning",`[Truncated: ${c.join(", ")}]`)}`}return o}function hr(i,e){let t=e?.operations;return{name:"grep",label:"grep",description:`Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${th} matches or ${51200/1024}KB (whichever is hit first). Long lines are truncated to ${500} chars.`,promptSnippet:"Search file contents for patterns (respects .gitignore)",parameters:Yk,async execute(n,{pattern:s,path:o,glob:r,ignoreCase:a,literal:l,context:c,limit:d},p,u,h){return new Promise((m,g)=>{if(p?.aborted){g(new Error("Operation aborted"));return}let x=!1,b=v=>{x||(x=!0,v())};(async()=>{try{let v=await An("rg",!0);if(!v){b(()=>g(new Error("ripgrep (rg) is not available and could not be downloaded")));return}let w=qe(o||".",i),C=t??Xk,R;try{R=await C.isDirectory(w)}catch{b(()=>g(new Error(`Path not found: ${w}`)));return}let k=c&&c>0?c:0,A=Math.max(1,d??th),S=ie=>{if(R){let Z=eh.relative(w,ie);if(Z&&!Z.startsWith(".."))return Z.replace(/\\/g,"/")}return eh.basename(ie)},I=new Map,P=async ie=>{let Z=I.get(ie);if(!Z){try{Z=(await C.readFile(ie)).replace(/\r\n/g,`
|
|
253
|
+
`).replace(/\r/g,`
|
|
254
|
+
`).split(`
|
|
255
|
+
`)}catch{Z=[]}I.set(ie,Z)}return Z},M=["--json","--line-number","--color=never","--hidden"];a&&M.push("--ignore-case"),l&&M.push("--fixed-strings"),r&&M.push("--glob",r),M.push("--",s,w);let _=Vk(v,M,{stdio:["ignore","pipe","pipe"]}),U=qk({input:_.stdout}),F="",$=0,Q=!1,oe=!1,ue=!1,Se=!1,X=[],me=()=>{U.close(),p?.removeEventListener("abort",Ee)},rt=(ie=!1)=>{_.killed||(Se=ie,_.kill())},Ee=()=>{ue=!0,rt()};p?.addEventListener("abort",Ee,{once:!0}),_.stderr?.on("data",ie=>{F+=ie.toString()});let Fr=async(ie,Z)=>{let at=S(ie),Rt=await P(ie);if(!Rt.length)return[`${at}:${Z}: (unable to read file)`];let lt=[],rn=k>0?Math.max(1,Z-k):Z,xt=k>0?Math.min(Rt.length,Z+k):Z;for(let bt=rn;bt<=xt;bt++){let $r=(Rt[bt-1]??"").replace(/\r/g,""),Br=bt===Z,{text:Gc,wasTruncated:Ag}=Ss($r);Ag&&(oe=!0),Br?lt.push(`${at}:${bt}: ${Gc}`):lt.push(`${at}-${bt}- ${Gc}`)}return lt},Ki=[];U.on("line",ie=>{if(!ie.trim()||$>=A)return;let Z;try{Z=JSON.parse(ie)}catch{return}if(Z.type==="match"){$++;let at=Z.data?.path?.text,Rt=Z.data?.line_number,lt=Z.data?.lines?.text;at&&typeof Rt=="number"&&Ki.push({filePath:at,lineNumber:Rt,lineText:lt}),$>=A&&(Q=!0,rt(!0))}}),_.on("error",ie=>{me(),b(()=>g(new Error(`Failed to run ripgrep: ${ie.message}`)))}),_.on("close",async ie=>{if(me(),ue){b(()=>g(new Error("Operation aborted")));return}if(!Se&&ie!==0&&ie!==1){let xt=F.trim()||`ripgrep exited with code ${ie}`;b(()=>g(new Error(xt)));return}if($===0){b(()=>m({content:[{type:"text",text:"No matches found"}],details:void 0}));return}for(let xt of Ki)if(k===0&&xt.lineText!==void 0){let bt=S(xt.filePath),Nc=xt.lineText.replace(/\r\n/g,`
|
|
256
|
+
`).replace(/\r/g,"").replace(/\n$/,""),{text:$r,wasTruncated:Br}=Ss(Nc);Br&&(oe=!0),X.push(`${bt}:${xt.lineNumber}: ${$r}`)}else{let bt=await Fr(xt.filePath,xt.lineNumber);X.push(...bt)}let Z=X.join(`
|
|
257
|
+
`),at=ht(Z,{maxLines:Number.MAX_SAFE_INTEGER}),Rt=at.content,lt={},rn=[];Q&&(rn.push(`${A} matches limit reached. Use limit=${A*2} for more, or refine pattern`),lt.matchLimitReached=A),at.truncated&&(rn.push(`${re(51200)} limit reached`),lt.truncation=at),oe&&(rn.push(`Some lines truncated to ${500} chars. Use read tool to see full lines`),lt.linesTruncated=!0),rn.length>0&&(Rt+=`
|
|
258
|
+
|
|
259
|
+
[${rn.join(". ")}]`),b(()=>m({content:[{type:"text",text:Rt}],details:Object.keys(lt).length>0?lt:void 0}))})}catch(v){b(()=>g(v))}})()})},renderCall(n,s,o){let r=o.lastComponent??new T("",0,0);return r.setText(Zk(n,s)),r},renderResult(n,s,o,r){let a=r.lastComponent??new T("",0,0);return a.setText(eS(n,s,o,r.showImages)),a}}}import{existsSync as tS,readdirSync as nS,statSync as iS}from"fs";import sS from"path";import{Type as Os}from"typebox";var oS=Os.Object({path:Os.Optional(Os.String({description:"Directory to list (default: current directory)"})),limit:Os.Optional(Os.Number({description:"Maximum number of entries to return (default: 500)"}))}),nh=500,rS={exists:tS,stat:iS,readdir:nS};function aS(i,e){let t=ae(i?.path),n=t!==null?nt(t||"."):null,s=i?.limit,o=Be(e),r=`${e.fg("toolTitle",e.bold("ls"))} ${n===null?o:e.fg("accent",n)}`;return s!==void 0&&(r+=e.fg("toolOutput",` (limit ${s})`)),r}function lS(i,e,t,n){let s=it(i,n).trim(),o="";if(s){let l=s.split(`
|
|
260
|
+
`),c=e.expanded?l.length:20,d=l.slice(0,c),p=l.length-c;o+=`
|
|
261
|
+
${d.map(u=>t.fg("toolOutput",u)).join(`
|
|
262
|
+
`)}`,p>0&&(o+=`${t.fg("muted",`
|
|
263
|
+
... (${p} more lines,`)} ${N("app.tools.expand","to expand")})`)}let r=i.details?.entryLimitReached,a=i.details?.truncation;if(r||a?.truncated){let l=[];r&&l.push(`${r} entries limit`),a?.truncated&&l.push(`${re(a.maxBytes??51200)} limit`),o+=`
|
|
264
|
+
${t.fg("warning",`[Truncated: ${l.join(", ")}]`)}`}return o}function gr(i,e){let t=e?.operations??rS;return{name:"ls",label:"ls",description:`List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to ${nh} entries or ${51200/1024}KB (whichever is hit first).`,promptSnippet:"List directory contents",parameters:oS,async execute(n,{path:s,limit:o},r,a,l){return new Promise((c,d)=>{if(r?.aborted){d(new Error("Operation aborted"));return}let p=()=>d(new Error("Operation aborted"));r?.addEventListener("abort",p,{once:!0}),(async()=>{try{let u=qe(s||".",i),h=o??nh;if(!await t.exists(u)){d(new Error(`Path not found: ${u}`));return}if(!(await t.stat(u)).isDirectory()){d(new Error(`Not a directory: ${u}`));return}let g;try{g=await t.readdir(u)}catch(A){d(new Error(`Cannot read directory: ${A.message}`));return}g.sort((A,S)=>A.toLowerCase().localeCompare(S.toLowerCase()));let x=[],b=!1;for(let A of g){if(x.length>=h){b=!0;break}let S=sS.join(u,A),I="";try{(await t.stat(S)).isDirectory()&&(I="/")}catch{continue}x.push(A+I)}if(r?.removeEventListener("abort",p),x.length===0){c({content:[{type:"text",text:"(empty directory)"}],details:void 0});return}let v=x.join(`
|
|
265
|
+
`),w=ht(v,{maxLines:Number.MAX_SAFE_INTEGER}),C=w.content,R={},k=[];b&&(k.push(`${h} entries limit reached. Use limit=${h*2} for more`),R.entryLimitReached=h),w.truncated&&(k.push(`${re(51200)} limit reached`),R.truncation=w),k.length>0&&(C+=`
|
|
266
|
+
|
|
267
|
+
[${k.join(". ")}]`),c({content:[{type:"text",text:C}],details:Object.keys(R).length>0?R:void 0})}catch(u){r?.removeEventListener("abort",p),d(u)}})()})},renderCall(n,s,o){let r=o.lastComponent??new T("",0,0);return r.setText(aS(n,s)),r},renderResult(n,s,o,r){let a=r.lastComponent??new T("",0,0);return a.setText(lS(n,s,o,r.showImages)),a}}}import{basename as rh,dirname as lh,isAbsolute as TS,relative as CS,resolve as ah,sep as ch}from"node:path";import{constants as MS}from"fs";import{access as RS,readFile as ES}from"fs/promises";import{Type as xi}from"typebox";function cS(i,e){if(e+8>i.length)return 1;let n=(i[e]<<8|i[e+1])===18761,s=c=>n?i[c]|i[c+1]<<8:i[c]<<8|i[c+1],r=(c=>n?i[c]|i[c+1]<<8|i[c+2]<<16|i[c+3]<<24:(i[c]<<24|i[c+1]<<16|i[c+2]<<8|i[c+3])>>>0)(e+4),a=e+r;if(a+2>i.length)return 1;let l=s(a);for(let c=0;c<l;c++){let d=a+2+c*12;if(d+12>i.length)return 1;if(s(d)===274){let p=s(d+8);return p>=1&&p<=8?p:1}}return 1}function pS(i){let e=2;for(;e<i.length-1;){if(i[e]!==255)return-1;let t=i[e+1];if(t===255){e++;continue}if(t===225){if(e+4>=i.length)return-1;let s=e+4;return s+6>i.length||!ih(i,s)?-1:s+6}if(e+4>i.length)return-1;let n=i[e+2]<<8|i[e+3];e+=2+n}return-1}function dS(i){let e=12;for(;e+8<=i.length;){let t=String.fromCharCode(i[e],i[e+1],i[e+2],i[e+3]),n=i[e+4]|i[e+5]<<8|i[e+6]<<16|i[e+7]<<24,s=e+8;if(t==="EXIF")return s+n>i.length?-1:n>=6&&ih(i,s)?s+6:s;e=s+n+n%2}return-1}function ih(i,e){return i[e]===69&&i[e+1]===120&&i[e+2]===105&&i[e+3]===102&&i[e+4]===0&&i[e+5]===0}function uS(i){let e=-1;return i.length>=2&&i[0]===255&&i[1]===216?e=pS(i):i.length>=12&&i[0]===82&&i[1]===73&&i[2]===70&&i[3]===70&&i[8]===87&&i[9]===69&&i[10]===66&&i[11]===80&&(e=dS(i)),e===-1?1:cS(i,e)}function fr(i,e,t){let n=e.get_width(),s=e.get_height(),o=e.get_raw_pixels(),r=new Uint8Array(o.length);for(let a=0;a<s;a++)for(let l=0;l<n;l++){let c=(a*n+l)*4,d=t(l,a,n,s)*4;r[d]=o[c],r[d+1]=o[c+1],r[d+2]=o[c+2],r[d+3]=o[c+3]}return new i.PhotonImage(r,s,n)}function xr(i,e,t){let n=uS(t);if(n===1)return e;switch(n){case 2:return i.fliph(e),e;case 3:return i.fliph(e),i.flipv(e),e;case 4:return i.flipv(e),e;case 5:{let s=fr(i,e,(o,r,a,l)=>o*l+(l-1-r));return i.fliph(s),s}case 6:return fr(i,e,(s,o,r,a)=>s*a+(a-1-o));case 7:{let s=fr(i,e,(o,r,a,l)=>(a-1-o)*l+r);return i.fliph(s),s}case 8:return fr(i,e,(s,o,r,a)=>(r-1-s)*a+o);default:return e}}import{createRequire as mS}from"module";import*as gi from"path";import{fileURLToPath as hS}from"url";var gS=mS(import.meta.url),mi=gS("fs"),vr="photon_rs_bg.wasm",hi=null,br=null;function fS(i){return typeof i=="string"?i:i instanceof URL?hS(i):null}function xS(){let i=gi.dirname(process.execPath);return[gi.join(i,vr),gi.join(i,"photon",vr),gi.join(process.cwd(),vr)]}function bS(){let i=mi.readFileSync.bind(mi),e=xS(),t=mi,n=((...s)=>{let[o,r]=s;if(fS(o)?.endsWith(vr))try{return i(...s)}catch(l){let c=l;if(c?.code&&c.code!=="ENOENT")throw l;for(let d of e)if(mi.existsSync(d))return r===void 0?i(d):i(d,r);throw l}return i(...s)});try{t.readFileSync=n}catch{Object.defineProperty(mi,"readFileSync",{value:n,writable:!0,configurable:!0})}return()=>{try{t.readFileSync=i}catch{Object.defineProperty(mi,"readFileSync",{value:i,writable:!0,configurable:!0})}}}async function fi(){return hi||br||(br=(async()=>{let i=bS();try{return hi=await import("@silvia-odwyer/photon-node"),hi}catch{return hi=null,hi}finally{i()}})(),br)}var vS=4.5*1024*1024,yS={maxWidth:2e3,maxHeight:2e3,maxBytes:vS,jpegQuality:80};function sh(i,e){let t=Buffer.from(i).toString("base64");return{data:t,encodedSize:Buffer.byteLength(t,"utf-8"),mimeType:e}}async function Nl(i,e){let t={...yS,...e},n=Buffer.from(i.data,"base64"),s=Buffer.byteLength(i.data,"utf-8"),o=await fi();if(!o)return null;let r;try{let g=function(w,C,R){let k=o.resize(r,w,C,o.SamplingFilter.Lanczos3);try{let A=[sh(k.get_bytes(),"image/png")];for(let S of R)A.push(sh(k.get_bytes_jpeg(S),"image/jpeg"));return A}finally{k.free()}};var a=g;let l=new Uint8Array(n),c=o.PhotonImage.new_from_byteslice(l);r=xr(o,c,l),r!==c&&c.free();let d=r.get_width(),p=r.get_height(),u=i.mimeType?.split("/")[1]??"png";if(d<=t.maxWidth&&p<=t.maxHeight&&s<t.maxBytes)return{data:i.data,mimeType:i.mimeType??`image/${u}`,originalWidth:d,originalHeight:p,width:d,height:p,wasResized:!1};let h=d,m=p;h>t.maxWidth&&(m=Math.round(m*t.maxWidth/h),h=t.maxWidth),m>t.maxHeight&&(h=Math.round(h*t.maxHeight/m),m=t.maxHeight);let x=Array.from(new Set([t.jpegQuality,85,70,55,40])),b=h,v=m;for(;;){let w=g(b,v,x);for(let k of w)if(k.encodedSize<t.maxBytes)return{data:k.data,mimeType:k.mimeType,originalWidth:d,originalHeight:p,width:b,height:v,wasResized:!0};if(b===1&&v===1)break;let C=b===1?1:Math.max(1,Math.floor(b*.75)),R=v===1?1:Math.max(1,Math.floor(v*.75));if(C===b&&R===v)break;b=C,v=R}return null}catch{return null}finally{r&&r.free()}}function Gl(i){if(!i.wasResized)return;let e=i.originalWidth/i.width;return`[Image: original ${i.originalWidth}x${i.originalHeight}, displayed at ${i.width}x${i.height}. Multiply coordinates by ${e.toFixed(2)} to map to original image.]`}import{open as wS}from"node:fs/promises";import{fileTypeFromBuffer as kS}from"file-type";var SS=new Set(["image/jpeg","image/png","image/gif","image/webp"]),oh=4100;async function Kl(i){let e=await wS(i,"r");try{let t=Buffer.alloc(oh),{bytesRead:n}=await e.read(t,0,oh,0);if(n===0)return null;let s=await kS(t.subarray(0,n));return!s||!SS.has(s.mime)?null:s.mime}finally{await e.close()}}var IS=xi.Object({path:xi.String({description:"Path to the file to read (relative or absolute)"}),offset:xi.Optional(xi.Number({description:"Line number to start reading from (1-indexed)"})),limit:xi.Optional(xi.Number({description:"Maximum number of lines to read"}))}),AS=new Set(["AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"]),PS={readFile:i=>ES(i),access:i=>RS(i,MS.R_OK),detectImageMimeType:Kl};function zl(i,e){if(i?.offset===void 0&&i?.limit===void 0)return"";let t=i.offset??1,n=i.limit!==void 0?t+i.limit-1:"";return e.fg("warning",`:${t}${n?`-${n}`:""}`)}function _S(i,e){let t=ae(i?.file_path??i?.path),n=t!==null?nt(t):null,s=Be(e),o=n===null?s:n?e.fg("accent",n):e.fg("toolOutput","...");return`${e.fg("toolTitle",e.bold("read"))} ${o}${zl(i,e)}`}function LS(i){let e=i.length;for(;e>0&&i[e-1]==="";)e--;return i.slice(0,e)}function WS(i){if(!(!i||i.input.includes("image")))return"[Current model does not support images. The image will be omitted from this request.]"}function OS(i){return i.split(ch).join("/")}function US(i){let e=lh(ya()),t=CS(ah(e),ah(i));if(t===""||t===".."||t.startsWith(`..${ch}`)||TS(t))return;let n=OS(t);if(n==="README.md"||n.startsWith("docs/")||n.startsWith("examples/"))return{kind:"docs",label:n}}function ph(i,e){let t=ae(i?.file_path??i?.path);if(!t)return;let n=pr(t,e),s=rh(n);if(s==="SKILL.md")return{kind:"skill",label:rh(lh(n))||s};let o=US(n);if(o)return o;if(AS.has(s))return{kind:"resource",label:Wm(n,e)}}function DS(i,e,t){let n=t.fg("dim",` (${z("app.tools.expand")} to expand)`);return i.kind==="skill"?t.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m ")+t.fg("customMessageText",i.label)+zl(e,t)+n:t.fg("toolTitle",t.bold(`read ${i.kind}`))+" "+t.fg("accent",i.label)+zl(e,t)+n}function FS(i,e,t,n,s,o,r){if(!t.expanded&&!r&&ph(i,o))return"";let a=ae(i?.file_path??i?.path),l=it(e,s),c=a?Tn(a):void 0,d=c?Jt(Ft(l),c):l.split(`
|
|
268
|
+
`),p=LS(d),u=t.expanded?p.length:10,h=p.slice(0,u),m=p.length-u,g=`
|
|
269
|
+
${h.map(b=>c?Ft(b):n.fg("toolOutput",Ft(b))).join(`
|
|
270
|
+
`)}`;m>0&&(g+=`${n.fg("muted",`
|
|
271
|
+
... (${m} more lines,`)} ${N("app.tools.expand","to expand")})`);let x=e.details?.truncation;return x?.truncated&&(x.firstLineExceedsLimit?g+=`
|
|
272
|
+
${n.fg("warning",`[First line exceeds ${re(x.maxBytes??51200)} limit]`)}`:x.truncatedBy==="lines"?g+=`
|
|
273
|
+
${n.fg("warning",`[Truncated: showing ${x.outputLines} of ${x.totalLines} lines (${x.maxLines??2e3} line limit)]`)}`:g+=`
|
|
274
|
+
${n.fg("warning",`[Truncated: ${x.outputLines} lines shown (${re(x.maxBytes??51200)} limit)]`)}`),g}function yr(i,e){let t=e?.autoResizeImages??!0,n=e?.operations??PS;return{name:"read",label:"read",description:`Read the contents of a file. Supports text files and images (jpg, png, gif, webp). Images are sent as attachments. For text files, output is truncated to ${2e3} lines or ${51200/1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,promptSnippet:"Read file contents",promptGuidelines:["Use read to examine files instead of cat or sed."],parameters:IS,async execute(s,{path:o,offset:r,limit:a},l,c,d){let p=pr(o,i);return new Promise((u,h)=>{if(l?.aborted){h(new Error("Operation aborted"));return}let m=!1,g=()=>{m=!0,h(new Error("Operation aborted"))};l?.addEventListener("abort",g,{once:!0}),(async()=>{try{if(await n.access(p),m)return;let x=n.detectImageMimeType?await n.detectImageMimeType(p):void 0,b,v,w=WS(d?.model);if(x){let R=(await n.readFile(p)).toString("base64");if(t){let k=await Nl({type:"image",data:R,mimeType:x});if(k){let A=Gl(k),S=`Read image file [${k.mimeType}]`;A&&(S+=`
|
|
275
|
+
${A}`),w&&(S+=`
|
|
276
|
+
${w}`),b=[{type:"text",text:S},{type:"image",data:k.data,mimeType:k.mimeType}]}else{let A=`Read image file [${x}]
|
|
277
|
+
[Image omitted: could not be resized below the inline image size limit.]`;w&&(A+=`
|
|
278
|
+
${w}`),b=[{type:"text",text:A}]}}else{let k=`Read image file [${x}]`;w&&(k+=`
|
|
279
|
+
${w}`),b=[{type:"text",text:k},{type:"image",data:R,mimeType:x}]}}else{let k=(await n.readFile(p)).toString("utf-8").split(`
|
|
280
|
+
`),A=k.length,S=r?Math.max(0,r-1):0,I=S+1;if(S>=k.length)throw new Error(`Offset ${r} is beyond end of file (${k.length} lines total)`);let P,M;if(a!==void 0){let F=Math.min(S+a,k.length);P=k.slice(S,F).join(`
|
|
281
|
+
`),M=F-S}else P=k.slice(S).join(`
|
|
282
|
+
`);let _=ht(P),U;if(_.firstLineExceedsLimit){let F=re(Buffer.byteLength(k[S],"utf-8"));U=`[Line ${I} is ${F}, exceeds ${re(51200)} limit. Use bash: sed -n '${I}p' ${o} | head -c ${51200}]`,v={truncation:_}}else if(_.truncated){let F=I+_.outputLines-1,$=F+1;U=_.content,_.truncatedBy==="lines"?U+=`
|
|
283
|
+
|
|
284
|
+
[Showing lines ${I}-${F} of ${A}. Use offset=${$} to continue.]`:U+=`
|
|
285
|
+
|
|
286
|
+
[Showing lines ${I}-${F} of ${A} (${re(51200)} limit). Use offset=${$} to continue.]`,v={truncation:_}}else if(M!==void 0&&S+M<k.length){let F=k.length-(S+M),$=S+M+1;U=`${_.content}
|
|
287
|
+
|
|
288
|
+
[${F} more lines in file. Use offset=${$} to continue.]`}else U=_.content;b=[{type:"text",text:U}]}if(m)return;l?.removeEventListener("abort",g),u({content:b,details:v})}catch(x){l?.removeEventListener("abort",g),m||h(x)}})()})},renderCall(s,o,r){let a=r.lastComponent??new T("",0,0),l=r.expanded?void 0:ph(s,r.cwd);return a.setText(l?DS(l,s,o):_S(s,o)),a},renderResult(s,o,r,a){let l=a.lastComponent??new T("",0,0);return l.setText(FS(a.args,s,o,r,a.showImages,a.cwd,a.isError)),l}}}import{mkdir as $S,writeFile as BS}from"fs/promises";import{dirname as NS}from"path";import{Type as Hl}from"typebox";var GS=Hl.Object({path:Hl.String({description:"Path to the file to write (relative or absolute)"}),content:Hl.String({description:"Content to write to the file"})}),KS={writeFile:(i,e)=>BS(i,e,"utf-8"),mkdir:i=>$S(i,{recursive:!0}).then(()=>{})},jl=class extends T{constructor(){super("",0,0)}},zS=50;function ql(i,e){return Jt(i,e)[0]??""}function HS(i){let e=Math.min(zS,i.normalizedLines.length);if(e===0)return;let t=i.normalizedLines.slice(0,e).join(`
|
|
289
|
+
`),n=Jt(t,i.lang);for(let s=0;s<e;s++)i.highlightedLines[s]=n[s]??ql(i.normalizedLines[s]??"",i.lang)}function wr(i,e){let t=i?Tn(i):void 0;if(!t)return;let n=Es(e),s=Ft(n);return{rawPath:i,lang:t,rawContent:e,normalizedLines:s.split(`
|
|
290
|
+
`),highlightedLines:Jt(s,t)}}function jS(i,e,t){let n=e?Tn(e):void 0;if(!n)return;if(!i||i.lang!==n||i.rawPath!==e||!t.startsWith(i.rawContent))return wr(e,t);if(t.length===i.rawContent.length)return i;let s=t.slice(i.rawContent.length),o=Es(s),r=Ft(o);i.rawContent=t,i.normalizedLines.length===0&&(i.normalizedLines.push(""),i.highlightedLines.push(""));let a=r.split(`
|
|
291
|
+
`),l=i.normalizedLines.length-1;i.normalizedLines[l]+=a[0],i.highlightedLines[l]=ql(i.normalizedLines[l],i.lang);for(let c=1;c<a.length;c++)i.normalizedLines.push(a[c]),i.highlightedLines.push(ql(a[c],i.lang));return HS(i),i}function qS(i){let e=i.length;for(;e>0&&i[e-1]==="";)e--;return i.slice(0,e)}function VS(i,e,t,n){let s=ae(i?.file_path??i?.path),o=ae(i?.content),r=s!==null?nt(s):null,a=Be(t),l=`${t.fg("toolTitle",t.bold("write"))} ${r===null?a:r?t.fg("accent",r):t.fg("toolOutput","...")}`;if(o===null)l+=`
|
|
292
|
+
|
|
293
|
+
${t.fg("error","[invalid content arg - expected string]")}`;else if(o){let c=s?Tn(s):void 0,d=c?n?.highlightedLines??Jt(Ft(Es(o)),c):Es(o).split(`
|
|
294
|
+
`),p=qS(d),u=p.length,h=e.expanded?p.length:10,m=p.slice(0,h),g=p.length-h;l+=`
|
|
295
|
+
|
|
296
|
+
${m.map(x=>c?x:t.fg("toolOutput",Ft(x))).join(`
|
|
297
|
+
`)}`,g>0&&(l+=`${t.fg("muted",`
|
|
298
|
+
... (${g} more lines, ${u} total,`)} ${N("app.tools.expand","to expand")})`)}return l}function QS(i,e){if(!i.isError)return;let t=i.content.filter(n=>n.type==="text").map(n=>n.text||"").join(`
|
|
299
|
+
`);if(t)return`
|
|
300
|
+
${e.fg("error",t)}`}function kr(i,e){let t=e?.operations??KS;return{name:"write",label:"write",description:"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",promptSnippet:"Create or overwrite files",promptGuidelines:["Use write only for new files or complete rewrites."],parameters:GS,async execute(n,{path:s,content:o},r,a,l){let c=qe(s,i),d=NS(c);return In(c,()=>new Promise((p,u)=>{if(r?.aborted){u(new Error("Operation aborted"));return}let h=!1,m=()=>{h=!0,u(new Error("Operation aborted"))};r?.addEventListener("abort",m,{once:!0}),(async()=>{try{if(await t.mkdir(d),h||(await t.writeFile(c,o),h))return;r?.removeEventListener("abort",m),p({content:[{type:"text",text:`Successfully wrote ${o.length} bytes to ${s}`}],details:void 0})}catch(g){r?.removeEventListener("abort",m),h||u(g)}})()}))},renderCall(n,s,o){let r=n,a=ae(r?.file_path??r?.path),l=ae(r?.content),c=o.lastComponent??new jl;return l!==null?c.cache=o.argsComplete?wr(a,l):jS(c.cache,a,l):c.cache=void 0,c.setText(VS(r,{expanded:o.expanded,isPartial:o.isPartial},s,c.cache)),c},renderResult(n,s,o,r){let a=QS({...n,isError:r.isError},o);if(!a){let c=r.lastComponent??new L;return c.clear(),c}let l=r.lastComponent??new T("",0,0);return l.setText(a),l}}}function tc(i,e){return{read:yr(i,e?.read),bash:cr(i,e?.bash),edit:ur(i,e?.edit),write:kr(i,e?.write),grep:hr(i,e?.grep),find:mr(i,e?.find),ls:gr(i,e?.ls)}}function nc(i){let e=i.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);return e?{name:e[1],location:e[2],content:e[3],userMessage:e[4]?.trim()||void 0}:null}import g3 from"proper-lockfile";import{Type as y}from"typebox";import{Compile as oT}from"typebox/compile";var ic={anthropic:"Anthropic","amazon-bedrock":"Amazon Bedrock","azure-openai-responses":"Azure OpenAI Responses",cerebras:"Cerebras","cloudflare-ai-gateway":"Cloudflare AI Gateway","cloudflare-workers-ai":"Cloudflare Workers AI",deepseek:"DeepSeek",fireworks:"Fireworks",google:"Google Gemini","google-vertex":"Google Vertex AI",groq:"Groq",huggingface:"Hugging Face","kimi-coding":"Kimi For Coding",mistral:"Mistral",minimax:"MiniMax","minimax-cn":"MiniMax (China)",moonshotai:"Moonshot AI","moonshotai-cn":"Moonshot AI (China)",opencode:"OpenCode Zen","opencode-go":"OpenCode Go",openai:"OpenAI",openrouter:"OpenRouter",together:"Together AI","vercel-ai-gateway":"Vercel AI Gateway",xai:"xAI",zai:"ZAI",xiaomi:"Xiaomi MiMo","xiaomi-token-plan-cn":"Xiaomi MiMo Token Plan (China)","xiaomi-token-plan-ams":"Xiaomi MiMo Token Plan (Amsterdam)","xiaomi-token-plan-sgp":"Xiaomi MiMo Token Plan (Singapore)"};var uh=y.Object({p50:y.Optional(y.Number()),p75:y.Optional(y.Number()),p90:y.Optional(y.Number()),p99:y.Optional(y.Number())}),rT=y.Object({allow_fallbacks:y.Optional(y.Boolean()),require_parameters:y.Optional(y.Boolean()),data_collection:y.Optional(y.Union([y.Literal("deny"),y.Literal("allow")])),zdr:y.Optional(y.Boolean()),enforce_distillable_text:y.Optional(y.Boolean()),order:y.Optional(y.Array(y.String())),only:y.Optional(y.Array(y.String())),ignore:y.Optional(y.Array(y.String())),quantizations:y.Optional(y.Array(y.String())),sort:y.Optional(y.Union([y.String(),y.Object({by:y.Optional(y.String()),partition:y.Optional(y.Union([y.String(),y.Null()]))})])),max_price:y.Optional(y.Object({prompt:y.Optional(y.Union([y.Number(),y.String()])),completion:y.Optional(y.Union([y.Number(),y.String()])),image:y.Optional(y.Union([y.Number(),y.String()])),audio:y.Optional(y.Union([y.Number(),y.String()])),request:y.Optional(y.Union([y.Number(),y.String()]))})),preferred_min_throughput:y.Optional(y.Union([y.Number(),uh])),preferred_max_latency:y.Optional(y.Union([y.Number(),uh]))}),aT=y.Object({only:y.Optional(y.Array(y.String())),order:y.Optional(y.Array(y.String()))}),bi=y.Union([y.String(),y.Null()]),mh=y.Object({off:y.Optional(bi),minimal:y.Optional(bi),low:y.Optional(bi),medium:y.Optional(bi),high:y.Optional(bi),xhigh:y.Optional(bi)}),lT=y.Object({supportsStore:y.Optional(y.Boolean()),supportsDeveloperRole:y.Optional(y.Boolean()),supportsReasoningEffort:y.Optional(y.Boolean()),supportsUsageInStreaming:y.Optional(y.Boolean()),maxTokensField:y.Optional(y.Union([y.Literal("max_completion_tokens"),y.Literal("max_tokens")])),requiresToolResultName:y.Optional(y.Boolean()),requiresAssistantAfterToolResult:y.Optional(y.Boolean()),requiresThinkingAsText:y.Optional(y.Boolean()),requiresReasoningContentOnAssistantMessages:y.Optional(y.Boolean()),thinkingFormat:y.Optional(y.Union([y.Literal("openai"),y.Literal("openrouter"),y.Literal("together"),y.Literal("deepseek"),y.Literal("zai"),y.Literal("qwen"),y.Literal("qwen-chat-template")])),cacheControlFormat:y.Optional(y.Literal("anthropic")),openRouterRouting:y.Optional(rT),vercelGatewayRouting:y.Optional(aT),supportsStrictMode:y.Optional(y.Boolean()),supportsLongCacheRetention:y.Optional(y.Boolean())}),cT=y.Object({sendSessionIdHeader:y.Optional(y.Boolean()),supportsLongCacheRetention:y.Optional(y.Boolean())}),pT=y.Object({supportsEagerToolInputStreaming:y.Optional(y.Boolean()),supportsLongCacheRetention:y.Optional(y.Boolean())}),sc=y.Union([lT,cT,pT]),dT=y.Object({id:y.String({minLength:1}),name:y.Optional(y.String({minLength:1})),api:y.Optional(y.String({minLength:1})),baseUrl:y.Optional(y.String({minLength:1})),reasoning:y.Optional(y.Boolean()),thinkingLevelMap:y.Optional(mh),input:y.Optional(y.Array(y.Union([y.Literal("text"),y.Literal("image")]))),cost:y.Optional(y.Object({input:y.Number(),output:y.Number(),cacheRead:y.Number(),cacheWrite:y.Number()})),contextWindow:y.Optional(y.Number()),maxTokens:y.Optional(y.Number()),headers:y.Optional(y.Record(y.String(),y.String())),compat:y.Optional(sc)}),uT=y.Object({name:y.Optional(y.String({minLength:1})),reasoning:y.Optional(y.Boolean()),thinkingLevelMap:y.Optional(mh),input:y.Optional(y.Array(y.Union([y.Literal("text"),y.Literal("image")]))),cost:y.Optional(y.Object({input:y.Optional(y.Number()),output:y.Optional(y.Number()),cacheRead:y.Optional(y.Number()),cacheWrite:y.Optional(y.Number())})),contextWindow:y.Optional(y.Number()),maxTokens:y.Optional(y.Number()),headers:y.Optional(y.Record(y.String(),y.String())),compat:y.Optional(sc)}),mT=y.Object({name:y.Optional(y.String({minLength:1})),baseUrl:y.Optional(y.String({minLength:1})),apiKey:y.Optional(y.String({minLength:1})),api:y.Optional(y.String({minLength:1})),headers:y.Optional(y.Record(y.String(),y.String())),compat:y.Optional(sc),authHeader:y.Optional(y.Boolean()),models:y.Optional(y.Array(dT)),modelOverrides:y.Optional(y.Record(y.String(),uT))}),hT=y.Object({providers:y.Record(y.String(),mT)}),L3=oT(hT);import{spawn as xh,spawnSync as xT}from"node:child_process";import{createHash as bT}from"node:crypto";import{existsSync as q,mkdirSync as oc,readdirSync as yi,readFileSync as Ds,rmSync as bh,statSync as Zt,writeFileSync as vh}from"node:fs";import{homedir as vT,tmpdir as yT}from"node:os";import{basename as lc,dirname as st,join as j,relative as ot,resolve as Ct,sep as wT}from"node:path";import{globSync as kT}from"glob";import Fs from"ignore";import{minimatch as vi}from"minimatch";import hh from"hosted-git-info";function gh(i){let e=i.match(/^git@([^:]+):(.+)$/);if(e){let l=e[2]??"",c=l.indexOf("@");if(c<0)return{repo:i};let d=l.slice(0,c),p=l.slice(c+1);return!d||!p?{repo:i}:{repo:`git@${e[1]??""}:${d}`,ref:p}}if(i.includes("://"))try{let l=new URL(i),c=l.pathname.replace(/^\/+/,""),d=c.indexOf("@");if(d<0)return{repo:i};let p=c.slice(0,d),u=c.slice(d+1);return!p||!u?{repo:i}:(l.pathname=`/${p}`,{repo:l.toString().replace(/\/$/,""),ref:u})}catch{return{repo:i}}let t=i.indexOf("/");if(t<0)return{repo:i};let n=i.slice(0,t),s=i.slice(t+1),o=s.indexOf("@");if(o<0)return{repo:i};let r=s.slice(0,o),a=s.slice(o+1);return!r||!a?{repo:i}:{repo:`${n}/${r}`,ref:a}}function gT(i){let{repo:e,ref:t}=gh(i),n=e,s="",o="",r=e.match(/^git@([^:]+):(.+)$/);if(r)s=r[1]??"",o=r[2]??"";else if(e.startsWith("https://")||e.startsWith("http://")||e.startsWith("ssh://")||e.startsWith("git://"))try{let l=new URL(e);s=l.hostname,o=l.pathname.replace(/^\/+/,"")}catch{return null}else{let l=e.indexOf("/");if(l<0||(s=e.slice(0,l),o=e.slice(l+1),!s.includes(".")&&s!=="localhost"))return null;n=`https://${e}`}let a=o.replace(/\.git$/,"").replace(/^\/+/,"");return!s||!a||a.split("/").length<2?null:{type:"git",repo:n,host:s,path:a,ref:t,pinned:!!t}}function Us(i){let e=i.trim(),t=e.startsWith("git:"),n=t?e.slice(4).trim():e;if(!t&&!/^(https?|ssh|git):\/\//i.test(n))return null;let s=gh(n),o=[s.ref?`${s.repo}#${s.ref}`:void 0,n].filter(a=>!!a);for(let a of o){let l=hh.fromUrl(a);if(l){if(s.ref&&l.project?.includes("@"))continue;return{type:"git",repo:!s.repo.startsWith("http://")&&!s.repo.startsWith("https://")&&!s.repo.startsWith("ssh://")&&!s.repo.startsWith("git://")&&!s.repo.startsWith("git@")?`https://${s.repo}`:s.repo,host:l.domain||"",path:`${l.user}/${l.project}`.replace(/\.git$/,""),ref:l.committish||s.ref||void 0,pinned:!!(l.committish||s.ref)}}}let r=[s.ref?`https://${s.repo}#${s.ref}`:void 0,`https://${n}`].filter(a=>!!a);for(let a of r){let l=hh.fromUrl(a);if(l){if(s.ref&&l.project?.includes("@"))continue;return{type:"git",repo:`https://${s.repo}`,host:l.domain||"",path:`${l.user}/${l.project}`.replace(/\.git$/,""),ref:l.committish||s.ref||void 0,pinned:!!(l.committish||s.ref)}}}return gT(n)}var fT;function fh(){return fT!==void 0}function rc(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{let i=Ds("/proc/self/environ","utf-8"),e={};for(let t of i.split("\0")){let n=t.indexOf("=");n>0&&(e[t.slice(0,n)]=t.slice(n+1))}return e}catch{return process.env}}var Tt=1e4,yh=4,ST=4;function Pn(){let i=process.env.PI_OFFLINE;return i?i==="1"||i.toLowerCase()==="true"||i.toLowerCase()==="yes":!1}function wh(i){return i.origin==="package"?4:(i.scope==="project"?0:2)+(i.source==="local"?0:1)}var Sr=["extensions","skills","prompts","themes"],TT={extensions:/\.(ts|js)$/,skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/},CT=[".gitignore",".ignore",".fdignore"];function ke(i){return i.split(wT).join("/")}function _n(){return process.env.HOME||vT()}function MT(i,e){let t=i.trim();if(!t||t.startsWith("#")&&!t.startsWith("\\#"))return null;let n=i,s=!1;n.startsWith("!")?(s=!0,n=n.slice(1)):n.startsWith("\\!")&&(n=n.slice(1)),n.startsWith("/")&&(n=n.slice(1));let o=e?`${e}${n}`:n;return s?`!${o}`:o}function $s(i,e,t){let n=ot(t,e),s=n?`${ke(n)}/`:"";for(let o of CT){let r=j(e,o);if(q(r))try{let l=Ds(r,"utf-8").split(/\r?\n/).map(c=>MT(c,s)).filter(c=>!!c);l.length>0&&i.add(l)}catch{}}}function RT(i){return i.startsWith("!")||i.startsWith("+")||i.startsWith("-")||i.includes("*")||i.includes("?")}function ac(i){return i.startsWith("!")||i.startsWith("+")||i.startsWith("-")}function ET(i){return i.includes("*")||i.includes("?")}function IT(i){let e=[],t=[];for(let n of i)RT(n)?t.push(n):e.push(n);return{plain:e,patterns:t}}function Ch(i,e,t=!0,n,s){let o=[];if(!q(i))return o;let r=s??i,a=n??Fs();$s(a,i,r);try{let l=yi(i,{withFileTypes:!0});for(let c of l){if(c.name.startsWith(".")||t&&c.name==="node_modules")continue;let d=j(i,c.name),p=c.isDirectory(),u=c.isFile();if(c.isSymbolicLink())try{let g=Zt(d);p=g.isDirectory(),u=g.isFile()}catch{continue}let h=ke(ot(r,d)),m=p?`${h}/`:h;a.ignores(m)||(p?o.push(...Ch(d,e,t,a,r)):u&&e.test(c.name)&&o.push(d))}}catch{}return o}function dc(i,e,t,n){let s=[];if(!q(i))return s;let o=n??i,r=t??Fs();$s(r,i,o);try{let a=yi(i,{withFileTypes:!0});for(let l of a){if(l.name!=="SKILL.md")continue;let c=j(i,l.name),d=l.isFile();if(l.isSymbolicLink())try{d=Zt(c).isFile()}catch{continue}let p=ke(ot(o,c));if(d&&!r.ignores(p))return s.push(c),s}for(let l of a){if(l.name.startsWith(".")||l.name==="node_modules")continue;let c=j(i,l.name),d=l.isDirectory(),p=l.isFile();if(l.isSymbolicLink())try{let h=Zt(c);d=h.isDirectory(),p=h.isFile()}catch{continue}let u=ke(ot(o,c));if(e==="pi"&&i===o&&p&&l.name.endsWith(".md")&&!r.ignores(u)){s.push(c);continue}d&&(r.ignores(`${u}/`)||s.push(...dc(c,e,r,o)))}}catch{}return s}function Tr(i,e){return dc(i,e)}function AT(i){let e=Ct(i);for(;;){if(q(j(e,".git")))return e;let t=st(e);if(t===e)return null;e=t}}function PT(i){let e=[],t=Ct(i),n=AT(t),s=t;for(;e.push(j(s,".agents","skills")),!(n&&s===n);){let o=st(s);if(o===s)break;s=o}return e}function kh(i){let e=[];if(!q(i))return e;let t=Fs();$s(t,i,i);try{let n=yi(i,{withFileTypes:!0});for(let s of n){if(s.name.startsWith(".")||s.name==="node_modules")continue;let o=j(i,s.name),r=s.isFile();if(s.isSymbolicLink())try{r=Zt(o).isFile()}catch{continue}let a=ke(ot(i,o));t.ignores(a)||r&&s.name.endsWith(".md")&&e.push(o)}}catch{}return e}function Sh(i){let e=[];if(!q(i))return e;let t=Fs();$s(t,i,i);try{let n=yi(i,{withFileTypes:!0});for(let s of n){if(s.name.startsWith(".")||s.name==="node_modules")continue;let o=j(i,s.name),r=s.isFile();if(s.isSymbolicLink())try{r=Zt(o).isFile()}catch{continue}let a=ke(ot(i,o));t.ignores(a)||r&&s.name.endsWith(".json")&&e.push(o)}}catch{}return e}function _T(i){try{let e=Ds(i,"utf-8");return JSON.parse(e).pi??null}catch{return null}}function Th(i){let e=j(i,"package.json");if(q(e)){let s=_T(e);if(s?.extensions?.length){let o=[];for(let r of s.extensions){let a=Ct(i,r);q(a)&&o.push(a)}if(o.length>0)return o}}let t=j(i,"index.ts"),n=j(i,"index.js");return q(t)?[t]:q(n)?[n]:null}function cc(i){let e=[];if(!q(i))return e;let t=Th(i);if(t)return t;let n=Fs();$s(n,i,i);try{let s=yi(i,{withFileTypes:!0});for(let o of s){if(o.name.startsWith(".")||o.name==="node_modules")continue;let r=j(i,o.name),a=o.isDirectory(),l=o.isFile();if(o.isSymbolicLink())try{let p=Zt(r);a=p.isDirectory(),l=p.isFile()}catch{continue}let c=ke(ot(i,r)),d=a?`${c}/`:c;if(!n.ignores(d)){if(l&&(o.name.endsWith(".ts")||o.name.endsWith(".js")))e.push(r);else if(a){let p=Th(r);p&&e.push(...p)}}}}catch{}return e}function Cr(i,e){return e==="skills"?dc(i,"pi"):e==="extensions"?cc(i):Ch(i,TT[e])}function pc(i,e,t){let n=ke(ot(t,i)),s=lc(i),o=ke(i),r=s==="SKILL.md",a=r?st(i):void 0,l=r?ke(ot(t,a)):void 0,c=r?lc(a):void 0,d=r?ke(a):void 0;return e.some(p=>{let u=ke(p);return vi(n,u)||vi(s,u)||vi(o,u)?!0:r?vi(l,u)||vi(c,u)||vi(d,u):!1})}function LT(i){let e=i.startsWith("./")||i.startsWith(".\\")?i.slice(2):i;return ke(e)}function Rr(i,e,t){if(e.length===0)return!1;let n=ke(ot(t,i)),s=lc(i),o=ke(i),r=s==="SKILL.md",a=r?st(i):void 0,l=r?ke(ot(t,a)):void 0,c=r?ke(a):void 0;return e.some(d=>{let p=LT(d);return p===n||p===o?!0:r?p===l||p===c:!1})}function WT(i){return i.filter(e=>e.startsWith("!")||e.startsWith("+")||e.startsWith("-"))}function OT(i,e,t){let n=WT(e),s=n.filter(l=>l.startsWith("!")).map(l=>l.slice(1)),o=n.filter(l=>l.startsWith("+")).map(l=>l.slice(1)),r=n.filter(l=>l.startsWith("-")).map(l=>l.slice(1)),a=!0;return s.length>0&&pc(i,s,t)&&(a=!1),o.length>0&&Rr(i,o,t)&&(a=!0),r.length>0&&Rr(i,r,t)&&(a=!1),a}function Mr(i,e,t){let n=[],s=[],o=[],r=[];for(let l of e)l.startsWith("+")?o.push(l.slice(1)):l.startsWith("-")?r.push(l.slice(1)):l.startsWith("!")?s.push(l.slice(1)):n.push(l);let a;if(n.length===0?a=[...i]:a=i.filter(l=>pc(l,n,t)),s.length>0&&(a=a.filter(l=>!pc(l,s,t))),o.length>0)for(let l of i)!a.includes(l)&&Rr(l,o,t)&&a.push(l);return r.length>0&&(a=a.filter(l=>!Rr(l,r,t))),new Set(a)}var Ln=class{constructor(e){this.cwd=e.cwd,this.agentDir=e.agentDir,this.settingsManager=e.settingsManager}setProgressCallback(e){this.progressCallback=e}addSourceToSettings(e,t){let n=t?.local?"project":"user",o=(n==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],r=this.normalizePackageSourceForSettings(e,n);if(o.some(c=>this.packageSourcesMatch(c,e,n)))return!1;let l=[...o,r];return n==="project"?this.settingsManager.setProjectPackages(l):this.settingsManager.setPackages(l),!0}removeSourceFromSettings(e,t){let n=t?.local?"project":"user",o=(n==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],r=o.filter(l=>!this.packageSourcesMatch(l,e,n));return r.length!==o.length?(n==="project"?this.settingsManager.setProjectPackages(r):this.settingsManager.setPackages(r),!0):!1}getInstalledPath(e,t){let n=this.parseSource(e);if(n.type==="npm"){let s=this.getNpmInstallPath(n,t);return q(s)?s:void 0}if(n.type==="git"){let s=this.getGitInstallPath(n,t);return q(s)?s:void 0}if(n.type==="local"){let s=this.getBaseDirForScope(t),o=this.resolvePathFromBase(n.path,s);return q(o)?o:void 0}}emitProgress(e){this.progressCallback?.(e)}async withProgress(e,t,n,s){this.emitProgress({type:"start",action:e,source:t,message:n});try{await s(),this.emitProgress({type:"complete",action:e,source:t})}catch(o){let r=o instanceof Error?o.message:String(o);throw this.emitProgress({type:"error",action:e,source:t,message:r}),o}}async resolve(e){let t=this.createAccumulator(),n=this.settingsManager.getGlobalSettings(),s=this.settingsManager.getProjectSettings(),o=[];for(let c of s.packages??[])o.push({pkg:c,scope:"project"});for(let c of n.packages??[])o.push({pkg:c,scope:"user"});let r=this.dedupePackages(o);await this.resolvePackageSources(r,t,e);let a=this.agentDir,l=j(this.cwd,Te);for(let c of Sr){let d=this.getTargetMap(t,c),p=n[c]??[],u=s[c]??[];this.resolveLocalEntries(u,c,d,{source:"local",scope:"project",origin:"top-level"},l),this.resolveLocalEntries(p,c,d,{source:"local",scope:"user",origin:"top-level"},a)}return this.addAutoDiscoveredResources(t,n,s,a,l),this.toResolvedPaths(t)}async resolveExtensionSources(e,t){let n=this.createAccumulator(),s=t?.temporary?"temporary":t?.local?"project":"user",o=e.map(r=>({pkg:r,scope:s}));return await this.resolvePackageSources(o,n),this.toResolvedPaths(n)}listConfiguredPackages(){let e=this.settingsManager.getGlobalSettings(),t=this.settingsManager.getProjectSettings(),n=[];for(let s of e.packages??[]){let o=typeof s=="string"?s:s.source;n.push({source:o,scope:"user",filtered:typeof s=="object",installedPath:this.getInstalledPath(o,"user")})}for(let s of t.packages??[]){let o=typeof s=="string"?s:s.source;n.push({source:o,scope:"project",filtered:typeof s=="object",installedPath:this.getInstalledPath(o,"project")})}return n}async install(e,t){let n=this.parseSource(e),s=t?.local?"project":"user";await this.withProgress("install",e,`Installing ${e}...`,async()=>{if(n.type==="npm"){await this.installNpm(n,s,!1);return}if(n.type==="git"){await this.installGit(n,s);return}if(n.type==="local"){let o=this.resolvePath(n.path);if(!q(o))throw new Error(`Path does not exist: ${o}`);return}throw new Error(`Unsupported install source: ${e}`)})}async installAndPersist(e,t){await this.install(e,t),this.addSourceToSettings(e,t)}async remove(e,t){let n=this.parseSource(e),s=t?.local?"project":"user";await this.withProgress("remove",e,`Removing ${e}...`,async()=>{if(n.type==="npm"){await this.uninstallNpm(n,s);return}if(n.type==="git"){await this.removeGit(n,s);return}if(n.type!=="local")throw new Error(`Unsupported remove source: ${e}`)})}async removeAndPersist(e,t){return await this.remove(e,t),this.removeSourceFromSettings(e,t)}async update(e){let t=this.settingsManager.getGlobalSettings(),n=this.settingsManager.getProjectSettings(),s=e?this.getPackageIdentity(e):void 0,o=!1,r=[];for(let a of t.packages??[]){let l=typeof a=="string"?a:a.source;s&&this.getPackageIdentity(l,"user")!==s||(o=!0,r.push({source:l,scope:"user"}))}for(let a of n.packages??[]){let l=typeof a=="string"?a:a.source;s&&this.getPackageIdentity(l,"project")!==s||(o=!0,r.push({source:l,scope:"project"}))}if(e&&!o)throw new Error(this.buildNoMatchingPackageMessage(e,[...t.packages??[],...n.packages??[]]));await this.updateConfiguredSources(r)}async updateConfiguredSources(e){if(Pn()||e.length===0)return;let t=[],n=[];for(let c of e){let d=this.parseSource(c.source);if(!(d.type==="local"||d.pinned)){if(d.type==="npm"){t.push({...c,parsed:d});continue}n.push({...c,parsed:d})}}let s=t.map(c=>async()=>({entry:c,shouldUpdate:await this.shouldUpdateNpmSource(c.parsed,c.scope)})),o=await this.runWithConcurrency(s,yh),r=[],a=[];for(let c of o)c.shouldUpdate&&(c.entry.scope==="user"?r.push(c.entry):a.push(c.entry));let l=[];if(r.length>0&&l.push(this.updateNpmBatch(r,"user")),a.length>0&&l.push(this.updateNpmBatch(a,"project")),n.length>0){let c=n.map(d=>async()=>this.withProgress("update",d.source,`Updating ${d.source}...`,async()=>{await this.updateGit(d.parsed,d.scope)}));l.push(this.runWithConcurrency(c,ST).then(()=>{}))}await Promise.all(l)}async shouldUpdateNpmSource(e,t){let n=this.getNpmInstallPath(e,t),s=q(n)?this.getInstalledNpmVersion(n):void 0;if(!s)return!0;try{return await this.getLatestNpmVersion(e.name)!==s}catch{return!0}}async updateNpmBatch(e,t){if(e.length===0)return;let n=e.length===1?e[0].source:`${t} npm packages`,s=e.length===1?`Updating ${e[0].source}...`:`Updating ${t} npm packages...`,o=e.map(r=>`${r.parsed.name}@latest`);await this.withProgress("update",n,s,async()=>{await this.installNpmBatch(o,t)})}async installNpmBatch(e,t){if(t==="user"){await this.runNpmCommand(["install","-g",...e]);return}let n=this.getNpmInstallRoot(t,!1);this.ensureNpmProject(n),await this.runNpmCommand(["install",...e,"--prefix",n])}async checkForAvailableUpdates(){if(Pn())return[];let e=this.settingsManager.getGlobalSettings(),t=this.settingsManager.getProjectSettings(),n=[];for(let a of t.packages??[])n.push({pkg:a,scope:"project"});for(let a of e.packages??[])n.push({pkg:a,scope:"user"});let o=this.dedupePackages(n).filter(a=>a.scope!=="temporary").map(a=>async()=>{let l=typeof a.pkg=="string"?a.pkg:a.pkg.source,c=this.parseSource(l);if(c.type==="local"||c.pinned)return;if(c.type==="npm"){let u=this.getNpmInstallPath(c,a.scope);return!q(u)||!await this.npmHasAvailableUpdate(c,u)?void 0:{source:l,displayName:c.name,type:"npm",scope:a.scope}}let d=this.getGitInstallPath(c,a.scope);if(!(!q(d)||!await this.gitHasAvailableUpdate(d)))return{source:l,displayName:`${c.host}/${c.path}`,type:"git",scope:a.scope}});return(await this.runWithConcurrency(o,yh)).filter(a=>a!==void 0)}async resolvePackageSources(e,t,n){for(let{pkg:s,scope:o}of e){let r=typeof s=="string"?s:s.source,a=typeof s=="object"?s:void 0,l=this.parseSource(r),c={source:r,scope:o,origin:"package"};if(l.type==="local"){let p=this.getBaseDirForScope(o);this.resolveLocalExtensionSource(l,t,a,c,p);continue}let d=async()=>{if(Pn())return!1;if(!n)return await this.installParsedSource(l,o),!0;let p=await n(r);if(p==="skip")return!1;if(p==="error")throw new Error(`Missing source: ${r}`);return await this.installParsedSource(l,o),!0};if(l.type==="npm"){let p=this.getNpmInstallPath(l,o);if((!q(p)||l.pinned&&!await this.installedNpmMatchesPinnedVersion(l,p))&&!await d())continue;c.baseDir=p,this.collectPackageResources(p,t,a,c);continue}if(l.type==="git"){let p=this.getGitInstallPath(l,o);if(q(p))o==="temporary"&&!l.pinned&&!Pn()&&await this.refreshTemporaryGitSource(l,r);else if(!await d())continue;c.baseDir=p,this.collectPackageResources(p,t,a,c)}}}resolveLocalExtensionSource(e,t,n,s,o){let r=this.resolvePathFromBase(e.path,o);if(q(r))try{let a=Zt(r);if(a.isFile()){s.baseDir=st(r),this.addResource(t.extensions,r,s,!0);return}a.isDirectory()&&(s.baseDir=r,this.collectPackageResources(r,t,n,s)||this.addResource(t.extensions,r,s,!0))}catch{return}}async installParsedSource(e,t){if(e.type==="npm"){await this.installNpm(e,t,t==="temporary");return}if(e.type==="git"){await this.installGit(e,t);return}}getPackageSourceString(e){return typeof e=="string"?e:e.source}getSourceMatchKeyForInput(e){let t=this.parseSource(e);return t.type==="npm"?`npm:${t.name}`:t.type==="git"?`git:${t.host}/${t.path}`:`local:${this.resolvePath(t.path)}`}getSourceMatchKeyForSettings(e,t){let n=this.parseSource(e);if(n.type==="npm")return`npm:${n.name}`;if(n.type==="git")return`git:${n.host}/${n.path}`;let s=this.getBaseDirForScope(t);return`local:${this.resolvePathFromBase(n.path,s)}`}buildNoMatchingPackageMessage(e,t){let n=this.findSuggestedConfiguredSource(e,t);return n?`No matching package found for ${e}. Did you mean ${n}?`:`No matching package found for ${e}`}findSuggestedConfiguredSource(e,t){let n=e.trim(),s=new Set;for(let o of t){let r=this.getPackageSourceString(o),a=this.parseSource(r);if(a.type==="npm"){(n===a.name||n===a.spec)&&s.add(r);continue}if(a.type==="git"){let l=`${a.host}/${a.path}`,c=a.ref?`${l}@${a.ref}`:void 0;(n===l||c&&n===c)&&s.add(r)}}return s.values().next().value}packageSourcesMatch(e,t,n){let s=this.getSourceMatchKeyForSettings(this.getPackageSourceString(e),n),o=this.getSourceMatchKeyForInput(t);return s===o}normalizePackageSourceForSettings(e,t){let n=this.parseSource(e);if(n.type!=="local")return e;let s=this.getBaseDirForScope(t),o=this.resolvePath(n.path);return ot(s,o)||"."}parseSource(e){if(e.startsWith("npm:")){let n=e.slice(4).trim(),{name:s,version:o}=this.parseNpmSpec(n);return{type:"npm",spec:n,name:s,pinned:!!o}}if(sr(e))return{type:"local",path:e};let t=Us(e);return t||{type:"local",path:e}}async installedNpmMatchesPinnedVersion(e,t){let n=this.getInstalledNpmVersion(t);if(!n)return!1;let{version:s}=this.parseNpmSpec(e.spec);return s?n===s:!0}async npmHasAvailableUpdate(e,t){if(Pn())return!1;let n=this.getInstalledNpmVersion(t);if(!n)return!1;try{return await this.getLatestNpmVersion(e.name)!==n}catch{return!1}}getInstalledNpmVersion(e){let t=j(e,"package.json");if(q(t))try{let n=Ds(t,"utf-8");return JSON.parse(n).version}catch{return}}async getLatestNpmVersion(e){let t=this.getNpmCommand(),s=(await this.runCommandCapture(t.command,[...t.args,"view",e,"version","--json"],{cwd:this.cwd,timeoutMs:Tt})).trim();if(!s)throw new Error("Empty response from npm view");return JSON.parse(s)}async gitHasAvailableUpdate(e){if(Pn())return!1;try{let t=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:e,timeoutMs:Tt}),n=await this.getRemoteGitHead(e);return t.trim()!==n.trim()}catch{return!1}}async getRemoteGitHead(e){let t=await this.getGitUpstreamRef(e);if(t){let r=(await this.runGitRemoteCommand(e,["ls-remote","origin",t])).match(/^([0-9a-f]{40})\s+/m);if(r?.[1])return r[1]}let s=(await this.runGitRemoteCommand(e,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!s?.[1])throw new Error("Failed to determine remote HEAD");return s[1]}async getLocalGitUpdateTarget(e){try{let n=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:e,timeoutMs:Tt})).trim();if(!n.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${n}`);let s=n.slice(7);if(!s)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:e,timeoutMs:Tt}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:e}).catch(()=>{});let t=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:e,timeoutMs:Tt}),s=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:e,timeoutMs:Tt}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return s?{ref:"origin/HEAD",head:t,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`]}:{ref:"origin/HEAD",head:t,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(e){try{let n=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:e,timeoutMs:Tt})).trim();if(!n.startsWith("origin/"))return;let s=n.slice(7);return s?`refs/heads/${s}`:void 0}catch{return}}runGitRemoteCommand(e,t){return this.runCommandCapture("git",t,{cwd:e,timeoutMs:Tt,env:{GIT_TERMINAL_PROMPT:"0"}})}async runWithConcurrency(e,t){if(e.length===0)return[];let n=new Array(e.length),s=0,o=Math.max(1,Math.min(t,e.length)),r=async()=>{for(;;){let a=s;if(s+=1,a>=e.length)return;n[a]=await e[a]()}};return await Promise.all(Array.from({length:o},()=>r())),n}getPackageIdentity(e,t){let n=this.parseSource(e);if(n.type==="npm")return`npm:${n.name}`;if(n.type==="git")return`git:${n.host}/${n.path}`;if(t){let s=this.getBaseDirForScope(t);return`local:${this.resolvePathFromBase(n.path,s)}`}return`local:${this.resolvePath(n.path)}`}dedupePackages(e){let t=new Map;for(let n of e){let s=typeof n.pkg=="string"?n.pkg:n.pkg.source,o=this.getPackageIdentity(s,n.scope),r=t.get(o);r?n.scope==="project"&&r.scope==="user"&&t.set(o,n):t.set(o,n)}return Array.from(t.values())}parseNpmSpec(e){let t=e.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!t)return{name:e};let n=t[1]??e,s=t[2];return{name:n,version:s}}getNpmCommand(){let e=this.settingsManager.getNpmCommand();if(!e||e.length===0)return{command:"npm",args:[]};let[t,...n]=e;if(!t)throw new Error("Invalid npmCommand: first array entry must be a non-empty command");return{command:t,args:n}}async runNpmCommand(e,t){let n=this.getNpmCommand();await this.runCommand(n.command,[...n.args,...e],t)}getGitDependencyInstallArgs(){let e=this.settingsManager.getNpmCommand();return e&&e.length>0?["install"]:["install","--omit=dev"]}runNpmCommandSync(e){let t=this.getNpmCommand();return this.runCommandSync(t.command,[...t.args,...e])}async installNpm(e,t,n){if(t==="user"&&!n){await this.runNpmCommand(["install","-g",e.spec]);return}let s=this.getNpmInstallRoot(t,n);this.ensureNpmProject(s),await this.runNpmCommand(["install",e.spec,"--prefix",s])}async uninstallNpm(e,t){if(t==="user"){await this.runNpmCommand(["uninstall","-g",e.name]);return}let n=this.getNpmInstallRoot(t,!1);q(n)&&await this.runNpmCommand(["uninstall",e.name,"--prefix",n])}async installGit(e,t){let n=this.getGitInstallPath(e,t);if(q(n))return;let s=this.getGitInstallRoot(t);s&&this.ensureGitIgnore(s),oc(st(n),{recursive:!0}),await this.runCommand("git",["clone",e.repo,n]),e.ref&&await this.runCommand("git",["checkout",e.ref],{cwd:n});let o=j(n,"package.json");q(o)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:n})}async updateGit(e,t){let n=this.getGitInstallPath(e,t);if(!q(n)){await this.installGit(e,t);return}let s=await this.getLocalGitUpdateTarget(n);await this.runCommand("git",s.fetchArgs,{cwd:n});let o=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:n,timeoutMs:Tt}),r=await this.runCommandCapture("git",["rev-parse",s.ref],{cwd:n,timeoutMs:Tt});if(o.trim()===r.trim())return;await this.runCommand("git",["reset","--hard",s.ref],{cwd:n}),await this.runCommand("git",["clean","-fdx"],{cwd:n});let a=j(n,"package.json");q(a)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:n})}async refreshTemporaryGitSource(e,t){if(!Pn())try{await this.withProgress("pull",t,`Refreshing ${t}...`,async()=>{await this.updateGit(e,"temporary")})}catch{}}async removeGit(e,t){let n=this.getGitInstallPath(e,t);q(n)&&(bh(n,{recursive:!0,force:!0}),this.pruneEmptyGitParents(n,this.getGitInstallRoot(t)))}pruneEmptyGitParents(e,t){if(!t)return;let n=Ct(t),s=st(e);for(;s.startsWith(n)&&s!==n;){if(!q(s)){s=st(s);continue}if(yi(s).length>0)break;try{bh(s,{recursive:!0,force:!0})}catch{break}s=st(s)}}ensureNpmProject(e){q(e)||oc(e,{recursive:!0}),this.ensureGitIgnore(e);let t=j(e,"package.json");q(t)||vh(t,JSON.stringify({name:"pi-extensions",private:!0},null,2),"utf-8")}ensureGitIgnore(e){q(e)||oc(e,{recursive:!0});let t=j(e,".gitignore");q(t)||vh(t,`*
|
|
301
|
+
!.gitignore
|
|
302
|
+
`,"utf-8")}getNpmInstallRoot(e,t){return t?this.getTemporaryDir("npm"):e==="project"?j(this.cwd,Te,"npm"):j(this.getGlobalNpmRoot(),"..")}getGlobalNpmRoot(){let e=this.getNpmCommand(),t=[e.command,...e.args].join("\0");if(this.globalNpmRoot&&this.globalNpmRootCommandKey===t)return this.globalNpmRoot;if(e.command==="bun"){let s=this.runNpmCommandSync(["pm","bin","-g"]).trim();this.globalNpmRoot=j(st(s),"install","global","node_modules")}else this.globalNpmRoot=this.runNpmCommandSync(["root","-g"]).trim();return this.globalNpmRootCommandKey=t,this.globalNpmRoot}getNpmInstallPath(e,t){return t==="temporary"?j(this.getTemporaryDir("npm"),"node_modules",e.name):t==="project"?j(this.cwd,Te,"npm","node_modules",e.name):j(this.getGlobalNpmRoot(),e.name)}getGitInstallPath(e,t){return t==="temporary"?this.getTemporaryDir(`git-${e.host}`,e.path):t==="project"?j(this.cwd,Te,"git",e.host,e.path):j(this.agentDir,"git",e.host,e.path)}getGitInstallRoot(e){if(e!=="temporary")return e==="project"?j(this.cwd,Te,"git"):j(this.agentDir,"git")}getTemporaryDir(e,t){let n=bT("sha256").update(`${e}-${t??""}`).digest("hex").slice(0,8);return j(yT(),"pi-extensions",e,n,t??"")}getBaseDirForScope(e){return e==="project"?j(this.cwd,Te):e==="user"?this.agentDir:this.cwd}resolvePath(e){let t=e.trim();return t==="~"?_n():t.startsWith("~/")?j(_n(),t.slice(2)):t.startsWith("~")?j(_n(),t.slice(1)):Ct(this.cwd,t)}resolvePathFromBase(e,t){let n=e.trim();return n==="~"?_n():n.startsWith("~/")?j(_n(),n.slice(2)):n.startsWith("~")?j(_n(),n.slice(1)):Ct(t,n)}collectPackageResources(e,t,n,s){if(n){for(let a of Sr){let l=n[a],c=this.getTargetMap(t,a);l!==void 0?this.applyPackageFilter(e,l,a,c,s):this.collectDefaultResources(e,a,c,s)}return!0}let o=this.readPiManifest(e);if(o){for(let a of Sr){let l=o[a];this.addManifestEntries(l,e,a,this.getTargetMap(t,a),s)}return!0}let r=!1;for(let a of Sr){let l=j(e,a);if(q(l)){let c=Cr(l,a);for(let d of c)this.addResource(this.getTargetMap(t,a),d,s,!0);r=!0}}return r}collectDefaultResources(e,t,n,s){let r=this.readPiManifest(e)?.[t];if(r){this.addManifestEntries(r,e,t,n,s);return}let a=j(e,t);if(q(a)){let l=Cr(a,t);for(let c of l)this.addResource(n,c,s,!0)}}applyPackageFilter(e,t,n,s,o){let{allFiles:r}=this.collectManifestFiles(e,n);if(t.length===0){for(let l of r)this.addResource(s,l,o,!1);return}let a=Mr(r,t,e);for(let l of r){let c=a.has(l);this.addResource(s,l,o,c)}}collectManifestFiles(e,t){let s=this.readPiManifest(e)?.[t];if(s&&s.length>0){let a=this.collectFilesFromManifestEntries(s,e,t),l=s.filter(ac),c=l.length>0?Mr(a,l,e):new Set(a);return{allFiles:Array.from(c),enabledByManifest:c}}let o=j(e,t);if(!q(o))return{allFiles:[],enabledByManifest:new Set};let r=Cr(o,t);return{allFiles:r,enabledByManifest:new Set(r)}}readPiManifest(e){let t=j(e,"package.json");if(!q(t))return null;try{let n=Ds(t,"utf-8");return JSON.parse(n).pi??null}catch{return null}}addManifestEntries(e,t,n,s,o){if(!e)return;let r=this.collectFilesFromManifestEntries(e,t,n),a=e.filter(ac),l=Mr(r,a,t);for(let c of r)l.has(c)&&this.addResource(s,c,o,!0)}collectFilesFromManifestEntries(e,t,n){let o=e.filter(r=>!ac(r)).flatMap(r=>ET(r)?kT(r,{cwd:t,absolute:!0,dot:!1,nodir:!1}).map(a=>Ct(a)):[Ct(t,r)]);return this.collectFilesFromPaths(o,n)}resolveLocalEntries(e,t,n,s,o){if(e.length===0)return;let{plain:r,patterns:a}=IT(e),l=r.map(p=>this.resolvePathFromBase(p,o)),c=this.collectFilesFromPaths(l,t),d=Mr(c,a,o);for(let p of c)this.addResource(n,p,s,d.has(p))}addAutoDiscoveredResources(e,t,n,s,o){let r={source:"auto",scope:"user",origin:"top-level",baseDir:s},a={source:"auto",scope:"project",origin:"top-level",baseDir:o},l={extensions:t.extensions??[],skills:t.skills??[],prompts:t.prompts??[],themes:t.themes??[]},c={extensions:n.extensions??[],skills:n.skills??[],prompts:n.prompts??[],themes:n.themes??[]},d={extensions:j(s,"extensions"),skills:j(s,"skills"),prompts:j(s,"prompts"),themes:j(s,"themes")},p={extensions:j(o,"extensions"),skills:j(o,"skills"),prompts:j(o,"prompts"),themes:j(o,"themes")},u=j(_n(),".agents","skills"),h=PT(this.cwd).filter(b=>Ct(b)!==Ct(u)),m=(b,v,w,C,R)=>{let k=this.getTargetMap(e,b);for(let A of v){let S=OT(A,C,R);this.addResource(k,A,w,S)}};m("extensions",cc(p.extensions),a,c.extensions,o),m("skills",Tr(p.skills,"pi"),a,c.skills,o);for(let b of h){let v=st(b),w={...a,baseDir:v};m("skills",Tr(b,"agents"),w,c.skills,v)}m("prompts",kh(p.prompts),a,c.prompts,o),m("themes",Sh(p.themes),a,c.themes,o),m("extensions",cc(d.extensions),r,l.extensions,s),m("skills",Tr(d.skills,"pi"),r,l.skills,s);let g=st(u),x={...r,baseDir:g};m("skills",Tr(u,"agents"),x,l.skills,g),m("prompts",kh(d.prompts),r,l.prompts,s),m("themes",Sh(d.themes),r,l.themes,s)}collectFilesFromPaths(e,t){let n=[];for(let s of e)if(q(s))try{let o=Zt(s);o.isFile()?n.push(s):o.isDirectory()&&n.push(...Cr(s,t))}catch{}return n}getTargetMap(e,t){switch(t){case"extensions":return e.extensions;case"skills":return e.skills;case"prompts":return e.prompts;case"themes":return e.themes;default:throw new Error(`Unknown resource type: ${t}`)}}addResource(e,t,n,s){t&&(e.has(t)||e.set(t,{metadata:n,enabled:s}))}createAccumulator(){return{extensions:new Map,skills:new Map,prompts:new Map,themes:new Map}}toResolvedPaths(e){let t=n=>{let s=Array.from(n.entries()).map(([r,{metadata:a,enabled:l}])=>({path:r,enabled:l,metadata:a}));s.sort((r,a)=>wh(r.metadata)-wh(a.metadata));let o=new Set;return s.filter(r=>{let a=li(r.path);return o.has(a)?!1:(o.add(a),!0)})};return{extensions:t(e.extensions),skills:t(e.skills),prompts:t(e.prompts),themes:t(e.themes)}}spawnCommand(e,t,n){return xh(e,t,{cwd:n?.cwd,stdio:fh()?["ignore",2,2]:"inherit",shell:Hn(e),env:rc()})}spawnCaptureCommand(e,t,n){let s=rc();return xh(e,t,{cwd:n?.cwd,stdio:["ignore","pipe","pipe"],shell:Hn(e),env:n?.env?{...s,...n.env}:s})}runCommandCapture(e,t,n){return new Promise((s,o)=>{let r=this.spawnCaptureCommand(e,t,n),a="",l="",c=!1,d=typeof n?.timeoutMs=="number"?setTimeout(()=>{c=!0,r.kill()},n.timeoutMs):void 0;r.stdout?.on("data",p=>{a+=p.toString()}),r.stderr?.on("data",p=>{l+=p.toString()}),r.once("error",p=>{d&&clearTimeout(d),o(p)}),r.once("close",(p,u)=>{if(d&&clearTimeout(d),c){o(new Error(`${e} ${t.join(" ")} timed out after ${n?.timeoutMs}ms`));return}if(p===0){s(a.trim());return}let h=p===null?`signal ${u??"unknown"}`:`code ${p}`;o(new Error(`${e} ${t.join(" ")} failed with ${h}: ${l||a}`))})})}runCommand(e,t,n){return new Promise((s,o)=>{let r=this.spawnCommand(e,t,n);r.on("error",o),r.on("exit",a=>{a===0?s():o(new Error(`${e} ${t.join(" ")} failed with code ${a}`))})})}runCommandSync(e,t){let n=xT(e,t,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",shell:Hn(e),env:rc()});if(n.error||n.status!==0)throw new Error(`Failed to run ${e} ${t.join(" ")}: ${n.error?.message||n.stderr||n.stdout}`);return(n.stdout||n.stderr||"").trim()}};import o4 from"chalk";import Z3 from"proper-lockfile";import mc from"chalk";import{minimatch as Mh}from"minimatch";import b4 from"chalk";var DT=["off","minimal","low","medium","high","xhigh"];function uc(i){return DT.includes(i)}var gc={"amazon-bedrock":"us.anthropic.claude-opus-4-6-v1",anthropic:"claude-opus-4-7",openai:"gpt-5.4","azure-openai-responses":"gpt-5.4","openai-codex":"gpt-5.5",deepseek:"deepseek-v4-pro",google:"gemini-3.1-pro-preview","google-vertex":"gemini-3.1-pro-preview","github-copilot":"gpt-5.4",openrouter:"moonshotai/kimi-k2.6","vercel-ai-gateway":"zai/glm-5.1",xai:"grok-4.20-0309-reasoning",groq:"openai/gpt-oss-120b",cerebras:"zai-glm-4.7",zai:"glm-5.1",mistral:"devstral-medium-latest",minimax:"MiniMax-M2.7","minimax-cn":"MiniMax-M2.7",moonshotai:"kimi-k2.6","moonshotai-cn":"kimi-k2.6",huggingface:"moonshotai/Kimi-K2.6",fireworks:"accounts/fireworks/models/kimi-k2p6",together:"moonshotai/Kimi-K2.6",opencode:"kimi-k2.6","opencode-go":"kimi-k2.6","kimi-coding":"kimi-for-coding","cloudflare-workers-ai":"@cf/moonshotai/kimi-k2.6","cloudflare-ai-gateway":"workers-ai/@cf/moonshotai/kimi-k2.6",xiaomi:"mimo-v2.5-pro","xiaomi-token-plan-cn":"mimo-v2.5-pro","xiaomi-token-plan-ams":"mimo-v2.5-pro","xiaomi-token-plan-sgp":"mimo-v2.5-pro"};function Rh(i){return i.endsWith("-latest")?!0:!/-\d{8}$/.test(i)}function fc(i,e){let t=i.trim();if(!t)return;let n=t.toLowerCase(),s=e.filter(a=>`${a.provider}/${a.id}`.toLowerCase()===n);if(s.length===1)return s[0];if(s.length>1)return;let o=t.indexOf("/");if(o!==-1){let a=t.substring(0,o).trim(),l=t.substring(o+1).trim();if(a&&l){let c=e.filter(d=>d.provider.toLowerCase()===a.toLowerCase()&&d.id.toLowerCase()===l.toLowerCase());if(c.length===1)return c[0];if(c.length>1)return}}let r=e.filter(a=>a.id.toLowerCase()===n);return r.length===1?r[0]:void 0}function FT(i,e){let t=fc(i,e);if(t)return t;let n=e.filter(r=>r.id.toLowerCase().includes(i.toLowerCase())||r.name?.toLowerCase().includes(i.toLowerCase()));if(n.length===0)return;let s=n.filter(r=>Rh(r.id)),o=n.filter(r=>!Rh(r.id));return s.length>0?(s.sort((r,a)=>a.id.localeCompare(r.id)),s[0]):(o.sort((r,a)=>a.id.localeCompare(r.id)),o[0])}function hc(i,e,t){let n=FT(i,e);if(n)return{model:n,thinkingLevel:void 0,warning:void 0};let s=i.lastIndexOf(":");if(s===-1)return{model:void 0,thinkingLevel:void 0,warning:void 0};let o=i.substring(0,s),r=i.substring(s+1);if(uc(r)){let a=hc(o,e,t);return a.model?{model:a.model,thinkingLevel:a.warning?void 0:r,warning:a.warning}:a}else{if(!(t?.allowInvalidThinkingLevelFallback??!0))return{model:void 0,thinkingLevel:void 0,warning:void 0};let l=hc(o,e,t);return l.model?{model:l.model,thinkingLevel:void 0,warning:`Invalid thinking level "${r}" in pattern "${i}". Using default instead.`}:l}}async function Er(i,e){let t=await e.getAvailable(),n=[];for(let s of i){if(s.includes("*")||s.includes("?")||s.includes("[")){let l=s.lastIndexOf(":"),c=s,d;if(l!==-1){let u=s.substring(l+1);uc(u)&&(d=u,c=s.substring(0,l))}let p=t.filter(u=>{let h=`${u.provider}/${u.id}`;return Mh(h,c,{nocase:!0})||Mh(u.id,c,{nocase:!0})});if(p.length===0){console.warn(mc.yellow(`Warning: No models match pattern "${s}"`));continue}for(let u of p)n.find(h=>dt(h.model,u))||n.push({model:u,thinkingLevel:d});continue}let{model:o,thinkingLevel:r,warning:a}=hc(s,t);if(a&&console.warn(mc.yellow(`Warning: ${a}`)),!o){console.warn(mc.yellow(`Warning: No models match pattern "${s}"`));continue}n.find(l=>dt(l.model,o))||n.push({model:o,thinkingLevel:r})}return n}function $T(i){return i?i==="1"||i.toLowerCase()==="true"||i.toLowerCase()==="yes":!1}function xc(i,e=process.env.PI_TELEMETRY){return e!==void 0?$T(e):i.getEnableInstallTelemetry()}var E4=process.env.PI_TIMING==="1";var I4=Date.now();function BT(i){let e=i.sessionFile?`
|
|
303
|
+
Session file: ${i.sessionFile}`:"";return`Stored session working directory does not exist: ${i.sessionCwd}${e}
|
|
304
|
+
Current working directory: ${i.fallbackCwd}`}function bc(i){return`cwd from session file does not exist
|
|
305
|
+
${i.sessionCwd}
|
|
306
|
+
|
|
307
|
+
continue in current cwd
|
|
308
|
+
${i.fallbackCwd}`}var wi=class extends Error{constructor(e){super(BT(e)),this.name="MissingSessionCwdError",this.issue=e}};var Ir=class extends Error{constructor(e){super(`File not found: ${e}`),this.name="SessionImportFileNotFoundError",this.filePath=e}};import W6 from"chalk";import dU from"chalk";import vU from"chalk";import{existsSync as jT,readFileSync as qT}from"fs";import{join as VT}from"path";var Lh={...oo,"app.interrupt":{defaultKeys:"escape",description:"Cancel or abort"},"app.clear":{defaultKeys:"ctrl+c",description:"Clear editor"},"app.exit":{defaultKeys:"ctrl+d",description:"Exit when editor is empty"},"app.suspend":{defaultKeys:process.platform==="win32"?[]:"ctrl+z",description:"Suspend to background"},"app.thinking.cycle":{defaultKeys:"shift+tab",description:"Cycle thinking level"},"app.model.cycleForward":{defaultKeys:"ctrl+p",description:"Cycle to next model"},"app.model.cycleBackward":{defaultKeys:"shift+ctrl+p",description:"Cycle to previous model"},"app.model.select":{defaultKeys:"ctrl+l",description:"Open model selector"},"app.tools.expand":{defaultKeys:"ctrl+o",description:"Toggle tool output"},"app.thinking.toggle":{defaultKeys:"ctrl+t",description:"Toggle thinking blocks"},"app.session.toggleNamedFilter":{defaultKeys:"ctrl+n",description:"Toggle named session filter"},"app.editor.external":{defaultKeys:"ctrl+g",description:"Open external editor"},"app.message.followUp":{defaultKeys:"alt+enter",description:"Queue follow-up message"},"app.message.dequeue":{defaultKeys:"alt+up",description:"Restore queued messages"},"app.clipboard.pasteImage":{defaultKeys:process.platform==="win32"?"alt+v":"ctrl+v",description:"Paste image from clipboard"},"app.session.new":{defaultKeys:[],description:"Start a new session"},"app.session.tree":{defaultKeys:[],description:"Open session tree"},"app.session.fork":{defaultKeys:[],description:"Fork current session"},"app.session.resume":{defaultKeys:[],description:"Resume a session"},"app.tree.foldOrUp":{defaultKeys:["ctrl+left","alt+left"],description:"Fold tree branch or move up"},"app.tree.unfoldOrDown":{defaultKeys:["ctrl+right","alt+right"],description:"Unfold tree branch or move down"},"app.tree.editLabel":{defaultKeys:"shift+l",description:"Edit tree label"},"app.tree.toggleLabelTimestamp":{defaultKeys:"shift+t",description:"Toggle tree label timestamps"},"app.session.togglePath":{defaultKeys:"ctrl+p",description:"Toggle session path display"},"app.session.toggleSort":{defaultKeys:"ctrl+s",description:"Toggle session sort mode"},"app.session.rename":{defaultKeys:"ctrl+r",description:"Rename session"},"app.session.delete":{defaultKeys:"ctrl+d",description:"Delete session"},"app.session.deleteNoninvasive":{defaultKeys:"ctrl+backspace",description:"Delete session when query is empty"},"app.models.save":{defaultKeys:"ctrl+s",description:"Save model selection"},"app.models.enableAll":{defaultKeys:"ctrl+a",description:"Enable all models"},"app.models.clearAll":{defaultKeys:"ctrl+x",description:"Clear all models"},"app.models.toggleProvider":{defaultKeys:"ctrl+p",description:"Toggle all models for provider"},"app.models.reorderUp":{defaultKeys:"alt+up",description:"Move model up in order"},"app.models.reorderDown":{defaultKeys:"alt+down",description:"Move model down in order"},"app.tree.filter.default":{defaultKeys:"ctrl+d",description:"Tree filter: default view"},"app.tree.filter.noTools":{defaultKeys:"ctrl+t",description:"Tree filter: hide tool results"},"app.tree.filter.userOnly":{defaultKeys:"ctrl+u",description:"Tree filter: user messages only"},"app.tree.filter.labeledOnly":{defaultKeys:"ctrl+l",description:"Tree filter: labeled entries only"},"app.tree.filter.all":{defaultKeys:"ctrl+a",description:"Tree filter: show all entries"},"app.tree.filter.cycleForward":{defaultKeys:"ctrl+o",description:"Tree filter: cycle forward"},"app.tree.filter.cycleBackward":{defaultKeys:"shift+ctrl+o",description:"Tree filter: cycle backward"}},Wh={cursorUp:"tui.editor.cursorUp",cursorDown:"tui.editor.cursorDown",cursorLeft:"tui.editor.cursorLeft",cursorRight:"tui.editor.cursorRight",cursorWordLeft:"tui.editor.cursorWordLeft",cursorWordRight:"tui.editor.cursorWordRight",cursorLineStart:"tui.editor.cursorLineStart",cursorLineEnd:"tui.editor.cursorLineEnd",jumpForward:"tui.editor.jumpForward",jumpBackward:"tui.editor.jumpBackward",pageUp:"tui.editor.pageUp",pageDown:"tui.editor.pageDown",deleteCharBackward:"tui.editor.deleteCharBackward",deleteCharForward:"tui.editor.deleteCharForward",deleteWordBackward:"tui.editor.deleteWordBackward",deleteWordForward:"tui.editor.deleteWordForward",deleteToLineStart:"tui.editor.deleteToLineStart",deleteToLineEnd:"tui.editor.deleteToLineEnd",yank:"tui.editor.yank",yankPop:"tui.editor.yankPop",undo:"tui.editor.undo",newLine:"tui.input.newLine",submit:"tui.input.submit",tab:"tui.input.tab",copy:"tui.input.copy",selectUp:"tui.select.up",selectDown:"tui.select.down",selectPageUp:"tui.select.pageUp",selectPageDown:"tui.select.pageDown",selectConfirm:"tui.select.confirm",selectCancel:"tui.select.cancel",interrupt:"app.interrupt",clear:"app.clear",exit:"app.exit",suspend:"app.suspend",cycleThinkingLevel:"app.thinking.cycle",cycleModelForward:"app.model.cycleForward",cycleModelBackward:"app.model.cycleBackward",selectModel:"app.model.select",expandTools:"app.tools.expand",toggleThinking:"app.thinking.toggle",toggleSessionNamedFilter:"app.session.toggleNamedFilter",externalEditor:"app.editor.external",followUp:"app.message.followUp",dequeue:"app.message.dequeue",pasteImage:"app.clipboard.pasteImage",newSession:"app.session.new",tree:"app.session.tree",fork:"app.session.fork",resume:"app.session.resume",treeFoldOrUp:"app.tree.foldOrUp",treeUnfoldOrDown:"app.tree.unfoldOrDown",treeEditLabel:"app.tree.editLabel",treeToggleLabelTimestamp:"app.tree.toggleLabelTimestamp",toggleSessionPath:"app.session.togglePath",toggleSessionSort:"app.session.toggleSort",renameSession:"app.session.rename",deleteSession:"app.session.delete",deleteSessionNoninvasive:"app.session.deleteNoninvasive"};function Oh(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function QT(i){return i in Wh}function JT(i){if(!Oh(i))return{};let e={};for(let[t,n]of Object.entries(i)){if(typeof n=="string"){e[t]=n;continue}Array.isArray(n)&&n.every(s=>typeof s=="string")&&(e[t]=n)}return e}function Uh(i){let e={},t=!1;for(let[n,s]of Object.entries(i)){let o=QT(n)?Wh[n]:n;if(o!==n&&(t=!0),n!==o&&Object.hasOwn(i,o)){t=!0;continue}e[o]=s}return{config:YT(e),migrated:t}}function YT(i){let e={};for(let n of Object.keys(Lh))Object.hasOwn(i,n)&&(e[n]=i[n]);let t=Object.keys(i).filter(n=>!Object.hasOwn(e,n)).sort();for(let n of t)e[n]=i[n];return e}function XT(i){if(jT(i))try{let e=JSON.parse(qT(i,"utf-8"));return Oh(e)?e:void 0}catch{return}}var en=class i extends $n{constructor(e={},t){super(Lh,e),this.configPath=t}static create(e=ce()){let t=VT(e,"keybindings.json"),n=i.loadFromFile(t);return new i(n,t)}reload(){this.configPath&&this.setUserBindings(i.loadFromFile(this.configPath))}getEffectiveConfig(){return this.getResolvedBindings()}static loadFromFile(e){let t=XT(e);return t?JT(Uh(t).config):{}}};import{spawnSync as nC}from"node:child_process";import{existsSync as iC}from"node:fs";import{unlink as sC}from"node:fs/promises";import*as Nh from"node:os";var O=class{constructor(e=t=>f.fg("border",t)){this.color=e}invalidate(){}render(e){return[this.color("\u2500".repeat(Math.max(1,e)))]}};function Dh(i){return i.toLowerCase().replace(/\s+/g," ").trim()}function ZT(i){return`${i.id} ${i.name??""} ${i.allMessagesText} ${i.cwd}`}function yc(i){return!!i.name?.trim()}function eC(i,e){return e==="all"?!0:yc(i)}function tC(i){let e=i.trim();if(!e)return{mode:"tokens",tokens:[],regex:null};if(e.startsWith("re:")){let a=e.slice(3).trim();if(!a)return{mode:"regex",tokens:[],regex:null,error:"Empty regex"};try{return{mode:"regex",tokens:[],regex:new RegExp(a,"i")}}catch(l){let c=l instanceof Error?l.message:String(l);return{mode:"regex",tokens:[],regex:null,error:c}}}let t=[],n="",s=!1,o=!1,r=a=>{let l=n.trim();n="",l&&t.push({kind:a,value:l})};for(let a=0;a<e.length;a++){let l=e[a];if(l==='"'){s?(r("phrase"),s=!1):(r("fuzzy"),s=!0);continue}if(!s&&/\s/.test(l)){r("fuzzy");continue}n+=l}return s&&(o=!0),o?{mode:"tokens",tokens:e.split(/\s+/).map(a=>a.trim()).filter(a=>a.length>0).map(a=>({kind:"fuzzy",value:a})),regex:null}:(r(s?"phrase":"fuzzy"),{mode:"tokens",tokens:t,regex:null})}function Fh(i,e){let t=ZT(i);if(e.mode==="regex"){if(!e.regex)return{matches:!1,score:0};let o=t.search(e.regex);return o<0?{matches:!1,score:0}:{matches:!0,score:o*.1}}if(e.tokens.length===0)return{matches:!0,score:0};let n=0,s=null;for(let o of e.tokens){if(o.kind==="phrase"){s===null&&(s=Dh(t));let a=Dh(o.value);if(!a)continue;let l=s.indexOf(a);if(l<0)return{matches:!1,score:0};n+=l*.1;continue}let r=Js(o.value,t);if(!r.matches)return{matches:!1,score:0};n+=r.score}return{matches:!0,score:n}}function $h(i,e,t,n="all"){let s=n==="all"?i:i.filter(l=>eC(l,n));if(!e.trim())return s;let r=tC(e);if(r.error)return[];if(t==="recent"){let l=[];for(let c of s)Fh(c,r).matches&&l.push(c);return l}let a=[];for(let l of s){let c=Fh(l,r);c.matches&&a.push({session:l,score:c.score})}return a.sort((l,c)=>l.score!==c.score?l.score-c.score:c.session.modified.getTime()-l.session.modified.getTime()),a.map(l=>l.session)}function Bh(i){let e=Nh.homedir();return i&&(i.startsWith(e)?`~${i.slice(e.length)}`:i)}function oC(i){let t=new Date().getTime()-i.getTime(),n=Math.floor(t/6e4),s=Math.floor(t/36e5),o=Math.floor(t/864e5);return n<1?"now":n<60?`${n}m`:s<24?`${s}h`:o<7?`${o}d`:o<30?`${Math.floor(o/7)}w`:o<365?`${Math.floor(o/30)}mo`:`${Math.floor(o/365)}y`}function Ns(i){return i&&li(i)}var wc=class{constructor(e,t,n,s){this.loading=!1;this.loadProgress=null;this.showPath=!1;this.confirmingDeletePath=null;this.statusMessage=null;this.statusTimeout=null;this.showRenameHint=!1;this.scope=e,this.sortMode=t,this.nameFilter=n,this.requestRender=s}setScope(e){this.scope=e}setSortMode(e){this.sortMode=e}setNameFilter(e){this.nameFilter=e}setLoading(e){this.loading=e,this.loadProgress=null}setProgress(e,t){this.loadProgress={loaded:e,total:t}}setShowPath(e){this.showPath=e}setShowRenameHint(e){this.showRenameHint=e}setConfirmingDeletePath(e){this.confirmingDeletePath=e}clearStatusTimeout(){this.statusTimeout&&(clearTimeout(this.statusTimeout),this.statusTimeout=null)}setStatusMessage(e,t){this.clearStatusTimeout(),this.statusMessage=e,!(!e||!t)&&(this.statusTimeout=setTimeout(()=>{this.statusMessage=null,this.statusTimeout=null,this.requestRender()},t))}invalidate(){}render(e){let t=this.scope==="current"?"Resume Session (Current Folder)":"Resume Session (All)",n=f.bold(t),s=this.sortMode==="threaded"?"Threaded":this.sortMode==="recent"?"Recent":"Fuzzy",o=f.fg("muted","Sort: ")+f.fg("accent",s),r=this.nameFilter==="all"?"All":"Named",a=f.fg("muted","Name: ")+f.fg("accent",r),l;if(this.loading){let g=this.loadProgress?`${this.loadProgress.loaded}/${this.loadProgress.total}`:"...";l=`${f.fg("muted","\u25CB Current Folder | ")}${f.fg("accent",`Loading ${g}`)}`}else this.scope==="current"?l=`${f.fg("accent","\u25C9 Current Folder")}${f.fg("muted"," | \u25CB All")}`:l=`${f.fg("muted","\u25CB Current Folder | ")}${f.fg("accent","\u25C9 All")}`;let c=G(`${l} ${a} ${o}`,e,""),d=Math.max(0,e-W(c)-1),p=G(n,d,""),u=Math.max(0,e-W(p)-W(c)),h,m;if(this.confirmingDeletePath!==null){let g=`Delete session? ${N("tui.select.confirm","confirm")} \xB7 ${N("tui.select.cancel","cancel")}`;h=f.fg("error",G(g,e,"\u2026")),m=""}else if(this.statusMessage){let g=this.statusMessage.type==="error"?"error":"accent";h=f.fg(g,G(this.statusMessage.message,e,"\u2026")),m=""}else{let g=this.showPath?"(on)":"(off)",x=f.fg("muted"," \xB7 "),b=N("tui.input.tab","scope")+x+f.fg("muted",'re:<pattern> regex \xB7 "phrase" exact'),v=[N("app.session.toggleSort","sort"),N("app.session.toggleNamedFilter","named"),N("app.session.delete","delete"),N("app.session.togglePath",`path ${g}`)];this.showRenameHint&&v.push(N("app.session.rename","rename"));let w=v.join(x);h=G(b,e,"\u2026"),m=G(w,e,"\u2026")}return[`${p}${" ".repeat(u)}${c}`,h,m]}};function rC(i){let e=new Map;for(let s of i){let o=Ns(s.path)??s.path;e.set(o,{session:s,children:[]})}let t=[];for(let s of i){let o=Ns(s.path)??s.path,r=e.get(o),a=Ns(s.parentSessionPath);a&&e.has(a)?e.get(a).children.push(r):t.push(r)}let n=s=>{s.sort((o,r)=>r.session.modified.getTime()-o.session.modified.getTime());for(let o of s)n(o.children)};return n(t),t}function aC(i){let e=[],t=(n,s,o,r)=>{e.push({session:n.session,depth:s,isLast:r,ancestorContinues:o});for(let a=0;a<n.children.length;a++){let l=a===n.children.length-1,c=s>0?!r:!1;t(n.children[a],s+1,[...o,c],l)}};for(let n=0;n<i.length;n++)t(i[n],0,[],n===i.length-1);return e}var kc=class{constructor(e,t,n,s,o,r){this.allSessions=[];this.filteredSessions=[];this.selectedIndex=0;this.showCwd=!1;this.sortMode="threaded";this.nameFilter="all";this.showPath=!1;this.confirmingDeletePath=null;this.onExit=()=>{};this.maxVisible=10;this._focused=!1;this.allSessions=e,this.filteredSessions=[],this.searchInput=new pe,this.showCwd=t,this.sortMode=n,this.nameFilter=s,this.keybindings=o,this.currentSessionCanonicalPath=Ns(r),this.filterSessions(""),this.searchInput.onSubmit=()=>{if(this.filteredSessions[this.selectedIndex]){let a=this.filteredSessions[this.selectedIndex];this.onSelect&&this.onSelect(a.session.path)}}}getSelectedSessionPath(){return this.filteredSessions[this.selectedIndex]?.session.path}get focused(){return this._focused}set focused(e){this._focused=e,this.searchInput.focused=e}setSortMode(e){this.sortMode=e,this.filterSessions(this.searchInput.getValue())}setNameFilter(e){this.nameFilter=e,this.filterSessions(this.searchInput.getValue())}setSessions(e,t){this.allSessions=e,this.showCwd=t,this.filterSessions(this.searchInput.getValue())}filterSessions(e){let t=e.trim(),n=this.nameFilter==="all"?this.allSessions:this.allSessions.filter(s=>yc(s));if(this.sortMode==="threaded"&&!t){let s=rC(n);this.filteredSessions=aC(s)}else{let s=$h(n,e,this.sortMode,"all");this.filteredSessions=s.map(o=>({session:o,depth:0,isLast:!0,ancestorContinues:[]}))}this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredSessions.length-1))}setConfirmingDeletePath(e){this.confirmingDeletePath=e,this.onDeleteConfirmationChange?.(e)}startDeleteConfirmationForSelectedSession(){let e=this.filteredSessions[this.selectedIndex];if(e){if(this.isCurrentSessionPath(e.session.path)){this.onError?.("Cannot delete the currently active session");return}this.setConfirmingDeletePath(e.session.path)}}isCurrentSessionPath(e){return this.currentSessionCanonicalPath?(Ns(e)??e)===this.currentSessionCanonicalPath:!1}invalidate(){}render(e){let t=[];if(t.push(...this.searchInput.render(e)),t.push(""),this.filteredSessions.length===0){let o;if(this.nameFilter==="named"){let r=z("app.session.toggleNamedFilter");this.showCwd?o=` No named sessions found. Press ${r} to show all.`:o=` No named sessions in current folder. Press ${r} to show all, or Tab to view all.`}else this.showCwd?o=" No sessions found":o=" No sessions in current folder. Press Tab to view all.";return t.push(f.fg("muted",G(o,e,"\u2026"))),t}let n=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredSessions.length-this.maxVisible)),s=Math.min(n+this.maxVisible,this.filteredSessions.length);for(let o=n;o<s;o++){let r=this.filteredSessions[o],a=r.session,l=o===this.selectedIndex,c=a.path===this.confirmingDeletePath,d=this.isCurrentSessionPath(a.path),p=this.buildTreePrefix(r),u=!!a.name,m=(a.name??a.firstMessage).replace(/[\x00-\x1f\x7f]/g," ").trim(),g=oC(a.modified),b=`${String(a.messageCount)} ${g}`;this.showCwd&&a.cwd&&(b=`${Bh(a.cwd)} ${b}`),this.showPath&&(b=`${Bh(a.path)} ${b}`);let v=l?f.fg("accent","\u203A "):" ",w=W(p),C=W(b)+2,R=e-2-w-C,k=G(m,Math.max(10,R),"\u2026"),A=null;c?A="error":d?A="accent":u&&(A="warning");let S=A?f.fg(A,k):k;l&&(S=f.bold(S));let I=v+f.fg("dim",p)+S,P=W(I),M=Math.max(1,e-P-W(b)),_=f.fg(c?"error":"dim",b),U=I+" ".repeat(M)+_;l&&(U=f.bg("selectedBg",U)),t.push(G(U,e))}if(n>0||s<this.filteredSessions.length){let o=` (${this.selectedIndex+1}/${this.filteredSessions.length})`,r=f.fg("muted",G(o,e,""));t.push(r)}return t}buildTreePrefix(e){if(e.depth===0)return"";let t=e.ancestorContinues.map(s=>s?"\u2502 ":" "),n=e.isLast?"\u2514\u2500 ":"\u251C\u2500 ";return t.join("")+n}handleInput(e){let t=V();if(this.confirmingDeletePath!==null){if(t.matches(e,"tui.select.confirm")){let n=this.confirmingDeletePath;this.setConfirmingDeletePath(null),this.onDeleteSession?.(n);return}if(t.matches(e,"tui.select.cancel")){this.setConfirmingDeletePath(null);return}return}if(t.matches(e,"tui.input.tab")){this.onToggleScope&&this.onToggleScope();return}if(t.matches(e,"app.session.toggleSort")){this.onToggleSort?.();return}if(this.keybindings.matches(e,"app.session.toggleNamedFilter")){this.onToggleNameFilter?.();return}if(t.matches(e,"app.session.togglePath")){this.showPath=!this.showPath,this.onTogglePath?.(this.showPath);return}if(t.matches(e,"app.session.delete")){this.startDeleteConfirmationForSelectedSession();return}if(t.matches(e,"app.session.rename")){let n=this.filteredSessions[this.selectedIndex];n&&this.onRenameSession?.(n.session.path);return}if(t.matches(e,"app.session.deleteNoninvasive")){if(this.searchInput.getValue().length>0){this.searchInput.handleInput(e),this.filterSessions(this.searchInput.getValue());return}this.startDeleteConfirmationForSelectedSession();return}if(t.matches(e,"tui.select.up"))this.selectedIndex=Math.max(0,this.selectedIndex-1);else if(t.matches(e,"tui.select.down"))this.selectedIndex=Math.min(this.filteredSessions.length-1,this.selectedIndex+1);else if(t.matches(e,"tui.select.pageUp"))this.selectedIndex=Math.max(0,this.selectedIndex-this.maxVisible);else if(t.matches(e,"tui.select.pageDown"))this.selectedIndex=Math.min(this.filteredSessions.length-1,this.selectedIndex+this.maxVisible);else if(t.matches(e,"tui.select.confirm")){let n=this.filteredSessions[this.selectedIndex];n&&this.onSelect&&this.onSelect(n.session.path)}else t.matches(e,"tui.select.cancel")?this.onCancel&&this.onCancel():(this.searchInput.handleInput(e),this.filterSessions(this.searchInput.getValue()))}};async function lC(i){let e=i.startsWith("-")?["--",i]:[i],t=nC("trash",e,{encoding:"utf-8"}),n=()=>{let s=[];t.error&&s.push(t.error.message);let o=t.stderr?.trim();return o&&s.push(o.split(`
|
|
309
|
+
`)[0]??o),s.length===0?null:`trash: ${s.join(" \xB7 ").slice(0,200)}`};if(t.status===0||!iC(i))return{ok:!0,method:"trash"};try{return await sC(i),{ok:!0,method:"unlink"}}catch(s){let o=s instanceof Error?s.message:String(s),r=n();return{ok:!1,method:"unlink",error:r?`${o} (${r})`:o}}}var Wn=class extends L{constructor(t,n,s,o,r,a,l,c){super();this.canRename=!0;this.scope="current";this.sortMode="threaded";this.nameFilter="all";this.currentSessions=null;this.allSessions=null;this.currentLoading=!1;this.allLoading=!1;this.allLoadSeq=0;this.mode="list";this.renameInput=new pe;this.renameTargetPath=null;this._focused=!1;this.keybindings=l?.keybindings??en.create(),this.currentSessionsLoader=t,this.allSessionsLoader=n,this.onCancel=o,this.requestRender=a,this.header=new wc(this.scope,this.sortMode,this.nameFilter,this.requestRender);let d=l?.renameSession;this.renameSession=d,this.canRename=!!d,this.header.setShowRenameHint(l?.showRenameHint??this.canRename),this.sessionList=new kc([],!1,this.sortMode,this.nameFilter,this.keybindings,c),this.buildBaseLayout(this.sessionList),this.renameInput.onSubmit=u=>{this.confirmRename(u)};let p=()=>this.header.setStatusMessage(null);this.sessionList.onSelect=u=>{p(),s(u)},this.sessionList.onCancel=()=>{p(),o()},this.sessionList.onExit=()=>{p(),r()},this.sessionList.onToggleScope=()=>this.toggleScope(),this.sessionList.onToggleSort=()=>this.toggleSortMode(),this.sessionList.onToggleNameFilter=()=>this.toggleNameFilter(),this.sessionList.onRenameSession=u=>{if(!d||this.scope==="current"&&this.currentLoading||this.scope==="all"&&this.allLoading)return;let m=(this.scope==="all"?this.allSessions??[]:this.currentSessions??[]).find(g=>g.path===u);this.enterRenameMode(u,m?.name)},this.sessionList.onTogglePath=u=>{this.header.setShowPath(u),this.requestRender()},this.sessionList.onDeleteConfirmationChange=u=>{this.header.setConfirmingDeletePath(u),this.requestRender()},this.sessionList.onError=u=>{this.header.setStatusMessage({type:"error",message:u},3e3),this.requestRender()},this.sessionList.onDeleteSession=async u=>{let h=await lC(u);if(h.ok){this.currentSessions&&(this.currentSessions=this.currentSessions.filter(b=>b.path!==u)),this.allSessions&&(this.allSessions=this.allSessions.filter(b=>b.path!==u));let m=this.scope==="all"?this.allSessions??[]:this.currentSessions??[],g=this.scope==="all";this.sessionList.setSessions(m,g);let x=h.method==="trash"?"Session moved to trash":"Session deleted";this.header.setStatusMessage({type:"info",message:x},2e3),await this.refreshSessionsAfterMutation()}else{let m=h.error??"Unknown error";this.header.setStatusMessage({type:"error",message:`Failed to delete: ${m}`},3e3)}this.requestRender()},this.loadCurrentSessions()}handleInput(t){if(this.mode==="rename"){if(V().matches(t,"tui.select.cancel")){this.exitRenameMode();return}this.renameInput.handleInput(t);return}this.sessionList.handleInput(t)}get focused(){return this._focused}set focused(t){this._focused=t,this.sessionList.focused=t,this.renameInput.focused=t,t&&this.mode==="rename"&&(this.renameInput.focused=!0)}buildBaseLayout(t,n){this.clear(),this.addChild(new E(1)),this.addChild(new O(s=>f.fg("accent",s))),this.addChild(new E(1)),(n?.showHeader??!0)&&(this.addChild(this.header),this.addChild(new E(1))),this.addChild(t),this.addChild(new E(1)),this.addChild(new O(s=>f.fg("accent",s)))}loadCurrentSessions(){this.loadScope("current","initial")}enterRenameMode(t,n){this.mode="rename",this.renameTargetPath=t,this.renameInput.setValue(n??""),this.renameInput.focused=!0;let s=new L;s.addChild(new T(f.bold("Rename Session"),1,0)),s.addChild(new E(1)),s.addChild(this.renameInput),s.addChild(new E(1)),s.addChild(new T(f.fg("muted",`${z("tui.select.confirm")} to save \xB7 ${z("tui.select.cancel")} to cancel`),1,0)),this.buildBaseLayout(s,{showHeader:!1}),this.requestRender()}exitRenameMode(){this.mode="list",this.renameTargetPath=null,this.buildBaseLayout(this.sessionList),this.requestRender()}async confirmRename(t){let n=t.trim();if(!n)return;let s=this.renameTargetPath;if(!s){this.exitRenameMode();return}let o=this.renameSession;if(!o){this.exitRenameMode();return}try{await o(s,n),await this.refreshSessionsAfterMutation()}finally{this.exitRenameMode()}}async loadScope(t,n){let s=t==="all";t==="current"?this.currentLoading=!0:this.allLoading=!0;let o=t==="all"?++this.allLoadSeq:void 0;this.header.setScope(t),this.header.setLoading(!0),this.requestRender();let r=(a,l)=>{t===this.scope&&(o!==void 0&&o!==this.allLoadSeq||(this.header.setProgress(a,l),this.requestRender()))};try{let a=await(t==="current"?this.currentSessionsLoader(r):this.allSessionsLoader(r));if(t==="current"?(this.currentSessions=a,this.currentLoading=!1):(this.allSessions=a,this.allLoading=!1),t!==this.scope||o!==void 0&&o!==this.allLoadSeq)return;this.header.setLoading(!1),this.sessionList.setSessions(a,s),this.requestRender(),t==="all"&&a.length===0&&(this.currentSessions?.length??0)===0&&this.onCancel()}catch(a){if(t==="current"?this.currentLoading=!1:this.allLoading=!1,t!==this.scope||o!==void 0&&o!==this.allLoadSeq)return;let l=a instanceof Error?a.message:String(a);this.header.setLoading(!1),this.header.setStatusMessage({type:"error",message:`Failed to load sessions: ${l}`},4e3),n==="initial"&&this.sessionList.setSessions([],s),this.requestRender()}}toggleSortMode(){this.sortMode=this.sortMode==="threaded"?"recent":this.sortMode==="recent"?"relevance":"threaded",this.header.setSortMode(this.sortMode),this.sessionList.setSortMode(this.sortMode),this.requestRender()}toggleNameFilter(){this.nameFilter=this.nameFilter==="all"?"named":"all",this.header.setNameFilter(this.nameFilter),this.sessionList.setNameFilter(this.nameFilter),this.requestRender()}async refreshSessionsAfterMutation(){await this.loadScope(this.scope,"refresh")}toggleScope(){if(this.scope==="current"){if(this.scope="all",this.header.setScope(this.scope),this.allSessions!==null){this.header.setLoading(!1),this.sessionList.setSessions(this.allSessions,!0),this.requestRender();return}this.allLoading||this.loadScope("all","toggle");return}this.scope="current",this.header.setScope(this.scope),this.header.setLoading(this.currentLoading),this.sessionList.setSessions(this.currentSessions??[],!1),this.requestRender()}getSessionList(){return this.sessionList}};import qU from"chalk";import*as vg from"node:crypto";import*as ft from"node:fs";import*as Gi from"node:os";import*as se from"node:path";import{spawn as fg,spawnSync as xg}from"child_process";import{execFile as cC,spawnSync as pC}from"child_process";import{existsSync as ki,readFileSync as Ar,statSync as dC,unwatchFile as uC,watchFile as mC}from"fs";import{dirname as zh,join as Si,resolve as Gh}from"path";function Kh(i){let e=i;for(;;){let t=Si(e,".git");if(ki(t))try{let s=dC(t);if(s.isFile()){let o=Ar(t,"utf8").trim();if(o.startsWith("gitdir: ")){let r=Gh(e,o.slice(8).trim()),a=Si(r,"HEAD");if(!ki(a))return null;let l=Si(r,"commondir"),c=ki(l)?Gh(r,Ar(l,"utf8").trim()):r;return{repoDir:e,commonGitDir:c,headPath:a}}}else if(s.isDirectory()){let o=Si(t,"HEAD");return ki(o)?{repoDir:e,commonGitDir:t,headPath:o}:null}}catch{return null}let n=zh(e);if(n===e)return null;e=n}}function hC(i){let e=pC("git",["--no-optional-locks","symbolic-ref","--quiet","--short","HEAD"],{cwd:i,encoding:"utf8",stdio:["ignore","pipe","ignore"]});return(e.status===0?e.stdout.trim():"")||null}function gC(i){return new Promise(e=>{cC("git",["--no-optional-locks","symbolic-ref","--quiet","--short","HEAD"],{cwd:i,encoding:"utf8"},(t,n)=>{if(t){e(null);return}let s=n.trim();e(s||null)})})}var Pr=class i{constructor(e){this.extensionStatuses=new Map;this.cachedBranch=void 0;this.gitPaths=void 0;this.headWatcher=null;this.reftableWatcher=null;this.reftableTablesListWatcher=null;this.reftableTablesListPath=null;this.branchChangeCallbacks=new Set;this.availableProviderCount=0;this.refreshTimer=null;this.gitWatcherRetryTimer=null;this.refreshInFlight=!1;this.refreshPending=!1;this.disposed=!1;this.cwd=e,this.gitPaths=Kh(e),this.setupGitWatcher()}static{this.WATCH_DEBOUNCE_MS=500}getGitBranch(){return this.cachedBranch===void 0&&(this.cachedBranch=this.resolveGitBranchSync()),this.cachedBranch}getExtensionStatuses(){return this.extensionStatuses}onBranchChange(e){return this.branchChangeCallbacks.add(e),()=>this.branchChangeCallbacks.delete(e)}setExtensionStatus(e,t){t===void 0?this.extensionStatuses.delete(e):this.extensionStatuses.set(e,t)}clearExtensionStatuses(){this.extensionStatuses.clear()}getAvailableProviderCount(){return this.availableProviderCount}setAvailableProviderCount(e){this.availableProviderCount=e}setCwd(e){this.cwd!==e&&(this.cwd=e,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),this.clearGitWatchers(),this.cachedBranch=void 0,this.gitPaths=Kh(e),this.setupGitWatcher(),this.notifyBranchChange())}dispose(){this.disposed=!0,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),this.clearGitWatchers(),this.branchChangeCallbacks.clear()}notifyBranchChange(){for(let e of this.branchChangeCallbacks)e()}scheduleRefresh(){if(!(this.disposed||this.refreshTimer)){if(this.refreshInFlight){this.refreshPending=!0;return}this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.refreshGitBranchAsync()},i.WATCH_DEBOUNCE_MS)}}async refreshGitBranchAsync(){if(!this.disposed){if(this.refreshInFlight){this.refreshPending=!0;return}this.refreshInFlight=!0;try{let e=await this.resolveGitBranchAsync();if(this.disposed)return;if(this.cachedBranch!==void 0&&this.cachedBranch!==e){this.cachedBranch=e,this.notifyBranchChange();return}this.cachedBranch=e}finally{this.refreshInFlight=!1,this.refreshPending&&!this.disposed&&(this.refreshPending=!1,this.scheduleRefresh())}}}resolveGitBranchSync(){try{if(!this.gitPaths)return null;let e=Ar(this.gitPaths.headPath,"utf8").trim();if(e.startsWith("ref: refs/heads/")){let t=e.slice(16);return t===".invalid"?hC(this.gitPaths.repoDir)??"detached":t}return"detached"}catch{return null}}async resolveGitBranchAsync(){try{if(!this.gitPaths)return null;let e=Ar(this.gitPaths.headPath,"utf8").trim();if(e.startsWith("ref: refs/heads/")){let t=e.slice(16);return t===".invalid"?await gC(this.gitPaths.repoDir)??"detached":t}return"detached"}catch{return null}}clearGitWatchers(){vn(this.headWatcher),this.headWatcher=null,vn(this.reftableWatcher),this.reftableWatcher=null,vn(this.reftableTablesListWatcher),this.reftableTablesListWatcher=null,this.reftableTablesListPath&&(uC(this.reftableTablesListPath),this.reftableTablesListPath=null),this.gitWatcherRetryTimer&&(clearTimeout(this.gitWatcherRetryTimer),this.gitWatcherRetryTimer=null)}scheduleGitWatcherRetry(){this.disposed||this.gitWatcherRetryTimer||(this.gitWatcherRetryTimer=setTimeout(()=>{this.gitWatcherRetryTimer=null,this.setupGitWatcher()},Ou))}handleGitWatcherError(){this.clearGitWatchers(),this.scheduleGitWatcherRetry()}setupGitWatcher(){if(this.clearGitWatchers(),!this.gitPaths||(this.headWatcher=Zn(zh(this.gitPaths.headPath),(t,n)=>{(!n||n==="HEAD")&&this.scheduleRefresh()},()=>this.handleGitWatcherError()),!this.headWatcher))return;let e=Si(this.gitPaths.commonGitDir,"reftable");if(ki(e)){if(this.reftableWatcher=Zn(e,()=>{this.scheduleRefresh()},()=>this.handleGitWatcherError()),!this.reftableWatcher)return;let t=Si(e,"tables.list");if(ki(t)){if(this.reftableTablesListPath=t,this.reftableTablesListWatcher=Zn(t,()=>{this.scheduleRefresh()},()=>this.handleGitWatcherError()),!this.reftableTablesListWatcher)return;mC(t,{interval:250},(n,s)=>{(n.mtimeMs!==s.mtimeMs||n.ctimeMs!==s.ctimeMs||n.size!==s.size)&&this.scheduleRefresh()})}}}};var Sc=[{name:"settings",description:"Open settings menu"},{name:"model",description:"Select model (opens selector UI)"},{name:"scoped-models",description:"Enable/disable models for Ctrl+P cycling"},{name:"export",description:"Export session (HTML default, or specify path: .html/.jsonl)"},{name:"import",description:"Import and resume a session from a JSONL file"},{name:"share",description:"Share session as a secret GitHub gist"},{name:"copy",description:"Copy last agent message to clipboard"},{name:"name",description:"Set session display name"},{name:"session",description:"Show session info and stats"},{name:"changelog",description:"Show changelog entries"},{name:"hotkeys",description:"Show all keyboard shortcuts"},{name:"fork",description:"Create a new fork from a previous user message"},{name:"clone",description:"Duplicate the current session at the current position"},{name:"tree",description:"Navigate session tree (switch branches)"},{name:"login",description:"Configure provider authentication"},{name:"logout",description:"Remove provider authentication"},{name:"new",description:"Start a new session"},{name:"compact",description:"Manually compact the session context"},{name:"resume",description:"Resume a different session"},{name:"reload",description:"Reload keybindings, extensions, skills, prompts, and themes"},{name:"quit",description:`Quit ${Ae}`}];import{existsSync as fC,readFileSync as xC}from"fs";function Tc(i){if(!fC(i))return[];try{let t=xC(i,"utf-8").split(`
|
|
310
|
+
`),n=[],s=[],o=null;for(let r of t)if(r.startsWith("## ")){o&&s.length>0&&n.push({...o,content:s.join(`
|
|
311
|
+
`).trim()});let a=r.match(/##\s+\[?(\d+)\.(\d+)\.(\d+)\]?/);a?(o={major:Number.parseInt(a[1],10),minor:Number.parseInt(a[2],10),patch:Number.parseInt(a[3],10)},s=[r]):(o=null,s=[])}else o&&s.push(r);return o&&s.length>0&&n.push({...o,content:s.join(`
|
|
312
|
+
`).trim()}),n}catch(e){return console.error(`Warning: Could not parse changelog: ${e}`),[]}}function bC(i,e){return i.major!==e.major?i.major-e.major:i.minor!==e.minor?i.minor-e.minor:i.patch-e.patch}function Hh(i,e){let t=e.split(".").map(Number),n={major:t[0]||0,minor:t[1]||0,patch:t[2]||0,content:""};return i.filter(s=>bC(s,n)>0)}import{execSync as Ci,spawn as UC}from"child_process";import{platform as DC}from"os";import{spawnSync as kC}from"child_process";import{randomUUID as SC}from"crypto";import{readFileSync as qh,unlinkSync as TC}from"fs";import{tmpdir as CC}from"os";import{join as MC}from"path";import{createRequire as vC}from"module";var yC=vC(import.meta.url),$t=null,wC=process.platform!=="linux"||!!(process.env.DISPLAY||process.env.WAYLAND_DISPLAY);if(!process.env.TERMUX_VERSION&&wC)try{$t=yC("@mariozechner/clipboard")}catch{$t=null}var _r=["image/png","image/jpeg","image/webp","image/gif"],Cc=1e3,RC=3e3,EC=5e3,IC=50*1024*1024;function Mc(i=process.env){return!!i.WAYLAND_DISPLAY||i.XDG_SESSION_TYPE==="wayland"}function Gs(i){return i.split(";")[0]?.trim().toLowerCase()??i.toLowerCase()}function Vh(i){switch(Gs(i)){case"image/png":return"png";case"image/jpeg":return"jpg";case"image/webp":return"webp";case"image/gif":return"gif";default:return null}}function Qh(i){let e=i.map(n=>n.trim()).filter(Boolean).map(n=>({raw:n,base:Gs(n)}));for(let n of _r){let s=e.find(o=>o.base===n);if(s)return s.raw}return e.find(n=>n.base.startsWith("image/"))?.raw??null}function AC(i){let e=Gs(i);return _r.some(t=>t===e)}async function PC(i){let e=await fi();if(!e)return null;try{let t=e.PhotonImage.new_from_byteslice(i);try{return t.get_bytes()}finally{t.free()}}catch{return null}}function Ti(i,e,t){let n=t?.timeoutMs??RC,s=t?.maxBufferBytes??IC,o=kC(i,e,{timeout:n,maxBuffer:s,env:t?.env});return o.error?{ok:!1,stdout:Buffer.alloc(0)}:o.status!==0?{ok:!1,stdout:Buffer.alloc(0)}:{ok:!0,stdout:Buffer.isBuffer(o.stdout)?o.stdout:Buffer.from(o.stdout??"",typeof o.stdout=="string"?"utf-8":void 0)}}function _C(){let i=Ti("wl-paste",["--list-types"],{timeoutMs:Cc});if(!i.ok)return null;let e=i.stdout.toString("utf-8").split(/\r?\n/).map(s=>s.trim()).filter(Boolean),t=Qh(e);if(!t)return null;let n=Ti("wl-paste",["--type",t,"--no-newline"]);return!n.ok||n.stdout.length===0?null:{bytes:n.stdout,mimeType:Gs(t)}}function LC(i=process.env){if(i.WSL_DISTRO_NAME||i.WSLENV)return!0;try{let e=qh("/proc/version","utf-8");return/microsoft|wsl/i.test(e)}catch{return!1}}function WC(){let i=MC(CC(),`pi-wsl-clip-${SC()}.png`);try{let e=Ti("wslpath",["-w",i],{timeoutMs:Cc});if(!e.ok)return null;let t=e.stdout.toString("utf-8").trim();if(!t)return null;let s=["Add-Type -AssemblyName System.Windows.Forms","Add-Type -AssemblyName System.Drawing",`$path = '${t.replaceAll("'","''")}'`,"$img = [System.Windows.Forms.Clipboard]::GetImage()","if ($img) { $img.Save($path, [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'ok' } else { Write-Output 'empty' }"].join("; "),o=Ti("powershell.exe",["-NoProfile","-Command",s],{timeoutMs:EC});if(!o.ok||o.stdout.toString("utf-8").trim()!=="ok")return null;let a=qh(i);return a.length===0?null:{bytes:new Uint8Array(a),mimeType:"image/png"}}catch{return null}finally{try{TC(i)}catch{}}}function OC(){let i=Ti("xclip",["-selection","clipboard","-t","TARGETS","-o"],{timeoutMs:Cc}),e=[];i.ok&&(e=i.stdout.toString("utf-8").split(/\r?\n/).map(s=>s.trim()).filter(Boolean));let t=e.length>0?Qh(e):null,n=t?[t,..._r]:[..._r];for(let s of n){let o=Ti("xclip",["-selection","clipboard","-t",s,"-o"]);if(o.ok&&o.stdout.length>0)return{bytes:o.stdout,mimeType:Gs(s)}}return null}async function jh(){if(!$t||!$t.hasImage())return null;let i=await $t.getImageBinary();return!i||i.length===0?null:{bytes:i instanceof Uint8Array?i:Uint8Array.from(i),mimeType:"image/png"}}async function Jh(i){let e=i?.env??process.env,t=i?.platform??process.platform;if(e.TERMUX_VERSION)return null;let n=null;if(t==="linux"){let s=LC(e),o=Mc(e);(o||s)&&(n=_C()??OC()),!n&&s&&(n=WC()),!n&&!o&&(n=await jh())}else n=await jh();if(!n)return null;if(!AC(n.mimeType)){let s=await PC(n.bytes);return s?{bytes:s,mimeType:"image/png"}:null}return n}function Yh(i){try{Ci("xclip -selection clipboard",i)}catch{Ci("xsel --clipboard --input",i)}}var FC=1e5;function $C(i=process.env){return!!(i.SSH_CONNECTION||i.SSH_CLIENT||i.MOSH_CONNECTION)}function BC(i){let e=Buffer.from(i).toString("base64");return e.length>FC?!1:(process.stdout.write(`\x1B]52;c;${e}\x07`),!0)}async function Rc(i){let e=!1,t=DC();try{$t&&t!=="linux"&&(await $t.setText(i),e=!0)}catch{}let n=$C();if(e&&!n)return;let s={input:i,timeout:5e3,stdio:["pipe","ignore","ignore"]};if(!e)try{if(t==="darwin")Ci("pbcopy",s),e=!0;else if(t==="win32")Ci("clip",s),e=!0;else{if(process.env.TERMUX_VERSION)try{Ci("termux-clipboard-set",s),e=!0}catch{}if(!e){let o=!!process.env.WAYLAND_DISPLAY,r=!!process.env.DISPLAY;if(Mc()&&o)try{Ci("which wl-copy",{stdio:"ignore"});let l=UC("wl-copy",[],{stdio:["pipe","ignore","ignore"]});l.stdin.on("error",()=>{}),l.stdin.write(i),l.stdin.end(),l.unref(),e=!0}catch{r&&(Yh(s),e=!0)}else r&&(Yh(s),e=!0)}}}catch{}if(n||!e){let o=BC(i);e=e||o}if(!e)throw new Error("Failed to copy to clipboard")}function Lr(i){let e=process.versions.bun?`bun/${process.versions.bun}`:`node/${process.version}`;return`pi/${i} (${process.platform}; ${e}; ${process.arch})`}var NC="https://pi.dev/api/latest-version",GC=1e4;function Xh(i){let e=i.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(e)return{major:Number.parseInt(e[1],10),minor:Number.parseInt(e[2],10),patch:Number.parseInt(e[3],10),prerelease:e[4]}}function KC(i,e){let t=Xh(i),n=Xh(e);if(!(!t||!n))return t.major!==n.major?t.major-n.major:t.minor!==n.minor?t.minor-n.minor:t.patch!==n.patch?t.patch-n.patch:t.prerelease===n.prerelease?0:t.prerelease?n.prerelease?t.prerelease.localeCompare(n.prerelease):-1:1}function Zh(i,e){let t=KC(i,e);return t!==void 0?t>0:i.trim()!==e.trim()}async function eg(i,e={}){if(process.env.PI_SKIP_VERSION_CHECK||process.env.PI_OFFLINE)return;let t=await fetch(NC,{headers:{"User-Agent":Lr(i),accept:"application/json"},signal:AbortSignal.timeout(e.timeoutMs??GC)});if(!t.ok)return;let n=await t.json();if(typeof n.version!="string"||!n.version.trim())return;let s=typeof n.packageName=="string"&&n.packageName.trim()?n.packageName.trim():void 0;return{version:n.version.trim(),packageName:s}}async function zC(i,e={}){return(await eg(i,e))?.version}async function tg(i){try{let e=await zC(i);return e&&Zh(e,i)?e:void 0}catch{return}}var Ve=31,sg=36,HC=[255,255,255,127,255,240,255,127,255,237,255,127,255,219,255,127,255,183,255,127,255,119,254,127,63,248,254,127,223,255,254,127,223,63,252,127,159,195,251,127,111,252,244,127,247,15,247,127,247,255,247,127,247,255,227,127,247,7,232,127,239,248,103,112,15,255,187,111,241,0,208,91,253,63,236,83,193,255,239,87,159,253,238,95,159,252,174,95,31,120,172,95,63,0,80,108,127,0,220,119,255,192,63,120,255,1,248,127,255,3,156,120,255,7,140,124,255,15,206,120,255,255,207,127,255,255,207,120,255,255,223,120,255,255,223,125,255,255,63,126,255,255,255,127],jC=Math.ceil(Ve/8),be=Math.ceil(sg/2),ng=["typewriter","scanline","rain","fade","crt","glitch","dissolve"];function ig(i,e){if(e>=sg)return!1;let t=e*jC+Math.floor(i/8),n=i%8;return(HC[t]>>n&1)===0}function qC(i,e){let t=ig(i,e*2),n=ig(i,e*2+1);return t&&n?"\u2588":t?"\u2580":n?"\u2584":" "}function VC(){let i=[];for(let e=0;e<be;e++){let t=[];for(let n=0;n<Ve;n++)t.push(qC(n,e));i.push(t)}return i}var Mi=class{constructor(e){this.interval=null;this.effectState={};this.cachedLines=[];this.cachedWidth=0;this.gridVersion=0;this.cachedVersion=-1;this.ui=e,this.effect=ng[Math.floor(Math.random()*ng.length)],this.finalGrid=VC(),this.currentGrid=this.createEmptyGrid(),this.initEffect(),this.startAnimation()}invalidate(){this.cachedWidth=0}render(e){if(e===this.cachedWidth&&this.cachedVersion===this.gridVersion)return this.cachedLines;let t=1,n=e-t;this.cachedLines=this.currentGrid.map(r=>{let a=r.slice(0,n).join(""),l=Math.max(0,e-t-a.length);return` ${f.fg("accent",a)}${" ".repeat(l)}`});let s="ARMIN SAYS HI",o=Math.max(0,e-t-s.length);return this.cachedLines.push(` ${f.fg("accent",s)}${" ".repeat(o)}`),this.cachedWidth=e,this.cachedVersion=this.gridVersion,this.cachedLines}createEmptyGrid(){return Array.from({length:be},()=>Array(Ve).fill(" "))}initEffect(){switch(this.effect){case"typewriter":this.effectState={pos:0};break;case"scanline":this.effectState={row:0};break;case"rain":this.effectState={drops:Array.from({length:Ve},()=>({y:-Math.floor(Math.random()*be*2),settled:0}))};break;case"fade":{let e=[];for(let t=0;t<be;t++)for(let n=0;n<Ve;n++)e.push([t,n]);for(let t=e.length-1;t>0;t--){let n=Math.floor(Math.random()*(t+1));[e[t],e[n]]=[e[n],e[t]]}this.effectState={positions:e,idx:0};break}case"crt":this.effectState={expansion:0};break;case"glitch":this.effectState={phase:0,glitchFrames:8};break;case"dissolve":{this.currentGrid=Array.from({length:be},()=>Array.from({length:Ve},()=>{let t=[" ","\u2591","\u2592","\u2593","\u2588","\u2580","\u2584"];return t[Math.floor(Math.random()*t.length)]}));let e=[];for(let t=0;t<be;t++)for(let n=0;n<Ve;n++)e.push([t,n]);for(let t=e.length-1;t>0;t--){let n=Math.floor(Math.random()*(t+1));[e[t],e[n]]=[e[n],e[t]]}this.effectState={positions:e,idx:0};break}}}startAnimation(){let e=this.effect==="glitch"?60:30;this.interval=setInterval(()=>{let t=this.tickEffect();this.updateDisplay(),this.ui.requestRender(),t&&this.stopAnimation()},1e3/e)}stopAnimation(){this.interval&&(clearInterval(this.interval),this.interval=null)}tickEffect(){switch(this.effect){case"typewriter":return this.tickTypewriter();case"scanline":return this.tickScanline();case"rain":return this.tickRain();case"fade":return this.tickFade();case"crt":return this.tickCrt();case"glitch":return this.tickGlitch();case"dissolve":return this.tickDissolve();default:return!0}}tickTypewriter(){let e=this.effectState,t=3;for(let n=0;n<t;n++){let s=Math.floor(e.pos/Ve),o=e.pos%Ve;if(s>=be)return!0;this.currentGrid[s][o]=this.finalGrid[s][o],e.pos++}return!1}tickScanline(){let e=this.effectState;if(e.row>=be)return!0;for(let t=0;t<Ve;t++)this.currentGrid[e.row][t]=this.finalGrid[e.row][t];return e.row++,!1}tickRain(){let e=this.effectState,t=!0;this.currentGrid=this.createEmptyGrid();for(let n=0;n<Ve;n++){let s=e.drops[n];for(let r=be-1;r>=be-s.settled;r--)r>=0&&(this.currentGrid[r][n]=this.finalGrid[r][n]);if(s.settled>=be)continue;t=!1;let o=-1;for(let r=be-1-s.settled;r>=0;r--)if(this.finalGrid[r][n]!==" "){o=r;break}s.y++,s.y>=0&&s.y<be&&(o>=0&&s.y>=o?(s.settled=be-o,s.y=-Math.floor(Math.random()*5)-1):this.currentGrid[s.y][n]="\u2593")}return t}tickFade(){let e=this.effectState,t=15;for(let n=0;n<t;n++){if(e.idx>=e.positions.length)return!0;let[s,o]=e.positions[e.idx];this.currentGrid[s][o]=this.finalGrid[s][o],e.idx++}return!1}tickCrt(){let e=this.effectState,t=Math.floor(be/2);this.currentGrid=this.createEmptyGrid();let n=t-e.expansion,s=t+e.expansion;for(let o=Math.max(0,n);o<=Math.min(be-1,s);o++)for(let r=0;r<Ve;r++)this.currentGrid[o][r]=this.finalGrid[o][r];return e.expansion++,e.expansion>be}tickGlitch(){let e=this.effectState;return e.phase<e.glitchFrames?(this.currentGrid=this.finalGrid.map(t=>{let n=Math.floor(Math.random()*7)-3,s=[...t];if(Math.random()<.3)return s.slice(n).concat(s.slice(0,n)).slice(0,Ve);if(Math.random()<.2){let o=Math.floor(Math.random()*be);return[...this.finalGrid[o]]}return s}),e.phase++,!1):(this.currentGrid=this.finalGrid.map(t=>[...t]),!0)}tickDissolve(){let e=this.effectState,t=20;for(let n=0;n<t;n++){if(e.idx>=e.positions.length)return!0;let[s,o]=e.positions[e.idx];this.currentGrid[s][o]=this.finalGrid[s][o],e.idx++}return!1}updateDisplay(){this.gridVersion++}dispose(){this.stopAnimation()}};var QC="\x1B]133;A\x07",JC="\x1B]133;B\x07",YC="\x1B]133;C\x07",Bt=class extends L{constructor(t,n=!1,s=we(),o="Thinking..."){super();this.hasToolCalls=!1;this.hideThinkingBlock=n,this.markdownTheme=s,this.hiddenThinkingLabel=o,this.contentContainer=new L,this.addChild(this.contentContainer),t&&this.updateContent(t)}invalidate(){super.invalidate(),this.lastMessage&&this.updateContent(this.lastMessage)}setHideThinkingBlock(t){this.hideThinkingBlock=t,this.lastMessage&&this.updateContent(this.lastMessage)}setHiddenThinkingLabel(t){this.hiddenThinkingLabel=t,this.lastMessage&&this.updateContent(this.lastMessage)}render(t){let n=super.render(t);return this.hasToolCalls||n.length===0||(n[0]=QC+n[0],n[n.length-1]=JC+YC+n[n.length-1]),n}updateContent(t){this.lastMessage=t,this.contentContainer.clear();let n=t.content.some(o=>o.type==="text"&&o.text.trim()||o.type==="thinking"&&o.thinking.trim());n&&this.contentContainer.addChild(new E(1));for(let o=0;o<t.content.length;o++){let r=t.content[o];if(r.type==="text"&&r.text.trim())this.contentContainer.addChild(new le(r.text.trim(),1,0,this.markdownTheme));else if(r.type==="thinking"&&r.thinking.trim()){let a=t.content.slice(o+1).some(l=>l.type==="text"&&l.text.trim()||l.type==="thinking"&&l.thinking.trim());this.hideThinkingBlock?(this.contentContainer.addChild(new T(f.italic(f.fg("thinkingText",this.hiddenThinkingLabel)),1,0)),a&&this.contentContainer.addChild(new E(1))):(this.contentContainer.addChild(new le(r.thinking.trim(),1,0,this.markdownTheme,{color:l=>f.fg("thinkingText",l),italic:!0})),a&&this.contentContainer.addChild(new E(1)))}}let s=t.content.some(o=>o.type==="toolCall");if(this.hasToolCalls=s,!s){if(t.stopReason==="aborted"){let o=t.errorMessage&&t.errorMessage!=="Request was aborted"?t.errorMessage:"Operation aborted";n?this.contentContainer.addChild(new E(1)):this.contentContainer.addChild(new E(1)),this.contentContainer.addChild(new T(f.fg("error",o),1,0))}else if(t.stopReason==="error"){let o=t.errorMessage||"Unknown error";this.contentContainer.addChild(new E(1)),this.contentContainer.addChild(new T(f.fg("error",`Error: ${o}`),1,0))}}}};import XC from"strip-ansi";var og=20,tn=class extends L{constructor(t,n,s=!1){super();this.outputLines=[];this.status="running";this.exitCode=void 0;this.expanded=!1;this.command=t;let o=s?"dim":"bashMode",r=l=>f.fg(o,l);this.addChild(new E(1)),this.addChild(new O(r)),this.contentContainer=new L,this.addChild(this.contentContainer);let a=new T(f.fg(o,f.bold(`$ ${t}`)),1,0);this.contentContainer.addChild(a),this.loader=new Fe(n,l=>f.fg(o,l),l=>f.fg("muted",l),`Running... (${z("tui.select.cancel")} to cancel)`),this.contentContainer.addChild(this.loader),this.addChild(new O(r))}setExpanded(t){this.expanded=t,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}appendOutput(t){let s=XC(t).replace(/\r\n/g,`
|
|
313
|
+
`).replace(/\r/g,`
|
|
314
|
+
`).split(`
|
|
315
|
+
`);this.outputLines.length>0&&s.length>0?(this.outputLines[this.outputLines.length-1]+=s[0],this.outputLines.push(...s.slice(1))):this.outputLines.push(...s),this.updateDisplay()}setComplete(t,n,s,o){this.exitCode=t,this.status=n?"cancelled":t!==0&&t!==void 0&&t!==null?"error":"complete",this.truncationResult=s,this.fullOutputPath=o,this.loader.stop(),this.updateDisplay()}updateDisplay(){let t=this.outputLines.join(`
|
|
316
|
+
`),n=Mn(t,{maxLines:2e3,maxBytes:51200}),s=n.content?n.content.split(`
|
|
317
|
+
`):[],o=s.slice(-og),r=s.length-o.length;this.contentContainer.clear();let a=new T(f.fg("bashMode",f.bold(`$ ${this.command}`)),1,0);if(this.contentContainer.addChild(a),s.length>0)if(this.expanded){let l=s.map(c=>f.fg("muted",c)).join(`
|
|
318
|
+
`);this.contentContainer.addChild(new T(`
|
|
319
|
+
${l}`,1,0))}else{let c=`
|
|
320
|
+
${o.map(u=>f.fg("muted",u)).join(`
|
|
321
|
+
`)}`,d,p;this.contentContainer.addChild({render:u=>((p===void 0||d!==u)&&(p=ci(c,og,u,1).visualLines,d=u),p??[]),invalidate:()=>{d=void 0,p=void 0}})}if(this.status==="running")this.contentContainer.addChild(this.loader);else{let l=[];r>0&&(this.expanded?l.push(`(${N("app.tools.expand","to collapse")})`):l.push(`${f.fg("muted",`... ${r} more lines`)} (${N("app.tools.expand","to expand")})`)),this.status==="cancelled"?l.push(f.fg("warning","(cancelled)")):this.status==="error"&&l.push(f.fg("error",`(exit ${this.exitCode})`)),(this.truncationResult?.truncated||n.truncated)&&this.fullOutputPath&&l.push(f.fg("warning",`Output truncated. Full output: ${this.fullOutputPath}`)),l.length>0&&this.contentContainer.addChild(new T(`
|
|
322
|
+
${l.join(`
|
|
323
|
+
`)}`,1,0))}}getOutput(){return this.outputLines.join(`
|
|
324
|
+
`)}getCommand(){return this.command}};var Ri=class extends L{constructor(e,t,n,s){super(),this.cancellable=s?.cancellable??!0;let o=r=>t.fg("border",r);this.addChild(new O(o)),this.cancellable?this.loader=new Ji(e,r=>t.fg("accent",r),r=>t.fg("muted",r),n):(this.signalController=new AbortController,this.loader=new Fe(e,r=>t.fg("accent",r),r=>t.fg("muted",r),n)),this.addChild(this.loader),this.cancellable&&(this.addChild(new E(1)),this.addChild(new T(N("tui.select.cancel","cancel"),1,0))),this.addChild(new E(1)),this.addChild(new O(o))}get signal(){return this.cancellable?this.loader.signal:this.signalController?.signal??new AbortController().signal}set onAbort(e){this.cancellable&&(this.loader.onAbort=e)}handleInput(e){this.cancellable&&this.loader.handleInput(e)}dispose(){"dispose"in this.loader&&typeof this.loader.dispose=="function"?this.loader.dispose():"stop"in this.loader&&typeof this.loader.stop=="function"&&this.loader.stop()}};var Ei=class extends he{constructor(t,n=we()){super(1,1,s=>f.bg("customMessageBg",s));this.expanded=!1;this.message=t,this.markdownTheme=n,this.updateDisplay()}setExpanded(t){this.expanded=t,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}updateDisplay(){this.clear();let t=f.fg("customMessageLabel","\x1B[1m[branch]\x1B[22m");if(this.addChild(new T(t,0,0)),this.addChild(new E(1)),this.expanded){let n=`**Branch Summary**
|
|
325
|
+
|
|
326
|
+
`;this.addChild(new le(n+this.message.summary,0,0,this.markdownTheme,{color:s=>f.fg("customMessageText",s)}))}else this.addChild(new T(f.fg("customMessageText","Branch summary (")+f.fg("dim",z("app.tools.expand"))+f.fg("customMessageText"," to expand)"),0,0))}};var Ii=class extends he{constructor(t,n=we()){super(1,1,s=>f.bg("customMessageBg",s));this.expanded=!1;this.message=t,this.markdownTheme=n,this.updateDisplay()}setExpanded(t){this.expanded=t,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}updateDisplay(){this.clear();let t=this.message.tokensBefore.toLocaleString(),n=f.fg("customMessageLabel","\x1B[1m[compaction]\x1B[22m");if(this.addChild(new T(n,0,0)),this.addChild(new E(1)),this.expanded){let s=`**Compacted from ${t} tokens**
|
|
327
|
+
|
|
328
|
+
`;this.addChild(new le(s+this.message.summary,0,0,this.markdownTheme,{color:o=>f.fg("customMessageText",o)}))}else this.addChild(new T(f.fg("customMessageText",`Compacted from ${t} tokens (`)+f.fg("dim",z("app.tools.expand"))+f.fg("customMessageText"," to expand)"),0,0))}};var nn=class{constructor(e,t,n,s){this.tui=t;this.onTick=n;this.onExpire=s;this.remainingSeconds=Math.ceil(e/1e3),this.onTick(this.remainingSeconds),this.intervalId=setInterval(()=>{this.remainingSeconds--,this.onTick(this.remainingSeconds),this.tui?.requestRender(),this.remainingSeconds<=0&&(this.dispose(),this.onExpire())},1e3)}dispose(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}};var Ai=class extends un{constructor(t,n,s,o){super(t,n,o);this.actionHandlers=new Map;this.keybindings=s}onAction(t,n){this.actionHandlers.set(t,n)}handleInput(t){if(!this.onExtensionShortcut?.(t)){if(this.keybindings.matches(t,"app.clipboard.pasteImage")){this.onPasteImage?.();return}if(this.keybindings.matches(t,"app.interrupt")){if(!this.isShowingAutocomplete()){let n=this.onEscape??this.actionHandlers.get("app.interrupt");if(n){n();return}}super.handleInput(t);return}if(this.keybindings.matches(t,"app.exit")&&this.getText().length===0){let n=this.onCtrlD??this.actionHandlers.get("app.exit");n&&n();return}for(let[n,s]of this.actionHandlers)if(n!=="app.interrupt"&&n!=="app.exit"&&this.keybindings.matches(t,n)){s();return}super.handleInput(t)}}};var Pi=class extends L{constructor(t,n,s=we()){super();this._expanded=!1;this.message=t,this.customRenderer=n,this.markdownTheme=s,this.addChild(new E(1)),this.box=new he(1,1,o=>f.bg("customMessageBg",o)),this.rebuild()}setExpanded(t){this._expanded!==t&&(this._expanded=t,this.rebuild())}invalidate(){super.invalidate(),this.rebuild()}rebuild(){if(this.customComponent&&(this.removeChild(this.customComponent),this.customComponent=void 0),this.removeChild(this.box),this.customRenderer)try{let s=this.customRenderer(this.message,{expanded:this._expanded},f);if(s){this.customComponent=s,this.addChild(s);return}}catch{}this.addChild(this.box),this.box.clear();let t=f.fg("customMessageLabel",`\x1B[1m[${this.message.customType}]\x1B[22m`);this.box.addChild(new T(t,0,0)),this.box.addChild(new E(1));let n;typeof this.message.content=="string"?n=this.message.content:n=this.message.content.filter(s=>s.type==="text").map(s=>s.text).join(`
|
|
329
|
+
`),this.box.addChild(new le(n,0,0,this.markdownTheme,{color:s=>f.fg("customMessageText",s)}))}};var Ec="bbbab8b9b9b6b9b8b5bcbbb8b8b7b4b7b5b2b6b5b2b8b7b4b7b6b3b6b4b1bdbcb8bab8b6bbb8b5b8b5b1bbb8b4c2bebbc1bebac0bdbabfbcb9c1bebabfbebbc0bfbcc0bdbabbb8b5c1bfbcbfbcb8bbb9b6bfbcb8c2bfbcc1bfbcbfbbb8bdb9b6b8b7b5b9b8b5b8b8b5b5b5b2b6b5b2b8b7b4b9b8b5b9b8b5b6b5b3bab8b5bcbab7bbb9b6bbb8b5bfb9b5bdb2abbcb0a8beb2aabeb5afbfbab6bebab7c0bfbcbebdbabebbb8c0bdbabfbebbc2bebbbdbab7c3c0bdc3c0bdc1bebbc2bebabfbcb8bab9b6b7b6b3b2b1aeb6b5b2b5b4b1b5b4b2b6b5b2b7b6b4b9b8b6b7b6b3bbbab7b2afaba5988fb49e90b09481b79a88b39683b09583b7a395bfb6b0c0bdbabdbbb8bebcb9c1bfbcc0bebbbdbab7bebbb8c2bfbcc0bdbac0bcb9bdb9b6c0bcb8b5b4b2b4b3b0bab9b6b9b9b6b5b4b1b5b4b1b6b5b3b9b8b5b9b8b6b9b8b6b2aeaa968174a6836eaa856eab846eaf8973ac8973b08f79b18f7ab39786b7a89dbbb3aebfbab6c2c0bdbebcb9bfbdbac3c1bdc2bebbc0bcb9bdb9b6c1bdbabfbbb8b4b3b0b9b8b5b8b7b5b4b3b1b5b4b1b8b7b4b8b7b5bab9b6bbbab7b1afad8c7a719d735ca47860a87d65a98069ae8972ae8c75af8d77aa826ba98067aa8974b39e90b6a79dbbb2adc0bdbac1bfbdbfbbb8c1bdb9bebab6c0bdb9bfbbb8c1bdbab4b2b0b7b6b4b7b6b3b4b2b0bab9b7b6b5b2b6b5b2bab9b6bab9b6958c87977663aa836bac8772b08f7aad8c77b2917db0917db0907cac8971a77d64a87f67ac8972b29887b8a89dbfbab5bfbdbac1bebac0bcb9c0bcb9c0bcb9c1bebabebab7b8b7b4b7b6b4b5b4b1b5b4b2b7b6b3b5b4b2bab9b7bab9b6b4b1ada88f7fad8973ae8d78b19684b19685b29786b69a89b29582b1917daa856ea87e66a97e66ad866ea9826baf9280b8ada6bdbbb8bebab7bfbbb8c1bdbabfbbb8bcb8b4bcb8b5b6b4b2b7b5b3b6b5b2b8b7b4b3b2afb8b7b4b6b5b2b3b2b0b3a59aab856fad8d78b0917eb19886b49b8bb49a89b39785b0917eaf8f7cab866fa77d65a77a61a87d64a9816ab08f79b5a296c1bcb8c3bfbcc2bebbbebab7bfbbb7bdbab6c2bebab8b7b4b7b6b4b6b5b3b7b6b3b6b5b2b9b8b6b4b3b1b6b1acac8f7ca9826bae8f7aaf9583b49c8cb49c8bb79d8cb59987b19380ad8e79ae8c77af8e78ac8771a3775faa826bae8972b39888bbb6b2bebbb8bfbbb8bfbbb8c0bdb9bebbb7c0bdb9b6b5b2b9b8b5b4b3b1b8b7b5b4b3b0b7b6b4b6b5b3b1a7a0aa8772a77d65a88570b49887b19b8d9c887c907a6d987f71aa907faf917daf8e7aad8c78ac8b77a8836ca9836cac8770b49b8abdb6b2c0bcb9c0bdb9bfbbb8bebab7bfbcb9bebab7b9b8b6b5b4b2b9b8b5b8b7b5b8b7b4b7b6b4b5b4b2b3a9a2ad8973a1755da9856fb398858c776a65544b776358725d526e594d9c7f6eb1907ba68672ad8e7aab8771ac856db18f79b3a092beb9b5c1bdbabdb9b5bebab7bfbbb7bebab7bcb9b6b7b6b4b6b6b3b8b7b4b5b4b2b8b6b4b7b6b3b4b3b0b4aba4a6826ba3775fb08e79b19584a88e7daa8e7db29481ad8f7c997e6da38674ac8d79ac8e7aae917f9a7c6a896a599a7c6ab3a398c1bdbabdb9b6bcb8b5bebab6bebab7bdb9b5bdb9b6b5b4b1b7b5b3b5b4b2b7b6b3b7b6b4b3b3b0b3b2b0b4aca5a7846fa97f68ae8f7bae9383b59c8bb2937fae8e79ac8b76af927eaf927eb29683b39885b2988891786a72594c6e594d978d86bdbab7bab7b3c0bcb9c0bcb9bebab7bebbb7bdb9b6b3b2b0b4b3b0b5b4b2b4b4b1b4b3b1b4b3b1b4b3b0b6ada5aa8670a57a62ad8e7ab29b8cb69d8dab856fa9826aa88069ab8771af907db49987b19684b29886b59987b39480b09787b5a9a1bcb8b5bebab7bdb9b5bebab7bfbbb8bfbbb7bbb7b4b3b2afb8b7b5b8b7b5b3b2b0b5b4b2b6b5b3b6b4b1afa299a98975a9826baf907cb39988b49a89af8e7aac8973aa856eaf8c74b1917dae907dac907db39988b29785b49785b7a090b9aca3bfbab7bcb8b5bdb9b6bcb8b4bcb8b5bdb9b5bcb8b4b5b4b2b6b5b3b4b3b0b4b3b0b9b8b5b8b6b4908b88887467aa8f7ea78976ad8973b08b74b59885b69e8eb29888b1917cb1917db1937fae907cb19686b39a8ab29886b59b8ab8a192b6aaa3b7b2afbcb8b4bcb8b5bbb7b4c0bcb9bebab7c0bcb9b6b5b2b6b5b3b4b3b0bab9b7b7b6b4b1b0ae7b716ba083709b806f716158967764b08870b29481b69b8ab69f8fb39a89b69f90b49d8db39a89b29988b49c8cb6a090b8a496baa49593867f8f8986bfbbb7bdb9b5bcb7b4bab6b3b9b5b2bab6b2b4b3b1b3b3b0b6b5b3b8b7b5b4b2b0a7a5a38f837dae917ea084725a504c63544da28370b39784b59e8db2a093a698909b918b998e8790857e95877dad998bb39c8cb5a091b9a2938d827c95908dbebab6bbb7b3bdbab7bbb7b4bdb9b6bbb7b4b4b3b0b5b4b1b8b7b5b6b5b3b8b8b5b4b2af968f8ab29a8bab9485544b483a323073655d96887f70655f61595547403e453e3c453f3d57504f655e5b90847db39c8db7a090b6a09189807aaba6a3bdb9b6c0bcb9bebab7bcb7b4bebab7bbb7b4b3b2b0b6b5b3b2b1afb7b6b4b8b7b4b5b4b1aeaba8b5a89fac998d4d44412d25244d46444e4744322b293a3230423937433a37352d2a59504c534b48524a48988a81b59f8fb19c8d827974b2afacbdb9b5bcb8b4bdb9b5bcb8b5bdb9b6bab6b2b8b7b5b5b4b2b6b6b3b9b8b5b7b6b3b6b5b2b8b6b3b9b4b1b2a9a26c64612d25242d2625312a28352d2c453d3a78675c8d7a6ea09792aea6a0615854332b29524a479f8e82b09d90a49b96c1bdb9bebab7bfbbb8bbb8b4b9b5b1b8b4b0b9b4b0b7b6b4b8b7b5b8b7b4b6b5b3b8b6b3bab9b6b9b8b5b4b3b0b7b5b2a5a29f453d3b261e1d261f1e2e2625413936857268977865b19482b5a69caca5a07c7572453d3b746963a0948cc5bfbbc0bbb8beb9b6bbb7b3bbb6b3b7b3afb8b4b0b9b5b1b7b6b3b6b5b3b5b4b2b5b4b2b7b6b3b7b6b3b8b6b3b4b2afb7b6b3b3b1ae6d6765251f1e1e18172a22212d2523443b3971625ab19888b09482a89182877e792c25243e3634766d6abeb9b5bfbbb7bebab6bcb7b3bbb6b3b9b5b1b7b3afb8b4b0b4b3b0b5b4b1b5b4b1b4b3b1b5b4b2b8b6b4b5b3b0b9b6b4b5b4b1b6b4b27f79762a2322221c1b2d2524221b1a443e3c47413f6f676281766f867971675e5a3e37352a222166605dbab7b3bdb9b5beb9b5bcb7b3bcb7b3b9b4b0bab6b2bab6b2b5b3b0b6b4b2b3b2afb7b6b3b4b4b1b4b3b0b6b4b1b5b4b1b4b3b0b9b6b29a8c8252474230292828201f181212322c2c231e1d1c16162c26252923222d26252d2523332b2a8e8885bcb8b5bcb7b3bbb6b2bcb7b3b9b4b1b9b5b1b7b2afb7b2ae7a838e9b9b9caeadacb3b2b0b3b2afb7b7b4b6b5b3b6b6b3b7b6b3b9ada4a991808e7b6f50453f2b24231a14142923221f19181d17161f18182620201d17162a22215d5654b7b3b0bbb7b3bbb6b2b8b4b0bab5b1bbb6b2bab5b1b8b4b0bab6b22c496b4c5d735f68766e727a828285929090adaba8b7b2aeb6a59ab39682a28470a387748e76674e403a1a14141d1716181211221c1c1f1918221c1b2f2827342d2c8d8884bab6b3b9b5b2bab5b1bab5b1b9b4b0bab6b2b8b4b0b9b4b0b7b2ae325e8b365f8a3a5d833f5b7a545f70646469706b6aa08f84b08e78b18e769f7e689e7f6b9e816d907766584940362d2a1c1615201b1a1a1413201a1a251e1d393331a39e9bbab5b1bcb7b3bab6b2b8b3afb8b4b0b9b4b0b9b4b1bab5b2b5b0ac3d6c9843729d44719c426e98415f805a64716f6a699d8677b1927eb3947faa89749d7a649f7f6ba487749e837186716454463f2c25231e181837302e3a33317a7471beb9b6bcb8b4bbb6b2b6b2aebab5b1b9b5b1b8b3afbab6b2b6b1adb5aeaa4877a14c7aa44e7ba345719a3a5d80586b7f767475927b6eb1927faf8e79b08e78a78169a07861a17f6aa58570a688749b83738270666f66618a8480a49e99b7b2aebab6b2bcb8b4b9b5b1b7b2aebab5b1b9b4b0b6b1aeb6b1adb2aca8b2aca84876a04a78a2517fa74771973a5d80405c7a6161677c695fac8a75b08d77b4917aaf8971ad876fa5816aa6846ea78670a98a76ac9484ab9f96b2aca8bdb8b4bcb7b3bcb8b4bcb8b4b8b3afb7b2aeb9b4b0b8b3afb8b2aeb6afabb3aeaab2aeaa4878a14b7aa34c7ba44a759b3d63873b5f825b67766f5f569c7e6caf8c77b18f79b28f78b5927caf8e78a98872aa8a76a98a76ac917fada199b7b0acb9b3afbfb9b5c1bab6bdb6b2b8b3afbab5b1b9b4b0b6afabb7b1adb3ada9b3aeaab0aba8",Ks=32,rg=32;function ZC(){let i=[];for(let e=0;e<rg;e++){let t=[];for(let n=0;n<Ks;n++){let s=(e*Ks+n)*6,o=parseInt(Ec.slice(s,s+2),16),r=parseInt(Ec.slice(s+2,s+4),16),a=parseInt(Ec.slice(s+4,s+6),16);t.push([o,r,a])}i.push(t)}return i}function Ic(i,e,t,n=!1){return`\x1B[${n?48:38};2;${i};${e};${t}m`}var ag="\x1B[0m";function eM(){let i=ZC(),e=[];for(let t=0;t<rg;t+=2){let n="";for(let s=0;s<Ks;s++){let o=i[t][s],r=i[t+1]?.[s]??o;n+=`${Ic(r[0],r[1],r[2])}${Ic(o[0],o[1],o[2],!0)}\u2584`}n+=ag,e.push(n)}return e}var zs=class{constructor(e){this.interval=null;this.tick=0;this.maxTicks=25;this.cachedLines=[];this.cachedWidth=0;this.cachedTick=-1;this.ui=e,this.image=eM(),this.startAnimation()}invalidate(){this.cachedWidth=0}startAnimation(){this.interval=setInterval(()=>{this.tick++,this.tick>=this.maxTicks&&this.stopAnimation(),this.cachedWidth=0,this.ui.requestRender()},80)}stopAnimation(){this.interval&&(clearInterval(this.interval),this.interval=null)}render(e){if(e===this.cachedWidth&&this.cachedTick===this.tick)return this.cachedLines;let t=f,n=[],s=a=>{let l=a.replace(/\x1b\[[0-9;]*m/g,"").length,c=Math.max(0,Math.floor((e-l)/2));return" ".repeat(c)+a};n.push("");let o=Math.min(this.image.length,Math.floor(this.tick/this.maxTicks*(this.image.length+3)));for(let a=0;a<this.image.length;a++)if(a<o)n.push(s(this.image[a]));else if(a===o){let l="\u2593".repeat(Ks);n.push(s(Ic(100,200,255)+l+ag))}else n.push(s(" ".repeat(Ks)));n.push("");let r=Math.max(0,this.tick-this.maxTicks*.6);return r>0||this.tick>=this.maxTicks?(n.push(s(t.fg("accent","Free Kimi K2.5 via OpenCode Zen"))),n.push(s(t.fg("success",'"Powered by daxnuts"'))),n.push(s(t.fg("muted","\u2014 @thdxr")))):(n.push(""),n.push(""),n.push("")),n.push(""),r>2||this.tick>=this.maxTicks?(n.push(s(t.fg("dim","Try OpenCode"))),n.push(s(t.fg("mdLink","https://mistral.ai/news/mistral-vibe-2-0")))):(n.push(""),n.push("")),n.push(""),this.cachedLines=n,this.cachedWidth=e,this.cachedTick=this.tick,n}dispose(){this.stopAnimation()}};import*as cg from"node:fs";var tM="https://mariozechner.at/posts/2026-04-08-ive-sold-out/",pg="clankolas.png",Wr,lg=!1;function nM(){if(lg)return Wr;lg=!0;try{Wr=cg.readFileSync(Gp(pg)).toString("base64")}catch{Wr=void 0}return Wr}var Or=class extends L{constructor(){super(),this.addChild(new O(t=>f.fg("accent",t))),this.addChild(new T(f.bold(f.fg("accent","pi has joined Earendil")),1,0)),this.addChild(new E(1)),this.addChild(new T(f.fg("muted","Read the blog post:"),1,0)),this.addChild(new T(f.fg("mdLink",tM),1,0)),this.addChild(new E(1));let e=nM();e&&(this.addChild(new mn(e,"image/png",{fallbackColor:t=>f.fg("muted",t)},{maxWidthCells:56,filename:pg})),this.addChild(new E(1))),this.addChild(new O(t=>f.fg("accent",t)))}};import{spawnSync as iM}from"node:child_process";import*as Li from"node:fs";import*as dg from"node:os";import*as ug from"node:path";var _i=class extends L{constructor(t,n,s,o,r,a,l){super();this._focused=!1;this.tui=t,this.keybindings=n,this.onSubmitCallback=r,this.onCancelCallback=a,this.addChild(new O),this.addChild(new E(1)),this.addChild(new T(f.fg("accent",s),1,0)),this.addChild(new E(1)),this.editor=new un(t,ws(),l),o&&this.editor.setText(o),this.editor.onSubmit=p=>{this.onSubmitCallback(p)},this.addChild(this.editor),this.addChild(new E(1));let c=!!(process.env.VISUAL||process.env.EDITOR),d=N("tui.select.confirm","submit")+" "+N("tui.input.newLine","newline")+" "+N("tui.select.cancel","cancel")+(c?` ${N("app.editor.external","external editor")}`:"");this.addChild(new T(d,1,0)),this.addChild(new E(1)),this.addChild(new O)}get focused(){return this._focused}set focused(t){this._focused=t,this.editor.focused=t}handleInput(t){if(V().matches(t,"tui.select.cancel")){this.onCancelCallback();return}if(this.keybindings.matches(t,"app.editor.external")){this.openExternalEditor();return}this.editor.handleInput(t)}openExternalEditor(){let t=process.env.VISUAL||process.env.EDITOR;if(!t)return;let n=this.editor.getText(),s=ug.join(dg.tmpdir(),`pi-extension-editor-${Date.now()}.md`);try{Li.writeFileSync(s,n,"utf-8"),this.tui.stop();let[o,...r]=t.split(" ");if(iM(o,[...r,s],{stdio:"inherit",shell:process.platform==="win32"}).status===0){let l=Li.readFileSync(s,"utf-8").replace(/\n$/,"");this.editor.setText(l)}}finally{try{Li.unlinkSync(s)}catch{}this.tui.start(),this.tui.requestRender(!0)}}};var Wi=class extends L{constructor(t,n,s,o,r){super();this._focused=!1;this.onSubmitCallback=s,this.onCancelCallback=o,this.baseTitle=t,this.addChild(new O),this.addChild(new E(1)),this.titleText=new T(f.fg("accent",t),1,0),this.addChild(this.titleText),this.addChild(new E(1)),r?.timeout&&r.timeout>0&&r.tui&&(this.countdown=new nn(r.timeout,r.tui,a=>this.titleText.setText(f.fg("accent",`${this.baseTitle} (${a}s)`)),()=>this.onCancelCallback())),this.input=new pe,this.addChild(this.input),this.addChild(new E(1)),this.addChild(new T(`${N("tui.select.confirm","submit")} ${N("tui.select.cancel","cancel")}`,1,0)),this.addChild(new E(1)),this.addChild(new O)}get focused(){return this._focused}set focused(t){this._focused=t,this.input.focused=t}handleInput(t){let n=V();n.matches(t,"tui.select.confirm")||t===`
|
|
330
|
+
`?this.onSubmitCallback(this.input.getValue()):n.matches(t,"tui.select.cancel")?this.onCancelCallback():this.input.handleInput(t)}dispose(){this.countdown?.dispose()}};var Nt=class extends L{constructor(t,n,s,o,r){super();this.selectedIndex=0;this.options=n,this.onSelectCallback=s,this.onCancelCallback=o,this.baseTitle=t,this.addChild(new O),this.addChild(new E(1)),this.titleText=new T(f.fg("accent",f.bold(t)),1,0),this.addChild(this.titleText),this.addChild(new E(1)),r?.timeout&&r.timeout>0&&r.tui&&(this.countdown=new nn(r.timeout,r.tui,a=>this.titleText.setText(f.fg("accent",f.bold(`${this.baseTitle} (${a}s)`))),()=>this.onCancelCallback())),this.listContainer=new L,this.addChild(this.listContainer),this.addChild(new E(1)),this.addChild(new T(Le("\u2191\u2193","navigate")+" "+N("tui.select.confirm","select")+" "+N("tui.select.cancel","cancel"),1,0)),this.addChild(new E(1)),this.addChild(new O),this.updateList()}updateList(){this.listContainer.clear();for(let t=0;t<this.options.length;t++){let s=t===this.selectedIndex?f.fg("accent","\u2192 ")+f.fg("accent",this.options[t]):` ${f.fg("text",this.options[t])}`;this.listContainer.addChild(new T(s,1,0))}}handleInput(t){let n=V();if(n.matches(t,"tui.select.up")||t==="k")this.selectedIndex=Math.max(0,this.selectedIndex-1),this.updateList();else if(n.matches(t,"tui.select.down")||t==="j")this.selectedIndex=Math.min(this.options.length-1,this.selectedIndex+1),this.updateList();else if(n.matches(t,"tui.select.confirm")||t===`
|
|
331
|
+
`){let s=this.options[this.selectedIndex];s&&this.onSelectCallback(s)}else n.matches(t,"tui.select.cancel")&&this.onCancelCallback()}dispose(){this.countdown?.dispose()}};function sM(i){return i.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()}function Oi(i){return i<1e3?i.toString():i<1e4?`${(i/1e3).toFixed(1)}k`:i<1e6?`${Math.round(i/1e3)}k`:i<1e7?`${(i/1e6).toFixed(1)}M`:`${Math.round(i/1e6)}M`}var Ui=class{constructor(e,t){this.session=e;this.footerData=t;this.autoCompactEnabled=!0}setSession(e){this.session=e}setAutoCompactEnabled(e){this.autoCompactEnabled=e}invalidate(){}dispose(){}render(e){let t=this.session.state,n=0,s=0,o=0,r=0,a=0;for(let X of this.session.sessionManager.getEntries())X.type==="message"&&X.message.role==="assistant"&&(n+=X.message.usage.input,s+=X.message.usage.output,o+=X.message.usage.cacheRead,r+=X.message.usage.cacheWrite,a+=X.message.usage.cost.total);let l=this.session.getContextUsage(),c=l?.contextWindow??t.model?.contextWindow??0,d=l?.percent??0,p=l?.percent!==null?d.toFixed(1):"?",u=this.session.sessionManager.getCwd(),h=process.env.HOME||process.env.USERPROFILE;h&&u.startsWith(h)&&(u=`~${u.slice(h.length)}`);let m=this.footerData.getGitBranch();m&&(u=`${u} (${m})`);let g=this.session.sessionManager.getSessionName();g&&(u=`${u} \u2022 ${g}`);let x=[];n&&x.push(`\u2191${Oi(n)}`),s&&x.push(`\u2193${Oi(s)}`),o&&x.push(`R${Oi(o)}`),r&&x.push(`W${Oi(r)}`);let b=t.model?this.session.modelRegistry.isUsingOAuth(t.model):!1;if(a||b){let X=`$${a.toFixed(3)}${b?" (sub)":""}`;x.push(X)}let v,w=this.autoCompactEnabled?" (auto)":"",C=p==="?"?`?/${Oi(c)}${w}`:`${p}%/${Oi(c)}${w}`;d>90?v=f.fg("error",C):d>70?v=f.fg("warning",C):v=C,x.push(v);let R=x.join(" "),k=t.model?.id||"no-model",A=W(R);A>e&&(R=G(R,e,"..."),A=W(R));let S=2,I=k;if(t.model?.reasoning){let X=t.thinkingLevel||"off";I=X==="off"?`${k} \u2022 thinking off`:`${k} \u2022 ${X}`}let P=I;this.footerData.getAvailableProviderCount()>1&&t.model&&(P=`(${t.model.provider}) ${I}`,A+S+W(P)>e&&(P=I));let M=W(P),_=A+S+M,U;if(_<=e){let X=" ".repeat(e-A-M);U=R+X+P}else{let X=e-A-S;if(X>0){let me=G(P,X,""),rt=W(me),Ee=" ".repeat(Math.max(0,e-A-rt));U=R+Ee+me}else U=R}let F=f.fg("dim",R),$=U.slice(R.length),Q=f.fg("dim",$),ue=[G(f.fg("dim",u),e,f.fg("dim","...")),F+Q],Se=this.footerData.getExtensionStatuses();if(Se.size>0){let me=Array.from(Se.entries()).sort(([rt],[Ee])=>rt.localeCompare(Ee)).map(([,rt])=>sM(rt)).join(" ");ue.push(G(me,e,f.fg("dim","...")))}return ue}};import{exec as oM}from"child_process";var sn=class extends L{constructor(t,n,s,o,r){super();this.onComplete=s;this.abortController=new AbortController;this._focused=!1;this.tui=t;let a=Rl().find(d=>d.id===n),l=o||a?.name||n,c=r??`Login to ${l}`;this.addChild(new O),this.addChild(new T(f.fg("accent",f.bold(c)),1,0)),this.contentContainer=new L,this.addChild(this.contentContainer),this.input=new pe,this.input.onSubmit=()=>{this.inputResolver&&(this.inputResolver(this.input.getValue()),this.inputResolver=void 0,this.inputRejecter=void 0)},this.input.onEscape=()=>{this.cancel()},this.addChild(new O)}get focused(){return this._focused}set focused(t){this._focused=t,this.input.focused=t}get signal(){return this.abortController.signal}cancel(){this.abortController.abort(),this.inputRejecter&&(this.inputRejecter(new Error("Login cancelled")),this.inputResolver=void 0,this.inputRejecter=void 0),this.onComplete(!1,"Login cancelled")}showAuth(t,n){this.contentContainer.clear(),this.contentContainer.addChild(new E(1));let s=`\x1B]8;;${t}\x07${t}\x1B]8;;\x07`;this.contentContainer.addChild(new T(f.fg("accent",s),1,0));let o=process.platform==="darwin"?"Cmd+click to open":"Ctrl+click to open",r=`\x1B]8;;${t}\x07${o}\x1B]8;;\x07`;this.contentContainer.addChild(new T(f.fg("dim",r),1,0)),n&&(this.contentContainer.addChild(new E(1)),this.contentContainer.addChild(new T(f.fg("warning",n),1,0)));let a=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";oM(`${a} "${t}"`),this.tui.requestRender()}showManualInput(t){return this.contentContainer.addChild(new E(1)),this.contentContainer.addChild(new T(f.fg("dim",t),1,0)),this.contentContainer.addChild(this.input),this.contentContainer.addChild(new T(`(${N("tui.select.cancel","to cancel")})`,1,0)),this.tui.requestRender(),new Promise((n,s)=>{this.inputResolver=n,this.inputRejecter=s})}showPrompt(t,n){return this.contentContainer.addChild(new E(1)),this.contentContainer.addChild(new T(f.fg("text",t),1,0)),n&&this.contentContainer.addChild(new T(f.fg("dim",`e.g., ${n}`),1,0)),this.contentContainer.addChild(this.input),this.contentContainer.addChild(new T(`(${N("tui.select.cancel","to cancel,")} ${N("tui.select.confirm","to submit")})`,1,0)),this.input.setValue(""),this.tui.requestRender(),new Promise((s,o)=>{this.inputResolver=s,this.inputRejecter=o})}showInfo(t){this.contentContainer.clear(),this.contentContainer.addChild(new E(1));for(let n of t)this.contentContainer.addChild(new T(n,1,0));this.contentContainer.addChild(new E(1)),this.contentContainer.addChild(new T(`(${N("tui.select.cancel","to close")})`,1,0)),this.tui.requestRender()}showWaiting(t){this.contentContainer.addChild(new E(1)),this.contentContainer.addChild(new T(f.fg("dim",t),1,0)),this.contentContainer.addChild(new T(`(${N("tui.select.cancel","to cancel")})`,1,0)),this.tui.requestRender()}showProgress(t){this.contentContainer.addChild(new T(f.fg("dim",t),1,0)),this.tui.requestRender()}handleInput(t){if(V().matches(t,"tui.select.cancel")){this.cancel();return}this.input.handleInput(t)}};var Di=class extends L{constructor(t,n,s,o,r,a,l,c){super();this._focused=!1;this.allModels=[];this.scopedModelItems=[];this.activeModels=[];this.filteredModels=[];this.selectedIndex=0;this.scope="all";if(this.tui=t,this.currentModel=n,this.settingsManager=s,this.modelRegistry=o,this.scopedModels=r,this.scope=r.length>0?"scoped":"all",this.onSelectCallback=a,this.onCancelCallback=l,this.addChild(new O),this.addChild(new E(1)),r.length>0)this.scopeText=new T(this.getScopeText(),0,0),this.addChild(this.scopeText),this.scopeHintText=new T(this.getScopeHintText(),0,0),this.addChild(this.scopeHintText);else{let d="Only showing models from configured providers. Use /login to add providers.";this.addChild(new T(f.fg("warning",d),0,0))}this.addChild(new E(1)),this.searchInput=new pe,c&&this.searchInput.setValue(c),this.searchInput.onSubmit=()=>{this.filteredModels[this.selectedIndex]&&this.handleSelect(this.filteredModels[this.selectedIndex].model)},this.addChild(this.searchInput),this.addChild(new E(1)),this.listContainer=new L,this.addChild(this.listContainer),this.addChild(new E(1)),this.addChild(new O),this.loadModels().then(()=>{c?this.filterModels(c):this.updateList(),this.tui.requestRender()})}get focused(){return this._focused}set focused(t){this._focused=t,this.searchInput.focused=t}async loadModels(){let t;this.modelRegistry.refresh();let n=this.modelRegistry.getError();n&&(this.errorMessage=n);try{t=(await this.modelRegistry.getAvailable()).map(r=>({provider:r.provider,id:r.id,model:r}))}catch(o){this.allModels=[],this.scopedModelItems=[],this.activeModels=[],this.filteredModels=[],this.errorMessage=o instanceof Error?o.message:String(o);return}this.allModels=this.sortModels(t),this.scopedModels=this.scopedModels.map(o=>{let r=this.modelRegistry.find(o.model.provider,o.model.id);return r?{...o,model:r}:o}),this.scopedModelItems=this.scopedModels.map(o=>({provider:o.model.provider,id:o.model.id,model:o.model})),this.activeModels=this.scope==="scoped"?this.scopedModelItems:this.allModels,this.filteredModels=this.activeModels;let s=this.filteredModels.findIndex(o=>dt(this.currentModel,o.model));this.selectedIndex=s>=0?s:Math.min(this.selectedIndex,Math.max(0,this.filteredModels.length-1))}sortModels(t){let n=[...t];return n.sort((s,o)=>{let r=dt(this.currentModel,s.model),a=dt(this.currentModel,o.model);return r&&!a?-1:!r&&a?1:s.provider.localeCompare(o.provider)}),n}getScopeText(){let t=this.scope==="all"?f.fg("accent","all"):f.fg("muted","all"),n=this.scope==="scoped"?f.fg("accent","scoped"):f.fg("muted","scoped");return`${f.fg("muted","Scope: ")}${t}${f.fg("muted"," | ")}${n}`}getScopeHintText(){return N("tui.input.tab","scope")+f.fg("muted"," (all/scoped)")}setScope(t){if(this.scope===t)return;this.scope=t,this.activeModels=this.scope==="scoped"?this.scopedModelItems:this.allModels;let n=this.activeModels.findIndex(s=>dt(this.currentModel,s.model));this.selectedIndex=n>=0?n:0,this.filterModels(this.searchInput.getValue()),this.scopeText&&this.scopeText.setText(this.getScopeText())}filterModels(t){this.filteredModels=t?We(this.activeModels,t,({id:n,provider:s})=>`${n} ${s} ${s}/${n} ${s} ${n}`):this.activeModels,this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredModels.length-1)),this.updateList()}updateList(){this.listContainer.clear();let t=10,n=Math.max(0,Math.min(this.selectedIndex-Math.floor(t/2),this.filteredModels.length-t)),s=Math.min(n+t,this.filteredModels.length);for(let o=n;o<s;o++){let r=this.filteredModels[o];if(!r)continue;let a=o===this.selectedIndex,l=dt(this.currentModel,r.model),c="";if(a){let d=f.fg("accent","\u2192 "),p=`${r.id}`,u=f.fg("muted",`[${r.provider}]`),h=l?f.fg("success"," \u2713"):"";c=`${d+f.fg("accent",p)} ${u}${h}`}else{let d=` ${r.id}`,p=f.fg("muted",`[${r.provider}]`),u=l?f.fg("success"," \u2713"):"";c=`${d} ${p}${u}`}this.listContainer.addChild(new T(c,0,0))}if(n>0||s<this.filteredModels.length){let o=f.fg("muted",` (${this.selectedIndex+1}/${this.filteredModels.length})`);this.listContainer.addChild(new T(o,0,0))}if(this.errorMessage){let o=this.errorMessage.split(`
|
|
332
|
+
`);for(let r of o)this.listContainer.addChild(new T(f.fg("error",r),0,0))}else if(this.filteredModels.length===0)this.listContainer.addChild(new T(f.fg("muted"," No matching models"),0,0));else{let o=this.filteredModels[this.selectedIndex];this.listContainer.addChild(new E(1)),this.listContainer.addChild(new T(f.fg("muted",` Model Name: ${o.model.name}`),0,0))}}handleInput(t){let n=V();if(n.matches(t,"tui.input.tab")){if(this.scopedModelItems.length>0){let s=this.scope==="all"?"scoped":"all";this.setScope(s),this.scopeHintText&&this.scopeHintText.setText(this.getScopeHintText())}return}if(n.matches(t,"tui.select.up")){if(this.filteredModels.length===0)return;this.selectedIndex=this.selectedIndex===0?this.filteredModels.length-1:this.selectedIndex-1,this.updateList()}else if(n.matches(t,"tui.select.down")){if(this.filteredModels.length===0)return;this.selectedIndex=this.selectedIndex===this.filteredModels.length-1?0:this.selectedIndex+1,this.updateList()}else if(n.matches(t,"tui.select.confirm")){let s=this.filteredModels[this.selectedIndex];s&&this.handleSelect(s.model)}else n.matches(t,"tui.select.cancel")?this.onCancelCallback():(this.searchInput.handleInput(t),this.filterModels(this.searchInput.getValue()))}handleSelect(t){this.settingsManager.setDefaultModelAndProvider(t.provider,t.id),this.onSelectCallback(t)}getSearchInput(){return this.searchInput}};var On=class extends L{constructor(t,n,s,o,r,a){super();this._focused=!1;this.selectedIndex=0;this.mode=t,this.authStorage=n,this.getAuthStatus=a??(c=>this.authStorage.getAuthStatus(c)),this.allProviders=s,this.filteredProviders=s,this.onSelectCallback=o,this.onCancelCallback=r,this.addChild(new O),this.addChild(new E(1));let l=t==="login"?"Select provider to configure:":"Select provider to logout:";this.addChild(new $e(f.fg("accent",f.bold(l)),1,0)),this.addChild(new E(1)),this.searchInput=new pe,this.searchInput.onSubmit=()=>{let c=this.filteredProviders[this.selectedIndex];c&&this.onSelectCallback(c.id)},this.addChild(this.searchInput),this.addChild(new E(1)),this.listContainer=new L,this.addChild(this.listContainer),this.addChild(new E(1)),this.addChild(new O),this.filterProviders("")}get focused(){return this._focused}set focused(t){this._focused=t,this.searchInput.focused=t}filterProviders(t){this.filteredProviders=t?We(this.allProviders,t,n=>`${n.name} ${n.id} ${n.authType}`):this.allProviders,this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,Math.max(0,this.filteredProviders.length-1))),this.updateList()}updateList(){this.listContainer.clear();let t=8,n=Math.max(0,Math.min(this.selectedIndex-Math.floor(t/2),this.filteredProviders.length-t)),s=Math.min(n+t,this.filteredProviders.length);for(let o=n;o<s;o++){let r=this.filteredProviders[o];if(!r)continue;let a=o===this.selectedIndex,l=this.formatStatusIndicator(r),c="";if(a){let d=f.fg("accent","\u2192 "),p=f.fg("accent",r.name);c=d+p+l}else c=` ${f.fg("text",r.name)}`+l;this.listContainer.addChild(new $e(c,1,0))}if(n>0||s<this.filteredProviders.length){let o=f.fg("muted",` (${this.selectedIndex+1}/${this.filteredProviders.length})`);this.listContainer.addChild(new $e(o,1,0))}if(this.filteredProviders.length===0){let o=this.allProviders.length===0?this.mode==="login"?"No providers available":"No providers logged in. Use /login first.":"No matching providers";this.listContainer.addChild(new $e(f.fg("muted",` ${o}`),1,0))}}formatStatusIndicator(t){let n=this.authStorage.get(t.id);if(n?.type===t.authType)return f.fg("success"," \u2713 configured");if(n){let o=n.type==="oauth"?"subscription configured":"API key configured";return f.fg("muted"," \u2022 ")+f.fg("warning",o)}if(t.authType!=="api_key")return f.fg("muted"," \u2022 unconfigured");let s=this.getAuthStatus(t.id);switch(s.source){case"environment":return f.fg("success",` \u2713 env: ${s.label??"API key"}`);case"runtime":return f.fg("success"," \u2713 runtime API key");case"fallback":return f.fg("success"," \u2713 custom API key");case"models_json_key":return f.fg("success"," \u2713 key in models.json");case"models_json_command":return f.fg("success"," \u2713 command in models.json");default:return f.fg("muted"," \u2022 unconfigured")}}handleInput(t){let n=V();if(n.matches(t,"tui.select.up")){if(this.filteredProviders.length===0)return;this.selectedIndex=Math.max(0,this.selectedIndex-1),this.updateList()}else if(n.matches(t,"tui.select.down")){if(this.filteredProviders.length===0)return;this.selectedIndex=Math.min(this.filteredProviders.length-1,this.selectedIndex+1),this.updateList()}else if(n.matches(t,"tui.select.confirm")){let s=this.filteredProviders[this.selectedIndex];s&&this.onSelectCallback(s.id)}else n.matches(t,"tui.select.cancel")?this.onCancelCallback():(this.searchInput.handleInput(t),this.filterProviders(this.searchInput.getValue()))}};function Ac(i,e){return i===null||i.includes(e)}function rM(i,e){if(i===null)return[e];let t=i.indexOf(e);return t>=0?[...i.slice(0,t),...i.slice(t+1)]:[...i,e]}function mg(i,e,t){if(i===null)return null;let n=t??e,s=[...i];for(let o of n)s.includes(o)||s.push(o);return s.length===e.length?null:s}function hg(i,e,t){if(i===null)return t?e.filter(s=>!t.includes(s)):[];let n=new Set(t??i);return i.filter(s=>!n.has(s))}function aM(i,e,t){if(i===null)return null;let n=[...i],s=n.indexOf(e);if(s<0)return n;let o=s+t;if(o<0||o>=n.length)return n;let r=[...n];return[r[s],r[o]]=[r[o],r[s]],r}function lM(i,e){if(i===null)return e;let t=new Set(i);return[...i,...e.filter(n=>!t.has(n))]}var Hs=class extends L{constructor(t,n){super();this.modelsById=new Map;this.allIds=[];this.enabledIds=null;this.filteredItems=[];this.selectedIndex=0;this._focused=!1;this.maxVisible=8;this.isDirty=!1;this.callbacks=n;for(let s of t.allModels){let o=`${s.provider}/${s.id}`;this.modelsById.set(o,s),this.allIds.push(o)}this.enabledIds=t.enabledModelIds===null?null:[...t.enabledModelIds],this.filteredItems=this.buildItems(),this.addChild(new O),this.addChild(new E(1)),this.addChild(new T(f.fg("accent",f.bold("Model Configuration")),0,0)),this.addChild(new T(f.fg("muted",`Session-only. ${z("app.models.save")} to save to settings.`),0,0)),this.addChild(new E(1)),this.searchInput=new pe,this.addChild(this.searchInput),this.addChild(new E(1)),this.listContainer=new L,this.addChild(this.listContainer),this.addChild(new E(1)),this.footerText=new T(this.getFooterText(),0,0),this.addChild(this.footerText),this.addChild(new O),this.updateList()}get focused(){return this._focused}set focused(t){this._focused=t,this.searchInput.focused=t}buildItems(){return lM(this.enabledIds,this.allIds).filter(t=>this.modelsById.has(t)).map(t=>({fullId:t,model:this.modelsById.get(t),enabled:Ac(this.enabledIds,t)}))}getFooterText(){let t=this.enabledIds?.length??this.allIds.length,s=this.enabledIds===null?"all enabled":`${t}/${this.allIds.length} enabled`,o=[`${z("tui.select.confirm")} toggle`,`${z("app.models.enableAll")} all`,`${z("app.models.clearAll")} clear`,`${z("app.models.toggleProvider")} provider`,`${z("app.models.reorderUp")}/${z("app.models.reorderDown")} reorder`,`${z("app.models.save")} save`,s];return this.isDirty?f.fg("dim",` ${o.join(" \xB7 ")} `)+f.fg("warning","(unsaved)"):f.fg("dim",` ${o.join(" \xB7 ")}`)}refresh(){let t=this.searchInput.getValue(),n=this.buildItems();this.filteredItems=t?We(n,t,s=>`${s.model.id} ${s.model.provider}`):n,this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredItems.length-1)),this.updateList(),this.footerText.setText(this.getFooterText())}notifyChange(){this.callbacks.onChange(this.enabledIds===null?null:[...this.enabledIds])}updateList(){if(this.listContainer.clear(),this.filteredItems.length===0){this.listContainer.addChild(new T(f.fg("muted"," No matching models"),0,0));return}let t=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible)),n=Math.min(t+this.maxVisible,this.filteredItems.length),s=this.enabledIds===null;for(let o=t;o<n;o++){let r=this.filteredItems[o],a=o===this.selectedIndex,l=a?f.fg("accent","\u2192 "):" ",c=a?f.fg("accent",r.model.id):r.model.id,d=f.fg("muted",` [${r.model.provider}]`),p=s?"":r.enabled?f.fg("success"," \u2713"):f.fg("dim"," \u2717");this.listContainer.addChild(new T(`${l}${c}${d}${p}`,0,0))}if((t>0||n<this.filteredItems.length)&&this.listContainer.addChild(new T(f.fg("muted",` (${this.selectedIndex+1}/${this.filteredItems.length})`),0,0)),this.filteredItems.length>0){let o=this.filteredItems[this.selectedIndex];this.listContainer.addChild(new E(1)),this.listContainer.addChild(new T(f.fg("muted",` Model Name: ${o.model.name}`),0,0))}}handleInput(t){let n=V();if(n.matches(t,"tui.select.up")){if(this.filteredItems.length===0)return;this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.updateList();return}if(n.matches(t,"tui.select.down")){if(this.filteredItems.length===0)return;this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.updateList();return}let s=n.matches(t,"app.models.reorderUp"),o=n.matches(t,"app.models.reorderDown");if(s||o){if(this.enabledIds===null)return;let r=this.filteredItems[this.selectedIndex];if(r&&Ac(this.enabledIds,r.fullId)){let a=s?-1:1,c=this.enabledIds.indexOf(r.fullId)+a;c>=0&&c<this.enabledIds.length&&(this.enabledIds=aM(this.enabledIds,r.fullId,a),this.isDirty=!0,this.selectedIndex+=a,this.refresh(),this.notifyChange())}return}if(n.matches(t,"tui.select.confirm")){let r=this.filteredItems[this.selectedIndex];r&&(this.enabledIds=rM(this.enabledIds,r.fullId),this.isDirty=!0,this.refresh(),this.notifyChange());return}if(n.matches(t,"app.models.enableAll")){let r=this.searchInput.getValue()?this.filteredItems.map(a=>a.fullId):void 0;this.enabledIds=mg(this.enabledIds,this.allIds,r),this.isDirty=!0,this.refresh(),this.notifyChange();return}if(n.matches(t,"app.models.clearAll")){let r=this.searchInput.getValue()?this.filteredItems.map(a=>a.fullId):void 0;this.enabledIds=hg(this.enabledIds,this.allIds,r),this.isDirty=!0,this.refresh(),this.notifyChange();return}if(n.matches(t,"app.models.toggleProvider")){let r=this.filteredItems[this.selectedIndex];if(r){let a=r.model.provider,l=this.allIds.filter(d=>this.modelsById.get(d).provider===a),c=l.every(d=>Ac(this.enabledIds,d));this.enabledIds=c?hg(this.enabledIds,this.allIds,l):mg(this.enabledIds,this.allIds,l),this.isDirty=!0,this.refresh(),this.notifyChange()}return}if(n.matches(t,"app.models.save")){this.callbacks.onPersist(this.enabledIds===null?null:[...this.enabledIds]),this.isDirty=!1,this.footerText.setText(this.getFooterText());return}if(ge(t,cn.ctrl("c"))){this.searchInput.getValue()?(this.searchInput.setValue(""),this.refresh()):this.callbacks.onCancel();return}if(ge(t,cn.escape)){this.callbacks.onCancel();return}this.searchInput.handleInput(t),this.refresh()}getSearchInput(){return this.searchInput}};var cM={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},pM={off:"No reasoning",minimal:"Very brief reasoning (~1k tokens)",low:"Light reasoning (~2k tokens)",medium:"Moderate reasoning (~8k tokens)",high:"Deep reasoning (~16k tokens)",xhigh:"Maximum reasoning (~32k tokens)"},Pc=class extends L{constructor(e,t,n){super(),this.state={...e};let s=[{id:"anthropic-extra-usage",label:"Anthropic extra usage",description:"Warn when Anthropic subscription auth may use paid extra usage",currentValue:this.state.anthropicExtraUsage??!0?"true":"false",values:["true","false"]}];this.settingsList=new zn(s,Math.min(s.length,10),Go(),(o,r)=>{switch(o){case"anthropic-extra-usage":this.state={...this.state,anthropicExtraUsage:r==="true"},t({...this.state});break}},n),this.addChild(this.settingsList)}handleInput(e){this.settingsList.handleInput(e)}},Ur=class extends L{constructor(e,t,n,s,o,r,a){super(),this.addChild(new T(f.bold(f.fg("accent",e)),0,0)),t&&(this.addChild(new E(1)),this.addChild(new T(f.fg("muted",t),0,0))),this.addChild(new E(1)),this.selectList=new Ye(n,Math.min(n.length,10),Cn(),cM);let l=n.findIndex(c=>c.value===s);l!==-1&&this.selectList.setSelectedIndex(l),this.selectList.onSelect=c=>{o(c.value)},this.selectList.onCancel=r,a&&(this.selectList.onSelectionChange=c=>{a(c.value)}),this.addChild(this.selectList),this.addChild(new E(1)),this.addChild(new T(f.fg("dim"," Enter to select \xB7 Esc to go back"),0,0))}handleInput(e){this.selectList.handleInput(e)}},Fi=class extends L{constructor(e,t){super();let n=ve().images,s=Rs("app.message.followUp"),o={...e.warnings},r=[{id:"autocompact",label:"Auto-compact",description:"Automatically compact context when it gets too large",currentValue:e.autoCompact?"true":"false",values:["true","false"]},{id:"steering-mode",label:"Steering mode",description:"Enter while streaming queues steering messages. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.",currentValue:e.steeringMode,values:["one-at-a-time","all"]},{id:"follow-up-mode",label:"Follow-up mode",description:`${s} queues follow-up messages until agent stops. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.`,currentValue:e.followUpMode,values:["one-at-a-time","all"]},{id:"transport",label:"Transport",description:"Preferred transport for providers that support multiple transports",currentValue:e.transport,values:["sse","websocket","websocket-cached","auto"]},{id:"hide-thinking",label:"Hide thinking",description:"Hide thinking blocks in assistant responses",currentValue:e.hideThinkingBlock?"true":"false",values:["true","false"]},{id:"collapse-changelog",label:"Collapse changelog",description:"Show condensed changelog after updates",currentValue:e.collapseChangelog?"true":"false",values:["true","false"]},{id:"quiet-startup",label:"Quiet startup",description:"Disable verbose printing at startup",currentValue:e.quietStartup?"true":"false",values:["true","false"]},{id:"install-telemetry",label:"Install telemetry",description:"Send an anonymous version/update ping after changelog-detected updates",currentValue:e.enableInstallTelemetry?"true":"false",values:["true","false"]},{id:"double-escape-action",label:"Double-escape action",description:"Action when pressing Escape twice with empty editor",currentValue:e.doubleEscapeAction,values:["tree","fork","none"]},{id:"tree-filter-mode",label:"Tree filter mode",description:"Default filter when opening /tree",currentValue:e.treeFilterMode,values:["default","no-tools","user-only","labeled-only","all"]},{id:"warnings",label:"Warnings",description:"Enable or disable individual warnings",currentValue:"configure",submenu:(m,g)=>new Pc(o,x=>{o=x,t.onWarningsChange(x)},()=>g())},{id:"thinking",label:"Thinking level",description:"Reasoning depth for thinking-capable models",currentValue:e.thinkingLevel,submenu:(m,g)=>new Ur("Thinking Level","Select reasoning depth for thinking-capable models",e.availableThinkingLevels.map(x=>({value:x,label:x,description:pM[x]})),m,x=>{t.onThinkingLevelChange(x),g(x)},()=>g())},{id:"theme",label:"Theme",description:"Color theme for the interface",currentValue:e.currentTheme,submenu:(m,g)=>new Ur("Theme","Select color theme",e.availableThemes.map(x=>({value:x,label:x})),m,x=>{t.onThemeChange(x),g(x)},()=>{t.onThemePreview?.(m),g()},x=>{t.onThemePreview?.(x)})}];n&&(r.splice(1,0,{id:"show-images",label:"Show images",description:"Render images inline in terminal",currentValue:e.showImages?"true":"false",values:["true","false"]}),r.splice(2,0,{id:"image-width-cells",label:"Image width",description:"Preferred inline image width in terminal cells",currentValue:String(e.imageWidthCells),values:["60","80","120"]})),r.splice(n?3:1,0,{id:"auto-resize-images",label:"Auto-resize images",description:"Resize large images to 2000x2000 max for better model compatibility",currentValue:e.autoResizeImages?"true":"false",values:["true","false"]});let a=r.findIndex(m=>m.id==="auto-resize-images");r.splice(a+1,0,{id:"block-images",label:"Block images",description:"Prevent images from being sent to LLM providers",currentValue:e.blockImages?"true":"false",values:["true","false"]});let l=r.findIndex(m=>m.id==="block-images");r.splice(l+1,0,{id:"skill-commands",label:"Skill commands",description:"Register skills as /skill:name commands",currentValue:e.enableSkillCommands?"true":"false",values:["true","false"]});let c=r.findIndex(m=>m.id==="skill-commands");r.splice(c+1,0,{id:"show-hardware-cursor",label:"Show hardware cursor",description:"Show the terminal cursor while still positioning it for IME support",currentValue:e.showHardwareCursor?"true":"false",values:["true","false"]});let d=r.findIndex(m=>m.id==="show-hardware-cursor");r.splice(d+1,0,{id:"editor-padding",label:"Editor padding",description:"Horizontal padding for input editor (0-3)",currentValue:String(e.editorPaddingX),values:["0","1","2","3"]});let p=r.findIndex(m=>m.id==="editor-padding");r.splice(p+1,0,{id:"autocomplete-max-visible",label:"Autocomplete max items",description:"Max visible items in autocomplete dropdown (3-20)",currentValue:String(e.autocompleteMaxVisible),values:["3","5","7","10","15","20"]});let u=r.findIndex(m=>m.id==="autocomplete-max-visible");r.splice(u+1,0,{id:"clear-on-shrink",label:"Clear on shrink",description:"Clear empty rows when content shrinks (may cause flicker)",currentValue:e.clearOnShrink?"true":"false",values:["true","false"]});let h=r.findIndex(m=>m.id==="clear-on-shrink");r.splice(h+1,0,{id:"terminal-progress",label:"Terminal progress",description:"Show OSC 9;4 progress indicators in the terminal tab bar",currentValue:e.showTerminalProgress?"true":"false",values:["true","false"]}),this.addChild(new O),this.settingsList=new zn(r,10,Go(),(m,g)=>{switch(m){case"autocompact":t.onAutoCompactChange(g==="true");break;case"show-images":t.onShowImagesChange(g==="true");break;case"image-width-cells":t.onImageWidthCellsChange(parseInt(g,10));break;case"auto-resize-images":t.onAutoResizeImagesChange(g==="true");break;case"block-images":t.onBlockImagesChange(g==="true");break;case"skill-commands":t.onEnableSkillCommandsChange(g==="true");break;case"steering-mode":t.onSteeringModeChange(g);break;case"follow-up-mode":t.onFollowUpModeChange(g);break;case"transport":t.onTransportChange(g);break;case"hide-thinking":t.onHideThinkingBlockChange(g==="true");break;case"collapse-changelog":t.onCollapseChangelogChange(g==="true");break;case"quiet-startup":t.onQuietStartupChange(g==="true");break;case"install-telemetry":t.onEnableInstallTelemetryChange(g==="true");break;case"double-escape-action":t.onDoubleEscapeActionChange(g);break;case"tree-filter-mode":t.onTreeFilterModeChange(g);break;case"show-hardware-cursor":t.onShowHardwareCursorChange(g==="true");break;case"editor-padding":t.onEditorPaddingXChange(parseInt(g,10));break;case"autocomplete-max-visible":t.onAutocompleteMaxVisibleChange(parseInt(g,10));break;case"clear-on-shrink":t.onClearOnShrinkChange(g==="true");break;case"terminal-progress":t.onShowTerminalProgressChange(g==="true");break}},t.onCancel,{enableSearch:!0}),this.addChild(this.settingsList),this.addChild(new O)}getSettingsList(){return this.settingsList}};var $i=class extends he{constructor(t,n=we()){super(1,1,s=>f.bg("customMessageBg",s));this.expanded=!1;this.skillBlock=t,this.markdownTheme=n,this.updateDisplay()}setExpanded(t){this.expanded=t,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}updateDisplay(){if(this.clear(),this.expanded){let t=f.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m");this.addChild(new T(t,0,0));let n=`**${this.skillBlock.name}**
|
|
333
|
+
|
|
334
|
+
`;this.addChild(new le(n+this.skillBlock.content,0,0,this.markdownTheme,{color:s=>f.fg("customMessageText",s)}))}else{let t=f.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m ")+f.fg("customMessageText",this.skillBlock.name)+f.fg("dim",` (${z("app.tools.expand")} to expand)`);this.addChild(new T(t,0,0))}}};async function gg(i,e){if(e==="image/png")return{data:i,mimeType:e};let t=await fi();if(!t)return null;try{let n=new Uint8Array(Buffer.from(i,"base64")),s=t.PhotonImage.new_from_byteslice(n),o=xr(t,s,n);o!==s&&s.free();try{let r=o.get_bytes();return{data:Buffer.from(r).toString("base64"),mimeType:"image/png"}}finally{o.free()}}catch{return null}}var Mt=class extends L{constructor(t,n,s,o={},r,a,l){super();this.rendererState={};this.imageComponents=[];this.imageSpacers=[];this.expanded=!1;this.isPartial=!0;this.executionStarted=!1;this.argsComplete=!1;this.convertedImages=new Map;this.hideComponent=!1;this.toolName=t,this.toolCallId=n,this.args=s,this.toolDefinition=r,this.builtInToolDefinition=tc(l)[t],this.showImages=o.showImages??!0,this.imageWidthCells=o.imageWidthCells??60,this.ui=a,this.cwd=l,this.addChild(new E(1)),this.contentBox=new he(1,1,c=>f.bg("toolPendingBg",c)),this.contentText=new T("",1,1,c=>f.bg("toolPendingBg",c)),this.selfRenderContainer=new L,this.hasRendererDefinition()?this.addChild(this.getRenderShell()==="self"?this.selfRenderContainer:this.contentBox):this.addChild(this.contentText),this.updateDisplay()}getCallRenderer(){return this.builtInToolDefinition?this.toolDefinition?this.toolDefinition.renderCall??this.builtInToolDefinition.renderCall:this.builtInToolDefinition.renderCall:this.toolDefinition?.renderCall}getResultRenderer(){return this.builtInToolDefinition?this.toolDefinition?this.toolDefinition.renderResult??this.builtInToolDefinition.renderResult:this.builtInToolDefinition.renderResult:this.toolDefinition?.renderResult}hasRendererDefinition(){return this.builtInToolDefinition!==void 0||this.toolDefinition!==void 0}getRenderShell(){return this.builtInToolDefinition?this.toolDefinition?this.toolDefinition.renderShell??this.builtInToolDefinition.renderShell??"default":this.builtInToolDefinition.renderShell??"default":this.toolDefinition?.renderShell??"default"}getRenderContext(t){return{args:this.args,toolCallId:this.toolCallId,invalidate:()=>{this.invalidate(),this.ui.requestRender()},lastComponent:t,state:this.rendererState,cwd:this.cwd,executionStarted:this.executionStarted,argsComplete:this.argsComplete,isPartial:this.isPartial,expanded:this.expanded,showImages:this.showImages,isError:this.result?.isError??!1}}createCallFallback(){return new T(f.fg("toolTitle",f.bold(this.toolName)),0,0)}createResultFallback(){let t=this.getTextOutput();if(t)return new T(f.fg("toolOutput",t),0,0)}updateArgs(t){this.args=t,this.updateDisplay()}markExecutionStarted(){this.executionStarted=!0,this.updateDisplay(),this.ui.requestRender()}setArgsComplete(){this.argsComplete=!0,this.updateDisplay(),this.ui.requestRender()}updateResult(t,n=!1){this.result=t,this.isPartial=n,this.updateDisplay(),this.maybeConvertImagesForKitty()}maybeConvertImagesForKitty(){if(ve().images!=="kitty"||!this.result)return;let n=this.result.content.filter(s=>s.type==="image");for(let s=0;s<n.length;s++){let o=n[s];if(!o.data||!o.mimeType||o.mimeType==="image/png"||this.convertedImages.has(s))continue;let r=s;gg(o.data,o.mimeType).then(a=>{a&&(this.convertedImages.set(r,a),this.updateDisplay(),this.ui.requestRender())})}}setExpanded(t){this.expanded=t,this.updateDisplay()}setShowImages(t){this.showImages=t,this.updateDisplay()}setImageWidthCells(t){this.imageWidthCells=Math.max(1,Math.floor(t)),this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}render(t){return this.hideComponent?[]:super.render(t)}updateDisplay(){let t=this.isPartial?s=>f.bg("toolPendingBg",s):this.result?.isError?s=>f.bg("toolErrorBg",s):s=>f.bg("toolSuccessBg",s),n=!1;if(this.hideComponent=!1,this.hasRendererDefinition()){let s=this.getRenderShell()==="self"?this.selfRenderContainer:this.contentBox;s instanceof he&&s.setBgFn(t),s.clear();let o=this.getCallRenderer();if(!o)s.addChild(this.createCallFallback()),n=!0;else try{let r=o(this.args,f,this.getRenderContext(this.callRendererComponent));this.callRendererComponent=r,s.addChild(r),n=!0}catch{this.callRendererComponent=void 0,s.addChild(this.createCallFallback()),n=!0}if(this.result){let r=this.getResultRenderer();if(r)try{let a=r({content:this.result.content,details:this.result.details},{expanded:this.expanded,isPartial:this.isPartial},f,this.getRenderContext(this.resultRendererComponent));this.resultRendererComponent=a,s.addChild(a),n=!0}catch{this.resultRendererComponent=void 0;let a=this.createResultFallback();a&&(s.addChild(a),n=!0)}else{let a=this.createResultFallback();a&&(s.addChild(a),n=!0)}}}else this.contentText.setCustomBgFn(t),this.contentText.setText(this.formatToolExecution()),n=!0;for(let s of this.imageComponents)this.removeChild(s);this.imageComponents=[];for(let s of this.imageSpacers)this.removeChild(s);if(this.imageSpacers=[],this.result){let s=this.result.content.filter(r=>r.type==="image"),o=ve();for(let r=0;r<s.length;r++){let a=s[r];if(o.images&&this.showImages&&a.data&&a.mimeType){let l=this.convertedImages.get(r),c=l?.data??a.data,d=l?.mimeType??a.mimeType;if(o.images==="kitty"&&d!=="image/png")continue;let p=new E(1);this.addChild(p),this.imageSpacers.push(p);let u=new mn(c,d,{fallbackColor:h=>f.fg("toolOutput",h)},{maxWidthCells:this.imageWidthCells});this.imageComponents.push(u),this.addChild(u)}}}this.hasRendererDefinition()&&!n&&this.imageComponents.length===0&&(this.hideComponent=!0)}getTextOutput(){return it(this.result,this.showImages)}formatToolExecution(){let t=f.fg("toolTitle",f.bold(this.toolName)),n=JSON.stringify(this.args,null,2);n&&(t+=`
|
|
335
|
+
|
|
336
|
+
${n}`);let s=this.getTextOutput();return s&&(t+=`
|
|
337
|
+
${s}`),t}};var _c=class{constructor(e,t,n,s,o){this.flatNodes=[];this.filteredNodes=[];this.selectedIndex=0;this.filterMode="default";this.searchQuery="";this.toolCallMap=new Map;this.multipleRoots=!1;this.showLabelTimestamps=!1;this.activePathIds=new Set;this.visibleParentMap=new Map;this.visibleChildrenMap=new Map;this.lastSelectedId=null;this.foldedNodes=new Set;this.currentLeafId=t,this.maxVisibleLines=n,this.filterMode=o??"default",this.multipleRoots=e.length>1,this.flatNodes=this.flattenTree(e),this.buildActivePath(),this.applyFilter();let r=s??t;this.selectedIndex=this.findNearestVisibleIndex(r),this.lastSelectedId=this.filteredNodes[this.selectedIndex]?.node.entry.id??null}findNearestVisibleIndex(e){if(this.filteredNodes.length===0)return 0;let t=new Map;for(let o of this.flatNodes)t.set(o.node.entry.id,o);let n=new Map(this.filteredNodes.map((o,r)=>[o.node.entry.id,r])),s=e;for(;s!==null;){let o=n.get(s);if(o!==void 0)return o;let r=t.get(s);if(!r)break;s=r.node.entry.parentId??null}return this.filteredNodes.length-1}buildActivePath(){if(this.activePathIds.clear(),!this.currentLeafId)return;let e=new Map;for(let n of this.flatNodes)e.set(n.node.entry.id,n);let t=this.currentLeafId;for(;t;){this.activePathIds.add(t);let n=e.get(t);if(!n)break;t=n.node.entry.parentId??null}}flattenTree(e){let t=[];this.toolCallMap.clear();let n=[],s=new Map,o=this.currentLeafId;{let l=[],c=[...e];for(;c.length>0;){let d=c.pop();l.push(d);for(let p=d.children.length-1;p>=0;p--)c.push(d.children[p])}for(let d=l.length-1;d>=0;d--){let p=l[d],u=o!==null&&p.entry.id===o;for(let h of p.children)s.get(h)&&(u=!0);s.set(p,u)}}let r=e.length>1,a=[...e].sort((l,c)=>Number(s.get(c))-Number(s.get(l)));for(let l=a.length-1;l>=0;l--){let c=l===a.length-1;n.push([a[l],r?1:0,r,r,c,[],r])}for(;n.length>0;){let[l,c,d,p,u,h,m]=n.pop(),g=l.entry;if(g.type==="message"&&g.message.role==="assistant"){let S=g.message.content;if(Array.isArray(S)){for(let I of S)if(typeof I=="object"&&I!==null&&"type"in I&&I.type==="toolCall"){let P=I;this.toolCallMap.set(P.id,{name:P.name,arguments:P.arguments})}}}t.push({node:l,indent:c,showConnector:p,isLast:u,gutters:h,isVirtualRootChild:m});let x=l.children,b=x.length>1,v=(()=>{let S=[],I=[];for(let P of x)s.get(P)?S.push(P):I.push(P);return[...S,...I]})(),w;b||d&&c>0?w=c+1:w=c;let C=p&&!m,R=this.multipleRoots?Math.max(0,c-1):c,k=Math.max(0,R-1),A=C?[...h,{position:k,show:!u}]:h;for(let S=v.length-1;S>=0;S--){let I=S===v.length-1;n.push([v[S],w,b,b,I,A,!1])}}return t}applyFilter(){this.filteredNodes.length>0&&(this.lastSelectedId=this.filteredNodes[this.selectedIndex]?.node.entry.id??this.lastSelectedId);let e=this.searchQuery.toLowerCase().split(/\s+/).filter(Boolean);if(this.filteredNodes=this.flatNodes.filter(t=>{let n=t.node.entry,s=n.id===this.currentLeafId;if(n.type==="message"&&n.message.role==="assistant"&&!s){let a=n.message,l=this.hasTextContent(a.content),c=a.stopReason&&a.stopReason!=="stop"&&a.stopReason!=="toolUse";if(!l&&!c)return!1}let o=!0,r=n.type==="label"||n.type==="custom"||n.type==="model_change"||n.type==="thinking_level_change"||n.type==="session_info";switch(this.filterMode){case"user-only":o=n.type==="message"&&n.message.role==="user";break;case"no-tools":o=!r&&!(n.type==="message"&&n.message.role==="toolResult");break;case"labeled-only":o=t.node.label!==void 0;break;case"all":o=!0;break;default:o=!r;break}if(!o)return!1;if(e.length>0){let a=this.getSearchableText(t.node).toLowerCase();return e.every(l=>a.includes(l))}return!0}),this.foldedNodes.size>0){let t=new Set;for(let n of this.flatNodes){let{id:s,parentId:o}=n.node.entry;o!=null&&(this.foldedNodes.has(o)||t.has(o))&&t.add(s)}this.filteredNodes=this.filteredNodes.filter(n=>!t.has(n.node.entry.id))}this.recalculateVisualStructure(),this.lastSelectedId?this.selectedIndex=this.findNearestVisibleIndex(this.lastSelectedId):this.selectedIndex>=this.filteredNodes.length&&(this.selectedIndex=Math.max(0,this.filteredNodes.length-1)),this.filteredNodes.length>0&&(this.lastSelectedId=this.filteredNodes[this.selectedIndex]?.node.entry.id??this.lastSelectedId)}recalculateVisualStructure(){if(this.filteredNodes.length===0)return;let e=new Set(this.filteredNodes.map(c=>c.node.entry.id)),t=new Map;for(let c of this.flatNodes)t.set(c.node.entry.id,c);let n=c=>{let d=t.get(c)?.node.entry.parentId??null;for(;d!==null;){if(e.has(d))return d;d=t.get(d)?.node.entry.parentId??null}return null},s=new Map,o=new Map;o.set(null,[]);for(let c of this.filteredNodes){let d=c.node.entry.id,p=n(d);s.set(d,p),o.has(p)||o.set(p,[]),o.get(p).push(d)}let r=o.get(null);this.multipleRoots=r.length>1;let a=new Map;for(let c of this.filteredNodes)a.set(c.node.entry.id,c);let l=[];for(let c=r.length-1;c>=0;c--){let d=c===r.length-1;l.push([r[c],this.multipleRoots?1:0,this.multipleRoots,this.multipleRoots,d,[],this.multipleRoots])}for(;l.length>0;){let[c,d,p,u,h,m,g]=l.pop(),x=a.get(c);if(!x)continue;x.indent=d,x.showConnector=u,x.isLast=h,x.gutters=m,x.isVirtualRootChild=g;let b=o.get(c)||[],v=b.length>1,w;v||p&&d>0?w=d+1:w=d;let C=u&&!g,R=this.multipleRoots?Math.max(0,d-1):d,k=Math.max(0,R-1),A=C?[...m,{position:k,show:!h}]:m;for(let S=b.length-1;S>=0;S--){let I=S===b.length-1;l.push([b[S],w,v,v,I,A,!1])}}this.visibleParentMap=s,this.visibleChildrenMap=o}getSearchableText(e){let t=e.entry,n=[];switch(e.label&&n.push(e.label),t.type){case"message":{let s=t.message;if(n.push(s.role),"content"in s&&s.content&&n.push(this.extractContent(s.content)),s.role==="bashExecution"){let o=s;o.command&&n.push(o.command)}break}case"custom_message":{n.push(t.customType),typeof t.content=="string"?n.push(t.content):n.push(this.extractContent(t.content));break}case"compaction":n.push("compaction");break;case"branch_summary":n.push("branch summary",t.summary);break;case"session_info":n.push("title"),t.name&&n.push(t.name);break;case"model_change":n.push("model",t.modelId);break;case"thinking_level_change":n.push("thinking",t.thinkingLevel);break;case"custom":n.push("custom",t.customType);break;case"label":n.push("label",t.label??"");break}return n.join(" ")}invalidate(){}getSearchQuery(){return this.searchQuery}getSelectedNode(){return this.filteredNodes[this.selectedIndex]?.node}updateNodeLabel(e,t,n){for(let s of this.flatNodes)if(s.node.entry.id===e){s.node.label=t,s.node.labelTimestamp=t?n??new Date().toISOString():void 0;break}}getStatusLabels(){let e="";switch(this.filterMode){case"no-tools":e+=" [no-tools]";break;case"user-only":e+=" [user]";break;case"labeled-only":e+=" [labeled]";break;case"all":e+=" [all]";break}return this.showLabelTimestamps&&(e+=" [+label time]"),e}render(e){let t=[];if(this.filteredNodes.length===0)return t.push(G(f.fg("muted"," No entries found"),e)),t.push(G(f.fg("muted",` (0/0)${this.getStatusLabels()}`),e)),t;let n=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisibleLines/2),this.filteredNodes.length-this.maxVisibleLines)),s=Math.min(n+this.maxVisibleLines,this.filteredNodes.length);for(let o=n;o<s;o++){let r=this.filteredNodes[o],a=r.node.entry,l=o===this.selectedIndex,c=l?f.fg("accent","\u203A "):" ",d=this.multipleRoots?Math.max(0,r.indent-1):r.indent,p=r.showConnector&&!r.isVirtualRootChild?r.isLast?"\u2514\u2500 ":"\u251C\u2500 ":"",u=p?d-1:-1,h=d*3,m=[],g=this.foldedNodes.has(a.id);for(let I=0;I<h;I++){let P=Math.floor(I/3),M=I%3,_=r.gutters.find(U=>U.position===P);if(_)M===0?m.push(_.show?"\u2502":" "):m.push(" ");else if(p&&P===u)if(M===0)m.push(r.isLast?"\u2514":"\u251C");else if(M===1){let U=this.isFoldable(a.id);m.push(g?"\u229E":U?"\u229F":"\u2500")}else m.push(" ");else m.push(" ")}let x=m.join(""),b=r.showConnector&&!r.isVirtualRootChild,v=g&&!b?f.fg("accent","\u229E "):"",C=this.activePathIds.has(a.id)?f.fg("accent","\u2022 "):"",R=r.node.label?f.fg("warning",`[${r.node.label}] `):"",k=this.showLabelTimestamps&&r.node.label&&r.node.labelTimestamp?f.fg("muted",`${this.formatLabelTimestamp(r.node.labelTimestamp)} `):"",A=this.getEntryDisplayText(r.node,l),S=c+f.fg("dim",x)+v+C+R+k+A;l&&(S=f.bg("selectedBg",S)),t.push(G(S,e))}return t.push(G(f.fg("muted",` (${this.selectedIndex+1}/${this.filteredNodes.length})${this.getStatusLabels()}`),e)),t}getEntryDisplayText(e,t){let n=e.entry,s,o=r=>r.replace(/[\n\t]/g," ").trim();switch(n.type){case"message":{let r=n.message,a=r.role;if(a==="user"){let l=r,c=o(this.extractContent(l.content));s=f.fg("accent","user: ")+c}else if(a==="assistant"){let l=r,c=o(this.extractContent(l.content));if(c)s=f.fg("success","assistant: ")+c;else if(l.stopReason==="aborted")s=f.fg("success","assistant: ")+f.fg("muted","(aborted)");else if(l.errorMessage){let d=o(l.errorMessage).slice(0,80);s=f.fg("success","assistant: ")+f.fg("error",d)}else s=f.fg("success","assistant: ")+f.fg("muted","(no content)")}else if(a==="toolResult"){let l=r,c=l.toolCallId?this.toolCallMap.get(l.toolCallId):void 0;c?s=f.fg("muted",this.formatToolCall(c.name,c.arguments)):s=f.fg("muted",`[${l.toolName??"tool"}]`)}else if(a==="bashExecution"){let l=r;s=f.fg("dim",`[bash]: ${o(l.command??"")}`)}else s=f.fg("dim",`[${a}]`);break}case"custom_message":{let r=typeof n.content=="string"?n.content:n.content.filter(a=>a.type==="text").map(a=>a.text).join("");s=f.fg("customMessageLabel",`[${n.customType}]: `)+o(r);break}case"compaction":{let r=Math.round(n.tokensBefore/1e3);s=f.fg("borderAccent",`[compaction: ${r}k tokens]`);break}case"branch_summary":s=f.fg("warning","[branch summary]: ")+o(n.summary);break;case"model_change":s=f.fg("dim",`[model: ${n.modelId}]`);break;case"thinking_level_change":s=f.fg("dim",`[thinking: ${n.thinkingLevel}]`);break;case"custom":s=f.fg("dim",`[custom: ${n.customType}]`);break;case"label":s=f.fg("dim",`[label: ${n.label??"(cleared)"}]`);break;case"session_info":s=n.name?[f.fg("dim","[title: "),f.fg("dim",n.name),f.fg("dim","]")].join(""):[f.fg("dim","[title: "),f.italic(f.fg("dim","empty")),f.fg("dim","]")].join("");break;default:s=""}return t?f.bold(s):s}formatLabelTimestamp(e){let t=new Date(e),n=new Date,s=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0"),r=`${s}:${o}`;if(t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate())return r;let a=t.getMonth()+1,l=t.getDate();return t.getFullYear()===n.getFullYear()?`${a}/${l} ${r}`:`${t.getFullYear().toString().slice(-2)}/${a}/${l} ${r}`}extractContent(e){if(typeof e=="string")return e.slice(0,200);if(Array.isArray(e)){let n="";for(let s of e)if(typeof s=="object"&&s!==null&&"type"in s&&s.type==="text"&&(n+=s.text,n.length>=200))return n.slice(0,200);return n}return""}hasTextContent(e){if(typeof e=="string")return e.trim().length>0;if(Array.isArray(e)){for(let t of e)if(typeof t=="object"&&t!==null&&"type"in t&&t.type==="text"){let n=t.text;if(n&&n.trim().length>0)return!0}}return!1}formatToolCall(e,t){let n=s=>{let o=process.env.HOME||process.env.USERPROFILE||"";return o&&s.startsWith(o)?`~${s.slice(o.length)}`:s};switch(e){case"read":{let s=n(String(t.path||t.file_path||"")),o=t.offset,r=t.limit,a=s;if(o!==void 0||r!==void 0){let l=o??1,c=r!==void 0?l+r-1:"";a+=`:${l}${c?`-${c}`:""}`}return`[read: ${a}]`}case"write":return`[write: ${n(String(t.path||t.file_path||""))}]`;case"edit":return`[edit: ${n(String(t.path||t.file_path||""))}]`;case"bash":{let s=String(t.command||"");return`[bash: ${s.replace(/[\n\t]/g," ").trim().slice(0,50)}${s.length>50?"...":""}]`}case"grep":{let s=String(t.pattern||""),o=n(String(t.path||"."));return`[grep: /${s}/ in ${o}]`}case"find":{let s=String(t.pattern||""),o=n(String(t.path||"."));return`[find: ${s} in ${o}]`}case"ls":return`[ls: ${n(String(t.path||"."))}]`;default:{let s=JSON.stringify(t).slice(0,40);return`[${e}: ${s}${JSON.stringify(t).length>40?"...":""}]`}}}handleInput(e){let t=V();if(t.matches(e,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredNodes.length-1:this.selectedIndex-1;else if(t.matches(e,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredNodes.length-1?0:this.selectedIndex+1;else if(t.matches(e,"app.tree.foldOrUp")){let n=this.filteredNodes[this.selectedIndex]?.node.entry.id;n&&this.isFoldable(n)&&!this.foldedNodes.has(n)?(this.foldedNodes.add(n),this.applyFilter()):this.selectedIndex=this.findBranchSegmentStart("up")}else if(t.matches(e,"app.tree.unfoldOrDown")){let n=this.filteredNodes[this.selectedIndex]?.node.entry.id;n&&this.foldedNodes.has(n)?(this.foldedNodes.delete(n),this.applyFilter()):this.selectedIndex=this.findBranchSegmentStart("down")}else if(t.matches(e,"tui.editor.cursorLeft")||t.matches(e,"tui.select.pageUp"))this.selectedIndex=Math.max(0,this.selectedIndex-this.maxVisibleLines);else if(t.matches(e,"tui.editor.cursorRight")||t.matches(e,"tui.select.pageDown"))this.selectedIndex=Math.min(this.filteredNodes.length-1,this.selectedIndex+this.maxVisibleLines);else if(t.matches(e,"tui.select.confirm")){let n=this.filteredNodes[this.selectedIndex];n&&this.onSelect&&this.onSelect(n.node.entry.id)}else if(t.matches(e,"tui.select.cancel"))this.searchQuery?(this.searchQuery="",this.foldedNodes.clear(),this.applyFilter()):this.onCancel?.();else if(t.matches(e,"app.tree.filter.default"))this.filterMode="default",this.foldedNodes.clear(),this.applyFilter();else if(t.matches(e,"app.tree.filter.noTools"))this.filterMode=this.filterMode==="no-tools"?"default":"no-tools",this.foldedNodes.clear(),this.applyFilter();else if(t.matches(e,"app.tree.filter.userOnly"))this.filterMode=this.filterMode==="user-only"?"default":"user-only",this.foldedNodes.clear(),this.applyFilter();else if(t.matches(e,"app.tree.filter.labeledOnly"))this.filterMode=this.filterMode==="labeled-only"?"default":"labeled-only",this.foldedNodes.clear(),this.applyFilter();else if(t.matches(e,"app.tree.filter.all"))this.filterMode=this.filterMode==="all"?"default":"all",this.foldedNodes.clear(),this.applyFilter();else if(t.matches(e,"app.tree.filter.cycleBackward")){let n=["default","no-tools","user-only","labeled-only","all"],s=n.indexOf(this.filterMode);this.filterMode=n[(s-1+n.length)%n.length],this.foldedNodes.clear(),this.applyFilter()}else if(t.matches(e,"app.tree.filter.cycleForward")){let n=["default","no-tools","user-only","labeled-only","all"],s=n.indexOf(this.filterMode);this.filterMode=n[(s+1)%n.length],this.foldedNodes.clear(),this.applyFilter()}else if(t.matches(e,"tui.editor.deleteCharBackward"))this.searchQuery.length>0&&(this.searchQuery=this.searchQuery.slice(0,-1),this.foldedNodes.clear(),this.applyFilter());else if(t.matches(e,"app.tree.editLabel")){let n=this.filteredNodes[this.selectedIndex];n&&this.onLabelEdit&&this.onLabelEdit(n.node.entry.id,n.node.label)}else t.matches(e,"app.tree.toggleLabelTimestamp")?this.showLabelTimestamps=!this.showLabelTimestamps:![...e].some(s=>{let o=s.charCodeAt(0);return o<32||o===127||o>=128&&o<=159})&&e.length>0&&(this.searchQuery+=e,this.foldedNodes.clear(),this.applyFilter())}isFoldable(e){let t=this.visibleChildrenMap.get(e);if(!t||t.length===0)return!1;let n=this.visibleParentMap.get(e);if(n==null)return!0;let s=this.visibleChildrenMap.get(n);return s!==void 0&&s.length>1}findBranchSegmentStart(e){let t=this.filteredNodes[this.selectedIndex]?.node.entry.id;if(!t)return this.selectedIndex;let n=new Map(this.filteredNodes.map((o,r)=>[o.node.entry.id,r])),s=t;if(e==="down")for(;;){let o=this.visibleChildrenMap.get(s)??[];if(o.length===0)return n.get(s);if(o.length>1)return n.get(o[0]);s=o[0]}for(;;){let o=this.visibleParentMap.get(s)??null;if(o===null)return n.get(s);if((this.visibleChildrenMap.get(o)??[]).length>1){let a=n.get(s);if(a<this.selectedIndex)return a}s=o}}},Lc=class{constructor(e){this.treeList=e}invalidate(){}render(e){let t=this.treeList.getSearchQuery();return t?[G(` ${f.fg("muted","Type to search:")} ${f.fg("accent",t)}`,e)]:[G(` ${f.fg("muted","Type to search:")}`,e)]}handleInput(e){}},Wc=class{constructor(e,t){this._focused=!1;this.entryId=e,this.input=new pe,t&&this.input.setValue(t)}get focused(){return this._focused}set focused(e){this._focused=e,this.input.focused=e}invalidate(){}render(e){let t=[],s=e-2;return t.push(G(` ${f.fg("muted","Label (empty to remove):")}`,e)),t.push(...this.input.render(s).map(o=>G(` ${o}`,e))),t.push(G(` ${N("tui.select.confirm","save")} ${N("tui.select.cancel","cancel")}`,e)),t}handleInput(e){let t=V();if(t.matches(e,"tui.select.confirm")){let n=this.input.getValue().trim();this.onSubmit?.(this.entryId,n||void 0)}else t.matches(e,"tui.select.cancel")?this.onCancel?.():this.input.handleInput(e)}},Bi=class extends L{constructor(t,n,s,o,r,a,l,c){super();this.labelInput=null;this._focused=!1;this.onLabelChangeCallback=a;let d=Math.max(5,Math.floor(s/2));this.treeList=new _c(t,n,d,l,c),this.treeList.onSelect=o,this.treeList.onCancel=r,this.treeList.onLabelEdit=(m,g)=>this.showLabelInput(m,g),this.treeContainer=new L,this.treeContainer.addChild(this.treeList),this.labelInputContainer=new L,this.addChild(new E(1)),this.addChild(new O),this.addChild(new T(f.bold(" Session Tree"),1,0));let p=[z("app.tree.filter.default"),z("app.tree.filter.noTools"),z("app.tree.filter.userOnly"),z("app.tree.filter.labeledOnly"),z("app.tree.filter.all")].join("/"),u=`${z("app.tree.filter.cycleForward")}/${z("app.tree.filter.cycleBackward")}`,h=`${z("app.tree.foldOrUp")}/${z("app.tree.unfoldOrDown")}`;this.addChild(new $e(f.fg("muted",` \u2191/\u2193: move. \u2190/\u2192: page. ${h}: fold/branch. ${z("app.tree.editLabel")}: label. ${p}: filters (${u} cycle). ${z("app.tree.toggleLabelTimestamp")}: label time`),0,0)),this.addChild(new Lc(this.treeList)),this.addChild(new O),this.addChild(new E(1)),this.addChild(this.treeContainer),this.addChild(this.labelInputContainer),this.addChild(new E(1)),this.addChild(new O),t.length===0&&setTimeout(()=>r(),100)}get focused(){return this._focused}set focused(t){this._focused=t,this.labelInput&&(this.labelInput.focused=t)}showLabelInput(t,n){this.labelInput=new Wc(t,n),this.labelInput.onSubmit=(s,o)=>{this.treeList.updateNodeLabel(s,o),this.onLabelChangeCallback?.(s,o),this.hideLabelInput()},this.labelInput.onCancel=()=>this.hideLabelInput(),this.labelInput.focused=this._focused,this.treeContainer.clear(),this.labelInputContainer.clear(),this.labelInputContainer.addChild(this.labelInput)}hideLabelInput(){this.labelInput=null,this.labelInputContainer.clear(),this.treeContainer.clear(),this.treeContainer.addChild(this.treeList)}handleInput(t){this.labelInput?this.labelInput.handleInput(t):this.treeList.handleInput(t)}getTreeList(){return this.treeList}};var dM="\x1B]133;A\x07",uM="\x1B]133;B\x07",mM="\x1B]133;C\x07",Un=class extends L{constructor(e,t=we()){super(),this.contentBox=new he(1,1,n=>f.bg("userMessageBg",n)),this.contentBox.addChild(new le(e,0,0,t,{color:n=>f.fg("userMessageText",n)})),this.addChild(this.contentBox)}render(e){let t=super.render(e);return t.length===0||(t[0]=dM+t[0],t[t.length-1]=uM+mM+t[t.length-1]),t}};var Oc=class{constructor(e,t){this.messages=[];this.selectedIndex=0;this.maxVisible=10;this.messages=e;let n=t?e.findIndex(s=>s.id===t):-1;this.selectedIndex=n>=0?n:Math.max(0,e.length-1)}invalidate(){}render(e){let t=[];if(this.messages.length===0)return t.push(f.fg("muted"," No user messages found")),t;let n=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.messages.length-this.maxVisible)),s=Math.min(n+this.maxVisible,this.messages.length);for(let o=n;o<s;o++){let r=this.messages[o],a=o===this.selectedIndex,l=r.text.replace(/\n/g," ").trim(),c=a?f.fg("accent","\u203A "):" ",d=e-2,p=G(l,d),u=c+(a?f.bold(p):p);t.push(u);let m=` Message ${o+1} of ${this.messages.length}`,g=f.fg("muted",m);t.push(g),t.push("")}if(n>0||s<this.messages.length){let o=f.fg("muted",` (${this.selectedIndex+1}/${this.messages.length})`);t.push(o)}return t}handleInput(e){let t=V();if(t.matches(e,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.messages.length-1:this.selectedIndex-1;else if(t.matches(e,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.messages.length-1?0:this.selectedIndex+1;else if(t.matches(e,"tui.select.confirm")){let n=this.messages[this.selectedIndex];n&&this.onSelect&&this.onSelect(n.id)}else t.matches(e,"tui.select.cancel")&&this.onCancel&&this.onCancel()}},Ni=class extends L{constructor(e,t,n,s){super(),this.addChild(new E(1)),this.addChild(new T(f.bold("Fork from Message"),1,0)),this.addChild(new T(f.fg("muted","Select a user message to copy the active path up to that point into a new session"),1,0)),this.addChild(new E(1)),this.addChild(new O),this.addChild(new E(1)),this.messageList=new Oc(e,s),this.messageList.onSelect=t,this.messageList.onCancel=n,this.addChild(this.messageList),this.addChild(new E(1)),this.addChild(new O),e.length===0&&setTimeout(()=>n(),100)}getMessageList(){return this.messageList}};function js(i){return typeof i=="object"&&i!==null&&"setExpanded"in i&&typeof i.setExpanded=="function"}var Dr=class extends T{constructor(t,n,s=!1,o=0,r=0){super(s?n():t(),o,r);this.getCollapsedText=t;this.getExpandedText=n}setExpanded(t){this.setText(t?this.getExpandedText():this.getCollapsedText())}},hM=new Set(["EIO","EPIPE","ENOTCONN"]);function gM(i){if(!i||typeof i!="object"||!("code"in i))return!1;let e=i.code;return e!==void 0&&hM.has(e)}var bg="Anthropic subscription auth is active. Third-party harness usage draws from extra usage and is billed per token, not your Claude plan limits. Manage extra usage at https://claude.ai/settings/usage.";function fM(i){return typeof i=="string"&&i.startsWith("sk-ant-oat")}function xM(i){return!!i&&i.provider==="unknown"&&i.id==="unknown"&&i.api==="unknown"}function bM(i){return i in gc}var vM="amazon-bedrock",yM=new Set(Ra());function wM(i,e,t=yM){return ic[i]?!0:t.has(i)?!1:!e.has(i)}var qs=class i{constructor(e,t={}){this.options=t;this.autocompleteProviderWrappers=[];this.isInitialized=!1;this.loadingAnimation=void 0;this.workingMessage=void 0;this.workingVisible=!0;this.workingIndicatorOptions=void 0;this.defaultWorkingMessage="Working...";this.defaultHiddenThinkingLabel="Thinking...";this.hiddenThinkingLabel=this.defaultHiddenThinkingLabel;this.lastSigintTime=0;this.lastEscapeTime=0;this.changelogMarkdown=void 0;this.startupNoticesShown=!1;this.anthropicSubscriptionWarningShown=!1;this.lastStatusSpacer=void 0;this.lastStatusText=void 0;this.streamingComponent=void 0;this.streamingMessage=void 0;this.pendingTools=new Map;this.toolOutputExpanded=!1;this.hideThinkingBlock=!1;this.skillCommands=new Map;this.signalCleanupHandlers=[];this.isBashMode=!1;this.bashComponent=void 0;this.pendingBashComponents=[];this.autoCompactionLoader=void 0;this.retryLoader=void 0;this.retryCountdown=void 0;this.compactionQueuedMessages=[];this.shutdownRequested=!1;this.extensionSelector=void 0;this.extensionInput=void 0;this.extensionEditor=void 0;this.extensionTerminalInputUnsubscribers=new Set;this.extensionWidgetsAbove=new Map;this.extensionWidgetsBelow=new Map;this.customFooter=void 0;this.builtInHeader=void 0;this.customHeader=void 0;this.isShuttingDown=!1;this.runtimeHost=e,this.runtimeHost.setBeforeSessionInvalidate(()=>{this.resetExtensionUI()}),this.runtimeHost.setRebindSession(async()=>{await this.rebindCurrentSession()}),this.version=Lt,this.ui=new Ht(new jt,this.settingsManager.getShowHardwareCursor()),this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink()),this.headerContainer=new L,this.chatContainer=new L,this.pendingMessagesContainer=new L,this.statusContainer=new L,this.widgetContainerAbove=new L,this.widgetContainerBelow=new L,this.keybindings=en.create(),Qi(this.keybindings);let n=this.settingsManager.getEditorPaddingX(),s=this.settingsManager.getAutocompleteMaxVisible();this.defaultEditor=new Ai(this.ui,ws(),this.keybindings,{paddingX:n,autocompleteMaxVisible:s}),this.editor=this.defaultEditor,this.editorContainer=new L,this.editorContainer.addChild(this.editor),this.footerDataProvider=new Pr(this.sessionManager.getCwd()),this.footer=new Ui(this.session,this.footerDataProvider),this.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled),this.hideThinkingBlock=this.settingsManager.getHideThinkingBlock(),No(this.session.resourceLoader.getThemes().themes),vs(this.settingsManager.getTheme(),!0)}get session(){return this.runtimeHost.session}get agent(){return this.session.agent}get sessionManager(){return this.session.sessionManager}get settingsManager(){return this.session.settingsManager}getAutocompleteSourceTag(e){if(!e)return;let t=e.scope==="user"?"u":e.scope==="project"?"p":"t",n=e.source.trim();if(n==="auto"||n==="local"||n==="cli")return t;if(n.startsWith("npm:"))return`${t}:${n}`;let s=Us(n);if(s){let o=s.ref?`@${s.ref}`:"";return`${t}:git:${s.host}/${s.path}${o}`}return t}prefixAutocompleteDescription(e,t){let n=this.getAutocompleteSourceTag(t);return n?e?`[${n}] ${e}`:`[${n}]`:e}getBuiltInCommandConflictDiagnostics(e){let t=new Set(Sc.map(n=>n.name));return e.getRegisteredCommands().filter(n=>t.has(n.name)).map(n=>({type:"warning",message:n.invocationName===n.name?`Extension command '/${n.name}' conflicts with built-in interactive command. Skipping in autocomplete.`:`Extension command '/${n.name}' conflicts with built-in interactive command. Available as '/${n.invocationName}'.`,path:n.sourceInfo.path}))}createBaseAutocompleteProvider(){let e=Sc.map(a=>({name:a.name,description:a.description})),t=e.find(a=>a.name==="model");t&&(t.getArgumentCompletions=a=>{let l=this.session.scopedModels.length>0?this.session.scopedModels.map(p=>p.model):this.session.modelRegistry.getAvailable();if(l.length===0)return null;let c=l.map(p=>({id:p.id,provider:p.provider,label:`${p.provider}/${p.id}`})),d=We(c,a,p=>`${p.id} ${p.provider}`);return d.length===0?null:d.map(p=>({value:p.label,label:p.id,description:p.provider}))});let n=this.session.promptTemplates.map(a=>({name:a.name,description:this.prefixAutocompleteDescription(a.description,a.sourceInfo),...a.argumentHint&&{argumentHint:a.argumentHint}})),s=new Set(e.map(a=>a.name)),o=this.session.extensionRunner.getRegisteredCommands().filter(a=>!s.has(a.name)).map(a=>({name:a.invocationName,description:this.prefixAutocompleteDescription(a.description,a.sourceInfo),getArgumentCompletions:a.getArgumentCompletions}));this.skillCommands.clear();let r=[];if(this.settingsManager.getEnableSkillCommands())for(let a of this.session.resourceLoader.getSkills().skills){let l=`skill:${a.name}`;this.skillCommands.set(l,a.filePath),r.push({name:l,description:this.prefixAutocompleteDescription(a.description,a.sourceInfo)})}return new zi([...e,...n,...o,...r],this.sessionManager.getCwd(),this.fdPath)}setupAutocompleteProvider(){let e=this.createBaseAutocompleteProvider();for(let t of this.autocompleteProviderWrappers)e=t(e);this.autocompleteProvider=e,this.defaultEditor.setAutocompleteProvider(e),this.editor!==this.defaultEditor&&this.editor.setAutocompleteProvider?.(e)}showStartupNoticesIfNeeded(){if(!this.startupNoticesShown&&(this.startupNoticesShown=!0,!!this.changelogMarkdown)){if(this.chatContainer.children.length>0&&this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new O),this.settingsManager.getCollapseChangelog()){let e=this.changelogMarkdown.match(/##\s+\[?(\d+\.\d+\.\d+)\]?/),n=`Updated to v${e?e[1]:this.version}. Use ${f.bold("/changelog")} to view full changelog.`;this.chatContainer.addChild(new T(n,1,0))}else this.chatContainer.addChild(new T(f.bold(f.fg("accent","What's New")),1,0)),this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new le(this.changelogMarkdown.trim(),1,0,this.getMarkdownThemeWithSettings())),this.chatContainer.addChild(new E(1));this.chatContainer.addChild(new O)}}async init(){if(this.isInitialized)return;this.registerSignalHandlers(),this.changelogMarkdown=this.getChangelogForDisplay();let[e]=await Promise.all([An("fd"),An("rg")]);if(this.fdPath=e,this.ui.addChild(this.headerContainer),this.options.verbose||!this.settingsManager.getQuietStartup()){let t=f.bold(f.fg("accent",Ae))+f.fg("dim",` v${this.version}`),n=(l,c)=>N(l,c),s=[n("app.interrupt","to interrupt"),n("app.clear","to clear"),Le(`${z("app.clear")} twice`,"to exit"),n("app.exit","to exit (empty)"),n("app.suspend","to suspend"),N("tui.editor.deleteToLineEnd","to delete to end"),n("app.thinking.cycle","to cycle thinking level"),Le(`${z("app.model.cycleForward")}/${z("app.model.cycleBackward")}`,"to cycle models"),n("app.model.select","to select model"),n("app.tools.expand","to expand tools"),n("app.thinking.toggle","to expand thinking"),n("app.editor.external","for external editor"),Le("/","for commands"),Le("!","to run bash"),Le("!!","to run bash (no context)"),n("app.message.followUp","to queue follow-up"),n("app.message.dequeue","to edit all queued messages"),n("app.clipboard.pasteImage","to paste image"),Le("drop files","to attach")].join(`
|
|
338
|
+
`),o=[n("app.interrupt","interrupt"),Le(`${z("app.clear")}/${z("app.exit")}`,"clear/exit"),Le("/","commands"),Le("!","bash"),n("app.tools.expand","more")].join(f.fg("muted"," \xB7 ")),r=f.fg("dim",`Press ${z("app.tools.expand")} to show full startup help and loaded resources.`),a=f.fg("dim","Pi can explain its own features and look up its docs. Ask it how to use or extend Pi.");this.builtInHeader=new Dr(()=>`${t}
|
|
339
|
+
${o}
|
|
340
|
+
${r}
|
|
341
|
+
|
|
342
|
+
${a}`,()=>`${t}
|
|
343
|
+
${s}
|
|
344
|
+
|
|
345
|
+
${a}`,this.getStartupExpansionState(),1,0),this.headerContainer.addChild(new E(1)),this.headerContainer.addChild(this.builtInHeader),this.headerContainer.addChild(new E(1))}else this.builtInHeader=new T("",0,0),this.headerContainer.addChild(this.builtInHeader);this.ui.addChild(this.chatContainer),this.ui.addChild(this.pendingMessagesContainer),this.ui.addChild(this.statusContainer),this.renderWidgets(),this.ui.addChild(this.widgetContainerAbove),this.ui.addChild(this.editorContainer),this.ui.addChild(this.widgetContainerBelow),this.ui.addChild(this.footer),this.ui.setFocus(this.editor),this.setupKeyHandlers(),this.setupEditorSubmitHandler(),this.ui.start(),this.isInitialized=!0,await this.rebindCurrentSession(),this.renderInitialMessages(),Qu(()=>{this.ui.invalidate(),this.updateEditorBorderColor(),this.ui.requestRender()}),this.footerDataProvider.onBranchChange(()=>{this.ui.requestRender()}),await this.updateAvailableProviderCount()}updateTerminalTitle(){let e=se.basename(this.sessionManager.getCwd()),t=this.sessionManager.getSessionName();t?this.ui.terminal.setTitle(`${wa} - ${t} - ${e}`):this.ui.terminal.setTitle(`${wa} - ${e}`)}async run(){await this.init(),tg(this.version).then(a=>{a&&this.showNewVersionNotification(a)}),this.checkForPackageUpdates().then(a=>{a.length>0&&this.showPackageUpdateNotification(a)}),this.checkTmuxKeyboardSetup().then(a=>{a&&this.showWarning(a)});let{migratedProviders:e,modelFallbackMessage:t,initialMessage:n,initialImages:s,initialMessages:o}=this.options;e&&e.length>0&&this.showWarning(`Migrated credentials to auth.json: ${e.join(", ")}`);let r=this.session.modelRegistry.getError();if(r&&this.showError(`models.json error: ${r}`),t&&this.showWarning(t),this.maybeWarnAboutAnthropicSubscriptionAuth(),n)try{await this.session.prompt(n,{images:s})}catch(a){let l=a instanceof Error?a.message:"Unknown error occurred";this.showError(l)}if(o)for(let a of o)try{await this.session.prompt(a)}catch(l){let c=l instanceof Error?l.message:"Unknown error occurred";this.showError(c)}for(;;){let a=await this.getUserInput();try{await this.session.prompt(a)}catch(l){let c=l instanceof Error?l.message:"Unknown error occurred";this.showError(c)}}}async checkForPackageUpdates(){if(process.env.PI_OFFLINE)return[];try{return(await new Ln({cwd:this.sessionManager.getCwd(),agentDir:ce(),settingsManager:this.settingsManager}).checkForAvailableUpdates()).map(n=>n.displayName)}catch{return[]}}async checkTmuxKeyboardSetup(){if(!process.env.TMUX)return;let e=s=>new Promise(o=>{let r=fg("tmux",["show","-gv",s],{stdio:["ignore","pipe","ignore"]}),a="",l=setTimeout(()=>{r.kill(),o(void 0)},2e3);r.stdout?.on("data",c=>{a+=c.toString()}),r.on("error",()=>{clearTimeout(l),o(void 0)}),r.on("close",c=>{clearTimeout(l),o(c===0?a.trim():void 0)})}),[t,n]=await Promise.all([e("extended-keys"),e("extended-keys-format")]);if(t!==void 0){if(t!=="on"&&t!=="always")return"tmux extended-keys is off. Modified Enter keys may not work. Add `set -g extended-keys on` to ~/.tmux.conf and restart tmux.";if(n==="xterm")return"tmux extended-keys-format is xterm. Pi works best with csi-u. Add `set -g extended-keys-format csi-u` to ~/.tmux.conf and restart tmux."}}getChangelogForDisplay(){if(this.session.state.messages.length>0)return;let e=this.settingsManager.getLastChangelogVersion(),t=vo(),n=Tc(t);if(!e){this.settingsManager.setLastChangelogVersion(Lt),this.reportInstallTelemetry(Lt);return}let s=Hh(n,e);if(s.length>0)return this.settingsManager.setLastChangelogVersion(Lt),this.reportInstallTelemetry(Lt),s.map(o=>o.content).join(`
|
|
346
|
+
|
|
347
|
+
`)}reportInstallTelemetry(e){process.env.PI_OFFLINE||xc(this.settingsManager)&&fetch(`https://pi.dev/api/report-install?version=${encodeURIComponent(e)}`,{headers:{"User-Agent":Lr(e)},signal:AbortSignal.timeout(5e3)}).then(()=>{}).catch(()=>{})}getMarkdownThemeWithSettings(){return{...we(),codeBlockIndent:this.settingsManager.getCodeBlockIndent()}}formatDisplayPath(e){let t=Gi.homedir(),n=e;return n.startsWith(t)&&(n=`~${n.slice(t.length)}`),n}formatExtensionDisplayPath(e){let t=this.formatDisplayPath(e);return t=t.replace(/\/index\.ts$/,"").replace(/\/index\.js$/,""),t}formatContextPath(e){let t=se.resolve(this.sessionManager.getCwd()),n=se.isAbsolute(e)?se.resolve(e):se.resolve(t,e),s=Il(n,t);return s!==void 0?s:this.formatDisplayPath(n)}getStartupExpansionState(){return this.options.verbose||this.toolOutputExpanded}getShortPath(e,t){let n=t?.baseDir;if(n&&this.isPackageSource(t)){let a=se.relative(se.resolve(n),se.resolve(e));if(a&&a!=="."&&!a.startsWith("..")&&!a.startsWith(`..${se.sep}`)&&!se.isAbsolute(a))return a.replace(/\\/g,"/")}let s=t?.source??"",o=e.match(/node_modules\/(@?[^/]+(?:\/[^/]+)?)\/(.*)/);if(o&&s.startsWith("npm:"))return o[2];let r=e.match(/git\/[^/]+\/[^/]+\/(.*)/);return r&&s.startsWith("git:")?r[1]:this.formatDisplayPath(e)}getCompactPathLabel(e,t){let n=this.getShortPath(e,t),o=n.replace(/\\/g,"/").split("/").filter(r=>r.length>0&&r!=="~");return o.length>0?o[o.length-1]:n}getCompactPackageSourceLabel(e){let t=e?.source??"";if(t.startsWith("npm:"))return t.slice(4)||t;let n=Us(t);return n&&n.path||t}getCompactExtensionLabel(e,t){if(!this.isPackageSource(t))return this.getCompactPathLabel(e,t);let n=this.getCompactPackageSourceLabel(t);if(!n)return this.getCompactPathLabel(e,t);let s=this.getShortPath(e,t).replace(/\\/g,"/"),o=s.startsWith("extensions/")?s.slice(11):s,r=se.posix.parse(o);return r.name==="index"?!r.dir||r.dir==="."?n:`${n}:${r.dir}`:`${n}:${o}`}getCompactDisplayPathSegments(e){return this.formatDisplayPath(e).replace(/\\/g,"/").split("/").filter(t=>t.length>0&&t!=="~")}getCompactNonPackageExtensionLabel(e,t,n){let s=n[t]?.segments;if(!s||s.length===0)return this.getCompactPathLabel(e);for(let o=1;o<=s.length;o+=1){let r=s.slice(-o).join("/");if(n.every((l,c)=>c===t?!0:l.segments.slice(-o).join("/")!==r))return r}return s.join("/")}getCompactExtensionLabels(e){let t=e.map(n=>{let s=this.getCompactDisplayPathSegments(n.path),o=s[s.length-1];return s.length>1&&(o==="index.ts"||o==="index.js")&&s.pop(),{path:n.path,sourceInfo:n.sourceInfo,segments:s}}).filter(n=>!this.isPackageSource(n.sourceInfo));return e.map(n=>{if(this.isPackageSource(n.sourceInfo))return this.getCompactExtensionLabel(n.path,n.sourceInfo);let s=t.findIndex(o=>o.path===n.path);return s===-1?this.getCompactPathLabel(n.path,n.sourceInfo):this.getCompactNonPackageExtensionLabel(n.path,s,t)})}getDisplaySourceInfo(e){let t=e?.source??"local",n=e?.scope??"project";return t==="local"?n==="user"?{label:"user",color:"muted"}:n==="project"?{label:"project",color:"muted"}:n==="temporary"?{label:"path",scopeLabel:"temp",color:"muted"}:{label:"path",color:"muted"}:t==="cli"?{label:"path",scopeLabel:n==="temporary"?"temp":void 0,color:"muted"}:{label:t,scopeLabel:n==="user"?"user":n==="project"?"project":n==="temporary"?"temp":void 0,color:"accent"}}getScopeGroup(e){let t=e?.source??"local",n=e?.scope??"project";return t==="cli"||n==="temporary"?"path":n==="user"?"user":n==="project"?"project":"path"}isPackageSource(e){let t=e?.source??"";return t.startsWith("npm:")||t.startsWith("git:")}buildScopeGroups(e){let t={user:{scope:"user",paths:[],packages:new Map},project:{scope:"project",paths:[],packages:new Map},path:{scope:"path",paths:[],packages:new Map}};for(let n of e){let s=this.getScopeGroup(n.sourceInfo),o=t[s],r=n.sourceInfo?.source??"local";if(this.isPackageSource(n.sourceInfo)){let a=o.packages.get(r)??[];a.push(n),o.packages.set(r,a)}else o.paths.push(n)}return[t.project,t.user,t.path].filter(n=>n.paths.length>0||n.packages.size>0)}formatScopeGroups(e,t){let n=[];for(let s of e){n.push(` ${f.fg("accent",s.scope)}`);let o=[...s.paths].sort((a,l)=>a.path.localeCompare(l.path));for(let a of o)n.push(f.fg("dim",` ${t.formatPath(a)}`));let r=Array.from(s.packages.entries()).sort(([a],[l])=>a.localeCompare(l));for(let[a,l]of r){n.push(` ${f.fg("mdLink",a)}`);let c=[...l].sort((d,p)=>d.path.localeCompare(p.path));for(let d of c)n.push(f.fg("dim",` ${t.formatPackagePath(d,a)}`))}}return n.join(`
|
|
348
|
+
`)}findSourceInfoForPath(e,t){let n=t.get(e);if(n)return n;let s=e;for(;s.includes("/");){s=s.substring(0,s.lastIndexOf("/"));let o=t.get(s);if(o)return o}}formatPathWithSource(e,t){if(t){let n=this.getShortPath(e,t),{label:s,scopeLabel:o}=this.getDisplaySourceInfo(t);return`${o?`${s} (${o})`:s} ${n}`}return this.formatDisplayPath(e)}formatDiagnostics(e,t){let n=[],s=new Map,o=[];for(let r of e)if(r.type==="collision"&&r.collision){let a=s.get(r.collision.name)??[];a.push(r),s.set(r.collision.name,a)}else o.push(r);for(let[r,a]of s){let l=a[0]?.collision;if(l){n.push(f.fg("warning",` "${r}" collision:`)),n.push(f.fg("dim",` ${f.fg("success","\u2713")} ${this.formatPathWithSource(l.winnerPath,this.findSourceInfoForPath(l.winnerPath,t))}`));for(let c of a)c.collision&&n.push(f.fg("dim",` ${f.fg("warning","\u2717")} ${this.formatPathWithSource(c.collision.loserPath,this.findSourceInfoForPath(c.collision.loserPath,t))} (skipped)`))}}for(let r of o)if(r.path){let a=this.formatPathWithSource(r.path,this.findSourceInfoForPath(r.path,t));n.push(f.fg(r.type==="error"?"error":"warning",` ${a}`)),n.push(f.fg(r.type==="error"?"error":"warning",` ${r.message}`))}else n.push(f.fg(r.type==="error"?"error":"warning",` ${r.message}`));return n.join(`
|
|
349
|
+
`)}showLoadedResources(e){let t=e?.force||this.options.verbose||!this.settingsManager.getQuietStartup(),n=t||e?.showDiagnosticsWhenQuiet===!0;if(!t&&!n)return;let s=(u,h="mdHeading")=>f.fg(h,`[${u}]`),o=(u,h)=>{let m=u.map(g=>g.trim()).filter(g=>g.length>0);return h?.sort!==!1&&m.sort((g,x)=>g.localeCompare(x)),f.fg("dim",` ${m.join(", ")}`)},r=(u,h,m=h,g="mdHeading")=>{let x=new Dr(()=>`${s(u,g)}
|
|
350
|
+
${h}`,()=>`${s(u,g)}
|
|
351
|
+
${m}`,this.getStartupExpansionState(),0,0);this.chatContainer.addChild(x),this.chatContainer.addChild(new E(1))},a=this.session.resourceLoader.getSkills(),l=this.session.resourceLoader.getPrompts(),c=this.session.resourceLoader.getThemes(),d=e?.extensions??this.session.resourceLoader.getExtensions().extensions.map(u=>({path:u.path,sourceInfo:u.sourceInfo})),p=new Map;for(let u of d)u.sourceInfo&&p.set(u.path,u.sourceInfo);for(let u of a.skills)u.sourceInfo&&p.set(u.filePath,u.sourceInfo);for(let u of l.prompts)u.sourceInfo&&p.set(u.filePath,u.sourceInfo);for(let u of c.themes)u.sourcePath&&u.sourceInfo&&p.set(u.sourcePath,u.sourceInfo);if(t){let u=this.session.resourceLoader.getAgentsFiles().agentsFiles;if(u.length>0){this.chatContainer.addChild(new E(1));let b=u.map(w=>f.fg("dim",` ${this.formatDisplayPath(w.path)}`)).join(`
|
|
352
|
+
`),v=o(u.map(w=>this.formatContextPath(w.path)),{sort:!1});r("Context",v,b)}let h=a.skills;if(h.length>0){let b=this.buildScopeGroups(h.map(C=>({path:C.filePath,sourceInfo:C.sourceInfo}))),v=this.formatScopeGroups(b,{formatPath:C=>this.formatDisplayPath(C.path),formatPackagePath:C=>this.getShortPath(C.path,C.sourceInfo)}),w=o(h.map(C=>C.name));r("Skills",w,v)}let m=this.session.promptTemplates;if(m.length>0){let b=this.buildScopeGroups(m.map(R=>({path:R.filePath,sourceInfo:R.sourceInfo}))),v=new Map(m.map(R=>[R.filePath,R])),w=this.formatScopeGroups(b,{formatPath:R=>{let k=v.get(R.path);return k?`/${k.name}`:this.formatDisplayPath(R.path)},formatPackagePath:R=>{let k=v.get(R.path);return k?`/${k.name}`:this.formatDisplayPath(R.path)}}),C=o(m.map(R=>`/${R.name}`));r("Prompts",C,w)}if(d.length>0){let b=this.buildScopeGroups(d),v=this.formatScopeGroups(b,{formatPath:C=>this.formatExtensionDisplayPath(C.path),formatPackagePath:C=>this.formatExtensionDisplayPath(this.getShortPath(C.path,C.sourceInfo))}),w=o(this.getCompactExtensionLabels(d));r("Extensions",w,v,"mdHeading")}let x=c.themes.filter(b=>b.sourcePath);if(x.length>0){let b=this.buildScopeGroups(x.map(C=>({path:C.sourcePath,sourceInfo:C.sourceInfo}))),v=this.formatScopeGroups(b,{formatPath:C=>this.formatDisplayPath(C.path),formatPackagePath:C=>this.getShortPath(C.path,C.sourceInfo)}),w=o(x.map(C=>C.name??this.getCompactPathLabel(C.sourcePath,C.sourceInfo)));r("Themes",w,v)}}if(n){let u=a.diagnostics;if(u.length>0){let w=this.formatDiagnostics(u,p);this.chatContainer.addChild(new T(`${f.fg("warning","[Skill conflicts]")}
|
|
353
|
+
${w}`,0,0)),this.chatContainer.addChild(new E(1))}let h=l.diagnostics;if(h.length>0){let w=this.formatDiagnostics(h,p);this.chatContainer.addChild(new T(`${f.fg("warning","[Prompt conflicts]")}
|
|
354
|
+
${w}`,0,0)),this.chatContainer.addChild(new E(1))}let m=[],g=this.session.resourceLoader.getExtensions().errors;if(g.length>0)for(let w of g)m.push({type:"error",message:w.error,path:w.path});let x=this.session.extensionRunner.getCommandDiagnostics();m.push(...x),m.push(...this.getBuiltInCommandConflictDiagnostics(this.session.extensionRunner));let b=this.session.extensionRunner.getShortcutDiagnostics();if(m.push(...b),m.length>0){let w=this.formatDiagnostics(m,p);this.chatContainer.addChild(new T(`${f.fg("warning","[Extension issues]")}
|
|
355
|
+
${w}`,0,0)),this.chatContainer.addChild(new E(1))}let v=c.diagnostics;if(v.length>0){let w=this.formatDiagnostics(v,p);this.chatContainer.addChild(new T(`${f.fg("warning","[Theme conflicts]")}
|
|
356
|
+
${w}`,0,0)),this.chatContainer.addChild(new E(1))}}}async bindCurrentSessionExtensions(){let e=this.createExtensionUIContext();await this.session.bindExtensions({uiContext:e,commandContextActions:{waitForIdle:()=>this.session.agent.waitForIdle(),newSession:async n=>{this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.statusContainer.clear();try{let s=await this.runtimeHost.newSession(n);return s.cancelled||(this.renderCurrentSessionState(),this.ui.requestRender()),s}catch(s){return this.handleFatalRuntimeError("Failed to create session",s)}},fork:async(n,s)=>{try{let o=await this.runtimeHost.fork(n,s);return o.cancelled||(this.renderCurrentSessionState(),this.editor.setText(o.selectedText??""),this.showStatus("Forked to new session")),{cancelled:o.cancelled}}catch(o){return this.handleFatalRuntimeError("Failed to fork session",o)}},navigateTree:async(n,s)=>{let o=await this.session.navigateTree(n,{summarize:s?.summarize,customInstructions:s?.customInstructions,replaceInstructions:s?.replaceInstructions,label:s?.label});return o.cancelled?{cancelled:!0}:(this.chatContainer.clear(),this.renderInitialMessages(),o.editorText&&!this.editor.getText().trim()&&this.editor.setText(o.editorText),this.showStatus("Navigated to selected point"),this.flushCompactionQueue({willRetry:!1}),{cancelled:!1})},switchSession:async(n,s)=>this.handleResumeSession(n,s),reload:async()=>{await this.handleReloadCommand()}},shutdownHandler:()=>{this.shutdownRequested=!0,this.session.isStreaming||this.shutdown()},onError:n=>{this.showExtensionError(n.extensionPath,n.error,n.stack)}}),No(this.session.resourceLoader.getThemes().themes),this.setupAutocompleteProvider();let t=this.session.extensionRunner;this.setupExtensionShortcuts(t),this.showLoadedResources({force:!1,showDiagnosticsWhenQuiet:!0}),this.showStartupNoticesIfNeeded()}applyRuntimeSettings(){this.footer.setSession(this.session),this.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled),this.footerDataProvider.setCwd(this.sessionManager.getCwd()),this.hideThinkingBlock=this.settingsManager.getHideThinkingBlock(),this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor()),this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());let e=this.settingsManager.getEditorPaddingX(),t=this.settingsManager.getAutocompleteMaxVisible();this.defaultEditor.setPaddingX(e),this.defaultEditor.setAutocompleteMaxVisible(t),this.editor!==this.defaultEditor&&(this.editor.setPaddingX?.(e),this.editor.setAutocompleteMaxVisible?.(t))}async rebindCurrentSession(){this.unsubscribe?.(),this.unsubscribe=void 0,this.applyRuntimeSettings(),await this.bindCurrentSessionExtensions(),this.subscribeToAgent(),await this.updateAvailableProviderCount(),this.updateEditorBorderColor(),this.updateTerminalTitle()}async handleFatalRuntimeError(e,t){let n=t instanceof Error?t.message:String(t);this.showError(`${e}: ${n}`),ii(),this.stop(),process.exit(1)}renderCurrentSessionState(){this.chatContainer.clear(),this.pendingMessagesContainer.clear(),this.compactionQueuedMessages=[],this.streamingComponent=void 0,this.streamingMessage=void 0,this.pendingTools.clear(),this.renderInitialMessages()}getRegisteredToolDefinition(e){return this.session.getToolDefinition(e)}setupExtensionShortcuts(e){let t=e.getShortcuts(this.keybindings.getEffectiveConfig());if(t.size===0)return;let n=()=>({ui:this.createExtensionUIContext(),hasUI:!0,cwd:this.sessionManager.getCwd(),sessionManager:this.sessionManager,modelRegistry:this.session.modelRegistry,model:this.session.model,isIdle:()=>!this.session.isStreaming,signal:this.session.agent.signal,abort:()=>this.session.abort(),hasPendingMessages:()=>this.session.pendingMessageCount>0,shutdown:()=>{this.shutdownRequested=!0},getContextUsage:()=>this.session.getContextUsage(),compact:s=>{(async()=>{try{let o=await this.session.compact(s?.customInstructions);s?.onComplete?.(o)}catch(o){let r=o instanceof Error?o:new Error(String(o));s?.onError?.(r)}})()},getSystemPrompt:()=>this.session.systemPrompt});this.defaultEditor.onExtensionShortcut=s=>{for(let[o,r]of t)if(ge(s,o))return Promise.resolve(r.handler(n())).catch(a=>{this.showError(`Shortcut handler error: ${a instanceof Error?a.message:String(a)}`)}),!0;return!1}}setExtensionStatus(e,t){this.footerDataProvider.setExtensionStatus(e,t),this.ui.requestRender()}getWorkingLoaderMessage(){return this.workingMessage??this.defaultWorkingMessage}createWorkingLoader(){return new Fe(this.ui,e=>f.fg("accent",e),e=>f.fg("muted",e),this.getWorkingLoaderMessage(),this.workingIndicatorOptions)}stopWorkingLoader(){this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.statusContainer.clear()}setWorkingVisible(e){if(this.workingVisible=e,!e){this.stopWorkingLoader(),this.ui.requestRender();return}this.session.isStreaming&&!this.loadingAnimation&&(this.statusContainer.clear(),this.loadingAnimation=this.createWorkingLoader(),this.statusContainer.addChild(this.loadingAnimation)),this.ui.requestRender()}setWorkingIndicator(e){this.workingIndicatorOptions=e,this.loadingAnimation?.setIndicator(e),this.ui.requestRender()}setHiddenThinkingLabel(e){this.hiddenThinkingLabel=e??this.defaultHiddenThinkingLabel;for(let t of this.chatContainer.children)t instanceof Bt&&t.setHiddenThinkingLabel(this.hiddenThinkingLabel);this.streamingComponent&&this.streamingComponent.setHiddenThinkingLabel(this.hiddenThinkingLabel),this.ui.requestRender()}setExtensionWidget(e,t,n){let s=n?.placement??"aboveEditor",o=l=>{let c=l.get(e);c?.dispose&&c.dispose(),l.delete(e)};if(o(this.extensionWidgetsAbove),o(this.extensionWidgetsBelow),t===void 0){this.renderWidgets();return}let r;if(Array.isArray(t)){let l=new L;for(let c of t.slice(0,i.MAX_WIDGET_LINES))l.addChild(new T(c,1,0));t.length>i.MAX_WIDGET_LINES&&l.addChild(new T(f.fg("muted","... (widget truncated)"),1,0)),r=l}else r=t(this.ui,f);(s==="belowEditor"?this.extensionWidgetsBelow:this.extensionWidgetsAbove).set(e,r),this.renderWidgets()}clearExtensionWidgets(){for(let e of this.extensionWidgetsAbove.values())e.dispose?.();for(let e of this.extensionWidgetsBelow.values())e.dispose?.();this.extensionWidgetsAbove.clear(),this.extensionWidgetsBelow.clear(),this.renderWidgets()}resetExtensionUI(){this.extensionSelector&&this.hideExtensionSelector(),this.extensionInput&&this.hideExtensionInput(),this.extensionEditor&&this.hideExtensionEditor(),this.ui.hideOverlay(),this.clearExtensionTerminalInputListeners(),this.setExtensionFooter(void 0),this.setExtensionHeader(void 0),this.clearExtensionWidgets(),this.footerDataProvider.clearExtensionStatuses(),this.footer.invalidate(),this.autocompleteProviderWrappers=[],this.setCustomEditorComponent(void 0),this.setupAutocompleteProvider(),this.defaultEditor.onExtensionShortcut=void 0,this.updateTerminalTitle(),this.workingMessage=void 0,this.workingVisible=!0,this.setWorkingIndicator(),this.loadingAnimation&&this.loadingAnimation.setMessage(`${this.defaultWorkingMessage} (${z("app.interrupt")} to interrupt)`),this.setHiddenThinkingLabel()}static{this.MAX_WIDGET_LINES=10}renderWidgets(){!this.widgetContainerAbove||!this.widgetContainerBelow||(this.renderWidgetContainer(this.widgetContainerAbove,this.extensionWidgetsAbove,!0,!0),this.renderWidgetContainer(this.widgetContainerBelow,this.extensionWidgetsBelow,!1,!1),this.ui.requestRender())}renderWidgetContainer(e,t,n,s){if(e.clear(),t.size===0){n&&e.addChild(new E(1));return}s&&e.addChild(new E(1));for(let o of t.values())e.addChild(o)}setExtensionFooter(e){this.customFooter?.dispose&&this.customFooter.dispose(),this.customFooter?this.ui.removeChild(this.customFooter):this.ui.removeChild(this.footer),e?(this.customFooter=e(this.ui,f,this.footerDataProvider),this.ui.addChild(this.customFooter)):(this.customFooter=void 0,this.ui.addChild(this.footer)),this.ui.requestRender()}setExtensionHeader(e){if(!this.builtInHeader)return;this.customHeader?.dispose&&this.customHeader.dispose();let t=this.customHeader||this.builtInHeader,n=this.headerContainer.children.indexOf(t);e?(this.customHeader=e(this.ui,f),js(this.customHeader)&&this.customHeader.setExpanded(this.toolOutputExpanded),n!==-1?this.headerContainer.children[n]=this.customHeader:this.headerContainer.children.unshift(this.customHeader)):(this.customHeader=void 0,js(this.builtInHeader)&&this.builtInHeader.setExpanded(this.toolOutputExpanded),n!==-1&&(this.headerContainer.children[n]=this.builtInHeader)),this.ui.requestRender()}addExtensionTerminalInputListener(e){let t=this.ui.addInputListener(e);return this.extensionTerminalInputUnsubscribers.add(t),()=>{t(),this.extensionTerminalInputUnsubscribers.delete(t)}}clearExtensionTerminalInputListeners(){for(let e of this.extensionTerminalInputUnsubscribers)e();this.extensionTerminalInputUnsubscribers.clear()}createExtensionUIContext(){return{select:(e,t,n)=>this.showExtensionSelector(e,t,n),confirm:(e,t,n)=>this.showExtensionConfirm(e,t,n),input:(e,t,n)=>this.showExtensionInput(e,t,n),notify:(e,t)=>this.showExtensionNotify(e,t),onTerminalInput:e=>this.addExtensionTerminalInputListener(e),setStatus:(e,t)=>this.setExtensionStatus(e,t),setWorkingMessage:e=>{this.workingMessage=e,this.loadingAnimation&&this.loadingAnimation.setMessage(e??this.defaultWorkingMessage)},setWorkingVisible:e=>this.setWorkingVisible(e),setWorkingIndicator:e=>this.setWorkingIndicator(e),setHiddenThinkingLabel:e=>this.setHiddenThinkingLabel(e),setWidget:(e,t,n)=>this.setExtensionWidget(e,t,n),setFooter:e=>this.setExtensionFooter(e),setHeader:e=>this.setExtensionHeader(e),setTitle:e=>this.ui.terminal.setTitle(e),custom:(e,t)=>this.showExtensionCustom(e,t),pasteToEditor:e=>this.editor.handleInput(`\x1B[200~${e}\x1B[201~`),setEditorText:e=>this.editor.setText(e),getEditorText:()=>this.editor.getExpandedText?.()??this.editor.getText(),editor:(e,t)=>this.showExtensionEditor(e,t),addAutocompleteProvider:e=>{this.autocompleteProviderWrappers.push(e),this.setupAutocompleteProvider()},setEditorComponent:e=>this.setCustomEditorComponent(e),getEditorComponent:()=>this.editorComponentFactory,get theme(){return f},getAllThemes:()=>Ku(),getTheme:e=>ju(e),setTheme:e=>{if(e instanceof ti)return Vu(e),this.ui.requestRender(),{success:!0};let t=ys(e,!0);return t.success&&(this.settingsManager.getTheme()!==e&&this.settingsManager.setTheme(e),this.ui.requestRender()),t},getToolsExpanded:()=>this.toolOutputExpanded,setToolsExpanded:e=>this.setToolsExpanded(e)}}showExtensionSelector(e,t,n){return new Promise(s=>{if(n?.signal?.aborted){s(void 0);return}let o=()=>{this.hideExtensionSelector(),s(void 0)};n?.signal?.addEventListener("abort",o,{once:!0}),this.extensionSelector=new Nt(e,t,r=>{n?.signal?.removeEventListener("abort",o),this.hideExtensionSelector(),s(r)},()=>{n?.signal?.removeEventListener("abort",o),this.hideExtensionSelector(),s(void 0)},{tui:this.ui,timeout:n?.timeout}),this.editorContainer.clear(),this.editorContainer.addChild(this.extensionSelector),this.ui.setFocus(this.extensionSelector),this.ui.requestRender()})}hideExtensionSelector(){this.extensionSelector?.dispose(),this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.extensionSelector=void 0,this.ui.setFocus(this.editor),this.ui.requestRender()}async showExtensionConfirm(e,t,n){return await this.showExtensionSelector(`${e}
|
|
357
|
+
${t}`,["Yes","No"],n)==="Yes"}async promptForMissingSessionCwd(e){return await this.showExtensionConfirm("Session cwd not found",bc(e.issue))?e.issue.fallbackCwd:void 0}showExtensionInput(e,t,n){return new Promise(s=>{if(n?.signal?.aborted){s(void 0);return}let o=()=>{this.hideExtensionInput(),s(void 0)};n?.signal?.addEventListener("abort",o,{once:!0}),this.extensionInput=new Wi(e,t,r=>{n?.signal?.removeEventListener("abort",o),this.hideExtensionInput(),s(r)},()=>{n?.signal?.removeEventListener("abort",o),this.hideExtensionInput(),s(void 0)},{tui:this.ui,timeout:n?.timeout}),this.editorContainer.clear(),this.editorContainer.addChild(this.extensionInput),this.ui.setFocus(this.extensionInput),this.ui.requestRender()})}hideExtensionInput(){this.extensionInput?.dispose(),this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.extensionInput=void 0,this.ui.setFocus(this.editor),this.ui.requestRender()}showExtensionEditor(e,t){return new Promise(n=>{this.extensionEditor=new _i(this.ui,this.keybindings,e,t,s=>{this.hideExtensionEditor(),n(s)},()=>{this.hideExtensionEditor(),n(void 0)}),this.editorContainer.clear(),this.editorContainer.addChild(this.extensionEditor),this.ui.setFocus(this.extensionEditor),this.ui.requestRender()})}hideExtensionEditor(){this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.extensionEditor=void 0,this.ui.setFocus(this.editor),this.ui.requestRender()}setCustomEditorComponent(e){this.editorComponentFactory=e;let t=this.editor.getText();if(this.editorContainer.clear(),e){let n=e(this.ui,ws(),this.keybindings);n.onSubmit=this.defaultEditor.onSubmit,n.onChange=this.defaultEditor.onChange,n.setText(t),n.borderColor!==void 0&&(n.borderColor=this.defaultEditor.borderColor),n.setPaddingX!==void 0&&n.setPaddingX(this.defaultEditor.getPaddingX()),n.setAutocompleteProvider&&this.autocompleteProvider&&n.setAutocompleteProvider(this.autocompleteProvider);let s=n;if("actionHandlers"in s&&s.actionHandlers instanceof Map){s.onEscape||(s.onEscape=()=>this.defaultEditor.onEscape?.()),s.onCtrlD||(s.onCtrlD=()=>this.defaultEditor.onCtrlD?.()),s.onPasteImage||(s.onPasteImage=()=>this.defaultEditor.onPasteImage?.()),s.onExtensionShortcut||(s.onExtensionShortcut=o=>this.defaultEditor.onExtensionShortcut?.(o));for(let[o,r]of this.defaultEditor.actionHandlers)s.actionHandlers.set(o,r)}this.editor=n}else this.defaultEditor.setText(t),this.editor=this.defaultEditor;this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor),this.ui.requestRender()}showExtensionNotify(e,t){t==="error"?this.showError(e):t==="warning"?this.showWarning(e):this.showStatus(e)}async showExtensionCustom(e,t){let n=this.editor.getText(),s=t?.overlay??!1,o=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.editor.setText(n),this.ui.setFocus(this.editor),this.ui.requestRender()};return new Promise((r,a)=>{let l,c=!1,d=p=>{if(!c){c=!0,s?this.ui.hideOverlay():o(),r(p);try{l?.dispose?.()}catch{}}};Promise.resolve(e(this.ui,f,this.keybindings,d)).then(p=>{if(!c)if(l=p,s){let u=()=>{if(t?.overlayOptions)return typeof t.overlayOptions=="function"?t.overlayOptions():t.overlayOptions;let m=l.width;return m?{width:m}:void 0},h=this.ui.showOverlay(l,u());t?.onHandle?.(h)}else this.editorContainer.clear(),this.editorContainer.addChild(l),this.ui.setFocus(l),this.ui.requestRender()}).catch(p=>{c||(s||o(),a(p))})})}showExtensionError(e,t,n){let s=`Extension "${e}" error: ${t}`,o=new T(f.fg("error",s),1,0);if(this.chatContainer.addChild(o),n){let r=n.split(`
|
|
358
|
+
`).slice(1).map(a=>f.fg("dim",` ${a.trim()}`)).join(`
|
|
359
|
+
`);r&&this.chatContainer.addChild(new T(r,1,0))}this.ui.requestRender()}setupKeyHandlers(){this.defaultEditor.onEscape=()=>{if(this.session.isStreaming)this.restoreQueuedMessagesToEditor({abort:!0});else if(this.session.isBashRunning)this.session.abortBash();else if(this.isBashMode)this.editor.setText(""),this.isBashMode=!1,this.updateEditorBorderColor();else if(!this.editor.getText().trim()){let e=this.settingsManager.getDoubleEscapeAction();if(e!=="none"){let t=Date.now();t-this.lastEscapeTime<500?(e==="tree"?this.showTreeSelector():this.showUserMessageSelector(),this.lastEscapeTime=0):this.lastEscapeTime=t}}},this.defaultEditor.onAction("app.clear",()=>this.handleCtrlC()),this.defaultEditor.onCtrlD=()=>this.handleCtrlD(),this.defaultEditor.onAction("app.suspend",()=>this.handleCtrlZ()),this.defaultEditor.onAction("app.thinking.cycle",()=>this.cycleThinkingLevel()),this.defaultEditor.onAction("app.model.cycleForward",()=>this.cycleModel("forward")),this.defaultEditor.onAction("app.model.cycleBackward",()=>this.cycleModel("backward")),this.ui.onDebug=()=>this.handleDebugCommand(),this.defaultEditor.onAction("app.model.select",()=>this.showModelSelector()),this.defaultEditor.onAction("app.tools.expand",()=>this.toggleToolOutputExpansion()),this.defaultEditor.onAction("app.thinking.toggle",()=>this.toggleThinkingBlockVisibility()),this.defaultEditor.onAction("app.editor.external",()=>this.openExternalEditor()),this.defaultEditor.onAction("app.message.followUp",()=>this.handleFollowUp()),this.defaultEditor.onAction("app.message.dequeue",()=>this.handleDequeue()),this.defaultEditor.onAction("app.session.new",()=>this.handleClearCommand()),this.defaultEditor.onAction("app.session.tree",()=>this.showTreeSelector()),this.defaultEditor.onAction("app.session.fork",()=>this.showUserMessageSelector()),this.defaultEditor.onAction("app.session.resume",()=>this.showSessionSelector()),this.defaultEditor.onChange=e=>{let t=this.isBashMode;this.isBashMode=e.trimStart().startsWith("!"),t!==this.isBashMode&&this.updateEditorBorderColor()},this.defaultEditor.onPasteImage=()=>{this.handleClipboardImagePaste()}}async handleClipboardImagePaste(){try{let e=await Jh();if(!e)return;let t=Gi.tmpdir(),n=Vh(e.mimeType)??"png",s=`pi-clipboard-${vg.randomUUID()}.${n}`,o=se.join(t,s);ft.writeFileSync(o,Buffer.from(e.bytes)),this.editor.insertTextAtCursor?.(o),this.ui.requestRender()}catch{}}setupEditorSubmitHandler(){this.defaultEditor.onSubmit=async e=>{if(e=e.trim(),!!e){if(e==="/settings"){this.showSettingsSelector(),this.editor.setText("");return}if(e==="/scoped-models"){this.editor.setText(""),await this.showModelsSelector();return}if(e==="/model"||e.startsWith("/model ")){let t=e.startsWith("/model ")?e.slice(7).trim():void 0;this.editor.setText(""),await this.handleModelCommand(t);return}if(e==="/export"||e.startsWith("/export ")){await this.handleExportCommand(e),this.editor.setText("");return}if(e==="/import"||e.startsWith("/import ")){await this.handleImportCommand(e),this.editor.setText("");return}if(e==="/share"){await this.handleShareCommand(),this.editor.setText("");return}if(e==="/copy"){await this.handleCopyCommand(),this.editor.setText("");return}if(e==="/name"||e.startsWith("/name ")){this.handleNameCommand(e),this.editor.setText("");return}if(e==="/session"){this.handleSessionCommand(),this.editor.setText("");return}if(e==="/changelog"){this.handleChangelogCommand(),this.editor.setText("");return}if(e==="/hotkeys"){this.handleHotkeysCommand(),this.editor.setText("");return}if(e==="/fork"){this.showUserMessageSelector(),this.editor.setText("");return}if(e==="/clone"){this.editor.setText(""),await this.handleCloneCommand();return}if(e==="/tree"){this.showTreeSelector(),this.editor.setText("");return}if(e==="/login"){this.showOAuthSelector("login"),this.editor.setText("");return}if(e==="/logout"){this.showOAuthSelector("logout"),this.editor.setText("");return}if(e==="/new"){this.editor.setText(""),await this.handleClearCommand();return}if(e==="/compact"||e.startsWith("/compact ")){let t=e.startsWith("/compact ")?e.slice(9).trim():void 0;this.editor.setText(""),await this.handleCompactCommand(t);return}if(e==="/reload"){this.editor.setText(""),await this.handleReloadCommand();return}if(e==="/debug"){this.handleDebugCommand(),this.editor.setText("");return}if(e==="/arminsayshi"){this.handleArminSaysHi(),this.editor.setText("");return}if(e==="/dementedelves"){this.handleDementedDelves(),this.editor.setText("");return}if(e==="/resume"){this.showSessionSelector(),this.editor.setText("");return}if(e==="/quit"){this.editor.setText(""),await this.shutdown();return}if(e.startsWith("!")){let t=e.startsWith("!!"),n=t?e.slice(2).trim():e.slice(1).trim();if(n){if(this.session.isBashRunning){this.showWarning("A bash command is already running. Press Esc to cancel it first."),this.editor.setText(e);return}this.editor.addToHistory?.(e),await this.handleBashCommand(n,t),this.isBashMode=!1,this.updateEditorBorderColor();return}}if(this.session.isCompacting){this.isExtensionCommand(e)?(this.editor.addToHistory?.(e),this.editor.setText(""),await this.session.prompt(e)):this.queueCompactionMessage(e,"steer");return}if(this.session.isStreaming){this.editor.addToHistory?.(e),this.editor.setText(""),await this.session.prompt(e,{streamingBehavior:"steer"}),this.updatePendingMessagesDisplay(),this.ui.requestRender();return}this.flushPendingBashComponents(),this.onInputCallback&&this.onInputCallback(e),this.editor.addToHistory?.(e)}}}subscribeToAgent(){this.unsubscribe=this.session.subscribe(async e=>{await this.handleEvent(e)})}async handleEvent(e){switch(this.isInitialized||await this.init(),this.footer.invalidate(),e.type){case"agent_start":this.pendingTools.clear(),this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!0),this.retryEscapeHandler&&(this.defaultEditor.onEscape=this.retryEscapeHandler,this.retryEscapeHandler=void 0),this.retryCountdown&&(this.retryCountdown.dispose(),this.retryCountdown=void 0),this.retryLoader&&(this.retryLoader.stop(),this.retryLoader=void 0),this.stopWorkingLoader(),this.workingVisible&&(this.loadingAnimation=this.createWorkingLoader(),this.statusContainer.addChild(this.loadingAnimation)),this.ui.requestRender();break;case"queue_update":this.updatePendingMessagesDisplay(),this.ui.requestRender();break;case"session_info_changed":this.updateTerminalTitle(),this.footer.invalidate(),this.ui.requestRender();break;case"thinking_level_changed":this.footer.invalidate(),this.updateEditorBorderColor();break;case"message_start":e.message.role==="custom"?(this.addMessageToChat(e.message),this.ui.requestRender()):e.message.role==="user"?(this.addMessageToChat(e.message),this.updatePendingMessagesDisplay(),this.ui.requestRender()):e.message.role==="assistant"&&(this.streamingComponent=new Bt(void 0,this.hideThinkingBlock,this.getMarkdownThemeWithSettings(),this.hiddenThinkingLabel),this.streamingMessage=e.message,this.chatContainer.addChild(this.streamingComponent),this.streamingComponent.updateContent(this.streamingMessage),this.ui.requestRender());break;case"message_update":if(this.streamingComponent&&e.message.role==="assistant"){this.streamingMessage=e.message,this.streamingComponent.updateContent(this.streamingMessage);for(let t of this.streamingMessage.content)if(t.type==="toolCall")if(this.pendingTools.has(t.id)){let n=this.pendingTools.get(t.id);n&&n.updateArgs(t.arguments)}else{let n=new Mt(t.name,t.id,t.arguments,{showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells()},this.getRegisteredToolDefinition(t.name),this.ui,this.sessionManager.getCwd());n.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(n),this.pendingTools.set(t.id,n)}this.ui.requestRender()}break;case"message_end":if(e.message.role==="user")break;if(this.streamingComponent&&e.message.role==="assistant"){this.streamingMessage=e.message;let t;if(this.streamingMessage.stopReason==="aborted"){let n=this.session.retryAttempt;t=n>0?`Aborted after ${n} retry attempt${n>1?"s":""}`:"Operation aborted",this.streamingMessage.errorMessage=t}if(this.streamingComponent.updateContent(this.streamingMessage),this.streamingMessage.stopReason==="aborted"||this.streamingMessage.stopReason==="error"){t||(t=this.streamingMessage.errorMessage||"Error");for(let[,n]of this.pendingTools.entries())n.updateResult({content:[{type:"text",text:t}],isError:!0});this.pendingTools.clear()}else for(let[,n]of this.pendingTools.entries())n.setArgsComplete();this.streamingComponent=void 0,this.streamingMessage=void 0,this.footer.invalidate()}this.ui.requestRender();break;case"tool_execution_start":{let t=this.pendingTools.get(e.toolCallId);t||(t=new Mt(e.toolName,e.toolCallId,e.args,{showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells()},this.getRegisteredToolDefinition(e.toolName),this.ui,this.sessionManager.getCwd()),t.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(t),this.pendingTools.set(e.toolCallId,t)),t.markExecutionStarted(),this.ui.requestRender();break}case"tool_execution_update":{let t=this.pendingTools.get(e.toolCallId);t&&(t.updateResult({...e.partialResult,isError:!1},!0),this.ui.requestRender());break}case"tool_execution_end":{let t=this.pendingTools.get(e.toolCallId);t&&(t.updateResult({...e.result,isError:e.isError}),this.pendingTools.delete(e.toolCallId),this.ui.requestRender());break}case"agent_end":this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!1),this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0,this.statusContainer.clear()),this.streamingComponent&&(this.chatContainer.removeChild(this.streamingComponent),this.streamingComponent=void 0,this.streamingMessage=void 0),this.pendingTools.clear(),await this.checkShutdownRequested(),this.ui.requestRender();break;case"compaction_start":{this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!0),this.autoCompactionEscapeHandler=this.defaultEditor.onEscape,this.defaultEditor.onEscape=()=>{this.session.abortCompaction()},this.statusContainer.clear();let t=`(${z("app.interrupt")} to cancel)`,n=e.reason==="manual"?`Compacting context... ${t}`:`${e.reason==="overflow"?"Context overflow detected, ":""}Auto-compacting... ${t}`;this.autoCompactionLoader=new Fe(this.ui,s=>f.fg("accent",s),s=>f.fg("muted",s),n),this.statusContainer.addChild(this.autoCompactionLoader),this.ui.requestRender();break}case"compaction_end":{this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!1),this.autoCompactionEscapeHandler&&(this.defaultEditor.onEscape=this.autoCompactionEscapeHandler,this.autoCompactionEscapeHandler=void 0),this.autoCompactionLoader&&(this.autoCompactionLoader.stop(),this.autoCompactionLoader=void 0,this.statusContainer.clear()),e.aborted?e.reason==="manual"?this.showError("Compaction cancelled"):this.showStatus("Auto-compaction cancelled"):e.result?(this.chatContainer.clear(),this.rebuildChatFromMessages(),this.addMessageToChat(si(e.result.summary,e.result.tokensBefore,new Date().toISOString())),this.footer.invalidate()):e.errorMessage&&(e.reason==="manual"?this.showError(e.errorMessage):(this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new T(f.fg("error",e.errorMessage),1,0)))),this.flushCompactionQueue({willRetry:e.willRetry}),this.ui.requestRender();break}case"auto_retry_start":{this.retryEscapeHandler=this.defaultEditor.onEscape,this.defaultEditor.onEscape=()=>{this.session.abortRetry()},this.statusContainer.clear(),this.retryCountdown?.dispose();let t=n=>`Retrying (${e.attempt}/${e.maxAttempts}) in ${n}s... (${z("app.interrupt")} to cancel)`;this.retryLoader=new Fe(this.ui,n=>f.fg("warning",n),n=>f.fg("muted",n),t(Math.ceil(e.delayMs/1e3))),this.retryCountdown=new nn(e.delayMs,this.ui,n=>{this.retryLoader?.setMessage(t(n))},()=>{this.retryCountdown=void 0}),this.statusContainer.addChild(this.retryLoader),this.ui.requestRender();break}case"auto_retry_end":{this.retryEscapeHandler&&(this.defaultEditor.onEscape=this.retryEscapeHandler,this.retryEscapeHandler=void 0),this.retryCountdown&&(this.retryCountdown.dispose(),this.retryCountdown=void 0),this.retryLoader&&(this.retryLoader.stop(),this.retryLoader=void 0,this.statusContainer.clear()),e.success||this.showError(`Retry failed after ${e.attempt} attempts: ${e.finalError||"Unknown error"}`),this.ui.requestRender();break}}}getUserMessageText(e){return e.role!=="user"?"":(typeof e.content=="string"?[{type:"text",text:e.content}]:e.content.filter(n=>n.type==="text")).map(n=>n.text).join("")}showStatus(e){let t=this.chatContainer.children,n=t.length>0?t[t.length-1]:void 0,s=t.length>1?t[t.length-2]:void 0;if(n&&s&&n===this.lastStatusText&&s===this.lastStatusSpacer){this.lastStatusText.setText(f.fg("dim",e)),this.ui.requestRender();return}let o=new E(1),r=new T(f.fg("dim",e),1,0);this.chatContainer.addChild(o),this.chatContainer.addChild(r),this.lastStatusSpacer=o,this.lastStatusText=r,this.ui.requestRender()}addMessageToChat(e,t){switch(e.role){case"bashExecution":{let n=new tn(e.command,this.ui,e.excludeFromContext);e.output&&n.appendOutput(e.output),n.setComplete(e.exitCode,e.cancelled,e.truncated?{truncated:!0}:void 0,e.fullOutputPath),this.chatContainer.addChild(n);break}case"custom":{if(e.display){let n=this.session.extensionRunner.getMessageRenderer(e.customType),s=new Pi(e,n,this.getMarkdownThemeWithSettings());s.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(s)}break}case"compactionSummary":{this.chatContainer.addChild(new E(1));let n=new Ii(e,this.getMarkdownThemeWithSettings());n.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(n);break}case"branchSummary":{this.chatContainer.addChild(new E(1));let n=new Ei(e,this.getMarkdownThemeWithSettings());n.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(n);break}case"user":{let n=this.getUserMessageText(e);if(n){this.chatContainer.children.length>0&&this.chatContainer.addChild(new E(1));let s=nc(n);if(s){let o=new $i(s,this.getMarkdownThemeWithSettings());if(o.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(o),s.userMessage){let r=new Un(s.userMessage,this.getMarkdownThemeWithSettings());this.chatContainer.addChild(r)}}else{let o=new Un(n,this.getMarkdownThemeWithSettings());this.chatContainer.addChild(o)}t?.populateHistory&&this.editor.addToHistory?.(n)}break}case"assistant":{let n=new Bt(e,this.hideThinkingBlock,this.getMarkdownThemeWithSettings(),this.hiddenThinkingLabel);this.chatContainer.addChild(n);break}case"toolResult":break;default:{let n=e}}}renderSessionContext(e,t={}){this.pendingTools.clear();let n=new Map;t.updateFooter&&(this.footer.invalidate(),this.updateEditorBorderColor());for(let s of e.messages)if(s.role==="assistant"){this.addMessageToChat(s);for(let o of s.content)if(o.type==="toolCall"){let r=new Mt(o.name,o.id,o.arguments,{showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells()},this.getRegisteredToolDefinition(o.name),this.ui,this.sessionManager.getCwd());if(r.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(r),s.stopReason==="aborted"||s.stopReason==="error"){let a;if(s.stopReason==="aborted"){let l=this.session.retryAttempt;a=l>0?`Aborted after ${l} retry attempt${l>1?"s":""}`:"Operation aborted"}else a=s.errorMessage||"Error";r.updateResult({content:[{type:"text",text:a}],isError:!0})}else n.set(o.id,r)}}else if(s.role==="toolResult"){let o=n.get(s.toolCallId);o&&(o.updateResult(s),n.delete(s.toolCallId))}else this.addMessageToChat(s,t);for(let[s,o]of n)this.pendingTools.set(s,o);this.ui.requestRender()}renderInitialMessages(){let e=this.sessionManager.buildSessionContext();this.renderSessionContext(e,{updateFooter:!0,populateHistory:!0});let n=this.sessionManager.getEntries().filter(s=>s.type==="compaction").length;if(n>0){let s=n===1?"1 time":`${n} times`;this.showStatus(`Session compacted ${s}`)}}async getUserInput(){return new Promise(e=>{this.onInputCallback=t=>{this.onInputCallback=void 0,e(t)}})}rebuildChatFromMessages(){this.chatContainer.clear();let e=this.sessionManager.buildSessionContext();this.renderSessionContext(e)}handleCtrlC(){let e=Date.now();e-this.lastSigintTime<500?this.shutdown():(this.clearEditor(),this.lastSigintTime=e)}handleCtrlD(){this.shutdown()}async shutdown(){this.isShuttingDown||(this.isShuttingDown=!0,this.unregisterSignalHandlers(),await this.ui.terminal.drainInput(1e3),this.stop(),await this.runtimeHost.dispose(),process.exit(0))}emergencyTerminalExit(){this.isShuttingDown=!0,this.unregisterSignalHandlers(),ks(),process.exit(129)}async checkShutdownRequested(){this.shutdownRequested&&await this.shutdown()}registerSignalHandlers(){this.unregisterSignalHandlers();let e=["SIGTERM"];process.platform!=="win32"&&e.push("SIGHUP");for(let n of e){let s=()=>{n==="SIGHUP"&&this.emergencyTerminalExit(),ks(),this.shutdown()};process.prependListener(n,s),this.signalCleanupHandlers.push(()=>process.off(n,s))}let t=n=>{throw gM(n)&&this.emergencyTerminalExit(),n};process.stdout.on("error",t),process.stderr.on("error",t),this.signalCleanupHandlers.push(()=>process.stdout.off("error",t)),this.signalCleanupHandlers.push(()=>process.stderr.off("error",t))}unregisterSignalHandlers(){for(let e of this.signalCleanupHandlers)e();this.signalCleanupHandlers=[]}handleCtrlZ(){if(process.platform==="win32"){this.showStatus("Suspend to background is not supported on Windows");return}let e=setInterval(()=>{},2**30),t=()=>{};process.on("SIGINT",t),process.once("SIGCONT",()=>{clearInterval(e),process.removeListener("SIGINT",t),this.ui.start(),this.ui.requestRender(!0)});try{this.ui.stop(),process.kill(0,"SIGTSTP")}catch(n){throw clearInterval(e),process.removeListener("SIGINT",t),n}}async handleFollowUp(){let e=(this.editor.getExpandedText?.()??this.editor.getText()).trim();if(e){if(this.session.isCompacting){this.isExtensionCommand(e)?(this.editor.addToHistory?.(e),this.editor.setText(""),await this.session.prompt(e)):this.queueCompactionMessage(e,"followUp");return}this.session.isStreaming?(this.editor.addToHistory?.(e),this.editor.setText(""),await this.session.prompt(e,{streamingBehavior:"followUp"}),this.updatePendingMessagesDisplay(),this.ui.requestRender()):this.editor.onSubmit&&(this.editor.setText(""),this.editor.onSubmit(e))}}handleDequeue(){let e=this.restoreQueuedMessagesToEditor();e===0?this.showStatus("No queued messages to restore"):this.showStatus(`Restored ${e} queued message${e>1?"s":""} to editor`)}updateEditorBorderColor(){if(this.isBashMode)this.editor.borderColor=f.getBashModeBorderColor();else{let e=this.session.thinkingLevel||"off";this.editor.borderColor=f.getThinkingBorderColor(e)}this.ui.requestRender()}cycleThinkingLevel(){let e=this.session.cycleThinkingLevel();e===void 0?this.showStatus("Current model does not support thinking"):(this.footer.invalidate(),this.updateEditorBorderColor(),this.showStatus(`Thinking level: ${e}`))}async cycleModel(e){try{let t=await this.session.cycleModel(e);if(t===void 0){let n=this.session.scopedModels.length>0?"Only one model in scope":"Only one model available";this.showStatus(n)}else{this.footer.invalidate(),this.updateEditorBorderColor();let n=t.model.reasoning&&t.thinkingLevel!=="off"?` (thinking: ${t.thinkingLevel})`:"";this.showStatus(`Switched to ${t.model.name||t.model.id}${n}`),this.maybeWarnAboutAnthropicSubscriptionAuth(t.model)}}catch(t){this.showError(t instanceof Error?t.message:String(t))}}toggleToolOutputExpansion(){this.setToolsExpanded(!this.toolOutputExpanded)}setToolsExpanded(e){this.toolOutputExpanded=e;let t=this.customHeader??this.builtInHeader;js(t)&&t.setExpanded(e);for(let n of this.chatContainer.children)js(n)&&n.setExpanded(e);this.ui.requestRender()}toggleThinkingBlockVisibility(){this.hideThinkingBlock=!this.hideThinkingBlock,this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock),this.chatContainer.clear(),this.rebuildChatFromMessages(),this.streamingComponent&&this.streamingMessage&&(this.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock),this.streamingComponent.updateContent(this.streamingMessage),this.chatContainer.addChild(this.streamingComponent)),this.showStatus(`Thinking blocks: ${this.hideThinkingBlock?"hidden":"visible"}`)}openExternalEditor(){let e=process.env.VISUAL||process.env.EDITOR;if(!e){this.showWarning("No editor configured. Set $VISUAL or $EDITOR environment variable.");return}let t=this.editor.getExpandedText?.()??this.editor.getText(),n=se.join(Gi.tmpdir(),`pi-editor-${Date.now()}.pi.md`);try{ft.writeFileSync(n,t,"utf-8"),this.ui.stop();let[s,...o]=e.split(" ");if(xg(s,[...o,n],{stdio:"inherit",shell:process.platform==="win32"}).status===0){let a=ft.readFileSync(n,"utf-8").replace(/\n$/,"");this.editor.setText(a)}}finally{try{ft.unlinkSync(n)}catch{}this.ui.start(),this.ui.requestRender(!0)}}clearEditor(){this.editor.setText(""),this.ui.requestRender()}showError(e){this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new T(f.fg("error",`Error: ${e}`),1,0)),this.ui.requestRender()}showWarning(e){this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new T(f.fg("warning",`Warning: ${e}`),1,0)),this.ui.requestRender()}showNewVersionNotification(e){let t=f.fg("accent",`${Ae} update`),n=f.fg("muted",`New version ${e} is available. Run `)+t,s="https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/CHANGELOG.md",o=ve().hyperlinks?Xi(f.fg("accent","open changelog"),s):f.fg("accent",s),r=f.fg("muted","Changelog: ")+o;this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new O(a=>f.fg("warning",a))),this.chatContainer.addChild(new T(`${f.bold(f.fg("warning","Update Available"))}
|
|
360
|
+
${n}
|
|
361
|
+
${r}`,1,0)),this.chatContainer.addChild(new O(a=>f.fg("warning",a))),this.ui.requestRender()}showPackageUpdateNotification(e){let t=f.fg("accent",`${Ae} update`),n=f.fg("muted","Package updates are available. Run ")+t,s=e.map(o=>`- ${o}`).join(`
|
|
362
|
+
`);this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new O(o=>f.fg("warning",o))),this.chatContainer.addChild(new T(`${f.bold(f.fg("warning","Package Updates Available"))}
|
|
363
|
+
${n}
|
|
364
|
+
${f.fg("muted","Packages:")}
|
|
365
|
+
${s}`,1,0)),this.chatContainer.addChild(new O(o=>f.fg("warning",o))),this.ui.requestRender()}getAllQueuedMessages(){return{steering:[...this.session.getSteeringMessages(),...this.compactionQueuedMessages.filter(e=>e.mode==="steer").map(e=>e.text)],followUp:[...this.session.getFollowUpMessages(),...this.compactionQueuedMessages.filter(e=>e.mode==="followUp").map(e=>e.text)]}}clearAllQueues(){let{steering:e,followUp:t}=this.session.clearQueue(),n=this.compactionQueuedMessages.filter(o=>o.mode==="steer").map(o=>o.text),s=this.compactionQueuedMessages.filter(o=>o.mode==="followUp").map(o=>o.text);return this.compactionQueuedMessages=[],{steering:[...e,...n],followUp:[...t,...s]}}updatePendingMessagesDisplay(){this.pendingMessagesContainer.clear();let{steering:e,followUp:t}=this.getAllQueuedMessages();if(e.length>0||t.length>0){this.pendingMessagesContainer.addChild(new E(1));for(let o of e){let r=f.fg("dim",`Steering: ${o}`);this.pendingMessagesContainer.addChild(new $e(r,1,0))}for(let o of t){let r=f.fg("dim",`Follow-up: ${o}`);this.pendingMessagesContainer.addChild(new $e(r,1,0))}let n=this.getAppKeyDisplay("app.message.dequeue"),s=f.fg("dim",`\u21B3 ${n} to edit all queued messages`);this.pendingMessagesContainer.addChild(new $e(s,1,0))}}restoreQueuedMessagesToEditor(e){let{steering:t,followUp:n}=this.clearAllQueues(),s=[...t,...n];if(s.length===0)return this.updatePendingMessagesDisplay(),e?.abort&&this.agent.abort(),0;let o=s.join(`
|
|
366
|
+
|
|
367
|
+
`),r=e?.currentText??this.editor.getText(),a=[o,r].filter(l=>l.trim()).join(`
|
|
368
|
+
|
|
369
|
+
`);return this.editor.setText(a),this.updatePendingMessagesDisplay(),e?.abort&&this.agent.abort(),s.length}queueCompactionMessage(e,t){this.compactionQueuedMessages.push({text:e,mode:t}),this.editor.addToHistory?.(e),this.editor.setText(""),this.updatePendingMessagesDisplay(),this.showStatus("Queued message for after compaction")}isExtensionCommand(e){if(!e.startsWith("/"))return!1;let t=this.session.extensionRunner,n=e.indexOf(" "),s=n===-1?e.slice(1):e.slice(1,n);return!!t.getCommand(s)}async flushCompactionQueue(e){if(this.compactionQueuedMessages.length===0)return;let t=[...this.compactionQueuedMessages];this.compactionQueuedMessages=[],this.updatePendingMessagesDisplay();let n=s=>{this.session.clearQueue(),this.compactionQueuedMessages=t,this.updatePendingMessagesDisplay(),this.showError(`Failed to send queued message${t.length>1?"s":""}: ${s instanceof Error?s.message:String(s)}`)};try{if(e?.willRetry){for(let c of t)this.isExtensionCommand(c.text)?await this.session.prompt(c.text):c.mode==="followUp"?await this.session.followUp(c.text):await this.session.steer(c.text);this.updatePendingMessagesDisplay();return}let s=t.findIndex(c=>!this.isExtensionCommand(c.text));if(s===-1){for(let c of t)await this.session.prompt(c.text);return}let o=t.slice(0,s),r=t[s],a=t.slice(s+1);for(let c of o)await this.session.prompt(c.text);let l=this.session.prompt(r.text).catch(c=>{n(c)});for(let c of a)this.isExtensionCommand(c.text)?await this.session.prompt(c.text):c.mode==="followUp"?await this.session.followUp(c.text):await this.session.steer(c.text);this.updatePendingMessagesDisplay()}catch(s){n(s)}}flushPendingBashComponents(){for(let e of this.pendingBashComponents)this.pendingMessagesContainer.removeChild(e),this.chatContainer.addChild(e);this.pendingBashComponents=[]}showSelector(e){let t=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor)},{component:n,focus:s}=e(t);this.editorContainer.clear(),this.editorContainer.addChild(n),this.ui.setFocus(s),this.ui.requestRender()}showSettingsSelector(){this.showSelector(e=>{let t=new Fi({autoCompact:this.session.autoCompactionEnabled,showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells(),autoResizeImages:this.settingsManager.getImageAutoResize(),blockImages:this.settingsManager.getBlockImages(),enableSkillCommands:this.settingsManager.getEnableSkillCommands(),steeringMode:this.session.steeringMode,followUpMode:this.session.followUpMode,transport:this.settingsManager.getTransport(),thinkingLevel:this.session.thinkingLevel,availableThinkingLevels:this.session.getAvailableThinkingLevels(),currentTheme:this.settingsManager.getTheme()||"dark",availableThemes:tl(),hideThinkingBlock:this.hideThinkingBlock,collapseChangelog:this.settingsManager.getCollapseChangelog(),enableInstallTelemetry:this.settingsManager.getEnableInstallTelemetry(),doubleEscapeAction:this.settingsManager.getDoubleEscapeAction(),treeFilterMode:this.settingsManager.getTreeFilterMode(),showHardwareCursor:this.settingsManager.getShowHardwareCursor(),editorPaddingX:this.settingsManager.getEditorPaddingX(),autocompleteMaxVisible:this.settingsManager.getAutocompleteMaxVisible(),quietStartup:this.settingsManager.getQuietStartup(),clearOnShrink:this.settingsManager.getClearOnShrink(),showTerminalProgress:this.settingsManager.getShowTerminalProgress(),warnings:this.settingsManager.getWarnings()},{onAutoCompactChange:n=>{this.session.setAutoCompactionEnabled(n),this.footer.setAutoCompactEnabled(n)},onShowImagesChange:n=>{this.settingsManager.setShowImages(n);for(let s of this.chatContainer.children)s instanceof Mt&&s.setShowImages(n)},onImageWidthCellsChange:n=>{this.settingsManager.setImageWidthCells(n);for(let s of this.chatContainer.children)s instanceof Mt&&s.setImageWidthCells(n)},onAutoResizeImagesChange:n=>{this.settingsManager.setImageAutoResize(n)},onBlockImagesChange:n=>{this.settingsManager.setBlockImages(n)},onEnableSkillCommandsChange:n=>{this.settingsManager.setEnableSkillCommands(n),this.setupAutocompleteProvider()},onSteeringModeChange:n=>{this.session.setSteeringMode(n)},onFollowUpModeChange:n=>{this.session.setFollowUpMode(n)},onTransportChange:n=>{this.settingsManager.setTransport(n),this.session.agent.transport=n},onThinkingLevelChange:n=>{this.session.setThinkingLevel(n),this.footer.invalidate(),this.updateEditorBorderColor()},onThemeChange:n=>{let s=ys(n,!0);this.settingsManager.setTheme(n),this.ui.invalidate(),s.success||this.showError(`Failed to load theme "${n}": ${s.error}
|
|
370
|
+
Fell back to dark theme.`)},onThemePreview:n=>{ys(n,!0).success&&(this.ui.invalidate(),this.ui.requestRender())},onHideThinkingBlockChange:n=>{this.hideThinkingBlock=n,this.settingsManager.setHideThinkingBlock(n);for(let s of this.chatContainer.children)s instanceof Bt&&s.setHideThinkingBlock(n);this.chatContainer.clear(),this.rebuildChatFromMessages()},onCollapseChangelogChange:n=>{this.settingsManager.setCollapseChangelog(n)},onEnableInstallTelemetryChange:n=>{this.settingsManager.setEnableInstallTelemetry(n)},onQuietStartupChange:n=>{this.settingsManager.setQuietStartup(n)},onDoubleEscapeActionChange:n=>{this.settingsManager.setDoubleEscapeAction(n)},onTreeFilterModeChange:n=>{this.settingsManager.setTreeFilterMode(n)},onShowHardwareCursorChange:n=>{this.settingsManager.setShowHardwareCursor(n),this.ui.setShowHardwareCursor(n)},onEditorPaddingXChange:n=>{this.settingsManager.setEditorPaddingX(n),this.defaultEditor.setPaddingX(n),this.editor!==this.defaultEditor&&this.editor.setPaddingX!==void 0&&this.editor.setPaddingX(n)},onAutocompleteMaxVisibleChange:n=>{this.settingsManager.setAutocompleteMaxVisible(n),this.defaultEditor.setAutocompleteMaxVisible(n),this.editor!==this.defaultEditor&&this.editor.setAutocompleteMaxVisible!==void 0&&this.editor.setAutocompleteMaxVisible(n)},onClearOnShrinkChange:n=>{this.settingsManager.setClearOnShrink(n),this.ui.setClearOnShrink(n)},onShowTerminalProgressChange:n=>{this.settingsManager.setShowTerminalProgress(n)},onWarningsChange:n=>{this.settingsManager.setWarnings(n)},onCancel:()=>{e(),this.ui.requestRender()}});return{component:t,focus:t.getSettingsList()}})}async handleModelCommand(e){if(!e){this.showModelSelector();return}let t=await this.findExactModelMatch(e);if(t){try{await this.session.setModel(t),this.footer.invalidate(),this.updateEditorBorderColor(),this.showStatus(`Model: ${t.id}`),this.maybeWarnAboutAnthropicSubscriptionAuth(t),this.checkDaxnutsEasterEgg(t)}catch(n){this.showError(n instanceof Error?n.message:String(n))}return}this.showModelSelector(e)}async findExactModelMatch(e){let t=await this.getModelCandidates();return fc(e,t)}async getModelCandidates(){if(this.session.scopedModels.length>0)return this.session.scopedModels.map(e=>e.model);this.session.modelRegistry.refresh();try{return await this.session.modelRegistry.getAvailable()}catch{return[]}}async updateAvailableProviderCount(){let e=await this.getModelCandidates(),t=new Set(e.map(n=>n.provider));this.footerDataProvider.setAvailableProviderCount(t.size)}async maybeWarnAboutAnthropicSubscriptionAuth(e=this.session.model){if(this.settingsManager.getWarnings().anthropicExtraUsage===!1||this.anthropicSubscriptionWarningShown||!e||e.provider!=="anthropic")return;if(this.session.modelRegistry.authStorage.get("anthropic")?.type==="oauth"){this.anthropicSubscriptionWarningShown=!0,this.showWarning(bg);return}try{let n=await this.session.modelRegistry.getApiKeyForProvider(e.provider);if(!fM(n))return;this.anthropicSubscriptionWarningShown=!0,this.showWarning(bg)}catch{}}showModelSelector(e){this.showSelector(t=>{let n=new Di(this.ui,this.session.model,this.settingsManager,this.session.modelRegistry,this.session.scopedModels,async s=>{try{await this.session.setModel(s),this.footer.invalidate(),this.updateEditorBorderColor(),t(),this.showStatus(`Model: ${s.id}`),this.maybeWarnAboutAnthropicSubscriptionAuth(s),this.checkDaxnutsEasterEgg(s)}catch(o){t(),this.showError(o instanceof Error?o.message:String(o))}},()=>{t(),this.ui.requestRender()},e);return{component:n,focus:n}})}async showModelsSelector(){this.session.modelRegistry.refresh();let e=this.session.modelRegistry.getAvailable();if(e.length===0){this.showStatus("No models available");return}let t=this.session.scopedModels,n=t.length>0,s=null;if(n)s=t.map(r=>`${r.model.provider}/${r.model.id}`);else{let r=this.settingsManager.getEnabledModels();r!==void 0&&r.length>0&&(s=(await Er(r,this.session.modelRegistry)).map(l=>`${l.model.provider}/${l.model.id}`))}let o=async r=>{if(s=r===null?null:[...r],r&&r.length>0&&r.length<e.length){let a=await Er(r,this.session.modelRegistry);this.session.setScopedModels(a.map(l=>({model:l.model,thinkingLevel:l.thinkingLevel})))}else this.session.setScopedModels([]);await this.updateAvailableProviderCount(),this.ui.requestRender()};this.showSelector(r=>{let a=new Hs({allModels:e,enabledModelIds:s},{onChange:async l=>{await o(l)},onPersist:l=>{let c=l===null||l.length===e.length?void 0:l;this.settingsManager.setEnabledModels(c?[...c]:void 0),this.showStatus("Model selection saved to settings")},onCancel:()=>{r(),this.ui.requestRender()}});return{component:a,focus:a}})}showUserMessageSelector(){let e=this.session.getUserMessagesForForking();if(e.length===0){this.showStatus("No messages to fork from");return}let t=e[e.length-1]?.entryId;this.showSelector(n=>{let s=new Ni(e.map(o=>({id:o.entryId,text:o.text})),async o=>{try{let r=await this.runtimeHost.fork(o);if(r.cancelled){n(),this.ui.requestRender();return}this.renderCurrentSessionState(),this.editor.setText(r.selectedText??""),n(),this.showStatus("Forked to new session")}catch(r){n(),this.showError(r instanceof Error?r.message:String(r))}},()=>{n(),this.ui.requestRender()},t);return{component:s,focus:s.getMessageList()}})}async handleCloneCommand(){let e=this.sessionManager.getLeafId();if(!e){this.showStatus("Nothing to clone yet");return}try{if((await this.runtimeHost.fork(e,{position:"at"})).cancelled){this.ui.requestRender();return}this.renderCurrentSessionState(),this.editor.setText(""),this.showStatus("Cloned to new session")}catch(t){this.showError(t instanceof Error?t.message:String(t))}}showTreeSelector(e){let t=this.sessionManager.getTree(),n=this.sessionManager.getLeafId(),s=this.settingsManager.getTreeFilterMode();if(t.length===0){this.showStatus("No entries in session");return}this.showSelector(o=>{let r=new Bi(t,n,this.ui.terminal.rows,async a=>{if(a===n){o(),this.showStatus("Already at this point");return}o();let l=!1,c;if(!this.settingsManager.getBranchSummarySkipPrompt())for(;;){let u=await this.showExtensionSelector("Summarize branch?",["No summary","Summarize","Summarize with custom prompt"]);if(u===void 0){this.showTreeSelector(a);return}if(l=u!=="No summary",!(u==="Summarize with custom prompt"&&(c=await this.showExtensionEditor("Custom summarization instructions"),c===void 0)))break}let d,p=this.defaultEditor.onEscape;l&&(this.defaultEditor.onEscape=()=>{this.session.abortBranchSummary()},this.chatContainer.addChild(new E(1)),d=new Fe(this.ui,u=>f.fg("accent",u),u=>f.fg("muted",u),`Summarizing branch... (${z("app.interrupt")} to cancel)`),this.statusContainer.addChild(d),this.ui.requestRender());try{let u=await this.session.navigateTree(a,{summarize:l,customInstructions:c});if(u.aborted){this.showStatus("Branch summarization cancelled"),this.showTreeSelector(a);return}if(u.cancelled){this.showStatus("Navigation cancelled");return}this.chatContainer.clear(),this.renderInitialMessages(),u.editorText&&!this.editor.getText().trim()&&this.editor.setText(u.editorText),this.showStatus("Navigated to selected point"),this.flushCompactionQueue({willRetry:!1})}catch(u){this.showError(u instanceof Error?u.message:String(u))}finally{d&&(d.stop(),this.statusContainer.clear()),this.defaultEditor.onEscape=p}},()=>{o(),this.ui.requestRender()},(a,l)=>{this.sessionManager.appendLabelChange(a,l),this.ui.requestRender()},e,s);return{component:r,focus:r}})}showSessionSelector(){this.showSelector(e=>{let t=new Wn(n=>gt.list(this.sessionManager.getCwd(),this.sessionManager.getSessionDir(),n),gt.listAll,async n=>{e(),await this.handleResumeSession(n)},()=>{e(),this.ui.requestRender()},()=>{this.shutdown()},()=>this.ui.requestRender(),{renameSession:async(n,s)=>{let o=(s??"").trim();if(!o)return;gt.open(n).appendSessionInfo(o)},showRenameHint:!0,keybindings:this.keybindings},this.sessionManager.getSessionFile());return{component:t,focus:t}})}async handleResumeSession(e,t){this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.statusContainer.clear();try{let n=await this.runtimeHost.switchSession(e,{withSession:t?.withSession});return n.cancelled||(this.renderCurrentSessionState(),this.showStatus("Resumed session")),n}catch(n){if(n instanceof wi){let s=await this.promptForMissingSessionCwd(n);if(!s)return this.showStatus("Resume cancelled"),{cancelled:!0};let o=await this.runtimeHost.switchSession(e,{cwdOverride:s,withSession:t?.withSession});return o.cancelled||(this.renderCurrentSessionState(),this.showStatus("Resumed session in current cwd")),o}return this.handleFatalRuntimeError("Failed to resume session",n)}}getLoginProviderOptions(e){let n=this.session.modelRegistry.authStorage.getOAuthProviders(),s=new Set(n.map(l=>l.id)),o=n.map(l=>({id:l.id,name:l.name,authType:"oauth"})),r=new Set(this.session.modelRegistry.getAll().map(l=>l.provider));for(let l of r)wM(l,s)&&o.push({id:l,name:this.session.modelRegistry.getProviderDisplayName(l),authType:"api_key"});return(e?o.filter(l=>l.authType===e):o).sort((l,c)=>l.name.localeCompare(c.name))}getLogoutProviderOptions(){let e=this.session.modelRegistry.authStorage,t=[];for(let n of e.list()){let s=e.get(n);s&&t.push({id:n,name:this.session.modelRegistry.getProviderDisplayName(n),authType:s.type})}return t.sort((n,s)=>n.name.localeCompare(s.name))}showLoginAuthTypeSelector(){let e="Use a subscription",t="Use an API key";this.showSelector(n=>{let s=new Nt("Select authentication method:",[e,t],o=>{n();let r=o===e?"oauth":"api_key";this.showLoginProviderSelector(r)},()=>{n(),this.ui.requestRender()});return{component:s,focus:s}})}showLoginProviderSelector(e){let t=this.getLoginProviderOptions(e);if(t.length===0){this.showStatus(e==="oauth"?"No subscription providers available.":"No API key providers available.");return}this.showSelector(n=>{let s=new On("login",this.session.modelRegistry.authStorage,t,async o=>{n();let r=t.find(a=>a.id===o);r&&(r.authType==="oauth"?await this.showLoginDialog(r.id,r.name):r.id===vM?this.showBedrockSetupDialog(r.id,r.name):await this.showApiKeyLoginDialog(r.id,r.name))},()=>{n(),this.showLoginAuthTypeSelector()},o=>this.session.modelRegistry.getProviderAuthStatus(o));return{component:s,focus:s}})}async showOAuthSelector(e){if(e==="login"){this.showLoginAuthTypeSelector();return}let t=this.getLogoutProviderOptions();if(t.length===0){this.showStatus("No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.");return}this.showSelector(n=>{let s=new On(e,this.session.modelRegistry.authStorage,t,async o=>{n();let r=t.find(a=>a.id===o);if(r)try{this.session.modelRegistry.authStorage.logout(r.id),this.session.modelRegistry.refresh(),await this.updateAvailableProviderCount();let a=r.authType==="oauth"?`Logged out of ${r.name}`:`Removed stored API key for ${r.name}. Environment variables and models.json config are unchanged.`;this.showStatus(a)}catch(a){this.showError(`Logout failed: ${a instanceof Error?a.message:String(a)}`)}},()=>{n(),this.ui.requestRender()});return{component:s,focus:s}})}async completeProviderAuthentication(e,t,n,s){this.session.modelRegistry.refresh();let o=n==="oauth"?`Logged in to ${t}`:`Saved API key for ${t}`,r,a;if(xM(s)){let c=this.session.modelRegistry.getAvailable().filter(d=>d.provider===e);if(!bM(e))a=`${o}, but no default model is configured for provider "${e}". Use /model to select a model.`;else if(c.length===0)a=`${o}, but no models are available for that provider. Use /model to select a model.`;else{let d=gc[e];if(r=c.find(p=>p.id===d),!r)a=`${o}, but its default model "${d}" is not available. Use /model to select a model.`;else try{await this.session.setModel(r)}catch(p){r=void 0;let u=p instanceof Error?p.message:String(p);a=`${o}, but selecting its default model failed: ${u}. Use /model to select a model.`}}}await this.updateAvailableProviderCount(),this.footer.invalidate(),this.updateEditorBorderColor(),r?(this.showStatus(`${o}. Selected ${r.id}. Credentials saved to ${ka()}`),this.maybeWarnAboutAnthropicSubscriptionAuth(r),this.checkDaxnutsEasterEgg(r)):(this.showStatus(`${o}. Credentials saved to ${ka()}`),a?this.showError(a):this.maybeWarnAboutAnthropicSubscriptionAuth())}showBedrockSetupDialog(e,t){let n=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor),this.ui.requestRender()},s=new sn(this.ui,e,()=>n(),t,"Amazon Bedrock setup");s.showInfo([f.fg("text","Amazon Bedrock uses AWS credentials instead of a single API key."),f.fg("text","Configure an AWS profile, IAM keys, bearer token, or role-based credentials."),f.fg("muted","See:"),f.fg("accent",` ${se.join(bo(),"providers.md")}`)]),this.editorContainer.clear(),this.editorContainer.addChild(s),this.ui.setFocus(s),this.ui.requestRender()}async showApiKeyLoginDialog(e,t){let n=this.session.model,s=new sn(this.ui,e,(r,a)=>{},t);this.editorContainer.clear(),this.editorContainer.addChild(s),this.ui.setFocus(s),this.ui.requestRender();let o=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor),this.ui.requestRender()};try{let r=(await s.showPrompt("Enter API key:")).trim();if(!r)throw new Error("API key cannot be empty.");this.session.modelRegistry.authStorage.set(e,{type:"api_key",key:r}),o(),await this.completeProviderAuthentication(e,t,"api_key",n)}catch(r){o();let a=r instanceof Error?r.message:String(r);a!=="Login cancelled"&&this.showError(`Failed to save API key for ${t}: ${a}`)}}showOAuthLoginSelect(e,t){return new Promise(n=>{let s=()=>{this.editorContainer.clear(),this.editorContainer.addChild(e),this.ui.setFocus(e),this.ui.requestRender()},o=t.options.map(a=>a.label),r=new Nt(t.message,o,a=>{s(),n(t.options.find(l=>l.label===a)?.id)},()=>{s(),n(void 0)});this.editorContainer.clear(),this.editorContainer.addChild(r),this.ui.setFocus(r),this.ui.requestRender()})}async showLoginDialog(e,t){let n=this.session.modelRegistry.authStorage.getOAuthProviders().find(p=>p.id===e),s=this.session.model,o=n?.usesCallbackServer??!1,r=new sn(this.ui,e,(p,u)=>{},t);this.editorContainer.clear(),this.editorContainer.addChild(r),this.ui.setFocus(r),this.ui.requestRender();let a,l,c=new Promise((p,u)=>{a=p,l=u}),d=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor),this.ui.requestRender()};try{await this.session.modelRegistry.authStorage.login(e,{onAuth:p=>{r.showAuth(p.url,p.instructions),o?r.showManualInput("Paste redirect URL below, or complete login in browser:").then(u=>{u&&a&&(a(u),a=void 0)}).catch(()=>{l&&(l(new Error("Login cancelled")),l=void 0)}):e==="github-copilot"&&r.showWaiting("Waiting for browser authentication...")},onPrompt:async p=>r.showPrompt(p.message,p.placeholder),onProgress:p=>{r.showProgress(p)},onSelect:p=>this.showOAuthLoginSelect(r,p),onManualCodeInput:()=>c,signal:r.signal}),d(),await this.completeProviderAuthentication(e,t,"oauth",s)}catch(p){d();let u=p instanceof Error?p.message:String(p);u!=="Login cancelled"&&this.showError(`Failed to login to ${t}: ${u}`)}}async handleReloadCommand(){if(this.session.isStreaming){this.showWarning("Wait for the current response to finish before reloading.");return}if(this.session.isCompacting){this.showWarning("Wait for compaction to finish before reloading.");return}this.resetExtensionUI();let e=new L,t=o=>f.fg("border",o);e.addChild(new O(t)),e.addChild(new E(1)),e.addChild(new T(f.fg("muted","Reloading keybindings, extensions, skills, prompts, themes..."),1,0)),e.addChild(new E(1)),e.addChild(new O(t));let n=this.editor;this.editorContainer.clear(),this.editorContainer.addChild(e),this.ui.setFocus(e),this.ui.requestRender(!0),await new Promise(o=>process.nextTick(o));let s=o=>{this.editorContainer.clear(),this.editorContainer.addChild(o),this.ui.setFocus(o),this.ui.requestRender()};try{await this.session.reload(),this.keybindings.reload();let o=this.customHeader??this.builtInHeader;js(o)&&o.setExpanded(this.toolOutputExpanded),No(this.session.resourceLoader.getThemes().themes),this.hideThinkingBlock=this.settingsManager.getHideThinkingBlock();let r=this.settingsManager.getTheme(),a=r?ys(r,!0):{success:!0};a.success||this.showError(`Failed to load theme "${r}": ${a.error}
|
|
371
|
+
Fell back to dark theme.`);let l=this.settingsManager.getEditorPaddingX(),c=this.settingsManager.getAutocompleteMaxVisible();this.defaultEditor.setPaddingX(l),this.defaultEditor.setAutocompleteMaxVisible(c),this.editor!==this.defaultEditor&&(this.editor.setPaddingX?.(l),this.editor.setAutocompleteMaxVisible?.(c)),this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor()),this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink()),this.setupAutocompleteProvider();let d=this.session.extensionRunner;this.setupExtensionShortcuts(d),this.rebuildChatFromMessages(),s(this.editor),this.showLoadedResources({force:!1,showDiagnosticsWhenQuiet:!0});let p=this.session.modelRegistry.getError();p&&this.showError(`models.json error: ${p}`),this.showStatus("Reloaded keybindings, extensions, skills, prompts, themes")}catch(o){s(n),this.showError(`Reload failed: ${o instanceof Error?o.message:String(o)}`)}}async handleExportCommand(e){let t=this.getPathCommandArgument(e,"/export");try{if(t?.endsWith(".jsonl")){let n=this.session.exportToJsonl(t);this.showStatus(`Session exported to: ${n}`)}else{let n=await this.session.exportToHtml(t);this.showStatus(`Session exported to: ${n}`)}}catch(n){this.showError(`Failed to export session: ${n instanceof Error?n.message:"Unknown error"}`)}}getPathCommandArgument(e,t){if(e===t||!e.startsWith(`${t} `))return;let n=e.slice(t.length+1).trimStart();if(!n)return;let s=n[0];if(s==='"'||s==="'"){let r=n.indexOf(s,1);return r<0?void 0:n.slice(1,r)}let o=n.search(/\s/);return o<0?n:n.slice(0,o)}async handleImportCommand(e){let t=this.getPathCommandArgument(e,"/import");if(!t){this.showError("Usage: /import <path.jsonl>");return}if(!await this.showExtensionConfirm("Import session",`Replace current session with ${t}?`)){this.showStatus("Import cancelled");return}try{if(this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.statusContainer.clear(),(await this.runtimeHost.importFromJsonl(t)).cancelled){this.showStatus("Import cancelled");return}this.renderCurrentSessionState(),this.showStatus(`Session imported from: ${t}`)}catch(s){if(s instanceof wi){let o=await this.promptForMissingSessionCwd(s);if(!o){this.showStatus("Import cancelled");return}if((await this.runtimeHost.importFromJsonl(t,o)).cancelled){this.showStatus("Import cancelled");return}this.renderCurrentSessionState(),this.showStatus(`Session imported from: ${t}`);return}if(s instanceof Ir){this.showError(`Failed to import session: ${s.message}`);return}await this.handleFatalRuntimeError("Failed to import session",s)}}async handleShareCommand(){try{if(xg("gh",["auth","status"],{encoding:"utf-8"}).status!==0){this.showError("GitHub CLI is not logged in. Run 'gh auth login' first.");return}}catch{this.showError("GitHub CLI (gh) is not installed. Install it from https://cli.github.com/");return}let e=se.join(Gi.tmpdir(),"session.html");try{await this.session.exportToHtml(e)}catch(o){this.showError(`Failed to export session: ${o instanceof Error?o.message:"Unknown error"}`);return}let t=new Ri(this.ui,f,"Creating gist...");this.editorContainer.clear(),this.editorContainer.addChild(t),this.ui.setFocus(t),this.ui.requestRender();let n=()=>{t.dispose(),this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor);try{ft.unlinkSync(e)}catch{}},s=null;t.onAbort=()=>{s?.kill(),n(),this.showStatus("Share cancelled")};try{let o=await new Promise(c=>{s=fg("gh",["gist","create","--public=false",e]);let d="",p="";s.stdout?.on("data",u=>{d+=u.toString()}),s.stderr?.on("data",u=>{p+=u.toString()}),s.on("close",u=>c({stdout:d,stderr:p,code:u}))});if(t.signal.aborted)return;if(n(),o.code!==0){let c=o.stderr?.trim()||"Unknown error";this.showError(`Failed to create gist: ${c}`);return}let r=o.stdout?.trim(),a=r?.split("/").pop();if(!a){this.showError("Failed to parse gist ID from gh output");return}let l=qp(a);this.showStatus(`Share URL: ${l}
|
|
372
|
+
Gist: ${r}`)}catch(o){t.signal.aborted||(n(),this.showError(`Failed to create gist: ${o instanceof Error?o.message:"Unknown error"}`))}}async handleCopyCommand(){let e=this.session.getLastAssistantText();if(!e){this.showError("No agent messages to copy yet.");return}try{await Rc(e),this.showStatus("Copied last agent message to clipboard")}catch(t){this.showError(t instanceof Error?t.message:String(t))}}handleNameCommand(e){let t=e.replace(/^\/name\s*/,"").trim();if(!t){let n=this.sessionManager.getSessionName();n?(this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new T(f.fg("dim",`Session name: ${n}`),1,0))):this.showWarning("Usage: /name <name>"),this.ui.requestRender();return}this.session.setSessionName(t),this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new T(f.fg("dim",`Session name set: ${t}`),1,0)),this.ui.requestRender()}handleSessionCommand(){let e=this.session.getSessionStats(),t=this.sessionManager.getSessionName(),n=`${f.bold("Session Info")}
|
|
373
|
+
|
|
374
|
+
`;t&&(n+=`${f.fg("dim","Name:")} ${t}
|
|
375
|
+
`),n+=`${f.fg("dim","File:")} ${e.sessionFile??"In-memory"}
|
|
376
|
+
`,n+=`${f.fg("dim","ID:")} ${e.sessionId}
|
|
377
|
+
|
|
378
|
+
`,n+=`${f.bold("Messages")}
|
|
379
|
+
`,n+=`${f.fg("dim","User:")} ${e.userMessages}
|
|
380
|
+
`,n+=`${f.fg("dim","Assistant:")} ${e.assistantMessages}
|
|
381
|
+
`,n+=`${f.fg("dim","Tool Calls:")} ${e.toolCalls}
|
|
382
|
+
`,n+=`${f.fg("dim","Tool Results:")} ${e.toolResults}
|
|
383
|
+
`,n+=`${f.fg("dim","Total:")} ${e.totalMessages}
|
|
384
|
+
|
|
385
|
+
`,n+=`${f.bold("Tokens")}
|
|
386
|
+
`,n+=`${f.fg("dim","Input:")} ${e.tokens.input.toLocaleString()}
|
|
387
|
+
`,n+=`${f.fg("dim","Output:")} ${e.tokens.output.toLocaleString()}
|
|
388
|
+
`,e.tokens.cacheRead>0&&(n+=`${f.fg("dim","Cache Read:")} ${e.tokens.cacheRead.toLocaleString()}
|
|
389
|
+
`),e.tokens.cacheWrite>0&&(n+=`${f.fg("dim","Cache Write:")} ${e.tokens.cacheWrite.toLocaleString()}
|
|
390
|
+
`),n+=`${f.fg("dim","Total:")} ${e.tokens.total.toLocaleString()}
|
|
391
|
+
`,e.cost>0&&(n+=`
|
|
392
|
+
${f.bold("Cost")}
|
|
393
|
+
`,n+=`${f.fg("dim","Total:")} ${e.cost.toFixed(4)}`),this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new T(n,1,0)),this.ui.requestRender()}handleChangelogCommand(){let e=vo(),t=Tc(e),n=t.length>0?t.reverse().map(s=>s.content).join(`
|
|
394
|
+
|
|
395
|
+
`):"No changelog entries found.";this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new O),this.chatContainer.addChild(new T(f.bold(f.fg("accent","What's New")),1,0)),this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new le(n,1,1,this.getMarkdownThemeWithSettings())),this.chatContainer.addChild(new O),this.ui.requestRender()}getAppKeyDisplay(e){return Rs(e)}getEditorKeyDisplay(e){return Rs(e)}handleHotkeysCommand(){let e=this.getEditorKeyDisplay("tui.editor.cursorUp"),t=this.getEditorKeyDisplay("tui.editor.cursorDown"),n=this.getEditorKeyDisplay("tui.editor.cursorLeft"),s=this.getEditorKeyDisplay("tui.editor.cursorRight"),o=this.getEditorKeyDisplay("tui.editor.cursorWordLeft"),r=this.getEditorKeyDisplay("tui.editor.cursorWordRight"),a=this.getEditorKeyDisplay("tui.editor.cursorLineStart"),l=this.getEditorKeyDisplay("tui.editor.cursorLineEnd"),c=this.getEditorKeyDisplay("tui.editor.jumpForward"),d=this.getEditorKeyDisplay("tui.editor.jumpBackward"),p=this.getEditorKeyDisplay("tui.editor.pageUp"),u=this.getEditorKeyDisplay("tui.editor.pageDown"),h=this.getEditorKeyDisplay("tui.input.submit"),m=this.getEditorKeyDisplay("tui.input.newLine"),g=this.getEditorKeyDisplay("tui.editor.deleteWordBackward"),x=this.getEditorKeyDisplay("tui.editor.deleteWordForward"),b=this.getEditorKeyDisplay("tui.editor.deleteToLineStart"),v=this.getEditorKeyDisplay("tui.editor.deleteToLineEnd"),w=this.getEditorKeyDisplay("tui.editor.yank"),C=this.getEditorKeyDisplay("tui.editor.yankPop"),R=this.getEditorKeyDisplay("tui.editor.undo"),k=this.getEditorKeyDisplay("tui.input.tab"),A=this.getAppKeyDisplay("app.interrupt"),S=this.getAppKeyDisplay("app.clear"),I=this.getAppKeyDisplay("app.exit"),P=this.getAppKeyDisplay("app.suspend"),M=this.getAppKeyDisplay("app.thinking.cycle"),_=this.getAppKeyDisplay("app.model.cycleForward"),U=this.getAppKeyDisplay("app.model.select"),F=this.getAppKeyDisplay("app.tools.expand"),$=this.getAppKeyDisplay("app.thinking.toggle"),Q=this.getAppKeyDisplay("app.editor.external"),oe=this.getAppKeyDisplay("app.model.cycleBackward"),ue=this.getAppKeyDisplay("app.message.followUp"),Se=this.getAppKeyDisplay("app.message.dequeue"),X=this.getAppKeyDisplay("app.clipboard.pasteImage"),me=`
|
|
396
|
+
**Navigation**
|
|
397
|
+
| Key | Action |
|
|
398
|
+
|-----|--------|
|
|
399
|
+
| \`${e}\` / \`${t}\` / \`${n}\` / \`${s}\` | Move cursor / browse history (Up when empty) |
|
|
400
|
+
| \`${o}\` / \`${r}\` | Move by word |
|
|
401
|
+
| \`${a}\` | Start of line |
|
|
402
|
+
| \`${l}\` | End of line |
|
|
403
|
+
| \`${c}\` | Jump forward to character |
|
|
404
|
+
| \`${d}\` | Jump backward to character |
|
|
405
|
+
| \`${p}\` / \`${u}\` | Scroll by page |
|
|
406
|
+
|
|
407
|
+
**Editing**
|
|
408
|
+
| Key | Action |
|
|
409
|
+
|-----|--------|
|
|
410
|
+
| \`${h}\` | Send message |
|
|
411
|
+
| \`${m}\` | New line${process.platform==="win32"?" (Ctrl+Enter on Windows Terminal)":""} |
|
|
412
|
+
| \`${g}\` | Delete word backwards |
|
|
413
|
+
| \`${x}\` | Delete word forwards |
|
|
414
|
+
| \`${b}\` | Delete to start of line |
|
|
415
|
+
| \`${v}\` | Delete to end of line |
|
|
416
|
+
| \`${w}\` | Paste the most-recently-deleted text |
|
|
417
|
+
| \`${C}\` | Cycle through the deleted text after pasting |
|
|
418
|
+
| \`${R}\` | Undo |
|
|
419
|
+
|
|
420
|
+
**Other**
|
|
421
|
+
| Key | Action |
|
|
422
|
+
|-----|--------|
|
|
423
|
+
| \`${k}\` | Path completion / accept autocomplete |
|
|
424
|
+
| \`${A}\` | Cancel autocomplete / abort streaming |
|
|
425
|
+
| \`${S}\` | Clear editor (first) / exit (second) |
|
|
426
|
+
| \`${I}\` | Exit (when editor is empty) |
|
|
427
|
+
| \`${P}\` | Suspend to background |
|
|
428
|
+
| \`${M}\` | Cycle thinking level |
|
|
429
|
+
| \`${_}\` / \`${oe}\` | Cycle models |
|
|
430
|
+
| \`${U}\` | Open model selector |
|
|
431
|
+
| \`${F}\` | Toggle tool output expansion |
|
|
432
|
+
| \`${$}\` | Toggle thinking block visibility |
|
|
433
|
+
| \`${Q}\` | Edit message in external editor |
|
|
434
|
+
| \`${ue}\` | Queue follow-up message |
|
|
435
|
+
| \`${Se}\` | Restore queued messages |
|
|
436
|
+
| \`${X}\` | Paste image from clipboard |
|
|
437
|
+
| \`/\` | Slash commands |
|
|
438
|
+
| \`!\` | Run bash command |
|
|
439
|
+
| \`!!\` | Run bash command (excluded from context) |
|
|
440
|
+
`,Ee=this.session.extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());if(Ee.size>0){me+=`
|
|
441
|
+
**Extensions**
|
|
442
|
+
| Key | Action |
|
|
443
|
+
|-----|--------|
|
|
444
|
+
`;for(let[Fr,Ki]of Ee){let ie=Ki.description??Ki.extensionPath,Z=or(Fr,{capitalize:!0});me+=`| \`${Z}\` | ${ie} |
|
|
445
|
+
`}}this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new O),this.chatContainer.addChild(new T(f.bold(f.fg("accent","Keyboard Shortcuts")),1,0)),this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new le(me.trim(),1,1,this.getMarkdownThemeWithSettings())),this.chatContainer.addChild(new O),this.ui.requestRender()}async handleClearCommand(){this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.statusContainer.clear();try{if((await this.runtimeHost.newSession()).cancelled)return;this.renderCurrentSessionState(),this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new T(`${f.fg("accent","\u2713 New session started")}`,1,1)),this.ui.requestRender()}catch(e){await this.handleFatalRuntimeError("Failed to create session",e)}}handleDebugCommand(){let e=this.ui.terminal.columns,t=this.ui.terminal.rows,n=this.ui.render(e),s=Qp(),o=[`Debug output at ${new Date().toISOString()}`,`Terminal: ${e}x${t}`,`Total lines: ${n.length}`,"","=== All rendered lines with visible widths ===",...n.map((r,a)=>{let l=W(r),c=JSON.stringify(r);return`[${a}] (w=${l}) ${c}`}),"","=== Agent messages (JSONL) ===",...this.session.messages.map(r=>JSON.stringify(r)),""].join(`
|
|
446
|
+
`);ft.mkdirSync(se.dirname(s),{recursive:!0}),ft.writeFileSync(s,o),this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new T(`${f.fg("accent","\u2713 Debug log written")}
|
|
447
|
+
${f.fg("muted",s)}`,1,1)),this.ui.requestRender()}handleArminSaysHi(){this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new Mi(this.ui)),this.ui.requestRender()}handleDementedDelves(){this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new Or),this.ui.requestRender()}handleDaxnuts(){this.chatContainer.addChild(new E(1)),this.chatContainer.addChild(new zs(this.ui)),this.ui.requestRender()}checkDaxnutsEasterEgg(e){e.provider==="opencode"&&e.id.toLowerCase().includes("kimi-k2.5")&&this.handleDaxnuts()}async handleBashCommand(e,t=!1){let s=await this.session.extensionRunner.emitUserBash({type:"user_bash",command:e,excludeFromContext:t,cwd:this.sessionManager.getCwd()});if(s?.result){let r=s.result;this.bashComponent=new tn(e,this.ui,t),this.session.isStreaming?(this.pendingMessagesContainer.addChild(this.bashComponent),this.pendingBashComponents.push(this.bashComponent)):this.chatContainer.addChild(this.bashComponent),r.output&&this.bashComponent.appendOutput(r.output),this.bashComponent.setComplete(r.exitCode,r.cancelled,r.truncated?{truncated:!0,content:r.output}:void 0,r.fullOutputPath),this.session.recordBashResult(e,r,{excludeFromContext:t}),this.bashComponent=void 0,this.ui.requestRender();return}let o=this.session.isStreaming;this.bashComponent=new tn(e,this.ui,t),o?(this.pendingMessagesContainer.addChild(this.bashComponent),this.pendingBashComponents.push(this.bashComponent)):this.chatContainer.addChild(this.bashComponent),this.ui.requestRender();try{let r=await this.session.executeBash(e,a=>{this.bashComponent&&(this.bashComponent.appendOutput(a),this.ui.requestRender())},{excludeFromContext:t,operations:s?.operations});this.bashComponent&&this.bashComponent.setComplete(r.exitCode,r.cancelled,r.truncated?{truncated:!0,content:r.output}:void 0,r.fullOutputPath)}catch(r){this.bashComponent&&this.bashComponent.setComplete(void 0,!1),this.showError(`Bash command failed: ${r instanceof Error?r.message:"Unknown error"}`)}this.bashComponent=void 0,this.ui.requestRender()}async handleCompactCommand(e){if(this.sessionManager.getEntries().filter(s=>s.type==="message").length<2){this.showWarning("Nothing to compact (no messages yet)");return}this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.statusContainer.clear();try{await this.session.compact(e)}catch{}}stop(){this.unregisterSignalHandlers(),this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!1),this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.clearExtensionTerminalInputListeners(),this.footer.dispose(),this.footerDataProvider.dispose(),this.unsubscribe&&this.unsubscribe(),this.isInitialized&&(this.ui.stop(),this.isInitialized=!1)}};import a6 from"chalk";import{createTwoFilesPatch as PM}from"diff";import{readFile as _M,writeFile as LM,rm as WM,mkdir as OM}from"node:fs/promises";import{dirname as UM,relative as DM,resolve as FM}from"node:path";var kg="filechanges:baseline",Sg="filechanges:clear",Tg="filechanges:untrack";function $M(i){return i.startsWith("@")?i.slice(1):i}function Uc(i,e){let t=$M(e),n=FM(i,t),s=DM(i,n),o=s&&!s.startsWith("..")&&s!==""?s:t;return{absPath:n,relPath:o}}async function Dc(i){try{return await _M(i,"utf-8")}catch{return null}}function Fc(i){let e=0,t=0;for(let n of i.split(`
|
|
448
|
+
`))n.startsWith("+++ ")||n.startsWith("--- ")||n.startsWith("@@")||(n.startsWith("+")?e++:n.startsWith("-")&&t++);return{added:e,removed:t}}function BM(i,e){return`(+${i}/-${e})`}function NM(i,e){let t=e.match(/^\+(\d+)\/\-(\d+)$/);if(!t)return i.fg("muted",e);let n=Number(t[1]),s=Number(t[2]),o=n===0?i.fg("text",`+${n}`):i.fg("success",`+${n}`),r=s===0?i.fg("text",`-${s}`):i.fg("error",`-${s}`);return o+i.fg("text","/")+r}function GM(i,e){if(i.size===0)return;let t=0,n=0;for(let s of i.values())s.kind==="new"?n++:t++;return e?e.fg("muted",`\u0394 ${t} + ${n}`):`\u0394 ${t} + ${n}`}function Cg(i,e){if(i.size===0)return;let t=[...i.values()].sort((o,r)=>r.updatedAt-o.updatedAt),n=8,s=[];for(let o of t.slice(0,n)){let r=o.kind==="new"?"+":"\u0394";if(!e){s.push(`${r} ${o.displayPath} ${BM(o.added,o.removed)}`);continue}let a=e.fg("muted",`${r} `)+e.fg("muted",`${o.displayPath} `),l,c=o.added===0?e.fg("text",`+${o.added}`):e.fg("success",`+${o.added}`),d=o.removed===0?e.fg("text",`-${o.removed}`):e.fg("error",`-${o.removed}`);l=e.fg("text","(")+c+e.fg("text","/")+d+e.fg("text",")"),s.push(a+l)}return t.length>n&&s.push(e?e.fg("dim",`\u2026and ${t.length-n} more`):`\u2026and ${t.length-n} more`),s}function $c(i,e,t){return PM(i,i,e??"",t,"","",{context:3})}async function KM(i){await OM(UM(i),{recursive:!0})}function Mg(i){let e=new Map,t=new Map,n=new Map;function s(p){p?.hasUI&&(p.ui.setStatus("filechanges",GM(t,p.ui.theme)),p.ui.setWidget("filechanges",Cg(t,p.ui.theme)))}async function o(p,u){let h=e.get(u);if(!h)return;let m=await Dc(h.absPath);if(h.originalContent===null){if(m===null){t.delete(u);return}let w=h.path,C=$c(w,null,m),{added:R,removed:k}=Fc(C);t.set(u,{path:h.path,absPath:h.absPath,displayPath:w,originalContent:null,currentContent:m,diff:C,added:R,removed:k,kind:"new",updatedAt:Date.now()});return}if(m===null){let w=h.path,C=$c(w,h.originalContent,""),{added:R,removed:k}=Fc(C);t.set(u,{path:h.path,absPath:h.absPath,displayPath:w,originalContent:h.originalContent,currentContent:"",diff:C,added:R,removed:k,kind:"edited",updatedAt:Date.now()});return}if(m===h.originalContent){t.delete(u);return}let g=h.path,x=$c(g,h.originalContent,m),{added:b,removed:v}=Fc(x);t.set(u,{path:h.path,absPath:h.absPath,displayPath:g,originalContent:h.originalContent,currentContent:m,diff:x,added:b,removed:v,kind:"edited",updatedAt:Date.now()})}async function r(p,u){e.clear(),t.clear(),n.clear(),i.appendEntry(Sg,{timestamp:Date.now(),reason:u}),s(p)}async function a(p){if(await p.waitForIdle(),t.size===0){p.hasUI&&p.ui.notify("filechanges: nothing to decline.","info");return}let u=p.args?.includes("force")??!1;if(p.hasUI&&!u){if(!await p.ui.confirm("Decline sling changes?","This will revert ALL currently logged sling changes (overwrite files / delete created files)."))return}else if(!p.hasUI&&!u)throw new Error("Decline requires confirmation. Run: /filechanges-decline force");let h=[...t.values()].sort((x,b)=>b.updatedAt-x.updatedAt),m=0,g=[];for(let x of h)try{x.originalContent===null?await WM(x.absPath,{force:!0}):(await KM(x.absPath),await LM(x.absPath,x.originalContent,"utf-8")),m++}catch(b){g.push(`${x.displayPath}: ${b?.message??String(b)}`)}await r(p,"decline"),p.hasUI&&(g.length===0?p.ui.notify(`filechanges: declined changes for ${m} file(s).`,"info"):(p.ui.notify(`filechanges: declined with ${g.length} error(s). Run /filechanges to inspect; see console for details.`,"warning"),console.warn(`[filechanges] decline errors:
|
|
449
|
+
`+g.join(`
|
|
450
|
+
`))))}async function l(p){if(await p.waitForIdle(),t.size===0){p.hasUI&&p.ui.notify("filechanges: nothing to accept.","info");return}let u=p.args?.includes("force")??!1;if(p.hasUI&&!u){if(!await p.ui.confirm("Accept sling changes?","This will keep current files as-is and clear the modification log."))return}else if(!p.hasUI&&!u)throw new Error("Accept requires confirmation. Run: /filechanges-accept force");let h=t.size;await r(p,"accept"),p.hasUI&&p.ui.notify(`filechanges: accepted changes for ${h} file(s).`,"info")}function c(p){return p?p.split(/\s+/g).map(u=>u.trim()).filter(Boolean):[]}i.registerCommand("filechanges",{description:"Show files changed by sling and inspect diffs",handler:async(p,u)=>{if(u.args=c(p),await u.waitForIdle(),s(u),!u.hasUI){if([...t.values()].sort((g,x)=>x.updatedAt-g.updatedAt).length===0){console.log("filechanges: no sling made modifications recorded.");return}let m=Cg(t)??[];console.log(m.join(`
|
|
451
|
+
`));return}for(;;){await u.waitForIdle(),s(u);let h=[...t.values()].sort((v,w)=>w.updatedAt-v.updatedAt);if(h.length===0){u.ui.notify("filechanges: no sling made modifications recorded.","info");return}let m=[{value:"__accept__",label:"Accept changes (clear log)",description:"Keep current files"},{value:"__decline__",label:"Undo changes (revert)",description:"Restore original contents"},{value:"__sep__",label:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",description:""},...h.map(v=>({value:v.path,label:`${v.kind==="new"?"+":"\u0394"} ${v.displayPath}`,description:`+${v.added}/-${v.removed}`}))],g=await u.ui.custom((v,w,C,R)=>{let k=new L;k.addChild(new O(S=>w.fg("accent",S))),k.addChild(new T(w.fg("accent",w.bold("File changes")),1,0));let A=new Ye(m,Math.min(14,m.length),{selectedPrefix:S=>w.fg("accent",S),selectedText:S=>w.fg("accent",S),description:S=>NM(w,S),scrollInfo:S=>w.fg("dim",S),noMatch:S=>w.fg("warning",S)});return A.onSelect=S=>{S.value!=="__sep__"&&R(S.value)},A.onCancel=()=>R(null),k.addChild(A),k.addChild(new T(w.fg("dim","\u2191\u2193 navigate \u2022 enter select \u2022 esc close"),1,0)),k.addChild(new O(S=>w.fg("accent",S))),{render:S=>k.render(S),invalidate:()=>k.invalidate(),handleInput:S=>{A.handleInput(S),v.requestRender()}}},{overlay:!0});if(!g)return;if(g==="__accept__"){await l(u);return}if(g==="__decline__"){await a(u);return}let x=t.get(g);if(!x){u.ui.notify("filechanges: entry not found (maybe log was cleared).","warning");continue}let b="```diff\n"+(x.diff.trimEnd()||"(no diff)")+"\n```";await u.ui.custom((v,w,C,R)=>{let k=new L;return k.addChild(new O(A=>w.fg("accent",A))),k.addChild(new T(w.fg("accent",w.bold(x.displayPath)),1,0)),k.addChild(new le(b,1,0,we())),k.addChild(new T(w.fg("dim","esc to go back"),1,0)),k.addChild(new O(A=>w.fg("accent",A))),{render:A=>k.render(A),invalidate:()=>k.invalidate(),handleInput:A=>{ge(A,cn.escape)||ge(A,cn.ctrl("c"))?R():v.requestRender()}}},{overlay:!0})}}}),i.registerCommand("filechanges-accept",{description:"Accept sling made changes (keeps files, clears log)",handler:async(p,u)=>{u.args=c(p),await l(u)}}),i.registerCommand("filechanges-decline",{description:"Decline sling made changes (reverts files, clears log)",handler:async(p,u)=>{u.args=c(p),await a(u)}});async function d(p){e.clear(),t.clear(),n.clear();for(let u of p.sessionManager.getBranch())if(u.type==="custom"){if(u.customType===Sg){e.clear(),t.clear();continue}if(u.customType===kg){let h=u.data;if(!h?.path)continue;let{absPath:m,relPath:g}=Uc(p.cwd,h.path);e.set(g,{path:g,absPath:m,originalContent:typeof h.originalContent=="string"?h.originalContent:null,createdAt:typeof h.timestamp=="number"?h.timestamp:Date.now()});continue}if(u.customType===Tg){let h=u.data;if(!h?.path)continue;let{relPath:m}=Uc(p.cwd,h.path);e.delete(m),t.delete(m);continue}}for(let u of e.keys())await o(p,u);s(p)}i.on("session_start",async(p,u)=>{await d(u)}),i.on("session_before_switch",async(p,u)=>{await d(u)}),i.on("session_tree",async(p,u)=>{await d(u)}),i.on("session_before_fork",async(p,u)=>{await d(u)}),i.on("tool_call",async(p,u)=>{if(Ms("edit",p)||Ms("write",p)){let{absPath:h,relPath:m}=Uc(u.cwd,p.input.path),g=await Dc(h);n.set(p.toolCallId,{path:m,absPath:h,before:g})}}),i.on("tool_result",async(p,u)=>{if(p.isError){n.delete(p.toolCallId);return}if(!nr(p)&&!ir(p))return;let h=n.get(p.toolCallId);if(n.delete(p.toolCallId),!h)return;e.has(h.path)||(e.set(h.path,{path:h.path,absPath:h.absPath,originalContent:h.before,createdAt:Date.now()}),i.appendEntry(kg,{path:h.path,originalContent:h.before,timestamp:Date.now()})),await o(u,h.path);let m=e.get(h.path),g=await Dc(h.absPath);m&&(m.originalContent!==null&&g===m.originalContent||m.originalContent===null&&g===null)&&(e.delete(h.path),t.delete(h.path),i.appendEntry(Tg,{path:h.path,timestamp:Date.now()})),s(u)})}function Rg(i){}var HM=on.join(Ig(),".pi","agent"),jM=on.join(Ig(),".agents"),Vs=null,Eg=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function qM(i){let e=on.basename(process.cwd()),t=i.getSessionName();return t?`\u03C0 - ${t} - ${e}`:`\u03C0 - ${e}`}function Dn(i){i.ui.setWorkingMessage(zM.magenta(ma[Math.floor(Math.random()*ma.length)]+"..."))}function VM(i){let e=null,t=0;function n(l){e&&(clearInterval(e),e=null),t=0,l.ui.setTitle(qM(i))}function s(l){n(l),e=setInterval(()=>{let c=Eg[t%Eg.length],d=on.basename(process.cwd()),p=i.getSessionName(),u=p?`${c} \u03C0 - ${p} - ${d}`:`${c} \u03C0 - ${d}`;l.ui.setTitle(u),t++},80)}ua(),Mg(i),Rg(i),i.on("resources_discover",async l=>{let d=[on.join(l.cwd,".sling","agent"),jM,HM],p=[],u=[],h=[];for(let m of d){let g=on.join(m,"skills");Bc(g)&&p.push(g);let x=on.join(m,"prompts");Bc(x)&&u.push(x);let b=on.join(m,"themes");Bc(b)&&h.push(b)}return{skillPaths:p,promptPaths:u,themePaths:h}});let o=new WeakSet;i.on("session_start",async(l,c)=>{let d=c.modelRegistry.authStorage;if(!o.has(d)){let p=d.getOAuthProviders.bind(d);d.getOAuthProviders=()=>p().filter(u=>u.id==="slingshot"),o.add(d)}c.hasUI&&c.ui.setHeader(Bp)});let r=!1;i.registerCommand("footer",{description:"Toggle custom footer",handler:async(l,c)=>{r=!r,r?(c.ui.setFooter((d,p,u)=>({dispose:u.onBranchChange(()=>d.requestRender()),invalidate(){},render(m){let g=0,x=0,b=0;for(let S of c.sessionManager.getBranch())if(S.type==="message"&&S.message.role==="assistant"){let I=S.message;g+=I.usage.input,x+=I.usage.output,b+=I.usage.cost.total}let v=u.getGitBranch(),w=S=>S<1e3?`${S}`:`${(S/1e3).toFixed(1)}k`,C=p.fg("dim",`\u2191${w(g)} \u2193${w(x)} $${b.toFixed(3)}`),R=v?` (${v})`:"",k=p.fg("dim",`${c.model?.id||"no-model"}${R}`),A=" ".repeat(Math.max(1,m-W(C)-W(k)));return[G(C+A+k,m)]}})),c.ui.notify("Custom footer enabled","info")):(c.ui.setFooter(void 0),c.ui.notify("Default footer restored","info"))}}),i.registerProvider("slingshot",{baseUrl:Ap,api:"openai-completions",apiKey:"SLINGSHOT_API_KEY",models:Dp,oauth:{name:"Slingshot",login:pa,refreshToken:uo,getApiKey:l=>(Vs=l,l.access)}}),i.registerCommand("slingshot-debug",{description:"Toggle Slingshot analytics debug logging",handler:async(l,c)=>{let d=!yt();if(Fp(d),d){let p="Slingshot Analytics Debug: ENABLED \u2705",u=$p();u&&(p+=`
|
|
33
452
|
|
|
34
453
|
Log file:
|
|
35
|
-
${
|
|
36
|
-
`).filter(
|
|
37
|
-
`)),
|
|
38
|
-
`).length+"",message_id:
|
|
454
|
+
${u}`),i.sendMessage({customType:"slingshot-debug-status",content:p,display:!0})}else i.sendMessage({customType:"slingshot-debug-status",content:"Slingshot Analytics Debug: DISABLED \u274C",display:!0})}}),i.registerCommand("refresh-token",{description:"Manually refresh Slingshot OAuth token",handler:async(l,c)=>{try{let d=c.modelRegistry.authStorage,p=d.get("slingshot");if(!p||p.type!=="oauth"){c.ui.notify("No Slingshot OAuth credentials found. Please use /login slingshot first.","error");return}c.ui.setStatus("refresh","Refreshing Slingshot token...");let u=await uo(p);d.set("slingshot",{type:"oauth",...u}),Vs=u,c.ui.setStatus("refresh",void 0),c.ui.notify("Slingshot token refreshed successfully!","info")}catch(d){c.ui.setStatus("refresh",void 0);let p=d instanceof Error?d.message:String(d);c.ui.notify(`Failed to refresh token: ${p}`,"error")}}});let a=co();i.on("before_agent_start",async(l,c)=>{try{s(c),Dn(c),ga(c,"random");let d=await ho(l,c,Vs);if(!d?.headers||!d.sageCommonData)return;a=co(),go("agentExecutionStatus",d.headers,d.sageCommonData,{agent_id:a,agent_name:"Sling_Coding_Assistant",agent_execution_status:"Started",agent_correlation_id:a,agent_type:"Temp"})}catch(d){console.error("[Slingshot] Analytics error. Run /slingshot-debug for details.",d),yt()&&(Ie(`CRITICAL ERROR in event handler: ${d?.message||d}`),d?.stack&&Ie(d.stack))}}),i.on("agent_end",async(l,c)=>{try{n(c);let d=await ho(l,c,Vs);if(!d?.headers||!d.sageCommonData)return;await go("agentExecutionStatus",d.headers,d.sageCommonData,{agent_id:a,agent_name:"Sling_Coding_Assistant",agent_execution_status:"Success",agent_correlation_id:a,agent_type:"Temp",tools_list:[]})}catch(d){i.sendMessage({customType:"slingshot-analytics-error",content:"[Slingshot] Analytics error. Run /slingshot-debug for details.",display:!0}),yt()&&(Ie(`CRITICAL ERROR in event handler: ${d?.message||d}`),d?.stack&&Ie(d.stack))}}),i.on("tool_execution_start",async(l,c)=>{Dn(c)}),i.on("tool_result",async(l,c)=>{if(Dn(c),l.toolName==="write"||l.toolName==="edit")try{let d=await ho(l,c,Vs);if(!d?.headers||!d.sageCommonData||l.isError)return;let p=l.input.path+"",h=p.split(".").pop()||"",m="";l.toolName==="write"?m=l.input.content+"":l.toolName==="edit"&&(m=(l.details?.diff+"").split(`
|
|
455
|
+
`).filter(g=>g.startsWith("+")||g.startsWith("-")).join(`
|
|
456
|
+
`)),go(`${l.toolName==="edit"?"insertCode":"createNewFile"}`,d.headers,d.sageCommonData,{programming_language:h,number_of_lines:m.split(`
|
|
457
|
+
`).length+"",message_id:c.sessionManager.getSessionId()+"-"+a,code_block_id:c.sessionManager.getSessionId()+"-"+p})}catch(d){i.sendMessage({customType:"slingshot-analytics-error",content:"[Slingshot] Analytics error. Run /slingshot-debug for details.",display:!0}),yt()&&(Ie(`CRITICAL ERROR in event handler: ${d?.message||d}`),d?.stack&&Ie(d.stack))}}),i.on("tool_execution_end",async(l,c)=>{Dn(c)}),i.on("message_start",async(l,c)=>{Dn(c)}),i.on("message_update",async(l,c)=>{Dn(c)}),i.on("message_end",async(l,c)=>{Dn(c)})}export{VM as default};
|