@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
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `ensureWorktree`: create-or-reuse a worktree for a branch on behalf of a
|
|
3
|
+
* plugin spawn. A thin, never-throwing wrapper over `listWorktrees` +
|
|
4
|
+
* `addWorktree` (the functions `POST /api/git/worktree` uses), adding known-folder
|
|
5
|
+
* admission, ref validation, reuse containment under `<main>/.worktrees/`, and a
|
|
6
|
+
* per-repo lock. Returns a typed result; every failure maps to a public code.
|
|
7
|
+
*
|
|
8
|
+
* See change: add-plugin-spawn-worktree (design D1, D3, D4, D5).
|
|
9
|
+
*/
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { type Admission, type AdmitCwdOptions, admissionAllows, releaseAdmission } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
|
|
13
|
+
import { slugifyBranch } from "@blackbelt-technology/pi-dashboard-shared/git-worktree-helpers.js";
|
|
14
|
+
import { execFileSync } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
|
|
15
|
+
import { admitRouteCwd } from "../lib/route-admission.js";
|
|
16
|
+
import { safeRealpathSync } from "../resolve-path.js";
|
|
17
|
+
import {
|
|
18
|
+
type AddWorktreeError,
|
|
19
|
+
addWorktree,
|
|
20
|
+
listWorktrees,
|
|
21
|
+
pruneWorktrees,
|
|
22
|
+
resolveDefaultBase,
|
|
23
|
+
resolveMainPath,
|
|
24
|
+
} from "./git-operations.js";
|
|
25
|
+
import type { WorktreeEntry } from "./git-worktree.js";
|
|
26
|
+
import { isValidRefArg } from "./ref-arg.js";
|
|
27
|
+
import { repoLockKey, withRepoLock } from "./repo-lock.js";
|
|
28
|
+
|
|
29
|
+
type EnsureWorktreeCode =
|
|
30
|
+
| "not_git"
|
|
31
|
+
| "admission_unavailable"
|
|
32
|
+
| "branch_invalid"
|
|
33
|
+
| "exists"
|
|
34
|
+
| "base_not_found"
|
|
35
|
+
| "branch_in_use"
|
|
36
|
+
| "policy_mismatch"
|
|
37
|
+
| "git_failed";
|
|
38
|
+
|
|
39
|
+
export type EnsureWorktreeResult =
|
|
40
|
+
| { ok: true; path: string; branch: string; created: boolean }
|
|
41
|
+
| { ok: false; code: EnsureWorktreeCode; message: string };
|
|
42
|
+
|
|
43
|
+
export interface EnsureWorktreeOptions {
|
|
44
|
+
/** Directory inside the repository (a plugin's spawn `cwd`). Admitted against `knownCwds`. */
|
|
45
|
+
cwd: string;
|
|
46
|
+
branch: string;
|
|
47
|
+
/** Fork point for a brand-new branch only; ignored when the branch or worktree already exists. */
|
|
48
|
+
base?: string;
|
|
49
|
+
ifExists: "reuse" | "fail";
|
|
50
|
+
/** Host cwd-policy check on the target worktree path; `false` → `policy_mismatch`. Runs before any git write. */
|
|
51
|
+
checkTarget?: (target: string) => boolean;
|
|
52
|
+
/** Live known-folder set (same set the git routes admit against). Fail-closed default: nothing is known. */
|
|
53
|
+
knownCwds?: () => string[];
|
|
54
|
+
admitOptions?: AdmitCwdOptions;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Seams for tests; every default is the real implementation. */
|
|
58
|
+
export interface EnsureWorktreeDeps {
|
|
59
|
+
admit?: (cwd: string) => Promise<Admission>;
|
|
60
|
+
listWorktrees?: typeof listWorktrees;
|
|
61
|
+
addWorktree?: typeof addWorktree;
|
|
62
|
+
prune?: (cwd: string) => unknown;
|
|
63
|
+
resolveDefaultBase?: typeof resolveDefaultBase;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const GIT_TIMEOUT = 15_000;
|
|
67
|
+
|
|
68
|
+
/** Run git with argv (no shell); true iff it exits 0. */
|
|
69
|
+
function gitOk(args: string[], cwd: string): boolean {
|
|
70
|
+
try {
|
|
71
|
+
execFileSync("git", args, { cwd, stdio: ["ignore", "pipe", "pipe"], timeout: GIT_TIMEOUT });
|
|
72
|
+
return true;
|
|
73
|
+
} catch {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const fail = (code: EnsureWorktreeCode, message: string): EnsureWorktreeResult => ({ ok: false, code, message });
|
|
79
|
+
|
|
80
|
+
/** True iff `child` is strictly inside `dir` (both resolved; symlink-safe for existing paths). */
|
|
81
|
+
function isInside(dir: string, child: string): boolean {
|
|
82
|
+
const rel = path.relative(safeRealpathSync(dir), safeRealpathSync(child));
|
|
83
|
+
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Branch name safe to hand to git as a positional ref: argv-safe, a legal ref name, no `@{…}` shorthand. */
|
|
87
|
+
function isLegalBranch(branch: string, cwd: string): boolean {
|
|
88
|
+
if (!isValidRefArg(branch) || branch.includes("@{")) return false;
|
|
89
|
+
return gitOk(["check-ref-format", "--branch", branch], cwd);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const ADD_ERROR_CODE: Record<AddWorktreeError, EnsureWorktreeCode> = {
|
|
93
|
+
not_a_repo: "not_git",
|
|
94
|
+
cwd_invalid: "not_git",
|
|
95
|
+
invalid_ref: "branch_invalid",
|
|
96
|
+
branch_in_use: "branch_in_use",
|
|
97
|
+
branch_exists: "git_failed",
|
|
98
|
+
path_exists: "git_failed",
|
|
99
|
+
base_not_found: "base_not_found",
|
|
100
|
+
git_failed: "git_failed",
|
|
101
|
+
git_not_found: "git_failed",
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
export async function ensureWorktree(opts: EnsureWorktreeOptions, deps: EnsureWorktreeDeps = {}): Promise<EnsureWorktreeResult> {
|
|
105
|
+
try {
|
|
106
|
+
return await run(opts, deps);
|
|
107
|
+
} catch (err) {
|
|
108
|
+
return fail("git_failed", err instanceof Error ? err.message : String(err));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function run(opts: EnsureWorktreeOptions, deps: EnsureWorktreeDeps): Promise<EnsureWorktreeResult> {
|
|
113
|
+
const { branch, base, ifExists } = opts;
|
|
114
|
+
const admit = deps.admit ?? ((c: string) => admitRouteCwd(c, { knownCwds: opts.knownCwds, admitOptions: opts.admitOptions }));
|
|
115
|
+
const list = deps.listWorktrees ?? listWorktrees;
|
|
116
|
+
const add = deps.addWorktree ?? addWorktree;
|
|
117
|
+
const prune = deps.prune ?? pruneWorktrees;
|
|
118
|
+
const defaultBase = deps.resolveDefaultBase ?? resolveDefaultBase;
|
|
119
|
+
|
|
120
|
+
// Admission: the same known-folder rule the route applies, released in `finally`.
|
|
121
|
+
const admission = await admit(opts.cwd);
|
|
122
|
+
try {
|
|
123
|
+
if (admission.kind === "indeterminate") return fail("admission_unavailable", "cwd admission could not be decided right now");
|
|
124
|
+
if (admission.kind !== "admit" || !admissionAllows(admission, opts.cwd)) return fail("not_git", "cwd is not a known git folder");
|
|
125
|
+
const cwd = admission.token.canonCwd;
|
|
126
|
+
if (!fs.statSync(cwd, { throwIfNoEntry: false })?.isDirectory()) return fail("not_git", "cwd is not a directory");
|
|
127
|
+
|
|
128
|
+
const main = resolveMainPath(cwd);
|
|
129
|
+
if (!main) return fail("not_git", "not a git repository");
|
|
130
|
+
|
|
131
|
+
// Validation: every check below runs before any mutating git call.
|
|
132
|
+
if (!isLegalBranch(branch, cwd)) return fail("branch_invalid", "invalid branch name");
|
|
133
|
+
if (base !== undefined && !isValidRefArg(base)) return fail("branch_invalid", "invalid base ref");
|
|
134
|
+
const slug = slugifyBranch(branch);
|
|
135
|
+
const worktreesDir = path.join(main, ".worktrees");
|
|
136
|
+
const derived = path.join(worktreesDir, slug);
|
|
137
|
+
if (!slug || !isInside(worktreesDir, derived) || path.resolve(derived) !== derived) {
|
|
138
|
+
return fail("branch_invalid", "branch does not map to a path under .worktrees/");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return await withRepoLock(repoLockKey(cwd), async () => {
|
|
142
|
+
const policyOk = (target: string) => opts.checkTarget?.(target) !== false;
|
|
143
|
+
|
|
144
|
+
// Step 1: an existing registration for the branch (bare-name match).
|
|
145
|
+
let entries: WorktreeEntry[] = list(cwd);
|
|
146
|
+
let match = entries.find((e) => e.branch === branch);
|
|
147
|
+
if (match && (match.isMain || !isInside(worktreesDir, match.path))) {
|
|
148
|
+
return fail("branch_in_use", "branch is checked out outside the worktree directory");
|
|
149
|
+
}
|
|
150
|
+
if (match && match.exists === false) {
|
|
151
|
+
if (!policyOk(derived)) return fail("policy_mismatch", "target is outside the caller's cwd policy");
|
|
152
|
+
prune(cwd);
|
|
153
|
+
entries = list(cwd);
|
|
154
|
+
match = entries.find((e) => e.branch === branch);
|
|
155
|
+
if (match && match.exists === false) return fail("git_failed", "stale worktree registration could not be pruned");
|
|
156
|
+
}
|
|
157
|
+
if (match) {
|
|
158
|
+
if (ifExists === "fail") return fail("exists", "a worktree for this branch already exists");
|
|
159
|
+
if (!policyOk(match.path)) return fail("policy_mismatch", "target is outside the caller's cwd policy");
|
|
160
|
+
return { ok: true, path: match.path, branch, created: false };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (!policyOk(derived)) return fail("policy_mismatch", "target is outside the caller's cwd policy");
|
|
164
|
+
|
|
165
|
+
// Steps 2-4: pick the add mode. An existing local branch is checked out, an origin-only
|
|
166
|
+
// branch is continued from `origin/<branch>`, anything else forks `base` (verified here only).
|
|
167
|
+
let added: ReturnType<typeof addWorktree>;
|
|
168
|
+
if (gitOk(["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], cwd)) {
|
|
169
|
+
added = add({ cwd, base: branch });
|
|
170
|
+
} else if (gitOk(["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`], cwd)) {
|
|
171
|
+
added = add({ cwd, base: `origin/${branch}`, newBranch: branch });
|
|
172
|
+
} else {
|
|
173
|
+
const from = base ?? defaultBase(cwd);
|
|
174
|
+
if (!from || !gitOk(["rev-parse", "--verify", "--end-of-options", `${from}^{commit}`], cwd)) {
|
|
175
|
+
return fail("base_not_found", "base ref not found");
|
|
176
|
+
}
|
|
177
|
+
added = add({ cwd, base: from, newBranch: branch });
|
|
178
|
+
}
|
|
179
|
+
if (!added.ok) return fail(ADD_ERROR_CODE[added.error] ?? "git_failed", added.message);
|
|
180
|
+
return { ok: true, path: added.path, branch, created: true };
|
|
181
|
+
});
|
|
182
|
+
} finally {
|
|
183
|
+
if (admission.kind === "admit") releaseAdmission(admission.token);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -1032,7 +1032,7 @@ export interface LifecycleFailure<C extends string = string> {
|
|
|
1032
1032
|
* (the `info/exclude` write) — the AUTHORIZATION anchor is
|
|
1033
1033
|
* `resolveMainPath`.
|
|
1034
1034
|
*/
|
|
1035
|
-
function resolveCommonDirAbs(cwd: string): string | null {
|
|
1035
|
+
export function resolveCommonDirAbs(cwd: string): string | null {
|
|
1036
1036
|
const raw = tryRun(["git", "rev-parse", "--path-format=absolute", "--git-common-dir"], cwd);
|
|
1037
1037
|
if (!raw) return null;
|
|
1038
1038
|
return path.isAbsolute(raw) ? raw : path.resolve(cwd, raw);
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-repository async mutex for worktree create-or-reuse. Keyed by the
|
|
3
|
+
* repository's resolved common git dir, so every worktree of one repo shares a
|
|
4
|
+
* key. `POST /api/git/worktree` and `ensureWorktree` both take it, so a dialog
|
|
5
|
+
* create and a plugin create for one repo serialize.
|
|
6
|
+
*
|
|
7
|
+
* See change: add-plugin-spawn-worktree (D4).
|
|
8
|
+
*/
|
|
9
|
+
import { safeRealpathSync } from "../resolve-path.js";
|
|
10
|
+
import { resolveCommonDirAbs } from "./git-operations.js";
|
|
11
|
+
|
|
12
|
+
const tails = new Map<string, Promise<unknown>>();
|
|
13
|
+
const depths = new Map<string, number>();
|
|
14
|
+
|
|
15
|
+
/** Calls currently holding or waiting for `key`'s lock (0 when idle). Lets a test observe that a caller has queued. */
|
|
16
|
+
export function repoLockDepth(key: string): number {
|
|
17
|
+
return depths.get(key) ?? 0;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Lock key for the repository containing `cwd` (falls back to `cwd` when it has no resolvable common dir). */
|
|
21
|
+
export function repoLockKey(cwd: string): string {
|
|
22
|
+
const common = resolveCommonDirAbs(cwd);
|
|
23
|
+
return safeRealpathSync(common ?? cwd);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Run `fn` once every earlier holder of `key` has finished. A throwing `fn` releases the lock and rethrows. */
|
|
27
|
+
export async function withRepoLock<T>(key: string, fn: () => Promise<T> | T): Promise<T> {
|
|
28
|
+
const prev = tails.get(key) ?? Promise.resolve();
|
|
29
|
+
const run = prev.then(fn);
|
|
30
|
+
const tail = run.catch(() => undefined);
|
|
31
|
+
tails.set(key, tail);
|
|
32
|
+
depths.set(key, repoLockDepth(key) + 1);
|
|
33
|
+
try {
|
|
34
|
+
return await run;
|
|
35
|
+
} finally {
|
|
36
|
+
const left = repoLockDepth(key) - 1;
|
|
37
|
+
if (left > 0) depths.set(key, left);
|
|
38
|
+
else depths.delete(key);
|
|
39
|
+
// Drop the entry once nobody queued behind us, so the map stays bounded.
|
|
40
|
+
if (tails.get(key) === tail) tails.delete(key);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared worktree-init run starter: the trust check → gate → run → broadcast body
|
|
3
|
+
* of `POST /api/git/worktree/init`, extracted so the plugin-spawn hook starts the
|
|
4
|
+
* SAME run (config-root resolution, TOFU trust, gate cache, registry run state,
|
|
5
|
+
* `sendCwd` broadcast, stderr redaction) instead of re-implementing it.
|
|
6
|
+
*
|
|
7
|
+
* Trust is only ever CHECKED here, never granted: granting (`confirmHash`, scope,
|
|
8
|
+
* pi mirror) stays in the route, which owns the request that carries the consent.
|
|
9
|
+
*
|
|
10
|
+
* See change: generalize-worktree-init-hook, add-plugin-spawn-worktree (design D6).
|
|
11
|
+
*/
|
|
12
|
+
import { resolveConfigRoot } from "./git-operations.js";
|
|
13
|
+
import { redactGitText } from "./redact-git-text.js";
|
|
14
|
+
import {
|
|
15
|
+
evaluateGate,
|
|
16
|
+
type GateResult,
|
|
17
|
+
hookDefHash,
|
|
18
|
+
type InitProgress,
|
|
19
|
+
readInitHook,
|
|
20
|
+
runInitHook,
|
|
21
|
+
type WorktreeInitHook,
|
|
22
|
+
} from "./worktree-init.js";
|
|
23
|
+
import { mapInitStderrToHint } from "./worktree-init-errors.js";
|
|
24
|
+
import type { WorktreeInitRegistry } from "./worktree-init-registry.js";
|
|
25
|
+
import { isTrusted } from "./worktree-init-trust.js";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Per-resolved-checkout cache of the gate result, with a short TTL, keyed by the hook definition it
|
|
29
|
+
* was evaluated for (a different hook for the same checkout must evaluate its own gate).
|
|
30
|
+
* Invalidated when a hook run starts/exits for that checkout.
|
|
31
|
+
* See change: generalize-worktree-init-hook.
|
|
32
|
+
*/
|
|
33
|
+
const GATE_CACHE_TTL_MS = 30 * 1000;
|
|
34
|
+
const gateCache = new Map<string, { hash: string; needsInit: boolean; evaluatedAt: number }>();
|
|
35
|
+
export function invalidateGateCache(checkoutPath: string): void {
|
|
36
|
+
gateCache.delete(checkoutPath);
|
|
37
|
+
}
|
|
38
|
+
export async function evaluateGateCached(checkoutPath: string, hook: WorktreeInitHook): Promise<GateResult> {
|
|
39
|
+
const hash = hookDefHash(hook);
|
|
40
|
+
const hit = gateCache.get(checkoutPath);
|
|
41
|
+
if (hit && hit.hash === hash && Date.now() - hit.evaluatedAt < GATE_CACHE_TTL_MS) return { needsInit: hit.needsInit };
|
|
42
|
+
const res = await evaluateGate(checkoutPath, hook);
|
|
43
|
+
gateCache.set(checkoutPath, { hash, needsInit: res.needsInit, evaluatedAt: Date.now() });
|
|
44
|
+
return res;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Last non-empty line of the progress tail, for the ghost preview. The tail is
|
|
49
|
+
* the most recent <= 4KB of combined output; the chip shows only its final line.
|
|
50
|
+
* See change: friendlier-worktree-init.
|
|
51
|
+
*/
|
|
52
|
+
function lastLineOf(tail: string): string {
|
|
53
|
+
const lines = tail.split(/\r?\n/);
|
|
54
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
55
|
+
const line = lines[i]?.trim();
|
|
56
|
+
if (line) return line;
|
|
57
|
+
}
|
|
58
|
+
return "";
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface StartWorktreeInitOptions {
|
|
62
|
+
registry?: WorktreeInitRegistry;
|
|
63
|
+
/** Legacy per-click subscriber id; echoed on the progress/done/failed broadcasts. */
|
|
64
|
+
requestId?: string;
|
|
65
|
+
/** Return `already_running` instead of restarting when the registry holds a running run for `cwd`. */
|
|
66
|
+
skipIfRunning?: boolean;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export type StartWorktreeInitResult =
|
|
70
|
+
| { status: "no_hook" }
|
|
71
|
+
| { status: "untrusted"; hook: WorktreeInitHook; hash: string }
|
|
72
|
+
| { status: "already_initialized" }
|
|
73
|
+
| { status: "already_running" }
|
|
74
|
+
| { status: "done"; durationMs: number }
|
|
75
|
+
| { status: "failed"; code: string; hint: string; stderr: string };
|
|
76
|
+
|
|
77
|
+
/** `cwd` must be a canonical (admitted / worktree) checkout path: it keys the registry and the gate cache. */
|
|
78
|
+
export async function startWorktreeInit(cwd: string, opts: StartWorktreeInitOptions = {}): Promise<StartWorktreeInitResult> {
|
|
79
|
+
const { registry, requestId, skipIfRunning } = opts;
|
|
80
|
+
const redact = (text: unknown) => redactGitText(text, { root: cwd });
|
|
81
|
+
const configRoot = resolveConfigRoot(cwd);
|
|
82
|
+
if (!configRoot) return { status: "no_hook" };
|
|
83
|
+
const hook = readInitHook(configRoot);
|
|
84
|
+
if (!hook) return { status: "no_hook" };
|
|
85
|
+
const hash = hookDefHash(hook);
|
|
86
|
+
if (!isTrusted(configRoot, hash)) {
|
|
87
|
+
// Echo the hash so the client confirms with `confirmHash` without re-implementing the canonical hash.
|
|
88
|
+
return { status: "untrusted", hook, hash };
|
|
89
|
+
}
|
|
90
|
+
// Re-trust case: the hook was edited (invalidating trust) but the gate is already satisfied
|
|
91
|
+
// (`needsInit === false`). Granting trust should clear the control WITHOUT re-running the hook.
|
|
92
|
+
const preGate = await evaluateGateCached(cwd, hook);
|
|
93
|
+
// A live run wins over a satisfied gate: a hook can create its gate artifact (e.g. `node_modules`) mid-run,
|
|
94
|
+
// and a skipIfRunning caller must still wait for the run. Checked synchronously before `startRun`.
|
|
95
|
+
if (skipIfRunning && registry?.getActiveRuns().some((r) => r.cwd === cwd && r.phase === "running")) {
|
|
96
|
+
return { status: "already_running" };
|
|
97
|
+
}
|
|
98
|
+
if (!preGate.needsInit) return { status: "already_initialized" };
|
|
99
|
+
// Fan out to the legacy per-click requestId subscriber (if any) AND to
|
|
100
|
+
// every cwd-keyed subscriber (refresh / second tab / auto-init).
|
|
101
|
+
const sendIf = (msg: any) => {
|
|
102
|
+
if (registry) {
|
|
103
|
+
if (requestId) registry.send(requestId, msg);
|
|
104
|
+
registry.sendCwd(cwd, msg);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
registry?.startRun(cwd);
|
|
108
|
+
const onProgress = (p: InitProgress) => {
|
|
109
|
+
registry?.progressRun(cwd, lastLineOf(p.line), p.line);
|
|
110
|
+
sendIf({ type: "worktree_init_progress", requestId: requestId ?? "", cwd, line: p.line });
|
|
111
|
+
};
|
|
112
|
+
invalidateGateCache(cwd);
|
|
113
|
+
const runResult = await runInitHook(cwd, hook, onProgress);
|
|
114
|
+
invalidateGateCache(cwd);
|
|
115
|
+
if (runResult.ok) {
|
|
116
|
+
registry?.finishRun(cwd, "done");
|
|
117
|
+
sendIf({ type: "worktree_init_done", requestId: requestId ?? "", cwd, durationMs: runResult.durationMs });
|
|
118
|
+
return { status: "done", durationMs: runResult.durationMs };
|
|
119
|
+
}
|
|
120
|
+
// B20: the mapper sees the RAW stderr (so it can match paths); BOTH the mapped hint and the
|
|
121
|
+
// stderr are redacted AFTER mapping, against the checkout the hook ran in (`cwd`).
|
|
122
|
+
const rawStderr = runResult.stderr ?? "";
|
|
123
|
+
const hint = redact(mapInitStderrToHint(rawStderr) ?? `init failed (${runResult.code ?? "unknown"})`);
|
|
124
|
+
const stderr = redact(rawStderr);
|
|
125
|
+
const code = runResult.code ?? "init_failed";
|
|
126
|
+
registry?.finishRun(cwd, "failed", code);
|
|
127
|
+
sendIf({ type: "worktree_init_failed", requestId: requestId ?? "", cwd, code, message: hint, stderr });
|
|
128
|
+
return { status: "failed", code, hint, stderr };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Wait for the run the registry reported as running for `cwd`: resolves its terminal phase (`done` /
|
|
133
|
+
* `failed`), or `timeout` when it does not finish in time OR its entry is gone before a terminal phase
|
|
134
|
+
* was observed (evicted: the outcome is unknown, never assumed to be success). Used by the plugin-spawn
|
|
135
|
+
* hook when another trigger (the browser) started the run first, so an unattended prompt never races
|
|
136
|
+
* `pnpm install`.
|
|
137
|
+
*/
|
|
138
|
+
export async function awaitInitRun(
|
|
139
|
+
registry: WorktreeInitRegistry,
|
|
140
|
+
cwd: string,
|
|
141
|
+
{ timeoutMs = 10 * 60_000, pollMs = 500 }: { timeoutMs?: number; pollMs?: number } = {},
|
|
142
|
+
): Promise<"done" | "failed" | "timeout"> {
|
|
143
|
+
const deadline = Date.now() + timeoutMs;
|
|
144
|
+
for (;;) {
|
|
145
|
+
const run = registry.getActiveRuns().find((r) => r.cwd === cwd);
|
|
146
|
+
if (!run) return "timeout";
|
|
147
|
+
if (run.phase !== "running") return run.phase === "failed" ? "failed" : "done";
|
|
148
|
+
if (Date.now() >= deadline) return "timeout";
|
|
149
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
150
|
+
}
|
|
151
|
+
}
|
|
@@ -24,6 +24,7 @@ import { spawn } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.j
|
|
|
24
24
|
import type { ChildProcess, SpawnOptions } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
|
|
25
25
|
import { getDefaultRegistry } from "@blackbelt-technology/pi-dashboard-shared/tool-registry/index.js";
|
|
26
26
|
import { stripDashboardHeapFlag } from "@blackbelt-technology/pi-dashboard-shared/heap-flags.js";
|
|
27
|
+
import { normalizeCwdKey } from "../spawn-process/spawn-register-watchdog.js";
|
|
27
28
|
|
|
28
29
|
/**
|
|
29
30
|
* Default env for every hook child (gate, script run, agent spawn): a COPY of
|
|
@@ -343,7 +344,10 @@ async function runAgent(
|
|
|
343
344
|
try {
|
|
344
345
|
child = spawnFn(piBin, args, {
|
|
345
346
|
cwd,
|
|
346
|
-
|
|
347
|
+
// pi is exec'd without a shell, so nothing re-derives PWD: name the
|
|
348
|
+
// checkout. Gate/script (`bash -c`) envs stay as-is. See change:
|
|
349
|
+
// fix-spawned-session-pwd (D2b).
|
|
350
|
+
env: opts.env ?? { ...defaultHookEnv(), PWD: normalizeCwdKey(path.resolve(cwd)) },
|
|
347
351
|
detached: true,
|
|
348
352
|
stdio: ["ignore", logFd ?? "ignore", logFd ?? "ignore"],
|
|
349
353
|
} as SpawnOptions);
|
|
@@ -73,6 +73,8 @@ const FAMILY_BY_SEGMENT: Readonly<Record<string, Family>> = {
|
|
|
73
73
|
// providers / models
|
|
74
74
|
providers: "providers",
|
|
75
75
|
"provider-auth": "providers",
|
|
76
|
+
// See change: add-provider-advanced-settings.
|
|
77
|
+
"provider-overrides": "providers",
|
|
76
78
|
models: "providers",
|
|
77
79
|
"model-proxy": "providers",
|
|
78
80
|
// packages / runtimes / tools
|
|
@@ -130,6 +132,8 @@ const FAMILY_BY_SEGMENT: Readonly<Record<string, Family>> = {
|
|
|
130
132
|
// Operator reset of the persisted baseline CSP report counters (change: harden-cors-and-csp-reporting).
|
|
131
133
|
"csp-reports": "system",
|
|
132
134
|
"nav-intent": "system",
|
|
135
|
+
// Framing probe for web-link previews: one outbound HEAD per operator click (change: rich-chat-links).
|
|
136
|
+
web: "system",
|
|
133
137
|
};
|
|
134
138
|
|
|
135
139
|
// `/api/pi-trust/query` is the bridge's own credentialed call, classified like the ticket mint
|
|
@@ -167,7 +171,7 @@ export function classifyHttpRoad(
|
|
|
167
171
|
if (route.startsWith("/editor/")) {
|
|
168
172
|
return { road: "non-session", action: "editor.write", resource: { kind: "editor", route } };
|
|
169
173
|
}
|
|
170
|
-
if (route.startsWith("/live/")) {
|
|
174
|
+
if (route.startsWith("/live/") || route.startsWith("/preview/")) {
|
|
171
175
|
return { road: "non-session", action: `live.${verbOf(method)}`, resource: { kind: "live", route } };
|
|
172
176
|
}
|
|
173
177
|
if (!route.startsWith("/api/")) return undefined;
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* target is governed when EITHER its raw or dot-resolved form is, and public
|
|
14
14
|
* only when BOTH are. Unparseable ⇒ governed (fail closed).
|
|
15
15
|
*/
|
|
16
|
-
import { parseGuardTarget } from "../auth/localhost-guard.js";
|
|
16
|
+
import { PUBLIC_PLUGIN_CALLBACK_PATHS, parseGuardTarget } from "../auth/localhost-guard.js";
|
|
17
17
|
|
|
18
18
|
const FLOOR_PREFIXES = ["/api/", "/editor/", "/live/"] as const;
|
|
19
19
|
const PRE_AUTH_PATHS: ReadonlySet<string> = new Set(["/api/health", "/api/identity/login-config"]);
|
|
@@ -39,6 +39,9 @@ export function identityFloorAllows(input: {
|
|
|
39
39
|
if (!target) return false;
|
|
40
40
|
if (!governed(target.raw) && !governed(target.resolved)) return true;
|
|
41
41
|
const readOnly = input.method === "GET" || input.method === "HEAD";
|
|
42
|
-
if (readOnly)
|
|
42
|
+
if (readOnly) {
|
|
43
|
+
const open = (p: string) => PRE_AUTH_PATHS.has(p) || PUBLIC_PLUGIN_CALLBACK_PATHS.has(p);
|
|
44
|
+
return open(target.raw) && open(target.resolved);
|
|
45
|
+
}
|
|
43
46
|
return input.method === "POST" && PRE_AUTH_POST_PATHS.has(target.raw) && PRE_AUTH_POST_PATHS.has(target.resolved);
|
|
44
47
|
}
|
|
@@ -35,12 +35,15 @@ export const SESSION_OWNED_MESSAGES: ReadonlySet<string> = new Set([
|
|
|
35
35
|
"archive_session",
|
|
36
36
|
"attach_proposal",
|
|
37
37
|
"clear_followup_entries",
|
|
38
|
+
"clear_steering_entries",
|
|
38
39
|
"detach_proposal",
|
|
39
40
|
"dismiss_replace_proposal",
|
|
40
41
|
"edit_followup_entry",
|
|
41
42
|
"extension_ui_response",
|
|
42
43
|
"fetch_content",
|
|
43
|
-
|
|
44
|
+
// A browser's acknowledgement of a `flows_open` pin for one session (flows plugin).
|
|
45
|
+
// See change: add-flow-open-tool.
|
|
46
|
+
"flows_open_ack",
|
|
44
47
|
"force_kill",
|
|
45
48
|
"history_backfill",
|
|
46
49
|
"kill_process",
|
|
@@ -48,11 +51,16 @@ export const SESSION_OWNED_MESSAGES: ReadonlySet<string> = new Set([
|
|
|
48
51
|
"prompt_response",
|
|
49
52
|
"prompt_resync_request",
|
|
50
53
|
"remove_followup_entry",
|
|
54
|
+
"remove_steering_entry",
|
|
51
55
|
"rename_session",
|
|
52
56
|
"resume_session",
|
|
53
57
|
"retry_session",
|
|
54
58
|
"send_prompt",
|
|
55
59
|
"session_unview",
|
|
60
|
+
"sudo_credential_cancel",
|
|
61
|
+
"sudo_credential_forget",
|
|
62
|
+
"sudo_credential_response",
|
|
63
|
+
"sudo_credential_shown",
|
|
56
64
|
"session_view",
|
|
57
65
|
"setSessionDisplayPrefs",
|
|
58
66
|
"set_model",
|
|
@@ -61,7 +69,6 @@ export const SESSION_OWNED_MESSAGES: ReadonlySet<string> = new Set([
|
|
|
61
69
|
"set_thinking_level",
|
|
62
70
|
"shutdown",
|
|
63
71
|
"stop_after_turn",
|
|
64
|
-
"subagent_resync_request",
|
|
65
72
|
"subscribe",
|
|
66
73
|
"unarchive_session",
|
|
67
74
|
"unsubscribe",
|
|
@@ -90,10 +97,10 @@ export const NON_SESSION_MESSAGES: ReadonlySet<string> = new Set([
|
|
|
90
97
|
"create_workspace",
|
|
91
98
|
"delete_workspace",
|
|
92
99
|
"favorite_model",
|
|
93
|
-
"flow_management",
|
|
94
100
|
"grant_response",
|
|
95
101
|
"kill_terminal",
|
|
96
102
|
"list_files",
|
|
103
|
+
"live_preview_accept",
|
|
97
104
|
"move_folder_to_workspace",
|
|
98
105
|
"open_inline_terminal",
|
|
99
106
|
"openspec_bulk_archive",
|
|
@@ -56,6 +56,8 @@ const WS_ROADS: Readonly<Record<string, readonly [HostAction, string]>> = {
|
|
|
56
56
|
// branch / worktree progress
|
|
57
57
|
worktree_init_subscribe: ["branch.read", "branch"],
|
|
58
58
|
worktree_init_unsubscribe: ["branch.read", "branch"],
|
|
59
|
+
// live previews: the tab announces the preview tiers it renders (D9)
|
|
60
|
+
live_preview_accept: ["live.read", "live"],
|
|
59
61
|
// files
|
|
60
62
|
list_files: ["files.read", "files"],
|
|
61
63
|
watch_files: ["files.read", "files"],
|
|
@@ -84,7 +86,6 @@ const WS_ROADS: Readonly<Record<string, readonly [HostAction, string]>> = {
|
|
|
84
86
|
browser_relay_input: ["plugin:browser:write", "plugin"],
|
|
85
87
|
browser_relay_subscribe: ["plugin:browser:read", "plugin"],
|
|
86
88
|
browser_relay_unsubscribe: ["plugin:browser:read", "plugin"],
|
|
87
|
-
flow_management: ["plugin:flows:write", "plugin"],
|
|
88
89
|
request_roles: ["plugin:roles:read", "plugin"],
|
|
89
90
|
role_preset_delete: ["plugin:roles:write", "plugin"],
|
|
90
91
|
role_preset_load: ["plugin:roles:write", "plugin"],
|
|
@@ -50,6 +50,17 @@ export interface BrowseRoots {
|
|
|
50
50
|
sensitive: string[];
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
+
/**
|
|
54
|
+
* `within` for two CANONICAL absolute paths (real paths from `fs.realpath` / the forbidden sets):
|
|
55
|
+
* a string-prefix test on POSIX, where `path.relative` is a case-sensitive resolve + split (the hot
|
|
56
|
+
* cost once the sensitive list grew to ~30 entries, harden-agent-tool-guards D7). Windows keeps
|
|
57
|
+
* `within` (its relative is case-insensitive and drive-aware).
|
|
58
|
+
*/
|
|
59
|
+
const underOrEqual: (p: string, base: string) => boolean =
|
|
60
|
+
path.sep === "/"
|
|
61
|
+
? (p, base) => p === base || p.startsWith(base.endsWith("/") ? base : `${base}/`)
|
|
62
|
+
: within;
|
|
63
|
+
|
|
53
64
|
const warnedSources = new Set<string>();
|
|
54
65
|
function warnOnce(source: string, err: unknown): void {
|
|
55
66
|
if (warnedSources.has(source)) return;
|
|
@@ -85,8 +96,8 @@ export async function resolveBrowseRoots(
|
|
|
85
96
|
// sensitive dir, or is an ancestor of any forbidden subject.
|
|
86
97
|
const forbidden = [...sets.whole, ...sets.sensitive];
|
|
87
98
|
const ungrantable = (real: string): boolean =>
|
|
88
|
-
forbidden.some((f) =>
|
|
89
|
-
sets.sensitive.some((f) =>
|
|
99
|
+
forbidden.some((f) => underOrEqual(f, real)) || // real equals or contains a forbidden subject
|
|
100
|
+
sets.sensitive.some((f) => underOrEqual(real, f)); // real is at/under a sensitive dir
|
|
90
101
|
|
|
91
102
|
const candidates: string[] = [];
|
|
92
103
|
for (const [name, read] of named) {
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build a header-safe `Content-Disposition: attachment` value for a file name.
|
|
3
|
+
*
|
|
4
|
+
* - `filename="…"`: every char outside printable ASCII (0x20-0x7E, so CR/LF
|
|
5
|
+
* too), plus `"` and `\`, becomes `_` — no header injection, no quoted-string
|
|
6
|
+
* escapes.
|
|
7
|
+
* - `filename*=UTF-8''…`: RFC 5987 `attr-char` percent-encoding. `encodeURIComponent`
|
|
8
|
+
* leaves `' ( ) *` literal, which are not `attr-char`, so they are encoded too
|
|
9
|
+
* (`!` and `~` are legal and stay literal).
|
|
10
|
+
*
|
|
11
|
+
* See change: add-file-download.
|
|
12
|
+
*/
|
|
13
|
+
export function contentDispositionAttachment(name: string): string {
|
|
14
|
+
const ascii = name.replace(/[^\x20-\x7e]|["\\]/g, "_");
|
|
15
|
+
const encoded = encodeURIComponent(name).replace(
|
|
16
|
+
/['()*]/g,
|
|
17
|
+
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
|
|
18
|
+
);
|
|
19
|
+
return `attachment; filename="${ascii}"; filename*=UTF-8''${encoded}`;
|
|
20
|
+
}
|