@stonerzju/opencode 1.2.16-offline.1

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