@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,88 @@
|
|
|
1
|
+
import { createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import type { IncomingMessage } from "node:http";
|
|
3
|
+
|
|
4
|
+
const SESSION_COOKIE = "piagent_webui_session";
|
|
5
|
+
|
|
6
|
+
function secret(): string { return randomBytes(32).toString("base64url"); }
|
|
7
|
+
function equal(left: string, right: string): boolean {
|
|
8
|
+
const a = Buffer.from(left), b = Buffer.from(right);
|
|
9
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
10
|
+
}
|
|
11
|
+
function cookie(request: IncomingMessage, name: string): string | null {
|
|
12
|
+
for (const part of String(request.headers.cookie ?? "").split(";")) {
|
|
13
|
+
const index = part.indexOf("=");
|
|
14
|
+
if (index > 0 && part.slice(0, index).trim() === name) return part.slice(index + 1).trim();
|
|
15
|
+
}
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type BrowserSession = { id: string; csrf: string; expiresAt: number };
|
|
20
|
+
|
|
21
|
+
export class SessionAuthority {
|
|
22
|
+
readonly #initialBootstrap: string;
|
|
23
|
+
readonly #bootstrapTtlMs: number;
|
|
24
|
+
readonly #sessionTtlMs: number;
|
|
25
|
+
readonly #cookieSigningKey = randomBytes(32);
|
|
26
|
+
#bootstraps = new Map<string, number>();
|
|
27
|
+
#sessions = new Map<string, BrowserSession>();
|
|
28
|
+
|
|
29
|
+
constructor(options: { now?: number; bootstrapTtlMs?: number; sessionTtlMs?: number } = {}) {
|
|
30
|
+
this.#bootstrapTtlMs = options.bootstrapTtlMs ?? 60_000;
|
|
31
|
+
this.#sessionTtlMs = options.sessionTtlMs ?? 8 * 60 * 60_000;
|
|
32
|
+
this.#initialBootstrap = this.issueBootstrapCapability(options.now ?? Date.now());
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
get bootstrapCapability(): string { return this.#initialBootstrap; }
|
|
36
|
+
|
|
37
|
+
issueBootstrapCapability(now = Date.now()): string {
|
|
38
|
+
for (const [value, createdAt] of this.#bootstraps) {
|
|
39
|
+
if (now > createdAt + this.#bootstrapTtlMs) this.#bootstraps.delete(value);
|
|
40
|
+
}
|
|
41
|
+
while (this.#bootstraps.size >= 8) this.#bootstraps.delete(this.#bootstraps.keys().next().value as string);
|
|
42
|
+
const value = secret();
|
|
43
|
+
this.#bootstraps.set(value, now);
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
exchange(candidate: string, now = Date.now()): BrowserSession | null {
|
|
48
|
+
const match = [...this.#bootstraps].find(([value, createdAt]) => now <= createdAt + this.#bootstrapTtlMs && equal(candidate, value));
|
|
49
|
+
if (!match) return null;
|
|
50
|
+
this.#bootstraps.delete(match[0]);
|
|
51
|
+
const session = { id: randomUUID(), csrf: secret(), expiresAt: now + this.#sessionTtlMs };
|
|
52
|
+
this.#sessions.set(session.id, session);
|
|
53
|
+
return session;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
authenticate(request: IncomingMessage, now = Date.now()): BrowserSession | null {
|
|
57
|
+
const value = cookie(request, SESSION_COOKIE);
|
|
58
|
+
if (!value) return null;
|
|
59
|
+
const separator = value.lastIndexOf(".");
|
|
60
|
+
if (separator < 1) return null;
|
|
61
|
+
const id = value.slice(0, separator), signature = value.slice(separator + 1);
|
|
62
|
+
if (!equal(signature, this.#cookieSignature(id))) return null;
|
|
63
|
+
const session = this.#sessions.get(id);
|
|
64
|
+
if (!session || session.expiresAt < now || !equal(id, session.id)) {
|
|
65
|
+
if (session) this.#sessions.delete(id);
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
return session;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
authorizeMutation(request: IncomingMessage, now = Date.now()): BrowserSession | null {
|
|
72
|
+
const session = this.authenticate(request, now);
|
|
73
|
+
const csrf = request.headers["x-piagent-csrf"];
|
|
74
|
+
return session && typeof csrf === "string" && equal(csrf, session.csrf) ? session : null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
cookieHeader(session: BrowserSession): string {
|
|
78
|
+
const seconds = Math.max(1, Math.floor((session.expiresAt - Date.now()) / 1000));
|
|
79
|
+
const token = `${session.id}.${this.#cookieSignature(session.id)}`;
|
|
80
|
+
return `${SESSION_COOKIE}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${seconds}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
#cookieSignature(id: string): string {
|
|
84
|
+
return createHmac("sha256", this.#cookieSigningKey).update(id).digest("base64url");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
invalidate(): void { this.#bootstraps.clear(); this.#sessions.clear(); }
|
|
88
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { timingSafeEqual } from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import net from "node:net";
|
|
4
|
+
|
|
5
|
+
import { IpcReadModelClient } from "./ipc-read-model-client.ts";
|
|
6
|
+
import { startLoopbackServer, type LoopbackServer } from "./loopback-server.ts";
|
|
7
|
+
|
|
8
|
+
type InitMessage = {
|
|
9
|
+
channel: "piagent-webui";
|
|
10
|
+
type: "init";
|
|
11
|
+
staticRoot: string;
|
|
12
|
+
controlSocket: string;
|
|
13
|
+
controlToken: string;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
function equal(left: string, right: string): boolean {
|
|
17
|
+
const a = Buffer.from(left), b = Buffer.from(right);
|
|
18
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function controlServer(socketPath: string, token: string, web: LoopbackServer): Promise<net.Server> {
|
|
22
|
+
try {
|
|
23
|
+
const stat = fs.lstatSync(socketPath);
|
|
24
|
+
if (!stat.isSocket()) throw new Error("webui-control-path-unsafe");
|
|
25
|
+
fs.unlinkSync(socketPath);
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
28
|
+
}
|
|
29
|
+
const server = net.createServer((socket) => {
|
|
30
|
+
let input = Buffer.alloc(0), settled = false;
|
|
31
|
+
socket.setTimeout(2_000, () => socket.destroy());
|
|
32
|
+
socket.on("data", (chunk) => {
|
|
33
|
+
if (settled) return;
|
|
34
|
+
input = Buffer.concat([input, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
|
|
35
|
+
if (input.length > 4_096) { settled = true; socket.end('{"ok":false,"error":"request-limit"}\n'); return; }
|
|
36
|
+
const newline = input.indexOf(10);
|
|
37
|
+
if (newline < 0) return;
|
|
38
|
+
settled = true;
|
|
39
|
+
try {
|
|
40
|
+
const value = JSON.parse(input.subarray(0, newline).toString("utf8"));
|
|
41
|
+
if (!value || value.action !== "launch" || typeof value.token !== "string" || !equal(value.token, token)) {
|
|
42
|
+
socket.end('{"ok":false,"error":"authority-rejected"}\n'); return;
|
|
43
|
+
}
|
|
44
|
+
socket.end(`${JSON.stringify({ ok: true, launchUrl: web.issueLaunchUrl() })}\n`);
|
|
45
|
+
} catch { socket.end('{"ok":false,"error":"invalid-request"}\n'); }
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
await new Promise<void>((resolve, reject) => {
|
|
49
|
+
server.once("error", reject);
|
|
50
|
+
server.listen(socketPath, resolve);
|
|
51
|
+
});
|
|
52
|
+
fs.chmodSync(socketPath, 0o600);
|
|
53
|
+
return server;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
let closing = false, web: LoopbackServer | undefined, control: net.Server | undefined, controlPath: string | undefined;
|
|
57
|
+
async function close(code = 0): Promise<void> {
|
|
58
|
+
if (closing) return;
|
|
59
|
+
closing = true;
|
|
60
|
+
await web?.close().catch(() => undefined);
|
|
61
|
+
await new Promise<void>((resolve) => control ? control.close(() => resolve()) : resolve());
|
|
62
|
+
if (controlPath) {
|
|
63
|
+
try { if (fs.lstatSync(controlPath).isSocket()) fs.unlinkSync(controlPath); } catch { /* already removed */ }
|
|
64
|
+
}
|
|
65
|
+
process.exit(code);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
process.once("message", (message: unknown) => { void (async () => {
|
|
69
|
+
const init = message as Partial<InitMessage>;
|
|
70
|
+
if (init.channel !== "piagent-webui" || init.type !== "init" || typeof init.staticRoot !== "string"
|
|
71
|
+
|| typeof init.controlSocket !== "string" || typeof init.controlToken !== "string") throw new Error("webui-sidecar-init-invalid");
|
|
72
|
+
const client = new IpcReadModelClient();
|
|
73
|
+
web = await startLoopbackServer({ staticRoot: init.staticRoot, readCapabilities: () => client.capabilities(), readModel: client,
|
|
74
|
+
executeControl: (command) => client.executeControl(command), executeAttachment: (command) => client.executeAttachment(command),
|
|
75
|
+
executeApproval: (approvalRef, decision) => client.executeApproval(approvalRef, decision) });
|
|
76
|
+
controlPath = init.controlSocket;
|
|
77
|
+
control = await controlServer(init.controlSocket, init.controlToken, web);
|
|
78
|
+
process.send?.({ channel: "piagent-webui", type: "ready", origin: web.origin, launchUrl: web.launchUrl });
|
|
79
|
+
})().catch((error) => {
|
|
80
|
+
process.send?.({ channel: "piagent-webui", type: "fatal", error: error instanceof Error ? error.message : "sidecar-start-failed" });
|
|
81
|
+
void close(1);
|
|
82
|
+
}); });
|
|
83
|
+
|
|
84
|
+
process.once("disconnect", () => { void close(0); });
|
|
85
|
+
process.once("SIGTERM", () => { void close(0); });
|
|
86
|
+
process.once("SIGINT", () => { void close(0); });
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
|
|
3
|
+
import type { StreamEvent, WebUiReadModelProvider } from "./read-model-provider.ts";
|
|
4
|
+
|
|
5
|
+
const CURSOR = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;
|
|
6
|
+
const MAX_EVENT_BYTES = 65_536;
|
|
7
|
+
const MAX_HANDOFF_EVENTS = 256;
|
|
8
|
+
|
|
9
|
+
function frame(event: string, value: unknown, cursor?: string): string | null {
|
|
10
|
+
let json: string;
|
|
11
|
+
try { json = JSON.stringify(value); } catch { return null; }
|
|
12
|
+
if (Buffer.byteLength(json) > MAX_EVENT_BYTES || (cursor && !CURSOR.test(cursor))) return null;
|
|
13
|
+
return `${cursor ? `id: ${cursor}\n` : ""}event: ${event}\ndata: ${json}\n\n`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export class SseHub {
|
|
17
|
+
readonly #provider: WebUiReadModelProvider;
|
|
18
|
+
readonly #clients = new Set<ServerResponse>();
|
|
19
|
+
readonly #maximumClients: number;
|
|
20
|
+
readonly #maximumReplayEvents: number;
|
|
21
|
+
|
|
22
|
+
constructor(provider: WebUiReadModelProvider, options: { maximumClients?: number; maximumReplayEvents?: number } = {}) {
|
|
23
|
+
this.#provider = provider;
|
|
24
|
+
this.#maximumClients = Math.max(1, Math.min(32, options.maximumClients ?? 8));
|
|
25
|
+
this.#maximumReplayEvents = Math.max(1, Math.min(10_000, options.maximumReplayEvents ?? 10_000));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async open(request: IncomingMessage, response: ServerResponse, after: string | null): Promise<void> {
|
|
29
|
+
if (this.#clients.size >= this.#maximumClients) {
|
|
30
|
+
response.statusCode = 503; response.end(JSON.stringify({ error: { code: "sse-client-limit" } })); return;
|
|
31
|
+
}
|
|
32
|
+
const buffered: StreamEvent[] = [];
|
|
33
|
+
let live = false, handoffOverflow = false;
|
|
34
|
+
const writeEvent = (event: StreamEvent): boolean => {
|
|
35
|
+
const encoded = frame("runtime-event", event.value, event.cursor);
|
|
36
|
+
if (!encoded) { response.end(frame("resync-required", { reasonCode: "event-payload-limit", latestCursor: event.cursor }) as string); return false; }
|
|
37
|
+
response.write(encoded); return true;
|
|
38
|
+
};
|
|
39
|
+
const unsubscribe = this.#provider.subscribe((event: StreamEvent) => {
|
|
40
|
+
if (live) { writeEvent(event); return; }
|
|
41
|
+
if (buffered.length >= MAX_HANDOFF_EVENTS) { handoffOverflow = true; return; }
|
|
42
|
+
buffered.push(event);
|
|
43
|
+
});
|
|
44
|
+
let replay;
|
|
45
|
+
try { replay = await this.#provider.replay(after, this.#maximumReplayEvents); }
|
|
46
|
+
catch (error) { unsubscribe(); throw error; }
|
|
47
|
+
response.statusCode = 200;
|
|
48
|
+
response.setHeader("Cache-Control", "no-store");
|
|
49
|
+
response.setHeader("Content-Type", "text/event-stream; charset=utf-8");
|
|
50
|
+
response.setHeader("Connection", "keep-alive");
|
|
51
|
+
response.flushHeaders();
|
|
52
|
+
if (replay.state === "resync-required" || replay.state === "truncated" || handoffOverflow) {
|
|
53
|
+
unsubscribe();
|
|
54
|
+
response.end(frame("resync-required", { reasonCode: replay.reasonCode ?? "event-replay-limit", latestCursor: replay.latestCursor }) ?? "event: resync-required\ndata: {}\n\n");
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const replayed = new Set<string>();
|
|
58
|
+
for (const event of replay.events) {
|
|
59
|
+
replayed.add(event.cursor);
|
|
60
|
+
if (!writeEvent(event)) { unsubscribe(); return; }
|
|
61
|
+
}
|
|
62
|
+
live = true;
|
|
63
|
+
for (const event of buffered) if (!replayed.has(event.cursor) && !writeEvent(event)) { unsubscribe(); return; }
|
|
64
|
+
response.write("retry: 2000\n\n");
|
|
65
|
+
this.#clients.add(response);
|
|
66
|
+
const heartbeat = setInterval(() => { if (!response.destroyed) response.write(": keepalive\n\n"); }, 15_000);
|
|
67
|
+
heartbeat.unref();
|
|
68
|
+
const cleanup = () => { clearInterval(heartbeat); unsubscribe(); this.#clients.delete(response); };
|
|
69
|
+
request.once("close", cleanup); response.once("close", cleanup);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
close(): void {
|
|
73
|
+
for (const response of this.#clients) response.end();
|
|
74
|
+
this.#clients.clear();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
const MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
5
|
+
const MAX_TOTAL_BYTES = 16 * 1024 * 1024;
|
|
6
|
+
const MIME = new Map([
|
|
7
|
+
[".css", "text/css; charset=utf-8"], [".html", "text/html; charset=utf-8"],
|
|
8
|
+
[".js", "text/javascript; charset=utf-8"], [".json", "application/json; charset=utf-8"],
|
|
9
|
+
[".svg", "image/svg+xml"], [".woff2", "font/woff2"]
|
|
10
|
+
]);
|
|
11
|
+
|
|
12
|
+
export type StaticAsset = { body: Buffer; contentType: string };
|
|
13
|
+
|
|
14
|
+
export function loadStaticBundle(root: string): ReadonlyMap<string, StaticAsset> {
|
|
15
|
+
const absoluteRoot = path.resolve(root), rootStat = fs.lstatSync(absoluteRoot);
|
|
16
|
+
if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) throw new Error("static-root-invalid");
|
|
17
|
+
const assets = new Map<string, StaticAsset>();
|
|
18
|
+
let total = 0;
|
|
19
|
+
const visit = (directory: string) => {
|
|
20
|
+
for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
21
|
+
const absolute = path.join(directory, entry.name), stat = fs.lstatSync(absolute);
|
|
22
|
+
if (stat.isSymbolicLink()) throw new Error("static-symlink-rejected");
|
|
23
|
+
if (entry.isDirectory()) { visit(absolute); continue; }
|
|
24
|
+
const relative = path.relative(absoluteRoot, absolute).split(path.sep).join("/");
|
|
25
|
+
const contentType = MIME.get(path.extname(relative));
|
|
26
|
+
if (!entry.isFile() || !contentType || stat.size > MAX_FILE_BYTES) throw new Error("static-asset-invalid");
|
|
27
|
+
total += stat.size;
|
|
28
|
+
if (total > MAX_TOTAL_BYTES) throw new Error("static-bundle-limit");
|
|
29
|
+
const descriptor = fs.openSync(absolute, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
|
|
30
|
+
try {
|
|
31
|
+
const opened = fs.fstatSync(descriptor);
|
|
32
|
+
if (!opened.isFile() || opened.dev !== stat.dev || opened.ino !== stat.ino || opened.size !== stat.size) throw new Error("static-asset-race");
|
|
33
|
+
assets.set(relative === "index.html" ? "/" : `/${relative}`, { body: fs.readFileSync(descriptor), contentType });
|
|
34
|
+
} finally { fs.closeSync(descriptor); }
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
visit(absoluteRoot);
|
|
38
|
+
if (!assets.has("/")) throw new Error("static-index-missing");
|
|
39
|
+
return assets;
|
|
40
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
import { redactSensitiveText } from "../../piagent-core/extensions/redaction-core.js";
|
|
4
|
+
|
|
5
|
+
const MAX_ENTRIES = 50_000;
|
|
6
|
+
const MAX_ITEMS = 200;
|
|
7
|
+
const MAX_TEXT = 16_384;
|
|
8
|
+
const ANSI = /\u001b(?:[@-_]|\[[0-?]*[ -/]*[@-~])/g;
|
|
9
|
+
|
|
10
|
+
type TranscriptIdentity = { projectRef: string; runtimeInstanceId: string; sessionRef: string; taskId: string | null; taskRunId: string | null;
|
|
11
|
+
agentOperationId: null; toolCallId: null };
|
|
12
|
+
type TranscriptRevision = { runtimeRevision: string; taskRevision: string | null; controlRevision: string | null; workspaceRevision: string | null;
|
|
13
|
+
indexRevision: string | null; approvalRevision: string | null; sessionOptionRevision: string | null; queueRevision: string | null };
|
|
14
|
+
type TranscriptContent = { state: "available" | "redacted" | "unavailable"; text: string | null; textChars: number | null; digest: string | null;
|
|
15
|
+
truncated: boolean; redacted: boolean; imageCount: number; reasonCode: string | null };
|
|
16
|
+
type TranscriptItem = { messageRef: string; parentMessageRef: string | null; role: "user" | "assistant" | "tool-result"; recordedAt: string;
|
|
17
|
+
agentOperationId: string | null; turnIndex: number | null; content: TranscriptContent;
|
|
18
|
+
toolCalls: Array<{ toolCallRef: string; toolName: string; state: "requested" | "completed" | "failed" | "unknown" }> };
|
|
19
|
+
export type TranscriptDocument = { schemaVersion: 1; version: "piagent-webui-transcript-v1"; generatedAt: string; identity: TranscriptIdentity;
|
|
20
|
+
revision: TranscriptRevision; eventCursor: string; state: "ready" | "unavailable"; items: TranscriptItem[];
|
|
21
|
+
page: { beforeCursor: string | null; nextBeforeCursor: string | null; hasOlder: boolean; limit: number; truncated: boolean }; reasonCode: string | null };
|
|
22
|
+
|
|
23
|
+
export type TranscriptProjectionInput = {
|
|
24
|
+
identity: TranscriptIdentity;
|
|
25
|
+
revision: TranscriptRevision;
|
|
26
|
+
eventCursor: string;
|
|
27
|
+
entries: unknown[];
|
|
28
|
+
beforeCursor?: string | null;
|
|
29
|
+
limit?: number;
|
|
30
|
+
generatedAt?: string;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
function hash(value: string): string { return createHash("sha256").update(value).digest("hex"); }
|
|
34
|
+
function opaque(prefix: string, value: unknown): string { return `${prefix}.${hash(JSON.stringify(value))}`; }
|
|
35
|
+
function timestamp(value: unknown): string | null {
|
|
36
|
+
const parsed = typeof value === "number" && Number.isFinite(value) ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
|
|
37
|
+
return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null;
|
|
38
|
+
}
|
|
39
|
+
function messageText(message: any): string {
|
|
40
|
+
if (typeof message?.content === "string") return message.content;
|
|
41
|
+
if (!Array.isArray(message?.content)) return "";
|
|
42
|
+
return message.content.filter((item: any) => item?.type === "text" && typeof item.text === "string").map((item: any) => item.text).join("\n");
|
|
43
|
+
}
|
|
44
|
+
function assistantFailureReason(message: any): string | null {
|
|
45
|
+
if (message?.role !== "assistant" || message?.stopReason !== "error") return null;
|
|
46
|
+
const detail = String(message?.errorMessage ?? "").toLowerCase();
|
|
47
|
+
if (/(?:authentication|auth|token|credential).{0,48}expired|expired.{0,48}(?:authentication|auth|token|credential)/.test(detail)) {
|
|
48
|
+
return "provider-auth-expired";
|
|
49
|
+
}
|
|
50
|
+
if (/(?:authentication|unauthorized|forbidden|credential|api[ _-]?key|log[ -]?in|sign[ -]?in)/.test(detail)) {
|
|
51
|
+
return "provider-auth-required";
|
|
52
|
+
}
|
|
53
|
+
if (/(?:rate[ _-]?limit|too many requests|quota)/.test(detail)) return "provider-rate-limited";
|
|
54
|
+
if (/(?:network|fetch failed|econn|timed? ?out|unavailable)/.test(detail)) return "provider-unavailable";
|
|
55
|
+
return "provider-response-failed";
|
|
56
|
+
}
|
|
57
|
+
function safeText(value: string): { full: string; preview: string; redacted: boolean; truncated: boolean } {
|
|
58
|
+
const clean = value.replace(ANSI, "").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, " ");
|
|
59
|
+
const redaction = redactSensitiveText(clean);
|
|
60
|
+
return { full: redaction.text, preview: redaction.text.slice(0, MAX_TEXT), redacted: redaction.redacted,
|
|
61
|
+
truncated: redaction.text.length > MAX_TEXT };
|
|
62
|
+
}
|
|
63
|
+
function safeToolName(value: unknown): string {
|
|
64
|
+
const projected = safeText(String(value ?? "tool"));
|
|
65
|
+
if (projected.redacted) return "redacted-tool";
|
|
66
|
+
return projected.full.replace(/[^A-Za-z0-9._:@~-]/g, "-").replace(/^[^A-Za-z0-9]+/, "").slice(0, 80) || "tool";
|
|
67
|
+
}
|
|
68
|
+
function imageCount(message: any): number {
|
|
69
|
+
return Array.isArray(message?.content) ? Math.min(32, message.content.filter((item: any) => item?.type === "image").length) : 0;
|
|
70
|
+
}
|
|
71
|
+
function toolCalls(message: any, sessionRef: string, role: TranscriptItem["role"]): TranscriptItem["toolCalls"] {
|
|
72
|
+
const values: Array<{ id: unknown; name: unknown; state: "requested" | "completed" | "failed" | "unknown" }> = [];
|
|
73
|
+
if (role === "assistant" && Array.isArray(message?.content)) {
|
|
74
|
+
for (const item of message.content) if (item?.type === "toolCall") values.push({ id: item.id, name: item.name, state: "requested" });
|
|
75
|
+
} else if (role === "tool-result") {
|
|
76
|
+
values.push({ id: message?.toolCallId, name: message?.toolName, state: message?.isError ? "failed" : "completed" });
|
|
77
|
+
}
|
|
78
|
+
return values.slice(0, 64).map((item, index) => {
|
|
79
|
+
return { toolCallRef: opaque("tool", [sessionRef, item.id ?? index]), toolName: safeToolName(item.name), state: item.state };
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
function role(message: any): TranscriptItem["role"] | null {
|
|
83
|
+
return message?.role === "user" ? "user" : message?.role === "assistant" ? "assistant" : message?.role === "toolResult" ? "tool-result" : null;
|
|
84
|
+
}
|
|
85
|
+
function unavailableContent(reasonCode: string): TranscriptContent {
|
|
86
|
+
return { state: "unavailable", text: null, textChars: null, digest: null, truncated: false, redacted: false, imageCount: 0, reasonCode };
|
|
87
|
+
}
|
|
88
|
+
function item(entry: any, identity: TranscriptIdentity): TranscriptItem | null {
|
|
89
|
+
if (!entry || entry.type !== "message" || !entry.message) return null;
|
|
90
|
+
const itemRole = role(entry.message), recordedAt = timestamp(entry.timestamp ?? entry.message.timestamp);
|
|
91
|
+
if (!itemRole || !recordedAt || typeof entry.id !== "string" || entry.id.length === 0) return null;
|
|
92
|
+
const content = itemRole === "tool-result" ? unavailableContent("tool-output-in-activity-preview") : (() => {
|
|
93
|
+
const projected = safeText(messageText(entry.message));
|
|
94
|
+
const failureReason = projected.full.length === 0 ? assistantFailureReason(entry.message) : null;
|
|
95
|
+
if (failureReason) return unavailableContent(failureReason);
|
|
96
|
+
return { state: projected.redacted ? "redacted" as const : "available" as const, text: projected.preview,
|
|
97
|
+
textChars: Math.min(1_000_000_000, projected.full.length), digest: `sha256:${hash(projected.full)}`, truncated: projected.truncated,
|
|
98
|
+
redacted: projected.redacted, imageCount: imageCount(entry.message), reasonCode: projected.redacted ? "sensitive-values-redacted" as const : null };
|
|
99
|
+
})();
|
|
100
|
+
return { messageRef: opaque("message", [identity.sessionRef, entry.id]), parentMessageRef: null, role: itemRole, recordedAt,
|
|
101
|
+
agentOperationId: null, turnIndex: null, content, toolCalls: toolCalls(entry.message, identity.sessionRef, itemRole) };
|
|
102
|
+
}
|
|
103
|
+
function unavailable(input: TranscriptProjectionInput, reasonCode: string, limit: number): TranscriptDocument {
|
|
104
|
+
return { schemaVersion: 1, version: "piagent-webui-transcript-v1", generatedAt: input.generatedAt ?? new Date().toISOString(),
|
|
105
|
+
identity: structuredClone(input.identity), revision: structuredClone(input.revision), eventCursor: input.eventCursor,
|
|
106
|
+
state: "unavailable", items: [], page: { beforeCursor: input.beforeCursor ?? null, nextBeforeCursor: null, hasOlder: false, limit, truncated: false }, reasonCode };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function projectTranscript(input: TranscriptProjectionInput): TranscriptDocument {
|
|
110
|
+
const limit = Math.max(1, Math.min(MAX_ITEMS, Number.isInteger(input.limit) ? Number(input.limit) : 50));
|
|
111
|
+
if (!Array.isArray(input.entries) || input.entries.length > MAX_ENTRIES) return unavailable(input, "transcript-history-unavailable", limit);
|
|
112
|
+
const projected = input.entries.map((entry) => ({ entry, item: item(entry, input.identity) })).filter((value): value is { entry: any; item: TranscriptItem } => Boolean(value.item));
|
|
113
|
+
const cursors = projected.map(({ entry }) => opaque("transcript", [input.identity.sessionRef, entry.id]));
|
|
114
|
+
let end = projected.length;
|
|
115
|
+
if (input.beforeCursor) {
|
|
116
|
+
const cursorIndex = cursors.indexOf(input.beforeCursor);
|
|
117
|
+
if (cursorIndex < 0) return unavailable(input, "transcript-cursor-gap", limit);
|
|
118
|
+
end = cursorIndex;
|
|
119
|
+
}
|
|
120
|
+
const start = Math.max(0, end - limit), selected = projected.slice(start, end).map((value) => value.item), hasOlder = start > 0;
|
|
121
|
+
return { schemaVersion: 1, version: "piagent-webui-transcript-v1", generatedAt: input.generatedAt ?? new Date().toISOString(),
|
|
122
|
+
identity: structuredClone(input.identity), revision: structuredClone(input.revision), eventCursor: input.eventCursor,
|
|
123
|
+
state: "ready", items: selected, page: { beforeCursor: input.beforeCursor ?? null, nextBeforeCursor: hasOlder ? cursors[start] : null,
|
|
124
|
+
hasOlder, limit, truncated: projected.length !== input.entries.filter((entry: any) => entry?.type === "message").length }, reasonCode: null };
|
|
125
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "https://piagent.io.vn/schemas/mutation-provenance-record.schema.json",
|
|
4
|
+
"title": "Piagent mutation provenance record v1",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"additionalProperties": false,
|
|
7
|
+
"required": [
|
|
8
|
+
"schemaVersion", "version", "recordId", "evidenceRef", "taskId", "taskRunId",
|
|
9
|
+
"sessionIdentityHash", "toolCallIdentityHash", "toolName", "recordedAt", "evidenceMode",
|
|
10
|
+
"beforeTreeDigest", "afterTreeDigest", "changes", "integrityDigest"
|
|
11
|
+
],
|
|
12
|
+
"properties": {
|
|
13
|
+
"schemaVersion": { "const": 1 },
|
|
14
|
+
"version": { "const": "piagent-mutation-provenance-v1" },
|
|
15
|
+
"recordId": { "type": "string", "pattern": "^provenance\\.[a-f0-9]{64}$" },
|
|
16
|
+
"evidenceRef": { "type": "string", "pattern": "^mutation\\.[a-f0-9]{64}$" },
|
|
17
|
+
"taskId": { "type": "string", "minLength": 1, "maxLength": 160, "pattern": "^[A-Za-z0-9][A-Za-z0-9._:@~-]*$" },
|
|
18
|
+
"taskRunId": { "type": "string", "minLength": 1, "maxLength": 160, "pattern": "^[A-Za-z0-9][A-Za-z0-9._:@~-]*$" },
|
|
19
|
+
"sessionIdentityHash": { "$ref": "#/$defs/digest" },
|
|
20
|
+
"toolCallIdentityHash": { "$ref": "#/$defs/digest" },
|
|
21
|
+
"toolName": { "enum": ["edit", "write", "apply_patch", "shell", "opaque"] },
|
|
22
|
+
"recordedAt": { "type": "string", "format": "date-time", "maxLength": 32 },
|
|
23
|
+
"evidenceMode": { "enum": ["exact-runtime", "observed-runtime"] },
|
|
24
|
+
"beforeTreeDigest": { "$ref": "#/$defs/treeDigest" },
|
|
25
|
+
"afterTreeDigest": { "$ref": "#/$defs/treeDigest" },
|
|
26
|
+
"changes": {
|
|
27
|
+
"type": "array",
|
|
28
|
+
"minItems": 1,
|
|
29
|
+
"maxItems": 100,
|
|
30
|
+
"items": { "$ref": "#/$defs/change" }
|
|
31
|
+
},
|
|
32
|
+
"integrityDigest": { "$ref": "#/$defs/digest" }
|
|
33
|
+
},
|
|
34
|
+
"$defs": {
|
|
35
|
+
"digest": { "type": "string", "pattern": "^sha256:[a-f0-9]{64}$" },
|
|
36
|
+
"treeDigest": { "type": "string", "pattern": "^wt-content-v2:[a-f0-9]{64}$" },
|
|
37
|
+
"carrierDigest": { "type": "string", "pattern": "^wt-content-v2:[a-f0-9]{64}$" },
|
|
38
|
+
"change": {
|
|
39
|
+
"type": "object",
|
|
40
|
+
"additionalProperties": false,
|
|
41
|
+
"required": [
|
|
42
|
+
"pathDigest", "repoPathBase64", "beforeCarrierDigest", "afterCarrierDigest",
|
|
43
|
+
"afterContentDigest", "proofMode", "effect"
|
|
44
|
+
],
|
|
45
|
+
"properties": {
|
|
46
|
+
"pathDigest": { "$ref": "#/$defs/digest" },
|
|
47
|
+
"repoPathBase64": { "type": "string", "minLength": 1, "maxLength": 4096, "pattern": "^[A-Za-z0-9_-]+$" },
|
|
48
|
+
"beforeCarrierDigest": {
|
|
49
|
+
"oneOf": [{ "type": "null" }, { "$ref": "#/$defs/carrierDigest" }]
|
|
50
|
+
},
|
|
51
|
+
"afterCarrierDigest": {
|
|
52
|
+
"oneOf": [{ "type": "null" }, { "$ref": "#/$defs/carrierDigest" }]
|
|
53
|
+
},
|
|
54
|
+
"afterContentDigest": {
|
|
55
|
+
"oneOf": [{ "type": "null" }, { "$ref": "#/$defs/digest" }]
|
|
56
|
+
},
|
|
57
|
+
"proofMode": {
|
|
58
|
+
"oneOf": [{ "type": "null" }, { "enum": ["full-content", "exact-replacement"] }]
|
|
59
|
+
},
|
|
60
|
+
"effect": { "enum": ["exact-content", "content-preserved", "content-changed", "unknown"] }
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
"allOf": [
|
|
65
|
+
{
|
|
66
|
+
"if": { "properties": { "evidenceMode": { "const": "exact-runtime" } }, "required": ["evidenceMode"] },
|
|
67
|
+
"then": {
|
|
68
|
+
"properties": {
|
|
69
|
+
"toolName": { "enum": ["edit", "write", "apply_patch"] },
|
|
70
|
+
"changes": {
|
|
71
|
+
"type": "array",
|
|
72
|
+
"items": {
|
|
73
|
+
"type": "object",
|
|
74
|
+
"properties": {
|
|
75
|
+
"afterCarrierDigest": { "$ref": "#/$defs/carrierDigest" },
|
|
76
|
+
"afterContentDigest": { "$ref": "#/$defs/digest" },
|
|
77
|
+
"proofMode": { "enum": ["full-content", "exact-replacement"] },
|
|
78
|
+
"effect": { "const": "exact-content" }
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
"else": {
|
|
85
|
+
"properties": {
|
|
86
|
+
"changes": {
|
|
87
|
+
"type": "array",
|
|
88
|
+
"items": {
|
|
89
|
+
"type": "object",
|
|
90
|
+
"properties": {
|
|
91
|
+
"proofMode": { "type": "null" },
|
|
92
|
+
"effect": { "enum": ["content-preserved", "content-changed", "unknown"] }
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
]
|
|
100
|
+
}
|