@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,16 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="vi">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
|
+
<meta name="color-scheme" content="dark" />
|
|
7
|
+
<meta name="csp-nonce" content="__PIAGENT_CSP_NONCE__" />
|
|
8
|
+
<meta name="piagent-webui-mode" content="__PIAGENT_WEBUI_MODE__" />
|
|
9
|
+
<title>Piagent WebUI</title>
|
|
10
|
+
<script type="module" crossorigin src="/assets/index-bu7XpD9Q.js"></script>
|
|
11
|
+
<link rel="stylesheet" crossorigin href="/assets/index-DwKCWbwd.css">
|
|
12
|
+
</head>
|
|
13
|
+
<body>
|
|
14
|
+
<div id="root"></div>
|
|
15
|
+
</body>
|
|
16
|
+
</html>
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
import { redactSensitiveText } from "../../piagent-core/extensions/redaction-core.js";
|
|
7
|
+
import { supportedChatImageMimeType } from "../../piagent-core/runtime/input/chat-images.ts";
|
|
8
|
+
import type { BridgeIdentity, BridgeSnapshot } from "./same-session-bridge.ts";
|
|
9
|
+
|
|
10
|
+
export const ATTACHMENT_LIMITS = {
|
|
11
|
+
countPerMessage: 4,
|
|
12
|
+
imageBytes: 8 * 1024 * 1024,
|
|
13
|
+
textBytes: 256 * 1024,
|
|
14
|
+
totalBytesPerMessage: 16 * 1024 * 1024,
|
|
15
|
+
runtimeCount: 64,
|
|
16
|
+
runtimeBytes: 64 * 1024 * 1024,
|
|
17
|
+
ttlMs: 10 * 60_000
|
|
18
|
+
} as const;
|
|
19
|
+
|
|
20
|
+
const IMAGE_MIMES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp"]);
|
|
21
|
+
const TEXT_MIMES = new Set(["text/plain", "text/markdown", "application/json"]);
|
|
22
|
+
const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;
|
|
23
|
+
const PUBLIC_REF = /^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/;
|
|
24
|
+
const REVISION = /^[A-Za-z0-9][A-Za-z0-9._:~-]{0,159}$/;
|
|
25
|
+
const IDEMPOTENCY = /^[A-Za-z0-9._~-]{32,128}$/;
|
|
26
|
+
const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
27
|
+
const OWNED_FILE = /^[a-f0-9]{48}\.bin$/;
|
|
28
|
+
|
|
29
|
+
type StoredAttachment = Attachment & {
|
|
30
|
+
projectRef: string;
|
|
31
|
+
runtimeInstanceId: string;
|
|
32
|
+
sessionRef: string;
|
|
33
|
+
absolutePath: string;
|
|
34
|
+
device: number;
|
|
35
|
+
inode: number;
|
|
36
|
+
};
|
|
37
|
+
type Attachment = { attachmentRef: string; messageRequestId: string; displayName: string; kind: "file" | "image";
|
|
38
|
+
mimeType: string; sizeBytes: number; expiresAt: string };
|
|
39
|
+
type StageCommand = { schemaVersion: 1; version: "piagent-webui-attachment-v1"; messageType: "stage-command"; commandId: string;
|
|
40
|
+
idempotencyKey: string; requestedAt: string; expiresAt: string; identity: BridgeIdentity; expectedRuntimeRevision: string;
|
|
41
|
+
messageRequestId: string; file: { displayName: string; declaredMimeType: string; dataBase64: string } };
|
|
42
|
+
type StageResultCode = "staged" | "invalid-command" | "identity-mismatch" | "stale-revision" | "expired" | "unsupported-type"
|
|
43
|
+
| "invalid-content" | "limit-exceeded" | "storage-unavailable" | "idempotency-payload-mismatch" | "capability-unavailable";
|
|
44
|
+
export type StageReceipt = { schemaVersion: 1; version: "piagent-webui-attachment-v1"; messageType: "stage-receipt"; commandId: string;
|
|
45
|
+
identity: BridgeIdentity; phase: "settled" | "rejected"; resultCode: StageResultCode; requestedAt: string; settledAt: string;
|
|
46
|
+
deduplicated: boolean; attachment: Attachment | null; error: { code: string; message: string; retryable: boolean } | null };
|
|
47
|
+
type DiscardCommand = Omit<StageCommand, "messageType" | "file"> & { messageType: "discard-command"; attachmentRef: string };
|
|
48
|
+
export type DiscardReceipt = Omit<StageReceipt, "messageType" | "resultCode" | "attachment"> & { messageType: "discard-receipt";
|
|
49
|
+
resultCode: "discarded" | "invalid-command" | "identity-mismatch" | "stale-revision" | "expired" | "attachment-unavailable"
|
|
50
|
+
| "idempotency-payload-mismatch" | "capability-unavailable"; attachmentRef: string | null };
|
|
51
|
+
type CachedStage = { fingerprint: string; receipt: StageReceipt; expiresAt: number };
|
|
52
|
+
type TextContent = { type: "text"; text: string };
|
|
53
|
+
type ImageContent = { type: "image"; data: string; mimeType: string };
|
|
54
|
+
export type PreparedAttachments = { content: string | Array<TextContent | ImageContent>; observedText: string };
|
|
55
|
+
|
|
56
|
+
function exactKeys(value: unknown, expected: string[]): boolean {
|
|
57
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value)
|
|
58
|
+
&& JSON.stringify(Object.keys(value as Record<string, unknown>).sort()) === JSON.stringify([...expected].sort()));
|
|
59
|
+
}
|
|
60
|
+
function timestamp(value: unknown): value is string {
|
|
61
|
+
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) return false;
|
|
62
|
+
const parsed = Date.parse(value);
|
|
63
|
+
return Number.isFinite(parsed) && new Date(parsed).toISOString() === value;
|
|
64
|
+
}
|
|
65
|
+
function validIdentity(value: unknown): value is BridgeIdentity {
|
|
66
|
+
if (!exactKeys(value, ["projectRef", "runtimeInstanceId", "sessionRef", "taskId", "taskRunId", "agentOperationId", "toolCallId"])) return false;
|
|
67
|
+
const item = value as BridgeIdentity;
|
|
68
|
+
return [item.projectRef, item.runtimeInstanceId, item.sessionRef].every((part) => typeof part === "string" && REF.test(part))
|
|
69
|
+
&& (item.taskId === null || typeof item.taskId === "string" && PUBLIC_REF.test(item.taskId))
|
|
70
|
+
&& (item.taskRunId === null || typeof item.taskRunId === "string" && PUBLIC_REF.test(item.taskRunId))
|
|
71
|
+
&& (item.taskRunId === null || item.taskId !== null)
|
|
72
|
+
&& (item.agentOperationId === null || typeof item.agentOperationId === "string" && REF.test(item.agentOperationId))
|
|
73
|
+
&& item.toolCallId === null;
|
|
74
|
+
}
|
|
75
|
+
function sameIdentity(left: BridgeIdentity, right: BridgeIdentity): boolean {
|
|
76
|
+
return left.projectRef === right.projectRef && left.runtimeInstanceId === right.runtimeInstanceId && left.sessionRef === right.sessionRef
|
|
77
|
+
&& left.taskId === right.taskId && left.taskRunId === right.taskRunId && left.agentOperationId === right.agentOperationId && left.toolCallId === right.toolCallId;
|
|
78
|
+
}
|
|
79
|
+
function fingerprint(command: unknown): string {
|
|
80
|
+
return createHash("sha256").update(JSON.stringify(command)).digest("hex");
|
|
81
|
+
}
|
|
82
|
+
function safeName(value: unknown): string {
|
|
83
|
+
const basename = path.basename(String(value ?? "attachment").replace(/[\\/]/g, "_"));
|
|
84
|
+
return redactSensitiveText(basename).text.replace(/[\u0000-\u001F\u007F]/g, " ").replace(/\s+/g, " ").trim().slice(0, 160) || "attachment";
|
|
85
|
+
}
|
|
86
|
+
function errorMessage(code: StageReceipt["resultCode"]): string {
|
|
87
|
+
const messages: Partial<Record<StageReceipt["resultCode"], string>> = {
|
|
88
|
+
"invalid-command": "The attachment command is invalid.", "identity-mismatch": "The attachment targets a different Pi session.",
|
|
89
|
+
"stale-revision": "The Pi session changed before the attachment was staged.", expired: "The attachment command expired.",
|
|
90
|
+
"unsupported-type": "This file type is not supported.", "invalid-content": "The selected file content is invalid.",
|
|
91
|
+
"limit-exceeded": "The attachment limit was exceeded.", "storage-unavailable": "Private attachment storage is unavailable.",
|
|
92
|
+
"idempotency-payload-mismatch": "This upload key was already used for different content.",
|
|
93
|
+
"capability-unavailable": "The active Pi model cannot accept this attachment."
|
|
94
|
+
};
|
|
95
|
+
return messages[code] ?? "The attachment could not be staged.";
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export class AttachmentStore {
|
|
99
|
+
readonly #runtimeInstanceId: string;
|
|
100
|
+
readonly #bridgeSnapshot: () => BridgeSnapshot;
|
|
101
|
+
readonly #modelSupportsImages: () => boolean;
|
|
102
|
+
readonly #now: () => Date;
|
|
103
|
+
#directory: string;
|
|
104
|
+
readonly #directoryDevice: number;
|
|
105
|
+
readonly #directoryInode: number;
|
|
106
|
+
readonly #records = new Map<string, StoredAttachment>();
|
|
107
|
+
readonly #cache = new Map<string, CachedStage>();
|
|
108
|
+
readonly #discardCache = new Map<string, { fingerprint: string; receipt: DiscardReceipt; expiresAt: number }>();
|
|
109
|
+
#closed = false;
|
|
110
|
+
|
|
111
|
+
constructor(options: { runtimeInstanceId: string; bridgeSnapshot: () => BridgeSnapshot; modelSupportsImages: () => boolean;
|
|
112
|
+
now?: () => Date; tempRoot?: string }) {
|
|
113
|
+
if (!REF.test(options.runtimeInstanceId)) throw new Error("webui-attachment-runtime-invalid");
|
|
114
|
+
this.#runtimeInstanceId = options.runtimeInstanceId; this.#bridgeSnapshot = options.bridgeSnapshot;
|
|
115
|
+
this.#modelSupportsImages = options.modelSupportsImages; this.#now = options.now ?? (() => new Date());
|
|
116
|
+
const parent = path.resolve(options.tempRoot ?? os.tmpdir());
|
|
117
|
+
this.#directory = fs.mkdtempSync(path.join(parent, "piagent-webui-attachments-"));
|
|
118
|
+
fs.chmodSync(this.#directory, 0o700);
|
|
119
|
+
const inspected = fs.lstatSync(this.#directory);
|
|
120
|
+
if (!inspected.isDirectory() || inspected.isSymbolicLink() || (inspected.mode & 0o077) !== 0) throw new Error("webui-attachment-storage-unsafe");
|
|
121
|
+
this.#directoryDevice = inspected.dev; this.#directoryInode = inspected.ino;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
capability(): { kinds: Array<"file" | "image">; mimeTypes: string[] } {
|
|
125
|
+
const image = this.#modelSupportsImages();
|
|
126
|
+
return { kinds: image ? ["file", "image"] : ["file"], mimeTypes: [...TEXT_MIMES, ...(image ? IMAGE_MIMES : [])].sort() };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
stage(input: unknown): StageReceipt {
|
|
130
|
+
const now = this.#now(); this.#cleanup(now.getTime());
|
|
131
|
+
const snapshot = this.#bridgeSnapshot(), command = input as StageCommand;
|
|
132
|
+
const invalid = this.#validate(command);
|
|
133
|
+
if (invalid) return this.#reject(command, snapshot, "invalid-command", invalid, now);
|
|
134
|
+
const key = command.idempotencyKey, found = this.#cache.get(key), commandFingerprint = fingerprint(command);
|
|
135
|
+
if (found) {
|
|
136
|
+
if (found.fingerprint !== commandFingerprint) return this.#reject(command, snapshot, "idempotency-payload-mismatch", null, now);
|
|
137
|
+
return { ...structuredClone(found.receipt), deduplicated: true };
|
|
138
|
+
}
|
|
139
|
+
if (this.#closed || snapshot.state !== "ready" || snapshot.taskState === "terminal" || !snapshot.identity || !snapshot.revisions)
|
|
140
|
+
return this.#reject(command, snapshot, "capability-unavailable", "attachment-store-not-ready", now);
|
|
141
|
+
if (Date.parse(command.requestedAt) > now.getTime() + 30_000) return this.#reject(command, snapshot, "invalid-command", "requested-at-in-future", now);
|
|
142
|
+
if (now.getTime() > Date.parse(command.expiresAt)) return this.#reject(command, snapshot, "expired", null, now);
|
|
143
|
+
if (!sameIdentity(command.identity, snapshot.identity)) return this.#reject(command, snapshot, "identity-mismatch", null, now);
|
|
144
|
+
if (command.expectedRuntimeRevision !== snapshot.revisions.runtimeRevision) return this.#reject(command, snapshot, "stale-revision", null, now);
|
|
145
|
+
|
|
146
|
+
let bytes: Buffer;
|
|
147
|
+
try { bytes = Buffer.from(command.file.dataBase64, "base64"); }
|
|
148
|
+
catch { return this.#reject(command, snapshot, "invalid-content", "base64-decode-failed", now); }
|
|
149
|
+
if (bytes.length < 1 || bytes.toString("base64") !== command.file.dataBase64) return this.#reject(command, snapshot, "invalid-content", "base64-noncanonical", now);
|
|
150
|
+
const declared = command.file.declaredMimeType, image = IMAGE_MIMES.has(declared), text = TEXT_MIMES.has(declared);
|
|
151
|
+
if (!image && !text) return this.#reject(command, snapshot, "unsupported-type", null, now);
|
|
152
|
+
let mimeType = declared;
|
|
153
|
+
if (image) {
|
|
154
|
+
if (!this.#modelSupportsImages()) return this.#reject(command, snapshot, "capability-unavailable", "model-image-input-unavailable", now);
|
|
155
|
+
const detected = supportedChatImageMimeType(bytes);
|
|
156
|
+
if (!detected || detected !== declared) return this.#reject(command, snapshot, "invalid-content", "image-mime-mismatch", now);
|
|
157
|
+
mimeType = detected;
|
|
158
|
+
if (bytes.length > ATTACHMENT_LIMITS.imageBytes) return this.#reject(command, snapshot, "limit-exceeded", "image-size-limit", now);
|
|
159
|
+
} else {
|
|
160
|
+
if (bytes.length > ATTACHMENT_LIMITS.textBytes) return this.#reject(command, snapshot, "limit-exceeded", "text-size-limit", now);
|
|
161
|
+
try {
|
|
162
|
+
const decoded = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
163
|
+
if (decoded.includes("\0")) throw new Error("nul");
|
|
164
|
+
if (declared === "application/json") JSON.parse(decoded);
|
|
165
|
+
} catch { return this.#reject(command, snapshot, "invalid-content", "text-content-invalid", now); }
|
|
166
|
+
}
|
|
167
|
+
const messageRecords = [...this.#records.values()].filter((item) => item.sessionRef === snapshot.identity!.sessionRef
|
|
168
|
+
&& item.messageRequestId === command.messageRequestId);
|
|
169
|
+
if (messageRecords.length >= ATTACHMENT_LIMITS.countPerMessage
|
|
170
|
+
|| messageRecords.reduce((sum, item) => sum + item.sizeBytes, 0) + bytes.length > ATTACHMENT_LIMITS.totalBytesPerMessage
|
|
171
|
+
|| this.#records.size >= ATTACHMENT_LIMITS.runtimeCount
|
|
172
|
+
|| [...this.#records.values()].reduce((sum, item) => sum + item.sizeBytes, 0) + bytes.length > ATTACHMENT_LIMITS.runtimeBytes)
|
|
173
|
+
return this.#reject(command, snapshot, "limit-exceeded", "attachment-capacity-limit", now);
|
|
174
|
+
const attachmentRef = `attachment.${randomBytes(24).toString("hex")}`, filename = `${randomBytes(24).toString("hex")}.bin`;
|
|
175
|
+
const absolutePath = path.join(this.#directory, filename), expiresAt = new Date(now.getTime() + ATTACHMENT_LIMITS.ttlMs).toISOString();
|
|
176
|
+
try {
|
|
177
|
+
if (!this.#safeDirectory()) throw new Error("unsafe-directory");
|
|
178
|
+
const descriptor = fs.openSync(absolutePath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
|
|
179
|
+
try { fs.writeFileSync(descriptor, bytes); fs.fsyncSync(descriptor); fs.fchmodSync(descriptor, 0o600); }
|
|
180
|
+
finally { fs.closeSync(descriptor); }
|
|
181
|
+
const inspected = fs.lstatSync(absolutePath);
|
|
182
|
+
if (!inspected.isFile() || inspected.isSymbolicLink() || inspected.size !== bytes.length || (inspected.mode & 0o077) !== 0) throw new Error("unsafe-file");
|
|
183
|
+
const attachment = { attachmentRef, messageRequestId: command.messageRequestId, displayName: safeName(command.file.displayName),
|
|
184
|
+
kind: image ? "image" as const : "file" as const, mimeType, sizeBytes: bytes.length, expiresAt };
|
|
185
|
+
this.#records.set(attachmentRef, { ...attachment, projectRef: snapshot.identity.projectRef, runtimeInstanceId: snapshot.identity.runtimeInstanceId,
|
|
186
|
+
sessionRef: snapshot.identity.sessionRef, absolutePath, device: inspected.dev, inode: inspected.ino });
|
|
187
|
+
const receipt = this.#receipt(command, snapshot.identity, "settled", "staged", attachment, null, now, false);
|
|
188
|
+
this.#cache.set(key, { fingerprint: commandFingerprint, receipt: structuredClone(receipt), expiresAt: Date.parse(expiresAt) });
|
|
189
|
+
return receipt;
|
|
190
|
+
} catch {
|
|
191
|
+
this.#deleteOwnedPath(absolutePath); return this.#reject(command, snapshot, "storage-unavailable", null, now);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
execute(input: unknown): StageReceipt | DiscardReceipt {
|
|
196
|
+
return (input as { messageType?: unknown })?.messageType === "discard-command" ? this.discard(input) : this.stage(input);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
discard(input: unknown): DiscardReceipt {
|
|
200
|
+
const now = this.#now(); this.#cleanup(now.getTime()); const snapshot = this.#bridgeSnapshot(), command = input as DiscardCommand;
|
|
201
|
+
const reject = (code: Exclude<DiscardReceipt["resultCode"], "discarded">, reason: string = code): DiscardReceipt => ({ schemaVersion: 1,
|
|
202
|
+
version: "piagent-webui-attachment-v1", messageType: "discard-receipt", commandId: typeof command?.commandId === "string" && REF.test(command.commandId)
|
|
203
|
+
? command.commandId : `attachment-command.${createHash("sha256").update(reason).digest("hex")}`, identity: structuredClone(snapshot.identity ?? {
|
|
204
|
+
projectRef: `project.${"0".repeat(64)}`, runtimeInstanceId: this.#runtimeInstanceId, sessionRef: `session.${"0".repeat(64)}`,
|
|
205
|
+
taskId: null, taskRunId: null, agentOperationId: null, toolCallId: null }), phase: "rejected", resultCode: code,
|
|
206
|
+
requestedAt: timestamp(command?.requestedAt) ? command.requestedAt : now.toISOString(), settledAt: now.toISOString(), deduplicated: false,
|
|
207
|
+
attachmentRef: null, error: { code: reason, message: errorMessage(code === "attachment-unavailable" ? "capability-unavailable" : code as StageResultCode), retryable: false } });
|
|
208
|
+
if (!command || !exactKeys(command, ["schemaVersion", "version", "messageType", "commandId", "idempotencyKey", "requestedAt", "expiresAt", "identity",
|
|
209
|
+
"expectedRuntimeRevision", "messageRequestId", "attachmentRef"]) || command.schemaVersion !== 1 || command.version !== "piagent-webui-attachment-v1"
|
|
210
|
+
|| command.messageType !== "discard-command" || !REF.test(command.commandId) || !IDEMPOTENCY.test(command.idempotencyKey) || !timestamp(command.requestedAt)
|
|
211
|
+
|| !timestamp(command.expiresAt) || Date.parse(command.requestedAt) > Date.parse(command.expiresAt) || Date.parse(command.expiresAt) - Date.parse(command.requestedAt) > 300_000
|
|
212
|
+
|| !validIdentity(command.identity) || !REVISION.test(command.expectedRuntimeRevision) || !REF.test(command.messageRequestId) || !REF.test(command.attachmentRef)) return reject("invalid-command");
|
|
213
|
+
const found = this.#discardCache.get(command.idempotencyKey), commandFingerprint = fingerprint(command);
|
|
214
|
+
if (found) return found.fingerprint === commandFingerprint ? { ...structuredClone(found.receipt), deduplicated: true } : reject("idempotency-payload-mismatch");
|
|
215
|
+
if (this.#closed || snapshot.state !== "ready" || !snapshot.identity || !snapshot.revisions) return reject("capability-unavailable");
|
|
216
|
+
if (Date.parse(command.requestedAt) > now.getTime() + 30_000) return reject("invalid-command", "requested-at-in-future");
|
|
217
|
+
if (now.getTime() > Date.parse(command.expiresAt)) return reject("expired");
|
|
218
|
+
if (!sameIdentity(command.identity, snapshot.identity)) return reject("identity-mismatch");
|
|
219
|
+
if (command.expectedRuntimeRevision !== snapshot.revisions.runtimeRevision) return reject("stale-revision");
|
|
220
|
+
const record = this.#records.get(command.attachmentRef);
|
|
221
|
+
if (!record || record.messageRequestId !== command.messageRequestId || record.sessionRef !== snapshot.identity.sessionRef) return reject("attachment-unavailable");
|
|
222
|
+
this.#consume(record);
|
|
223
|
+
const receipt = { schemaVersion: 1, version: "piagent-webui-attachment-v1", messageType: "discard-receipt", commandId: command.commandId,
|
|
224
|
+
identity: structuredClone(snapshot.identity), phase: "settled", resultCode: "discarded", requestedAt: command.requestedAt,
|
|
225
|
+
settledAt: now.toISOString(), deduplicated: false, attachmentRef: command.attachmentRef, error: null } satisfies DiscardReceipt;
|
|
226
|
+
this.#discardCache.set(command.idempotencyKey, { fingerprint: commandFingerprint, receipt: structuredClone(receipt), expiresAt: Date.parse(command.expiresAt) });
|
|
227
|
+
return receipt;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
claim(refs: string[], messageRequestId: string, identity: BridgeIdentity, text: string): PreparedAttachments {
|
|
231
|
+
const now = this.#now().getTime(); this.#cleanup(now);
|
|
232
|
+
if (this.#closed || refs.length < 1 || refs.length > ATTACHMENT_LIMITS.countPerMessage || new Set(refs).size !== refs.length)
|
|
233
|
+
throw new Error("attachment-reference-invalid");
|
|
234
|
+
const records = refs.map((ref) => this.#records.get(ref));
|
|
235
|
+
if (records.some((record) => !record)) throw new Error("attachment-reference-unavailable");
|
|
236
|
+
const exact = records as StoredAttachment[];
|
|
237
|
+
if (exact.some((record) => record.messageRequestId !== messageRequestId || record.projectRef !== identity.projectRef
|
|
238
|
+
|| record.runtimeInstanceId !== identity.runtimeInstanceId || record.sessionRef !== identity.sessionRef || Date.parse(record.expiresAt) < now)
|
|
239
|
+
|| exact.reduce((sum, record) => sum + record.sizeBytes, 0) > ATTACHMENT_LIMITS.totalBytesPerMessage) throw new Error("attachment-authority-mismatch");
|
|
240
|
+
if (exact.some((record) => record.kind === "image") && !this.#modelSupportsImages()) throw new Error("model-image-input-unavailable");
|
|
241
|
+
const content: Array<TextContent | ImageContent> = [{ type: "text", text }], observedTexts = [text];
|
|
242
|
+
try {
|
|
243
|
+
for (const record of exact) {
|
|
244
|
+
const bytes = this.#readOwned(record);
|
|
245
|
+
if (record.kind === "image") content.push({ type: "image", data: bytes.toString("base64"), mimeType: record.mimeType });
|
|
246
|
+
else {
|
|
247
|
+
const body = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
248
|
+
const attachmentText = `[Attached file: ${record.displayName} (${record.mimeType}, ${record.sizeBytes} bytes)]\n${body}\n[End attached file]`;
|
|
249
|
+
content.push({ type: "text", text: attachmentText }); observedTexts.push(attachmentText);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
} catch (error) {
|
|
253
|
+
exact.forEach((record) => this.#consume(record)); throw error;
|
|
254
|
+
}
|
|
255
|
+
exact.forEach((record) => this.#consume(record));
|
|
256
|
+
return { content, observedText: observedTexts.join("\n") };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
close(): void {
|
|
260
|
+
if (this.#closed) return; this.#closed = true;
|
|
261
|
+
for (const record of this.#records.values()) this.#deleteOwnedPath(record.absolutePath);
|
|
262
|
+
this.#records.clear(); this.#cache.clear(); this.#discardCache.clear();
|
|
263
|
+
try { if (this.#safeDirectory()) fs.rmdirSync(this.#directory); } catch { /* never recurse beyond files owned by this store */ }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
reset(): void {
|
|
267
|
+
for (const record of this.#records.values()) this.#deleteOwnedPath(record.absolutePath);
|
|
268
|
+
this.#records.clear(); this.#cache.clear(); this.#discardCache.clear();
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
#validate(command: StageCommand): string | null {
|
|
272
|
+
if (!command || typeof command !== "object" || command.schemaVersion !== 1 || command.version !== "piagent-webui-attachment-v1"
|
|
273
|
+
|| command.messageType !== "stage-command" || !exactKeys(command, ["schemaVersion", "version", "messageType", "commandId", "idempotencyKey", "requestedAt", "expiresAt", "identity", "expectedRuntimeRevision", "messageRequestId", "file"])) return "unsupported-command-shape";
|
|
274
|
+
if (!REF.test(command.commandId) || !IDEMPOTENCY.test(command.idempotencyKey) || !timestamp(command.requestedAt) || !timestamp(command.expiresAt)
|
|
275
|
+
|| Date.parse(command.requestedAt) > Date.parse(command.expiresAt) || Date.parse(command.expiresAt) - Date.parse(command.requestedAt) > 300_000
|
|
276
|
+
|| !validIdentity(command.identity) || !REVISION.test(command.expectedRuntimeRevision) || !REF.test(command.messageRequestId)) return "invalid-command-metadata";
|
|
277
|
+
if (!exactKeys(command.file, ["displayName", "declaredMimeType", "dataBase64"]) || typeof command.file.displayName !== "string"
|
|
278
|
+
|| command.file.displayName.length < 1 || command.file.displayName.length > 255 || /[\u0000-\u001F\u007F/\\]/.test(command.file.displayName)
|
|
279
|
+
|| typeof command.file.declaredMimeType !== "string" || typeof command.file.dataBase64 !== "string"
|
|
280
|
+
|| command.file.dataBase64.length < 4 || command.file.dataBase64.length > 11_184_812 || !BASE64.test(command.file.dataBase64)) return "invalid-file-payload";
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
#receipt(command: Partial<StageCommand>, identity: BridgeIdentity, phase: StageReceipt["phase"], resultCode: StageReceipt["resultCode"],
|
|
285
|
+
attachment: Attachment | null, reason: string | null, now: Date, deduplicated: boolean): StageReceipt {
|
|
286
|
+
return { schemaVersion: 1, version: "piagent-webui-attachment-v1", messageType: "stage-receipt",
|
|
287
|
+
commandId: typeof command.commandId === "string" && REF.test(command.commandId) ? command.commandId : `attachment-command.${createHash("sha256").update(reason ?? resultCode).digest("hex")}`,
|
|
288
|
+
identity: structuredClone(identity), phase, resultCode, requestedAt: timestamp(command.requestedAt) ? command.requestedAt : now.toISOString(),
|
|
289
|
+
settledAt: now.toISOString(), deduplicated, attachment, error: phase === "rejected" ? { code: reason ?? resultCode,
|
|
290
|
+
message: errorMessage(resultCode), retryable: resultCode === "storage-unavailable" } : null };
|
|
291
|
+
}
|
|
292
|
+
#reject(command: Partial<StageCommand>, snapshot: BridgeSnapshot, code: Exclude<StageReceipt["resultCode"], "staged">,
|
|
293
|
+
reason: string | null, now: Date): StageReceipt {
|
|
294
|
+
const identity = snapshot.identity ?? { projectRef: `project.${"0".repeat(64)}`, runtimeInstanceId: this.#runtimeInstanceId,
|
|
295
|
+
sessionRef: `session.${"0".repeat(64)}`, taskId: null, taskRunId: null, agentOperationId: null, toolCallId: null };
|
|
296
|
+
return this.#receipt(command, identity, "rejected", code, null, reason, now, false);
|
|
297
|
+
}
|
|
298
|
+
#readOwned(record: StoredAttachment): Buffer {
|
|
299
|
+
if (!this.#safeDirectory() || path.dirname(record.absolutePath) !== this.#directory || !OWNED_FILE.test(path.basename(record.absolutePath))) throw new Error("attachment-storage-boundary");
|
|
300
|
+
const descriptor = fs.openSync(record.absolutePath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
301
|
+
try {
|
|
302
|
+
const inspected = fs.fstatSync(descriptor);
|
|
303
|
+
if (!inspected.isFile() || inspected.dev !== record.device || inspected.ino !== record.inode || inspected.size !== record.sizeBytes) throw new Error("attachment-file-changed");
|
|
304
|
+
const bytes = Buffer.alloc(inspected.size); let offset = 0;
|
|
305
|
+
while (offset < bytes.length) { const read = fs.readSync(descriptor, bytes, offset, bytes.length - offset, offset); if (read <= 0) break; offset += read; }
|
|
306
|
+
if (offset !== bytes.length) throw new Error("attachment-file-short-read"); return bytes;
|
|
307
|
+
} finally { fs.closeSync(descriptor); }
|
|
308
|
+
}
|
|
309
|
+
#consume(record: StoredAttachment): void { this.#records.delete(record.attachmentRef); this.#deleteOwnedPath(record.absolutePath); }
|
|
310
|
+
#deleteOwnedPath(target: string): void {
|
|
311
|
+
if (!this.#safeDirectory() || path.dirname(target) !== this.#directory || !OWNED_FILE.test(path.basename(target))) return;
|
|
312
|
+
try { fs.unlinkSync(target); } catch { /* cleanup is bounded and best-effort */ }
|
|
313
|
+
}
|
|
314
|
+
#safeDirectory(): boolean {
|
|
315
|
+
try { const current = fs.lstatSync(this.#directory); return current.isDirectory() && !current.isSymbolicLink()
|
|
316
|
+
&& current.dev === this.#directoryDevice && current.ino === this.#directoryInode && (current.mode & 0o077) === 0; } catch { return false; }
|
|
317
|
+
}
|
|
318
|
+
#cleanup(now: number): void {
|
|
319
|
+
for (const record of this.#records.values()) if (Date.parse(record.expiresAt) <= now) this.#consume(record);
|
|
320
|
+
for (const [key, cached] of this.#cache) if (cached.expiresAt <= now) this.#cache.delete(key);
|
|
321
|
+
for (const [key, cached] of this.#discardCache) if (cached.expiresAt <= now) this.#discardCache.delete(key);
|
|
322
|
+
}
|
|
323
|
+
}
|