cerebras-cli 1.0.5 → 1.0.138

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 (322) hide show
  1. package/AGENTS.md +27 -0
  2. package/Dockerfile +10 -0
  3. package/README.md +5 -3
  4. package/bin/{opencode.cjs → opencode} +4 -4
  5. package/bunfig.toml +4 -0
  6. package/package.json +89 -32
  7. package/parsers-config.ts +239 -0
  8. package/script/build.ts +151 -0
  9. package/script/postinstall.mjs +122 -0
  10. package/script/publish.ts +256 -0
  11. package/script/schema.ts +47 -0
  12. package/snake_game.py +111 -0
  13. package/src/acp/README.md +164 -0
  14. package/src/acp/agent.ts +812 -0
  15. package/src/acp/session.ts +70 -0
  16. package/src/acp/types.ts +22 -0
  17. package/src/agent/agent.ts +310 -0
  18. package/src/agent/generate.txt +75 -0
  19. package/src/auth/index.ts +70 -0
  20. package/src/bun/index.ts +152 -0
  21. package/src/bus/global.ts +10 -0
  22. package/src/bus/index.ts +142 -0
  23. package/src/cli/bootstrap.ts +17 -0
  24. package/src/cli/cmd/acp.ts +88 -0
  25. package/src/cli/cmd/agent.ts +165 -0
  26. package/src/cli/cmd/auth.ts +369 -0
  27. package/src/cli/cmd/cmd.ts +7 -0
  28. package/src/cli/cmd/debug/config.ts +15 -0
  29. package/src/cli/cmd/debug/file.ts +91 -0
  30. package/src/cli/cmd/debug/index.ts +43 -0
  31. package/src/cli/cmd/debug/lsp.ts +47 -0
  32. package/src/cli/cmd/debug/ripgrep.ts +83 -0
  33. package/src/cli/cmd/debug/scrap.ts +15 -0
  34. package/src/cli/cmd/debug/skill.ts +36 -0
  35. package/src/cli/cmd/debug/snapshot.ts +48 -0
  36. package/src/cli/cmd/export.ts +88 -0
  37. package/src/cli/cmd/generate.ts +38 -0
  38. package/src/cli/cmd/github.ts +1200 -0
  39. package/src/cli/cmd/import.ts +98 -0
  40. package/src/cli/cmd/mcp.ts +400 -0
  41. package/src/cli/cmd/models.ts +77 -0
  42. package/src/cli/cmd/pr.ts +112 -0
  43. package/src/cli/cmd/run.ts +342 -0
  44. package/src/cli/cmd/serve.ts +31 -0
  45. package/src/cli/cmd/session.ts +106 -0
  46. package/src/cli/cmd/stats.ts +298 -0
  47. package/src/cli/cmd/tui/app.tsx +833 -0
  48. package/src/cli/cmd/tui/attach.ts +25 -0
  49. package/src/cli/cmd/tui/component/border.tsx +21 -0
  50. package/src/cli/cmd/tui/component/cerebras-onboarding.tsx +225 -0
  51. package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
  52. package/src/cli/cmd/tui/component/dialog-command.tsx +124 -0
  53. package/src/cli/cmd/tui/component/dialog-feedback.tsx +160 -0
  54. package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
  55. package/src/cli/cmd/tui/component/dialog-model.tsx +223 -0
  56. package/src/cli/cmd/tui/component/dialog-notification.tsx +78 -0
  57. package/src/cli/cmd/tui/component/dialog-provider.tsx +222 -0
  58. package/src/cli/cmd/tui/component/dialog-session-list.tsx +97 -0
  59. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
  60. package/src/cli/cmd/tui/component/dialog-status.tsx +114 -0
  61. package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
  62. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
  63. package/src/cli/cmd/tui/component/logo.tsx +43 -0
  64. package/src/cli/cmd/tui/component/notification-banner.tsx +58 -0
  65. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +530 -0
  66. package/src/cli/cmd/tui/component/prompt/history.tsx +107 -0
  67. package/src/cli/cmd/tui/component/prompt/index.tsx +931 -0
  68. package/src/cli/cmd/tui/component/quickstart-onboarding.tsx +116 -0
  69. package/src/cli/cmd/tui/context/args.tsx +14 -0
  70. package/src/cli/cmd/tui/context/directory.ts +12 -0
  71. package/src/cli/cmd/tui/context/exit.tsx +23 -0
  72. package/src/cli/cmd/tui/context/helper.tsx +25 -0
  73. package/src/cli/cmd/tui/context/keybind.tsx +111 -0
  74. package/src/cli/cmd/tui/context/kv.tsx +49 -0
  75. package/src/cli/cmd/tui/context/local.tsx +338 -0
  76. package/src/cli/cmd/tui/context/prompt.tsx +18 -0
  77. package/src/cli/cmd/tui/context/route.tsx +45 -0
  78. package/src/cli/cmd/tui/context/sdk.tsx +75 -0
  79. package/src/cli/cmd/tui/context/sync.tsx +374 -0
  80. package/src/cli/cmd/tui/context/theme/aura.json +69 -0
  81. package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
  82. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +233 -0
  83. package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
  84. package/src/cli/cmd/tui/context/theme/cobalt2.json +228 -0
  85. package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
  86. package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
  87. package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
  88. package/src/cli/cmd/tui/context/theme/github.json +233 -0
  89. package/src/cli/cmd/tui/context/theme/gruvbox.json +95 -0
  90. package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
  91. package/src/cli/cmd/tui/context/theme/material.json +235 -0
  92. package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
  93. package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
  94. package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
  95. package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
  96. package/src/cli/cmd/tui/context/theme/nord.json +223 -0
  97. package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
  98. package/src/cli/cmd/tui/context/theme/orng.json +245 -0
  99. package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
  100. package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
  101. package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
  102. package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
  103. package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
  104. package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
  105. package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
  106. package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
  107. package/src/cli/cmd/tui/context/theme.tsx +1077 -0
  108. package/src/cli/cmd/tui/event.ts +39 -0
  109. package/src/cli/cmd/tui/routes/home.tsx +150 -0
  110. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +93 -0
  111. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +37 -0
  112. package/src/cli/cmd/tui/routes/session/footer.tsx +76 -0
  113. package/src/cli/cmd/tui/routes/session/header.tsx +181 -0
  114. package/src/cli/cmd/tui/routes/session/index.tsx +1695 -0
  115. package/src/cli/cmd/tui/routes/session/sidebar.tsx +686 -0
  116. package/src/cli/cmd/tui/spawn.ts +60 -0
  117. package/src/cli/cmd/tui/thread.ts +120 -0
  118. package/src/cli/cmd/tui/ui/dialog-alert.tsx +55 -0
  119. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +81 -0
  120. package/src/cli/cmd/tui/ui/dialog-help.tsx +36 -0
  121. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +75 -0
  122. package/src/cli/cmd/tui/ui/dialog-select.tsx +317 -0
  123. package/src/cli/cmd/tui/ui/dialog.tsx +170 -0
  124. package/src/cli/cmd/tui/ui/spinner.ts +368 -0
  125. package/src/cli/cmd/tui/ui/toast.tsx +100 -0
  126. package/src/cli/cmd/tui/util/clipboard.ts +127 -0
  127. package/src/cli/cmd/tui/util/editor.ts +32 -0
  128. package/src/cli/cmd/tui/util/terminal.ts +114 -0
  129. package/src/cli/cmd/tui/worker.ts +63 -0
  130. package/src/cli/cmd/uninstall.ts +344 -0
  131. package/src/cli/cmd/upgrade.ts +67 -0
  132. package/src/cli/cmd/web.ts +84 -0
  133. package/src/cli/error.ts +55 -0
  134. package/src/cli/ui.ts +84 -0
  135. package/src/cli/upgrade.ts +25 -0
  136. package/src/command/index.ts +79 -0
  137. package/src/command/template/initialize.txt +10 -0
  138. package/src/command/template/review.txt +73 -0
  139. package/src/config/config.ts +886 -0
  140. package/src/config/markdown.ts +41 -0
  141. package/src/env/index.ts +26 -0
  142. package/src/file/fzf.ts +124 -0
  143. package/src/file/ignore.ts +83 -0
  144. package/src/file/index.ts +326 -0
  145. package/src/file/ripgrep.ts +391 -0
  146. package/src/file/time.ts +38 -0
  147. package/src/file/watcher.ts +89 -0
  148. package/src/flag/flag.ts +29 -0
  149. package/src/format/formatter.ts +277 -0
  150. package/src/format/index.ts +137 -0
  151. package/src/global/index.ts +52 -0
  152. package/src/id/id.ts +73 -0
  153. package/src/ide/index.ts +75 -0
  154. package/src/index.ts +158 -0
  155. package/src/installation/index.ts +194 -0
  156. package/src/lsp/client.ts +215 -0
  157. package/src/lsp/index.ts +370 -0
  158. package/src/lsp/language.ts +111 -0
  159. package/src/lsp/server.ts +1327 -0
  160. package/src/mcp/auth.ts +82 -0
  161. package/src/mcp/index.ts +576 -0
  162. package/src/mcp/oauth-callback.ts +203 -0
  163. package/src/mcp/oauth-provider.ts +132 -0
  164. package/src/notification/index.ts +101 -0
  165. package/src/patch/index.ts +622 -0
  166. package/src/permission/index.ts +198 -0
  167. package/src/plugin/index.ts +95 -0
  168. package/src/project/bootstrap.ts +31 -0
  169. package/src/project/instance.ts +68 -0
  170. package/src/project/project.ts +133 -0
  171. package/src/project/state.ts +65 -0
  172. package/src/project/vcs.ts +77 -0
  173. package/src/provider/auth.ts +143 -0
  174. package/src/provider/models-macro.ts +11 -0
  175. package/src/provider/models.ts +93 -0
  176. package/src/provider/provider.ts +1005 -0
  177. package/src/provider/sdk/openai-compatible/src/README.md +5 -0
  178. package/src/provider/sdk/openai-compatible/src/index.ts +2 -0
  179. package/src/provider/sdk/openai-compatible/src/openai-compatible-provider.ts +100 -0
  180. package/src/provider/sdk/openai-compatible/src/responses/convert-to-openai-responses-input.ts +303 -0
  181. package/src/provider/sdk/openai-compatible/src/responses/map-openai-responses-finish-reason.ts +27 -0
  182. package/src/provider/sdk/openai-compatible/src/responses/openai-config.ts +18 -0
  183. package/src/provider/sdk/openai-compatible/src/responses/openai-error.ts +22 -0
  184. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-api-types.ts +207 -0
  185. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-language-model.ts +1713 -0
  186. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-prepare-tools.ts +177 -0
  187. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-settings.ts +1 -0
  188. package/src/provider/sdk/openai-compatible/src/responses/tool/code-interpreter.ts +88 -0
  189. package/src/provider/sdk/openai-compatible/src/responses/tool/file-search.ts +128 -0
  190. package/src/provider/sdk/openai-compatible/src/responses/tool/image-generation.ts +115 -0
  191. package/src/provider/sdk/openai-compatible/src/responses/tool/local-shell.ts +65 -0
  192. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search-preview.ts +104 -0
  193. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search.ts +103 -0
  194. package/src/provider/transform.ts +406 -0
  195. package/src/pty/index.ts +226 -0
  196. package/src/ratelimit/index.ts +185 -0
  197. package/src/server/error.ts +36 -0
  198. package/src/server/project.ts +50 -0
  199. package/src/server/server.ts +2463 -0
  200. package/src/server/tui.ts +71 -0
  201. package/src/session/compaction.ts +257 -0
  202. package/src/session/index.ts +470 -0
  203. package/src/session/message-v2.ts +641 -0
  204. package/src/session/message.ts +189 -0
  205. package/src/session/processor.ts +448 -0
  206. package/src/session/prompt/anthropic-20250930.txt +166 -0
  207. package/src/session/prompt/anthropic.txt +105 -0
  208. package/src/session/prompt/anthropic_spoof.txt +1 -0
  209. package/src/session/prompt/beast.txt +147 -0
  210. package/src/session/prompt/build-switch.txt +5 -0
  211. package/src/session/prompt/codex.txt +318 -0
  212. package/src/session/prompt/compaction.txt +12 -0
  213. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  214. package/src/session/prompt/gemini.txt +155 -0
  215. package/src/session/prompt/max-steps.txt +16 -0
  216. package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  217. package/src/session/prompt/plan.txt +26 -0
  218. package/src/session/prompt/polaris.txt +107 -0
  219. package/src/session/prompt/qwen.txt +109 -0
  220. package/src/session/prompt/summarize.txt +4 -0
  221. package/src/session/prompt/title.txt +36 -0
  222. package/src/session/prompt.ts +1541 -0
  223. package/src/session/retry.ts +82 -0
  224. package/src/session/revert.ts +108 -0
  225. package/src/session/status.ts +75 -0
  226. package/src/session/summary.ts +203 -0
  227. package/src/session/system.ts +148 -0
  228. package/src/session/todo.ts +36 -0
  229. package/src/share/share-next.ts +195 -0
  230. package/src/share/share.ts +87 -0
  231. package/src/skill/index.ts +2 -0
  232. package/src/skill/skill.ts +138 -0
  233. package/src/snapshot/index.ts +197 -0
  234. package/src/storage/storage.ts +226 -0
  235. package/src/telemetry/index.ts +247 -0
  236. package/src/tool/bash.ts +365 -0
  237. package/src/tool/bash.txt +128 -0
  238. package/src/tool/batch.ts +173 -0
  239. package/src/tool/batch.txt +28 -0
  240. package/src/tool/codesearch.ts +138 -0
  241. package/src/tool/codesearch.txt +12 -0
  242. package/src/tool/edit.ts +674 -0
  243. package/src/tool/edit.txt +10 -0
  244. package/src/tool/glob.ts +65 -0
  245. package/src/tool/glob.txt +6 -0
  246. package/src/tool/grep.ts +120 -0
  247. package/src/tool/grep.txt +8 -0
  248. package/src/tool/invalid.ts +17 -0
  249. package/src/tool/ls.ts +110 -0
  250. package/src/tool/ls.txt +1 -0
  251. package/src/tool/lsp-diagnostics.ts +26 -0
  252. package/src/tool/lsp-diagnostics.txt +1 -0
  253. package/src/tool/lsp-hover.ts +31 -0
  254. package/src/tool/lsp-hover.txt +1 -0
  255. package/src/tool/multiedit.ts +46 -0
  256. package/src/tool/multiedit.txt +41 -0
  257. package/src/tool/patch.ts +233 -0
  258. package/src/tool/patch.txt +1 -0
  259. package/src/tool/read.ts +217 -0
  260. package/src/tool/read.txt +12 -0
  261. package/src/tool/registry.ts +150 -0
  262. package/src/tool/skill.ts +85 -0
  263. package/src/tool/task.ts +135 -0
  264. package/src/tool/task.txt +60 -0
  265. package/src/tool/todo.ts +39 -0
  266. package/src/tool/todoread.txt +14 -0
  267. package/src/tool/todowrite.txt +167 -0
  268. package/src/tool/tool.ts +66 -0
  269. package/src/tool/webfetch.ts +187 -0
  270. package/src/tool/webfetch.txt +14 -0
  271. package/src/tool/websearch.ts +150 -0
  272. package/src/tool/websearch.txt +11 -0
  273. package/src/tool/write.ts +99 -0
  274. package/src/tool/write.txt +8 -0
  275. package/src/types/shims.d.ts +3 -0
  276. package/src/util/color.ts +19 -0
  277. package/src/util/context.ts +25 -0
  278. package/src/util/defer.ts +12 -0
  279. package/src/util/eventloop.ts +20 -0
  280. package/src/util/filesystem.ts +69 -0
  281. package/src/util/fn.ts +11 -0
  282. package/src/util/iife.ts +3 -0
  283. package/src/util/keybind.ts +79 -0
  284. package/src/util/lazy.ts +11 -0
  285. package/src/util/locale.ts +81 -0
  286. package/src/util/lock.ts +98 -0
  287. package/src/util/log.ts +177 -0
  288. package/src/util/queue.ts +32 -0
  289. package/src/util/rpc.ts +42 -0
  290. package/src/util/scrap.ts +10 -0
  291. package/src/util/signal.ts +12 -0
  292. package/src/util/timeout.ts +14 -0
  293. package/src/util/token.ts +7 -0
  294. package/src/util/wildcard.ts +54 -0
  295. package/sst-env.d.ts +9 -0
  296. package/test/bun.test.ts +53 -0
  297. package/test/config/agent-color.test.ts +66 -0
  298. package/test/config/config.test.ts +503 -0
  299. package/test/config/markdown.test.ts +89 -0
  300. package/test/file/ignore.test.ts +10 -0
  301. package/test/fixture/fixture.ts +28 -0
  302. package/test/fixture/lsp/fake-lsp-server.js +77 -0
  303. package/test/ide/ide.test.ts +82 -0
  304. package/test/keybind.test.ts +317 -0
  305. package/test/lsp/client.test.ts +95 -0
  306. package/test/patch/patch.test.ts +348 -0
  307. package/test/preload.ts +38 -0
  308. package/test/project/project.test.ts +42 -0
  309. package/test/provider/provider.test.ts +1809 -0
  310. package/test/provider/transform.test.ts +305 -0
  311. package/test/session/retry.test.ts +61 -0
  312. package/test/session/session.test.ts +71 -0
  313. package/test/snapshot/snapshot.test.ts +939 -0
  314. package/test/tool/__snapshots__/tool.test.ts.snap +9 -0
  315. package/test/tool/bash.test.ts +55 -0
  316. package/test/tool/patch.test.ts +259 -0
  317. package/test/util/iife.test.ts +36 -0
  318. package/test/util/lazy.test.ts +50 -0
  319. package/test/util/timeout.test.ts +21 -0
  320. package/test/util/wildcard.test.ts +55 -0
  321. package/tsconfig.json +17 -0
  322. package/cerebras-cli-1.0.0.tgz +0 -0
