koro-ai 1.0.0

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 (670) hide show
  1. package/AGENTS.md +69 -0
  2. package/BUN_SHELL_MIGRATION_PLAN.md +136 -0
  3. package/Dockerfile +18 -0
  4. package/README.md +15 -0
  5. package/bin/koro +16 -0
  6. package/bin/opencode +179 -0
  7. package/bunfig.toml +7 -0
  8. package/drizzle.config.ts +10 -0
  9. package/git +0 -0
  10. package/migration/20260127222353_familiar_lady_ursula/migration.sql +90 -0
  11. package/migration/20260127222353_familiar_lady_ursula/snapshot.json +796 -0
  12. package/migration/20260211171708_add_project_commands/migration.sql +1 -0
  13. package/migration/20260211171708_add_project_commands/snapshot.json +806 -0
  14. package/migration/20260213144116_wakeful_the_professor/migration.sql +11 -0
  15. package/migration/20260213144116_wakeful_the_professor/snapshot.json +897 -0
  16. package/migration/20260225215848_workspace/migration.sql +7 -0
  17. package/migration/20260225215848_workspace/snapshot.json +959 -0
  18. package/migration/20260227213759_add_session_workspace_id/migration.sql +2 -0
  19. package/migration/20260227213759_add_session_workspace_id/snapshot.json +983 -0
  20. package/migration/20260228203230_blue_harpoon/migration.sql +17 -0
  21. package/migration/20260228203230_blue_harpoon/snapshot.json +1102 -0
  22. package/migration/20260303231226_add_workspace_fields/migration.sql +5 -0
  23. package/migration/20260303231226_add_workspace_fields/snapshot.json +1013 -0
  24. package/migration/20260309230000_move_org_to_state/migration.sql +3 -0
  25. package/migration/20260309230000_move_org_to_state/snapshot.json +1156 -0
  26. package/migration/20260312043431_session_message_cursor/migration.sql +4 -0
  27. package/migration/20260312043431_session_message_cursor/snapshot.json +1168 -0
  28. package/migration/20260323234822_events/migration.sql +13 -0
  29. package/migration/20260323234822_events/snapshot.json +1271 -0
  30. package/package.json +163 -0
  31. package/parsers-config.ts +290 -0
  32. package/script/build-node.ts +56 -0
  33. package/script/build.ts +276 -0
  34. package/script/check-migrations.ts +16 -0
  35. package/script/postinstall.mjs +131 -0
  36. package/script/publish.ts +181 -0
  37. package/script/schema.ts +63 -0
  38. package/script/seed-e2e.ts +60 -0
  39. package/script/upgrade-opentui.ts +64 -0
  40. package/specs/effect-migration.md +294 -0
  41. package/specs/tui-plugins.md +436 -0
  42. package/src/account/account.sql.ts +39 -0
  43. package/src/account/index.ts +424 -0
  44. package/src/account/repo.ts +163 -0
  45. package/src/account/schema.ts +91 -0
  46. package/src/acp/README.md +174 -0
  47. package/src/acp/agent.ts +1763 -0
  48. package/src/acp/session.ts +116 -0
  49. package/src/acp/types.ts +24 -0
  50. package/src/agent/agent.ts +476 -0
  51. package/src/agent/generate.txt +75 -0
  52. package/src/agent/prompt/compaction.txt +15 -0
  53. package/src/agent/prompt/explore.txt +18 -0
  54. package/src/agent/prompt/summary.txt +11 -0
  55. package/src/agent/prompt/title.txt +44 -0
  56. package/src/auth/index.ts +109 -0
  57. package/src/bus/bus-event.ts +40 -0
  58. package/src/bus/global.ts +10 -0
  59. package/src/bus/index.ts +185 -0
  60. package/src/cli/bootstrap.ts +17 -0
  61. package/src/cli/cmd/account.ts +257 -0
  62. package/src/cli/cmd/acp.ts +70 -0
  63. package/src/cli/cmd/agent.ts +245 -0
  64. package/src/cli/cmd/cmd.ts +7 -0
  65. package/src/cli/cmd/db.ts +119 -0
  66. package/src/cli/cmd/debug/agent.ts +167 -0
  67. package/src/cli/cmd/debug/config.ts +16 -0
  68. package/src/cli/cmd/debug/file.ts +97 -0
  69. package/src/cli/cmd/debug/index.ts +48 -0
  70. package/src/cli/cmd/debug/lsp.ts +53 -0
  71. package/src/cli/cmd/debug/ripgrep.ts +87 -0
  72. package/src/cli/cmd/debug/scrap.ts +16 -0
  73. package/src/cli/cmd/debug/skill.ts +16 -0
  74. package/src/cli/cmd/debug/snapshot.ts +52 -0
  75. package/src/cli/cmd/export.ts +89 -0
  76. package/src/cli/cmd/generate.ts +38 -0
  77. package/src/cli/cmd/github.ts +1646 -0
  78. package/src/cli/cmd/import.ts +207 -0
  79. package/src/cli/cmd/mcp.ts +754 -0
  80. package/src/cli/cmd/models.ts +78 -0
  81. package/src/cli/cmd/plug.ts +233 -0
  82. package/src/cli/cmd/pr.ts +127 -0
  83. package/src/cli/cmd/providers.ts +478 -0
  84. package/src/cli/cmd/run.ts +676 -0
  85. package/src/cli/cmd/serve.ts +24 -0
  86. package/src/cli/cmd/session.ts +159 -0
  87. package/src/cli/cmd/stats.ts +410 -0
  88. package/src/cli/cmd/tui/app.tsx +919 -0
  89. package/src/cli/cmd/tui/attach.ts +88 -0
  90. package/src/cli/cmd/tui/component/border.tsx +21 -0
  91. package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
  92. package/src/cli/cmd/tui/component/dialog-command.tsx +171 -0
  93. package/src/cli/cmd/tui/component/dialog-import-share.tsx +118 -0
  94. package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
  95. package/src/cli/cmd/tui/component/dialog-model.tsx +179 -0
  96. package/src/cli/cmd/tui/component/dialog-provider.tsx +329 -0
  97. package/src/cli/cmd/tui/component/dialog-session-list.tsx +108 -0
  98. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
  99. package/src/cli/cmd/tui/component/dialog-skill.tsx +36 -0
  100. package/src/cli/cmd/tui/component/dialog-stash.tsx +87 -0
  101. package/src/cli/cmd/tui/component/dialog-status.tsx +168 -0
  102. package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
  103. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
  104. package/src/cli/cmd/tui/component/dialog-variant.tsx +39 -0
  105. package/src/cli/cmd/tui/component/dialog-workspace-list.tsx +320 -0
  106. package/src/cli/cmd/tui/component/error-component.tsx +92 -0
  107. package/src/cli/cmd/tui/component/logo.tsx +85 -0
  108. package/src/cli/cmd/tui/component/plugin-route-missing.tsx +14 -0
  109. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +672 -0
  110. package/src/cli/cmd/tui/component/prompt/frecency.tsx +90 -0
  111. package/src/cli/cmd/tui/component/prompt/history.tsx +108 -0
  112. package/src/cli/cmd/tui/component/prompt/index.tsx +1310 -0
  113. package/src/cli/cmd/tui/component/prompt/part.ts +16 -0
  114. package/src/cli/cmd/tui/component/prompt/stash.tsx +101 -0
  115. package/src/cli/cmd/tui/component/spinner.tsx +24 -0
  116. package/src/cli/cmd/tui/component/startup-loading.tsx +63 -0
  117. package/src/cli/cmd/tui/component/task-panel.tsx +44 -0
  118. package/src/cli/cmd/tui/component/textarea-keybindings.ts +73 -0
  119. package/src/cli/cmd/tui/component/todo-item.tsx +32 -0
  120. package/src/cli/cmd/tui/component/token-bar.tsx +60 -0
  121. package/src/cli/cmd/tui/component/workspace/dialog-session-list.tsx +151 -0
  122. package/src/cli/cmd/tui/context/args.tsx +15 -0
  123. package/src/cli/cmd/tui/context/directory.ts +13 -0
  124. package/src/cli/cmd/tui/context/exit.tsx +60 -0
  125. package/src/cli/cmd/tui/context/helper.tsx +25 -0
  126. package/src/cli/cmd/tui/context/keybind.tsx +105 -0
  127. package/src/cli/cmd/tui/context/kv.tsx +52 -0
  128. package/src/cli/cmd/tui/context/local.tsx +412 -0
  129. package/src/cli/cmd/tui/context/plugin-keybinds.ts +41 -0
  130. package/src/cli/cmd/tui/context/prompt.tsx +18 -0
  131. package/src/cli/cmd/tui/context/route.tsx +52 -0
  132. package/src/cli/cmd/tui/context/sdk.tsx +128 -0
  133. package/src/cli/cmd/tui/context/sync.tsx +504 -0
  134. package/src/cli/cmd/tui/context/theme/aura.json +69 -0
  135. package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
  136. package/src/cli/cmd/tui/context/theme/carbonfox.json +248 -0
  137. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +233 -0
  138. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +233 -0
  139. package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
  140. package/src/cli/cmd/tui/context/theme/cobalt2.json +228 -0
  141. package/src/cli/cmd/tui/context/theme/cursor.json +249 -0
  142. package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
  143. package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
  144. package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
  145. package/src/cli/cmd/tui/context/theme/github.json +233 -0
  146. package/src/cli/cmd/tui/context/theme/gruvbox.json +242 -0
  147. package/src/cli/cmd/tui/context/theme/gtr.json +245 -0
  148. package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
  149. package/src/cli/cmd/tui/context/theme/koro.json +241 -0
  150. package/src/cli/cmd/tui/context/theme/lucent-orng.json +237 -0
  151. package/src/cli/cmd/tui/context/theme/material.json +235 -0
  152. package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
  153. package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
  154. package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
  155. package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
  156. package/src/cli/cmd/tui/context/theme/nord.json +223 -0
  157. package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
  158. package/src/cli/cmd/tui/context/theme/opencode.json +245 -0
  159. package/src/cli/cmd/tui/context/theme/orng.json +249 -0
  160. package/src/cli/cmd/tui/context/theme/osaka-jade.json +93 -0
  161. package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
  162. package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
  163. package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
  164. package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
  165. package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
  166. package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
  167. package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
  168. package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
  169. package/src/cli/cmd/tui/context/theme.tsx +1240 -0
  170. package/src/cli/cmd/tui/context/tui-config.tsx +9 -0
  171. package/src/cli/cmd/tui/event.ts +49 -0
  172. package/src/cli/cmd/tui/feature-plugins/home/footer.tsx +93 -0
  173. package/src/cli/cmd/tui/feature-plugins/home/tips-view.tsx +152 -0
  174. package/src/cli/cmd/tui/feature-plugins/home/tips.tsx +50 -0
  175. package/src/cli/cmd/tui/feature-plugins/sidebar/context.tsx +63 -0
  176. package/src/cli/cmd/tui/feature-plugins/sidebar/files.tsx +62 -0
  177. package/src/cli/cmd/tui/feature-plugins/sidebar/footer.tsx +93 -0
  178. package/src/cli/cmd/tui/feature-plugins/sidebar/lsp.tsx +66 -0
  179. package/src/cli/cmd/tui/feature-plugins/sidebar/mcp.tsx +96 -0
  180. package/src/cli/cmd/tui/feature-plugins/sidebar/todo.tsx +48 -0
  181. package/src/cli/cmd/tui/feature-plugins/system/plugins.tsx +270 -0
  182. package/src/cli/cmd/tui/plugin/api.tsx +430 -0
  183. package/src/cli/cmd/tui/plugin/index.ts +3 -0
  184. package/src/cli/cmd/tui/plugin/internal.ts +27 -0
  185. package/src/cli/cmd/tui/plugin/runtime.ts +1033 -0
  186. package/src/cli/cmd/tui/plugin/slots.tsx +60 -0
  187. package/src/cli/cmd/tui/routes/home.tsx +84 -0
  188. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +65 -0
  189. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +110 -0
  190. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +26 -0
  191. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +47 -0
  192. package/src/cli/cmd/tui/routes/session/footer.tsx +93 -0
  193. package/src/cli/cmd/tui/routes/session/index.tsx +2270 -0
  194. package/src/cli/cmd/tui/routes/session/permission.tsx +691 -0
  195. package/src/cli/cmd/tui/routes/session/question.tsx +468 -0
  196. package/src/cli/cmd/tui/routes/session/sidebar.tsx +74 -0
  197. package/src/cli/cmd/tui/routes/session/subagent-footer.tsx +131 -0
  198. package/src/cli/cmd/tui/thread.ts +232 -0
  199. package/src/cli/cmd/tui/ui/dialog-alert.tsx +59 -0
  200. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +89 -0
  201. package/src/cli/cmd/tui/ui/dialog-export-options.tsx +211 -0
  202. package/src/cli/cmd/tui/ui/dialog-help.tsx +40 -0
  203. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +130 -0
  204. package/src/cli/cmd/tui/ui/dialog-select.tsx +409 -0
  205. package/src/cli/cmd/tui/ui/dialog.tsx +192 -0
  206. package/src/cli/cmd/tui/ui/link.tsx +28 -0
  207. package/src/cli/cmd/tui/ui/spinner.ts +368 -0
  208. package/src/cli/cmd/tui/ui/toast.tsx +100 -0
  209. package/src/cli/cmd/tui/util/clipboard.ts +192 -0
  210. package/src/cli/cmd/tui/util/editor.ts +37 -0
  211. package/src/cli/cmd/tui/util/model.ts +23 -0
  212. package/src/cli/cmd/tui/util/scroll.ts +23 -0
  213. package/src/cli/cmd/tui/util/selection.ts +25 -0
  214. package/src/cli/cmd/tui/util/signal.ts +7 -0
  215. package/src/cli/cmd/tui/util/terminal.ts +114 -0
  216. package/src/cli/cmd/tui/util/transcript.ts +112 -0
  217. package/src/cli/cmd/tui/win32.ts +129 -0
  218. package/src/cli/cmd/tui/worker.ts +175 -0
  219. package/src/cli/cmd/uninstall.ts +353 -0
  220. package/src/cli/cmd/upgrade.ts +73 -0
  221. package/src/cli/cmd/web.ts +81 -0
  222. package/src/cli/effect/prompt.ts +25 -0
  223. package/src/cli/error.ts +46 -0
  224. package/src/cli/heap.ts +59 -0
  225. package/src/cli/logo.ts +14 -0
  226. package/src/cli/network.ts +60 -0
  227. package/src/cli/ui.ts +133 -0
  228. package/src/cli/upgrade.ts +31 -0
  229. package/src/command/index.ts +195 -0
  230. package/src/command/template/initialize.txt +66 -0
  231. package/src/command/template/review.txt +101 -0
  232. package/src/config/config.ts +1591 -0
  233. package/src/config/markdown.ts +99 -0
  234. package/src/config/paths.ts +181 -0
  235. package/src/config/tui-migrate.ts +155 -0
  236. package/src/config/tui-schema.ts +36 -0
  237. package/src/config/tui.ts +171 -0
  238. package/src/control-plane/adaptors/index.ts +20 -0
  239. package/src/control-plane/adaptors/worktree.ts +38 -0
  240. package/src/control-plane/schema.ts +17 -0
  241. package/src/control-plane/sse.ts +66 -0
  242. package/src/control-plane/types.ts +21 -0
  243. package/src/control-plane/workspace.sql.ts +17 -0
  244. package/src/control-plane/workspace.ts +154 -0
  245. package/src/effect/cross-spawn-spawner.ts +502 -0
  246. package/src/effect/instance-ref.ts +6 -0
  247. package/src/effect/instance-registry.ts +12 -0
  248. package/src/effect/instance-state.ts +82 -0
  249. package/src/effect/run-service.ts +33 -0
  250. package/src/effect/runner.ts +216 -0
  251. package/src/env/index.ts +28 -0
  252. package/src/file/ignore.ts +82 -0
  253. package/src/file/index.ts +686 -0
  254. package/src/file/protected.ts +59 -0
  255. package/src/file/ripgrep.ts +376 -0
  256. package/src/file/time.ts +133 -0
  257. package/src/file/watcher.ts +171 -0
  258. package/src/filesystem/index.ts +226 -0
  259. package/src/flag/flag.ts +155 -0
  260. package/src/format/formatter.ts +413 -0
  261. package/src/format/index.ts +203 -0
  262. package/src/git/index.ts +303 -0
  263. package/src/global/index.ts +161 -0
  264. package/src/id/id.ts +85 -0
  265. package/src/ide/index.ts +74 -0
  266. package/src/index.ts +240 -0
  267. package/src/installation/index.ts +355 -0
  268. package/src/installation/meta.ts +7 -0
  269. package/src/lsp/client.ts +252 -0
  270. package/src/lsp/index.ts +558 -0
  271. package/src/lsp/language.ts +120 -0
  272. package/src/lsp/launch.ts +21 -0
  273. package/src/lsp/server.ts +1958 -0
  274. package/src/mcp/auth.ts +173 -0
  275. package/src/mcp/index.ts +921 -0
  276. package/src/mcp/oauth-callback.ts +215 -0
  277. package/src/mcp/oauth-provider.ts +185 -0
  278. package/src/memory/index.ts +117 -0
  279. package/src/node.ts +1 -0
  280. package/src/npm/index.ts +180 -0
  281. package/src/orchestrator/agent-registry.ts +38 -0
  282. package/src/orchestrator/conflict.ts +25 -0
  283. package/src/orchestrator/context-manager.ts +22 -0
  284. package/src/orchestrator/index.ts +9 -0
  285. package/src/orchestrator/scheduler.ts +30 -0
  286. package/src/orchestrator/state-tracker.ts +71 -0
  287. package/src/orchestrator/task-manager.ts +69 -0
  288. package/src/patch/index.ts +680 -0
  289. package/src/permission/arity.ts +163 -0
  290. package/src/permission/evaluate.ts +15 -0
  291. package/src/permission/index.ts +325 -0
  292. package/src/permission/schema.ts +17 -0
  293. package/src/plugin/codex.ts +596 -0
  294. package/src/plugin/github-copilot/copilot.ts +353 -0
  295. package/src/plugin/github-copilot/models.ts +144 -0
  296. package/src/plugin/index.ts +281 -0
  297. package/src/plugin/install.ts +439 -0
  298. package/src/plugin/loader.ts +174 -0
  299. package/src/plugin/meta.ts +188 -0
  300. package/src/plugin/shared.ts +307 -0
  301. package/src/project/bootstrap.ts +31 -0
  302. package/src/project/instance.ts +175 -0
  303. package/src/project/project.sql.ts +16 -0
  304. package/src/project/project.ts +519 -0
  305. package/src/project/schema.ts +16 -0
  306. package/src/project/state.ts +70 -0
  307. package/src/project/vcs.ts +240 -0
  308. package/src/provider/auth.ts +253 -0
  309. package/src/provider/error.ts +197 -0
  310. package/src/provider/models-snapshot.ts +60410 -0
  311. package/src/provider/models.ts +162 -0
  312. package/src/provider/provider.ts +1677 -0
  313. package/src/provider/schema.ts +38 -0
  314. package/src/provider/sdk/copilot/README.md +5 -0
  315. package/src/provider/sdk/copilot/chat/convert-to-openai-compatible-chat-messages.ts +170 -0
  316. package/src/provider/sdk/copilot/chat/get-response-metadata.ts +15 -0
  317. package/src/provider/sdk/copilot/chat/map-openai-compatible-finish-reason.ts +19 -0
  318. package/src/provider/sdk/copilot/chat/openai-compatible-api-types.ts +64 -0
  319. package/src/provider/sdk/copilot/chat/openai-compatible-chat-language-model.ts +815 -0
  320. package/src/provider/sdk/copilot/chat/openai-compatible-chat-options.ts +28 -0
  321. package/src/provider/sdk/copilot/chat/openai-compatible-metadata-extractor.ts +44 -0
  322. package/src/provider/sdk/copilot/chat/openai-compatible-prepare-tools.ts +83 -0
  323. package/src/provider/sdk/copilot/copilot-provider.ts +100 -0
  324. package/src/provider/sdk/copilot/index.ts +2 -0
  325. package/src/provider/sdk/copilot/openai-compatible-error.ts +27 -0
  326. package/src/provider/sdk/copilot/responses/convert-to-openai-responses-input.ts +335 -0
  327. package/src/provider/sdk/copilot/responses/map-openai-responses-finish-reason.ts +22 -0
  328. package/src/provider/sdk/copilot/responses/openai-config.ts +18 -0
  329. package/src/provider/sdk/copilot/responses/openai-error.ts +22 -0
  330. package/src/provider/sdk/copilot/responses/openai-responses-api-types.ts +214 -0
  331. package/src/provider/sdk/copilot/responses/openai-responses-language-model.ts +1769 -0
  332. package/src/provider/sdk/copilot/responses/openai-responses-prepare-tools.ts +173 -0
  333. package/src/provider/sdk/copilot/responses/openai-responses-settings.ts +1 -0
  334. package/src/provider/sdk/copilot/responses/tool/code-interpreter.ts +87 -0
  335. package/src/provider/sdk/copilot/responses/tool/file-search.ts +127 -0
  336. package/src/provider/sdk/copilot/responses/tool/image-generation.ts +114 -0
  337. package/src/provider/sdk/copilot/responses/tool/local-shell.ts +64 -0
  338. package/src/provider/sdk/copilot/responses/tool/web-search-preview.ts +103 -0
  339. package/src/provider/sdk/copilot/responses/tool/web-search.ts +102 -0
  340. package/src/provider/transform.ts +1046 -0
  341. package/src/pty/index.ts +401 -0
  342. package/src/pty/schema.ts +17 -0
  343. package/src/question/index.ts +224 -0
  344. package/src/question/schema.ts +17 -0
  345. package/src/server/error.ts +36 -0
  346. package/src/server/event.ts +7 -0
  347. package/src/server/instance.ts +314 -0
  348. package/src/server/mdns.ts +60 -0
  349. package/src/server/middleware.ts +33 -0
  350. package/src/server/projectors.ts +28 -0
  351. package/src/server/router.ts +99 -0
  352. package/src/server/routes/config.ts +92 -0
  353. package/src/server/routes/event.ts +83 -0
  354. package/src/server/routes/experimental.ts +271 -0
  355. package/src/server/routes/file.ts +197 -0
  356. package/src/server/routes/global.ts +312 -0
  357. package/src/server/routes/mcp.ts +225 -0
  358. package/src/server/routes/permission.ts +69 -0
  359. package/src/server/routes/project.ts +118 -0
  360. package/src/server/routes/provider.ts +171 -0
  361. package/src/server/routes/pty.ts +211 -0
  362. package/src/server/routes/question.ts +99 -0
  363. package/src/server/routes/session.ts +1031 -0
  364. package/src/server/routes/tui.ts +379 -0
  365. package/src/server/routes/workspace.ts +94 -0
  366. package/src/server/server.ts +312 -0
  367. package/src/session/compaction.ts +428 -0
  368. package/src/session/index.ts +887 -0
  369. package/src/session/instruction.ts +258 -0
  370. package/src/session/llm.ts +370 -0
  371. package/src/session/message-v2.ts +1031 -0
  372. package/src/session/message.ts +191 -0
  373. package/src/session/overflow.ts +22 -0
  374. package/src/session/processor.ts +523 -0
  375. package/src/session/projectors.ts +135 -0
  376. package/src/session/prompt/anthropic.txt +105 -0
  377. package/src/session/prompt/beast.txt +147 -0
  378. package/src/session/prompt/build-switch.txt +5 -0
  379. package/src/session/prompt/codex.txt +79 -0
  380. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  381. package/src/session/prompt/default.txt +105 -0
  382. package/src/session/prompt/gemini.txt +155 -0
  383. package/src/session/prompt/gpt.txt +107 -0
  384. package/src/session/prompt/kimi.txt +114 -0
  385. package/src/session/prompt/max-steps.txt +16 -0
  386. package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  387. package/src/session/prompt/plan.txt +26 -0
  388. package/src/session/prompt/trinity.txt +97 -0
  389. package/src/session/prompt.ts +1908 -0
  390. package/src/session/retry.ts +106 -0
  391. package/src/session/revert.ts +176 -0
  392. package/src/session/schema.ts +38 -0
  393. package/src/session/session.sql.ts +103 -0
  394. package/src/session/status.ts +102 -0
  395. package/src/session/summary.ts +177 -0
  396. package/src/session/system.ts +76 -0
  397. package/src/session/todo.ts +95 -0
  398. package/src/share/share-next.ts +369 -0
  399. package/src/share/share.sql.ts +13 -0
  400. package/src/shell/shell.ts +110 -0
  401. package/src/skill/discovery.ts +116 -0
  402. package/src/skill/index.ts +277 -0
  403. package/src/snapshot/index.ts +571 -0
  404. package/src/sql.d.ts +4 -0
  405. package/src/storage/db.bun.ts +8 -0
  406. package/src/storage/db.node.ts +8 -0
  407. package/src/storage/db.ts +174 -0
  408. package/src/storage/json-migration.ts +425 -0
  409. package/src/storage/schema.sql.ts +10 -0
  410. package/src/storage/schema.ts +5 -0
  411. package/src/storage/storage.ts +353 -0
  412. package/src/sync/README.md +179 -0
  413. package/src/sync/event.sql.ts +16 -0
  414. package/src/sync/index.ts +263 -0
  415. package/src/sync/schema.ts +14 -0
  416. package/src/token/index.ts +77 -0
  417. package/src/tool/apply_patch.ts +281 -0
  418. package/src/tool/apply_patch.txt +33 -0
  419. package/src/tool/bash.ts +496 -0
  420. package/src/tool/bash.txt +117 -0
  421. package/src/tool/batch.ts +183 -0
  422. package/src/tool/batch.txt +24 -0
  423. package/src/tool/codesearch.ts +132 -0
  424. package/src/tool/codesearch.txt +12 -0
  425. package/src/tool/edit.ts +667 -0
  426. package/src/tool/edit.txt +10 -0
  427. package/src/tool/external-directory.ts +37 -0
  428. package/src/tool/glob.ts +78 -0
  429. package/src/tool/glob.txt +6 -0
  430. package/src/tool/grep.ts +156 -0
  431. package/src/tool/grep.txt +8 -0
  432. package/src/tool/invalid.ts +17 -0
  433. package/src/tool/ls.ts +121 -0
  434. package/src/tool/ls.txt +1 -0
  435. package/src/tool/lsp.ts +97 -0
  436. package/src/tool/lsp.txt +19 -0
  437. package/src/tool/multiedit.ts +46 -0
  438. package/src/tool/multiedit.txt +41 -0
  439. package/src/tool/plan-enter.txt +14 -0
  440. package/src/tool/plan-exit.txt +13 -0
  441. package/src/tool/plan.ts +131 -0
  442. package/src/tool/question.ts +46 -0
  443. package/src/tool/question.txt +10 -0
  444. package/src/tool/read.ts +296 -0
  445. package/src/tool/read.txt +14 -0
  446. package/src/tool/registry.ts +248 -0
  447. package/src/tool/schema.ts +17 -0
  448. package/src/tool/skill.ts +105 -0
  449. package/src/tool/task.ts +166 -0
  450. package/src/tool/task.txt +60 -0
  451. package/src/tool/todo.ts +48 -0
  452. package/src/tool/todowrite.txt +167 -0
  453. package/src/tool/tool.ts +112 -0
  454. package/src/tool/truncate.ts +144 -0
  455. package/src/tool/truncation-dir.ts +4 -0
  456. package/src/tool/webfetch.ts +206 -0
  457. package/src/tool/webfetch.txt +13 -0
  458. package/src/tool/websearch.ts +150 -0
  459. package/src/tool/websearch.txt +14 -0
  460. package/src/tool/write.ts +84 -0
  461. package/src/tool/write.txt +8 -0
  462. package/src/util/abort.ts +35 -0
  463. package/src/util/archive.ts +17 -0
  464. package/src/util/color.ts +19 -0
  465. package/src/util/context.ts +25 -0
  466. package/src/util/data-url.ts +9 -0
  467. package/src/util/defer.ts +12 -0
  468. package/src/util/effect-http-client.ts +11 -0
  469. package/src/util/effect-zod.ts +98 -0
  470. package/src/util/error.ts +77 -0
  471. package/src/util/filesystem.ts +245 -0
  472. package/src/util/flock.ts +333 -0
  473. package/src/util/fn.ts +21 -0
  474. package/src/util/format.ts +20 -0
  475. package/src/util/glob.ts +34 -0
  476. package/src/util/hash.ts +7 -0
  477. package/src/util/iife.ts +3 -0
  478. package/src/util/keybind.ts +103 -0
  479. package/src/util/lazy.ts +23 -0
  480. package/src/util/locale.ts +81 -0
  481. package/src/util/lock.ts +98 -0
  482. package/src/util/log.ts +182 -0
  483. package/src/util/network.ts +9 -0
  484. package/src/util/process.ts +176 -0
  485. package/src/util/queue.ts +32 -0
  486. package/src/util/record.ts +3 -0
  487. package/src/util/rpc.ts +66 -0
  488. package/src/util/schema.ts +53 -0
  489. package/src/util/scrap.ts +10 -0
  490. package/src/util/signal.ts +12 -0
  491. package/src/util/timeout.ts +14 -0
  492. package/src/util/token.ts +7 -0
  493. package/src/util/update-schema.ts +13 -0
  494. package/src/util/which.ts +14 -0
  495. package/src/util/wildcard.ts +59 -0
  496. package/src/worktree/index.ts +612 -0
  497. package/sst-env.d.ts +10 -0
  498. package/test/AGENTS.md +81 -0
  499. package/test/account/repo.test.ts +326 -0
  500. package/test/account/service.test.ts +393 -0
  501. package/test/acp/agent-interface.test.ts +51 -0
  502. package/test/acp/event-subscription.test.ts +685 -0
  503. package/test/agent/agent.test.ts +717 -0
  504. package/test/auth/auth.test.ts +58 -0
  505. package/test/bus/bus-effect.test.ts +164 -0
  506. package/test/bus/bus-integration.test.ts +87 -0
  507. package/test/bus/bus.test.ts +219 -0
  508. package/test/cli/account.test.ts +26 -0
  509. package/test/cli/cmd/tui/prompt-part.test.ts +47 -0
  510. package/test/cli/github-action.test.ts +198 -0
  511. package/test/cli/github-remote.test.ts +80 -0
  512. package/test/cli/import.test.ts +54 -0
  513. package/test/cli/plugin-auth-picker.test.ts +120 -0
  514. package/test/cli/tui/keybind-plugin.test.ts +90 -0
  515. package/test/cli/tui/plugin-add.test.ts +107 -0
  516. package/test/cli/tui/plugin-install.test.ts +89 -0
  517. package/test/cli/tui/plugin-lifecycle.test.ts +225 -0
  518. package/test/cli/tui/plugin-loader-entrypoint.test.ts +492 -0
  519. package/test/cli/tui/plugin-loader-pure.test.ts +72 -0
  520. package/test/cli/tui/plugin-loader.test.ts +752 -0
  521. package/test/cli/tui/plugin-toggle.test.ts +159 -0
  522. package/test/cli/tui/slot-replace.test.tsx +47 -0
  523. package/test/cli/tui/theme-store.test.ts +51 -0
  524. package/test/cli/tui/thread.test.ts +128 -0
  525. package/test/cli/tui/transcript.test.ts +426 -0
  526. package/test/config/agent-color.test.ts +71 -0
  527. package/test/config/config.test.ts +2348 -0
  528. package/test/config/fixtures/empty-frontmatter.md +4 -0
  529. package/test/config/fixtures/frontmatter.md +28 -0
  530. package/test/config/fixtures/markdown-header.md +11 -0
  531. package/test/config/fixtures/no-frontmatter.md +1 -0
  532. package/test/config/fixtures/weird-model-id.md +13 -0
  533. package/test/config/markdown.test.ts +228 -0
  534. package/test/config/tui.test.ts +752 -0
  535. package/test/control-plane/sse.test.ts +56 -0
  536. package/test/effect/cross-spawn-spawner.test.ts +412 -0
  537. package/test/effect/instance-state.test.ts +482 -0
  538. package/test/effect/run-service.test.ts +46 -0
  539. package/test/effect/runner.test.ts +523 -0
  540. package/test/fake/provider.ts +81 -0
  541. package/test/file/fsmonitor.test.ts +62 -0
  542. package/test/file/ignore.test.ts +10 -0
  543. package/test/file/index.test.ts +946 -0
  544. package/test/file/path-traversal.test.ts +198 -0
  545. package/test/file/ripgrep.test.ts +54 -0
  546. package/test/file/time.test.ts +445 -0
  547. package/test/file/watcher.test.ts +247 -0
  548. package/test/filesystem/filesystem.test.ts +319 -0
  549. package/test/fixture/db.ts +11 -0
  550. package/test/fixture/fixture.test.ts +26 -0
  551. package/test/fixture/fixture.ts +172 -0
  552. package/test/fixture/flock-worker.ts +72 -0
  553. package/test/fixture/lsp/fake-lsp-server.js +77 -0
  554. package/test/fixture/plug-worker.ts +93 -0
  555. package/test/fixture/plugin-meta-worker.ts +26 -0
  556. package/test/fixture/skills/agents-sdk/SKILL.md +152 -0
  557. package/test/fixture/skills/agents-sdk/references/callable.md +92 -0
  558. package/test/fixture/skills/cloudflare/SKILL.md +211 -0
  559. package/test/fixture/skills/index.json +6 -0
  560. package/test/fixture/tui-plugin.ts +337 -0
  561. package/test/fixture/tui-runtime.ts +27 -0
  562. package/test/format/format.test.ts +171 -0
  563. package/test/git/git.test.ts +128 -0
  564. package/test/ide/ide.test.ts +82 -0
  565. package/test/installation/installation.test.ts +151 -0
  566. package/test/keybind.test.ts +421 -0
  567. package/test/lib/effect.ts +53 -0
  568. package/test/lib/filesystem.ts +10 -0
  569. package/test/lib/llm-server.ts +795 -0
  570. package/test/lsp/client.test.ts +95 -0
  571. package/test/lsp/index.test.ts +55 -0
  572. package/test/lsp/launch.test.ts +22 -0
  573. package/test/lsp/lifecycle.test.ts +147 -0
  574. package/test/mcp/headers.test.ts +153 -0
  575. package/test/mcp/lifecycle.test.ts +750 -0
  576. package/test/mcp/oauth-auto-connect.test.ts +199 -0
  577. package/test/mcp/oauth-browser.test.ts +249 -0
  578. package/test/memory/abort-leak.test.ts +137 -0
  579. package/test/patch/patch.test.ts +348 -0
  580. package/test/permission/arity.test.ts +33 -0
  581. package/test/permission/next.test.ts +1148 -0
  582. package/test/permission-task.test.ts +323 -0
  583. package/test/plugin/auth-override.test.ts +74 -0
  584. package/test/plugin/codex.test.ts +123 -0
  585. package/test/plugin/github-copilot-models.test.ts +117 -0
  586. package/test/plugin/install-concurrency.test.ts +140 -0
  587. package/test/plugin/install.test.ts +570 -0
  588. package/test/plugin/loader-shared.test.ts +1136 -0
  589. package/test/plugin/meta.test.ts +137 -0
  590. package/test/plugin/trigger.test.ts +111 -0
  591. package/test/preload.ts +90 -0
  592. package/test/project/migrate-global.test.ts +140 -0
  593. package/test/project/project.test.ts +459 -0
  594. package/test/project/state.test.ts +115 -0
  595. package/test/project/vcs.test.ts +228 -0
  596. package/test/project/worktree-remove.test.ts +96 -0
  597. package/test/project/worktree.test.ts +173 -0
  598. package/test/provider/amazon-bedrock.test.ts +447 -0
  599. package/test/provider/copilot/convert-to-copilot-messages.test.ts +523 -0
  600. package/test/provider/copilot/copilot-chat-model.test.ts +592 -0
  601. package/test/provider/gitlab-duo.test.ts +412 -0
  602. package/test/provider/provider.test.ts +2284 -0
  603. package/test/provider/transform.test.ts +2839 -0
  604. package/test/pty/pty-output-isolation.test.ts +141 -0
  605. package/test/pty/pty-session.test.ts +92 -0
  606. package/test/pty/pty-shell.test.ts +59 -0
  607. package/test/question/question.test.ts +453 -0
  608. package/test/server/global-session-list.test.ts +89 -0
  609. package/test/server/project-init-git.test.ts +121 -0
  610. package/test/server/session-actions.test.ts +83 -0
  611. package/test/server/session-list.test.ts +98 -0
  612. package/test/server/session-messages.test.ts +159 -0
  613. package/test/server/session-select.test.ts +84 -0
  614. package/test/session/compaction.test.ts +1212 -0
  615. package/test/session/instruction.test.ts +286 -0
  616. package/test/session/llm.test.ts +1098 -0
  617. package/test/session/message-v2.test.ts +957 -0
  618. package/test/session/messages-pagination.test.ts +885 -0
  619. package/test/session/processor-effect.test.ts +747 -0
  620. package/test/session/prompt-effect.test.ts +1241 -0
  621. package/test/session/prompt.test.ts +518 -0
  622. package/test/session/retry.test.ts +232 -0
  623. package/test/session/revert-compact.test.ts +621 -0
  624. package/test/session/session.test.ts +142 -0
  625. package/test/session/snapshot-tool-race.test.ts +242 -0
  626. package/test/session/structured-output-integration.test.ts +233 -0
  627. package/test/session/structured-output.test.ts +391 -0
  628. package/test/session/system.test.ts +59 -0
  629. package/test/share/share-next.test.ts +333 -0
  630. package/test/shell/shell.test.ts +73 -0
  631. package/test/skill/discovery.test.ts +116 -0
  632. package/test/skill/skill.test.ts +392 -0
  633. package/test/snapshot/snapshot.test.ts +1312 -0
  634. package/test/storage/db.test.ts +14 -0
  635. package/test/storage/json-migration.test.ts +849 -0
  636. package/test/storage/storage.test.ts +295 -0
  637. package/test/sync/index.test.ts +191 -0
  638. package/test/tool/__snapshots__/tool.test.ts.snap +9 -0
  639. package/test/tool/apply_patch.test.ts +567 -0
  640. package/test/tool/bash.test.ts +1099 -0
  641. package/test/tool/edit.test.ts +681 -0
  642. package/test/tool/external-directory.test.ts +198 -0
  643. package/test/tool/fixtures/large-image.png +0 -0
  644. package/test/tool/fixtures/models-api.json +65179 -0
  645. package/test/tool/grep.test.ts +111 -0
  646. package/test/tool/question.test.ts +126 -0
  647. package/test/tool/read.test.ts +546 -0
  648. package/test/tool/registry.test.ts +126 -0
  649. package/test/tool/skill.test.ts +167 -0
  650. package/test/tool/task.test.ts +49 -0
  651. package/test/tool/tool-define.test.ts +101 -0
  652. package/test/tool/truncation.test.ts +161 -0
  653. package/test/tool/webfetch.test.ts +101 -0
  654. package/test/tool/write.test.ts +353 -0
  655. package/test/util/data-url.test.ts +14 -0
  656. package/test/util/effect-zod.test.ts +61 -0
  657. package/test/util/error.test.ts +38 -0
  658. package/test/util/filesystem.test.ts +656 -0
  659. package/test/util/flock.test.ts +383 -0
  660. package/test/util/format.test.ts +59 -0
  661. package/test/util/glob.test.ts +164 -0
  662. package/test/util/iife.test.ts +36 -0
  663. package/test/util/lazy.test.ts +50 -0
  664. package/test/util/lock.test.ts +72 -0
  665. package/test/util/module.test.ts +59 -0
  666. package/test/util/process.test.ts +128 -0
  667. package/test/util/timeout.test.ts +21 -0
  668. package/test/util/which.test.ts +100 -0
  669. package/test/util/wildcard.test.ts +90 -0
  670. package/tsconfig.json +23 -0
