blackriver-gateway 3.8.46

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 (2415) hide show
  1. package/.env.example +2070 -0
  2. package/@omniroute/opencode-plugin/LICENSE +21 -0
  3. package/@omniroute/opencode-plugin/README.md +296 -0
  4. package/@omniroute/opencode-plugin/package-lock.json +1930 -0
  5. package/@omniroute/opencode-plugin/package.json +73 -0
  6. package/@omniroute/opencode-plugin/src/index.ts +4685 -0
  7. package/@omniroute/opencode-plugin/src/logger.ts +74 -0
  8. package/@omniroute/opencode-plugin/src/naming.ts +301 -0
  9. package/@omniroute/opencode-plugin/tsconfig.json +20 -0
  10. package/@omniroute/opencode-plugin/tsup.config.ts +20 -0
  11. package/@omniroute/opencode-provider/LICENSE +21 -0
  12. package/@omniroute/opencode-provider/README.md +156 -0
  13. package/@omniroute/opencode-provider/package-lock.json +1514 -0
  14. package/@omniroute/opencode-provider/package.json +63 -0
  15. package/@omniroute/opencode-provider/src/index.ts +908 -0
  16. package/@omniroute/opencode-provider/tsconfig.json +20 -0
  17. package/@omniroute/opencode-provider/tsup.config.ts +18 -0
  18. package/LICENSE +22 -0
  19. package/README.md +1265 -0
  20. package/bin/_ops-common.sh +70 -0
  21. package/bin/cli/CONVENTIONS.md +224 -0
  22. package/bin/cli/README.md +146 -0
  23. package/bin/cli/api-commands/agent-skills.mjs +70 -0
  24. package/bin/cli/api-commands/agentbridge.mjs +155 -0
  25. package/bin/cli/api-commands/api-keys.mjs +42 -0
  26. package/bin/cli/api-commands/audio.mjs +40 -0
  27. package/bin/cli/api-commands/chat.mjs +58 -0
  28. package/bin/cli/api-commands/cli-tools.mjs +361 -0
  29. package/bin/cli/api-commands/cloud.mjs +81 -0
  30. package/bin/cli/api-commands/combos.mjs +69 -0
  31. package/bin/cli/api-commands/compression.mjs +128 -0
  32. package/bin/cli/api-commands/embedded-services.mjs +202 -0
  33. package/bin/cli/api-commands/embeddings.mjs +42 -0
  34. package/bin/cli/api-commands/fallback.mjs +49 -0
  35. package/bin/cli/api-commands/images.mjs +42 -0
  36. package/bin/cli/api-commands/memory.mjs +251 -0
  37. package/bin/cli/api-commands/messages.mjs +40 -0
  38. package/bin/cli/api-commands/models.mjs +89 -0
  39. package/bin/cli/api-commands/moderations.mjs +24 -0
  40. package/bin/cli/api-commands/oauth.mjs +114 -0
  41. package/bin/cli/api-commands/playground.mjs +83 -0
  42. package/bin/cli/api-commands/pricing.mjs +44 -0
  43. package/bin/cli/api-commands/provider-nodes.mjs +62 -0
  44. package/bin/cli/api-commands/providers.mjs +148 -0
  45. package/bin/cli/api-commands/quota.mjs +154 -0
  46. package/bin/cli/api-commands/registry.mjs +75 -0
  47. package/bin/cli/api-commands/rerank.mjs +24 -0
  48. package/bin/cli/api-commands/responses.mjs +24 -0
  49. package/bin/cli/api-commands/settings.mjs +228 -0
  50. package/bin/cli/api-commands/system.mjs +320 -0
  51. package/bin/cli/api-commands/telemetry.mjs +26 -0
  52. package/bin/cli/api-commands/traffic-inspector.mjs +307 -0
  53. package/bin/cli/api-commands/translator.mjs +65 -0
  54. package/bin/cli/api-commands/usage.mjs +117 -0
  55. package/bin/cli/api.mjs +269 -0
  56. package/bin/cli/commands/a2a.mjs +323 -0
  57. package/bin/cli/commands/audit.mjs +203 -0
  58. package/bin/cli/commands/autostart.mjs +57 -0
  59. package/bin/cli/commands/backup.mjs +469 -0
  60. package/bin/cli/commands/batches.mjs +235 -0
  61. package/bin/cli/commands/cache.mjs +102 -0
  62. package/bin/cli/commands/chat.mjs +162 -0
  63. package/bin/cli/commands/cloud.mjs +233 -0
  64. package/bin/cli/commands/combo.mjs +361 -0
  65. package/bin/cli/commands/completion.mjs +346 -0
  66. package/bin/cli/commands/compression.mjs +247 -0
  67. package/bin/cli/commands/config.mjs +351 -0
  68. package/bin/cli/commands/configure.mjs +180 -0
  69. package/bin/cli/commands/connect.mjs +132 -0
  70. package/bin/cli/commands/context-eng.mjs +182 -0
  71. package/bin/cli/commands/contexts.mjs +271 -0
  72. package/bin/cli/commands/cost.mjs +144 -0
  73. package/bin/cli/commands/dashboard.mjs +65 -0
  74. package/bin/cli/commands/doctor.mjs +527 -0
  75. package/bin/cli/commands/env.mjs +100 -0
  76. package/bin/cli/commands/eval.mjs +278 -0
  77. package/bin/cli/commands/files.mjs +144 -0
  78. package/bin/cli/commands/health.mjs +123 -0
  79. package/bin/cli/commands/keys.mjs +599 -0
  80. package/bin/cli/commands/launch-codex.mjs +201 -0
  81. package/bin/cli/commands/launch.mjs +155 -0
  82. package/bin/cli/commands/login.mjs +192 -0
  83. package/bin/cli/commands/logs.mjs +183 -0
  84. package/bin/cli/commands/mcp.mjs +273 -0
  85. package/bin/cli/commands/memory.mjs +244 -0
  86. package/bin/cli/commands/models.mjs +92 -0
  87. package/bin/cli/commands/nodes.mjs +177 -0
  88. package/bin/cli/commands/oauth.mjs +258 -0
  89. package/bin/cli/commands/oneproxy.mjs +120 -0
  90. package/bin/cli/commands/open.mjs +75 -0
  91. package/bin/cli/commands/openapi.mjs +168 -0
  92. package/bin/cli/commands/plugin.mjs +219 -0
  93. package/bin/cli/commands/policy.mjs +216 -0
  94. package/bin/cli/commands/pricing.mjs +123 -0
  95. package/bin/cli/commands/provider-cmd.mjs +18 -0
  96. package/bin/cli/commands/providers.mjs +706 -0
  97. package/bin/cli/commands/quota.mjs +100 -0
  98. package/bin/cli/commands/redis.mjs +294 -0
  99. package/bin/cli/commands/registry.mjs +162 -0
  100. package/bin/cli/commands/repl.mjs +19 -0
  101. package/bin/cli/commands/reset-encrypted-columns.mjs +88 -0
  102. package/bin/cli/commands/resilience.mjs +208 -0
  103. package/bin/cli/commands/restart.mjs +25 -0
  104. package/bin/cli/commands/runtime.mjs +98 -0
  105. package/bin/cli/commands/serve.mjs +426 -0
  106. package/bin/cli/commands/sessions.mjs +108 -0
  107. package/bin/cli/commands/setup-aider.mjs +146 -0
  108. package/bin/cli/commands/setup-claude.mjs +219 -0
  109. package/bin/cli/commands/setup-cline.mjs +160 -0
  110. package/bin/cli/commands/setup-codex.mjs +387 -0
  111. package/bin/cli/commands/setup-continue.mjs +173 -0
  112. package/bin/cli/commands/setup-crush.mjs +148 -0
  113. package/bin/cli/commands/setup-cursor.mjs +108 -0
  114. package/bin/cli/commands/setup-goose.mjs +150 -0
  115. package/bin/cli/commands/setup-kilo.mjs +178 -0
  116. package/bin/cli/commands/setup-open-code.mjs +398 -0
  117. package/bin/cli/commands/setup-opencode.mjs +129 -0
  118. package/bin/cli/commands/setup-qwen.mjs +156 -0
  119. package/bin/cli/commands/setup-roo.mjs +172 -0
  120. package/bin/cli/commands/setup.mjs +211 -0
  121. package/bin/cli/commands/simulate.mjs +125 -0
  122. package/bin/cli/commands/skills.mjs +373 -0
  123. package/bin/cli/commands/status.mjs +95 -0
  124. package/bin/cli/commands/stop.mjs +96 -0
  125. package/bin/cli/commands/stream.mjs +166 -0
  126. package/bin/cli/commands/sync.mjs +230 -0
  127. package/bin/cli/commands/tags.mjs +116 -0
  128. package/bin/cli/commands/telemetry.mjs +74 -0
  129. package/bin/cli/commands/test-provider.mjs +242 -0
  130. package/bin/cli/commands/tokens.mjs +118 -0
  131. package/bin/cli/commands/translator.mjs +131 -0
  132. package/bin/cli/commands/tray.mjs +36 -0
  133. package/bin/cli/commands/tunnel.mjs +347 -0
  134. package/bin/cli/commands/update.mjs +194 -0
  135. package/bin/cli/commands/usage.mjs +331 -0
  136. package/bin/cli/commands/webhooks.mjs +196 -0
  137. package/bin/cli/contexts.mjs +60 -0
  138. package/bin/cli/data-dir.mjs +59 -0
  139. package/bin/cli/encryption.mjs +67 -0
  140. package/bin/cli/i18n.mjs +106 -0
  141. package/bin/cli/io.mjs +83 -0
  142. package/bin/cli/locales/ar.json +32 -0
  143. package/bin/cli/locales/az.json +32 -0
  144. package/bin/cli/locales/bg.json +32 -0
  145. package/bin/cli/locales/bn.json +5 -0
  146. package/bin/cli/locales/cs.json +32 -0
  147. package/bin/cli/locales/da.json +32 -0
  148. package/bin/cli/locales/de.json +32 -0
  149. package/bin/cli/locales/en.json +1289 -0
  150. package/bin/cli/locales/es.json +32 -0
  151. package/bin/cli/locales/fa.json +32 -0
  152. package/bin/cli/locales/fi.json +32 -0
  153. package/bin/cli/locales/fr.json +32 -0
  154. package/bin/cli/locales/gu.json +5 -0
  155. package/bin/cli/locales/he.json +5 -0
  156. package/bin/cli/locales/hi.json +32 -0
  157. package/bin/cli/locales/hu.json +32 -0
  158. package/bin/cli/locales/id.json +32 -0
  159. package/bin/cli/locales/in.json +5 -0
  160. package/bin/cli/locales/it.json +32 -0
  161. package/bin/cli/locales/ja.json +32 -0
  162. package/bin/cli/locales/ko.json +32 -0
  163. package/bin/cli/locales/mr.json +5 -0
  164. package/bin/cli/locales/ms.json +5 -0
  165. package/bin/cli/locales/nl.json +32 -0
  166. package/bin/cli/locales/no.json +32 -0
  167. package/bin/cli/locales/phi.json +5 -0
  168. package/bin/cli/locales/pl.json +32 -0
  169. package/bin/cli/locales/pt-BR.json +1286 -0
  170. package/bin/cli/locales/pt.json +32 -0
  171. package/bin/cli/locales/ro.json +32 -0
  172. package/bin/cli/locales/ru.json +32 -0
  173. package/bin/cli/locales/sk.json +32 -0
  174. package/bin/cli/locales/sv.json +32 -0
  175. package/bin/cli/locales/sw.json +5 -0
  176. package/bin/cli/locales/ta.json +5 -0
  177. package/bin/cli/locales/te.json +5 -0
  178. package/bin/cli/locales/th.json +32 -0
  179. package/bin/cli/locales/tr.json +32 -0
  180. package/bin/cli/locales/uk-UA.json +32 -0
  181. package/bin/cli/locales/ur.json +5 -0
  182. package/bin/cli/locales/vi.json +32 -0
  183. package/bin/cli/locales/zh-CN.json +1262 -0
  184. package/bin/cli/output.mjs +200 -0
  185. package/bin/cli/plugins.mjs +90 -0
  186. package/bin/cli/program.mjs +40 -0
  187. package/bin/cli/provider-catalog.mjs +175 -0
  188. package/bin/cli/provider-store.mjs +312 -0
  189. package/bin/cli/provider-test.mjs +181 -0
  190. package/bin/cli/runtime/index.mjs +19 -0
  191. package/bin/cli/runtime/magicBytes.mjs +47 -0
  192. package/bin/cli/runtime/nativeDeps.mjs +137 -0
  193. package/bin/cli/runtime/processSupervisor.mjs +136 -0
  194. package/bin/cli/runtime/sqliteRuntime.mjs +129 -0
  195. package/bin/cli/runtime/supervisorPolicy.mjs +56 -0
  196. package/bin/cli/runtime/trayRuntime.ts +94 -0
  197. package/bin/cli/runtime.mjs +61 -0
  198. package/bin/cli/schemas/output-schemas.mjs +56 -0
  199. package/bin/cli/scripts/generate-locales.mjs +911 -0
  200. package/bin/cli/settings-store.mjs +45 -0
  201. package/bin/cli/spinner.mjs +30 -0
  202. package/bin/cli/sqlite.mjs +158 -0
  203. package/bin/cli/tray/autostart.mjs +410 -0
  204. package/bin/cli/tray/autostart.ts +18 -0
  205. package/bin/cli/tray/icon.png +0 -0
  206. package/bin/cli/tray/index.mjs +28 -0
  207. package/bin/cli/tray/tray.ps1 +99 -0
  208. package/bin/cli/tray/tray.ts +186 -0
  209. package/bin/cli/tray/traySystray.mjs +135 -0
  210. package/bin/cli/tray/trayWin.ts +91 -0
  211. package/bin/cli/tray/trayWindows.mjs +75 -0
  212. package/bin/cli/tui/Dashboard.jsx +70 -0
  213. package/bin/cli/tui/EvalWatch.jsx +171 -0
  214. package/bin/cli/tui/InterfaceMenu.jsx +55 -0
  215. package/bin/cli/tui/OAuthFlow.jsx +193 -0
  216. package/bin/cli/tui/ProvidersTestAll.jsx +190 -0
  217. package/bin/cli/tui/Repl.jsx +392 -0
  218. package/bin/cli/tui/session.mjs +54 -0
  219. package/bin/cli/tui/tabs/Combos.jsx +47 -0
  220. package/bin/cli/tui/tabs/Cost.jsx +52 -0
  221. package/bin/cli/tui/tabs/Health.jsx +53 -0
  222. package/bin/cli/tui/tabs/Keys.jsx +48 -0
  223. package/bin/cli/tui/tabs/Logs.jsx +60 -0
  224. package/bin/cli/tui/tabs/Overview.jsx +80 -0
  225. package/bin/cli/tui/tabs/Providers.jsx +48 -0
  226. package/bin/cli/tui-components/CodeBlock.jsx +15 -0
  227. package/bin/cli/tui-components/ConfirmDialog.jsx +40 -0
  228. package/bin/cli/tui-components/DataTable.jsx +50 -0
  229. package/bin/cli/tui-components/HeaderSwr.jsx +25 -0
  230. package/bin/cli/tui-components/KeyMaskedDisplay.jsx +12 -0
  231. package/bin/cli/tui-components/MarkdownView.jsx +13 -0
  232. package/bin/cli/tui-components/MenuSelect.jsx +38 -0
  233. package/bin/cli/tui-components/MultilineInput.jsx +18 -0
  234. package/bin/cli/tui-components/ProgressBar.jsx +15 -0
  235. package/bin/cli/tui-components/Sparkline.jsx +15 -0
  236. package/bin/cli/tui-components/StatusBadge.jsx +17 -0
  237. package/bin/cli/tui-components/TokenCounter.jsx +18 -0
  238. package/bin/cli/tui-components/theme.jsx +11 -0
  239. package/bin/cli/utils/cliToken.mjs +22 -0
  240. package/bin/cli/utils/clipboard.mjs +35 -0
  241. package/bin/cli/utils/environment.mjs +50 -0
  242. package/bin/cli/utils/pid.mjs +110 -0
  243. package/bin/cli/utils/storageKeyProvision.mjs +31 -0
  244. package/bin/cold-start-bench.sh +82 -0
  245. package/bin/mcp-server.mjs +71 -0
  246. package/bin/nodeRuntimeSupport.mjs +84 -0
  247. package/bin/omniroute.mjs +237 -0
  248. package/bin/reset-password.mjs +137 -0
  249. package/bin/restore-data.sh +64 -0
  250. package/bin/restore-policies.sh +77 -0
  251. package/bin/rollback.sh +102 -0
  252. package/bin/snapshot-data.sh +61 -0
  253. package/open-sse/config/agyModels.ts +157 -0
  254. package/open-sse/config/anthropicHeaders.ts +127 -0
  255. package/open-sse/config/antigravityModelAliases.ts +309 -0
  256. package/open-sse/config/antigravityUpstream.ts +20 -0
  257. package/open-sse/config/audioRegistry.ts +547 -0
  258. package/open-sse/config/azureAi.ts +49 -0
  259. package/open-sse/config/bedrock.ts +196 -0
  260. package/open-sse/config/cliFingerprints.ts +405 -0
  261. package/open-sse/config/codexClient.ts +49 -0
  262. package/open-sse/config/codexIdentity.ts +87 -0
  263. package/open-sse/config/codexInstructions.ts +122 -0
  264. package/open-sse/config/codexQuotaScopes.ts +87 -0
  265. package/open-sse/config/constants.ts +281 -0
  266. package/open-sse/config/contextEditing.ts +156 -0
  267. package/open-sse/config/credentialLoader.ts +123 -0
  268. package/open-sse/config/datarobot.ts +69 -0
  269. package/open-sse/config/defaultThinkingSignature.ts +8 -0
  270. package/open-sse/config/embeddingRegistry.ts +434 -0
  271. package/open-sse/config/errorConfig.ts +201 -0
  272. package/open-sse/config/freeModelCatalog.data.ts +467 -0
  273. package/open-sse/config/freeModelCatalog.ts +142 -0
  274. package/open-sse/config/freeTierCatalog.ts +101 -0
  275. package/open-sse/config/geminiRateLimits.json +34 -0
  276. package/open-sse/config/glmProvider.ts +488 -0
  277. package/open-sse/config/imageRegistry.ts +752 -0
  278. package/open-sse/config/maritalk.ts +18 -0
  279. package/open-sse/config/mediaServiceKinds.ts +70 -0
  280. package/open-sse/config/moderationRegistry.ts +89 -0
  281. package/open-sse/config/musicRegistry.ts +115 -0
  282. package/open-sse/config/oci.ts +44 -0
  283. package/open-sse/config/ocrRegistry.ts +82 -0
  284. package/open-sse/config/ollamaModels.ts +28 -0
  285. package/open-sse/config/providerErrorRules.ts +218 -0
  286. package/open-sse/config/providerFieldStrips.ts +42 -0
  287. package/open-sse/config/providerHeaderProfiles.ts +188 -0
  288. package/open-sse/config/providerModels.ts +199 -0
  289. package/open-sse/config/providerPluginManifest.ts +186 -0
  290. package/open-sse/config/providerPluginManifestRegistry.ts +31 -0
  291. package/open-sse/config/providerPluginManifestUrl.ts +26 -0
  292. package/open-sse/config/providerRegistry.ts +257 -0
  293. package/open-sse/config/providers/index.ts +377 -0
  294. package/open-sse/config/providers/registry/adapta-web/index.ts +20 -0
  295. package/open-sse/config/providers/registry/agentrouter/index.ts +24 -0
  296. package/open-sse/config/providers/registry/agy/index.ts +28 -0
  297. package/open-sse/config/providers/registry/ai21/index.ts +13 -0
  298. package/open-sse/config/providers/registry/aimlapi/index.ts +21 -0
  299. package/open-sse/config/providers/registry/alibaba/cn/index.ts +15 -0
  300. package/open-sse/config/providers/registry/alibaba/index.ts +15 -0
  301. package/open-sse/config/providers/registry/anthropic/index.ts +52 -0
  302. package/open-sse/config/providers/registry/antigravity/index.ts +28 -0
  303. package/open-sse/config/providers/registry/api-airforce/index.ts +57 -0
  304. package/open-sse/config/providers/registry/auggie/index.ts +38 -0
  305. package/open-sse/config/providers/registry/bai/index.ts +14 -0
  306. package/open-sse/config/providers/registry/baichuan/index.ts +20 -0
  307. package/open-sse/config/providers/registry/baidu/index.ts +31 -0
  308. package/open-sse/config/providers/registry/bailian-coding-plan/index.ts +27 -0
  309. package/open-sse/config/providers/registry/baseten/index.ts +13 -0
  310. package/open-sse/config/providers/registry/bazaarlink/index.ts +48 -0
  311. package/open-sse/config/providers/registry/bedrock/index.ts +49 -0
  312. package/open-sse/config/providers/registry/blackbox/index.ts +25 -0
  313. package/open-sse/config/providers/registry/blackbox/web/index.ts +19 -0
  314. package/open-sse/config/providers/registry/bluesminds/index.ts +39 -0
  315. package/open-sse/config/providers/registry/byteplus/index.ts +21 -0
  316. package/open-sse/config/providers/registry/bytez/index.ts +17 -0
  317. package/open-sse/config/providers/registry/cerebras/index.ts +16 -0
  318. package/open-sse/config/providers/registry/charm-hyper/index.ts +14 -0
  319. package/open-sse/config/providers/registry/chatgpt-web/index.ts +23 -0
  320. package/open-sse/config/providers/registry/chipotle/index.ts +14 -0
  321. package/open-sse/config/providers/registry/chutes/index.ts +12 -0
  322. package/open-sse/config/providers/registry/claude/index.ts +102 -0
  323. package/open-sse/config/providers/registry/claude/web/index.ts +16 -0
  324. package/open-sse/config/providers/registry/cline/index.ts +45 -0
  325. package/open-sse/config/providers/registry/clinepass/index.ts +47 -0
  326. package/open-sse/config/providers/registry/cloudflare-ai/index.ts +33 -0
  327. package/open-sse/config/providers/registry/codebuddy-cn/index.ts +151 -0
  328. package/open-sse/config/providers/registry/codestral/index.ts +13 -0
  329. package/open-sse/config/providers/registry/codex/index.ts +115 -0
  330. package/open-sse/config/providers/registry/cohere/index.ts +28 -0
  331. package/open-sse/config/providers/registry/command-code/index.ts +143 -0
  332. package/open-sse/config/providers/registry/copilot-m365-web/index.ts +12 -0
  333. package/open-sse/config/providers/registry/copilot-web/index.ts +16 -0
  334. package/open-sse/config/providers/registry/coze/index.ts +12 -0
  335. package/open-sse/config/providers/registry/crof/index.ts +38 -0
  336. package/open-sse/config/providers/registry/cursor/index.ts +111 -0
  337. package/open-sse/config/providers/registry/databricks/index.ts +13 -0
  338. package/open-sse/config/providers/registry/deepinfra/index.ts +13 -0
  339. package/open-sse/config/providers/registry/deepseek/index.ts +15 -0
  340. package/open-sse/config/providers/registry/deepseek/web/index.ts +35 -0
  341. package/open-sse/config/providers/registry/devin-cli/index.ts +68 -0
  342. package/open-sse/config/providers/registry/dgrid/index.ts +15 -0
  343. package/open-sse/config/providers/registry/dify/index.ts +12 -0
  344. package/open-sse/config/providers/registry/digitalocean/index.ts +11 -0
  345. package/open-sse/config/providers/registry/dit/index.ts +41 -0
  346. package/open-sse/config/providers/registry/doubao/index.ts +28 -0
  347. package/open-sse/config/providers/registry/doubao/web/index.ts +15 -0
  348. package/open-sse/config/providers/registry/duckduckgo-web/index.ts +19 -0
  349. package/open-sse/config/providers/registry/factory/index.ts +33 -0
  350. package/open-sse/config/providers/registry/featherless-ai/index.ts +13 -0
  351. package/open-sse/config/providers/registry/fireworks/index.ts +35 -0
  352. package/open-sse/config/providers/registry/freeaiapikey/index.ts +38 -0
  353. package/open-sse/config/providers/registry/freemodel-dev/index.ts +19 -0
  354. package/open-sse/config/providers/registry/friendliai/index.ts +16 -0
  355. package/open-sse/config/providers/registry/galadriel/index.ts +13 -0
  356. package/open-sse/config/providers/registry/gemini/index.ts +63 -0
  357. package/open-sse/config/providers/registry/gemini/web/index.ts +16 -0
  358. package/open-sse/config/providers/registry/gigachat/index.ts +13 -0
  359. package/open-sse/config/providers/registry/github/index.ts +161 -0
  360. package/open-sse/config/providers/registry/github/models/index.ts +38 -0
  361. package/open-sse/config/providers/registry/gitlab-duo/index.ts +29 -0
  362. package/open-sse/config/providers/registry/gitlawb/gmi/index.ts +19 -0
  363. package/open-sse/config/providers/registry/gitlawb/index.ts +18 -0
  364. package/open-sse/config/providers/registry/glhf/index.ts +12 -0
  365. package/open-sse/config/providers/registry/glm/cn/index.ts +17 -0
  366. package/open-sse/config/providers/registry/glm/index.ts +16 -0
  367. package/open-sse/config/providers/registry/glm/t/index.ts +16 -0
  368. package/open-sse/config/providers/registry/grok-cli/index.ts +32 -0
  369. package/open-sse/config/providers/registry/grok-web/index.ts +18 -0
  370. package/open-sse/config/providers/registry/groq/index.ts +25 -0
  371. package/open-sse/config/providers/registry/hackclub/index.ts +19 -0
  372. package/open-sse/config/providers/registry/haiper/index.ts +15 -0
  373. package/open-sse/config/providers/registry/hcnsec/index.ts +11 -0
  374. package/open-sse/config/providers/registry/heroku/index.ts +13 -0
  375. package/open-sse/config/providers/registry/huggingchat/index.ts +143 -0
  376. package/open-sse/config/providers/registry/huggingface/index.ts +20 -0
  377. package/open-sse/config/providers/registry/hyperbolic/index.ts +21 -0
  378. package/open-sse/config/providers/registry/ideogram/index.ts +15 -0
  379. package/open-sse/config/providers/registry/iflytek/index.ts +21 -0
  380. package/open-sse/config/providers/registry/inclusionai/index.ts +12 -0
  381. package/open-sse/config/providers/registry/inference-net/index.ts +13 -0
  382. package/open-sse/config/providers/registry/inner-ai/index.ts +43 -0
  383. package/open-sse/config/providers/registry/kenari/index.ts +14 -0
  384. package/open-sse/config/providers/registry/kie/index.ts +27 -0
  385. package/open-sse/config/providers/registry/kilo-gateway/index.ts +21 -0
  386. package/open-sse/config/providers/registry/kilocode/index.ts +43 -0
  387. package/open-sse/config/providers/registry/kimi/coding/index.ts +17 -0
  388. package/open-sse/config/providers/registry/kimi/coding-apikey/index.ts +9 -0
  389. package/open-sse/config/providers/registry/kimi/index.ts +17 -0
  390. package/open-sse/config/providers/registry/kimi/web/index.ts +27 -0
  391. package/open-sse/config/providers/registry/kiro/index.ts +50 -0
  392. package/open-sse/config/providers/registry/kluster/index.ts +12 -0
  393. package/open-sse/config/providers/registry/lambda-ai/index.ts +13 -0
  394. package/open-sse/config/providers/registry/leonardo/index.ts +15 -0
  395. package/open-sse/config/providers/registry/liquid/index.ts +12 -0
  396. package/open-sse/config/providers/registry/llamagate/index.ts +13 -0
  397. package/open-sse/config/providers/registry/llm7/index.ts +27 -0
  398. package/open-sse/config/providers/registry/longcat/index.ts +24 -0
  399. package/open-sse/config/providers/registry/maritalk/index.ts +13 -0
  400. package/open-sse/config/providers/registry/meta-llama/index.ts +13 -0
  401. package/open-sse/config/providers/registry/mimocode/index.ts +16 -0
  402. package/open-sse/config/providers/registry/minimax/cn/index.ts +24 -0
  403. package/open-sse/config/providers/registry/minimax/index.ts +24 -0
  404. package/open-sse/config/providers/registry/mistral/index.ts +18 -0
  405. package/open-sse/config/providers/registry/modal/index.ts +12 -0
  406. package/open-sse/config/providers/registry/modelscope/index.ts +24 -0
  407. package/open-sse/config/providers/registry/monsterapi/index.ts +17 -0
  408. package/open-sse/config/providers/registry/moonshot/index.ts +13 -0
  409. package/open-sse/config/providers/registry/morph/index.ts +13 -0
  410. package/open-sse/config/providers/registry/muse-spark-web/index.ts +24 -0
  411. package/open-sse/config/providers/registry/nanogpt/index.ts +13 -0
  412. package/open-sse/config/providers/registry/nebius/index.ts +9 -0
  413. package/open-sse/config/providers/registry/nlpcloud/index.ts +19 -0
  414. package/open-sse/config/providers/registry/nous-research/index.ts +15 -0
  415. package/open-sse/config/providers/registry/novita/index.ts +15 -0
  416. package/open-sse/config/providers/registry/nscale/index.ts +13 -0
  417. package/open-sse/config/providers/registry/nube/index.ts +17 -0
  418. package/open-sse/config/providers/registry/nvidia/index.ts +36 -0
  419. package/open-sse/config/providers/registry/ollama-cloud/index.ts +27 -0
  420. package/open-sse/config/providers/registry/openadapter/index.ts +25 -0
  421. package/open-sse/config/providers/registry/openai/index.ts +43 -0
  422. package/open-sse/config/providers/registry/opencode/go/index.ts +61 -0
  423. package/open-sse/config/providers/registry/opencode/index.ts +51 -0
  424. package/open-sse/config/providers/registry/opencode/zen/index.ts +98 -0
  425. package/open-sse/config/providers/registry/openrouter/index.ts +17 -0
  426. package/open-sse/config/providers/registry/orcarouter/index.ts +87 -0
  427. package/open-sse/config/providers/registry/ovhcloud/index.ts +13 -0
  428. package/open-sse/config/providers/registry/perplexity/index.ts +22 -0
  429. package/open-sse/config/providers/registry/perplexity/web/index.ts +23 -0
  430. package/open-sse/config/providers/registry/pioneer/index.ts +41 -0
  431. package/open-sse/config/providers/registry/pollinations/index.ts +51 -0
  432. package/open-sse/config/providers/registry/predibase/index.ts +13 -0
  433. package/open-sse/config/providers/registry/publicai/index.ts +13 -0
  434. package/open-sse/config/providers/registry/puter/index.ts +70 -0
  435. package/open-sse/config/providers/registry/qianfan/index.ts +18 -0
  436. package/open-sse/config/providers/registry/qiniu/index.ts +15 -0
  437. package/open-sse/config/providers/registry/qoder/index.ts +37 -0
  438. package/open-sse/config/providers/registry/qwen/index.ts +25 -0
  439. package/open-sse/config/providers/registry/qwen/web/index.ts +24 -0
  440. package/open-sse/config/providers/registry/reka/index.ts +18 -0
  441. package/open-sse/config/providers/registry/requesty/index.ts +11 -0
  442. package/open-sse/config/providers/registry/sambanova/index.ts +13 -0
  443. package/open-sse/config/providers/registry/scaleway/index.ts +20 -0
  444. package/open-sse/config/providers/registry/sensenova/index.ts +27 -0
  445. package/open-sse/config/providers/registry/siliconflow/index.ts +84 -0
  446. package/open-sse/config/providers/registry/snowflake/index.ts +13 -0
  447. package/open-sse/config/providers/registry/sparkdesk/index.ts +20 -0
  448. package/open-sse/config/providers/registry/stepfun/index.ts +20 -0
  449. package/open-sse/config/providers/registry/sumopod/index.ts +15 -0
  450. package/open-sse/config/providers/registry/suno/index.ts +18 -0
  451. package/open-sse/config/providers/registry/synthetic/index.ts +21 -0
  452. package/open-sse/config/providers/registry/t3-web/index.ts +45 -0
  453. package/open-sse/config/providers/registry/tencent/index.ts +25 -0
  454. package/open-sse/config/providers/registry/theoldllm/index.ts +51 -0
  455. package/open-sse/config/providers/registry/together/index.ts +20 -0
  456. package/open-sse/config/providers/registry/tokenrouter/index.ts +44 -0
  457. package/open-sse/config/providers/registry/trae/index.ts +24 -0
  458. package/open-sse/config/providers/registry/udio/index.ts +12 -0
  459. package/open-sse/config/providers/registry/uncloseai/index.ts +19 -0
  460. package/open-sse/config/providers/registry/upstage/index.ts +13 -0
  461. package/open-sse/config/providers/registry/v0-vercel/index.ts +13 -0
  462. package/open-sse/config/providers/registry/venice/index.ts +13 -0
  463. package/open-sse/config/providers/registry/veoaifree-web/index.ts +15 -0
  464. package/open-sse/config/providers/registry/vercel-ai-gateway/index.ts +13 -0
  465. package/open-sse/config/providers/registry/vertex/index.ts +33 -0
  466. package/open-sse/config/providers/registry/vertex/partner/index.ts +22 -0
  467. package/open-sse/config/providers/registry/volcengine/index.ts +13 -0
  468. package/open-sse/config/providers/registry/wafer/index.ts +19 -0
  469. package/open-sse/config/providers/registry/wandb/index.ts +13 -0
  470. package/open-sse/config/providers/registry/windsurf/index.ts +119 -0
  471. package/open-sse/config/providers/registry/x5lab/index.ts +15 -0
  472. package/open-sse/config/providers/registry/xai/index.ts +18 -0
  473. package/open-sse/config/providers/registry/xiaomi-mimo/index.ts +13 -0
  474. package/open-sse/config/providers/registry/yi/index.ts +12 -0
  475. package/open-sse/config/providers/registry/yuanbao-web/index.ts +37 -0
  476. package/open-sse/config/providers/registry/zai/index.ts +28 -0
  477. package/open-sse/config/providers/registry/zed-hosted/index.ts +35 -0
  478. package/open-sse/config/providers/registry/zenmux/index.ts +87 -0
  479. package/open-sse/config/providers/registry/zenmux-free/index.ts +40 -0
  480. package/open-sse/config/providers/shared.ts +766 -0
  481. package/open-sse/config/registryUtils.ts +134 -0
  482. package/open-sse/config/rerankRegistry.ts +196 -0
  483. package/open-sse/config/runway.ts +39 -0
  484. package/open-sse/config/sap.ts +58 -0
  485. package/open-sse/config/searchRegistry.ts +317 -0
  486. package/open-sse/config/toolCloaking.ts +253 -0
  487. package/open-sse/config/videoRegistry.ts +229 -0
  488. package/open-sse/config/watsonx.ts +43 -0
  489. package/open-sse/executors/adapta-web.ts +564 -0
  490. package/open-sse/executors/antigravity/sseCollect.ts +148 -0
  491. package/open-sse/executors/antigravity.ts +1716 -0
  492. package/open-sse/executors/antigravityUpstreamError.ts +25 -0
  493. package/open-sse/executors/auggie.ts +573 -0
  494. package/open-sse/executors/azure-openai.ts +48 -0
  495. package/open-sse/executors/base/headers.ts +93 -0
  496. package/open-sse/executors/base/reasoningEffort.ts +160 -0
  497. package/open-sse/executors/base.ts +1315 -0
  498. package/open-sse/executors/bedrock.ts +714 -0
  499. package/open-sse/executors/blackbox-web.ts +708 -0
  500. package/open-sse/executors/chatgpt-web/models.ts +133 -0
  501. package/open-sse/executors/chatgpt-web.ts +3107 -0
  502. package/open-sse/executors/chatgptWebErrors.ts +18 -0
  503. package/open-sse/executors/chatgptWebTools.ts +127 -0
  504. package/open-sse/executors/chipotle.ts +432 -0
  505. package/open-sse/executors/claude-web/payload.ts +230 -0
  506. package/open-sse/executors/claude-web-with-auto-refresh.ts +117 -0
  507. package/open-sse/executors/claude-web.ts +833 -0
  508. package/open-sse/executors/claudeIdentity.ts +445 -0
  509. package/open-sse/executors/cliproxyapi.ts +466 -0
  510. package/open-sse/executors/cloudflare-ai.ts +97 -0
  511. package/open-sse/executors/codebuddy-cn.ts +53 -0
  512. package/open-sse/executors/codex/quota.ts +114 -0
  513. package/open-sse/executors/codex/tools.ts +165 -0
  514. package/open-sse/executors/codex.ts +1270 -0
  515. package/open-sse/executors/commandCode.ts +716 -0
  516. package/open-sse/executors/copilot-m365-connection.ts +271 -0
  517. package/open-sse/executors/copilot-m365-frames.ts +279 -0
  518. package/open-sse/executors/copilot-m365-web.ts +341 -0
  519. package/open-sse/executors/copilot-web.ts +722 -0
  520. package/open-sse/executors/cursor/composer.ts +53 -0
  521. package/open-sse/executors/cursor/prompt.ts +75 -0
  522. package/open-sse/executors/cursor.ts +1465 -0
  523. package/open-sse/executors/deepseek-web/stream-format.ts +44 -0
  524. package/open-sse/executors/deepseek-web-with-auto-refresh.ts +184 -0
  525. package/open-sse/executors/deepseek-web.ts +1123 -0
  526. package/open-sse/executors/default/urlNormalizers.ts +64 -0
  527. package/open-sse/executors/default.ts +873 -0
  528. package/open-sse/executors/devin-cli.ts +470 -0
  529. package/open-sse/executors/doubao-web.ts +665 -0
  530. package/open-sse/executors/duckduckgo-web/challenge.ts +151 -0
  531. package/open-sse/executors/duckduckgo-web.ts +782 -0
  532. package/open-sse/executors/firecrawl-fetch.ts +177 -0
  533. package/open-sse/executors/forceResponsesUpstream.ts +60 -0
  534. package/open-sse/executors/gemini-business.ts +446 -0
  535. package/open-sse/executors/gemini-web.ts +413 -0
  536. package/open-sse/executors/github.ts +376 -0
  537. package/open-sse/executors/gitlab.ts +793 -0
  538. package/open-sse/executors/gitlabResponses.ts +191 -0
  539. package/open-sse/executors/glm.ts +520 -0
  540. package/open-sse/executors/grok-cli.ts +253 -0
  541. package/open-sse/executors/grok-web/native-tools.ts +182 -0
  542. package/open-sse/executors/grok-web/text-cleanup.ts +137 -0
  543. package/open-sse/executors/grok-web/tool-bridge.ts +666 -0
  544. package/open-sse/executors/grok-web/types.ts +47 -0
  545. package/open-sse/executors/grok-web.ts +883 -0
  546. package/open-sse/executors/huggingchat/jsonlStream.ts +221 -0
  547. package/open-sse/executors/huggingchat.ts +593 -0
  548. package/open-sse/executors/index.ts +232 -0
  549. package/open-sse/executors/inner-ai.ts +764 -0
  550. package/open-sse/executors/jina-reader-fetch.ts +119 -0
  551. package/open-sse/executors/kie.ts +109 -0
  552. package/open-sse/executors/kimi-web.ts +455 -0
  553. package/open-sse/executors/kimi.ts +133 -0
  554. package/open-sse/executors/kiro/eventstream.ts +192 -0
  555. package/open-sse/executors/kiro.ts +821 -0
  556. package/open-sse/executors/kiroThinking.ts +116 -0
  557. package/open-sse/executors/lmarena.ts +511 -0
  558. package/open-sse/executors/mimocode.ts +560 -0
  559. package/open-sse/executors/muse-spark-web/response-parser.ts +383 -0
  560. package/open-sse/executors/muse-spark-web.ts +928 -0
  561. package/open-sse/executors/ninerouter.ts +212 -0
  562. package/open-sse/executors/nlpcloud.ts +546 -0
  563. package/open-sse/executors/opencode.ts +336 -0
  564. package/open-sse/executors/perplexity-web/protocol.ts +503 -0
  565. package/open-sse/executors/perplexity-web.ts +545 -0
  566. package/open-sse/executors/poe-web.ts +158 -0
  567. package/open-sse/executors/pollinations.ts +119 -0
  568. package/open-sse/executors/puter.ts +59 -0
  569. package/open-sse/executors/qoder.ts +416 -0
  570. package/open-sse/executors/qwen-web.ts +474 -0
  571. package/open-sse/executors/t3-chat-web.ts +582 -0
  572. package/open-sse/executors/tavily-fetch.ts +103 -0
  573. package/open-sse/executors/theoldllm.ts +354 -0
  574. package/open-sse/executors/tinyfish-fetch.ts +131 -0
  575. package/open-sse/executors/trae.ts +481 -0
  576. package/open-sse/executors/v0-vercel-web.ts +164 -0
  577. package/open-sse/executors/venice-web.ts +165 -0
  578. package/open-sse/executors/veoaifree-web.ts +397 -0
  579. package/open-sse/executors/vertex.ts +208 -0
  580. package/open-sse/executors/vertexMedia.ts +341 -0
  581. package/open-sse/executors/windsurf.ts +706 -0
  582. package/open-sse/executors/xai.ts +94 -0
  583. package/open-sse/executors/yuanbao-web.ts +504 -0
  584. package/open-sse/executors/zed-hosted.ts +364 -0
  585. package/open-sse/executors/zenmux-free.ts +283 -0
  586. package/open-sse/handlers/audioSpeech.ts +1060 -0
  587. package/open-sse/handlers/audioTranscription.ts +554 -0
  588. package/open-sse/handlers/audioTranslation.ts +135 -0
  589. package/open-sse/handlers/chatCore/attemptLogging.ts +210 -0
  590. package/open-sse/handlers/chatCore/backgroundRedirect.ts +41 -0
  591. package/open-sse/handlers/chatCore/cacheUsageMeta.ts +65 -0
  592. package/open-sse/handlers/chatCore/cavemanOutputAnalytics.ts +47 -0
  593. package/open-sse/handlers/chatCore/claudeClassifierCompat.ts +99 -0
  594. package/open-sse/handlers/chatCore/claudeEffortVariant.ts +62 -0
  595. package/open-sse/handlers/chatCore/claudeMessageTypes.ts +15 -0
  596. package/open-sse/handlers/chatCore/claudeSystemRole.ts +48 -0
  597. package/open-sse/handlers/chatCore/claudeToolDefaults.ts +27 -0
  598. package/open-sse/handlers/chatCore/claudeUpstreamMessages.ts +143 -0
  599. package/open-sse/handlers/chatCore/clientUsageBuffer.ts +54 -0
  600. package/open-sse/handlers/chatCore/clineResponseEnvelope.ts +25 -0
  601. package/open-sse/handlers/chatCore/codexFailover.ts +41 -0
  602. package/open-sse/handlers/chatCore/codexQuota.ts +85 -0
  603. package/open-sse/handlers/chatCore/comboContextCache.ts +63 -0
  604. package/open-sse/handlers/chatCore/compressionAnalyticsWrite.ts +149 -0
  605. package/open-sse/handlers/chatCore/compressionCacheStats.ts +53 -0
  606. package/open-sse/handlers/chatCore/compressionComboPredicates.ts +41 -0
  607. package/open-sse/handlers/chatCore/compressionSettings.ts +35 -0
  608. package/open-sse/handlers/chatCore/compressionUsageReceipt.ts +27 -0
  609. package/open-sse/handlers/chatCore/contextEditingTelemetry.ts +40 -0
  610. package/open-sse/handlers/chatCore/cooldownClassification.ts +26 -0
  611. package/open-sse/handlers/chatCore/executionCredentials.ts +72 -0
  612. package/open-sse/handlers/chatCore/executorClientHeaders.ts +36 -0
  613. package/open-sse/handlers/chatCore/executorHelpers.ts +151 -0
  614. package/open-sse/handlers/chatCore/executorProxy.ts +117 -0
  615. package/open-sse/handlers/chatCore/failureUsage.ts +41 -0
  616. package/open-sse/handlers/chatCore/gamificationEvent.ts +28 -0
  617. package/open-sse/handlers/chatCore/headers.ts +65 -0
  618. package/open-sse/handlers/chatCore/idempotency.ts +65 -0
  619. package/open-sse/handlers/chatCore/jsonBodyToSse.ts +161 -0
  620. package/open-sse/handlers/chatCore/keyHealth.ts +113 -0
  621. package/open-sse/handlers/chatCore/logTruncation.ts +93 -0
  622. package/open-sse/handlers/chatCore/memoryExtraction.ts +131 -0
  623. package/open-sse/handlers/chatCore/memorySkillsInjection.ts +165 -0
  624. package/open-sse/handlers/chatCore/nonStreamingJsonResponse.ts +16 -0
  625. package/open-sse/handlers/chatCore/nonStreamingResponseBody.ts +155 -0
  626. package/open-sse/handlers/chatCore/nonStreamingResponseHeaders.ts +46 -0
  627. package/open-sse/handlers/chatCore/nonStreamingResponseParse.ts +135 -0
  628. package/open-sse/handlers/chatCore/nonStreamingSse.ts +171 -0
  629. package/open-sse/handlers/chatCore/nonStreamingUsageStats.ts +90 -0
  630. package/open-sse/handlers/chatCore/outputStyleTelemetry.ts +53 -0
  631. package/open-sse/handlers/chatCore/passthroughHelpers.ts +83 -0
  632. package/open-sse/handlers/chatCore/passthroughToolNames.ts +65 -0
  633. package/open-sse/handlers/chatCore/pluginOnRequest.ts +65 -0
  634. package/open-sse/handlers/chatCore/pluginOnResponse.ts +34 -0
  635. package/open-sse/handlers/chatCore/postCallGuardrailContext.ts +47 -0
  636. package/open-sse/handlers/chatCore/quotaShareConsumption.ts +41 -0
  637. package/open-sse/handlers/chatCore/requestFormat.ts +111 -0
  638. package/open-sse/handlers/chatCore/requestSetup.ts +51 -0
  639. package/open-sse/handlers/chatCore/responseHeaders.ts +138 -0
  640. package/open-sse/handlers/chatCore/sanitization.ts +63 -0
  641. package/open-sse/handlers/chatCore/semanticCache.ts +98 -0
  642. package/open-sse/handlers/chatCore/semanticCacheStore.ts +73 -0
  643. package/open-sse/handlers/chatCore/serviceTier.ts +70 -0
  644. package/open-sse/handlers/chatCore/skillsFormat.ts +33 -0
  645. package/open-sse/handlers/chatCore/stageTrace.ts +30 -0
  646. package/open-sse/handlers/chatCore/streamErrorResult.ts +58 -0
  647. package/open-sse/handlers/chatCore/streamFinalize.ts +48 -0
  648. package/open-sse/handlers/chatCore/streamingCost.ts +37 -0
  649. package/open-sse/handlers/chatCore/streamingPipeline.ts +99 -0
  650. package/open-sse/handlers/chatCore/streamingQuotaShare.ts +54 -0
  651. package/open-sse/handlers/chatCore/streamingResponseHeaders.ts +39 -0
  652. package/open-sse/handlers/chatCore/streamingSemanticCacheStore.ts +95 -0
  653. package/open-sse/handlers/chatCore/streamingUsageStats.ts +79 -0
  654. package/open-sse/handlers/chatCore/targetFormat.ts +34 -0
  655. package/open-sse/handlers/chatCore/telemetryHelpers.ts +78 -0
  656. package/open-sse/handlers/chatCore/upstreamBody.ts +168 -0
  657. package/open-sse/handlers/chatCore/upstreamExecuteHeaders.ts +71 -0
  658. package/open-sse/handlers/chatCore/upstreamTimeouts.ts +158 -0
  659. package/open-sse/handlers/chatCore.ts +4452 -0
  660. package/open-sse/handlers/embeddings.ts +378 -0
  661. package/open-sse/handlers/imageGeneration/providers/chatgptWeb.ts +187 -0
  662. package/open-sse/handlers/imageGeneration/providers/comfyUI.ts +116 -0
  663. package/open-sse/handlers/imageGeneration/providers/haiper.ts +120 -0
  664. package/open-sse/handlers/imageGeneration/providers/huggingface.ts +90 -0
  665. package/open-sse/handlers/imageGeneration/providers/hyperbolic.ts +100 -0
  666. package/open-sse/handlers/imageGeneration/providers/ideogram.ts +96 -0
  667. package/open-sse/handlers/imageGeneration/providers/imagen3.ts +136 -0
  668. package/open-sse/handlers/imageGeneration/providers/leonardo.ts +140 -0
  669. package/open-sse/handlers/imageGeneration/providers/nvidiaNim.ts +286 -0
  670. package/open-sse/handlers/imageGeneration/providers/sdWebUI.ts +94 -0
  671. package/open-sse/handlers/imageGeneration.ts +2880 -0
  672. package/open-sse/handlers/moderations.ts +82 -0
  673. package/open-sse/handlers/musicGeneration.ts +640 -0
  674. package/open-sse/handlers/ocr.ts +79 -0
  675. package/open-sse/handlers/rerank.ts +210 -0
  676. package/open-sse/handlers/responseSanitizer/reasoning.ts +149 -0
  677. package/open-sse/handlers/responseSanitizer.ts +1086 -0
  678. package/open-sse/handlers/responseTranslator.ts +640 -0
  679. package/open-sse/handlers/responsesHandler.ts +92 -0
  680. package/open-sse/handlers/search.ts +1545 -0
  681. package/open-sse/handlers/sseParser.ts +825 -0
  682. package/open-sse/handlers/usageExtractor.ts +93 -0
  683. package/open-sse/handlers/videoGeneration/googleFlow.ts +219 -0
  684. package/open-sse/handlers/videoGeneration/googleFlowHandler.ts +145 -0
  685. package/open-sse/handlers/videoGeneration.ts +1264 -0
  686. package/open-sse/handlers/webFetch.ts +130 -0
  687. package/open-sse/index.ts +170 -0
  688. package/open-sse/lib/deepseek-pow-solver.cjs +3 -0
  689. package/open-sse/lib/deepseek-pow.ts +189 -0
  690. package/open-sse/lib/sha3_wasm_bg.wasm +0 -0
  691. package/open-sse/mcp-server/README.md +611 -0
  692. package/open-sse/mcp-server/audit.ts +478 -0
  693. package/open-sse/mcp-server/catalog.ts +290 -0
  694. package/open-sse/mcp-server/descriptionCompressor.ts +243 -0
  695. package/open-sse/mcp-server/httpAuthContext.ts +42 -0
  696. package/open-sse/mcp-server/httpTransport.ts +306 -0
  697. package/open-sse/mcp-server/index.ts +19 -0
  698. package/open-sse/mcp-server/mcpCallerIdentity.ts +53 -0
  699. package/open-sse/mcp-server/runtimeHeartbeat.ts +162 -0
  700. package/open-sse/mcp-server/schemas/a2a.ts +203 -0
  701. package/open-sse/mcp-server/schemas/audit.ts +121 -0
  702. package/open-sse/mcp-server/schemas/index.ts +116 -0
  703. package/open-sse/mcp-server/schemas/pickFastestModel.ts +110 -0
  704. package/open-sse/mcp-server/schemas/toolDefinition.ts +31 -0
  705. package/open-sse/mcp-server/schemas/toolSearch.ts +37 -0
  706. package/open-sse/mcp-server/schemas/tools.ts +1481 -0
  707. package/open-sse/mcp-server/scopeEnforcement.ts +135 -0
  708. package/open-sse/mcp-server/server.ts +1370 -0
  709. package/open-sse/mcp-server/toolCardinality.ts +254 -0
  710. package/open-sse/mcp-server/toolSearch/catalog.ts +98 -0
  711. package/open-sse/mcp-server/toolSearch/handler.ts +18 -0
  712. package/open-sse/mcp-server/toolSearch/index.ts +5 -0
  713. package/open-sse/mcp-server/toolSearch/register.ts +36 -0
  714. package/open-sse/mcp-server/toolSearch/search.ts +96 -0
  715. package/open-sse/mcp-server/toolSearch/signature.ts +92 -0
  716. package/open-sse/mcp-server/tools/advancedTools.ts +1119 -0
  717. package/open-sse/mcp-server/tools/agentSkillTools.ts +83 -0
  718. package/open-sse/mcp-server/tools/compressionTools.ts +451 -0
  719. package/open-sse/mcp-server/tools/gamificationTools.ts +148 -0
  720. package/open-sse/mcp-server/tools/githubSkillTools.ts +141 -0
  721. package/open-sse/mcp-server/tools/memoryTools.ts +137 -0
  722. package/open-sse/mcp-server/tools/notionTools.ts +106 -0
  723. package/open-sse/mcp-server/tools/obsidianTools.ts +327 -0
  724. package/open-sse/mcp-server/tools/pickFastestModel.ts +293 -0
  725. package/open-sse/mcp-server/tools/pluginTools.ts +216 -0
  726. package/open-sse/mcp-server/tools/poolTools.ts +205 -0
  727. package/open-sse/mcp-server/tools/skillTools.ts +119 -0
  728. package/open-sse/package.json +17 -0
  729. package/open-sse/services/AGENTS.md +78 -0
  730. package/open-sse/services/accountFallback.ts +1863 -0
  731. package/open-sse/services/accountSelector.ts +80 -0
  732. package/open-sse/services/accountSemaphore.ts +367 -0
  733. package/open-sse/services/antigravity429Engine.ts +178 -0
  734. package/open-sse/services/antigravityClientProfile.ts +167 -0
  735. package/open-sse/services/antigravityCredits.ts +68 -0
  736. package/open-sse/services/antigravityHeaderScrub.ts +75 -0
  737. package/open-sse/services/antigravityHeaders.ts +121 -0
  738. package/open-sse/services/antigravityIdentity.ts +127 -0
  739. package/open-sse/services/antigravityObfuscation.ts +64 -0
  740. package/open-sse/services/antigravityProjectBootstrap.ts +145 -0
  741. package/open-sse/services/antigravityQuotaFamily.ts +56 -0
  742. package/open-sse/services/antigravityVersion.ts +163 -0
  743. package/open-sse/services/apiKeyRotator.ts +385 -0
  744. package/open-sse/services/autoCombo/autoPrefix.ts +61 -0
  745. package/open-sse/services/autoCombo/builtinCatalog.ts +126 -0
  746. package/open-sse/services/autoCombo/complexityRouter.ts +111 -0
  747. package/open-sse/services/autoCombo/engine.ts +314 -0
  748. package/open-sse/services/autoCombo/index.ts +18 -0
  749. package/open-sse/services/autoCombo/modePacks.ts +105 -0
  750. package/open-sse/services/autoCombo/modelFamily.ts +95 -0
  751. package/open-sse/services/autoCombo/paidModelFilter.ts +44 -0
  752. package/open-sse/services/autoCombo/persistence.ts +124 -0
  753. package/open-sse/services/autoCombo/pipelineRouter.ts +418 -0
  754. package/open-sse/services/autoCombo/providerDiversity.ts +170 -0
  755. package/open-sse/services/autoCombo/providerRegistryAccessor.ts +9 -0
  756. package/open-sse/services/autoCombo/requestControls.ts +80 -0
  757. package/open-sse/services/autoCombo/routerStrategy.ts +375 -0
  758. package/open-sse/services/autoCombo/scoring.ts +242 -0
  759. package/open-sse/services/autoCombo/selfHealing.ts +167 -0
  760. package/open-sse/services/autoCombo/speedRanking.ts +327 -0
  761. package/open-sse/services/autoCombo/suffixComposition.ts +147 -0
  762. package/open-sse/services/autoCombo/taskFitness.ts +407 -0
  763. package/open-sse/services/autoCombo/virtualFactory.ts +446 -0
  764. package/open-sse/services/autoRefreshDaemon.ts +206 -0
  765. package/open-sse/services/backgroundTaskDetector.ts +263 -0
  766. package/open-sse/services/bailianQuotaFetcher.ts +333 -0
  767. package/open-sse/services/batchProcessor.ts +914 -0
  768. package/open-sse/services/bedrock.ts +160 -0
  769. package/open-sse/services/browserBackedChat.ts +849 -0
  770. package/open-sse/services/browserPool.ts +501 -0
  771. package/open-sse/services/ccBridgeTransforms.ts +581 -0
  772. package/open-sse/services/ccWireImageBuiltins.ts +26 -0
  773. package/open-sse/services/chatgptImageCache.ts +143 -0
  774. package/open-sse/services/chatgptTlsClient.ts +628 -0
  775. package/open-sse/services/claudeAdaptiveThinking.ts +52 -0
  776. package/open-sse/services/claudeCodeCCH.ts +49 -0
  777. package/open-sse/services/claudeCodeCompatible.ts +1198 -0
  778. package/open-sse/services/claudeCodeCompatibleBeta.ts +23 -0
  779. package/open-sse/services/claudeCodeCompatibleThinkingDisplay.ts +34 -0
  780. package/open-sse/services/claudeCodeConstraints.ts +144 -0
  781. package/open-sse/services/claudeCodeExtraRemap.ts +18 -0
  782. package/open-sse/services/claudeCodeFingerprint.ts +46 -0
  783. package/open-sse/services/claudeCodeObfuscation.ts +116 -0
  784. package/open-sse/services/claudeCodeToolRemapper.ts +339 -0
  785. package/open-sse/services/claudeHaikuConstraints.ts +88 -0
  786. package/open-sse/services/claudeTlsClient.ts +590 -0
  787. package/open-sse/services/claudeTurnstileSolver.ts +206 -0
  788. package/open-sse/services/claudeUsageCooldown.ts +51 -0
  789. package/open-sse/services/claudeWebAutoRefresh.ts +224 -0
  790. package/open-sse/services/clinepassModels.ts +76 -0
  791. package/open-sse/services/cloudCodeHeaders.ts +41 -0
  792. package/open-sse/services/cloudCodeThinking.ts +71 -0
  793. package/open-sse/services/codeAssistSubscription.ts +83 -0
  794. package/open-sse/services/codexQuotaFetcher.ts +523 -0
  795. package/open-sse/services/codexUsageQuotas.ts +270 -0
  796. package/open-sse/services/codexVerbosity.ts +59 -0
  797. package/open-sse/services/combo/applyStrategyOrdering.ts +226 -0
  798. package/open-sse/services/combo/autoConfig.ts +62 -0
  799. package/open-sse/services/combo/autoStrategy.ts +475 -0
  800. package/open-sse/services/combo/comboCompatFallback.ts +82 -0
  801. package/open-sse/services/combo/comboCooldownRetry.ts +237 -0
  802. package/open-sse/services/combo/comboData.ts +24 -0
  803. package/open-sse/services/combo/comboPredicates.ts +211 -0
  804. package/open-sse/services/combo/comboSetup.ts +135 -0
  805. package/open-sse/services/combo/comboStructure.ts +766 -0
  806. package/open-sse/services/combo/concurrencyCaps.ts +76 -0
  807. package/open-sse/services/combo/context.ts +46 -0
  808. package/open-sse/services/combo/fingerprintExpansion.ts +105 -0
  809. package/open-sse/services/combo/headroomRanking.ts +91 -0
  810. package/open-sse/services/combo/providerWildcard.ts +253 -0
  811. package/open-sse/services/combo/quotaExhaustionCutoff.ts +140 -0
  812. package/open-sse/services/combo/quotaScoring.ts +311 -0
  813. package/open-sse/services/combo/quotaShareConcurrency.ts +74 -0
  814. package/open-sse/services/combo/quotaShareInflight.ts +133 -0
  815. package/open-sse/services/combo/quotaShareStrategy.ts +349 -0
  816. package/open-sse/services/combo/quotaStrategies.ts +647 -0
  817. package/open-sse/services/combo/resolveAutoStrategy.ts +334 -0
  818. package/open-sse/services/combo/responseValidation.ts +206 -0
  819. package/open-sse/services/combo/rrState.ts +98 -0
  820. package/open-sse/services/combo/runtimeUnits.ts +269 -0
  821. package/open-sse/services/combo/sessionStickiness.ts +301 -0
  822. package/open-sse/services/combo/shadowRouting.ts +179 -0
  823. package/open-sse/services/combo/targetExhaustion.ts +160 -0
  824. package/open-sse/services/combo/targetSorters.ts +174 -0
  825. package/open-sse/services/combo/targetTimeoutRunner.ts +91 -0
  826. package/open-sse/services/combo/types.ts +175 -0
  827. package/open-sse/services/combo/validateQuality.ts +445 -0
  828. package/open-sse/services/combo.ts +3085 -0
  829. package/open-sse/services/comboAgentMiddleware.ts +214 -0
  830. package/open-sse/services/comboConfig.ts +248 -0
  831. package/open-sse/services/comboManifestMetrics.ts +13 -0
  832. package/open-sse/services/comboMetrics.ts +480 -0
  833. package/open-sse/services/compression/adaptiveCompression/computeTarget.ts +31 -0
  834. package/open-sse/services/compression/adaptiveCompression/ladder.ts +59 -0
  835. package/open-sse/services/compression/adaptiveCompression/resolveAdaptivePlan.ts +104 -0
  836. package/open-sse/services/compression/adaptiveCompression/types.ts +61 -0
  837. package/open-sse/services/compression/aggressive.ts +204 -0
  838. package/open-sse/services/compression/bodyAdapter.ts +354 -0
  839. package/open-sse/services/compression/cacheAwareConfig.ts +60 -0
  840. package/open-sse/services/compression/cachingAware.ts +130 -0
  841. package/open-sse/services/compression/caveman.ts +602 -0
  842. package/open-sse/services/compression/cavemanRules.ts +432 -0
  843. package/open-sse/services/compression/deriveDefaultPlan.ts +59 -0
  844. package/open-sse/services/compression/diffHelper.ts +219 -0
  845. package/open-sse/services/compression/engineBreakdown.ts +29 -0
  846. package/open-sse/services/compression/engineCatalog.ts +91 -0
  847. package/open-sse/services/compression/engines/cavemanAdapter.ts +454 -0
  848. package/open-sse/services/compression/engines/ccr/ccrQuery.ts +110 -0
  849. package/open-sse/services/compression/engines/ccr/index.ts +460 -0
  850. package/open-sse/services/compression/engines/headroom/encoderComparison.ts +72 -0
  851. package/open-sse/services/compression/engines/headroom/gcf/decode_generic.ts +711 -0
  852. package/open-sse/services/compression/engines/headroom/gcf/generic.ts +332 -0
  853. package/open-sse/services/compression/engines/headroom/gcf/index.ts +9 -0
  854. package/open-sse/services/compression/engines/headroom/gcf/scalar.ts +336 -0
  855. package/open-sse/services/compression/engines/headroom/index.ts +286 -0
  856. package/open-sse/services/compression/engines/headroom/smartcrusher.ts +255 -0
  857. package/open-sse/services/compression/engines/headroom/tabular.ts +263 -0
  858. package/open-sse/services/compression/engines/headroom/toon.ts +43 -0
  859. package/open-sse/services/compression/engines/index.ts +42 -0
  860. package/open-sse/services/compression/engines/ionizer/index.ts +124 -0
  861. package/open-sse/services/compression/engines/ionizer/sample.ts +200 -0
  862. package/open-sse/services/compression/engines/llm/index.ts +346 -0
  863. package/open-sse/services/compression/engines/llmlingua/constants.ts +55 -0
  864. package/open-sse/services/compression/engines/llmlingua/index.ts +474 -0
  865. package/open-sse/services/compression/engines/llmlingua/modelStore.ts +67 -0
  866. package/open-sse/services/compression/engines/llmlingua/onnxWorker.ts +117 -0
  867. package/open-sse/services/compression/engines/llmlingua/ultraEntry.ts +109 -0
  868. package/open-sse/services/compression/engines/llmlingua/worker.ts +373 -0
  869. package/open-sse/services/compression/engines/mcpAccessibility/collapseRepeated.ts +121 -0
  870. package/open-sse/services/compression/engines/mcpAccessibility/constants.ts +63 -0
  871. package/open-sse/services/compression/engines/mcpAccessibility/index.ts +52 -0
  872. package/open-sse/services/compression/engines/readLifecycle/index.ts +299 -0
  873. package/open-sse/services/compression/engines/registry.ts +87 -0
  874. package/open-sse/services/compression/engines/relevance/configSchema.ts +63 -0
  875. package/open-sse/services/compression/engines/relevance/index.ts +185 -0
  876. package/open-sse/services/compression/engines/relevance/scorer.ts +85 -0
  877. package/open-sse/services/compression/engines/rtk/codeStripper.ts +145 -0
  878. package/open-sse/services/compression/engines/rtk/commandDetector.ts +482 -0
  879. package/open-sse/services/compression/engines/rtk/configSchema.ts +117 -0
  880. package/open-sse/services/compression/engines/rtk/deduplicator.ts +37 -0
  881. package/open-sse/services/compression/engines/rtk/discover.ts +150 -0
  882. package/open-sse/services/compression/engines/rtk/filterLoader.ts +245 -0
  883. package/open-sse/services/compression/engines/rtk/filterSchema.ts +207 -0
  884. package/open-sse/services/compression/engines/rtk/filters/aws.json +34 -0
  885. package/open-sse/services/compression/engines/rtk/filters/biome.json +35 -0
  886. package/open-sse/services/compression/engines/rtk/filters/build-eslint.json +37 -0
  887. package/open-sse/services/compression/engines/rtk/filters/build-typescript.json +33 -0
  888. package/open-sse/services/compression/engines/rtk/filters/build-vite.json +41 -0
  889. package/open-sse/services/compression/engines/rtk/filters/build-webpack.json +34 -0
  890. package/open-sse/services/compression/engines/rtk/filters/bundle-install.json +35 -0
  891. package/open-sse/services/compression/engines/rtk/filters/composer.json +81 -0
  892. package/open-sse/services/compression/engines/rtk/filters/curl.json +34 -0
  893. package/open-sse/services/compression/engines/rtk/filters/df.json +34 -0
  894. package/open-sse/services/compression/engines/rtk/filters/docker-build.json +78 -0
  895. package/open-sse/services/compression/engines/rtk/filters/docker-logs.json +42 -0
  896. package/open-sse/services/compression/engines/rtk/filters/docker-ps.json +33 -0
  897. package/open-sse/services/compression/engines/rtk/filters/dotnet.json +47 -0
  898. package/open-sse/services/compression/engines/rtk/filters/du.json +33 -0
  899. package/open-sse/services/compression/engines/rtk/filters/error-stacktrace.json +41 -0
  900. package/open-sse/services/compression/engines/rtk/filters/gcloud.json +34 -0
  901. package/open-sse/services/compression/engines/rtk/filters/generic-output.json +32 -0
  902. package/open-sse/services/compression/engines/rtk/filters/gh.json +98 -0
  903. package/open-sse/services/compression/engines/rtk/filters/git-branch.json +45 -0
  904. package/open-sse/services/compression/engines/rtk/filters/git-diff.json +33 -0
  905. package/open-sse/services/compression/engines/rtk/filters/git-log.json +33 -0
  906. package/open-sse/services/compression/engines/rtk/filters/git-status.json +40 -0
  907. package/open-sse/services/compression/engines/rtk/filters/golangci-lint.json +34 -0
  908. package/open-sse/services/compression/engines/rtk/filters/gradle.json +47 -0
  909. package/open-sse/services/compression/engines/rtk/filters/json-output.json +40 -0
  910. package/open-sse/services/compression/engines/rtk/filters/kubectl.json +99 -0
  911. package/open-sse/services/compression/engines/rtk/filters/make.json +38 -0
  912. package/open-sse/services/compression/engines/rtk/filters/mypy.json +34 -0
  913. package/open-sse/services/compression/engines/rtk/filters/npm-audit.json +43 -0
  914. package/open-sse/services/compression/engines/rtk/filters/npm-install.json +41 -0
  915. package/open-sse/services/compression/engines/rtk/filters/nx.json +34 -0
  916. package/open-sse/services/compression/engines/rtk/filters/pip.json +41 -0
  917. package/open-sse/services/compression/engines/rtk/filters/playwright.json +42 -0
  918. package/open-sse/services/compression/engines/rtk/filters/poetry-install.json +35 -0
  919. package/open-sse/services/compression/engines/rtk/filters/prettier.json +40 -0
  920. package/open-sse/services/compression/engines/rtk/filters/ps.json +34 -0
  921. package/open-sse/services/compression/engines/rtk/filters/rsync.json +33 -0
  922. package/open-sse/services/compression/engines/rtk/filters/rubocop.json +34 -0
  923. package/open-sse/services/compression/engines/rtk/filters/ruff.json +40 -0
  924. package/open-sse/services/compression/engines/rtk/filters/shell-find.json +33 -0
  925. package/open-sse/services/compression/engines/rtk/filters/shell-grep.json +37 -0
  926. package/open-sse/services/compression/engines/rtk/filters/shell-ls.json +33 -0
  927. package/open-sse/services/compression/engines/rtk/filters/ssh.json +43 -0
  928. package/open-sse/services/compression/engines/rtk/filters/systemctl-status.json +43 -0
  929. package/open-sse/services/compression/engines/rtk/filters/terraform-plan.json +34 -0
  930. package/open-sse/services/compression/engines/rtk/filters/test-cargo.json +42 -0
  931. package/open-sse/services/compression/engines/rtk/filters/test-go.json +41 -0
  932. package/open-sse/services/compression/engines/rtk/filters/test-jest.json +43 -0
  933. package/open-sse/services/compression/engines/rtk/filters/test-pytest.json +41 -0
  934. package/open-sse/services/compression/engines/rtk/filters/test-vitest.json +43 -0
  935. package/open-sse/services/compression/engines/rtk/filters/tofu-plan.json +34 -0
  936. package/open-sse/services/compression/engines/rtk/filters/turbo.json +34 -0
  937. package/open-sse/services/compression/engines/rtk/filters/uv-sync.json +35 -0
  938. package/open-sse/services/compression/engines/rtk/filters/wget.json +34 -0
  939. package/open-sse/services/compression/engines/rtk/grouper.ts +99 -0
  940. package/open-sse/services/compression/engines/rtk/index.ts +706 -0
  941. package/open-sse/services/compression/engines/rtk/learn.ts +290 -0
  942. package/open-sse/services/compression/engines/rtk/lineFilter.ts +178 -0
  943. package/open-sse/services/compression/engines/rtk/rawOutput.ts +208 -0
  944. package/open-sse/services/compression/engines/rtk/renderers/gitDiff.ts +39 -0
  945. package/open-sse/services/compression/engines/rtk/renderers/index.ts +50 -0
  946. package/open-sse/services/compression/engines/rtk/renderers/structuredTable.ts +96 -0
  947. package/open-sse/services/compression/engines/rtk/renderers/terraformPlan.ts +40 -0
  948. package/open-sse/services/compression/engines/rtk/renderers/testGreen.ts +70 -0
  949. package/open-sse/services/compression/engines/rtk/renderers/types.ts +13 -0
  950. package/open-sse/services/compression/engines/rtk/smartTruncate.ts +67 -0
  951. package/open-sse/services/compression/engines/rtk/splitCompositeCommand.ts +111 -0
  952. package/open-sse/services/compression/engines/rtk/verify.ts +107 -0
  953. package/open-sse/services/compression/engines/session-dedup/fuzzy.ts +153 -0
  954. package/open-sse/services/compression/engines/session-dedup/index.ts +435 -0
  955. package/open-sse/services/compression/engines/types.ts +77 -0
  956. package/open-sse/services/compression/entrypointWrap.ts +43 -0
  957. package/open-sse/services/compression/eval/aggregate.ts +62 -0
  958. package/open-sse/services/compression/eval/corpus.ts +45 -0
  959. package/open-sse/services/compression/eval/costMeter.ts +31 -0
  960. package/open-sse/services/compression/eval/executorModelClient.ts +44 -0
  961. package/open-sse/services/compression/eval/fidelityCheck.ts +61 -0
  962. package/open-sse/services/compression/eval/grader.ts +27 -0
  963. package/open-sse/services/compression/eval/judge.ts +68 -0
  964. package/open-sse/services/compression/eval/report.ts +44 -0
  965. package/open-sse/services/compression/eval/runner.ts +135 -0
  966. package/open-sse/services/compression/eval/savings.ts +30 -0
  967. package/open-sse/services/compression/eval/seedCorpus.ts +60 -0
  968. package/open-sse/services/compression/eval/types.ts +65 -0
  969. package/open-sse/services/compression/fidelityGate.ts +124 -0
  970. package/open-sse/services/compression/fidelityGateStep.ts +44 -0
  971. package/open-sse/services/compression/hardBudget.ts +196 -0
  972. package/open-sse/services/compression/harness/benchmark.ts +318 -0
  973. package/open-sse/services/compression/harness/budgetGate.ts +62 -0
  974. package/open-sse/services/compression/harness/index.ts +52 -0
  975. package/open-sse/services/compression/harness/measure.ts +98 -0
  976. package/open-sse/services/compression/harness/replay.ts +72 -0
  977. package/open-sse/services/compression/harness/runner.ts +58 -0
  978. package/open-sse/services/compression/index.ts +165 -0
  979. package/open-sse/services/compression/languageDetector.ts +51 -0
  980. package/open-sse/services/compression/lite.ts +241 -0
  981. package/open-sse/services/compression/messageContent.ts +89 -0
  982. package/open-sse/services/compression/outputMode.ts +175 -0
  983. package/open-sse/services/compression/outputStyles/apply.ts +135 -0
  984. package/open-sse/services/compression/outputStyles/backCompat.ts +29 -0
  985. package/open-sse/services/compression/outputStyles/catalog.ts +76 -0
  986. package/open-sse/services/compression/outputStyles/telemetry.ts +50 -0
  987. package/open-sse/services/compression/pipelineEngineBreaker.ts +139 -0
  988. package/open-sse/services/compression/pipelineGuards.ts +45 -0
  989. package/open-sse/services/compression/planResolution.ts +128 -0
  990. package/open-sse/services/compression/prefixFreeze.ts +124 -0
  991. package/open-sse/services/compression/preservation.ts +0 -0
  992. package/open-sse/services/compression/preserveSystemPromptMode.ts +72 -0
  993. package/open-sse/services/compression/progressiveAging.ts +145 -0
  994. package/open-sse/services/compression/quantumLock/index.ts +17 -0
  995. package/open-sse/services/compression/quantumLock/quantumLock.ts +58 -0
  996. package/open-sse/services/compression/quantumLock/quantumLockStep.ts +72 -0
  997. package/open-sse/services/compression/quantumLock/quantumPatterns.ts +80 -0
  998. package/open-sse/services/compression/quantumLock/strategyWrap.ts +72 -0
  999. package/open-sse/services/compression/resolveCompressionPlan.ts +28 -0
  1000. package/open-sse/services/compression/resultMemo.ts +83 -0
  1001. package/open-sse/services/compression/riskGate/index.ts +3 -0
  1002. package/open-sse/services/compression/riskGate/riskGate.ts +136 -0
  1003. package/open-sse/services/compression/riskGate/riskGateStep.ts +115 -0
  1004. package/open-sse/services/compression/riskGate/riskPatterns.ts +61 -0
  1005. package/open-sse/services/compression/riskGate/strategyWrap.ts +44 -0
  1006. package/open-sse/services/compression/ruleLoader.ts +273 -0
  1007. package/open-sse/services/compression/rules/_schema.json +31 -0
  1008. package/open-sse/services/compression/rules/de/context.json +38 -0
  1009. package/open-sse/services/compression/rules/de/dedup.json +38 -0
  1010. package/open-sse/services/compression/rules/de/filler.json +70 -0
  1011. package/open-sse/services/compression/rules/de/structural.json +30 -0
  1012. package/open-sse/services/compression/rules/de/ultra.json +107 -0
  1013. package/open-sse/services/compression/rules/en/context.json +88 -0
  1014. package/open-sse/services/compression/rules/en/dedup.json +38 -0
  1015. package/open-sse/services/compression/rules/en/filler.json +129 -0
  1016. package/open-sse/services/compression/rules/en/structural.json +102 -0
  1017. package/open-sse/services/compression/rules/en/ultra.json +107 -0
  1018. package/open-sse/services/compression/rules/es/context.json +87 -0
  1019. package/open-sse/services/compression/rules/es/dedup.json +38 -0
  1020. package/open-sse/services/compression/rules/es/filler.json +110 -0
  1021. package/open-sse/services/compression/rules/es/structural.json +105 -0
  1022. package/open-sse/services/compression/rules/es/ultra.json +107 -0
  1023. package/open-sse/services/compression/rules/fr/context.json +38 -0
  1024. package/open-sse/services/compression/rules/fr/dedup.json +38 -0
  1025. package/open-sse/services/compression/rules/fr/filler.json +70 -0
  1026. package/open-sse/services/compression/rules/fr/structural.json +30 -0
  1027. package/open-sse/services/compression/rules/fr/ultra.json +107 -0
  1028. package/open-sse/services/compression/rules/id/context.json +113 -0
  1029. package/open-sse/services/compression/rules/id/dedup.json +38 -0
  1030. package/open-sse/services/compression/rules/id/filler.json +138 -0
  1031. package/open-sse/services/compression/rules/id/structural.json +111 -0
  1032. package/open-sse/services/compression/rules/id/ultra.json +252 -0
  1033. package/open-sse/services/compression/rules/ja/context.json +38 -0
  1034. package/open-sse/services/compression/rules/ja/dedup.json +38 -0
  1035. package/open-sse/services/compression/rules/ja/filler.json +70 -0
  1036. package/open-sse/services/compression/rules/ja/structural.json +30 -0
  1037. package/open-sse/services/compression/rules/ja/ultra.json +86 -0
  1038. package/open-sse/services/compression/rules/pt-BR/context.json +69 -0
  1039. package/open-sse/services/compression/rules/pt-BR/dedup.json +51 -0
  1040. package/open-sse/services/compression/rules/pt-BR/filler.json +151 -0
  1041. package/open-sse/services/compression/rules/pt-BR/structural.json +78 -0
  1042. package/open-sse/services/compression/rules/pt-BR/ultra.json +192 -0
  1043. package/open-sse/services/compression/rules/zh/dedup.json +38 -0
  1044. package/open-sse/services/compression/rules/zh/filler.json +54 -0
  1045. package/open-sse/services/compression/rules/zh/ultra.json +55 -0
  1046. package/open-sse/services/compression/stackedStepCore.ts +87 -0
  1047. package/open-sse/services/compression/stats.ts +59 -0
  1048. package/open-sse/services/compression/strategySelector.ts +1007 -0
  1049. package/open-sse/services/compression/summarizer.ts +244 -0
  1050. package/open-sse/services/compression/toolResultCompressor.ts +283 -0
  1051. package/open-sse/services/compression/types.ts +479 -0
  1052. package/open-sse/services/compression/ultra.ts +321 -0
  1053. package/open-sse/services/compression/ultraHeuristic.ts +157 -0
  1054. package/open-sse/services/compression/validation.ts +432 -0
  1055. package/open-sse/services/contextHandoff.ts +770 -0
  1056. package/open-sse/services/contextManager.ts +617 -0
  1057. package/open-sse/services/credentialGate.ts +84 -0
  1058. package/open-sse/services/crofUsageFetcher.ts +182 -0
  1059. package/open-sse/services/cursorSessionManager.ts +208 -0
  1060. package/open-sse/services/deepseekQuotaFetcher.ts +244 -0
  1061. package/open-sse/services/deviceTracker.ts +307 -0
  1062. package/open-sse/services/emergencyFallback.ts +162 -0
  1063. package/open-sse/services/errorClassifier.ts +198 -0
  1064. package/open-sse/services/evalRouting.ts +276 -0
  1065. package/open-sse/services/freeWebSearch.ts +154 -0
  1066. package/open-sse/services/fusion.ts +337 -0
  1067. package/open-sse/services/geminiRateLimitTracker.ts +145 -0
  1068. package/open-sse/services/geminiThoughtSignatureStore.ts +329 -0
  1069. package/open-sse/services/genericQuotaFetcher.ts +215 -0
  1070. package/open-sse/services/gigachatAuth.ts +113 -0
  1071. package/open-sse/services/githubCopilotModels.ts +162 -0
  1072. package/open-sse/services/gpt5SamplingGuard.ts +81 -0
  1073. package/open-sse/services/grokTlsClient.ts +607 -0
  1074. package/open-sse/services/hfModelSuggestions.ts +63 -0
  1075. package/open-sse/services/inAppLoginService.ts +256 -0
  1076. package/open-sse/services/intentClassifier.ts +665 -0
  1077. package/open-sse/services/ipFilter.ts +340 -0
  1078. package/open-sse/services/keyGroupAuth.ts +84 -0
  1079. package/open-sse/services/kiroModels.ts +195 -0
  1080. package/open-sse/services/manifestAdapter.ts +134 -0
  1081. package/open-sse/services/mimoThinking.ts +54 -0
  1082. package/open-sse/services/model.ts +738 -0
  1083. package/open-sse/services/modelCapabilities.ts +5 -0
  1084. package/open-sse/services/modelDeprecation.ts +173 -0
  1085. package/open-sse/services/modelFamilyFallback.ts +240 -0
  1086. package/open-sse/services/modelStrip.ts +60 -0
  1087. package/open-sse/services/modelscopePolicy.ts +97 -0
  1088. package/open-sse/services/opencodeOllamaUsage.ts +562 -0
  1089. package/open-sse/services/opencodeQuotaFetcher.ts +351 -0
  1090. package/open-sse/services/payloadRules.ts +474 -0
  1091. package/open-sse/services/perplexityTlsClient.ts +593 -0
  1092. package/open-sse/services/pipeline.ts +189 -0
  1093. package/open-sse/services/provider.ts +460 -0
  1094. package/open-sse/services/providerCooldownTracker.ts +198 -0
  1095. package/open-sse/services/providerCostData.ts +52 -0
  1096. package/open-sse/services/providerDefaultRateLimit.ts +94 -0
  1097. package/open-sse/services/providerRequestDefaults.ts +88 -0
  1098. package/open-sse/services/proxyAutoSelector.ts +58 -0
  1099. package/open-sse/services/qoderCli.ts +987 -0
  1100. package/open-sse/services/qoderCliResolve.ts +111 -0
  1101. package/open-sse/services/quotaFetchThrottle.ts +118 -0
  1102. package/open-sse/services/quotaMonitor.ts +377 -0
  1103. package/open-sse/services/quotaPreflight.ts +349 -0
  1104. package/open-sse/services/qwenThinking.ts +44 -0
  1105. package/open-sse/services/rateLimitManager/headers.ts +94 -0
  1106. package/open-sse/services/rateLimitManager.ts +945 -0
  1107. package/open-sse/services/rateLimitSemaphore.ts +231 -0
  1108. package/open-sse/services/reasoningCache.ts +514 -0
  1109. package/open-sse/services/reasoningTokenBuffer.ts +50 -0
  1110. package/open-sse/services/refreshSerializer.ts +131 -0
  1111. package/open-sse/services/requestDedup.ts +127 -0
  1112. package/open-sse/services/responseModelEcho.ts +79 -0
  1113. package/open-sse/services/responsesInputSanitizer.ts +145 -0
  1114. package/open-sse/services/retryAfterJson.ts +44 -0
  1115. package/open-sse/services/roleNormalizer.ts +283 -0
  1116. package/open-sse/services/searchCache.ts +150 -0
  1117. package/open-sse/services/sessionManager.ts +380 -0
  1118. package/open-sse/services/sessionPool/fingerprintRotator.ts +126 -0
  1119. package/open-sse/services/sessionPool/index.ts +28 -0
  1120. package/open-sse/services/sessionPool/poolRegistry.ts +93 -0
  1121. package/open-sse/services/sessionPool/session.ts +119 -0
  1122. package/open-sse/services/sessionPool/sessionFactory.ts +57 -0
  1123. package/open-sse/services/sessionPool/sessionPool.ts +326 -0
  1124. package/open-sse/services/sessionPool/types.ts +100 -0
  1125. package/open-sse/services/sessionPool/webExecutorWrapper.ts +132 -0
  1126. package/open-sse/services/signatureCache.ts +189 -0
  1127. package/open-sse/services/slidingWindowLimiter.ts +84 -0
  1128. package/open-sse/services/specificityDetector.ts +89 -0
  1129. package/open-sse/services/specificityRules.ts +257 -0
  1130. package/open-sse/services/specificityTypes.ts +43 -0
  1131. package/open-sse/services/streamRecovery.ts +545 -0
  1132. package/open-sse/services/systemPrompt.ts +187 -0
  1133. package/open-sse/services/systemTransforms.ts +532 -0
  1134. package/open-sse/services/taskAwareRouter.ts +326 -0
  1135. package/open-sse/services/taskAwareRouting.ts +553 -0
  1136. package/open-sse/services/thinkingBudget.ts +391 -0
  1137. package/open-sse/services/tierConfig.ts +124 -0
  1138. package/open-sse/services/tierDefaults.json +26 -0
  1139. package/open-sse/services/tierResolver.ts +144 -0
  1140. package/open-sse/services/tierTypes.ts +40 -0
  1141. package/open-sse/services/tlsClientProxy.ts +30 -0
  1142. package/open-sse/services/tokenExtractionConfig.ts +398 -0
  1143. package/open-sse/services/tokenLimitCounter.ts +342 -0
  1144. package/open-sse/services/tokenRefresh.ts +2180 -0
  1145. package/open-sse/services/toolLatencyTracker.ts +89 -0
  1146. package/open-sse/services/toolLimitDetector.ts +87 -0
  1147. package/open-sse/services/toolSchemaSanitizer.ts +165 -0
  1148. package/open-sse/services/usage/antigravity.ts +794 -0
  1149. package/open-sse/services/usage/claude.ts +216 -0
  1150. package/open-sse/services/usage/codebuddy-cn.ts +199 -0
  1151. package/open-sse/services/usage/codex.ts +75 -0
  1152. package/open-sse/services/usage/cursor.ts +161 -0
  1153. package/open-sse/services/usage/glm.ts +220 -0
  1154. package/open-sse/services/usage/kimi.ts +209 -0
  1155. package/open-sse/services/usage/kiro.ts +243 -0
  1156. package/open-sse/services/usage/minimax.ts +346 -0
  1157. package/open-sse/services/usage/quota.ts +85 -0
  1158. package/open-sse/services/usage/scalars.ts +75 -0
  1159. package/open-sse/services/usage.ts +1058 -0
  1160. package/open-sse/services/volumeDetector.ts +224 -0
  1161. package/open-sse/services/webSearchFallback.ts +246 -0
  1162. package/open-sse/services/webSearchRouting.ts +68 -0
  1163. package/open-sse/services/webSessionPoolHealth.ts +287 -0
  1164. package/open-sse/services/wildcardRouter.ts +136 -0
  1165. package/open-sse/services/workflowFSM.ts +340 -0
  1166. package/open-sse/shared/zedAuth.ts +535 -0
  1167. package/open-sse/transformer/responsesTransformer.ts +667 -0
  1168. package/open-sse/translator/bootstrap.ts +27 -0
  1169. package/open-sse/translator/deepseekWebTools.ts +486 -0
  1170. package/open-sse/translator/formats.ts +12 -0
  1171. package/open-sse/translator/helpers/claudeHelper.ts +563 -0
  1172. package/open-sse/translator/helpers/geminiHelper.ts +657 -0
  1173. package/open-sse/translator/helpers/geminiToolsSanitizer.ts +255 -0
  1174. package/open-sse/translator/helpers/jsonUtil.ts +18 -0
  1175. package/open-sse/translator/helpers/maxTokensHelper.ts +21 -0
  1176. package/open-sse/translator/helpers/openaiHelper.ts +244 -0
  1177. package/open-sse/translator/helpers/responsesApiHelper.ts +9 -0
  1178. package/open-sse/translator/helpers/schemaCoercion.ts +408 -0
  1179. package/open-sse/translator/helpers/toolCallHelper.ts +224 -0
  1180. package/open-sse/translator/helpers/toolCallShim.ts +113 -0
  1181. package/open-sse/translator/image/sizeMapper.ts +22 -0
  1182. package/open-sse/translator/index.ts +614 -0
  1183. package/open-sse/translator/paramSupport.ts +70 -0
  1184. package/open-sse/translator/registry.ts +41 -0
  1185. package/open-sse/translator/request/antigravity-to-openai.ts +357 -0
  1186. package/open-sse/translator/request/claude-to-gemini.ts +236 -0
  1187. package/open-sse/translator/request/claude-to-openai.ts +534 -0
  1188. package/open-sse/translator/request/gemini-to-openai.ts +193 -0
  1189. package/open-sse/translator/request/openai-responses/helpers.ts +69 -0
  1190. package/open-sse/translator/request/openai-responses/toResponses.ts +357 -0
  1191. package/open-sse/translator/request/openai-responses.ts +533 -0
  1192. package/open-sse/translator/request/openai-to-claude/thinkingBudget.ts +89 -0
  1193. package/open-sse/translator/request/openai-to-claude/toolResultAdjacency.ts +106 -0
  1194. package/open-sse/translator/request/openai-to-claude.ts +747 -0
  1195. package/open-sse/translator/request/openai-to-cursor.ts +226 -0
  1196. package/open-sse/translator/request/openai-to-gemini/helpers.ts +142 -0
  1197. package/open-sse/translator/request/openai-to-gemini.ts +753 -0
  1198. package/open-sse/translator/request/openai-to-kiro/messageHelpers.ts +109 -0
  1199. package/open-sse/translator/request/openai-to-kiro.ts +889 -0
  1200. package/open-sse/translator/response/claude-to-openai.ts +327 -0
  1201. package/open-sse/translator/response/cursor-to-openai.ts +30 -0
  1202. package/open-sse/translator/response/gemini-to-claude.ts +199 -0
  1203. package/open-sse/translator/response/gemini-to-openai.ts +765 -0
  1204. package/open-sse/translator/response/kiro-to-openai.ts +211 -0
  1205. package/open-sse/translator/response/openai-responses/pureHelpers.ts +92 -0
  1206. package/open-sse/translator/response/openai-responses.ts +1011 -0
  1207. package/open-sse/translator/response/openai-to-antigravity.ts +145 -0
  1208. package/open-sse/translator/response/openai-to-claude.ts +289 -0
  1209. package/open-sse/translator/response/openai-to-gemini-sse.ts +431 -0
  1210. package/open-sse/translator/webTools.ts +531 -0
  1211. package/open-sse/tsconfig.json +25 -0
  1212. package/open-sse/types.d.ts +139 -0
  1213. package/open-sse/utils/agentGoalPolicy.ts +112 -0
  1214. package/open-sse/utils/aiSdkCompat.ts +179 -0
  1215. package/open-sse/utils/anthropicHost.ts +25 -0
  1216. package/open-sse/utils/awsSigV4.ts +139 -0
  1217. package/open-sse/utils/bypassHandler.ts +300 -0
  1218. package/open-sse/utils/cacheControlPolicy.ts +374 -0
  1219. package/open-sse/utils/claudeCodeMetaRequests.ts +87 -0
  1220. package/open-sse/utils/clinepassEnvelope.ts +59 -0
  1221. package/open-sse/utils/comfyuiClient.ts +126 -0
  1222. package/open-sse/utils/composerToolCalls.ts +307 -0
  1223. package/open-sse/utils/cors.ts +13 -0
  1224. package/open-sse/utils/cursorAgentProtobuf/wire.ts +143 -0
  1225. package/open-sse/utils/cursorAgentProtobuf.ts +1400 -0
  1226. package/open-sse/utils/cursorChecksum.ts +139 -0
  1227. package/open-sse/utils/cursorImages.ts +354 -0
  1228. package/open-sse/utils/cursorVersionDetector.ts +74 -0
  1229. package/open-sse/utils/diagnostics.ts +288 -0
  1230. package/open-sse/utils/earlyStreamKeepalive.ts +228 -0
  1231. package/open-sse/utils/error.ts +515 -0
  1232. package/open-sse/utils/estimateSize.ts +35 -0
  1233. package/open-sse/utils/finishReason.ts +36 -0
  1234. package/open-sse/utils/flattenToolHistory.ts +116 -0
  1235. package/open-sse/utils/headers.ts +61 -0
  1236. package/open-sse/utils/heapPressure.ts +81 -0
  1237. package/open-sse/utils/jsonToSse.ts +127 -0
  1238. package/open-sse/utils/keepaliveThreshold.ts +62 -0
  1239. package/open-sse/utils/kieTask.ts +127 -0
  1240. package/open-sse/utils/kiroSanitizer.ts +127 -0
  1241. package/open-sse/utils/logger.ts +190 -0
  1242. package/open-sse/utils/networkProxy.ts +75 -0
  1243. package/open-sse/utils/noThinkingAlias.ts +153 -0
  1244. package/open-sse/utils/number.ts +4 -0
  1245. package/open-sse/utils/ollamaTransform.ts +122 -0
  1246. package/open-sse/utils/opencodeHeaders.ts +98 -0
  1247. package/open-sse/utils/passthroughTailProcessor.ts +299 -0
  1248. package/open-sse/utils/progressTracker.ts +112 -0
  1249. package/open-sse/utils/providerRequestLogging.ts +272 -0
  1250. package/open-sse/utils/proxyDispatcher.ts +507 -0
  1251. package/open-sse/utils/proxyDispatcherCache.ts +124 -0
  1252. package/open-sse/utils/proxyFallback.ts +418 -0
  1253. package/open-sse/utils/proxyFamily.ts +24 -0
  1254. package/open-sse/utils/proxyFamilyResolve.ts +39 -0
  1255. package/open-sse/utils/proxyFetch.ts +666 -0
  1256. package/open-sse/utils/publicCreds.ts +215 -0
  1257. package/open-sse/utils/reasoningContentInjector.ts +73 -0
  1258. package/open-sse/utils/reasoningFields.ts +72 -0
  1259. package/open-sse/utils/requestLogger.ts +386 -0
  1260. package/open-sse/utils/responsesInputNormalization.ts +94 -0
  1261. package/open-sse/utils/responsesStatePolicy.ts +75 -0
  1262. package/open-sse/utils/responsesStreamHelpers.ts +166 -0
  1263. package/open-sse/utils/setupPolyfill.ts +33 -0
  1264. package/open-sse/utils/sha3-512.ts +164 -0
  1265. package/open-sse/utils/sleep.ts +9 -0
  1266. package/open-sse/utils/socksConnectorWithFamily.ts +89 -0
  1267. package/open-sse/utils/sseHeartbeat.ts +119 -0
  1268. package/open-sse/utils/stream.ts +2791 -0
  1269. package/open-sse/utils/streamFailureFinalization.ts +174 -0
  1270. package/open-sse/utils/streamHandler.ts +680 -0
  1271. package/open-sse/utils/streamHelpers.ts +460 -0
  1272. package/open-sse/utils/streamPayloadCollector.ts +700 -0
  1273. package/open-sse/utils/streamReadiness.ts +385 -0
  1274. package/open-sse/utils/streamReadinessPolicy.ts +132 -0
  1275. package/open-sse/utils/textualToolCall.ts +112 -0
  1276. package/open-sse/utils/thinkCloseMarker.ts +77 -0
  1277. package/open-sse/utils/thinkTagParser.ts +146 -0
  1278. package/open-sse/utils/tlsClient.ts +243 -0
  1279. package/open-sse/utils/toolCallArguments.ts +32 -0
  1280. package/open-sse/utils/toolSources.ts +69 -0
  1281. package/open-sse/utils/upstreamResponseHeaders.ts +47 -0
  1282. package/open-sse/utils/urlSanitize.ts +24 -0
  1283. package/open-sse/utils/usageTracking.ts +596 -0
  1284. package/package.json +393 -0
  1285. package/scripts/build/build-next-isolated.mjs +322 -0
  1286. package/scripts/build/colocateOptionals.mjs +144 -0
  1287. package/scripts/build/native-binary-compat.mjs +167 -0
  1288. package/scripts/build/postinstall.mjs +357 -0
  1289. package/scripts/build/postinstallSupport.mjs +45 -0
  1290. package/scripts/build/runtime-env.mjs +140 -0
  1291. package/scripts/build/sync-env.mjs +3 -0
  1292. package/scripts/check/check-supported-node-runtime.ts +20 -0
  1293. package/scripts/dev/responses-ws-proxy.mjs +907 -0
  1294. package/scripts/dev/sync-env.mjs +362 -0
  1295. package/scripts/dev/tls-options.mjs +92 -0
  1296. package/scripts/postinstall.mjs +27 -0
  1297. package/src/domain/assessment/assessor.ts +206 -0
  1298. package/src/domain/assessment/categorizer.ts +118 -0
  1299. package/src/domain/assessment/index.ts +24 -0
  1300. package/src/domain/assessment/migration.ts +111 -0
  1301. package/src/domain/assessment/selfHealer.ts +261 -0
  1302. package/src/domain/assessment/types.ts +361 -0
  1303. package/src/domain/comboResolver.ts +106 -0
  1304. package/src/domain/configAudit.ts +285 -0
  1305. package/src/domain/connectionModelRules.ts +82 -0
  1306. package/src/domain/costRules.ts +631 -0
  1307. package/src/domain/degradation.ts +253 -0
  1308. package/src/domain/fallbackPolicy.ts +160 -0
  1309. package/src/domain/lockoutPolicy.ts +208 -0
  1310. package/src/domain/modelAvailability.ts +41 -0
  1311. package/src/domain/omnirouteResponseMeta.ts +202 -0
  1312. package/src/domain/pipeline.ts +307 -0
  1313. package/src/domain/policyEngine.ts +195 -0
  1314. package/src/domain/prompts.ts +103 -0
  1315. package/src/domain/providerExpiration.ts +255 -0
  1316. package/src/domain/quotaCache.ts +553 -0
  1317. package/src/domain/responses.ts +139 -0
  1318. package/src/domain/tagRouter.ts +64 -0
  1319. package/src/domain/types.ts +123 -0
  1320. package/src/lib/a2a/README.md +748 -0
  1321. package/src/lib/a2a/routingLogger.ts +67 -0
  1322. package/src/lib/a2a/skills/costAnalysis.ts +162 -0
  1323. package/src/lib/a2a/skills/healthReport.ts +155 -0
  1324. package/src/lib/a2a/skills/listCapabilities.ts +72 -0
  1325. package/src/lib/a2a/skills/providerDiscovery.ts +202 -0
  1326. package/src/lib/a2a/skills/quotaManagement.ts +121 -0
  1327. package/src/lib/a2a/skills/smartRouting.ts +89 -0
  1328. package/src/lib/a2a/streaming.ts +149 -0
  1329. package/src/lib/a2a/taskExecution.ts +64 -0
  1330. package/src/lib/a2a/taskManager.ts +240 -0
  1331. package/src/lib/accessTokens/scopes.ts +51 -0
  1332. package/src/lib/acp/index.ts +11 -0
  1333. package/src/lib/acp/manager.ts +202 -0
  1334. package/src/lib/acp/registry.ts +384 -0
  1335. package/src/lib/agentSkills/catalog.ts +256 -0
  1336. package/src/lib/agentSkills/cliRegistryParser.ts +242 -0
  1337. package/src/lib/agentSkills/generator.ts +367 -0
  1338. package/src/lib/agentSkills/openapiParser.ts +201 -0
  1339. package/src/lib/agentSkills/schemas.ts +36 -0
  1340. package/src/lib/agentSkills/types.ts +101 -0
  1341. package/src/lib/api/comboErrorResponse.ts +80 -0
  1342. package/src/lib/api/errorResponse.ts +54 -0
  1343. package/src/lib/api/modelTestRunner.ts +390 -0
  1344. package/src/lib/api/proxyRegistryRouteHandlers.ts +142 -0
  1345. package/src/lib/api/requireCliToolsAuth.ts +5 -0
  1346. package/src/lib/api/requireManagementAuth.ts +118 -0
  1347. package/src/lib/api/serverErrorMessage.ts +36 -0
  1348. package/src/lib/apiBridgeServer.ts +233 -0
  1349. package/src/lib/apiKeyExposure.ts +19 -0
  1350. package/src/lib/arenaEloSync.ts +564 -0
  1351. package/src/lib/audit/activityIcons.ts +69 -0
  1352. package/src/lib/audit/highLevelActions.ts +57 -0
  1353. package/src/lib/audit/timeline.ts +132 -0
  1354. package/src/lib/auth/managementPassword.ts +117 -0
  1355. package/src/lib/batches/costEstimator.ts +130 -0
  1356. package/src/lib/batches/csvToJsonl.ts +248 -0
  1357. package/src/lib/batches/dispatch.ts +53 -0
  1358. package/src/lib/batches/retryFailed.ts +77 -0
  1359. package/src/lib/batches/schemas.ts +38 -0
  1360. package/src/lib/batches/types.ts +78 -0
  1361. package/src/lib/batches/validateJsonl.ts +154 -0
  1362. package/src/lib/benchmarks.ts +33 -0
  1363. package/src/lib/build-profile/featureDisabled.ts +23 -0
  1364. package/src/lib/cacheControlSettings.ts +25 -0
  1365. package/src/lib/cacheLayer.ts +220 -0
  1366. package/src/lib/catalog/openrouterCatalog.ts +177 -0
  1367. package/src/lib/cli-helper/claudeProfileAutoSync.ts +92 -0
  1368. package/src/lib/cli-helper/codexProfileAutoSync.ts +80 -0
  1369. package/src/lib/cli-helper/config-generator/claude.ts +25 -0
  1370. package/src/lib/cli-helper/config-generator/cline.ts +23 -0
  1371. package/src/lib/cli-helper/config-generator/codex.ts +34 -0
  1372. package/src/lib/cli-helper/config-generator/continue.ts +37 -0
  1373. package/src/lib/cli-helper/config-generator/hermes-agent.ts +210 -0
  1374. package/src/lib/cli-helper/config-generator/hermes.ts +47 -0
  1375. package/src/lib/cli-helper/config-generator/hermesHome.ts +40 -0
  1376. package/src/lib/cli-helper/config-generator/index.ts +124 -0
  1377. package/src/lib/cli-helper/config-generator/kilocode.ts +23 -0
  1378. package/src/lib/cli-helper/config-generator/opencode.ts +443 -0
  1379. package/src/lib/cli-helper/doctor/checks.ts +41 -0
  1380. package/src/lib/cli-helper/log-streamer.ts +78 -0
  1381. package/src/lib/cli-helper/tool-detector.ts +165 -0
  1382. package/src/lib/cliTools/batchStatusCache.ts +47 -0
  1383. package/src/lib/cliTools/checkToolConfigStatus.ts +112 -0
  1384. package/src/lib/cloudAgent/agents/codex.ts +148 -0
  1385. package/src/lib/cloudAgent/agents/cursor.ts +205 -0
  1386. package/src/lib/cloudAgent/agents/devin.ts +137 -0
  1387. package/src/lib/cloudAgent/agents/jules.ts +354 -0
  1388. package/src/lib/cloudAgent/api.ts +86 -0
  1389. package/src/lib/cloudAgent/baseAgent.ts +98 -0
  1390. package/src/lib/cloudAgent/credentials.ts +89 -0
  1391. package/src/lib/cloudAgent/db.ts +145 -0
  1392. package/src/lib/cloudAgent/index.ts +8 -0
  1393. package/src/lib/cloudAgent/julesApi.ts +7 -0
  1394. package/src/lib/cloudAgent/registry.ts +29 -0
  1395. package/src/lib/cloudAgent/types.ts +90 -0
  1396. package/src/lib/cloudSync.stub.ts +31 -0
  1397. package/src/lib/cloudSync.ts +210 -0
  1398. package/src/lib/cloudflaredTunnel.ts +933 -0
  1399. package/src/lib/combos/autoPromote.ts +92 -0
  1400. package/src/lib/combos/builderDraft.ts +242 -0
  1401. package/src/lib/combos/builderOptions.ts +681 -0
  1402. package/src/lib/combos/compositeTiers.ts +200 -0
  1403. package/src/lib/combos/controlCenter.ts +271 -0
  1404. package/src/lib/combos/intelligentRouting.ts +192 -0
  1405. package/src/lib/combos/steps.ts +322 -0
  1406. package/src/lib/combos/testHealth.ts +190 -0
  1407. package/src/lib/compliance/index.ts +637 -0
  1408. package/src/lib/compliance/noLog.ts +86 -0
  1409. package/src/lib/compliance/providerAudit.ts +98 -0
  1410. package/src/lib/compression/judgeModelClient.ts +43 -0
  1411. package/src/lib/config/hotReload.ts +115 -0
  1412. package/src/lib/config/runtimeSettings.ts +551 -0
  1413. package/src/lib/consoleInterceptor.ts +136 -0
  1414. package/src/lib/container.ts +122 -0
  1415. package/src/lib/contextWindowResolver.ts +147 -0
  1416. package/src/lib/copilot/codegraphKnowledge.ts +229 -0
  1417. package/src/lib/copilot/engine.ts +372 -0
  1418. package/src/lib/copilot/systemPrompt.ts +189 -0
  1419. package/src/lib/copilot/tools.ts +415 -0
  1420. package/src/lib/credentialHealth/cache.ts +206 -0
  1421. package/src/lib/credentialHealth/scheduler.ts +328 -0
  1422. package/src/lib/dataPaths.ts +122 -0
  1423. package/src/lib/db/AGENTS.md +70 -0
  1424. package/src/lib/db/_rowTypes.ts +45 -0
  1425. package/src/lib/db/accessTokens.ts +183 -0
  1426. package/src/lib/db/adapters/betterSqliteAdapter.ts +58 -0
  1427. package/src/lib/db/adapters/driverFactory.ts +98 -0
  1428. package/src/lib/db/adapters/nodeSqliteAdapter.ts +60 -0
  1429. package/src/lib/db/adapters/nodeSqliteShared.ts +148 -0
  1430. package/src/lib/db/adapters/sqljsAdapter.ts +232 -0
  1431. package/src/lib/db/adapters/types.ts +34 -0
  1432. package/src/lib/db/agentBridgeBypass.ts +81 -0
  1433. package/src/lib/db/agentBridgeMappings.ts +47 -0
  1434. package/src/lib/db/agentBridgeState.ts +115 -0
  1435. package/src/lib/db/apiKeyColumnFallbacks.ts +47 -0
  1436. package/src/lib/db/apiKeyContextSources.ts +107 -0
  1437. package/src/lib/db/apiKeyGroups.ts +318 -0
  1438. package/src/lib/db/apiKeyUsageLimitFields.ts +65 -0
  1439. package/src/lib/db/apiKeys/modelPermissions.ts +122 -0
  1440. package/src/lib/db/apiKeys/rowParsers.ts +161 -0
  1441. package/src/lib/db/apiKeys/types.ts +21 -0
  1442. package/src/lib/db/apiKeys.ts +1492 -0
  1443. package/src/lib/db/backup.ts +708 -0
  1444. package/src/lib/db/batches.ts +450 -0
  1445. package/src/lib/db/callLogStats.ts +235 -0
  1446. package/src/lib/db/caseMapping.ts +80 -0
  1447. package/src/lib/db/cleanup.ts +584 -0
  1448. package/src/lib/db/cliToolState.ts +159 -0
  1449. package/src/lib/db/comboForecast.ts +119 -0
  1450. package/src/lib/db/combos.ts +339 -0
  1451. package/src/lib/db/commandCodeAuth.ts +209 -0
  1452. package/src/lib/db/compression.ts +780 -0
  1453. package/src/lib/db/compressionAnalytics.ts +661 -0
  1454. package/src/lib/db/compressionCacheStats.ts +112 -0
  1455. package/src/lib/db/compressionCombos.ts +491 -0
  1456. package/src/lib/db/compressionRunTelemetry.ts +126 -0
  1457. package/src/lib/db/contextHandoffs.ts +233 -0
  1458. package/src/lib/db/core.ts +1520 -0
  1459. package/src/lib/db/creditBalance.ts +92 -0
  1460. package/src/lib/db/databaseSettings.ts +309 -0
  1461. package/src/lib/db/detailedLogs.ts +170 -0
  1462. package/src/lib/db/discovery.ts +97 -0
  1463. package/src/lib/db/discoveryResults.ts +176 -0
  1464. package/src/lib/db/domainState.ts +630 -0
  1465. package/src/lib/db/encryption.ts +327 -0
  1466. package/src/lib/db/evals.ts +786 -0
  1467. package/src/lib/db/featureFlags.ts +82 -0
  1468. package/src/lib/db/files.ts +170 -0
  1469. package/src/lib/db/freeProxies.ts +360 -0
  1470. package/src/lib/db/gamification.ts +613 -0
  1471. package/src/lib/db/healthCheck.ts +565 -0
  1472. package/src/lib/db/inspectorCustomHosts.ts +88 -0
  1473. package/src/lib/db/inspectorSessions.ts +161 -0
  1474. package/src/lib/db/jsonMigration.ts +321 -0
  1475. package/src/lib/db/memoryVec.ts +138 -0
  1476. package/src/lib/db/middleware.ts +239 -0
  1477. package/src/lib/db/migrationRunner/constants.ts +118 -0
  1478. package/src/lib/db/migrationRunner.ts +1069 -0
  1479. package/src/lib/db/migrations/001_initial_schema.sql +226 -0
  1480. package/src/lib/db/migrations/002_mcp_a2a_tables.sql +95 -0
  1481. package/src/lib/db/migrations/003_provider_node_custom_paths.sql +5 -0
  1482. package/src/lib/db/migrations/004_proxy_registry.sql +31 -0
  1483. package/src/lib/db/migrations/005_combo_agent_fields.sql +19 -0
  1484. package/src/lib/db/migrations/006_detailed_request_logs.sql +42 -0
  1485. package/src/lib/db/migrations/007_search_request_type.sql +4 -0
  1486. package/src/lib/db/migrations/008_registered_keys.sql +65 -0
  1487. package/src/lib/db/migrations/009_requested_model.sql +9 -0
  1488. package/src/lib/db/migrations/010_model_combo_mappings.sql +19 -0
  1489. package/src/lib/db/migrations/011_webhooks.sql +15 -0
  1490. package/src/lib/db/migrations/012_fix_token_input_cache_tokens.sql +15 -0
  1491. package/src/lib/db/migrations/013_quota_snapshots.sql +19 -0
  1492. package/src/lib/db/migrations/014_unified_log_artifacts.sql +15 -0
  1493. package/src/lib/db/migrations/015_create_memories.sql +22 -0
  1494. package/src/lib/db/migrations/016_create_skills.sql +37 -0
  1495. package/src/lib/db/migrations/017_version_manager_upstream_proxy.sql +56 -0
  1496. package/src/lib/db/migrations/018_call_logs_detailed_tokens.sql +6 -0
  1497. package/src/lib/db/migrations/019_context_handoffs.sql +28 -0
  1498. package/src/lib/db/migrations/020_combo_sort_order.sql +16 -0
  1499. package/src/lib/db/migrations/021_combo_call_log_targets.sql +5 -0
  1500. package/src/lib/db/migrations/022_add_memory_fts5.sql +33 -0
  1501. package/src/lib/db/migrations/023_fix_memory_fts_uuid.sql +55 -0
  1502. package/src/lib/db/migrations/024_create_sync_tokens.sql +15 -0
  1503. package/src/lib/db/migrations/025_call_logs_summary_storage.sql +145 -0
  1504. package/src/lib/db/migrations/027_skill_mode_and_metadata.sql +10 -0
  1505. package/src/lib/db/migrations/028_create_files_and_batches.sql +51 -0
  1506. package/src/lib/db/migrations/029_provider_connection_max_concurrent.sql +10 -0
  1507. package/src/lib/db/migrations/030_create_eval_runs.sql +28 -0
  1508. package/src/lib/db/migrations/031_create_eval_suites.sql +27 -0
  1509. package/src/lib/db/migrations/032_apikey_lifecycle.sql +24 -0
  1510. package/src/lib/db/migrations/033_create_reasoning_cache.sql +27 -0
  1511. package/src/lib/db/migrations/034_compression_settings.sql +10 -0
  1512. package/src/lib/db/migrations/035_standard_compression_config.sql +9 -0
  1513. package/src/lib/db/migrations/036_aggressive_compression.sql +4 -0
  1514. package/src/lib/db/migrations/037_ultra_compression.sql +6 -0
  1515. package/src/lib/db/migrations/038_compression_analytics.sql +13 -0
  1516. package/src/lib/db/migrations/039_compression_cache_stats.sql +15 -0
  1517. package/src/lib/db/migrations/040_oneproxy_proxy_fields.sql +24 -0
  1518. package/src/lib/db/migrations/041_compression_receipts.sql +18 -0
  1519. package/src/lib/db/migrations/042_compression_combos.sql +43 -0
  1520. package/src/lib/db/migrations/043_default_compression_combo_pipeline.sql +12 -0
  1521. package/src/lib/db/migrations/044_usage_history_api_key_backfill.sql +27 -0
  1522. package/src/lib/db/migrations/045_compression_tokens.sql +4 -0
  1523. package/src/lib/db/migrations/046_database_settings.sql +44 -0
  1524. package/src/lib/db/migrations/047_aggregation_tables.sql +44 -0
  1525. package/src/lib/db/migrations/048_summary_indexes.sql +29 -0
  1526. package/src/lib/db/migrations/049_compression_analytics_indexes.sql +10 -0
  1527. package/src/lib/db/migrations/050_session_account_affinity.sql +11 -0
  1528. package/src/lib/db/migrations/051_hot_path_db_indexes.sql +10 -0
  1529. package/src/lib/db/migrations/052_api_key_combo_throttle.sql +4 -0
  1530. package/src/lib/db/migrations/053_remove_status_from_files.sql +2 -0
  1531. package/src/lib/db/migrations/054_usage_history_service_tier.sql +4 -0
  1532. package/src/lib/db/migrations/056_mcp_accessibility_compression.sql +8 -0
  1533. package/src/lib/db/migrations/057_provider_connection_quota_window_thresholds.sql +14 -0
  1534. package/src/lib/db/migrations/058_command_code_auth_sessions.sql +19 -0
  1535. package/src/lib/db/migrations/059_manifest_routing.sql +21 -0
  1536. package/src/lib/db/migrations/060_create_gamification.sql +94 -0
  1537. package/src/lib/db/migrations/061_cloud_agent_credentials.sql +9 -0
  1538. package/src/lib/db/migrations/062_usage_history_combo_strategy.sql +4 -0
  1539. package/src/lib/db/migrations/063_add_last_model_to_handoffs.sql +7 -0
  1540. package/src/lib/db/migrations/064_create_session_model_history.sql +19 -0
  1541. package/src/lib/db/migrations/065_middleware_hooks.sql +45 -0
  1542. package/src/lib/db/migrations/066_api_key_groups.sql +47 -0
  1543. package/src/lib/db/migrations/067_relay_proxies.sql +56 -0
  1544. package/src/lib/db/migrations/068_free_proxies.sql +52 -0
  1545. package/src/lib/db/migrations/069_webhook_deliveries.sql +15 -0
  1546. package/src/lib/db/migrations/070_webhooks_kind_metadata.sql +3 -0
  1547. package/src/lib/db/migrations/071_services.sql +19 -0
  1548. package/src/lib/db/migrations/072_free_proxies_fk.sql +27 -0
  1549. package/src/lib/db/migrations/073_per_model_token_limits.sql +61 -0
  1550. package/src/lib/db/migrations/074_discovery_results.sql +20 -0
  1551. package/src/lib/db/migrations/075_api_key_self_service_usage_scopes.sql +51 -0
  1552. package/src/lib/db/migrations/076_create_plugins.sql +31 -0
  1553. package/src/lib/db/migrations/077_api_key_stream_default_mode.sql +3 -0
  1554. package/src/lib/db/migrations/078_quota_consumption.sql +24 -0
  1555. package/src/lib/db/migrations/079_provider_plans.sql +19 -0
  1556. package/src/lib/db/migrations/080_agent_bridge.sql +24 -0
  1557. package/src/lib/db/migrations/081_inspector_custom_hosts.sql +11 -0
  1558. package/src/lib/db/migrations/082_inspector_sessions.sql +18 -0
  1559. package/src/lib/db/migrations/083_memory_vec.sql +26 -0
  1560. package/src/lib/db/migrations/084_playground_presets.sql +15 -0
  1561. package/src/lib/db/migrations/085_quota_pools.sql +39 -0
  1562. package/src/lib/db/migrations/086_api_key_allowed_quotas.sql +8 -0
  1563. package/src/lib/db/migrations/087_quota_pool_connections.sql +21 -0
  1564. package/src/lib/db/migrations/088_quota_groups.sql +28 -0
  1565. package/src/lib/db/migrations/089_add_disable_non_public_to_api_keys.sql +3 -0
  1566. package/src/lib/db/migrations/090_plugin_metrics.sql +9 -0
  1567. package/src/lib/db/migrations/091_plugin_analytics.sql +23 -0
  1568. package/src/lib/db/migrations/092_api_key_context_sources.sql +13 -0
  1569. package/src/lib/db/migrations/093_proxy_enable_toggles.sql +17 -0
  1570. package/src/lib/db/migrations/094_per_key_proxy_toggles.sql +12 -0
  1571. package/src/lib/db/migrations/095_provider_node_custom_headers.sql +5 -0
  1572. package/src/lib/db/migrations/096_sync_context_cache_protection.sql +9 -0
  1573. package/src/lib/db/migrations/097_model_intelligence.sql +25 -0
  1574. package/src/lib/db/migrations/098_clear_semantic_cache_for_key_isolation.sql +4 -0
  1575. package/src/lib/db/migrations/099_proxy_family.sql +5 -0
  1576. package/src/lib/db/migrations/100_cli_access_tokens.sql +18 -0
  1577. package/src/lib/db/migrations/101_api_key_usage_limits.sql +4 -0
  1578. package/src/lib/db/migrations/102_compression_engines_map.sql +5 -0
  1579. package/src/lib/db/migrations/103_strip_legacy_combo_config_keys.sql +54 -0
  1580. package/src/lib/db/migrations/104_normalize_database_cache_size.sql +10 -0
  1581. package/src/lib/db/migrations/105_usage_history_endpoint.sql +6 -0
  1582. package/src/lib/db/migrations/106_quota_allocation_model_caps.sql +32 -0
  1583. package/src/lib/db/migrations/107_quota_combos_quota_share_strategy.sql +25 -0
  1584. package/src/lib/db/migrations/108_provider_quota_reset_events.sql +26 -0
  1585. package/src/lib/db/migrations/109_call_logs_correlation_id.sql +2 -0
  1586. package/src/lib/db/migrations/110_model_context_overrides.sql +17 -0
  1587. package/src/lib/db/migrations/111_memory_typed_decay.sql +10 -0
  1588. package/src/lib/db/migrations/112_batch_item_checkpoints.sql +18 -0
  1589. package/src/lib/db/migrations/113_provider_node_icon_url.sql +5 -0
  1590. package/src/lib/db/migrations/114_mux_service_seed.sql +12 -0
  1591. package/src/lib/db/migrations/115_bifrost_service.sql +9 -0
  1592. package/src/lib/db/migrations/116_call_logs_reasoning_source.sql +13 -0
  1593. package/src/lib/db/migrations/117_proxy_pool_rotation.sql +53 -0
  1594. package/src/lib/db/modelComboMappings.ts +255 -0
  1595. package/src/lib/db/modelContextOverrides.ts +133 -0
  1596. package/src/lib/db/modelIntelligence.ts +232 -0
  1597. package/src/lib/db/models/aliases.ts +61 -0
  1598. package/src/lib/db/models/compat.ts +249 -0
  1599. package/src/lib/db/models/mitmAlias.ts +32 -0
  1600. package/src/lib/db/models/shared.ts +19 -0
  1601. package/src/lib/db/models.ts +936 -0
  1602. package/src/lib/db/notion.ts +48 -0
  1603. package/src/lib/db/obsidian.ts +283 -0
  1604. package/src/lib/db/oneproxy.ts +293 -0
  1605. package/src/lib/db/optimizationSettings.ts +284 -0
  1606. package/src/lib/db/playgroundPresets.ts +167 -0
  1607. package/src/lib/db/pluginMetrics.ts +88 -0
  1608. package/src/lib/db/plugins.ts +280 -0
  1609. package/src/lib/db/prompts.ts +302 -0
  1610. package/src/lib/db/providerLimits.ts +131 -0
  1611. package/src/lib/db/providerNodeSelect.ts +48 -0
  1612. package/src/lib/db/providerPlans.ts +149 -0
  1613. package/src/lib/db/providerStats.ts +68 -0
  1614. package/src/lib/db/providers/columns.ts +116 -0
  1615. package/src/lib/db/providers/nodes.ts +169 -0
  1616. package/src/lib/db/providers/rateLimit.ts +198 -0
  1617. package/src/lib/db/providers.ts +803 -0
  1618. package/src/lib/db/proxies/mappers.ts +181 -0
  1619. package/src/lib/db/proxies/types.ts +78 -0
  1620. package/src/lib/db/proxies.ts +1176 -0
  1621. package/src/lib/db/proxyLogs.ts +35 -0
  1622. package/src/lib/db/quotaConsumption.ts +274 -0
  1623. package/src/lib/db/quotaGroups.ts +147 -0
  1624. package/src/lib/db/quotaModelCaps.ts +128 -0
  1625. package/src/lib/db/quotaPools.ts +548 -0
  1626. package/src/lib/db/quotaResetEvents.ts +334 -0
  1627. package/src/lib/db/quotaSnapshots.ts +209 -0
  1628. package/src/lib/db/readCache.ts +202 -0
  1629. package/src/lib/db/reasoningCache.ts +276 -0
  1630. package/src/lib/db/recovery.ts +33 -0
  1631. package/src/lib/db/registeredKeys.ts +532 -0
  1632. package/src/lib/db/relayProxies.ts +364 -0
  1633. package/src/lib/db/schemaColumns.ts +226 -0
  1634. package/src/lib/db/secrets.ts +28 -0
  1635. package/src/lib/db/semanticCache.ts +117 -0
  1636. package/src/lib/db/serviceModels.ts +79 -0
  1637. package/src/lib/db/sessionAccountAffinity.ts +212 -0
  1638. package/src/lib/db/settings/cacheMetrics.ts +235 -0
  1639. package/src/lib/db/settings/lkgp.ts +49 -0
  1640. package/src/lib/db/settings/pricing.ts +254 -0
  1641. package/src/lib/db/settings/shared.ts +9 -0
  1642. package/src/lib/db/settings.ts +661 -0
  1643. package/src/lib/db/skills.ts +62 -0
  1644. package/src/lib/db/stateReset.ts +30 -0
  1645. package/src/lib/db/stats.ts +71 -0
  1646. package/src/lib/db/syncTokens.ts +163 -0
  1647. package/src/lib/db/tierConfig.ts +88 -0
  1648. package/src/lib/db/tokenLimits.ts +295 -0
  1649. package/src/lib/db/upstreamProxy.ts +247 -0
  1650. package/src/lib/db/usageAnalytics/sources.ts +208 -0
  1651. package/src/lib/db/usageAnalytics.ts +723 -0
  1652. package/src/lib/db/usageLogs.ts +94 -0
  1653. package/src/lib/db/usageSummary.ts +18 -0
  1654. package/src/lib/db/vacuumScheduler.ts +326 -0
  1655. package/src/lib/db/versionManager.ts +377 -0
  1656. package/src/lib/db/webSessionDedup.ts +57 -0
  1657. package/src/lib/db/webhookDeliveries.ts +77 -0
  1658. package/src/lib/db/webhooks.ts +178 -0
  1659. package/src/lib/discovery/index.ts +137 -0
  1660. package/src/lib/display/names.ts +73 -0
  1661. package/src/lib/display/useProviderNodeMap.ts +68 -0
  1662. package/src/lib/docsI18nPath.ts +33 -0
  1663. package/src/lib/docsSanitizer.ts +42 -0
  1664. package/src/lib/embeddings/familyGuard.ts +24 -0
  1665. package/src/lib/embeddings/service.ts +288 -0
  1666. package/src/lib/env/runtimeEnv.ts +166 -0
  1667. package/src/lib/evals/evalRunner/builtinSuites.ts +676 -0
  1668. package/src/lib/evals/evalRunner.ts +301 -0
  1669. package/src/lib/evals/runtime.ts +311 -0
  1670. package/src/lib/events/eventBus.ts +148 -0
  1671. package/src/lib/events/types.ts +181 -0
  1672. package/src/lib/freeProviderRankings.ts +340 -0
  1673. package/src/lib/freeProxyProviders/index.ts +24 -0
  1674. package/src/lib/freeProxyProviders/iplocate.ts +107 -0
  1675. package/src/lib/freeProxyProviders/oneproxy.ts +127 -0
  1676. package/src/lib/freeProxyProviders/proxifly.ts +143 -0
  1677. package/src/lib/freeProxyProviders/types.ts +33 -0
  1678. package/src/lib/freeProxyProviders/webshare.ts +148 -0
  1679. package/src/lib/gamification/antiCheat.ts +160 -0
  1680. package/src/lib/gamification/badges.ts +542 -0
  1681. package/src/lib/gamification/events.ts +187 -0
  1682. package/src/lib/gamification/index.ts +37 -0
  1683. package/src/lib/gamification/invites.ts +127 -0
  1684. package/src/lib/gamification/leaderboard.ts +64 -0
  1685. package/src/lib/gamification/notifications.ts +118 -0
  1686. package/src/lib/gamification/servers.ts +179 -0
  1687. package/src/lib/gamification/sharing.ts +56 -0
  1688. package/src/lib/gamification/streaks.ts +164 -0
  1689. package/src/lib/gamification/xp.ts +152 -0
  1690. package/src/lib/gracefulShutdown.ts +151 -0
  1691. package/src/lib/guardrails/base.ts +65 -0
  1692. package/src/lib/guardrails/index.ts +4 -0
  1693. package/src/lib/guardrails/piiMasker.ts +208 -0
  1694. package/src/lib/guardrails/promptInjection.ts +285 -0
  1695. package/src/lib/guardrails/registry.ts +282 -0
  1696. package/src/lib/guardrails/visionBridge.ts +237 -0
  1697. package/src/lib/guardrails/visionBridgeHelpers.ts +499 -0
  1698. package/src/lib/guardrails/visionBridgeRouter.ts +271 -0
  1699. package/src/lib/headroom/detect.ts +214 -0
  1700. package/src/lib/headroom/process.ts +177 -0
  1701. package/src/lib/idempotencyLayer.ts +105 -0
  1702. package/src/lib/images/imageRouteModel.ts +168 -0
  1703. package/src/lib/initCloudSync.ts +52 -0
  1704. package/src/lib/inspector/agentBridgeMaintenanceApi.ts +70 -0
  1705. package/src/lib/inspector/captureState.ts +90 -0
  1706. package/src/lib/inspector/configPortability.ts +86 -0
  1707. package/src/lib/inspector/harExport.ts +188 -0
  1708. package/src/lib/inspector/matchesTrafficFilter.ts +37 -0
  1709. package/src/lib/inspector/secretMask.ts +6 -0
  1710. package/src/lib/inspector/tproxyCaptureApi.ts +60 -0
  1711. package/src/lib/ipUtils.ts +94 -0
  1712. package/src/lib/jobs/budgetResetJob.ts +40 -0
  1713. package/src/lib/jobs/reasoningCacheCleanupJob.ts +40 -0
  1714. package/src/lib/localDb.ts +797 -0
  1715. package/src/lib/localHealthCheck.ts +267 -0
  1716. package/src/lib/logEnv.ts +164 -0
  1717. package/src/lib/logPayloads.ts +110 -0
  1718. package/src/lib/logRotation.ts +206 -0
  1719. package/src/lib/machineToken.ts +53 -0
  1720. package/src/lib/memory/cache.ts +76 -0
  1721. package/src/lib/memory/embedding/cache.ts +77 -0
  1722. package/src/lib/memory/embedding/index.ts +281 -0
  1723. package/src/lib/memory/embedding/remote.ts +95 -0
  1724. package/src/lib/memory/embedding/staticPotion.ts +253 -0
  1725. package/src/lib/memory/embedding/transformersLocal.ts +153 -0
  1726. package/src/lib/memory/embedding/types.ts +40 -0
  1727. package/src/lib/memory/extraction.ts +195 -0
  1728. package/src/lib/memory/injection.ts +211 -0
  1729. package/src/lib/memory/qdrant.ts +521 -0
  1730. package/src/lib/memory/reindex.ts +102 -0
  1731. package/src/lib/memory/retrieval/scoring.ts +104 -0
  1732. package/src/lib/memory/retrieval.ts +1072 -0
  1733. package/src/lib/memory/schemas.ts +39 -0
  1734. package/src/lib/memory/settings.ts +184 -0
  1735. package/src/lib/memory/store.ts +621 -0
  1736. package/src/lib/memory/summarization.ts +202 -0
  1737. package/src/lib/memory/typedDecay.ts +245 -0
  1738. package/src/lib/memory/types.ts +45 -0
  1739. package/src/lib/memory/vectorStore.ts +425 -0
  1740. package/src/lib/memory/verify.ts +56 -0
  1741. package/src/lib/middleware/cliTokenAuth.ts +91 -0
  1742. package/src/lib/middleware/registry.ts +432 -0
  1743. package/src/lib/middleware/types.ts +129 -0
  1744. package/src/lib/modelAliasSeed.ts +82 -0
  1745. package/src/lib/modelCapabilities.ts +481 -0
  1746. package/src/lib/modelMetadataRegistry.ts +574 -0
  1747. package/src/lib/modelsDevSync/transform.ts +279 -0
  1748. package/src/lib/modelsDevSync.ts +677 -0
  1749. package/src/lib/monitoring/comboHealthAutopilot.ts +494 -0
  1750. package/src/lib/monitoring/observability.ts +336 -0
  1751. package/src/lib/monitoring/providerHealthAutopilot.ts +743 -0
  1752. package/src/lib/monitoring/providerHealthMatrix.ts +621 -0
  1753. package/src/lib/ngrokTunnel.ts +142 -0
  1754. package/src/lib/notion/api.ts +247 -0
  1755. package/src/lib/oauth/codexDeviceFlow.ts +316 -0
  1756. package/src/lib/oauth/config/index.ts +31 -0
  1757. package/src/lib/oauth/connectionPersistence.ts +114 -0
  1758. package/src/lib/oauth/constants/oauth.ts +494 -0
  1759. package/src/lib/oauth/credentialBlob.ts +105 -0
  1760. package/src/lib/oauth/deviceFlowTickets.ts +110 -0
  1761. package/src/lib/oauth/gitlab.ts +103 -0
  1762. package/src/lib/oauth/pasteCredentials.ts +51 -0
  1763. package/src/lib/oauth/providers/agy.ts +15 -0
  1764. package/src/lib/oauth/providers/antigravity.ts +159 -0
  1765. package/src/lib/oauth/providers/claude.ts +170 -0
  1766. package/src/lib/oauth/providers/cline.ts +91 -0
  1767. package/src/lib/oauth/providers/codebuddy-cn.ts +123 -0
  1768. package/src/lib/oauth/providers/codex.ts +214 -0
  1769. package/src/lib/oauth/providers/cursor.ts +15 -0
  1770. package/src/lib/oauth/providers/github.ts +89 -0
  1771. package/src/lib/oauth/providers/gitlab-duo.ts +124 -0
  1772. package/src/lib/oauth/providers/grok-cli.ts +155 -0
  1773. package/src/lib/oauth/providers/index.ts +59 -0
  1774. package/src/lib/oauth/providers/kilocode.ts +77 -0
  1775. package/src/lib/oauth/providers/kimi-coding.ts +135 -0
  1776. package/src/lib/oauth/providers/kiro.ts +185 -0
  1777. package/src/lib/oauth/providers/qoder.ts +81 -0
  1778. package/src/lib/oauth/providers/qwen.ts +82 -0
  1779. package/src/lib/oauth/providers/trae.ts +78 -0
  1780. package/src/lib/oauth/providers/windsurf.ts +64 -0
  1781. package/src/lib/oauth/providers/zed-hosted.ts +89 -0
  1782. package/src/lib/oauth/providers/zed.ts +35 -0
  1783. package/src/lib/oauth/providers.ts +278 -0
  1784. package/src/lib/oauth/services/codexImport.ts +222 -0
  1785. package/src/lib/oauth/services/cursor.ts +219 -0
  1786. package/src/lib/oauth/services/kiro.ts +441 -0
  1787. package/src/lib/oauth/utils/agyAuthImport.ts +259 -0
  1788. package/src/lib/oauth/utils/banner.ts +62 -0
  1789. package/src/lib/oauth/utils/claudeAuthFile.ts +334 -0
  1790. package/src/lib/oauth/utils/claudeAuthImport.ts +259 -0
  1791. package/src/lib/oauth/utils/claudeAuthZipExtract.ts +5 -0
  1792. package/src/lib/oauth/utils/cliProxyAuthImport.ts +142 -0
  1793. package/src/lib/oauth/utils/codexAuthFile.ts +352 -0
  1794. package/src/lib/oauth/utils/codexAuthImport.ts +294 -0
  1795. package/src/lib/oauth/utils/codexAuthZipExtract.ts +5 -0
  1796. package/src/lib/oauth/utils/jsonZipExtract.ts +89 -0
  1797. package/src/lib/oauth/utils/pkce.ts +37 -0
  1798. package/src/lib/oauth/utils/server.ts +122 -0
  1799. package/src/lib/oauth/utils/ui.ts +47 -0
  1800. package/src/lib/obsidian/api.ts +390 -0
  1801. package/src/lib/obsidianSync.ts +110 -0
  1802. package/src/lib/oneproxyRotator.ts +19 -0
  1803. package/src/lib/oneproxySync.ts +182 -0
  1804. package/src/lib/piiSanitizer.ts +416 -0
  1805. package/src/lib/playground/codeExport.ts +408 -0
  1806. package/src/lib/playground/promptImprover.ts +147 -0
  1807. package/src/lib/playground/streamMetrics.ts +61 -0
  1808. package/src/lib/playground/types.ts +114 -0
  1809. package/src/lib/plugins/devMode.ts +65 -0
  1810. package/src/lib/plugins/doctor.ts +138 -0
  1811. package/src/lib/plugins/errors.ts +38 -0
  1812. package/src/lib/plugins/hooks.ts +322 -0
  1813. package/src/lib/plugins/index.ts +72 -0
  1814. package/src/lib/plugins/loader.ts +326 -0
  1815. package/src/lib/plugins/logger.ts +50 -0
  1816. package/src/lib/plugins/manager.ts +579 -0
  1817. package/src/lib/plugins/manifest.ts +213 -0
  1818. package/src/lib/plugins/marketplace.ts +202 -0
  1819. package/src/lib/plugins/pluginWorker.ts +246 -0
  1820. package/src/lib/plugins/sandbox.ts +29 -0
  1821. package/src/lib/plugins/scanner.ts +110 -0
  1822. package/src/lib/plugins/sdk.ts +88 -0
  1823. package/src/lib/plugins/signing.ts +34 -0
  1824. package/src/lib/plugins/testRunner.ts +95 -0
  1825. package/src/lib/plugins/watcher.ts +90 -0
  1826. package/src/lib/pricingSync.ts +456 -0
  1827. package/src/lib/promptCache/index.ts +1 -0
  1828. package/src/lib/promptCache/prefixAnalyzer.ts +81 -0
  1829. package/src/lib/providerModels/cursorAgent.ts +166 -0
  1830. package/src/lib/providerModels/geminiModelsParser.ts +91 -0
  1831. package/src/lib/providerModels/managedAvailableModels.ts +165 -0
  1832. package/src/lib/providerModels/managedModelImport.ts +349 -0
  1833. package/src/lib/providerModels/modelDiscovery.ts +151 -0
  1834. package/src/lib/providers/catalog.ts +246 -0
  1835. package/src/lib/providers/claudeExtraUsage.ts +160 -0
  1836. package/src/lib/providers/claudeFastMode.ts +75 -0
  1837. package/src/lib/providers/codexConnectionDefaults.ts +85 -0
  1838. package/src/lib/providers/codexFastTier.ts +210 -0
  1839. package/src/lib/providers/imageValidation.ts +160 -0
  1840. package/src/lib/providers/managedAvailableModels.ts +21 -0
  1841. package/src/lib/providers/modelListingCapability.ts +26 -0
  1842. package/src/lib/providers/nvidiaValidationModel.ts +24 -0
  1843. package/src/lib/providers/requestDefaults.ts +318 -0
  1844. package/src/lib/providers/serviceKindIndex.ts +0 -0
  1845. package/src/lib/providers/staticModels.ts +170 -0
  1846. package/src/lib/providers/validation/anthropicFormat.ts +319 -0
  1847. package/src/lib/providers/validation/audioMiscProviders.ts +582 -0
  1848. package/src/lib/providers/validation/cloudProviders.ts +669 -0
  1849. package/src/lib/providers/validation/cozeError.ts +56 -0
  1850. package/src/lib/providers/validation/directChatProbe.ts +47 -0
  1851. package/src/lib/providers/validation/embeddingProviders.ts +143 -0
  1852. package/src/lib/providers/validation/headers.ts +122 -0
  1853. package/src/lib/providers/validation/metaAi.ts +117 -0
  1854. package/src/lib/providers/validation/openaiFormat.ts +500 -0
  1855. package/src/lib/providers/validation/searchProviders.ts +199 -0
  1856. package/src/lib/providers/validation/transport.ts +109 -0
  1857. package/src/lib/providers/validation/urlHelpers.ts +114 -0
  1858. package/src/lib/providers/validation/webProvidersA.ts +808 -0
  1859. package/src/lib/providers/validation/webProvidersB.ts +536 -0
  1860. package/src/lib/providers/validation.ts +772 -0
  1861. package/src/lib/providers/webCookieAuth.ts +157 -0
  1862. package/src/lib/providers/xai/thinking.ts +127 -0
  1863. package/src/lib/providers/xai/translators/claude.ts +368 -0
  1864. package/src/lib/providers/xai/translators/gemini.ts +371 -0
  1865. package/src/lib/providers/xai/translators/openai-chat.ts +310 -0
  1866. package/src/lib/providers/xai/translators/openai-responses.ts +77 -0
  1867. package/src/lib/proxyEgress.ts +388 -0
  1868. package/src/lib/proxyHealth/decision.ts +77 -0
  1869. package/src/lib/proxyHealth/scheduler.ts +207 -0
  1870. package/src/lib/proxyHealth/statusPolicy.ts +41 -0
  1871. package/src/lib/proxyHealth.ts +173 -0
  1872. package/src/lib/proxyLogger.ts +240 -0
  1873. package/src/lib/proxyRelay/cloudflareWorkerScript.ts +107 -0
  1874. package/src/lib/quota/QuotaStore.ts +23 -0
  1875. package/src/lib/quota/accountBuckets.ts +225 -0
  1876. package/src/lib/quota/burnRate.ts +111 -0
  1877. package/src/lib/quota/connectionProvider.ts +32 -0
  1878. package/src/lib/quota/connectionRecovery.ts +303 -0
  1879. package/src/lib/quota/dimensions.ts +61 -0
  1880. package/src/lib/quota/enforce.ts +401 -0
  1881. package/src/lib/quota/fairShare.ts +186 -0
  1882. package/src/lib/quota/planRegistry.ts +107 -0
  1883. package/src/lib/quota/planResolver.ts +78 -0
  1884. package/src/lib/quota/quotaCombos.ts +414 -0
  1885. package/src/lib/quota/quotaKey.ts +202 -0
  1886. package/src/lib/quota/quotaModelNaming.ts +84 -0
  1887. package/src/lib/quota/redisQuotaStore.ts +352 -0
  1888. package/src/lib/quota/saturationSignals.ts +559 -0
  1889. package/src/lib/quota/spendRecorder.ts +131 -0
  1890. package/src/lib/quota/sqliteQuotaStore.ts +282 -0
  1891. package/src/lib/quota/storeFactory.ts +124 -0
  1892. package/src/lib/quota/types.ts +94 -0
  1893. package/src/lib/resilience/modelLockoutSettings.ts +95 -0
  1894. package/src/lib/resilience/settings/normalize.ts +359 -0
  1895. package/src/lib/resilience/settings/types.ts +182 -0
  1896. package/src/lib/resilience/settings.ts +386 -0
  1897. package/src/lib/runtime/ports.ts +32 -0
  1898. package/src/lib/search/executeWebSearch.ts +270 -0
  1899. package/src/lib/security/localEndpoints.ts +82 -0
  1900. package/src/lib/semanticCache.ts +377 -0
  1901. package/src/lib/services/ServiceSupervisor.ts +243 -0
  1902. package/src/lib/services/apiKey.ts +40 -0
  1903. package/src/lib/services/bootstrap.ts +133 -0
  1904. package/src/lib/services/embedPath.ts +19 -0
  1905. package/src/lib/services/embedWsProxy.ts +285 -0
  1906. package/src/lib/services/healthCheck.ts +79 -0
  1907. package/src/lib/services/htmlRewriter.ts +185 -0
  1908. package/src/lib/services/installers/bifrost.ts +145 -0
  1909. package/src/lib/services/installers/cliproxy.ts +116 -0
  1910. package/src/lib/services/installers/mux.ts +178 -0
  1911. package/src/lib/services/installers/ninerouter.stub.ts +17 -0
  1912. package/src/lib/services/installers/ninerouter.ts +157 -0
  1913. package/src/lib/services/installers/utils.ts +167 -0
  1914. package/src/lib/services/modelSync.ts +105 -0
  1915. package/src/lib/services/portProbe.ts +104 -0
  1916. package/src/lib/services/registry.ts +42 -0
  1917. package/src/lib/services/reverseProxy.ts +180 -0
  1918. package/src/lib/services/ringBuffer.ts +91 -0
  1919. package/src/lib/services/types.ts +50 -0
  1920. package/src/lib/settingsCache.ts +62 -0
  1921. package/src/lib/skills/a2a.ts +34 -0
  1922. package/src/lib/skills/builtin/browser.ts +22 -0
  1923. package/src/lib/skills/builtins.ts +493 -0
  1924. package/src/lib/skills/custom.ts +41 -0
  1925. package/src/lib/skills/executor.ts +196 -0
  1926. package/src/lib/skills/githubCollector.ts +426 -0
  1927. package/src/lib/skills/hybrid.ts +67 -0
  1928. package/src/lib/skills/injection.ts +307 -0
  1929. package/src/lib/skills/interception.ts +343 -0
  1930. package/src/lib/skills/providerSettings.ts +14 -0
  1931. package/src/lib/skills/registry.ts +398 -0
  1932. package/src/lib/skills/sandbox.ts +178 -0
  1933. package/src/lib/skills/schemas.ts +43 -0
  1934. package/src/lib/skills/skillssh.ts +73 -0
  1935. package/src/lib/skills/types.ts +61 -0
  1936. package/src/lib/source.ts +7 -0
  1937. package/src/lib/spend/batchWriter.ts +208 -0
  1938. package/src/lib/sseTextTransform.ts +346 -0
  1939. package/src/lib/streamingPiiTransform.ts +350 -0
  1940. package/src/lib/sync/bundle.ts +208 -0
  1941. package/src/lib/sync/tokens.ts +107 -0
  1942. package/src/lib/system/autoUpdate.ts +400 -0
  1943. package/src/lib/system/globalPackagePath.ts +49 -0
  1944. package/src/lib/system/versionCheck.ts +163 -0
  1945. package/src/lib/tailscaleTunnel.ts +1201 -0
  1946. package/src/lib/tokenHealthCheck.ts +829 -0
  1947. package/src/lib/toolPolicy.ts +150 -0
  1948. package/src/lib/translator/streamTransform.ts +27 -0
  1949. package/src/lib/translatorEvents.ts +40 -0
  1950. package/src/lib/usage/aggregateHistory.ts +212 -0
  1951. package/src/lib/usage/apiKeySelfService.ts +420 -0
  1952. package/src/lib/usage/apiKeyUsageLimits.ts +578 -0
  1953. package/src/lib/usage/callLogArtifacts.ts +337 -0
  1954. package/src/lib/usage/callLogs/format.ts +129 -0
  1955. package/src/lib/usage/callLogs.ts +928 -0
  1956. package/src/lib/usage/callLogsBoundedQueries.ts +42 -0
  1957. package/src/lib/usage/codexResetCredits.ts +355 -0
  1958. package/src/lib/usage/comboForecast.ts +441 -0
  1959. package/src/lib/usage/comboHealth.ts +545 -0
  1960. package/src/lib/usage/comboHealthDashboard.ts +109 -0
  1961. package/src/lib/usage/comboScoringInspector.ts +416 -0
  1962. package/src/lib/usage/completedRequestDetails.ts +103 -0
  1963. package/src/lib/usage/costCalculator.ts +279 -0
  1964. package/src/lib/usage/fetcher.ts +483 -0
  1965. package/src/lib/usage/flatRateProviders.ts +59 -0
  1966. package/src/lib/usage/internalUsageCommand.ts +788 -0
  1967. package/src/lib/usage/migrations.ts +471 -0
  1968. package/src/lib/usage/pendingRequestScope.ts +26 -0
  1969. package/src/lib/usage/providerLimits/quotaNormalize.ts +72 -0
  1970. package/src/lib/usage/providerLimits.ts +997 -0
  1971. package/src/lib/usage/providerWindowCosts.ts +571 -0
  1972. package/src/lib/usage/resilienceExplain.ts +468 -0
  1973. package/src/lib/usage/routeExplain.ts +747 -0
  1974. package/src/lib/usage/tokenAccounting.ts +212 -0
  1975. package/src/lib/usage/usageEvents.ts +91 -0
  1976. package/src/lib/usage/usageHistory/helpers.ts +85 -0
  1977. package/src/lib/usage/usageHistory.ts +916 -0
  1978. package/src/lib/usage/usageStats.ts +581 -0
  1979. package/src/lib/usageAnalytics.ts +372 -0
  1980. package/src/lib/usageDb.ts +38 -0
  1981. package/src/lib/versionManager/binaryManager.ts +240 -0
  1982. package/src/lib/versionManager/healthMonitor.ts +71 -0
  1983. package/src/lib/versionManager/index.ts +155 -0
  1984. package/src/lib/versionManager/processManager.ts +155 -0
  1985. package/src/lib/versionManager/releaseChecker.ts +98 -0
  1986. package/src/lib/vscode/familyFirstModelIds.ts +92 -0
  1987. package/src/lib/vscode/modelPresentation.ts +132 -0
  1988. package/src/lib/vscode/reasoningMetadata.ts +183 -0
  1989. package/src/lib/vscode/serviceTierVariants.ts +202 -0
  1990. package/src/lib/vscode/tokenizedRequest.ts +79 -0
  1991. package/src/lib/webhookDispatcher.ts +221 -0
  1992. package/src/lib/webhooks/eventDescriptions.ts +76 -0
  1993. package/src/lib/webhooks/integrations/discord.ts +49 -0
  1994. package/src/lib/webhooks/integrations/slack.ts +45 -0
  1995. package/src/lib/webhooks/integrations/telegram.ts +67 -0
  1996. package/src/lib/ws/handshake.ts +129 -0
  1997. package/src/lib/zed-oauth/confirmedAccounts.ts +38 -0
  1998. package/src/lib/zed-oauth/credentialFingerprint.ts +23 -0
  1999. package/src/lib/zed-oauth/dockerDetect.ts +38 -0
  2000. package/src/lib/zed-oauth/importUtils.ts +46 -0
  2001. package/src/lib/zed-oauth/keychain-reader.stub.ts +28 -0
  2002. package/src/lib/zed-oauth/keychain-reader.ts +231 -0
  2003. package/src/mitm/_internal/bypass.cjs +170 -0
  2004. package/src/mitm/_internal/forwardTarget.cjs +55 -0
  2005. package/src/mitm/_internal/ingest.cjs +82 -0
  2006. package/src/mitm/cert/generate.ts +41 -0
  2007. package/src/mitm/cert/install.stub.ts +23 -0
  2008. package/src/mitm/cert/install.ts +440 -0
  2009. package/src/mitm/dataDir.ts +41 -0
  2010. package/src/mitm/detection/antigravity.ts +33 -0
  2011. package/src/mitm/detection/claudeCode.ts +25 -0
  2012. package/src/mitm/detection/codex.ts +25 -0
  2013. package/src/mitm/detection/copilot.ts +39 -0
  2014. package/src/mitm/detection/cursor.ts +31 -0
  2015. package/src/mitm/detection/index.ts +53 -0
  2016. package/src/mitm/detection/kiro.ts +30 -0
  2017. package/src/mitm/detection/openCode.ts +32 -0
  2018. package/src/mitm/detection/zed.ts +26 -0
  2019. package/src/mitm/dns/dnsConfig.ts +242 -0
  2020. package/src/mitm/dns/provision.ts +92 -0
  2021. package/src/mitm/handlers/antigravity.ts +192 -0
  2022. package/src/mitm/handlers/base.ts +333 -0
  2023. package/src/mitm/handlers/claudeCode.ts +56 -0
  2024. package/src/mitm/handlers/codex.ts +55 -0
  2025. package/src/mitm/handlers/copilot.ts +55 -0
  2026. package/src/mitm/handlers/cursor.ts +55 -0
  2027. package/src/mitm/handlers/kiro.ts +58 -0
  2028. package/src/mitm/handlers/openCode.ts +55 -0
  2029. package/src/mitm/handlers/trae.ts +24 -0
  2030. package/src/mitm/handlers/zed.ts +55 -0
  2031. package/src/mitm/inspector/agentBridgeHook.ts +137 -0
  2032. package/src/mitm/inspector/buffer.ts +201 -0
  2033. package/src/mitm/inspector/contextKey.ts +98 -0
  2034. package/src/mitm/inspector/conversationNormalizer.ts +393 -0
  2035. package/src/mitm/inspector/diagnostics.ts +67 -0
  2036. package/src/mitm/inspector/httpProxyServer.ts +272 -0
  2037. package/src/mitm/inspector/kindDetector.ts +87 -0
  2038. package/src/mitm/inspector/llmMetadataExtractor.ts +183 -0
  2039. package/src/mitm/inspector/pricing.ts +57 -0
  2040. package/src/mitm/inspector/processAttribution.ts +107 -0
  2041. package/src/mitm/inspector/sseMerger.ts +316 -0
  2042. package/src/mitm/inspector/systemProxyConfig.ts +316 -0
  2043. package/src/mitm/inspector/types.ts +112 -0
  2044. package/src/mitm/manager.runtime.ts +5 -0
  2045. package/src/mitm/manager.stub.ts +44 -0
  2046. package/src/mitm/manager.ts +762 -0
  2047. package/src/mitm/maskSecrets.ts +31 -0
  2048. package/src/mitm/passthrough.ts +76 -0
  2049. package/src/mitm/sanitizeHeaders.ts +61 -0
  2050. package/src/mitm/server.cjs +786 -0
  2051. package/src/mitm/socketTimeouts.ts +24 -0
  2052. package/src/mitm/systemCommands.ts +280 -0
  2053. package/src/mitm/targets/antigravity.ts +85 -0
  2054. package/src/mitm/targets/claudeCode.ts +37 -0
  2055. package/src/mitm/targets/codex.ts +30 -0
  2056. package/src/mitm/targets/copilot.ts +32 -0
  2057. package/src/mitm/targets/cursor.ts +33 -0
  2058. package/src/mitm/targets/index.ts +75 -0
  2059. package/src/mitm/targets/kiro.ts +64 -0
  2060. package/src/mitm/targets/openCode.ts +34 -0
  2061. package/src/mitm/targets/trae.ts +32 -0
  2062. package/src/mitm/targets/zed.ts +32 -0
  2063. package/src/mitm/tproxy/caTrust.ts +120 -0
  2064. package/src/mitm/tproxy/captureManager.ts +118 -0
  2065. package/src/mitm/tproxy/captureMode.ts +226 -0
  2066. package/src/mitm/tproxy/commands.ts +122 -0
  2067. package/src/mitm/tproxy/dynamicCert.ts +119 -0
  2068. package/src/mitm/tproxy/native/README.md +55 -0
  2069. package/src/mitm/tproxy/native/binding.gyp +9 -0
  2070. package/src/mitm/tproxy/native/transparent.c +147 -0
  2071. package/src/mitm/tproxy/setup.ts +68 -0
  2072. package/src/mitm/tproxy/tlsCapture.ts +368 -0
  2073. package/src/mitm/tproxy/transparentSocket.ts +131 -0
  2074. package/src/mitm/types.ts +75 -0
  2075. package/src/mitm/upstreamTrust.ts +40 -0
  2076. package/src/models/index.ts +29 -0
  2077. package/src/server/auth/loginGuard.ts +130 -0
  2078. package/src/server/authz/accessScopes.ts +62 -0
  2079. package/src/server/authz/accessTokenAuth.ts +67 -0
  2080. package/src/server/authz/assertAuth.ts +88 -0
  2081. package/src/server/authz/classify.ts +135 -0
  2082. package/src/server/authz/context.ts +44 -0
  2083. package/src/server/authz/csrf.ts +85 -0
  2084. package/src/server/authz/headers.ts +76 -0
  2085. package/src/server/authz/peerStamp.ts +99 -0
  2086. package/src/server/authz/pipeline.ts +370 -0
  2087. package/src/server/authz/policies/clientApi.ts +72 -0
  2088. package/src/server/authz/policies/management.ts +298 -0
  2089. package/src/server/authz/policies/public.ts +9 -0
  2090. package/src/server/authz/routeGuard.ts +233 -0
  2091. package/src/server/authz/types.ts +77 -0
  2092. package/src/server/cors/origins.ts +172 -0
  2093. package/src/server/origin/publicOrigin.ts +270 -0
  2094. package/src/server/ws/liveServer.ts +630 -0
  2095. package/src/server/ws/liveServerAllowList.ts +106 -0
  2096. package/src/server/ws/types.ts +57 -0
  2097. package/src/shared/components/Avatar.tsx +81 -0
  2098. package/src/shared/components/Badge.tsx +68 -0
  2099. package/src/shared/components/Breadcrumbs.tsx +103 -0
  2100. package/src/shared/components/Button.tsx +85 -0
  2101. package/src/shared/components/Card.tsx +141 -0
  2102. package/src/shared/components/Checkbox.tsx +38 -0
  2103. package/src/shared/components/CloudSyncStatus.tsx +104 -0
  2104. package/src/shared/components/Collapsible.tsx +93 -0
  2105. package/src/shared/components/CollapsibleSection.tsx +66 -0
  2106. package/src/shared/components/ColumnToggle.tsx +100 -0
  2107. package/src/shared/components/CommandPalette.tsx +375 -0
  2108. package/src/shared/components/ConsoleLogViewer.tsx +326 -0
  2109. package/src/shared/components/CursorAuthModal.tsx +198 -0
  2110. package/src/shared/components/DataTable.tsx +195 -0
  2111. package/src/shared/components/DegradationBadge.tsx +41 -0
  2112. package/src/shared/components/DistributeProxiesButton.tsx +74 -0
  2113. package/src/shared/components/EmptyState.tsx +121 -0
  2114. package/src/shared/components/ErrorPageScaffold.tsx +91 -0
  2115. package/src/shared/components/FilterBar.tsx +197 -0
  2116. package/src/shared/components/Footer.tsx +169 -0
  2117. package/src/shared/components/Header.tsx +284 -0
  2118. package/src/shared/components/InfoTooltip.tsx +34 -0
  2119. package/src/shared/components/Input.tsx +155 -0
  2120. package/src/shared/components/KiroAuthModal.tsx +425 -0
  2121. package/src/shared/components/KiroOAuthWrapper.tsx +116 -0
  2122. package/src/shared/components/KiroSocialOAuthModal.tsx +202 -0
  2123. package/src/shared/components/LanguageSelector.tsx +106 -0
  2124. package/src/shared/components/LinkifiedText.tsx +30 -0
  2125. package/src/shared/components/Loading.tsx +128 -0
  2126. package/src/shared/components/LocaleAutoDetect.tsx +43 -0
  2127. package/src/shared/components/MaintenanceBanner.tsx +87 -0
  2128. package/src/shared/components/ManualConfigModal.tsx +51 -0
  2129. package/src/shared/components/Modal.tsx +240 -0
  2130. package/src/shared/components/ModelRoutingSection.tsx +323 -0
  2131. package/src/shared/components/ModelSelectModal.tsx +618 -0
  2132. package/src/shared/components/MonacoEditor.tsx +23 -0
  2133. package/src/shared/components/NavigationProgress.tsx +105 -0
  2134. package/src/shared/components/NoAuthAccountCard.tsx +539 -0
  2135. package/src/shared/components/NoAuthProviderCard.tsx +40 -0
  2136. package/src/shared/components/NoAuthProviderToggle.tsx +36 -0
  2137. package/src/shared/components/NotificationToast.tsx +206 -0
  2138. package/src/shared/components/OAuthModal.tsx +992 -0
  2139. package/src/shared/components/OmniRouteLogo.tsx +86 -0
  2140. package/src/shared/components/PresetSlider.tsx +64 -0
  2141. package/src/shared/components/PricingModal.tsx +211 -0
  2142. package/src/shared/components/ProviderIcon.tsx +263 -0
  2143. package/src/shared/components/ProviderTestSlideOver.tsx +560 -0
  2144. package/src/shared/components/ProxyConfigModal.tsx +781 -0
  2145. package/src/shared/components/ProxyLogDetail.tsx +192 -0
  2146. package/src/shared/components/ProxyLogger.tsx +573 -0
  2147. package/src/shared/components/PwaRegister.tsx +22 -0
  2148. package/src/shared/components/RequestLoggerDetail.tsx +797 -0
  2149. package/src/shared/components/RequestLoggerV2.tsx +1628 -0
  2150. package/src/shared/components/RiskNoticeModal.tsx +81 -0
  2151. package/src/shared/components/SegmentedControl.tsx +69 -0
  2152. package/src/shared/components/Select.tsx +110 -0
  2153. package/src/shared/components/Sidebar.tsx +726 -0
  2154. package/src/shared/components/SkillsConceptCard.tsx +84 -0
  2155. package/src/shared/components/SystemMonitor.tsx +179 -0
  2156. package/src/shared/components/Textarea.tsx +29 -0
  2157. package/src/shared/components/ThemeProvider.tsx +14 -0
  2158. package/src/shared/components/ThemeToggle.tsx +52 -0
  2159. package/src/shared/components/Toggle.tsx +102 -0
  2160. package/src/shared/components/TokenHealthBadge.tsx +113 -0
  2161. package/src/shared/components/Tooltip.tsx +193 -0
  2162. package/src/shared/components/TraeAuthModal.tsx +334 -0
  2163. package/src/shared/components/UsageAnalytics.tsx +414 -0
  2164. package/src/shared/components/UsageStats.tsx +693 -0
  2165. package/src/shared/components/analytics/ApiKeyFilterDropdown.tsx +205 -0
  2166. package/src/shared/components/analytics/CustomRangePicker.tsx +195 -0
  2167. package/src/shared/components/analytics/TimeRangeSelector.tsx +49 -0
  2168. package/src/shared/components/analytics/chartColors.ts +12 -0
  2169. package/src/shared/components/analytics/charts.tsx +1023 -0
  2170. package/src/shared/components/analytics/index.tsx +28 -0
  2171. package/src/shared/components/analytics/rechartsCore.tsx +85 -0
  2172. package/src/shared/components/analytics/rechartsDonuts.tsx +195 -0
  2173. package/src/shared/components/analytics/rechartsUsageCharts.tsx +312 -0
  2174. package/src/shared/components/cli/CliComparisonCard.tsx +82 -0
  2175. package/src/shared/components/cli/CliConceptCard.tsx +58 -0
  2176. package/src/shared/components/cli/CliToolCard.tsx +152 -0
  2177. package/src/shared/components/cli/index.ts +8 -0
  2178. package/src/shared/components/compression/CompressionPipelineEditor.tsx +175 -0
  2179. package/src/shared/components/compression/EngineConfigForm.tsx +78 -0
  2180. package/src/shared/components/compression/EngineConfigPage.tsx +411 -0
  2181. package/src/shared/components/compression/compressionPipelineModel.ts +78 -0
  2182. package/src/shared/components/docs/APIReference.stories.tsx +35 -0
  2183. package/src/shared/components/docs/APIReference.tsx +83 -0
  2184. package/src/shared/components/docs/Callout.stories.tsx +40 -0
  2185. package/src/shared/components/docs/Callout.tsx +38 -0
  2186. package/src/shared/components/docs/CodeBlock.stories.tsx +25 -0
  2187. package/src/shared/components/docs/CodeBlock.tsx +52 -0
  2188. package/src/shared/components/docs/DocsBreadcrumbs.stories.tsx +20 -0
  2189. package/src/shared/components/docs/DocsBreadcrumbs.tsx +46 -0
  2190. package/src/shared/components/docs/DocsSidebar.stories.tsx +31 -0
  2191. package/src/shared/components/docs/DocsSidebar.tsx +77 -0
  2192. package/src/shared/components/docs/DocsThemeProvider.tsx +21 -0
  2193. package/src/shared/components/docs/Tabs.stories.tsx +26 -0
  2194. package/src/shared/components/docs/Tabs.tsx +50 -0
  2195. package/src/shared/components/docs/tokens.ts +38 -0
  2196. package/src/shared/components/flow/FlowCanvas.tsx +151 -0
  2197. package/src/shared/components/flow/StatusDot.tsx +36 -0
  2198. package/src/shared/components/flow/edgeStyles.ts +32 -0
  2199. package/src/shared/components/index.tsx +49 -0
  2200. package/src/shared/components/layouts/AuthLayout.tsx +28 -0
  2201. package/src/shared/components/layouts/DashboardLayout.tsx +131 -0
  2202. package/src/shared/components/layouts/index.tsx +3 -0
  2203. package/src/shared/components/lobeProviderIcons.ts +488 -0
  2204. package/src/shared/components/logTableStyles.ts +7 -0
  2205. package/src/shared/components/modelSelectModalHelpers.ts +75 -0
  2206. package/src/shared/components/oauthBlobSubmit.ts +42 -0
  2207. package/src/shared/components/proxyAssignment.ts +40 -0
  2208. package/src/shared/components/requestLoggerPreferences.ts +44 -0
  2209. package/src/shared/components/requestLoggerSignature.ts +56 -0
  2210. package/src/shared/constants/agentSkills.ts +457 -0
  2211. package/src/shared/constants/antigravityClientProfile.ts +29 -0
  2212. package/src/shared/constants/apiKeyPolicyScopes.ts +5 -0
  2213. package/src/shared/constants/appConfig.ts +12 -0
  2214. package/src/shared/constants/batch.ts +1 -0
  2215. package/src/shared/constants/batchEndpoints.ts +11 -0
  2216. package/src/shared/constants/bodySize.ts +39 -0
  2217. package/src/shared/constants/cliCompatProviders.ts +88 -0
  2218. package/src/shared/constants/cliTools.ts +862 -0
  2219. package/src/shared/constants/clientIdentityProfiles.ts +89 -0
  2220. package/src/shared/constants/colors.ts +147 -0
  2221. package/src/shared/constants/comboConfigMode.ts +9 -0
  2222. package/src/shared/constants/config.ts +44 -0
  2223. package/src/shared/constants/dashboardCsrf.ts +1 -0
  2224. package/src/shared/constants/endpointCategories.ts +133 -0
  2225. package/src/shared/constants/errorCodes.ts +245 -0
  2226. package/src/shared/constants/featureFlagDefinitions.ts +495 -0
  2227. package/src/shared/constants/headers.ts +16 -0
  2228. package/src/shared/constants/homeWidgets.ts +5 -0
  2229. package/src/shared/constants/index.ts +4 -0
  2230. package/src/shared/constants/managementScopes.ts +31 -0
  2231. package/src/shared/constants/mcpScopes.ts +78 -0
  2232. package/src/shared/constants/mitmToolHosts.ts +31 -0
  2233. package/src/shared/constants/modal.ts +5 -0
  2234. package/src/shared/constants/modelCompat.ts +9 -0
  2235. package/src/shared/constants/modelSpecs.ts +607 -0
  2236. package/src/shared/constants/models.ts +40 -0
  2237. package/src/shared/constants/openRouterPreset.ts +11 -0
  2238. package/src/shared/constants/pricing/default-pricing.ts +16 -0
  2239. package/src/shared/constants/pricing/frontier-labs.ts +386 -0
  2240. package/src/shared/constants/pricing/inference-hosts.ts +208 -0
  2241. package/src/shared/constants/pricing/oauth-subscriptions.ts +599 -0
  2242. package/src/shared/constants/pricing/regional.ts +168 -0
  2243. package/src/shared/constants/pricing/shared-tiers.ts +162 -0
  2244. package/src/shared/constants/pricing.ts +40 -0
  2245. package/src/shared/constants/providers/apikey/enterprise-cloud.ts +214 -0
  2246. package/src/shared/constants/providers/apikey/frontier-labs.ts +253 -0
  2247. package/src/shared/constants/providers/apikey/gateways.ts +662 -0
  2248. package/src/shared/constants/providers/apikey/index.ts +21 -0
  2249. package/src/shared/constants/providers/apikey/inference-hosts.ts +328 -0
  2250. package/src/shared/constants/providers/apikey/regional.ts +372 -0
  2251. package/src/shared/constants/providers/apikey/specialty-media.ts +266 -0
  2252. package/src/shared/constants/providers/audio.ts +71 -0
  2253. package/src/shared/constants/providers/cloud-agent.ts +36 -0
  2254. package/src/shared/constants/providers/local.ts +162 -0
  2255. package/src/shared/constants/providers/noauth.ts +123 -0
  2256. package/src/shared/constants/providers/oauth.ts +231 -0
  2257. package/src/shared/constants/providers/search.ts +125 -0
  2258. package/src/shared/constants/providers/system.ts +16 -0
  2259. package/src/shared/constants/providers/upstream-proxy.ts +36 -0
  2260. package/src/shared/constants/providers/web-cookie.ts +364 -0
  2261. package/src/shared/constants/providers.ts +449 -0
  2262. package/src/shared/constants/publicApiRoutes.ts +62 -0
  2263. package/src/shared/constants/responsesPreviousResponseId.ts +5 -0
  2264. package/src/shared/constants/routingStrategies.ts +216 -0
  2265. package/src/shared/constants/selfServiceScopes.ts +20 -0
  2266. package/src/shared/constants/serviceKinds.ts +34 -0
  2267. package/src/shared/constants/sidebarGroupVisibility.ts +31 -0
  2268. package/src/shared/constants/sidebarVisibility/sections.ts +769 -0
  2269. package/src/shared/constants/sidebarVisibility/types.ts +161 -0
  2270. package/src/shared/constants/sidebarVisibility.ts +291 -0
  2271. package/src/shared/constants/spawnCapablePrefixes.ts +35 -0
  2272. package/src/shared/constants/statusColors.ts +17 -0
  2273. package/src/shared/constants/upstreamHeaders.ts +42 -0
  2274. package/src/shared/constants/visionBridgeDefaults.ts +88 -0
  2275. package/src/shared/constants/visionModels.ts +68 -0
  2276. package/src/shared/contracts/quota.ts +138 -0
  2277. package/src/shared/hooks/cli/useToolBatchStatuses.ts +54 -0
  2278. package/src/shared/hooks/index.ts +3 -0
  2279. package/src/shared/hooks/useCopyToClipboard.ts +38 -0
  2280. package/src/shared/hooks/useDisplayBaseUrl.ts +49 -0
  2281. package/src/shared/hooks/useElectron.ts +197 -0
  2282. package/src/shared/hooks/useTheme.ts +59 -0
  2283. package/src/shared/http/apiErrorMessage.ts +19 -0
  2284. package/src/shared/lib/persistLocale.ts +19 -0
  2285. package/src/shared/middleware/bodySizeGuard.ts +97 -0
  2286. package/src/shared/middleware/chatBodyAdmission.ts +161 -0
  2287. package/src/shared/middleware/correlationId.ts +43 -0
  2288. package/src/shared/network/outboundUrlGuard.ts +276 -0
  2289. package/src/shared/network/remoteImageFetch.ts +182 -0
  2290. package/src/shared/network/safeOutboundFetch.ts +372 -0
  2291. package/src/shared/providers/webSessionCredentials.ts +308 -0
  2292. package/src/shared/reasoning/effortStandardization.ts +124 -0
  2293. package/src/shared/schemas/agentBridge.ts +37 -0
  2294. package/src/shared/schemas/cliCatalog.ts +66 -0
  2295. package/src/shared/schemas/inspector.ts +47 -0
  2296. package/src/shared/schemas/memory.ts +142 -0
  2297. package/src/shared/schemas/playground.ts +67 -0
  2298. package/src/shared/schemas/qdrant.ts +39 -0
  2299. package/src/shared/schemas/quota.ts +61 -0
  2300. package/src/shared/schemas/searchTools.ts +39 -0
  2301. package/src/shared/schemas/validation.ts +154 -0
  2302. package/src/shared/services/apiKeyResolver.ts +44 -0
  2303. package/src/shared/services/backupService.ts +233 -0
  2304. package/src/shared/services/claudeCliConfig.ts +17 -0
  2305. package/src/shared/services/cliRuntime.ts +1099 -0
  2306. package/src/shared/services/cloudSyncScheduler.ts +135 -0
  2307. package/src/shared/services/droidCustomModels.ts +118 -0
  2308. package/src/shared/services/initializeCloudSync.ts +31 -0
  2309. package/src/shared/services/loginShellPath.ts +87 -0
  2310. package/src/shared/services/modelSyncScheduler.ts +225 -0
  2311. package/src/shared/services/opencodeConfig.ts +140 -0
  2312. package/src/shared/services/providerLimitsSyncScheduler.ts +72 -0
  2313. package/src/shared/types/cliBatchStatus.ts +18 -0
  2314. package/src/shared/types/index.ts +3 -0
  2315. package/src/shared/types/pagination.ts +61 -0
  2316. package/src/shared/types/utilization.ts +405 -0
  2317. package/src/shared/utils/a11yAudit.ts +140 -0
  2318. package/src/shared/utils/api.ts +112 -0
  2319. package/src/shared/utils/apiAuth.ts +354 -0
  2320. package/src/shared/utils/apiKey.ts +92 -0
  2321. package/src/shared/utils/apiKeyPolicy.ts +680 -0
  2322. package/src/shared/utils/apiResponse.ts +79 -0
  2323. package/src/shared/utils/bulkApiKeyParser.ts +113 -0
  2324. package/src/shared/utils/circuitBreaker.ts +611 -0
  2325. package/src/shared/utils/classify429.ts +253 -0
  2326. package/src/shared/utils/cliCompat.ts +5 -0
  2327. package/src/shared/utils/clineAuth.ts +62 -0
  2328. package/src/shared/utils/clipboard.ts +49 -0
  2329. package/src/shared/utils/cloud.ts +41 -0
  2330. package/src/shared/utils/cn.ts +12 -0
  2331. package/src/shared/utils/codexBaseUrl.ts +32 -0
  2332. package/src/shared/utils/codexConfig.ts +30 -0
  2333. package/src/shared/utils/compressionHeaderEcho.ts +59 -0
  2334. package/src/shared/utils/cors.ts +24 -0
  2335. package/src/shared/utils/costEstimator.ts +126 -0
  2336. package/src/shared/utils/dashboardCsrf.ts +196 -0
  2337. package/src/shared/utils/featureFlags.ts +113 -0
  2338. package/src/shared/utils/fetchError.ts +26 -0
  2339. package/src/shared/utils/fetchTimeout.ts +78 -0
  2340. package/src/shared/utils/formatting.ts +183 -0
  2341. package/src/shared/utils/freeModels.ts +112 -0
  2342. package/src/shared/utils/index.ts +39 -0
  2343. package/src/shared/utils/inputSanitizer.ts +339 -0
  2344. package/src/shared/utils/linkify.ts +54 -0
  2345. package/src/shared/utils/logRedaction.ts +108 -0
  2346. package/src/shared/utils/logger.ts +173 -0
  2347. package/src/shared/utils/machine.ts +5 -0
  2348. package/src/shared/utils/machineId.ts +167 -0
  2349. package/src/shared/utils/maskEmail.ts +77 -0
  2350. package/src/shared/utils/modelCatalogSearch.ts +84 -0
  2351. package/src/shared/utils/noAuthProviders.ts +79 -0
  2352. package/src/shared/utils/nodeRuntimeSupport.ts +112 -0
  2353. package/src/shared/utils/parseApiKeys.ts +41 -0
  2354. package/src/shared/utils/providerDisplayLabel.ts +41 -0
  2355. package/src/shared/utils/providerHints.ts +73 -0
  2356. package/src/shared/utils/providerModelAliases.ts +68 -0
  2357. package/src/shared/utils/rateLimiter.ts +243 -0
  2358. package/src/shared/utils/releaseNotes.ts +53 -0
  2359. package/src/shared/utils/requestId.ts +102 -0
  2360. package/src/shared/utils/requestTelemetry.ts +189 -0
  2361. package/src/shared/utils/requestTimeout.ts +64 -0
  2362. package/src/shared/utils/resolveOmniRouteBaseUrl.ts +24 -0
  2363. package/src/shared/utils/runtimeTimeouts.ts +257 -0
  2364. package/src/shared/utils/secretsValidator.ts +135 -0
  2365. package/src/shared/utils/secureRandom.ts +66 -0
  2366. package/src/shared/utils/serviceTierLabels.ts +42 -0
  2367. package/src/shared/utils/shuffleDeck.ts +147 -0
  2368. package/src/shared/utils/sidebarRouteMatch.ts +43 -0
  2369. package/src/shared/utils/streamTracker.ts +187 -0
  2370. package/src/shared/utils/structuredLogger.ts +219 -0
  2371. package/src/shared/utils/tiktokenCounter.ts +21 -0
  2372. package/src/shared/utils/turkishText.ts +66 -0
  2373. package/src/shared/utils/upstreamError.ts +112 -0
  2374. package/src/shared/validation/compressionConfigSchemas.ts +234 -0
  2375. package/src/shared/validation/freeProxySchemas.ts +111 -0
  2376. package/src/shared/validation/helpers.ts +117 -0
  2377. package/src/shared/validation/oneproxySchemas.ts +14 -0
  2378. package/src/shared/validation/providerSchema.ts +51 -0
  2379. package/src/shared/validation/providerSpecificData.ts +354 -0
  2380. package/src/shared/validation/schemas/apiV1.ts +297 -0
  2381. package/src/shared/validation/schemas/auth.ts +200 -0
  2382. package/src/shared/validation/schemas/cli.ts +86 -0
  2383. package/src/shared/validation/schemas/cloud.ts +53 -0
  2384. package/src/shared/validation/schemas/combo.ts +373 -0
  2385. package/src/shared/validation/schemas/evals.ts +86 -0
  2386. package/src/shared/validation/schemas/gemini.ts +59 -0
  2387. package/src/shared/validation/schemas/keys.ts +144 -0
  2388. package/src/shared/validation/schemas/misc.ts +203 -0
  2389. package/src/shared/validation/schemas/payloadRules.ts +64 -0
  2390. package/src/shared/validation/schemas/pricing.ts +40 -0
  2391. package/src/shared/validation/schemas/provider.ts +430 -0
  2392. package/src/shared/validation/schemas/proxy.ts +243 -0
  2393. package/src/shared/validation/schemas/routing.ts +88 -0
  2394. package/src/shared/validation/schemas/settings.ts +267 -0
  2395. package/src/shared/validation/schemas/translator.ts +44 -0
  2396. package/src/shared/validation/schemas.ts +18 -0
  2397. package/src/shared/validation/settingsSchemas.ts +396 -0
  2398. package/src/sse/handlers/chat.ts +1750 -0
  2399. package/src/sse/handlers/chatHelpers.ts +859 -0
  2400. package/src/sse/handlers/requestBody.ts +24 -0
  2401. package/src/sse/handlers/resolveRoutingModel.ts +17 -0
  2402. package/src/sse/services/auth.ts +2446 -0
  2403. package/src/sse/services/cooldownAwareRetry.ts +162 -0
  2404. package/src/sse/services/model.ts +254 -0
  2405. package/src/sse/services/noAuthProviderSettings.ts +18 -0
  2406. package/src/sse/services/noAuthProxyResolution.ts +111 -0
  2407. package/src/sse/services/sessionAffinityPin.ts +247 -0
  2408. package/src/sse/services/streamState.ts +218 -0
  2409. package/src/sse/services/tokenRefresh.ts +275 -0
  2410. package/src/sse/utils/logger.ts +37 -0
  2411. package/src/types/databaseSettings.ts +124 -0
  2412. package/src/types/global.d.ts +122 -0
  2413. package/src/types/index.ts +10 -0
  2414. package/src/types/provider.ts +9 -0
  2415. package/src/types/sqljs.d.ts +32 -0
