@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
|
@@ -18,9 +18,17 @@
|
|
|
18
18
|
* Over plain http the check defeats an impostor answering at the address, NOT an
|
|
19
19
|
* on-path relay that forwards the challenge to the genuine server.
|
|
20
20
|
*
|
|
21
|
-
*
|
|
21
|
+
* Optional device key (`hooks.deviceKey`): the knock / redeem then carries
|
|
22
|
+
* `deviceKey {deviceNonce, pub, sig}` — a `pi-devbind/v1` signature over a fresh
|
|
23
|
+
* identity-challenge `deviceNonce` (re-challenged when the proving challenge is
|
|
24
|
+
* older than 30 s). No provider, no nonce, or no key held ⇒ the body is exactly
|
|
25
|
+
* what it was before; a failure to get a key never blocks the pairing.
|
|
26
|
+
*
|
|
27
|
+
* See change: add-lan-knock-pairing (D11); add-electron-server-windows (D2);
|
|
28
|
+
* device-key-mutual-check (D3).
|
|
22
29
|
*/
|
|
23
30
|
|
|
31
|
+
import { DEVICE_NONCE_REUSE_MS, type DeviceProof } from "./device-key-proof.js";
|
|
24
32
|
import { truncateUtf8 } from "./display-name.js";
|
|
25
33
|
import { isKnockRefusal, type KnockRefusal } from "./pairing-knock.js";
|
|
26
34
|
import { validateDeliveredRoutes } from "./server-routes.js";
|
|
@@ -64,12 +72,35 @@ export interface KnockHooks {
|
|
|
64
72
|
/** Delay injection (default `setTimeout`). */
|
|
65
73
|
sleep?: (ms: number) => Promise<void>;
|
|
66
74
|
pollIntervalMs?: number;
|
|
75
|
+
/** Device key to bind to this pairing request (see {@link DeviceKeyProvider}). Omitted ⇒ no key is sent. */
|
|
76
|
+
deviceKey?: DeviceKeyProvider;
|
|
67
77
|
/** Fetch redirect mode. Browsers leave it unset; Electron main passes `"manual"` (never follow off-origin). */
|
|
68
78
|
redirect?: RequestRedirect;
|
|
69
79
|
}
|
|
70
80
|
|
|
71
|
-
/**
|
|
72
|
-
|
|
81
|
+
/**
|
|
82
|
+
* Identity proof: `{proven: fingerprint}` or `{refused: reason}`. May throw on transport failure.
|
|
83
|
+
* `deviceNonce` is the challenge reply's server-issued nonce (absent on an older server).
|
|
84
|
+
*/
|
|
85
|
+
export type ProveFn = (
|
|
86
|
+
baseUrl: string,
|
|
87
|
+
) => Promise<{ proven: string; publicKey?: string; deviceNonce?: string } | { refused: string; identityFailure?: true }>;
|
|
88
|
+
|
|
89
|
+
/** The device-key half of a pairing request body: `pi-devbind/v1` proof over a fresh `deviceNonce`. */
|
|
90
|
+
export type KnockDeviceKey = DeviceProof;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Supplies the device key for a knock / redeem. The caller owns the key store (WebCrypto in a browser,
|
|
94
|
+
* Node crypto in Electron main); this client owns the challenge freshness and the body.
|
|
95
|
+
*/
|
|
96
|
+
export interface DeviceKeyProvider {
|
|
97
|
+
/** Sign `pi-devbind/v1` over (`fingerprint`, `deviceNonce`); `null` ⇒ no key held (knock without one). May create the key. */
|
|
98
|
+
sign(fingerprint: string, deviceNonce: string): Promise<{ pub: string; sig: string } | null>;
|
|
99
|
+
/** Re-run the identity challenge when `challenge` is missing or older than 30 s. Without it no fresh nonce ⇒ no key. */
|
|
100
|
+
prove?: ProveFn;
|
|
101
|
+
/** The challenge that proved the pin: its `deviceNonce` and the `hooks.now()` instant it was made. */
|
|
102
|
+
challenge?: { deviceNonce: string; at: number };
|
|
103
|
+
}
|
|
73
104
|
|
|
74
105
|
const DEFAULT_POLL_MS = 2000;
|
|
75
106
|
const REQUEST_TIMEOUT_MS = 10_000;
|
|
@@ -162,7 +193,7 @@ export async function proveExpected(
|
|
|
162
193
|
baseUrl: string,
|
|
163
194
|
expectedFingerprint: string,
|
|
164
195
|
prove: ProveFn,
|
|
165
|
-
): Promise<{ fingerprint: string; publicKey?: string } | Extract<KnockOutcome, { status: "identity_mismatch" }>> {
|
|
196
|
+
): Promise<{ fingerprint: string; publicKey?: string; deviceNonce?: string } | Extract<KnockOutcome, { status: "identity_mismatch" }>> {
|
|
166
197
|
const proof = await prove(baseUrl);
|
|
167
198
|
if ("refused" in proof || proof.proven !== expectedFingerprint) {
|
|
168
199
|
return {
|
|
@@ -172,7 +203,49 @@ export async function proveExpected(
|
|
|
172
203
|
stage: "challenge",
|
|
173
204
|
};
|
|
174
205
|
}
|
|
175
|
-
return {
|
|
206
|
+
return {
|
|
207
|
+
fingerprint: proof.proven,
|
|
208
|
+
...(proof.publicKey ? { publicKey: proof.publicKey } : {}),
|
|
209
|
+
...(proof.deviceNonce ? { deviceNonce: proof.deviceNonce } : {}),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* The `deviceKey` body member for a request to `baseUrl` whose identity `provenFingerprint` is proven, or `{}`
|
|
215
|
+
* (no key). Uses the proving challenge while it is younger than {@link DEVICE_NONCE_REUSE_MS}, else re-runs it
|
|
216
|
+
* through `provider.prove`; a re-challenge proving another fingerprint is an `identity_mismatch` (nothing is sent),
|
|
217
|
+
* any other failure just means "no key" — pairing never gets harder than without a key.
|
|
218
|
+
*/
|
|
219
|
+
async function deviceKeyMember(
|
|
220
|
+
baseUrl: string,
|
|
221
|
+
provenFingerprint: string,
|
|
222
|
+
hooks: KnockHooks,
|
|
223
|
+
): Promise<{ deviceKey?: KnockDeviceKey } | Extract<KnockOutcome, { status: "identity_mismatch" }>> {
|
|
224
|
+
const provider = hooks.deviceKey;
|
|
225
|
+
if (!provider) return {};
|
|
226
|
+
const now = (hooks.now ?? Date.now)();
|
|
227
|
+
let nonce: string | undefined;
|
|
228
|
+
if (provider.challenge && now - provider.challenge.at < DEVICE_NONCE_REUSE_MS) {
|
|
229
|
+
nonce = provider.challenge.deviceNonce;
|
|
230
|
+
} else if (provider.prove) {
|
|
231
|
+
try {
|
|
232
|
+
const proof = await provider.prove(baseUrl);
|
|
233
|
+
if ("refused" in proof) return {};
|
|
234
|
+
if (proof.proven !== provenFingerprint) {
|
|
235
|
+
return { status: "identity_mismatch", expected: provenFingerprint, proven: proof.proven, stage: "challenge" };
|
|
236
|
+
}
|
|
237
|
+
nonce = proof.deviceNonce;
|
|
238
|
+
} catch {
|
|
239
|
+
return {};
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (!nonce) return {};
|
|
243
|
+
try {
|
|
244
|
+
const signed = await provider.sign(provenFingerprint, nonce);
|
|
245
|
+
return signed ? { deviceKey: { deviceNonce: nonce, pub: signed.pub, sig: signed.sig } } : {};
|
|
246
|
+
} catch {
|
|
247
|
+
return {};
|
|
248
|
+
}
|
|
176
249
|
}
|
|
177
250
|
|
|
178
251
|
/**
|
|
@@ -185,10 +258,12 @@ export async function sendKnock(
|
|
|
185
258
|
name: string,
|
|
186
259
|
hooks: KnockHooks = {},
|
|
187
260
|
): Promise<KnockOutcome> {
|
|
261
|
+
const key = await deviceKeyMember(baseUrl, provenFingerprint, hooks);
|
|
262
|
+
if ("status" in key) return key;
|
|
188
263
|
const knock = await post<{ pendingId: string; confirmCode: string; expiresAt: number; fingerprint: string }>(
|
|
189
264
|
baseUrl,
|
|
190
265
|
"/api/pair/request",
|
|
191
|
-
knockRequestBody(name),
|
|
266
|
+
{ ...knockRequestBody(name), ...key },
|
|
192
267
|
hooks.redirect,
|
|
193
268
|
);
|
|
194
269
|
const data = knock.json.data;
|
|
@@ -223,7 +298,9 @@ export async function redeemPairingCode(
|
|
|
223
298
|
code: string,
|
|
224
299
|
hooks: KnockHooks = {},
|
|
225
300
|
): Promise<KnockOutcome> {
|
|
226
|
-
const
|
|
301
|
+
const key = await deviceKeyMember(baseUrl, provenFingerprint, hooks);
|
|
302
|
+
if ("status" in key) return key;
|
|
303
|
+
const redeemed = await post<{ pendingId: string; confirmCode: string }>(baseUrl, "/api/pair/redeem", { code, ...key }, hooks.redirect);
|
|
227
304
|
const data = redeemed.json.data;
|
|
228
305
|
if (!redeemed.json.success || !data) return refusal(redeemed.status, redeemed.json);
|
|
229
306
|
if (!/^\d{8}$/.test(String(data.confirmCode)) || typeof data.pendingId !== "string") return refusal(redeemed.status, {});
|
|
@@ -243,7 +320,14 @@ export async function knockServerWith(
|
|
|
243
320
|
// CHALLENGE — never knock an address that cannot prove the expected identity.
|
|
244
321
|
const proof = await proveExpected(baseUrl, expectedFingerprint, prove);
|
|
245
322
|
if ("status" in proof) return proof;
|
|
246
|
-
|
|
323
|
+
// The proving challenge is the freshest nonce: hand it to the provider (and the prover for a re-run).
|
|
324
|
+
const deviceKey: KnockHooks["deviceKey"] =
|
|
325
|
+
hooks.deviceKey && {
|
|
326
|
+
prove,
|
|
327
|
+
...hooks.deviceKey,
|
|
328
|
+
...(proof.deviceNonce ? { challenge: { deviceNonce: proof.deviceNonce, at: (hooks.now ?? Date.now)() } } : {}),
|
|
329
|
+
};
|
|
330
|
+
return sendKnock(baseUrl, proof.fingerprint, name, deviceKey ? { ...hooks, deviceKey } : hooks);
|
|
247
331
|
}
|
|
248
332
|
|
|
249
333
|
type PollData = { status: string; token?: string; routes?: unknown };
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-agent-settings-lock — NODE-ONLY primitive for a lock-coordinated,
|
|
3
|
+
* merge-friendly write of pi's global `settings.json`.
|
|
4
|
+
*
|
|
5
|
+
* Takes the SAME `proper-lockfile` lock pi takes (`<settings.json>.lock`,
|
|
6
|
+
* `realpath:false`, `stale:10_000`); tmp-file + `rename` makes the replace
|
|
7
|
+
* atomic, a failed write leaves the target untouched. Default target is
|
|
8
|
+
* `<agentDir>/settings.json` (`resolvePiAgentDir`, honours
|
|
9
|
+
* `PI_CODING_AGENT_DIR`); `FsDeps.settingsPath` overrides target + lock path.
|
|
10
|
+
*
|
|
11
|
+
* NEVER import from client code (boundary-tested; not in any barrel).
|
|
12
|
+
* Moved from `packages/server/src/pi-agent-settings.ts`.
|
|
13
|
+
* See change: edit-pi-agent-settings (D4, D5); stop-flows-edit-mode-project-writes (D3).
|
|
14
|
+
*/
|
|
15
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
16
|
+
import { promises as fsp, readFileSync } from "node:fs";
|
|
17
|
+
import { createRequire } from "node:module";
|
|
18
|
+
import { dirname, join, resolve } from "node:path";
|
|
19
|
+
import { resolvePiAgentDir } from "./dashboard-paths.js";
|
|
20
|
+
import { PI_MANAGED_SETTINGS_KEYS } from "./pi-settings-keys.js";
|
|
21
|
+
|
|
22
|
+
const _require = createRequire(import.meta.url);
|
|
23
|
+
const _lockfile = _require("proper-lockfile") as typeof import("proper-lockfile");
|
|
24
|
+
/** Async fs surface of the locked write path; injectable so failure paths are testable. */
|
|
25
|
+
export interface PiSettingsFs {
|
|
26
|
+
readFile: (path: string) => Promise<string>;
|
|
27
|
+
writeFile: (path: string, data: string) => Promise<void>;
|
|
28
|
+
rename: (from: string, to: string) => Promise<void>;
|
|
29
|
+
chmod: (path: string, mode: number) => Promise<void>;
|
|
30
|
+
stat: (path: string) => Promise<{ mode: number }>;
|
|
31
|
+
lstat: (path: string) => Promise<{ isSymbolicLink(): boolean }>;
|
|
32
|
+
realpath: (path: string) => Promise<string>;
|
|
33
|
+
readlink: (path: string) => Promise<string>;
|
|
34
|
+
mkdir: (path: string) => Promise<void>;
|
|
35
|
+
unlink: (path: string) => Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const defaultFs: PiSettingsFs = {
|
|
39
|
+
readFile: (p) => fsp.readFile(p, "utf-8"),
|
|
40
|
+
writeFile: (p, d) => fsp.writeFile(p, d, "utf-8"),
|
|
41
|
+
rename: (a, b) => fsp.rename(a, b),
|
|
42
|
+
chmod: (p, m) => fsp.chmod(p, m),
|
|
43
|
+
stat: (p) => fsp.stat(p),
|
|
44
|
+
lstat: (p) => fsp.lstat(p),
|
|
45
|
+
realpath: (p) => fsp.realpath(p),
|
|
46
|
+
readlink: (p) => fsp.readlink(p),
|
|
47
|
+
mkdir: async (p) => {
|
|
48
|
+
await fsp.mkdir(p, { recursive: true });
|
|
49
|
+
},
|
|
50
|
+
unlink: (p) => fsp.unlink(p),
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export interface FsDeps {
|
|
54
|
+
/** Override for tests. Defaults to `os.homedir()`. */
|
|
55
|
+
home?: string;
|
|
56
|
+
/** Test seam for `PI_CODING_AGENT_DIR`. */
|
|
57
|
+
agentDirEnv?: string;
|
|
58
|
+
/** Override individual async fs calls (failure-path tests). */
|
|
59
|
+
fs?: Partial<PiSettingsFs>;
|
|
60
|
+
/**
|
|
61
|
+
* Explicit target (and lock) path; bypasses `home`/`agentDirEnv`. Used by
|
|
62
|
+
* callers that must write the exact file another reader resolves (flows
|
|
63
|
+
* plugin → `<homedir>/.pi/agent/settings.json`).
|
|
64
|
+
*/
|
|
65
|
+
settingsPath?: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Absolute path of the global pi settings file (UNRESOLVED — also the lock path). */
|
|
69
|
+
export function piSettingsPath(deps: FsDeps = {}): string {
|
|
70
|
+
if (deps.settingsPath) return deps.settingsPath;
|
|
71
|
+
return join(resolvePiAgentDir({ homedir: deps.home, agentDirEnv: deps.agentDirEnv }), "settings.json");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function asObject(v: unknown): Record<string, unknown> {
|
|
75
|
+
return isPlainObject(v) ? v : {};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function isPlainObject(v: unknown): v is Record<string, unknown> {
|
|
79
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ── Reading + the concurrency token ──────────────────────────────────
|
|
83
|
+
|
|
84
|
+
/** Snapshot of the settings file. */
|
|
85
|
+
export interface PiSettingsState {
|
|
86
|
+
/** Parsed object; `{}` when absent or unparseable. */
|
|
87
|
+
settings: Record<string, unknown>;
|
|
88
|
+
/** Raw text as on disk (BOM kept); `""` when absent. */
|
|
89
|
+
raw: string;
|
|
90
|
+
/** Concurrency token (design D4). */
|
|
91
|
+
etag: string;
|
|
92
|
+
/** Set when the file exists but is not a valid JSON object. */
|
|
93
|
+
parseError?: string;
|
|
94
|
+
/** False when the file does not exist. */
|
|
95
|
+
exists: boolean;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const stripBom = (s: string): string => (s.charCodeAt(0) === 0xfeff ? s.slice(1) : s);
|
|
99
|
+
|
|
100
|
+
export function sortKeys(v: unknown): unknown {
|
|
101
|
+
if (Array.isArray(v)) return v.map(sortKeys);
|
|
102
|
+
if (isPlainObject(v)) {
|
|
103
|
+
const out: Record<string, unknown> = {};
|
|
104
|
+
for (const k of Object.keys(v).sort()) out[k] = sortKeys(v[k]);
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
return v;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 1-based line/column of a 0-based character offset, clamped into the text. */
|
|
111
|
+
function lineColumnAt(text: string, position: number): { line: number; column: number } {
|
|
112
|
+
const upto = text.slice(0, Math.max(0, Math.min(position, text.length)));
|
|
113
|
+
const lines = upto.split("\n");
|
|
114
|
+
return { line: lines.length, column: (lines[lines.length - 1]?.length ?? 0) + 1 };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Describe a parse failure WITHOUT quoting file content. Node's `SyntaxError`
|
|
119
|
+
* message can embed source text (a truncated file holding an API key would leak
|
|
120
|
+
* it through `parseError`), so only the numeric position survives: the
|
|
121
|
+
* `line L column C` pair when the message carries it, else a position derived
|
|
122
|
+
* from `position N`, else a fixed reason. See change: pi-settings-full-coverage (D5b).
|
|
123
|
+
*/
|
|
124
|
+
function describeParseFailure(err: unknown, text: string): string {
|
|
125
|
+
const msg = err instanceof Error ? err.message : "";
|
|
126
|
+
const lc = /\(line (\d+) column (\d+)\)/.exec(msg);
|
|
127
|
+
if (lc) return `Invalid JSON at line ${lc[1]}, column ${lc[2]}`;
|
|
128
|
+
const pos = /\bposition (\d+)/.exec(msg);
|
|
129
|
+
if (pos) {
|
|
130
|
+
const { line, column } = lineColumnAt(text, Number(pos[1]));
|
|
131
|
+
return `Invalid JSON at line ${line}, column ${column}`;
|
|
132
|
+
}
|
|
133
|
+
return "Invalid JSON";
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function parseText(raw: string): { obj?: Record<string, unknown>; error?: string } {
|
|
137
|
+
const text = stripBom(raw);
|
|
138
|
+
try {
|
|
139
|
+
const parsed: unknown = JSON.parse(text);
|
|
140
|
+
if (!isPlainObject(parsed)) return { error: "settings.json must contain a JSON object" };
|
|
141
|
+
return { obj: parsed };
|
|
142
|
+
} catch (err) {
|
|
143
|
+
return { error: describeParseFailure(err, text) };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Concurrency token: sha256 of the canonical form (BOM stripped, parsed, the
|
|
149
|
+
* mirrored default keys removed, keys sorted recursively). `"absent"` for no
|
|
150
|
+
* file; sha256 of the raw bytes when unparseable. Sorting makes reformatting
|
|
151
|
+
* and key reordering non-conflicts. See change: edit-pi-agent-settings (D4).
|
|
152
|
+
*/
|
|
153
|
+
export function computePiSettingsEtag(raw: string | null): string {
|
|
154
|
+
if (raw === null) return "absent";
|
|
155
|
+
const { obj } = parseText(raw);
|
|
156
|
+
if (!obj) return createHash("sha256").update(raw).digest("hex");
|
|
157
|
+
const rest = { ...obj };
|
|
158
|
+
for (const k of PI_MANAGED_SETTINGS_KEYS) delete rest[k];
|
|
159
|
+
return createHash("sha256").update(JSON.stringify(sortKeys(rest))).digest("hex");
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function buildState(raw: string | null): PiSettingsState {
|
|
163
|
+
if (raw === null) return { settings: {}, raw: "", etag: "absent", exists: false };
|
|
164
|
+
const { obj, error } = parseText(raw);
|
|
165
|
+
return {
|
|
166
|
+
settings: obj ?? {},
|
|
167
|
+
raw,
|
|
168
|
+
etag: computePiSettingsEtag(raw),
|
|
169
|
+
...(error ? { parseError: error } : {}),
|
|
170
|
+
exists: true,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function readRawSync(path: string): string | null {
|
|
175
|
+
try {
|
|
176
|
+
return readFileSync(path, "utf-8");
|
|
177
|
+
} catch (err) {
|
|
178
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
|
|
179
|
+
throw err;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Read the global settings file. Never throws on absent/unparseable content. */
|
|
184
|
+
export function readPiSettings(deps: FsDeps = {}): PiSettingsState {
|
|
185
|
+
return buildState(readRawSync(piSettingsPath(deps)));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// ── Lock-coordinated atomic write (design D5) ────────────────────────
|
|
189
|
+
|
|
190
|
+
export type LockedStep<T, F> = { fail: F } | { value: T; /** New file text; omit for "no write". */ write?: string };
|
|
191
|
+
|
|
192
|
+
export type LockedResult<T, F> =
|
|
193
|
+
| { ok: true; value: T; /** Post-write state (or current when nothing was written). */ state: PiSettingsState }
|
|
194
|
+
| { ok: false; error: "busy" }
|
|
195
|
+
| { ok: false; error: "io"; message: string }
|
|
196
|
+
| { ok: false; error: "stale"; state: PiSettingsState }
|
|
197
|
+
| { ok: false; error: "fn"; fail: F };
|
|
198
|
+
|
|
199
|
+
export interface LockOptions {
|
|
200
|
+
/** Reject with `stale` when the current token differs. */
|
|
201
|
+
baseEtag?: string;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const LOCK_OPTIONS = {
|
|
205
|
+
realpath: false,
|
|
206
|
+
stale: 10_000,
|
|
207
|
+
retries: { retries: 10, minTimeout: 20, maxTimeout: 20 },
|
|
208
|
+
} as const;
|
|
209
|
+
|
|
210
|
+
/** 2-space JSON with a trailing newline — the on-disk format of every write. */
|
|
211
|
+
export const formatJson = (obj: unknown): string => `${JSON.stringify(obj, null, 2)}\n`;
|
|
212
|
+
|
|
213
|
+
async function resolveWriteTarget(path: string, fs: PiSettingsFs): Promise<string> {
|
|
214
|
+
try {
|
|
215
|
+
if (!(await fs.lstat(path)).isSymbolicLink()) return path;
|
|
216
|
+
} catch {
|
|
217
|
+
return path; // absent
|
|
218
|
+
}
|
|
219
|
+
try {
|
|
220
|
+
return await fs.realpath(path);
|
|
221
|
+
} catch {
|
|
222
|
+
// Dangling link: write through to where it points, as pi's writeFileSync does.
|
|
223
|
+
return resolve(dirname(path), await fs.readlink(path));
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const errMessage = (err: unknown): string => (err instanceof Error ? err.message : String(err));
|
|
228
|
+
|
|
229
|
+
/** Acquire pi's lock on the settings path; `busy` when held past the retry budget. */
|
|
230
|
+
async function acquireLock(
|
|
231
|
+
path: string,
|
|
232
|
+
fs: PiSettingsFs,
|
|
233
|
+
): Promise<{ release: () => Promise<void> } | { fail: LockedResult<never, never> }> {
|
|
234
|
+
try {
|
|
235
|
+
await fs.mkdir(dirname(path));
|
|
236
|
+
const release = await _lockfile.lock(path, {
|
|
237
|
+
...LOCK_OPTIONS,
|
|
238
|
+
onCompromised: (err) => {
|
|
239
|
+
console.warn(`[pi-settings] lock compromised (${(err as { code?: string }).code ?? "unknown"})`);
|
|
240
|
+
},
|
|
241
|
+
});
|
|
242
|
+
return { release };
|
|
243
|
+
} catch (err) {
|
|
244
|
+
if ((err as { code?: unknown } | null)?.code === "ELOCKED") return { fail: { ok: false, error: "busy" } };
|
|
245
|
+
return { fail: { ok: false, error: "io", message: errMessage(err) } };
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const isEnoent = (err: unknown): boolean => (err as NodeJS.ErrnoException).code === "ENOENT";
|
|
250
|
+
|
|
251
|
+
async function readCurrent(path: string, fs: PiSettingsFs): Promise<string | null> {
|
|
252
|
+
try {
|
|
253
|
+
return await fs.readFile(path);
|
|
254
|
+
} catch (err) {
|
|
255
|
+
if (isEnoent(err)) return null;
|
|
256
|
+
throw err;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** tmp file in the target's directory + chmod to the target's mode + `rename`. */
|
|
261
|
+
async function replaceAtomically(path: string, text: string, existed: boolean, fs: PiSettingsFs): Promise<void> {
|
|
262
|
+
const target = await resolveWriteTarget(path, fs);
|
|
263
|
+
const tmp = join(dirname(target), `.${randomBytes(6).toString("hex")}.settings.tmp`);
|
|
264
|
+
try {
|
|
265
|
+
await fs.writeFile(tmp, text);
|
|
266
|
+
if (existed) {
|
|
267
|
+
try {
|
|
268
|
+
await fs.chmod(tmp, (await fs.stat(target)).mode & 0o7777);
|
|
269
|
+
} catch (err) {
|
|
270
|
+
if (!isEnoent(err)) throw err;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
await fs.rename(tmp, target);
|
|
274
|
+
} catch (err) {
|
|
275
|
+
await fs.unlink(tmp).catch(() => {});
|
|
276
|
+
throw err;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Run `fn` under the pi settings lock. `fn` is PURE and synchronous (re-read
|
|
282
|
+
* state in, new text out). Not acquired within the retry budget → `busy`;
|
|
283
|
+
* a failing tmp write → `io` with the target untouched.
|
|
284
|
+
*/
|
|
285
|
+
export async function withPiSettingsLock<T, F = never>(
|
|
286
|
+
fn: (state: PiSettingsState) => LockedStep<T, F>,
|
|
287
|
+
options: LockOptions = {},
|
|
288
|
+
deps: FsDeps = {},
|
|
289
|
+
): Promise<LockedResult<T, F>> {
|
|
290
|
+
const fs: PiSettingsFs = { ...defaultFs, ...deps.fs };
|
|
291
|
+
const path = piSettingsPath(deps);
|
|
292
|
+
|
|
293
|
+
const lock = await acquireLock(path, fs);
|
|
294
|
+
if ("fail" in lock) return lock.fail;
|
|
295
|
+
|
|
296
|
+
try {
|
|
297
|
+
const state = buildState(await readCurrent(path, fs));
|
|
298
|
+
if (options.baseEtag !== undefined && options.baseEtag !== state.etag) {
|
|
299
|
+
return { ok: false, error: "stale", state };
|
|
300
|
+
}
|
|
301
|
+
const step = fn(state);
|
|
302
|
+
if ("fail" in step) return { ok: false, error: "fn", fail: step.fail };
|
|
303
|
+
if (step.write === undefined) return { ok: true, value: step.value, state };
|
|
304
|
+
await replaceAtomically(path, step.write, state.exists, fs);
|
|
305
|
+
return { ok: true, value: step.value, state: buildState(step.write) };
|
|
306
|
+
} catch (err) {
|
|
307
|
+
return { ok: false, error: "io", message: errMessage(err) };
|
|
308
|
+
} finally {
|
|
309
|
+
await lock.release().catch(() => {});
|
|
310
|
+
}
|
|
311
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mirror of pi's path comparison (pi-coding-agent 1.5.0 `dist/utils/paths.js`
|
|
3
|
+
* `getPathComparisonKey` / `pathsEqual`, used by `trust-manager.js` to match
|
|
4
|
+
* `trust.json` keys): both paths are resolved, and on win32 compared
|
|
5
|
+
* case-insensitively. No filesystem access — comparison only, never display.
|
|
6
|
+
*
|
|
7
|
+
* The path module is injectable so the win32 branch is testable on any host;
|
|
8
|
+
* the default is read at call time (as pi's `getPlatformPathApi`).
|
|
9
|
+
* See change: update-pi-core-1-5-adopt-apis (design D2).
|
|
10
|
+
*/
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
|
|
13
|
+
/** `node:path`, `path.win32` or `path.posix` (all share this shape). */
|
|
14
|
+
export type PathApi = typeof path.posix;
|
|
15
|
+
|
|
16
|
+
/** `path.win32` on Windows, else `path.posix` — read at call time. */
|
|
17
|
+
export function nativePathApi(): PathApi {
|
|
18
|
+
// Mirrors pi's getPlatformPathApi, read at call time so tests can simulate win32.
|
|
19
|
+
return process.platform === "win32" ? path.win32 : path.posix; // platform-branch-ok: pi parity
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** pi's `getPathComparisonKey`: resolved, lower-cased on win32. */
|
|
23
|
+
export function piPathComparisonKey(p: string, pathApi: PathApi = nativePathApi()): string {
|
|
24
|
+
const resolved = pathApi.resolve(p);
|
|
25
|
+
return pathApi === path.win32 ? resolved.toLowerCase() : resolved;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** pi's `pathsEqual`: both paths name the same location. */
|
|
29
|
+
export function piPathsEqual(a: string, b: string, pathApi: PathApi = nativePathApi()): boolean {
|
|
30
|
+
return piPathComparisonKey(a, pathApi) === piPathComparisonKey(b, pathApi);
|
|
31
|
+
}
|
|
@@ -58,6 +58,13 @@ export interface PiSettingDef {
|
|
|
58
58
|
def: boolean | number | string | null;
|
|
59
59
|
/** Display text for a non-literal default. */
|
|
60
60
|
defText?: string;
|
|
61
|
+
/**
|
|
62
|
+
* `int` only: the canonical string `"disabled"` is also valid (pi 1.5 documents
|
|
63
|
+
* the key as `number | "disabled"`). The typed PATCH accepts exactly that
|
|
64
|
+
* spelling; pi's own parser is trim/case-insensitive.
|
|
65
|
+
* See change: update-pi-core-1-5-adopt-apis (design D4).
|
|
66
|
+
*/
|
|
67
|
+
disabledLiteral?: true;
|
|
61
68
|
category: PiSettingCategory;
|
|
62
69
|
label: string;
|
|
63
70
|
hint: string;
|
|
@@ -79,7 +86,7 @@ const intKey = (
|
|
|
79
86
|
category: PiSettingCategory,
|
|
80
87
|
label: string,
|
|
81
88
|
hint: string,
|
|
82
|
-
extra: Pick<PiSettingDef, "min" | "max" | "defText"> = { min: 0 },
|
|
89
|
+
extra: Pick<PiSettingDef, "min" | "max" | "defText" | "disabledLiteral"> = { min: 0 },
|
|
83
90
|
): PiSettingDef => ({ key, kind: "int", def, category, label, hint, ...extra });
|
|
84
91
|
const str = (
|
|
85
92
|
key: string,
|
|
@@ -102,8 +109,11 @@ const enumKey = (
|
|
|
102
109
|
export const PI_SETTINGS_SCHEMA: readonly PiSettingDef[] = [
|
|
103
110
|
// Model and thinking
|
|
104
111
|
bool("hideThinkingBlock", false, "model", "Hide thinking blocks", "Hide thinking blocks in pi's transcript"),
|
|
105
|
-
bool("
|
|
106
|
-
|
|
112
|
+
bool("notices.cacheMisses", false, "model", "Cache misses", "Show a notice when a response re-bills a significant part of the prompt cache, such as after a model switch or an idle gap"),
|
|
113
|
+
bool("notices.cacheWarming", false, "model", "Cache warming", "Show the cost of cache warming requests"),
|
|
114
|
+
bool("notices.compactionCosts", false, "model", "Compaction costs", "Show the cost of compactions and branch summaries"),
|
|
115
|
+
bool("notices.reasoningDrops", false, "model", "Reasoning drops", "Show a notice when a provider drops reasoning items from a request, such as OpenAI reasoning items after a prefix mismatch or Anthropic thinking blocks during recovery"),
|
|
116
|
+
enumKey("cacheWarming", ["off", "streaming", "idle"], "idle", "model", "Cache warming", "Keep eligible provider prompt caches warm during active runs and, with idle, for up to 30 minutes between runs; streaming warms only during active runs"),
|
|
107
117
|
intKey("thinkingBudgets.minimal", null, "model", "Thinking budget: minimal", "Token budget for the minimal thinking level", { min: 0, defText: "built-in" }),
|
|
108
118
|
intKey("thinkingBudgets.low", null, "model", "Thinking budget: low", "Token budget for the low thinking level", { min: 0, defText: "built-in" }),
|
|
109
119
|
intKey("thinkingBudgets.medium", null, "model", "Thinking budget: medium", "Token budget for the medium thinking level", { min: 0, defText: "built-in" }),
|
|
@@ -133,7 +143,7 @@ export const PI_SETTINGS_SCHEMA: readonly PiSettingDef[] = [
|
|
|
133
143
|
// Sessions and context
|
|
134
144
|
str("sessionDir", null, "sessions", "Session directory", "Session storage directory", "agent session directory"),
|
|
135
145
|
bool("compaction.enabled", true, "sessions", "Auto-compaction", "Compact long conversations automatically"),
|
|
136
|
-
intKey("compaction.reserveTokens", 16384, "sessions", "Compaction reserve tokens", "
|
|
146
|
+
intKey("compaction.reserveTokens", 16384, "sessions", "Compaction reserve tokens", "Free context tokens below which automatic compaction starts"),
|
|
137
147
|
intKey("compaction.keepRecentTokens", 20000, "sessions", "Compaction keep-recent tokens", "Recent tokens retained without summarization"),
|
|
138
148
|
intKey("branchSummary.reserveTokens", 16384, "sessions", "Branch summary reserve tokens", "Tokens reserved when summarizing branch history"),
|
|
139
149
|
bool("branchSummary.skipPrompt", false, "sessions", "Skip branch summary prompt", "Skip the branch-summary prompt and default to no summary"),
|
|
@@ -199,8 +209,14 @@ export const PI_SETTINGS_SCHEMA: readonly PiSettingDef[] = [
|
|
|
199
209
|
// Network
|
|
200
210
|
enumKey("transport", ["auto", "sse", "websocket", "websocket-cached"], "auto", "network", "Transport", "Preferred transport for providers that support several"),
|
|
201
211
|
str("httpProxy", null, "network", "HTTP proxy", "Proxy URL applied as HTTP_PROXY and HTTPS_PROXY for pi's HTTP clients", "none"),
|
|
202
|
-
intKey("httpIdleTimeoutMs", 300000, "network", "HTTP idle timeout (ms)", "HTTP header and body idle timeout; 0 disables"
|
|
203
|
-
|
|
212
|
+
intKey("httpIdleTimeoutMs", 300000, "network", "HTTP idle timeout (ms)", "HTTP header and body idle timeout; 0 disables", {
|
|
213
|
+
min: 0,
|
|
214
|
+
disabledLiteral: true,
|
|
215
|
+
}),
|
|
216
|
+
intKey("websocketConnectTimeoutMs", 15000, "network", "WebSocket connect timeout (ms)", "WebSocket connection timeout; 0 disables", {
|
|
217
|
+
min: 0,
|
|
218
|
+
disabledLiteral: true,
|
|
219
|
+
}),
|
|
204
220
|
|
|
205
221
|
// Shell
|
|
206
222
|
str("shellPath", null, "shell", "Shell path", "Custom shell executable path", "platform default"),
|
|
@@ -210,8 +226,7 @@ export const PI_SETTINGS_SCHEMA: readonly PiSettingDef[] = [
|
|
|
210
226
|
bool("enableSkillCommands", true, "resources", "Skill commands", "Register skills as /skill:name commands"),
|
|
211
227
|
|
|
212
228
|
// Updates and privacy
|
|
213
|
-
bool("collapseChangelog", false, "updates", "Condensed changelog", "Show a condensed changelog after an update"),
|
|
214
|
-
bool("enableInstallTelemetry", true, "updates", "Install telemetry", "Anonymous install/update reporting and selected provider attribution headers"),
|
|
229
|
+
bool("collapseChangelog", false, "updates", "Condensed changelog", "Show a condensed changelog after an update; also condenses extension package changelogs"),
|
|
215
230
|
bool("enableAnalytics", false, "updates", "Analytics", "Opt in to analytics data sharing"),
|
|
216
231
|
bool("warnings.anthropicExtraUsage", true, "updates", "Anthropic extra-usage warning", "Warn when Anthropic subscription authentication may use paid extra usage"),
|
|
217
232
|
];
|
|
@@ -226,6 +241,7 @@ export const PI_SETTINGS_BLOCKS: readonly string[] = [
|
|
|
226
241
|
"markdown",
|
|
227
242
|
"warnings",
|
|
228
243
|
"thinkingBudgets",
|
|
244
|
+
"notices",
|
|
229
245
|
];
|
|
230
246
|
|
|
231
247
|
const BY_KEY: ReadonlyMap<string, PiSettingDef> = new Map(PI_SETTINGS_SCHEMA.map((d) => [d.key, d]));
|
|
@@ -238,14 +254,41 @@ export function splitPiSettingKey(key: string): [string, string] | [string] {
|
|
|
238
254
|
return dot < 0 ? [key] : [key.slice(0, dot), key.slice(dot + 1)];
|
|
239
255
|
}
|
|
240
256
|
|
|
257
|
+
/**
|
|
258
|
+
* Replica of pi >=1.6.1 `SettingsManager.migrateSettings` for `showCacheMissNotices`
|
|
259
|
+
* (pi `dist/core/settings-manager.js` ~292-304; re-diff on every pi bump). A boolean
|
|
260
|
+
* legacy value fills the four `notices.*` leaves; leaves already present in `notices`
|
|
261
|
+
* win (a present `null` counts as set). The legacy key is always dropped, so a
|
|
262
|
+
* non-boolean value contributes nothing. Returns a new object; the input is untouched.
|
|
263
|
+
* See change: update-pi-core-1-7-adopt-apis (design D2).
|
|
264
|
+
*/
|
|
265
|
+
export function migrateLegacyNotices(settings: Record<string, unknown>): Record<string, unknown> {
|
|
266
|
+
const { showCacheMissNotices: legacy, ...rest } = settings;
|
|
267
|
+
if (typeof legacy !== "boolean") return structuredClone(rest);
|
|
268
|
+
const existing =
|
|
269
|
+
typeof rest.notices === "object" && rest.notices !== null ? (rest.notices as Record<string, unknown>) : {};
|
|
270
|
+
return structuredClone({
|
|
271
|
+
...rest,
|
|
272
|
+
notices: {
|
|
273
|
+
cacheMisses: legacy,
|
|
274
|
+
cacheWarming: legacy,
|
|
275
|
+
compactionCosts: legacy,
|
|
276
|
+
reasoningDrops: legacy,
|
|
277
|
+
...existing,
|
|
278
|
+
},
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
241
282
|
type KindCheck = (def: PiSettingDef, v: unknown) => string | null;
|
|
242
283
|
|
|
243
284
|
const checkInt: KindCheck = (def, v) => {
|
|
285
|
+
if (def.disabledLiteral && v === "disabled") return null;
|
|
244
286
|
const lo = def.min ?? 0;
|
|
245
287
|
const ok = typeof v === "number" && Number.isInteger(v) && v >= lo && (def.max === undefined || v <= def.max);
|
|
246
288
|
if (ok) return null;
|
|
247
289
|
if (def.max !== undefined) return `must be an integer from ${lo} to ${def.max}`;
|
|
248
|
-
|
|
290
|
+
if (lo > 0) return `must be an integer of at least ${lo}`;
|
|
291
|
+
return def.disabledLiteral ? 'must be a non-negative integer or "disabled"' : "must be a non-negative integer";
|
|
249
292
|
};
|
|
250
293
|
|
|
251
294
|
const checkString: KindCheck = (def, v) => {
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
import * as fs from "node:fs";
|
|
13
13
|
import path from "node:path";
|
|
14
14
|
import { getDashboardConfigDir } from "./dashboard-paths.js";
|
|
15
|
+
import { nativePathApi, type PathApi, piPathsEqual } from "./pi-path-compare.js";
|
|
15
16
|
import {
|
|
16
17
|
ancestorKeys,
|
|
17
18
|
identityMatches,
|
|
@@ -100,14 +101,25 @@ export function readPiTrustFileLockless(agentDir: string): PiTrustFileRead {
|
|
|
100
101
|
}
|
|
101
102
|
}
|
|
102
103
|
|
|
103
|
-
/**
|
|
104
|
+
/**
|
|
105
|
+
* pi's nearest recorded entry for `cwdKey` (walks `cwdKey` then its ancestors).
|
|
106
|
+
* Mirrors pi 1.5 `findNearestTrustEntry`: at each level every trust-file key is
|
|
107
|
+
* matched with pi's `pathsEqual` (resolved; case-insensitive on win32), the first
|
|
108
|
+
* key in object order with a boolean value wins, and the STORED key spelling is
|
|
109
|
+
* returned. `pathApi` defaults to the native `node:path`.
|
|
110
|
+
* See change: update-pi-core-1-5-adopt-apis (design D2).
|
|
111
|
+
*/
|
|
104
112
|
export function nearestRecordedEntry(
|
|
105
113
|
data: Record<string, boolean>,
|
|
106
114
|
cwdKey: string,
|
|
115
|
+
pathApi: PathApi = nativePathApi(),
|
|
107
116
|
): { path: string; decision: boolean } | null {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
117
|
+
const keys = Object.keys(data);
|
|
118
|
+
for (const dir of ancestorKeys(cwdKey, pathApi)) {
|
|
119
|
+
for (const k of keys) {
|
|
120
|
+
const v = data[k];
|
|
121
|
+
if ((v === true || v === false) && piPathsEqual(k, dir, pathApi)) return { path: k, decision: v };
|
|
122
|
+
}
|
|
111
123
|
}
|
|
112
124
|
return null;
|
|
113
125
|
}
|