@blackbelt-technology/pi-agent-dashboard 0.10.0 → 0.12.0

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 (474) hide show
  1. package/AGENTS.md +4 -2
  2. package/README.md +64 -18
  3. package/docs/architecture.md +2325 -270
  4. package/package.json +36 -20
  5. package/packages/extension/package.json +18 -9
  6. package/packages/extension/src/bridge-context.ts +6 -0
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +109 -70
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
  9. package/packages/extension/src/bridge-handlers/instance.ts +31 -13
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +149 -66
  11. package/packages/extension/src/bridge-shutdown.ts +44 -0
  12. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  13. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  14. package/packages/extension/src/bridge.ts +309 -284
  15. package/packages/extension/src/canvas-tool.ts +2 -0
  16. package/packages/extension/src/command-handler.ts +106 -37
  17. package/packages/extension/src/connect-target.ts +23 -0
  18. package/packages/extension/src/connection.ts +153 -38
  19. package/packages/extension/src/credential-guard.ts +300 -0
  20. package/packages/extension/src/custom-entry-forward.ts +27 -18
  21. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  22. package/packages/extension/src/default-model-apply.ts +83 -0
  23. package/packages/extension/src/dev-build.ts +11 -1
  24. package/packages/extension/src/flow-event-wiring.ts +19 -95
  25. package/packages/extension/src/followup-drain.ts +19 -5
  26. package/packages/extension/src/git-link-builder.ts +11 -2
  27. package/packages/extension/src/inbound-limits.ts +138 -0
  28. package/packages/extension/src/local-token-header.ts +77 -6
  29. package/packages/extension/src/model-refresh.ts +69 -0
  30. package/packages/extension/src/path-gate/decide.ts +68 -5
  31. package/packages/extension/src/path-gate/handler.ts +16 -8
  32. package/packages/extension/src/path-gate/index.ts +2 -2
  33. package/packages/extension/src/path-gate/roots.ts +15 -3
  34. package/packages/extension/src/path-gate/suppression.ts +3 -0
  35. package/packages/extension/src/pi-env.d.ts +8 -1
  36. package/packages/extension/src/pi-retry-settings.ts +11 -2
  37. package/packages/extension/src/pinned-endpoint.ts +44 -0
  38. package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
  39. package/packages/extension/src/preview-path-link.ts +151 -0
  40. package/packages/extension/src/project-init/scaffold.ts +98 -35
  41. package/packages/extension/src/project-trust-live.ts +143 -0
  42. package/packages/extension/src/project-trust.ts +178 -30
  43. package/packages/extension/src/provider-model-cache.ts +118 -0
  44. package/packages/extension/src/provider-register.ts +487 -46
  45. package/packages/extension/src/remote-registration-gate.ts +21 -21
  46. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  47. package/packages/extension/src/retry-tracker.ts +90 -7
  48. package/packages/extension/src/role-manager.ts +4 -2
  49. package/packages/extension/src/role-model-tools.ts +68 -10
  50. package/packages/extension/src/server-auto-start.ts +69 -3
  51. package/packages/extension/src/server-launcher.ts +26 -8
  52. package/packages/extension/src/server-proof-probe.ts +117 -0
  53. package/packages/extension/src/session-sync.ts +53 -24
  54. package/packages/extension/src/spawn-new-session.ts +22 -0
  55. package/packages/extension/src/steer-buffer.ts +164 -0
  56. package/packages/extension/src/stream-forward-buffer.ts +64 -15
  57. package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
  58. package/packages/extension/src/sudo-askpass/controller.ts +405 -0
  59. package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
  60. package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
  61. package/packages/extension/src/sudo-askpass/index.ts +11 -0
  62. package/packages/extension/src/sudo-askpass/install.ts +143 -0
  63. package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
  64. package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
  65. package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
  66. package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
  67. package/packages/extension/src/terminal-reload.ts +19 -5
  68. package/packages/extension/src/tool-update-filter-registry.ts +210 -0
  69. package/packages/extension/src/vault-delivery.ts +11 -1
  70. package/packages/extension/src/vault-redaction.ts +4 -3
  71. package/packages/server/package.json +17 -14
  72. package/packages/server/src/access/access-denials.ts +8 -0
  73. package/packages/server/src/access/access-grants.ts +303 -64
  74. package/packages/server/src/access/access-health.ts +10 -0
  75. package/packages/server/src/access/access-plane.ts +12 -1
  76. package/packages/server/src/access/containment-gate.ts +113 -30
  77. package/packages/server/src/access/cwd-verdict.ts +3 -3
  78. package/packages/server/src/access/denial-hold.ts +3 -0
  79. package/packages/server/src/access/grant-coordinator.ts +17 -1
  80. package/packages/server/src/access/named-grant.ts +3 -0
  81. package/packages/server/src/access/pending-grant-registry.ts +32 -5
  82. package/packages/server/src/access/pi-trust-live.ts +244 -0
  83. package/packages/server/src/access/pi-trust-mirror-service.ts +50 -11
  84. package/packages/server/src/access/planes.ts +107 -1
  85. package/packages/server/src/access/preview-egress-store.ts +153 -0
  86. package/packages/server/src/access/prompt-channel.ts +5 -0
  87. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  88. package/packages/server/src/access/provisioning.ts +763 -0
  89. package/packages/server/src/access/verified-read.ts +24 -7
  90. package/packages/server/src/access/yolo-session.ts +54 -2
  91. package/packages/server/src/acp-bridge/acp-session-adapter.ts +18 -5
  92. package/packages/server/src/acp-bridge/server-requests.ts +10 -4
  93. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  94. package/packages/server/src/auth/audit-log.ts +108 -0
  95. package/packages/server/src/auth/auth-plugin.ts +230 -38
  96. package/packages/server/src/auth/auth.ts +104 -4
  97. package/packages/server/src/auth/bearer-auth.ts +52 -12
  98. package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
  99. package/packages/server/src/auth/cors-origin.ts +90 -30
  100. package/packages/server/src/auth/credential-envelope.ts +233 -0
  101. package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
  102. package/packages/server/src/auth/credential-key-worker.mjs +108 -0
  103. package/packages/server/src/auth/credential-key.ts +479 -0
  104. package/packages/server/src/auth/credential-migration.ts +162 -0
  105. package/packages/server/src/auth/csp-report-paths.ts +26 -0
  106. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  107. package/packages/server/src/auth/csp-report-store.ts +406 -0
  108. package/packages/server/src/auth/csp.ts +145 -11
  109. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  110. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  111. package/packages/server/src/auth/device-proof.ts +202 -0
  112. package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
  113. package/packages/server/src/auth/host-admission.ts +7 -0
  114. package/packages/server/src/auth/host-gate.ts +13 -2
  115. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  116. package/packages/server/src/auth/local-proof.ts +69 -18
  117. package/packages/server/src/auth/localhost-guard.ts +98 -33
  118. package/packages/server/src/auth/locked-json-file.ts +68 -6
  119. package/packages/server/src/auth/models-json-store.ts +269 -0
  120. package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
  121. package/packages/server/src/auth/nav-intent.ts +72 -0
  122. package/packages/server/src/auth/node-guard.ts +36 -49
  123. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  124. package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
  125. package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
  126. package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
  127. package/packages/server/src/auth/plugin-credential-store.ts +81 -10
  128. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  129. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  130. package/packages/server/src/auth/proven-tls.ts +45 -0
  131. package/packages/server/src/auth/provider-auth-storage.ts +214 -12
  132. package/packages/server/src/auth/provider-block-checks.ts +321 -0
  133. package/packages/server/src/auth/provider-host-detect.ts +151 -0
  134. package/packages/server/src/auth/provider-key-file.ts +71 -0
  135. package/packages/server/src/auth/provider-readiness.ts +91 -0
  136. package/packages/server/src/auth/radius-mcp.ts +1 -1
  137. package/packages/server/src/auth/request-principal.ts +32 -0
  138. package/packages/server/src/auth/route-tier-gate.ts +3 -2
  139. package/packages/server/src/auth/secret-rotation.ts +246 -0
  140. package/packages/server/src/auth/secure-origin.ts +56 -0
  141. package/packages/server/src/auth/serve-app-host.ts +111 -11
  142. package/packages/server/src/auth/vertex-key-check.ts +140 -0
  143. package/packages/server/src/auth/ws-ticket.ts +40 -2
  144. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  145. package/packages/server/src/browse.ts +73 -20
  146. package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
  147. package/packages/server/src/browser-handlers/directory-handler.ts +34 -24
  148. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  149. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  150. package/packages/server/src/browser-handlers/session-action-handler.ts +167 -63
  151. package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
  152. package/packages/server/src/browser-handlers/subscription-handler.ts +146 -3
  153. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  154. package/packages/server/src/build-plugin-send-prompt.ts +18 -0
  155. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  156. package/packages/server/src/cli/credentials-command.ts +555 -0
  157. package/packages/server/src/cli.ts +229 -53
  158. package/packages/server/src/config-api.ts +53 -35
  159. package/packages/server/src/config-snapshot.ts +197 -1
  160. package/packages/server/src/directory-service.ts +193 -68
  161. package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
  162. package/packages/server/src/event-wiring.ts +322 -207
  163. package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
  164. package/packages/server/src/git-worktree/git-operations.ts +45 -11
  165. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  166. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  167. package/packages/server/src/git-worktree/repo-lock.ts +42 -0
  168. package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
  169. package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
  170. package/packages/server/src/git-worktree/worktree-init.ts +5 -1
  171. package/packages/server/src/identity/http-road-classification.ts +18 -2
  172. package/packages/server/src/identity/identity-floor.ts +5 -2
  173. package/packages/server/src/identity/ws-message-scope.ts +11 -3
  174. package/packages/server/src/identity/ws-road-classification.ts +3 -1
  175. package/packages/server/src/known-server-moves.ts +36 -15
  176. package/packages/server/src/lib/browse-roots.ts +129 -17
  177. package/packages/server/src/lib/client-dist.ts +36 -21
  178. package/packages/server/src/lib/content-disposition.ts +20 -0
  179. package/packages/server/src/lib/dashboard-state-guard.ts +513 -0
  180. package/packages/server/src/lib/diagram-render.ts +4 -6
  181. package/packages/server/src/lib/eml.ts +5 -10
  182. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  183. package/packages/server/src/lib/frame-policy-probe.ts +308 -0
  184. package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
  185. package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
  186. package/packages/server/src/lib/grep-worker.ts +23 -0
  187. package/packages/server/src/lib/grep.ts +96 -7
  188. package/packages/server/src/lib/index-html.ts +81 -0
  189. package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
  190. package/packages/server/src/lib/office-preview.ts +49 -13
  191. package/packages/server/src/lib/path-containment.ts +50 -10
  192. package/packages/server/src/lib/resolve-file-mention.ts +234 -40
  193. package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
  194. package/packages/server/src/lib/route-admission.ts +80 -0
  195. package/packages/server/src/lib/writable-handler-target.ts +4 -0
  196. package/packages/server/src/lib/writable-md-target.ts +26 -0
  197. package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
  198. package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
  199. package/packages/server/src/lifecycle/exit-signal.ts +43 -0
  200. package/packages/server/src/lifecycle/recovery-server.ts +65 -18
  201. package/packages/server/src/live-server/capability-redact.ts +31 -0
  202. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  203. package/packages/server/src/live-server/live-capability.ts +615 -44
  204. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  205. package/packages/server/src/live-server/live-csp.ts +141 -0
  206. package/packages/server/src/live-server/live-egress.ts +435 -0
  207. package/packages/server/src/live-server/live-exposure.ts +149 -0
  208. package/packages/server/src/live-server/live-log.ts +25 -0
  209. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  210. package/packages/server/src/live-server/live-server-manager.ts +220 -33
  211. package/packages/server/src/live-server/live-server-proxy.ts +411 -50
  212. package/packages/server/src/live-server/live-static.ts +231 -0
  213. package/packages/server/src/live-server/preview-dispatch.ts +286 -0
  214. package/packages/server/src/live-server/preview-observe.ts +53 -0
  215. package/packages/server/src/live-server/preview-origin.ts +182 -0
  216. package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
  217. package/packages/server/src/live-server/preview-path-store.ts +420 -0
  218. package/packages/server/src/live-server/preview-path.ts +40 -0
  219. package/packages/server/src/live-server/preview-pool.ts +385 -0
  220. package/packages/server/src/live-server/preview-preflight.ts +41 -0
  221. package/packages/server/src/live-server/preview-reserve.ts +44 -0
  222. package/packages/server/src/live-server/preview-tier.ts +217 -0
  223. package/packages/server/src/live-server/preview-viewers.ts +54 -0
  224. package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
  225. package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
  226. package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
  227. package/packages/server/src/model-proxy/internal-registry.ts +283 -21
  228. package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
  229. package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
  230. package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
  231. package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
  232. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  233. package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
  234. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  235. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
  236. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
  237. package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
  238. package/packages/server/src/openspec/readiness.ts +1 -1
  239. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  240. package/packages/server/src/openspec/workflow-schema.ts +141 -267
  241. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  242. package/packages/server/src/package/provider-probe.ts +202 -7
  243. package/packages/server/src/pairing/browser-gateway.ts +325 -51
  244. package/packages/server/src/pairing/device-key-intake.ts +120 -0
  245. package/packages/server/src/pairing/device-token-services.ts +26 -0
  246. package/packages/server/src/pairing/paired-devices.ts +702 -27
  247. package/packages/server/src/pairing/pairing.ts +103 -11
  248. package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
  249. package/packages/server/src/pairing/socket-locality.ts +26 -0
  250. package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
  251. package/packages/server/src/pending/pending-attach-registry.ts +15 -0
  252. package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
  253. package/packages/server/src/persistence/memory-event-store.ts +251 -296
  254. package/packages/server/src/persistence/preferences-store.ts +61 -2
  255. package/packages/server/src/pi/bridge-channel.ts +33 -0
  256. package/packages/server/src/pi/bridge-contention.ts +84 -2
  257. package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
  258. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  259. package/packages/server/src/pi/host-project-trust.ts +29 -15
  260. package/packages/server/src/pi/pi-gateway.ts +398 -41
  261. package/packages/server/src/pi/provisional-registration.ts +4 -1
  262. package/packages/server/src/pi/resource-toggle-trust.ts +18 -7
  263. package/packages/server/src/pi-agent-settings.ts +95 -301
  264. package/packages/server/src/pi-default-remirror.ts +89 -0
  265. package/packages/server/src/plugin-append-event.ts +35 -0
  266. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  267. package/packages/server/src/plugin-entry-stats.ts +61 -0
  268. package/packages/server/src/plugin-event-seam.ts +116 -4
  269. package/packages/server/src/plugin-local-request.ts +207 -0
  270. package/packages/server/src/plugin-ownership.ts +111 -0
  271. package/packages/server/src/plugin-policy-registry.ts +297 -0
  272. package/packages/server/src/plugin-request-lane.ts +92 -16
  273. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  274. package/packages/server/src/preferences-relay.ts +20 -0
  275. package/packages/server/src/project-seed.ts +347 -0
  276. package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
  277. package/packages/server/src/questions/question-store.ts +3 -2
  278. package/packages/server/src/routes/access-routes.ts +182 -15
  279. package/packages/server/src/routes/acme-routes.ts +14 -4
  280. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  281. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  282. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  283. package/packages/server/src/routes/file-routes.ts +640 -279
  284. package/packages/server/src/routes/file-write-binary-routes.ts +97 -24
  285. package/packages/server/src/routes/folder-project-routes.ts +18 -12
  286. package/packages/server/src/routes/frame-policy-routes.ts +215 -0
  287. package/packages/server/src/routes/git-routes.ts +340 -273
  288. package/packages/server/src/routes/grep-routes.ts +64 -14
  289. package/packages/server/src/routes/known-servers-routes.ts +189 -91
  290. package/packages/server/src/routes/live-server-routes.ts +572 -15
  291. package/packages/server/src/routes/local-proof-routes.ts +14 -0
  292. package/packages/server/src/routes/models-introspection-routes.ts +1 -1
  293. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  294. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  295. package/packages/server/src/routes/openspec-routes.ts +396 -31
  296. package/packages/server/src/routes/package-routes.ts +58 -10
  297. package/packages/server/src/routes/pairing-routes.ts +342 -17
  298. package/packages/server/src/routes/pi-settings-routes.ts +2 -0
  299. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  300. package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
  301. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  302. package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
  303. package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
  304. package/packages/server/src/routes/provider-auth-routes.ts +181 -10
  305. package/packages/server/src/routes/provider-override-routes.ts +158 -0
  306. package/packages/server/src/routes/provider-routes.ts +348 -86
  307. package/packages/server/src/routes/resource-activation-routes.ts +18 -4
  308. package/packages/server/src/routes/session-routes.ts +75 -25
  309. package/packages/server/src/routes/system-routes.ts +169 -52
  310. package/packages/server/src/routes/ui-link-base.ts +88 -0
  311. package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
  312. package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
  313. package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
  314. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  315. package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
  316. package/packages/server/src/server.ts +1139 -291
  317. package/packages/server/src/services/cli-service.ts +59 -10
  318. package/packages/server/src/services/secrets-resolver.ts +46 -30
  319. package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
  320. package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
  321. package/packages/server/src/session/death-reason.ts +11 -7
  322. package/packages/server/src/session/event-status-extraction.ts +5 -1
  323. package/packages/server/src/session/hydration-state.ts +148 -0
  324. package/packages/server/src/session/memory-session-manager.ts +31 -2
  325. package/packages/server/src/session/open-tool-calls.ts +81 -47
  326. package/packages/server/src/session/pid-target.ts +127 -0
  327. package/packages/server/src/session/replay-compaction.ts +18 -5
  328. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  329. package/packages/server/src/session/retained-transcript.ts +9 -2
  330. package/packages/server/src/session/seed-discovered-history.ts +85 -0
  331. package/packages/server/src/session/server-pid-context.ts +14 -0
  332. package/packages/server/src/session/session-api.ts +78 -29
  333. package/packages/server/src/session/session-archive.ts +7 -0
  334. package/packages/server/src/session/session-bootstrap.ts +9 -54
  335. package/packages/server/src/session/session-load-worker-pool.ts +11 -1
  336. package/packages/server/src/session/session-load-worker.ts +32 -4
  337. package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
  338. package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
  339. package/packages/server/src/spawn-process/headless-pid-registry.ts +393 -77
  340. package/packages/server/src/spawn-process/link-register.ts +42 -0
  341. package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
  342. package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
  343. package/packages/server/src/spawn-process/process-classifier.ts +8 -3
  344. package/packages/server/src/spawn-process/process-manager.ts +61 -6
  345. package/packages/server/src/spawn-process/restored-identity.ts +112 -0
  346. package/packages/server/src/spawn-process/session-terminator.ts +179 -18
  347. package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
  348. package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
  349. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
  350. package/packages/server/src/sudo-credential/relay.ts +337 -0
  351. package/packages/server/src/terminal/terminal-gateway.ts +10 -0
  352. package/packages/server/src/terminal/terminal-manager.ts +54 -46
  353. package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
  354. package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
  355. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  356. package/packages/server/src/tls/tls-config-validation.ts +2 -0
  357. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  358. package/packages/server/src/vault/vault-delivery-hub.ts +172 -26
  359. package/packages/server/src/vault/vault-routes.ts +9 -2
  360. package/packages/server/src/vault/vault-store.ts +87 -24
  361. package/packages/server/src/watch-files-handler.ts +66 -0
  362. package/packages/server/vendor/xlsx/LICENSE +201 -0
  363. package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
  364. package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
  365. package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
  366. package/packages/shared/package.json +4 -2
  367. package/packages/shared/src/agent-credential-files.ts +32 -0
  368. package/packages/shared/src/browser-protocol.ts +285 -59
  369. package/packages/shared/src/canvas-declare.ts +27 -0
  370. package/packages/shared/src/canvas-detect.ts +1 -1
  371. package/packages/shared/src/canvas-types.ts +2 -2
  372. package/packages/shared/src/config.ts +443 -187
  373. package/packages/shared/src/containment-guard.ts +45 -0
  374. package/packages/shared/src/credential-encryption.ts +87 -0
  375. package/packages/shared/src/custom-event-groups.ts +2 -0
  376. package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
  377. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  378. package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
  379. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  380. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  381. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  382. package/packages/shared/src/dashboard-plugin/index.ts +2 -0
  383. package/packages/shared/src/dashboard-plugin/manifest-types.ts +100 -1
  384. package/packages/shared/src/dashboard-plugin/plugin-status.ts +58 -3
  385. package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
  386. package/packages/shared/src/dashboard-plugin/slot-props.ts +47 -3
  387. package/packages/shared/src/dashboard-plugin/slot-types.ts +9 -1
  388. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +39 -3
  389. package/packages/shared/src/device-key-proof.ts +309 -0
  390. package/packages/shared/src/display-prefs.ts +13 -0
  391. package/packages/shared/src/doctor-core.ts +94 -27
  392. package/packages/shared/src/event-forward-declaration.ts +85 -12
  393. package/packages/shared/src/forbidden-subjects.ts +126 -14
  394. package/packages/shared/src/heap-limits.ts +0 -30
  395. package/packages/shared/src/host-admission.ts +2 -1
  396. package/packages/shared/src/index.ts +7 -6
  397. package/packages/shared/src/live-server.ts +161 -0
  398. package/packages/shared/src/local-proof-signal.ts +16 -0
  399. package/packages/shared/src/loopback-host.ts +26 -0
  400. package/packages/shared/src/mcp/verb-tiers.generated.ts +176 -0
  401. package/packages/shared/src/mdns-discovery.ts +25 -6
  402. package/packages/shared/src/models-json-reader.ts +41 -0
  403. package/packages/shared/src/nav-intent.ts +29 -0
  404. package/packages/shared/src/network-denial-signal.ts +15 -0
  405. package/packages/shared/src/node-version.ts +63 -60
  406. package/packages/shared/src/openspec-dependencies.ts +760 -0
  407. package/packages/shared/src/openspec-poller.ts +3 -2
  408. package/packages/shared/src/pairing-knock-client.ts +135 -11
  409. package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
  410. package/packages/shared/src/pi-path-compare.ts +31 -0
  411. package/packages/shared/src/pi-settings-schema.ts +52 -9
  412. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  413. package/packages/shared/src/pi-trust-mirror-snapshot.ts +21 -11
  414. package/packages/shared/src/pi-trust-mirror-types.ts +38 -3
  415. package/packages/shared/src/pi-trust-mirror.ts +47 -11
  416. package/packages/shared/src/pi-trust-resource-digest.ts +261 -0
  417. package/packages/shared/src/pid-namespace.ts +86 -0
  418. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  419. package/packages/shared/src/platform/git-source.ts +88 -26
  420. package/packages/shared/src/platform/git.ts +14 -8
  421. package/packages/shared/src/platform/native-ts-register.mjs +1 -1
  422. package/packages/shared/src/platform/process.ts +452 -5
  423. package/packages/shared/src/platform/resolve-pi-shell.ts +105 -0
  424. package/packages/shared/src/platform/select-git-source.ts +7 -0
  425. package/packages/shared/src/platform/spawn-runtime.ts +193 -7
  426. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  427. package/packages/shared/src/preview-egress.ts +192 -0
  428. package/packages/shared/src/preview-origins.ts +398 -0
  429. package/packages/shared/src/project-root.ts +16 -0
  430. package/packages/shared/src/prompt-answer.ts +9 -5
  431. package/packages/shared/src/protocol.ts +187 -86
  432. package/packages/shared/src/provider-env-catalog.ts +413 -0
  433. package/packages/shared/src/provider-overrides.ts +112 -0
  434. package/packages/shared/src/question-types.ts +6 -0
  435. package/packages/shared/src/recommended-extensions.ts +97 -26
  436. package/packages/shared/src/recovery-timing.ts +27 -0
  437. package/packages/shared/src/remote-credentials.ts +63 -0
  438. package/packages/shared/src/renderer-by-ext.ts +5 -2
  439. package/packages/shared/src/rest-api.ts +148 -11
  440. package/packages/shared/src/role-schema.ts +24 -0
  441. package/packages/shared/src/route-tiers.ts +149 -4
  442. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  443. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  444. package/packages/shared/src/runtime-overlay/compat.ts +70 -6
  445. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  446. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  447. package/packages/shared/src/safe-local-path.ts +24 -0
  448. package/packages/shared/src/sanitize-profiles.ts +98 -0
  449. package/packages/shared/src/secret-patterns.ts +49 -0
  450. package/packages/shared/src/server-launcher.ts +9 -1
  451. package/packages/shared/src/server-pinning.ts +55 -2
  452. package/packages/shared/src/server-routes.ts +462 -0
  453. package/packages/shared/src/session-ui-path.ts +11 -0
  454. package/packages/shared/src/source-matching.ts +2 -2
  455. package/packages/shared/src/state-replay.ts +40 -24
  456. package/packages/shared/src/sudo-credential.ts +71 -0
  457. package/packages/shared/src/tls-only-token.ts +16 -0
  458. package/packages/shared/src/tool-path-resolve.ts +16 -1
  459. package/packages/shared/src/tool-registry/definitions.ts +5 -5
  460. package/packages/shared/src/tool-registry/strategies.ts +13 -12
  461. package/packages/shared/src/tool-workdir.ts +56 -0
  462. package/packages/shared/src/trusted-types-mode.ts +72 -0
  463. package/packages/shared/src/types.ts +134 -109
  464. package/packages/shared/src/url-policy.ts +96 -0
  465. package/packages/shared/src/vault-delivery.ts +15 -0
  466. package/packages/shared/src/vertex-regions.ts +81 -0
  467. package/packages/shared/src/ws-message-tiers.ts +11 -3
  468. package/packages/extension/src/subagent-fanout-admission.ts +0 -234
  469. package/packages/extension/src/subagent-forward-sites.ts +0 -69
  470. package/packages/extension/src/subagent-frame-buffer.ts +0 -245
  471. package/packages/extension/src/subagent-frame-strip.ts +0 -109
  472. package/packages/extension/src/subagent-saturation.ts +0 -196
  473. package/packages/extension/src/subagent-tick-throttle.ts +0 -252
  474. package/packages/shared/src/anthropic-messages-source.ts +0 -8
