@bloxystudios/bloxycode 1.0.1 → 1.0.4

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