wyxrouter 0.4.71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +222 -0
- package/LICENSE +21 -0
- package/README.md +96 -0
- package/README.zh-CN.md +1311 -0
- package/assets/pixel-router-2d.png +0 -0
- package/cli/LICENSE +42 -0
- package/cli/README.md +125 -0
- package/cli/app/package.json +58 -0
- package/cli/cli.js +806 -0
- package/cli/package.json +48 -0
- package/i18n/README.ja-JP.md +1209 -0
- package/i18n/README.ru.md +1311 -0
- package/i18n/README.vi.md +1310 -0
- package/i18n/README.zh-CN.md +1306 -0
- package/images/9router.png +0 -0
- package/jsconfig.json +12 -0
- package/next.config.mjs +71 -0
- package/open-sse/config/appConstants.js +203 -0
- package/open-sse/config/codexInstructions.js +119 -0
- package/open-sse/config/constants.js +4 -0
- package/open-sse/config/defaultThinkingSignature.js +12 -0
- package/open-sse/config/errorConfig.js +85 -0
- package/open-sse/config/googleTtsLanguages.js +62 -0
- package/open-sse/config/kiroConstants.js +322 -0
- package/open-sse/config/models.js +13 -0
- package/open-sse/config/ollamaModels.js +19 -0
- package/open-sse/config/providerModels.js +944 -0
- package/open-sse/config/providers.js +458 -0
- package/open-sse/config/runtimeConfig.js +72 -0
- package/open-sse/config/ttsModels.js +129 -0
- package/open-sse/executors/antigravity.js +504 -0
- package/open-sse/executors/azure.js +57 -0
- package/open-sse/executors/base.js +185 -0
- package/open-sse/executors/codex.js +469 -0
- package/open-sse/executors/commandcode.js +88 -0
- package/open-sse/executors/cursor.js +795 -0
- package/open-sse/executors/default.js +497 -0
- package/open-sse/executors/gemini-cli.js +89 -0
- package/open-sse/executors/github.js +379 -0
- package/open-sse/executors/grok-web.js +345 -0
- package/open-sse/executors/iflow.js +108 -0
- package/open-sse/executors/index.js +75 -0
- package/open-sse/executors/kiro.js +508 -0
- package/open-sse/executors/ollama-local.js +14 -0
- package/open-sse/executors/opencode-go.js +41 -0
- package/open-sse/executors/opencode.js +32 -0
- package/open-sse/executors/perplexity-web.js +507 -0
- package/open-sse/executors/qoder.js +450 -0
- package/open-sse/executors/qwen.js +129 -0
- package/open-sse/executors/vertex.js +131 -0
- package/open-sse/executors/xiaomi-tokenplan.js +19 -0
- package/open-sse/handlers/chatCore/nonStreamingHandler.js +230 -0
- package/open-sse/handlers/chatCore/requestDetail.js +102 -0
- package/open-sse/handlers/chatCore/sseToJsonHandler.js +231 -0
- package/open-sse/handlers/chatCore/streamingHandler.js +103 -0
- package/open-sse/handlers/chatCore.js +287 -0
- package/open-sse/handlers/embeddingProviders/_base.js +4 -0
- package/open-sse/handlers/embeddingProviders/gemini.js +54 -0
- package/open-sse/handlers/embeddingProviders/index.js +23 -0
- package/open-sse/handlers/embeddingProviders/openai.js +39 -0
- package/open-sse/handlers/embeddingProviders/openaiCompatNode.js +13 -0
- package/open-sse/handlers/embeddingsCore.js +126 -0
- package/open-sse/handlers/fetch/index.js +237 -0
- package/open-sse/handlers/imageGenerationCore.js +189 -0
- package/open-sse/handlers/imageProviders/_base.js +31 -0
- package/open-sse/handlers/imageProviders/blackForestLabs.js +43 -0
- package/open-sse/handlers/imageProviders/cloudflareAi.js +178 -0
- package/open-sse/handlers/imageProviders/codex.js +198 -0
- package/open-sse/handlers/imageProviders/comfyui.js +8 -0
- package/open-sse/handlers/imageProviders/falAi.js +41 -0
- package/open-sse/handlers/imageProviders/gemini.js +25 -0
- package/open-sse/handlers/imageProviders/huggingface.js +22 -0
- package/open-sse/handlers/imageProviders/index.js +40 -0
- package/open-sse/handlers/imageProviders/nanobanana.js +58 -0
- package/open-sse/handlers/imageProviders/openai.js +40 -0
- package/open-sse/handlers/imageProviders/runwayml.js +47 -0
- package/open-sse/handlers/imageProviders/sdwebui.js +17 -0
- package/open-sse/handlers/imageProviders/stabilityAi.js +34 -0
- package/open-sse/handlers/responsesHandler.js +103 -0
- package/open-sse/handlers/search/callers.js +371 -0
- package/open-sse/handlers/search/chatSearch.js +409 -0
- package/open-sse/handlers/search/index.js +201 -0
- package/open-sse/handlers/search/normalizers.js +223 -0
- package/open-sse/handlers/sttCore.js +194 -0
- package/open-sse/handlers/ttsCore.js +74 -0
- package/open-sse/handlers/ttsProviders/_base.js +39 -0
- package/open-sse/handlers/ttsProviders/edgeTts.js +89 -0
- package/open-sse/handlers/ttsProviders/elevenlabs.js +48 -0
- package/open-sse/handlers/ttsProviders/gemini.js +117 -0
- package/open-sse/handlers/ttsProviders/genericFormats.js +169 -0
- package/open-sse/handlers/ttsProviders/googleTts.js +54 -0
- package/open-sse/handlers/ttsProviders/index.js +50 -0
- package/open-sse/handlers/ttsProviders/localDevice.js +87 -0
- package/open-sse/handlers/ttsProviders/minimax.js +59 -0
- package/open-sse/handlers/ttsProviders/openai.js +30 -0
- package/open-sse/handlers/ttsProviders/openrouter.js +70 -0
- package/open-sse/index.js +82 -0
- package/open-sse/rtk/applyFilter.js +15 -0
- package/open-sse/rtk/autodetect.js +111 -0
- package/open-sse/rtk/caveman.js +100 -0
- package/open-sse/rtk/cavemanPrompts.js +78 -0
- package/open-sse/rtk/constants.js +55 -0
- package/open-sse/rtk/filters/buildOutput.js +127 -0
- package/open-sse/rtk/filters/dedupLog.js +44 -0
- package/open-sse/rtk/filters/find.js +49 -0
- package/open-sse/rtk/filters/gitDiff.js +92 -0
- package/open-sse/rtk/filters/gitStatus.js +117 -0
- package/open-sse/rtk/filters/grep.js +48 -0
- package/open-sse/rtk/filters/ls.js +79 -0
- package/open-sse/rtk/filters/readNumbered.js +27 -0
- package/open-sse/rtk/filters/searchList.js +52 -0
- package/open-sse/rtk/filters/smartTruncate.js +15 -0
- package/open-sse/rtk/filters/tree.js +32 -0
- package/open-sse/rtk/index.js +155 -0
- package/open-sse/rtk/registry.js +38 -0
- package/open-sse/services/accountFallback.js +238 -0
- package/open-sse/services/combo.js +198 -0
- package/open-sse/services/compact.js +71 -0
- package/open-sse/services/kiroModels.js +332 -0
- package/open-sse/services/model.js +261 -0
- package/open-sse/services/oauthCredentialManager.js +151 -0
- package/open-sse/services/projectId.js +306 -0
- package/open-sse/services/provider.js +356 -0
- package/open-sse/services/qoderModels.js +214 -0
- package/open-sse/services/tokenRefresh.js +939 -0
- package/open-sse/services/usage.js +1496 -0
- package/open-sse/transformer/responsesTransformer.js +439 -0
- package/open-sse/transformer/streamToJsonConverter.js +103 -0
- package/open-sse/translator/formats.js +36 -0
- package/open-sse/translator/helpers/claudeHelper.js +216 -0
- package/open-sse/translator/helpers/geminiHelper.js +372 -0
- package/open-sse/translator/helpers/imageHelper.js +34 -0
- package/open-sse/translator/helpers/maxTokensHelper.js +27 -0
- package/open-sse/translator/helpers/openaiHelper.js +130 -0
- package/open-sse/translator/helpers/responsesApiHelper.js +139 -0
- package/open-sse/translator/helpers/toolCallHelper.js +148 -0
- package/open-sse/translator/index.js +251 -0
- package/open-sse/translator/request/antigravity-to-openai.js +229 -0
- package/open-sse/translator/request/claude-to-openai.js +232 -0
- package/open-sse/translator/request/gemini-to-openai.js +147 -0
- package/open-sse/translator/request/openai-responses.js +318 -0
- package/open-sse/translator/request/openai-to-claude.js +401 -0
- package/open-sse/translator/request/openai-to-commandcode.js +170 -0
- package/open-sse/translator/request/openai-to-cursor.js +183 -0
- package/open-sse/translator/request/openai-to-gemini.js +470 -0
- package/open-sse/translator/request/openai-to-kiro.js +629 -0
- package/open-sse/translator/request/openai-to-kiro.old.js +278 -0
- package/open-sse/translator/request/openai-to-ollama.js +192 -0
- package/open-sse/translator/request/openai-to-vertex.js +42 -0
- package/open-sse/translator/response/claude-to-openai.js +206 -0
- package/open-sse/translator/response/commandcode-to-openai.js +197 -0
- package/open-sse/translator/response/cursor-to-openai.js +30 -0
- package/open-sse/translator/response/gemini-to-openai.js +245 -0
- package/open-sse/translator/response/kiro-to-openai.js +195 -0
- package/open-sse/translator/response/ollama-to-openai.js +152 -0
- package/open-sse/translator/response/openai-responses.js +590 -0
- package/open-sse/translator/response/openai-to-antigravity.js +122 -0
- package/open-sse/translator/response/openai-to-claude.js +266 -0
- package/open-sse/utils/bypassHandler.js +298 -0
- package/open-sse/utils/claudeCloaking.js +155 -0
- package/open-sse/utils/claudeHeaderCache.js +70 -0
- package/open-sse/utils/clientDetector.js +63 -0
- package/open-sse/utils/cursorChecksum.js +149 -0
- package/open-sse/utils/cursorProtobuf.js +904 -0
- package/open-sse/utils/debugLog.js +14 -0
- package/open-sse/utils/error.js +147 -0
- package/open-sse/utils/ollamaTransform.js +85 -0
- package/open-sse/utils/proxyFetch.js +368 -0
- package/open-sse/utils/reasoningContentInjector.js +79 -0
- package/open-sse/utils/requestLogger.js +260 -0
- package/open-sse/utils/responsesStreamHelpers.js +49 -0
- package/open-sse/utils/sessionManager.js +82 -0
- package/open-sse/utils/stream.js +462 -0
- package/open-sse/utils/streamHandler.js +250 -0
- package/open-sse/utils/streamHelpers.js +122 -0
- package/open-sse/utils/toolDeduper.js +49 -0
- package/open-sse/utils/usageTracking.js +347 -0
- package/package.json +100 -0
- package/postcss.config.mjs +12 -0
- package/public/favicon.svg +11 -0
- package/public/file.svg +1 -0
- package/public/globe.svg +1 -0
- package/public/i18n/literals/ar.json +195 -0
- package/public/i18n/literals/bn.json +195 -0
- package/public/i18n/literals/cs.json +195 -0
- package/public/i18n/literals/da.json +195 -0
- package/public/i18n/literals/de.json +195 -0
- package/public/i18n/literals/el.json +195 -0
- package/public/i18n/literals/es.json +195 -0
- package/public/i18n/literals/fi.json +195 -0
- package/public/i18n/literals/fr.json +195 -0
- package/public/i18n/literals/he.json +195 -0
- package/public/i18n/literals/hi.json +195 -0
- package/public/i18n/literals/hu.json +195 -0
- package/public/i18n/literals/id.json +195 -0
- package/public/i18n/literals/it.json +195 -0
- package/public/i18n/literals/ja.json +195 -0
- package/public/i18n/literals/ko.json +195 -0
- package/public/i18n/literals/nl.json +195 -0
- package/public/i18n/literals/no.json +195 -0
- package/public/i18n/literals/pl.json +195 -0
- package/public/i18n/literals/pt-BR.json +195 -0
- package/public/i18n/literals/pt-PT.json +195 -0
- package/public/i18n/literals/ro.json +195 -0
- package/public/i18n/literals/ru.json +195 -0
- package/public/i18n/literals/sv.json +195 -0
- package/public/i18n/literals/th.json +195 -0
- package/public/i18n/literals/tl.json +195 -0
- package/public/i18n/literals/tr.json +195 -0
- package/public/i18n/literals/uk.json +195 -0
- package/public/i18n/literals/ur.json +195 -0
- package/public/i18n/literals/vi.json +195 -0
- package/public/i18n/literals/zh-CN.json +772 -0
- package/public/i18n/literals/zh-TW.json +195 -0
- package/public/icons/discord.svg +4 -0
- package/public/icons/icon-192.svg +4 -0
- package/public/icons/icon-512.svg +4 -0
- package/public/next.svg +1 -0
- package/public/providers/alicode-intl.png +0 -0
- package/public/providers/alicode.png +0 -0
- package/public/providers/amp.png +0 -0
- package/public/providers/anthropic-m.png +0 -0
- package/public/providers/anthropic.png +0 -0
- package/public/providers/antigravity.png +0 -0
- package/public/providers/assemblyai.png +0 -0
- package/public/providers/aws-polly.png +0 -0
- package/public/providers/azure.png +0 -0
- package/public/providers/black-forest-labs.png +0 -0
- package/public/providers/blackbox.png +0 -0
- package/public/providers/brave-search.png +0 -0
- package/public/providers/byteplus.png +0 -0
- package/public/providers/cartesia.png +0 -0
- package/public/providers/cerebras.png +0 -0
- package/public/providers/chutes.png +0 -0
- package/public/providers/claude.png +0 -0
- package/public/providers/cline.png +0 -0
- package/public/providers/cloudflare-ai.png +0 -0
- package/public/providers/codebuddy.svg +37 -0
- package/public/providers/codex.png +0 -0
- package/public/providers/cohere.png +0 -0
- package/public/providers/comfyui.png +0 -0
- package/public/providers/commandcode.png +0 -0
- package/public/providers/continue.png +0 -0
- package/public/providers/copilot.png +0 -0
- package/public/providers/coqui.png +0 -0
- package/public/providers/cursor.png +0 -0
- package/public/providers/deepgram.png +0 -0
- package/public/providers/deepseek-tui.png +0 -0
- package/public/providers/deepseek.png +0 -0
- package/public/providers/droid.png +0 -0
- package/public/providers/edge-tts.png +0 -0
- package/public/providers/elevenlabs.png +0 -0
- package/public/providers/exa.png +0 -0
- package/public/providers/fal-ai.png +0 -0
- package/public/providers/firecrawl.png +0 -0
- package/public/providers/fireworks.png +0 -0
- package/public/providers/gemini-cli.png +0 -0
- package/public/providers/gemini.png +0 -0
- package/public/providers/github.png +0 -0
- package/public/providers/glm-cn.png +0 -0
- package/public/providers/glm.png +0 -0
- package/public/providers/google-pse.png +0 -0
- package/public/providers/google-tts.png +0 -0
- package/public/providers/grok-web.png +0 -0
- package/public/providers/groq.png +0 -0
- package/public/providers/hermes.png +0 -0
- package/public/providers/huggingface.png +0 -0
- package/public/providers/hyperbolic.png +0 -0
- package/public/providers/iflow.png +0 -0
- package/public/providers/inworld.png +0 -0
- package/public/providers/jcode.png +0 -0
- package/public/providers/jina-ai.png +0 -0
- package/public/providers/jina-reader.png +0 -0
- package/public/providers/kilocode.png +0 -0
- package/public/providers/kimi-coding.png +0 -0
- package/public/providers/kimi.png +0 -0
- package/public/providers/kiro.png +0 -0
- package/public/providers/linkup.png +0 -0
- package/public/providers/local-device.png +0 -0
- package/public/providers/minimax-cn.png +0 -0
- package/public/providers/minimax.png +0 -0
- package/public/providers/mistral.png +0 -0
- package/public/providers/nanobanana.png +0 -0
- package/public/providers/nebius.png +0 -0
- package/public/providers/nvidia.png +0 -0
- package/public/providers/oai-cc.png +0 -0
- package/public/providers/oai-r.png +0 -0
- package/public/providers/ollama-local.png +0 -0
- package/public/providers/ollama.png +0 -0
- package/public/providers/openai.png +0 -0
- package/public/providers/openclaw.png +0 -0
- package/public/providers/opencode-go.png +0 -0
- package/public/providers/opencode.png +0 -0
- package/public/providers/openrouter.png +0 -0
- package/public/providers/perplexity-web.png +0 -0
- package/public/providers/perplexity.png +0 -0
- package/public/providers/playht.png +0 -0
- package/public/providers/qoder.png +0 -0
- package/public/providers/qwen.png +0 -0
- package/public/providers/recraft.png +0 -0
- package/public/providers/roo.png +0 -0
- package/public/providers/runwayml.png +0 -0
- package/public/providers/sdwebui.png +0 -0
- package/public/providers/searchapi.png +0 -0
- package/public/providers/searxng.png +0 -0
- package/public/providers/serper.png +0 -0
- package/public/providers/siliconflow.png +0 -0
- package/public/providers/stability-ai.png +0 -0
- package/public/providers/tavily.png +0 -0
- package/public/providers/together.png +0 -0
- package/public/providers/topaz.png +0 -0
- package/public/providers/tortoise.png +0 -0
- package/public/providers/vertex-partner.png +0 -0
- package/public/providers/vertex.png +0 -0
- package/public/providers/volcengine-ark.png +0 -0
- package/public/providers/voyage-ai.png +0 -0
- package/public/providers/xai.png +0 -0
- package/public/providers/xiaomi-mimo.png +0 -0
- package/public/providers/xiaomi-tokenplan.png +0 -0
- package/public/providers/youcom.png +0 -0
- package/public/sw.js +22 -0
- package/public/vercel.svg +1 -0
- package/public/window.svg +1 -0
- package/scripts/compact-request-details.mjs +71 -0
- package/scripts/import-codex-gptjson.mjs +342 -0
- package/scripts/start-standalone.mjs +25 -0
- package/scripts/translate-readme.js +201 -0
- package/src/app/(dashboard)/dashboard/automation/page.js +294 -0
- package/src/app/(dashboard)/dashboard/basic-chat/BasicChatPageClient.js +967 -0
- package/src/app/(dashboard)/dashboard/basic-chat/page.js +5 -0
- package/src/app/(dashboard)/dashboard/cli-tools/CLIToolsPageClient.js +66 -0
- package/src/app/(dashboard)/dashboard/cli-tools/[toolId]/ToolDetailClient.js +173 -0
- package/src/app/(dashboard)/dashboard/cli-tools/[toolId]/page.js +11 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/AntigravityToolCard.js +481 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/ApiKeySelect.js +66 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/BaseUrlSelect.js +174 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/ClaudeToolCard.js +390 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/ClineToolCard.js +301 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/CodexToolCard.js +458 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/CopilotToolCard.js +323 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/CoworkToolCard.js +640 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/DeepSeekTuiToolCard.js +338 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/DefaultToolCard.js +271 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/DroidToolCard.js +410 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/EndpointPresetControl.js +128 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/HermesToolCard.js +317 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/JcodeToolCard.js +380 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/KiloToolCard.js +275 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/MitmLinkCard.js +40 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/MitmServerCard.js +329 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/MitmToolCard.js +318 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/OpenClawToolCard.js +388 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/OpenCodeToolCard.js +500 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/ToolSummaryCard.js +39 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/cliEndpointMatch.js +13 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/index.js +19 -0
- package/src/app/(dashboard)/dashboard/cli-tools/page.js +7 -0
- package/src/app/(dashboard)/dashboard/combos/page.js +612 -0
- package/src/app/(dashboard)/dashboard/console-log/ConsoleLogClient.js +91 -0
- package/src/app/(dashboard)/dashboard/console-log/page.js +8 -0
- package/src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.js +1555 -0
- package/src/app/(dashboard)/dashboard/endpoint/page.js +7 -0
- package/src/app/(dashboard)/dashboard/media-providers/[kind]/[id]/page.js +1903 -0
- package/src/app/(dashboard)/dashboard/media-providers/[kind]/page.js +289 -0
- package/src/app/(dashboard)/dashboard/media-providers/combo/[id]/page.js +410 -0
- package/src/app/(dashboard)/dashboard/media-providers/web/page.js +209 -0
- package/src/app/(dashboard)/dashboard/mitm/MitmPageClient.js +117 -0
- package/src/app/(dashboard)/dashboard/mitm/page.js +5 -0
- package/src/app/(dashboard)/dashboard/page.js +7 -0
- package/src/app/(dashboard)/dashboard/profile/page.js +1140 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/AddApiKeyModal.js +389 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/AddCustomModelModal.js +125 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/CompatibleModelsSection.js +250 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/ConnectionRow.js +299 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/CooldownTimer.js +42 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/EditCompatibleNodeModal.js +161 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/ModelRow.js +95 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/PassthroughModelsSection.js +183 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/page.js +2053 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/page.new.js +1724 -0
- package/src/app/(dashboard)/dashboard/providers/components/ConnectionsCard.js +497 -0
- package/src/app/(dashboard)/dashboard/providers/components/ModelAvailabilityBadge.js +185 -0
- package/src/app/(dashboard)/dashboard/providers/components/ModelsCard.js +294 -0
- package/src/app/(dashboard)/dashboard/providers/new/page.js +220 -0
- package/src/app/(dashboard)/dashboard/providers/page.js +1365 -0
- package/src/app/(dashboard)/dashboard/proxy-pools/page.js +1092 -0
- package/src/app/(dashboard)/dashboard/quota/page.js +11 -0
- package/src/app/(dashboard)/dashboard/skills/page.js +112 -0
- package/src/app/(dashboard)/dashboard/translator/page.js +303 -0
- package/src/app/(dashboard)/dashboard/usage/components/OverviewCards.js +35 -0
- package/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/ProviderLimitCard.js +185 -0
- package/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/QuotaProgressBar.js +127 -0
- package/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/QuotaTable.js +259 -0
- package/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.js +1394 -0
- package/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils.js +244 -0
- package/src/app/(dashboard)/dashboard/usage/components/ProviderTopology.js +327 -0
- package/src/app/(dashboard)/dashboard/usage/components/RequestDetailsTab.js +433 -0
- package/src/app/(dashboard)/dashboard/usage/components/UsageChart.js +141 -0
- package/src/app/(dashboard)/dashboard/usage/components/UsageTable.js +247 -0
- package/src/app/(dashboard)/dashboard/usage/page.js +75 -0
- package/src/app/(dashboard)/layout.js +6 -0
- package/src/app/api/auth/login/route.js +76 -0
- package/src/app/api/auth/logout/route.js +12 -0
- package/src/app/api/auth/oidc/callback/route.js +87 -0
- package/src/app/api/auth/oidc/start/route.js +52 -0
- package/src/app/api/auth/oidc/test/route.js +84 -0
- package/src/app/api/auth/status/route.js +45 -0
- package/src/app/api/cli-tools/all-statuses/route.js +46 -0
- package/src/app/api/cli-tools/antigravity-mitm/alias/route.js +53 -0
- package/src/app/api/cli-tools/antigravity-mitm/route.js +202 -0
- package/src/app/api/cli-tools/claude-settings/route.js +203 -0
- package/src/app/api/cli-tools/cline-settings/route.js +133 -0
- package/src/app/api/cli-tools/codex-gateway/accounts/route.js +16 -0
- package/src/app/api/cli-tools/codex-settings/route.js +239 -0
- package/src/app/api/cli-tools/copilot-settings/route.js +148 -0
- package/src/app/api/cli-tools/cowork-mcp-registry/route.js +77 -0
- package/src/app/api/cli-tools/cowork-mcp-tools/route.js +95 -0
- package/src/app/api/cli-tools/cowork-settings/route.js +412 -0
- package/src/app/api/cli-tools/deepseek-tui-settings/route.js +164 -0
- package/src/app/api/cli-tools/droid-settings/route.js +213 -0
- package/src/app/api/cli-tools/hermes-settings/route.js +175 -0
- package/src/app/api/cli-tools/jcode-settings/route.js +216 -0
- package/src/app/api/cli-tools/kilo-settings/route.js +131 -0
- package/src/app/api/cli-tools/openclaw-settings/route.js +292 -0
- package/src/app/api/cli-tools/opencode-settings/route.js +259 -0
- package/src/app/api/combos/[id]/route.js +81 -0
- package/src/app/api/combos/route.js +48 -0
- package/src/app/api/health/route.js +15 -0
- package/src/app/api/init/route.js +4 -0
- package/src/app/api/keys/[id]/route.js +58 -0
- package/src/app/api/keys/route.js +42 -0
- package/src/app/api/locale/route.js +30 -0
- package/src/app/api/mcp/[plugin]/message/route.js +21 -0
- package/src/app/api/mcp/[plugin]/sse/route.js +37 -0
- package/src/app/api/media-providers/tts/deepgram/voices/route.js +65 -0
- package/src/app/api/media-providers/tts/elevenlabs/voices/route.js +71 -0
- package/src/app/api/media-providers/tts/inworld/voices/route.js +61 -0
- package/src/app/api/media-providers/tts/minimax/voices/route.js +113 -0
- package/src/app/api/media-providers/tts/voices/route.js +99 -0
- package/src/app/api/models/alias/route.js +53 -0
- package/src/app/api/models/availability/route.js +103 -0
- package/src/app/api/models/custom/route.js +48 -0
- package/src/app/api/models/disabled/route.js +50 -0
- package/src/app/api/models/route.js +64 -0
- package/src/app/api/models/test/ping.js +191 -0
- package/src/app/api/models/test/route.js +14 -0
- package/src/app/api/oauth/[provider]/[action]/route.js +343 -0
- package/src/app/api/oauth/codebuddy/bulk-import/[jobId]/cancel/route.js +19 -0
- package/src/app/api/oauth/codebuddy/bulk-import/[jobId]/manual/[workerId]/route.js +30 -0
- package/src/app/api/oauth/codebuddy/bulk-import/[jobId]/route.js +23 -0
- package/src/app/api/oauth/codebuddy/bulk-import/latest/route.js +25 -0
- package/src/app/api/oauth/codebuddy/bulk-import/route.js +49 -0
- package/src/app/api/oauth/codebuddy/quota-cookie/route.js +133 -0
- package/src/app/api/oauth/codex/import-token/route.js +96 -0
- package/src/app/api/oauth/cursor/auto-import/route.js +258 -0
- package/src/app/api/oauth/cursor/import/route.js +100 -0
- package/src/app/api/oauth/gitlab/pat/route.js +62 -0
- package/src/app/api/oauth/iflow/cookie/route.js +137 -0
- package/src/app/api/oauth/kiro/auto-import/route.js +85 -0
- package/src/app/api/oauth/kiro/bulk-import/[jobId]/cancel/route.js +18 -0
- package/src/app/api/oauth/kiro/bulk-import/[jobId]/manual/[workerId]/route.js +29 -0
- package/src/app/api/oauth/kiro/bulk-import/[jobId]/route.js +22 -0
- package/src/app/api/oauth/kiro/bulk-import/latest/route.js +25 -0
- package/src/app/api/oauth/kiro/bulk-import/route.js +49 -0
- package/src/app/api/oauth/kiro/import/route.js +110 -0
- package/src/app/api/oauth/kiro/social-authorize/route.js +27 -0
- package/src/app/api/oauth/kiro/social-exchange/route.js +41 -0
- package/src/app/api/pricing/route.js +134 -0
- package/src/app/api/provider-nodes/[id]/route.js +101 -0
- package/src/app/api/provider-nodes/route.js +104 -0
- package/src/app/api/provider-nodes/validate/route.js +201 -0
- package/src/app/api/providers/[id]/models/route.js +526 -0
- package/src/app/api/providers/[id]/route.js +189 -0
- package/src/app/api/providers/[id]/test/route.js +23 -0
- package/src/app/api/providers/[id]/test/testUtils.js +714 -0
- package/src/app/api/providers/[id]/test-models/route.js +66 -0
- package/src/app/api/providers/client/route.js +126 -0
- package/src/app/api/providers/kilo/free-models/route.js +55 -0
- package/src/app/api/providers/route.js +206 -0
- package/src/app/api/providers/suggested-models/filters.js +20 -0
- package/src/app/api/providers/suggested-models/route.js +32 -0
- package/src/app/api/providers/test-batch/route.js +131 -0
- package/src/app/api/providers/validate/route.js +637 -0
- package/src/app/api/proxy-pools/[id]/route.js +123 -0
- package/src/app/api/proxy-pools/[id]/test/route.js +70 -0
- package/src/app/api/proxy-pools/cloudflare-deploy/route.js +145 -0
- package/src/app/api/proxy-pools/deno-deploy/route.js +175 -0
- package/src/app/api/proxy-pools/route.js +93 -0
- package/src/app/api/proxy-pools/vercel-deploy/route.js +142 -0
- package/src/app/api/settings/database/route.js +36 -0
- package/src/app/api/settings/proxy-test/route.js +23 -0
- package/src/app/api/settings/require-login/route.js +15 -0
- package/src/app/api/settings/route.js +100 -0
- package/src/app/api/shutdown/route.js +24 -0
- package/src/app/api/tags/route.js +18 -0
- package/src/app/api/translator/console-logs/route.js +24 -0
- package/src/app/api/translator/console-logs/stream/route.js +79 -0
- package/src/app/api/translator/load/route.js +45 -0
- package/src/app/api/translator/save/route.js +44 -0
- package/src/app/api/translator/send/route.js +94 -0
- package/src/app/api/translator/translate/route.js +90 -0
- package/src/app/api/tunnel/disable/route.js +12 -0
- package/src/app/api/tunnel/enable/route.js +16 -0
- package/src/app/api/tunnel/status/route.js +13 -0
- package/src/app/api/tunnel/tailscale-check/route.js +50 -0
- package/src/app/api/tunnel/tailscale-disable/route.js +12 -0
- package/src/app/api/tunnel/tailscale-enable/route.js +12 -0
- package/src/app/api/tunnel/tailscale-install/route.js +72 -0
- package/src/app/api/usage/[connectionId]/route.js +188 -0
- package/src/app/api/usage/chart/route.js +21 -0
- package/src/app/api/usage/history/route.js +12 -0
- package/src/app/api/usage/logs/route.js +12 -0
- package/src/app/api/usage/providers/route.js +42 -0
- package/src/app/api/usage/request-details/route.js +57 -0
- package/src/app/api/usage/request-logs/route.js +13 -0
- package/src/app/api/usage/stats/route.js +23 -0
- package/src/app/api/usage/stream/route.js +79 -0
- package/src/app/api/v1/api/chat/route.js +37 -0
- package/src/app/api/v1/audio/speech/route.js +16 -0
- package/src/app/api/v1/audio/transcriptions/route.js +19 -0
- package/src/app/api/v1/audio/voices/route.js +68 -0
- package/src/app/api/v1/chat/completions/route.js +35 -0
- package/src/app/api/v1/embeddings/route.js +21 -0
- package/src/app/api/v1/images/generations/route.js +16 -0
- package/src/app/api/v1/messages/count_tokens/route.js +52 -0
- package/src/app/api/v1/messages/route.js +36 -0
- package/src/app/api/v1/models/[kind]/route.js +55 -0
- package/src/app/api/v1/models/info/route.js +110 -0
- package/src/app/api/v1/models/route.js +451 -0
- package/src/app/api/v1/responses/compact/route.js +37 -0
- package/src/app/api/v1/responses/route.js +30 -0
- package/src/app/api/v1/route.js +1 -0
- package/src/app/api/v1/search/route.js +21 -0
- package/src/app/api/v1/web/fetch/route.js +21 -0
- package/src/app/api/v1beta/models/[...path]/route.js +328 -0
- package/src/app/api/v1beta/models/route.js +44 -0
- package/src/app/api/version/route.js +45 -0
- package/src/app/api/version/shutdown/route.js +15 -0
- package/src/app/api/version/update/route.js +21 -0
- package/src/app/callback/page.js +148 -0
- package/src/app/dashboard/settings/pricing/page.js +173 -0
- package/src/app/favicon.ico +0 -0
- package/src/app/globals.css +496 -0
- package/src/app/landing/components/AnimatedBackground.js +57 -0
- package/src/app/landing/components/Features.js +133 -0
- package/src/app/landing/components/FlowAnimation.js +175 -0
- package/src/app/landing/components/Footer.js +61 -0
- package/src/app/landing/components/GetStarted.js +97 -0
- package/src/app/landing/components/HeroSection.js +47 -0
- package/src/app/landing/components/HowItWorks.js +66 -0
- package/src/app/landing/components/Navigation.js +72 -0
- package/src/app/landing/page.js +106 -0
- package/src/app/layout.js +49 -0
- package/src/app/login/page.js +197 -0
- package/src/app/manifest.js +30 -0
- package/src/app/page.js +5 -0
- package/src/dashboardGuard.js +242 -0
- package/src/i18n/RuntimeI18nProvider.js +27 -0
- package/src/i18n/config.js +146 -0
- package/src/i18n/runtime.js +162 -0
- package/src/lib/appUpdater.js +200 -0
- package/src/lib/auth/dashboardSession.js +68 -0
- package/src/lib/auth/loginLimiter.js +52 -0
- package/src/lib/auth/oidc.js +234 -0
- package/src/lib/consoleLogBuffer.js +79 -0
- package/src/lib/dataDir.js +29 -0
- package/src/lib/db/adapters/betterSqliteAdapter.js +55 -0
- package/src/lib/db/adapters/bunSqliteAdapter.js +63 -0
- package/src/lib/db/adapters/nodeSqliteAdapter.js +84 -0
- package/src/lib/db/adapters/sqljsAdapter.js +115 -0
- package/src/lib/db/backup.js +35 -0
- package/src/lib/db/driver.js +85 -0
- package/src/lib/db/helpers/jsonCol.js +9 -0
- package/src/lib/db/helpers/kvStore.js +39 -0
- package/src/lib/db/helpers/metaStore.js +22 -0
- package/src/lib/db/index.js +171 -0
- package/src/lib/db/migrate.js +286 -0
- package/src/lib/db/migrations/001-initial.js +14 -0
- package/src/lib/db/migrations/index.js +10 -0
- package/src/lib/db/paths.js +18 -0
- package/src/lib/db/repos/aliasRepo.js +62 -0
- package/src/lib/db/repos/apiKeysRepo.js +75 -0
- package/src/lib/db/repos/combosRepo.js +73 -0
- package/src/lib/db/repos/connectionsRepo.js +226 -0
- package/src/lib/db/repos/disabledModelsRepo.js +56 -0
- package/src/lib/db/repos/nodesRepo.js +95 -0
- package/src/lib/db/repos/pricingRepo.js +108 -0
- package/src/lib/db/repos/proxyPoolsRepo.js +103 -0
- package/src/lib/db/repos/requestDetailsRepo.js +259 -0
- package/src/lib/db/repos/settingsRepo.js +104 -0
- package/src/lib/db/repos/usageRepo.js +731 -0
- package/src/lib/db/schema.js +157 -0
- package/src/lib/db/version.js +21 -0
- package/src/lib/disabledModelsDb.js +4 -0
- package/src/lib/localDb.js +21 -0
- package/src/lib/mcp/stdioSseBridge.js +198 -0
- package/src/lib/mitmAliasCache.js +46 -0
- package/src/lib/network/connectionProxy.js +160 -0
- package/src/lib/network/initOutboundProxy.js +25 -0
- package/src/lib/network/outboundProxy.js +68 -0
- package/src/lib/network/proxyTest.js +91 -0
- package/src/lib/oauth/constants/oauth.js +284 -0
- package/src/lib/oauth/constants/xai.js +61 -0
- package/src/lib/oauth/providers.js +1506 -0
- package/src/lib/oauth/services/antigravity.js +321 -0
- package/src/lib/oauth/services/claude.js +136 -0
- package/src/lib/oauth/services/codebuddyBulkImportManager.js +454 -0
- package/src/lib/oauth/services/codex.js +144 -0
- package/src/lib/oauth/services/cursor.js +179 -0
- package/src/lib/oauth/services/gemini.js +240 -0
- package/src/lib/oauth/services/github.js +225 -0
- package/src/lib/oauth/services/iflow.js +202 -0
- package/src/lib/oauth/services/index.js +17 -0
- package/src/lib/oauth/services/kiro.js +334 -0
- package/src/lib/oauth/services/kiroBulkImportManager.js +778 -0
- package/src/lib/oauth/services/kiroConnections.js +93 -0
- package/src/lib/oauth/services/kiroGoogleAutomation.js +1136 -0
- package/src/lib/oauth/services/oauth.js +157 -0
- package/src/lib/oauth/services/openai.js +123 -0
- package/src/lib/oauth/services/qoder.js +216 -0
- package/src/lib/oauth/services/qwen.js +170 -0
- package/src/lib/oauth/services/xai.js +238 -0
- package/src/lib/oauth/utils/banner.js +63 -0
- package/src/lib/oauth/utils/pkce.js +39 -0
- package/src/lib/oauth/utils/server.js +415 -0
- package/src/lib/oauth/utils/ui.js +48 -0
- package/src/lib/providerNormalization.js +45 -0
- package/src/lib/qoder/constants.js +64 -0
- package/src/lib/qoder/cosy.js +175 -0
- package/src/lib/qoder/encoding.js +55 -0
- package/src/lib/requestDetailsDb.js +4 -0
- package/src/lib/tunnel/cloudflare/cloudflared.js +449 -0
- package/src/lib/tunnel/cloudflare/config.js +9 -0
- package/src/lib/tunnel/cloudflare/healthCheck.js +29 -0
- package/src/lib/tunnel/cloudflare/manager.js +151 -0
- package/src/lib/tunnel/cloudflare/pid.js +23 -0
- package/src/lib/tunnel/index.js +48 -0
- package/src/lib/tunnel/shared/dnsResolver.js +17 -0
- package/src/lib/tunnel/shared/internetCheck.js +26 -0
- package/src/lib/tunnel/shared/state.js +41 -0
- package/src/lib/tunnel/shared/watchdogConfig.js +8 -0
- package/src/lib/tunnel/tailscale/config.js +7 -0
- package/src/lib/tunnel/tailscale/healthCheck.js +29 -0
- package/src/lib/tunnel/tailscale/manager.js +129 -0
- package/src/lib/tunnel/tailscale/tailscale.js +790 -0
- package/src/lib/updater/updater.js +235 -0
- package/src/lib/usage/fetcher.js +208 -0
- package/src/lib/usageDb.js +7 -0
- package/src/mitm/antigravityIdeVersion.js +50 -0
- package/src/mitm/cert/generate.js +32 -0
- package/src/mitm/cert/install.js +269 -0
- package/src/mitm/cert/rootCA.js +173 -0
- package/src/mitm/config.js +87 -0
- package/src/mitm/dbReader.js +22 -0
- package/src/mitm/dns/dnsConfig.js +266 -0
- package/src/mitm/handlers/antigravity.js +33 -0
- package/src/mitm/handlers/base.js +226 -0
- package/src/mitm/handlers/copilot.js +35 -0
- package/src/mitm/handlers/cursor.js +15 -0
- package/src/mitm/handlers/kiro.js +526 -0
- package/src/mitm/logger.js +106 -0
- package/src/mitm/manager.js +851 -0
- package/src/mitm/paths.js +32 -0
- package/src/mitm/server.js +435 -0
- package/src/mitm/winElevated.js +81 -0
- package/src/models/index.js +38 -0
- package/src/proxy.js +5 -0
- package/src/shared/components/AddCustomEmbeddingModal.js +183 -0
- package/src/shared/components/Avatar.js +88 -0
- package/src/shared/components/Badge.js +54 -0
- package/src/shared/components/BulkAccountAutomationModal.js +508 -0
- package/src/shared/components/Button.js +56 -0
- package/src/shared/components/Card.js +116 -0
- package/src/shared/components/ChangelogModal.js +97 -0
- package/src/shared/components/CodeBuddyQuotaCookieModal.js +109 -0
- package/src/shared/components/ComboFormModal.js +176 -0
- package/src/shared/components/CursorAuthModal.js +212 -0
- package/src/shared/components/DonateModal.js +136 -0
- package/src/shared/components/Drawer.js +82 -0
- package/src/shared/components/EditConnectionModal.js +286 -0
- package/src/shared/components/Footer.js +132 -0
- package/src/shared/components/GitLabAuthModal.js +194 -0
- package/src/shared/components/Header.js +380 -0
- package/src/shared/components/HeaderLanguage.js +46 -0
- package/src/shared/components/HeaderMenu.js +126 -0
- package/src/shared/components/IFlowCookieModal.js +132 -0
- package/src/shared/components/Input.js +65 -0
- package/src/shared/components/KiroAuthModal.js +1171 -0
- package/src/shared/components/KiroOAuthWrapper.js +149 -0
- package/src/shared/components/KiroSocialOAuthModal.js +205 -0
- package/src/shared/components/LanguageSwitcher.js +190 -0
- package/src/shared/components/Loading.js +75 -0
- package/src/shared/components/ManualConfigModal.js +44 -0
- package/src/shared/components/McpMarketplaceModal.js +255 -0
- package/src/shared/components/Modal.js +146 -0
- package/src/shared/components/ModelSelectModal.js +537 -0
- package/src/shared/components/NineRemoteButton.js +23 -0
- package/src/shared/components/NineRemotePromoModal.js +99 -0
- package/src/shared/components/NoAuthProxyCard.js +86 -0
- package/src/shared/components/OAuthModal.js +682 -0
- package/src/shared/components/Pagination.js +150 -0
- package/src/shared/components/PricingModal.js +208 -0
- package/src/shared/components/ProviderIcon.js +63 -0
- package/src/shared/components/ProviderInfoCard.js +82 -0
- package/src/shared/components/RequestLogger.js +121 -0
- package/src/shared/components/SegmentedControl.js +48 -0
- package/src/shared/components/Select.js +67 -0
- package/src/shared/components/Sidebar.js +441 -0
- package/src/shared/components/ThemeProvider.js +15 -0
- package/src/shared/components/ThemeToggle.js +42 -0
- package/src/shared/components/Toggle.js +69 -0
- package/src/shared/components/Tooltip.js +25 -0
- package/src/shared/components/UsageStats.js +505 -0
- package/src/shared/components/index.js +46 -0
- package/src/shared/components/layouts/AuthLayout.js +29 -0
- package/src/shared/components/layouts/DashboardLayout.js +104 -0
- package/src/shared/components/layouts/index.js +4 -0
- package/src/shared/constants/cliTools.js +397 -0
- package/src/shared/constants/colors.js +77 -0
- package/src/shared/constants/config.js +99 -0
- package/src/shared/constants/coworkPlugins.js +75 -0
- package/src/shared/constants/index.js +4 -0
- package/src/shared/constants/locales.js +36 -0
- package/src/shared/constants/mitmToolHosts.js +12 -0
- package/src/shared/constants/models.js +38 -0
- package/src/shared/constants/pricing.js +303 -0
- package/src/shared/constants/providers.js +289 -0
- package/src/shared/constants/skills.js +78 -0
- package/src/shared/constants/ttsProviders.js +138 -0
- package/src/shared/hooks/index.js +2 -0
- package/src/shared/hooks/useCopyToClipboard.js +43 -0
- package/src/shared/hooks/useTheme.js +60 -0
- package/src/shared/services/bootstrap.js +12 -0
- package/src/shared/services/initializeApp.js +268 -0
- package/src/shared/utils/api.js +93 -0
- package/src/shared/utils/apiKey.js +98 -0
- package/src/shared/utils/clineAuth.js +37 -0
- package/src/shared/utils/cn.js +11 -0
- package/src/shared/utils/connectionStatus.js +162 -0
- package/src/shared/utils/index.js +40 -0
- package/src/shared/utils/machine.js +6 -0
- package/src/shared/utils/machineId.js +66 -0
- package/src/shared/utils/providerModelsFetcher.js +30 -0
- package/src/sse/handlers/chat.js +261 -0
- package/src/sse/handlers/embeddings.js +141 -0
- package/src/sse/handlers/fetch.js +213 -0
- package/src/sse/handlers/imageGeneration.js +142 -0
- package/src/sse/handlers/search.js +206 -0
- package/src/sse/handlers/stt.js +88 -0
- package/src/sse/handlers/tts.js +114 -0
- package/src/sse/services/auth.js +346 -0
- package/src/sse/services/codexGateway.js +215 -0
- package/src/sse/services/model.js +99 -0
- package/src/sse/services/tokenRefresh.js +319 -0
- package/src/sse/utils/logger.js +75 -0
- package/src/store/headerSearchStore.js +19 -0
- package/src/store/index.js +6 -0
- package/src/store/notificationStore.js +45 -0
- package/src/store/providerStore.js +55 -0
- package/src/store/settingsStore.js +51 -0
- package/src/store/themeStore.js +54 -0
- package/src/store/userStore.js +20 -0
- package/start.sh +4 -0
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { convertResponsesStreamToJson } from "../../transformer/streamToJsonConverter.js";
|
|
2
|
+
import { createErrorResult } from "../../utils/error.js";
|
|
3
|
+
import { HTTP_STATUS } from "../../config/runtimeConfig.js";
|
|
4
|
+
import { FORMATS } from "../../translator/formats.js";
|
|
5
|
+
import { buildRequestDetail, extractRequestConfig, saveUsageStats } from "./requestDetail.js";
|
|
6
|
+
import { saveRequestDetail, appendRequestLog } from "@/lib/usageDb.js";
|
|
7
|
+
|
|
8
|
+
function textFromResponsesMessageItem(item) {
|
|
9
|
+
if (!item?.content || !Array.isArray(item.content)) return "";
|
|
10
|
+
const byType = item.content.find((c) => c.type === "output_text");
|
|
11
|
+
if (typeof byType?.text === "string") return byType.text;
|
|
12
|
+
const anyText = item.content.find((c) => typeof c.text === "string");
|
|
13
|
+
if (typeof anyText?.text === "string") return anyText.text;
|
|
14
|
+
return "";
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Codex / Responses API may emit many alternating reasoning + message items.
|
|
19
|
+
* Early message blocks often have empty output_text; the user-visible answer is usually in the last non-empty message.
|
|
20
|
+
*/
|
|
21
|
+
function pickAssistantMessageForChatCompletion(output) {
|
|
22
|
+
if (!Array.isArray(output)) return { msgItem: null, textContent: null };
|
|
23
|
+
const messages = output.filter((item) => item?.type === "message");
|
|
24
|
+
if (messages.length === 0) return { msgItem: null, textContent: null };
|
|
25
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
26
|
+
const text = textFromResponsesMessageItem(messages[i]);
|
|
27
|
+
if (text.length > 0) return { msgItem: messages[i], textContent: text };
|
|
28
|
+
}
|
|
29
|
+
const last = messages[messages.length - 1];
|
|
30
|
+
return { msgItem: last, textContent: textFromResponsesMessageItem(last) };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Parse OpenAI-style SSE text into a single chat completion JSON.
|
|
35
|
+
* Used when provider forces streaming but client wants non-streaming.
|
|
36
|
+
*/
|
|
37
|
+
export function parseSSEToOpenAIResponse(rawSSE, fallbackModel) {
|
|
38
|
+
const chunks = [];
|
|
39
|
+
|
|
40
|
+
for (const line of String(rawSSE || "").split("\n")) {
|
|
41
|
+
const trimmed = line.trim();
|
|
42
|
+
if (!trimmed.startsWith("data:")) continue;
|
|
43
|
+
const payload = trimmed.slice(5).trim();
|
|
44
|
+
if (!payload || payload === "[DONE]") continue;
|
|
45
|
+
try { chunks.push(JSON.parse(payload)); } catch { /* ignore malformed lines */ }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (chunks.length === 0) return null;
|
|
49
|
+
|
|
50
|
+
const first = chunks[0];
|
|
51
|
+
const contentParts = [];
|
|
52
|
+
const reasoningParts = [];
|
|
53
|
+
const toolCallMap = new Map(); // index -> { id, type, function: { name, arguments } }
|
|
54
|
+
let finishReason = "stop";
|
|
55
|
+
let usage = null;
|
|
56
|
+
|
|
57
|
+
for (const chunk of chunks) {
|
|
58
|
+
const choice = chunk?.choices?.[0];
|
|
59
|
+
const delta = choice?.delta || {};
|
|
60
|
+
if (typeof delta.content === "string" && delta.content.length > 0) contentParts.push(delta.content);
|
|
61
|
+
if (typeof delta.reasoning_content === "string" && delta.reasoning_content.length > 0) reasoningParts.push(delta.reasoning_content);
|
|
62
|
+
if (choice?.finish_reason) finishReason = choice.finish_reason;
|
|
63
|
+
if (chunk?.usage && typeof chunk.usage === "object") usage = chunk.usage;
|
|
64
|
+
|
|
65
|
+
// Accumulate tool_calls from streaming deltas
|
|
66
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
67
|
+
for (const tc of delta.tool_calls) {
|
|
68
|
+
const idx = tc.index ?? 0;
|
|
69
|
+
if (!toolCallMap.has(idx)) {
|
|
70
|
+
toolCallMap.set(idx, { id: tc.id || "", type: "function", function: { name: "", arguments: "" } });
|
|
71
|
+
}
|
|
72
|
+
const existing = toolCallMap.get(idx);
|
|
73
|
+
if (tc.id) existing.id = tc.id;
|
|
74
|
+
if (tc.function?.name) existing.function.name += tc.function.name;
|
|
75
|
+
if (tc.function?.arguments) existing.function.arguments += tc.function.arguments;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const message = { role: "assistant", content: contentParts.join("") || (toolCallMap.size > 0 ? null : "") };
|
|
81
|
+
if (reasoningParts.length > 0) message.reasoning_content = reasoningParts.join("");
|
|
82
|
+
if (toolCallMap.size > 0) {
|
|
83
|
+
message.tool_calls = [...toolCallMap.entries()].sort((a, b) => a[0] - b[0]).map(([, tc]) => tc);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const result = {
|
|
87
|
+
id: first.id || `chatcmpl-${Date.now()}`,
|
|
88
|
+
object: "chat.completion",
|
|
89
|
+
created: first.created || Math.floor(Date.now() / 1000),
|
|
90
|
+
model: first.model || fallbackModel || "unknown",
|
|
91
|
+
choices: [{ index: 0, message, finish_reason: finishReason }]
|
|
92
|
+
};
|
|
93
|
+
if (usage) result.usage = usage;
|
|
94
|
+
return result;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Handle case: provider forced streaming but client wants JSON.
|
|
99
|
+
* Supports both Codex/Responses API SSE and standard Chat Completions SSE.
|
|
100
|
+
*/
|
|
101
|
+
export async function handleForcedSSEToJson({ providerResponse, sourceFormat, provider, model, body, stream, translatedBody, finalBody, requestStartTime, connectionId, apiKey, clientRawRequest, onRequestSuccess, trackDone, appendLog }) {
|
|
102
|
+
const contentType = providerResponse.headers.get("content-type") || "";
|
|
103
|
+
const isSSE = contentType.includes("text/event-stream") || (contentType === "" && provider === "codex");
|
|
104
|
+
if (!isSSE) return null; // not handled here
|
|
105
|
+
|
|
106
|
+
trackDone();
|
|
107
|
+
|
|
108
|
+
const ctx = {
|
|
109
|
+
provider, model, connectionId,
|
|
110
|
+
request: extractRequestConfig(body, stream),
|
|
111
|
+
providerRequest: finalBody || translatedBody || null
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
// Codex/Responses API SSE path
|
|
115
|
+
const isCodexResponsesApi = provider === "codex" || sourceFormat === FORMATS.OPENAI_RESPONSES;
|
|
116
|
+
if (isCodexResponsesApi) {
|
|
117
|
+
try {
|
|
118
|
+
const jsonResponse = await convertResponsesStreamToJson(providerResponse.body);
|
|
119
|
+
if (onRequestSuccess) await onRequestSuccess();
|
|
120
|
+
|
|
121
|
+
const usage = jsonResponse.usage || {};
|
|
122
|
+
appendLog({ tokens: usage, status: "200 OK" });
|
|
123
|
+
saveUsageStats({ provider, model, tokens: usage, connectionId, apiKey, endpoint: clientRawRequest?.endpoint });
|
|
124
|
+
|
|
125
|
+
const { msgItem, textContent } = pickAssistantMessageForChatCompletion(jsonResponse.output);
|
|
126
|
+
const totalLatency = Date.now() - requestStartTime;
|
|
127
|
+
|
|
128
|
+
saveRequestDetail(buildRequestDetail({
|
|
129
|
+
...ctx,
|
|
130
|
+
latency: { ttft: totalLatency, total: totalLatency },
|
|
131
|
+
tokens: { prompt_tokens: usage.input_tokens || 0, completion_tokens: usage.output_tokens || 0 },
|
|
132
|
+
response: { content: textContent, thinking: null, finish_reason: jsonResponse.status || "unknown" },
|
|
133
|
+
status: "success"
|
|
134
|
+
}, { endpoint: clientRawRequest?.endpoint || null })).catch(() => {});
|
|
135
|
+
|
|
136
|
+
// Client is Responses API → return as-is
|
|
137
|
+
if (sourceFormat === FORMATS.OPENAI_RESPONSES) {
|
|
138
|
+
return { success: true, response: new Response(JSON.stringify(jsonResponse), { headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" } }) };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Build client-format response
|
|
142
|
+
const inTokens = usage.input_tokens || 0;
|
|
143
|
+
const outTokens = usage.output_tokens || 0;
|
|
144
|
+
let finalResp;
|
|
145
|
+
|
|
146
|
+
// Extract tool calls from Responses API output (function_call items)
|
|
147
|
+
const funcCallItems = (jsonResponse.output || []).filter(item => item.type === "function_call");
|
|
148
|
+
const toolCalls = funcCallItems.map((item, idx) => ({
|
|
149
|
+
id: item.call_id || `call_${item.name}_${Date.now()}_${idx}`,
|
|
150
|
+
type: "function",
|
|
151
|
+
function: {
|
|
152
|
+
name: item.name,
|
|
153
|
+
arguments: typeof item.arguments === "string" ? item.arguments : JSON.stringify(item.arguments || {})
|
|
154
|
+
}
|
|
155
|
+
}));
|
|
156
|
+
const hasToolCalls = toolCalls.length > 0;
|
|
157
|
+
|
|
158
|
+
if (sourceFormat === FORMATS.ANTIGRAVITY || sourceFormat === FORMATS.GEMINI || sourceFormat === FORMATS.GEMINI_CLI) {
|
|
159
|
+
finalResp = {
|
|
160
|
+
response: {
|
|
161
|
+
candidates: [{ content: { role: "model", parts: [{ text: textContent || "" }] }, finishReason: "STOP", index: 0 }],
|
|
162
|
+
usageMetadata: { promptTokenCount: inTokens, candidatesTokenCount: outTokens, totalTokenCount: inTokens + outTokens },
|
|
163
|
+
modelVersion: model,
|
|
164
|
+
responseId: jsonResponse.id || `resp_${Date.now()}`
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
} else {
|
|
168
|
+
const message = { role: "assistant", content: textContent || (hasToolCalls ? null : "") };
|
|
169
|
+
if (hasToolCalls) message.tool_calls = toolCalls;
|
|
170
|
+
const responseDone = jsonResponse.status === "completed" || jsonResponse.status === "done";
|
|
171
|
+
const finishReason = hasToolCalls ? "tool_calls" : (responseDone ? "stop" : (jsonResponse.status || "stop"));
|
|
172
|
+
finalResp = {
|
|
173
|
+
id: jsonResponse.id || `chatcmpl-${Date.now()}`,
|
|
174
|
+
object: "chat.completion",
|
|
175
|
+
created: jsonResponse.created_at || Math.floor(Date.now() / 1000),
|
|
176
|
+
model: jsonResponse.model || model,
|
|
177
|
+
choices: [{ index: 0, message, finish_reason: finishReason }],
|
|
178
|
+
usage: { prompt_tokens: inTokens, completion_tokens: outTokens, total_tokens: inTokens + outTokens }
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return { success: true, response: new Response(JSON.stringify(finalResp), { headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" } }) };
|
|
183
|
+
} catch (err) {
|
|
184
|
+
console.error("[ChatCore] Responses API SSE→JSON failed:", err);
|
|
185
|
+
return createErrorResult(HTTP_STATUS.BAD_GATEWAY, "Failed to convert streaming response to JSON");
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Standard Chat Completions SSE path
|
|
190
|
+
try {
|
|
191
|
+
const sseText = await providerResponse.text();
|
|
192
|
+
const parsed = parseSSEToOpenAIResponse(sseText, model);
|
|
193
|
+
if (!parsed) return createErrorResult(HTTP_STATUS.BAD_GATEWAY, "Invalid SSE response for non-streaming request");
|
|
194
|
+
|
|
195
|
+
if (onRequestSuccess) await onRequestSuccess();
|
|
196
|
+
|
|
197
|
+
const usage = parsed.usage || {};
|
|
198
|
+
appendLog({ tokens: usage, status: "200 OK" });
|
|
199
|
+
saveUsageStats({ provider, model, tokens: usage, connectionId, apiKey, endpoint: clientRawRequest?.endpoint });
|
|
200
|
+
|
|
201
|
+
const totalLatency = Date.now() - requestStartTime;
|
|
202
|
+
saveRequestDetail(buildRequestDetail({
|
|
203
|
+
...ctx,
|
|
204
|
+
latency: { ttft: totalLatency, total: totalLatency },
|
|
205
|
+
tokens: usage,
|
|
206
|
+
response: {
|
|
207
|
+
content: parsed.choices?.[0]?.message?.content || null,
|
|
208
|
+
thinking: parsed.choices?.[0]?.message?.reasoning_content || null,
|
|
209
|
+
finish_reason: parsed.choices?.[0]?.finish_reason || "unknown"
|
|
210
|
+
},
|
|
211
|
+
status: "success"
|
|
212
|
+
}, { endpoint: clientRawRequest?.endpoint || null })).catch(() => {});
|
|
213
|
+
|
|
214
|
+
// Strip reasoning_content only when content is non-empty.
|
|
215
|
+
// When content is empty (e.g. thinking models that used all tokens for reasoning),
|
|
216
|
+
// reasoning_content is the only useful output and must be preserved.
|
|
217
|
+
// Previously this was unconditional, which broke Qwen3.5, Claude extended thinking, etc.
|
|
218
|
+
if (parsed?.choices) {
|
|
219
|
+
for (const choice of parsed.choices) {
|
|
220
|
+
if (choice?.message?.reasoning_content && choice.message.content) {
|
|
221
|
+
delete choice.message.reasoning_content;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
return { success: true, response: new Response(JSON.stringify(parsed), { headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" } }) };
|
|
227
|
+
} catch (err) {
|
|
228
|
+
console.error("[ChatCore] Chat Completions SSE→JSON failed:", err);
|
|
229
|
+
return createErrorResult(HTTP_STATUS.BAD_GATEWAY, "Failed to convert streaming response to JSON");
|
|
230
|
+
}
|
|
231
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { FORMATS } from "../../translator/formats.js";
|
|
2
|
+
import { needsTranslation } from "../../translator/index.js";
|
|
3
|
+
import { createSSETransformStreamWithLogger, createPassthroughStreamWithLogger } from "../../utils/stream.js";
|
|
4
|
+
import { pipeWithDisconnect } from "../../utils/streamHandler.js";
|
|
5
|
+
import { buildAbortedResponsesTerminalBytes } from "../../utils/responsesStreamHelpers.js";
|
|
6
|
+
import { buildRequestDetail, extractRequestConfig, saveUsageStats } from "./requestDetail.js";
|
|
7
|
+
import { saveRequestDetail } from "@/lib/usageDb.js";
|
|
8
|
+
|
|
9
|
+
const SSE_HEADERS = {
|
|
10
|
+
"Content-Type": "text/event-stream",
|
|
11
|
+
"Cache-Control": "no-cache",
|
|
12
|
+
"Connection": "keep-alive",
|
|
13
|
+
"Access-Control-Allow-Origin": "*"
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Determine which SSE transform stream to use based on provider/format.
|
|
18
|
+
*/
|
|
19
|
+
function buildTransformStream({ provider, sourceFormat, targetFormat, userAgent, reqLogger, toolNameMap, model, connectionId, body, onStreamComplete, apiKey }) {
|
|
20
|
+
const isDroidCLI = userAgent?.toLowerCase().includes("droid") || userAgent?.toLowerCase().includes("codex-cli");
|
|
21
|
+
const needsCodexTranslation = provider === "codex" && targetFormat === FORMATS.OPENAI_RESPONSES && !isDroidCLI;
|
|
22
|
+
|
|
23
|
+
if (needsCodexTranslation) {
|
|
24
|
+
// Codex returns Responses API SSE → translate to client format
|
|
25
|
+
let codexTarget;
|
|
26
|
+
if (sourceFormat === FORMATS.OPENAI_RESPONSES) codexTarget = FORMATS.OPENAI_RESPONSES;
|
|
27
|
+
else if (sourceFormat === FORMATS.CLAUDE) codexTarget = FORMATS.CLAUDE;
|
|
28
|
+
else if (sourceFormat === FORMATS.ANTIGRAVITY || sourceFormat === FORMATS.GEMINI || sourceFormat === FORMATS.GEMINI_CLI) codexTarget = FORMATS.ANTIGRAVITY;
|
|
29
|
+
else codexTarget = FORMATS.OPENAI;
|
|
30
|
+
return createSSETransformStreamWithLogger(FORMATS.OPENAI_RESPONSES, codexTarget, provider, reqLogger, toolNameMap, model, connectionId, body, onStreamComplete, apiKey);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (needsTranslation(targetFormat, sourceFormat)) {
|
|
34
|
+
return createSSETransformStreamWithLogger(targetFormat, sourceFormat, provider, reqLogger, toolNameMap, model, connectionId, body, onStreamComplete, apiKey);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return createPassthroughStreamWithLogger(provider, reqLogger, model, connectionId, body, onStreamComplete, apiKey);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Handle streaming response — pipe provider SSE through transform stream to client.
|
|
42
|
+
*/
|
|
43
|
+
export function handleStreamingResponse({ providerResponse, provider, model, sourceFormat, targetFormat, userAgent, body, stream, translatedBody, finalBody, requestStartTime, connectionId, apiKey, clientRawRequest, onRequestSuccess, reqLogger, toolNameMap, streamController, onStreamComplete, streamDetailId }) {
|
|
44
|
+
if (onRequestSuccess) onRequestSuccess();
|
|
45
|
+
|
|
46
|
+
const transformStream = buildTransformStream({ provider, sourceFormat, targetFormat, userAgent, reqLogger, toolNameMap, model, connectionId, body, onStreamComplete, apiKey });
|
|
47
|
+
|
|
48
|
+
// Responses passthrough: synthesize response.failed + [DONE] if the stream aborts/stalls before a terminal event
|
|
49
|
+
const isResponsesPassthrough = sourceFormat === FORMATS.OPENAI_RESPONSES && targetFormat === FORMATS.OPENAI_RESPONSES;
|
|
50
|
+
const onAbortTerminal = isResponsesPassthrough ? buildAbortedResponsesTerminalBytes : null;
|
|
51
|
+
const transformedBody = pipeWithDisconnect(providerResponse, transformStream, streamController, onAbortTerminal);
|
|
52
|
+
|
|
53
|
+
saveRequestDetail(buildRequestDetail({
|
|
54
|
+
provider, model, connectionId,
|
|
55
|
+
latency: { ttft: 0, total: Date.now() - requestStartTime },
|
|
56
|
+
tokens: { prompt_tokens: 0, completion_tokens: 0 },
|
|
57
|
+
request: extractRequestConfig(body, stream),
|
|
58
|
+
providerRequest: finalBody || translatedBody || null,
|
|
59
|
+
providerResponse: "[Streaming - raw response not captured]",
|
|
60
|
+
response: { content: "[Streaming in progress...]", thinking: null, type: "streaming" },
|
|
61
|
+
status: "success"
|
|
62
|
+
}, { id: streamDetailId })).catch(err => {
|
|
63
|
+
console.error("[RequestDetail] Failed to save streaming request:", err.message);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
success: true,
|
|
68
|
+
response: new Response(transformedBody, { headers: SSE_HEADERS })
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Build onStreamComplete callback for streaming usage tracking.
|
|
74
|
+
*/
|
|
75
|
+
export function buildOnStreamComplete({ provider, model, connectionId, apiKey, requestStartTime, body, stream, finalBody, translatedBody, clientRawRequest }) {
|
|
76
|
+
const streamDetailId = `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
|
|
77
|
+
|
|
78
|
+
const onStreamComplete = (contentObj, usage, ttftAt) => {
|
|
79
|
+
const latency = {
|
|
80
|
+
ttft: ttftAt ? ttftAt - requestStartTime : Date.now() - requestStartTime,
|
|
81
|
+
total: Date.now() - requestStartTime
|
|
82
|
+
};
|
|
83
|
+
const safeContent = contentObj?.content || "[Empty streaming response]";
|
|
84
|
+
const safeThinking = contentObj?.thinking || null;
|
|
85
|
+
|
|
86
|
+
saveRequestDetail(buildRequestDetail({
|
|
87
|
+
provider, model, connectionId,
|
|
88
|
+
latency,
|
|
89
|
+
tokens: usage || { prompt_tokens: 0, completion_tokens: 0 },
|
|
90
|
+
request: extractRequestConfig(body, stream),
|
|
91
|
+
providerRequest: finalBody || translatedBody || null,
|
|
92
|
+
providerResponse: safeContent,
|
|
93
|
+
response: { content: safeContent, thinking: safeThinking, type: "streaming" },
|
|
94
|
+
status: "success"
|
|
95
|
+
}, { id: streamDetailId })).catch(err => {
|
|
96
|
+
console.error("[RequestDetail] Failed to update streaming content:", err.message);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
saveUsageStats({ provider, model, tokens: usage, connectionId, apiKey, endpoint: clientRawRequest?.endpoint, label: "STREAM USAGE" });
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
return { onStreamComplete, streamDetailId };
|
|
103
|
+
}
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { detectFormat, getTargetFormat } from "../services/provider.js";
|
|
2
|
+
import { translateRequest } from "../translator/index.js";
|
|
3
|
+
import { FORMATS } from "../translator/formats.js";
|
|
4
|
+
import { COLORS } from "../utils/stream.js";
|
|
5
|
+
import { createStreamController } from "../utils/streamHandler.js";
|
|
6
|
+
import { refreshWithRetry } from "../services/tokenRefresh.js";
|
|
7
|
+
import { createRequestLogger } from "../utils/requestLogger.js";
|
|
8
|
+
import { getModelTargetFormat, getModelStrip, getModelUpstreamId, getModelType, PROVIDER_ID_TO_ALIAS } from "../config/providerModels.js";
|
|
9
|
+
import { createErrorResult, parseUpstreamError, formatProviderError } from "../utils/error.js";
|
|
10
|
+
import { HTTP_STATUS } from "../config/runtimeConfig.js";
|
|
11
|
+
import { handleBypassRequest } from "../utils/bypassHandler.js";
|
|
12
|
+
import { trackPendingRequest, appendRequestLog, saveRequestDetail } from "@/lib/usageDb.js";
|
|
13
|
+
import { getExecutor } from "../executors/index.js";
|
|
14
|
+
import { buildRequestDetail, extractRequestConfig } from "./chatCore/requestDetail.js";
|
|
15
|
+
import { handleForcedSSEToJson } from "./chatCore/sseToJsonHandler.js";
|
|
16
|
+
import { handleNonStreamingResponse } from "./chatCore/nonStreamingHandler.js";
|
|
17
|
+
import { handleStreamingResponse, buildOnStreamComplete } from "./chatCore/streamingHandler.js";
|
|
18
|
+
import { detectClientTool, isNativePassthrough } from "../utils/clientDetector.js";
|
|
19
|
+
import { dedupeTools } from "../utils/toolDeduper.js";
|
|
20
|
+
import { injectCaveman } from "../rtk/caveman.js";
|
|
21
|
+
import { compressMessages, formatRtkLog } from "../rtk/index.js";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Core chat handler - shared between SSE and Worker
|
|
25
|
+
* @param {object} options.body - Request body
|
|
26
|
+
* @param {object} options.modelInfo - { provider, model }
|
|
27
|
+
* @param {object} options.credentials - Provider credentials
|
|
28
|
+
* @param {string} options.sourceFormatOverride - Override detected source format (e.g. "openai-responses")
|
|
29
|
+
*/
|
|
30
|
+
export async function handleChatCore({ body, modelInfo, credentials, log, onCredentialsRefreshed, onRequestSuccess, onDisconnect, clientRawRequest, connectionId, userAgent, apiKey, ccFilterNaming, rtkEnabled, cavemanEnabled, cavemanLevel, sourceFormatOverride, providerThinking }) {
|
|
31
|
+
const { provider, model } = modelInfo;
|
|
32
|
+
const requestStartTime = Date.now();
|
|
33
|
+
|
|
34
|
+
const sourceFormat = sourceFormatOverride || detectFormat(body);
|
|
35
|
+
|
|
36
|
+
// Check for bypass patterns (warmup, skip, cc naming)
|
|
37
|
+
const bypassResponse = handleBypassRequest(body, model, userAgent, ccFilterNaming);
|
|
38
|
+
if (bypassResponse) return bypassResponse;
|
|
39
|
+
|
|
40
|
+
const alias = PROVIDER_ID_TO_ALIAS[provider] || provider;
|
|
41
|
+
const modelTargetFormat = getModelTargetFormat(alias, model);
|
|
42
|
+
const targetFormat = modelTargetFormat || getTargetFormat(provider);
|
|
43
|
+
const stripList = getModelStrip(alias, model);
|
|
44
|
+
const upstreamModel = getModelUpstreamId(alias, model);
|
|
45
|
+
|
|
46
|
+
// Inject provider-level thinking config override (only if client hasn't set)
|
|
47
|
+
// on/off → extended type (body.thinking), none/low/medium/high → effort type (body.reasoning_effort)
|
|
48
|
+
if (providerThinking?.mode && providerThinking.mode !== "auto") {
|
|
49
|
+
const mode = providerThinking.mode;
|
|
50
|
+
if (mode === "on" && !body.thinking) {
|
|
51
|
+
console.log("Injecting provider-level thinking config override: on");
|
|
52
|
+
body = { ...body, thinking: { type: "enabled", budget_tokens: 10000 } };
|
|
53
|
+
} else if (mode === "off") {
|
|
54
|
+
body = { ...body, thinking: { type: "disabled" } };
|
|
55
|
+
delete body.reasoning_effort;
|
|
56
|
+
if (body.reasoning && typeof body.reasoning === "object") {
|
|
57
|
+
body.reasoning = { ...body.reasoning, effort: "none" };
|
|
58
|
+
}
|
|
59
|
+
} else if (!body.reasoning_effort) {
|
|
60
|
+
body = { ...body, reasoning_effort: mode };
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const clientRequestedStreaming = body.stream === true || sourceFormat === FORMATS.ANTIGRAVITY || sourceFormat === FORMATS.GEMINI || sourceFormat === FORMATS.GEMINI_CLI;
|
|
65
|
+
const providerRequiresStreaming = provider === "openai" || provider === "codex" || provider === "commandcode";
|
|
66
|
+
let stream = providerRequiresStreaming ? true : (body.stream !== false);
|
|
67
|
+
|
|
68
|
+
// DeepSeek-TUI: interactive TUI panel sends stream:true and needs SSE.
|
|
69
|
+
// Non-interactive mode (-p flag) sends without stream and can't parse SSE.
|
|
70
|
+
// Only force non-streaming when client didn't explicitly request it.
|
|
71
|
+
const detectedTool = detectClientTool(clientRawRequest?.headers || {}, body);
|
|
72
|
+
if (detectedTool === "deepseek-tui" && body.stream !== true) stream = false;
|
|
73
|
+
|
|
74
|
+
// Check client Accept header preference for non-streaming requests
|
|
75
|
+
// This fixes AI SDK compatibility where clients send Accept: application/json
|
|
76
|
+
const acceptHeader = clientRawRequest?.headers?.accept || "";
|
|
77
|
+
const clientPrefersJson = acceptHeader.includes("application/json");
|
|
78
|
+
const clientPrefersSSE = acceptHeader.includes("text/event-stream");
|
|
79
|
+
if (clientPrefersJson && !clientPrefersSSE && body.stream !== true) {
|
|
80
|
+
stream = false;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const reqLogger = await createRequestLogger(sourceFormat, targetFormat, model);
|
|
84
|
+
if (clientRawRequest) reqLogger.logClientRawRequest(clientRawRequest.endpoint, clientRawRequest.body, clientRawRequest.headers);
|
|
85
|
+
reqLogger.logRawRequest(body);
|
|
86
|
+
log?.debug?.("FORMAT", `${sourceFormat} → ${targetFormat} | stream=${stream}`);
|
|
87
|
+
|
|
88
|
+
// Native passthrough: CLI tool and provider are the same ecosystem
|
|
89
|
+
// Skip all translation/normalization — only model and Bearer are swapped
|
|
90
|
+
const clientTool = detectClientTool(clientRawRequest?.headers || {}, body);
|
|
91
|
+
const passthrough = isNativePassthrough(clientTool, provider);
|
|
92
|
+
|
|
93
|
+
let translatedBody;
|
|
94
|
+
let toolNameMap;
|
|
95
|
+
if (passthrough) {
|
|
96
|
+
log?.debug?.("PASSTHROUGH", `${clientTool} → ${provider} | native lossless`);
|
|
97
|
+
translatedBody = { ...body, model: upstreamModel };
|
|
98
|
+
} else {
|
|
99
|
+
translatedBody = translateRequest(sourceFormat, targetFormat, upstreamModel, body, stream, credentials, provider, reqLogger, stripList, connectionId, clientTool);
|
|
100
|
+
if (!translatedBody) {
|
|
101
|
+
trackPendingRequest(model, provider, connectionId, false, true);
|
|
102
|
+
return createErrorResult(HTTP_STATUS.BAD_REQUEST, `Failed to translate request for ${sourceFormat} → ${targetFormat}`);
|
|
103
|
+
}
|
|
104
|
+
toolNameMap = translatedBody._toolNameMap;
|
|
105
|
+
delete translatedBody._toolNameMap;
|
|
106
|
+
translatedBody.model = upstreamModel;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Dedupe duplicate built-in tools when equivalent MCP tools are present (Claude clients only).
|
|
110
|
+
if (clientTool === "claude" && Array.isArray(translatedBody.tools)) {
|
|
111
|
+
const { tools: deduped, stripped } = dedupeTools(translatedBody.tools);
|
|
112
|
+
if (stripped.length > 0) {
|
|
113
|
+
translatedBody.tools = deduped;
|
|
114
|
+
log?.debug?.("TOOLDEDUP", `stripped ${stripped.length}: ${stripped.slice(0, 3).join(", ")}${stripped.length > 3 ? "..." : ""}`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Token savers: applied at the final body just before dispatch
|
|
119
|
+
// Covers both passthrough (source shape) and translated (target shape) flows
|
|
120
|
+
const finalFormat = passthrough ? sourceFormat : targetFormat;
|
|
121
|
+
|
|
122
|
+
// TTS models don't support tool messages/function calling
|
|
123
|
+
if (getModelType(alias, model) === "tts" && translatedBody.messages) {
|
|
124
|
+
translatedBody.messages = translatedBody.messages.filter(msg => msg.role !== "tool");
|
|
125
|
+
delete translatedBody.tools;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// RTK: compress tool_result content
|
|
129
|
+
const rtkStats = compressMessages(translatedBody, rtkEnabled);
|
|
130
|
+
const rtkLine = formatRtkLog(rtkStats);
|
|
131
|
+
if (rtkLine) console.log(rtkLine);
|
|
132
|
+
|
|
133
|
+
// Caveman: inject terse-style system prompt
|
|
134
|
+
if (cavemanEnabled && cavemanLevel) {
|
|
135
|
+
injectCaveman(translatedBody, finalFormat, cavemanLevel);
|
|
136
|
+
log?.debug?.("CAVEMAN", `${cavemanLevel} | ${finalFormat}`);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const executor = getExecutor(provider);
|
|
140
|
+
trackPendingRequest(model, provider, connectionId, true);
|
|
141
|
+
appendRequestLog({ model, provider, connectionId, status: "PENDING" }).catch(() => { });
|
|
142
|
+
|
|
143
|
+
const msgCount = translatedBody.messages?.length || translatedBody.input?.length || translatedBody.contents?.length || translatedBody.request?.contents?.length || 0;
|
|
144
|
+
log?.debug?.("REQUEST", `${provider.toUpperCase()} | ${model} | ${msgCount} msgs`);
|
|
145
|
+
|
|
146
|
+
const streamController = createStreamController({
|
|
147
|
+
onDisconnect: (reason) => {
|
|
148
|
+
trackPendingRequest(model, provider, connectionId, false);
|
|
149
|
+
if (onDisconnect) onDisconnect(reason);
|
|
150
|
+
},
|
|
151
|
+
onError: () => trackPendingRequest(model, provider, connectionId, false),
|
|
152
|
+
log, provider, model
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
const proxyOptions = {
|
|
156
|
+
connectionProxyEnabled: credentials?.providerSpecificData?.connectionProxyEnabled === true,
|
|
157
|
+
connectionProxyUrl: credentials?.providerSpecificData?.connectionProxyUrl || "",
|
|
158
|
+
connectionNoProxy: credentials?.providerSpecificData?.connectionNoProxy || "",
|
|
159
|
+
vercelRelayUrl: credentials?.providerSpecificData?.vercelRelayUrl || "",
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
if (proxyOptions.vercelRelayUrl) {
|
|
163
|
+
const connectionName = credentials?.connectionName || credentials?.connectionId || "unknown";
|
|
164
|
+
const poolId = credentials?.providerSpecificData?.connectionProxyPoolId || "none";
|
|
165
|
+
log?.info?.("PROXY", `${provider.toUpperCase()} | ${model} | conn=${connectionName} | pool=${poolId} | vercel-relay=${proxyOptions.vercelRelayUrl}`);
|
|
166
|
+
} else if (proxyOptions.connectionProxyEnabled && proxyOptions.connectionProxyUrl) {
|
|
167
|
+
let maskedProxyUrl = proxyOptions.connectionProxyUrl;
|
|
168
|
+
try {
|
|
169
|
+
const parsed = new URL(proxyOptions.connectionProxyUrl);
|
|
170
|
+
const host = parsed.hostname || "";
|
|
171
|
+
const port = parsed.port ? `:${parsed.port}` : "";
|
|
172
|
+
const protocol = parsed.protocol || "http:";
|
|
173
|
+
maskedProxyUrl = `${protocol}//${host}${port}`;
|
|
174
|
+
} catch {
|
|
175
|
+
// Keep raw if URL parsing fails
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const poolId = credentials?.providerSpecificData?.connectionProxyPoolId || "none";
|
|
179
|
+
const connectionName = credentials?.connectionName || credentials?.connectionId || "unknown";
|
|
180
|
+
log?.info?.("PROXY", `${provider.toUpperCase()} | ${model} | conn=${connectionName} | pool=${poolId} | url=${maskedProxyUrl}`);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if (proxyOptions.connectionProxyEnabled && proxyOptions.connectionNoProxy) {
|
|
184
|
+
const connectionName = credentials?.connectionName || credentials?.connectionId || "unknown";
|
|
185
|
+
log?.debug?.("PROXY", `${provider.toUpperCase()} | ${model} | conn=${connectionName} | no_proxy=${proxyOptions.connectionNoProxy}`);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Execute request
|
|
189
|
+
let providerResponse, providerUrl, providerHeaders, finalBody;
|
|
190
|
+
try {
|
|
191
|
+
const result = await executor.execute({ model, body: translatedBody, stream, credentials, signal: streamController.signal, log, proxyOptions });
|
|
192
|
+
providerResponse = result.response;
|
|
193
|
+
providerUrl = result.url;
|
|
194
|
+
providerHeaders = result.headers;
|
|
195
|
+
finalBody = result.transformedBody;
|
|
196
|
+
reqLogger.logTargetRequest(providerUrl, providerHeaders, finalBody);
|
|
197
|
+
} catch (error) {
|
|
198
|
+
trackPendingRequest(model, provider, connectionId, false, true);
|
|
199
|
+
appendRequestLog({ model, provider, connectionId, status: `FAILED ${error.name === "AbortError" ? 499 : HTTP_STATUS.BAD_GATEWAY}` }).catch(() => { });
|
|
200
|
+
saveRequestDetail(buildRequestDetail({
|
|
201
|
+
provider, model, connectionId,
|
|
202
|
+
latency: { ttft: 0, total: Date.now() - requestStartTime },
|
|
203
|
+
tokens: { prompt_tokens: 0, completion_tokens: 0 },
|
|
204
|
+
request: extractRequestConfig(body, stream),
|
|
205
|
+
providerRequest: translatedBody || null,
|
|
206
|
+
response: { error: error.message || String(error), status: error.name === "AbortError" ? 499 : 502, thinking: null },
|
|
207
|
+
status: "error"
|
|
208
|
+
})).catch(() => { });
|
|
209
|
+
|
|
210
|
+
if (error.name === "AbortError") {
|
|
211
|
+
streamController.handleError(error);
|
|
212
|
+
return createErrorResult(499, "Request aborted");
|
|
213
|
+
}
|
|
214
|
+
const errMsg = formatProviderError(error, provider, model, HTTP_STATUS.BAD_GATEWAY);
|
|
215
|
+
console.log(`${COLORS.red}[ERROR] ${errMsg}${COLORS.reset}`);
|
|
216
|
+
return createErrorResult(HTTP_STATUS.BAD_GATEWAY, errMsg);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Handle 401/403 - try token refresh (skip for noAuth providers)
|
|
220
|
+
if (!executor.noAuth && (providerResponse.status === HTTP_STATUS.UNAUTHORIZED || providerResponse.status === HTTP_STATUS.FORBIDDEN)) {
|
|
221
|
+
try {
|
|
222
|
+
const newCredentials = await refreshWithRetry(() => executor.refreshCredentials(credentials, log), 3, log);
|
|
223
|
+
if (newCredentials?.accessToken || newCredentials?.copilotToken) {
|
|
224
|
+
log?.info?.("TOKEN", `${provider.toUpperCase()} | refreshed`);
|
|
225
|
+
Object.assign(credentials, newCredentials);
|
|
226
|
+
if (onCredentialsRefreshed) {
|
|
227
|
+
try { await onCredentialsRefreshed(newCredentials); } catch (e) { log?.warn?.("TOKEN", `onCredentialsRefreshed failed: ${e.message}`); }
|
|
228
|
+
}
|
|
229
|
+
try {
|
|
230
|
+
const retryResult = await executor.execute({ model, body: translatedBody, stream, credentials, signal: streamController.signal, log, proxyOptions });
|
|
231
|
+
if (retryResult.response.ok) { providerResponse = retryResult.response; providerUrl = retryResult.url; }
|
|
232
|
+
} catch { log?.warn?.("TOKEN", `${provider.toUpperCase()} | retry after refresh failed`); }
|
|
233
|
+
} else {
|
|
234
|
+
log?.warn?.("TOKEN", `${provider.toUpperCase()} | refresh failed`);
|
|
235
|
+
}
|
|
236
|
+
} catch (e) {
|
|
237
|
+
log?.warn?.("TOKEN", `${provider.toUpperCase()} | refresh threw: ${e.message}`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Provider returned error
|
|
242
|
+
if (!providerResponse.ok) {
|
|
243
|
+
trackPendingRequest(model, provider, connectionId, false, true);
|
|
244
|
+
const { statusCode, message, resetsAtMs } = await parseUpstreamError(providerResponse, executor);
|
|
245
|
+
appendRequestLog({ model, provider, connectionId, status: `FAILED ${statusCode}` }).catch(() => { });
|
|
246
|
+
saveRequestDetail(buildRequestDetail({
|
|
247
|
+
provider, model, connectionId,
|
|
248
|
+
latency: { ttft: 0, total: Date.now() - requestStartTime },
|
|
249
|
+
tokens: { prompt_tokens: 0, completion_tokens: 0 },
|
|
250
|
+
request: extractRequestConfig(body, stream),
|
|
251
|
+
providerRequest: finalBody || translatedBody || null,
|
|
252
|
+
response: { error: message, status: statusCode, thinking: null },
|
|
253
|
+
status: "error"
|
|
254
|
+
})).catch(() => { });
|
|
255
|
+
|
|
256
|
+
const errMsg = formatProviderError(new Error(message), provider, model, statusCode);
|
|
257
|
+
console.log(`${COLORS.red}[ERROR] ${errMsg}${COLORS.reset}`);
|
|
258
|
+
reqLogger.logError(new Error(message), finalBody || translatedBody);
|
|
259
|
+
return createErrorResult(statusCode, errMsg, resetsAtMs);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const sharedCtx = { provider, model, body, stream, translatedBody, finalBody, requestStartTime, connectionId, apiKey, clientRawRequest, onRequestSuccess };
|
|
263
|
+
const appendLog = (extra) => appendRequestLog({ model, provider, connectionId, ...extra }).catch(() => { });
|
|
264
|
+
const trackDone = () => trackPendingRequest(model, provider, connectionId, false);
|
|
265
|
+
|
|
266
|
+
// Provider forced streaming but client wants JSON
|
|
267
|
+
if (!clientRequestedStreaming && providerRequiresStreaming) {
|
|
268
|
+
const result = await handleForcedSSEToJson({ ...sharedCtx, providerResponse, sourceFormat, trackDone, appendLog });
|
|
269
|
+
if (result) { streamController.handleComplete(); return result; }
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// True non-streaming response
|
|
273
|
+
if (!stream) {
|
|
274
|
+
const result = await handleNonStreamingResponse({ ...sharedCtx, providerResponse, sourceFormat, targetFormat, reqLogger, toolNameMap, trackDone, appendLog });
|
|
275
|
+
streamController.handleComplete();
|
|
276
|
+
return result;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// Streaming response
|
|
280
|
+
const { onStreamComplete, streamDetailId } = buildOnStreamComplete({ ...sharedCtx });
|
|
281
|
+
return handleStreamingResponse({ ...sharedCtx, providerResponse, sourceFormat, targetFormat, userAgent, reqLogger, toolNameMap, streamController, onStreamComplete, streamDetailId });
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export function isTokenExpiringSoon(expiresAt, bufferMs = 5 * 60 * 1000) {
|
|
285
|
+
if (!expiresAt) return false;
|
|
286
|
+
return new Date(expiresAt).getTime() - Date.now() < bufferMs;
|
|
287
|
+
}
|