mccode-ai 1.18.21

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