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