@fudrouter/fsrouter 0.6.64 → 0.6.65

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 (556) hide show
  1. package/open-sse/AGENTS.md +39 -0
  2. package/open-sse/config/anthropicHeaders.js +87 -0
  3. package/open-sse/config/appConstants.js +238 -0
  4. package/open-sse/config/audioRegistry.js +506 -0
  5. package/open-sse/config/cliFingerprints.js +304 -0
  6. package/open-sse/config/codexInstructions.js +119 -0
  7. package/open-sse/config/codexQuotaScopes.js +42 -0
  8. package/open-sse/config/constants.js +4 -0
  9. package/open-sse/config/contextEditing.js +68 -0
  10. package/open-sse/config/credentialLoader.js +83 -0
  11. package/open-sse/config/defaultThinkingSignature.js +12 -0
  12. package/open-sse/config/embeddingRegistry.js +264 -0
  13. package/open-sse/config/errorConfig.js +96 -0
  14. package/open-sse/config/freeModelCatalog.data.js +121 -0
  15. package/open-sse/config/freeModelCatalog.js +90 -0
  16. package/open-sse/config/freeTierCatalog.js +81 -0
  17. package/open-sse/config/googleTtsLanguages.js +62 -0
  18. package/open-sse/config/imageParamDefs.js +360 -0
  19. package/open-sse/config/imageRegistry.js +493 -0
  20. package/open-sse/config/kiroConstants.js +268 -0
  21. package/open-sse/config/mediaConfig.js +27 -0
  22. package/open-sse/config/mediaServiceKinds.js +71 -0
  23. package/open-sse/config/models.js +13 -0
  24. package/open-sse/config/moderationRegistry.js +71 -0
  25. package/open-sse/config/musicRegistry.js +99 -0
  26. package/open-sse/config/ocrRegistry.js +61 -0
  27. package/open-sse/config/ollamaModels.js +19 -0
  28. package/open-sse/config/providerErrorRules.js +114 -0
  29. package/open-sse/config/providerFieldStrips.js +35 -0
  30. package/open-sse/config/providerHeaderProfiles.js +191 -0
  31. package/open-sse/config/providerModels.js +106 -0
  32. package/open-sse/config/providerRegistry.js +16 -0
  33. package/open-sse/config/providers.js +19 -0
  34. package/open-sse/config/registryUtils.js +106 -0
  35. package/open-sse/config/rerankRegistry.js +177 -0
  36. package/open-sse/config/runtimeConfig.js +96 -0
  37. package/open-sse/config/runway.js +39 -0
  38. package/open-sse/config/searchRegistry.js +153 -0
  39. package/open-sse/config/toolCloaking.js +199 -0
  40. package/open-sse/config/ttsModels.js +129 -0
  41. package/open-sse/config/videoRegistry.js +207 -0
  42. package/open-sse/executors/adapta-web.js +435 -0
  43. package/open-sse/executors/antigravity.js +534 -0
  44. package/open-sse/executors/antigravityUpstreamError.js +13 -0
  45. package/open-sse/executors/auggie.js +437 -0
  46. package/open-sse/executors/azure-openai.js +32 -0
  47. package/open-sse/executors/azure.js +57 -0
  48. package/open-sse/executors/base.js +181 -0
  49. package/open-sse/executors/bedrock.js +633 -0
  50. package/open-sse/executors/blackbox-web.js +578 -0
  51. package/open-sse/executors/chatgpt-web.js +2042 -0
  52. package/open-sse/executors/chipotle.js +357 -0
  53. package/open-sse/executors/claude-web-with-auto-refresh.js +73 -0
  54. package/open-sse/executors/claude-web.js +586 -0
  55. package/open-sse/executors/cliproxyapi.js +296 -0
  56. package/open-sse/executors/cloudflare-ai.js +46 -0
  57. package/open-sse/executors/codebuddy-cn.js +40 -0
  58. package/open-sse/executors/codex.js +1324 -0
  59. package/open-sse/executors/commandCode.js +558 -0
  60. package/open-sse/executors/commandcode.js +88 -0
  61. package/open-sse/executors/copilot-m365-connection.js +176 -0
  62. package/open-sse/executors/copilot-m365-frames.js +192 -0
  63. package/open-sse/executors/copilot-m365-web.js +299 -0
  64. package/open-sse/executors/copilot-web.js +580 -0
  65. package/open-sse/executors/cursor.js +795 -0
  66. package/open-sse/executors/deepseek-web-with-auto-refresh.js +150 -0
  67. package/open-sse/executors/deepseek-web.js +875 -0
  68. package/open-sse/executors/default.js +430 -0
  69. package/open-sse/executors/devin-cli.js +351 -0
  70. package/open-sse/executors/doubao-web.js +550 -0
  71. package/open-sse/executors/duckduckgo-web.js +629 -0
  72. package/open-sse/executors/forceResponsesUpstream.js +33 -0
  73. package/open-sse/executors/gemini-business.js +320 -0
  74. package/open-sse/executors/gemini-cli.js +89 -0
  75. package/open-sse/executors/gemini-web.js +297 -0
  76. package/open-sse/executors/github.js +379 -0
  77. package/open-sse/executors/gitlab.js +569 -0
  78. package/open-sse/executors/glm.js +361 -0
  79. package/open-sse/executors/grok-cli.js +119 -0
  80. package/open-sse/executors/grok-web.js +345 -0
  81. package/open-sse/executors/huggingchat.js +467 -0
  82. package/open-sse/executors/iflow.js +108 -0
  83. package/open-sse/executors/index.js +78 -0
  84. package/open-sse/executors/inner-ai.js +527 -0
  85. package/open-sse/executors/kimchi.js +123 -0
  86. package/open-sse/executors/kimi-web.js +325 -0
  87. package/open-sse/executors/kimi.js +97 -0
  88. package/open-sse/executors/kiro.js +503 -0
  89. package/open-sse/executors/kiroThinking.js +44 -0
  90. package/open-sse/executors/lmarena.js +395 -0
  91. package/open-sse/executors/mimo-free.js +167 -0
  92. package/open-sse/executors/mimocode.js +392 -0
  93. package/open-sse/executors/ninerouter.js +155 -0
  94. package/open-sse/executors/nlpcloud.js +438 -0
  95. package/open-sse/executors/ollama-local.js +14 -0
  96. package/open-sse/executors/opencode-go.js +41 -0
  97. package/open-sse/executors/opencode.js +32 -0
  98. package/open-sse/executors/perplexity-web.js +581 -0
  99. package/open-sse/executors/poe-web.js +133 -0
  100. package/open-sse/executors/pollinations.js +95 -0
  101. package/open-sse/executors/puter.js +31 -0
  102. package/open-sse/executors/qoder.js +448 -0
  103. package/open-sse/executors/qwen-web.js +372 -0
  104. package/open-sse/executors/qwen.js +129 -0
  105. package/open-sse/executors/t3-chat-web.js +417 -0
  106. package/open-sse/executors/theoldllm.js +290 -0
  107. package/open-sse/executors/trae.js +418 -0
  108. package/open-sse/executors/v0-vercel-web.js +141 -0
  109. package/open-sse/executors/venice-web.js +142 -0
  110. package/open-sse/executors/vertex.js +131 -0
  111. package/open-sse/executors/vertexMedia.js +236 -0
  112. package/open-sse/executors/windsurf.js +560 -0
  113. package/open-sse/executors/xai.js +46 -0
  114. package/open-sse/executors/xiaomi-tokenplan.js +19 -0
  115. package/open-sse/executors/yuanbao-web.js +385 -0
  116. package/open-sse/executors/zed-hosted.js +281 -0
  117. package/open-sse/executors/zenmux-free.js +247 -0
  118. package/open-sse/handlers/audioSpeech.js +759 -0
  119. package/open-sse/handlers/audioTranscription.js +395 -0
  120. package/open-sse/handlers/audioTranslation.js +181 -0
  121. package/open-sse/handlers/chatCore/nonStreamingHandler.js +300 -0
  122. package/open-sse/handlers/chatCore/requestDetail.js +102 -0
  123. package/open-sse/handlers/chatCore/sseToJsonHandler.js +231 -0
  124. package/open-sse/handlers/chatCore/streamingHandler.js +95 -0
  125. package/open-sse/handlers/chatCore.js +404 -0
  126. package/open-sse/handlers/embeddingProviders/_base.js +4 -0
  127. package/open-sse/handlers/embeddingProviders/gemini.js +54 -0
  128. package/open-sse/handlers/embeddingProviders/index.js +23 -0
  129. package/open-sse/handlers/embeddingProviders/openai.js +39 -0
  130. package/open-sse/handlers/embeddingProviders/openaiCompatNode.js +13 -0
  131. package/open-sse/handlers/embeddingsCore.js +126 -0
  132. package/open-sse/handlers/fetch/index.js +237 -0
  133. package/open-sse/handlers/imageGenerationCore.js +230 -0
  134. package/open-sse/handlers/imageProviders/_base.js +31 -0
  135. package/open-sse/handlers/imageProviders/antigravity.js +73 -0
  136. package/open-sse/handlers/imageProviders/blackForestLabs.js +63 -0
  137. package/open-sse/handlers/imageProviders/cloudflareAi.js +207 -0
  138. package/open-sse/handlers/imageProviders/codex.js +217 -0
  139. package/open-sse/handlers/imageProviders/comfyui.js +25 -0
  140. package/open-sse/handlers/imageProviders/falAi.js +62 -0
  141. package/open-sse/handlers/imageProviders/gemini.js +40 -0
  142. package/open-sse/handlers/imageProviders/huggingface.js +38 -0
  143. package/open-sse/handlers/imageProviders/index.js +44 -0
  144. package/open-sse/handlers/imageProviders/leonardo.js +435 -0
  145. package/open-sse/handlers/imageProviders/nanobanana.js +79 -0
  146. package/open-sse/handlers/imageProviders/openai.js +61 -0
  147. package/open-sse/handlers/imageProviders/runwayml.js +72 -0
  148. package/open-sse/handlers/imageProviders/sdwebui.js +36 -0
  149. package/open-sse/handlers/imageProviders/stabilityAi.js +59 -0
  150. package/open-sse/handlers/imageProviders/weavy.js +222 -0
  151. package/open-sse/handlers/moderations.js +92 -0
  152. package/open-sse/handlers/ocr.js +89 -0
  153. package/open-sse/handlers/rerank.js +223 -0
  154. package/open-sse/handlers/responseSanitizer/reasoning.js +144 -0
  155. package/open-sse/handlers/responsesHandler.js +99 -0
  156. package/open-sse/handlers/search/callers.js +371 -0
  157. package/open-sse/handlers/search/chatSearch.js +409 -0
  158. package/open-sse/handlers/search/index.js +201 -0
  159. package/open-sse/handlers/search/normalizers.js +223 -0
  160. package/open-sse/handlers/search.js +1056 -0
  161. package/open-sse/handlers/sseParser.js +469 -0
  162. package/open-sse/handlers/sttCore.js +193 -0
  163. package/open-sse/handlers/ttsCore.js +74 -0
  164. package/open-sse/handlers/ttsProviders/_base.js +39 -0
  165. package/open-sse/handlers/ttsProviders/edgeTts.js +89 -0
  166. package/open-sse/handlers/ttsProviders/elevenlabs.js +48 -0
  167. package/open-sse/handlers/ttsProviders/gemini.js +117 -0
  168. package/open-sse/handlers/ttsProviders/genericFormats.js +169 -0
  169. package/open-sse/handlers/ttsProviders/googleTts.js +54 -0
  170. package/open-sse/handlers/ttsProviders/index.js +50 -0
  171. package/open-sse/handlers/ttsProviders/localDevice.js +87 -0
  172. package/open-sse/handlers/ttsProviders/minimax.js +59 -0
  173. package/open-sse/handlers/ttsProviders/openai.js +30 -0
  174. package/open-sse/handlers/ttsProviders/openrouter.js +70 -0
  175. package/open-sse/handlers/usageExtractor.js +93 -0
  176. package/open-sse/handlers/videoGenerationCore.js +119 -0
  177. package/open-sse/handlers/videoProviders/index.js +22 -0
  178. package/open-sse/handlers/videoProviders/leonardo.js +511 -0
  179. package/open-sse/handlers/videoProviders/weavy.js +198 -0
  180. package/open-sse/handlers/webFetch.js +200 -0
  181. package/open-sse/index.js +79 -0
  182. package/open-sse/mcp-server/audit.js +283 -0
  183. package/open-sse/mcp-server/catalog.js +184 -0
  184. package/open-sse/mcp-server/descriptionCompressor.js +175 -0
  185. package/open-sse/mcp-server/httpAuthContext.js +32 -0
  186. package/open-sse/mcp-server/httpTransport.js +229 -0
  187. package/open-sse/mcp-server/index.js +33 -0
  188. package/open-sse/mcp-server/mcpCallerIdentity.js +21 -0
  189. package/open-sse/mcp-server/runtimeHeartbeat.js +110 -0
  190. package/open-sse/mcp-server/schemas/a2a.js +153 -0
  191. package/open-sse/mcp-server/schemas/audit.js +17 -0
  192. package/open-sse/mcp-server/schemas/index.js +166 -0
  193. package/open-sse/mcp-server/schemas/pickFastestModel.js +90 -0
  194. package/open-sse/mcp-server/schemas/toolDefinition.js +0 -0
  195. package/open-sse/mcp-server/schemas/toolSearch.js +32 -0
  196. package/open-sse/mcp-server/schemas/tools.js +1219 -0
  197. package/open-sse/mcp-server/scopeEnforcement.js +80 -0
  198. package/open-sse/mcp-server/server.js +1168 -0
  199. package/open-sse/mcp-server/toolCardinality.js +78 -0
  200. package/open-sse/mcp-server/toolSearch/catalog.js +66 -0
  201. package/open-sse/mcp-server/toolSearch/handler.js +20 -0
  202. package/open-sse/mcp-server/toolSearch/index.js +10 -0
  203. package/open-sse/mcp-server/toolSearch/register.js +21 -0
  204. package/open-sse/mcp-server/toolSearch/search.js +55 -0
  205. package/open-sse/mcp-server/toolSearch/signature.js +67 -0
  206. package/open-sse/mcp-server/tools/advancedTools.js +893 -0
  207. package/open-sse/mcp-server/tools/agentSkillTools.js +69 -0
  208. package/open-sse/mcp-server/tools/compressionTools.js +309 -0
  209. package/open-sse/mcp-server/tools/gamificationTools.js +134 -0
  210. package/open-sse/mcp-server/tools/githubSkillTools.js +102 -0
  211. package/open-sse/mcp-server/tools/memoryTools.js +118 -0
  212. package/open-sse/mcp-server/tools/notionTools.js +101 -0
  213. package/open-sse/mcp-server/tools/obsidianTools.js +307 -0
  214. package/open-sse/mcp-server/tools/pickFastestModel.js +223 -0
  215. package/open-sse/mcp-server/tools/pluginTools.js +181 -0
  216. package/open-sse/mcp-server/tools/poolTools.js +139 -0
  217. package/open-sse/mcp-server/tools/skillTools.js +113 -0
  218. package/open-sse/package.json +10 -0
  219. package/open-sse/providers/REGISTRY_TEMPLATE.js +98 -0
  220. package/open-sse/providers/capabilities.js +293 -0
  221. package/open-sse/providers/index.js +51 -0
  222. package/open-sse/providers/models/helpers.js +20 -0
  223. package/open-sse/providers/models/namePatterns.js +33 -0
  224. package/open-sse/providers/models/schema.js +40 -0
  225. package/open-sse/providers/pricing.js +308 -0
  226. package/open-sse/providers/registry/alicode-intl.js +30 -0
  227. package/open-sse/providers/registry/alicode.js +31 -0
  228. package/open-sse/providers/registry/anthropic.js +37 -0
  229. package/open-sse/providers/registry/antigravity.js +81 -0
  230. package/open-sse/providers/registry/assemblyai.js +38 -0
  231. package/open-sse/providers/registry/aws-polly.js +45 -0
  232. package/open-sse/providers/registry/azure.js +21 -0
  233. package/open-sse/providers/registry/black-forest-labs.js +32 -0
  234. package/open-sse/providers/registry/blackbox.js +41 -0
  235. package/open-sse/providers/registry/brave-search.js +35 -0
  236. package/open-sse/providers/registry/byteplus.js +35 -0
  237. package/open-sse/providers/registry/cartesia.js +36 -0
  238. package/open-sse/providers/registry/cerebras.js +31 -0
  239. package/open-sse/providers/registry/chutes.js +24 -0
  240. package/open-sse/providers/registry/claude.js +87 -0
  241. package/open-sse/providers/registry/cline.js +51 -0
  242. package/open-sse/providers/registry/clinepass.js +57 -0
  243. package/open-sse/providers/registry/cloudflare-ai.js +55 -0
  244. package/open-sse/providers/registry/codebuddy-cn.js +77 -0
  245. package/open-sse/providers/registry/codex.js +100 -0
  246. package/open-sse/providers/registry/cohere.js +27 -0
  247. package/open-sse/providers/registry/comfyui.js +20 -0
  248. package/open-sse/providers/registry/commandcode.js +43 -0
  249. package/open-sse/providers/registry/coqui.js +30 -0
  250. package/open-sse/providers/registry/cursor.js +58 -0
  251. package/open-sse/providers/registry/deepgram.js +33 -0
  252. package/open-sse/providers/registry/deepseek.js +51 -0
  253. package/open-sse/providers/registry/digitalocean.js +92 -0
  254. package/open-sse/providers/registry/edge-tts.js +24 -0
  255. package/open-sse/providers/registry/elevenlabs.js +35 -0
  256. package/open-sse/providers/registry/exa.js +50 -0
  257. package/open-sse/providers/registry/fal-ai.js +34 -0
  258. package/open-sse/providers/registry/featherless.js +34 -0
  259. package/open-sse/providers/registry/firecrawl.js +34 -0
  260. package/open-sse/providers/registry/fireworks.js +29 -0
  261. package/open-sse/providers/registry/gemini-cli.js +58 -0
  262. package/open-sse/providers/registry/gemini.js +83 -0
  263. package/open-sse/providers/registry/github.js +88 -0
  264. package/open-sse/providers/registry/gitlab.js +32 -0
  265. package/open-sse/providers/registry/glm-cn.js +35 -0
  266. package/open-sse/providers/registry/glm.js +58 -0
  267. package/open-sse/providers/registry/google-pse.js +35 -0
  268. package/open-sse/providers/registry/google-tts.js +24 -0
  269. package/open-sse/providers/registry/grok-cli.js +86 -0
  270. package/open-sse/providers/registry/grok-web.js +39 -0
  271. package/open-sse/providers/registry/groq.js +37 -0
  272. package/open-sse/providers/registry/huggingface.js +34 -0
  273. package/open-sse/providers/registry/hyperbolic.js +35 -0
  274. package/open-sse/providers/registry/ibm-bob.js +27 -0
  275. package/open-sse/providers/registry/iflow.js +52 -0
  276. package/open-sse/providers/registry/index.js +210 -0
  277. package/open-sse/providers/registry/inworld.js +36 -0
  278. package/open-sse/providers/registry/jina-ai.js +42 -0
  279. package/open-sse/providers/registry/jina-reader.js +34 -0
  280. package/open-sse/providers/registry/kilocode.js +51 -0
  281. package/open-sse/providers/registry/kimchi.js +49 -0
  282. package/open-sse/providers/registry/kimi-coding.js +65 -0
  283. package/open-sse/providers/registry/kimi.js +56 -0
  284. package/open-sse/providers/registry/kiro.js +115 -0
  285. package/open-sse/providers/registry/linkup.js +34 -0
  286. package/open-sse/providers/registry/local-device.js +24 -0
  287. package/open-sse/providers/registry/mimo-free.js +24 -0
  288. package/open-sse/providers/registry/minimax-cn.js +76 -0
  289. package/open-sse/providers/registry/minimax.js +83 -0
  290. package/open-sse/providers/registry/mistral.js +34 -0
  291. package/open-sse/providers/registry/mmf.js +19 -0
  292. package/open-sse/providers/registry/nanobanana.js +35 -0
  293. package/open-sse/providers/registry/nebius.js +27 -0
  294. package/open-sse/providers/registry/nvidia.js +43 -0
  295. package/open-sse/providers/registry/ollama-local.js +19 -0
  296. package/open-sse/providers/registry/ollama.js +36 -0
  297. package/open-sse/providers/registry/openai.js +84 -0
  298. package/open-sse/providers/registry/opencode-go.js +41 -0
  299. package/open-sse/providers/registry/opencode.js +25 -0
  300. package/open-sse/providers/registry/openrouter.js +60 -0
  301. package/open-sse/providers/registry/perplexity-agent.js +49 -0
  302. package/open-sse/providers/registry/perplexity-web.js +33 -0
  303. package/open-sse/providers/registry/perplexity.js +37 -0
  304. package/open-sse/providers/registry/playht.js +36 -0
  305. package/open-sse/providers/registry/qoder.js +54 -0
  306. package/open-sse/providers/registry/qwen.js +33 -0
  307. package/open-sse/providers/registry/recraft.js +24 -0
  308. package/open-sse/providers/registry/runwayml.js +30 -0
  309. package/open-sse/providers/registry/sdwebui.js +20 -0
  310. package/open-sse/providers/registry/searchapi.js +35 -0
  311. package/open-sse/providers/registry/searxng.js +35 -0
  312. package/open-sse/providers/registry/serper.js +35 -0
  313. package/open-sse/providers/registry/siliconflow.js +39 -0
  314. package/open-sse/providers/registry/stability-ai.js +31 -0
  315. package/open-sse/providers/registry/tavily.js +50 -0
  316. package/open-sse/providers/registry/together.js +31 -0
  317. package/open-sse/providers/registry/topaz.js +19 -0
  318. package/open-sse/providers/registry/tortoise.js +30 -0
  319. package/open-sse/providers/registry/venice.js +56 -0
  320. package/open-sse/providers/registry/vercel-ai-gateway.js +41 -0
  321. package/open-sse/providers/registry/vertex-partner.js +29 -0
  322. package/open-sse/providers/registry/vertex.js +32 -0
  323. package/open-sse/providers/registry/volcengine-ark.js +35 -0
  324. package/open-sse/providers/registry/voyage-ai.js +30 -0
  325. package/open-sse/providers/registry/xai.js +45 -0
  326. package/open-sse/providers/registry/xiaomi-mimo.js +46 -0
  327. package/open-sse/providers/registry/xiaomi-tokenplan.js +63 -0
  328. package/open-sse/providers/registry/youcom.js +35 -0
  329. package/open-sse/providers/schema.js +76 -0
  330. package/open-sse/providers/shared.js +74 -0
  331. package/open-sse/providers/thinkingLevels.js +48 -0
  332. package/open-sse/rtk/applyFilter.js +15 -0
  333. package/open-sse/rtk/autodetect.js +111 -0
  334. package/open-sse/rtk/caveman.js +100 -0
  335. package/open-sse/rtk/cavemanPrompts.js +78 -0
  336. package/open-sse/rtk/constants.js +55 -0
  337. package/open-sse/rtk/filters/buildOutput.js +127 -0
  338. package/open-sse/rtk/filters/dedupLog.js +44 -0
  339. package/open-sse/rtk/filters/find.js +50 -0
  340. package/open-sse/rtk/filters/gitDiff.js +92 -0
  341. package/open-sse/rtk/filters/gitLog.js +99 -0
  342. package/open-sse/rtk/filters/gitStatus.js +117 -0
  343. package/open-sse/rtk/filters/grep.js +48 -0
  344. package/open-sse/rtk/filters/ls.js +79 -0
  345. package/open-sse/rtk/filters/readNumbered.js +27 -0
  346. package/open-sse/rtk/filters/searchList.js +52 -0
  347. package/open-sse/rtk/filters/smartTruncate.js +15 -0
  348. package/open-sse/rtk/filters/tree.js +32 -0
  349. package/open-sse/rtk/headroom.js +215 -0
  350. package/open-sse/rtk/index.js +155 -0
  351. package/open-sse/rtk/paleo.js +47 -0
  352. package/open-sse/rtk/ponytail.js +9 -0
  353. package/open-sse/rtk/ponytailPrompt.js +52 -0
  354. package/open-sse/rtk/ponytailPrompts.js +76 -0
  355. package/open-sse/rtk/pxpipe.js +104 -0
  356. package/open-sse/rtk/registry.js +38 -0
  357. package/open-sse/rtk/systemInject.js +98 -0
  358. package/open-sse/services/accountFallback.js +323 -0
  359. package/open-sse/services/antigravityHeaders.js +91 -0
  360. package/open-sse/services/antigravityVersion.js +154 -0
  361. package/open-sse/services/clinepassModels.js +63 -0
  362. package/open-sse/services/codexQuotaFetcher.js +312 -0
  363. package/open-sse/services/codexVerbosity.js +30 -0
  364. package/open-sse/services/combo/context.js +12 -0
  365. package/open-sse/services/combo/fingerprintExpansion.js +51 -0
  366. package/open-sse/services/combo/headroomRanking.js +28 -0
  367. package/open-sse/services/combo/quotaExhaustionCutoff.js +87 -0
  368. package/open-sse/services/combo/quotaScoring.js +226 -0
  369. package/open-sse/services/combo/quotaShareConcurrency.js +25 -0
  370. package/open-sse/services/combo/quotaShareInflight.js +50 -0
  371. package/open-sse/services/combo/quotaShareStrategy.js +130 -0
  372. package/open-sse/services/combo/resolveAutoStrategy.js +231 -0
  373. package/open-sse/services/combo/responseValidation.js +140 -0
  374. package/open-sse/services/combo/runtimeUnits.js +195 -0
  375. package/open-sse/services/combo/sessionStickiness.js +128 -0
  376. package/open-sse/services/combo/shadowRouting.js +131 -0
  377. package/open-sse/services/combo/targetExhaustion.js +75 -0
  378. package/open-sse/services/combo/targetSorters.js +126 -0
  379. package/open-sse/services/combo/targetTimeoutRunner.js +65 -0
  380. package/open-sse/services/combo/validateQuality.js +271 -0
  381. package/open-sse/services/combo.js +571 -0
  382. package/open-sse/services/comboAgentMiddleware.js +91 -0
  383. package/open-sse/services/comboConfig.js +153 -0
  384. package/open-sse/services/comboManifestMetrics.js +10 -0
  385. package/open-sse/services/comboMetrics.js +278 -0
  386. package/open-sse/services/compact.js +71 -0
  387. package/open-sse/services/copilotModels.js +155 -0
  388. package/open-sse/services/emergencyFallback.js +109 -0
  389. package/open-sse/services/errorClassifier.js +190 -0
  390. package/open-sse/services/evalRouting.js +201 -0
  391. package/open-sse/services/freeWebSearch.js +4 -0
  392. package/open-sse/services/fusion.js +223 -0
  393. package/open-sse/services/intentClassifier.js +631 -0
  394. package/open-sse/services/kimchiModels.js +176 -0
  395. package/open-sse/services/kiroModels.js +332 -0
  396. package/open-sse/services/model.js +136 -0
  397. package/open-sse/services/modelCapabilities.js +5 -0
  398. package/open-sse/services/modelDeprecation.js +101 -0
  399. package/open-sse/services/modelFamilyFallback.js +166 -0
  400. package/open-sse/services/oauthCredentialManager.js +156 -0
  401. package/open-sse/services/pipeline.js +107 -0
  402. package/open-sse/services/projectId.js +306 -0
  403. package/open-sse/services/provider.js +169 -0
  404. package/open-sse/services/providerCooldownTracker.js +94 -0
  405. package/open-sse/services/providerDefaultRateLimit.js +11 -0
  406. package/open-sse/services/proxyAutoSelector.js +24 -0
  407. package/open-sse/services/qoderModels.js +214 -0
  408. package/open-sse/services/quotaFetchThrottle.js +103 -0
  409. package/open-sse/services/quotaMonitor.js +310 -0
  410. package/open-sse/services/quotaPreflight.js +266 -0
  411. package/open-sse/services/rateLimitManager/headers.js +56 -0
  412. package/open-sse/services/rateLimitManager.js +616 -0
  413. package/open-sse/services/rateLimitSemaphore.js +112 -0
  414. package/open-sse/services/responsesInputSanitizer.js +99 -0
  415. package/open-sse/services/slidingWindowLimiter.js +44 -0
  416. package/open-sse/services/streamRecovery.js +355 -0
  417. package/open-sse/services/taskAwareRouter.js +227 -0
  418. package/open-sse/services/taskAwareRouting.js +332 -0
  419. package/open-sse/services/thinkingBudget.js +247 -0
  420. package/open-sse/services/tokenRefresh/dedup.js +31 -0
  421. package/open-sse/services/tokenRefresh/providers.js +624 -0
  422. package/open-sse/services/tokenRefresh.js +254 -0
  423. package/open-sse/services/usage/claude.js +147 -0
  424. package/open-sse/services/usage/codebuddy-cn.js +138 -0
  425. package/open-sse/services/usage/codex.js +267 -0
  426. package/open-sse/services/usage/github.js +100 -0
  427. package/open-sse/services/usage/google.js +241 -0
  428. package/open-sse/services/usage/grok-cli.js +274 -0
  429. package/open-sse/services/usage/kiro.js +188 -0
  430. package/open-sse/services/usage/minimax.js +234 -0
  431. package/open-sse/services/usage/misc.js +288 -0
  432. package/open-sse/services/usage/shared.js +70 -0
  433. package/open-sse/services/usage.js +62 -0
  434. package/open-sse/services/usageDb.js +2 -0
  435. package/open-sse/services/webSearchRouting.js +25 -0
  436. package/open-sse/services/wildcardRouter.js +59 -0
  437. package/open-sse/shared/clineAuth.js +37 -0
  438. package/open-sse/shared/machineId.js +19 -0
  439. package/open-sse/shared/qoder/constants.js +64 -0
  440. package/open-sse/shared/qoder/cosy.js +175 -0
  441. package/open-sse/shared/qoder/encoding.js +55 -0
  442. package/open-sse/transformer/responsesTransformer.js +439 -0
  443. package/open-sse/transformer/streamToJsonConverter.js +103 -0
  444. package/open-sse/translator/concerns/chunk.js +11 -0
  445. package/open-sse/translator/concerns/finishReason.js +63 -0
  446. package/open-sse/translator/concerns/image.js +124 -0
  447. package/open-sse/translator/concerns/json.js +5 -0
  448. package/open-sse/translator/concerns/message.js +7 -0
  449. package/open-sse/translator/concerns/modality.js +155 -0
  450. package/open-sse/translator/concerns/paramSupport.js +75 -0
  451. package/open-sse/translator/concerns/prefetch.js +96 -0
  452. package/open-sse/translator/concerns/reasoning.js +24 -0
  453. package/open-sse/translator/concerns/thinking.js +53 -0
  454. package/open-sse/translator/concerns/thinkingUnified.js +329 -0
  455. package/open-sse/translator/concerns/toolCall.js +153 -0
  456. package/open-sse/translator/concerns/usage.js +69 -0
  457. package/open-sse/translator/formats/claude.js +368 -0
  458. package/open-sse/translator/formats/gemini.js +380 -0
  459. package/open-sse/translator/formats/maxTokens.js +34 -0
  460. package/open-sse/translator/formats/openai.js +134 -0
  461. package/open-sse/translator/formats/responsesApi.js +141 -0
  462. package/open-sse/translator/formats.js +36 -0
  463. package/open-sse/translator/helpers/claudeHelper.js +216 -0
  464. package/open-sse/translator/helpers/geminiHelper.js +372 -0
  465. package/open-sse/translator/helpers/imageHelper.js +34 -0
  466. package/open-sse/translator/helpers/maxTokensHelper.js +27 -0
  467. package/open-sse/translator/helpers/openaiHelper.js +130 -0
  468. package/open-sse/translator/helpers/responsesApiHelper.js +139 -0
  469. package/open-sse/translator/helpers/toolCallHelper.js +148 -0
  470. package/open-sse/translator/index.js +252 -0
  471. package/open-sse/translator/request/antigravity-to-openai.js +242 -0
  472. package/open-sse/translator/request/claude-to-kiro.js +478 -0
  473. package/open-sse/translator/request/claude-to-openai.js +263 -0
  474. package/open-sse/translator/request/gemini-to-openai.js +152 -0
  475. package/open-sse/translator/request/openai-responses.js +385 -0
  476. package/open-sse/translator/request/openai-to-claude.js +383 -0
  477. package/open-sse/translator/request/openai-to-commandcode.js +176 -0
  478. package/open-sse/translator/request/openai-to-cursor.js +185 -0
  479. package/open-sse/translator/request/openai-to-gemini.js +442 -0
  480. package/open-sse/translator/request/openai-to-kiro.js +607 -0
  481. package/open-sse/translator/request/openai-to-kiro.old.js +278 -0
  482. package/open-sse/translator/request/openai-to-ollama.js +195 -0
  483. package/open-sse/translator/request/openai-to-vertex.js +42 -0
  484. package/open-sse/translator/response/claude-to-openai.js +195 -0
  485. package/open-sse/translator/response/commandcode-to-openai.js +188 -0
  486. package/open-sse/translator/response/cursor-to-openai.js +30 -0
  487. package/open-sse/translator/response/gemini-to-openai.js +147 -0
  488. package/open-sse/translator/response/kiro-to-claude.js +261 -0
  489. package/open-sse/translator/response/kiro-to-openai.js +160 -0
  490. package/open-sse/translator/response/ollama-to-openai.js +134 -0
  491. package/open-sse/translator/response/openai-responses.js +535 -0
  492. package/open-sse/translator/response/openai-to-antigravity.js +123 -0
  493. package/open-sse/translator/response/openai-to-claude.js +265 -0
  494. package/open-sse/translator/schema/blocks.js +43 -0
  495. package/open-sse/translator/schema/defaults.js +7 -0
  496. package/open-sse/translator/schema/finishReasons.js +27 -0
  497. package/open-sse/translator/schema/index.js +8 -0
  498. package/open-sse/translator/schema/roles.js +16 -0
  499. package/open-sse/utils/agentGoalPolicy.js +85 -0
  500. package/open-sse/utils/aiSdkCompat.js +75 -0
  501. package/open-sse/utils/bypassHandler.js +298 -0
  502. package/open-sse/utils/cacheControlPolicy.js +189 -0
  503. package/open-sse/utils/claudeCloaking.js +155 -0
  504. package/open-sse/utils/claudeHeaderCache.js +70 -0
  505. package/open-sse/utils/claudeSignature.js +41 -0
  506. package/open-sse/utils/clientDetector.js +63 -0
  507. package/open-sse/utils/codebuddySanitizer.js +96 -0
  508. package/open-sse/utils/composerToolCalls.js +158 -0
  509. package/open-sse/utils/cors.js +13 -0
  510. package/open-sse/utils/cursorChecksum.js +149 -0
  511. package/open-sse/utils/cursorImages.js +224 -0
  512. package/open-sse/utils/cursorProtobuf.js +904 -0
  513. package/open-sse/utils/cursorVersionDetector.js +55 -0
  514. package/open-sse/utils/debugLog.js +14 -0
  515. package/open-sse/utils/diagnostics.js +143 -0
  516. package/open-sse/utils/error.js +164 -0
  517. package/open-sse/utils/estimateSize.js +33 -0
  518. package/open-sse/utils/finishReason.js +32 -0
  519. package/open-sse/utils/flattenToolHistory.js +68 -0
  520. package/open-sse/utils/headers.js +36 -0
  521. package/open-sse/utils/heapPressure.js +35 -0
  522. package/open-sse/utils/jsonToSse.js +125 -0
  523. package/open-sse/utils/keepaliveThreshold.js +40 -0
  524. package/open-sse/utils/logger.js +104 -0
  525. package/open-sse/utils/noThinkingAlias.js +74 -0
  526. package/open-sse/utils/number.js +7 -0
  527. package/open-sse/utils/ollamaTransform.js +85 -0
  528. package/open-sse/utils/opencodeHeaders.js +47 -0
  529. package/open-sse/utils/progressTracker.js +81 -0
  530. package/open-sse/utils/providerRequestLogging.js +219 -0
  531. package/open-sse/utils/proxyFetch.js +369 -0
  532. package/open-sse/utils/reasoningContentInjector.js +79 -0
  533. package/open-sse/utils/reasoningFields.js +70 -0
  534. package/open-sse/utils/requestLogger.js +260 -0
  535. package/open-sse/utils/responsesInputNormalization.js +92 -0
  536. package/open-sse/utils/responsesStatePolicy.js +52 -0
  537. package/open-sse/utils/responsesStreamHelpers.js +49 -0
  538. package/open-sse/utils/sessionManager.js +240 -0
  539. package/open-sse/utils/sleep.js +6 -0
  540. package/open-sse/utils/sse.js +14 -0
  541. package/open-sse/utils/sseConstants.js +23 -0
  542. package/open-sse/utils/sseHeartbeat.js +104 -0
  543. package/open-sse/utils/stream.js +517 -0
  544. package/open-sse/utils/streamFailureFinalization.js +134 -0
  545. package/open-sse/utils/streamHandler.js +250 -0
  546. package/open-sse/utils/streamHelpers.js +137 -0
  547. package/open-sse/utils/textualToolCall.js +104 -0
  548. package/open-sse/utils/thinkCloseMarker.js +72 -0
  549. package/open-sse/utils/thinkTagParser.js +146 -0
  550. package/open-sse/utils/toolCallArguments.js +12 -0
  551. package/open-sse/utils/toolDeduper.js +49 -0
  552. package/open-sse/utils/toolSources.js +31 -0
  553. package/open-sse/utils/upstreamResponseHeaders.js +25 -0
  554. package/open-sse/utils/urlSanitize.js +15 -0
  555. package/open-sse/utils/usageTracking.js +347 -0
  556. package/package.json +1 -1
