codepro-ia 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 (393) hide show
  1. package/AGENTS.md +27 -0
  2. package/Dockerfile +18 -0
  3. package/README.md +70 -0
  4. package/bin/opencode +84 -0
  5. package/bunfig.toml +7 -0
  6. package/package.json +144 -0
  7. package/parsers-config.ts +253 -0
  8. package/script/build.ts +167 -0
  9. package/script/postinstall.mjs +125 -0
  10. package/script/publish-registries.ts +187 -0
  11. package/script/publish.ts +70 -0
  12. package/script/schema.ts +47 -0
  13. package/src/acp/README.md +164 -0
  14. package/src/acp/agent.ts +1127 -0
  15. package/src/acp/session.ts +101 -0
  16. package/src/acp/types.ts +22 -0
  17. package/src/agent/agent.ts +311 -0
  18. package/src/agent/generate.txt +75 -0
  19. package/src/agent/prompt/compaction.txt +12 -0
  20. package/src/agent/prompt/explore.txt +18 -0
  21. package/src/agent/prompt/summary.txt +11 -0
  22. package/src/agent/prompt/title.txt +43 -0
  23. package/src/auth/index.ts +73 -0
  24. package/src/bun/index.ts +134 -0
  25. package/src/bus/bus-event.ts +43 -0
  26. package/src/bus/global.ts +10 -0
  27. package/src/bus/index.ts +105 -0
  28. package/src/cli/bootstrap.ts +17 -0
  29. package/src/cli/cmd/acp.ts +69 -0
  30. package/src/cli/cmd/agent.ts +257 -0
  31. package/src/cli/cmd/auth.ts +400 -0
  32. package/src/cli/cmd/cmd.ts +7 -0
  33. package/src/cli/cmd/debug/agent.ts +166 -0
  34. package/src/cli/cmd/debug/config.ts +16 -0
  35. package/src/cli/cmd/debug/file.ts +97 -0
  36. package/src/cli/cmd/debug/index.ts +48 -0
  37. package/src/cli/cmd/debug/lsp.ts +52 -0
  38. package/src/cli/cmd/debug/ripgrep.ts +87 -0
  39. package/src/cli/cmd/debug/scrap.ts +16 -0
  40. package/src/cli/cmd/debug/skill.ts +16 -0
  41. package/src/cli/cmd/debug/snapshot.ts +52 -0
  42. package/src/cli/cmd/export.ts +88 -0
  43. package/src/cli/cmd/generate.ts +38 -0
  44. package/src/cli/cmd/github.ts +1548 -0
  45. package/src/cli/cmd/import.ts +98 -0
  46. package/src/cli/cmd/mcp.ts +755 -0
  47. package/src/cli/cmd/models.ts +77 -0
  48. package/src/cli/cmd/pr.ts +112 -0
  49. package/src/cli/cmd/run.ts +395 -0
  50. package/src/cli/cmd/serve.ts +20 -0
  51. package/src/cli/cmd/session.ts +135 -0
  52. package/src/cli/cmd/stats.ts +402 -0
  53. package/src/cli/cmd/tui/app.tsx +724 -0
  54. package/src/cli/cmd/tui/attach.ts +31 -0
  55. package/src/cli/cmd/tui/component/border.tsx +21 -0
  56. package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
  57. package/src/cli/cmd/tui/component/dialog-command.tsx +124 -0
  58. package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
  59. package/src/cli/cmd/tui/component/dialog-model.tsx +234 -0
  60. package/src/cli/cmd/tui/component/dialog-provider.tsx +256 -0
  61. package/src/cli/cmd/tui/component/dialog-session-list.tsx +114 -0
  62. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
  63. package/src/cli/cmd/tui/component/dialog-stash.tsx +87 -0
  64. package/src/cli/cmd/tui/component/dialog-status.tsx +164 -0
  65. package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
  66. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
  67. package/src/cli/cmd/tui/component/logo.tsx +106 -0
  68. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +763 -0
  69. package/src/cli/cmd/tui/component/prompt/frecency.tsx +89 -0
  70. package/src/cli/cmd/tui/component/prompt/history.tsx +108 -0
  71. package/src/cli/cmd/tui/component/prompt/index.tsx +1090 -0
  72. package/src/cli/cmd/tui/component/prompt/stash.tsx +101 -0
  73. package/src/cli/cmd/tui/component/textarea-keybindings.ts +73 -0
  74. package/src/cli/cmd/tui/component/tips.tsx +153 -0
  75. package/src/cli/cmd/tui/component/todo-item.tsx +32 -0
  76. package/src/cli/cmd/tui/context/args.tsx +14 -0
  77. package/src/cli/cmd/tui/context/directory.ts +13 -0
  78. package/src/cli/cmd/tui/context/exit.tsx +23 -0
  79. package/src/cli/cmd/tui/context/helper.tsx +25 -0
  80. package/src/cli/cmd/tui/context/keybind.tsx +101 -0
  81. package/src/cli/cmd/tui/context/kv.tsx +52 -0
  82. package/src/cli/cmd/tui/context/local.tsx +402 -0
  83. package/src/cli/cmd/tui/context/prompt.tsx +18 -0
  84. package/src/cli/cmd/tui/context/route.tsx +46 -0
  85. package/src/cli/cmd/tui/context/sdk.tsx +94 -0
  86. package/src/cli/cmd/tui/context/sync.tsx +427 -0
  87. package/src/cli/cmd/tui/context/theme/aura.json +69 -0
  88. package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
  89. package/src/cli/cmd/tui/context/theme/carbonfox.json +248 -0
  90. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +233 -0
  91. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +233 -0
  92. package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
  93. package/src/cli/cmd/tui/context/theme/cobalt2.json +228 -0
  94. package/src/cli/cmd/tui/context/theme/cursor.json +249 -0
  95. package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
  96. package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
  97. package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
  98. package/src/cli/cmd/tui/context/theme/github.json +233 -0
  99. package/src/cli/cmd/tui/context/theme/gruvbox.json +95 -0
  100. package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
  101. package/src/cli/cmd/tui/context/theme/lucent-orng.json +237 -0
  102. package/src/cli/cmd/tui/context/theme/material.json +235 -0
  103. package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
  104. package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
  105. package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
  106. package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
  107. package/src/cli/cmd/tui/context/theme/nord.json +223 -0
  108. package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
  109. package/src/cli/cmd/tui/context/theme/orng.json +249 -0
  110. package/src/cli/cmd/tui/context/theme/osaka-jade.json +93 -0
  111. package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
  112. package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
  113. package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
  114. package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
  115. package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
  116. package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
  117. package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
  118. package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
  119. package/src/cli/cmd/tui/context/theme.tsx +1152 -0
  120. package/src/cli/cmd/tui/event.ts +46 -0
  121. package/src/cli/cmd/tui/routes/home.tsx +141 -0
  122. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +64 -0
  123. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +109 -0
  124. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +26 -0
  125. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +47 -0
  126. package/src/cli/cmd/tui/routes/session/footer.tsx +91 -0
  127. package/src/cli/cmd/tui/routes/session/header.tsx +136 -0
  128. package/src/cli/cmd/tui/routes/session/index.tsx +1936 -0
  129. package/src/cli/cmd/tui/routes/session/permission.tsx +489 -0
  130. package/src/cli/cmd/tui/routes/session/question.tsx +435 -0
  131. package/src/cli/cmd/tui/routes/session/sidebar.tsx +312 -0
  132. package/src/cli/cmd/tui/thread.ts +165 -0
  133. package/src/cli/cmd/tui/ui/dialog-alert.tsx +57 -0
  134. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +83 -0
  135. package/src/cli/cmd/tui/ui/dialog-export-options.tsx +204 -0
  136. package/src/cli/cmd/tui/ui/dialog-help.tsx +38 -0
  137. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +77 -0
  138. package/src/cli/cmd/tui/ui/dialog-select.tsx +354 -0
  139. package/src/cli/cmd/tui/ui/dialog.tsx +167 -0
  140. package/src/cli/cmd/tui/ui/link.tsx +28 -0
  141. package/src/cli/cmd/tui/ui/spinner.ts +368 -0
  142. package/src/cli/cmd/tui/ui/toast.tsx +100 -0
  143. package/src/cli/cmd/tui/util/clipboard.ts +144 -0
  144. package/src/cli/cmd/tui/util/editor.ts +32 -0
  145. package/src/cli/cmd/tui/util/signal.ts +7 -0
  146. package/src/cli/cmd/tui/util/terminal.ts +114 -0
  147. package/src/cli/cmd/tui/util/transcript.ts +98 -0
  148. package/src/cli/cmd/tui/worker.ts +152 -0
  149. package/src/cli/cmd/uninstall.ts +344 -0
  150. package/src/cli/cmd/upgrade.ts +73 -0
  151. package/src/cli/cmd/web.ts +81 -0
  152. package/src/cli/error.ts +57 -0
  153. package/src/cli/network.ts +53 -0
  154. package/src/cli/ui.ts +88 -0
  155. package/src/cli/upgrade.ts +25 -0
  156. package/src/command/index.ts +131 -0
  157. package/src/command/template/initialize.txt +10 -0
  158. package/src/command/template/review.txt +97 -0
  159. package/src/config/config.ts +1246 -0
  160. package/src/config/markdown.ts +93 -0
  161. package/src/env/index.ts +26 -0
  162. package/src/file/ignore.ts +83 -0
  163. package/src/file/index.ts +411 -0
  164. package/src/file/ripgrep.ts +409 -0
  165. package/src/file/time.ts +64 -0
  166. package/src/file/watcher.ts +118 -0
  167. package/src/flag/flag.ts +54 -0
  168. package/src/format/formatter.ts +359 -0
  169. package/src/format/index.ts +137 -0
  170. package/src/global/index.ts +55 -0
  171. package/src/id/id.ts +83 -0
  172. package/src/ide/index.ts +76 -0
  173. package/src/index.ts +159 -0
  174. package/src/installation/index.ts +246 -0
  175. package/src/lsp/client.ts +252 -0
  176. package/src/lsp/index.ts +485 -0
  177. package/src/lsp/language.ts +119 -0
  178. package/src/lsp/server.ts +2032 -0
  179. package/src/mcp/auth.ts +135 -0
  180. package/src/mcp/index.ts +926 -0
  181. package/src/mcp/oauth-callback.ts +200 -0
  182. package/src/mcp/oauth-provider.ts +154 -0
  183. package/src/patch/index.ts +622 -0
  184. package/src/permission/arity.ts +163 -0
  185. package/src/permission/index.ts +210 -0
  186. package/src/permission/next.ts +269 -0
  187. package/src/plugin/codex.ts +493 -0
  188. package/src/plugin/copilot.ts +269 -0
  189. package/src/plugin/index.ts +135 -0
  190. package/src/project/bootstrap.ts +31 -0
  191. package/src/project/instance.ts +91 -0
  192. package/src/project/project.ts +320 -0
  193. package/src/project/state.ts +66 -0
  194. package/src/project/vcs.ts +76 -0
  195. package/src/provider/auth.ts +147 -0
  196. package/src/provider/models-macro.ts +11 -0
  197. package/src/provider/models.ts +112 -0
  198. package/src/provider/provider.ts +1220 -0
  199. package/src/provider/sdk/openai-compatible/src/README.md +5 -0
  200. package/src/provider/sdk/openai-compatible/src/index.ts +2 -0
  201. package/src/provider/sdk/openai-compatible/src/openai-compatible-provider.ts +100 -0
  202. package/src/provider/sdk/openai-compatible/src/responses/convert-to-openai-responses-input.ts +303 -0
  203. package/src/provider/sdk/openai-compatible/src/responses/map-openai-responses-finish-reason.ts +22 -0
  204. package/src/provider/sdk/openai-compatible/src/responses/openai-config.ts +18 -0
  205. package/src/provider/sdk/openai-compatible/src/responses/openai-error.ts +22 -0
  206. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-api-types.ts +207 -0
  207. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-language-model.ts +1713 -0
  208. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-prepare-tools.ts +177 -0
  209. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-settings.ts +1 -0
  210. package/src/provider/sdk/openai-compatible/src/responses/tool/code-interpreter.ts +88 -0
  211. package/src/provider/sdk/openai-compatible/src/responses/tool/file-search.ts +128 -0
  212. package/src/provider/sdk/openai-compatible/src/responses/tool/image-generation.ts +115 -0
  213. package/src/provider/sdk/openai-compatible/src/responses/tool/local-shell.ts +65 -0
  214. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search-preview.ts +104 -0
  215. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search.ts +103 -0
  216. package/src/provider/transform.ts +705 -0
  217. package/src/pty/index.ts +229 -0
  218. package/src/question/index.ts +171 -0
  219. package/src/server/error.ts +36 -0
  220. package/src/server/mdns.ts +59 -0
  221. package/src/server/routes/config.ts +92 -0
  222. package/src/server/routes/experimental.ts +157 -0
  223. package/src/server/routes/file.ts +197 -0
  224. package/src/server/routes/global.ts +135 -0
  225. package/src/server/routes/mcp.ts +225 -0
  226. package/src/server/routes/permission.ts +68 -0
  227. package/src/server/routes/project.ts +82 -0
  228. package/src/server/routes/provider.ts +165 -0
  229. package/src/server/routes/pty.ts +169 -0
  230. package/src/server/routes/question.ts +98 -0
  231. package/src/server/routes/session.ts +935 -0
  232. package/src/server/routes/tui.ts +377 -0
  233. package/src/server/server.ts +578 -0
  234. package/src/session/compaction.ts +225 -0
  235. package/src/session/index.ts +488 -0
  236. package/src/session/llm.ts +279 -0
  237. package/src/session/message-v2.ts +702 -0
  238. package/src/session/message.ts +189 -0
  239. package/src/session/processor.ts +406 -0
  240. package/src/session/prompt/anthropic-20250930.txt +166 -0
  241. package/src/session/prompt/anthropic.txt +105 -0
  242. package/src/session/prompt/anthropic_spoof.txt +1 -0
  243. package/src/session/prompt/beast.txt +147 -0
  244. package/src/session/prompt/build-switch.txt +5 -0
  245. package/src/session/prompt/codex.txt +72 -0
  246. package/src/session/prompt/codex_header.txt +72 -0
  247. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  248. package/src/session/prompt/gemini.txt +155 -0
  249. package/src/session/prompt/max-steps.txt +16 -0
  250. package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  251. package/src/session/prompt/plan.txt +26 -0
  252. package/src/session/prompt/qwen.txt +109 -0
  253. package/src/session/prompt.ts +1792 -0
  254. package/src/session/retry.ts +90 -0
  255. package/src/session/revert.ts +108 -0
  256. package/src/session/status.ts +76 -0
  257. package/src/session/summary.ts +150 -0
  258. package/src/session/system.ts +138 -0
  259. package/src/session/todo.ts +37 -0
  260. package/src/share/share-next.ts +194 -0
  261. package/src/share/share.ts +87 -0
  262. package/src/shell/shell.ts +67 -0
  263. package/src/skill/index.ts +1 -0
  264. package/src/skill/skill.ts +136 -0
  265. package/src/snapshot/index.ts +199 -0
  266. package/src/storage/storage.ts +227 -0
  267. package/src/tool/bash.ts +258 -0
  268. package/src/tool/bash.txt +115 -0
  269. package/src/tool/batch.ts +175 -0
  270. package/src/tool/batch.txt +24 -0
  271. package/src/tool/codesearch.ts +132 -0
  272. package/src/tool/codesearch.txt +12 -0
  273. package/src/tool/edit.ts +645 -0
  274. package/src/tool/edit.txt +10 -0
  275. package/src/tool/external-directory.ts +32 -0
  276. package/src/tool/glob.ts +77 -0
  277. package/src/tool/glob.txt +6 -0
  278. package/src/tool/grep.ts +154 -0
  279. package/src/tool/grep.txt +8 -0
  280. package/src/tool/invalid.ts +17 -0
  281. package/src/tool/ls.ts +121 -0
  282. package/src/tool/ls.txt +1 -0
  283. package/src/tool/lsp.ts +96 -0
  284. package/src/tool/lsp.txt +19 -0
  285. package/src/tool/multiedit.ts +46 -0
  286. package/src/tool/multiedit.txt +41 -0
  287. package/src/tool/patch.ts +201 -0
  288. package/src/tool/patch.txt +1 -0
  289. package/src/tool/plan-enter.txt +14 -0
  290. package/src/tool/plan-exit.txt +13 -0
  291. package/src/tool/plan.ts +130 -0
  292. package/src/tool/question.ts +33 -0
  293. package/src/tool/question.txt +10 -0
  294. package/src/tool/read.ts +200 -0
  295. package/src/tool/read.txt +12 -0
  296. package/src/tool/registry.ts +143 -0
  297. package/src/tool/skill.ts +75 -0
  298. package/src/tool/task.ts +188 -0
  299. package/src/tool/task.txt +60 -0
  300. package/src/tool/todo.ts +53 -0
  301. package/src/tool/todoread.txt +14 -0
  302. package/src/tool/todowrite.txt +167 -0
  303. package/src/tool/tool.ts +88 -0
  304. package/src/tool/truncation.ts +99 -0
  305. package/src/tool/webfetch.ts +182 -0
  306. package/src/tool/webfetch.txt +13 -0
  307. package/src/tool/websearch.ts +150 -0
  308. package/src/tool/websearch.txt +14 -0
  309. package/src/tool/write.ts +80 -0
  310. package/src/tool/write.txt +8 -0
  311. package/src/util/archive.ts +16 -0
  312. package/src/util/color.ts +19 -0
  313. package/src/util/context.ts +25 -0
  314. package/src/util/defer.ts +12 -0
  315. package/src/util/eventloop.ts +20 -0
  316. package/src/util/filesystem.ts +93 -0
  317. package/src/util/fn.ts +11 -0
  318. package/src/util/format.ts +20 -0
  319. package/src/util/iife.ts +3 -0
  320. package/src/util/keybind.ts +103 -0
  321. package/src/util/lazy.ts +18 -0
  322. package/src/util/locale.ts +81 -0
  323. package/src/util/lock.ts +98 -0
  324. package/src/util/log.ts +180 -0
  325. package/src/util/queue.ts +32 -0
  326. package/src/util/rpc.ts +66 -0
  327. package/src/util/scrap.ts +10 -0
  328. package/src/util/signal.ts +12 -0
  329. package/src/util/timeout.ts +14 -0
  330. package/src/util/token.ts +7 -0
  331. package/src/util/wildcard.ts +56 -0
  332. package/src/worktree/index.ts +217 -0
  333. package/sst-env.d.ts +9 -0
  334. package/test/agent/agent.test.ts +638 -0
  335. package/test/bun.test.ts +53 -0
  336. package/test/cli/github-action.test.ts +129 -0
  337. package/test/cli/github-remote.test.ts +80 -0
  338. package/test/cli/tui/transcript.test.ts +297 -0
  339. package/test/config/agent-color.test.ts +66 -0
  340. package/test/config/config.test.ts +1376 -0
  341. package/test/config/fixtures/empty-frontmatter.md +4 -0
  342. package/test/config/fixtures/frontmatter.md +28 -0
  343. package/test/config/fixtures/no-frontmatter.md +1 -0
  344. package/test/config/markdown.test.ts +192 -0
  345. package/test/file/ignore.test.ts +10 -0
  346. package/test/file/path-traversal.test.ts +198 -0
  347. package/test/fixture/fixture.ts +45 -0
  348. package/test/fixture/lsp/fake-lsp-server.js +77 -0
  349. package/test/ide/ide.test.ts +82 -0
  350. package/test/keybind.test.ts +421 -0
  351. package/test/lsp/client.test.ts +95 -0
  352. package/test/mcp/headers.test.ts +153 -0
  353. package/test/mcp/oauth-browser.test.ts +261 -0
  354. package/test/patch/patch.test.ts +348 -0
  355. package/test/permission/arity.test.ts +33 -0
  356. package/test/permission/next.test.ts +652 -0
  357. package/test/permission-task.test.ts +319 -0
  358. package/test/plugin/codex.test.ts +123 -0
  359. package/test/preload.ts +65 -0
  360. package/test/project/project.test.ts +120 -0
  361. package/test/provider/amazon-bedrock.test.ts +268 -0
  362. package/test/provider/gitlab-duo.test.ts +286 -0
  363. package/test/provider/provider.test.ts +2149 -0
  364. package/test/provider/transform.test.ts +1566 -0
  365. package/test/question/question.test.ts +300 -0
  366. package/test/server/session-list.test.ts +39 -0
  367. package/test/server/session-select.test.ts +78 -0
  368. package/test/session/compaction.test.ts +293 -0
  369. package/test/session/llm.test.ts +90 -0
  370. package/test/session/message-v2.test.ts +662 -0
  371. package/test/session/retry.test.ts +131 -0
  372. package/test/session/revert-compact.test.ts +285 -0
  373. package/test/session/session.test.ts +71 -0
  374. package/test/skill/skill.test.ts +185 -0
  375. package/test/snapshot/snapshot.test.ts +939 -0
  376. package/test/tool/__snapshots__/tool.test.ts.snap +9 -0
  377. package/test/tool/bash.test.ts +320 -0
  378. package/test/tool/external-directory.test.ts +126 -0
  379. package/test/tool/fixtures/large-image.png +0 -0
  380. package/test/tool/fixtures/models-api.json +33453 -0
  381. package/test/tool/grep.test.ts +109 -0
  382. package/test/tool/patch.test.ts +261 -0
  383. package/test/tool/read.test.ts +303 -0
  384. package/test/tool/registry.test.ts +76 -0
  385. package/test/tool/truncation.test.ts +159 -0
  386. package/test/util/filesystem.test.ts +39 -0
  387. package/test/util/format.test.ts +59 -0
  388. package/test/util/iife.test.ts +36 -0
  389. package/test/util/lazy.test.ts +50 -0
  390. package/test/util/lock.test.ts +72 -0
  391. package/test/util/timeout.test.ts +21 -0
  392. package/test/util/wildcard.test.ts +75 -0
  393. package/tsconfig.json +16 -0