@@ -0,0 +1,1005 @@
1
+ import z from "zod"
2
+ import fuzzysort from "fuzzysort"
3
+ import { Config } from "../config/config"
4
+ import { mapValues, mergeDeep, 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 "@opencode-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
+ import { RateLimit } from "@/ratelimit"
17
+
18
+ // Direct imports for bundled providers
19
+ import { createAmazonBedrock } from "@ai-sdk/amazon-bedrock"
20
+ import { createAnthropic } from "@ai-sdk/anthropic"
21
+ import { createAzure } from "@ai-sdk/azure"
22
+ import { createGoogleGenerativeAI } from "@ai-sdk/google"
23
+ import { createVertex } from "@ai-sdk/google-vertex"
24
+ import { createVertexAnthropic } from "@ai-sdk/google-vertex/anthropic"
25
+ import { createOpenAI } from "@ai-sdk/openai"
26
+ import { createOpenAICompatible } from "@ai-sdk/openai-compatible"
27
+ import { createOpenRouter, type LanguageModelV2 } from "@openrouter/ai-sdk-provider"
28
+ import { createOpenaiCompatible as createGitHubCopilotOpenAICompatible } from "./sdk/openai-compatible/src"
29
+
30
+ export namespace Provider {
31
+ const log = Log.create({ service: "provider" })
32
+
33
+ const BUNDLED_PROVIDERS: Record<string, (options: any) => SDK> = {
34
+ "@ai-sdk/amazon-bedrock": createAmazonBedrock,
35
+ "@ai-sdk/anthropic": createAnthropic,
36
+ "@ai-sdk/azure": createAzure,
37
+ "@ai-sdk/google": createGoogleGenerativeAI,
38
+ "@ai-sdk/google-vertex": createVertex,
39
+ "@ai-sdk/google-vertex/anthropic": createVertexAnthropic,
40
+ "@ai-sdk/openai": createOpenAI,
41
+ "@ai-sdk/openai-compatible": createOpenAICompatible,
42
+ "@openrouter/ai-sdk-provider": createOpenRouter,
43
+ // @ts-ignore (TODO: kill this code so we dont have to maintain it)
44
+ "@ai-sdk/github-copilot": createGitHubCopilotOpenAICompatible,
45
+ // Use OpenAI-compatible SDK for Cerebras to handle response format differences
46
+ "@ai-sdk/cerebras": createOpenAICompatible,
47
+ }
48
+
49
+ type CustomModelLoader = (sdk: any, modelID: string, options?: Record<string, any>) => Promise<any>
50
+ type CustomLoader = (provider: Info) => Promise<{
51
+ autoload: boolean
52
+ getModel?: CustomModelLoader
53
+ options?: Record<string, any>
54
+ }>
55
+
56
+ const CUSTOM_LOADERS: Record<string, CustomLoader> = {
57
+ async anthropic() {
58
+ return {
59
+ autoload: false,
60
+ options: {
61
+ headers: {
62
+ "anthropic-beta":
63
+ "claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",
64
+ },
65
+ },
66
+ }
67
+ },
68
+ async opencode(input) {
69
+ const hasKey = await (async () => {
70
+ const env = Env.all()
71
+ if (input.env.some((item) => env[item])) return true
72
+ if (await Auth.get(input.id)) return true
73
+ return false
74
+ })()
75
+
76
+ if (!hasKey) {
77
+ for (const [key, value] of Object.entries(input.models)) {
78
+ if (value.cost.input === 0) continue
79
+ delete input.models[key]
80
+ }
81
+ }
82
+
83
+ return {
84
+ autoload: Object.keys(input.models).length > 0,
85
+ options: hasKey ? {} : { apiKey: "public" },
86
+ }
87
+ },
88
+ openai: async () => {
89
+ return {
90
+ autoload: false,
91
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
92
+ return sdk.responses(modelID)
93
+ },
94
+ options: {},
95
+ }
96
+ },
97
+ cerebras: async () => {
98
+ return {
99
+ autoload: false,
100
+ options: {
101
+ baseURL: "https://api.cerebras.ai/v1",
102
+ headers: {
103
+ "X-Cerebras-3rd-Party-Integration": "cli",
104
+ },
105
+ },
106
+ }
107
+ },
108
+ "github-copilot": async () => {
109
+ return {
110
+ autoload: false,
111
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
112
+ if (modelID.includes("codex")) {
113
+ return sdk.responses(modelID)
114
+ }
115
+ return sdk.chat(modelID)
116
+ },
117
+ options: {},
118
+ }
119
+ },
120
+ "github-copilot-enterprise": async () => {
121
+ return {
122
+ autoload: false,
123
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
124
+ if (modelID.includes("codex")) {
125
+ return sdk.responses(modelID)
126
+ }
127
+ return sdk.chat(modelID)
128
+ },
129
+ options: {},
130
+ }
131
+ },
132
+ azure: async () => {
133
+ return {
134
+ autoload: false,
135
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
136
+ if (options?.["useCompletionUrls"]) {
137
+ return sdk.chat(modelID)
138
+ } else {
139
+ return sdk.responses(modelID)
140
+ }
141
+ },
142
+ options: {},
143
+ }
144
+ },
145
+ "azure-cognitive-services": async () => {
146
+ const resourceName = Env.get("AZURE_COGNITIVE_SERVICES_RESOURCE_NAME")
147
+ return {
148
+ autoload: false,
149
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
150
+ if (options?.["useCompletionUrls"]) {
151
+ return sdk.chat(modelID)
152
+ } else {
153
+ return sdk.responses(modelID)
154
+ }
155
+ },
156
+ options: {
157
+ baseURL: resourceName ? `https://${resourceName}.cognitiveservices.azure.com/openai` : undefined,
158
+ },
159
+ }
160
+ },
161
+ "amazon-bedrock": async () => {
162
+ const [awsProfile, awsAccessKeyId, awsBearerToken, awsRegion] = await Promise.all([
163
+ Env.get("AWS_PROFILE"),
164
+ Env.get("AWS_ACCESS_KEY_ID"),
165
+ Env.get("AWS_BEARER_TOKEN_BEDROCK"),
166
+ Env.get("AWS_REGION"),
167
+ ])
168
+ if (!awsProfile && !awsAccessKeyId && !awsBearerToken) return { autoload: false }
169
+
170
+ const region = awsRegion ?? "us-east-1"
171
+
172
+ const { fromNodeProviderChain } = await import(await BunProc.install("@aws-sdk/credential-providers"))
173
+ return {
174
+ autoload: true,
175
+ options: {
176
+ region,
177
+ credentialProvider: fromNodeProviderChain(),
178
+ },
179
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
180
+ // Skip region prefixing if model already has global prefix
181
+ if (modelID.startsWith("global.")) {
182
+ return sdk.languageModel(modelID)
183
+ }
184
+
185
+ let regionPrefix = region.split("-")[0]
186
+
187
+ switch (regionPrefix) {
188
+ case "us": {
189
+ const modelRequiresPrefix = [
190
+ "nova-micro",
191
+ "nova-lite",
192
+ "nova-pro",
193
+ "nova-premier",
194
+ "claude",
195
+ "deepseek",
196
+ ].some((m) => modelID.includes(m))
197
+ const isGovCloud = region.startsWith("us-gov")
198
+ if (modelRequiresPrefix && !isGovCloud) {
199
+ modelID = `${regionPrefix}.${modelID}`
200
+ }
201
+ break
202
+ }
203
+ case "eu": {
204
+ const regionRequiresPrefix = [
205
+ "eu-west-1",
206
+ "eu-west-2",
207
+ "eu-west-3",
208
+ "eu-north-1",
209
+ "eu-central-1",
210
+ "eu-south-1",
211
+ "eu-south-2",
212
+ ].some((r) => region.includes(r))
213
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "llama3", "pixtral"].some((m) =>
214
+ modelID.includes(m),
215
+ )
216
+ if (regionRequiresPrefix && modelRequiresPrefix) {
217
+ modelID = `${regionPrefix}.${modelID}`
218
+ }
219
+ break
220
+ }
221
+ case "ap": {
222
+ const isAustraliaRegion = ["ap-southeast-2", "ap-southeast-4"].includes(region)
223
+ if (
224
+ isAustraliaRegion &&
225
+ ["anthropic.claude-sonnet-4-5", "anthropic.claude-haiku"].some((m) => modelID.includes(m))
226
+ ) {
227
+ regionPrefix = "au"
228
+ modelID = `${regionPrefix}.${modelID}`
229
+ } else {
230
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "nova-pro"].some((m) =>
231
+ modelID.includes(m),
232
+ )
233
+ if (modelRequiresPrefix) {
234
+ regionPrefix = "apac"
235
+ modelID = `${regionPrefix}.${modelID}`
236
+ }
237
+ }
238
+ break
239
+ }
240
+ }
241
+
242
+ return sdk.languageModel(modelID)
243
+ },
244
+ }
245
+ },
246
+ openrouter: async () => {
247
+ return {
248
+ autoload: false,
249
+ options: {
250
+ headers: {
251
+ "HTTP-Referer": "https://opencode.ai/",
252
+ "X-Title": "opencode",
253
+ },
254
+ },
255
+ }
256
+ },
257
+ vercel: async () => {
258
+ return {
259
+ autoload: false,
260
+ options: {
261
+ headers: {
262
+ "http-referer": "https://opencode.ai/",
263
+ "x-title": "opencode",
264
+ },
265
+ },
266
+ }
267
+ },
268
+ "google-vertex": async () => {
269
+ const project = Env.get("GOOGLE_CLOUD_PROJECT") ?? Env.get("GCP_PROJECT") ?? Env.get("GCLOUD_PROJECT")
270
+ const location = Env.get("GOOGLE_CLOUD_LOCATION") ?? Env.get("VERTEX_LOCATION") ?? "us-east5"
271
+ const autoload = Boolean(project)
272
+ if (!autoload) return { autoload: false }
273
+ return {
274
+ autoload: true,
275
+ options: {
276
+ project,
277
+ location,
278
+ },
279
+ async getModel(sdk: any, modelID: string) {
280
+ const id = String(modelID).trim()
281
+ return sdk.languageModel(id)
282
+ },
283
+ }
284
+ },
285
+ "google-vertex-anthropic": async () => {
286
+ const project = Env.get("GOOGLE_CLOUD_PROJECT") ?? Env.get("GCP_PROJECT") ?? Env.get("GCLOUD_PROJECT")
287
+ const location = Env.get("GOOGLE_CLOUD_LOCATION") ?? Env.get("VERTEX_LOCATION") ?? "global"
288
+ const autoload = Boolean(project)
289
+ if (!autoload) return { autoload: false }
290
+ return {
291
+ autoload: true,
292
+ options: {
293
+ project,
294
+ location,
295
+ },
296
+ async getModel(sdk: any, modelID) {
297
+ const id = String(modelID).trim()
298
+ return sdk.languageModel(id)
299
+ },
300
+ }
301
+ },
302
+ "sap-ai-core": async () => {
303
+ const auth = await Auth.get("sap-ai-core")
304
+ const envServiceKey = iife(() => {
305
+ const envAICoreServiceKey = Env.get("AICORE_SERVICE_KEY")
306
+ if (envAICoreServiceKey) return envAICoreServiceKey
307
+ if (auth?.type === "api") {
308
+ Env.set("AICORE_SERVICE_KEY", auth.key)
309
+ return auth.key
310
+ }
311
+ return undefined
312
+ })
313
+ const deploymentId = Env.get("AICORE_DEPLOYMENT_ID")
314
+ const resourceGroup = Env.get("AICORE_RESOURCE_GROUP")
315
+
316
+ return {
317
+ autoload: !!envServiceKey,
318
+ options: envServiceKey ? { deploymentId, resourceGroup } : {},
319
+ async getModel(sdk: any, modelID: string) {
320
+ return sdk(modelID)
321
+ },
322
+ }
323
+ },
324
+ zenmux: 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
+ }
336
+
337
+ export const Model = z
338
+ .object({
339
+ id: z.string(),
340
+ providerID: z.string(),
341
+ api: z.object({
342
+ id: z.string(),
343
+ url: z.string(),
344
+ npm: z.string(),
345
+ }),
346
+ name: z.string(),
347
+ capabilities: z.object({
348
+ temperature: z.boolean(),
349
+ reasoning: z.boolean(),
350
+ attachment: z.boolean(),
351
+ toolcall: z.boolean(),
352
+ input: z.object({
353
+ text: z.boolean(),
354
+ audio: z.boolean(),
355
+ image: z.boolean(),
356
+ video: z.boolean(),
357
+ pdf: z.boolean(),
358
+ }),
359
+ output: z.object({
360
+ text: z.boolean(),
361
+ audio: z.boolean(),
362
+ image: z.boolean(),
363
+ video: z.boolean(),
364
+ pdf: z.boolean(),
365
+ }),
366
+ }),
367
+ cost: z.object({
368
+ input: z.number(),
369
+ output: z.number(),
370
+ cache: z.object({
371
+ read: z.number(),
372
+ write: z.number(),
373
+ }),
374
+ experimentalOver200K: z
375
+ .object({
376
+ input: z.number(),
377
+ output: z.number(),
378
+ cache: z.object({
379
+ read: z.number(),
380
+ write: z.number(),
381
+ }),
382
+ })
383
+ .optional(),
384
+ }),
385
+ limit: z.object({
386
+ context: z.number(),
387
+ output: z.number(),
388
+ }),
389
+ status: z.enum(["alpha", "beta", "deprecated", "active"]),
390
+ options: z.record(z.string(), z.any()),
391
+ headers: z.record(z.string(), z.string()),
392
+ })
393
+ .meta({
394
+ ref: "Model",
395
+ })
396
+ export type Model = z.infer<typeof Model>
397
+
398
+ export const Info = z
399
+ .object({
400
+ id: z.string(),
401
+ name: z.string(),
402
+ source: z.enum(["env", "config", "custom", "api"]),
403
+ env: z.string().array(),
404
+ key: z.string().optional(),
405
+ options: z.record(z.string(), z.any()),
406
+ models: z.record(z.string(), Model),
407
+ })
408
+ .meta({
409
+ ref: "Provider",
410
+ })
411
+ export type Info = z.infer<typeof Info>
412
+
413
+ function fromModelsDevModel(provider: ModelsDev.Provider, model: ModelsDev.Model): Model {
414
+ return {
415
+ id: model.id,
416
+ providerID: provider.id,
417
+ name: model.name,
418
+ api: {
419
+ id: model.id,
420
+ url: provider.api!,
421
+ npm: model.provider?.npm ?? provider.npm ?? provider.id,
422
+ },
423
+ status: model.status ?? "active",
424
+ headers: model.headers ?? {},
425
+ options: model.options ?? {},
426
+ cost: {
427
+ input: model.cost?.input ?? 0,
428
+ output: model.cost?.output ?? 0,
429
+ cache: {
430
+ read: model.cost?.cache_read ?? 0,
431
+ write: model.cost?.cache_write ?? 0,
432
+ },
433
+ experimentalOver200K: model.cost?.context_over_200k
434
+ ? {
435
+ cache: {
436
+ read: model.cost.context_over_200k.cache_read ?? 0,
437
+ write: model.cost.context_over_200k.cache_write ?? 0,
438
+ },
439
+ input: model.cost.context_over_200k.input,
440
+ output: model.cost.context_over_200k.output,
441
+ }
442
+ : undefined,
443
+ },
444
+ limit: {
445
+ context: model.limit.context,
446
+ output: model.limit.output,
447
+ },
448
+ capabilities: {
449
+ temperature: model.temperature,
450
+ reasoning: model.reasoning,
451
+ attachment: model.attachment,
452
+ toolcall: model.tool_call,
453
+ input: {
454
+ text: model.modalities?.input?.includes("text") ?? false,
455
+ audio: model.modalities?.input?.includes("audio") ?? false,
456
+ image: model.modalities?.input?.includes("image") ?? false,
457
+ video: model.modalities?.input?.includes("video") ?? false,
458
+ pdf: model.modalities?.input?.includes("pdf") ?? false,
459
+ },
460
+ output: {
461
+ text: model.modalities?.output?.includes("text") ?? false,
462
+ audio: model.modalities?.output?.includes("audio") ?? false,
463
+ image: model.modalities?.output?.includes("image") ?? false,
464
+ video: model.modalities?.output?.includes("video") ?? false,
465
+ pdf: model.modalities?.output?.includes("pdf") ?? false,
466
+ },
467
+ },
468
+ }
469
+ }
470
+
471
+ export function fromModelsDevProvider(provider: ModelsDev.Provider): Info {
472
+ return {
473
+ id: provider.id,
474
+ source: "custom",
475
+ name: provider.name,
476
+ env: provider.env ?? [],
477
+ options: {},
478
+ models: mapValues(provider.models, (model) => fromModelsDevModel(provider, model)),
479
+ }
480
+ }
481
+
482
+ const state = Instance.state(async () => {
483
+ using _ = log.time("state")
484
+ const config = await Config.get()
485
+ const modelsDev = await ModelsDev.get()
486
+ const database = mapValues(modelsDev, fromModelsDevProvider)
487
+
488
+ const disabled = new Set(config.disabled_providers ?? [])
489
+ const enabled = config.enabled_providers ? new Set(config.enabled_providers) : null
490
+
491
+ function isProviderAllowed(providerID: string): boolean {
492
+ if (enabled && !enabled.has(providerID)) return false
493
+ if (disabled.has(providerID)) return false
494
+ return true
495
+ }
496
+
497
+ const providers: { [providerID: string]: Info } = {}
498
+ const languages = new Map<string, LanguageModelV2>()
499
+ const modelLoaders: {
500
+ [providerID: string]: CustomModelLoader
501
+ } = {}
502
+ const sdk = new Map<number, SDK>()
503
+
504
+ log.info("init")
505
+
506
+ const configProviders = Object.entries(config.provider ?? {})
507
+
508
+ // Add GitHub Copilot Enterprise provider that inherits from GitHub Copilot
509
+ if (database["github-copilot"]) {
510
+ const githubCopilot = database["github-copilot"]
511
+ database["github-copilot-enterprise"] = {
512
+ ...githubCopilot,
513
+ id: "github-copilot-enterprise",
514
+ name: "GitHub Copilot Enterprise",
515
+ models: mapValues(githubCopilot.models, (model) => ({
516
+ ...model,
517
+ providerID: "github-copilot-enterprise",
518
+ })),
519
+ }
520
+ }
521
+
522
+ function mergeProvider(providerID: string, provider: Partial<Info>) {
523
+ const existing = providers[providerID]
524
+ if (existing) {
525
+ // @ts-expect-error
526
+ providers[providerID] = mergeDeep(existing, provider)
527
+ return
528
+ }
529
+ const match = database[providerID]
530
+ if (!match) return
531
+ // @ts-expect-error
532
+ providers[providerID] = mergeDeep(match, provider)
533
+ }
534
+
535
+ // extend database from config
536
+ for (const [providerID, provider] of configProviders) {
537
+ const existing = database[providerID]
538
+ const parsed: Info = {
539
+ id: providerID,
540
+ name: provider.name ?? existing?.name ?? providerID,
541
+ env: provider.env ?? existing?.env ?? [],
542
+ options: mergeDeep(existing?.options ?? {}, provider.options ?? {}),
543
+ source: "config",
544
+ models: existing?.models ?? {},
545
+ }
546
+
547
+ for (const [modelID, model] of Object.entries(provider.models ?? {})) {
548
+ const existingModel = parsed.models[model.id ?? modelID]
549
+ const name = iife(() => {
550
+ if (model.name) return model.name
551
+ if (model.id && model.id !== modelID) return modelID
552
+ return existingModel?.name ?? modelID
553
+ })
554
+ const parsedModel: Model = {
555
+ id: modelID,
556
+ api: {
557
+ id: model.id ?? existingModel?.api.id ?? modelID,
558
+ npm:
559
+ model.provider?.npm ?? provider.npm ?? existingModel?.api.npm ?? modelsDev[providerID]?.npm ?? providerID,
560
+ url: provider?.api ?? existingModel?.api.url ?? modelsDev[providerID]?.api,
561
+ },
562
+ status: model.status ?? existingModel?.status ?? "active",
563
+ name,
564
+ providerID,
565
+ capabilities: {
566
+ temperature: model.temperature ?? existingModel?.capabilities.temperature ?? false,
567
+ reasoning: model.reasoning ?? existingModel?.capabilities.reasoning ?? false,
568
+ attachment: model.attachment ?? existingModel?.capabilities.attachment ?? false,
569
+ toolcall: model.tool_call ?? existingModel?.capabilities.toolcall ?? true,
570
+ input: {
571
+ text: model.modalities?.input?.includes("text") ?? existingModel?.capabilities.input.text ?? true,
572
+ audio: model.modalities?.input?.includes("audio") ?? existingModel?.capabilities.input.audio ?? false,
573
+ image: model.modalities?.input?.includes("image") ?? existingModel?.capabilities.input.image ?? false,
574
+ video: model.modalities?.input?.includes("video") ?? existingModel?.capabilities.input.video ?? false,
575
+ pdf: model.modalities?.input?.includes("pdf") ?? existingModel?.capabilities.input.pdf ?? false,
576
+ },
577
+ output: {
578
+ text: model.modalities?.output?.includes("text") ?? existingModel?.capabilities.output.text ?? true,
579
+ audio: model.modalities?.output?.includes("audio") ?? existingModel?.capabilities.output.audio ?? false,
580
+ image: model.modalities?.output?.includes("image") ?? existingModel?.capabilities.output.image ?? false,
581
+ video: model.modalities?.output?.includes("video") ?? existingModel?.capabilities.output.video ?? false,
582
+ pdf: model.modalities?.output?.includes("pdf") ?? existingModel?.capabilities.output.pdf ?? false,
583
+ },
584
+ },
585
+ cost: {
586
+ input: model?.cost?.input ?? existingModel?.cost?.input ?? 0,
587
+ output: model?.cost?.output ?? existingModel?.cost?.output ?? 0,
588
+ cache: {
589
+ read: model?.cost?.cache_read ?? existingModel?.cost?.cache.read ?? 0,
590
+ write: model?.cost?.cache_write ?? existingModel?.cost?.cache.write ?? 0,
591
+ },
592
+ },
593
+ options: mergeDeep(existingModel?.options ?? {}, model.options ?? {}),
594
+ limit: {
595
+ context: model.limit?.context ?? existingModel?.limit?.context ?? 0,
596
+ output: model.limit?.output ?? existingModel?.limit?.output ?? 0,
597
+ },
598
+ headers: mergeDeep(existingModel?.headers ?? {}, model.headers ?? {}),
599
+ }
600
+ parsed.models[modelID] = parsedModel
601
+ }
602
+ database[providerID] = parsed
603
+ }
604
+
605
+ // load env
606
+ const env = Env.all()
607
+ for (const [providerID, provider] of Object.entries(database)) {
608
+ if (disabled.has(providerID)) continue
609
+ const apiKey = provider.env.map((item) => env[item]).find(Boolean)
610
+ if (!apiKey) continue
611
+ mergeProvider(providerID, {
612
+ source: "env",
613
+ key: provider.env.length === 1 ? apiKey : undefined,
614
+ })
615
+ }
616
+
617
+ // load apikeys
618
+ for (const [providerID, provider] of Object.entries(await Auth.all())) {
619
+ if (disabled.has(providerID)) continue
620
+ if (provider.type === "api") {
621
+ mergeProvider(providerID, {
622
+ source: "api",
623
+ key: provider.key,
624
+ })
625
+ }
626
+ }
627
+
628
+ for (const plugin of await Plugin.list()) {
629
+ if (!plugin.auth) continue
630
+ const providerID = plugin.auth.provider
631
+ if (disabled.has(providerID)) continue
632
+
633
+ // For github-copilot plugin, check if auth exists for either github-copilot or github-copilot-enterprise
634
+ let hasAuth = false
635
+ const auth = await Auth.get(providerID)
636
+ if (auth) hasAuth = true
637
+
638
+ // Special handling for github-copilot: also check for enterprise auth
639
+ if (providerID === "github-copilot" && !hasAuth) {
640
+ const enterpriseAuth = await Auth.get("github-copilot-enterprise")
641
+ if (enterpriseAuth) hasAuth = true
642
+ }
643
+
644
+ if (!hasAuth) continue
645
+ if (!plugin.auth.loader) continue
646
+
647
+ // Load for the main provider if auth exists
648
+ if (auth) {
649
+ const options = await plugin.auth.loader(() => Auth.get(providerID) as any, database[plugin.auth.provider])
650
+ mergeProvider(plugin.auth.provider, {
651
+ source: "custom",
652
+ options: options,
653
+ })
654
+ }
655
+
656
+ // If this is github-copilot plugin, also register for github-copilot-enterprise if auth exists
657
+ if (providerID === "github-copilot") {
658
+ const enterpriseProviderID = "github-copilot-enterprise"
659
+ if (!disabled.has(enterpriseProviderID)) {
660
+ const enterpriseAuth = await Auth.get(enterpriseProviderID)
661
+ if (enterpriseAuth) {
662
+ const enterpriseOptions = await plugin.auth.loader(
663
+ () => Auth.get(enterpriseProviderID) as any,
664
+ database[enterpriseProviderID],
665
+ )
666
+ mergeProvider(enterpriseProviderID, {
667
+ source: "custom",
668
+ options: enterpriseOptions,
669
+ })
670
+ }
671
+ }
672
+ }
673
+ }
674
+
675
+ for (const [providerID, fn] of Object.entries(CUSTOM_LOADERS)) {
676
+ if (disabled.has(providerID)) continue
677
+ const result = await fn(database[providerID])
678
+ if (result && (result.autoload || providers[providerID])) {
679
+ if (result.getModel) modelLoaders[providerID] = result.getModel
680
+ mergeProvider(providerID, {
681
+ source: "custom",
682
+ options: result.options,
683
+ })
684
+ }
685
+ }
686
+
687
+ // load config
688
+ for (const [providerID, provider] of configProviders) {
689
+ const partial: Partial<Info> = { source: "config" }
690
+ if (provider.env) partial.env = provider.env
691
+ if (provider.name) partial.name = provider.name
692
+ if (provider.options) partial.options = provider.options
693
+ mergeProvider(providerID, partial)
694
+ }
695
+
696
+ for (const [providerID, provider] of Object.entries(providers)) {
697
+ if (!isProviderAllowed(providerID)) {
698
+ delete providers[providerID]
699
+ continue
700
+ }
701
+
702
+ if (providerID === "github-copilot" || providerID === "github-copilot-enterprise") {
703
+ provider.models = mapValues(provider.models, (model) => ({
704
+ ...model,
705
+ api: {
706
+ ...model.api,
707
+ npm: "@ai-sdk/github-copilot",
708
+ },
709
+ }))
710
+ }
711
+
712
+ const configProvider = config.provider?.[providerID]
713
+
714
+ for (const [modelID, model] of Object.entries(provider.models)) {
715
+ model.api.id = model.api.id ?? model.id ?? modelID
716
+ if (modelID === "gpt-5-chat-latest" || (providerID === "openrouter" && modelID === "openai/gpt-5-chat"))
717
+ delete provider.models[modelID]
718
+ if (model.status === "alpha" && !Flag.OPENCODE_ENABLE_EXPERIMENTAL_MODELS) delete provider.models[modelID]
719
+ if (
720
+ (configProvider?.blacklist && configProvider.blacklist.includes(modelID)) ||
721
+ (configProvider?.whitelist && !configProvider.whitelist.includes(modelID))
722
+ )
723
+ delete provider.models[modelID]
724
+ }
725
+
726
+ if (Object.keys(provider.models).length === 0) {
727
+ delete providers[providerID]
728
+ continue
729
+ }
730
+
731
+ log.info("found", { providerID })
732
+ }
733
+
734
+ return {
735
+ models: languages,
736
+ providers,
737
+ sdk,
738
+ modelLoaders,
739
+ }
740
+ })
741
+
742
+ export async function list() {
743
+ return state().then((state) => state.providers)
744
+ }
745
+
746
+ async function getSDK(model: Model) {
747
+ try {
748
+ using _ = log.time("getSDK", {
749
+ providerID: model.providerID,
750
+ })
751
+ const s = await state()
752
+ const provider = s.providers[model.providerID]
753
+ const options = { ...provider.options }
754
+
755
+ if (model.api.npm.includes("@ai-sdk/openai-compatible") && options["includeUsage"] !== false) {
756
+ options["includeUsage"] = true
757
+ }
758
+
759
+ if (!options["baseURL"]) options["baseURL"] = model.api.url
760
+ if (options["apiKey"] === undefined && provider.key) options["apiKey"] = provider.key
761
+ if (model.headers)
762
+ options["headers"] = {
763
+ ...options["headers"],
764
+ ...model.headers,
765
+ }
766
+
767
+ const key = Bun.hash.xxHash32(JSON.stringify({ npm: model.api.npm, options }))
768
+ const existing = s.sdk.get(key)
769
+ if (existing) return existing
770
+
771
+ const customFetch = options["fetch"]
772
+
773
+ options["fetch"] = async (input: any, init?: BunFetchRequestInit) => {
774
+ // Preserve custom fetch if it exists, wrap it with timeout logic
775
+ const fetchFn = customFetch ?? fetch
776
+ const opts = init ?? {}
777
+
778
+ if (options["timeout"] !== undefined && options["timeout"] !== null) {
779
+ const signals: AbortSignal[] = []
780
+ if (opts.signal) signals.push(opts.signal)
781
+ if (options["timeout"] !== false) signals.push(AbortSignal.timeout(options["timeout"]))
782
+
783
+ const combined = signals.length > 1 ? AbortSignal.any(signals) : signals[0]
784
+
785
+ opts.signal = combined
786
+ }
787
+
788
+ const response = await fetchFn(input, {
789
+ ...opts,
790
+ // @ts-ignore see here: https://github.com/oven-sh/bun/issues/16682
791
+ timeout: false,
792
+ })
793
+
794
+ // Capture rate limit headers from response
795
+ try {
796
+ const rateLimitInfo = RateLimit.parseHeaders(response.headers, model.providerID)
797
+ if (rateLimitInfo) {
798
+ RateLimit.setLatest(model.providerID, rateLimitInfo)
799
+ }
800
+ } catch {
801
+ // Ignore errors parsing rate limit headers
802
+ }
803
+
804
+ return response
805
+ }
806
+
807
+ // Special case: google-vertex-anthropic uses a subpath import
808
+ const bundledKey =
809
+ model.providerID === "google-vertex-anthropic" ? "@ai-sdk/google-vertex/anthropic" : model.api.npm
810
+ const bundledFn = BUNDLED_PROVIDERS[bundledKey]
811
+ if (bundledFn) {
812
+ log.info("using bundled provider", { providerID: model.providerID, pkg: bundledKey })
813
+ const loaded = bundledFn({
814
+ name: model.providerID,
815
+ ...options,
816
+ })
817
+ s.sdk.set(key, loaded)
818
+ return loaded as SDK
819
+ }
820
+
821
+ let installedPath: string
822
+ if (!model.api.npm.startsWith("file://")) {
823
+ installedPath = await BunProc.install(model.api.npm, "latest")
824
+ } else {
825
+ log.info("loading local provider", { pkg: model.api.npm })
826
+ installedPath = model.api.npm
827
+ }
828
+
829
+ const mod = await import(installedPath)
830
+
831
+ const fn = mod[Object.keys(mod).find((key) => key.startsWith("create"))!]
832
+ const loaded = fn({
833
+ name: model.providerID,
834
+ ...options,
835
+ })
836
+ s.sdk.set(key, loaded)
837
+ return loaded as SDK
838
+ } catch (e) {
839
+ throw new InitError({ providerID: model.providerID }, { cause: e })
840
+ }
841
+ }
842
+
843
+ export async function getProvider(providerID: string) {
844
+ return state().then((s) => s.providers[providerID])
845
+ }
846
+
847
+ export async function getModel(providerID: string, modelID: string) {
848
+ const s = await state()
849
+ const provider = s.providers[providerID]
850
+ if (!provider) {
851
+ const availableProviders = Object.keys(s.providers)
852
+ const matches = fuzzysort.go(providerID, availableProviders, { limit: 3, threshold: -10000 })
853
+ const suggestions = matches.map((m) => m.target)
854
+ throw new ModelNotFoundError({ providerID, modelID, suggestions })
855
+ }
856
+
857
+ const info = provider.models[modelID]
858
+ if (!info) {
859
+ const availableModels = Object.keys(provider.models)
860
+ const matches = fuzzysort.go(modelID, availableModels, { limit: 3, threshold: -10000 })
861
+ const suggestions = matches.map((m) => m.target)
862
+ throw new ModelNotFoundError({ providerID, modelID, suggestions })
863
+ }
864
+ return info
865
+ }
866
+
867
+ export async function getLanguage(model: Model) {
868
+ const s = await state()
869
+ const key = `${model.providerID}/${model.id}`
870
+ if (s.models.has(key)) return s.models.get(key)!
871
+
872
+ const provider = s.providers[model.providerID]
873
+ const sdk = await getSDK(model)
874
+
875
+ try {
876
+ const language = s.modelLoaders[model.providerID]
877
+ ? await s.modelLoaders[model.providerID](sdk, model.api.id, provider.options)
878
+ : sdk.languageModel(model.api.id)
879
+ s.models.set(key, language)
880
+ return language
881
+ } catch (e) {
882
+ if (e instanceof NoSuchModelError)
883
+ throw new ModelNotFoundError(
884
+ {
885
+ modelID: model.id,
886
+ providerID: model.providerID,
887
+ },
888
+ { cause: e },
889
+ )
890
+ throw e
891
+ }
892
+ }
893
+
894
+ export async function closest(providerID: string, query: string[]) {
895
+ const s = await state()
896
+ const provider = s.providers[providerID]
897
+ if (!provider) return undefined
898
+ for (const item of query) {
899
+ for (const modelID of Object.keys(provider.models)) {
900
+ if (modelID.includes(item))
901
+ return {
902
+ providerID,
903
+ modelID,
904
+ }
905
+ }
906
+ }
907
+ }
908
+
909
+ export async function getSmallModel(providerID: string) {
910
+ const cfg = await Config.get()
911
+
912
+ if (cfg.small_model) {
913
+ const parsed = parseModel(cfg.small_model)
914
+ return getModel(parsed.providerID, parsed.modelID)
915
+ }
916
+
917
+ const provider = await state().then((state) => state.providers[providerID])
918
+ if (provider) {
919
+ let priority = [
920
+ "claude-haiku-4-5",
921
+ "claude-haiku-4.5",
922
+ "3-5-haiku",
923
+ "3.5-haiku",
924
+ "gemini-2.5-flash",
925
+ "gpt-5-nano",
926
+ ]
927
+ // claude-haiku-4.5 is considered a premium model in github copilot, we shouldn't use premium requests for title gen
928
+ if (providerID === "github-copilot") {
929
+ priority = priority.filter((m) => m !== "claude-haiku-4.5")
930
+ }
931
+ if (providerID.startsWith("opencode")) {
932
+ priority = ["gpt-5-nano"]
933
+ }
934
+ for (const item of priority) {
935
+ for (const model of Object.keys(provider.models)) {
936
+ if (model.includes(item)) return getModel(providerID, model)
937
+ }
938
+ }
939
+ }
940
+
941
+ // Check if Cerebras provider is available before using it (Cerebras Code CLI default)
942
+ const cerebrasProvider = await state().then((state) => state.providers["cerebras"])
943
+ if (cerebrasProvider && cerebrasProvider.models["zai-glm-4.7"]) {
944
+ return getModel("cerebras", "zai-glm-4.7")
945
+ }
946
+
947
+ // Fallback to opencode provider
948
+ const opencodeProvider = await state().then((state) => state.providers["opencode"])
949
+ if (opencodeProvider && opencodeProvider.models["gpt-5-nano"]) {
950
+ return getModel("opencode", "gpt-5-nano")
951
+ }
952
+
953
+ return undefined
954
+ }
955
+
956
+ const priority = ["zai-glm-4.7", "gpt-5", "claude-sonnet-4", "big-pickle", "gemini-3-pro"]
957
+ export function sort(models: Model[]) {
958
+ return sortBy(
959
+ models,
960
+ [(model) => priority.findIndex((filter) => model.id.includes(filter)), "desc"],
961
+ [(model) => (model.id.includes("latest") ? 0 : 1), "asc"],
962
+ [(model) => model.id, "desc"],
963
+ )
964
+ }
965
+
966
+ export async function defaultModel() {
967
+ const cfg = await Config.get()
968
+ if (cfg.model) return parseModel(cfg.model)
969
+
970
+ const provider = await list()
971
+ .then((val) => Object.values(val))
972
+ .then((x) => x.find((p) => !cfg.provider || Object.keys(cfg.provider).includes(p.id)))
973
+ if (!provider) throw new Error("no providers found")
974
+ const [model] = sort(Object.values(provider.models))
975
+ if (!model) throw new Error("no models found")
976
+ return {
977
+ providerID: provider.id,
978
+ modelID: model.id,
979
+ }
980
+ }
981
+
982
+ export function parseModel(model: string) {
983
+ const [providerID, ...rest] = model.split("/")
984
+ return {
985
+ providerID: providerID,
986
+ modelID: rest.join("/"),
987
+ }
988
+ }
989
+
990
+ export const ModelNotFoundError = NamedError.create(
991
+ "ProviderModelNotFoundError",
992
+ z.object({
993
+ providerID: z.string(),
994
+ modelID: z.string(),
995
+ suggestions: z.array(z.string()).optional(),
996
+ }),
997
+ )
998
+
999
+ export const InitError = NamedError.create(
1000
+ "ProviderInitError",
1001
+ z.object({
1002
+ providerID: z.string(),
1003
+ }),
1004
+ )
1005
+ }