borgmcp 1.1.15 → 2.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 (459) hide show
  1. package/CONTRIBUTING.md +15 -0
  2. package/LICENSE +201 -33
  3. package/NOTICE +2 -0
  4. package/README.md +85 -36
  5. package/SECURITY.md +7 -0
  6. package/dist/agent-runtime.d.ts.map +1 -0
  7. package/dist/agent-runtime.js +63 -1
  8. package/dist/agent-runtime.js.map +1 -0
  9. package/dist/assimilate-cmd.d.ts +96 -17
  10. package/dist/assimilate-cmd.d.ts.map +1 -0
  11. package/dist/assimilate-cmd.js +1396 -48
  12. package/dist/assimilate-cmd.js.map +1 -0
  13. package/dist/assimilate-deps.d.ts.map +1 -0
  14. package/dist/assimilate-deps.js +384 -3
  15. package/dist/assimilate-deps.js.map +1 -0
  16. package/dist/assimilate-guard.d.ts +5 -7
  17. package/dist/assimilate-guard.d.ts.map +1 -0
  18. package/dist/assimilate-guard.js +60 -2
  19. package/dist/assimilate-guard.js.map +1 -0
  20. package/dist/assimilate-welcome.d.ts +1 -1
  21. package/dist/assimilate-welcome.d.ts.map +1 -0
  22. package/dist/assimilate-welcome.js +32 -2
  23. package/dist/assimilate-welcome.js.map +1 -0
  24. package/dist/auth-env.d.ts +7 -50
  25. package/dist/auth-env.d.ts.map +1 -0
  26. package/dist/auth-env.js +22 -1
  27. package/dist/auth-env.js.map +1 -0
  28. package/dist/backends/launch-all-pastelist.d.ts.map +1 -0
  29. package/dist/backends/launch-all-pastelist.js +11 -4
  30. package/dist/backends/launch-all-pastelist.js.map +1 -0
  31. package/dist/backends/launch-all-tmux.d.ts.map +1 -0
  32. package/dist/backends/launch-all-tmux.js +49 -1
  33. package/dist/backends/launch-all-tmux.js.map +1 -0
  34. package/dist/backends/launch-all-windows.d.ts.map +1 -0
  35. package/dist/backends/launch-all-windows.js +86 -12
  36. package/dist/backends/launch-all-windows.js.map +1 -0
  37. package/dist/bare-launch-menu.d.ts.map +1 -0
  38. package/dist/bare-launch-menu.js +83 -6
  39. package/dist/bare-launch-menu.js.map +1 -0
  40. package/dist/claude-launch-args.d.ts.map +1 -0
  41. package/dist/claude-launch-args.js +34 -1
  42. package/dist/claude-launch-args.js.map +1 -0
  43. package/dist/claude.d.ts.map +1 -0
  44. package/dist/claude.js +486 -14
  45. package/dist/claude.js.map +1 -0
  46. package/dist/cleanup-cmd.d.ts +5 -5
  47. package/dist/cleanup-cmd.d.ts.map +1 -0
  48. package/dist/cleanup-cmd.js +453 -14
  49. package/dist/cleanup-cmd.js.map +1 -0
  50. package/dist/clear-rewake-core.d.ts.map +1 -0
  51. package/dist/clear-rewake-core.js +23 -2
  52. package/dist/clear-rewake-core.js.map +1 -0
  53. package/dist/clear-rewake.d.ts.map +1 -0
  54. package/dist/clear-rewake.js +19 -1
  55. package/dist/clear-rewake.js.map +1 -0
  56. package/dist/cli-help.d.ts +5 -0
  57. package/dist/cli-help.d.ts.map +1 -0
  58. package/dist/cli-help.js +104 -56
  59. package/dist/cli-help.js.map +1 -0
  60. package/dist/cli-platform.d.ts.map +1 -0
  61. package/dist/cli-platform.js +106 -4
  62. package/dist/cli-platform.js.map +1 -0
  63. package/dist/cli-tool-approval.d.ts +84 -0
  64. package/dist/cli-tool-approval.d.ts.map +1 -0
  65. package/dist/cli-tool-approval.js +583 -0
  66. package/dist/cli-tool-approval.js.map +1 -0
  67. package/dist/codex-app-server.d.ts.map +1 -0
  68. package/dist/codex-app-server.js +228 -4
  69. package/dist/codex-app-server.js.map +1 -0
  70. package/dist/codex-app-wake.d.ts.map +1 -0
  71. package/dist/codex-app-wake.js +432 -2
  72. package/dist/codex-app-wake.js.map +1 -0
  73. package/dist/codex-launch.d.ts.map +1 -0
  74. package/dist/codex-launch.js +102 -2
  75. package/dist/codex-launch.js.map +1 -0
  76. package/dist/codex-remote.d.ts +6 -1
  77. package/dist/codex-remote.d.ts.map +1 -0
  78. package/dist/codex-remote.js +394 -1
  79. package/dist/codex-remote.js.map +1 -0
  80. package/dist/codex-wake-resolve.d.ts.map +1 -0
  81. package/dist/codex-wake-resolve.js +127 -1
  82. package/dist/codex-wake-resolve.js.map +1 -0
  83. package/dist/config-utils.d.ts +2 -2
  84. package/dist/config-utils.d.ts.map +1 -0
  85. package/dist/config-utils.js +766 -3
  86. package/dist/config-utils.js.map +1 -0
  87. package/dist/config.d.ts +98 -61
  88. package/dist/config.d.ts.map +1 -0
  89. package/dist/config.js +426 -1
  90. package/dist/config.js.map +1 -0
  91. package/dist/console-prefix.d.ts.map +1 -0
  92. package/dist/console-prefix.js +96 -1
  93. package/dist/console-prefix.js.map +1 -0
  94. package/dist/cube-name.d.ts.map +1 -0
  95. package/dist/cube-name.js +67 -1
  96. package/dist/cube-name.js.map +1 -0
  97. package/dist/cubes.d.ts +126 -18
  98. package/dist/cubes.d.ts.map +1 -0
  99. package/dist/cubes.js +412 -4
  100. package/dist/cubes.js.map +1 -0
  101. package/dist/debug.d.ts.map +1 -0
  102. package/dist/debug.js +71 -1
  103. package/dist/debug.js.map +1 -0
  104. package/dist/direct-log.d.ts.map +1 -0
  105. package/dist/direct-log.js +11 -1
  106. package/dist/direct-log.js.map +1 -0
  107. package/dist/docs-sections.d.ts +11 -10
  108. package/dist/docs-sections.d.ts.map +1 -0
  109. package/dist/docs-sections.js +113 -3
  110. package/dist/docs-sections.js.map +1 -0
  111. package/dist/drone-lifecycle.d.ts +5 -21
  112. package/dist/drone-lifecycle.d.ts.map +1 -0
  113. package/dist/drone-lifecycle.js +57 -8
  114. package/dist/drone-lifecycle.js.map +1 -0
  115. package/dist/drone-management.d.ts +29 -0
  116. package/dist/drone-management.d.ts.map +1 -0
  117. package/dist/drone-management.js +109 -0
  118. package/dist/drone-management.js.map +1 -0
  119. package/dist/ensure-mcp-config.d.ts.map +1 -0
  120. package/dist/ensure-mcp-config.js +36 -1
  121. package/dist/ensure-mcp-config.js.map +1 -0
  122. package/dist/evict-drone.d.ts +10 -2
  123. package/dist/evict-drone.d.ts.map +1 -0
  124. package/dist/evict-drone.js +60 -1
  125. package/dist/evict-drone.js.map +1 -0
  126. package/dist/gc-orphan-inboxes.d.ts.map +1 -0
  127. package/dist/gc-orphan-inboxes.js +177 -1
  128. package/dist/gc-orphan-inboxes.js.map +1 -0
  129. package/dist/inbox-monitor.d.ts +1 -1
  130. package/dist/inbox-monitor.d.ts.map +1 -0
  131. package/dist/inbox-monitor.js +856 -3
  132. package/dist/inbox-monitor.js.map +1 -0
  133. package/dist/index.d.ts +6 -4
  134. package/dist/index.d.ts.map +1 -0
  135. package/dist/index.js +1034 -37
  136. package/dist/index.js.map +1 -0
  137. package/dist/launch-all-cmd.d.ts.map +1 -0
  138. package/dist/launch-all-cmd.js +377 -37
  139. package/dist/launch-all-cmd.js.map +1 -0
  140. package/dist/launch-all-command.d.ts.map +1 -0
  141. package/dist/launch-all-command.js +24 -1
  142. package/dist/launch-all-command.js.map +1 -0
  143. package/dist/launch-all-deps.d.ts +3 -8
  144. package/dist/launch-all-deps.d.ts.map +1 -0
  145. package/dist/launch-all-deps.js +99 -1
  146. package/dist/launch-all-deps.js.map +1 -0
  147. package/dist/launch-all-discovery.d.ts +1 -0
  148. package/dist/launch-all-discovery.d.ts.map +1 -0
  149. package/dist/launch-all-discovery.js +90 -4
  150. package/dist/launch-all-discovery.js.map +1 -0
  151. package/dist/launch-all-locks.d.ts.map +1 -0
  152. package/dist/launch-all-locks.js +54 -1
  153. package/dist/launch-all-locks.js.map +1 -0
  154. package/dist/launch-gate.d.ts +2 -2
  155. package/dist/launch-gate.d.ts.map +1 -0
  156. package/dist/launch-gate.js +73 -1
  157. package/dist/launch-gate.js.map +1 -0
  158. package/dist/lifecycle-log-guard.d.ts.map +1 -0
  159. package/dist/lifecycle-log-guard.js +93 -2
  160. package/dist/lifecycle-log-guard.js.map +1 -0
  161. package/dist/list-roles-render.d.ts.map +1 -0
  162. package/dist/list-roles-render.js +40 -6
  163. package/dist/list-roles-render.js.map +1 -0
  164. package/dist/local-log-routing.d.ts +19 -0
  165. package/dist/local-log-routing.d.ts.map +1 -0
  166. package/dist/local-log-routing.js +67 -0
  167. package/dist/local-log-routing.js.map +1 -0
  168. package/dist/local-manage-tool-result.d.ts +8 -0
  169. package/dist/local-manage-tool-result.d.ts.map +1 -0
  170. package/dist/local-manage-tool-result.js +10 -0
  171. package/dist/local-manage-tool-result.js.map +1 -0
  172. package/dist/local-server-cursor.d.ts +34 -0
  173. package/dist/local-server-cursor.d.ts.map +1 -0
  174. package/dist/local-server-cursor.js +151 -0
  175. package/dist/local-server-cursor.js.map +1 -0
  176. package/dist/log-audit.d.ts.map +1 -0
  177. package/dist/log-audit.js +194 -3
  178. package/dist/log-audit.js.map +1 -0
  179. package/dist/log-stream.d.ts +31 -18
  180. package/dist/log-stream.d.ts.map +1 -0
  181. package/dist/log-stream.js +1214 -12
  182. package/dist/log-stream.js.map +1 -0
  183. package/dist/model-presets.d.ts.map +1 -0
  184. package/dist/model-presets.js +19 -1
  185. package/dist/model-presets.js.map +1 -0
  186. package/dist/name-validator.d.ts.map +1 -0
  187. package/dist/name-validator.js +22 -1
  188. package/dist/name-validator.js.map +1 -0
  189. package/dist/opencode-drone.d.ts.map +1 -0
  190. package/dist/opencode-drone.js +438 -4
  191. package/dist/opencode-drone.js.map +1 -0
  192. package/dist/opencode-plugin.d.ts +1 -1
  193. package/dist/opencode-plugin.d.ts.map +1 -0
  194. package/dist/opencode-plugin.js +29 -4
  195. package/dist/opencode-plugin.js.map +1 -0
  196. package/dist/parse-assimilate-args.d.ts +1 -1
  197. package/dist/parse-assimilate-args.d.ts.map +1 -0
  198. package/dist/parse-assimilate-args.js +125 -1
  199. package/dist/parse-assimilate-args.js.map +1 -0
  200. package/dist/parse-launch-all-args.d.ts.map +1 -0
  201. package/dist/parse-launch-all-args.js +70 -1
  202. package/dist/parse-launch-all-args.js.map +1 -0
  203. package/dist/postinstall-banner.d.ts.map +1 -0
  204. package/dist/postinstall-banner.js +27 -2
  205. package/dist/postinstall-banner.js.map +1 -0
  206. package/dist/postinstall.d.ts.map +1 -0
  207. package/dist/postinstall.js +32 -5
  208. package/dist/postinstall.js.map +1 -0
  209. package/dist/readiness-probe.d.ts.map +1 -0
  210. package/dist/readiness-probe.js +9 -1
  211. package/dist/readiness-probe.js.map +1 -0
  212. package/dist/regen-format.d.ts.map +1 -0
  213. package/dist/regen-format.js +545 -13
  214. package/dist/regen-format.js.map +1 -0
  215. package/dist/regen.d.ts.map +1 -0
  216. package/dist/regen.js +141 -5
  217. package/dist/regen.js.map +1 -0
  218. package/dist/remote-client.d.ts +65 -175
  219. package/dist/remote-client.d.ts.map +1 -0
  220. package/dist/remote-client.js +942 -1
  221. package/dist/remote-client.js.map +1 -0
  222. package/dist/reset-local-seat-cmd.d.ts +50 -0
  223. package/dist/reset-local-seat-cmd.d.ts.map +1 -0
  224. package/dist/reset-local-seat-cmd.js +169 -0
  225. package/dist/reset-local-seat-cmd.js.map +1 -0
  226. package/dist/role-match.d.ts.map +1 -0
  227. package/dist/role-match.js +23 -1
  228. package/dist/role-match.js.map +1 -0
  229. package/dist/role-resolver.d.ts.map +1 -0
  230. package/dist/role-resolver.js +60 -1
  231. package/dist/role-resolver.js.map +1 -0
  232. package/dist/roster-render.d.ts.map +1 -0
  233. package/dist/roster-render.js +121 -3
  234. package/dist/roster-render.js.map +1 -0
  235. package/dist/seat-probe.d.ts +32 -13
  236. package/dist/seat-probe.d.ts.map +1 -0
  237. package/dist/seat-probe.js +78 -1
  238. package/dist/seat-probe.js.map +1 -0
  239. package/dist/seat-store.d.ts +76 -0
  240. package/dist/seat-store.d.ts.map +1 -0
  241. package/dist/seat-store.js +309 -0
  242. package/dist/seat-store.js.map +1 -0
  243. package/dist/seats.d.ts +303 -0
  244. package/dist/seats.d.ts.map +1 -0
  245. package/dist/seats.js +551 -0
  246. package/dist/seats.js.map +1 -0
  247. package/dist/self-path.d.ts +27 -0
  248. package/dist/self-path.d.ts.map +1 -0
  249. package/dist/self-path.js +43 -0
  250. package/dist/self-path.js.map +1 -0
  251. package/dist/server-endpoint.d.ts +9 -0
  252. package/dist/server-endpoint.d.ts.map +1 -0
  253. package/dist/server-endpoint.js +38 -0
  254. package/dist/server-endpoint.js.map +1 -0
  255. package/dist/server-errors.d.ts +50 -0
  256. package/dist/server-errors.d.ts.map +1 -0
  257. package/dist/server-errors.js +79 -0
  258. package/dist/server-errors.js.map +1 -0
  259. package/dist/server-handshake.d.ts +197 -0
  260. package/dist/server-handshake.d.ts.map +1 -0
  261. package/dist/server-handshake.js +505 -0
  262. package/dist/server-handshake.js.map +1 -0
  263. package/dist/server-response.d.ts +3 -0
  264. package/dist/server-response.d.ts.map +1 -0
  265. package/dist/server-response.js +67 -0
  266. package/dist/server-response.js.map +1 -0
  267. package/dist/server-trust.d.ts +14 -0
  268. package/dist/server-trust.d.ts.map +1 -0
  269. package/dist/server-trust.js +225 -0
  270. package/dist/server-trust.js.map +1 -0
  271. package/dist/setup-confirm.d.ts +3 -3
  272. package/dist/setup-confirm.d.ts.map +1 -0
  273. package/dist/setup-confirm.js +126 -2
  274. package/dist/setup-confirm.js.map +1 -0
  275. package/dist/setup.d.ts +5 -3
  276. package/dist/setup.d.ts.map +1 -0
  277. package/dist/setup.js +169 -46
  278. package/dist/setup.js.map +1 -0
  279. package/dist/shell-escape.d.ts.map +1 -0
  280. package/dist/shell-escape.js +22 -1
  281. package/dist/shell-escape.js.map +1 -0
  282. package/dist/spawn.d.ts +2 -2
  283. package/dist/spawn.d.ts.map +1 -0
  284. package/dist/spawn.js +29 -10
  285. package/dist/spawn.js.map +1 -0
  286. package/dist/startup-services.d.ts +0 -1
  287. package/dist/startup-services.d.ts.map +1 -0
  288. package/dist/startup-services.js +26 -1
  289. package/dist/startup-services.js.map +1 -0
  290. package/dist/stream-owner.d.ts +6 -2
  291. package/dist/stream-owner.d.ts.map +1 -0
  292. package/dist/stream-owner.js +547 -2
  293. package/dist/stream-owner.js.map +1 -0
  294. package/dist/stream-status.d.ts +1 -1
  295. package/dist/stream-status.d.ts.map +1 -0
  296. package/dist/stream-status.js +268 -3
  297. package/dist/stream-status.js.map +1 -0
  298. package/dist/sync-roles-render.d.ts.map +1 -0
  299. package/dist/sync-roles-render.js +118 -3
  300. package/dist/sync-roles-render.js.map +1 -0
  301. package/dist/sync.d.ts +1 -1
  302. package/dist/sync.d.ts.map +1 -0
  303. package/dist/sync.js +286 -22
  304. package/dist/sync.js.map +1 -0
  305. package/dist/terminal-title.d.ts.map +1 -0
  306. package/dist/terminal-title.js +68 -1
  307. package/dist/terminal-title.js.map +1 -0
  308. package/dist/token-store.d.ts +17 -111
  309. package/dist/token-store.d.ts.map +1 -0
  310. package/dist/token-store.js +81 -1
  311. package/dist/token-store.js.map +1 -0
  312. package/dist/tool-manifest.d.ts +4 -8
  313. package/dist/tool-manifest.d.ts.map +1 -0
  314. package/dist/tool-manifest.js +554 -1
  315. package/dist/tool-manifest.js.map +1 -0
  316. package/dist/tool-scope.d.ts +8 -12
  317. package/dist/tool-scope.d.ts.map +1 -0
  318. package/dist/tool-scope.js +97 -1
  319. package/dist/tool-scope.js.map +1 -0
  320. package/dist/types.d.ts +1 -5
  321. package/dist/types.d.ts.map +1 -0
  322. package/dist/types.js +5 -0
  323. package/dist/types.js.map +1 -0
  324. package/dist/unknown-subcommand.d.ts +1 -1
  325. package/dist/unknown-subcommand.d.ts.map +1 -0
  326. package/dist/unknown-subcommand.js +37 -1
  327. package/dist/unknown-subcommand.js.map +1 -0
  328. package/dist/version.d.ts +1 -1
  329. package/dist/version.d.ts.map +1 -0
  330. package/dist/version.js +78 -2
  331. package/dist/version.js.map +1 -0
  332. package/dist/working-repo.d.ts.map +1 -0
  333. package/dist/working-repo.js +81 -1
  334. package/dist/working-repo.js.map +1 -0
  335. package/dist/worktree-lifecycle.d.ts.map +1 -0
  336. package/dist/worktree-lifecycle.js +205 -2
  337. package/dist/worktree-lifecycle.js.map +1 -0
  338. package/docs/EXTRACTION_PROVENANCE.md +40 -0
  339. package/docs/LOCAL_SERVER.md +103 -0
  340. package/docs/RELEASING.md +120 -0
  341. package/package.json +52 -34
  342. package/src/agent-runtime.ts +69 -0
  343. package/src/assimilate-cmd.ts +1864 -0
  344. package/src/assimilate-deps.ts +444 -0
  345. package/src/assimilate-guard.ts +84 -0
  346. package/src/assimilate-welcome.ts +39 -0
  347. package/src/auth-env.ts +21 -0
  348. package/src/backends/launch-all-pastelist.ts +18 -0
  349. package/src/backends/launch-all-tmux.ts +75 -0
  350. package/src/backends/launch-all-windows.ts +110 -0
  351. package/src/bare-launch-menu.ts +148 -0
  352. package/src/claude-launch-args.ts +35 -0
  353. package/src/claude.ts +561 -0
  354. package/src/cleanup-cmd.ts +581 -0
  355. package/src/clear-rewake-core.ts +34 -0
  356. package/src/clear-rewake.ts +18 -0
  357. package/src/cli-help.ts +116 -0
  358. package/src/cli-platform.ts +127 -0
  359. package/src/cli-tool-approval.ts +716 -0
  360. package/src/codex-app-server.ts +238 -0
  361. package/src/codex-app-wake.ts +512 -0
  362. package/src/codex-launch.ts +140 -0
  363. package/src/codex-remote.ts +500 -0
  364. package/src/codex-wake-resolve.ts +155 -0
  365. package/src/config-utils.ts +811 -0
  366. package/src/config.ts +595 -0
  367. package/src/console-prefix.ts +99 -0
  368. package/src/cube-name.ts +69 -0
  369. package/src/cubes.ts +583 -0
  370. package/src/debug.ts +73 -0
  371. package/src/direct-log.ts +9 -0
  372. package/src/docs-sections.ts +129 -0
  373. package/src/drone-lifecycle.ts +62 -0
  374. package/src/drone-management.ts +162 -0
  375. package/src/ensure-mcp-config.ts +54 -0
  376. package/src/evict-drone.ts +82 -0
  377. package/src/gc-orphan-inboxes.ts +229 -0
  378. package/src/inbox-monitor.ts +1005 -0
  379. package/src/index.ts +1201 -0
  380. package/src/launch-all-cmd.ts +450 -0
  381. package/src/launch-all-command.ts +30 -0
  382. package/src/launch-all-deps.ts +188 -0
  383. package/src/launch-all-discovery.ts +118 -0
  384. package/src/launch-all-locks.ts +74 -0
  385. package/src/launch-gate.ts +80 -0
  386. package/src/lifecycle-log-guard.ts +144 -0
  387. package/src/list-roles-render.ts +52 -0
  388. package/src/local-log-routing.ts +106 -0
  389. package/src/local-manage-tool-result.ts +10 -0
  390. package/src/local-server-cursor.ts +188 -0
  391. package/src/log-audit.ts +207 -0
  392. package/src/log-stream.ts +1505 -0
  393. package/src/model-presets.ts +22 -0
  394. package/src/name-validator.ts +23 -0
  395. package/src/opencode-drone.ts +528 -0
  396. package/src/opencode-plugin.ts +38 -0
  397. package/src/parse-assimilate-args.ts +125 -0
  398. package/src/parse-launch-all-args.ts +100 -0
  399. package/src/postinstall-banner.ts +37 -0
  400. package/src/postinstall.ts +36 -0
  401. package/src/readiness-probe.ts +12 -0
  402. package/src/regen-format.ts +651 -0
  403. package/src/regen.ts +150 -0
  404. package/src/remote-client.ts +1379 -0
  405. package/src/reset-local-seat-cmd.ts +227 -0
  406. package/src/role-match.ts +29 -0
  407. package/src/role-resolver.ts +93 -0
  408. package/src/roster-render.ts +196 -0
  409. package/src/seat-probe.ts +115 -0
  410. package/src/seat-store.ts +333 -0
  411. package/src/seats.ts +741 -0
  412. package/src/self-path.ts +51 -0
  413. package/src/server-endpoint.ts +38 -0
  414. package/src/server-errors.ts +93 -0
  415. package/src/server-handshake.ts +783 -0
  416. package/src/server-response.ts +76 -0
  417. package/src/server-trust.ts +245 -0
  418. package/src/setup-confirm.ts +171 -0
  419. package/src/setup.ts +186 -0
  420. package/src/shell-escape.ts +22 -0
  421. package/src/spawn.ts +31 -0
  422. package/src/startup-services.ts +36 -0
  423. package/src/stream-owner.ts +686 -0
  424. package/src/stream-status.ts +337 -0
  425. package/src/sync-roles-render.ts +163 -0
  426. package/src/sync.ts +363 -0
  427. package/src/terminal-title.ts +76 -0
  428. package/src/token-store.ts +102 -0
  429. package/src/tool-manifest.ts +610 -0
  430. package/src/tool-scope.ts +110 -0
  431. package/src/types.ts +5 -0
  432. package/src/unknown-subcommand.ts +35 -0
  433. package/src/version.ts +82 -0
  434. package/src/working-repo.ts +99 -0
  435. package/src/worktree-lifecycle.ts +254 -0
  436. package/dist/auth-recovery.d.ts +0 -33
  437. package/dist/auth-recovery.js +0 -1
  438. package/dist/auth.d.ts +0 -103
  439. package/dist/auth.js +0 -39
  440. package/dist/device-auth.d.ts +0 -75
  441. package/dist/device-auth.js +0 -1
  442. package/dist/drone-address.d.ts +0 -26
  443. package/dist/drone-address.js +0 -1
  444. package/dist/get-started.d.ts +0 -20
  445. package/dist/get-started.js +0 -2
  446. package/dist/health-beat.d.ts +0 -134
  447. package/dist/health-beat.js +0 -1
  448. package/dist/role-section.d.ts +0 -110
  449. package/dist/role-section.js +0 -8
  450. package/dist/setup-action.d.ts +0 -20
  451. package/dist/setup-action.js +0 -1
  452. package/dist/stale-version-check.d.ts +0 -40
  453. package/dist/stale-version-check.js +0 -1
  454. package/dist/subscription-retry.d.ts +0 -40
  455. package/dist/subscription-retry.js +0 -1
  456. package/dist/templates.d.ts +0 -107
  457. package/dist/templates.js +0 -359
  458. package/dist/token-crypto.d.ts +0 -50
  459. package/dist/token-crypto.js +0 -1
