@happy-creative/iroder 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (697) hide show
  1. package/.qwen/settings.json +8 -0
  2. package/.qwen/settings.json.orig +7 -0
  3. package/AGENTS.md +69 -0
  4. package/BUN_SHELL_MIGRATION_PLAN.md +136 -0
  5. package/Dockerfile +20 -0
  6. package/README.md +15 -0
  7. package/bin/iroder +182 -0
  8. package/docker-compose.iroder.yml +18 -0
  9. package/drizzle.config.ts +10 -0
  10. package/git +0 -0
  11. package/migration/20260127222353_familiar_lady_ursula/migration.sql +90 -0
  12. package/migration/20260127222353_familiar_lady_ursula/snapshot.json +796 -0
  13. package/migration/20260211171708_add_project_commands/migration.sql +1 -0
  14. package/migration/20260211171708_add_project_commands/snapshot.json +806 -0
  15. package/migration/20260213144116_wakeful_the_professor/migration.sql +11 -0
  16. package/migration/20260213144116_wakeful_the_professor/snapshot.json +897 -0
  17. package/migration/20260225215848_workspace/migration.sql +7 -0
  18. package/migration/20260225215848_workspace/snapshot.json +959 -0
  19. package/migration/20260227213759_add_session_workspace_id/migration.sql +2 -0
  20. package/migration/20260227213759_add_session_workspace_id/snapshot.json +983 -0
  21. package/migration/20260228203230_blue_harpoon/migration.sql +17 -0
  22. package/migration/20260228203230_blue_harpoon/snapshot.json +1102 -0
  23. package/migration/20260303231226_add_workspace_fields/migration.sql +5 -0
  24. package/migration/20260303231226_add_workspace_fields/snapshot.json +1013 -0
  25. package/migration/20260309230000_move_org_to_state/migration.sql +3 -0
  26. package/migration/20260309230000_move_org_to_state/snapshot.json +1156 -0
  27. package/migration/20260312043431_session_message_cursor/migration.sql +4 -0
  28. package/migration/20260312043431_session_message_cursor/snapshot.json +1168 -0
  29. package/migration/20260323234822_events/migration.sql +13 -0
  30. package/migration/20260323234822_events/snapshot.json +1271 -0
  31. package/package.json +180 -0
  32. package/parsers-config.ts +290 -0
  33. package/script/build-node.ts +60 -0
  34. package/script/build.ts +281 -0
  35. package/script/check-migrations.ts +16 -0
  36. package/script/e2e-local-real-key.ts +197 -0
  37. package/script/fix-node-pty.ts +28 -0
  38. package/script/postinstall.mjs +131 -0
  39. package/script/publish-all.sh +68 -0
  40. package/script/publish.ts +181 -0
  41. package/script/schema.ts +63 -0
  42. package/script/seed-e2e.ts +60 -0
  43. package/script/upgrade-opentui.ts +64 -0
  44. package/specs/effect-migration.md +310 -0
  45. package/specs/tui-plugins.md +436 -0
  46. package/specs/v2/keymappings.md +10 -0
  47. package/specs/v2/message-shape.md +136 -0
  48. package/src/account/account.sql.ts +39 -0
  49. package/src/account/index.ts +488 -0
  50. package/src/account/repo.ts +166 -0
  51. package/src/account/schema.ts +119 -0
  52. package/src/account/url.ts +8 -0
  53. package/src/acp/README.md +174 -0
  54. package/src/acp/agent.ts +1847 -0
  55. package/src/acp/session.ts +116 -0
  56. package/src/acp/types.ts +24 -0
  57. package/src/agent/agent.ts +422 -0
  58. package/src/agent/generate.txt +75 -0
  59. package/src/agent/prompt/compaction.txt +15 -0
  60. package/src/agent/prompt/explore.txt +18 -0
  61. package/src/agent/prompt/summary.txt +11 -0
  62. package/src/agent/prompt/title.txt +44 -0
  63. package/src/auth/index.ts +110 -0
  64. package/src/bus/bus-event.ts +40 -0
  65. package/src/bus/global.ts +10 -0
  66. package/src/bus/index.ts +185 -0
  67. package/src/cli/bootstrap.ts +17 -0
  68. package/src/cli/cmd/account.ts +257 -0
  69. package/src/cli/cmd/acp.ts +72 -0
  70. package/src/cli/cmd/agent.ts +245 -0
  71. package/src/cli/cmd/cmd.ts +7 -0
  72. package/src/cli/cmd/db.ts +120 -0
  73. package/src/cli/cmd/debug/agent.ts +170 -0
  74. package/src/cli/cmd/debug/config.ts +16 -0
  75. package/src/cli/cmd/debug/file.ts +97 -0
  76. package/src/cli/cmd/debug/index.ts +48 -0
  77. package/src/cli/cmd/debug/lsp.ts +53 -0
  78. package/src/cli/cmd/debug/ripgrep.ts +87 -0
  79. package/src/cli/cmd/debug/scrap.ts +16 -0
  80. package/src/cli/cmd/debug/skill.ts +16 -0
  81. package/src/cli/cmd/debug/snapshot.ts +52 -0
  82. package/src/cli/cmd/export.ts +89 -0
  83. package/src/cli/cmd/generate.ts +38 -0
  84. package/src/cli/cmd/github.ts +1647 -0
  85. package/src/cli/cmd/import.ts +207 -0
  86. package/src/cli/cmd/mcp.ts +754 -0
  87. package/src/cli/cmd/models.ts +78 -0
  88. package/src/cli/cmd/plug.ts +233 -0
  89. package/src/cli/cmd/pr.ts +127 -0
  90. package/src/cli/cmd/providers.ts +480 -0
  91. package/src/cli/cmd/run.ts +692 -0
  92. package/src/cli/cmd/serve.ts +23 -0
  93. package/src/cli/cmd/session.ts +159 -0
  94. package/src/cli/cmd/stats.ts +410 -0
  95. package/src/cli/cmd/tui/app.tsx +940 -0
  96. package/src/cli/cmd/tui/attach.ts +88 -0
  97. package/src/cli/cmd/tui/component/border.tsx +21 -0
  98. package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
  99. package/src/cli/cmd/tui/component/dialog-command.tsx +171 -0
  100. package/src/cli/cmd/tui/component/dialog-console-org.tsx +103 -0
  101. package/src/cli/cmd/tui/component/dialog-go-upsell.tsx +100 -0
  102. package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
  103. package/src/cli/cmd/tui/component/dialog-model.tsx +183 -0
  104. package/src/cli/cmd/tui/component/dialog-provider.tsx +360 -0
  105. package/src/cli/cmd/tui/component/dialog-session-list.tsx +108 -0
  106. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
  107. package/src/cli/cmd/tui/component/dialog-skill.tsx +36 -0
  108. package/src/cli/cmd/tui/component/dialog-stash.tsx +87 -0
  109. package/src/cli/cmd/tui/component/dialog-status.tsx +168 -0
  110. package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
  111. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
  112. package/src/cli/cmd/tui/component/dialog-variant.tsx +39 -0
  113. package/src/cli/cmd/tui/component/dialog-workspace-list.tsx +320 -0
  114. package/src/cli/cmd/tui/component/error-component.tsx +93 -0
  115. package/src/cli/cmd/tui/component/logo.tsx +85 -0
  116. package/src/cli/cmd/tui/component/plugin-route-missing.tsx +14 -0
  117. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +672 -0
  118. package/src/cli/cmd/tui/component/prompt/frecency.tsx +90 -0
  119. package/src/cli/cmd/tui/component/prompt/history.tsx +108 -0
  120. package/src/cli/cmd/tui/component/prompt/index.tsx +1261 -0
  121. package/src/cli/cmd/tui/component/prompt/part.ts +16 -0
  122. package/src/cli/cmd/tui/component/prompt/stash.tsx +101 -0
  123. package/src/cli/cmd/tui/component/spinner.tsx +24 -0
  124. package/src/cli/cmd/tui/component/startup-loading.tsx +63 -0
  125. package/src/cli/cmd/tui/component/textarea-keybindings.ts +73 -0
  126. package/src/cli/cmd/tui/component/todo-item.tsx +32 -0
  127. package/src/cli/cmd/tui/component/workspace/dialog-session-list.tsx +151 -0
  128. package/src/cli/cmd/tui/context/args.tsx +15 -0
  129. package/src/cli/cmd/tui/context/directory.ts +13 -0
  130. package/src/cli/cmd/tui/context/exit.tsx +60 -0
  131. package/src/cli/cmd/tui/context/helper.tsx +25 -0
  132. package/src/cli/cmd/tui/context/keybind.tsx +105 -0
  133. package/src/cli/cmd/tui/context/kv.tsx +52 -0
  134. package/src/cli/cmd/tui/context/local.tsx +412 -0
  135. package/src/cli/cmd/tui/context/plugin-keybinds.ts +41 -0
  136. package/src/cli/cmd/tui/context/prompt.tsx +18 -0
  137. package/src/cli/cmd/tui/context/route.tsx +52 -0
  138. package/src/cli/cmd/tui/context/sdk.tsx +115 -0
  139. package/src/cli/cmd/tui/context/sync.tsx +516 -0
  140. package/src/cli/cmd/tui/context/theme/aura.json +69 -0
  141. package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
  142. package/src/cli/cmd/tui/context/theme/carbonfox.json +248 -0
  143. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +233 -0
  144. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +233 -0
  145. package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
  146. package/src/cli/cmd/tui/context/theme/cobalt2.json +228 -0
  147. package/src/cli/cmd/tui/context/theme/cursor.json +249 -0
  148. package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
  149. package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
  150. package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
  151. package/src/cli/cmd/tui/context/theme/github.json +233 -0
  152. package/src/cli/cmd/tui/context/theme/gruvbox.json +242 -0
  153. package/src/cli/cmd/tui/context/theme/iroder.json +245 -0
  154. package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
  155. package/src/cli/cmd/tui/context/theme/lucent-orng.json +237 -0
  156. package/src/cli/cmd/tui/context/theme/material.json +235 -0
  157. package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
  158. package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
  159. package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
  160. package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
  161. package/src/cli/cmd/tui/context/theme/nord.json +223 -0
  162. package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
  163. package/src/cli/cmd/tui/context/theme/opencode.json +245 -0
  164. package/src/cli/cmd/tui/context/theme/orng.json +249 -0
  165. package/src/cli/cmd/tui/context/theme/osaka-jade.json +93 -0
  166. package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
  167. package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
  168. package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
  169. package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
  170. package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
  171. package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
  172. package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
  173. package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
  174. package/src/cli/cmd/tui/context/theme.tsx +1236 -0
  175. package/src/cli/cmd/tui/context/tui-config.tsx +9 -0
  176. package/src/cli/cmd/tui/event.ts +49 -0
  177. package/src/cli/cmd/tui/feature-plugins/home/footer.tsx +93 -0
  178. package/src/cli/cmd/tui/feature-plugins/home/tips-view.tsx +155 -0
  179. package/src/cli/cmd/tui/feature-plugins/home/tips.tsx +50 -0
  180. package/src/cli/cmd/tui/feature-plugins/sidebar/context.tsx +63 -0
  181. package/src/cli/cmd/tui/feature-plugins/sidebar/files.tsx +62 -0
  182. package/src/cli/cmd/tui/feature-plugins/sidebar/footer.tsx +93 -0
  183. package/src/cli/cmd/tui/feature-plugins/sidebar/lsp.tsx +66 -0
  184. package/src/cli/cmd/tui/feature-plugins/sidebar/mcp.tsx +96 -0
  185. package/src/cli/cmd/tui/feature-plugins/sidebar/todo.tsx +48 -0
  186. package/src/cli/cmd/tui/feature-plugins/system/plugins.tsx +270 -0
  187. package/src/cli/cmd/tui/plugin/api.tsx +397 -0
  188. package/src/cli/cmd/tui/plugin/index.ts +3 -0
  189. package/src/cli/cmd/tui/plugin/internal.ts +27 -0
  190. package/src/cli/cmd/tui/plugin/runtime.ts +1031 -0
  191. package/src/cli/cmd/tui/plugin/slots.tsx +60 -0
  192. package/src/cli/cmd/tui/routes/home.tsx +84 -0
  193. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +65 -0
  194. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +110 -0
  195. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +26 -0
  196. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +47 -0
  197. package/src/cli/cmd/tui/routes/session/footer.tsx +91 -0
  198. package/src/cli/cmd/tui/routes/session/index.tsx +2281 -0
  199. package/src/cli/cmd/tui/routes/session/permission.tsx +691 -0
  200. package/src/cli/cmd/tui/routes/session/question.tsx +468 -0
  201. package/src/cli/cmd/tui/routes/session/sidebar.tsx +74 -0
  202. package/src/cli/cmd/tui/routes/session/subagent-footer.tsx +131 -0
  203. package/src/cli/cmd/tui/thread.ts +241 -0
  204. package/src/cli/cmd/tui/ui/dialog-alert.tsx +59 -0
  205. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +89 -0
  206. package/src/cli/cmd/tui/ui/dialog-export-options.tsx +211 -0
  207. package/src/cli/cmd/tui/ui/dialog-help.tsx +40 -0
  208. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +115 -0
  209. package/src/cli/cmd/tui/ui/dialog-select.tsx +417 -0
  210. package/src/cli/cmd/tui/ui/dialog.tsx +192 -0
  211. package/src/cli/cmd/tui/ui/link.tsx +28 -0
  212. package/src/cli/cmd/tui/ui/spinner.ts +368 -0
  213. package/src/cli/cmd/tui/ui/toast.tsx +100 -0
  214. package/src/cli/cmd/tui/util/clipboard.ts +192 -0
  215. package/src/cli/cmd/tui/util/editor.ts +37 -0
  216. package/src/cli/cmd/tui/util/model.ts +23 -0
  217. package/src/cli/cmd/tui/util/provider-origin.ts +7 -0
  218. package/src/cli/cmd/tui/util/scroll.ts +23 -0
  219. package/src/cli/cmd/tui/util/selection.ts +25 -0
  220. package/src/cli/cmd/tui/util/signal.ts +7 -0
  221. package/src/cli/cmd/tui/util/terminal.ts +114 -0
  222. package/src/cli/cmd/tui/util/transcript.ts +112 -0
  223. package/src/cli/cmd/tui/win32.ts +129 -0
  224. package/src/cli/cmd/tui/worker.ts +195 -0
  225. package/src/cli/cmd/uninstall.ts +353 -0
  226. package/src/cli/cmd/upgrade.ts +73 -0
  227. package/src/cli/cmd/web.ts +83 -0
  228. package/src/cli/commands.ts +58 -0
  229. package/src/cli/effect/prompt.ts +25 -0
  230. package/src/cli/error.ts +50 -0
  231. package/src/cli/heap.ts +59 -0
  232. package/src/cli/llm-ready.ts +22 -0
  233. package/src/cli/logo.ts +8 -0
  234. package/src/cli/network.ts +60 -0
  235. package/src/cli/ui.ts +132 -0
  236. package/src/cli/upgrade.ts +31 -0
  237. package/src/command/index.ts +195 -0
  238. package/src/command/template/initialize.txt +66 -0
  239. package/src/command/template/review.txt +101 -0
  240. package/src/config/config.ts +1659 -0
  241. package/src/config/console-state.ts +15 -0
  242. package/src/config/markdown.ts +99 -0
  243. package/src/config/paths.ts +167 -0
  244. package/src/config/tui-migrate.ts +156 -0
  245. package/src/config/tui-schema.ts +37 -0
  246. package/src/config/tui.ts +179 -0
  247. package/src/control-plane/adaptors/index.ts +23 -0
  248. package/src/control-plane/adaptors/remote-acp.ts +35 -0
  249. package/src/control-plane/adaptors/remote-http.ts +35 -0
  250. package/src/control-plane/adaptors/worktree.ts +42 -0
  251. package/src/control-plane/schema.ts +17 -0
  252. package/src/control-plane/sse.ts +66 -0
  253. package/src/control-plane/types.ts +32 -0
  254. package/src/control-plane/workspace.sql.ts +17 -0
  255. package/src/control-plane/workspace.ts +169 -0
  256. package/src/effect/cross-spawn-spawner.ts +502 -0
  257. package/src/effect/instance-ref.ts +6 -0
  258. package/src/effect/instance-registry.ts +12 -0
  259. package/src/effect/instance-state.ts +82 -0
  260. package/src/effect/oltp.ts +34 -0
  261. package/src/effect/run-service.ts +34 -0
  262. package/src/effect/runner.ts +216 -0
  263. package/src/env/index.ts +28 -0
  264. package/src/file/ignore.ts +82 -0
  265. package/src/file/index.ts +686 -0
  266. package/src/file/protected.ts +59 -0
  267. package/src/file/ripgrep.ts +376 -0
  268. package/src/file/time.ts +133 -0
  269. package/src/file/watcher.ts +171 -0
  270. package/src/filesystem/index.ts +236 -0
  271. package/src/flag/flag.ts +171 -0
  272. package/src/format/formatter.ts +413 -0
  273. package/src/format/index.ts +203 -0
  274. package/src/git/index.ts +303 -0
  275. package/src/global/index.ts +54 -0
  276. package/src/id/id.ts +85 -0
  277. package/src/ide/index.ts +74 -0
  278. package/src/index.ts +202 -0
  279. package/src/installation/index.ts +356 -0
  280. package/src/installation/meta.ts +7 -0
  281. package/src/lsp/client.ts +252 -0
  282. package/src/lsp/index.ts +558 -0
  283. package/src/lsp/language.ts +120 -0
  284. package/src/lsp/launch.ts +21 -0
  285. package/src/lsp/server.ts +1968 -0
  286. package/src/mcp/auth.ts +173 -0
  287. package/src/mcp/index.ts +921 -0
  288. package/src/mcp/oauth-callback.ts +216 -0
  289. package/src/mcp/oauth-provider.ts +186 -0
  290. package/src/node.ts +6 -0
  291. package/src/npm/index.ts +188 -0
  292. package/src/patch/index.ts +680 -0
  293. package/src/permission/arity.ts +163 -0
  294. package/src/permission/evaluate.ts +15 -0
  295. package/src/permission/index.ts +325 -0
  296. package/src/permission/schema.ts +17 -0
  297. package/src/plugin/cloudflare.ts +67 -0
  298. package/src/plugin/codex.ts +608 -0
  299. package/src/plugin/github-copilot/copilot.ts +361 -0
  300. package/src/plugin/github-copilot/models.ts +144 -0
  301. package/src/plugin/index.ts +293 -0
  302. package/src/plugin/install.ts +439 -0
  303. package/src/plugin/loader.ts +174 -0
  304. package/src/plugin/meta.ts +188 -0
  305. package/src/plugin/shared.ts +323 -0
  306. package/src/project/bootstrap.ts +31 -0
  307. package/src/project/instance.ts +175 -0
  308. package/src/project/project.sql.ts +16 -0
  309. package/src/project/project.ts +519 -0
  310. package/src/project/schema.ts +16 -0
  311. package/src/project/state.ts +70 -0
  312. package/src/project/vcs.ts +254 -0
  313. package/src/provider/auth.ts +253 -0
  314. package/src/provider/error.ts +197 -0
  315. package/src/provider/models.ts +159 -0
  316. package/src/provider/provider.ts +1748 -0
  317. package/src/provider/schema.ts +38 -0
  318. package/src/provider/sdk/copilot/README.md +5 -0
  319. package/src/provider/sdk/copilot/chat/convert-to-openai-compatible-chat-messages.ts +170 -0
  320. package/src/provider/sdk/copilot/chat/get-response-metadata.ts +15 -0
  321. package/src/provider/sdk/copilot/chat/map-openai-compatible-finish-reason.ts +19 -0
  322. package/src/provider/sdk/copilot/chat/openai-compatible-api-types.ts +64 -0
  323. package/src/provider/sdk/copilot/chat/openai-compatible-chat-language-model.ts +815 -0
  324. package/src/provider/sdk/copilot/chat/openai-compatible-chat-options.ts +28 -0
  325. package/src/provider/sdk/copilot/chat/openai-compatible-metadata-extractor.ts +44 -0
  326. package/src/provider/sdk/copilot/chat/openai-compatible-prepare-tools.ts +83 -0
  327. package/src/provider/sdk/copilot/copilot-provider.ts +100 -0
  328. package/src/provider/sdk/copilot/index.ts +2 -0
  329. package/src/provider/sdk/copilot/openai-compatible-error.ts +27 -0
  330. package/src/provider/sdk/copilot/responses/convert-to-openai-responses-input.ts +335 -0
  331. package/src/provider/sdk/copilot/responses/map-openai-responses-finish-reason.ts +22 -0
  332. package/src/provider/sdk/copilot/responses/openai-config.ts +18 -0
  333. package/src/provider/sdk/copilot/responses/openai-error.ts +22 -0
  334. package/src/provider/sdk/copilot/responses/openai-responses-api-types.ts +214 -0
  335. package/src/provider/sdk/copilot/responses/openai-responses-language-model.ts +1769 -0
  336. package/src/provider/sdk/copilot/responses/openai-responses-prepare-tools.ts +173 -0
  337. package/src/provider/sdk/copilot/responses/openai-responses-settings.ts +1 -0
  338. package/src/provider/sdk/copilot/responses/tool/code-interpreter.ts +87 -0
  339. package/src/provider/sdk/copilot/responses/tool/file-search.ts +127 -0
  340. package/src/provider/sdk/copilot/responses/tool/image-generation.ts +114 -0
  341. package/src/provider/sdk/copilot/responses/tool/local-shell.ts +64 -0
  342. package/src/provider/sdk/copilot/responses/tool/web-search-preview.ts +103 -0
  343. package/src/provider/sdk/copilot/responses/tool/web-search.ts +102 -0
  344. package/src/provider/transform.ts +1051 -0
  345. package/src/pty/index.ts +397 -0
  346. package/src/pty/pty.bun.ts +26 -0
  347. package/src/pty/pty.node.ts +27 -0
  348. package/src/pty/pty.ts +25 -0
  349. package/src/pty/schema.ts +17 -0
  350. package/src/question/index.ts +224 -0
  351. package/src/question/schema.ts +17 -0
  352. package/src/runtime/adapters/acp/index.ts +127 -0
  353. package/src/runtime/adapters/local/index.ts +6 -0
  354. package/src/runtime/core/agent.ts +13 -0
  355. package/src/runtime/core/mcp.ts +10 -0
  356. package/src/runtime/core/ports.ts +16 -0
  357. package/src/runtime/core/service.ts +19 -0
  358. package/src/runtime/core/session-summarize.ts +52 -0
  359. package/src/runtime/core/session.ts +110 -0
  360. package/src/runtime/core/skill.ts +10 -0
  361. package/src/runtime/core/transport.ts +10 -0
  362. package/src/runtime/factory.ts +20 -0
  363. package/src/runtime/ports.ts +74 -0
  364. package/src/server/error.ts +36 -0
  365. package/src/server/event.ts +7 -0
  366. package/src/server/instance.ts +322 -0
  367. package/src/server/mdns.ts +60 -0
  368. package/src/server/middleware.ts +33 -0
  369. package/src/server/projectors.ts +28 -0
  370. package/src/server/proxy.ts +134 -0
  371. package/src/server/router.ts +161 -0
  372. package/src/server/routes/config.ts +92 -0
  373. package/src/server/routes/event.ts +83 -0
  374. package/src/server/routes/experimental.ts +379 -0
  375. package/src/server/routes/file.ts +197 -0
  376. package/src/server/routes/global.ts +312 -0
  377. package/src/server/routes/mcp.ts +226 -0
  378. package/src/server/routes/permission.ts +69 -0
  379. package/src/server/routes/project.ts +118 -0
  380. package/src/server/routes/provider.ts +171 -0
  381. package/src/server/routes/pty.ts +210 -0
  382. package/src/server/routes/question.ts +99 -0
  383. package/src/server/routes/session.ts +1011 -0
  384. package/src/server/routes/tui.ts +379 -0
  385. package/src/server/routes/workspace.ts +94 -0
  386. package/src/server/server.ts +367 -0
  387. package/src/session/compaction.ts +425 -0
  388. package/src/session/index.ts +887 -0
  389. package/src/session/instruction.ts +258 -0
  390. package/src/session/llm.ts +412 -0
  391. package/src/session/message-v2.ts +1038 -0
  392. package/src/session/message.ts +191 -0
  393. package/src/session/overflow.ts +22 -0
  394. package/src/session/processor.ts +515 -0
  395. package/src/session/projectors.ts +135 -0
  396. package/src/session/prompt/anthropic.txt +105 -0
  397. package/src/session/prompt/beast.txt +147 -0
  398. package/src/session/prompt/build-switch.txt +5 -0
  399. package/src/session/prompt/codex.txt +79 -0
  400. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  401. package/src/session/prompt/default.txt +105 -0
  402. package/src/session/prompt/gemini.txt +155 -0
  403. package/src/session/prompt/gpt.txt +107 -0
  404. package/src/session/prompt/kimi.txt +95 -0
  405. package/src/session/prompt/max-steps.txt +16 -0
  406. package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  407. package/src/session/prompt/plan.txt +26 -0
  408. package/src/session/prompt/trinity.txt +97 -0
  409. package/src/session/prompt.ts +1908 -0
  410. package/src/session/retry.ts +123 -0
  411. package/src/session/revert.ts +176 -0
  412. package/src/session/schema.ts +38 -0
  413. package/src/session/session.sql.ts +103 -0
  414. package/src/session/status.ts +102 -0
  415. package/src/session/summary.ts +177 -0
  416. package/src/session/system.ts +76 -0
  417. package/src/session/todo.ts +95 -0
  418. package/src/share/share-next.ts +370 -0
  419. package/src/share/share.sql.ts +13 -0
  420. package/src/shell/shell.ts +110 -0
  421. package/src/skill/discovery.ts +116 -0
  422. package/src/skill/index.ts +289 -0
  423. package/src/snapshot/index.ts +723 -0
  424. package/src/sql.d.ts +4 -0
  425. package/src/storage/db.bun.ts +8 -0
  426. package/src/storage/db.node.ts +8 -0
  427. package/src/storage/db.ts +174 -0
  428. package/src/storage/json-migration.ts +425 -0
  429. package/src/storage/schema.sql.ts +10 -0
  430. package/src/storage/schema.ts +5 -0
  431. package/src/storage/storage.ts +353 -0
  432. package/src/sync/README.md +179 -0
  433. package/src/sync/event.sql.ts +16 -0
  434. package/src/sync/index.ts +263 -0
  435. package/src/sync/schema.ts +14 -0
  436. package/src/testing/llm-server.ts +2 -0
  437. package/src/tool/apply_patch.ts +279 -0
  438. package/src/tool/apply_patch.txt +33 -0
  439. package/src/tool/bash.ts +498 -0
  440. package/src/tool/bash.txt +117 -0
  441. package/src/tool/codesearch.ts +133 -0
  442. package/src/tool/codesearch.txt +12 -0
  443. package/src/tool/edit.ts +666 -0
  444. package/src/tool/edit.txt +10 -0
  445. package/src/tool/external-directory.ts +46 -0
  446. package/src/tool/glob.ts +78 -0
  447. package/src/tool/glob.txt +6 -0
  448. package/src/tool/grep.ts +156 -0
  449. package/src/tool/grep.txt +8 -0
  450. package/src/tool/invalid.ts +17 -0
  451. package/src/tool/ls.ts +121 -0
  452. package/src/tool/ls.txt +1 -0
  453. package/src/tool/lsp.ts +97 -0
  454. package/src/tool/lsp.txt +19 -0
  455. package/src/tool/multiedit.ts +46 -0
  456. package/src/tool/multiedit.txt +41 -0
  457. package/src/tool/plan-enter.txt +14 -0
  458. package/src/tool/plan-exit.txt +13 -0
  459. package/src/tool/plan.ts +131 -0
  460. package/src/tool/question.ts +46 -0
  461. package/src/tool/question.txt +10 -0
  462. package/src/tool/read.ts +330 -0
  463. package/src/tool/read.txt +14 -0
  464. package/src/tool/registry.ts +303 -0
  465. package/src/tool/schema.ts +17 -0
  466. package/src/tool/skill.ts +120 -0
  467. package/src/tool/task.ts +192 -0
  468. package/src/tool/task.txt +57 -0
  469. package/src/tool/todo.ts +48 -0
  470. package/src/tool/todowrite.txt +167 -0
  471. package/src/tool/tool.ts +137 -0
  472. package/src/tool/truncate.ts +144 -0
  473. package/src/tool/truncation-dir.ts +4 -0
  474. package/src/tool/webfetch.ts +210 -0
  475. package/src/tool/webfetch.txt +13 -0
  476. package/src/tool/websearch.ts +151 -0
  477. package/src/tool/websearch.txt +14 -0
  478. package/src/tool/write.ts +84 -0
  479. package/src/tool/write.txt +8 -0
  480. package/src/url/site.ts +118 -0
  481. package/src/util/abort.ts +35 -0
  482. package/src/util/archive.ts +17 -0
  483. package/src/util/color.ts +19 -0
  484. package/src/util/context.ts +25 -0
  485. package/src/util/data-url.ts +9 -0
  486. package/src/util/defer.ts +12 -0
  487. package/src/util/effect-http-client.ts +11 -0
  488. package/src/util/effect-zod.ts +98 -0
  489. package/src/util/error.ts +77 -0
  490. package/src/util/filesystem.ts +245 -0
  491. package/src/util/flock.ts +333 -0
  492. package/src/util/fn.ts +21 -0
  493. package/src/util/format.ts +20 -0
  494. package/src/util/glob.ts +34 -0
  495. package/src/util/hash.ts +7 -0
  496. package/src/util/iife.ts +3 -0
  497. package/src/util/keybind.ts +103 -0
  498. package/src/util/lazy.ts +23 -0
  499. package/src/util/locale.ts +81 -0
  500. package/src/util/lock.ts +98 -0
  501. package/src/util/log.ts +182 -0
  502. package/src/util/network.ts +9 -0
  503. package/src/util/process.ts +176 -0
  504. package/src/util/queue.ts +32 -0
  505. package/src/util/record.ts +3 -0
  506. package/src/util/rpc.ts +66 -0
  507. package/src/util/schema.ts +53 -0
  508. package/src/util/scrap.ts +10 -0
  509. package/src/util/signal.ts +12 -0
  510. package/src/util/timeout.ts +14 -0
  511. package/src/util/token.ts +7 -0
  512. package/src/util/update-schema.ts +13 -0
  513. package/src/util/which.ts +14 -0
  514. package/src/util/wildcard.ts +59 -0
  515. package/src/worktree/index.ts +612 -0
  516. package/sst-env.d.ts +10 -0
  517. package/test/AGENTS.md +81 -0
  518. package/test/account/repo.test.ts +352 -0
  519. package/test/account/service.test.ts +456 -0
  520. package/test/acp/agent-interface.test.ts +51 -0
  521. package/test/acp/event-subscription.test.ts +685 -0
  522. package/test/agent/agent.test.ts +717 -0
  523. package/test/auth/auth.test.ts +58 -0
  524. package/test/bus/bus-effect.test.ts +164 -0
  525. package/test/bus/bus-integration.test.ts +87 -0
  526. package/test/bus/bus.test.ts +219 -0
  527. package/test/cli/account.test.ts +26 -0
  528. package/test/cli/cmd/tui/prompt-part.test.ts +47 -0
  529. package/test/cli/commands.test.ts +49 -0
  530. package/test/cli/error.test.ts +18 -0
  531. package/test/cli/github-action.test.ts +198 -0
  532. package/test/cli/github-remote.test.ts +80 -0
  533. package/test/cli/import.test.ts +54 -0
  534. package/test/cli/llm-ready.test.ts +49 -0
  535. package/test/cli/plugin-auth-picker.test.ts +120 -0
  536. package/test/cli/tui/keybind-plugin.test.ts +90 -0
  537. package/test/cli/tui/plugin-add.test.ts +107 -0
  538. package/test/cli/tui/plugin-install.test.ts +89 -0
  539. package/test/cli/tui/plugin-lifecycle.test.ts +225 -0
  540. package/test/cli/tui/plugin-loader-entrypoint.test.ts +492 -0
  541. package/test/cli/tui/plugin-loader-pure.test.ts +72 -0
  542. package/test/cli/tui/plugin-loader.test.ts +752 -0
  543. package/test/cli/tui/plugin-toggle.test.ts +159 -0
  544. package/test/cli/tui/slot-replace.test.tsx +47 -0
  545. package/test/cli/tui/theme-store.test.ts +51 -0
  546. package/test/cli/tui/thread.test.ts +128 -0
  547. package/test/cli/tui/transcript.test.ts +426 -0
  548. package/test/config/agent-color.test.ts +71 -0
  549. package/test/config/config.test.ts +2364 -0
  550. package/test/config/fixtures/empty-frontmatter.md +4 -0
  551. package/test/config/fixtures/frontmatter.md +28 -0
  552. package/test/config/fixtures/markdown-header.md +11 -0
  553. package/test/config/fixtures/no-frontmatter.md +1 -0
  554. package/test/config/fixtures/weird-model-id.md +13 -0
  555. package/test/config/markdown.test.ts +228 -0
  556. package/test/config/tui.test.ts +800 -0
  557. package/test/control-plane/sse.test.ts +56 -0
  558. package/test/effect/cross-spawn-spawner.test.ts +412 -0
  559. package/test/effect/instance-state.test.ts +482 -0
  560. package/test/effect/run-service.test.ts +46 -0
  561. package/test/effect/runner.test.ts +523 -0
  562. package/test/fake/provider.ts +81 -0
  563. package/test/file/fsmonitor.test.ts +62 -0
  564. package/test/file/ignore.test.ts +10 -0
  565. package/test/file/index.test.ts +946 -0
  566. package/test/file/path-traversal.test.ts +198 -0
  567. package/test/file/ripgrep.test.ts +54 -0
  568. package/test/file/time.test.ts +445 -0
  569. package/test/file/watcher.test.ts +247 -0
  570. package/test/filesystem/filesystem.test.ts +319 -0
  571. package/test/fixture/db.ts +11 -0
  572. package/test/fixture/fixture.test.ts +26 -0
  573. package/test/fixture/fixture.ts +174 -0
  574. package/test/fixture/flock-worker.ts +72 -0
  575. package/test/fixture/lsp/fake-lsp-server.js +77 -0
  576. package/test/fixture/plug-worker.ts +93 -0
  577. package/test/fixture/plugin-meta-worker.ts +26 -0
  578. package/test/fixture/skills/agents-sdk/SKILL.md +152 -0
  579. package/test/fixture/skills/agents-sdk/references/callable.md +92 -0
  580. package/test/fixture/skills/cloudflare/SKILL.md +211 -0
  581. package/test/fixture/skills/index.json +6 -0
  582. package/test/fixture/tui-plugin.ts +328 -0
  583. package/test/fixture/tui-runtime.ts +27 -0
  584. package/test/format/format.test.ts +171 -0
  585. package/test/git/git.test.ts +128 -0
  586. package/test/ide/ide.test.ts +82 -0
  587. package/test/installation/installation.test.ts +151 -0
  588. package/test/keybind.test.ts +421 -0
  589. package/test/lib/effect.ts +53 -0
  590. package/test/lib/filesystem.ts +10 -0
  591. package/test/lib/llm-server.ts +795 -0
  592. package/test/lsp/client.test.ts +95 -0
  593. package/test/lsp/index.test.ts +138 -0
  594. package/test/lsp/launch.test.ts +22 -0
  595. package/test/lsp/lifecycle.test.ts +147 -0
  596. package/test/mcp/headers.test.ts +153 -0
  597. package/test/mcp/lifecycle.test.ts +750 -0
  598. package/test/mcp/oauth-auto-connect.test.ts +199 -0
  599. package/test/mcp/oauth-browser.test.ts +249 -0
  600. package/test/memory/abort-leak.test.ts +151 -0
  601. package/test/npm.test.ts +18 -0
  602. package/test/patch/patch.test.ts +348 -0
  603. package/test/permission/arity.test.ts +33 -0
  604. package/test/permission/next.test.ts +1148 -0
  605. package/test/permission-task.test.ts +323 -0
  606. package/test/plugin/auth-override.test.ts +74 -0
  607. package/test/plugin/codex.test.ts +123 -0
  608. package/test/plugin/github-copilot-models.test.ts +117 -0
  609. package/test/plugin/install-concurrency.test.ts +140 -0
  610. package/test/plugin/install.test.ts +570 -0
  611. package/test/plugin/loader-shared.test.ts +1136 -0
  612. package/test/plugin/meta.test.ts +137 -0
  613. package/test/plugin/shared.test.ts +88 -0
  614. package/test/plugin/trigger.test.ts +111 -0
  615. package/test/preload.ts +90 -0
  616. package/test/project/migrate-global.test.ts +141 -0
  617. package/test/project/project.test.ts +459 -0
  618. package/test/project/state.test.ts +115 -0
  619. package/test/project/vcs.test.ts +228 -0
  620. package/test/project/worktree-remove.test.ts +96 -0
  621. package/test/project/worktree.test.ts +173 -0
  622. package/test/provider/amazon-bedrock.test.ts +447 -0
  623. package/test/provider/copilot/convert-to-copilot-messages.test.ts +523 -0
  624. package/test/provider/copilot/copilot-chat-model.test.ts +592 -0
  625. package/test/provider/gitlab-duo.test.ts +412 -0
  626. package/test/provider/provider.test.ts +2494 -0
  627. package/test/provider/transform.test.ts +2839 -0
  628. package/test/pty/pty-output-isolation.test.ts +141 -0
  629. package/test/pty/pty-session.test.ts +92 -0
  630. package/test/pty/pty-shell.test.ts +59 -0
  631. package/test/question/question.test.ts +453 -0
  632. package/test/runtime/acp-adapter.test.ts +84 -0
  633. package/test/runtime/core-service.test.ts +16 -0
  634. package/test/runtime/session-summarize.test.ts +104 -0
  635. package/test/server/global-session-list.test.ts +89 -0
  636. package/test/server/project-init-git.test.ts +121 -0
  637. package/test/server/router.test.ts +52 -0
  638. package/test/server/session-actions.test.ts +83 -0
  639. package/test/server/session-list.test.ts +98 -0
  640. package/test/server/session-messages.test.ts +159 -0
  641. package/test/server/session-select.test.ts +84 -0
  642. package/test/session/compaction.test.ts +1239 -0
  643. package/test/session/instruction.test.ts +286 -0
  644. package/test/session/llm.test.ts +1093 -0
  645. package/test/session/message-v2.test.ts +957 -0
  646. package/test/session/messages-pagination.test.ts +885 -0
  647. package/test/session/processor-effect.test.ts +741 -0
  648. package/test/session/prompt-effect.test.ts +1339 -0
  649. package/test/session/prompt.test.ts +533 -0
  650. package/test/session/retry.test.ts +251 -0
  651. package/test/session/revert-compact.test.ts +621 -0
  652. package/test/session/session.test.ts +142 -0
  653. package/test/session/snapshot-tool-race.test.ts +242 -0
  654. package/test/session/structured-output-integration.test.ts +233 -0
  655. package/test/session/structured-output.test.ts +391 -0
  656. package/test/session/system.test.ts +59 -0
  657. package/test/share/share-next.test.ts +332 -0
  658. package/test/shell/shell.test.ts +73 -0
  659. package/test/skill/discovery.test.ts +116 -0
  660. package/test/skill/skill.test.ts +428 -0
  661. package/test/snapshot/snapshot.test.ts +1397 -0
  662. package/test/storage/db.test.ts +14 -0
  663. package/test/storage/json-migration.test.ts +832 -0
  664. package/test/storage/storage.test.ts +295 -0
  665. package/test/sync/index.test.ts +191 -0
  666. package/test/tool/apply_patch.test.ts +565 -0
  667. package/test/tool/bash.test.ts +1099 -0
  668. package/test/tool/edit.test.ts +681 -0
  669. package/test/tool/external-directory.test.ts +198 -0
  670. package/test/tool/fixtures/large-image.png +0 -0
  671. package/test/tool/fixtures/models-api.json +65179 -0
  672. package/test/tool/grep.test.ts +111 -0
  673. package/test/tool/question.test.ts +126 -0
  674. package/test/tool/read.test.ts +468 -0
  675. package/test/tool/registry.test.ts +157 -0
  676. package/test/tool/skill.test.ts +170 -0
  677. package/test/tool/task.test.ts +412 -0
  678. package/test/tool/tool-define.test.ts +49 -0
  679. package/test/tool/truncation.test.ts +161 -0
  680. package/test/tool/webfetch.test.ts +96 -0
  681. package/test/tool/write.test.ts +353 -0
  682. package/test/util/data-url.test.ts +14 -0
  683. package/test/util/effect-zod.test.ts +61 -0
  684. package/test/util/error.test.ts +38 -0
  685. package/test/util/filesystem.test.ts +656 -0
  686. package/test/util/flock.test.ts +383 -0
  687. package/test/util/format.test.ts +59 -0
  688. package/test/util/glob.test.ts +164 -0
  689. package/test/util/iife.test.ts +36 -0
  690. package/test/util/lazy.test.ts +50 -0
  691. package/test/util/lock.test.ts +72 -0
  692. package/test/util/module.test.ts +59 -0
  693. package/test/util/process.test.ts +128 -0
  694. package/test/util/timeout.test.ts +21 -0
  695. package/test/util/which.test.ts +100 -0
  696. package/test/util/wildcard.test.ts +90 -0
  697. package/tsconfig.json +23 -0
