easc-cli 1.1.28

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 (404) hide show
  1. package/AGENTS.md +27 -0
  2. package/Dockerfile +18 -0
  3. package/README.md +15 -0
  4. package/bin/opencode +108 -0
  5. package/bunfig.toml +7 -0
  6. package/package.json +132 -0
  7. package/parsers-config.ts +253 -0
  8. package/script/build.ts +172 -0
  9. package/script/deploy.ts +64 -0
  10. package/script/postinstall.mjs +125 -0
  11. package/script/publish-registries.ts +187 -0
  12. package/script/publish.ts +70 -0
  13. package/script/schema.ts +47 -0
  14. package/script/seed-e2e.ts +50 -0
  15. package/src/acp/README.md +164 -0
  16. package/src/acp/agent.ts +1285 -0
  17. package/src/acp/session.ts +105 -0
  18. package/src/acp/types.ts +22 -0
  19. package/src/agent/agent.ts +332 -0
  20. package/src/agent/generate.txt +75 -0
  21. package/src/agent/prompt/compaction.txt +12 -0
  22. package/src/agent/prompt/explore.txt +18 -0
  23. package/src/agent/prompt/summary.txt +11 -0
  24. package/src/agent/prompt/title.txt +43 -0
  25. package/src/auth/eliseart.ts +76 -0
  26. package/src/auth/index.ts +73 -0
  27. package/src/bun/index.ts +134 -0
  28. package/src/bus/bus-event.ts +43 -0
  29. package/src/bus/global.ts +10 -0
  30. package/src/bus/index.ts +105 -0
  31. package/src/cli/bootstrap.ts +17 -0
  32. package/src/cli/cmd/account.ts +81 -0
  33. package/src/cli/cmd/acp.ts +69 -0
  34. package/src/cli/cmd/agent.ts +257 -0
  35. package/src/cli/cmd/auth.ts +427 -0
  36. package/src/cli/cmd/cmd.ts +7 -0
  37. package/src/cli/cmd/debug/agent.ts +166 -0
  38. package/src/cli/cmd/debug/config.ts +16 -0
  39. package/src/cli/cmd/debug/file.ts +97 -0
  40. package/src/cli/cmd/debug/index.ts +48 -0
  41. package/src/cli/cmd/debug/lsp.ts +52 -0
  42. package/src/cli/cmd/debug/ripgrep.ts +87 -0
  43. package/src/cli/cmd/debug/scrap.ts +16 -0
  44. package/src/cli/cmd/debug/skill.ts +16 -0
  45. package/src/cli/cmd/debug/snapshot.ts +52 -0
  46. package/src/cli/cmd/export.ts +88 -0
  47. package/src/cli/cmd/generate.ts +38 -0
  48. package/src/cli/cmd/github.ts +1548 -0
  49. package/src/cli/cmd/import.ts +98 -0
  50. package/src/cli/cmd/mcp.ts +827 -0
  51. package/src/cli/cmd/models.ts +77 -0
  52. package/src/cli/cmd/pr.ts +112 -0
  53. package/src/cli/cmd/run.ts +407 -0
  54. package/src/cli/cmd/serve.ts +20 -0
  55. package/src/cli/cmd/session.ts +135 -0
  56. package/src/cli/cmd/stats.ts +402 -0
  57. package/src/cli/cmd/tui/app.tsx +774 -0
  58. package/src/cli/cmd/tui/attach.ts +31 -0
  59. package/src/cli/cmd/tui/component/border.tsx +21 -0
  60. package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
  61. package/src/cli/cmd/tui/component/dialog-command.tsx +148 -0
  62. package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
  63. package/src/cli/cmd/tui/component/dialog-model.tsx +234 -0
  64. package/src/cli/cmd/tui/component/dialog-provider.tsx +256 -0
  65. package/src/cli/cmd/tui/component/dialog-session-list.tsx +114 -0
  66. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
  67. package/src/cli/cmd/tui/component/dialog-stash.tsx +87 -0
  68. package/src/cli/cmd/tui/component/dialog-status.tsx +164 -0
  69. package/src/cli/cmd/tui/component/dialog-supabase.tsx +102 -0
  70. package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
  71. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
  72. package/src/cli/cmd/tui/component/logo.tsx +88 -0
  73. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +653 -0
  74. package/src/cli/cmd/tui/component/prompt/frecency.tsx +89 -0
  75. package/src/cli/cmd/tui/component/prompt/history.tsx +108 -0
  76. package/src/cli/cmd/tui/component/prompt/index.tsx +1182 -0
  77. package/src/cli/cmd/tui/component/prompt/stash.tsx +101 -0
  78. package/src/cli/cmd/tui/component/spinner.tsx +16 -0
  79. package/src/cli/cmd/tui/component/textarea-keybindings.ts +73 -0
  80. package/src/cli/cmd/tui/component/tips.tsx +153 -0
  81. package/src/cli/cmd/tui/component/todo-item.tsx +32 -0
  82. package/src/cli/cmd/tui/context/args.tsx +14 -0
  83. package/src/cli/cmd/tui/context/directory.ts +13 -0
  84. package/src/cli/cmd/tui/context/exit.tsx +23 -0
  85. package/src/cli/cmd/tui/context/helper.tsx +25 -0
  86. package/src/cli/cmd/tui/context/keybind.tsx +101 -0
  87. package/src/cli/cmd/tui/context/kv.tsx +52 -0
  88. package/src/cli/cmd/tui/context/local.tsx +402 -0
  89. package/src/cli/cmd/tui/context/prompt.tsx +18 -0
  90. package/src/cli/cmd/tui/context/route.tsx +46 -0
  91. package/src/cli/cmd/tui/context/sdk.tsx +94 -0
  92. package/src/cli/cmd/tui/context/sync.tsx +445 -0
  93. package/src/cli/cmd/tui/context/theme/aura.json +69 -0
  94. package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
  95. package/src/cli/cmd/tui/context/theme/carbonfox.json +248 -0
  96. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +233 -0
  97. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +233 -0
  98. package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
  99. package/src/cli/cmd/tui/context/theme/cobalt2.json +228 -0
  100. package/src/cli/cmd/tui/context/theme/cursor.json +249 -0
  101. package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
  102. package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
  103. package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
  104. package/src/cli/cmd/tui/context/theme/github.json +233 -0
  105. package/src/cli/cmd/tui/context/theme/gruvbox.json +95 -0
  106. package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
  107. package/src/cli/cmd/tui/context/theme/lucent-orng.json +237 -0
  108. package/src/cli/cmd/tui/context/theme/material.json +235 -0
  109. package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
  110. package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
  111. package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
  112. package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
  113. package/src/cli/cmd/tui/context/theme/nord.json +223 -0
  114. package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
  115. package/src/cli/cmd/tui/context/theme/orng.json +249 -0
  116. package/src/cli/cmd/tui/context/theme/osaka-jade.json +93 -0
  117. package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
  118. package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
  119. package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
  120. package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
  121. package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
  122. package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
  123. package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
  124. package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
  125. package/src/cli/cmd/tui/context/theme.tsx +1152 -0
  126. package/src/cli/cmd/tui/event.ts +48 -0
  127. package/src/cli/cmd/tui/routes/home.tsx +140 -0
  128. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +64 -0
  129. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +109 -0
  130. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +26 -0
  131. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +47 -0
  132. package/src/cli/cmd/tui/routes/session/dialog-tool.tsx +63 -0
  133. package/src/cli/cmd/tui/routes/session/footer.tsx +129 -0
  134. package/src/cli/cmd/tui/routes/session/header.tsx +136 -0
  135. package/src/cli/cmd/tui/routes/session/index.tsx +2132 -0
  136. package/src/cli/cmd/tui/routes/session/permission.tsx +495 -0
  137. package/src/cli/cmd/tui/routes/session/question.tsx +435 -0
  138. package/src/cli/cmd/tui/routes/session/sidebar.tsx +313 -0
  139. package/src/cli/cmd/tui/thread.ts +165 -0
  140. package/src/cli/cmd/tui/ui/dialog-alert.tsx +57 -0
  141. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +83 -0
  142. package/src/cli/cmd/tui/ui/dialog-export-options.tsx +204 -0
  143. package/src/cli/cmd/tui/ui/dialog-help.tsx +38 -0
  144. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +77 -0
  145. package/src/cli/cmd/tui/ui/dialog-select.tsx +376 -0
  146. package/src/cli/cmd/tui/ui/dialog.tsx +167 -0
  147. package/src/cli/cmd/tui/ui/link.tsx +28 -0
  148. package/src/cli/cmd/tui/ui/spinner.ts +368 -0
  149. package/src/cli/cmd/tui/ui/toast.tsx +100 -0
  150. package/src/cli/cmd/tui/util/clipboard.ts +160 -0
  151. package/src/cli/cmd/tui/util/editor.ts +32 -0
  152. package/src/cli/cmd/tui/util/signal.ts +7 -0
  153. package/src/cli/cmd/tui/util/terminal.ts +114 -0
  154. package/src/cli/cmd/tui/util/transcript.ts +98 -0
  155. package/src/cli/cmd/tui/worker.ts +152 -0
  156. package/src/cli/cmd/uninstall.ts +357 -0
  157. package/src/cli/cmd/upgrade.ts +73 -0
  158. package/src/cli/cmd/web.ts +81 -0
  159. package/src/cli/error.ts +57 -0
  160. package/src/cli/network.ts +53 -0
  161. package/src/cli/ui.ts +84 -0
  162. package/src/cli/upgrade.ts +25 -0
  163. package/src/command/index.ts +131 -0
  164. package/src/command/template/initialize.txt +10 -0
  165. package/src/command/template/review.txt +99 -0
  166. package/src/config/config.ts +1361 -0
  167. package/src/config/markdown.ts +93 -0
  168. package/src/env/index.ts +26 -0
  169. package/src/file/ignore.ts +83 -0
  170. package/src/file/index.ts +411 -0
  171. package/src/file/ripgrep.ts +407 -0
  172. package/src/file/time.ts +64 -0
  173. package/src/file/watcher.ts +127 -0
  174. package/src/flag/flag.ts +54 -0
  175. package/src/format/formatter.ts +342 -0
  176. package/src/format/index.ts +137 -0
  177. package/src/global/index.ts +55 -0
  178. package/src/id/id.ts +83 -0
  179. package/src/ide/index.ts +76 -0
  180. package/src/index.ts +162 -0
  181. package/src/installation/index.ts +246 -0
  182. package/src/lsp/client.ts +252 -0
  183. package/src/lsp/index.ts +485 -0
  184. package/src/lsp/language.ts +119 -0
  185. package/src/lsp/server.ts +2046 -0
  186. package/src/mcp/auth.ts +135 -0
  187. package/src/mcp/index.ts +931 -0
  188. package/src/mcp/oauth-callback.ts +200 -0
  189. package/src/mcp/oauth-provider.ts +154 -0
  190. package/src/patch/index.ts +680 -0
  191. package/src/permission/arity.ts +163 -0
  192. package/src/permission/index.ts +210 -0
  193. package/src/permission/next.ts +269 -0
  194. package/src/plugin/codex.ts +493 -0
  195. package/src/plugin/copilot.ts +269 -0
  196. package/src/plugin/index.ts +135 -0
  197. package/src/project/bootstrap.ts +35 -0
  198. package/src/project/instance.ts +91 -0
  199. package/src/project/project.ts +339 -0
  200. package/src/project/state.ts +66 -0
  201. package/src/project/vcs.ts +76 -0
  202. package/src/provider/auth.ts +147 -0
  203. package/src/provider/models-macro.ts +11 -0
  204. package/src/provider/models.ts +112 -0
  205. package/src/provider/provider.ts +1391 -0
  206. package/src/provider/sdk/openai-compatible/src/README.md +5 -0
  207. package/src/provider/sdk/openai-compatible/src/index.ts +2 -0
  208. package/src/provider/sdk/openai-compatible/src/openai-compatible-provider.ts +100 -0
  209. package/src/provider/sdk/openai-compatible/src/responses/convert-to-openai-responses-input.ts +303 -0
  210. package/src/provider/sdk/openai-compatible/src/responses/map-openai-responses-finish-reason.ts +22 -0
  211. package/src/provider/sdk/openai-compatible/src/responses/openai-config.ts +18 -0
  212. package/src/provider/sdk/openai-compatible/src/responses/openai-error.ts +22 -0
  213. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-api-types.ts +207 -0
  214. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-language-model.ts +1732 -0
  215. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-prepare-tools.ts +177 -0
  216. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-settings.ts +1 -0
  217. package/src/provider/sdk/openai-compatible/src/responses/tool/code-interpreter.ts +88 -0
  218. package/src/provider/sdk/openai-compatible/src/responses/tool/file-search.ts +128 -0
  219. package/src/provider/sdk/openai-compatible/src/responses/tool/image-generation.ts +115 -0
  220. package/src/provider/sdk/openai-compatible/src/responses/tool/local-shell.ts +65 -0
  221. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search-preview.ts +104 -0
  222. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search.ts +103 -0
  223. package/src/provider/transform.ts +733 -0
  224. package/src/pty/index.ts +232 -0
  225. package/src/question/index.ts +171 -0
  226. package/src/scheduler/index.ts +61 -0
  227. package/src/server/error.ts +36 -0
  228. package/src/server/event.ts +7 -0
  229. package/src/server/mdns.ts +59 -0
  230. package/src/server/routes/config.ts +92 -0
  231. package/src/server/routes/experimental.ts +208 -0
  232. package/src/server/routes/file.ts +197 -0
  233. package/src/server/routes/global.ts +135 -0
  234. package/src/server/routes/mcp.ts +361 -0
  235. package/src/server/routes/permission.ts +68 -0
  236. package/src/server/routes/project.ts +82 -0
  237. package/src/server/routes/provider.ts +165 -0
  238. package/src/server/routes/pty.ts +169 -0
  239. package/src/server/routes/question.ts +98 -0
  240. package/src/server/routes/session.ts +935 -0
  241. package/src/server/routes/tui.ts +379 -0
  242. package/src/server/server.ts +573 -0
  243. package/src/session/compaction.ts +225 -0
  244. package/src/session/index.ts +488 -0
  245. package/src/session/llm.ts +279 -0
  246. package/src/session/message-v2.ts +702 -0
  247. package/src/session/message.ts +189 -0
  248. package/src/session/processor.ts +406 -0
  249. package/src/session/prompt/anthropic-20250930.txt +166 -0
  250. package/src/session/prompt/anthropic.txt +105 -0
  251. package/src/session/prompt/anthropic_spoof.txt +1 -0
  252. package/src/session/prompt/beast.txt +147 -0
  253. package/src/session/prompt/build-switch.txt +5 -0
  254. package/src/session/prompt/codex_header.txt +79 -0
  255. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  256. package/src/session/prompt/gemini.txt +155 -0
  257. package/src/session/prompt/max-steps.txt +16 -0
  258. package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  259. package/src/session/prompt/plan.txt +26 -0
  260. package/src/session/prompt/qwen.txt +109 -0
  261. package/src/session/prompt.ts +1820 -0
  262. package/src/session/retry.ts +90 -0
  263. package/src/session/revert.ts +108 -0
  264. package/src/session/status.ts +76 -0
  265. package/src/session/summary.ts +150 -0
  266. package/src/session/system.ts +152 -0
  267. package/src/session/todo.ts +37 -0
  268. package/src/share/share-next.ts +200 -0
  269. package/src/share/share.ts +92 -0
  270. package/src/shell/shell.ts +67 -0
  271. package/src/skill/index.ts +1 -0
  272. package/src/skill/skill.ts +136 -0
  273. package/src/snapshot/index.ts +236 -0
  274. package/src/storage/storage.ts +227 -0
  275. package/src/tool/apply_patch.ts +269 -0
  276. package/src/tool/apply_patch.txt +33 -0
  277. package/src/tool/bash.ts +259 -0
  278. package/src/tool/bash.txt +115 -0
  279. package/src/tool/batch.ts +175 -0
  280. package/src/tool/batch.txt +24 -0
  281. package/src/tool/codesearch.ts +132 -0
  282. package/src/tool/codesearch.txt +12 -0
  283. package/src/tool/edit.ts +645 -0
  284. package/src/tool/edit.txt +10 -0
  285. package/src/tool/external-directory.ts +32 -0
  286. package/src/tool/glob.ts +77 -0
  287. package/src/tool/glob.txt +6 -0
  288. package/src/tool/grep.ts +154 -0
  289. package/src/tool/grep.txt +8 -0
  290. package/src/tool/invalid.ts +17 -0
  291. package/src/tool/ls.ts +121 -0
  292. package/src/tool/ls.txt +1 -0
  293. package/src/tool/lsp.ts +96 -0
  294. package/src/tool/lsp.txt +19 -0
  295. package/src/tool/multiedit.ts +46 -0
  296. package/src/tool/multiedit.txt +41 -0
  297. package/src/tool/plan-enter.txt +14 -0
  298. package/src/tool/plan-exit.txt +13 -0
  299. package/src/tool/plan.ts +130 -0
  300. package/src/tool/question.ts +33 -0
  301. package/src/tool/question.txt +10 -0
  302. package/src/tool/read.ts +202 -0
  303. package/src/tool/read.txt +12 -0
  304. package/src/tool/registry.ts +163 -0
  305. package/src/tool/skill.ts +75 -0
  306. package/src/tool/task.ts +188 -0
  307. package/src/tool/task.txt +60 -0
  308. package/src/tool/todo.ts +53 -0
  309. package/src/tool/todoread.txt +14 -0
  310. package/src/tool/todowrite.txt +167 -0
  311. package/src/tool/tool.ts +88 -0
  312. package/src/tool/truncation.ts +106 -0
  313. package/src/tool/webfetch.ts +182 -0
  314. package/src/tool/webfetch.txt +13 -0
  315. package/src/tool/websearch.ts +150 -0
  316. package/src/tool/websearch.txt +14 -0
  317. package/src/tool/write.ts +80 -0
  318. package/src/tool/write.txt +8 -0
  319. package/src/util/archive.ts +16 -0
  320. package/src/util/color.ts +19 -0
  321. package/src/util/context.ts +25 -0
  322. package/src/util/defer.ts +12 -0
  323. package/src/util/eventloop.ts +20 -0
  324. package/src/util/filesystem.ts +93 -0
  325. package/src/util/fn.ts +11 -0
  326. package/src/util/format.ts +20 -0
  327. package/src/util/iife.ts +3 -0
  328. package/src/util/keybind.ts +103 -0
  329. package/src/util/lazy.ts +18 -0
  330. package/src/util/locale.ts +81 -0
  331. package/src/util/lock.ts +98 -0
  332. package/src/util/log.ts +180 -0
  333. package/src/util/queue.ts +32 -0
  334. package/src/util/rpc.ts +66 -0
  335. package/src/util/scrap.ts +10 -0
  336. package/src/util/signal.ts +12 -0
  337. package/src/util/timeout.ts +14 -0
  338. package/src/util/token.ts +7 -0
  339. package/src/util/wildcard.ts +56 -0
  340. package/src/worktree/index.ts +424 -0
  341. package/sst-env.d.ts +9 -0
  342. package/test/acp/event-subscription.test.ts +436 -0
  343. package/test/agent/agent.test.ts +638 -0
  344. package/test/bun.test.ts +53 -0
  345. package/test/cli/github-action.test.ts +129 -0
  346. package/test/cli/github-remote.test.ts +80 -0
  347. package/test/cli/tui/transcript.test.ts +297 -0
  348. package/test/config/agent-color.test.ts +66 -0
  349. package/test/config/config.test.ts +1414 -0
  350. package/test/config/fixtures/empty-frontmatter.md +4 -0
  351. package/test/config/fixtures/frontmatter.md +28 -0
  352. package/test/config/fixtures/no-frontmatter.md +1 -0
  353. package/test/config/markdown.test.ts +192 -0
  354. package/test/file/ignore.test.ts +10 -0
  355. package/test/file/path-traversal.test.ts +198 -0
  356. package/test/fixture/fixture.ts +45 -0
  357. package/test/fixture/lsp/fake-lsp-server.js +77 -0
  358. package/test/ide/ide.test.ts +82 -0
  359. package/test/keybind.test.ts +421 -0
  360. package/test/lsp/client.test.ts +95 -0
  361. package/test/mcp/headers.test.ts +153 -0
  362. package/test/mcp/oauth-browser.test.ts +261 -0
  363. package/test/patch/patch.test.ts +348 -0
  364. package/test/permission/arity.test.ts +33 -0
  365. package/test/permission/next.test.ts +652 -0
  366. package/test/permission-task.test.ts +319 -0
  367. package/test/plugin/codex.test.ts +123 -0
  368. package/test/preload.ts +65 -0
  369. package/test/project/project.test.ts +120 -0
  370. package/test/provider/amazon-bedrock.test.ts +268 -0
  371. package/test/provider/gitlab-duo.test.ts +286 -0
  372. package/test/provider/provider.test.ts +2149 -0
  373. package/test/provider/transform.test.ts +1596 -0
  374. package/test/question/question.test.ts +300 -0
  375. package/test/scheduler.test.ts +73 -0
  376. package/test/server/session-list.test.ts +39 -0
  377. package/test/server/session-select.test.ts +78 -0
  378. package/test/session/compaction.test.ts +293 -0
  379. package/test/session/llm.test.ts +90 -0
  380. package/test/session/message-v2.test.ts +662 -0
  381. package/test/session/retry.test.ts +131 -0
  382. package/test/session/revert-compact.test.ts +285 -0
  383. package/test/session/session.test.ts +71 -0
  384. package/test/skill/skill.test.ts +185 -0
  385. package/test/snapshot/snapshot.test.ts +939 -0
  386. package/test/tool/__snapshots__/tool.test.ts.snap +9 -0
  387. package/test/tool/apply_patch.test.ts +499 -0
  388. package/test/tool/bash.test.ts +320 -0
  389. package/test/tool/external-directory.test.ts +126 -0
  390. package/test/tool/fixtures/large-image.png +0 -0
  391. package/test/tool/fixtures/models-api.json +33453 -0
  392. package/test/tool/grep.test.ts +109 -0
  393. package/test/tool/question.test.ts +105 -0
  394. package/test/tool/read.test.ts +332 -0
  395. package/test/tool/registry.test.ts +76 -0
  396. package/test/tool/truncation.test.ts +159 -0
  397. package/test/util/filesystem.test.ts +39 -0
  398. package/test/util/format.test.ts +59 -0
  399. package/test/util/iife.test.ts +36 -0
  400. package/test/util/lazy.test.ts +50 -0
  401. package/test/util/lock.test.ts +72 -0
  402. package/test/util/timeout.test.ts +21 -0
  403. package/test/util/wildcard.test.ts +75 -0
  404. package/tsconfig.json +16 -0
