@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,239 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
import { readContextTelemetry } from "../../piagent-core/extensions/context-engine.js";
|
|
5
|
+
import { activeSessionTask } from "../../piagent-core/extensions/task-state.js";
|
|
6
|
+
import { runtimeConnectionDefinitions, runtimeProtectedPaths } from "../../piagent-core/runtime/inspection/project-runtime-inspection.ts";
|
|
7
|
+
import { setRuntimeMcpEnabled } from "../../piagent-core/runtime/inspection/mcp-control.ts";
|
|
8
|
+
import { webUiModelRef } from "../../piagent-core/runtime/inspection/webui-snapshot.ts";
|
|
9
|
+
import { redactSensitiveText } from "../../piagent-core/security/sensitive-data.js";
|
|
10
|
+
import { piApprovalBroker } from "../../piagent-core/runtime/inspection/approval-broker.ts";
|
|
11
|
+
import { CoreInspectionProvider } from "../server/core-inspection-provider.ts";
|
|
12
|
+
import { ReadModelNotFound, type WebUiReadModelProvider } from "../server/read-model-provider.ts";
|
|
13
|
+
import { projectRefForCwd, sessionRefForPath, type PiSessionInfo } from "./session-catalog.ts";
|
|
14
|
+
import { nativeProjectPickerAvailable } from "./native-project-picker.ts";
|
|
15
|
+
import type { McpAuthBroker } from "./mcp-auth-broker.ts";
|
|
16
|
+
|
|
17
|
+
type PiHost = {
|
|
18
|
+
SessionManager: {
|
|
19
|
+
listAll(): Promise<PiSessionInfo[]>;
|
|
20
|
+
open(file: string): {
|
|
21
|
+
getBranch(): unknown[];
|
|
22
|
+
buildSessionContext(): { model: { provider: string; modelId: string } | null; thinkingLevel: string; messages: unknown[] };
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
calculateContextTokens(usage: unknown): number;
|
|
26
|
+
estimateTokens(message: unknown): number;
|
|
27
|
+
getLatestCompactionEntry(entries: unknown[]): unknown | null;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
type ModelRuntime = {
|
|
31
|
+
getModel(provider: string, modelId: string): Record<string, unknown> | undefined;
|
|
32
|
+
getAvailableSnapshot(): readonly Record<string, unknown>[];
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
type ProjectSource = { list(): Array<{ projectRef: string; placeRef: string; label: string }> };
|
|
36
|
+
|
|
37
|
+
const CACHE_LIMIT = 32;
|
|
38
|
+
const PUBLIC_MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/;
|
|
39
|
+
const EMPTY_REPLAY = {
|
|
40
|
+
state: "current" as const,
|
|
41
|
+
events: [],
|
|
42
|
+
nextCursor: "inspection-start",
|
|
43
|
+
latestCursor: "inspection-start",
|
|
44
|
+
reasonCode: null
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
function inspectionRuntimeRef(gatewayInstanceRef: string, sessionRef: string): string {
|
|
48
|
+
return `runtime.${createHash("sha256").update(`${gatewayInstanceRef}\0${sessionRef}`).digest("hex")}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function safeRead<T>(read: () => T, fallback: T): T {
|
|
52
|
+
try { return read(); } catch { return fallback; }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function safeName(value: unknown): string {
|
|
56
|
+
return redactSensitiveText(String(value ?? "")).text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 120)
|
|
57
|
+
|| "Unnamed connection";
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function safeModelId(value: unknown): string | null {
|
|
61
|
+
if (typeof value !== "string" || !PUBLIC_MODEL_ID.test(value)) return null;
|
|
62
|
+
return redactSensitiveText(value).redacted ? null : value;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function persistedContextUsage(host: PiHost, entries: unknown[], messages: unknown[], model: Record<string, unknown> | undefined) {
|
|
66
|
+
const contextWindow = Number(model?.contextWindow);
|
|
67
|
+
if (!Number.isFinite(contextWindow) || contextWindow <= 0) return undefined;
|
|
68
|
+
const latestCompaction = host.getLatestCompactionEntry(entries);
|
|
69
|
+
if (latestCompaction) {
|
|
70
|
+
const boundary = entries.lastIndexOf(latestCompaction);
|
|
71
|
+
let hasPostCompactionUsage = false;
|
|
72
|
+
for (let index = entries.length - 1; index > boundary; index -= 1) {
|
|
73
|
+
const entry = entries[index] as { type?: unknown; message?: { role?: unknown; stopReason?: unknown; usage?: unknown } } | undefined;
|
|
74
|
+
const message = entry?.type === "message" ? entry.message : undefined;
|
|
75
|
+
if (message?.role === "assistant" && message.usage && message.stopReason !== "aborted" && message.stopReason !== "error"
|
|
76
|
+
&& host.calculateContextTokens(message.usage) > 0) {
|
|
77
|
+
hasPostCompactionUsage = true;
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (!hasPostCompactionUsage) return { tokens: null, contextWindow, percent: null };
|
|
82
|
+
}
|
|
83
|
+
let lastUsageIndex = -1, tokens = 0;
|
|
84
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
85
|
+
const message = messages[index] as { role?: unknown; stopReason?: unknown; usage?: unknown } | undefined;
|
|
86
|
+
if (message?.role !== "assistant" || !message.usage || message.stopReason === "aborted" || message.stopReason === "error") continue;
|
|
87
|
+
const measured = host.calculateContextTokens(message.usage);
|
|
88
|
+
if (measured > 0) { tokens = measured; lastUsageIndex = index; break; }
|
|
89
|
+
}
|
|
90
|
+
for (let index = lastUsageIndex + 1; index < messages.length; index += 1) tokens += host.estimateTokens(messages[index]);
|
|
91
|
+
if (!Number.isFinite(tokens) || tokens < 0) return undefined;
|
|
92
|
+
return { tokens, contextWindow, percent: tokens / contextWindow * 100 };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export class SessionInspectionRegistry {
|
|
96
|
+
readonly #gatewayInstanceRef: string;
|
|
97
|
+
readonly #host: PiHost;
|
|
98
|
+
readonly #key: Buffer;
|
|
99
|
+
readonly #packageRoot: string;
|
|
100
|
+
readonly #models?: ModelRuntime;
|
|
101
|
+
readonly #projects?: ProjectSource;
|
|
102
|
+
readonly #mcpAuth?: McpAuthBroker;
|
|
103
|
+
readonly #providers = new Map<string, { modifiedAt: string; provider: CoreInspectionProvider }>();
|
|
104
|
+
|
|
105
|
+
constructor(options: { gatewayInstanceRef: string; host: PiHost; key: Buffer; packageRoot: string; models?: ModelRuntime; projects?: ProjectSource;
|
|
106
|
+
mcpAuth?: McpAuthBroker }) {
|
|
107
|
+
this.#gatewayInstanceRef = options.gatewayInstanceRef;
|
|
108
|
+
this.#host = options.host;
|
|
109
|
+
this.#key = options.key;
|
|
110
|
+
this.#packageRoot = options.packageRoot;
|
|
111
|
+
this.#models = options.models;
|
|
112
|
+
this.#projects = options.projects;
|
|
113
|
+
this.#mcpAuth = options.mcpAuth;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
#connectionRef(server: { scope: string; origin: string; name: string }): string {
|
|
117
|
+
return `mcp.${createHash("sha256").update(`${server.scope}\0${server.origin}\0${server.name}`).digest("hex")}`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async #sessionInfo(sessionRef: string): Promise<PiSessionInfo> {
|
|
121
|
+
const sessions = await this.#host.SessionManager.listAll();
|
|
122
|
+
const found = sessions.filter((candidate) => sessionRefForPath(this.#key, candidate.path) === sessionRef);
|
|
123
|
+
if (found.length !== 1) throw new ReadModelNotFound();
|
|
124
|
+
return found[0]!;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async connections(sessionRef: string): Promise<unknown> {
|
|
128
|
+
const info = await this.#sessionInfo(sessionRef);
|
|
129
|
+
const definitions = safeRead(() => runtimeConnectionDefinitions(info.cwd), { servers: [], unreadableLayerCount: 1 });
|
|
130
|
+
const servers = await Promise.all(definitions.servers.slice(0, 100).map(async (server) => {
|
|
131
|
+
const auth = await this.#mcpAuth?.describe(info.cwd, server.name) ?? { oauthSupported: false as const, authState: "unavailable" as const };
|
|
132
|
+
return { connectionRef: this.#connectionRef(server), name: safeName(server.name), kind: "mcp" as const, scope: server.scope,
|
|
133
|
+
origin: safeName(server.origin), transport: typeof server.entry.url === "string" ? "http" as const
|
|
134
|
+
: typeof server.entry.command === "string" ? "stdio" as const : "unknown" as const,
|
|
135
|
+
state: server.entry.enabled === false ? "disabled" as const : auth.authState === "connected" ? "connected" as const : "configured" as const,
|
|
136
|
+
requiresApproval: server.requiresApproval, oauthSupported: auth.oauthSupported, authState: auth.authState,
|
|
137
|
+
toggleSupported: !server.origin.startsWith("import:") };
|
|
138
|
+
}));
|
|
139
|
+
return {
|
|
140
|
+
schemaVersion: 1,
|
|
141
|
+
version: "piagent-session-connections-v1",
|
|
142
|
+
generatedAt: new Date().toISOString(),
|
|
143
|
+
sessionRef,
|
|
144
|
+
state: definitions.unreadableLayerCount ? "degraded" : "ready",
|
|
145
|
+
summary: { configured: servers.length, connected: null, approvalRequired: servers.filter((server) => server.requiresApproval).length },
|
|
146
|
+
connections: servers,
|
|
147
|
+
truncated: servers.length >= 100,
|
|
148
|
+
reasonCode: definitions.unreadableLayerCount ? "one-or-more-connection-layers-unreadable" : null
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async executeConnectionCommand(input: unknown): Promise<unknown> {
|
|
153
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("mcp-command-invalid");
|
|
154
|
+
const command = input as Record<string, unknown>, keys = Object.keys(command);
|
|
155
|
+
if (!keys.every((key) => ["action", "sessionRef", "connectionRef"].includes(key)) || keys.length !== 3
|
|
156
|
+
|| !["mcp.enable", "mcp.disable", "mcp.oauth"].includes(String(command.action))
|
|
157
|
+
|| typeof command.sessionRef !== "string" || typeof command.connectionRef !== "string") throw new Error("mcp-command-invalid");
|
|
158
|
+
const info = await this.#sessionInfo(command.sessionRef), definitions = safeRead(() => runtimeConnectionDefinitions(info.cwd), { servers: [], unreadableLayerCount: 1 });
|
|
159
|
+
const matches = definitions.servers.filter((server) => this.#connectionRef(server) === command.connectionRef);
|
|
160
|
+
if (matches.length !== 1) throw new Error("mcp-connection-not-found");
|
|
161
|
+
const server = matches[0]!;
|
|
162
|
+
if (command.action === "mcp.oauth") {
|
|
163
|
+
if (!this.#mcpAuth) throw new Error("mcp-oauth-unavailable");
|
|
164
|
+
return await this.#mcpAuth.start({ sessionRef: command.sessionRef, connectionRef: command.connectionRef, cwd: info.cwd, name: server.name });
|
|
165
|
+
}
|
|
166
|
+
setRuntimeMcpEnabled({ projectPath: info.cwd, name: server.name, scope: server.scope, enabled: command.action === "mcp.enable" });
|
|
167
|
+
return await this.connections(command.sessionRef);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async creationOptions(): Promise<unknown> {
|
|
171
|
+
const sessions = await this.#host.SessionManager.listAll();
|
|
172
|
+
const projects = new Map<string, { projectRef: string; placeRef: string; label: string }>();
|
|
173
|
+
for (const info of sessions) {
|
|
174
|
+
if (!info.cwd) continue;
|
|
175
|
+
const projectRef = projectRefForCwd(this.#key, info.cwd);
|
|
176
|
+
if (!projects.has(projectRef)) projects.set(projectRef, { projectRef, placeRef: projectRef,
|
|
177
|
+
label: safeName(path.basename(info.cwd) || "Project") });
|
|
178
|
+
}
|
|
179
|
+
for (const project of safeRead(() => this.#projects?.list() ?? [], [])) {
|
|
180
|
+
if (!projects.has(project.projectRef)) projects.set(project.projectRef, project);
|
|
181
|
+
}
|
|
182
|
+
const models = (this.#models?.getAvailableSnapshot() ?? []).slice(0, 300).flatMap((value) => {
|
|
183
|
+
const provider = safeModelId(value.provider);
|
|
184
|
+
const modelId = safeModelId(value.id);
|
|
185
|
+
if (!provider || !modelId || typeof value.reasoning !== "boolean") return [];
|
|
186
|
+
const mapping = value.thinkingLevelMap && typeof value.thinkingLevelMap === "object"
|
|
187
|
+
? value.thinkingLevelMap as Record<string, unknown> : {};
|
|
188
|
+
const thinkingLevels = value.reasoning ? ["off", "minimal", "low", "medium", "high", "xhigh", "max"]
|
|
189
|
+
.filter((level) => mapping[level] !== null && !(["xhigh", "max"].includes(level) && mapping[level] === undefined)) : ["off"];
|
|
190
|
+
return [{ modelRef: webUiModelRef(provider, modelId), provider, modelId, displayName: safeName(value.name ?? modelId),
|
|
191
|
+
reasoning: value.reasoning, thinkingLevels }];
|
|
192
|
+
});
|
|
193
|
+
return { schemaVersion: 1, version: "piagent-session-creation-options-v1", generatedAt: new Date().toISOString(),
|
|
194
|
+
projects: [...projects.values()].slice(0, 200), models,
|
|
195
|
+
projectImport: nativeProjectPickerAvailable() ? { status: "available", reasonCode: null }
|
|
196
|
+
: { status: "unavailable", reasonCode: "native-project-picker-unavailable" },
|
|
197
|
+
reasonCode: projects.size ? null : "no-known-project" };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async provider(sessionRef: string): Promise<WebUiReadModelProvider> {
|
|
201
|
+
const info = await this.#sessionInfo(sessionRef);
|
|
202
|
+
const modifiedAt = info.modified.toISOString();
|
|
203
|
+
const cached = this.#providers.get(sessionRef);
|
|
204
|
+
if (cached?.modifiedAt === modifiedAt) return cached.provider;
|
|
205
|
+
|
|
206
|
+
let manager: ReturnType<PiHost["SessionManager"]["open"]>;
|
|
207
|
+
try { manager = this.#host.SessionManager.open(info.path); }
|
|
208
|
+
catch { throw new ReadModelNotFound(); }
|
|
209
|
+
const context = safeRead(() => manager.buildSessionContext(), { model: null, thinkingLevel: "unknown", messages: [] });
|
|
210
|
+
const model = context.model ? this.#models?.getModel(context.model.provider, context.model.modelId) : undefined;
|
|
211
|
+
const entries = safeRead(() => manager.getBranch(), []);
|
|
212
|
+
const contextUsage = safeRead(() => persistedContextUsage(this.#host, entries, context.messages, model), undefined);
|
|
213
|
+
const eventStore = {
|
|
214
|
+
retention: () => ({ eventRetentionCount: 0, eventRetentionSeconds: 0 }),
|
|
215
|
+
currentCursor: () => null,
|
|
216
|
+
resyncRequired: () => false,
|
|
217
|
+
replay: () => EMPTY_REPLAY
|
|
218
|
+
};
|
|
219
|
+
const provider = new CoreInspectionProvider({
|
|
220
|
+
cwd: info.cwd,
|
|
221
|
+
sessionId: info.id,
|
|
222
|
+
runtimeInstanceId: inspectionRuntimeRef(this.#gatewayInstanceRef, sessionRef),
|
|
223
|
+
eventStore,
|
|
224
|
+
task: () => safeRead(() => activeSessionTask(info.cwd, info.id), undefined),
|
|
225
|
+
activityEvents: () => safeRead(() => readContextTelemetry(info.cwd, { limit: 5_000 }), []),
|
|
226
|
+
sessionEntries: () => entries,
|
|
227
|
+
protectedPaths: () => runtimeProtectedPaths(this.#packageRoot, info.cwd),
|
|
228
|
+
contextUsage: () => contextUsage,
|
|
229
|
+
model: () => model,
|
|
230
|
+
thinkingLevel: () => context.thinkingLevel,
|
|
231
|
+
approvalProjection: () => piApprovalBroker.projection(info.cwd, info.id),
|
|
232
|
+
approvalDetail: (approvalRef) => piApprovalBroker.detail(info.cwd, info.id, approvalRef)
|
|
233
|
+
});
|
|
234
|
+
this.#providers.delete(sessionRef);
|
|
235
|
+
this.#providers.set(sessionRef, { modifiedAt, provider });
|
|
236
|
+
while (this.#providers.size > CACHE_LIMIT) this.#providers.delete(this.#providers.keys().next().value as string);
|
|
237
|
+
return provider;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "../ownership/session-lease-store.ts";
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { createHmac } 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
|
+
|
|
7
|
+
const FILE_LIMIT = 4 * 1024 * 1024;
|
|
8
|
+
const RECORD_LIMIT = 8 * 1024;
|
|
9
|
+
const ENTRY_LIMIT = 10_000;
|
|
10
|
+
const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;
|
|
11
|
+
|
|
12
|
+
export type SessionMetadata = {
|
|
13
|
+
pinned: boolean;
|
|
14
|
+
archived: boolean;
|
|
15
|
+
unread: boolean;
|
|
16
|
+
projectGroup: string | null;
|
|
17
|
+
revision: string;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
type MetadataRecord = {
|
|
21
|
+
version: "piagent-session-metadata-v1";
|
|
22
|
+
sequence: number;
|
|
23
|
+
recordedAt: string;
|
|
24
|
+
sessionRef: string;
|
|
25
|
+
previousRevision: string | null;
|
|
26
|
+
pinned: boolean;
|
|
27
|
+
archived: boolean;
|
|
28
|
+
unread: boolean;
|
|
29
|
+
projectGroup: string | null;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export type MetadataSnapshot = {
|
|
33
|
+
state: "ready" | "unavailable";
|
|
34
|
+
revision: string | null;
|
|
35
|
+
sessions: ReadonlyMap<string, SessionMetadata>;
|
|
36
|
+
reasonCode: string | null;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function digest(key: Buffer, namespace: string, value: unknown): string {
|
|
40
|
+
return `${namespace}_${createHmac("sha256", key).update(JSON.stringify(value)).digest("hex")}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function exactTimestamp(value: unknown): value is string {
|
|
44
|
+
return typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)
|
|
45
|
+
&& Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function safeGroup(value: unknown): string | null {
|
|
49
|
+
if (value === null || value === undefined) return null;
|
|
50
|
+
if (typeof value !== "string") throw new Error("session-metadata-group-invalid");
|
|
51
|
+
const text = redactSensitiveText(value).text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
|
|
52
|
+
if (!text || text.length > 120) throw new Error("session-metadata-group-invalid");
|
|
53
|
+
return text;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function validRecord(value: unknown): value is MetadataRecord {
|
|
57
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
58
|
+
const record = value as Partial<MetadataRecord>;
|
|
59
|
+
return Object.keys(record).every((key) => ["version", "sequence", "recordedAt", "sessionRef", "previousRevision",
|
|
60
|
+
"pinned", "archived", "unread", "projectGroup"].includes(key))
|
|
61
|
+
&& record.version === "piagent-session-metadata-v1"
|
|
62
|
+
&& Number.isSafeInteger(record.sequence) && Number(record.sequence) > 0
|
|
63
|
+
&& exactTimestamp(record.recordedAt) && typeof record.sessionRef === "string" && REF.test(record.sessionRef)
|
|
64
|
+
&& (record.previousRevision === null || typeof record.previousRevision === "string" && REF.test(record.previousRevision))
|
|
65
|
+
&& typeof record.pinned === "boolean" && typeof record.archived === "boolean" && typeof record.unread === "boolean"
|
|
66
|
+
&& (record.projectGroup === null || typeof record.projectGroup === "string" && record.projectGroup.length > 0
|
|
67
|
+
&& record.projectGroup.length <= 120 && !/[\u0000-\u001f\u007f]/.test(record.projectGroup));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export class SessionMetadataStore {
|
|
71
|
+
readonly directory: string;
|
|
72
|
+
readonly file: string;
|
|
73
|
+
readonly #key: Buffer;
|
|
74
|
+
|
|
75
|
+
constructor(root: string, key: Buffer) {
|
|
76
|
+
this.directory = path.join(root, "sessions");
|
|
77
|
+
this.file = path.join(this.directory, "index.jsonl");
|
|
78
|
+
this.#key = key;
|
|
79
|
+
fs.mkdirSync(this.directory, { recursive: true, mode: 0o700 });
|
|
80
|
+
const stat = fs.lstatSync(this.directory);
|
|
81
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()
|
|
82
|
+
|| (typeof process.getuid === "function" && stat.uid !== process.getuid())) throw new Error("session-metadata-root-invalid");
|
|
83
|
+
fs.chmodSync(this.directory, 0o700);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
#readRecords(): MetadataRecord[] {
|
|
87
|
+
let stat: fs.Stats;
|
|
88
|
+
try { stat = fs.lstatSync(this.file); }
|
|
89
|
+
catch { return []; }
|
|
90
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > FILE_LIMIT) throw new Error("session-metadata-file-invalid");
|
|
91
|
+
const descriptor = fs.openSync(this.file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
|
|
92
|
+
try {
|
|
93
|
+
const opened = fs.fstatSync(descriptor);
|
|
94
|
+
if (opened.dev !== stat.dev || opened.ino !== stat.ino || opened.size !== stat.size) throw new Error("session-metadata-file-race");
|
|
95
|
+
const text = fs.readFileSync(descriptor, "utf8");
|
|
96
|
+
const lines = text ? text.split("\n") : [];
|
|
97
|
+
if (lines.at(-1) === "") lines.pop();
|
|
98
|
+
if (lines.length > ENTRY_LIMIT) throw new Error("session-metadata-entry-limit");
|
|
99
|
+
return lines.map((line, index) => {
|
|
100
|
+
if (!line || Buffer.byteLength(line) > RECORD_LIMIT) throw new Error("session-metadata-record-limit");
|
|
101
|
+
let value: unknown;
|
|
102
|
+
try { value = JSON.parse(line); } catch { throw new Error("session-metadata-record-invalid"); }
|
|
103
|
+
if (!validRecord(value) || value.sequence !== index + 1) throw new Error("session-metadata-record-invalid");
|
|
104
|
+
return value;
|
|
105
|
+
});
|
|
106
|
+
} finally { fs.closeSync(descriptor); }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
read(): MetadataSnapshot {
|
|
110
|
+
try {
|
|
111
|
+
const records = this.#readRecords();
|
|
112
|
+
const sessions = new Map<string, SessionMetadata>();
|
|
113
|
+
for (const record of records) {
|
|
114
|
+
const prior = sessions.get(record.sessionRef);
|
|
115
|
+
if (record.previousRevision !== (prior?.revision ?? null)) throw new Error("session-metadata-chain-invalid");
|
|
116
|
+
sessions.set(record.sessionRef, {
|
|
117
|
+
pinned: record.pinned, archived: record.archived, unread: record.unread, projectGroup: record.projectGroup,
|
|
118
|
+
revision: digest(this.#key, "metadata-revision", record)
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
return { state: "ready", revision: digest(this.#key, "metadata-store", records), sessions, reasonCode: null };
|
|
122
|
+
} catch {
|
|
123
|
+
return { state: "unavailable", revision: null, sessions: new Map(), reasonCode: "metadata-overlay-unavailable" };
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
update(sessionRef: string, expectedRevision: string | null, patch: Partial<Pick<SessionMetadata, "pinned" | "archived" | "unread" | "projectGroup">>, now = new Date()): SessionMetadata {
|
|
128
|
+
if (!REF.test(sessionRef)) throw new Error("session-metadata-ref-invalid");
|
|
129
|
+
const snapshot = this.read();
|
|
130
|
+
if (snapshot.state !== "ready") throw new Error(snapshot.reasonCode ?? "session-metadata-unavailable");
|
|
131
|
+
const current = snapshot.sessions.get(sessionRef);
|
|
132
|
+
if ((current?.revision ?? null) !== expectedRevision) throw new Error("session-metadata-stale-revision");
|
|
133
|
+
if (!Number.isFinite(now.getTime())) throw new Error("session-metadata-time-invalid");
|
|
134
|
+
const record: MetadataRecord = {
|
|
135
|
+
version: "piagent-session-metadata-v1", sequence: this.#readRecords().length + 1, recordedAt: now.toISOString(), sessionRef,
|
|
136
|
+
previousRevision: current?.revision ?? null, pinned: patch.pinned ?? current?.pinned ?? false,
|
|
137
|
+
archived: patch.archived ?? current?.archived ?? false, unread: patch.unread ?? current?.unread ?? false,
|
|
138
|
+
projectGroup: "projectGroup" in patch ? safeGroup(patch.projectGroup) : current?.projectGroup ?? null
|
|
139
|
+
};
|
|
140
|
+
const body = Buffer.from(`${JSON.stringify(record)}\n`);
|
|
141
|
+
if (body.length > RECORD_LIMIT) throw new Error("session-metadata-record-limit");
|
|
142
|
+
let stat: fs.Stats | null = null;
|
|
143
|
+
try { stat = fs.lstatSync(this.file); } catch { /* first record */ }
|
|
144
|
+
if (stat && (!stat.isFile() || stat.isSymbolicLink() || stat.size + body.length > FILE_LIMIT)) throw new Error("session-metadata-file-invalid");
|
|
145
|
+
const descriptor = fs.openSync(this.file, fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT
|
|
146
|
+
| (fs.constants.O_NOFOLLOW ?? 0), 0o600);
|
|
147
|
+
try { fs.writeFileSync(descriptor, body); fs.fsyncSync(descriptor); }
|
|
148
|
+
finally { fs.closeSync(descriptor); }
|
|
149
|
+
fs.chmodSync(this.file, 0o600);
|
|
150
|
+
return this.read().sessions.get(sessionRef)!;
|
|
151
|
+
}
|
|
152
|
+
}
|