innocode 1.0.0

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