@fudrouter/fsrouter 0.6.63 → 0.6.64

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.
Files changed (559) hide show
  1. package/bin/rewriteSseImports.js +5 -1
  2. package/dist/open-sse/executors/cliproxyapi.js +2 -2
  3. package/dist/open-sse/services/rateLimitManager.js +4 -4
  4. package/package.json +1 -1
  5. package/open-sse/AGENTS.md +0 -39
  6. package/open-sse/config/anthropicHeaders.js +0 -87
  7. package/open-sse/config/appConstants.js +0 -238
  8. package/open-sse/config/audioRegistry.js +0 -506
  9. package/open-sse/config/cliFingerprints.js +0 -304
  10. package/open-sse/config/codexInstructions.js +0 -119
  11. package/open-sse/config/codexQuotaScopes.js +0 -42
  12. package/open-sse/config/constants.js +0 -4
  13. package/open-sse/config/contextEditing.js +0 -68
  14. package/open-sse/config/credentialLoader.js +0 -83
  15. package/open-sse/config/defaultThinkingSignature.js +0 -12
  16. package/open-sse/config/embeddingRegistry.js +0 -264
  17. package/open-sse/config/errorConfig.js +0 -96
  18. package/open-sse/config/freeModelCatalog.data.js +0 -121
  19. package/open-sse/config/freeModelCatalog.js +0 -90
  20. package/open-sse/config/freeTierCatalog.js +0 -81
  21. package/open-sse/config/googleTtsLanguages.js +0 -62
  22. package/open-sse/config/imageParamDefs.js +0 -360
  23. package/open-sse/config/imageRegistry.js +0 -493
  24. package/open-sse/config/kiroConstants.js +0 -268
  25. package/open-sse/config/mediaConfig.js +0 -27
  26. package/open-sse/config/mediaServiceKinds.js +0 -71
  27. package/open-sse/config/models.js +0 -13
  28. package/open-sse/config/moderationRegistry.js +0 -71
  29. package/open-sse/config/musicRegistry.js +0 -99
  30. package/open-sse/config/ocrRegistry.js +0 -61
  31. package/open-sse/config/ollamaModels.js +0 -19
  32. package/open-sse/config/providerErrorRules.js +0 -114
  33. package/open-sse/config/providerFieldStrips.js +0 -35
  34. package/open-sse/config/providerHeaderProfiles.js +0 -191
  35. package/open-sse/config/providerModels.js +0 -106
  36. package/open-sse/config/providerRegistry.js +0 -16
  37. package/open-sse/config/providers.js +0 -19
  38. package/open-sse/config/registryUtils.js +0 -106
  39. package/open-sse/config/rerankRegistry.js +0 -177
  40. package/open-sse/config/runtimeConfig.js +0 -96
  41. package/open-sse/config/runway.js +0 -39
  42. package/open-sse/config/searchRegistry.js +0 -153
  43. package/open-sse/config/toolCloaking.js +0 -199
  44. package/open-sse/config/ttsModels.js +0 -129
  45. package/open-sse/config/videoRegistry.js +0 -207
  46. package/open-sse/executors/adapta-web.js +0 -435
  47. package/open-sse/executors/antigravity.js +0 -534
  48. package/open-sse/executors/antigravityUpstreamError.js +0 -13
  49. package/open-sse/executors/auggie.js +0 -437
  50. package/open-sse/executors/azure-openai.js +0 -32
  51. package/open-sse/executors/azure.js +0 -57
  52. package/open-sse/executors/base.js +0 -181
  53. package/open-sse/executors/bedrock.js +0 -633
  54. package/open-sse/executors/blackbox-web.js +0 -578
  55. package/open-sse/executors/chatgpt-web.js +0 -2042
  56. package/open-sse/executors/chipotle.js +0 -357
  57. package/open-sse/executors/claude-web-with-auto-refresh.js +0 -73
  58. package/open-sse/executors/claude-web.js +0 -586
  59. package/open-sse/executors/cliproxyapi.js +0 -296
  60. package/open-sse/executors/cloudflare-ai.js +0 -46
  61. package/open-sse/executors/codebuddy-cn.js +0 -40
  62. package/open-sse/executors/codex.js +0 -1324
  63. package/open-sse/executors/commandCode.js +0 -558
  64. package/open-sse/executors/commandcode.js +0 -88
  65. package/open-sse/executors/copilot-m365-connection.js +0 -176
  66. package/open-sse/executors/copilot-m365-frames.js +0 -192
  67. package/open-sse/executors/copilot-m365-web.js +0 -299
  68. package/open-sse/executors/copilot-web.js +0 -580
  69. package/open-sse/executors/cursor.js +0 -795
  70. package/open-sse/executors/deepseek-web-with-auto-refresh.js +0 -150
  71. package/open-sse/executors/deepseek-web.js +0 -875
  72. package/open-sse/executors/default.js +0 -430
  73. package/open-sse/executors/devin-cli.js +0 -351
  74. package/open-sse/executors/doubao-web.js +0 -550
  75. package/open-sse/executors/duckduckgo-web.js +0 -629
  76. package/open-sse/executors/forceResponsesUpstream.js +0 -33
  77. package/open-sse/executors/gemini-business.js +0 -320
  78. package/open-sse/executors/gemini-cli.js +0 -89
  79. package/open-sse/executors/gemini-web.js +0 -297
  80. package/open-sse/executors/github.js +0 -379
  81. package/open-sse/executors/gitlab.js +0 -569
  82. package/open-sse/executors/glm.js +0 -361
  83. package/open-sse/executors/grok-cli.js +0 -119
  84. package/open-sse/executors/grok-web.js +0 -345
  85. package/open-sse/executors/huggingchat.js +0 -467
  86. package/open-sse/executors/iflow.js +0 -108
  87. package/open-sse/executors/index.js +0 -78
  88. package/open-sse/executors/inner-ai.js +0 -527
  89. package/open-sse/executors/kimchi.js +0 -123
  90. package/open-sse/executors/kimi-web.js +0 -325
  91. package/open-sse/executors/kimi.js +0 -97
  92. package/open-sse/executors/kiro.js +0 -503
  93. package/open-sse/executors/kiroThinking.js +0 -44
  94. package/open-sse/executors/lmarena.js +0 -395
  95. package/open-sse/executors/mimo-free.js +0 -167
  96. package/open-sse/executors/mimocode.js +0 -392
  97. package/open-sse/executors/ninerouter.js +0 -155
  98. package/open-sse/executors/nlpcloud.js +0 -438
  99. package/open-sse/executors/ollama-local.js +0 -14
  100. package/open-sse/executors/opencode-go.js +0 -41
  101. package/open-sse/executors/opencode.js +0 -32
  102. package/open-sse/executors/perplexity-web.js +0 -581
  103. package/open-sse/executors/poe-web.js +0 -133
  104. package/open-sse/executors/pollinations.js +0 -95
  105. package/open-sse/executors/puter.js +0 -31
  106. package/open-sse/executors/qoder.js +0 -448
  107. package/open-sse/executors/qwen-web.js +0 -372
  108. package/open-sse/executors/qwen.js +0 -129
  109. package/open-sse/executors/t3-chat-web.js +0 -417
  110. package/open-sse/executors/theoldllm.js +0 -290
  111. package/open-sse/executors/trae.js +0 -418
  112. package/open-sse/executors/v0-vercel-web.js +0 -141
  113. package/open-sse/executors/venice-web.js +0 -142
  114. package/open-sse/executors/vertex.js +0 -131
  115. package/open-sse/executors/vertexMedia.js +0 -236
  116. package/open-sse/executors/windsurf.js +0 -560
  117. package/open-sse/executors/xai.js +0 -46
  118. package/open-sse/executors/xiaomi-tokenplan.js +0 -19
  119. package/open-sse/executors/yuanbao-web.js +0 -385
  120. package/open-sse/executors/zed-hosted.js +0 -281
  121. package/open-sse/executors/zenmux-free.js +0 -247
  122. package/open-sse/handlers/audioSpeech.js +0 -759
  123. package/open-sse/handlers/audioTranscription.js +0 -395
  124. package/open-sse/handlers/audioTranslation.js +0 -181
  125. package/open-sse/handlers/chatCore/nonStreamingHandler.js +0 -300
  126. package/open-sse/handlers/chatCore/requestDetail.js +0 -102
  127. package/open-sse/handlers/chatCore/sseToJsonHandler.js +0 -231
  128. package/open-sse/handlers/chatCore/streamingHandler.js +0 -95
  129. package/open-sse/handlers/chatCore.js +0 -404
  130. package/open-sse/handlers/embeddingProviders/_base.js +0 -4
  131. package/open-sse/handlers/embeddingProviders/gemini.js +0 -54
  132. package/open-sse/handlers/embeddingProviders/index.js +0 -23
  133. package/open-sse/handlers/embeddingProviders/openai.js +0 -39
  134. package/open-sse/handlers/embeddingProviders/openaiCompatNode.js +0 -13
  135. package/open-sse/handlers/embeddingsCore.js +0 -126
  136. package/open-sse/handlers/fetch/index.js +0 -237
  137. package/open-sse/handlers/imageGenerationCore.js +0 -230
  138. package/open-sse/handlers/imageProviders/_base.js +0 -31
  139. package/open-sse/handlers/imageProviders/antigravity.js +0 -73
  140. package/open-sse/handlers/imageProviders/blackForestLabs.js +0 -63
  141. package/open-sse/handlers/imageProviders/cloudflareAi.js +0 -207
  142. package/open-sse/handlers/imageProviders/codex.js +0 -217
  143. package/open-sse/handlers/imageProviders/comfyui.js +0 -25
  144. package/open-sse/handlers/imageProviders/falAi.js +0 -62
  145. package/open-sse/handlers/imageProviders/gemini.js +0 -40
  146. package/open-sse/handlers/imageProviders/huggingface.js +0 -38
  147. package/open-sse/handlers/imageProviders/index.js +0 -44
  148. package/open-sse/handlers/imageProviders/leonardo.js +0 -435
  149. package/open-sse/handlers/imageProviders/nanobanana.js +0 -79
  150. package/open-sse/handlers/imageProviders/openai.js +0 -61
  151. package/open-sse/handlers/imageProviders/runwayml.js +0 -72
  152. package/open-sse/handlers/imageProviders/sdwebui.js +0 -36
  153. package/open-sse/handlers/imageProviders/stabilityAi.js +0 -59
  154. package/open-sse/handlers/imageProviders/weavy.js +0 -222
  155. package/open-sse/handlers/moderations.js +0 -92
  156. package/open-sse/handlers/ocr.js +0 -89
  157. package/open-sse/handlers/rerank.js +0 -223
  158. package/open-sse/handlers/responseSanitizer/reasoning.js +0 -144
  159. package/open-sse/handlers/responsesHandler.js +0 -99
  160. package/open-sse/handlers/search/callers.js +0 -371
  161. package/open-sse/handlers/search/chatSearch.js +0 -409
  162. package/open-sse/handlers/search/index.js +0 -201
  163. package/open-sse/handlers/search/normalizers.js +0 -223
  164. package/open-sse/handlers/search.js +0 -1056
  165. package/open-sse/handlers/sseParser.js +0 -469
  166. package/open-sse/handlers/sttCore.js +0 -193
  167. package/open-sse/handlers/ttsCore.js +0 -74
  168. package/open-sse/handlers/ttsProviders/_base.js +0 -39
  169. package/open-sse/handlers/ttsProviders/edgeTts.js +0 -89
  170. package/open-sse/handlers/ttsProviders/elevenlabs.js +0 -48
  171. package/open-sse/handlers/ttsProviders/gemini.js +0 -117
  172. package/open-sse/handlers/ttsProviders/genericFormats.js +0 -169
  173. package/open-sse/handlers/ttsProviders/googleTts.js +0 -54
  174. package/open-sse/handlers/ttsProviders/index.js +0 -50
  175. package/open-sse/handlers/ttsProviders/localDevice.js +0 -87
  176. package/open-sse/handlers/ttsProviders/minimax.js +0 -59
  177. package/open-sse/handlers/ttsProviders/openai.js +0 -30
  178. package/open-sse/handlers/ttsProviders/openrouter.js +0 -70
  179. package/open-sse/handlers/usageExtractor.js +0 -93
  180. package/open-sse/handlers/videoGenerationCore.js +0 -119
  181. package/open-sse/handlers/videoProviders/index.js +0 -22
  182. package/open-sse/handlers/videoProviders/leonardo.js +0 -511
  183. package/open-sse/handlers/videoProviders/weavy.js +0 -198
  184. package/open-sse/handlers/webFetch.js +0 -200
  185. package/open-sse/index.js +0 -79
  186. package/open-sse/mcp-server/audit.js +0 -283
  187. package/open-sse/mcp-server/catalog.js +0 -184
  188. package/open-sse/mcp-server/descriptionCompressor.js +0 -175
  189. package/open-sse/mcp-server/httpAuthContext.js +0 -32
  190. package/open-sse/mcp-server/httpTransport.js +0 -229
  191. package/open-sse/mcp-server/index.js +0 -33
  192. package/open-sse/mcp-server/mcpCallerIdentity.js +0 -21
  193. package/open-sse/mcp-server/runtimeHeartbeat.js +0 -110
  194. package/open-sse/mcp-server/schemas/a2a.js +0 -153
  195. package/open-sse/mcp-server/schemas/audit.js +0 -17
  196. package/open-sse/mcp-server/schemas/index.js +0 -166
  197. package/open-sse/mcp-server/schemas/pickFastestModel.js +0 -90
  198. package/open-sse/mcp-server/schemas/toolDefinition.js +0 -0
  199. package/open-sse/mcp-server/schemas/toolSearch.js +0 -32
  200. package/open-sse/mcp-server/schemas/tools.js +0 -1219
  201. package/open-sse/mcp-server/scopeEnforcement.js +0 -80
  202. package/open-sse/mcp-server/server.js +0 -1168
  203. package/open-sse/mcp-server/toolCardinality.js +0 -78
  204. package/open-sse/mcp-server/toolSearch/catalog.js +0 -66
  205. package/open-sse/mcp-server/toolSearch/handler.js +0 -20
  206. package/open-sse/mcp-server/toolSearch/index.js +0 -10
  207. package/open-sse/mcp-server/toolSearch/register.js +0 -21
  208. package/open-sse/mcp-server/toolSearch/search.js +0 -55
  209. package/open-sse/mcp-server/toolSearch/signature.js +0 -67
  210. package/open-sse/mcp-server/tools/advancedTools.js +0 -893
  211. package/open-sse/mcp-server/tools/agentSkillTools.js +0 -69
  212. package/open-sse/mcp-server/tools/compressionTools.js +0 -309
  213. package/open-sse/mcp-server/tools/gamificationTools.js +0 -134
  214. package/open-sse/mcp-server/tools/githubSkillTools.js +0 -102
  215. package/open-sse/mcp-server/tools/memoryTools.js +0 -118
  216. package/open-sse/mcp-server/tools/notionTools.js +0 -101
  217. package/open-sse/mcp-server/tools/obsidianTools.js +0 -307
  218. package/open-sse/mcp-server/tools/pickFastestModel.js +0 -223
  219. package/open-sse/mcp-server/tools/pluginTools.js +0 -181
  220. package/open-sse/mcp-server/tools/poolTools.js +0 -139
  221. package/open-sse/mcp-server/tools/skillTools.js +0 -113
  222. package/open-sse/package.json +0 -10
  223. package/open-sse/providers/REGISTRY_TEMPLATE.js +0 -98
  224. package/open-sse/providers/capabilities.js +0 -293
  225. package/open-sse/providers/index.js +0 -51
  226. package/open-sse/providers/models/helpers.js +0 -20
  227. package/open-sse/providers/models/namePatterns.js +0 -33
  228. package/open-sse/providers/models/schema.js +0 -40
  229. package/open-sse/providers/pricing.js +0 -308
  230. package/open-sse/providers/registry/alicode-intl.js +0 -30
  231. package/open-sse/providers/registry/alicode.js +0 -31
  232. package/open-sse/providers/registry/anthropic.js +0 -37
  233. package/open-sse/providers/registry/antigravity.js +0 -81
  234. package/open-sse/providers/registry/assemblyai.js +0 -38
  235. package/open-sse/providers/registry/aws-polly.js +0 -45
  236. package/open-sse/providers/registry/azure.js +0 -21
  237. package/open-sse/providers/registry/black-forest-labs.js +0 -32
  238. package/open-sse/providers/registry/blackbox.js +0 -41
  239. package/open-sse/providers/registry/brave-search.js +0 -35
  240. package/open-sse/providers/registry/byteplus.js +0 -35
  241. package/open-sse/providers/registry/cartesia.js +0 -36
  242. package/open-sse/providers/registry/cerebras.js +0 -31
  243. package/open-sse/providers/registry/chutes.js +0 -24
  244. package/open-sse/providers/registry/claude.js +0 -87
  245. package/open-sse/providers/registry/cline.js +0 -51
  246. package/open-sse/providers/registry/clinepass.js +0 -57
  247. package/open-sse/providers/registry/cloudflare-ai.js +0 -55
  248. package/open-sse/providers/registry/codebuddy-cn.js +0 -77
  249. package/open-sse/providers/registry/codex.js +0 -100
  250. package/open-sse/providers/registry/cohere.js +0 -27
  251. package/open-sse/providers/registry/comfyui.js +0 -20
  252. package/open-sse/providers/registry/commandcode.js +0 -43
  253. package/open-sse/providers/registry/coqui.js +0 -30
  254. package/open-sse/providers/registry/cursor.js +0 -58
  255. package/open-sse/providers/registry/deepgram.js +0 -33
  256. package/open-sse/providers/registry/deepseek.js +0 -51
  257. package/open-sse/providers/registry/digitalocean.js +0 -92
  258. package/open-sse/providers/registry/edge-tts.js +0 -24
  259. package/open-sse/providers/registry/elevenlabs.js +0 -35
  260. package/open-sse/providers/registry/exa.js +0 -50
  261. package/open-sse/providers/registry/fal-ai.js +0 -34
  262. package/open-sse/providers/registry/featherless.js +0 -34
  263. package/open-sse/providers/registry/firecrawl.js +0 -34
  264. package/open-sse/providers/registry/fireworks.js +0 -29
  265. package/open-sse/providers/registry/gemini-cli.js +0 -58
  266. package/open-sse/providers/registry/gemini.js +0 -83
  267. package/open-sse/providers/registry/github.js +0 -88
  268. package/open-sse/providers/registry/gitlab.js +0 -32
  269. package/open-sse/providers/registry/glm-cn.js +0 -35
  270. package/open-sse/providers/registry/glm.js +0 -58
  271. package/open-sse/providers/registry/google-pse.js +0 -35
  272. package/open-sse/providers/registry/google-tts.js +0 -24
  273. package/open-sse/providers/registry/grok-cli.js +0 -86
  274. package/open-sse/providers/registry/grok-web.js +0 -39
  275. package/open-sse/providers/registry/groq.js +0 -37
  276. package/open-sse/providers/registry/huggingface.js +0 -34
  277. package/open-sse/providers/registry/hyperbolic.js +0 -35
  278. package/open-sse/providers/registry/ibm-bob.js +0 -27
  279. package/open-sse/providers/registry/iflow.js +0 -52
  280. package/open-sse/providers/registry/index.js +0 -210
  281. package/open-sse/providers/registry/inworld.js +0 -36
  282. package/open-sse/providers/registry/jina-ai.js +0 -42
  283. package/open-sse/providers/registry/jina-reader.js +0 -34
  284. package/open-sse/providers/registry/kilocode.js +0 -51
  285. package/open-sse/providers/registry/kimchi.js +0 -49
  286. package/open-sse/providers/registry/kimi-coding.js +0 -65
  287. package/open-sse/providers/registry/kimi.js +0 -56
  288. package/open-sse/providers/registry/kiro.js +0 -115
  289. package/open-sse/providers/registry/linkup.js +0 -34
  290. package/open-sse/providers/registry/local-device.js +0 -24
  291. package/open-sse/providers/registry/mimo-free.js +0 -24
  292. package/open-sse/providers/registry/minimax-cn.js +0 -76
  293. package/open-sse/providers/registry/minimax.js +0 -83
  294. package/open-sse/providers/registry/mistral.js +0 -34
  295. package/open-sse/providers/registry/mmf.js +0 -19
  296. package/open-sse/providers/registry/nanobanana.js +0 -35
  297. package/open-sse/providers/registry/nebius.js +0 -27
  298. package/open-sse/providers/registry/nvidia.js +0 -43
  299. package/open-sse/providers/registry/ollama-local.js +0 -19
  300. package/open-sse/providers/registry/ollama.js +0 -36
  301. package/open-sse/providers/registry/openai.js +0 -84
  302. package/open-sse/providers/registry/opencode-go.js +0 -41
  303. package/open-sse/providers/registry/opencode.js +0 -25
  304. package/open-sse/providers/registry/openrouter.js +0 -60
  305. package/open-sse/providers/registry/perplexity-agent.js +0 -49
  306. package/open-sse/providers/registry/perplexity-web.js +0 -33
  307. package/open-sse/providers/registry/perplexity.js +0 -37
  308. package/open-sse/providers/registry/playht.js +0 -36
  309. package/open-sse/providers/registry/qoder.js +0 -54
  310. package/open-sse/providers/registry/qwen.js +0 -33
  311. package/open-sse/providers/registry/recraft.js +0 -24
  312. package/open-sse/providers/registry/runwayml.js +0 -30
  313. package/open-sse/providers/registry/sdwebui.js +0 -20
  314. package/open-sse/providers/registry/searchapi.js +0 -35
  315. package/open-sse/providers/registry/searxng.js +0 -35
  316. package/open-sse/providers/registry/serper.js +0 -35
  317. package/open-sse/providers/registry/siliconflow.js +0 -39
  318. package/open-sse/providers/registry/stability-ai.js +0 -31
  319. package/open-sse/providers/registry/tavily.js +0 -50
  320. package/open-sse/providers/registry/together.js +0 -31
  321. package/open-sse/providers/registry/topaz.js +0 -19
  322. package/open-sse/providers/registry/tortoise.js +0 -30
  323. package/open-sse/providers/registry/venice.js +0 -56
  324. package/open-sse/providers/registry/vercel-ai-gateway.js +0 -41
  325. package/open-sse/providers/registry/vertex-partner.js +0 -29
  326. package/open-sse/providers/registry/vertex.js +0 -32
  327. package/open-sse/providers/registry/volcengine-ark.js +0 -35
  328. package/open-sse/providers/registry/voyage-ai.js +0 -30
  329. package/open-sse/providers/registry/xai.js +0 -45
  330. package/open-sse/providers/registry/xiaomi-mimo.js +0 -46
  331. package/open-sse/providers/registry/xiaomi-tokenplan.js +0 -63
  332. package/open-sse/providers/registry/youcom.js +0 -35
  333. package/open-sse/providers/schema.js +0 -76
  334. package/open-sse/providers/shared.js +0 -74
  335. package/open-sse/providers/thinkingLevels.js +0 -48
  336. package/open-sse/rtk/applyFilter.js +0 -15
  337. package/open-sse/rtk/autodetect.js +0 -111
  338. package/open-sse/rtk/caveman.js +0 -100
  339. package/open-sse/rtk/cavemanPrompts.js +0 -78
  340. package/open-sse/rtk/constants.js +0 -55
  341. package/open-sse/rtk/filters/buildOutput.js +0 -127
  342. package/open-sse/rtk/filters/dedupLog.js +0 -44
  343. package/open-sse/rtk/filters/find.js +0 -50
  344. package/open-sse/rtk/filters/gitDiff.js +0 -92
  345. package/open-sse/rtk/filters/gitLog.js +0 -99
  346. package/open-sse/rtk/filters/gitStatus.js +0 -117
  347. package/open-sse/rtk/filters/grep.js +0 -48
  348. package/open-sse/rtk/filters/ls.js +0 -79
  349. package/open-sse/rtk/filters/readNumbered.js +0 -27
  350. package/open-sse/rtk/filters/searchList.js +0 -52
  351. package/open-sse/rtk/filters/smartTruncate.js +0 -15
  352. package/open-sse/rtk/filters/tree.js +0 -32
  353. package/open-sse/rtk/headroom.js +0 -215
  354. package/open-sse/rtk/index.js +0 -155
  355. package/open-sse/rtk/paleo.js +0 -47
  356. package/open-sse/rtk/ponytail.js +0 -9
  357. package/open-sse/rtk/ponytailPrompt.js +0 -52
  358. package/open-sse/rtk/ponytailPrompts.js +0 -76
  359. package/open-sse/rtk/pxpipe.js +0 -104
  360. package/open-sse/rtk/registry.js +0 -38
  361. package/open-sse/rtk/systemInject.js +0 -98
  362. package/open-sse/services/accountFallback.js +0 -323
  363. package/open-sse/services/antigravityHeaders.js +0 -91
  364. package/open-sse/services/antigravityVersion.js +0 -154
  365. package/open-sse/services/clinepassModels.js +0 -63
  366. package/open-sse/services/codexQuotaFetcher.js +0 -312
  367. package/open-sse/services/codexVerbosity.js +0 -30
  368. package/open-sse/services/combo/context.js +0 -12
  369. package/open-sse/services/combo/fingerprintExpansion.js +0 -51
  370. package/open-sse/services/combo/headroomRanking.js +0 -28
  371. package/open-sse/services/combo/quotaExhaustionCutoff.js +0 -87
  372. package/open-sse/services/combo/quotaScoring.js +0 -226
  373. package/open-sse/services/combo/quotaShareConcurrency.js +0 -25
  374. package/open-sse/services/combo/quotaShareInflight.js +0 -50
  375. package/open-sse/services/combo/quotaShareStrategy.js +0 -130
  376. package/open-sse/services/combo/resolveAutoStrategy.js +0 -231
  377. package/open-sse/services/combo/responseValidation.js +0 -140
  378. package/open-sse/services/combo/runtimeUnits.js +0 -195
  379. package/open-sse/services/combo/sessionStickiness.js +0 -128
  380. package/open-sse/services/combo/shadowRouting.js +0 -131
  381. package/open-sse/services/combo/targetExhaustion.js +0 -75
  382. package/open-sse/services/combo/targetSorters.js +0 -126
  383. package/open-sse/services/combo/targetTimeoutRunner.js +0 -65
  384. package/open-sse/services/combo/validateQuality.js +0 -271
  385. package/open-sse/services/combo.js +0 -571
  386. package/open-sse/services/comboAgentMiddleware.js +0 -91
  387. package/open-sse/services/comboConfig.js +0 -153
  388. package/open-sse/services/comboManifestMetrics.js +0 -10
  389. package/open-sse/services/comboMetrics.js +0 -278
  390. package/open-sse/services/compact.js +0 -71
  391. package/open-sse/services/copilotModels.js +0 -155
  392. package/open-sse/services/emergencyFallback.js +0 -109
  393. package/open-sse/services/errorClassifier.js +0 -190
  394. package/open-sse/services/evalRouting.js +0 -201
  395. package/open-sse/services/freeWebSearch.js +0 -4
  396. package/open-sse/services/fusion.js +0 -223
  397. package/open-sse/services/intentClassifier.js +0 -631
  398. package/open-sse/services/kimchiModels.js +0 -176
  399. package/open-sse/services/kiroModels.js +0 -332
  400. package/open-sse/services/model.js +0 -136
  401. package/open-sse/services/modelCapabilities.js +0 -5
  402. package/open-sse/services/modelDeprecation.js +0 -101
  403. package/open-sse/services/modelFamilyFallback.js +0 -166
  404. package/open-sse/services/oauthCredentialManager.js +0 -156
  405. package/open-sse/services/pipeline.js +0 -107
  406. package/open-sse/services/projectId.js +0 -306
  407. package/open-sse/services/provider.js +0 -169
  408. package/open-sse/services/providerCooldownTracker.js +0 -94
  409. package/open-sse/services/providerDefaultRateLimit.js +0 -11
  410. package/open-sse/services/proxyAutoSelector.js +0 -24
  411. package/open-sse/services/qoderModels.js +0 -214
  412. package/open-sse/services/quotaFetchThrottle.js +0 -103
  413. package/open-sse/services/quotaMonitor.js +0 -310
  414. package/open-sse/services/quotaPreflight.js +0 -266
  415. package/open-sse/services/rateLimitManager/headers.js +0 -56
  416. package/open-sse/services/rateLimitManager.js +0 -616
  417. package/open-sse/services/rateLimitSemaphore.js +0 -112
  418. package/open-sse/services/responsesInputSanitizer.js +0 -99
  419. package/open-sse/services/slidingWindowLimiter.js +0 -44
  420. package/open-sse/services/streamRecovery.js +0 -355
  421. package/open-sse/services/taskAwareRouter.js +0 -227
  422. package/open-sse/services/taskAwareRouting.js +0 -332
  423. package/open-sse/services/thinkingBudget.js +0 -247
  424. package/open-sse/services/tokenRefresh/dedup.js +0 -31
  425. package/open-sse/services/tokenRefresh/providers.js +0 -624
  426. package/open-sse/services/tokenRefresh.js +0 -254
  427. package/open-sse/services/usage/claude.js +0 -147
  428. package/open-sse/services/usage/codebuddy-cn.js +0 -138
  429. package/open-sse/services/usage/codex.js +0 -267
  430. package/open-sse/services/usage/github.js +0 -100
  431. package/open-sse/services/usage/google.js +0 -241
  432. package/open-sse/services/usage/grok-cli.js +0 -274
  433. package/open-sse/services/usage/kiro.js +0 -188
  434. package/open-sse/services/usage/minimax.js +0 -234
  435. package/open-sse/services/usage/misc.js +0 -288
  436. package/open-sse/services/usage/shared.js +0 -70
  437. package/open-sse/services/usage.js +0 -62
  438. package/open-sse/services/usageDb.js +0 -2
  439. package/open-sse/services/webSearchRouting.js +0 -25
  440. package/open-sse/services/wildcardRouter.js +0 -59
  441. package/open-sse/shared/clineAuth.js +0 -37
  442. package/open-sse/shared/machineId.js +0 -19
  443. package/open-sse/shared/qoder/constants.js +0 -64
  444. package/open-sse/shared/qoder/cosy.js +0 -175
  445. package/open-sse/shared/qoder/encoding.js +0 -55
  446. package/open-sse/transformer/responsesTransformer.js +0 -439
  447. package/open-sse/transformer/streamToJsonConverter.js +0 -103
  448. package/open-sse/translator/concerns/chunk.js +0 -11
  449. package/open-sse/translator/concerns/finishReason.js +0 -63
  450. package/open-sse/translator/concerns/image.js +0 -124
  451. package/open-sse/translator/concerns/json.js +0 -5
  452. package/open-sse/translator/concerns/message.js +0 -7
  453. package/open-sse/translator/concerns/modality.js +0 -155
  454. package/open-sse/translator/concerns/paramSupport.js +0 -75
  455. package/open-sse/translator/concerns/prefetch.js +0 -96
  456. package/open-sse/translator/concerns/reasoning.js +0 -24
  457. package/open-sse/translator/concerns/thinking.js +0 -53
  458. package/open-sse/translator/concerns/thinkingUnified.js +0 -329
  459. package/open-sse/translator/concerns/toolCall.js +0 -153
  460. package/open-sse/translator/concerns/usage.js +0 -69
  461. package/open-sse/translator/formats/claude.js +0 -368
  462. package/open-sse/translator/formats/gemini.js +0 -380
  463. package/open-sse/translator/formats/maxTokens.js +0 -34
  464. package/open-sse/translator/formats/openai.js +0 -134
  465. package/open-sse/translator/formats/responsesApi.js +0 -141
  466. package/open-sse/translator/formats.js +0 -36
  467. package/open-sse/translator/helpers/claudeHelper.js +0 -216
  468. package/open-sse/translator/helpers/geminiHelper.js +0 -372
  469. package/open-sse/translator/helpers/imageHelper.js +0 -34
  470. package/open-sse/translator/helpers/maxTokensHelper.js +0 -27
  471. package/open-sse/translator/helpers/openaiHelper.js +0 -130
  472. package/open-sse/translator/helpers/responsesApiHelper.js +0 -139
  473. package/open-sse/translator/helpers/toolCallHelper.js +0 -148
  474. package/open-sse/translator/index.js +0 -252
  475. package/open-sse/translator/request/antigravity-to-openai.js +0 -242
  476. package/open-sse/translator/request/claude-to-kiro.js +0 -478
  477. package/open-sse/translator/request/claude-to-openai.js +0 -263
  478. package/open-sse/translator/request/gemini-to-openai.js +0 -152
  479. package/open-sse/translator/request/openai-responses.js +0 -385
  480. package/open-sse/translator/request/openai-to-claude.js +0 -383
  481. package/open-sse/translator/request/openai-to-commandcode.js +0 -176
  482. package/open-sse/translator/request/openai-to-cursor.js +0 -185
  483. package/open-sse/translator/request/openai-to-gemini.js +0 -442
  484. package/open-sse/translator/request/openai-to-kiro.js +0 -607
  485. package/open-sse/translator/request/openai-to-kiro.old.js +0 -278
  486. package/open-sse/translator/request/openai-to-ollama.js +0 -195
  487. package/open-sse/translator/request/openai-to-vertex.js +0 -42
  488. package/open-sse/translator/response/claude-to-openai.js +0 -195
  489. package/open-sse/translator/response/commandcode-to-openai.js +0 -188
  490. package/open-sse/translator/response/cursor-to-openai.js +0 -30
  491. package/open-sse/translator/response/gemini-to-openai.js +0 -147
  492. package/open-sse/translator/response/kiro-to-claude.js +0 -261
  493. package/open-sse/translator/response/kiro-to-openai.js +0 -160
  494. package/open-sse/translator/response/ollama-to-openai.js +0 -134
  495. package/open-sse/translator/response/openai-responses.js +0 -535
  496. package/open-sse/translator/response/openai-to-antigravity.js +0 -123
  497. package/open-sse/translator/response/openai-to-claude.js +0 -265
  498. package/open-sse/translator/schema/blocks.js +0 -43
  499. package/open-sse/translator/schema/defaults.js +0 -7
  500. package/open-sse/translator/schema/finishReasons.js +0 -27
  501. package/open-sse/translator/schema/index.js +0 -8
  502. package/open-sse/translator/schema/roles.js +0 -16
  503. package/open-sse/utils/agentGoalPolicy.js +0 -85
  504. package/open-sse/utils/aiSdkCompat.js +0 -75
  505. package/open-sse/utils/bypassHandler.js +0 -298
  506. package/open-sse/utils/cacheControlPolicy.js +0 -189
  507. package/open-sse/utils/claudeCloaking.js +0 -155
  508. package/open-sse/utils/claudeHeaderCache.js +0 -70
  509. package/open-sse/utils/claudeSignature.js +0 -41
  510. package/open-sse/utils/clientDetector.js +0 -63
  511. package/open-sse/utils/codebuddySanitizer.js +0 -96
  512. package/open-sse/utils/composerToolCalls.js +0 -158
  513. package/open-sse/utils/cors.js +0 -13
  514. package/open-sse/utils/cursorChecksum.js +0 -149
  515. package/open-sse/utils/cursorImages.js +0 -224
  516. package/open-sse/utils/cursorProtobuf.js +0 -904
  517. package/open-sse/utils/cursorVersionDetector.js +0 -55
  518. package/open-sse/utils/debugLog.js +0 -14
  519. package/open-sse/utils/diagnostics.js +0 -143
  520. package/open-sse/utils/error.js +0 -164
  521. package/open-sse/utils/estimateSize.js +0 -33
  522. package/open-sse/utils/finishReason.js +0 -32
  523. package/open-sse/utils/flattenToolHistory.js +0 -68
  524. package/open-sse/utils/headers.js +0 -36
  525. package/open-sse/utils/heapPressure.js +0 -35
  526. package/open-sse/utils/jsonToSse.js +0 -125
  527. package/open-sse/utils/keepaliveThreshold.js +0 -40
  528. package/open-sse/utils/logger.js +0 -104
  529. package/open-sse/utils/noThinkingAlias.js +0 -74
  530. package/open-sse/utils/number.js +0 -7
  531. package/open-sse/utils/ollamaTransform.js +0 -85
  532. package/open-sse/utils/opencodeHeaders.js +0 -47
  533. package/open-sse/utils/progressTracker.js +0 -81
  534. package/open-sse/utils/providerRequestLogging.js +0 -219
  535. package/open-sse/utils/proxyFetch.js +0 -369
  536. package/open-sse/utils/reasoningContentInjector.js +0 -79
  537. package/open-sse/utils/reasoningFields.js +0 -70
  538. package/open-sse/utils/requestLogger.js +0 -260
  539. package/open-sse/utils/responsesInputNormalization.js +0 -92
  540. package/open-sse/utils/responsesStatePolicy.js +0 -52
  541. package/open-sse/utils/responsesStreamHelpers.js +0 -49
  542. package/open-sse/utils/sessionManager.js +0 -240
  543. package/open-sse/utils/sleep.js +0 -6
  544. package/open-sse/utils/sse.js +0 -14
  545. package/open-sse/utils/sseConstants.js +0 -23
  546. package/open-sse/utils/sseHeartbeat.js +0 -104
  547. package/open-sse/utils/stream.js +0 -517
  548. package/open-sse/utils/streamFailureFinalization.js +0 -134
  549. package/open-sse/utils/streamHandler.js +0 -250
  550. package/open-sse/utils/streamHelpers.js +0 -137
  551. package/open-sse/utils/textualToolCall.js +0 -104
  552. package/open-sse/utils/thinkCloseMarker.js +0 -72
  553. package/open-sse/utils/thinkTagParser.js +0 -146
  554. package/open-sse/utils/toolCallArguments.js +0 -12
  555. package/open-sse/utils/toolDeduper.js +0 -49
  556. package/open-sse/utils/toolSources.js +0 -31
  557. package/open-sse/utils/upstreamResponseHeaders.js +0 -25
  558. package/open-sse/utils/urlSanitize.js +0 -15
  559. package/open-sse/utils/usageTracking.js +0 -347
@@ -1,1324 +0,0 @@
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;