@@ -0,0 +1,783 @@
1
+ import {
2
+ ATTACH_PATH,
3
+ CUBES_PATH,
4
+ ENROLLMENT_EXCHANGE_PATH,
5
+ HEALTH_PATH,
6
+ PROTOCOL_INFO_PATH,
7
+ createAttachRequestEnvelope,
8
+ createProtocolEnvelope,
9
+ decodeAttachResponseEnvelope,
10
+ decodeCreateCubeRequest,
11
+ decodeCreateCubeResponseEnvelope,
12
+ decodeEnrollmentExchangeRequest,
13
+ decodeEnrollmentExchangeResponseEnvelope,
14
+ decodeProtocolErrorEnvelope,
15
+ decodeProtocolTagPreflight,
16
+ ErrorCode,
17
+ type CreateCubeResponse,
18
+ type ProtocolTagPreflight,
19
+ type ServerCapability,
20
+ } from 'borgmcp-shared/protocol';
21
+ import { createHash, randomUUID } from 'node:crypto';
22
+ import {
23
+ activatePendingServerEnrollment,
24
+ clearPendingServerCubeCreation,
25
+ clearPendingServerEnrollment,
26
+ getServerCredential,
27
+ getServerCredentialRecord,
28
+ getPendingServerEnrollment,
29
+ getOrCreatePendingServerCubeCreation,
30
+ getOrCreatePendingServerEnrollment,
31
+ type PendingServerCubeCreationRecord,
32
+ } from './config.js';
33
+ import {
34
+ activateAndBindSeat,
35
+ bindPendingSeatToWorktree,
36
+ scrubPendingSeat,
37
+ seatRef,
38
+ type ActivateSeatOutcome,
39
+ type BindPendingSeatOutcome,
40
+ type SeatBinding,
41
+ type SeatOperation as ServerSessionOperation,
42
+ } from './seats.js';
43
+ import { BorgServerError } from './server-errors.js';
44
+ import { readBoundedResponseBody } from './server-response.js';
45
+ import {
46
+ loadBorgServerTrust,
47
+ type BorgServerTrust,
48
+ } from './server-trust.js';
49
+
50
+ const HANDSHAKE_BODY_LIMIT = 64 * 1024;
51
+ const HANDSHAKE_TIMEOUT_MS = 5_000;
52
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
53
+ const CLIENT_ATTACH_PATH = '/api/client/attach';
54
+ export const DEFAULT_LOCAL_SERVER_ORIGIN = 'https://127.0.0.1:7091' as const;
55
+
56
+ type FetchLike = typeof fetch;
57
+
58
+ function handshakeUrl(origin: string, path: string): string {
59
+ return new URL(path, `${origin}/`).toString();
60
+ }
61
+
62
+ /** Bodyless, non-identifying liveness probe from the shared contract. */
63
+ export async function probeBorgServer(
64
+ origin: string,
65
+ fetchImpl: FetchLike = fetch,
66
+ timeoutMs = 750,
67
+ ): Promise<boolean> {
68
+ const controller = new AbortController();
69
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
70
+ try {
71
+ const response = await fetchImpl(handshakeUrl(origin, HEALTH_PATH), {
72
+ method: 'GET',
73
+ redirect: 'error',
74
+ signal: controller.signal,
75
+ });
76
+ return response.status === 204;
77
+ } catch {
78
+ return false;
79
+ } finally {
80
+ clearTimeout(timeout);
81
+ }
82
+ }
83
+
84
+ const readHandshakeBody = (response: Response, signal?: AbortSignal) =>
85
+ readBoundedResponseBody(
86
+ response,
87
+ HANDSHAKE_BODY_LIMIT,
88
+ 'Borg server protocol handshake exceeded the response limit',
89
+ signal,
90
+ );
91
+
92
+ async function readHandshakeBodyWithTimeout(response: Response): Promise<string> {
93
+ const controller = new AbortController();
94
+ const timeout = setTimeout(() => {
95
+ controller.abort(new Error('Borg server protocol handshake timed out'));
96
+ }, HANDSHAKE_TIMEOUT_MS);
97
+ try {
98
+ return await readHandshakeBody(response, controller.signal);
99
+ } finally {
100
+ clearTimeout(timeout);
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Credential-free protocol-tag preflight. After the caller has verified pinned
106
+ * TLS, confirm the server speaks the exact protocol tag BEFORE any bearer is
107
+ * created, sent, or a seat attached. Sends NO Authorization header, cookie,
108
+ * query, or body; rejects redirects; and bounds the response. A tag mismatch,
109
+ * an extra field, or any transport anomaly fails closed here — no keychain
110
+ * write and no attach. The bearer is proven only at attach.
111
+ */
112
+ export async function preflightBorgServerTag(
113
+ origin: string,
114
+ fetchImpl: FetchLike = fetch,
115
+ ): Promise<ProtocolTagPreflight> {
116
+ const controller = new AbortController();
117
+ const timeout = setTimeout(() => controller.abort(), HANDSHAKE_TIMEOUT_MS);
118
+ try {
119
+ const response = await fetchImpl(handshakeUrl(origin, PROTOCOL_INFO_PATH), {
120
+ method: 'GET',
121
+ redirect: 'error',
122
+ signal: controller.signal,
123
+ headers: {
124
+ Accept: 'application/json',
125
+ },
126
+ });
127
+ if (!response.ok) {
128
+ throw new Error(`Borg server protocol preflight failed (HTTP ${response.status})`);
129
+ }
130
+
131
+ let decoded: unknown;
132
+ try {
133
+ decoded = JSON.parse(await readHandshakeBody(response, controller.signal));
134
+ } catch (error) {
135
+ if (error instanceof Error && error.message.includes('response limit')) throw error;
136
+ throw new Error('Borg server returned an invalid protocol preflight');
137
+ }
138
+ return decodeProtocolTagPreflight(decoded);
139
+ } finally {
140
+ clearTimeout(timeout);
141
+ }
142
+ }
143
+
144
+ export interface EnrolledServerConnection {
145
+ token: string;
146
+ trustIdentity: string;
147
+ protocol: ProtocolTagPreflight;
148
+ clientId?: string | null;
149
+ serverCapabilities?: ServerCapability[];
150
+ }
151
+
152
+ export interface ResolvedServerAuthority extends BorgServerTrust {
153
+ token: string;
154
+ }
155
+
156
+ export interface NewServerEnrollment extends EnrolledServerConnection {
157
+ clientId: string;
158
+ serverCapabilities: ServerCapability[];
159
+ }
160
+
161
+ export interface ServerAttachResult {
162
+ cube: { id: string; name: string };
163
+ role: {
164
+ id: string;
165
+ name: string;
166
+ role_class?: 'queen' | 'worker';
167
+ is_human_seat?: boolean;
168
+ };
169
+ drone: { id: string; label: string };
170
+ session: {
171
+ credentialRef: string;
172
+ sessionId: string;
173
+ expiresAt: string;
174
+ };
175
+ result: 'created' | 'reused';
176
+ }
177
+
178
+ /**
179
+ * Attach an enrolled client principal to one granted cube/role over protocol v2.
180
+ * The client CSPRNG-generates the session bearer and persists it PENDING in the
181
+ * OS keychain (keyed by the stable per-seat identity) BEFORE this request, so an
182
+ * interrupted/lost response is recovered by re-sending the exact same bearer —
183
+ * the server binds only its digest. A verified `created`/`reused` response
184
+ * activates that pending record in place; the server never returns a bearer.
185
+ */
186
+ /**
187
+ * The PREPARE + network half of an attach, WITHOUT the keychain pending→ACTIVE
188
+ * transition. The deferred `activate` / `scrubPending` thunks let the cube-lock-
189
+ * owning orchestration (assimilate) FINALIZE binding-FIRST: write the cubes
190
+ * binding referencing this exact pending record under the cube lock, THEN call
191
+ * `activate()` as the single last step. `credentialRef` is the deterministic
192
+ * per-seat account, known here (before activation) so the binding can reference
193
+ * it. `scrubPending` compare-and-scrubs ONLY this own pending record on a
194
+ * FINALIZE abort.
195
+ */
196
+ export interface PreparedServerAttach {
197
+ cube: ServerAttachResult['cube'];
198
+ role: ServerAttachResult['role'];
199
+ drone: ServerAttachResult['drone'];
200
+ session: { sessionId: string; expiresAt: string };
201
+ result: 'created' | 'reused';
202
+ credentialRef: string;
203
+ pendingBearerDigest: string;
204
+ /** The single-store ATOMIC activate+bind (CR#2 collapse): given the worktree
205
+ * binding + display (known only at FINALIZE), stamp the exact digest-matched
206
+ * PENDING record ACTIVE and bind the worktree in ONE commit. Returns the typed
207
+ * outcome (`activated`/`missing`/`replaced`) — never throws for a race. */
208
+ activate: (binding: SeatBinding) => Promise<ActivateSeatOutcome>;
209
+ scrubPending: () => Promise<boolean>;
210
+ /** CR#2: bind the EXACT digest-matched PENDING record to the preserved worktree
211
+ * WITHOUT activating (it stays pending). Invoked by the activation-failure path so
212
+ * the preserved sibling worktree owns a discoverable, resumable pending record —
213
+ * the rerun FROM there re-derives the exact ref and re-sends the identical bearer
214
+ * (ghost-free convergence). Fail-closed typed outcome; never throws for a race. */
215
+ bindPending: (binding: SeatBinding) => Promise<BindPendingSeatOutcome>;
216
+ }
217
+
218
+ /**
219
+ * The NETWORK-ONLY half of an attach: POST the ALREADY-MINTED pending bearer and
220
+ * decode, WITHOUT minting (the mint is owned by the single-store prepareSeat, CR#1).
221
+ * Returns the deferred activate/scrubPending handles: FINALIZE calls `activate`
222
+ * with the decided worktree binding, and activateAndBindSeat stamps ACTIVE + binds
223
+ * the worktree in ONE atomic commit (activate+bind merged — no cross-store gap).
224
+ */
225
+ export async function sendBorgServerAttach(
226
+ origin: string,
227
+ trustIdentity: string,
228
+ parentCredential: string,
229
+ request: {
230
+ cubeId: string;
231
+ roleId: string;
232
+ operation: ServerSessionOperation;
233
+ priorDroneId?: string;
234
+ },
235
+ pendingBearer: string,
236
+ deps: {
237
+ fetchImpl?: FetchLike;
238
+ activateAndBind?: typeof activateAndBindSeat;
239
+ bindPending?: typeof bindPendingSeatToWorktree;
240
+ scrubPending?: typeof scrubPendingSeat;
241
+ sessionCredentialRef?: typeof seatRef;
242
+ } = {},
243
+ ): Promise<PreparedServerAttach> {
244
+ if (!UUID_RE.test(request.cubeId) || !UUID_RE.test(request.roleId)) {
245
+ throw new Error('Borg server attach requires valid cube and role identities');
246
+ }
247
+ if (request.priorDroneId !== undefined && !UUID_RE.test(request.priorDroneId)) {
248
+ throw new Error('Borg server attach prior drone identity is invalid');
249
+ }
250
+ if (!/^[A-Za-z0-9_-]{43,1024}$/.test(parentCredential)) {
251
+ throw new Error('stored Borg server enrollment credential is invalid');
252
+ }
253
+ const pending = { credential: pendingBearer };
254
+
255
+ const controller = new AbortController();
256
+ const timeout = setTimeout(() => controller.abort(), HANDSHAKE_TIMEOUT_MS);
257
+ try {
258
+ const response = await (deps.fetchImpl ?? fetch)(handshakeUrl(origin, ATTACH_PATH), {
259
+ method: 'POST',
260
+ redirect: 'error',
261
+ signal: controller.signal,
262
+ headers: {
263
+ Accept: 'application/json',
264
+ 'Content-Type': 'application/json',
265
+ Authorization: `Bearer ${parentCredential}`,
266
+ },
267
+ body: JSON.stringify(createAttachRequestEnvelope(randomUUID(), {
268
+ cube_id: request.cubeId,
269
+ role_id: request.roleId,
270
+ session_credential: pending.credential,
271
+ ...(request.priorDroneId === undefined
272
+ ? {}
273
+ : { prior_drone_id: request.priorDroneId }),
274
+ })),
275
+ });
276
+ if (response.status === 401 || response.status === 403) {
277
+ // A typed SESSION_REJECTED body means the presented bearer targets a seat
278
+ // already bound to a different session (takeover), distinct from a rejected
279
+ // parent enrollment credential. Decode defensively; any anomaly falls back
280
+ // to the generic credential rejection below. Never echo the response body.
281
+ if (response.status === 401) {
282
+ let rejectedCode: ErrorCode | undefined;
283
+ try {
284
+ rejectedCode = decodeProtocolErrorEnvelope(
285
+ JSON.parse(await readHandshakeBody(response, controller.signal)),
286
+ ).error.code;
287
+ } catch {
288
+ rejectedCode = undefined;
289
+ }
290
+ if (rejectedCode === ErrorCode.SESSION_REJECTED) {
291
+ throw new BorgServerError(
292
+ 'SESSION_REJECTED',
293
+ 'Borg server rejected the session: the seat is already bound to another session',
294
+ );
295
+ }
296
+ }
297
+ throw new BorgServerError('CREDENTIAL_REJECTED', 'Borg server enrollment was rejected');
298
+ }
299
+ if (response.status === 409) {
300
+ throw new BorgServerError('ATTACH_CONFLICT', 'Borg server attach request conflicted');
301
+ }
302
+ if (!response.ok) {
303
+ throw new Error(`Borg server attach failed (HTTP ${response.status})`);
304
+ }
305
+
306
+ let decoded: ReturnType<typeof decodeAttachResponseEnvelope>['payload'];
307
+ try {
308
+ decoded = decodeAttachResponseEnvelope(
309
+ JSON.parse(await readHandshakeBody(response, controller.signal)),
310
+ ).payload;
311
+ } catch (error) {
312
+ if (error instanceof Error && error.message.includes('response limit')) throw error;
313
+ throw new Error('Borg server returned an invalid attach response');
314
+ }
315
+ if (decoded.cube.id !== request.cubeId || decoded.role.id !== request.roleId) {
316
+ throw new Error('Borg server returned an attach identity outside the request');
317
+ }
318
+
319
+ const seatInput = {
320
+ origin,
321
+ trustIdentity,
322
+ cubeId: request.cubeId,
323
+ roleId: request.roleId,
324
+ operation: request.operation,
325
+ };
326
+ const credentialRef = (deps.sessionCredentialRef ?? seatRef)(seatInput);
327
+ const pendingBearerDigest = createHash('sha256').update(pending.credential).digest('hex');
328
+ return {
329
+ cube: decoded.cube,
330
+ role: decoded.role,
331
+ drone: decoded.drone,
332
+ session: {
333
+ sessionId: decoded.session.id,
334
+ expiresAt: decoded.session.expires_at,
335
+ },
336
+ result: decoded.result,
337
+ credentialRef,
338
+ pendingBearerDigest,
339
+ // The single-store ATOMIC activate+bind — invoked by FINALIZE with the decided
340
+ // worktree binding. Stamps server metadata + the worktree binding ONLY onto the
341
+ // EXACT pending record whose bearer we sent (digest-matched), in ONE commit. A
342
+ // same-ref replacement or a concurrent delete aborts (`replaced`/`missing`) —
343
+ // never binds bearer A's server session onto bearer B, and never leaves an
344
+ // ACTIVE credential without a binding (they land together).
345
+ activate: (binding: SeatBinding) =>
346
+ (deps.activateAndBind ?? activateAndBindSeat)({
347
+ ...seatInput,
348
+ droneId: decoded.drone.id,
349
+ sessionId: decoded.session.id,
350
+ expiresAt: decoded.session.expires_at,
351
+ expectedPendingDigest: pendingBearerDigest,
352
+ worktree: binding.worktree,
353
+ name: binding.name,
354
+ droneLabel: binding.droneLabel,
355
+ ...(binding.roleName !== undefined ? { roleName: binding.roleName } : {}),
356
+ ...(binding.roleClass !== undefined ? { roleClass: binding.roleClass } : {}),
357
+ ...(binding.isHumanSeat !== undefined ? { isHumanSeat: binding.isHumanSeat } : {}),
358
+ }),
359
+ // Abort-scrub of ONLY this own pending record (never an ACTIVE record, never
360
+ // a same-ref replacement) — invoked when the server did not honor the
361
+ // reattach/remint intent.
362
+ scrubPending: () => (deps.scrubPending ?? scrubPendingSeat)(
363
+ credentialRef,
364
+ { origin, trustIdentity, cubeId: request.cubeId },
365
+ pendingBearerDigest,
366
+ ),
367
+ // CR#2: on activation failure, bind the EXACT digest-matched PENDING record to
368
+ // the preserved (spawned) worktree WITHOUT activating it — it stays pending, so
369
+ // it is non-hydratable as a live seat but IS discoverable/resumable from that
370
+ // worktree. The rerun re-sends the identical bearer and converges (no ghost).
371
+ bindPending: (binding: SeatBinding) =>
372
+ (deps.bindPending ?? bindPendingSeatToWorktree)({
373
+ ...seatInput,
374
+ expectedPendingDigest: pendingBearerDigest,
375
+ droneId: decoded.drone.id,
376
+ worktree: binding.worktree,
377
+ name: binding.name,
378
+ droneLabel: binding.droneLabel,
379
+ ...(binding.roleName !== undefined ? { roleName: binding.roleName } : {}),
380
+ ...(binding.roleClass !== undefined ? { roleClass: binding.roleClass } : {}),
381
+ ...(binding.isHumanSeat !== undefined ? { isHumanSeat: binding.isHumanSeat } : {}),
382
+ }),
383
+ };
384
+ } finally {
385
+ clearTimeout(timeout);
386
+ }
387
+ }
388
+
389
+ // SR-seven (c): the pre-composite mint-without-cube-lock seams (prepareBorgServerAttach)
390
+ // and the activate-first no-binding wrapper (attachBorgServer) are DELETED — there is
391
+ // no code path, not even test-only, that mints/sends a session_credential outside the
392
+ // cube-owned composite. The ONLY session-credential send is sendBorgServerAttach, driven
393
+ // by assimilate-deps AFTER prepareSeat has minted under the single store flock.
394
+
395
+ /**
396
+ * Redeem one invitation after the caller has verified TLS and derived the
397
+ * stable server/CA identity. The client-generated bearer + retry key are
398
+ * persisted PENDING in the local 0600 file store before the first request. A
399
+ * transport-ambiguous exchange is retried with that exact tuple; only a decoded
400
+ * response followed by an authenticated protocol proof activates the bearer.
401
+ */
402
+ export async function enrollBorgServer(
403
+ origin: string,
404
+ trustIdentity: string,
405
+ invitation: string,
406
+ deps: {
407
+ fetchImpl?: FetchLike;
408
+ prepareEnrollment?: typeof getOrCreatePendingServerEnrollment;
409
+ activateEnrollment?: typeof activatePendingServerEnrollment;
410
+ clearPendingEnrollment?: typeof clearPendingServerEnrollment;
411
+ clientName?: string;
412
+ } = {},
413
+ ): Promise<NewServerEnrollment> {
414
+ const fetchImpl = deps.fetchImpl ?? fetch;
415
+ // Credential-free tag preflight FIRST (CR fb4d6eba): after pinned TLS, an
416
+ // incompatible server must be rejected before any credential is created or
417
+ // persisted and before any invitation/secret-bearing request is sent.
418
+ const protocol = await preflightBorgServerTag(origin, fetchImpl);
419
+
420
+ const pending = await (deps.prepareEnrollment ?? getOrCreatePendingServerEnrollment)({
421
+ origin,
422
+ trustIdentity,
423
+ invitation,
424
+ ...(deps.clientName ? { clientName: deps.clientName } : {}),
425
+ });
426
+ const request = decodeEnrollmentExchangeRequest({
427
+ invitation: pending.invitation,
428
+ retry_key: pending.retryKey,
429
+ client_credential: pending.credential,
430
+ ...(pending.clientName ? { client_name: pending.clientName } : {}),
431
+ });
432
+ let response: Response | null = null;
433
+ let lastTransportError: unknown;
434
+ for (let attempt = 0; attempt < 2 && response === null; attempt += 1) {
435
+ const controller = new AbortController();
436
+ const timeout = setTimeout(() => controller.abort(), HANDSHAKE_TIMEOUT_MS);
437
+ try {
438
+ response = await fetchImpl(handshakeUrl(origin, ENROLLMENT_EXCHANGE_PATH), {
439
+ method: 'POST',
440
+ redirect: 'error',
441
+ signal: controller.signal,
442
+ headers: {
443
+ Accept: 'application/json',
444
+ 'Content-Type': 'application/json',
445
+ },
446
+ body: JSON.stringify(createProtocolEnvelope(randomUUID(), request)),
447
+ });
448
+ } catch (error) {
449
+ lastTransportError = error;
450
+ } finally {
451
+ clearTimeout(timeout);
452
+ }
453
+ }
454
+ if (!response) throw lastTransportError;
455
+
456
+ if (response.status === 401 || response.status === 403) {
457
+ await (deps.clearPendingEnrollment ?? clearPendingServerEnrollment)(
458
+ origin,
459
+ trustIdentity,
460
+ pending.retryKey,
461
+ );
462
+ throw new BorgServerError(
463
+ 'INVITATION_REJECTED',
464
+ 'the invitation was rejected or expired',
465
+ );
466
+ }
467
+ if (response.status !== 201) {
468
+ throw new Error(`Borg server enrollment failed (HTTP ${response.status})`);
469
+ }
470
+ let decoded: ReturnType<typeof decodeEnrollmentExchangeResponseEnvelope>;
471
+ try {
472
+ decoded = decodeEnrollmentExchangeResponseEnvelope(
473
+ JSON.parse(await readHandshakeBodyWithTimeout(response)),
474
+ );
475
+ } catch (error) {
476
+ if (error instanceof Error && error.message.includes('response limit')) throw error;
477
+ throw new Error('Borg server returned an invalid enrollment envelope');
478
+ }
479
+
480
+ await (deps.activateEnrollment ?? activatePendingServerEnrollment)({
481
+ origin,
482
+ trustIdentity,
483
+ retryKey: pending.retryKey,
484
+ credential: pending.credential,
485
+ clientId: decoded.payload.client_id,
486
+ serverCapabilities: decoded.payload.server_capabilities,
487
+ });
488
+ return {
489
+ token: pending.credential,
490
+ trustIdentity,
491
+ protocol,
492
+ clientId: decoded.payload.client_id,
493
+ serverCapabilities: decoded.payload.server_capabilities,
494
+ };
495
+ }
496
+
497
+ /** Resume an exact durable enrollment tuple without asking for the invitation again. */
498
+ export async function resumeBorgServerEnrollment(
499
+ origin: string,
500
+ trustIdentity: string,
501
+ deps: {
502
+ fetchImpl?: FetchLike;
503
+ loadPendingEnrollment?: typeof getPendingServerEnrollment;
504
+ activateEnrollment?: typeof activatePendingServerEnrollment;
505
+ clearPendingEnrollment?: typeof clearPendingServerEnrollment;
506
+ onPending?: () => void;
507
+ } = {},
508
+ ): Promise<NewServerEnrollment | null> {
509
+ const pending = await (deps.loadPendingEnrollment ?? getPendingServerEnrollment)(
510
+ origin,
511
+ trustIdentity,
512
+ );
513
+ if (!pending) return null;
514
+ deps.onPending?.();
515
+ return enrollBorgServer(origin, trustIdentity, pending.invitation, {
516
+ ...(deps.fetchImpl === undefined ? {} : { fetchImpl: deps.fetchImpl }),
517
+ prepareEnrollment: async () => pending,
518
+ ...(deps.activateEnrollment === undefined
519
+ ? {}
520
+ : { activateEnrollment: deps.activateEnrollment }),
521
+ ...(deps.clearPendingEnrollment === undefined
522
+ ? {}
523
+ : { clearPendingEnrollment: deps.clearPendingEnrollment }),
524
+ ...(pending.clientName === undefined ? {} : { clientName: pending.clientName }),
525
+ });
526
+ }
527
+
528
+ /**
529
+ * Create one repository cube through the narrow owner capability. The retry
530
+ * key is persisted in the OS keychain before network I/O and reused exactly
531
+ * after an ambiguous transport result. Ordinary clients are denied locally
532
+ * before any create request is sent.
533
+ */
534
+ export async function createBorgServerCube(
535
+ origin: string,
536
+ trustIdentity: string,
537
+ parentCredential: string,
538
+ input: { projectRoot: string; name: string },
539
+ deps: {
540
+ fetchImpl?: FetchLike;
541
+ loadCredentialRecord?: typeof getServerCredentialRecord;
542
+ prepareCubeCreation?: typeof getOrCreatePendingServerCubeCreation;
543
+ clearCubeCreation?: typeof clearPendingServerCubeCreation;
544
+ } = {},
545
+ ): Promise<CreateCubeResponse> {
546
+ const active = await (deps.loadCredentialRecord ?? getServerCredentialRecord)(
547
+ origin,
548
+ trustIdentity,
549
+ );
550
+ if (!active || active.credential !== parentCredential) {
551
+ throw new BorgServerError('CREDENTIAL_REJECTED', 'stored Borg server credential was rejected');
552
+ }
553
+ if (!active.clientId || !active.serverCapabilities.includes('create_cube')) {
554
+ throw new BorgServerError(
555
+ 'CREATE_CUBE_DENIED',
556
+ 'This Borg server client is not authorized to create cubes',
557
+ );
558
+ }
559
+ const pending = await (deps.prepareCubeCreation ?? getOrCreatePendingServerCubeCreation)({
560
+ origin,
561
+ trustIdentity,
562
+ clientId: active.clientId,
563
+ projectRoot: input.projectRoot,
564
+ name: input.name,
565
+ template: 'default',
566
+ });
567
+ const request = decodeCreateCubeRequest({
568
+ retry_key: pending.retryKey,
569
+ name: pending.name,
570
+ template: pending.template,
571
+ });
572
+
573
+ const fetchImpl = deps.fetchImpl ?? fetch;
574
+ let response: Response | null = null;
575
+ let lastTransportError: unknown;
576
+ for (let attempt = 0; attempt < 2 && response === null; attempt += 1) {
577
+ const controller = new AbortController();
578
+ const timeout = setTimeout(() => controller.abort(), HANDSHAKE_TIMEOUT_MS);
579
+ try {
580
+ response = await fetchImpl(handshakeUrl(origin, CUBES_PATH), {
581
+ method: 'POST',
582
+ redirect: 'error',
583
+ signal: controller.signal,
584
+ headers: {
585
+ Accept: 'application/json',
586
+ 'Content-Type': 'application/json',
587
+ Authorization: `Bearer ${parentCredential}`,
588
+ },
589
+ body: JSON.stringify(createProtocolEnvelope(randomUUID(), request)),
590
+ });
591
+ } catch (error) {
592
+ lastTransportError = error;
593
+ } finally {
594
+ clearTimeout(timeout);
595
+ }
596
+ }
597
+ if (!response) throw lastTransportError;
598
+ if (response.status === 401 || response.status === 403) {
599
+ throw new BorgServerError('CREDENTIAL_REJECTED', 'Borg server enrollment was rejected');
600
+ }
601
+ if (response.status === 404) {
602
+ throw new BorgServerError(
603
+ 'CREATE_CUBE_DENIED',
604
+ 'This Borg server client is not authorized to create cubes',
605
+ );
606
+ }
607
+ if (response.status === 409) {
608
+ throw new Error('Borg server cube creation retry state conflicted');
609
+ }
610
+ if (response.status !== 201) {
611
+ throw new Error(`Borg server cube creation failed (HTTP ${response.status})`);
612
+ }
613
+ let decoded: ReturnType<typeof decodeCreateCubeResponseEnvelope>;
614
+ try {
615
+ decoded = decodeCreateCubeResponseEnvelope(
616
+ JSON.parse(await readHandshakeBodyWithTimeout(response)),
617
+ );
618
+ } catch (error) {
619
+ if (error instanceof Error && error.message.includes('response limit')) throw error;
620
+ throw new Error('Borg server returned an invalid cube creation envelope');
621
+ }
622
+ await (deps.clearCubeCreation ?? clearPendingServerCubeCreation)(
623
+ pending as PendingServerCubeCreationRecord,
624
+ );
625
+ return decoded.payload;
626
+ }
627
+
628
+ export async function createLocalBorgServerCube(
629
+ origin: string,
630
+ trustIdentity: string,
631
+ parentCredential: string,
632
+ input: { projectRoot: string; name: string },
633
+ deps: { loadTrust?: typeof loadBorgServerTrust } = {},
634
+ ): Promise<CreateCubeResponse> {
635
+ const trust = await (deps.loadTrust ?? loadBorgServerTrust)(origin);
636
+ if (trust.identity !== trustIdentity) {
637
+ throw new Error('Borg server trust identity changed; refusing cube creation');
638
+ }
639
+ return createBorgServerCube(origin, trustIdentity, parentCredential, input, {
640
+ fetchImpl: trust.fetchImpl,
641
+ });
642
+ }
643
+
644
+ /**
645
+ * Swappable Part-4 integration seam. Trust verification supplies the server/CA
646
+ * identity; this function then reads only the credential bound to that exact
647
+ * origin+identity pair and negotiates the authenticated shared contract.
648
+ */
649
+ export async function connectEnrolledBorgServer(
650
+ origin: string,
651
+ trustIdentity: string,
652
+ deps: {
653
+ loadCredential?: typeof getServerCredential;
654
+ loadCredentialRecord?: typeof getServerCredentialRecord;
655
+ fetchImpl?: FetchLike;
656
+ } = {},
657
+ ): Promise<EnrolledServerConnection> {
658
+ const active = deps.loadCredentialRecord
659
+ ? await deps.loadCredentialRecord(origin, trustIdentity)
660
+ : deps.loadCredential
661
+ ? null
662
+ : await getServerCredentialRecord(origin, trustIdentity);
663
+ const token = active?.credential ?? await (deps.loadCredential ?? getServerCredential)(
664
+ origin,
665
+ trustIdentity,
666
+ );
667
+ if (!token) {
668
+ throw new BorgServerError(
669
+ 'NOT_ENROLLED',
670
+ 'no enrolled credential is stored for this Borg server identity',
671
+ );
672
+ }
673
+ const protocol = await preflightBorgServerTag(origin, deps.fetchImpl ?? fetch);
674
+ return {
675
+ token,
676
+ trustIdentity,
677
+ protocol,
678
+ ...(active === null ? {} : {
679
+ clientId: active.clientId,
680
+ serverCapabilities: active.serverCapabilities,
681
+ }),
682
+ };
683
+ }
684
+
685
+ /** Resolve the same-user server CA and its authority-bound keychain credential. */
686
+ export async function resolveBorgServerAuthority(
687
+ origin: string,
688
+ deps: {
689
+ loadTrust?: typeof loadBorgServerTrust;
690
+ loadCredential?: typeof getServerCredential;
691
+ loadCredentialRecord?: typeof getServerCredentialRecord;
692
+ } = {},
693
+ ): Promise<ResolvedServerAuthority> {
694
+ const trust = await (deps.loadTrust ?? loadBorgServerTrust)(origin);
695
+ const active = deps.loadCredentialRecord
696
+ ? await deps.loadCredentialRecord(origin, trust.identity)
697
+ : deps.loadCredential
698
+ ? null
699
+ : await getServerCredentialRecord(origin, trust.identity);
700
+ const token = active?.credential ?? await (deps.loadCredential ?? getServerCredential)(
701
+ origin,
702
+ trust.identity,
703
+ );
704
+ if (!token) {
705
+ throw new BorgServerError(
706
+ 'NOT_ENROLLED',
707
+ 'no enrolled credential is stored for this Borg server identity',
708
+ );
709
+ }
710
+ return { ...trust, token };
711
+ }
712
+
713
+ /** Load pinned trust, then prove the stored credential against /api/protocol. */
714
+ export async function connectLocalBorgServer(
715
+ origin: string,
716
+ deps: {
717
+ loadTrust?: typeof loadBorgServerTrust;
718
+ loadCredential?: typeof getServerCredential;
719
+ loadCredentialRecord?: typeof getServerCredentialRecord;
720
+ } = {},
721
+ ): Promise<EnrolledServerConnection> {
722
+ const trust = await (deps.loadTrust ?? loadBorgServerTrust)(origin);
723
+ return connectEnrolledBorgServer(origin, trust.identity, {
724
+ fetchImpl: trust.fetchImpl,
725
+ ...(deps.loadCredential === undefined ? {} : { loadCredential: deps.loadCredential }),
726
+ ...(deps.loadCredentialRecord === undefined
727
+ ? {}
728
+ : { loadCredentialRecord: deps.loadCredentialRecord }),
729
+ });
730
+ }
731
+
732
+ /** Load and verify the local CA before sending an enrollment invitation. */
733
+ export async function enrollLocalBorgServer(
734
+ origin: string,
735
+ invitation: string,
736
+ deps: {
737
+ loadTrust?: typeof loadBorgServerTrust;
738
+ prepareEnrollment?: typeof getOrCreatePendingServerEnrollment;
739
+ activateEnrollment?: typeof activatePendingServerEnrollment;
740
+ clearPendingEnrollment?: typeof clearPendingServerEnrollment;
741
+ clientName?: string;
742
+ } = {},
743
+ ): Promise<NewServerEnrollment> {
744
+ const trust = await (deps.loadTrust ?? loadBorgServerTrust)(origin);
745
+ return enrollBorgServer(origin, trust.identity, invitation, {
746
+ fetchImpl: trust.fetchImpl,
747
+ ...(deps.prepareEnrollment === undefined ? {} : { prepareEnrollment: deps.prepareEnrollment }),
748
+ ...(deps.activateEnrollment === undefined ? {} : { activateEnrollment: deps.activateEnrollment }),
749
+ ...(deps.clearPendingEnrollment === undefined
750
+ ? {}
751
+ : { clearPendingEnrollment: deps.clearPendingEnrollment }),
752
+ ...(deps.clientName === undefined ? {} : { clientName: deps.clientName }),
753
+ });
754
+ }
755
+
756
+ /** Load verified trust and resume a prior ambiguous enrollment before prompting. */
757
+ export async function resumeLocalBorgServerEnrollment(
758
+ origin: string,
759
+ deps: {
760
+ loadTrust?: typeof loadBorgServerTrust;
761
+ loadPendingEnrollment?: typeof getPendingServerEnrollment;
762
+ onPending?: () => void;
763
+ } = {},
764
+ ): Promise<NewServerEnrollment | null> {
765
+ const trust = await (deps.loadTrust ?? loadBorgServerTrust)(origin);
766
+ return resumeBorgServerEnrollment(origin, trust.identity, {
767
+ fetchImpl: trust.fetchImpl,
768
+ ...(deps.loadPendingEnrollment === undefined
769
+ ? {}
770
+ : { loadPendingEnrollment: deps.loadPendingEnrollment }),
771
+ ...(deps.onPending === undefined ? {} : { onPending: deps.onPending }),
772
+ });
773
+ }
774
+
775
+ /** Advisory discovery that still verifies the server-owned CA. */
776
+ export async function probeLocalBorgServer(origin: string): Promise<boolean> {
777
+ try {
778
+ const trust = await loadBorgServerTrust(origin);
779
+ return await probeBorgServer(origin, trust.fetchImpl);
780
+ } catch {
781
+ return false;
782
+ }
783
+ }