@blackbelt-technology/pi-agent-dashboard 0.10.0 → 0.11.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 (255) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +47 -6
  3. package/docs/architecture.md +1369 -63
  4. package/package.json +14 -9
  5. package/packages/extension/package.json +5 -3
  6. package/packages/extension/src/bridge-handlers/dispatch.ts +57 -3
  7. package/packages/extension/src/bridge-handlers/instance.ts +10 -1
  8. package/packages/extension/src/bridge-handlers/lifecycle.ts +65 -26
  9. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  10. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  11. package/packages/extension/src/bridge.ts +41 -28
  12. package/packages/extension/src/canvas-tool.ts +2 -0
  13. package/packages/extension/src/command-handler.ts +80 -6
  14. package/packages/extension/src/connect-target.ts +23 -0
  15. package/packages/extension/src/connection.ts +30 -7
  16. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  17. package/packages/extension/src/dev-build.ts +11 -1
  18. package/packages/extension/src/git-link-builder.ts +11 -2
  19. package/packages/extension/src/inbound-limits.ts +138 -0
  20. package/packages/extension/src/local-token-header.ts +77 -6
  21. package/packages/extension/src/model-refresh.ts +69 -0
  22. package/packages/extension/src/pinned-endpoint.ts +44 -0
  23. package/packages/extension/src/project-trust-live.ts +143 -0
  24. package/packages/extension/src/project-trust.ts +159 -20
  25. package/packages/extension/src/provider-register.ts +59 -18
  26. package/packages/extension/src/remote-registration-gate.ts +21 -21
  27. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  28. package/packages/extension/src/role-model-tools.ts +47 -6
  29. package/packages/extension/src/server-auto-start.ts +1 -1
  30. package/packages/extension/src/server-proof-probe.ts +117 -0
  31. package/packages/extension/src/session-sync.ts +42 -12
  32. package/packages/extension/src/vault-delivery.ts +11 -1
  33. package/packages/server/package.json +8 -8
  34. package/packages/server/src/access/access-grants.ts +61 -8
  35. package/packages/server/src/access/access-health.ts +10 -0
  36. package/packages/server/src/access/access-plane.ts +5 -1
  37. package/packages/server/src/access/containment-gate.ts +55 -17
  38. package/packages/server/src/access/cwd-verdict.ts +3 -3
  39. package/packages/server/src/access/pi-trust-live.ts +244 -0
  40. package/packages/server/src/access/pi-trust-mirror-service.ts +44 -11
  41. package/packages/server/src/access/planes.ts +106 -1
  42. package/packages/server/src/access/preview-egress-store.ts +153 -0
  43. package/packages/server/src/access/prompt-channel.ts +5 -0
  44. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  45. package/packages/server/src/access/provisioning.ts +763 -0
  46. package/packages/server/src/access/yolo-session.ts +54 -2
  47. package/packages/server/src/acp-bridge/acp-session-adapter.ts +8 -3
  48. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  49. package/packages/server/src/auth/audit-log.ts +80 -0
  50. package/packages/server/src/auth/auth-plugin.ts +44 -25
  51. package/packages/server/src/auth/auth.ts +24 -4
  52. package/packages/server/src/auth/bearer-auth.ts +52 -12
  53. package/packages/server/src/auth/cors-origin.ts +76 -29
  54. package/packages/server/src/auth/csp-report-paths.ts +31 -0
  55. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  56. package/packages/server/src/auth/csp-report-store.ts +406 -0
  57. package/packages/server/src/auth/csp.ts +105 -9
  58. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  59. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  60. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  61. package/packages/server/src/auth/local-proof.ts +69 -18
  62. package/packages/server/src/auth/localhost-guard.ts +48 -10
  63. package/packages/server/src/auth/nav-intent.ts +72 -0
  64. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  65. package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
  66. package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
  67. package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
  68. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  69. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  70. package/packages/server/src/auth/proven-tls.ts +45 -0
  71. package/packages/server/src/auth/provider-auth-storage.ts +6 -1
  72. package/packages/server/src/auth/radius-mcp.ts +1 -1
  73. package/packages/server/src/auth/request-principal.ts +32 -0
  74. package/packages/server/src/auth/secret-rotation.ts +246 -0
  75. package/packages/server/src/auth/secure-origin.ts +56 -0
  76. package/packages/server/src/auth/serve-app-host.ts +111 -11
  77. package/packages/server/src/auth/ws-ticket.ts +39 -1
  78. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  79. package/packages/server/src/browser-handlers/directory-handler.ts +23 -0
  80. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  81. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  82. package/packages/server/src/browser-handlers/session-action-handler.ts +9 -1
  83. package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
  84. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  85. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  86. package/packages/server/src/cli.ts +210 -39
  87. package/packages/server/src/config-api.ts +23 -1
  88. package/packages/server/src/config-snapshot.ts +48 -1
  89. package/packages/server/src/directory-service.ts +160 -54
  90. package/packages/server/src/event-wiring.ts +143 -108
  91. package/packages/server/src/git-worktree/git-operations.ts +44 -10
  92. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  93. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  94. package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
  95. package/packages/server/src/identity/http-road-classification.ts +13 -1
  96. package/packages/server/src/identity/ws-message-scope.ts +1 -0
  97. package/packages/server/src/identity/ws-road-classification.ts +1 -0
  98. package/packages/server/src/known-server-moves.ts +36 -15
  99. package/packages/server/src/lib/browse-roots.ts +118 -17
  100. package/packages/server/src/lib/client-dist.ts +36 -21
  101. package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
  102. package/packages/server/src/lib/diagram-render.ts +4 -6
  103. package/packages/server/src/lib/eml.ts +3 -8
  104. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  105. package/packages/server/src/lib/grep-worker.ts +23 -0
  106. package/packages/server/src/lib/grep.ts +93 -7
  107. package/packages/server/src/lib/index-html.ts +81 -0
  108. package/packages/server/src/lib/office-preview.ts +2 -3
  109. package/packages/server/src/lib/path-containment.ts +7 -0
  110. package/packages/server/src/lib/resolve-file-mention.ts +11 -9
  111. package/packages/server/src/lib/route-admission.ts +80 -0
  112. package/packages/server/src/lib/writable-md-target.ts +4 -0
  113. package/packages/server/src/lifecycle/recovery-server.ts +65 -18
  114. package/packages/server/src/live-server/capability-redact.ts +15 -0
  115. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  116. package/packages/server/src/live-server/live-capability.ts +224 -17
  117. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  118. package/packages/server/src/live-server/live-csp.ts +93 -0
  119. package/packages/server/src/live-server/live-egress.ts +435 -0
  120. package/packages/server/src/live-server/live-exposure.ts +149 -0
  121. package/packages/server/src/live-server/live-log.ts +21 -0
  122. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  123. package/packages/server/src/live-server/live-server-manager.ts +209 -33
  124. package/packages/server/src/live-server/live-server-proxy.ts +162 -17
  125. package/packages/server/src/live-server/live-static.ts +228 -0
  126. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  127. package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
  128. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  129. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
  130. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
  131. package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
  132. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  133. package/packages/server/src/openspec/workflow-schema.ts +141 -267
  134. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  135. package/packages/server/src/package/provider-probe.ts +8 -2
  136. package/packages/server/src/pairing/browser-gateway.ts +188 -12
  137. package/packages/server/src/pairing/device-token-services.ts +26 -0
  138. package/packages/server/src/pairing/paired-devices.ts +335 -22
  139. package/packages/server/src/pairing/pairing.ts +34 -4
  140. package/packages/server/src/pairing/socket-locality.ts +26 -0
  141. package/packages/server/src/persistence/preferences-store.ts +9 -0
  142. package/packages/server/src/pi/bridge-channel.ts +33 -0
  143. package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
  144. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  145. package/packages/server/src/pi/host-project-trust.ts +14 -6
  146. package/packages/server/src/pi/pi-gateway.ts +191 -21
  147. package/packages/server/src/pi/resource-toggle-trust.ts +1 -1
  148. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  149. package/packages/server/src/plugin-event-seam.ts +116 -4
  150. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  151. package/packages/server/src/routes/access-routes.ts +159 -9
  152. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  153. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  154. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  155. package/packages/server/src/routes/file-routes.ts +329 -209
  156. package/packages/server/src/routes/file-write-binary-routes.ts +77 -20
  157. package/packages/server/src/routes/folder-project-routes.ts +18 -12
  158. package/packages/server/src/routes/git-routes.ts +319 -203
  159. package/packages/server/src/routes/grep-routes.ts +38 -14
  160. package/packages/server/src/routes/known-servers-routes.ts +189 -91
  161. package/packages/server/src/routes/live-server-routes.ts +378 -15
  162. package/packages/server/src/routes/local-proof-routes.ts +14 -0
  163. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  164. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  165. package/packages/server/src/routes/openspec-routes.ts +379 -28
  166. package/packages/server/src/routes/package-routes.ts +58 -10
  167. package/packages/server/src/routes/pairing-routes.ts +146 -10
  168. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  169. package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
  170. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  171. package/packages/server/src/routes/provider-auth-routes.ts +15 -2
  172. package/packages/server/src/routes/resource-activation-routes.ts +18 -4
  173. package/packages/server/src/routes/session-routes.ts +51 -4
  174. package/packages/server/src/routes/system-routes.ts +84 -15
  175. package/packages/server/src/routes/ui-link-base.ts +88 -0
  176. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  177. package/packages/server/src/server.ts +648 -137
  178. package/packages/server/src/session/hydration-state.ts +148 -0
  179. package/packages/server/src/session/memory-session-manager.ts +7 -0
  180. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  181. package/packages/server/src/session/retained-transcript.ts +9 -2
  182. package/packages/server/src/session/session-load-worker.ts +11 -2
  183. package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
  184. package/packages/server/src/terminal/terminal-manager.ts +54 -46
  185. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  186. package/packages/server/src/tls/tls-config-validation.ts +2 -0
  187. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  188. package/packages/server/src/vault/vault-delivery-hub.ts +155 -25
  189. package/packages/server/src/watch-files-handler.ts +66 -0
  190. package/packages/shared/package.json +1 -1
  191. package/packages/shared/src/browser-protocol.ts +148 -2
  192. package/packages/shared/src/canvas-declare.ts +27 -0
  193. package/packages/shared/src/config.ts +372 -53
  194. package/packages/shared/src/containment-guard.ts +35 -0
  195. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
  196. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  197. package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
  198. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  199. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  200. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  201. package/packages/shared/src/dashboard-plugin/index.ts +2 -0
  202. package/packages/shared/src/dashboard-plugin/manifest-types.ts +54 -1
  203. package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
  204. package/packages/shared/src/dashboard-plugin/slot-props.ts +45 -3
  205. package/packages/shared/src/dashboard-plugin/slot-types.ts +8 -0
  206. package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
  207. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +28 -0
  208. package/packages/shared/src/display-prefs.ts +13 -0
  209. package/packages/shared/src/doctor-core.ts +94 -27
  210. package/packages/shared/src/live-server.ts +141 -0
  211. package/packages/shared/src/local-proof-signal.ts +16 -0
  212. package/packages/shared/src/loopback-host.ts +26 -0
  213. package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
  214. package/packages/shared/src/mdns-discovery.ts +25 -6
  215. package/packages/shared/src/nav-intent.ts +29 -0
  216. package/packages/shared/src/openspec-dependencies.ts +760 -0
  217. package/packages/shared/src/openspec-poller.ts +3 -2
  218. package/packages/shared/src/pairing-knock-client.ts +44 -4
  219. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  220. package/packages/shared/src/pi-trust-mirror-snapshot.ts +5 -7
  221. package/packages/shared/src/pi-trust-mirror-types.ts +36 -3
  222. package/packages/shared/src/pi-trust-mirror.ts +29 -3
  223. package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
  224. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  225. package/packages/shared/src/platform/git-source.ts +88 -26
  226. package/packages/shared/src/platform/git.ts +14 -8
  227. package/packages/shared/src/platform/process.ts +48 -4
  228. package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
  229. package/packages/shared/src/platform/select-git-source.ts +7 -0
  230. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  231. package/packages/shared/src/preview-egress.ts +138 -0
  232. package/packages/shared/src/project-root.ts +16 -0
  233. package/packages/shared/src/protocol.ts +40 -1
  234. package/packages/shared/src/recommended-extensions.ts +18 -0
  235. package/packages/shared/src/recovery-timing.ts +27 -0
  236. package/packages/shared/src/remote-credentials.ts +63 -0
  237. package/packages/shared/src/rest-api.ts +55 -8
  238. package/packages/shared/src/route-tiers.ts +55 -1
  239. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  240. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  241. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  242. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  243. package/packages/shared/src/safe-local-path.ts +24 -0
  244. package/packages/shared/src/sanitize-profiles.ts +98 -0
  245. package/packages/shared/src/server-launcher.ts +9 -1
  246. package/packages/shared/src/server-pinning.ts +55 -2
  247. package/packages/shared/src/server-routes.ts +462 -0
  248. package/packages/shared/src/session-ui-path.ts +11 -0
  249. package/packages/shared/src/tls-only-token.ts +16 -0
  250. package/packages/shared/src/tool-registry/definitions.ts +5 -5
  251. package/packages/shared/src/tool-registry/strategies.ts +12 -11
  252. package/packages/shared/src/types.ts +66 -0
  253. package/packages/shared/src/url-policy.ts +96 -0
  254. package/packages/shared/src/vault-delivery.ts +15 -0
  255. package/packages/shared/src/ws-message-tiers.ts +1 -0
