mervexai 0.0.97

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 (782) hide show
  1. package/AGENTS.md +131 -0
  2. package/Dockerfile +18 -0
  3. package/README.md +15 -0
  4. package/bin/mervex +222 -0
  5. package/bunfig.toml +7 -0
  6. package/git +0 -0
  7. package/migration/20260511173437_session-metadata/migration.sql +1 -0
  8. package/migration/20260511173437_session-metadata/snapshot.json +1500 -0
  9. package/package.json +159 -0
  10. package/parsers-config.ts +1 -0
  11. package/script/bench-search.ts +94 -0
  12. package/script/bench-test-suite.ts +52 -0
  13. package/script/build.ts +257 -0
  14. package/script/generate.ts +14 -0
  15. package/script/httpapi-exercise.ts +1 -0
  16. package/script/postinstall.mjs +185 -0
  17. package/script/profile-test-files.ts +42 -0
  18. package/script/publish.ts +213 -0
  19. package/script/run-workspace-server +106 -0
  20. package/script/schema.ts +77 -0
  21. package/script/time.ts +6 -0
  22. package/script/trace-imports.ts +153 -0
  23. package/specs/effect/error-boundaries-plan.md +235 -0
  24. package/specs/effect/errors.md +207 -0
  25. package/specs/effect/facades.md +218 -0
  26. package/specs/effect/guide.md +247 -0
  27. package/specs/effect/instance-context.md +13 -0
  28. package/specs/effect/loose-ends.md +30 -0
  29. package/specs/effect/migration.md +62 -0
  30. package/specs/effect/routes.md +61 -0
  31. package/specs/effect/schema.md +88 -0
  32. package/specs/effect/server-package.md +58 -0
  33. package/specs/effect/todo.md +241 -0
  34. package/specs/effect/tools.md +88 -0
  35. package/specs/openapi-translation-cleanup.md +204 -0
  36. package/specs/tui-plugins.md +544 -0
  37. package/specs/v2/api.ts +67 -0
  38. package/specs/v2/message-shape.md +136 -0
  39. package/specs/v2/notifications.md +13 -0
  40. package/specs/v2/tui-command-shim.md +67 -0
  41. package/src/account/account.ts +481 -0
  42. package/src/account/repo.ts +171 -0
  43. package/src/account/schema.ts +99 -0
  44. package/src/account/url.ts +8 -0
  45. package/src/acp/agent.ts +95 -0
  46. package/src/acp/config-option.ts +203 -0
  47. package/src/acp/content.ts +269 -0
  48. package/src/acp/directory.ts +212 -0
  49. package/src/acp/error.ts +97 -0
  50. package/src/acp/event.ts +421 -0
  51. package/src/acp/permission.ts +254 -0
  52. package/src/acp/profile.ts +42 -0
  53. package/src/acp/service.ts +1105 -0
  54. package/src/acp/session.ts +232 -0
  55. package/src/acp/tool.ts +364 -0
  56. package/src/acp/usage.ts +243 -0
  57. package/src/agent/agent.ts +508 -0
  58. package/src/agent/generate.txt +75 -0
  59. package/src/agent/prompt/architect.txt +7 -0
  60. package/src/agent/prompt/ask.txt +7 -0
  61. package/src/agent/prompt/compaction.txt +5 -0
  62. package/src/agent/prompt/explore.txt +18 -0
  63. package/src/agent/prompt/summary.txt +11 -0
  64. package/src/agent/prompt/title.txt +44 -0
  65. package/src/agent/subagent-permissions.ts +27 -0
  66. package/src/audio.d.ts +14 -0
  67. package/src/auth/index.ts +97 -0
  68. package/src/background/job.ts +37 -0
  69. package/src/bus/global.ts +22 -0
  70. package/src/cli/bootstrap.ts +11 -0
  71. package/src/cli/cmd/account.ts +264 -0
  72. package/src/cli/cmd/acp.ts +73 -0
  73. package/src/cli/cmd/agent.ts +259 -0
  74. package/src/cli/cmd/attach.ts +148 -0
  75. package/src/cli/cmd/cmd.ts +7 -0
  76. package/src/cli/cmd/db.ts +62 -0
  77. package/src/cli/cmd/debug/agent.handler.ts +193 -0
  78. package/src/cli/cmd/debug/agent.ts +27 -0
  79. package/src/cli/cmd/debug/config.ts +14 -0
  80. package/src/cli/cmd/debug/file.ts +73 -0
  81. package/src/cli/cmd/debug/index.ts +87 -0
  82. package/src/cli/cmd/debug/lsp.ts +50 -0
  83. package/src/cli/cmd/debug/ripgrep.ts +79 -0
  84. package/src/cli/cmd/debug/scrap.ts +16 -0
  85. package/src/cli/cmd/debug/skill.ts +15 -0
  86. package/src/cli/cmd/debug/snapshot.ts +50 -0
  87. package/src/cli/cmd/debug/startup.ts +11 -0
  88. package/src/cli/cmd/debug/v2.ts +42 -0
  89. package/src/cli/cmd/export.ts +292 -0
  90. package/src/cli/cmd/generate.ts +54 -0
  91. package/src/cli/cmd/github.handler.ts +1606 -0
  92. package/src/cli/cmd/github.shared.ts +30 -0
  93. package/src/cli/cmd/github.ts +42 -0
  94. package/src/cli/cmd/import.ts +230 -0
  95. package/src/cli/cmd/mcp.ts +840 -0
  96. package/src/cli/cmd/models.ts +66 -0
  97. package/src/cli/cmd/plug.ts +230 -0
  98. package/src/cli/cmd/pr.ts +115 -0
  99. package/src/cli/cmd/prompt-display.ts +1 -0
  100. package/src/cli/cmd/providers.ts +594 -0
  101. package/src/cli/cmd/repair.ts +231 -0
  102. package/src/cli/cmd/run/demo.ts +1274 -0
  103. package/src/cli/cmd/run/entry.body.ts +205 -0
  104. package/src/cli/cmd/run/footer.command.tsx +1070 -0
  105. package/src/cli/cmd/run/footer.menu.tsx +351 -0
  106. package/src/cli/cmd/run/footer.permission.tsx +472 -0
  107. package/src/cli/cmd/run/footer.prompt.tsx +1306 -0
  108. package/src/cli/cmd/run/footer.question.tsx +573 -0
  109. package/src/cli/cmd/run/footer.subagent.tsx +175 -0
  110. package/src/cli/cmd/run/footer.ts +1129 -0
  111. package/src/cli/cmd/run/footer.view.tsx +945 -0
  112. package/src/cli/cmd/run/footer.width.ts +27 -0
  113. package/src/cli/cmd/run/permission.shared.ts +256 -0
  114. package/src/cli/cmd/run/prompt.editor.ts +157 -0
  115. package/src/cli/cmd/run/prompt.shared.ts +153 -0
  116. package/src/cli/cmd/run/question.shared.ts +340 -0
  117. package/src/cli/cmd/run/runtime.boot.ts +202 -0
  118. package/src/cli/cmd/run/runtime.lifecycle.ts +406 -0
  119. package/src/cli/cmd/run/runtime.queue.ts +349 -0
  120. package/src/cli/cmd/run/runtime.shared.ts +17 -0
  121. package/src/cli/cmd/run/runtime.stdin.ts +37 -0
  122. package/src/cli/cmd/run/runtime.ts +814 -0
  123. package/src/cli/cmd/run/scrollback.shared.ts +92 -0
  124. package/src/cli/cmd/run/scrollback.surface.ts +431 -0
  125. package/src/cli/cmd/run/scrollback.writer.tsx +352 -0
  126. package/src/cli/cmd/run/session-data.ts +1113 -0
  127. package/src/cli/cmd/run/session-replay.ts +374 -0
  128. package/src/cli/cmd/run/session.shared.ts +196 -0
  129. package/src/cli/cmd/run/splash.ts +280 -0
  130. package/src/cli/cmd/run/stream.transport.ts +1462 -0
  131. package/src/cli/cmd/run/stream.ts +175 -0
  132. package/src/cli/cmd/run/subagent-data.ts +876 -0
  133. package/src/cli/cmd/run/theme.ts +690 -0
  134. package/src/cli/cmd/run/tool.ts +1486 -0
  135. package/src/cli/cmd/run/trace.ts +94 -0
  136. package/src/cli/cmd/run/turn-summary.ts +47 -0
  137. package/src/cli/cmd/run/types.ts +350 -0
  138. package/src/cli/cmd/run/variant.shared.ts +216 -0
  139. package/src/cli/cmd/run.ts +1104 -0
  140. package/src/cli/cmd/serve.ts +24 -0
  141. package/src/cli/cmd/session.ts +147 -0
  142. package/src/cli/cmd/stats.ts +393 -0
  143. package/src/cli/cmd/tui.ts +317 -0
  144. package/src/cli/cmd/uninstall.ts +353 -0
  145. package/src/cli/cmd/upgrade.ts +74 -0
  146. package/src/cli/cmd/web.ts +84 -0
  147. package/src/cli/effect/prompt.ts +37 -0
  148. package/src/cli/effect-cmd.ts +96 -0
  149. package/src/cli/error.ts +130 -0
  150. package/src/cli/heap.ts +45 -0
  151. package/src/cli/logo.ts +1 -0
  152. package/src/cli/network.ts +80 -0
  153. package/src/cli/tui/layer.ts +8 -0
  154. package/src/cli/tui/validate-session.ts +29 -0
  155. package/src/cli/tui/worker.ts +80 -0
  156. package/src/cli/ui.ts +131 -0
  157. package/src/cli/upgrade.ts +68 -0
  158. package/src/command/index.ts +328 -0
  159. package/src/command/template/initialize.txt +66 -0
  160. package/src/command/template/review.txt +101 -0
  161. package/src/config/agent.ts +59 -0
  162. package/src/config/command.ts +39 -0
  163. package/src/config/config.ts +720 -0
  164. package/src/config/entry-name.ts +19 -0
  165. package/src/config/managed.ts +69 -0
  166. package/src/config/markdown.ts +36 -0
  167. package/src/config/parse.ts +61 -0
  168. package/src/config/paths.ts +45 -0
  169. package/src/config/plugin.ts +79 -0
  170. package/src/config/tui-cwd.ts +5 -0
  171. package/src/config/tui-host-attention.ts +21 -0
  172. package/src/config/tui-migrate.ts +132 -0
  173. package/src/config/tui.ts +276 -0
  174. package/src/config/variable.ts +91 -0
  175. package/src/control-plane/adapters/index.ts +41 -0
  176. package/src/control-plane/adapters/worktree.ts +96 -0
  177. package/src/control-plane/dev/README.md +19 -0
  178. package/src/control-plane/dev/debug-workspace-plugin.ts +73 -0
  179. package/src/control-plane/types.ts +59 -0
  180. package/src/control-plane/util.ts +39 -0
  181. package/src/control-plane/workspace-adapter-runtime.ts +51 -0
  182. package/src/control-plane/workspace-context.ts +26 -0
  183. package/src/control-plane/workspace.ts +966 -0
  184. package/src/effect/app-node-builder-v1.ts +12 -0
  185. package/src/effect/app-runtime.ts +135 -0
  186. package/src/effect/bootstrap-runtime.ts +19 -0
  187. package/src/effect/bridge.ts +84 -0
  188. package/src/effect/config-service.ts +67 -0
  189. package/src/effect/instance-ref.ts +11 -0
  190. package/src/effect/instance-registry.ts +12 -0
  191. package/src/effect/instance-state.ts +69 -0
  192. package/src/effect/promise.ts +17 -0
  193. package/src/effect/run-service.ts +47 -0
  194. package/src/effect/runner.ts +217 -0
  195. package/src/effect/runtime-flags.ts +78 -0
  196. package/src/env/index.ts +41 -0
  197. package/src/event-manifest.ts +3 -0
  198. package/src/event-v2-bridge.ts +71 -0
  199. package/src/format/formatter.ts +404 -0
  200. package/src/format/index.ts +203 -0
  201. package/src/format/output-style.ts +84 -0
  202. package/src/git/auto-commit.ts +70 -0
  203. package/src/git/index.ts +348 -0
  204. package/src/hooks/index.ts +172 -0
  205. package/src/id/id.ts +80 -0
  206. package/src/ide/index.ts +54 -0
  207. package/src/image/image.ts +172 -0
  208. package/src/index.ts +229 -0
  209. package/src/installation/index.ts +336 -0
  210. package/src/lsp/client.ts +650 -0
  211. package/src/lsp/diagnostic.ts +29 -0
  212. package/src/lsp/language.ts +121 -0
  213. package/src/lsp/launch.ts +21 -0
  214. package/src/lsp/lsp.ts +507 -0
  215. package/src/lsp/server.ts +1983 -0
  216. package/src/markdown.d.ts +4 -0
  217. package/src/mcp/auth.ts +163 -0
  218. package/src/mcp/browser.ts +37 -0
  219. package/src/mcp/catalog.ts +170 -0
  220. package/src/mcp/index.ts +1007 -0
  221. package/src/mcp/oauth-callback.ts +194 -0
  222. package/src/mcp/oauth-provider.ts +259 -0
  223. package/src/node.ts +4 -0
  224. package/src/patch/index.ts +686 -0
  225. package/src/permission/arity.ts +163 -0
  226. package/src/permission/evaluate.ts +1 -0
  227. package/src/permission/index.ts +223 -0
  228. package/src/permission/sandbox.ts +150 -0
  229. package/src/plugin/azure.ts +26 -0
  230. package/src/plugin/cerebras.ts +11 -0
  231. package/src/plugin/cloudflare.ts +65 -0
  232. package/src/plugin/digitalocean.ts +325 -0
  233. package/src/plugin/index.ts +316 -0
  234. package/src/plugin/install.ts +439 -0
  235. package/src/plugin/loader.ts +237 -0
  236. package/src/plugin/meta.ts +188 -0
  237. package/src/plugin/modal/modal.ts +17 -0
  238. package/src/plugin/modal/models.ts +133 -0
  239. package/src/plugin/openai/README.md +31 -0
  240. package/src/plugin/openai/codex.ts +572 -0
  241. package/src/plugin/openai/ws-pool.ts +271 -0
  242. package/src/plugin/openai/ws.ts +383 -0
  243. package/src/plugin/pty-environment.ts +24 -0
  244. package/src/plugin/shared.ts +323 -0
  245. package/src/plugin/snowflake-cortex.ts +507 -0
  246. package/src/plugin/tui/internal.ts +10 -0
  247. package/src/plugin/tui/runtime.ts +1131 -0
  248. package/src/plugin/xai.ts +339 -0
  249. package/src/project/bootstrap-service.ts +9 -0
  250. package/src/project/bootstrap.ts +58 -0
  251. package/src/project/instance-context.ts +24 -0
  252. package/src/project/instance-runtime.ts +16 -0
  253. package/src/project/instance-store.ts +213 -0
  254. package/src/project/project.ts +483 -0
  255. package/src/project/vcs.ts +423 -0
  256. package/src/provider/auth.ts +229 -0
  257. package/src/provider/error.ts +195 -0
  258. package/src/provider/model-status.ts +8 -0
  259. package/src/provider/provider.ts +2399 -0
  260. package/src/provider/transform.ts +1856 -0
  261. package/src/question/index.ts +161 -0
  262. package/src/question/schema.ts +4 -0
  263. package/src/server/auth.ts +48 -0
  264. package/src/server/event.ts +10 -0
  265. package/src/server/global-lifecycle.ts +28 -0
  266. package/src/server/init-projectors.ts +3 -0
  267. package/src/server/mdns.ts +47 -0
  268. package/src/server/projectors.ts +1 -0
  269. package/src/server/proxy-util.ts +48 -0
  270. package/src/server/routes/instance/httpapi/AGENTS.md +39 -0
  271. package/src/server/routes/instance/httpapi/api.ts +97 -0
  272. package/src/server/routes/instance/httpapi/errors.ts +193 -0
  273. package/src/server/routes/instance/httpapi/groups/config.ts +65 -0
  274. package/src/server/routes/instance/httpapi/groups/control-plane.ts +35 -0
  275. package/src/server/routes/instance/httpapi/groups/control.ts +76 -0
  276. package/src/server/routes/instance/httpapi/groups/event.ts +29 -0
  277. package/src/server/routes/instance/httpapi/groups/experimental.ts +275 -0
  278. package/src/server/routes/instance/httpapi/groups/file.ts +185 -0
  279. package/src/server/routes/instance/httpapi/groups/global.ts +163 -0
  280. package/src/server/routes/instance/httpapi/groups/instance.ts +206 -0
  281. package/src/server/routes/instance/httpapi/groups/mcp.ts +156 -0
  282. package/src/server/routes/instance/httpapi/groups/metadata.ts +18 -0
  283. package/src/server/routes/instance/httpapi/groups/permission.ts +61 -0
  284. package/src/server/routes/instance/httpapi/groups/project-copy.ts +32 -0
  285. package/src/server/routes/instance/httpapi/groups/project.ts +93 -0
  286. package/src/server/routes/instance/httpapi/groups/provider.ts +101 -0
  287. package/src/server/routes/instance/httpapi/groups/pty.ts +172 -0
  288. package/src/server/routes/instance/httpapi/groups/query.ts +12 -0
  289. package/src/server/routes/instance/httpapi/groups/question.ts +74 -0
  290. package/src/server/routes/instance/httpapi/groups/session.ts +462 -0
  291. package/src/server/routes/instance/httpapi/groups/sync.ts +113 -0
  292. package/src/server/routes/instance/httpapi/groups/tui.ts +208 -0
  293. package/src/server/routes/instance/httpapi/groups/workspace.ts +141 -0
  294. package/src/server/routes/instance/httpapi/handlers/config.ts +34 -0
  295. package/src/server/routes/instance/httpapi/handlers/control-plane.ts +37 -0
  296. package/src/server/routes/instance/httpapi/handlers/control.ts +43 -0
  297. package/src/server/routes/instance/httpapi/handlers/event.ts +99 -0
  298. package/src/server/routes/instance/httpapi/handlers/experimental.ts +193 -0
  299. package/src/server/routes/instance/httpapi/handlers/file.ts +139 -0
  300. package/src/server/routes/instance/httpapi/handlers/global.ts +144 -0
  301. package/src/server/routes/instance/httpapi/handlers/instance.ts +110 -0
  302. package/src/server/routes/instance/httpapi/handlers/mcp.ts +111 -0
  303. package/src/server/routes/instance/httpapi/handlers/permission.ts +41 -0
  304. package/src/server/routes/instance/httpapi/handlers/project-copy.ts +83 -0
  305. package/src/server/routes/instance/httpapi/handlers/project.ts +63 -0
  306. package/src/server/routes/instance/httpapi/handlers/provider.ts +116 -0
  307. package/src/server/routes/instance/httpapi/handlers/pty.ts +273 -0
  308. package/src/server/routes/instance/httpapi/handlers/question.ts +54 -0
  309. package/src/server/routes/instance/httpapi/handlers/session-errors.ts +21 -0
  310. package/src/server/routes/instance/httpapi/handlers/session.ts +442 -0
  311. package/src/server/routes/instance/httpapi/handlers/sync.ts +89 -0
  312. package/src/server/routes/instance/httpapi/handlers/tui.ts +131 -0
  313. package/src/server/routes/instance/httpapi/handlers/workspace.ts +102 -0
  314. package/src/server/routes/instance/httpapi/lifecycle.ts +54 -0
  315. package/src/server/routes/instance/httpapi/middleware/authorization.ts +150 -0
  316. package/src/server/routes/instance/httpapi/middleware/compression.ts +64 -0
  317. package/src/server/routes/instance/httpapi/middleware/cors-vary.ts +29 -0
  318. package/src/server/routes/instance/httpapi/middleware/error.ts +43 -0
  319. package/src/server/routes/instance/httpapi/middleware/fence.ts +25 -0
  320. package/src/server/routes/instance/httpapi/middleware/instance-context.ts +43 -0
  321. package/src/server/routes/instance/httpapi/middleware/proxy.ts +131 -0
  322. package/src/server/routes/instance/httpapi/middleware/schema-error.ts +41 -0
  323. package/src/server/routes/instance/httpapi/middleware/workspace-routing.ts +250 -0
  324. package/src/server/routes/instance/httpapi/public.ts +537 -0
  325. package/src/server/routes/instance/httpapi/server.ts +325 -0
  326. package/src/server/routes/instance/httpapi/websocket-tracker.ts +60 -0
  327. package/src/server/server.ts +227 -0
  328. package/src/server/shared/fence.ts +60 -0
  329. package/src/server/shared/pty-ticket.ts +15 -0
  330. package/src/server/shared/public-ui.ts +12 -0
  331. package/src/server/shared/tui-control.ts +28 -0
  332. package/src/server/shared/ui.ts +108 -0
  333. package/src/server/shared/workspace-routing.ts +45 -0
  334. package/src/server/tui-event.ts +1 -0
  335. package/src/session/auto-skill.ts +71 -0
  336. package/src/session/compaction.ts +637 -0
  337. package/src/session/instruction.ts +237 -0
  338. package/src/session/llm/AGENTS.md +90 -0
  339. package/src/session/llm/ai-sdk.ts +291 -0
  340. package/src/session/llm/native-request.ts +196 -0
  341. package/src/session/llm/native-runtime.ts +195 -0
  342. package/src/session/llm/request.ts +229 -0
  343. package/src/session/llm.ts +404 -0
  344. package/src/session/message-error.ts +14 -0
  345. package/src/session/message-v2.ts +737 -0
  346. package/src/session/message.ts +148 -0
  347. package/src/session/overflow.ts +69 -0
  348. package/src/session/processor.ts +718 -0
  349. package/src/session/prompt/anthropic.txt +105 -0
  350. package/src/session/prompt/beast.txt +147 -0
  351. package/src/session/prompt/build-switch.txt +5 -0
  352. package/src/session/prompt/codex.txt +79 -0
  353. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  354. package/src/session/prompt/default.txt +95 -0
  355. package/src/session/prompt/gemini.txt +155 -0
  356. package/src/session/prompt/gpt.txt +107 -0
  357. package/src/session/prompt/kimi.txt +95 -0
  358. package/src/session/prompt/meta.txt +65 -0
  359. package/src/session/prompt/plan-mode.txt +70 -0
  360. package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  361. package/src/session/prompt/plan.txt +26 -0
  362. package/src/session/prompt/trinity.txt +97 -0
  363. package/src/session/prompt.ts +2151 -0
  364. package/src/session/rate-limit.ts +176 -0
  365. package/src/session/reminders.ts +92 -0
  366. package/src/session/retry.ts +211 -0
  367. package/src/session/revert.ts +136 -0
  368. package/src/session/run-state.ts +151 -0
  369. package/src/session/schema.ts +26 -0
  370. package/src/session/session.ts +1050 -0
  371. package/src/session/speculation.ts +88 -0
  372. package/src/session/status.ts +56 -0
  373. package/src/session/summary.ts +164 -0
  374. package/src/session/system.ts +152 -0
  375. package/src/session/todo.ts +74 -0
  376. package/src/session/tools.ts +626 -0
  377. package/src/session/watch.ts +86 -0
  378. package/src/share/session.ts +58 -0
  379. package/src/share/share-next.ts +371 -0
  380. package/src/skill/discovery.ts +140 -0
  381. package/src/skill/index.ts +430 -0
  382. package/src/skill/restriction.ts +62 -0
  383. package/src/snapshot/index.ts +807 -0
  384. package/src/sql.d.ts +4 -0
  385. package/src/storage/schema.ts +5 -0
  386. package/src/storage/storage.ts +327 -0
  387. package/src/sync/README.md +179 -0
  388. package/src/sync/schema.ts +11 -0
  389. package/src/temporary.ts +31 -0
  390. package/src/tool/apply_patch.ts +313 -0
  391. package/src/tool/apply_patch.txt +33 -0
  392. package/src/tool/audio-gen.ts +50 -0
  393. package/src/tool/code-mode.ts +310 -0
  394. package/src/tool/diff-context.ts +64 -0
  395. package/src/tool/edit.ts +749 -0
  396. package/src/tool/edit.txt +10 -0
  397. package/src/tool/external-directory.ts +49 -0
  398. package/src/tool/glob.ts +76 -0
  399. package/src/tool/glob.txt +6 -0
  400. package/src/tool/grep.ts +115 -0
  401. package/src/tool/grep.txt +8 -0
  402. package/src/tool/image-gen.ts +50 -0
  403. package/src/tool/invalid.ts +21 -0
  404. package/src/tool/json-schema.ts +164 -0
  405. package/src/tool/lsp.ts +113 -0
  406. package/src/tool/lsp.txt +24 -0
  407. package/src/tool/mcp-websearch.ts +96 -0
  408. package/src/tool/plan-enter.txt +14 -0
  409. package/src/tool/plan-exit.txt +13 -0
  410. package/src/tool/plan.ts +79 -0
  411. package/src/tool/question.ts +44 -0
  412. package/src/tool/question.txt +10 -0
  413. package/src/tool/read.ts +386 -0
  414. package/src/tool/read.txt +14 -0
  415. package/src/tool/registry.ts +478 -0
  416. package/src/tool/repomap.ts +287 -0
  417. package/src/tool/schema.ts +14 -0
  418. package/src/tool/shell/id.ts +19 -0
  419. package/src/tool/shell/prompt.ts +295 -0
  420. package/src/tool/shell/shell.txt +21 -0
  421. package/src/tool/shell.ts +684 -0
  422. package/src/tool/skill.ts +81 -0
  423. package/src/tool/skill.txt +5 -0
  424. package/src/tool/task.ts +461 -0
  425. package/src/tool/task.txt +21 -0
  426. package/src/tool/todo.ts +46 -0
  427. package/src/tool/todowrite.txt +44 -0
  428. package/src/tool/tool.ts +183 -0
  429. package/src/tool/truncate.ts +156 -0
  430. package/src/tool/truncation-dir.ts +4 -0
  431. package/src/tool/video-gen.ts +50 -0
  432. package/src/tool/webfetch.ts +192 -0
  433. package/src/tool/webfetch.txt +13 -0
  434. package/src/tool/websearch.ts +143 -0
  435. package/src/tool/websearch.txt +14 -0
  436. package/src/tool/write.ts +117 -0
  437. package/src/tool/write.txt +8 -0
  438. package/src/util/archive.ts +17 -0
  439. package/src/util/bom.ts +27 -0
  440. package/src/util/data-url.ts +9 -0
  441. package/src/util/defer.ts +10 -0
  442. package/src/util/effect-http-client.ts +11 -0
  443. package/src/util/error.ts +1 -0
  444. package/src/util/filesystem.ts +251 -0
  445. package/src/util/html.ts +8 -0
  446. package/src/util/iife.ts +3 -0
  447. package/src/util/lazy.ts +20 -0
  448. package/src/util/local-context.ts +25 -0
  449. package/src/util/locale.ts +2 -0
  450. package/src/util/media.ts +26 -0
  451. package/src/util/process.ts +177 -0
  452. package/src/util/proxy-env.ts +72 -0
  453. package/src/util/queue.ts +32 -0
  454. package/src/util/record.ts +1 -0
  455. package/src/util/repository.ts +232 -0
  456. package/src/util/rpc.ts +66 -0
  457. package/src/util/signal.ts +12 -0
  458. package/src/util/timeout.ts +13 -0
  459. package/src/util/token.ts +1 -0
  460. package/src/util/wildcard.ts +59 -0
  461. package/src/verify/verify.ts +106 -0
  462. package/src/worktree/index.ts +623 -0
  463. package/sst-env.d.ts +10 -0
  464. package/test/AGENTS.md +204 -0
  465. package/test/EFFECT_TEST_MIGRATION.md +169 -0
  466. package/test/account/repo.test.ts +355 -0
  467. package/test/account/service.test.ts +524 -0
  468. package/test/acp/config-option.test.ts +229 -0
  469. package/test/acp/content.test.ts +235 -0
  470. package/test/acp/directory.test.ts +188 -0
  471. package/test/acp/error.test.ts +67 -0
  472. package/test/acp/event.test.ts +751 -0
  473. package/test/acp/permission.test.ts +401 -0
  474. package/test/acp/service-session.test.ts +1374 -0
  475. package/test/acp/session.test.ts +201 -0
  476. package/test/acp/tool.test.ts +298 -0
  477. package/test/acp/usage.test.ts +318 -0
  478. package/test/agent/agent.test.ts +755 -0
  479. package/test/agent/plan-mode-subagent-bypass.test.ts +160 -0
  480. package/test/agent/plugin-agent-regression.test.ts +51 -0
  481. package/test/auth/auth.test.ts +75 -0
  482. package/test/background/job.test.ts +244 -0
  483. package/test/cli/account.test.ts +30 -0
  484. package/test/cli/acp/acp-test-client.ts +97 -0
  485. package/test/cli/acp/config-options.test.ts +103 -0
  486. package/test/cli/acp/helpers.ts +96 -0
  487. package/test/cli/acp/initialize-auth.test.ts +61 -0
  488. package/test/cli/acp/lifecycle.test.ts +118 -0
  489. package/test/cli/acp/prompt-content.test.ts +97 -0
  490. package/test/cli/acp/skills.test.ts +38 -0
  491. package/test/cli/cmd/tui/attention.test.ts +484 -0
  492. package/test/cli/effect-cmd-instance-als.test.ts +40 -0
  493. package/test/cli/error.test.ts +95 -0
  494. package/test/cli/github-action.test.ts +199 -0
  495. package/test/cli/github-remote.test.ts +90 -0
  496. package/test/cli/help/__snapshots__/help-snapshots.test.ts.snap +623 -0
  497. package/test/cli/help/help-snapshots.test.ts +140 -0
  498. package/test/cli/import.test.ts +90 -0
  499. package/test/cli/mcp-add.test.ts +74 -0
  500. package/test/cli/plugin-auth-picker.test.ts +120 -0
  501. package/test/cli/run/entry.body.test.ts +536 -0
  502. package/test/cli/run/footer.menu.test.ts +43 -0
  503. package/test/cli/run/footer.view.test.tsx +1411 -0
  504. package/test/cli/run/footer.width.test.ts +35 -0
  505. package/test/cli/run/permission.shared.test.ts +144 -0
  506. package/test/cli/run/prompt.editor.test.ts +101 -0
  507. package/test/cli/run/prompt.shared.test.ts +101 -0
  508. package/test/cli/run/question.shared.test.ts +115 -0
  509. package/test/cli/run/run-process.test.ts +338 -0
  510. package/test/cli/run/runtime.boot.test.ts +283 -0
  511. package/test/cli/run/runtime.queue.test.ts +481 -0
  512. package/test/cli/run/runtime.stdin.test.ts +71 -0
  513. package/test/cli/run/runtime.test.ts +238 -0
  514. package/test/cli/run/scrollback.surface.test.ts +1092 -0
  515. package/test/cli/run/session-data.test.ts +593 -0
  516. package/test/cli/run/session-replay.test.ts +691 -0
  517. package/test/cli/run/session.shared.test.ts +247 -0
  518. package/test/cli/run/stream.test.ts +56 -0
  519. package/test/cli/run/stream.transport.test.ts +2363 -0
  520. package/test/cli/run/subagent-data.test.ts +547 -0
  521. package/test/cli/run/theme.test.ts +177 -0
  522. package/test/cli/run/variant.shared.test.ts +218 -0
  523. package/test/cli/serve/serve-process.test.ts +61 -0
  524. package/test/cli/smokes/read-only.test.ts +115 -0
  525. package/test/cli/tui/attach.test.ts +11 -0
  526. package/test/cli/tui/editor-context-zed.test.ts +379 -0
  527. package/test/cli/tui/editor-context.test.tsx +297 -0
  528. package/test/cli/tui/plugin-add.test.ts +110 -0
  529. package/test/cli/tui/plugin-install.test.ts +87 -0
  530. package/test/cli/tui/plugin-lifecycle.test.ts +224 -0
  531. package/test/cli/tui/plugin-loader-entrypoint.test.ts +485 -0
  532. package/test/cli/tui/plugin-loader-pure.test.ts +72 -0
  533. package/test/cli/tui/plugin-loader.test.ts +1332 -0
  534. package/test/cli/tui/plugin-toggle.test.ts +264 -0
  535. package/test/cli/tui/thread.test.ts +101 -0
  536. package/test/config/agent-color.test.ts +47 -0
  537. package/test/config/config.test.ts +2047 -0
  538. package/test/config/entry-name.test.ts +57 -0
  539. package/test/config/fixtures/empty-frontmatter.md +4 -0
  540. package/test/config/fixtures/frontmatter.md +28 -0
  541. package/test/config/fixtures/markdown-header.md +11 -0
  542. package/test/config/fixtures/no-frontmatter.md +1 -0
  543. package/test/config/fixtures/weird-model-id.md +13 -0
  544. package/test/config/lsp.test.ts +69 -0
  545. package/test/config/markdown.test.ts +228 -0
  546. package/test/config/plugin.test.ts +0 -0
  547. package/test/config/tui.test.ts +894 -0
  548. package/test/control-plane/adapters.test.ts +71 -0
  549. package/test/control-plane/workspace.test.ts +1717 -0
  550. package/test/effect/app-runtime-logger.test.ts +101 -0
  551. package/test/effect/config-service.test.ts +65 -0
  552. package/test/effect/instance-state.test.ts +392 -0
  553. package/test/effect/run-service.test.ts +89 -0
  554. package/test/effect/runner.test.ts +514 -0
  555. package/test/effect/runtime-flags.test.ts +374 -0
  556. package/test/event-manifest.test.ts +24 -0
  557. package/test/fake/account.ts +9 -0
  558. package/test/fake/auth.ts +8 -0
  559. package/test/fake/npm.ts +8 -0
  560. package/test/fake/provider.ts +83 -0
  561. package/test/fake/skill.ts +8 -0
  562. package/test/filesystem/filesystem.test.ts +318 -0
  563. package/test/fixture/agent-plugin.constants.ts +6 -0
  564. package/test/fixture/agent-plugin.ts +12 -0
  565. package/test/fixture/config.ts +24 -0
  566. package/test/fixture/db.ts +11 -0
  567. package/test/fixture/fixture.test.ts +26 -0
  568. package/test/fixture/fixture.ts +228 -0
  569. package/test/fixture/flag.ts +20 -0
  570. package/test/fixture/flock-worker.ts +72 -0
  571. package/test/fixture/lsp/fake-lsp-server.js +249 -0
  572. package/test/fixture/mcp-lifecycle-stdio.ts +26 -0
  573. package/test/fixture/mcp-session-recovery.ts +50 -0
  574. package/test/fixture/plug-worker.ts +93 -0
  575. package/test/fixture/plugin-meta-worker.ts +19 -0
  576. package/test/fixture/plugin.ts +10 -0
  577. package/test/fixture/skills/agents-sdk/SKILL.md +152 -0
  578. package/test/fixture/skills/agents-sdk/references/callable.md +92 -0
  579. package/test/fixture/skills/cloudflare/SKILL.md +211 -0
  580. package/test/fixture/skills/index.json +6 -0
  581. package/test/fixture/tui-environment.tsx +32 -0
  582. package/test/fixture/tui-plugin.ts +355 -0
  583. package/test/fixture/tui-runtime.ts +56 -0
  584. package/test/fixture/tui-sdk.ts +82 -0
  585. package/test/fixture/workspace.ts +34 -0
  586. package/test/fixtures/recordings/session/native-anthropic-tool-loop.json +49 -0
  587. package/test/fixtures/recordings/session/native-openai-oauth-tool-loop.json +45 -0
  588. package/test/fixtures/recordings/session/native-zen-tool-loop.json +49 -0
  589. package/test/format/format.test.ts +235 -0
  590. package/test/git/auto-commit.test.ts +63 -0
  591. package/test/git/git.test.ts +179 -0
  592. package/test/ide/ide.test.ts +82 -0
  593. package/test/image/fixtures/picture-5mb-base64.png +0 -0
  594. package/test/image/image.test.ts +121 -0
  595. package/test/installation/installation.test.ts +240 -0
  596. package/test/lib/cli-process.ts +535 -0
  597. package/test/lib/effect.ts +177 -0
  598. package/test/lib/filesystem.ts +10 -0
  599. package/test/lib/llm-server.ts +779 -0
  600. package/test/lib/snapshot.ts +73 -0
  601. package/test/lib/test-provider.ts +37 -0
  602. package/test/lib/websocket.ts +46 -0
  603. package/test/lsp/client.test.ts +488 -0
  604. package/test/lsp/index.test.ts +231 -0
  605. package/test/lsp/jdtls-root.test.ts +459 -0
  606. package/test/lsp/launch.test.ts +22 -0
  607. package/test/lsp/lifecycle.test.ts +160 -0
  608. package/test/mcp/auth.test.ts +78 -0
  609. package/test/mcp/catalog.test.ts +107 -0
  610. package/test/mcp/headers.test.ts +102 -0
  611. package/test/mcp/lifecycle.test.ts +560 -0
  612. package/test/mcp/oauth-auto-connect.test.ts +300 -0
  613. package/test/mcp/oauth-browser.test.ts +225 -0
  614. package/test/mcp/oauth-callback.test.ts +114 -0
  615. package/test/mcp/oauth-provider.test.ts +102 -0
  616. package/test/mcp/session-recovery.test.ts +27 -0
  617. package/test/mcp/transport.test.ts +38 -0
  618. package/test/patch/patch.test.ts +384 -0
  619. package/test/permission/arity.test.ts +33 -0
  620. package/test/permission/next.test.ts +1174 -0
  621. package/test/permission/sandbox.test.ts +89 -0
  622. package/test/permission-task.test.ts +319 -0
  623. package/test/plugin/auth-override.test.ts +101 -0
  624. package/test/plugin/cerebras.test.ts +47 -0
  625. package/test/plugin/cloudflare.test.ts +25 -0
  626. package/test/plugin/codex.test.ts +463 -0
  627. package/test/plugin/install-concurrency.test.ts +140 -0
  628. package/test/plugin/install.test.ts +570 -0
  629. package/test/plugin/loader-shared.test.ts +1306 -0
  630. package/test/plugin/meta.test.ts +137 -0
  631. package/test/plugin/modal-models.test.ts +198 -0
  632. package/test/plugin/openai-rollout.test.ts +17 -0
  633. package/test/plugin/openai-ws.test.ts +909 -0
  634. package/test/plugin/shared.test.ts +88 -0
  635. package/test/plugin/snowflake-cortex.test.ts +278 -0
  636. package/test/plugin/trigger.test.ts +108 -0
  637. package/test/plugin/workspace-adapter.test.ts +111 -0
  638. package/test/plugin/xai.test.ts +585 -0
  639. package/test/preload.ts +92 -0
  640. package/test/project/instance-bootstrap.test.ts +115 -0
  641. package/test/project/instance.test.ts +248 -0
  642. package/test/project/migrate-global.test.ts +168 -0
  643. package/test/project/project-directory.test.ts +202 -0
  644. package/test/project/project.test.ts +808 -0
  645. package/test/project/vcs.test.ts +335 -0
  646. package/test/project/worktree-remove.test.ts +128 -0
  647. package/test/project/worktree.test.ts +324 -0
  648. package/test/provider/amazon-bedrock.test.ts +361 -0
  649. package/test/provider/cf-ai-gateway-e2e.test.ts +320 -0
  650. package/test/provider/digitalocean.test.ts +124 -0
  651. package/test/provider/error.test.ts +24 -0
  652. package/test/provider/gitlab-duo.test.ts +412 -0
  653. package/test/provider/header-timeout.test.ts +234 -0
  654. package/test/provider/model-status.test.ts +61 -0
  655. package/test/provider/provider.test.ts +2118 -0
  656. package/test/provider/transform.test.ts +5682 -0
  657. package/test/question/question.test.ts +459 -0
  658. package/test/server/AGENTS.md +15 -0
  659. package/test/server/auth.test.ts +59 -0
  660. package/test/server/global-bus.ts +31 -0
  661. package/test/server/global-session-list.test.ts +108 -0
  662. package/test/server/httpapi-authorization.test.ts +174 -0
  663. package/test/server/httpapi-compression.test.ts +151 -0
  664. package/test/server/httpapi-config.test.ts +110 -0
  665. package/test/server/httpapi-control-plane.test.ts +63 -0
  666. package/test/server/httpapi-cors-vary.test.ts +63 -0
  667. package/test/server/httpapi-cors.test.ts +122 -0
  668. package/test/server/httpapi-error-middleware.test.ts +101 -0
  669. package/test/server/httpapi-event.test.ts +94 -0
  670. package/test/server/httpapi-exercise/assertions.ts +64 -0
  671. package/test/server/httpapi-exercise/backend.ts +144 -0
  672. package/test/server/httpapi-exercise/dsl.ts +210 -0
  673. package/test/server/httpapi-exercise/environment.ts +40 -0
  674. package/test/server/httpapi-exercise/index.ts +1802 -0
  675. package/test/server/httpapi-exercise/report.ts +66 -0
  676. package/test/server/httpapi-exercise/routing.ts +96 -0
  677. package/test/server/httpapi-exercise/runner.ts +267 -0
  678. package/test/server/httpapi-exercise/runtime.ts +52 -0
  679. package/test/server/httpapi-exercise/types.ts +127 -0
  680. package/test/server/httpapi-experimental.test.ts +298 -0
  681. package/test/server/httpapi-file.test.ts +83 -0
  682. package/test/server/httpapi-global.test.ts +90 -0
  683. package/test/server/httpapi-instance-context.test.ts +352 -0
  684. package/test/server/httpapi-instance-route-auth.test.ts +81 -0
  685. package/test/server/httpapi-instance.test.ts +265 -0
  686. package/test/server/httpapi-layer.ts +33 -0
  687. package/test/server/httpapi-listen.test.ts +465 -0
  688. package/test/server/httpapi-mcp-oauth.test.ts +73 -0
  689. package/test/server/httpapi-mcp.test.ts +223 -0
  690. package/test/server/httpapi-mdns.test.ts +79 -0
  691. package/test/server/httpapi-promptasync-context.test.ts +212 -0
  692. package/test/server/httpapi-provider.test.ts +401 -0
  693. package/test/server/httpapi-pty.test.ts +299 -0
  694. package/test/server/httpapi-public-openapi.test.ts +350 -0
  695. package/test/server/httpapi-query-schema-drift.test.ts +330 -0
  696. package/test/server/httpapi-reference.test.ts +63 -0
  697. package/test/server/httpapi-schema-error-body.test.ts +166 -0
  698. package/test/server/httpapi-sdk.test.ts +913 -0
  699. package/test/server/httpapi-session.test.ts +1090 -0
  700. package/test/server/httpapi-sync.test.ts +149 -0
  701. package/test/server/httpapi-ui.test.ts +457 -0
  702. package/test/server/httpapi-v2-location.test.ts +126 -0
  703. package/test/server/httpapi-v2-pty.test.ts +250 -0
  704. package/test/server/httpapi-workspace-routing.test.ts +552 -0
  705. package/test/server/httpapi-workspace.test.ts +506 -0
  706. package/test/server/negative-tokens-regression.test.ts +84 -0
  707. package/test/server/project-copy.test.ts +127 -0
  708. package/test/server/project-init-git.test.ts +118 -0
  709. package/test/server/proxy-util.test.ts +113 -0
  710. package/test/server/sdk-error-shape.test.ts +81 -0
  711. package/test/server/sdk-v1-smoke.test.ts +57 -0
  712. package/test/server/session-actions.test.ts +110 -0
  713. package/test/server/session-diff-missing-patch.test.ts +97 -0
  714. package/test/server/session-list.test.ts +302 -0
  715. package/test/server/session-messages.test.ts +180 -0
  716. package/test/server/session-select.test.ts +67 -0
  717. package/test/server/workspace-proxy.test.ts +181 -0
  718. package/test/server/workspace-routing.test.ts +101 -0
  719. package/test/server/worktree-endpoint-repro.test.ts +307 -0
  720. package/test/session/compaction.test.ts +1975 -0
  721. package/test/session/instruction.test.ts +264 -0
  722. package/test/session/llm-native-recorded.test.ts +413 -0
  723. package/test/session/llm-native.test.ts +761 -0
  724. package/test/session/llm.test.ts +2249 -0
  725. package/test/session/message-v2.test.ts +1729 -0
  726. package/test/session/messages-pagination.test.ts +1057 -0
  727. package/test/session/processor-effect.test.ts +1171 -0
  728. package/test/session/prompt.test.ts +2470 -0
  729. package/test/session/retry.test.ts +521 -0
  730. package/test/session/revert-compact.test.ts +683 -0
  731. package/test/session/schema-decoding.test.ts +313 -0
  732. package/test/session/session-schema.test.ts +78 -0
  733. package/test/session/session.test.ts +285 -0
  734. package/test/session/snapshot-tool-race.test.ts +189 -0
  735. package/test/session/structured-output-integration.test.ts +235 -0
  736. package/test/session/structured-output.test.ts +387 -0
  737. package/test/session/system.test.ts +168 -0
  738. package/test/share/share-next.test.ts +324 -0
  739. package/test/skill/discovery.test.ts +186 -0
  740. package/test/skill/restriction.test.ts +57 -0
  741. package/test/skill/skill.test.ts +588 -0
  742. package/test/snapshot/snapshot.test.ts +1218 -0
  743. package/test/storage/storage.test.ts +297 -0
  744. package/test/tool/__snapshots__/parameters.test.ts.snap +466 -0
  745. package/test/tool/__snapshots__/tool.test.ts.snap +9 -0
  746. package/test/tool/apply_patch.test.ts +529 -0
  747. package/test/tool/code-mode-integration.test.ts +331 -0
  748. package/test/tool/code-mode.test.ts +730 -0
  749. package/test/tool/edit.test.ts +576 -0
  750. package/test/tool/external-directory.test.ts +156 -0
  751. package/test/tool/fixtures/large-image.png +0 -0
  752. package/test/tool/fixtures/models-api.json +172692 -0
  753. package/test/tool/glob.test.ts +132 -0
  754. package/test/tool/grep.test.ts +223 -0
  755. package/test/tool/lsp.test.ts +184 -0
  756. package/test/tool/parameters.test.ts +290 -0
  757. package/test/tool/question.test.ts +133 -0
  758. package/test/tool/read.test.ts +608 -0
  759. package/test/tool/registry.test.ts +572 -0
  760. package/test/tool/shell.test.ts +1199 -0
  761. package/test/tool/skill.test.ts +134 -0
  762. package/test/tool/task.test.ts +1101 -0
  763. package/test/tool/tool-define.test.ts +154 -0
  764. package/test/tool/truncation.test.ts +266 -0
  765. package/test/tool/webfetch.test.ts +119 -0
  766. package/test/tool/websearch.test.ts +100 -0
  767. package/test/tool/write.test.ts +281 -0
  768. package/test/util/data-url.test.ts +14 -0
  769. package/test/util/error.test.ts +16 -0
  770. package/test/util/filesystem.test.ts +656 -0
  771. package/test/util/glob.test.ts +164 -0
  772. package/test/util/html.test.ts +15 -0
  773. package/test/util/iife.test.ts +36 -0
  774. package/test/util/lazy.test.ts +50 -0
  775. package/test/util/module.test.ts +59 -0
  776. package/test/util/process.test.ts +128 -0
  777. package/test/util/repository.test.ts +93 -0
  778. package/test/util/timeout.test.ts +21 -0
  779. package/test/util/wildcard.test.ts +90 -0
  780. package/test/v2/session-message-updater.test.ts +269 -0
  781. package/test/verify/verify.test.ts +61 -0
  782. package/tsconfig.json +16 -0