@@ -0,0 +1,1659 @@
1
+ import { Log } from "../util/log"
2
+ import path from "path"
3
+ import { pathToFileURL } from "url"
4
+ import os from "os"
5
+ import { Process } from "../util/process"
6
+ import z from "zod"
7
+ import { ModelsDev } from "../provider/models"
8
+ import { mergeDeep, pipe, unique } from "remeda"
9
+ import { Global } from "../global"
10
+ import fsNode from "fs/promises"
11
+ import { NamedError } from "@happy-creative/util/error"
12
+ import { Flag } from "../flag/flag"
13
+ import { Auth } from "../auth"
14
+ import { Env } from "../env"
15
+ import {
16
+ type ParseError as JsoncParseError,
17
+ applyEdits,
18
+ modify,
19
+ parse as parseJsonc,
20
+ printParseErrorCode,
21
+ } from "jsonc-parser"
22
+ import { Instance, type InstanceContext } from "../project/instance"
23
+ import { LSPServer } from "../lsp/server"
24
+ import { Installation } from "@/installation"
25
+ import { ConfigMarkdown } from "./markdown"
26
+ import { constants, existsSync } from "fs"
27
+ import { Bus } from "@/bus"
28
+ import { GlobalBus } from "@/bus/global"
29
+ import { Event } from "../server/event"
30
+ import { Glob } from "../util/glob"
31
+ import { iife } from "@/util/iife"
32
+ import { Account } from "@/account"
33
+ import { isRecord } from "@/util/record"
34
+ import { ConfigPaths } from "./paths"
35
+ import { Filesystem } from "@/util/filesystem"
36
+ import type { ConsoleState } from "./console-state"
37
+ import { AppFileSystem } from "@/filesystem"
38
+ import { InstanceState } from "@/effect/instance-state"
39
+ import { makeRuntime } from "@/effect/run-service"
40
+ import { Duration, Effect, Layer, Option, ServiceMap } from "effect"
41
+ import { Flock } from "@/util/flock"
42
+ import { isPathPluginSpec, parsePluginSpecifier, resolvePathPluginTarget } from "@/plugin/shared"
43
+ import { Npm } from "@/npm"
44
+ import { Site } from "@/url/site"
45
+
46
+ export namespace Config {
47
+ const ModelId = z.string().meta({ $ref: Site.modelSchema() })
48
+ const PluginOptions = z.record(z.string(), z.unknown())
49
+ export const PluginSpec = z.union([z.string(), z.tuple([z.string(), PluginOptions])])
50
+
51
+ export type PluginOptions = z.infer<typeof PluginOptions>
52
+ export type PluginSpec = z.infer<typeof PluginSpec>
53
+ export type PluginScope = "global" | "local"
54
+ export type PluginOrigin = {
55
+ spec: PluginSpec
56
+ source: string
57
+ scope: PluginScope
58
+ }
59
+
60
+ const log = Log.create({ service: "config" })
61
+
62
+ // Managed settings directory for enterprise deployments (highest priority, admin-controlled)
63
+ // These settings override all user and project settings
64
+ function systemManagedConfigDir(): string {
65
+ switch (process.platform) {
66
+ case "darwin":
67
+ return "/Library/Application Support/iroder"
68
+ case "win32":
69
+ return path.join(process.env.ProgramData || "C:\\ProgramData", "iroder")
70
+ default:
71
+ return "/etc/iroder"
72
+ }
73
+ }
74
+
75
+ export function managedConfigDir() {
76
+ return process.env.IRODER_TEST_MANAGED_CONFIG_DIR || systemManagedConfigDir()
77
+ }
78
+
79
+ const managedDir = managedConfigDir()
80
+
81
+ const MANAGED_PLIST_DOMAIN = "ai.iroder.managed"
82
+
83
+ // Keys injected by macOS/MDM into the managed plist that are not Iroder config
84
+ const PLIST_META = new Set([
85
+ "PayloadDisplayName",
86
+ "PayloadIdentifier",
87
+ "PayloadType",
88
+ "PayloadUUID",
89
+ "PayloadVersion",
90
+ "_manualProfile",
91
+ ])
92
+
93
+ /**
94
+ * Parse raw JSON (from plutil conversion of a managed plist) into Iroder config.
95
+ * Strips MDM metadata keys before parsing through the config schema.
96
+ * Pure function — no OS interaction, safe to unit test directly.
97
+ */
98
+ export function parseManagedPlist(json: string, source: string): Info {
99
+ const raw = JSON.parse(json)
100
+ for (const key of Object.keys(raw)) {
101
+ if (PLIST_META.has(key)) delete raw[key]
102
+ }
103
+ return parseConfig(JSON.stringify(raw), source)
104
+ }
105
+
106
+ /**
107
+ * Read macOS managed preferences deployed via .mobileconfig / MDM (Jamf, Kandji, etc).
108
+ * MDM-installed profiles write to /Library/Managed Preferences/ which is only writable by root.
109
+ * User-scoped plists are checked first, then machine-scoped.
110
+ */
111
+ async function readManagedPreferences(): Promise<Info> {
112
+ if (process.platform !== "darwin") return {}
113
+
114
+ const domain = MANAGED_PLIST_DOMAIN
115
+ const user = os.userInfo().username
116
+ const paths = [
117
+ path.join("/Library/Managed Preferences", user, `${domain}.plist`),
118
+ path.join("/Library/Managed Preferences", `${domain}.plist`),
119
+ ]
120
+
121
+ for (const plist of paths) {
122
+ if (!existsSync(plist)) continue
123
+ log.info("reading macOS managed preferences", { path: plist })
124
+ const result = await Process.run(["plutil", "-convert", "json", "-o", "-", plist], { nothrow: true })
125
+ if (result.code !== 0) {
126
+ log.warn("failed to convert managed preferences plist", { path: plist })
127
+ continue
128
+ }
129
+ return parseManagedPlist(result.stdout.toString(), `mobileconfig:${plist}`)
130
+ }
131
+ return {}
132
+ }
133
+
134
+ // Custom merge function that concatenates array fields instead of replacing them
135
+ function mergeConfigConcatArrays(target: Info, source: Info): Info {
136
+ const merged = mergeDeep(target, source)
137
+ if (target.instructions && source.instructions) {
138
+ merged.instructions = Array.from(new Set([...target.instructions, ...source.instructions]))
139
+ }
140
+ return merged
141
+ }
142
+
143
+ export type InstallInput = {
144
+ signal?: AbortSignal
145
+ waitTick?: (input: { dir: string; attempt: number; delay: number; waited: number }) => void | Promise<void>
146
+ }
147
+
148
+ export async function installDependencies(dir: string, input?: InstallInput) {
149
+ if (!(await isWritable(dir))) return
150
+ await using _ = await Flock.acquire(`config-install:${Filesystem.resolve(dir)}`, {
151
+ signal: input?.signal,
152
+ onWait: (tick) =>
153
+ input?.waitTick?.({
154
+ dir,
155
+ attempt: tick.attempt,
156
+ delay: tick.delay,
157
+ waited: tick.waited,
158
+ }),
159
+ })
160
+ input?.signal?.throwIfAborted()
161
+
162
+ const pkg = path.join(dir, "package.json")
163
+ const target = Installation.isLocal() ? "*" : Installation.VERSION
164
+ const json = await Filesystem.readJson<{ dependencies?: Record<string, string> }>(pkg).catch(() => ({
165
+ dependencies: {},
166
+ }))
167
+ json.dependencies = {
168
+ ...json.dependencies,
169
+ "@happy-creative/plugin": target,
170
+ }
171
+ await Filesystem.writeJson(pkg, json)
172
+
173
+ const gitignore = path.join(dir, ".gitignore")
174
+ const ignore = await Filesystem.exists(gitignore)
175
+ if (!ignore) {
176
+ await Filesystem.write(
177
+ gitignore,
178
+ ["node_modules", "package.json", "package-lock.json", "bun.lock", ".gitignore"].join("\n"),
179
+ )
180
+ }
181
+ await Npm.install(dir)
182
+ }
183
+
184
+ async function isWritable(dir: string) {
185
+ try {
186
+ await fsNode.access(dir, constants.W_OK)
187
+ return true
188
+ } catch {
189
+ return false
190
+ }
191
+ }
192
+
193
+ function rel(item: string, patterns: string[]) {
194
+ const normalizedItem = item.replaceAll("\\", "/")
195
+ for (const pattern of patterns) {
196
+ const index = normalizedItem.indexOf(pattern)
197
+ if (index === -1) continue
198
+ return normalizedItem.slice(index + pattern.length)
199
+ }
200
+ }
201
+
202
+ function trim(file: string) {
203
+ const ext = path.extname(file)
204
+ return ext.length ? file.slice(0, -ext.length) : file
205
+ }
206
+
207
+ async function loadCommand(dir: string) {
208
+ const result: Record<string, Command> = {}
209
+ for (const item of await Glob.scan("{command,commands}/**/*.md", {
210
+ cwd: dir,
211
+ absolute: true,
212
+ dot: true,
213
+ symlink: true,
214
+ })) {
215
+ const md = await ConfigMarkdown.parse(item).catch(async (err) => {
216
+ const message = ConfigMarkdown.FrontmatterError.isInstance(err)
217
+ ? err.data.message
218
+ : `Failed to parse command ${item}`
219
+ const { Session } = await import("@/session")
220
+ Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })
221
+ log.error("failed to load command", { command: item, err })
222
+ return undefined
223
+ })
224
+ if (!md) continue
225
+
226
+ const patterns = ["/.iroder/command/", "/.iroder/commands/", "/command/", "/commands/"]
227
+ const file = rel(item, patterns) ?? path.basename(item)
228
+ const name = trim(file)
229
+
230
+ const config = {
231
+ name,
232
+ ...md.data,
233
+ template: md.content.trim(),
234
+ }
235
+ const parsed = Command.safeParse(config)
236
+ if (parsed.success) {
237
+ result[config.name] = parsed.data
238
+ continue
239
+ }
240
+ throw new InvalidError({ path: item, issues: parsed.error.issues }, { cause: parsed.error })
241
+ }
242
+ return result
243
+ }
244
+
245
+ async function loadAgent(dir: string) {
246
+ const result: Record<string, Agent> = {}
247
+
248
+ for (const item of await Glob.scan("{agent,agents}/**/*.md", {
249
+ cwd: dir,
250
+ absolute: true,
251
+ dot: true,
252
+ symlink: true,
253
+ })) {
254
+ const md = await ConfigMarkdown.parse(item).catch(async (err) => {
255
+ const message = ConfigMarkdown.FrontmatterError.isInstance(err)
256
+ ? err.data.message
257
+ : `Failed to parse agent ${item}`
258
+ const { Session } = await import("@/session")
259
+ Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })
260
+ log.error("failed to load agent", { agent: item, err })
261
+ return undefined
262
+ })
263
+ if (!md) continue
264
+
265
+ const patterns = ["/.iroder/agent/", "/.iroder/agents/", "/agent/", "/agents/"]
266
+ const file = rel(item, patterns) ?? path.basename(item)
267
+ const agentName = trim(file)
268
+
269
+ const config = {
270
+ name: agentName,
271
+ ...md.data,
272
+ prompt: md.content.trim(),
273
+ }
274
+ const parsed = Agent.safeParse(config)
275
+ if (parsed.success) {
276
+ result[config.name] = parsed.data
277
+ continue
278
+ }
279
+ throw new InvalidError({ path: item, issues: parsed.error.issues }, { cause: parsed.error })
280
+ }
281
+ return result
282
+ }
283
+
284
+ async function loadMode(dir: string) {
285
+ const result: Record<string, Agent> = {}
286
+ for (const item of await Glob.scan("{mode,modes}/*.md", {
287
+ cwd: dir,
288
+ absolute: true,
289
+ dot: true,
290
+ symlink: true,
291
+ })) {
292
+ const md = await ConfigMarkdown.parse(item).catch(async (err) => {
293
+ const message = ConfigMarkdown.FrontmatterError.isInstance(err)
294
+ ? err.data.message
295
+ : `Failed to parse mode ${item}`
296
+ const { Session } = await import("@/session")
297
+ Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })
298
+ log.error("failed to load mode", { mode: item, err })
299
+ return undefined
300
+ })
301
+ if (!md) continue
302
+
303
+ const config = {
304
+ name: path.basename(item, ".md"),
305
+ ...md.data,
306
+ prompt: md.content.trim(),
307
+ }
308
+ const parsed = Agent.safeParse(config)
309
+ if (parsed.success) {
310
+ result[config.name] = {
311
+ ...parsed.data,
312
+ mode: "primary" as const,
313
+ }
314
+ continue
315
+ }
316
+ }
317
+ return result
318
+ }
319
+
320
+ async function loadPlugin(dir: string) {
321
+ const plugins: PluginSpec[] = []
322
+
323
+ for (const item of await Glob.scan("{plugin,plugins}/*.{ts,js}", {
324
+ cwd: dir,
325
+ absolute: true,
326
+ dot: true,
327
+ symlink: true,
328
+ })) {
329
+ plugins.push(pathToFileURL(item).href)
330
+ }
331
+ return plugins
332
+ }
333
+
334
+ export function pluginSpecifier(plugin: PluginSpec): string {
335
+ return Array.isArray(plugin) ? plugin[0] : plugin
336
+ }
337
+
338
+ export function pluginOptions(plugin: PluginSpec): PluginOptions | undefined {
339
+ return Array.isArray(plugin) ? plugin[1] : undefined
340
+ }
341
+
342
+ export async function resolvePluginSpec(plugin: PluginSpec, configFilepath: string): Promise<PluginSpec> {
343
+ const spec = pluginSpecifier(plugin)
344
+ if (!isPathPluginSpec(spec)) return plugin
345
+
346
+ const base = path.dirname(configFilepath)
347
+ const file = (() => {
348
+ if (spec.startsWith("file://")) return spec
349
+ if (path.isAbsolute(spec) || /^[A-Za-z]:[\\/]/.test(spec)) return pathToFileURL(spec).href
350
+ return pathToFileURL(path.resolve(base, spec)).href
351
+ })()
352
+
353
+ const resolved = await resolvePathPluginTarget(file).catch(() => file)
354
+
355
+ if (Array.isArray(plugin)) return [resolved, plugin[1]]
356
+ return resolved
357
+ }
358
+
359
+ export function deduplicatePluginOrigins(plugins: PluginOrigin[]): PluginOrigin[] {
360
+ const seen = new Set<string>()
361
+ const list: PluginOrigin[] = []
362
+
363
+ for (const plugin of plugins.toReversed()) {
364
+ const spec = pluginSpecifier(plugin.spec)
365
+ const name = spec.startsWith("file://") ? spec : parsePluginSpecifier(spec).pkg
366
+ if (seen.has(name)) continue
367
+ seen.add(name)
368
+ list.push(plugin)
369
+ }
370
+
371
+ return list.toReversed()
372
+ }
373
+
374
+ export const McpLocal = z
375
+ .object({
376
+ type: z.literal("local").describe("Type of MCP server connection"),
377
+ command: z.string().array().describe("Command and arguments to run the MCP server"),
378
+ environment: z
379
+ .record(z.string(), z.string())
380
+ .optional()
381
+ .describe("Environment variables to set when running the MCP server"),
382
+ enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"),
383
+ timeout: z
384
+ .number()
385
+ .int()
386
+ .positive()
387
+ .optional()
388
+ .describe("Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."),
389
+ })
390
+ .strict()
391
+ .meta({
392
+ ref: "McpLocalConfig",
393
+ })
394
+
395
+ export const McpOAuth = z
396
+ .object({
397
+ clientId: z
398
+ .string()
399
+ .optional()
400
+ .describe("OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted."),
401
+ clientSecret: z.string().optional().describe("OAuth client secret (if required by the authorization server)"),
402
+ scope: z.string().optional().describe("OAuth scopes to request during authorization"),
403
+ })
404
+ .strict()
405
+ .meta({
406
+ ref: "McpOAuthConfig",
407
+ })
408
+ export type McpOAuth = z.infer<typeof McpOAuth>
409
+
410
+ export const McpRemote = z
411
+ .object({
412
+ type: z.literal("remote").describe("Type of MCP server connection"),
413
+ url: z.string().describe("URL of the remote MCP server"),
414
+ enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"),
415
+ headers: z.record(z.string(), z.string()).optional().describe("Headers to send with the request"),
416
+ oauth: z
417
+ .union([McpOAuth, z.literal(false)])
418
+ .optional()
419
+ .describe(
420
+ "OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection.",
421
+ ),
422
+ timeout: z
423
+ .number()
424
+ .int()
425
+ .positive()
426
+ .optional()
427
+ .describe("Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."),
428
+ })
429
+ .strict()
430
+ .meta({
431
+ ref: "McpRemoteConfig",
432
+ })
433
+
434
+ export const Mcp = z.discriminatedUnion("type", [McpLocal, McpRemote])
435
+ export type Mcp = z.infer<typeof Mcp>
436
+
437
+ export const PermissionAction = z.enum(["ask", "allow", "deny"]).meta({
438
+ ref: "PermissionActionConfig",
439
+ })
440
+ export type PermissionAction = z.infer<typeof PermissionAction>
441
+
442
+ export const PermissionObject = z.record(z.string(), PermissionAction).meta({
443
+ ref: "PermissionObjectConfig",
444
+ })
445
+ export type PermissionObject = z.infer<typeof PermissionObject>
446
+
447
+ export const PermissionRule = z.union([PermissionAction, PermissionObject]).meta({
448
+ ref: "PermissionRuleConfig",
449
+ })
450
+ export type PermissionRule = z.infer<typeof PermissionRule>
451
+
452
+ // Capture original key order before zod reorders, then rebuild in original order
453
+ const permissionPreprocess = (val: unknown) => {
454
+ if (typeof val === "object" && val !== null && !Array.isArray(val)) {
455
+ return { __originalKeys: Object.keys(val), ...val }
456
+ }
457
+ return val
458
+ }
459
+
460
+ const permissionTransform = (x: unknown): Record<string, PermissionRule> => {
461
+ if (typeof x === "string") return { "*": x as PermissionAction }
462
+ const obj = x as { __originalKeys?: string[] } & Record<string, unknown>
463
+ const { __originalKeys, ...rest } = obj
464
+ if (!__originalKeys) return rest as Record<string, PermissionRule>
465
+ const result: Record<string, PermissionRule> = {}
466
+ for (const key of __originalKeys) {
467
+ if (key in rest) result[key] = rest[key] as PermissionRule
468
+ }
469
+ return result
470
+ }
471
+
472
+ export const Permission = z
473
+ .preprocess(
474
+ permissionPreprocess,
475
+ z
476
+ .object({
477
+ __originalKeys: z.string().array().optional(),
478
+ read: PermissionRule.optional(),
479
+ edit: PermissionRule.optional(),
480
+ glob: PermissionRule.optional(),
481
+ grep: PermissionRule.optional(),
482
+ list: PermissionRule.optional(),
483
+ bash: PermissionRule.optional(),
484
+ task: PermissionRule.optional(),
485
+ external_directory: PermissionRule.optional(),
486
+ todowrite: PermissionAction.optional(),
487
+ question: PermissionAction.optional(),
488
+ webfetch: PermissionAction.optional(),
489
+ websearch: PermissionAction.optional(),
490
+ codesearch: PermissionAction.optional(),
491
+ lsp: PermissionRule.optional(),
492
+ doom_loop: PermissionAction.optional(),
493
+ skill: PermissionRule.optional(),
494
+ })
495
+ .catchall(PermissionRule)
496
+ .or(PermissionAction),
497
+ )
498
+ .transform(permissionTransform)
499
+ .meta({
500
+ ref: "PermissionConfig",
501
+ })
502
+ export type Permission = z.infer<typeof Permission>
503
+
504
+ export const Command = z.object({
505
+ template: z.string(),
506
+ description: z.string().optional(),
507
+ agent: z.string().optional(),
508
+ model: ModelId.optional(),
509
+ subtask: z.boolean().optional(),
510
+ })
511
+ export type Command = z.infer<typeof Command>
512
+
513
+ export const Skills = z.object({
514
+ paths: z.array(z.string()).optional().describe("Additional paths to skill folders"),
515
+ urls: z
516
+ .array(z.string())
517
+ .optional()
518
+ .describe("URLs to fetch skills from (e.g., https://example.com/.well-known/skills/)"),
519
+ disabled: z.array(z.string()).optional().describe("Disable specific skills by name"),
520
+ })
521
+ export type Skills = z.infer<typeof Skills>
522
+
523
+ export const Agent = z
524
+ .object({
525
+ model: ModelId.optional(),
526
+ variant: z
527
+ .string()
528
+ .optional()
529
+ .describe("Default model variant for this agent (applies only when using the agent's configured model)."),
530
+ temperature: z.number().optional(),
531
+ top_p: z.number().optional(),
532
+ prompt: z.string().optional(),
533
+ tools: z.record(z.string(), z.boolean()).optional().describe("@deprecated Use 'permission' field instead"),
534
+ disable: z.boolean().optional(),
535
+ description: z.string().optional().describe("Description of when to use the agent"),
536
+ mode: z.enum(["subagent", "primary", "all"]).optional(),
537
+ hidden: z
538
+ .boolean()
539
+ .optional()
540
+ .describe("Hide this subagent from the @ autocomplete menu (default: false, only applies to mode: subagent)"),
541
+ options: z.record(z.string(), z.any()).optional(),
542
+ color: z
543
+ .union([
544
+ z.string().regex(/^#[0-9a-fA-F]{6}$/, "Invalid hex color format"),
545
+ z.enum(["primary", "secondary", "accent", "success", "warning", "error", "info"]),
546
+ ])
547
+ .optional()
548
+ .describe("Hex color code (e.g., #FF5733) or theme color (e.g., primary)"),
549
+ steps: z
550
+ .number()
551
+ .int()
552
+ .positive()
553
+ .optional()
554
+ .describe("Maximum number of agentic iterations before forcing text-only response"),
555
+ maxSteps: z.number().int().positive().optional().describe("@deprecated Use 'steps' field instead."),
556
+ permission: Permission.optional(),
557
+ })
558
+ .catchall(z.any())
559
+ .transform((agent, ctx) => {
560
+ const knownKeys = new Set([
561
+ "name",
562
+ "model",
563
+ "variant",
564
+ "prompt",
565
+ "description",
566
+ "temperature",
567
+ "top_p",
568
+ "mode",
569
+ "hidden",
570
+ "color",
571
+ "steps",
572
+ "maxSteps",
573
+ "options",
574
+ "permission",
575
+ "disable",
576
+ "tools",
577
+ ])
578
+
579
+ // Extract unknown properties into options
580
+ const options: Record<string, unknown> = { ...agent.options }
581
+ for (const [key, value] of Object.entries(agent)) {
582
+ if (!knownKeys.has(key)) options[key] = value
583
+ }
584
+
585
+ // Convert legacy tools config to permissions
586
+ const permission: Permission = {}
587
+ for (const [tool, enabled] of Object.entries(agent.tools ?? {})) {
588
+ const action = enabled ? "allow" : "deny"
589
+ // write, edit, patch, multiedit all map to edit permission
590
+ if (tool === "write" || tool === "edit" || tool === "patch" || tool === "multiedit") {
591
+ permission.edit = action
592
+ } else {
593
+ permission[tool] = action
594
+ }
595
+ }
596
+ Object.assign(permission, agent.permission)
597
+
598
+ // Convert legacy maxSteps to steps
599
+ const steps = agent.steps ?? agent.maxSteps
600
+
601
+ return { ...agent, options, permission, steps } as typeof agent & {
602
+ options?: Record<string, unknown>
603
+ permission?: Permission
604
+ steps?: number
605
+ }
606
+ })
607
+ .meta({
608
+ ref: "AgentConfig",
609
+ })
610
+ export type Agent = z.infer<typeof Agent>
611
+
612
+ export const Keybinds = z
613
+ .object({
614
+ leader: z.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"),
615
+ app_exit: z.string().optional().default("ctrl+c,ctrl+d,<leader>q").describe("Exit the application"),
616
+ editor_open: z.string().optional().default("<leader>e").describe("Open external editor"),
617
+ theme_list: z.string().optional().default("<leader>t").describe("List available themes"),
618
+ sidebar_toggle: z.string().optional().default("<leader>b").describe("Toggle sidebar"),
619
+ scrollbar_toggle: z.string().optional().default("none").describe("Toggle session scrollbar"),
620
+ username_toggle: z.string().optional().default("none").describe("Toggle username visibility"),
621
+ status_view: z.string().optional().default("<leader>s").describe("View status"),
622
+ session_export: z.string().optional().default("<leader>x").describe("Export session to editor"),
623
+ session_new: z.string().optional().default("<leader>n").describe("Create a new session"),
624
+ session_list: z.string().optional().default("<leader>l").describe("List all sessions"),
625
+ session_timeline: z.string().optional().default("<leader>g").describe("Show session timeline"),
626
+ session_fork: z.string().optional().default("none").describe("Fork session from message"),
627
+ session_rename: z.string().optional().default("ctrl+r").describe("Rename session"),
628
+ session_delete: z.string().optional().default("ctrl+d").describe("Delete session"),
629
+ stash_delete: z.string().optional().default("ctrl+d").describe("Delete stash entry"),
630
+ model_provider_list: z.string().optional().default("ctrl+a").describe("Open provider list from model dialog"),
631
+ model_favorite_toggle: z.string().optional().default("ctrl+f").describe("Toggle model favorite status"),
632
+ session_share: z.string().optional().default("none").describe("Share current session"),
633
+ session_unshare: z.string().optional().default("none").describe("Unshare current session"),
634
+ session_interrupt: z.string().optional().default("escape").describe("Interrupt current session"),
635
+ session_compact: z.string().optional().default("<leader>c").describe("Compact the session"),
636
+ messages_page_up: z.string().optional().default("pageup,ctrl+alt+b").describe("Scroll messages up by one page"),
637
+ messages_page_down: z
638
+ .string()
639
+ .optional()
640
+ .default("pagedown,ctrl+alt+f")
641
+ .describe("Scroll messages down by one page"),
642
+ messages_line_up: z.string().optional().default("ctrl+alt+y").describe("Scroll messages up by one line"),
643
+ messages_line_down: z.string().optional().default("ctrl+alt+e").describe("Scroll messages down by one line"),
644
+ messages_half_page_up: z.string().optional().default("ctrl+alt+u").describe("Scroll messages up by half page"),
645
+ messages_half_page_down: z
646
+ .string()
647
+ .optional()
648
+ .default("ctrl+alt+d")
649
+ .describe("Scroll messages down by half page"),
650
+ messages_first: z.string().optional().default("ctrl+g,home").describe("Navigate to first message"),
651
+ messages_last: z.string().optional().default("ctrl+alt+g,end").describe("Navigate to last message"),
652
+ messages_next: z.string().optional().default("none").describe("Navigate to next message"),
653
+ messages_previous: z.string().optional().default("none").describe("Navigate to previous message"),
654
+ messages_last_user: z.string().optional().default("none").describe("Navigate to last user message"),
655
+ messages_copy: z.string().optional().default("<leader>y").describe("Copy message"),
656
+ messages_undo: z.string().optional().default("<leader>u").describe("Undo message"),
657
+ messages_redo: z.string().optional().default("<leader>r").describe("Redo message"),
658
+ messages_toggle_conceal: z
659
+ .string()
660
+ .optional()
661
+ .default("<leader>h")
662
+ .describe("Toggle code block concealment in messages"),
663
+ tool_details: z.string().optional().default("none").describe("Toggle tool details visibility"),
664
+ model_list: z.string().optional().default("<leader>m").describe("List available models"),
665
+ model_cycle_recent: z.string().optional().default("f2").describe("Next recently used model"),
666
+ model_cycle_recent_reverse: z.string().optional().default("shift+f2").describe("Previous recently used model"),
667
+ model_cycle_favorite: z.string().optional().default("none").describe("Next favorite model"),
668
+ model_cycle_favorite_reverse: z.string().optional().default("none").describe("Previous favorite model"),
669
+ command_list: z.string().optional().default("ctrl+p").describe("List available commands"),
670
+ agent_list: z.string().optional().default("<leader>a").describe("List agents"),
671
+ agent_cycle: z.string().optional().default("tab").describe("Next agent"),
672
+ agent_cycle_reverse: z.string().optional().default("shift+tab").describe("Previous agent"),
673
+ variant_cycle: z.string().optional().default("ctrl+t").describe("Cycle model variants"),
674
+ variant_list: z.string().optional().default("none").describe("List model variants"),
675
+ input_clear: z.string().optional().default("ctrl+c").describe("Clear input field"),
676
+ input_paste: z.string().optional().default("ctrl+v").describe("Paste from clipboard"),
677
+ input_submit: z.string().optional().default("return").describe("Submit input"),
678
+ input_newline: z
679
+ .string()
680
+ .optional()
681
+ .default("shift+return,ctrl+return,alt+return,ctrl+j")
682
+ .describe("Insert newline in input"),
683
+ input_move_left: z.string().optional().default("left,ctrl+b").describe("Move cursor left in input"),
684
+ input_move_right: z.string().optional().default("right,ctrl+f").describe("Move cursor right in input"),
685
+ input_move_up: z.string().optional().default("up").describe("Move cursor up in input"),
686
+ input_move_down: z.string().optional().default("down").describe("Move cursor down in input"),
687
+ input_select_left: z.string().optional().default("shift+left").describe("Select left in input"),
688
+ input_select_right: z.string().optional().default("shift+right").describe("Select right in input"),
689
+ input_select_up: z.string().optional().default("shift+up").describe("Select up in input"),
690
+ input_select_down: z.string().optional().default("shift+down").describe("Select down in input"),
691
+ input_line_home: z.string().optional().default("ctrl+a").describe("Move to start of line in input"),
692
+ input_line_end: z.string().optional().default("ctrl+e").describe("Move to end of line in input"),
693
+ input_select_line_home: z
694
+ .string()
695
+ .optional()
696
+ .default("ctrl+shift+a")
697
+ .describe("Select to start of line in input"),
698
+ input_select_line_end: z.string().optional().default("ctrl+shift+e").describe("Select to end of line in input"),
699
+ input_visual_line_home: z.string().optional().default("alt+a").describe("Move to start of visual line in input"),
700
+ input_visual_line_end: z.string().optional().default("alt+e").describe("Move to end of visual line in input"),
701
+ input_select_visual_line_home: z
702
+ .string()
703
+ .optional()
704
+ .default("alt+shift+a")
705
+ .describe("Select to start of visual line in input"),
706
+ input_select_visual_line_end: z
707
+ .string()
708
+ .optional()
709
+ .default("alt+shift+e")
710
+ .describe("Select to end of visual line in input"),
711
+ input_buffer_home: z.string().optional().default("home").describe("Move to start of buffer in input"),
712
+ input_buffer_end: z.string().optional().default("end").describe("Move to end of buffer in input"),
713
+ input_select_buffer_home: z
714
+ .string()
715
+ .optional()
716
+ .default("shift+home")
717
+ .describe("Select to start of buffer in input"),
718
+ input_select_buffer_end: z.string().optional().default("shift+end").describe("Select to end of buffer in input"),
719
+ input_delete_line: z.string().optional().default("ctrl+shift+d").describe("Delete line in input"),
720
+ input_delete_to_line_end: z.string().optional().default("ctrl+k").describe("Delete to end of line in input"),
721
+ input_delete_to_line_start: z.string().optional().default("ctrl+u").describe("Delete to start of line in input"),
722
+ input_backspace: z.string().optional().default("backspace,shift+backspace").describe("Backspace in input"),
723
+ input_delete: z.string().optional().default("ctrl+d,delete,shift+delete").describe("Delete character in input"),
724
+ input_undo: z.string().optional().default("ctrl+-,super+z").describe("Undo in input"),
725
+ input_redo: z.string().optional().default("ctrl+.,super+shift+z").describe("Redo in input"),
726
+ input_word_forward: z
727
+ .string()
728
+ .optional()
729
+ .default("alt+f,alt+right,ctrl+right")
730
+ .describe("Move word forward in input"),
731
+ input_word_backward: z
732
+ .string()
733
+ .optional()
734
+ .default("alt+b,alt+left,ctrl+left")
735
+ .describe("Move word backward in input"),
736
+ input_select_word_forward: z
737
+ .string()
738
+ .optional()
739
+ .default("alt+shift+f,alt+shift+right")
740
+ .describe("Select word forward in input"),
741
+ input_select_word_backward: z
742
+ .string()
743
+ .optional()
744
+ .default("alt+shift+b,alt+shift+left")
745
+ .describe("Select word backward in input"),
746
+ input_delete_word_forward: z
747
+ .string()
748
+ .optional()
749
+ .default("alt+d,alt+delete,ctrl+delete")
750
+ .describe("Delete word forward in input"),
751
+ input_delete_word_backward: z
752
+ .string()
753
+ .optional()
754
+ .default("ctrl+w,ctrl+backspace,alt+backspace")
755
+ .describe("Delete word backward in input"),
756
+ history_previous: z.string().optional().default("up").describe("Previous history item"),
757
+ history_next: z.string().optional().default("down").describe("Next history item"),
758
+ session_child_first: z.string().optional().default("<leader>down").describe("Go to first child session"),
759
+ session_child_cycle: z.string().optional().default("right").describe("Go to next child session"),
760
+ session_child_cycle_reverse: z.string().optional().default("left").describe("Go to previous child session"),
761
+ session_parent: z.string().optional().default("up").describe("Go to parent session"),
762
+ terminal_suspend: z.string().optional().default("ctrl+z").describe("Suspend terminal"),
763
+ terminal_title_toggle: z.string().optional().default("none").describe("Toggle terminal title"),
764
+ tips_toggle: z.string().optional().default("<leader>h").describe("Toggle tips on home screen"),
765
+ plugin_manager: z.string().optional().default("none").describe("Open plugin manager dialog"),
766
+ display_thinking: z.string().optional().default("none").describe("Toggle thinking blocks visibility"),
767
+ })
768
+ .strict()
769
+ .meta({
770
+ ref: "KeybindsConfig",
771
+ })
772
+
773
+ export const Server = z
774
+ .object({
775
+ port: z.number().int().positive().optional().describe("Port to listen on"),
776
+ hostname: z.string().optional().describe("Hostname to listen on"),
777
+ mdns: z.boolean().optional().describe("Enable mDNS service discovery"),
778
+ mdnsDomain: z.string().optional().describe("Custom domain name for mDNS service (default: iroder.local)"),
779
+ cors: z.array(z.string()).optional().describe("Additional domains to allow for CORS"),
780
+ })
781
+ .strict()
782
+ .meta({
783
+ ref: "ServerConfig",
784
+ })
785
+
786
+ export const Layout = z.enum(["auto", "stretch"]).meta({
787
+ ref: "LayoutConfig",
788
+ })
789
+ export type Layout = z.infer<typeof Layout>
790
+
791
+ export const Model = z
792
+ .object({
793
+ id: z.string(),
794
+ name: z.string(),
795
+ family: z.string().optional(),
796
+ release_date: z.string(),
797
+ attachment: z.boolean(),
798
+ reasoning: z.boolean(),
799
+ temperature: z.boolean(),
800
+ tool_call: z.boolean(),
801
+ interleaved: z
802
+ .union([
803
+ z.literal(true),
804
+ z
805
+ .object({
806
+ field: z.enum(["reasoning_content", "reasoning_details"]),
807
+ })
808
+ .strict(),
809
+ ])
810
+ .optional(),
811
+ cost: z
812
+ .object({
813
+ input: z.number(),
814
+ output: z.number(),
815
+ cache_read: z.number().optional(),
816
+ cache_write: z.number().optional(),
817
+ context_over_200k: z
818
+ .object({
819
+ input: z.number(),
820
+ output: z.number(),
821
+ cache_read: z.number().optional(),
822
+ cache_write: z.number().optional(),
823
+ })
824
+ .optional(),
825
+ })
826
+ .optional(),
827
+ limit: z.object({
828
+ context: z.number(),
829
+ input: z.number().optional(),
830
+ output: z.number(),
831
+ }),
832
+ modalities: z
833
+ .object({
834
+ input: z.array(z.enum(["text", "audio", "image", "video", "pdf"])),
835
+ output: z.array(z.enum(["text", "audio", "image", "video", "pdf"])),
836
+ })
837
+ .optional(),
838
+ experimental: z.boolean().optional(),
839
+ status: z.enum(["alpha", "beta", "deprecated"]).optional(),
840
+ provider: z.object({ npm: z.string().optional(), api: z.string().optional() }).optional(),
841
+ options: z.record(z.string(), z.any()),
842
+ headers: z.record(z.string(), z.string()).optional(),
843
+ variants: z
844
+ .record(
845
+ z.string(),
846
+ z
847
+ .object({
848
+ disabled: z.boolean().optional().describe("Disable this variant for the model"),
849
+ })
850
+ .catchall(z.any()),
851
+ )
852
+ .optional()
853
+ .describe("Variant-specific configuration"),
854
+ })
855
+ .partial()
856
+
857
+ export const Provider = z
858
+ .object({
859
+ api: z.string().optional(),
860
+ name: z.string(),
861
+ env: z.array(z.string()),
862
+ id: z.string(),
863
+ npm: z.string().optional(),
864
+ whitelist: z.array(z.string()).optional(),
865
+ blacklist: z.array(z.string()).optional(),
866
+ options: z
867
+ .object({
868
+ apiKey: z.string().optional(),
869
+ baseURL: z.string().optional(),
870
+ enterpriseUrl: z.string().optional().describe("GitHub Enterprise URL for copilot authentication"),
871
+ setCacheKey: z.boolean().optional().describe("Enable promptCacheKey for this provider (default false)"),
872
+ timeout: z
873
+ .union([
874
+ z
875
+ .number()
876
+ .int()
877
+ .positive()
878
+ .describe(
879
+ "Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout.",
880
+ ),
881
+ z.literal(false).describe("Disable timeout for this provider entirely."),
882
+ ])
883
+ .optional()
884
+ .describe(
885
+ "Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout.",
886
+ ),
887
+ chunkTimeout: z
888
+ .number()
889
+ .int()
890
+ .positive()
891
+ .optional()
892
+ .describe(
893
+ "Timeout in milliseconds between streamed SSE chunks for this provider. If no chunk arrives within this window, the request is aborted.",
894
+ ),
895
+ })
896
+ .catchall(z.any())
897
+ .optional(),
898
+ models: z.record(z.string(), Model).optional(),
899
+ })
900
+ .partial()
901
+ .strict()
902
+ .meta({
903
+ ref: "ProviderConfig",
904
+ })
905
+
906
+ export type Provider = z.infer<typeof Provider>
907
+
908
+ export const Info = z
909
+ .object({
910
+ $schema: z.string().optional().describe("JSON schema reference for configuration validation"),
911
+ logLevel: Log.Level.optional().describe("Log level"),
912
+ server: Server.optional().describe("Server configuration for iroder serve and web commands"),
913
+ command: z
914
+ .record(z.string(), Command)
915
+ .optional()
916
+ .describe(`Command configuration, see ${Site.docsPath("commands")}`),
917
+ skills: Skills.optional().describe("Additional skill folder paths"),
918
+ watcher: z
919
+ .object({
920
+ ignore: z.array(z.string()).optional(),
921
+ })
922
+ .optional(),
923
+ snapshot: z
924
+ .boolean()
925
+ .optional()
926
+ .describe(
927
+ "Enable or disable snapshot tracking. When false, filesystem snapshots are not recorded and undoing or reverting will not undo/redo file changes. Defaults to true.",
928
+ ),
929
+ plugin: PluginSpec.array().optional(),
930
+ share: z
931
+ .enum(["manual", "auto", "disabled"])
932
+ .optional()
933
+ .describe(
934
+ "Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing",
935
+ ),
936
+ autoshare: z
937
+ .boolean()
938
+ .optional()
939
+ .describe("@deprecated Use 'share' field instead. Share newly created sessions automatically"),
940
+ autoupdate: z
941
+ .union([z.boolean(), z.literal("notify")])
942
+ .optional()
943
+ .describe(
944
+ "Automatically update to the latest version. Set to true to auto-update, false to disable, or 'notify' to show update notifications",
945
+ ),
946
+ disabled_providers: z.array(z.string()).optional().describe("Disable providers that are loaded automatically"),
947
+ enabled_providers: z
948
+ .array(z.string())
949
+ .optional()
950
+ .describe("When set, ONLY these providers will be enabled. All other providers will be ignored"),
951
+ model: ModelId.describe("Model to use in the format of provider/model, eg anthropic/claude-2").optional(),
952
+ small_model: ModelId.describe(
953
+ "Small model to use for tasks like title generation in the format of provider/model",
954
+ ).optional(),
955
+ default_agent: z
956
+ .string()
957
+ .optional()
958
+ .describe(
959
+ "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.",
960
+ ),
961
+ username: z
962
+ .string()
963
+ .optional()
964
+ .describe("Custom username to display in conversations instead of system username"),
965
+ mode: z
966
+ .object({
967
+ build: Agent.optional(),
968
+ plan: Agent.optional(),
969
+ })
970
+ .catchall(Agent)
971
+ .optional()
972
+ .describe("@deprecated Use `agent` field instead."),
973
+ agent: z
974
+ .object({
975
+ // primary
976
+ plan: Agent.optional(),
977
+ build: Agent.optional(),
978
+ // subagent
979
+ general: Agent.optional(),
980
+ explore: Agent.optional(),
981
+ // specialized
982
+ title: Agent.optional(),
983
+ summary: Agent.optional(),
984
+ compaction: Agent.optional(),
985
+ })
986
+ .catchall(Agent)
987
+ .optional()
988
+ .describe(`Agent configuration, see ${Site.docsPath("agents")}`),
989
+ provider: z
990
+ .record(z.string(), Provider)
991
+ .optional()
992
+ .describe("Custom provider configurations and model overrides"),
993
+ mcp: z
994
+ .record(
995
+ z.string(),
996
+ z.union([
997
+ Mcp,
998
+ z
999
+ .object({
1000
+ enabled: z.boolean(),
1001
+ })
1002
+ .strict(),
1003
+ ]),
1004
+ )
1005
+ .optional()
1006
+ .describe("MCP (Model Context Protocol) server configurations"),
1007
+ formatter: z
1008
+ .union([
1009
+ z.literal(false),
1010
+ z.record(
1011
+ z.string(),
1012
+ z.object({
1013
+ disabled: z.boolean().optional(),
1014
+ command: z.array(z.string()).optional(),
1015
+ environment: z.record(z.string(), z.string()).optional(),
1016
+ extensions: z.array(z.string()).optional(),
1017
+ }),
1018
+ ),
1019
+ ])
1020
+ .optional(),
1021
+ lsp: z
1022
+ .union([
1023
+ z.literal(false),
1024
+ z.record(
1025
+ z.string(),
1026
+ z.union([
1027
+ z.object({
1028
+ disabled: z.literal(true),
1029
+ }),
1030
+ z.object({
1031
+ command: z.array(z.string()),
1032
+ extensions: z.array(z.string()).optional(),
1033
+ disabled: z.boolean().optional(),
1034
+ env: z.record(z.string(), z.string()).optional(),
1035
+ initialization: z.record(z.string(), z.any()).optional(),
1036
+ }),
1037
+ ]),
1038
+ ),
1039
+ ])
1040
+ .optional()
1041
+ .refine(
1042
+ (data) => {
1043
+ if (!data) return true
1044
+ if (typeof data === "boolean") return true
1045
+ const serverIds = new Set(Object.values(LSPServer).map((s) => s.id))
1046
+
1047
+ return Object.entries(data).every(([id, config]) => {
1048
+ if (config.disabled) return true
1049
+ if (serverIds.has(id)) return true
1050
+ return Boolean(config.extensions)
1051
+ })
1052
+ },
1053
+ {
1054
+ error: "For custom LSP servers, 'extensions' array is required.",
1055
+ },
1056
+ ),
1057
+ instructions: z.array(z.string()).optional().describe("Additional instruction files or patterns to include"),
1058
+ layout: Layout.optional().describe("@deprecated Always uses stretch layout."),
1059
+ permission: Permission.optional(),
1060
+ tools: z.record(z.string(), z.boolean()).optional(),
1061
+ enterprise: z
1062
+ .object({
1063
+ url: z.string().optional().describe("Enterprise URL"),
1064
+ })
1065
+ .optional(),
1066
+ compaction: z
1067
+ .object({
1068
+ auto: z.boolean().optional().describe("Enable automatic compaction when context is full (default: true)"),
1069
+ prune: z.boolean().optional().describe("Enable pruning of old tool outputs (default: true)"),
1070
+ reserved: z
1071
+ .number()
1072
+ .int()
1073
+ .min(0)
1074
+ .optional()
1075
+ .describe("Token buffer for compaction. Leaves enough window to avoid overflow during compaction."),
1076
+ })
1077
+ .optional(),
1078
+ experimental: z
1079
+ .object({
1080
+ disable_paste_summary: z.boolean().optional(),
1081
+ batch_tool: z.boolean().optional().describe("Enable the batch tool"),
1082
+ openTelemetry: z
1083
+ .boolean()
1084
+ .optional()
1085
+ .describe("Enable OpenTelemetry spans for AI SDK calls (using the 'experimental_telemetry' flag)"),
1086
+ primary_tools: z
1087
+ .array(z.string())
1088
+ .optional()
1089
+ .describe("Tools that should only be available to primary agents."),
1090
+ continue_loop_on_deny: z.boolean().optional().describe("Continue the agent loop when a tool call is denied"),
1091
+ mcp_timeout: z
1092
+ .number()
1093
+ .int()
1094
+ .positive()
1095
+ .optional()
1096
+ .describe("Timeout in milliseconds for model context protocol (MCP) requests"),
1097
+ })
1098
+ .optional(),
1099
+ })
1100
+ .strict()
1101
+ .meta({
1102
+ ref: "Config",
1103
+ })
1104
+
1105
+ export type Info = z.output<typeof Info> & {
1106
+ plugin_origins?: PluginOrigin[]
1107
+ }
1108
+
1109
+ type State = {
1110
+ config: Info
1111
+ directories: string[]
1112
+ deps: Promise<void>[]
1113
+ consoleState: ConsoleState
1114
+ }
1115
+
1116
+ export interface Interface {
1117
+ readonly get: () => Effect.Effect<Info>
1118
+ readonly getGlobal: () => Effect.Effect<Info>
1119
+ readonly getConsoleState: () => Effect.Effect<ConsoleState>
1120
+ readonly update: (config: Info) => Effect.Effect<void>
1121
+ readonly updateGlobal: (config: Info) => Effect.Effect<Info>
1122
+ readonly invalidate: (wait?: boolean) => Effect.Effect<void>
1123
+ readonly directories: () => Effect.Effect<string[]>
1124
+ readonly waitForDependencies: () => Effect.Effect<void>
1125
+ }
1126
+
1127
+ export class Service extends ServiceMap.Service<Service, Interface>()("@iroder/Config") { }
1128
+
1129
+ function globalConfigFile() {
1130
+ const candidates = ["iroder.jsonc", "iroder.json", "config.json"].map((file) =>
1131
+ path.join(Global.Path.config, file),
1132
+ )
1133
+ for (const file of candidates) {
1134
+ if (existsSync(file)) return file
1135
+ }
1136
+ return candidates[0]
1137
+ }
1138
+
1139
+ function patchJsonc(input: string, patch: unknown, path: string[] = []): string {
1140
+ if (!isRecord(patch)) {
1141
+ const edits = modify(input, path, patch, {
1142
+ formattingOptions: {
1143
+ insertSpaces: true,
1144
+ tabSize: 2,
1145
+ },
1146
+ })
1147
+ return applyEdits(input, edits)
1148
+ }
1149
+
1150
+ return Object.entries(patch).reduce((result, [key, value]) => {
1151
+ if (value === undefined) return result
1152
+ return patchJsonc(result, value, [...path, key])
1153
+ }, input)
1154
+ }
1155
+
1156
+ function writable(info: Info) {
1157
+ const { plugin_origins, ...next } = info
1158
+ return next
1159
+ }
1160
+
1161
+ function parseConfig(text: string, filepath: string): Info {
1162
+ const errors: JsoncParseError[] = []
1163
+ const data = parseJsonc(text, errors, { allowTrailingComma: true })
1164
+ if (errors.length) {
1165
+ const lines = text.split("\n")
1166
+ const errorDetails = errors
1167
+ .map((e) => {
1168
+ const beforeOffset = text.substring(0, e.offset).split("\n")
1169
+ const line = beforeOffset.length
1170
+ const column = beforeOffset[beforeOffset.length - 1].length + 1
1171
+ const problemLine = lines[line - 1]
1172
+
1173
+ const error = `${printParseErrorCode(e.error)} at line ${line}, column ${column}`
1174
+ if (!problemLine) return error
1175
+
1176
+ return `${error}\n Line ${line}: ${problemLine}\n${"".padStart(column + 9)}^`
1177
+ })
1178
+ .join("\n")
1179
+
1180
+ throw new JsonError({
1181
+ path: filepath,
1182
+ message: `\n--- JSONC Input ---\n${text}\n--- Errors ---\n${errorDetails}\n--- End ---`,
1183
+ })
1184
+ }
1185
+
1186
+ const parsed = Info.safeParse(data)
1187
+ if (parsed.success) return parsed.data
1188
+
1189
+ throw new InvalidError({
1190
+ path: filepath,
1191
+ issues: parsed.error.issues,
1192
+ })
1193
+ }
1194
+
1195
+ export const { JsonError, InvalidError } = ConfigPaths
1196
+
1197
+ export const ConfigDirectoryTypoError = NamedError.create(
1198
+ "ConfigDirectoryTypoError",
1199
+ z.object({
1200
+ path: z.string(),
1201
+ dir: z.string(),
1202
+ suggestion: z.string(),
1203
+ }),
1204
+ )
1205
+
1206
+ export const layer: Layer.Layer<Service, never, AppFileSystem.Service | Auth.Service | Account.Service> =
1207
+ Layer.effect(
1208
+ Service,
1209
+ Effect.gen(function* () {
1210
+ const fs = yield* AppFileSystem.Service
1211
+ const authSvc = yield* Auth.Service
1212
+ const accountSvc = yield* Account.Service
1213
+
1214
+ const readConfigFile = Effect.fnUntraced(function* (filepath: string) {
1215
+ return yield* fs.readFileString(filepath).pipe(
1216
+ Effect.catchIf(
1217
+ (e) => e.reason._tag === "NotFound",
1218
+ () => Effect.succeed(undefined),
1219
+ ),
1220
+ Effect.orDie,
1221
+ )
1222
+ })
1223
+
1224
+ const loadConfig = Effect.fnUntraced(function* (
1225
+ text: string,
1226
+ options: { path: string } | { dir: string; source: string },
1227
+ ) {
1228
+ const original = text
1229
+ const source = "path" in options ? options.path : options.source
1230
+ const isFile = "path" in options
1231
+ const data = yield* Effect.promise(() =>
1232
+ ConfigPaths.parseText(
1233
+ text,
1234
+ "path" in options ? options.path : { source: options.source, dir: options.dir },
1235
+ ),
1236
+ )
1237
+
1238
+ const normalized = (() => {
1239
+ if (!data || typeof data !== "object" || Array.isArray(data)) return data
1240
+ const copy = { ...(data as Record<string, unknown>) }
1241
+ const hadLegacy = "theme" in copy || "keybinds" in copy || "tui" in copy
1242
+ if (!hadLegacy) return copy
1243
+ delete copy.theme
1244
+ delete copy.keybinds
1245
+ delete copy.tui
1246
+ log.warn("tui keys in iroder config are deprecated; move them to tui.json", { path: source })
1247
+ return copy
1248
+ })()
1249
+
1250
+ const parsed = Info.safeParse(normalized)
1251
+ if (parsed.success) {
1252
+ if (!parsed.data.$schema && isFile) {
1253
+ const schema = Site.configSchema()
1254
+ parsed.data.$schema = schema
1255
+ const updated = original.replace(/^\s*\{/, `{\n "$schema": "${schema}",`)
1256
+ yield* fs.writeFileString(options.path, updated).pipe(Effect.catch(() => Effect.void))
1257
+ }
1258
+ const data = parsed.data
1259
+ if (data.plugin && isFile) {
1260
+ const list = data.plugin
1261
+ for (let i = 0; i < list.length; i++) {
1262
+ list[i] = yield* Effect.promise(() => resolvePluginSpec(list[i], options.path))
1263
+ }
1264
+ }
1265
+ return data
1266
+ }
1267
+
1268
+ throw new InvalidError({
1269
+ path: source,
1270
+ issues: parsed.error.issues,
1271
+ })
1272
+ })
1273
+
1274
+ const loadFile = Effect.fnUntraced(function* (filepath: string) {
1275
+ log.info("loading", { path: filepath })
1276
+ const text = yield* readConfigFile(filepath)
1277
+ if (!text) return {} as Info
1278
+ return yield* loadConfig(text, { path: filepath })
1279
+ })
1280
+
1281
+ const loadGlobal = Effect.fnUntraced(function* () {
1282
+ let result: Info = pipe(
1283
+ {},
1284
+ mergeDeep(yield* loadFile(path.join(Global.Path.config, "config.json"))),
1285
+ mergeDeep(yield* loadFile(path.join(Global.Path.config, "iroder.json"))),
1286
+ mergeDeep(yield* loadFile(path.join(Global.Path.config, "iroder.jsonc"))),
1287
+ )
1288
+
1289
+ const legacy = path.join(Global.Path.config, "config")
1290
+ if (existsSync(legacy)) {
1291
+ yield* Effect.promise(() =>
1292
+ import(pathToFileURL(legacy).href, { with: { type: "toml" } })
1293
+ .then(async (mod) => {
1294
+ const { provider, model, ...rest } = mod.default
1295
+ if (provider && model) result.model = `${provider}/${model}`
1296
+ result["$schema"] = Site.configSchema()
1297
+ result = mergeDeep(result, rest)
1298
+ await fsNode.writeFile(path.join(Global.Path.config, "config.json"), JSON.stringify(result, null, 2))
1299
+ await fsNode.unlink(legacy)
1300
+ })
1301
+ .catch(() => { }),
1302
+ )
1303
+ }
1304
+
1305
+ return result
1306
+ })
1307
+
1308
+ const [cachedGlobal, invalidateGlobal] = yield* Effect.cachedInvalidateWithTTL(
1309
+ loadGlobal().pipe(
1310
+ Effect.tapError((error) =>
1311
+ Effect.sync(() => log.error("failed to load global config, using defaults", { error: String(error) })),
1312
+ ),
1313
+ Effect.orElseSucceed((): Info => ({})),
1314
+ ),
1315
+ Duration.infinity,
1316
+ )
1317
+
1318
+ const getGlobal = Effect.fn("Config.getGlobal")(function* () {
1319
+ return yield* cachedGlobal
1320
+ })
1321
+
1322
+ const loadInstanceState = Effect.fnUntraced(function* (ctx: InstanceContext) {
1323
+ const auth = yield* authSvc.all().pipe(Effect.orDie)
1324
+
1325
+ let result: Info = {}
1326
+ const consoleManagedProviders = new Set<string>()
1327
+ let activeOrgName: string | undefined
1328
+
1329
+ const scope = (source: string): PluginScope => {
1330
+ if (source.startsWith("http://") || source.startsWith("https://")) return "global"
1331
+ if (source === "IRODER_CONFIG_CONTENT") return "local"
1332
+ if (Instance.containsPath(source)) return "local"
1333
+ return "global"
1334
+ }
1335
+
1336
+ const track = (source: string, list: PluginSpec[] | undefined, kind?: PluginScope) => {
1337
+ if (!list?.length) return
1338
+ const hit = kind ?? scope(source)
1339
+ const plugins = deduplicatePluginOrigins([
1340
+ ...(result.plugin_origins ?? []),
1341
+ ...list.map((spec) => ({ spec, source, scope: hit })),
1342
+ ])
1343
+ result.plugin = plugins.map((item) => item.spec)
1344
+ result.plugin_origins = plugins
1345
+ }
1346
+
1347
+ const merge = (source: string, next: Info, kind?: PluginScope) => {
1348
+ result = mergeConfigConcatArrays(result, next)
1349
+ track(source, next.plugin, kind)
1350
+ }
1351
+
1352
+ for (const [key, value] of Object.entries(auth)) {
1353
+ if (value.type === "wellknown") {
1354
+ const url = key.replace(/\/+$/, "")
1355
+ process.env[value.key] = value.token
1356
+ log.debug("fetching remote config", { url: `${url}/.well-known/iroder` })
1357
+ const response = yield* Effect.promise(() => fetch(`${url}/.well-known/iroder`))
1358
+ if (!response.ok) {
1359
+ throw new Error(`failed to fetch remote config from ${url}: ${response.status}`)
1360
+ }
1361
+ const wellknown = (yield* Effect.promise(() => response.json())) as any
1362
+ const remoteConfig = wellknown.config ?? {}
1363
+ if (!remoteConfig.$schema) remoteConfig.$schema = Site.configSchema()
1364
+ const source = `${url}/.well-known/iroder`
1365
+ const next = yield* loadConfig(JSON.stringify(remoteConfig), {
1366
+ dir: path.dirname(source),
1367
+ source,
1368
+ })
1369
+ merge(source, next, "global")
1370
+ log.debug("loaded remote config from well-known", { url })
1371
+ }
1372
+ }
1373
+
1374
+ const global = yield* getGlobal()
1375
+ merge(Global.Path.config, global, "global")
1376
+
1377
+ if (Flag.IRODER_CONFIG) {
1378
+ merge(Flag.IRODER_CONFIG, yield* loadFile(Flag.IRODER_CONFIG))
1379
+ log.debug("loaded custom config", { path: Flag.IRODER_CONFIG })
1380
+ }
1381
+
1382
+ if (!Flag.IRODER_DISABLE_PROJECT_CONFIG) {
1383
+ for (const file of yield* Effect.promise(() =>
1384
+ ConfigPaths.projectFiles("iroder", ctx.directory, ctx.worktree),
1385
+ )) {
1386
+ merge(file, yield* loadFile(file), "local")
1387
+ }
1388
+ }
1389
+
1390
+ result.agent = result.agent || {}
1391
+ result.mode = result.mode || {}
1392
+ result.plugin = result.plugin || []
1393
+
1394
+ const directories = yield* Effect.promise(() => ConfigPaths.directories(ctx.directory, ctx.worktree))
1395
+
1396
+ if (Flag.IRODER_CONFIG_DIR) {
1397
+ log.debug("loading config from IRODER_CONFIG_DIR", { path: Flag.IRODER_CONFIG_DIR })
1398
+ }
1399
+
1400
+ const deps: Promise<void>[] = []
1401
+
1402
+ for (const dir of unique(directories)) {
1403
+ if (dir.endsWith(".iroder") || dir === Flag.IRODER_CONFIG_DIR) {
1404
+ for (const file of ["iroder.json", "iroder.jsonc"]) {
1405
+ const source = path.join(dir, file)
1406
+ log.debug(`loading config from ${source}`)
1407
+ merge(source, yield* loadFile(source))
1408
+ result.agent ??= {}
1409
+ result.mode ??= {}
1410
+ result.plugin ??= []
1411
+ }
1412
+ }
1413
+
1414
+ const dep = iife(async () => {
1415
+ await installDependencies(dir)
1416
+ })
1417
+ void dep.catch((err) => {
1418
+ log.warn("background dependency install failed", { dir, error: err })
1419
+ })
1420
+ deps.push(dep)
1421
+
1422
+ result.command = mergeDeep(result.command ?? {}, yield* Effect.promise(() => loadCommand(dir)))
1423
+ result.agent = mergeDeep(result.agent, yield* Effect.promise(() => loadAgent(dir)))
1424
+ result.agent = mergeDeep(result.agent, yield* Effect.promise(() => loadMode(dir)))
1425
+ const list = yield* Effect.promise(() => loadPlugin(dir))
1426
+ track(dir, list)
1427
+ }
1428
+
1429
+ if (process.env.IRODER_CONFIG_CONTENT) {
1430
+ const source = "IRODER_CONFIG_CONTENT"
1431
+ const next = yield* loadConfig(process.env.IRODER_CONFIG_CONTENT, {
1432
+ dir: ctx.directory,
1433
+ source,
1434
+ })
1435
+ merge(source, next, "local")
1436
+ log.debug("loaded custom config from IRODER_CONFIG_CONTENT")
1437
+ }
1438
+
1439
+ const activeOrg = Option.getOrUndefined(
1440
+ yield* accountSvc.activeOrg().pipe(Effect.catch(() => Effect.succeed(Option.none()))),
1441
+ )
1442
+ if (activeOrg) {
1443
+ yield* Effect.gen(function* () {
1444
+ const [configOpt, tokenOpt] = yield* Effect.all(
1445
+ [accountSvc.config(activeOrg.account.id, activeOrg.org.id), accountSvc.token(activeOrg.account.id)],
1446
+ { concurrency: 2 },
1447
+ )
1448
+ if (Option.isSome(tokenOpt)) {
1449
+ process.env["IRODER_CONSOLE_TOKEN"] = tokenOpt.value
1450
+ Env.set("IRODER_CONSOLE_TOKEN", tokenOpt.value)
1451
+ }
1452
+
1453
+ activeOrgName = activeOrg.org.name
1454
+
1455
+ if (Option.isSome(configOpt)) {
1456
+ const source = `${activeOrg.account.url}/api/config`
1457
+ const next = yield* loadConfig(JSON.stringify(configOpt.value), {
1458
+ dir: path.dirname(source),
1459
+ source,
1460
+ })
1461
+ for (const providerID of Object.keys(next.provider ?? {})) {
1462
+ consoleManagedProviders.add(providerID)
1463
+ }
1464
+ merge(source, next, "global")
1465
+ }
1466
+ }).pipe(
1467
+ Effect.catch((err) => {
1468
+ log.debug("failed to fetch remote account config", {
1469
+ error: err instanceof Error ? err.message : String(err),
1470
+ })
1471
+ return Effect.void
1472
+ }),
1473
+ )
1474
+ }
1475
+
1476
+ if (existsSync(managedDir)) {
1477
+ for (const file of ["iroder.json", "iroder.jsonc"]) {
1478
+ const source = path.join(managedDir, file)
1479
+ merge(source, yield* loadFile(source), "global")
1480
+ }
1481
+ }
1482
+
1483
+ // macOS managed preferences (.mobileconfig deployed via MDM) override everything
1484
+ result = mergeConfigConcatArrays(result, yield* Effect.promise(() => readManagedPreferences()))
1485
+
1486
+ for (const [name, mode] of Object.entries(result.mode ?? {})) {
1487
+ result.agent = mergeDeep(result.agent ?? {}, {
1488
+ [name]: {
1489
+ ...mode,
1490
+ mode: "primary" as const,
1491
+ },
1492
+ })
1493
+ }
1494
+
1495
+ if (Flag.IRODER_PERMISSION) {
1496
+ result.permission = mergeDeep(result.permission ?? {}, JSON.parse(Flag.IRODER_PERMISSION))
1497
+ }
1498
+
1499
+ if (result.tools) {
1500
+ const perms: Record<string, Config.PermissionAction> = {}
1501
+ for (const [tool, enabled] of Object.entries(result.tools)) {
1502
+ const action: Config.PermissionAction = enabled ? "allow" : "deny"
1503
+ if (tool === "write" || tool === "edit" || tool === "patch" || tool === "multiedit") {
1504
+ perms.edit = action
1505
+ continue
1506
+ }
1507
+ perms[tool] = action
1508
+ }
1509
+ result.permission = mergeDeep(perms, result.permission ?? {})
1510
+ }
1511
+
1512
+ if (!result.username) result.username = os.userInfo().username
1513
+
1514
+ if (result.autoshare === true && !result.share) {
1515
+ result.share = "auto"
1516
+ }
1517
+
1518
+ if (Flag.IRODER_DISABLE_AUTOCOMPACT) {
1519
+ result.compaction = { ...result.compaction, auto: false }
1520
+ }
1521
+ if (Flag.IRODER_DISABLE_PRUNE) {
1522
+ result.compaction = { ...result.compaction, prune: false }
1523
+ }
1524
+
1525
+ return {
1526
+ config: result,
1527
+ directories,
1528
+ deps,
1529
+ consoleState: {
1530
+ consoleManagedProviders: Array.from(consoleManagedProviders),
1531
+ activeOrgName,
1532
+ switchableOrgCount: 0,
1533
+ },
1534
+ }
1535
+ })
1536
+
1537
+ const state = yield* InstanceState.make<State>(
1538
+ Effect.fn("Config.state")(function* (ctx) {
1539
+ return yield* loadInstanceState(ctx)
1540
+ }),
1541
+ )
1542
+
1543
+ const get = Effect.fn("Config.get")(function* () {
1544
+ return yield* InstanceState.use(state, (s) => s.config)
1545
+ })
1546
+
1547
+ const directories = Effect.fn("Config.directories")(function* () {
1548
+ return yield* InstanceState.use(state, (s) => s.directories)
1549
+ })
1550
+
1551
+ const getConsoleState = Effect.fn("Config.getConsoleState")(function* () {
1552
+ return yield* InstanceState.use(state, (s) => s.consoleState)
1553
+ })
1554
+
1555
+ const waitForDependencies = Effect.fn("Config.waitForDependencies")(function* () {
1556
+ yield* InstanceState.useEffect(state, (s) => Effect.promise(() => Promise.all(s.deps).then(() => undefined)))
1557
+ })
1558
+
1559
+ const update = Effect.fn("Config.update")(function* (config: Info) {
1560
+ const dir = yield* InstanceState.directory
1561
+ const file = path.join(dir, "config.json")
1562
+ const existing = yield* loadFile(file)
1563
+ yield* fs
1564
+ .writeFileString(file, JSON.stringify(mergeDeep(writable(existing), writable(config)), null, 2))
1565
+ .pipe(Effect.orDie)
1566
+ yield* Effect.promise(() => Instance.dispose())
1567
+ })
1568
+
1569
+ const invalidate = Effect.fn("Config.invalidate")(function* (wait?: boolean) {
1570
+ yield* invalidateGlobal
1571
+ const task = Instance.disposeAll()
1572
+ .catch(() => undefined)
1573
+ .finally(() =>
1574
+ GlobalBus.emit("event", {
1575
+ directory: "global",
1576
+ payload: {
1577
+ type: Event.Disposed.type,
1578
+ properties: {},
1579
+ },
1580
+ }),
1581
+ )
1582
+ if (wait) yield* Effect.promise(() => task)
1583
+ else void task
1584
+ })
1585
+
1586
+ const updateGlobal = Effect.fn("Config.updateGlobal")(function* (config: Info) {
1587
+ const file = globalConfigFile()
1588
+ const before = (yield* readConfigFile(file)) ?? "{}"
1589
+ const input = writable(config)
1590
+
1591
+ let next: Info
1592
+ if (!file.endsWith(".jsonc")) {
1593
+ const existing = parseConfig(before, file)
1594
+ const merged = mergeDeep(writable(existing), input)
1595
+ yield* fs.writeFileString(file, JSON.stringify(merged, null, 2)).pipe(Effect.orDie)
1596
+ next = merged
1597
+ } else {
1598
+ const updated = patchJsonc(before, input)
1599
+ next = parseConfig(updated, file)
1600
+ yield* fs.writeFileString(file, updated).pipe(Effect.orDie)
1601
+ }
1602
+
1603
+ yield* invalidate()
1604
+ return next
1605
+ })
1606
+
1607
+ return Service.of({
1608
+ get,
1609
+ getGlobal,
1610
+ getConsoleState,
1611
+ update,
1612
+ updateGlobal,
1613
+ invalidate,
1614
+ directories,
1615
+ waitForDependencies,
1616
+ })
1617
+ }),
1618
+ )
1619
+
1620
+ export const defaultLayer = layer.pipe(
1621
+ Layer.provide(AppFileSystem.defaultLayer),
1622
+ Layer.provide(Auth.defaultLayer),
1623
+ Layer.provide(Account.defaultLayer),
1624
+ )
1625
+
1626
+ const { runPromise } = makeRuntime(Service, defaultLayer)
1627
+
1628
+ export async function get() {
1629
+ return runPromise((svc) => svc.get())
1630
+ }
1631
+
1632
+ export async function getGlobal() {
1633
+ return runPromise((svc) => svc.getGlobal())
1634
+ }
1635
+
1636
+ export async function getConsoleState() {
1637
+ return runPromise((svc) => svc.getConsoleState())
1638
+ }
1639
+
1640
+ export async function update(config: Info) {
1641
+ return runPromise((svc) => svc.update(config))
1642
+ }
1643
+
1644
+ export async function updateGlobal(config: Info) {
1645
+ return runPromise((svc) => svc.updateGlobal(config))
1646
+ }
1647
+
1648
+ export async function invalidate(wait = false) {
1649
+ return runPromise((svc) => svc.invalidate(wait))
1650
+ }
1651
+
1652
+ export async function directories() {
1653
+ return runPromise((svc) => svc.directories())
1654
+ }
1655
+
1656
+ export async function waitForDependencies() {
1657
+ return runPromise((svc) => svc.waitForDependencies())
1658
+ }
1659
+ }