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,4685 @@
1
+ /**
2
+ * OpenCode plugin for the OmniRoute AI Gateway.
3
+ *
4
+ * Implements the official `@opencode-ai/plugin` Plugin contract (auth +
5
+ * provider + config hooks) to drive a running OmniRoute instance from
6
+ * OpenCode without hand-curated `provider.<id>.models` blocks in
7
+ * opencode.json[c]:
8
+ *
9
+ * - `auth` — registers `/connect <providerId>` flow (API key prompt)
10
+ * - `provider` — dynamic `/v1/models` fetch with TTL cache, capabilities
11
+ * pass-through (OmniRoute is the source of truth — no
12
+ * client-side variant synthesis)
13
+ * - `config` — backward-compat shim for OC versions that predate the
14
+ * `provider.models` hook (≤ 1.14.48)
15
+ *
16
+ * Two ways to consume the plugin:
17
+ *
18
+ * 1. Single-instance (default `providerId: "omniroute"`):
19
+ *
20
+ * ```json
21
+ * {
22
+ * "$schema": "https://opencode.ai/config.json",
23
+ * "plugin": ["@omniroute/opencode-plugin"]
24
+ * }
25
+ * ```
26
+ *
27
+ * 2. Multi-instance via plugin options (prod + preprod side by side):
28
+ *
29
+ * ```json
30
+ * {
31
+ * "$schema": "https://opencode.ai/config.json",
32
+ * "plugin": [
33
+ * ["@omniroute/opencode-plugin", { "providerId": "omniroute" }],
34
+ * ["@omniroute/opencode-plugin", { "providerId": "omniroute-preprod" }]
35
+ * ]
36
+ * }
37
+ * ```
38
+ *
39
+ * Then `opencode connect <providerId>` to provision the API key per instance.
40
+ *
41
+ * Companion library: `@omniroute/opencode-provider` (build-time config generator)
42
+ * remains supported for users who can't run plugins (CI, scripted scaffolding).
43
+ *
44
+ * @see https://opencode.ai/docs/plugins for the OpenCode plugin contract.
45
+ * @see https://github.com/diegosouzapw/OmniRoute for the AI Gateway.
46
+ */
47
+
48
+ import { createHash } from "node:crypto";
49
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
50
+ import * as os from "node:os";
51
+ import * as path from "node:path";
52
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
53
+ import { homedir } from "node:os";
54
+ import { join } from "node:path";
55
+ import { randomUUID } from "node:crypto";
56
+ import type { AuthHook, Config, Plugin, PluginOptions, ProviderHook } from "@opencode-ai/plugin";
57
+ import type { Model as ModelV2 } from "@opencode-ai/sdk/v2";
58
+ import { z } from "zod";
59
+ import { logger as _logger, setLogLevel, type LogLevel as _LogLevel } from "./logger.js";
60
+ import {
61
+ PROVIDER_TAG_SEPARATOR as _PROVIDER_TAG_SEPARATOR,
62
+ shortProviderLabel as _shortProviderLabel,
63
+ normaliseFreeLabel as _normaliseFreeLabel,
64
+ formatAutoComboName,
65
+ autoComboModelId,
66
+ formatFreeBudget,
67
+ type AutoVariant,
68
+ AUTO_VARIANTS,
69
+ AUTO_VARIANT_DESCRIPTIONS,
70
+ type FreeModelFreeType,
71
+ } from "./naming.js";
72
+
73
+ /**
74
+ * Zod schema for plugin options accepted as the second element of the
75
+ * `plugin: [name, opts]` tuple in opencode.json. Strict by design — unknown
76
+ * keys are rejected so typos in opencode.json surface immediately at plugin
77
+ * construction time instead of silently being dropped.
78
+ *
79
+ * Doc per field:
80
+ *
81
+ * - `providerId` OpenCode provider id this plugin instance binds to.
82
+ * Multiple plugin instances coexist by giving each a
83
+ * different `providerId` ("omniroute", "omniroute-preprod",
84
+ * "omniroute-local"). Maps to `ProviderHook.id` and
85
+ * `AuthHook.provider` in the @opencode-ai/plugin contract.
86
+ * Default: "omniroute".
87
+ * - `displayName` Label rendered in the OpenCode UI. Default derives
88
+ * from providerId.
89
+ * - `modelCacheTtl` `/v1/models` TTL cache duration in milliseconds.
90
+ * Default: 300_000 (5 min).
91
+ * - `baseURL` Override base URL for this OmniRoute instance. When
92
+ * absent, the loader falls back to a credential-attached
93
+ * baseURL set by `/connect`.
94
+ */
95
+ /**
96
+ * Optional feature toggles. Every field is opt-in/out per call; defaults
97
+ * mirror the v0.1.0 behaviour so existing opencode.json files do not need
98
+ * to change.
99
+ *
100
+ * - `combos` Discover `/api/combos` and surface them as
101
+ * pseudo-models with LCD capabilities. Default true.
102
+ * - `enrichment` Pull display names + pricing from
103
+ * `/api/pricing/models` and overlay them onto the
104
+ * ModelV2 entries derived from `/v1/models`. Solves
105
+ * the "raw id in UI" complaint without client-side
106
+ * heuristics. Default true.
107
+ * - `compressionMetadata` Pull `/api/context/combos` so combo entries can
108
+ * be tagged with their compression pipeline
109
+ * (e.g. `rtk:standard → caveman:full`). Off by
110
+ * default — adds one network call per refresh and
111
+ * the data is only useful for combo entries.
112
+ * - `geminiSanitization` Strip `$schema`/`$ref`/`additionalProperties`
113
+ * from `tools[].function.parameters` when the
114
+ * model id contains "gemini". Default true.
115
+ * - `mcpAutoEmit` Auto-write an `mcp.<providerId>` remote entry
116
+ * into the OC config pointing at
117
+ * `<baseURL>/api/mcp/stream` with the resolved
118
+ * Bearer token. Default false — keeps opencode.json
119
+ * in control unless explicitly opted in.
120
+ * - `mcpToken` Optional separate Bearer token to use in the
121
+ * auto-emitted MCP entry. Falls back to the
122
+ * provider's API key (from auth.json) when unset.
123
+ * Useful when a narrower-scoped MCP-only key is
124
+ * preferred over the chat/inference key.
125
+ * - `fetchInterceptor` Inject Authorization: Bearer + Content-Type on
126
+ * every outbound request to baseURL. Default true.
127
+ * - `debugLog` Capture every outbound request + response to a
128
+ * JSONL file at
129
+ * `~/.local/share/opencode/plugins/omniroute-debug-{providerId}.jsonl`.
130
+ * Each line: `{ reqId, ts, url, method, reqBody,
131
+ * resStatus, resBody, durationMs }`.
132
+ * Default false. Opt-in.
133
+ * - `apiFormat` Per-provider-prefix API format routing. Model IDs
134
+ * whose prefix (the part before `/`) matches an entry
135
+ * in `anthropicPrefixes` are served via the Anthropic
136
+ * SDK (`@ai-sdk/anthropic`, sends to `/v1/messages`
137
+ * with native cache_control, tool_choice, etc.).
138
+ * All other models fall back to `openai-compatible`.
139
+ *
140
+ * Default `anthropicPrefixes`:
141
+ * ["cc", "claude", "anthropic", "kiro", "kr"]
142
+ * (covers OmniRoute's canonical Anthropic aliases).
143
+ *
144
+ * Set `anthropicPrefixes: []` to disable and force
145
+ * everything through OpenAI-compat.
146
+ *
147
+ * Example:
148
+ * ```json
149
+ * "apiFormat": { "anthropicPrefixes": ["cc","claude","anthropic","kiro"] }
150
+ * ```
151
+ */
152
+ const apiFormatSchema = z
153
+ .object({
154
+ anthropicPrefixes: z.array(z.string()).optional(),
155
+ })
156
+ .strict()
157
+ .optional();
158
+
159
+ const featuresSchema = z
160
+ .object({
161
+ combos: z.boolean().optional(),
162
+ autoCombos: z.boolean().optional(),
163
+ enrichment: z.boolean().optional(),
164
+ compressionMetadata: z.boolean().optional(),
165
+ geminiSanitization: z.boolean().optional(),
166
+ mcpAutoEmit: z.boolean().optional(),
167
+ mcpToken: z.string().min(1).optional(),
168
+ fetchInterceptor: z.boolean().optional(),
169
+ usableOnly: z.boolean().optional(),
170
+ diskCache: z.boolean().optional(),
171
+ providerTag: z.boolean().optional(),
172
+ debugLog: z.boolean().optional(),
173
+ startupDebug: z.boolean().optional(),
174
+ logLevel: z.enum(["error", "warn", "info", "debug"]).optional(),
175
+ apiFormat: apiFormatSchema,
176
+ })
177
+ .strict();
178
+
179
+ const optionsSchema = z
180
+ .object({
181
+ providerId: z
182
+ .string()
183
+ .min(1)
184
+ .regex(/^[a-z0-9-]+$/i, "providerId must be a slug")
185
+ .optional(),
186
+ displayName: z.string().min(1).optional(),
187
+ modelCacheTtl: z.number().positive().optional(),
188
+ baseURL: z.string().url().optional(),
189
+ features: featuresSchema.optional(),
190
+ })
191
+ .strict();
192
+
193
+ /**
194
+ * Plugin options shape — inferred directly from the Zod schema so the
195
+ * validator and the static type can never drift. Replaces the standalone
196
+ * interface previously declared here (T-02). Every consumer continues to
197
+ * import `OmniRoutePluginOptions` as before; only the source of truth
198
+ * shifted from a hand-written interface to `z.infer<typeof optionsSchema>`.
199
+ */
200
+ export type OmniRoutePluginOptions = z.infer<typeof optionsSchema>;
201
+
202
+ export const OMNIROUTE_PROVIDER_KEY = "omniroute" as const;
203
+
204
+ /** Deployed plugin version (injected at build time by tsup define). */
205
+ export const PLUGIN_VERSION: string =
206
+ ((globalThis as Record<string, unknown>).__PLUGIN_VERSION__ as string) ?? "dev";
207
+
208
+ /** Deployed plugin git commit hash (injected at build time by tsup define). */
209
+ export const PLUGIN_GIT_HASH: string =
210
+ ((globalThis as Record<string, unknown>).__PLUGIN_GIT_HASH__ as string) ?? "unknown";
211
+
212
+ export const DEFAULT_MODEL_CACHE_TTL_MS = 300_000 as const;
213
+
214
+ // Manual trim helpers avoid polynomial-regex CodeQL warnings on
215
+ // user-supplied baseURL strings (string.replace(/\/+$/, "")). The same
216
+ // behaviour, no backtracking.
217
+ function trimTrailingSlashes(value: string): string {
218
+ let i = value.length;
219
+ while (i > 0 && value.charCodeAt(i - 1) === 0x2f /* "/" */) i--;
220
+ return i === value.length ? value : value.slice(0, i);
221
+ }
222
+
223
+ function trimTrailingDashes(value: string): string {
224
+ let i = value.length;
225
+ while (i > 0 && value.charCodeAt(i - 1) === 0x2d /* "-" */) i--;
226
+ return i === value.length ? value : value.slice(0, i);
227
+ }
228
+ function trimLeadingDashes(value: string): string {
229
+ let i = 0;
230
+ while (i < value.length && value.charCodeAt(i) === 0x2d /* "-" */) i++;
231
+ return i === 0 ? value : value.slice(i);
232
+ }
233
+
234
+ /**
235
+ * Resolve effective options from the optional plugin-options object,
236
+ * applying defaults. Centralises the providerId fallback so every hook
237
+ * sees a consistent identifier.
238
+ */
239
+ export function resolveOmniRoutePluginOptions(
240
+ opts?: OmniRoutePluginOptions
241
+ ): Required<Pick<OmniRoutePluginOptions, "providerId" | "displayName" | "modelCacheTtl">> &
242
+ Pick<OmniRoutePluginOptions, "baseURL" | "features"> {
243
+ const rawProviderId = opts?.providerId ?? OMNIROUTE_PROVIDER_KEY;
244
+ // OC 1.17.8+ native-adapter gate rejects providerID not in
245
+ // {openai, anthropic, opencode*}. Silently prefix so existing
246
+ // configs (providerId: "omniroute") keep working.
247
+ const providerId = rawProviderId.startsWith("opencode-")
248
+ ? rawProviderId
249
+ : `opencode-${rawProviderId}`;
250
+ const displayName =
251
+ opts?.displayName ??
252
+ (providerId === `opencode-${OMNIROUTE_PROVIDER_KEY}`
253
+ ? "OmniRoute"
254
+ : `OmniRoute (${providerId})`);
255
+ const modelCacheTtl =
256
+ typeof opts?.modelCacheTtl === "number" && opts.modelCacheTtl > 0
257
+ ? opts.modelCacheTtl
258
+ : DEFAULT_MODEL_CACHE_TTL_MS;
259
+ return {
260
+ providerId,
261
+ displayName,
262
+ modelCacheTtl,
263
+ baseURL: opts?.baseURL,
264
+ features: opts?.features,
265
+ };
266
+ }
267
+
268
+ /**
269
+ * Strict parse of raw plugin options (as received from opencode.json or a
270
+ * direct factory call) into the validated `OmniRoutePluginOptions` shape.
271
+ *
272
+ * - `null` / `undefined` → `{}` (no opts is valid, defaults take over).
273
+ * - Unknown keys → throws (strict schema catches typos in opencode.json).
274
+ * - Empty / malformed values (e.g. empty providerId, non-URL baseURL,
275
+ * negative modelCacheTtl) → throws.
276
+ *
277
+ * Validation happens at plugin invocation time (inside `OmniRoutePlugin`),
278
+ * NOT at module import — so a bad opencode.json fails the affected plugin
279
+ * instance with an actionable message instead of crashing the whole TUI on
280
+ * startup.
281
+ *
282
+ * Exported so callers and tests can validate options independent of the
283
+ * full plugin factory invocation.
284
+ */
285
+ export function parseOmniRoutePluginOptions(opts: unknown): OmniRoutePluginOptions {
286
+ if (opts === null || opts === undefined) return {};
287
+ const result = optionsSchema.safeParse(opts);
288
+ if (!result.success) {
289
+ const errs = result.error.issues
290
+ .map((i) => {
291
+ const path = i.path.length > 0 ? i.path.join(".") : "<root>";
292
+ return `${path}: ${i.message}`;
293
+ })
294
+ .join("; ");
295
+ throw new Error(`Invalid @omniroute/opencode-plugin options: ${errs}`);
296
+ }
297
+ return result.data;
298
+ }
299
+
300
+ /**
301
+ * Internal coercion shim. Delegates to `parseOmniRoutePluginOptions` to keep
302
+ * the public surface stable while routing all validation through the Zod
303
+ * schema. Always returns an object (never undefined) so downstream hooks see
304
+ * the same shape regardless of whether opencode.json passed `null`,
305
+ * `undefined`, or an empty bag.
306
+ */
307
+ function coercePluginOptions(opts?: PluginOptions): OmniRoutePluginOptions {
308
+ return parseOmniRoutePluginOptions(opts);
309
+ }
310
+
311
+ // ────────────────────────────────────────────────────────────────────────────
312
+ // Per-prefix API format routing (apiFormat feature)
313
+ // ────────────────────────────────────────────────────────────────────────────
314
+
315
+ /**
316
+ * Default provider-prefix list that triggers the Anthropic SDK format.
317
+ * Covers OmniRoute's canonical Anthropic aliases: `cc/`, `claude/`,
318
+ * `anthropic/`, plus the user-configured `kiro/` and `kr/` upstream
319
+ * connections that proxy Anthropic models.
320
+ */
321
+ export const DEFAULT_ANTHROPIC_PREFIXES = ["cc", "claude", "anthropic", "kiro", "kr"];
322
+
323
+ /**
324
+ * Ensure a baseURL ends with `/v1` so the OpenAI-compat SDK constructs
325
+ * `/v1/chat/completions` correctly. The Anthropic SDK does NOT want `/v1`
326
+ * (it appends `/v1/messages` automatically), so callers should branch on
327
+ * format first.
328
+ */
329
+ export function ensureV1Suffix(url: string): string {
330
+ const trimmed = trimTrailingSlashes(url);
331
+ return trimmed.endsWith("/v1") ? trimmed : `${trimmed}/v1`;
332
+ }
333
+
334
+ /**
335
+ * Resolve the API block (id + url + npm package) for a given model id.
336
+ *
337
+ * Decision matrix:
338
+ * - If the model id's prefix (the substring before the first `/`) is in
339
+ * `apiFormat.anthropicPrefixes` (or the default list), return the
340
+ * Anthropic SDK block: `id: "anthropic"`, `url: baseURL` (no `/v1`),
341
+ * `npm: "@ai-sdk/anthropic"`.
342
+ * - Otherwise return the OpenAI-compat block: `id: "openai-compatible"`,
343
+ * `url: baseURL + "/v1"`, `npm: "@ai-sdk/openai-compatible"`.
344
+ *
345
+ * Combos span multiple providers. Callers should pass each combo member's
346
+ * id through this function and pick the LCD format (lowest common
347
+ * denominator that every upstream actually understands).
348
+ */
349
+ export function resolveApiBlock(
350
+ modelId: string,
351
+ baseURL: string,
352
+ apiFormat?: { anthropicPrefixes?: string[] }
353
+ ): { id: string; url: string; npm: string } {
354
+ const prefixes = apiFormat?.anthropicPrefixes ?? DEFAULT_ANTHROPIC_PREFIXES;
355
+ const slash = modelId.indexOf("/");
356
+ const prefix = slash === -1 ? modelId : modelId.slice(0, slash);
357
+ const isAnthropic = prefixes.includes(prefix);
358
+ return isAnthropic
359
+ ? {
360
+ id: "anthropic",
361
+ url: trimTrailingSlashes(baseURL),
362
+ npm: "@ai-sdk/anthropic",
363
+ }
364
+ : {
365
+ id: "openai-compatible",
366
+ url: ensureV1Suffix(baseURL),
367
+ npm: "@ai-sdk/openai-compatible",
368
+ };
369
+ }
370
+
371
+ /**
372
+ * Build the AuthHook portion of the plugin for a given options bag. Exported
373
+ * standalone so the auth contract can be unit-tested without faking the full
374
+ * PluginInput / Hooks surface.
375
+ *
376
+ * Contract notes:
377
+ * - `provider` binds to `providerId` (NOT a hardcoded module constant — fixes
378
+ * the multi-instance bug in opencode-omniroute-auth@1.2.1 which pinned
379
+ * `OMNIROUTE_PROVIDER_ID = "omniroute"` at module scope).
380
+ * - `methods[0]` is the `api` flavor (no OAuth flow; OmniRoute issues bearer
381
+ * keys directly). Label includes the resolved displayName so multi-instance
382
+ * setups stay distinguishable in the OC TUI.
383
+ * - `methods[0].prompts` uses the official `{type:"text", key, message}`
384
+ * shape from `@opencode-ai/plugin@1.15.6`. The contract does NOT expose
385
+ * a `mask: true` flag on text prompts — the OC TUI is expected to handle
386
+ * credential masking by itself (per OC's `auth login` UX).
387
+ * - `loader` reads the stored credentials via `getAuth()` and projects them
388
+ * into the AI-SDK `openai-compatible` options shape (`apiKey`, `baseURL`).
389
+ * The fetch interceptor (`fetch`) is wired in T-04; left absent here so
390
+ * downstream code falls back to the SDK default fetch.
391
+ * - The loader rejects non-`api` auth flavors (oauth / wellknown) and empty
392
+ * keys by returning `{}` — OC then surfaces the `/connect` flow to the
393
+ * user instead of dispatching a request with bogus credentials.
394
+ */
395
+ export function createOmniRouteAuthHook(opts?: OmniRoutePluginOptions): AuthHook {
396
+ const { providerId, displayName, baseURL, features } = resolveOmniRoutePluginOptions(opts);
397
+ // Both fetch-layer features default ON (parity with the rest of the plugin's
398
+ // `features.X !== false` convention). Honoring them here lets users disable
399
+ // the interceptor/sanitizer from opencode.json — previously these flags were
400
+ // documented and schema-validated but silently ignored.
401
+ const wantFetchInterceptor = (features ?? {}).fetchInterceptor !== false;
402
+ const wantGeminiSanitization = (features ?? {}).geminiSanitization !== false;
403
+ const wantDebugLog = (features ?? {}).debugLog === true;
404
+
405
+ const hook: AuthHook = {
406
+ provider: providerId,
407
+ methods: [
408
+ {
409
+ type: "api",
410
+ label: `${displayName} API Key`,
411
+ prompts: [
412
+ {
413
+ type: "text",
414
+ key: "apiKey",
415
+ message: `OmniRoute API key (${providerId})`,
416
+ },
417
+ ],
418
+ },
419
+ ],
420
+ loader: async (getAuth, _provider) => {
421
+ const auth = await getAuth();
422
+ if (
423
+ auth &&
424
+ typeof auth === "object" &&
425
+ (auth as { type?: unknown }).type === "api" &&
426
+ typeof (auth as { key?: unknown }).key === "string" &&
427
+ (auth as { key: string }).key.length > 0
428
+ ) {
429
+ const apiKey = (auth as { key: string }).key;
430
+ // baseURL resolution: plugin opts win, then a credential-attached
431
+ // baseURL (some auth backends stash it alongside the key), else empty.
432
+ // Re-cast through `unknown` first: Auth is a discriminated union
433
+ // (api | oauth | wellknown) and TS refuses a direct narrowing to a
434
+ // hypothetical `{ baseURL: string }` shape because WellKnownAuth has
435
+ // no `baseURL`. We've already checked the runtime type via typeof so
436
+ // the unknown-bridge is a safe assertion, not a lie.
437
+ const authBaseURL = (auth as unknown as { baseURL?: unknown }).baseURL;
438
+ const resolvedBaseURL = baseURL ?? (typeof authBaseURL === "string" ? authBaseURL : "");
439
+ // Without a baseURL the interceptor can't tell which requests to
440
+ // intercept (it would either gate-keep nothing or, worse, all
441
+ // outbound traffic). Fall back to apiKey-only and let the SDK use
442
+ // its default fetch. The /connect flow + plugin opts should make
443
+ // this branch unreachable in practice.
444
+ if (!resolvedBaseURL) {
445
+ return { apiKey };
446
+ }
447
+ // Composition: sanitise Gemini tool schemas FIRST (T-06), then inject
448
+ // Bearer (T-04). Both layers are pure with respect to the other's
449
+ // concern (body vs headers) so order is logically free; wrapping the
450
+ // pure body-transform around the header-injecting interceptor reads
451
+ // cleaner and keeps T-06 testable in isolation against any inner fetch
452
+ // (real or stub). Each layer is gated by its feature flag; when both
453
+ // are disabled we fall back to the SDK's default fetch (apiKey only).
454
+ let composedFetch: typeof fetch | undefined;
455
+ if (wantFetchInterceptor) {
456
+ composedFetch = createOmniRouteFetchInterceptor({
457
+ apiKey,
458
+ baseURL: resolvedBaseURL,
459
+ });
460
+ }
461
+ if (wantGeminiSanitization) {
462
+ composedFetch = createGeminiSanitizingFetch(composedFetch ?? fetch);
463
+ }
464
+ if (wantDebugLog || debugLogEnabled(providerId)) {
465
+ composedFetch = createDebugLoggingFetch(composedFetch ?? fetch, providerId, wantDebugLog);
466
+ }
467
+ return composedFetch
468
+ ? { apiKey, baseURL: resolvedBaseURL, fetch: composedFetch }
469
+ : { apiKey, baseURL: resolvedBaseURL };
470
+ }
471
+ return {};
472
+ },
473
+ };
474
+
475
+ return hook;
476
+ }
477
+
478
+ /**
479
+ * Plugin factory. Returns the OpenCode Plugin object wired with the three
480
+ * hooks. Concrete hook bodies land in subsequent tickets (T-03 provider.models,
481
+ * T-04 fetch interceptor, T-06 Gemini sanitization, T-07 config backward-compat).
482
+ *
483
+ * Per `@opencode-ai/plugin@1.15.6`, the Plugin signature is
484
+ * `(input: PluginInput, options?: PluginOptions) => Promise<Hooks>` — opts
485
+ * arrive as the SECOND argument (from the `[name, opts]` tuple in
486
+ * opencode.json), NOT as a closure binding. Multi-instance support follows
487
+ * from each plugin tuple invoking the factory with its own opts.
488
+ */
489
+ export const OmniRoutePlugin: Plugin = async (_input, options) => {
490
+ const resolved = coercePluginOptions(options);
491
+ // T-07: a single per-plugin-instance cache shared between the provider
492
+ // hook (T-03/T-05) and the config-shim hook (T-07). On OC ≥1.14.49 both
493
+ // hooks fire within the same Plugin invocation, so a shared cache keeps
494
+ // /v1/models + /api/combos at exactly one round-trip per TTL refresh
495
+ // instead of two. On OC ≤1.14.48 only the config hook runs; the cache
496
+ // still works (single producer + single consumer through the same map).
497
+ // Each `OmniRoutePlugin(...)` invocation gets its OWN cache via closure,
498
+ // so prod + preprod side-by-side instances do NOT collide.
499
+ const sharedCache: OmniRouteFetchCache = new Map();
500
+ // Debug breadcrumb: confirm server() invocation + resolved options.
501
+ // Useful when diagnosing "is the plugin even running" from OC logs.
502
+ const _ver: string =
503
+ ((globalThis as Record<string, unknown>).__PLUGIN_VERSION__ as string) ?? "dev";
504
+ const _hash: string =
505
+ ((globalThis as Record<string, unknown>).__PLUGIN_GIT_HASH__ as string) ?? "unknown";
506
+ const _prefixes = resolved.features?.apiFormat?.anthropicPrefixes ?? DEFAULT_ANTHROPIC_PREFIXES;
507
+ _logger.always(
508
+ `v${_ver} (${_hash}) initialized` +
509
+ ` providerId=${resolved.providerId}` +
510
+ ` baseURL=${resolved.baseURL ?? "(from auth.json)"}` +
511
+ ` modelCacheTtl=${resolved.modelCacheTtl}ms` +
512
+ ` apiFormat=anthropic:[${_prefixes.join(",")}]` +
513
+ ` debugLog=${resolved.features?.debugLog ?? false}` +
514
+ ` logLevel=${resolved.features?.startupDebug ? "debug" : (resolved.features?.logLevel ?? "warn")}`
515
+ );
516
+
517
+ // Wire log level: startupDebug:true → "debug", explicit logLevel wins.
518
+ setLogLevel(resolved.features?.startupDebug ? "debug" : (resolved.features?.logLevel ?? "warn"));
519
+ return {
520
+ auth: createOmniRouteAuthHook(resolved),
521
+ provider: createOmniRouteProviderHook(resolved, { cache: sharedCache }),
522
+ config: createOmniRouteConfigHook(resolved, { cache: sharedCache }),
523
+ };
524
+ };
525
+
526
+ /**
527
+ * v1 plugin shape per OC plugin loader (`packages/opencode/src/plugin/shared.ts:readV1Plugin`).
528
+ * OC checks the default export for an object with `{id, server}` shape FIRST.
529
+ * If that fails it falls back to legacy `getLegacyPlugins` which walks every
530
+ * named export and rejects any non-function value — our package has
531
+ * constants (OMNIROUTE_PROVIDER_KEY, DEFAULT_MODEL_CACHE_TTL_MS) + types +
532
+ * schemas as named exports, so the legacy path always fails for us.
533
+ *
534
+ * Using v1 shape skips the legacy walk entirely. The `id` field is the
535
+ * plugin MODULE identifier (one per published package); per-instance
536
+ * `providerId` still flows through `options.providerId` as before.
537
+ */
538
+ const OmniRouteV1Plugin = {
539
+ id: "@omniroute/opencode-plugin",
540
+ server: OmniRoutePlugin,
541
+ };
542
+
543
+ export default OmniRouteV1Plugin;
544
+
545
+ // ────────────────────────────────────────────────────────────────────────────
546
+ // Provider hook (T-03) — /v1/models pass-through with TTL cache
547
+ // ────────────────────────────────────────────────────────────────────────────
548
+
549
+ /**
550
+ * Raw shape of a `/v1/models` entry from OmniRoute. Captured verbatim from
551
+ * the prod gateway response (sample at /tmp/prod-v1-models.json: 455 entries).
552
+ * STRICT source-of-truth (OQ-3): every field that lands in ModelV2 traces
553
+ * back to this shape — no client-side variant synthesis.
554
+ */
555
+ export interface OmniRouteRawModelEntry {
556
+ id: string;
557
+ object?: string;
558
+ owned_by?: string;
559
+ root?: string | null;
560
+ parent?: string | null;
561
+ context_length?: number;
562
+ max_input_tokens?: number;
563
+ max_output_tokens?: number;
564
+ input_modalities?: string[];
565
+ output_modalities?: string[];
566
+ capabilities?: {
567
+ tool_calling?: boolean;
568
+ reasoning?: boolean;
569
+ vision?: boolean;
570
+ thinking?: boolean;
571
+ attachment?: boolean;
572
+ structured_output?: boolean;
573
+ temperature?: boolean;
574
+ };
575
+ release_date?: string;
576
+ last_updated?: string;
577
+ api_format?: string;
578
+ }
579
+
580
+ /**
581
+ * Fetcher contract: returns the raw `/v1/models` entry list from a running
582
+ * OmniRoute instance. Surfaced as a dependency so unit tests can inject a
583
+ * stub without monkey-patching global `fetch`.
584
+ *
585
+ * Why we inline this instead of using `@omniroute/opencode-provider`'s
586
+ * `fetchLiveModels`: the sibling helper returns a stripped `{id, name,
587
+ * contextLength?}` shape (see opencode-provider/src/index.ts:480-569) that
588
+ * drops the `capabilities` / `*_modalities` / `max_*_tokens` blocks T-03
589
+ * needs for ModelV2 pass-through. Adopting the sibling here would force a
590
+ * client-side re-fetch or re-introduce the synthesis we explicitly rejected
591
+ * in OQ-3. A 30-line raw fetcher is cheaper than mutating the sibling's
592
+ * stable v0.1.0 contract.
593
+ */
594
+ export type OmniRouteModelsFetcher = (
595
+ baseURL: string,
596
+ apiKey: string,
597
+ timeoutMs?: number
598
+ ) => Promise<OmniRouteRawModelEntry[]>;
599
+
600
+ /**
601
+ * Default fetcher: `GET <baseURL>/v1/models` with bearer auth + AbortController
602
+ * timeout. Accepts both the `{object:"list", data:[…]}` envelope OmniRoute
603
+ * emits today and a bare-array envelope (defensive — keeps the plugin
604
+ * working if a future OmniRoute build trims the wrapper). Anything that
605
+ * isn't an object with a string `id` is filtered out silently.
606
+ */
607
+ export const defaultOmniRouteModelsFetcher: OmniRouteModelsFetcher = async (
608
+ baseURL,
609
+ apiKey,
610
+ timeoutMs = 10_000
611
+ ) => {
612
+ if (!apiKey) throw new Error("@omniroute/opencode-plugin: apiKey required to fetch /v1/models");
613
+ if (!baseURL) throw new Error("@omniroute/opencode-plugin: baseURL required to fetch /v1/models");
614
+
615
+ const trimmed = trimTrailingSlashes(baseURL);
616
+ // Tolerate both `https://host` and `https://host/v1` forms — the gateway
617
+ // exposes /v1/models either way; we just don't want a double `/v1/v1`.
618
+ const url = /\/v\d+$/.test(trimmed) ? `${trimmed}/models` : `${trimmed}/v1/models`;
619
+
620
+ const controller = new AbortController();
621
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
622
+ try {
623
+ const res = await fetch(url, {
624
+ method: "GET",
625
+ headers: {
626
+ Authorization: `Bearer ${apiKey}`,
627
+ Accept: "application/json",
628
+ },
629
+ signal: controller.signal,
630
+ });
631
+ if (!res.ok) {
632
+ throw new Error(
633
+ `@omniroute/opencode-plugin: GET ${url} failed: ${res.status} ${res.statusText}`
634
+ );
635
+ }
636
+ const body = (await res.json()) as unknown;
637
+ const rawList: unknown[] = Array.isArray(body)
638
+ ? body
639
+ : body && typeof body === "object" && Array.isArray((body as { data?: unknown }).data)
640
+ ? ((body as { data: unknown[] }).data as unknown[])
641
+ : [];
642
+ const out: OmniRouteRawModelEntry[] = [];
643
+ for (const r of rawList) {
644
+ if (r && typeof r === "object" && typeof (r as { id?: unknown }).id === "string") {
645
+ out.push(r as OmniRouteRawModelEntry);
646
+ }
647
+ }
648
+ return out;
649
+ } finally {
650
+ clearTimeout(timer);
651
+ }
652
+ };
653
+
654
+ /**
655
+ * Map a raw `/v1/models` entry → `ModelV2` (the type @opencode-ai/sdk/v2
656
+ * exports as `Model`, re-exported by @opencode-ai/plugin as `ModelV2`).
657
+ *
658
+ * ModelV2 (as of @opencode-ai/sdk@v2 — see node_modules path
659
+ * `@opencode-ai/sdk/dist/v2/gen/types.gen.d.ts:964-1043`) requires a much
660
+ * richer shape than the T-03 spec's mapping table assumed. Concretely it
661
+ * expects:
662
+ * - flat `id`, `name`, `providerID`, `api: {id,url,npm}`
663
+ * - nested `capabilities: { temperature, reasoning, attachment, toolcall,
664
+ * input:{text,audio,image,video,pdf}, output:{…}, interleaved }`
665
+ * - `cost: { input, output, cache:{read,write} }` (NOT optional)
666
+ * - `limit: { context, input?, output }`
667
+ * - `status: "alpha"|"beta"|"deprecated"|"active"`, `options:{}`, `headers:{}`
668
+ * - `release_date: string`
669
+ *
670
+ * Deviations from the T-03 spec (documented per ticket §2 "CRITICAL: Check
671
+ * the actual ModelV2 type and adapt if field names differ"):
672
+ * 1. Spec's flat `tool_call` / `reasoning` / `attachment` / `modalities`
673
+ * top-level fields don't exist in ModelV2 — folded into
674
+ * `capabilities.{toolcall, reasoning, attachment, input.*, output.*}`.
675
+ * 2. `cost: undefined` is illegal (cost is required). OmniRoute doesn't
676
+ * surface pricing on /v1/models, so we emit a zeroed cost block.
677
+ * Downstream OC reads this for display only — the live pricing is
678
+ * OmniRoute's responsibility at routing time.
679
+ * 3. `tool_call` (spec) → `toolcall` (ModelV2 field name; one word).
680
+ * 4. `attachment` (spec) maps from `capabilities.vision` per OmniRoute
681
+ * convention: vision = ability to receive image attachments. If the
682
+ * raw entry happens to expose an explicit `capabilities.attachment`
683
+ * (some combo entries do), that wins.
684
+ * 5. `thinking` from OmniRoute has no 1:1 ModelV2 slot. We OR it into
685
+ * `reasoning` so thinking-only models still surface a non-false
686
+ * reasoning flag.
687
+ * 6. `last_updated` from OmniRoute has no ModelV2 slot — dropped (the
688
+ * spec also flagged this as "may not exist", and the prod sample
689
+ * confirms it's optional). `release_date` lands in ModelV2.release_date
690
+ * with `""` fallback (the field is required as `string`).
691
+ * 7. `temperature: true` per OmniRoute convention (OpenAI-compat mode
692
+ * always supports the temperature knob). If a raw entry sets
693
+ * `capabilities.temperature` explicitly, that wins.
694
+ * 8. Input/output modality arrays: each known modality flips its boolean.
695
+ * Unknown strings (future OmniRoute additions) are ignored — when the
696
+ * server adds new modalities we can map them here without breaking
697
+ * existing entries.
698
+ * 9. `status: "active"` — OmniRoute doesn't tier models alpha/beta on
699
+ * /v1/models, and OC needs a non-deprecated status to expose the
700
+ * model in the picker. If a future entry surfaces an explicit
701
+ * lifecycle hint we can map it then.
702
+ * 10. `options: {}` and `headers: {}` left empty — they're escape hatches
703
+ * for OC users to attach per-model overrides; the provider plugin
704
+ * must not preempt them.
705
+ * 11. `limit.input` is OPTIONAL on ModelV2 (the `?` modifier). We only
706
+ * emit it when OmniRoute supplies `max_input_tokens` — keeps the
707
+ * shape clean for combo entries that only carry context_length.
708
+ */
709
+
710
+ export function mapRawModelToModelV2(
711
+ raw: OmniRouteRawModelEntry,
712
+ ctx: { providerId: string; baseURL: string; apiFormat?: { anthropicPrefixes?: string[] } }
713
+ ): ModelV2 {
714
+ const caps = raw.capabilities ?? {};
715
+ const inMods = new Set(raw.input_modalities ?? ["text"]);
716
+ const outMods = new Set(raw.output_modalities ?? ["text"]);
717
+
718
+ return {
719
+ // OC's static-catalog reader parses the key on `/` to recover
720
+ // `(providerID, modelID)`. If the raw id is already provider-prefixed
721
+ // (e.g. `cc/claude-opus-4-7` from the `cc` Claude Code alias, or
722
+ // `nvidia/llama-3-70b` from a provider that ships prefixed ids), leave
723
+ // it as-is — double-prefixing breaks OC's lookup. Otherwise prefix with
724
+ // the resolved `providerId` so a bare key like `claude-opus-4` parses as
725
+ // `(omniroute, claude-opus-4)` and the credentials resolve correctly.
726
+ id: raw.id.includes("/") ? raw.id : `${ctx.providerId}/${raw.id}`,
727
+ /**
728
+ * Display name. Falls back to raw.id when no enrichment is available;
729
+ * the caller (`createOmniRouteProviderHook`) overlays
730
+ * `/api/pricing/models` data via `applyEnrichment` when
731
+ * `features.enrichment` is true.
732
+ */
733
+ name: _normaliseFreeLabel(raw.id),
734
+ capabilities: {
735
+ temperature: caps.temperature ?? true,
736
+ reasoning: Boolean(caps.reasoning || caps.thinking),
737
+ attachment: Boolean(caps.attachment ?? caps.vision ?? false),
738
+ toolcall: Boolean(caps.tool_calling ?? false),
739
+ input: {
740
+ text: inMods.has("text"),
741
+ audio: inMods.has("audio"),
742
+ image: inMods.has("image"),
743
+ video: inMods.has("video"),
744
+ pdf: inMods.has("pdf"),
745
+ },
746
+ output: {
747
+ text: outMods.has("text"),
748
+ audio: outMods.has("audio"),
749
+ image: outMods.has("image"),
750
+ video: outMods.has("video"),
751
+ pdf: outMods.has("pdf"),
752
+ },
753
+ interleaved: Boolean(caps.thinking),
754
+ },
755
+ cost: {
756
+ input: 0,
757
+ output: 0,
758
+ cache: { read: 0, write: 0 },
759
+ },
760
+ limit: {
761
+ context: typeof raw.context_length === "number" ? raw.context_length : 0,
762
+ ...(typeof raw.max_input_tokens === "number" ? { input: raw.max_input_tokens } : {}),
763
+ output: typeof raw.max_output_tokens === "number" ? raw.max_output_tokens : 0,
764
+ },
765
+ status: "active",
766
+ options: {},
767
+ headers: {},
768
+ release_date: raw.release_date ?? "",
769
+ providerID: ctx.providerId,
770
+ api: resolveApiBlock(raw.id, ctx.baseURL, ctx.apiFormat),
771
+ };
772
+ }
773
+
774
+ // ────────────────────────────────────────────────────────────────────────────
775
+ // Combo discovery (T-05) — /api/combos pass-through with LCD capability roll-up
776
+ // ────────────────────────────────────────────────────────────────────────────
777
+
778
+ /**
779
+ * Raw shape of a single combo entry as returned by OmniRoute's `/api/combos`.
780
+ *
781
+ * Schema established via a live probe against
782
+ * an OmniRoute `/api/combos` endpoint with a management-scoped key
783
+ * (response saved at /tmp/t05-combos.json) cross-referenced against the
784
+ * source-of-truth in this repo:
785
+ *
786
+ * - `src/app/api/combos/route.ts` GET handler — emits `{combos: [...]}`
787
+ * envelope after `getCombos()`.
788
+ * - `src/lib/db/combos.ts` `getCombos()` — returns rows persisted via
789
+ * `createCombo` / `updateCombo`, each shaped by `normalizeStoredCombo`.
790
+ * - `src/lib/combos/steps.ts` `ComboModelStep` + `ComboRefStep` — define
791
+ * the `models[]` array entry shape (a step references a member model
792
+ * by its full provider-prefixed id, e.g. `"claude-opus-4-5-thinking"`).
793
+ *
794
+ * Note: the preprod gateway returned `{combos: []}` at probe time (no combos
795
+ * provisioned). The defensive parser accepts both `{combos:[...]}` and a
796
+ * bare array envelope so the plugin keeps working if a future OmniRoute
797
+ * build trims the wrapper (mirrors the same pattern in the sibling
798
+ * `@omniroute/opencode-provider#listCombos`).
799
+ *
800
+ * STRICT source-of-truth (OQ-3, per T-03): every ModelV2 field a combo
801
+ * surfaces traces back to either (a) this raw combo entry or (b) the LCD
802
+ * roll-up across its raw member models. No client-side variant synthesis.
803
+ */
804
+ export interface OmniRouteRawComboMemberRef {
805
+ /** Step kind: "model" references a raw model id; "combo-ref" nests another combo. */
806
+ kind?: "model" | "combo-ref";
807
+ /** Full model id referenced by this step (when kind === "model"). */
808
+ model?: string;
809
+ /** Nested combo name (when kind === "combo-ref"). */
810
+ comboName?: string;
811
+ /** Routing weight inside the combo (0–100, advisory at LCD time). */
812
+ weight?: number;
813
+ /** Step-local label, distinct from the parent combo's display name. */
814
+ label?: string;
815
+ }
816
+
817
+ export interface OmniRouteRawCombo {
818
+ id: string;
819
+ name?: string;
820
+ /** Routing strategy. Surfaced for forward-compat but not consumed by LCD. */
821
+ strategy?: string;
822
+ /** Member step list. Only `kind: "model"` steps participate in LCD. */
823
+ models?: OmniRouteRawComboMemberRef[];
824
+ /** Hidden combos are excluded from the OC model picker. */
825
+ isHidden?: boolean;
826
+ /** When OmniRoute attaches a lifecycle hint we forward it; today it doesn't. */
827
+ release_date?: string;
828
+ }
829
+
830
+ /**
831
+ * Fetcher contract for `/api/combos`. Same DI shape as
832
+ * `OmniRouteModelsFetcher` so unit tests can inject a stub instead of
833
+ * monkey-patching global `fetch`.
834
+ */
835
+ export type OmniRouteCombosFetcher = (
836
+ baseURL: string,
837
+ apiKey: string,
838
+ timeoutMs?: number
839
+ ) => Promise<OmniRouteRawCombo[]>;
840
+
841
+ /**
842
+ * Default fetcher: `GET <baseURL>/api/combos` with bearer auth +
843
+ * AbortController timeout. Accepts both the `{combos: [...]}` envelope the
844
+ * gateway emits today and a bare-array envelope (defensive — keeps the
845
+ * plugin working if a future OmniRoute build trims the wrapper).
846
+ *
847
+ * Differences from `defaultOmniRouteModelsFetcher`:
848
+ * - URL is `/api/combos`, NOT `/v1/combos`. The `/v1/...` namespace is the
849
+ * OpenAI-compatible surface (chat completions, models); combo discovery
850
+ * lives on the management plane under `/api/...`. We tolerate both
851
+ * `https://host` and `https://host/v1` baseURL forms by stripping the
852
+ * trailing `/v1` segment before appending `/api/combos`.
853
+ * - Combos endpoint requires a management-scoped API key when
854
+ * `REQUIRE_API_KEY` is enabled. We don't enforce that here; the
855
+ * gateway returns 401/403 with an actionable error which we propagate.
856
+ *
857
+ * Anything that isn't an object with a string `id` is filtered out silently.
858
+ */
859
+ export const defaultOmniRouteCombosFetcher: OmniRouteCombosFetcher = async (
860
+ baseURL,
861
+ apiKey,
862
+ timeoutMs = 10_000
863
+ ) => {
864
+ if (!apiKey) throw new Error("@omniroute/opencode-plugin: apiKey required to fetch /api/combos");
865
+ if (!baseURL)
866
+ throw new Error("@omniroute/opencode-plugin: baseURL required to fetch /api/combos");
867
+
868
+ // Strip trailing slashes, then strip a trailing `/v1` so we land on the
869
+ // management plane. Models live under `/v1/models`; combos live under
870
+ // `/api/combos` from the same gateway root.
871
+ const trimmed = trimTrailingSlashes(baseURL);
872
+ const root = trimmed.replace(/\/v\d+$/, "");
873
+ const url = `${root}/api/combos`;
874
+
875
+ const controller = new AbortController();
876
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
877
+ try {
878
+ const res = await fetch(url, {
879
+ method: "GET",
880
+ headers: {
881
+ Authorization: `Bearer ${apiKey}`,
882
+ Accept: "application/json",
883
+ },
884
+ signal: controller.signal,
885
+ });
886
+ if (!res.ok) {
887
+ throw new Error(
888
+ `@omniroute/opencode-plugin: GET ${url} failed: ${res.status} ${res.statusText}`
889
+ );
890
+ }
891
+ const body = (await res.json()) as unknown;
892
+ const rawList: unknown[] = Array.isArray(body)
893
+ ? body
894
+ : body && typeof body === "object" && Array.isArray((body as { combos?: unknown }).combos)
895
+ ? ((body as { combos: unknown[] }).combos as unknown[])
896
+ : [];
897
+ const out: OmniRouteRawCombo[] = [];
898
+ for (const r of rawList) {
899
+ if (r && typeof r === "object" && typeof (r as { id?: unknown }).id === "string") {
900
+ out.push(r as OmniRouteRawCombo);
901
+ }
902
+ }
903
+ return out;
904
+ } finally {
905
+ clearTimeout(timer);
906
+ }
907
+ };
908
+
909
+ /**
910
+ * Map a raw combo entry → `ModelV2` by computing the lowest-common-denominator
911
+ * (LCD) of its underlying member models. The LCD policy is the only way to
912
+ * surface a single capability vector to OpenCode without lying: if any member
913
+ * lacks a capability, the combo as a whole cannot guarantee it.
914
+ *
915
+ * LCD rules:
916
+ * - `limit.context` = `min(...members.context_length)`.
917
+ * - `limit.output` = `min(...members.max_output_tokens)`.
918
+ * - `limit.input` = `min(...members.max_input_tokens)` ONLY when every
919
+ * member declares one (ModelV2.limit.input is optional — better to
920
+ * omit than to fabricate a min over partial data).
921
+ * - `capabilities.toolcall` / `reasoning` / `attachment` / `temperature`:
922
+ * `every(member ⇒ supports?)`. The `reasoning` axis ORs across
923
+ * `reasoning` and `thinking` per member before AND-ing across the
924
+ * combo (mirrors `mapRawModelToModelV2`). The `attachment` axis ORs
925
+ * across `attachment` and `vision` per member. The `temperature` axis
926
+ * uses default-true semantics: a member supports temperature unless
927
+ * it explicitly declares `temperature: false`.
928
+ * - `capabilities.input.*` / `output.*`: flattened AND across members'
929
+ * modality flags. Missing arrays default to `["text"]` (same default
930
+ * as `mapRawModelToModelV2`).
931
+ *
932
+ * Defensive: empty members array → ALL capabilities `false`, limits zero.
933
+ * That's an intentional safety posture (you can't route through an empty
934
+ * combo, so OC should grey it out in the picker).
935
+ *
936
+ * Spec mapping (T-05 §Scope.3): `cost` zeroed; `status = "active"`;
937
+ * `release_date = combo.release_date ?? ""`; `api.id = "openai-compatible"`;
938
+ * `name = combo.name ?? combo.id`.
939
+ *
940
+ * @param combo Raw `/api/combos` entry.
941
+ * @param members Raw `/v1/models` entries for THIS combo's member ids.
942
+ * Caller resolves `combo.models[].model` ids; unknown ids
943
+ * are silently dropped before this call.
944
+ * @param providerId OpenCode provider id (multi-instance aware).
945
+ * @param baseURL Resolved gateway base URL for ModelV2.api.url.
946
+ */
947
+ export function mapComboToModelV2(
948
+ combo: OmniRouteRawCombo,
949
+ members: OmniRouteRawModelEntry[],
950
+ providerId: string,
951
+ baseURL: string,
952
+ apiFormat?: { anthropicPrefixes?: string[] }
953
+ ): ModelV2 {
954
+ // `every` over an empty array returns true (would lie about an empty
955
+ // combo's capabilities) — short-circuit to all-false when no members.
956
+ const hasMembers = members.length > 0;
957
+
958
+ const memberInMods = members.map((m) => new Set(m.input_modalities ?? ["text"]));
959
+ const memberOutMods = members.map((m) => new Set(m.output_modalities ?? ["text"]));
960
+
961
+ const modalityAllHave = (sets: Array<Set<string>>, key: string): boolean =>
962
+ hasMembers && sets.every((s) => s.has(key));
963
+
964
+ const contextValues = members
965
+ .map((m) => m.context_length)
966
+ .filter((v): v is number => typeof v === "number" && v > 0);
967
+ const outputValues = members
968
+ .map((m) => m.max_output_tokens)
969
+ .filter((v): v is number => typeof v === "number" && v > 0);
970
+ const inputValues = members
971
+ .map((m) => m.max_input_tokens)
972
+ .filter((v): v is number => typeof v === "number" && v > 0);
973
+
974
+ const everyDeclaresInput = hasMembers && inputValues.length === members.length;
975
+
976
+ const capabilities: ModelV2["capabilities"] = {
977
+ temperature:
978
+ hasMembers && members.every((m) => (m.capabilities?.temperature ?? true) !== false),
979
+ reasoning:
980
+ hasMembers &&
981
+ members.every((m) => Boolean(m.capabilities?.reasoning || m.capabilities?.thinking)),
982
+ attachment:
983
+ hasMembers &&
984
+ members.every((m) => Boolean(m.capabilities?.attachment ?? m.capabilities?.vision ?? false)),
985
+ toolcall: hasMembers && members.every((m) => Boolean(m.capabilities?.tool_calling ?? false)),
986
+ input: {
987
+ text: modalityAllHave(memberInMods, "text"),
988
+ audio: modalityAllHave(memberInMods, "audio"),
989
+ image: modalityAllHave(memberInMods, "image"),
990
+ video: modalityAllHave(memberInMods, "video"),
991
+ pdf: modalityAllHave(memberInMods, "pdf"),
992
+ },
993
+ output: {
994
+ text: modalityAllHave(memberOutMods, "text"),
995
+ audio: modalityAllHave(memberOutMods, "audio"),
996
+ image: modalityAllHave(memberOutMods, "image"),
997
+ video: modalityAllHave(memberOutMods, "video"),
998
+ pdf: modalityAllHave(memberOutMods, "pdf"),
999
+ },
1000
+ interleaved: hasMembers && members.every((m) => Boolean(m.capabilities?.thinking)),
1001
+ };
1002
+
1003
+ // Combos span multiple providers. Use Anthropic format only when ALL
1004
+ // members resolve to Anthropic — otherwise fall back to OpenAI-compat
1005
+ // (lowest common denominator that every upstream understands).
1006
+ const comboApiBlock = (() => {
1007
+ if (!hasMembers) return resolveApiBlock("", baseURL, apiFormat);
1008
+ const allAnthropic = members.every(
1009
+ (m) => resolveApiBlock(m.id, baseURL, apiFormat).id === "anthropic"
1010
+ );
1011
+ return allAnthropic
1012
+ ? resolveApiBlock(members[0].id, baseURL, apiFormat)
1013
+ : {
1014
+ id: "openai-compatible",
1015
+ url: ensureV1Suffix(baseURL),
1016
+ npm: "@ai-sdk/openai-compatible",
1017
+ };
1018
+ })();
1019
+
1020
+ return {
1021
+ id: combo.id,
1022
+ providerID: providerId,
1023
+ api: comboApiBlock,
1024
+ name: combo.name && combo.name.trim().length > 0 ? combo.name : combo.id,
1025
+ capabilities,
1026
+ cost: {
1027
+ input: 0,
1028
+ output: 0,
1029
+ cache: { read: 0, write: 0 },
1030
+ },
1031
+ limit: {
1032
+ context: contextValues.length > 0 ? Math.min(...contextValues) : 0,
1033
+ ...(everyDeclaresInput ? { input: Math.min(...inputValues) } : {}),
1034
+ output: outputValues.length > 0 ? Math.min(...outputValues) : 0,
1035
+ },
1036
+ status: "active",
1037
+ options: {},
1038
+ headers: {},
1039
+ release_date: combo.release_date ?? "",
1040
+ };
1041
+ }
1042
+
1043
+ // ─────────────────────────────────────────────────────────────────────────
1044
+ // AUTO COMBOS — virtual server-side combos exposed via /api/combos/auto
1045
+ // ─────────────────────────────────────────────────────────────────────────
1046
+
1047
+ /**
1048
+ * Raw shape of an auto combo entry as returned by OmniRoute's
1049
+ * `/api/combos/auto` endpoint. Auto combos are virtual — they self-manage
1050
+ * provider selection via scoring/bandit exploration at runtime.
1051
+ */
1052
+ export interface OmniRouteRawAutoCombo {
1053
+ /** Stable id (e.g. "auto", "auto/coding"). */
1054
+ id: string;
1055
+ /** Human-readable name (e.g. "Auto", "Auto Coding"). */
1056
+ name: string;
1057
+ /** Variant key or undefined for the default auto. */
1058
+ variant?: AutoVariant;
1059
+ /** Provider names eligible for this auto combo. */
1060
+ candidatePool?: string[];
1061
+ /** Number of candidates resolved at fetch time. */
1062
+ candidateCount?: number;
1063
+ /** MAX of candidates' context windows, served by newer OmniRoute builds.
1064
+ * Absent on older servers — mapper falls back to a safe positive default. */
1065
+ context_length?: number;
1066
+ /** MAX of candidates' max output tokens (same provenance as context_length). */
1067
+ max_output_tokens?: number;
1068
+ /** Whether this auto combo should be hidden from the picker. */
1069
+ isHidden?: boolean;
1070
+ /** Auto-combo configuration. */
1071
+ config?: {
1072
+ auto?: {
1073
+ candidatePool?: string[];
1074
+ explorationRate?: number;
1075
+ routerStrategy?: string;
1076
+ };
1077
+ };
1078
+ }
1079
+
1080
+ /**
1081
+ * Fetcher contract for `/api/combos/auto`. Returns the list of virtual
1082
+ * auto combos the server can create. Same DI pattern as other fetchers.
1083
+ */
1084
+ export type OmniRouteAutoCombosFetcher = (
1085
+ baseURL: string,
1086
+ apiKey: string,
1087
+ timeoutMs?: number
1088
+ ) => Promise<OmniRouteRawAutoCombo[]>;
1089
+
1090
+ /**
1091
+ * Default auto combos fetcher: `GET <baseURL>/api/combos/auto`.
1092
+ *
1093
+ * Fault-tolerant: returns empty array on 404 (endpoint doesn't exist yet)
1094
+ * or any non-2xx / network error. Logs a warning in those cases.
1095
+ */
1096
+ export const defaultOmniRouteAutoCombosFetcher: OmniRouteAutoCombosFetcher = async (
1097
+ baseURL,
1098
+ apiKey,
1099
+ timeoutMs = 5_000
1100
+ ) => {
1101
+ if (!apiKey || !baseURL) return [];
1102
+
1103
+ const trimmed = trimTrailingSlashes(baseURL);
1104
+ const root = trimmed.replace(/\/v\d+$/, "");
1105
+ const url = `${root}/api/combos/auto`;
1106
+
1107
+ const controller = new AbortController();
1108
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1109
+ try {
1110
+ const res = await fetch(url, {
1111
+ method: "GET",
1112
+ headers: {
1113
+ Authorization: `Bearer ${apiKey}`,
1114
+ Accept: "application/json",
1115
+ },
1116
+ signal: controller.signal,
1117
+ });
1118
+ // 404 = endpoint not deployed yet — expected during rollout
1119
+ if (res.status === 404) {
1120
+ console.warn(
1121
+ `[omniroute-plugin] /api/combos/auto not available (404) — auto combos disabled`
1122
+ );
1123
+ return [];
1124
+ }
1125
+ if (!res.ok) {
1126
+ console.warn(
1127
+ `[omniroute-plugin] /api/combos/auto failed: ${res.status} ${res.statusText} — auto combos disabled`
1128
+ );
1129
+ return [];
1130
+ }
1131
+ const body = (await res.json()) as unknown;
1132
+ const rawList: unknown[] = Array.isArray(body)
1133
+ ? body
1134
+ : body && typeof body === "object" && Array.isArray((body as { combos?: unknown }).combos)
1135
+ ? ((body as { combos: unknown[] }).combos as unknown[])
1136
+ : [];
1137
+ const out: OmniRouteRawAutoCombo[] = [];
1138
+ for (const r of rawList) {
1139
+ if (r && typeof r === "object" && typeof (r as { id?: unknown }).id === "string") {
1140
+ out.push(r as OmniRouteRawAutoCombo);
1141
+ }
1142
+ }
1143
+ return out;
1144
+ } catch (err) {
1145
+ // Network error, timeout, abort — all non-fatal
1146
+ console.warn(
1147
+ `[omniroute-plugin] /api/combos/auto fetch failed: ${err instanceof Error ? err.message : String(err)} — auto combos disabled`
1148
+ );
1149
+ return [];
1150
+ } finally {
1151
+ clearTimeout(timer);
1152
+ }
1153
+ };
1154
+
1155
+ /** Fallbacks when the server does not advertise auto-combo limits (older
1156
+ * OmniRoute builds). MUST be positive: OpenCode's overflow guard treats
1157
+ * `limit.context === 0` as "never overflow" and silently DISABLES smart
1158
+ * auto-compaction, letting the session grow until the gateway's destructive
1159
+ * history purge kicks in (the "agent keeps forgetting things" bug). */
1160
+ const AUTO_COMBO_FALLBACK_CONTEXT = 128_000;
1161
+ const AUTO_COMBO_FALLBACK_OUTPUT = 8_192;
1162
+
1163
+ /**
1164
+ * Convert a raw auto combo into a static model entry for the OpenCode picker.
1165
+ * Auto combos have tool_call=true, reasoning=true by default (they route
1166
+ * to capable models). Context/output limits come from the server (MAX of
1167
+ * the candidate pool's windows — the gateway's context pre-filter routes
1168
+ * oversized requests to large-window candidates); a safe positive fallback
1169
+ * applies when the server omits them. Never 0.
1170
+ */
1171
+ export function mapAutoComboToStaticEntry(
1172
+ autoCombo: OmniRouteRawAutoCombo
1173
+ ): OmniRouteStaticModelEntry {
1174
+ const variant = autoCombo.variant;
1175
+ const name = formatAutoComboName(variant, autoCombo.candidateCount);
1176
+ const context =
1177
+ typeof autoCombo.context_length === "number" && autoCombo.context_length > 0
1178
+ ? autoCombo.context_length
1179
+ : AUTO_COMBO_FALLBACK_CONTEXT;
1180
+ const output =
1181
+ typeof autoCombo.max_output_tokens === "number" && autoCombo.max_output_tokens > 0
1182
+ ? autoCombo.max_output_tokens
1183
+ : AUTO_COMBO_FALLBACK_OUTPUT;
1184
+ // No `providerID` field on static-catalog entries — OC ignores it on the static
1185
+ // path, and stamping it on auto-combos but not on raw/combo entries was an
1186
+ // internal inconsistency. The dynamic-hook path builds its ModelV2 from the
1187
+ // individual fields below and never read this field either.
1188
+ return {
1189
+ name,
1190
+ attachment: false,
1191
+ reasoning: true,
1192
+ temperature: true,
1193
+ tool_call: true,
1194
+ limit: { context, output },
1195
+ modalities: {
1196
+ input: ["text"],
1197
+ output: ["text"],
1198
+ },
1199
+ cost: { input: 0, output: 0, cache_read: 0, cache_write: 0 },
1200
+ };
1201
+ }
1202
+
1203
+ // ─────────────────────────────────────────────────────────────────────────
1204
+ // ENRICHMENT — pull display names + pricing from /api/pricing/models so
1205
+ // the UI doesn't have to render raw model ids. Gated by features.enrichment.
1206
+ // ─────────────────────────────────────────────────────────────────────────
1207
+
1208
+ /**
1209
+ * Per-model enrichment overlay derived from OmniRoute's
1210
+ * `/api/pricing/models` endpoint. The endpoint returns a per-provider
1211
+ * catalog with curated `name` strings (e.g. `Claude 4.7 Opus`,
1212
+ * `GPT 5.5 Pro`, `Gemini 3.1 Pro`) and per-million-token pricing
1213
+ * (`pricing.input`, `pricing.output`, `pricing.cacheRead`,
1214
+ * `pricing.cacheWrite`). These overlay the ModelV2 entries produced by
1215
+ * `mapRawModelToModelV2`.
1216
+ */
1217
+ export interface OmniRouteEnrichmentEntry {
1218
+ /** Human-readable display name. Replaces ModelV2.name when present. */
1219
+ name?: string;
1220
+ /** Per-million-token cost overlay onto ModelV2.cost. */
1221
+ pricing?: {
1222
+ input?: number;
1223
+ output?: number;
1224
+ cacheRead?: number;
1225
+ cacheWrite?: number;
1226
+ };
1227
+ /**
1228
+ * Provider alias prefix seen in `/v1/models` ids (e.g. `cc`, `gemini`).
1229
+ * Populated by `defaultOmniRouteEnrichmentFetcher` from
1230
+ * `/api/pricing/models` keys. Drives the `usableOnly` alias↔canonical
1231
+ * resolution.
1232
+ */
1233
+ providerAlias?: string;
1234
+ /**
1235
+ * Canonical provider id used by `/api/providers` connections (e.g.
1236
+ * `claude`, `gemini`, `kiro`). Populated from the per-provider
1237
+ * `entry.id` field inside `/api/pricing/models`.
1238
+ */
1239
+ providerCanonical?: string;
1240
+ /**
1241
+ * Human-readable upstream provider label (e.g. `Claude`, `Kiro`,
1242
+ * `Windsurf`, `GitHub Models`). Populated from the per-provider
1243
+ * `entry.name` field inside `/api/pricing/models`. Used by the
1244
+ * `providerTag` feature to suffix `ModelV2.name` with the routing
1245
+ * destination so the OC TUI picker can differentiate the same
1246
+ * model id sold through different upstream connections.
1247
+ */
1248
+ providerDisplayName?: string;
1249
+ /** Free-model budget type (from freeModelCatalog). */
1250
+ freeType?: FreeModelFreeType;
1251
+ /** Monthly token budget for recurring free models. */
1252
+ monthlyTokens?: number;
1253
+ /** Credit token budget for credit-based free models. */
1254
+ creditTokens?: number;
1255
+ }
1256
+
1257
+ /** Map keyed by full model id (possibly namespaced, e.g. `cc/claude-sonnet-4-6`). */
1258
+ export type OmniRouteEnrichmentMap = Map<string, OmniRouteEnrichmentEntry>;
1259
+
1260
+ export type OmniRouteEnrichmentFetcher = (
1261
+ baseURL: string,
1262
+ apiKey: string,
1263
+ timeoutMs?: number
1264
+ ) => Promise<OmniRouteEnrichmentMap>;
1265
+
1266
+ /**
1267
+ * Default enrichment fetcher — pulls nice display names from
1268
+ * `GET /api/pricing/models` and merges per-million-token pricing from
1269
+ * `GET /api/pricing` (the actual pricing source — `/api/pricing/models` is
1270
+ * a catalog endpoint whose entries are `{id, name, custom}` only).
1271
+ *
1272
+ * `/api/pricing/models` shape (catalog):
1273
+ * - `{ [providerAlias]: { id, alias, name, models: [{ id, name, custom }] } }`
1274
+ *
1275
+ * `/api/pricing` shape (pricing only):
1276
+ * - `{ [providerAlias]: { [modelId]: { input, output, cached, reasoning, cache_creation } } }`
1277
+ * where values are USD per million tokens.
1278
+ *
1279
+ * The two responses are joined on `(providerAlias, modelId)` and the merged
1280
+ * entries are stored under both `${providerAlias}/${modelId}` and bare
1281
+ * `${modelId}` keys so downstream lookups against either form succeed.
1282
+ *
1283
+ * Soft-fails (returns whatever was collected) on non-2xx or parse errors;
1284
+ * the two fetches are independent so one missing source still surfaces the
1285
+ * other.
1286
+ */
1287
+ export const defaultOmniRouteEnrichmentFetcher: OmniRouteEnrichmentFetcher = async (
1288
+ baseURL,
1289
+ apiKey,
1290
+ timeoutMs = 10_000
1291
+ ) => {
1292
+ const out: OmniRouteEnrichmentMap = new Map();
1293
+ if (!baseURL || !apiKey) return out;
1294
+ const root = baseURL.replace(/\/v1\/?$/, "").replace(/\/$/, "");
1295
+ const headers = {
1296
+ Authorization: `Bearer ${apiKey}`,
1297
+ Accept: "application/json",
1298
+ };
1299
+
1300
+ // ── 1. Catalog with nice display names ────────────────────────────────
1301
+ const catalogAc = new AbortController();
1302
+ const catalogTimer = setTimeout(() => catalogAc.abort(), timeoutMs);
1303
+ try {
1304
+ const res = await fetch(`${root}/api/pricing/models`, {
1305
+ method: "GET",
1306
+ headers,
1307
+ signal: catalogAc.signal,
1308
+ });
1309
+ if (res.ok) {
1310
+ const body = (await res.json()) as unknown;
1311
+ const providers =
1312
+ (body as { providers?: Record<string, { models?: unknown[] }> })?.providers ??
1313
+ (body as Record<string, { models?: unknown[] }>);
1314
+ if (providers && typeof providers === "object") {
1315
+ for (const [providerAlias, slot] of Object.entries(providers)) {
1316
+ if (!slot || typeof slot !== "object") continue;
1317
+ const models = (slot as { models?: unknown[] }).models;
1318
+ if (!Array.isArray(models)) continue;
1319
+ // Canonical id sits at the per-provider top level (e.g.
1320
+ // `pricing-models.cc.id === 'claude'`). Falls back to the alias
1321
+ // itself when missing — common case alias===canonical.
1322
+ const canonicalRaw = (slot as { id?: unknown }).id;
1323
+ const providerCanonical =
1324
+ typeof canonicalRaw === "string" && canonicalRaw.length > 0
1325
+ ? canonicalRaw
1326
+ : providerAlias;
1327
+ // Upstream provider human label (e.g. `Claude`, `Kiro`,
1328
+ // `GitHub Models`). Optional — falls back to undefined when
1329
+ // OmniRoute hasn't curated a label for this slot.
1330
+ const slotNameRaw = (slot as { name?: unknown }).name;
1331
+ const providerDisplayName =
1332
+ typeof slotNameRaw === "string" && slotNameRaw.trim().length > 0
1333
+ ? slotNameRaw.trim()
1334
+ : undefined;
1335
+ for (const m of models) {
1336
+ if (!m || typeof m !== "object") continue;
1337
+ const id = (m as { id?: unknown }).id;
1338
+ if (typeof id !== "string" || id.length === 0) continue;
1339
+ const name = (m as { name?: unknown }).name;
1340
+ const entry: OmniRouteEnrichmentEntry = {
1341
+ providerAlias,
1342
+ providerCanonical,
1343
+ };
1344
+ if (providerDisplayName) entry.providerDisplayName = providerDisplayName;
1345
+ if (typeof name === "string" && name.trim().length > 0) entry.name = name;
1346
+ const namespaced = `${providerAlias}/${id}`;
1347
+ if (!out.has(namespaced)) out.set(namespaced, entry);
1348
+ if (!out.has(id)) out.set(id, entry);
1349
+ }
1350
+ }
1351
+ }
1352
+ }
1353
+ } catch {
1354
+ // Soft-fail; keep going to pricing fetch.
1355
+ } finally {
1356
+ clearTimeout(catalogTimer);
1357
+ }
1358
+
1359
+ // ── 2. Pricing values from /api/pricing ───────────────────────────────
1360
+ const priceAc = new AbortController();
1361
+ const priceTimer = setTimeout(() => priceAc.abort(), timeoutMs);
1362
+ try {
1363
+ const res = await fetch(`${root}/api/pricing`, {
1364
+ method: "GET",
1365
+ headers,
1366
+ signal: priceAc.signal,
1367
+ });
1368
+ if (res.ok) {
1369
+ const body = (await res.json()) as unknown;
1370
+ if (body && typeof body === "object" && !Array.isArray(body)) {
1371
+ for (const [providerAlias, slot] of Object.entries(body as Record<string, unknown>)) {
1372
+ if (!slot || typeof slot !== "object" || Array.isArray(slot)) continue;
1373
+ for (const [modelId, raw] of Object.entries(slot as Record<string, unknown>)) {
1374
+ if (!raw || typeof raw !== "object") continue;
1375
+ const p = raw as Record<string, unknown>;
1376
+ const parsed: NonNullable<OmniRouteEnrichmentEntry["pricing"]> = {};
1377
+ // OmniRoute `/api/pricing` keys:
1378
+ // input → cost.input
1379
+ // output → cost.output
1380
+ // cached → cost.cache.read (alias: cacheRead)
1381
+ // cache_creation → cost.cache.write (alias: cacheWrite)
1382
+ // Tolerate alternative spellings for forward-compat.
1383
+ if (typeof p.input === "number") parsed.input = p.input;
1384
+ if (typeof p.output === "number") parsed.output = p.output;
1385
+ const cacheRead =
1386
+ typeof p.cached === "number"
1387
+ ? p.cached
1388
+ : typeof p.cacheRead === "number"
1389
+ ? p.cacheRead
1390
+ : undefined;
1391
+ if (typeof cacheRead === "number") parsed.cacheRead = cacheRead;
1392
+ const cacheWrite =
1393
+ typeof p.cache_creation === "number"
1394
+ ? p.cache_creation
1395
+ : typeof p.cacheWrite === "number"
1396
+ ? p.cacheWrite
1397
+ : undefined;
1398
+ if (typeof cacheWrite === "number") parsed.cacheWrite = cacheWrite;
1399
+ if (Object.keys(parsed).length === 0) continue;
1400
+ const namespaced = `${providerAlias}/${modelId}`;
1401
+ const existingNs = out.get(namespaced);
1402
+ if (existingNs)
1403
+ existingNs.pricing = {
1404
+ ...(existingNs.pricing ?? {}),
1405
+ ...parsed,
1406
+ };
1407
+ else out.set(namespaced, { pricing: parsed });
1408
+ const existingBare = out.get(modelId);
1409
+ if (existingBare)
1410
+ existingBare.pricing = {
1411
+ ...(existingBare.pricing ?? {}),
1412
+ ...parsed,
1413
+ };
1414
+ else out.set(modelId, { pricing: parsed });
1415
+ }
1416
+ }
1417
+ }
1418
+ }
1419
+ } catch {
1420
+ // Soft-fail; return whatever names we collected.
1421
+ } finally {
1422
+ clearTimeout(priceTimer);
1423
+ }
1424
+
1425
+ // ── 3. Free model budgets from /api/free-tier/summary ──────────────────
1426
+ // Best-effort fetch: populates freeType/monthlyTokens/creditTokens on
1427
+ // enrichment entries that match. 404 = endpoint doesn't exist — skip.
1428
+ // Uses the EXISTING /api/free-tier/summary endpoint (no new server code).
1429
+ const freeAc = new AbortController();
1430
+ const freeTimer = setTimeout(() => freeAc.abort(), timeoutMs);
1431
+ try {
1432
+ const res = await fetch(`${root}/api/free-tier/summary`, {
1433
+ method: "GET",
1434
+ headers,
1435
+ signal: freeAc.signal,
1436
+ });
1437
+ if (res.ok) {
1438
+ const body = (await res.json()) as unknown;
1439
+ // Response shape: { perModel: FreeModelBudget[], ... }
1440
+ const perModel: unknown[] =
1441
+ body && typeof body === "object" && Array.isArray((body as { perModel?: unknown }).perModel)
1442
+ ? ((body as { perModel: unknown[] }).perModel as unknown[])
1443
+ : Array.isArray(body)
1444
+ ? (body as unknown[])
1445
+ : [];
1446
+ let matched = 0;
1447
+ for (const fm of perModel) {
1448
+ if (!fm || typeof fm !== "object") continue;
1449
+ const fmObj = fm as Record<string, unknown>;
1450
+ const provider = typeof fmObj.provider === "string" ? fmObj.provider : "";
1451
+ const modelId = typeof fmObj.modelId === "string" ? fmObj.modelId : "";
1452
+ const freeType = typeof fmObj.freeType === "string" ? fmObj.freeType : "";
1453
+ if (!modelId || !freeType) continue;
1454
+ const monthlyTokens =
1455
+ typeof fmObj.monthlyTokens === "number" ? fmObj.monthlyTokens : undefined;
1456
+ const creditTokens =
1457
+ typeof fmObj.creditTokens === "number" ? fmObj.creditTokens : undefined;
1458
+ // Match against enrichment entries: namespaced, bare, and displayName
1459
+ const displayName = typeof fmObj.displayName === "string" ? fmObj.displayName : "";
1460
+ const candidates = [
1461
+ `${provider}/${modelId}`,
1462
+ modelId,
1463
+ ...(displayName ? [displayName] : []),
1464
+ ];
1465
+ for (const key of candidates) {
1466
+ const entry = out.get(key);
1467
+ if (entry) {
1468
+ entry.freeType = freeType as FreeModelFreeType;
1469
+ if (monthlyTokens !== undefined) entry.monthlyTokens = monthlyTokens;
1470
+ if (creditTokens !== undefined) entry.creditTokens = creditTokens;
1471
+ matched++;
1472
+ break;
1473
+ }
1474
+ }
1475
+ }
1476
+ _logger.debug(
1477
+ `free-tier/summary: ${perModel.length} models returned, ${matched} matched enrichment entries`
1478
+ );
1479
+ }
1480
+ } catch {
1481
+ // Soft-fail; free metadata is optional.
1482
+ } finally {
1483
+ clearTimeout(freeTimer);
1484
+ }
1485
+
1486
+ return out;
1487
+ };
1488
+
1489
+ // ── Startup diagnostics writer (file-based) ──────────────────────────────
1490
+ // OC doesn't capture plugin console.warn in its log file. Write diagnostics
1491
+ // to a file so they're readable after session starts. Capped at 64KB.
1492
+ async function writeStartupDiagnostics(params: {
1493
+ providerId: string;
1494
+ baseURL: string;
1495
+ modelCount: number;
1496
+ comboCount: number;
1497
+ enrichmentSize: number;
1498
+ autoComboCount: number;
1499
+ enrichment: OmniRouteEnrichmentMap;
1500
+ autoCombos: OmniRouteRawAutoCombo[];
1501
+ }): Promise<void> {
1502
+ const {
1503
+ providerId,
1504
+ baseURL,
1505
+ modelCount,
1506
+ comboCount,
1507
+ enrichmentSize,
1508
+ autoComboCount,
1509
+ enrichment,
1510
+ autoCombos,
1511
+ } = params;
1512
+ const enriched = [...enrichment.entries()];
1513
+ const withName = enriched.filter(([, e]) => e.name);
1514
+ const withPricing = enriched.filter(([, e]) => e.pricing);
1515
+ const withFree = enriched.filter(([, e]) => e.freeType);
1516
+
1517
+ const lines: string[] = [];
1518
+ lines.push(`=== startupDebug ${new Date().toISOString()} ===`);
1519
+ lines.push(`providerId=${providerId} baseURL=${baseURL}`);
1520
+ lines.push(
1521
+ `models=${modelCount} combos=${comboCount} enrichment=${enrichmentSize} autoCombos=${autoComboCount}`
1522
+ );
1523
+ lines.push(
1524
+ `enrichment: ${withName.length} with name, ${withPricing.length} with pricing, ${withFree.length} free`
1525
+ );
1526
+ if (withFree.length > 0) {
1527
+ lines.push(`free models (${withFree.length}):`);
1528
+ for (const [k, e] of withFree.slice(0, 10)) {
1529
+ lines.push(
1530
+ ` ${k} → name=${e.name ?? "(none)"}, freeType=${e.freeType}, monthly=${e.monthlyTokens ?? 0}, credits=${e.creditTokens ?? 0}`
1531
+ );
1532
+ }
1533
+ } else {
1534
+ lines.push(
1535
+ `NO free models detected. ` +
1536
+ (enrichmentSize === 0
1537
+ ? "Enrichment map is EMPTY."
1538
+ : `Enrichment has ${enrichmentSize} entries but none have freeType.`)
1539
+ );
1540
+ }
1541
+ const sampleNames = enriched
1542
+ .filter(([, e]) => e.name)
1543
+ .slice(0, 5)
1544
+ .map(([k, e]) => ` ${k} → "${e.name}"`);
1545
+ if (sampleNames.length > 0) {
1546
+ lines.push(`sample enriched names:`);
1547
+ lines.push(sampleNames.join("\n"));
1548
+ }
1549
+ if (autoCombos.length > 0) {
1550
+ lines.push(
1551
+ `auto combos: ${autoCombos.length} — ${autoCombos.map((ac) => `${ac.id}(${ac.candidateCount ?? "?"}p)`).join(", ")}`
1552
+ );
1553
+ }
1554
+ lines.push(`=== end startupDebug ===\n`);
1555
+
1556
+ const diagnostics = lines.join("\n");
1557
+ _logger.debug(diagnostics);
1558
+
1559
+ try {
1560
+ const diagDir =
1561
+ process.env.OPENCODE_DATA_DIR ?? path.join(os.homedir(), ".local/share/opencode");
1562
+ const diagPath = path.join(diagDir, "plugins", "omniroute-startup-diagnostics.log");
1563
+ let existing = "";
1564
+ try {
1565
+ existing = await readFile(diagPath, "utf8");
1566
+ } catch {
1567
+ /* first write */
1568
+ }
1569
+ const KEEP = 65_536;
1570
+ const combined = existing + diagnostics;
1571
+ const trimmed = combined.length > KEEP ? combined.slice(combined.length - KEEP) : combined;
1572
+ await writeFile(diagPath, trimmed, "utf8");
1573
+ } catch {
1574
+ /* best effort */
1575
+ }
1576
+ }
1577
+
1578
+ /**
1579
+ * Separator used by `applyProviderTag` between the upstream provider
1580
+ * label (prefix) and the enriched model name. ASCII hyphen with
1581
+ * surrounding spaces — terminal-safe everywhere, never collides with
1582
+ * a model id (those use slashes / dots / underscores).
1583
+ *
1584
+ * Layout: `<short-label> - <model name>` (label leads so column scans
1585
+ * group by provider — e.g. `Claude - Claude Opus 4.7`,
1586
+ * `Kiro - Claude Opus 4.7`).
1587
+ */
1588
+ export const PROVIDER_TAG_SEPARATOR = _PROVIDER_TAG_SEPARATOR;
1589
+
1590
+ // Re-export from naming.ts — thin wrapper preserving OmniRouteEnrichmentEntry signature
1591
+ export function shortProviderLabel(
1592
+ enrichment: OmniRouteEnrichmentEntry | undefined
1593
+ ): string | undefined {
1594
+ return _shortProviderLabel(enrichment);
1595
+ }
1596
+
1597
+ /**
1598
+ * Prepend the upstream provider label to `model.name` so the OC TUI
1599
+ * picker can differentiate the same model id sold through different
1600
+ * upstream connections (e.g. `cc/claude-opus-4-7` via Anthropic
1601
+ * vs `kr/claude-opus-4-7` via Kiro). Result shape:
1602
+ *
1603
+ * `<label>${PROVIDER_TAG_SEPARATOR}<enriched name>`
1604
+ * → `Claude - Claude Opus 4.7`
1605
+ * → `Kiro - Claude Opus 4.7`
1606
+ * → `AssemblyAI - Universal 2 (Transcription)` (slot.name fits, used verbatim)
1607
+ * → `GHM - GPT 5` (slot.name "GitHub Models" > 12 chars → UPPER(alias))
1608
+ *
1609
+ * Mutates the model in place and is idempotent — running twice never
1610
+ * double-prefixes. No-op when:
1611
+ *
1612
+ * - `enrichment` is undefined,
1613
+ * - {@link shortProviderLabel} returns `undefined`
1614
+ * (no `providerDisplayName` AND no `providerAlias`),
1615
+ * - the current `model.name` already starts with the prefix.
1616
+ *
1617
+ * Combos are intentionally skipped by callers (they're multi-upstream
1618
+ * by definition; the `Combo: ` prefix conveys that). Raw models call
1619
+ * this after `applyEnrichment` so the tag layers on top of the
1620
+ * friendly name.
1621
+ */
1622
+ export function applyProviderTag(
1623
+ model: ModelV2,
1624
+ enrichment: OmniRouteEnrichmentEntry | undefined
1625
+ ): ModelV2 {
1626
+ const label = shortProviderLabel(enrichment);
1627
+ if (!label) return model;
1628
+ const prefix = `${label}${PROVIDER_TAG_SEPARATOR}`;
1629
+ if (model.name.startsWith(prefix)) return model;
1630
+ // When enrichment already prepended [Free], move it before the provider
1631
+ // tag: "[Free] GPT-4.1" → "[Free] GHM - GPT-4.1" not "GHM - [Free] GPT-4.1"
1632
+ if (model.name.startsWith("[Free] ")) {
1633
+ model.name = `[Free] ${prefix}${model.name.slice(7)}`;
1634
+ } else {
1635
+ model.name = `${prefix}${model.name}`;
1636
+ }
1637
+ return model;
1638
+ }
1639
+
1640
+ /**
1641
+ * Reverse-index the enrichment map from `providerCanonical → providerAlias`.
1642
+ *
1643
+ * OmniRoute's `/api/pricing/models` is keyed by short ALIAS (`cc`, `cx`,
1644
+ * `pol`). But `/v1/models` exposes some models a SECOND time under their
1645
+ * CANONICAL name (`claude/claude-opus-4-7`, `codex/gpt-5.5`,
1646
+ * `pollinations/midjourney`). Without a reverse map, those canonical
1647
+ * rows miss enrichment entirely and surface as raw ids in the picker.
1648
+ *
1649
+ * Built once per refresh from the enrichment entries themselves — no
1650
+ * hardcoded registry. Only records `canonical → alias` mappings when
1651
+ * both are present AND distinct (skips slots where alias === canonical
1652
+ * like `kiro`).
1653
+ */
1654
+ export function buildCanonicalToAliasMap(
1655
+ enrichment: OmniRouteEnrichmentMap | undefined
1656
+ ): Map<string, string> {
1657
+ const out = new Map<string, string>();
1658
+ if (!enrichment) return out;
1659
+ for (const entry of enrichment.values()) {
1660
+ const alias = typeof entry.providerAlias === "string" ? entry.providerAlias.trim() : "";
1661
+ const canonical =
1662
+ typeof entry.providerCanonical === "string" ? entry.providerCanonical.trim() : "";
1663
+ if (alias.length === 0 || canonical.length === 0) continue;
1664
+ if (alias === canonical) continue;
1665
+ if (!out.has(canonical)) out.set(canonical, alias);
1666
+ }
1667
+ return out;
1668
+ }
1669
+
1670
+ /**
1671
+ * Enrichment lookup with alias-fallback chain.
1672
+ *
1673
+ * Resolution order (first hit wins):
1674
+ *
1675
+ * 1. `enrichment.get(rawId)` — direct hit on `<prefix>/<modelId>` or
1676
+ * bare id (the fetcher writes under both forms).
1677
+ * 2. If `rawId` is `<canonical>/<modelId>` and `canonicalToAlias` has
1678
+ * a mapping for `canonical`, try `<alias>/<modelId>`. This rescues
1679
+ * duplicate rows like `claude/claude-opus-4-7` (canonical) when
1680
+ * enrichment only indexed under `cc/claude-opus-4-7` (alias).
1681
+ * 3. Bare `<modelId>` as a last resort. Already covered by step 1 in
1682
+ * practice (fetcher writes bare keys), but kept defensive.
1683
+ *
1684
+ * Returns `undefined` when no lookup hits.
1685
+ */
1686
+ export function lookupEnrichment(
1687
+ rawId: string,
1688
+ enrichment: OmniRouteEnrichmentMap | undefined,
1689
+ canonicalToAlias: Map<string, string>
1690
+ ): OmniRouteEnrichmentEntry | undefined {
1691
+ if (!enrichment) return undefined;
1692
+ const direct = enrichment.get(rawId);
1693
+ if (direct) return direct;
1694
+ const slash = rawId.indexOf("/");
1695
+ if (slash > 0) {
1696
+ const prefix = rawId.slice(0, slash);
1697
+ const modelId = rawId.slice(slash + 1);
1698
+ const alias = canonicalToAlias.get(prefix);
1699
+ if (alias && alias !== prefix) {
1700
+ const viaAlias = enrichment.get(`${alias}/${modelId}`);
1701
+ if (viaAlias) return viaAlias;
1702
+ }
1703
+ const bare = enrichment.get(modelId);
1704
+ if (bare) return bare;
1705
+ }
1706
+ return undefined;
1707
+ }
1708
+
1709
+ /**
1710
+ * Pre-pass: detect raw rows that are the CANONICAL twin of an ALIAS row
1711
+ * already in the catalog. Returns the set of canonical-keyed ids to skip
1712
+ * during the raw-model loop so each model surfaces exactly once under
1713
+ * its enriched alias key.
1714
+ *
1715
+ * Example: `/v1/models` returns BOTH `cc/claude-opus-4-7` and
1716
+ * `claude/claude-opus-4-7`. The former is enriched (alias `cc` exists
1717
+ * in `/api/pricing/models`); the latter is raw. We keep `cc/...` and
1718
+ * drop `claude/...`.
1719
+ *
1720
+ * Built once per refresh. Cheap — O(M) where M = raw model count.
1721
+ */
1722
+ export function canonicalDedupSet(
1723
+ rawModels: ReadonlyArray<OmniRouteRawModelEntry>,
1724
+ canonicalToAlias: Map<string, string>
1725
+ ): Set<string> {
1726
+ const drop = new Set<string>();
1727
+ if (canonicalToAlias.size === 0) return drop;
1728
+ // Index every alias key present in the raw catalog.
1729
+ const aliasKeys = new Set<string>();
1730
+ for (const m of rawModels) {
1731
+ if (typeof m.id === "string" && m.id.length > 0) aliasKeys.add(m.id);
1732
+ }
1733
+ for (const m of rawModels) {
1734
+ if (typeof m.id !== "string" || m.id.length === 0) continue;
1735
+ const slash = m.id.indexOf("/");
1736
+ if (slash <= 0) continue;
1737
+ const prefix = m.id.slice(0, slash);
1738
+ const modelId = m.id.slice(slash + 1);
1739
+ const alias = canonicalToAlias.get(prefix);
1740
+ if (!alias || alias === prefix) continue;
1741
+ // Canonical row only gets suppressed if the alias row actually
1742
+ // exists — otherwise we'd hide the model entirely.
1743
+ if (aliasKeys.has(`${alias}/${modelId}`)) drop.add(m.id);
1744
+ }
1745
+ return drop;
1746
+ }
1747
+
1748
+ /**
1749
+ * Build a per-alias index of enrichment metadata so we can render the
1750
+ * provider prefix even for raw models that don't have their own
1751
+ * curated `/api/pricing/models` entry.
1752
+ *
1753
+ * Real example: OmniRoute's `pricing['cohere']` slot lists 10 curated
1754
+ * models but `/v1/models` also returns `cohere/rerank-multilingual-v3.0`
1755
+ * and `cohere/rerank-v4.0-fast` (not in the curated 10). Without this
1756
+ * index, those rows surface in the picker as `cohere/...` with no
1757
+ * `Cohere - ` prefix because the per-model enrichment lookup misses.
1758
+ *
1759
+ * This index records the first non-empty `providerDisplayName` seen
1760
+ * for each alias, plus the alias itself. Callers use it to synthesize
1761
+ * a minimal `OmniRouteEnrichmentEntry` whenever the direct lookup
1762
+ * misses but the raw id's prefix matches a known alias.
1763
+ *
1764
+ * Built once per refresh; first-wins on duplicate alias (matches
1765
+ * `buildCanonicalToAliasMap` semantics).
1766
+ */
1767
+ export function buildAliasIndex(
1768
+ enrichment: OmniRouteEnrichmentMap | undefined
1769
+ ): Map<string, OmniRouteEnrichmentEntry> {
1770
+ const out = new Map<string, OmniRouteEnrichmentEntry>();
1771
+ if (!enrichment) return out;
1772
+ for (const entry of enrichment.values()) {
1773
+ const alias = typeof entry.providerAlias === "string" ? entry.providerAlias.trim() : "";
1774
+ if (alias.length === 0) continue;
1775
+ if (out.has(alias)) {
1776
+ // First-wins, but upgrade to the first entry that carries a
1777
+ // non-empty providerDisplayName so the prefix renders nicely.
1778
+ const existing = out.get(alias);
1779
+ if (
1780
+ existing &&
1781
+ (!existing.providerDisplayName || existing.providerDisplayName.trim().length === 0) &&
1782
+ typeof entry.providerDisplayName === "string" &&
1783
+ entry.providerDisplayName.trim().length > 0
1784
+ ) {
1785
+ out.set(alias, entry);
1786
+ }
1787
+ continue;
1788
+ }
1789
+ out.set(alias, entry);
1790
+ }
1791
+ return out;
1792
+ }
1793
+
1794
+ /**
1795
+ * Resolve a synthesised enrichment entry for `applyProviderTag` /
1796
+ * `shortProviderLabel` consumption, combining two sources:
1797
+ *
1798
+ * 1. The direct per-model enrichment match (if present).
1799
+ * 2. A per-alias fallback derived from `buildAliasIndex` — covers raw
1800
+ * ids whose prefix matches a known alias but the specific model
1801
+ * id wasn't curated in `/api/pricing/models`. Example:
1802
+ * `cohere/rerank-multilingual-v3.0` falls back to the cohere slot's
1803
+ * `providerDisplayName='Cohere'` even though that specific id
1804
+ * isn't in the curated 10-model list.
1805
+ *
1806
+ * Returns `undefined` when neither source surfaces an alias.
1807
+ *
1808
+ * NOTE: this function is read-only over its inputs; it never mutates
1809
+ * the underlying `direct` entry. When it falls back to the alias
1810
+ * index, it constructs a fresh minimal entry exposing only the
1811
+ * provider-prefix fields (`providerAlias`, `providerCanonical`,
1812
+ * `providerDisplayName`). Other fields (name, pricing) are explicitly
1813
+ * left undefined so `applyEnrichment` won't accidentally overwrite a
1814
+ * model name with the alias-slot label.
1815
+ */
1816
+ export function resolveProviderTagEntry(
1817
+ rawId: string,
1818
+ direct: OmniRouteEnrichmentEntry | undefined,
1819
+ aliasIndex: Map<string, OmniRouteEnrichmentEntry>,
1820
+ canonicalToAlias?: Map<string, string>
1821
+ ): OmniRouteEnrichmentEntry | undefined {
1822
+ if (direct) {
1823
+ const alias = typeof direct.providerAlias === "string" ? direct.providerAlias.trim() : "";
1824
+ const display =
1825
+ typeof direct.providerDisplayName === "string" ? direct.providerDisplayName.trim() : "";
1826
+ if (alias.length > 0 || display.length > 0) return direct;
1827
+ }
1828
+ const slash = rawId.indexOf("/");
1829
+ if (slash <= 0) return direct;
1830
+ const prefix = rawId.slice(0, slash);
1831
+ // 1. Direct alias lookup (`cohere/...` → cohere slot keyed by alias=cohere).
1832
+ let fromAlias = aliasIndex.get(prefix);
1833
+ // 2. Canonical fallback (`pollinations/...` → look up via alias `pol`).
1834
+ if (!fromAlias && canonicalToAlias) {
1835
+ const alias = canonicalToAlias.get(prefix);
1836
+ if (alias) fromAlias = aliasIndex.get(alias);
1837
+ }
1838
+ if (!fromAlias) return direct;
1839
+ // Synthesize: borrow only the provider-prefix metadata.
1840
+ return {
1841
+ providerAlias: fromAlias.providerAlias,
1842
+ providerCanonical: fromAlias.providerCanonical,
1843
+ providerDisplayName: fromAlias.providerDisplayName,
1844
+ };
1845
+ }
1846
+
1847
+ /**
1848
+ * Apply enrichment overlay onto a ModelV2 entry. Mutates and returns the
1849
+ * passed entry for convenience.
1850
+ */
1851
+ /**
1852
+ * Normalise a model display name so free-tier models always carry a
1853
+ * consistent `[Free] ` prefix instead of a trailing `(Free)` suffix or an
1854
+ * ad-hoc `free` word anywhere in the name.
1855
+ *
1856
+ * Examples:
1857
+ * "GPT-4.1 (Free)" → "[Free] GPT-4.1"
1858
+ * "DeepSeek V4 Flash Free" → "[Free] DeepSeek V4 Flash"
1859
+ * "Claude Opus 4.7" → "Claude Opus 4.7" (unchanged)
1860
+ */
1861
+ export { _normaliseFreeLabel as normaliseFreeLabel };
1862
+
1863
+ export function applyEnrichment(
1864
+ model: ModelV2,
1865
+ enrichment: OmniRouteEnrichmentEntry | undefined
1866
+ ): ModelV2 {
1867
+ if (!enrichment) return model;
1868
+ if (enrichment.name && enrichment.name.trim().length > 0) {
1869
+ model.name = _normaliseFreeLabel(enrichment.name);
1870
+ }
1871
+ if (enrichment.pricing) {
1872
+ if (typeof enrichment.pricing.input === "number") {
1873
+ model.cost.input = enrichment.pricing.input;
1874
+ }
1875
+ if (typeof enrichment.pricing.output === "number") {
1876
+ model.cost.output = enrichment.pricing.output;
1877
+ }
1878
+ if (typeof enrichment.pricing.cacheRead === "number") {
1879
+ model.cost.cache.read = enrichment.pricing.cacheRead;
1880
+ }
1881
+ if (typeof enrichment.pricing.cacheWrite === "number") {
1882
+ model.cost.cache.write = enrichment.pricing.cacheWrite;
1883
+ }
1884
+ }
1885
+ return model;
1886
+ }
1887
+
1888
+ // ─────────────────────────────────────────────────────────────────────────
1889
+ // COMPRESSION METADATA — pull /api/context/combos so combo entries can be
1890
+ // tagged with their compression pipeline. Gated by
1891
+ // features.compressionMetadata (off by default).
1892
+ // ─────────────────────────────────────────────────────────────────────────
1893
+
1894
+ /** Single step in a compression combo's pipeline. */
1895
+ export interface OmniRouteCompressionStep {
1896
+ engine: string; // "rtk" | "caveman" | "aggressive" | ...
1897
+ intensity?: string; // "minimal" | "lite" | "standard" | "full" | "ultra" | "aggressive"
1898
+ }
1899
+
1900
+ /** Compression combo as returned by /api/context/combos. */
1901
+ export interface OmniRouteCompressionCombo {
1902
+ id: string;
1903
+ name?: string;
1904
+ description?: string;
1905
+ pipeline: OmniRouteCompressionStep[];
1906
+ isDefault?: boolean;
1907
+ }
1908
+
1909
+ export type OmniRouteCompressionMetaFetcher = (
1910
+ baseURL: string,
1911
+ apiKey: string,
1912
+ timeoutMs?: number
1913
+ ) => Promise<OmniRouteCompressionCombo[]>;
1914
+
1915
+ /**
1916
+ * Default compression-metadata fetcher — calls `GET /api/context/combos`.
1917
+ * Tolerates envelope shapes `{ combos: [...] }`, `[...]`, or
1918
+ * `{ data: [...] }`. Soft-fails (returns []) on non-2xx or parse errors.
1919
+ */
1920
+ export const defaultOmniRouteCompressionMetaFetcher: OmniRouteCompressionMetaFetcher = async (
1921
+ baseURL,
1922
+ apiKey,
1923
+ timeoutMs = 10_000
1924
+ ) => {
1925
+ const empty: OmniRouteCompressionCombo[] = [];
1926
+ if (!baseURL || !apiKey) return empty;
1927
+ const root = baseURL.replace(/\/v1\/?$/, "").replace(/\/$/, "");
1928
+ const url = `${root}/api/context/combos`;
1929
+ const ac = new AbortController();
1930
+ const timer = setTimeout(() => ac.abort(), timeoutMs);
1931
+ try {
1932
+ const res = await fetch(url, {
1933
+ method: "GET",
1934
+ headers: {
1935
+ Authorization: `Bearer ${apiKey}`,
1936
+ Accept: "application/json",
1937
+ },
1938
+ signal: ac.signal,
1939
+ });
1940
+ if (!res.ok) return empty;
1941
+ const body = (await res.json()) as unknown;
1942
+ const list = Array.isArray(body)
1943
+ ? body
1944
+ : Array.isArray((body as { combos?: unknown[] })?.combos)
1945
+ ? (body as { combos: unknown[] }).combos
1946
+ : Array.isArray((body as { data?: unknown[] })?.data)
1947
+ ? (body as { data: unknown[] }).data
1948
+ : [];
1949
+ const out: OmniRouteCompressionCombo[] = [];
1950
+ for (const raw of list) {
1951
+ if (!raw || typeof raw !== "object") continue;
1952
+ const id = (raw as { id?: unknown }).id;
1953
+ const pipeline = (raw as { pipeline?: unknown }).pipeline;
1954
+ if (typeof id !== "string" || id.length === 0) continue;
1955
+ if (!Array.isArray(pipeline)) continue;
1956
+ const steps: OmniRouteCompressionStep[] = [];
1957
+ for (const step of pipeline) {
1958
+ if (!step || typeof step !== "object") continue;
1959
+ const engine = (step as { engine?: unknown }).engine;
1960
+ if (typeof engine !== "string" || engine.length === 0) continue;
1961
+ const intensity = (step as { intensity?: unknown }).intensity;
1962
+ const entry: OmniRouteCompressionStep = { engine };
1963
+ if (typeof intensity === "string" && intensity.length > 0) {
1964
+ entry.intensity = intensity;
1965
+ }
1966
+ steps.push(entry);
1967
+ }
1968
+ const combo: OmniRouteCompressionCombo = { id, pipeline: steps };
1969
+ const name = (raw as { name?: unknown }).name;
1970
+ if (typeof name === "string" && name.length > 0) combo.name = name;
1971
+ const description = (raw as { description?: unknown }).description;
1972
+ if (typeof description === "string") combo.description = description;
1973
+ const isDefault = (raw as { isDefault?: unknown }).isDefault;
1974
+ if (typeof isDefault === "boolean") combo.isDefault = isDefault;
1975
+ out.push(combo);
1976
+ }
1977
+ return out;
1978
+ } catch {
1979
+ return empty;
1980
+ } finally {
1981
+ clearTimeout(timer);
1982
+ }
1983
+ };
1984
+
1985
+ /**
1986
+ * Map of well-known compression-intensity tokens to a single emoji
1987
+ * conveying "how much" compression is applied. Traffic-light palette:
1988
+ *
1989
+ * 🟢 minimal / lite — almost no loss
1990
+ * 🟡 standard — balanced
1991
+ * 🟠 aggressive / full — heavy
1992
+ * 🔴 ultra — extreme
1993
+ *
1994
+ * Lookup is case-insensitive. Unknown intensities fall through to the
1995
+ * raw text form (`engine:<intensity>`) so we never hide a value that
1996
+ * OmniRoute knows but the plugin doesn't.
1997
+ *
1998
+ * Exported for callers (and tests) that want to assemble their own
1999
+ * pipeline strings.
2000
+ */
2001
+ export const COMPRESSION_INTENSITY_EMOJI: Record<string, string> = {
2002
+ minimal: "🟢",
2003
+ lite: "🟢",
2004
+ standard: "🟡",
2005
+ aggressive: "🟠",
2006
+ full: "🟠",
2007
+ ultra: "🔴",
2008
+ };
2009
+
2010
+ /**
2011
+ * Format a compression pipeline as a short human-readable string for
2012
+ * combo `name` decoration. Intensity tokens render as a traffic-light
2013
+ * emoji so a column scan reveals "how compressed" the combo is at a
2014
+ * glance:
2015
+ *
2016
+ * `[rtk🟡 → caveman🟠]` (rtk:standard → caveman:full)
2017
+ * `[rtk🔴]` (rtk:ultra, single-step)
2018
+ * `[caveman]` (engine without intensity, no emoji)
2019
+ * `[rtk:custom-thing]` (unknown intensity, raw-text fallback)
2020
+ */
2021
+ export function formatCompressionPipeline(pipeline: OmniRouteCompressionStep[]): string {
2022
+ if (!pipeline || pipeline.length === 0) return "";
2023
+ return (
2024
+ "[" +
2025
+ pipeline
2026
+ .map((s) => {
2027
+ if (!s.intensity) return s.engine;
2028
+ const emoji = COMPRESSION_INTENSITY_EMOJI[s.intensity.toLowerCase()];
2029
+ return emoji ? `${s.engine}${emoji}` : `${s.engine}:${s.intensity}`;
2030
+ })
2031
+ .join(" → ") +
2032
+ "]"
2033
+ );
2034
+ }
2035
+
2036
+ // ─────────────────────────────────────────────────────────────────────────
2037
+ // /api/providers (provider-connection status) — optional read used by the
2038
+ // `features.usableOnly` filter. Returns the operator's installed OmniRoute
2039
+ // provider connections, each with `provider` (canonical id), `isActive`,
2040
+ // `testStatus`. We treat a provider as USABLE when at least one of its
2041
+ // connections is `isActive: true && testStatus: 'active'`. Aliases (e.g.
2042
+ // `cc → claude`) are resolved through the enrichment map.
2043
+ // ─────────────────────────────────────────────────────────────────────────
2044
+
2045
+ /** Subset of `/api/providers/connections[]` we read. Other fields are kept as a permissive index signature. */
2046
+ export interface OmniRouteProviderConnection {
2047
+ /** Connection UUID. */
2048
+ id: string;
2049
+ /** Canonical provider id, e.g. `claude`, `gemini`, `kiro`. Matches `entry.id` in `/api/pricing/models`. */
2050
+ provider: string;
2051
+ /** Connection auth flavor, e.g. `apikey`, `oauth`, `cookie`. */
2052
+ authType?: string;
2053
+ /** Operator-visible label. */
2054
+ name?: string;
2055
+ /** Operator toggle — when false, the connection is provisioned but disabled. */
2056
+ isActive?: boolean;
2057
+ /** Health-check verdict — `active` means routable; `expired`/`error`/`unavailable` mean not. */
2058
+ testStatus?: string;
2059
+ /** Permissive bag — additional fields (priority, backoffLevel, etc.) pass through untouched. */
2060
+ [k: string]: unknown;
2061
+ }
2062
+
2063
+ export type OmniRouteProvidersFetcher = (
2064
+ baseURL: string,
2065
+ apiKey: string,
2066
+ timeoutMs?: number
2067
+ ) => Promise<OmniRouteProviderConnection[]>;
2068
+
2069
+ /**
2070
+ * Default providers fetcher — calls `GET /api/providers`. Tolerates envelope
2071
+ * shapes `{ connections: [...] }`, `[...]`, or `{ data: [...] }`. Soft-fails
2072
+ * (returns []) on non-2xx or parse errors so the `usableOnly` filter
2073
+ * gracefully degrades to "no filter" instead of hiding the whole catalog.
2074
+ */
2075
+ export const defaultOmniRouteProvidersFetcher: OmniRouteProvidersFetcher = async (
2076
+ baseURL,
2077
+ apiKey,
2078
+ timeoutMs = 10_000
2079
+ ) => {
2080
+ const empty: OmniRouteProviderConnection[] = [];
2081
+ if (!baseURL || !apiKey) return empty;
2082
+ const root = baseURL.replace(/\/v1\/?$/, "").replace(/\/$/, "");
2083
+ const url = `${root}/api/providers`;
2084
+ const ac = new AbortController();
2085
+ const timer = setTimeout(() => ac.abort(), timeoutMs);
2086
+ try {
2087
+ const res = await fetch(url, {
2088
+ method: "GET",
2089
+ headers: {
2090
+ Authorization: `Bearer ${apiKey}`,
2091
+ Accept: "application/json",
2092
+ },
2093
+ signal: ac.signal,
2094
+ });
2095
+ if (!res.ok) return empty;
2096
+ const body = (await res.json()) as unknown;
2097
+ const list = Array.isArray(body)
2098
+ ? body
2099
+ : Array.isArray((body as { connections?: unknown[] })?.connections)
2100
+ ? (body as { connections: unknown[] }).connections
2101
+ : Array.isArray((body as { data?: unknown[] })?.data)
2102
+ ? (body as { data: unknown[] }).data
2103
+ : [];
2104
+ const out: OmniRouteProviderConnection[] = [];
2105
+ for (const raw of list) {
2106
+ if (!raw || typeof raw !== "object") continue;
2107
+ const provider = (raw as { provider?: unknown }).provider;
2108
+ if (typeof provider !== "string" || provider.length === 0) continue;
2109
+ const id = (raw as { id?: unknown }).id;
2110
+ const idStr = typeof id === "string" && id.length > 0 ? id : provider;
2111
+ out.push({ ...(raw as Record<string, unknown>), id: idStr, provider });
2112
+ }
2113
+ return out;
2114
+ } catch {
2115
+ return empty;
2116
+ } finally {
2117
+ clearTimeout(timer);
2118
+ }
2119
+ };
2120
+
2121
+ /**
2122
+ * Compute the set of provider aliases that have at least one healthy,
2123
+ * active connection. Resolves alias → canonical id through the enrichment
2124
+ * map (which is keyed under both `${alias}/${id}` and bare `${id}` — we
2125
+ * walk only the namespaced keys to derive the alias↔canonical mapping).
2126
+ *
2127
+ * Returns:
2128
+ * - `aliases`: set of alias prefixes safe to keep (e.g. `cc`, `gemini`).
2129
+ * - `canonicals`: set of canonical provider ids (e.g. `claude`, `kiro`).
2130
+ *
2131
+ * Callers should treat membership in EITHER set as "usable" — raw model
2132
+ * ids may be `<alias>/<model>` (`cc/claude-opus-4-7`) OR `<canonical>/<model>`
2133
+ * (`claude/sonnet-4`) depending on the OmniRoute deployment's `/v1/models`
2134
+ * surface shape.
2135
+ *
2136
+ * Subtract-filter semantics: callers MUST also keep models whose prefix is
2137
+ * unknown to BOTH `/api/pricing/models` and `/api/providers` (e.g.
2138
+ * agentrouter-style synthetic prefixes). The right boolean is "if I see this
2139
+ * prefix in EITHER catalog table AND it's not usable, drop; otherwise keep".
2140
+ */
2141
+ export function usableProviderAliasSet(
2142
+ connections: OmniRouteProviderConnection[],
2143
+ enrichment: OmniRouteEnrichmentMap | undefined
2144
+ ): {
2145
+ aliases: Set<string>;
2146
+ canonicals: Set<string>;
2147
+ knownAliases: Set<string>;
2148
+ } {
2149
+ const usableCanonicals = new Set<string>();
2150
+ for (const c of connections) {
2151
+ if (!c || c.isActive !== true) continue;
2152
+ if (typeof c.testStatus === "string" && c.testStatus !== "active") continue;
2153
+ if (typeof c.provider === "string" && c.provider.length > 0) {
2154
+ usableCanonicals.add(c.provider);
2155
+ }
2156
+ }
2157
+ const aliases = new Set<string>();
2158
+ const knownAliases = new Set<string>();
2159
+ if (enrichment) {
2160
+ // Walk enrichment entries to map alias → canonical via the metadata
2161
+ // populated by `defaultOmniRouteEnrichmentFetcher`. Every entry carries
2162
+ // its providerAlias + providerCanonical so the namespaced/bare key
2163
+ // duplication is harmless. Collect EVERY alias we encounter (regardless
2164
+ // of usability) into `knownAliases` so the downstream filter can decide
2165
+ // "this prefix was in /api/pricing/models" in O(1) instead of O(E).
2166
+ for (const entry of enrichment.values()) {
2167
+ const alias = entry.providerAlias;
2168
+ const canonical = entry.providerCanonical;
2169
+ if (typeof alias !== "string" || alias.length === 0) continue;
2170
+ knownAliases.add(alias);
2171
+ if (typeof canonical !== "string" || canonical.length === 0) continue;
2172
+ if (usableCanonicals.has(canonical)) aliases.add(alias);
2173
+ }
2174
+ }
2175
+ // Always include every usable canonical as an alias too — handles the
2176
+ // common case where `/v1/models` ids use the canonical id directly
2177
+ // (e.g. `gemini/gemini-1.5-pro`).
2178
+ for (const canonical of usableCanonicals) aliases.add(canonical);
2179
+ return { aliases, canonicals: usableCanonicals, knownAliases };
2180
+ }
2181
+
2182
+ /**
2183
+ * Decide whether a raw `/v1/models` id passes the `usableOnly` filter.
2184
+ *
2185
+ * Rules (subtract-filter — bias toward keep):
2186
+ * - id has no `/` → keep (combos/synthetic entries handled separately).
2187
+ * - prefix matches a known usable alias OR canonical → keep.
2188
+ * - prefix is unknown to BOTH the connection table AND the enrichment
2189
+ * map → keep (we can't prove it's NOT usable; could be agentrouter).
2190
+ * - prefix is known to the enrichment map BUT not in usable set → drop.
2191
+ *
2192
+ * Pure function — exported so static + dynamic hooks share the same
2193
+ * verdict logic without divergence.
2194
+ */
2195
+ export function isUsableRawModelId(
2196
+ id: string,
2197
+ usable: {
2198
+ aliases: Set<string>;
2199
+ canonicals: Set<string>;
2200
+ knownAliases: Set<string>;
2201
+ },
2202
+ enrichment: OmniRouteEnrichmentMap | undefined
2203
+ ): boolean {
2204
+ const slash = id.indexOf("/");
2205
+ if (slash <= 0) return true;
2206
+ const prefix = id.slice(0, slash);
2207
+ if (usable.aliases.has(prefix) || usable.canonicals.has(prefix)) return true;
2208
+ // O(1) "known prefix" check via pre-calculated knownAliases set.
2209
+ // If prefix was in /api/pricing/models but is NOT in usable set,
2210
+ // drop the model. Unknown prefixes (e.g. agentrouter-style synthetic)
2211
+ // pass through (subtract-filter semantics).
2212
+ if (usable.knownAliases.has(prefix)) return false;
2213
+ return true;
2214
+ }
2215
+
2216
+ /**
2217
+ * Decide whether a combo passes the `usableOnly` filter. A combo keeps
2218
+ * when AT LEAST ONE of its members maps to a usable canonical provider.
2219
+ * Combos with zero resolvable members pass through (already degraded to
2220
+ * all-false LCD posture and surfaced as cosmetic-only entries).
2221
+ */
2222
+ export function isUsableCombo(
2223
+ combo: OmniRouteRawCombo,
2224
+ usable: {
2225
+ aliases: Set<string>;
2226
+ canonicals: Set<string>;
2227
+ knownAliases: Set<string>;
2228
+ }
2229
+ ): boolean {
2230
+ const steps = Array.isArray(combo.models) ? combo.models : [];
2231
+ if (steps.length === 0) return true;
2232
+ // The provider id is folded INTO the full model string by OmniRoute's
2233
+ // `normalizeComboRecord` (e.g. "cc/claude-opus-4-7") — combo member refs do
2234
+ // NOT carry a separate `providerId` field. Derive the prefix from `step.model`
2235
+ // and apply the same subtract-filter verdict as `isUsableRawModelId`.
2236
+ let sawResolvableMember = false;
2237
+ for (const step of steps) {
2238
+ // Nested combo refs carry no model id we can resolve to a provider here.
2239
+ if (step?.kind === "combo-ref") continue;
2240
+ const modelId = typeof step?.model === "string" ? step.model : "";
2241
+ const slash = modelId.indexOf("/");
2242
+ if (slash <= 0) continue; // no provider prefix to evaluate
2243
+ sawResolvableMember = true;
2244
+ const prefix = modelId.slice(0, slash);
2245
+ if (usable.aliases.has(prefix) || usable.canonicals.has(prefix)) return true;
2246
+ // Unknown prefix (not in the known-alias universe) → can't prove
2247
+ // unroutable; keep. Known-but-not-usable prefixes keep scanning.
2248
+ if (!usable.knownAliases.has(prefix)) return true;
2249
+ }
2250
+ // No member resolved to a provider prefix → can't prove unroutable; keep.
2251
+ if (!sawResolvableMember) return true;
2252
+ // Every resolvable member used a known-but-non-usable prefix → drop.
2253
+ return false;
2254
+ }
2255
+
2256
+ /**
2257
+ * Slugify a combo display name into a copy/paste-friendly URL-safe segment.
2258
+ * Lowercases, replaces any run of non-alphanumeric chars with a single dash,
2259
+ * trims leading/trailing dashes. Empty input or all-special input returns
2260
+ * the empty string (caller must fall back to the combo's UUID id).
2261
+ *
2262
+ * Example: `Claude Tier` → `claude-tier`, `GPT 5.5 / Pro` → `gpt-5-5-pro`.
2263
+ */
2264
+ export function slugifyComboName(name: string): string {
2265
+ if (typeof name !== "string") return "";
2266
+ return trimLeadingDashes(trimTrailingDashes(name.toLowerCase().replace(/[^a-z0-9]+/g, "-")));
2267
+ }
2268
+
2269
+ /**
2270
+ * Build a combo's static-block key, provider-prefixed as `<providerId>/<slug>`
2271
+ * (e.g. `omniroute/MASTER`, `omniroute/MASTER-LIGHT`), guaranteeing uniqueness
2272
+ * across an entire static catalog. If `<providerId>/<slug>` is already present in
2273
+ * `used`, suffixes a short UUID-prefix disambiguator from `combo.id` so the second
2274
+ * combo doesn't silently overwrite the first. Mutates `used` in place by recording
2275
+ * the chosen key. Returns the final `<providerId>/<slug>` key.
2276
+ *
2277
+ * NOTE: the key MUST carry the OWNING provider prefix (`omniroute/…`), never a
2278
+ * `combo/` namespace — OpenCode parses model IDs on `/` to extract the provider,
2279
+ * so `combo/MASTER` would resolve provider=`combo` (no credentials) and fail with
2280
+ * "Unable to determine provider", whereas `omniroute/MASTER` resolves provider=
2281
+ * `omniroute` and the openai-compatible adapter strips the prefix and sends the
2282
+ * bare slug upstream, which the server resolves via getComboByName. See PR #4184.
2283
+ *
2284
+ * Falls back to `<providerId>/<id>` when the friendly name slugifies to the empty
2285
+ * string (e.g. a combo named just punctuation).
2286
+ */
2287
+ export function buildComboKey(
2288
+ combo: OmniRouteRawCombo,
2289
+ used: Set<string>,
2290
+ providerId: string
2291
+ ): string {
2292
+ const friendlyName = combo.name && combo.name.trim().length > 0 ? combo.name.trim() : combo.id;
2293
+ let slug = slugifyComboName(friendlyName);
2294
+ if (slug.length === 0) slug = combo.id;
2295
+ let key = `${providerId}/${slug}`;
2296
+ if (used.has(key)) {
2297
+ const tail = combo.id.split("-")[0] ?? combo.id;
2298
+ key = `${providerId}/${slug}-${tail}`;
2299
+ // Defensive: in the (impossible) event the disambiguated key also
2300
+ // collides, append the full id.
2301
+ if (used.has(key)) key = `${providerId}/${slug}-${combo.id}`;
2302
+ }
2303
+ used.add(key);
2304
+ return key;
2305
+ }
2306
+
2307
+ /**
2308
+ * Internal cache key: `${baseURL}::sha256(apiKey)`. We hash the apiKey so
2309
+ * the key is safe to log / inspect via debugger without leaking the secret.
2310
+ * Different (baseURL, apiKey) tuples MUST keep independent cache entries:
2311
+ * a single OC user may register prod + preprod OmniRoute side-by-side with
2312
+ * distinct keys, and serving one's catalog from the other's cache would be
2313
+ * a correctness bug, not just a privacy one.
2314
+ */
2315
+ // codeql[js/insufficient-password-hash]: the input here is an API-key
2316
+ // identifier we use solely to derive an in-memory cache lookup key — it is
2317
+ // never stored, transmitted, compared against a hash, or used as a password.
2318
+ // SHA-256 is intentional: cheap + deterministic, prevents the raw secret
2319
+ // from sitting in memory dumps alongside the cache map. Slow KDFs (bcrypt/
2320
+ // argon2) would defeat the purpose (sub-ms lookups on every request).
2321
+ function modelsCacheKey(baseURL: string, credentialId: string): string {
2322
+ const h = createHash("sha256").update(credentialId).digest("hex");
2323
+ return `${baseURL}::${h}`;
2324
+ }
2325
+
2326
+ /**
2327
+ * Shared fetch-result cache entry. Holds the RAW `/v1/models` + `/api/combos`
2328
+ * responses (NOT a pre-derived ModelV2 / static-entry shape) so the provider
2329
+ * hook (T-03/T-05) and the config-shim hook (T-07) can derive their own
2330
+ * output shapes from the same source without re-fetching.
2331
+ *
2332
+ * Why raw instead of derived:
2333
+ * - provider hook emits ModelV2 (rich nested capabilities + cost + limits).
2334
+ * - config hook emits the stripped sibling shape
2335
+ * (`{name, attachment, reasoning, tool_call, temperature, limit?}`).
2336
+ * - These overlap but neither is a superset of the other (ModelV2 has no
2337
+ * `tool_call` field — it's `toolcall`; the stripped shape has no
2338
+ * `cost`/`status`/`headers`). Caching the raw responses is the only
2339
+ * lossless option.
2340
+ * - On OC ≥1.14.49 cold start BOTH hooks fire within the same
2341
+ * OmniRoutePlugin instance — sharing the cache means /v1/models +
2342
+ * /api/combos each hit the gateway exactly ONCE per TTL refresh, not
2343
+ * twice.
2344
+ */
2345
+ export interface OmniRouteFetchCacheEntry {
2346
+ rawModels: OmniRouteRawModelEntry[];
2347
+ rawCombos: OmniRouteRawCombo[];
2348
+ rawAutoCombos: OmniRouteRawAutoCombo[];
2349
+ /** Display-name + pricing overlay from /api/pricing/models. Empty Map when feature is disabled or fetch failed. */
2350
+ rawEnrichment: OmniRouteEnrichmentMap;
2351
+ /** Compression combos from /api/context/combos. Empty array when feature is disabled or fetch failed. */
2352
+ rawCompressionCombos: OmniRouteCompressionCombo[];
2353
+ /** Provider connections from /api/providers. Empty array when feature is disabled or fetch failed. */
2354
+ rawConnections: OmniRouteProviderConnection[];
2355
+ expiresAt: number;
2356
+ }
2357
+
2358
+ export type OmniRouteFetchCache = Map<string, OmniRouteFetchCacheEntry>;
2359
+
2360
+ /**
2361
+ * Build the ProviderHook portion of the plugin for a given options bag.
2362
+ * Exported standalone so the contract is unit-testable without faking the
2363
+ * full PluginInput / Hooks surface, and so multi-instance setups can each
2364
+ * own their own cache (a fresh hook closure per plugin tuple).
2365
+ *
2366
+ * Behavioural contract:
2367
+ * - `id` binds to the resolved `providerId` (multi-instance: each plugin
2368
+ * tuple's hook lists models under its own provider id).
2369
+ * - `models(provider, ctx)` extracts the api key from `ctx.auth` (rejecting
2370
+ * non-`api` flavors with `{}` — same posture as the auth loader); calls
2371
+ * both `/v1/models` and `/api/combos` fetchers; maps raw `/v1/models`
2372
+ * entries through `mapRawModelToModelV2`; maps each `/api/combos` entry
2373
+ * through `mapComboToModelV2` (LCD across its member models); merges
2374
+ * combos into the same map under their combo id; caches the unified
2375
+ * result by `(baseURL, sha256(apiKey))` for `modelCacheTtl`.
2376
+ * - **Combo / model ID collisions: combos win.** OmniRoute treats combos
2377
+ * as the curated routing surface; if a combo and a raw model share an
2378
+ * id the operator's intent is clearly the combo. We emit a
2379
+ * `console.warn` exactly once per `(baseURL, apiKey, comboId)`
2380
+ * collision so the operator can spot the unusual naming choice
2381
+ * without log spam on every cache refresh.
2382
+ * - **Combos fetch failure does NOT break the catalog**: soft-fail with
2383
+ * a `console.warn` and fall back to a models-only catalog. Rationale:
2384
+ * `/api/combos` requires a management-scoped key and OmniRoute may
2385
+ * not have any combos provisioned (preprod returned `{combos: []}`
2386
+ * at probe time). Hard-failing the entire catalog when combos are
2387
+ * optional would silently hide the whole provider from OC's model
2388
+ * picker.
2389
+ * - **`/v1/models` fetch failure DOES propagate.** Without models
2390
+ * there's no catalog at all, so an empty `{}` would just mask the
2391
+ * error.
2392
+ * - Cache is in-memory per hook instance, shared between models and
2393
+ * combos (one fetch pair per (baseURL, apiKey) per TTL refresh).
2394
+ *
2395
+ * @param opts Plugin options (providerId, baseURL, modelCacheTtl, …).
2396
+ * @param deps Dependency injection. `fetcher` defaults to the live
2397
+ * `/v1/models` HTTP fetcher; `combosFetcher` defaults to the
2398
+ * live `/api/combos` HTTP fetcher (override for tests / to
2399
+ * disable combos by injecting one that returns `[]`). `now`
2400
+ * defaults to `Date.now` (overridable for TTL tests). `cache`
2401
+ * lets the caller share state across reconstructions (unused
2402
+ * outside tests today).
2403
+ */
2404
+ export function createOmniRouteProviderHook(
2405
+ opts?: OmniRoutePluginOptions,
2406
+ deps: {
2407
+ fetcher?: OmniRouteModelsFetcher;
2408
+ combosFetcher?: OmniRouteCombosFetcher;
2409
+ autoCombosFetcher?: OmniRouteAutoCombosFetcher;
2410
+ enrichmentFetcher?: OmniRouteEnrichmentFetcher;
2411
+ compressionMetaFetcher?: OmniRouteCompressionMetaFetcher;
2412
+ providersFetcher?: OmniRouteProvidersFetcher;
2413
+ now?: () => number;
2414
+ cache?: OmniRouteFetchCache;
2415
+ } = {}
2416
+ ): ProviderHook {
2417
+ const resolved = resolveOmniRoutePluginOptions(opts);
2418
+ const fetcher = deps.fetcher ?? defaultOmniRouteModelsFetcher;
2419
+ // T-05: combo discovery merges `/api/combos` entries into the same map as
2420
+ // `/v1/models`. Default fetcher is declared further down the file; the
2421
+ // reference resolves at hook-invocation time, not at hook-construction
2422
+ // time, so source-order beyond hoisting rules has no semantic effect.
2423
+ const combosFetcher = deps.combosFetcher ?? defaultOmniRouteCombosFetcher;
2424
+ const autoCombosFetcher = deps.autoCombosFetcher ?? defaultOmniRouteAutoCombosFetcher;
2425
+ const enrichmentFetcher = deps.enrichmentFetcher ?? defaultOmniRouteEnrichmentFetcher;
2426
+ const compressionMetaFetcher =
2427
+ deps.compressionMetaFetcher ?? defaultOmniRouteCompressionMetaFetcher;
2428
+ const providersFetcher = deps.providersFetcher ?? defaultOmniRouteProvidersFetcher;
2429
+ // Features defaults (mirror v0.1.0 behavior when unset).
2430
+ const features = resolved.features ?? {};
2431
+ const wantCombos = features.combos !== false;
2432
+ const wantAutoCombos = features.autoCombos !== false;
2433
+ const wantEnrichment = features.enrichment !== false;
2434
+ const wantCompressionMeta = features.compressionMetadata === true;
2435
+ const wantUsableOnly = features.usableOnly === true;
2436
+ const wantProviderTag = features.providerTag !== false;
2437
+ const now = deps.now ?? Date.now;
2438
+ // T-07: cache holds RAW fetch results (not pre-derived ModelV2) so that
2439
+ // the config-shim hook can share the same cache and derive its stripped
2440
+ // sibling shape from the same source without a second round-trip.
2441
+ const cache: OmniRouteFetchCache = deps.cache ?? new Map();
2442
+ // T-05: collision-warning deduper. Emit warn once per (cacheKey, comboId)
2443
+ // tuple per hook instance so the operator sees the unusual naming choice
2444
+ // once per session, not once per cache refresh.
2445
+ const collisionWarned = new Set<string>();
2446
+
2447
+ return {
2448
+ id: resolved.providerId,
2449
+ async models(_provider, ctx) {
2450
+ // Auth narrowing — same posture as the auth loader (T-02). Non-api
2451
+ // flavors and empty keys → empty catalog. OC then exposes the
2452
+ // /connect flow rather than spamming /v1/models with bad creds.
2453
+ const auth = ctx?.auth;
2454
+ if (
2455
+ !auth ||
2456
+ typeof auth !== "object" ||
2457
+ (auth as { type?: unknown }).type !== "api" ||
2458
+ typeof (auth as { key?: unknown }).key !== "string" ||
2459
+ (auth as { key: string }).key.length === 0
2460
+ ) {
2461
+ return {};
2462
+ }
2463
+ const apiKey = (auth as { key: string }).key;
2464
+
2465
+ // baseURL resolution: plugin opts first, then credential-attached
2466
+ // baseURL (auth backends sometimes stash it next to the key), then the
2467
+ // provider config itself — a baseURL set via opencode.json provider
2468
+ // options (or a config hook) lands on `provider.options` and is not
2469
+ // visible through either of the first two links. No silent default to
2470
+ // localhost: a misconfigured plugin should surface a clear warning,
2471
+ // not phantom /v1/models calls. Cast through unknown because the Auth
2472
+ // union (OAuth | ApiAuth | WellKnownAuth) doesn't declare baseURL on
2473
+ // any branch — we duck-type it as a defensive extension point.
2474
+ const authBaseURL = (auth as unknown as { baseURL?: unknown }).baseURL;
2475
+ const providerBaseURL = (_provider as { options?: { baseURL?: unknown } } | undefined)
2476
+ ?.options?.baseURL;
2477
+ const baseURL =
2478
+ resolved.baseURL ??
2479
+ (typeof authBaseURL === "string" && authBaseURL.length > 0 ? authBaseURL : undefined) ??
2480
+ (typeof providerBaseURL === "string" && providerBaseURL.length > 0
2481
+ ? providerBaseURL
2482
+ : undefined) ??
2483
+ "";
2484
+ if (!baseURL) {
2485
+ console.warn(
2486
+ `[omniroute-plugin] provider.models(${resolved.providerId}): ` +
2487
+ `no baseURL resolvable — checked plugin opts, auth.json, and provider config. ` +
2488
+ `Set baseURL in opencode.json plugin options or run \`opencode connect ${resolved.providerId}\` with a baseURL.`
2489
+ );
2490
+ return {};
2491
+ }
2492
+
2493
+ const cacheKey = modelsCacheKey(baseURL, apiKey);
2494
+ const t = now();
2495
+ const cached = cache.get(cacheKey);
2496
+
2497
+ let rawModels: OmniRouteRawModelEntry[];
2498
+ let rawCombos: OmniRouteRawCombo[];
2499
+ let rawAutoCombos: OmniRouteRawAutoCombo[];
2500
+ let rawEnrichment: OmniRouteEnrichmentMap;
2501
+ let rawCompressionCombos: OmniRouteCompressionCombo[];
2502
+ let rawConnections: OmniRouteProviderConnection[];
2503
+ if (cached && cached.expiresAt > t) {
2504
+ rawModels = cached.rawModels;
2505
+ rawCombos = cached.rawCombos;
2506
+ rawAutoCombos = cached.rawAutoCombos;
2507
+ rawEnrichment = cached.rawEnrichment;
2508
+ rawCompressionCombos = cached.rawCompressionCombos;
2509
+ rawConnections = cached.rawConnections;
2510
+ } else {
2511
+ // Models fetch is required (no catalog otherwise → silent provider
2512
+ // disappearance). We do NOT wrap this in a try; let the error
2513
+ // propagate to OC's UI.
2514
+ rawModels = await fetcher(baseURL, apiKey, 10_000);
2515
+
2516
+ // T-05: combos fetch is best-effort, gated by features.combos.
2517
+ // Soft-fail on any error: emit a console.warn and fall back to a
2518
+ // models-only catalog. Rationale: /api/combos requires a
2519
+ // management-scoped key and OmniRoute may not have any combos
2520
+ // provisioned. Hard-failing when combos are optional would
2521
+ // silently hide the whole provider from OC's picker.
2522
+ rawCombos = [];
2523
+ if (wantCombos) {
2524
+ try {
2525
+ rawCombos = await combosFetcher(baseURL, apiKey, 10_000);
2526
+ } catch (err) {
2527
+ console.warn(
2528
+ "[omniroute-plugin] combos fetch failed, falling back to models-only catalog",
2529
+ err
2530
+ );
2531
+ }
2532
+ }
2533
+
2534
+ // Auto combos fetch — virtual server-side combos. Best-effort,
2535
+ // gated by features.autoCombos. Soft-fails silently (the endpoint
2536
+ // may not exist yet on older OmniRoute versions).
2537
+ rawAutoCombos = [];
2538
+ if (wantAutoCombos) {
2539
+ try {
2540
+ rawAutoCombos = await autoCombosFetcher(baseURL, apiKey, 5_000);
2541
+ } catch {
2542
+ // Already handled inside the default fetcher — this catch
2543
+ // is belt-and-suspenders for injected stubs.
2544
+ }
2545
+ }
2546
+
2547
+ // Enrichment fetch (nice names + pricing). Best-effort, gated by
2548
+ // features.enrichment. Soft-fails to empty map.
2549
+ rawEnrichment = new Map();
2550
+ if (wantEnrichment) {
2551
+ try {
2552
+ rawEnrichment = await enrichmentFetcher(baseURL, apiKey, 10_000);
2553
+ } catch (err) {
2554
+ console.warn(
2555
+ "[omniroute-plugin] enrichment fetch failed, falling back to raw ids",
2556
+ err
2557
+ );
2558
+ }
2559
+ }
2560
+
2561
+ // Compression metadata fetch. Off by default, gated by
2562
+ // features.compressionMetadata. Soft-fails to empty array.
2563
+ rawCompressionCombos = [];
2564
+ if (wantCompressionMeta) {
2565
+ try {
2566
+ rawCompressionCombos = await compressionMetaFetcher(baseURL, apiKey, 10_000);
2567
+ } catch (err) {
2568
+ console.warn("[omniroute-plugin] compression-metadata fetch failed", err);
2569
+ }
2570
+ }
2571
+
2572
+ // Provider-connections fetch. Off by default, gated by
2573
+ // features.usableOnly. Soft-fails to empty array — when the
2574
+ // connection table is unreadable we skip the filter entirely
2575
+ // (subtract-filter semantics: don't drop everything we couldn't
2576
+ // verify).
2577
+ rawConnections = [];
2578
+ if (wantUsableOnly) {
2579
+ try {
2580
+ rawConnections = await providersFetcher(baseURL, apiKey, 10_000);
2581
+ } catch (err) {
2582
+ console.warn(
2583
+ "[omniroute-plugin] /api/providers fetch failed; usableOnly filter disabled for this refresh",
2584
+ err
2585
+ );
2586
+ }
2587
+ }
2588
+
2589
+ cache.set(cacheKey, {
2590
+ rawModels,
2591
+ rawCombos,
2592
+ rawAutoCombos,
2593
+ rawEnrichment,
2594
+ rawCompressionCombos,
2595
+ rawConnections,
2596
+ expiresAt: t + resolved.modelCacheTtl,
2597
+ });
2598
+
2599
+ // Debug breadcrumb: surface fetch result so operators can confirm
2600
+ // the dynamic pipeline fired and how much catalog OmniRoute returned.
2601
+ // Emitted once per cache miss (TTL refresh) — quiet on cache hits.
2602
+ console.warn(
2603
+ `[omniroute-plugin] catalog refreshed for providerId=${resolved.providerId} baseURL=${baseURL}: ` +
2604
+ `${rawModels.length} models + ${rawCombos.length} combos + ` +
2605
+ `${rawEnrichment.size} enrichment entries + ` +
2606
+ `${rawCompressionCombos.length} compression combos + ` +
2607
+ `${rawConnections.length} connections ` +
2608
+ `(TTL=${resolved.modelCacheTtl}ms)`
2609
+ );
2610
+
2611
+ // ── Startup debug: deep-dive into enrichment + auto combos ──────
2612
+ if (resolved.features?.startupDebug === true) {
2613
+ await writeStartupDiagnostics({
2614
+ providerId: resolved.providerId,
2615
+ baseURL,
2616
+ modelCount: rawModels.length,
2617
+ comboCount: rawCombos.length,
2618
+ enrichmentSize: rawEnrichment.size,
2619
+ autoComboCount: rawAutoCombos.length,
2620
+ enrichment: rawEnrichment,
2621
+ autoCombos: rawAutoCombos,
2622
+ });
2623
+ }
2624
+ }
2625
+
2626
+ // Lookup index for LCD member resolution: O(1) per member lookup.
2627
+ // Indexed by raw model `id` — combo steps reference this exact
2628
+ // string per ComboModelStep in src/lib/combos/steps.ts.
2629
+ const rawModelById = new Map<string, OmniRouteRawModelEntry>();
2630
+ for (const entry of rawModels) {
2631
+ if (entry.id) rawModelById.set(entry.id, entry);
2632
+ }
2633
+
2634
+ // usableOnly filter — compute the set of usable alias prefixes once
2635
+ // per refresh. Empty when feature is off OR connection fetch failed
2636
+ // OR no connections returned, in which case we keep everything
2637
+ // (subtract-filter semantics: only drop when we can prove a prefix
2638
+ // is NOT usable; never hide the catalog on a soft-fail).
2639
+ const usable =
2640
+ wantUsableOnly && rawConnections.length > 0
2641
+ ? usableProviderAliasSet(rawConnections, rawEnrichment)
2642
+ : undefined;
2643
+
2644
+ // Build the canonical→alias reverse map AND the canonical-dedup
2645
+ // set once per refresh. Together they fix the dual-keyed
2646
+ // `/v1/models` problem where the same model surfaces under BOTH
2647
+ // `<alias>/<id>` (enriched) AND `<canonical>/<id>` (raw): we keep
2648
+ // the alias key and skip the canonical twin entirely.
2649
+ const canonicalToAlias = buildCanonicalToAliasMap(rawEnrichment);
2650
+ const canonicalDedup = canonicalDedupSet(rawModels, canonicalToAlias);
2651
+ const aliasIndex = buildAliasIndex(rawEnrichment);
2652
+
2653
+ // Map raw models → ModelV2 keyed by id. When enrichment data is
2654
+ // present (features.enrichment, default on), overlay the nicer
2655
+ // display name + pricing from /api/pricing/models via the
2656
+ // alias-fallback lookup chain (covers canonical rows lacking
2657
+ // direct pricing entries).
2658
+ const models: Record<string, ModelV2> = {};
2659
+ for (const entry of rawModels) {
2660
+ if (!entry.id) continue;
2661
+ if (canonicalDedup.has(entry.id)) continue;
2662
+ if (usable && !isUsableRawModelId(entry.id, usable, rawEnrichment)) continue;
2663
+ const model = mapRawModelToModelV2(entry, {
2664
+ providerId: resolved.providerId,
2665
+ baseURL,
2666
+ apiFormat: resolved.features?.apiFormat,
2667
+ });
2668
+ const enrichEntry = lookupEnrichment(entry.id, rawEnrichment, canonicalToAlias);
2669
+ applyEnrichment(model, enrichEntry);
2670
+ // Prepend upstream provider label (e.g. `Claude - Claude Opus 4.7`)
2671
+ // so the picker groups same-model rows by upstream connection.
2672
+ // Idempotent + gated by `features.providerTag` (default-on).
2673
+ // Combos skip this on purpose. The alias-index fallback rescues
2674
+ // raw rows like `cohere/rerank-multilingual-v3.0` whose specific
2675
+ // model id isn't in `/api/pricing/models` but whose slot is.
2676
+ if (wantProviderTag) {
2677
+ const tagEntry = resolveProviderTagEntry(
2678
+ entry.id,
2679
+ enrichEntry,
2680
+ aliasIndex,
2681
+ canonicalToAlias
2682
+ );
2683
+ applyProviderTag(model, tagEntry);
2684
+ }
2685
+ // OC's static-catalog reader parses the key on `/` to recover
2686
+ // (providerID, modelID). `mapRawModelToModelV2` already stamps the
2687
+ // prefixed id on `model.id` (e.g. `omniroute/claude-primary`), so we
2688
+ // must key by `model.id` — not by the raw `entry.id` which would be
2689
+ // a bare slug and parse as `providerID=slug, modelID=""`.
2690
+ models[model.id] = model;
2691
+ }
2692
+
2693
+ // Default compression combo (used to decorate ALL combo names when
2694
+ // compression metadata is present). OmniRoute returns at most one
2695
+ // entry with `isDefault: true` per /api/context/combos.
2696
+ const defaultCompression = wantCompressionMeta
2697
+ ? rawCompressionCombos.find((c) => c.isDefault === true)
2698
+ : undefined;
2699
+
2700
+ // T-05: map raw combos → ModelV2. Skip hidden combos (operator
2701
+ // preference — provisioned but intentionally not surfaced).
2702
+ // Resolve each combo's member step list into the matching raw
2703
+ // model entries; unknown member ids are silently dropped before
2704
+ // mapComboToModelV2 sees them, which then degrades to the
2705
+ // all-false LCD posture if zero members remain.
2706
+ //
2707
+ // Combos are keyed under the `combo/<slug>` namespace so the TUI
2708
+ // picker separates them from provider/model pairs and the UUID
2709
+ // never surfaces. This mirrors `buildStaticProviderEntry` so the
2710
+ // static + dynamic catalogs publish identical keys.
2711
+ const comboNames = new Set<string>();
2712
+ for (const combo of rawCombos) {
2713
+ if (!combo || combo.isHidden === true) continue;
2714
+ const n = combo.name && combo.name.trim().length > 0 ? combo.name.trim() : combo.id;
2715
+ if (typeof n === "string" && n.length > 0) comboNames.add(n);
2716
+ }
2717
+ for (const key of Object.keys(models)) {
2718
+ if (comboNames.has(key)) delete models[key];
2719
+ }
2720
+
2721
+ // ── Combo LCD across nested combo-refs (T-NN) ───────────────────────
2722
+ // Combos can nest other combos via `kind: "combo-ref"` members
2723
+ // (e.g. MASTER-LIGHT contains OldLLM, KIRO, Opecode Zen FREE). The
2724
+ // nested combo's own `limit.context` is computed below in this same
2725
+ // loop, so we need a fixpoint iteration: if a combo-ref points at a
2726
+ // combo not yet processed, defer this combo and try again after the
2727
+ // sibling combos catch up. We bound the retries so a circular combo
2728
+ // graph can't deadlock the picker.
2729
+ const MAX_COMBO_PASSES = 8;
2730
+ const usedComboKeys = new Set<string>();
2731
+ // Combos in `rawCombos` that still need (re)processing this round.
2732
+ // Shrinks as combos resolve.
2733
+ let pending = rawCombos.filter((combo) => {
2734
+ if (!combo.id) return false;
2735
+ if (combo.isHidden === true) return false;
2736
+ if (usable && !isUsableCombo(combo, usable)) return false;
2737
+ return true;
2738
+ });
2739
+ // Resolved nested combos keyed by their friendly name, so parent
2740
+ // combos that reference them via combo-ref can lift the full
2741
+ // capability vector (not just the context window) into their own
2742
+ // LCD pass.
2743
+ const resolvedComboModelsByName = new Map<string, ModelV2>();
2744
+
2745
+ for (let pass = 0; pass < MAX_COMBO_PASSES && pending.length > 0; pass++) {
2746
+ const stillPending: typeof pending = [];
2747
+ for (const combo of pending) {
2748
+ const memberSteps = Array.isArray(combo.models) ? combo.models : [];
2749
+ const memberEntries: OmniRouteRawModelEntry[] = [];
2750
+ let deferredThisPass = false;
2751
+
2752
+ for (const step of memberSteps) {
2753
+ // Unknown-bridge: ComboMemberRef's DTS type only declares
2754
+ // `model?: string`, so verify the runtime shape before reading
2755
+ // either `model` (raw member) or `comboName` (nested combo).
2756
+ const stepKind = (step as unknown as { kind?: unknown }).kind;
2757
+
2758
+ if (stepKind === "combo-ref") {
2759
+ const comboName = (step as unknown as { comboName?: unknown }).comboName;
2760
+ if (typeof comboName !== "string" || comboName.length === 0) {
2761
+ continue;
2762
+ }
2763
+ const nestedModel = resolvedComboModelsByName.get(comboName);
2764
+ if (!nestedModel) {
2765
+ // Nested combo hasn't been processed yet. Defer this
2766
+ // combo to the next pass.
2767
+ deferredThisPass = true;
2768
+ break;
2769
+ }
2770
+ // Synthesize a member entry that contributes only the
2771
+ // nested combo's pre-computed context_length + max_output.
2772
+ // Other capability axes default conservatively (no tool
2773
+ // calls, no vision) — a nested combo's modalities are an
2774
+ // OR, but if we let raw-model defaults leak in we'd
2775
+ // over-claim. The combo's own LCD (computed by
2776
+ // mapComboToModelV2 from the synthesized entries) will only
2777
+ // further restrict capabilities, so this is safe.
2778
+ // Synthesize a member entry carrying the nested combo's
2779
+ // pre-computed context + capabilities + modalities so the
2780
+ // parent combo's LCD is accurate across the whole graph
2781
+ // (not just its direct raw-model members).
2782
+ const inputModalities: string[] = [];
2783
+ if (nestedModel.capabilities.input.text) inputModalities.push("text");
2784
+ if (nestedModel.capabilities.input.audio) inputModalities.push("audio");
2785
+ if (nestedModel.capabilities.input.image) inputModalities.push("image");
2786
+ if (nestedModel.capabilities.input.video) inputModalities.push("video");
2787
+ if (nestedModel.capabilities.input.pdf) inputModalities.push("pdf");
2788
+
2789
+ const outputModalities: string[] = [];
2790
+ if (nestedModel.capabilities.output.text) outputModalities.push("text");
2791
+ if (nestedModel.capabilities.output.audio) outputModalities.push("audio");
2792
+ if (nestedModel.capabilities.output.image) outputModalities.push("image");
2793
+ if (nestedModel.capabilities.output.video) outputModalities.push("video");
2794
+ if (nestedModel.capabilities.output.pdf) outputModalities.push("pdf");
2795
+
2796
+ memberEntries.push({
2797
+ id: `combo-ref:${comboName}`,
2798
+ context_length: nestedModel.limit.context,
2799
+ max_output_tokens: nestedModel.limit.output,
2800
+ max_input_tokens: nestedModel.limit.input ?? 0,
2801
+ owned_by: "combo",
2802
+ input_modalities: inputModalities,
2803
+ output_modalities: outputModalities,
2804
+ capabilities: {
2805
+ temperature: nestedModel.capabilities.temperature,
2806
+ reasoning: nestedModel.capabilities.reasoning,
2807
+ thinking: nestedModel.capabilities.interleaved,
2808
+ attachment: nestedModel.capabilities.attachment,
2809
+ tool_calling: nestedModel.capabilities.toolcall,
2810
+ },
2811
+ } as unknown as OmniRouteRawModelEntry);
2812
+ continue;
2813
+ }
2814
+
2815
+ const modelId = (step as unknown as { model?: unknown }).model;
2816
+ if (typeof modelId !== "string" || modelId.length === 0) continue;
2817
+ const member = rawModelById.get(modelId);
2818
+ if (member) memberEntries.push(member);
2819
+ }
2820
+
2821
+ if (deferredThisPass) {
2822
+ stillPending.push(combo);
2823
+ continue;
2824
+ }
2825
+
2826
+ const mapped = mapComboToModelV2(
2827
+ combo,
2828
+ memberEntries,
2829
+ resolved.providerId,
2830
+ baseURL,
2831
+ features.apiFormat
2832
+ );
2833
+ const hasMembers = memberEntries.length > 0;
2834
+
2835
+ // Apply enrichment overlay to combos too (OmniRoute's
2836
+ // /api/pricing/models surfaces combos alongside provider-scoped
2837
+ // models with curated names).
2838
+ applyEnrichment(mapped, rawEnrichment.get(combo.id));
2839
+
2840
+ // unroutable combo would mislead the picker.
2841
+ if (hasMembers && defaultCompression && defaultCompression.pipeline.length > 0) {
2842
+ const tag = formatCompressionPipeline(defaultCompression.pipeline);
2843
+ if (tag.length > 0 && !mapped.name.includes(tag)) {
2844
+ mapped.name = `${mapped.name} ${tag}`;
2845
+ }
2846
+ }
2847
+
2848
+ const comboKey = buildComboKey(combo, usedComboKeys, resolved.providerId);
2849
+
2850
+ // Collision policy: combos win. Warn ONCE per (cacheKey, comboKey)
2851
+ // when overwriting a same-key raw model so the operator can spot
2852
+ // the unusual naming choice without log spam. Suppress the warning
2853
+ // when the collision is the intentional dedup pattern (combo.name
2854
+ // exactly matches an existing raw model's id) — /v1/models
2855
+ // pre-mirrors combos as raw entries and the operator's intent is
2856
+ // always "combo wins" in that case.
2857
+ if (Object.prototype.hasOwnProperty.call(models, comboKey)) {
2858
+ const existing = models[comboKey];
2859
+ // Intentional dedup: `/v1/models` pre-mirrors combos as raw
2860
+ // entries, so the bare combo name appears as the model id in
2861
+ // `rawModels`. After our prefixing the existing entry's id is
2862
+ // `${providerId}/${raw.id}` — the combo name is a substring of
2863
+ // that prefixed id (or, for already-prefixed raw models, the
2864
+ // exact id). Use `endsWith` to avoid matching substrings of
2865
+ // unrelated prefixed ids.
2866
+ const isIntentionalDedup =
2867
+ existing &&
2868
+ combo.name &&
2869
+ combo.name.trim().length > 0 &&
2870
+ (existing.id === combo.name.trim() || existing.id.endsWith(`/${combo.name.trim()}`));
2871
+ if (!isIntentionalDedup) {
2872
+ const dedupeKey = `${cacheKey}::${comboKey}`;
2873
+ if (!collisionWarned.has(dedupeKey)) {
2874
+ collisionWarned.add(dedupeKey);
2875
+ console.warn(
2876
+ `[omniroute-plugin] combo key "${comboKey}" collides with a model id; combo wins.`
2877
+ );
2878
+ }
2879
+ }
2880
+ }
2881
+ models[comboKey] = mapped;
2882
+
2883
+ // Make this combo's resolved model available to parent combos
2884
+ // that reference it via combo-ref. Use the friendly name
2885
+ // (combo.name) since that's the lookup key on the parent side.
2886
+ const lookupName =
2887
+ combo.name && combo.name.trim().length > 0 ? combo.name.trim() : combo.id;
2888
+ resolvedComboModelsByName.set(lookupName, mapped);
2889
+ }
2890
+ if (stillPending.length === pending.length) break;
2891
+ pending = stillPending;
2892
+ }
2893
+
2894
+ if (pending.length > 0) {
2895
+ console.warn(
2896
+ `[omniroute-plugin] ${pending.length} combo(s) could not resolve all nested combo-refs after ${MAX_COMBO_PASSES} passes; they will advertise context=0 to avoid over-claiming.`
2897
+ );
2898
+ }
2899
+
2900
+ // ── Auto combos in dynamic catalog ────────────────────────────────
2901
+ // Convert virtual auto combos from /api/combos/auto into ModelV2
2902
+ // entries so they appear in the dynamic provider.models() path
2903
+ // (used by OpenCode ≥1.14.49).
2904
+ if (rawAutoCombos.length > 0) {
2905
+ for (const autoCombo of rawAutoCombos) {
2906
+ if (!autoCombo || !autoCombo.id) continue;
2907
+ if (autoCombo.isHidden === true) continue;
2908
+ const entry = mapAutoComboToStaticEntry(autoCombo);
2909
+ const key = autoComboModelId(autoCombo.variant);
2910
+ const mapped: ModelV2 = {
2911
+ id: key,
2912
+ name: entry.name,
2913
+ capabilities: {
2914
+ temperature: entry.temperature ?? true,
2915
+ reasoning: entry.reasoning ?? false,
2916
+ attachment: entry.attachment ?? false,
2917
+ toolcall: entry.tool_call ?? false,
2918
+ input: {
2919
+ text: true,
2920
+ audio: false,
2921
+ image: false,
2922
+ video: false,
2923
+ pdf: false,
2924
+ },
2925
+ output: {
2926
+ text: true,
2927
+ audio: false,
2928
+ image: false,
2929
+ video: false,
2930
+ pdf: false,
2931
+ },
2932
+ interleaved: false,
2933
+ },
2934
+ cost: {
2935
+ input: 0,
2936
+ output: 0,
2937
+ cache: { read: 0, write: 0 },
2938
+ },
2939
+ limit: {
2940
+ context: entry.limit?.context ?? 0,
2941
+ output: entry.limit?.output ?? 0,
2942
+ },
2943
+ api: {
2944
+ id: "openai-compatible",
2945
+ url: ensureV1Suffix(baseURL),
2946
+ npm: "@ai-sdk/openai-compatible",
2947
+ },
2948
+ status: "active",
2949
+ release_date: "",
2950
+ providerID: resolved.providerId,
2951
+ options: {},
2952
+ headers: {},
2953
+ };
2954
+ models[key] = mapped;
2955
+ }
2956
+ }
2957
+
2958
+ return models;
2959
+ },
2960
+ };
2961
+ }
2962
+
2963
+ // ────────────────────────────────────────────────────────────────────────────
2964
+ // Fetch interceptor (T-04) — Bearer + Content-Type injection on outbound
2965
+ // provider requests targeting the configured OmniRoute baseURL
2966
+ // ────────────────────────────────────────────────────────────────────────────
2967
+
2968
+ /**
2969
+ * Build a `fetch`-compatible interceptor that injects `Authorization: Bearer`
2970
+ * (and a default `Content-Type`) onto outbound requests targeting the given
2971
+ * `baseURL`. Requests to any other host pass through untouched — the apiKey
2972
+ * is treated as a secret bound to the configured OmniRoute instance and
2973
+ * MUST NOT leak to third-party endpoints (a vector AI-SDKs occasionally
2974
+ * exercise when a tool call rewrites the URL mid-flight).
2975
+ *
2976
+ * Ported from Alph4d0g's `opencode-omniroute-auth@1.2.1` `createFetchInterceptor`
2977
+ * (their `dist/src/plugin.js:477-516`) with these intentional deviations:
2978
+ *
2979
+ * - **`baseURL` is required** here (no `localhost:20128/v1` fallback). T-04
2980
+ * callers always have an authoritative baseURL (from plugin opts or
2981
+ * auth.json); a silent local default would be a footgun.
2982
+ * - **Content-Type defaulting is gated on `init.body` presence**. Their
2983
+ * version unconditionally sets `application/json` even on `GET /v1/models`,
2984
+ * which is harmless but noisy; we only set it when there's a body to
2985
+ * describe.
2986
+ * - **Gemini schema sanitisation is NOT applied here** — that's T-06's
2987
+ * responsibility and will land as a body-transform step inside this
2988
+ * same function (or as a thin wrapper around it).
2989
+ * - **Header merge strategy mirrors theirs**: Request-attached headers
2990
+ * first, then `init.headers` overlay, then our injected
2991
+ * Authorization/Content-Type — so the apiKey we own ALWAYS wins over
2992
+ * any caller-supplied Bearer for the same OmniRoute provider.
2993
+ *
2994
+ * @see https://opencode.ai/docs/plugins for the AuthLoaderResult.fetch contract
2995
+ * (the returned function is invoked by the AI-SDK in lieu of global fetch).
2996
+ */
2997
+ export function createOmniRouteFetchInterceptor(config: {
2998
+ apiKey: string;
2999
+ baseURL: string;
3000
+ }): typeof fetch {
3001
+ const trimmed = trimTrailingSlashes(config.baseURL);
3002
+ // Use `<base>/` for prefix matching to prevent suffix-spoof attacks
3003
+ // (e.g. baseURL `https://or.example.com/v1` should NOT match
3004
+ // `https://or.example.com/v1-attacker.evil/...`).
3005
+ const prefix = `${trimmed}/`;
3006
+ return async (input, init = {}) => {
3007
+ const url =
3008
+ typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
3009
+
3010
+ const targetsOmniRoute = url === trimmed || url.startsWith(prefix);
3011
+ if (!targetsOmniRoute) {
3012
+ return fetch(input, init);
3013
+ }
3014
+
3015
+ // Merge order: Request-attached headers (when input is a Request) →
3016
+ // init.headers overlay → our injected headers last (so we win).
3017
+ const headers = new Headers(input instanceof Request ? input.headers : undefined);
3018
+ if (init.headers) {
3019
+ const initHeaders = new Headers(init.headers);
3020
+ initHeaders.forEach((value, key) => {
3021
+ headers.set(key, value);
3022
+ });
3023
+ }
3024
+
3025
+ headers.set("Authorization", `Bearer ${config.apiKey}`);
3026
+ // Only default Content-Type when the caller actually has a body AND
3027
+ // hasn't already declared the media type themselves.
3028
+ const hasBody = init.body != null || input instanceof Request;
3029
+ if (!headers.has("Content-Type") && hasBody) {
3030
+ headers.set("Content-Type", "application/json");
3031
+ }
3032
+
3033
+ return fetch(input, { ...init, headers });
3034
+ };
3035
+ }
3036
+
3037
+ // ────────────────────────────────────────────────────────────────────────────
3038
+ // Gemini tool-schema sanitisation (T-06) — strip JSON-schema keywords that
3039
+ // the Gemini API rejects from outbound chat-completion / responses bodies
3040
+ // when the target model is a Gemini variant.
3041
+ // ────────────────────────────────────────────────────────────────────────────
3042
+
3043
+ /**
3044
+ * JSON-Schema keywords that the Gemini API rejects when present anywhere in
3045
+ * a function-calling tool definition. Standard OpenAI / Anthropic clients
3046
+ * happily emit these (they're valid Draft-07 schema) but Gemini's tool
3047
+ * validator throws on them, breaking OmniRoute → Gemini chains transparently.
3048
+ *
3049
+ * Source: behavioural reverse-engineering from Alph4d0g's
3050
+ * opencode-omniroute-auth@1.2.1 (dist/src/plugin.js:517).
3051
+ */
3052
+ const GEMINI_SCHEMA_KEYS_TO_REMOVE = new Set(["$schema", "$ref", "ref", "additionalProperties"]);
3053
+
3054
+ function isRecord(v: unknown): v is Record<string, unknown> {
3055
+ return typeof v === "object" && v !== null && !Array.isArray(v);
3056
+ }
3057
+
3058
+ /**
3059
+ * Recursively strip `GEMINI_SCHEMA_KEYS_TO_REMOVE` from an arbitrary
3060
+ * JSON-Schema-shaped record. Walks both the record's own properties and
3061
+ * any nested objects / arrays so deeply nested `properties.x.properties.y`
3062
+ * trees are reached without a separate traversal pass. Mutates in place
3063
+ * and reports whether any key was deleted so callers can skip a
3064
+ * `JSON.stringify` round-trip when nothing changed.
3065
+ */
3066
+ function stripSchemaKeys(schema: Record<string, unknown>): boolean {
3067
+ let changed = false;
3068
+ for (const key of Object.keys(schema)) {
3069
+ if (GEMINI_SCHEMA_KEYS_TO_REMOVE.has(key)) {
3070
+ delete schema[key];
3071
+ changed = true;
3072
+ continue;
3073
+ }
3074
+ const value = schema[key];
3075
+ if (Array.isArray(value)) {
3076
+ for (const item of value) {
3077
+ if (isRecord(item)) {
3078
+ changed = stripSchemaKeys(item) || changed;
3079
+ }
3080
+ }
3081
+ continue;
3082
+ }
3083
+ if (isRecord(value)) {
3084
+ changed = stripSchemaKeys(value) || changed;
3085
+ }
3086
+ }
3087
+ return changed;
3088
+ }
3089
+
3090
+ /**
3091
+ * Walk every tool definition in the payload and strip Gemini-incompatible
3092
+ * schema keywords. Handles both chat-completion shape
3093
+ * (`tools[].function.parameters`) and Responses-API shape
3094
+ * (`tools[].input_schema`), plus the Gemini-native `function_declaration`
3095
+ * variant some adapters use.
3096
+ *
3097
+ * Also strips top-level schema keywords from the payload itself — clients
3098
+ * occasionally attach a top-level `$schema` declaration when re-serialising
3099
+ * tool bundles, and Gemini rejects those too.
3100
+ */
3101
+ function sanitizeToolSchemaContainer(payload: Record<string, unknown>): boolean {
3102
+ let changed = false;
3103
+ // Top-level keyword strip — covers payload-level `$schema` etc.
3104
+ for (const key of Object.keys(payload)) {
3105
+ if (GEMINI_SCHEMA_KEYS_TO_REMOVE.has(key)) {
3106
+ delete payload[key];
3107
+ changed = true;
3108
+ }
3109
+ }
3110
+ const tools = (payload as { tools?: unknown }).tools;
3111
+ if (!Array.isArray(tools)) {
3112
+ return changed;
3113
+ }
3114
+ for (const tool of tools) {
3115
+ if (!isRecord(tool)) continue;
3116
+ const fn = (tool as { function?: unknown }).function;
3117
+ if (isRecord(fn) && isRecord((fn as { parameters?: unknown }).parameters)) {
3118
+ changed = stripSchemaKeys(fn.parameters as Record<string, unknown>) || changed;
3119
+ }
3120
+ const fnDecl = (tool as { function_declaration?: unknown }).function_declaration;
3121
+ if (isRecord(fnDecl) && isRecord((fnDecl as { parameters?: unknown }).parameters)) {
3122
+ changed = stripSchemaKeys(fnDecl.parameters as Record<string, unknown>) || changed;
3123
+ }
3124
+ const inputSchema = (tool as { input_schema?: unknown }).input_schema;
3125
+ if (isRecord(inputSchema)) {
3126
+ changed = stripSchemaKeys(inputSchema) || changed;
3127
+ }
3128
+ }
3129
+ return changed;
3130
+ }
3131
+
3132
+ /**
3133
+ * Pure function — recursively strip Gemini-incompatible JSON-Schema
3134
+ * keywords (`$schema`, `$ref`, `ref`, `additionalProperties`) from the
3135
+ * tool definitions on a chat-completions / responses payload.
3136
+ *
3137
+ * Walks:
3138
+ * - `payload.tools[].function.parameters` (OpenAI chat-completions shape)
3139
+ * - `payload.tools[].function_declaration.parameters` (Gemini-native shape
3140
+ * some adapters round-trip)
3141
+ * - `payload.tools[].input_schema` (Responses-API shape)
3142
+ * - all `properties.<x>` (and `properties.<x>.properties.<y>`…) inside
3143
+ * each container, recursing through nested objects and arrays.
3144
+ * - top-level payload keys (some clients attach a payload-level `$schema`).
3145
+ *
3146
+ * Returns the cleaned payload. Does NOT mutate input — clones first via
3147
+ * `structuredClone` so callers can keep a reference to the original. If
3148
+ * the payload is not a record, or carries no tools and no top-level
3149
+ * stripped keys, returns a (still cloned) equivalent.
3150
+ *
3151
+ * Exported so the body-transform layer is unit-testable independent of the
3152
+ * fetch wrapper.
3153
+ */
3154
+ export function sanitizeGeminiToolSchemas(payload: unknown): unknown {
3155
+ if (!isRecord(payload)) {
3156
+ // Non-record payloads (string, array, number, null) can't carry tool
3157
+ // schemas. Pass back the same value — there's nothing to clone-and-strip
3158
+ // and propagating the original keeps caller semantics simple.
3159
+ return payload;
3160
+ }
3161
+ // structuredClone is available in Node 18+; the package's engines field
3162
+ // already requires Node >=22.22.3 so we can rely on it without a
3163
+ // JSON round-trip fallback.
3164
+ const cloned = structuredClone(payload) as Record<string, unknown>;
3165
+ sanitizeToolSchemaContainer(cloned);
3166
+ return cloned;
3167
+ }
3168
+
3169
+ /**
3170
+ * Detect whether a payload is bound for a Gemini model. Returns true if
3171
+ * `payload.model` is a string AND matches any known Gemini routing pattern:
3172
+ *
3173
+ * - case-insensitive substring `gemini` (covers bare `gemini-1.5-pro`,
3174
+ * `gemini-2.5-flash`, etc.)
3175
+ * - `models/gemini-…` (Google Generative AI canonical id form)
3176
+ * - `google-vertex/gemini-…` (OpenCode + AI-SDK Vertex routing prefix)
3177
+ *
3178
+ * Liberal by design: a false positive (cleaning a payload that didn't
3179
+ * need cleaning) costs only a structuredClone + one walk; a false negative
3180
+ * breaks the whole chain by forwarding $schema/additionalProperties to
3181
+ * Gemini which throws 400 INVALID_ARGUMENT. The first three checks
3182
+ * collapse into the case-insensitive substring check, but they're
3183
+ * documented separately so future maintainers see the intent.
3184
+ *
3185
+ * Exported so callers and tests can probe detection independent of the
3186
+ * fetch wrapper.
3187
+ */
3188
+ export function shouldSanitizeForGemini(payload: unknown): boolean {
3189
+ if (!isRecord(payload)) return false;
3190
+ const model = (payload as { model?: unknown }).model;
3191
+ if (typeof model !== "string") return false;
3192
+ return /gemini/i.test(model);
3193
+ }
3194
+
3195
+ /**
3196
+ * Module-level latch so the streaming-body warning fires AT MOST once per
3197
+ * Node process. ReadableStream bodies can't be safely cloned + JSON-parsed
3198
+ * without consuming the stream (and re-creating a stream that survives both
3199
+ * read paths is non-trivial), so the sanitiser skips them — but we want
3200
+ * the operator to see one heads-up that schema stripping won't run on
3201
+ * those requests.
3202
+ */
3203
+ let geminiStreamingWarningEmitted = false;
3204
+
3205
+ /**
3206
+ * Wrapper over an inner `fetch` that applies Gemini schema sanitisation to
3207
+ * outbound chat-completion / responses request bodies.
3208
+ *
3209
+ * Behaviour:
3210
+ * - URL gate: only inspects requests whose URL path contains
3211
+ * `/chat/completions` or `/responses` (lenient about prefix — works for
3212
+ * `/v1/chat/completions`, `/openai/v1/chat/completions`, …).
3213
+ * - Body extraction handles `string`, `Buffer` / `Uint8Array`,
3214
+ * `URLSearchParams` (calls `.toString()`), `Blob` (`await .text()`),
3215
+ * AND `Request` input where the body lives on the Request not init.
3216
+ * `ReadableStream` bodies are skipped (see below).
3217
+ * - Body must JSON.parse to a record; otherwise pass-through.
3218
+ * - `shouldSanitizeForGemini` gates the actual transform — non-Gemini
3219
+ * payloads pass through unchanged regardless of endpoint.
3220
+ * - Fail-open: ANY error during extraction / parse / sanitise falls back
3221
+ * to forwarding the original `(input, init)` to the inner fetch.
3222
+ * Sanitisation is a best-effort guard, never a hard failure mode.
3223
+ * - `ReadableStream` bodies → skipped with a ONE-TIME `console.warn`.
3224
+ * The Gemini-quirk only manifests with tool calls in the body, and
3225
+ * OC streams plain text deltas; the operator should still know.
3226
+ *
3227
+ * @param inner The next fetch in the chain (typically the Bearer-injecting
3228
+ * interceptor from `createOmniRouteFetchInterceptor`).
3229
+ */
3230
+ export function createGeminiSanitizingFetch(inner: typeof fetch): typeof fetch {
3231
+ return async (input, init) => {
3232
+ try {
3233
+ const url =
3234
+ typeof input === "string"
3235
+ ? input
3236
+ : input instanceof URL
3237
+ ? input.toString()
3238
+ : input instanceof Request
3239
+ ? input.url
3240
+ : "";
3241
+
3242
+ // URL gate — match the path substring with prefix tolerance.
3243
+ const targetsCompletions = url.includes("/chat/completions") || url.includes("/responses");
3244
+ if (!targetsCompletions) {
3245
+ return inner(input, init);
3246
+ }
3247
+
3248
+ // Body extraction. Cover the body shapes the AI-SDK + adapter layer
3249
+ // actually emit; bail to pass-through on anything we can't read
3250
+ // synchronously without consuming a stream.
3251
+ let rawBody: string | undefined;
3252
+ const initBody = init?.body as unknown;
3253
+
3254
+ if (typeof initBody === "string") {
3255
+ rawBody = initBody;
3256
+ } else if (initBody instanceof URLSearchParams) {
3257
+ // Form-encoded bodies are never chat-completion JSON; pass-through.
3258
+ return inner(input, init);
3259
+ } else if (typeof Buffer !== "undefined" && initBody instanceof Buffer) {
3260
+ rawBody = initBody.toString("utf8");
3261
+ } else if (initBody instanceof Uint8Array) {
3262
+ rawBody = new TextDecoder().decode(initBody);
3263
+ } else if (initBody instanceof ReadableStream) {
3264
+ // Streaming body — skip with one-shot warning.
3265
+ if (!geminiStreamingWarningEmitted) {
3266
+ geminiStreamingWarningEmitted = true;
3267
+
3268
+ console.warn(
3269
+ "[omniroute-plugin] sanitizeGemini: streaming Request body, skipping schema strip (Gemini may reject)"
3270
+ );
3271
+ }
3272
+ return inner(input, init);
3273
+ } else if (
3274
+ initBody !== null &&
3275
+ initBody !== undefined &&
3276
+ typeof (initBody as { text?: unknown }).text === "function"
3277
+ ) {
3278
+ // Blob-like (has .text(): Promise<string>). Streaming was already
3279
+ // matched above — anything left with a `.text` method we can buffer.
3280
+ try {
3281
+ rawBody = await (initBody as { text(): Promise<string> }).text();
3282
+ } catch {
3283
+ return inner(input, init);
3284
+ }
3285
+ } else if (initBody === undefined && input instanceof Request) {
3286
+ // Body lives on the Request object itself, not init. Clone before
3287
+ // reading — consuming the original Request body would make it
3288
+ // unreadable downstream.
3289
+ try {
3290
+ rawBody = await (input as Request).clone().text();
3291
+ } catch {
3292
+ return inner(input, init);
3293
+ }
3294
+ }
3295
+
3296
+ if (rawBody === undefined || rawBody.length === 0) {
3297
+ return inner(input, init);
3298
+ }
3299
+
3300
+ let payload: unknown;
3301
+ try {
3302
+ payload = JSON.parse(rawBody);
3303
+ } catch {
3304
+ // Non-JSON body → pass-through, never throw.
3305
+ return inner(input, init);
3306
+ }
3307
+
3308
+ if (!shouldSanitizeForGemini(payload)) {
3309
+ return inner(input, init);
3310
+ }
3311
+
3312
+ const cleaned = sanitizeGeminiToolSchemas(payload);
3313
+ const newBody = JSON.stringify(cleaned);
3314
+ // Cloning init: we need to replace `body` without mutating the caller's
3315
+ // init bag. If init was undefined (Request-input path), construct one.
3316
+ const newInit: RequestInit = { ...(init ?? {}), body: newBody };
3317
+ return inner(input, newInit);
3318
+ } catch {
3319
+ // Total fail-open — never let a sanitiser bug break the request path.
3320
+ return inner(input, init);
3321
+ }
3322
+ };
3323
+ }
3324
+
3325
+ /**
3326
+ * Test-only hook: reset the module-level streaming-warning latch so each
3327
+ * test can independently assert the one-shot semantics. Not part of the
3328
+ * public stability contract — prefixed with `__` per convention to signal
3329
+ * "do not depend on this from production code".
3330
+ */
3331
+ export function __resetGeminiStreamingWarning(): void {
3332
+ geminiStreamingWarningEmitted = false;
3333
+ }
3334
+
3335
+ // ────────────────────────────────────────────────────────────────────────────
3336
+ // Config hook (T-07) — backward-compat shim for OC ≤1.14.48
3337
+ //
3338
+ // OC ≤1.14.48 does NOT call `provider.models()` at startup; it reads the
3339
+ // catalog from the static `provider.<id>` config block instead. OC ≥1.14.49
3340
+ // calls `provider.models()` dynamically AND merges the dynamic catalog over
3341
+ // any static block (dynamic wins on collision). To support both, the plugin
3342
+ // publishes a static block via `config` AND a dynamic one via `provider.models`
3343
+ // — OC's resolution order picks the right one per OC version. This module
3344
+ // implements the static-publish half.
3345
+ //
3346
+ // Sibling shape source-of-truth: see
3347
+ // `@omniroute/opencode-provider/src/index.ts` (`createOmniRouteProvider`,
3348
+ // `OpenCodeProviderEntry`, `OpenCodeModelEntry`). We replicate that shape
3349
+ // here rather than depending on the sibling package — the plugin must stay
3350
+ // self-contained (npm-installable on its own, no peer dep on the provider
3351
+ // builder).
3352
+ // ────────────────────────────────────────────────────────────────────────────
3353
+
3354
+ /**
3355
+ * Per-model entry shape under `provider.<id>.models[modelId]`. Mirrors
3356
+ * `OpenCodeModelEntry` exported by `@omniroute/opencode-provider`. Stripped
3357
+ * down to the fields OC's static catalog reader actually consumes — NOT a
3358
+ * full ModelV2 (that's the dynamic-hook shape). Optional fields are omitted
3359
+ * when OmniRoute didn't surface a value, NOT emitted as `undefined` — the
3360
+ * resulting JSON must be diffable across OmniRoute deployments without
3361
+ * `undefined` noise.
3362
+ */
3363
+ /** Modalities accepted by OC's static catalog reader (see `@opencode-ai/sdk`). */
3364
+ export type OmniRouteModalityKind = "text" | "audio" | "image" | "video" | "pdf";
3365
+
3366
+ const STATIC_MODALITY_VALUES: ReadonlySet<OmniRouteModalityKind> = new Set([
3367
+ "text",
3368
+ "audio",
3369
+ "image",
3370
+ "video",
3371
+ "pdf",
3372
+ ]);
3373
+
3374
+ /** Normalise + filter raw modality list to the values OC accepts. Deduped. */
3375
+ function normaliseModalities(raw: unknown): OmniRouteModalityKind[] {
3376
+ if (!Array.isArray(raw)) return [];
3377
+ const out: OmniRouteModalityKind[] = [];
3378
+ const seen = new Set<string>();
3379
+ for (const v of raw) {
3380
+ if (typeof v !== "string") continue;
3381
+ const lower = v.toLowerCase() as OmniRouteModalityKind;
3382
+ if (!STATIC_MODALITY_VALUES.has(lower)) continue;
3383
+ if (seen.has(lower)) continue;
3384
+ seen.add(lower);
3385
+ out.push(lower);
3386
+ }
3387
+ return out;
3388
+ }
3389
+
3390
+ export interface OmniRouteStaticModelEntry {
3391
+ /** Owning provider id. SHOULD match the parent `provider.<id>` key so OC's
3392
+ * static-catalog reader resolves credentials via `providerID` instead of
3393
+ * parsing the model key on `/`. Optional: OC's schema validator may
3394
+ * reject the entire provider block when this field is present but the
3395
+ * model KEY already carries the provider prefix (e.g. `omniroute/MASTER`),
3396
+ * since the prefix makes the field redundant and the field is not part of
3397
+ * OC's expected schema. We omit it from entries and rely on the prefix
3398
+ * on the KEY alone. See PR #4184. */
3399
+ providerID?: string;
3400
+ /** Display label rendered in OC's model picker. Defaults to the model id. */
3401
+ name: string;
3402
+
3403
+ /** ISO date the model was released. Surfaces in OC's model card when present. */
3404
+ release_date?: string;
3405
+ /** Model accepts image / file attachments. */
3406
+ attachment?: boolean;
3407
+ /** Model exposes a reasoning / extended-thinking surface. */
3408
+ reasoning?: boolean;
3409
+ /** Model honours the `temperature` parameter. */
3410
+ temperature?: boolean;
3411
+ /** Model supports function / tool calling. */
3412
+ tool_call?: boolean;
3413
+ /**
3414
+ * Per-million-token cost. Maps from OmniRoute `/api/pricing` shape:
3415
+ * `input`/`output` pass through; `cached` → `cache_read`;
3416
+ * `cache_creation` → `cache_write`. Omitted when no pricing slot resolves.
3417
+ */
3418
+ cost?: {
3419
+ input: number;
3420
+ output: number;
3421
+ cache_read?: number;
3422
+ cache_write?: number;
3423
+ };
3424
+ /**
3425
+ * Context-window limits. OC's static reader requires both `context` AND
3426
+ * `output` when `limit` is present, so the field is only emitted when
3427
+ * BOTH are known.
3428
+ */
3429
+ limit?: {
3430
+ context: number;
3431
+ output: number;
3432
+ };
3433
+ /**
3434
+ * Modality lists the model accepts (input) and emits (output). Maps from
3435
+ * OmniRoute's `input_modalities` / `output_modalities` on `/v1/models`.
3436
+ * Emitted only when at least one modality is known — without this field
3437
+ * OC's runtime catalog defaults `input.image: false` even when the model
3438
+ * card has `attachment: true`, which blocks clipboard image paste in the
3439
+ * TUI for vision-capable models.
3440
+ */
3441
+ modalities?: {
3442
+ input: OmniRouteModalityKind[];
3443
+ output: OmniRouteModalityKind[];
3444
+ };
3445
+ }
3446
+
3447
+ /**
3448
+ * Static `provider.<id>` block written to `input.provider` by the config hook.
3449
+ * Mirrors `OpenCodeProviderEntry` from `@omniroute/opencode-provider`.
3450
+ *
3451
+ * - `npm` is always `"@ai-sdk/openai-compatible"` — OmniRoute exposes an
3452
+ * OpenAI-compatible surface and that's the AI-SDK adapter that speaks it.
3453
+ * - `options.baseURL` MUST be the fully-qualified `/v1` URL (the AI-SDK
3454
+ * appends paths like `/chat/completions` directly under it).
3455
+ * - `options.apiKey` is the bearer token; the fetch interceptor (T-04)
3456
+ * also injects it on the dynamic path, but the static block needs it
3457
+ * embedded too so OC ≤1.14.48 can construct the SDK client without
3458
+ * going through the auth hook.
3459
+ */
3460
+ export interface OmniRouteStaticProviderEntry {
3461
+ npm: "@ai-sdk/openai-compatible";
3462
+ name: string;
3463
+ options: {
3464
+ baseURL: string;
3465
+ apiKey: string;
3466
+ };
3467
+ models: Record<string, OmniRouteStaticModelEntry>;
3468
+ }
3469
+
3470
+ /**
3471
+ * Build the static `provider.<id>` block from raw `/v1/models` + `/api/combos`
3472
+ * responses. Pure function — no I/O, no side effects, no dependency on the
3473
+ * sibling provider package. Exported so callers and tests can construct the
3474
+ * block independently of the auth.json + fetch pipeline.
3475
+ *
3476
+ * Mapping rules (per the sibling `createOmniRouteProvider` output spec):
3477
+ *
3478
+ * - One entry per raw model AND one entry per non-hidden combo.
3479
+ * - `name` = model id (no separate display name on `/v1/models`).
3480
+ * - `attachment` = `caps.attachment ?? caps.vision ?? false` — same
3481
+ * convention as `mapRawModelToModelV2` (T-03).
3482
+ * - `reasoning` = `caps.reasoning || caps.thinking`. Booleans only — we
3483
+ * do NOT emit the field when both source flags are absent (keeps the
3484
+ * stripped shape minimal).
3485
+ * - `temperature` = `caps.temperature ?? true` — OpenAI-compat surface
3486
+ * supports temperature by default; only an explicit `false` suppresses.
3487
+ * - `tool_call` = `caps.tool_calling ?? false`.
3488
+ * - `limit.context` = raw `context_length` when > 0; omitted otherwise.
3489
+ * - `limit.input` = raw `max_input_tokens` when present.
3490
+ * - `limit.output` = raw `max_output_tokens` when present.
3491
+ *
3492
+ * For combos: LCD across member raw models (matches `mapComboToModelV2`):
3493
+ *
3494
+ * - `attachment`, `reasoning`, `tool_call`, `temperature`: `every` member.
3495
+ * - `limit.context` = min(member context_lengths).
3496
+ * - `limit.input` = min(member max_input_tokens) ONLY when every member
3497
+ * declares one.
3498
+ * - `limit.output` = min(member max_output_tokens).
3499
+ * - Empty members → all-false / limits omitted.
3500
+ *
3501
+ * Collision: combos win (matches the dynamic provider hook).
3502
+ *
3503
+ * @param rawModels Raw `/v1/models` entries (may be empty).
3504
+ * @param rawCombos Raw `/api/combos` entries (may be empty).
3505
+ * @param opts Resolved plugin options (we read `displayName` + `providerId`).
3506
+ * @param baseURL Fully-qualified `/v1` base URL — written verbatim to
3507
+ * `options.baseURL`. Caller is responsible for `/v1`
3508
+ * normalisation; we do NOT touch it here.
3509
+ * @param apiKey Bearer token — written verbatim to `options.apiKey`.
3510
+ */
3511
+ export function buildStaticProviderEntry(
3512
+ rawModels: OmniRouteRawModelEntry[],
3513
+ rawCombos: OmniRouteRawCombo[],
3514
+ opts: ReturnType<typeof resolveOmniRoutePluginOptions>,
3515
+ baseURL: string,
3516
+ apiKey: string,
3517
+ enrichment?: OmniRouteEnrichmentMap,
3518
+ compressionCombos?: OmniRouteCompressionCombo[],
3519
+ connections?: OmniRouteProviderConnection[],
3520
+ rawAutoCombos?: OmniRouteRawAutoCombo[]
3521
+ ): OmniRouteStaticProviderEntry {
3522
+ const models: Record<string, OmniRouteStaticModelEntry> = {};
3523
+
3524
+ // usableOnly filter — compute once when feature enabled AND we have
3525
+ // connection data to filter against. Soft-fail (empty connections list)
3526
+ // disables the filter rather than hiding the catalog.
3527
+ const wantUsableOnly = opts.features?.usableOnly === true;
3528
+ const usable =
3529
+ wantUsableOnly && connections && connections.length > 0
3530
+ ? usableProviderAliasSet(connections, enrichment)
3531
+ : undefined;
3532
+ // Provider-tag suffix — default-on, opt-out via `features.providerTag: false`.
3533
+ // Prepends e.g. `Claude - ` to enriched raw-model names so the picker
3534
+ // can tell `cc/claude-opus-4-7` (Anthropic) apart from `kr/claude-opus-4-7`
3535
+ // (Kiro). Combos skip this by design.
3536
+ const wantProviderTag = opts.features?.providerTag !== false;
3537
+
3538
+ // Build a name-set of every non-hidden combo from `/api/combos`. OmniRoute
3539
+ // pre-mirrors combos into `/v1/models` with the friendly name as the raw
3540
+ // id (e.g. `claude-primary`, `gemini-pro`), so without dedup the static
3541
+ // catalog ends up with both `claude-primary` (raw, opaque) AND the same
3542
+ // combo under `combo/claude-primary` (rich LCD). We suppress the raw twin
3543
+ // so each combo surfaces exactly once, under the `combo/` namespace.
3544
+ const comboNames = new Set<string>();
3545
+ for (const combo of rawCombos) {
3546
+ if (!combo || combo.isHidden === true) continue;
3547
+ const name = combo.name && combo.name.trim().length > 0 ? combo.name.trim() : combo.id;
3548
+ if (typeof name === "string" && name.length > 0) comboNames.add(name);
3549
+ }
3550
+
3551
+ // Build the canonical→alias reverse map AND the canonical-dedup set
3552
+ // once per static-block construction. Same shape as the dynamic hook
3553
+ // so both catalogs publish identical keys (no `claude/X` raw twin
3554
+ // shadowing the enriched `cc/X` row).
3555
+ const canonicalToAlias = buildCanonicalToAliasMap(enrichment);
3556
+ const canonicalDedup = canonicalDedupSet(rawModels, canonicalToAlias);
3557
+ const aliasIndex = buildAliasIndex(enrichment);
3558
+
3559
+ // Raw model entries → stripped per-model shape.
3560
+ for (const raw of rawModels) {
3561
+ if (!raw.id) continue;
3562
+ // Skip the 20 named no-slash entries that shadow combos under the
3563
+ // `combo/<name>` namespace. We keep `codex-auto-review` and any other
3564
+ // future no-slash raw entry that doesn't have a matching combo.
3565
+ if (comboNames.has(raw.id)) continue;
3566
+ // Skip canonical-named twins when the alias-keyed enriched row exists.
3567
+ if (canonicalDedup.has(raw.id)) continue;
3568
+ if (usable && !isUsableRawModelId(raw.id, usable, enrichment)) continue;
3569
+ const caps = raw.capabilities ?? {};
3570
+ // Enrichment overlay: `/api/pricing/models` carries human display names
3571
+ // (e.g. "Claude Opus 4.7" for raw id "cc/claude-opus-4-7"). The OC TUI
3572
+ // model picker reads this `name` straight from the static block on
3573
+ // OC ≤1.15.5 where the dynamic provider hook never fires. Falls back
3574
+ // to the raw id when no enrichment entry is found. The alias-fallback
3575
+ // lookup rescues `<canonical>/<id>` rows whose enrichment indexed only
3576
+ // under `<alias>/<id>`.
3577
+ const enrichmentEntry = lookupEnrichment(raw.id, enrichment, canonicalToAlias);
3578
+ const enrichmentName = enrichmentEntry?.name;
3579
+ let displayName = enrichmentName && enrichmentName.length > 0 ? enrichmentName : raw.id;
3580
+ // Provider-tag PREFIX — `<label> - <name>` so the picker groups by
3581
+ // upstream provider when scanning a column of model names. Mirrors
3582
+ // `applyProviderTag` used in the dynamic hook. Idempotent: skip
3583
+ // when the name already starts with the prefix. The alias-index
3584
+ // fallback rescues raw rows like `cohere/rerank-multilingual-v3.0`
3585
+ // whose specific model id isn't in `/api/pricing/models` but whose
3586
+ // slot is.
3587
+ if (wantProviderTag) {
3588
+ const tagEntry = resolveProviderTagEntry(
3589
+ raw.id,
3590
+ enrichmentEntry,
3591
+ aliasIndex,
3592
+ canonicalToAlias
3593
+ );
3594
+ const label = shortProviderLabel(tagEntry);
3595
+ if (label) {
3596
+ const prefix = `${label}${PROVIDER_TAG_SEPARATOR}`;
3597
+ if (!displayName.startsWith(prefix)) displayName = `${prefix}${displayName}`;
3598
+ }
3599
+ }
3600
+ // OC's static-catalog schema doesn't expect a `providerID` field on
3601
+ // individual entries — the parent block ID is the provider. Adding
3602
+ // unknown fields here can cause OC's schema validator to reject the
3603
+ // entire provider block, hiding ALL models. The provider prefix on the
3604
+ // model KEY (e.g. `omniroute/claude-opus-4`) is what OC uses to recover
3605
+ // (providerID, modelID) when the user selects a model.
3606
+ const entry: OmniRouteStaticModelEntry = { name: displayName };
3607
+
3608
+ const attachment = caps.attachment ?? caps.vision;
3609
+ if (typeof attachment === "boolean") entry.attachment = attachment;
3610
+
3611
+ if (typeof caps.reasoning === "boolean" || typeof caps.thinking === "boolean") {
3612
+ entry.reasoning = Boolean(caps.reasoning || caps.thinking);
3613
+ }
3614
+
3615
+ if (typeof caps.temperature === "boolean") {
3616
+ entry.temperature = caps.temperature;
3617
+ }
3618
+
3619
+ if (typeof caps.tool_calling === "boolean") {
3620
+ entry.tool_call = caps.tool_calling;
3621
+ }
3622
+
3623
+ // OC's SDK schema requires BOTH `context` and `output` when `limit` is
3624
+ // present. We previously emitted `limit.input` too, but the SDK reader
3625
+ // doesn't accept it — drop it. Only emit `limit` when both required
3626
+ // values are known.
3627
+ if (
3628
+ typeof raw.context_length === "number" &&
3629
+ raw.context_length > 0 &&
3630
+ typeof raw.max_output_tokens === "number" &&
3631
+ raw.max_output_tokens > 0
3632
+ ) {
3633
+ entry.limit = {
3634
+ context: raw.context_length,
3635
+ output: raw.max_output_tokens,
3636
+ };
3637
+ }
3638
+
3639
+ // Modalities — emit when OmniRoute surfaced any. Without this field
3640
+ // OC's runtime model defaults `input.image: false` even for vision-
3641
+ // capable models, blocking clipboard image paste in the TUI.
3642
+ const inModalities = normaliseModalities(raw.input_modalities);
3643
+ const outModalities = normaliseModalities(raw.output_modalities);
3644
+ if (inModalities.length > 0 || outModalities.length > 0) {
3645
+ entry.modalities = {
3646
+ input: inModalities.length > 0 ? inModalities : ["text"],
3647
+ output: outModalities.length > 0 ? outModalities : ["text"],
3648
+ };
3649
+ }
3650
+
3651
+ // Cost from enrichment pricing (sourced from `/api/pricing`). Map
3652
+ // OmniRoute field names to OC's static-schema field names.
3653
+ const pricing = enrichmentEntry?.pricing;
3654
+ if (pricing && (typeof pricing.input === "number" || typeof pricing.output === "number")) {
3655
+ const cost: NonNullable<OmniRouteStaticModelEntry["cost"]> = {
3656
+ input: typeof pricing.input === "number" ? pricing.input : 0,
3657
+ output: typeof pricing.output === "number" ? pricing.output : 0,
3658
+ };
3659
+ if (typeof pricing.cacheRead === "number") cost.cache_read = pricing.cacheRead;
3660
+ if (typeof pricing.cacheWrite === "number") cost.cache_write = pricing.cacheWrite;
3661
+ entry.cost = cost;
3662
+ }
3663
+
3664
+ // release_date from /v1/models — surfaces in OC's model card when present.
3665
+ if (typeof raw.release_date === "string" && raw.release_date.length > 0) {
3666
+ entry.release_date = raw.release_date;
3667
+ }
3668
+
3669
+ // OC's static-catalog reader parses each key on `/` and rejects the
3670
+ // entire provider block if ANY key resolves to a parsed providerID that
3671
+ // has no corresponding provider block. So bare keys (no `/`) MUST be
3672
+ // prefixed with the resolved providerId. Already-prefixed keys
3673
+ // (e.g. `cc/claude-opus-4-7`) are left as-is to avoid double-prefixing.
3674
+ models[raw.id.includes("/") ? raw.id : `${opts.providerId}/${raw.id}`] = entry;
3675
+ }
3676
+
3677
+ // Combo entries → stripped LCD shape. Each combo is keyed as
3678
+ // `combo/<friendly-name>` so the OC TUI model picker shows them under a
3679
+ // distinct namespace (e.g. `combo/claude-primary`) instead of the opaque
3680
+ // upstream UUID id (e.g. `b4a0211e-e3e1-472d-b252-fb9bf6d1c935`).
3681
+ const rawModelById = new Map<string, OmniRouteRawModelEntry>();
3682
+ for (const m of rawModels) {
3683
+ if (m.id) rawModelById.set(m.id, m);
3684
+ }
3685
+
3686
+ // Resolve the default compression pipeline once — its short signature
3687
+ // (e.g. `[rtk:standard → caveman:full]`) is appended to every routable
3688
+ // combo `name` so operators can see what compression a combo applies
3689
+ // at a glance. Provider hook does the same decoration when feature is
3690
+ // on. Suffix is suppressed for combos with no resolvable members —
3691
+ // claiming compression on an unroutable combo would mislead the
3692
+ // picker.
3693
+ let compressionSuffix = "";
3694
+ if (compressionCombos && compressionCombos.length > 0) {
3695
+ const def = compressionCombos.find((c) => c.isDefault === true);
3696
+ if (def) {
3697
+ const sig = formatCompressionPipeline(def.pipeline);
3698
+ if (sig.length > 0) compressionSuffix = ` ${sig}`;
3699
+ }
3700
+ }
3701
+
3702
+ // Track combo keys to detect slug collisions across the catalog.
3703
+ const usedComboKeys = new Set<string>();
3704
+ const reportedCollisions = new Set<string>();
3705
+
3706
+ // ── Combo LCD across nested combo-refs (T-NN mirror) ─────────────────
3707
+ // Mirror of the dynamic-catalog fixpoint iteration: combos can nest
3708
+ // other combos via `kind: "combo-ref"` members (e.g. MASTER-LIGHT
3709
+ // contains OldLLM, KIRO, Opecode Zen FREE). The nested combo's own
3710
+ // capabilities and limits are computed in this same loop, so we need
3711
+ // a fixpoint pass: if a combo-ref points at a combo not yet processed,
3712
+ // defer this combo and try again after the sibling combos catch up.
3713
+ // We bound the retries so a circular combo graph can't deadlock the
3714
+ // picker, and we break early when a pass makes no progress.
3715
+ const MAX_STATIC_COMBO_PASSES = 8;
3716
+ const resolvedStaticCombosByName = new Map<string, OmniRouteStaticModelEntry>();
3717
+ let pendingStatic = rawCombos.filter((combo) => {
3718
+ if (!combo.id) return false;
3719
+ if (combo.isHidden === true) return false;
3720
+ if (usable && !isUsableCombo(combo, usable)) return false;
3721
+ return true;
3722
+ });
3723
+
3724
+ for (let pass = 0; pass < MAX_STATIC_COMBO_PASSES && pendingStatic.length > 0; pass++) {
3725
+ const stillPendingStatic: typeof pendingStatic = [];
3726
+ for (const combo of pendingStatic) {
3727
+ const memberSteps = Array.isArray(combo.models) ? combo.models : [];
3728
+ const memberEntries: OmniRouteRawModelEntry[] = [];
3729
+ let deferredThisPass = false;
3730
+
3731
+ for (const step of memberSteps) {
3732
+ const stepKind = (step as unknown as { kind?: unknown }).kind;
3733
+
3734
+ if (stepKind === "combo-ref") {
3735
+ const comboName = (step as unknown as { comboName?: unknown }).comboName;
3736
+ if (typeof comboName !== "string" || comboName.length === 0) {
3737
+ continue;
3738
+ }
3739
+ const nestedEntry = resolvedStaticCombosByName.get(comboName);
3740
+ if (!nestedEntry) {
3741
+ deferredThisPass = true;
3742
+ break;
3743
+ }
3744
+ // Synthesize a raw-model-shaped member entry carrying the
3745
+ // nested combo's pre-computed context + capabilities +
3746
+ // modalities. Mirrors the dynamic path so the static catalog
3747
+ // stays in lockstep with the dynamic one.
3748
+ const inputModalities = (nestedEntry.modalities?.input ?? ["text"]) as string[];
3749
+ const outputModalities = (nestedEntry.modalities?.output ?? ["text"]) as string[];
3750
+ memberEntries.push({
3751
+ id: `combo-ref:${comboName}`,
3752
+ context_length: nestedEntry.limit?.context ?? 0,
3753
+ max_output_tokens: nestedEntry.limit?.output ?? 0,
3754
+ max_input_tokens: 0,
3755
+ owned_by: "combo",
3756
+ input_modalities: inputModalities,
3757
+ output_modalities: outputModalities,
3758
+ capabilities: {
3759
+ temperature: nestedEntry.temperature,
3760
+ reasoning: nestedEntry.reasoning,
3761
+ thinking: nestedEntry.reasoning,
3762
+ attachment: nestedEntry.attachment,
3763
+ tool_calling: nestedEntry.tool_call,
3764
+ },
3765
+ } as unknown as OmniRouteRawModelEntry);
3766
+ continue;
3767
+ }
3768
+
3769
+ const modelId = (step as unknown as { model?: unknown }).model;
3770
+ if (typeof modelId !== "string" || modelId.length === 0) continue;
3771
+ const member = rawModelById.get(modelId);
3772
+ if (member) memberEntries.push(member);
3773
+ }
3774
+
3775
+ if (deferredThisPass) {
3776
+ stillPendingStatic.push(combo);
3777
+ continue;
3778
+ }
3779
+
3780
+ const hasMembers = memberEntries.length > 0;
3781
+ const friendlyName =
3782
+ combo.name && combo.name.trim().length > 0 ? combo.name.trim() : combo.id;
3783
+ const displayName =
3784
+ hasMembers && compressionSuffix ? `${friendlyName} ${compressionSuffix}` : friendlyName;
3785
+ // See the raw-model entry comment above — `providerID` on entries is
3786
+ // not part of OC's static-catalog schema; the parent block ID is the
3787
+ // provider and the KEY prefix (`omniroute/<slug>`) is what OC parses.
3788
+ const entry: OmniRouteStaticModelEntry = { name: displayName };
3789
+
3790
+ if (hasMembers) {
3791
+ // LCD across capabilities — every member must support for the combo
3792
+ // to support. Mirrors mapComboToModelV2.
3793
+ entry.attachment = memberEntries.every((m) =>
3794
+ Boolean(m.capabilities?.attachment ?? m.capabilities?.vision ?? false)
3795
+ );
3796
+ entry.reasoning = memberEntries.every((m) =>
3797
+ Boolean(m.capabilities?.reasoning || m.capabilities?.thinking)
3798
+ );
3799
+ entry.temperature = memberEntries.every(
3800
+ (m) => (m.capabilities?.temperature ?? true) !== false
3801
+ );
3802
+ entry.tool_call = memberEntries.every((m) =>
3803
+ Boolean(m.capabilities?.tool_calling ?? false)
3804
+ );
3805
+
3806
+ // LCD across limits — min over declared values. OC's SDK static schema
3807
+ // accepts only `context` + `output` on `limit`, so we drop the legacy
3808
+ // `input` emission. Emit only when BOTH context AND output are known
3809
+ // across at least one member (mirrors the required-field constraint).
3810
+ const contextValues = memberEntries
3811
+ .map((m) => m.context_length)
3812
+ .filter((v): v is number => typeof v === "number" && v > 0);
3813
+ const outputValues = memberEntries
3814
+ .map((m) => m.max_output_tokens)
3815
+ .filter((v): v is number => typeof v === "number" && v > 0);
3816
+
3817
+ if (contextValues.length > 0 && outputValues.length > 0) {
3818
+ entry.limit = {
3819
+ context: Math.min(...contextValues),
3820
+ output: Math.min(...outputValues),
3821
+ };
3822
+ }
3823
+
3824
+ // LCD across modalities — combo accepts modality M iff every member
3825
+ // accepts M. Same intersection rule as runtime capabilities.
3826
+ const inSets = memberEntries.map((m) => new Set(normaliseModalities(m.input_modalities)));
3827
+ const outSets = memberEntries.map((m) => new Set(normaliseModalities(m.output_modalities)));
3828
+ const intersect = (sets: Set<OmniRouteModalityKind>[]): OmniRouteModalityKind[] => {
3829
+ if (sets.length === 0) return [];
3830
+ const [first, ...rest] = sets;
3831
+ const out: OmniRouteModalityKind[] = [];
3832
+ for (const v of first) {
3833
+ if (rest.every((s) => s.has(v))) out.push(v);
3834
+ }
3835
+ return out;
3836
+ };
3837
+ const inModalities = intersect(inSets);
3838
+ const outModalities = intersect(outSets);
3839
+ if (inModalities.length > 0 || outModalities.length > 0) {
3840
+ entry.modalities = {
3841
+ input: inModalities.length > 0 ? inModalities : ["text"],
3842
+ output: outModalities.length > 0 ? outModalities : ["text"],
3843
+ };
3844
+ }
3845
+ } else {
3846
+ // Empty members → safety posture: all caps false. Caller's OC picker
3847
+ // will grey out an unroutable combo rather than promise capabilities
3848
+ // we can't honour.
3849
+ entry.attachment = false;
3850
+ entry.reasoning = false;
3851
+ entry.temperature = false;
3852
+ entry.tool_call = false;
3853
+ }
3854
+
3855
+ // Key under bare slug (e.g. `claude-primary`) — no `combo/` prefix
3856
+ // because OpenCode parses model IDs on `/` and would treat
3857
+ // `combo/MASTER` as provider=`combo`. Slug collisions across
3858
+ // combos are disambiguated with a short UUID-prefix suffix; see
3859
+ // `buildComboKey` for the policy.
3860
+ models[buildComboKey(combo, usedComboKeys, opts.providerId)] = entry;
3861
+
3862
+ // Make this combo's resolved entry available to parent combos
3863
+ // that reference it via combo-ref. Use the friendly name since
3864
+ // that's the lookup key on the parent side.
3865
+ resolvedStaticCombosByName.set(friendlyName, entry);
3866
+ }
3867
+
3868
+ if (stillPendingStatic.length === pendingStatic.length) {
3869
+ // No progress in this pass — remaining combos have unresolvable
3870
+ // refs (missing nested combo, circular graph, or nested combo
3871
+ // with no members). Break early to avoid wasting the pass budget.
3872
+ break;
3873
+ }
3874
+ pendingStatic = stillPendingStatic;
3875
+ }
3876
+
3877
+ if (pendingStatic.length > 0) {
3878
+ console.warn(
3879
+ `[omniroute-plugin] ${pendingStatic.length} combo(s) in the static catalog could not resolve all nested combo-refs after ${MAX_STATIC_COMBO_PASSES} passes; they will be omitted.`
3880
+ );
3881
+ }
3882
+
3883
+ // ── Auto combos ────────────────────────────────────────────────────────
3884
+ // Virtual server-side combos (auto/coding, auto/fast, etc.) are fetched
3885
+ // from /api/combos/auto and added as model entries. They self-manage
3886
+ // provider selection at runtime via scoring/bandit exploration.
3887
+ if (rawAutoCombos && rawAutoCombos.length > 0) {
3888
+ for (const autoCombo of rawAutoCombos) {
3889
+ if (!autoCombo || !autoCombo.id) continue;
3890
+ if (autoCombo.isHidden === true) continue;
3891
+ const entry = mapAutoComboToStaticEntry(autoCombo);
3892
+ // Use the variant as the key: "auto", "auto/coding", etc.
3893
+ const key = autoComboModelId(autoCombo.variant);
3894
+ if (models[key]) {
3895
+ // Collision with a raw model or DB combo — auto combo wins (log once)
3896
+ if (!reportedCollisions.has(key)) {
3897
+ reportedCollisions.add(key);
3898
+ console.warn(
3899
+ `[omniroute-plugin] auto combo key "${key}" collides with an existing model; auto combo wins.`
3900
+ );
3901
+ }
3902
+ }
3903
+ models[key] = entry;
3904
+ }
3905
+ }
3906
+
3907
+ return {
3908
+ npm: "@ai-sdk/openai-compatible",
3909
+ name: opts.displayName,
3910
+ options: { baseURL, apiKey },
3911
+ models,
3912
+ };
3913
+ }
3914
+
3915
+ /**
3916
+ * Shape we expect inside `auth.json`. The file is keyed by providerId, with
3917
+ * each entry being a flavor-tagged credential. Today only the `api` flavor
3918
+ * is consumed by this plugin (OAuth + WellKnown flavors are passed through
3919
+ * but never decoded into a static block).
3920
+ */
3921
+ interface AuthJsonApiEntry {
3922
+ type: "api";
3923
+ key: string;
3924
+ baseURL?: string;
3925
+ }
3926
+
3927
+ type AuthJsonShape = Record<string, AuthJsonApiEntry | { type?: string; [k: string]: unknown }>;
3928
+
3929
+ /**
3930
+ * Read & parse `auth.json` from OC's data dir. The path resolution mirrors
3931
+ * OC core's:
3932
+ *
3933
+ * `${OPENCODE_DATA_DIR ?? path.join(os.homedir(), ".local/share/opencode")}/auth.json`
3934
+ *
3935
+ * Returns `undefined` when the file is missing (most-common case on a fresh
3936
+ * install — silent no-op). Returns `null` when the file exists but doesn't
3937
+ * parse as JSON (logs ONE warn so the operator sees the corruption).
3938
+ *
3939
+ * Exported as a dependency-injectable function on `createOmniRouteConfigHook`
3940
+ * so tests can stub it without monkey-patching `node:fs/promises`.
3941
+ */
3942
+ // ─────────────────────────────────────────────────────────────────────────
3943
+ // Disk-cache fallback. Persists the last successful raw-fetch snapshot to
3944
+ // `${OPENCODE_DATA_DIR ?? ~/.local/share/opencode}/plugins/omniroute-<providerId>.json`.
3945
+ // When `/v1/models` is unreachable (e.g. IP whitelist drop, offline laptop)
3946
+ // AND the in-memory cache is cold, the config hook reads from disk so the
3947
+ // last-known catalog still surfaces in OC's model picker. Feature-flagged:
3948
+ // `features.diskCache !== false` (default-on).
3949
+ // ─────────────────────────────────────────────────────────────────────────
3950
+
3951
+ /** Disk snapshot envelope. Versioned for forward-compat. */
3952
+ interface OmniRouteDiskSnapshot {
3953
+ v: 1;
3954
+ rawModels: OmniRouteRawModelEntry[];
3955
+ rawCombos: OmniRouteRawCombo[];
3956
+ rawAutoCombos?: OmniRouteRawAutoCombo[];
3957
+ /** Serialised as array-of-pairs (Map is not JSON-friendly). */
3958
+ rawEnrichment: Array<[string, OmniRouteEnrichmentEntry]>;
3959
+ rawCompressionCombos: OmniRouteCompressionCombo[];
3960
+ rawConnections: OmniRouteProviderConnection[];
3961
+ /** When the snapshot was written (epoch ms). */
3962
+ writtenAt: number;
3963
+ }
3964
+
3965
+ /** Resolve the disk-snapshot path for a given providerId. */
3966
+ export function diskSnapshotPath(providerId: string): string {
3967
+ const dir = process.env.OPENCODE_DATA_DIR ?? path.join(os.homedir(), ".local/share/opencode");
3968
+ return path.join(dir, "plugins", `omniroute-${providerId}.json`);
3969
+ }
3970
+
3971
+ export type OmniRouteDiskSnapshotWriter = (
3972
+ providerId: string,
3973
+ entry: Omit<OmniRouteFetchCacheEntry, "expiresAt">
3974
+ ) => Promise<void>;
3975
+
3976
+ export type OmniRouteDiskSnapshotReader = (
3977
+ providerId: string
3978
+ ) => Promise<Omit<OmniRouteFetchCacheEntry, "expiresAt"> | undefined>;
3979
+
3980
+ /** Best-effort disk write. Soft-fails on any I/O error (no exception thrown). */
3981
+ export const defaultDiskSnapshotWriter: OmniRouteDiskSnapshotWriter = async (providerId, entry) => {
3982
+ try {
3983
+ const file = diskSnapshotPath(providerId);
3984
+ // Restrict perms to the owner: the snapshot lives alongside auth.json
3985
+ // (0o600) and embeds provider topology + masked connection records.
3986
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
3987
+ const snapshot: OmniRouteDiskSnapshot = {
3988
+ v: 1,
3989
+ rawModels: entry.rawModels,
3990
+ rawCombos: entry.rawCombos,
3991
+ rawAutoCombos: entry.rawAutoCombos,
3992
+ rawEnrichment: Array.from(entry.rawEnrichment.entries()),
3993
+ rawCompressionCombos: entry.rawCompressionCombos,
3994
+ rawConnections: entry.rawConnections,
3995
+ writtenAt: Date.now(),
3996
+ };
3997
+ await writeFile(file, JSON.stringify(snapshot), {
3998
+ encoding: "utf8",
3999
+ mode: 0o600,
4000
+ });
4001
+ } catch {
4002
+ // Soft-fail; caller already has the in-memory cache.
4003
+ }
4004
+ };
4005
+
4006
+ /** Best-effort disk read. Returns `undefined` when missing/corrupt/unreadable. */
4007
+ export const defaultDiskSnapshotReader: OmniRouteDiskSnapshotReader = async (providerId) => {
4008
+ try {
4009
+ const file = diskSnapshotPath(providerId);
4010
+ const body = await readFile(file, "utf8");
4011
+ const parsed = JSON.parse(body) as Partial<OmniRouteDiskSnapshot>;
4012
+ if (!parsed || parsed.v !== 1) return undefined;
4013
+ return {
4014
+ rawModels: Array.isArray(parsed.rawModels) ? parsed.rawModels : [],
4015
+ rawCombos: Array.isArray(parsed.rawCombos) ? parsed.rawCombos : [],
4016
+ rawAutoCombos: Array.isArray(parsed.rawAutoCombos) ? parsed.rawAutoCombos : [],
4017
+ rawEnrichment: new Map(Array.isArray(parsed.rawEnrichment) ? parsed.rawEnrichment : []),
4018
+ rawCompressionCombos: Array.isArray(parsed.rawCompressionCombos)
4019
+ ? parsed.rawCompressionCombos
4020
+ : [],
4021
+ rawConnections: Array.isArray(parsed.rawConnections) ? parsed.rawConnections : [],
4022
+ };
4023
+ } catch {
4024
+ return undefined;
4025
+ }
4026
+ };
4027
+
4028
+ /** No-op disk-cache pair — used by tests to avoid filesystem side effects. */
4029
+ export const noopDiskSnapshotWriter: OmniRouteDiskSnapshotWriter = async () => {};
4030
+
4031
+ // ────────────────────────────────────────────────────────────────────────────
4032
+ // Debug logging (features.debugLog)
4033
+ // ────────────────────────────────────────────────────────────────────────────
4034
+
4035
+ /**
4036
+ * One captured request/response pair written to the debug JSONL log.
4037
+ * Schema documented in the schema-aware `DebugLogEntry` interface below.
4038
+ */
4039
+ export interface DebugLogEntry {
4040
+ reqId: string;
4041
+ providerId: string;
4042
+ ts: number;
4043
+ url: string;
4044
+ method: string;
4045
+ reqHeaders: Record<string, string>;
4046
+ reqBody: unknown;
4047
+ resStatus: number | null;
4048
+ resHeaders: Record<string, string>;
4049
+ resBody: unknown;
4050
+ durationMs: number | null;
4051
+ error?: string;
4052
+ }
4053
+
4054
+ function debugLogDir(): string {
4055
+ return join(
4056
+ process.env.OPENCODE_DATA_DIR ?? join(homedir(), ".local", "share", "opencode"),
4057
+ "plugins"
4058
+ );
4059
+ }
4060
+
4061
+ function debugLogPath(providerId: string): string {
4062
+ return join(debugLogDir(), `omniroute-debug-${providerId}.jsonl`);
4063
+ }
4064
+
4065
+ function debugStatePath(providerId: string): string {
4066
+ return join(debugLogDir(), `omniroute-debug-${providerId}.state.json`);
4067
+ }
4068
+
4069
+ export function debugLogEnabled(providerId: string): boolean {
4070
+ try {
4071
+ const p = debugStatePath(providerId);
4072
+ if (!existsSync(p)) return false;
4073
+ const s = JSON.parse(readFileSync(p, "utf8")) as { enabled?: boolean };
4074
+ return s.enabled === true;
4075
+ } catch {
4076
+ return false;
4077
+ }
4078
+ }
4079
+
4080
+ export function debugLogSetEnabled(providerId: string, enabled: boolean): void {
4081
+ try {
4082
+ const dir = debugLogDir();
4083
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
4084
+ writeFileSync(debugStatePath(providerId), JSON.stringify({ enabled, ts: Date.now() }, null, 2));
4085
+ } catch (err) {
4086
+ // best-effort; never break the auth flow
4087
+ console.warn(`[omniroute-plugin] debugLogSetEnabled failed: ${(err as Error).message}`);
4088
+ }
4089
+ }
4090
+
4091
+ export function debugLogAppend(entry: DebugLogEntry): void {
4092
+ try {
4093
+ const dir = debugLogDir();
4094
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
4095
+ appendFileSync(debugLogPath(entry.providerId), JSON.stringify(entry) + "\n", "utf8");
4096
+ } catch (err) {
4097
+ console.warn(`[omniroute-plugin] debugLogAppend failed: ${(err as Error).message}`);
4098
+ }
4099
+ }
4100
+
4101
+ export function debugLogRead(providerId: string, limit = 20): DebugLogEntry[] {
4102
+ try {
4103
+ const p = debugLogPath(providerId);
4104
+ if (!existsSync(p)) return [];
4105
+ const lines = readFileSync(p, "utf8").trim().split("\n").filter(Boolean);
4106
+ return lines
4107
+ .slice(-limit)
4108
+ .map((line) => {
4109
+ try {
4110
+ return JSON.parse(line) as DebugLogEntry;
4111
+ } catch {
4112
+ return null;
4113
+ }
4114
+ })
4115
+ .filter((e): e is DebugLogEntry => e !== null);
4116
+ } catch {
4117
+ return [];
4118
+ }
4119
+ }
4120
+
4121
+ export function debugLogGetById(providerId: string, reqId: string): DebugLogEntry | null {
4122
+ try {
4123
+ const p = debugLogPath(providerId);
4124
+ if (!existsSync(p)) return null;
4125
+ const lines = readFileSync(p, "utf8").trim().split("\n").filter(Boolean);
4126
+ for (let i = lines.length - 1; i >= 0; i--) {
4127
+ try {
4128
+ const e = JSON.parse(lines[i]) as DebugLogEntry;
4129
+ if (e.reqId === reqId) return e;
4130
+ } catch {
4131
+ // skip malformed
4132
+ }
4133
+ }
4134
+ return null;
4135
+ } catch {
4136
+ return null;
4137
+ }
4138
+ }
4139
+
4140
+ export function debugLogClear(providerId: string): void {
4141
+ try {
4142
+ const p = debugLogPath(providerId);
4143
+ if (existsSync(p)) writeFileSync(p, "", "utf8");
4144
+ } catch (err) {
4145
+ console.warn(`[omniroute-plugin] debugLogClear failed: ${(err as Error).message}`);
4146
+ }
4147
+ }
4148
+
4149
+ /**
4150
+ * Wrap a fetch function to capture request/response pairs into the debug
4151
+ * JSONL log. Honours the `featureDefault` opt-in flag and the on-disk
4152
+ * runtime toggle (`debugLogEnabled`).
4153
+ */
4154
+ export function createDebugLoggingFetch(
4155
+ inner: typeof fetch,
4156
+ providerId: string,
4157
+ featureDefault: boolean
4158
+ ): typeof fetch {
4159
+ return async (input, init) => {
4160
+ const active = featureDefault || debugLogEnabled(providerId);
4161
+ if (!active) return inner(input, init);
4162
+ const reqId = randomUUID();
4163
+ const url =
4164
+ typeof input === "string"
4165
+ ? input
4166
+ : input instanceof URL
4167
+ ? input.toString()
4168
+ : input instanceof Request
4169
+ ? input.url
4170
+ : String(input);
4171
+ const method = (
4172
+ init?.method ?? (typeof input === "string" ? "GET" : ((input as Request).method ?? "GET"))
4173
+ ).toUpperCase();
4174
+ const reqHeaders: Record<string, string> = {};
4175
+ if (input instanceof Request) {
4176
+ input.headers.forEach((v, k) => (reqHeaders[k] = v));
4177
+ }
4178
+ if (init?.headers) {
4179
+ const h = init.headers;
4180
+ if (h instanceof Headers) h.forEach((v, k) => (reqHeaders[k] = v));
4181
+ else if (Array.isArray(h)) for (const [k, v] of h) reqHeaders[k] = v;
4182
+ else Object.assign(reqHeaders, h);
4183
+ }
4184
+ let reqBody: unknown = undefined;
4185
+ if (init?.body) {
4186
+ if (typeof init.body === "string") {
4187
+ try {
4188
+ reqBody = JSON.parse(init.body);
4189
+ } catch {
4190
+ reqBody = init.body.slice(0, 4096);
4191
+ }
4192
+ } else {
4193
+ reqBody = "[non-string body]";
4194
+ }
4195
+ } else if (input instanceof Request) {
4196
+ try {
4197
+ const clonedReq = input.clone();
4198
+ const text = await clonedReq.text();
4199
+ try {
4200
+ reqBody = JSON.parse(text);
4201
+ } catch {
4202
+ reqBody = text.slice(0, 4096);
4203
+ }
4204
+ } catch {
4205
+ reqBody = "[body unreadable]";
4206
+ }
4207
+ }
4208
+ const t0 = Date.now();
4209
+ try {
4210
+ const res = await inner(input, init);
4211
+ const durationMs = Date.now() - t0;
4212
+ const resHeaders: Record<string, string> = {};
4213
+ res.headers.forEach((v, k) => (resHeaders[k] = v));
4214
+ let resBody: unknown = undefined;
4215
+ try {
4216
+ const clone = res.clone();
4217
+ const ct = clone.headers.get("content-type") ?? "";
4218
+ if (ct.includes("application/json")) {
4219
+ resBody = await clone.json();
4220
+ } else if (ct.includes("text/event-stream")) {
4221
+ resBody = "[stream]";
4222
+ } else if (ct.includes("text/")) {
4223
+ const txt = await clone.text();
4224
+ resBody = txt.length > 4096 ? txt.slice(0, 4096) + "...[truncated]" : txt;
4225
+ } else {
4226
+ resBody = `[${ct || "unknown"} body, status ${res.status}]`;
4227
+ }
4228
+ } catch {
4229
+ resBody = "[body unparseable]";
4230
+ }
4231
+ debugLogAppend({
4232
+ reqId,
4233
+ providerId,
4234
+ ts: t0,
4235
+ url,
4236
+ method,
4237
+ reqHeaders,
4238
+ reqBody,
4239
+ resStatus: res.status,
4240
+ resHeaders,
4241
+ resBody,
4242
+ durationMs,
4243
+ });
4244
+ return res;
4245
+ } catch (err) {
4246
+ const durationMs = Date.now() - t0;
4247
+ debugLogAppend({
4248
+ reqId,
4249
+ providerId,
4250
+ ts: t0,
4251
+ url,
4252
+ method,
4253
+ reqHeaders,
4254
+ reqBody,
4255
+ resStatus: null,
4256
+ resHeaders: {},
4257
+ resBody: undefined,
4258
+ durationMs,
4259
+ error: (err as Error).message,
4260
+ });
4261
+ throw err;
4262
+ }
4263
+ };
4264
+ }
4265
+ export const noopDiskSnapshotReader: OmniRouteDiskSnapshotReader = async () => undefined;
4266
+
4267
+ export type OmniRouteReadAuthJson = () => Promise<AuthJsonShape | undefined | null>;
4268
+
4269
+ export const defaultReadAuthJson: OmniRouteReadAuthJson = async () => {
4270
+ const dir = process.env.OPENCODE_DATA_DIR ?? path.join(os.homedir(), ".local/share/opencode");
4271
+ const file = path.join(dir, "auth.json");
4272
+ let body: string;
4273
+ try {
4274
+ body = await readFile(file, "utf8");
4275
+ } catch {
4276
+ // File missing or unreadable — silent no-op. This is the expected path
4277
+ // on a fresh install BEFORE `/connect` has been run.
4278
+ return undefined;
4279
+ }
4280
+ try {
4281
+ const parsed = JSON.parse(body) as unknown;
4282
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
4283
+ return parsed as AuthJsonShape;
4284
+ }
4285
+ return null;
4286
+ } catch {
4287
+ return null;
4288
+ }
4289
+ };
4290
+
4291
+ /**
4292
+ * Build the config-hook portion of the plugin for a given options bag.
4293
+ * Exported standalone so the contract is unit-testable without faking the
4294
+ * full PluginInput / Hooks surface, and so multi-instance setups can each
4295
+ * own their own (auth.json reader, fetch cache, fetcher) trio.
4296
+ *
4297
+ * Behavioural contract:
4298
+ * - Runs BEFORE `auth.loader` in the OC startup sequence (per the
4299
+ * @opencode-ai/plugin contract). `getAuth()` is NOT available here,
4300
+ * so we read `auth.json` directly via the injected reader.
4301
+ * - No-op when:
4302
+ * (a) `auth.json` is missing / unreadable (fresh install before
4303
+ * `/connect`),
4304
+ * (b) `auth.json[providerId]` is missing or not type-api,
4305
+ * (c) `apiKey` is empty after extraction,
4306
+ * (d) `baseURL` is unresolvable (neither opts.baseURL nor
4307
+ * `auth.json[providerId].baseURL`),
4308
+ * (e) `input.provider[providerId]` is ALREADY set (operator override
4309
+ * wins — we never clobber manually-curated catalogs).
4310
+ * Each no-op path emits ONE debug-level breadcrumb to `console.warn`
4311
+ * so the operator can diagnose without log spam. Malformed `auth.json`
4312
+ * warns once and continues as if the file were missing.
4313
+ * - Fail-open on fetcher errors: a `/v1/models` failure → still publish
4314
+ * a stub `{models: {}}` provider block (so OC has a complete-shape
4315
+ * entry to render). A `/api/combos` failure → publish models-only.
4316
+ * Both paths emit ONE `console.warn`.
4317
+ * - When the provider hook (T-03/T-05) has ALREADY populated the shared
4318
+ * cache for this (baseURL, apiKey) tuple, we reuse the raw payloads
4319
+ * directly — no second fetch. (And vice-versa: the config hook fires
4320
+ * first on OC ≥1.14.49 cold start, populating the cache for the
4321
+ * provider hook moments later.)
4322
+ * - DUAL-PUBLISH SAFE: on OC ≥1.14.49 BOTH this static block and the
4323
+ * dynamic `provider.models()` result will land in OC's catalog
4324
+ * reducer. The dynamic block wins by OC's own merge rule — see
4325
+ * OpenCode core's provider resolution order — so emitting both is a
4326
+ * correctness-positive: ≤1.14.48 reads static, ≥1.14.49 prefers
4327
+ * dynamic but the static one keeps things responsive during the
4328
+ * ~50ms window before the dynamic fetch resolves.
4329
+ *
4330
+ * @param opts Plugin options (validated, resolved with defaults).
4331
+ * @param deps Dependency injection.
4332
+ * - `readAuthJson` — replaces `defaultReadAuthJson` (test stub).
4333
+ * - `fetcher` — replaces `defaultOmniRouteModelsFetcher`.
4334
+ * - `combosFetcher` — replaces `defaultOmniRouteCombosFetcher`.
4335
+ * - `now` — clock for cache TTL (default `Date.now`).
4336
+ * - `cache` — shared fetch-result cache (see
4337
+ * `OmniRouteFetchCache`). Pass the same Map the
4338
+ * provider hook owns to dedupe round-trips.
4339
+ * - `logger` — `{warn}` sink for breadcrumb capture in tests.
4340
+ * Defaults to `console`.
4341
+ */
4342
+ export function createOmniRouteConfigHook(
4343
+ opts?: OmniRoutePluginOptions,
4344
+ deps: {
4345
+ readAuthJson?: OmniRouteReadAuthJson;
4346
+ fetcher?: OmniRouteModelsFetcher;
4347
+ combosFetcher?: OmniRouteCombosFetcher;
4348
+ autoCombosFetcher?: OmniRouteAutoCombosFetcher;
4349
+ enrichmentFetcher?: OmniRouteEnrichmentFetcher;
4350
+ compressionMetaFetcher?: OmniRouteCompressionMetaFetcher;
4351
+ providersFetcher?: OmniRouteProvidersFetcher;
4352
+ diskSnapshotReader?: OmniRouteDiskSnapshotReader;
4353
+ diskSnapshotWriter?: OmniRouteDiskSnapshotWriter;
4354
+ now?: () => number;
4355
+ cache?: OmniRouteFetchCache;
4356
+ logger?: { warn: (...args: unknown[]) => void };
4357
+ } = {}
4358
+ ): (input: Config) => Promise<void> {
4359
+ const resolved = resolveOmniRoutePluginOptions(opts);
4360
+ const readAuthJson = deps.readAuthJson ?? defaultReadAuthJson;
4361
+ const fetcher = deps.fetcher ?? defaultOmniRouteModelsFetcher;
4362
+ const combosFetcher = deps.combosFetcher ?? defaultOmniRouteCombosFetcher;
4363
+ const autoCombosFetcher = deps.autoCombosFetcher ?? defaultOmniRouteAutoCombosFetcher;
4364
+ const enrichmentFetcher = deps.enrichmentFetcher ?? defaultOmniRouteEnrichmentFetcher;
4365
+ const compressionMetaFetcher =
4366
+ deps.compressionMetaFetcher ?? defaultOmniRouteCompressionMetaFetcher;
4367
+ const providersFetcher = deps.providersFetcher ?? defaultOmniRouteProvidersFetcher;
4368
+ const diskSnapshotReader = deps.diskSnapshotReader ?? defaultDiskSnapshotReader;
4369
+ const diskSnapshotWriter = deps.diskSnapshotWriter ?? defaultDiskSnapshotWriter;
4370
+ const now = deps.now ?? Date.now;
4371
+ const cache: OmniRouteFetchCache = deps.cache ?? new Map();
4372
+ const logger = deps.logger ?? console;
4373
+ const features = resolved.features ?? {};
4374
+ const wantAutoCombos = features.autoCombos !== false;
4375
+ const wantEnrichment = features.enrichment !== false;
4376
+ const wantCompressionMeta = features.compressionMetadata === true;
4377
+ const wantUsableOnly = features.usableOnly === true;
4378
+ const wantDiskCache = features.diskCache !== false;
4379
+ const wantProviderTag = features.providerTag !== false;
4380
+
4381
+ return async (input: Config) => {
4382
+ // (e) operator override — `input.provider[providerId]` already set →
4383
+ // leave it alone. Manually curated catalogs ALWAYS win over the plugin's
4384
+ // generated block. Detect-and-respect before any I/O.
4385
+ const existingProviders = (input as { provider?: Record<string, unknown> }).provider;
4386
+ if (existingProviders && existingProviders[resolved.providerId] !== undefined) {
4387
+ logger.warn(
4388
+ `[omniroute-plugin] config shim skipped: provider.${resolved.providerId} already set by user`
4389
+ );
4390
+ return;
4391
+ }
4392
+
4393
+ // Read auth.json. `undefined` = missing file (silent path), `null` =
4394
+ // malformed JSON (warn once and treat as missing).
4395
+ let authJson: AuthJsonShape | undefined | null;
4396
+ try {
4397
+ authJson = await readAuthJson();
4398
+ } catch {
4399
+ // Reader threw — be conservative and treat like a missing file.
4400
+ authJson = undefined;
4401
+ }
4402
+
4403
+ if (authJson === null) {
4404
+ logger.warn("[omniroute-plugin] config shim: auth.json failed to parse; treating as missing");
4405
+ authJson = undefined;
4406
+ }
4407
+
4408
+ // Try both prefixed (e.g. opencode-omniroute) and unprefixed (e.g. omniroute)
4409
+ // keys so a user who ran `/connect omniroute` before the auto-prefix fix
4410
+ // does not need to re-auth. Also handles dual-key for auth.json entries
4411
+ // written by a newer OC dispatcher with the prefixed key.
4412
+ const bareKey = resolved.providerId.startsWith("opencode-")
4413
+ ? resolved.providerId.slice("opencode-".length)
4414
+ : resolved.providerId;
4415
+ const lookupKeys = [resolved.providerId];
4416
+ if (bareKey !== resolved.providerId) lookupKeys.push(bareKey);
4417
+ let entry;
4418
+ for (const k of lookupKeys) {
4419
+ const e = authJson?.[k];
4420
+ if (e?.type === "api" && typeof e.key === "string" && e.key.length > 0) {
4421
+ entry = e;
4422
+ break;
4423
+ }
4424
+ }
4425
+ const apiKey = entry?.type === "api" && typeof entry.key === "string" ? entry.key : "";
4426
+
4427
+ if (!apiKey) {
4428
+ // (c) no apiKey — silent no-op (with debug breadcrumb). The operator
4429
+ // hasn't run `/connect <providerId>` yet, OR the stored credential
4430
+ // isn't api-flavored. OC will handle the `/connect` flow at runtime.
4431
+ logger.warn(
4432
+ `[omniroute-plugin] config shim skipped: no apiKey for providerId=${resolved.providerId}`
4433
+ );
4434
+ return;
4435
+ }
4436
+
4437
+ // baseURL resolution: opts.baseURL wins, then auth.json's stored baseURL.
4438
+ // No silent localhost default — a misconfigured plugin should surface a
4439
+ // breadcrumb and skip, not phantom requests.
4440
+ const storedBaseURL = entry && typeof entry.baseURL === "string" ? entry.baseURL : undefined;
4441
+ const baseURL = resolved.baseURL ?? storedBaseURL ?? "";
4442
+ if (!baseURL) {
4443
+ logger.warn(
4444
+ `[omniroute-plugin] config shim skipped: no baseURL for providerId=${resolved.providerId}`
4445
+ );
4446
+ return;
4447
+ }
4448
+
4449
+ // Try the shared cache first. On OC ≥1.14.49 the provider hook may have
4450
+ // populated it moments earlier; on OC ≤1.14.48 only this hook runs but
4451
+ // the cache still works (single producer + consumer through one Map).
4452
+ const cacheKey = modelsCacheKey(baseURL, apiKey);
4453
+ const t = now();
4454
+ const cached = cache.get(cacheKey);
4455
+
4456
+ let rawModels: OmniRouteRawModelEntry[];
4457
+ let rawCombos: OmniRouteRawCombo[];
4458
+ let rawAutoCombos: OmniRouteRawAutoCombo[];
4459
+ let rawEnrichment: OmniRouteEnrichmentMap;
4460
+ let rawCompressionCombos: OmniRouteCompressionCombo[];
4461
+ let rawConnections: OmniRouteProviderConnection[];
4462
+
4463
+ if (cached && cached.expiresAt > t) {
4464
+ rawModels = cached.rawModels;
4465
+ rawCombos = cached.rawCombos;
4466
+ rawAutoCombos = cached.rawAutoCombos;
4467
+ rawEnrichment = cached.rawEnrichment;
4468
+ rawCompressionCombos = cached.rawCompressionCombos;
4469
+ rawConnections = cached.rawConnections;
4470
+ } else {
4471
+ // Fail-open fetcher errors: on /v1/models throw, fall back to empty
4472
+ // catalog (still publish a stub block so OC has a complete-shape
4473
+ // entry); on /api/combos throw, publish models-only. Disk-cache
4474
+ // fallback below recovers the last-known-good catalog when the
4475
+ // fetcher threw (network down / 403 / timeout) AND features.diskCache
4476
+ // !== false. A 0-entry SUCCESS (fresh tenant) does NOT trigger
4477
+ // disk fallback — that's a valid empty catalog.
4478
+ let modelsFetchThrew = false;
4479
+ try {
4480
+ rawModels = await fetcher(baseURL, apiKey, 10_000);
4481
+ } catch (err) {
4482
+ logger.warn(
4483
+ "[omniroute-plugin] config shim: /v1/models fetch failed; publishing stub provider entry",
4484
+ err
4485
+ );
4486
+ rawModels = [];
4487
+ modelsFetchThrew = true;
4488
+ }
4489
+ const modelsFetchOk = !modelsFetchThrew && rawModels.length > 0;
4490
+
4491
+ rawCombos = [];
4492
+ try {
4493
+ rawCombos = await combosFetcher(baseURL, apiKey, 10_000);
4494
+ } catch (err) {
4495
+ logger.warn(
4496
+ "[omniroute-plugin] config shim: /api/combos fetch failed; publishing models-only static catalog",
4497
+ err
4498
+ );
4499
+ }
4500
+
4501
+ rawAutoCombos = [];
4502
+ if (wantAutoCombos) {
4503
+ try {
4504
+ rawAutoCombos = await autoCombosFetcher(baseURL, apiKey, 5_000);
4505
+ } catch {
4506
+ // Already handled inside the default fetcher
4507
+ }
4508
+ }
4509
+
4510
+ // Eagerly fetch enrichment so the static block can overlay human
4511
+ // display names on raw model ids. On OC ≤1.15.5 the dynamic
4512
+ // `provider.models` hook never fires in `serve` mode, so the static
4513
+ // block IS what reaches `/provider` and the TUI model picker.
4514
+ // Gated by `features.enrichment` (default-on). Soft-fail on error —
4515
+ // we still publish a name-less catalog if /api/pricing/models is
4516
+ // unreachable.
4517
+ rawEnrichment = new Map();
4518
+ if (wantEnrichment) {
4519
+ try {
4520
+ rawEnrichment = await enrichmentFetcher(baseURL, apiKey, 10_000);
4521
+ } catch (err) {
4522
+ logger.warn(
4523
+ "[omniroute-plugin] config shim: /api/pricing/models fetch failed; publishing raw-id static catalog",
4524
+ err
4525
+ );
4526
+ }
4527
+ }
4528
+
4529
+ // Compression-metadata fetch — opt-in via features.compressionMetadata.
4530
+ // When on, the default pipeline is appended to every combo `name` so
4531
+ // the TUI picker advertises which compression a combo applies.
4532
+ rawCompressionCombos = [];
4533
+ if (wantCompressionMeta) {
4534
+ try {
4535
+ rawCompressionCombos = await compressionMetaFetcher(baseURL, apiKey, 10_000);
4536
+ } catch (err) {
4537
+ logger.warn(
4538
+ "[omniroute-plugin] config shim: /api/context/combos fetch failed; publishing combos without compression suffix",
4539
+ err
4540
+ );
4541
+ }
4542
+ }
4543
+
4544
+ // Provider-connections fetch — opt-in via features.usableOnly. When
4545
+ // on, the static catalog filters out models/combos whose canonical
4546
+ // provider has no active connection. Soft-fail (empty list) disables
4547
+ // the filter for this refresh, never hiding the whole catalog.
4548
+ rawConnections = [];
4549
+ if (wantUsableOnly) {
4550
+ try {
4551
+ rawConnections = await providersFetcher(baseURL, apiKey, 10_000);
4552
+ } catch (err) {
4553
+ logger.warn(
4554
+ "[omniroute-plugin] config shim: /api/providers fetch failed; usableOnly filter disabled for this refresh",
4555
+ err
4556
+ );
4557
+ }
4558
+ }
4559
+
4560
+ // Disk-cache fallback: when the live fetch returned no models AND
4561
+ // features.diskCache !== false, hydrate from the last-known-good
4562
+ // snapshot so OC still surfaces a usable catalog (e.g. IP whitelist
4563
+ // drop, offline laptop). The snapshot is whatever we last wrote on
4564
+ // a healthy refresh; staleness is bounded only by how recently the
4565
+ // user was online.
4566
+ if (modelsFetchThrew && wantDiskCache) {
4567
+ const snapshot = await diskSnapshotReader(resolved.providerId);
4568
+ if (snapshot && snapshot.rawModels.length > 0) {
4569
+ logger.warn(
4570
+ `[omniroute-plugin] config shim: /v1/models unreachable; using stale disk cache (${snapshot.rawModels.length} models)`
4571
+ );
4572
+ rawModels = snapshot.rawModels;
4573
+ rawCombos = snapshot.rawCombos;
4574
+ rawAutoCombos = snapshot.rawAutoCombos ?? [];
4575
+ rawEnrichment = snapshot.rawEnrichment;
4576
+ rawCompressionCombos = snapshot.rawCompressionCombos;
4577
+ rawConnections = snapshot.rawConnections;
4578
+ }
4579
+ }
4580
+
4581
+ // Cache even partial results — a subsequent provider-hook call should
4582
+ // not re-burn the timeout window on the same broken endpoint.
4583
+ cache.set(cacheKey, {
4584
+ rawModels,
4585
+ rawCombos,
4586
+ rawAutoCombos,
4587
+ rawEnrichment,
4588
+ rawCompressionCombos,
4589
+ rawConnections,
4590
+ expiresAt: t + resolved.modelCacheTtl,
4591
+ });
4592
+
4593
+ // Startup diagnostics (file-based) — fires at startup via config hook
4594
+ if (resolved.features?.startupDebug === true) {
4595
+ await writeStartupDiagnostics({
4596
+ providerId: resolved.providerId,
4597
+ baseURL,
4598
+ modelCount: rawModels.length,
4599
+ comboCount: rawCombos.length,
4600
+ enrichmentSize: rawEnrichment.size,
4601
+ autoComboCount: rawAutoCombos.length,
4602
+ enrichment: rawEnrichment,
4603
+ autoCombos: rawAutoCombos,
4604
+ });
4605
+ }
4606
+
4607
+ // Disk-cache write: persist the last successful (or any non-empty)
4608
+ // catalog so a subsequent cold start with a failed fetch can recover.
4609
+ // Best-effort; soft-fail keeps us moving when the data dir isn't
4610
+ // writable (e.g. read-only container).
4611
+ if (modelsFetchOk && wantDiskCache) {
4612
+ await diskSnapshotWriter(resolved.providerId, {
4613
+ rawModels,
4614
+ rawCombos,
4615
+ rawAutoCombos,
4616
+ rawEnrichment,
4617
+ rawCompressionCombos,
4618
+ rawConnections,
4619
+ });
4620
+ }
4621
+ }
4622
+
4623
+ const block = buildStaticProviderEntry(
4624
+ rawModels,
4625
+ rawCombos,
4626
+ resolved,
4627
+ baseURL,
4628
+ apiKey,
4629
+ rawEnrichment,
4630
+ rawCompressionCombos,
4631
+ rawConnections,
4632
+ rawAutoCombos
4633
+ );
4634
+
4635
+ // Mutate the input.provider map. The Config type declares
4636
+ // `provider?: {[key: string]: ProviderConfig}` — we initialise the
4637
+ // bag when absent so users who never set `provider` in opencode.json
4638
+ // still get the static block.
4639
+ const inputWithProvider = input as { provider?: Record<string, unknown> };
4640
+ if (!inputWithProvider.provider) {
4641
+ inputWithProvider.provider = {};
4642
+ }
4643
+ inputWithProvider.provider[resolved.providerId] = block;
4644
+
4645
+ // ─────────────────────────────────────────────────────────────────────
4646
+ // MCP auto-emit — opt-in via features.mcpAutoEmit. When enabled, writes
4647
+ // an `input.mcp[<providerId>]` remote entry pointing at
4648
+ // `<baseURL>/api/mcp/stream` with the resolved Bearer token. Token
4649
+ // resolution: features.mcpToken wins if set; otherwise falls back to
4650
+ // the same apiKey used for chat. Operator overrides win (same posture
4651
+ // as provider-block emit): if input.mcp[providerId] is already set,
4652
+ // we leave it alone.
4653
+ // ─────────────────────────────────────────────────────────────────────
4654
+ if (features.mcpAutoEmit === true) {
4655
+ const mcpKey = features.mcpToken ?? apiKey;
4656
+ if (!mcpKey) {
4657
+ logger.warn(
4658
+ `[omniroute-plugin] mcp auto-emit skipped: no Bearer token for providerId=${resolved.providerId}`
4659
+ );
4660
+ } else {
4661
+ const inputWithMcp = input as { mcp?: Record<string, unknown> };
4662
+ if (!inputWithMcp.mcp) {
4663
+ inputWithMcp.mcp = {};
4664
+ }
4665
+ if (inputWithMcp.mcp[resolved.providerId] !== undefined) {
4666
+ logger.warn(
4667
+ `[omniroute-plugin] mcp auto-emit skipped: mcp.${resolved.providerId} already set by user`
4668
+ );
4669
+ } else {
4670
+ // Strip a trailing `/v1` from baseURL when present so we land on
4671
+ // the MCP transport at /api/mcp/stream, not /v1/api/mcp/stream.
4672
+ const mcpRoot = baseURL.replace(/\/v1\/?$/, "").replace(/\/$/, "");
4673
+ inputWithMcp.mcp[resolved.providerId] = {
4674
+ type: "remote",
4675
+ url: `${mcpRoot}/api/mcp/stream`,
4676
+ enabled: true,
4677
+ headers: {
4678
+ Authorization: `Bearer ${mcpKey}`,
4679
+ },
4680
+ };
4681
+ }
4682
+ }
4683
+ }
4684
+ };
4685
+ }