@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,73 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
|
|
5
|
+
import { gatewayProfileState, readOrCreateCatalogKey } from "../ownership/profile-state.ts";
|
|
6
|
+
import { sessionRefForPath } from "../ownership/session-refs.ts";
|
|
7
|
+
import { SessionLeaseStore, type SessionLeaseSnapshot } from "../ownership/session-lease-store.ts";
|
|
8
|
+
|
|
9
|
+
type Binding = {
|
|
10
|
+
rawSessionId: string;
|
|
11
|
+
sessionRef: string;
|
|
12
|
+
lease: SessionLeaseSnapshot;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Registers the Pi TUI as the exact session writer in the same durable lease
|
|
17
|
+
* authority used by the Gateway. A failed registration is fail-closed for new
|
|
18
|
+
* input/tool work; it never claims that two runtimes can safely share JSONL.
|
|
19
|
+
*/
|
|
20
|
+
export class TerminalSessionAdapter {
|
|
21
|
+
readonly #terminalInstanceRef = `terminal_${process.pid}_${randomBytes(16).toString("base64url")}`;
|
|
22
|
+
readonly #runtimeInstanceRef: string;
|
|
23
|
+
readonly #leases: SessionLeaseStore;
|
|
24
|
+
readonly #key: Buffer;
|
|
25
|
+
#binding: Binding | null = null;
|
|
26
|
+
#reasonCode: string | null = "terminal-session-not-bound";
|
|
27
|
+
|
|
28
|
+
constructor(runtimeInstanceRef: string, agentDir?: string) {
|
|
29
|
+
this.#runtimeInstanceRef = runtimeInstanceRef;
|
|
30
|
+
const state = gatewayProfileState(agentDir);
|
|
31
|
+
this.#key = readOrCreateCatalogKey(state);
|
|
32
|
+
this.#leases = new SessionLeaseStore(state.root, this.#key);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
bind(ctx: ExtensionContext): void {
|
|
36
|
+
const file = ctx.sessionManager.getSessionFile();
|
|
37
|
+
if (!file) { this.#reasonCode = "terminal-session-not-persisted"; throw new Error(this.#reasonCode); }
|
|
38
|
+
const rawSessionId = ctx.sessionManager.getSessionId();
|
|
39
|
+
const sessionRef = sessionRefForPath(this.#key, file);
|
|
40
|
+
if (this.#binding?.rawSessionId === rawSessionId && this.#binding.sessionRef === sessionRef
|
|
41
|
+
&& this.#leases.inspect(sessionRef).ownerEpoch === this.#binding.lease.ownerEpoch) {
|
|
42
|
+
this.#reasonCode = null; return;
|
|
43
|
+
}
|
|
44
|
+
this.release();
|
|
45
|
+
const lease = this.#leases.acquireTerminal(sessionRef, this.#terminalInstanceRef, this.#runtimeInstanceRef);
|
|
46
|
+
this.#binding = { rawSessionId, sessionRef, lease };
|
|
47
|
+
this.#reasonCode = null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
dispatchAllowed(ctx: ExtensionContext): boolean {
|
|
51
|
+
const binding = this.#binding;
|
|
52
|
+
if (!binding || binding.rawSessionId !== ctx.sessionManager.getSessionId()) return false;
|
|
53
|
+
const current = this.#leases.inspect(binding.sessionRef);
|
|
54
|
+
const exact = current.state === "terminal-owned" && current.ownerEpoch === binding.lease.ownerEpoch
|
|
55
|
+
&& current.gatewayInstanceRef === this.#terminalInstanceRef && current.runtimeInstanceRef === this.#runtimeInstanceRef;
|
|
56
|
+
if (!exact) this.#reasonCode = current.state === "gateway-owned" ? "session-owned-by-gateway" : "terminal-session-lease-lost";
|
|
57
|
+
return exact;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
reasonCode(): string { return this.#reasonCode ?? "terminal-session-lease-unavailable"; }
|
|
61
|
+
|
|
62
|
+
release(): void {
|
|
63
|
+
const binding = this.#binding;
|
|
64
|
+
this.#binding = null;
|
|
65
|
+
if (!binding?.lease.ownerEpoch) return;
|
|
66
|
+
try {
|
|
67
|
+
this.#leases.releaseTerminal(binding.sessionRef, binding.lease.ownerEpoch, this.#terminalInstanceRef, this.#runtimeInstanceRef);
|
|
68
|
+
this.#reasonCode = "terminal-session-released";
|
|
69
|
+
} catch {
|
|
70
|
+
this.#reasonCode = "terminal-session-release-unproven";
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
export type VSCodeHandoffResult = { state: "settled" | "rejected" | "uncertain"; reasonCode: string | null };
|
|
7
|
+
|
|
8
|
+
function executable(candidate: string): string | null {
|
|
9
|
+
try {
|
|
10
|
+
if (!path.isAbsolute(candidate)) return null;
|
|
11
|
+
const resolved = fs.realpathSync.native(candidate), stat = fs.lstatSync(resolved);
|
|
12
|
+
if (!stat.isFile() || stat.isSymbolicLink()) return null;
|
|
13
|
+
fs.accessSync(resolved, fs.constants.X_OK); return resolved;
|
|
14
|
+
} catch { return null; }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function discoverVSCodeCli(input: { platform?: NodeJS.Platform; pathValue?: string } = {}): string | null {
|
|
18
|
+
const platform = input.platform ?? process.platform, candidates: string[] = [];
|
|
19
|
+
if (platform === "darwin") candidates.push("/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code",
|
|
20
|
+
path.join(os.homedir(), "Applications/Visual Studio Code.app/Contents/Resources/app/bin/code"));
|
|
21
|
+
for (const directory of String(input.pathValue ?? process.env.PATH ?? "").split(path.delimiter))
|
|
22
|
+
if (directory && path.isAbsolute(directory)) candidates.push(path.join(directory, platform === "win32" ? "code.exe" : "code"));
|
|
23
|
+
for (const candidate of [...new Set(candidates)]) { const resolved = executable(candidate); if (resolved) return resolved; }
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class VSCodeHandoff {
|
|
28
|
+
readonly #cli: string | null; readonly #timeoutMs: number;
|
|
29
|
+
constructor(options: { cli?: string | null; timeoutMs?: number } = {}) {
|
|
30
|
+
this.#cli = options.cli === undefined ? discoverVSCodeCli() : options.cli ? executable(options.cli) : null;
|
|
31
|
+
this.#timeoutMs = Math.max(500, Math.min(30_000, options.timeoutMs ?? 8_000));
|
|
32
|
+
}
|
|
33
|
+
available(): boolean { return this.#cli !== null; }
|
|
34
|
+
async open(absolutePath: string, line: number | null, column: number | null): Promise<VSCodeHandoffResult> {
|
|
35
|
+
if (!this.#cli) return { state: "rejected", reasonCode: "vscode-cli-unavailable" };
|
|
36
|
+
const location = line === null ? absolutePath : `${absolutePath}:${line}${column === null ? "" : `:${column}`}`;
|
|
37
|
+
return new Promise((resolve) => {
|
|
38
|
+
let settled = false, stderrBytes = 0, timedOut = false;
|
|
39
|
+
const child = spawn(this.#cli!, ["--reuse-window", "--goto", location], { shell: false, windowsHide: true,
|
|
40
|
+
env: { PATH: process.env.PATH, HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE, TMPDIR: process.env.TMPDIR,
|
|
41
|
+
SystemRoot: process.env.SystemRoot, ComSpec: process.env.ComSpec }, stdio: ["ignore", "ignore", "pipe"] });
|
|
42
|
+
child.stderr.on("data", (chunk: Buffer) => { stderrBytes += chunk.length; if (stderrBytes > 64 * 1024) child.kill("SIGKILL"); });
|
|
43
|
+
const timer = setTimeout(() => { timedOut = true; child.kill("SIGKILL"); }, this.#timeoutMs); timer.unref?.();
|
|
44
|
+
child.once("error", () => { clearTimeout(timer); if (!settled) { settled = true; resolve({ state: "rejected", reasonCode: "vscode-launch-failed" }); } });
|
|
45
|
+
child.once("close", (code) => { clearTimeout(timer); if (settled) return; settled = true;
|
|
46
|
+
resolve(timedOut ? { state: "uncertain", reasonCode: "vscode-launch-timeout" }
|
|
47
|
+
: code === 0 && stderrBytes <= 64 * 1024 ? { state: "settled", reasonCode: null }
|
|
48
|
+
: { state: "rejected", reasonCode: "vscode-launch-failed" }); });
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import net from "node:net";
|
|
3
|
+
|
|
4
|
+
const MAX_MESSAGE_BYTES = 4_096;
|
|
5
|
+
|
|
6
|
+
export type GatewayControlRequest = { action: "health" | "issue-launch-url" | "stop" };
|
|
7
|
+
export type GatewayControlResponse = { ok: true; value: unknown } | { ok: false; error: string };
|
|
8
|
+
|
|
9
|
+
export async function requestGatewayControl(socketPath: string, request: GatewayControlRequest, timeoutMs = 1_500): Promise<GatewayControlResponse> {
|
|
10
|
+
return await new Promise((resolve, reject) => {
|
|
11
|
+
const socket = net.createConnection({ path: socketPath });
|
|
12
|
+
let body = "", settled = false;
|
|
13
|
+
const finish = (callback: () => void) => { if (settled) return; settled = true; clearTimeout(timer); socket.destroy(); callback(); };
|
|
14
|
+
const timer = setTimeout(() => finish(() => reject(new Error("gateway-control-timeout"))), timeoutMs);
|
|
15
|
+
socket.setEncoding("utf8");
|
|
16
|
+
socket.once("connect", () => socket.write(`${JSON.stringify(request)}\n`));
|
|
17
|
+
socket.on("data", (chunk) => {
|
|
18
|
+
body += chunk;
|
|
19
|
+
if (Buffer.byteLength(body) > MAX_MESSAGE_BYTES) return finish(() => reject(new Error("gateway-control-response-limit")));
|
|
20
|
+
const newline = body.indexOf("\n");
|
|
21
|
+
if (newline < 0) return;
|
|
22
|
+
finish(() => {
|
|
23
|
+
try { resolve(JSON.parse(body.slice(0, newline)) as GatewayControlResponse); }
|
|
24
|
+
catch { reject(new Error("gateway-control-response-invalid")); }
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
socket.once("error", (error) => finish(() => reject(error)));
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function removeStaleSocket(socketPath: string): Promise<void> {
|
|
32
|
+
let before: fs.Stats;
|
|
33
|
+
try { before = fs.lstatSync(socketPath); }
|
|
34
|
+
catch { return; }
|
|
35
|
+
if (!before.isSocket() || before.isSymbolicLink()) throw new Error("gateway-control-path-invalid");
|
|
36
|
+
try {
|
|
37
|
+
const live = await requestGatewayControl(socketPath, { action: "health" }, 500);
|
|
38
|
+
if (live.ok) throw new Error("gateway-already-running");
|
|
39
|
+
} catch (error) {
|
|
40
|
+
if (error instanceof Error && error.message === "gateway-already-running") throw error;
|
|
41
|
+
}
|
|
42
|
+
const after = fs.lstatSync(socketPath);
|
|
43
|
+
if (!after.isSocket() || after.dev !== before.dev || after.ino !== before.ino) throw new Error("gateway-control-path-race");
|
|
44
|
+
fs.unlinkSync(socketPath);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function startGatewayControlSocket(options: {
|
|
48
|
+
socketPath: string;
|
|
49
|
+
handle(request: GatewayControlRequest): Promise<GatewayControlResponse> | GatewayControlResponse;
|
|
50
|
+
}): Promise<{ close(): Promise<void> }> {
|
|
51
|
+
await removeStaleSocket(options.socketPath);
|
|
52
|
+
const server = net.createServer((socket) => {
|
|
53
|
+
socket.setEncoding("utf8");
|
|
54
|
+
let body = "", finished = false;
|
|
55
|
+
const fail = (error: string) => { if (finished) return; finished = true; socket.end(`${JSON.stringify({ ok: false, error })}\n`); };
|
|
56
|
+
socket.on("data", (chunk) => {
|
|
57
|
+
if (finished) return;
|
|
58
|
+
body += chunk;
|
|
59
|
+
if (Buffer.byteLength(body) > MAX_MESSAGE_BYTES) return fail("request-limit");
|
|
60
|
+
const newline = body.indexOf("\n");
|
|
61
|
+
if (newline < 0) return;
|
|
62
|
+
finished = true;
|
|
63
|
+
void (async () => {
|
|
64
|
+
let request: GatewayControlRequest;
|
|
65
|
+
try {
|
|
66
|
+
const parsed = JSON.parse(body.slice(0, newline)) as Partial<GatewayControlRequest>;
|
|
67
|
+
if (!parsed || !["health", "issue-launch-url", "stop"].includes(String(parsed.action))
|
|
68
|
+
|| Object.keys(parsed).some((key) => key !== "action")) throw new Error("invalid");
|
|
69
|
+
request = parsed as GatewayControlRequest;
|
|
70
|
+
} catch { socket.end(`${JSON.stringify({ ok: false, error: "invalid-request" })}\n`); return; }
|
|
71
|
+
try { socket.end(`${JSON.stringify(await options.handle(request))}\n`); }
|
|
72
|
+
catch { socket.end(`${JSON.stringify({ ok: false, error: "control-failed" })}\n`); }
|
|
73
|
+
})();
|
|
74
|
+
});
|
|
75
|
+
socket.once("error", () => { socket.destroy(); });
|
|
76
|
+
});
|
|
77
|
+
await new Promise<void>((resolve, reject) => {
|
|
78
|
+
server.once("error", reject);
|
|
79
|
+
server.listen(options.socketPath, resolve);
|
|
80
|
+
});
|
|
81
|
+
fs.chmodSync(options.socketPath, 0o600);
|
|
82
|
+
const identity = fs.lstatSync(options.socketPath);
|
|
83
|
+
return {
|
|
84
|
+
close: async () => {
|
|
85
|
+
await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
|
|
86
|
+
try {
|
|
87
|
+
const current = fs.lstatSync(options.socketPath);
|
|
88
|
+
if (current.isSocket() && current.dev === identity.dev && current.ino === identity.ino) fs.unlinkSync(options.socketPath);
|
|
89
|
+
} catch { /* already removed */ }
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
type ExtensionLoadResult = {
|
|
5
|
+
extensions: Array<{ path: string; resolvedPath: string }>;
|
|
6
|
+
errors: Array<{ path: string; error: string }>;
|
|
7
|
+
runtime: unknown;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
const PIAGENT_GUARD_SUFFIX = path.join("packages", "piagent-core", "extensions", "piagent-guard.ts");
|
|
11
|
+
|
|
12
|
+
function canonicalExtensionPath(value: string): string {
|
|
13
|
+
try { return fs.realpathSync.native(value); }
|
|
14
|
+
catch { return path.resolve(value); }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function isPiagentGuardPath(value: string): boolean {
|
|
18
|
+
const normalized = path.normalize(value);
|
|
19
|
+
return normalized === PIAGENT_GUARD_SUFFIX || normalized.endsWith(`${path.sep}${PIAGENT_GUARD_SUFFIX}`);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function preferAuthoritativePiagentGuard(
|
|
23
|
+
guardPath: string
|
|
24
|
+
): (base: ExtensionLoadResult) => ExtensionLoadResult {
|
|
25
|
+
const authoritative = canonicalExtensionPath(guardPath);
|
|
26
|
+
const authorityAliases = [guardPath, path.resolve(guardPath), authoritative].map((value) => path.normalize(value));
|
|
27
|
+
return (base) => {
|
|
28
|
+
const loadedAuthoritative = base.extensions.some((extension) =>
|
|
29
|
+
canonicalExtensionPath(extension.resolvedPath || extension.path) === authoritative);
|
|
30
|
+
if (!loadedAuthoritative) return base;
|
|
31
|
+
const removed = new Set<string>();
|
|
32
|
+
const extensions = base.extensions.filter((extension) => {
|
|
33
|
+
const resolved = canonicalExtensionPath(extension.resolvedPath || extension.path);
|
|
34
|
+
const duplicate = resolved !== authoritative && isPiagentGuardPath(resolved);
|
|
35
|
+
if (duplicate) removed.add(resolved);
|
|
36
|
+
return !duplicate;
|
|
37
|
+
});
|
|
38
|
+
if (removed.size === 0) return base;
|
|
39
|
+
const errors = base.errors.filter((diagnostic) => {
|
|
40
|
+
const diagnosticPath = canonicalExtensionPath(diagnostic.path);
|
|
41
|
+
return !(removed.has(diagnosticPath)
|
|
42
|
+
&& diagnostic.error.includes("conflicts with")
|
|
43
|
+
&& authorityAliases.some((value) => diagnostic.error.includes(value)));
|
|
44
|
+
});
|
|
45
|
+
return { ...base, extensions, errors };
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export type GatewayEventKind = "catalog.changed" | "session.changed" | "runtime.changed" | "message.delta"
|
|
2
|
+
| "message.completed" | "tool.started" | "tool.completed";
|
|
3
|
+
|
|
4
|
+
export type GatewayProtocolEvent = {
|
|
5
|
+
schemaVersion: 1;
|
|
6
|
+
version: "piagent-gateway-protocol-v1";
|
|
7
|
+
messageType: "event";
|
|
8
|
+
sequence: number;
|
|
9
|
+
stateVersion: number;
|
|
10
|
+
generatedAt: string;
|
|
11
|
+
kind: GatewayEventKind | "resync.required";
|
|
12
|
+
payload: Record<string, unknown>;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export class GatewayEventStore {
|
|
16
|
+
readonly #maximumCount: number;
|
|
17
|
+
readonly #maximumAgeMs: number;
|
|
18
|
+
#events: GatewayProtocolEvent[] = [];
|
|
19
|
+
#sequence = 0;
|
|
20
|
+
#listeners = new Set<(event: GatewayProtocolEvent) => void>();
|
|
21
|
+
|
|
22
|
+
constructor(options: { maximumCount?: number; maximumAgeMs?: number } = {}) {
|
|
23
|
+
this.#maximumCount = Math.max(1, Math.min(10_000, options.maximumCount ?? 1_000));
|
|
24
|
+
this.#maximumAgeMs = Math.max(1_000, Math.min(24 * 60 * 60_000, options.maximumAgeMs ?? 60 * 60_000));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
get stateVersion(): number { return this.#sequence; }
|
|
28
|
+
|
|
29
|
+
#prune(now: number): void {
|
|
30
|
+
const cutoff = now - this.#maximumAgeMs;
|
|
31
|
+
while (this.#events.length > this.#maximumCount || this.#events[0] && Date.parse(this.#events[0].generatedAt) < cutoff) this.#events.shift();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
publish(kind: GatewayEventKind, payload: Record<string, unknown>, now = new Date()): GatewayProtocolEvent {
|
|
35
|
+
if (!Number.isFinite(now.getTime())) throw new Error("gateway-event-time-invalid");
|
|
36
|
+
this.#sequence += 1;
|
|
37
|
+
const event: GatewayProtocolEvent = {
|
|
38
|
+
schemaVersion: 1, version: "piagent-gateway-protocol-v1", messageType: "event",
|
|
39
|
+
sequence: this.#sequence, stateVersion: this.#sequence, generatedAt: now.toISOString(), kind, payload
|
|
40
|
+
};
|
|
41
|
+
this.#events.push(event); this.#prune(now.getTime());
|
|
42
|
+
for (const listener of this.#listeners) { try { listener(event); } catch { /* observers cannot block truth */ } }
|
|
43
|
+
return event;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
subscribe(listener: (event: GatewayProtocolEvent) => void): () => void {
|
|
47
|
+
this.#listeners.add(listener);
|
|
48
|
+
return () => { this.#listeners.delete(listener); };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
replay(after: number | null): { state: "current" | "resync-required"; events: GatewayProtocolEvent[]; earliestSequence: number; currentSequence: number } {
|
|
52
|
+
this.#prune(Date.now());
|
|
53
|
+
const earliestSequence = this.#events[0]?.sequence ?? this.#sequence;
|
|
54
|
+
if (after !== null && after < Math.max(0, earliestSequence - 1)) {
|
|
55
|
+
return { state: "resync-required", events: [], earliestSequence, currentSequence: this.#sequence };
|
|
56
|
+
}
|
|
57
|
+
return { state: "current", events: after === null ? [] : this.#events.filter((event) => event.sequence > after), earliestSequence,
|
|
58
|
+
currentSequence: this.#sequence };
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { PiagentGatewayCapabilityHandshakeV1 } from "../contracts/generated/gateway-capabilities-v1.ts";
|
|
2
|
+
import type { Catalog, SessionDetail } from "../contracts/generated/session-catalog-v1.ts";
|
|
3
|
+
import type { GatewayProtocolHandler, GatewayRequest } from "../server/gateway-websocket.ts";
|
|
4
|
+
import { GatewayEventStore } from "./gateway-events.ts";
|
|
5
|
+
|
|
6
|
+
type ListParams = { cursor: string | null; limit: number; filter: "active" | "archived" | "all"; query: string | null; projectRef: string | null };
|
|
7
|
+
|
|
8
|
+
export class GatewayProtocolFailure extends Error {
|
|
9
|
+
readonly code: string;
|
|
10
|
+
readonly retryable: boolean;
|
|
11
|
+
constructor(code: string, retryable = false) { super(code); this.code = code; this.retryable = retryable; }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class GatewayProtocolService implements GatewayProtocolHandler {
|
|
15
|
+
readonly events: GatewayEventStore;
|
|
16
|
+
readonly #capabilities: () => PiagentGatewayCapabilityHandshakeV1;
|
|
17
|
+
readonly #catalog: () => Promise<Catalog>;
|
|
18
|
+
readonly #command?: { execute(command: unknown): Promise<unknown> };
|
|
19
|
+
|
|
20
|
+
constructor(options: {
|
|
21
|
+
capabilities(): PiagentGatewayCapabilityHandshakeV1;
|
|
22
|
+
catalog(): Promise<Catalog>;
|
|
23
|
+
events?: GatewayEventStore;
|
|
24
|
+
command?: { execute(command: unknown): Promise<unknown> };
|
|
25
|
+
}) {
|
|
26
|
+
this.#capabilities = options.capabilities;
|
|
27
|
+
this.#catalog = options.catalog;
|
|
28
|
+
this.#command = options.command;
|
|
29
|
+
this.events = options.events ?? new GatewayEventStore();
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
capabilities(): PiagentGatewayCapabilityHandshakeV1 { return this.#capabilities(); }
|
|
33
|
+
|
|
34
|
+
async execute(request: GatewayRequest): Promise<unknown> {
|
|
35
|
+
if (request.method === "gateway.health") return this.#capabilities();
|
|
36
|
+
if (request.method === "sessions.command") {
|
|
37
|
+
if (!this.#command) throw new GatewayProtocolFailure("session-actions-unavailable");
|
|
38
|
+
try { return await this.#command.execute(request.params.command); }
|
|
39
|
+
catch (error) { throw new GatewayProtocolFailure(error instanceof Error ? error.message : "invalid-session-command"); }
|
|
40
|
+
}
|
|
41
|
+
const catalog = await this.#catalog();
|
|
42
|
+
if (catalog.state !== "ready") throw new GatewayProtocolFailure(catalog.reasonCode ?? "catalog-unavailable", true);
|
|
43
|
+
if (request.method === "sessions.get") {
|
|
44
|
+
const session = catalog.sessions.find((item) => item.sessionRef === request.params.sessionRef);
|
|
45
|
+
if (!session) throw new GatewayProtocolFailure("session-not-found");
|
|
46
|
+
const detail: SessionDetail = {
|
|
47
|
+
schemaVersion: 1, version: "piagent-session-detail-v1", generatedAt: new Date().toISOString(),
|
|
48
|
+
gatewayInstanceRef: catalog.gatewayInstanceRef, catalogRevision: catalog.catalogRevision!, session
|
|
49
|
+
};
|
|
50
|
+
return detail;
|
|
51
|
+
}
|
|
52
|
+
const params = request.params as ListParams;
|
|
53
|
+
if (params.cursor !== null) throw new GatewayProtocolFailure("catalog-cursor-unavailable", true);
|
|
54
|
+
const query = params.query?.toLocaleLowerCase() ?? null;
|
|
55
|
+
const filtered = catalog.sessions.filter((item) => (params.filter === "all" || (params.filter === "archived") === item.archived)
|
|
56
|
+
&& (!params.projectRef || item.projectRef === params.projectRef)
|
|
57
|
+
&& (!query || `${item.title} ${item.projectLabel} ${item.preview}`.toLocaleLowerCase().includes(query)));
|
|
58
|
+
const sessions = filtered.slice(0, params.limit);
|
|
59
|
+
return {
|
|
60
|
+
...catalog, sessions,
|
|
61
|
+
page: { limit: params.limit, returned: sessions.length, total: filtered.length, nextCursor: null, truncated: filtered.length > sessions.length }
|
|
62
|
+
} satisfies Catalog;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
import { redactSensitiveText } from "../../piagent-core/security/sensitive-data.js";
|
|
6
|
+
import type { PiagentGatewayCapabilityHandshakeV1 } from "../contracts/generated/gateway-capabilities-v1.ts";
|
|
7
|
+
import { startLoopbackServer } from "../server/loopback-server.ts";
|
|
8
|
+
import { startGatewayControlSocket, type GatewayControlResponse } from "./control-socket.ts";
|
|
9
|
+
import { loadPinnedPiHost } from "./pi-host.ts";
|
|
10
|
+
import {
|
|
11
|
+
gatewayProfileState,
|
|
12
|
+
profileRef,
|
|
13
|
+
readOrCreateCatalogKey,
|
|
14
|
+
removeGatewayDescriptor,
|
|
15
|
+
writeGatewayDescriptor,
|
|
16
|
+
type GatewayDescriptor
|
|
17
|
+
} from "./profile-state.ts";
|
|
18
|
+
import { buildSessionCatalog } from "./session-catalog.ts";
|
|
19
|
+
import { SessionMetadataStore } from "./session-metadata-store.ts";
|
|
20
|
+
import { GatewayProtocolService } from "./gateway-protocol-service.ts";
|
|
21
|
+
import { SessionLeaseStore } from "./session-lease-store.ts";
|
|
22
|
+
import { SessionRuntimeSupervisor } from "./session-runtime-supervisor.ts";
|
|
23
|
+
import { SessionCommandStore } from "./session-command-store.ts";
|
|
24
|
+
import { SessionCommandController } from "./session-command-controller.ts";
|
|
25
|
+
import { GatewayEventStore } from "./gateway-events.ts";
|
|
26
|
+
import { SessionInspectionRegistry } from "./session-inspection-registry.ts";
|
|
27
|
+
import { ProjectRegistry } from "./project-registry.ts";
|
|
28
|
+
import { pickNativeProjectFolders } from "./native-project-picker.ts";
|
|
29
|
+
import { ProviderAuthBroker } from "./provider-auth-broker.ts";
|
|
30
|
+
import { McpAuthBroker } from "./mcp-auth-broker.ts";
|
|
31
|
+
|
|
32
|
+
function unavailable(reasonCode: string) {
|
|
33
|
+
return { status: "unavailable" as const, version: null, reasonCode };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function available(version = 1) { return { status: "available" as const, version, reasonCode: null }; }
|
|
37
|
+
|
|
38
|
+
function safeModelLabel(value: unknown): string {
|
|
39
|
+
return (redactSensitiveText(String(value ?? "Model")).text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim() || "Model").slice(0, 120);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function capabilities(gatewayInstanceRef: string, runtimeAvailable = false): PiagentGatewayCapabilityHandshakeV1 {
|
|
43
|
+
return {
|
|
44
|
+
schemaVersion: 1,
|
|
45
|
+
version: "piagent-gateway-capabilities-v1",
|
|
46
|
+
generatedAt: new Date().toISOString(),
|
|
47
|
+
gatewayInstanceRef,
|
|
48
|
+
protocol: { minimum: 1, maximum: 1, selected: 1, compatibility: "ready" },
|
|
49
|
+
mode: runtimeAvailable ? "full" : "read-only",
|
|
50
|
+
capabilities: {
|
|
51
|
+
catalog: available(),
|
|
52
|
+
events: available(),
|
|
53
|
+
terminalAdapter: runtimeAvailable ? available() : unavailable("terminal-adapter-not-enabled"),
|
|
54
|
+
sessionRuntime: runtimeAvailable ? available() : unavailable("session-runtime-not-enabled"),
|
|
55
|
+
sessionActions: {
|
|
56
|
+
create: runtimeAvailable ? available() : unavailable("session-runtime-not-enabled"),
|
|
57
|
+
send: runtimeAvailable ? available() : unavailable("session-runtime-not-enabled"),
|
|
58
|
+
abort: runtimeAvailable ? available() : unavailable("session-runtime-not-enabled"),
|
|
59
|
+
setModel: runtimeAvailable ? available() : unavailable("session-runtime-not-enabled"),
|
|
60
|
+
setThinking: runtimeAvailable ? available() : unavailable("session-runtime-not-enabled"),
|
|
61
|
+
setPermission: runtimeAvailable ? available() : unavailable("session-runtime-not-enabled"),
|
|
62
|
+
rename: runtimeAvailable ? available() : unavailable("session-runtime-not-enabled"),
|
|
63
|
+
pin: runtimeAvailable ? available() : unavailable("session-runtime-not-enabled"),
|
|
64
|
+
archive: runtimeAvailable ? available() : unavailable("session-runtime-not-enabled"),
|
|
65
|
+
unarchive: runtimeAvailable ? available() : unavailable("session-runtime-not-enabled"),
|
|
66
|
+
fork: runtimeAvailable ? available() : unavailable("session-runtime-not-enabled"),
|
|
67
|
+
acquire: runtimeAvailable ? available() : unavailable("session-owner-lease-not-enabled"),
|
|
68
|
+
release: runtimeAvailable ? available() : unavailable("session-owner-lease-not-enabled")
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
reasonCode: null
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function startPiagentGateway(options: {
|
|
76
|
+
packageRoot: string;
|
|
77
|
+
expectedPiVersion: string;
|
|
78
|
+
agentDir?: string;
|
|
79
|
+
}): Promise<{ descriptor: GatewayDescriptor; wait(): Promise<void>; close(): Promise<void> }> {
|
|
80
|
+
const state = gatewayProfileState(options.agentDir);
|
|
81
|
+
process.env.PI_CODING_AGENT_DIR = state.agentDir;
|
|
82
|
+
const key = readOrCreateCatalogKey(state);
|
|
83
|
+
const metadata = new SessionMetadataStore(state.root, key);
|
|
84
|
+
const projects = new ProjectRegistry(state.root, key);
|
|
85
|
+
const gatewayInstanceRef = `gateway_${process.pid}_${randomBytes(24).toString("base64url")}`;
|
|
86
|
+
const staticRoot = path.join(options.packageRoot, "packages", "piagent-webui", "dist", "client");
|
|
87
|
+
if (!fs.existsSync(path.join(staticRoot, "index.html"))) throw new Error("gateway-webui-build-missing");
|
|
88
|
+
|
|
89
|
+
let descriptor: GatewayDescriptor | null = null;
|
|
90
|
+
let loopback: Awaited<ReturnType<typeof startLoopbackServer>> | null = null;
|
|
91
|
+
let control: Awaited<ReturnType<typeof startGatewayControlSocket>> | null = null;
|
|
92
|
+
let runtimes: SessionRuntimeSupervisor | null = null;
|
|
93
|
+
let mcpAuth: McpAuthBroker | null = null;
|
|
94
|
+
let closing: Promise<void> | null = null;
|
|
95
|
+
let settleWait: (() => void) | null = null;
|
|
96
|
+
const waited = new Promise<void>((resolve) => { settleWait = resolve; });
|
|
97
|
+
|
|
98
|
+
const close = async () => {
|
|
99
|
+
if (closing) return await closing;
|
|
100
|
+
closing = (async () => {
|
|
101
|
+
removeGatewayDescriptor(state, gatewayInstanceRef);
|
|
102
|
+
await loopback?.close().catch(() => undefined);
|
|
103
|
+
await mcpAuth?.close().catch(() => undefined);
|
|
104
|
+
await runtimes?.close().catch(() => undefined);
|
|
105
|
+
await control?.close().catch(() => undefined);
|
|
106
|
+
settleWait?.();
|
|
107
|
+
})();
|
|
108
|
+
return await closing;
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const reply = (value: unknown): GatewayControlResponse => ({ ok: true, value });
|
|
112
|
+
control = await startGatewayControlSocket({
|
|
113
|
+
socketPath: state.controlSocket,
|
|
114
|
+
handle(request) {
|
|
115
|
+
if (request.action === "health") return reply(descriptor ?? { state: "starting", gatewayInstanceRef });
|
|
116
|
+
if (request.action === "issue-launch-url") {
|
|
117
|
+
if (!loopback) return { ok: false, error: "gateway-starting" };
|
|
118
|
+
return reply({ launchUrl: loopback.issueLaunchUrl(), gatewayInstanceRef });
|
|
119
|
+
}
|
|
120
|
+
setImmediate(() => { void close(); });
|
|
121
|
+
return reply({ stopping: true, gatewayInstanceRef });
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
try {
|
|
126
|
+
const host = await loadPinnedPiHost(options.expectedPiVersion);
|
|
127
|
+
const inspectionModels = await host.ModelRuntime.create({
|
|
128
|
+
authPath: path.join(state.agentDir, "auth.json"),
|
|
129
|
+
modelsPath: path.join(state.agentDir, "models.json"),
|
|
130
|
+
allowModelNetwork: false
|
|
131
|
+
});
|
|
132
|
+
const providerAuth = new ProviderAuthBroker(inspectionModels);
|
|
133
|
+
mcpAuth = new McpAuthBroker(state.agentDir);
|
|
134
|
+
const leases = new SessionLeaseStore(state.root, key);
|
|
135
|
+
const events = new GatewayEventStore();
|
|
136
|
+
runtimes = new SessionRuntimeSupervisor({
|
|
137
|
+
gatewayInstanceRef, key, leases, listSessions: () => host.SessionManager.listAll(),
|
|
138
|
+
host, agentDir: state.agentDir, packageRoot: options.packageRoot, modelRuntime: inspectionModels, events,
|
|
139
|
+
resolveProject: (projectRef) => projects.resolve(projectRef)
|
|
140
|
+
});
|
|
141
|
+
const readCatalog = () => buildSessionCatalog({
|
|
142
|
+
gatewayInstanceRef,
|
|
143
|
+
key,
|
|
144
|
+
listSessions: () => runtimes!.listSessions(),
|
|
145
|
+
readMetadata: () => metadata.read(),
|
|
146
|
+
readOwnership: (sessionRef) => runtimes!.ownership(sessionRef),
|
|
147
|
+
readSessionOptions: (info) => {
|
|
148
|
+
try {
|
|
149
|
+
const context = host.SessionManager.open(info.path).buildSessionContext();
|
|
150
|
+
const model = context.model ? inspectionModels.getModel(context.model.provider, context.model.modelId) : null;
|
|
151
|
+
const thinking = ["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(String(context.thinkingLevel))
|
|
152
|
+
? context.thinkingLevel : "unknown";
|
|
153
|
+
return { modelLabel: model ? safeModelLabel(model.name ?? model.id ?? context.model?.modelId) : null,
|
|
154
|
+
thinkingLevel: thinking };
|
|
155
|
+
} catch { return { modelLabel: null, thinkingLevel: "unknown" }; }
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
runtimes.setProjectionReader(async (sessionRef) => {
|
|
159
|
+
const catalog = await readCatalog(), session = catalog.sessions.find((item) => item.sessionRef === sessionRef);
|
|
160
|
+
if (catalog.state !== "ready" || !session) throw new Error("session-projection-unavailable");
|
|
161
|
+
return { sessionRevision: session.sessionRevision, liveState: session.liveState };
|
|
162
|
+
});
|
|
163
|
+
const commands = new SessionCommandController({ catalog: readCatalog, runtimes, metadata,
|
|
164
|
+
store: new SessionCommandStore(state.root, key), events });
|
|
165
|
+
const protocol = new GatewayProtocolService({ capabilities: () => capabilities(gatewayInstanceRef, true), catalog: readCatalog,
|
|
166
|
+
events, command: commands });
|
|
167
|
+
const inspections = new SessionInspectionRegistry({ gatewayInstanceRef, host, key, packageRoot: options.packageRoot,
|
|
168
|
+
models: inspectionModels, projects, mcpAuth });
|
|
169
|
+
loopback = await startLoopbackServer({
|
|
170
|
+
staticRoot,
|
|
171
|
+
mode: "gateway",
|
|
172
|
+
readCapabilities: () => capabilities(gatewayInstanceRef, true),
|
|
173
|
+
readSessionCatalog: readCatalog,
|
|
174
|
+
readSessionCreationOptions: () => inspections.creationOptions(),
|
|
175
|
+
readSessionModel: (sessionRef) => inspections.provider(sessionRef),
|
|
176
|
+
readSessionConnections: (sessionRef) => inspections.connections(sessionRef),
|
|
177
|
+
executeSessionConnection: (command) => inspections.executeConnectionCommand(command),
|
|
178
|
+
executeApproval: (approvalRef, decision) => runtimes!.decideApproval(approvalRef, decision),
|
|
179
|
+
readMcpAuthJob: (jobRef) => mcpAuth!.read(jobRef),
|
|
180
|
+
cancelMcpAuthJob: (jobRef) => mcpAuth!.cancel(jobRef),
|
|
181
|
+
readProviderAuthCatalog: () => providerAuth.catalog(),
|
|
182
|
+
readProviderAuthJob: (jobRef) => providerAuth.read(jobRef),
|
|
183
|
+
executeProviderAuth: (command) => {
|
|
184
|
+
const action = command && typeof command === "object" && !Array.isArray(command) ? (command as Record<string, unknown>).action : null;
|
|
185
|
+
if (action === "provider-auth.start") return providerAuth.start(command);
|
|
186
|
+
if (action === "provider-auth.respond") return providerAuth.respond(command);
|
|
187
|
+
if (action === "provider-auth.cancel") return providerAuth.cancel(command);
|
|
188
|
+
throw new Error("provider-auth-command-invalid");
|
|
189
|
+
},
|
|
190
|
+
executeProjectImport: async () => {
|
|
191
|
+
const imported = await pickNativeProjectFolders();
|
|
192
|
+
const registered = imported.map((folder) => projects.register(folder));
|
|
193
|
+
const project = registered[0]!;
|
|
194
|
+
events.publish("catalog.changed", { reasonCode: "project-imported" });
|
|
195
|
+
return { schemaVersion: 1, version: "piagent-project-import-result-v1", importedAt: new Date().toISOString(), project, projects: registered };
|
|
196
|
+
},
|
|
197
|
+
gatewayProtocol: protocol
|
|
198
|
+
});
|
|
199
|
+
descriptor = {
|
|
200
|
+
version: "piagent-gateway-descriptor-v1",
|
|
201
|
+
gatewayInstanceRef,
|
|
202
|
+
pid: process.pid,
|
|
203
|
+
startedAt: new Date().toISOString(),
|
|
204
|
+
origin: loopback.origin,
|
|
205
|
+
controlSocket: state.controlSocket,
|
|
206
|
+
profileRef: profileRef(state, key)
|
|
207
|
+
};
|
|
208
|
+
writeGatewayDescriptor(state, descriptor);
|
|
209
|
+
} catch (error) {
|
|
210
|
+
await close();
|
|
211
|
+
throw error;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return { descriptor, wait: () => waited, close };
|
|
215
|
+
}
|