@@ -0,0 +1,571 @@
1
+ /**
2
+ * Shared combo (model combo) handling with fallback support
3
+ */
4
+
5
+ import { checkFallbackError, formatRetryAfter } from "./accountFallback.js";
6
+ import { unavailableResponse } from "../utils/error.js";
7
+ import { getCapabilitiesForModel } from "../providers/capabilities.js";
8
+ import { extractTextContent } from "../translator/formats/gemini.js";
9
+
10
+ // Hard capabilities = input modalities; missing one drops request data (e.g. image
11
+ // stripped). Must be prioritized. Soft (e.g. search) only degrades a feature.
12
+ const HARD_CAPS = new Set(["vision", "pdf", "audioInput", "videoInput"]);
13
+
14
+ // Prefixes used when flattening tool turns into plain prose for panel models.
15
+ const TOOL_CALL_PREFIX = "[Called tools: ";
16
+ const TOOL_RESULT_PREFIX = "[Tool result: ";
17
+
18
+ // Flatten tool turns into prose so panel models keep the context but can't loop
19
+ // on tools: drop the request's tools, turn tool/function results into assistant
20
+ // text, and inline assistant tool_calls names instead of the structured field.
21
+ function flattenToolHistory(messages) {
22
+ return messages
23
+ .filter((msg) => msg)
24
+ .map((msg) => {
25
+ if (msg.role === "tool" || msg.role === "function") {
26
+ return { role: "assistant", content: `${TOOL_RESULT_PREFIX}${extractTextContent(msg.content) || String(msg.content ?? "")}]` };
27
+ }
28
+ if (msg.role === "assistant" && Array.isArray(msg.tool_calls)) {
29
+ const { tool_calls, ...rest } = msg;
30
+ const names = tool_calls.map((c) => c?.function?.name || c?.name || "tool").join(", ");
31
+ const base = extractTextContent(rest.content) || (typeof rest.content === "string" ? rest.content : "");
32
+ return { ...rest, content: `${base}${base ? "\n" : ""}${TOOL_CALL_PREFIX}${names}]` };
33
+ }
34
+ if (Array.isArray(msg.content)) {
35
+ const hasToolUse = msg.content.some((c) => c.type === "tool_use");
36
+ const hasToolResult = msg.content.some((c) => c.type === "tool_result");
37
+ if (hasToolUse || hasToolResult) {
38
+ const textParts = [];
39
+ const toolNames = [];
40
+ const toolResults = [];
41
+ for (const block of msg.content) {
42
+ if (block.type === "text" && block.text) textParts.push(block.text);
43
+ if (block.type === "tool_use") toolNames.push(block.name || "tool");
44
+ if (block.type === "tool_result") toolResults.push(extractTextContent(block.content) || String(block.content ?? ""));
45
+ }
46
+ const { ...rest } = msg;
47
+ let newContent = textParts.join("\n");
48
+ if (toolNames.length > 0) {
49
+ newContent = `${newContent}${newContent ? "\n" : ""}${TOOL_CALL_PREFIX}${toolNames.join(", ")}]`;
50
+ }
51
+ if (toolResults.length > 0) {
52
+ newContent = `${newContent}${newContent ? "\n" : ""}${TOOL_RESULT_PREFIX}${toolResults.join("\n")}]`;
53
+ }
54
+ return { ...rest, content: newContent };
55
+ }
56
+ }
57
+ return msg;
58
+ });
59
+ }
60
+
61
+ // Reorder combo models by capability fit. Stable; never drops a model (fallback intact).
62
+ // Tier 0: satisfies all hard + all soft. Tier 1: all hard only. Tier 2: rest.
63
+ export function reorderByCapabilities(models, required) {
64
+ if (!required || required.size === 0 || !Array.isArray(models) || models.length <= 1) return models;
65
+ const hard = [...required].filter((c) => HARD_CAPS.has(c));
66
+ const soft = [...required].filter((c) => !HARD_CAPS.has(c));
67
+
68
+ const tierOf = (m) => {
69
+ const slash = typeof m === "string" ? m.indexOf("/") : -1;
70
+ const provider = slash > 0 ? m.slice(0, slash) : "";
71
+ const model = slash > 0 ? m.slice(slash + 1) : m;
72
+ const caps = getCapabilitiesForModel(provider, model);
73
+ if (!hard.every((c) => caps[c] === true)) return 2;
74
+ return soft.every((c) => caps[c] === true) ? 0 : 1;
75
+ };
76
+
77
+ // Stable sort by tier (Array.prototype.sort is stable in modern engines).
78
+ return models
79
+ .map((m, i) => ({ m, i, t: tierOf(m) }))
80
+ .sort((a, b) => a.t - b.t || a.i - b.i)
81
+ .map((x) => x.m);
82
+ }
83
+
84
+ /**
85
+ * Track rotation state per combo (for round-robin strategy)
86
+ * @type {Map<string, { index: number, consecutiveUseCount: number }>}
87
+ */
88
+ const comboRotationState = new Map();
89
+
90
+ // Trailing run of items after the last assistant/model turn = the current user
91
+ // turn. It may span several messages (e.g. text + image split across blocks),
92
+ // so we return all of them. History media (older turns) must not pin the combo
93
+ // to a vision model — those get stripped + placeholdered downstream instead.
94
+ function trailingUserItems(arr) {
95
+ if (!Array.isArray(arr) || arr.length === 0) return [];
96
+ const isAssistant = (r) => r === "assistant" || r === "model";
97
+ let i = arr.length - 1;
98
+ while (i >= 0 && !isAssistant(arr[i]?.role)) i--;
99
+ return arr.slice(i + 1);
100
+ }
101
+
102
+ // Detect which capabilities a request needs. Modalities (vision/pdf) are scanned
103
+ // only on the current user turn; "search" is request-wide (lives in tools).
104
+ // Returns a Set of: "vision" | "pdf" | "search".
105
+ export function detectRequiredCapabilities(body) {
106
+ const required = new Set();
107
+ if (!body || typeof body !== "object") return required;
108
+
109
+ const scanBlock = (b) => {
110
+ if (!b || typeof b !== "object") return;
111
+ const t = b.type;
112
+ if (t === "image_url" || t === "image" || t === "input_image") required.add("vision");
113
+ if (t === "file" || t === "document" || t === "input_file") required.add("pdf");
114
+ // gemini parts: inlineData/fileData carry a mime
115
+ const mime = b.inlineData?.mimeType || b.fileData?.mimeType;
116
+ if (typeof mime === "string" && mime.startsWith("image/")) required.add("vision");
117
+ if (mime === "application/pdf") required.add("pdf");
118
+ };
119
+
120
+ const scanContent = (content) => {
121
+ if (Array.isArray(content)) for (const b of content) scanBlock(b);
122
+ };
123
+
124
+ // Modalities: current user turn only (trailing user run across each known shape).
125
+ for (const m of trailingUserItems(body.messages)) scanContent(m.content); // openai / claude
126
+ for (const it of trailingUserItems(body.input)) scanContent(it.content); // responses
127
+ const contents = body.contents || body.request?.contents; // gemini / antigravity
128
+ for (const c of trailingUserItems(contents)) scanContent(c.parts);
129
+
130
+ // search: temporarily disabled in auto-switch (feature not wired yet).
131
+
132
+ return required;
133
+ }
134
+
135
+ function normalizeStickyLimit(stickyLimit) {
136
+ const parsed = Number.parseInt(stickyLimit, 10);
137
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 1;
138
+ }
139
+
140
+ function rotateModelsFromIndex(models, currentIndex) {
141
+ const rotatedModels = [...models];
142
+ for (let i = 0; i < currentIndex; i++) {
143
+ const moved = rotatedModels.shift();
144
+ rotatedModels.push(moved);
145
+ }
146
+ return rotatedModels;
147
+ }
148
+
149
+ /**
150
+ * Get rotated model list based on strategy
151
+ * @param {string[]} models - Array of model strings
152
+ * @param {string} comboName - Name of the combo
153
+ * @param {string} strategy - "fallback" or "round-robin"
154
+ * @param {number|string} [stickyLimit=1] - Requests per combo model before switching
155
+ * @returns {string[]} Rotated models array
156
+ */
157
+ export function getRotatedModels(models, comboName, strategy, stickyLimit = 1) {
158
+ if (!models || models.length <= 1 || strategy !== "round-robin") {
159
+ return models;
160
+ }
161
+
162
+ const rotationKey = comboName || "__default__";
163
+ const normalizedStickyLimit = normalizeStickyLimit(stickyLimit);
164
+ const existingState = comboRotationState.get(rotationKey);
165
+ const state = typeof existingState === "number"
166
+ ? { index: existingState, consecutiveUseCount: 0 }
167
+ : (existingState || { index: 0, consecutiveUseCount: 0 });
168
+
169
+ const currentIndex = state.index % models.length;
170
+ const rotatedModels = rotateModelsFromIndex(models, currentIndex);
171
+ const nextUseCount = state.consecutiveUseCount + 1;
172
+
173
+ if (nextUseCount >= normalizedStickyLimit) {
174
+ comboRotationState.set(rotationKey, {
175
+ index: (currentIndex + 1) % models.length,
176
+ consecutiveUseCount: 0,
177
+ });
178
+ } else {
179
+ comboRotationState.set(rotationKey, {
180
+ index: currentIndex,
181
+ consecutiveUseCount: nextUseCount,
182
+ });
183
+ }
184
+
185
+ return rotatedModels;
186
+ }
187
+
188
+ /**
189
+ * Reset in-memory rotation state when combo/settings change
190
+ * @param {string} [comboName] - Combo name to reset; omit to clear all
191
+ */
192
+ export function resetComboRotation(comboName) {
193
+ if (comboName) comboRotationState.delete(comboName);
194
+ else comboRotationState.clear();
195
+ }
196
+
197
+ /**
198
+ * Get combo models from combos data
199
+ * @param {string} modelStr - Model string to check
200
+ * @param {Array|Object} combosData - Array of combos or object with combos
201
+ * @returns {string[]|null} Array of models or null if not a combo
202
+ */
203
+ export function getComboModelsFromData(modelStr, combosData) {
204
+ // Don't check if it's in provider/model format
205
+ if (modelStr.includes("/")) return null;
206
+
207
+ // Handle both array and object formats
208
+ const combos = Array.isArray(combosData) ? combosData : (combosData?.combos || []);
209
+
210
+ const combo = combos.find(c => c.name === modelStr);
211
+ if (combo && combo.models && combo.models.length > 0) {
212
+ return combo.models;
213
+ }
214
+ return null;
215
+ }
216
+
217
+ /**
218
+ * Handle combo chat with fallback
219
+ * @param {Object} options
220
+ * @param {Object} options.body - Request body
221
+ * @param {string[]} options.models - Array of model strings to try
222
+ * @param {Function} options.handleSingleModel - Function to handle single model: (body, modelStr) => Promise<Response>
223
+ * @param {Object} options.log - Logger object
224
+ * @param {string} [options.comboName] - Name of the combo (for round-robin tracking)
225
+ * @param {string} [options.comboStrategy] - Strategy: "fallback" or "round-robin"
226
+ * @param {number|string} [options.comboStickyLimit=1] - Requests per combo model before switching
227
+ * @returns {Promise<Response>}
228
+ */
229
+ export async function handleComboChat({ body, models, handleSingleModel, log, comboName, comboStrategy, comboStickyLimit = 1, autoSwitch = true }) {
230
+ // Apply rotation strategy if enabled
231
+ let rotatedModels = getRotatedModels(models, comboName, comboStrategy, comboStickyLimit);
232
+
233
+ // Auto-switch: float models that satisfy the request's required capabilities to the front.
234
+ if (autoSwitch) {
235
+ const required = detectRequiredCapabilities(body);
236
+ if (required.size > 0) {
237
+ const reordered = reorderByCapabilities(rotatedModels, required);
238
+ if (reordered[0] !== rotatedModels[0]) {
239
+ log.info("COMBO", `auto-switch for [${[...required].join(",")}] → ${reordered[0]}`);
240
+ }
241
+ rotatedModels = reordered;
242
+ }
243
+ }
244
+
245
+ let lastError = null;
246
+ let earliestRetryAfter = null;
247
+ let lastStatus = null;
248
+
249
+ for (let i = 0; i < rotatedModels.length; i++) {
250
+ const modelStr = rotatedModels[i];
251
+ log.info("COMBO", `Trying model ${i + 1}/${rotatedModels.length}: ${modelStr}`);
252
+
253
+ try {
254
+ const result = await handleSingleModel(body, modelStr);
255
+
256
+ // Success (2xx) - return response
257
+ if (result.ok) {
258
+ log.info("COMBO", `Model ${modelStr} succeeded`);
259
+ return result;
260
+ }
261
+
262
+ // Extract error info from response
263
+ let errorText = result.statusText || "";
264
+ let retryAfter = null;
265
+ try {
266
+ const errorBody = await result.clone().json();
267
+ errorText = errorBody?.error?.message || errorBody?.error || errorBody?.message || errorText;
268
+ retryAfter = errorBody?.retryAfter || null;
269
+ } catch {
270
+ // Ignore JSON parse errors
271
+ }
272
+
273
+ // Track earliest retryAfter across all combo models
274
+ if (retryAfter && (!earliestRetryAfter || new Date(retryAfter) < new Date(earliestRetryAfter))) {
275
+ earliestRetryAfter = retryAfter;
276
+ }
277
+
278
+ // Normalize error text to string (Worker-safe)
279
+ if (typeof errorText !== "string") {
280
+ try { errorText = JSON.stringify(errorText); } catch { errorText = String(errorText); }
281
+ }
282
+
283
+ // Check if should fallback to next model
284
+ const { shouldFallback, cooldownMs } = checkFallbackError(result.status, errorText);
285
+
286
+ if (!shouldFallback) {
287
+ log.warn("COMBO", `Model ${modelStr} failed (no fallback)`, { status: result.status });
288
+ return result;
289
+ }
290
+
291
+ // For transient errors (503/502/504), wait for cooldown before falling through
292
+ // so a briefly-overloaded provider gets a chance to recover rather than being
293
+ // skipped immediately (fixes: combo falls through on transient 503)
294
+ if (cooldownMs && cooldownMs > 0 && cooldownMs <= 5000 &&
295
+ (result.status === 503 || result.status === 502 || result.status === 504)) {
296
+ log.info("COMBO", `Model ${modelStr} transient ${result.status}, waiting ${cooldownMs}ms before next`);
297
+ await new Promise(r => setTimeout(r, cooldownMs));
298
+ }
299
+
300
+ // Fallback to next model
301
+ lastError = errorText || String(result.status);
302
+ if (!lastStatus) lastStatus = result.status;
303
+ log.warn("COMBO", `Model ${modelStr} failed, trying next`, { status: result.status });
304
+ } catch (error) {
305
+ // Catch unexpected exceptions to ensure fallback continues
306
+ lastError = error.message || String(error);
307
+ if (!lastStatus) lastStatus = 500;
308
+ log.warn("COMBO", `Model ${modelStr} threw error, trying next`, { error: lastError });
309
+ }
310
+ }
311
+
312
+ // All models failed
313
+ // Use 503 (Service Unavailable) rather than 406 (Not Acceptable) — 406 implies
314
+ // the request itself is invalid, but here the providers are simply unavailable
315
+ // or have no active credentials. 503 is more accurate and retryable by clients.
316
+ const allDisabled = lastError && lastError.toLowerCase().includes("no credentials");
317
+ const status = allDisabled ? 503 : (lastStatus || 503);
318
+ const msg = lastError || "All combo models unavailable";
319
+
320
+ if (earliestRetryAfter) {
321
+ const retryHuman = formatRetryAfter(earliestRetryAfter);
322
+ log.warn("COMBO", `All models failed | ${msg} (${retryHuman})`);
323
+ return unavailableResponse(status, msg, earliestRetryAfter, retryHuman);
324
+ }
325
+
326
+ log.warn("COMBO", `All models failed | ${msg}`);
327
+ return new Response(
328
+ JSON.stringify({ error: { message: msg } }),
329
+ { status, headers: { "Content-Type": "application/json" } }
330
+ );
331
+ }
332
+
333
+ /**
334
+ * Extract assistant text from a non-stream completion across formats
335
+ * (OpenAI chat, Claude messages, Gemini, OpenAI Responses). Returns "" if none.
336
+ * Panel responses are already translated to the client format by chatCore, so the
337
+ * leaf content→string step reuses the translator's own extractTextContent.
338
+ */
339
+ function extractPanelText(json) {
340
+ if (!json || typeof json !== "object") return "";
341
+
342
+ // OpenAI chat completion
343
+ const choice = json.choices?.[0];
344
+ if (choice) {
345
+ const msg = choice.message ?? choice.delta ?? {};
346
+ const t = extractTextContent(msg.content);
347
+ if (t.trim()) return t;
348
+ if (typeof choice.text === "string" && choice.text.trim()) return choice.text;
349
+ }
350
+
351
+ // Claude messages (text blocks share OpenAI's {type:"text"} shape)
352
+ const claudeText = extractTextContent(json.content);
353
+ if (claudeText.trim()) return claudeText;
354
+
355
+ // Gemini (parts carry .text without a type discriminator)
356
+ const parts = json.candidates?.[0]?.content?.parts;
357
+ if (Array.isArray(parts)) {
358
+ const t = parts.map((p) => p?.text || "").join("");
359
+ if (t.trim()) return t;
360
+ }
361
+
362
+ // OpenAI Responses API
363
+ if (Array.isArray(json.output)) {
364
+ const t = json.output
365
+ .flatMap((o) => (Array.isArray(o.content) ? o.content.map((c) => c?.text || "") : []))
366
+ .join("");
367
+ if (t.trim()) return t;
368
+ }
369
+
370
+ return "";
371
+ }
372
+
373
+ /**
374
+ * Append a synthesized user turn to whichever message array the request format uses.
375
+ * Preserves the original conversation + system prompt so the judge has full context.
376
+ */
377
+ function appendUserTurn(body, text) {
378
+ const next = { ...body };
379
+ if (Array.isArray(body.messages)) {
380
+ next.messages = [...body.messages, { role: "user", content: text }];
381
+ } else if (Array.isArray(body.input)) {
382
+ next.input = [...body.input, { role: "user", content: text }];
383
+ } else if (Array.isArray(body.contents)) {
384
+ next.contents = [...body.contents, { role: "user", parts: [{ text }] }];
385
+ } else {
386
+ next.messages = [{ role: "user", content: text }];
387
+ }
388
+ return next;
389
+ }
390
+
391
+ /**
392
+ * Build the judge directive. Per OpenRouter's Fusion design, the judge does NOT
393
+ * merge — it analyzes (consensus / contradictions / partial coverage / unique
394
+ * insights / blind spots) then writes one answer grounded in that analysis.
395
+ * ~3/4 of fusion's quality lift comes from this synthesis step.
396
+ *
397
+ * Sources are anonymized ("Source N") so the judge weighs substance, not the
398
+ * reputation of a model brand.
399
+ */
400
+ function buildJudgePrompt(answers) {
401
+ const panel = answers
402
+ .map((a, i) => `[Source ${i + 1}]\n${a.text}`)
403
+ .join("\n\n");
404
+
405
+ return [
406
+ `You are the JUDGE in a model-fusion panel. ${answers.length} expert models independently answered the user's most recent request. Their responses are below, anonymized by source.`,
407
+ "",
408
+ "Do NOT mention that multiple models were used, and do NOT refer to the sources. Produce ONE authoritative final answer addressed directly to the user.",
409
+ "",
410
+ "First, internally analyze the panel along these dimensions: consensus (points most sources agree on — treat as higher-confidence), contradictions (where they disagree — resolve with your own judgment), partial coverage, unique insights only one source surfaced, and blind spots every source missed. Then write the best possible final answer grounded in that analysis — more complete and correct than any single response, with no filler.",
411
+ "",
412
+ "=== PANEL RESPONSES ===",
413
+ panel,
414
+ "=== END PANEL RESPONSES ===",
415
+ "",
416
+ "Now write the final answer to the user's original request.",
417
+ ].join("\n");
418
+ }
419
+
420
+ // Fusion tuning. Overridable per-combo via settings.comboStrategies[name].
421
+ const FUSION_DEFAULTS = {
422
+ minPanel: 2, // answers needed before stragglers get a grace window
423
+ stragglerGraceMs: 8000, // wait this long for laggards once quorum is reached
424
+ panelHardTimeoutMs: 90000, // absolute cap so one hung model can't stall forever
425
+ };
426
+
427
+ // Resolve a Response (or {__error}) within ms; the loser keeps running but is ignored.
428
+ function withTimeout(promise, ms) {
429
+ return new Promise((resolve) => {
430
+ const t = setTimeout(() => resolve({ __timeout: true }), ms);
431
+ Promise.resolve(promise)
432
+ .then((v) => { clearTimeout(t); resolve(v); })
433
+ .catch((e) => { clearTimeout(t); resolve({ __error: e }); });
434
+ });
435
+ }
436
+
437
+ /**
438
+ * Collect panel responses with quorum-grace: as soon as `minPanel` calls succeed,
439
+ * start a short grace timer for the rest, then proceed with whatever arrived. This
440
+ * caps the straggler penalty (the slowest model otherwise dominates wall time) while
441
+ * still preferring a full panel when everyone is fast. Bounded by a hard timeout.
442
+ * Returns a sparse array aligned to `calls` (undefined = not yet / dropped).
443
+ */
444
+ function collectPanel(calls, { minPanel, stragglerGraceMs, panelHardTimeoutMs }) {
445
+ return new Promise((resolve) => {
446
+ const out = new Array(calls.length);
447
+ let settled = 0;
448
+ let ok = 0;
449
+ let finished = false;
450
+ let graceTimer = null;
451
+ const finish = () => {
452
+ if (finished) return;
453
+ finished = true;
454
+ clearTimeout(hardTimer);
455
+ if (graceTimer) clearTimeout(graceTimer);
456
+ resolve(out);
457
+ };
458
+ const hardTimer = setTimeout(finish, panelHardTimeoutMs);
459
+ calls.forEach((p, i) => {
460
+ Promise.resolve(p)
461
+ .then((v) => { out[i] = v; })
462
+ .catch((e) => { out[i] = { __error: e }; })
463
+ .finally(() => {
464
+ settled++;
465
+ if (out[i] && out[i].ok) ok++;
466
+ if (settled === calls.length) return finish();
467
+ if (ok >= minPanel && !graceTimer) graceTimer = setTimeout(finish, stragglerGraceMs);
468
+ });
469
+ });
470
+ });
471
+ }
472
+
473
+ /**
474
+ * Handle a fusion combo: fan the prompt out to every panel model in parallel,
475
+ * then a judge model synthesizes one final answer from all panel responses.
476
+ *
477
+ * Panel calls are forced non-streaming with tools stripped (the judge needs
478
+ * complete prose to synthesize). The judge call keeps the client's original
479
+ * stream flag + tools, so streaming and downstream tool use still work.
480
+ *
481
+ * Speed: quorum-grace collection caps the straggler penalty. Quality: the judge
482
+ * runs the consensus/contradiction/blind-spot analysis before writing.
483
+ *
484
+ * Degrades gracefully: 0 panel answers -> 503, exactly 1 -> return it directly.
485
+ *
486
+ * @param {Object} options
487
+ * @param {Object} options.body - Request body (client format)
488
+ * @param {string[]} options.models - Panel model strings
489
+ * @param {Function} options.handleSingleModel - (body, modelStr) => Promise<Response>
490
+ * @param {Object} options.log - Logger
491
+ * @param {string} [options.comboName] - Combo name (logging)
492
+ * @param {string} [options.judgeModel] - Judge model; falls back to panel[0]
493
+ * @param {Object} [options.tuning] - Override FUSION_DEFAULTS (minPanel, grace, timeout)
494
+ * @returns {Promise<Response>}
495
+ */
496
+ export async function handleFusionChat({ body, models, handleSingleModel, log, comboName, judgeModel, tuning }) {
497
+ const panel = Array.isArray(models) ? models.filter(Boolean) : [];
498
+ if (panel.length === 0) {
499
+ return new Response(
500
+ JSON.stringify({ error: { message: "Fusion combo has no models" } }),
501
+ { status: 400, headers: { "Content-Type": "application/json" } }
502
+ );
503
+ }
504
+
505
+ // A single-model fusion has nothing to fuse — just answer directly.
506
+ if (panel.length === 1) {
507
+ return handleSingleModel(body, panel[0]);
508
+ }
509
+
510
+ const cfg = { ...FUSION_DEFAULTS, ...(tuning || {}) };
511
+ const minPanel = Math.min(Math.max(2, cfg.minPanel), panel.length);
512
+ const judge = judgeModel && judgeModel.trim() ? judgeModel.trim() : panel[0];
513
+ log.info("FUSION", `Combo "${comboName}" | panel=${panel.length} [${panel.join(", ")}] | judge=${judge} | quorum=${minPanel}`);
514
+
515
+ // 1. Fan out to the panel in parallel: non-streaming, tools stripped (we want prose).
516
+ const { tools, tool_choice, ...rest } = body;
517
+ const panelBody = { ...rest, stream: false };
518
+
519
+ // Flatten tool turns to prose so panel models keep context without emitting tool_calls.
520
+ if (Array.isArray(panelBody.messages)) {
521
+ panelBody.messages = flattenToolHistory(panelBody.messages);
522
+ } else if (Array.isArray(panelBody.input)) {
523
+ panelBody.input = flattenToolHistory(panelBody.input);
524
+ }
525
+
526
+ const t0 = Date.now();
527
+ const calls = panel.map((m) => withTimeout(handleSingleModel(panelBody, m, true), cfg.panelHardTimeoutMs));
528
+ const settled = await collectPanel(calls, { ...cfg, minPanel });
529
+ log.info("FUSION", `fan-out collected in ${Date.now() - t0}ms`);
530
+
531
+ // 2. Collect successful answers.
532
+ const answers = [];
533
+ for (let i = 0; i < settled.length; i++) {
534
+ const res = settled[i];
535
+ const model = panel[i];
536
+ if (!res) { log.warn("FUSION", `Panel ${model} dropped (straggler/timeout)`); continue; }
537
+ if (res.__timeout) { log.warn("FUSION", `Panel ${model} timed out`); continue; }
538
+ if (res.__error) { log.warn("FUSION", `Panel ${model} threw`, { error: res.__error?.message || String(res.__error) }); continue; }
539
+ if (!res.ok) { log.warn("FUSION", `Panel ${model} failed`, { status: res.status }); continue; }
540
+ try {
541
+ const json = await res.clone().json();
542
+ const text = extractPanelText(json);
543
+ if (text) {
544
+ answers.push({ model, text });
545
+ log.info("FUSION", `Panel ${model} ok (${text.length} chars)`);
546
+ } else {
547
+ log.warn("FUSION", `Panel ${model} returned empty content`);
548
+ }
549
+ } catch (e) {
550
+ log.warn("FUSION", `Panel ${model} unparseable`, { error: e.message || String(e) });
551
+ }
552
+ }
553
+
554
+ // 3. Degrade gracefully when the panel is too thin to fuse.
555
+ if (answers.length === 0) {
556
+ log.warn("FUSION", "All panel models failed");
557
+ return new Response(
558
+ JSON.stringify({ error: { message: "All fusion panel models failed" } }),
559
+ { status: 503, headers: { "Content-Type": "application/json" } }
560
+ );
561
+ }
562
+ if (answers.length === 1) {
563
+ log.info("FUSION", `Only ${answers[0].model} succeeded — answering directly (no fusion)`);
564
+ return handleSingleModel(body, answers[0].model);
565
+ }
566
+
567
+ // 4. Judge analyzes + writes one final answer (streams to client if requested).
568
+ const judgeBody = appendUserTurn(body, buildJudgePrompt(answers));
569
+ log.info("FUSION", `Judging ${answers.length} answers with ${judge}`);
570
+ return handleSingleModel(judgeBody, judge);
571
+ }
@@ -0,0 +1,91 @@
1
+ const CACHE_TAG_PATTERN = /<omniModel>([^<]+)<\/omniModel>/;
2
+ const CACHE_TAG_PATTERN_GLOBAL = /(?:\\n|\n|\r){0,16}<omniModel>([^<]+)<\/omniModel>(?:\\n|\n|\r){0,16}/g;
3
+ function injectModelTag(messages, providerModel) {
4
+ const cleaned = messages.map((msg2) => {
5
+ if (msg2.role === "assistant" && typeof msg2.content === "string") {
6
+ return { ...msg2, content: msg2.content.replace(CACHE_TAG_PATTERN_GLOBAL, "").trimEnd() };
7
+ }
8
+ return msg2;
9
+ });
10
+ const lastAssistantIdx = cleaned.map((m) => m.role).lastIndexOf("assistant");
11
+ if (lastAssistantIdx === -1) {
12
+ return [...cleaned, { role: "assistant", content: `<omniModel>${providerModel}</omniModel>` }];
13
+ }
14
+ const msg = cleaned[lastAssistantIdx];
15
+ if (typeof msg.content !== "string") {
16
+ return [...cleaned, { role: "assistant", content: `<omniModel>${providerModel}</omniModel>` }];
17
+ }
18
+ const tagged = [...cleaned];
19
+ tagged[lastAssistantIdx] = {
20
+ ...msg,
21
+ content: `${msg.content}<omniModel>${providerModel}</omniModel>`
22
+ };
23
+ return tagged;
24
+ }
25
+ function extractPinnedModel(messages) {
26
+ for (let i = messages.length - 1; i >= 0; i--) {
27
+ const msg = messages[i];
28
+ if (msg.role === "assistant" && typeof msg.content === "string") {
29
+ const match = CACHE_TAG_PATTERN.exec(msg.content);
30
+ if (match) return match[1];
31
+ }
32
+ }
33
+ return null;
34
+ }
35
+ function applySystemMessageOverride(messages, systemMessage) {
36
+ const filtered = messages.filter((m) => m.role !== "system");
37
+ return [{ role: "system", content: systemMessage }, ...filtered];
38
+ }
39
+ function applyToolFilter(tools, pattern) {
40
+ if (!tools || !pattern) return tools;
41
+ let regex;
42
+ try {
43
+ regex = new RegExp(pattern);
44
+ } catch {
45
+ console.warn(`[ComboAgent] Invalid tool_filter_regex: "${pattern}"`);
46
+ return tools;
47
+ }
48
+ return tools.filter((tool) => {
49
+ const t = tool;
50
+ const name = t.function?.name ?? t.name ?? "";
51
+ return regex.test(String(name));
52
+ });
53
+ }
54
+ function stripModelTags(messages) {
55
+ return messages.map((msg) => {
56
+ if (typeof msg.content === "string" && CACHE_TAG_PATTERN.test(msg.content)) {
57
+ return { ...msg, content: msg.content.replace(CACHE_TAG_PATTERN_GLOBAL, "").trimEnd() };
58
+ }
59
+ return msg;
60
+ });
61
+ }
62
+ function applyComboAgentMiddleware(body, comboConfig, providerModel) {
63
+ if (!comboConfig) return { body, pinnedModel: null };
64
+ let messages = Array.isArray(body.messages) ? [...body.messages] : [];
65
+ let pinnedModel = null;
66
+ pinnedModel = null;
67
+ if (comboConfig.system_message && comboConfig.system_message.trim()) {
68
+ messages = applySystemMessageOverride(messages, comboConfig.system_message);
69
+ }
70
+ const filteredTools = applyToolFilter(
71
+ body.tools,
72
+ comboConfig.tool_filter_regex
73
+ );
74
+ messages = stripModelTags(messages);
75
+ return {
76
+ body: {
77
+ ...body,
78
+ messages,
79
+ ...filteredTools !== body.tools && { tools: filteredTools }
80
+ },
81
+ pinnedModel
82
+ };
83
+ }
84
+ export {
85
+ applyComboAgentMiddleware,
86
+ applySystemMessageOverride,
87
+ applyToolFilter,
88
+ extractPinnedModel,
89
+ injectModelTag,
90
+ stripModelTags
91
+ };