chad-code 1.3.1 → 1.3.2

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