jonsoc 1.1.49 → 1.1.50

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