easc-cli 1.1.28

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