@fudrouter/fsrouter 0.6.61 → 0.6.63
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/bin/copyJs.js +13 -9
- package/open-sse/AGENTS.md +39 -0
- package/open-sse/config/anthropicHeaders.js +87 -0
- package/open-sse/config/appConstants.js +238 -0
- package/open-sse/config/audioRegistry.js +506 -0
- package/open-sse/config/cliFingerprints.js +304 -0
- package/open-sse/config/codexInstructions.js +119 -0
- package/open-sse/config/codexQuotaScopes.js +42 -0
- package/open-sse/config/constants.js +4 -0
- package/open-sse/config/contextEditing.js +68 -0
- package/open-sse/config/credentialLoader.js +83 -0
- package/open-sse/config/defaultThinkingSignature.js +12 -0
- package/open-sse/config/embeddingRegistry.js +264 -0
- package/open-sse/config/errorConfig.js +96 -0
- package/open-sse/config/freeModelCatalog.data.js +121 -0
- package/open-sse/config/freeModelCatalog.js +90 -0
- package/open-sse/config/freeTierCatalog.js +81 -0
- package/open-sse/config/googleTtsLanguages.js +62 -0
- package/open-sse/config/imageParamDefs.js +360 -0
- package/open-sse/config/imageRegistry.js +493 -0
- package/open-sse/config/kiroConstants.js +268 -0
- package/open-sse/config/mediaConfig.js +27 -0
- package/open-sse/config/mediaServiceKinds.js +71 -0
- package/open-sse/config/models.js +13 -0
- package/open-sse/config/moderationRegistry.js +71 -0
- package/open-sse/config/musicRegistry.js +99 -0
- package/open-sse/config/ocrRegistry.js +61 -0
- package/open-sse/config/ollamaModels.js +19 -0
- package/open-sse/config/providerErrorRules.js +114 -0
- package/open-sse/config/providerFieldStrips.js +35 -0
- package/open-sse/config/providerHeaderProfiles.js +191 -0
- package/open-sse/config/providerModels.js +106 -0
- package/open-sse/config/providerRegistry.js +16 -0
- package/open-sse/config/providers.js +19 -0
- package/open-sse/config/registryUtils.js +106 -0
- package/open-sse/config/rerankRegistry.js +177 -0
- package/open-sse/config/runtimeConfig.js +96 -0
- package/open-sse/config/runway.js +39 -0
- package/open-sse/config/searchRegistry.js +153 -0
- package/open-sse/config/toolCloaking.js +199 -0
- package/open-sse/config/ttsModels.js +129 -0
- package/open-sse/config/videoRegistry.js +207 -0
- package/open-sse/executors/adapta-web.js +435 -0
- package/open-sse/executors/antigravity.js +534 -0
- package/open-sse/executors/antigravityUpstreamError.js +13 -0
- package/open-sse/executors/auggie.js +437 -0
- package/open-sse/executors/azure-openai.js +32 -0
- package/open-sse/executors/azure.js +57 -0
- package/open-sse/executors/base.js +181 -0
- package/open-sse/executors/bedrock.js +633 -0
- package/open-sse/executors/blackbox-web.js +578 -0
- package/open-sse/executors/chatgpt-web.js +2042 -0
- package/open-sse/executors/chipotle.js +357 -0
- package/open-sse/executors/claude-web-with-auto-refresh.js +73 -0
- package/open-sse/executors/claude-web.js +586 -0
- package/open-sse/executors/cliproxyapi.js +296 -0
- package/open-sse/executors/cloudflare-ai.js +46 -0
- package/open-sse/executors/codebuddy-cn.js +40 -0
- package/open-sse/executors/codex.js +1324 -0
- package/open-sse/executors/commandCode.js +558 -0
- package/open-sse/executors/commandcode.js +88 -0
- package/open-sse/executors/copilot-m365-connection.js +176 -0
- package/open-sse/executors/copilot-m365-frames.js +192 -0
- package/open-sse/executors/copilot-m365-web.js +299 -0
- package/open-sse/executors/copilot-web.js +580 -0
- package/open-sse/executors/cursor.js +795 -0
- package/open-sse/executors/deepseek-web-with-auto-refresh.js +150 -0
- package/open-sse/executors/deepseek-web.js +875 -0
- package/open-sse/executors/default.js +430 -0
- package/open-sse/executors/devin-cli.js +351 -0
- package/open-sse/executors/doubao-web.js +550 -0
- package/open-sse/executors/duckduckgo-web.js +629 -0
- package/open-sse/executors/forceResponsesUpstream.js +33 -0
- package/open-sse/executors/gemini-business.js +320 -0
- package/open-sse/executors/gemini-cli.js +89 -0
- package/open-sse/executors/gemini-web.js +297 -0
- package/open-sse/executors/github.js +379 -0
- package/open-sse/executors/gitlab.js +569 -0
- package/open-sse/executors/glm.js +361 -0
- package/open-sse/executors/grok-cli.js +119 -0
- package/open-sse/executors/grok-web.js +345 -0
- package/open-sse/executors/huggingchat.js +467 -0
- package/open-sse/executors/iflow.js +108 -0
- package/open-sse/executors/index.js +78 -0
- package/open-sse/executors/inner-ai.js +527 -0
- package/open-sse/executors/kimchi.js +123 -0
- package/open-sse/executors/kimi-web.js +325 -0
- package/open-sse/executors/kimi.js +97 -0
- package/open-sse/executors/kiro.js +503 -0
- package/open-sse/executors/kiroThinking.js +44 -0
- package/open-sse/executors/lmarena.js +395 -0
- package/open-sse/executors/mimo-free.js +167 -0
- package/open-sse/executors/mimocode.js +392 -0
- package/open-sse/executors/ninerouter.js +155 -0
- package/open-sse/executors/nlpcloud.js +438 -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 +581 -0
- package/open-sse/executors/poe-web.js +133 -0
- package/open-sse/executors/pollinations.js +95 -0
- package/open-sse/executors/puter.js +31 -0
- package/open-sse/executors/qoder.js +448 -0
- package/open-sse/executors/qwen-web.js +372 -0
- package/open-sse/executors/qwen.js +129 -0
- package/open-sse/executors/t3-chat-web.js +417 -0
- package/open-sse/executors/theoldllm.js +290 -0
- package/open-sse/executors/trae.js +418 -0
- package/open-sse/executors/v0-vercel-web.js +141 -0
- package/open-sse/executors/venice-web.js +142 -0
- package/open-sse/executors/vertex.js +131 -0
- package/open-sse/executors/vertexMedia.js +236 -0
- package/open-sse/executors/windsurf.js +560 -0
- package/open-sse/executors/xai.js +46 -0
- package/open-sse/executors/xiaomi-tokenplan.js +19 -0
- package/open-sse/executors/yuanbao-web.js +385 -0
- package/open-sse/executors/zed-hosted.js +281 -0
- package/open-sse/executors/zenmux-free.js +247 -0
- package/open-sse/handlers/audioSpeech.js +759 -0
- package/open-sse/handlers/audioTranscription.js +395 -0
- package/open-sse/handlers/audioTranslation.js +181 -0
- package/open-sse/handlers/chatCore/nonStreamingHandler.js +300 -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 +95 -0
- package/open-sse/handlers/chatCore.js +404 -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 +230 -0
- package/open-sse/handlers/imageProviders/_base.js +31 -0
- package/open-sse/handlers/imageProviders/antigravity.js +73 -0
- package/open-sse/handlers/imageProviders/blackForestLabs.js +63 -0
- package/open-sse/handlers/imageProviders/cloudflareAi.js +207 -0
- package/open-sse/handlers/imageProviders/codex.js +217 -0
- package/open-sse/handlers/imageProviders/comfyui.js +25 -0
- package/open-sse/handlers/imageProviders/falAi.js +62 -0
- package/open-sse/handlers/imageProviders/gemini.js +40 -0
- package/open-sse/handlers/imageProviders/huggingface.js +38 -0
- package/open-sse/handlers/imageProviders/index.js +44 -0
- package/open-sse/handlers/imageProviders/leonardo.js +435 -0
- package/open-sse/handlers/imageProviders/nanobanana.js +79 -0
- package/open-sse/handlers/imageProviders/openai.js +61 -0
- package/open-sse/handlers/imageProviders/runwayml.js +72 -0
- package/open-sse/handlers/imageProviders/sdwebui.js +36 -0
- package/open-sse/handlers/imageProviders/stabilityAi.js +59 -0
- package/open-sse/handlers/imageProviders/weavy.js +222 -0
- package/open-sse/handlers/moderations.js +92 -0
- package/open-sse/handlers/ocr.js +89 -0
- package/open-sse/handlers/rerank.js +223 -0
- package/open-sse/handlers/responseSanitizer/reasoning.js +144 -0
- package/open-sse/handlers/responsesHandler.js +99 -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/search.js +1056 -0
- package/open-sse/handlers/sseParser.js +469 -0
- package/open-sse/handlers/sttCore.js +193 -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/handlers/usageExtractor.js +93 -0
- package/open-sse/handlers/videoGenerationCore.js +119 -0
- package/open-sse/handlers/videoProviders/index.js +22 -0
- package/open-sse/handlers/videoProviders/leonardo.js +511 -0
- package/open-sse/handlers/videoProviders/weavy.js +198 -0
- package/open-sse/handlers/webFetch.js +200 -0
- package/open-sse/index.js +79 -0
- package/open-sse/mcp-server/audit.js +283 -0
- package/open-sse/mcp-server/catalog.js +184 -0
- package/open-sse/mcp-server/descriptionCompressor.js +175 -0
- package/open-sse/mcp-server/httpAuthContext.js +32 -0
- package/open-sse/mcp-server/httpTransport.js +229 -0
- package/open-sse/mcp-server/index.js +33 -0
- package/open-sse/mcp-server/mcpCallerIdentity.js +21 -0
- package/open-sse/mcp-server/runtimeHeartbeat.js +110 -0
- package/open-sse/mcp-server/schemas/a2a.js +153 -0
- package/open-sse/mcp-server/schemas/audit.js +17 -0
- package/open-sse/mcp-server/schemas/index.js +166 -0
- package/open-sse/mcp-server/schemas/pickFastestModel.js +90 -0
- package/open-sse/mcp-server/schemas/toolDefinition.js +0 -0
- package/open-sse/mcp-server/schemas/toolSearch.js +32 -0
- package/open-sse/mcp-server/schemas/tools.js +1219 -0
- package/open-sse/mcp-server/scopeEnforcement.js +80 -0
- package/open-sse/mcp-server/server.js +1168 -0
- package/open-sse/mcp-server/toolCardinality.js +78 -0
- package/open-sse/mcp-server/toolSearch/catalog.js +66 -0
- package/open-sse/mcp-server/toolSearch/handler.js +20 -0
- package/open-sse/mcp-server/toolSearch/index.js +10 -0
- package/open-sse/mcp-server/toolSearch/register.js +21 -0
- package/open-sse/mcp-server/toolSearch/search.js +55 -0
- package/open-sse/mcp-server/toolSearch/signature.js +67 -0
- package/open-sse/mcp-server/tools/advancedTools.js +893 -0
- package/open-sse/mcp-server/tools/agentSkillTools.js +69 -0
- package/open-sse/mcp-server/tools/compressionTools.js +309 -0
- package/open-sse/mcp-server/tools/gamificationTools.js +134 -0
- package/open-sse/mcp-server/tools/githubSkillTools.js +102 -0
- package/open-sse/mcp-server/tools/memoryTools.js +118 -0
- package/open-sse/mcp-server/tools/notionTools.js +101 -0
- package/open-sse/mcp-server/tools/obsidianTools.js +307 -0
- package/open-sse/mcp-server/tools/pickFastestModel.js +223 -0
- package/open-sse/mcp-server/tools/pluginTools.js +181 -0
- package/open-sse/mcp-server/tools/poolTools.js +139 -0
- package/open-sse/mcp-server/tools/skillTools.js +113 -0
- package/open-sse/package.json +10 -0
- package/open-sse/providers/REGISTRY_TEMPLATE.js +98 -0
- package/open-sse/providers/capabilities.js +293 -0
- package/open-sse/providers/index.js +51 -0
- package/open-sse/providers/models/helpers.js +20 -0
- package/open-sse/providers/models/namePatterns.js +33 -0
- package/open-sse/providers/models/schema.js +40 -0
- package/open-sse/providers/pricing.js +308 -0
- package/open-sse/providers/registry/alicode-intl.js +30 -0
- package/open-sse/providers/registry/alicode.js +31 -0
- package/open-sse/providers/registry/anthropic.js +37 -0
- package/open-sse/providers/registry/antigravity.js +81 -0
- package/open-sse/providers/registry/assemblyai.js +38 -0
- package/open-sse/providers/registry/aws-polly.js +45 -0
- package/open-sse/providers/registry/azure.js +21 -0
- package/open-sse/providers/registry/black-forest-labs.js +32 -0
- package/open-sse/providers/registry/blackbox.js +41 -0
- package/open-sse/providers/registry/brave-search.js +35 -0
- package/open-sse/providers/registry/byteplus.js +35 -0
- package/open-sse/providers/registry/cartesia.js +36 -0
- package/open-sse/providers/registry/cerebras.js +31 -0
- package/open-sse/providers/registry/chutes.js +24 -0
- package/open-sse/providers/registry/claude.js +87 -0
- package/open-sse/providers/registry/cline.js +51 -0
- package/open-sse/providers/registry/clinepass.js +57 -0
- package/open-sse/providers/registry/cloudflare-ai.js +55 -0
- package/open-sse/providers/registry/codebuddy-cn.js +77 -0
- package/open-sse/providers/registry/codex.js +100 -0
- package/open-sse/providers/registry/cohere.js +27 -0
- package/open-sse/providers/registry/comfyui.js +20 -0
- package/open-sse/providers/registry/commandcode.js +43 -0
- package/open-sse/providers/registry/coqui.js +30 -0
- package/open-sse/providers/registry/cursor.js +58 -0
- package/open-sse/providers/registry/deepgram.js +33 -0
- package/open-sse/providers/registry/deepseek.js +51 -0
- package/open-sse/providers/registry/digitalocean.js +92 -0
- package/open-sse/providers/registry/edge-tts.js +24 -0
- package/open-sse/providers/registry/elevenlabs.js +35 -0
- package/open-sse/providers/registry/exa.js +50 -0
- package/open-sse/providers/registry/fal-ai.js +34 -0
- package/open-sse/providers/registry/featherless.js +34 -0
- package/open-sse/providers/registry/firecrawl.js +34 -0
- package/open-sse/providers/registry/fireworks.js +29 -0
- package/open-sse/providers/registry/gemini-cli.js +58 -0
- package/open-sse/providers/registry/gemini.js +83 -0
- package/open-sse/providers/registry/github.js +88 -0
- package/open-sse/providers/registry/gitlab.js +32 -0
- package/open-sse/providers/registry/glm-cn.js +35 -0
- package/open-sse/providers/registry/glm.js +58 -0
- package/open-sse/providers/registry/google-pse.js +35 -0
- package/open-sse/providers/registry/google-tts.js +24 -0
- package/open-sse/providers/registry/grok-cli.js +86 -0
- package/open-sse/providers/registry/grok-web.js +39 -0
- package/open-sse/providers/registry/groq.js +37 -0
- package/open-sse/providers/registry/huggingface.js +34 -0
- package/open-sse/providers/registry/hyperbolic.js +35 -0
- package/open-sse/providers/registry/ibm-bob.js +27 -0
- package/open-sse/providers/registry/iflow.js +52 -0
- package/open-sse/providers/registry/index.js +210 -0
- package/open-sse/providers/registry/inworld.js +36 -0
- package/open-sse/providers/registry/jina-ai.js +42 -0
- package/open-sse/providers/registry/jina-reader.js +34 -0
- package/open-sse/providers/registry/kilocode.js +51 -0
- package/open-sse/providers/registry/kimchi.js +49 -0
- package/open-sse/providers/registry/kimi-coding.js +65 -0
- package/open-sse/providers/registry/kimi.js +56 -0
- package/open-sse/providers/registry/kiro.js +115 -0
- package/open-sse/providers/registry/linkup.js +34 -0
- package/open-sse/providers/registry/local-device.js +24 -0
- package/open-sse/providers/registry/mimo-free.js +24 -0
- package/open-sse/providers/registry/minimax-cn.js +76 -0
- package/open-sse/providers/registry/minimax.js +83 -0
- package/open-sse/providers/registry/mistral.js +34 -0
- package/open-sse/providers/registry/mmf.js +19 -0
- package/open-sse/providers/registry/nanobanana.js +35 -0
- package/open-sse/providers/registry/nebius.js +27 -0
- package/open-sse/providers/registry/nvidia.js +43 -0
- package/open-sse/providers/registry/ollama-local.js +19 -0
- package/open-sse/providers/registry/ollama.js +36 -0
- package/open-sse/providers/registry/openai.js +84 -0
- package/open-sse/providers/registry/opencode-go.js +41 -0
- package/open-sse/providers/registry/opencode.js +25 -0
- package/open-sse/providers/registry/openrouter.js +60 -0
- package/open-sse/providers/registry/perplexity-agent.js +49 -0
- package/open-sse/providers/registry/perplexity-web.js +33 -0
- package/open-sse/providers/registry/perplexity.js +37 -0
- package/open-sse/providers/registry/playht.js +36 -0
- package/open-sse/providers/registry/qoder.js +54 -0
- package/open-sse/providers/registry/qwen.js +33 -0
- package/open-sse/providers/registry/recraft.js +24 -0
- package/open-sse/providers/registry/runwayml.js +30 -0
- package/open-sse/providers/registry/sdwebui.js +20 -0
- package/open-sse/providers/registry/searchapi.js +35 -0
- package/open-sse/providers/registry/searxng.js +35 -0
- package/open-sse/providers/registry/serper.js +35 -0
- package/open-sse/providers/registry/siliconflow.js +39 -0
- package/open-sse/providers/registry/stability-ai.js +31 -0
- package/open-sse/providers/registry/tavily.js +50 -0
- package/open-sse/providers/registry/together.js +31 -0
- package/open-sse/providers/registry/topaz.js +19 -0
- package/open-sse/providers/registry/tortoise.js +30 -0
- package/open-sse/providers/registry/venice.js +56 -0
- package/open-sse/providers/registry/vercel-ai-gateway.js +41 -0
- package/open-sse/providers/registry/vertex-partner.js +29 -0
- package/open-sse/providers/registry/vertex.js +32 -0
- package/open-sse/providers/registry/volcengine-ark.js +35 -0
- package/open-sse/providers/registry/voyage-ai.js +30 -0
- package/open-sse/providers/registry/xai.js +45 -0
- package/open-sse/providers/registry/xiaomi-mimo.js +46 -0
- package/open-sse/providers/registry/xiaomi-tokenplan.js +63 -0
- package/open-sse/providers/registry/youcom.js +35 -0
- package/open-sse/providers/schema.js +76 -0
- package/open-sse/providers/shared.js +74 -0
- package/open-sse/providers/thinkingLevels.js +48 -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 +50 -0
- package/open-sse/rtk/filters/gitDiff.js +92 -0
- package/open-sse/rtk/filters/gitLog.js +99 -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/headroom.js +215 -0
- package/open-sse/rtk/index.js +155 -0
- package/open-sse/rtk/paleo.js +47 -0
- package/open-sse/rtk/ponytail.js +9 -0
- package/open-sse/rtk/ponytailPrompt.js +52 -0
- package/open-sse/rtk/ponytailPrompts.js +76 -0
- package/open-sse/rtk/pxpipe.js +104 -0
- package/open-sse/rtk/registry.js +38 -0
- package/open-sse/rtk/systemInject.js +98 -0
- package/open-sse/services/accountFallback.js +323 -0
- package/open-sse/services/antigravityHeaders.js +91 -0
- package/open-sse/services/antigravityVersion.js +154 -0
- package/open-sse/services/clinepassModels.js +63 -0
- package/open-sse/services/codexQuotaFetcher.js +312 -0
- package/open-sse/services/codexVerbosity.js +30 -0
- package/open-sse/services/combo/context.js +12 -0
- package/open-sse/services/combo/fingerprintExpansion.js +51 -0
- package/open-sse/services/combo/headroomRanking.js +28 -0
- package/open-sse/services/combo/quotaExhaustionCutoff.js +87 -0
- package/open-sse/services/combo/quotaScoring.js +226 -0
- package/open-sse/services/combo/quotaShareConcurrency.js +25 -0
- package/open-sse/services/combo/quotaShareInflight.js +50 -0
- package/open-sse/services/combo/quotaShareStrategy.js +130 -0
- package/open-sse/services/combo/resolveAutoStrategy.js +231 -0
- package/open-sse/services/combo/responseValidation.js +140 -0
- package/open-sse/services/combo/runtimeUnits.js +195 -0
- package/open-sse/services/combo/sessionStickiness.js +128 -0
- package/open-sse/services/combo/shadowRouting.js +131 -0
- package/open-sse/services/combo/targetExhaustion.js +75 -0
- package/open-sse/services/combo/targetSorters.js +126 -0
- package/open-sse/services/combo/targetTimeoutRunner.js +65 -0
- package/open-sse/services/combo/validateQuality.js +271 -0
- package/open-sse/services/combo.js +571 -0
- package/open-sse/services/comboAgentMiddleware.js +91 -0
- package/open-sse/services/comboConfig.js +153 -0
- package/open-sse/services/comboManifestMetrics.js +10 -0
- package/open-sse/services/comboMetrics.js +278 -0
- package/open-sse/services/compact.js +71 -0
- package/open-sse/services/copilotModels.js +155 -0
- package/open-sse/services/emergencyFallback.js +109 -0
- package/open-sse/services/errorClassifier.js +190 -0
- package/open-sse/services/evalRouting.js +201 -0
- package/open-sse/services/freeWebSearch.js +4 -0
- package/open-sse/services/fusion.js +223 -0
- package/open-sse/services/intentClassifier.js +631 -0
- package/open-sse/services/kimchiModels.js +176 -0
- package/open-sse/services/kiroModels.js +332 -0
- package/open-sse/services/model.js +136 -0
- package/open-sse/services/modelCapabilities.js +5 -0
- package/open-sse/services/modelDeprecation.js +101 -0
- package/open-sse/services/modelFamilyFallback.js +166 -0
- package/open-sse/services/oauthCredentialManager.js +156 -0
- package/open-sse/services/pipeline.js +107 -0
- package/open-sse/services/projectId.js +306 -0
- package/open-sse/services/provider.js +169 -0
- package/open-sse/services/providerCooldownTracker.js +94 -0
- package/open-sse/services/providerDefaultRateLimit.js +11 -0
- package/open-sse/services/proxyAutoSelector.js +24 -0
- package/open-sse/services/qoderModels.js +214 -0
- package/open-sse/services/quotaFetchThrottle.js +103 -0
- package/open-sse/services/quotaMonitor.js +310 -0
- package/open-sse/services/quotaPreflight.js +266 -0
- package/open-sse/services/rateLimitManager/headers.js +56 -0
- package/open-sse/services/rateLimitManager.js +616 -0
- package/open-sse/services/rateLimitSemaphore.js +112 -0
- package/open-sse/services/responsesInputSanitizer.js +99 -0
- package/open-sse/services/slidingWindowLimiter.js +44 -0
- package/open-sse/services/streamRecovery.js +355 -0
- package/open-sse/services/taskAwareRouter.js +227 -0
- package/open-sse/services/taskAwareRouting.js +332 -0
- package/open-sse/services/thinkingBudget.js +247 -0
- package/open-sse/services/tokenRefresh/dedup.js +31 -0
- package/open-sse/services/tokenRefresh/providers.js +624 -0
- package/open-sse/services/tokenRefresh.js +254 -0
- package/open-sse/services/usage/claude.js +147 -0
- package/open-sse/services/usage/codebuddy-cn.js +138 -0
- package/open-sse/services/usage/codex.js +267 -0
- package/open-sse/services/usage/github.js +100 -0
- package/open-sse/services/usage/google.js +241 -0
- package/open-sse/services/usage/grok-cli.js +274 -0
- package/open-sse/services/usage/kiro.js +188 -0
- package/open-sse/services/usage/minimax.js +234 -0
- package/open-sse/services/usage/misc.js +288 -0
- package/open-sse/services/usage/shared.js +70 -0
- package/open-sse/services/usage.js +62 -0
- package/open-sse/services/usageDb.js +2 -0
- package/open-sse/services/webSearchRouting.js +25 -0
- package/open-sse/services/wildcardRouter.js +59 -0
- package/open-sse/shared/clineAuth.js +37 -0
- package/open-sse/shared/machineId.js +19 -0
- package/open-sse/shared/qoder/constants.js +64 -0
- package/open-sse/shared/qoder/cosy.js +175 -0
- package/open-sse/shared/qoder/encoding.js +55 -0
- package/open-sse/transformer/responsesTransformer.js +439 -0
- package/open-sse/transformer/streamToJsonConverter.js +103 -0
- package/open-sse/translator/concerns/chunk.js +11 -0
- package/open-sse/translator/concerns/finishReason.js +63 -0
- package/open-sse/translator/concerns/image.js +124 -0
- package/open-sse/translator/concerns/json.js +5 -0
- package/open-sse/translator/concerns/message.js +7 -0
- package/open-sse/translator/concerns/modality.js +155 -0
- package/open-sse/translator/concerns/paramSupport.js +75 -0
- package/open-sse/translator/concerns/prefetch.js +96 -0
- package/open-sse/translator/concerns/reasoning.js +24 -0
- package/open-sse/translator/concerns/thinking.js +53 -0
- package/open-sse/translator/concerns/thinkingUnified.js +329 -0
- package/open-sse/translator/concerns/toolCall.js +153 -0
- package/open-sse/translator/concerns/usage.js +69 -0
- package/open-sse/translator/formats/claude.js +368 -0
- package/open-sse/translator/formats/gemini.js +380 -0
- package/open-sse/translator/formats/maxTokens.js +34 -0
- package/open-sse/translator/formats/openai.js +134 -0
- package/open-sse/translator/formats/responsesApi.js +141 -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 +252 -0
- package/open-sse/translator/request/antigravity-to-openai.js +242 -0
- package/open-sse/translator/request/claude-to-kiro.js +478 -0
- package/open-sse/translator/request/claude-to-openai.js +263 -0
- package/open-sse/translator/request/gemini-to-openai.js +152 -0
- package/open-sse/translator/request/openai-responses.js +385 -0
- package/open-sse/translator/request/openai-to-claude.js +383 -0
- package/open-sse/translator/request/openai-to-commandcode.js +176 -0
- package/open-sse/translator/request/openai-to-cursor.js +185 -0
- package/open-sse/translator/request/openai-to-gemini.js +442 -0
- package/open-sse/translator/request/openai-to-kiro.js +607 -0
- package/open-sse/translator/request/openai-to-kiro.old.js +278 -0
- package/open-sse/translator/request/openai-to-ollama.js +195 -0
- package/open-sse/translator/request/openai-to-vertex.js +42 -0
- package/open-sse/translator/response/claude-to-openai.js +195 -0
- package/open-sse/translator/response/commandcode-to-openai.js +188 -0
- package/open-sse/translator/response/cursor-to-openai.js +30 -0
- package/open-sse/translator/response/gemini-to-openai.js +147 -0
- package/open-sse/translator/response/kiro-to-claude.js +261 -0
- package/open-sse/translator/response/kiro-to-openai.js +160 -0
- package/open-sse/translator/response/ollama-to-openai.js +134 -0
- package/open-sse/translator/response/openai-responses.js +535 -0
- package/open-sse/translator/response/openai-to-antigravity.js +123 -0
- package/open-sse/translator/response/openai-to-claude.js +265 -0
- package/open-sse/translator/schema/blocks.js +43 -0
- package/open-sse/translator/schema/defaults.js +7 -0
- package/open-sse/translator/schema/finishReasons.js +27 -0
- package/open-sse/translator/schema/index.js +8 -0
- package/open-sse/translator/schema/roles.js +16 -0
- package/open-sse/utils/agentGoalPolicy.js +85 -0
- package/open-sse/utils/aiSdkCompat.js +75 -0
- package/open-sse/utils/bypassHandler.js +298 -0
- package/open-sse/utils/cacheControlPolicy.js +189 -0
- package/open-sse/utils/claudeCloaking.js +155 -0
- package/open-sse/utils/claudeHeaderCache.js +70 -0
- package/open-sse/utils/claudeSignature.js +41 -0
- package/open-sse/utils/clientDetector.js +63 -0
- package/open-sse/utils/codebuddySanitizer.js +96 -0
- package/open-sse/utils/composerToolCalls.js +158 -0
- package/open-sse/utils/cors.js +13 -0
- package/open-sse/utils/cursorChecksum.js +149 -0
- package/open-sse/utils/cursorImages.js +224 -0
- package/open-sse/utils/cursorProtobuf.js +904 -0
- package/open-sse/utils/cursorVersionDetector.js +55 -0
- package/open-sse/utils/debugLog.js +14 -0
- package/open-sse/utils/diagnostics.js +143 -0
- package/open-sse/utils/error.js +164 -0
- package/open-sse/utils/estimateSize.js +33 -0
- package/open-sse/utils/finishReason.js +32 -0
- package/open-sse/utils/flattenToolHistory.js +68 -0
- package/open-sse/utils/headers.js +36 -0
- package/open-sse/utils/heapPressure.js +35 -0
- package/open-sse/utils/jsonToSse.js +125 -0
- package/open-sse/utils/keepaliveThreshold.js +40 -0
- package/open-sse/utils/logger.js +104 -0
- package/open-sse/utils/noThinkingAlias.js +74 -0
- package/open-sse/utils/number.js +7 -0
- package/open-sse/utils/ollamaTransform.js +85 -0
- package/open-sse/utils/opencodeHeaders.js +47 -0
- package/open-sse/utils/progressTracker.js +81 -0
- package/open-sse/utils/providerRequestLogging.js +219 -0
- package/open-sse/utils/proxyFetch.js +369 -0
- package/open-sse/utils/reasoningContentInjector.js +79 -0
- package/open-sse/utils/reasoningFields.js +70 -0
- package/open-sse/utils/requestLogger.js +260 -0
- package/open-sse/utils/responsesInputNormalization.js +92 -0
- package/open-sse/utils/responsesStatePolicy.js +52 -0
- package/open-sse/utils/responsesStreamHelpers.js +49 -0
- package/open-sse/utils/sessionManager.js +240 -0
- package/open-sse/utils/sleep.js +6 -0
- package/open-sse/utils/sse.js +14 -0
- package/open-sse/utils/sseConstants.js +23 -0
- package/open-sse/utils/sseHeartbeat.js +104 -0
- package/open-sse/utils/stream.js +517 -0
- package/open-sse/utils/streamFailureFinalization.js +134 -0
- package/open-sse/utils/streamHandler.js +250 -0
- package/open-sse/utils/streamHelpers.js +137 -0
- package/open-sse/utils/textualToolCall.js +104 -0
- package/open-sse/utils/thinkCloseMarker.js +72 -0
- package/open-sse/utils/thinkTagParser.js +146 -0
- package/open-sse/utils/toolCallArguments.js +12 -0
- package/open-sse/utils/toolDeduper.js +49 -0
- package/open-sse/utils/toolSources.js +31 -0
- package/open-sse/utils/upstreamResponseHeaders.js +25 -0
- package/open-sse/utils/urlSanitize.js +15 -0
- package/open-sse/utils/usageTracking.js +347 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1324 @@
|
|
|
1
|
+
// ─── Codex Executor (AMRouter) ─────────────────────────────────────────────
|
|
2
|
+
// Converted from OmniRoute TypeScript to plain JavaScript for AMRouter.
|
|
3
|
+
// Inlines: codex/quota.ts, codex/tools.ts sub-modules.
|
|
4
|
+
// Preserves all key business logic from OmniRoute codex.ts (1270 lines).
|
|
5
|
+
|
|
6
|
+
import { createRequire } from "module";
|
|
7
|
+
import { BaseExecutor } from "./base.js";
|
|
8
|
+
import { PROVIDERS } from "../config/providers.js";
|
|
9
|
+
import { CODEX_DEFAULT_INSTRUCTIONS } from "../config/codexInstructions.js";
|
|
10
|
+
import { normalizeResponsesInput } from "../translator/formats/responsesApi.js";
|
|
11
|
+
import { fetchImageAsBase64 } from "../translator/concerns/image.js";
|
|
12
|
+
import { getModelUpstreamId } from "../config/providerModels.js";
|
|
13
|
+
import { DEFAULT_RETRY_CONFIG, HTTP_STATUS, resolveRetryEntry } from "../config/runtimeConfig.js";
|
|
14
|
+
import { resolveSessionId } from "../utils/sessionManager.js";
|
|
15
|
+
import {
|
|
16
|
+
refreshProviderCredentials,
|
|
17
|
+
shouldRefreshCredentials,
|
|
18
|
+
} from "../services/oauthCredentialManager.js";
|
|
19
|
+
import { getAccessToken } from "../services/tokenRefresh.js";
|
|
20
|
+
import { dbg } from "../utils/debugLog.js";
|
|
21
|
+
|
|
22
|
+
// ─── Inline stubs for OmniRoute-only modules ─────────────────────────────
|
|
23
|
+
|
|
24
|
+
// OmniRoute codexInstructions.ts also exports CODEX_CHAT_DEFAULT_INSTRUCTIONS
|
|
25
|
+
const CODEX_CHAT_DEFAULT_INSTRUCTIONS =
|
|
26
|
+
"You are a helpful assistant. Follow the developer instructions in the conversation.";
|
|
27
|
+
|
|
28
|
+
// OmniRoute config/codexClient.ts
|
|
29
|
+
function getCodexClientVersion() { return "0.200.0"; }
|
|
30
|
+
function getCodexUserAgent() { return "codex-cli/0.200.0 (node)"; }
|
|
31
|
+
function normalizeCodexSessionId(v) {
|
|
32
|
+
if (typeof v !== "string") return null;
|
|
33
|
+
const t = v.trim();
|
|
34
|
+
return t.length > 0 ? t.slice(0, 256) : null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// OmniRoute config/codexIdentity.ts — client identity for Codex backend
|
|
38
|
+
function createCodexClientIdentity(sessionId, providerSpecificData) {
|
|
39
|
+
// Return a minimal identity object; real OmniRoute reads from config/DB
|
|
40
|
+
if (!sessionId) return null;
|
|
41
|
+
return { sessionId, clientId: "amrouter" };
|
|
42
|
+
}
|
|
43
|
+
function applyCodexClientIdentityHeaders(headers, identity) {
|
|
44
|
+
if (!identity) return;
|
|
45
|
+
// Codex backend expects these headers for identity tracking
|
|
46
|
+
if (identity.sessionId) headers["session_id"] = identity.sessionId;
|
|
47
|
+
}
|
|
48
|
+
function applyCodexClientMetadata(body, identity) {
|
|
49
|
+
if (!identity) return;
|
|
50
|
+
// Codex client_metadata is used for telemetry
|
|
51
|
+
if (!body.client_metadata) body.client_metadata = {};
|
|
52
|
+
body.client_metadata.client_id = identity.clientId || "amrouter";
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// OmniRoute lib/providers/requestDefaults.ts
|
|
56
|
+
function getCodexRequestDefaults(providerSpecificData) {
|
|
57
|
+
return {
|
|
58
|
+
serviceTier: providerSpecificData?.serviceTier || null,
|
|
59
|
+
reasoningEffort: providerSpecificData?.reasoningEffort || null,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// OmniRoute config/codexQuotaScopes.ts — scope-aware rate limiting
|
|
64
|
+
function getCodexModelScope(model) {
|
|
65
|
+
if (typeof model !== "string") return "codex";
|
|
66
|
+
const lower = model.toLowerCase();
|
|
67
|
+
if (lower.includes("spark") || lower.includes("mini")) return "spark";
|
|
68
|
+
return "codex";
|
|
69
|
+
}
|
|
70
|
+
function getCodexRateLimitKey(model, connectionId) {
|
|
71
|
+
const scope = getCodexModelScope(model);
|
|
72
|
+
return `${scope}:${connectionId || "default"}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// OmniRoute services/responsesInputSanitizer.ts
|
|
76
|
+
function sanitizeResponsesInputItems(input, _strict, options) {
|
|
77
|
+
if (!Array.isArray(input)) return input;
|
|
78
|
+
const dropInternal = options?.dropInternalAssistantMessages;
|
|
79
|
+
return input.filter((item) => {
|
|
80
|
+
if (!item || typeof item !== "object") return true;
|
|
81
|
+
// Drop internal assistant messages that aren't meant for upstream
|
|
82
|
+
if (dropInternal && item.role === "assistant" && item._internal) return false;
|
|
83
|
+
return true;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// OmniRoute services/codexVerbosity.ts
|
|
88
|
+
function normalizeCodexVerbosity(body) {
|
|
89
|
+
// Fold Chat-style `verbosity` / Responses `text.verbosity` into text:{verbosity}
|
|
90
|
+
const verbosity = body.verbosity;
|
|
91
|
+
if (verbosity !== undefined) {
|
|
92
|
+
delete body.verbosity;
|
|
93
|
+
if (typeof verbosity === "string" && verbosity.trim()) {
|
|
94
|
+
body.text = { ...(body.text && typeof body.text === "object" ? body.text : {}), verbosity: verbosity.trim().toLowerCase() };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
// Ensure text.verbosity is a valid value
|
|
98
|
+
if (body.text && typeof body.text === "object" && body.text.verbosity) {
|
|
99
|
+
const v = String(body.text.verbosity).toLowerCase();
|
|
100
|
+
const VALID = new Set(["low", "medium", "high"]);
|
|
101
|
+
if (!VALID.has(v)) delete body.text.verbosity;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// OmniRoute services/thinkingBudget.ts
|
|
106
|
+
const ThinkingMode = { PASSTHROUGH: "passthrough", DEFAULT: "default" };
|
|
107
|
+
function getThinkingBudgetConfig() {
|
|
108
|
+
const mode = process.env.CODEX_THINKING_MODE || ThinkingMode.DEFAULT;
|
|
109
|
+
return { mode };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// OmniRoute utils/cors.ts
|
|
113
|
+
const CORS_HEADERS = {
|
|
114
|
+
"Access-Control-Allow-Origin": "*",
|
|
115
|
+
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
|
|
116
|
+
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
// OmniRoute utils/responsesInputNormalization.ts
|
|
120
|
+
function normalizeCodexResponsesInput(body) {
|
|
121
|
+
// Handle messages/prompt → input conversion (Cursor, other clients)
|
|
122
|
+
if (!body.input && Array.isArray(body.messages)) {
|
|
123
|
+
body.input = body.messages.map((msg) => ({
|
|
124
|
+
type: "message",
|
|
125
|
+
role: typeof msg.role === "string" ? msg.role : "user",
|
|
126
|
+
...(typeof msg.phase === "string" ? { phase: msg.phase } : {}),
|
|
127
|
+
content:
|
|
128
|
+
typeof msg.content === "string"
|
|
129
|
+
? [{ type: "input_text", text: msg.content }]
|
|
130
|
+
: Array.isArray(msg.content)
|
|
131
|
+
? msg.content.map((cp) => {
|
|
132
|
+
if (cp && typeof cp === "object" && !Array.isArray(cp) && cp.type === "text") {
|
|
133
|
+
return { type: "input_text", text: cp.text };
|
|
134
|
+
}
|
|
135
|
+
return cp;
|
|
136
|
+
})
|
|
137
|
+
: [],
|
|
138
|
+
}));
|
|
139
|
+
} else if (!body.input && typeof body.prompt === "string" && body.prompt.trim()) {
|
|
140
|
+
body.input = [
|
|
141
|
+
{ type: "message", role: "user", content: [{ type: "input_text", text: body.prompt }] },
|
|
142
|
+
];
|
|
143
|
+
} else if (!body.input && Array.isArray(body.prompt)) {
|
|
144
|
+
body.input = body.prompt.map((p) => ({
|
|
145
|
+
type: "message",
|
|
146
|
+
role: "user",
|
|
147
|
+
content: [{ type: "input_text", text: typeof p === "string" ? p : JSON.stringify(p) }],
|
|
148
|
+
}));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// OmniRoute utils/providerRequestLogging.ts — stub
|
|
153
|
+
const prl = {
|
|
154
|
+
async captureCurrentProviderBody(_url, _headers, _body, _log) { /* noop */ },
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
// ─── Constants ──────────────────────────────────────────────────────────────
|
|
158
|
+
|
|
159
|
+
const EFFORT_ORDER = ["none", "low", "medium", "high", "xhigh"];
|
|
160
|
+
const CODEX_FAST_WIRE_VALUE = "priority";
|
|
161
|
+
const CODEX_RESPONSES_WS_URL = "wss://chatgpt.com/backend-api/codex/responses";
|
|
162
|
+
const CODEX_REASONING_ENCRYPTED_CONTENT_INCLUDE = "reasoning.encrypted_content";
|
|
163
|
+
const CODEX_DEFAULT_REASONING_SUMMARY = "auto";
|
|
164
|
+
|
|
165
|
+
const MAX_EFFORT_BY_MODEL = {
|
|
166
|
+
"gpt-5.3-codex": "xhigh",
|
|
167
|
+
"gpt-5.1-codex-max": "xhigh",
|
|
168
|
+
"gpt-5-mini": "high",
|
|
169
|
+
"gpt-5.1-mini": "high",
|
|
170
|
+
"gpt-4.1-mini": "high",
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const RESPONSES_API_ALLOWLIST = new Set([
|
|
174
|
+
"model", "input", "instructions", "tools", "tool_choice", "stream", "store",
|
|
175
|
+
"reasoning", "service_tier", "include", "prompt_cache_key", "client_metadata", "text",
|
|
176
|
+
]);
|
|
177
|
+
|
|
178
|
+
// Server-generated item id prefixes that Codex /responses cannot resolve when store=false
|
|
179
|
+
const SERVER_ID_PATTERN = /^(rs|fc|resp|msg)_/;
|
|
180
|
+
// ─── Inlined: codex/quota.ts ────────────────────────────────────────────────
|
|
181
|
+
// Quota parsing + reset/cooldown scheduling (pure).
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Parsed quota snapshot from Codex response headers.
|
|
185
|
+
* Codex includes per-account usage windows that allow precise reset scheduling.
|
|
186
|
+
*/
|
|
187
|
+
// (CodexQuotaSnapshot is a plain object: { usage5h, limit5h, resetAt5h, usage7d, limit7d, resetAt7d })
|
|
188
|
+
|
|
189
|
+
export function parseCodexQuotaHeaders(headers) {
|
|
190
|
+
const usage5h = headers["x-codex-5h-usage"] ?? null;
|
|
191
|
+
const limit5h = headers["x-codex-5h-limit"] ?? null;
|
|
192
|
+
const resetAt5h = headers["x-codex-5h-reset-at"] ?? null;
|
|
193
|
+
const usage7d = headers["x-codex-7d-usage"] ?? null;
|
|
194
|
+
const limit7d = headers["x-codex-7d-limit"] ?? null;
|
|
195
|
+
const resetAt7d = headers["x-codex-7d-reset-at"] ?? null;
|
|
196
|
+
|
|
197
|
+
if (!usage5h && !limit5h && !resetAt5h && !usage7d && !limit7d && !resetAt7d) {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return {
|
|
202
|
+
usage5h: usage5h ? parseFloat(usage5h) : 0,
|
|
203
|
+
limit5h: limit5h ? parseFloat(limit5h) : Infinity,
|
|
204
|
+
resetAt5h: resetAt5h ?? null,
|
|
205
|
+
usage7d: usage7d ? parseFloat(usage7d) : 0,
|
|
206
|
+
limit7d: limit7d ? parseFloat(limit7d) : Infinity,
|
|
207
|
+
resetAt7d: resetAt7d ?? null,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function getCodexResetTime(quota) {
|
|
212
|
+
const times = [];
|
|
213
|
+
if (quota.resetAt7d) {
|
|
214
|
+
const t = new Date(quota.resetAt7d).getTime();
|
|
215
|
+
if (!isNaN(t) && t > Date.now()) times.push(t);
|
|
216
|
+
}
|
|
217
|
+
if (quota.resetAt5h) {
|
|
218
|
+
const t = new Date(quota.resetAt5h).getTime();
|
|
219
|
+
if (!isNaN(t) && t > Date.now()) times.push(t);
|
|
220
|
+
}
|
|
221
|
+
if (times.length === 0) return null;
|
|
222
|
+
return Math.max(...times);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function getCodexDualWindowCooldownMs(quota, threshold = 0.95) {
|
|
226
|
+
const now = Date.now();
|
|
227
|
+
const ratio7d = quota.limit7d > 0 && Number.isFinite(quota.limit7d) ? quota.usage7d / quota.limit7d : 0;
|
|
228
|
+
const ratio5h = quota.limit5h > 0 && Number.isFinite(quota.limit5h) ? quota.usage5h / quota.limit5h : 0;
|
|
229
|
+
|
|
230
|
+
if (ratio7d >= threshold && quota.resetAt7d) {
|
|
231
|
+
const resetTime = new Date(quota.resetAt7d).getTime();
|
|
232
|
+
if (resetTime > now) return { cooldownMs: resetTime - now, window: "7d" };
|
|
233
|
+
}
|
|
234
|
+
if (ratio5h >= threshold && quota.resetAt5h) {
|
|
235
|
+
const resetTime = new Date(quota.resetAt5h).getTime();
|
|
236
|
+
if (resetTime > now) return { cooldownMs: resetTime - now, window: "5h" };
|
|
237
|
+
}
|
|
238
|
+
return { cooldownMs: 0, window: "none" };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// ─── Inlined: codex/tools.ts ────────────────────────────────────────────────
|
|
242
|
+
// Codex Responses-API tool normalization (hosted-tool passthrough + free-plan gating).
|
|
243
|
+
|
|
244
|
+
export const CODEX_HOSTED_TOOL_TYPES = new Set([
|
|
245
|
+
"tool_search", "image_generation", "web_search", "web_search_preview",
|
|
246
|
+
"file_search", "computer", "computer_use_preview", "code_interpreter", "mcp",
|
|
247
|
+
]);
|
|
248
|
+
|
|
249
|
+
export function isCodexFreePlan(providerSpecificData) {
|
|
250
|
+
if (!providerSpecificData || typeof providerSpecificData !== "object") return false;
|
|
251
|
+
const plan = providerSpecificData.workspacePlanType;
|
|
252
|
+
return typeof plan === "string" && plan.trim().toLowerCase() === "free";
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function normalizeCodexTools(body, options) {
|
|
256
|
+
if (!Array.isArray(body.tools)) return;
|
|
257
|
+
const dropImageGen = options?.dropImageGeneration;
|
|
258
|
+
const preserveCustom = options?.preserveCustomTools;
|
|
259
|
+
|
|
260
|
+
const validToolNames = new Set();
|
|
261
|
+
body.tools = body.tools.filter((toolValue) => {
|
|
262
|
+
if (!toolValue || typeof toolValue !== "object" || Array.isArray(toolValue)) return false;
|
|
263
|
+
|
|
264
|
+
const toolType = typeof toolValue.type === "string" ? toolValue.type : "";
|
|
265
|
+
|
|
266
|
+
// Preserve namespace tools (MCP tool groups)
|
|
267
|
+
if (toolType === "namespace") {
|
|
268
|
+
if (Array.isArray(toolValue.tools)) {
|
|
269
|
+
for (const st of toolValue.tools) {
|
|
270
|
+
if (st && typeof st === "object" && !Array.isArray(st)) {
|
|
271
|
+
const name = typeof st.name === "string" ? st.name.trim().slice(0, 128) : "";
|
|
272
|
+
if (name) validToolNames.add(name);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return true;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// Native Codex clients send Responses API custom tools (apply_patch etc.)
|
|
280
|
+
if (toolType === "custom" && preserveCustom === true) {
|
|
281
|
+
const name = typeof toolValue.name === "string" ? toolValue.name.trim().slice(0, 128) : "";
|
|
282
|
+
if (!name) return false;
|
|
283
|
+
toolValue.name = name;
|
|
284
|
+
validToolNames.add(name);
|
|
285
|
+
return true;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (toolType !== "function") {
|
|
289
|
+
// Not a function tool — check if it's a known hosted tool
|
|
290
|
+
const hasFunctionObject = toolValue.function && typeof toolValue.function === "object";
|
|
291
|
+
const hasName = typeof toolValue.name === "string";
|
|
292
|
+
if (!toolType || hasFunctionObject || hasName) return false;
|
|
293
|
+
if (CODEX_HOSTED_TOOL_TYPES.has(toolType)) {
|
|
294
|
+
if (toolType === "image_generation" && dropImageGen) return false;
|
|
295
|
+
return true;
|
|
296
|
+
}
|
|
297
|
+
console.debug(`[Codex] dropping unknown hosted tool type: ${toolType}`);
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// Function tool — flatten Chat Completions shape into Responses flat format
|
|
302
|
+
const rawName = typeof toolValue.name === "string"
|
|
303
|
+
? toolValue.name
|
|
304
|
+
: toolValue.function && typeof toolValue.function === "object" && !Array.isArray(toolValue.function) && typeof toolValue.function.name === "string"
|
|
305
|
+
? toolValue.function.name
|
|
306
|
+
: "";
|
|
307
|
+
const name = rawName.trim();
|
|
308
|
+
if (!name) return false;
|
|
309
|
+
|
|
310
|
+
const fn = toolValue.function && typeof toolValue.function === "object" && !Array.isArray(toolValue.function)
|
|
311
|
+
? toolValue.function : null;
|
|
312
|
+
const description = typeof toolValue.description === "string"
|
|
313
|
+
? toolValue.description
|
|
314
|
+
: typeof fn?.description === "string" ? fn.description : "";
|
|
315
|
+
const parameters = (toolValue.parameters && typeof toolValue.parameters === "object" && !Array.isArray(toolValue.parameters))
|
|
316
|
+
? toolValue.parameters
|
|
317
|
+
: (fn?.parameters && typeof fn.parameters === "object" && !Array.isArray(fn.parameters)
|
|
318
|
+
? fn.parameters
|
|
319
|
+
: { type: "object", properties: {} });
|
|
320
|
+
const strict = typeof toolValue.strict === "boolean"
|
|
321
|
+
? toolValue.strict
|
|
322
|
+
: typeof fn?.strict === "boolean" ? fn.strict : undefined;
|
|
323
|
+
|
|
324
|
+
// Rewrite in-place to Responses format
|
|
325
|
+
for (const key of Object.keys(toolValue)) delete toolValue[key];
|
|
326
|
+
toolValue.type = "function";
|
|
327
|
+
toolValue.name = name.slice(0, 128);
|
|
328
|
+
if (description) toolValue.description = description;
|
|
329
|
+
toolValue.parameters = parameters;
|
|
330
|
+
if (strict !== undefined) toolValue.strict = strict;
|
|
331
|
+
|
|
332
|
+
validToolNames.add(name);
|
|
333
|
+
return true;
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
// Drop tool_choice if it references an unknown function name
|
|
337
|
+
if (body.tool_choice && typeof body.tool_choice === "object" && !Array.isArray(body.tool_choice)) {
|
|
338
|
+
if (body.tool_choice.type === "function") {
|
|
339
|
+
const n = typeof body.tool_choice.name === "string" ? body.tool_choice.name.trim() : "";
|
|
340
|
+
if (!n || !validToolNames.has(n)) delete body.tool_choice;
|
|
341
|
+
} else if (body.tool_choice.type === "local_shell") {
|
|
342
|
+
delete body.tool_choice;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
// ─── Core utility functions ─────────────────────────────────────────────────
|
|
347
|
+
|
|
348
|
+
// wreq-js is a Rust-native module that requires platform-specific .node binaries.
|
|
349
|
+
// Lazy-load with try/catch to gracefully fall back to HTTP when WebSocket unavailable.
|
|
350
|
+
const _wreqRequire = createRequire(import.meta.url);
|
|
351
|
+
|
|
352
|
+
let _websocketFn = null;
|
|
353
|
+
let _wreqChecked = false;
|
|
354
|
+
let _websocketOverride;
|
|
355
|
+
|
|
356
|
+
function getCodexWebSocketTransport() {
|
|
357
|
+
if (_websocketOverride !== undefined) return _websocketOverride;
|
|
358
|
+
if (_wreqChecked) return _websocketFn;
|
|
359
|
+
_wreqChecked = true;
|
|
360
|
+
try {
|
|
361
|
+
const mod = _wreqRequire("wreq-js");
|
|
362
|
+
_websocketFn = typeof mod.websocket === "function" ? mod.websocket : null;
|
|
363
|
+
} catch {
|
|
364
|
+
console.warn("[codex] wreq-js import failed, websocket disabled");
|
|
365
|
+
_websocketFn = null;
|
|
366
|
+
}
|
|
367
|
+
return _websocketFn;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
export function __setCodexWebSocketTransportForTesting(websocket) {
|
|
371
|
+
_websocketOverride = websocket;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function codexWebSocketUnavailableResponse() {
|
|
375
|
+
return new Response(
|
|
376
|
+
JSON.stringify({
|
|
377
|
+
error: {
|
|
378
|
+
code: "wreq_unavailable",
|
|
379
|
+
message: "Codex WebSocket transport unavailable: wreq-js native module is missing for this platform",
|
|
380
|
+
},
|
|
381
|
+
}),
|
|
382
|
+
{
|
|
383
|
+
status: 503,
|
|
384
|
+
headers: { "Content-Type": "application/json", ...CORS_HEADERS },
|
|
385
|
+
},
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function splitCodexReasoningSuffix(model) {
|
|
390
|
+
const modelId = typeof model === "string" ? model : "";
|
|
391
|
+
for (const level of EFFORT_ORDER) {
|
|
392
|
+
if (modelId.endsWith(`-${level}`)) {
|
|
393
|
+
return { baseModel: modelId.slice(0, -`-${level}`.length), effort: level };
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
return { baseModel: modelId, effort: null };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export function getCodexUpstreamModel(model) {
|
|
400
|
+
return splitCodexReasoningSuffix(model).baseModel;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// Convert role=system → role=developer in body.input (GPT-5 cache-aware)
|
|
404
|
+
function convertSystemToDeveloperRole(body) {
|
|
405
|
+
if (!Array.isArray(body.input)) return;
|
|
406
|
+
for (const itemValue of body.input) {
|
|
407
|
+
if (!itemValue || typeof itemValue !== "object" || Array.isArray(itemValue)) continue;
|
|
408
|
+
const role = typeof itemValue.role === "string" ? itemValue.role : "";
|
|
409
|
+
const type = typeof itemValue.type === "string" ? itemValue.type : "";
|
|
410
|
+
if (role === "system" && (!type || type === "message")) {
|
|
411
|
+
itemValue.role = "developer";
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// Strip server-generated item IDs from input — avoids 404 with store=false.
|
|
417
|
+
// Also strips reasoning blobs and empty input repair.
|
|
418
|
+
export function stripStoredItemReferences(body) {
|
|
419
|
+
if (Array.isArray(body.input) && body.input.length === 0) {
|
|
420
|
+
body.input = [
|
|
421
|
+
{ type: "message", role: "user", content: [{ type: "input_text", text: "continue" }] },
|
|
422
|
+
];
|
|
423
|
+
}
|
|
424
|
+
if (!Array.isArray(body.input)) return;
|
|
425
|
+
|
|
426
|
+
let strippedCount = 0;
|
|
427
|
+
body.input = body.input.filter((item) => {
|
|
428
|
+
// Bare string references: "rs_abc123"
|
|
429
|
+
if (typeof item === "string" && SERVER_ID_PATTERN.test(item)) {
|
|
430
|
+
strippedCount++;
|
|
431
|
+
return false;
|
|
432
|
+
}
|
|
433
|
+
// Object references: { type: "item_reference", id: "rs_..." }
|
|
434
|
+
if (item && typeof item === "object" && !Array.isArray(item) && item.type === "item_reference") {
|
|
435
|
+
strippedCount++;
|
|
436
|
+
return false;
|
|
437
|
+
}
|
|
438
|
+
// Reasoning blobs (encrypted_content) unusable with store=false
|
|
439
|
+
if (item && typeof item === "object" && !Array.isArray(item) && item.type === "reasoning") {
|
|
440
|
+
strippedCount++;
|
|
441
|
+
return false;
|
|
442
|
+
}
|
|
443
|
+
// Object items with server-generated IDs: strip the id field but keep the item
|
|
444
|
+
if (item && typeof item === "object" && !Array.isArray(item)) {
|
|
445
|
+
if (typeof item.id === "string" && SERVER_ID_PATTERN.test(item.id)) {
|
|
446
|
+
delete item.id;
|
|
447
|
+
strippedCount++;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
return true;
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
if (strippedCount > 0) {
|
|
454
|
+
console.debug(`[Codex] stripStoredItemReferences: sanitized ${strippedCount} server-generated ID(s) from input`);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// Repair missing function_call_output items (some clients omit them)
|
|
459
|
+
function repairMissingCodexFunctionCallOutputs(body) {
|
|
460
|
+
if (!Array.isArray(body.input)) return;
|
|
461
|
+
const existingOutputIds = new Set();
|
|
462
|
+
for (const item of body.input) {
|
|
463
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) continue;
|
|
464
|
+
if (item.type !== "function_call_output") continue;
|
|
465
|
+
if (typeof item.call_id === "string" && item.call_id.trim()) {
|
|
466
|
+
existingOutputIds.add(item.call_id.trim());
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
const repaired = [];
|
|
470
|
+
let insertedCount = 0;
|
|
471
|
+
for (const item of body.input) {
|
|
472
|
+
repaired.push(item);
|
|
473
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) continue;
|
|
474
|
+
if (item.type !== "function_call") continue;
|
|
475
|
+
const callId = typeof item.call_id === "string" ? item.call_id.trim() : "";
|
|
476
|
+
if (!callId || existingOutputIds.has(callId)) continue;
|
|
477
|
+
repaired.push({ type: "function_call_output", call_id: callId, output: "" });
|
|
478
|
+
existingOutputIds.add(callId);
|
|
479
|
+
insertedCount++;
|
|
480
|
+
}
|
|
481
|
+
if (insertedCount > 0) {
|
|
482
|
+
body.input = repaired;
|
|
483
|
+
console.debug(`[Codex] repairMissingCodexFunctionCallOutputs: inserted ${insertedCount} empty function_call_output item(s)`);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function getResponsesSubpath(endpointPath) {
|
|
488
|
+
let normalizedEndpoint = String(endpointPath || "");
|
|
489
|
+
while (normalizedEndpoint.endsWith("/") && normalizedEndpoint.length > 0) {
|
|
490
|
+
normalizedEndpoint = normalizedEndpoint.slice(0, -1);
|
|
491
|
+
}
|
|
492
|
+
const lower = normalizedEndpoint.toLowerCase();
|
|
493
|
+
if (lower === "responses" || lower.endsWith("/responses")) return "";
|
|
494
|
+
const responsesSlash = "/responses/";
|
|
495
|
+
const idx = lower.lastIndexOf(responsesSlash);
|
|
496
|
+
if (idx !== -1) return normalizedEndpoint.slice(idx + "/responses".length);
|
|
497
|
+
if (lower.startsWith("responses/")) return normalizedEndpoint.slice("responses".length);
|
|
498
|
+
return null;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
export function isCompactResponsesEndpoint(endpointPath) {
|
|
502
|
+
return getResponsesSubpath(endpointPath)?.toLowerCase() === "/compact";
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function normalizeServiceTierValue(value) {
|
|
506
|
+
if (typeof value !== "string") return undefined;
|
|
507
|
+
const normalized = value.trim().toLowerCase();
|
|
508
|
+
if (!normalized) return undefined;
|
|
509
|
+
if (normalized === "fast") return CODEX_FAST_WIRE_VALUE;
|
|
510
|
+
return normalized;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function normalizeEffortValue(value) {
|
|
514
|
+
if (typeof value !== "string") return undefined;
|
|
515
|
+
const normalized = value.trim().toLowerCase();
|
|
516
|
+
if (normalized === "max") return "xhigh";
|
|
517
|
+
return normalized || undefined;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
function clampEffort(model, requested) {
|
|
521
|
+
const max = MAX_EFFORT_BY_MODEL[model] ?? "xhigh";
|
|
522
|
+
const reqIdx = EFFORT_ORDER.indexOf(requested);
|
|
523
|
+
const maxIdx = EFFORT_ORDER.indexOf(max);
|
|
524
|
+
if (reqIdx > maxIdx) {
|
|
525
|
+
console.debug(`[Codex] clampEffort: "${requested}" → "${max}" (model: ${model})`);
|
|
526
|
+
return max;
|
|
527
|
+
}
|
|
528
|
+
return requested;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function ensureCodexReasoningSummary(body) {
|
|
532
|
+
const reasoning = body.reasoning && typeof body.reasoning === "object" && !Array.isArray(body.reasoning)
|
|
533
|
+
? body.reasoning : null;
|
|
534
|
+
if (!reasoning || normalizeEffortValue(reasoning.effort) === "none") return;
|
|
535
|
+
if (!("summary" in reasoning)) reasoning.summary = CODEX_DEFAULT_REASONING_SUMMARY;
|
|
536
|
+
if (!Array.isArray(body.include)) {
|
|
537
|
+
body.include = [CODEX_REASONING_ENCRYPTED_CONTENT_INCLUDE];
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
if (!body.include.includes(CODEX_REASONING_ENCRYPTED_CONTENT_INCLUDE)) {
|
|
541
|
+
body.include = [...body.include, CODEX_REASONING_ENCRYPTED_CONTENT_INCLUDE];
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function consumeResponsesStoreMarker(body) {
|
|
546
|
+
const marker = body._omnirouteResponsesStore;
|
|
547
|
+
delete body._omnirouteResponsesStore;
|
|
548
|
+
return marker;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// Global Codex WebSocket kill-switch (default ON in AMRouter)
|
|
552
|
+
function isCodexWsGloballyEnabled() {
|
|
553
|
+
try {
|
|
554
|
+
const v = process.env.AMROUTER_CODEX_WS_ENABLED;
|
|
555
|
+
if (v === "false" || v === "0") return false;
|
|
556
|
+
} catch { /* noop */ }
|
|
557
|
+
return true;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
export function isCodexResponsesWebSocketRequired(_model, credentials) {
|
|
561
|
+
if (!isCodexWsGloballyEnabled()) return false;
|
|
562
|
+
const psd = credentials && typeof credentials === "object" ? credentials.providerSpecificData : null;
|
|
563
|
+
return !!(psd?.codexTransport === "websocket" && getCodexWebSocketTransport());
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function toStatusCode(value) {
|
|
567
|
+
if (typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599) return value;
|
|
568
|
+
if (typeof value === "string" && /^\d{3}$/.test(value.trim())) {
|
|
569
|
+
const parsed = Number(value.trim());
|
|
570
|
+
return parsed >= 400 && parsed <= 599 ? parsed : null;
|
|
571
|
+
}
|
|
572
|
+
return null;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
function looksLikeQuotaOrRateLimit(code, type, message) {
|
|
576
|
+
const haystack = `${code} ${type} ${message}`.toLowerCase();
|
|
577
|
+
return (
|
|
578
|
+
haystack.includes("usage_limit_reached") ||
|
|
579
|
+
haystack.includes("rate_limit") ||
|
|
580
|
+
haystack.includes("rate limit") ||
|
|
581
|
+
haystack.includes("quota") ||
|
|
582
|
+
haystack.includes("too many requests") ||
|
|
583
|
+
haystack.includes("limit has been reached") ||
|
|
584
|
+
haystack.includes("limit reached")
|
|
585
|
+
);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function toCodexResponseFailedEvent(parsed) {
|
|
589
|
+
const response = parsed.response && typeof parsed.response === "object" && !Array.isArray(parsed.response)
|
|
590
|
+
? parsed.response : null;
|
|
591
|
+
const upstreamError = response?.error && typeof response.error === "object" && !Array.isArray(response.error)
|
|
592
|
+
? response.error
|
|
593
|
+
: parsed.error && typeof parsed.error === "object" && !Array.isArray(parsed.error)
|
|
594
|
+
? parsed.error
|
|
595
|
+
: parsed;
|
|
596
|
+
const code = typeof upstreamError.code === "string" ? upstreamError.code
|
|
597
|
+
: typeof upstreamError.type === "string" ? upstreamError.type : "upstream_error";
|
|
598
|
+
const type = typeof upstreamError.type === "string" ? upstreamError.type : "";
|
|
599
|
+
const message = typeof upstreamError.message === "string" && upstreamError.message.trim()
|
|
600
|
+
? upstreamError.message : "Codex upstream error";
|
|
601
|
+
const error = { code, message };
|
|
602
|
+
const explicitStatus = toStatusCode(parsed.status_code) ?? toStatusCode(parsed.status) ??
|
|
603
|
+
toStatusCode(response?.status_code) ?? toStatusCode(response?.status) ??
|
|
604
|
+
toStatusCode(upstreamError.status_code) ?? toStatusCode(upstreamError.status);
|
|
605
|
+
const statusCode = explicitStatus ?? (looksLikeQuotaOrRateLimit(code, type, message) ? 429 : null);
|
|
606
|
+
if (type) error.type = type;
|
|
607
|
+
if (statusCode !== null) error.status_code = statusCode;
|
|
608
|
+
return {
|
|
609
|
+
type: "response.failed",
|
|
610
|
+
response: { id: typeof response?.id === "string" ? response.id : null, status: "failed", error },
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// Env-gated kill-switch: drop non-standard codex.* SSE events
|
|
615
|
+
function codexDropNonstandardEvents() {
|
|
616
|
+
const v = process.env.AMROUTER_CODEX_DROP_NONSTANDARD_EVENTS;
|
|
617
|
+
return v === "true" || v === "1" || v === "yes";
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
export function filterNonstandardCodexSse(response) {
|
|
621
|
+
const contentType = response.headers.get("content-type") || "";
|
|
622
|
+
if (!response.body || !contentType.includes("text/event-stream")) return response;
|
|
623
|
+
const decoder = new TextDecoder();
|
|
624
|
+
const encoder = new TextEncoder();
|
|
625
|
+
let buffer = "";
|
|
626
|
+
const dropBlock = (block) => {
|
|
627
|
+
const match = /^event:\s*(.+)$/m.exec(block);
|
|
628
|
+
return !!match && match[1].trim().startsWith("codex.");
|
|
629
|
+
};
|
|
630
|
+
const transform = new TransformStream({
|
|
631
|
+
transform(chunk, controller) {
|
|
632
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
633
|
+
let sep;
|
|
634
|
+
while ((sep = buffer.indexOf("\n\n")) !== -1) {
|
|
635
|
+
const block = buffer.slice(0, sep + 2);
|
|
636
|
+
buffer = buffer.slice(sep + 2);
|
|
637
|
+
if (!dropBlock(block)) controller.enqueue(encoder.encode(block));
|
|
638
|
+
}
|
|
639
|
+
},
|
|
640
|
+
flush(controller) {
|
|
641
|
+
if (buffer && !dropBlock(buffer)) controller.enqueue(encoder.encode(buffer));
|
|
642
|
+
},
|
|
643
|
+
});
|
|
644
|
+
return new Response(response.body.pipeThrough(transform), {
|
|
645
|
+
status: response.status,
|
|
646
|
+
statusText: response.statusText,
|
|
647
|
+
headers: response.headers,
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
export function encodeResponseSseEvent(raw) {
|
|
652
|
+
let eventType = "message";
|
|
653
|
+
let payload = raw;
|
|
654
|
+
let terminal = false;
|
|
655
|
+
try {
|
|
656
|
+
const parsed = JSON.parse(raw);
|
|
657
|
+
if (parsed && typeof parsed.type === "string" && parsed.type.trim()) {
|
|
658
|
+
eventType = parsed.type.trim();
|
|
659
|
+
if (eventType === "error" || eventType === "response.failed") {
|
|
660
|
+
const failed = toCodexResponseFailedEvent(parsed);
|
|
661
|
+
payload = JSON.stringify(failed);
|
|
662
|
+
eventType = "response.failed";
|
|
663
|
+
}
|
|
664
|
+
terminal = eventType === "response.completed" || eventType === "response.failed";
|
|
665
|
+
}
|
|
666
|
+
} catch {
|
|
667
|
+
console.warn("[codex] SSE payload parse failed, using raw payload");
|
|
668
|
+
}
|
|
669
|
+
if (eventType.startsWith("codex.") && codexDropNonstandardEvents()) {
|
|
670
|
+
return { sse: "", terminal };
|
|
671
|
+
}
|
|
672
|
+
if (!payload.trim()) return { sse: "", terminal };
|
|
673
|
+
return { sse: `event: ${eventType}\ndata: ${payload}\n\n`, terminal };
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
function toWebSocketUrl(url) {
|
|
677
|
+
if (/^wss?:\/\//.test(url)) return url;
|
|
678
|
+
if (url.startsWith("https:")) return url.replace(/^https:/, "wss:");
|
|
679
|
+
if (url.startsWith("http:")) return url.replace(/^http:/, "ws:");
|
|
680
|
+
return CODEX_RESPONSES_WS_URL;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function normalizeCodexWsHeaders(headers) {
|
|
684
|
+
const result = {};
|
|
685
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
686
|
+
const lower = key.toLowerCase();
|
|
687
|
+
if (lower === "host" || lower === "connection" || lower === "upgrade" ||
|
|
688
|
+
lower === "sec-websocket-key" || lower === "sec-websocket-version" ||
|
|
689
|
+
lower === "sec-websocket-extensions") continue;
|
|
690
|
+
result[key] = value;
|
|
691
|
+
}
|
|
692
|
+
result.Origin = "https://chatgpt.com";
|
|
693
|
+
return result;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// Resolve prompt-cache session id for AMRouter
|
|
697
|
+
function resolveCacheSessionId(body, credentials) {
|
|
698
|
+
return resolveSessionId({
|
|
699
|
+
headers: credentials?.rawHeaders,
|
|
700
|
+
body,
|
|
701
|
+
connectionId: credentials?.connectionId,
|
|
702
|
+
workspaceId: credentials?.providerSpecificData?.workspaceId,
|
|
703
|
+
scope: "codex",
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
// ─── CodexExecutor class ────────────────────────────────────────────────────
|
|
707
|
+
|
|
708
|
+
export class CodexExecutor extends BaseExecutor {
|
|
709
|
+
constructor() {
|
|
710
|
+
super("codex", PROVIDERS.codex);
|
|
711
|
+
this._currentSessionId = null;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// ── execute: SSE retry loop + WebSocket transport support ──────────────
|
|
715
|
+
|
|
716
|
+
async execute(args) {
|
|
717
|
+
const imgCount = Array.isArray(args.body?.input)
|
|
718
|
+
? args.body.input.reduce((n, it) => n + (Array.isArray(it.content) ? it.content.filter(c => c.type === "image_url").length : 0), 0)
|
|
719
|
+
: 0;
|
|
720
|
+
const inputLen = Array.isArray(args.body?.input) ? args.body.input.length : 0;
|
|
721
|
+
dbg("CODEX", `execute start | inputItems=${inputLen} | images=${imgCount} | sessionId=${this._currentSessionId || "pending"}`);
|
|
722
|
+
|
|
723
|
+
// Prefetch remote images as base64 (Codex backend can't fetch them)
|
|
724
|
+
await this.prefetchImages(args.body);
|
|
725
|
+
|
|
726
|
+
// WebSocket transport path — opt-in via providerSpecificData.codexTransport
|
|
727
|
+
const sessionId = this.getPromptCacheSessionId(args.credentials, args.body);
|
|
728
|
+
const identity = createCodexClientIdentity(sessionId, args.credentials?.providerSpecificData ?? null);
|
|
729
|
+
const credentials = identity
|
|
730
|
+
? {
|
|
731
|
+
...args.credentials,
|
|
732
|
+
providerSpecificData: {
|
|
733
|
+
...(args.credentials?.providerSpecificData || {}),
|
|
734
|
+
codexClientIdentity: identity,
|
|
735
|
+
},
|
|
736
|
+
}
|
|
737
|
+
: args.credentials;
|
|
738
|
+
const nextArgs = { ...args, credentials };
|
|
739
|
+
|
|
740
|
+
if (!isCodexResponsesWebSocketRequired(nextArgs.model, nextArgs.credentials)) {
|
|
741
|
+
// HTTP SSE path with retry loop
|
|
742
|
+
return this._executeWithRetry(nextArgs);
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
// WebSocket path
|
|
746
|
+
return this._executeWebSocket(nextArgs);
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
async _executeWithRetry(args) {
|
|
750
|
+
// Retry loop for SSE-level overloaded errors (200 OK body contains event: error)
|
|
751
|
+
const retryConfig = { ...DEFAULT_RETRY_CONFIG, ...this.config.retry };
|
|
752
|
+
const { attempts, delayMs } = resolveRetryEntry(retryConfig[503]);
|
|
753
|
+
let attempt = 0;
|
|
754
|
+
while (true) {
|
|
755
|
+
const result = await super.execute(args);
|
|
756
|
+
const peek = await this._peekSseTransientError(result.response);
|
|
757
|
+
if (!peek.matched) {
|
|
758
|
+
if (peek.replacementBody) {
|
|
759
|
+
result.response = new Response(peek.replacementBody, {
|
|
760
|
+
status: result.response.status,
|
|
761
|
+
statusText: result.response.statusText,
|
|
762
|
+
headers: result.response.headers,
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
// Filter non-standard codex.* events if kill-switch is on
|
|
766
|
+
if (codexDropNonstandardEvents()) {
|
|
767
|
+
const resp = result.response;
|
|
768
|
+
if (resp?.body) {
|
|
769
|
+
result.response = filterNonstandardCodexSse(resp);
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
return result;
|
|
773
|
+
}
|
|
774
|
+
if (peek.accountFallback) {
|
|
775
|
+
args.log?.warn?.("RETRY", `CODEX | SSE account fallback "${peek.message}"`);
|
|
776
|
+
result.response = this._codexSseErrorResponse(HTTP_STATUS.SERVICE_UNAVAILABLE, peek.message || "Selected model is at capacity.");
|
|
777
|
+
return result;
|
|
778
|
+
}
|
|
779
|
+
if (attempt >= attempts) {
|
|
780
|
+
args.log?.warn?.("RETRY", `CODEX | SSE overloaded "${peek.matched}" — retries exhausted (${attempt}/${attempts})`);
|
|
781
|
+
result.response = this._codexSseErrorResponse(HTTP_STATUS.SERVICE_UNAVAILABLE, peek.message || peek.matched);
|
|
782
|
+
return result;
|
|
783
|
+
}
|
|
784
|
+
attempt++;
|
|
785
|
+
args.log?.debug?.("RETRY", `CODEX | SSE "${peek.matched}" retry ${attempt}/${attempts} after ${delayMs / 1000}s`);
|
|
786
|
+
dbg("CODEX", `SSE overloaded "${peek.matched}" → retry ${attempt}/${attempts} in ${delayMs}ms`);
|
|
787
|
+
await new Promise(r => setTimeout(r, delayMs));
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
async _executeWebSocket(args) {
|
|
792
|
+
const url = CODEX_RESPONSES_WS_URL;
|
|
793
|
+
const headers = normalizeCodexWsHeaders(this.buildHeaders(args.credentials, true));
|
|
794
|
+
|
|
795
|
+
// Merge extra headers if provided
|
|
796
|
+
if (args.upstreamExtraHeaders && typeof args.upstreamExtraHeaders === "object") {
|
|
797
|
+
for (const [k, v] of Object.entries(args.upstreamExtraHeaders)) {
|
|
798
|
+
if (typeof v === "string") headers[k] = v;
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
const transformedBody = await this.transformRequest(args.model, args.body, true, args.credentials);
|
|
803
|
+
transformedBody.model = getCodexUpstreamModel(transformedBody.model || args.model);
|
|
804
|
+
delete transformedBody.stream;
|
|
805
|
+
delete transformedBody.stream_options;
|
|
806
|
+
|
|
807
|
+
const bodyString = JSON.stringify({ type: "response.create", ...transformedBody });
|
|
808
|
+
|
|
809
|
+
const websocketFn = getCodexWebSocketTransport();
|
|
810
|
+
if (!websocketFn) {
|
|
811
|
+
return { response: codexWebSocketUnavailableResponse(), url, headers, transformedBody };
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
const encoder = new TextEncoder();
|
|
815
|
+
let closed = false;
|
|
816
|
+
let ws = null;
|
|
817
|
+
let streamController = null;
|
|
818
|
+
|
|
819
|
+
const closeUpstream = (reason) => {
|
|
820
|
+
try { ws?.close(1000, reason); } catch { /* ignore close races */ }
|
|
821
|
+
};
|
|
822
|
+
|
|
823
|
+
let abortHandler = null;
|
|
824
|
+
const removeAbortListener = () => {
|
|
825
|
+
if (!abortHandler) return;
|
|
826
|
+
args.signal?.removeEventListener("abort", abortHandler);
|
|
827
|
+
abortHandler = null;
|
|
828
|
+
};
|
|
829
|
+
|
|
830
|
+
const finishStream = ({ reason, emitDone = true, closeController = true, closeSocket = true }) => {
|
|
831
|
+
if (closed) return;
|
|
832
|
+
closed = true;
|
|
833
|
+
removeAbortListener();
|
|
834
|
+
if (closeSocket) closeUpstream(reason);
|
|
835
|
+
const controller = streamController;
|
|
836
|
+
if (!controller || !closeController) return;
|
|
837
|
+
if (emitDone) {
|
|
838
|
+
try { controller.enqueue(encoder.encode("data: [DONE]\n\n")); } catch { /* downstream may be gone */ }
|
|
839
|
+
}
|
|
840
|
+
try { controller.close(); } catch { /* controller may already be closed */ }
|
|
841
|
+
};
|
|
842
|
+
|
|
843
|
+
const failController = (code, message) => {
|
|
844
|
+
if (closed) return;
|
|
845
|
+
const controller = streamController;
|
|
846
|
+
const payload = JSON.stringify({
|
|
847
|
+
type: "response.failed",
|
|
848
|
+
response: { id: null, status: "failed", error: { code, message } },
|
|
849
|
+
});
|
|
850
|
+
try { controller?.enqueue(encoder.encode(`event: response.failed\ndata: ${payload}\n\n`)); } catch { /* downstream closed */ }
|
|
851
|
+
finishStream({ reason: "upstream_failed" });
|
|
852
|
+
};
|
|
853
|
+
|
|
854
|
+
const stream = new ReadableStream({
|
|
855
|
+
async start(controller) {
|
|
856
|
+
streamController = controller;
|
|
857
|
+
abortHandler = () => finishStream({ reason: "client_aborted" });
|
|
858
|
+
args.signal?.addEventListener("abort", abortHandler, { once: true });
|
|
859
|
+
|
|
860
|
+
try {
|
|
861
|
+
ws = await websocketFn(toWebSocketUrl(url), { browser: "chrome_142", os: "windows", headers });
|
|
862
|
+
if (closed) return;
|
|
863
|
+
if (args.signal?.aborted) { finishStream({ reason: "client_aborted" }); return; }
|
|
864
|
+
|
|
865
|
+
ws.onmessage = (event) => {
|
|
866
|
+
if (closed) return;
|
|
867
|
+
const raw = typeof event.data === "string"
|
|
868
|
+
? event.data
|
|
869
|
+
: Buffer.from(event.data).toString("utf8");
|
|
870
|
+
const sseEvent = encodeResponseSseEvent(raw);
|
|
871
|
+
if (closed) return;
|
|
872
|
+
if (sseEvent.sse) {
|
|
873
|
+
try { controller.enqueue(encoder.encode(sseEvent.sse)); } catch {
|
|
874
|
+
finishStream({ reason: "downstream_closed", emitDone: false, closeController: false });
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
if (sseEvent.terminal) finishStream({ reason: "terminal_event" });
|
|
879
|
+
};
|
|
880
|
+
ws.onerror = (event) => {
|
|
881
|
+
failController("upstream_websocket_error", event.message || "Codex upstream WebSocket error");
|
|
882
|
+
};
|
|
883
|
+
ws.onclose = () => {
|
|
884
|
+
finishStream({ reason: "upstream_closed", closeSocket: false });
|
|
885
|
+
};
|
|
886
|
+
if (!closed) {
|
|
887
|
+
await prl.captureCurrentProviderBody(url, headers, bodyString, args.log);
|
|
888
|
+
ws.send(bodyString);
|
|
889
|
+
}
|
|
890
|
+
} catch (error) {
|
|
891
|
+
failController("upstream_websocket_connect_failed", error instanceof Error ? error.message : String(error));
|
|
892
|
+
}
|
|
893
|
+
},
|
|
894
|
+
cancel() {
|
|
895
|
+
finishStream({ reason: "client_cancelled", emitDone: false, closeController: false });
|
|
896
|
+
},
|
|
897
|
+
});
|
|
898
|
+
|
|
899
|
+
return {
|
|
900
|
+
response: new Response(stream, {
|
|
901
|
+
status: 200,
|
|
902
|
+
headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" },
|
|
903
|
+
}),
|
|
904
|
+
url, headers, transformedBody,
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// ── Prefetch remote images as base64 ──────────────────────────────────
|
|
909
|
+
|
|
910
|
+
async prefetchImages(body) {
|
|
911
|
+
if (!Array.isArray(body?.input)) return;
|
|
912
|
+
for (const item of body.input) {
|
|
913
|
+
if (!Array.isArray(item.content)) continue;
|
|
914
|
+
const pending = item.content.map(async (c) => {
|
|
915
|
+
if (c.type !== "image_url") return c;
|
|
916
|
+
const url = typeof c.image_url === "string" ? c.image_url : c.image_url?.url;
|
|
917
|
+
const detail = c.image_url?.detail || "auto";
|
|
918
|
+
if (!url) return c;
|
|
919
|
+
if (url.startsWith("data:")) return { type: "input_image", image_url: url, detail };
|
|
920
|
+
const fetched = await fetchImageAsBase64(url, { timeoutMs: 15000 });
|
|
921
|
+
return { type: "input_image", image_url: fetched?.url || url, detail };
|
|
922
|
+
});
|
|
923
|
+
item.content = await Promise.all(pending);
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// ── SSE transient error peek ──────────────────────────────────────────
|
|
928
|
+
|
|
929
|
+
async _peekSseTransientError(response) {
|
|
930
|
+
const CODEX_SSE_RETRY_PATTERNS = ["server_is_overloaded", "service_unavailable_error"];
|
|
931
|
+
const CODEX_SSE_ACCOUNT_FALLBACK_PATTERNS = ["selected model is at capacity", "model_at_capacity"];
|
|
932
|
+
const CODEX_SSE_USER_OUTPUT_PATTERNS = [
|
|
933
|
+
"event: response.output_text.delta", "event: response.function_call_arguments.delta",
|
|
934
|
+
'"type":"response.output_text.delta"', '"type":"response.function_call_arguments.delta"',
|
|
935
|
+
];
|
|
936
|
+
const CODEX_SSE_PEEK_BYTES = 256 * 1024;
|
|
937
|
+
|
|
938
|
+
if (!response || !response.ok || !response.body) return { matched: null, message: null, accountFallback: false, replacementBody: null };
|
|
939
|
+
const reader = response.body.getReader();
|
|
940
|
+
const decoder = new TextDecoder();
|
|
941
|
+
const chunks = [];
|
|
942
|
+
let text = "";
|
|
943
|
+
let matched = null;
|
|
944
|
+
let accountFallback = false;
|
|
945
|
+
try {
|
|
946
|
+
while (text.length < CODEX_SSE_PEEK_BYTES) {
|
|
947
|
+
const { done, value } = await reader.read();
|
|
948
|
+
if (done) break;
|
|
949
|
+
chunks.push(value);
|
|
950
|
+
text += decoder.decode(value, { stream: true });
|
|
951
|
+
const lowerText = text.toLowerCase();
|
|
952
|
+
const accountHit = CODEX_SSE_ACCOUNT_FALLBACK_PATTERNS.find(p => lowerText.includes(p));
|
|
953
|
+
if (accountHit) { matched = accountHit; accountFallback = true; break; }
|
|
954
|
+
const retryHit = CODEX_SSE_RETRY_PATTERNS.find(p => lowerText.includes(p));
|
|
955
|
+
if (retryHit) { matched = retryHit; break; }
|
|
956
|
+
if (CODEX_SSE_USER_OUTPUT_PATTERNS.some(p => lowerText.includes(p))) break;
|
|
957
|
+
}
|
|
958
|
+
} catch (e) {
|
|
959
|
+
dbg("CODEX", `peek read error: ${e.message}`);
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
if (matched) {
|
|
963
|
+
try { await reader.cancel(); } catch { /* noop */ }
|
|
964
|
+
try { reader.releaseLock(); } catch { /* noop */ }
|
|
965
|
+
return { matched, message: this._extractSseErrorMessage(text, matched), accountFallback, replacementBody: null };
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
reader.releaseLock();
|
|
969
|
+
const upstream = response.body;
|
|
970
|
+
let upstreamReader = null;
|
|
971
|
+
const replacementBody = new ReadableStream({
|
|
972
|
+
start(controller) {
|
|
973
|
+
for (const c of chunks) controller.enqueue(c);
|
|
974
|
+
upstreamReader = upstream.getReader();
|
|
975
|
+
},
|
|
976
|
+
async pull(controller) {
|
|
977
|
+
try {
|
|
978
|
+
const { done, value } = await upstreamReader.read();
|
|
979
|
+
if (done) { controller.close(); return; }
|
|
980
|
+
controller.enqueue(value);
|
|
981
|
+
} catch (e) { controller.error(e); }
|
|
982
|
+
},
|
|
983
|
+
cancel(reason) {
|
|
984
|
+
try { upstreamReader?.cancel(reason); } catch { /* noop */ }
|
|
985
|
+
},
|
|
986
|
+
});
|
|
987
|
+
return { matched: null, message: null, accountFallback: false, replacementBody };
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
_extractSseErrorMessage(text, fallback) {
|
|
991
|
+
const exact = text?.match(/Selected model is at capacity\. Please try a different model\./i)?.[0];
|
|
992
|
+
if (exact) return exact;
|
|
993
|
+
for (const line of String(text || "").split(/\r?\n/)) {
|
|
994
|
+
if (!line.startsWith("data:")) continue;
|
|
995
|
+
const data = line.slice(5).trim();
|
|
996
|
+
if (!data || data === "[DONE]") continue;
|
|
997
|
+
try {
|
|
998
|
+
const parsed = JSON.parse(data);
|
|
999
|
+
const message = this._findNestedMessage(parsed);
|
|
1000
|
+
if (message) return message;
|
|
1001
|
+
} catch { /* Ignore non-JSON */ }
|
|
1002
|
+
}
|
|
1003
|
+
return fallback || "Selected model is at capacity. Please try a different model.";
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
_findNestedMessage(value, depth = 0) {
|
|
1007
|
+
if (!value || depth > 6 || typeof value === "string") return null;
|
|
1008
|
+
if (Array.isArray(value)) {
|
|
1009
|
+
for (const item of value) { const f = this._findNestedMessage(item, depth + 1); if (f) return f; }
|
|
1010
|
+
return null;
|
|
1011
|
+
}
|
|
1012
|
+
if (typeof value !== "object") return null;
|
|
1013
|
+
if (typeof value.message === "string" && value.message.trim()) return value.message;
|
|
1014
|
+
if (typeof value.error?.message === "string" && value.error.message.trim()) return value.error.message;
|
|
1015
|
+
if (typeof value.response?.error?.message === "string" && value.response.error.message.trim()) return value.response.error.message;
|
|
1016
|
+
for (const child of Object.values(value)) { const f = this._findNestedMessage(child, depth + 1); if (f) return f; }
|
|
1017
|
+
return null;
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
_codexSseErrorResponse(status, message) {
|
|
1021
|
+
return new Response(JSON.stringify({
|
|
1022
|
+
error: {
|
|
1023
|
+
message,
|
|
1024
|
+
type: status >= 500 ? "server_error" : "invalid_request_error",
|
|
1025
|
+
code: status === HTTP_STATUS.SERVICE_UNAVAILABLE ? "service_unavailable" : "upstream_error",
|
|
1026
|
+
},
|
|
1027
|
+
}), { status, headers: { "Content-Type": "application/json" } });
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
// ── Header / URL builders ─────────────────────────────────────────────
|
|
1031
|
+
|
|
1032
|
+
buildUrl(model, stream, urlIndex = 0, credentials = null) {
|
|
1033
|
+
const responsesSubpath = getResponsesSubpath(credentials?.requestEndpointPath);
|
|
1034
|
+
if (responsesSubpath !== null) {
|
|
1035
|
+
const baseUrl = String(this.config.baseUrl || "").replace(/\/$/, "");
|
|
1036
|
+
if (baseUrl.endsWith("/responses")) return `${baseUrl}${responsesSubpath}`;
|
|
1037
|
+
return `${baseUrl}/responses${responsesSubpath}`;
|
|
1038
|
+
}
|
|
1039
|
+
if (this._isCompact) {
|
|
1040
|
+
const base = super.buildUrl(model, stream, urlIndex, credentials);
|
|
1041
|
+
return `${base}/compact`;
|
|
1042
|
+
}
|
|
1043
|
+
return super.buildUrl(model, stream, urlIndex, credentials);
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
buildHeaders(credentials, stream = true) {
|
|
1047
|
+
const isCompactRequest = isCompactResponsesEndpoint(credentials?.requestEndpointPath);
|
|
1048
|
+
const headers = super.buildHeaders(credentials, isCompactRequest ? false : true);
|
|
1049
|
+
|
|
1050
|
+
// Codex client version + user agent
|
|
1051
|
+
headers["Version"] = getCodexClientVersion();
|
|
1052
|
+
headers["User-Agent"] = getCodexUserAgent();
|
|
1053
|
+
|
|
1054
|
+
// Workspace binding header
|
|
1055
|
+
const workspaceId = credentials?.providerSpecificData?.workspaceId;
|
|
1056
|
+
if (typeof workspaceId === "string" && workspaceId) {
|
|
1057
|
+
headers["chatgpt-account-id"] = workspaceId;
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
// Also support chatgptAccountId / accountId as fallback
|
|
1061
|
+
const accountId = credentials?.providerSpecificData?.chatgptAccountId || credentials?.providerSpecificData?.accountId;
|
|
1062
|
+
if (typeof accountId === "string" && accountId && !headers["chatgpt-account-id"]) {
|
|
1063
|
+
headers["chatgpt-account-id"] = accountId;
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
// Originator header — identifies the client type to Codex backend
|
|
1067
|
+
if (!headers["originator"]) headers["originator"] = "codex_cli_rs";
|
|
1068
|
+
|
|
1069
|
+
// Session ID for prompt cache affinity
|
|
1070
|
+
const cacheSessionId = this.getPromptCacheSessionId(credentials, null);
|
|
1071
|
+
if (cacheSessionId) headers["session_id"] = cacheSessionId;
|
|
1072
|
+
|
|
1073
|
+
// Client identity headers
|
|
1074
|
+
const clientIdentity = credentials?.providerSpecificData?.codexClientIdentity;
|
|
1075
|
+
applyCodexClientIdentityHeaders(headers, clientIdentity);
|
|
1076
|
+
|
|
1077
|
+
return headers;
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
// ── Prompt cache session ID ───────────────────────────────────────────
|
|
1081
|
+
|
|
1082
|
+
getPromptCacheSessionId(credentials, body) {
|
|
1083
|
+
const promptCacheKey = normalizeCodexSessionId(body?.prompt_cache_key);
|
|
1084
|
+
if (promptCacheKey) return promptCacheKey;
|
|
1085
|
+
|
|
1086
|
+
const sessionId = body?.session_id ?? body?.conversation_id;
|
|
1087
|
+
const normalizedSessionId = normalizeCodexSessionId(sessionId);
|
|
1088
|
+
if (normalizedSessionId) return normalizedSessionId;
|
|
1089
|
+
|
|
1090
|
+
// AMRouter: use resolveSessionId for stable session IDs
|
|
1091
|
+
if (credentials) {
|
|
1092
|
+
return resolveCacheSessionId(body || {}, credentials);
|
|
1093
|
+
}
|
|
1094
|
+
return normalizeCodexSessionId(credentials?.providerSpecificData?.workspaceId) || null;
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
// ── Credential refresh ────────────────────────────────────────────────
|
|
1098
|
+
|
|
1099
|
+
async refreshCredentials(credentials, log) {
|
|
1100
|
+
if (!credentials?.refreshToken) {
|
|
1101
|
+
log?.warn?.("TOKEN_REFRESH", "Codex: no refresh token available, re-authentication required");
|
|
1102
|
+
return null;
|
|
1103
|
+
}
|
|
1104
|
+
// Try AMRouter's refreshProviderCredentials first
|
|
1105
|
+
try {
|
|
1106
|
+
const result = await refreshProviderCredentials("codex", credentials, log);
|
|
1107
|
+
if (result) return result;
|
|
1108
|
+
} catch { /* fall through to getAccessToken */ }
|
|
1109
|
+
|
|
1110
|
+
// Fallback to getAccessToken
|
|
1111
|
+
const result = await getAccessToken("codex", credentials, log);
|
|
1112
|
+
if (!result) {
|
|
1113
|
+
log?.warn?.("TOKEN_REFRESH", "Codex: token refresh failed — re-authentication required");
|
|
1114
|
+
return null;
|
|
1115
|
+
}
|
|
1116
|
+
if (result.error) {
|
|
1117
|
+
log?.warn?.("TOKEN_REFRESH", `Codex: token refresh failed (${result.error}) — re-authentication required`);
|
|
1118
|
+
return null;
|
|
1119
|
+
}
|
|
1120
|
+
return result;
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
needsRefresh(credentials) {
|
|
1124
|
+
return shouldRefreshCredentials("codex", credentials);
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
// ── Parse 429 with usage_limit_reached ────────────────────────────────
|
|
1128
|
+
|
|
1129
|
+
parseError(response, bodyText) {
|
|
1130
|
+
if (response.status === 429 && bodyText) {
|
|
1131
|
+
try {
|
|
1132
|
+
const json = JSON.parse(bodyText);
|
|
1133
|
+
const err = json?.error;
|
|
1134
|
+
if (err?.type === "usage_limit_reached") {
|
|
1135
|
+
const now = Date.now();
|
|
1136
|
+
let resetsAtMs = null;
|
|
1137
|
+
if (typeof err.resets_at === "number" && err.resets_at > 0) {
|
|
1138
|
+
const ms = err.resets_at * 1000;
|
|
1139
|
+
if (ms > now) resetsAtMs = ms;
|
|
1140
|
+
}
|
|
1141
|
+
if (!resetsAtMs && typeof err.resets_in_seconds === "number" && err.resets_in_seconds > 0) {
|
|
1142
|
+
resetsAtMs = now + err.resets_in_seconds * 1000;
|
|
1143
|
+
}
|
|
1144
|
+
if (resetsAtMs) return { status: 429, message: err.message || bodyText, resetsAtMs };
|
|
1145
|
+
}
|
|
1146
|
+
} catch { /* fall through */ }
|
|
1147
|
+
}
|
|
1148
|
+
return super.parseError(response, bodyText);
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
// ── Transform request (main business logic) ───────────────────────────
|
|
1152
|
+
|
|
1153
|
+
transformRequest(model, bodyInput, stream, credentials) {
|
|
1154
|
+
this._isCompact = !!bodyInput?._compact;
|
|
1155
|
+
// Do not mutate the caller's payload in place
|
|
1156
|
+
const body = bodyInput && typeof bodyInput === "object"
|
|
1157
|
+
? structuredClone(bodyInput)
|
|
1158
|
+
: {};
|
|
1159
|
+
|
|
1160
|
+
const nativeCodexPassthrough = body?._nativeCodexPassthrough === true;
|
|
1161
|
+
const isCompactRequest = isCompactResponsesEndpoint(credentials?.requestEndpointPath);
|
|
1162
|
+
const requestDefaults = getCodexRequestDefaults(credentials?.providerSpecificData);
|
|
1163
|
+
const thinkingBudgetConfig = getThinkingBudgetConfig();
|
|
1164
|
+
const allowConnectionReasoningDefaults = thinkingBudgetConfig.mode === ThinkingMode.PASSTHROUGH;
|
|
1165
|
+
consumeResponsesStoreMarker(body);
|
|
1166
|
+
|
|
1167
|
+
// Resolve conversation-stable session_id
|
|
1168
|
+
this._currentSessionId = this.getPromptCacheSessionId(credentials, body);
|
|
1169
|
+
|
|
1170
|
+
// Codex /responses rejects stream=false, but /responses/compact rejects the stream field entirely
|
|
1171
|
+
if (isCompactRequest) {
|
|
1172
|
+
delete body.stream;
|
|
1173
|
+
delete body.stream_options;
|
|
1174
|
+
delete body.client_metadata;
|
|
1175
|
+
} else {
|
|
1176
|
+
body.stream = true;
|
|
1177
|
+
}
|
|
1178
|
+
delete body._nativeCodexPassthrough;
|
|
1179
|
+
delete body._compact;
|
|
1180
|
+
|
|
1181
|
+
const requestServiceTier = normalizeServiceTierValue(body.service_tier);
|
|
1182
|
+
if (requestServiceTier) {
|
|
1183
|
+
body.service_tier = requestServiceTier;
|
|
1184
|
+
} else if (requestDefaults.serviceTier) {
|
|
1185
|
+
body.service_tier = requestDefaults.serviceTier;
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
// Messages/prompt → input conversion (must run before role conversion + strip)
|
|
1189
|
+
normalizeCodexResponsesInput(body);
|
|
1190
|
+
|
|
1191
|
+
// Normalize string input to array format
|
|
1192
|
+
const normalized = normalizeResponsesInput(body.input);
|
|
1193
|
+
if (normalized) body.input = normalized;
|
|
1194
|
+
|
|
1195
|
+
// Ensure input is present and non-empty
|
|
1196
|
+
if (!body.input || (Array.isArray(body.input) && body.input.length === 0)) {
|
|
1197
|
+
body.input = [{ type: "message", role: "user", content: [{ type: "input_text", text: "continue" }] }];
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
if (Array.isArray(body.input)) {
|
|
1201
|
+
body.input = sanitizeResponsesInputItems(body.input, false, {
|
|
1202
|
+
dropInternalAssistantMessages: !nativeCodexPassthrough,
|
|
1203
|
+
});
|
|
1204
|
+
}
|
|
1205
|
+
repairMissingCodexFunctionCallOutputs(body);
|
|
1206
|
+
|
|
1207
|
+
// Cache-aware system → developer role conversion
|
|
1208
|
+
convertSystemToDeveloperRole(body);
|
|
1209
|
+
|
|
1210
|
+
if (nativeCodexPassthrough) {
|
|
1211
|
+
if (!body.instructions || (typeof body.instructions === "string" && body.instructions.trim() === "")) {
|
|
1212
|
+
body.instructions = "Follow the developer instructions in the conversation.";
|
|
1213
|
+
}
|
|
1214
|
+
} else {
|
|
1215
|
+
const hasTools = Array.isArray(body.tools) && body.tools.length > 0;
|
|
1216
|
+
if (!body.instructions || (typeof body.instructions === "string" && body.instructions.trim() === "")) {
|
|
1217
|
+
body.instructions = hasTools ? CODEX_DEFAULT_INSTRUCTIONS : CODEX_CHAT_DEFAULT_INSTRUCTIONS;
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
// Store: regular Codex rejects store=true; compact rejects the field entirely
|
|
1222
|
+
const explicitStoreSetting = credentials?.providerSpecificData?.openaiStoreEnabled;
|
|
1223
|
+
if (isCompactRequest) {
|
|
1224
|
+
delete body.store;
|
|
1225
|
+
} else if (explicitStoreSetting === true) {
|
|
1226
|
+
body.store = true;
|
|
1227
|
+
} else {
|
|
1228
|
+
body.store = false;
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
// Normalize tools (hosted tool passthrough, free-plan gating)
|
|
1232
|
+
normalizeCodexTools(body, {
|
|
1233
|
+
dropImageGeneration: isCodexFreePlan(credentials?.providerSpecificData),
|
|
1234
|
+
preserveCustomTools: nativeCodexPassthrough,
|
|
1235
|
+
});
|
|
1236
|
+
|
|
1237
|
+
// Strip stored item references
|
|
1238
|
+
stripStoredItemReferences(body);
|
|
1239
|
+
|
|
1240
|
+
// Clean up messages/prompt fields
|
|
1241
|
+
delete body.messages;
|
|
1242
|
+
delete body.prompt;
|
|
1243
|
+
|
|
1244
|
+
// Map virtual Codex review models to upstream
|
|
1245
|
+
if (typeof body.model === "string") {
|
|
1246
|
+
body.model = getModelUpstreamId("cx", body.model) || body.model;
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
// Extract thinking level from model name suffix
|
|
1250
|
+
let modelEffort = null;
|
|
1251
|
+
let cleanModel = typeof body.model === "string" ? body.model : model;
|
|
1252
|
+
const splitModel = splitCodexReasoningSuffix(cleanModel);
|
|
1253
|
+
if (splitModel.effort) {
|
|
1254
|
+
modelEffort = splitModel.effort;
|
|
1255
|
+
body.model = splitModel.baseModel;
|
|
1256
|
+
cleanModel = splitModel.baseModel;
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
// Reasoning effort: model suffix > explicit reasoning.effort > reasoning_effort > defaults
|
|
1260
|
+
const reasoningRecord = body.reasoning && typeof body.reasoning === "object" && !Array.isArray(body.reasoning)
|
|
1261
|
+
? body.reasoning : null;
|
|
1262
|
+
const explicitReasoning = normalizeEffortValue(reasoningRecord?.effort);
|
|
1263
|
+
const requestReasoningEffort = normalizeEffortValue(body.reasoning_effort);
|
|
1264
|
+
const fallbackReasoningEffort = allowConnectionReasoningDefaults
|
|
1265
|
+
? requestDefaults.reasoningEffort || "medium" : undefined;
|
|
1266
|
+
const rawEffort = modelEffort || explicitReasoning || requestReasoningEffort || fallbackReasoningEffort;
|
|
1267
|
+
|
|
1268
|
+
if (rawEffort) {
|
|
1269
|
+
body.reasoning = { ...(reasoningRecord || {}), effort: clampEffort(cleanModel, rawEffort) };
|
|
1270
|
+
}
|
|
1271
|
+
ensureCodexReasoningSummary(body);
|
|
1272
|
+
delete body.reasoning_effort;
|
|
1273
|
+
|
|
1274
|
+
// Remove unsupported parameters
|
|
1275
|
+
delete body.max_tokens;
|
|
1276
|
+
delete body.max_output_tokens;
|
|
1277
|
+
delete body.truncation;
|
|
1278
|
+
delete body.background;
|
|
1279
|
+
delete body.prompt_cache_retention;
|
|
1280
|
+
delete body.safety_identifier;
|
|
1281
|
+
delete body.user;
|
|
1282
|
+
delete body.temperature;
|
|
1283
|
+
delete body.top_p;
|
|
1284
|
+
delete body.frequency_penalty;
|
|
1285
|
+
delete body.presence_penalty;
|
|
1286
|
+
delete body.logprobs;
|
|
1287
|
+
delete body.top_logprobs;
|
|
1288
|
+
delete body.n;
|
|
1289
|
+
delete body.seed;
|
|
1290
|
+
delete body.max_completion_tokens;
|
|
1291
|
+
delete body.metadata;
|
|
1292
|
+
delete body.stream_options;
|
|
1293
|
+
|
|
1294
|
+
// Inject prompt_cache_key for Codex prompt caching
|
|
1295
|
+
if (!body.prompt_cache_key) {
|
|
1296
|
+
const cacheSessionId = this.getPromptCacheSessionId(credentials, body);
|
|
1297
|
+
if (cacheSessionId) body.prompt_cache_key = cacheSessionId;
|
|
1298
|
+
}
|
|
1299
|
+
if (!isCompactRequest) {
|
|
1300
|
+
applyCodexClientMetadata(body, credentials?.providerSpecificData?.codexClientIdentity);
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
// Delete session_id and conversation_id from body (unsupported upstream)
|
|
1304
|
+
delete body.session_id;
|
|
1305
|
+
delete body.conversation_id;
|
|
1306
|
+
|
|
1307
|
+
// previous_response_id: store=false → backend can't resolve; avoid 404
|
|
1308
|
+
delete body.previous_response_id;
|
|
1309
|
+
|
|
1310
|
+
if (nativeCodexPassthrough) return body;
|
|
1311
|
+
|
|
1312
|
+
// GPT-5 verbosity normalization
|
|
1313
|
+
normalizeCodexVerbosity(body);
|
|
1314
|
+
|
|
1315
|
+
// Final allowlist filter — strip unknown fields
|
|
1316
|
+
for (const key of Object.keys(body)) {
|
|
1317
|
+
if (!RESPONSES_API_ALLOWLIST.has(key)) delete body[key];
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
return body;
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
export default CodexExecutor;
|