nikcli 0.0.6

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