@blackbelt-technology/pi-agent-dashboard 0.11.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 (337) hide show
  1. package/AGENTS.md +2 -0
  2. package/README.md +17 -12
  3. package/docs/architecture.md +973 -224
  4. package/package.json +29 -18
  5. package/packages/extension/package.json +16 -9
  6. package/packages/extension/src/bridge-context.ts +6 -0
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +54 -69
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
  9. package/packages/extension/src/bridge-handlers/instance.ts +21 -12
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +84 -40
  11. package/packages/extension/src/bridge-shutdown.ts +44 -0
  12. package/packages/extension/src/bridge.ts +272 -260
  13. package/packages/extension/src/command-handler.ts +26 -31
  14. package/packages/extension/src/connection.ts +123 -31
  15. package/packages/extension/src/credential-guard.ts +300 -0
  16. package/packages/extension/src/custom-entry-forward.ts +27 -18
  17. package/packages/extension/src/default-model-apply.ts +83 -0
  18. package/packages/extension/src/flow-event-wiring.ts +19 -95
  19. package/packages/extension/src/followup-drain.ts +19 -5
  20. package/packages/extension/src/path-gate/decide.ts +68 -5
  21. package/packages/extension/src/path-gate/handler.ts +16 -8
  22. package/packages/extension/src/path-gate/index.ts +2 -2
  23. package/packages/extension/src/path-gate/roots.ts +15 -3
  24. package/packages/extension/src/path-gate/suppression.ts +3 -0
  25. package/packages/extension/src/pi-env.d.ts +8 -1
  26. package/packages/extension/src/pi-retry-settings.ts +11 -2
  27. package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
  28. package/packages/extension/src/preview-path-link.ts +151 -0
  29. package/packages/extension/src/project-init/scaffold.ts +98 -35
  30. package/packages/extension/src/project-trust.ts +24 -15
  31. package/packages/extension/src/provider-model-cache.ts +118 -0
  32. package/packages/extension/src/provider-register.ts +428 -28
  33. package/packages/extension/src/retry-tracker.ts +90 -7
  34. package/packages/extension/src/role-manager.ts +4 -2
  35. package/packages/extension/src/role-model-tools.ts +21 -4
  36. package/packages/extension/src/server-auto-start.ts +68 -2
  37. package/packages/extension/src/server-launcher.ts +26 -8
  38. package/packages/extension/src/session-sync.ts +11 -12
  39. package/packages/extension/src/spawn-new-session.ts +22 -0
  40. package/packages/extension/src/steer-buffer.ts +164 -0
  41. package/packages/extension/src/stream-forward-buffer.ts +64 -15
  42. package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
  43. package/packages/extension/src/sudo-askpass/controller.ts +405 -0
  44. package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
  45. package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
  46. package/packages/extension/src/sudo-askpass/index.ts +11 -0
  47. package/packages/extension/src/sudo-askpass/install.ts +143 -0
  48. package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
  49. package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
  50. package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
  51. package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
  52. package/packages/extension/src/terminal-reload.ts +19 -5
  53. package/packages/extension/src/tool-update-filter-registry.ts +210 -0
  54. package/packages/extension/src/vault-redaction.ts +4 -3
  55. package/packages/server/package.json +17 -14
  56. package/packages/server/src/access/access-denials.ts +8 -0
  57. package/packages/server/src/access/access-grants.ts +244 -58
  58. package/packages/server/src/access/access-plane.ts +7 -0
  59. package/packages/server/src/access/containment-gate.ts +66 -21
  60. package/packages/server/src/access/denial-hold.ts +3 -0
  61. package/packages/server/src/access/grant-coordinator.ts +17 -1
  62. package/packages/server/src/access/named-grant.ts +3 -0
  63. package/packages/server/src/access/pending-grant-registry.ts +32 -5
  64. package/packages/server/src/access/pi-trust-mirror-service.ts +7 -1
  65. package/packages/server/src/access/planes.ts +1 -0
  66. package/packages/server/src/access/verified-read.ts +24 -7
  67. package/packages/server/src/acp-bridge/acp-session-adapter.ts +10 -2
  68. package/packages/server/src/acp-bridge/server-requests.ts +10 -4
  69. package/packages/server/src/agent-events/agent-event-hub.ts +1 -1
  70. package/packages/server/src/auth/audit-log.ts +28 -0
  71. package/packages/server/src/auth/auth-plugin.ts +188 -15
  72. package/packages/server/src/auth/auth.ts +80 -0
  73. package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
  74. package/packages/server/src/auth/cors-origin.ts +14 -1
  75. package/packages/server/src/auth/credential-envelope.ts +233 -0
  76. package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
  77. package/packages/server/src/auth/credential-key-worker.mjs +108 -0
  78. package/packages/server/src/auth/credential-key.ts +479 -0
  79. package/packages/server/src/auth/credential-migration.ts +162 -0
  80. package/packages/server/src/auth/csp-report-paths.ts +0 -5
  81. package/packages/server/src/auth/csp.ts +74 -36
  82. package/packages/server/src/auth/device-proof.ts +202 -0
  83. package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
  84. package/packages/server/src/auth/host-admission.ts +7 -0
  85. package/packages/server/src/auth/host-gate.ts +13 -2
  86. package/packages/server/src/auth/localhost-guard.ts +50 -23
  87. package/packages/server/src/auth/locked-json-file.ts +68 -6
  88. package/packages/server/src/auth/models-json-store.ts +269 -0
  89. package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
  90. package/packages/server/src/auth/node-guard.ts +36 -49
  91. package/packages/server/src/auth/plugin-credential-store.ts +81 -10
  92. package/packages/server/src/auth/provider-auth-storage.ts +208 -11
  93. package/packages/server/src/auth/provider-block-checks.ts +321 -0
  94. package/packages/server/src/auth/provider-host-detect.ts +151 -0
  95. package/packages/server/src/auth/provider-key-file.ts +71 -0
  96. package/packages/server/src/auth/provider-readiness.ts +91 -0
  97. package/packages/server/src/auth/route-tier-gate.ts +3 -2
  98. package/packages/server/src/auth/vertex-key-check.ts +140 -0
  99. package/packages/server/src/auth/ws-ticket.ts +1 -1
  100. package/packages/server/src/browse.ts +73 -20
  101. package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
  102. package/packages/server/src/browser-handlers/directory-handler.ts +11 -24
  103. package/packages/server/src/browser-handlers/session-action-handler.ts +158 -62
  104. package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
  105. package/packages/server/src/browser-handlers/subscription-handler.ts +46 -1
  106. package/packages/server/src/build-plugin-send-prompt.ts +18 -0
  107. package/packages/server/src/cli/credentials-command.ts +555 -0
  108. package/packages/server/src/cli.ts +21 -16
  109. package/packages/server/src/config-api.ts +34 -38
  110. package/packages/server/src/config-snapshot.ts +149 -0
  111. package/packages/server/src/directory-service.ts +33 -14
  112. package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
  113. package/packages/server/src/event-wiring.ts +181 -101
  114. package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
  115. package/packages/server/src/git-worktree/git-operations.ts +1 -1
  116. package/packages/server/src/git-worktree/repo-lock.ts +42 -0
  117. package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
  118. package/packages/server/src/git-worktree/worktree-init.ts +5 -1
  119. package/packages/server/src/identity/http-road-classification.ts +5 -1
  120. package/packages/server/src/identity/identity-floor.ts +5 -2
  121. package/packages/server/src/identity/ws-message-scope.ts +10 -3
  122. package/packages/server/src/identity/ws-road-classification.ts +2 -1
  123. package/packages/server/src/lib/browse-roots.ts +13 -2
  124. package/packages/server/src/lib/content-disposition.ts +20 -0
  125. package/packages/server/src/lib/dashboard-state-guard.ts +304 -21
  126. package/packages/server/src/lib/eml.ts +2 -2
  127. package/packages/server/src/lib/frame-policy-probe.ts +308 -0
  128. package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
  129. package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
  130. package/packages/server/src/lib/grep.ts +4 -1
  131. package/packages/server/src/lib/index-html.ts +2 -2
  132. package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
  133. package/packages/server/src/lib/office-preview.ts +47 -10
  134. package/packages/server/src/lib/path-containment.ts +45 -12
  135. package/packages/server/src/lib/resolve-file-mention.ts +230 -38
  136. package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
  137. package/packages/server/src/lib/writable-handler-target.ts +4 -0
  138. package/packages/server/src/lib/writable-md-target.ts +22 -0
  139. package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
  140. package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
  141. package/packages/server/src/lifecycle/exit-signal.ts +43 -0
  142. package/packages/server/src/live-server/capability-redact.ts +21 -5
  143. package/packages/server/src/live-server/live-capability.ts +416 -52
  144. package/packages/server/src/live-server/live-csp-report.ts +1 -1
  145. package/packages/server/src/live-server/live-csp.ts +64 -16
  146. package/packages/server/src/live-server/live-log.ts +5 -1
  147. package/packages/server/src/live-server/live-server-manager.ts +11 -0
  148. package/packages/server/src/live-server/live-server-proxy.ts +268 -52
  149. package/packages/server/src/live-server/live-static.ts +4 -1
  150. package/packages/server/src/live-server/preview-dispatch.ts +286 -0
  151. package/packages/server/src/live-server/preview-observe.ts +53 -0
  152. package/packages/server/src/live-server/preview-origin.ts +182 -0
  153. package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
  154. package/packages/server/src/live-server/preview-path-store.ts +420 -0
  155. package/packages/server/src/live-server/preview-path.ts +40 -0
  156. package/packages/server/src/live-server/preview-pool.ts +385 -0
  157. package/packages/server/src/live-server/preview-preflight.ts +41 -0
  158. package/packages/server/src/live-server/preview-reserve.ts +44 -0
  159. package/packages/server/src/live-server/preview-tier.ts +217 -0
  160. package/packages/server/src/live-server/preview-viewers.ts +54 -0
  161. package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
  162. package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
  163. package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
  164. package/packages/server/src/model-proxy/internal-registry.ts +283 -21
  165. package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
  166. package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
  167. package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
  168. package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
  169. package/packages/server/src/openspec/readiness.ts +1 -1
  170. package/packages/server/src/package/provider-probe.ts +194 -5
  171. package/packages/server/src/pairing/browser-gateway.ts +140 -42
  172. package/packages/server/src/pairing/device-key-intake.ts +120 -0
  173. package/packages/server/src/pairing/paired-devices.ts +370 -8
  174. package/packages/server/src/pairing/pairing.ts +69 -7
  175. package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
  176. package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
  177. package/packages/server/src/pending/pending-attach-registry.ts +15 -0
  178. package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
  179. package/packages/server/src/persistence/memory-event-store.ts +251 -296
  180. package/packages/server/src/persistence/preferences-store.ts +52 -2
  181. package/packages/server/src/pi/bridge-contention.ts +84 -2
  182. package/packages/server/src/pi/host-project-trust.ts +15 -9
  183. package/packages/server/src/pi/pi-gateway.ts +208 -21
  184. package/packages/server/src/pi/provisional-registration.ts +4 -1
  185. package/packages/server/src/pi/resource-toggle-trust.ts +17 -6
  186. package/packages/server/src/pi-agent-settings.ts +95 -301
  187. package/packages/server/src/pi-default-remirror.ts +89 -0
  188. package/packages/server/src/plugin-append-event.ts +35 -0
  189. package/packages/server/src/plugin-entry-stats.ts +61 -0
  190. package/packages/server/src/plugin-local-request.ts +207 -0
  191. package/packages/server/src/plugin-ownership.ts +111 -0
  192. package/packages/server/src/plugin-policy-registry.ts +297 -0
  193. package/packages/server/src/plugin-request-lane.ts +92 -16
  194. package/packages/server/src/preferences-relay.ts +20 -0
  195. package/packages/server/src/project-seed.ts +347 -0
  196. package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
  197. package/packages/server/src/questions/question-store.ts +3 -2
  198. package/packages/server/src/routes/access-routes.ts +23 -6
  199. package/packages/server/src/routes/acme-routes.ts +14 -4
  200. package/packages/server/src/routes/agent-event-stream-routes.ts +1 -1
  201. package/packages/server/src/routes/file-routes.ts +327 -86
  202. package/packages/server/src/routes/file-write-binary-routes.ts +20 -4
  203. package/packages/server/src/routes/frame-policy-routes.ts +215 -0
  204. package/packages/server/src/routes/git-routes.ts +29 -78
  205. package/packages/server/src/routes/grep-routes.ts +26 -0
  206. package/packages/server/src/routes/live-server-routes.ts +198 -4
  207. package/packages/server/src/routes/models-introspection-routes.ts +1 -1
  208. package/packages/server/src/routes/openspec-routes.ts +17 -3
  209. package/packages/server/src/routes/pairing-routes.ts +200 -11
  210. package/packages/server/src/routes/pi-settings-routes.ts +2 -0
  211. package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
  212. package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
  213. package/packages/server/src/routes/provider-auth-routes.ts +167 -9
  214. package/packages/server/src/routes/provider-override-routes.ts +158 -0
  215. package/packages/server/src/routes/provider-routes.ts +348 -86
  216. package/packages/server/src/routes/session-routes.ts +25 -22
  217. package/packages/server/src/routes/system-routes.ts +87 -39
  218. package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
  219. package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
  220. package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
  221. package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
  222. package/packages/server/src/server.ts +512 -175
  223. package/packages/server/src/services/cli-service.ts +59 -10
  224. package/packages/server/src/services/secrets-resolver.ts +46 -30
  225. package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
  226. package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
  227. package/packages/server/src/session/death-reason.ts +11 -7
  228. package/packages/server/src/session/event-status-extraction.ts +5 -1
  229. package/packages/server/src/session/memory-session-manager.ts +24 -2
  230. package/packages/server/src/session/open-tool-calls.ts +81 -47
  231. package/packages/server/src/session/pid-target.ts +127 -0
  232. package/packages/server/src/session/replay-compaction.ts +18 -5
  233. package/packages/server/src/session/seed-discovered-history.ts +85 -0
  234. package/packages/server/src/session/server-pid-context.ts +14 -0
  235. package/packages/server/src/session/session-api.ts +78 -29
  236. package/packages/server/src/session/session-archive.ts +7 -0
  237. package/packages/server/src/session/session-bootstrap.ts +9 -54
  238. package/packages/server/src/session/session-load-worker-pool.ts +11 -1
  239. package/packages/server/src/session/session-load-worker.ts +22 -3
  240. package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
  241. package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
  242. package/packages/server/src/spawn-process/headless-pid-registry.ts +383 -72
  243. package/packages/server/src/spawn-process/link-register.ts +42 -0
  244. package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
  245. package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
  246. package/packages/server/src/spawn-process/process-classifier.ts +8 -3
  247. package/packages/server/src/spawn-process/process-manager.ts +61 -6
  248. package/packages/server/src/spawn-process/restored-identity.ts +112 -0
  249. package/packages/server/src/spawn-process/session-terminator.ts +179 -18
  250. package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
  251. package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
  252. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
  253. package/packages/server/src/sudo-credential/relay.ts +337 -0
  254. package/packages/server/src/terminal/terminal-gateway.ts +10 -0
  255. package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
  256. package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
  257. package/packages/server/src/vault/vault-delivery-hub.ts +17 -1
  258. package/packages/server/src/vault/vault-routes.ts +9 -2
  259. package/packages/server/src/vault/vault-store.ts +87 -24
  260. package/packages/server/vendor/xlsx/LICENSE +201 -0
  261. package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
  262. package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
  263. package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
  264. package/packages/shared/package.json +4 -2
  265. package/packages/shared/src/agent-credential-files.ts +32 -0
  266. package/packages/shared/src/browser-protocol.ts +137 -57
  267. package/packages/shared/src/canvas-detect.ts +1 -1
  268. package/packages/shared/src/canvas-types.ts +2 -2
  269. package/packages/shared/src/config.ts +73 -136
  270. package/packages/shared/src/containment-guard.ts +14 -4
  271. package/packages/shared/src/credential-encryption.ts +87 -0
  272. package/packages/shared/src/custom-event-groups.ts +2 -0
  273. package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
  274. package/packages/shared/src/dashboard-plugin/host-api.ts +1 -1
  275. package/packages/shared/src/dashboard-plugin/manifest-types.ts +46 -0
  276. package/packages/shared/src/dashboard-plugin/plugin-status.ts +4 -3
  277. package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
  278. package/packages/shared/src/dashboard-plugin/slot-props.ts +2 -0
  279. package/packages/shared/src/dashboard-plugin/slot-types.ts +1 -1
  280. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +11 -3
  281. package/packages/shared/src/device-key-proof.ts +309 -0
  282. package/packages/shared/src/event-forward-declaration.ts +85 -12
  283. package/packages/shared/src/forbidden-subjects.ts +126 -14
  284. package/packages/shared/src/heap-limits.ts +0 -30
  285. package/packages/shared/src/host-admission.ts +2 -1
  286. package/packages/shared/src/index.ts +7 -6
  287. package/packages/shared/src/live-server.ts +20 -0
  288. package/packages/shared/src/mcp/verb-tiers.generated.ts +1 -3
  289. package/packages/shared/src/models-json-reader.ts +41 -0
  290. package/packages/shared/src/network-denial-signal.ts +15 -0
  291. package/packages/shared/src/node-version.ts +63 -60
  292. package/packages/shared/src/pairing-knock-client.ts +92 -8
  293. package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
  294. package/packages/shared/src/pi-path-compare.ts +31 -0
  295. package/packages/shared/src/pi-settings-schema.ts +52 -9
  296. package/packages/shared/src/pi-trust-mirror-snapshot.ts +16 -4
  297. package/packages/shared/src/pi-trust-mirror-types.ts +2 -0
  298. package/packages/shared/src/pi-trust-mirror.ts +18 -8
  299. package/packages/shared/src/pi-trust-resource-digest.ts +18 -12
  300. package/packages/shared/src/pid-namespace.ts +86 -0
  301. package/packages/shared/src/platform/native-ts-register.mjs +1 -1
  302. package/packages/shared/src/platform/process.ts +404 -1
  303. package/packages/shared/src/platform/resolve-pi-shell.ts +38 -9
  304. package/packages/shared/src/platform/spawn-runtime.ts +193 -7
  305. package/packages/shared/src/preview-egress.ts +56 -2
  306. package/packages/shared/src/preview-origins.ts +398 -0
  307. package/packages/shared/src/prompt-answer.ts +9 -5
  308. package/packages/shared/src/protocol.ts +147 -85
  309. package/packages/shared/src/provider-env-catalog.ts +413 -0
  310. package/packages/shared/src/provider-overrides.ts +112 -0
  311. package/packages/shared/src/question-types.ts +6 -0
  312. package/packages/shared/src/recommended-extensions.ts +79 -26
  313. package/packages/shared/src/renderer-by-ext.ts +5 -2
  314. package/packages/shared/src/rest-api.ts +93 -3
  315. package/packages/shared/src/role-schema.ts +24 -0
  316. package/packages/shared/src/route-tiers.ts +94 -3
  317. package/packages/shared/src/runtime-overlay/compat.ts +70 -6
  318. package/packages/shared/src/secret-patterns.ts +49 -0
  319. package/packages/shared/src/source-matching.ts +2 -2
  320. package/packages/shared/src/state-replay.ts +40 -24
  321. package/packages/shared/src/sudo-credential.ts +71 -0
  322. package/packages/shared/src/tool-path-resolve.ts +16 -1
  323. package/packages/shared/src/tool-registry/strategies.ts +1 -1
  324. package/packages/shared/src/tool-workdir.ts +56 -0
  325. package/packages/shared/src/trusted-types-mode.ts +72 -0
  326. package/packages/shared/src/types.ts +68 -109
  327. package/packages/shared/src/vertex-regions.ts +81 -0
  328. package/packages/shared/src/ws-message-tiers.ts +10 -3
  329. package/packages/extension/src/subagent-fanout-admission.ts +0 -234
  330. package/packages/extension/src/subagent-forward-sites.ts +0 -69
  331. package/packages/extension/src/subagent-frame-buffer.ts +0 -245
  332. package/packages/extension/src/subagent-frame-strip.ts +0 -109
  333. package/packages/extension/src/subagent-saturation.ts +0 -196
  334. package/packages/extension/src/subagent-tick-throttle.ts +0 -252
  335. package/packages/shared/src/anthropic-messages-source.ts +0 -8
  336. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +0 -9
  337. package/packages/shared/src/dashboard-plugin/subagent-types.ts +0 -219