@@ -6,8 +6,12 @@
6
6
  * Layout verified by the R1 CI spike (dugite-native v2.53.0-3):
7
7
  * cmd/git.exe git launcher
8
8
  * usr/bin/sh.exe POSIX shell (GNU bash under the name `sh`;
9
- * dugite-native ships NO bash.exe). pi's
10
- * `!`/`!!` call pi.exec("sh"), so this matches.
9
+ * dugite-native ships NO bash.exe).
10
+ * usr/bin/bash.exe byte copy of sh.exe added by the build step
11
+ * (download-git-windows.mjs). pi's getShellConfig()
12
+ * (bash tool, `!`, `!cmd`) resolves only a file named
13
+ * bash.exe — never sh.exe — so this is the file pi
14
+ * picks when usr/bin precedes System32 on PATH.
11
15
  * <libdir>/bin git core libs + DLLs. <libdir> is
12
16
  * arch-specific: `mingw64` on win32-x64,
13
17
  * `clangarm64` on win32-arm64.
@@ -19,11 +23,11 @@
19
23
  * This module is the ONLY place allowed to reference bundled-git paths
20
24
  * (enforced by no-hardcoded-bundled-git-paths.test.ts).
21
25
  *
22
- * See change: embed-git-bash-on-windows.
26
+ * See change: embed-git-bash-on-windows, fix-windows-bundled-bash-exe.
23
27
  */
