@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
@@ -0,0 +1,321 @@
1
+ /**
2
+ * Pre-pi checks for a browser-supplied provider block, shared by every writer of
3
+ * a block (`PUT /api/provider-overrides/:provider` → `models.json`, and the
4
+ * `block` field of `PATCH /api/providers/:name` → `providers.json`):
5
+ *
6
+ * - value classifier (pi's resolver: `!command` / `$NAME` reference / literal),
7
+ * - `maskBlock` (secrets → `ENV_MASK_MARKER`) and the restoring `prepareBlock`,
8
+ * - structural refusals: `too_large`, `prototype_key`, `duplicate_model_id`,
9
+ * `orphan_mask`, `userinfo_refused`, `command_refused`, `RECURSIVE_PROXY`.
10
+ *
11
+ * Refusal codes carry a caller-chosen prefix (`provider_overrides` or `providers`);
12
+ * `RECURSIVE_PROXY` is unprefixed. Pure: no I/O, never logs, never runs a command.
13
+ *
14
+ * See change: add-provider-advanced-settings (D3, tasks 2.2 / 2.3).
15
+ */
16
+ import {
17
+ ENV_MASK_MARKER,
18
+ PROVIDER_BLOCK_MAX_BYTES,
19
+ type ProviderBlock,
20
+ } from "@blackbelt-technology/pi-dashboard-shared/provider-overrides.js";
21
+ import { resolveBlockValue } from "../model-proxy/models-block-apply.js";
22
+
23
+ export type BlockCodePrefix = "provider_overrides" | "providers";
24
+
25
+ /** A refused block write: HTTP status, final (prefixed) code, human message. */
26
+ export interface BlockRefusal {
27
+ status: number;
28
+ code: string;
29
+ error: string;
30
+ }
31
+
32
+ export type ValueClass = "command" | "reference" | "literal";
33
+
34
+ /** Classify a config value as pi's resolver does (`resolveBlockValue` is the single rule source). */
35
+ export function classifyValue(value: string): ValueClass {
36
+ let referenced = false;
37
+ const probe = new Proxy({} as NodeJS.ProcessEnv, {
38
+ get: () => {
39
+ referenced = true;
40
+ return "x";
41
+ },
42
+ });
43
+ const r = resolveBlockValue(value, probe);
44
+ if (r.kind === "command") return "command";
45
+ return referenced ? "reference" : "literal";
46
+ }
47
+
48
+ const isRec = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
49
+ const own = (o: object, k: string): boolean => Object.hasOwn(o, k);
50
+
51
+ const refuse = (prefix: BlockCodePrefix, status: number, code: string, error: string): BlockRefusal => ({
52
+ status,
53
+ code: `${prefix}.${code}`,
54
+ error,
55
+ });
56
+
57
+ // ── URL userinfo / query parts (string-level, so nothing is re-encoded) ─────────
58
+
59
+ interface UrlParts {
60
+ scheme: string;
61
+ userinfo: string | null;
62
+ rest: string; // host + path
63
+ query: string | null;
64
+ hash: string;
65
+ }
66
+
67
+ const URL_RE = /^([a-z][a-z0-9+.-]*:\/\/)([^/?#]*@)?([^?#]*)(\?[^#]*)?(#.*)?$/is;
68
+
69
+ function splitUrl(url: string): UrlParts | null {
70
+ const m = URL_RE.exec(url);
71
+ if (!m) return null;
72
+ return { scheme: m[1], userinfo: m[2] ? m[2].slice(0, -1) : null, rest: m[3], query: m[4] ? m[4].slice(1) : null, hash: m[5] ?? "" };
73
+ }
74
+
75
+ function joinUrl(p: UrlParts): string {
76
+ return `${p.scheme}${p.userinfo !== null ? `${p.userinfo}@` : ""}${p.rest}${p.query !== null ? `?${p.query}` : ""}${p.hash}`;
77
+ }
78
+
79
+ /** `[name, value|null]` pairs of a raw query string (`null` = no `=`). */
80
+ function splitQuery(q: string): Array<[string, string | null]> {
81
+ return q.split("&").map((pair) => {
82
+ const i = pair.indexOf("=");
83
+ return i < 0 ? [pair, null] : [pair.slice(0, i), pair.slice(i + 1)];
84
+ });
85
+ }
86
+ const joinQuery = (pairs: Array<[string, string | null]>): string =>
87
+ pairs.map(([k, v]) => (v === null ? k : `${k}=${v}`)).join("&");
88
+
89
+ function maskUrl(url: string): string {
90
+ const p = splitUrl(url);
91
+ if (!p) return url;
92
+ if (p.userinfo !== null && p.userinfo !== "") p.userinfo = ENV_MASK_MARKER;
93
+ if (p.query !== null) {
94
+ p.query = joinQuery(splitQuery(p.query).map(([k, v]) => [k, v ? ENV_MASK_MARKER : v] as [string, string | null]));
95
+ }
96
+ return joinUrl(p);
97
+ }
98
+
99
+ // ── mask ──────────────────────────────────────────────────────────────────────
100
+
101
+ function maskValue(key: string | undefined, value: unknown): unknown {
102
+ if (Array.isArray(value)) return value.map((v) => maskValue(undefined, v));
103
+ if (!isRec(value)) {
104
+ if (typeof value === "string") {
105
+ if (key === "apiKey" && value !== "" && classifyValue(value) === "literal") return ENV_MASK_MARKER;
106
+ if (key === "baseUrl") return maskUrl(value);
107
+ }
108
+ return value;
109
+ }
110
+ const out: Record<string, unknown> = {};
111
+ for (const [k, v] of Object.entries(value)) {
112
+ if (k === "headers" && isRec(v)) {
113
+ const h: Record<string, unknown> = {};
114
+ for (const [name, hv] of Object.entries(v)) {
115
+ h[name] = typeof hv === "string" && hv !== "" && classifyValue(hv) === "literal" ? ENV_MASK_MARKER : hv;
116
+ }
117
+ out[k] = h;
118
+ } else out[k] = maskValue(k, v);
119
+ }
120
+ return out;
121
+ }
122
+
123
+ /** Response form of a stored block: literal `apiKey`/header values, userinfo and query values → `ENV_MASK_MARKER`. */
124
+ export function maskBlock(block: ProviderBlock): ProviderBlock {
125
+ return maskValue(undefined, block) as ProviderBlock;
126
+ }
127
+
128
+ // ── raw body ──────────────────────────────────────────────────────────────────
129
+
130
+ /** 413 `too_large` when the raw body exceeds `PROVIDER_BLOCK_MAX_BYTES`; counted on bytes, before parsing. */
131
+ export function checkRawBodySize(rawBytes: number, prefix: BlockCodePrefix): BlockRefusal | null {
132
+ return rawBytes > PROVIDER_BLOCK_MAX_BYTES
133
+ ? refuse(prefix, 413, "too_large", `Request body exceeds ${PROVIDER_BLOCK_MAX_BYTES} bytes`)
134
+ : null;
135
+ }
136
+
137
+ const PROTOTYPE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
138
+
139
+ function hasPrototypeKey(v: unknown): boolean {
140
+ if (Array.isArray(v)) return v.some(hasPrototypeKey);
141
+ if (!isRec(v)) return false;
142
+ for (const k of Object.keys(v)) if (PROTOTYPE_KEYS.has(k) || hasPrototypeKey(v[k])) return true;
143
+ return false;
144
+ }
145
+
146
+ function hasDuplicateModelId(v: unknown): boolean {
147
+ if (Array.isArray(v)) return v.some(hasDuplicateModelId);
148
+ if (!isRec(v)) return false;
149
+ for (const [k, child] of Object.entries(v)) {
150
+ if (k === "models" && Array.isArray(child)) {
151
+ const seen = new Set<string>();
152
+ for (const m of child) {
153
+ if (isRec(m) && typeof m.id === "string") {
154
+ if (seen.has(m.id)) return true;
155
+ seen.add(m.id);
156
+ }
157
+ }
158
+ }
159
+ if (hasDuplicateModelId(child)) return true;
160
+ }
161
+ return false;
162
+ }
163
+
164
+ // ── restore + refuse ──────────────────────────────────────────────────────────
165
+
166
+ class Refused extends Error {
167
+ readonly refusal: BlockRefusal;
168
+ constructor(refusal: BlockRefusal) {
169
+ super(refusal.code);
170
+ this.refusal = refusal;
171
+ }
172
+ }
173
+
174
+ interface Ctx {
175
+ prefix: BlockCodePrefix;
176
+ isSelfPointing: (url: string) => boolean;
177
+ }
178
+
179
+ /** Restore a masked / unchanged-checked URL against the stored URL at the same path. */
180
+ function restoreUrl(ctx: Ctx, incoming: string, stored: unknown): string {
181
+ const p = splitUrl(incoming);
182
+ if (!p) return incoming;
183
+ const s = typeof stored === "string" ? splitUrl(stored) : null;
184
+ const orphan = () => new Refused(refuse(ctx.prefix, 400, "orphan_mask", "A masked value has no stored value to keep"));
185
+ if (p.userinfo !== null && p.userinfo !== "") {
186
+ if (p.userinfo === ENV_MASK_MARKER) {
187
+ if (!s || !s.userinfo) throw orphan();
188
+ p.userinfo = s.userinfo;
189
+ } else if (!s || s.userinfo !== p.userinfo) {
190
+ throw new Refused(refuse(ctx.prefix, 400, "userinfo_refused", "Credentials in a URL cannot be added or changed here"));
191
+ }
192
+ }
193
+ if (p.query !== null) {
194
+ const stored = s?.query ? splitQuery(s.query) : [];
195
+ p.query = joinQuery(
196
+ splitQuery(p.query).map(([k, v]) => {
197
+ if (v !== ENV_MASK_MARKER) return [k, v] as [string, string | null];
198
+ const sv = stored.find(([sk]) => sk === k)?.[1];
199
+ if (sv === undefined || sv === null) throw orphan();
200
+ return [k, sv] as [string, string | null];
201
+ }),
202
+ );
203
+ }
204
+ const out = joinUrl(p);
205
+ if (ctx.isSelfPointing(out)) {
206
+ throw new Refused({ status: 400, code: "RECURSIVE_PROXY", error: "baseUrl points back at this dashboard" });
207
+ }
208
+ return out;
209
+ }
210
+
211
+ function restoreSecret(ctx: Ctx, incoming: string, stored: unknown): string {
212
+ if (incoming === ENV_MASK_MARKER) {
213
+ if (typeof stored !== "string") {
214
+ throw new Refused(refuse(ctx.prefix, 400, "orphan_mask", "A masked value has no stored value to keep"));
215
+ }
216
+ return stored;
217
+ }
218
+ if (classifyValue(incoming) === "command" && stored !== incoming) {
219
+ throw new Refused(refuse(ctx.prefix, 400, "command_refused", "A command value cannot be added or changed here"));
220
+ }
221
+ return incoming;
222
+ }
223
+
224
+ function restoreHeaders(ctx: Ctx, incoming: Record<string, unknown>, stored: unknown): Record<string, unknown> {
225
+ const sto = isRec(stored) ? stored : {};
226
+ const lookup = (name: string): unknown => {
227
+ const hit = Object.keys(sto).find((k) => k.toLowerCase() === name.toLowerCase());
228
+ return hit === undefined ? undefined : sto[hit];
229
+ };
230
+ const out: Record<string, unknown> = {};
231
+ for (const [name, v] of Object.entries(incoming)) {
232
+ out[name] = typeof v === "string" ? restoreSecret(ctx, v, lookup(name)) : v;
233
+ }
234
+ return out;
235
+ }
236
+
237
+ function restoreNode(ctx: Ctx, key: string | undefined, incoming: unknown, stored: unknown): unknown {
238
+ if (Array.isArray(incoming)) {
239
+ const sto = Array.isArray(stored) ? stored : [];
240
+ return incoming.map((item, i) => {
241
+ // `models[]` entries follow their id; any other array follows position.
242
+ const match =
243
+ key === "models" && isRec(item) && typeof item.id === "string"
244
+ ? sto.find((s) => isRec(s) && s.id === item.id)
245
+ : sto[i];
246
+ return restoreNode(ctx, undefined, item, match);
247
+ });
248
+ }
249
+ if (isRec(incoming)) {
250
+ const sto = isRec(stored) ? stored : {};
251
+ const out: Record<string, unknown> = {};
252
+ for (const [k, v] of Object.entries(incoming)) {
253
+ if (k === "headers" && isRec(v)) out[k] = restoreHeaders(ctx, v, sto[k]);
254
+ else out[k] = restoreNode(ctx, k, v, own(sto, k) ? sto[k] : undefined);
255
+ }
256
+ return out;
257
+ }
258
+ if (typeof incoming === "string") {
259
+ if (key === "apiKey") return restoreSecret(ctx, incoming, stored);
260
+ if (key === "baseUrl") return restoreUrl(ctx, incoming, stored);
261
+ }
262
+ return incoming;
263
+ }
264
+
265
+ const EMPTY_DROPPED = ["headers", "compat", "modelOverrides", "models"] as const;
266
+ const isEmpty = (v: unknown): boolean => (Array.isArray(v) ? v.length === 0 : isRec(v) && Object.keys(v).length === 0);
267
+
268
+ /** Drop empty `headers`/`compat`/`modelOverrides`/`models` and empty per-model overrides; `{}` = nothing left. */
269
+ function normalizeBlock(block: ProviderBlock): ProviderBlock {
270
+ const out: Record<string, unknown> = { ...block };
271
+ if (isRec(out.modelOverrides)) {
272
+ const mo: Record<string, unknown> = {};
273
+ for (const [id, o] of Object.entries(out.modelOverrides)) {
274
+ if (!isRec(o)) {
275
+ mo[id] = o;
276
+ continue;
277
+ }
278
+ const one = { ...o };
279
+ for (const f of ["headers", "compat"]) if (isEmpty(one[f])) delete one[f];
280
+ if (Object.keys(one).length > 0) mo[id] = one;
281
+ }
282
+ out.modelOverrides = mo;
283
+ }
284
+ for (const f of EMPTY_DROPPED) if (isEmpty(out[f])) delete out[f];
285
+ return out as ProviderBlock;
286
+ }
287
+
288
+ export interface PrepareBlockOptions {
289
+ /** Block as sent by the browser (already JSON-parsed). */
290
+ incoming: unknown;
291
+ /** Stored (unmasked) block, or undefined. Mask markers are restored from it. */
292
+ stored: ProviderBlock | undefined;
293
+ prefix: BlockCodePrefix;
294
+ /** True when a `baseUrl` points back at the dashboard (see `recursion-guard.ts`). */
295
+ isSelfPointing: (url: string) => boolean;
296
+ }
297
+
298
+ export type PrepareBlockResult = { ok: true; block: ProviderBlock } | { ok: false; refusal: BlockRefusal };
299
+
300
+ /**
301
+ * Run every pre-pi refusal on `incoming`, restore mask markers from `stored`, and
302
+ * normalise. Order: prototype_key, duplicate_model_id, then restore walk
303
+ * (orphan_mask / userinfo_refused / command_refused / RECURSIVE_PROXY).
304
+ */
305
+ export function prepareBlock(opts: PrepareBlockOptions): PrepareBlockResult {
306
+ const { incoming, stored, prefix } = opts;
307
+ if (!isRec(incoming)) return { ok: false, refusal: refuse(prefix, 400, "invalid_block", "block must be an object") };
308
+ if (hasPrototypeKey(incoming)) {
309
+ return { ok: false, refusal: refuse(prefix, 400, "prototype_key", "Keys __proto__, constructor and prototype are not allowed") };
310
+ }
311
+ if (hasDuplicateModelId(incoming)) {
312
+ return { ok: false, refusal: refuse(prefix, 400, "duplicate_model_id", "Two models share the same id") };
313
+ }
314
+ try {
315
+ const restored = restoreNode({ prefix, isSelfPointing: opts.isSelfPointing }, undefined, incoming, stored ?? {});
316
+ return { ok: true, block: normalizeBlock(restored as ProviderBlock) };
317
+ } catch (err) {
318
+ if (err instanceof Refused) return { ok: false, refusal: err.refusal };
319
+ throw err;
320
+ }
321
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Host detection for the provider settings pane: what the dashboard host
3
+ * already has for a provider (gcloud ADC login, AWS profiles, AWS credentials
4
+ * in the environment / a role), and the catalogue method to preselect.
5
+ *
6
+ * Reads the same locations pi reads, as the account the server runs as. Every
7
+ * file is size-capped (64 KiB); unreadable or malformed → not found. Returns
8
+ * names, regions, project ids and account emails only — never a key, token,
9
+ * secret or file contents (the AWS credentials file contributes section names
10
+ * only). Pure parsers + one I/O wrapper. See change: add-provider-env-config (D6).
11
+ */
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import type { ProviderHostDetect } from "@blackbelt-technology/pi-dashboard-shared/rest-api.js";
16
+
17
+ const HOST_FILE_MAX_BYTES = 64 * 1024;
18
+
19
+ // ── Pure parsers ─────────────────────────────────────────────────────────────
20
+
21
+ /** INI sections → key/value maps. `null` when any line is not blank, comment, section or `key = value`. */
22
+ export function parseIni(text: string): Map<string, Record<string, string>> | null {
23
+ const out = new Map<string, Record<string, string>>();
24
+ let current: Record<string, string> | null = null;
25
+ for (const raw of text.split(/\r?\n/)) {
26
+ const line = raw.trim();
27
+ if (!line || line.startsWith("#") || line.startsWith(";")) continue;
28
+ const section = /^\[([^\]]+)\]$/.exec(line);
29
+ if (section) {
30
+ const name = section[1].trim();
31
+ current = out.get(name) ?? Object.create(null);
32
+ out.set(name, current as Record<string, string>);
33
+ continue;
34
+ }
35
+ const eq = line.indexOf("=");
36
+ if (eq > 0) {
37
+ // Indented continuation lines (AWS nested settings) land in the same section.
38
+ if (current) current[line.slice(0, eq).trim()] = line.slice(eq + 1).trim();
39
+ continue;
40
+ }
41
+ if (/^\s/.test(raw)) continue;
42
+ return null;
43
+ }
44
+ return out;
45
+ }
46
+
47
+ interface AdcInfo {
48
+ type: string;
49
+ quotaProject?: string;
50
+ account?: string;
51
+ }
52
+
53
+ /** Application Default Credentials JSON → type, quota project, service-account email. */
54
+ function parseAdc(text: string): AdcInfo | null {
55
+ try {
56
+ const j = JSON.parse(text) as Record<string, unknown>;
57
+ if (!j || typeof j !== "object" || Array.isArray(j) || typeof j.type !== "string") return null;
58
+ const info: AdcInfo = { type: j.type };
59
+ if (typeof j.quota_project_id === "string" && j.quota_project_id) info.quotaProject = j.quota_project_id;
60
+ if (typeof j.client_email === "string" && j.client_email) info.account = j.client_email;
61
+ return info;
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+
67
+ /** AWS profiles: config sections (`[profile x]` → x, `[default]`) with region, then credentials-only names. */
68
+ function parseAwsProfiles(configText: string | null, credentialsText: string | null): { name: string; region?: string }[] {
69
+ const profiles: { name: string; region?: string }[] = [];
70
+ const seen = new Set<string>();
71
+ const config = configText === null ? null : parseIni(configText);
72
+ for (const [section, values] of config ?? []) {
73
+ let name: string | null = null;
74
+ if (section === "default") name = "default";
75
+ else if (section.startsWith("profile ")) name = section.slice("profile ".length).trim();
76
+ if (!name || seen.has(name)) continue;
77
+ seen.add(name);
78
+ profiles.push(values.region ? { name, region: values.region } : { name });
79
+ }
80
+ const credentials = credentialsText === null ? null : parseIni(credentialsText);
81
+ for (const section of credentials?.keys() ?? []) {
82
+ const name = section.trim();
83
+ if (!name || seen.has(name)) continue;
84
+ seen.add(name);
85
+ profiles.push({ name });
86
+ }
87
+ return profiles;
88
+ }
89
+
90
+ // ── I/O wrapper ──────────────────────────────────────────────────────────────
91
+
92
+ export interface HostDetectDeps {
93
+ env?: Readonly<Record<string, string | undefined>>;
94
+ home?: string;
95
+ }
96
+
97
+ /** Read a small regular file, else `null` (missing, too large, not a file, unreadable). */
98
+ function readSmallFile(file: string): string | null {
99
+ try {
100
+ const st = fs.statSync(file);
101
+ if (!st.isFile() || st.size > HOST_FILE_MAX_BYTES) return null;
102
+ return fs.readFileSync(file, "utf-8");
103
+ } catch {
104
+ return null;
105
+ }
106
+ }
107
+
108
+ function detectVertex(env: HostDetectDeps["env"] & object, home: string): ProviderHostDetect {
109
+ const adcPath = env.GOOGLE_APPLICATION_CREDENTIALS || path.join(home, ".config", "gcloud", "application_default_credentials.json");
110
+ const adcText = readSmallFile(adcPath);
111
+ const adc = adcText === null ? null : parseAdc(adcText);
112
+ if (!adc) return { suggested: "service-account" };
113
+ let project = adc.quotaProject;
114
+ if (!project) {
115
+ const gcloudDir = path.join(home, ".config", "gcloud");
116
+ const active = env.CLOUDSDK_ACTIVE_CONFIG_NAME || readSmallFile(path.join(gcloudDir, "active_config"))?.trim() || "default";
117
+ if (/^[A-Za-z0-9_.-]+$/.test(active)) {
118
+ const cfgText = readSmallFile(path.join(gcloudDir, "configurations", `config_${active}`));
119
+ const cfg = cfgText === null ? null : parseIni(cfgText);
120
+ const p = cfg?.get("core")?.project;
121
+ if (p) project = p;
122
+ }
123
+ }
124
+ const found: { project?: string; account?: string } = {};
125
+ if (project) found.project = project;
126
+ if (adc.account) found.account = adc.account;
127
+ return { adc: found, suggested: "adc" };
128
+ }
129
+
130
+ function detectBedrock(env: HostDetectDeps["env"] & object, home: string): ProviderHostDetect {
131
+ const configText = readSmallFile(env.AWS_CONFIG_FILE || path.join(home, ".aws", "config"));
132
+ const credentialsText = readSmallFile(env.AWS_SHARED_CREDENTIALS_FILE || path.join(home, ".aws", "credentials"));
133
+ const profiles = parseAwsProfiles(configText, credentialsText);
134
+ let chain: ProviderHostDetect["chain"];
135
+ if (env.AWS_ACCESS_KEY_ID && env.AWS_SECRET_ACCESS_KEY) chain = "environment";
136
+ else if (env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI || env.AWS_CONTAINER_CREDENTIALS_FULL_URI) chain = "container role";
137
+ else if (env.AWS_WEB_IDENTITY_TOKEN_FILE) chain = "web identity";
138
+ const out: ProviderHostDetect = { profiles };
139
+ if (chain) out.chain = chain;
140
+ out.suggested = profiles.length > 0 ? "aws-profile" : chain ? "credential-chain" : "bearer-token";
141
+ return out;
142
+ }
143
+
144
+ /** What the host has for `provider` (bare catalogue id). Unknown providers → `{}`. */
145
+ export function detectHost(provider: string, deps: HostDetectDeps = {}): ProviderHostDetect {
146
+ const env = deps.env ?? process.env;
147
+ const home = deps.home ?? os.homedir();
148
+ if (provider === "google-vertex") return detectVertex(env, home);
149
+ if (provider === "amazon-bedrock") return detectBedrock(env, home);
150
+ return {};
151
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Service-account key-file inspection for the settings pane: reads ONLY
3
+ * `project_id` and `client_email` from a user-named file on the dashboard host.
4
+ *
5
+ * The path must pass the browse confinement for the request (non-local →
6
+ * shared roots, sensitive subtrees refused; symlinks resolved) BEFORE anything
7
+ * is opened. Regular file, ≤ 64 KiB, JSON, `type: "service_account"`.
8
+ * `private_key` and every other field never leave this function.
9
+ * See change: add-provider-env-config (D7).
10
+ */
11
+ import fs from "node:fs";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+ import type { KeyFileInfo } from "@blackbelt-technology/pi-dashboard-shared/rest-api.js";
15
+ import { type BrowseRoots, isWithinBrowseRoots } from "../lib/browse-roots.js";
16
+
17
+ const KEY_FILE_MAX_BYTES = 64 * 1024;
18
+
19
+ type KeyFileError = Extract<KeyFileInfo, { ok: false }>["error"];
20
+ const fail = (error: KeyFileError): KeyFileInfo => ({ ok: false, error });
21
+
22
+ function expandHome(p: string): string {
23
+ if (p === "~") return os.homedir();
24
+ if (p.startsWith("~/")) return path.join(os.homedir(), p.slice(2));
25
+ return p;
26
+ }
27
+
28
+ /** `roots === null` = locally trusted request (unconfined). */
29
+ export async function inspectKeyFile(rawPath: string, roots: BrowseRoots | null): Promise<KeyFileInfo> {
30
+ const requested = path.resolve(os.homedir(), expandHome(rawPath.trim()));
31
+ if (roots && !(await isWithinBrowseRoots(requested, roots))) return fail("provider_auth.key_file_outside_roots");
32
+ let real: string;
33
+ try {
34
+ real = await fs.promises.realpath(requested);
35
+ } catch (err) {
36
+ return (err as NodeJS.ErrnoException)?.code === "ENOENT" ? fail("provider_auth.key_file_not_found") : fail("provider_auth.key_file_unreadable");
37
+ }
38
+ // Re-check the resolved target: a symlink inside a root may point outside it.
39
+ if (roots && !(await isWithinBrowseRoots(real, roots))) return fail("provider_auth.key_file_outside_roots");
40
+ let text: string;
41
+ // Open the resolved path without following a (swapped-in) symlink, then
42
+ // fstat + a bounded read on the SAME descriptor: no check-then-read gap.
43
+ let handle: fs.promises.FileHandle | undefined;
44
+ try {
45
+ handle = await fs.promises.open(real, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
46
+ const st = await handle.stat();
47
+ if (!st.isFile()) return fail("provider_auth.key_file_unreadable");
48
+ if (st.size > KEY_FILE_MAX_BYTES) return fail("provider_auth.key_file_too_large");
49
+ const buf = Buffer.alloc(KEY_FILE_MAX_BYTES + 1);
50
+ const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
51
+ if (bytesRead > KEY_FILE_MAX_BYTES) return fail("provider_auth.key_file_too_large");
52
+ text = buf.subarray(0, bytesRead).toString("utf-8");
53
+ } catch (err) {
54
+ const code = (err as NodeJS.ErrnoException)?.code;
55
+ if (code === "ENOENT") return fail("provider_auth.key_file_not_found");
56
+ if (code === "EISDIR") return fail("provider_auth.key_file_unreadable");
57
+ return fail("provider_auth.key_file_unreadable");
58
+ } finally {
59
+ await handle?.close().catch(() => {});
60
+ }
61
+ let json: unknown;
62
+ try {
63
+ json = JSON.parse(text);
64
+ } catch {
65
+ return fail("provider_auth.key_file_not_service_account");
66
+ }
67
+ const j = json as Record<string, unknown> | null;
68
+ if (!j || typeof j !== "object" || j.type !== "service_account") return fail("provider_auth.key_file_not_service_account");
69
+ if (typeof j.project_id !== "string" || typeof j.client_email !== "string") return fail("provider_auth.key_file_not_service_account");
70
+ return { ok: true, project: j.project_id, account: j.client_email };
71
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * pi readiness of stored api-key credentials: the server's own pi runtime
3
+ * decides (`checkAuth` → the provider's `resolve`), never re-implemented here.
4
+ *
5
+ * Bounded: 2 s per check, at most 4 checks at once, results cached per
6
+ * auth.json stamp (mtime + size) and dropped by every dashboard write. A check
7
+ * that throws or times out, and a provider the runtime does not know, yield no
8
+ * entry (→ no `piReady`). See change: add-provider-env-config (D5).
9
+ */
10
+ import fs from "node:fs";
11
+ import type { AuthData } from "./provider-auth-storage.js";
12
+ import type { RuntimeCatalogueSource } from "./runtime-provider-catalogue.js";
13
+
14
+ const READINESS_TIMEOUT_MS = 2_000;
15
+ const READINESS_CONCURRENCY = 4;
16
+
17
+ interface ReadinessDeps {
18
+ runtime: RuntimeCatalogueSource | undefined;
19
+ /** auth.json path whose stamp keys the cache; absent → no cache. */
20
+ authPath?: string;
21
+ timeoutMs?: number;
22
+ }
23
+
24
+ let cache: { stamp: string; map: Map<string, boolean> } | null = null;
25
+
26
+ /** Drop cached results (called after every credential write). */
27
+ export function invalidateReadiness(): void {
28
+ cache = null;
29
+ }
30
+
31
+ function stampOf(file: string | undefined): string | null {
32
+ if (!file) return null;
33
+ try {
34
+ const st = fs.statSync(file);
35
+ return `${st.mtimeMs}:${st.size}`;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ const TIMED_OUT = Symbol("timeout");
42
+
43
+ async function checkOne(runtime: RuntimeCatalogueSource, id: string, timeoutMs: number): Promise<boolean | undefined> {
44
+ let timer: ReturnType<typeof setTimeout> | undefined;
45
+ try {
46
+ const result = await Promise.race([
47
+ runtime.checkAuth(id),
48
+ new Promise<typeof TIMED_OUT>((resolve) => {
49
+ timer = setTimeout(() => resolve(TIMED_OUT), timeoutMs);
50
+ timer.unref?.();
51
+ }),
52
+ ]);
53
+ if (result === TIMED_OUT) return undefined;
54
+ return !!result && result.type === "api_key";
55
+ } catch {
56
+ return undefined;
57
+ } finally {
58
+ if (timer) clearTimeout(timer);
59
+ }
60
+ }
61
+
62
+ /** Readiness per auth.json key, for every stored api-key credential the runtime knows. */
63
+ export async function computeReadiness(authData: AuthData, deps: ReadinessDeps): Promise<Map<string, boolean>> {
64
+ const { runtime } = deps;
65
+ const out = new Map<string, boolean>();
66
+ if (!runtime || typeof runtime.checkAuth !== "function" || typeof runtime.getProviders !== "function") return out;
67
+ const stamp = stampOf(deps.authPath);
68
+ if (stamp && cache?.stamp === stamp) return new Map(cache.map);
69
+
70
+ let known: Set<string>;
71
+ try {
72
+ known = new Set(runtime.getProviders().map((p) => p.id));
73
+ } catch {
74
+ return out;
75
+ }
76
+ const ids = Object.entries(authData)
77
+ .filter(([id, cred]) => cred?.type === "api_key" && known.has(id))
78
+ .map(([id]) => id);
79
+ const timeoutMs = deps.timeoutMs ?? READINESS_TIMEOUT_MS;
80
+ let next = 0;
81
+ const worker = async () => {
82
+ while (next < ids.length) {
83
+ const id = ids[next++];
84
+ const ready = await checkOne(runtime, id, timeoutMs);
85
+ if (ready !== undefined) out.set(id, ready);
86
+ }
87
+ };
88
+ await Promise.all(Array.from({ length: Math.min(READINESS_CONCURRENCY, ids.length) }, worker));
89
+ if (stamp) cache = { stamp, map: new Map(out) };
90
+ return out;
91
+ }
@@ -27,8 +27,9 @@
27
27
  *
28
28
  * See change: expand-mcp-tiered-surface (task 2.2).
29
29
  */
30
- import { rank, type Tier } from "@blackbelt-technology/pi-dashboard-shared/tiers.js";
30
+
31
31
  import { routeTier } from "@blackbelt-technology/pi-dashboard-shared/route-tiers.js";
32
+ import { rank, type Tier } from "@blackbelt-technology/pi-dashboard-shared/tiers.js";
32
33
  import { LIVE_PREVIEW_TIER } from "@blackbelt-technology/pi-dashboard-shared/ws-message-tiers.js";
33
34
  import type { FastifyReply, FastifyRequest } from "fastify";
34
35
  import type { LocalTrustContext } from "./local-proof.js";
@@ -123,7 +124,7 @@ export function createRouteTierGate(deps: RouteTierGateDeps) {
123
124
  // tier its WS upgrade needs. See change: add-passkey-user-auth.
124
125
  let requiredTier: Tier;
125
126
  if (route.startsWith("/api/")) requiredTier = routeTier(request.method, route);
126
- else if (route.startsWith("/live/")) requiredTier = LIVE_PREVIEW_TIER;
127
+ else if (route.startsWith("/live/") || route.startsWith("/preview/")) requiredTier = LIVE_PREVIEW_TIER;
127
128
  else return;
128
129
 
129
130
  const refusal = tierRefusalFor(request, requiredTier, deps.getTrustedNetworks, deps.localTrust);