@@ -34,6 +34,7 @@ import {
34
34
  } from "../access/verified-read.js";
35
35
  import type { LocalTrustContext } from "../auth/local-proof.js";
36
36
  import { canDiscloseAccessPosture, isLocallyTrusted } from "../auth/localhost-guard.js";
37
+ import { requestPrincipalKey } from "../auth/request-principal.js";
37
38
  import {
38
39
  CreateProjectError,
39
40
  type CreateProjectReason,
@@ -52,7 +53,8 @@ import {
52
53
  isWithinBrowseRoots,
53
54
  resolveBrowseRoots,
54
55
  } from "../lib/browse-roots.js";
55
- import { DashboardStateRefused, openStateChecked, readFileStateChecked } from "../lib/dashboard-state-guard.js";
56
+ import { contentDispositionAttachment } from "../lib/content-disposition.js";
57
+ import { ContainmentBindingRefused, DashboardStateRefused, openStateChecked, readFileStateChecked } from "../lib/dashboard-state-guard.js";
56
58
  import { decodeFileUri } from "../lib/decode-file-uri.js";
57
59
  import { renderDiagram } from "../lib/diagram-render.js";
58
60
  import { createDigestGate, type DigestGate, type DigestLane } from "../lib/digest-gate.js";
@@ -61,6 +63,7 @@ import { admitFileCwd, CWD_UNAVAILABLE_FAILURE, cwdAnchors, type GateWire, relea
61
63
  import { enumerateMdCandidates } from "../lib/md-candidates.js";
62
64
  import { extToContentType } from "../lib/mime-types.js";
63
65
  import {
66
+ convertBound,
64
67
  createDefaultDocxPdfEngine,
65
68
  type DocxPdfEngine,
66
69
  type DocxRenderMode,
@@ -119,8 +122,21 @@ export function sendGateFailure(reply: import("fastify").FastifyReply, gate: Gat
119
122
  }
120
123
 
121
124
  import { serializeWrite } from "../lib/file-write-lock.js";
122
- import { resolveFileMention } from "../lib/resolve-file-mention.js";
123
- import { isWritableMdTarget } from "../lib/writable-md-target.js";
125
+ import { getMentionFuzzyIndex, type MentionFuzzyIndex } from "../lib/mention-fuzzy-index.js";
126
+ import { type ContainmentMemo, resolveMentionTagged } from "../lib/resolve-file-mention.js";
127
+ import {
128
+ BATCH_BODY_LIMIT_BYTES,
129
+ BATCH_CONCURRENCY,
130
+ BATCH_RATE_PER_MINUTE,
131
+ type BatchResult,
132
+ createWindowLimiter,
133
+ formatBatchLog,
134
+ MAX_FIELD_CHARS,
135
+ mapConcurrent,
136
+ parseBatchBody,
137
+ toBatchResult,
138
+ } from "../lib/resolve-mentions-batch.js";
139
+ import { isTextDocWriteTarget, isWritableMdTarget } from "../lib/writable-md-target.js";
124
140
  import type { PreferencesStore } from "../persistence/preferences-store.js";
125
141
  import type { SessionManager } from "../session/memory-session-manager.js";
126
142
  import {
@@ -225,14 +241,29 @@ type MdWriteOutcome =
225
241
  | { code: 404 | 409 | 413 | 500; error: string };
226
242
 
227
243
  /** Parsed + authorized write request, or a {code,error} reply mapping. */
228
- type MdWritePrep = { resolved: string; content: string; mtime: number } | GateFailure;
244
+ type MdWritePrep =
245
+ | {
246
+ resolved: string;
247
+ content: string;
248
+ mtime: number;
249
+ /** Set when a write-mode GRANT admitted an outside-cwd target: the real path the gate decided. */
250
+ gatedReal?: string;
251
+ }
252
+ | GateFailure;
229
253
 
230
254
  // Parse, scope-validate, and authorize a `POST /api/file/write` body. Keeps the
231
255
  // route handler trivial. Authorization is the `isWritableMdTarget` security
232
256
  // boundary. See change: directory-settings-page-and-scoped-md-editing.
257
+ //
258
+ // A text doc OUTSIDE the admitted cwd (directory scope only) is not a flat 403 any more: it goes to the
259
+ // write-mode containment gate (`evaluateContainment(..., {action:"write"})`), which admits it only through
260
+ // a WRITE grant or a fresh operator write prompt (allow once / always / deny). A read grant and the
261
+ // bound-checkout-root widening never admit a write. Global scope (no cwd) is unchanged.
262
+ // See change: fix-file-link-editor-routing (D2).
233
263
  async function prepareMdWrite(
234
264
  body: { cwd?: unknown; path?: unknown; content?: unknown; mtime?: unknown },
235
265
  routeAdmission: RouteAdmissionDeps,
266
+ req: { request: import("fastify").FastifyRequest; reply: import("fastify").FastifyReply },
236
267
  ): Promise<MdWritePrep> {
237
268
  const rawPath = typeof body.path === "string" ? body.path : "";
238
269
  const content = typeof body.content === "string" ? body.content : undefined;
@@ -242,10 +273,30 @@ async function prepareMdWrite(
242
273
  }
243
274
  const target = await resolveScopedMdPath(body.cwd, rawPath, routeAdmission);
244
275
  if ("code" in target) return target;
245
- if (!(await isWritableMdTarget(target.resolved, { cwd: target.cwd }))) {
276
+ if (await isWritableMdTarget(target.resolved, { cwd: target.cwd })) {
277
+ return { resolved: target.resolved, content, mtime };
278
+ }
279
+ // Only the outside-cwd text-doc case reaches the gate: global scope, a non-text extension, a Mermaid
280
+ // source and a dashboard-state path all stay a plain 403 with no prompt.
281
+ if (target.cwd === undefined || !(await isTextDocWriteTarget(target.resolved))) {
246
282
  return { code: 403, error: "target is not a writable markdown file in scope" };
247
283
  }
248
- return { resolved: target.resolved, content, mtime };
284
+ // The gate runs BEFORE any stat (`performAtomicMdWrite`): a stat-first route would be an existence
285
+ // oracle for arbitrary outside paths.
286
+ const decision = await evaluateContainment(target.resolved, [target.cwd], {
287
+ site: "file-routes:write",
288
+ subjectKind: "file",
289
+ session: target.cwd,
290
+ hold: { request: req.request, reply: req.reply },
291
+ disclosure: canDiscloseAccessPosture(req.request),
292
+ action: "write",
293
+ });
294
+ // Only a GRANT-admitted decision proceeds: layer ① admitting a path `isWritableMdTarget` just refused
295
+ // would be a contradiction, so it fails closed.
296
+ if (!containmentAllows(decision, target.resolved) || !decision.viaGrant) {
297
+ return { code: 403, error: "path outside working directory — write not granted", ...decision.remedy };
298
+ }
299
+ return { resolved: target.resolved, content, mtime, gatedReal: decision.real };
249
300
  }
250
301
 
251
302
  // Atomic markdown write with optimistic-concurrency. Caller MUST run this inside
@@ -257,6 +308,7 @@ async function performAtomicMdWrite(
257
308
  resolved: string,
258
309
  content: string,
259
310
  mtime: number,
311
+ gatedReal?: string,
260
312
  ): Promise<MdWriteOutcome> {
261
313
  // Canonicalize to the realpath target: an in-scope symlink to an allowed
262
314
  // markdown file is authorized by `isWritableMdTarget` on its realpath, so we
@@ -270,6 +322,11 @@ async function performAtomicMdWrite(
270
322
  } catch {
271
323
  return { code: 404, error: "file not found" };
272
324
  }
325
+ // Re-bind: a target admitted by a write grant must still resolve to the path the gate decided. A symlink
326
+ // repointed during the operator hold (or after the gate) is refused with nothing written.
327
+ if (gatedReal !== undefined && real !== gatedReal) {
328
+ return { code: 409, error: "target changed while access was being decided" };
329
+ }
273
330
  // Full-precision mtime token: rounding could collapse two fast saves into one
274
331
  // token and let a stale write pass the 409 check.
275
332
  if (current.mtimeMs !== mtime) {
@@ -383,7 +440,7 @@ export async function gateFilePath(
383
440
  * `quiet`: record no denial and raise no prompt (a per-request re-check on a static preview).
384
441
  */
385
442
  opts: { allowGrant?: boolean; disclosure?: boolean; quiet?: boolean } = {},
386
- ): Promise<{ resolved: string; viaGrant: boolean } | GateFailure> {
443
+ ): Promise<{ resolved: string; real: string; viaGrant: boolean } | GateFailure> {
387
444
  if (!cwd || !relPath) return { code: 400, error: "cwd and path parameters required" };
388
445
  const admitted = await admitFileCwd(cwd, routeAdmission);
389
446
  if (!admitted.ok) return admitted.failure;
@@ -408,7 +465,7 @@ export async function gateFilePath(
408
465
  // `lstat` and therefore refuse an in-scope final-component SYMLINK that
409
466
  // layers ①/② admit. Dropping it turned "apply only on a grant" into
410
467
  // "apply always".
411
- return { resolved, viaGrant: decision.viaGrant };
468
+ return { resolved, real: decision.real, viaGrant: decision.viaGrant };
412
469
  }
413
470
 
414
471
  /**
@@ -429,7 +486,7 @@ async function gateReadPath(
429
486
  reply: import("fastify").FastifyReply;
430
487
  quiet?: boolean;
431
488
  },
432
- ): Promise<{ resolved: string; viaGrant: boolean; relPath: string } | GateFailure> {
489
+ ): Promise<{ resolved: string; real: string; viaGrant: boolean; relPath: string } | GateFailure> {
433
490
  const relPath = rawPath ? decodeFileUri(rawPath) : rawPath;
434
491
  if (!cwd || !relPath) return { code: 400, error: "cwd and path parameters required" };
435
492
  const admitted = await admitFileCwd(cwd, req.routeAdmission);
@@ -455,7 +512,7 @@ async function gateReadPath(
455
512
  if (!containmentAllows(readDecision, resolved)) {
456
513
  return { code: 403, error: "path outside working directory", ...readDecision.remedy };
457
514
  }
458
- return { resolved, viaGrant: readDecision.viaGrant, relPath };
515
+ return { resolved, real: readDecision.real, viaGrant: readDecision.viaGrant, relPath };
459
516
  }
460
517
 
461
518
  const CREATE_PROJECT_STATUS: Record<CreateProjectReason, number> = {
@@ -508,9 +565,12 @@ export function registerFileRoutes(
508
565
  * the known set of this registrar's own `sessionManager` + `preferencesStore`.
509
566
  */
510
567
  routeAdmission?: RouteAdmissionDeps;
568
+ /** Tracked-file index behind mention recovery (change: rich-chat-links). Absent → the process-wide index. */
569
+ mentionFuzzyIndex?: MentionFuzzyIndex;
511
570
  },
512
571
  ) {
513
572
  const { sessionManager, preferencesStore, networkGuard } = deps;
573
+ const mentionIndex = deps.mentionFuzzyIndex ?? getMentionFuzzyIndex();
514
574
  const routeAdmission: RouteAdmissionDeps = {
515
575
  ...deps.routeAdmission,
516
576
  knownCwds: deps.routeAdmission?.knownCwds ?? (() => listKnownFolderCwds({ sessionManager, preferencesStore })),
@@ -536,7 +596,7 @@ export function registerFileRoutes(
536
596
  /** The caller may see `promptOutcome` (`canDiscloseAccessPosture`). */
537
597
  disclosure: boolean,
538
598
  ): Promise<
539
- | { resolved: string; ext: string; stat: import("node:fs").Stats; viaGrant: boolean }
599
+ | { resolved: string; real: string; ext: string; stat: import("node:fs").Stats; viaGrant: boolean }
540
600
  | GateFailure
541
601
  > {
542
602
  if (!cwd || !relPath) return { code: 400, error: "cwd and path parameters required" };
@@ -580,7 +640,7 @@ export function registerFileRoutes(
580
640
  throw err;
581
641
  }
582
642
  }
583
- return { resolved, ext, stat, viaGrant: decision.viaGrant };
643
+ return { resolved, real: decision.real, ext, stat, viaGrant: decision.viaGrant };
584
644
  }
585
645
 
586
646
  // Browse confinement applies ONLY to requests that are not genuinely local
@@ -612,7 +672,7 @@ export function registerFileRoutes(
612
672
  // Without `detect`, this is a single-readdir enumeration with no filesystem
613
673
  // probes — use `GET /api/browse/flags` to classify lazily.
614
674
  // See change: split-browse-flags.
615
- fastify.get<{ Querystring: { path?: string; q?: string; detect?: string } }>(
675
+ fastify.get<{ Querystring: { path?: string; q?: string; detect?: string; files?: string; hidden?: string; ext?: string } }>(
616
676
  "/api/browse",
617
677
  { preHandler: networkGuard },
618
678
  async (request, reply) => {
@@ -625,7 +685,14 @@ export function registerFileRoutes(
625
685
  const result = await listDirectories(
626
686
  requested,
627
687
  request.query.q || undefined,
628
- { detect: request.query.detect === "1" },
688
+ {
689
+ detect: request.query.detect === "1",
690
+ files: request.query.files === "1",
691
+ hidden: request.query.hidden === "1",
692
+ ext: request.query.ext || undefined,
693
+ // Independent of confinement: `browseConfineRemote=false` must not expose credential dirs.
694
+ excludeForbidden: !isLocallyTrusted({ ip: request.ip, headers: request.headers }, deps.localTrust),
695
+ },
629
696
  );
630
697
  if (roots) {
631
698
  result.confined = true;
@@ -753,18 +820,23 @@ export function registerFileRoutes(
753
820
  // two syscalls, so without it the path could be swapped for a symlink or
754
821
  // a FIFO in the gap. Layer ①/② reads keep the pre-existing open.
755
822
  const fh = gate.viaGrant
756
- ? await openVerifiedRegularFile(resolved)
757
- : await openStateChecked(resolved, "r");
823
+ ? await openVerifiedRegularFile(gate.real, { decidedReal: gate.real })
824
+ : await openStateChecked(gate.real, "r", { decidedReal: gate.real });
758
825
  let kindResult;
759
826
  let content: string | undefined;
827
+ // size/mtime come from the SAME checked handle as the content, so a link retargeted after the
828
+ // decision can never pair A's bytes with B's mtime (the editor's optimistic-concurrency token).
829
+ let handleStat: import("node:fs").Stats;
760
830
  try {
761
- const sniffLen = Math.min(1024, stat.size);
831
+ handleStat = await fh.stat();
832
+ const sniffLen = Math.min(1024, handleStat.size);
762
833
  const sniff = Buffer.alloc(sniffLen);
763
834
  if (sniffLen > 0) await fh.read(sniff, 0, sniffLen, 0);
764
835
  kindResult = fileKind(resolved, sniff);
765
836
  if (
766
837
  kindResult.viewer === "monaco" ||
767
838
  kindResult.viewer === "markdown" ||
839
+ kindResult.kind === "html" || // read-only Source tab (rich-chat-links)
768
840
  kindResult.editable === true
769
841
  ) {
770
842
  content = await fh.readFile("utf-8");
@@ -778,13 +850,13 @@ export function registerFileRoutes(
778
850
  type: "file",
779
851
  kind: kindResult.kind,
780
852
  mimeType: kindResult.mimeType,
781
- size: stat.size,
853
+ size: handleStat.size,
782
854
  // mtime drives the editor's optimistic-concurrency check on write.
783
855
  // Full precision: `/api/file/write` compares against raw `mtimeMs`,
784
856
  // so a rounded token 409s on every save on sub-ms filesystems.
785
857
  // See change: directory-settings-page-and-scoped-md-editing,
786
858
  // fix-editor-mtime-token-precision.
787
- mtime: stat.mtimeMs,
859
+ mtime: handleStat.mtimeMs,
788
860
  ...(content !== undefined ? { content } : {}),
789
861
  },
790
862
  } satisfies ApiResponse;
@@ -835,8 +907,8 @@ export function registerFileRoutes(
835
907
  try {
836
908
  release = await digestGate.acquire(lane, ac.signal);
837
909
  const fh = gate.viaGrant
838
- ? await openVerifiedRegularFile(gate.resolved)
839
- : await fs.open(gate.resolved, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0));
910
+ ? await openVerifiedRegularFile(gate.real, { decidedReal: gate.real })
911
+ : await openStateChecked(gate.real, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0), { decidedReal: gate.real });
840
912
  try {
841
913
  const stat = await fh.stat();
842
914
  if (!stat.isFile()) {
@@ -853,7 +925,7 @@ export function registerFileRoutes(
853
925
  await fh.close();
854
926
  }
855
927
  } catch (err) {
856
- if (err instanceof VerifiedReadRefused) {
928
+ if (err instanceof VerifiedReadRefused || err instanceof DashboardStateRefused) {
857
929
  reply.code(403);
858
930
  return { success: false, error: "path outside working directory" } satisfies ApiResponse;
859
931
  }
@@ -917,7 +989,7 @@ export function registerFileRoutes(
917
989
  if ("code" in gate) {
918
990
  return sendGateFailure(reply, gate);
919
991
  }
920
- const { cmd, args } = build(systemOpenPlatform, gate.resolved);
992
+ const { cmd, args } = build(systemOpenPlatform, gate.real);
921
993
  systemOpenRun(cmd, args);
922
994
  return { success: true, data: { spawned: true } };
923
995
  };
@@ -1020,7 +1092,7 @@ export function registerFileRoutes(
1020
1092
  // the handler still refuses content above the 256 MiB ceiling.
1021
1093
  { preHandler: networkGuard, bodyLimit: 600 * 1024 * 1024 },
1022
1094
  async (request, reply) => {
1023
- const prep = await prepareMdWrite(request.body ?? {}, routeAdmission);
1095
+ const prep = await prepareMdWrite(request.body ?? {}, routeAdmission, { request, reply });
1024
1096
  if ("code" in prep) {
1025
1097
  return sendGateFailure(reply, prep);
1026
1098
  }
@@ -1030,7 +1102,7 @@ export function registerFileRoutes(
1030
1102
  // cannot run two writes to one file at once. See change: add-editor-pane-file-handlers (D4).
1031
1103
  const lockKey = await safeRealpath(prep.resolved);
1032
1104
  const outcome = await serializeWrite(lockKey, () =>
1033
- performAtomicMdWrite(prep.resolved, prep.content, prep.mtime),
1105
+ performAtomicMdWrite(prep.resolved, prep.content, prep.mtime, prep.gatedReal),
1034
1106
  );
1035
1107
  if (outcome.code !== 200) {
1036
1108
  reply.code(outcome.code);
@@ -1093,14 +1165,27 @@ export function registerFileRoutes(
1093
1165
  return { success: false, error: "target is not a readable markdown file in scope" } satisfies ApiResponse;
1094
1166
  }
1095
1167
  try {
1096
- const stat = await fs.stat(resolved);
1097
- const content = await fs.readFile(resolved, "utf-8");
1168
+ // One checked handle for both the bytes and the mtime token, so they describe the same file
1169
+ // even under a swap (and the credential recheck covers the opened inode).
1170
+ const fh = await openStateChecked(resolved, "r");
1171
+ let content: string;
1172
+ let mtimeMs: number;
1173
+ try {
1174
+ content = await fh.readFile("utf-8");
1175
+ mtimeMs = (await fh.stat()).mtimeMs;
1176
+ } finally {
1177
+ await fh.close().catch(() => undefined);
1178
+ }
1098
1179
  // Full-precision mtime token (matches the write-side conflict check).
1099
1180
  return {
1100
1181
  success: true,
1101
- data: { content, mtime: stat.mtimeMs },
1182
+ data: { content, mtime: mtimeMs },
1102
1183
  } satisfies ApiResponse;
1103
- } catch {
1184
+ } catch (err) {
1185
+ if (err instanceof DashboardStateRefused) {
1186
+ reply.code(403);
1187
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1188
+ }
1104
1189
  reply.code(404);
1105
1190
  return { success: false, error: "not found" } satisfies ApiResponse;
1106
1191
  }
@@ -1194,14 +1279,21 @@ export function registerFileRoutes(
1194
1279
 
1195
1280
  // Lazy file-mention resolver (change: server-side-file-mention-resolution).
1196
1281
  //
1197
- // Body `{ cwd, mention }` → `{ resolved, kind }` or `{ resolved: null }`.
1282
+ // Body `{ cwd, mention }` → `{ resolved, kind }`, `{ resolved, kind, outside: true }` (containment
1283
+ // failed: never statted, so the payload is independent of existence — change fix-file-link-editor-routing
1284
+ // D1) or `{ resolved: null }`.
1198
1285
  // `cwd` is UNTRUSTED request input and is gated against the known-session set
1199
1286
  // (mirrors `/api/file`, NOT the wider exists-only pinned set — design D2/F6/F7,
1200
1287
  // so a resolve never succeeds on a path the open route would 403) BEFORE any
1201
1288
  // resolution. `resolveFileMention` then expands `~/`, runs containment
1202
1289
  // (cwd + git-root + `~/.pi`) BEFORE `fs.stat`, and returns null for a
1203
1290
  // non-existent in-scope mention (never an error).
1204
- fastify.post<{ Body: { cwd?: unknown; mention?: unknown } }>(
1291
+ //
1292
+ // Opt-in recovery (change: rich-chat-links, design D3): `recover: true` (literal boolean) enables the producing
1293
+ // tool's directory (`toolCwd`, a string ≤ 1024 chars) and the tracked-file fuzzy fallback; without it the answer
1294
+ // is exactly the exact-only lookup. Every answer carries `state` (found | recovered | ambiguous | missing | gated);
1295
+ // recovery adds `via`, ambiguity adds `candidates` (and `resolved: null`).
1296
+ fastify.post<{ Body: { cwd?: unknown; mention?: unknown; recover?: unknown; toolCwd?: unknown } }>(
1205
1297
  "/api/file/resolve-mention",
1206
1298
  { preHandler: networkGuard },
1207
1299
  async (request, reply) => {
@@ -1212,13 +1304,98 @@ export function registerFileRoutes(
1212
1304
  reply.code(400);
1213
1305
  return { success: false, error: "cwd and mention are required" } satisfies ApiResponse;
1214
1306
  }
1307
+ const toolCwd = typeof body.toolCwd === "string" && body.toolCwd !== "" ? body.toolCwd : undefined;
1308
+ if (toolCwd !== undefined && toolCwd.length > MAX_FIELD_CHARS) {
1309
+ reply.code(400);
1310
+ return { success: false, error: `toolCwd exceeds ${MAX_FIELD_CHARS} characters` } satisfies ApiResponse;
1311
+ }
1215
1312
  const admitted = await admitFileCwd(cwd, routeAdmission, { reply });
1216
1313
  if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
1217
- const result = await resolveFileMention(mention, { cwd: admitted.cwd, canonCwd: admitted.canonCwd });
1218
- return {
1219
- success: true,
1220
- data: result ? { resolved: result.resolved, kind: result.kind } : { resolved: null },
1221
- } satisfies ApiResponse;
1314
+ const result = await resolveMentionTagged(mention, {
1315
+ cwd: admitted.cwd,
1316
+ canonCwd: admitted.canonCwd,
1317
+ recover: body.recover === true,
1318
+ toolCwd,
1319
+ fuzzyIndex: mentionIndex,
1320
+ });
1321
+ return { success: true, data: result } satisfies ApiResponse;
1322
+ },
1323
+ );
1324
+
1325
+ // Batch mention resolver (change: rich-chat-links, design D3/D14). Body `{ cwd, items: [{ mention, toolCwd?,
1326
+ // reRooted? }] }` → `{ results }` in request order. Always recovers. Same network guard, tier (`observe`) and
1327
+ // `cwd` admission as the single route, and admission runs BEFORE any resolution. Bounds: 512 KB body (413),
1328
+ // any string field > 1024 chars (400, decided before any filesystem access), 200 resolved items per request
1329
+ // (the rest `unknown`), 60 requests/min per principal (429). `gated` items carry only their state.
1330
+ const batchLimiter = createWindowLimiter(BATCH_RATE_PER_MINUTE);
1331
+ fastify.post(
1332
+ "/api/file/resolve-mentions",
1333
+ { preHandler: networkGuard, bodyLimit: BATCH_BODY_LIMIT_BYTES },
1334
+ async (request, reply) => {
1335
+ const started = performance.now();
1336
+ const principal = requestPrincipalKey(request);
1337
+ // Without a real principal every local caller would share one bucket anyway; key by address.
1338
+ if (!batchLimiter.take(principal === "local-operator" ? `${principal}@${request.ip}` : principal)) {
1339
+ reply.code(429);
1340
+ return { success: false, error: "rate limited" } satisfies ApiResponse;
1341
+ }
1342
+ const parsed = parseBatchBody(request.body);
1343
+ if (!parsed.ok) {
1344
+ reply.code(400);
1345
+ return { success: false, error: parsed.error } satisfies ApiResponse;
1346
+ }
1347
+ const admitted = await admitFileCwd(parsed.cwd, routeAdmission, { reply });
1348
+ if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
1349
+
1350
+ const counters = { stats: 0 };
1351
+ const containmentMemo: ContainmentMemo = new Map();
1352
+ const fuzzy = { hit: 0, miss: 0, skipped: 0, buildMs: 0 };
1353
+ const fuzzyIndex: MentionFuzzyIndex = {
1354
+ clear: () => mentionIndex.clear(),
1355
+ lookup: async (c, m) => {
1356
+ const r = await mentionIndex.lookup(c, m);
1357
+ if (r.status === "skipped") fuzzy.skipped++;
1358
+ else {
1359
+ if (r.cached) fuzzy.hit++;
1360
+ else {
1361
+ fuzzy.miss++;
1362
+ fuzzy.buildMs = Math.max(fuzzy.buildMs, r.buildMs ?? 0);
1363
+ }
1364
+ }
1365
+ return r;
1366
+ },
1367
+ };
1368
+ const resolved = await mapConcurrent(parsed.items, BATCH_CONCURRENCY, async (item): Promise<BatchResult> =>
1369
+ toBatchResult(
1370
+ await resolveMentionTagged(item.mention, {
1371
+ cwd: admitted.cwd,
1372
+ canonCwd: admitted.canonCwd,
1373
+ recover: true,
1374
+ toolCwd: item.toolCwd,
1375
+ reRooted: item.reRooted,
1376
+ fuzzyIndex,
1377
+ counters,
1378
+ containmentMemo,
1379
+ }),
1380
+ ),
1381
+ );
1382
+ // Items past the cap are never materialised: one shared `unknown`, same order and length as the request.
1383
+ const overflow = parsed.total - parsed.items.length;
1384
+ const results: BatchResult[] = overflow > 0 ? resolved.concat(new Array<BatchResult>(overflow).fill({ state: "unknown" })) : resolved;
1385
+ const counts: Partial<Record<BatchResult["state"], number>> = {};
1386
+ for (const r of resolved) counts[r.state] = (counts[r.state] ?? 0) + 1;
1387
+ if (overflow > 0) counts.unknown = overflow;
1388
+ console.log(
1389
+ formatBatchLog({
1390
+ cwd: admitted.cwd,
1391
+ items: parsed.total,
1392
+ counts,
1393
+ fuzzy,
1394
+ stats: counters.stats,
1395
+ totalMs: performance.now() - started,
1396
+ }),
1397
+ );
1398
+ return { success: true, data: { results } } satisfies ApiResponse;
1222
1399
  },
1223
1400
  );
1224
1401
 
@@ -1237,8 +1414,9 @@ export function registerFileRoutes(
1237
1414
  // Streams the file bytes with `Content-Type` from extension, supports
1238
1415
  // HTTP Range so `<video>` seek works. Same cwd-allowlist + anti-traversal
1239
1416
  // gate as `/api/file`. Sets `Content-Disposition: inline` and a short
1240
- // private cache.
1241
- fastify.get<{ Querystring: { cwd?: string; path?: string } }>(
1417
+ // private cache. `download=1` switches to an attachment disposition
1418
+ // (change: add-file-download); nothing else about the route changes.
1419
+ fastify.get<{ Querystring: { cwd?: string; path?: string; download?: string } }>(
1242
1420
  "/api/file/raw",
1243
1421
  { preHandler: networkGuard },
1244
1422
  async (request, reply) => {
@@ -1264,7 +1442,13 @@ export function registerFileRoutes(
1264
1442
  // True only when the GRANT layer admitted this read — layers ①/② and the
1265
1443
  // artifact root do NOT get handle verification (task 2.8 scope).
1266
1444
  let viaGrant = false;
1267
- if (!containmentAllows(await decidePassive(resolved, rawAnchors, { allowGrant: false }), resolved)) {
1445
+ // The real path the admitting decision was made on; the open below is bound to it.
1446
+ // An artifact-root image carries no decision (real-path contained by its own check) → opens `resolved`.
1447
+ let decidedReal: string | undefined;
1448
+ const passiveDecision = await decidePassive(resolved, rawAnchors, { allowGrant: false });
1449
+ if (containmentAllows(passiveDecision, resolved)) {
1450
+ decidedReal = passiveDecision.real;
1451
+ } else {
1268
1452
  if (!(await isImageUnderArtifactRoot(resolved))) {
1269
1453
  const rawDecision = await evaluateContainment(resolved, rawAnchors, {
1270
1454
  site: "file-routes:raw",
@@ -1277,6 +1461,7 @@ export function registerFileRoutes(
1277
1461
  return { success: false, error: "path outside working directory", ...rawDecision.remedy } as unknown as ApiResponse;
1278
1462
  }
1279
1463
  viaGrant = rawDecision.viaGrant;
1464
+ decidedReal = rawDecision.real;
1280
1465
  }
1281
1466
  }
1282
1467
 
@@ -1299,7 +1484,10 @@ export function registerFileRoutes(
1299
1484
  const size = stat.size;
1300
1485
 
1301
1486
  reply.header("Content-Type", contentType);
1302
- reply.header("Content-Disposition", "inline");
1487
+ reply.header(
1488
+ "Content-Disposition",
1489
+ request.query.download === "1" ? contentDispositionAttachment(path.basename(resolved)) : "inline",
1490
+ );
1303
1491
  // Scriptable media types (SVG/HTML/XML) opened directly would run with the
1304
1492
  // dashboard origin. Enforce an opaque-origin sandbox in EVERY dashboard CSP
1305
1493
  // mode, on 200/206/416 and every admission path. The baseline CSP hook
@@ -1362,17 +1550,24 @@ export function registerFileRoutes(
1362
1550
 
1363
1551
  // A grant-admitted read additionally binds the bytes served to the inode
1364
1552
  // that was checked (design D14, task 2.8).
1553
+ // The media headers were set above; an open-time refusal answers JSON, so reset them (a JSON body under
1554
+ // the file's own content type is a 500) and keep the refusal out of caches.
1555
+ const openRefusal = (code: number, error: string): ApiResponse => {
1556
+ reply.code(code);
1557
+ reply.type("application/json; charset=utf-8");
1558
+ reply.header("Cache-Control", "no-store");
1559
+ reply.removeHeader("Accept-Ranges");
1560
+ reply.removeHeader("Content-Security-Policy");
1561
+ reply.removeHeader("Content-Disposition"); // `download=1` must not save the JSON refusal as the file
1562
+ return { success: false, error };
1563
+ };
1365
1564
  let grantedHandle: Awaited<ReturnType<typeof openVerifiedRegularFile>> | undefined;
1366
1565
  if (viaGrant) {
1367
1566
  try {
1368
- grantedHandle = await openVerifiedRegularFile(resolved);
1567
+ grantedHandle = await openVerifiedRegularFile(decidedReal ?? resolved, decidedReal ? { decidedReal } : {});
1369
1568
  } catch (err) {
1370
- if (err instanceof VerifiedReadRefused) {
1371
- reply.code(403);
1372
- return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1373
- }
1374
- reply.code(404);
1375
- return { success: false, error: "not found" } satisfies ApiResponse;
1569
+ if (err instanceof VerifiedReadRefused) return openRefusal(403, "path outside working directory");
1570
+ return openRefusal(404, "not found");
1376
1571
  }
1377
1572
  }
1378
1573
 
@@ -1381,13 +1576,11 @@ export function registerFileRoutes(
1381
1576
  let rawHandle: Awaited<ReturnType<typeof openStateChecked>> | undefined;
1382
1577
  if (!grantedHandle) {
1383
1578
  try {
1384
- rawHandle = await openStateChecked(resolved, "r");
1579
+ rawHandle = await openStateChecked(decidedReal ?? resolved, "r", decidedReal ? { decidedReal } : {});
1385
1580
  } catch (err) {
1386
- reply.code(err instanceof DashboardStateRefused ? 403 : 404);
1387
- return {
1388
- success: false,
1389
- error: err instanceof DashboardStateRefused ? "path outside working directory" : "not found",
1390
- } satisfies ApiResponse;
1581
+ return err instanceof DashboardStateRefused
1582
+ ? openRefusal(403, "path outside working directory")
1583
+ : openRefusal(404, "not found");
1391
1584
  }
1392
1585
  }
1393
1586
  const servedHandle = grantedHandle ?? rawHandle!;
@@ -1447,11 +1640,20 @@ export function registerFileRoutes(
1447
1640
  if ("code" in gate) {
1448
1641
  return sendGateFailure(reply, gate);
1449
1642
  }
1450
- const result = await renderPptx(
1451
- gate.resolved,
1452
- { mtimeMs: gate.stat.mtimeMs, size: gate.stat.size },
1453
- { engine: docxPdfEngine },
1454
- );
1643
+ let result: Awaited<ReturnType<typeof renderPptx>>;
1644
+ try {
1645
+ result = await renderPptx(
1646
+ gate.real,
1647
+ { mtimeMs: gate.stat.mtimeMs, size: gate.stat.size },
1648
+ { engine: docxPdfEngine },
1649
+ );
1650
+ } catch (err) {
1651
+ if (err instanceof ContainmentBindingRefused) {
1652
+ reply.code(403);
1653
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1654
+ }
1655
+ throw err;
1656
+ }
1455
1657
  if (!result.success) {
1456
1658
  return { success: false, error: result.error } satisfies ApiResponse;
1457
1659
  }
@@ -1471,11 +1673,20 @@ export function registerFileRoutes(
1471
1673
  if ("code" in gate) {
1472
1674
  return sendGateFailure(reply, gate);
1473
1675
  }
1474
- const result = await renderDocx(
1475
- gate.resolved,
1476
- { mtimeMs: gate.stat.mtimeMs, size: gate.stat.size },
1477
- { mode: docxRenderMode, engine: docxPdfEngine, caps: officeCaps },
1478
- );
1676
+ let result: Awaited<ReturnType<typeof renderDocx>>;
1677
+ try {
1678
+ result = await renderDocx(
1679
+ gate.real,
1680
+ { mtimeMs: gate.stat.mtimeMs, size: gate.stat.size },
1681
+ { mode: docxRenderMode, engine: docxPdfEngine, caps: officeCaps },
1682
+ );
1683
+ } catch (err) {
1684
+ if (err instanceof ContainmentBindingRefused) {
1685
+ reply.code(403);
1686
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1687
+ }
1688
+ throw err;
1689
+ }
1479
1690
  if (!result.success) {
1480
1691
  // Unrenderable tail (corrupt/password/library bug) → 200 + success:false
1481
1692
  // so the client maps it to FallbackPreview (design D5).
@@ -1515,7 +1726,7 @@ export function registerFileRoutes(
1515
1726
  // Verified against the open handle (design D14, task 2.8) — a granted
1516
1727
  // FIFO would otherwise block this read indefinitely.
1517
1728
  try {
1518
- source = await readFileVerifiedUtf8(resolved);
1729
+ source = await readFileVerifiedUtf8(renderDecision.real, { decidedReal: renderDecision.real });
1519
1730
  } catch (err) {
1520
1731
  if (err instanceof VerifiedReadRefused) {
1521
1732
  reply.code(403);
@@ -1526,8 +1737,12 @@ export function registerFileRoutes(
1526
1737
  }
1527
1738
  } else {
1528
1739
  try {
1529
- source = await readFileStateChecked(resolved, "utf-8");
1530
- } catch {
1740
+ source = await readFileStateChecked(renderDecision.real, "utf-8", { decidedReal: renderDecision.real });
1741
+ } catch (err) {
1742
+ if (err instanceof DashboardStateRefused) {
1743
+ reply.code(403);
1744
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1745
+ }
1531
1746
  reply.code(404);
1532
1747
  return { success: false, error: "not found" } satisfies ApiResponse;
1533
1748
  }
@@ -1573,14 +1788,24 @@ export function registerFileRoutes(
1573
1788
  if ("code" in gate) {
1574
1789
  return sendGateFailure(reply, gate);
1575
1790
  }
1576
- const out = pdfCachePath(gate.resolved, gate.stat.mtimeMs, gate.stat.size);
1791
+ const out = pdfCachePath(gate.real, gate.stat.mtimeMs, gate.stat.size);
1577
1792
  try {
1578
1793
  await fs.access(out);
1579
1794
  } catch {
1580
1795
  try {
1796
+ // The converter takes a PATH, so the post-open (dev, ino) recheck runs immediately before it
1797
+ // to narrow the swap window. Residual: a swap after this checked open; the converter only
1798
+ // accepts .docx/.pptx and emits a PDF rendering, never the file bytes.
1799
+ // See change: close-security-map-high-findings (D1, F7).
1800
+ const guard = await openStateChecked(gate.real, "r", { decidedReal: gate.real });
1801
+ await guard.close().catch(() => undefined);
1581
1802
  await fs.mkdir(path.dirname(out), { recursive: true });
1582
- await docxPdfEngine.toPdf(gate.resolved, out);
1803
+ await convertBound(docxPdfEngine, gate.real, out);
1583
1804
  } catch (err) {
1805
+ if (err instanceof DashboardStateRefused) {
1806
+ reply.code(403);
1807
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1808
+ }
1584
1809
  reply.code(500);
1585
1810
  return {
1586
1811
  success: false,
@@ -1619,7 +1844,7 @@ export function registerFileRoutes(
1619
1844
  // Read from the VERIFIED handle, so the bytes parsed are the bytes
1620
1845
  // checked (design D14, task 2.8) — not a third resolution of the path.
1621
1846
  try {
1622
- buffer = await readFileVerified(gate.resolved);
1847
+ buffer = await readFileVerified(gate.real, { decidedReal: gate.real });
1623
1848
  } catch (err) {
1624
1849
  if (err instanceof VerifiedReadRefused) {
1625
1850
  reply.code(403);
@@ -1630,8 +1855,12 @@ export function registerFileRoutes(
1630
1855
  }
1631
1856
  } else {
1632
1857
  try {
1633
- buffer = await readFileStateChecked(gate.resolved);
1634
- } catch {
1858
+ buffer = await readFileStateChecked(gate.real, undefined, { decidedReal: gate.real });
1859
+ } catch (err) {
1860
+ if (err instanceof DashboardStateRefused) {
1861
+ reply.code(403);
1862
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1863
+ }
1635
1864
  reply.code(404);
1636
1865
  return { success: false, error: "not found" } satisfies ApiResponse;
1637
1866
  }
@@ -1692,12 +1921,22 @@ export function registerFileRoutes(
1692
1921
  // previously followed — started failing 400. For a grant admission the
1693
1922
  // bytes now come from the VERIFIED handle, so the path is not resolved a
1694
1923
  // third time to race. (Found by the task 4.5 review gate.)
1695
- const parsed = gate.viaGrant
1696
- ? await loadParsedEml(gate.resolved, stat, await readFileVerified(gate.resolved))
1697
- : await loadParsedEml(gate.resolved, stat);
1924
+ // Both branches read through the bound opener (decided real path) and hand the bytes on, so
1925
+ // `lib/eml.ts` never re-resolves the pathname. See change: close-local-listener-and-egress-gaps.
1926
+ const parsed = await loadParsedEml(
1927
+ gate.resolved,
1928
+ stat,
1929
+ gate.viaGrant
1930
+ ? await readFileVerified(gate.real, { decidedReal: gate.real })
1931
+ : await readFileStateChecked(gate.real, undefined, { decidedReal: gate.real }),
1932
+ );
1698
1933
  const data = await toParseResult(parsed, { allowRemote: request.query.allowRemote === "1" });
1699
1934
  return { success: true, data } satisfies ApiResponse;
1700
1935
  } catch (err) {
1936
+ if (err instanceof DashboardStateRefused || (err instanceof VerifiedReadRefused && err.reason === "state-file")) {
1937
+ reply.code(403);
1938
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1939
+ }
1701
1940
  const msg = err instanceof Error ? err.message : "failed to parse EML";
1702
1941
  reply.code(400);
1703
1942
  return { success: false, error: msg } satisfies ApiResponse;
@@ -1746,10 +1985,18 @@ export function registerFileRoutes(
1746
1985
  let parsed;
1747
1986
  try {
1748
1987
  // Same grant-only rule as the EML parse site above (task 4.5 review).
1749
- parsed = gate.viaGrant
1750
- ? await loadParsedEml(gate.resolved, stat, await readFileVerified(gate.resolved))
1751
- : await loadParsedEml(gate.resolved, stat);
1988
+ parsed = await loadParsedEml(
1989
+ gate.resolved,
1990
+ stat,
1991
+ gate.viaGrant
1992
+ ? await readFileVerified(gate.real, { decidedReal: gate.real })
1993
+ : await readFileStateChecked(gate.real, undefined, { decidedReal: gate.real }),
1994
+ );
1752
1995
  } catch (err) {
1996
+ if (err instanceof DashboardStateRefused || (err instanceof VerifiedReadRefused && err.reason === "state-file")) {
1997
+ reply.code(403);
1998
+ return { success: false, error: "path outside working directory" } satisfies ApiResponse;
1999
+ }
1753
2000
  const msg = err instanceof Error ? err.message : "failed to parse EML";
1754
2001
  reply.code(400);
1755
2002
  return { success: false, error: msg } satisfies ApiResponse;
@@ -1759,16 +2006,10 @@ export function registerFileRoutes(
1759
2006
  reply.code(404);
1760
2007
  return { success: false, error: "attachment index out of range" } satisfies ApiResponse;
1761
2008
  }
1762
- // Header-safe filename: strip CR/LF/quote (anti-injection), fold non-ASCII
1763
- // to `_` for the legacy `filename=`, and carry the exact name via RFC 5987
1764
- // `filename*` so UTF-8 names (e.g. Hungarian) survive.
1765
- const rawName = (att.filename || `attachment-${index}`).replace(/["\r\n]/g, "");
1766
- const asciiName = rawName.replace(/[^\x20-\x7e]/g, "_");
2009
+ // Header-safe attachment name (shared helper; see change: add-file-download).
2010
+ const rawName = att.filename || `attachment-${index}`;
1767
2011
  reply.header("Content-Type", att.contentType || "application/octet-stream");
1768
- reply.header(
1769
- "Content-Disposition",
1770
- `attachment; filename="${asciiName}"; filename*=UTF-8''${encodeURIComponent(rawName)}`,
1771
- );
2012
+ reply.header("Content-Disposition", contentDispositionAttachment(rawName));
1772
2013
  reply.header("X-Content-Type-Options", "nosniff");
1773
2014
  reply.header("Cache-Control", "private, max-age=60");
1774
2015
  reply.header("Content-Length", String(att.content.length));