@fudrouter/fsrouter 0.6.72 → 0.6.74
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/dist/lib/headroom/detect.js +97 -7
- package/dist/lib/headroom/process.js +136 -4
- package/dist/open-sse/config/appConstants.js +23 -79
- package/dist/open-sse/config/cliFingerprints.js +1 -1
- package/dist/open-sse/config/errorConfig.js +0 -11
- package/dist/open-sse/config/grokCli.js +10 -0
- package/dist/open-sse/config/kiroConstants.js +99 -46
- package/dist/open-sse/config/runtimeConfig.js +2 -0
- package/dist/open-sse/config/ttsModels.js +2 -0
- package/dist/open-sse/executors/antigravity.js +250 -164
- package/dist/open-sse/executors/base.js +16 -11
- package/dist/open-sse/executors/codex.js +269 -1108
- package/dist/open-sse/executors/commandCode.js +1 -1
- package/dist/open-sse/executors/commandcode.js +10 -4
- package/dist/open-sse/executors/cursor.js +96 -203
- package/dist/open-sse/executors/default.js +146 -244
- package/dist/open-sse/executors/github.js +128 -73
- package/dist/open-sse/executors/grok-cli.js +527 -94
- package/dist/open-sse/executors/grok-web.js +5 -7
- package/dist/open-sse/executors/index.js +12 -0
- package/dist/open-sse/executors/kiro.js +150 -61
- package/dist/open-sse/executors/opencode-go.js +12 -4
- package/dist/open-sse/executors/opencode.js +1 -1
- package/dist/open-sse/executors/perplexity-web.js +20 -96
- package/dist/open-sse/executors/qoder.js +28 -18
- package/dist/open-sse/executors/vertex.js +53 -7
- package/dist/open-sse/executors/xiaomi-tokenplan.js +6 -5
- package/dist/open-sse/handlers/chatCore/nonStreamingHandler.js +97 -85
- package/dist/open-sse/handlers/chatCore/requestDetail.js +32 -8
- package/dist/open-sse/handlers/chatCore/sseToJsonHandler.js +13 -7
- package/dist/open-sse/handlers/chatCore/streamingHandler.js +74 -25
- package/dist/open-sse/handlers/chatCore.js +35 -41
- package/dist/open-sse/handlers/embeddingProviders/index.js +1 -0
- package/dist/open-sse/handlers/embeddingProviders/openai.js +8 -16
- package/dist/open-sse/handlers/imageProviders/blackForestLabs.js +2 -21
- package/dist/open-sse/handlers/imageProviders/cloudflareAi.js +2 -30
- package/dist/open-sse/handlers/imageProviders/codex.js +2 -20
- package/dist/open-sse/handlers/imageProviders/comfyui.js +5 -18
- package/dist/open-sse/handlers/imageProviders/falAi.js +2 -22
- package/dist/open-sse/handlers/imageProviders/gemini.js +2 -16
- package/dist/open-sse/handlers/imageProviders/huggingface.js +2 -17
- package/dist/open-sse/handlers/imageProviders/index.js +3 -4
- package/dist/open-sse/handlers/imageProviders/leonardo.js +1 -1
- package/dist/open-sse/handlers/imageProviders/nanobanana.js +4 -23
- package/dist/open-sse/handlers/imageProviders/openai.js +15 -43
- package/dist/open-sse/handlers/imageProviders/runwayml.js +2 -26
- package/dist/open-sse/handlers/imageProviders/sdwebui.js +4 -20
- package/dist/open-sse/handlers/imageProviders/stabilityAi.js +2 -26
- package/dist/open-sse/handlers/imageProviders/weavy.js +1 -1
- package/dist/open-sse/handlers/search/chatSearch.js +60 -14
- package/dist/open-sse/handlers/ttsProviders/gemini.js +14 -3
- package/dist/open-sse/handlers/ttsProviders/index.js +4 -2
- package/dist/open-sse/handlers/ttsProviders/openai.js +4 -1
- package/dist/open-sse/handlers/ttsProviders/openrouter.js +7 -4
- package/dist/open-sse/handlers/videoCore.js +166 -0
- package/dist/open-sse/handlers/videoProviders/weavy.js +1 -1
- package/dist/open-sse/mcp-server/catalog.js +1 -1
- package/dist/open-sse/mcp-server/server.js +2 -2
- package/dist/open-sse/mcp-server/tools/advancedTools.js +2 -2
- package/dist/open-sse/mcp-server/tools/agentSkillTools.js +1 -1
- package/dist/open-sse/mcp-server/tools/compressionTools.js +4 -4
- package/dist/open-sse/mcp-server/tools/gamificationTools.js +10 -10
- package/dist/open-sse/mcp-server/tools/githubSkillTools.js +1 -1
- package/dist/open-sse/mcp-server/tools/memoryTools.js +3 -3
- package/dist/open-sse/mcp-server/tools/notionTools.js +2 -2
- package/dist/open-sse/mcp-server/tools/obsidianTools.js +2 -2
- package/dist/open-sse/mcp-server/tools/pickFastestModel.js +1 -1
- package/dist/open-sse/mcp-server/tools/pluginTools.js +4 -4
- package/dist/open-sse/mcp-server/tools/skillTools.js +2 -2
- package/dist/open-sse/providers/capabilities.js +24 -4
- package/dist/open-sse/providers/registry/alicode-intl.js +1 -1
- package/dist/open-sse/providers/registry/anthropic.js +1 -8
- package/dist/open-sse/providers/registry/codex.js +0 -9
- package/dist/open-sse/providers/registry/cohere.js +0 -2
- package/dist/open-sse/providers/registry/gemini.js +0 -2
- package/dist/open-sse/providers/registry/github.js +9 -6
- package/dist/open-sse/providers/registry/grok-cli.js +28 -18
- package/dist/open-sse/providers/registry/index.js +74 -80
- package/dist/open-sse/providers/registry/kiro.js +12 -0
- package/dist/open-sse/providers/registry/mistral.js +0 -3
- package/dist/open-sse/providers/registry/openai.js +0 -3
- package/dist/open-sse/providers/registry/perplexity.js +0 -2
- package/dist/open-sse/providers/registry/xai.js +5 -3
- package/dist/open-sse/rtk/autodetect.js +10 -2
- package/dist/open-sse/rtk/caveman.js +2 -93
- package/dist/open-sse/rtk/cavemanPrompts.js +34 -2
- package/dist/open-sse/rtk/constants.js +7 -2
- package/dist/open-sse/rtk/headroom.js +133 -0
- package/dist/open-sse/rtk/ponytail.js +1 -1
- package/dist/open-sse/rtk/registry.js +2 -0
- package/dist/open-sse/services/accountFallback.js +0 -108
- package/dist/open-sse/services/combo/quotaExhaustionCutoff.js +2 -2
- package/dist/open-sse/services/combo/quotaShareStrategy.js +1 -1
- package/dist/open-sse/services/combo/resolveAutoStrategy.js +1 -1
- package/dist/open-sse/services/combo/sessionStickiness.js +1 -1
- package/dist/open-sse/services/combo/targetSorters.js +2 -2
- package/dist/open-sse/services/combo/validateQuality.js +1 -1
- package/dist/open-sse/services/comboConfig.js +1 -1
- package/dist/open-sse/services/emergencyFallback.js +1 -1
- package/dist/open-sse/services/grokCliModels.js +127 -0
- package/dist/open-sse/services/model.js +7 -1
- package/dist/open-sse/services/provider.js +1 -1
- package/dist/open-sse/services/proxyAutoSelector.js +1 -1
- package/dist/open-sse/services/tokenRefresh/providers.js +3 -3
- package/dist/open-sse/services/usage/codex.js +148 -214
- package/dist/open-sse/services/usage/grok-cli.js +61 -7
- package/dist/open-sse/services/usage/misc.js +0 -19
- package/dist/open-sse/services/usage.js +0 -2
- package/dist/open-sse/translator/concerns/paramSupport.js +2 -2
- package/dist/open-sse/translator/concerns/thinkingUnified.js +6 -0
- package/dist/open-sse/translator/index.js +97 -59
- package/dist/open-sse/translator/request/claude-to-kiro.js +67 -40
- package/dist/open-sse/translator/request/openai-responses.js +1 -0
- package/dist/open-sse/translator/request/openai-to-commandcode.js +0 -4
- package/dist/open-sse/translator/request/openai-to-kiro.js +49 -20
- package/dist/open-sse/translator/response/commandcode-to-openai.js +0 -4
- package/dist/open-sse/utils/bypassHandler.js +18 -3
- package/dist/open-sse/utils/claudeCloaking.js +15 -5
- package/dist/open-sse/utils/cursorImages.js +1 -1
- package/dist/open-sse/utils/error.js +0 -17
- package/dist/open-sse/utils/keepaliveThreshold.js +4 -4
- package/dist/open-sse/utils/kiroSessionReplay.js +125 -0
- package/dist/open-sse/utils/noThinkingAlias.js +1 -1
- package/dist/open-sse/utils/proxyFetch.js +0 -1
- package/dist/open-sse/utils/reasoningContentInjector.js +4 -7
- package/dist/open-sse/utils/responsesStatePolicy.js +1 -1
- package/dist/open-sse/utils/responsesStreamHelpers.js +1 -0
- package/dist/open-sse/utils/sessionManager.js +49 -22
- package/dist/open-sse/utils/stream.js +54 -77
- package/dist/open-sse/utils/streamHandler.js +19 -15
- package/dist/open-sse/utils/streamHelpers.js +2 -17
- package/dist/open-sse/utils/usageTracking.js +103 -12
- package/dist/routes/headroom/extras/route.js +58 -0
- package/dist/routes/headroom/restart/route.js +33 -0
- package/open-sse/config/appConstants.js +23 -79
- package/open-sse/config/errorConfig.js +0 -11
- package/open-sse/config/grokCli.js +10 -0
- package/open-sse/config/kiroConstants.js +99 -46
- package/open-sse/config/runtimeConfig.js +2 -0
- package/open-sse/config/ttsModels.js +2 -0
- package/open-sse/executors/antigravity.js +250 -164
- package/open-sse/executors/base.js +16 -11
- package/open-sse/executors/codex.js +269 -1108
- package/open-sse/executors/commandcode.js +10 -4
- package/open-sse/executors/cursor.js +96 -203
- package/open-sse/executors/default.js +146 -244
- package/open-sse/executors/github.js +128 -73
- package/open-sse/executors/grok-cli.js +527 -94
- package/open-sse/executors/grok-web.js +5 -7
- package/open-sse/executors/index.js +12 -0
- package/open-sse/executors/kiro.js +150 -61
- package/open-sse/executors/opencode-go.js +12 -4
- package/open-sse/executors/opencode.js +1 -1
- package/open-sse/executors/perplexity-web.js +20 -96
- package/open-sse/executors/qoder.js +28 -18
- package/open-sse/executors/vertex.js +53 -7
- package/open-sse/executors/xiaomi-tokenplan.js +6 -5
- package/open-sse/handlers/chatCore/nonStreamingHandler.js +97 -85
- package/open-sse/handlers/chatCore/requestDetail.js +32 -8
- package/open-sse/handlers/chatCore/sseToJsonHandler.js +13 -7
- package/open-sse/handlers/chatCore/streamingHandler.js +74 -25
- package/open-sse/handlers/chatCore.js +35 -41
- package/open-sse/handlers/embeddingProviders/index.js +1 -0
- package/open-sse/handlers/embeddingProviders/openai.js +8 -16
- package/open-sse/handlers/imageProviders/blackForestLabs.js +2 -21
- package/open-sse/handlers/imageProviders/cloudflareAi.js +2 -30
- package/open-sse/handlers/imageProviders/codex.js +2 -20
- package/open-sse/handlers/imageProviders/comfyui.js +5 -18
- package/open-sse/handlers/imageProviders/falAi.js +2 -22
- package/open-sse/handlers/imageProviders/gemini.js +2 -16
- package/open-sse/handlers/imageProviders/huggingface.js +2 -17
- package/open-sse/handlers/imageProviders/index.js +3 -4
- package/open-sse/handlers/imageProviders/leonardo.js +1 -1
- package/open-sse/handlers/imageProviders/nanobanana.js +4 -23
- package/open-sse/handlers/imageProviders/openai.js +15 -43
- package/open-sse/handlers/imageProviders/runwayml.js +2 -26
- package/open-sse/handlers/imageProviders/sdwebui.js +4 -20
- package/open-sse/handlers/imageProviders/stabilityAi.js +2 -26
- package/open-sse/handlers/imageProviders/weavy.js +1 -1
- package/open-sse/handlers/search/chatSearch.js +60 -14
- package/open-sse/handlers/ttsProviders/gemini.js +14 -3
- package/open-sse/handlers/ttsProviders/index.js +4 -2
- package/open-sse/handlers/ttsProviders/openai.js +4 -1
- package/open-sse/handlers/ttsProviders/openrouter.js +7 -4
- package/open-sse/handlers/videoCore.js +166 -0
- package/open-sse/handlers/videoProviders/weavy.js +1 -1
- package/open-sse/mcp-server/audit.js +1 -1
- package/open-sse/mcp-server/catalog.js +2 -2
- package/open-sse/mcp-server/descriptionCompressor.js +1 -1
- package/open-sse/mcp-server/mcpCallerIdentity.js +1 -1
- package/open-sse/mcp-server/schemas/tools.js +1 -1
- package/open-sse/mcp-server/server.js +4 -4
- package/open-sse/mcp-server/tools/advancedTools.js +5 -5
- package/open-sse/mcp-server/tools/agentSkillTools.js +1 -1
- package/open-sse/mcp-server/tools/compressionTools.js +4 -4
- package/open-sse/mcp-server/tools/gamificationTools.js +10 -10
- package/open-sse/mcp-server/tools/githubSkillTools.js +1 -1
- package/open-sse/mcp-server/tools/memoryTools.js +3 -3
- package/open-sse/mcp-server/tools/notionTools.js +2 -2
- package/open-sse/mcp-server/tools/obsidianTools.js +2 -2
- package/open-sse/mcp-server/tools/pickFastestModel.js +3 -3
- package/open-sse/mcp-server/tools/pluginTools.js +4 -4
- package/open-sse/mcp-server/tools/skillTools.js +2 -2
- package/open-sse/providers/capabilities.js +24 -4
- package/open-sse/providers/registry/alicode-intl.js +1 -1
- package/open-sse/providers/registry/anthropic.js +1 -8
- package/open-sse/providers/registry/codex.js +0 -9
- package/open-sse/providers/registry/cohere.js +0 -2
- package/open-sse/providers/registry/gemini.js +0 -2
- package/open-sse/providers/registry/github.js +9 -6
- package/open-sse/providers/registry/grok-cli.js +28 -18
- package/open-sse/providers/registry/index.js +74 -80
- package/open-sse/providers/registry/kiro.js +12 -0
- package/open-sse/providers/registry/mistral.js +0 -3
- package/open-sse/providers/registry/openai.js +0 -3
- package/open-sse/providers/registry/perplexity.js +0 -2
- package/open-sse/providers/registry/xai.js +5 -3
- package/open-sse/rtk/autodetect.js +10 -2
- package/open-sse/rtk/caveman.js +2 -93
- package/open-sse/rtk/cavemanPrompts.js +34 -2
- package/open-sse/rtk/constants.js +7 -2
- package/open-sse/rtk/headroom.js +133 -0
- package/open-sse/rtk/ponytail.js +1 -1
- package/open-sse/rtk/registry.js +2 -0
- package/open-sse/services/accountFallback.js +0 -108
- package/open-sse/services/combo/quotaExhaustionCutoff.js +2 -2
- package/open-sse/services/combo/quotaShareStrategy.js +1 -1
- package/open-sse/services/combo/resolveAutoStrategy.js +1 -1
- package/open-sse/services/combo/sessionStickiness.js +1 -1
- package/open-sse/services/combo/shadowRouting.js +1 -1
- package/open-sse/services/combo/targetSorters.js +4 -4
- package/open-sse/services/combo/validateQuality.js +1 -1
- package/open-sse/services/evalRouting.js +1 -1
- package/open-sse/services/grokCliModels.js +127 -0
- package/open-sse/services/model.js +7 -1
- package/open-sse/services/modelCapabilities.js +1 -1
- package/open-sse/services/modelFamilyFallback.js +1 -1
- package/open-sse/services/provider.js +1 -1
- package/open-sse/services/providerCooldownTracker.js +1 -1
- package/open-sse/services/rateLimitManager.js +1 -1
- package/open-sse/services/tokenRefresh/providers.js +3 -3
- package/open-sse/services/usage/codex.js +148 -214
- package/open-sse/services/usage/grok-cli.js +61 -7
- package/open-sse/services/usage/misc.js +0 -19
- package/open-sse/services/usage.js +0 -2
- package/open-sse/translator/concerns/paramSupport.js +2 -2
- package/open-sse/translator/concerns/thinkingUnified.js +6 -0
- package/open-sse/translator/index.js +97 -59
- package/open-sse/translator/request/claude-to-kiro.js +67 -40
- package/open-sse/translator/request/openai-responses.js +1 -0
- package/open-sse/translator/request/openai-to-commandcode.js +0 -4
- package/open-sse/translator/request/openai-to-kiro.js +49 -20
- package/open-sse/translator/response/commandcode-to-openai.js +0 -4
- package/open-sse/utils/bypassHandler.js +18 -3
- package/open-sse/utils/claudeCloaking.js +15 -5
- package/open-sse/utils/error.js +0 -17
- package/open-sse/utils/kiroSessionReplay.js +125 -0
- package/open-sse/utils/logger.js +1 -1
- package/open-sse/utils/proxyFetch.js +0 -1
- package/open-sse/utils/reasoningContentInjector.js +4 -7
- package/open-sse/utils/responsesStreamHelpers.js +1 -0
- package/open-sse/utils/sessionManager.js +49 -22
- package/open-sse/utils/stream.js +54 -77
- package/open-sse/utils/streamHandler.js +19 -15
- package/open-sse/utils/streamHelpers.js +2 -17
- package/open-sse/utils/usageTracking.js +103 -12
- package/package.json +4 -7
- package/public/assets/EndpointPageClient.C2WMTYy0.js +6 -0
- package/public/assets/{Loading.Bj-WGl4k.js → Loading.BHPtQ9vj.js} +1 -1
- package/public/assets/{NoAuthProxyCard.qAv57b-0.js → NoAuthProxyCard.BDcXaWvM.js} +1 -1
- package/public/assets/index.Be3gbrBl.js +89 -0
- package/public/assets/index.COMgQZYj.css +1 -0
- package/public/assets/{page.CbkENBd5.js → page.-lpNgYAw.js} +1 -1
- package/public/assets/{page.CssmrzTT.js → page.11hpNKmq.js} +1 -1
- package/public/assets/{page.C72FTTJr.js → page.B-LxsnqU.js} +1 -1
- package/public/assets/{page.sOFOrxqq.js → page.B-dzeIUC.js} +1 -1
- package/public/assets/{page.CsxWmPoI.js → page.B-nBR75u.js} +1 -1
- package/public/assets/{page.Dx_GRRdT.js → page.B3QqvLep.js} +1 -1
- package/public/assets/{page.DPyOkPVo.js → page.B8xdkCWA.js} +1 -1
- package/public/assets/{page.DUI8kqOY.js → page.BFb7yUd8.js} +1 -1
- package/public/assets/page.BbPPdoas.js +1 -0
- package/public/assets/page.BdS20a1O.js +1 -0
- package/public/assets/{page.DibhF7f-.js → page.BfmI9KYe.js} +1 -1
- package/public/assets/{page.DX4Nno6M.js → page.BgGJovOg.js} +1 -1
- package/public/assets/{page.BnmTC5jG.js → page.C0gBvR4O.js} +1 -1
- package/public/assets/{page.D5gj98Oe.js → page.C6bYizL7.js} +1 -1
- package/public/assets/{page.vla5Mzki.js → page.C8sLEMa6.js} +1 -1
- package/public/assets/{page.CXd_R9yU.js → page.CCNsZBXp.js} +1 -1
- package/public/assets/{page.CQlVGoXg.js → page.CF_YSLwP.js} +1 -1
- package/public/assets/{page.BbO1pspY.js → page.CPTtRDxw.js} +1 -1
- package/public/assets/{page.D1oKew1j.js → page.CdMmlUEm.js} +1 -1
- package/public/assets/{page.DxMDTbSx.js → page.Cged1bOZ.js} +1 -1
- package/public/assets/{page.Cj5h09Zo.js → page.Ch647dVk.js} +1 -1
- package/public/assets/{page.DVIHRbxB.js → page.CpvXDkQF.js} +1 -1
- package/public/assets/{page.i4KDuWcM.js → page.CrBl7f8N.js} +1 -1
- package/public/assets/{page.BSLJ4tx5.js → page.CrP7niA2.js} +1 -1
- package/public/assets/{page.CnTop8Zt.js → page.CvUFZzXr.js} +1 -1
- package/public/assets/{page.O2ddJYoT.js → page.CyUqJPmx.js} +1 -1
- package/public/assets/{page.DBhu4Arl.js → page.D8Rp8fFR.js} +1 -1
- package/public/assets/{page.CPZav1_c.js → page.Df9qtrdG.js} +1 -1
- package/public/assets/{page.Qkkv8roc.js → page.DiL4Gwqe.js} +1 -1
- package/public/assets/{page.BdmJ3yY3.js → page.Dl1apZE2.js} +1 -1
- package/public/assets/{page.1qjqvrwX.js → page.HV0w1d5C.js} +1 -1
- package/public/assets/{page.ChX1NqmC.js → page.N1x4YL8_.js} +1 -1
- package/public/assets/{page.Dh5f0XJC.js → page.P2Ny5veR.js} +1 -1
- package/public/assets/{page.CSs3-gdt.js → page.fOOCr18J.js} +1 -1
- package/public/assets/{page.Ir7KvKcF.js → page.sUIPWIiF.js} +1 -1
- package/public/assets/{page.CzlQTyAL.js → page.tE7PpWYW.js} +1 -1
- package/public/assets/{page.DzZLqI5Q.js → page.uziaGZsT.js} +1 -1
- package/public/index.html +2 -2
- package/public/assets/EndpointPageClient.LyNNvZ4z.js +0 -6
- package/public/assets/index.BuPfZebu.css +0 -1
- package/public/assets/index.CShjRV_B.js +0 -89
- package/public/assets/page.DD_czjjP.js +0 -1
|
@@ -1,753 +1,269 @@
|
|
|
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
1
|
import { BaseExecutor } from "./base.js";
|
|
8
|
-
import { PROVIDERS } from "../config/providers.js";
|
|
9
2
|
import { CODEX_DEFAULT_INSTRUCTIONS } from "../config/codexInstructions.js";
|
|
10
|
-
import {
|
|
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";
|
|
3
|
+
import { PROVIDERS } from "../config/providers.js";
|
|
15
4
|
import {
|
|
16
5
|
refreshProviderCredentials,
|
|
17
6
|
shouldRefreshCredentials,
|
|
18
7
|
} from "../services/oauthCredentialManager.js";
|
|
19
|
-
import {
|
|
8
|
+
import { normalizeResponsesInput } from "../translator/formats/responsesApi.js";
|
|
9
|
+
import { fetchImageAsBase64 } from "../translator/concerns/image.js";
|
|
10
|
+
import { getModelUpstreamId } from "../config/providerModels.js";
|
|
11
|
+
import { DEFAULT_RETRY_CONFIG, HTTP_STATUS, resolveRetryEntry } from "../config/runtimeConfig.js";
|
|
20
12
|
import { dbg } from "../utils/debugLog.js";
|
|
13
|
+
import { resolveSessionId } from "../utils/sessionManager.js";
|
|
21
14
|
|
|
22
|
-
//
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const
|
|
26
|
-
"
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
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
|
-
};
|
|
15
|
+
// SSE error patterns inside 200-OK bodies. Some retry same account first; capacity rotates accounts.
|
|
16
|
+
const CODEX_SSE_RETRY_PATTERNS = ["server_is_overloaded", "service_unavailable_error"];
|
|
17
|
+
const CODEX_SSE_ACCOUNT_FALLBACK_PATTERNS = ["selected model is at capacity", "model_at_capacity"];
|
|
18
|
+
const CODEX_SSE_USER_OUTPUT_PATTERNS = [
|
|
19
|
+
"event: response.output_text.delta",
|
|
20
|
+
"event: response.function_call_arguments.delta",
|
|
21
|
+
'"type":"response.output_text.delta"',
|
|
22
|
+
'"type":"response.function_call_arguments.delta"',
|
|
23
|
+
];
|
|
24
|
+
const CODEX_SSE_PEEK_BYTES = 256 * 1024;
|
|
25
|
+
const CODEX_MODEL_CAPACITY_MESSAGE = "Selected model is at capacity. Please try a different model.";
|
|
156
26
|
|
|
157
|
-
//
|
|
27
|
+
// Server-generated item id prefixes that Codex /responses cannot resolve when store=false
|
|
28
|
+
const SERVER_ID_PATTERN = /^(rs|fc|resp|msg)_/;
|
|
158
29
|
|
|
159
|
-
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
30
|
+
// Hosted tool types that Codex/OpenAI Responses executes server-side
|
|
31
|
+
const CODEX_HOSTED_TOOL_TYPES = new Set([
|
|
32
|
+
"image_generation", "web_search", "web_search_preview", "file_search",
|
|
33
|
+
"computer", "computer_use_preview", "code_interpreter", "mcp", "local_shell",
|
|
34
|
+
"tool_search"
|
|
35
|
+
]);
|
|
164
36
|
|
|
165
|
-
|
|
166
|
-
|
|
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
|
-
};
|
|
37
|
+
// Responses-native freeform tools carry a name plus format payload and must pass through intact.
|
|
38
|
+
const CODEX_PASSTHROUGH_TOOL_TYPES = new Set(["custom"]);
|
|
172
39
|
|
|
40
|
+
// Allowlist of fields accepted by Codex Responses API — anything else is stripped
|
|
173
41
|
const RESPONSES_API_ALLOWLIST = new Set([
|
|
174
42
|
"model", "input", "instructions", "tools", "tool_choice", "stream", "store",
|
|
175
|
-
"reasoning", "service_tier", "include", "prompt_cache_key", "client_metadata",
|
|
43
|
+
"reasoning", "service_tier", "include", "prompt_cache_key", "client_metadata",
|
|
44
|
+
"text"
|
|
176
45
|
]);
|
|
177
46
|
|
|
178
|
-
//
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
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" };
|
|
47
|
+
// Convert role=system → role=developer in body.input (keeps content in cacheable prefix)
|
|
48
|
+
function convertSystemToDeveloperRole(body) {
|
|
49
|
+
if (!Array.isArray(body.input)) return;
|
|
50
|
+
for (const item of body.input) {
|
|
51
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) continue;
|
|
52
|
+
const isSystemMsg = item.role === "system" && (!item.type || item.type === "message");
|
|
53
|
+
if (isSystemMsg) item.role = "developer";
|
|
237
54
|
}
|
|
238
|
-
return { cooldownMs: 0, window: "none" };
|
|
239
55
|
}
|
|
240
56
|
|
|
241
|
-
//
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
return typeof plan === "string" && plan.trim().toLowerCase() === "free";
|
|
57
|
+
// Strip server-generated item IDs (rs_/fc_/resp_/msg_) from input — avoids 404 with store=false
|
|
58
|
+
function stripStoredItemReferences(body) {
|
|
59
|
+
if (!Array.isArray(body.input)) return;
|
|
60
|
+
body.input = body.input.filter((item) => {
|
|
61
|
+
if (typeof item === "string" && SERVER_ID_PATTERN.test(item)) return false;
|
|
62
|
+
if (item && typeof item === "object" && !Array.isArray(item)) {
|
|
63
|
+
if (item.type === "item_reference") return false;
|
|
64
|
+
if (typeof item.id === "string" && SERVER_ID_PATTERN.test(item.id)) delete item.id;
|
|
65
|
+
}
|
|
66
|
+
return true;
|
|
67
|
+
});
|
|
253
68
|
}
|
|
254
69
|
|
|
255
|
-
|
|
70
|
+
// Flatten Chat-Completions tool shape into Responses flat format + filter unsupported tools
|
|
71
|
+
function normalizeCodexTools(body) {
|
|
256
72
|
if (!Array.isArray(body.tools)) return;
|
|
257
|
-
const
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
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
|
-
}
|
|
73
|
+
const validNames = new Set();
|
|
74
|
+
body.tools = body.tools.filter((tool) => {
|
|
75
|
+
if (!tool || typeof tool !== "object" || Array.isArray(tool)) return false;
|
|
76
|
+
const type = typeof tool.type === "string" ? tool.type : "";
|
|
77
|
+
if (type === "namespace") {
|
|
78
|
+
if (Array.isArray(tool.tools)) {
|
|
79
|
+
for (const st of tool.tools) {
|
|
80
|
+
const n = typeof st?.name === "string" ? st.name.trim().slice(0, 128) : "";
|
|
81
|
+
if (n) validNames.add(n);
|
|
274
82
|
}
|
|
275
83
|
}
|
|
276
84
|
return true;
|
|
277
85
|
}
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
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;
|
|
86
|
+
if (type !== "function") {
|
|
87
|
+
if (CODEX_PASSTHROUGH_TOOL_TYPES.has(type)) return true;
|
|
88
|
+
if (!type || tool.function || typeof tool.name === "string") return false;
|
|
89
|
+
return CODEX_HOSTED_TOOL_TYPES.has(type);
|
|
299
90
|
}
|
|
300
|
-
|
|
301
|
-
|
|
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
|
-
: "";
|
|
91
|
+
const fn = tool.function && typeof tool.function === "object" && !Array.isArray(tool.function) ? tool.function : null;
|
|
92
|
+
const rawName = typeof tool.name === "string" ? tool.name : (typeof fn?.name === "string" ? fn.name : "");
|
|
307
93
|
const name = rawName.trim();
|
|
308
94
|
if (!name) return false;
|
|
309
|
-
|
|
310
|
-
const
|
|
311
|
-
?
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
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);
|
|
95
|
+
const description = typeof tool.description === "string" ? tool.description : (typeof fn?.description === "string" ? fn.description : "");
|
|
96
|
+
const parameters = (tool.parameters && typeof tool.parameters === "object" && !Array.isArray(tool.parameters))
|
|
97
|
+
? tool.parameters
|
|
98
|
+
: (fn?.parameters && typeof fn.parameters === "object" && !Array.isArray(fn.parameters) ? fn.parameters : { type: "object", properties: {} });
|
|
99
|
+
for (const k of Object.keys(tool)) delete tool[k];
|
|
100
|
+
tool.type = "function";
|
|
101
|
+
tool.name = name.slice(0, 128);
|
|
102
|
+
if (description) tool.description = description;
|
|
103
|
+
tool.parameters = parameters;
|
|
104
|
+
validNames.add(name);
|
|
333
105
|
return true;
|
|
334
106
|
});
|
|
335
|
-
|
|
336
107
|
// Drop tool_choice if it references an unknown function name
|
|
337
108
|
if (body.tool_choice && typeof body.tool_choice === "object" && !Array.isArray(body.tool_choice)) {
|
|
338
109
|
if (body.tool_choice.type === "function") {
|
|
339
110
|
const n = typeof body.tool_choice.name === "string" ? body.tool_choice.name.trim() : "";
|
|
340
|
-
if (!n || !
|
|
341
|
-
} else if (body.tool_choice.type === "local_shell") {
|
|
342
|
-
delete body.tool_choice;
|
|
111
|
+
if (!n || !validNames.has(n)) delete body.tool_choice;
|
|
343
112
|
}
|
|
344
113
|
}
|
|
345
114
|
}
|
|
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
115
|
|
|
370
|
-
|
|
371
|
-
|
|
116
|
+
// Resolve prompt-cache session id: client session → assistant-text-hash → workspaceId → connection
|
|
117
|
+
function resolveCacheSessionId(body, credentials) {
|
|
118
|
+
return resolveSessionId({
|
|
119
|
+
headers: credentials?.rawHeaders,
|
|
120
|
+
body,
|
|
121
|
+
connectionId: credentials?.connectionId,
|
|
122
|
+
workspaceId: credentials?.providerSpecificData?.workspaceId,
|
|
123
|
+
scope: "codex"
|
|
124
|
+
});
|
|
372
125
|
}
|
|
373
126
|
|
|
374
|
-
function
|
|
375
|
-
return
|
|
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
|
-
);
|
|
127
|
+
function normalizeReasoningEffort(value) {
|
|
128
|
+
return value === "max" ? "xhigh" : value;
|
|
387
129
|
}
|
|
388
130
|
|
|
389
|
-
function
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
131
|
+
function findNestedMessage(value, depth = 0) {
|
|
132
|
+
if (!value || depth > 6 || typeof value === "string") return null;
|
|
133
|
+
if (Array.isArray(value)) {
|
|
134
|
+
for (const item of value) {
|
|
135
|
+
const found = findNestedMessage(item, depth + 1);
|
|
136
|
+
if (found) return found;
|
|
394
137
|
}
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
if (typeof value !== "object") return null;
|
|
141
|
+
if (typeof value.message === "string" && value.message.trim()) return value.message;
|
|
142
|
+
if (typeof value.error?.message === "string" && value.error.message.trim()) return value.error.message;
|
|
143
|
+
if (typeof value.response?.error?.message === "string" && value.response.error.message.trim()) return value.response.error.message;
|
|
144
|
+
for (const child of Object.values(value)) {
|
|
145
|
+
const found = findNestedMessage(child, depth + 1);
|
|
146
|
+
if (found) return found;
|
|
395
147
|
}
|
|
396
|
-
return
|
|
148
|
+
return null;
|
|
397
149
|
}
|
|
398
150
|
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
151
|
+
function extractSseErrorMessage(text, fallback) {
|
|
152
|
+
const exact = text?.match(/Selected model is at capacity\. Please try a different model\./i)?.[0];
|
|
153
|
+
if (exact) return exact;
|
|
402
154
|
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
155
|
+
for (const line of String(text || "").split(/\r?\n/)) {
|
|
156
|
+
if (!line.startsWith("data:")) continue;
|
|
157
|
+
const data = line.slice(5).trim();
|
|
158
|
+
if (!data || data === "[DONE]") continue;
|
|
159
|
+
try {
|
|
160
|
+
const message = findNestedMessage(JSON.parse(data));
|
|
161
|
+
if (message) return message;
|
|
162
|
+
} catch {
|
|
163
|
+
// Ignore non-JSON SSE data lines.
|
|
412
164
|
}
|
|
413
165
|
}
|
|
414
|
-
}
|
|
415
166
|
|
|
416
|
-
|
|
417
|
-
|
|
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;
|
|
167
|
+
return fallback || CODEX_MODEL_CAPACITY_MESSAGE;
|
|
168
|
+
}
|
|
425
169
|
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
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
|
-
}
|
|
170
|
+
function codexSseErrorResponse(status, message) {
|
|
171
|
+
return new Response(JSON.stringify({
|
|
172
|
+
error: {
|
|
173
|
+
message,
|
|
174
|
+
type: status >= 500 ? "server_error" : "invalid_request_error",
|
|
175
|
+
code: status === HTTP_STATUS.SERVICE_UNAVAILABLE ? "service_unavailable" : "upstream_error",
|
|
449
176
|
}
|
|
450
|
-
|
|
177
|
+
}), {
|
|
178
|
+
status,
|
|
179
|
+
headers: { "Content-Type": "application/json" },
|
|
451
180
|
});
|
|
452
|
-
|
|
453
|
-
if (strippedCount > 0) {
|
|
454
|
-
console.debug(`[Codex] stripStoredItemReferences: sanitized ${strippedCount} server-generated ID(s) from input`);
|
|
455
|
-
}
|
|
456
181
|
}
|
|
457
182
|
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
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)`);
|
|
183
|
+
/**
|
|
184
|
+
* Codex Executor - handles OpenAI Codex API (Responses API format)
|
|
185
|
+
* Automatically injects default instructions if missing
|
|
186
|
+
*/
|
|
187
|
+
export class CodexExecutor extends BaseExecutor {
|
|
188
|
+
constructor() {
|
|
189
|
+
super("codex", PROVIDERS.codex);
|
|
190
|
+
this._currentSessionId = null;
|
|
484
191
|
}
|
|
485
|
-
}
|
|
486
192
|
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
193
|
+
/**
|
|
194
|
+
* Override headers to add codex-specific identity headers.
|
|
195
|
+
* transformRequest runs BEFORE buildHeaders, sets this._currentSessionId.
|
|
196
|
+
*/
|
|
197
|
+
buildHeaders(credentials, stream = true) {
|
|
198
|
+
const headers = super.buildHeaders(credentials, stream);
|
|
199
|
+
headers["session_id"] = this._currentSessionId || credentials?.connectionId || "default";
|
|
200
|
+
// Identify client type to Codex backend (matches official codex CLI)
|
|
201
|
+
if (!headers["originator"]) headers["originator"] = "codex_cli_rs";
|
|
202
|
+
// Account/workspace binding header — required when multiple Codex accounts
|
|
203
|
+
// are configured. OAuth import stores ChatGPT account ID as chatgptAccountId;
|
|
204
|
+
// older/custom rows may use workspaceId/accountId. Prefer explicit workspaceId
|
|
205
|
+
// but fall back to chatgptAccountId so requests don't cross-bind to the wrong
|
|
206
|
+
// OpenAI account and surface as token_invalid after adding another account.
|
|
207
|
+
const accountId =
|
|
208
|
+
credentials?.providerSpecificData?.workspaceId ||
|
|
209
|
+
credentials?.providerSpecificData?.chatgptAccountId ||
|
|
210
|
+
credentials?.providerSpecificData?.accountId;
|
|
211
|
+
if (typeof accountId === "string" && accountId && !headers["ChatGPT-Account-ID"]) {
|
|
212
|
+
headers["ChatGPT-Account-ID"] = accountId;
|
|
213
|
+
}
|
|
214
|
+
return headers;
|
|
491
215
|
}
|
|
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
216
|
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
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;
|
|
217
|
+
buildUrl(model, stream, urlIndex = 0, credentials = null) {
|
|
218
|
+
const base = super.buildUrl(model, stream, urlIndex, credentials);
|
|
219
|
+
return this._isCompact ? `${base}/compact` : base;
|
|
527
220
|
}
|
|
528
|
-
return requested;
|
|
529
|
-
}
|
|
530
221
|
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
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];
|
|
222
|
+
async refreshCredentials(credentials, log) {
|
|
223
|
+
if (!credentials?.refreshToken) return null;
|
|
224
|
+
return refreshProviderCredentials("codex", credentials, log);
|
|
542
225
|
}
|
|
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
226
|
|
|
560
|
-
|
|
561
|
-
|
|
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;
|
|
227
|
+
needsRefresh(credentials) {
|
|
228
|
+
return shouldRefreshCredentials("codex", credentials);
|
|
571
229
|
}
|
|
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
230
|
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
if (
|
|
658
|
-
|
|
659
|
-
if (
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
231
|
+
/**
|
|
232
|
+
* Prefetch remote image URLs and inline them as base64 data URIs.
|
|
233
|
+
* Runs before execute() because Codex backend cannot fetch remote images.
|
|
234
|
+
* Mutates body.input in place.
|
|
235
|
+
*/
|
|
236
|
+
async prefetchImages(body) {
|
|
237
|
+
if (!Array.isArray(body?.input)) return;
|
|
238
|
+
for (const item of body.input) {
|
|
239
|
+
if (!Array.isArray(item.content)) continue;
|
|
240
|
+
const pending = item.content.map(async (c) => {
|
|
241
|
+
if (c.type !== "image_url") return c;
|
|
242
|
+
const url = typeof c.image_url === "string" ? c.image_url : c.image_url?.url;
|
|
243
|
+
const detail = c.image_url?.detail || "auto";
|
|
244
|
+
if (!url) return c;
|
|
245
|
+
if (url.startsWith("data:")) return { type: "input_image", image_url: url, detail };
|
|
246
|
+
const fetched = await fetchImageAsBase64(url, { timeoutMs: 15000 });
|
|
247
|
+
return { type: "input_image", image_url: fetched?.url || url, detail };
|
|
248
|
+
});
|
|
249
|
+
item.content = await Promise.all(pending);
|
|
665
250
|
}
|
|
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
251
|
}
|
|
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
252
|
|
|
716
253
|
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;
|
|
254
|
+
const imgCount = Array.isArray(args.body?.input) ? args.body.input.reduce((n, it) => n + (Array.isArray(it.content) ? it.content.filter(c => c.type === "image_url").length : 0), 0) : 0;
|
|
720
255
|
const inputLen = Array.isArray(args.body?.input) ? args.body.input.length : 0;
|
|
721
256
|
dbg("CODEX", `execute start | inputItems=${inputLen} | images=${imgCount} | sessionId=${this._currentSessionId || "pending"}`);
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
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);
|
|
257
|
+
if (imgCount > 0) {
|
|
258
|
+
const t0 = Date.now();
|
|
259
|
+
await this.prefetchImages(args.body);
|
|
260
|
+
dbg("CODEX", `prefetchImages done | ${Date.now() - t0}ms`);
|
|
261
|
+
} else {
|
|
262
|
+
await this.prefetchImages(args.body);
|
|
743
263
|
}
|
|
744
264
|
|
|
745
|
-
// WebSocket path
|
|
746
|
-
return this._executeWebSocket(nextArgs);
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
async _executeWithRetry(args) {
|
|
750
265
|
// Retry loop for SSE-level overloaded errors (200 OK body contains event: error)
|
|
266
|
+
// Reuses 503 retry config — same semantic: upstream temporarily unavailable
|
|
751
267
|
const retryConfig = { ...DEFAULT_RETRY_CONFIG, ...this.config.retry };
|
|
752
268
|
const { attempts, delayMs } = resolveRetryEntry(retryConfig[503]);
|
|
753
269
|
let attempt = 0;
|
|
@@ -755,6 +271,7 @@ export class CodexExecutor extends BaseExecutor {
|
|
|
755
271
|
const result = await super.execute(args);
|
|
756
272
|
const peek = await this._peekSseTransientError(result.response);
|
|
757
273
|
if (!peek.matched) {
|
|
274
|
+
// Replace body with re-assembled stream (prefix bytes already read + rest)
|
|
758
275
|
if (peek.replacementBody) {
|
|
759
276
|
result.response = new Response(peek.replacementBody, {
|
|
760
277
|
status: result.response.status,
|
|
@@ -762,23 +279,16 @@ export class CodexExecutor extends BaseExecutor {
|
|
|
762
279
|
headers: result.response.headers,
|
|
763
280
|
});
|
|
764
281
|
}
|
|
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
282
|
return result;
|
|
773
283
|
}
|
|
774
284
|
if (peek.accountFallback) {
|
|
775
285
|
args.log?.warn?.("RETRY", `CODEX | SSE account fallback "${peek.message}"`);
|
|
776
|
-
result.response =
|
|
286
|
+
result.response = codexSseErrorResponse(HTTP_STATUS.SERVICE_UNAVAILABLE, peek.message || CODEX_MODEL_CAPACITY_MESSAGE);
|
|
777
287
|
return result;
|
|
778
288
|
}
|
|
779
289
|
if (attempt >= attempts) {
|
|
780
290
|
args.log?.warn?.("RETRY", `CODEX | SSE overloaded "${peek.matched}" — retries exhausted (${attempt}/${attempts})`);
|
|
781
|
-
result.response =
|
|
291
|
+
result.response = codexSseErrorResponse(HTTP_STATUS.SERVICE_UNAVAILABLE, peek.message || peek.matched);
|
|
782
292
|
return result;
|
|
783
293
|
}
|
|
784
294
|
attempt++;
|
|
@@ -788,153 +298,10 @@ export class CodexExecutor extends BaseExecutor {
|
|
|
788
298
|
}
|
|
789
299
|
}
|
|
790
300
|
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
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
|
-
|
|
301
|
+
// Peek first N bytes of SSE body to detect upstream transient errors.
|
|
302
|
+
// Returns { matched: string|null, message: string|null, accountFallback: boolean, replacementBody: ReadableStream|null }.
|
|
303
|
+
// Caller must use replacementBody when no error matched (original body has been read).
|
|
929
304
|
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
305
|
if (!response || !response.ok || !response.body) return { matched: null, message: null, accountFallback: false, replacementBody: null };
|
|
939
306
|
const reader = response.body.getReader();
|
|
940
307
|
const decoder = new TextDecoder();
|
|
@@ -962,10 +329,12 @@ export class CodexExecutor extends BaseExecutor {
|
|
|
962
329
|
if (matched) {
|
|
963
330
|
try { await reader.cancel(); } catch { /* noop */ }
|
|
964
331
|
try { reader.releaseLock(); } catch { /* noop */ }
|
|
965
|
-
return { matched, message:
|
|
332
|
+
return { matched, message: extractSseErrorMessage(text, matched), accountFallback, replacementBody: null };
|
|
966
333
|
}
|
|
967
334
|
|
|
968
335
|
reader.releaseLock();
|
|
336
|
+
|
|
337
|
+
// Re-assemble stream: prefix chunks + remaining upstream body
|
|
969
338
|
const upstream = response.body;
|
|
970
339
|
let upstreamReader = null;
|
|
971
340
|
const replacementBody = new ReadableStream({
|
|
@@ -987,145 +356,7 @@ export class CodexExecutor extends BaseExecutor {
|
|
|
987
356
|
return { matched: null, message: null, accountFallback: false, replacementBody };
|
|
988
357
|
}
|
|
989
358
|
|
|
990
|
-
|
|
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
|
-
|
|
359
|
+
// Parse Codex usage_limit_reached to extract precise resetsAtMs; fallback to default otherwise
|
|
1129
360
|
parseError(response, bodyText) {
|
|
1130
361
|
if (response.status === 429 && bodyText) {
|
|
1131
362
|
try {
|
|
@@ -1141,144 +372,88 @@ export class CodexExecutor extends BaseExecutor {
|
|
|
1141
372
|
if (!resetsAtMs && typeof err.resets_in_seconds === "number" && err.resets_in_seconds > 0) {
|
|
1142
373
|
resetsAtMs = now + err.resets_in_seconds * 1000;
|
|
1143
374
|
}
|
|
1144
|
-
if (resetsAtMs)
|
|
375
|
+
if (resetsAtMs) {
|
|
376
|
+
return { status: 429, message: err.message || bodyText, resetsAtMs };
|
|
377
|
+
}
|
|
1145
378
|
}
|
|
1146
|
-
} catch { /* fall through */ }
|
|
379
|
+
} catch { /* fall through to default */ }
|
|
1147
380
|
}
|
|
1148
381
|
return super.parseError(response, bodyText);
|
|
1149
382
|
}
|
|
1150
383
|
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
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;
|
|
384
|
+
/**
|
|
385
|
+
* Transform request before sending - inject default instructions if missing.
|
|
386
|
+
* Image fetching is handled separately in prefetchImages() so this stays sync.
|
|
387
|
+
*/
|
|
388
|
+
transformRequest(model, body, stream, credentials) {
|
|
389
|
+
this._isCompact = !!body._compact;
|
|
1179
390
|
delete body._compact;
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
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
|
|
391
|
+
// Resolve conversation-stable session_id (priority: body → assistant-text → workspace → machine)
|
|
392
|
+
this._currentSessionId = resolveCacheSessionId(body, credentials);
|
|
393
|
+
// Convert string input to array format (Codex API requires input as array)
|
|
1192
394
|
const normalized = normalizeResponsesInput(body.input);
|
|
1193
395
|
if (normalized) body.input = normalized;
|
|
1194
396
|
|
|
1195
|
-
// Ensure input is present and non-empty
|
|
397
|
+
// Ensure input is present and non-empty (Codex API rejects empty input)
|
|
1196
398
|
if (!body.input || (Array.isArray(body.input) && body.input.length === 0)) {
|
|
1197
|
-
body.input = [{ type: "message", role: "user", content: [{ type: "input_text", text: "
|
|
399
|
+
body.input = [{ type: "message", role: "user", content: [{ type: "input_text", text: "..." }] }];
|
|
1198
400
|
}
|
|
1199
401
|
|
|
1200
|
-
|
|
1201
|
-
body.input = sanitizeResponsesInputItems(body.input, false, {
|
|
1202
|
-
dropInternalAssistantMessages: !nativeCodexPassthrough,
|
|
1203
|
-
});
|
|
1204
|
-
}
|
|
1205
|
-
repairMissingCodexFunctionCallOutputs(body);
|
|
1206
|
-
|
|
1207
|
-
// Cache-aware system → developer role conversion
|
|
402
|
+
// Keep system prompts in body.input as role=developer so they stay in the cacheable prefix
|
|
1208
403
|
convertSystemToDeveloperRole(body);
|
|
404
|
+
// Strip server-generated item IDs (rs_/fc_/resp_/msg_) — Codex /responses can't resolve when store=false
|
|
405
|
+
stripStoredItemReferences(body);
|
|
406
|
+
// Flatten function tools + drop unsupported types
|
|
407
|
+
normalizeCodexTools(body);
|
|
1209
408
|
|
|
1210
|
-
|
|
1211
|
-
|
|
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
|
-
}
|
|
409
|
+
// Ensure streaming is enabled (Codex API requires it)
|
|
410
|
+
body.stream = true;
|
|
1220
411
|
|
|
1221
|
-
//
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
delete body.store;
|
|
1225
|
-
} else if (explicitStoreSetting === true) {
|
|
1226
|
-
body.store = true;
|
|
1227
|
-
} else {
|
|
1228
|
-
body.store = false;
|
|
412
|
+
// If no instructions provided, inject default Codex instructions
|
|
413
|
+
if (!body.instructions || body.instructions.trim() === "") {
|
|
414
|
+
body.instructions = CODEX_DEFAULT_INSTRUCTIONS;
|
|
1229
415
|
}
|
|
1230
416
|
|
|
1231
|
-
//
|
|
1232
|
-
|
|
1233
|
-
dropImageGeneration: isCodexFreePlan(credentials?.providerSpecificData),
|
|
1234
|
-
preserveCustomTools: nativeCodexPassthrough,
|
|
1235
|
-
});
|
|
1236
|
-
|
|
1237
|
-
// Strip stored item references
|
|
1238
|
-
stripStoredItemReferences(body);
|
|
417
|
+
// Ensure store is false (Codex requirement)
|
|
418
|
+
body.store = false;
|
|
1239
419
|
|
|
1240
|
-
//
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
// Map virtual Codex review models to upstream
|
|
1245
|
-
if (typeof body.model === "string") {
|
|
1246
|
-
body.model = getModelUpstreamId("cx", body.model) || body.model;
|
|
420
|
+
// Inject prompt_cache_key for stable Codex prompt caching
|
|
421
|
+
if (!body.prompt_cache_key && this._currentSessionId) {
|
|
422
|
+
body.prompt_cache_key = this._currentSessionId;
|
|
1247
423
|
}
|
|
1248
424
|
|
|
425
|
+
// Map virtual Codex review models to the upstream Codex model before suffix parsing.
|
|
426
|
+
body.model = getModelUpstreamId("cx", body.model || model);
|
|
427
|
+
|
|
1249
428
|
// Extract thinking level from model name suffix
|
|
429
|
+
// e.g., gpt-5.3-codex-high → high, gpt-5.3-codex → medium (default)
|
|
430
|
+
const effortLevels = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh'];
|
|
1250
431
|
let modelEffort = null;
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
432
|
+
for (const level of effortLevels) {
|
|
433
|
+
if (body.model.endsWith(`-${level}`)) {
|
|
434
|
+
modelEffort = level;
|
|
435
|
+
// Strip suffix from model name for actual API call
|
|
436
|
+
body.model = body.model.replace(`-${level}`, '');
|
|
437
|
+
break;
|
|
438
|
+
}
|
|
1257
439
|
}
|
|
1258
440
|
|
|
1259
|
-
//
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
const rawEffort = modelEffort || explicitReasoning || requestReasoningEffort || fallbackReasoningEffort;
|
|
1267
|
-
|
|
1268
|
-
if (rawEffort) {
|
|
1269
|
-
body.reasoning = { ...(reasoningRecord || {}), effort: clampEffort(cleanModel, rawEffort) };
|
|
441
|
+
// Priority: explicit reasoning.effort > reasoning_effort param > model suffix > default (medium)
|
|
442
|
+
if (!body.reasoning) {
|
|
443
|
+
const effort = normalizeReasoningEffort(body.reasoning_effort || modelEffort || 'low');
|
|
444
|
+
body.reasoning = { effort, summary: "auto" };
|
|
445
|
+
} else {
|
|
446
|
+
body.reasoning.effort = normalizeReasoningEffort(body.reasoning.effort);
|
|
447
|
+
if (!body.reasoning.summary) body.reasoning.summary = "auto";
|
|
1270
448
|
}
|
|
1271
|
-
ensureCodexReasoningSummary(body);
|
|
1272
449
|
delete body.reasoning_effort;
|
|
1273
450
|
|
|
1274
|
-
//
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
delete body.safety_identifier;
|
|
1281
|
-
delete body.user;
|
|
451
|
+
// Include reasoning encrypted content (required by Codex backend for reasoning models)
|
|
452
|
+
if (body.reasoning && body.reasoning.effort && body.reasoning.effort !== 'none') {
|
|
453
|
+
body.include = ["reasoning.encrypted_content"];
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// Remove unsupported parameters for Codex API
|
|
1282
457
|
delete body.temperature;
|
|
1283
458
|
delete body.top_p;
|
|
1284
459
|
delete body.frequency_penalty;
|
|
@@ -1287,38 +462,24 @@ export class CodexExecutor extends BaseExecutor {
|
|
|
1287
462
|
delete body.top_logprobs;
|
|
1288
463
|
delete body.n;
|
|
1289
464
|
delete body.seed;
|
|
465
|
+
delete body.max_tokens;
|
|
1290
466
|
delete body.max_completion_tokens;
|
|
1291
|
-
delete body.
|
|
1292
|
-
delete body.
|
|
467
|
+
delete body.max_output_tokens; // Responses API clients send this but Codex rejects it
|
|
468
|
+
delete body.user; // Cursor sends this but Codex doesn't support it
|
|
469
|
+
delete body.prompt_cache_retention; // Cursor sends this but Codex doesn't support it
|
|
470
|
+
delete body.metadata; // Cursor sends this but Codex doesn't support it
|
|
471
|
+
delete body.stream_options; // Cursor sends this but Codex doesn't support it
|
|
472
|
+
delete body.safety_identifier; // Droid CLI sends this but Codex doesn't support it
|
|
473
|
+
delete body.previous_response_id; // store=false → backend can't resolve previous resp; avoid 404
|
|
1293
474
|
|
|
1294
|
-
|
|
1295
|
-
if (
|
|
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
|
-
}
|
|
475
|
+
if (body.service_tier === "fast") body.service_tier = "priority";
|
|
476
|
+
if (body.service_tier && body.service_tier !== "priority") delete body.service_tier;
|
|
1302
477
|
|
|
1303
|
-
//
|
|
1304
|
-
|
|
1305
|
-
|
|
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];
|
|
478
|
+
// Final allowlist filter — strip any unknown field that could trigger upstream "routing_unsupported"
|
|
479
|
+
for (const k of Object.keys(body)) {
|
|
480
|
+
if (!RESPONSES_API_ALLOWLIST.has(k)) delete body[k];
|
|
1318
481
|
}
|
|
1319
482
|
|
|
1320
483
|
return body;
|
|
1321
484
|
}
|
|
1322
485
|
}
|
|
1323
|
-
|
|
1324
|
-
export default CodexExecutor;
|