@@ -0,0 +1,185 @@
1
+ /**
2
+ * `ensureWorktree`: create-or-reuse a worktree for a branch on behalf of a
3
+ * plugin spawn. A thin, never-throwing wrapper over `listWorktrees` +
4
+ * `addWorktree` (the functions `POST /api/git/worktree` uses), adding known-folder
5
+ * admission, ref validation, reuse containment under `<main>/.worktrees/`, and a
6
+ * per-repo lock. Returns a typed result; every failure maps to a public code.
7
+ *
8
+ * See change: add-plugin-spawn-worktree (design D1, D3, D4, D5).
9
+ */
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import { type Admission, type AdmitCwdOptions, admissionAllows, releaseAdmission } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
13
+ import { slugifyBranch } from "@blackbelt-technology/pi-dashboard-shared/git-worktree-helpers.js";
14
+ import { execFileSync } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
15
+ import { admitRouteCwd } from "../lib/route-admission.js";
16
+ import { safeRealpathSync } from "../resolve-path.js";
17
+ import {
18
+ type AddWorktreeError,
19
+ addWorktree,
20
+ listWorktrees,
21
+ pruneWorktrees,
22
+ resolveDefaultBase,
23
+ resolveMainPath,
24
+ } from "./git-operations.js";
25
+ import type { WorktreeEntry } from "./git-worktree.js";
26
+ import { isValidRefArg } from "./ref-arg.js";
27
+ import { repoLockKey, withRepoLock } from "./repo-lock.js";
28
+
29
+ type EnsureWorktreeCode =
30
+ | "not_git"
31
+ | "admission_unavailable"
32
+ | "branch_invalid"
33
+ | "exists"
34
+ | "base_not_found"
35
+ | "branch_in_use"
36
+ | "policy_mismatch"
37
+ | "git_failed";
38
+
39
+ export type EnsureWorktreeResult =
40
+ | { ok: true; path: string; branch: string; created: boolean }
41
+ | { ok: false; code: EnsureWorktreeCode; message: string };
42
+
43
+ export interface EnsureWorktreeOptions {
44
+ /** Directory inside the repository (a plugin's spawn `cwd`). Admitted against `knownCwds`. */
45
+ cwd: string;
46
+ branch: string;
47
+ /** Fork point for a brand-new branch only; ignored when the branch or worktree already exists. */
48
+ base?: string;
49
+ ifExists: "reuse" | "fail";
50
+ /** Host cwd-policy check on the target worktree path; `false` → `policy_mismatch`. Runs before any git write. */
51
+ checkTarget?: (target: string) => boolean;
52
+ /** Live known-folder set (same set the git routes admit against). Fail-closed default: nothing is known. */
53
+ knownCwds?: () => string[];
54
+ admitOptions?: AdmitCwdOptions;
55
+ }
56
+
57
+ /** Seams for tests; every default is the real implementation. */
58
+ export interface EnsureWorktreeDeps {
59
+ admit?: (cwd: string) => Promise<Admission>;
60
+ listWorktrees?: typeof listWorktrees;
61
+ addWorktree?: typeof addWorktree;
62
+ prune?: (cwd: string) => unknown;
63
+ resolveDefaultBase?: typeof resolveDefaultBase;
64
+ }
65
+
66
+ const GIT_TIMEOUT = 15_000;
67
+
68
+ /** Run git with argv (no shell); true iff it exits 0. */
69
+ function gitOk(args: string[], cwd: string): boolean {
70
+ try {
71
+ execFileSync("git", args, { cwd, stdio: ["ignore", "pipe", "pipe"], timeout: GIT_TIMEOUT });
72
+ return true;
73
+ } catch {
74
+ return false;
75
+ }
76
+ }
77
+
78
+ const fail = (code: EnsureWorktreeCode, message: string): EnsureWorktreeResult => ({ ok: false, code, message });
79
+
80
+ /** True iff `child` is strictly inside `dir` (both resolved; symlink-safe for existing paths). */
81
+ function isInside(dir: string, child: string): boolean {
82
+ const rel = path.relative(safeRealpathSync(dir), safeRealpathSync(child));
83
+ return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
84
+ }
85
+
86
+ /** Branch name safe to hand to git as a positional ref: argv-safe, a legal ref name, no `@{…}` shorthand. */
87
+ function isLegalBranch(branch: string, cwd: string): boolean {
88
+ if (!isValidRefArg(branch) || branch.includes("@{")) return false;
89
+ return gitOk(["check-ref-format", "--branch", branch], cwd);
90
+ }
91
+
92
+ const ADD_ERROR_CODE: Record<AddWorktreeError, EnsureWorktreeCode> = {
93
+ not_a_repo: "not_git",
94
+ cwd_invalid: "not_git",
95
+ invalid_ref: "branch_invalid",
96
+ branch_in_use: "branch_in_use",
97
+ branch_exists: "git_failed",
98
+ path_exists: "git_failed",
99
+ base_not_found: "base_not_found",
100
+ git_failed: "git_failed",
101
+ git_not_found: "git_failed",
102
+ };
103
+
104
+ export async function ensureWorktree(opts: EnsureWorktreeOptions, deps: EnsureWorktreeDeps = {}): Promise<EnsureWorktreeResult> {
105
+ try {
106
+ return await run(opts, deps);
107
+ } catch (err) {
108
+ return fail("git_failed", err instanceof Error ? err.message : String(err));
109
+ }
110
+ }
111
+
112
+ async function run(opts: EnsureWorktreeOptions, deps: EnsureWorktreeDeps): Promise<EnsureWorktreeResult> {
113
+ const { branch, base, ifExists } = opts;
114
+ const admit = deps.admit ?? ((c: string) => admitRouteCwd(c, { knownCwds: opts.knownCwds, admitOptions: opts.admitOptions }));
115
+ const list = deps.listWorktrees ?? listWorktrees;
116
+ const add = deps.addWorktree ?? addWorktree;
117
+ const prune = deps.prune ?? pruneWorktrees;
118
+ const defaultBase = deps.resolveDefaultBase ?? resolveDefaultBase;
119
+
120
+ // Admission: the same known-folder rule the route applies, released in `finally`.
121
+ const admission = await admit(opts.cwd);
122
+ try {
123
+ if (admission.kind === "indeterminate") return fail("admission_unavailable", "cwd admission could not be decided right now");
124
+ if (admission.kind !== "admit" || !admissionAllows(admission, opts.cwd)) return fail("not_git", "cwd is not a known git folder");
125
+ const cwd = admission.token.canonCwd;
126
+ if (!fs.statSync(cwd, { throwIfNoEntry: false })?.isDirectory()) return fail("not_git", "cwd is not a directory");
127
+
128
+ const main = resolveMainPath(cwd);
129
+ if (!main) return fail("not_git", "not a git repository");
130
+
131
+ // Validation: every check below runs before any mutating git call.
132
+ if (!isLegalBranch(branch, cwd)) return fail("branch_invalid", "invalid branch name");
133
+ if (base !== undefined && !isValidRefArg(base)) return fail("branch_invalid", "invalid base ref");
134
+ const slug = slugifyBranch(branch);
135
+ const worktreesDir = path.join(main, ".worktrees");
136
+ const derived = path.join(worktreesDir, slug);
137
+ if (!slug || !isInside(worktreesDir, derived) || path.resolve(derived) !== derived) {
138
+ return fail("branch_invalid", "branch does not map to a path under .worktrees/");
139
+ }
140
+
141
+ return await withRepoLock(repoLockKey(cwd), async () => {
142
+ const policyOk = (target: string) => opts.checkTarget?.(target) !== false;
143
+
144
+ // Step 1: an existing registration for the branch (bare-name match).
145
+ let entries: WorktreeEntry[] = list(cwd);
146
+ let match = entries.find((e) => e.branch === branch);
147
+ if (match && (match.isMain || !isInside(worktreesDir, match.path))) {
148
+ return fail("branch_in_use", "branch is checked out outside the worktree directory");
149
+ }
150
+ if (match && match.exists === false) {
151
+ if (!policyOk(derived)) return fail("policy_mismatch", "target is outside the caller's cwd policy");
152
+ prune(cwd);
153
+ entries = list(cwd);
154
+ match = entries.find((e) => e.branch === branch);
155
+ if (match && match.exists === false) return fail("git_failed", "stale worktree registration could not be pruned");
156
+ }
157
+ if (match) {
158
+ if (ifExists === "fail") return fail("exists", "a worktree for this branch already exists");
159
+ if (!policyOk(match.path)) return fail("policy_mismatch", "target is outside the caller's cwd policy");
160
+ return { ok: true, path: match.path, branch, created: false };
161
+ }
162
+
163
+ if (!policyOk(derived)) return fail("policy_mismatch", "target is outside the caller's cwd policy");
164
+
165
+ // Steps 2-4: pick the add mode. An existing local branch is checked out, an origin-only
166
+ // branch is continued from `origin/<branch>`, anything else forks `base` (verified here only).
167
+ let added: ReturnType<typeof addWorktree>;
168
+ if (gitOk(["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], cwd)) {
169
+ added = add({ cwd, base: branch });
170
+ } else if (gitOk(["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`], cwd)) {
171
+ added = add({ cwd, base: `origin/${branch}`, newBranch: branch });
172
+ } else {
173
+ const from = base ?? defaultBase(cwd);
174
+ if (!from || !gitOk(["rev-parse", "--verify", "--end-of-options", `${from}^{commit}`], cwd)) {
175
+ return fail("base_not_found", "base ref not found");
176
+ }
177
+ added = add({ cwd, base: from, newBranch: branch });
178
+ }
179
+ if (!added.ok) return fail(ADD_ERROR_CODE[added.error] ?? "git_failed", added.message);
180
+ return { ok: true, path: added.path, branch, created: true };
181
+ });
182
+ } finally {
183
+ if (admission.kind === "admit") releaseAdmission(admission.token);
184
+ }
185
+ }
@@ -27,6 +27,8 @@ import type { GitStatus } from "@blackbelt-technology/pi-dashboard-shared/types.
27
27
  // are otherwise un-spyable). `pruneWorktrees` calls `self.resolveMainPath`.
28
28
  // See change: support-non-git-init-hook.
29
29
  import * as self from "./git-operations.js";
30
+ import { redactGitText } from "./redact-git-text.js";
31
+ import { assertRefArg, isValidRefArg } from "./ref-arg.js";
30
32
  import {
31
33
  ensureWorktreeExcludeLine,
32
34
  isOrphanWorktreePath,
@@ -325,12 +327,12 @@ export async function commitFiles(opts: {
325
327
 
326
328
  const staged = await runGitCapture(["add", "--", ...safePaths], cwd);
327
329
  if (staged.code !== 0) {
328
- throw new GitCommitError("stage-failed", staged.stderr.trim() || "git add failed");
330
+ throw new GitCommitError("stage-failed", redactGitText(staged.stderr.trim() || "git add failed", { root: cwd }));
329
331
  }
330
332
 
331
333
  const committed = await runGitCapture(["commit", "-F", "-", "--", ...safePaths], cwd, message);
332
334
  if (committed.code !== 0) {
333
- throw new GitCommitError("commit-failed", committed.stderr.trim() || "git commit failed");
335
+ throw new GitCommitError("commit-failed", redactGitText(committed.stderr.trim() || "git commit failed", { root: cwd }));
334
336
  }
335
337
 
336
338
  const head = await runGitCapture(["rev-parse", "HEAD"], cwd);
@@ -354,7 +356,7 @@ export async function getChangedFiles(cwd: string): Promise<GitChangedFile[]> {
354
356
  // Propagate a real git failure instead of masking it as "no changes". A
355
357
  // clean tree still exits 0 with empty stdout → `[]` below.
356
358
  if (statusRes.code !== 0) {
357
- throw new GitCommitError("not-a-repo", statusRes.stderr.trim() || "git status failed");
359
+ throw new GitCommitError("not-a-repo", redactGitText(statusRes.stderr.trim() || "git status failed", { root: cwd }));
358
360
  }
359
361
 
360
362
  const files: GitChangedFile[] = [];
@@ -480,12 +482,24 @@ export interface CheckoutDirty {
480
482
  files: string[];
481
483
  }
482
484
 
483
- /** Checkout a branch. Returns dirty info if working tree is dirty and stash=false. */
485
+ /**
486
+ * Checkout a branch. Returns dirty info if working tree is dirty and stash=false.
487
+ * Throws `InvalidRefError` (before ANY git process starts) when `branch`, or the local name
488
+ * derived from it by stripping the remote prefix, is not a safe positional git argument.
489
+ * See change: harden-git-terminal-plugin-boundaries (B1r).
490
+ */
484
491
  export function checkoutBranch(
485
492
  cwd: string,
486
493
  branch: string,
487
494
  stash: boolean
488
495
  ): CheckoutResult | CheckoutDirty {
496
+ assertRefArg(branch, "branch");
497
+ // Check if this is a remote branch that needs a local tracking branch
498
+ const isRemote = branch.includes("/");
499
+ const localName = isRemote ? branch.replace(/^[^/]+\//, "") : branch;
500
+ // The derived name reaches `git checkout [-b] <localName>`: validate it too (`origin/-x`, `origin/`).
501
+ if (isRemote) assertRefArg(localName, "local branch name");
502
+
489
503
  // Already on this branch?
490
504
  const headRef = tryRun(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd);
491
505
  if (headRef === branch) return { success: true };
@@ -502,10 +516,7 @@ export function checkoutBranch(
502
516
  stashed = true;
503
517
  }
504
518
 
505
- // Check if this is a remote branch that needs a local tracking branch
506
- const isRemote = branch.includes("/");
507
519
  if (isRemote) {
508
- const localName = branch.replace(/^[^/]+\//, "");
509
520
  // Check if local branch exists
510
521
  const localExists = tryRun(["git", "rev-parse", "--verify", `refs/heads/${localName}`], cwd);
511
522
  if (!localExists) {
@@ -691,6 +702,8 @@ export function pruneWorktrees(
691
702
  export type AddWorktreeError =
692
703
  | "not_a_repo"
693
704
  | "cwd_invalid"
705
+ /** A caller-supplied ref / path is option-like or has control characters (B1r). */
706
+ | "invalid_ref"
694
707
  | "branch_in_use"
695
708
  | "branch_exists"
696
709
  | "path_exists"
@@ -722,6 +735,10 @@ export interface AddWorktreeFailure {
722
735
  orphanLikely?: boolean;
723
736
  }
724
737
 
738
+ function invalidRef(what: string): { ok: false; error: "invalid_ref"; message: string } {
739
+ return { ok: false, error: "invalid_ref", message: `invalid ${what}` };
740
+ }
741
+
725
742
  export interface AddWorktreeOptions {
726
743
  /** Cwd inside the parent repo (any worktree's path resolves to the same parent). */
727
744
  cwd: string;
@@ -750,6 +767,12 @@ export interface AddWorktreeOptions {
750
767
  */
751
768
  export function addWorktree(opts: AddWorktreeOptions): AddWorktreeSuccess | AddWorktreeFailure {
752
769
  const { cwd, base, newBranch, force } = opts;
770
+ // B1r: every caller-supplied argument is validated before any git process starts. `path` is
771
+ // optional (absent → derived default); `newBranch` absent → checkout mode.
772
+ // See change: harden-git-terminal-plugin-boundaries.
773
+ if (!isValidRefArg(base)) return invalidRef("base");
774
+ if (newBranch !== undefined && !isValidRefArg(newBranch)) return invalidRef("newBranch");
775
+ if (opts.path !== undefined && opts.path !== "" && !isValidRefArg(opts.path)) return invalidRef("path");
753
776
  // Checkout mode = no newBranch. `base` is the existing branch ref to
754
777
  // check out. See change: worktree-checkout-existing-branch.
755
778
  const checkoutMode = newBranch === undefined;
@@ -780,6 +803,8 @@ export function addWorktree(opts: AddWorktreeOptions): AddWorktreeSuccess | AddW
780
803
  // branch name (bare name triggers DWIM for remote-only refs); fork mode
781
804
  // forks from `base`.
782
805
  const checkoutCommitish = resolvedBranch;
806
+ // The derived local name (`origin/-x` → `-x`) reaches git as a positional argument too.
807
+ if (!isValidRefArg(resolvedBranch)) return invalidRef("derived branch name");
783
808
  // Derive worktree path when not supplied. Fork mode slugs the new
784
809
  // branch name; checkout mode slugs the local name of the base ref so
785
810
  // `origin/foo` lands at `.worktrees/foo`, not `.worktrees/origin-foo`.
@@ -1007,7 +1032,7 @@ export interface LifecycleFailure<C extends string = string> {
1007
1032
  * (the `info/exclude` write) — the AUTHORIZATION anchor is
1008
1033
  * `resolveMainPath`.
1009
1034
  */
1010
- function resolveCommonDirAbs(cwd: string): string | null {
1035
+ export function resolveCommonDirAbs(cwd: string): string | null {
1011
1036
  const raw = tryRun(["git", "rev-parse", "--path-format=absolute", "--git-common-dir"], cwd);
1012
1037
  if (!raw) return null;
1013
1038
  return path.isAbsolute(raw) ? raw : path.resolve(cwd, raw);
@@ -1275,7 +1300,8 @@ export function resolveDefaultBase(
1275
1300
 
1276
1301
  /** `resolveDefaultBase` that throws `GitMissingError` instead of swallowing a missing binary. */
1277
1302
  function resolveDefaultBaseStrict(cwd: string, hint?: string): string | null {
1278
- if (hint && tryRunStrict(["git", "rev-parse", "--verify", hint], cwd)) return hint;
1303
+ // B1r: a stored hint is untrusted (WS-supplied) — an option-like hint is ignored, never passed to git.
1304
+ if (isValidRefArg(hint) && tryRunStrict(["git", "rev-parse", "--verify", hint], cwd)) return hint;
1279
1305
  for (const name of BASE_FALLBACKS) {
1280
1306
  if (tryRunStrict(["git", "rev-parse", "--verify", `refs/heads/${name}`], cwd)) return name;
1281
1307
  }
@@ -1315,8 +1341,8 @@ export function resolveRemoteBase(
1315
1341
  /** `resolveRemoteBase` that throws `GitMissingError` instead of swallowing a missing binary. */
1316
1342
  function resolveRemoteBaseStrict(cwd: string, hint?: string): string | null {
1317
1343
  const stripOrigin = (n: string) => n.replace(/^origin\//, "");
1318
- const hintBare = hint ? stripOrigin(hint) : undefined;
1319
- if (hintBare && tryRunStrict(["git", "rev-parse", "--verify", `refs/remotes/origin/${hintBare}`], cwd)) {
1344
+ const hintBare = isValidRefArg(hint) ? stripOrigin(hint) : undefined;
1345
+ if (isValidRefArg(hintBare) && tryRunStrict(["git", "rev-parse", "--verify", `refs/remotes/origin/${hintBare}`], cwd)) {
1320
1346
  return hintBare;
1321
1347
  }
1322
1348
  for (const name of BASE_FALLBACKS) {
@@ -1645,6 +1671,7 @@ function computeOrphanLikely(cwd: string, worktreePath: string, mainPath?: strin
1645
1671
  }
1646
1672
 
1647
1673
  export type OrphanCleanupError =
1674
+ | "invalid_ref"
1648
1675
  | "outside_repo"
1649
1676
  | "not_a_directory"
1650
1677
  | "not_orphan"
@@ -1701,6 +1728,11 @@ export function orphanCleanup(
1701
1728
  const maxFiles = opts.maxFiles ?? 20;
1702
1729
  const maxFileSize = opts.maxFileSize ?? 1_048_576; // 1 MB
1703
1730
 
1731
+ // B1r: an option-like / control-character path is refused before anything touches git or the fs.
1732
+ if (!isValidRefArg(targetPath)) {
1733
+ return { ok: false, error: "invalid_ref", message: "invalid path" };
1734
+ }
1735
+
1704
1736
  // ── (i) Resolve the anchor: the RESOLVED main checkout (D6) — an orphan
1705
1737
  // can be cleaned from any worktree of the repo. `null` is a refusal.
1706
1738
  const repoRoot = resolveMainPath(cwd);
@@ -1955,6 +1987,8 @@ export function addWorktreeFromPr(opts: {
1955
1987
  path?: string;
1956
1988
  }): AddWorktreeFromPrSuccess | AddWorktreeFromPrFailure {
1957
1989
  const { cwd, prNumber } = opts;
1990
+ // B1r: an option-like `path` is refused before any git process starts.
1991
+ if (opts.path !== undefined && opts.path !== "" && !isValidRefArg(opts.path)) return invalidRef("path");
1958
1992
  // D2: one resolution proves repo-ness and anchors the derived path. The
1959
1993
  // refusal happens BEFORE any fetch — an unresolvable checkout never
1960
1994
  // touches the network.
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Redaction of git-derived text (error / message / stderr) before it reaches a client.
3
+ *
4
+ * Rules, applied in this order:
5
+ * 1. strip URL userinfo from `http(s)://user:pw@host` (password-less `user@` too);
6
+ * `ssh://user:pw@host` keeps the user, drops the password; scp-form is untouched;
7
+ * 2. mask specific token shapes only (`sk-`, `ghp_`, `github_pat_`, `glpat-`, `Bearer`) to
8
+ * their prefix + `***` — deliberately NOT a generic long-blob rule, so 40-hex commit SHAs
9
+ * survive;
10
+ * 3. absolute paths under the operation's repository root become repo-relative (root → `.`);
11
+ * 4. absolute paths under the home directory become `~/…`;
12
+ * 5. any other absolute path (POSIX or drive-letter) becomes `<path>`.
13
+ *
14
+ * Pure and linear-time: every pattern is anchored on a literal prefix and uses bounded or
15
+ * single-pass character classes (no nested quantifiers). Never throws.
16
+ *
17
+ * See change: harden-git-terminal-plugin-boundaries (B20).
18
+ */
19
+
20
+ import os from "node:os";
21
+
22
+ export interface RedactContext {
23
+ /** The repository / worktree root the git operation ran in. Captured at operation time. */
24
+ root?: string;
25
+ /** Home directory (default: `os.homedir()`). Pass `""` to disable the `~` rule. */
26
+ home?: string;
27
+ }
28
+
29
+ /** `http(s)://[userinfo@]host` — userinfo runs to the LAST `@` of the authority (a raw `@` may sit in a password). */
30
+ const HTTP_USERINFO = /(https?:\/\/)[^\s/]*@/gi;
31
+ /** `ssh://user:password@host` → `ssh://user@host`. */
32
+ const SSH_PASSWORD = /(ssh:\/\/[^\s/:@]*):[^\s/]*@/gi;
33
+ /** Token shapes: prefix + >= 20 `[A-Za-z0-9_-]`, with a non-word character (or start) before the prefix. */
34
+ const TOKEN = /(?<![A-Za-z0-9_])(sk-|ghp_|github_pat_|glpat-)[A-Za-z0-9_-]{20,}/g;
35
+ const BEARER = /\b(Bearer)[ \t]+[A-Za-z0-9._~+/=-]+/gi;
36
+ /**
37
+ * An absolute path: POSIX `/…` after start / whitespace / an opening or quoting character (never
38
+ * after `:` or a word character, so `https://host/x`, `git@h:o/r.git` and `a/b` are not paths), or a
39
+ * drive-letter `D:\…` / `D:/…`. The body stops at whitespace, quotes, brackets and `:` so a
40
+ * `path:line:col` suffix survives.
41
+ */
42
+ const ABS_PATH =
43
+ /(?<=^|[\s"'`(\[{=,;<>|]|file:\/\/)\/[^\s"'`<>|*?:,;()[\]{}]*|(?<![A-Za-z0-9_])[A-Za-z]:[\\/][^\s"'`<>|*?:,;()[\]{}]*/g;
44
+ const TRAILING_PUNCT = /[.!?]+$/;
45
+
46
+ function stripTrailingSep(p: string): string {
47
+ return p.length > 1 ? p.replace(/[\\/]+$/, "") || p.slice(0, 1) : p;
48
+ }
49
+
50
+ /** If `p` is `base` or lies inside it, the remainder (without a leading separator); else `undefined`. */
51
+ function under(p: string, base: string | undefined): string | undefined {
52
+ if (!base) return undefined;
53
+ const b = stripTrailingSep(base);
54
+ if (b.length === 0) return undefined;
55
+ const windows = /^[A-Za-z]:/.test(b) || b.includes("\\");
56
+ const norm = (s: string) => (windows ? s.replace(/\\/g, "/").toLowerCase() : s);
57
+ const np = norm(p);
58
+ const nb = norm(b);
59
+ if (np === nb) return "";
60
+ const prefix = nb.endsWith("/") ? nb : `${nb}/`;
61
+ if (np.startsWith(prefix)) return p.slice(prefix.length);
62
+ return undefined;
63
+ }
64
+
65
+ function redactPath(p: string, root: string | undefined, home: string | undefined): string {
66
+ const rel = under(p, root);
67
+ if (rel !== undefined) return rel === "" ? "." : rel;
68
+ const homeRel = under(p, home);
69
+ if (homeRel !== undefined) return homeRel === "" ? "~" : `~/${homeRel}`;
70
+ return "<path>";
71
+ }
72
+
73
+ /** Best-effort text of an unknown thrown value (Error → message, string as is, else empty). */
74
+ export function gitErrorText(err: unknown): string {
75
+ if (typeof err === "string") return err;
76
+ if (err && typeof err === "object") {
77
+ const m = (err as { message?: unknown }).message;
78
+ if (typeof m === "string") return m;
79
+ }
80
+ return "";
81
+ }
82
+
83
+ function toText(input: unknown): string {
84
+ if (input === undefined || input === null) return "";
85
+ if (typeof input === "string") return input;
86
+ if (Buffer.isBuffer(input)) return input.toString("utf-8");
87
+ if (input instanceof Error) return input.message ?? "";
88
+ return gitErrorText(input);
89
+ }
90
+
91
+ function homeDir(ctx: RedactContext): string | undefined {
92
+ if (ctx.home !== undefined) return ctx.home || undefined;
93
+ try {
94
+ return os.homedir() || undefined;
95
+ } catch {
96
+ return undefined;
97
+ }
98
+ }
99
+
100
+ /** Redact `input` per the module rules. Never throws; `""`/nullish → `""`. */
101
+ export function redactGitText(input: unknown, ctx: RedactContext = {}): string {
102
+ try {
103
+ let text = toText(input);
104
+ if (text.length === 0) return "";
105
+ const root = ctx.root || undefined;
106
+ const home = homeDir(ctx);
107
+ if (text.includes("://")) {
108
+ text = text.replace(HTTP_USERINFO, "$1").replace(SSH_PASSWORD, "$1@");
109
+ }
110
+ text = text.replace(TOKEN, "$1***").replace(BEARER, "$1 ***");
111
+ if (text.includes("/") || text.includes(":\\")) {
112
+ text = text.replace(ABS_PATH, (match) => {
113
+ const tail = TRAILING_PUNCT.exec(match)?.[0] ?? "";
114
+ const body = tail ? match.slice(0, match.length - tail.length) : match;
115
+ if (body.length <= 1) return match; // a lone "/" is not a path
116
+ return redactPath(body, root, home) + tail;
117
+ });
118
+ }
119
+ return text;
120
+ } catch {
121
+ // Fail closed: never echo the unredacted text if redaction itself failed.
122
+ return "";
123
+ }
124
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Validator for caller-supplied git arguments (refs, commit-ishes, new branch names, base hints,
3
+ * worktree paths). A PRESENT value must be a non-empty string that does not begin with `-` and
4
+ * contains no C0 control character (0x00–0x1F) or DEL (0x7F); otherwise it could be parsed by git
5
+ * as an option (`--upload-pack=…`, `--orphan=…`) or smuggle a line break.
6
+ *
7
+ * The validator IS the control — no `--end-of-options`. Precedent: `packages/kb/src/sources.ts`.
8
+ *
9
+ * See change: harden-git-terminal-plugin-boundaries (B1r).
10
+ */
11
+
12
+ /** Stable error `code` carried by `InvalidRefError` and the HTTP 400 body. */
13
+ export const INVALID_REF_CODE = "invalid_ref";
14
+
15
+ export class InvalidRefError extends Error {
16
+ readonly code = INVALID_REF_CODE;
17
+ constructor(message = "invalid git ref") {
18
+ super(message);
19
+ this.name = "InvalidRefError";
20
+ }
21
+ }
22
+
23
+ const CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
24
+
25
+ /** True iff `v` is a string safe to hand to git as a positional ref/path argument. */
26
+ export function isValidRefArg(v: unknown): v is string {
27
+ return typeof v === "string" && v.length > 0 && v.charCodeAt(0) !== 0x2d && !CONTROL_CHARS.test(v);
28
+ }
29
+
30
+ /** Returns `v` when valid, else throws `InvalidRefError`. */
31
+ export function assertRefArg(v: unknown, label = "ref"): string {
32
+ if (!isValidRefArg(v)) throw new InvalidRefError(`invalid ${label}`);
33
+ return v;
34
+ }
35
+
36
+ /** A required field that is absent, `null` or `""` (the endpoint's existing "missing parameter" case). */
37
+ export function isMissingArg(v: unknown): boolean {
38
+ return v === undefined || v === null || v === "";
39
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Per-repository async mutex for worktree create-or-reuse. Keyed by the
3
+ * repository's resolved common git dir, so every worktree of one repo shares a
4
+ * key. `POST /api/git/worktree` and `ensureWorktree` both take it, so a dialog
5
+ * create and a plugin create for one repo serialize.
6
+ *
7
+ * See change: add-plugin-spawn-worktree (D4).
8
+ */
9
+ import { safeRealpathSync } from "../resolve-path.js";
10
+ import { resolveCommonDirAbs } from "./git-operations.js";
11
+
12
+ const tails = new Map<string, Promise<unknown>>();
13
+ const depths = new Map<string, number>();
14
+
15
+ /** Calls currently holding or waiting for `key`'s lock (0 when idle). Lets a test observe that a caller has queued. */
16
+ export function repoLockDepth(key: string): number {
17
+ return depths.get(key) ?? 0;
18
+ }
19
+
20
+ /** Lock key for the repository containing `cwd` (falls back to `cwd` when it has no resolvable common dir). */
21
+ export function repoLockKey(cwd: string): string {
22
+ const common = resolveCommonDirAbs(cwd);
23
+ return safeRealpathSync(common ?? cwd);
24
+ }
25
+
26
+ /** Run `fn` once every earlier holder of `key` has finished. A throwing `fn` releases the lock and rethrows. */
27
+ export async function withRepoLock<T>(key: string, fn: () => Promise<T> | T): Promise<T> {
28
+ const prev = tails.get(key) ?? Promise.resolve();
29
+ const run = prev.then(fn);
30
+ const tail = run.catch(() => undefined);
31
+ tails.set(key, tail);
32
+ depths.set(key, repoLockDepth(key) + 1);
33
+ try {
34
+ return await run;
35
+ } finally {
36
+ const left = repoLockDepth(key) - 1;
37
+ if (left > 0) depths.set(key, left);
38
+ else depths.delete(key);
39
+ // Drop the entry once nobody queued behind us, so the map stays bounded.
40
+ if (tails.get(key) === tail) tails.delete(key);
41
+ }
42
+ }