@piagent/platform 1.3.1 → 1.4.1
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/CHANGELOG.md +132 -0
- package/README.md +10 -4
- package/README.vi.md +27 -0
- package/architecture/layers.json +96 -1
- package/docs/README.md +1 -0
- package/docs/architecture.md +1 -0
- package/docs/authority-manifest.md +1 -0
- package/docs/auto-delegation-policy.md +1 -0
- package/docs/capability-packs.md +1 -0
- package/docs/command-reference-vietnamese.md +5 -4
- package/docs/context-engine.md +1 -0
- package/docs/context-window-policy.md +1 -0
- package/docs/distribution-standard.md +8 -7
- package/docs/en/architecture.md +13 -0
- package/docs/herdr-workflow.md +1 -0
- package/docs/languages.json +20 -4
- package/docs/mcp-and-tools.md +125 -9
- package/docs/memory-policy.md +1 -0
- package/docs/model-options.md +1 -0
- package/docs/oauth-providers.md +1 -0
- package/docs/operator-manual-vietnamese.md +15 -12
- package/docs/package-architecture-notes.md +1 -0
- package/docs/project-adapters.md +1 -0
- package/docs/project-onboarding.md +1 -0
- package/docs/publishing-for-teams.md +37 -0
- package/docs/quality-benchmark.md +1 -0
- package/docs/quickstart-vietnamese.md +3 -2
- package/docs/release-install-policy.md +22 -8
- package/docs/runtime-harness-standard.md +2 -1
- package/docs/runtime-policy-design.md +1 -0
- package/docs/runtime-quality-baseline.md +1 -0
- package/docs/security-redaction-benchmark.md +1 -0
- package/docs/security-threat-model.md +2 -1
- package/docs/subagent-orchestration-capabilities.md +1 -0
- package/docs/subagents-and-multiagent.md +1 -0
- package/docs/task-implementation-contract.md +12 -4
- package/docs/task-lifecycle-vietnamese.md +1 -0
- package/docs/team-onboarding.md +3 -2
- package/docs/third-party-neutrality.md +26 -0
- package/docs/usage-observability.md +71 -0
- package/docs/vercel-docs-site.md +1 -0
- package/docs/vi/architecture.md +13 -0
- package/docs/workflow-recipes.md +1 -0
- package/docs-site/architecture.html +5 -1
- package/docs-site/benchmark.html +5 -1
- package/docs-site/commands.html +5 -1
- package/docs-site/content/en/index.html +49 -0
- package/docs-site/content/en/runtime.html +13 -0
- package/docs-site/content/index.html +49 -0
- package/docs-site/content/runtime.html +28 -0
- package/docs-site/context-engine.html +5 -1
- package/docs-site/en/architecture.html +5 -1
- package/docs-site/en/benchmark.html +5 -1
- package/docs-site/en/commands.html +5 -1
- package/docs-site/en/context-engine.html +5 -1
- package/docs-site/en/index.html +54 -1
- package/docs-site/en/mcp-approval.html +5 -1
- package/docs-site/en/mcp-auth.html +5 -1
- package/docs-site/en/mcp-servers.html +5 -1
- package/docs-site/en/mcp.html +5 -1
- package/docs-site/en/permissions.html +5 -1
- package/docs-site/en/profiles.html +5 -1
- package/docs-site/en/quickstart.html +5 -1
- package/docs-site/en/runtime.html +18 -1
- package/docs-site/en/scope.html +5 -1
- package/docs-site/en/security.html +5 -1
- package/docs-site/en/team.html +5 -1
- package/docs-site/en/whats-new.html +5 -1
- package/docs-site/en/workflows.html +5 -1
- package/docs-site/index.html +54 -1
- package/docs-site/mcp-approval.html +5 -1
- package/docs-site/mcp-auth.html +5 -1
- package/docs-site/mcp-servers.html +5 -1
- package/docs-site/mcp.html +5 -1
- package/docs-site/permissions.html +5 -1
- package/docs-site/profiles.html +5 -1
- package/docs-site/quickstart.html +5 -1
- package/docs-site/runtime.html +33 -1
- package/docs-site/scope.html +5 -1
- package/docs-site/security.html +5 -1
- package/docs-site/team.html +5 -1
- package/docs-site/whats-new.html +5 -1
- package/docs-site/workflows.html +5 -1
- package/evals/fixtures/mutation-provenance-record.invalid.json +17 -0
- package/evals/fixtures/mutation-provenance-record.valid.json +27 -0
- package/evals/fixtures/piagent-webui/approval-v1.invalid.json +54 -0
- package/evals/fixtures/piagent-webui/approval-v1.valid.json +58 -0
- package/evals/fixtures/piagent-webui/attachment-v1.invalid.json +25 -0
- package/evals/fixtures/piagent-webui/attachment-v1.valid.json +25 -0
- package/evals/fixtures/piagent-webui/capabilities-v1.invalid.json +51 -0
- package/evals/fixtures/piagent-webui/capabilities-v1.valid.json +122 -0
- package/evals/fixtures/piagent-webui/commit-summary-v1.invalid.json +10 -0
- package/evals/fixtures/piagent-webui/commit-summary-v1.valid.json +25 -0
- package/evals/fixtures/piagent-webui/control-command-v1.invalid.json +37 -0
- package/evals/fixtures/piagent-webui/control-command-v1.valid.json +35 -0
- package/evals/fixtures/piagent-webui/diff-v1.invalid.json +13 -0
- package/evals/fixtures/piagent-webui/diff-v1.valid.json +141 -0
- package/evals/fixtures/piagent-webui/gateway-capabilities-v1.invalid.json +35 -0
- package/evals/fixtures/piagent-webui/gateway-capabilities-v1.valid.json +35 -0
- package/evals/fixtures/piagent-webui/gateway-protocol-v1.invalid.json +14 -0
- package/evals/fixtures/piagent-webui/gateway-protocol-v1.valid.json +14 -0
- package/evals/fixtures/piagent-webui/handoff-history-v1.invalid.json +16 -0
- package/evals/fixtures/piagent-webui/handoff-history-v1.valid.json +16 -0
- package/evals/fixtures/piagent-webui/model-catalog-v1.invalid.json +31 -0
- package/evals/fixtures/piagent-webui/model-catalog-v1.valid.json +43 -0
- package/evals/fixtures/piagent-webui/queue-v1.invalid.json +29 -0
- package/evals/fixtures/piagent-webui/queue-v1.valid.json +44 -0
- package/evals/fixtures/piagent-webui/recovery-history-v1.invalid.json +17 -0
- package/evals/fixtures/piagent-webui/recovery-history-v1.valid.json +20 -0
- package/evals/fixtures/piagent-webui/release-monitor-v1.invalid.json +12 -0
- package/evals/fixtures/piagent-webui/release-monitor-v1.valid.json +29 -0
- package/evals/fixtures/piagent-webui/review-state-v1.invalid.json +25 -0
- package/evals/fixtures/piagent-webui/review-state-v1.valid.json +38 -0
- package/evals/fixtures/piagent-webui/runtime-event-v2.invalid.json +49 -0
- package/evals/fixtures/piagent-webui/runtime-event-v2.valid.json +49 -0
- package/evals/fixtures/piagent-webui/session-catalog-v1.invalid.json +17 -0
- package/evals/fixtures/piagent-webui/session-catalog-v1.valid.json +58 -0
- package/evals/fixtures/piagent-webui/session-command-v1.invalid.json +19 -0
- package/evals/fixtures/piagent-webui/session-command-v1.valid.json +19 -0
- package/evals/fixtures/piagent-webui/snapshot-v1.invalid.json +5 -0
- package/evals/fixtures/piagent-webui/snapshot-v1.valid.json +191 -0
- package/evals/fixtures/piagent-webui/source-change-v1.invalid.json +57 -0
- package/evals/fixtures/piagent-webui/source-change-v1.valid.json +98 -0
- package/evals/fixtures/piagent-webui/source-mutation-v1.invalid.json +19 -0
- package/evals/fixtures/piagent-webui/source-mutation-v1.valid.json +38 -0
- package/evals/fixtures/piagent-webui/source-revert-v1.invalid.json +20 -0
- package/evals/fixtures/piagent-webui/source-revert-v1.valid.json +62 -0
- package/evals/fixtures/piagent-webui/subagent-tree-v1.invalid.json +26 -0
- package/evals/fixtures/piagent-webui/subagent-tree-v1.valid.json +39 -0
- package/evals/fixtures/piagent-webui/task-index-v1.invalid.json +15 -0
- package/evals/fixtures/piagent-webui/task-index-v1.valid.json +15 -0
- package/evals/fixtures/piagent-webui/task-timeline-v1.invalid.json +14 -0
- package/evals/fixtures/piagent-webui/task-timeline-v1.valid.json +16 -0
- package/evals/fixtures/piagent-webui/transcript-v1.invalid.json +35 -0
- package/evals/fixtures/piagent-webui/transcript-v1.valid.json +55 -0
- package/evals/fixtures/task-baseline-manifest.invalid.json +16 -0
- package/evals/fixtures/task-baseline-manifest.valid.json +41 -0
- package/evals/fixtures/verifier-file-snapshot.invalid.json +21 -0
- package/evals/fixtures/verifier-file-snapshot.valid.json +21 -0
- package/package.json +43 -4
- package/packages/piagent-core/README.md +3 -2
- package/packages/piagent-core/benchmark/benchmark-candidate.d.ts +1 -0
- package/packages/piagent-core/benchmark/benchmark-forensics.d.ts +1 -0
- package/packages/piagent-core/benchmark/benchmark-ledger.d.ts +4 -0
- package/packages/piagent-core/benchmark/benchmark-record-validation.d.ts +1 -0
- package/packages/piagent-core/benchmark/benchmark-runtime.d.ts +1 -0
- package/packages/piagent-core/capabilities/capability-core.js +2 -2
- package/packages/piagent-core/capabilities/capability-verification-cache.js +17 -7
- package/packages/piagent-core/capabilities/runtime-integrity.js +190 -0
- package/packages/piagent-core/extensions/piagent-guard.ts +80 -272
- package/packages/piagent-core/extensions/redaction-core.d.ts +2 -0
- package/packages/piagent-core/extensions/runtime-evidence.js +12 -1
- package/packages/piagent-core/extensions/shell-reach.ts +250 -0
- package/packages/piagent-core/extensions/task-journal.js +30 -1
- package/packages/piagent-core/extensions/task-state.js +33 -36
- package/packages/piagent-core/mcp/mcp-command-actions.js +1 -1
- package/packages/piagent-core/mcp/mcp-server-catalog.js +139 -9
- package/packages/piagent-core/package.json +1 -1
- package/packages/piagent-core/runtime/hooks/session-start-hook.ts +2 -2
- package/packages/piagent-core/runtime/hooks/tool-call-hook.ts +12 -2
- package/packages/piagent-core/runtime/hooks/tool-result-hook.ts +20 -19
- package/packages/piagent-core/runtime/hooks/tool-result-metadata.ts +13 -0
- package/packages/piagent-core/runtime/input/chat-images.ts +2 -2
- package/packages/piagent-core/runtime/inspection/activity-event-adapter.ts +94 -0
- package/packages/piagent-core/runtime/inspection/approval-broker.ts +318 -0
- package/packages/piagent-core/runtime/inspection/commit-summary-projection.ts +59 -0
- package/packages/piagent-core/runtime/inspection/context-telemetry-inspection.ts +37 -0
- package/packages/piagent-core/runtime/inspection/criteria-links.ts +295 -0
- package/packages/piagent-core/runtime/inspection/diff-projection.ts +499 -0
- package/packages/piagent-core/runtime/inspection/git-filter-safety.ts +38 -0
- package/packages/piagent-core/runtime/inspection/git-numstat-adapter.ts +71 -0
- package/packages/piagent-core/runtime/inspection/git-status-adapter.ts +493 -0
- package/packages/piagent-core/runtime/inspection/git-tree-adapter.ts +108 -0
- package/packages/piagent-core/runtime/inspection/mcp-control.ts +10 -0
- package/packages/piagent-core/runtime/inspection/mutation-provenance-contract.ts +131 -0
- package/packages/piagent-core/runtime/inspection/mutation-provenance-recorder.ts +48 -0
- package/packages/piagent-core/runtime/inspection/mutation-provenance-store.ts +161 -0
- package/packages/piagent-core/runtime/inspection/project-runtime-inspection.ts +36 -0
- package/packages/piagent-core/runtime/inspection/review-state-contract.ts +108 -0
- package/packages/piagent-core/runtime/inspection/review-state-projection.ts +93 -0
- package/packages/piagent-core/runtime/inspection/review-state-store.ts +112 -0
- package/packages/piagent-core/runtime/inspection/runtime-event-store.ts +262 -0
- package/packages/piagent-core/runtime/inspection/same-process-bridge-proof.ts +103 -0
- package/packages/piagent-core/runtime/inspection/source-change-projection.ts +471 -0
- package/packages/piagent-core/runtime/inspection/source-evidence-contract.ts +139 -0
- package/packages/piagent-core/runtime/inspection/source-evidence-store.ts +315 -0
- package/packages/piagent-core/runtime/inspection/source-handoff-store.ts +70 -0
- package/packages/piagent-core/runtime/inspection/source-inspection-plan.ts +34 -0
- package/packages/piagent-core/runtime/inspection/source-mutation-projection.ts +164 -0
- package/packages/piagent-core/runtime/inspection/source-mutation-store.ts +168 -0
- package/packages/piagent-core/runtime/inspection/source-open-target.ts +38 -0
- package/packages/piagent-core/runtime/inspection/source-revert-projection.ts +147 -0
- package/packages/piagent-core/runtime/inspection/task-baseline-start-capture.ts +22 -0
- package/packages/piagent-core/runtime/inspection/task-compaction-history.ts +160 -0
- package/packages/piagent-core/runtime/inspection/task-control-journal.ts +131 -0
- package/packages/piagent-core/runtime/inspection/task-handoff-history.ts +95 -0
- package/packages/piagent-core/runtime/inspection/task-provenance-projection.ts +60 -0
- package/packages/piagent-core/runtime/inspection/task-recovery-timeline.ts +88 -0
- package/packages/piagent-core/runtime/inspection/task-run-index.ts +87 -0
- package/packages/piagent-core/runtime/inspection/task-source-projection.ts +401 -0
- package/packages/piagent-core/runtime/inspection/task-subagent-tree.ts +101 -0
- package/packages/piagent-core/runtime/inspection/text-diff.ts +60 -0
- package/packages/piagent-core/runtime/inspection/verifier-snapshot-contract.ts +114 -0
- package/packages/piagent-core/runtime/inspection/verifier-snapshot-store.ts +189 -0
- package/packages/piagent-core/runtime/inspection/webui-snapshot.ts +320 -0
- package/packages/piagent-core/runtime/inspection/workspace-file-reader.ts +132 -0
- package/packages/piagent-core/runtime/inspection/workspace-source-projection.ts +96 -0
- package/packages/piagent-core/runtime/inspection/zero-turn-conformance.ts +175 -0
- package/packages/piagent-core/runtime/orchestration/owned-work-budget.ts +93 -6
- package/packages/piagent-core/runtime/policy/block-remedy.ts +139 -0
- package/packages/piagent-core/runtime/policy/source-index-transaction.ts +173 -0
- package/packages/piagent-core/runtime/policy/source-mutation-guard-binding.ts +42 -0
- package/packages/piagent-core/runtime/policy/source-mutation-guard.ts +184 -0
- package/packages/piagent-core/runtime/policy/source-worktree-transaction.ts +105 -0
- package/packages/piagent-core/runtime/product/activity-inspector-footer.ts +5 -3
- package/packages/piagent-core/runtime/product/activity-inspector.ts +85 -343
- package/packages/piagent-core/runtime/recovery/resume-state.ts +38 -1
- package/packages/piagent-core/runtime/registration/activity-inspector-command.ts +68 -14
- package/packages/piagent-core/runtime/registration/task-start-tool.ts +22 -27
- package/packages/piagent-core/runtime/session/model-authorship-state.ts +31 -3
- package/packages/piagent-core/runtime/session/runtime-state.ts +11 -1
- package/packages/piagent-core/runtime/session/token-economics.js +34 -0
- package/packages/piagent-core/runtime/tools/phase-tool-runtime.ts +2 -1
- package/packages/piagent-core/runtime/workflows/task-intake.ts +5 -0
- package/packages/piagent-core/security/sensitive-data.js +7 -0
- package/packages/piagent-webui/dist/client/assets/index-DwKCWbwd.css +1 -0
- package/packages/piagent-webui/dist/client/assets/index-bu7XpD9Q.js +172 -0
- package/packages/piagent-webui/dist/client/index.html +16 -0
- package/packages/piagent-webui/extension/attachment-store.ts +323 -0
- package/packages/piagent-webui/extension/held-message-queue.ts +311 -0
- package/packages/piagent-webui/extension/lifecycle-controller.ts +423 -0
- package/packages/piagent-webui/extension/lifecycle-event-adapter.ts +23 -0
- package/packages/piagent-webui/extension/piagent-webui.ts +470 -0
- package/packages/piagent-webui/extension/review-controller.ts +160 -0
- package/packages/piagent-webui/extension/same-session-bridge.ts +500 -0
- package/packages/piagent-webui/extension/session-options-controller.ts +281 -0
- package/packages/piagent-webui/extension/session-stream-adapter.ts +249 -0
- package/packages/piagent-webui/extension/source-mutation-controller.ts +215 -0
- package/packages/piagent-webui/extension/source-open-controller.ts +136 -0
- package/packages/piagent-webui/extension/source-revert-controller.ts +189 -0
- package/packages/piagent-webui/extension/terminal-session-adapter.ts +73 -0
- package/packages/piagent-webui/extension/vscode-handoff.ts +51 -0
- package/packages/piagent-webui/gateway/control-socket.ts +92 -0
- package/packages/piagent-webui/gateway/extension-authority.ts +47 -0
- package/packages/piagent-webui/gateway/gateway-events.ts +60 -0
- package/packages/piagent-webui/gateway/gateway-protocol-service.ts +64 -0
- package/packages/piagent-webui/gateway/gateway-service.ts +215 -0
- package/packages/piagent-webui/gateway/gateway-session-stream.ts +110 -0
- package/packages/piagent-webui/gateway/mcp-auth-broker.ts +158 -0
- package/packages/piagent-webui/gateway/native-project-picker.ts +29 -0
- package/packages/piagent-webui/gateway/pi-host.ts +41 -0
- package/packages/piagent-webui/gateway/profile-state.ts +1 -0
- package/packages/piagent-webui/gateway/project-registry.ts +108 -0
- package/packages/piagent-webui/gateway/provider-auth-broker.ts +172 -0
- package/packages/piagent-webui/gateway/session-catalog.ts +128 -0
- package/packages/piagent-webui/gateway/session-command-controller.ts +237 -0
- package/packages/piagent-webui/gateway/session-command-store.ts +224 -0
- package/packages/piagent-webui/gateway/session-inspection-registry.ts +239 -0
- package/packages/piagent-webui/gateway/session-lease-store.ts +1 -0
- package/packages/piagent-webui/gateway/session-metadata-store.ts +152 -0
- package/packages/piagent-webui/gateway/session-runtime-supervisor.ts +489 -0
- package/packages/piagent-webui/ownership/gateway-runtime-context.ts +8 -0
- package/packages/piagent-webui/ownership/profile-state.ts +117 -0
- package/packages/piagent-webui/ownership/session-lease-store.ts +329 -0
- package/packages/piagent-webui/ownership/session-refs.ts +8 -0
- package/packages/piagent-webui/package.json +33 -0
- package/packages/piagent-webui/server/README.md +4 -0
- package/packages/piagent-webui/server/benchmark-release-monitor.ts +230 -0
- package/packages/piagent-webui/server/core-inspection-provider.ts +403 -0
- package/packages/piagent-webui/server/gateway-websocket.ts +143 -0
- package/packages/piagent-webui/server/http-security.ts +27 -0
- package/packages/piagent-webui/server/ipc-read-model-client.ts +89 -0
- package/packages/piagent-webui/server/loopback-server.ts +368 -0
- package/packages/piagent-webui/server/read-model-provider.ts +37 -0
- package/packages/piagent-webui/server/read-only-router.ts +105 -0
- package/packages/piagent-webui/server/session-auth.ts +88 -0
- package/packages/piagent-webui/server/sidecar-main.ts +86 -0
- package/packages/piagent-webui/server/sse-hub.ts +76 -0
- package/packages/piagent-webui/server/static-bundle.ts +40 -0
- package/packages/piagent-webui/server/transcript-projection.ts +125 -0
- package/schemas/mutation-provenance-record.schema.json +100 -0
- package/schemas/piagent-webui/approval-v1.schema.json +654 -0
- package/schemas/piagent-webui/attachment-v1.schema.json +267 -0
- package/schemas/piagent-webui/capabilities-v1.schema.json +729 -0
- package/schemas/piagent-webui/catalog-v1.json +240 -0
- package/schemas/piagent-webui/commit-summary-v1.schema.json +63 -0
- package/schemas/piagent-webui/common-v1.schema.json +479 -0
- package/schemas/piagent-webui/control-command-v1.schema.json +1780 -0
- package/schemas/piagent-webui/diff-v1.schema.json +826 -0
- package/schemas/piagent-webui/gateway-capabilities-v1.schema.json +136 -0
- package/schemas/piagent-webui/gateway-protocol-v1.schema.json +456 -0
- package/schemas/piagent-webui/handoff-history-v1.schema.json +92 -0
- package/schemas/piagent-webui/model-catalog-v1.schema.json +95 -0
- package/schemas/piagent-webui/queue-v1.schema.json +99 -0
- package/schemas/piagent-webui/recovery-history-v1.schema.json +144 -0
- package/schemas/piagent-webui/release-monitor-v1.schema.json +173 -0
- package/schemas/piagent-webui/review-state-v1.schema.json +206 -0
- package/schemas/piagent-webui/runtime-event-v2.schema.json +5206 -0
- package/schemas/piagent-webui/session-catalog-v1.schema.json +222 -0
- package/schemas/piagent-webui/session-command-v1.schema.json +390 -0
- package/schemas/piagent-webui/snapshot-v1.schema.json +2622 -0
- package/schemas/piagent-webui/source-change-v1.schema.json +763 -0
- package/schemas/piagent-webui/source-mutation-v1.schema.json +96 -0
- package/schemas/piagent-webui/source-revert-v1.schema.json +130 -0
- package/schemas/piagent-webui/subagent-tree-v1.schema.json +88 -0
- package/schemas/piagent-webui/task-index-v1.schema.json +74 -0
- package/schemas/piagent-webui/task-timeline-v1.schema.json +49 -0
- package/schemas/piagent-webui/transcript-v1.schema.json +243 -0
- package/schemas/task-baseline-manifest.schema.json +122 -0
- package/schemas/verifier-file-snapshot.schema.json +81 -0
- package/scripts/build-docs-site.mjs +21 -1
- package/scripts/check-architecture.mjs +1 -0
- package/scripts/check-doc-languages.mjs +19 -2
- package/scripts/check-third-party-neutrality.mjs +43 -0
- package/scripts/explain-command.mjs +240 -0
- package/scripts/install-global.sh +105 -4
- package/scripts/mcp-manage.mjs +17 -4
- package/scripts/pi-session-stats.sh +10 -2
- package/scripts/piagent-cli.mjs +30 -3
- package/scripts/piagent-dashboard.mjs +261 -0
- package/scripts/piagent-webui-launcher.mjs +121 -0
- package/scripts/setup.sh +69 -33
- package/scripts/traffic-snapshot.mjs +214 -0
- package/scripts/typescript-loader.mjs +42 -1
- package/scripts/uninstall-global.sh +53 -2
- package/scripts/update-global.mjs +33 -1
- package/scripts/verify-local.sh +257 -0
- package/scripts/verify-release-identity.mjs +4 -1
- package/scripts/verify-translation-pairing.mjs +121 -0
|
@@ -49,7 +49,7 @@ type SessionStartHookDependencies = {
|
|
|
49
49
|
inspectResume: (cwd: string, task: TaskContract, sessionId: string) => ResumeState;
|
|
50
50
|
telemetry: (ctx: ExtensionContext, payload: Record<string, unknown>) => void;
|
|
51
51
|
syncTrajectory?: (ctx: ExtensionContext, task: TaskContract) => TrajectorySyncResult;
|
|
52
|
-
afterStart?: (ctx: ExtensionContext) => void
|
|
52
|
+
afterStart?: (ctx: ExtensionContext) => void | Promise<void>;
|
|
53
53
|
};
|
|
54
54
|
|
|
55
55
|
export function registerSessionStartHook(pi: ExtensionAPI, dependencies: SessionStartHookDependencies): void {
|
|
@@ -227,6 +227,6 @@ export function registerSessionStartHook(pi: ExtensionAPI, dependencies: Session
|
|
|
227
227
|
taskRecovery,
|
|
228
228
|
executionBackend
|
|
229
229
|
});
|
|
230
|
-
dependencies.afterStart?.(ctx);
|
|
230
|
+
await dependencies.afterStart?.(ctx);
|
|
231
231
|
});
|
|
232
232
|
}
|
|
@@ -2,6 +2,7 @@ import crypto from "node:crypto";
|
|
|
2
2
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
|
|
4
4
|
import { toolResultFingerprint } from "../../extensions/context-engine.js";
|
|
5
|
+
import { withRemedy } from "../policy/block-remedy.ts";
|
|
5
6
|
import { observeTrajectorySync } from "../trajectory/trajectory-observability.ts";
|
|
6
7
|
import type { TrajectorySyncResult } from "../trajectory/trajectory-runtime.ts";
|
|
7
8
|
|
|
@@ -17,6 +18,7 @@ type ToolCallHookDependencies = {
|
|
|
17
18
|
beforeAuthorize?: (event: ToolCallEvent, ctx: ExtensionContext) => Promise<ToolCallDecision> | ToolCallDecision;
|
|
18
19
|
authorize: (event: ToolCallEvent, ctx: ExtensionContext) => Promise<ToolCallDecision> | ToolCallDecision;
|
|
19
20
|
reviewBudgetDecision?: (event: ToolCallEvent, ctx: ExtensionContext) => ToolCallDecision;
|
|
21
|
+
beforeStart?: (event: ToolCallEvent, ctx: ExtensionContext) => ToolCallDecision;
|
|
20
22
|
afterDecision?: (
|
|
21
23
|
event: ToolCallEvent,
|
|
22
24
|
ctx: ExtensionContext,
|
|
@@ -72,7 +74,15 @@ export function registerToolCallHook(pi: ExtensionAPI, dependencies: ToolCallHoo
|
|
|
72
74
|
const decision = authorizationDecision && typeof authorizationDecision === "object" && authorizationDecision.block
|
|
73
75
|
? authorizationDecision
|
|
74
76
|
: dependencies.reviewBudgetDecision?.(resolvedEvent, ctx);
|
|
75
|
-
const
|
|
77
|
+
const startDecision = !(decision && typeof decision === "object" && decision.block) ? dependencies.beforeStart?.(resolvedEvent, ctx) : undefined;
|
|
78
|
+
const finalDecision = startDecision && typeof startDecision === "object" && startDecision.block ? startDecision : decision;
|
|
79
|
+
// Every refusal leaves through here, so this is where it is answered. A
|
|
80
|
+
// remedy attached at the 29 sites that build one is a remedy the next site
|
|
81
|
+
// will forget.
|
|
82
|
+
const answered = finalDecision && typeof finalDecision === "object" && finalDecision.block
|
|
83
|
+
? withRemedy(finalDecision)
|
|
84
|
+
: finalDecision;
|
|
85
|
+
const blockedDecision = answered && typeof answered === "object" ? answered : undefined;
|
|
76
86
|
record(ctx, {
|
|
77
87
|
activityId: `decision:${toolCallId}`,
|
|
78
88
|
event: "tool_decision",
|
|
@@ -88,6 +98,6 @@ export function registerToolCallHook(pi: ExtensionAPI, dependencies: ToolCallHoo
|
|
|
88
98
|
observeTrajectorySync(ctx, dependencies.afterAuthorized?.(resolvedEvent, ctx, { toolCallId }), dependencies.telemetry);
|
|
89
99
|
}
|
|
90
100
|
dependencies.afterDecision?.(resolvedEvent, ctx, { toolCallId, allowed: !blockedDecision?.block, reason: blockedDecision?.reason });
|
|
91
|
-
return
|
|
101
|
+
return answered;
|
|
92
102
|
});
|
|
93
103
|
}
|
|
@@ -11,6 +11,7 @@ import { redactForStorage, redactSensitiveText } from "../../extensions/redactio
|
|
|
11
11
|
import { appendObservedBashResult, hashEvidenceCommand, observedBashResultFromToolResultEvent } from "../../extensions/runtime-evidence.js";
|
|
12
12
|
import { workingTreeSnapshot, workingTreeSnapshotHasUnavailableEvidence } from "../../extensions/task-state.js";
|
|
13
13
|
import { workingTreeObservation } from "../../extensions/working-tree-digest.js";
|
|
14
|
+
import { recordMutationResult } from "../inspection/mutation-provenance-recorder.ts";
|
|
14
15
|
import { boundedGitDiffReview } from "../quality/performance-assurance.ts";
|
|
15
16
|
import { currentFileContentDigests } from "../quality/model-mutation-proof.ts";
|
|
16
17
|
import { boundedPerformanceReviewResultText } from "../quality/performance-review-evidence.ts";
|
|
@@ -18,6 +19,7 @@ import { attachToolResultCompactionDetails, compactToolResultDetails, compactToo
|
|
|
18
19
|
import { RuntimeSessionState, type ObservedTaskContext } from "../session/runtime-state.ts";
|
|
19
20
|
import { observeTrajectorySync } from "../trajectory/trajectory-observability.ts";
|
|
20
21
|
import type { TrajectorySyncResult } from "../trajectory/trajectory-runtime.ts";
|
|
22
|
+
import { patchLineStats } from "./tool-result-metadata.ts";
|
|
21
23
|
|
|
22
24
|
type ToolResultEvent = { toolCallId?: string; toolName: string; input?: unknown; content?: unknown; details?: unknown; isError?: boolean; usage?: unknown };
|
|
23
25
|
type ObservedBashResult = NonNullable<ReturnType<typeof observedBashResultFromToolResultEvent>>;
|
|
@@ -50,7 +52,8 @@ type ToolResultHookDependencies = {
|
|
|
50
52
|
ctx: ExtensionContext,
|
|
51
53
|
observed: ObservedVerificationResult,
|
|
52
54
|
pendingContext: ObservedTaskContext[],
|
|
53
|
-
maxManifestFiles: number, shellSnapshotBefore?: Record<string, string>, eventTree?: WorkingTreeObservation
|
|
55
|
+
maxManifestFiles: number, shellSnapshotBefore?: Record<string, string>, eventTree?: WorkingTreeObservation,
|
|
56
|
+
readProtectedPaths?: string[]
|
|
54
57
|
) => unknown;
|
|
55
58
|
extractLikelyPath: (cwd: string, input: Record<string, unknown>) => string | undefined;
|
|
56
59
|
mutationTargets: (cwd: string, toolName: string, input: Record<string, unknown>) => string[];
|
|
@@ -124,20 +127,6 @@ function boundedToolResultText(content: unknown): string {
|
|
|
124
127
|
return text.slice(-20_000);
|
|
125
128
|
}
|
|
126
129
|
|
|
127
|
-
function patchLineStats(details: unknown): { additions?: number; deletions?: number } {
|
|
128
|
-
if (!details || typeof details !== "object") return {};
|
|
129
|
-
const patch = (details as Record<string, unknown>).patch;
|
|
130
|
-
if (typeof patch !== "string" || !patch.trim()) return {};
|
|
131
|
-
let additions = 0;
|
|
132
|
-
let deletions = 0;
|
|
133
|
-
for (const line of patch.split(/\r?\n/)) {
|
|
134
|
-
if (line.startsWith("+++ ") || line.startsWith("--- ")) continue;
|
|
135
|
-
if (line.startsWith("+")) additions += 1;
|
|
136
|
-
else if (line.startsWith("-")) deletions += 1;
|
|
137
|
-
}
|
|
138
|
-
return { additions, deletions };
|
|
139
|
-
}
|
|
140
|
-
|
|
141
130
|
function countChangedStringLeaves(before: unknown, after: unknown): number {
|
|
142
131
|
if (typeof before === "string" && typeof after === "string") return before === after ? 0 : 1;
|
|
143
132
|
if (Array.isArray(before) && Array.isArray(after)) {
|
|
@@ -270,9 +259,9 @@ export function registerToolResultHook(pi: ExtensionAPI, dependencies: ToolResul
|
|
|
270
259
|
dependencies.recordObservedTaskVerification(
|
|
271
260
|
pi,
|
|
272
261
|
ctx,
|
|
273
|
-
{ ...observed, outputText: boundedToolResultText(event.content) },
|
|
262
|
+
{ ...observed, toolCallId: observed.toolCallId ?? resultToolCallId, outputText: boundedToolResultText(event.content) },
|
|
274
263
|
pendingContext,
|
|
275
|
-
dependencies.maxManifestFiles, shellSnapshotBefore, eventTree
|
|
264
|
+
dependencies.maxManifestFiles, shellSnapshotBefore, eventTree, readProtectedPaths
|
|
276
265
|
);
|
|
277
266
|
}
|
|
278
267
|
|
|
@@ -287,20 +276,32 @@ export function registerToolResultHook(pi: ExtensionAPI, dependencies: ToolResul
|
|
|
287
276
|
const currentSnapshot = taskIdentity ? eventTree?.snapshot : undefined;
|
|
288
277
|
const currentTreeDigest = taskIdentity ? eventTree?.digest : undefined;
|
|
289
278
|
const directMutationResult = modelMutationIdentity && currentSnapshot
|
|
290
|
-
? dependencies.state.
|
|
279
|
+
? dependencies.state.completeAuthorizedModelMutationEvidence(
|
|
291
280
|
modelMutationIdentity,
|
|
292
281
|
resultToolCallId,
|
|
293
282
|
successfulToolResult(event),
|
|
294
283
|
currentSnapshot,
|
|
295
284
|
currentFileContentDigests(ctx.cwd, directMutationTargets)
|
|
296
285
|
)
|
|
297
|
-
: { changedPaths: [] as string[], recordedDigests: {} as Record<string, string
|
|
286
|
+
: { changedPaths: [] as string[], recordedDigests: {} as Record<string, string>, beforeSnapshot: null,
|
|
287
|
+
targetPaths: [] as string[], recordedContentDigests: {} as Record<string, string>, proofModes: {} as Record<string, "full-content" | "exact-replacement"> };
|
|
298
288
|
const shellChangedPaths = taskIdentity && currentSnapshot && shellSnapshotBefore
|
|
299
289
|
? changedSnapshotFiles(shellSnapshotBefore, currentSnapshot)
|
|
300
290
|
: [];
|
|
301
291
|
if (modelMutationIdentity && shellChangedPaths.length > 0) {
|
|
302
292
|
dependencies.state.invalidateSuccessfulModelMutationPaths(modelMutationIdentity, shellChangedPaths);
|
|
303
293
|
}
|
|
294
|
+
if (modelMutationIdentity && currentSnapshot) {
|
|
295
|
+
try {
|
|
296
|
+
recordMutationResult({
|
|
297
|
+
projectRoot: ctx.cwd, identity: modelMutationIdentity, toolCallId: resultToolCallId, toolName: event.toolName,
|
|
298
|
+
recordedAt: dependencies.now(), successful: successfulToolResult(event), currentSnapshot,
|
|
299
|
+
completion: directMutationResult, shellSnapshotBefore, shellChangedPaths, protectedPaths: readProtectedPaths
|
|
300
|
+
});
|
|
301
|
+
} catch (error) {
|
|
302
|
+
ctx.ui.notify(`Piagent could not persist mutation provenance: ${error instanceof Error ? error.message : String(error)}`, "warn");
|
|
303
|
+
}
|
|
304
|
+
}
|
|
304
305
|
const outputText = boundedToolResultText(event.content);
|
|
305
306
|
const performanceReviewOutputText = boundedPerformanceReviewResultText(event.content);
|
|
306
307
|
const observedExitCode = observed?.exitCode
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export function patchLineStats(details: unknown): { additions?: number; deletions?: number } {
|
|
2
|
+
if (!details || typeof details !== "object") return {};
|
|
3
|
+
const patch = (details as Record<string, unknown>).patch;
|
|
4
|
+
if (typeof patch !== "string" || !patch.trim()) return {};
|
|
5
|
+
let additions = 0;
|
|
6
|
+
let deletions = 0;
|
|
7
|
+
for (const line of patch.split(/\r?\n/)) {
|
|
8
|
+
if (line.startsWith("+++ ") || line.startsWith("--- ")) continue;
|
|
9
|
+
if (line.startsWith("+")) additions += 1;
|
|
10
|
+
else if (line.startsWith("-")) deletions += 1;
|
|
11
|
+
}
|
|
12
|
+
return { additions, deletions };
|
|
13
|
+
}
|
|
@@ -32,7 +32,7 @@ function escapeRegExp(input: string): string {
|
|
|
32
32
|
return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
function
|
|
35
|
+
export function supportedChatImageMimeType(bytes: Buffer): string | undefined {
|
|
36
36
|
if (
|
|
37
37
|
bytes.length >= 24
|
|
38
38
|
&& bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
|
|
@@ -236,7 +236,7 @@ export function readChatImage(
|
|
|
236
236
|
offset += read;
|
|
237
237
|
}
|
|
238
238
|
if (offset !== bytes.length) return { status: "error", reason: "file changed while it was being read" };
|
|
239
|
-
const mimeType =
|
|
239
|
+
const mimeType = supportedChatImageMimeType(bytes);
|
|
240
240
|
if (!mimeType) return { status: "error", reason: "file bytes are not a supported image" };
|
|
241
241
|
return { status: "ok", absolutePath: canonicalPath, bytes, mimeType };
|
|
242
242
|
} finally {
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
import { redactSensitiveText } from "../../extensions/redaction-core.js";
|
|
4
|
+
import type { ActivityInspectorEvent } from "../product/activity-inspector.ts";
|
|
5
|
+
import type { RuntimeEventDraft, RuntimeEventRevision } from "./runtime-event-store.ts";
|
|
6
|
+
|
|
7
|
+
export type RuntimeEventIdentity = {
|
|
8
|
+
projectRef: string;
|
|
9
|
+
runtimeInstanceId: string;
|
|
10
|
+
sessionRef: string;
|
|
11
|
+
taskId: string | null;
|
|
12
|
+
taskRunId: string | null;
|
|
13
|
+
agentOperationId?: string | null;
|
|
14
|
+
};
|
|
15
|
+
export type ActivityEventAdapterInput = {
|
|
16
|
+
event: ActivityInspectorEvent & Record<string, unknown>;
|
|
17
|
+
identity: RuntimeEventIdentity;
|
|
18
|
+
revision: RuntimeEventRevision;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
22
|
+
function hash(value: string): string { return createHash("sha256").update(value).digest("hex"); }
|
|
23
|
+
function opaque(prefix: string, value: unknown): string { return `${prefix}.${hash(String(value ?? "unknown"))}`; }
|
|
24
|
+
function digest(value: unknown): string | null {
|
|
25
|
+
const candidate = String(value ?? "");
|
|
26
|
+
return /^[a-f0-9]{64}$/.test(candidate) ? `sha256:${candidate}` : /^sha256:[a-f0-9]{64}$/.test(candidate) ? candidate : null;
|
|
27
|
+
}
|
|
28
|
+
function safeText(value: unknown, maximum = 4000): { text: string; redacted: number } {
|
|
29
|
+
const source = String(value ?? "");
|
|
30
|
+
const redaction = redactSensitiveText(source);
|
|
31
|
+
const text = redaction.text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim().slice(0, maximum);
|
|
32
|
+
return { text, redacted: redaction.redacted ? 1 : 0 };
|
|
33
|
+
}
|
|
34
|
+
function correlation() {
|
|
35
|
+
return { commandId: null, messageRequestId: null, replacementId: null, approvalRequestId: null, causationEventId: null, idempotencyKeyDigest: null };
|
|
36
|
+
}
|
|
37
|
+
function base(identity: RuntimeEventIdentity, revision: RuntimeEventRevision, sourceObservedAt: string): Omit<RuntimeEventDraft, "kind" | "payload" | "evidence" | "redaction"> {
|
|
38
|
+
return { sourceObservedAt, projectRef: identity.projectRef, runtimeInstanceId: identity.runtimeInstanceId, sessionRef: identity.sessionRef,
|
|
39
|
+
taskId: identity.taskId, taskRunId: identity.taskRunId, agentOperationId: null, turnIndex: null, messageRef: null, toolCallId: null,
|
|
40
|
+
revision, correlation: correlation() };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function adaptActivityTelemetryEvent(input: ActivityEventAdapterInput): RuntimeEventDraft | null {
|
|
44
|
+
const event = input.event, observedAt = String(event.recordedAt ?? "");
|
|
45
|
+
if (!TIMESTAMP.test(observedAt)) return null;
|
|
46
|
+
const eventName = String(event.event ?? "");
|
|
47
|
+
if (!["tool_call", "tool_result", "tool_decision"].includes(eventName)) return null;
|
|
48
|
+
if (eventName === "tool_decision" && event.decision !== "blocked") return null;
|
|
49
|
+
const toolName = safeText(event.toolName ?? "unknown", 80).text.replace(/[^A-Za-z0-9._:@~-]/g, "-") || "unknown";
|
|
50
|
+
const rawToolCall = String(event.toolCallId ?? event.activityId ?? `${observedAt}:${toolName}`);
|
|
51
|
+
const hasOperation = typeof input.identity.agentOperationId === "string" && input.identity.agentOperationId.length > 0;
|
|
52
|
+
const operationRef = hasOperation ? opaque("operation", input.identity.agentOperationId) : null;
|
|
53
|
+
const toolCallRef = hasOperation ? opaque("tool", rawToolCall) : null;
|
|
54
|
+
const activityType = hasOperation ? "tool" : ["bash", "shell", "exec"].includes(toolName) ? "command" : "other";
|
|
55
|
+
const failed = eventName === "tool_result" && (event.isError === true || typeof event.exitCode === "number" && event.exitCode !== 0);
|
|
56
|
+
const blocked = eventName === "tool_decision";
|
|
57
|
+
const state = eventName === "tool_call" ? "started" : blocked ? "blocked" : failed ? "failed" : "finished";
|
|
58
|
+
const kind = `activity.${state}`;
|
|
59
|
+
const previewValue = blocked ? event.reason : event.command ?? event.targetPath ?? event.toolName;
|
|
60
|
+
const preview = safeText(previewValue, 4000);
|
|
61
|
+
const storedRedactions = typeof event.sensitiveValuesRedacted === "number" && Number.isInteger(event.sensitiveValuesRedacted)
|
|
62
|
+
? Math.max(0, Math.min(10_000, event.sensitiveValuesRedacted)) : 0;
|
|
63
|
+
const reasonCode = blocked ? "policy-blocked" : failed ? "tool-result-failed" : null;
|
|
64
|
+
return {
|
|
65
|
+
...base(input.identity, input.revision, observedAt), agentOperationId: operationRef, toolCallId: toolCallRef,
|
|
66
|
+
kind, evidence: "derived",
|
|
67
|
+
payload: {
|
|
68
|
+
state, activityType, activityRef: opaque("activity", `${input.identity.runtimeInstanceId}\0${input.identity.sessionRef}\0${rawToolCall}`),
|
|
69
|
+
toolName, inputDigest: digest((event as any).inputHash), outputDigest: digest((event as any).outputHash),
|
|
70
|
+
preview: preview.text || null, previewKind: preview.text ? "summary" : "none",
|
|
71
|
+
outputBytes: Number.isInteger((event as any).outputBytes) && (event as any).outputBytes >= 0 ? Math.min(1_000_000_000, (event as any).outputBytes) : null,
|
|
72
|
+
outputLines: Number.isInteger((event as any).outputLines) && (event as any).outputLines >= 0 ? Math.min(1_000_000_000, (event as any).outputLines) : null,
|
|
73
|
+
exitCode: typeof event.exitCode === "number" && Number.isInteger(event.exitCode) ? event.exitCode : null,
|
|
74
|
+
isError: eventName === "tool_result" ? failed : null,
|
|
75
|
+
affectedFileRefs: [], criterionIds: [], verifierAttemptIds: [], reasonCode
|
|
76
|
+
},
|
|
77
|
+
redaction: { applied: preview.redacted + storedRedactions > 0, valuesRemoved: Math.min(10_000, preview.redacted + storedRedactions), truncated: String(previewValue ?? "").length > 4000 }
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function runtimeStartedEventDraft(input: {
|
|
82
|
+
identity: Pick<RuntimeEventIdentity, "projectRef" | "runtimeInstanceId" | "sessionRef">;
|
|
83
|
+
revision: RuntimeEventRevision;
|
|
84
|
+
sourceObservedAt: string;
|
|
85
|
+
buildRef: string;
|
|
86
|
+
capabilitySnapshotRef: string;
|
|
87
|
+
}): RuntimeEventDraft {
|
|
88
|
+
return {
|
|
89
|
+
...base({ ...input.identity, taskId: null, taskRunId: null }, input.revision, input.sourceObservedAt),
|
|
90
|
+
kind: "runtime.started", evidence: "observed",
|
|
91
|
+
payload: { connectionState: "connected", operationState: "idle", buildRef: input.buildRef, capabilitySnapshotRef: input.capabilitySnapshotRef, reasonCode: null },
|
|
92
|
+
redaction: { applied: false, valuesRemoved: 0, truncated: false }
|
|
93
|
+
};
|
|
94
|
+
}
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
import { createHmac, randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
import { redactSensitiveText } from "../../extensions/redaction-core.js";
|
|
5
|
+
|
|
6
|
+
const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;
|
|
7
|
+
const PUBLIC_REF = /^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/;
|
|
8
|
+
const REVISION = /^[A-Za-z0-9][A-Za-z0-9._:~-]{0,159}$/;
|
|
9
|
+
const DIGEST = /^sha256:[a-f0-9]{64}$/;
|
|
10
|
+
const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
11
|
+
const MAX_PENDING = 32, MAX_RECENT = 64, DEFAULT_TTL_MS = 5 * 60_000;
|
|
12
|
+
|
|
13
|
+
type Identity = { projectRef: string; runtimeInstanceId: string; sessionRef: string; taskId: string; taskRunId: string;
|
|
14
|
+
agentOperationId: string; toolCallId: string };
|
|
15
|
+
type TreePrecondition = { workspaceRevision: string; indexRevision: string | null; preimageDigest: string };
|
|
16
|
+
type Revisions = { runtimeRevision: string; taskRevision: string; controlRevision: string; approvalRevision: string;
|
|
17
|
+
treePrecondition: TreePrecondition | null };
|
|
18
|
+
type ReceiptRevisions = Omit<Revisions, "treePrecondition">;
|
|
19
|
+
export type ApprovalAuthority = { identity: Omit<Identity, "toolCallId">; revisions: Omit<ReceiptRevisions, "approvalRevision">;
|
|
20
|
+
taskState: "active" | "terminal" } | null;
|
|
21
|
+
export type ApprovalActionDraft = {
|
|
22
|
+
kind: "external-provider-action" | "filesystem-write" | "filesystem-delete" | "workspace-patch" | "source-stage" | "source-unstage" | "source-revert";
|
|
23
|
+
preconditionClass: "runtime-only" | "workspace-tree" | "workspace-index";
|
|
24
|
+
toolName: string; rawAction: unknown; commandPreview?: string | null; parameterPreview?: string; targetPaths?: string[];
|
|
25
|
+
targetSummaries?: string[]; provider?: string | null; urlOrigin?: string | null; requestedScope: string; reason: string;
|
|
26
|
+
riskClass: "low" | "medium" | "high" | "critical"; allowConsequence: string; denyConsequence: string;
|
|
27
|
+
treePrecondition?: TreePrecondition | null;
|
|
28
|
+
};
|
|
29
|
+
type Request = { schemaVersion: 1; version: "piagent-webui-approval-v1"; recordType: "request"; approvalRef: string; decisionToken: string;
|
|
30
|
+
identity: Identity; action: Record<string, unknown>; expectedRevisions: Revisions; state: "waiting"; requestedAt: string; expiresAt: string;
|
|
31
|
+
executor: "pi-guard"; directExecution: false };
|
|
32
|
+
type Receipt = { schemaVersion: 1; version: "piagent-webui-approval-v1"; recordType: "receipt"; approvalRef: string; decisionId: string | null;
|
|
33
|
+
identity: Identity; actionDigest: string; state: "resolved" | "expired" | "cancelled"; decision: "allow" | "deny" | null;
|
|
34
|
+
winnerSurface: "webui" | "terminal" | "runtime-expiry" | "runtime-control" | "runtime-restart"; resolutionReason: string | null;
|
|
35
|
+
resolvedAt: string; preRevisions: Revisions; postRevisions: ReceiptRevisions; permit: Record<string, unknown>; deduplicated: boolean;
|
|
36
|
+
auditRef: string; executor: "pi-guard"; directExecution: false };
|
|
37
|
+
type Binding = { cwd: string; rawSessionId: string; runtimeInstanceId: string; secret: Buffer; authority(): ApprovalAuthority;
|
|
38
|
+
listeners: Set<(event: ApprovalBrokerEvent) => void>; pending: Map<string, Pending>; requests: Map<string, Request>; recent: Receipt[];
|
|
39
|
+
approvalCounter: number; approvalRevision: string };
|
|
40
|
+
type Pending = { request: Request; resolve(value: ApprovalGuardDecision): void; receipt: Receipt | null; timer: NodeJS.Timeout;
|
|
41
|
+
finalWaiters: Array<(receipt: Receipt) => void>; recheck(): boolean };
|
|
42
|
+
export type ApprovalBrokerEvent = { kind: "requested" | "resolved" | "expired" | "cancelled"; approvalRef: string; request?: Request; receipt?: Receipt };
|
|
43
|
+
export type ApprovalGuardDecision = { allowed: boolean; brokered: boolean; receipt: Receipt | null;
|
|
44
|
+
consume(): boolean; cancel(reasonCode?: string): void };
|
|
45
|
+
|
|
46
|
+
function canonical(value: unknown): string {
|
|
47
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
48
|
+
if (!value || typeof value !== "object") return JSON.stringify(value);
|
|
49
|
+
return `{${Object.entries(value as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b))
|
|
50
|
+
.map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;
|
|
51
|
+
}
|
|
52
|
+
function exactTimestamp(value: unknown): value is string {
|
|
53
|
+
if (typeof value !== "string" || !TIMESTAMP.test(value)) return false;
|
|
54
|
+
const parsed = Date.parse(value); return Number.isFinite(parsed) && new Date(parsed).toISOString() === value;
|
|
55
|
+
}
|
|
56
|
+
function exactKeys(value: unknown, keys: string[]): boolean {
|
|
57
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value)
|
|
58
|
+
&& canonical(Object.keys(value as Record<string, unknown>).sort()) === canonical([...keys].sort()));
|
|
59
|
+
}
|
|
60
|
+
function ref(prefix: string, secret: Buffer, value: unknown): string {
|
|
61
|
+
return `${prefix}.${createHmac("sha256", secret).update(canonical(value)).digest("hex")}`;
|
|
62
|
+
}
|
|
63
|
+
function digest(secret: Buffer, value: unknown): string { return `sha256:${createHmac("sha256", secret).update(canonical(value)).digest("hex")}`; }
|
|
64
|
+
function safe(value: unknown, maximum: number): { text: string; redacted: boolean; truncated: boolean } {
|
|
65
|
+
const raw = String(value ?? ""); const redacted = redactSensitiveText(raw);
|
|
66
|
+
const clean = redacted.text.replace(/\u001b(?:[@-_]|\[[0-?]*[ -/]*[@-~])/g, "").replace(/[\u0000-\u001f\u007f-\u009f]/g, " ")
|
|
67
|
+
.replace(/\s+/g, " ").trim();
|
|
68
|
+
return { text: clean.slice(0, maximum), redacted: redacted.redacted, truncated: clean.length > maximum };
|
|
69
|
+
}
|
|
70
|
+
function publicId(value: string): string { const clean = safe(value, 160).text.replace(/[^A-Za-z0-9._:@~-]/g, "-"); return PUBLIC_REF.test(clean) ? clean : "unknown"; }
|
|
71
|
+
function reasonCode(value: string, fallback: string): string { const clean = safe(value, 96).text.toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^-+|-+$/g, ""); return clean || fallback; }
|
|
72
|
+
function key(cwd: string, rawSessionId: string): string { return `${cwd}\0${rawSessionId}`; }
|
|
73
|
+
function clone<T>(value: T): T { return structuredClone(value); }
|
|
74
|
+
|
|
75
|
+
export class PiApprovalBroker {
|
|
76
|
+
readonly #bindings = new Map<string, Binding>();
|
|
77
|
+
|
|
78
|
+
bind(input: { cwd: string; rawSessionId: string; runtimeInstanceId: string; authority(): ApprovalAuthority }): () => void {
|
|
79
|
+
const bindingKey = key(input.cwd, input.rawSessionId), prior = this.#bindings.get(bindingKey);
|
|
80
|
+
if (prior && prior.runtimeInstanceId !== input.runtimeInstanceId) this.#cancelBinding(prior, "runtime-replaced", "runtime-restart");
|
|
81
|
+
if (prior?.runtimeInstanceId === input.runtimeInstanceId) { prior.authority = input.authority; return () => this.unbind(input); }
|
|
82
|
+
const secret = randomBytes(32);
|
|
83
|
+
const binding: Binding = { ...input, secret, listeners: new Set(), pending: new Map(), requests: new Map(), recent: [], approvalCounter: 0,
|
|
84
|
+
approvalRevision: ref("approval-rev", secret, [input.runtimeInstanceId, 0]) };
|
|
85
|
+
this.#bindings.set(bindingKey, binding);
|
|
86
|
+
return () => this.unbind(input);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
unbind(input: { cwd: string; rawSessionId: string; runtimeInstanceId: string }): void {
|
|
90
|
+
const bindingKey = key(input.cwd, input.rawSessionId), binding = this.#bindings.get(bindingKey);
|
|
91
|
+
if (!binding || binding.runtimeInstanceId !== input.runtimeInstanceId) return;
|
|
92
|
+
this.#cancelBinding(binding, "runtime-stopped", "runtime-restart"); this.#bindings.delete(bindingKey);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
subscribe(cwd: string, rawSessionId: string, listener: (event: ApprovalBrokerEvent) => void): () => void {
|
|
96
|
+
const binding = this.#bindings.get(key(cwd, rawSessionId)); if (!binding) return () => undefined;
|
|
97
|
+
binding.listeners.add(listener); return () => binding.listeners.delete(listener);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
cancelForControl(cwd: string, rawSessionId: string, taskRunId: string, reason = "task-pausing"): number {
|
|
101
|
+
const binding = this.#bindings.get(key(cwd, rawSessionId)); if (!binding) return 0;
|
|
102
|
+
const targets = [...binding.pending.entries()].filter(([, pending]) => pending.request.identity.taskRunId === taskRunId);
|
|
103
|
+
for (const [approvalRef] of targets) this.#cancelPending(binding, approvalRef, reason, "runtime-control", "cancelled");
|
|
104
|
+
return targets.length;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
projection(cwd: string, rawSessionId: string): { revision: string | null; summary: Record<string, unknown> } {
|
|
108
|
+
const binding = this.#bindings.get(key(cwd, rawSessionId));
|
|
109
|
+
if (!binding) return { revision: null, summary: { state: "unknown", pending: [], recent: [],
|
|
110
|
+
health: { state: "unavailable", reasonCode: "approval-broker-unavailable", message: "Approval broker is unavailable" } } };
|
|
111
|
+
const pending = [...binding.pending.values()].filter((item) => !item.receipt).map((item) => this.#summary(item.request));
|
|
112
|
+
const recent = binding.recent.slice(-MAX_RECENT).reverse().map((item) => this.#summary(item));
|
|
113
|
+
const latest = binding.recent.at(-1);
|
|
114
|
+
const state = pending.length ? "waiting" : !latest ? "none" : latest.state === "expired" ? "expired" : "resolved";
|
|
115
|
+
return { revision: binding.approvalRevision, summary: { state, pending, recent: state === "none" ? [] : recent,
|
|
116
|
+
health: { state: "ok", reasonCode: null, message: null } } };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
detail(cwd: string, rawSessionId: string, approvalRef: string): Request | null {
|
|
120
|
+
if (!REF.test(approvalRef)) return null;
|
|
121
|
+
const pending = this.#bindings.get(key(cwd, rawSessionId))?.pending.get(approvalRef);
|
|
122
|
+
return pending && !pending.receipt ? clone(pending.request) : null;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async request(input: { cwd: string; rawSessionId: string; toolCallId: string; action: ApprovalActionDraft;
|
|
126
|
+
expectedTask?: { taskId: string; taskRunId: string } | null; terminalConfirm(): Promise<boolean>; recheck?(): boolean; ttlMs?: number }): Promise<ApprovalGuardDecision> {
|
|
127
|
+
const binding = this.#bindings.get(key(input.cwd, input.rawSessionId));
|
|
128
|
+
const authority = binding?.authority();
|
|
129
|
+
if (!binding || !authority || authority.taskState !== "active" || input.expectedTask && (authority.identity.taskId !== input.expectedTask.taskId || authority.identity.taskRunId !== input.expectedTask.taskRunId)
|
|
130
|
+
|| !REF.test(authority.identity.agentOperationId)
|
|
131
|
+
|| !REF.test(input.toolCallId) || binding.pending.size >= MAX_PENDING) return this.#terminalOnly(input.terminalConfirm);
|
|
132
|
+
const now = Date.now(), requestedAt = new Date(now).toISOString(), expiresAt = new Date(now + Math.min(Math.max(input.ttlMs ?? DEFAULT_TTL_MS, 5_000), DEFAULT_TTL_MS)).toISOString();
|
|
133
|
+
const approvalRef = ref("approval", binding.secret, [input.toolCallId, now, randomUUID()]);
|
|
134
|
+
const decisionToken = randomBytes(32).toString("base64url");
|
|
135
|
+
const nextRevision = this.#nextRevision(binding, "requested", approvalRef);
|
|
136
|
+
const identity: Identity = { ...authority.identity, toolCallId: input.toolCallId };
|
|
137
|
+
const action = this.#action(binding, input.action, input.cwd);
|
|
138
|
+
const expectedRevisions: Revisions = { ...authority.revisions, approvalRevision: nextRevision,
|
|
139
|
+
treePrecondition: input.action.preconditionClass === "runtime-only" ? null : input.action.treePrecondition ?? null };
|
|
140
|
+
if ((input.action.preconditionClass !== "runtime-only" && !expectedRevisions.treePrecondition)
|
|
141
|
+
|| !this.#validTree(expectedRevisions.treePrecondition)) return this.#terminalOnly(input.terminalConfirm);
|
|
142
|
+
const request: Request = { schemaVersion: 1, version: "piagent-webui-approval-v1", recordType: "request", approvalRef, decisionToken,
|
|
143
|
+
identity, action, expectedRevisions, state: "waiting", requestedAt, expiresAt, executor: "pi-guard", directExecution: false };
|
|
144
|
+
const result = new Promise<ApprovalGuardDecision>((resolve) => {
|
|
145
|
+
const timer = setTimeout(() => this.#expire(binding, approvalRef), Date.parse(expiresAt) - Date.now()); timer.unref();
|
|
146
|
+
binding.pending.set(approvalRef, { request, resolve, receipt: null, timer, finalWaiters: [], recheck: input.recheck ?? (() => true) }); binding.requests.set(approvalRef, request);
|
|
147
|
+
while (binding.requests.size > MAX_PENDING + MAX_RECENT) binding.requests.delete(binding.requests.keys().next().value as string);
|
|
148
|
+
});
|
|
149
|
+
this.#emit(binding, { kind: "requested", approvalRef, request: clone(request) });
|
|
150
|
+
void Promise.resolve().then(input.terminalConfirm).then(
|
|
151
|
+
(allow) => this.#settle(binding, approvalRef, allow ? "allow" : "deny", "terminal", ref("decision", binding.secret, [approvalRef, "terminal", now])),
|
|
152
|
+
() => this.#settle(binding, approvalRef, "deny", "terminal", ref("decision", binding.secret, [approvalRef, "terminal-error", now]))
|
|
153
|
+
);
|
|
154
|
+
return result;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async decide(cwd: string, rawSessionId: string, approvalRef: string, value: unknown): Promise<Receipt> {
|
|
158
|
+
const binding = this.#bindings.get(key(cwd, rawSessionId)); if (!binding || !REF.test(approvalRef)) throw new Error("approval-unavailable");
|
|
159
|
+
const pending = binding.pending.get(approvalRef);
|
|
160
|
+
if (!pending) {
|
|
161
|
+
const prior = binding.recent.find((item) => item.approvalRef === approvalRef);
|
|
162
|
+
const request = binding.requests.get(approvalRef);
|
|
163
|
+
if (prior && request && this.#validDecision(value, request, null) && (value as any).decisionId === prior.decisionId) return { ...clone(prior), deduplicated: true };
|
|
164
|
+
throw new Error("approval-not-pending");
|
|
165
|
+
}
|
|
166
|
+
if (!this.#validDecision(value, pending.request, null)) throw new Error("approval-decision-invalid");
|
|
167
|
+
const decision = value as any;
|
|
168
|
+
if (pending.receipt) {
|
|
169
|
+
if (decision.decisionId !== pending.receipt.decisionId) throw new Error("approval-already-resolved");
|
|
170
|
+
if (pending.receipt.permit.status === "provisional") return new Promise<Receipt>((resolve) => pending.finalWaiters.push((receipt) => resolve({ ...receipt, deduplicated: true })));
|
|
171
|
+
return { ...clone(pending.receipt), deduplicated: true };
|
|
172
|
+
}
|
|
173
|
+
if (Date.now() >= Date.parse(pending.request.expiresAt)) { this.#expire(binding, approvalRef); throw new Error("approval-expired"); }
|
|
174
|
+
const final = new Promise<Receipt>((resolve) => pending.finalWaiters.push(resolve));
|
|
175
|
+
this.#settle(binding, approvalRef, decision.decision, "webui", decision.decisionId);
|
|
176
|
+
if (decision.decision === "deny") return clone(binding.recent.at(-1)!);
|
|
177
|
+
return final;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
#terminalOnly(confirm: () => Promise<boolean>): Promise<ApprovalGuardDecision> {
|
|
181
|
+
return Promise.resolve().then(confirm).then((allowed) => ({ allowed, brokered: false, receipt: null,
|
|
182
|
+
consume: () => allowed, cancel: () => undefined }), () => ({ allowed: false, brokered: false, receipt: null,
|
|
183
|
+
consume: () => false, cancel: () => undefined }));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
#action(binding: Binding, draft: ApprovalActionDraft, cwd: string): Record<string, unknown> {
|
|
187
|
+
const command = draft.commandPreview === null || draft.commandPreview === undefined ? null : safe(draft.commandPreview, 4_000);
|
|
188
|
+
const parameter = safe(draft.parameterPreview ?? "No additional parameters", 4_000);
|
|
189
|
+
const targetPaths = (draft.targetPaths ?? []).slice(0, 32).map((item) => safe(item, 500)).filter((item) => item.text).map((item) => item.text);
|
|
190
|
+
const targetSummaries = (draft.targetSummaries ?? []).slice(0, 32).map((item) => safe(item, 500)).filter((item) => item.text).map((item) => item.text);
|
|
191
|
+
const removed = [command, parameter].filter((item) => item?.redacted).length;
|
|
192
|
+
const truncated = Boolean(command?.truncated || parameter.truncated || (draft.targetPaths?.length ?? 0) > 32 || (draft.targetSummaries?.length ?? 0) > 32);
|
|
193
|
+
const provider = draft.provider ? safe(draft.provider, 160).text : "";
|
|
194
|
+
const targetProvided = targetPaths.length > 0 || targetSummaries.length > 0;
|
|
195
|
+
return { kind: draft.kind, preconditionClass: draft.preconditionClass, toolName: publicId(draft.toolName),
|
|
196
|
+
actionDigest: digest(binding.secret, draft.rawAction), canonicalization: "digest-bound-action-v1", previewPolicy: "redacted-no-secrets-v1",
|
|
197
|
+
commandPreview: command?.text || null, parameterPreview: parameter.text || "No additional parameters",
|
|
198
|
+
targetEvidence: targetProvided ? { state: "provided", reasonCode: null } : { state: "redacted", reasonCode: "target-not-exposed" },
|
|
199
|
+
cwdRef: ref("cwd", binding.secret, cwd), cwdDisplay: safe(path.basename(cwd), 500).text || null,
|
|
200
|
+
targetRefs: [], targetPaths, targetSummaries, providerRef: provider ? ref("provider", binding.secret, provider) : null,
|
|
201
|
+
urlOrigin: /^https?:\/\/(?:[A-Za-z0-9-]+\.)*[A-Za-z0-9-]+(?::[0-9]{1,5})?$/.test(draft.urlOrigin ?? "") ? draft.urlOrigin : null,
|
|
202
|
+
requestedScope: reasonCode(draft.requestedScope, "one-action"), reason: safe(draft.reason, 500).text || "Human confirmation is required",
|
|
203
|
+
riskClass: draft.riskClass, consequences: { allow: safe(draft.allowConsequence, 500).text || "Allow this exact action once",
|
|
204
|
+
deny: safe(draft.denyConsequence, 500).text || "Block this action" },
|
|
205
|
+
redaction: { applied: removed > 0, valuesRemoved: removed, truncated } };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
#validDecision(value: unknown, request?: Request, receipt?: Receipt | null): boolean {
|
|
209
|
+
if (!exactKeys(value, ["schemaVersion", "version", "recordType", "approvalRef", "decisionId", "decisionToken", "identity", "actionDigest",
|
|
210
|
+
"expectedRevisions", "decision", "reason", "decidedAt", "expiresAt", "decisionSurface", "executor", "directExecution"])) return false;
|
|
211
|
+
const item = value as any;
|
|
212
|
+
if (item.schemaVersion !== 1 || item.version !== "piagent-webui-approval-v1" || item.recordType !== "decision"
|
|
213
|
+
|| !REF.test(item.approvalRef) || !REF.test(item.decisionId) || typeof item.decisionToken !== "string" || item.decisionToken.length < 32
|
|
214
|
+
|| !["allow", "deny"].includes(item.decision) || !exactTimestamp(item.decidedAt) || !exactTimestamp(item.expiresAt)
|
|
215
|
+
|| item.decisionSurface !== "webui" || item.executor !== "pi-guard" || item.directExecution !== false
|
|
216
|
+
|| !(item.reason === null || typeof item.reason === "string" && item.reason.length <= 500)) return false;
|
|
217
|
+
if (request) return item.approvalRef === request.approvalRef && item.decisionToken === request.decisionToken
|
|
218
|
+
&& item.actionDigest === request.action.actionDigest && canonical(item.identity) === canonical(request.identity)
|
|
219
|
+
&& canonical(item.expectedRevisions) === canonical(request.expectedRevisions) && item.expiresAt === request.expiresAt
|
|
220
|
+
&& Date.parse(item.decidedAt) >= Date.parse(request.requestedAt) - 1_000 && Date.parse(item.decidedAt) <= Date.now() + 1_000;
|
|
221
|
+
return Boolean(receipt && item.approvalRef === receipt.approvalRef && item.decisionId === receipt.decisionId
|
|
222
|
+
&& item.actionDigest === receipt.actionDigest && canonical(item.identity) === canonical(receipt.identity));
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
#validTree(value: TreePrecondition | null): boolean {
|
|
226
|
+
return value === null || Boolean(REVISION.test(value.workspaceRevision) && (value.indexRevision === null || REVISION.test(value.indexRevision)) && DIGEST.test(value.preimageDigest));
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
#settle(binding: Binding, approvalRef: string, decision: "allow" | "deny", surface: "webui" | "terminal", decisionId: string): void {
|
|
230
|
+
const pending = binding.pending.get(approvalRef); if (!pending || pending.receipt) return;
|
|
231
|
+
clearTimeout(pending.timer); const resolvedAt = new Date().toISOString();
|
|
232
|
+
const postRevision = this.#nextRevision(binding, "resolved", [approvalRef, decision, surface]);
|
|
233
|
+
const receipt: Receipt = { schemaVersion: 1, version: "piagent-webui-approval-v1", recordType: "receipt", approvalRef, decisionId,
|
|
234
|
+
identity: clone(pending.request.identity), actionDigest: String(pending.request.action.actionDigest), state: "resolved", decision,
|
|
235
|
+
winnerSurface: surface, resolutionReason: null, resolvedAt, preRevisions: clone(pending.request.expectedRevisions),
|
|
236
|
+
postRevisions: { runtimeRevision: pending.request.expectedRevisions.runtimeRevision, taskRevision: pending.request.expectedRevisions.taskRevision,
|
|
237
|
+
controlRevision: pending.request.expectedRevisions.controlRevision, approvalRevision: postRevision },
|
|
238
|
+
permit: decision === "allow" ? { status: "provisional", issuedAt: resolvedAt, consumedAt: null, reasonCode: null }
|
|
239
|
+
: { status: "not-issued", issuedAt: null, consumedAt: null, reasonCode: null }, deduplicated: false,
|
|
240
|
+
auditRef: ref("approval-audit", binding.secret, [approvalRef, resolvedAt, surface, decision]), executor: "pi-guard", directExecution: false };
|
|
241
|
+
pending.receipt = receipt; binding.recent.push(receipt); binding.recent = binding.recent.slice(-MAX_RECENT);
|
|
242
|
+
this.#emit(binding, { kind: "resolved", approvalRef, receipt: clone(receipt) });
|
|
243
|
+
const decisionResult: ApprovalGuardDecision = { allowed: decision === "allow", brokered: true, receipt: clone(receipt),
|
|
244
|
+
consume: () => this.#consume(binding, receipt), cancel: (reason = "guard-cancelled") => this.#cancelPermit(binding, receipt, reason) };
|
|
245
|
+
pending.resolve(decisionResult);
|
|
246
|
+
if (decision === "deny") this.#finish(binding, pending, receipt);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
#consume(binding: Binding, receipt: Receipt): boolean {
|
|
250
|
+
if (receipt.permit.status !== "provisional") return receipt.permit.status === "consumed";
|
|
251
|
+
const authority = binding.authority();
|
|
252
|
+
const pending = binding.pending.get(receipt.approvalRef);
|
|
253
|
+
const expectedIdentity = { projectRef: receipt.identity.projectRef, runtimeInstanceId: receipt.identity.runtimeInstanceId,
|
|
254
|
+
sessionRef: receipt.identity.sessionRef, taskId: receipt.identity.taskId, taskRunId: receipt.identity.taskRunId,
|
|
255
|
+
agentOperationId: receipt.identity.agentOperationId };
|
|
256
|
+
if (!authority || authority.taskState !== "active" || !pending?.recheck() || canonical(authority.identity) !== canonical(expectedIdentity)) {
|
|
257
|
+
this.#cancelPermit(binding, receipt, "authority-changed"); return false;
|
|
258
|
+
}
|
|
259
|
+
const expected = receipt.preRevisions;
|
|
260
|
+
if (authority.revisions.runtimeRevision !== expected.runtimeRevision || authority.revisions.taskRevision !== expected.taskRevision
|
|
261
|
+
|| authority.revisions.controlRevision !== expected.controlRevision || binding.approvalRevision !== receipt.postRevisions.approvalRevision) {
|
|
262
|
+
this.#cancelPermit(binding, receipt, "revision-changed"); return false;
|
|
263
|
+
}
|
|
264
|
+
const consumedAt = new Date().toISOString(); receipt.permit = { status: "consumed", issuedAt: receipt.permit.issuedAt, consumedAt, reasonCode: null };
|
|
265
|
+
receipt.postRevisions.approvalRevision = this.#nextRevision(binding, "permit-consumed", receipt.approvalRef);
|
|
266
|
+
if (pending) this.#finish(binding, pending, receipt);
|
|
267
|
+
this.#emit(binding, { kind: "resolved", approvalRef: receipt.approvalRef, receipt: clone(receipt) }); return true;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
#cancelPermit(binding: Binding, receipt: Receipt, reason: string): void {
|
|
271
|
+
if (receipt.permit.status !== "provisional") return;
|
|
272
|
+
receipt.permit = { status: "cancelled", issuedAt: receipt.permit.issuedAt, consumedAt: null, reasonCode: reasonCode(reason, "guard-cancelled") };
|
|
273
|
+
receipt.postRevisions.approvalRevision = this.#nextRevision(binding, "permit-cancelled", [receipt.approvalRef, reason]);
|
|
274
|
+
const pending = binding.pending.get(receipt.approvalRef); if (pending) this.#finish(binding, pending, receipt);
|
|
275
|
+
this.#emit(binding, { kind: "cancelled", approvalRef: receipt.approvalRef, receipt: clone(receipt) });
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
#expire(binding: Binding, approvalRef: string): void { this.#cancelPending(binding, approvalRef, "approval-expired", "runtime-expiry", "expired"); }
|
|
279
|
+
#cancelBinding(binding: Binding, reason: string, surface: "runtime-restart" | "runtime-control"): void {
|
|
280
|
+
for (const approvalRef of [...binding.pending.keys()]) this.#cancelPending(binding, approvalRef, reason, surface, "cancelled");
|
|
281
|
+
}
|
|
282
|
+
#cancelPending(binding: Binding, approvalRef: string, reason: string, surface: "runtime-expiry" | "runtime-restart" | "runtime-control", state: "expired" | "cancelled"): void {
|
|
283
|
+
const pending = binding.pending.get(approvalRef); if (!pending || pending.receipt) return; clearTimeout(pending.timer);
|
|
284
|
+
const resolvedAt = new Date().toISOString(), post = this.#nextRevision(binding, state, approvalRef);
|
|
285
|
+
const receipt: Receipt = { schemaVersion: 1, version: "piagent-webui-approval-v1", recordType: "receipt", approvalRef, decisionId: null,
|
|
286
|
+
identity: clone(pending.request.identity), actionDigest: String(pending.request.action.actionDigest), state, decision: null, winnerSurface: surface,
|
|
287
|
+
resolutionReason: reasonCode(reason, "approval-cancelled"), resolvedAt, preRevisions: clone(pending.request.expectedRevisions),
|
|
288
|
+
postRevisions: { runtimeRevision: pending.request.expectedRevisions.runtimeRevision, taskRevision: pending.request.expectedRevisions.taskRevision,
|
|
289
|
+
controlRevision: pending.request.expectedRevisions.controlRevision, approvalRevision: post },
|
|
290
|
+
permit: { status: state === "expired" ? "expired" : "cancelled", issuedAt: null, consumedAt: null, reasonCode: reasonCode(reason, "approval-cancelled") },
|
|
291
|
+
deduplicated: false, auditRef: ref("approval-audit", binding.secret, [approvalRef, resolvedAt, surface]), executor: "pi-guard", directExecution: false };
|
|
292
|
+
pending.receipt = receipt; binding.recent.push(receipt); binding.recent = binding.recent.slice(-MAX_RECENT);
|
|
293
|
+
this.#emit(binding, { kind: state === "expired" ? "expired" : "cancelled", approvalRef, receipt: clone(receipt) });
|
|
294
|
+
pending.resolve({ allowed: false, brokered: true, receipt: clone(receipt), consume: () => false, cancel: () => undefined }); this.#finish(binding, pending, receipt);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
#finish(binding: Binding, pending: Pending, receipt: Receipt): void {
|
|
298
|
+
binding.pending.delete(receipt.approvalRef); for (const resolve of pending.finalWaiters.splice(0)) resolve(clone(receipt));
|
|
299
|
+
}
|
|
300
|
+
#nextRevision(binding: Binding, kind: string, value: unknown): string {
|
|
301
|
+
binding.approvalCounter += 1; binding.approvalRevision = ref("approval-rev", binding.secret, [binding.runtimeInstanceId, binding.approvalCounter, kind, value]);
|
|
302
|
+
return binding.approvalRevision;
|
|
303
|
+
}
|
|
304
|
+
#emit(binding: Binding, event: ApprovalBrokerEvent): void { for (const listener of binding.listeners) { try { listener(clone(event)); } catch { /* projection listeners are fail-soft */ } } }
|
|
305
|
+
#summary(value: Request | Receipt): Record<string, unknown> {
|
|
306
|
+
if (value.recordType === "request") return { approvalRef: value.approvalRef, state: "waiting", resolution: null,
|
|
307
|
+
actionSummary: safe(`${value.action.toolName}: ${value.action.reason}`, 500).text || "Approval required", toolCallId: value.identity.toolCallId,
|
|
308
|
+
expiresAt: value.expiresAt, reasonCode: null };
|
|
309
|
+
return { approvalRef: value.approvalRef, state: value.state === "expired" ? "expired" : "resolved",
|
|
310
|
+
resolution: value.state === "expired" ? "expired" : value.state === "cancelled" ? "cancelled" : value.decision,
|
|
311
|
+
actionSummary: safe(`${value.identity.toolCallId}: ${value.decision ?? value.state}`, 500).text || "Approval resolved",
|
|
312
|
+
toolCallId: value.identity.toolCallId, expiresAt: null, reasonCode: value.state === "expired" ? value.resolutionReason : null };
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const BROKER_KEY = Symbol.for("piagent.webui.approval-broker.v1");
|
|
317
|
+
const root = globalThis as typeof globalThis & { [BROKER_KEY]?: PiApprovalBroker };
|
|
318
|
+
export const piApprovalBroker = root[BROKER_KEY] ??= new PiApprovalBroker();
|