@@ -0,0 +1,2399 @@
1
+ import { LayerNode } from "@msrfteam/core/effect/layer-node"
2
+ import { ProxyAgent } from "undici"
3
+ import os from "os"
4
+ import { ConfigV1 } from "@msrfteam/core/v1/config/config"
5
+ import fuzzysort from "fuzzysort"
6
+ import { Config } from "@/config/config"
7
+ import { mapValues, mergeDeep, omit, pickBy, sortBy } from "remeda"
8
+ import { NoSuchModelError, type Provider as SDK } from "ai"
9
+ import { Npm } from "@msrfteam/core/npm"
10
+ import { Hash } from "@msrfteam/core/util/hash"
11
+ import { Plugin } from "../plugin"
12
+ import { serviceUse } from "@msrfteam/core/effect/service-use"
13
+ import { type LanguageModelV3 } from "@ai-sdk/provider"
14
+ import { ModelsDev } from "@msrfteam/core/models-dev"
15
+ import { Auth } from "../auth"
16
+ import { Env } from "../env"
17
+ import { InstallationVersion } from "@msrfteam/core/installation/version"
18
+ import { iife } from "@/util/iife"
19
+ import { Global } from "@msrfteam/core/global"
20
+ import path from "path"
21
+ import { pathToFileURL } from "url"
22
+ import { Effect, Layer, Context, Schema, Types } from "effect"
23
+ import { EffectBridge } from "@/effect/bridge"
24
+ import { InstanceState } from "@/effect/instance-state"
25
+ import { EffectPromise } from "@/effect/promise"
26
+ import { FSUtil } from "@msrfteam/core/fs-util"
27
+ import { isRecord } from "@/util/record"
28
+ import { optional } from "@msrfteam/core/schema"
29
+ import { ProviderTransform } from "./transform"
30
+ import { ProviderV2 } from "@msrfteam/core/provider"
31
+ import { ModelV2 } from "@msrfteam/core/model"
32
+ import { ModelStatus } from "./model-status"
33
+ import { RuntimeFlags } from "@/effect/runtime-flags"
34
+ import { ProviderError } from "./error"
35
+
36
+ const OPENAI_HEADER_TIMEOUT_DEFAULT = 300_000
37
+
38
+ function wrapSSE(res: Response, ms: number, ctl: AbortController) {
39
+ if (typeof ms !== "number" || ms <= 0) return res
40
+ if (!res.body) return res
41
+ if (!res.headers.get("content-type")?.includes("text/event-stream")) return res
42
+
43
+ const reader = res.body.getReader()
44
+ const body = new ReadableStream<Uint8Array>({
45
+ async pull(ctrl) {
46
+ const part = await new Promise<Awaited<ReturnType<typeof reader.read>>>((resolve, reject) => {
47
+ const id = setTimeout(() => {
48
+ const err = new ProviderError.ResponseStreamError("SSE read timed out")
49
+ ctl.abort(err)
50
+ void reader.cancel(err)
51
+ reject(err)
52
+ }, ms)
53
+
54
+ reader.read().then(
55
+ (part) => {
56
+ clearTimeout(id)
57
+ resolve(part)
58
+ },
59
+ (err) => {
60
+ clearTimeout(id)
61
+ reject(err)
62
+ },
63
+ )
64
+ })
65
+
66
+ if (part.done) {
67
+ ctrl.close()
68
+ return
69
+ }
70
+
71
+ ctrl.enqueue(part.value)
72
+ },
73
+ async cancel(reason) {
74
+ ctl.abort(reason)
75
+ await reader.cancel(reason)
76
+ },
77
+ })
78
+
79
+ return new Response(body, {
80
+ headers: new Headers(res.headers),
81
+ status: res.status,
82
+ statusText: res.statusText,
83
+ })
84
+ }
85
+
86
+ function timeoutController(ms: number) {
87
+ const ctl = new AbortController()
88
+ const id = setTimeout(() => ctl.abort(new ProviderError.HeaderTimeoutError(ms)), ms)
89
+ return {
90
+ signal: ctl.signal,
91
+ clear: () => clearTimeout(id),
92
+ }
93
+ }
94
+
95
+ function googleVertexAnthropicBaseURL(project: string | undefined, location: string | undefined) {
96
+ if (!project) return
97
+ if (location !== "eu" && location !== "us") return
98
+ // Continental multi-regions require Regional Endpoint Platform domains.
99
+ return `https://aiplatform.${location}.rep.googleapis.com/v1/projects/${project}/locations/${location}/publishers/anthropic/models`
100
+ }
101
+
102
+ function googleVertexEndpoint(location: string) {
103
+ if (location === "global") return "aiplatform.googleapis.com"
104
+ if (location === "eu" || location === "us") return `aiplatform.${location}.rep.googleapis.com`
105
+ return `${location}-aiplatform.googleapis.com`
106
+ }
107
+
108
+ type BundledSDK = {
109
+ languageModel(modelId: string): LanguageModelV3
110
+ chat?: (modelId: string) => LanguageModelV3
111
+ responses?: (modelId: string) => LanguageModelV3
112
+ }
113
+
114
+ const BUNDLED_PROVIDERS: Record<string, () => Promise<(opts: any) => BundledSDK>> = {
115
+ "@ai-sdk/amazon-bedrock": () => import("@ai-sdk/amazon-bedrock").then((m) => m.createAmazonBedrock),
116
+ "@ai-sdk/amazon-bedrock/mantle": () => import("@ai-sdk/amazon-bedrock/mantle").then((m) => m.createBedrockMantle),
117
+ "@ai-sdk/anthropic": () => import("@ai-sdk/anthropic").then((m) => m.createAnthropic),
118
+ "@ai-sdk/azure": () => import("@ai-sdk/azure").then((m) => m.createAzure),
119
+ "@ai-sdk/google": () => import("@ai-sdk/google").then((m) => m.createGoogleGenerativeAI),
120
+ "@ai-sdk/google-vertex": () => import("@ai-sdk/google-vertex").then((m) => m.createVertex),
121
+ "@ai-sdk/google-vertex/anthropic": () =>
122
+ import("@ai-sdk/google-vertex/anthropic").then((m) => m.createVertexAnthropic),
123
+ "@ai-sdk/openai": () => import("@ai-sdk/openai").then((m) => m.createOpenAI),
124
+ "@ai-sdk/openai-compatible": () => import("@ai-sdk/openai-compatible").then((m) => m.createOpenAICompatible),
125
+ "@openrouter/ai-sdk-provider": () => import("@openrouter/ai-sdk-provider").then((m) => m.createOpenRouter),
126
+ "@ai-sdk/xai": () => import("@ai-sdk/xai").then((m) => m.createXai),
127
+ "@ai-sdk/mistral": () => import("@ai-sdk/mistral").then((m) => m.createMistral),
128
+ "@ai-sdk/groq": () => import("@ai-sdk/groq").then((m) => m.createGroq),
129
+ "@ai-sdk/deepinfra": () => import("@ai-sdk/deepinfra").then((m) => m.createDeepInfra),
130
+ "@ai-sdk/cerebras": () => import("@ai-sdk/cerebras").then((m) => m.createCerebras),
131
+ "@ai-sdk/cohere": () => import("@ai-sdk/cohere").then((m) => m.createCohere),
132
+ "@ai-sdk/gateway": () => import("@ai-sdk/gateway").then((m) => m.createGateway),
133
+ "@ai-sdk/togetherai": () => import("@ai-sdk/togetherai").then((m) => m.createTogetherAI),
134
+ "@ai-sdk/perplexity": () => import("@ai-sdk/perplexity").then((m) => m.createPerplexity),
135
+ "@ai-sdk/vercel": () => import("@ai-sdk/vercel").then((m) => m.createVercel),
136
+ "@ai-sdk/alibaba": () => import("@ai-sdk/alibaba").then((m) => m.createAlibaba),
137
+ "gitlab-ai-provider": () => import("gitlab-ai-provider").then((m) => m.createGitLab),
138
+ "venice-ai-sdk-provider": () => import("venice-ai-sdk-provider").then((m) => m.createVenice),
139
+ }
140
+
141
+ type CustomModelLoader = (sdk: any, modelID: string, options?: Record<string, any>, model?: Model) => Promise<any>
142
+ type CustomVarsLoader = (options: Record<string, any>) => Record<string, string>
143
+ type CustomDiscoverModels = () => Promise<Record<string, Model>>
144
+ type CustomLoader = (provider: Info) => Effect.Effect<{
145
+ autoload: boolean
146
+ getModel?: CustomModelLoader
147
+ vars?: CustomVarsLoader
148
+ options?: Record<string, any>
149
+ discoverModels?: CustomDiscoverModels
150
+ }>
151
+
152
+ type CustomDep = {
153
+ auth: (id: string) => Effect.Effect<Auth.Info | undefined>
154
+ config: () => Effect.Effect<ConfigV1.Info>
155
+ env: () => Effect.Effect<Record<string, string | undefined>>
156
+ get: (key: string) => Effect.Effect<string | undefined>
157
+ }
158
+
159
+ function selectAzureLanguageModel(sdk: any, modelID: string, useChat: boolean) {
160
+ if (useChat && sdk.chat) return sdk.chat(modelID)
161
+ if (sdk.responses) return sdk.responses(modelID)
162
+ if (sdk.messages) return sdk.messages(modelID)
163
+ if (sdk.chat) return sdk.chat(modelID)
164
+ return sdk.languageModel(modelID)
165
+ }
166
+
167
+ function selectBedrockMantleLanguageModel(sdk: BundledSDK, modelID: string) {
168
+ if (modelID === "openai.gpt-oss-safeguard-20b" || modelID === "openai.gpt-oss-safeguard-120b")
169
+ return sdk.chat?.(modelID) ?? sdk.languageModel(modelID)
170
+ return sdk.responses?.(modelID) ?? sdk.languageModel(modelID)
171
+ }
172
+
173
+ function custom(dep: CustomDep): Record<string, CustomLoader> {
174
+ return {
175
+ anthropic: () =>
176
+ Effect.succeed({
177
+ autoload: false,
178
+ options: {
179
+ headers: {
180
+ "anthropic-beta": "interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",
181
+ },
182
+ },
183
+ }),
184
+ mervex: Effect.fnUntraced(function* (input: Info) {
185
+ const env = yield* dep.env()
186
+ const hasKey = iife(() => {
187
+ if (input.env.some((item) => env[item])) return true
188
+ return false
189
+ })
190
+ const ok =
191
+ hasKey ||
192
+ Boolean(yield* dep.auth(input.id)) ||
193
+ Boolean((yield* dep.config()).provider?.["mervex"]?.options?.apiKey)
194
+
195
+ if (!ok) {
196
+ for (const [key, value] of Object.entries(input.models)) {
197
+ if (value.cost.input === 0) continue
198
+ delete input.models[key]
199
+ }
200
+ }
201
+
202
+ return {
203
+ autoload: Object.keys(input.models).length > 0,
204
+ options: ok ? { baseURL: MERVEX_BASE_URL } : { apiKey: "public", baseURL: MERVEX_BASE_URL },
205
+ }
206
+ }),
207
+ openai: () =>
208
+ Effect.succeed({
209
+ autoload: false,
210
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
211
+ return sdk.responses(modelID)
212
+ },
213
+ options: { headerTimeout: OPENAI_HEADER_TIMEOUT_DEFAULT },
214
+ }),
215
+ meta: () =>
216
+ Effect.succeed({
217
+ autoload: false,
218
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
219
+ return sdk.responses(modelID)
220
+ },
221
+ }),
222
+ xai: () =>
223
+ Effect.succeed({
224
+ autoload: false,
225
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
226
+ return sdk.responses(modelID)
227
+ },
228
+ options: {},
229
+ }),
230
+ azure: Effect.fnUntraced(function* (provider: Info) {
231
+ const env = yield* dep.env()
232
+ const auth = yield* dep.auth(provider.id)
233
+ const resource = iife(() => {
234
+ return [
235
+ provider.options?.resourceName,
236
+ auth?.type === "api" ? auth.metadata?.resourceName : undefined,
237
+ env["AZURE_RESOURCE_NAME"],
238
+ ].find((name) => typeof name === "string" && name.trim() !== "")
239
+ })
240
+
241
+ if (!resource && !provider.options?.baseURL) {
242
+ return {
243
+ autoload: false,
244
+ async getModel() {
245
+ throw new Error(
246
+ "AZURE_RESOURCE_NAME is missing, set it using env var or reconnecting the azure provider and setting it",
247
+ )
248
+ },
249
+ }
250
+ }
251
+
252
+ return {
253
+ autoload: false,
254
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
255
+ return selectAzureLanguageModel(sdk, modelID, Boolean(options?.["useCompletionUrls"]))
256
+ },
257
+ options: {
258
+ resourceName: resource,
259
+ },
260
+ vars(_options): Record<string, string> {
261
+ if (resource) {
262
+ return {
263
+ AZURE_RESOURCE_NAME: resource,
264
+ }
265
+ }
266
+ return {}
267
+ },
268
+ }
269
+ }),
270
+ "azure-cognitive-services": Effect.fnUntraced(function* (provider: Info) {
271
+ const resourceName = yield* dep.get("AZURE_COGNITIVE_SERVICES_RESOURCE_NAME")
272
+ return {
273
+ autoload: false,
274
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
275
+ return selectAzureLanguageModel(sdk, modelID, Boolean(options?.["useCompletionUrls"]))
276
+ },
277
+ options: {
278
+ baseURL: resourceName
279
+ ? `https://${resourceName}.cognitiveservices.azure.com/openai${provider.options?.useDeploymentBasedUrls ? "" : "/v1"}`
280
+ : undefined,
281
+ },
282
+ }
283
+ }),
284
+ "amazon-bedrock": Effect.fnUntraced(function* () {
285
+ const providerConfig = (yield* dep.config()).provider?.["amazon-bedrock"]
286
+ const auth = yield* dep.auth("amazon-bedrock")
287
+ const env = yield* dep.env()
288
+
289
+ // Region precedence: 1) config file, 2) env var, 3) default
290
+ const configRegion = providerConfig?.options?.region
291
+ const envRegion = env["AWS_REGION"]
292
+ const defaultRegion = configRegion ?? envRegion ?? "us-east-1"
293
+
294
+ // Profile: config file takes precedence over env var
295
+ const configProfile = providerConfig?.options?.profile
296
+ const envProfile = env["AWS_PROFILE"]
297
+ const profile = configProfile ?? envProfile
298
+
299
+ const awsAccessKeyId = env["AWS_ACCESS_KEY_ID"]
300
+ const configApiKey = providerConfig?.options?.apiKey
301
+
302
+ // TODO: Using process.env directly because Env.set only updates a process.env shallow copy,
303
+ // until the scope of the Env API is clarified (test only or runtime?)
304
+ const awsBearerToken = iife(() => {
305
+ const envToken = process.env.AWS_BEARER_TOKEN_BEDROCK
306
+ if (envToken) return envToken
307
+ if (auth?.type === "api") {
308
+ process.env.AWS_BEARER_TOKEN_BEDROCK = auth.key
309
+ return auth.key
310
+ }
311
+ return undefined
312
+ })
313
+
314
+ const awsWebIdentityTokenFile = env["AWS_WEB_IDENTITY_TOKEN_FILE"]
315
+
316
+ const containerCreds = Boolean(
317
+ process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI || process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI,
318
+ )
319
+
320
+ if (
321
+ !profile &&
322
+ !awsAccessKeyId &&
323
+ !awsBearerToken &&
324
+ !configApiKey &&
325
+ !awsWebIdentityTokenFile &&
326
+ !containerCreds
327
+ )
328
+ return { autoload: false }
329
+
330
+ const { fromNodeProviderChain } = yield* Effect.promise(() => import("@aws-sdk/credential-providers"))
331
+
332
+ const providerOptions: Record<string, any> = {
333
+ region: defaultRegion,
334
+ }
335
+
336
+ // Only use credential chain if no bearer token exists
337
+ // Bearer token takes precedence over credential chain (profiles, access keys, IAM roles, web identity tokens)
338
+ if (!awsBearerToken && !configApiKey) {
339
+ // Build credential provider options (only pass profile if specified)
340
+ const credentialProviderOptions = profile ? { profile } : {}
341
+
342
+ providerOptions.credentialProvider = fromNodeProviderChain(credentialProviderOptions)
343
+ }
344
+
345
+ // Add custom endpoint if specified (endpoint takes precedence over baseURL)
346
+ const endpoint = providerConfig?.options?.endpoint ?? providerConfig?.options?.baseURL
347
+ if (endpoint) {
348
+ providerOptions.baseURL = endpoint
349
+ }
350
+
351
+ return {
352
+ autoload: true,
353
+ options: providerOptions,
354
+ vars(options: Record<string, any>) {
355
+ return { AWS_REGION: options.region ?? defaultRegion }
356
+ },
357
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>, model?: Model) {
358
+ if (model?.api.npm === "@ai-sdk/amazon-bedrock/mantle") return selectBedrockMantleLanguageModel(sdk, modelID)
359
+
360
+ // Skip region prefixing if model already has a cross-region inference profile prefix
361
+ // Models from models.dev may already include prefixes like us., eu., global., etc.
362
+ const crossRegionPrefixes = ["global.", "us.", "eu.", "jp.", "apac.", "au."]
363
+ if (crossRegionPrefixes.some((prefix) => modelID.startsWith(prefix))) {
364
+ return sdk.languageModel(modelID)
365
+ }
366
+
367
+ // Region resolution precedence (highest to lowest):
368
+ // 1. options.region from mervex.json provider config
369
+ // 2. defaultRegion from AWS_REGION environment variable
370
+ // 3. Default "us-east-1" (baked into defaultRegion)
371
+ const region = options?.region ?? defaultRegion
372
+
373
+ let regionPrefix = region.split("-")[0]
374
+
375
+ switch (regionPrefix) {
376
+ case "us": {
377
+ const modelRequiresPrefix = [
378
+ "nova-micro",
379
+ "nova-lite",
380
+ "nova-pro",
381
+ "nova-premier",
382
+ "nova-2",
383
+ "claude",
384
+ "deepseek",
385
+ ].some((m) => modelID.includes(m))
386
+ const isGovCloud = region.startsWith("us-gov")
387
+ if (modelRequiresPrefix && !isGovCloud) {
388
+ modelID = `${regionPrefix}.${modelID}`
389
+ }
390
+ break
391
+ }
392
+ case "eu": {
393
+ const regionRequiresPrefix = [
394
+ "eu-west-1",
395
+ "eu-west-2",
396
+ "eu-west-3",
397
+ "eu-north-1",
398
+ "eu-central-1",
399
+ "eu-south-1",
400
+ "eu-south-2",
401
+ ].some((r) => region.includes(r))
402
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "llama3", "pixtral"].some((m) =>
403
+ modelID.includes(m),
404
+ )
405
+ if (regionRequiresPrefix && modelRequiresPrefix) {
406
+ modelID = `${regionPrefix}.${modelID}`
407
+ }
408
+ break
409
+ }
410
+ case "ap": {
411
+ const isAustraliaRegion = ["ap-southeast-2", "ap-southeast-4"].includes(region)
412
+ const isTokyoRegion = region === "ap-northeast-1"
413
+ if (
414
+ isAustraliaRegion &&
415
+ ["anthropic.claude-sonnet-4-5", "anthropic.claude-haiku"].some((m) => modelID.includes(m))
416
+ ) {
417
+ regionPrefix = "au"
418
+ modelID = `${regionPrefix}.${modelID}`
419
+ } else if (isTokyoRegion) {
420
+ // Tokyo region uses jp. prefix for cross-region inference
421
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "nova-pro"].some((m) =>
422
+ modelID.includes(m),
423
+ )
424
+ if (modelRequiresPrefix) {
425
+ regionPrefix = "jp"
426
+ modelID = `${regionPrefix}.${modelID}`
427
+ }
428
+ } else {
429
+ // Other APAC regions use apac. prefix
430
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "nova-pro"].some((m) =>
431
+ modelID.includes(m),
432
+ )
433
+ if (modelRequiresPrefix) {
434
+ regionPrefix = "apac"
435
+ modelID = `${regionPrefix}.${modelID}`
436
+ }
437
+ }
438
+ break
439
+ }
440
+ }
441
+
442
+ return sdk.languageModel(modelID)
443
+ },
444
+ }
445
+ }),
446
+ llmgateway: () =>
447
+ Effect.succeed({
448
+ autoload: false,
449
+ options: {
450
+ headers: {
451
+ "HTTP-Referer": "https://mervex.ai/",
452
+ "X-Title": "mervex",
453
+ "X-Source": "mervex",
454
+ },
455
+ },
456
+ }),
457
+ openrouter: () =>
458
+ Effect.succeed({
459
+ autoload: false,
460
+ options: {
461
+ headers: {
462
+ "HTTP-Referer": "https://mervex.ai/",
463
+ "X-Title": "mervex",
464
+ },
465
+ },
466
+ }),
467
+ nvidia: (provider) =>
468
+ Effect.succeed({
469
+ autoload: provider.source === "config",
470
+ options: {
471
+ headers: {
472
+ "HTTP-Referer": "https://mervex.ai/",
473
+ "X-Title": "mervex",
474
+ "X-BILLING-INVOKE-ORIGIN": "Mervex",
475
+ },
476
+ },
477
+ }),
478
+ vercel: () =>
479
+ Effect.succeed({
480
+ autoload: false,
481
+ options: {
482
+ headers: {
483
+ "http-referer": "https://mervex.ai/",
484
+ "x-title": "mervex",
485
+ },
486
+ },
487
+ }),
488
+ "google-vertex": Effect.fnUntraced(function* (provider: Info) {
489
+ const env = yield* dep.env()
490
+ // models.dev advertises GOOGLE_VERTEX_PROJECT for Vertex; keep the wider
491
+ // Google Cloud project env names as fallbacks for existing ADC setups.
492
+ const project =
493
+ provider.options?.project ??
494
+ env["GOOGLE_VERTEX_PROJECT"] ??
495
+ env["GOOGLE_CLOUD_PROJECT"] ??
496
+ env["GCP_PROJECT"] ??
497
+ env["GCLOUD_PROJECT"]
498
+
499
+ const location = String(
500
+ provider.options?.location ??
501
+ env["GOOGLE_VERTEX_LOCATION"] ??
502
+ env["GOOGLE_CLOUD_LOCATION"] ??
503
+ env["VERTEX_LOCATION"] ??
504
+ "us-central1",
505
+ )
506
+
507
+ const autoload = Boolean(project)
508
+ if (!autoload) return { autoload: false }
509
+ return {
510
+ autoload: true,
511
+ vars(_options: Record<string, any>) {
512
+ return {
513
+ ...(project && { GOOGLE_VERTEX_PROJECT: project }),
514
+ GOOGLE_VERTEX_LOCATION: location,
515
+ GOOGLE_VERTEX_ENDPOINT: googleVertexEndpoint(location),
516
+ }
517
+ },
518
+ options: {
519
+ project,
520
+ location,
521
+ fetch: async (input: RequestInfo | URL, init?: RequestInit) => {
522
+ const { GoogleAuth } = await import("google-auth-library")
523
+ const auth = new GoogleAuth({ scopes: ["https://www.googleapis.com/auth/cloud-platform"] })
524
+ const client = await auth.getClient()
525
+ const token = await client.getAccessToken()
526
+
527
+ const headers = new Headers(init?.headers)
528
+ headers.set("Authorization", `Bearer ${token.token}`)
529
+
530
+ return fetch(input, { ...init, headers })
531
+ },
532
+ },
533
+ async getModel(sdk: any, modelID: string) {
534
+ const id = String(modelID).trim()
535
+ return sdk.languageModel(id)
536
+ },
537
+ }
538
+ }),
539
+ "google-vertex-anthropic": Effect.fnUntraced(function* () {
540
+ const env = yield* dep.env()
541
+ const project = env["GOOGLE_CLOUD_PROJECT"] ?? env["GCP_PROJECT"] ?? env["GCLOUD_PROJECT"]
542
+ const location = env["GOOGLE_CLOUD_LOCATION"] ?? env["VERTEX_LOCATION"] ?? "global"
543
+ const autoload = Boolean(project)
544
+ if (!autoload) return { autoload: false }
545
+ const baseURL = googleVertexAnthropicBaseURL(project, location)
546
+ return {
547
+ autoload: true,
548
+ options: {
549
+ project,
550
+ location,
551
+ ...(baseURL && { baseURL }),
552
+ },
553
+ async getModel(sdk: any, modelID) {
554
+ const id = String(modelID).trim()
555
+ return sdk.languageModel(id)
556
+ },
557
+ }
558
+ }),
559
+ "sap-ai-core": Effect.fnUntraced(function* () {
560
+ const auth = yield* dep.auth("sap-ai-core")
561
+ // TODO: Using process.env directly because Env.set only updates a shallow copy (not process.env),
562
+ // until the scope of the Env API is clarified (test only or runtime?)
563
+ const envServiceKey = iife(() => {
564
+ const envAICoreServiceKey = process.env.AICORE_SERVICE_KEY
565
+ if (envAICoreServiceKey) return envAICoreServiceKey
566
+ if (auth?.type === "api") {
567
+ process.env.AICORE_SERVICE_KEY = auth.key
568
+ return auth.key
569
+ }
570
+ return undefined
571
+ })
572
+ const deploymentId = process.env.AICORE_DEPLOYMENT_ID
573
+ const resourceGroup = process.env.AICORE_RESOURCE_GROUP
574
+
575
+ return {
576
+ autoload: !!envServiceKey,
577
+ options: envServiceKey ? { deploymentId, resourceGroup } : {},
578
+ async getModel(sdk: any, modelID: string) {
579
+ return sdk(modelID)
580
+ },
581
+ }
582
+ }),
583
+ zenmux: () =>
584
+ Effect.succeed({
585
+ autoload: false,
586
+ options: {
587
+ headers: {
588
+ "HTTP-Referer": "https://mervex.ai/",
589
+ "X-Title": "mervex",
590
+ },
591
+ },
592
+ }),
593
+ gitlab: Effect.fnUntraced(function* (input: Info) {
594
+ const {
595
+ VERSION: GITLAB_PROVIDER_VERSION,
596
+ isWorkflowModel,
597
+ discoverWorkflowModels,
598
+ } = yield* Effect.promise(() => import("gitlab-ai-provider"))
599
+
600
+ const instanceUrl = (yield* dep.get("GITLAB_INSTANCE_URL")) || "https://gitlab.com"
601
+
602
+ const auth = yield* dep.auth(input.id)
603
+ const apiKey = auth?.type === "oauth" ? auth.access : auth?.type === "api" ? auth.key : undefined
604
+ const token = apiKey ?? (yield* dep.get("GITLAB_TOKEN"))
605
+
606
+ const providerConfig = (yield* dep.config()).provider?.["gitlab"]
607
+ const directory = yield* InstanceState.directory
608
+
609
+ const aiGatewayHeaders = {
610
+ "User-Agent": `mervex/${InstallationVersion} gitlab-ai-provider/${GITLAB_PROVIDER_VERSION} (${os.platform()} ${os.release()}; ${os.arch()})`,
611
+ "anthropic-beta": "context-1m-2025-08-07",
612
+ ...providerConfig?.options?.aiGatewayHeaders,
613
+ }
614
+
615
+ const featureFlags = {
616
+ duo_agent_platform_agentic_chat: true,
617
+ duo_agent_platform: true,
618
+ ...providerConfig?.options?.featureFlags,
619
+ }
620
+
621
+ return {
622
+ autoload: !!token,
623
+ options: {
624
+ instanceUrl,
625
+ apiKey: token,
626
+ aiGatewayHeaders,
627
+ featureFlags,
628
+ },
629
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
630
+ if (modelID.startsWith("duo-workflow-")) {
631
+ const workflowRef = typeof options?.workflowRef === "string" ? options.workflowRef : undefined
632
+ // Use the static mapping if it exists, otherwise use duo-workflow with selectedModelRef
633
+ const sdkModelID = isWorkflowModel(modelID) ? modelID : "duo-workflow"
634
+ const workflowDefinition =
635
+ typeof options?.workflowDefinition === "string" ? options.workflowDefinition : undefined
636
+ const model = sdk.workflowChat(sdkModelID, {
637
+ featureFlags,
638
+ workflowDefinition,
639
+ })
640
+ if (workflowRef) {
641
+ model.selectedModelRef = workflowRef
642
+ }
643
+ return model
644
+ }
645
+ return sdk.agenticChat(modelID, {
646
+ aiGatewayHeaders,
647
+ featureFlags,
648
+ })
649
+ },
650
+ async discoverModels(): Promise<Record<string, Model>> {
651
+ if (!apiKey) {
652
+ return {}
653
+ }
654
+
655
+ try {
656
+ const token = apiKey
657
+ const getHeaders = (): Record<string, string> =>
658
+ auth?.type === "api" ? { "PRIVATE-TOKEN": token } : { Authorization: `Bearer ${token}` }
659
+
660
+ const result = await discoverWorkflowModels({ instanceUrl, getHeaders }, { workingDirectory: directory })
661
+
662
+ if (!result.models.length) {
663
+ return {}
664
+ }
665
+
666
+ const models: Record<string, Model> = {}
667
+ for (const m of result.models) {
668
+ if (!input.models[m.id]) {
669
+ models[m.id] = {
670
+ id: ModelV2.ID.make(m.id),
671
+ providerID: ProviderV2.ID.make("gitlab"),
672
+ name: `Agent Platform (${m.name})`,
673
+ family: "",
674
+ api: {
675
+ id: m.id,
676
+ url: instanceUrl,
677
+ npm: "gitlab-ai-provider",
678
+ },
679
+ status: "active",
680
+ headers: {},
681
+ options: { workflowRef: m.ref },
682
+ cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
683
+ limit: { context: m.context, output: m.output },
684
+ capabilities: {
685
+ temperature: false,
686
+ reasoning: true,
687
+ attachment: true,
688
+ toolcall: true,
689
+ input: {
690
+ text: true,
691
+ audio: false,
692
+ image: true,
693
+ video: false,
694
+ pdf: true,
695
+ },
696
+ output: {
697
+ text: true,
698
+ audio: false,
699
+ image: false,
700
+ video: false,
701
+ pdf: false,
702
+ },
703
+ interleaved: false,
704
+ },
705
+ release_date: "",
706
+ variants: {},
707
+ }
708
+ }
709
+ }
710
+
711
+ return models
712
+ } catch (e) {
713
+ return {}
714
+ }
715
+ },
716
+ }
717
+ }),
718
+ "cloudflare-workers-ai": Effect.fnUntraced(function* (input: Info) {
719
+ // When baseURL is already configured (e.g. corporate config routing through a proxy/gateway),
720
+ // skip the account ID check because the URL is already fully specified.
721
+ if (input.options?.baseURL) return { autoload: false }
722
+
723
+ const auth = yield* dep.auth(input.id)
724
+ const env = yield* dep.env()
725
+ const accountId = env["CLOUDFLARE_ACCOUNT_ID"] || (auth?.type === "api" ? auth.metadata?.accountId : undefined)
726
+ if (!accountId)
727
+ return {
728
+ autoload: false,
729
+ async getModel() {
730
+ throw new Error(
731
+ "CLOUDFLARE_ACCOUNT_ID is missing. Set it with: export CLOUDFLARE_ACCOUNT_ID=<your-account-id>",
732
+ )
733
+ },
734
+ }
735
+
736
+ const apiKey = env["CLOUDFLARE_API_KEY"] || (auth?.type === "api" ? auth.key : undefined)
737
+
738
+ return {
739
+ autoload: !!apiKey,
740
+ options: {
741
+ apiKey,
742
+ headers: {
743
+ "User-Agent": `mervex/${InstallationVersion} cloudflare-workers-ai (${os.platform()} ${os.release()}; ${os.arch()})`,
744
+ },
745
+ },
746
+ async getModel(sdk: any, modelID: string) {
747
+ return sdk.languageModel(modelID)
748
+ },
749
+ vars(_options) {
750
+ return {
751
+ CLOUDFLARE_ACCOUNT_ID: accountId,
752
+ }
753
+ },
754
+ }
755
+ }),
756
+ "cloudflare-ai-gateway": Effect.fnUntraced(function* (input: Info) {
757
+ // When baseURL is already configured (e.g. corporate config), skip the ID checks.
758
+ if (input.options?.baseURL) return { autoload: false }
759
+
760
+ const auth = yield* dep.auth(input.id)
761
+ const env = yield* dep.env()
762
+ const accountId = env["CLOUDFLARE_ACCOUNT_ID"] || (auth?.type === "api" ? auth.metadata?.accountId : undefined)
763
+ // The Cloudflare auth prompt stores this value as gatewayId metadata.
764
+ const gateway = env["CLOUDFLARE_GATEWAY_ID"] || (auth?.type === "api" ? auth.metadata?.gatewayId : undefined)
765
+
766
+ if (!accountId || !gateway) {
767
+ const missing = [
768
+ !accountId ? "CLOUDFLARE_ACCOUNT_ID" : undefined,
769
+ !gateway ? "CLOUDFLARE_GATEWAY_ID" : undefined,
770
+ ].filter((x): x is string => Boolean(x))
771
+ return {
772
+ autoload: false,
773
+ async getModel() {
774
+ throw new Error(
775
+ `${missing.join(" and ")} missing. Set with: ${missing.map((x) => `export ${x}=<value>`).join(" && ")}`,
776
+ )
777
+ },
778
+ }
779
+ }
780
+
781
+ // Get API token from env or auth - required for authenticated gateways
782
+ const apiToken =
783
+ env["CLOUDFLARE_API_TOKEN"] || env["CF_AIG_TOKEN"] || (auth?.type === "api" ? auth.key : undefined)
784
+
785
+ if (!apiToken) {
786
+ throw new Error(
787
+ "CLOUDFLARE_API_TOKEN (or CF_AIG_TOKEN) is required for Cloudflare AI Gateway. " +
788
+ "Set it via environment variable or run `mervex auth cloudflare-ai-gateway`.",
789
+ )
790
+ }
791
+
792
+ const { createAiGateway } = yield* Effect.promise(() => import("ai-gateway-provider"))
793
+ const { createUnified } = yield* Effect.promise(() => import("ai-gateway-provider/providers/unified"))
794
+ const { createOpenAI } = yield* Effect.promise(() => import("ai-gateway-provider/providers/openai"))
795
+ const { createAnthropic } = yield* Effect.promise(() => import("ai-gateway-provider/providers/anthropic"))
796
+ const { createOpenAICompatible } = yield* Effect.promise(() => import("@ai-sdk/openai-compatible"))
797
+
798
+ const metadata = iife(() => {
799
+ if (input.options?.metadata) return input.options.metadata
800
+ try {
801
+ return JSON.parse(input.options?.headers?.["cf-aig-metadata"])
802
+ } catch {
803
+ return undefined
804
+ }
805
+ })
806
+ const opts = {
807
+ metadata,
808
+ cacheTtl: input.options?.cacheTtl,
809
+ cacheKey: input.options?.cacheKey,
810
+ skipCache: input.options?.skipCache,
811
+ collectLog: input.options?.collectLog,
812
+ headers: {
813
+ "User-Agent": `mervex/${InstallationVersion} cloudflare-ai-gateway (${os.platform()} ${os.release()}; ${os.arch()})`,
814
+ },
815
+ }
816
+
817
+ const aigateway = createAiGateway({
818
+ accountId,
819
+ gateway,
820
+ apiKey: apiToken,
821
+ ...(Object.values(opts).some((v) => v !== undefined) ? { options: opts } : {}),
822
+ })
823
+ return {
824
+ autoload: true,
825
+ async getModel(_sdk: any, modelID: string, _options?: Record<string, any>) {
826
+ // Model IDs use Unified API format: provider/model (e.g., "anthropic/claude-sonnet-4-5").
827
+ // OpenAI and Anthropic ride their native passthrough routes so agents get the Responses
828
+ // and Messages APIs; new OpenAI models reject tools+reasoning_effort on chat completions.
829
+ // The passthrough wrappers inject a CF_TEMP_TOKEN sentinel that the gateway strips before
830
+ // dispatch, so upstream billing stays on the gateway (Unified Billing / stored BYOK).
831
+ if (modelID.startsWith("openai/")) return aigateway(createOpenAI()(modelID.slice("openai/".length)))
832
+ // models.dev lists Anthropic ids with dotted versions (claude-haiku-4.5); Anthropic's
833
+ // Messages API expects dashed native slugs (claude-haiku-4-5), so translate before passing.
834
+ // No native Anthropic slug contains a dot, so the blanket replacement is lossless here -
835
+ // unlike OpenAI above, whose native ids (e.g. gpt-4.1) keep their dots and must not be touched.
836
+ if (modelID.startsWith("anthropic/"))
837
+ return aigateway(createAnthropic()(modelID.slice("anthropic/".length).replaceAll(".", "-")))
838
+ // Workers AI is the only first-party provider whose upstream is Cloudflare itself, so it is
839
+ // the only one that should receive the Cloudflare token as its upstream Authorization header.
840
+ // The Unified API addresses Workers AI both with the explicit "workers-ai/" prefix and as
841
+ // bare "@cf/..." ids. Third-party providers must not receive the token; they rely on the
842
+ // gateway's stored/BYOK keys instead.
843
+ // Workers AI is Cloudflare's own upstream, so it rides the unified compat route with the
844
+ // Cloudflare token as its upstream Authorization header.
845
+ const isWorkersAi = modelID.startsWith("workers-ai/") || modelID.startsWith("@cf/")
846
+ if (isWorkersAi) return aigateway(createUnified({ apiKey: apiToken })(modelID))
847
+
848
+ // Every other third-party provider (google, xai, alibaba, deepseek, moonshotai, …) is only
849
+ // served by Cloudflare's catalog-aware REST API. The universal/compat gateway route rejects
850
+ // them with "Invalid provider" (the gateway's compat endpoint doesn't front those upstreams),
851
+ // so point an OpenAI-compatible client at the REST endpoint and bind it to the gateway with
852
+ // cf-aig-gateway-id — that keeps requests gateway-routed (analytics/caching/BYOK), not a
853
+ // bypass. models.dev ids (provider/model, dotted) pass through unchanged.
854
+ return createOpenAICompatible({
855
+ name: "cloudflare-ai-gateway",
856
+ baseURL: `https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/v1`,
857
+ apiKey: apiToken,
858
+ headers: { "cf-aig-gateway-id": gateway },
859
+ })(modelID)
860
+ },
861
+ options: {},
862
+ }
863
+ }),
864
+ cerebras: () =>
865
+ Effect.succeed({
866
+ autoload: false,
867
+ options: {
868
+ headers: {
869
+ "X-Cerebras-3rd-Party-Integration": "mervex",
870
+ },
871
+ },
872
+ }),
873
+ kilo: () =>
874
+ Effect.succeed({
875
+ autoload: false,
876
+ options: {
877
+ headers: {
878
+ "HTTP-Referer": "https://mervex.ai/",
879
+ "X-Title": "mervex",
880
+ },
881
+ },
882
+ }),
883
+ "snowflake-cortex": Effect.fnUntraced(function* (input: Info) {
884
+ const env = yield* dep.env()
885
+ const auth = yield* dep.auth(input.id)
886
+
887
+ const account =
888
+ env["SNOWFLAKE_ACCOUNT"] ??
889
+ (auth?.type === "api" ? auth.metadata?.account : undefined) ??
890
+ (auth?.type === "oauth" ? auth.accountId : undefined) ??
891
+ input.options?.account
892
+
893
+ const envToken = env["SNOWFLAKE_CORTEX_TOKEN"] ?? env["SNOWFLAKE_CORTEX_PAT"]
894
+ const apiKeyToken = auth?.type === "api" ? auth.key : undefined
895
+ const oauthToken = auth?.type === "oauth" ? auth.access : undefined
896
+ const configToken = input.options?.token ?? input.options?.apiKey
897
+
898
+ const token = envToken ?? apiKeyToken ?? oauthToken ?? configToken
899
+
900
+ if (!account || !token) {
901
+ const missing = [!account && "SNOWFLAKE_ACCOUNT", !token && "SNOWFLAKE_CORTEX_TOKEN"].filter(Boolean).join(", ")
902
+ return {
903
+ autoload: false,
904
+ async getModel() {
905
+ throw new Error(
906
+ `Snowflake Cortex: missing credentials (${missing}). Provide a bearer token (OAuth, JWT, or PAT) via env var, mervex auth, or provider options.`,
907
+ )
908
+ },
909
+ }
910
+ }
911
+
912
+ const baseURL = `https://${account}.snowflakecomputing.com/api/v2/cortex/v1`
913
+
914
+ const options: Record<string, any> = { baseURL, apiKey: token }
915
+
916
+ // Only skip provider-level fetch when the token is from OAuth with no override.
917
+ // For OAuth tokens, the plugin auth loader's combined fetch handles
918
+ // OAuth refresh + snowflake transformations in one place.
919
+ // For env/config/API-key tokens, the provider fetch applies snowflake
920
+ // transformations directly.
921
+ const useOAuthHandler =
922
+ oauthToken !== undefined && envToken === undefined && apiKeyToken === undefined && configToken === undefined
923
+ if (!useOAuthHandler) {
924
+ options.fetch = async (url: RequestInfo | URL, init?: RequestInit) => {
925
+ if (init?.body && typeof init.body === "string") {
926
+ try {
927
+ const body = JSON.parse(init.body)
928
+ if ("max_tokens" in body) {
929
+ body.max_completion_tokens = body.max_tokens
930
+ delete body.max_tokens
931
+ init = { ...init, body: JSON.stringify(body) }
932
+ }
933
+ } catch {}
934
+ }
935
+
936
+ const response = await fetch(url, init)
937
+
938
+ if (!response.ok && response.status === 400) {
939
+ try {
940
+ const errorData = await response.clone().json()
941
+ const errorMessage = String(errorData.message || errorData.error || "")
942
+ if (errorMessage.toLowerCase().includes("conversation complete")) {
943
+ return new Response(
944
+ JSON.stringify({
945
+ choices: [{ finish_reason: "stop", message: { content: "", role: "assistant" } }],
946
+ }),
947
+ { status: 200, headers: new Headers({ "content-type": "application/json" }) },
948
+ )
949
+ }
950
+ } catch {}
951
+ }
952
+
953
+ if (response.body && response.headers.get("content-type")?.includes("text/event-stream")) {
954
+ const reader = response.body.getReader()
955
+ const encoder = new TextEncoder()
956
+ const decoder = new TextDecoder()
957
+ const stream = new ReadableStream({
958
+ async pull(ctrl) {
959
+ const { done, value } = await reader.read()
960
+ if (done) {
961
+ ctrl.close()
962
+ return
963
+ }
964
+ const text = decoder.decode(value, { stream: true })
965
+ ctrl.enqueue(encoder.encode(text.replace(/"role"\s*:\s*""/g, '"role":"assistant"')))
966
+ },
967
+ cancel() {
968
+ reader.cancel()
969
+ },
970
+ })
971
+ return new Response(stream, { headers: response.headers, status: response.status })
972
+ }
973
+
974
+ return response
975
+ }
976
+ }
977
+
978
+ return {
979
+ autoload: input.source === "config",
980
+ options,
981
+ }
982
+ }),
983
+ }
984
+ }
985
+
986
+ const ProviderApiInfo = Schema.Struct({
987
+ id: Schema.String,
988
+ url: Schema.String,
989
+ npm: Schema.String,
990
+ })
991
+
992
+ const ProviderModalities = Schema.Struct({
993
+ text: Schema.Boolean,
994
+ audio: Schema.Boolean,
995
+ image: Schema.Boolean,
996
+ video: Schema.Boolean,
997
+ pdf: Schema.Boolean,
998
+ })
999
+
1000
+ const ProviderInterleavedField = Schema.Union([
1001
+ Schema.Literals(["reasoning", "reasoning_content", "reasoning_text"]),
1002
+ Schema.String,
1003
+ ])
1004
+
1005
+ const ProviderInterleaved = Schema.Union([
1006
+ Schema.Boolean,
1007
+ Schema.Struct({
1008
+ field: ProviderInterleavedField,
1009
+ }),
1010
+ ])
1011
+
1012
+ const ProviderCapabilities = Schema.Struct({
1013
+ temperature: Schema.Boolean,
1014
+ reasoning: Schema.Boolean,
1015
+ attachment: Schema.Boolean,
1016
+ toolcall: Schema.Boolean,
1017
+ input: ProviderModalities,
1018
+ output: ProviderModalities,
1019
+ interleaved: ProviderInterleaved,
1020
+ })
1021
+
1022
+ const ProviderCacheCost = Schema.Struct({
1023
+ read: Schema.Finite,
1024
+ write: Schema.Finite,
1025
+ })
1026
+
1027
+ const ProviderCostTier = Schema.Struct({
1028
+ input: Schema.Finite,
1029
+ output: Schema.Finite,
1030
+ cache: ProviderCacheCost,
1031
+ tier: Schema.Struct({
1032
+ type: Schema.Literal("context"),
1033
+ size: Schema.Finite,
1034
+ }),
1035
+ })
1036
+
1037
+ const ProviderCost = Schema.Struct({
1038
+ input: Schema.Finite,
1039
+ output: Schema.Finite,
1040
+ cache: ProviderCacheCost,
1041
+ tiers: optional(Schema.Array(ProviderCostTier)),
1042
+ experimentalOver200K: optional(
1043
+ Schema.Struct({
1044
+ input: Schema.Finite,
1045
+ output: Schema.Finite,
1046
+ cache: ProviderCacheCost,
1047
+ }),
1048
+ ),
1049
+ })
1050
+
1051
+ const ProviderLimit = Schema.Struct({
1052
+ context: Schema.Finite,
1053
+ input: optional(Schema.Finite),
1054
+ output: Schema.Finite,
1055
+ })
1056
+
1057
+ export const Model = Schema.Struct({
1058
+ id: ModelV2.ID,
1059
+ providerID: ProviderV2.ID,
1060
+ api: ProviderApiInfo,
1061
+ name: Schema.String,
1062
+ family: optional(Schema.String),
1063
+ capabilities: ProviderCapabilities,
1064
+ cost: ProviderCost,
1065
+ limit: ProviderLimit,
1066
+ status: ModelStatus,
1067
+ options: Schema.Record(Schema.String, Schema.Any),
1068
+ headers: Schema.Record(Schema.String, Schema.String),
1069
+ release_date: Schema.String,
1070
+ variants: optional(Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Any))),
1071
+ }).annotate({ identifier: "Model" })
1072
+ export type Model = Types.DeepMutable<Schema.Schema.Type<typeof Model>>
1073
+
1074
+ export const Info = Schema.Struct({
1075
+ id: ProviderV2.ID,
1076
+ name: Schema.String,
1077
+ source: Schema.Literals(["env", "config", "custom", "api"]),
1078
+ env: Schema.Array(Schema.String),
1079
+ key: optional(Schema.String),
1080
+ options: Schema.Record(Schema.String, Schema.Any),
1081
+ models: Schema.Record(Schema.String, Model),
1082
+ rateLimit: optional(
1083
+ Schema.Struct({
1084
+ rpm: optional(Schema.Number),
1085
+ tpm: optional(Schema.Number),
1086
+ rpd: optional(Schema.Number),
1087
+ tpd: optional(Schema.Number),
1088
+ maxInputTokens: optional(Schema.Number),
1089
+ }),
1090
+ ),
1091
+ }).annotate({ identifier: "Provider" })
1092
+ export type Info = Types.DeepMutable<Schema.Schema.Type<typeof Info>>
1093
+
1094
+ const DefaultModelIDs = Schema.Record(Schema.String, Schema.String)
1095
+
1096
+ export const ListResult = Schema.Struct({
1097
+ all: Schema.Array(Info),
1098
+ default: DefaultModelIDs,
1099
+ connected: Schema.Array(Schema.String),
1100
+ })
1101
+ export type ListResult = Types.DeepMutable<Schema.Schema.Type<typeof ListResult>>
1102
+
1103
+ export const ConfigProvidersResult = Schema.Struct({
1104
+ providers: Schema.Array(Info),
1105
+ default: DefaultModelIDs,
1106
+ })
1107
+ export type ConfigProvidersResult = Types.DeepMutable<Schema.Schema.Type<typeof ConfigProvidersResult>>
1108
+
1109
+ export function toPublicInfo(provider: Info): Info {
1110
+ return JSON.parse(
1111
+ JSON.stringify(
1112
+ {
1113
+ ...provider,
1114
+ models: Object.fromEntries(Object.entries(provider.models).filter(([, model]) => Schema.is(Model)(model))),
1115
+ },
1116
+ (_, value) => {
1117
+ if (typeof value === "function" || typeof value === "symbol" || value === undefined) return undefined
1118
+ if (typeof value === "bigint") return value.toString()
1119
+ return value
1120
+ },
1121
+ ),
1122
+ )
1123
+ }
1124
+
1125
+ export function defaultModelIDs<T extends { models: Record<string, { id: string }> }>(providers: Record<string, T>) {
1126
+ return mapValues(providers, (item) => sort(Object.values(item.models))[0].id)
1127
+ }
1128
+
1129
+ export class ModelNotFoundError extends Schema.TaggedErrorClass<ModelNotFoundError>()("ProviderModelNotFoundError", {
1130
+ providerID: ProviderV2.ID,
1131
+ modelID: ModelV2.ID,
1132
+ suggestions: Schema.optional(Schema.Array(Schema.String)),
1133
+ cause: Schema.optional(Schema.Defect()),
1134
+ }) {
1135
+ override get message() {
1136
+ const suggestions = this.suggestions?.length ? ` Did you mean: ${this.suggestions.join(", ")}?` : ""
1137
+ return `Model not found: ${this.providerID}/${this.modelID}.${suggestions}`
1138
+ }
1139
+
1140
+ static isInstance(input: unknown): input is ModelNotFoundError {
1141
+ return input instanceof ModelNotFoundError
1142
+ }
1143
+ }
1144
+
1145
+ export class InitError extends Schema.TaggedErrorClass<InitError>()("ProviderInitError", {
1146
+ providerID: ProviderV2.ID,
1147
+ cause: Schema.optional(Schema.Defect()),
1148
+ }) {
1149
+ override get message() {
1150
+ return `Failed to initialize provider: ${this.providerID}`
1151
+ }
1152
+
1153
+ static isInstance(input: unknown): input is InitError {
1154
+ return input instanceof InitError
1155
+ }
1156
+ }
1157
+
1158
+ export class NoProvidersError extends Schema.TaggedErrorClass<NoProvidersError>()("ProviderNoProvidersError", {}) {
1159
+ override get message() {
1160
+ return "No providers are available"
1161
+ }
1162
+
1163
+ static isInstance(input: unknown): input is NoProvidersError {
1164
+ return input instanceof NoProvidersError
1165
+ }
1166
+ }
1167
+
1168
+ export class NoModelsError extends Schema.TaggedErrorClass<NoModelsError>()("ProviderNoModelsError", {
1169
+ providerID: ProviderV2.ID,
1170
+ }) {
1171
+ override get message() {
1172
+ return `No models are available for provider: ${this.providerID}`
1173
+ }
1174
+
1175
+ static isInstance(input: unknown): input is NoModelsError {
1176
+ return input instanceof NoModelsError
1177
+ }
1178
+ }
1179
+
1180
+ export type DefaultModelError = ModelNotFoundError | NoProvidersError | NoModelsError
1181
+ export type Error = ModelNotFoundError | InitError | NoProvidersError | NoModelsError
1182
+
1183
+ export interface Interface {
1184
+ readonly list: () => Effect.Effect<Record<ProviderV2.ID, Info>>
1185
+ readonly catalog: () => Effect.Effect<Record<ProviderV2.ID, Info>>
1186
+ readonly getProvider: (providerID: ProviderV2.ID) => Effect.Effect<Info>
1187
+ readonly getModel: (providerID: ProviderV2.ID, modelID: ModelV2.ID) => Effect.Effect<Model, ModelNotFoundError>
1188
+ readonly getLanguage: (model: Model) => Effect.Effect<LanguageModelV3, ModelNotFoundError>
1189
+ readonly closest: (
1190
+ providerID: ProviderV2.ID,
1191
+ query: string[],
1192
+ ) => Effect.Effect<{ providerID: ProviderV2.ID; modelID: string } | undefined>
1193
+ readonly getSmallModel: (providerID: ProviderV2.ID) => Effect.Effect<Model | undefined>
1194
+ readonly defaultModel: () => Effect.Effect<{ providerID: ProviderV2.ID; modelID: ModelV2.ID }, DefaultModelError>
1195
+ }
1196
+
1197
+ interface State {
1198
+ models: Map<string, LanguageModelV3>
1199
+ providers: Record<ProviderV2.ID, Info>
1200
+ catalog: Record<ProviderV2.ID, Info>
1201
+ sdk: Map<string, BundledSDK>
1202
+ modelLoaders: Record<string, CustomModelLoader>
1203
+ varsLoaders: Record<string, CustomVarsLoader>
1204
+ }
1205
+
1206
+ export class Service extends Context.Service<Service, Interface>()("@mervex/Provider") {}
1207
+
1208
+ export const use = serviceUse(Service)
1209
+
1210
+ function cost(c: ModelsDev.Model["cost"]): Model["cost"] {
1211
+ const result: Model["cost"] = {
1212
+ input: c?.input ?? 0,
1213
+ output: c?.output ?? 0,
1214
+ cache: {
1215
+ read: c?.cache_read ?? 0,
1216
+ write: c?.cache_write ?? 0,
1217
+ },
1218
+ }
1219
+ if (c?.tiers) {
1220
+ result.tiers = c.tiers.map((item) => ({
1221
+ input: item.input,
1222
+ output: item.output,
1223
+ cache: {
1224
+ read: item.cache_read ?? 0,
1225
+ write: item.cache_write ?? 0,
1226
+ },
1227
+ tier: item.tier,
1228
+ }))
1229
+ }
1230
+ if (c?.context_over_200k) {
1231
+ result.experimentalOver200K = {
1232
+ cache: {
1233
+ read: c.context_over_200k.cache_read ?? 0,
1234
+ write: c.context_over_200k.cache_write ?? 0,
1235
+ },
1236
+ input: c.context_over_200k.input,
1237
+ output: c.context_over_200k.output,
1238
+ }
1239
+ }
1240
+ return result
1241
+ }
1242
+
1243
+ // Cloudflare AI Gateway routes OpenAI and Anthropic models through their native
1244
+ // passthrough SDKs (Responses / Messages APIs). Resolving the native npm before
1245
+ // variants are computed makes reasoning variants produce payloads the native
1246
+ // SDKs understand (e.g. anthropic `effort` instead of compat `reasoningEffort`).
1247
+ function cloudflareGatewayNpm(providerID: string, modelID: string) {
1248
+ if (providerID !== "cloudflare-ai-gateway") return undefined
1249
+ if (modelID.startsWith("openai/")) return "@ai-sdk/openai"
1250
+ if (modelID.startsWith("anthropic/")) return "@ai-sdk/anthropic"
1251
+ return undefined
1252
+ }
1253
+
1254
+ function fromModelsDevModel(provider: ModelsDev.Provider, model: ModelsDev.Model): Model {
1255
+ const base: Model = {
1256
+ id: ModelV2.ID.make(model.id),
1257
+ providerID: ProviderV2.ID.make(provider.id),
1258
+ name: model.name,
1259
+ family: model.family,
1260
+ api: {
1261
+ id: model.id,
1262
+ url: model.provider?.api ?? provider.api ?? "",
1263
+ npm:
1264
+ cloudflareGatewayNpm(provider.id, model.id) ??
1265
+ model.provider?.npm ??
1266
+ provider.npm ??
1267
+ "@ai-sdk/openai-compatible",
1268
+ },
1269
+ status: model.status ?? "active",
1270
+ headers: {},
1271
+ options: {},
1272
+ cost: cost(model.cost),
1273
+ limit: {
1274
+ context: model.limit.context,
1275
+ input: model.limit.input,
1276
+ output: model.limit.output,
1277
+ },
1278
+ capabilities: {
1279
+ temperature: model.temperature ?? false,
1280
+ reasoning: model.reasoning ?? false,
1281
+ attachment: model.attachment ?? false,
1282
+ toolcall: model.tool_call ?? true,
1283
+ input: {
1284
+ text: model.modalities?.input?.includes("text") ?? false,
1285
+ audio: model.modalities?.input?.includes("audio") ?? false,
1286
+ image: model.modalities?.input?.includes("image") ?? false,
1287
+ video: model.modalities?.input?.includes("video") ?? false,
1288
+ pdf: model.modalities?.input?.includes("pdf") ?? false,
1289
+ },
1290
+ output: {
1291
+ text: model.modalities?.output?.includes("text") ?? false,
1292
+ audio: model.modalities?.output?.includes("audio") ?? false,
1293
+ image: model.modalities?.output?.includes("image") ?? false,
1294
+ video: model.modalities?.output?.includes("video") ?? false,
1295
+ pdf: model.modalities?.output?.includes("pdf") ?? false,
1296
+ },
1297
+ interleaved: typeof model.interleaved === "string" ? { field: model.interleaved } : (model.interleaved ?? false),
1298
+ },
1299
+ release_date: model.release_date ?? "",
1300
+ variants: {},
1301
+ }
1302
+
1303
+ const variants = ProviderTransform.reasoningVariants(model, base) ?? ProviderTransform.variants(base)
1304
+
1305
+ return {
1306
+ ...base,
1307
+ variants: mapValues(variants, (v) => v),
1308
+ }
1309
+ }
1310
+
1311
+ export function fromModelsDevProvider(provider: ModelsDev.Provider): Info {
1312
+ const models: Record<string, Model> = {}
1313
+ for (const [key, model] of Object.entries(provider.models)) {
1314
+ models[key] = fromModelsDevModel(provider, model)
1315
+ for (const [mode, opts] of Object.entries(model.experimental?.modes ?? {})) {
1316
+ const id = `${model.id}-${mode}`
1317
+ const base = fromModelsDevModel(provider, model)
1318
+ models[id] = {
1319
+ ...base,
1320
+ id: ModelV2.ID.make(id),
1321
+ name: `${model.name} ${mode[0].toUpperCase()}${mode.slice(1)}`,
1322
+ cost: opts.cost ? mergeDeep(base.cost, cost(opts.cost)) : base.cost,
1323
+ options: modeOptions(base, opts.provider?.body),
1324
+ headers: opts.provider?.headers ?? base.headers,
1325
+ }
1326
+ }
1327
+ }
1328
+ return {
1329
+ id: ProviderV2.ID.make(provider.id),
1330
+ source: "custom",
1331
+ name: provider.name,
1332
+ env: [...(provider.env ?? [])],
1333
+ options: {},
1334
+ models,
1335
+ }
1336
+ }
1337
+
1338
+ const MERVEX_BASE_URL = "https://api.mervex.cc.cd/v1"
1339
+
1340
+ const GEEKHUB_BASE_URL = "https://api.geekhub.mx/v1"
1341
+
1342
+ function geekhubModel(id: string, name: string, context: number, reasoning = false): Model {
1343
+ return {
1344
+ id: ModelV2.ID.make(id),
1345
+ providerID: ProviderV2.ID.make("geekhub"),
1346
+ name,
1347
+ family: "geekhub-free",
1348
+ api: {
1349
+ id,
1350
+ url: GEEKHUB_BASE_URL,
1351
+ npm: "@ai-sdk/openai-compatible",
1352
+ },
1353
+ status: "active",
1354
+ headers: {},
1355
+ options: {},
1356
+ cost: {
1357
+ input: 0,
1358
+ output: 0,
1359
+ cache: { read: 0, write: 0 },
1360
+ },
1361
+ limit: {
1362
+ context,
1363
+ output: context > 262144 ? 16000 : 8000,
1364
+ },
1365
+ capabilities: {
1366
+ temperature: true,
1367
+ reasoning,
1368
+ attachment: false,
1369
+ toolcall: true,
1370
+ input: { text: true, audio: false, image: false, video: false, pdf: false },
1371
+ output: { text: true, audio: false, image: false, video: false, pdf: false },
1372
+ interleaved: false,
1373
+ },
1374
+ release_date: "2026-09-01",
1375
+ variants: {},
1376
+ }
1377
+ }
1378
+
1379
+ function geekhubProvider(): Info {
1380
+ const defs: Array<[string, string, number, boolean?]> = [
1381
+ ["cohere/north-mini-code:free", "North Mini Code Free", 256000],
1382
+ ["dots/dots-3-note-preview:free", "Dots 3 Note Preview Free", 512000],
1383
+ ["google/gemma-4-26b-a4b-it:free", "Gemma 4 26B A4B IT Free", 262144],
1384
+ ["google/gemma-4-31b-it:free", "Gemma 4 31B IT Free", 262144],
1385
+ ["inclusionai/ling-3.0-flash-fin:free", "Ling 3.0 Flash Fin Free", 262144],
1386
+ ["inclusionai/ling-3.0-flash-sante:free", "Ling 3.0 Flash Sante Free", 262144],
1387
+ ["inclusionai/ling-3.0-flash-vl:free", "Ling 3.0 Flash VL Free", 262144],
1388
+ ["liquid/lfm-2.5-2.6b:free", "LFM 2.5 2.6B Free", 65536],
1389
+ ["nex-agi/nex-n2.5-mini:free", "Nex N2.5 Mini Free", 262144],
1390
+ ["nex-agi/nex-n2.5-pro:free", "Nex N2.5 Pro Free", 262144],
1391
+ ["nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free", "Nemotron 3 Nano Omni Reasoning Free", 256000, true],
1392
+ ["nvidia/nemotron-3-super-120b-a12b:free", "Nemotron 3 Super 120B Free", 262144],
1393
+ ["nvidia/nemotron-3-ultra-550b-a55b:free", "Nemotron 3 Ultra 550B Free", 1000000],
1394
+ ["nvidia/nemotron-3.5-content-safety:free", "Nemotron 3.5 Content Safety Free", 128000],
1395
+ ["nvidia/nemotron-3.5-lightning:free", "Nemotron 3.5 Lightning Free", 1000000],
1396
+ ["poolside/laguna-s-2.1:free", "Laguna S 2.1 Free", 262144],
1397
+ ["poolside/laguna-xs-2.1:free", "Laguna XS 2.1 Free", 262144],
1398
+ ["thinkingmachines/inkling-small:free", "Inkling Small Free", 1048576],
1399
+ ["thinkingmachines/inkling:free", "Inkling Free", 1048576],
1400
+ ["qwen/qwen3.8-27b:free", "Qwen 3.8 27B Free", 262144],
1401
+ ["dots-studio/dots-3-note-preview:free", "Dots 3 Note Preview Free", 512000],
1402
+ ["z-ai/glm-5.2:free", "GLM 5.2 Free", 32768],
1403
+ ]
1404
+ const models: Record<string, Model> = {}
1405
+ for (const [id, name, context, reasoning] of defs) {
1406
+ models[id] = geekhubModel(id, name, context, reasoning ?? false)
1407
+ }
1408
+ for (const model of Object.values(models)) {
1409
+ const variants = ProviderTransform.variants(model)
1410
+ model.variants = mapValues(variants, (v) => v)
1411
+ }
1412
+ return {
1413
+ id: ProviderV2.ID.make("geekhub"),
1414
+ source: "custom",
1415
+ name: "GeekHub",
1416
+ env: ["GEEKHUB_API_KEY"],
1417
+ options: {},
1418
+ models,
1419
+ }
1420
+ }
1421
+
1422
+ function mervexModel(id: string, name: string, opts: {
1423
+ context: number
1424
+ output: number
1425
+ reasoning?: boolean
1426
+ attachment?: boolean
1427
+ costInput?: number
1428
+ costOutput?: number
1429
+ vip?: boolean
1430
+ }): Model {
1431
+ return {
1432
+ id: ModelV2.ID.make(id),
1433
+ providerID: ProviderV2.ID.make("mervex"),
1434
+ name,
1435
+ family: opts.vip ? "mervex-vip" : "mervex",
1436
+ api: {
1437
+ id,
1438
+ url: MERVEX_BASE_URL,
1439
+ npm: "@ai-sdk/openai-compatible",
1440
+ },
1441
+ status: "active",
1442
+ headers: {},
1443
+ options: {},
1444
+ cost: {
1445
+ input: opts.costInput ?? 0,
1446
+ output: opts.costOutput ?? 0,
1447
+ cache: { read: 0, write: 0 },
1448
+ },
1449
+ limit: {
1450
+ context: opts.context,
1451
+ output: opts.output,
1452
+ },
1453
+ capabilities: {
1454
+ temperature: true,
1455
+ reasoning: opts.reasoning ?? false,
1456
+ attachment: opts.attachment ?? false,
1457
+ toolcall: true,
1458
+ input: { text: true, audio: false, image: opts.attachment ?? false, video: false, pdf: opts.attachment ?? false },
1459
+ output: { text: true, audio: false, image: false, video: false, pdf: false },
1460
+ interleaved: false,
1461
+ },
1462
+ release_date: "2026-01-01",
1463
+ variants: {},
1464
+ }
1465
+ }
1466
+
1467
+ type MervexRemoteModel = {
1468
+ id: string
1469
+ name: string
1470
+ tier?: string
1471
+ vipOnly: boolean
1472
+ vision: boolean
1473
+ contextLimit?: number
1474
+ outputLimit?: number
1475
+ }
1476
+
1477
+ const fetchMervexRemoteModels = Effect.fn("Provider.fetchMervexRemoteModels")(function* (baseURL: string) {
1478
+ const response = yield* Effect.tryPromise({
1479
+ try: () =>
1480
+ fetch(`${baseURL.replace(/\/$/, "")}/models`, {
1481
+ signal: AbortSignal.timeout(10000),
1482
+ headers: { Accept: "application/json" },
1483
+ }),
1484
+ catch: () => new Error("mervex models fetch failed"),
1485
+ }).pipe(Effect.catch(() => Effect.succeed(undefined)))
1486
+ if (!response || !response.ok) return undefined
1487
+ const json = yield* Effect.tryPromise({
1488
+ try: () => response.json() as Promise<unknown>,
1489
+ catch: () => new Error("mervex models parse failed"),
1490
+ }).pipe(Effect.catch(() => Effect.succeed(undefined)))
1491
+ if (!isRecord(json) || !Array.isArray(json.data)) return undefined
1492
+ const models: MervexRemoteModel[] = []
1493
+ for (const item of json.data) {
1494
+ if (!isRecord(item) || typeof item.id !== "string") continue
1495
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined)
1496
+ models.push({
1497
+ id: item.id,
1498
+ name: typeof item.name === "string" && item.name ? item.name : item.id,
1499
+ tier: typeof item.tier === "string" ? item.tier : undefined,
1500
+ vipOnly: item.is_vip_only === true,
1501
+ vision: item.supports_vision === true,
1502
+ contextLimit: num(item.context_limit),
1503
+ outputLimit: num(item.output_limit),
1504
+ })
1505
+ }
1506
+ return models.length ? models : undefined
1507
+ })
1508
+
1509
+ function mervexRemoteDefaults(tier: string | undefined): { context: number; output: number; reasoning: boolean } {
1510
+ if (tier === "pro") return { context: 64000, output: 16000, reasoning: true }
1511
+ if (tier === "max") return { context: 64000, output: 16000, reasoning: true }
1512
+ if (tier === "medium" || tier === "chat") return { context: 32000, output: 8000, reasoning: true }
1513
+ return { context: 16000, output: 4000, reasoning: false }
1514
+ }
1515
+
1516
+ // Display policy: model names shown without parenthetical descriptors.
1517
+ function cleanModelName(name: string): string {
1518
+ return name.replace(/\s*\([^()]*\)\s*/g, " ").replace(/\s+/g, " ").trim()
1519
+ }
1520
+
1521
+ function mergeMervexRemoteModels(info: Info, remote: MervexRemoteModel[]) {
1522
+ const remoteIDs = new Set(remote.map((item) => item.id))
1523
+ for (const id of Object.keys(info.models)) {
1524
+ // Server no longer lists this model: hide it via deprecated status.
1525
+ // The existing loader drops deprecated models from listings.
1526
+ if (!remoteIDs.has(id)) info.models[id].status = "deprecated"
1527
+ }
1528
+ for (const item of remote) {
1529
+ const existing = info.models[item.id]
1530
+ if (existing) {
1531
+ existing.name = cleanModelName(item.name)
1532
+ existing.family = item.vipOnly ? "mervex-vip" : "mervex"
1533
+ existing.capabilities.attachment = existing.capabilities.attachment || item.vision
1534
+ existing.capabilities.input.image = existing.capabilities.input.image || item.vision
1535
+ existing.capabilities.input.pdf = existing.capabilities.input.pdf || item.vision
1536
+ // Server is the source of truth for enforced limits; sync them so
1537
+ // requests stay within what the backend accepts.
1538
+ if (item.contextLimit) existing.limit.context = item.contextLimit
1539
+ if (item.outputLimit) existing.limit.output = item.outputLimit
1540
+ continue
1541
+ }
1542
+ const defaults = mervexRemoteDefaults(item.tier)
1543
+ info.models[item.id] = mervexModel(item.id, cleanModelName(item.name), {
1544
+ context: item.contextLimit ?? defaults.context,
1545
+ output: item.outputLimit ?? defaults.output,
1546
+ reasoning: defaults.reasoning,
1547
+ attachment: item.vision,
1548
+ vip: item.vipOnly,
1549
+ })
1550
+ }
1551
+ }
1552
+
1553
+ function mervexProvider(): Info {
1554
+ const models: Record<string, Model> = {
1555
+ "Msrfteam/Mervex-ai-v0.1-lite": mervexModel("Msrfteam/Mervex-ai-v0.1-lite", "Mervex V0.1 Lite", {
1556
+ context: 8000,
1557
+ output: 2000,
1558
+ }),
1559
+ "Msrfteam/Mervex-ai-v0.1": mervexModel("Msrfteam/Mervex-ai-v0.1", "Mervex V0.1", {
1560
+ context: 16000,
1561
+ output: 4000,
1562
+ reasoning: true,
1563
+ attachment: true,
1564
+ }),
1565
+ "Msrfteam/Mervex-ai-v0.1-pro": mervexModel("Msrfteam/Mervex-ai-v0.1-pro", "Mervex V0.1 Pro", {
1566
+ context: 16000,
1567
+ output: 4000,
1568
+ reasoning: true,
1569
+ }),
1570
+ "Msrfteam/Mervex-ai-v0.2": mervexModel("Msrfteam/Mervex-ai-v0.2", "Mervex V0.2", {
1571
+ context: 32000,
1572
+ output: 8000,
1573
+ reasoning: true,
1574
+ attachment: true,
1575
+ }),
1576
+ "Msrfteam/Mervex-ai-v0.2-pro": mervexModel("Msrfteam/Mervex-ai-v0.2-pro", "Mervex V0.2 Pro", {
1577
+ context: 64000,
1578
+ output: 16000,
1579
+ reasoning: true,
1580
+ attachment: true,
1581
+ vip: true,
1582
+ }),
1583
+ "Msrfteam/Mervex-ai-v0.1-mg": mervexModel("Msrfteam/Mervex-ai-v0.1-mg", "Mervex V0.1 MG", {
1584
+ context: 32000,
1585
+ output: 8000,
1586
+ vip: true,
1587
+ }),
1588
+ "Msrfteam/Mervex-ai-v0.1-sch": mervexModel("Msrfteam/Mervex-ai-v0.1-sch", "Mervex V0.1 SCH", {
1589
+ context: 32000,
1590
+ output: 8000,
1591
+ vip: true,
1592
+ }),
1593
+ "Msrfteam/Mervex-ai-v0.1-vd": mervexModel("Msrfteam/Mervex-ai-v0.1-vd", "Mervex V0.1 VD", {
1594
+ context: 32000,
1595
+ output: 8000,
1596
+ vip: true,
1597
+ }),
1598
+ "Msrfteam/Mervex-ai-v0.1-aud": mervexModel("Msrfteam/Mervex-ai-v0.1-aud", "Mervex V0.1 AUD", {
1599
+ context: 32000,
1600
+ output: 8000,
1601
+ vip: true,
1602
+ }),
1603
+ }
1604
+ for (const [id, model] of Object.entries(models)) {
1605
+ const variants = ProviderTransform.variants(model)
1606
+ model.variants = mapValues(variants, (v) => v)
1607
+ }
1608
+ return {
1609
+ id: ProviderV2.ID.make("mervex"),
1610
+ source: "custom",
1611
+ name: "Msr F Team",
1612
+ env: ["MERVEX_API_KEY"],
1613
+ options: {},
1614
+ models,
1615
+ // Cautious free-tier defaults: the backend itself pays per token
1616
+ // (OpenRouter etc.), so guard both request count AND token volume.
1617
+ // VIP users can raise these in mervex.jsonc `provider.mervex.rateLimit`.
1618
+ rateLimit: {
1619
+ rpm: 10,
1620
+ rpd: 200,
1621
+ tpd: 1_000_000,
1622
+ maxInputTokens: 32_768,
1623
+ },
1624
+ }
1625
+ }
1626
+
1627
+ function modeOptions(model: Model, body: Record<string, unknown> | undefined) {
1628
+ if (!body) return model.options
1629
+ const options = Object.fromEntries(
1630
+ Object.entries(body).map(([key, value]) => [key.replace(/_([a-z])/g, (_, char) => char.toUpperCase()), value]),
1631
+ )
1632
+ const reasoning = body.reasoning
1633
+ if (model.api.npm !== "@ai-sdk/openai" || !isRecord(reasoning) || typeof reasoning.mode !== "string") return options
1634
+ const { reasoning: _, ...rest } = options
1635
+ return { ...rest, reasoningMode: reasoning.mode }
1636
+ }
1637
+
1638
+ function modelSuggestions(provider: Info | undefined, modelID: ModelV2.ID, enableExperimentalModels: boolean) {
1639
+ const available = provider
1640
+ ? Object.keys(provider.models).filter((id) => {
1641
+ const model = provider.models[id]
1642
+ if (model.status === "deprecated") return false
1643
+ if (model.status === "alpha" && !enableExperimentalModels) return false
1644
+ return true
1645
+ })
1646
+ : []
1647
+ const fuzzy = fuzzysort.go(modelID, available, { limit: 3, threshold: -10000 }).map((m) => m.target)
1648
+ if (fuzzy.length) return fuzzy
1649
+ const query = modelID
1650
+ .toLowerCase()
1651
+ .split(/[^a-z0-9]+/)
1652
+ .filter((part) => part.length > 1)
1653
+ return sortBy(
1654
+ available
1655
+ .map((id) => ({
1656
+ id,
1657
+ score: query.filter((part) => id.toLowerCase().includes(part)).length,
1658
+ }))
1659
+ .filter((item) => item.score > 0),
1660
+ [(item) => item.score, "desc"],
1661
+ [(item) => item.id, "asc"],
1662
+ )
1663
+ .slice(0, 3)
1664
+ .map((item) => item.id)
1665
+ }
1666
+
1667
+ const layer = Layer.effect(
1668
+ Service,
1669
+ Effect.gen(function* () {
1670
+ const fs = yield* FSUtil.Service
1671
+ const config = yield* Config.Service
1672
+ const auth = yield* Auth.Service
1673
+ const env = yield* Env.Service
1674
+ const plugin = yield* Plugin.Service
1675
+ const modelsDevSvc = yield* ModelsDev.Service
1676
+ const runtimeFlags = yield* RuntimeFlags.Service
1677
+
1678
+ const state = yield* InstanceState.make<State>(() =>
1679
+ Effect.gen(function* () {
1680
+ const bridge = yield* EffectBridge.make()
1681
+ const cfg = yield* config.get()
1682
+ const modelsDev = yield* modelsDevSvc.get()
1683
+ const catalog = mapValues(modelsDev, fromModelsDevProvider)
1684
+ const mervexInfo = mervexProvider()
1685
+ const mervexCfg = (cfg.provider as Record<string, { options?: Record<string, any> }> | undefined)?.["mervex"]
1686
+ const mervexBaseURL =
1687
+ typeof mervexCfg?.options?.baseURL === "string" && mervexCfg.options.baseURL
1688
+ ? mervexCfg.options.baseURL
1689
+ : MERVEX_BASE_URL
1690
+ const remoteMervexModels = yield* fetchMervexRemoteModels(mervexBaseURL).pipe(
1691
+ Effect.catch(() => Effect.succeed(undefined)),
1692
+ )
1693
+ if (remoteMervexModels) mergeMervexRemoteModels(mervexInfo, remoteMervexModels)
1694
+ catalog[mervexInfo.id] = mervexInfo
1695
+ const geekhubInfo = geekhubProvider()
1696
+ catalog[geekhubInfo.id] = geekhubInfo
1697
+ const database = mapValues(catalog, toPublicInfo)
1698
+
1699
+ const providers: Record<ProviderV2.ID, Info> = {} as Record<ProviderV2.ID, Info>
1700
+ const languages = new Map<string, LanguageModelV3>()
1701
+ const modelLoaders: {
1702
+ [providerID: string]: CustomModelLoader
1703
+ } = {}
1704
+ const varsLoaders: {
1705
+ [providerID: string]: CustomVarsLoader
1706
+ } = {}
1707
+ const sdk = new Map<string, BundledSDK>()
1708
+ const discoveryLoaders: {
1709
+ [providerID: string]: CustomDiscoverModels
1710
+ } = {}
1711
+ const dep = {
1712
+ auth: (id: string) => auth.get(id).pipe(Effect.orDie),
1713
+ config: () => config.get(),
1714
+ env: () => env.all(),
1715
+ get: (key: string) => env.get(key),
1716
+ }
1717
+
1718
+ function mergeProvider(providerID: ProviderV2.ID, provider: Partial<Info>) {
1719
+ const existing = providers[providerID]
1720
+ if (existing) {
1721
+ // @ts-expect-error
1722
+ providers[providerID] = mergeDeep(existing, provider)
1723
+ return
1724
+ }
1725
+ const match = database[providerID]
1726
+ if (!match) return
1727
+ // @ts-expect-error
1728
+ providers[providerID] = mergeDeep(match, provider)
1729
+ }
1730
+
1731
+ // load plugins first so config() hook runs before reading cfg.provider
1732
+ const plugins = yield* plugin.list()
1733
+
1734
+ // now read config providers - includes any modifications from plugin config() hook
1735
+ const configProviders = Object.entries(cfg.provider ?? {})
1736
+ const disabled = new Set(cfg.disabled_providers ?? [])
1737
+ const enabled = cfg.enabled_providers ? new Set(cfg.enabled_providers) : null
1738
+
1739
+ function isProviderAllowed(providerID: ProviderV2.ID): boolean {
1740
+ if (enabled && !enabled.has(providerID)) return false
1741
+ if (disabled.has(providerID)) return false
1742
+ return true
1743
+ }
1744
+
1745
+ for (const hook of plugins) {
1746
+ const p = hook.provider
1747
+ const models = p?.models
1748
+ if (!p || !models) continue
1749
+
1750
+ const providerID = ProviderV2.ID.make(p.id)
1751
+ if (disabled.has(providerID)) continue
1752
+
1753
+ const provider = database[providerID]
1754
+ if (!provider) continue
1755
+ const pluginAuth = yield* auth.get(providerID).pipe(Effect.orDie)
1756
+
1757
+ provider.models = yield* Effect.promise(async () => {
1758
+ const next = await models(toPublicInfo(provider), { auth: pluginAuth })
1759
+ return Object.fromEntries(
1760
+ Object.entries(next).map(([id, model]) => [
1761
+ id,
1762
+ {
1763
+ ...model,
1764
+ id: ModelV2.ID.make(id),
1765
+ providerID,
1766
+ },
1767
+ ]),
1768
+ )
1769
+ })
1770
+ }
1771
+
1772
+ // extend database from config
1773
+ for (const [providerID, provider] of configProviders) {
1774
+ const existing = database[providerID]
1775
+ const parsed: Info = {
1776
+ id: ProviderV2.ID.make(providerID),
1777
+ name: provider.name ?? existing?.name ?? providerID,
1778
+ env: provider.env ?? existing?.env ?? [],
1779
+ options: mergeDeep(existing?.options ?? {}, provider.options ?? {}),
1780
+ source: "config",
1781
+ models: existing?.models ?? {},
1782
+ }
1783
+
1784
+ for (const [modelID, model] of Object.entries(provider.models ?? {})) {
1785
+ const existingModel = parsed.models[model.id ?? modelID]
1786
+ const apiID = model.id ?? existingModel?.api.id ?? modelID
1787
+ const apiNpm =
1788
+ model.provider?.npm ??
1789
+ provider.npm ??
1790
+ existingModel?.api.npm ??
1791
+ // Config-defined gateway models bypass fromModelsDevModel, so resolve the
1792
+ // native passthrough npm here before falling back to the catalog default.
1793
+ cloudflareGatewayNpm(providerID, apiID) ??
1794
+ modelsDev[providerID]?.npm ??
1795
+ "@ai-sdk/openai-compatible"
1796
+ const name = iife(() => {
1797
+ if (model.name) return model.name
1798
+ if (model.id && model.id !== modelID) return modelID
1799
+ return existingModel?.name ?? modelID
1800
+ })
1801
+ const parsedModel: Model = {
1802
+ id: ModelV2.ID.make(modelID),
1803
+ api: {
1804
+ id: apiID,
1805
+ npm: apiNpm,
1806
+ url: model.provider?.api ?? provider?.api ?? existingModel?.api.url ?? modelsDev[providerID]?.api ?? "",
1807
+ },
1808
+ status: model.status ?? existingModel?.status ?? "active",
1809
+ name,
1810
+ providerID: ProviderV2.ID.make(providerID),
1811
+ capabilities: {
1812
+ temperature: model.temperature ?? existingModel?.capabilities.temperature ?? false,
1813
+ reasoning: model.reasoning ?? existingModel?.capabilities.reasoning ?? false,
1814
+ attachment: model.attachment ?? existingModel?.capabilities.attachment ?? false,
1815
+ toolcall: model.tool_call ?? existingModel?.capabilities.toolcall ?? true,
1816
+ input: {
1817
+ text: model.modalities?.input?.includes("text") ?? existingModel?.capabilities.input.text ?? true,
1818
+ audio: model.modalities?.input?.includes("audio") ?? existingModel?.capabilities.input.audio ?? false,
1819
+ image: model.modalities?.input?.includes("image") ?? existingModel?.capabilities.input.image ?? false,
1820
+ video: model.modalities?.input?.includes("video") ?? existingModel?.capabilities.input.video ?? false,
1821
+ pdf: model.modalities?.input?.includes("pdf") ?? existingModel?.capabilities.input.pdf ?? false,
1822
+ },
1823
+ output: {
1824
+ text: model.modalities?.output?.includes("text") ?? existingModel?.capabilities.output.text ?? true,
1825
+ audio:
1826
+ model.modalities?.output?.includes("audio") ?? existingModel?.capabilities.output.audio ?? false,
1827
+ image:
1828
+ model.modalities?.output?.includes("image") ?? existingModel?.capabilities.output.image ?? false,
1829
+ video:
1830
+ model.modalities?.output?.includes("video") ?? existingModel?.capabilities.output.video ?? false,
1831
+ pdf: model.modalities?.output?.includes("pdf") ?? existingModel?.capabilities.output.pdf ?? false,
1832
+ },
1833
+ interleaved:
1834
+ (typeof model.interleaved === "string" ? { field: model.interleaved } : model.interleaved) ??
1835
+ existingModel?.capabilities.interleaved ??
1836
+ (!existingModel && apiNpm === "@ai-sdk/openai-compatible" && apiID.includes("deepseek")
1837
+ ? { field: "reasoning_content" }
1838
+ : false),
1839
+ },
1840
+ cost: {
1841
+ input: model?.cost?.input ?? existingModel?.cost?.input ?? 0,
1842
+ output: model?.cost?.output ?? existingModel?.cost?.output ?? 0,
1843
+ cache: {
1844
+ read: model?.cost?.cache_read ?? existingModel?.cost?.cache.read ?? 0,
1845
+ write: model?.cost?.cache_write ?? existingModel?.cost?.cache.write ?? 0,
1846
+ },
1847
+ },
1848
+ options: mergeDeep(existingModel?.options ?? {}, model.options ?? {}),
1849
+ limit: {
1850
+ context: model.limit?.context ?? existingModel?.limit?.context ?? 0,
1851
+ input: model.limit?.input ?? existingModel?.limit?.input,
1852
+ output: model.limit?.output ?? existingModel?.limit?.output ?? 0,
1853
+ },
1854
+ headers: mergeDeep(existingModel?.headers ?? {}, model.headers ?? {}),
1855
+ family: model.family ?? existingModel?.family ?? "",
1856
+ release_date: model.release_date ?? existingModel?.release_date ?? "",
1857
+ variants: {},
1858
+ }
1859
+ const variants =
1860
+ existingModel?.api.npm === parsedModel.api.npm
1861
+ ? (existingModel.variants ?? ProviderTransform.variants(parsedModel))
1862
+ : ProviderTransform.variants(parsedModel)
1863
+ const merged = mergeDeep(variants, model.variants ?? {})
1864
+ parsedModel.variants = mapValues(
1865
+ pickBy(merged, (v) => !v.disabled),
1866
+ (v) => omit(v, ["disabled"]),
1867
+ )
1868
+ parsed.models[modelID] = parsedModel
1869
+ }
1870
+ database[providerID] = parsed
1871
+ }
1872
+
1873
+ // load env
1874
+ const envs = yield* env.all()
1875
+ for (const [id, provider] of Object.entries(database)) {
1876
+ const providerID = ProviderV2.ID.make(id)
1877
+ if (disabled.has(providerID)) continue
1878
+ const apiKey = provider.env.map((item) => envs[item]).find(Boolean)
1879
+ if (!apiKey) continue
1880
+ mergeProvider(providerID, {
1881
+ source: "env",
1882
+ key: provider.env.length === 1 ? apiKey : undefined,
1883
+ })
1884
+ }
1885
+
1886
+ // load apikeys
1887
+ const auths = yield* auth.all().pipe(Effect.orDie)
1888
+ for (const [id, provider] of Object.entries(auths)) {
1889
+ const providerID = ProviderV2.ID.make(id)
1890
+ if (disabled.has(providerID)) continue
1891
+ if (provider.type === "api") {
1892
+ mergeProvider(providerID, {
1893
+ source: "api",
1894
+ key: provider.key,
1895
+ })
1896
+ }
1897
+ }
1898
+
1899
+ // plugin auth loader - database now has entries for config providers
1900
+ for (const plugin of plugins) {
1901
+ if (!plugin.auth) continue
1902
+ const providerID = ProviderV2.ID.make(plugin.auth.provider)
1903
+ if (disabled.has(providerID)) continue
1904
+
1905
+ const stored = yield* auth.get(providerID).pipe(Effect.orDie)
1906
+ if (!stored) continue
1907
+ if (!plugin.auth.loader) continue
1908
+
1909
+ const options = yield* Effect.promise(() =>
1910
+ plugin.auth!.loader!(
1911
+ () => bridge.promise(auth.get(providerID).pipe(Effect.orDie)) as any,
1912
+ toPublicInfo(database[plugin.auth!.provider]),
1913
+ ),
1914
+ )
1915
+ const opts = options ?? {}
1916
+ const patch: Partial<Info> = providers[providerID] ? { options: opts } : { source: "custom", options: opts }
1917
+ mergeProvider(providerID, patch)
1918
+ }
1919
+
1920
+ for (const [id, fn] of Object.entries(custom(dep))) {
1921
+ const providerID = ProviderV2.ID.make(id)
1922
+ if (disabled.has(providerID)) continue
1923
+ const data = database[providerID]
1924
+ if (!data) {
1925
+ continue
1926
+ }
1927
+ const result = yield* fn(data)
1928
+ if (result && (result.autoload || providers[providerID])) {
1929
+ if (result.getModel) modelLoaders[providerID] = result.getModel
1930
+ if (result.vars) varsLoaders[providerID] = result.vars
1931
+ if (result.discoverModels) discoveryLoaders[providerID] = result.discoverModels
1932
+ const opts = result.options ?? {}
1933
+ const patch: Partial<Info> = providers[providerID] ? { options: opts } : { source: "custom", options: opts }
1934
+ mergeProvider(providerID, patch)
1935
+ }
1936
+ }
1937
+
1938
+ // load config - re-apply with updated data
1939
+ for (const [id, provider] of configProviders) {
1940
+ const providerID = ProviderV2.ID.make(id)
1941
+ const partial: Partial<Info> = { source: "config" }
1942
+ if (provider.env) partial.env = provider.env
1943
+ if (provider.name) partial.name = provider.name
1944
+ if (provider.options) partial.options = provider.options
1945
+ if (provider.rateLimit) partial.rateLimit = provider.rateLimit
1946
+ mergeProvider(providerID, partial)
1947
+ }
1948
+
1949
+ const gitlab = ProviderV2.ID.make("gitlab")
1950
+ if (discoveryLoaders[gitlab] && providers[gitlab] && isProviderAllowed(gitlab)) {
1951
+ yield* Effect.promise(async () => {
1952
+ try {
1953
+ const discovered = await discoveryLoaders[gitlab]()
1954
+ for (const [modelID, model] of Object.entries(discovered)) {
1955
+ if (!providers[gitlab].models[modelID]) {
1956
+ providers[gitlab].models[modelID] = model
1957
+ }
1958
+ }
1959
+ } catch (e) {}
1960
+ })
1961
+ }
1962
+
1963
+ for (const [id, provider] of Object.entries(providers)) {
1964
+ const providerID = ProviderV2.ID.make(id)
1965
+ if (!isProviderAllowed(providerID)) {
1966
+ delete providers[providerID]
1967
+ continue
1968
+ }
1969
+
1970
+ const configProvider = cfg.provider?.[providerID]
1971
+
1972
+ for (const [modelID, model] of Object.entries(provider.models)) {
1973
+ model.api.id = model.api.id ?? model.id ?? modelID
1974
+
1975
+ if (
1976
+ // These chat aliases are invalid for the special handling in the
1977
+ // built-in providers below, but custom providers may support them.
1978
+ (modelID === "gpt-5-chat-latest" &&
1979
+ (providerID === ProviderV2.ID.openai ||
1980
+ providerID === ProviderV2.ID.githubCopilot ||
1981
+ providerID === ProviderV2.ID.openrouter)) ||
1982
+ (providerID === ProviderV2.ID.openrouter && modelID === "openai/gpt-5-chat")
1983
+ )
1984
+ delete provider.models[modelID]
1985
+ if (model.status === "alpha" && !runtimeFlags.enableExperimentalModels) delete provider.models[modelID]
1986
+ if (model.status === "deprecated") delete provider.models[modelID]
1987
+ if (
1988
+ (configProvider?.blacklist && configProvider.blacklist.includes(modelID)) ||
1989
+ (configProvider?.whitelist && !configProvider.whitelist.includes(modelID))
1990
+ )
1991
+ delete provider.models[modelID]
1992
+
1993
+ if (model.variants === undefined) {
1994
+ model.variants = mapValues(ProviderTransform.variants(model), (v) => v)
1995
+ }
1996
+
1997
+ const configVariants = configProvider?.models?.[modelID]?.variants
1998
+ if (configVariants && model.variants) {
1999
+ const merged = mergeDeep(model.variants, configVariants)
2000
+ model.variants = mapValues(
2001
+ pickBy(merged, (v) => !v.disabled),
2002
+ (v) => omit(v, ["disabled"]),
2003
+ )
2004
+ }
2005
+ }
2006
+
2007
+ if (Object.keys(provider.models).length === 0) {
2008
+ delete providers[providerID]
2009
+ continue
2010
+ }
2011
+ }
2012
+
2013
+ return {
2014
+ models: languages,
2015
+ providers,
2016
+ catalog,
2017
+ sdk,
2018
+ modelLoaders,
2019
+ varsLoaders,
2020
+ }
2021
+ }),
2022
+ )
2023
+
2024
+ const list = Effect.fn("Provider.list")(() => InstanceState.use(state, (s) => s.providers))
2025
+
2026
+ const catalog = Effect.fn("Provider.catalog")(() => InstanceState.use(state, (s) => s.catalog))
2027
+
2028
+ async function resolveSDK(
2029
+ model: Model,
2030
+ s: State,
2031
+ envs: Record<string, string | undefined>,
2032
+ globalProxy?: ConfigV1.Info["proxy"],
2033
+ providerProxy?: ConfigV1.Info["proxy"],
2034
+ ) {
2035
+ try {
2036
+ const provider = s.providers[model.providerID]
2037
+ const options = { ...provider.options }
2038
+
2039
+ if (
2040
+ model.providerID === "google-vertex" &&
2041
+ model.api.npm === "@ai-sdk/google-vertex/anthropic" &&
2042
+ !options.baseURL
2043
+ ) {
2044
+ const baseURL = googleVertexAnthropicBaseURL(
2045
+ typeof options.project === "string" ? options.project : undefined,
2046
+ typeof options.location === "string" ? options.location : undefined,
2047
+ )
2048
+ if (baseURL) options.baseURL = baseURL
2049
+ }
2050
+
2051
+ if (model.providerID === "google-vertex" && !model.api.npm.includes("@ai-sdk/openai-compatible")) {
2052
+ delete options.fetch
2053
+ }
2054
+
2055
+ if (model.api.npm.includes("@ai-sdk/openai-compatible") && options["includeUsage"] !== false) {
2056
+ options["includeUsage"] = true
2057
+ }
2058
+
2059
+ const baseURL = iife(() => {
2060
+ let url =
2061
+ typeof options["baseURL"] === "string" && options["baseURL"] !== "" ? options["baseURL"] : model.api.url
2062
+ if (!url) return
2063
+
2064
+ const loader = s.varsLoaders[model.providerID]
2065
+ if (loader) {
2066
+ const vars = loader(options)
2067
+ for (const [key, value] of Object.entries(vars)) {
2068
+ const field = "${" + key + "}"
2069
+ url = url.replaceAll(field, value)
2070
+ }
2071
+ }
2072
+
2073
+ url = url.replace(/\$\{([^}]+)\}/g, (item, key) => {
2074
+ const val = envs[String(key)]
2075
+ return val ?? item
2076
+ })
2077
+ return url
2078
+ })
2079
+
2080
+ if (baseURL !== undefined) options["baseURL"] = baseURL
2081
+ if (options["apiKey"] === undefined && provider.key) options["apiKey"] = provider.key
2082
+ if (model.headers)
2083
+ options["headers"] = {
2084
+ ...options["headers"],
2085
+ ...model.headers,
2086
+ }
2087
+
2088
+ const key = Hash.fast(
2089
+ JSON.stringify({
2090
+ providerID: model.providerID,
2091
+ npm: model.api.npm,
2092
+ options,
2093
+ }),
2094
+ )
2095
+ const existing = s.sdk.get(key)
2096
+ if (existing) return existing
2097
+
2098
+ const customFetch = options["fetch"]
2099
+ const chunkTimeout = options["chunkTimeout"]
2100
+ const headerTimeout = options["headerTimeout"]
2101
+ delete options["chunkTimeout"]
2102
+ delete options["headerTimeout"]
2103
+
2104
+ const proxyConfig = providerProxy ?? globalProxy
2105
+ let proxyAgent: ProxyAgent | undefined
2106
+ if (proxyConfig) {
2107
+ const url = proxyConfig.https ?? proxyConfig.http
2108
+ if (url) {
2109
+ proxyAgent = new ProxyAgent({
2110
+ uri: url,
2111
+ requestTls: { rejectUnauthorized: true },
2112
+ })
2113
+ }
2114
+ }
2115
+
2116
+ options["fetch"] = async (input: any, init?: BunFetchRequestInit) => {
2117
+ const fetchFn = customFetch ?? fetch
2118
+ const opts = init ?? {}
2119
+ const chunkAbortCtl = typeof chunkTimeout === "number" && chunkTimeout > 0 ? new AbortController() : undefined
2120
+ const headerTimeoutMs = headerTimeout === false ? undefined : headerTimeout
2121
+ const headerTimeoutCtl = typeof headerTimeoutMs === "number" ? timeoutController(headerTimeoutMs) : undefined
2122
+ const signals: AbortSignal[] = []
2123
+
2124
+ if (opts.signal) signals.push(opts.signal)
2125
+ if (chunkAbortCtl) signals.push(chunkAbortCtl.signal)
2126
+ if (headerTimeoutCtl) signals.push(headerTimeoutCtl.signal)
2127
+ if (options["timeout"] !== undefined && options["timeout"] !== null && options["timeout"] !== false)
2128
+ signals.push(AbortSignal.timeout(options["timeout"]))
2129
+
2130
+ const combined = signals.length === 0 ? null : signals.length === 1 ? signals[0] : AbortSignal.any(signals)
2131
+ if (combined) opts.signal = combined
2132
+
2133
+ if (proxyAgent) {
2134
+ // @ts-ignore undici dispatcher
2135
+ opts.dispatcher = proxyAgent
2136
+ }
2137
+
2138
+ const res = await fetchFn(input, {
2139
+ ...opts,
2140
+ // @ts-ignore see here: https://github.com/oven-sh/bun/issues/16682
2141
+ timeout: false,
2142
+ }).finally(() => headerTimeoutCtl?.clear())
2143
+
2144
+ if (!chunkAbortCtl) return res
2145
+ return wrapSSE(res, chunkTimeout, chunkAbortCtl)
2146
+ }
2147
+
2148
+ const bundledLoader = BUNDLED_PROVIDERS[model.api.npm]
2149
+ if (bundledLoader) {
2150
+ const factory = await bundledLoader()
2151
+ const loaded = factory({
2152
+ name: model.providerID,
2153
+ ...options,
2154
+ })
2155
+ s.sdk.set(key, loaded)
2156
+ return loaded as SDK
2157
+ }
2158
+
2159
+ const installedPath = await (async () => {
2160
+ if (model.api.npm.startsWith("file://")) {
2161
+ return model.api.npm
2162
+ }
2163
+ const item = await Npm.add(model.api.npm)
2164
+ if (!item.entrypoint) throw new Error(`Package ${model.api.npm} has no import entrypoint`)
2165
+ return item.entrypoint
2166
+ })()
2167
+
2168
+ // `installedPath` is a local entry path or an existing `file://` URL. Normalize
2169
+ // only path inputs so Node on Windows accepts the dynamic import.
2170
+ const importSpec = installedPath.startsWith("file://") ? installedPath : pathToFileURL(installedPath).href
2171
+ const mod = await import(importSpec)
2172
+
2173
+ const fn = mod[Object.keys(mod).find((key) => key.startsWith("create"))!]
2174
+ const loaded = fn({
2175
+ name: model.providerID,
2176
+ ...options,
2177
+ })
2178
+ s.sdk.set(key, loaded)
2179
+ return loaded as SDK
2180
+ } catch (e) {
2181
+ throw new InitError({ providerID: model.providerID, cause: e })
2182
+ }
2183
+ }
2184
+
2185
+ const getProvider = Effect.fn("Provider.getProvider")((providerID: ProviderV2.ID) =>
2186
+ InstanceState.use(state, (s) => s.providers[providerID]),
2187
+ )
2188
+
2189
+ const getModel = Effect.fn("Provider.getModel")(function* (providerID: ProviderV2.ID, modelID: ModelV2.ID) {
2190
+ const s = yield* InstanceState.get(state)
2191
+ const provider = s.providers[providerID]
2192
+ if (!provider) {
2193
+ const catalogProvider = s.catalog[providerID]
2194
+ const suggestions = catalogProvider
2195
+ ? modelSuggestions(catalogProvider, modelID, runtimeFlags.enableExperimentalModels)
2196
+ : fuzzysort
2197
+ .go(providerID, Object.keys({ ...s.catalog, ...s.providers }), { limit: 3, threshold: -10000 })
2198
+ .map((m) => m.target)
2199
+ return yield* new ModelNotFoundError({ providerID, modelID, suggestions })
2200
+ }
2201
+
2202
+ const info = provider.models[modelID]
2203
+ if (!info) {
2204
+ const current = modelSuggestions(provider, modelID, runtimeFlags.enableExperimentalModels)
2205
+ const suggestions = current.length
2206
+ ? current
2207
+ : modelSuggestions(s.catalog[providerID], modelID, runtimeFlags.enableExperimentalModels)
2208
+ return yield* new ModelNotFoundError({ providerID, modelID, suggestions })
2209
+ }
2210
+ return info
2211
+ })
2212
+
2213
+ const getLanguage = Effect.fn("Provider.getLanguage")(function* (model: Model) {
2214
+ const s = yield* InstanceState.get(state)
2215
+ const envs = yield* env.all()
2216
+ const cfg = yield* config.get()
2217
+ const key = `${model.providerID}/${model.id}`
2218
+ if (s.models.has(key)) return s.models.get(key)!
2219
+
2220
+ const provider = s.providers[model.providerID]
2221
+ return yield* EffectPromise.refineRejection(
2222
+ async () => {
2223
+ const sdk = await resolveSDK(model, s, envs, cfg.proxy, cfg.provider?.[model.providerID]?.proxy)
2224
+ const language = s.modelLoaders[model.providerID]
2225
+ ? await s.modelLoaders[model.providerID](
2226
+ sdk,
2227
+ model.api.id,
2228
+ {
2229
+ ...provider.options,
2230
+ ...model.options,
2231
+ },
2232
+ model,
2233
+ )
2234
+ : sdk.languageModel(model.api.id)
2235
+ s.models.set(key, language)
2236
+ return language
2237
+ },
2238
+ (cause) =>
2239
+ cause instanceof NoSuchModelError
2240
+ ? new ModelNotFoundError({ modelID: model.id, providerID: model.providerID, cause })
2241
+ : undefined,
2242
+ )
2243
+ })
2244
+
2245
+ const closest = Effect.fn("Provider.closest")(function* (providerID: ProviderV2.ID, query: string[]) {
2246
+ const s = yield* InstanceState.get(state)
2247
+ const provider = s.providers[providerID]
2248
+ if (!provider) return undefined
2249
+ for (const item of query) {
2250
+ for (const modelID of Object.keys(provider.models)) {
2251
+ if (modelID.includes(item)) return { providerID, modelID }
2252
+ }
2253
+ }
2254
+ return undefined
2255
+ })
2256
+
2257
+ const getSmallModel = Effect.fn("Provider.getSmallModel")(function* (providerID: ProviderV2.ID) {
2258
+ const cfg = yield* config.get()
2259
+
2260
+ if (cfg.small_model) {
2261
+ const parsed = parseModel(cfg.small_model)
2262
+ return yield* getModel(parsed.providerID, parsed.modelID).pipe(
2263
+ Effect.catchTag("ProviderModelNotFoundError", () => Effect.succeed(undefined)),
2264
+ )
2265
+ }
2266
+
2267
+ const s = yield* InstanceState.get(state)
2268
+ const provider = s.providers[providerID]
2269
+ if (!provider) return undefined
2270
+
2271
+ const experimental = yield* plugin.trigger<"experimental.provider.small_model">(
2272
+ "experimental.provider.small_model",
2273
+ { provider: toPublicInfo(provider) },
2274
+ { model: undefined },
2275
+ )
2276
+ if (experimental.model) {
2277
+ return {
2278
+ ...experimental.model,
2279
+ id: ModelV2.ID.make(experimental.model.id),
2280
+ providerID: ProviderV2.ID.make(experimental.model.providerID),
2281
+ }
2282
+ }
2283
+
2284
+ // TODO: Remove these provider-specific assumptions once model syncing reliably reports available deployments.
2285
+ if (providerID === ProviderV2.ID.azure || providerID === ProviderV2.ID.make("azure-cognitive-services")) {
2286
+ return undefined
2287
+ }
2288
+
2289
+ const priority = providerID.startsWith("mervex")
2290
+ ? ["gpt-nano", ...smallModelFamilyPriority]
2291
+ : providerID.startsWith("mervex")
2292
+ ? ["gpt-nano"]
2293
+ : providerID.startsWith("deleted-provider")
2294
+ ? ["gpt-mini", ...smallModelFamilyPriority]
2295
+ : smallModelFamilyPriority
2296
+ const models = sortBy(
2297
+ Object.values(provider.models),
2298
+ [(model) => model.release_date, "desc"],
2299
+ [(model) => model.id, "desc"],
2300
+ )
2301
+ for (const family of priority) {
2302
+ const candidates = models.filter((model) => model.family === family)
2303
+ if (providerID === ProviderV2.ID.amazonBedrock) {
2304
+ const crossRegionPrefixes = ["global.", "us.", "eu."]
2305
+
2306
+ const globalMatch = candidates.find((model) => model.id.startsWith("global."))
2307
+ if (globalMatch) return globalMatch
2308
+
2309
+ const region = provider.options?.region
2310
+ if (region) {
2311
+ const regionPrefix = region.split("-")[0]
2312
+ if (regionPrefix === "us" || regionPrefix === "eu") {
2313
+ const regionalMatch = candidates.find((model) => model.id.startsWith(`${regionPrefix}.`))
2314
+ if (regionalMatch) return regionalMatch
2315
+ }
2316
+ }
2317
+
2318
+ const unprefixed = candidates.find((model) => !crossRegionPrefixes.some((p) => model.id.startsWith(p)))
2319
+ if (unprefixed) return unprefixed
2320
+ continue
2321
+ }
2322
+ if (candidates[0]) return candidates[0]
2323
+ }
2324
+
2325
+ return undefined
2326
+ })
2327
+
2328
+ const defaultModel = Effect.fn("Provider.defaultModel")(function* () {
2329
+ const cfg = yield* config.get()
2330
+ if (cfg.model) return parseModel(cfg.model)
2331
+
2332
+ const s = yield* InstanceState.get(state)
2333
+ const recent = yield* fs.readJson(path.join(Global.Path.state, "model.json")).pipe(
2334
+ Effect.map((x): { providerID: ProviderV2.ID; modelID: ModelV2.ID }[] => {
2335
+ if (!isRecord(x) || !Array.isArray(x.recent)) return []
2336
+ return x.recent.flatMap((item) => {
2337
+ if (!isRecord(item)) return []
2338
+ if (typeof item.providerID !== "string") return []
2339
+ if (typeof item.modelID !== "string") return []
2340
+ return [{ providerID: ProviderV2.ID.make(item.providerID), modelID: ModelV2.ID.make(item.modelID) }]
2341
+ })
2342
+ }),
2343
+ Effect.catch(() => Effect.succeed([] as { providerID: ProviderV2.ID; modelID: ModelV2.ID }[])),
2344
+ )
2345
+ for (const entry of recent) {
2346
+ const provider = s.providers[entry.providerID]
2347
+ if (!provider) continue
2348
+ if (!provider.models[entry.modelID]) continue
2349
+ return { providerID: entry.providerID, modelID: entry.modelID }
2350
+ }
2351
+
2352
+ const configured = Object.keys(cfg.provider ?? {})
2353
+ const allProviders = Object.values(s.providers).sort((a, b) => {
2354
+ if (a.id === "mervex") return -1
2355
+ if (b.id === "mervex") return 1
2356
+ if (a.id === "mervex") return -1
2357
+ if (b.id === "mervex") return 1
2358
+ return 0
2359
+ })
2360
+ const provider = allProviders.find((p) => configured.length === 0 || configured.includes(p.id))
2361
+ if (!provider) return yield* new NoProvidersError()
2362
+ const [model] = sort(Object.values(provider.models))
2363
+ if (!model) return yield* new NoModelsError({ providerID: provider.id })
2364
+ return {
2365
+ providerID: provider.id,
2366
+ modelID: model.id,
2367
+ }
2368
+ })
2369
+
2370
+ return Service.of({ list, catalog, getProvider, getModel, getLanguage, closest, getSmallModel, defaultModel })
2371
+ }),
2372
+ )
2373
+
2374
+ const priority = ["mervex-ai", "gpt-5", "claude-sonnet-4", "big-pickle", "gemini-3-pro"]
2375
+ const smallModelFamilyPriority = ["gemini-flash", "gpt-nano", "claude-haiku"]
2376
+ export function sort<T extends { id: string }>(models: T[]) {
2377
+ return sortBy(
2378
+ models,
2379
+ [(model) => priority.findIndex((filter) => model.id.includes(filter)), "desc"],
2380
+ [(model) => (model.id.includes("latest") ? 0 : 1), "asc"],
2381
+ [(model) => model.id, "desc"],
2382
+ )
2383
+ }
2384
+
2385
+ export function parseModel(model: string) {
2386
+ const [providerID, ...rest] = model.split("/")
2387
+ return {
2388
+ providerID: ProviderV2.ID.make(providerID),
2389
+ modelID: ModelV2.ID.make(rest.join("/")),
2390
+ }
2391
+ }
2392
+
2393
+ export const node = LayerNode.make({
2394
+ service: Service,
2395
+ layer: layer,
2396
+ deps: [FSUtil.node, Config.node, Auth.node, Env.node, Plugin.node, ModelsDev.node, RuntimeFlags.node],
2397
+ })
2398
+
2399
+ export * as Provider from "./provider"