easc-cli 1.1.37 → 1.1.41

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 (413) hide show
  1. package/bin/opencode +4 -6
  2. package/bin/package.json +3 -0
  3. package/package.json +14 -119
  4. package/{script/postinstall.mjs → postinstall.mjs} +4 -4
  5. package/AGENTS.md +0 -27
  6. package/Dockerfile +0 -18
  7. package/README.md +0 -15
  8. package/bunfig.toml +0 -7
  9. package/charity-website/README.md +0 -252
  10. package/charity-website/admin/index.html +0 -299
  11. package/charity-website/package.json +0 -40
  12. package/charity-website/public/index.html +0 -265
  13. package/charity-website/src/css/admin.css +0 -710
  14. package/charity-website/src/css/style.css +0 -741
  15. package/charity-website/src/js/admin.js +0 -743
  16. package/charity-website/src/js/app.js +0 -444
  17. package/parsers-config.ts +0 -253
  18. package/script/build.ts +0 -172
  19. package/script/deploy.ts +0 -96
  20. package/script/publish-registries.ts +0 -187
  21. package/script/publish.ts +0 -70
  22. package/script/schema.ts +0 -47
  23. package/script/seed-e2e.ts +0 -50
  24. package/src/acp/README.md +0 -164
  25. package/src/acp/agent.ts +0 -1285
  26. package/src/acp/session.ts +0 -105
  27. package/src/acp/types.ts +0 -22
  28. package/src/agent/agent.ts +0 -332
  29. package/src/agent/generate.txt +0 -75
  30. package/src/agent/prompt/compaction.txt +0 -12
  31. package/src/agent/prompt/explore.txt +0 -18
  32. package/src/agent/prompt/summary.txt +0 -11
  33. package/src/agent/prompt/title.txt +0 -43
  34. package/src/auth/eliseart.ts +0 -76
  35. package/src/auth/index.ts +0 -73
  36. package/src/bun/index.ts +0 -134
  37. package/src/bus/bus-event.ts +0 -43
  38. package/src/bus/global.ts +0 -10
  39. package/src/bus/index.ts +0 -105
  40. package/src/cli/bootstrap.ts +0 -17
  41. package/src/cli/cmd/account.ts +0 -81
  42. package/src/cli/cmd/acp.ts +0 -69
  43. package/src/cli/cmd/agent.ts +0 -257
  44. package/src/cli/cmd/auth.ts +0 -427
  45. package/src/cli/cmd/cmd.ts +0 -7
  46. package/src/cli/cmd/debug/agent.ts +0 -166
  47. package/src/cli/cmd/debug/config.ts +0 -16
  48. package/src/cli/cmd/debug/file.ts +0 -97
  49. package/src/cli/cmd/debug/index.ts +0 -48
  50. package/src/cli/cmd/debug/lsp.ts +0 -52
  51. package/src/cli/cmd/debug/ripgrep.ts +0 -87
  52. package/src/cli/cmd/debug/scrap.ts +0 -16
  53. package/src/cli/cmd/debug/skill.ts +0 -16
  54. package/src/cli/cmd/debug/snapshot.ts +0 -52
  55. package/src/cli/cmd/export.ts +0 -88
  56. package/src/cli/cmd/generate.ts +0 -38
  57. package/src/cli/cmd/github.ts +0 -1548
  58. package/src/cli/cmd/import.ts +0 -98
  59. package/src/cli/cmd/mcp.ts +0 -827
  60. package/src/cli/cmd/models.ts +0 -77
  61. package/src/cli/cmd/pr.ts +0 -112
  62. package/src/cli/cmd/run.ts +0 -407
  63. package/src/cli/cmd/serve.ts +0 -20
  64. package/src/cli/cmd/session.ts +0 -135
  65. package/src/cli/cmd/stats.ts +0 -402
  66. package/src/cli/cmd/tui/app.tsx +0 -774
  67. package/src/cli/cmd/tui/attach.ts +0 -31
  68. package/src/cli/cmd/tui/component/border.tsx +0 -21
  69. package/src/cli/cmd/tui/component/dialog-agent.tsx +0 -31
  70. package/src/cli/cmd/tui/component/dialog-command.tsx +0 -148
  71. package/src/cli/cmd/tui/component/dialog-mcp.tsx +0 -86
  72. package/src/cli/cmd/tui/component/dialog-model.tsx +0 -234
  73. package/src/cli/cmd/tui/component/dialog-provider.tsx +0 -256
  74. package/src/cli/cmd/tui/component/dialog-session-list.tsx +0 -114
  75. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +0 -31
  76. package/src/cli/cmd/tui/component/dialog-stash.tsx +0 -87
  77. package/src/cli/cmd/tui/component/dialog-status.tsx +0 -164
  78. package/src/cli/cmd/tui/component/dialog-supabase.tsx +0 -102
  79. package/src/cli/cmd/tui/component/dialog-tag.tsx +0 -44
  80. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +0 -50
  81. package/src/cli/cmd/tui/component/logo.tsx +0 -88
  82. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +0 -653
  83. package/src/cli/cmd/tui/component/prompt/frecency.tsx +0 -89
  84. package/src/cli/cmd/tui/component/prompt/history.tsx +0 -108
  85. package/src/cli/cmd/tui/component/prompt/index.tsx +0 -1182
  86. package/src/cli/cmd/tui/component/prompt/stash.tsx +0 -101
  87. package/src/cli/cmd/tui/component/spinner.tsx +0 -16
  88. package/src/cli/cmd/tui/component/textarea-keybindings.ts +0 -73
  89. package/src/cli/cmd/tui/component/tips.tsx +0 -153
  90. package/src/cli/cmd/tui/component/todo-item.tsx +0 -32
  91. package/src/cli/cmd/tui/context/args.tsx +0 -14
  92. package/src/cli/cmd/tui/context/directory.ts +0 -13
  93. package/src/cli/cmd/tui/context/exit.tsx +0 -23
  94. package/src/cli/cmd/tui/context/helper.tsx +0 -25
  95. package/src/cli/cmd/tui/context/keybind.tsx +0 -101
  96. package/src/cli/cmd/tui/context/kv.tsx +0 -52
  97. package/src/cli/cmd/tui/context/local.tsx +0 -402
  98. package/src/cli/cmd/tui/context/prompt.tsx +0 -18
  99. package/src/cli/cmd/tui/context/route.tsx +0 -46
  100. package/src/cli/cmd/tui/context/sdk.tsx +0 -94
  101. package/src/cli/cmd/tui/context/sync.tsx +0 -445
  102. package/src/cli/cmd/tui/context/theme/aura.json +0 -69
  103. package/src/cli/cmd/tui/context/theme/ayu.json +0 -80
  104. package/src/cli/cmd/tui/context/theme/carbonfox.json +0 -248
  105. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +0 -233
  106. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +0 -233
  107. package/src/cli/cmd/tui/context/theme/catppuccin.json +0 -112
  108. package/src/cli/cmd/tui/context/theme/cobalt2.json +0 -228
  109. package/src/cli/cmd/tui/context/theme/cursor.json +0 -249
  110. package/src/cli/cmd/tui/context/theme/dracula.json +0 -219
  111. package/src/cli/cmd/tui/context/theme/everforest.json +0 -241
  112. package/src/cli/cmd/tui/context/theme/flexoki.json +0 -237
  113. package/src/cli/cmd/tui/context/theme/github.json +0 -233
  114. package/src/cli/cmd/tui/context/theme/gruvbox.json +0 -95
  115. package/src/cli/cmd/tui/context/theme/kanagawa.json +0 -77
  116. package/src/cli/cmd/tui/context/theme/lucent-orng.json +0 -237
  117. package/src/cli/cmd/tui/context/theme/material.json +0 -235
  118. package/src/cli/cmd/tui/context/theme/matrix.json +0 -77
  119. package/src/cli/cmd/tui/context/theme/mercury.json +0 -252
  120. package/src/cli/cmd/tui/context/theme/monokai.json +0 -221
  121. package/src/cli/cmd/tui/context/theme/nightowl.json +0 -221
  122. package/src/cli/cmd/tui/context/theme/nord.json +0 -223
  123. package/src/cli/cmd/tui/context/theme/one-dark.json +0 -84
  124. package/src/cli/cmd/tui/context/theme/orng.json +0 -249
  125. package/src/cli/cmd/tui/context/theme/osaka-jade.json +0 -93
  126. package/src/cli/cmd/tui/context/theme/palenight.json +0 -222
  127. package/src/cli/cmd/tui/context/theme/rosepine.json +0 -234
  128. package/src/cli/cmd/tui/context/theme/solarized.json +0 -223
  129. package/src/cli/cmd/tui/context/theme/synthwave84.json +0 -226
  130. package/src/cli/cmd/tui/context/theme/tokyonight.json +0 -243
  131. package/src/cli/cmd/tui/context/theme/vercel.json +0 -245
  132. package/src/cli/cmd/tui/context/theme/vesper.json +0 -218
  133. package/src/cli/cmd/tui/context/theme/zenburn.json +0 -223
  134. package/src/cli/cmd/tui/context/theme.tsx +0 -1152
  135. package/src/cli/cmd/tui/event.ts +0 -48
  136. package/src/cli/cmd/tui/routes/home.tsx +0 -140
  137. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +0 -64
  138. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +0 -109
  139. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +0 -26
  140. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +0 -47
  141. package/src/cli/cmd/tui/routes/session/dialog-tool.tsx +0 -63
  142. package/src/cli/cmd/tui/routes/session/footer.tsx +0 -129
  143. package/src/cli/cmd/tui/routes/session/header.tsx +0 -136
  144. package/src/cli/cmd/tui/routes/session/index.tsx +0 -2132
  145. package/src/cli/cmd/tui/routes/session/permission.tsx +0 -495
  146. package/src/cli/cmd/tui/routes/session/question.tsx +0 -435
  147. package/src/cli/cmd/tui/routes/session/sidebar.tsx +0 -313
  148. package/src/cli/cmd/tui/thread.ts +0 -165
  149. package/src/cli/cmd/tui/ui/dialog-alert.tsx +0 -57
  150. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +0 -83
  151. package/src/cli/cmd/tui/ui/dialog-export-options.tsx +0 -204
  152. package/src/cli/cmd/tui/ui/dialog-help.tsx +0 -38
  153. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +0 -77
  154. package/src/cli/cmd/tui/ui/dialog-select.tsx +0 -376
  155. package/src/cli/cmd/tui/ui/dialog.tsx +0 -167
  156. package/src/cli/cmd/tui/ui/link.tsx +0 -28
  157. package/src/cli/cmd/tui/ui/spinner.ts +0 -368
  158. package/src/cli/cmd/tui/ui/toast.tsx +0 -100
  159. package/src/cli/cmd/tui/util/clipboard.ts +0 -160
  160. package/src/cli/cmd/tui/util/editor.ts +0 -32
  161. package/src/cli/cmd/tui/util/signal.ts +0 -7
  162. package/src/cli/cmd/tui/util/terminal.ts +0 -114
  163. package/src/cli/cmd/tui/util/transcript.ts +0 -98
  164. package/src/cli/cmd/tui/worker.ts +0 -152
  165. package/src/cli/cmd/uninstall.ts +0 -357
  166. package/src/cli/cmd/upgrade.ts +0 -73
  167. package/src/cli/cmd/web.ts +0 -81
  168. package/src/cli/error.ts +0 -57
  169. package/src/cli/network.ts +0 -53
  170. package/src/cli/ui.ts +0 -84
  171. package/src/cli/upgrade.ts +0 -25
  172. package/src/command/index.ts +0 -131
  173. package/src/command/template/initialize.txt +0 -10
  174. package/src/command/template/review.txt +0 -99
  175. package/src/config/config.ts +0 -1361
  176. package/src/config/markdown.ts +0 -93
  177. package/src/env/index.ts +0 -26
  178. package/src/file/ignore.ts +0 -83
  179. package/src/file/index.ts +0 -411
  180. package/src/file/ripgrep.ts +0 -407
  181. package/src/file/time.ts +0 -64
  182. package/src/file/watcher.ts +0 -127
  183. package/src/flag/flag.ts +0 -54
  184. package/src/format/formatter.ts +0 -342
  185. package/src/format/index.ts +0 -137
  186. package/src/global/index.ts +0 -55
  187. package/src/id/id.ts +0 -83
  188. package/src/ide/index.ts +0 -76
  189. package/src/index.ts +0 -162
  190. package/src/installation/index.ts +0 -246
  191. package/src/lsp/client.ts +0 -252
  192. package/src/lsp/index.ts +0 -485
  193. package/src/lsp/language.ts +0 -119
  194. package/src/lsp/server.ts +0 -2046
  195. package/src/mcp/auth.ts +0 -135
  196. package/src/mcp/index.ts +0 -931
  197. package/src/mcp/oauth-callback.ts +0 -200
  198. package/src/mcp/oauth-provider.ts +0 -154
  199. package/src/patch/index.ts +0 -680
  200. package/src/permission/arity.ts +0 -163
  201. package/src/permission/index.ts +0 -210
  202. package/src/permission/next.ts +0 -269
  203. package/src/plugin/codex.ts +0 -493
  204. package/src/plugin/copilot.ts +0 -269
  205. package/src/plugin/index.ts +0 -136
  206. package/src/project/bootstrap.ts +0 -35
  207. package/src/project/instance.ts +0 -91
  208. package/src/project/project.ts +0 -339
  209. package/src/project/state.ts +0 -66
  210. package/src/project/vcs.ts +0 -76
  211. package/src/provider/auth.ts +0 -147
  212. package/src/provider/models-macro.ts +0 -11
  213. package/src/provider/models.ts +0 -112
  214. package/src/provider/provider.ts +0 -1435
  215. package/src/provider/sdk/openai-compatible/src/README.md +0 -5
  216. package/src/provider/sdk/openai-compatible/src/index.ts +0 -2
  217. package/src/provider/sdk/openai-compatible/src/openai-compatible-provider.ts +0 -100
  218. package/src/provider/sdk/openai-compatible/src/responses/convert-to-openai-responses-input.ts +0 -303
  219. package/src/provider/sdk/openai-compatible/src/responses/map-openai-responses-finish-reason.ts +0 -22
  220. package/src/provider/sdk/openai-compatible/src/responses/openai-config.ts +0 -18
  221. package/src/provider/sdk/openai-compatible/src/responses/openai-error.ts +0 -22
  222. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-api-types.ts +0 -207
  223. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-language-model.ts +0 -1732
  224. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-prepare-tools.ts +0 -177
  225. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-settings.ts +0 -1
  226. package/src/provider/sdk/openai-compatible/src/responses/tool/code-interpreter.ts +0 -88
  227. package/src/provider/sdk/openai-compatible/src/responses/tool/file-search.ts +0 -128
  228. package/src/provider/sdk/openai-compatible/src/responses/tool/image-generation.ts +0 -115
  229. package/src/provider/sdk/openai-compatible/src/responses/tool/local-shell.ts +0 -65
  230. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search-preview.ts +0 -104
  231. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search.ts +0 -103
  232. package/src/provider/transform.ts +0 -733
  233. package/src/pty/index.ts +0 -232
  234. package/src/question/index.ts +0 -171
  235. package/src/scheduler/index.ts +0 -61
  236. package/src/server/error.ts +0 -36
  237. package/src/server/event.ts +0 -7
  238. package/src/server/mdns.ts +0 -59
  239. package/src/server/routes/config.ts +0 -92
  240. package/src/server/routes/experimental.ts +0 -208
  241. package/src/server/routes/file.ts +0 -197
  242. package/src/server/routes/global.ts +0 -135
  243. package/src/server/routes/mcp.ts +0 -361
  244. package/src/server/routes/permission.ts +0 -68
  245. package/src/server/routes/project.ts +0 -82
  246. package/src/server/routes/provider.ts +0 -165
  247. package/src/server/routes/pty.ts +0 -169
  248. package/src/server/routes/question.ts +0 -98
  249. package/src/server/routes/session.ts +0 -935
  250. package/src/server/routes/tui.ts +0 -379
  251. package/src/server/server.ts +0 -573
  252. package/src/session/compaction.ts +0 -225
  253. package/src/session/index.ts +0 -488
  254. package/src/session/llm.ts +0 -279
  255. package/src/session/message-v2.ts +0 -702
  256. package/src/session/message.ts +0 -189
  257. package/src/session/processor.ts +0 -406
  258. package/src/session/prompt/anthropic-20250930.txt +0 -166
  259. package/src/session/prompt/anthropic.txt +0 -105
  260. package/src/session/prompt/anthropic_spoof.txt +0 -1
  261. package/src/session/prompt/beast.txt +0 -147
  262. package/src/session/prompt/build-switch.txt +0 -5
  263. package/src/session/prompt/codex_header.txt +0 -79
  264. package/src/session/prompt/copilot-gpt-5.txt +0 -143
  265. package/src/session/prompt/gemini.txt +0 -155
  266. package/src/session/prompt/max-steps.txt +0 -16
  267. package/src/session/prompt/plan-reminder-anthropic.txt +0 -67
  268. package/src/session/prompt/plan.txt +0 -26
  269. package/src/session/prompt/qwen.txt +0 -109
  270. package/src/session/prompt.ts +0 -1820
  271. package/src/session/retry.ts +0 -90
  272. package/src/session/revert.ts +0 -108
  273. package/src/session/status.ts +0 -76
  274. package/src/session/summary.ts +0 -150
  275. package/src/session/system.ts +0 -152
  276. package/src/session/todo.ts +0 -37
  277. package/src/share/share-next.ts +0 -200
  278. package/src/share/share.ts +0 -92
  279. package/src/shell/shell.ts +0 -67
  280. package/src/skill/index.ts +0 -1
  281. package/src/skill/skill.ts +0 -136
  282. package/src/snapshot/index.ts +0 -236
  283. package/src/storage/storage.ts +0 -227
  284. package/src/tool/apply_patch.ts +0 -269
  285. package/src/tool/apply_patch.txt +0 -33
  286. package/src/tool/bash.ts +0 -259
  287. package/src/tool/bash.txt +0 -115
  288. package/src/tool/batch.ts +0 -175
  289. package/src/tool/batch.txt +0 -24
  290. package/src/tool/codesearch.ts +0 -132
  291. package/src/tool/codesearch.txt +0 -12
  292. package/src/tool/edit.ts +0 -645
  293. package/src/tool/edit.txt +0 -10
  294. package/src/tool/external-directory.ts +0 -32
  295. package/src/tool/glob.ts +0 -77
  296. package/src/tool/glob.txt +0 -6
  297. package/src/tool/grep.ts +0 -154
  298. package/src/tool/grep.txt +0 -8
  299. package/src/tool/invalid.ts +0 -17
  300. package/src/tool/ls.ts +0 -121
  301. package/src/tool/ls.txt +0 -1
  302. package/src/tool/lsp.ts +0 -96
  303. package/src/tool/lsp.txt +0 -19
  304. package/src/tool/multiedit.ts +0 -46
  305. package/src/tool/multiedit.txt +0 -41
  306. package/src/tool/plan-enter.txt +0 -14
  307. package/src/tool/plan-exit.txt +0 -13
  308. package/src/tool/plan.ts +0 -130
  309. package/src/tool/question.ts +0 -33
  310. package/src/tool/question.txt +0 -10
  311. package/src/tool/read.ts +0 -202
  312. package/src/tool/read.txt +0 -12
  313. package/src/tool/registry.ts +0 -164
  314. package/src/tool/skill.ts +0 -75
  315. package/src/tool/task.ts +0 -188
  316. package/src/tool/task.txt +0 -60
  317. package/src/tool/todo.ts +0 -53
  318. package/src/tool/todoread.txt +0 -14
  319. package/src/tool/todowrite.txt +0 -167
  320. package/src/tool/tool.ts +0 -88
  321. package/src/tool/truncation.ts +0 -106
  322. package/src/tool/webfetch.ts +0 -182
  323. package/src/tool/webfetch.txt +0 -13
  324. package/src/tool/websearch.ts +0 -150
  325. package/src/tool/websearch.txt +0 -14
  326. package/src/tool/write.ts +0 -80
  327. package/src/tool/write.txt +0 -8
  328. package/src/util/archive.ts +0 -16
  329. package/src/util/color.ts +0 -19
  330. package/src/util/context.ts +0 -25
  331. package/src/util/defer.ts +0 -12
  332. package/src/util/eventloop.ts +0 -20
  333. package/src/util/filesystem.ts +0 -93
  334. package/src/util/fn.ts +0 -11
  335. package/src/util/format.ts +0 -20
  336. package/src/util/iife.ts +0 -3
  337. package/src/util/keybind.ts +0 -103
  338. package/src/util/lazy.ts +0 -18
  339. package/src/util/locale.ts +0 -81
  340. package/src/util/lock.ts +0 -98
  341. package/src/util/log.ts +0 -180
  342. package/src/util/queue.ts +0 -32
  343. package/src/util/rpc.ts +0 -66
  344. package/src/util/scrap.ts +0 -10
  345. package/src/util/signal.ts +0 -12
  346. package/src/util/timeout.ts +0 -14
  347. package/src/util/token.ts +0 -7
  348. package/src/util/wildcard.ts +0 -56
  349. package/src/worktree/index.ts +0 -424
  350. package/sst-env.d.ts +0 -9
  351. package/test/acp/event-subscription.test.ts +0 -436
  352. package/test/agent/agent.test.ts +0 -638
  353. package/test/bun.test.ts +0 -53
  354. package/test/cli/github-action.test.ts +0 -129
  355. package/test/cli/github-remote.test.ts +0 -80
  356. package/test/cli/tui/transcript.test.ts +0 -297
  357. package/test/config/agent-color.test.ts +0 -66
  358. package/test/config/config.test.ts +0 -1414
  359. package/test/config/fixtures/empty-frontmatter.md +0 -4
  360. package/test/config/fixtures/frontmatter.md +0 -28
  361. package/test/config/fixtures/no-frontmatter.md +0 -1
  362. package/test/config/markdown.test.ts +0 -192
  363. package/test/file/ignore.test.ts +0 -10
  364. package/test/file/path-traversal.test.ts +0 -198
  365. package/test/fixture/fixture.ts +0 -45
  366. package/test/fixture/lsp/fake-lsp-server.js +0 -77
  367. package/test/ide/ide.test.ts +0 -82
  368. package/test/keybind.test.ts +0 -421
  369. package/test/lsp/client.test.ts +0 -95
  370. package/test/mcp/headers.test.ts +0 -153
  371. package/test/mcp/oauth-browser.test.ts +0 -261
  372. package/test/patch/patch.test.ts +0 -348
  373. package/test/permission/arity.test.ts +0 -33
  374. package/test/permission/next.test.ts +0 -652
  375. package/test/permission-task.test.ts +0 -319
  376. package/test/plugin/codex.test.ts +0 -123
  377. package/test/preload.ts +0 -65
  378. package/test/project/project.test.ts +0 -120
  379. package/test/provider/amazon-bedrock.test.ts +0 -268
  380. package/test/provider/gitlab-duo.test.ts +0 -286
  381. package/test/provider/provider.test.ts +0 -2149
  382. package/test/provider/transform.test.ts +0 -1596
  383. package/test/question/question.test.ts +0 -300
  384. package/test/scheduler.test.ts +0 -73
  385. package/test/server/session-list.test.ts +0 -39
  386. package/test/server/session-select.test.ts +0 -78
  387. package/test/session/compaction.test.ts +0 -293
  388. package/test/session/llm.test.ts +0 -90
  389. package/test/session/message-v2.test.ts +0 -662
  390. package/test/session/retry.test.ts +0 -131
  391. package/test/session/revert-compact.test.ts +0 -285
  392. package/test/session/session.test.ts +0 -71
  393. package/test/skill/skill.test.ts +0 -185
  394. package/test/snapshot/snapshot.test.ts +0 -939
  395. package/test/tool/__snapshots__/tool.test.ts.snap +0 -9
  396. package/test/tool/apply_patch.test.ts +0 -499
  397. package/test/tool/bash.test.ts +0 -320
  398. package/test/tool/external-directory.test.ts +0 -126
  399. package/test/tool/fixtures/large-image.png +0 -0
  400. package/test/tool/fixtures/models-api.json +0 -33453
  401. package/test/tool/grep.test.ts +0 -109
  402. package/test/tool/question.test.ts +0 -105
  403. package/test/tool/read.test.ts +0 -332
  404. package/test/tool/registry.test.ts +0 -76
  405. package/test/tool/truncation.test.ts +0 -159
  406. package/test/util/filesystem.test.ts +0 -39
  407. package/test/util/format.test.ts +0 -59
  408. package/test/util/iife.test.ts +0 -36
  409. package/test/util/lazy.test.ts +0 -50
  410. package/test/util/lock.test.ts +0 -72
  411. package/test/util/timeout.test.ts +0 -21
  412. package/test/util/wildcard.test.ts +0 -75
  413. package/tsconfig.json +0 -16
@@ -1,1361 +0,0 @@
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(pathToFileURL(path.join(Global.Path.config, "config")).href, {
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
- }