@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
|
@@ -25,6 +25,7 @@ export type MirrorWithheldReason =
|
|
|
25
25
|
| "recorded-entry"
|
|
26
26
|
| "store-unreadable"
|
|
27
27
|
| "not-covered-session"
|
|
28
|
+
| "not-covered"
|
|
28
29
|
| "identity-weak"
|
|
29
30
|
| "live-timeout"
|
|
30
31
|
| "live-unreachable"
|
|
@@ -51,6 +52,7 @@ export const MIRROR_WITHHELD_LABELS: Record<MirrorWithheldReason, string> = {
|
|
|
51
52
|
"recorded-entry": "pi already has a recorded decision for this folder",
|
|
52
53
|
"store-unreadable": "pi's trust store could not be read",
|
|
53
54
|
"not-covered-session": "dashboard trust does not cover this session kind",
|
|
55
|
+
"not-covered": "no dashboard trust source covers this folder",
|
|
54
56
|
"identity-weak": "folder proof unavailable (empty, symlinked, referenced code outside it, or too large)",
|
|
55
57
|
"live-timeout": "live query did not finish within the time budget",
|
|
56
58
|
"live-unreachable": "dashboard server could not be reached",
|
|
@@ -61,13 +61,16 @@ export function isCanonicalAbsolutePath(p: unknown): p is string {
|
|
|
61
61
|
);
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
-
/**
|
|
65
|
-
|
|
64
|
+
/**
|
|
65
|
+
* `key` itself, then each ancestor, up to the root. `pathApi` (default: the
|
|
66
|
+
* native `node:path`) lets callers walk win32 keys on any host.
|
|
67
|
+
*/
|
|
68
|
+
export function ancestorKeys(key: string, pathApi: typeof path.posix = path): string[] {
|
|
66
69
|
const out: string[] = [];
|
|
67
70
|
let cur = key;
|
|
68
71
|
for (;;) {
|
|
69
72
|
out.push(cur);
|
|
70
|
-
const parent =
|
|
73
|
+
const parent = pathApi.dirname(cur);
|
|
71
74
|
if (parent === cur) return out;
|
|
72
75
|
cur = parent;
|
|
73
76
|
}
|
|
@@ -240,7 +243,10 @@ export interface PiTrustDecision {
|
|
|
240
243
|
}
|
|
241
244
|
|
|
242
245
|
export interface DecidePiTrustInput {
|
|
243
|
-
/**
|
|
246
|
+
/**
|
|
247
|
+
* pi's own `hasTrustRequiringProjectResources(cwd)`. `false` ⇒ implicitly
|
|
248
|
+
* trusted only when nothing is recorded (pi 1.5 order).
|
|
249
|
+
*/
|
|
244
250
|
hasTrustRequiringResources: boolean;
|
|
245
251
|
/** pi's nearest recorded entry (true OR false), or null. */
|
|
246
252
|
recordedEntry: { path: string; decision: boolean } | null;
|
|
@@ -252,15 +258,19 @@ export interface DecidePiTrustInput {
|
|
|
252
258
|
}
|
|
253
259
|
|
|
254
260
|
/**
|
|
255
|
-
*
|
|
256
|
-
*
|
|
257
|
-
* is pi's
|
|
261
|
+
* pi's recorded entry (true or false) → implicit (no trust-requiring project
|
|
262
|
+
* resources) → dashboard trust (even over `never`) → `defaultProjectTrust`.
|
|
263
|
+
* This is pi 1.5's order (`project-trust.js:22-23`): the recorded entry decides
|
|
264
|
+
* first, even for a folder with no trust-requiring resources; dashboard trust
|
|
265
|
+
* and the default apply only to folders that have such resources. Never writes
|
|
266
|
+
* anything. CLI `--approve/--no-approve` is pi's and outside this core.
|
|
267
|
+
* See change: update-pi-core-1-5-adopt-apis (design D2).
|
|
258
268
|
*/
|
|
259
269
|
export function decidePiTrust(input: DecidePiTrustInput): PiTrustDecision {
|
|
260
|
-
if (!input.hasTrustRequiringResources) return { trusted: true, source: { kind: "implicit" } };
|
|
261
270
|
if (input.recordedEntry) {
|
|
262
271
|
return { trusted: input.recordedEntry.decision, source: { kind: "recorded", path: input.recordedEntry.path } };
|
|
263
272
|
}
|
|
273
|
+
if (!input.hasTrustRequiringResources) return { trusted: true, source: { kind: "implicit" } };
|
|
264
274
|
if (input.mirrorEnabled && input.mirrorEntry) {
|
|
265
275
|
return {
|
|
266
276
|
trusted: true,
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
import { createHash, createHmac, randomBytes } from "node:crypto";
|
|
23
23
|
import * as fsp from "node:fs/promises";
|
|
24
24
|
import path from "node:path";
|
|
25
|
+
import { nativePathApi, type PathApi, piPathsEqual } from "./pi-path-compare.js";
|
|
25
26
|
|
|
26
27
|
/**
|
|
27
28
|
* pi does not export its own list (`TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES`),
|
|
@@ -184,11 +185,11 @@ function compareCodePoints(a: string, b: string): number {
|
|
|
184
185
|
return ai.length - bi.length;
|
|
185
186
|
}
|
|
186
187
|
|
|
187
|
-
async function realOrSelf(p: string): Promise<string> {
|
|
188
|
+
async function realOrSelf(p: string, pathApi: PathApi): Promise<string> {
|
|
188
189
|
try {
|
|
189
190
|
return await fsp.realpath(p);
|
|
190
191
|
} catch {
|
|
191
|
-
return
|
|
192
|
+
return pathApi.resolve(p);
|
|
192
193
|
}
|
|
193
194
|
}
|
|
194
195
|
|
|
@@ -205,15 +206,18 @@ async function collectPiResources(w: Walk, cwd: string): Promise<void> {
|
|
|
205
206
|
}
|
|
206
207
|
}
|
|
207
208
|
|
|
208
|
-
/**
|
|
209
|
-
|
|
209
|
+
/**
|
|
210
|
+
* `<d>/.agents/skills` for the cwd and every ancestor, except the user's own —
|
|
211
|
+
* excluded with pi's `pathsEqual` (1.5.0 `trust-manager.js:167`).
|
|
212
|
+
*/
|
|
213
|
+
async function collectAgentSkills(w: Walk, cwd: string, userSkills: string, pathApi: PathApi): Promise<void> {
|
|
210
214
|
for (let dir = cwd, k = 0; ; k += 1) {
|
|
211
|
-
const agents =
|
|
215
|
+
const agents = pathApi.join(dir, ".agents");
|
|
212
216
|
const agentsStat = await lstatOrNull(agents, w);
|
|
213
217
|
if (agentsStat?.isSymbolicLink()) throw new FailClosed("symlink");
|
|
214
|
-
const skills =
|
|
215
|
-
if (skills
|
|
216
|
-
const parent =
|
|
218
|
+
const skills = pathApi.join(agents, "skills");
|
|
219
|
+
if (!piPathsEqual(skills, userSkills, pathApi) && agentsStat) await addTree(w, skills, `a${k}`);
|
|
220
|
+
const parent = pathApi.dirname(dir);
|
|
217
221
|
if (parent === dir) return;
|
|
218
222
|
dir = parent;
|
|
219
223
|
}
|
|
@@ -222,19 +226,21 @@ async function collectAgentSkills(w: Walk, cwd: string, userSkills: string): Pro
|
|
|
222
226
|
/**
|
|
223
227
|
* The manifest of pi's trust-requiring resources for `cwd` (a canonical key), or
|
|
224
228
|
* `null` when the set is empty or cannot be bound. `home` is this side's own home
|
|
225
|
-
* (its `.agents/skills` is the user's, excluded).
|
|
229
|
+
* (its `.agents/skills` is the user's, excluded). `pathApi` (default native) is
|
|
230
|
+
* the path module for the skills walk and that exclusion (win32 testable anywhere).
|
|
226
231
|
*/
|
|
227
232
|
export async function trustResourceManifest(
|
|
228
233
|
cwd: string,
|
|
229
|
-
opts: { home: string; signal?: AbortSignal },
|
|
234
|
+
opts: { home: string; signal?: AbortSignal; pathApi?: PathApi },
|
|
230
235
|
): Promise<string | null> {
|
|
231
236
|
const w: Walk = { entries: [], bytes: 0, signal: opts.signal };
|
|
232
237
|
try {
|
|
233
238
|
checkAbort(w);
|
|
234
|
-
const
|
|
239
|
+
const pathApi = opts.pathApi ?? nativePathApi();
|
|
240
|
+
const userSkills = pathApi.join(await realOrSelf(opts.home, pathApi), ".agents", "skills");
|
|
235
241
|
checkAbort(w);
|
|
236
242
|
await collectPiResources(w, cwd);
|
|
237
|
-
await collectAgentSkills(w, cwd, userSkills);
|
|
243
|
+
await collectAgentSkills(w, cwd, userSkills, pathApi);
|
|
238
244
|
if (w.entries.length === 0) return null;
|
|
239
245
|
w.entries.sort((a, b) => compareCodePoints(a.label, b.label));
|
|
240
246
|
return w.entries.map((e) => e.line).join("\n");
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ONE builder for a pi process's pid-namespace report. Used at every bridge
|
|
3
|
+
* `session_register` site, in-process by the ACP bridge, and by the server for
|
|
4
|
+
* its own `ServerPidContext` — so both sides compare like with like.
|
|
5
|
+
*
|
|
6
|
+
* - `kind`/`distro`: `"wsl"` + `WSL_DISTRO_NAME` when that env var is non-empty.
|
|
7
|
+
* - `nsId`: Linux only, the `/proc/self/ns/pid` link.
|
|
8
|
+
* - `hostId`: Linux `/proc/sys/kernel/random/boot_id` (no hostname fallback);
|
|
9
|
+
* elsewhere `os.hostname()` (a weak discriminator, documented in design Risks).
|
|
10
|
+
* - Unreadable fields are omitted, never `null`; the builder never throws.
|
|
11
|
+
*
|
|
12
|
+
* Node-only (fs/os): never import from the client bundle.
|
|
13
|
+
* See change: scope-pids-to-namespace.
|
|
14
|
+
*/
|
|
15
|
+
import { readFileSync, readlinkSync } from "node:fs";
|
|
16
|
+
import { hostname as osHostname } from "node:os";
|
|
17
|
+
import type { PidNamespace } from "./types.js";
|
|
18
|
+
|
|
19
|
+
export type { PidNamespace } from "./types.js";
|
|
20
|
+
|
|
21
|
+
/** Injectable seams (tests); every field defaults to the real process/OS. */
|
|
22
|
+
export interface PidNamespaceOpts {
|
|
23
|
+
platform?: NodeJS.Platform | string;
|
|
24
|
+
env?: Record<string, string | undefined>;
|
|
25
|
+
readlink?: (path: string) => string;
|
|
26
|
+
readFile?: (path: string) => string;
|
|
27
|
+
hostname?: () => string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The server's own namespace, computed once at startup. */
|
|
31
|
+
export interface ServerPidContext {
|
|
32
|
+
platform: string;
|
|
33
|
+
hostId?: string;
|
|
34
|
+
nsId?: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const NS_LINK = "/proc/self/ns/pid";
|
|
38
|
+
const BOOT_ID = "/proc/sys/kernel/random/boot_id";
|
|
39
|
+
|
|
40
|
+
function attempt(read: () => string): string | undefined {
|
|
41
|
+
try {
|
|
42
|
+
const v = read().trim();
|
|
43
|
+
return v === "" ? undefined : v;
|
|
44
|
+
} catch {
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function buildPidNamespace(opts: PidNamespaceOpts = {}): PidNamespace {
|
|
50
|
+
const platform = opts.platform ?? process.platform;
|
|
51
|
+
const env = opts.env ?? process.env;
|
|
52
|
+
const readlink = opts.readlink ?? ((p: string) => readlinkSync(p));
|
|
53
|
+
const readFile = opts.readFile ?? ((p: string) => readFileSync(p, "utf8"));
|
|
54
|
+
const hostname = opts.hostname ?? osHostname;
|
|
55
|
+
|
|
56
|
+
const distro = env.WSL_DISTRO_NAME;
|
|
57
|
+
const ns: PidNamespace = distro ? { platform, kind: "wsl", distro } : { platform, kind: "host" };
|
|
58
|
+
|
|
59
|
+
if (platform === "linux") {
|
|
60
|
+
const nsId = attempt(() => readlink(NS_LINK));
|
|
61
|
+
if (nsId !== undefined) ns.nsId = nsId;
|
|
62
|
+
const hostId = attempt(() => readFile(BOOT_ID));
|
|
63
|
+
if (hostId !== undefined) ns.hostId = hostId;
|
|
64
|
+
} else {
|
|
65
|
+
const hostId = attempt(hostname);
|
|
66
|
+
if (hostId !== undefined) ns.hostId = hostId;
|
|
67
|
+
}
|
|
68
|
+
return ns;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
let processNs: PidNamespace | undefined;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* THIS process's namespace, built once and reused: every register a bridge
|
|
75
|
+
* sends (first, reattach, provisional) therefore carries the identical value.
|
|
76
|
+
*/
|
|
77
|
+
export function processPidNamespace(): PidNamespace {
|
|
78
|
+
processNs ??= buildPidNamespace();
|
|
79
|
+
return processNs;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The server's context: the same builder, reduced to the compared fields. */
|
|
83
|
+
export function buildServerPidContext(opts: PidNamespaceOpts = {}): ServerPidContext {
|
|
84
|
+
const { platform, hostId, nsId } = buildPidNamespace(opts);
|
|
85
|
+
return { platform, ...(hostId !== undefined ? { hostId } : {}), ...(nsId !== undefined ? { nsId } : {}) };
|
|
86
|
+
}
|
|
@@ -19,7 +19,7 @@ const tier = selectLoaderTier(nodeModule);
|
|
|
19
19
|
if (typeof (tier === 1 ? nodeModule.registerHooks : nodeModule.register) !== "function") {
|
|
20
20
|
throw new Error(
|
|
21
21
|
`pi-dashboard: this Node (${process.version}) lacks the module hook registration API ` +
|
|
22
|
-
"(module.registerHooks / module.register) the native TypeScript loader needs. Use a supported Node (>=
|
|
22
|
+
"(module.registerHooks / module.register) the native TypeScript loader needs. Use a supported Node (>=26.0.0 <27).",
|
|
23
23
|
);
|
|
24
24
|
}
|
|
25
25
|
|
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import fs from "node:fs";
|
|
11
|
-
import {
|
|
11
|
+
import { win32 as pathWin32 } from "node:path";
|
|
12
|
+
import { execFile as defaultExecFile, execSync } from "./exec.js";
|
|
12
13
|
|
|
13
14
|
export type ExecFn = (cmd: string, opts: { encoding: "utf-8" }) => string;
|
|
14
15
|
export type KillFn = (pid: number, signal: NodeJS.Signals | number) => void;
|
|
@@ -155,6 +156,47 @@ export function processStartedAt(pid: number, opts: ProcessStartedAtOpts = {}):
|
|
|
155
156
|
}
|
|
156
157
|
}
|
|
157
158
|
|
|
159
|
+
/** Callback-form `execFile` seam for {@link processStartedAtAsync}. */
|
|
160
|
+
export type ExecFileCbFn = (
|
|
161
|
+
file: string,
|
|
162
|
+
args: string[],
|
|
163
|
+
opts: { env?: NodeJS.ProcessEnv; timeout?: number; windowsHide?: boolean },
|
|
164
|
+
cb: (err: Error | null, stdout: string) => void,
|
|
165
|
+
) => void;
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Async {@link processStartedAt}: same result, but `ps` runs through an async
|
|
169
|
+
* `execFile` (argv, no shell, `LC_ALL=C`, bounded by `timeoutMs`) so a slow or
|
|
170
|
+
* hung `ps` never blocks the event loop — a caller's own timeout can then fire.
|
|
171
|
+
* Linux keeps the synchronous `/proc` read (no subprocess); Windows is null.
|
|
172
|
+
* Never rejects. See change: guard-restored-headless-identity.
|
|
173
|
+
*/
|
|
174
|
+
export function processStartedAtAsync(
|
|
175
|
+
pid: number,
|
|
176
|
+
opts: { platform?: NodeJS.Platform; readFile?: (path: string) => string; execFile?: ExecFileCbFn; timeoutMs?: number } = {},
|
|
177
|
+
): Promise<number | null> {
|
|
178
|
+
const platform = opts.platform ?? process.platform;
|
|
179
|
+
if (!Number.isInteger(pid) || pid <= 0 || platform === "win32") return Promise.resolve(null);
|
|
180
|
+
if (platform === "linux") return Promise.resolve(processStartedAt(pid, { platform, readFile: opts.readFile }));
|
|
181
|
+
const run = opts.execFile ?? (defaultExecFile as unknown as ExecFileCbFn);
|
|
182
|
+
return new Promise((resolve) => {
|
|
183
|
+
try {
|
|
184
|
+
run(
|
|
185
|
+
"ps",
|
|
186
|
+
["-o", "lstart=", "-p", String(pid)],
|
|
187
|
+
{ env: { ...process.env, LC_ALL: "C" }, timeout: opts.timeoutMs ?? 2000, windowsHide: true },
|
|
188
|
+
(err, stdout) => {
|
|
189
|
+
if (err) return resolve(null);
|
|
190
|
+
const ms = Date.parse(String(stdout).trim());
|
|
191
|
+
resolve(Number.isFinite(ms) ? ms : null);
|
|
192
|
+
},
|
|
193
|
+
);
|
|
194
|
+
} catch {
|
|
195
|
+
resolve(null);
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
158
200
|
/** Outcome of a signal-0 probe, distinguishing PROOF of absence from denial. */
|
|
159
201
|
export type SignalZeroOutcome = "alive" | "esrch" | "other-errno";
|
|
160
202
|
|
|
@@ -335,3 +377,364 @@ export async function killProcessGroup(
|
|
|
335
377
|
while (groupAlive() && Date.now() < killDeadline) await sleep(50);
|
|
336
378
|
return { ok: !groupAlive(), forced: true };
|
|
337
379
|
}
|
|
380
|
+
|
|
381
|
+
// ── Windows / WSL process identity + verified kill ───────────────────────────
|
|
382
|
+
// See change: add-windows-process-identity (D3, D4). Every helper below spawns
|
|
383
|
+
// an absolute-path `powershell.exe` / `wsl.exe` through ONE shared limiter and
|
|
384
|
+
// validates its inputs BEFORE anything is interpolated into a script.
|
|
385
|
+
|
|
386
|
+
/** Where a recorded pid lives: the server's own OS, or inside a WSL distribution. */
|
|
387
|
+
export type ProcessTarget = { kind: "host" } | { kind: "wsl"; distro: string };
|
|
388
|
+
|
|
389
|
+
/** Result of a verify-and-kill helper. `error` is NEVER to be read as dead. */
|
|
390
|
+
export type VerifyKillResult = "killed" | "mismatch" | "absent" | "error";
|
|
391
|
+
|
|
392
|
+
/** Tri-state WSL liveness. `unknown` reads as alive. */
|
|
393
|
+
export type WslLivenessResult = "alive" | "absent" | "unknown";
|
|
394
|
+
|
|
395
|
+
/** Async exec seam: resolves stdout on exit 0, rejects otherwise; honours `signal`. */
|
|
396
|
+
export type ProcessControlExecFn = (
|
|
397
|
+
file: string,
|
|
398
|
+
args: string[],
|
|
399
|
+
opts: { env: NodeJS.ProcessEnv; signal: AbortSignal; windowsHide: true },
|
|
400
|
+
) => Promise<string | { stdout: string }>;
|
|
401
|
+
|
|
402
|
+
export interface ProcessControlOpts {
|
|
403
|
+
/** Override platform (defaults to process.platform). */
|
|
404
|
+
platform?: NodeJS.Platform;
|
|
405
|
+
/** Override env (defaults to process.env); only `SystemRoot` is read. */
|
|
406
|
+
env?: NodeJS.ProcessEnv;
|
|
407
|
+
/** Override the async exec (for tests). */
|
|
408
|
+
execFile?: ProcessControlExecFn;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** Concurrent PowerShell / `wsl.exe` invocations allowed per server (W5). */
|
|
412
|
+
const PROCESS_CONTROL_SLOTS = 2;
|
|
413
|
+
/** Extra wrapper time a verify-and-kill gets for the in-script TERM → KILL ladder (W12). */
|
|
414
|
+
const KILL_LADDER_GRACE_MS = 10_000;
|
|
415
|
+
const DEFAULT_PROBE_TIMEOUT_MS = 10_000;
|
|
416
|
+
const DEFAULT_KILL_TIMEOUT_MS = 5_000;
|
|
417
|
+
const MAX_PID = 4_294_967_295;
|
|
418
|
+
|
|
419
|
+
let inFlight = 0;
|
|
420
|
+
const waiters: Array<() => void> = [];
|
|
421
|
+
|
|
422
|
+
/** Test hook: drop all limiter state (slots and queued waiters). */
|
|
423
|
+
export function resetProcessControlLimiter(): void {
|
|
424
|
+
inFlight = 0;
|
|
425
|
+
waiters.length = 0;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function acquireSlot(): Promise<void> {
|
|
429
|
+
if (inFlight < PROCESS_CONTROL_SLOTS) {
|
|
430
|
+
inFlight++;
|
|
431
|
+
return Promise.resolve();
|
|
432
|
+
}
|
|
433
|
+
return new Promise((resolve) => waiters.push(resolve));
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function releaseSlot(): void {
|
|
437
|
+
const next = waiters.shift();
|
|
438
|
+
if (next) next(); // the slot passes straight to the next waiter (FIFO)
|
|
439
|
+
else inFlight = Math.max(0, inFlight - 1);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function defaultProcessControlExec(
|
|
443
|
+
file: string,
|
|
444
|
+
args: string[],
|
|
445
|
+
o: { env: NodeJS.ProcessEnv; signal: AbortSignal; windowsHide: true },
|
|
446
|
+
): Promise<string> {
|
|
447
|
+
return new Promise((resolve, reject) => {
|
|
448
|
+
defaultExecFile(
|
|
449
|
+
file,
|
|
450
|
+
args,
|
|
451
|
+
{ encoding: "utf8", env: o.env, signal: o.signal, windowsHide: o.windowsHide, maxBuffer: 1024 * 1024 },
|
|
452
|
+
(err, stdout) => (err ? reject(err) : resolve(String(stdout))),
|
|
453
|
+
);
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Run `file args` under the shared limiter. `timeoutMs` starts at slot
|
|
459
|
+
* acquisition (queue wait never consumes it). Resolves the raw stdout, or
|
|
460
|
+
* `null` on any failure, timeout or rejection. Never rejects.
|
|
461
|
+
*/
|
|
462
|
+
async function runLimited(
|
|
463
|
+
file: string,
|
|
464
|
+
args: string[],
|
|
465
|
+
timeoutMs: number,
|
|
466
|
+
opts: ProcessControlOpts,
|
|
467
|
+
): Promise<string | null> {
|
|
468
|
+
await acquireSlot();
|
|
469
|
+
const controller = new AbortController();
|
|
470
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
471
|
+
try {
|
|
472
|
+
const run = opts.execFile ?? defaultProcessControlExec;
|
|
473
|
+
const exec = Promise.resolve()
|
|
474
|
+
.then(() => run(file, args, { env: opts.env ?? process.env, signal: controller.signal, windowsHide: true }))
|
|
475
|
+
.then((r) => (typeof r === "string" ? r : String(r?.stdout ?? "")));
|
|
476
|
+
exec.catch(() => undefined); // a late rejection after a timeout is not an unhandled one
|
|
477
|
+
const timeout = new Promise<null>((resolve) => {
|
|
478
|
+
timer = setTimeout(() => {
|
|
479
|
+
controller.abort();
|
|
480
|
+
resolve(null);
|
|
481
|
+
}, timeoutMs);
|
|
482
|
+
});
|
|
483
|
+
return await Promise.race([exec, timeout]).catch(() => null);
|
|
484
|
+
} finally {
|
|
485
|
+
if (timer) clearTimeout(timer);
|
|
486
|
+
releaseSlot();
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** Floor a validated non-negative number to a plain decimal integer (never exponent form). */
|
|
491
|
+
function safeInt(n: number): number {
|
|
492
|
+
return Math.min(Math.floor(n), Number.MAX_SAFE_INTEGER);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function validPid(pid: unknown): pid is number {
|
|
496
|
+
return typeof pid === "number" && Number.isInteger(pid) && pid >= 1 && pid <= MAX_PID;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function validDistro(distro: unknown): distro is string {
|
|
500
|
+
return typeof distro === "string" && /^[A-Za-z0-9._-]{1,64}$/.test(distro) && !distro.startsWith("-");
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function validTarget(target: unknown): target is ProcessTarget {
|
|
504
|
+
if (!target || typeof target !== "object") return false;
|
|
505
|
+
const t = target as { kind?: unknown; distro?: unknown };
|
|
506
|
+
return t.kind === "host" || (t.kind === "wsl" && validDistro(t.distro));
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function nonNegFinite(n: unknown): n is number {
|
|
510
|
+
return typeof n === "number" && Number.isFinite(n) && n >= 0;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function validTimeout(n: unknown): n is number {
|
|
514
|
+
return typeof n === "number" && Number.isFinite(n) && n > 0;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** Absolute `%SystemRoot%\System32\<rel>`, or null when SystemRoot is missing/relative. */
|
|
518
|
+
function systemExe(env: NodeJS.ProcessEnv, rel: string): string | null {
|
|
519
|
+
const root = env.SystemRoot ?? env.SYSTEMROOT ?? env.systemroot;
|
|
520
|
+
if (typeof root !== "string" || root === "" || !pathWin32.isAbsolute(root)) return null;
|
|
521
|
+
return pathWin32.join(root, "System32", rel);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
const POWERSHELL_REL = "WindowsPowerShell\\v1.0\\powershell.exe";
|
|
525
|
+
const PS_FLAGS = ["-NoProfile", "-NonInteractive", "-Command"];
|
|
526
|
+
|
|
527
|
+
function powershellInvocation(opts: ProcessControlOpts, script: string): { file: string; args: string[] } | null {
|
|
528
|
+
if ((opts.platform ?? process.platform) !== "win32") return null;
|
|
529
|
+
const file = systemExe(opts.env ?? process.env, POWERSHELL_REL);
|
|
530
|
+
return file ? { file, args: [...PS_FLAGS, script] } : null;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function wslInvocation(opts: ProcessControlOpts, distro: string, script: string): { file: string; args: string[] } | null {
|
|
534
|
+
if ((opts.platform ?? process.platform) !== "win32") return null;
|
|
535
|
+
const file = systemExe(opts.env ?? process.env, "wsl.exe");
|
|
536
|
+
return file ? { file, args: ["-d", distro, "--exec", "sh", "-c", script] } : null;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** The trimmed stdout, exactly one of `markers`, else null (W10: any noise is an error). */
|
|
540
|
+
function exactMarker<T extends string>(stdout: string | null, markers: readonly T[]): T | null {
|
|
541
|
+
if (stdout === null) return null;
|
|
542
|
+
const t = stdout.trim();
|
|
543
|
+
return (markers as readonly string[]).includes(t) ? (t as T) : null;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// PowerShell scripts: single quoted tokens only, numeric values interpolated
|
|
547
|
+
// AFTER validation. `$null = $p.Handle` pins the process handle so Windows
|
|
548
|
+
// cannot recycle the pid while the check and the kill run (D4).
|
|
549
|
+
const PS_START_MS = "[DateTimeOffset]::new($p.StartTime.ToUniversalTime()).ToUnixTimeMilliseconds()";
|
|
550
|
+
|
|
551
|
+
function psProbeScript(pid: number): string {
|
|
552
|
+
return `$p = Get-Process -Id ${pid} -ErrorAction SilentlyContinue; if ($null -ne $p) { ${PS_START_MS} }`;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function psVerifyKillScript(pid: number, maxStartMs: number, taskkillExe: string): string {
|
|
556
|
+
return [
|
|
557
|
+
"$ErrorActionPreference = 'Stop'",
|
|
558
|
+
`try { $p = Get-Process -Id ${pid} -ErrorAction SilentlyContinue`,
|
|
559
|
+
"if ($null -eq $p) { 'absent'; exit 0 }",
|
|
560
|
+
"$null = $p.Handle",
|
|
561
|
+
`$s = ${PS_START_MS}`,
|
|
562
|
+
`if ($s -gt ${safeInt(maxStartMs)}) { 'mismatch'; exit 0 }`,
|
|
563
|
+
// absolute System32 path: `taskkill` by bare name would resolve through the inherited PATH
|
|
564
|
+
`& '${taskkillExe.replace(/'/g, "''")}' /F /T /PID ${pid} | Out-Null`,
|
|
565
|
+
"if ($LASTEXITCODE -ne 0 -and -not $p.HasExited) { exit 1 }",
|
|
566
|
+
"'killed' } catch { exit 1 }",
|
|
567
|
+
].join("; ");
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// POSIX `sh` fragments run inside the distribution (`wsl.exe --exec sh -c`).
|
|
571
|
+
// No double quotes or backslashes: the string crosses the Windows command line.
|
|
572
|
+
const SH_PREAMBLE = "LC_ALL=C; export LC_ALL";
|
|
573
|
+
/** Reads /proc/<pid>/stat into `$1..` (field 3 onward, parsed after the LAST `)`); exits 1 when unreadable. */
|
|
574
|
+
function shStat(pid: number): string {
|
|
575
|
+
return [`st=$(cat /proc/${pid}/stat 2>/dev/null) || exit 1`, "rest=${st##*) }", "set -- $rest", "[ -n $3 ] || exit 1"].join("; ");
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** After {@link shStat}: sets `now_ms` / `start_ms` (both on the WSL clock) or exits 1. */
|
|
579
|
+
const SH_AGE = [
|
|
580
|
+
"ticks=${20}",
|
|
581
|
+
"[ -n $ticks ] || exit 1",
|
|
582
|
+
"read up _ < /proc/uptime || exit 1",
|
|
583
|
+
"hz=$(getconf CLK_TCK 2>/dev/null || echo 100)",
|
|
584
|
+
"cs=$(( 1${up#*.} - 100 ))",
|
|
585
|
+
"now_ms=$(( ${up%.*} * 1000 + cs * 10 ))",
|
|
586
|
+
"start_ms=$(( ticks * 1000 / hz ))",
|
|
587
|
+
].join("; ");
|
|
588
|
+
|
|
589
|
+
function shProbeScript(pid: number): string {
|
|
590
|
+
return [SH_PREAMBLE, shStat(pid), SH_AGE, "echo $now_ms $start_ms"].join("; ");
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/** Prints `alive | absent | unknown` from a `kill -0` under LC_ALL=C. */
|
|
594
|
+
function shLivenessScript(pid: number): string {
|
|
595
|
+
return [
|
|
596
|
+
SH_PREAMBLE,
|
|
597
|
+
`e=$(kill -0 ${pid} 2>&1)`,
|
|
598
|
+
"case $e in '') echo alive;; *'No such process'*) echo absent;; *) echo unknown;; esac",
|
|
599
|
+
].join("; ");
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
function shVerifyKillScript(pid: number, minAgeMs: number | undefined, timeoutMs: number): string {
|
|
603
|
+
const polls = Math.max(1, Math.ceil(timeoutMs / 200));
|
|
604
|
+
const parts = [
|
|
605
|
+
SH_PREAMBLE,
|
|
606
|
+
`e=$(kill -0 ${pid} 2>&1)`,
|
|
607
|
+
"case $e in '') ;; *'No such process'*) echo absent; exit 0;; *) exit 1;; esac",
|
|
608
|
+
shStat(pid),
|
|
609
|
+
];
|
|
610
|
+
if (minAgeMs !== undefined) {
|
|
611
|
+
parts.push(SH_AGE, `age_ms=$(( now_ms - start_ms ))`, `[ $age_ms -ge ${safeInt(minAgeMs)} ] || { echo mismatch; exit 0; }`);
|
|
612
|
+
}
|
|
613
|
+
// dash rejects `kill -SIG -- -N` (`--` then a negative number): pass `-N` right after the signal.
|
|
614
|
+
// Only an explicit "No such process" counts as gone; any other kill error is NOT read as dead.
|
|
615
|
+
parts.push(
|
|
616
|
+
// group-aware: only a group leader (pgrp == pid, /proc/<pid>/stat field 5) gets a group signal
|
|
617
|
+
"pg=$3",
|
|
618
|
+
`if [ $pg = ${pid} ]; then t=-${pid}; else t=${pid}; fi`,
|
|
619
|
+
// a non-leader zombie (state Z, awaiting its parent's wait) is already dead
|
|
620
|
+
`alive() { r=$(kill -0 $t 2>&1); case $r in '') ;; *'No such process'*) return 1;; esac; [ $pg != ${pid} ] || return 0; z=$(cat /proc/${pid}/stat 2>/dev/null); zr=\${z##*) }; case $zr in Z*) return 1;; esac; return 0; }`,
|
|
621
|
+
"e=$(kill -TERM $t 2>&1)",
|
|
622
|
+
"case $e in '') ;; *'No such process'*) echo absent; exit 0;; *) exit 1;; esac",
|
|
623
|
+
`i=0; while [ $i -lt ${polls} ]; do alive || { echo killed; exit 0; }; sleep 0.2; i=$((i+1)); done`,
|
|
624
|
+
"kill -KILL $t 2>/dev/null",
|
|
625
|
+
"i=0; while [ $i -lt 10 ]; do alive || { echo killed; exit 0; }; sleep 0.2; i=$((i+1)); done",
|
|
626
|
+
"exit 1",
|
|
627
|
+
);
|
|
628
|
+
return parts.join("; ");
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* Epoch-ms start time of `pid` on `target`, or null when it cannot be determined
|
|
633
|
+
* (dead pid, invalid input, wrong platform, timeout, wedged helper). Never throws.
|
|
634
|
+
*
|
|
635
|
+
* - win32 host: PowerShell `Get-Process` `.StartTime` (exact to the ms).
|
|
636
|
+
* - POSIX host: {@link processStartedAt}.
|
|
637
|
+
* - WSL `D`: the process AGE measured inside `D` carried onto the server clock
|
|
638
|
+
* (`Date.now() − age`), so WSL ↔ Windows clock skew cancels out.
|
|
639
|
+
*
|
|
640
|
+
* Counts against the shared limiter (win32 / WSL only). See change:
|
|
641
|
+
* add-windows-process-identity.
|
|
642
|
+
*/
|
|
643
|
+
export async function probeProcessStart(
|
|
644
|
+
pid: number,
|
|
645
|
+
target: ProcessTarget,
|
|
646
|
+
opts: ProcessControlOpts & { timeoutMs?: number; processStartedAt?: (pid: number) => number | null | Promise<number | null> } = {},
|
|
647
|
+
): Promise<number | null> {
|
|
648
|
+
if (!validPid(pid) || !validTarget(target)) return null;
|
|
649
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
|
|
650
|
+
if (!validTimeout(timeoutMs)) return null;
|
|
651
|
+
const platform = opts.platform ?? process.platform;
|
|
652
|
+
if (target.kind === "host" && platform !== "win32") {
|
|
653
|
+
try {
|
|
654
|
+
return await (opts.processStartedAt
|
|
655
|
+
? opts.processStartedAt(pid)
|
|
656
|
+
: processStartedAtAsync(pid, { platform, timeoutMs }));
|
|
657
|
+
} catch {
|
|
658
|
+
return null;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
if (target.kind === "host") {
|
|
662
|
+
const inv = powershellInvocation(opts, psProbeScript(pid));
|
|
663
|
+
if (!inv) return null;
|
|
664
|
+
const out = await runLimited(inv.file, inv.args, timeoutMs, opts);
|
|
665
|
+
const t = out?.trim();
|
|
666
|
+
if (!t || !/^\d+$/.test(t)) return null;
|
|
667
|
+
const ms = Number(t);
|
|
668
|
+
return Number.isSafeInteger(ms) ? ms : null;
|
|
669
|
+
}
|
|
670
|
+
const inv = wslInvocation(opts, target.distro, shProbeScript(pid));
|
|
671
|
+
if (!inv) return null;
|
|
672
|
+
const out = await runLimited(inv.file, inv.args, timeoutMs, opts);
|
|
673
|
+
const sampledAt = Date.now();
|
|
674
|
+
const m = out === null ? null : /^(\d+) (\d+)$/.exec(out.trim());
|
|
675
|
+
if (!m) return null;
|
|
676
|
+
const age = Number(m[1]) - Number(m[2]);
|
|
677
|
+
if (!Number.isFinite(age) || age < 0) return null;
|
|
678
|
+
return sampledAt - age;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/**
|
|
682
|
+
* Verify identity and kill the process tree of `pid` in ONE PowerShell
|
|
683
|
+
* invocation (win32 host only): the handle is pinned, `StartTime ≤ maxStartMs`
|
|
684
|
+
* is checked, then `taskkill /F /T` runs while the handle is still open — so
|
|
685
|
+
* pid reuse cannot redirect the kill. `error` is never to be read as dead.
|
|
686
|
+
* See change: add-windows-process-identity (D4).
|
|
687
|
+
*/
|
|
688
|
+
export async function verifyAndKillWindows(
|
|
689
|
+
pid: number,
|
|
690
|
+
opts: ProcessControlOpts & { maxStartMs: number; timeoutMs?: number },
|
|
691
|
+
): Promise<VerifyKillResult> {
|
|
692
|
+
const timeoutMs = opts?.timeoutMs ?? DEFAULT_KILL_TIMEOUT_MS;
|
|
693
|
+
if (!validPid(pid) || !nonNegFinite(opts?.maxStartMs) || !validTimeout(timeoutMs)) return "error";
|
|
694
|
+
const taskkillExe = systemExe(opts.env ?? process.env, "taskkill.exe");
|
|
695
|
+
if (!taskkillExe) return "error";
|
|
696
|
+
const inv = powershellInvocation(opts, psVerifyKillScript(pid, opts.maxStartMs, taskkillExe));
|
|
697
|
+
if (!inv) return "error";
|
|
698
|
+
const out = await runLimited(inv.file, inv.args, timeoutMs + KILL_LADDER_GRACE_MS, opts);
|
|
699
|
+
return exactMarker(out, ["killed", "mismatch", "absent"] as const) ?? "error";
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* Tri-state liveness of a WSL pid, decided ONLY inside the distribution.
|
|
704
|
+
* `absent` only on the script's explicit marker; any failure/timeout is
|
|
705
|
+
* `unknown`, which reads as alive. See change: add-windows-process-identity.
|
|
706
|
+
*/
|
|
707
|
+
export async function wslLiveness(
|
|
708
|
+
pid: number,
|
|
709
|
+
distro: string,
|
|
710
|
+
opts: ProcessControlOpts & { timeoutMs?: number } = {},
|
|
711
|
+
): Promise<WslLivenessResult> {
|
|
712
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
|
|
713
|
+
if (!validPid(pid) || !validDistro(distro) || !validTimeout(timeoutMs)) return "unknown";
|
|
714
|
+
const inv = wslInvocation(opts, distro, shLivenessScript(pid));
|
|
715
|
+
if (!inv) return "unknown";
|
|
716
|
+
const out = await runLimited(inv.file, inv.args, timeoutMs, opts);
|
|
717
|
+
return exactMarker(out, ["alive", "absent"] as const) ?? "unknown";
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/**
|
|
721
|
+
* Verify identity and kill `pid` inside WSL distribution `distro` in ONE
|
|
722
|
+
* `sh -c`: optional age check (`minAgeMs`, an AGE not a time, so clock skew is
|
|
723
|
+
* irrelevant), then a group-aware SIGTERM → poll → SIGKILL. The group leader is
|
|
724
|
+
* read from `/proc/<pid>/stat` (no `ps`). `error` is never to be read as dead.
|
|
725
|
+
* Residual: the few ms between the in-script check and `kill` inside one shell.
|
|
726
|
+
* See change: add-windows-process-identity (D4).
|
|
727
|
+
*/
|
|
728
|
+
export async function verifyAndKillWsl(
|
|
729
|
+
pid: number,
|
|
730
|
+
distro: string,
|
|
731
|
+
opts: ProcessControlOpts & { minAgeMs?: number; timeoutMs?: number } = {},
|
|
732
|
+
): Promise<VerifyKillResult> {
|
|
733
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_KILL_TIMEOUT_MS;
|
|
734
|
+
if (!validPid(pid) || !validDistro(distro) || !validTimeout(timeoutMs)) return "error";
|
|
735
|
+
if (opts.minAgeMs !== undefined && !nonNegFinite(opts.minAgeMs)) return "error";
|
|
736
|
+
const inv = wslInvocation(opts, distro, shVerifyKillScript(pid, opts.minAgeMs, timeoutMs));
|
|
737
|
+
if (!inv) return "error";
|
|
738
|
+
const out = await runLimited(inv.file, inv.args, timeoutMs + KILL_LADDER_GRACE_MS, opts);
|
|
739
|
+
return exactMarker(out, ["killed", "mismatch", "absent"] as const) ?? "error";
|
|
740
|
+
}
|