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,199 @@
1
+ import { BusEvent } from "@/bus/bus-event"
2
+ import { Bus } from "@/bus"
3
+ import z from "zod"
4
+ import { Log } from "../util/log"
5
+ import { Identifier } from "../id/id"
6
+ import { Plugin } from "../plugin"
7
+ import { Instance } from "../project/instance"
8
+ import { Wildcard } from "../util/wildcard"
9
+
10
+ export namespace Permission {
11
+ const log = Log.create({ service: "permission" })
12
+
13
+ function toKeys(pattern: Info["pattern"], type: string): string[] {
14
+ return pattern === undefined ? [type] : Array.isArray(pattern) ? pattern : [pattern]
15
+ }
16
+
17
+ function covered(keys: string[], approved: Record<string, boolean>): boolean {
18
+ const pats = Object.keys(approved)
19
+ return keys.every((k) => pats.some((p) => Wildcard.match(k, p)))
20
+ }
21
+
22
+ export const Info = z
23
+ .object({
24
+ id: z.string(),
25
+ type: z.string(),
26
+ pattern: z.union([z.string(), z.array(z.string())]).optional(),
27
+ sessionID: z.string(),
28
+ messageID: z.string(),
29
+ callID: z.string().optional(),
30
+ title: z.string(),
31
+ metadata: z.record(z.string(), z.any()),
32
+ time: z.object({
33
+ created: z.number(),
34
+ }),
35
+ })
36
+ .meta({
37
+ ref: "Permission",
38
+ })
39
+ export type Info = z.infer<typeof Info>
40
+
41
+ export const Event = {
42
+ Updated: BusEvent.define("permission.updated", Info),
43
+ Replied: BusEvent.define(
44
+ "permission.replied",
45
+ z.object({
46
+ sessionID: z.string(),
47
+ permissionID: z.string(),
48
+ response: z.string(),
49
+ }),
50
+ ),
51
+ }
52
+
53
+ const state = Instance.state(
54
+ () => {
55
+ const pending: {
56
+ [sessionID: string]: {
57
+ [permissionID: string]: {
58
+ info: Info
59
+ resolve: () => void
60
+ reject: (e: any) => void
61
+ }
62
+ }
63
+ } = {}
64
+
65
+ const approved: {
66
+ [sessionID: string]: {
67
+ [permissionID: string]: boolean
68
+ }
69
+ } = {}
70
+
71
+ return {
72
+ pending,
73
+ approved,
74
+ }
75
+ },
76
+ async (state) => {
77
+ for (const pending of Object.values(state.pending)) {
78
+ for (const item of Object.values(pending)) {
79
+ item.reject(new RejectedError(item.info.sessionID, item.info.id, item.info.callID, item.info.metadata))
80
+ }
81
+ }
82
+ },
83
+ )
84
+
85
+ export function pending() {
86
+ return state().pending
87
+ }
88
+
89
+ export async function ask(input: {
90
+ type: Info["type"]
91
+ title: Info["title"]
92
+ pattern?: Info["pattern"]
93
+ callID?: Info["callID"]
94
+ sessionID: Info["sessionID"]
95
+ messageID: Info["messageID"]
96
+ metadata: Info["metadata"]
97
+ }) {
98
+ const { pending, approved } = state()
99
+ log.info("asking", {
100
+ sessionID: input.sessionID,
101
+ messageID: input.messageID,
102
+ toolCallID: input.callID,
103
+ pattern: input.pattern,
104
+ })
105
+ const approvedForSession = approved[input.sessionID] || {}
106
+ const keys = toKeys(input.pattern, input.type)
107
+ if (covered(keys, approvedForSession)) return
108
+ const info: Info = {
109
+ id: Identifier.ascending("permission"),
110
+ type: input.type,
111
+ pattern: input.pattern,
112
+ sessionID: input.sessionID,
113
+ messageID: input.messageID,
114
+ callID: input.callID,
115
+ title: input.title,
116
+ metadata: input.metadata,
117
+ time: {
118
+ created: Date.now(),
119
+ },
120
+ }
121
+
122
+ switch (
123
+ await Plugin.trigger("permission.ask", info, {
124
+ status: "ask",
125
+ }).then((x) => x.status)
126
+ ) {
127
+ case "deny":
128
+ throw new RejectedError(info.sessionID, info.id, info.callID, info.metadata)
129
+ case "allow":
130
+ return
131
+ }
132
+
133
+ pending[input.sessionID] = pending[input.sessionID] || {}
134
+ return new Promise<void>((resolve, reject) => {
135
+ pending[input.sessionID][info.id] = {
136
+ info,
137
+ resolve,
138
+ reject,
139
+ }
140
+ Bus.publish(Event.Updated, info)
141
+ })
142
+ }
143
+
144
+ export const Response = z.enum(["once", "always", "reject"])
145
+ export type Response = z.infer<typeof Response>
146
+
147
+ export function respond(input: { sessionID: Info["sessionID"]; permissionID: Info["id"]; response: Response }) {
148
+ log.info("response", input)
149
+ const { pending, approved } = state()
150
+ const match = pending[input.sessionID]?.[input.permissionID]
151
+ if (!match) return
152
+ delete pending[input.sessionID][input.permissionID]
153
+ Bus.publish(Event.Replied, {
154
+ sessionID: input.sessionID,
155
+ permissionID: input.permissionID,
156
+ response: input.response,
157
+ })
158
+ if (input.response === "reject") {
159
+ match.reject(new RejectedError(input.sessionID, input.permissionID, match.info.callID, match.info.metadata))
160
+ return
161
+ }
162
+ match.resolve()
163
+ if (input.response === "always") {
164
+ approved[input.sessionID] = approved[input.sessionID] || {}
165
+ const approveKeys = toKeys(match.info.pattern, match.info.type)
166
+ for (const k of approveKeys) {
167
+ approved[input.sessionID][k] = true
168
+ }
169
+ const items = pending[input.sessionID]
170
+ if (!items) return
171
+ for (const item of Object.values(items)) {
172
+ const itemKeys = toKeys(item.info.pattern, item.info.type)
173
+ if (covered(itemKeys, approved[input.sessionID])) {
174
+ respond({
175
+ sessionID: item.info.sessionID,
176
+ permissionID: item.info.id,
177
+ response: input.response,
178
+ })
179
+ }
180
+ }
181
+ }
182
+ }
183
+
184
+ export class RejectedError extends Error {
185
+ constructor(
186
+ public readonly sessionID: string,
187
+ public readonly permissionID: string,
188
+ public readonly toolCallID?: string,
189
+ public readonly metadata?: Record<string, any>,
190
+ public readonly reason?: string,
191
+ ) {
192
+ super(
193
+ reason !== undefined
194
+ ? reason
195
+ : `The user rejected permission to use this specific tool call. You may try again with different parameters.`,
196
+ )
197
+ }
198
+ }
199
+ }
@@ -0,0 +1,101 @@
1
+ import type { Hooks, PluginInput, Plugin as PluginInstance } from "@bincode-ai/plugin"
2
+ import { Config } from "../config/config"
3
+ import { Bus } from "../bus"
4
+ import { Log } from "../util/log"
5
+ import { createBincodeClient } from "@bincode-ai/sdk"
6
+ import { Server } from "../server/server"
7
+ import { BunProc } from "../bun"
8
+ import { Instance } from "../project/instance"
9
+ import { Flag } from "../flag/flag"
10
+
11
+ export namespace Plugin {
12
+ const log = Log.create({ service: "plugin" })
13
+
14
+ const state = Instance.state(async () => {
15
+ const client = createBincodeClient({
16
+ baseUrl: "http://localhost:4096",
17
+ // @ts-ignore - fetch type incompatibility
18
+ fetch: async (...args) => Server.App().fetch(...args),
19
+ })
20
+ const config = await Config.get()
21
+ const hooks = []
22
+ const input: PluginInput = {
23
+ client,
24
+ project: Instance.project,
25
+ worktree: Instance.worktree,
26
+ directory: Instance.directory,
27
+ $: Bun.$,
28
+ }
29
+ const plugins = [...(config.plugin ?? [])]
30
+ if (!Flag.BINCODE_DISABLE_DEFAULT_PLUGINS) {
31
+ plugins.push("bincode-copilot-auth@0.0.9")
32
+ plugins.push("bincode-anthropic-auth@0.0.5")
33
+ }
34
+ for (let plugin of plugins) {
35
+ log.info("loading plugin", { path: plugin })
36
+ if (!plugin.startsWith("file://")) {
37
+ const lastAtIndex = plugin.lastIndexOf("@")
38
+ const pkg = lastAtIndex > 0 ? plugin.substring(0, lastAtIndex) : plugin
39
+ const version = lastAtIndex > 0 ? plugin.substring(lastAtIndex + 1) : "latest"
40
+ try {
41
+ plugin = await BunProc.install(pkg, version)
42
+ } catch (e) {
43
+ log.warn("failed to install plugin", { pkg, version, error: e instanceof Error ? e.message : String(e) })
44
+ continue
45
+ }
46
+ }
47
+ try {
48
+ const mod = await import(plugin)
49
+ for (const [_name, fn] of Object.entries<PluginInstance>(mod)) {
50
+ const init = await fn(input)
51
+ hooks.push(init)
52
+ }
53
+ } catch (e) {
54
+ log.warn("failed to load plugin", { plugin, error: e instanceof Error ? e.message : String(e) })
55
+ continue
56
+ }
57
+ }
58
+
59
+ return {
60
+ hooks,
61
+ input,
62
+ }
63
+ })
64
+
65
+ export async function trigger<
66
+ Name extends Exclude<keyof Required<Hooks>, "auth" | "event" | "tool">,
67
+ Input = Parameters<Required<Hooks>[Name]>[0],
68
+ Output = Parameters<Required<Hooks>[Name]>[1],
69
+ >(name: Name, input: Input, output: Output): Promise<Output> {
70
+ if (!name) return output
71
+ for (const hook of await state().then((x) => x.hooks)) {
72
+ const fn = hook[name]
73
+ if (!fn) continue
74
+ // @ts-expect-error if you feel adventurous, please fix the typing, make sure to bump the try-counter if you
75
+ // give up.
76
+ // try-counter: 2
77
+ await fn(input, output)
78
+ }
79
+ return output
80
+ }
81
+
82
+ export async function list() {
83
+ return state().then((x) => x.hooks)
84
+ }
85
+
86
+ export async function init() {
87
+ const hooks = await state().then((x) => x.hooks)
88
+ const config = await Config.get()
89
+ for (const hook of hooks) {
90
+ await hook.config?.(config)
91
+ }
92
+ Bus.subscribeAll(async (input) => {
93
+ const hooks = await state().then((x) => x.hooks)
94
+ for (const hook of hooks) {
95
+ hook["event"]?.({
96
+ event: input,
97
+ })
98
+ }
99
+ })
100
+ }
101
+ }
@@ -0,0 +1,31 @@
1
+ import { Plugin } from "../plugin"
2
+ import { Share } from "../share/share"
3
+ import { Format } from "../format"
4
+ import { LSP } from "../lsp"
5
+ import { FileWatcher } from "../file/watcher"
6
+ import { File } from "../file"
7
+ import { Project } from "./project"
8
+ import { Bus } from "../bus"
9
+ import { Command } from "../command"
10
+ import { Instance } from "./instance"
11
+ import { Vcs } from "./vcs"
12
+ import { Log } from "@/util/log"
13
+ import { ShareNext } from "@/share/share-next"
14
+
15
+ export async function InstanceBootstrap() {
16
+ Log.Default.info("bootstrapping", { directory: Instance.directory })
17
+ await Plugin.init()
18
+ Share.init()
19
+ ShareNext.init()
20
+ Format.init()
21
+ await LSP.init()
22
+ FileWatcher.init()
23
+ File.init()
24
+ Vcs.init()
25
+
26
+ Bus.subscribe(Command.Event.Executed, async (payload) => {
27
+ if (payload.properties.name === Command.Default.INIT) {
28
+ await Project.setInitialized(Instance.project.id)
29
+ }
30
+ })
31
+ }
@@ -0,0 +1,78 @@
1
+ import { Log } from "@/util/log"
2
+ import { Context } from "../util/context"
3
+ import { Project } from "./project"
4
+ import { State } from "./state"
5
+ import { iife } from "@/util/iife"
6
+ import { GlobalBus } from "@/bus/global"
7
+
8
+ interface Context {
9
+ directory: string
10
+ worktree: string
11
+ project: Project.Info
12
+ }
13
+ const context = Context.create<Context>("instance")
14
+ const cache = new Map<string, Promise<Context>>()
15
+
16
+ export const Instance = {
17
+ async provide<R>(input: { directory: string; init?: () => Promise<any>; fn: () => R }): Promise<R> {
18
+ let existing = cache.get(input.directory)
19
+ if (!existing) {
20
+ Log.Default.info("creating instance", { directory: input.directory })
21
+ existing = iife(async () => {
22
+ const project = await Project.fromDirectory(input.directory)
23
+ const ctx = {
24
+ directory: input.directory,
25
+ worktree: project.worktree,
26
+ project,
27
+ }
28
+ await context.provide(ctx, async () => {
29
+ await input.init?.()
30
+ })
31
+ return ctx
32
+ })
33
+ cache.set(input.directory, existing)
34
+ }
35
+ const ctx = await existing
36
+ return context.provide(ctx, async () => {
37
+ return input.fn()
38
+ })
39
+ },
40
+ get directory() {
41
+ return context.use().directory
42
+ },
43
+ get worktree() {
44
+ return context.use().worktree
45
+ },
46
+ get project() {
47
+ return context.use().project
48
+ },
49
+ state<S>(init: () => S, dispose?: (state: Awaited<S>) => Promise<void>): () => S {
50
+ return State.create(() => Instance.directory, init, dispose)
51
+ },
52
+ async dispose() {
53
+ Log.Default.info("disposing instance", { directory: Instance.directory })
54
+ await State.dispose(Instance.directory)
55
+ cache.delete(Instance.directory)
56
+ GlobalBus.emit("event", {
57
+ directory: Instance.directory,
58
+ payload: {
59
+ type: "server.instance.disposed",
60
+ properties: {
61
+ directory: Instance.directory,
62
+ },
63
+ },
64
+ })
65
+ },
66
+ async disposeAll() {
67
+ Log.Default.info("disposing all instances")
68
+ for (const [_key, value] of cache) {
69
+ const awaited = await value.catch(() => {})
70
+ if (awaited) {
71
+ await context.provide(await value, async () => {
72
+ await Instance.dispose()
73
+ })
74
+ }
75
+ }
76
+ cache.clear()
77
+ },
78
+ }
@@ -0,0 +1,221 @@
1
+ import z from "zod"
2
+ import { Filesystem } from "../util/filesystem"
3
+ import path from "path"
4
+ import { $ } from "bun"
5
+ import { Storage } from "../storage/storage"
6
+ import { Log } from "../util/log"
7
+ import { Flag } from "@/flag/flag"
8
+ import { Session } from "../session"
9
+ import { work } from "../util/queue"
10
+ import { fn } from "@bincode-ai/util/fn"
11
+ import { BusEvent } from "@/bus/bus-event"
12
+ import { iife } from "@/util/iife"
13
+ import { GlobalBus } from "@/bus/global"
14
+
15
+ export namespace Project {
16
+ const log = Log.create({ service: "project" })
17
+ export const Info = z
18
+ .object({
19
+ id: z.string(),
20
+ worktree: z.string(),
21
+ vcs: z.literal("git").optional(),
22
+ name: z.string().optional(),
23
+ icon: z
24
+ .object({
25
+ url: z.string().optional(),
26
+ color: z.string().optional(),
27
+ })
28
+ .optional(),
29
+ time: z.object({
30
+ created: z.number(),
31
+ updated: z.number(),
32
+ initialized: z.number().optional(),
33
+ }),
34
+ })
35
+ .meta({
36
+ ref: "Project",
37
+ })
38
+ export type Info = z.infer<typeof Info>
39
+
40
+ export const Event = {
41
+ Updated: BusEvent.define("project.updated", Info),
42
+ }
43
+
44
+ export async function fromDirectory(directory: string) {
45
+ log.info("fromDirectory", { directory })
46
+
47
+ const { id, worktree, vcs } = await iife(async () => {
48
+ const matches = Filesystem.up({ targets: [".git"], start: directory })
49
+ const git = await matches.next().then((x) => x.value)
50
+ await matches.return()
51
+ if (git) {
52
+ let worktree = path.dirname(git)
53
+ let id = await Bun.file(path.join(git, "bincode"))
54
+ .text()
55
+ .then((x) => x.trim())
56
+ .catch(() => {})
57
+ if (!id) {
58
+ const roots = await $`git rev-list --max-parents=0 --all`
59
+ .quiet()
60
+ .nothrow()
61
+ .cwd(worktree)
62
+ .text()
63
+ .then((x) =>
64
+ x
65
+ .split("\n")
66
+ .filter(Boolean)
67
+ .map((x) => x.trim())
68
+ .toSorted(),
69
+ )
70
+ id = roots[0]
71
+ if (id) Bun.file(path.join(git, "bincode")).write(id)
72
+ }
73
+ if (!id)
74
+ return {
75
+ id: "global",
76
+ worktree,
77
+ vcs: "git",
78
+ }
79
+ worktree = await $`git rev-parse --show-toplevel`
80
+ .quiet()
81
+ .nothrow()
82
+ .cwd(worktree)
83
+ .text()
84
+ .then((x) => path.resolve(worktree, x.trim()))
85
+ return { id, worktree, vcs: "git" }
86
+ }
87
+
88
+ return {
89
+ id: "global",
90
+ worktree: "/",
91
+ vcs: Info.shape.vcs.parse(Flag.BINCODE_FAKE_VCS),
92
+ }
93
+ })
94
+
95
+ let existing = await Storage.read<Info>(["project", id]).catch(() => undefined)
96
+ if (!existing) {
97
+ existing = {
98
+ id,
99
+ worktree,
100
+ vcs: vcs as Info["vcs"],
101
+ time: {
102
+ created: Date.now(),
103
+ updated: Date.now(),
104
+ },
105
+ }
106
+ if (id !== "global") {
107
+ await migrateFromGlobal(id, worktree)
108
+ }
109
+ }
110
+ if (Flag.BINCODE_EXPERIMENTAL_ICON_DISCOVERY) discover(existing)
111
+ const result: Info = {
112
+ ...existing,
113
+ worktree,
114
+ vcs: vcs as Info["vcs"],
115
+ time: {
116
+ ...existing.time,
117
+ updated: Date.now(),
118
+ },
119
+ }
120
+ await Storage.write<Info>(["project", id], result)
121
+ GlobalBus.emit("event", {
122
+ payload: {
123
+ type: Event.Updated.type,
124
+ properties: result,
125
+ },
126
+ })
127
+ return result
128
+ }
129
+
130
+ export async function discover(input: Info) {
131
+ if (input.vcs !== "git") return
132
+ if (input.icon?.url) return
133
+ const glob = new Bun.Glob("**/{favicon}.{ico,png,svg,jpg,jpeg,webp}")
134
+ const matches = await Array.fromAsync(
135
+ glob.scan({
136
+ cwd: input.worktree,
137
+ absolute: true,
138
+ onlyFiles: true,
139
+ followSymlinks: false,
140
+ dot: false,
141
+ }),
142
+ )
143
+ const shortest = matches.sort((a, b) => a.length - b.length)[0]
144
+ if (!shortest) return
145
+ const file = Bun.file(shortest)
146
+ const buffer = await file.arrayBuffer()
147
+ const base64 = Buffer.from(buffer).toString("base64")
148
+ const mime = file.type || "image/png"
149
+ const url = `data:${mime};base64,${base64}`
150
+ await update({
151
+ projectID: input.id,
152
+ icon: {
153
+ url,
154
+ },
155
+ })
156
+ return
157
+ }
158
+
159
+ async function migrateFromGlobal(newProjectID: string, worktree: string) {
160
+ const globalProject = await Storage.read<Info>(["project", "global"]).catch(() => undefined)
161
+ if (!globalProject) return
162
+
163
+ const globalSessions = await Storage.list(["session", "global"]).catch(() => [])
164
+ if (globalSessions.length === 0) return
165
+
166
+ log.info("migrating sessions from global", { newProjectID, worktree, count: globalSessions.length })
167
+
168
+ await work(10, globalSessions, async (key) => {
169
+ const sessionID = key[key.length - 1]
170
+ const session = await Storage.read<Session.Info>(key).catch(() => undefined)
171
+ if (!session) return
172
+ if (session.directory && session.directory !== worktree) return
173
+
174
+ session.projectID = newProjectID
175
+ log.info("migrating session", { sessionID, from: "global", to: newProjectID })
176
+ await Storage.write(["session", newProjectID, sessionID], session)
177
+ await Storage.remove(key)
178
+ }).catch((error) => {
179
+ log.error("failed to migrate sessions from global to project", { error, projectId: newProjectID })
180
+ })
181
+ }
182
+
183
+ export async function setInitialized(projectID: string) {
184
+ await Storage.update<Info>(["project", projectID], (draft) => {
185
+ draft.time.initialized = Date.now()
186
+ })
187
+ }
188
+
189
+ export async function list() {
190
+ const keys = await Storage.list(["project"])
191
+ return await Promise.all(keys.map((x) => Storage.read<Info>(x)))
192
+ }
193
+
194
+ export const update = fn(
195
+ z.object({
196
+ projectID: z.string(),
197
+ name: z.string().optional(),
198
+ icon: Info.shape.icon.optional(),
199
+ }),
200
+ async (input) => {
201
+ const result = await Storage.update<Info>(["project", input.projectID], (draft) => {
202
+ if (input.name !== undefined) draft.name = input.name
203
+ if (input.icon !== undefined) {
204
+ draft.icon = {
205
+ ...draft.icon,
206
+ }
207
+ if (input.icon.url !== undefined) draft.icon.url = input.icon.url
208
+ if (input.icon.color !== undefined) draft.icon.color = input.icon.color
209
+ }
210
+ draft.time.updated = Date.now()
211
+ })
212
+ GlobalBus.emit("event", {
213
+ payload: {
214
+ type: Event.Updated.type,
215
+ properties: result,
216
+ },
217
+ })
218
+ return result
219
+ },
220
+ )
221
+ }
@@ -0,0 +1,65 @@
1
+ import { Log } from "@/util/log"
2
+
3
+ export namespace State {
4
+ interface Entry {
5
+ state: any
6
+ dispose?: (state: any) => Promise<void>
7
+ }
8
+
9
+ const log = Log.create({ service: "state" })
10
+ const recordsByKey = new Map<string, Map<any, Entry>>()
11
+
12
+ export function create<S>(root: () => string, init: () => S, dispose?: (state: Awaited<S>) => Promise<void>) {
13
+ return () => {
14
+ const key = root()
15
+ let entries = recordsByKey.get(key)
16
+ if (!entries) {
17
+ entries = new Map<string, Entry>()
18
+ recordsByKey.set(key, entries)
19
+ }
20
+ const exists = entries.get(init)
21
+ if (exists) return exists.state as S
22
+ const state = init()
23
+ entries.set(init, {
24
+ state,
25
+ dispose,
26
+ })
27
+ return state
28
+ }
29
+ }
30
+
31
+ export async function dispose(key: string) {
32
+ const entries = recordsByKey.get(key)
33
+ if (!entries) return
34
+
35
+ log.info("waiting for state disposal to complete", { key })
36
+
37
+ let disposalFinished = false
38
+
39
+ setTimeout(() => {
40
+ if (!disposalFinished) {
41
+ log.warn(
42
+ "state disposal is taking an unusually long time - if it does not complete in a reasonable time, please report this as a bug",
43
+ { key },
44
+ )
45
+ }
46
+ }, 10000).unref()
47
+
48
+ const tasks: Promise<void>[] = []
49
+ for (const entry of entries.values()) {
50
+ if (!entry.dispose) continue
51
+
52
+ const task = Promise.resolve(entry.state)
53
+ .then((state) => entry.dispose!(state))
54
+ .catch((error) => {
55
+ log.error("Error while disposing state:", { error, key })
56
+ })
57
+
58
+ tasks.push(task)
59
+ }
60
+ entries.clear()
61
+ await Promise.all(tasks)
62
+ disposalFinished = true
63
+ log.info("state disposal completed", { key })
64
+ }
65
+ }