@@ -0,0 +1,1220 @@
1
+ import z from "zod"
2
+ import fuzzysort from "fuzzysort"
3
+ import { Config } from "../config/config"
4
+ import { mapValues, mergeDeep, omit, pickBy, sortBy } from "remeda"
5
+ import { NoSuchModelError, type Provider as SDK } from "ai"
6
+ import { Log } from "../util/log"
7
+ import { BunProc } from "../bun"
8
+ import { Plugin } from "../plugin"
9
+ import { ModelsDev } from "./models"
10
+ import { NamedError } from "@codepro-ai/util/error"
11
+ import { Auth } from "../auth"
12
+ import { Env } from "../env"
13
+ import { Instance } from "../project/instance"
14
+ import { Flag } from "../flag/flag"
15
+ import { iife } from "@/util/iife"
16
+
17
+ // Direct imports for bundled providers
18
+ import { createAmazonBedrock, type AmazonBedrockProviderSettings } from "@ai-sdk/amazon-bedrock"
19
+ import { createAnthropic } from "@ai-sdk/anthropic"
20
+ import { createAzure } from "@ai-sdk/azure"
21
+ import { createGoogleGenerativeAI } from "@ai-sdk/google"
22
+ import { createVertex } from "@ai-sdk/google-vertex"
23
+ import { createVertexAnthropic } from "@ai-sdk/google-vertex/anthropic"
24
+ import { createOpenAI } from "@ai-sdk/openai"
25
+ import { createOpenAICompatible } from "@ai-sdk/openai-compatible"
26
+ import { createOpenRouter, type LanguageModelV2 } from "@openrouter/ai-sdk-provider"
27
+ import { createOpenaiCompatible as createGitHubCopilotOpenAICompatible } from "./sdk/openai-compatible/src"
28
+ import { createXai } from "@ai-sdk/xai"
29
+ import { createMistral } from "@ai-sdk/mistral"
30
+ import { createGroq } from "@ai-sdk/groq"
31
+ import { createDeepInfra } from "@ai-sdk/deepinfra"
32
+ import { createCerebras } from "@ai-sdk/cerebras"
33
+ import { createCohere } from "@ai-sdk/cohere"
34
+ import { createGateway } from "@ai-sdk/gateway"
35
+ import { createTogetherAI } from "@ai-sdk/togetherai"
36
+ import { createPerplexity } from "@ai-sdk/perplexity"
37
+ import { createVercel } from "@ai-sdk/vercel"
38
+ import { createGitLab } from "@gitlab/gitlab-ai-provider"
39
+ import { ProviderTransform } from "./transform"
40
+
41
+ export namespace Provider {
42
+ const log = Log.create({ service: "provider" })
43
+
44
+ const BUNDLED_PROVIDERS: Record<string, (options: any) => SDK> = {
45
+ "@ai-sdk/amazon-bedrock": createAmazonBedrock,
46
+ "@ai-sdk/anthropic": createAnthropic,
47
+ "@ai-sdk/azure": createAzure,
48
+ "@ai-sdk/google": createGoogleGenerativeAI,
49
+ "@ai-sdk/google-vertex": createVertex,
50
+ "@ai-sdk/google-vertex/anthropic": createVertexAnthropic,
51
+ "@ai-sdk/openai": createOpenAI,
52
+ "@ai-sdk/openai-compatible": createOpenAICompatible,
53
+ "@openrouter/ai-sdk-provider": createOpenRouter,
54
+ "@ai-sdk/xai": createXai,
55
+ "@ai-sdk/mistral": createMistral,
56
+ "@ai-sdk/groq": createGroq,
57
+ "@ai-sdk/deepinfra": createDeepInfra,
58
+ "@ai-sdk/cerebras": createCerebras,
59
+ "@ai-sdk/cohere": createCohere,
60
+ "@ai-sdk/gateway": createGateway,
61
+ "@ai-sdk/togetherai": createTogetherAI,
62
+ "@ai-sdk/perplexity": createPerplexity,
63
+ "@ai-sdk/vercel": createVercel,
64
+ "@gitlab/gitlab-ai-provider": createGitLab,
65
+ // @ts-ignore (TODO: kill this code so we dont have to maintain it)
66
+ "@ai-sdk/github-copilot": createGitHubCopilotOpenAICompatible,
67
+ }
68
+
69
+ type CustomModelLoader = (sdk: any, modelID: string, options?: Record<string, any>) => Promise<any>
70
+ type CustomLoader = (provider: Info) => Promise<{
71
+ autoload: boolean
72
+ getModel?: CustomModelLoader
73
+ options?: Record<string, any>
74
+ }>
75
+
76
+ const CUSTOM_LOADERS: Record<string, CustomLoader> = {
77
+ async anthropic() {
78
+ return {
79
+ autoload: false,
80
+ options: {
81
+ headers: {
82
+ "anthropic-beta":
83
+ "claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",
84
+ },
85
+ },
86
+ }
87
+ },
88
+ async opencode(input) {
89
+ const hasKey = await (async () => {
90
+ const env = Env.all()
91
+ if (input.env.some((item) => env[item])) return true
92
+ if (await Auth.get(input.id)) return true
93
+ const config = await Config.get()
94
+ if (config.provider?.["opencode"]?.options?.apiKey) return true
95
+ return false
96
+ })()
97
+
98
+ if (!hasKey) {
99
+ for (const [key, value] of Object.entries(input.models)) {
100
+ if (value.cost.input === 0) continue
101
+ delete input.models[key]
102
+ }
103
+ }
104
+
105
+ return {
106
+ autoload: Object.keys(input.models).length > 0,
107
+ options: hasKey ? {} : { apiKey: "public" },
108
+ }
109
+ },
110
+ openai: async () => {
111
+ return {
112
+ autoload: false,
113
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
114
+ return sdk.responses(modelID)
115
+ },
116
+ options: {},
117
+ }
118
+ },
119
+ "github-copilot": async () => {
120
+ return {
121
+ autoload: false,
122
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
123
+ if (modelID.includes("codex")) {
124
+ return sdk.responses(modelID)
125
+ }
126
+ return sdk.chat(modelID)
127
+ },
128
+ options: {},
129
+ }
130
+ },
131
+ "github-copilot-enterprise": async () => {
132
+ return {
133
+ autoload: false,
134
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
135
+ if (modelID.includes("codex")) {
136
+ return sdk.responses(modelID)
137
+ }
138
+ return sdk.chat(modelID)
139
+ },
140
+ options: {},
141
+ }
142
+ },
143
+ azure: async () => {
144
+ return {
145
+ autoload: false,
146
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
147
+ if (options?.["useCompletionUrls"]) {
148
+ return sdk.chat(modelID)
149
+ } else {
150
+ return sdk.responses(modelID)
151
+ }
152
+ },
153
+ options: {},
154
+ }
155
+ },
156
+ "azure-cognitive-services": async () => {
157
+ const resourceName = Env.get("AZURE_COGNITIVE_SERVICES_RESOURCE_NAME")
158
+ return {
159
+ autoload: false,
160
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
161
+ if (options?.["useCompletionUrls"]) {
162
+ return sdk.chat(modelID)
163
+ } else {
164
+ return sdk.responses(modelID)
165
+ }
166
+ },
167
+ options: {
168
+ baseURL: resourceName ? `https://${resourceName}.cognitiveservices.azure.com/openai` : undefined,
169
+ },
170
+ }
171
+ },
172
+ "amazon-bedrock": async () => {
173
+ const config = await Config.get()
174
+ const providerConfig = config.provider?.["amazon-bedrock"]
175
+
176
+ const auth = await Auth.get("amazon-bedrock")
177
+
178
+ // Region precedence: 1) config file, 2) env var, 3) default
179
+ const configRegion = providerConfig?.options?.region
180
+ const envRegion = Env.get("AWS_REGION")
181
+ const defaultRegion = configRegion ?? envRegion ?? "us-east-1"
182
+
183
+ // Profile: config file takes precedence over env var
184
+ const configProfile = providerConfig?.options?.profile
185
+ const envProfile = Env.get("AWS_PROFILE")
186
+ const profile = configProfile ?? envProfile
187
+
188
+ const awsAccessKeyId = Env.get("AWS_ACCESS_KEY_ID")
189
+
190
+ const awsBearerToken = iife(() => {
191
+ const envToken = Env.get("AWS_BEARER_TOKEN_BEDROCK")
192
+ if (envToken) return envToken
193
+ if (auth?.type === "api") {
194
+ Env.set("AWS_BEARER_TOKEN_BEDROCK", auth.key)
195
+ return auth.key
196
+ }
197
+ return undefined
198
+ })
199
+
200
+ const awsWebIdentityTokenFile = Env.get("AWS_WEB_IDENTITY_TOKEN_FILE")
201
+
202
+ if (!profile && !awsAccessKeyId && !awsBearerToken && !awsWebIdentityTokenFile) return { autoload: false }
203
+
204
+ const providerOptions: AmazonBedrockProviderSettings = {
205
+ region: defaultRegion,
206
+ }
207
+
208
+ // Only use credential chain if no bearer token exists
209
+ // Bearer token takes precedence over credential chain (profiles, access keys, IAM roles, web identity tokens)
210
+ if (!awsBearerToken) {
211
+ const { fromNodeProviderChain } = await import(await BunProc.install("@aws-sdk/credential-providers"))
212
+
213
+ // Build credential provider options (only pass profile if specified)
214
+ const credentialProviderOptions = profile ? { profile } : {}
215
+
216
+ providerOptions.credentialProvider = fromNodeProviderChain(credentialProviderOptions)
217
+ }
218
+
219
+ // Add custom endpoint if specified (endpoint takes precedence over baseURL)
220
+ const endpoint = providerConfig?.options?.endpoint ?? providerConfig?.options?.baseURL
221
+ if (endpoint) {
222
+ providerOptions.baseURL = endpoint
223
+ }
224
+
225
+ return {
226
+ autoload: true,
227
+ options: providerOptions,
228
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
229
+ // Skip region prefixing if model already has a cross-region inference profile prefix
230
+ if (modelID.startsWith("global.") || modelID.startsWith("jp.")) {
231
+ return sdk.languageModel(modelID)
232
+ }
233
+
234
+ // Region resolution precedence (highest to lowest):
235
+ // 1. options.region from opencode.json provider config
236
+ // 2. defaultRegion from AWS_REGION environment variable
237
+ // 3. Default "us-east-1" (baked into defaultRegion)
238
+ const region = options?.region ?? defaultRegion
239
+
240
+ let regionPrefix = region.split("-")[0]
241
+
242
+ switch (regionPrefix) {
243
+ case "us": {
244
+ const modelRequiresPrefix = [
245
+ "nova-micro",
246
+ "nova-lite",
247
+ "nova-pro",
248
+ "nova-premier",
249
+ "nova-2",
250
+ "claude",
251
+ "deepseek",
252
+ ].some((m) => modelID.includes(m))
253
+ const isGovCloud = region.startsWith("us-gov")
254
+ if (modelRequiresPrefix && !isGovCloud) {
255
+ modelID = `${regionPrefix}.${modelID}`
256
+ }
257
+ break
258
+ }
259
+ case "eu": {
260
+ const regionRequiresPrefix = [
261
+ "eu-west-1",
262
+ "eu-west-2",
263
+ "eu-west-3",
264
+ "eu-north-1",
265
+ "eu-central-1",
266
+ "eu-south-1",
267
+ "eu-south-2",
268
+ ].some((r) => region.includes(r))
269
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "llama3", "pixtral"].some((m) =>
270
+ modelID.includes(m),
271
+ )
272
+ if (regionRequiresPrefix && modelRequiresPrefix) {
273
+ modelID = `${regionPrefix}.${modelID}`
274
+ }
275
+ break
276
+ }
277
+ case "ap": {
278
+ const isAustraliaRegion = ["ap-southeast-2", "ap-southeast-4"].includes(region)
279
+ const isTokyoRegion = region === "ap-northeast-1"
280
+ if (
281
+ isAustraliaRegion &&
282
+ ["anthropic.claude-sonnet-4-5", "anthropic.claude-haiku"].some((m) => modelID.includes(m))
283
+ ) {
284
+ regionPrefix = "au"
285
+ modelID = `${regionPrefix}.${modelID}`
286
+ } else if (isTokyoRegion) {
287
+ // Tokyo region uses jp. prefix for cross-region inference
288
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "nova-pro"].some((m) =>
289
+ modelID.includes(m),
290
+ )
291
+ if (modelRequiresPrefix) {
292
+ regionPrefix = "jp"
293
+ modelID = `${regionPrefix}.${modelID}`
294
+ }
295
+ } else {
296
+ // Other APAC regions use apac. prefix
297
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "nova-pro"].some((m) =>
298
+ modelID.includes(m),
299
+ )
300
+ if (modelRequiresPrefix) {
301
+ regionPrefix = "apac"
302
+ modelID = `${regionPrefix}.${modelID}`
303
+ }
304
+ }
305
+ break
306
+ }
307
+ }
308
+
309
+ return sdk.languageModel(modelID)
310
+ },
311
+ }
312
+ },
313
+ openrouter: async () => {
314
+ return {
315
+ autoload: false,
316
+ options: {
317
+ headers: {
318
+ "HTTP-Referer": "https://opencode.ai/",
319
+ "X-Title": "opencode",
320
+ },
321
+ },
322
+ }
323
+ },
324
+ vercel: async () => {
325
+ return {
326
+ autoload: false,
327
+ options: {
328
+ headers: {
329
+ "http-referer": "https://opencode.ai/",
330
+ "x-title": "opencode",
331
+ },
332
+ },
333
+ }
334
+ },
335
+ "google-vertex": async () => {
336
+ const project = Env.get("GOOGLE_CLOUD_PROJECT") ?? Env.get("GCP_PROJECT") ?? Env.get("GCLOUD_PROJECT")
337
+ const location = Env.get("GOOGLE_CLOUD_LOCATION") ?? Env.get("VERTEX_LOCATION") ?? "us-east5"
338
+ const autoload = Boolean(project)
339
+ if (!autoload) return { autoload: false }
340
+ return {
341
+ autoload: true,
342
+ options: {
343
+ project,
344
+ location,
345
+ },
346
+ async getModel(sdk: any, modelID: string) {
347
+ const id = String(modelID).trim()
348
+ return sdk.languageModel(id)
349
+ },
350
+ }
351
+ },
352
+ "google-vertex-anthropic": async () => {
353
+ const project = Env.get("GOOGLE_CLOUD_PROJECT") ?? Env.get("GCP_PROJECT") ?? Env.get("GCLOUD_PROJECT")
354
+ const location = Env.get("GOOGLE_CLOUD_LOCATION") ?? Env.get("VERTEX_LOCATION") ?? "global"
355
+ const autoload = Boolean(project)
356
+ if (!autoload) return { autoload: false }
357
+ return {
358
+ autoload: true,
359
+ options: {
360
+ project,
361
+ location,
362
+ },
363
+ async getModel(sdk: any, modelID) {
364
+ const id = String(modelID).trim()
365
+ return sdk.languageModel(id)
366
+ },
367
+ }
368
+ },
369
+ "sap-ai-core": async () => {
370
+ const auth = await Auth.get("sap-ai-core")
371
+ const envServiceKey = iife(() => {
372
+ const envAICoreServiceKey = Env.get("AICORE_SERVICE_KEY")
373
+ if (envAICoreServiceKey) return envAICoreServiceKey
374
+ if (auth?.type === "api") {
375
+ Env.set("AICORE_SERVICE_KEY", auth.key)
376
+ return auth.key
377
+ }
378
+ return undefined
379
+ })
380
+ const deploymentId = Env.get("AICORE_DEPLOYMENT_ID")
381
+ const resourceGroup = Env.get("AICORE_RESOURCE_GROUP")
382
+
383
+ return {
384
+ autoload: !!envServiceKey,
385
+ options: envServiceKey ? { deploymentId, resourceGroup } : {},
386
+ async getModel(sdk: any, modelID: string) {
387
+ return sdk(modelID)
388
+ },
389
+ }
390
+ },
391
+ zenmux: async () => {
392
+ return {
393
+ autoload: false,
394
+ options: {
395
+ headers: {
396
+ "HTTP-Referer": "https://opencode.ai/",
397
+ "X-Title": "opencode",
398
+ },
399
+ },
400
+ }
401
+ },
402
+ gitlab: async (input) => {
403
+ const instanceUrl = Env.get("GITLAB_INSTANCE_URL") || "https://gitlab.com"
404
+
405
+ const auth = await Auth.get(input.id)
406
+ const apiKey = await (async () => {
407
+ if (auth?.type === "oauth") return auth.access
408
+ if (auth?.type === "api") return auth.key
409
+ return Env.get("GITLAB_TOKEN")
410
+ })()
411
+
412
+ const config = await Config.get()
413
+ const providerConfig = config.provider?.["gitlab"]
414
+
415
+ return {
416
+ autoload: !!apiKey,
417
+ options: {
418
+ instanceUrl,
419
+ apiKey,
420
+ featureFlags: {
421
+ duo_agent_platform_agentic_chat: true,
422
+ duo_agent_platform: true,
423
+ ...(providerConfig?.options?.featureFlags || {}),
424
+ },
425
+ },
426
+ async getModel(sdk: ReturnType<typeof createGitLab>, modelID: string) {
427
+ return sdk.agenticChat(modelID, {
428
+ featureFlags: {
429
+ duo_agent_platform_agentic_chat: true,
430
+ duo_agent_platform: true,
431
+ ...(providerConfig?.options?.featureFlags || {}),
432
+ },
433
+ })
434
+ },
435
+ }
436
+ },
437
+ "cloudflare-ai-gateway": async (input) => {
438
+ const accountId = Env.get("CLOUDFLARE_ACCOUNT_ID")
439
+ const gateway = Env.get("CLOUDFLARE_GATEWAY_ID")
440
+
441
+ if (!accountId || !gateway) return { autoload: false }
442
+
443
+ // Get API token from env or auth prompt
444
+ const apiToken = await (async () => {
445
+ const envToken = Env.get("CLOUDFLARE_API_TOKEN")
446
+ if (envToken) return envToken
447
+ const auth = await Auth.get(input.id)
448
+ if (auth?.type === "api") return auth.key
449
+ return undefined
450
+ })()
451
+
452
+ return {
453
+ autoload: true,
454
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
455
+ return sdk.languageModel(modelID)
456
+ },
457
+ options: {
458
+ baseURL: `https://gateway.ai.cloudflare.com/v1/${accountId}/${gateway}/compat`,
459
+ headers: {
460
+ // Cloudflare AI Gateway uses cf-aig-authorization for authenticated gateways
461
+ // This enables Unified Billing where Cloudflare handles upstream provider auth
462
+ ...(apiToken ? { "cf-aig-authorization": `Bearer ${apiToken}` } : {}),
463
+ "HTTP-Referer": "https://opencode.ai/",
464
+ "X-Title": "opencode",
465
+ },
466
+ // Custom fetch to handle parameter transformation and auth
467
+ fetch: async (input: RequestInfo | URL, init?: RequestInit) => {
468
+ const headers = new Headers(init?.headers)
469
+ // Strip Authorization header - AI Gateway uses cf-aig-authorization instead
470
+ headers.delete("Authorization")
471
+
472
+ // Transform max_tokens to max_completion_tokens for newer models
473
+ if (init?.body && init.method === "POST") {
474
+ try {
475
+ const body = JSON.parse(init.body as string)
476
+ if (body.max_tokens !== undefined && !body.max_completion_tokens) {
477
+ body.max_completion_tokens = body.max_tokens
478
+ delete body.max_tokens
479
+ init = { ...init, body: JSON.stringify(body) }
480
+ }
481
+ } catch (e) {
482
+ // If body parsing fails, continue with original request
483
+ }
484
+ }
485
+
486
+ return fetch(input, { ...init, headers })
487
+ },
488
+ },
489
+ }
490
+ },
491
+ cerebras: async () => {
492
+ return {
493
+ autoload: false,
494
+ options: {
495
+ headers: {
496
+ "X-Cerebras-3rd-Party-Integration": "opencode",
497
+ },
498
+ },
499
+ }
500
+ },
501
+ }
502
+
503
+ export const Model = z
504
+ .object({
505
+ id: z.string(),
506
+ providerID: z.string(),
507
+ api: z.object({
508
+ id: z.string(),
509
+ url: z.string(),
510
+ npm: z.string(),
511
+ }),
512
+ name: z.string(),
513
+ family: z.string().optional(),
514
+ capabilities: z.object({
515
+ temperature: z.boolean(),
516
+ reasoning: z.boolean(),
517
+ attachment: z.boolean(),
518
+ toolcall: z.boolean(),
519
+ input: z.object({
520
+ text: z.boolean(),
521
+ audio: z.boolean(),
522
+ image: z.boolean(),
523
+ video: z.boolean(),
524
+ pdf: z.boolean(),
525
+ }),
526
+ output: z.object({
527
+ text: z.boolean(),
528
+ audio: z.boolean(),
529
+ image: z.boolean(),
530
+ video: z.boolean(),
531
+ pdf: z.boolean(),
532
+ }),
533
+ interleaved: z.union([
534
+ z.boolean(),
535
+ z.object({
536
+ field: z.enum(["reasoning_content", "reasoning_details"]),
537
+ }),
538
+ ]),
539
+ }),
540
+ cost: z.object({
541
+ input: z.number(),
542
+ output: z.number(),
543
+ cache: z.object({
544
+ read: z.number(),
545
+ write: z.number(),
546
+ }),
547
+ experimentalOver200K: z
548
+ .object({
549
+ input: z.number(),
550
+ output: z.number(),
551
+ cache: z.object({
552
+ read: z.number(),
553
+ write: z.number(),
554
+ }),
555
+ })
556
+ .optional(),
557
+ }),
558
+ limit: z.object({
559
+ context: z.number(),
560
+ input: z.number().optional(),
561
+ output: z.number(),
562
+ }),
563
+ status: z.enum(["alpha", "beta", "deprecated", "active"]),
564
+ options: z.record(z.string(), z.any()),
565
+ headers: z.record(z.string(), z.string()),
566
+ release_date: z.string(),
567
+ variants: z.record(z.string(), z.record(z.string(), z.any())).optional(),
568
+ })
569
+ .meta({
570
+ ref: "Model",
571
+ })
572
+ export type Model = z.infer<typeof Model>
573
+
574
+ export const Info = z
575
+ .object({
576
+ id: z.string(),
577
+ name: z.string(),
578
+ source: z.enum(["env", "config", "custom", "api"]),
579
+ env: z.string().array(),
580
+ key: z.string().optional(),
581
+ options: z.record(z.string(), z.any()),
582
+ models: z.record(z.string(), Model),
583
+ })
584
+ .meta({
585
+ ref: "Provider",
586
+ })
587
+ export type Info = z.infer<typeof Info>
588
+
589
+ function fromModelsDevModel(provider: ModelsDev.Provider, model: ModelsDev.Model): Model {
590
+ const m: Model = {
591
+ id: model.id,
592
+ providerID: provider.id,
593
+ name: model.name,
594
+ family: model.family,
595
+ api: {
596
+ id: model.id,
597
+ url: provider.api!,
598
+ npm: model.provider?.npm ?? provider.npm ?? "@ai-sdk/openai-compatible",
599
+ },
600
+ status: model.status ?? "active",
601
+ headers: model.headers ?? {},
602
+ options: model.options ?? {},
603
+ cost: {
604
+ input: model.cost?.input ?? 0,
605
+ output: model.cost?.output ?? 0,
606
+ cache: {
607
+ read: model.cost?.cache_read ?? 0,
608
+ write: model.cost?.cache_write ?? 0,
609
+ },
610
+ experimentalOver200K: model.cost?.context_over_200k
611
+ ? {
612
+ cache: {
613
+ read: model.cost.context_over_200k.cache_read ?? 0,
614
+ write: model.cost.context_over_200k.cache_write ?? 0,
615
+ },
616
+ input: model.cost.context_over_200k.input,
617
+ output: model.cost.context_over_200k.output,
618
+ }
619
+ : undefined,
620
+ },
621
+ limit: {
622
+ context: model.limit.context,
623
+ input: model.limit.input,
624
+ output: model.limit.output,
625
+ },
626
+ capabilities: {
627
+ temperature: model.temperature,
628
+ reasoning: model.reasoning,
629
+ attachment: model.attachment,
630
+ toolcall: model.tool_call,
631
+ input: {
632
+ text: model.modalities?.input?.includes("text") ?? false,
633
+ audio: model.modalities?.input?.includes("audio") ?? false,
634
+ image: model.modalities?.input?.includes("image") ?? false,
635
+ video: model.modalities?.input?.includes("video") ?? false,
636
+ pdf: model.modalities?.input?.includes("pdf") ?? false,
637
+ },
638
+ output: {
639
+ text: model.modalities?.output?.includes("text") ?? false,
640
+ audio: model.modalities?.output?.includes("audio") ?? false,
641
+ image: model.modalities?.output?.includes("image") ?? false,
642
+ video: model.modalities?.output?.includes("video") ?? false,
643
+ pdf: model.modalities?.output?.includes("pdf") ?? false,
644
+ },
645
+ interleaved: model.interleaved ?? false,
646
+ },
647
+ release_date: model.release_date,
648
+ variants: {},
649
+ }
650
+
651
+ m.variants = mapValues(ProviderTransform.variants(m), (v) => v)
652
+
653
+ return m
654
+ }
655
+
656
+ export function fromModelsDevProvider(provider: ModelsDev.Provider): Info {
657
+ return {
658
+ id: provider.id,
659
+ source: "custom",
660
+ name: provider.name,
661
+ env: provider.env ?? [],
662
+ options: {},
663
+ models: mapValues(provider.models, (model) => fromModelsDevModel(provider, model)),
664
+ }
665
+ }
666
+
667
+ const state = Instance.state(async () => {
668
+ using _ = log.time("state")
669
+ const config = await Config.get()
670
+ const modelsDev = await ModelsDev.get()
671
+ const database = mapValues(modelsDev, fromModelsDevProvider)
672
+
673
+ const disabled = new Set(config.disabled_providers ?? [])
674
+ const enabled = config.enabled_providers ? new Set(config.enabled_providers) : null
675
+
676
+ function isProviderAllowed(providerID: string): boolean {
677
+ if (enabled && !enabled.has(providerID)) return false
678
+ if (disabled.has(providerID)) return false
679
+ return true
680
+ }
681
+
682
+ const providers: { [providerID: string]: Info } = {}
683
+ const languages = new Map<string, LanguageModelV2>()
684
+ const modelLoaders: {
685
+ [providerID: string]: CustomModelLoader
686
+ } = {}
687
+ const sdk = new Map<number, SDK>()
688
+
689
+ log.info("init")
690
+
691
+ const configProviders = Object.entries(config.provider ?? {})
692
+
693
+ // Add GitHub Copilot Enterprise provider that inherits from GitHub Copilot
694
+ if (database["github-copilot"]) {
695
+ const githubCopilot = database["github-copilot"]
696
+ database["github-copilot-enterprise"] = {
697
+ ...githubCopilot,
698
+ id: "github-copilot-enterprise",
699
+ name: "GitHub Copilot Enterprise",
700
+ models: mapValues(githubCopilot.models, (model) => ({
701
+ ...model,
702
+ providerID: "github-copilot-enterprise",
703
+ })),
704
+ }
705
+ }
706
+
707
+ function mergeProvider(providerID: string, provider: Partial<Info>) {
708
+ const existing = providers[providerID]
709
+ if (existing) {
710
+ // @ts-expect-error
711
+ providers[providerID] = mergeDeep(existing, provider)
712
+ return
713
+ }
714
+ const match = database[providerID]
715
+ if (!match) return
716
+ // @ts-expect-error
717
+ providers[providerID] = mergeDeep(match, provider)
718
+ }
719
+
720
+ // extend database from config
721
+ for (const [providerID, provider] of configProviders) {
722
+ const existing = database[providerID]
723
+ const parsed: Info = {
724
+ id: providerID,
725
+ name: provider.name ?? existing?.name ?? providerID,
726
+ env: provider.env ?? existing?.env ?? [],
727
+ options: mergeDeep(existing?.options ?? {}, provider.options ?? {}),
728
+ source: "config",
729
+ models: existing?.models ?? {},
730
+ }
731
+
732
+ for (const [modelID, model] of Object.entries(provider.models ?? {})) {
733
+ const existingModel = parsed.models[model.id ?? modelID]
734
+ const name = iife(() => {
735
+ if (model.name) return model.name
736
+ if (model.id && model.id !== modelID) return modelID
737
+ return existingModel?.name ?? modelID
738
+ })
739
+ const parsedModel: Model = {
740
+ id: modelID,
741
+ api: {
742
+ id: model.id ?? existingModel?.api.id ?? modelID,
743
+ npm:
744
+ model.provider?.npm ??
745
+ provider.npm ??
746
+ existingModel?.api.npm ??
747
+ modelsDev[providerID]?.npm ??
748
+ "@ai-sdk/openai-compatible",
749
+ url: provider?.api ?? existingModel?.api.url ?? modelsDev[providerID]?.api,
750
+ },
751
+ status: model.status ?? existingModel?.status ?? "active",
752
+ name,
753
+ providerID,
754
+ capabilities: {
755
+ temperature: model.temperature ?? existingModel?.capabilities.temperature ?? false,
756
+ reasoning: model.reasoning ?? existingModel?.capabilities.reasoning ?? false,
757
+ attachment: model.attachment ?? existingModel?.capabilities.attachment ?? false,
758
+ toolcall: model.tool_call ?? existingModel?.capabilities.toolcall ?? true,
759
+ input: {
760
+ text: model.modalities?.input?.includes("text") ?? existingModel?.capabilities.input.text ?? true,
761
+ audio: model.modalities?.input?.includes("audio") ?? existingModel?.capabilities.input.audio ?? false,
762
+ image: model.modalities?.input?.includes("image") ?? existingModel?.capabilities.input.image ?? false,
763
+ video: model.modalities?.input?.includes("video") ?? existingModel?.capabilities.input.video ?? false,
764
+ pdf: model.modalities?.input?.includes("pdf") ?? existingModel?.capabilities.input.pdf ?? false,
765
+ },
766
+ output: {
767
+ text: model.modalities?.output?.includes("text") ?? existingModel?.capabilities.output.text ?? true,
768
+ audio: model.modalities?.output?.includes("audio") ?? existingModel?.capabilities.output.audio ?? false,
769
+ image: model.modalities?.output?.includes("image") ?? existingModel?.capabilities.output.image ?? false,
770
+ video: model.modalities?.output?.includes("video") ?? existingModel?.capabilities.output.video ?? false,
771
+ pdf: model.modalities?.output?.includes("pdf") ?? existingModel?.capabilities.output.pdf ?? false,
772
+ },
773
+ interleaved: model.interleaved ?? false,
774
+ },
775
+ cost: {
776
+ input: model?.cost?.input ?? existingModel?.cost?.input ?? 0,
777
+ output: model?.cost?.output ?? existingModel?.cost?.output ?? 0,
778
+ cache: {
779
+ read: model?.cost?.cache_read ?? existingModel?.cost?.cache.read ?? 0,
780
+ write: model?.cost?.cache_write ?? existingModel?.cost?.cache.write ?? 0,
781
+ },
782
+ },
783
+ options: mergeDeep(existingModel?.options ?? {}, model.options ?? {}),
784
+ limit: {
785
+ context: model.limit?.context ?? existingModel?.limit?.context ?? 0,
786
+ output: model.limit?.output ?? existingModel?.limit?.output ?? 0,
787
+ },
788
+ headers: mergeDeep(existingModel?.headers ?? {}, model.headers ?? {}),
789
+ family: model.family ?? existingModel?.family ?? "",
790
+ release_date: model.release_date ?? existingModel?.release_date ?? "",
791
+ variants: {},
792
+ }
793
+ const merged = mergeDeep(ProviderTransform.variants(parsedModel), model.variants ?? {})
794
+ parsedModel.variants = mapValues(
795
+ pickBy(merged, (v) => !v.disabled),
796
+ (v) => omit(v, ["disabled"]),
797
+ )
798
+ parsed.models[modelID] = parsedModel
799
+ }
800
+ database[providerID] = parsed
801
+ }
802
+
803
+ // load env
804
+ const env = Env.all()
805
+ for (const [providerID, provider] of Object.entries(database)) {
806
+ if (disabled.has(providerID)) continue
807
+ const apiKey = provider.env.map((item) => env[item]).find(Boolean)
808
+ if (!apiKey) continue
809
+ mergeProvider(providerID, {
810
+ source: "env",
811
+ key: provider.env.length === 1 ? apiKey : undefined,
812
+ })
813
+ }
814
+
815
+ // load apikeys
816
+ for (const [providerID, provider] of Object.entries(await Auth.all())) {
817
+ if (disabled.has(providerID)) continue
818
+ if (provider.type === "api") {
819
+ mergeProvider(providerID, {
820
+ source: "api",
821
+ key: provider.key,
822
+ })
823
+ }
824
+ }
825
+
826
+ for (const plugin of await Plugin.list()) {
827
+ if (!plugin.auth) continue
828
+ const providerID = plugin.auth.provider
829
+ if (disabled.has(providerID)) continue
830
+
831
+ // For github-copilot plugin, check if auth exists for either github-copilot or github-copilot-enterprise
832
+ let hasAuth = false
833
+ const auth = await Auth.get(providerID)
834
+ if (auth) hasAuth = true
835
+
836
+ // Special handling for github-copilot: also check for enterprise auth
837
+ if (providerID === "github-copilot" && !hasAuth) {
838
+ const enterpriseAuth = await Auth.get("github-copilot-enterprise")
839
+ if (enterpriseAuth) hasAuth = true
840
+ }
841
+
842
+ if (!hasAuth) continue
843
+ if (!plugin.auth.loader) continue
844
+
845
+ // Load for the main provider if auth exists
846
+ if (auth) {
847
+ const options = await plugin.auth.loader(() => Auth.get(providerID) as any, database[plugin.auth.provider])
848
+ mergeProvider(plugin.auth.provider, {
849
+ source: "custom",
850
+ options: options,
851
+ })
852
+ }
853
+
854
+ // If this is github-copilot plugin, also register for github-copilot-enterprise if auth exists
855
+ if (providerID === "github-copilot") {
856
+ const enterpriseProviderID = "github-copilot-enterprise"
857
+ if (!disabled.has(enterpriseProviderID)) {
858
+ const enterpriseAuth = await Auth.get(enterpriseProviderID)
859
+ if (enterpriseAuth) {
860
+ const enterpriseOptions = await plugin.auth.loader(
861
+ () => Auth.get(enterpriseProviderID) as any,
862
+ database[enterpriseProviderID],
863
+ )
864
+ mergeProvider(enterpriseProviderID, {
865
+ source: "custom",
866
+ options: enterpriseOptions,
867
+ })
868
+ }
869
+ }
870
+ }
871
+ }
872
+
873
+ for (const [providerID, fn] of Object.entries(CUSTOM_LOADERS)) {
874
+ if (disabled.has(providerID)) continue
875
+ const data = database[providerID]
876
+ if (!data) {
877
+ log.error("Provider does not exist in model list " + providerID)
878
+ continue
879
+ }
880
+ const result = await fn(data)
881
+ if (result && (result.autoload || providers[providerID])) {
882
+ if (result.getModel) modelLoaders[providerID] = result.getModel
883
+ mergeProvider(providerID, {
884
+ source: "custom",
885
+ options: result.options,
886
+ })
887
+ }
888
+ }
889
+
890
+ // load config
891
+ for (const [providerID, provider] of configProviders) {
892
+ const partial: Partial<Info> = { source: "config" }
893
+ if (provider.env) partial.env = provider.env
894
+ if (provider.name) partial.name = provider.name
895
+ if (provider.options) partial.options = provider.options
896
+ mergeProvider(providerID, partial)
897
+ }
898
+
899
+ for (const [providerID, provider] of Object.entries(providers)) {
900
+ if (!isProviderAllowed(providerID)) {
901
+ delete providers[providerID]
902
+ continue
903
+ }
904
+
905
+ if (providerID === "github-copilot" || providerID === "github-copilot-enterprise") {
906
+ provider.models = mapValues(provider.models, (model) => ({
907
+ ...model,
908
+ api: {
909
+ ...model.api,
910
+ npm: "@ai-sdk/github-copilot",
911
+ },
912
+ }))
913
+ }
914
+
915
+ const configProvider = config.provider?.[providerID]
916
+
917
+ for (const [modelID, model] of Object.entries(provider.models)) {
918
+ model.api.id = model.api.id ?? model.id ?? modelID
919
+ if (modelID === "gpt-5-chat-latest" || (providerID === "openrouter" && modelID === "openai/gpt-5-chat"))
920
+ delete provider.models[modelID]
921
+ if (model.status === "alpha" && !Flag.OPENCODE_ENABLE_EXPERIMENTAL_MODELS) delete provider.models[modelID]
922
+ if (model.status === "deprecated") delete provider.models[modelID]
923
+ if (
924
+ (configProvider?.blacklist && configProvider.blacklist.includes(modelID)) ||
925
+ (configProvider?.whitelist && !configProvider.whitelist.includes(modelID))
926
+ )
927
+ delete provider.models[modelID]
928
+
929
+ // Filter out disabled variants from config
930
+ const configVariants = configProvider?.models?.[modelID]?.variants
931
+ if (configVariants && model.variants) {
932
+ const merged = mergeDeep(model.variants, configVariants)
933
+ model.variants = mapValues(
934
+ pickBy(merged, (v) => !v.disabled),
935
+ (v) => omit(v, ["disabled"]),
936
+ )
937
+ }
938
+ }
939
+
940
+ if (Object.keys(provider.models).length === 0) {
941
+ delete providers[providerID]
942
+ continue
943
+ }
944
+
945
+ log.info("found", { providerID })
946
+ }
947
+
948
+ return {
949
+ models: languages,
950
+ providers,
951
+ sdk,
952
+ modelLoaders,
953
+ }
954
+ })
955
+
956
+ export async function list() {
957
+ return state().then((state) => state.providers)
958
+ }
959
+
960
+ async function getSDK(model: Model) {
961
+ try {
962
+ using _ = log.time("getSDK", {
963
+ providerID: model.providerID,
964
+ })
965
+ const s = await state()
966
+ const provider = s.providers[model.providerID]
967
+ const options = { ...provider.options }
968
+
969
+ if (model.api.npm.includes("@ai-sdk/openai-compatible") && options["includeUsage"] !== false) {
970
+ options["includeUsage"] = true
971
+ }
972
+
973
+ if (!options["baseURL"]) options["baseURL"] = model.api.url
974
+ if (options["apiKey"] === undefined && provider.key) options["apiKey"] = provider.key
975
+ if (model.headers)
976
+ options["headers"] = {
977
+ ...options["headers"],
978
+ ...model.headers,
979
+ }
980
+
981
+ const key = Bun.hash.xxHash32(JSON.stringify({ npm: model.api.npm, options }))
982
+ const existing = s.sdk.get(key)
983
+ if (existing) return existing
984
+
985
+ const customFetch = options["fetch"]
986
+
987
+ options["fetch"] = async (input: any, init?: BunFetchRequestInit) => {
988
+ // Preserve custom fetch if it exists, wrap it with timeout logic
989
+ const fetchFn = customFetch ?? fetch
990
+ const opts = init ?? {}
991
+
992
+ if (options["timeout"] !== undefined && options["timeout"] !== null) {
993
+ const signals: AbortSignal[] = []
994
+ if (opts.signal) signals.push(opts.signal)
995
+ if (options["timeout"] !== false) signals.push(AbortSignal.timeout(options["timeout"]))
996
+
997
+ const combined = signals.length > 1 ? AbortSignal.any(signals) : signals[0]
998
+
999
+ opts.signal = combined
1000
+ }
1001
+
1002
+ // Strip openai itemId metadata following what codex does
1003
+ // Codex uses #[serde(skip_serializing)] on id fields for all item types:
1004
+ // Message, Reasoning, FunctionCall, LocalShellCall, CustomToolCall, WebSearchCall
1005
+ // IDs are only re-attached for Azure with store=true
1006
+ if (model.api.npm === "@ai-sdk/openai" && opts.body && opts.method === "POST") {
1007
+ const body = JSON.parse(opts.body as string)
1008
+ const isAzure = model.providerID.includes("azure")
1009
+ const keepIds = isAzure && body.store === true
1010
+ if (!keepIds && Array.isArray(body.input)) {
1011
+ for (const item of body.input) {
1012
+ if ("id" in item) {
1013
+ delete item.id
1014
+ }
1015
+ }
1016
+ opts.body = JSON.stringify(body)
1017
+ }
1018
+ }
1019
+
1020
+ return fetchFn(input, {
1021
+ ...opts,
1022
+ // @ts-ignore see here: https://github.com/oven-sh/bun/issues/16682
1023
+ timeout: false,
1024
+ })
1025
+ }
1026
+
1027
+ // Special case: google-vertex-anthropic uses a subpath import
1028
+ const bundledKey =
1029
+ model.providerID === "google-vertex-anthropic" ? "@ai-sdk/google-vertex/anthropic" : model.api.npm
1030
+ const bundledFn = BUNDLED_PROVIDERS[bundledKey]
1031
+ if (bundledFn) {
1032
+ log.info("using bundled provider", { providerID: model.providerID, pkg: bundledKey })
1033
+ const loaded = bundledFn({
1034
+ name: model.providerID,
1035
+ ...options,
1036
+ })
1037
+ s.sdk.set(key, loaded)
1038
+ return loaded as SDK
1039
+ }
1040
+
1041
+ let installedPath: string
1042
+ if (!model.api.npm.startsWith("file://")) {
1043
+ installedPath = await BunProc.install(model.api.npm, "latest")
1044
+ } else {
1045
+ log.info("loading local provider", { pkg: model.api.npm })
1046
+ installedPath = model.api.npm
1047
+ }
1048
+
1049
+ const mod = await import(installedPath)
1050
+
1051
+ const fn = mod[Object.keys(mod).find((key) => key.startsWith("create"))!]
1052
+ const loaded = fn({
1053
+ name: model.providerID,
1054
+ ...options,
1055
+ })
1056
+ s.sdk.set(key, loaded)
1057
+ return loaded as SDK
1058
+ } catch (e) {
1059
+ throw new InitError({ providerID: model.providerID }, { cause: e })
1060
+ }
1061
+ }
1062
+
1063
+ export async function getProvider(providerID: string) {
1064
+ return state().then((s) => s.providers[providerID])
1065
+ }
1066
+
1067
+ export async function getModel(providerID: string, modelID: string) {
1068
+ const s = await state()
1069
+ const provider = s.providers[providerID]
1070
+ if (!provider) {
1071
+ const availableProviders = Object.keys(s.providers)
1072
+ const matches = fuzzysort.go(providerID, availableProviders, { limit: 3, threshold: -10000 })
1073
+ const suggestions = matches.map((m) => m.target)
1074
+ throw new ModelNotFoundError({ providerID, modelID, suggestions })
1075
+ }
1076
+
1077
+ const info = provider.models[modelID]
1078
+ if (!info) {
1079
+ const availableModels = Object.keys(provider.models)
1080
+ const matches = fuzzysort.go(modelID, availableModels, { limit: 3, threshold: -10000 })
1081
+ const suggestions = matches.map((m) => m.target)
1082
+ throw new ModelNotFoundError({ providerID, modelID, suggestions })
1083
+ }
1084
+ return info
1085
+ }
1086
+
1087
+ export async function getLanguage(model: Model): Promise<LanguageModelV2> {
1088
+ const s = await state()
1089
+ const key = `${model.providerID}/${model.id}`
1090
+ if (s.models.has(key)) return s.models.get(key)!
1091
+
1092
+ const provider = s.providers[model.providerID]
1093
+ const sdk = await getSDK(model)
1094
+
1095
+ try {
1096
+ const language = s.modelLoaders[model.providerID]
1097
+ ? await s.modelLoaders[model.providerID](sdk, model.api.id, provider.options)
1098
+ : sdk.languageModel(model.api.id)
1099
+ s.models.set(key, language)
1100
+ return language
1101
+ } catch (e) {
1102
+ if (e instanceof NoSuchModelError)
1103
+ throw new ModelNotFoundError(
1104
+ {
1105
+ modelID: model.id,
1106
+ providerID: model.providerID,
1107
+ },
1108
+ { cause: e },
1109
+ )
1110
+ throw e
1111
+ }
1112
+ }
1113
+
1114
+ export async function closest(providerID: string, query: string[]) {
1115
+ const s = await state()
1116
+ const provider = s.providers[providerID]
1117
+ if (!provider) return undefined
1118
+ for (const item of query) {
1119
+ for (const modelID of Object.keys(provider.models)) {
1120
+ if (modelID.includes(item))
1121
+ return {
1122
+ providerID,
1123
+ modelID,
1124
+ }
1125
+ }
1126
+ }
1127
+ }
1128
+
1129
+ export async function getSmallModel(providerID: string) {
1130
+ const cfg = await Config.get()
1131
+
1132
+ if (cfg.small_model) {
1133
+ const parsed = parseModel(cfg.small_model)
1134
+ return getModel(parsed.providerID, parsed.modelID)
1135
+ }
1136
+
1137
+ const provider = await state().then((state) => state.providers[providerID])
1138
+ if (provider) {
1139
+ let priority = [
1140
+ "claude-haiku-4-5",
1141
+ "claude-haiku-4.5",
1142
+ "3-5-haiku",
1143
+ "3.5-haiku",
1144
+ "gemini-3-flash",
1145
+ "gemini-2.5-flash",
1146
+ "gpt-5-nano",
1147
+ ]
1148
+ if (providerID.startsWith("opencode")) {
1149
+ priority = ["gpt-5-nano"]
1150
+ }
1151
+ if (providerID.startsWith("github-copilot")) {
1152
+ // prioritize free models for github copilot
1153
+ priority = ["gpt-5-mini", "claude-haiku-4.5", ...priority]
1154
+ }
1155
+ for (const item of priority) {
1156
+ for (const model of Object.keys(provider.models)) {
1157
+ if (model.includes(item)) return getModel(providerID, model)
1158
+ }
1159
+ }
1160
+ }
1161
+
1162
+ // Check if opencode provider is available before using it
1163
+ const opencodeProvider = await state().then((state) => state.providers["opencode"])
1164
+ if (opencodeProvider && opencodeProvider.models["gpt-5-nano"]) {
1165
+ return getModel("opencode", "gpt-5-nano")
1166
+ }
1167
+
1168
+ return undefined
1169
+ }
1170
+
1171
+ const priority = ["gpt-5", "claude-sonnet-4", "big-pickle", "gemini-3-pro"]
1172
+ export function sort(models: Model[]) {
1173
+ return sortBy(
1174
+ models,
1175
+ [(model) => priority.findIndex((filter) => model.id.includes(filter)), "desc"],
1176
+ [(model) => (model.id.includes("latest") ? 0 : 1), "asc"],
1177
+ [(model) => model.id, "desc"],
1178
+ )
1179
+ }
1180
+
1181
+ export async function defaultModel() {
1182
+ const cfg = await Config.get()
1183
+ if (cfg.model) return parseModel(cfg.model)
1184
+
1185
+ const provider = await list()
1186
+ .then((val) => Object.values(val))
1187
+ .then((x) => x.find((p) => !cfg.provider || Object.keys(cfg.provider).includes(p.id)))
1188
+ if (!provider) throw new Error("no providers found")
1189
+ const [model] = sort(Object.values(provider.models))
1190
+ if (!model) throw new Error("no models found")
1191
+ return {
1192
+ providerID: provider.id,
1193
+ modelID: model.id,
1194
+ }
1195
+ }
1196
+
1197
+ export function parseModel(model: string) {
1198
+ const [providerID, ...rest] = model.split("/")
1199
+ return {
1200
+ providerID: providerID,
1201
+ modelID: rest.join("/"),
1202
+ }
1203
+ }
1204
+
1205
+ export const ModelNotFoundError = NamedError.create(
1206
+ "ProviderModelNotFoundError",
1207
+ z.object({
1208
+ providerID: z.string(),
1209
+ modelID: z.string(),
1210
+ suggestions: z.array(z.string()).optional(),
1211
+ }),
1212
+ )
1213
+
1214
+ export const InitError = NamedError.create(
1215
+ "ProviderInitError",
1216
+ z.object({
1217
+ providerID: z.string(),
1218
+ }),
1219
+ )
1220
+ }