opencode-v2 1.1.53

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