@@ -0,0 +1,1361 @@
1
+ import { Log } from "../util/log"
2
+ import path from "path"
3
+ import { pathToFileURL } from "url"
4
+ import os from "os"
5
+ import z from "zod"
6
+ import { Filesystem } from "../util/filesystem"
7
+ import { ModelsDev } from "../provider/models"
8
+ import { mergeDeep, pipe, unique } from "remeda"
9
+ import { Global } from "../global"
10
+ import fs from "fs/promises"
11
+ import { lazy } from "../util/lazy"
12
+ import { NamedError } from "@eliseart.ai/util/error"
13
+ import { Flag } from "../flag/flag"
14
+ import { Auth } from "../auth"
15
+ import {
16
+ type ParseError as JsoncParseError,
17
+ applyEdits,
18
+ modify,
19
+ parse as parseJsonc,
20
+ printParseErrorCode,
21
+ } from "jsonc-parser"
22
+ import { Instance } from "../project/instance"
23
+ import { LSPServer } from "../lsp/server"
24
+ import { BunProc } from "@/bun"
25
+ import { Installation } from "@/installation"
26
+ import { ConfigMarkdown } from "./markdown"
27
+ import { existsSync } from "fs"
28
+ import { Bus } from "@/bus"
29
+ import { GlobalBus } from "@/bus/global"
30
+ import { Event } from "../server/event"
31
+
32
+ export namespace Config {
33
+ const log = Log.create({ service: "config" })
34
+
35
+ // Custom merge function that concatenates array fields instead of replacing them
36
+ function mergeConfigConcatArrays(target: Info, source: Info): Info {
37
+ const merged = mergeDeep(target, source)
38
+ if (target.plugin && source.plugin) {
39
+ merged.plugin = Array.from(new Set([...target.plugin, ...source.plugin]))
40
+ }
41
+ if (target.instructions && source.instructions) {
42
+ merged.instructions = Array.from(new Set([...target.instructions, ...source.instructions]))
43
+ }
44
+ return merged
45
+ }
46
+
47
+ export const state = Instance.state(async () => {
48
+ const auth = await Auth.all()
49
+
50
+ // Load remote/well-known config first as the base layer (lowest precedence)
51
+ // This allows organizations to provide default configs that users can override
52
+ let result: Info = {}
53
+ for (const [key, value] of Object.entries(auth)) {
54
+ if (value.type === "wellknown") {
55
+ process.env[value.key] = value.token
56
+ log.debug("fetching remote config", { url: `${key}/.well-known/opencode` })
57
+ const response = await fetch(`${key}/.well-known/opencode`)
58
+ if (!response.ok) {
59
+ throw new Error(`failed to fetch remote config from ${key}: ${response.status}`)
60
+ }
61
+ const wellknown = (await response.json()) as any
62
+ const remoteConfig = wellknown.config ?? {}
63
+ // Add $schema to prevent load() from trying to write back to a non-existent file
64
+ if (!remoteConfig.$schema) remoteConfig.$schema = "https://eliseart.ai/config.json"
65
+ result = mergeConfigConcatArrays(
66
+ result,
67
+ await load(JSON.stringify(remoteConfig), `${key}/.well-known/opencode`),
68
+ )
69
+ log.debug("loaded remote config from well-known", { url: key })
70
+ }
71
+ }
72
+
73
+ // Global user config overrides remote config
74
+ result = mergeConfigConcatArrays(result, await global())
75
+
76
+ // Custom config path overrides global
77
+ if (Flag.OPENCODE_CONFIG) {
78
+ result = mergeConfigConcatArrays(result, await loadFile(Flag.OPENCODE_CONFIG))
79
+ log.debug("loaded custom config", { path: Flag.OPENCODE_CONFIG })
80
+ }
81
+
82
+ // Project config has highest precedence (overrides global and remote)
83
+ for (const file of ["opencode.jsonc", "opencode.json"]) {
84
+ const found = await Filesystem.findUp(file, Instance.directory, Instance.worktree)
85
+ for (const resolved of found.toReversed()) {
86
+ result = mergeConfigConcatArrays(result, await loadFile(resolved))
87
+ }
88
+ }
89
+
90
+ // Inline config content has highest precedence
91
+ if (Flag.OPENCODE_CONFIG_CONTENT) {
92
+ result = mergeConfigConcatArrays(result, JSON.parse(Flag.OPENCODE_CONFIG_CONTENT))
93
+ log.debug("loaded custom config from OPENCODE_CONFIG_CONTENT")
94
+ }
95
+
96
+ result.agent = result.agent || {}
97
+ result.mode = result.mode || {}
98
+ result.plugin = result.plugin || []
99
+
100
+ const directories = [
101
+ Global.Path.config,
102
+ ...(await Array.fromAsync(
103
+ Filesystem.up({
104
+ targets: [".opencode"],
105
+ start: Instance.directory,
106
+ stop: Instance.worktree,
107
+ }),
108
+ )),
109
+ ...(await Array.fromAsync(
110
+ Filesystem.up({
111
+ targets: [".opencode"],
112
+ start: Global.Path.home,
113
+ stop: Global.Path.home,
114
+ }),
115
+ )),
116
+ ]
117
+
118
+ if (Flag.OPENCODE_CONFIG_DIR) {
119
+ directories.push(Flag.OPENCODE_CONFIG_DIR)
120
+ log.debug("loading config from OPENCODE_CONFIG_DIR", { path: Flag.OPENCODE_CONFIG_DIR })
121
+ }
122
+
123
+ for (const dir of unique(directories)) {
124
+ if (dir.endsWith(".opencode") || dir === Flag.OPENCODE_CONFIG_DIR) {
125
+ for (const file of ["opencode.jsonc", "opencode.json"]) {
126
+ log.debug(`loading config from ${path.join(dir, file)}`)
127
+ result = mergeConfigConcatArrays(result, await loadFile(path.join(dir, file)))
128
+ // to satisfy the type checker
129
+ result.agent ??= {}
130
+ result.mode ??= {}
131
+ result.plugin ??= []
132
+ }
133
+ }
134
+
135
+ const exists = existsSync(path.join(dir, "node_modules"))
136
+ const installing = installDependencies(dir)
137
+ if (!exists) await installing
138
+
139
+ result.command = mergeDeep(result.command ?? {}, await loadCommand(dir))
140
+ result.agent = mergeDeep(result.agent, await loadAgent(dir))
141
+ result.agent = mergeDeep(result.agent, await loadMode(dir))
142
+ result.plugin.push(...(await loadPlugin(dir)))
143
+ }
144
+
145
+ // Migrate deprecated mode field to agent field
146
+ for (const [name, mode] of Object.entries(result.mode)) {
147
+ result.agent = mergeDeep(result.agent ?? {}, {
148
+ [name]: {
149
+ ...mode,
150
+ mode: "primary" as const,
151
+ },
152
+ })
153
+ }
154
+
155
+ if (Flag.OPENCODE_PERMISSION) {
156
+ result.permission = mergeDeep(result.permission ?? {}, JSON.parse(Flag.OPENCODE_PERMISSION))
157
+ }
158
+
159
+ // Backwards compatibility: legacy top-level `tools` config
160
+ if (result.tools) {
161
+ const perms: Record<string, Config.PermissionAction> = {}
162
+ for (const [tool, enabled] of Object.entries(result.tools)) {
163
+ const action: Config.PermissionAction = enabled ? "allow" : "deny"
164
+ if (tool === "write" || tool === "edit" || tool === "patch" || tool === "multiedit") {
165
+ perms.edit = action
166
+ continue
167
+ }
168
+ perms[tool] = action
169
+ }
170
+ result.permission = mergeDeep(perms, result.permission ?? {})
171
+ }
172
+
173
+ if (!result.username) result.username = os.userInfo().username
174
+
175
+ // Handle migration from autoshare to share field
176
+ if (result.autoshare === true && !result.share) {
177
+ result.share = "auto"
178
+ }
179
+
180
+ if (!result.keybinds) result.keybinds = Info.shape.keybinds.parse({})
181
+
182
+ // Apply flag overrides for compaction settings
183
+ if (Flag.OPENCODE_DISABLE_AUTOCOMPACT) {
184
+ result.compaction = { ...result.compaction, auto: false }
185
+ }
186
+ if (Flag.OPENCODE_DISABLE_PRUNE) {
187
+ result.compaction = { ...result.compaction, prune: false }
188
+ }
189
+
190
+ result.plugin = deduplicatePlugins(result.plugin ?? [])
191
+
192
+ return {
193
+ config: result,
194
+ directories,
195
+ }
196
+ })
197
+
198
+ export async function installDependencies(dir: string) {
199
+ const pkg = path.join(dir, "package.json")
200
+
201
+ if (!(await Bun.file(pkg).exists())) {
202
+ await Bun.write(pkg, "{}")
203
+ }
204
+
205
+ const gitignore = path.join(dir, ".gitignore")
206
+ const hasGitIgnore = await Bun.file(gitignore).exists()
207
+ if (!hasGitIgnore) await Bun.write(gitignore, ["node_modules", "package.json", "bun.lock", ".gitignore"].join("\n"))
208
+
209
+ await BunProc.run(
210
+ ["add", "@eliseart.ai/plugin@" + (Installation.isLocal() ? "latest" : Installation.VERSION), "--exact"],
211
+ {
212
+ cwd: dir,
213
+ },
214
+ ).catch(() => {})
215
+
216
+ // Install any additional dependencies defined in the package.json
217
+ // This allows local plugins and custom tools to use external packages
218
+ await BunProc.run(["install"], { cwd: dir }).catch(() => {})
219
+ }
220
+
221
+ function rel(item: string, patterns: string[]) {
222
+ for (const pattern of patterns) {
223
+ const index = item.indexOf(pattern)
224
+ if (index === -1) continue
225
+ return item.slice(index + pattern.length)
226
+ }
227
+ }
228
+
229
+ function trim(file: string) {
230
+ const ext = path.extname(file)
231
+ return ext.length ? file.slice(0, -ext.length) : file
232
+ }
233
+
234
+ const COMMAND_GLOB = new Bun.Glob("{command,commands}/**/*.md")
235
+ async function loadCommand(dir: string) {
236
+ const result: Record<string, Command> = {}
237
+ for await (const item of COMMAND_GLOB.scan({
238
+ absolute: true,
239
+ followSymlinks: true,
240
+ dot: true,
241
+ cwd: dir,
242
+ })) {
243
+ const md = await ConfigMarkdown.parse(item).catch(async (err) => {
244
+ const message = ConfigMarkdown.FrontmatterError.isInstance(err)
245
+ ? err.data.message
246
+ : `Failed to parse command ${item}`
247
+ const { Session } = await import("@/session")
248
+ Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })
249
+ log.error("failed to load command", { command: item, err })
250
+ return undefined
251
+ })
252
+ if (!md) continue
253
+
254
+ const patterns = ["/.opencode/command/", "/.opencode/commands/", "/command/", "/commands/"]
255
+ const file = rel(item, patterns) ?? path.basename(item)
256
+ const name = trim(file)
257
+
258
+ const config = {
259
+ name,
260
+ ...md.data,
261
+ template: md.content.trim(),
262
+ }
263
+ const parsed = Command.safeParse(config)
264
+ if (parsed.success) {
265
+ result[config.name] = parsed.data
266
+ continue
267
+ }
268
+ throw new InvalidError({ path: item, issues: parsed.error.issues }, { cause: parsed.error })
269
+ }
270
+ return result
271
+ }
272
+
273
+ const AGENT_GLOB = new Bun.Glob("{agent,agents}/**/*.md")
274
+ async function loadAgent(dir: string) {
275
+ const result: Record<string, Agent> = {}
276
+
277
+ for await (const item of AGENT_GLOB.scan({
278
+ absolute: true,
279
+ followSymlinks: true,
280
+ dot: true,
281
+ cwd: dir,
282
+ })) {
283
+ const md = await ConfigMarkdown.parse(item).catch(async (err) => {
284
+ const message = ConfigMarkdown.FrontmatterError.isInstance(err)
285
+ ? err.data.message
286
+ : `Failed to parse agent ${item}`
287
+ const { Session } = await import("@/session")
288
+ Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })
289
+ log.error("failed to load agent", { agent: item, err })
290
+ return undefined
291
+ })
292
+ if (!md) continue
293
+
294
+ const patterns = ["/.opencode/agent/", "/.opencode/agents/", "/agent/", "/agents/"]
295
+ const file = rel(item, patterns) ?? path.basename(item)
296
+ const agentName = trim(file)
297
+
298
+ const config = {
299
+ name: agentName,
300
+ ...md.data,
301
+ prompt: md.content.trim(),
302
+ }
303
+ const parsed = Agent.safeParse(config)
304
+ if (parsed.success) {
305
+ result[config.name] = parsed.data
306
+ continue
307
+ }
308
+ throw new InvalidError({ path: item, issues: parsed.error.issues }, { cause: parsed.error })
309
+ }
310
+ return result
311
+ }
312
+
313
+ const MODE_GLOB = new Bun.Glob("{mode,modes}/*.md")
314
+ async function loadMode(dir: string) {
315
+ const result: Record<string, Agent> = {}
316
+ for await (const item of MODE_GLOB.scan({
317
+ absolute: true,
318
+ followSymlinks: true,
319
+ dot: true,
320
+ cwd: dir,
321
+ })) {
322
+ const md = await ConfigMarkdown.parse(item).catch(async (err) => {
323
+ const message = ConfigMarkdown.FrontmatterError.isInstance(err)
324
+ ? err.data.message
325
+ : `Failed to parse mode ${item}`
326
+ const { Session } = await import("@/session")
327
+ Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })
328
+ log.error("failed to load mode", { mode: item, err })
329
+ return undefined
330
+ })
331
+ if (!md) continue
332
+
333
+ const config = {
334
+ name: path.basename(item, ".md"),
335
+ ...md.data,
336
+ prompt: md.content.trim(),
337
+ }
338
+ const parsed = Agent.safeParse(config)
339
+ if (parsed.success) {
340
+ result[config.name] = {
341
+ ...parsed.data,
342
+ mode: "primary" as const,
343
+ }
344
+ continue
345
+ }
346
+ }
347
+ return result
348
+ }
349
+
350
+ const PLUGIN_GLOB = new Bun.Glob("{plugin,plugins}/*.{ts,js}")
351
+ async function loadPlugin(dir: string) {
352
+ const plugins: string[] = []
353
+
354
+ for await (const item of PLUGIN_GLOB.scan({
355
+ absolute: true,
356
+ followSymlinks: true,
357
+ dot: true,
358
+ cwd: dir,
359
+ })) {
360
+ plugins.push(pathToFileURL(item).href)
361
+ }
362
+ return plugins
363
+ }
364
+
365
+ /**
366
+ * Extracts a canonical plugin name from a plugin specifier.
367
+ * - For file:// URLs: extracts filename without extension
368
+ * - For npm packages: extracts package name without version
369
+ *
370
+ * @example
371
+ * getPluginName("file:///path/to/plugin/foo.js") // "foo"
372
+ * getPluginName("oh-my-opencode@2.4.3") // "oh-my-opencode"
373
+ * getPluginName("@scope/pkg@1.0.0") // "@scope/pkg"
374
+ */
375
+ export function getPluginName(plugin: string): string {
376
+ if (plugin.startsWith("file://")) {
377
+ return path.parse(new URL(plugin).pathname).name
378
+ }
379
+ const lastAt = plugin.lastIndexOf("@")
380
+ if (lastAt > 0) {
381
+ return plugin.substring(0, lastAt)
382
+ }
383
+ return plugin
384
+ }
385
+
386
+ /**
387
+ * Deduplicates plugins by name, with later entries (higher priority) winning.
388
+ * Priority order (highest to lowest):
389
+ * 1. Local plugin/ directory
390
+ * 2. Local opencode.json
391
+ * 3. Global plugin/ directory
392
+ * 4. Global opencode.json
393
+ *
394
+ * Since plugins are added in low-to-high priority order,
395
+ * we reverse, deduplicate (keeping first occurrence), then restore order.
396
+ */
397
+ export function deduplicatePlugins(plugins: string[]): string[] {
398
+ // seenNames: canonical plugin names for duplicate detection
399
+ // e.g., "oh-my-opencode", "@scope/pkg"
400
+ const seenNames = new Set<string>()
401
+
402
+ // uniqueSpecifiers: full plugin specifiers to return
403
+ // e.g., "oh-my-opencode@2.4.3", "file:///path/to/plugin.js"
404
+ const uniqueSpecifiers: string[] = []
405
+
406
+ for (const specifier of plugins.toReversed()) {
407
+ const name = getPluginName(specifier)
408
+ if (!seenNames.has(name)) {
409
+ seenNames.add(name)
410
+ uniqueSpecifiers.push(specifier)
411
+ }
412
+ }
413
+
414
+ return uniqueSpecifiers.toReversed()
415
+ }
416
+
417
+ export const McpLocal = z
418
+ .object({
419
+ type: z.literal("local").describe("Type of MCP server connection"),
420
+ command: z.string().array().describe("Command and arguments to run the MCP server"),
421
+ environment: z
422
+ .record(z.string(), z.string())
423
+ .optional()
424
+ .describe("Environment variables to set when running the MCP server"),
425
+ enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"),
426
+ timeout: z
427
+ .number()
428
+ .int()
429
+ .positive()
430
+ .optional()
431
+ .describe("Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."),
432
+ })
433
+ .strict()
434
+ .meta({
435
+ ref: "McpLocalConfig",
436
+ })
437
+
438
+ export const McpOAuth = z
439
+ .object({
440
+ clientId: z
441
+ .string()
442
+ .optional()
443
+ .describe("OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted."),
444
+ clientSecret: z.string().optional().describe("OAuth client secret (if required by the authorization server)"),
445
+ scope: z.string().optional().describe("OAuth scopes to request during authorization"),
446
+ })
447
+ .strict()
448
+ .meta({
449
+ ref: "McpOAuthConfig",
450
+ })
451
+ export type McpOAuth = z.infer<typeof McpOAuth>
452
+
453
+ export const McpRemote = z
454
+ .object({
455
+ type: z.literal("remote").describe("Type of MCP server connection"),
456
+ url: z.string().describe("URL of the remote MCP server"),
457
+ enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"),
458
+ headers: z.record(z.string(), z.string()).optional().describe("Headers to send with the request"),
459
+ oauth: z
460
+ .union([McpOAuth, z.literal(false)])
461
+ .optional()
462
+ .describe(
463
+ "OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection.",
464
+ ),
465
+ timeout: z
466
+ .number()
467
+ .int()
468
+ .positive()
469
+ .optional()
470
+ .describe("Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."),
471
+ })
472
+ .strict()
473
+ .meta({
474
+ ref: "McpRemoteConfig",
475
+ })
476
+
477
+ export const Mcp = z.discriminatedUnion("type", [McpLocal, McpRemote])
478
+ export type Mcp = z.infer<typeof Mcp>
479
+
480
+ export const PermissionAction = z.enum(["ask", "allow", "deny"]).meta({
481
+ ref: "PermissionActionConfig",
482
+ })
483
+ export type PermissionAction = z.infer<typeof PermissionAction>
484
+
485
+ export const PermissionObject = z.record(z.string(), PermissionAction).meta({
486
+ ref: "PermissionObjectConfig",
487
+ })
488
+ export type PermissionObject = z.infer<typeof PermissionObject>
489
+
490
+ export const PermissionRule = z.union([PermissionAction, PermissionObject]).meta({
491
+ ref: "PermissionRuleConfig",
492
+ })
493
+ export type PermissionRule = z.infer<typeof PermissionRule>
494
+
495
+ // Capture original key order before zod reorders, then rebuild in original order
496
+ const permissionPreprocess = (val: unknown) => {
497
+ if (typeof val === "object" && val !== null && !Array.isArray(val)) {
498
+ return { __originalKeys: Object.keys(val), ...val }
499
+ }
500
+ return val
501
+ }
502
+
503
+ const permissionTransform = (x: unknown): Record<string, PermissionRule> => {
504
+ if (typeof x === "string") return { "*": x as PermissionAction }
505
+ const obj = x as { __originalKeys?: string[] } & Record<string, unknown>
506
+ const { __originalKeys, ...rest } = obj
507
+ if (!__originalKeys) return rest as Record<string, PermissionRule>
508
+ const result: Record<string, PermissionRule> = {}
509
+ for (const key of __originalKeys) {
510
+ if (key in rest) result[key] = rest[key] as PermissionRule
511
+ }
512
+ return result
513
+ }
514
+
515
+ export const Permission = z
516
+ .preprocess(
517
+ permissionPreprocess,
518
+ z
519
+ .object({
520
+ __originalKeys: z.string().array().optional(),
521
+ read: PermissionRule.optional(),
522
+ edit: PermissionRule.optional(),
523
+ glob: PermissionRule.optional(),
524
+ grep: PermissionRule.optional(),
525
+ list: PermissionRule.optional(),
526
+ bash: PermissionRule.optional(),
527
+ task: PermissionRule.optional(),
528
+ external_directory: PermissionRule.optional(),
529
+ todowrite: PermissionAction.optional(),
530
+ todoread: PermissionAction.optional(),
531
+ question: PermissionAction.optional(),
532
+ webfetch: PermissionAction.optional(),
533
+ websearch: PermissionAction.optional(),
534
+ codesearch: PermissionAction.optional(),
535
+ lsp: PermissionRule.optional(),
536
+ doom_loop: PermissionAction.optional(),
537
+ })
538
+ .catchall(PermissionRule)
539
+ .or(PermissionAction),
540
+ )
541
+ .transform(permissionTransform)
542
+ .meta({
543
+ ref: "PermissionConfig",
544
+ })
545
+ export type Permission = z.infer<typeof Permission>
546
+
547
+ export const Command = z.object({
548
+ template: z.string(),
549
+ description: z.string().optional(),
550
+ agent: z.string().optional(),
551
+ model: z.string().optional(),
552
+ subtask: z.boolean().optional(),
553
+ })
554
+ export type Command = z.infer<typeof Command>
555
+
556
+ export const Agent = z
557
+ .object({
558
+ model: z.string().optional(),
559
+ temperature: z.number().optional(),
560
+ top_p: z.number().optional(),
561
+ prompt: z.string().optional(),
562
+ tools: z.record(z.string(), z.boolean()).optional().describe("@deprecated Use 'permission' field instead"),
563
+ disable: z.boolean().optional(),
564
+ description: z.string().optional().describe("Description of when to use the agent"),
565
+ mode: z.enum(["subagent", "primary", "all"]).optional(),
566
+ hidden: z
567
+ .boolean()
568
+ .optional()
569
+ .describe("Hide this subagent from the @ autocomplete menu (default: false, only applies to mode: subagent)"),
570
+ options: z.record(z.string(), z.any()).optional(),
571
+ color: z
572
+ .string()
573
+ .regex(/^#[0-9a-fA-F]{6}$/, "Invalid hex color format")
574
+ .optional()
575
+ .describe("Hex color code for the agent (e.g., #FF5733)"),
576
+ steps: z
577
+ .number()
578
+ .int()
579
+ .positive()
580
+ .optional()
581
+ .describe("Maximum number of agentic iterations before forcing text-only response"),
582
+ maxSteps: z.number().int().positive().optional().describe("@deprecated Use 'steps' field instead."),
583
+ permission: Permission.optional(),
584
+ })
585
+ .catchall(z.any())
586
+ .transform((agent, ctx) => {
587
+ const knownKeys = new Set([
588
+ "name",
589
+ "model",
590
+ "prompt",
591
+ "description",
592
+ "temperature",
593
+ "top_p",
594
+ "mode",
595
+ "hidden",
596
+ "color",
597
+ "steps",
598
+ "maxSteps",
599
+ "options",
600
+ "permission",
601
+ "disable",
602
+ "tools",
603
+ ])
604
+
605
+ // Extract unknown properties into options
606
+ const options: Record<string, unknown> = { ...agent.options }
607
+ for (const [key, value] of Object.entries(agent)) {
608
+ if (!knownKeys.has(key)) options[key] = value
609
+ }
610
+
611
+ // Convert legacy tools config to permissions
612
+ const permission: Permission = {}
613
+ for (const [tool, enabled] of Object.entries(agent.tools ?? {})) {
614
+ const action = enabled ? "allow" : "deny"
615
+ // write, edit, patch, multiedit all map to edit permission
616
+ if (tool === "write" || tool === "edit" || tool === "patch" || tool === "multiedit") {
617
+ permission.edit = action
618
+ } else {
619
+ permission[tool] = action
620
+ }
621
+ }
622
+ Object.assign(permission, agent.permission)
623
+
624
+ // Convert legacy maxSteps to steps
625
+ const steps = agent.steps ?? agent.maxSteps
626
+
627
+ return { ...agent, options, permission, steps } as typeof agent & {
628
+ options?: Record<string, unknown>
629
+ permission?: Permission
630
+ steps?: number
631
+ }
632
+ })
633
+ .meta({
634
+ ref: "AgentConfig",
635
+ })
636
+ export type Agent = z.infer<typeof Agent>
637
+
638
+ export const Keybinds = z
639
+ .object({
640
+ leader: z.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"),
641
+ app_exit: z.string().optional().default("ctrl+c,ctrl+d,<leader>q").describe("Exit the application"),
642
+ editor_open: z.string().optional().default("<leader>e").describe("Open external editor"),
643
+ theme_list: z.string().optional().default("<leader>t").describe("List available themes"),
644
+ sidebar_toggle: z.string().optional().default("<leader>b").describe("Toggle sidebar"),
645
+ scrollbar_toggle: z.string().optional().default("none").describe("Toggle session scrollbar"),
646
+ username_toggle: z.string().optional().default("none").describe("Toggle username visibility"),
647
+ status_view: z.string().optional().default("<leader>s").describe("View status"),
648
+ session_export: z.string().optional().default("<leader>x").describe("Export session to editor"),
649
+ session_new: z.string().optional().default("<leader>n").describe("Create a new session"),
650
+ session_list: z.string().optional().default("<leader>l").describe("List all sessions"),
651
+ session_timeline: z.string().optional().default("<leader>g").describe("Show session timeline"),
652
+ session_fork: z.string().optional().default("none").describe("Fork session from message"),
653
+ session_rename: z.string().optional().default("ctrl+r").describe("Rename session"),
654
+ session_delete: z.string().optional().default("ctrl+d").describe("Delete session"),
655
+ stash_delete: z.string().optional().default("ctrl+d").describe("Delete stash entry"),
656
+ model_provider_list: z.string().optional().default("ctrl+a").describe("Open provider list from model dialog"),
657
+ model_favorite_toggle: z.string().optional().default("ctrl+f").describe("Toggle model favorite status"),
658
+ session_share: z.string().optional().default("none").describe("Share current session"),
659
+ session_unshare: z.string().optional().default("none").describe("Unshare current session"),
660
+ session_interrupt: z.string().optional().default("escape").describe("Interrupt current session"),
661
+ session_compact: z.string().optional().default("<leader>c").describe("Compact the session"),
662
+ messages_page_up: z.string().optional().default("pageup,ctrl+alt+b").describe("Scroll messages up by one page"),
663
+ messages_page_down: z
664
+ .string()
665
+ .optional()
666
+ .default("pagedown,ctrl+alt+f")
667
+ .describe("Scroll messages down by one page"),
668
+ messages_line_up: z.string().optional().default("ctrl+alt+y").describe("Scroll messages up by one line"),
669
+ messages_line_down: z.string().optional().default("ctrl+alt+e").describe("Scroll messages down by one line"),
670
+ messages_half_page_up: z.string().optional().default("ctrl+alt+u").describe("Scroll messages up by half page"),
671
+ messages_half_page_down: z
672
+ .string()
673
+ .optional()
674
+ .default("ctrl+alt+d")
675
+ .describe("Scroll messages down by half page"),
676
+ messages_first: z.string().optional().default("ctrl+g,home").describe("Navigate to first message"),
677
+ messages_last: z.string().optional().default("ctrl+alt+g,end").describe("Navigate to last message"),
678
+ messages_next: z.string().optional().default("none").describe("Navigate to next message"),
679
+ messages_previous: z.string().optional().default("none").describe("Navigate to previous message"),
680
+ messages_last_user: z.string().optional().default("none").describe("Navigate to last user message"),
681
+ messages_copy: z.string().optional().default("<leader>y").describe("Copy message"),
682
+ messages_undo: z.string().optional().default("<leader>u").describe("Undo message"),
683
+ messages_redo: z.string().optional().default("<leader>r").describe("Redo message"),
684
+ messages_toggle_conceal: z
685
+ .string()
686
+ .optional()
687
+ .default("<leader>h")
688
+ .describe("Toggle code block concealment in messages"),
689
+ tool_details: z.string().optional().default("none").describe("Toggle tool details visibility"),
690
+ model_list: z.string().optional().default("<leader>m").describe("List available models"),
691
+ model_cycle_recent: z.string().optional().default("f2").describe("Next recently used model"),
692
+ model_cycle_recent_reverse: z.string().optional().default("shift+f2").describe("Previous recently used model"),
693
+ model_cycle_favorite: z.string().optional().default("none").describe("Next favorite model"),
694
+ model_cycle_favorite_reverse: z.string().optional().default("none").describe("Previous favorite model"),
695
+ command_list: z.string().optional().default("ctrl+p").describe("List available commands"),
696
+ agent_list: z.string().optional().default("<leader>a").describe("List agents"),
697
+ agent_cycle: z.string().optional().default("tab").describe("Next agent"),
698
+ agent_cycle_reverse: z.string().optional().default("shift+tab").describe("Previous agent"),
699
+ variant_cycle: z.string().optional().default("ctrl+t").describe("Cycle model variants"),
700
+ input_clear: z.string().optional().default("ctrl+c").describe("Clear input field"),
701
+ input_paste: z.string().optional().default("ctrl+v").describe("Paste from clipboard"),
702
+ input_submit: z.string().optional().default("return").describe("Submit input"),
703
+ input_newline: z
704
+ .string()
705
+ .optional()
706
+ .default("shift+return,ctrl+return,alt+return,ctrl+j")
707
+ .describe("Insert newline in input"),
708
+ input_move_left: z.string().optional().default("left,ctrl+b").describe("Move cursor left in input"),
709
+ input_move_right: z.string().optional().default("right,ctrl+f").describe("Move cursor right in input"),
710
+ input_move_up: z.string().optional().default("up").describe("Move cursor up in input"),
711
+ input_move_down: z.string().optional().default("down").describe("Move cursor down in input"),
712
+ input_select_left: z.string().optional().default("shift+left").describe("Select left in input"),
713
+ input_select_right: z.string().optional().default("shift+right").describe("Select right in input"),
714
+ input_select_up: z.string().optional().default("shift+up").describe("Select up in input"),
715
+ input_select_down: z.string().optional().default("shift+down").describe("Select down in input"),
716
+ input_line_home: z.string().optional().default("ctrl+a").describe("Move to start of line in input"),
717
+ input_line_end: z.string().optional().default("ctrl+e").describe("Move to end of line in input"),
718
+ input_select_line_home: z
719
+ .string()
720
+ .optional()
721
+ .default("ctrl+shift+a")
722
+ .describe("Select to start of line in input"),
723
+ input_select_line_end: z.string().optional().default("ctrl+shift+e").describe("Select to end of line in input"),
724
+ input_visual_line_home: z.string().optional().default("alt+a").describe("Move to start of visual line in input"),
725
+ input_visual_line_end: z.string().optional().default("alt+e").describe("Move to end of visual line in input"),
726
+ input_select_visual_line_home: z
727
+ .string()
728
+ .optional()
729
+ .default("alt+shift+a")
730
+ .describe("Select to start of visual line in input"),
731
+ input_select_visual_line_end: z
732
+ .string()
733
+ .optional()
734
+ .default("alt+shift+e")
735
+ .describe("Select to end of visual line in input"),
736
+ input_buffer_home: z.string().optional().default("home").describe("Move to start of buffer in input"),
737
+ input_buffer_end: z.string().optional().default("end").describe("Move to end of buffer in input"),
738
+ input_select_buffer_home: z
739
+ .string()
740
+ .optional()
741
+ .default("shift+home")
742
+ .describe("Select to start of buffer in input"),
743
+ input_select_buffer_end: z.string().optional().default("shift+end").describe("Select to end of buffer in input"),
744
+ input_delete_line: z.string().optional().default("ctrl+shift+d").describe("Delete line in input"),
745
+ input_delete_to_line_end: z.string().optional().default("ctrl+k").describe("Delete to end of line in input"),
746
+ input_delete_to_line_start: z.string().optional().default("ctrl+u").describe("Delete to start of line in input"),
747
+ input_backspace: z.string().optional().default("backspace,shift+backspace").describe("Backspace in input"),
748
+ input_delete: z.string().optional().default("ctrl+d,delete,shift+delete").describe("Delete character in input"),
749
+ input_undo: z.string().optional().default("ctrl+-,super+z").describe("Undo in input"),
750
+ input_redo: z.string().optional().default("ctrl+.,super+shift+z").describe("Redo in input"),
751
+ input_word_forward: z
752
+ .string()
753
+ .optional()
754
+ .default("alt+f,alt+right,ctrl+right")
755
+ .describe("Move word forward in input"),
756
+ input_word_backward: z
757
+ .string()
758
+ .optional()
759
+ .default("alt+b,alt+left,ctrl+left")
760
+ .describe("Move word backward in input"),
761
+ input_select_word_forward: z
762
+ .string()
763
+ .optional()
764
+ .default("alt+shift+f,alt+shift+right")
765
+ .describe("Select word forward in input"),
766
+ input_select_word_backward: z
767
+ .string()
768
+ .optional()
769
+ .default("alt+shift+b,alt+shift+left")
770
+ .describe("Select word backward in input"),
771
+ input_delete_word_forward: z
772
+ .string()
773
+ .optional()
774
+ .default("alt+d,alt+delete,ctrl+delete")
775
+ .describe("Delete word forward in input"),
776
+ input_delete_word_backward: z
777
+ .string()
778
+ .optional()
779
+ .default("ctrl+w,ctrl+backspace,alt+backspace")
780
+ .describe("Delete word backward in input"),
781
+ history_previous: z.string().optional().default("up").describe("Previous history item"),
782
+ history_next: z.string().optional().default("down").describe("Next history item"),
783
+ session_child_cycle: z.string().optional().default("<leader>right").describe("Next child session"),
784
+ session_child_cycle_reverse: z.string().optional().default("<leader>left").describe("Previous child session"),
785
+ session_parent: z.string().optional().default("<leader>up").describe("Go to parent session"),
786
+ terminal_suspend: z.string().optional().default("ctrl+z").describe("Suspend terminal"),
787
+ terminal_title_toggle: z.string().optional().default("none").describe("Toggle terminal title"),
788
+ tips_toggle: z.string().optional().default("<leader>h").describe("Toggle tips on home screen"),
789
+ })
790
+ .strict()
791
+ .meta({
792
+ ref: "KeybindsConfig",
793
+ })
794
+
795
+ export const TUI = z.object({
796
+ scroll_speed: z.number().min(0.001).optional().describe("TUI scroll speed"),
797
+ scroll_acceleration: z
798
+ .object({
799
+ enabled: z.boolean().describe("Enable scroll acceleration"),
800
+ })
801
+ .optional()
802
+ .describe("Scroll acceleration settings"),
803
+ diff_style: z
804
+ .enum(["auto", "stacked"])
805
+ .optional()
806
+ .describe("Control diff rendering style: 'auto' adapts to terminal width, 'stacked' always shows single column"),
807
+ })
808
+
809
+ export const Server = z
810
+ .object({
811
+ port: z.number().int().positive().optional().describe("Port to listen on"),
812
+ hostname: z.string().optional().describe("Hostname to listen on"),
813
+ mdns: z.boolean().optional().describe("Enable mDNS service discovery"),
814
+ cors: z.array(z.string()).optional().describe("Additional domains to allow for CORS"),
815
+ })
816
+ .strict()
817
+ .meta({
818
+ ref: "ServerConfig",
819
+ })
820
+
821
+ export const Layout = z.enum(["auto", "stretch"]).meta({
822
+ ref: "LayoutConfig",
823
+ })
824
+ export type Layout = z.infer<typeof Layout>
825
+
826
+ export const Provider = ModelsDev.Provider.partial()
827
+ .extend({
828
+ whitelist: z.array(z.string()).optional(),
829
+ blacklist: z.array(z.string()).optional(),
830
+ models: z
831
+ .record(
832
+ z.string(),
833
+ ModelsDev.Model.partial().extend({
834
+ variants: z
835
+ .record(
836
+ z.string(),
837
+ z
838
+ .object({
839
+ disabled: z.boolean().optional().describe("Disable this variant for the model"),
840
+ })
841
+ .catchall(z.any()),
842
+ )
843
+ .optional()
844
+ .describe("Variant-specific configuration"),
845
+ }),
846
+ )
847
+ .optional(),
848
+ options: z
849
+ .object({
850
+ apiKey: z.string().optional(),
851
+ baseURL: z.string().optional(),
852
+ enterpriseUrl: z.string().optional().describe("GitHub Enterprise URL for copilot authentication"),
853
+ setCacheKey: z.boolean().optional().describe("Enable promptCacheKey for this provider (default false)"),
854
+ timeout: z
855
+ .union([
856
+ z
857
+ .number()
858
+ .int()
859
+ .positive()
860
+ .describe(
861
+ "Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout.",
862
+ ),
863
+ z.literal(false).describe("Disable timeout for this provider entirely."),
864
+ ])
865
+ .optional()
866
+ .describe(
867
+ "Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout.",
868
+ ),
869
+ })
870
+ .catchall(z.any())
871
+ .optional(),
872
+ })
873
+ .strict()
874
+ .meta({
875
+ ref: "ProviderConfig",
876
+ })
877
+ export type Provider = z.infer<typeof Provider>
878
+
879
+ export const Info = z
880
+ .object({
881
+ $schema: z.string().optional().describe("JSON schema reference for configuration validation"),
882
+ theme: z.string().optional().describe("Theme name to use for the interface"),
883
+ keybinds: Keybinds.optional().describe("Custom keybind configurations"),
884
+ logLevel: Log.Level.optional().describe("Log level"),
885
+ tui: TUI.optional().describe("TUI specific settings"),
886
+ server: Server.optional().describe("Server configuration for opencode serve and web commands"),
887
+ command: z
888
+ .record(z.string(), Command)
889
+ .optional()
890
+ .describe("Command configuration, see https://eliseart.ai/docs/commands"),
891
+ watcher: z
892
+ .object({
893
+ ignore: z.array(z.string()).optional(),
894
+ })
895
+ .optional(),
896
+ plugin: z.string().array().optional(),
897
+ snapshot: z.boolean().optional(),
898
+ share: z
899
+ .enum(["manual", "auto", "disabled"])
900
+ .optional()
901
+ .describe(
902
+ "Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing",
903
+ ),
904
+ autoshare: z
905
+ .boolean()
906
+ .optional()
907
+ .describe("@deprecated Use 'share' field instead. Share newly created sessions automatically"),
908
+ autoupdate: z
909
+ .union([z.boolean(), z.literal("notify")])
910
+ .optional()
911
+ .describe(
912
+ "Automatically update to the latest version. Set to true to auto-update, false to disable, or 'notify' to show update notifications",
913
+ ),
914
+ disabled_providers: z.array(z.string()).optional().describe("Disable providers that are loaded automatically"),
915
+ enabled_providers: z
916
+ .array(z.string())
917
+ .optional()
918
+ .describe("When set, ONLY these providers will be enabled. All other providers will be ignored"),
919
+ model: z.string().describe("Model to use in the format of provider/model, eg anthropic/claude-2").optional(),
920
+ small_model: z
921
+ .string()
922
+ .describe("Small model to use for tasks like title generation in the format of provider/model")
923
+ .optional(),
924
+ default_agent: z
925
+ .string()
926
+ .optional()
927
+ .describe(
928
+ "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.",
929
+ ),
930
+ username: z
931
+ .string()
932
+ .optional()
933
+ .describe("Custom username to display in conversations instead of system username"),
934
+ mode: z
935
+ .object({
936
+ build: Agent.optional(),
937
+ plan: Agent.optional(),
938
+ })
939
+ .catchall(Agent)
940
+ .optional()
941
+ .describe("@deprecated Use `agent` field instead."),
942
+ agent: z
943
+ .object({
944
+ // primary
945
+ plan: Agent.optional(),
946
+ build: Agent.optional(),
947
+ // subagent
948
+ general: Agent.optional(),
949
+ explore: Agent.optional(),
950
+ // specialized
951
+ title: Agent.optional(),
952
+ summary: Agent.optional(),
953
+ compaction: Agent.optional(),
954
+ })
955
+ .catchall(Agent)
956
+ .optional()
957
+ .describe("Agent configuration, see https://eliseart.ai/docs/agents"),
958
+ provider: z
959
+ .record(z.string(), Provider)
960
+ .optional()
961
+ .describe("Custom provider configurations and model overrides"),
962
+ mcp: z
963
+ .record(
964
+ z.string(),
965
+ z.union([
966
+ Mcp,
967
+ z
968
+ .object({
969
+ enabled: z.boolean(),
970
+ })
971
+ .strict(),
972
+ ]),
973
+ )
974
+ .optional()
975
+ .describe("MCP (Model Context Protocol) server configurations"),
976
+ formatter: z
977
+ .union([
978
+ z.literal(false),
979
+ z.record(
980
+ z.string(),
981
+ z.object({
982
+ disabled: z.boolean().optional(),
983
+ command: z.array(z.string()).optional(),
984
+ environment: z.record(z.string(), z.string()).optional(),
985
+ extensions: z.array(z.string()).optional(),
986
+ }),
987
+ ),
988
+ ])
989
+ .optional(),
990
+ lsp: z
991
+ .union([
992
+ z.literal(false),
993
+ z.record(
994
+ z.string(),
995
+ z.union([
996
+ z.object({
997
+ disabled: z.literal(true),
998
+ }),
999
+ z.object({
1000
+ command: z.array(z.string()),
1001
+ extensions: z.array(z.string()).optional(),
1002
+ disabled: z.boolean().optional(),
1003
+ env: z.record(z.string(), z.string()).optional(),
1004
+ initialization: z.record(z.string(), z.any()).optional(),
1005
+ }),
1006
+ ]),
1007
+ ),
1008
+ ])
1009
+ .optional()
1010
+ .refine(
1011
+ (data) => {
1012
+ if (!data) return true
1013
+ if (typeof data === "boolean") return true
1014
+ const serverIds = new Set(Object.values(LSPServer).map((s) => s.id))
1015
+
1016
+ return Object.entries(data).every(([id, config]) => {
1017
+ if (config.disabled) return true
1018
+ if (serverIds.has(id)) return true
1019
+ return Boolean(config.extensions)
1020
+ })
1021
+ },
1022
+ {
1023
+ error: "For custom LSP servers, 'extensions' array is required.",
1024
+ },
1025
+ ),
1026
+ instructions: z.array(z.string()).optional().describe("Additional instruction files or patterns to include"),
1027
+ layout: Layout.optional().describe("@deprecated Always uses stretch layout."),
1028
+ permission: Permission.optional(),
1029
+ tools: z.record(z.string(), z.boolean()).optional(),
1030
+ enterprise: z
1031
+ .object({
1032
+ url: z.string().optional().describe("Enterprise URL"),
1033
+ })
1034
+ .optional(),
1035
+ compaction: z
1036
+ .object({
1037
+ auto: z.boolean().optional().describe("Enable automatic compaction when context is full (default: true)"),
1038
+ prune: z.boolean().optional().describe("Enable pruning of old tool outputs (default: true)"),
1039
+ })
1040
+ .optional(),
1041
+ experimental: z
1042
+ .object({
1043
+ hook: z
1044
+ .object({
1045
+ file_edited: z
1046
+ .record(
1047
+ z.string(),
1048
+ z
1049
+ .object({
1050
+ command: z.string().array(),
1051
+ environment: z.record(z.string(), z.string()).optional(),
1052
+ })
1053
+ .array(),
1054
+ )
1055
+ .optional(),
1056
+ session_completed: z
1057
+ .object({
1058
+ command: z.string().array(),
1059
+ environment: z.record(z.string(), z.string()).optional(),
1060
+ })
1061
+ .array()
1062
+ .optional(),
1063
+ })
1064
+ .optional(),
1065
+ chatMaxRetries: z.number().optional().describe("Number of retries for chat completions on failure"),
1066
+ disable_paste_summary: z.boolean().optional(),
1067
+ batch_tool: z.boolean().optional().describe("Enable the batch tool"),
1068
+ openTelemetry: z
1069
+ .boolean()
1070
+ .optional()
1071
+ .describe("Enable OpenTelemetry spans for AI SDK calls (using the 'experimental_telemetry' flag)"),
1072
+ primary_tools: z
1073
+ .array(z.string())
1074
+ .optional()
1075
+ .describe("Tools that should only be available to primary agents."),
1076
+ continue_loop_on_deny: z.boolean().optional().describe("Continue the agent loop when a tool call is denied"),
1077
+ mcp_timeout: z
1078
+ .number()
1079
+ .int()
1080
+ .positive()
1081
+ .optional()
1082
+ .describe("Timeout in milliseconds for model context protocol (MCP) requests"),
1083
+ })
1084
+ .optional(),
1085
+ })
1086
+ .strict()
1087
+ .meta({
1088
+ ref: "Config",
1089
+ })
1090
+
1091
+ export type Info = z.output<typeof Info>
1092
+
1093
+ export const global = lazy(async () => {
1094
+ let result: Info = pipe(
1095
+ {},
1096
+ mergeDeep(await loadFile(path.join(Global.Path.config, "config.json"))),
1097
+ mergeDeep(await loadFile(path.join(Global.Path.config, "opencode.json"))),
1098
+ mergeDeep(await loadFile(path.join(Global.Path.config, "opencode.jsonc"))),
1099
+ )
1100
+
1101
+ await import(path.join(Global.Path.config, "config"), {
1102
+ with: {
1103
+ type: "toml",
1104
+ },
1105
+ })
1106
+ .then(async (mod) => {
1107
+ const { provider, model, ...rest } = mod.default
1108
+ if (provider && model) result.model = `${provider}/${model}`
1109
+ result["$schema"] = "https://eliseart.ai/config.json"
1110
+ result = mergeDeep(result, rest)
1111
+ await Bun.write(path.join(Global.Path.config, "config.json"), JSON.stringify(result, null, 2))
1112
+ await fs.unlink(path.join(Global.Path.config, "config"))
1113
+ })
1114
+ .catch(() => {})
1115
+
1116
+ return result
1117
+ })
1118
+
1119
+ async function loadFile(filepath: string): Promise<Info> {
1120
+ log.info("loading", { path: filepath })
1121
+ let text = await Bun.file(filepath)
1122
+ .text()
1123
+ .catch((err) => {
1124
+ if (err.code === "ENOENT") return
1125
+ throw new JsonError({ path: filepath }, { cause: err })
1126
+ })
1127
+ if (!text) return {}
1128
+ return load(text, filepath)
1129
+ }
1130
+
1131
+ async function load(text: string, configFilepath: string) {
1132
+ const original = text
1133
+ text = text.replace(/\{env:([^}]+)\}/g, (_, varName) => {
1134
+ return process.env[varName] || ""
1135
+ })
1136
+
1137
+ const fileMatches = text.match(/\{file:[^}]+\}/g)
1138
+ if (fileMatches) {
1139
+ const configDir = path.dirname(configFilepath)
1140
+ const lines = text.split("\n")
1141
+
1142
+ for (const match of fileMatches) {
1143
+ const lineIndex = lines.findIndex((line) => line.includes(match))
1144
+ if (lineIndex !== -1 && lines[lineIndex].trim().startsWith("//")) {
1145
+ continue // Skip if line is commented
1146
+ }
1147
+ let filePath = match.replace(/^\{file:/, "").replace(/\}$/, "")
1148
+ if (filePath.startsWith("~/")) {
1149
+ filePath = path.join(os.homedir(), filePath.slice(2))
1150
+ }
1151
+ const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(configDir, filePath)
1152
+ const fileContent = (
1153
+ await Bun.file(resolvedPath)
1154
+ .text()
1155
+ .catch((error) => {
1156
+ const errMsg = `bad file reference: "${match}"`
1157
+ if (error.code === "ENOENT") {
1158
+ throw new InvalidError(
1159
+ {
1160
+ path: configFilepath,
1161
+ message: errMsg + ` ${resolvedPath} does not exist`,
1162
+ },
1163
+ { cause: error },
1164
+ )
1165
+ }
1166
+ throw new InvalidError({ path: configFilepath, message: errMsg }, { cause: error })
1167
+ })
1168
+ ).trim()
1169
+ // escape newlines/quotes, strip outer quotes
1170
+ text = text.replace(match, JSON.stringify(fileContent).slice(1, -1))
1171
+ }
1172
+ }
1173
+
1174
+ const errors: JsoncParseError[] = []
1175
+ const data = parseJsonc(text, errors, { allowTrailingComma: true })
1176
+ if (errors.length) {
1177
+ const lines = text.split("\n")
1178
+ const errorDetails = errors
1179
+ .map((e) => {
1180
+ const beforeOffset = text.substring(0, e.offset).split("\n")
1181
+ const line = beforeOffset.length
1182
+ const column = beforeOffset[beforeOffset.length - 1].length + 1
1183
+ const problemLine = lines[line - 1]
1184
+
1185
+ const error = `${printParseErrorCode(e.error)} at line ${line}, column ${column}`
1186
+ if (!problemLine) return error
1187
+
1188
+ return `${error}\n Line ${line}: ${problemLine}\n${"".padStart(column + 9)}^`
1189
+ })
1190
+ .join("\n")
1191
+
1192
+ throw new JsonError({
1193
+ path: configFilepath,
1194
+ message: `\n--- JSONC Input ---\n${text}\n--- Errors ---\n${errorDetails}\n--- End ---`,
1195
+ })
1196
+ }
1197
+
1198
+ const parsed = Info.safeParse(data)
1199
+ if (parsed.success) {
1200
+ if (!parsed.data.$schema) {
1201
+ parsed.data.$schema = "https://eliseart.ai/config.json"
1202
+ // Write the $schema to the original text to preserve variables like {env:VAR}
1203
+ const updated = original.replace(/^\s*\{/, '{\n "$schema": "https://eliseart.ai/config.json",')
1204
+ await Bun.write(configFilepath, updated).catch(() => {})
1205
+ }
1206
+ const data = parsed.data
1207
+ if (data.plugin) {
1208
+ for (let i = 0; i < data.plugin.length; i++) {
1209
+ const plugin = data.plugin[i]
1210
+ try {
1211
+ data.plugin[i] = import.meta.resolve!(plugin, configFilepath)
1212
+ } catch (err) {}
1213
+ }
1214
+ }
1215
+ return data
1216
+ }
1217
+
1218
+ throw new InvalidError({
1219
+ path: configFilepath,
1220
+ issues: parsed.error.issues,
1221
+ })
1222
+ }
1223
+ export const JsonError = NamedError.create(
1224
+ "ConfigJsonError",
1225
+ z.object({
1226
+ path: z.string(),
1227
+ message: z.string().optional(),
1228
+ }),
1229
+ )
1230
+
1231
+ export const ConfigDirectoryTypoError = NamedError.create(
1232
+ "ConfigDirectoryTypoError",
1233
+ z.object({
1234
+ path: z.string(),
1235
+ dir: z.string(),
1236
+ suggestion: z.string(),
1237
+ }),
1238
+ )
1239
+
1240
+ export const InvalidError = NamedError.create(
1241
+ "ConfigInvalidError",
1242
+ z.object({
1243
+ path: z.string(),
1244
+ issues: z.custom<z.core.$ZodIssue[]>().optional(),
1245
+ message: z.string().optional(),
1246
+ }),
1247
+ )
1248
+
1249
+ export async function get() {
1250
+ return state().then((x) => x.config)
1251
+ }
1252
+
1253
+ export async function getGlobal() {
1254
+ return global()
1255
+ }
1256
+
1257
+ export async function update(config: Info) {
1258
+ const filepath = path.join(Instance.directory, "config.json")
1259
+ const existing = await loadFile(filepath)
1260
+ await Bun.write(filepath, JSON.stringify(mergeDeep(existing, config), null, 2))
1261
+ await Instance.dispose()
1262
+ }
1263
+
1264
+ function globalConfigFile() {
1265
+ const candidates = ["opencode.jsonc", "opencode.json", "config.json"].map((file) =>
1266
+ path.join(Global.Path.config, file),
1267
+ )
1268
+ for (const file of candidates) {
1269
+ if (existsSync(file)) return file
1270
+ }
1271
+ return candidates[0]
1272
+ }
1273
+
1274
+ function isRecord(value: unknown): value is Record<string, unknown> {
1275
+ return !!value && typeof value === "object" && !Array.isArray(value)
1276
+ }
1277
+
1278
+ function patchJsonc(input: string, patch: unknown, path: string[] = []): string {
1279
+ if (!isRecord(patch)) {
1280
+ const edits = modify(input, path, patch, {
1281
+ formattingOptions: {
1282
+ insertSpaces: true,
1283
+ tabSize: 2,
1284
+ },
1285
+ })
1286
+ return applyEdits(input, edits)
1287
+ }
1288
+
1289
+ return Object.entries(patch).reduce((result, [key, value]) => {
1290
+ if (value === undefined) return result
1291
+ return patchJsonc(result, value, [...path, key])
1292
+ }, input)
1293
+ }
1294
+
1295
+ function parseConfig(text: string, filepath: string): Info {
1296
+ const errors: JsoncParseError[] = []
1297
+ const data = parseJsonc(text, errors, { allowTrailingComma: true })
1298
+ if (errors.length) {
1299
+ const lines = text.split("\n")
1300
+ const errorDetails = errors
1301
+ .map((e) => {
1302
+ const beforeOffset = text.substring(0, e.offset).split("\n")
1303
+ const line = beforeOffset.length
1304
+ const column = beforeOffset[beforeOffset.length - 1].length + 1
1305
+ const problemLine = lines[line - 1]
1306
+
1307
+ const error = `${printParseErrorCode(e.error)} at line ${line}, column ${column}`
1308
+ if (!problemLine) return error
1309
+
1310
+ return `${error}\n Line ${line}: ${problemLine}\n${"".padStart(column + 9)}^`
1311
+ })
1312
+ .join("\n")
1313
+
1314
+ throw new JsonError({
1315
+ path: filepath,
1316
+ message: `\n--- JSONC Input ---\n${text}\n--- Errors ---\n${errorDetails}\n--- End ---`,
1317
+ })
1318
+ }
1319
+
1320
+ const parsed = Info.safeParse(data)
1321
+ if (parsed.success) return parsed.data
1322
+
1323
+ throw new InvalidError({
1324
+ path: filepath,
1325
+ issues: parsed.error.issues,
1326
+ })
1327
+ }
1328
+
1329
+ export async function updateGlobal(config: Info) {
1330
+ const filepath = globalConfigFile()
1331
+ const before = await Bun.file(filepath)
1332
+ .text()
1333
+ .catch((err) => {
1334
+ if (err.code === "ENOENT") return "{}"
1335
+ throw new JsonError({ path: filepath }, { cause: err })
1336
+ })
1337
+
1338
+ if (!filepath.endsWith(".jsonc")) {
1339
+ const existing = parseConfig(before, filepath)
1340
+ await Bun.write(filepath, JSON.stringify(mergeDeep(existing, config), null, 2))
1341
+ } else {
1342
+ const next = patchJsonc(before, config)
1343
+ parseConfig(next, filepath)
1344
+ await Bun.write(filepath, next)
1345
+ }
1346
+
1347
+ global.reset()
1348
+ await Instance.disposeAll()
1349
+ GlobalBus.emit("event", {
1350
+ directory: "global",
1351
+ payload: {
1352
+ type: Event.Disposed.type,
1353
+ properties: {},
1354
+ },
1355
+ })
1356
+ }
1357
+
1358
+ export async function directories() {
1359
+ return state().then((x) => x.directories)
1360
+ }
1361
+ }