@code0123/opencode-android-arm64 1.1.55 → 1.1.56

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