@@ -0,0 +1,1750 @@
1
+ import { randomUUID } from "crypto";
2
+ import { resolveChatRequestBody } from "./requestBody";
3
+ import { normalizeReasoningRequest } from "@/shared/reasoning/effortStandardization";
4
+ import { resolveRoutingModel } from "./resolveRoutingModel";
5
+ import {
6
+ getProviderCredentialsWithQuotaPreflight,
7
+ markAccountUnavailable,
8
+ extractApiKey,
9
+ isValidApiKey,
10
+ extractSessionAffinityKey,
11
+ } from "../services/auth";
12
+ import {
13
+ getRuntimeProviderProfile,
14
+ shouldMarkAccountExhaustedFrom429,
15
+ clearModelLock,
16
+ lockModel,
17
+ recordModelLockoutFailure,
18
+ isDailyQuotaExhausted,
19
+ } from "@omniroute/open-sse/services/accountFallback.ts";
20
+ import { getModelInfo, getComboForModel } from "../services/model";
21
+ import { resolveBareModelToConnectionDefault } from "@omniroute/open-sse/services/model.ts";
22
+ import { errorResponse } from "@omniroute/open-sse/utils/error.ts";
23
+ import { acceptHeaderForcesStream } from "@omniroute/open-sse/utils/aiSdkCompat.ts";
24
+ import { isSelfInflictedUpstreamTimeout } from "@omniroute/open-sse/handlers/chatCore/cooldownClassification.ts";
25
+ import { applyNoThinkingAlias } from "@omniroute/open-sse/utils/noThinkingAlias.ts";
26
+ import { handleComboChat } from "@omniroute/open-sse/services/combo.ts";
27
+ import {
28
+ resolveRequestModePack,
29
+ parseRequestBudgetCap,
30
+ } from "@omniroute/open-sse/services/autoCombo/requestControls.ts";
31
+ import { resolveComboConfig } from "@omniroute/open-sse/services/comboConfig.ts";
32
+ import { injectHandoffIntoBody } from "@omniroute/open-sse/services/contextHandoff.ts";
33
+ import {
34
+ HTTP_STATUS,
35
+ ANTIGRAVITY_PRE_RESPONSE_TIMEOUT_CODE,
36
+ } from "@omniroute/open-sse/config/constants.ts";
37
+ import { getTargetFormat } from "@omniroute/open-sse/services/provider.ts";
38
+ import {
39
+ getModelTargetFormat,
40
+ PROVIDER_ID_TO_ALIAS,
41
+ } from "@omniroute/open-sse/config/providerModels.ts";
42
+ import type { AutoVariant } from "@omniroute/open-sse/services/autoCombo/autoPrefix.ts";
43
+ import {
44
+ AUTO_TEMPLATE_VARIANTS,
45
+ VALID_AUTO_VARIANTS,
46
+ } from "@omniroute/open-sse/services/autoCombo/builtinCatalog.ts";
47
+ import {
48
+ parseAutoSuffix,
49
+ type AutoCategory,
50
+ type AutoTier,
51
+ } from "@omniroute/open-sse/services/autoCombo/suffixComposition.ts";
52
+ import * as log from "../utils/logger";
53
+ import { checkAndRefreshToken } from "../services/tokenRefresh";
54
+ import { createHookContext, runHooks, initPreRequestRegistry } from "@/lib/middleware/registry";
55
+ import { deleteHandoff, getHandoff } from "@/lib/db/contextHandoffs";
56
+ import { updateCombo } from "@/lib/db/combos";
57
+ import { promoteSuccessfulComboModel } from "@/lib/combos/autoPromote";
58
+ import {
59
+ deleteSessionAccountAffinity,
60
+ evictSessionAccountAffinityForConnection,
61
+ getCachedSettings,
62
+ getCombos,
63
+ getCombosCacheVersion,
64
+ getSessionAccountAffinity,
65
+ } from "@/lib/localDb";
66
+ import { resolveModelLockoutSettings } from "@/lib/resilience/modelLockoutSettings";
67
+ import {
68
+ ensureOpenAIStoreSessionFallback,
69
+ isOpenAIResponsesStoreEnabled,
70
+ } from "@/lib/providers/requestDefaults";
71
+ import { guardrailRegistry, resolveDisabledGuardrails } from "@/lib/guardrails";
72
+ import {
73
+ resolveModelOrError,
74
+ checkPipelineGates,
75
+ executeChatWithBreaker,
76
+ handleNoCredentials,
77
+ safeResolveProxy,
78
+ safeLogEvents,
79
+ applyExecutorProxyToInfo,
80
+ shouldRetryStreamEarlyEof,
81
+ withSessionHeader,
82
+ withSelectedConnectionHeader,
83
+ withCorrelationId,
84
+ } from "./chatHelpers";
85
+ import { connectionHasExtraKeys } from "@omniroute/open-sse/services/apiKeyRotator.ts";
86
+
87
+ // Pipeline integration — wired modules
88
+ import { classify429FromError, type FailureKind } from "@/shared/utils/classify429";
89
+ import { resolveUseUpstream429BreakerHints } from "@/shared/utils/providerHints";
90
+ import { getCircuitBreaker, isLocalStreamLifecycleError } from "../../shared/utils/circuitBreaker";
91
+ import { markAccountExhaustedFrom429 } from "../../domain/quotaCache";
92
+ import { RequestTelemetry, recordTelemetry } from "../../shared/utils/requestTelemetry";
93
+ import { generateRequestId } from "../../shared/utils/requestId";
94
+ import { logAuditEvent } from "../../lib/compliance/index";
95
+ import { enforceApiKeyPolicy } from "../../shared/utils/apiKeyPolicy";
96
+ import { hasProviderQuotaBypassScope } from "../../shared/constants/apiKeyPolicyScopes";
97
+ import { cloneLogPayload } from "@/lib/logPayloads";
98
+ import { handleInternalUsageCommand } from "@/lib/usage/internalUsageCommand";
99
+ import {
100
+ applyTaskAwareRouting,
101
+ getTaskRoutingConfig,
102
+ } from "@omniroute/open-sse/services/taskAwareRouter.ts";
103
+ import {
104
+ hasNativeWebSearchTool,
105
+ resolveWebSearchRouteOverride,
106
+ } from "@omniroute/open-sse/services/webSearchRouting.ts";
107
+ import {
108
+ generateSessionId as generateStableSessionId,
109
+ touchSession,
110
+ extractExternalSessionId,
111
+ checkSessionLimit,
112
+ registerKeySession,
113
+ isSessionRegisteredForKey,
114
+ } from "@omniroute/open-sse/services/sessionManager.ts";
115
+ import { startQuotaMonitor } from "@omniroute/open-sse/services/quotaMonitor.ts";
116
+ import {
117
+ isFallbackDecision,
118
+ shouldUseFallback,
119
+ } from "@omniroute/open-sse/services/emergencyFallback.ts";
120
+ import {
121
+ registerCodexConnection,
122
+ registerCodexQuotaFetcher,
123
+ } from "@omniroute/open-sse/services/codexQuotaFetcher.ts";
124
+ import { registerBailianCodingPlanQuotaFetcher } from "@omniroute/open-sse/services/bailianQuotaFetcher.ts";
125
+ import { registerCrofUsageFetcher } from "@omniroute/open-sse/services/crofUsageFetcher.ts";
126
+ import { registerDeepseekQuotaFetcher } from "@omniroute/open-sse/services/deepseekQuotaFetcher.ts";
127
+ import { registerOpencodeQuotaFetcher } from "@omniroute/open-sse/services/opencodeQuotaFetcher.ts";
128
+ import { registerGenericQuotaFetchers } from "@omniroute/open-sse/services/genericQuotaFetcher.ts";
129
+ import {
130
+ getCooldownAwareRetryDecision,
131
+ resolveCooldownAwareRetrySettings,
132
+ waitForCooldownAwareRetry,
133
+ } from "../services/cooldownAwareRetry";
134
+ import { constrainConnectionsToQuota, resolveQuotaKeyScope } from "../../lib/quota/quotaKey";
135
+
136
+ registerCodexQuotaFetcher();
137
+
138
+ // Register Bailian Coding Plan quota fetcher at module load (once per server start).
139
+ // This hooks into the quotaPreflight + quotaMonitor systems so that combos
140
+ // can proactively switch accounts before quota is exhausted.
141
+ registerBailianCodingPlanQuotaFetcher();
142
+
143
+ // Register CrofAI usage fetcher (subscription requests + credits balance).
144
+ // Surfaces usable_requests + credits in the monitor and only blocks (preflight
145
+ // opt-in) when the active bucket reaches zero.
146
+ registerCrofUsageFetcher();
147
+
148
+ // Register DeepSeek balance quota fetcher.
149
+ // Hooks into quotaPreflight + quotaMonitor so combos can switch accounts before balance is exhausted.
150
+ registerDeepseekQuotaFetcher();
151
+
152
+ // Register OpenCode quota fetcher (opencode-go / opencode / opencode-zen).
153
+ // Surfaces the $12/5h, $30/wk, $60/mo windows in the limits page and enables
154
+ // quota-aware preflight switching between connections. (#2852)
155
+ registerOpencodeQuotaFetcher();
156
+
157
+ // Register the generic quota fetcher for every other provider that has a
158
+ // usage implementation in usage.ts but no bespoke preflight fetcher. This is
159
+ // what lets the per-window cutoff modal in Dashboard › Limits actually
160
+ // enforce thresholds for Claude / GLM / Cursor / etc., not just Codex.
161
+ registerGenericQuotaFetchers();
162
+ let combosCachePromise: Promise<unknown[]> | null = null;
163
+ let combosCacheTs = 0;
164
+ let combosCacheVersionSnapshot = -1;
165
+ const COMBOS_CACHE_TTL_MS = 10_000;
166
+
167
+ async function getCombosCachedForChat(): Promise<unknown[]> {
168
+ const now = Date.now();
169
+ // Explicit non-null check: we intentionally cache and return the Promise
170
+ // itself (to dedupe concurrent callers), so this is not a forgotten await.
171
+ // The version check makes combo edits (create/update/delete/reorder) take
172
+ // effect immediately instead of after the 10s TTL — otherwise a removed
173
+ // target/model could keep being served as a "phantom" for up to 10s (#3147).
174
+ if (
175
+ combosCachePromise !== null &&
176
+ now - combosCacheTs < COMBOS_CACHE_TTL_MS &&
177
+ combosCacheVersionSnapshot === getCombosCacheVersion()
178
+ ) {
179
+ return combosCachePromise;
180
+ }
181
+
182
+ combosCacheTs = now;
183
+ combosCacheVersionSnapshot = getCombosCacheVersion();
184
+ combosCachePromise = getCombos().catch(() => []);
185
+ return combosCachePromise;
186
+ }
187
+
188
+ function normalizeAllowedConnectionIds(value: unknown): string[] | null {
189
+ if (!Array.isArray(value)) return null;
190
+ const ids = value.filter(
191
+ (entry): entry is string => typeof entry === "string" && entry.trim().length > 0
192
+ );
193
+ return ids.length > 0 ? ids : null;
194
+ }
195
+
196
+ function intersectAllowedConnectionIds(primary: unknown, secondary: unknown): string[] | null {
197
+ const first = normalizeAllowedConnectionIds(primary);
198
+ const second = normalizeAllowedConnectionIds(secondary);
199
+
200
+ if (first && second) {
201
+ return first.filter((id) => second.includes(id));
202
+ }
203
+
204
+ return first || second || null;
205
+ }
206
+
207
+ const PROVIDER_BREAKER_FAILURE_STATUSES = new Set([408, 500, 502, 503, 504]);
208
+ const comboPromoteDeps = { updateCombo, info: log.info, warn: log.warn };
209
+
210
+ /**
211
+ * Handle chat completion request
212
+ * Supports: OpenAI, Claude, Gemini, OpenAI Responses API formats
213
+ * Format detection and translation handled by translator
214
+ */
215
+ export async function handleChat(
216
+ request: any,
217
+ clientRawRequest: any = null,
218
+ preParsedBody: any = null,
219
+ correlationId?: string
220
+ ) {
221
+ // Pipeline: Start request telemetry
222
+ const reqId = correlationId || generateRequestId();
223
+ const telemetry = new RequestTelemetry(reqId);
224
+
225
+ let body;
226
+ try {
227
+ telemetry.startPhase("parse");
228
+ body = await resolveChatRequestBody(request, preParsedBody);
229
+ telemetry.endPhase();
230
+ } catch {
231
+ log.warn("CHAT", "Invalid JSON body");
232
+ return errorResponse(HTTP_STATUS.BAD_REQUEST, "Invalid JSON body");
233
+ }
234
+
235
+ // Feature #6241: fold the canonical `effort` / `thinking` request params onto the
236
+ // per-provider reasoning fields (reasoning_effort / reasoning.effort / thinking) that the
237
+ // existing translators already consume. Done here — right after the body is first
238
+ // resolved, before any reasoning field is read below — so it flows uniformly into every
239
+ // downstream mapper (Anthropic / Gemini / xAI / Responses). An explicit client
240
+ // reasoning_effort / reasoning / object-shaped thinking always wins (backward compatible).
241
+ body = normalizeReasoningRequest(body);
242
+
243
+ // Early guard: an explicitly empty `messages` array is invalid for every
244
+ // upstream (Anthropic/OpenAI both reject "at least one message is required").
245
+ // Forwarding it produced a confusing raw upstream 400/502; reject it here with
246
+ // a clear OmniRoute-level error before any routing or upstream call (#5110).
247
+ // Responses-API requests use `input` (not `messages`) so they are unaffected,
248
+ // and an absent `messages` field is left to downstream validation.
249
+ if (
250
+ Array.isArray((body as { messages?: unknown }).messages) &&
251
+ (body as { messages: unknown[] }).messages.length === 0
252
+ ) {
253
+ log.warn("CHAT", "Rejecting request with empty messages array");
254
+ return errorResponse(HTTP_STATUS.BAD_REQUEST, "messages: at least one message is required");
255
+ }
256
+
257
+ // Reject non-string `model` before it reaches downstream code that calls
258
+ // `.toLowerCase()` / `.split()` / `.startsWith()` on it (crash-then-500 with an
259
+ // empty body, escaping the error sanitizer — #6407). An explicit `null`/`undefined`
260
+ // stays permitted here because the existing `Missing model` guard below returns a
261
+ // clean 400 for those; anything else that is not a string is a client type error.
262
+ const rawModel = (body as { model?: unknown }).model;
263
+ if (rawModel !== undefined && rawModel !== null && typeof rawModel !== "string") {
264
+ log.warn("CHAT", `Rejecting non-string model (typeof=${typeof rawModel})`);
265
+ return errorResponse(
266
+ HTTP_STATUS.BAD_REQUEST,
267
+ `model: Expected string, received ${Array.isArray(rawModel) ? "array" : typeof rawModel}`
268
+ );
269
+ }
270
+
271
+ // Early schema validation for scalar params BEFORE provider/model resolution (#6412).
272
+ // Previously, a bad `temperature: "not-a-number"` on an unknown provider returned
273
+ // 404 "model_not_found" — hiding the real schema error. Validate the param shape
274
+ // first so the client gets a 400 with the field name. Kept narrow to widely-supported
275
+ // OpenAI-spec params (temperature 0..2, top_p 0..1, max_tokens int >=1) so we don't
276
+ // reject legitimate provider-specific fields.
277
+ {
278
+ const b = body as {
279
+ temperature?: unknown;
280
+ top_p?: unknown;
281
+ max_tokens?: unknown;
282
+ n?: unknown;
283
+ };
284
+ const badParam = (name: string, msg: string) =>
285
+ errorResponse(HTTP_STATUS.BAD_REQUEST, `${name}: ${msg}`);
286
+ if (b.temperature !== undefined) {
287
+ if (typeof b.temperature !== "number" || Number.isNaN(b.temperature)) {
288
+ return badParam("temperature", "must be a number");
289
+ }
290
+ if (b.temperature < 0 || b.temperature > 2) {
291
+ return badParam("temperature", "must be between 0 and 2");
292
+ }
293
+ }
294
+ if (b.top_p !== undefined) {
295
+ if (typeof b.top_p !== "number" || Number.isNaN(b.top_p)) {
296
+ return badParam("top_p", "must be a number");
297
+ }
298
+ if (b.top_p < 0 || b.top_p > 1) {
299
+ return badParam("top_p", "must be between 0 and 1");
300
+ }
301
+ }
302
+ if (b.max_tokens !== undefined) {
303
+ if (
304
+ typeof b.max_tokens !== "number" ||
305
+ !Number.isInteger(b.max_tokens) ||
306
+ b.max_tokens < 1
307
+ ) {
308
+ return badParam("max_tokens", "must be a positive integer");
309
+ }
310
+ }
311
+ if (b.n !== undefined) {
312
+ if (typeof b.n !== "number" || !Number.isInteger(b.n) || b.n < 1) {
313
+ return badParam("n", "must be a positive integer");
314
+ }
315
+ }
316
+ }
317
+
318
+ // buildClientRawRequest already deep-clones the body, so pass `body` directly — the
319
+ // prior local clone was a redundant second full-body copy on the hot path (#5152).
320
+ if (!clientRawRequest) {
321
+ clientRawRequest = buildClientRawRequest(request, body);
322
+ }
323
+
324
+ // T01 — Accept-header streaming opt-in (#302 / #5305). A bare `Accept:
325
+ // text/event-stream` with `stream` omitted opts a curl/httpx-style client into
326
+ // SSE; a client that ALSO lists application/json (OpenAI / Vercel AI SDK
327
+ // non-stream signature) does NOT — it expects a JSON object. An explicit body
328
+ // `stream` value (true or false) always wins. See acceptHeaderForcesStream.
329
+ const acceptHeader = request.headers.get("accept") || "";
330
+ if (acceptHeaderForcesStream(acceptHeader, body.stream)) {
331
+ body = { ...body, stream: true };
332
+ log.debug(
333
+ "STREAM",
334
+ "Accept: text/event-stream header → overriding stream=true (body had no stream field)"
335
+ );
336
+ }
337
+
338
+ // Log request endpoint and model
339
+ const url = new URL(request.url);
340
+
341
+ // No-thinking gateway alias (Fase 8.1): `no-think/<provider>/<model>`
342
+ // resolves back to the real model with reasoning suppressed in place, before any
343
+ // model resolution / combo routing sees it. Claude/Messages path forces
344
+ // `thinking:{type:"disabled"}`; OpenAI path drops the reasoning fields.
345
+ const noThinking = applyNoThinkingAlias(body, {
346
+ claudeFormat: url.pathname.includes("/messages"),
347
+ });
348
+ if (noThinking.applied) {
349
+ log.debug("NO_THINKING", `Resolved no-thinking alias → ${noThinking.realModel}`);
350
+ }
351
+
352
+ // X-Route-Model header overrides body.model for routing purposes (see
353
+ // resolveRoutingModel). The resolved model still passes through
354
+ // enforceApiKeyPolicy below, so it cannot bypass per-key allowlists.
355
+ let modelStr = resolveRoutingModel(request, body);
356
+
357
+ // Count messages (support both messages[] and input[] formats)
358
+ const msgCount = body.messages?.length || body.input?.length || 0;
359
+ const toolCount = body.tools?.length || 0;
360
+ const effort = body.reasoning_effort || body.reasoning?.effort || null;
361
+ log.request(
362
+ "POST",
363
+ `${url.pathname} | ${modelStr} | ${msgCount} msgs${toolCount ? ` | ${toolCount} tools` : ""}${effort ? ` | effort=${effort}` : ""}`
364
+ );
365
+
366
+ // Log only that an API key was provided — never the key itself, not even a
367
+ // masked prefix/last4. These debug lines get copied verbatim into bug reports
368
+ // and support tickets, so any key fragment is sensitive.
369
+ const authHeader = request.headers.get("Authorization");
370
+ const apiKey = extractApiKey(request);
371
+ if (authHeader && apiKey) {
372
+ log.debug("AUTH", "API key provided");
373
+ } else {
374
+ log.debug("AUTH", "No API key provided (local mode)");
375
+ }
376
+
377
+ const internalUsageCommandResponse = await handleInternalUsageCommand(request, body);
378
+ if (internalUsageCommandResponse) {
379
+ recordTelemetry(telemetry);
380
+ return internalUsageCommandResponse;
381
+ }
382
+
383
+ const isComboLiveTest = request.headers?.get?.("x-internal-test") === "combo-health-check";
384
+
385
+ if (!modelStr) {
386
+ log.warn("CHAT", "Missing model");
387
+ return errorResponse(HTTP_STATUS.BAD_REQUEST, "Missing model");
388
+ }
389
+
390
+ // T04: client-provided external session header has priority over generated fingerprint.
391
+ const externalSessionId = extractExternalSessionId(request.headers);
392
+ const sessionId = externalSessionId || generateStableSessionId(body);
393
+ const sessionAffinityKey = extractSessionAffinityKey(body, request.headers) || sessionId;
394
+ const requestedConnectionId = request.headers.get("x-omniroute-connection")?.trim() || null;
395
+ if (sessionId) {
396
+ touchSession(sessionId);
397
+ }
398
+
399
+ // Pipeline: API key policy enforcement (model restrictions + budget limits)
400
+ telemetry.startPhase("policy");
401
+ const policy = await enforceApiKeyPolicy(request, modelStr);
402
+ if (policy.rejection) {
403
+ log.warn(
404
+ "POLICY",
405
+ `API key policy rejected: ${modelStr} (key=${policy.apiKeyInfo?.id || "unknown"})`
406
+ );
407
+ return policy.rejection;
408
+ }
409
+ const apiKeyInfo = policy.apiKeyInfo;
410
+ const bypassProviderQuotaPolicy = hasProviderQuotaBypassScope(apiKeyInfo?.scopes);
411
+ telemetry.endPhase();
412
+
413
+ // Guardrail pre-call pipeline — prompt injection, PII masking, and future custom rules.
414
+ telemetry.startPhase("validate");
415
+ const preCallGuardrails = await guardrailRegistry.runPreCallHooks(body, {
416
+ apiKeyInfo: apiKeyInfo as any,
417
+ disabledGuardrails: resolveDisabledGuardrails({
418
+ apiKeyInfo: (apiKeyInfo ?? null) as any,
419
+ body,
420
+ headers: request.headers,
421
+ }),
422
+ endpoint: new URL(request.url).pathname,
423
+ headers: request.headers,
424
+ log,
425
+ method: request.method,
426
+ model: modelStr,
427
+ stream: body?.stream === true,
428
+ });
429
+ if (preCallGuardrails.blocked) {
430
+ log.warn("GUARDRAIL", "Request blocked during pre-call guardrails", {
431
+ guardrail: preCallGuardrails.guardrail,
432
+ message: preCallGuardrails.message,
433
+ });
434
+ return errorResponse(
435
+ HTTP_STATUS.BAD_REQUEST,
436
+ preCallGuardrails.message || "Request rejected: suspicious content detected"
437
+ );
438
+ }
439
+ body = preCallGuardrails.payload;
440
+ telemetry.endPhase();
441
+
442
+ // T08: per-key active session limit (0 = unlimited).
443
+ if (apiKeyInfo?.id && sessionId) {
444
+ const maxSessions =
445
+ typeof apiKeyInfo.maxSessions === "number" && apiKeyInfo.maxSessions > 0
446
+ ? apiKeyInfo.maxSessions
447
+ : 0;
448
+
449
+ if (maxSessions > 0 && !isSessionRegisteredForKey(apiKeyInfo.id, sessionId)) {
450
+ const sessionViolation = checkSessionLimit(apiKeyInfo.id, maxSessions);
451
+ if (sessionViolation) {
452
+ return withSessionHeader(
453
+ errorResponse(HTTP_STATUS.RATE_LIMITED, sessionViolation.message),
454
+ sessionId
455
+ );
456
+ }
457
+ registerKeySession(apiKeyInfo.id, sessionId);
458
+ }
459
+ }
460
+
461
+ // T09 — Pre-request Middleware Hooks
462
+ // Execute user-defined hooks BEFORE task-aware routing and combo selection
463
+ initPreRequestRegistry();
464
+ const hookContext = createHookContext({
465
+ body: body as Record<string, unknown>,
466
+ headers: Object.fromEntries(request?.headers?.entries() || []) as Record<
467
+ string,
468
+ string | string[] | undefined
469
+ >,
470
+ model: modelStr,
471
+ combo: undefined,
472
+ apiKeyInfo: apiKeyInfo as Record<string, unknown> | undefined,
473
+ log,
474
+ });
475
+
476
+ const { context: hookCtx, response: hookResponse } = await runHooks(hookContext);
477
+
478
+ // Apply hook mutations
479
+ body = hookCtx.body as any;
480
+ if (hookCtx.model && hookCtx.model !== modelStr) {
481
+ modelStr = hookCtx.model;
482
+ }
483
+
484
+ // Short-circuit if a hook returned a direct response
485
+ if (hookResponse) {
486
+ return errorResponse(hookResponse.status, hookResponse.body as any);
487
+ }
488
+
489
+ // T05 — Task-Aware Smart Routing
490
+ // Detect the semantic task type and optionally route to the optimal model
491
+ let resolvedModelStr = modelStr;
492
+ let taskRouteInfo: { taskType: string; wasRouted: boolean } | null = null;
493
+ if (getTaskRoutingConfig().enabled) {
494
+ telemetry.startPhase("task-route");
495
+ const tr = applyTaskAwareRouting(modelStr, body);
496
+ if (tr.wasRouted) {
497
+ resolvedModelStr = tr.model;
498
+ body = { ...body, model: tr.model };
499
+ log.info(
500
+ "T05",
501
+ `Task-Aware: detected="${tr.taskType}" → model override: ${modelStr} → ${tr.model}`
502
+ );
503
+ } else if (tr.taskType !== "chat") {
504
+ log.debug("T05", `Task-Aware: detected="${tr.taskType}" (no override configured)`);
505
+ }
506
+ taskRouteInfo = { taskType: tr.taskType, wasRouted: tr.wasRouted };
507
+ telemetry.endPhase();
508
+ }
509
+
510
+ // #4481 layer 2 — Web-Search Routing (CCR-style Router.webSearch): a native web_search
511
+ // server tool + a configured `webSearchRouteModel` routes the whole request to that
512
+ // model (some providers don't implement Anthropic's web_search_20250305 server tool).
513
+ // Settings are read only when a web-search tool is present; the override lands before
514
+ // auto/combo resolution and the layer-1 fallback so the target's own handling applies.
515
+ if (hasNativeWebSearchTool(body)) {
516
+ const wsSettings = await getCachedSettings().catch(() => ({}) as Record<string, unknown>);
517
+ const wsRoute = resolveWebSearchRouteOverride(resolvedModelStr, body, wsSettings);
518
+ if (wsRoute.wasRouted) {
519
+ log.info(
520
+ "WEBSEARCH-ROUTE",
521
+ `web_search tool → model override: ${resolvedModelStr} → ${wsRoute.model}`
522
+ );
523
+ resolvedModelStr = wsRoute.model;
524
+ body = { ...body, model: wsRoute.model };
525
+ }
526
+ }
527
+
528
+ // ── Zero-Config Auto-Routing (auto and auto/ prefix) ────────────────────────
529
+ // If the model ID is "auto" or starts with "auto/", bypass DB combo lookup
530
+ // entirely and generate a virtual auto-combo on-the-fly from connected providers.
531
+ let autoVariant: AutoVariant | undefined;
532
+ // #4235 Phase B: `auto/<category>:<tier>` overlay (e.g. auto/coding:fast, auto/vision).
533
+ let autoSpec: { category?: AutoCategory; tier?: AutoTier } | undefined;
534
+ let isAutoRouting = resolvedModelStr === "auto" || resolvedModelStr.startsWith("auto/");
535
+ let recognizedBuiltInAuto = resolvedModelStr === "auto";
536
+ if (Object.prototype.hasOwnProperty.call(AUTO_TEMPLATE_VARIANTS, resolvedModelStr)) {
537
+ recognizedBuiltInAuto = true;
538
+ autoVariant = AUTO_TEMPLATE_VARIANTS[resolvedModelStr];
539
+ } else if (resolvedModelStr.startsWith("auto/")) {
540
+ const suffix = resolvedModelStr.slice(5);
541
+ if (VALID_AUTO_VARIANTS.has(suffix as AutoVariant)) {
542
+ recognizedBuiltInAuto = true;
543
+ } else {
544
+ const parsedSuffix = parseAutoSuffix(suffix);
545
+ if (parsedSuffix.valid) {
546
+ recognizedBuiltInAuto = true;
547
+ autoSpec = { category: parsedSuffix.category, tier: parsedSuffix.tier };
548
+ }
549
+ }
550
+ }
551
+
552
+ if (isAutoRouting) {
553
+ // C2: Enforce autoRoutingEnabled setting.
554
+ // Issue #2346: `getSettings` was never imported in this module; only
555
+ // `getCachedSettings` is. Calling the bare name caused a ReferenceError
556
+ // on every auto-routed request. The cached variant has the same shape
557
+ // and benefits the auto-routing hot path.
558
+ const settings = await getCachedSettings().catch(() => ({}) as Record<string, unknown>);
559
+ if (settings?.autoRoutingEnabled === false) {
560
+ return errorResponse(
561
+ HTTP_STATUS.BAD_REQUEST,
562
+ "Auto routing is disabled. Enable it in Settings > Routing."
563
+ );
564
+ }
565
+
566
+ try {
567
+ const { parseAutoPrefix } =
568
+ await import("@omniroute/open-sse/services/autoCombo/autoPrefix.ts");
569
+ const parsed = parseAutoPrefix(resolvedModelStr);
570
+ if (parsed.valid) {
571
+ if (!Object.prototype.hasOwnProperty.call(AUTO_TEMPLATE_VARIANTS, resolvedModelStr)) {
572
+ autoVariant = parsed.variant;
573
+ }
574
+ // C3: Apply autoRoutingDefaultVariant from settings when bare "auto" is used
575
+ if (
576
+ resolvedModelStr === "auto" &&
577
+ autoVariant === undefined &&
578
+ settings?.autoRoutingDefaultVariant
579
+ ) {
580
+ autoVariant = settings.autoRoutingDefaultVariant as AutoVariant;
581
+ }
582
+ log.info(
583
+ "AUTO",
584
+ `Zero-config routing variant: ${autoVariant || "default"} (model=${resolvedModelStr})`
585
+ );
586
+ } else if (!autoSpec) {
587
+ log.warn("AUTO", `Invalid auto prefix format: ${resolvedModelStr}`);
588
+ }
589
+ } catch (err) {
590
+ log.error("AUTO", "Failed to load auto-prefix parser", { err });
591
+ }
592
+ }
593
+ // ────────────────────────────────────────────────────────────────────────────
594
+
595
+ // Check if model is a combo (has multiple models with fallback)
596
+ telemetry.startPhase("resolve");
597
+ let combo: any = await getComboForModel(resolvedModelStr);
598
+
599
+ // "auto" prefix fuzzy matching: "auto/fast" → "auto/best-fast", etc.
600
+ // parseModel splits "auto/fast" into provider="auto" which isn't a real provider.
601
+ if (!combo && resolvedModelStr.startsWith("auto/")) {
602
+ const suffix = resolvedModelStr.slice(5);
603
+ for (const candidate of [`auto/best-${suffix}`, `auto/${suffix}`]) {
604
+ combo = await getComboForModel(candidate);
605
+ if (combo) {
606
+ log.info("ROUTING", `"${resolvedModelStr}" → combo "${candidate}" (auto fuzzy)`);
607
+ break;
608
+ }
609
+ }
610
+ }
611
+
612
+ // Auto-prefix short-circuit: if a recognized auto/ prefix was detected, replace combo with virtual one
613
+ if (isAutoRouting && combo === null) {
614
+ if (!recognizedBuiltInAuto) {
615
+ return errorResponse(
616
+ HTTP_STATUS.BAD_REQUEST,
617
+ `Model '${resolvedModelStr}' is not a valid combo or provider. Unknown built-in auto combo.`
618
+ );
619
+ }
620
+
621
+ try {
622
+ const { createVirtualAutoCombo } =
623
+ await import("@omniroute/open-sse/services/autoCombo/virtualFactory.ts");
624
+ const virtualCombo = await createVirtualAutoCombo(autoVariant, autoSpec);
625
+ virtualCombo.name = resolvedModelStr;
626
+ virtualCombo.id = resolvedModelStr;
627
+ combo = virtualCombo;
628
+ log.info(
629
+ "AUTO",
630
+ `Virtual auto-combo created: ${combo.name} (${virtualCombo.candidatePool?.length || 0} candidates)`
631
+ );
632
+ } catch (err) {
633
+ log.error("AUTO", "Failed to create virtual auto-combo", { err });
634
+ }
635
+ }
636
+ if (combo) {
637
+ log.info(
638
+ "CHAT",
639
+ `Combo "${modelStr}" [${combo.strategy || "priority"}] with ${combo.models.length} models`
640
+ );
641
+
642
+ // Pre-check function used by combo routing. For explicit combo live tests,
643
+ // avoid pre-skipping so each model gets a real execution attempt.
644
+ const comboPreselectedCredentials = new Map<string, any>();
645
+ const getComboCredentialCacheKey = (
646
+ modelString: string,
647
+ target?: { connectionId?: string | null; executionKey?: string | null }
648
+ ) => `${target?.executionKey || target?.connectionId || ""}:${modelString}`;
649
+ const checkModelAvailable = async (
650
+ modelString: string,
651
+ target?: {
652
+ allowRateLimitedConnection?: boolean;
653
+ connectionId?: string | null;
654
+ allowedConnectionIds?: string[] | null;
655
+ executionKey?: string | null;
656
+ providerId?: string | null;
657
+ }
658
+ ) => {
659
+ if (isComboLiveTest) return true;
660
+
661
+ // Use getModelInfo to resolve custom prefixes, but prefer the combo
662
+ // target's providerId when available — the model string's provider
663
+ // prefix may differ from the credential provider ID (e.g. model
664
+ // "xiaomi/mimo-v2-flash" resolves to provider "xiaomi" but the combo
665
+ // target specifies providerId: "opengate" for credential lookup).
666
+ const modelInfo = await getModelInfo(modelString);
667
+ // Apply the same prefix-override guard as handleSingleModelChat:
668
+ // if providerId is just the prefix already in the model string, use
669
+ // the fully-resolved modelInfo.provider for a precise credential check.
670
+ const provider = (() => {
671
+ if (!target?.providerId) return modelInfo.provider;
672
+ if (target.providerId === modelInfo.provider) return modelInfo.provider;
673
+ if (modelString.startsWith(target.providerId + "/")) return modelInfo.provider;
674
+ return target.providerId;
675
+ })();
676
+ if (!provider) return true; // can't determine provider, let it try
677
+
678
+ const resolvedModel = modelInfo.model || modelString;
679
+ const hasForcedConnection =
680
+ typeof target?.connectionId === "string" && target.connectionId.trim().length > 0;
681
+ let allowedConnections = intersectAllowedConnectionIds(
682
+ apiKeyInfo?.allowedConnections ?? null,
683
+ target?.allowedConnectionIds ?? null
684
+ );
685
+
686
+ // A4: quota-exclusive keys must only use the pool's connection(s).
687
+ if (apiKeyInfo?.allowedQuotas && apiKeyInfo.allowedQuotas.length > 0) {
688
+ const quotaScope = await resolveQuotaKeyScope(apiKeyInfo.allowedQuotas);
689
+ allowedConnections = constrainConnectionsToQuota(
690
+ allowedConnections ?? [],
691
+ quotaScope.connectionIds
692
+ );
693
+ }
694
+
695
+ if (Array.isArray(allowedConnections) && allowedConnections.length === 0) {
696
+ return false;
697
+ }
698
+
699
+ const creds = await getProviderCredentialsWithQuotaPreflight(
700
+ provider,
701
+ null,
702
+ allowedConnections,
703
+ resolvedModel,
704
+ {
705
+ sessionKey: sessionAffinityKey,
706
+ ...(target?.allowRateLimitedConnection ? { allowRateLimitedConnections: true } : {}),
707
+ ...(target?.connectionId ? { forcedConnectionId: target.connectionId } : {}),
708
+ ...(bypassProviderQuotaPolicy ? { bypassQuotaPolicy: true } : {}),
709
+ }
710
+ );
711
+ if (!creds || creds.allRateLimited) return false;
712
+
713
+ comboPreselectedCredentials.set(getComboCredentialCacheKey(modelString, target), creds);
714
+ return true;
715
+ };
716
+
717
+ // Fetch settings and all combos for config cascade and nested resolution
718
+ const [settings, allCombos] = await Promise.all([
719
+ getCachedSettings().catch(() => ({})),
720
+ getCombosCachedForChat(),
721
+ ]);
722
+ const relayConfig =
723
+ combo.strategy === "context-relay" ? resolveComboConfig(combo, settings) : null;
724
+ // Per-request Auto-Combo controls (#6023 / #6024 / #6025): steer an `auto`
725
+ // combo on this single request without mutating its stored config.
726
+ const requestModeHeader = request.headers.get("x-omniroute-mode")?.trim() || null;
727
+ const requestBudgetHeader = request.headers.get("x-omniroute-budget")?.trim() || null;
728
+ const perRequestMode = resolveRequestModePack(requestModeHeader);
729
+ const perRequestBudgetCap = parseRequestBudgetCap(requestBudgetHeader);
730
+ const relayOptions =
731
+ combo.strategy === "context-relay" ||
732
+ bypassProviderQuotaPolicy ||
733
+ perRequestMode.override ||
734
+ perRequestBudgetCap !== undefined
735
+ ? {
736
+ ...(combo.strategy === "context-relay"
737
+ ? {
738
+ sessionId,
739
+ config: relayConfig,
740
+ }
741
+ : {}),
742
+ ...(bypassProviderQuotaPolicy ? { bypassProviderQuotaPolicy: true } : {}),
743
+ ...(perRequestMode.override ? { mode: requestModeHeader } : {}),
744
+ ...(perRequestBudgetCap !== undefined ? { budgetCap: perRequestBudgetCap } : {}),
745
+ }
746
+ : undefined;
747
+ telemetry.endPhase();
748
+
749
+ // Context-relay keeps generation in combo.ts, but handoff injection lives here
750
+ // because only this layer knows which connectionId was actually selected.
751
+ const response = await (handleComboChat as any)({
752
+ body,
753
+ combo,
754
+ handleSingleModel: (
755
+ b: any,
756
+ m: string,
757
+ target?: {
758
+ allowRateLimitedConnection?: boolean;
759
+ connectionId?: string | null;
760
+ executionKey?: string | null;
761
+ stepId?: string | null;
762
+ allowedConnectionIds?: string[] | null;
763
+ failoverBeforeRetry?: boolean;
764
+ providerId?: string | null;
765
+ effectiveComboStrategy?: string | null;
766
+ }
767
+ ) =>
768
+ handleSingleModelChat(
769
+ b,
770
+ m,
771
+ clientRawRequest,
772
+ request,
773
+ combo.name,
774
+ apiKeyInfo,
775
+ telemetry,
776
+ {
777
+ sessionId,
778
+ sessionAffinityKey,
779
+ forceLiveComboTest: isComboLiveTest,
780
+ forcedConnectionId: target?.connectionId ?? null,
781
+ allowedConnectionIds: target?.allowedConnectionIds ?? null,
782
+ comboStepId: target?.stepId || null,
783
+ comboExecutionKey: target?.executionKey || target?.stepId || null,
784
+ skipUpstreamRetry: target?.failoverBeforeRetry ?? false,
785
+ allowRateLimitedConnection: target?.allowRateLimitedConnection === true,
786
+ preselectedCredentials: comboPreselectedCredentials.get(
787
+ getComboCredentialCacheKey(m, target)
788
+ ),
789
+ cachedSettings: settings,
790
+ providerId: target?.providerId ?? null,
791
+ correlationId: reqId,
792
+ modelPinned: (target as any)?.modelPinned ?? false,
793
+ },
794
+ target?.effectiveComboStrategy ?? combo.strategy,
795
+ true
796
+ ).then(async (res: Response) => {
797
+ // Auto-promote the winning combo model to position #1 (opt-in flag).
798
+ if (res?.ok)
799
+ await promoteSuccessfulComboModel(
800
+ combo,
801
+ m,
802
+ settings as Record<string, unknown>,
803
+ comboPromoteDeps
804
+ );
805
+ return res;
806
+ }),
807
+ isModelAvailable: checkModelAvailable,
808
+ log,
809
+ settings,
810
+ allCombos,
811
+ apiKeyAllowedConnections: apiKeyInfo?.allowedConnections ?? null,
812
+ relayOptions,
813
+ signal: request?.signal ?? null,
814
+ correlationId: reqId,
815
+ });
816
+
817
+ // ── Global Fallback Provider (#689) ────────────────────────────────────
818
+ // If combo exhausted all models, try the global fallback before giving up.
819
+ if (
820
+ !response.ok &&
821
+ [502, 503].includes(response.status) &&
822
+ typeof (settings as any)?.globalFallbackModel === "string" &&
823
+ (settings as any).globalFallbackModel.trim()
824
+ ) {
825
+ const fallbackModel = (settings as any).globalFallbackModel.trim();
826
+ log.info(
827
+ "GLOBAL_FALLBACK",
828
+ `Combo "${combo.name}" exhausted — attempting global fallback: ${fallbackModel}`
829
+ );
830
+ try {
831
+ const fallbackResponse = await handleSingleModelChat(
832
+ body,
833
+ fallbackModel,
834
+ clientRawRequest,
835
+ request,
836
+ combo.name,
837
+ apiKeyInfo,
838
+ telemetry,
839
+ {
840
+ sessionId,
841
+ sessionAffinityKey,
842
+ emergencyFallbackTried: true,
843
+ forceLiveComboTest: isComboLiveTest,
844
+ },
845
+ combo.strategy,
846
+ true
847
+ );
848
+ if (fallbackResponse.ok) {
849
+ log.info("GLOBAL_FALLBACK", `Global fallback ${fallbackModel} succeeded`);
850
+ recordTelemetry(telemetry);
851
+ return withSessionHeader(fallbackResponse, sessionId);
852
+ }
853
+ log.warn(
854
+ "GLOBAL_FALLBACK",
855
+ `Global fallback ${fallbackModel} also failed (${fallbackResponse.status})`
856
+ );
857
+ } catch (err: any) {
858
+ log.warn("GLOBAL_FALLBACK", `Global fallback error: ${err?.message || "unknown"}`);
859
+ }
860
+ }
861
+ // ─────────────────────────────────────────────────────────────────────────
862
+
863
+ // Record telemetry
864
+ recordTelemetry(telemetry);
865
+ // Log combo failures that bypassed handleChatCore (e.g. all targets skipped by circuit breaker)
866
+ if (!response.ok) {
867
+ try {
868
+ const { saveCallLog } = await import("@/lib/usageDb");
869
+ saveCallLog({
870
+ id: undefined,
871
+ method: "POST",
872
+ path: clientRawRequest?.endpoint || "/v1/chat/completions",
873
+ status: response.status,
874
+ model: body?.model || resolvedModelStr,
875
+ requestedModel: body?.model || resolvedModelStr,
876
+ provider: "-",
877
+ connectionId: undefined,
878
+ duration: Date.now() - (telemetry?.startTime || Date.now()),
879
+ tokens: {},
880
+ error: `[${response.status}] Combo "${combo.name}" failed — all targets exhausted`,
881
+ comboName: combo.name,
882
+ comboStepId: null,
883
+ comboExecutionKey: null,
884
+ correlationId: reqId,
885
+ }).catch(() => {});
886
+ } catch {}
887
+ }
888
+ return withCorrelationId(withSessionHeader(response, sessionId), reqId);
889
+ }
890
+ telemetry.endPhase();
891
+
892
+ // Single model request
893
+ const response = await handleSingleModelChat(
894
+ body,
895
+ resolvedModelStr,
896
+ clientRawRequest,
897
+ request,
898
+ null,
899
+ apiKeyInfo,
900
+ telemetry,
901
+ {
902
+ sessionId,
903
+ sessionAffinityKey,
904
+ forceLiveComboTest: isComboLiveTest,
905
+ forcedConnectionId: requestedConnectionId,
906
+ correlationId: reqId,
907
+ },
908
+ null,
909
+ false
910
+ );
911
+ recordTelemetry(telemetry);
912
+ return withCorrelationId(withSessionHeader(response, sessionId), reqId);
913
+ }
914
+
915
+ export function buildClientRawRequest(request: Request, body: unknown) {
916
+ const url = new URL(request.url);
917
+ return {
918
+ endpoint: url.pathname,
919
+ body: cloneLogPayload(body),
920
+ headers: Object.fromEntries(request.headers.entries()),
921
+ signal: request.signal ?? null,
922
+ };
923
+ }
924
+
925
+ /**
926
+ * Handle single model chat request
927
+ *
928
+ * Refactored: model resolution, logging, pipeline gates, and chat execution
929
+ * extracted to focused helpers. This function orchestrates the credential
930
+ * retry loop.
931
+ */
932
+ async function handleSingleModelChat(
933
+ body: any,
934
+ modelStr: string,
935
+ clientRawRequest: any = null,
936
+ request: any = null,
937
+ comboName: string | null = null,
938
+ apiKeyInfo: any = null,
939
+ telemetry: any = null,
940
+ runtimeOptions: {
941
+ emergencyFallbackTried?: boolean;
942
+ forceLiveComboTest?: boolean;
943
+ sessionId?: string | null;
944
+ sessionAffinityKey?: string | null;
945
+ forcedConnectionId?: string | null;
946
+ allowedConnectionIds?: string[] | null;
947
+ comboStepId?: string | null;
948
+ comboExecutionKey?: string | null;
949
+ skipUpstreamRetry?: boolean;
950
+ allowRateLimitedConnection?: boolean;
951
+ preselectedCredentials?: any;
952
+ cachedSettings?: any;
953
+ providerId?: string | null;
954
+ correlationId?: string | null;
955
+ } = {},
956
+ comboStrategy: string | null = null,
957
+ isCombo: boolean = false
958
+ ) {
959
+ // 1. Resolve model → provider/model
960
+ const resolved = await resolveModelOrError(
961
+ modelStr,
962
+ body,
963
+ clientRawRequest?.endpoint,
964
+ clientRawRequest?.headers
965
+ );
966
+ if (resolved.error) return resolved.error;
967
+
968
+ // Safety net: if auto-combo resolution returned a combo object, redirect
969
+ // to combo flow. This handles the case where the auto-fuzzy match in
970
+ // resolveModelOrError found a combo but the main handler's combo lookup missed it.
971
+ if ((resolved as any).combo) {
972
+ const redirectCombo = (resolved as any).combo;
973
+ log.info(
974
+ "ROUTING",
975
+ `Safety-net combo redirect for "${modelStr}" → combo="${redirectCombo.name}"`
976
+ );
977
+ log.info("ROUTING", `Auto-combo redirect from handleSingleModelChat for "${modelStr}"`);
978
+ log.info("ROUTING", `Auto-combo redirect to combo flow for "${modelStr}"`);
979
+ return handleComboChat({
980
+ body,
981
+ combo: redirectCombo,
982
+ handleSingleModel: (
983
+ b: any,
984
+ m: string,
985
+ target?: {
986
+ connectionId?: string | null;
987
+ executionKey?: string | null;
988
+ stepId?: string | null;
989
+ failoverBeforeRetry?: boolean;
990
+ allowRateLimitedConnection?: boolean;
991
+ providerId?: string | null;
992
+ effectiveComboStrategy?: string | null;
993
+ }
994
+ ) =>
995
+ handleSingleModelChat(
996
+ b,
997
+ m,
998
+ clientRawRequest,
999
+ request,
1000
+ redirectCombo.name ?? modelStr,
1001
+ apiKeyInfo,
1002
+ telemetry,
1003
+ {
1004
+ sessionId: "", // safety-net redirect doesn't have session context
1005
+ forceLiveComboTest: false,
1006
+ forcedConnectionId: null,
1007
+ allowedConnectionIds: null,
1008
+ comboStepId: null,
1009
+ comboExecutionKey: null,
1010
+ skipUpstreamRetry: target?.failoverBeforeRetry ?? false,
1011
+ allowRateLimitedConnection: target?.allowRateLimitedConnection === true,
1012
+ providerId: target?.providerId ?? null,
1013
+ correlationId: runtimeOptions?.correlationId ?? null,
1014
+ },
1015
+ target?.effectiveComboStrategy ?? redirectCombo.strategy ?? "priority",
1016
+ false
1017
+ ),
1018
+ isModelAvailable: async () => true,
1019
+ log,
1020
+ settings: {},
1021
+ allCombos: [],
1022
+ relayOptions: undefined,
1023
+ signal: request?.signal ?? null,
1024
+ correlationId: runtimeOptions?.correlationId ?? null,
1025
+ });
1026
+ }
1027
+
1028
+ const {
1029
+ provider: resolvedProvider,
1030
+ model,
1031
+ sourceFormat,
1032
+ targetFormat,
1033
+ extendedContext,
1034
+ apiFormat,
1035
+ } = resolved;
1036
+ // Prefer the combo target's providerId when available — the model string's
1037
+ // provider prefix may differ from the credential provider ID (e.g. model
1038
+ // "xiaomi/mimo-v2-flash" resolves to provider "xiaomi" but the combo target
1039
+ // may specify providerId: "opengate" for credential lookup).
1040
+ // Guard: if runtimeOptions.providerId is merely the prefix already encoded in
1041
+ // the model string (e.g. "p2" from "p2/test-model"), and resolveModelOrError
1042
+ // expanded it to a full custom-node ID (e.g. "openai-compatible-chat-e2e-p2"),
1043
+ // trust resolvedProvider so the executor receives the full node ID and can
1044
+ // correctly resolve the custom baseUrl. (#3058 follow-up)
1045
+ const provider = (() => {
1046
+ if (!runtimeOptions.providerId) return resolvedProvider;
1047
+ // If the override is identical to resolvedProvider, no-op.
1048
+ if (runtimeOptions.providerId === resolvedProvider) return resolvedProvider;
1049
+ // If the model string already encodes runtimeOptions.providerId as its prefix,
1050
+ // the override is implicit (not an intentional redirect) — use resolvedProvider.
1051
+ if (modelStr.startsWith(runtimeOptions.providerId + "/")) return resolvedProvider;
1052
+ // Intentional override (e.g. providerId points to a different credential pool).
1053
+ return runtimeOptions.providerId;
1054
+ })();
1055
+ const forceLiveComboTest = runtimeOptions.forceLiveComboTest === true;
1056
+ const bypassProviderQuotaPolicy = hasProviderQuotaBypassScope(apiKeyInfo?.scopes);
1057
+ const hasForcedConnection =
1058
+ typeof runtimeOptions.forcedConnectionId === "string" &&
1059
+ runtimeOptions.forcedConnectionId.trim().length > 0;
1060
+ let effectiveAllowedConnections = intersectAllowedConnectionIds(
1061
+ apiKeyInfo?.allowedConnections ?? null,
1062
+ runtimeOptions.allowedConnectionIds ?? null
1063
+ );
1064
+
1065
+ // A4: quota-exclusive keys must only use the pool's connection(s).
1066
+ if (apiKeyInfo?.allowedQuotas && apiKeyInfo.allowedQuotas.length > 0) {
1067
+ const quotaScope = await resolveQuotaKeyScope(apiKeyInfo.allowedQuotas);
1068
+ effectiveAllowedConnections = constrainConnectionsToQuota(
1069
+ effectiveAllowedConnections ?? [],
1070
+ quotaScope.connectionIds
1071
+ );
1072
+ }
1073
+
1074
+ const bypassReason = forceLiveComboTest
1075
+ ? "combo live test"
1076
+ : hasForcedConnection
1077
+ ? "fixed combo step connection"
1078
+ : undefined;
1079
+
1080
+ // 2. Pipeline gates (availability + provider circuit breaker)
1081
+ const providerProfile = await getRuntimeProviderProfile(provider);
1082
+ const gate = await checkPipelineGates(provider, model, {
1083
+ ignoreCircuitBreaker: forceLiveComboTest || hasForcedConnection,
1084
+ ignoreModelCooldown: forceLiveComboTest || hasForcedConnection,
1085
+ providerProfile,
1086
+ ...(bypassReason ? { bypassReason } : {}),
1087
+ });
1088
+ if (gate) {
1089
+ // Log the rejected request so it appears in /dashboard/logs
1090
+ try {
1091
+ const { saveCallLog } = await import("@/lib/usageDb");
1092
+ saveCallLog({
1093
+ id: undefined,
1094
+ method: "POST",
1095
+ path: clientRawRequest?.endpoint || "/v1/chat/completions",
1096
+ status: gate.status,
1097
+ model,
1098
+ requestedModel: body?.model || modelStr,
1099
+ provider,
1100
+ connectionId: undefined,
1101
+ duration: Date.now() - (telemetry?.startTime || Date.now()),
1102
+ tokens: {},
1103
+ error: `[${gate.status}] Pipeline gate rejected`,
1104
+ comboName: isCombo ? comboName : null,
1105
+ comboStepId: isCombo ? (runtimeOptions?.comboStepId ?? null) : null,
1106
+ comboExecutionKey: isCombo ? (runtimeOptions?.comboExecutionKey ?? null) : null,
1107
+ correlationId: runtimeOptions?.correlationId ?? null,
1108
+ }).catch(() => {});
1109
+ } catch {}
1110
+ return gate;
1111
+ }
1112
+
1113
+ // Issue #2100 follow-up: opt-in upstream 429 hint trust per provider.
1114
+ const useHints429 = resolveUseUpstream429BreakerHints(
1115
+ provider,
1116
+ (providerProfile as { useUpstream429BreakerHints?: boolean }).useUpstream429BreakerHints
1117
+ );
1118
+ const breaker = getCircuitBreaker(provider, {
1119
+ failureThreshold: providerProfile.failureThreshold,
1120
+ resetTimeout: providerProfile.resetTimeoutMs,
1121
+ // #4602: a local WS-bridge "Controller is already closed" throw is not an
1122
+ // upstream outage — keep it from tripping the whole-provider breaker.
1123
+ isFailure: (e) => !isLocalStreamLifecycleError(e),
1124
+ onStateChange: (name: string, from: string, to: string) =>
1125
+ log.info("CIRCUIT", `${name}: ${from} → ${to}`),
1126
+ ...(useHints429
1127
+ ? {
1128
+ cooldownByKind: {
1129
+ rate_limit: 60_000,
1130
+ quota_exhausted: 3_600_000,
1131
+ } satisfies Partial<Record<FailureKind, number>>,
1132
+ classifyError: classify429FromError,
1133
+ }
1134
+ : {}),
1135
+ });
1136
+
1137
+ const userAgent = request?.headers?.get("user-agent") || "";
1138
+ const baseRetrySettings = resolveCooldownAwareRetrySettings(
1139
+ runtimeOptions.cachedSettings ?? (await getCachedSettings().catch(() => ({})))
1140
+ );
1141
+ const disableCooldownAwareRetry =
1142
+ isCombo || forceLiveComboTest || runtimeOptions.emergencyFallbackTried === true;
1143
+ const retrySettings = disableCooldownAwareRetry
1144
+ ? {
1145
+ ...baseRetrySettings,
1146
+ enabled: false,
1147
+ maxRetries: 0,
1148
+ maxRetryWaitSec: 0,
1149
+ maxRetryWaitMs: 0,
1150
+ }
1151
+ : baseRetrySettings;
1152
+ const requestSignal = request?.signal ?? null;
1153
+
1154
+ if (Array.isArray(effectiveAllowedConnections) && effectiveAllowedConnections.length === 0) {
1155
+ log.debug("AUTH", `${provider}/${model} filtered out by connection-level routing constraints`);
1156
+ return errorResponse(
1157
+ HTTP_STATUS.SERVICE_UNAVAILABLE,
1158
+ "No eligible connections matched the requested routing constraints"
1159
+ );
1160
+ }
1161
+
1162
+ // 3. Credential retry loop
1163
+ let requestRetryAttempt = 0;
1164
+ let requestRetryLastError = null;
1165
+ let requestRetryLastStatus = null;
1166
+ let requestRetryLastCooldownMs = 0;
1167
+ // Bug #3758: per-request counter bounding the early-close (STREAM_EARLY_EOF)
1168
+ // re-attempt to exactly one for the whole request. Declared outside both retry
1169
+ // loops so it can never reset and loop.
1170
+ let streamEarlyEofRetries = 0;
1171
+
1172
+ requestAttemptLoop: while (true) {
1173
+ const excludedConnectionIds = new Set<string>();
1174
+ let lastError = requestRetryLastError;
1175
+ let lastStatus = requestRetryLastStatus;
1176
+ let lastCooldownMs = requestRetryLastCooldownMs;
1177
+ let preselectedCredentials = runtimeOptions.preselectedCredentials;
1178
+
1179
+ while (true) {
1180
+ const credentials =
1181
+ preselectedCredentials && excludedConnectionIds.size === 0
1182
+ ? preselectedCredentials
1183
+ : await getProviderCredentialsWithQuotaPreflight(
1184
+ provider,
1185
+ null,
1186
+ effectiveAllowedConnections,
1187
+ model,
1188
+ {
1189
+ sessionKey: runtimeOptions.sessionAffinityKey ?? runtimeOptions.sessionId ?? null,
1190
+ excludeConnectionIds: Array.from(excludedConnectionIds),
1191
+ ...(runtimeOptions.allowRateLimitedConnection
1192
+ ? { allowRateLimitedConnections: true }
1193
+ : {}),
1194
+ ...(forceLiveComboTest
1195
+ ? {
1196
+ allowSuppressedConnections: true,
1197
+ bypassQuotaPolicy: true,
1198
+ }
1199
+ : {}),
1200
+ ...(!forceLiveComboTest && bypassProviderQuotaPolicy
1201
+ ? { bypassQuotaPolicy: true }
1202
+ : {}),
1203
+ ...(runtimeOptions.forcedConnectionId
1204
+ ? { forcedConnectionId: runtimeOptions.forcedConnectionId }
1205
+ : {}),
1206
+ }
1207
+ );
1208
+ preselectedCredentials = null;
1209
+
1210
+ if (!credentials || "allRateLimited" in credentials || !credentials.connectionId) {
1211
+ if (credentials?.allRateLimited) {
1212
+ const retryDecision = getCooldownAwareRetryDecision({
1213
+ retryAfter: credentials.retryAfter,
1214
+ settings: retrySettings,
1215
+ attempt: requestRetryAttempt,
1216
+ });
1217
+
1218
+ if (retryDecision.shouldRetry) {
1219
+ const waitSec = Math.max(Math.ceil(retryDecision.waitMs / 1000), 0);
1220
+ log.info(
1221
+ "COOLDOWN_RETRY",
1222
+ `${provider}/${model} all connections cooling down (${retryDecision.retryAfterHuman || `retry in ${waitSec}s`}) — waiting ${waitSec}s before retry ${requestRetryAttempt + 1}/${retrySettings.maxRetries}`
1223
+ );
1224
+
1225
+ const completed = await waitForCooldownAwareRetry(retryDecision.waitMs, requestSignal);
1226
+ if (!completed) {
1227
+ log.info(
1228
+ "COOLDOWN_RETRY",
1229
+ `${provider}/${model} retry wait aborted by client disconnect`
1230
+ );
1231
+ return errorResponse(499, "Request aborted");
1232
+ }
1233
+
1234
+ requestRetryAttempt += 1;
1235
+ log.info(
1236
+ "COOLDOWN_RETRY",
1237
+ `${provider}/${model} cooldown elapsed — restarting request attempt ${requestRetryAttempt}/${retrySettings.maxRetries}`
1238
+ );
1239
+ continue requestAttemptLoop;
1240
+ }
1241
+ }
1242
+
1243
+ const breakerFailureStatus = Number(lastStatus ?? credentials?.lastErrorCode);
1244
+ if (
1245
+ !forceLiveComboTest &&
1246
+ credentials?.allRateLimited &&
1247
+ PROVIDER_BREAKER_FAILURE_STATUSES.has(breakerFailureStatus)
1248
+ ) {
1249
+ breaker._onFailure();
1250
+ }
1251
+
1252
+ const noCredsRes = handleNoCredentials(
1253
+ credentials,
1254
+ excludedConnectionIds.size > 0 ? Array.from(excludedConnectionIds)[0] : null,
1255
+ provider,
1256
+ model,
1257
+ lastError,
1258
+ lastStatus
1259
+ );
1260
+ const lastFailedConnectionId =
1261
+ excludedConnectionIds.size > 0
1262
+ ? Array.from(excludedConnectionIds)[excludedConnectionIds.size - 1]
1263
+ : null;
1264
+ return withSelectedConnectionHeader(noCredsRes, lastFailedConnectionId);
1265
+ }
1266
+
1267
+ const accountId = credentials.connectionId.slice(0, 8);
1268
+ log.info("AUTH", `Using ${provider} account: ${accountId}...`);
1269
+ // #474: when the request used a bare model name (no "/" — e.g. an alias
1270
+ // that resolved to "auto") and the selected connection declares a
1271
+ // defaultModel, resolve the bare name to that real model ID before the
1272
+ // upstream call so the provider receives a concrete model rather than the
1273
+ // placeholder. A "/"-qualified model name is always left untouched.
1274
+ const effectiveModel =
1275
+ resolveBareModelToConnectionDefault(modelStr, model, credentials.defaultModel) ?? model;
1276
+ let requestBody =
1277
+ effectiveModel !== model ? { ...body, model: `${provider}/${effectiveModel}` } : body;
1278
+ let injectedHandoff = null;
1279
+ if (
1280
+ comboStrategy === "context-relay" &&
1281
+ comboName &&
1282
+ runtimeOptions.sessionId &&
1283
+ body?._omnirouteSkipContextRelay !== true
1284
+ ) {
1285
+ const handoff = getHandoff(runtimeOptions.sessionId, comboName);
1286
+ if (handoff && handoff.fromAccount !== credentials.connectionId) {
1287
+ // Inject only after a real account switch. The combo loop itself cannot
1288
+ // reliably detect this because account selection happens inside auth.
1289
+ requestBody = injectHandoffIntoBody(body, handoff);
1290
+ injectedHandoff = handoff;
1291
+ log.info(
1292
+ "CONTEXT_RELAY",
1293
+ `Injecting handoff for session ${runtimeOptions.sessionId}: ${handoff.fromAccount.slice(
1294
+ 0,
1295
+ 8
1296
+ )} -> ${credentials.connectionId.slice(0, 8)}`
1297
+ );
1298
+ }
1299
+ }
1300
+ const refreshedCredentials = await checkAndRefreshToken(provider, credentials);
1301
+ const storeEnabled = isOpenAIResponsesStoreEnabled(
1302
+ refreshedCredentials?.providerSpecificData ?? credentials?.providerSpecificData
1303
+ );
1304
+ if (provider === "codex" && storeEnabled && runtimeOptions.sessionId) {
1305
+ requestBody = ensureOpenAIStoreSessionFallback(requestBody, runtimeOptions.sessionId);
1306
+ }
1307
+ if (provider === "codex" && refreshedCredentials?.accessToken && credentials.connectionId) {
1308
+ const workspaceId =
1309
+ typeof refreshedCredentials?.providerSpecificData?.workspaceId === "string" &&
1310
+ refreshedCredentials.providerSpecificData.workspaceId.trim().length > 0
1311
+ ? refreshedCredentials.providerSpecificData.workspaceId
1312
+ : typeof credentials?.providerSpecificData?.workspaceId === "string" &&
1313
+ credentials.providerSpecificData.workspaceId.trim().length > 0
1314
+ ? credentials.providerSpecificData.workspaceId
1315
+ : undefined;
1316
+ registerCodexConnection(credentials.connectionId, {
1317
+ accessToken: refreshedCredentials.accessToken,
1318
+ ...(workspaceId ? { workspaceId } : {}),
1319
+ });
1320
+ }
1321
+ if (runtimeOptions.sessionId && body?._omnirouteInternalRequest !== "context-handoff") {
1322
+ touchSession(runtimeOptions.sessionId, credentials.connectionId);
1323
+ startQuotaMonitor(
1324
+ runtimeOptions.sessionId,
1325
+ provider,
1326
+ credentials.connectionId,
1327
+ refreshedCredentials
1328
+ );
1329
+ }
1330
+ const proxyInfo = await safeResolveProxy(credentials.connectionId, apiKeyInfo?.id);
1331
+ // #5217: sink for the proxy the executor pins internally (e.g. OpencodeExecutor
1332
+ // rotation) so the egress log below reflects the real egress, not "direct".
1333
+ const appliedProxySink: { proxy: unknown } = { proxy: null };
1334
+ const proxyStartTime = Date.now();
1335
+
1336
+ // 4. Execute chat via core after breaker gate checks (with optional TLS tracking)
1337
+ if (telemetry) telemetry.startPhase("connect");
1338
+ const { result, tlsFingerprintUsed } = await executeChatWithBreaker({
1339
+ bypassCircuitBreaker: forceLiveComboTest || hasForcedConnection,
1340
+ breaker,
1341
+ body: requestBody,
1342
+ provider,
1343
+ model: effectiveModel,
1344
+ refreshedCredentials,
1345
+ proxyInfo,
1346
+ appliedProxySink,
1347
+ log,
1348
+ clientRawRequest,
1349
+ credentials,
1350
+ apiKeyInfo,
1351
+ userAgent,
1352
+ comboName,
1353
+ comboStrategy,
1354
+ isCombo,
1355
+ comboStepId: runtimeOptions.comboStepId ?? null,
1356
+ comboExecutionKey: runtimeOptions.comboExecutionKey ?? runtimeOptions.comboStepId ?? null,
1357
+ extendedContext,
1358
+ modelApiFormat: apiFormat,
1359
+ providerProfile,
1360
+ cachedSettings: runtimeOptions.cachedSettings,
1361
+ skipUpstreamRetry: runtimeOptions.skipUpstreamRetry ?? false,
1362
+ correlationId: runtimeOptions?.correlationId ?? null,
1363
+ modelPinned: runtimeOptions?.modelPinned ?? false,
1364
+ });
1365
+ if (telemetry) telemetry.endPhase();
1366
+
1367
+ const proxyLatency = Date.now() - proxyStartTime;
1368
+ const providerAlias = PROVIDER_ID_TO_ALIAS[provider] || provider;
1369
+ const effectiveTargetFormat =
1370
+ getModelTargetFormat(providerAlias, model) ||
1371
+ getTargetFormat(provider, credentials.providerSpecificData) ||
1372
+ targetFormat;
1373
+
1374
+ // 5. Log proxy + translation events (fire-and-forget; never blocks the response)
1375
+ // #5217: reflect the proxy the executor actually applied (per-account rotation).
1376
+ void safeLogEvents({
1377
+ result,
1378
+ proxyInfo: applyExecutorProxyToInfo(proxyInfo, appliedProxySink.proxy),
1379
+ proxyLatency,
1380
+ provider,
1381
+ model,
1382
+ sourceFormat,
1383
+ targetFormat: effectiveTargetFormat,
1384
+ credentials,
1385
+ comboName,
1386
+ clientRawRequest,
1387
+ tlsFingerprintUsed,
1388
+ });
1389
+
1390
+ if (result.success) {
1391
+ clearModelLock(provider, credentials.connectionId, model);
1392
+ if (!forceLiveComboTest) {
1393
+ breaker._onSuccess();
1394
+ }
1395
+ if (injectedHandoff && runtimeOptions.sessionId && comboName) {
1396
+ deleteHandoff(runtimeOptions.sessionId, comboName);
1397
+ }
1398
+ if (telemetry) telemetry.startPhase("finalize");
1399
+ if (telemetry) telemetry.endPhase();
1400
+ return result.response;
1401
+ }
1402
+
1403
+ const isAntigravityStreamReadinessFailure =
1404
+ provider === "antigravity" &&
1405
+ (result.errorCode === "STREAM_READINESS_TIMEOUT" ||
1406
+ result.errorCode === "STREAM_EARLY_EOF" ||
1407
+ result.errorType === "stream_timeout" ||
1408
+ result.errorType === "stream_early_eof");
1409
+
1410
+ if (
1411
+ (result.errorType === "stream_timeout" || result.errorType === "stream_early_eof") &&
1412
+ !isAntigravityStreamReadinessFailure
1413
+ ) {
1414
+ // Bug #3758: flaky OpenAI-compatible upstreams (e.g. NVIDIA NIM) sometimes
1415
+ // send HTTP 200 then close the SSE early with zero useful frames
1416
+ // (STREAM_EARLY_EOF). That is a transient upstream glitch, not a bad key — so
1417
+ // allow exactly ONE bounded same-connection re-attempt before surfacing the
1418
+ // 502. Do NOT retry STREAM_READINESS_TIMEOUT (a slow-but-alive upstream;
1419
+ // retrying would only double latency) and do NOT mark the account unavailable
1420
+ // for the early close.
1421
+ if (
1422
+ shouldRetryStreamEarlyEof(result.errorCode, streamEarlyEofRetries) &&
1423
+ !hasForcedConnection
1424
+ ) {
1425
+ streamEarlyEofRetries += 1;
1426
+ log.warn(
1427
+ "STREAM",
1428
+ `${provider}/${model} closed the stream early before useful content — retrying once (attempt ${streamEarlyEofRetries})`
1429
+ );
1430
+ // Plain re-attempt of the same request: no markAccountUnavailable, no
1431
+ // excludedConnectionIds mutation (an early close is not a bad connection).
1432
+ continue;
1433
+ }
1434
+
1435
+ // Stream readiness timeout is an upstream stall after an HTTP response was received,
1436
+ // not an account/quota failure. Do NOT mark the account unavailable here.
1437
+ return withSelectedConnectionHeader(result.response, credentials?.connectionId);
1438
+ }
1439
+
1440
+ if (isAntigravityStreamReadinessFailure) {
1441
+ const { shouldFallback, cooldownMs } = await markAccountUnavailable(
1442
+ credentials.connectionId,
1443
+ result.status || HTTP_STATUS.BAD_GATEWAY,
1444
+ result.error || result.errorCode || "Antigravity stream ended before useful content",
1445
+ provider,
1446
+ model,
1447
+ providerProfile,
1448
+ { isCombo }
1449
+ );
1450
+
1451
+ if (shouldFallback && !hasForcedConnection) {
1452
+ log.warn(
1453
+ "AUTH",
1454
+ `Antigravity connection ${accountId}... produced no useful stream content, trying fallback connection`
1455
+ );
1456
+ if (Number.isFinite(cooldownMs) && cooldownMs > 0) {
1457
+ lastCooldownMs = cooldownMs;
1458
+ requestRetryLastCooldownMs = cooldownMs;
1459
+ }
1460
+ if (runtimeOptions.sessionAffinityKey) {
1461
+ try {
1462
+ const affinity = getSessionAccountAffinity(
1463
+ runtimeOptions.sessionAffinityKey,
1464
+ provider
1465
+ );
1466
+ if (affinity?.connectionId === credentials.connectionId) {
1467
+ deleteSessionAccountAffinity(runtimeOptions.sessionAffinityKey, provider);
1468
+ }
1469
+ } catch {
1470
+ // best-effort: selection also excludes this connection for the current retry.
1471
+ }
1472
+ }
1473
+ excludedConnectionIds.add(credentials.connectionId);
1474
+ lastError = result.error;
1475
+ lastStatus = result.status;
1476
+ requestRetryLastError = result.error;
1477
+ requestRetryLastStatus = result.status;
1478
+ continue;
1479
+ }
1480
+
1481
+ return withSelectedConnectionHeader(result.response, credentials?.connectionId);
1482
+ }
1483
+
1484
+ const isAntigravityPreResponseTimeout =
1485
+ provider === "antigravity" &&
1486
+ result.status === HTTP_STATUS.GATEWAY_TIMEOUT &&
1487
+ (result.errorType === "upstream_timeout" ||
1488
+ result.errorCode === ANTIGRAVITY_PRE_RESPONSE_TIMEOUT_CODE);
1489
+
1490
+ if (isAntigravityPreResponseTimeout) {
1491
+ const { shouldFallback, cooldownMs } = await markAccountUnavailable(
1492
+ credentials.connectionId,
1493
+ result.status,
1494
+ result.error || ANTIGRAVITY_PRE_RESPONSE_TIMEOUT_CODE,
1495
+ provider,
1496
+ model,
1497
+ providerProfile,
1498
+ { isCombo }
1499
+ );
1500
+
1501
+ if (shouldFallback && !hasForcedConnection) {
1502
+ log.warn(
1503
+ "AUTH",
1504
+ `Antigravity connection ${accountId}... timed out before response headers, trying fallback connection`
1505
+ );
1506
+ if (Number.isFinite(cooldownMs) && cooldownMs > 0) {
1507
+ lastCooldownMs = cooldownMs;
1508
+ requestRetryLastCooldownMs = cooldownMs;
1509
+ }
1510
+ if (runtimeOptions.sessionAffinityKey) {
1511
+ try {
1512
+ const affinity = getSessionAccountAffinity(
1513
+ runtimeOptions.sessionAffinityKey,
1514
+ provider
1515
+ );
1516
+ if (affinity?.connectionId === credentials.connectionId) {
1517
+ deleteSessionAccountAffinity(runtimeOptions.sessionAffinityKey, provider);
1518
+ }
1519
+ } catch {
1520
+ // best-effort: selection also excludes this connection for the current retry.
1521
+ }
1522
+ }
1523
+ excludedConnectionIds.add(credentials.connectionId);
1524
+ lastError = result.error;
1525
+ lastStatus = result.status;
1526
+ requestRetryLastError = result.error;
1527
+ requestRetryLastStatus = result.status;
1528
+ continue;
1529
+ }
1530
+
1531
+ return withSelectedConnectionHeader(result.response, credentials?.connectionId);
1532
+ }
1533
+
1534
+ if (result.errorType === "account_semaphore_capacity") {
1535
+ // Local concurrency pressure is not an upstream quota failure. Prefer another
1536
+ // account when possible; pinned combo steps fall through to combo orchestration.
1537
+ if (hasForcedConnection) {
1538
+ return withSelectedConnectionHeader(result.response, credentials?.connectionId);
1539
+ }
1540
+
1541
+ log.warn(
1542
+ "AUTH",
1543
+ `Account ${accountId}... at local concurrency cap, trying fallback account`
1544
+ );
1545
+ excludedConnectionIds.add(credentials.connectionId);
1546
+ lastError = result.error;
1547
+ lastStatus = result.status;
1548
+ requestRetryLastError = result.error;
1549
+ requestRetryLastStatus = result.status;
1550
+ continue;
1551
+ }
1552
+
1553
+ // Emergency fallback for budget exhaustion (402 / billing / quota keywords):
1554
+ // reroute to a free model (default provider/model: nvidia + openai/gpt-oss-120b) exactly once.
1555
+ // Combo targets never emergency-hop: the combo is the operator's fallback policy
1556
+ // (target-level orchestration plus the global fallback #689 after it), and a
1557
+ // per-target hop burns extra upstream calls against exhausted providers (#1731).
1558
+ if (!runtimeOptions.emergencyFallbackTried && !comboName) {
1559
+ const fallbackDecision = shouldUseFallback(
1560
+ Number(result.status || 0),
1561
+ String(result.error || ""),
1562
+ Array.isArray(body?.tools) && body.tools.length > 0
1563
+ );
1564
+
1565
+ if (isFallbackDecision(fallbackDecision)) {
1566
+ const fallbackModelStr = `${fallbackDecision.provider}/${fallbackDecision.model}`;
1567
+ const currentModelStr = `${provider}/${model}`;
1568
+
1569
+ if (fallbackModelStr !== currentModelStr) {
1570
+ const fallbackBody = { ...body, model: fallbackModelStr };
1571
+
1572
+ // Cap output on emergency fallback to avoid unexpected long responses.
1573
+ const maxTokens = Math.min(
1574
+ Number(
1575
+ fallbackBody.max_tokens ??
1576
+ fallbackBody.max_completion_tokens ??
1577
+ fallbackDecision.maxOutputTokens
1578
+ ) || fallbackDecision.maxOutputTokens,
1579
+ fallbackDecision.maxOutputTokens
1580
+ );
1581
+ fallbackBody.max_tokens = maxTokens;
1582
+ fallbackBody.max_completion_tokens = maxTokens;
1583
+
1584
+ log.warn(
1585
+ "EMERGENCY_FALLBACK",
1586
+ `${currentModelStr} -> ${fallbackModelStr} | reason=${fallbackDecision.reason}`
1587
+ );
1588
+
1589
+ const fallbackResponse = await handleSingleModelChat(
1590
+ fallbackBody,
1591
+ fallbackModelStr,
1592
+ clientRawRequest,
1593
+ request,
1594
+ comboName,
1595
+ apiKeyInfo,
1596
+ telemetry,
1597
+ {
1598
+ ...runtimeOptions,
1599
+ emergencyFallbackTried: true,
1600
+ forcedConnectionId: null,
1601
+ comboStepId: null,
1602
+ comboExecutionKey: null,
1603
+ },
1604
+ null, // no strategy for emergency fallback
1605
+ Boolean(comboName) // isCombo if comboName exists
1606
+ );
1607
+
1608
+ if (fallbackResponse.ok) {
1609
+ return fallbackResponse;
1610
+ }
1611
+
1612
+ log.warn(
1613
+ "EMERGENCY_FALLBACK",
1614
+ `Emergency fallback to ${fallbackModelStr} failed with status ${fallbackResponse.status}. Resuming original provider account fallback.`
1615
+ );
1616
+ }
1617
+ }
1618
+ }
1619
+
1620
+ // 6. Daily quota error check - must be executed before markAccountUnavailable
1621
+ // Check if it's a daily quota exhausted error (e.g., ModelScope/Kimi "today's quota for model")
1622
+ // Daily quota lockout overrides subsequent rate_limited lockout, ensuring lockout until tomorrow 0:00
1623
+ let dailyQuotaExhausted = false;
1624
+ const errorStr = String(result.error || "");
1625
+ const failureKind =
1626
+ result.status === 429
1627
+ ? classify429FromError({ status: result.status, message: errorStr })
1628
+ : undefined;
1629
+ if (result.status === 429 && isDailyQuotaExhausted(errorStr)) {
1630
+ // Parse which model is quota-limited
1631
+ const match = errorStr.match(/today's quota for model ([^,]+)/);
1632
+ const limitedModel = match ? match[1].trim() : model;
1633
+
1634
+ const mlSettings = resolveModelLockoutSettings(runtimeOptions.cachedSettings);
1635
+ if (mlSettings.enabled && mlSettings.errorCodes.includes(result.status)) {
1636
+ // Lock this model on this connection until tomorrow 00:00
1637
+ const lockResult = recordModelLockoutFailure(
1638
+ provider,
1639
+ credentials.connectionId,
1640
+ limitedModel,
1641
+ "quota_exhausted",
1642
+ result.status,
1643
+ 0,
1644
+ providerProfile,
1645
+ { maxCooldownMs: mlSettings.maxCooldownMs }
1646
+ );
1647
+
1648
+ log.info(
1649
+ "MODEL_DAILY_QUOTA",
1650
+ JSON.stringify({
1651
+ connection: credentials.connectionId.slice(0, 8),
1652
+ model: limitedModel,
1653
+ cooldownMs: lockResult.cooldownMs,
1654
+ failureCount: lockResult.failureCount,
1655
+ })
1656
+ );
1657
+ }
1658
+
1659
+ dailyQuotaExhausted = true;
1660
+ }
1661
+
1662
+ // 7. Mark account as quota-exhausted only for explicit long-window quota signals.
1663
+ // A plain 429/high-traffic response should trigger fallback/cooldown, not poison
1664
+ // quotaCache as exhausted for 5 minutes while usage quota may still be available.
1665
+ if (!dailyQuotaExhausted) {
1666
+ const passthroughModels = credentials.providerSpecificData?.passthroughModels;
1667
+ if (
1668
+ result.status === 429 &&
1669
+ shouldMarkAccountExhaustedFrom429(provider, model, passthroughModels, failureKind)
1670
+ ) {
1671
+ markAccountExhaustedFrom429(credentials.connectionId, provider);
1672
+ }
1673
+ }
1674
+
1675
+ // 8. Fallback to next account
1676
+ // A3 guard: if 401 and connection has extra keys, skip connection-level disable
1677
+ // (key-level failure already recorded in chatCore.ts via T07)
1678
+ // Check extra keys directly from credentials for reliability across restarts
1679
+ const hasExtraKeys =
1680
+ ((credentials.providerSpecificData?.extraApiKeys as string[] | undefined) ?? []).length >
1681
+ 0 || connectionHasExtraKeys(credentials.connectionId);
1682
+ const is401 = result.status === 401;
1683
+ // Our own timeout fired on a slow upstream; don't cool down a healthy account.
1684
+ const skipConnectionDisable =
1685
+ result.status === 499 ||
1686
+ result.errorCode === "client_disconnected" ||
1687
+ result.errorType === "client_disconnected" ||
1688
+ (is401 && hasExtraKeys) ||
1689
+ isSelfInflictedUpstreamTimeout(result.status, result.errorType, provider);
1690
+
1691
+ const { shouldFallback, cooldownMs } = skipConnectionDisable
1692
+ ? { shouldFallback: false, cooldownMs: 0 }
1693
+ : await markAccountUnavailable(
1694
+ credentials.connectionId,
1695
+ result.status,
1696
+ result.error,
1697
+ provider,
1698
+ model,
1699
+ providerProfile,
1700
+ {
1701
+ persistUnavailableState: !(
1702
+ isCombo &&
1703
+ result.status === 429 &&
1704
+ (failureKind === "rate_limit" || failureKind === "transient")
1705
+ ),
1706
+ isCombo,
1707
+ }
1708
+ );
1709
+
1710
+ if (shouldFallback) {
1711
+ if (Number.isFinite(cooldownMs) && cooldownMs > 0) {
1712
+ lastCooldownMs = cooldownMs;
1713
+ requestRetryLastCooldownMs = cooldownMs;
1714
+ }
1715
+ log.warn("AUTH", `Account ${accountId}... unavailable (${result.status}), trying fallback`);
1716
+ // #6219: evict the sticky session pin when the pinned account fails over,
1717
+ // otherwise the next request re-pins the same throttled account until
1718
+ // restart. Guarded by connection match so a pin for a different (healthy)
1719
+ // account is left intact.
1720
+ if (runtimeOptions.sessionAffinityKey) {
1721
+ try {
1722
+ evictSessionAccountAffinityForConnection(
1723
+ runtimeOptions.sessionAffinityKey,
1724
+ provider,
1725
+ credentials.connectionId
1726
+ );
1727
+ } catch {
1728
+ // best-effort: selection also excludes this connection for the current retry.
1729
+ }
1730
+ }
1731
+ excludedConnectionIds.add(credentials.connectionId);
1732
+ lastError = result.error;
1733
+ lastStatus = result.status;
1734
+ requestRetryLastError = result.error;
1735
+ requestRetryLastStatus = result.status;
1736
+ continue;
1737
+ }
1738
+
1739
+ if (
1740
+ !forceLiveComboTest &&
1741
+ !isCombo &&
1742
+ PROVIDER_BREAKER_FAILURE_STATUSES.has(Number(result.status))
1743
+ ) {
1744
+ breaker._onFailure();
1745
+ }
1746
+
1747
+ return withSelectedConnectionHeader(result.response, credentials?.connectionId);
1748
+ }
1749
+ }
1750
+ }