@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.
- package/AGENTS.md +2 -0
- package/README.md +17 -12
- package/docs/architecture.md +973 -224
- package/package.json +29 -18
- package/packages/extension/package.json +16 -9
- package/packages/extension/src/bridge-context.ts +6 -0
- package/packages/extension/src/bridge-handlers/dispatch.ts +54 -69
- package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
- package/packages/extension/src/bridge-handlers/instance.ts +21 -12
- package/packages/extension/src/bridge-handlers/lifecycle.ts +84 -40
- package/packages/extension/src/bridge-shutdown.ts +44 -0
- package/packages/extension/src/bridge.ts +272 -260
- package/packages/extension/src/command-handler.ts +26 -31
- package/packages/extension/src/connection.ts +123 -31
- package/packages/extension/src/credential-guard.ts +300 -0
- package/packages/extension/src/custom-entry-forward.ts +27 -18
- package/packages/extension/src/default-model-apply.ts +83 -0
- package/packages/extension/src/flow-event-wiring.ts +19 -95
- package/packages/extension/src/followup-drain.ts +19 -5
- package/packages/extension/src/path-gate/decide.ts +68 -5
- package/packages/extension/src/path-gate/handler.ts +16 -8
- package/packages/extension/src/path-gate/index.ts +2 -2
- package/packages/extension/src/path-gate/roots.ts +15 -3
- package/packages/extension/src/path-gate/suppression.ts +3 -0
- package/packages/extension/src/pi-env.d.ts +8 -1
- package/packages/extension/src/pi-retry-settings.ts +11 -2
- package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
- package/packages/extension/src/preview-path-link.ts +151 -0
- package/packages/extension/src/project-init/scaffold.ts +98 -35
- package/packages/extension/src/project-trust.ts +24 -15
- package/packages/extension/src/provider-model-cache.ts +118 -0
- package/packages/extension/src/provider-register.ts +428 -28
- package/packages/extension/src/retry-tracker.ts +90 -7
- package/packages/extension/src/role-manager.ts +4 -2
- package/packages/extension/src/role-model-tools.ts +21 -4
- package/packages/extension/src/server-auto-start.ts +68 -2
- package/packages/extension/src/server-launcher.ts +26 -8
- package/packages/extension/src/session-sync.ts +11 -12
- package/packages/extension/src/spawn-new-session.ts +22 -0
- package/packages/extension/src/steer-buffer.ts +164 -0
- package/packages/extension/src/stream-forward-buffer.ts +64 -15
- package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
- package/packages/extension/src/sudo-askpass/controller.ts +405 -0
- package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
- package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
- package/packages/extension/src/sudo-askpass/index.ts +11 -0
- package/packages/extension/src/sudo-askpass/install.ts +143 -0
- package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
- package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
- package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
- package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
- package/packages/extension/src/terminal-reload.ts +19 -5
- package/packages/extension/src/tool-update-filter-registry.ts +210 -0
- package/packages/extension/src/vault-redaction.ts +4 -3
- package/packages/server/package.json +17 -14
- package/packages/server/src/access/access-denials.ts +8 -0
- package/packages/server/src/access/access-grants.ts +244 -58
- package/packages/server/src/access/access-plane.ts +7 -0
- package/packages/server/src/access/containment-gate.ts +66 -21
- package/packages/server/src/access/denial-hold.ts +3 -0
- package/packages/server/src/access/grant-coordinator.ts +17 -1
- package/packages/server/src/access/named-grant.ts +3 -0
- package/packages/server/src/access/pending-grant-registry.ts +32 -5
- package/packages/server/src/access/pi-trust-mirror-service.ts +7 -1
- package/packages/server/src/access/planes.ts +1 -0
- package/packages/server/src/access/verified-read.ts +24 -7
- package/packages/server/src/acp-bridge/acp-session-adapter.ts +10 -2
- package/packages/server/src/acp-bridge/server-requests.ts +10 -4
- package/packages/server/src/agent-events/agent-event-hub.ts +1 -1
- package/packages/server/src/auth/audit-log.ts +28 -0
- package/packages/server/src/auth/auth-plugin.ts +188 -15
- package/packages/server/src/auth/auth.ts +80 -0
- package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
- package/packages/server/src/auth/cors-origin.ts +14 -1
- package/packages/server/src/auth/credential-envelope.ts +233 -0
- package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
- package/packages/server/src/auth/credential-key-worker.mjs +108 -0
- package/packages/server/src/auth/credential-key.ts +479 -0
- package/packages/server/src/auth/credential-migration.ts +162 -0
- package/packages/server/src/auth/csp-report-paths.ts +0 -5
- package/packages/server/src/auth/csp.ts +74 -36
- package/packages/server/src/auth/device-proof.ts +202 -0
- package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
- package/packages/server/src/auth/host-admission.ts +7 -0
- package/packages/server/src/auth/host-gate.ts +13 -2
- package/packages/server/src/auth/localhost-guard.ts +50 -23
- package/packages/server/src/auth/locked-json-file.ts +68 -6
- package/packages/server/src/auth/models-json-store.ts +269 -0
- package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
- package/packages/server/src/auth/node-guard.ts +36 -49
- package/packages/server/src/auth/plugin-credential-store.ts +81 -10
- package/packages/server/src/auth/provider-auth-storage.ts +208 -11
- package/packages/server/src/auth/provider-block-checks.ts +321 -0
- package/packages/server/src/auth/provider-host-detect.ts +151 -0
- package/packages/server/src/auth/provider-key-file.ts +71 -0
- package/packages/server/src/auth/provider-readiness.ts +91 -0
- package/packages/server/src/auth/route-tier-gate.ts +3 -2
- package/packages/server/src/auth/vertex-key-check.ts +140 -0
- package/packages/server/src/auth/ws-ticket.ts +1 -1
- package/packages/server/src/browse.ts +73 -20
- package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
- package/packages/server/src/browser-handlers/directory-handler.ts +11 -24
- package/packages/server/src/browser-handlers/session-action-handler.ts +158 -62
- package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
- package/packages/server/src/browser-handlers/subscription-handler.ts +46 -1
- package/packages/server/src/build-plugin-send-prompt.ts +18 -0
- package/packages/server/src/cli/credentials-command.ts +555 -0
- package/packages/server/src/cli.ts +21 -16
- package/packages/server/src/config-api.ts +34 -38
- package/packages/server/src/config-snapshot.ts +149 -0
- package/packages/server/src/directory-service.ts +33 -14
- package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
- package/packages/server/src/event-wiring.ts +181 -101
- package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
- package/packages/server/src/git-worktree/git-operations.ts +1 -1
- package/packages/server/src/git-worktree/repo-lock.ts +42 -0
- package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
- package/packages/server/src/git-worktree/worktree-init.ts +5 -1
- package/packages/server/src/identity/http-road-classification.ts +5 -1
- package/packages/server/src/identity/identity-floor.ts +5 -2
- package/packages/server/src/identity/ws-message-scope.ts +10 -3
- package/packages/server/src/identity/ws-road-classification.ts +2 -1
- package/packages/server/src/lib/browse-roots.ts +13 -2
- package/packages/server/src/lib/content-disposition.ts +20 -0
- package/packages/server/src/lib/dashboard-state-guard.ts +304 -21
- package/packages/server/src/lib/eml.ts +2 -2
- package/packages/server/src/lib/frame-policy-probe.ts +308 -0
- package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
- package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
- package/packages/server/src/lib/grep.ts +4 -1
- package/packages/server/src/lib/index-html.ts +2 -2
- package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
- package/packages/server/src/lib/office-preview.ts +47 -10
- package/packages/server/src/lib/path-containment.ts +45 -12
- package/packages/server/src/lib/resolve-file-mention.ts +230 -38
- package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
- package/packages/server/src/lib/writable-handler-target.ts +4 -0
- package/packages/server/src/lib/writable-md-target.ts +22 -0
- package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
- package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
- package/packages/server/src/lifecycle/exit-signal.ts +43 -0
- package/packages/server/src/live-server/capability-redact.ts +21 -5
- package/packages/server/src/live-server/live-capability.ts +416 -52
- package/packages/server/src/live-server/live-csp-report.ts +1 -1
- package/packages/server/src/live-server/live-csp.ts +64 -16
- package/packages/server/src/live-server/live-log.ts +5 -1
- package/packages/server/src/live-server/live-server-manager.ts +11 -0
- package/packages/server/src/live-server/live-server-proxy.ts +268 -52
- package/packages/server/src/live-server/live-static.ts +4 -1
- package/packages/server/src/live-server/preview-dispatch.ts +286 -0
- package/packages/server/src/live-server/preview-observe.ts +53 -0
- package/packages/server/src/live-server/preview-origin.ts +182 -0
- package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
- package/packages/server/src/live-server/preview-path-store.ts +420 -0
- package/packages/server/src/live-server/preview-path.ts +40 -0
- package/packages/server/src/live-server/preview-pool.ts +385 -0
- package/packages/server/src/live-server/preview-preflight.ts +41 -0
- package/packages/server/src/live-server/preview-reserve.ts +44 -0
- package/packages/server/src/live-server/preview-tier.ts +217 -0
- package/packages/server/src/live-server/preview-viewers.ts +54 -0
- package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
- package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
- package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
- package/packages/server/src/model-proxy/internal-registry.ts +283 -21
- package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
- package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
- package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
- package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
- package/packages/server/src/openspec/readiness.ts +1 -1
- package/packages/server/src/package/provider-probe.ts +194 -5
- package/packages/server/src/pairing/browser-gateway.ts +140 -42
- package/packages/server/src/pairing/device-key-intake.ts +120 -0
- package/packages/server/src/pairing/paired-devices.ts +370 -8
- package/packages/server/src/pairing/pairing.ts +69 -7
- package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
- package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
- package/packages/server/src/pending/pending-attach-registry.ts +15 -0
- package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
- package/packages/server/src/persistence/memory-event-store.ts +251 -296
- package/packages/server/src/persistence/preferences-store.ts +52 -2
- package/packages/server/src/pi/bridge-contention.ts +84 -2
- package/packages/server/src/pi/host-project-trust.ts +15 -9
- package/packages/server/src/pi/pi-gateway.ts +208 -21
- package/packages/server/src/pi/provisional-registration.ts +4 -1
- package/packages/server/src/pi/resource-toggle-trust.ts +17 -6
- package/packages/server/src/pi-agent-settings.ts +95 -301
- package/packages/server/src/pi-default-remirror.ts +89 -0
- package/packages/server/src/plugin-append-event.ts +35 -0
- package/packages/server/src/plugin-entry-stats.ts +61 -0
- package/packages/server/src/plugin-local-request.ts +207 -0
- package/packages/server/src/plugin-ownership.ts +111 -0
- package/packages/server/src/plugin-policy-registry.ts +297 -0
- package/packages/server/src/plugin-request-lane.ts +92 -16
- package/packages/server/src/preferences-relay.ts +20 -0
- package/packages/server/src/project-seed.ts +347 -0
- package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
- package/packages/server/src/questions/question-store.ts +3 -2
- package/packages/server/src/routes/access-routes.ts +23 -6
- package/packages/server/src/routes/acme-routes.ts +14 -4
- package/packages/server/src/routes/agent-event-stream-routes.ts +1 -1
- package/packages/server/src/routes/file-routes.ts +327 -86
- package/packages/server/src/routes/file-write-binary-routes.ts +20 -4
- package/packages/server/src/routes/frame-policy-routes.ts +215 -0
- package/packages/server/src/routes/git-routes.ts +29 -78
- package/packages/server/src/routes/grep-routes.ts +26 -0
- package/packages/server/src/routes/live-server-routes.ts +198 -4
- package/packages/server/src/routes/models-introspection-routes.ts +1 -1
- package/packages/server/src/routes/openspec-routes.ts +17 -3
- package/packages/server/src/routes/pairing-routes.ts +200 -11
- package/packages/server/src/routes/pi-settings-routes.ts +2 -0
- package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
- package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
- package/packages/server/src/routes/provider-auth-routes.ts +167 -9
- package/packages/server/src/routes/provider-override-routes.ts +158 -0
- package/packages/server/src/routes/provider-routes.ts +348 -86
- package/packages/server/src/routes/session-routes.ts +25 -22
- package/packages/server/src/routes/system-routes.ts +87 -39
- package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
- package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
- package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
- package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
- package/packages/server/src/server.ts +512 -175
- package/packages/server/src/services/cli-service.ts +59 -10
- package/packages/server/src/services/secrets-resolver.ts +46 -30
- package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
- package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
- package/packages/server/src/session/death-reason.ts +11 -7
- package/packages/server/src/session/event-status-extraction.ts +5 -1
- package/packages/server/src/session/memory-session-manager.ts +24 -2
- package/packages/server/src/session/open-tool-calls.ts +81 -47
- package/packages/server/src/session/pid-target.ts +127 -0
- package/packages/server/src/session/replay-compaction.ts +18 -5
- package/packages/server/src/session/seed-discovered-history.ts +85 -0
- package/packages/server/src/session/server-pid-context.ts +14 -0
- package/packages/server/src/session/session-api.ts +78 -29
- package/packages/server/src/session/session-archive.ts +7 -0
- package/packages/server/src/session/session-bootstrap.ts +9 -54
- package/packages/server/src/session/session-load-worker-pool.ts +11 -1
- package/packages/server/src/session/session-load-worker.ts +22 -3
- package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
- package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
- package/packages/server/src/spawn-process/headless-pid-registry.ts +383 -72
- package/packages/server/src/spawn-process/link-register.ts +42 -0
- package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
- package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
- package/packages/server/src/spawn-process/process-classifier.ts +8 -3
- package/packages/server/src/spawn-process/process-manager.ts +61 -6
- package/packages/server/src/spawn-process/restored-identity.ts +112 -0
- package/packages/server/src/spawn-process/session-terminator.ts +179 -18
- package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
- package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
- package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
- package/packages/server/src/sudo-credential/relay.ts +337 -0
- package/packages/server/src/terminal/terminal-gateway.ts +10 -0
- package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
- package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
- package/packages/server/src/vault/vault-delivery-hub.ts +17 -1
- package/packages/server/src/vault/vault-routes.ts +9 -2
- package/packages/server/src/vault/vault-store.ts +87 -24
- package/packages/server/vendor/xlsx/LICENSE +201 -0
- package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
- package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
- package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
- package/packages/shared/package.json +4 -2
- package/packages/shared/src/agent-credential-files.ts +32 -0
- package/packages/shared/src/browser-protocol.ts +137 -57
- package/packages/shared/src/canvas-detect.ts +1 -1
- package/packages/shared/src/canvas-types.ts +2 -2
- package/packages/shared/src/config.ts +73 -136
- package/packages/shared/src/containment-guard.ts +14 -4
- package/packages/shared/src/credential-encryption.ts +87 -0
- package/packages/shared/src/custom-event-groups.ts +2 -0
- package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
- package/packages/shared/src/dashboard-plugin/host-api.ts +1 -1
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +46 -0
- package/packages/shared/src/dashboard-plugin/plugin-status.ts +4 -3
- package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
- package/packages/shared/src/dashboard-plugin/slot-props.ts +2 -0
- package/packages/shared/src/dashboard-plugin/slot-types.ts +1 -1
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +11 -3
- package/packages/shared/src/device-key-proof.ts +309 -0
- package/packages/shared/src/event-forward-declaration.ts +85 -12
- package/packages/shared/src/forbidden-subjects.ts +126 -14
- package/packages/shared/src/heap-limits.ts +0 -30
- package/packages/shared/src/host-admission.ts +2 -1
- package/packages/shared/src/index.ts +7 -6
- package/packages/shared/src/live-server.ts +20 -0
- package/packages/shared/src/mcp/verb-tiers.generated.ts +1 -3
- package/packages/shared/src/models-json-reader.ts +41 -0
- package/packages/shared/src/network-denial-signal.ts +15 -0
- package/packages/shared/src/node-version.ts +63 -60
- package/packages/shared/src/pairing-knock-client.ts +92 -8
- package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
- package/packages/shared/src/pi-path-compare.ts +31 -0
- package/packages/shared/src/pi-settings-schema.ts +52 -9
- package/packages/shared/src/pi-trust-mirror-snapshot.ts +16 -4
- package/packages/shared/src/pi-trust-mirror-types.ts +2 -0
- package/packages/shared/src/pi-trust-mirror.ts +18 -8
- package/packages/shared/src/pi-trust-resource-digest.ts +18 -12
- package/packages/shared/src/pid-namespace.ts +86 -0
- package/packages/shared/src/platform/native-ts-register.mjs +1 -1
- package/packages/shared/src/platform/process.ts +404 -1
- package/packages/shared/src/platform/resolve-pi-shell.ts +38 -9
- package/packages/shared/src/platform/spawn-runtime.ts +193 -7
- package/packages/shared/src/preview-egress.ts +56 -2
- package/packages/shared/src/preview-origins.ts +398 -0
- package/packages/shared/src/prompt-answer.ts +9 -5
- package/packages/shared/src/protocol.ts +147 -85
- package/packages/shared/src/provider-env-catalog.ts +413 -0
- package/packages/shared/src/provider-overrides.ts +112 -0
- package/packages/shared/src/question-types.ts +6 -0
- package/packages/shared/src/recommended-extensions.ts +79 -26
- package/packages/shared/src/renderer-by-ext.ts +5 -2
- package/packages/shared/src/rest-api.ts +93 -3
- package/packages/shared/src/role-schema.ts +24 -0
- package/packages/shared/src/route-tiers.ts +94 -3
- package/packages/shared/src/runtime-overlay/compat.ts +70 -6
- package/packages/shared/src/secret-patterns.ts +49 -0
- package/packages/shared/src/source-matching.ts +2 -2
- package/packages/shared/src/state-replay.ts +40 -24
- package/packages/shared/src/sudo-credential.ts +71 -0
- package/packages/shared/src/tool-path-resolve.ts +16 -1
- package/packages/shared/src/tool-registry/strategies.ts +1 -1
- package/packages/shared/src/tool-workdir.ts +56 -0
- package/packages/shared/src/trusted-types-mode.ts +72 -0
- package/packages/shared/src/types.ts +68 -109
- package/packages/shared/src/vertex-regions.ts +81 -0
- package/packages/shared/src/ws-message-tiers.ts +10 -3
- package/packages/extension/src/subagent-fanout-admission.ts +0 -234
- package/packages/extension/src/subagent-forward-sites.ts +0 -69
- package/packages/extension/src/subagent-frame-buffer.ts +0 -245
- package/packages/extension/src/subagent-frame-strip.ts +0 -109
- package/packages/extension/src/subagent-saturation.ts +0 -196
- package/packages/extension/src/subagent-tick-throttle.ts +0 -252
- package/packages/shared/src/anthropic-messages-source.ts +0 -8
- package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +0 -9
- package/packages/shared/src/dashboard-plugin/subagent-types.ts +0 -219
|
@@ -16,31 +16,252 @@
|
|
|
16
16
|
* `$HOME`; the `~/.pi` anchor can never be widened by request input.
|
|
17
17
|
*
|
|
18
18
|
* A leading `~/` expands to the home directory; `~user/` is NOT expanded. A
|
|
19
|
-
* mention that does not
|
|
20
|
-
*
|
|
19
|
+
* contained mention that does not exist returns null (never an error). A mention that FAILS
|
|
20
|
+
* containment is never statted and returns `{ resolved, kind, outside: true }` (the normalized
|
|
21
|
+
* candidate): that discloses nothing about existence, and lets the client open the editor pane
|
|
22
|
+
* where the read gate decides (design D1).
|
|
21
23
|
*
|
|
22
|
-
*
|
|
24
|
+
* Tagged pipeline (change: rich-chat-links, design D3): `resolveMentionTagged` runs
|
|
25
|
+
* 0. re-rooted candidate (worktree parity; same containment, else continue with the original)
|
|
26
|
+
* 1. producing tool's directory (opt-in `recover` + `toolCwd`; dir AND joined path must pass containment,
|
|
27
|
+
* an out-of-scope dir is skipped silently — never `gated`)
|
|
28
|
+
* 2. exact (`~/` | absolute | cwd-relative); a containment failure on the user's own mention is `gated`
|
|
29
|
+
* 3. fuzzy over tracked files (opt-in `recover`; `mention-fuzzy-index.ts`, at most 25 stats per mention)
|
|
30
|
+
* and tags the outcome `found | recovered | ambiguous | missing | gated`. `resolveFileMention` stays the
|
|
31
|
+
* exact-only legacy shape on top of it.
|
|
32
|
+
*
|
|
33
|
+
* See change: server-side-file-mention-resolution, fix-file-link-editor-routing, rich-chat-links,
|
|
34
|
+
* spec `tool-output-linkification`.
|
|
23
35
|
*/
|
|
24
36
|
import fs from "node:fs/promises";
|
|
25
37
|
import os from "node:os";
|
|
26
38
|
import path from "node:path";
|
|
27
39
|
import { containmentAllows } from "@blackbelt-technology/pi-dashboard-shared/containment-guard.js";
|
|
40
|
+
import { grantedSubjects } from "../access/access-grants.js";
|
|
28
41
|
import { decidePassive } from "../access/containment-gate.js";
|
|
42
|
+
import { dashboardStateRefuses } from "./dashboard-state-guard.js";
|
|
43
|
+
import { getMentionFuzzyIndex, type MentionFuzzyIndex } from "./mention-fuzzy-index.js";
|
|
44
|
+
import { safeRealpath, within } from "./path-containment.js";
|
|
29
45
|
|
|
30
|
-
|
|
46
|
+
type MentionKind = "abs" | "tilde" | "relative";
|
|
31
47
|
|
|
32
48
|
export interface ResolvedMention {
|
|
33
49
|
resolved: string;
|
|
34
50
|
kind: MentionKind;
|
|
51
|
+
/**
|
|
52
|
+
* True iff the candidate FAILED containment (never statted, so independent of existence). The open route's
|
|
53
|
+
* own gate (grant / prompt / 403 / 404) stays the sole authority for reading it.
|
|
54
|
+
*/
|
|
55
|
+
outside?: true;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
type Containment = "contained" | "granted-missing" | "outside";
|
|
59
|
+
|
|
60
|
+
type MentionState = "found" | "recovered" | "ambiguous" | "missing" | "gated";
|
|
61
|
+
|
|
62
|
+
/** Result of the tagged pipeline. `resolved` is `null` for `ambiguous` and `missing`. */
|
|
63
|
+
export interface TaggedMention {
|
|
64
|
+
state: MentionState;
|
|
65
|
+
resolved: string | null;
|
|
66
|
+
kind?: MentionKind | "fuzzy";
|
|
67
|
+
/** Present when recovery (not the plain exact lookup) produced the answer. */
|
|
68
|
+
via?: "tool-dir" | "fuzzy";
|
|
69
|
+
/** `ambiguous` only: up to 10 on-disk paths (tool-dir candidate first). */
|
|
70
|
+
candidates?: string[];
|
|
71
|
+
/** `gated` only (containment failed; never statted). */
|
|
72
|
+
outside?: true;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface ResolveMentionOptions {
|
|
76
|
+
cwd: string;
|
|
77
|
+
/** Admitted canonical cwd, when it differs from `cwd`: an additional containment anchor. */
|
|
78
|
+
canonCwd?: string;
|
|
79
|
+
/** Producing tool's working directory (untrusted; relative to `cwd` or absolute). Honoured only with `recover`. */
|
|
80
|
+
toolCwd?: string;
|
|
81
|
+
/** Worktree re-rooted spelling of `mention` (untrusted). Tried first; falls through when it does not resolve. */
|
|
82
|
+
reRooted?: string;
|
|
83
|
+
/** Opt into the tool directory and the fuzzy fallback. */
|
|
84
|
+
recover?: boolean;
|
|
85
|
+
/** Test seam; defaults to the process-wide index. */
|
|
86
|
+
fuzzyIndex?: MentionFuzzyIndex;
|
|
87
|
+
/** Optional tally of `fs.stat` calls (request observability, design D14); shared across a batch. */
|
|
88
|
+
counters?: { stats: number };
|
|
89
|
+
/**
|
|
90
|
+
* Optional per-request containment memo, keyed by candidate path. Shared across the items of ONE batch request
|
|
91
|
+
* (same anchors), so a repeated tool directory or candidate is judged once. Never outlives the request.
|
|
92
|
+
*/
|
|
93
|
+
containmentMemo?: ContainmentMemo;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
type PassiveDecision = Awaited<ReturnType<typeof decidePassive>>;
|
|
97
|
+
|
|
98
|
+
/** A containment verdict plus the raw decision it came from. */
|
|
99
|
+
interface Judged {
|
|
100
|
+
decision: PassiveDecision;
|
|
101
|
+
containment: Containment;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Per-request containment memo (see `ResolveMentionOptions.containmentMemo`). */
|
|
105
|
+
export type ContainmentMemo = Map<string, Promise<Judged>>;
|
|
106
|
+
|
|
107
|
+
interface Ctx {
|
|
108
|
+
anchors: string[];
|
|
109
|
+
counters?: { stats: number };
|
|
110
|
+
memo?: ContainmentMemo;
|
|
35
111
|
}
|
|
36
112
|
|
|
113
|
+
/** Maximum candidates reported for an ambiguous mention. */
|
|
114
|
+
export const MAX_CANDIDATES = 10;
|
|
115
|
+
|
|
37
116
|
/** Server-derived `~/.pi` containment anchor. Read at call time (fake-HOME safe). */
|
|
38
117
|
function homePiAnchor(): string {
|
|
39
118
|
return path.join(os.homedir(), ".pi");
|
|
40
119
|
}
|
|
41
120
|
|
|
121
|
+
function anchorsFor(cwd: string, canonCwd: string | undefined): string[] {
|
|
122
|
+
return canonCwd !== undefined && canonCwd !== cwd ? [cwd, canonCwd, homePiAnchor()] : [cwd, homePiAnchor()];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** `~/…` → home, absolute → verbatim, otherwise cwd-relative; normalised so `..` is collapsed BEFORE containment. */
|
|
126
|
+
function candidateOf(mention: string, cwd: string): { candidate: string; kind: MentionKind } {
|
|
127
|
+
if (mention.startsWith("~/")) return { candidate: path.resolve(path.join(os.homedir(), mention.slice(2))), kind: "tilde" };
|
|
128
|
+
if (path.isAbsolute(mention)) return { candidate: path.resolve(mention), kind: "abs" };
|
|
129
|
+
// A bare `~user/…` reaches here (not `~/`) and is joined to cwd verbatim — it is NEVER expanded to another user's home.
|
|
130
|
+
return { candidate: path.resolve(cwd, mention), kind: "relative" };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
42
134
|
/**
|
|
43
|
-
*
|
|
135
|
+
* Containment BEFORE stat (design D2). Anchors: cwd + fixed `~/.pi`; git-root widening comes from layer ② of
|
|
136
|
+
* `isAllowed` (via `decidePassive`). Consumes grants; returns no body, so it can never originate a grant (D12).
|
|
137
|
+
* A path under a grant that does not exist is "granted-missing" (like a missing in-cwd file): the grant layer
|
|
138
|
+
* needs a real file, so the nearest existing ancestor is judged. Only already-granted subjects can answer that
|
|
139
|
+
* way, so an ungranted path stays existence-independent.
|
|
140
|
+
*/
|
|
141
|
+
async function classifyFresh(candidate: string, anchors: string[]): Promise<Judged> {
|
|
142
|
+
const decision = await decidePassive(candidate, anchors, { allowGrant: true });
|
|
143
|
+
if (containmentAllows(decision, candidate)) return { decision, containment: "contained" };
|
|
144
|
+
if (!(await dashboardStateRefuses(candidate))) {
|
|
145
|
+
const real = await safeRealpath(candidate);
|
|
146
|
+
if (grantedSubjects().some((subject) => within(real, subject))) return { decision, containment: "granted-missing" };
|
|
147
|
+
}
|
|
148
|
+
return { decision, containment: "outside" };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Memoised per request when `ctx.memo` is set. Keeps the raw decision so each stat site can guard on it directly. */
|
|
152
|
+
function judge(candidate: string, ctx: Ctx): Promise<Judged> {
|
|
153
|
+
if (!ctx.memo) return classifyFresh(candidate, ctx.anchors);
|
|
154
|
+
let hit = ctx.memo.get(candidate);
|
|
155
|
+
if (!hit) {
|
|
156
|
+
hit = classifyFresh(candidate, ctx.anchors);
|
|
157
|
+
ctx.memo.set(candidate, hit);
|
|
158
|
+
}
|
|
159
|
+
return hit;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async function classify(candidate: string, ctx: Ctx): Promise<Containment> {
|
|
163
|
+
return (await judge(candidate, ctx)).containment;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function exists(p: string, counters?: { stats: number }): Promise<boolean> {
|
|
167
|
+
if (counters) counters.stats++;
|
|
168
|
+
try {
|
|
169
|
+
await fs.stat(p);
|
|
170
|
+
return true;
|
|
171
|
+
} catch {
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Contained AND on disk; the only way a candidate other than the user's own mention gets stat-ed. */
|
|
177
|
+
async function containedAndPresent(candidate: string, ctx: Ctx): Promise<boolean> {
|
|
178
|
+
const { decision } = await judge(candidate, ctx);
|
|
179
|
+
// The guard sits at the stat site (not behind a helper) so the path-injection barrier is visible to CodeQL.
|
|
180
|
+
return containmentAllows(decision, candidate) && (await exists(candidate, ctx.counters));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Step 1: the producing tool's directory. Dir and joined path must both be contained; otherwise skipped silently. */
|
|
184
|
+
async function toolDirCandidate(mention: string, toolCwd: string, cwd: string, ctx: Ctx): Promise<string | null> {
|
|
185
|
+
const dir = path.resolve(cwd, toolCwd);
|
|
186
|
+
if ((await classify(dir, ctx)) !== "contained") return null;
|
|
187
|
+
const joined = path.resolve(dir, mention);
|
|
188
|
+
return (await containedAndPresent(joined, ctx)) ? joined : null;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Step 3: fuzzy fallback over tracked files. Stat budget: the index hands over at most 25 matches. */
|
|
192
|
+
async function fuzzy(mention: string, cwd: string, index: MentionFuzzyIndex, ctx: Ctx): Promise<TaggedMention> {
|
|
193
|
+
const missing: TaggedMention = { state: "missing", resolved: null };
|
|
194
|
+
let look: Awaited<ReturnType<MentionFuzzyIndex["lookup"]>>;
|
|
195
|
+
try {
|
|
196
|
+
look = await index.lookup(cwd, mention);
|
|
197
|
+
} catch {
|
|
198
|
+
return missing;
|
|
199
|
+
}
|
|
200
|
+
if (look.status !== "ok" || look.total === 0) return missing;
|
|
201
|
+
|
|
202
|
+
if (look.total === 1) {
|
|
203
|
+
const only = look.matches[0];
|
|
204
|
+
return (await containedAndPresent(only, ctx))
|
|
205
|
+
? { state: "recovered", resolved: only, kind: "fuzzy", via: "fuzzy" }
|
|
206
|
+
: missing;
|
|
207
|
+
}
|
|
208
|
+
// Several tracked matches: never auto-select, even when exactly one is on disk. Checked in chunks of
|
|
209
|
+
// MAX_CANDIDATES (concurrent within a chunk) until enough are on disk; at most MAX_MATCHES stats overall.
|
|
210
|
+
const onDisk: string[] = [];
|
|
211
|
+
for (let i = 0; i < look.matches.length && onDisk.length < MAX_CANDIDATES; i += MAX_CANDIDATES) {
|
|
212
|
+
const chunk = look.matches.slice(i, i + MAX_CANDIDATES);
|
|
213
|
+
const present = await Promise.all(chunk.map((match) => containedAndPresent(match, ctx)));
|
|
214
|
+
chunk.forEach((match, j) => {
|
|
215
|
+
if (present[j] && onDisk.length < MAX_CANDIDATES) onDisk.push(match);
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
return onDisk.length > 0 ? { state: "ambiguous", resolved: null, candidates: onDisk } : missing;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Resolve `mention` through the tagged pipeline. Never throws for a bad mention; `cwd` must already be admitted.
|
|
223
|
+
* Without `recover`, the result is exactly the exact-only lookup (`found | gated | missing`).
|
|
224
|
+
*/
|
|
225
|
+
export async function resolveMentionTagged(mention: string, opts: ResolveMentionOptions): Promise<TaggedMention> {
|
|
226
|
+
const { cwd, canonCwd, toolCwd, reRooted, recover = false } = opts;
|
|
227
|
+
const missing: TaggedMention = { state: "missing", resolved: null };
|
|
228
|
+
if (!mention) return missing;
|
|
229
|
+
const ctx: Ctx = { anchors: anchorsFor(cwd, canonCwd), counters: opts.counters, memo: opts.containmentMemo };
|
|
230
|
+
|
|
231
|
+
// 0. Worktree re-root: same containment as the mention; an out-of-scope / absent copy falls through silently.
|
|
232
|
+
if (reRooted) {
|
|
233
|
+
const rr = candidateOf(reRooted, cwd);
|
|
234
|
+
if (await containedAndPresent(rr.candidate, ctx)) return { state: "found", resolved: rr.candidate, kind: rr.kind };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const exact = candidateOf(mention, cwd);
|
|
238
|
+
|
|
239
|
+
// 1. Producing tool's directory (relative mentions only) and
|
|
240
|
+
// 2. exact, evaluated side by side. A containment failure on the user's own mention is `gated`: no stat,
|
|
241
|
+
// independent of existence.
|
|
242
|
+
const [toolHit, judged] = await Promise.all([
|
|
243
|
+
recover && toolCwd && exact.kind === "relative" ? toolDirCandidate(mention, toolCwd, cwd, ctx) : null,
|
|
244
|
+
judge(exact.candidate, ctx),
|
|
245
|
+
]);
|
|
246
|
+
const { containment } = judged;
|
|
247
|
+
const exactHit = containmentAllows(judged.decision, exact.candidate) && (await exists(exact.candidate, ctx.counters));
|
|
248
|
+
|
|
249
|
+
if (toolHit && exactHit) {
|
|
250
|
+
const [a, b] = await Promise.all([safeRealpath(toolHit), safeRealpath(exact.candidate)]);
|
|
251
|
+
if (a === b) return { state: "found", resolved: exact.candidate, kind: exact.kind };
|
|
252
|
+
return { state: "ambiguous", resolved: null, candidates: [toolHit, exact.candidate] };
|
|
253
|
+
}
|
|
254
|
+
if (toolHit) return { state: "found", resolved: toolHit, kind: "relative", via: "tool-dir" };
|
|
255
|
+
if (exactHit) return { state: "found", resolved: exact.candidate, kind: exact.kind };
|
|
256
|
+
if (containment === "outside") return { state: "gated", resolved: exact.candidate, kind: exact.kind, outside: true };
|
|
257
|
+
|
|
258
|
+
// 3. Fuzzy fallback (opt-in).
|
|
259
|
+
if (recover) return fuzzy(mention, cwd, opts.fuzzyIndex ?? getMentionFuzzyIndex(), ctx);
|
|
260
|
+
return missing;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Resolve `mention` to an existing in-scope absolute path, an `outside` candidate (containment failed, no stat), or null. `canonCwd` (the admitted
|
|
44
265
|
* canonical cwd, when it differs from `cwd`) is an additional containment anchor.
|
|
45
266
|
*
|
|
46
267
|
* Candidate + kind:
|
|
@@ -54,37 +275,8 @@ export async function resolveFileMention(
|
|
|
54
275
|
mention: string,
|
|
55
276
|
{ cwd, canonCwd }: { cwd: string; canonCwd?: string },
|
|
56
277
|
): Promise<ResolvedMention | null> {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
if (mention.startsWith("~/")) {
|
|
62
|
-
candidate = path.join(os.homedir(), mention.slice(2));
|
|
63
|
-
kind = "tilde";
|
|
64
|
-
} else if (path.isAbsolute(mention)) {
|
|
65
|
-
candidate = mention;
|
|
66
|
-
kind = "abs";
|
|
67
|
-
} else {
|
|
68
|
-
// A bare `~user/…` reaches here (not `~/`) and is joined to cwd verbatim —
|
|
69
|
-
// it is NEVER expanded to another user's home.
|
|
70
|
-
candidate = path.resolve(cwd, mention);
|
|
71
|
-
kind = "relative";
|
|
72
|
-
}
|
|
73
|
-
// Normalize so `..` segments are collapsed before the containment gate.
|
|
74
|
-
candidate = path.resolve(candidate);
|
|
75
|
-
|
|
76
|
-
// Containment BEFORE stat (design D2). Anchors: cwd + fixed `~/.pi`; git-root
|
|
77
|
-
// widening comes from the layer ② of `isAllowed` (via `decidePassive`).
|
|
78
|
-
// Consumes grants; returns null rather than a body, so it can never
|
|
79
|
-
// originate a grant (design D12).
|
|
80
|
-
// The canonical cwd joins the request spelling when it differs (core-file-cwd-admission D2), so a
|
|
81
|
-
// mention resolved here opens through the same anchor set as `/api/file`.
|
|
82
|
-
const anchors = canonCwd !== undefined && canonCwd !== cwd ? [cwd, canonCwd, homePiAnchor()] : [cwd, homePiAnchor()];
|
|
83
|
-
if (!containmentAllows(await decidePassive(candidate, anchors, { allowGrant: true }), candidate)) return null;
|
|
84
|
-
try {
|
|
85
|
-
await fs.stat(candidate);
|
|
86
|
-
} catch {
|
|
87
|
-
return null;
|
|
88
|
-
}
|
|
89
|
-
return { resolved: candidate, kind };
|
|
278
|
+
const r = await resolveMentionTagged(mention, { cwd, canonCwd });
|
|
279
|
+
if (r.state === "gated") return { resolved: r.resolved as string, kind: r.kind as MentionKind, outside: true };
|
|
280
|
+
if (r.state === "found") return { resolved: r.resolved as string, kind: r.kind as MentionKind };
|
|
281
|
+
return null;
|
|
90
282
|
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure helpers for `POST /api/file/resolve-mentions` (design D3/D14 of rich-chat-links): request
|
|
3
|
+
* validation, the wire shape of a batch result, a per-principal sliding-window limiter and the one
|
|
4
|
+
* structured log line per request. No filesystem access happens here, so a 400 is decided before any
|
|
5
|
+
* path is touched; the route wires admission and `resolveMentionTagged` around these.
|
|
6
|
+
*
|
|
7
|
+
* Wire: `{ cwd, items: [{ mention, toolCwd?, reRooted? }] }` → `{ results: BatchResult[] }`, same order and
|
|
8
|
+
* length as `items`. Items past {@link MAX_BATCH_ITEMS} come back `{ state: "unknown" }` (the client asks
|
|
9
|
+
* again in a later flush). A `gated` item carries NOTHING but its state, so two out-of-scope mentions are
|
|
10
|
+
* byte-identical whether or not the file exists.
|
|
11
|
+
*/
|
|
12
|
+
import crypto from "node:crypto";
|
|
13
|
+
import type { TaggedMention } from "./resolve-file-mention.js";
|
|
14
|
+
|
|
15
|
+
export const MAX_BATCH_ITEMS = 200;
|
|
16
|
+
export const MAX_FIELD_CHARS = 1024;
|
|
17
|
+
export const BATCH_BODY_LIMIT_BYTES = 512 * 1024;
|
|
18
|
+
export const BATCH_RATE_PER_MINUTE = 60;
|
|
19
|
+
|
|
20
|
+
interface BatchItem {
|
|
21
|
+
mention: string;
|
|
22
|
+
toolCwd?: string;
|
|
23
|
+
reRooted?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Per-item wire result. `unknown` = not processed (past the cap); everything else is a {@link TaggedMention} state. */
|
|
27
|
+
export interface BatchResult {
|
|
28
|
+
state: TaggedMention["state"] | "unknown";
|
|
29
|
+
resolved?: string;
|
|
30
|
+
kind?: NonNullable<TaggedMention["kind"]>;
|
|
31
|
+
via?: NonNullable<TaggedMention["via"]>;
|
|
32
|
+
candidates?: string[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** `items` holds at most {@link MAX_BATCH_ITEMS} entries; `total` is the request's full item count (the rest are answered `unknown`). */
|
|
36
|
+
export type BatchParse = { ok: true; cwd: string; items: BatchItem[]; total: number } | { ok: false; error: string };
|
|
37
|
+
|
|
38
|
+
type ItemParse = { ok: true; item: BatchItem } | { ok: false; error: string };
|
|
39
|
+
|
|
40
|
+
/** Validate one untrusted item: shape first, then the bound on every string field. */
|
|
41
|
+
function parseBatchItem(raw: unknown): ItemParse {
|
|
42
|
+
if (typeof raw !== "object" || raw === null) return { ok: false, error: "each item must be an object" };
|
|
43
|
+
const { mention, toolCwd, reRooted } = raw as Record<string, unknown>;
|
|
44
|
+
if (typeof mention !== "string") return { ok: false, error: "each item needs a string mention" };
|
|
45
|
+
for (const field of [mention, toolCwd, reRooted]) {
|
|
46
|
+
if (field !== undefined && typeof field !== "string") return { ok: false, error: "toolCwd and reRooted must be strings" };
|
|
47
|
+
if (typeof field === "string" && field.length > MAX_FIELD_CHARS) {
|
|
48
|
+
return { ok: false, error: `a field exceeds ${MAX_FIELD_CHARS} characters` };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
ok: true,
|
|
53
|
+
item: { mention, ...(toolCwd ? { toolCwd: toolCwd as string } : {}), ...(reRooted ? { reRooted: reRooted as string } : {}) },
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Validate the untrusted body. Every string field of every item is bounded, including items past the
|
|
59
|
+
* cap — but those are only checked, never materialised (a 512 KB body of tiny items stays cheap).
|
|
60
|
+
*/
|
|
61
|
+
export function parseBatchBody(body: unknown): BatchParse {
|
|
62
|
+
const b = (typeof body === "object" && body !== null ? body : {}) as { cwd?: unknown; items?: unknown };
|
|
63
|
+
if (typeof b.cwd !== "string" || b.cwd === "") return { ok: false, error: "cwd and items are required" };
|
|
64
|
+
if (!Array.isArray(b.items)) return { ok: false, error: "cwd and items are required" };
|
|
65
|
+
const items: BatchItem[] = [];
|
|
66
|
+
const raws = b.items as unknown[];
|
|
67
|
+
for (let i = 0; i < raws.length; i++) {
|
|
68
|
+
const parsed = parseBatchItem(raws[i]);
|
|
69
|
+
if (!parsed.ok) return parsed;
|
|
70
|
+
if (i < MAX_BATCH_ITEMS) items.push(parsed.item);
|
|
71
|
+
}
|
|
72
|
+
return { ok: true, cwd: b.cwd, items, total: raws.length };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Wire form of a tagged result for the batch: no `resolved: null`, and `gated` reveals nothing beyond its state. */
|
|
76
|
+
export function toBatchResult(t: TaggedMention): BatchResult {
|
|
77
|
+
if (t.state === "gated" || t.state === "missing") return { state: t.state };
|
|
78
|
+
return {
|
|
79
|
+
state: t.state,
|
|
80
|
+
...(t.resolved !== null ? { resolved: t.resolved } : {}),
|
|
81
|
+
...(t.kind ? { kind: t.kind } : {}),
|
|
82
|
+
...(t.via ? { via: t.via } : {}),
|
|
83
|
+
...(t.candidates ? { candidates: t.candidates } : {}),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Items resolved at once. Small and fixed: enough to overlap filesystem latency, never a thundering herd. */
|
|
88
|
+
export const BATCH_CONCURRENCY = 16;
|
|
89
|
+
|
|
90
|
+
/** `Promise.all(items.map(fn))` with at most `limit` in flight; results keep input order. */
|
|
91
|
+
export async function mapConcurrent<T, R>(items: readonly T[], limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]> {
|
|
92
|
+
const out = new Array<R>(items.length);
|
|
93
|
+
let next = 0;
|
|
94
|
+
const worker = async (): Promise<void> => {
|
|
95
|
+
while (next < items.length) {
|
|
96
|
+
const i = next++;
|
|
97
|
+
out[i] = await fn(items[i], i);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const WINDOW_MS = 60_000;
|
|
105
|
+
const MAX_LIMITER_KEYS = 1000;
|
|
106
|
+
|
|
107
|
+
/** Sliding-window limiter, `limit` takes per 60 s per key. Bounded: the least recently used key is evicted. */
|
|
108
|
+
export function createWindowLimiter(limit: number, now: () => number = Date.now): { take(key: string): boolean } {
|
|
109
|
+
const hits = new Map<string, number[]>();
|
|
110
|
+
return {
|
|
111
|
+
take(key) {
|
|
112
|
+
const t = now();
|
|
113
|
+
const recent = (hits.get(key) ?? []).filter((x) => t - x < WINDOW_MS);
|
|
114
|
+
hits.delete(key);
|
|
115
|
+
hits.set(key, recent);
|
|
116
|
+
if (hits.size > MAX_LIMITER_KEYS) hits.delete(hits.keys().next().value as string);
|
|
117
|
+
if (recent.length >= limit) return false;
|
|
118
|
+
recent.push(t);
|
|
119
|
+
return true;
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface BatchLogFacts {
|
|
125
|
+
cwd: string;
|
|
126
|
+
items: number;
|
|
127
|
+
counts: Partial<Record<BatchResult["state"], number>>;
|
|
128
|
+
fuzzy: { hit: number; miss: number; skipped: number; buildMs: number };
|
|
129
|
+
stats: number;
|
|
130
|
+
totalMs: number;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** One line per request. Carries a cwd hash and counts only — never a mention, path or directory. */
|
|
134
|
+
export function formatBatchLog(f: BatchLogFacts): string {
|
|
135
|
+
const cwdHash = crypto.createHash("sha256").update(f.cwd).digest("hex").slice(0, 8);
|
|
136
|
+
const c = (s: BatchResult["state"]): number => f.counts[s] ?? 0;
|
|
137
|
+
return (
|
|
138
|
+
`[resolve-mentions] cwd=${cwdHash} items=${f.items} found=${c("found")} recovered=${c("recovered")} ` +
|
|
139
|
+
`ambiguous=${c("ambiguous")} missing=${c("missing")} gated=${c("gated")} unknown=${c("unknown")} ` +
|
|
140
|
+
`fuzzy_hit=${f.fuzzy.hit} fuzzy_miss=${f.fuzzy.miss} fuzzy_skipped=${f.fuzzy.skipped} ` +
|
|
141
|
+
`index_build_ms=${Math.round(f.fuzzy.buildMs)} stats=${f.stats} total_ms=${Math.round(f.totalMs)}`
|
|
142
|
+
);
|
|
143
|
+
}
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
import fs from "node:fs/promises";
|
|
13
13
|
import path from "node:path";
|
|
14
14
|
import { extOf } from "@blackbelt-technology/pi-dashboard-shared/file-kind.js";
|
|
15
|
+
import { dashboardStateRefuses } from "./dashboard-state-guard.js";
|
|
15
16
|
import { safeRealpath, within } from "./path-containment.js";
|
|
16
17
|
|
|
17
18
|
interface HandlerTargetClaim {
|
|
@@ -53,6 +54,9 @@ export async function isWritableHandlerTarget(
|
|
|
53
54
|
const ext = extOf(requested);
|
|
54
55
|
if (!ext || !opts.claim.extensions.includes(ext)) return null;
|
|
55
56
|
const real = await safeRealpath(requested);
|
|
57
|
+
// Dashboard state + pi-agent credential files (real path, both tiers) are never a write target, whatever
|
|
58
|
+
// extension a claim declares. See change: close-security-map-high-findings (D1, H6).
|
|
59
|
+
if (await dashboardStateRefuses(real)) return null;
|
|
56
60
|
const dir = await fs.realpath(path.dirname(requested));
|
|
57
61
|
if (!within(dir, root)) return null;
|
|
58
62
|
if ((opts.mode ?? "overwrite") === "overwrite") {
|
|
@@ -82,6 +82,28 @@ async function allowedRoot(opts: WritableMdTargetOptions): Promise<string | null
|
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
+
/**
|
|
86
|
+
* The extension + dashboard-state half of {@link isWritableMdTarget}, WITHOUT the scope-root check:
|
|
87
|
+
* true iff `absPath` is absolute, its REAL path is not under the dashboard state dir, and its real
|
|
88
|
+
* extension is an allowlisted text-doc kind (`.md .mdx .adoc .asciidoc .csv`). Mermaid sources
|
|
89
|
+
* (`.mmd`, `.mermaid`) are directory-only and never pass here, so they can never reach the
|
|
90
|
+
* outside-cwd write-grant gate. Never throws.
|
|
91
|
+
*
|
|
92
|
+
* Used by `POST /api/file/write` to decide whether a target outside the session cwd may be offered
|
|
93
|
+
* to the write gate at all (`evaluateContainment(..., {action:"write"})`).
|
|
94
|
+
* See change: fix-file-link-editor-routing (D2).
|
|
95
|
+
*/
|
|
96
|
+
export async function isTextDocWriteTarget(absPath: string): Promise<boolean> {
|
|
97
|
+
if (!path.isAbsolute(absPath)) return false;
|
|
98
|
+
try {
|
|
99
|
+
const real = await safeRealpath(path.resolve(absPath));
|
|
100
|
+
if (await dashboardStateRefuses(real)) return false;
|
|
101
|
+
return WRITABLE_MD_EXTENSIONS.has(extOf(real));
|
|
102
|
+
} catch {
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
85
107
|
/**
|
|
86
108
|
* True iff `absPath` is an authorized markdown write target for the given scope.
|
|
87
109
|
*
|
|
@@ -18,20 +18,20 @@
|
|
|
18
18
|
* held). Falls back to Tier 1 on any failure (koffi load, null handle,
|
|
19
19
|
* denied access). Never throws.
|
|
20
20
|
*
|
|
21
|
-
* `readLivePpid()` returns the server's LIVE parent PID (reparenting-aware)
|
|
22
|
-
*
|
|
23
|
-
*
|
|
21
|
+
* `readLivePpid()` returns the server's LIVE parent PID (reparenting-aware).
|
|
22
|
+
* On Node 26 `process.ppid` is itself live (re-read per access, follows
|
|
23
|
+
* reparenting — pinned by `boot-parent-liveness-no-spawn.test.ts`), so the
|
|
24
|
+
* reader never forks a subprocess on the `/api/health` hot path.
|
|
24
25
|
*
|
|
25
26
|
* Supported-Node floor: koffi 3.x targets N-API 8 (Node >= 16). The bundled
|
|
26
|
-
* server runtime (Node
|
|
27
|
-
* (>=
|
|
27
|
+
* server runtime (Node 26, `BUNDLED_NODE_VERSION`) and the package `engines`
|
|
28
|
+
* floor (>= 26.0.0) are both comfortably within koffi's supported N-API range, so
|
|
28
29
|
* no Node/koffi pin mismatch. See change: electron-attach-ownership-fixes
|
|
29
30
|
* (task 1b.3).
|
|
30
31
|
*
|
|
31
32
|
* See change: electron-attach-ownership-fixes.
|
|
32
33
|
*/
|
|
33
34
|
|
|
34
|
-
import { execFileSync } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
|
|
35
35
|
import { readFileSync } from "node:fs";
|
|
36
36
|
import { createRequire } from "node:module";
|
|
37
37
|
import { isProcessAlive, signalZero, type KillFn } from "@blackbelt-technology/pi-dashboard-shared/platform/process.js";
|
|
@@ -176,25 +176,10 @@ const readLivePpidImpl: () => number = (() => {
|
|
|
176
176
|
}
|
|
177
177
|
};
|
|
178
178
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
// shell) + a hard timeout so a stalled `ps` can never block the
|
|
184
|
-
// single-threaded Fastify event loop on the health hot path.
|
|
185
|
-
const out = execFileSync("ps", ["-o", "ppid=", "-p", String(process.pid)], {
|
|
186
|
-
encoding: "utf-8",
|
|
187
|
-
timeout: 1000,
|
|
188
|
-
});
|
|
189
|
-
const ppid = Number.parseInt(out.trim(), 10);
|
|
190
|
-
return Number.isFinite(ppid) ? ppid : process.ppid;
|
|
191
|
-
} catch {
|
|
192
|
-
return process.ppid;
|
|
193
|
-
}
|
|
194
|
-
};
|
|
195
|
-
}
|
|
196
|
-
// Windows (and any other platform): Windows never reparents, so the cached
|
|
197
|
-
// getter is correct; zombie detection uses bootParentAlive there.
|
|
179
|
+
// macOS, Windows and any other platform: `process.ppid` is a live getter.
|
|
180
|
+
// macOS previously forked a synchronous `ps` here — measured 1–4 s
|
|
181
|
+
// event-loop stalls per /api/health request under load. Windows never
|
|
182
|
+
// reparents; zombie detection uses bootParentAlive there.
|
|
198
183
|
return () => process.ppid;
|
|
199
184
|
})();
|
|
200
185
|
|