@@ -0,0 +1,1677 @@
1
+ import z from "zod"
2
+ import os from "os"
3
+ import fuzzysort from "fuzzysort"
4
+ import { Config } from "../config/config"
5
+ import { mapValues, mergeDeep, omit, pickBy, sortBy } from "remeda"
6
+ import { NoSuchModelError, type Provider as SDK } from "ai"
7
+ import { Log } from "../util/log"
8
+ import { Npm } from "../npm"
9
+ import { Hash } from "../util/hash"
10
+ import { Plugin } from "../plugin"
11
+ import { NamedError } from "@opencode-ai/util/error"
12
+ import { type LanguageModelV3 } from "@ai-sdk/provider"
13
+ import { ModelsDev } from "./models"
14
+ import { Auth } from "../auth"
15
+ import { Env } from "../env"
16
+ import { Instance } from "../project/instance"
17
+ import { Flag } from "../flag/flag"
18
+ import { iife } from "@/util/iife"
19
+ import { Global } from "../global"
20
+ import path from "path"
21
+ import { Filesystem } from "../util/filesystem"
22
+ import { Effect, Layer, ServiceMap } from "effect"
23
+ import { InstanceState } from "@/effect/instance-state"
24
+ import { makeRuntime } from "@/effect/run-service"
25
+
26
+ // Direct imports for bundled providers
27
+ import { createAmazonBedrock, type AmazonBedrockProviderSettings } from "@ai-sdk/amazon-bedrock"
28
+ import { createAnthropic } from "@ai-sdk/anthropic"
29
+ import { createAzure } from "@ai-sdk/azure"
30
+ import { createGoogleGenerativeAI } from "@ai-sdk/google"
31
+ import { createVertex } from "@ai-sdk/google-vertex"
32
+ import { createVertexAnthropic } from "@ai-sdk/google-vertex/anthropic"
33
+ import { createOpenAI } from "@ai-sdk/openai"
34
+ import { createOpenAICompatible } from "@ai-sdk/openai-compatible"
35
+ import { createOpenRouter } from "@openrouter/ai-sdk-provider"
36
+ import { createOpenaiCompatible as createGitHubCopilotOpenAICompatible } from "./sdk/copilot"
37
+ import { createXai } from "@ai-sdk/xai"
38
+ import { createMistral } from "@ai-sdk/mistral"
39
+ import { createGroq } from "@ai-sdk/groq"
40
+ import { createDeepInfra } from "@ai-sdk/deepinfra"
41
+ import { createCerebras } from "@ai-sdk/cerebras"
42
+ import { createCohere } from "@ai-sdk/cohere"
43
+ import { createGateway } from "@ai-sdk/gateway"
44
+ import { createTogetherAI } from "@ai-sdk/togetherai"
45
+ import { createPerplexity } from "@ai-sdk/perplexity"
46
+ import { createVercel } from "@ai-sdk/vercel"
47
+ import { createVenice } from "venice-ai-sdk-provider"
48
+ import {
49
+ createGitLab,
50
+ VERSION as GITLAB_PROVIDER_VERSION,
51
+ isWorkflowModel,
52
+ discoverWorkflowModels,
53
+ } from "gitlab-ai-provider"
54
+ import { fromNodeProviderChain } from "@aws-sdk/credential-providers"
55
+ import { GoogleAuth } from "google-auth-library"
56
+ import { ProviderTransform } from "./transform"
57
+ import { Installation } from "../installation"
58
+ import { ModelID, ProviderID } from "./schema"
59
+
60
+ export namespace Provider {
61
+ const log = Log.create({ service: "provider" })
62
+
63
+ function shouldUseCopilotResponsesApi(modelID: string): boolean {
64
+ const match = /^gpt-(\d+)/.exec(modelID)
65
+ if (!match) return false
66
+ return Number(match[1]) >= 5 && !modelID.startsWith("gpt-5-mini")
67
+ }
68
+
69
+ function wrapSSE(res: Response, ms: number, ctl: AbortController) {
70
+ if (typeof ms !== "number" || ms <= 0) return res
71
+ if (!res.body) return res
72
+ if (!res.headers.get("content-type")?.includes("text/event-stream")) return res
73
+
74
+ const reader = res.body.getReader()
75
+ const body = new ReadableStream<Uint8Array>({
76
+ async pull(ctrl) {
77
+ const part = await new Promise<Awaited<ReturnType<typeof reader.read>>>((resolve, reject) => {
78
+ const id = setTimeout(() => {
79
+ const err = new Error("SSE read timed out")
80
+ ctl.abort(err)
81
+ void reader.cancel(err)
82
+ reject(err)
83
+ }, ms)
84
+
85
+ reader.read().then(
86
+ (part) => {
87
+ clearTimeout(id)
88
+ resolve(part)
89
+ },
90
+ (err) => {
91
+ clearTimeout(id)
92
+ reject(err)
93
+ },
94
+ )
95
+ })
96
+
97
+ if (part.done) {
98
+ ctrl.close()
99
+ return
100
+ }
101
+
102
+ ctrl.enqueue(part.value)
103
+ },
104
+ async cancel(reason) {
105
+ ctl.abort(reason)
106
+ await reader.cancel(reason)
107
+ },
108
+ })
109
+
110
+ return new Response(body, {
111
+ headers: new Headers(res.headers),
112
+ status: res.status,
113
+ statusText: res.statusText,
114
+ })
115
+ }
116
+
117
+ function e2eURL() {
118
+ const url = Env.get("OPENCODE_E2E_LLM_URL")
119
+ if (typeof url !== "string" || url === "") return
120
+ return url
121
+ }
122
+
123
+ type BundledSDK = {
124
+ languageModel(modelId: string): LanguageModelV3
125
+ }
126
+
127
+ const BUNDLED_PROVIDERS: Record<string, (options: any) => BundledSDK> = {
128
+ "@ai-sdk/amazon-bedrock": createAmazonBedrock,
129
+ "@ai-sdk/anthropic": createAnthropic,
130
+ "@ai-sdk/azure": createAzure,
131
+ "@ai-sdk/google": createGoogleGenerativeAI,
132
+ "@ai-sdk/google-vertex": createVertex,
133
+ "@ai-sdk/google-vertex/anthropic": createVertexAnthropic,
134
+ "@ai-sdk/openai": createOpenAI,
135
+ "@ai-sdk/openai-compatible": createOpenAICompatible,
136
+ "@openrouter/ai-sdk-provider": createOpenRouter,
137
+ "@ai-sdk/xai": createXai,
138
+ "@ai-sdk/mistral": createMistral,
139
+ "@ai-sdk/groq": createGroq,
140
+ "@ai-sdk/deepinfra": createDeepInfra,
141
+ "@ai-sdk/cerebras": createCerebras,
142
+ "@ai-sdk/cohere": createCohere,
143
+ "@ai-sdk/gateway": createGateway,
144
+ "@ai-sdk/togetherai": createTogetherAI,
145
+ "@ai-sdk/perplexity": createPerplexity,
146
+ "@ai-sdk/vercel": createVercel,
147
+ "gitlab-ai-provider": createGitLab,
148
+ "@ai-sdk/github-copilot": createGitHubCopilotOpenAICompatible,
149
+ "venice-ai-sdk-provider": createVenice,
150
+ }
151
+
152
+ type CustomModelLoader = (sdk: any, modelID: string, options?: Record<string, any>) => Promise<any>
153
+ type CustomVarsLoader = (options: Record<string, any>) => Record<string, string>
154
+ type CustomDiscoverModels = () => Promise<Record<string, Model>>
155
+ type CustomLoader = (provider: Info) => Promise<{
156
+ autoload: boolean
157
+ getModel?: CustomModelLoader
158
+ vars?: CustomVarsLoader
159
+ options?: Record<string, any>
160
+ discoverModels?: CustomDiscoverModels
161
+ }>
162
+
163
+ function useLanguageModel(sdk: any) {
164
+ return sdk.responses === undefined && sdk.chat === undefined
165
+ }
166
+
167
+ const CUSTOM_LOADERS: Record<string, CustomLoader> = {
168
+ async anthropic() {
169
+ return {
170
+ autoload: false,
171
+ options: {
172
+ headers: {
173
+ "anthropic-beta": "interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",
174
+ },
175
+ },
176
+ }
177
+ },
178
+ async opencode(input) {
179
+ const hasKey = await (async () => {
180
+ const env = Env.all()
181
+ if (input.env.some((item) => env[item])) return true
182
+ if (await Auth.get(input.id)) return true
183
+ const config = await Config.get()
184
+ if (config.provider?.["opencode"]?.options?.apiKey) return true
185
+ return false
186
+ })()
187
+
188
+ if (!hasKey) {
189
+ for (const [key, value] of Object.entries(input.models)) {
190
+ if (value.cost.input === 0) continue
191
+ delete input.models[key]
192
+ }
193
+ }
194
+
195
+ return {
196
+ autoload: Object.keys(input.models).length > 0,
197
+ options: hasKey ? {} : { apiKey: "public" },
198
+ }
199
+ },
200
+ openai: async () => {
201
+ return {
202
+ autoload: false,
203
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
204
+ return sdk.responses(modelID)
205
+ },
206
+ options: {},
207
+ }
208
+ },
209
+ xai: async () => {
210
+ return {
211
+ autoload: false,
212
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
213
+ return sdk.responses(modelID)
214
+ },
215
+ options: {},
216
+ }
217
+ },
218
+ "github-copilot": async () => {
219
+ return {
220
+ autoload: false,
221
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
222
+ if (useLanguageModel(sdk)) return sdk.languageModel(modelID)
223
+ return shouldUseCopilotResponsesApi(modelID) ? sdk.responses(modelID) : sdk.chat(modelID)
224
+ },
225
+ options: {},
226
+ }
227
+ },
228
+ azure: async (provider) => {
229
+ const resource = iife(() => {
230
+ const name = provider.options?.resourceName
231
+ if (typeof name === "string" && name.trim() !== "") return name
232
+ return Env.get("AZURE_RESOURCE_NAME")
233
+ })
234
+
235
+ return {
236
+ autoload: false,
237
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
238
+ if (useLanguageModel(sdk)) return sdk.languageModel(modelID)
239
+ if (options?.["useCompletionUrls"]) {
240
+ return sdk.chat(modelID)
241
+ } else {
242
+ return sdk.responses(modelID)
243
+ }
244
+ },
245
+ options: {},
246
+ vars(_options) {
247
+ return {
248
+ ...(resource && { AZURE_RESOURCE_NAME: resource }),
249
+ }
250
+ },
251
+ }
252
+ },
253
+ "azure-cognitive-services": async () => {
254
+ const resourceName = Env.get("AZURE_COGNITIVE_SERVICES_RESOURCE_NAME")
255
+ return {
256
+ autoload: false,
257
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
258
+ if (useLanguageModel(sdk)) return sdk.languageModel(modelID)
259
+ if (options?.["useCompletionUrls"]) {
260
+ return sdk.chat(modelID)
261
+ } else {
262
+ return sdk.responses(modelID)
263
+ }
264
+ },
265
+ options: {
266
+ baseURL: resourceName ? `https://${resourceName}.cognitiveservices.azure.com/openai` : undefined,
267
+ },
268
+ }
269
+ },
270
+ "amazon-bedrock": async () => {
271
+ const config = await Config.get()
272
+ const providerConfig = config.provider?.["amazon-bedrock"]
273
+
274
+ const auth = await Auth.get("amazon-bedrock")
275
+
276
+ // Region precedence: 1) config file, 2) env var, 3) default
277
+ const configRegion = providerConfig?.options?.region
278
+ const envRegion = Env.get("AWS_REGION")
279
+ const defaultRegion = configRegion ?? envRegion ?? "us-east-1"
280
+
281
+ // Profile: config file takes precedence over env var
282
+ const configProfile = providerConfig?.options?.profile
283
+ const envProfile = Env.get("AWS_PROFILE")
284
+ const profile = configProfile ?? envProfile
285
+
286
+ const awsAccessKeyId = Env.get("AWS_ACCESS_KEY_ID")
287
+
288
+ // TODO: Using process.env directly because Env.set only updates a process.env shallow copy,
289
+ // until the scope of the Env API is clarified (test only or runtime?)
290
+ const awsBearerToken = iife(() => {
291
+ const envToken = process.env.AWS_BEARER_TOKEN_BEDROCK
292
+ if (envToken) return envToken
293
+ if (auth?.type === "api") {
294
+ process.env.AWS_BEARER_TOKEN_BEDROCK = auth.key
295
+ return auth.key
296
+ }
297
+ return undefined
298
+ })
299
+
300
+ const awsWebIdentityTokenFile = Env.get("AWS_WEB_IDENTITY_TOKEN_FILE")
301
+
302
+ const containerCreds = Boolean(
303
+ process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI || process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI,
304
+ )
305
+
306
+ if (!profile && !awsAccessKeyId && !awsBearerToken && !awsWebIdentityTokenFile && !containerCreds)
307
+ return { autoload: false }
308
+
309
+ const providerOptions: AmazonBedrockProviderSettings = {
310
+ region: defaultRegion,
311
+ }
312
+
313
+ // Only use credential chain if no bearer token exists
314
+ // Bearer token takes precedence over credential chain (profiles, access keys, IAM roles, web identity tokens)
315
+ if (!awsBearerToken) {
316
+ // Build credential provider options (only pass profile if specified)
317
+ const credentialProviderOptions = profile ? { profile } : {}
318
+
319
+ providerOptions.credentialProvider = fromNodeProviderChain(credentialProviderOptions)
320
+ }
321
+
322
+ // Add custom endpoint if specified (endpoint takes precedence over baseURL)
323
+ const endpoint = providerConfig?.options?.endpoint ?? providerConfig?.options?.baseURL
324
+ if (endpoint) {
325
+ providerOptions.baseURL = endpoint
326
+ }
327
+
328
+ return {
329
+ autoload: true,
330
+ options: providerOptions,
331
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
332
+ // Skip region prefixing if model already has a cross-region inference profile prefix
333
+ // Models from models.dev may already include prefixes like us., eu., global., etc.
334
+ const crossRegionPrefixes = ["global.", "us.", "eu.", "jp.", "apac.", "au."]
335
+ if (crossRegionPrefixes.some((prefix) => modelID.startsWith(prefix))) {
336
+ return sdk.languageModel(modelID)
337
+ }
338
+
339
+ // Region resolution precedence (highest to lowest):
340
+ // 1. options.region from opencode.json provider config
341
+ // 2. defaultRegion from AWS_REGION environment variable
342
+ // 3. Default "us-east-1" (baked into defaultRegion)
343
+ const region = options?.region ?? defaultRegion
344
+
345
+ let regionPrefix = region.split("-")[0]
346
+
347
+ switch (regionPrefix) {
348
+ case "us": {
349
+ const modelRequiresPrefix = [
350
+ "nova-micro",
351
+ "nova-lite",
352
+ "nova-pro",
353
+ "nova-premier",
354
+ "nova-2",
355
+ "claude",
356
+ "deepseek",
357
+ ].some((m) => modelID.includes(m))
358
+ const isGovCloud = region.startsWith("us-gov")
359
+ if (modelRequiresPrefix && !isGovCloud) {
360
+ modelID = `${regionPrefix}.${modelID}`
361
+ }
362
+ break
363
+ }
364
+ case "eu": {
365
+ const regionRequiresPrefix = [
366
+ "eu-west-1",
367
+ "eu-west-2",
368
+ "eu-west-3",
369
+ "eu-north-1",
370
+ "eu-central-1",
371
+ "eu-south-1",
372
+ "eu-south-2",
373
+ ].some((r) => region.includes(r))
374
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "llama3", "pixtral"].some((m) =>
375
+ modelID.includes(m),
376
+ )
377
+ if (regionRequiresPrefix && modelRequiresPrefix) {
378
+ modelID = `${regionPrefix}.${modelID}`
379
+ }
380
+ break
381
+ }
382
+ case "ap": {
383
+ const isAustraliaRegion = ["ap-southeast-2", "ap-southeast-4"].includes(region)
384
+ const isTokyoRegion = region === "ap-northeast-1"
385
+ if (
386
+ isAustraliaRegion &&
387
+ ["anthropic.claude-sonnet-4-5", "anthropic.claude-haiku"].some((m) => modelID.includes(m))
388
+ ) {
389
+ regionPrefix = "au"
390
+ modelID = `${regionPrefix}.${modelID}`
391
+ } else if (isTokyoRegion) {
392
+ // Tokyo region uses jp. prefix for cross-region inference
393
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "nova-pro"].some((m) =>
394
+ modelID.includes(m),
395
+ )
396
+ if (modelRequiresPrefix) {
397
+ regionPrefix = "jp"
398
+ modelID = `${regionPrefix}.${modelID}`
399
+ }
400
+ } else {
401
+ // Other APAC regions use apac. prefix
402
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "nova-pro"].some((m) =>
403
+ modelID.includes(m),
404
+ )
405
+ if (modelRequiresPrefix) {
406
+ regionPrefix = "apac"
407
+ modelID = `${regionPrefix}.${modelID}`
408
+ }
409
+ }
410
+ break
411
+ }
412
+ }
413
+
414
+ return sdk.languageModel(modelID)
415
+ },
416
+ }
417
+ },
418
+ openrouter: async () => {
419
+ return {
420
+ autoload: false,
421
+ options: {
422
+ headers: {
423
+ "HTTP-Referer": "https://opencode.ai/",
424
+ "X-Title": "opencode",
425
+ },
426
+ },
427
+ }
428
+ },
429
+ vercel: async () => {
430
+ return {
431
+ autoload: false,
432
+ options: {
433
+ headers: {
434
+ "http-referer": "https://opencode.ai/",
435
+ "x-title": "opencode",
436
+ },
437
+ },
438
+ }
439
+ },
440
+ "google-vertex": async (provider) => {
441
+ const project =
442
+ provider.options?.project ??
443
+ Env.get("GOOGLE_CLOUD_PROJECT") ??
444
+ Env.get("GCP_PROJECT") ??
445
+ Env.get("GCLOUD_PROJECT")
446
+
447
+ const location = String(
448
+ provider.options?.location ??
449
+ Env.get("GOOGLE_VERTEX_LOCATION") ??
450
+ Env.get("GOOGLE_CLOUD_LOCATION") ??
451
+ Env.get("VERTEX_LOCATION") ??
452
+ "us-central1",
453
+ )
454
+
455
+ const autoload = Boolean(project)
456
+ if (!autoload) return { autoload: false }
457
+ return {
458
+ autoload: true,
459
+ vars(_options: Record<string, any>) {
460
+ const endpoint = location === "global" ? "aiplatform.googleapis.com" : `${location}-aiplatform.googleapis.com`
461
+ return {
462
+ ...(project && { GOOGLE_VERTEX_PROJECT: project }),
463
+ GOOGLE_VERTEX_LOCATION: location,
464
+ GOOGLE_VERTEX_ENDPOINT: endpoint,
465
+ }
466
+ },
467
+ options: {
468
+ project,
469
+ location,
470
+ fetch: async (input: RequestInfo | URL, init?: RequestInit) => {
471
+ const auth = new GoogleAuth()
472
+ const client = await auth.getApplicationDefault()
473
+ const token = await client.credential.getAccessToken()
474
+
475
+ const headers = new Headers(init?.headers)
476
+ headers.set("Authorization", `Bearer ${token.token}`)
477
+
478
+ return fetch(input, { ...init, headers })
479
+ },
480
+ },
481
+ async getModel(sdk: any, modelID: string) {
482
+ const id = String(modelID).trim()
483
+ return sdk.languageModel(id)
484
+ },
485
+ }
486
+ },
487
+ "google-vertex-anthropic": async () => {
488
+ const project = Env.get("GOOGLE_CLOUD_PROJECT") ?? Env.get("GCP_PROJECT") ?? Env.get("GCLOUD_PROJECT")
489
+ const location = Env.get("GOOGLE_CLOUD_LOCATION") ?? Env.get("VERTEX_LOCATION") ?? "global"
490
+ const autoload = Boolean(project)
491
+ if (!autoload) return { autoload: false }
492
+ return {
493
+ autoload: true,
494
+ options: {
495
+ project,
496
+ location,
497
+ },
498
+ async getModel(sdk: any, modelID) {
499
+ const id = String(modelID).trim()
500
+ return sdk.languageModel(id)
501
+ },
502
+ }
503
+ },
504
+ "sap-ai-core": async () => {
505
+ const auth = await Auth.get("sap-ai-core")
506
+ // TODO: Using process.env directly because Env.set only updates a shallow copy (not process.env),
507
+ // until the scope of the Env API is clarified (test only or runtime?)
508
+ const envServiceKey = iife(() => {
509
+ const envAICoreServiceKey = process.env.AICORE_SERVICE_KEY
510
+ if (envAICoreServiceKey) return envAICoreServiceKey
511
+ if (auth?.type === "api") {
512
+ process.env.AICORE_SERVICE_KEY = auth.key
513
+ return auth.key
514
+ }
515
+ return undefined
516
+ })
517
+ const deploymentId = process.env.AICORE_DEPLOYMENT_ID
518
+ const resourceGroup = process.env.AICORE_RESOURCE_GROUP
519
+
520
+ return {
521
+ autoload: !!envServiceKey,
522
+ options: envServiceKey ? { deploymentId, resourceGroup } : {},
523
+ async getModel(sdk: any, modelID: string) {
524
+ return sdk(modelID)
525
+ },
526
+ }
527
+ },
528
+ zenmux: async () => {
529
+ return {
530
+ autoload: false,
531
+ options: {
532
+ headers: {
533
+ "HTTP-Referer": "https://opencode.ai/",
534
+ "X-Title": "opencode",
535
+ },
536
+ },
537
+ }
538
+ },
539
+ gitlab: async (input) => {
540
+ const instanceUrl = Env.get("GITLAB_INSTANCE_URL") || "https://gitlab.com"
541
+
542
+ const auth = await Auth.get(input.id)
543
+ const apiKey = await (async () => {
544
+ if (auth?.type === "oauth") return auth.access
545
+ if (auth?.type === "api") return auth.key
546
+ return Env.get("GITLAB_TOKEN")
547
+ })()
548
+
549
+ const config = await Config.get()
550
+ const providerConfig = config.provider?.["gitlab"]
551
+
552
+ const aiGatewayHeaders = {
553
+ "User-Agent": `opencode/${Installation.VERSION} gitlab-ai-provider/${GITLAB_PROVIDER_VERSION} (${os.platform()} ${os.release()}; ${os.arch()})`,
554
+ "anthropic-beta": "context-1m-2025-08-07",
555
+ ...(providerConfig?.options?.aiGatewayHeaders || {}),
556
+ }
557
+
558
+ const featureFlags = {
559
+ duo_agent_platform_agentic_chat: true,
560
+ duo_agent_platform: true,
561
+ ...(providerConfig?.options?.featureFlags || {}),
562
+ }
563
+
564
+ return {
565
+ autoload: !!apiKey,
566
+ options: {
567
+ instanceUrl,
568
+ apiKey,
569
+ aiGatewayHeaders,
570
+ featureFlags,
571
+ },
572
+ async getModel(sdk: ReturnType<typeof createGitLab>, modelID: string, options?: Record<string, any>) {
573
+ if (modelID.startsWith("duo-workflow-")) {
574
+ const workflowRef = options?.workflowRef as string | undefined
575
+ // Use the static mapping if it exists, otherwise use duo-workflow with selectedModelRef
576
+ const sdkModelID = isWorkflowModel(modelID) ? modelID : "duo-workflow"
577
+ const model = sdk.workflowChat(sdkModelID, {
578
+ featureFlags,
579
+ })
580
+ if (workflowRef) {
581
+ model.selectedModelRef = workflowRef
582
+ }
583
+ return model
584
+ }
585
+ return sdk.agenticChat(modelID, {
586
+ aiGatewayHeaders,
587
+ featureFlags,
588
+ })
589
+ },
590
+ async discoverModels(): Promise<Record<string, Model>> {
591
+ if (!apiKey) {
592
+ log.info("gitlab model discovery skipped: no apiKey")
593
+ return {}
594
+ }
595
+
596
+ try {
597
+ const token = apiKey
598
+ const getHeaders = (): Record<string, string> =>
599
+ auth?.type === "api" ? { "PRIVATE-TOKEN": token } : { Authorization: `Bearer ${token}` }
600
+
601
+ log.info("gitlab model discovery starting", { instanceUrl })
602
+ const result = await discoverWorkflowModels(
603
+ { instanceUrl, getHeaders },
604
+ { workingDirectory: Instance.directory },
605
+ )
606
+
607
+ if (!result.models.length) {
608
+ log.info("gitlab model discovery skipped: no models found", {
609
+ project: result.project
610
+ ? {
611
+ id: result.project.id,
612
+ path: result.project.pathWithNamespace,
613
+ }
614
+ : null,
615
+ })
616
+ return {}
617
+ }
618
+
619
+ const models: Record<string, Model> = {}
620
+ for (const m of result.models) {
621
+ if (!input.models[m.id]) {
622
+ models[m.id] = {
623
+ id: ModelID.make(m.id),
624
+ providerID: ProviderID.make("gitlab"),
625
+ name: `Agent Platform (${m.name})`,
626
+ family: "",
627
+ api: {
628
+ id: m.id,
629
+ url: instanceUrl,
630
+ npm: "gitlab-ai-provider",
631
+ },
632
+ status: "active",
633
+ headers: {},
634
+ options: { workflowRef: m.ref },
635
+ cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
636
+ limit: { context: m.context, output: m.output },
637
+ capabilities: {
638
+ temperature: false,
639
+ reasoning: true,
640
+ attachment: true,
641
+ toolcall: true,
642
+ input: {
643
+ text: true,
644
+ audio: false,
645
+ image: true,
646
+ video: false,
647
+ pdf: true,
648
+ },
649
+ output: {
650
+ text: true,
651
+ audio: false,
652
+ image: false,
653
+ video: false,
654
+ pdf: false,
655
+ },
656
+ interleaved: false,
657
+ },
658
+ release_date: "",
659
+ variants: {},
660
+ }
661
+ }
662
+ }
663
+
664
+ log.info("gitlab model discovery complete", {
665
+ count: Object.keys(models).length,
666
+ models: Object.keys(models),
667
+ })
668
+ return models
669
+ } catch (e) {
670
+ log.warn("gitlab model discovery failed", { error: e })
671
+ return {}
672
+ }
673
+ },
674
+ }
675
+ },
676
+ "cloudflare-workers-ai": async (input) => {
677
+ const accountId = Env.get("CLOUDFLARE_ACCOUNT_ID")
678
+ if (!accountId) return { autoload: false }
679
+
680
+ const apiKey = await iife(async () => {
681
+ const envToken = Env.get("CLOUDFLARE_API_KEY")
682
+ if (envToken) return envToken
683
+ const auth = await Auth.get(input.id)
684
+ if (auth?.type === "api") return auth.key
685
+ return undefined
686
+ })
687
+
688
+ return {
689
+ autoload: !!apiKey,
690
+ options: {
691
+ apiKey,
692
+ headers: {
693
+ "User-Agent": `opencode/${Installation.VERSION} cloudflare-workers-ai (${os.platform()} ${os.release()}; ${os.arch()})`,
694
+ },
695
+ },
696
+ async getModel(sdk: any, modelID: string) {
697
+ return sdk.languageModel(modelID)
698
+ },
699
+ vars(_options) {
700
+ return {
701
+ CLOUDFLARE_ACCOUNT_ID: accountId,
702
+ }
703
+ },
704
+ }
705
+ },
706
+ "cloudflare-ai-gateway": async (input) => {
707
+ const accountId = Env.get("CLOUDFLARE_ACCOUNT_ID")
708
+ const gateway = Env.get("CLOUDFLARE_GATEWAY_ID")
709
+
710
+ if (!accountId || !gateway) return { autoload: false }
711
+
712
+ // Get API token from env or auth - required for authenticated gateways
713
+ const apiToken = await (async () => {
714
+ const envToken = Env.get("CLOUDFLARE_API_TOKEN") || Env.get("CF_AIG_TOKEN")
715
+ if (envToken) return envToken
716
+ const auth = await Auth.get(input.id)
717
+ if (auth?.type === "api") return auth.key
718
+ return undefined
719
+ })()
720
+
721
+ if (!apiToken) {
722
+ throw new Error(
723
+ "CLOUDFLARE_API_TOKEN (or CF_AIG_TOKEN) is required for Cloudflare AI Gateway. " +
724
+ "Set it via environment variable or run `opencode auth cloudflare-ai-gateway`.",
725
+ )
726
+ }
727
+
728
+ // Use official ai-gateway-provider package (v2.x for AI SDK v5 compatibility)
729
+ const { createAiGateway } = await import("ai-gateway-provider")
730
+ const { createUnified } = await import("ai-gateway-provider/providers/unified")
731
+
732
+ const metadata = iife(() => {
733
+ if (input.options?.metadata) return input.options.metadata
734
+ try {
735
+ return JSON.parse(input.options?.headers?.["cf-aig-metadata"])
736
+ } catch {
737
+ return undefined
738
+ }
739
+ })
740
+ const opts = {
741
+ metadata,
742
+ cacheTtl: input.options?.cacheTtl,
743
+ cacheKey: input.options?.cacheKey,
744
+ skipCache: input.options?.skipCache,
745
+ collectLog: input.options?.collectLog,
746
+ headers: {
747
+ "User-Agent": `opencode/${Installation.VERSION} cloudflare-ai-gateway (${os.platform()} ${os.release()}; ${os.arch()})`,
748
+ },
749
+ }
750
+
751
+ const aigateway = createAiGateway({
752
+ accountId,
753
+ gateway,
754
+ apiKey: apiToken,
755
+ ...(Object.values(opts).some((v) => v !== undefined) ? { options: opts } : {}),
756
+ })
757
+ const unified = createUnified()
758
+
759
+ return {
760
+ autoload: true,
761
+ async getModel(_sdk: any, modelID: string, _options?: Record<string, any>) {
762
+ // Model IDs use Unified API format: provider/model (e.g., "anthropic/claude-sonnet-4-5")
763
+ return aigateway(unified(modelID))
764
+ },
765
+ options: {},
766
+ }
767
+ },
768
+ cerebras: async () => {
769
+ return {
770
+ autoload: false,
771
+ options: {
772
+ headers: {
773
+ "X-Cerebras-3rd-Party-Integration": "opencode",
774
+ },
775
+ },
776
+ }
777
+ },
778
+ kilo: async () => {
779
+ return {
780
+ autoload: false,
781
+ options: {
782
+ headers: {
783
+ "HTTP-Referer": "https://opencode.ai/",
784
+ "X-Title": "opencode",
785
+ },
786
+ },
787
+ }
788
+ },
789
+ }
790
+
791
+ export const Model = z
792
+ .object({
793
+ id: ModelID.zod,
794
+ providerID: ProviderID.zod,
795
+ api: z.object({
796
+ id: z.string(),
797
+ url: z.string(),
798
+ npm: z.string(),
799
+ }),
800
+ name: z.string(),
801
+ family: z.string().optional(),
802
+ capabilities: z.object({
803
+ temperature: z.boolean(),
804
+ reasoning: z.boolean(),
805
+ attachment: z.boolean(),
806
+ toolcall: z.boolean(),
807
+ input: z.object({
808
+ text: z.boolean(),
809
+ audio: z.boolean(),
810
+ image: z.boolean(),
811
+ video: z.boolean(),
812
+ pdf: z.boolean(),
813
+ }),
814
+ output: z.object({
815
+ text: z.boolean(),
816
+ audio: z.boolean(),
817
+ image: z.boolean(),
818
+ video: z.boolean(),
819
+ pdf: z.boolean(),
820
+ }),
821
+ interleaved: z.union([
822
+ z.boolean(),
823
+ z.object({
824
+ field: z.enum(["reasoning_content", "reasoning_details"]),
825
+ }),
826
+ ]),
827
+ }),
828
+ cost: z.object({
829
+ input: z.number(),
830
+ output: z.number(),
831
+ cache: z.object({
832
+ read: z.number(),
833
+ write: z.number(),
834
+ }),
835
+ experimentalOver200K: z
836
+ .object({
837
+ input: z.number(),
838
+ output: z.number(),
839
+ cache: z.object({
840
+ read: z.number(),
841
+ write: z.number(),
842
+ }),
843
+ })
844
+ .optional(),
845
+ }),
846
+ limit: z.object({
847
+ context: z.number(),
848
+ input: z.number().optional(),
849
+ output: z.number(),
850
+ }),
851
+ status: z.enum(["alpha", "beta", "deprecated", "active"]),
852
+ options: z.record(z.string(), z.any()),
853
+ headers: z.record(z.string(), z.string()),
854
+ release_date: z.string(),
855
+ variants: z.record(z.string(), z.record(z.string(), z.any())).optional(),
856
+ })
857
+ .meta({
858
+ ref: "Model",
859
+ })
860
+ export type Model = z.infer<typeof Model>
861
+
862
+ export const Info = z
863
+ .object({
864
+ id: ProviderID.zod,
865
+ name: z.string(),
866
+ source: z.enum(["env", "config", "custom", "api"]),
867
+ env: z.string().array(),
868
+ key: z.string().optional(),
869
+ options: z.record(z.string(), z.any()),
870
+ models: z.record(z.string(), Model),
871
+ })
872
+ .meta({
873
+ ref: "Provider",
874
+ })
875
+ export type Info = z.infer<typeof Info>
876
+
877
+ export interface Interface {
878
+ readonly list: () => Effect.Effect<Record<ProviderID, Info>>
879
+ readonly getProvider: (providerID: ProviderID) => Effect.Effect<Info>
880
+ readonly getModel: (providerID: ProviderID, modelID: ModelID) => Effect.Effect<Model>
881
+ readonly getLanguage: (model: Model) => Effect.Effect<LanguageModelV3>
882
+ readonly closest: (
883
+ providerID: ProviderID,
884
+ query: string[],
885
+ ) => Effect.Effect<{ providerID: ProviderID; modelID: string } | undefined>
886
+ readonly getSmallModel: (providerID: ProviderID) => Effect.Effect<Model | undefined>
887
+ readonly defaultModel: () => Effect.Effect<{ providerID: ProviderID; modelID: ModelID }>
888
+ }
889
+
890
+ interface State {
891
+ models: Map<string, LanguageModelV3>
892
+ providers: Record<ProviderID, Info>
893
+ sdk: Map<string, BundledSDK>
894
+ modelLoaders: Record<string, CustomModelLoader>
895
+ varsLoaders: Record<string, CustomVarsLoader>
896
+ }
897
+
898
+ export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/Provider") {}
899
+
900
+ function fromModelsDevModel(provider: ModelsDev.Provider, model: ModelsDev.Model): Model {
901
+ const m: Model = {
902
+ id: ModelID.make(model.id),
903
+ providerID: ProviderID.make(provider.id),
904
+ name: model.name,
905
+ family: model.family,
906
+ api: {
907
+ id: model.id,
908
+ url: model.provider?.api ?? provider.api!,
909
+ npm: model.provider?.npm ?? provider.npm ?? "@ai-sdk/openai-compatible",
910
+ },
911
+ status: model.status ?? "active",
912
+ headers: model.headers ?? {},
913
+ options: model.options ?? {},
914
+ cost: {
915
+ input: model.cost?.input ?? 0,
916
+ output: model.cost?.output ?? 0,
917
+ cache: {
918
+ read: model.cost?.cache_read ?? 0,
919
+ write: model.cost?.cache_write ?? 0,
920
+ },
921
+ experimentalOver200K: model.cost?.context_over_200k
922
+ ? {
923
+ cache: {
924
+ read: model.cost.context_over_200k.cache_read ?? 0,
925
+ write: model.cost.context_over_200k.cache_write ?? 0,
926
+ },
927
+ input: model.cost.context_over_200k.input,
928
+ output: model.cost.context_over_200k.output,
929
+ }
930
+ : undefined,
931
+ },
932
+ limit: {
933
+ context: model.limit.context,
934
+ input: model.limit.input,
935
+ output: model.limit.output,
936
+ },
937
+ capabilities: {
938
+ temperature: model.temperature,
939
+ reasoning: model.reasoning,
940
+ attachment: model.attachment,
941
+ toolcall: model.tool_call,
942
+ input: {
943
+ text: model.modalities?.input?.includes("text") ?? false,
944
+ audio: model.modalities?.input?.includes("audio") ?? false,
945
+ image: model.modalities?.input?.includes("image") ?? false,
946
+ video: model.modalities?.input?.includes("video") ?? false,
947
+ pdf: model.modalities?.input?.includes("pdf") ?? false,
948
+ },
949
+ output: {
950
+ text: model.modalities?.output?.includes("text") ?? false,
951
+ audio: model.modalities?.output?.includes("audio") ?? false,
952
+ image: model.modalities?.output?.includes("image") ?? false,
953
+ video: model.modalities?.output?.includes("video") ?? false,
954
+ pdf: model.modalities?.output?.includes("pdf") ?? false,
955
+ },
956
+ interleaved: model.interleaved ?? false,
957
+ },
958
+ release_date: model.release_date,
959
+ variants: {},
960
+ }
961
+
962
+ m.variants = mapValues(ProviderTransform.variants(m), (v) => v)
963
+
964
+ return m
965
+ }
966
+
967
+ export function fromModelsDevProvider(provider: ModelsDev.Provider): Info {
968
+ return {
969
+ id: ProviderID.make(provider.id),
970
+ source: "custom",
971
+ name: provider.name,
972
+ env: provider.env ?? [],
973
+ options: {},
974
+ models: mapValues(provider.models, (model) => fromModelsDevModel(provider, model)),
975
+ }
976
+ }
977
+
978
+ const layer: Layer.Layer<Service, never, Config.Service | Auth.Service | Plugin.Service> = Layer.effect(
979
+ Service,
980
+ Effect.gen(function* () {
981
+ const config = yield* Config.Service
982
+ const auth = yield* Auth.Service
983
+ const plugin = yield* Plugin.Service
984
+
985
+ const state = yield* InstanceState.make<State>(() =>
986
+ Effect.gen(function* () {
987
+ using _ = log.time("state")
988
+ const cfg = yield* config.get()
989
+ const modelsDev = yield* Effect.promise(() => ModelsDev.get())
990
+ const database = mapValues(modelsDev, fromModelsDevProvider)
991
+
992
+ const disabled = new Set(cfg.disabled_providers ?? [])
993
+ const enabled = cfg.enabled_providers ? new Set(cfg.enabled_providers) : null
994
+
995
+ function isProviderAllowed(providerID: ProviderID): boolean {
996
+ if (enabled && !enabled.has(providerID)) return false
997
+ if (disabled.has(providerID)) return false
998
+ return true
999
+ }
1000
+
1001
+ const providers: Record<ProviderID, Info> = {} as Record<ProviderID, Info>
1002
+ const languages = new Map<string, LanguageModelV3>()
1003
+ const modelLoaders: {
1004
+ [providerID: string]: CustomModelLoader
1005
+ } = {}
1006
+ const varsLoaders: {
1007
+ [providerID: string]: CustomVarsLoader
1008
+ } = {}
1009
+ const sdk = new Map<string, BundledSDK>()
1010
+ const discoveryLoaders: {
1011
+ [providerID: string]: CustomDiscoverModels
1012
+ } = {}
1013
+
1014
+ log.info("init")
1015
+
1016
+ const configProviders = Object.entries(cfg.provider ?? {})
1017
+
1018
+ function mergeProvider(providerID: ProviderID, provider: Partial<Info>) {
1019
+ const existing = providers[providerID]
1020
+ if (existing) {
1021
+ // @ts-expect-error
1022
+ providers[providerID] = mergeDeep(existing, provider)
1023
+ return
1024
+ }
1025
+ const match = database[providerID]
1026
+ if (!match) return
1027
+ // @ts-expect-error
1028
+ providers[providerID] = mergeDeep(match, provider)
1029
+ }
1030
+
1031
+ // extend database from config
1032
+ for (const [providerID, provider] of configProviders) {
1033
+ const existing = database[providerID]
1034
+ const parsed: Info = {
1035
+ id: ProviderID.make(providerID),
1036
+ name: provider.name ?? existing?.name ?? providerID,
1037
+ env: provider.env ?? existing?.env ?? [],
1038
+ options: mergeDeep(existing?.options ?? {}, provider.options ?? {}),
1039
+ source: "config",
1040
+ models: existing?.models ?? {},
1041
+ }
1042
+
1043
+ for (const [modelID, model] of Object.entries(provider.models ?? {})) {
1044
+ const existingModel = parsed.models[model.id ?? modelID]
1045
+ const name = iife(() => {
1046
+ if (model.name) return model.name
1047
+ if (model.id && model.id !== modelID) return modelID
1048
+ return existingModel?.name ?? modelID
1049
+ })
1050
+ const parsedModel: Model = {
1051
+ id: ModelID.make(modelID),
1052
+ api: {
1053
+ id: model.id ?? existingModel?.api.id ?? modelID,
1054
+ npm:
1055
+ model.provider?.npm ??
1056
+ provider.npm ??
1057
+ existingModel?.api.npm ??
1058
+ modelsDev[providerID]?.npm ??
1059
+ "@ai-sdk/openai-compatible",
1060
+ url: model.provider?.api ?? provider?.api ?? existingModel?.api.url ?? modelsDev[providerID]?.api,
1061
+ },
1062
+ status: model.status ?? existingModel?.status ?? "active",
1063
+ name,
1064
+ providerID: ProviderID.make(providerID),
1065
+ capabilities: {
1066
+ temperature: model.temperature ?? existingModel?.capabilities.temperature ?? false,
1067
+ reasoning: model.reasoning ?? existingModel?.capabilities.reasoning ?? false,
1068
+ attachment: model.attachment ?? existingModel?.capabilities.attachment ?? false,
1069
+ toolcall: model.tool_call ?? existingModel?.capabilities.toolcall ?? true,
1070
+ input: {
1071
+ text: model.modalities?.input?.includes("text") ?? existingModel?.capabilities.input.text ?? true,
1072
+ audio:
1073
+ model.modalities?.input?.includes("audio") ?? existingModel?.capabilities.input.audio ?? false,
1074
+ image:
1075
+ model.modalities?.input?.includes("image") ?? existingModel?.capabilities.input.image ?? false,
1076
+ video:
1077
+ model.modalities?.input?.includes("video") ?? existingModel?.capabilities.input.video ?? false,
1078
+ pdf: model.modalities?.input?.includes("pdf") ?? existingModel?.capabilities.input.pdf ?? false,
1079
+ },
1080
+ output: {
1081
+ text: model.modalities?.output?.includes("text") ?? existingModel?.capabilities.output.text ?? true,
1082
+ audio:
1083
+ model.modalities?.output?.includes("audio") ?? existingModel?.capabilities.output.audio ?? false,
1084
+ image:
1085
+ model.modalities?.output?.includes("image") ?? existingModel?.capabilities.output.image ?? false,
1086
+ video:
1087
+ model.modalities?.output?.includes("video") ?? existingModel?.capabilities.output.video ?? false,
1088
+ pdf: model.modalities?.output?.includes("pdf") ?? existingModel?.capabilities.output.pdf ?? false,
1089
+ },
1090
+ interleaved: model.interleaved ?? false,
1091
+ },
1092
+ cost: {
1093
+ input: model?.cost?.input ?? existingModel?.cost?.input ?? 0,
1094
+ output: model?.cost?.output ?? existingModel?.cost?.output ?? 0,
1095
+ cache: {
1096
+ read: model?.cost?.cache_read ?? existingModel?.cost?.cache.read ?? 0,
1097
+ write: model?.cost?.cache_write ?? existingModel?.cost?.cache.write ?? 0,
1098
+ },
1099
+ },
1100
+ options: mergeDeep(existingModel?.options ?? {}, model.options ?? {}),
1101
+ limit: {
1102
+ context: model.limit?.context ?? existingModel?.limit?.context ?? 0,
1103
+ input: model.limit?.input ?? existingModel?.limit?.input,
1104
+ output: model.limit?.output ?? existingModel?.limit?.output ?? 0,
1105
+ },
1106
+ headers: mergeDeep(existingModel?.headers ?? {}, model.headers ?? {}),
1107
+ family: model.family ?? existingModel?.family ?? "",
1108
+ release_date: model.release_date ?? existingModel?.release_date ?? "",
1109
+ variants: {},
1110
+ }
1111
+ const merged = mergeDeep(ProviderTransform.variants(parsedModel), model.variants ?? {})
1112
+ parsedModel.variants = mapValues(
1113
+ pickBy(merged, (v) => !v.disabled),
1114
+ (v) => omit(v, ["disabled"]),
1115
+ )
1116
+ parsed.models[modelID] = parsedModel
1117
+ }
1118
+ database[providerID] = parsed
1119
+ }
1120
+
1121
+ // load env
1122
+ const env = Env.all()
1123
+ for (const [id, provider] of Object.entries(database)) {
1124
+ const providerID = ProviderID.make(id)
1125
+ if (disabled.has(providerID)) continue
1126
+ const apiKey = provider.env.map((item) => env[item]).find(Boolean)
1127
+ if (!apiKey) continue
1128
+ mergeProvider(providerID, {
1129
+ source: "env",
1130
+ key: provider.env.length === 1 ? apiKey : undefined,
1131
+ })
1132
+ }
1133
+
1134
+ // load apikeys
1135
+ const auths = yield* auth.all().pipe(Effect.orDie)
1136
+ for (const [id, provider] of Object.entries(auths)) {
1137
+ const providerID = ProviderID.make(id)
1138
+ if (disabled.has(providerID)) continue
1139
+ if (provider.type === "api") {
1140
+ mergeProvider(providerID, {
1141
+ source: "api",
1142
+ key: provider.key,
1143
+ })
1144
+ }
1145
+ }
1146
+
1147
+ const plugins = yield* plugin.list()
1148
+ for (const plugin of plugins) {
1149
+ if (!plugin.auth) continue
1150
+ const providerID = ProviderID.make(plugin.auth.provider)
1151
+ if (disabled.has(providerID)) continue
1152
+
1153
+ const pluginAuth = yield* auth.get(providerID).pipe(Effect.orDie)
1154
+ if (!pluginAuth) continue
1155
+ if (!plugin.auth.loader) continue
1156
+
1157
+ const options = yield* Effect.promise(() =>
1158
+ plugin.auth!.loader!(() => Auth.get(providerID) as any, database[plugin.auth!.provider]),
1159
+ )
1160
+ const opts = options ?? {}
1161
+ const patch: Partial<Info> = providers[providerID] ? { options: opts } : { source: "custom", options: opts }
1162
+ mergeProvider(providerID, patch)
1163
+ }
1164
+
1165
+ for (const [id, fn] of Object.entries(CUSTOM_LOADERS)) {
1166
+ const providerID = ProviderID.make(id)
1167
+ if (disabled.has(providerID)) continue
1168
+ const data = database[providerID]
1169
+ if (!data) {
1170
+ log.error("Provider does not exist in model list " + providerID)
1171
+ continue
1172
+ }
1173
+ const result = yield* Effect.promise(() => fn(data))
1174
+ if (result && (result.autoload || providers[providerID])) {
1175
+ if (result.getModel) modelLoaders[providerID] = result.getModel
1176
+ if (result.vars) varsLoaders[providerID] = result.vars
1177
+ if (result.discoverModels) discoveryLoaders[providerID] = result.discoverModels
1178
+ const opts = result.options ?? {}
1179
+ const patch: Partial<Info> = providers[providerID]
1180
+ ? { options: opts }
1181
+ : { source: "custom", options: opts }
1182
+ mergeProvider(providerID, patch)
1183
+ }
1184
+ }
1185
+
1186
+ // load config
1187
+ for (const [id, provider] of configProviders) {
1188
+ const providerID = ProviderID.make(id)
1189
+ const partial: Partial<Info> = { source: "config" }
1190
+ if (provider.env) partial.env = provider.env
1191
+ if (provider.name) partial.name = provider.name
1192
+ if (provider.options) partial.options = provider.options
1193
+ mergeProvider(providerID, partial)
1194
+ }
1195
+
1196
+ const gitlab = ProviderID.make("gitlab")
1197
+ if (discoveryLoaders[gitlab] && providers[gitlab] && isProviderAllowed(gitlab)) {
1198
+ yield* Effect.promise(async () => {
1199
+ try {
1200
+ const discovered = await discoveryLoaders[gitlab]()
1201
+ for (const [modelID, model] of Object.entries(discovered)) {
1202
+ if (!providers[gitlab].models[modelID]) {
1203
+ providers[gitlab].models[modelID] = model
1204
+ }
1205
+ }
1206
+ } catch (e) {
1207
+ log.warn("state discovery error", { id: "gitlab", error: e })
1208
+ }
1209
+ })
1210
+ }
1211
+
1212
+ for (const hook of plugins) {
1213
+ const p = hook.provider
1214
+ const models = p?.models
1215
+ if (!p || !models) continue
1216
+
1217
+ const providerID = ProviderID.make(p.id)
1218
+ if (disabled.has(providerID)) continue
1219
+
1220
+ const provider = providers[providerID]
1221
+ if (!provider) continue
1222
+ const pluginAuth = yield* auth.get(providerID).pipe(Effect.orDie)
1223
+
1224
+ provider.models = yield* Effect.promise(async () => {
1225
+ const next = await models(provider, { auth: pluginAuth })
1226
+ return Object.fromEntries(
1227
+ Object.entries(next).map(([id, model]) => [
1228
+ id,
1229
+ {
1230
+ ...model,
1231
+ id: ModelID.make(id),
1232
+ providerID,
1233
+ },
1234
+ ]),
1235
+ )
1236
+ })
1237
+ }
1238
+
1239
+ for (const [id, provider] of Object.entries(providers)) {
1240
+ const providerID = ProviderID.make(id)
1241
+ if (!isProviderAllowed(providerID)) {
1242
+ delete providers[providerID]
1243
+ continue
1244
+ }
1245
+
1246
+ const configProvider = cfg.provider?.[providerID]
1247
+
1248
+ for (const [modelID, model] of Object.entries(provider.models)) {
1249
+ model.api.id = model.api.id ?? model.id ?? modelID
1250
+ if (
1251
+ modelID === "gpt-5-chat-latest" ||
1252
+ (providerID === ProviderID.openrouter && modelID === "openai/gpt-5-chat")
1253
+ )
1254
+ delete provider.models[modelID]
1255
+ if (model.status === "alpha" && !Flag.OPENCODE_ENABLE_EXPERIMENTAL_MODELS) delete provider.models[modelID]
1256
+ if (model.status === "deprecated") delete provider.models[modelID]
1257
+ if (
1258
+ (configProvider?.blacklist && configProvider.blacklist.includes(modelID)) ||
1259
+ (configProvider?.whitelist && !configProvider.whitelist.includes(modelID))
1260
+ )
1261
+ delete provider.models[modelID]
1262
+
1263
+ model.variants = mapValues(ProviderTransform.variants(model), (v) => v)
1264
+
1265
+ const configVariants = configProvider?.models?.[modelID]?.variants
1266
+ if (configVariants && model.variants) {
1267
+ const merged = mergeDeep(model.variants, configVariants)
1268
+ model.variants = mapValues(
1269
+ pickBy(merged, (v) => !v.disabled),
1270
+ (v) => omit(v, ["disabled"]),
1271
+ )
1272
+ }
1273
+ }
1274
+
1275
+ if (Object.keys(provider.models).length === 0) {
1276
+ delete providers[providerID]
1277
+ continue
1278
+ }
1279
+
1280
+ log.info("found", { providerID })
1281
+ }
1282
+
1283
+ return {
1284
+ models: languages,
1285
+ providers,
1286
+ sdk,
1287
+ modelLoaders,
1288
+ varsLoaders,
1289
+ }
1290
+ }),
1291
+ )
1292
+
1293
+ const list = Effect.fn("Provider.list")(() => InstanceState.use(state, (s) => s.providers))
1294
+
1295
+ async function resolveSDK(model: Model, s: State) {
1296
+ try {
1297
+ using _ = log.time("getSDK", {
1298
+ providerID: model.providerID,
1299
+ })
1300
+ const provider = s.providers[model.providerID]
1301
+ const options = { ...provider.options }
1302
+
1303
+ if (model.providerID === "google-vertex" && !model.api.npm.includes("@ai-sdk/openai-compatible")) {
1304
+ delete options.fetch
1305
+ }
1306
+
1307
+ if (model.api.npm.includes("@ai-sdk/openai-compatible") && options["includeUsage"] !== false) {
1308
+ options["includeUsage"] = true
1309
+ }
1310
+
1311
+ const baseURL = iife(() => {
1312
+ let url =
1313
+ typeof options["baseURL"] === "string" && options["baseURL"] !== "" ? options["baseURL"] : model.api.url
1314
+ if (!url) return
1315
+
1316
+ const loader = s.varsLoaders[model.providerID]
1317
+ if (loader) {
1318
+ const vars = loader(options)
1319
+ for (const [key, value] of Object.entries(vars)) {
1320
+ const field = "${" + key + "}"
1321
+ url = url.replaceAll(field, value)
1322
+ }
1323
+ }
1324
+
1325
+ url = url.replace(/\$\{([^}]+)\}/g, (item, key) => {
1326
+ const val = Env.get(String(key))
1327
+ return val ?? item
1328
+ })
1329
+ return url
1330
+ })
1331
+
1332
+ if (baseURL !== undefined) options["baseURL"] = baseURL
1333
+ if (options["apiKey"] === undefined && provider.key) options["apiKey"] = provider.key
1334
+ if (model.headers)
1335
+ options["headers"] = {
1336
+ ...options["headers"],
1337
+ ...model.headers,
1338
+ }
1339
+
1340
+ const key = Hash.fast(
1341
+ JSON.stringify({
1342
+ providerID: model.providerID,
1343
+ npm: model.api.npm,
1344
+ options,
1345
+ }),
1346
+ )
1347
+ const existing = s.sdk.get(key)
1348
+ if (existing) return existing
1349
+
1350
+ const customFetch = options["fetch"]
1351
+ const chunkTimeout = options["chunkTimeout"]
1352
+ delete options["chunkTimeout"]
1353
+
1354
+ options["fetch"] = async (input: any, init?: BunFetchRequestInit) => {
1355
+ const fetchFn = customFetch ?? fetch
1356
+ const opts = init ?? {}
1357
+ const chunkAbortCtl =
1358
+ typeof chunkTimeout === "number" && chunkTimeout > 0 ? new AbortController() : undefined
1359
+ const signals: AbortSignal[] = []
1360
+
1361
+ if (opts.signal) signals.push(opts.signal)
1362
+ if (chunkAbortCtl) signals.push(chunkAbortCtl.signal)
1363
+ if (options["timeout"] !== undefined && options["timeout"] !== null && options["timeout"] !== false)
1364
+ signals.push(AbortSignal.timeout(options["timeout"]))
1365
+
1366
+ const combined = signals.length === 0 ? null : signals.length === 1 ? signals[0] : AbortSignal.any(signals)
1367
+ if (combined) opts.signal = combined
1368
+
1369
+ // Strip openai itemId metadata following what codex does
1370
+ if (model.api.npm === "@ai-sdk/openai" && opts.body && opts.method === "POST") {
1371
+ const body = JSON.parse(opts.body as string)
1372
+ const isAzure = model.providerID.includes("azure")
1373
+ const keepIds = isAzure && body.store === true
1374
+ if (!keepIds && Array.isArray(body.input)) {
1375
+ for (const item of body.input) {
1376
+ if ("id" in item) {
1377
+ delete item.id
1378
+ }
1379
+ }
1380
+ opts.body = JSON.stringify(body)
1381
+ }
1382
+ }
1383
+
1384
+ const res = await fetchFn(input, {
1385
+ ...opts,
1386
+ // @ts-ignore see here: https://github.com/oven-sh/bun/issues/16682
1387
+ timeout: false,
1388
+ })
1389
+
1390
+ if (!chunkAbortCtl) return res
1391
+ return wrapSSE(res, chunkTimeout, chunkAbortCtl)
1392
+ }
1393
+
1394
+ const bundledFn = BUNDLED_PROVIDERS[model.api.npm]
1395
+ if (bundledFn) {
1396
+ log.info("using bundled provider", {
1397
+ providerID: model.providerID,
1398
+ pkg: model.api.npm,
1399
+ })
1400
+ const loaded = bundledFn({
1401
+ name: model.providerID,
1402
+ ...options,
1403
+ })
1404
+ s.sdk.set(key, loaded)
1405
+ return loaded as SDK
1406
+ }
1407
+
1408
+ let installedPath: string
1409
+ if (!model.api.npm.startsWith("file://")) {
1410
+ const item = await Npm.add(model.api.npm)
1411
+ if (!item.entrypoint) throw new Error(`Package ${model.api.npm} has no import entrypoint`)
1412
+ installedPath = item.entrypoint
1413
+ } else {
1414
+ log.info("loading local provider", { pkg: model.api.npm })
1415
+ installedPath = model.api.npm
1416
+ }
1417
+
1418
+ const mod = await import(installedPath)
1419
+
1420
+ const fn = mod[Object.keys(mod).find((key) => key.startsWith("create"))!]
1421
+ const loaded = fn({
1422
+ name: model.providerID,
1423
+ ...options,
1424
+ })
1425
+ s.sdk.set(key, loaded)
1426
+ return loaded as SDK
1427
+ } catch (e) {
1428
+ throw new InitError({ providerID: model.providerID }, { cause: e })
1429
+ }
1430
+ }
1431
+
1432
+ const getProvider = Effect.fn("Provider.getProvider")((providerID: ProviderID) =>
1433
+ InstanceState.use(state, (s) => s.providers[providerID]),
1434
+ )
1435
+
1436
+ const getModel = Effect.fn("Provider.getModel")(function* (providerID: ProviderID, modelID: ModelID) {
1437
+ const s = yield* InstanceState.get(state)
1438
+ const provider = s.providers[providerID]
1439
+ if (!provider) {
1440
+ const available = Object.keys(s.providers)
1441
+ const matches = fuzzysort.go(providerID, available, { limit: 3, threshold: -10000 })
1442
+ throw new ModelNotFoundError({ providerID, modelID, suggestions: matches.map((m) => m.target) })
1443
+ }
1444
+
1445
+ const info = provider.models[modelID]
1446
+ if (!info) {
1447
+ const available = Object.keys(provider.models)
1448
+ const matches = fuzzysort.go(modelID, available, { limit: 3, threshold: -10000 })
1449
+ throw new ModelNotFoundError({ providerID, modelID, suggestions: matches.map((m) => m.target) })
1450
+ }
1451
+ return info
1452
+ })
1453
+
1454
+ const getLanguage = Effect.fn("Provider.getLanguage")(function* (model: Model) {
1455
+ const s = yield* InstanceState.get(state)
1456
+ const key = `${model.providerID}/${model.id}`
1457
+ if (s.models.has(key)) return s.models.get(key)!
1458
+
1459
+ return yield* Effect.promise(async () => {
1460
+ const url = e2eURL()
1461
+ if (url) {
1462
+ const language = createOpenAICompatible({
1463
+ name: model.providerID,
1464
+ apiKey: "test-key",
1465
+ baseURL: url,
1466
+ }).chatModel(model.api.id)
1467
+ s.models.set(key, language)
1468
+ return language
1469
+ }
1470
+
1471
+ const provider = s.providers[model.providerID]
1472
+ const sdk = await resolveSDK(model, s)
1473
+
1474
+ try {
1475
+ const language = s.modelLoaders[model.providerID]
1476
+ ? await s.modelLoaders[model.providerID](sdk, model.api.id, {
1477
+ ...provider.options,
1478
+ ...model.options,
1479
+ })
1480
+ : sdk.languageModel(model.api.id)
1481
+ s.models.set(key, language)
1482
+ return language
1483
+ } catch (e) {
1484
+ if (e instanceof NoSuchModelError)
1485
+ throw new ModelNotFoundError(
1486
+ {
1487
+ modelID: model.id,
1488
+ providerID: model.providerID,
1489
+ },
1490
+ { cause: e },
1491
+ )
1492
+ throw e
1493
+ }
1494
+ })
1495
+ })
1496
+
1497
+ const closest = Effect.fn("Provider.closest")(function* (providerID: ProviderID, query: string[]) {
1498
+ const s = yield* InstanceState.get(state)
1499
+ const provider = s.providers[providerID]
1500
+ if (!provider) return undefined
1501
+ for (const item of query) {
1502
+ for (const modelID of Object.keys(provider.models)) {
1503
+ if (modelID.includes(item)) return { providerID, modelID }
1504
+ }
1505
+ }
1506
+ return undefined
1507
+ })
1508
+
1509
+ const getSmallModel = Effect.fn("Provider.getSmallModel")(function* (providerID: ProviderID) {
1510
+ const cfg = yield* config.get()
1511
+
1512
+ if (cfg.small_model) {
1513
+ const parsed = parseModel(cfg.small_model)
1514
+ return yield* getModel(parsed.providerID, parsed.modelID)
1515
+ }
1516
+
1517
+ const s = yield* InstanceState.get(state)
1518
+ const provider = s.providers[providerID]
1519
+ if (!provider) return undefined
1520
+
1521
+ let priority = [
1522
+ "claude-haiku-4-5",
1523
+ "claude-haiku-4.5",
1524
+ "3-5-haiku",
1525
+ "3.5-haiku",
1526
+ "gemini-3-flash",
1527
+ "gemini-2.5-flash",
1528
+ "gpt-5-nano",
1529
+ ]
1530
+ if (providerID.startsWith("opencode")) {
1531
+ priority = ["gpt-5-nano"]
1532
+ }
1533
+ if (providerID.startsWith("github-copilot")) {
1534
+ priority = ["gpt-5-mini", "claude-haiku-4.5", ...priority]
1535
+ }
1536
+ for (const item of priority) {
1537
+ if (providerID === ProviderID.amazonBedrock) {
1538
+ const crossRegionPrefixes = ["global.", "us.", "eu."]
1539
+ const candidates = Object.keys(provider.models).filter((m) => m.includes(item))
1540
+
1541
+ const globalMatch = candidates.find((m) => m.startsWith("global."))
1542
+ if (globalMatch) return yield* getModel(providerID, ModelID.make(globalMatch))
1543
+
1544
+ const region = provider.options?.region
1545
+ if (region) {
1546
+ const regionPrefix = region.split("-")[0]
1547
+ if (regionPrefix === "us" || regionPrefix === "eu") {
1548
+ const regionalMatch = candidates.find((m) => m.startsWith(`${regionPrefix}.`))
1549
+ if (regionalMatch) return yield* getModel(providerID, ModelID.make(regionalMatch))
1550
+ }
1551
+ }
1552
+
1553
+ const unprefixed = candidates.find((m) => !crossRegionPrefixes.some((p) => m.startsWith(p)))
1554
+ if (unprefixed) return yield* getModel(providerID, ModelID.make(unprefixed))
1555
+ } else {
1556
+ for (const model of Object.keys(provider.models)) {
1557
+ if (model.includes(item)) return yield* getModel(providerID, ModelID.make(model))
1558
+ }
1559
+ }
1560
+ }
1561
+
1562
+ return undefined
1563
+ })
1564
+
1565
+ const defaultModel = Effect.fn("Provider.defaultModel")(function* () {
1566
+ const cfg = yield* config.get()
1567
+ if (cfg.model) return parseModel(cfg.model)
1568
+
1569
+ const s = yield* InstanceState.get(state)
1570
+ const recent = yield* Effect.promise(() =>
1571
+ Filesystem.readJson<{
1572
+ recent?: { providerID: ProviderID; modelID: ModelID }[]
1573
+ }>(path.join(Global.Path.state, "model.json"))
1574
+ .then((x): { providerID: ProviderID; modelID: ModelID }[] => (Array.isArray(x.recent) ? x.recent : []))
1575
+ .catch((): { providerID: ProviderID; modelID: ModelID }[] => []),
1576
+ )
1577
+ for (const entry of recent) {
1578
+ const provider = s.providers[entry.providerID]
1579
+ if (!provider) continue
1580
+ if (!provider.models[entry.modelID]) continue
1581
+ return { providerID: entry.providerID, modelID: entry.modelID }
1582
+ }
1583
+
1584
+ // Try opencode/big-pickle as default fallback
1585
+ const opencodeProvider = s.providers["opencode"]
1586
+ if (opencodeProvider && opencodeProvider.models["big-pickle"]) {
1587
+ return { providerID: ProviderID.opencode, modelID: ModelID.make("big-pickle") }
1588
+ }
1589
+
1590
+ const provider = Object.values(s.providers).find(
1591
+ (p) => !cfg.provider || Object.keys(cfg.provider).includes(p.id),
1592
+ )
1593
+ if (!provider) throw new Error("no providers found")
1594
+ const [model] = sort(Object.values(provider.models))
1595
+ if (!model) throw new Error("no models found")
1596
+ return {
1597
+ providerID: provider.id,
1598
+ modelID: model.id,
1599
+ }
1600
+ })
1601
+
1602
+ return Service.of({ list, getProvider, getModel, getLanguage, closest, getSmallModel, defaultModel })
1603
+ }),
1604
+ )
1605
+
1606
+ export const defaultLayer = Layer.suspend(() =>
1607
+ layer.pipe(
1608
+ Layer.provide(Config.defaultLayer),
1609
+ Layer.provide(Auth.defaultLayer),
1610
+ Layer.provide(Plugin.defaultLayer),
1611
+ ),
1612
+ )
1613
+
1614
+ const { runPromise } = makeRuntime(Service, defaultLayer)
1615
+
1616
+ export async function list() {
1617
+ return runPromise((svc) => svc.list())
1618
+ }
1619
+
1620
+ export async function getProvider(providerID: ProviderID) {
1621
+ return runPromise((svc) => svc.getProvider(providerID))
1622
+ }
1623
+
1624
+ export async function getModel(providerID: ProviderID, modelID: ModelID) {
1625
+ return runPromise((svc) => svc.getModel(providerID, modelID))
1626
+ }
1627
+
1628
+ export async function getLanguage(model: Model) {
1629
+ return runPromise((svc) => svc.getLanguage(model))
1630
+ }
1631
+
1632
+ export async function closest(providerID: ProviderID, query: string[]) {
1633
+ return runPromise((svc) => svc.closest(providerID, query))
1634
+ }
1635
+
1636
+ export async function getSmallModel(providerID: ProviderID) {
1637
+ return runPromise((svc) => svc.getSmallModel(providerID))
1638
+ }
1639
+
1640
+ export async function defaultModel() {
1641
+ return runPromise((svc) => svc.defaultModel())
1642
+ }
1643
+
1644
+ const priority = ["gpt-5", "claude-sonnet-4", "big-pickle", "gemini-3-pro"]
1645
+ export function sort<T extends { id: string }>(models: T[]) {
1646
+ return sortBy(
1647
+ models,
1648
+ [(model) => priority.findIndex((filter) => model.id.includes(filter)), "desc"],
1649
+ [(model) => (model.id.includes("latest") ? 0 : 1), "asc"],
1650
+ [(model) => model.id, "desc"],
1651
+ )
1652
+ }
1653
+
1654
+ export function parseModel(model: string) {
1655
+ const [providerID, ...rest] = model.split("/")
1656
+ return {
1657
+ providerID: ProviderID.make(providerID),
1658
+ modelID: ModelID.make(rest.join("/")),
1659
+ }
1660
+ }
1661
+
1662
+ export const ModelNotFoundError = NamedError.create(
1663
+ "ProviderModelNotFoundError",
1664
+ z.object({
1665
+ providerID: ProviderID.zod,
1666
+ modelID: ModelID.zod,
1667
+ suggestions: z.array(z.string()).optional(),
1668
+ }),
1669
+ )
1670
+
1671
+ export const InitError = NamedError.create(
1672
+ "ProviderInitError",
1673
+ z.object({
1674
+ providerID: ProviderID.zod,
1675
+ }),
1676
+ )
1677
+ }