24
28
  import { existsSync } from "node:fs";
25
29
  import path from "node:path";
26
- import type { GitSource } from "./select-git-source.js";
30
+ import type { GitSource, WindowsBashSourceSetting } from "./select-git-source.js";
27
31
 
28
32
  /** Arch-specific MinGW/Clang library dir names, in probe order. */
29
33
  const GIT_LIBDIRS = ["mingw64", "clangarm64"] as const;
@@ -90,6 +94,52 @@ export interface EnsureBundledGitOpts {
90
94
  candidates?: string[];
91
95
  /** Override `fs.existsSync` for tests. */
92
96
  exists?: (p: string) => boolean;
97
+ /**
98
+ * Where `usr/bin` (the bundled bash) sits on PATH. "bundled" (default) →
99
+ * prepended ahead of System32; "host" → appended last so pi resolves the
100
+ * host's first `bash.exe`. See change: fix-windows-bundled-bash-exe.
101
+ */
102
+ bashSource?: WindowsBashSourceSetting;
103
+ }
104
+
105
+ /** Slash-normalised, trailing-separator-trimmed, case-folded PATH entry key. */
106
+ const entryKey = (e: string): string => e.trim().replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase();
107
+
108
+ /** Existing, de-duplicated (case/slash-insensitive) subset of `dirs`, order kept. */
109
+ function existingUnique(dirs: string[], exists: (p: string) => boolean): string[] {
110
+ const seen = new Set<string>();
111
+ return dirs.filter((dir) => {
112
+ const k = entryKey(dir);
113
+ if (!exists(dir) || seen.has(k)) return false;
114
+ seen.add(k);
115
+ return true;
116
+ });
117
+ }
118
+
119
+ /**
120
+ * Placement. `cmd` + `<libdir>/bin` always precede the inherited PATH. `usr/bin`
121
+ * (bash.exe + MSYS coreutils) precedes it in "bundled" mode and follows it in
122
+ * "host" mode. Existing entries for the dirs being placed are stripped first
123
+ * (case/trailing-slash-insensitive) so switching mode MOVES usr/bin and
124
+ * re-applying is idempotent. Operates on the already-normalised `PATH` key
125
+ * (callers run normalizeEnvPathKey first).
126
+ */
127
+ function placeBundledDirs(
128
+ currentPath: string,
129
+ gitDir: string,
130
+ libDir: string | null,
131
+ bashSource: WindowsBashSourceSetting,
132
+ exists: (p: string) => boolean,
133
+ ): string {
134
+ const join = path.win32.join;
135
+ const usrBin = join(gitDir, "usr", "bin");
136
+ const front = [join(gitDir, "cmd"), ...(bashSource === "bundled" ? [usrBin] : []), ...(libDir ? [join(gitDir, libDir, "bin")] : [])];
137
+ const frontOk = existingUnique(front, exists);
138
+ const backOk = existingUnique(bashSource === "host" ? [usrBin] : [], exists);
139
+
140
+ const ours = new Set([...frontOk, ...backOk].map(entryKey));
141
+ const rest = currentPath.split(";").filter((e) => e.trim() !== "" && !ours.has(entryKey(e)));
142
+ return [...frontOk, ...rest, ...backOk].join(";");
93
143
  }
