@epoch-ai/cli 2.2.5 → 2.2.7

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