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,1760 @@
1
+ import { Log } from "../util/log"
2
+ import path from "path"
3
+ import { pathToFileURL } from "url"
4
+ import { createRequire } from "module"
5
+ import os from "os"
6
+ import z from "zod"
7
+ import { Filesystem } from "../util/filesystem"
8
+ import { ModelsDev } from "../provider/models"
9
+ import { mergeDeep, pipe, unique } from "remeda"
10
+ import { Global } from "../global"
11
+ import fs from "fs/promises"
12
+ import { lazy } from "../util/lazy"
13
+ import { NamedError } from "@nikcli-ai/util/error"
14
+ import { Flag } from "../flag/flag"
15
+ import { Auth } from "../auth"
16
+ import {
17
+ type ParseError as JsoncParseError,
18
+ applyEdits,
19
+ modify,
20
+ parse as parseJsonc,
21
+ printParseErrorCode,
22
+ } from "jsonc-parser"
23
+ import { Instance } from "../project/instance"
24
+ import { LSPServer } from "../lsp/server"
25
+ import { BunProc } from "@/bun"
26
+ import { Installation } from "@/installation"
27
+ import { ConfigMarkdown } from "./markdown"
28
+ import { existsSync } from "fs"
29
+ import { Bus } from "@/bus"
30
+ import { GlobalBus } from "@/bus/global"
31
+ import { Event } from "../server/event"
32
+
33
+ export namespace Config {
34
+ const log = Log.create({ service: "config" })
35
+
36
+ // PluginSpec: string or [string, options] tuple
37
+ const _PluginOptions = z.record(z.string(), z.unknown())
38
+ export const PluginSpec = z.union([z.string(), z.tuple([z.string(), _PluginOptions])])
39
+ export type PluginOptions = z.infer<typeof _PluginOptions>
40
+ export type PluginSpec = z.infer<typeof PluginSpec>
41
+
42
+ function systemManagedConfigDir(): string {
43
+ switch (process.platform) {
44
+ case "darwin":
45
+ return "/Library/Application Support/nikcli"
46
+ case "win32":
47
+ return path.join(process.env.ProgramData || "C:\\ProgramData", "nikcli")
48
+ default:
49
+ return "/etc/nikcli"
50
+ }
51
+ }
52
+
53
+ export function managedConfigDir() {
54
+ return process.env["NIKCLI_TEST_MANAGED_CONFIG_DIR"] || systemManagedConfigDir()
55
+ }
56
+
57
+ export function pluginSpecifier(plugin: PluginSpec): string {
58
+ return Array.isArray(plugin) ? plugin[0] : plugin
59
+ }
60
+
61
+ export function pluginOptions(plugin: PluginSpec): PluginOptions | undefined {
62
+ return Array.isArray(plugin) ? (plugin[1] as PluginOptions) : undefined
63
+ }
64
+
65
+ export async function resolvePluginSpec(plugin: PluginSpec, configFilepath: string): Promise<PluginSpec> {
66
+ const { isPathPluginSpec, resolvePathPluginTarget } = await import("../plugin/shared")
67
+ const spec = pluginSpecifier(plugin)
68
+ if (!isPathPluginSpec(spec)) return plugin
69
+ if (spec.startsWith("file://")) {
70
+ const resolved = await resolvePathPluginTarget(spec).catch(() => spec)
71
+ if (Array.isArray(plugin)) return [resolved, plugin[1]]
72
+ return resolved
73
+ }
74
+ if (path.isAbsolute(spec) || /^[A-Za-z]:[\\/]/.test(spec)) {
75
+ const base = pathToFileURL(spec).href
76
+ const resolved = await resolvePathPluginTarget(base).catch(() => base)
77
+ if (Array.isArray(plugin)) return [resolved, plugin[1]]
78
+ return resolved
79
+ }
80
+ try {
81
+ const base = import.meta.resolve!(spec, configFilepath)
82
+ const resolved = await resolvePathPluginTarget(base).catch(() => base)
83
+ if (Array.isArray(plugin)) return [resolved, plugin[1]]
84
+ return resolved
85
+ } catch {
86
+ try {
87
+ const require = createRequire(configFilepath)
88
+ const base = pathToFileURL(require.resolve(spec)).href
89
+ const resolved = await resolvePathPluginTarget(base).catch(() => base)
90
+ if (Array.isArray(plugin)) return [resolved, plugin[1]]
91
+ return resolved
92
+ } catch {
93
+ return plugin
94
+ }
95
+ }
96
+ }
97
+
98
+ // Custom merge function that concatenates array fields instead of replacing them
99
+ function mergeConfigConcatArrays(target: Info, source: Info): Info {
100
+ const merged = mergeDeep(target, source)
101
+ if (target.plugin && source.plugin) {
102
+ merged.plugin = Array.from(new Set([...target.plugin, ...source.plugin]))
103
+ }
104
+ if (target.instructions && source.instructions) {
105
+ merged.instructions = Array.from(new Set([...target.instructions, ...source.instructions]))
106
+ }
107
+ return merged
108
+ }
109
+
110
+ export const state = Instance.state(async () => {
111
+ const auth = await Auth.all()
112
+
113
+ // Load remote/well-known config first as the base layer (lowest precedence)
114
+ // This allows organizations to provide default configs that users can override
115
+ let result: Info = {}
116
+ for (const [key, value] of Object.entries(auth)) {
117
+ if (value.type === "wellknown") {
118
+ process.env[value.key] = value.token
119
+ log.debug("fetching remote config", { url: `${key}/.well-known/nikcli` })
120
+ const response = await fetch(`${key}/.well-known/nikcli`)
121
+ if (!response.ok) {
122
+ throw new Error(`failed to fetch remote config from ${key}: ${response.status}`)
123
+ }
124
+ const wellknown = (await response.json()) as any
125
+ const remoteConfig = wellknown.config ?? {}
126
+ // Add $schema to prevent load() from trying to write back to a non-existent file
127
+ if (!remoteConfig.$schema) remoteConfig.$schema = "https://nikcli.store/config.json"
128
+ result = mergeConfigConcatArrays(result, await load(JSON.stringify(remoteConfig), `${key}/.well-known/nikcli`))
129
+ log.debug("loaded remote config from well-known", { url: key })
130
+ }
131
+ }
132
+
133
+ // Global user config overrides remote config
134
+ result = mergeConfigConcatArrays(result, await global())
135
+
136
+ // Custom config path overrides global
137
+ if (Flag.NIKCLI_CONFIG) {
138
+ result = mergeConfigConcatArrays(result, await loadFile(Flag.NIKCLI_CONFIG))
139
+ log.debug("loaded custom config", { path: Flag.NIKCLI_CONFIG })
140
+ }
141
+
142
+ // Project config has highest precedence (overrides global and remote)
143
+ if (!Flag.NIKCLI_DISABLE_PROJECT_CONFIG) {
144
+ for (const file of ["nikcli.jsonc", "nikcli.json", "config.json"]) {
145
+ const found = await Filesystem.findUp(file, Instance.directory, Instance.worktree)
146
+ for (const resolved of found.toReversed()) {
147
+ result = mergeConfigConcatArrays(result, await loadFile(resolved))
148
+ }
149
+ }
150
+ }
151
+
152
+ // Inline config content has highest precedence
153
+ if (Flag.NIKCLI_CONFIG_CONTENT) {
154
+ result = mergeConfigConcatArrays(result, JSON.parse(Flag.NIKCLI_CONFIG_CONTENT))
155
+ log.debug("loaded custom config from NIKCLI_CONFIG_CONTENT")
156
+ }
157
+
158
+ result.agent = result.agent || {}
159
+ result.mode = result.mode || {}
160
+ result.plugin = result.plugin || []
161
+
162
+ const directories = [
163
+ Global.Path.config,
164
+ // Only scan project .nikcli/ directories when project discovery is enabled
165
+ ...(!Flag.NIKCLI_DISABLE_PROJECT_CONFIG
166
+ ? await Array.fromAsync(
167
+ Filesystem.up({
168
+ targets: [".nikcli"],
169
+ start: Instance.directory,
170
+ stop: Instance.worktree,
171
+ }),
172
+ )
173
+ : []),
174
+ // Always scan ~/.nikcli/ (user home directory)
175
+ ...(await Array.fromAsync(
176
+ Filesystem.up({
177
+ targets: [".nikcli"],
178
+ start: Global.Path.home,
179
+ stop: Global.Path.home,
180
+ }),
181
+ )),
182
+ ]
183
+
184
+ if (Flag.NIKCLI_CONFIG_DIR) {
185
+ directories.push(Flag.NIKCLI_CONFIG_DIR)
186
+ log.debug("loading config from NIKCLI_CONFIG_DIR", { path: Flag.NIKCLI_CONFIG_DIR })
187
+ }
188
+
189
+ for (const dir of unique(directories)) {
190
+ if (dir.endsWith(".nikcli") || dir === Flag.NIKCLI_CONFIG_DIR) {
191
+ for (const file of ["config.json", "nikcli.jsonc", "nikcli.json"]) {
192
+ log.debug(`loading config from ${path.join(dir, file)}`)
193
+ result = mergeConfigConcatArrays(result, await loadFile(path.join(dir, file)))
194
+ // to satisfy the type checker
195
+ result.agent ??= {}
196
+ result.mode ??= {}
197
+ result.plugin ??= []
198
+ }
199
+ }
200
+
201
+ const exists = existsSync(path.join(dir, "node_modules"))
202
+ const installing = installDependencies(dir)
203
+ if (!exists) await installing
204
+
205
+ result.command = mergeDeep(result.command ?? {}, await loadCommand(dir))
206
+ result.agent = mergeDeep(result.agent, await loadAgent(dir))
207
+ result.agent = mergeDeep(result.agent, await loadMode(dir))
208
+ result.plugin.push(...(await loadPlugin(dir)))
209
+ }
210
+
211
+ // Migrate deprecated mode field to agent field
212
+ for (const [name, mode] of Object.entries(result.mode)) {
213
+ result.agent = mergeDeep(result.agent ?? {}, {
214
+ [name]: {
215
+ ...mode,
216
+ mode: "primary" as const,
217
+ },
218
+ })
219
+ }
220
+
221
+ if (Flag.NIKCLI_PERMISSION) {
222
+ result.permission = mergeDeep(result.permission ?? {}, JSON.parse(Flag.NIKCLI_PERMISSION))
223
+ }
224
+
225
+ // Backwards compatibility: legacy top-level `tools` config
226
+ if (result.tools) {
227
+ const perms: Record<string, Config.PermissionAction> = {}
228
+ for (const [tool, enabled] of Object.entries(result.tools)) {
229
+ const action: Config.PermissionAction = enabled ? "allow" : "deny"
230
+ if (tool === "write" || tool === "edit" || tool === "patch" || tool === "multiedit") {
231
+ perms.edit = action
232
+ continue
233
+ }
234
+ perms[tool] = action
235
+ }
236
+ result.permission = mergeDeep(perms, result.permission ?? {})
237
+ }
238
+
239
+ if (!result.username) result.username = os.userInfo().username
240
+
241
+ // Handle migration from autoshare to share field
242
+ if (result.autoshare === true && !result.share) {
243
+ result.share = "auto"
244
+ }
245
+
246
+ if (!result.keybinds) result.keybinds = Info.shape.keybinds.parse({})
247
+
248
+ // Apply flag overrides for compaction settings
249
+ if (Flag.NIKCLI_DISABLE_AUTOCOMPACT) {
250
+ result.compaction = { ...result.compaction, auto: false }
251
+ }
252
+ if (Flag.NIKCLI_DISABLE_PRUNE) {
253
+ result.compaction = { ...result.compaction, prune: false }
254
+ }
255
+
256
+ result.plugin = deduplicatePlugins(result.plugin ?? [])
257
+
258
+ return {
259
+ config: result,
260
+ directories,
261
+ }
262
+ })
263
+
264
+ export async function installDependencies(dir: string) {
265
+ const pkg = path.join(dir, "package.json")
266
+
267
+ if (!(await Bun.file(pkg).exists())) {
268
+ await Bun.write(pkg, "{}")
269
+ }
270
+
271
+ const gitignore = path.join(dir, ".gitignore")
272
+ const hasGitIgnore = await Bun.file(gitignore).exists()
273
+ if (!hasGitIgnore) await Bun.write(gitignore, ["node_modules", "package.json", "bun.lock", ".gitignore"].join("\n"))
274
+
275
+ await BunProc.run(
276
+ ["add", "@nikcli-ai/plugin@" + (Installation.isLocal() ? "latest" : Installation.VERSION), "--exact"],
277
+ {
278
+ cwd: dir,
279
+ },
280
+ ).catch(() => {})
281
+
282
+ // Install any additional dependencies defined in the package.json
283
+ // This allows local plugins and custom tools to use external packages
284
+ await BunProc.run(["install"], { cwd: dir }).catch(() => {})
285
+ }
286
+
287
+ function rel(item: string, patterns: string[]) {
288
+ for (const pattern of patterns) {
289
+ const index = item.indexOf(pattern)
290
+ if (index === -1) continue
291
+ return item.slice(index + pattern.length)
292
+ }
293
+ }
294
+
295
+ function trim(file: string) {
296
+ const ext = path.extname(file)
297
+ return ext.length ? file.slice(0, -ext.length) : file
298
+ }
299
+
300
+ const COMMAND_GLOB = new Bun.Glob("{command,commands}/**/*.md")
301
+ async function loadCommand(dir: string) {
302
+ const result: Record<string, Command> = {}
303
+ for await (const item of COMMAND_GLOB.scan({
304
+ absolute: true,
305
+ followSymlinks: true,
306
+ dot: true,
307
+ cwd: dir,
308
+ })) {
309
+ const md = await ConfigMarkdown.parse(item).catch(async (err) => {
310
+ const message = ConfigMarkdown.FrontmatterError.isInstance(err)
311
+ ? err.data.message
312
+ : `Failed to parse command ${item}`
313
+ const { Session } = await import("@/session")
314
+ Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })
315
+ log.error("failed to load command", { command: item, err })
316
+ return undefined
317
+ })
318
+ if (!md) continue
319
+
320
+ const patterns = ["/.nikcli/command/", "/.nikcli/commands/", "/command/", "/commands/"]
321
+ const file = rel(item, patterns) ?? path.basename(item)
322
+ const name = trim(file)
323
+
324
+ const config = {
325
+ name,
326
+ ...md.data,
327
+ template: md.content.trim(),
328
+ }
329
+ const parsed = Command.safeParse(config)
330
+ if (parsed.success) {
331
+ result[config.name] = parsed.data
332
+ continue
333
+ }
334
+ throw new InvalidError({ path: item, issues: parsed.error.issues }, { cause: parsed.error })
335
+ }
336
+ return result
337
+ }
338
+
339
+ const AGENT_GLOB = new Bun.Glob("{agent,agents}/**/*.md")
340
+ async function loadAgent(dir: string) {
341
+ const result: Record<string, Agent> = {}
342
+
343
+ for await (const item of AGENT_GLOB.scan({
344
+ absolute: true,
345
+ followSymlinks: true,
346
+ dot: true,
347
+ cwd: dir,
348
+ })) {
349
+ const md = await ConfigMarkdown.parse(item).catch(async (err) => {
350
+ const message = ConfigMarkdown.FrontmatterError.isInstance(err)
351
+ ? err.data.message
352
+ : `Failed to parse agent ${item}`
353
+ const { Session } = await import("@/session")
354
+ Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })
355
+ log.error("failed to load agent", { agent: item, err })
356
+ return undefined
357
+ })
358
+ if (!md) continue
359
+
360
+ const patterns = ["/.nikcli/agent/", "/.nikcli/agents/", "/agent/", "/agents/"]
361
+ const file = rel(item, patterns) ?? path.basename(item)
362
+ const agentName = trim(file)
363
+
364
+ const config = {
365
+ name: agentName,
366
+ ...md.data,
367
+ prompt: md.content.trim(),
368
+ }
369
+ const parsed = Agent.safeParse(config)
370
+ if (parsed.success) {
371
+ result[config.name] = parsed.data
372
+ continue
373
+ }
374
+ throw new InvalidError({ path: item, issues: parsed.error.issues }, { cause: parsed.error })
375
+ }
376
+ return result
377
+ }
378
+
379
+ const MODE_GLOB = new Bun.Glob("{mode,modes}/*.md")
380
+ async function loadMode(dir: string) {
381
+ const result: Record<string, Agent> = {}
382
+ for await (const item of MODE_GLOB.scan({
383
+ absolute: true,
384
+ followSymlinks: true,
385
+ dot: true,
386
+ cwd: dir,
387
+ })) {
388
+ const md = await ConfigMarkdown.parse(item).catch(async (err) => {
389
+ const message = ConfigMarkdown.FrontmatterError.isInstance(err)
390
+ ? err.data.message
391
+ : `Failed to parse mode ${item}`
392
+ const { Session } = await import("@/session")
393
+ Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })
394
+ log.error("failed to load mode", { mode: item, err })
395
+ return undefined
396
+ })
397
+ if (!md) continue
398
+
399
+ const config = {
400
+ name: path.basename(item, ".md"),
401
+ ...md.data,
402
+ prompt: md.content.trim(),
403
+ }
404
+ const parsed = Agent.safeParse(config)
405
+ if (parsed.success) {
406
+ result[config.name] = {
407
+ ...parsed.data,
408
+ mode: "primary" as const,
409
+ }
410
+ continue
411
+ }
412
+ }
413
+ return result
414
+ }
415
+
416
+ const PLUGIN_GLOB = new Bun.Glob("{plugin,plugins}/*.{ts,js}")
417
+ async function loadPlugin(dir: string) {
418
+ const plugins: string[] = []
419
+
420
+ for await (const item of PLUGIN_GLOB.scan({
421
+ absolute: true,
422
+ followSymlinks: true,
423
+ dot: true,
424
+ cwd: dir,
425
+ })) {
426
+ plugins.push(pathToFileURL(item).href)
427
+ }
428
+ return plugins
429
+ }
430
+
431
+ /**
432
+ * Extracts a canonical plugin name from a plugin specifier.
433
+ * - For file:// URLs: extracts filename without extension
434
+ * - For npm packages: extracts package name without version
435
+ *
436
+ * @example
437
+ * getPluginName("file:///path/to/plugin/foo.js") // "foo"
438
+ * getPluginName("oh-my-nikcli@2.4.3") // "oh-my-nikcli"
439
+ * getPluginName("@scope/pkg@1.0.0") // "@scope/pkg"
440
+ */
441
+ export function getPluginName(plugin: string): string {
442
+ if (plugin.startsWith("file://")) {
443
+ return path.parse(new URL(plugin).pathname).name
444
+ }
445
+ const lastAt = plugin.lastIndexOf("@")
446
+ if (lastAt > 0) {
447
+ return plugin.substring(0, lastAt)
448
+ }
449
+ return plugin
450
+ }
451
+
452
+ /**
453
+ * Deduplicates plugins by name, with later entries (higher priority) winning.
454
+ * Priority order (highest to lowest):
455
+ * 1. Local plugin/ directory
456
+ * 2. Local nikcli.json
457
+ * 3. Global plugin/ directory
458
+ * 4. Global nikcli.json
459
+ *
460
+ * Since plugins are added in low-to-high priority order,
461
+ * we reverse, deduplicate (keeping first occurrence), then restore order.
462
+ */
463
+ export function deduplicatePlugins(plugins: string[]): string[] {
464
+ // seenNames: canonical plugin names for duplicate detection
465
+ // e.g., "oh-my-nikcli", "@scope/pkg"
466
+ const seenNames = new Set<string>()
467
+
468
+ // uniqueSpecifiers: full plugin specifiers to return
469
+ // e.g., "oh-my-nikcli@2.4.3", "file:///path/to/plugin.js"
470
+ const uniqueSpecifiers: string[] = []
471
+
472
+ for (const specifier of plugins.toReversed()) {
473
+ const name = getPluginName(specifier)
474
+ if (!seenNames.has(name)) {
475
+ seenNames.add(name)
476
+ uniqueSpecifiers.push(specifier)
477
+ }
478
+ }
479
+
480
+ return uniqueSpecifiers.toReversed()
481
+ }
482
+
483
+ export const McpLocal = z
484
+ .object({
485
+ type: z.literal("local").describe("Type of MCP server connection"),
486
+ command: z.string().array().describe("Command and arguments to run the MCP server"),
487
+ environment: z
488
+ .record(z.string(), z.string())
489
+ .optional()
490
+ .describe("Environment variables to set when running the MCP server"),
491
+ enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"),
492
+ timeout: z
493
+ .number()
494
+ .int()
495
+ .positive()
496
+ .optional()
497
+ .describe("Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."),
498
+ })
499
+ .strict()
500
+ .meta({
501
+ ref: "McpLocalConfig",
502
+ })
503
+
504
+ export const McpOAuth = z
505
+ .object({
506
+ clientId: z
507
+ .string()
508
+ .optional()
509
+ .describe("OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted."),
510
+ clientSecret: z.string().optional().describe("OAuth client secret (if required by the authorization server)"),
511
+ scope: z.string().optional().describe("OAuth scopes to request during authorization"),
512
+ })
513
+ .strict()
514
+ .meta({
515
+ ref: "McpOAuthConfig",
516
+ })
517
+ export type McpOAuth = z.infer<typeof McpOAuth>
518
+
519
+ export const McpRemote = z
520
+ .object({
521
+ type: z.literal("remote").describe("Type of MCP server connection"),
522
+ url: z.string().describe("URL of the remote MCP server"),
523
+ enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"),
524
+ headers: z.record(z.string(), z.string()).optional().describe("Headers to send with the request"),
525
+ oauth: z
526
+ .union([McpOAuth, z.literal(false)])
527
+ .optional()
528
+ .describe(
529
+ "OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection.",
530
+ ),
531
+ timeout: z
532
+ .number()
533
+ .int()
534
+ .positive()
535
+ .optional()
536
+ .describe("Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."),
537
+ })
538
+ .strict()
539
+ .meta({
540
+ ref: "McpRemoteConfig",
541
+ })
542
+
543
+ export const Mcp = z.discriminatedUnion("type", [McpLocal, McpRemote])
544
+ export type Mcp = z.infer<typeof Mcp>
545
+
546
+ export const ConnectorFigma = z
547
+ .object({
548
+ type: z.literal("figma"),
549
+ token: z.string().optional().describe("Figma personal access token"),
550
+ enabled: z.boolean().optional(),
551
+ })
552
+ .strict()
553
+ .meta({ ref: "ConnectorFigma" })
554
+ export type ConnectorFigma = z.infer<typeof ConnectorFigma>
555
+
556
+ export const ConnectorSlack = z
557
+ .object({
558
+ type: z.literal("slack"),
559
+ botToken: z.string().optional().describe("Slack bot token"),
560
+ teamId: z.string().optional().describe("Slack team ID"),
561
+ enabled: z.boolean().optional(),
562
+ })
563
+ .strict()
564
+ .meta({ ref: "ConnectorSlack" })
565
+ export type ConnectorSlack = z.infer<typeof ConnectorSlack>
566
+
567
+ export const ConnectorGithub = z
568
+ .object({
569
+ type: z.literal("github"),
570
+ token: z.string().optional().describe("GitHub personal access token"),
571
+ oauthClientId: z.string().optional().describe("GitHub OAuth client ID for mobile device flow"),
572
+ clientId: z.string().optional().describe("Alias for GitHub OAuth client ID"),
573
+ enabled: z.boolean().optional(),
574
+ })
575
+ .strict()
576
+ .meta({ ref: "ConnectorGithub" })
577
+ export type ConnectorGithub = z.infer<typeof ConnectorGithub>
578
+
579
+ export const ConnectorLovable = z
580
+ .object({
581
+ type: z.literal("lovable"),
582
+ token: z.string().optional().describe("Lovable API key"),
583
+ apiKey: z.string().optional().describe("Legacy Lovable API key"),
584
+ enabled: z.boolean().optional(),
585
+ })
586
+ .strict()
587
+ .meta({ ref: "ConnectorLovable" })
588
+ export type ConnectorLovable = z.infer<typeof ConnectorLovable>
589
+
590
+ export const ConnectorDiscord = z
591
+ .object({
592
+ type: z.literal("discord"),
593
+ botToken: z.string().optional().describe("Discord bot token"),
594
+ enabled: z.boolean().optional(),
595
+ })
596
+ .strict()
597
+ .meta({ ref: "ConnectorDiscord" })
598
+ export type ConnectorDiscord = z.infer<typeof ConnectorDiscord>
599
+
600
+ export const ConnectorTeams = z
601
+ .object({
602
+ type: z.literal("teams"),
603
+ botToken: z.string().optional().describe("Microsoft Teams bot token"),
604
+ enabled: z.boolean().optional(),
605
+ })
606
+ .strict()
607
+ .meta({ ref: "ConnectorTeams" })
608
+ export type ConnectorTeams = z.infer<typeof ConnectorTeams>
609
+
610
+ export const ConnectorGChat = z
611
+ .object({
612
+ type: z.literal("gchat"),
613
+ botToken: z.string().optional().describe("Google Chat bot token"),
614
+ enabled: z.boolean().optional(),
615
+ })
616
+ .strict()
617
+ .meta({ ref: "ConnectorGChat" })
618
+ export type ConnectorGChat = z.infer<typeof ConnectorGChat>
619
+
620
+ export const ConnectorLinear = z
621
+ .object({
622
+ type: z.literal("linear"),
623
+ botToken: z.string().optional().describe("Linear bot token"),
624
+ enabled: z.boolean().optional(),
625
+ })
626
+ .strict()
627
+ .meta({ ref: "ConnectorLinear" })
628
+ export type ConnectorLinear = z.infer<typeof ConnectorLinear>
629
+
630
+ export const Connector = z.discriminatedUnion("type", [
631
+ ConnectorFigma,
632
+ ConnectorSlack,
633
+ ConnectorGithub,
634
+ ConnectorLovable,
635
+ ConnectorDiscord,
636
+ ConnectorTeams,
637
+ ConnectorGChat,
638
+ ConnectorLinear,
639
+ ])
640
+ export type Connector = z.infer<typeof Connector>
641
+
642
+ export const PermissionAction = z.enum(["ask", "allow", "deny"]).meta({
643
+ ref: "PermissionActionConfig",
644
+ })
645
+ export type PermissionAction = z.infer<typeof PermissionAction>
646
+
647
+ export const PermissionObject = z.record(z.string(), PermissionAction).meta({
648
+ ref: "PermissionObjectConfig",
649
+ })
650
+ export type PermissionObject = z.infer<typeof PermissionObject>
651
+
652
+ export const PermissionRule = z.union([PermissionAction, PermissionObject]).meta({
653
+ ref: "PermissionRuleConfig",
654
+ })
655
+ export type PermissionRule = z.infer<typeof PermissionRule>
656
+
657
+ // Capture original key order before zod reorders, then rebuild in original order
658
+ const permissionPreprocess = (val: unknown) => {
659
+ if (typeof val === "object" && val !== null && !Array.isArray(val)) {
660
+ return { __originalKeys: Object.keys(val), ...val }
661
+ }
662
+ return val
663
+ }
664
+
665
+ const permissionTransform = (x: unknown): Record<string, PermissionRule> => {
666
+ if (typeof x === "string") return { "*": x as PermissionAction }
667
+ const obj = x as { __originalKeys?: string[] } & Record<string, unknown>
668
+ const { __originalKeys, ...rest } = obj
669
+ if (!__originalKeys) return rest as Record<string, PermissionRule>
670
+ const result: Record<string, PermissionRule> = {}
671
+ for (const key of __originalKeys) {
672
+ if (key in rest) result[key] = rest[key] as PermissionRule
673
+ }
674
+ return result
675
+ }
676
+
677
+ export const Permission = z
678
+ .preprocess(
679
+ permissionPreprocess,
680
+ z
681
+ .object({
682
+ __originalKeys: z.string().array().optional(),
683
+ read: PermissionRule.optional(),
684
+ edit: PermissionRule.optional(),
685
+ glob: PermissionRule.optional(),
686
+ grep: PermissionRule.optional(),
687
+ list: PermissionRule.optional(),
688
+ tree: PermissionRule.optional(),
689
+ bash: PermissionRule.optional(),
690
+ task: PermissionRule.optional(),
691
+ subagents: PermissionRule.optional(),
692
+ docs_add: PermissionRule.optional(),
693
+ docs_search: PermissionRule.optional(),
694
+ docs_load: PermissionRule.optional(),
695
+ docs_unload: PermissionRule.optional(),
696
+ docs_context: PermissionRule.optional(),
697
+ docs_request: PermissionRule.optional(),
698
+ docs_gap_report: PermissionRule.optional(),
699
+ smart_docs: PermissionRule.optional(),
700
+ context_collect: PermissionRule.optional(),
701
+ context_search: PermissionRule.optional(),
702
+ context_related: PermissionRule.optional(),
703
+ context_diagnostics: PermissionRule.optional(),
704
+ memory_search: PermissionRule.optional(),
705
+ rag_index: PermissionRule.optional(),
706
+ rag_search: PermissionRule.optional(),
707
+ rag_status: PermissionRule.optional(),
708
+ rag_reset: PermissionRule.optional(),
709
+ generate_image: PermissionRule.optional(),
710
+ external_directory: PermissionRule.optional(),
711
+ todowrite: PermissionAction.optional(),
712
+ todoread: PermissionAction.optional(),
713
+ question: PermissionAction.optional(),
714
+ webfetch: PermissionAction.optional(),
715
+ websearch: PermissionAction.optional(),
716
+ codesearch: PermissionAction.optional(),
717
+ speak: PermissionRule.optional(),
718
+ lsp: PermissionRule.optional(),
719
+ doom_loop: PermissionAction.optional(),
720
+ })
721
+ .catchall(PermissionRule)
722
+ .or(PermissionAction),
723
+ )
724
+ .transform(permissionTransform)
725
+ .meta({
726
+ ref: "PermissionConfig",
727
+ })
728
+ export type Permission = z.infer<typeof Permission>
729
+
730
+ export const Command = z.object({
731
+ template: z.string(),
732
+ description: z.string().optional(),
733
+ agent: z.string().optional(),
734
+ model: z.string().optional(),
735
+ subtask: z.boolean().optional(),
736
+ })
737
+ export type Command = z.infer<typeof Command>
738
+
739
+ export const Agent = z
740
+ .object({
741
+ model: z.string().optional(),
742
+ variant: z
743
+ .string()
744
+ .optional()
745
+ .describe("Default model variant for this agent (applies only when using the agent's configured model)."),
746
+ temperature: z.number().optional(),
747
+ top_p: z.number().optional(),
748
+ prompt: z.string().optional(),
749
+ tools: z.record(z.string(), z.boolean()).optional().describe("@deprecated Use 'permission' field instead"),
750
+ disable: z.boolean().optional(),
751
+ description: z.string().optional().describe("Description of when to use the agent"),
752
+ mode: z.enum(["subagent", "primary", "all"]).optional(),
753
+ hidden: z
754
+ .boolean()
755
+ .optional()
756
+ .describe("Hide this subagent from the @ autocomplete menu (default: false, only applies to mode: subagent)"),
757
+ options: z.record(z.string(), z.any()).optional(),
758
+ color: z
759
+ .string()
760
+ .regex(/^#[0-9a-fA-F]{6}$/, "Invalid hex color format")
761
+ .optional()
762
+ .describe("Hex color code for the agent (e.g., #FF5733)"),
763
+ steps: z
764
+ .number()
765
+ .int()
766
+ .positive()
767
+ .optional()
768
+ .describe("Maximum number of agentic iterations before forcing text-only response"),
769
+ maxSteps: z.number().int().positive().optional().describe("@deprecated Use 'steps' field instead."),
770
+ permission: Permission.optional(),
771
+ })
772
+ .catchall(z.any())
773
+ .transform((agent, ctx) => {
774
+ const knownKeys = new Set([
775
+ "name",
776
+ "model",
777
+ "variant",
778
+ "prompt",
779
+ "description",
780
+ "temperature",
781
+ "top_p",
782
+ "mode",
783
+ "hidden",
784
+ "color",
785
+ "steps",
786
+ "maxSteps",
787
+ "options",
788
+ "permission",
789
+ "disable",
790
+ "tools",
791
+ ])
792
+
793
+ // Extract unknown properties into options
794
+ const options: Record<string, unknown> = { ...agent.options }
795
+ for (const [key, value] of Object.entries(agent)) {
796
+ if (!knownKeys.has(key)) options[key] = value
797
+ }
798
+
799
+ // Convert legacy tools config to permissions
800
+ const permission: Permission = {}
801
+ for (const [tool, enabled] of Object.entries(agent.tools ?? {})) {
802
+ const action = enabled ? "allow" : "deny"
803
+ // write, edit, patch, multiedit all map to edit permission
804
+ if (tool === "write" || tool === "edit" || tool === "patch" || tool === "multiedit") {
805
+ permission.edit = action
806
+ } else {
807
+ permission[tool] = action
808
+ }
809
+ }
810
+ Object.assign(permission, agent.permission)
811
+
812
+ // Convert legacy maxSteps to steps
813
+ const steps = agent.steps ?? agent.maxSteps
814
+
815
+ return { ...agent, options, permission, steps } as typeof agent & {
816
+ options?: Record<string, unknown>
817
+ permission?: Permission
818
+ steps?: number
819
+ }
820
+ })
821
+ .meta({
822
+ ref: "AgentConfig",
823
+ })
824
+ export type Agent = z.infer<typeof Agent>
825
+
826
+ export const Keybinds = z
827
+ .object({
828
+ leader: z.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"),
829
+ app_exit: z.string().optional().default("ctrl+c,ctrl+d,<leader>q").describe("Exit the application"),
830
+ editor_open: z.string().optional().default("<leader>e").describe("Open external editor"),
831
+ theme_list: z.string().optional().default("<leader>t").describe("List available themes"),
832
+ sidebar_toggle: z.string().optional().default("<leader>b").describe("Toggle sidebar"),
833
+ scrollbar_toggle: z.string().optional().default("none").describe("Toggle session scrollbar"),
834
+ username_toggle: z.string().optional().default("none").describe("Toggle username visibility"),
835
+ status_view: z.string().optional().default("<leader>s").describe("View status"),
836
+ session_export: z.string().optional().default("<leader>x").describe("Export session to editor"),
837
+ session_new: z.string().optional().default("<leader>n").describe("Create a new session"),
838
+ session_list: z.string().optional().default("<leader>l").describe("List all sessions"),
839
+ session_timeline: z.string().optional().default("<leader>g").describe("Show session timeline"),
840
+ session_fork: z.string().optional().default("none").describe("Fork session from message"),
841
+ session_rename: z.string().optional().default("ctrl+r").describe("Rename session"),
842
+ session_delete: z.string().optional().default("ctrl+d").describe("Delete session"),
843
+ stash_delete: z.string().optional().default("ctrl+d").describe("Delete stash entry"),
844
+ model_provider_list: z.string().optional().default("ctrl+a").describe("Open provider list from model dialog"),
845
+ model_favorite_toggle: z.string().optional().default("ctrl+f").describe("Toggle model favorite status"),
846
+ session_share: z.string().optional().default("none").describe("Share current session"),
847
+ session_unshare: z.string().optional().default("none").describe("Unshare current session"),
848
+ session_interrupt: z.string().optional().default("escape").describe("Interrupt current session"),
849
+ subtask_background: z
850
+ .string()
851
+ .optional()
852
+ .default("ctrl+b")
853
+ .describe("Background current subtask and return to parent session"),
854
+ subtask_picker: z.string().optional().default("down").describe("Open background subtask picker"),
855
+ session_compact: z.string().optional().default("<leader>c").describe("Compact the session"),
856
+ messages_page_up: z.string().optional().default("pageup,ctrl+alt+b").describe("Scroll messages up by one page"),
857
+ messages_page_down: z
858
+ .string()
859
+ .optional()
860
+ .default("pagedown,ctrl+alt+f")
861
+ .describe("Scroll messages down by one page"),
862
+ messages_line_up: z.string().optional().default("ctrl+alt+y").describe("Scroll messages up by one line"),
863
+ messages_line_down: z.string().optional().default("ctrl+alt+e").describe("Scroll messages down by one line"),
864
+ messages_half_page_up: z.string().optional().default("ctrl+alt+u").describe("Scroll messages up by half page"),
865
+ messages_half_page_down: z
866
+ .string()
867
+ .optional()
868
+ .default("ctrl+alt+d")
869
+ .describe("Scroll messages down by half page"),
870
+ messages_first: z.string().optional().default("ctrl+g,home").describe("Navigate to first message"),
871
+ messages_last: z.string().optional().default("ctrl+alt+g,end").describe("Navigate to last message"),
872
+ messages_next: z.string().optional().default("none").describe("Navigate to next message"),
873
+ messages_previous: z.string().optional().default("none").describe("Navigate to previous message"),
874
+ messages_last_user: z.string().optional().default("none").describe("Navigate to last user message"),
875
+ messages_copy: z.string().optional().default("<leader>y").describe("Copy message"),
876
+ messages_undo: z.string().optional().default("<leader>u").describe("Undo message"),
877
+ messages_redo: z.string().optional().default("<leader>r").describe("Redo message"),
878
+ messages_toggle_conceal: z
879
+ .string()
880
+ .optional()
881
+ .default("<leader>h")
882
+ .describe("Toggle code block concealment in messages"),
883
+ tool_details: z.string().optional().default("none").describe("Toggle tool details visibility"),
884
+ model_list: z.string().optional().default("<leader>m").describe("List available models"),
885
+ model_cycle_recent: z.string().optional().default("f2").describe("Next recently used model"),
886
+ model_cycle_recent_reverse: z.string().optional().default("shift+f2").describe("Previous recently used model"),
887
+ model_cycle_favorite: z.string().optional().default("none").describe("Next favorite model"),
888
+ model_cycle_favorite_reverse: z.string().optional().default("none").describe("Previous favorite model"),
889
+ command_list: z.string().optional().default("ctrl+p").describe("List available commands"),
890
+ agent_list: z.string().optional().default("<leader>a").describe("List agents"),
891
+ agent_cycle: z.string().optional().default("tab").describe("Next agent"),
892
+ agent_cycle_reverse: z.string().optional().default("shift+tab").describe("Previous agent"),
893
+ variant_cycle: z.string().optional().default("ctrl+t").describe("Cycle model variants"),
894
+ input_clear: z.string().optional().default("ctrl+c").describe("Clear input field"),
895
+ input_paste: z.string().optional().default("ctrl+v").describe("Paste from clipboard"),
896
+ input_submit: z.string().optional().default("return").describe("Submit input"),
897
+ input_newline: z
898
+ .string()
899
+ .optional()
900
+ .default("shift+return,ctrl+return,alt+return,ctrl+j")
901
+ .describe("Insert newline in input"),
902
+ input_move_left: z.string().optional().default("left,ctrl+b").describe("Move cursor left in input"),
903
+ input_move_right: z.string().optional().default("right,ctrl+f").describe("Move cursor right in input"),
904
+ input_move_up: z.string().optional().default("up").describe("Move cursor up in input"),
905
+ input_move_down: z.string().optional().default("down").describe("Move cursor down in input"),
906
+ input_select_left: z.string().optional().default("shift+left").describe("Select left in input"),
907
+ input_select_right: z.string().optional().default("shift+right").describe("Select right in input"),
908
+ input_select_up: z.string().optional().default("shift+up").describe("Select up in input"),
909
+ input_select_down: z.string().optional().default("shift+down").describe("Select down in input"),
910
+ input_line_home: z.string().optional().default("ctrl+a").describe("Move to start of line in input"),
911
+ input_line_end: z.string().optional().default("ctrl+e").describe("Move to end of line in input"),
912
+ input_select_line_home: z
913
+ .string()
914
+ .optional()
915
+ .default("ctrl+shift+a")
916
+ .describe("Select to start of line in input"),
917
+ input_select_line_end: z.string().optional().default("ctrl+shift+e").describe("Select to end of line in input"),
918
+ input_visual_line_home: z.string().optional().default("alt+a").describe("Move to start of visual line in input"),
919
+ input_visual_line_end: z.string().optional().default("alt+e").describe("Move to end of visual line in input"),
920
+ input_select_visual_line_home: z
921
+ .string()
922
+ .optional()
923
+ .default("alt+shift+a")
924
+ .describe("Select to start of visual line in input"),
925
+ input_select_visual_line_end: z
926
+ .string()
927
+ .optional()
928
+ .default("alt+shift+e")
929
+ .describe("Select to end of visual line in input"),
930
+ input_buffer_home: z.string().optional().default("home").describe("Move to start of buffer in input"),
931
+ input_buffer_end: z.string().optional().default("end").describe("Move to end of buffer in input"),
932
+ input_select_buffer_home: z
933
+ .string()
934
+ .optional()
935
+ .default("shift+home")
936
+ .describe("Select to start of buffer in input"),
937
+ input_select_buffer_end: z.string().optional().default("shift+end").describe("Select to end of buffer in input"),
938
+ input_delete_line: z.string().optional().default("ctrl+shift+d").describe("Delete line in input"),
939
+ input_delete_to_line_end: z.string().optional().default("ctrl+k").describe("Delete to end of line in input"),
940
+ input_delete_to_line_start: z.string().optional().default("ctrl+u").describe("Delete to start of line in input"),
941
+ input_backspace: z.string().optional().default("backspace,shift+backspace").describe("Backspace in input"),
942
+ input_delete: z.string().optional().default("ctrl+d,delete,shift+delete").describe("Delete character in input"),
943
+ input_undo: z.string().optional().default("ctrl+-,super+z").describe("Undo in input"),
944
+ input_redo: z.string().optional().default("ctrl+.,super+shift+z").describe("Redo in input"),
945
+ input_word_forward: z
946
+ .string()
947
+ .optional()
948
+ .default("alt+f,alt+right,ctrl+right")
949
+ .describe("Move word forward in input"),
950
+ input_word_backward: z
951
+ .string()
952
+ .optional()
953
+ .default("alt+b,alt+left,ctrl+left")
954
+ .describe("Move word backward in input"),
955
+ input_select_word_forward: z
956
+ .string()
957
+ .optional()
958
+ .default("alt+shift+f,alt+shift+right")
959
+ .describe("Select word forward in input"),
960
+ input_select_word_backward: z
961
+ .string()
962
+ .optional()
963
+ .default("alt+shift+b,alt+shift+left")
964
+ .describe("Select word backward in input"),
965
+ input_delete_word_forward: z
966
+ .string()
967
+ .optional()
968
+ .default("alt+d,alt+delete,ctrl+delete")
969
+ .describe("Delete word forward in input"),
970
+ input_delete_word_backward: z
971
+ .string()
972
+ .optional()
973
+ .default("ctrl+w,ctrl+backspace,alt+backspace")
974
+ .describe("Delete word backward in input"),
975
+ history_previous: z.string().optional().default("up").describe("Previous history item"),
976
+ history_next: z.string().optional().default("down").describe("Next history item"),
977
+ session_child_cycle: z.string().optional().default("<leader>right").describe("Next child session"),
978
+ session_child_cycle_reverse: z.string().optional().default("<leader>left").describe("Previous child session"),
979
+ // NOTE: for subtasks we prefer `subtask_background` (ctrl+b) which also
980
+ // adds the child back to the background list. Keep this bound to ctrl+b
981
+ // so "Parent" in subagent sessions matches the behavior users expect.
982
+ session_parent: z.string().optional().default("ctrl+b").describe("Go to parent session"),
983
+ session_child_close: z.string().optional().default("<leader>c").describe("Close subagent session"),
984
+ terminal_suspend: z.string().optional().default("ctrl+z").describe("Suspend terminal"),
985
+ terminal_title_toggle: z.string().optional().default("none").describe("Toggle terminal title"),
986
+ tips_toggle: z.string().optional().default("<leader>h").describe("Toggle tips on home screen"),
987
+ voice_record: z.string().optional().default("ctrl+alt+v").describe("Toggle voice recording (push to talk)"),
988
+ })
989
+ .strict()
990
+ .meta({
991
+ ref: "KeybindsConfig",
992
+ })
993
+
994
+ export const TUI = z.object({
995
+ scroll_speed: z.number().min(0.001).optional().describe("TUI scroll speed"),
996
+ scroll_acceleration: z
997
+ .object({
998
+ enabled: z.boolean().describe("Enable scroll acceleration"),
999
+ })
1000
+ .optional()
1001
+ .describe("Scroll acceleration settings"),
1002
+ diff_style: z
1003
+ .enum(["auto", "stacked"])
1004
+ .optional()
1005
+ .describe("Control diff rendering style: 'auto' adapts to terminal width, 'stacked' always shows single column"),
1006
+ })
1007
+
1008
+ export const AdsItem = z
1009
+ .object({
1010
+ id: z.string().describe("Unique ad identifier"),
1011
+ text: z.string().describe("Ad message text"),
1012
+ url: z.string().url().optional().describe("Optional URL to show with the ad"),
1013
+ enabled: z.boolean().optional().describe("Enable this ad"),
1014
+ })
1015
+ .strict()
1016
+ .meta({
1017
+ ref: "AdsItemConfig",
1018
+ })
1019
+ export type AdsItem = z.infer<typeof AdsItem>
1020
+
1021
+ export const Ads = z
1022
+ .object({
1023
+ enabled: z.boolean().optional().describe("Enable ads in the TUI"),
1024
+ ratio: z.number().min(0).max(1).optional().describe("Chance to show an ad instead of a tip (0-1)"),
1025
+ items: z.array(AdsItem).optional().describe("User-defined ads"),
1026
+ })
1027
+ .strict()
1028
+ .meta({
1029
+ ref: "AdsConfig",
1030
+ })
1031
+ export type Ads = z.infer<typeof Ads>
1032
+
1033
+ export const Server = z
1034
+ .object({
1035
+ port: z.number().int().positive().optional().describe("Port to listen on"),
1036
+ hostname: z.string().optional().describe("Hostname to listen on"),
1037
+ mdns: z.boolean().optional().describe("Enable mDNS service discovery"),
1038
+ cors: z.array(z.string()).optional().describe("Additional domains to allow for CORS"),
1039
+ })
1040
+ .strict()
1041
+ .meta({
1042
+ ref: "ServerConfig",
1043
+ })
1044
+
1045
+ export const Remote = z
1046
+ .object({
1047
+ enabled: z.boolean().optional().describe("Enable Remote Control automatically for all TUI sessions"),
1048
+ enableTunnel: z.boolean().optional().describe("Enable public tunnel by default for Remote Control"),
1049
+ provider: z
1050
+ .enum(["localtunnel", "cloudflared", "ngrok", "remotosh", "none"])
1051
+ .optional()
1052
+ .describe("Preferred tunnel provider for Remote Control"),
1053
+ askOnExistingSession: z
1054
+ .boolean()
1055
+ .optional()
1056
+ .describe("Prompt to continue existing remote session or start a new one"),
1057
+ })
1058
+ .strict()
1059
+ .meta({
1060
+ ref: "RemoteConfig",
1061
+ })
1062
+ export type Remote = z.infer<typeof Remote>
1063
+
1064
+ export const Layout = z.enum(["auto", "stretch"]).meta({
1065
+ ref: "LayoutConfig",
1066
+ })
1067
+ export type Layout = z.infer<typeof Layout>
1068
+
1069
+ export const Rag = z
1070
+ .object({
1071
+ model: z.string().optional().describe("Embedding model for RAG (e.g., nvidia/llama-embed-nemotron-8b)"),
1072
+ provider: z.string().optional().describe("Provider for RAG embeddings (defaults to nvidia)"),
1073
+ })
1074
+ .strict()
1075
+ .meta({
1076
+ ref: "RagConfig",
1077
+ })
1078
+ export type Rag = z.infer<typeof Rag>
1079
+
1080
+ export const Image = z
1081
+ .object({
1082
+ model: z
1083
+ .string()
1084
+ .optional()
1085
+ .describe("Image generation model (e.g., openai/gpt-5-image, google/nano-banana-pro-2.5)"),
1086
+ provider: z.string().optional().describe("Provider for image generation (e.g., openrouter, openai, vercel)"),
1087
+ })
1088
+ .strict()
1089
+ .meta({
1090
+ ref: "ImageConfig",
1091
+ })
1092
+ export type Image = z.infer<typeof Image>
1093
+
1094
+ export const Speak = z
1095
+ .object({
1096
+ provider: z.string().optional().describe("TTS provider (e.g., elevenlabs, openrouter)"),
1097
+ model: z.string().optional().describe("TTS voice ID (e.g., ElevenLabs voice ID, OpenRouter voice name)"),
1098
+ modelId: z.string().optional().describe("TTS model ID (e.g., eleven_v3, openai/gpt-audio-mini)"),
1099
+ outputFormat: z.string().optional().describe("TTS output format (e.g., mp3_44100_128, mp3, wav)"),
1100
+ })
1101
+ .strict()
1102
+ .meta({
1103
+ ref: "SpeakConfig",
1104
+ })
1105
+ export type Speak = z.infer<typeof Speak>
1106
+
1107
+ export const Provider = ModelsDev.Provider.partial()
1108
+ .extend({
1109
+ whitelist: z.array(z.string()).optional(),
1110
+ blacklist: z.array(z.string()).optional(),
1111
+ models: z
1112
+ .record(
1113
+ z.string(),
1114
+ ModelsDev.Model.partial().extend({
1115
+ variants: z
1116
+ .record(
1117
+ z.string(),
1118
+ z
1119
+ .object({
1120
+ disabled: z.boolean().optional().describe("Disable this variant for the model"),
1121
+ })
1122
+ .catchall(z.any()),
1123
+ )
1124
+ .optional()
1125
+ .describe("Variant-specific configuration"),
1126
+ }),
1127
+ )
1128
+ .optional(),
1129
+ options: z
1130
+ .object({
1131
+ apiKey: z.string().optional(),
1132
+ baseURL: z.string().optional(),
1133
+ enterpriseUrl: z.string().optional().describe("GitHub Enterprise URL for copilot authentication"),
1134
+ setCacheKey: z.boolean().optional().describe("Enable promptCacheKey for this provider (default false)"),
1135
+ timeout: z
1136
+ .union([
1137
+ z
1138
+ .number()
1139
+ .int()
1140
+ .positive()
1141
+ .describe(
1142
+ "Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout.",
1143
+ ),
1144
+ z.literal(false).describe("Disable timeout for this provider entirely."),
1145
+ ])
1146
+ .optional()
1147
+ .describe(
1148
+ "Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout.",
1149
+ ),
1150
+ })
1151
+ .catchall(z.any())
1152
+ .optional(),
1153
+ })
1154
+ .strict()
1155
+ .meta({
1156
+ ref: "ProviderConfig",
1157
+ })
1158
+ export type Provider = z.infer<typeof Provider>
1159
+
1160
+ export const Info = z
1161
+ .object({
1162
+ $schema: z.string().optional().describe("JSON schema reference for configuration validation"),
1163
+ theme: z.string().optional().describe("Theme name to use for the interface"),
1164
+ keybinds: Keybinds.optional().describe("Custom keybind configurations"),
1165
+ logLevel: Log.Level.optional().describe("Log level"),
1166
+ tui: TUI.optional().describe("TUI specific settings"),
1167
+ ads: Ads.optional().describe("User-defined ads shown in the TUI tips area"),
1168
+ server: Server.optional().describe("Server configuration for nikcli serve and web commands"),
1169
+ remote: Remote.optional().describe("Remote Control defaults and behavior"),
1170
+ command: z
1171
+ .record(z.string(), Command)
1172
+ .optional()
1173
+ .describe("Command configuration, see https://nikcli.store/docs/commands"),
1174
+ watcher: z
1175
+ .object({
1176
+ ignore: z.array(z.string()).optional(),
1177
+ })
1178
+ .optional(),
1179
+ plugin: z.string().array().optional(),
1180
+ snapshot: z.boolean().optional(),
1181
+ share: z
1182
+ .enum(["manual", "auto", "disabled"])
1183
+ .optional()
1184
+ .describe(
1185
+ "Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing",
1186
+ ),
1187
+ autoshare: z
1188
+ .boolean()
1189
+ .optional()
1190
+ .describe("@deprecated Use 'share' field instead. Share newly created sessions automatically"),
1191
+ autoupdate: z
1192
+ .union([z.boolean(), z.literal("notify")])
1193
+ .optional()
1194
+ .describe(
1195
+ "Automatically update to the latest version. Set to true to auto-update, false to disable, or 'notify' to show update notifications",
1196
+ ),
1197
+ disabled_providers: z.array(z.string()).optional().describe("Disable providers that are loaded automatically"),
1198
+ enabled_providers: z
1199
+ .array(z.string())
1200
+ .optional()
1201
+ .describe("When set, ONLY these providers will be enabled. All other providers will be ignored"),
1202
+ model: z.string().describe("Model to use in the format of provider/model, eg anthropic/claude-2").optional(),
1203
+ small_model: z
1204
+ .string()
1205
+ .describe("Small model to use for tasks like title generation in the format of provider/model")
1206
+ .optional(),
1207
+ default_agent: z
1208
+ .string()
1209
+ .optional()
1210
+ .describe(
1211
+ "Default agent to use when none is specified. Must be a primary agent. Falls back to 'build' if not set or if the specified agent is invalid.",
1212
+ ),
1213
+ username: z
1214
+ .string()
1215
+ .optional()
1216
+ .describe("Custom username to display in conversations instead of system username"),
1217
+ mode: z
1218
+ .object({
1219
+ build: Agent.optional(),
1220
+ plan: Agent.optional(),
1221
+ })
1222
+ .catchall(Agent)
1223
+ .optional()
1224
+ .describe("@deprecated Use `agent` field instead."),
1225
+ agent: z
1226
+ .object({
1227
+ // primary
1228
+ plan: Agent.optional(),
1229
+ build: Agent.optional(),
1230
+ // subagent
1231
+ general: Agent.optional(),
1232
+ explore: Agent.optional(),
1233
+ // specialized
1234
+ title: Agent.optional(),
1235
+ summary: Agent.optional(),
1236
+ compaction: Agent.optional(),
1237
+ })
1238
+ .catchall(Agent)
1239
+ .optional()
1240
+ .describe("Agent configuration, see https://nikcli.store/docs/agents"),
1241
+ provider: z
1242
+ .record(z.string(), Provider)
1243
+ .optional()
1244
+ .describe("Custom provider configurations and model overrides"),
1245
+ mcp: z
1246
+ .record(
1247
+ z.string(),
1248
+ z.union([
1249
+ Mcp,
1250
+ z
1251
+ .object({
1252
+ enabled: z.boolean(),
1253
+ })
1254
+ .strict(),
1255
+ ]),
1256
+ )
1257
+ .optional()
1258
+ .describe("MCP (Model Context Protocol) server configurations"),
1259
+ connectors: z
1260
+ .record(
1261
+ z.string(),
1262
+ z.union([
1263
+ Connector,
1264
+ z
1265
+ .object({
1266
+ enabled: z.boolean(),
1267
+ })
1268
+ .strict(),
1269
+ ]),
1270
+ )
1271
+ .optional()
1272
+ .describe("External service connectors (Figma, Slack, GitHub, Lovable)"),
1273
+ formatter: z
1274
+ .union([
1275
+ z.literal(false),
1276
+ z.record(
1277
+ z.string(),
1278
+ z.object({
1279
+ disabled: z.boolean().optional(),
1280
+ command: z.array(z.string()).optional(),
1281
+ environment: z.record(z.string(), z.string()).optional(),
1282
+ extensions: z.array(z.string()).optional(),
1283
+ }),
1284
+ ),
1285
+ ])
1286
+ .optional(),
1287
+ lsp: z
1288
+ .union([
1289
+ z.literal(false),
1290
+ z.record(
1291
+ z.string(),
1292
+ z.union([
1293
+ z.object({
1294
+ disabled: z.literal(true),
1295
+ }),
1296
+ z.object({
1297
+ command: z.array(z.string()),
1298
+ extensions: z.array(z.string()).optional(),
1299
+ disabled: z.boolean().optional(),
1300
+ env: z.record(z.string(), z.string()).optional(),
1301
+ initialization: z.record(z.string(), z.any()).optional(),
1302
+ }),
1303
+ ]),
1304
+ ),
1305
+ ])
1306
+ .optional()
1307
+ .refine(
1308
+ (data) => {
1309
+ if (!data) return true
1310
+ if (typeof data === "boolean") return true
1311
+ const serverIds = new Set(Object.values(LSPServer).map((s) => s.id))
1312
+
1313
+ return Object.entries(data).every(([id, config]) => {
1314
+ if (config.disabled) return true
1315
+ if (serverIds.has(id)) return true
1316
+ return Boolean(config.extensions)
1317
+ })
1318
+ },
1319
+ {
1320
+ error: "For custom LSP servers, 'extensions' array is required.",
1321
+ },
1322
+ ),
1323
+ instructions: z.array(z.string()).optional().describe("Additional instruction files or patterns to include"),
1324
+ layout: Layout.optional().describe("@deprecated Always uses stretch layout."),
1325
+ permission: Permission.optional(),
1326
+ tools: z.record(z.string(), z.boolean()).optional(),
1327
+ enterprise: z
1328
+ .object({
1329
+ url: z.string().optional().describe("Enterprise URL"),
1330
+ })
1331
+ .optional(),
1332
+ compaction: z
1333
+ .object({
1334
+ auto: z.boolean().optional().describe("Enable automatic compaction when context is full (default: true)"),
1335
+ prune: z.boolean().optional().describe("Enable pruning of old tool outputs (default: true)"),
1336
+ reserved: z
1337
+ .number()
1338
+ .int()
1339
+ .min(0)
1340
+ .optional()
1341
+ .describe("Token buffer for compaction. Leaves enough window to avoid overflow during compaction."),
1342
+ })
1343
+ .optional(),
1344
+ experimental: z
1345
+ .object({
1346
+ hook: z
1347
+ .object({
1348
+ file_edited: z
1349
+ .record(
1350
+ z.string(),
1351
+ z
1352
+ .object({
1353
+ command: z.string().array(),
1354
+ environment: z.record(z.string(), z.string()).optional(),
1355
+ })
1356
+ .array(),
1357
+ )
1358
+ .optional(),
1359
+ session_completed: z
1360
+ .object({
1361
+ command: z.string().array(),
1362
+ environment: z.record(z.string(), z.string()).optional(),
1363
+ })
1364
+ .array()
1365
+ .optional(),
1366
+ })
1367
+ .optional(),
1368
+ chatMaxRetries: z.number().optional().describe("Number of retries for chat completions on failure"),
1369
+ disable_paste_summary: z.boolean().optional(),
1370
+ batch_tool: z.boolean().optional().describe("Enable the batch tool"),
1371
+ openTelemetry: z
1372
+ .boolean()
1373
+ .optional()
1374
+ .describe("Enable OpenTelemetry spans for AI SDK calls (using the 'experimental_telemetry' flag)"),
1375
+ primary_tools: z
1376
+ .array(z.string())
1377
+ .optional()
1378
+ .describe("Tools that should only be available to primary agents."),
1379
+ continue_loop_on_deny: z.boolean().optional().describe("Continue the agent loop when a tool call is denied"),
1380
+ mcp_timeout: z
1381
+ .number()
1382
+ .int()
1383
+ .positive()
1384
+ .optional()
1385
+ .describe("Timeout in milliseconds for model context protocol (MCP) requests"),
1386
+ })
1387
+ .optional(),
1388
+ rag: Rag.optional().describe("RAG embedding configuration"),
1389
+ image: Image.optional().describe("Image generation configuration"),
1390
+ speak: Speak.optional().describe("Text-to-speech configuration"),
1391
+ notifications: z
1392
+ .object({
1393
+ todo: z
1394
+ .object({
1395
+ enabled: z.boolean().optional().describe("Enable todo notifications"),
1396
+ macos: z.boolean().optional().describe("Enable macOS native notifications"),
1397
+ slack: z
1398
+ .object({
1399
+ enabled: z.boolean().optional(),
1400
+ connector: z.string().optional().describe("Name of the Slack connector to use"),
1401
+ channel: z.string().optional().describe("Slack channel ID or name"),
1402
+ })
1403
+ .optional(),
1404
+ discord: z
1405
+ .object({
1406
+ enabled: z.boolean().optional(),
1407
+ webhook: z.string().optional().describe("Discord webhook URL"),
1408
+ })
1409
+ .optional(),
1410
+ })
1411
+ .optional(),
1412
+ icon: z
1413
+ .object({
1414
+ url: z.string().optional().describe("Icon image URL or file path for macOS notifications"),
1415
+ alt: z.string().optional().describe("Alt text (unused for macOS)"),
1416
+ })
1417
+ .optional(),
1418
+ notify: z
1419
+ .object({
1420
+ enabled: z.boolean().optional().describe("Enable native notifications"),
1421
+ macos: z.boolean().optional().describe("Enable macOS native notifications"),
1422
+ slack: z
1423
+ .object({
1424
+ enabled: z.boolean().optional(),
1425
+ connector: z.string().optional().describe("Name of the Slack connector to use"),
1426
+ channel: z.string().optional().describe("Slack channel ID or name"),
1427
+ })
1428
+ .optional(),
1429
+ discord: z
1430
+ .object({
1431
+ enabled: z.boolean().optional(),
1432
+ webhook: z.string().optional().describe("Discord webhook URL"),
1433
+ })
1434
+ .optional(),
1435
+ events: z
1436
+ .object({
1437
+ sessionIdle: z.boolean().optional().describe("Notify when a session becomes idle"),
1438
+ sessionError: z.boolean().optional().describe("Notify when a session errors"),
1439
+ permissionAsked: z.boolean().optional().describe("Notify when permissions are requested"),
1440
+ questionAsked: z.boolean().optional().describe("Notify when questions are asked"),
1441
+ })
1442
+ .optional(),
1443
+ idleMinMs: z
1444
+ .number()
1445
+ .int()
1446
+ .positive()
1447
+ .optional()
1448
+ .describe("Minimum busy duration before idle notifications"),
1449
+ rateLimit: z
1450
+ .object({
1451
+ windowMs: z.number().int().positive().optional().describe("Rate limit window in ms"),
1452
+ maxPerWindow: z.number().int().positive().optional().describe("Max notifications per window"),
1453
+ })
1454
+ .optional(),
1455
+ retry: z
1456
+ .object({
1457
+ attempts: z.number().int().positive().optional(),
1458
+ delay: z.number().int().positive().optional().describe("Initial retry delay in ms"),
1459
+ factor: z.number().positive().optional().describe("Backoff multiplier"),
1460
+ maxDelay: z.number().int().positive().optional().describe("Max retry delay in ms"),
1461
+ timeoutMs: z.number().int().positive().optional().describe("Timeout per attempt in ms"),
1462
+ })
1463
+ .optional(),
1464
+ breaker: z
1465
+ .object({
1466
+ failures: z.number().int().positive().optional().describe("Failures before circuit opens"),
1467
+ cooldownMs: z.number().int().positive().optional().describe("Circuit breaker cooldown in ms"),
1468
+ })
1469
+ .optional(),
1470
+ quietHours: z
1471
+ .object({
1472
+ enabled: z.boolean().optional().describe("Enable quiet hours"),
1473
+ start: z.string().optional().describe("Quiet hours start (HH:MM)"),
1474
+ end: z.string().optional().describe("Quiet hours end (HH:MM)"),
1475
+ suppress: z
1476
+ .array(z.enum(["macos", "slack", "discord"]))
1477
+ .optional()
1478
+ .describe("Channels suppressed during quiet hours"),
1479
+ })
1480
+ .optional(),
1481
+ })
1482
+ .optional(),
1483
+ })
1484
+ .optional()
1485
+ .describe("Notification settings for various events"),
1486
+ })
1487
+ .strict()
1488
+ .meta({
1489
+ ref: "Config",
1490
+ })
1491
+
1492
+ export type Info = z.output<typeof Info>
1493
+
1494
+ export const global = lazy(async () => {
1495
+ let result: Info = pipe(
1496
+ {},
1497
+ mergeDeep(await loadFile(path.join(Global.Path.config, "config.json"))),
1498
+ mergeDeep(await loadFile(path.join(Global.Path.config, "nikcli.json"))),
1499
+ mergeDeep(await loadFile(path.join(Global.Path.config, "nikcli.jsonc"))),
1500
+ )
1501
+
1502
+ await import(path.join(Global.Path.config, "config"), {
1503
+ with: {
1504
+ type: "toml",
1505
+ },
1506
+ })
1507
+ .then(async (mod) => {
1508
+ const { provider, model, ...rest } = mod.default
1509
+ if (provider && model) result.model = `${provider}/${model}`
1510
+ result["$schema"] = "https://nikcli.store/config.json"
1511
+ result = mergeDeep(result, rest)
1512
+ await Bun.write(path.join(Global.Path.config, "config.json"), JSON.stringify(result, null, 2))
1513
+ await fs.unlink(path.join(Global.Path.config, "config"))
1514
+ })
1515
+ .catch(() => {})
1516
+
1517
+ return result
1518
+ })
1519
+
1520
+ async function loadFile(filepath: string): Promise<Info> {
1521
+ log.info("loading", { path: filepath })
1522
+ let text = await Bun.file(filepath)
1523
+ .text()
1524
+ .catch((err) => {
1525
+ if (err.code === "ENOENT") return
1526
+ throw new JsonError({ path: filepath }, { cause: err })
1527
+ })
1528
+ if (!text) return {}
1529
+ return load(text, filepath)
1530
+ }
1531
+
1532
+ async function load(text: string, configFilepath: string) {
1533
+ const original = text
1534
+ text = text.replace(/\{env:([^}]+)\}/g, (_, varName) => {
1535
+ return process.env[varName] || ""
1536
+ })
1537
+
1538
+ const fileMatches = text.match(/\{file:[^}]+\}/g)
1539
+ if (fileMatches) {
1540
+ const configDir = path.dirname(configFilepath)
1541
+ const lines = text.split("\n")
1542
+
1543
+ for (const match of fileMatches) {
1544
+ const lineIndex = lines.findIndex((line) => line.includes(match))
1545
+ if (lineIndex !== -1 && lines[lineIndex].trim().startsWith("//")) {
1546
+ continue // Skip if line is commented
1547
+ }
1548
+ let filePath = match.replace(/^\{file:/, "").replace(/\}$/, "")
1549
+ if (filePath.startsWith("~/")) {
1550
+ filePath = path.join(os.homedir(), filePath.slice(2))
1551
+ }
1552
+ const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(configDir, filePath)
1553
+ const fileContent = (
1554
+ await Bun.file(resolvedPath)
1555
+ .text()
1556
+ .catch((error) => {
1557
+ const errMsg = `bad file reference: "${match}"`
1558
+ if (error.code === "ENOENT") {
1559
+ throw new InvalidError(
1560
+ {
1561
+ path: configFilepath,
1562
+ message: errMsg + ` ${resolvedPath} does not exist`,
1563
+ },
1564
+ { cause: error },
1565
+ )
1566
+ }
1567
+ throw new InvalidError({ path: configFilepath, message: errMsg }, { cause: error })
1568
+ })
1569
+ ).trim()
1570
+ // escape newlines/quotes, strip outer quotes
1571
+ text = text.replace(match, JSON.stringify(fileContent).slice(1, -1))
1572
+ }
1573
+ }
1574
+
1575
+ const errors: JsoncParseError[] = []
1576
+ const data = parseJsonc(text, errors, { allowTrailingComma: true })
1577
+ if (errors.length) {
1578
+ const lines = text.split("\n")
1579
+ const errorDetails = errors
1580
+ .map((e) => {
1581
+ const beforeOffset = text.substring(0, e.offset).split("\n")
1582
+ const line = beforeOffset.length
1583
+ const column = beforeOffset[beforeOffset.length - 1].length + 1
1584
+ const problemLine = lines[line - 1]
1585
+
1586
+ const error = `${printParseErrorCode(e.error)} at line ${line}, column ${column}`
1587
+ if (!problemLine) return error
1588
+
1589
+ return `${error}\n Line ${line}: ${problemLine}\n${"".padStart(column + 9)}^`
1590
+ })
1591
+ .join("\n")
1592
+
1593
+ throw new JsonError({
1594
+ path: configFilepath,
1595
+ message: `\n--- JSONC Input ---\n${text}\n--- Errors ---\n${errorDetails}\n--- End ---`,
1596
+ })
1597
+ }
1598
+
1599
+ const parsed = Info.safeParse(data)
1600
+ if (parsed.success) {
1601
+ if (!parsed.data.$schema) {
1602
+ parsed.data.$schema = "https://nikcli.store/config.json"
1603
+ // Write the $schema to the original text to preserve variables like {env:VAR}
1604
+ const updated = original.replace(/^\s*\{/, '{\n "$schema": "https://nikcli.store/config.json",')
1605
+ await Bun.write(configFilepath, updated).catch(() => {})
1606
+ }
1607
+ const data = parsed.data
1608
+ if (data.plugin) {
1609
+ for (let i = 0; i < data.plugin.length; i++) {
1610
+ const plugin = data.plugin[i]
1611
+ try {
1612
+ data.plugin[i] = import.meta.resolve!(plugin, configFilepath)
1613
+ } catch (err) {}
1614
+ }
1615
+ }
1616
+ return data
1617
+ }
1618
+
1619
+ throw new InvalidError({
1620
+ path: configFilepath,
1621
+ issues: parsed.error.issues,
1622
+ })
1623
+ }
1624
+ export const JsonError = NamedError.create(
1625
+ "ConfigJsonError",
1626
+ z.object({
1627
+ path: z.string(),
1628
+ message: z.string().optional(),
1629
+ }),
1630
+ )
1631
+
1632
+ export const ConfigDirectoryTypoError = NamedError.create(
1633
+ "ConfigDirectoryTypoError",
1634
+ z.object({
1635
+ path: z.string(),
1636
+ dir: z.string(),
1637
+ suggestion: z.string(),
1638
+ }),
1639
+ )
1640
+
1641
+ export const InvalidError = NamedError.create(
1642
+ "ConfigInvalidError",
1643
+ z.object({
1644
+ path: z.string(),
1645
+ issues: z.custom<z.core.$ZodIssue[]>().optional(),
1646
+ message: z.string().optional(),
1647
+ }),
1648
+ )
1649
+
1650
+ export async function get() {
1651
+ return state().then((x) => x.config)
1652
+ }
1653
+
1654
+ export async function getGlobal() {
1655
+ return global()
1656
+ }
1657
+
1658
+ export async function update(config: Info) {
1659
+ const filepath = path.join(Instance.directory, "config.json")
1660
+ const existing = await loadFile(filepath)
1661
+ await Bun.write(filepath, JSON.stringify(mergeDeep(existing, config), null, 2))
1662
+ await Instance.dispose()
1663
+ }
1664
+
1665
+ function globalConfigFile() {
1666
+ const candidates = ["nikcli.jsonc", "nikcli.json", "config.json"].map((file) => path.join(Global.Path.config, file))
1667
+ for (const file of candidates) {
1668
+ if (existsSync(file)) return file
1669
+ }
1670
+ return candidates[0]
1671
+ }
1672
+
1673
+ function isRecord(value: unknown): value is Record<string, unknown> {
1674
+ return !!value && typeof value === "object" && !Array.isArray(value)
1675
+ }
1676
+
1677
+ function patchJsonc(input: string, patch: unknown, path: string[] = []): string {
1678
+ if (!isRecord(patch)) {
1679
+ const edits = modify(input, path, patch, {
1680
+ formattingOptions: {
1681
+ insertSpaces: true,
1682
+ tabSize: 2,
1683
+ },
1684
+ })
1685
+ return applyEdits(input, edits)
1686
+ }
1687
+
1688
+ return Object.entries(patch).reduce((result, [key, value]) => {
1689
+ if (value === undefined) return result
1690
+ return patchJsonc(result, value, [...path, key])
1691
+ }, input)
1692
+ }
1693
+
1694
+ function parseConfig(text: string, filepath: string): Info {
1695
+ const errors: JsoncParseError[] = []
1696
+ const data = parseJsonc(text, errors, { allowTrailingComma: true })
1697
+ if (errors.length) {
1698
+ const lines = text.split("\n")
1699
+ const errorDetails = errors
1700
+ .map((e) => {
1701
+ const beforeOffset = text.substring(0, e.offset).split("\n")
1702
+ const line = beforeOffset.length
1703
+ const column = beforeOffset[beforeOffset.length - 1].length + 1
1704
+ const problemLine = lines[line - 1]
1705
+
1706
+ const error = `${printParseErrorCode(e.error)} at line ${line}, column ${column}`
1707
+ if (!problemLine) return error
1708
+
1709
+ return `${error}\n Line ${line}: ${problemLine}\n${"".padStart(column + 9)}^`
1710
+ })
1711
+ .join("\n")
1712
+
1713
+ throw new JsonError({
1714
+ path: filepath,
1715
+ message: `\n--- JSONC Input ---\n${text}\n--- Errors ---\n${errorDetails}\n--- End ---`,
1716
+ })
1717
+ }
1718
+
1719
+ const parsed = Info.safeParse(data)
1720
+ if (parsed.success) return parsed.data
1721
+
1722
+ throw new InvalidError({
1723
+ path: filepath,
1724
+ issues: parsed.error.issues,
1725
+ })
1726
+ }
1727
+
1728
+ export async function updateGlobal(config: Info) {
1729
+ const filepath = globalConfigFile()
1730
+ const before = await Bun.file(filepath)
1731
+ .text()
1732
+ .catch((err) => {
1733
+ if (err.code === "ENOENT") return "{}"
1734
+ throw new JsonError({ path: filepath }, { cause: err })
1735
+ })
1736
+
1737
+ if (!filepath.endsWith(".jsonc")) {
1738
+ const existing = parseConfig(before, filepath)
1739
+ await Bun.write(filepath, JSON.stringify(mergeDeep(existing, config), null, 2))
1740
+ } else {
1741
+ const next = patchJsonc(before, config)
1742
+ parseConfig(next, filepath)
1743
+ await Bun.write(filepath, next)
1744
+ }
1745
+
1746
+ global.reset()
1747
+ await Instance.disposeAll()
1748
+ GlobalBus.emit("event", {
1749
+ directory: "global",
1750
+ payload: {
1751
+ type: Event.Disposed.type,
1752
+ properties: {},
1753
+ },
1754
+ })
1755
+ }
1756
+
1757
+ export async function directories() {
1758
+ return state().then((x) => x.directories)
1759
+ }
1760
+ }