94
144
 
95
145
  /**
@@ -126,37 +176,10 @@ export function ensureBundledGitOnPath(
126
176
  const join = path.win32.join;
127
177
  const libDir = resolveLibDir(gitDir, exists);
128
178
 
129
- // PATH prepends, highest priority first. git launcher → shell+coreutils
130
- // → arch DLLs/libexec. libDir-dependent entry omitted when absent.
131
- const dirs = [join(gitDir, "cmd"), join(gitDir, "usr", "bin")];
132
- if (libDir) dirs.push(join(gitDir, libDir, "bin"));
133
-
134
- const currentPath = env.PATH ?? "";
135
- // Exact per-entry equality (case-insensitive), NOT substring containment:
136
- // substring matching would let `C:\x\usr\bin-old` block the required
137
- // `C:\x\usr\bin` prepend. Trailing separators trimmed.
138
- const present = new Set(
139
- currentPath
140
- .split(";")
141
- .map((e) => e.trim().replace(/[\\/]+$/, "").toLowerCase())
142
- .filter(Boolean),
143
- );
144
- const seen = new Set<string>();
145
- const toAdd: string[] = [];
146
- for (const dir of dirs) {
147
- if (!exists(dir)) continue;
148
- const lower = dir.replace(/[\\/]+$/, "").toLowerCase();
149
- if (present.has(lower) || seen.has(lower)) continue;
150
- seen.add(lower);
151
- toAdd.push(dir);
152
- }
153
-
154
- const DELIM = ";";
179
+ const bashSource = opts.bashSource === "host" ? "host" : "bundled";
180
+ const newPath = placeBundledDirs(env.PATH ?? "", gitDir, libDir, bashSource, exists);
155
181
  let out = env;
156
- if (toAdd.length > 0) {
157
- const newPath = currentPath
158
- ? `${toAdd.join(DELIM)}${DELIM}${currentPath}`
159
- : toAdd.join(DELIM);
182
+ if (newPath !== (env.PATH ?? "")) {
160
183
  out = { ...out, PATH: newPath };
161
184
  }
162
185
 
@@ -12,19 +12,24 @@
12
12
  * injected by the caller to avoid a binary-lookup ↔ git-source import
13
13
  * cycle.
14
14
  *
15
- * See change: embed-git-bash-on-windows.
15
+ * See change: embed-git-bash-on-windows, fix-windows-bundled-bash-exe.
16
16
  */
17
- import {
18
- selectGitSource,
19
- type GitSource,
20
- type WindowsGitSourceSetting,
21
- } from "./select-git-source.js";
17
+
18
+ import path from "node:path";
22
19
  import {
23
20
  ensureBundledGitOnPath,
24
21
  resolveBundledGitDir,
25
22
  } from "./ensure-bundled-git.js";
23
+ import { ensureWindowsSystemPath } from "./ensure-windows-path.js";
24
+ import { normalizeEnvPathKey } from "./env-path-key.js";
26
25
  import { spawnSync } from "./exec.js";
27
- import path from "node:path";
26
+ import { resolvePiShell } from "./resolve-pi-shell.js";
27
+ import {
28
+ type GitSource,
29
+ selectGitSource,
30
+ type WindowsBashSourceSetting,
31
+ type WindowsGitSourceSetting,
32
+ } from "./select-git-source.js";
28
33
 
29
34
  export type WhichFn = (cmd: string) => string | null;
30
35
 
@@ -33,11 +38,26 @@ export interface ActiveGitSource {
33
38
  setting: WindowsGitSourceSetting;
34
39
  /** Bundled git root when source is "bundled" and present, else null. */
35
40
  gitDir: string | null;
41
+ /** Where bundled `usr/bin` sits on PATH (only matters when source is "bundled"). */
42
+ bashSetting: WindowsBashSourceSetting;
36
43
  }
37
44
 
38
45
  let configuredSetting: WindowsGitSourceSetting = "auto";
46
+ let bashSetting: WindowsBashSourceSetting = "bundled";
39
47
  let cached: ActiveGitSource | null = null;
40
48
 
49
+ /**
50
+ * Seed the configured bash placement (server reads `windowsBashSource` from
51
+ * DashboardConfig). Invalidates both caches. See change: fix-windows-bundled-bash-exe.
52
+ */
53
+ export function setWindowsBashSourceSetting(setting: WindowsBashSourceSetting): void {
54
+ const next: WindowsBashSourceSetting = setting === "host" ? "host" : "bundled";
55
+ if (next !== bashSetting) {
56
+ bashSetting = next;
57
+ invalidateGitSourceCache();
58
+ }
59
+ }
60
+
41
61
  /** Seed the configured setting (server reads it from DashboardConfig). */
