@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
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
|
|
8
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
9
|
+
|
|
10
|
+
import { resolveLocalStatePath, ensurePrivateStateDirectory } from "../../piagent-core/extensions/local-state-path.js";
|
|
11
|
+
import { loadProjectContextIndexPolicy, effectiveProtectedPaths } from "../../piagent-core/extensions/context-index-policy.js";
|
|
12
|
+
import { readContextTelemetry } from "../../piagent-core/extensions/context-engine.js";
|
|
13
|
+
import { activeSessionTask, workingTreeSnapshot, workingTreeSnapshotHasUnavailableEvidence } from "../../piagent-core/extensions/task-state.js";
|
|
14
|
+
import { workingTreeEvidenceDigest } from "../../piagent-core/extensions/task-lifecycle.js";
|
|
15
|
+
import { piApprovalBroker, type ApprovalBrokerEvent, type ApprovalAuthority } from "../../piagent-core/runtime/inspection/approval-broker.ts";
|
|
16
|
+
import { RuntimeEventStore, type RuntimeEventDraft } from "../../piagent-core/runtime/inspection/runtime-event-store.ts";
|
|
17
|
+
import { inspectTaskControlState } from "../../piagent-core/runtime/inspection/task-control-journal.ts";
|
|
18
|
+
import { webUiProjectRef, webUiSessionRef, webUiTaskRevision } from "../../piagent-core/runtime/inspection/webui-snapshot.ts";
|
|
19
|
+
import { piSourceMutationGuard } from "../../piagent-core/runtime/policy/source-mutation-guard.ts";
|
|
20
|
+
import { CoreInspectionProvider } from "../server/core-inspection-provider.ts";
|
|
21
|
+
import type { SourceView } from "../server/read-model-provider.ts";
|
|
22
|
+
import { SameSessionPiBridge, type BridgeTaskFacts } from "./same-session-bridge.ts";
|
|
23
|
+
import { AttachmentStore } from "./attachment-store.ts";
|
|
24
|
+
import { HeldMessageQueue } from "./held-message-queue.ts";
|
|
25
|
+
import { LifecycleController } from "./lifecycle-controller.ts";
|
|
26
|
+
import { lifecycleRuntimeDraft } from "./lifecycle-event-adapter.ts";
|
|
27
|
+
import { PiSessionStreamAdapter } from "./session-stream-adapter.ts";
|
|
28
|
+
import { SessionOptionsController } from "./session-options-controller.ts";
|
|
29
|
+
import { ReviewController } from "./review-controller.ts";
|
|
30
|
+
import { SourceMutationController } from "./source-mutation-controller.ts";
|
|
31
|
+
import { SourceRevertController } from "./source-revert-controller.ts";
|
|
32
|
+
import { SourceOpenController } from "./source-open-controller.ts";
|
|
33
|
+
import { VSCodeHandoff } from "./vscode-handoff.ts";
|
|
34
|
+
import { TerminalSessionAdapter } from "./terminal-session-adapter.ts";
|
|
35
|
+
import { isGatewayRuntimeContext } from "../ownership/gateway-runtime-context.ts";
|
|
36
|
+
|
|
37
|
+
const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
38
|
+
const PLATFORM_ROOT = path.resolve(PACKAGE_ROOT, "../..");
|
|
39
|
+
const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;
|
|
40
|
+
const SOURCE_VIEWS = new Set<SourceView>(["task", "working-tree", "staged"]);
|
|
41
|
+
type Manager = {
|
|
42
|
+
key: string;
|
|
43
|
+
ctx: ExtensionContext;
|
|
44
|
+
child: ChildProcess;
|
|
45
|
+
provider: CoreInspectionProvider;
|
|
46
|
+
eventReader: EventReader;
|
|
47
|
+
lastCursor: string;
|
|
48
|
+
descriptor: string;
|
|
49
|
+
controlDirectory: string;
|
|
50
|
+
controlSocket: string;
|
|
51
|
+
origin: string;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
function hash(value: string): string { return createHash("sha256").update(value).digest("hex"); }
|
|
55
|
+
export function createWebUiExtensionRuntimeInstanceRef(): string { return `runtime.${hash(randomBytes(32).toString("hex"))}`; }
|
|
56
|
+
function key(ctx: ExtensionContext): string { return `${ctx.cwd}\0${ctx.sessionManager.getSessionId()}`; }
|
|
57
|
+
function sessionRef(ctx: ExtensionContext): string { return webUiSessionRef(ctx.sessionManager.getSessionId()); }
|
|
58
|
+
function descriptorDirectory(cwd: string): string { return path.join(cwd, ".pi", "piagent-state", "webui-launcher"); }
|
|
59
|
+
function descriptorPath(ctx: ExtensionContext): string { return path.join(descriptorDirectory(ctx.cwd), `${hash(sessionRef(ctx))}.json`); }
|
|
60
|
+
|
|
61
|
+
class EventReader {
|
|
62
|
+
readonly #store: RuntimeEventStore;
|
|
63
|
+
constructor(ctx: ExtensionContext, runtimeInstanceId: string) {
|
|
64
|
+
this.#store = new RuntimeEventStore({ projectRoot: ctx.cwd, projectRef: webUiProjectRef(ctx.cwd),
|
|
65
|
+
runtimeInstanceId, sessionRef: sessionRef(ctx) });
|
|
66
|
+
}
|
|
67
|
+
retention(): unknown { return this.#store.retention(); }
|
|
68
|
+
currentCursor(): string { return this.#store.currentCursor(); }
|
|
69
|
+
resyncRequired(): boolean { return this.#store.resyncRequired(); }
|
|
70
|
+
replay(after: string | null, limit: number) { return this.#store.replay(after, limit); }
|
|
71
|
+
append(draft: RuntimeEventDraft) { return this.#store.append(draft); }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function protectedPaths(ctx: ExtensionContext): string[] {
|
|
75
|
+
try {
|
|
76
|
+
const resolved = loadProjectContextIndexPolicy(PLATFORM_ROOT, ctx.cwd);
|
|
77
|
+
return effectiveProtectedPaths(resolved.policy, resolved.profile).readProtectedPaths;
|
|
78
|
+
} catch { return [".pi/piagent-state/**", ".pi/context-index.json"]; }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function writeDescriptor(ctx: ExtensionContext, value: Record<string, unknown>): string {
|
|
82
|
+
const directory = ensurePrivateStateDirectory(ctx.cwd, descriptorDirectory(ctx.cwd), "WebUI launcher directory");
|
|
83
|
+
const target = resolveLocalStatePath(ctx.cwd, descriptorPath(ctx), { label: "WebUI launcher descriptor" });
|
|
84
|
+
try {
|
|
85
|
+
const existing = fs.lstatSync(target);
|
|
86
|
+
if (!existing.isFile() || existing.isSymbolicLink()) throw new Error("WebUI launcher descriptor is unsafe");
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
89
|
+
}
|
|
90
|
+
const temporary = path.join(directory, `.descriptor-${process.pid}-${randomBytes(8).toString("hex")}.tmp`);
|
|
91
|
+
const descriptor = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
|
|
92
|
+
try { fs.writeFileSync(descriptor, `${JSON.stringify(value)}\n`); fs.fsyncSync(descriptor); fs.fchmodSync(descriptor, 0o600); }
|
|
93
|
+
finally { fs.closeSync(descriptor); }
|
|
94
|
+
fs.renameSync(temporary, target);
|
|
95
|
+
return target;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function removeDescriptor(cwd: string, target: string): void {
|
|
99
|
+
try {
|
|
100
|
+
const verified = resolveLocalStatePath(cwd, target, { label: "WebUI launcher descriptor", kind: "file" });
|
|
101
|
+
fs.unlinkSync(verified);
|
|
102
|
+
} catch { /* already absent or unsafe: never broaden the delete target */ }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function removeControlDirectory(directory: string): void {
|
|
106
|
+
if (path.dirname(directory) !== path.resolve(os.tmpdir()) || !path.basename(directory).startsWith("piagent-webui-")) return;
|
|
107
|
+
try {
|
|
108
|
+
for (const entry of fs.readdirSync(directory)) {
|
|
109
|
+
if (entry !== "control.sock") return;
|
|
110
|
+
const socket = path.join(directory, entry), stat = fs.lstatSync(socket);
|
|
111
|
+
if (!stat.isSocket()) return;
|
|
112
|
+
fs.unlinkSync(socket);
|
|
113
|
+
}
|
|
114
|
+
fs.rmdirSync(directory);
|
|
115
|
+
} catch { /* the sidecar may already have removed its private socket directory */ }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function openLocalUrl(url: string): boolean {
|
|
119
|
+
const command = process.platform === "darwin" ? "open" : process.platform === "linux" ? "xdg-open" : null;
|
|
120
|
+
if (!command) return false;
|
|
121
|
+
try { const child = spawn(command, [url], { detached: true, stdio: "ignore" }); child.unref(); return true; }
|
|
122
|
+
catch { return false; }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function readMethod(provider: CoreInspectionProvider, queue: HeldMessageQueue, sessionOptions: SessionOptionsController, lifecycle: LifecycleController,
|
|
126
|
+
review: ReviewController, sourceMutation: SourceMutationController, sourceRevert: SourceRevertController, attachments: AttachmentStore | null,
|
|
127
|
+
sourceOpen: SourceOpenController,
|
|
128
|
+
approvalDecision: (approvalRef: string, decision: unknown) => Promise<unknown>,
|
|
129
|
+
method: string, args: unknown[]): Promise<unknown> {
|
|
130
|
+
if (method === "snapshot" && args.length === 0) return provider.snapshot();
|
|
131
|
+
if (method === "capabilities" && args.length === 0) return provider.snapshot().then((value: any) => value.capabilities);
|
|
132
|
+
if (method === "activity" && args.length === 0) return provider.activity();
|
|
133
|
+
if (method === "sourceChanges" && args.length === 1 && SOURCE_VIEWS.has(args[0] as SourceView)) return provider.sourceChanges(args[0] as SourceView);
|
|
134
|
+
if (method === "diff" && args.length === 2 && SOURCE_VIEWS.has(args[0] as SourceView) && typeof args[1] === "string" && REF.test(args[1])) return provider.diff(args[0] as SourceView, args[1]);
|
|
135
|
+
if (method === "review" && args.length === 2 && SOURCE_VIEWS.has(args[0] as SourceView) && typeof args[1] === "string" && REF.test(args[1])) return provider.review(args[0] as SourceView, args[1]);
|
|
136
|
+
if (method === "sourceMutation" && args.length === 2 && ["source.stage", "source.unstage"].includes(String(args[0]))
|
|
137
|
+
&& typeof args[1] === "string" && REF.test(args[1])) return provider.sourceMutation(args[0] as "source.stage" | "source.unstage", args[1]);
|
|
138
|
+
if (method === "sourceRevert" && args.length === 2 && typeof args[0] === "string" && REF.test(args[0])
|
|
139
|
+
&& (args[1] === null || typeof args[1] === "string" && REF.test(args[1]))) return provider.sourceRevert(args[0], args[1] as string | null);
|
|
140
|
+
if (method === "commitSummary" && args.length === 0) return provider.commitSummary();
|
|
141
|
+
if (method === "taskIndex" && args.length === 0) return provider.taskIndex();
|
|
142
|
+
if (method === "taskTimeline" && args.length === 1 && typeof args[0] === "string" && REF.test(args[0])) return provider.taskTimeline(args[0]);
|
|
143
|
+
if (method === "recoveryHistory" && args.length === 1 && typeof args[0] === "string" && REF.test(args[0])) return provider.recoveryHistory(args[0]);
|
|
144
|
+
if (method === "handoffHistory" && args.length === 1 && typeof args[0] === "string" && REF.test(args[0])) return provider.handoffHistory(args[0]);
|
|
145
|
+
if (method === "subagentTree" && args.length === 1 && typeof args[0] === "string" && REF.test(args[0])) return provider.subagentTree(args[0]);
|
|
146
|
+
if (method === "releaseMonitor" && args.length === 0) return provider.releaseMonitor();
|
|
147
|
+
if (method === "logPreview" && args.length === 1 && typeof args[0] === "string" && REF.test(args[0])) return provider.logPreview(args[0]);
|
|
148
|
+
if (method === "transcript" && args.length === 2 && (args[0] === null || typeof args[0] === "string" && REF.test(args[0]))
|
|
149
|
+
&& Number.isInteger(args[1]) && Number(args[1]) >= 1 && Number(args[1]) <= 200) return provider.transcript(args[0] as string | null, Number(args[1]));
|
|
150
|
+
if (method === "queue" && args.length === 0) return provider.queue();
|
|
151
|
+
if (method === "modelCatalog" && args.length === 0) return provider.modelCatalog();
|
|
152
|
+
if (method === "approval" && args.length === 1 && typeof args[0] === "string" && REF.test(args[0])) return provider.approval(args[0]);
|
|
153
|
+
if (method === "approvalDecision" && args.length === 2 && typeof args[0] === "string" && REF.test(args[0])
|
|
154
|
+
&& args[1] && typeof args[1] === "object") return approvalDecision(args[0], args[1]);
|
|
155
|
+
if (method === "attachment" && args.length === 1 && args[0] && typeof args[0] === "object" && attachments) return Promise.resolve(attachments.execute(args[0]));
|
|
156
|
+
if (method === "replay" && args.length === 2 && (args[0] === null || typeof args[0] === "string" && REF.test(args[0]))
|
|
157
|
+
&& Number.isInteger(args[1]) && Number(args[1]) >= 1 && Number(args[1]) <= 10_000) return Promise.resolve(provider.replay(args[0] as string | null, Number(args[1])));
|
|
158
|
+
if (method === "control" && args.length === 1 && args[0] && typeof args[0] === "object") {
|
|
159
|
+
const action = (args[0] as Record<string, unknown>).action;
|
|
160
|
+
const execute = action === "review.mark" ? review.execute(args[0])
|
|
161
|
+
: action === "source.stage" || action === "source.unstage" ? sourceMutation.execute(args[0])
|
|
162
|
+
: action === "source.revert" ? sourceRevert.execute(args[0])
|
|
163
|
+
: action === "source.open-in-vscode" ? sourceOpen.execute(args[0])
|
|
164
|
+
: typeof action === "string" && action.startsWith("lifecycle.") ? lifecycle.execute(args[0])
|
|
165
|
+
: action === "session-options.set-model" || action === "session-options.set-thinking" ? sessionOptions.execute(args[0]) : queue.execute(args[0]);
|
|
166
|
+
return execute.then((receipt) => { provider.invalidate(); return receipt; });
|
|
167
|
+
}
|
|
168
|
+
return Promise.reject(new Error("webui-read-request-invalid"));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export default function piagentWebUiExtension(pi: ExtensionAPI): void {
|
|
172
|
+
const runtimeInstanceId = createWebUiExtensionRuntimeInstanceRef();
|
|
173
|
+
let terminalAdapter: TerminalSessionAdapter | null = null;
|
|
174
|
+
const managers = new Map<string, Manager>();
|
|
175
|
+
const eventReaders = new Map<string, EventReader>();
|
|
176
|
+
const taskFacts = (ctx: ExtensionContext): BridgeTaskFacts => {
|
|
177
|
+
const task = activeSessionTask(ctx.cwd, ctx.sessionManager.getSessionId());
|
|
178
|
+
if (!task) return null;
|
|
179
|
+
const taskRevision = webUiTaskRevision(task), control = inspectTaskControlState(ctx.cwd, task);
|
|
180
|
+
return { taskId: task.taskId, taskRunId: task.taskRunId, taskRevision, controlState: control.state,
|
|
181
|
+
controlRevision: control.controlRevision };
|
|
182
|
+
};
|
|
183
|
+
let currentContext: ExtensionContext | null = null, attachments: AttachmentStore | null = null;
|
|
184
|
+
let approvalBinding: { key: string; unbind(): void; unsubscribe(): void } | null = null;
|
|
185
|
+
const bridge = new SameSessionPiBridge(pi, { runtimeInstanceId, taskFacts,
|
|
186
|
+
prepareAttachments: (refs, request, identity, text) => {
|
|
187
|
+
if (!attachments) throw new Error("attachment-store-unavailable"); return attachments.claim(refs, request, identity, text);
|
|
188
|
+
} });
|
|
189
|
+
try { attachments = new AttachmentStore({ runtimeInstanceId, bridgeSnapshot: () => bridge.snapshot(),
|
|
190
|
+
modelSupportsImages: () => Array.isArray(currentContext?.model?.input) && currentContext.model.input.includes("image") }); }
|
|
191
|
+
catch { attachments = null; }
|
|
192
|
+
const queue = new HeldMessageQueue({ bridge, appendEntry: (customType, data) => pi.appendEntry(customType, data) });
|
|
193
|
+
const sessionOptions = new SessionOptionsController({ pi, bridge });
|
|
194
|
+
const vscode = new VSCodeHandoff();
|
|
195
|
+
const lifecycle = new LifecycleController({ bridge, runtimeInstanceId,
|
|
196
|
+
task: (ctx) => activeSessionTask(ctx.cwd, ctx.sessionManager.getSessionId()), abort: (ctx) => ctx.abort(),
|
|
197
|
+
cancelApprovals: (ctx, taskRunId) => { piApprovalBroker.cancelForControl(ctx.cwd, ctx.sessionManager.getSessionId(), taskRunId); },
|
|
198
|
+
treeDigest: (ctx) => { const snapshot = workingTreeSnapshot(ctx.cwd); return workingTreeSnapshotHasUnavailableEvidence(snapshot)
|
|
199
|
+
? null : workingTreeEvidenceDigest(snapshot as Record<string, string>); } });
|
|
200
|
+
const stream = new PiSessionStreamAdapter();
|
|
201
|
+
const bridgeSoft = (action: () => void): void => { try { action(); } catch { /* bridge failure never affects the Pi session */ } };
|
|
202
|
+
|
|
203
|
+
function approvalAuthority(): ApprovalAuthority {
|
|
204
|
+
const snapshot = bridge.snapshot(), identity = snapshot.identity, revisions = snapshot.revisions;
|
|
205
|
+
if (snapshot.state !== "ready" || !identity || !revisions || !identity.taskId || !identity.taskRunId || !identity.agentOperationId
|
|
206
|
+
|| !["active", "terminal"].includes(snapshot.taskState)
|
|
207
|
+
|| !revisions.taskRevision || !revisions.controlRevision) return null;
|
|
208
|
+
return { identity: { projectRef: identity.projectRef, runtimeInstanceId: identity.runtimeInstanceId, sessionRef: identity.sessionRef,
|
|
209
|
+
taskId: identity.taskId, taskRunId: identity.taskRunId, agentOperationId: identity.agentOperationId },
|
|
210
|
+
revisions: { runtimeRevision: revisions.runtimeRevision, taskRevision: revisions.taskRevision, controlRevision: revisions.controlRevision },
|
|
211
|
+
taskState: snapshot.taskState === "terminal" ? "terminal" : "active" };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function approvalDraft(event: ApprovalBrokerEvent): RuntimeEventDraft | null {
|
|
215
|
+
const snapshot = bridge.snapshot(), identity = snapshot.identity, revisions = snapshot.revisions;
|
|
216
|
+
const request = event.request as any, receipt = event.receipt as any, record = request ?? receipt;
|
|
217
|
+
if (!identity?.agentOperationId || !identity.taskId || !identity.taskRunId || !revisions || !record?.identity?.toolCallId) return null;
|
|
218
|
+
const approval = currentContext ? piApprovalBroker.projection(currentContext.cwd, currentContext.sessionManager.getSessionId()) : null;
|
|
219
|
+
const expired = event.kind === "expired", requested = event.kind === "requested";
|
|
220
|
+
const action = request?.action, resolution = receipt?.decision ?? (receipt?.state === "cancelled" ? "cancel" : expired ? "deny" : null);
|
|
221
|
+
const actionSummary = request ? `${String(action.toolName)}: ${String(action.reason)}` : `${String(record.identity.toolCallId)}: ${String(resolution ?? receipt?.state)}`;
|
|
222
|
+
return { sourceObservedAt: requested ? request.requestedAt : receipt.resolvedAt, projectRef: identity.projectRef,
|
|
223
|
+
runtimeInstanceId: identity.runtimeInstanceId, sessionRef: identity.sessionRef, taskId: identity.taskId, taskRunId: identity.taskRunId,
|
|
224
|
+
agentOperationId: identity.agentOperationId, turnIndex: null, messageRef: null, toolCallId: record.identity.toolCallId,
|
|
225
|
+
revision: { ...revisions, approvalRevision: approval?.revision ?? null }, kind: requested ? "approval.requested" : expired ? "approval.expired" : "approval.resolved",
|
|
226
|
+
correlation: { commandId: null, messageRequestId: null, replacementId: null, approvalRequestId: event.approvalRef,
|
|
227
|
+
causationEventId: null, idempotencyKeyDigest: null }, evidence: "observed",
|
|
228
|
+
payload: { state: requested ? "requested" : expired ? "expired" : "resolved", actionDigest: requested ? action.actionDigest : receipt.actionDigest,
|
|
229
|
+
actionSummary: actionSummary.slice(0, 500), decision: resolution, expiresAt: requested ? request.expiresAt : null,
|
|
230
|
+
resolutionCode: requested ? null : String(receipt.resolutionReason ?? receipt.winnerSurface ?? "approval-resolved") },
|
|
231
|
+
redaction: requested ? structuredClone(action.redaction) : { applied: false, valuesRemoved: 0, truncated: false } };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function bindApproval(ctx: ExtensionContext): void {
|
|
235
|
+
const bindingKey = key(ctx);
|
|
236
|
+
if (approvalBinding && approvalBinding.key !== bindingKey) { approvalBinding.unsubscribe(); approvalBinding.unbind(); approvalBinding = null; }
|
|
237
|
+
const unbind = piApprovalBroker.bind({ cwd: ctx.cwd, rawSessionId: ctx.sessionManager.getSessionId(), runtimeInstanceId, authority: approvalAuthority });
|
|
238
|
+
if (approvalBinding) { approvalBinding.unbind = unbind; return; }
|
|
239
|
+
const unsubscribe = piApprovalBroker.subscribe(ctx.cwd, ctx.sessionManager.getSessionId(), (event) => {
|
|
240
|
+
const draft = approvalDraft(event); if (draft) publishDrafts(ctx, [draft]); currentManager(ctx)?.provider.invalidate();
|
|
241
|
+
});
|
|
242
|
+
approvalBinding = { key: bindingKey, unbind, unsubscribe };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function eventReader(ctx: ExtensionContext): EventReader {
|
|
246
|
+
const readerKey = key(ctx), existing = eventReaders.get(readerKey);
|
|
247
|
+
if (existing) return existing;
|
|
248
|
+
const reader = new EventReader(ctx, runtimeInstanceId); eventReaders.set(readerKey, reader); return reader;
|
|
249
|
+
}
|
|
250
|
+
lifecycle.subscribe((event) => { const draft = lifecycleRuntimeDraft(event, bridge.snapshot()); if (draft && currentContext) publishDrafts(currentContext, [draft]);
|
|
251
|
+
if (currentContext) currentManager(currentContext)?.provider.invalidate(); });
|
|
252
|
+
function publishDrafts(ctx: ExtensionContext, drafts: RuntimeEventDraft[]): void {
|
|
253
|
+
if (!drafts.length) return;
|
|
254
|
+
try {
|
|
255
|
+
const reader = eventReader(ctx), manager = currentManager(ctx);
|
|
256
|
+
for (const draft of drafts) {
|
|
257
|
+
const result = reader.append(draft);
|
|
258
|
+
if (result.appended) manager?.provider.publishObserved(result.event);
|
|
259
|
+
}
|
|
260
|
+
if (manager) manager.lastCursor = reader.currentCursor();
|
|
261
|
+
} catch { /* streaming projection is best-effort and never blocks Pi */ }
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function currentManager(ctx: ExtensionContext): Manager | undefined {
|
|
265
|
+
const manager = managers.get(key(ctx));
|
|
266
|
+
if (manager && manager.child.exitCode === null && !manager.child.killed) { manager.ctx = ctx; return manager; }
|
|
267
|
+
if (manager) managers.delete(manager.key);
|
|
268
|
+
return undefined;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function publishPersisted(ctx: ExtensionContext): void {
|
|
272
|
+
const manager = currentManager(ctx);
|
|
273
|
+
if (!manager) return;
|
|
274
|
+
setTimeout(() => {
|
|
275
|
+
try {
|
|
276
|
+
const replay = manager.eventReader.replay(manager.lastCursor, 100);
|
|
277
|
+
if (replay.state !== "current") return;
|
|
278
|
+
for (const event of replay.events) manager.provider.publishObserved(event);
|
|
279
|
+
manager.lastCursor = replay.nextCursor;
|
|
280
|
+
} catch { /* a projection failure never affects the Pi agent loop */ }
|
|
281
|
+
}, 0).unref();
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async function stopManager(manager: Manager): Promise<void> {
|
|
285
|
+
managers.delete(manager.key);
|
|
286
|
+
removeDescriptor(manager.ctx.cwd, manager.descriptor);
|
|
287
|
+
if (manager.child.exitCode === null && !manager.child.killed) manager.child.kill("SIGTERM");
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
async function start(ctx: ExtensionContext, openBrowser: boolean): Promise<Manager> {
|
|
291
|
+
const existing = currentManager(ctx);
|
|
292
|
+
if (existing) {
|
|
293
|
+
ctx.ui.notify(`Piagent WebUI is already running at ${existing.origin}`, "info");
|
|
294
|
+
return existing;
|
|
295
|
+
}
|
|
296
|
+
const staticRoot = path.join(PACKAGE_ROOT, "dist", "client");
|
|
297
|
+
if (!fs.existsSync(path.join(staticRoot, "index.html"))) throw new Error("WebUI static build is missing; run npm run build --workspace @piagent/webui");
|
|
298
|
+
const reader = eventReader(ctx);
|
|
299
|
+
const provider = new CoreInspectionProvider({
|
|
300
|
+
cwd: ctx.cwd, sessionId: ctx.sessionManager.getSessionId(), runtimeInstanceId, eventStore: reader,
|
|
301
|
+
task: () => activeSessionTask(ctx.cwd, ctx.sessionManager.getSessionId()),
|
|
302
|
+
activityEvents: () => readContextTelemetry(ctx.cwd, { limit: 5_000 }) as unknown[],
|
|
303
|
+
currentActivity: () => [], sessionEntries: () => ctx.sessionManager.getBranch(), protectedPaths: () => protectedPaths(ctx),
|
|
304
|
+
contextUsage: () => ctx.getContextUsage(), model: () => ctx.model,
|
|
305
|
+
thinkingLevel: () => ctx.thinkingLevel ?? pi.getThinkingLevel(),
|
|
306
|
+
queueProjection: () => queue.projection(),
|
|
307
|
+
modelCatalog: () => sessionOptions.catalog(),
|
|
308
|
+
attachmentCapability: attachments ? () => attachments!.capability() : undefined,
|
|
309
|
+
approvalProjection: () => piApprovalBroker.projection(ctx.cwd, ctx.sessionManager.getSessionId()),
|
|
310
|
+
approvalDetail: (approvalRef) => piApprovalBroker.detail(ctx.cwd, ctx.sessionManager.getSessionId(), approvalRef),
|
|
311
|
+
sourceMutationGuardAvailable: () => piSourceMutationGuard.available(ctx.cwd, ctx.sessionManager.getSessionId()),
|
|
312
|
+
sourceOpenAvailable: () => vscode.available(),
|
|
313
|
+
lifecycleControl: () => lifecycle.snapshot(),
|
|
314
|
+
chatControl: () => { const snapshot = bridge.snapshot(), held = queue.snapshot(); return { ...snapshot, heldCount: held.heldCount,
|
|
315
|
+
queueRevision: held.queueRevision }; }
|
|
316
|
+
});
|
|
317
|
+
const review = new ReviewController({ bridge, projectRoot: ctx.cwd,
|
|
318
|
+
resolve: (view, fileRef) => provider.review(view, fileRef) as Promise<import("../../piagent-core/runtime/inspection/review-state-projection.ts").ReviewStateProjection> });
|
|
319
|
+
const sourceMutation = new SourceMutationController({ bridge, projectRoot: ctx.cwd,
|
|
320
|
+
resolve: (action, fileRef) => provider.sourceMutationAuthority(action, fileRef), revisions: () => provider.canonicalRevisions(),
|
|
321
|
+
mutate: (input) => piSourceMutationGuard.execute({ cwd: ctx.cwd, rawSessionId: ctx.sessionManager.getSessionId(), ...input }) });
|
|
322
|
+
const sourceRevert = new SourceRevertController({ bridge, projectRoot: ctx.cwd,
|
|
323
|
+
resolve: (fileRef, hunkRefs) => provider.sourceRevertAuthority(fileRef, hunkRefs), revisions: () => provider.canonicalRevisions(),
|
|
324
|
+
mutate: (input) => piSourceMutationGuard.executeRevert({ cwd: ctx.cwd, rawSessionId: ctx.sessionManager.getSessionId(), ...input }) });
|
|
325
|
+
const sourceOpen = new SourceOpenController({ bridge, projectRoot: ctx.cwd, resolve: (fileRef) => provider.sourceOpenAuthority(fileRef),
|
|
326
|
+
open: (absolutePath, line, column) => vscode.open(absolutePath, line, column) });
|
|
327
|
+
const socketDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "piagent-webui-"));
|
|
328
|
+
fs.chmodSync(socketDirectory, 0o700);
|
|
329
|
+
const socket = path.join(socketDirectory, "control.sock");
|
|
330
|
+
const controlToken = randomBytes(32).toString("base64url");
|
|
331
|
+
const loader = path.join(PLATFORM_ROOT, "scripts", "register-typescript-loader.mjs");
|
|
332
|
+
const main = path.join(PACKAGE_ROOT, "server", "sidecar-main.ts");
|
|
333
|
+
const child = spawn(process.execPath, ["--disable-warning=ExperimentalWarning", "--import", loader, main], {
|
|
334
|
+
cwd: ctx.cwd, env: { PATH: process.env.PATH ?? "", TMPDIR: process.env.TMPDIR ?? os.tmpdir(), NO_COLOR: "1" },
|
|
335
|
+
stdio: ["ignore", "ignore", "pipe", "ipc"]
|
|
336
|
+
});
|
|
337
|
+
let diagnostics = "";
|
|
338
|
+
child.stderr?.on("data", (chunk) => { diagnostics = `${diagnostics}${String(chunk)}`.slice(-4_096); });
|
|
339
|
+
let ready: { origin: string; launchUrl: string };
|
|
340
|
+
try {
|
|
341
|
+
ready = await new Promise<{ origin: string; launchUrl: string }>((resolve, reject) => {
|
|
342
|
+
const timer = setTimeout(() => reject(new Error("WebUI sidecar start timed out")), 30_000); timer.unref();
|
|
343
|
+
child.once("error", reject);
|
|
344
|
+
child.once("exit", (code) => reject(new Error(`WebUI sidecar exited (${code ?? "unknown"}): ${diagnostics.replace(/\s+/g, " ").slice(0, 300)}`)));
|
|
345
|
+
child.on("message", (message: any) => {
|
|
346
|
+
if (message?.channel !== "piagent-webui") return;
|
|
347
|
+
if (message.type === "ready" && typeof message.origin === "string" && typeof message.launchUrl === "string") {
|
|
348
|
+
clearTimeout(timer); resolve({ origin: message.origin, launchUrl: message.launchUrl });
|
|
349
|
+
} else if (message.type === "fatal") { clearTimeout(timer); reject(new Error("WebUI sidecar could not start")); }
|
|
350
|
+
});
|
|
351
|
+
child.send({ channel: "piagent-webui", type: "init", staticRoot, controlSocket: socket, controlToken });
|
|
352
|
+
});
|
|
353
|
+
} catch (error) {
|
|
354
|
+
if (child.exitCode === null && !child.killed) child.kill("SIGTERM");
|
|
355
|
+
removeControlDirectory(socketDirectory);
|
|
356
|
+
throw error;
|
|
357
|
+
}
|
|
358
|
+
const manager = { key: key(ctx), ctx, child, provider, eventReader: reader, lastCursor: reader.currentCursor(),
|
|
359
|
+
descriptor: "", controlDirectory: socketDirectory, controlSocket: socket, origin: ready.origin } satisfies Manager;
|
|
360
|
+
manager.descriptor = writeDescriptor(ctx, { schemaVersion: 1, projectRef: webUiProjectRef(ctx.cwd), sessionRef: sessionRef(ctx),
|
|
361
|
+
runtimeInstanceId, origin: ready.origin, controlSocket: socket, controlToken, sidecarPid: child.pid, createdAt: new Date().toISOString() });
|
|
362
|
+
managers.set(manager.key, manager);
|
|
363
|
+
const unsubscribe = provider.subscribe((event) => child.connected && child.send?.({ channel: "piagent-webui", type: "event", event }));
|
|
364
|
+
child.on("message", (message: any) => {
|
|
365
|
+
if (message?.channel !== "piagent-webui" || message.type !== "request" || typeof message.requestId !== "string"
|
|
366
|
+
|| typeof message.method !== "string" || !Array.isArray(message.args)) return;
|
|
367
|
+
void readMethod(provider, queue, sessionOptions, lifecycle, review, sourceMutation, sourceRevert, attachments, sourceOpen,
|
|
368
|
+
(approvalRef, decision) => piApprovalBroker.decide(ctx.cwd, ctx.sessionManager.getSessionId(), approvalRef, decision),
|
|
369
|
+
message.method, message.args).then(
|
|
370
|
+
(value) => child.connected && child.send?.({ channel: "piagent-webui", type: "response", requestId: message.requestId, ok: true, value }),
|
|
371
|
+
(error) => child.connected && child.send?.({ channel: "piagent-webui", type: "response", requestId: message.requestId, ok: false,
|
|
372
|
+
error: message.method === "approvalDecision" && error instanceof Error && /^approval-[a-z-]+$/.test(error.message) ? error.message : "read-model-unavailable" })
|
|
373
|
+
);
|
|
374
|
+
});
|
|
375
|
+
child.once("exit", () => { unsubscribe(); managers.delete(manager.key); removeDescriptor(ctx.cwd, manager.descriptor);
|
|
376
|
+
removeControlDirectory(manager.controlDirectory); });
|
|
377
|
+
if (openBrowser && !openLocalUrl(ready.launchUrl)) ctx.ui.notify(`Open this local URL: ${ready.launchUrl}`, "info");
|
|
378
|
+
ctx.ui.notify(`Piagent WebUI is ready at ${ready.origin}`, "info");
|
|
379
|
+
return manager;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
pi.registerCommand("piagent-webui", {
|
|
383
|
+
description: "Open the local read-only Piagent WebUI for this exact session",
|
|
384
|
+
handler: async (raw: string, ctx: ExtensionContext) => {
|
|
385
|
+
const action = String(raw ?? "").trim().toLowerCase() || "open";
|
|
386
|
+
if (action === "stop") {
|
|
387
|
+
const manager = currentManager(ctx);
|
|
388
|
+
if (!manager) { ctx.ui.notify("Piagent WebUI is not running for this session.", "info"); return; }
|
|
389
|
+
await stopManager(manager); ctx.ui.notify("Piagent WebUI stopped. The Pi session is unchanged.", "info"); return;
|
|
390
|
+
}
|
|
391
|
+
if (action === "status") {
|
|
392
|
+
const manager = currentManager(ctx);
|
|
393
|
+
ctx.ui.notify(manager ? `Piagent WebUI is running at ${manager.origin}` : "Piagent WebUI is not running for this session.", "info"); return;
|
|
394
|
+
}
|
|
395
|
+
if (!['open', '--no-open'].includes(action)) { ctx.ui.notify("Usage: /piagent-webui [open|--no-open|status|stop]", "warning"); return; }
|
|
396
|
+
try { await start(ctx, action !== "--no-open"); }
|
|
397
|
+
catch (error) { ctx.ui.notify(error instanceof Error ? error.message : "Piagent WebUI could not start", "error"); }
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
pi.on("tool_call", (event, ctx) => { publishPersisted(ctx); if (!isGatewayRuntimeContext(ctx) && !terminalAdapter?.dispatchAllowed(ctx)) return { block: true,
|
|
402
|
+
reason: `Piagent cannot prove this terminal owns the session (${terminalAdapter?.reasonCode() ?? "terminal-session-adapter-unavailable"}).` };
|
|
403
|
+
if (!lifecycle.toolAllowed(String(event.toolName ?? ""), ctx)) return { block: true,
|
|
404
|
+
reason: "Piagent lifecycle control blocks tool work while the task is paused, stopping, or terminal. A terminal task may only start its successor." }; });
|
|
405
|
+
pi.on("tool_result", (_event, ctx) => publishPersisted(ctx));
|
|
406
|
+
pi.on("input", (event, ctx) => {
|
|
407
|
+
if (!isGatewayRuntimeContext(ctx) && !terminalAdapter?.dispatchAllowed(ctx)) {
|
|
408
|
+
try { ctx.ui.notify(`Piagent cannot prove this terminal owns the session (${terminalAdapter?.reasonCode() ?? "terminal-session-adapter-unavailable"}).`, "error"); }
|
|
409
|
+
catch { /* optional UI */ }
|
|
410
|
+
return { action: "handled" } as const;
|
|
411
|
+
}
|
|
412
|
+
if (!lifecycle.inputAllowed(ctx)) {
|
|
413
|
+
try { ctx.ui.notify("Piagent task is paused or stopping. Resume it before sending new work.", "warning"); } catch { /* optional UI */ }
|
|
414
|
+
return { action: "handled" } as const;
|
|
415
|
+
}
|
|
416
|
+
if (bridge.sessionOptionMutationActive(ctx)) {
|
|
417
|
+
try { ctx.ui.notify("Piagent WebUI is finishing a model/thinking change; retry this input after it settles.", "warning"); } catch { /* optional UI */ }
|
|
418
|
+
return { action: "handled" } as const;
|
|
419
|
+
}
|
|
420
|
+
bridgeSoft(() => bridge.observeInput(event, ctx)); return undefined;
|
|
421
|
+
});
|
|
422
|
+
pi.on("agent_start", (_event, ctx) => {
|
|
423
|
+
bridgeSoft(() => bridge.observeAgentStart(ctx)); bridgeSoft(() => lifecycle.observeAgentStart(ctx)); publishDrafts(ctx, stream.agentStarted(bridge.snapshot()));
|
|
424
|
+
});
|
|
425
|
+
pi.on("turn_start", (event, ctx) => publishDrafts(ctx, stream.turnStarted(event, bridge.snapshot())));
|
|
426
|
+
pi.on("message_start", (event, ctx) => {
|
|
427
|
+
bridgeSoft(() => bridge.observeMessageStart(event, ctx)); publishDrafts(ctx, stream.messageStarted(event, bridge.snapshot()));
|
|
428
|
+
});
|
|
429
|
+
pi.on("message_update", (event, ctx) => publishDrafts(ctx, stream.messageUpdated(event, bridge.snapshot())));
|
|
430
|
+
pi.on("message_end", (event, ctx) => publishDrafts(ctx, stream.messageEnded(event, bridge.snapshot())));
|
|
431
|
+
pi.on("tool_execution_start", (event, ctx) => { bridgeSoft(() => lifecycle.observeToolStart(ctx)); publishDrafts(ctx, stream.toolStarted(event, bridge.snapshot())); });
|
|
432
|
+
pi.on("tool_execution_update", (event, ctx) => publishDrafts(ctx, stream.toolUpdated(event, bridge.snapshot())));
|
|
433
|
+
pi.on("tool_execution_end", (event, ctx) => { publishDrafts(ctx, stream.toolEnded(event, bridge.snapshot())); bridgeSoft(() => lifecycle.observeToolEnd(ctx)); });
|
|
434
|
+
pi.on("turn_end", (event, ctx) => publishDrafts(ctx, stream.turnEnded(event, bridge.snapshot())));
|
|
435
|
+
pi.on("agent_settled", (_event, ctx) => {
|
|
436
|
+
publishDrafts(ctx, stream.agentSettled(bridge.snapshot(), typeof ctx.hasPendingMessages === "function" ? ctx.hasPendingMessages() : null));
|
|
437
|
+
const operationId = bridge.snapshot().identity?.agentOperationId ?? null;
|
|
438
|
+
bridgeSoft(() => bridge.observeAgentSettled(ctx)); bridgeSoft(() => lifecycle.observeAgentSettled(ctx, operationId)); publishPersisted(ctx);
|
|
439
|
+
});
|
|
440
|
+
pi.on("session_info_changed", (_event, ctx) => { currentContext = ctx; bridgeSoft(() => bridge.refresh(ctx)); });
|
|
441
|
+
pi.on("model_select", (_event, ctx) => { currentContext = ctx; bridgeSoft(() => sessionOptions.observeHostOptionChange(ctx)); currentManager(ctx)?.provider.invalidate(); });
|
|
442
|
+
pi.on("thinking_level_select", (_event, ctx) => { currentContext = ctx; bridgeSoft(() => sessionOptions.observeHostOptionChange(ctx)); currentManager(ctx)?.provider.invalidate(); });
|
|
443
|
+
pi.on("session_before_switch", () => { lifecycle.replacementPending(); bridgeSoft(() => bridge.replacementPending()); });
|
|
444
|
+
pi.on("session_before_fork", () => { lifecycle.replacementPending(); bridgeSoft(() => bridge.replacementPending()); });
|
|
445
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
446
|
+
currentContext = ctx; stream.reset(); queue.reset(); sessionOptions.reset(); attachments?.reset();
|
|
447
|
+
if (!isGatewayRuntimeContext(ctx)) {
|
|
448
|
+
try { terminalAdapter ??= new TerminalSessionAdapter(runtimeInstanceId); } catch { terminalAdapter = null; }
|
|
449
|
+
try { terminalAdapter?.bind(ctx); }
|
|
450
|
+
catch (error) { try { ctx.ui.notify(error instanceof Error ? error.message : "terminal-session-lease-unavailable", "error"); } catch { /* optional UI */ } }
|
|
451
|
+
}
|
|
452
|
+
bridgeSoft(() => bridge.bind(ctx));
|
|
453
|
+
bridgeSoft(() => lifecycle.bind(ctx));
|
|
454
|
+
bridgeSoft(() => bindApproval(ctx));
|
|
455
|
+
bridgeSoft(() => sessionOptions.bind(ctx));
|
|
456
|
+
if (String(process.env.PIAGENT_WEBUI_AUTOSTART ?? "").toLowerCase() !== "1") return;
|
|
457
|
+
try { await start(ctx, false); }
|
|
458
|
+
catch (error) { ctx.ui.notify(error instanceof Error ? error.message : "Piagent WebUI could not start", "error"); }
|
|
459
|
+
});
|
|
460
|
+
pi.on("session_shutdown", async (_event, ctx) => {
|
|
461
|
+
stream.reset(); queue.reset(); sessionOptions.reset(); attachments?.close(); eventReaders.delete(key(ctx));
|
|
462
|
+
if (approvalBinding?.key === key(ctx)) { approvalBinding.unsubscribe(); approvalBinding.unbind(); approvalBinding = null; }
|
|
463
|
+
lifecycle.shutdown();
|
|
464
|
+
bridgeSoft(() => bridge.shutdown(ctx));
|
|
465
|
+
terminalAdapter?.release();
|
|
466
|
+
const manager = currentManager(ctx);
|
|
467
|
+
if (manager) await stopManager(manager);
|
|
468
|
+
currentContext = null;
|
|
469
|
+
});
|
|
470
|
+
}
|