bincode-cli 1.0.1

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