42
62
  export function setWindowsGitSourceSetting(setting: WindowsGitSourceSetting): void {
43
63
  if (setting !== configuredSetting) {
@@ -56,6 +76,10 @@ export interface GitSourceResolveOpts {
56
76
  /** Override `process.resourcesPath` for tests / standalone bundles. */
57
77
  resourcesPath?: string;
58
78
  candidates?: string[];
79
+ /** Override `process.platform` (test seam). */
80
+ platform?: NodeJS.Platform;
81
+ /** Override `fs.existsSync` (test seam). */
82
+ exists?: (p: string) => boolean;
59
83
  }
60
84
 
61
85
  /**
@@ -64,15 +88,17 @@ export interface GitSourceResolveOpts {
64
88
  */
65
89
  export function getActiveGitSource(which: WhichFn, opts: GitSourceResolveOpts = {}): ActiveGitSource {
66
90
  if (cached) return cached;
67
- const source = selectGitSource({ setting: configuredSetting, which });
91
+ const source = selectGitSource({ setting: configuredSetting, which, platform: opts.platform });
68
92
  const gitDir =
69
93
  source === "bundled"
70
94
  ? resolveBundledGitDir({
95
+ platform: opts.platform,
71
96
  resourcesPath: opts.resourcesPath ?? (process as { resourcesPath?: string }).resourcesPath,
72
97
  candidates: opts.candidates,
98
+ exists: opts.exists,
73
99
  })
74
100
  : null;
75
- cached = { source, setting: configuredSetting, gitDir };
101
+ cached = { source, setting: configuredSetting, gitDir, bashSetting };
76
102
  return cached;
77
103
  }
78
104
 
@@ -87,8 +113,14 @@ export function augmentEnvWithGitSource(
87
113
  opts: GitSourceResolveOpts = {},
88
114
  ): NodeJS.ProcessEnv {
89
115
  try {
90
- const { source, gitDir } = getActiveGitSource(which, opts);
91
- return ensureBundledGitOnPath(env, { source, gitDir });
116
+ const { source, gitDir, bashSetting: bashSource } = getActiveGitSource(which, opts);
117
+ return ensureBundledGitOnPath(env, {
118
+ source,
119
+ gitDir,
120
+ bashSource,
121
+ platform: opts.platform,
122
+ exists: opts.exists,
123
+ });
92
124
  } catch {
93
125
  return env;
94
126
  }
@@ -101,8 +133,26 @@ export interface GitSourceReadout {
101
133
  gitPath: string | null;
102
134
  /** `git --version` output, or null when unresolved. */
103
135
  gitVersion: string | null;
104
- /** Resolved POSIX shell path (bundled usr/bin/sh.exe or host), or null. */
136
+ /**
137
+ * The `bash.exe` pi-coding-agent would resolve for a fresh spawn (pi's
138
+ * getShellConfig order over the augmented spawn env), or null. Never `sh.exe`.
139
+ */
105
140
  shellPath: string | null;
141
+ /** Effective `windowsBashSource` placement. */
142
+ bashSetting: WindowsBashSourceSetting;
143
+ /** `shellPath` is the System32/Sysnative WSL launcher (pi stdin-transport shell). */
144
+ shellIsWslLauncher: boolean;
145
+ }
146
+
147
+ export interface GitSourceReadoutOpts extends GitSourceResolveOpts {
148
+ /**
149
+ * The env a real spawn would receive (`ToolResolver.buildSpawnEnv(process.env)`),
150
+ * or a thunk for it — evaluated only on a readout-cache miss on win32, so
151
+ * health polls on other platforms / cache hits pay nothing. When omitted, a
152
+ * minimal equivalent is derived from `process.env` (normalised PATH key +
153
+ * System32 + bundled git).
154
+ */
155
+ spawnEnv?: NodeJS.ProcessEnv | (() => NodeJS.ProcessEnv);
106
156
  }
107
157
 
108
158
  let readoutCache: GitSourceReadout | null = null;
@@ -119,27 +169,39 @@ function probeVersion(gitPath: string): string | null {
119
169
  /**
120
170
  * Windows-only diagnostic readout for /api/health + Diagnostics. Returns
121
171
  * null on macOS/Linux (the setting is a no-op there). Cached for the life
122
- * of the process; reset by invalidateGitSourceCache().
172
+ * of the process; reset by invalidateGitSourceCache() (config write) — NOT
173
+ * re-probed when Git for Windows is installed/removed at runtime.
174
+ *
175
+ * Documented residuals: the session cwd (`where.exe` searches it first) and a
176
+ * user-set pi `shellPath` (applies to the bash tool and `!` only).
123
177
  */
124
- export function getGitSourceReadout(which: WhichFn, opts: GitSourceResolveOpts = {}): GitSourceReadout | null {
125
- if (process.platform !== "win32") return null;
178
+ export function getGitSourceReadout(which: WhichFn, opts: GitSourceReadoutOpts = {}): GitSourceReadout | null {
179
+ const platform = opts.platform ?? process.platform;
180
+ if (platform !== "win32") return null;
126
181
  if (readoutCache) return readoutCache;
127
- const { source, setting, gitDir } = getActiveGitSource(which, opts);
128
- let gitPath: string | null = null;
129
- let shellPath: string | null = null;
130
- if (source === "bundled" && gitDir) {
131
- gitPath = path.win32.join(gitDir, "cmd", "git.exe");
132
- shellPath = path.win32.join(gitDir, "usr", "bin", "sh.exe");
133
- } else {
134
- gitPath = which("git");
135
- shellPath = which("bash") ?? which("sh");
136
- }
182
+ const { source, setting, gitDir, bashSetting: bashSource } = getActiveGitSource(which, opts);
183
+ const exists = opts.exists;
184
+ const join = path.win32.join;
185
+
186
+ const gitPath = source === "bundled" && gitDir ? join(gitDir, "cmd", "git.exe") : which("git");
187
+
188
+ const spawnEnv =
189
+ (typeof opts.spawnEnv === "function" ? opts.spawnEnv() : opts.spawnEnv) ??
190
+ augmentEnvWithGitSource(
191
+ ensureWindowsSystemPath(normalizeEnvPathKey({ ...process.env }, platform), { platform, exists }),
192
+ which,
193
+ opts,
194
+ );
195
+ const shell = resolvePiShell({ env: spawnEnv, exists });
196
+
137
197
  readoutCache = {
138
198
  setting,
139
199
  source,
140
200
  gitPath,
141
201
  gitVersion: gitPath ? probeVersion(gitPath) : null,
142
- shellPath,
202
+ shellPath: shell?.path ?? null,
203
+ bashSetting: bashSource,
204
+ shellIsWslLauncher: shell?.isWslLauncher ?? false,
143
205
  };
144
206
  return readoutCache;
145
207
  }
@@ -20,7 +20,7 @@ import path from "node:path";
20
20
  import type { GitPrChecks, GitPrState, GitStatus } from "../types.js";
21
21
  import { type CheckRollupEntry, collapseCheckRollup } from "./check-rollup.js";
22
22
  import { normalizePath, samePath } from "./paths.js";
23
- import { type Recipe, type Result, type RunCtx, run, runAsync, unwrap } from "./runner.js";
23
+ import { type ExecError, type Recipe, type Result, type RunCtx, run, runAsync, unwrap } from "./runner.js";
24
24
 
25
25
  /**
26
26
  * Parse `git status --porcelain=v2 --branch` stdout into a `GitStatus`.
@@ -984,32 +984,37 @@ export async function checkoutRootsClassifiedAsync(
984
984
  ): Promise<ClassifiedCheckoutRoots> {
985
985
  const exec = classifiedRunner(opts);
986
986
  const failed: string[] = [];
987
- const fail = (name: string) => {
988
- if (!failed.includes(name)) failed.push(name);
987
+ // A cwd that is a regular file cannot host a process (`spawn ENOTDIR`): that is "this is not a
988
+ // repository", a definitive answer — not a failed probe, which would read as `indeterminate`.
989
+ // See change: core-cwd-admission (D6).
990
+ let notADirectory = false;
991
+ const fail = (name: string, error: ExecError) => {
992
+ if (error.kind === "spawn-failure" && /\bENOTDIR\b/.test(error.message)) notADirectory = true;
993
+ else if (!failed.includes(name)) failed.push(name);
989
994
  };
990
995
  const roots = await resolveCheckoutRootsFromAsync({
991
996
  gitDir: async () => {
992
997
  const r = await exec(GIT_DIR_ABS, input);
993
998
  if (r.ok) return r.value;
994
- if (r.error.kind !== "exit") fail("git-dir");
999
+ if (r.error.kind !== "exit") fail("git-dir", r.error);
995
1000
  return undefined;
996
1001
  },
997
1002
  commonDir: async () => {
998
1003
  const r = await exec(GIT_COMMON_DIR_ABS, input);
999
1004
  if (r.ok) return r.value;
1000
- if (r.error.kind !== "exit") fail("git-common-dir");
1005
+ if (r.error.kind !== "exit") fail("git-common-dir", r.error);
1001
1006
  return undefined;
1002
1007
  },
1003
1008
  topLevel: async () => {
1004
1009
  const r = await exec(GIT_TOPLEVEL, input);
1005
1010
  if (r.ok) return r.value;
1006
- if (r.error.kind !== "exit") fail("show-toplevel");
1011
+ if (r.error.kind !== "exit") fail("show-toplevel", r.error);
1007
1012
  return undefined;
1008
1013
  },
1009
1014
  localCoreWorktree: async (commonDir) => {
1010
1015
  const r = await exec(GIT_CONFIG_LOCAL_CORE_WORKTREE, { cwd: input.cwd, gitDir: commonDir });
1011
1016
  if (r.ok) return r.value;
1012
- fail("config core.worktree");
1017
+ fail("config core.worktree", r.error);
1013
1018
  return undefined;
1014
1019
  },
1015
1020
  localCoreBare: async (commonDir) => {
@@ -1017,12 +1022,13 @@ export async function checkoutRootsClassifiedAsync(
1017
1022
  if (failed.length > 0) return "unknown";
1018
1023
  const r = await exec(GIT_CONFIG_LOCAL_CORE_BARE, { cwd: input.cwd, gitDir: commonDir });
1019
1024
  if (!r.ok) {
1020
- fail("config core.bare");
1025
+ fail("config core.bare", r.error);
1021
1026
  return "unknown";
1022
1027
  }
1023
1028
  return r.value === "true" ? "bare" : "not-bare";
1024
1029
  },
1025
1030
  });
1031
+ if (notADirectory && failed.length === 0) return { kind: "none" };
1026
1032
  if (failed.length > 0) return { kind: "failed", failedProbes: failed };
1027
1033
  return roots ? { kind: "roots", roots } : { kind: "none" };
1028
1034
  }
@@ -67,6 +67,9 @@ export function parseNetstatListeners(output: string, port: number, selfPid: num
67
67
  * Best-effort: any failure returns []. Excludes the current process PID.
68
68
  */
69
69
  export function findPortHolders(port: number, opts: ProcessOpts = {}): number[] {
70
+ // Integer-range guard: the port is interpolated into a shell string below.
71
+ // See change: triage-codeql-alert-debt (design D3 #30).
72
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return [];
70
73
  const platform = opts.platform ?? process.platform;
71
74
  const exec = opts.exec ?? defaultExec;
72
75
  try {
@@ -85,14 +88,20 @@ export function findPortHolders(port: number, opts: ProcessOpts = {}): number[]
85
88
 
86
89
  /**
87
90
  * Check whether a PID is alive. Cross-platform via `process.kill(pid, 0)`.
91
+ *
92
+ * Default: any throw (incl. `EPERM`) means "not alive" — unchanged for existing
93
+ * callers. With `epermAlive: true`, `EPERM` (process exists, signal not
94
+ * permitted) counts as ALIVE; only `ESRCH`/other errors mean gone. Use the
95
+ * opt-in when a false "gone" would be unsafe (e.g. before spawning a
96
+ * replacement server). See change: electron-attach-version-skew (D4b).
88
97
  */
89
- export function isProcessAlive(pid: number, opts: { kill?: KillFn } = {}): boolean {
98
+ export function isProcessAlive(pid: number, opts: { kill?: KillFn; epermAlive?: boolean } = {}): boolean {
90
99
  const kill = opts.kill ?? defaultKill;
91
100
  try {
92
101
  kill(pid, 0);
93
102
  return true;
94
- } catch {
95
- return false;
103
+ } catch (err) {
104
+ return opts.epermAlive === true && (err as NodeJS.ErrnoException)?.code === "EPERM";
96
105
  }
97
106
  }
98
107
 
@@ -176,10 +185,43 @@ export interface KillProcessResult {
176
185
  forced: boolean;
177
186
  }
178
187
 
188
+ /**
189
+ * Own process-group id, cached for the default `exec` only. Only a VALID pgid is
190
+ * cached: a failed lookup (null) is retried on the next call.
191
+ */
192
+ let ownPgidCache: number | undefined;
193
+
194
+ function readOwnPgid(exec: ExecFn): number | null {
195
+ const cacheable = exec === defaultExec;
196
+ if (cacheable && ownPgidCache !== undefined) return ownPgidCache;
197
+ let pgid: number | null = null;
198
+ try {
199
+ const n = Number(String(exec(`ps -o pgid= -p ${process.pid}`, { encoding: "utf-8" })).trim());
200
+ pgid = Number.isInteger(n) && n > 0 ? n : null;
201
+ } catch {
202
+ pgid = null;
203
+ }
204
+ if (cacheable && pgid !== null) ownPgidCache = pgid;
205
+ return pgid;
206
+ }
207
+
208
+ /**
209
+ * POSIX: does `pid` lead its own process group, and is that group NOT ours?
210
+ * Unknown own pgid ⇒ false (fall back to single-pid; never risk our own group).
211
+ */
212
+ function leadsForeignGroup(pid: number, kill: KillFn, exec: ExecFn): boolean {
213
+ if (!Number.isInteger(pid) || pid <= 1) return false;
214
+ if (signalZero(-pid, { kill }) === "esrch") return false;
215
+ const own = readOwnPgid(exec);
216
+ return own !== null && own !== pid;
217
+ }
218
+
179
219
  /**
180
220
  * Terminate a process, cross-platform:
181
221
  * - win32: `taskkill /F /T /PID <pid>` (tree kill, immediate)
182
- * - unix: SIGTERM → wait up to `timeoutMs` → SIGKILL if still alive
222
+ * - unix, `pid` leads its own (foreign) process group: {@link killProcessGroup}
223
+ * — SIGTERM → `timeoutMs` → SIGKILL to `-pid`, so children die with it (#912)
224
+ * - unix, otherwise: SIGTERM → wait up to `timeoutMs` → SIGKILL if still alive
183
225
  *
184
226
  * Returns `{ ok, forced }`. `ok` is true if the process was terminated (or
185
227
  * was already dead); `forced` is true if SIGKILL was needed on Unix.
@@ -204,6 +246,8 @@ export async function killProcess(
204
246
  }
205
247
  }
206
248
 
249
+ if (leadsForeignGroup(pid, kill, exec)) return killProcessGroup(pid, { ...opts, timeoutMs });
250
+
207
251
  try {
208
252
  kill(pid, "SIGTERM");
209
253
  } catch {
@@ -0,0 +1,76 @@
1
+ /**
2
+ * resolvePiShell — which `bash.exe` pi-coding-agent would pick on Windows, so
3
+ * diagnostics report what the agent will actually run (not what the dashboard
4
+ * would like it to run).
5
+ *
6
+ * Replica of pi-coding-agent 1.3.0 `getShellConfig()` with no `shellPath`
7
+ * (dist/utils/shell.js — re-check on every pi bump; the build gate
8
+ * assert-bundled-bash-resolvable.mjs compares this replica to the shipped pi):
9
+ * 1. `%ProgramFiles%\Git\bin\bash.exe`, then `%ProgramFiles(x86)%\Git\bin\bash.exe`
10
+ * — first that exists;
11
+ * 2. else the first `where bash.exe` hit that exists — modelled as the first
12
+ * PATH directory holding `bash.exe` (`where` lists only existing files, in
13
+ * PATH order; it also searches the process cwd first, a documented residual);
14
+ * 3. else none (pi throws "No bash shell found").
15
+ * pi never looks for `sh.exe`.
16
+ *
17
+ * Pure: env + fs are injected. Contains NO bundled-git path literals (it only
18
+ * scans PATH), so it stays outside no-hardcoded-bundled-git-paths.test.ts.
19
+ *
20
+ * See change: fix-windows-bundled-bash-exe.
21
+ */
22
+ import { existsSync } from "node:fs";
23
+ import path from "node:path";
24
+
25
+ export interface ResolvedPiShell {
26
+ path: string;
27
+ /** pi treats System32/Sysnative bash.exe as the WSL launcher (stdin transport). */
28
+ isWslLauncher: boolean;
29
+ }
30
+
31
+ export interface ResolvePiShellOpts {
32
+ /** Spawn env the agent process would receive. */
33
+ env: NodeJS.ProcessEnv;
34
+ /** Override `fs.existsSync` for tests. */
35
+ exists?: (p: string) => boolean;
36
+ }
37
+
38
+ /** pi's `isLegacyWslBashPath`: `[a-z]:\windows\(system32|sysnative)\bash.exe`. */
39
+ export function isWslLauncherBash(p: string): boolean {
40
+ const normalized = p.replace(/\//g, "\\").toLowerCase();
41
+ return /^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized);
42
+ }
43
+
44
+ /** Case-insensitive env lookup (Windows env keys are case-insensitive). */
45
+ function envGet(env: NodeJS.ProcessEnv, name: string): string | undefined {
46
+ const lower = name.toLowerCase();
47
+ for (const key of Object.keys(env)) {
48
+ if (key.toLowerCase() === lower) {
49
+ const v = env[key];
50
+ if (typeof v === "string" && v !== "") return v;
51
+ }
52
+ }
53
+ return undefined;
54
+ }
55
+
56
+ export function resolvePiShell(opts: ResolvePiShellOpts): ResolvedPiShell | null {
57
+ const exists = opts.exists ?? existsSync;
58
+ const join = path.win32.join;
59
+ const found = (p: string): ResolvedPiShell => ({ path: p, isWslLauncher: isWslLauncherBash(p) });
60
+
61
+ for (const key of ["ProgramFiles", "ProgramFiles(x86)"]) {
62
+ const root = envGet(opts.env, key);
63
+ if (!root) continue;
64
+ const candidate = `${root}\\Git\\bin\\bash.exe`;
65
+ if (exists(candidate)) return found(candidate);
66
+ }
67
+
68
+ const pathValue = envGet(opts.env, "PATH") ?? "";
69
+ for (const raw of pathValue.split(";")) {
70
+ const dir = raw.trim().replace(/^"(.*)"$/, "$1");
71
+ if (!dir) continue;
72
+ const candidate = join(dir, "bash.exe");
73
+ if (exists(candidate)) return found(candidate);
74
+ }
75
+ return null;
76
+ }
@@ -19,6 +19,13 @@
19
19
  export type GitSource = "host" | "bundled";
20
20
  export type WindowsGitSourceSetting = "auto" | "host" | "bundled";
21
21
 
22
+ /**
23
+ * Windows-only: where `usr/bin` of the bundled git tree sits on the spawn PATH
24
+ * (decides which `bash.exe` pi resolves). No effect unless the git source is
25
+ * "bundled". See change: fix-windows-bundled-bash-exe.
26
+ */
27
+ export type WindowsBashSourceSetting = "bundled" | "host";
28
+
22
29
  export interface SelectGitSourceOpts {
23
30
  /** Config value. Default "auto". */
24
31
  setting?: WindowsGitSourceSetting;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Request-`cwd` parsing + admission for plugin REST routes (automation, flows).
3
+ *
4
+ * One boundary for the three questions a route asks of a caller-supplied `cwd`,
5
+ * in a fixed order, all BEFORE any filesystem / git access under it:
6
+ * 1. shape — a present value that is not a single string → 400 `invalid_cwd`
7
+ * (array from `?cwd=a&cwd=b`, JSON object / number / boolean);
8
+ * 2. presence — absent or `""` on a route that needs a folder → 400 `cwd_required`
9
+ * (never defaulted to the server process cwd);
10
+ * 3. admission — a supplied cwd is decided by the tri-state {@link admitCwd}:
11
+ * refuse → 403 (existing plugin refusal body), indeterminate →
12
+ * 503 `cwd-admission-unavailable` + `Retry-After: 1`.
13
+ * `admitCwd` is never called for outcomes 1 and 2.
14
+ *
15
+ * The caller releases the admission token in its handler `finally` (`release()`).
16
+ * See change: harden-git-terminal-plugin-boundaries (S1r).
17
+ */
18
+ import { type AdmitCwdOptions, admissionAllows, admitCwd, releaseAdmission } from "./cwd-guard.js";
19
+
20
+ export interface RouteCwdOptions {
21
+ /** `true` → an absent or empty cwd is `cwd_required`; `false` → it resolves to `cwd: undefined`. */
22
+ required: boolean;
23
+ /** Live admit set, read on every request (never cached here). Fail-closed default: nothing known. */
24
+ knownCwds?: () => string[];
25
+ /** `admitCwd` options (the host's throttled `onIndeterminate` logger; test seams). */
26
+ admitOptions?: AdmitCwdOptions;
27
+ }
28
+
29
+ export interface RouteCwdRefusal {
30
+ ok: false;
31
+ status: number;
32
+ body: Record<string, unknown>;
33
+ headers?: Record<string, string>;
34
+ }
35
+
36
+ export type RouteCwdResult = { ok: true; cwd: string | undefined; release: () => void } | RouteCwdRefusal;
37
+
38
+ const NO_KNOWN = (): string[] => [];
39
+ const NOOP = (): void => {};
40
+
41
+ const DENIED_REASON = "cwd is not a known session or pinned directory.";
42
+ const DENIED_HINT = "Pin this directory to allow it, or open a session rooted in it.";
43
+
44
+ /** Parse (shape → presence) then admit a request `cwd` for a plugin route. */
45
+ export async function admitRouteCwdParam(raw: unknown, opts: RouteCwdOptions): Promise<RouteCwdResult> {
46
+ // JSON `null` carries no value: same as absent.
47
+ if (raw !== undefined && raw !== null && typeof raw !== "string") {
48
+ return {
49
+ ok: false,
50
+ status: 400,
51
+ body: { error: "invalid_cwd", message: "cwd must be a single string" },
52
+ };
53
+ }
54
+ if (raw === undefined || raw === null || raw === "") {
55
+ if (opts.required) {
56
+ return { ok: false, status: 400, body: { error: "cwd_required", message: "cwd is required" } };
57
+ }
58
+ return { ok: true, cwd: undefined, release: NOOP };
59
+ }
60
+ const admission = await admitCwd(raw, opts.knownCwds ?? NO_KNOWN, opts.admitOptions);
61
+ if (admission.kind === "admit" && admissionAllows(admission, raw)) {
62
+ const { token } = admission;
63
+ return { ok: true, cwd: raw, release: () => releaseAdmission(token) };
64
+ }
65
+ if (admission.kind === "indeterminate") {
66
+ return {
67
+ ok: false,
68
+ status: 503,
69
+ body: {
70
+ error: "cwd-admission-unavailable",
71
+ message: "cwd admission could not be decided right now",
72
+ retryAfterMs: 1000,
73
+ },
74
+ headers: { "Retry-After": "1" },
75
+ };
76
+ }
77
+ return {
78
+ ok: false,
79
+ status: 403,
80
+ body: { error: "not-allowed", message: `cwd not allowed: ${raw}`, reason: DENIED_REASON, hint: DENIED_HINT },
81
+ };
82
+ }
83
+
84
+ /** The minimal reply surface {@link sendRouteCwdRefusal} needs (a Fastify reply satisfies it). */
85
+ interface ReplyLike {
86
+ code(status: number): unknown;
87
+ header(name: string, value: string): unknown;
88
+ }
89
+
90
+ /** Write a refusal onto `reply` and return its body (handlers `return` it). */
91
+ export function sendRouteCwdRefusal(reply: ReplyLike, refusal: RouteCwdRefusal): Record<string, unknown> {
92
+ for (const [k, v] of Object.entries(refusal.headers ?? {})) reply.header(k, v);
93
+ reply.code(refusal.status);
94
+ return refusal.body;
95
+ }