swayrouter 1.0.0
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/.env.example +43 -0
- package/CHANGELOG.md +132 -0
- package/LICENSE +30 -0
- package/README.id.md +633 -0
- package/README.md +628 -0
- package/cli/cli.js +388 -0
- package/cli/package.json +4 -0
- package/cli/src/cli/commands/xaiVideo.js +280 -0
- package/cli/src/cli/tray/SwayAvatar.svg +20 -0
- package/cli/src/cli/tray/autostart.js +351 -0
- package/cli/src/cli/tray/icon.ico +0 -0
- package/cli/src/cli/tray/icon.png +0 -0
- package/cli/src/cli/tray/tray.js +258 -0
- package/cli/src/cli/tray/tray.ps1 +129 -0
- package/cli/src/cli/tray/trayHost.js +157 -0
- package/cli/src/cli/tray/trayWin.js +83 -0
- package/cli/src/cli/utils/display.js +123 -0
- package/cli/src/cli/utils/input.js +138 -0
- package/cli/src/runtime/discover.js +153 -0
- package/cli/src/runtime/lifecycle.js +333 -0
- package/cli/src/runtime/runMenu.js +250 -0
- package/cli/src/runtime/uiAdapters.js +12 -0
- package/cli/src/runtime/update.js +130 -0
- package/dashboard/dist/assets/CliTools-Ch3gKuNw.js +24 -0
- package/dashboard/dist/assets/Combo-BBCldjWi.js +1 -0
- package/dashboard/dist/assets/ConsoleLog-wywAYcPT.js +6 -0
- package/dashboard/dist/assets/Dashboard-DxzyF41b.js +1 -0
- package/dashboard/dist/assets/Header-C_9Su9BF.js +1 -0
- package/dashboard/dist/assets/Keys-D0ufgcsc.js +1 -0
- package/dashboard/dist/assets/Login-BeKpipS_.js +1 -0
- package/dashboard/dist/assets/ManageApiKey-CVXsmW2B.js +1 -0
- package/dashboard/dist/assets/OAuthCallback-D_UZYcF6.js +1 -0
- package/dashboard/dist/assets/Provider-BU7JfTqm.js +4 -0
- package/dashboard/dist/assets/ProviderModelAccordion-BAifkfVR.js +1 -0
- package/dashboard/dist/assets/Proxy-CU15VJ--.js +1 -0
- package/dashboard/dist/assets/QuotaMonitor-HzGK7bcc.js +1 -0
- package/dashboard/dist/assets/Settings-Dt4y2dC0.js +1 -0
- package/dashboard/dist/assets/Setup-DSDUwU7N.js +1 -0
- package/dashboard/dist/assets/StatusBadge-1nAOyHU2.js +1 -0
- package/dashboard/dist/assets/SwayChat-Bup7up6D.js +10 -0
- package/dashboard/dist/assets/Usage-eWnrPQ_v.js +4 -0
- package/dashboard/dist/assets/accordion-DOOPDDgt.js +1 -0
- package/dashboard/dist/assets/admin-extras-api-CCdu5TFM.js +1 -0
- package/dashboard/dist/assets/api-keys-api-ifAC2Ok3.js +1 -0
- package/dashboard/dist/assets/card-CC0Omjcv.js +1 -0
- package/dashboard/dist/assets/chatStudio-C0zPz_Z_.js +2 -0
- package/dashboard/dist/assets/checkbox-7SZBrmbN.js +1 -0
- package/dashboard/dist/assets/connections-api-_N54UD3S.js +1 -0
- package/dashboard/dist/assets/copy-button-qBvM6H9z.js +1 -0
- package/dashboard/dist/assets/currency-api-SV9CBf5e.js +1 -0
- package/dashboard/dist/assets/flip-button-BGgkjtl0.js +1 -0
- package/dashboard/dist/assets/frame-cUiti6Lq.js +1 -0
- package/dashboard/dist/assets/icons-vendor-CUx7SB5V.js +541 -0
- package/dashboard/dist/assets/index-B6j-9zHy.js +10 -0
- package/dashboard/dist/assets/index-C-_l0yYz.css +1 -0
- package/dashboard/dist/assets/live-mode-CHShLY4E.js +1 -0
- package/dashboard/dist/assets/markdown-vendor-BY8e1gQ8.js +29 -0
- package/dashboard/dist/assets/motion-vendor-g5fpGzmJ.js +9 -0
- package/dashboard/dist/assets/oauth-callback-CqYQzyd7.js +1 -0
- package/dashboard/dist/assets/query-vendor-DVevaSVS.js +1 -0
- package/dashboard/dist/assets/react-vendor-xnYrwzsL.js +61 -0
- package/dashboard/dist/assets/ripple-button-l8aMiVVG.js +1 -0
- package/dashboard/dist/assets/segmented-CqmEnQjZ.js +1 -0
- package/dashboard/dist/assets/select-D8pUtMXp.js +1 -0
- package/dashboard/dist/assets/skeleton-7uJDiIXe.js +1 -0
- package/dashboard/dist/assets/table-D0M60Tu1.js +1 -0
- package/dashboard/dist/assets/tabs-C6YkuulG.js +1 -0
- package/dashboard/dist/assets/tunnel-api-DDPsBaDV.js +1 -0
- package/dashboard/dist/assets/ui-vendor-BuM9f2NY.js +17 -0
- package/dashboard/dist/image2/SwayAvatar.svg +20 -0
- package/dashboard/dist/index.html +32 -0
- package/dashboard/dist/logo/avatar.svg +1 -0
- package/dashboard/dist/logo/sway.svg +20 -0
- package/dashboard/dist/logo/swaychat.svg +20 -0
- package/dashboard/dist/providers/SwayCustom.svg +19 -0
- package/dashboard/dist/providers/alicode.svg +12 -0
- package/dashboard/dist/providers/anthropic.svg +11 -0
- package/dashboard/dist/providers/antigravity.svg +3 -0
- package/dashboard/dist/providers/azure.svg +5 -0
- package/dashboard/dist/providers/baidu.svg +3 -0
- package/dashboard/dist/providers/blackbox.svg +5 -0
- package/dashboard/dist/providers/byteplus.svg +3 -0
- package/dashboard/dist/providers/cerebras.svg +4 -0
- package/dashboard/dist/providers/chutes.svg +4 -0
- package/dashboard/dist/providers/claude.svg +3 -0
- package/dashboard/dist/providers/cline.svg +11 -0
- package/dashboard/dist/providers/cloudflare-ai.svg +4 -0
- package/dashboard/dist/providers/codebuddy.svg +11 -0
- package/dashboard/dist/providers/codex.svg +10 -0
- package/dashboard/dist/providers/commandcode.svg +3 -0
- package/dashboard/dist/providers/cursor.svg +3 -0
- package/dashboard/dist/providers/deepseek.svg +10 -0
- package/dashboard/dist/providers/featherless.svg +3 -0
- package/dashboard/dist/providers/fireworks.svg +3 -0
- package/dashboard/dist/providers/gemini.svg +3 -0
- package/dashboard/dist/providers/geminicli.svg +11 -0
- package/dashboard/dist/providers/github.svg +3 -0
- package/dashboard/dist/providers/grok.svg +3 -0
- package/dashboard/dist/providers/groq.svg +3 -0
- package/dashboard/dist/providers/hermesagent.svg +1 -0
- package/dashboard/dist/providers/kilocode.svg +15 -0
- package/dashboard/dist/providers/kimchi.svg +3 -0
- package/dashboard/dist/providers/kimi.svg +4 -0
- package/dashboard/dist/providers/kiro.svg +10 -0
- package/dashboard/dist/providers/meta.svg +3 -0
- package/dashboard/dist/providers/mimo.svg +10 -0
- package/dashboard/dist/providers/minimax.svg +3 -0
- package/dashboard/dist/providers/mistral.svg +3 -0
- package/dashboard/dist/providers/morph.svg +3 -0
- package/dashboard/dist/providers/nebius.svg +4 -0
- package/dashboard/dist/providers/nvidia.svg +3 -0
- package/dashboard/dist/providers/ollama.svg +3 -0
- package/dashboard/dist/providers/omp.svg +5 -0
- package/dashboard/dist/providers/openai.svg +3 -0
- package/dashboard/dist/providers/opencode.svg +3 -0
- package/dashboard/dist/providers/openrouter.svg +3 -0
- package/dashboard/dist/providers/perplexity.svg +3 -0
- package/dashboard/dist/providers/poolside.svg +36 -0
- package/dashboard/dist/providers/qoder.svg +11 -0
- package/dashboard/dist/providers/sumopod.svg +3 -0
- package/dashboard/dist/providers/tencent.svg +5 -0
- package/dashboard/dist/providers/together.svg +12 -0
- package/dashboard/dist/providers/trae.svg +3 -0
- package/dashboard/dist/providers/venice.svg +4 -0
- package/dashboard/dist/providers/vercel.svg +3 -0
- package/dashboard/dist/providers/vertex.svg +17 -0
- package/dashboard/dist/providers/windsurf.svg +10 -0
- package/dashboard/dist/providers/zai.svg +3 -0
- package/dashboard/tsconfig.json +13 -0
- package/package.json +87 -0
- package/src/config/appConstants.js +153 -0
- package/src/config/defaultThinkingSignature.js +7 -0
- package/src/config/errorConfig.js +117 -0
- package/src/config/grokCli.js +9 -0
- package/src/config/kiroConstants.js +235 -0
- package/src/config/mediaConfig.js +20 -0
- package/src/config/ollamaModels.js +18 -0
- package/src/config/providerModels.js +109 -0
- package/src/config/providers.js +17 -0
- package/src/config/runtimeConfig.js +84 -0
- package/src/dashboardGuard.js +254 -0
- package/src/executors/antigravity.js +389 -0
- package/src/executors/azure.js +49 -0
- package/src/executors/base.js +225 -0
- package/src/executors/codebuddy-cn.js +23 -0
- package/src/executors/codebuddy-intl.js +60 -0
- package/src/executors/codex.js +436 -0
- package/src/executors/commandcode.js +83 -0
- package/src/executors/cursor.js +1075 -0
- package/src/executors/default.js +294 -0
- package/src/executors/gemini-cli.js +88 -0
- package/src/executors/github.js +393 -0
- package/src/executors/grok-cli.js +510 -0
- package/src/executors/grok-web.js +342 -0
- package/src/executors/index.js +86 -0
- package/src/executors/kimchi.js +116 -0
- package/src/executors/kiro.js +1155 -0
- package/src/executors/ollama-local.js +14 -0
- package/src/executors/opencode-go.js +47 -0
- package/src/executors/opencode.js +31 -0
- package/src/executors/qoder.js +433 -0
- package/src/executors/trae.js +318 -0
- package/src/executors/vertex.js +151 -0
- package/src/executors/windsurf.js +555 -0
- package/src/executors/xiaomi-tokenplan.js +16 -0
- package/src/handlers/chatCore/nonStreamingHandler.js +370 -0
- package/src/handlers/chatCore/requestDetail.js +130 -0
- package/src/handlers/chatCore/sseToJsonHandler.js +318 -0
- package/src/handlers/chatCore/streamingHandler.js +250 -0
- package/src/handlers/chatCore.js +652 -0
- package/src/lib/auth/dashboardSession.js +83 -0
- package/src/lib/auth/loginLimiter.js +99 -0
- package/src/lib/cache/ttlCache.js +153 -0
- package/src/lib/consoleLogBuffer.js +127 -0
- package/src/lib/dataDir.js +45 -0
- package/src/lib/db/adapters/betterSqliteAdapter.js +36 -0
- package/src/lib/db/adapters/bunSqliteAdapter.js +47 -0
- package/src/lib/db/adapters/nodeSqliteAdapter.js +65 -0
- package/src/lib/db/adapters/runtimeHelpers.js +23 -0
- package/src/lib/db/adapters/sqljsAdapter.js +103 -0
- package/src/lib/db/backup.js +75 -0
- package/src/lib/db/driver.js +110 -0
- package/src/lib/db/helpers/jsonCol.js +18 -0
- package/src/lib/db/helpers/kvStore.js +48 -0
- package/src/lib/db/helpers/metaStore.js +32 -0
- package/src/lib/db/index.js +473 -0
- package/src/lib/db/migrate.js +267 -0
- package/src/lib/db/migrations/001-initial.js +12 -0
- package/src/lib/db/migrations/002-prune-headroom-pxpipe-settings.js +32 -0
- package/src/lib/db/migrations/004-request-details-trace-id.js +12 -0
- package/src/lib/db/migrations/005-request-details-payload-capture.js +11 -0
- package/src/lib/db/migrations/007-headroom-readd-settings.js +35 -0
- package/src/lib/db/migrations/008-account-model-locks.js +22 -0
- package/src/lib/db/migrations/009-warp-pool-lifecycle.js +5 -0
- package/src/lib/db/migrations/010-api-key-file-permissions.js +7 -0
- package/src/lib/db/migrations/011-remove-upstream-user-agent-profile.js +41 -0
- package/src/lib/db/migrations/012-remove-headroom-settings.js +33 -0
- package/src/lib/db/migrations/013-default-fill-first-routing.js +20 -0
- package/src/lib/db/migrations/014-normalize-fill-first-routing.js +37 -0
- package/src/lib/db/migrations/015-remove-ip-ban-tables.js +8 -0
- package/src/lib/db/migrations/016-prune-legacy-codebuddy-intl-models.js +25 -0
- package/src/lib/db/migrations/index.js +20 -0
- package/src/lib/db/nineRouterMigration.js +785 -0
- package/src/lib/db/paths.js +23 -0
- package/src/lib/db/repos/accountModelLocksRepo.js +74 -0
- package/src/lib/db/repos/aliasRepo.js +108 -0
- package/src/lib/db/repos/apiKeysRepo.js +204 -0
- package/src/lib/db/repos/combosRepo.js +85 -0
- package/src/lib/db/repos/connectionsRepo.js +522 -0
- package/src/lib/db/repos/disabledModelsRepo.js +63 -0
- package/src/lib/db/repos/nodesRepo.js +127 -0
- package/src/lib/db/repos/pricingRepo.js +108 -0
- package/src/lib/db/repos/proxyPoolsRepo.js +104 -0
- package/src/lib/db/repos/requestDetailsRepo.js +345 -0
- package/src/lib/db/repos/settingsRepo.js +135 -0
- package/src/lib/db/repos/usageRepo.js +1335 -0
- package/src/lib/db/schema.js +179 -0
- package/src/lib/db/version.js +32 -0
- package/src/lib/db/writeBehind.js +174 -0
- package/src/lib/disabledModelsDb.js +3 -0
- package/src/lib/env.ts +175 -0
- package/src/lib/errors/publicError.js +18 -0
- package/src/lib/grokBuildConfig.js +243 -0
- package/src/lib/guardRequest.js +51 -0
- package/src/lib/localDb.js +21 -0
- package/src/lib/mcp/stdioSseBridge.js +174 -0
- package/src/lib/network/connectionProxy.js +200 -0
- package/src/lib/network/proxyTest.js +158 -0
- package/src/lib/network/proxyUrl.js +76 -0
- package/src/lib/network/relay.js +71 -0
- package/src/lib/oauth/constants/oauth.js +152 -0
- package/src/lib/oauth/constants/xai.js +43 -0
- package/src/lib/oauth/kiroExternalIdp.js +167 -0
- package/src/lib/oauth/providerHelpers.js +90 -0
- package/src/lib/oauth/providers/_shared.js +12 -0
- package/src/lib/oauth/providers/antigravity.js +126 -0
- package/src/lib/oauth/providers/claude.js +60 -0
- package/src/lib/oauth/providers/cline.js +62 -0
- package/src/lib/oauth/providers/clinepass.js +62 -0
- package/src/lib/oauth/providers/codebuddy-cn.js +75 -0
- package/src/lib/oauth/providers/codebuddy-intl.js +73 -0
- package/src/lib/oauth/providers/codex.js +72 -0
- package/src/lib/oauth/providers/cursor.js +18 -0
- package/src/lib/oauth/providers/gemini-cli.js +84 -0
- package/src/lib/oauth/providers/github.js +96 -0
- package/src/lib/oauth/providers/grok-cli.js +123 -0
- package/src/lib/oauth/providers/index.js +233 -0
- package/src/lib/oauth/providers/kilocode.js +60 -0
- package/src/lib/oauth/providers/kimchi.js +79 -0
- package/src/lib/oauth/providers/kimi.js +79 -0
- package/src/lib/oauth/providers/kiro.js +147 -0
- package/src/lib/oauth/providers/qoder.js +90 -0
- package/src/lib/oauth/providers/trae.js +244 -0
- package/src/lib/oauth/providers/windsurf.js +123 -0
- package/src/lib/oauth/providers/xai.js +95 -0
- package/src/lib/oauth/providers.js +16 -0
- package/src/lib/oauth/services/cursor.js +132 -0
- package/src/lib/oauth/services/kiro.js +351 -0
- package/src/lib/oauth/services/oauth.js +135 -0
- package/src/lib/oauth/services/qoder.js +151 -0
- package/src/lib/oauth/services/xai.js +204 -0
- package/src/lib/oauth/utils/ideDetect.js +55 -0
- package/src/lib/oauth/utils/pkce.js +25 -0
- package/src/lib/oauth/utils/server.js +732 -0
- package/src/lib/oauth/utils/ui.js +43 -0
- package/src/lib/providerNormalization.js +40 -0
- package/src/lib/qoder/constants.js +1 -0
- package/src/lib/requestDetailsDb.js +3 -0
- package/src/lib/resourceProfile.ts +124 -0
- package/src/lib/runtimeSecrets.ts +130 -0
- package/src/lib/security/payloadCapture.js +87 -0
- package/src/lib/tunnel/cloudflare/cloudflared.js +436 -0
- package/src/lib/tunnel/cloudflare/config.js +8 -0
- package/src/lib/tunnel/cloudflare/healthCheck.js +37 -0
- package/src/lib/tunnel/cloudflare/manager.js +149 -0
- package/src/lib/tunnel/cloudflare/pid.js +31 -0
- package/src/lib/tunnel/cloudflare/publicUrl.js +41 -0
- package/src/lib/tunnel/cloudflare/requirements.js +12 -0
- package/src/lib/tunnel/index.js +26 -0
- package/src/lib/tunnel/shared/dnsResolver.js +16 -0
- package/src/lib/tunnel/shared/internetCheck.js +30 -0
- package/src/lib/tunnel/shared/state.js +45 -0
- package/src/lib/tunnel/shared/watchdogConfig.js +6 -0
- package/src/lib/update/installer.js +52 -0
- package/src/lib/update/version.js +116 -0
- package/src/lib/usageDb.js +6 -0
- package/src/lib/usageRefresh.js +88 -0
- package/src/lifecycle/appLifecycle.ts +99 -0
- package/src/models.js +36 -0
- package/src/next/headers.js +12 -0
- package/src/next/server.js +74 -0
- package/src/observability/metrics.js +439 -0
- package/src/observability/tracing.js +107 -0
- package/src/open-sse-index.js +70 -0
- package/src/providers/capabilities.js +299 -0
- package/src/providers/display.ts +142 -0
- package/src/providers/index.js +27 -0
- package/src/providers/models/helpers.js +19 -0
- package/src/providers/models/namePatterns.js +27 -0
- package/src/providers/models/schema.js +32 -0
- package/src/providers/pricing.js +248 -0
- package/src/providers/registry/agentrouter.js +52 -0
- package/src/providers/registry/alicode-intl.js +32 -0
- package/src/providers/registry/alicode.js +33 -0
- package/src/providers/registry/alims-intl.js +30 -0
- package/src/providers/registry/anthropic.js +29 -0
- package/src/providers/registry/antigravity.js +139 -0
- package/src/providers/registry/azure.js +23 -0
- package/src/providers/registry/baidu.js +35 -0
- package/src/providers/registry/blackbox.js +41 -0
- package/src/providers/registry/byteplus.js +36 -0
- package/src/providers/registry/cerebras.js +33 -0
- package/src/providers/registry/chutes.js +26 -0
- package/src/providers/registry/claude.js +80 -0
- package/src/providers/registry/cline.js +53 -0
- package/src/providers/registry/clinepass.js +62 -0
- package/src/providers/registry/cloudflare-ai.js +84 -0
- package/src/providers/registry/codebuddy-cn.js +95 -0
- package/src/providers/registry/codebuddy-intl.js +91 -0
- package/src/providers/registry/codex.js +145 -0
- package/src/providers/registry/commandcode.js +45 -0
- package/src/providers/registry/cursor.js +61 -0
- package/src/providers/registry/deepseek.js +55 -0
- package/src/providers/registry/featherless.js +36 -0
- package/src/providers/registry/fireworks.js +34 -0
- package/src/providers/registry/gemini-cli.js +59 -0
- package/src/providers/registry/gemini.js +76 -0
- package/src/providers/registry/github.js +131 -0
- package/src/providers/registry/glm-cn.js +35 -0
- package/src/providers/registry/glm.js +58 -0
- package/src/providers/registry/grok-cli.js +87 -0
- package/src/providers/registry/grok-web.js +41 -0
- package/src/providers/registry/groq.js +38 -0
- package/src/providers/registry/index.js +77 -0
- package/src/providers/registry/kilo-gateway.js +34 -0
- package/src/providers/registry/kilocode.js +48 -0
- package/src/providers/registry/kimchi.js +49 -0
- package/src/providers/registry/kimi.js +82 -0
- package/src/providers/registry/kiro.js +132 -0
- package/src/providers/registry/meta.js +34 -0
- package/src/providers/registry/minimax-cn.js +90 -0
- package/src/providers/registry/minimax.js +90 -0
- package/src/providers/registry/mistral.js +36 -0
- package/src/providers/registry/morph.js +31 -0
- package/src/providers/registry/nebius.js +26 -0
- package/src/providers/registry/nvidia.js +55 -0
- package/src/providers/registry/ollama-local.js +18 -0
- package/src/providers/registry/ollama.js +38 -0
- package/src/providers/registry/openai.js +114 -0
- package/src/providers/registry/opencode-go.js +41 -0
- package/src/providers/registry/opencode.js +26 -0
- package/src/providers/registry/openrouter.js +36 -0
- package/src/providers/registry/perplexity.js +56 -0
- package/src/providers/registry/poolside.js +30 -0
- package/src/providers/registry/qoder.js +58 -0
- package/src/providers/registry/sumopod.js +84 -0
- package/src/providers/registry/tencent.js +29 -0
- package/src/providers/registry/together.js +38 -0
- package/src/providers/registry/trae.js +71 -0
- package/src/providers/registry/venice.js +69 -0
- package/src/providers/registry/vercel-ai-gateway.js +37 -0
- package/src/providers/registry/vertex-partner.js +31 -0
- package/src/providers/registry/vertex.js +33 -0
- package/src/providers/registry/windsurf.js +129 -0
- package/src/providers/registry/xai.js +46 -0
- package/src/providers/registry/xiaomi-mimo.js +66 -0
- package/src/providers/registry/xiaomi-tokenplan.js +58 -0
- package/src/providers/registryEntry.js +3 -0
- package/src/providers/schema.js +33 -0
- package/src/providers/shared.js +114 -0
- package/src/providers/thinkingLevels.js +49 -0
- package/src/routes/api/auth/login/route.js +82 -0
- package/src/routes/api/auth/logout/route.js +9 -0
- package/src/routes/api/auth/reset-password/route.js +12 -0
- package/src/routes/api/auth/status/route.js +33 -0
- package/src/routes/api/auth/verify-password/route.js +39 -0
- package/src/routes/api/chat/tools/curl/route.js +100 -0
- package/src/routes/api/chat/tools/router/route.js +215 -0
- package/src/routes/api/chat/tools/search/route.js +362 -0
- package/src/routes/api/chat/tools/shell/route.js +228 -0
- package/src/routes/api/cli-tools/all-statuses/route.js +37 -0
- package/src/routes/api/cli-tools/claude-settings/route.js +261 -0
- package/src/routes/api/cli-tools/codex-settings/route.js +220 -0
- package/src/routes/api/cli-tools/cowork-mcp-registry/route.js +80 -0
- package/src/routes/api/cli-tools/cowork-mcp-tools/route.js +96 -0
- package/src/routes/api/cli-tools/cowork-settings/route.js +380 -0
- package/src/routes/api/cli-tools/grok-build-settings/route.js +152 -0
- package/src/routes/api/cli-tools/hermes-settings/route.js +169 -0
- package/src/routes/api/cli-tools/kilo-settings/route.js +131 -0
- package/src/routes/api/cli-tools/model-mappings/route.js +43 -0
- package/src/routes/api/cli-tools/omp-settings/route.js +266 -0
- package/src/routes/api/cli-tools/opencode-settings/route.js +243 -0
- package/src/routes/api/combos/[id]/route.js +73 -0
- package/src/routes/api/combos/route.js +43 -0
- package/src/routes/api/health/live/route.js +7 -0
- package/src/routes/api/health/ready/route.js +19 -0
- package/src/routes/api/health/route.js +17 -0
- package/src/routes/api/inflight/stream/route.js +24 -0
- package/src/routes/api/init/route.js +3 -0
- package/src/routes/api/keys/[id]/route.js +71 -0
- package/src/routes/api/keys/route.js +41 -0
- package/src/routes/api/logs/route.js +19 -0
- package/src/routes/api/mcp/[plugin]/message/route.js +23 -0
- package/src/routes/api/mcp/[plugin]/sse/route.js +35 -0
- package/src/routes/api/models/availability/route.js +104 -0
- package/src/routes/api/models/custom/route.js +58 -0
- package/src/routes/api/models/disabled/route.js +47 -0
- package/src/routes/api/models/route.js +64 -0
- package/src/routes/api/models/test/ping.js +236 -0
- package/src/routes/api/models/test/route.js +14 -0
- package/src/routes/api/oauth/[provider]/[action]/route.js +491 -0
- package/src/routes/api/oauth/codex/bulk-import/route.js +105 -0
- package/src/routes/api/oauth/codex/import-token/route.js +82 -0
- package/src/routes/api/oauth/cursor/auto-import/route.js +250 -0
- package/src/routes/api/oauth/cursor/import/route.js +86 -0
- package/src/routes/api/oauth/kiro/api-key/route.js +60 -0
- package/src/routes/api/oauth/kiro/auto-import/route.js +120 -0
- package/src/routes/api/oauth/kiro/import/route.js +72 -0
- package/src/routes/api/oauth/kiro/import-cli-proxy/route.js +42 -0
- package/src/routes/api/oauth/kiro/social-authorize/route.js +40 -0
- package/src/routes/api/oauth/kiro/social-exchange/route.js +62 -0
- package/src/routes/api/pricing/route.js +96 -0
- package/src/routes/api/provider-nodes/[id]/route.js +106 -0
- package/src/routes/api/provider-nodes/route.js +110 -0
- package/src/routes/api/provider-nodes/validate/route.js +197 -0
- package/src/routes/api/providers/[id]/models/route.js +716 -0
- package/src/routes/api/providers/[id]/route.js +195 -0
- package/src/routes/api/providers/[id]/test/route.js +27 -0
- package/src/routes/api/providers/[id]/test/testUtils.js +912 -0
- package/src/routes/api/providers/[id]/test-models/route.js +211 -0
- package/src/routes/api/providers/catalog/route.js +58 -0
- package/src/routes/api/providers/client/route.js +133 -0
- package/src/routes/api/providers/counts/route.js +43 -0
- package/src/routes/api/providers/kilo/free-models/route.js +58 -0
- package/src/routes/api/providers/route.js +361 -0
- package/src/routes/api/providers/suggested-models/filters.js +24 -0
- package/src/routes/api/providers/suggested-models/route.js +34 -0
- package/src/routes/api/providers/test-batch/route.js +145 -0
- package/src/routes/api/providers/validate/route.js +633 -0
- package/src/routes/api/proxy-pools/[id]/route.js +129 -0
- package/src/routes/api/proxy-pools/[id]/test/route.js +64 -0
- package/src/routes/api/proxy-pools/cloudflare-deploy/route.js +183 -0
- package/src/routes/api/proxy-pools/route.js +85 -0
- package/src/routes/api/proxy-pools/vercel-deploy/route.js +181 -0
- package/src/routes/api/settings/currency/route.js +29 -0
- package/src/routes/api/settings/database/path/route.js +8 -0
- package/src/routes/api/settings/database/route.js +89 -0
- package/src/routes/api/settings/migrate-9router/route.js +81 -0
- package/src/routes/api/settings/require-login/route.js +14 -0
- package/src/routes/api/settings/route.js +186 -0
- package/src/routes/api/shutdown/route.js +25 -0
- package/src/routes/api/tags/route.js +17 -0
- package/src/routes/api/translator/console-logs/route.js +28 -0
- package/src/routes/api/translator/console-logs/stream/route.js +95 -0
- package/src/routes/api/tunnel/disable/route.js +18 -0
- package/src/routes/api/tunnel/enable/route.js +32 -0
- package/src/routes/api/tunnel/status/route.js +23 -0
- package/src/routes/api/update/route.js +42 -0
- package/src/routes/api/usage/[connectionId]/codex-reset-credits/route.js +169 -0
- package/src/routes/api/usage/[connectionId]/route.js +222 -0
- package/src/routes/api/usage/chart/route.js +27 -0
- package/src/routes/api/usage/history/route.js +94 -0
- package/src/routes/api/usage/logs/route.js +14 -0
- package/src/routes/api/usage/providers/route.js +36 -0
- package/src/routes/api/usage/request-details/route.js +61 -0
- package/src/routes/api/usage/request-logs/route.js +15 -0
- package/src/routes/api/usage/stats/route.js +23 -0
- package/src/routes/api/usage/stream/route.js +78 -0
- package/src/routes/api/v1/api/chat/route.js +36 -0
- package/src/routes/api/v1/chat/completions/route.js +28 -0
- package/src/routes/api/v1/images/edits/route.js +70 -0
- package/src/routes/api/v1/images/generations/route.js +50 -0
- package/src/routes/api/v1/images/imageValidation.js +45 -0
- package/src/routes/api/v1/messages/count_tokens/route.js +87 -0
- package/src/routes/api/v1/messages/route.js +26 -0
- package/src/routes/api/v1/models/route.js +440 -0
- package/src/routes/api/v1/responses/compact/route.js +34 -0
- package/src/routes/api/v1/responses/route.js +26 -0
- package/src/routes/api/v1/route.js +1 -0
- package/src/routes/api/version/route.js +11 -0
- package/src/routes/table.js +1141 -0
- package/src/rtk/applyFilter.js +13 -0
- package/src/rtk/autodetect.js +104 -0
- package/src/rtk/caveman.js +6 -0
- package/src/rtk/cavemanPrompts.js +107 -0
- package/src/rtk/constants.js +51 -0
- package/src/rtk/filters/buildOutput.js +120 -0
- package/src/rtk/filters/dedupLog.js +43 -0
- package/src/rtk/filters/find.js +47 -0
- package/src/rtk/filters/gitDiff.js +90 -0
- package/src/rtk/filters/gitLog.js +88 -0
- package/src/rtk/filters/gitStatus.js +101 -0
- package/src/rtk/filters/grep.js +45 -0
- package/src/rtk/filters/ls.js +73 -0
- package/src/rtk/filters/readNumbered.js +22 -0
- package/src/rtk/filters/searchList.js +49 -0
- package/src/rtk/filters/smartTruncate.js +13 -0
- package/src/rtk/filters/tree.js +28 -0
- package/src/rtk/index.js +143 -0
- package/src/rtk/ponytail.js +6 -0
- package/src/rtk/ponytailPrompt.js +49 -0
- package/src/rtk/systemInject.js +89 -0
- package/src/server.ts +474 -0
- package/src/services/accountFallback.js +241 -0
- package/src/services/accountPool.js +389 -0
- package/src/services/capacityAdapter.js +140 -0
- package/src/services/cliModelMapping.js +84 -0
- package/src/services/clinepassModels.js +60 -0
- package/src/services/codebuddyModels.js +250 -0
- package/src/services/combo.js +482 -0
- package/src/services/copilotModels.js +126 -0
- package/src/services/currencyRate.js +56 -0
- package/src/services/cursorModels.js +197 -0
- package/src/services/grokCliModels.js +130 -0
- package/src/services/kimchiModels.js +175 -0
- package/src/services/kiroModels.js +246 -0
- package/src/services/model.js +83 -0
- package/src/services/oauthCredentialManager.js +153 -0
- package/src/services/projectId.js +240 -0
- package/src/services/provider.js +145 -0
- package/src/services/qoderModels.js +274 -0
- package/src/services/tokenRefresh/dedup.js +70 -0
- package/src/services/tokenRefresh/providers.js +626 -0
- package/src/services/tokenRefresh.js +274 -0
- package/src/services/usage/claude.js +134 -0
- package/src/services/usage/codebuddy-cn.js +212 -0
- package/src/services/usage/codex.js +193 -0
- package/src/services/usage/deepseek.js +103 -0
- package/src/services/usage/github.js +94 -0
- package/src/services/usage/google.js +218 -0
- package/src/services/usage/grok-cli.js +368 -0
- package/src/services/usage/grokCliQuotaFrame.js +170 -0
- package/src/services/usage/kimi.js +185 -0
- package/src/services/usage/kiro.js +172 -0
- package/src/services/usage/minimax.js +215 -0
- package/src/services/usage/misc.js +264 -0
- package/src/services/usage/shared.js +59 -0
- package/src/services/usage.js +56 -0
- package/src/shared/clineAuth.js +37 -0
- package/src/shared/constants/config.js +80 -0
- package/src/shared/constants/coworkPlugins.js +69 -0
- package/src/shared/constants/models.js +41 -0
- package/src/shared/constants/providers.js +128 -0
- package/src/shared/constants/providersDisplay.js +1 -0
- package/src/shared/qoder/constants.js +50 -0
- package/src/shared/qoder/cosy.js +134 -0
- package/src/shared/qoder/encoding.js +36 -0
- package/src/shared/services/initializeApp.js +226 -0
- package/src/shared/services/quotaAutoPing.js +310 -0
- package/src/shared/utils/apiKey.js +65 -0
- package/src/shared/utils/clineAuth.js +1 -0
- package/src/shared/utils/index.js +3 -0
- package/src/shared/utils/machineId.js +60 -0
- package/src/shared/utils/ssrfGuard.js +280 -0
- package/src/sse/handlers/chat.js +426 -0
- package/src/sse/oauthLease.js +32 -0
- package/src/sse/recovery.js +235 -0
- package/src/sse/services/auth.js +489 -0
- package/src/sse/services/backgroundTokenRefresh.js +173 -0
- package/src/sse/services/model.js +129 -0
- package/src/sse/services/requestCancellation.js +4 -0
- package/src/sse/services/tokenRefresh.js +264 -0
- package/src/sse/utils/logger.js +142 -0
- package/src/staticServe.ts +95 -0
- package/src/transformer/streamToJsonConverter.js +87 -0
- package/src/translator/canonical.js +81 -0
- package/src/translator/concerns/chunk.js +9 -0
- package/src/translator/concerns/compatFallback.js +147 -0
- package/src/translator/concerns/finishReason.js +59 -0
- package/src/translator/concerns/image.js +105 -0
- package/src/translator/concerns/json.js +4 -0
- package/src/translator/concerns/kiroConversation.js +428 -0
- package/src/translator/concerns/message.js +5 -0
- package/src/translator/concerns/modality.js +134 -0
- package/src/translator/concerns/paramSupport.js +97 -0
- package/src/translator/concerns/prefetch.js +86 -0
- package/src/translator/concerns/reasoning.js +18 -0
- package/src/translator/concerns/thinking.js +40 -0
- package/src/translator/concerns/thinkingUnified.js +319 -0
- package/src/translator/concerns/toolCall.js +134 -0
- package/src/translator/concerns/usage.js +61 -0
- package/src/translator/detection.js +42 -0
- package/src/translator/formats/claude.js +323 -0
- package/src/translator/formats/gemini.js +366 -0
- package/src/translator/formats/maxTokens.js +19 -0
- package/src/translator/formats/openai.js +116 -0
- package/src/translator/formats/responsesApi.js +117 -0
- package/src/translator/formats.js +28 -0
- package/src/translator/index.js +237 -0
- package/src/translator/request/antigravity-to-openai.js +217 -0
- package/src/translator/request/claude-to-kiro.js +288 -0
- package/src/translator/request/claude-to-openai.js +199 -0
- package/src/translator/request/gemini-to-openai.js +142 -0
- package/src/translator/request/openai-responses.js +373 -0
- package/src/translator/request/openai-to-claude.js +260 -0
- package/src/translator/request/openai-to-commandcode.js +161 -0
- package/src/translator/request/openai-to-cursor.js +175 -0
- package/src/translator/request/openai-to-gemini.js +422 -0
- package/src/translator/request/openai-to-kiro.js +360 -0
- package/src/translator/request/openai-to-ollama.js +152 -0
- package/src/translator/request/openai-to-vertex.js +36 -0
- package/src/translator/response/claude-to-openai.js +185 -0
- package/src/translator/response/commandcode-to-openai.js +164 -0
- package/src/translator/response/cursor-to-openai.js +18 -0
- package/src/translator/response/gemini-to-openai.js +127 -0
- package/src/translator/response/kiro-to-claude.js +230 -0
- package/src/translator/response/kiro-to-openai.js +136 -0
- package/src/translator/response/ollama-to-openai.js +106 -0
- package/src/translator/response/openai-responses.js +534 -0
- package/src/translator/response/openai-to-antigravity.js +107 -0
- package/src/translator/response/openai-to-claude.js +231 -0
- package/src/translator/schema/blocks.js +40 -0
- package/src/translator/schema/defaults.js +3 -0
- package/src/translator/schema/finishReasons.js +22 -0
- package/src/translator/schema/index.js +7 -0
- package/src/translator/schema/roles.js +12 -0
- package/src/transport/requestBoundary.ts +223 -0
- package/src/transport/routerAdmission.ts +380 -0
- package/src/types/provider.ts +59 -0
- package/src/utils/bypassHandler.js +272 -0
- package/src/utils/claudeCloaking.js +10 -0
- package/src/utils/claudeSignature.js +35 -0
- package/src/utils/clientDetector.js +183 -0
- package/src/utils/cursorChecksum.js +104 -0
- package/src/utils/cursorProtobuf.js +801 -0
- package/src/utils/debugLog.js +12 -0
- package/src/utils/error.js +120 -0
- package/src/utils/inflight.js +127 -0
- package/src/utils/kiroSessionReplay.js +139 -0
- package/src/utils/ollamaTransform.js +83 -0
- package/src/utils/proxyFetch.js +308 -0
- package/src/utils/reasoningContentInjector.js +71 -0
- package/src/utils/requestLogger.js +272 -0
- package/src/utils/responsesStreamHelpers.js +46 -0
- package/src/utils/sessionManager.js +205 -0
- package/src/utils/sse.js +13 -0
- package/src/utils/sseConstants.js +21 -0
- package/src/utils/stream.js +511 -0
- package/src/utils/streamHandler.js +256 -0
- package/src/utils/streamHelpers.js +113 -0
- package/src/utils/toolDeduper.js +44 -0
- package/src/utils/usageTracking.js +329 -0
- package/tsconfig.json +45 -0
|
@@ -0,0 +1,1155 @@
|
|
|
1
|
+
import { BaseExecutor } from "./base.js";
|
|
2
|
+
import { PROVIDERS } from "../config/providers.js";
|
|
3
|
+
import {
|
|
4
|
+
KIRO_CODEWHISPERER_TARGET,
|
|
5
|
+
KIRO_ENDPOINT_FALLBACK_STATUSES,
|
|
6
|
+
resolveKiroModel,
|
|
7
|
+
} from "../config/kiroConstants.js";
|
|
8
|
+
import { v4 as uuidv4 } from "uuid";
|
|
9
|
+
import { refreshKiroToken } from "../services/tokenRefresh.js";
|
|
10
|
+
import { SSE_DONE, SSE_HEADERS } from "../utils/sseConstants.js";
|
|
11
|
+
import { getCapabilitiesForModel } from "../providers/capabilities.js";
|
|
12
|
+
import { STREAM_FIRST_CHUNK_TIMEOUT_MS } from "../config/runtimeConfig.js";
|
|
13
|
+
|
|
14
|
+
const KIRO_REPAIR_BUFFER_MAX_BYTES = 8 * 1024 * 1024;
|
|
15
|
+
const KIRO_REPAIR_HEARTBEAT_MS = 10_000;
|
|
16
|
+
const KIRO_SHORT_FINAL_MAX_CHARS = 800;
|
|
17
|
+
const EVENTSTREAM_MAX_MESSAGE_BYTES = 24 * 1024 * 1024;
|
|
18
|
+
const EVENTSTREAM_MAX_HEADERS_BYTES = 128 * 1024;
|
|
19
|
+
const KIRO_EVENT_TYPES = new Set([
|
|
20
|
+
"assistantResponseEvent",
|
|
21
|
+
"reasoningContentEvent",
|
|
22
|
+
"codeEvent",
|
|
23
|
+
"toolUseEvent",
|
|
24
|
+
"messageStopEvent",
|
|
25
|
+
"metadataEvent",
|
|
26
|
+
"MetadataEvent",
|
|
27
|
+
"contextUsageEvent",
|
|
28
|
+
"meteringEvent",
|
|
29
|
+
"metricsEvent"
|
|
30
|
+
]);
|
|
31
|
+
const encoder = new TextEncoder();
|
|
32
|
+
const decoder = new TextDecoder();
|
|
33
|
+
const CRC32_TABLE = Uint32Array.from({ length: 256 }, (_, index) => {
|
|
34
|
+
let value = index;
|
|
35
|
+
for (let bit = 0; bit < 8; bit++) {
|
|
36
|
+
value = (value >>> 1) ^ ((value & 1) ? 0xedb88320 : 0);
|
|
37
|
+
}
|
|
38
|
+
return value >>> 0;
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const SHORT_FUTURE_ACTION = /^(?:(?:(?:現在|接著|接下來|下一步)[,,::\s]*(?:我(?:只)?(?:會|要|將|再)?\s*)?|我只再)(?:補|查|確認|驗證|追(?:查|蹤)?|繼續|檢查|測試)|我(?:會|要|將)(?:再|重新)?(?:補(?:齊|查)?|抓取|查(?:詢)?|確認|驗證|追(?:查|蹤)?|繼續|檢查|測試)|(?:(?:next|now|then)\b[\s,:-]*)?(?:i(?:'ll| will| am going to| need to)|let me)\s+(?:verify|check|confirm|validate|investigate|trace|continue|follow up|test)\b)/iu;
|
|
42
|
+
|
|
43
|
+
const OBSERVED_TRAILING_FUTURE_ACTION = /^目前證據顯示[\s\S]{1,700}[。.!?;;]\s*最後補查\s+504\s+access\s+log[,,]\s*確認\s+host[//]路徑與是否為集中流量[。.!]?$/iu;
|
|
44
|
+
const ENGLISH_FUTURE_ACTION = /^(?:(?:next|now|then)\b[\s,:-]*)?(?:i(?:'ll| will| am going to| need to)|let me)\s+(?:verify|check|confirm|validate|investigate|trace|continue|follow up|test)\b/iu;
|
|
45
|
+
const ENGLISH_RESULT_CLAUSE = /(?:[:;\n]|[.!?]\s+\S|\b(?:status|checksum|response|deployment)\s+(?:is|are|was|were|matches?|equals?|returned)\b)/iu;
|
|
46
|
+
const CHINESE_FUTURE_ACTION = /^(?:(?:現在|接著|接下來|下一步)[,,::\s]*(?:我(?:只)?(?:會|要|將|再)?\s*)?|我只再|我(?:會|要|將)(?:再|重新)?)(?:補|抓取|查|確認|驗證|追|繼續|檢查|測試)/u;
|
|
47
|
+
const CHINESE_RESULT_CLAUSE = /(?:[。!?]\s*\S|(?:版本|狀態|回應|結果|部署|校驗碼)(?:是|為|等於|顯示))/u;
|
|
48
|
+
const USER_WAIT = /(?:請(?:你|先)|你(?:先|需要|可以|提供|確認|批准|允許)|等待(?:你|使用者)|等你|核准|同意|授權|\b(?:after|when|once)\s+you\b|\byour\s+(?:approval|confirmation|permission|input)\b|\bwait(?:ing)?\s+for\s+you\b|\bplease\s+(?:approve|confirm|provide|send)\b)/iu;
|
|
49
|
+
const COMPLETED_FINAL = /(?:已(?:經)?完成|完成(?:了|驗證|確認)|修復完成|確認無誤|驗證(?:完成|通過)|測試(?:均)?通過|結論|總結|\b(?:done|completed|fixed|verified|confirmed|passed|in conclusion|summary)\b|\b(?:is|are) complete\b)/iu;
|
|
50
|
+
const RESULT_EVIDENCE = /(?:顯示|發現|因此|成功|失敗|正常|無錯誤|沒有錯誤|\b(?:found|shows?|showed|because|therefore|succeeded|failed|healthy|green|no errors?)\b)/iu;
|
|
51
|
+
|
|
52
|
+
function crc32(bytes) {
|
|
53
|
+
let crc = 0xffffffff;
|
|
54
|
+
for (const byte of bytes) crc = CRC32_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
|
|
55
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function envPositiveInt(name, fallback) {
|
|
59
|
+
const parsed = Number.parseInt(process.env?.[name] || "", 10);
|
|
60
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function concatChunks(chunks, totalBytes) {
|
|
64
|
+
const output = new Uint8Array(totalBytes);
|
|
65
|
+
let offset = 0;
|
|
66
|
+
for (const chunk of chunks) {
|
|
67
|
+
output.set(chunk, offset);
|
|
68
|
+
offset += chunk.byteLength;
|
|
69
|
+
}
|
|
70
|
+
return output;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function makeAbortError(reason) {
|
|
74
|
+
const error = new Error(reason?.message || reason || "Request aborted");
|
|
75
|
+
error.name = "AbortError";
|
|
76
|
+
return error;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function readWithTimeout(reader, signal, timeoutMs, message) {
|
|
80
|
+
if (signal?.aborted) throw makeAbortError(signal.reason);
|
|
81
|
+
let timeout;
|
|
82
|
+
let abortHandler;
|
|
83
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
84
|
+
timeout = setTimeout(() => reject(new Error(message)), timeoutMs);
|
|
85
|
+
});
|
|
86
|
+
const abortPromise = new Promise((_, reject) => {
|
|
87
|
+
abortHandler = () => reject(makeAbortError(signal.reason));
|
|
88
|
+
signal?.addEventListener("abort", abortHandler, { once: true });
|
|
89
|
+
});
|
|
90
|
+
try {
|
|
91
|
+
return await Promise.race([reader.read(), timeoutPromise, abortPromise]);
|
|
92
|
+
} finally {
|
|
93
|
+
clearTimeout(timeout);
|
|
94
|
+
signal?.removeEventListener?.("abort", abortHandler);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function readResponsePrefix(response, signal, maxBytes, timeoutMs) {
|
|
99
|
+
const reader = response?.body?.getReader?.();
|
|
100
|
+
if (!reader) return "";
|
|
101
|
+
const chunks = [];
|
|
102
|
+
let totalBytes = 0;
|
|
103
|
+
try {
|
|
104
|
+
while (totalBytes < maxBytes) {
|
|
105
|
+
const { done, value } = await readWithTimeout(
|
|
106
|
+
reader,
|
|
107
|
+
signal,
|
|
108
|
+
timeoutMs,
|
|
109
|
+
"Kiro retry error body stalled"
|
|
110
|
+
);
|
|
111
|
+
if (done) break;
|
|
112
|
+
const remaining = maxBytes - totalBytes;
|
|
113
|
+
const chunk = value.byteLength > remaining ? value.slice(0, remaining) : value;
|
|
114
|
+
chunks.push(chunk);
|
|
115
|
+
totalBytes += chunk.byteLength;
|
|
116
|
+
if (value.byteLength > remaining) break;
|
|
117
|
+
}
|
|
118
|
+
} finally {
|
|
119
|
+
await reader.cancel("bounded Kiro retry error body").catch(() => {});
|
|
120
|
+
}
|
|
121
|
+
return decoder.decode(concatChunks(chunks, totalBytes));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function normalizeStopReason(value) {
|
|
125
|
+
const reason = String(value || "").trim().replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase().replace(/[\s-]+/g, "_");
|
|
126
|
+
if (["endturn", "end_turn", "stop", "stop_sequence"].includes(reason)) return "end_turn";
|
|
127
|
+
if (["tooluse", "tool_use", "tool_calls"].includes(reason)) return "tool_use";
|
|
128
|
+
if (["maxtokens", "max_tokens", "max_output_tokens", "length"].includes(reason)) return "max_tokens";
|
|
129
|
+
return reason || null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function stopDisposition(stopReason, hasToolCalls) {
|
|
133
|
+
if (["malformed_model_output", "invalid_model_output"].includes(stopReason)) return "retryable_protocol_failure";
|
|
134
|
+
if (["cancelled", "pause_turn", "model_context_window_exceeded"].includes(stopReason)) return "terminal_incomplete";
|
|
135
|
+
if (stopReason === "refusal" || /(?:content.*filter|guardrail|safety|policy|blocked)/u.test(stopReason)) return "terminal_refusal";
|
|
136
|
+
if (stopReason === "max_tokens") return hasToolCalls ? "terminal_incomplete" : "length";
|
|
137
|
+
if (stopReason && !["end_turn", "tool_use"].includes(stopReason)) return "unknown_failure";
|
|
138
|
+
if (hasToolCalls || stopReason === "tool_use") return "tool_use";
|
|
139
|
+
if (!stopReason || stopReason === "end_turn") return "complete";
|
|
140
|
+
return "unknown_failure";
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function mergeStopReason(current, incoming) {
|
|
144
|
+
if (!incoming) return current;
|
|
145
|
+
if (!current) return incoming;
|
|
146
|
+
const severity = (reason) => {
|
|
147
|
+
const disposition = stopDisposition(reason, false);
|
|
148
|
+
if (disposition === "terminal_refusal") return 6;
|
|
149
|
+
if (disposition === "terminal_incomplete") return 5;
|
|
150
|
+
if (disposition === "unknown_failure") return 4;
|
|
151
|
+
if (disposition === "retryable_protocol_failure") return 3;
|
|
152
|
+
if (disposition === "length") return 2;
|
|
153
|
+
return 1;
|
|
154
|
+
};
|
|
155
|
+
return severity(incoming) > severity(current) ? incoming : current;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function isEllipsisOnly(value) {
|
|
159
|
+
return ["...", "…"].includes(String(value || "").trim());
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function isShortFutureAction(value) {
|
|
163
|
+
const text = String(value || "").trim().replaceAll("’", "'");
|
|
164
|
+
if (OBSERVED_TRAILING_FUTURE_ACTION.test(text)) return true;
|
|
165
|
+
if (ENGLISH_FUTURE_ACTION.test(text) && ENGLISH_RESULT_CLAUSE.test(text)) return false;
|
|
166
|
+
if (CHINESE_FUTURE_ACTION.test(text) && CHINESE_RESULT_CLAUSE.test(text)) return false;
|
|
167
|
+
return text.length > 0 && text.length <= KIRO_SHORT_FINAL_MAX_CHARS &&
|
|
168
|
+
SHORT_FUTURE_ACTION.test(text) && !USER_WAIT.test(text) &&
|
|
169
|
+
!COMPLETED_FINAL.test(text) && !RESULT_EVIDENCE.test(text);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function encodeSSEError(code, message, details) {
|
|
173
|
+
return encoder.encode(`data: ${JSON.stringify({ error: {
|
|
174
|
+
message,
|
|
175
|
+
type: "upstream_error",
|
|
176
|
+
code,
|
|
177
|
+
...(details ? { details } : {})
|
|
178
|
+
} })}\n\ndata: [DONE]\n\n`);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function inspectSSEChunk(chunk, state) {
|
|
182
|
+
for (const line of decoder.decode(chunk).split("\n")) {
|
|
183
|
+
if (!line.startsWith("data: ")) continue;
|
|
184
|
+
const data = line.slice(6).trim();
|
|
185
|
+
if (!data || data === "[DONE]") continue;
|
|
186
|
+
try {
|
|
187
|
+
const event = JSON.parse(data);
|
|
188
|
+
if (event.error) state.error = event.error;
|
|
189
|
+
for (const choice of event.choices || []) {
|
|
190
|
+
const delta = choice.delta || {};
|
|
191
|
+
if (typeof delta.content === "string") state.content += delta.content;
|
|
192
|
+
if (typeof delta.reasoning_content === "string") state.reasoning += delta.reasoning_content;
|
|
193
|
+
if (delta.tool_calls?.length) state.hasToolCalls = true;
|
|
194
|
+
}
|
|
195
|
+
} catch { }
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export class KiroExecutor extends BaseExecutor {
|
|
200
|
+
constructor() {
|
|
201
|
+
super("kiro", PROVIDERS.kiro);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
buildHeaders(credentials, stream = true, url = "") {
|
|
205
|
+
const headers = {
|
|
206
|
+
...this.config.headers,
|
|
207
|
+
"Amz-Sdk-Request": "attempt=1; max=3",
|
|
208
|
+
"Amz-Sdk-Invocation-Id": uuidv4()
|
|
209
|
+
};
|
|
210
|
+
if (url.includes("://codewhisperer.")) {
|
|
211
|
+
headers["X-Amz-Target"] = KIRO_CODEWHISPERER_TARGET;
|
|
212
|
+
} else {
|
|
213
|
+
delete headers["X-Amz-Target"];
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const authMethod = credentials?.providerSpecificData?.authMethod;
|
|
217
|
+
const isApiKey = authMethod === "api_key";
|
|
218
|
+
const isExternalIdp = authMethod === "external_idp";
|
|
219
|
+
|
|
220
|
+
const apiKey = credentials?.apiKey || (isApiKey ? credentials?.accessToken : null);
|
|
221
|
+
if (isApiKey && apiKey) {
|
|
222
|
+
headers["Authorization"] = `Bearer ${apiKey}`;
|
|
223
|
+
headers["TokenType"] = "API_KEY";
|
|
224
|
+
} else if (credentials?.accessToken) {
|
|
225
|
+
headers["Authorization"] = `Bearer ${credentials.accessToken}`;
|
|
226
|
+
if (isExternalIdp) {
|
|
227
|
+
headers["TokenType"] = "EXTERNAL_IDP";
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
return headers;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
getOrderedBaseUrls(credentials) {
|
|
235
|
+
const baseUrls = this.getBaseUrls();
|
|
236
|
+
const authMethod = credentials?.providerSpecificData?.authMethod;
|
|
237
|
+
|
|
238
|
+
const isCodeWhispererSurface =
|
|
239
|
+
authMethod === "api_key" || authMethod === "external_idp" || authMethod === "idc";
|
|
240
|
+
if (!isCodeWhispererSurface) return baseUrls;
|
|
241
|
+
|
|
242
|
+
const region = (credentials?.providerSpecificData?.region || "us-east-1").trim();
|
|
243
|
+
const regionalize = (u) =>
|
|
244
|
+
region && region !== "us-east-1" && u.includes("amazonaws.com")
|
|
245
|
+
? u.replace(/([a-z]+)\.[a-z0-9-]+\.amazonaws\.com/, `$1.${region}.amazonaws.com`)
|
|
246
|
+
: u;
|
|
247
|
+
|
|
248
|
+
const amazon = baseUrls.filter((u) => u.includes("amazonaws.com")).map(regionalize);
|
|
249
|
+
const others = baseUrls.filter((u) => !u.includes("amazonaws.com"));
|
|
250
|
+
if (authMethod === "api_key") {
|
|
251
|
+
const q = amazon.filter((u) => u.includes("://q."));
|
|
252
|
+
const remaining = amazon.filter((u) => !u.includes("://q."));
|
|
253
|
+
return q.length > 0
|
|
254
|
+
? [...q, ...remaining, ...others]
|
|
255
|
+
: [...amazon, ...others];
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
return amazon.length > 0 ? [...amazon, ...others] : baseUrls;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
buildUrl(model, stream, urlIndex = 0, credentials = null) {
|
|
262
|
+
const baseUrls = this.getOrderedBaseUrls(credentials);
|
|
263
|
+
return baseUrls[urlIndex] || baseUrls[0] || this.config.baseUrl;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
shouldRetry(status, urlIndex) {
|
|
267
|
+
const hasFallback = urlIndex + 1 < this.getFallbackCount();
|
|
268
|
+
return super.shouldRetry(status, urlIndex)
|
|
269
|
+
|| (hasFallback && KIRO_ENDPOINT_FALLBACK_STATUSES.has(status));
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
transformRequest(model, body, stream, credentials) {
|
|
273
|
+
return body;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async execute(args) {
|
|
277
|
+
const result = await super.execute(args);
|
|
278
|
+
if (result?.response?.ok) this.attachIntegrityGate(result, args);
|
|
279
|
+
return result;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
attachIntegrityGate(result, args) {
|
|
283
|
+
const abortController = new AbortController();
|
|
284
|
+
const maxBytes = envPositiveInt("KIRO_TOOL_CALL_REPAIR_BUFFER_MAX_BYTES", KIRO_REPAIR_BUFFER_MAX_BYTES);
|
|
285
|
+
const legacyTimeout = envPositiveInt("KIRO_TOOL_CALL_REPAIR_TIMEOUT_MS", STREAM_FIRST_CHUNK_TIMEOUT_MS);
|
|
286
|
+
const ttftTimeoutMs = envPositiveInt("KIRO_TOOL_CALL_REPAIR_TTFT_TIMEOUT_MS", legacyTimeout);
|
|
287
|
+
const stallTimeoutMs = envPositiveInt("KIRO_TOOL_CALL_REPAIR_STALL_TIMEOUT_MS", legacyTimeout);
|
|
288
|
+
const repairEnabled = args.credentials?.providerSpecificData?.kiroToolCallRepair !== false &&
|
|
289
|
+
process.env.KIRO_TOOL_CALL_REPAIR !== "false";
|
|
290
|
+
const forwardAbort = () => abortController.abort(args.signal?.reason);
|
|
291
|
+
args.signal?.addEventListener("abort", forwardAbort, { once: true });
|
|
292
|
+
let open = true;
|
|
293
|
+
let heartbeatTimer;
|
|
294
|
+
|
|
295
|
+
const stream = new ReadableStream({
|
|
296
|
+
start: async (controller) => {
|
|
297
|
+
const heartbeat = () => {
|
|
298
|
+
if (!open) return;
|
|
299
|
+
try {
|
|
300
|
+
controller.enqueue(encoder.encode(": kiro-validation\n\n"));
|
|
301
|
+
} catch {
|
|
302
|
+
open = false;
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
heartbeat();
|
|
306
|
+
heartbeatTimer = setInterval(heartbeat, KIRO_REPAIR_HEARTBEAT_MS);
|
|
307
|
+
|
|
308
|
+
try {
|
|
309
|
+
const bytes = await this.runIntegrityRecovery(result.response, args, {
|
|
310
|
+
signal: abortController.signal,
|
|
311
|
+
maxBytes,
|
|
312
|
+
ttftTimeoutMs,
|
|
313
|
+
stallTimeoutMs,
|
|
314
|
+
repairEnabled
|
|
315
|
+
});
|
|
316
|
+
if (abortController.signal.aborted) throw makeAbortError(abortController.signal.reason);
|
|
317
|
+
controller.enqueue(bytes);
|
|
318
|
+
controller.close();
|
|
319
|
+
} catch (error) {
|
|
320
|
+
if (open && error.name === "AbortError") {
|
|
321
|
+
controller.error(error);
|
|
322
|
+
} else if (open && error.name !== "AbortError") {
|
|
323
|
+
controller.enqueue(encodeSSEError(
|
|
324
|
+
"kiro_integrity_gate_failed",
|
|
325
|
+
error.message || "Kiro integrity validation failed"
|
|
326
|
+
));
|
|
327
|
+
controller.close();
|
|
328
|
+
}
|
|
329
|
+
} finally {
|
|
330
|
+
open = false;
|
|
331
|
+
clearInterval(heartbeatTimer);
|
|
332
|
+
args.signal?.removeEventListener?.("abort", forwardAbort);
|
|
333
|
+
}
|
|
334
|
+
},
|
|
335
|
+
cancel(reason) {
|
|
336
|
+
open = false;
|
|
337
|
+
clearInterval(heartbeatTimer);
|
|
338
|
+
abortController.abort(reason || "client cancelled");
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
result.response = new Response(stream, {
|
|
343
|
+
status: result.response.status,
|
|
344
|
+
statusText: result.response.statusText,
|
|
345
|
+
headers: { ...SSE_HEADERS }
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
async runIntegrityRecovery(rawResponse, args, options) {
|
|
350
|
+
const first = await this.readRecoverableIntegrityAttempt(
|
|
351
|
+
rawResponse,
|
|
352
|
+
args.model,
|
|
353
|
+
options,
|
|
354
|
+
"initial"
|
|
355
|
+
);
|
|
356
|
+
if (first.kind === "complete") return first.bytes;
|
|
357
|
+
if (first.kind === "terminal_stop" || first.kind === "upstream_error") {
|
|
358
|
+
return this.integrityFailureSSE(first);
|
|
359
|
+
}
|
|
360
|
+
if (first.kind === "invalid_tool" && !options.repairEnabled) {
|
|
361
|
+
return encodeSSEError("invalid_kiro_tool_call", first.message, first.diagnostics);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const repairBody = structuredClone(args.body || {});
|
|
365
|
+
|
|
366
|
+
const retry = await BaseExecutor.prototype.execute.call(this, {
|
|
367
|
+
...args,
|
|
368
|
+
body: repairBody,
|
|
369
|
+
signal: options.signal
|
|
370
|
+
});
|
|
371
|
+
if (!retry?.response?.ok) {
|
|
372
|
+
let body = "";
|
|
373
|
+
try {
|
|
374
|
+
body = await readResponsePrefix(
|
|
375
|
+
retry?.response,
|
|
376
|
+
options.signal,
|
|
377
|
+
Math.min(options.maxBytes, 4096),
|
|
378
|
+
options.stallTimeoutMs
|
|
379
|
+
);
|
|
380
|
+
} catch (error) {
|
|
381
|
+
if (error.name === "AbortError") throw error;
|
|
382
|
+
}
|
|
383
|
+
return encodeSSEError(
|
|
384
|
+
"kiro_integrity_retry_upstream_error",
|
|
385
|
+
body || `Kiro integrity retry failed with HTTP ${retry?.response?.status || 502}`,
|
|
386
|
+
{ status: retry?.response?.status || 502 }
|
|
387
|
+
);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const second = await this.readRecoverableIntegrityAttempt(
|
|
391
|
+
retry.response,
|
|
392
|
+
args.model,
|
|
393
|
+
options,
|
|
394
|
+
"retry"
|
|
395
|
+
);
|
|
396
|
+
if (second.kind === "complete") return second.bytes;
|
|
397
|
+
if (second.kind === "terminal_stop" || second.kind === "upstream_error") {
|
|
398
|
+
return this.integrityFailureSSE(second);
|
|
399
|
+
}
|
|
400
|
+
const code = second.kind === "ellipsis"
|
|
401
|
+
? "kiro_ellipsis_retry_failed"
|
|
402
|
+
: second.kind === "short_final"
|
|
403
|
+
? "kiro_short_final_retry_failed"
|
|
404
|
+
: second.kind === "invalid_tool"
|
|
405
|
+
? "kiro_tool_call_repair_retry_failed"
|
|
406
|
+
: "kiro_missing_terminal_retry_failed";
|
|
407
|
+
return encodeSSEError(
|
|
408
|
+
code,
|
|
409
|
+
`Kiro integrity validation failed after one bounded retry: ${second.message || second.kind}`,
|
|
410
|
+
{ attempts: [first.diagnostics, second.diagnostics].filter(Boolean) }
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
integrityFailureSSE(attempt) {
|
|
415
|
+
const disposition = attempt.diagnostics?.stop_disposition;
|
|
416
|
+
const code = attempt.diagnostics?.terminal_provenance === "integrity_buffer_exceeded"
|
|
417
|
+
? "kiro_integrity_buffer_exceeded"
|
|
418
|
+
: attempt.kind === "upstream_error"
|
|
419
|
+
? "kiro_upstream_eventstream_error"
|
|
420
|
+
: disposition === "terminal_refusal"
|
|
421
|
+
? "kiro_terminal_refusal"
|
|
422
|
+
: disposition === "terminal_incomplete"
|
|
423
|
+
? "kiro_terminal_incomplete"
|
|
424
|
+
: "kiro_unknown_stop_reason";
|
|
425
|
+
return encodeSSEError(code, attempt.message || "Kiro stream ended with a terminal failure", attempt.diagnostics);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
async readRecoverableIntegrityAttempt(rawResponse, model, options, attempt) {
|
|
429
|
+
try {
|
|
430
|
+
return await this.readIntegrityAttempt(rawResponse, model, options, attempt);
|
|
431
|
+
} catch (error) {
|
|
432
|
+
if (error.name === "AbortError") throw error;
|
|
433
|
+
return {
|
|
434
|
+
kind: "missing_terminal",
|
|
435
|
+
message: error.message || "Kiro transport read failed",
|
|
436
|
+
diagnostics: {
|
|
437
|
+
attempt,
|
|
438
|
+
terminal_provenance: "transport_read_error",
|
|
439
|
+
transport_state: "upstream_error",
|
|
440
|
+
stop_reason: null,
|
|
441
|
+
stop_disposition: "terminal_incomplete",
|
|
442
|
+
response_state: "no_semantic_output",
|
|
443
|
+
event_counts: {},
|
|
444
|
+
incomplete_frame_bytes: 0
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
async readIntegrityAttempt(rawResponse, model, options, attempt) {
|
|
451
|
+
let diagnostics;
|
|
452
|
+
const transformed = this.transformEventStreamToSSE(rawResponse, model, {
|
|
453
|
+
maxToolBytes: Math.max(1, Math.floor(options.maxBytes / 2)),
|
|
454
|
+
onTerminalState: (value) => {
|
|
455
|
+
diagnostics = value;
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
const reader = transformed.body.getReader();
|
|
459
|
+
const chunks = [];
|
|
460
|
+
let totalBytes = 0;
|
|
461
|
+
let sawChunk = false;
|
|
462
|
+
const output = { content: "", reasoning: "", hasToolCalls: false, error: null };
|
|
463
|
+
|
|
464
|
+
try {
|
|
465
|
+
while (true) {
|
|
466
|
+
const timeoutMs = sawChunk ? options.stallTimeoutMs : options.ttftTimeoutMs;
|
|
467
|
+
const phase = sawChunk ? "stalled" : "timed out before first chunk";
|
|
468
|
+
const { done, value } = await readWithTimeout(
|
|
469
|
+
reader,
|
|
470
|
+
options.signal,
|
|
471
|
+
timeoutMs,
|
|
472
|
+
`Kiro integrity validation ${phase}`
|
|
473
|
+
);
|
|
474
|
+
if (done) break;
|
|
475
|
+
sawChunk = true;
|
|
476
|
+
totalBytes += value.byteLength;
|
|
477
|
+
if (totalBytes > options.maxBytes) {
|
|
478
|
+
await reader.cancel("kiro_integrity_buffer_exceeded").catch(() => {});
|
|
479
|
+
return {
|
|
480
|
+
kind: "terminal_stop",
|
|
481
|
+
message: `Kiro integrity buffer exceeded ${options.maxBytes} bytes`,
|
|
482
|
+
diagnostics: { terminal_provenance: "integrity_buffer_exceeded" }
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
chunks.push(value);
|
|
486
|
+
inspectSSEChunk(value, output);
|
|
487
|
+
}
|
|
488
|
+
} catch (error) {
|
|
489
|
+
await reader.cancel(error.message).catch(() => {});
|
|
490
|
+
throw error;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
const safeDiagnostics = {
|
|
494
|
+
attempt,
|
|
495
|
+
terminal_provenance: diagnostics?.terminal_provenance || "missing_terminal_diagnostics",
|
|
496
|
+
transport_state: diagnostics?.transport_state || "unknown",
|
|
497
|
+
stop_reason: diagnostics?.stop_reason || null,
|
|
498
|
+
stop_disposition: diagnostics?.stop_disposition || "terminal_incomplete",
|
|
499
|
+
response_state: diagnostics?.response_state || "no_semantic_output",
|
|
500
|
+
event_counts: diagnostics?.event_counts || {},
|
|
501
|
+
incomplete_frame_bytes: diagnostics?.incomplete_frame_bytes || 0
|
|
502
|
+
};
|
|
503
|
+
if (safeDiagnostics.stop_disposition === "retryable_protocol_failure") {
|
|
504
|
+
const kind = safeDiagnostics.terminal_provenance === "invalid_tool_call"
|
|
505
|
+
? "invalid_tool"
|
|
506
|
+
: "retryable_stop";
|
|
507
|
+
return { kind, message: output.error?.message, diagnostics: safeDiagnostics };
|
|
508
|
+
}
|
|
509
|
+
if (safeDiagnostics.stop_disposition === "terminal_incomplete" ||
|
|
510
|
+
safeDiagnostics.stop_disposition === "terminal_refusal" ||
|
|
511
|
+
safeDiagnostics.stop_disposition === "unknown_failure") {
|
|
512
|
+
const kind = safeDiagnostics.terminal_provenance === "upstream_eventstream_error"
|
|
513
|
+
? "upstream_error"
|
|
514
|
+
: safeDiagnostics.terminal_provenance === "integrity_buffer_exceeded"
|
|
515
|
+
? "terminal_stop"
|
|
516
|
+
: ["metadata_stop_reason", "message_stop_event"].includes(safeDiagnostics.terminal_provenance)
|
|
517
|
+
? "terminal_stop"
|
|
518
|
+
: "missing_terminal";
|
|
519
|
+
return { kind, message: output.error?.message, diagnostics: safeDiagnostics };
|
|
520
|
+
}
|
|
521
|
+
if (output.error) {
|
|
522
|
+
return { kind: "missing_terminal", message: output.error.message, diagnostics: safeDiagnostics };
|
|
523
|
+
}
|
|
524
|
+
if (!output.hasToolCalls) {
|
|
525
|
+
if (isEllipsisOnly(output.content) ||
|
|
526
|
+
(!output.content.trim() && isEllipsisOnly(output.reasoning))) {
|
|
527
|
+
return { kind: "ellipsis", diagnostics: safeDiagnostics };
|
|
528
|
+
}
|
|
529
|
+
if (isShortFutureAction(output.content)) {
|
|
530
|
+
return { kind: "short_final", diagnostics: safeDiagnostics };
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
return { kind: "complete", bytes: concatChunks(chunks, totalBytes), diagnostics: safeDiagnostics };
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
transformEventStreamToSSE(response, model, options = {}) {
|
|
537
|
+
const responseId = `chatcmpl-${Date.now()}`;
|
|
538
|
+
const created = Math.floor(Date.now() / 1000);
|
|
539
|
+
const capabilityModel = resolveKiroModel(model).upstream;
|
|
540
|
+
const contextWindow = getCapabilitiesForModel("kiro", capabilityModel).contextWindow || 200000;
|
|
541
|
+
const eventCounts = {};
|
|
542
|
+
const state = {
|
|
543
|
+
buffer: new Uint8Array(0),
|
|
544
|
+
chunkIndex: 0,
|
|
545
|
+
toolCounter: 0,
|
|
546
|
+
tools: new Map(),
|
|
547
|
+
bufferedToolBytes: 0,
|
|
548
|
+
hasText: false,
|
|
549
|
+
hasReasoning: false,
|
|
550
|
+
hasCode: false,
|
|
551
|
+
hasToolCalls: false,
|
|
552
|
+
sawToolUse: false,
|
|
553
|
+
explicitStop: false,
|
|
554
|
+
stopReason: null,
|
|
555
|
+
terminalProvenance: null,
|
|
556
|
+
transportState: "consuming_response",
|
|
557
|
+
totalContentLength: 0,
|
|
558
|
+
contextUsagePercentage: 0,
|
|
559
|
+
hasContextUsage: false,
|
|
560
|
+
hasMetering: false,
|
|
561
|
+
usage: null,
|
|
562
|
+
inThinking: false,
|
|
563
|
+
toolValidationError: null,
|
|
564
|
+
validatedFrames: 0,
|
|
565
|
+
finished: false
|
|
566
|
+
};
|
|
567
|
+
|
|
568
|
+
const diagnostics = (overrides = {}) => ({
|
|
569
|
+
terminal_provenance: state.terminalProvenance || "clean_eventstream_eof",
|
|
570
|
+
transport_state: state.transportState,
|
|
571
|
+
stop_reason: state.stopReason,
|
|
572
|
+
stop_disposition: stopDisposition(state.stopReason, state.hasToolCalls),
|
|
573
|
+
response_state: state.hasToolCalls
|
|
574
|
+
? "valid_tool"
|
|
575
|
+
: state.hasText || state.hasReasoning || state.hasCode
|
|
576
|
+
? "text_reasoning"
|
|
577
|
+
: state.explicitStop
|
|
578
|
+
? "explicit_stop"
|
|
579
|
+
: "no_semantic_output",
|
|
580
|
+
event_counts: { ...eventCounts },
|
|
581
|
+
incomplete_frame_bytes: state.buffer.byteLength,
|
|
582
|
+
...overrides
|
|
583
|
+
});
|
|
584
|
+
const sseChunk = (delta, finishReason = null, usage) => encoder.encode(`data: ${JSON.stringify({
|
|
585
|
+
id: responseId,
|
|
586
|
+
object: "chat.completion.chunk",
|
|
587
|
+
created,
|
|
588
|
+
model,
|
|
589
|
+
choices: [{ index: 0, delta, finish_reason: finishReason }],
|
|
590
|
+
...(usage ? { usage } : {})
|
|
591
|
+
})}\n\n`);
|
|
592
|
+
const emitDelta = (controller, delta) => {
|
|
593
|
+
if (state.chunkIndex === 0) delta = { role: "assistant", ...delta };
|
|
594
|
+
state.chunkIndex++;
|
|
595
|
+
controller.enqueue(sseChunk(delta));
|
|
596
|
+
};
|
|
597
|
+
const fail = (controller, provenance, code, message, extra = {}) => {
|
|
598
|
+
state.finished = true;
|
|
599
|
+
state.terminalProvenance = provenance;
|
|
600
|
+
state.transportState = extra.transport_state || "corrupt_frame";
|
|
601
|
+
const detail = diagnostics({
|
|
602
|
+
stop_disposition: extra.stop_disposition || "terminal_incomplete",
|
|
603
|
+
...extra
|
|
604
|
+
});
|
|
605
|
+
options.onTerminalState?.(detail);
|
|
606
|
+
controller.enqueue(encodeSSEError(code, message, detail));
|
|
607
|
+
};
|
|
608
|
+
const assertToolBufferBound = () => {
|
|
609
|
+
if (state.bufferedToolBytes <= (options.maxToolBytes || KIRO_REPAIR_BUFFER_MAX_BYTES / 2)) return;
|
|
610
|
+
const error = new Error("Kiro buffered tool input exceeded the integrity memory bound");
|
|
611
|
+
error.code = "KIRO_BUFFER_EXCEEDED";
|
|
612
|
+
throw error;
|
|
613
|
+
};
|
|
614
|
+
const appendToolInput = (tool, input) => {
|
|
615
|
+
if (input === undefined) return;
|
|
616
|
+
if (typeof input === "string") {
|
|
617
|
+
if (tool.inputKind && tool.inputKind !== "string") throw new Error("Kiro tool input changed fragment type");
|
|
618
|
+
tool.inputKind = "string";
|
|
619
|
+
tool.inputChunks ||= [];
|
|
620
|
+
tool.inputChunks.push(input);
|
|
621
|
+
state.bufferedToolBytes += encoder.encode(input).byteLength;
|
|
622
|
+
} else if (input && typeof input === "object" && !Array.isArray(input)) {
|
|
623
|
+
if (tool.inputKind && tool.inputKind !== "object") throw new Error("Kiro tool input changed fragment type");
|
|
624
|
+
tool.inputKind = "object";
|
|
625
|
+
state.bufferedToolBytes -= tool.inputBytes || 0;
|
|
626
|
+
tool.inputObject = input;
|
|
627
|
+
tool.inputBytes = encoder.encode(JSON.stringify(input)).byteLength;
|
|
628
|
+
state.bufferedToolBytes += tool.inputBytes;
|
|
629
|
+
} else {
|
|
630
|
+
throw new Error("Kiro tool input must be a JSON object");
|
|
631
|
+
}
|
|
632
|
+
assertToolBufferBound();
|
|
633
|
+
};
|
|
634
|
+
const parsedToolInput = (tool) => {
|
|
635
|
+
if (!tool.inputKind) throw new Error("Kiro tool call is missing input");
|
|
636
|
+
if (tool.inputKind === "object") return tool.inputObject;
|
|
637
|
+
try {
|
|
638
|
+
const input = JSON.parse(tool.inputChunks.join(""));
|
|
639
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("not an object");
|
|
640
|
+
return input;
|
|
641
|
+
} catch (error) {
|
|
642
|
+
throw new Error(`Kiro tool input must be valid object JSON (${error.message})`);
|
|
643
|
+
}
|
|
644
|
+
};
|
|
645
|
+
const emitTools = (controller) => {
|
|
646
|
+
for (const tool of state.tools.values()) {
|
|
647
|
+
const input = parsedToolInput(tool);
|
|
648
|
+
if (tool.name === "tool_call") {
|
|
649
|
+
if (typeof input.name !== "string" || !input.name.trim()) {
|
|
650
|
+
throw new Error("Invalid Kiro tool_call payload: missing nested MCP tool name");
|
|
651
|
+
}
|
|
652
|
+
if (!Object.prototype.hasOwnProperty.call(input, "arguments")) {
|
|
653
|
+
throw new Error("Invalid Kiro tool_call payload: missing nested MCP tool arguments");
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
const index = state.toolCounter++;
|
|
657
|
+
emitDelta(controller, {
|
|
658
|
+
tool_calls: [{
|
|
659
|
+
index,
|
|
660
|
+
id: tool.id,
|
|
661
|
+
type: "function",
|
|
662
|
+
function: { name: tool.name, arguments: "" }
|
|
663
|
+
}]
|
|
664
|
+
});
|
|
665
|
+
emitDelta(controller, {
|
|
666
|
+
tool_calls: [{ index, function: { arguments: JSON.stringify(input) } }]
|
|
667
|
+
});
|
|
668
|
+
state.hasToolCalls = true;
|
|
669
|
+
}
|
|
670
|
+
state.tools.clear();
|
|
671
|
+
state.bufferedToolBytes = 0;
|
|
672
|
+
if (state.stopReason === "tool_use" && !state.hasToolCalls) {
|
|
673
|
+
throw new Error("Kiro tool_use stop reason did not include a complete tool call");
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
const processEvent = (event, controller) => {
|
|
677
|
+
const messageType = event.headers[":message-type"];
|
|
678
|
+
if (messageType === "error" || messageType === "exception") {
|
|
679
|
+
fail(
|
|
680
|
+
controller,
|
|
681
|
+
"upstream_eventstream_error",
|
|
682
|
+
"kiro_upstream_eventstream_error",
|
|
683
|
+
event.payload?.message || `Kiro upstream sent an EventStream ${messageType}`,
|
|
684
|
+
{ transport_state: "upstream_error" }
|
|
685
|
+
);
|
|
686
|
+
return false;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
const eventType = event.headers[":event-type"] || "";
|
|
690
|
+
const eventCountKey = KIRO_EVENT_TYPES.has(eventType) ? eventType : "other";
|
|
691
|
+
eventCounts[eventCountKey] = (eventCounts[eventCountKey] || 0) + 1;
|
|
692
|
+
if (eventType === "assistantResponseEvent" && typeof event.payload?.content === "string") {
|
|
693
|
+
let content = event.payload.content;
|
|
694
|
+
if (state.inThinking) {
|
|
695
|
+
const end = content.indexOf("</thinking>");
|
|
696
|
+
if (end < 0) content = "";
|
|
697
|
+
else {
|
|
698
|
+
state.inThinking = false;
|
|
699
|
+
content = content.slice(end + 11).replace(/^\n/u, "");
|
|
700
|
+
}
|
|
701
|
+
} else {
|
|
702
|
+
const start = content.indexOf("<thinking>");
|
|
703
|
+
if (start >= 0) {
|
|
704
|
+
const end = content.indexOf("</thinking>", start + 10);
|
|
705
|
+
if (end < 0) {
|
|
706
|
+
state.inThinking = true;
|
|
707
|
+
content = content.slice(0, start);
|
|
708
|
+
} else {
|
|
709
|
+
content = content.slice(0, start) + content.slice(end + 11).replace(/^\n/u, "");
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
if (content || !state.hasReasoning) {
|
|
714
|
+
state.hasText ||= content.length > 0;
|
|
715
|
+
state.totalContentLength += content.length;
|
|
716
|
+
emitDelta(controller, { content });
|
|
717
|
+
}
|
|
718
|
+
} else if (eventType === "reasoningContentEvent") {
|
|
719
|
+
const value = event.payload?.reasoningContentEvent || event.payload || {};
|
|
720
|
+
const content = typeof value === "string" ? value : value.text || value.content || "";
|
|
721
|
+
if (content) {
|
|
722
|
+
state.hasReasoning = true;
|
|
723
|
+
state.totalContentLength += content.length;
|
|
724
|
+
emitDelta(controller, { reasoning_content: content });
|
|
725
|
+
}
|
|
726
|
+
} else if (eventType === "codeEvent" && typeof event.payload?.content === "string") {
|
|
727
|
+
state.hasCode = true;
|
|
728
|
+
state.totalContentLength += event.payload.content.length;
|
|
729
|
+
emitDelta(controller, { content: event.payload.content });
|
|
730
|
+
} else if (eventType === "toolUseEvent") {
|
|
731
|
+
state.sawToolUse = true;
|
|
732
|
+
if (state.toolValidationError) return true;
|
|
733
|
+
const values = Array.isArray(event.payload) ? event.payload : [event.payload];
|
|
734
|
+
if (!values[0]) throw new Error("Kiro toolUseEvent is empty");
|
|
735
|
+
for (const value of values) {
|
|
736
|
+
const name = typeof value?.name === "string" ? value.name.trim() : "";
|
|
737
|
+
if (!name) throw new Error("Kiro toolUseEvent is missing a tool name");
|
|
738
|
+
let id;
|
|
739
|
+
if (value.toolUseId == null) {
|
|
740
|
+
id = `call_${created}_${state.tools.size + 1}`;
|
|
741
|
+
} else if (typeof value.toolUseId !== "string" || !value.toolUseId.trim()) {
|
|
742
|
+
throw new Error("Kiro toolUseEvent has an invalid toolUseId");
|
|
743
|
+
} else {
|
|
744
|
+
id = value.toolUseId;
|
|
745
|
+
}
|
|
746
|
+
let tool = state.tools.get(id);
|
|
747
|
+
if (!tool) {
|
|
748
|
+
tool = { id, name };
|
|
749
|
+
state.tools.set(id, tool);
|
|
750
|
+
state.bufferedToolBytes += encoder.encode(id).byteLength + encoder.encode(name).byteLength + 32;
|
|
751
|
+
assertToolBufferBound();
|
|
752
|
+
} else if (tool.name !== name) {
|
|
753
|
+
throw new Error("Kiro tool name changed between fragments");
|
|
754
|
+
}
|
|
755
|
+
appendToolInput(tool, value.input);
|
|
756
|
+
}
|
|
757
|
+
} else if (eventType === "messageStopEvent") {
|
|
758
|
+
state.explicitStop = true;
|
|
759
|
+
const reason = normalizeStopReason(
|
|
760
|
+
event.payload?.stopReason ?? event.payload?.stop_reason
|
|
761
|
+
) || (state.sawToolUse ? "tool_use" : "end_turn");
|
|
762
|
+
const merged = mergeStopReason(state.stopReason, reason);
|
|
763
|
+
if (merged !== state.stopReason) state.terminalProvenance = "message_stop_event";
|
|
764
|
+
state.stopReason = merged;
|
|
765
|
+
} else if (eventType === "metadataEvent" || eventType === "MetadataEvent") {
|
|
766
|
+
const metadata = event.payload?.metadataEvent || event.payload?.metadata || event.payload;
|
|
767
|
+
const reason = normalizeStopReason(metadata?.stopReason ?? metadata?.stop_reason);
|
|
768
|
+
if (reason) {
|
|
769
|
+
state.explicitStop = true;
|
|
770
|
+
const merged = mergeStopReason(state.stopReason, reason);
|
|
771
|
+
if (merged !== state.stopReason) state.terminalProvenance = "metadata_stop_reason";
|
|
772
|
+
state.stopReason = merged;
|
|
773
|
+
}
|
|
774
|
+
} else if (eventType === "contextUsageEvent") {
|
|
775
|
+
const percentage = Number(event.payload?.contextUsagePercentage);
|
|
776
|
+
if (Number.isFinite(percentage)) {
|
|
777
|
+
state.contextUsagePercentage = percentage;
|
|
778
|
+
state.hasContextUsage = true;
|
|
779
|
+
}
|
|
780
|
+
} else if (eventType === "meteringEvent") {
|
|
781
|
+
state.hasMetering = true;
|
|
782
|
+
const metering = event.payload?.meteringEvent || event.payload || {};
|
|
783
|
+
const credits = Number(metering.usage);
|
|
784
|
+
if (Number.isFinite(credits)) {
|
|
785
|
+
state.usage = {
|
|
786
|
+
...(state.usage || {}),
|
|
787
|
+
kiro_credits: credits,
|
|
788
|
+
kiro_credit_unit: typeof metering.unit === "string" ? metering.unit : "credit"
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
} else if (eventType === "metricsEvent") {
|
|
792
|
+
const metrics = event.payload?.metricsEvent || event.payload || {};
|
|
793
|
+
const prompt = Number(metrics.inputTokens) || 0;
|
|
794
|
+
const completion = Number(metrics.outputTokens) || 0;
|
|
795
|
+
if (prompt || completion) {
|
|
796
|
+
state.usage = {
|
|
797
|
+
...(state.usage || {}),
|
|
798
|
+
prompt_tokens: prompt,
|
|
799
|
+
completion_tokens: completion,
|
|
800
|
+
total_tokens: prompt + completion
|
|
801
|
+
};
|
|
802
|
+
const cacheRead = Number(metrics.cacheReadInputTokens || metrics.cache_read_input_tokens) || 0;
|
|
803
|
+
const cacheCreate = Number(metrics.cacheCreationInputTokens || metrics.cache_creation_input_tokens) || 0;
|
|
804
|
+
if (cacheRead) state.usage.cache_read_input_tokens = cacheRead;
|
|
805
|
+
if (cacheCreate) state.usage.cache_creation_input_tokens = cacheCreate;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
return true;
|
|
809
|
+
};
|
|
810
|
+
const processBytes = (chunk, controller) => {
|
|
811
|
+
const combinedLength = state.buffer.byteLength + chunk.byteLength;
|
|
812
|
+
if (combinedLength > (options.maxRawBytes || EVENTSTREAM_MAX_MESSAGE_BYTES)) {
|
|
813
|
+
fail(
|
|
814
|
+
controller,
|
|
815
|
+
"corrupt_eventstream_frame",
|
|
816
|
+
"kiro_missing_terminal",
|
|
817
|
+
"Kiro EventStream buffered bytes exceed the protocol bound"
|
|
818
|
+
);
|
|
819
|
+
return false;
|
|
820
|
+
}
|
|
821
|
+
if (state.buffer.byteLength === 0) {
|
|
822
|
+
state.buffer = chunk;
|
|
823
|
+
} else {
|
|
824
|
+
const joined = new Uint8Array(combinedLength);
|
|
825
|
+
joined.set(state.buffer);
|
|
826
|
+
joined.set(chunk, state.buffer.byteLength);
|
|
827
|
+
state.buffer = joined;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
while (state.buffer.byteLength >= 12) {
|
|
831
|
+
const view = new DataView(state.buffer.buffer, state.buffer.byteOffset);
|
|
832
|
+
if (view.getUint32(8, false) !== crc32(state.buffer.subarray(0, 8))) {
|
|
833
|
+
fail(controller, "corrupt_eventstream_frame", "kiro_missing_terminal", "Kiro EventStream prelude CRC mismatch");
|
|
834
|
+
return false;
|
|
835
|
+
}
|
|
836
|
+
const totalLength = view.getUint32(0, false);
|
|
837
|
+
const headersLength = view.getUint32(4, false);
|
|
838
|
+
if (totalLength < 16 || totalLength > EVENTSTREAM_MAX_MESSAGE_BYTES ||
|
|
839
|
+
headersLength > EVENTSTREAM_MAX_HEADERS_BYTES || headersLength > totalLength - 16) {
|
|
840
|
+
fail(controller, "corrupt_eventstream_frame", "kiro_missing_terminal", "Kiro EventStream frame bounds are invalid");
|
|
841
|
+
return false;
|
|
842
|
+
}
|
|
843
|
+
if (state.buffer.byteLength < totalLength) break;
|
|
844
|
+
const frame = state.buffer.slice(0, totalLength);
|
|
845
|
+
state.buffer = state.buffer.slice(totalLength);
|
|
846
|
+
let event;
|
|
847
|
+
try {
|
|
848
|
+
event = parseEventFrame(frame);
|
|
849
|
+
} catch (error) {
|
|
850
|
+
fail(controller, "corrupt_eventstream_frame", "kiro_missing_terminal", error.message);
|
|
851
|
+
return false;
|
|
852
|
+
}
|
|
853
|
+
state.transportState = "valid_complete_frame";
|
|
854
|
+
state.validatedFrames++;
|
|
855
|
+
try {
|
|
856
|
+
if (!processEvent(event, controller)) return false;
|
|
857
|
+
} catch (error) {
|
|
858
|
+
const bufferExceeded = error.code === "KIRO_BUFFER_EXCEEDED";
|
|
859
|
+
if (!bufferExceeded) {
|
|
860
|
+
state.toolValidationError ||= error.message;
|
|
861
|
+
state.tools.clear();
|
|
862
|
+
state.bufferedToolBytes = 0;
|
|
863
|
+
continue;
|
|
864
|
+
}
|
|
865
|
+
fail(
|
|
866
|
+
controller,
|
|
867
|
+
"integrity_buffer_exceeded",
|
|
868
|
+
"kiro_integrity_buffer_exceeded",
|
|
869
|
+
error.message,
|
|
870
|
+
{
|
|
871
|
+
transport_state: state.transportState,
|
|
872
|
+
stop_disposition: "terminal_incomplete"
|
|
873
|
+
}
|
|
874
|
+
);
|
|
875
|
+
return false;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
return true;
|
|
879
|
+
};
|
|
880
|
+
const finish = (controller) => {
|
|
881
|
+
if (state.finished) return;
|
|
882
|
+
if (state.buffer.byteLength) {
|
|
883
|
+
fail(
|
|
884
|
+
controller,
|
|
885
|
+
"incomplete_eventstream_frame",
|
|
886
|
+
"kiro_missing_terminal",
|
|
887
|
+
"Kiro EventStream ended with a truncated frame",
|
|
888
|
+
{ transport_state: "incomplete_frame" }
|
|
889
|
+
);
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
892
|
+
state.transportState = "clean_eof";
|
|
893
|
+
const declaredDisposition = stopDisposition(state.stopReason, state.sawToolUse);
|
|
894
|
+
if (["retryable_protocol_failure", "terminal_incomplete", "terminal_refusal", "unknown_failure"].includes(declaredDisposition)) {
|
|
895
|
+
const code = declaredDisposition === "retryable_protocol_failure"
|
|
896
|
+
? "kiro_retryable_protocol_failure"
|
|
897
|
+
: declaredDisposition === "terminal_refusal"
|
|
898
|
+
? "kiro_terminal_refusal"
|
|
899
|
+
: declaredDisposition === "terminal_incomplete"
|
|
900
|
+
? "kiro_terminal_incomplete"
|
|
901
|
+
: "kiro_unknown_stop_reason";
|
|
902
|
+
fail(
|
|
903
|
+
controller,
|
|
904
|
+
state.terminalProvenance || "metadata_stop_reason",
|
|
905
|
+
code,
|
|
906
|
+
`Kiro ended with non-success stop reason: ${state.stopReason}`,
|
|
907
|
+
{ transport_state: state.transportState, stop_disposition: declaredDisposition }
|
|
908
|
+
);
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
if (state.toolValidationError) {
|
|
912
|
+
fail(
|
|
913
|
+
controller,
|
|
914
|
+
"invalid_tool_call",
|
|
915
|
+
"invalid_kiro_tool_call",
|
|
916
|
+
state.toolValidationError,
|
|
917
|
+
{ transport_state: state.transportState, stop_disposition: "retryable_protocol_failure" }
|
|
918
|
+
);
|
|
919
|
+
return;
|
|
920
|
+
}
|
|
921
|
+
try {
|
|
922
|
+
emitTools(controller);
|
|
923
|
+
} catch (error) {
|
|
924
|
+
fail(
|
|
925
|
+
controller,
|
|
926
|
+
"invalid_tool_call",
|
|
927
|
+
"invalid_kiro_tool_call",
|
|
928
|
+
error.message,
|
|
929
|
+
{ transport_state: state.transportState, stop_disposition: "retryable_protocol_failure" }
|
|
930
|
+
);
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
const hasOutput = state.hasText || state.hasReasoning || state.hasCode || state.hasToolCalls;
|
|
935
|
+
if (!hasOutput && !state.explicitStop) {
|
|
936
|
+
fail(
|
|
937
|
+
controller,
|
|
938
|
+
"empty_response_eof",
|
|
939
|
+
"kiro_missing_terminal",
|
|
940
|
+
"Kiro EventStream ended without model output",
|
|
941
|
+
{ transport_state: state.transportState }
|
|
942
|
+
);
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
const disposition = stopDisposition(state.stopReason, state.hasToolCalls);
|
|
947
|
+
if (["retryable_protocol_failure", "terminal_incomplete", "terminal_refusal", "unknown_failure"].includes(disposition)) {
|
|
948
|
+
const code = disposition === "retryable_protocol_failure"
|
|
949
|
+
? "kiro_retryable_protocol_failure"
|
|
950
|
+
: disposition === "terminal_refusal"
|
|
951
|
+
? "kiro_terminal_refusal"
|
|
952
|
+
: disposition === "terminal_incomplete"
|
|
953
|
+
? "kiro_terminal_incomplete"
|
|
954
|
+
: "kiro_unknown_stop_reason";
|
|
955
|
+
fail(
|
|
956
|
+
controller,
|
|
957
|
+
state.terminalProvenance || "metadata_stop_reason",
|
|
958
|
+
code,
|
|
959
|
+
`Kiro ended with non-success stop reason: ${state.stopReason}`,
|
|
960
|
+
{ transport_state: state.transportState, stop_disposition: disposition }
|
|
961
|
+
);
|
|
962
|
+
return;
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
if (state.hasMetering && state.hasContextUsage && !state.usage?.total_tokens) {
|
|
966
|
+
const completion = state.totalContentLength
|
|
967
|
+
? Math.max(1, Math.floor(state.totalContentLength / 4))
|
|
968
|
+
: 0;
|
|
969
|
+
const prompt = Math.floor(state.contextUsagePercentage * contextWindow / 100);
|
|
970
|
+
state.usage = {
|
|
971
|
+
...(state.usage || {}),
|
|
972
|
+
prompt_tokens: prompt,
|
|
973
|
+
completion_tokens: completion,
|
|
974
|
+
total_tokens: prompt + completion
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
const finishReason = state.hasToolCalls
|
|
978
|
+
? "tool_calls"
|
|
979
|
+
: disposition === "length"
|
|
980
|
+
? "length"
|
|
981
|
+
: "stop";
|
|
982
|
+
controller.enqueue(sseChunk({}, finishReason, state.usage));
|
|
983
|
+
controller.enqueue(encoder.encode(SSE_DONE));
|
|
984
|
+
state.finished = true;
|
|
985
|
+
options.onTerminalState?.(diagnostics({
|
|
986
|
+
terminal_provenance: state.terminalProvenance || "clean_eventstream_eof",
|
|
987
|
+
transport_state: state.transportState,
|
|
988
|
+
stop_disposition: disposition
|
|
989
|
+
}));
|
|
990
|
+
};
|
|
991
|
+
|
|
992
|
+
if (!response.body) {
|
|
993
|
+
const detail = diagnostics({
|
|
994
|
+
terminal_provenance: "missing_response_body",
|
|
995
|
+
transport_state: "missing_body",
|
|
996
|
+
stop_disposition: "terminal_incomplete"
|
|
997
|
+
});
|
|
998
|
+
options.onTerminalState?.(detail);
|
|
999
|
+
return new Response(encodeSSEError(
|
|
1000
|
+
"kiro_missing_terminal",
|
|
1001
|
+
"Kiro response did not include an EventStream body",
|
|
1002
|
+
detail
|
|
1003
|
+
), { status: response.status, headers: { ...SSE_HEADERS } });
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
const reader = response.body.getReader();
|
|
1007
|
+
const stream = new ReadableStream({
|
|
1008
|
+
start: async (controller) => {
|
|
1009
|
+
try {
|
|
1010
|
+
while (!state.finished) {
|
|
1011
|
+
const { done, value } = await reader.read();
|
|
1012
|
+
if (done) break;
|
|
1013
|
+
const chunksBefore = state.chunkIndex;
|
|
1014
|
+
const framesBefore = state.validatedFrames;
|
|
1015
|
+
if (!processBytes(value, controller)) {
|
|
1016
|
+
await reader.cancel("invalid Kiro EventStream").catch(() => {});
|
|
1017
|
+
break;
|
|
1018
|
+
}
|
|
1019
|
+
if (state.validatedFrames > framesBefore && state.chunkIndex === chunksBefore) {
|
|
1020
|
+
controller.enqueue(encoder.encode(": kiro-upstream\n\n"));
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
finish(controller);
|
|
1024
|
+
controller.close();
|
|
1025
|
+
} catch (error) {
|
|
1026
|
+
if (!state.finished) {
|
|
1027
|
+
fail(
|
|
1028
|
+
controller,
|
|
1029
|
+
"upstream_read_error",
|
|
1030
|
+
"kiro_missing_terminal",
|
|
1031
|
+
error.message || "Kiro EventStream read failed",
|
|
1032
|
+
{ transport_state: "upstream_error" }
|
|
1033
|
+
);
|
|
1034
|
+
}
|
|
1035
|
+
controller.close();
|
|
1036
|
+
}
|
|
1037
|
+
},
|
|
1038
|
+
cancel(reason) {
|
|
1039
|
+
return reader.cancel(reason);
|
|
1040
|
+
}
|
|
1041
|
+
});
|
|
1042
|
+
return new Response(stream, {
|
|
1043
|
+
status: response.status,
|
|
1044
|
+
statusText: response.statusText,
|
|
1045
|
+
headers: { ...SSE_HEADERS }
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
async refreshCredentials(credentials, log, proxyOptions = null) {
|
|
1050
|
+
if (!credentials.refreshToken) return null;
|
|
1051
|
+
|
|
1052
|
+
try {
|
|
1053
|
+
|
|
1054
|
+
const result = await refreshKiroToken(
|
|
1055
|
+
credentials.refreshToken,
|
|
1056
|
+
credentials.providerSpecificData,
|
|
1057
|
+
log,
|
|
1058
|
+
proxyOptions
|
|
1059
|
+
);
|
|
1060
|
+
|
|
1061
|
+
return result;
|
|
1062
|
+
} catch (error) {
|
|
1063
|
+
log?.error?.("TOKEN", `Kiro refresh error: ${error.message}`);
|
|
1064
|
+
return null;
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
function parseEventFrame(data) {
|
|
1070
|
+
if (!(data instanceof Uint8Array) || data.byteLength < 16) {
|
|
1071
|
+
throw new Error("AWS EventStream frame is shorter than 16 bytes");
|
|
1072
|
+
}
|
|
1073
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
1074
|
+
const totalLength = view.getUint32(0, false);
|
|
1075
|
+
const headersLength = view.getUint32(4, false);
|
|
1076
|
+
if (totalLength !== data.byteLength) {
|
|
1077
|
+
throw new Error("AWS EventStream frame length does not match its prelude");
|
|
1078
|
+
}
|
|
1079
|
+
if (totalLength > EVENTSTREAM_MAX_MESSAGE_BYTES ||
|
|
1080
|
+
headersLength > EVENTSTREAM_MAX_HEADERS_BYTES ||
|
|
1081
|
+
headersLength > totalLength - 16) {
|
|
1082
|
+
throw new Error("AWS EventStream frame bounds are invalid");
|
|
1083
|
+
}
|
|
1084
|
+
if (view.getUint32(8, false) !== crc32(data.subarray(0, 8))) {
|
|
1085
|
+
throw new Error("AWS EventStream prelude CRC mismatch");
|
|
1086
|
+
}
|
|
1087
|
+
if (view.getUint32(totalLength - 4, false) !== crc32(data.subarray(0, totalLength - 4))) {
|
|
1088
|
+
throw new Error("AWS EventStream message CRC mismatch");
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
const headers = Object.create(null);
|
|
1092
|
+
const names = new Set();
|
|
1093
|
+
let offset = 12;
|
|
1094
|
+
const headerEnd = offset + headersLength;
|
|
1095
|
+
const requireBytes = (count) => {
|
|
1096
|
+
if (offset + count > headerEnd) {
|
|
1097
|
+
throw new Error("AWS EventStream header exceeds its declared bounds");
|
|
1098
|
+
}
|
|
1099
|
+
};
|
|
1100
|
+
|
|
1101
|
+
while (offset < headerEnd) {
|
|
1102
|
+
requireBytes(1);
|
|
1103
|
+
const nameLength = data[offset++];
|
|
1104
|
+
requireBytes(nameLength + 1);
|
|
1105
|
+
const name = decoder.decode(data.subarray(offset, offset + nameLength));
|
|
1106
|
+
offset += nameLength;
|
|
1107
|
+
if (names.has(name)) throw new Error(`AWS EventStream contains duplicate header: ${name}`);
|
|
1108
|
+
names.add(name);
|
|
1109
|
+
const type = data[offset++];
|
|
1110
|
+
|
|
1111
|
+
if (type === 0 || type === 1) {
|
|
1112
|
+
headers[name] = type === 0;
|
|
1113
|
+
} else if (type === 2) {
|
|
1114
|
+
requireBytes(1);
|
|
1115
|
+
headers[name] = view.getInt8(offset);
|
|
1116
|
+
offset += 1;
|
|
1117
|
+
} else if (type === 3) {
|
|
1118
|
+
requireBytes(2);
|
|
1119
|
+
headers[name] = view.getInt16(offset, false);
|
|
1120
|
+
offset += 2;
|
|
1121
|
+
} else if (type === 4) {
|
|
1122
|
+
requireBytes(4);
|
|
1123
|
+
headers[name] = view.getInt32(offset, false);
|
|
1124
|
+
offset += 4;
|
|
1125
|
+
} else if (type === 5 || type === 8) {
|
|
1126
|
+
requireBytes(8);
|
|
1127
|
+
offset += 8;
|
|
1128
|
+
} else if (type === 6 || type === 7) {
|
|
1129
|
+
requireBytes(2);
|
|
1130
|
+
const valueLength = view.getUint16(offset, false);
|
|
1131
|
+
offset += 2;
|
|
1132
|
+
requireBytes(valueLength);
|
|
1133
|
+
const bytes = data.subarray(offset, offset + valueLength);
|
|
1134
|
+
headers[name] = type === 7 ? decoder.decode(bytes) : bytes;
|
|
1135
|
+
offset += valueLength;
|
|
1136
|
+
} else if (type === 9) {
|
|
1137
|
+
requireBytes(16);
|
|
1138
|
+
offset += 16;
|
|
1139
|
+
} else {
|
|
1140
|
+
throw new Error(`AWS EventStream header ${name} has unknown type ${type}`);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
const payloadBytes = data.subarray(headerEnd, totalLength - 4);
|
|
1145
|
+
if (payloadBytes.byteLength === 0) return { headers, payload: null };
|
|
1146
|
+
const payloadText = decoder.decode(payloadBytes);
|
|
1147
|
+
if (!payloadText.trim()) return { headers, payload: null };
|
|
1148
|
+
try {
|
|
1149
|
+
return { headers, payload: JSON.parse(payloadText) };
|
|
1150
|
+
} catch (error) {
|
|
1151
|
+
throw new Error(`AWS EventStream payload is not valid JSON (${error.message})`);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
export default KiroExecutor;
|