@piagent/platform 1.3.0 → 1.4.0
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 +56 -3
- package/README.md +3 -3
- 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 +10 -2
- 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/herdr-workflow.md +1 -0
- package/docs/mcp-and-tools.md +14 -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 +1 -0
- package/docs/quality-benchmark.md +1 -0
- package/docs/quickstart-vietnamese.md +3 -2
- package/docs/release-install-policy.md +11 -7
- package/docs/runtime-harness-standard.md +1 -0
- 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 +1 -0
- 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 +1 -0
- package/docs/vercel-docs-site.md +1 -0
- package/docs/workflow-recipes.md +1 -0
- package/docs-site/architecture.html +1 -1
- package/docs-site/benchmark.html +1 -1
- package/docs-site/commands.html +1 -1
- package/docs-site/context-engine.html +1 -1
- package/docs-site/en/architecture.html +1 -1
- package/docs-site/en/benchmark.html +1 -1
- package/docs-site/en/commands.html +1 -1
- package/docs-site/en/context-engine.html +1 -1
- package/docs-site/en/index.html +1 -1
- package/docs-site/en/mcp-approval.html +1 -1
- package/docs-site/en/mcp-auth.html +1 -1
- package/docs-site/en/mcp-servers.html +1 -1
- package/docs-site/en/mcp.html +1 -1
- package/docs-site/en/permissions.html +1 -1
- package/docs-site/en/profiles.html +1 -1
- package/docs-site/en/quickstart.html +1 -1
- package/docs-site/en/runtime.html +1 -1
- package/docs-site/en/scope.html +1 -1
- package/docs-site/en/security.html +1 -1
- package/docs-site/en/team.html +1 -1
- package/docs-site/en/whats-new.html +1 -1
- package/docs-site/en/workflows.html +1 -1
- package/docs-site/index.html +1 -1
- package/docs-site/mcp-approval.html +1 -1
- package/docs-site/mcp-auth.html +1 -1
- package/docs-site/mcp-servers.html +1 -1
- package/docs-site/mcp.html +1 -1
- package/docs-site/permissions.html +1 -1
- package/docs-site/profiles.html +1 -1
- package/docs-site/quickstart.html +1 -1
- package/docs-site/runtime.html +1 -1
- package/docs-site/scope.html +1 -1
- package/docs-site/security.html +1 -1
- package/docs-site/team.html +1 -1
- package/docs-site/whats-new.html +1 -1
- package/docs-site/workflows.html +1 -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 +30 -3
- 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 +280 -0
- package/packages/piagent-core/capabilities/runtime-integrity.js +153 -1
- package/packages/piagent-core/extensions/document-intake.ts +24 -10
- package/packages/piagent-core/extensions/piagent-guard.ts +90 -73
- package/packages/piagent-core/extensions/redaction-core.d.ts +2 -0
- package/packages/piagent-core/extensions/state-retention.js +77 -44
- 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-server-catalog.js +5 -5
- 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 +5 -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 +68 -4
- 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 +13 -14
- 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-webui/dist/client/assets/index-DjMntaK5.js +172 -0
- package/packages/piagent-webui/dist/client/assets/index-DwKCWbwd.css +1 -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 +408 -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/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 +204 -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 +485 -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 +110 -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/check-architecture.mjs +1 -0
- package/scripts/check-doc-languages.mjs +19 -2
- package/scripts/check-third-party-neutrality.mjs +43 -0
- package/scripts/install-global.sh +1 -1
- package/scripts/piagent-cli.mjs +17 -3
- package/scripts/piagent-dashboard.mjs +208 -0
- package/scripts/piagent-webui-launcher.mjs +121 -0
- package/scripts/typescript-loader.mjs +26 -1
- package/scripts/verify-local.sh +253 -0
- package/scripts/verify-release-identity.mjs +4 -1
|
@@ -0,0 +1,500 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { webUiProjectRef, webUiSessionRef } from "../../piagent-core/runtime/inspection/webui-snapshot.ts";
|
|
5
|
+
export const WEBUI_CONTROL_ENTRY_TYPE = "piagent-webui-control-receipt-v1";
|
|
6
|
+
const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/, PUBLIC_REF = /^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/;
|
|
7
|
+
const REVISION = /^[A-Za-z0-9][A-Za-z0-9._:~-]{0,159}$/, DIGEST = /^sha256:[a-f0-9]{64}$/;
|
|
8
|
+
const IDEMPOTENCY = /^[A-Za-z0-9._~-]{32,128}$/;
|
|
9
|
+
const MAX_EVENTS = 256, MAX_SESSION_ENTRIES = 50_000; type NullableRef = string | null;
|
|
10
|
+
export type BridgeIdentity = { projectRef: string; runtimeInstanceId: string; sessionRef: string; taskId: string | null; taskRunId: string | null; agentOperationId: string | null; toolCallId: null };
|
|
11
|
+
export type BridgeRevisions = { runtimeRevision: string; taskRevision: NullableRef; controlRevision: NullableRef; workspaceRevision: NullableRef;
|
|
12
|
+
indexRevision: NullableRef; approvalRevision: NullableRef; sessionOptionRevision: NullableRef; queueRevision: NullableRef };
|
|
13
|
+
export type BridgeTaskFacts = { taskId: string; taskRunId: string; taskRevision: string; controlRevision: string;
|
|
14
|
+
controlState: "active" | "pause-requested" | "paused" | "terminal" | "unknown" } | null;
|
|
15
|
+
export type NewOperationChatCommand = {
|
|
16
|
+
schemaVersion: 1; version: "piagent-webui-control-v1"; messageType: "command"; commandId: string; idempotencyKey: string; requestedAt: string;
|
|
17
|
+
expiresAt: string; capabilityScope: "control.chat"; action: "chat.send"; actionDigest: string;
|
|
18
|
+
identity: BridgeIdentity; expectedRevisions: BridgeRevisions & { workspacePreimage: null; indexPreimage: null; patchPreimage: null };
|
|
19
|
+
payload: { messageRequestId: string; capabilityAction: "send"; delivery: "new-operation" | "follow-up" | "steer";
|
|
20
|
+
text: string; attachmentRefs: string[]; contentDigest: string };
|
|
21
|
+
};
|
|
22
|
+
export type ChatReceipt = {
|
|
23
|
+
schemaVersion: 1; version: "piagent-webui-control-v1"; messageType: "receipt"; commandId: string; idempotencyKeyDigest: string;
|
|
24
|
+
action: "chat.send"; actionDigest: string; identity: BridgeIdentity; phase: "requested" | "accepted" | "settled" | "rejected" | "uncertain";
|
|
25
|
+
resultCode: "dispatch-requested" | "dispatch-observed" | "dispatch-rejected" | "dispatch-unknown" | "identity-mismatch"
|
|
26
|
+
| "stale-revision" | "capability-unavailable" | "replay" | "idempotency-payload-mismatch" | "expired" | "invalid-command" | "resync-required";
|
|
27
|
+
requestedAt: string; settledAt: string | null; observedRevisionsBefore: BridgeRevisions; observedRevisionsAfter: BridgeRevisions; deduplicated: boolean;
|
|
28
|
+
auditRef: string | null; settlementEvidenceRef: string | null; error: { code: string; message: string; retryable: boolean } | null;
|
|
29
|
+
};
|
|
30
|
+
export type BridgeEvent = { sequence: number; at: string; kind: "binding.ready" | "binding.closed" | "operation.started" | "operation.settled" | "command.receipt";
|
|
31
|
+
sessionRef: string | null; operationRef: string | null; commandId: string | null; resultCode: string | null };
|
|
32
|
+
export type BridgeSnapshot = { state: "unbound" | "ready" | "replacement-pending" | "shutdown"; identity: BridgeIdentity | null; revisions: BridgeRevisions | null;
|
|
33
|
+
liveness: "idle" | "running" | "unknown"; taskState: "none" | "active" | "pause-requested" | "paused" | "terminal" | "unknown"; eventSequence: number };
|
|
34
|
+
export type SessionOptionMutationPermit = { commitObservation(record: (before: BridgeRevisions, after: BridgeRevisions) => void): { before: BridgeRevisions; after: BridgeRevisions; recorded: boolean } | null; release(): void };
|
|
35
|
+
type Binding = { ctx: ExtensionContext; rawSessionId: string; identity: BridgeIdentity; revisions: BridgeRevisions; state: BridgeSnapshot["state"] };
|
|
36
|
+
type SessionOptionPermitState = { token: number; generation: number; rawSessionId: string; before: BridgeRevisions; externalConflict: boolean };
|
|
37
|
+
type DispatchContent = Parameters<ExtensionAPI["sendUserMessage"]>[0];
|
|
38
|
+
type PreparedDispatch = { content: DispatchContent; observedText: string };
|
|
39
|
+
type PendingDispatch = { command: NewOperationChatCommand; operationId: string; before: BridgeRevisions; leafBefore: string | null; correlationToken: string;
|
|
40
|
+
observedText: string; resolve(receipt: ChatReceipt): void; timer: NodeJS.Timeout; inputObserved: boolean };
|
|
41
|
+
type Stored = { receipt: ChatReceipt; messageRequestId?: string; contentDigest?: string; attachmentRefs?: string[] };
|
|
42
|
+
function sha(value: string): string { return `sha256:${createHash("sha256").update(value).digest("hex")}`; }
|
|
43
|
+
function ref(prefix: string, value: unknown): string { return `${prefix}.${createHash("sha256").update(JSON.stringify(value)).digest("hex")}`; }
|
|
44
|
+
function canonical(value: unknown): string { if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`; if (!value || typeof value !== "object") return JSON.stringify(value);
|
|
45
|
+
return `{${Object.entries(value as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`; }
|
|
46
|
+
function copy<T>(value: T): T { return structuredClone(value); }
|
|
47
|
+
function same(left: unknown, right: unknown): boolean { return canonical(left) === canonical(right); }
|
|
48
|
+
function timestamp(value: unknown): value is string {
|
|
49
|
+
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) return false; const parsed = Date.parse(value);
|
|
50
|
+
return Number.isFinite(parsed) && new Date(parsed).toISOString() === value;
|
|
51
|
+
}
|
|
52
|
+
function exactKeys(value: unknown, expected: string[]): boolean {
|
|
53
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value) && same(Object.keys(value as Record<string, unknown>).sort(), [...expected].sort()));
|
|
54
|
+
}
|
|
55
|
+
function validRef(value: unknown): value is string { return typeof value === "string" && REF.test(value); }
|
|
56
|
+
function validPublicRef(value: unknown): value is string { return typeof value === "string" && PUBLIC_REF.test(value); }
|
|
57
|
+
function validRevision(value: unknown): value is string { return typeof value === "string" && REVISION.test(value); }
|
|
58
|
+
function validDigest(value: unknown): value is string { return typeof value === "string" && DIGEST.test(value); }
|
|
59
|
+
function validIdentity(value: unknown): value is BridgeIdentity {
|
|
60
|
+
if (!exactKeys(value, ["projectRef", "runtimeInstanceId", "sessionRef", "taskId", "taskRunId", "agentOperationId", "toolCallId"])) return false;
|
|
61
|
+
const identity = value as BridgeIdentity;
|
|
62
|
+
return validRef(identity.projectRef) && validRef(identity.runtimeInstanceId) && validRef(identity.sessionRef)
|
|
63
|
+
&& (identity.taskId === null || validPublicRef(identity.taskId)) && (identity.taskRunId === null || validPublicRef(identity.taskRunId))
|
|
64
|
+
&& (identity.taskRunId === null || identity.taskId !== null) && (identity.agentOperationId === null || validRef(identity.agentOperationId))
|
|
65
|
+
&& identity.toolCallId === null;
|
|
66
|
+
}
|
|
67
|
+
function validRevisions(value: unknown): value is BridgeRevisions {
|
|
68
|
+
if (!exactKeys(value, ["runtimeRevision", "taskRevision", "controlRevision", "workspaceRevision", "indexRevision", "approvalRevision", "sessionOptionRevision", "queueRevision"])) return false;
|
|
69
|
+
const revisions = value as BridgeRevisions;
|
|
70
|
+
return validRevision(revisions.runtimeRevision) && [revisions.taskRevision, revisions.controlRevision, revisions.workspaceRevision,
|
|
71
|
+
revisions.indexRevision, revisions.approvalRevision, revisions.sessionOptionRevision, revisions.queueRevision]
|
|
72
|
+
.every((item) => item === null || validRevision(item));
|
|
73
|
+
}
|
|
74
|
+
function validError(value: unknown): boolean {
|
|
75
|
+
return Boolean(exactKeys(value, ["code", "message", "retryable"]) && typeof (value as any).code === "string"
|
|
76
|
+
&& /^[a-z0-9][a-z0-9.-]{0,95}$/.test((value as any).code) && typeof (value as any).message === "string"
|
|
77
|
+
&& (value as any).message.length > 0 && (value as any).message.length <= 500 && typeof (value as any).retryable === "boolean");
|
|
78
|
+
}
|
|
79
|
+
function validReceipt(value: unknown): value is ChatReceipt {
|
|
80
|
+
if (!exactKeys(value, ["schemaVersion", "version", "messageType", "commandId", "idempotencyKeyDigest", "action", "actionDigest", "identity", "phase",
|
|
81
|
+
"resultCode", "requestedAt", "settledAt", "observedRevisionsBefore", "observedRevisionsAfter", "deduplicated", "auditRef", "settlementEvidenceRef", "error"])) return false;
|
|
82
|
+
const receipt = value as ChatReceipt;
|
|
83
|
+
if (receipt.schemaVersion !== 1 || receipt.version !== "piagent-webui-control-v1" || receipt.messageType !== "receipt" || receipt.action !== "chat.send"
|
|
84
|
+
|| !validRef(receipt.commandId) || !validDigest(receipt.idempotencyKeyDigest) || !validDigest(receipt.actionDigest) || !validIdentity(receipt.identity)
|
|
85
|
+
|| !timestamp(receipt.requestedAt) || !validRevisions(receipt.observedRevisionsBefore) || !validRevisions(receipt.observedRevisionsAfter)
|
|
86
|
+
|| typeof receipt.deduplicated !== "boolean" || receipt.auditRef !== null) return false;
|
|
87
|
+
if (receipt.phase === "requested") return receipt.resultCode === "dispatch-requested" && receipt.settledAt === null
|
|
88
|
+
&& receipt.settlementEvidenceRef === null && receipt.error === null && !receipt.deduplicated;
|
|
89
|
+
if (receipt.phase === "accepted") return receipt.resultCode === "dispatch-requested" && receipt.settledAt === null
|
|
90
|
+
&& receipt.settlementEvidenceRef === null && receipt.error === null && !receipt.deduplicated;
|
|
91
|
+
if (!timestamp(receipt.settledAt)) return false;
|
|
92
|
+
if (receipt.phase === "settled") return receipt.resultCode === "dispatch-observed" && validRef(receipt.identity.agentOperationId)
|
|
93
|
+
&& validRef(receipt.settlementEvidenceRef) && receipt.error === null;
|
|
94
|
+
if (receipt.phase === "uncertain") return receipt.resultCode === "dispatch-unknown" && receipt.settlementEvidenceRef === null && validError(receipt.error);
|
|
95
|
+
const rejected = new Set<ChatReceipt["resultCode"]>(["dispatch-rejected", "identity-mismatch", "stale-revision", "capability-unavailable", "replay",
|
|
96
|
+
"idempotency-payload-mismatch", "expired", "invalid-command", "resync-required"]);
|
|
97
|
+
return receipt.phase === "rejected" && rejected.has(receipt.resultCode) && receipt.settlementEvidenceRef === null && validError(receipt.error)
|
|
98
|
+
&& (receipt.resultCode !== "replay" || receipt.deduplicated);
|
|
99
|
+
}
|
|
100
|
+
function messageText(message: any): string {
|
|
101
|
+
return Array.isArray(message?.content) ? message.content.filter((item: any) => item?.type === "text").map((item: any) => String(item.text ?? "")).join("\n") : String(message?.content ?? "");
|
|
102
|
+
}
|
|
103
|
+
function firstMessageText(message: any): string { return Array.isArray(message?.content) ? String(message.content.find((item: any) => item?.type === "text")?.text ?? "") : String(message?.content ?? ""); }
|
|
104
|
+
function dispatchEntry(pending: PendingDispatch, ctx: ExtensionContext): any | null {
|
|
105
|
+
return ctx.sessionManager.getBranch().find((entry: any) => entry?.type === "message" && entry.parentId === pending.leafBefore
|
|
106
|
+
&& entry.message?.role === "user" && messageText(entry.message) === pending.observedText) ?? null;
|
|
107
|
+
}
|
|
108
|
+
export function chatContentDigest(payload: Pick<NewOperationChatCommand["payload"], "text" | "attachmentRefs">): string {
|
|
109
|
+
return sha(canonical({ text: payload.text, attachmentRefs: payload.attachmentRefs }));
|
|
110
|
+
}
|
|
111
|
+
export function controlActionDigest(command: { action: unknown; identity: unknown; expectedRevisions: unknown; payload: unknown }): string {
|
|
112
|
+
return sha(canonical({ action: command.action, identity: command.identity, expectedRevisions: command.expectedRevisions, payload: command.payload }));
|
|
113
|
+
}
|
|
114
|
+
export const chatActionDigest = controlActionDigest;
|
|
115
|
+
export class SameSessionPiBridge {
|
|
116
|
+
readonly #pi: ExtensionAPI;
|
|
117
|
+
readonly #runtimeInstanceId: string;
|
|
118
|
+
readonly #taskFacts: (ctx: ExtensionContext) => BridgeTaskFacts;
|
|
119
|
+
readonly #prepareAttachments: ((refs: string[], messageRequestId: string, identity: BridgeIdentity, text: string) => PreparedDispatch) | null;
|
|
120
|
+
readonly #now: () => Date;
|
|
121
|
+
#binding: Binding | null = null;
|
|
122
|
+
#generation = 0;
|
|
123
|
+
#queueCounter = 0;
|
|
124
|
+
#sessionOptionCounter = 0;
|
|
125
|
+
#sessionOptionPermit: SessionOptionPermitState | null = null;
|
|
126
|
+
#sessionOptionPermitCounter = 0;
|
|
127
|
+
#operationCounter = 0;
|
|
128
|
+
#pending: PendingDispatch | null = null;
|
|
129
|
+
readonly #dispatchContext = new AsyncLocalStorage<string>();
|
|
130
|
+
#receiptsByKey = new Map<string, ChatReceipt>();
|
|
131
|
+
#receiptsByCommand = new Map<string, ChatReceipt>();
|
|
132
|
+
#storedByKey = new Map<string, { messageRequestId: string; contentDigest: string; attachmentRefs: string[] }>();
|
|
133
|
+
#messageRequests = new Set<string>();
|
|
134
|
+
#serial: Promise<unknown> = Promise.resolve();
|
|
135
|
+
#events: BridgeEvent[] = [];
|
|
136
|
+
#sequence = 0;
|
|
137
|
+
readonly #listeners = new Set<(event: BridgeEvent) => void>();
|
|
138
|
+
constructor(pi: ExtensionAPI, options: { runtimeInstanceId: string; taskFacts?: (ctx: ExtensionContext) => BridgeTaskFacts; now?: () => Date;
|
|
139
|
+
prepareAttachments?: (refs: string[], messageRequestId: string, identity: BridgeIdentity, text: string) => PreparedDispatch }) {
|
|
140
|
+
if (!validRef(options.runtimeInstanceId)) throw new Error("webui-bridge-runtime-identity-invalid");
|
|
141
|
+
this.#pi = pi; this.#runtimeInstanceId = options.runtimeInstanceId; this.#taskFacts = options.taskFacts ?? (() => null);
|
|
142
|
+
this.#prepareAttachments = options.prepareAttachments ?? null; this.#now = options.now ?? (() => new Date());
|
|
143
|
+
}
|
|
144
|
+
#event(kind: BridgeEvent["kind"], details: Partial<Pick<BridgeEvent, "operationRef" | "commandId" | "resultCode">> = {}): void {
|
|
145
|
+
const event = { sequence: ++this.#sequence, at: this.#now().toISOString(), kind, sessionRef: this.#binding?.identity.sessionRef ?? null,
|
|
146
|
+
operationRef: details.operationRef ?? null, commandId: details.commandId ?? null, resultCode: details.resultCode ?? null } satisfies BridgeEvent;
|
|
147
|
+
this.#events.push(event); if (this.#events.length > MAX_EVENTS) this.#events.splice(0, this.#events.length - MAX_EVENTS);
|
|
148
|
+
for (const listener of this.#listeners) {
|
|
149
|
+
try { listener(copy(event)); } catch { /* observation is best-effort and never blocks authority settlement */ }
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
#revision(prefix: string, ...parts: unknown[]): string { return ref(prefix, [this.#runtimeInstanceId, this.#generation, ...parts]); }
|
|
153
|
+
#currentIdentity(ctx: ExtensionContext): BridgeIdentity {
|
|
154
|
+
const task = this.#taskFacts(ctx);
|
|
155
|
+
return { projectRef: webUiProjectRef(ctx.cwd), runtimeInstanceId: this.#runtimeInstanceId, sessionRef: webUiSessionRef(ctx.sessionManager.getSessionId()),
|
|
156
|
+
taskId: task?.taskId ?? null, taskRunId: task?.taskRunId ?? null, agentOperationId: this.#binding?.identity.agentOperationId ?? null, toolCallId: null };
|
|
157
|
+
}
|
|
158
|
+
#currentRevisions(ctx: ExtensionContext): BridgeRevisions {
|
|
159
|
+
const task = this.#taskFacts(ctx);
|
|
160
|
+
return { runtimeRevision: this.#revision("runtime-rev", ctx.cwd, ctx.sessionManager.getSessionId(), this.#operationCounter), taskRevision: task?.taskRevision ?? null,
|
|
161
|
+
controlRevision: task?.controlRevision ?? null, workspaceRevision: null, indexRevision: null, approvalRevision: null,
|
|
162
|
+
sessionOptionRevision: this.#revision("session-option-rev", ctx.sessionManager.getSessionId(), this.#sessionOptionCounter),
|
|
163
|
+
queueRevision: this.#revision("queue-rev", this.#queueCounter) };
|
|
164
|
+
}
|
|
165
|
+
#refresh(): void {
|
|
166
|
+
if (!this.#binding) return;
|
|
167
|
+
this.#binding.identity = this.#currentIdentity(this.#binding.ctx);
|
|
168
|
+
this.#binding.revisions = this.#currentRevisions(this.#binding.ctx);
|
|
169
|
+
}
|
|
170
|
+
#loadReceipts(ctx: ExtensionContext): void {
|
|
171
|
+
this.#receiptsByKey.clear(); this.#receiptsByCommand.clear(); this.#storedByKey.clear(); this.#messageRequests.clear();
|
|
172
|
+
const branch = ctx.sessionManager.getBranch();
|
|
173
|
+
if (!Array.isArray(branch) || branch.length > MAX_SESSION_ENTRIES) throw new Error("webui-bridge-receipt-history-unavailable");
|
|
174
|
+
const requested = new Map<string, { receipt: ChatReceipt; messageRequestId: string; contentDigest: string; attachmentRefs: string[]; entryId: string }>();
|
|
175
|
+
const entriesById = new Map(branch.map((entry: any) => [entry?.id, entry]));
|
|
176
|
+
for (const entry of branch) {
|
|
177
|
+
if (entry?.type !== "custom" || entry.customType !== WEBUI_CONTROL_ENTRY_TYPE) continue;
|
|
178
|
+
if (!exactKeys(entry.data, ["receipt"]) && !exactKeys(entry.data, ["receipt", "messageRequestId", "contentDigest"])
|
|
179
|
+
&& !exactKeys(entry.data, ["receipt", "messageRequestId", "contentDigest", "attachmentRefs"])) throw new Error("webui-bridge-receipt-store-corrupt");
|
|
180
|
+
const receipt = (entry.data as Stored).receipt;
|
|
181
|
+
const messageRequestId = (entry.data as Stored).messageRequestId;
|
|
182
|
+
const contentDigest = (entry.data as Stored).contentDigest;
|
|
183
|
+
const attachmentRefs = (entry.data as Stored).attachmentRefs ?? [];
|
|
184
|
+
if (!validReceipt(receipt) || !(messageRequestId === undefined || validRef(messageRequestId)) || !(contentDigest === undefined || validDigest(contentDigest)))
|
|
185
|
+
throw new Error("webui-bridge-receipt-store-corrupt");
|
|
186
|
+
if (!Array.isArray(attachmentRefs) || attachmentRefs.length > 4 || attachmentRefs.some((item) => !validRef(item))) throw new Error("webui-bridge-receipt-store-corrupt");
|
|
187
|
+
if (receipt.identity.runtimeInstanceId !== this.#runtimeInstanceId || receipt.identity.sessionRef !== webUiSessionRef(ctx.sessionManager.getSessionId())) continue;
|
|
188
|
+
if (attachmentRefs.length > 0) continue; // bytes are not persisted; proof is runtime-lifetime only
|
|
189
|
+
if (receipt.resultCode === "idempotency-payload-mismatch") continue;
|
|
190
|
+
const requestKey = `${receipt.commandId}\0${receipt.idempotencyKeyDigest}`;
|
|
191
|
+
if (receipt.phase === "requested") {
|
|
192
|
+
if (!messageRequestId || !contentDigest || !validRef(entry.id) || requested.has(requestKey)) throw new Error("webui-bridge-receipt-store-corrupt");
|
|
193
|
+
requested.set(requestKey, { receipt, messageRequestId, contentDigest, attachmentRefs, entryId: entry.id });
|
|
194
|
+
} else if (receipt.resultCode === "dispatch-observed" || receipt.resultCode === "dispatch-unknown" || receipt.phase === "accepted") {
|
|
195
|
+
const prior = requested.get(requestKey);
|
|
196
|
+
if (!prior || !messageRequestId || !contentDigest || messageRequestId !== prior.messageRequestId || contentDigest !== prior.contentDigest || receipt.actionDigest !== prior.receipt.actionDigest
|
|
197
|
+
|| receipt.requestedAt !== prior.receipt.requestedAt || !same(receipt.observedRevisionsBefore, prior.receipt.observedRevisionsBefore)
|
|
198
|
+
|| !same(receipt.identity, prior.receipt.identity) || !same(attachmentRefs, prior.attachmentRefs)) throw new Error("webui-bridge-receipt-store-corrupt");
|
|
199
|
+
if (receipt.resultCode === "dispatch-observed") {
|
|
200
|
+
const evidence = entriesById.get(receipt.settlementEvidenceRef as string) as any;
|
|
201
|
+
if (!evidence || evidence.type !== "message" || evidence.parentId !== prior.entryId || evidence.message?.role !== "user"
|
|
202
|
+
|| chatContentDigest({ text: firstMessageText(evidence.message), attachmentRefs: prior.attachmentRefs }) !== prior.contentDigest) throw new Error("webui-bridge-receipt-store-corrupt");
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
this.#receiptsByKey.set(receipt.idempotencyKeyDigest, copy(receipt)); this.#receiptsByCommand.set(receipt.commandId, copy(receipt));
|
|
206
|
+
if (messageRequestId && contentDigest) {
|
|
207
|
+
this.#messageRequests.add(messageRequestId); this.#storedByKey.set(receipt.idempotencyKeyDigest, { messageRequestId, contentDigest, attachmentRefs });
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
bind(ctx: ExtensionContext): void {
|
|
212
|
+
const rawSessionId = ctx.sessionManager.getSessionId();
|
|
213
|
+
if (typeof rawSessionId !== "string" || !rawSessionId || !validRef(this.#runtimeInstanceId)) throw new Error("webui-bridge-identity-unavailable");
|
|
214
|
+
if (this.#pending) this.#settlePending("dispatch-unknown", "uncertain", "session-rebound-before-dispatch-observation", false);
|
|
215
|
+
this.#generation += 1; this.#queueCounter = 0; this.#sessionOptionCounter = 0; this.#sessionOptionPermit = null;
|
|
216
|
+
this.#operationCounter = 0; this.#pending = null;
|
|
217
|
+
this.#binding = { ctx, rawSessionId, state: "ready", identity: {} as BridgeIdentity, revisions: {} as BridgeRevisions };
|
|
218
|
+
try { this.#refresh(); this.#loadReceipts(ctx); this.#event("binding.ready"); }
|
|
219
|
+
catch (error) { this.#binding = null; throw error; }
|
|
220
|
+
}
|
|
221
|
+
refresh(ctx: ExtensionContext): boolean {
|
|
222
|
+
if (!this.#binding || this.#binding.rawSessionId !== ctx.sessionManager.getSessionId() || this.#binding.identity.projectRef !== webUiProjectRef(ctx.cwd)) return false;
|
|
223
|
+
this.#binding.ctx = ctx; this.#refresh(); return true;
|
|
224
|
+
}
|
|
225
|
+
replacementPending(): void {
|
|
226
|
+
if (!this.#binding) return;
|
|
227
|
+
this.#binding.state = "replacement-pending";
|
|
228
|
+
if (this.#pending) this.#settlePending("dispatch-unknown", "uncertain", "session-replacement-before-dispatch-observation", false);
|
|
229
|
+
this.#event("binding.closed", { resultCode: "replacement-pending" });
|
|
230
|
+
}
|
|
231
|
+
revalidateUnchangedSession(ctx: ExtensionContext): boolean {
|
|
232
|
+
if (!this.#binding || this.#binding.state !== "replacement-pending"
|
|
233
|
+
|| this.#binding.rawSessionId !== ctx.sessionManager.getSessionId()
|
|
234
|
+
|| this.#binding.identity.projectRef !== webUiProjectRef(ctx.cwd)) return false;
|
|
235
|
+
this.#generation += 1; this.#binding.ctx = ctx; this.#binding.state = "ready"; this.#refresh();
|
|
236
|
+
this.#event("binding.ready", { resultCode: "replacement-cancelled-or-failed" }); return true;
|
|
237
|
+
}
|
|
238
|
+
shutdown(ctx?: ExtensionContext): void {
|
|
239
|
+
if (!this.#binding || ctx && this.#binding.rawSessionId !== ctx.sessionManager.getSessionId()) return;
|
|
240
|
+
if (this.#pending) this.#settlePending("dispatch-unknown", "uncertain", "session-shutdown-before-dispatch-observation", false);
|
|
241
|
+
this.#sessionOptionPermit = null; this.#binding.state = "shutdown"; this.#event("binding.closed", { resultCode: "shutdown" }); this.#binding = null;
|
|
242
|
+
}
|
|
243
|
+
snapshot(): BridgeSnapshot {
|
|
244
|
+
if (!this.#binding) return { state: "unbound", identity: null, revisions: null, liveness: "unknown", taskState: "none", eventSequence: this.#sequence };
|
|
245
|
+
this.#refresh();
|
|
246
|
+
const task = this.#taskFacts(this.#binding.ctx);
|
|
247
|
+
return { state: this.#binding.state, identity: copy(this.#binding.identity), revisions: copy(this.#binding.revisions),
|
|
248
|
+
liveness: this.#binding.identity.agentOperationId ? "running" : this.#binding.ctx.isIdle() ? "idle" : "unknown",
|
|
249
|
+
taskState: task?.controlState ?? "none", eventSequence: this.#sequence };
|
|
250
|
+
}
|
|
251
|
+
events(after = 0): { state: "current" | "resync-required"; events: BridgeEvent[]; latestSequence: number } {
|
|
252
|
+
const first = this.#events[0]?.sequence ?? this.#sequence + 1;
|
|
253
|
+
return { state: after > 0 && after < first - 1 ? "resync-required" : "current", events: this.#events.filter((event) => event.sequence > after).map(copy), latestSequence: this.#sequence };
|
|
254
|
+
}
|
|
255
|
+
subscribe(listener: (event: BridgeEvent) => void): () => void { this.#listeners.add(listener); return () => this.#listeners.delete(listener); }
|
|
256
|
+
commitQueueMutation(record: (before: BridgeRevisions, after: BridgeRevisions) => void): { before: BridgeRevisions; after: BridgeRevisions } | null {
|
|
257
|
+
if (!this.#binding || this.#binding.state !== "ready") return null;
|
|
258
|
+
this.#refresh();
|
|
259
|
+
const before = copy(this.#binding.revisions), previousCounter = this.#queueCounter;
|
|
260
|
+
this.#queueCounter += 1; this.#refresh();
|
|
261
|
+
const after = copy(this.#binding.revisions);
|
|
262
|
+
try { record(copy(before), copy(after)); }
|
|
263
|
+
catch { this.#queueCounter = previousCounter; this.#refresh(); return null; }
|
|
264
|
+
return { before, after };
|
|
265
|
+
}
|
|
266
|
+
#commitSessionOptionObservation(permit: SessionOptionPermitState,
|
|
267
|
+
record: (before: BridgeRevisions, after: BridgeRevisions) => void): {
|
|
268
|
+
before: BridgeRevisions; after: BridgeRevisions; recorded: boolean;
|
|
269
|
+
} | null {
|
|
270
|
+
if (!this.#binding || this.#binding.state !== "ready" || !this.#sessionOptionPermit
|
|
271
|
+
|| !same(this.#sessionOptionPermit, permit) || permit.generation !== this.#generation || permit.rawSessionId !== this.#binding.rawSessionId) return null;
|
|
272
|
+
this.#refresh();
|
|
273
|
+
const before = copy(permit.before);
|
|
274
|
+
if (!permit.externalConflict) { this.#sessionOptionCounter += 1; this.#refresh(); }
|
|
275
|
+
const after = copy(this.#binding.revisions); if (permit.externalConflict) return { before, after, recorded: false };
|
|
276
|
+
try { record(copy(before), copy(after)); return { before, after, recorded: true }; }
|
|
277
|
+
catch { return { before, after, recorded: false }; }
|
|
278
|
+
}
|
|
279
|
+
beginSessionOptionMutation(): SessionOptionMutationPermit | null {
|
|
280
|
+
if (!this.#binding || this.#binding.state !== "ready" || this.#sessionOptionPermit || this.#pending
|
|
281
|
+
|| this.#binding.identity.agentOperationId || !this.#binding.ctx.isIdle()
|
|
282
|
+
|| (this.#taskFacts(this.#binding.ctx)?.controlState ?? "active") !== "active"
|
|
283
|
+
|| (typeof this.#binding.ctx.hasPendingMessages === "function" && this.#binding.ctx.hasPendingMessages())) return null;
|
|
284
|
+
this.#refresh();
|
|
285
|
+
const permit = { token: ++this.#sessionOptionPermitCounter, generation: this.#generation, rawSessionId: this.#binding.rawSessionId,
|
|
286
|
+
before: copy(this.#binding.revisions), externalConflict: false };
|
|
287
|
+
this.#sessionOptionPermit = permit;
|
|
288
|
+
return {
|
|
289
|
+
commitObservation: (record) => this.#commitSessionOptionObservation(permit, record),
|
|
290
|
+
release: () => { if (this.#sessionOptionPermit && same(this.#sessionOptionPermit, permit)) this.#sessionOptionPermit = null; }
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
sessionOptionMutationActive(ctx?: ExtensionContext): boolean {
|
|
294
|
+
return Boolean(this.#sessionOptionPermit) && Boolean(this.#binding && (!ctx
|
|
295
|
+
|| this.#binding.rawSessionId === ctx.sessionManager.getSessionId() && this.#binding.identity.projectRef === webUiProjectRef(ctx.cwd)));
|
|
296
|
+
}
|
|
297
|
+
observeSessionOptionChange(ctx: ExtensionContext, causal = false): boolean {
|
|
298
|
+
if (!this.refresh(ctx) || !this.#binding || !["ready", "replacement-pending"].includes(this.#binding.state)) return false;
|
|
299
|
+
this.#sessionOptionCounter += 1;
|
|
300
|
+
if (!causal && this.#sessionOptionPermit?.rawSessionId === this.#binding.rawSessionId) this.#sessionOptionPermit.externalConflict = true;
|
|
301
|
+
this.#refresh(); return true;
|
|
302
|
+
}
|
|
303
|
+
observeInput(event: { source?: unknown; text?: unknown }, ctx: ExtensionContext): void {
|
|
304
|
+
if ((event.source === "interactive" || event.source === "rpc") && this.#binding?.state === "replacement-pending") {
|
|
305
|
+
this.revalidateUnchangedSession(ctx);
|
|
306
|
+
}
|
|
307
|
+
if (!this.refresh(ctx) || this.#binding?.state !== "ready") return; const pending = this.#pending;
|
|
308
|
+
if (pending && event.source === "extension" && event.text === pending.observedText
|
|
309
|
+
&& this.#dispatchContext.getStore() === pending.correlationToken) {
|
|
310
|
+
pending.inputObserved = true;
|
|
311
|
+
if (pending.command.payload.delivery !== "new-operation") this.#acceptPending();
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
observeMessageStart(event: { message?: unknown }, ctx: ExtensionContext): void {
|
|
315
|
+
if (!this.refresh(ctx) || this.#binding?.state !== "ready") return; const pending = this.#pending, message = event.message as any;
|
|
316
|
+
const leaf = pending ? ctx.sessionManager.getLeafEntry?.() : null;
|
|
317
|
+
const leafObserved = Boolean(pending && leaf?.type === "message" && leaf.id !== pending.leafBefore && leaf.parentId === pending.leafBefore && leaf.message?.role === "user"
|
|
318
|
+
&& messageText(leaf.message) === pending.observedText);
|
|
319
|
+
if (pending && pending.inputObserved && leafObserved && message?.role === "user" && messageText(message) === pending.observedText)
|
|
320
|
+
this.#settlePending("dispatch-observed", "settled", null, true, leaf.id);
|
|
321
|
+
}
|
|
322
|
+
observeAgentStart(ctx: ExtensionContext): void {
|
|
323
|
+
if (!this.refresh(ctx) || !this.#binding || this.#binding.state !== "ready") return;
|
|
324
|
+
const pending = this.#pending;
|
|
325
|
+
const operationId = pending?.operationId ?? this.#revision("operation", ++this.#operationCounter, "external");
|
|
326
|
+
this.#binding.identity.agentOperationId = operationId; this.#refresh(); this.#event("operation.started", { operationRef: operationId, commandId: pending?.command.commandId });
|
|
327
|
+
const observedEntry = pending ? dispatchEntry(pending, ctx) : null;
|
|
328
|
+
const messageObserved = Boolean(observedEntry);
|
|
329
|
+
if (pending && pending.inputObserved && messageObserved) this.#settlePending("dispatch-observed", "settled", null, true, observedEntry.id);
|
|
330
|
+
}
|
|
331
|
+
observeAgentSettled(ctx: ExtensionContext): void {
|
|
332
|
+
if (!this.refresh(ctx) || !this.#binding || this.#binding.state !== "ready") return;
|
|
333
|
+
const operationId = this.#binding.identity.agentOperationId;
|
|
334
|
+
if (this.#pending) {
|
|
335
|
+
const observedEntry = dispatchEntry(this.#pending, ctx);
|
|
336
|
+
if (this.#pending.inputObserved && observedEntry) this.#settlePending("dispatch-observed", "settled", null, true, observedEntry.id);
|
|
337
|
+
else this.#settlePending("dispatch-unknown", "uncertain", "agent-settled-without-dispatch-observation", false);
|
|
338
|
+
}
|
|
339
|
+
this.#binding.identity.agentOperationId = null; this.#operationCounter += 1; this.#refresh(); this.#event("operation.settled", { operationRef: operationId });
|
|
340
|
+
}
|
|
341
|
+
execute(command: NewOperationChatCommand): Promise<ChatReceipt> {
|
|
342
|
+
const run = this.#serial.then(() => this.#execute(command), () => this.#execute(command));
|
|
343
|
+
this.#serial = run.catch(() => undefined); return run;
|
|
344
|
+
}
|
|
345
|
+
async #execute(command: NewOperationChatCommand): Promise<ChatReceipt> {
|
|
346
|
+
const binding = this.#binding, now = this.#now();
|
|
347
|
+
const structural = this.#validate(command);
|
|
348
|
+
if (!binding || binding.state !== "ready") return this.#rejection(command, "resync-required", "bridge-binding-not-ready", "The current Pi session binding is unavailable.");
|
|
349
|
+
this.#refresh();
|
|
350
|
+
if (structural) return this.#rejection(command, "invalid-command", structural, "The chat command is invalid.");
|
|
351
|
+
const keyDigest = sha(command.idempotencyKey), oldByKey = this.#receiptsByKey.get(keyDigest), oldByCommand = this.#receiptsByCommand.get(command.commandId);
|
|
352
|
+
if (oldByKey || oldByCommand) {
|
|
353
|
+
const old = oldByKey ?? oldByCommand!;
|
|
354
|
+
if (old.actionDigest !== command.actionDigest || old.commandId !== command.commandId || old.idempotencyKeyDigest !== keyDigest)
|
|
355
|
+
return this.#rejection(command, "idempotency-payload-mismatch", "idempotency-payload-mismatch", "The command key was already bound to a different payload.");
|
|
356
|
+
if (old.phase === "requested") {
|
|
357
|
+
const stored = this.#storedByKey.get(old.idempotencyKeyDigest);
|
|
358
|
+
if (!stored) return this.#rejection(command, "resync-required", "receipt-history-unavailable", "The requested dispatch cannot be reconciled.");
|
|
359
|
+
const uncertain = { ...copy(old), phase: "uncertain" as const, resultCode: "dispatch-unknown" as const, settledAt: this.#now().toISOString(),
|
|
360
|
+
observedRevisionsAfter: copy(this.#binding.revisions), deduplicated: false, settlementEvidenceRef: null,
|
|
361
|
+
error: { code: "dispatch-acknowledgement-ambiguous", message: "A prior dispatch may have started; automatic resend is disabled.", retryable: false } };
|
|
362
|
+
this.#record(uncertain, stored.messageRequestId, stored.contentDigest, stored.attachmentRefs); return uncertain;
|
|
363
|
+
}
|
|
364
|
+
return { ...copy(old), deduplicated: true };
|
|
365
|
+
}
|
|
366
|
+
if (Date.parse(command.requestedAt) > now.getTime() + 30_000) return this.#rejection(command, "invalid-command", "requested-at-in-future", "The chat command timestamp is not yet valid.");
|
|
367
|
+
if (now.getTime() > Date.parse(command.expiresAt)) return this.#rejection(command, "expired", "command-expired", "The chat command expired before dispatch.");
|
|
368
|
+
if (!same(command.identity, binding.identity)) return this.#rejection(command, "identity-mismatch", "identity-mismatch", "The command does not target the current Pi session.");
|
|
369
|
+
if (command.expectedRevisions.runtimeRevision !== binding.revisions.runtimeRevision || command.expectedRevisions.queueRevision !== binding.revisions.queueRevision
|
|
370
|
+
|| command.expectedRevisions.taskRevision !== binding.revisions.taskRevision || command.expectedRevisions.controlRevision !== binding.revisions.controlRevision)
|
|
371
|
+
return this.#rejection(command, "stale-revision", "stale-revision", "The current Pi session changed before dispatch.");
|
|
372
|
+
if (this.#sessionOptionPermit)
|
|
373
|
+
return this.#rejection(command, "capability-unavailable", "session-option-change-in-progress", "A model or thinking change is being settled.");
|
|
374
|
+
const controlState = this.#taskFacts(binding.ctx)?.controlState;
|
|
375
|
+
if (controlState && controlState !== "active")
|
|
376
|
+
return this.#rejection(command, "capability-unavailable", controlState === "terminal" ? "task-terminal" : "task-control-gate-closed",
|
|
377
|
+
controlState === "terminal" ? "A completed task cannot accept another dispatch." : "Task lifecycle control currently blocks dispatch.");
|
|
378
|
+
const delivery = command.payload.delivery;
|
|
379
|
+
if (delivery === "new-operation" && (!binding.ctx.isIdle() || binding.identity.agentOperationId))
|
|
380
|
+
return this.#rejection(command, "dispatch-rejected", "agent-not-idle", "A new operation can start only while the Pi session is idle.");
|
|
381
|
+
if (delivery !== "new-operation" && (binding.ctx.isIdle() || !binding.identity.agentOperationId))
|
|
382
|
+
return this.#rejection(command, "dispatch-rejected", "agent-not-running", "Follow-up and Interrupt & Send require the current Pi operation to be running.");
|
|
383
|
+
if (this.#messageRequests.has(command.payload.messageRequestId)) return this.#rejection(command, "replay", "message-request-replay", "This message request was already accepted.");
|
|
384
|
+
let prepared: PreparedDispatch = { content: command.payload.text, observedText: command.payload.text };
|
|
385
|
+
if (command.payload.attachmentRefs.length > 0) {
|
|
386
|
+
if (!this.#prepareAttachments) return this.#rejection(command, "capability-unavailable", "attachments-unavailable", "Attachments are unavailable.");
|
|
387
|
+
try { prepared = this.#prepareAttachments(command.payload.attachmentRefs, command.payload.messageRequestId, command.identity, command.payload.text); }
|
|
388
|
+
catch { return this.#rejection(command, "dispatch-rejected", "attachment-reference-unavailable", "One or more staged attachments are unavailable."); }
|
|
389
|
+
}
|
|
390
|
+
const operationId = delivery === "new-operation"
|
|
391
|
+
? this.#revision("operation", ++this.#operationCounter, command.commandId, command.actionDigest)
|
|
392
|
+
: binding.identity.agentOperationId as string;
|
|
393
|
+
if (delivery === "new-operation") binding.identity.agentOperationId = operationId;
|
|
394
|
+
this.#queueCounter += 1; const before = copy(binding.revisions); this.#refresh();
|
|
395
|
+
const requested = this.#receipt(command, before, "requested", "dispatch-requested", null, false, operationId);
|
|
396
|
+
if (!this.#record(requested, command.payload.messageRequestId, command.payload.contentDigest, command.payload.attachmentRefs)) {
|
|
397
|
+
if (delivery === "new-operation") {
|
|
398
|
+
binding.identity.agentOperationId = null; this.#operationCounter += 1; this.#refresh();
|
|
399
|
+
}
|
|
400
|
+
return this.#rejection(command, "capability-unavailable", "receipt-store-unavailable", "The durable session receipt store is unavailable.", "rejected", false);
|
|
401
|
+
}
|
|
402
|
+
this.#messageRequests.add(command.payload.messageRequestId);
|
|
403
|
+
return new Promise<ChatReceipt>((resolve) => {
|
|
404
|
+
const timer = setTimeout(() => this.#settlePending("dispatch-unknown", "uncertain", "dispatch-observation-timeout", false), 5_000); timer.unref();
|
|
405
|
+
const correlationToken = `correlation.${randomBytes(24).toString("hex")}`;
|
|
406
|
+
this.#pending = { command: copy(command), operationId, before, leafBefore: binding.ctx.sessionManager.getLeafId?.() ?? null,
|
|
407
|
+
correlationToken, observedText: prepared.observedText, resolve, timer, inputObserved: false };
|
|
408
|
+
try { this.#dispatchContext.run(correlationToken, () => this.#pi.sendUserMessage(prepared.content,
|
|
409
|
+
delivery === "new-operation" ? undefined : { deliverAs: delivery === "steer" ? "steer" : "followUp" })); }
|
|
410
|
+
catch { this.#settlePending("dispatch-rejected", "rejected", "pi-send-user-message-rejected", false); }
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
#validate(command: NewOperationChatCommand): string | null {
|
|
414
|
+
if (!command || typeof command !== "object" || command.schemaVersion !== 1 || command.version !== "piagent-webui-control-v1"
|
|
415
|
+
|| command.messageType !== "command" || command.action !== "chat.send" || command.capabilityScope !== "control.chat") return "unsupported-command-shape";
|
|
416
|
+
if (!exactKeys(command, ["schemaVersion", "version", "messageType", "commandId", "idempotencyKey", "requestedAt", "expiresAt", "capabilityScope", "action", "actionDigest", "identity", "expectedRevisions", "payload"])
|
|
417
|
+
|| !exactKeys(command.identity, ["projectRef", "runtimeInstanceId", "sessionRef", "taskId", "taskRunId", "agentOperationId", "toolCallId"])
|
|
418
|
+
|| !exactKeys(command.expectedRevisions, ["runtimeRevision", "taskRevision", "controlRevision", "workspaceRevision", "indexRevision", "approvalRevision", "sessionOptionRevision", "queueRevision", "workspacePreimage", "indexPreimage", "patchPreimage"])
|
|
419
|
+
|| !exactKeys(command.payload, ["messageRequestId", "capabilityAction", "delivery", "text", "attachmentRefs", "contentDigest"])) return "unknown-command-field";
|
|
420
|
+
if (!validRef(command.commandId) || typeof command.idempotencyKey !== "string" || !IDEMPOTENCY.test(command.idempotencyKey)
|
|
421
|
+
|| !timestamp(command.requestedAt) || !timestamp(command.expiresAt)
|
|
422
|
+
|| Date.parse(command.requestedAt) > Date.parse(command.expiresAt) || Date.parse(command.expiresAt) - Date.parse(command.requestedAt) > 300_000) return "invalid-command-metadata";
|
|
423
|
+
const revisions = command.expectedRevisions;
|
|
424
|
+
if (!validIdentity(command.identity) || !validRevision(revisions.runtimeRevision) || !validRevision(revisions.queueRevision)
|
|
425
|
+
|| ![revisions.taskRevision, revisions.controlRevision, revisions.workspaceRevision, revisions.indexRevision, revisions.approvalRevision, revisions.sessionOptionRevision]
|
|
426
|
+
.every((value) => value === null || validRevision(value)) || revisions.workspacePreimage !== null || revisions.indexPreimage !== null || revisions.patchPreimage !== null)
|
|
427
|
+
return "invalid-authority-binding";
|
|
428
|
+
const payload = command.payload;
|
|
429
|
+
if (!payload || !validRef(payload.messageRequestId) || !["new-operation", "follow-up", "steer"].includes(payload.delivery)
|
|
430
|
+
|| payload.capabilityAction !== (payload.delivery === "steer" ? "interruptAndSend" : "send")
|
|
431
|
+
|| typeof payload.text !== "string" || payload.text.length < 1 || Buffer.byteLength(payload.text) > 65_536 || payload.text.includes("\0")
|
|
432
|
+
|| !Array.isArray(payload.attachmentRefs) || payload.attachmentRefs.length > 4 || new Set(payload.attachmentRefs).size !== payload.attachmentRefs.length
|
|
433
|
+
|| payload.attachmentRefs.some((item) => !validRef(item)) || payload.contentDigest !== chatContentDigest(payload)) return "invalid-message-payload";
|
|
434
|
+
if (!validDigest(command.actionDigest) || command.actionDigest !== controlActionDigest(command)) return "action-digest-mismatch";
|
|
435
|
+
return null;
|
|
436
|
+
}
|
|
437
|
+
#receipt(command: NewOperationChatCommand, before: BridgeRevisions, phase: ChatReceipt["phase"], resultCode: ChatReceipt["resultCode"], reason: string | null,
|
|
438
|
+
deduplicated: boolean, operationId: string | null, settlementEvidenceRef: string | null = null): ChatReceipt {
|
|
439
|
+
const terminal = phase !== "requested" && phase !== "accepted", settledAt = terminal ? this.#now().toISOString() : null;
|
|
440
|
+
const identity = { ...command.identity, agentOperationId: operationId };
|
|
441
|
+
return { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "receipt", commandId: command.commandId,
|
|
442
|
+
idempotencyKeyDigest: sha(command.idempotencyKey), action: "chat.send", actionDigest: command.actionDigest, identity,
|
|
443
|
+
phase, resultCode, requestedAt: command.requestedAt, settledAt, observedRevisionsBefore: copy(before),
|
|
444
|
+
observedRevisionsAfter: copy(this.#binding?.revisions ?? before), deduplicated, auditRef: null,
|
|
445
|
+
settlementEvidenceRef: phase === "settled" ? settlementEvidenceRef : null,
|
|
446
|
+
error: phase === "rejected" || phase === "uncertain" ? { code: reason ?? resultCode, message: reason ? reason.replace(/-/g, " ") : resultCode, retryable: false } : null };
|
|
447
|
+
}
|
|
448
|
+
#rejection(command: NewOperationChatCommand, resultCode: ChatReceipt["resultCode"], reason: string, message: string,
|
|
449
|
+
phase: "rejected" | "uncertain" = "rejected", persist = true): ChatReceipt {
|
|
450
|
+
const fallback = this.#binding?.revisions ?? { runtimeRevision: ref("runtime-rev", "unbound"), taskRevision: null, controlRevision: null,
|
|
451
|
+
workspaceRevision: null, indexRevision: null, approvalRevision: null, sessionOptionRevision: null, queueRevision: null };
|
|
452
|
+
const safe = command && typeof command === "object" ? command : {} as NewOperationChatCommand;
|
|
453
|
+
const safeIdentity = validIdentity(safe.identity) ? copy(safe.identity) : copy(this.#binding?.identity ?? { projectRef: ref("project", "unbound"), runtimeInstanceId: this.#runtimeInstanceId,
|
|
454
|
+
sessionRef: ref("session", "unbound"), taskId: null, taskRunId: null, agentOperationId: null, toolCallId: null });
|
|
455
|
+
const safeCommand = { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "command",
|
|
456
|
+
commandId: validRef(safe.commandId) ? safe.commandId : ref("command", reason),
|
|
457
|
+
idempotencyKey: typeof safe.idempotencyKey === "string" && IDEMPOTENCY.test(safe.idempotencyKey) ? safe.idempotencyKey : "invalid-command-key-0000000000000000",
|
|
458
|
+
requestedAt: timestamp(safe.requestedAt) ? safe.requestedAt : this.#now().toISOString(), expiresAt: this.#now().toISOString(),
|
|
459
|
+
capabilityScope: "control.chat", action: "chat.send", actionDigest: validDigest(safe.actionDigest) ? safe.actionDigest : sha(reason),
|
|
460
|
+
identity: safeIdentity, expectedRevisions: { ...fallback, workspacePreimage: null, indexPreimage: null, patchPreimage: null },
|
|
461
|
+
payload: { messageRequestId: ref("message-request", reason), capabilityAction: "send", delivery: "new-operation", text: "invalid", attachmentRefs: [], contentDigest: sha("invalid") }
|
|
462
|
+
} as NewOperationChatCommand;
|
|
463
|
+
const receipt = { ...this.#receipt(safeCommand,
|
|
464
|
+
fallback, phase, resultCode, reason, resultCode === "replay", validIdentity(safe.identity) ? safe.identity.agentOperationId : null),
|
|
465
|
+
error: { code: reason, message, retryable: false } };
|
|
466
|
+
if (persist) this.#record(receipt); return receipt;
|
|
467
|
+
}
|
|
468
|
+
#record(receipt: ChatReceipt, messageRequestId?: string, contentDigest?: string, attachmentRefs: string[] = []): boolean {
|
|
469
|
+
try { this.#pi.appendEntry(WEBUI_CONTROL_ENTRY_TYPE, { receipt: copy(receipt), ...(messageRequestId && contentDigest ? { messageRequestId, contentDigest,
|
|
470
|
+
...(attachmentRefs.length ? { attachmentRefs: copy(attachmentRefs) } : {}) } : {}) } satisfies Stored); }
|
|
471
|
+
catch { return false; }
|
|
472
|
+
if (receipt.resultCode !== "idempotency-payload-mismatch") {
|
|
473
|
+
this.#receiptsByKey.set(receipt.idempotencyKeyDigest, copy(receipt)); this.#receiptsByCommand.set(receipt.commandId, copy(receipt));
|
|
474
|
+
if (messageRequestId && contentDigest) this.#storedByKey.set(receipt.idempotencyKeyDigest, { messageRequestId, contentDigest, attachmentRefs: copy(attachmentRefs) });
|
|
475
|
+
}
|
|
476
|
+
this.#event("command.receipt", { operationRef: receipt.identity.agentOperationId, commandId: receipt.commandId, resultCode: receipt.resultCode });
|
|
477
|
+
return true;
|
|
478
|
+
}
|
|
479
|
+
#settlePending(resultCode: "dispatch-observed" | "dispatch-rejected" | "dispatch-unknown", phase: "settled" | "rejected" | "uncertain", reason: string | null,
|
|
480
|
+
observed: boolean, evidenceRef: unknown = null): void {
|
|
481
|
+
const pending = this.#pending; if (!pending) return; clearTimeout(pending.timer); this.#pending = null;
|
|
482
|
+
if (!this.#binding) return pending.resolve(this.#rejection(pending.command, "dispatch-unknown", reason ?? "bridge-unbound", "Dispatch settlement is unavailable.", "uncertain"));
|
|
483
|
+
const exactEvidenceRef = validRef(evidenceRef) ? evidenceRef : null;
|
|
484
|
+
if (phase === "settled" && !exactEvidenceRef) { phase = "uncertain"; resultCode = "dispatch-unknown"; reason = "settlement-evidence-unavailable"; observed = false; }
|
|
485
|
+
if (!observed && pending.command.payload.delivery === "new-operation") {
|
|
486
|
+
this.#binding.identity.agentOperationId = null; this.#operationCounter += 1; this.#refresh();
|
|
487
|
+
}
|
|
488
|
+
const receipt = this.#receipt(pending.command, pending.before, phase, resultCode, reason, false, pending.operationId, exactEvidenceRef);
|
|
489
|
+
if (this.#record(receipt, pending.command.payload.messageRequestId, pending.command.payload.contentDigest, pending.command.payload.attachmentRefs)) pending.resolve(receipt);
|
|
490
|
+
else pending.resolve(this.#receipt(pending.command, pending.before, "uncertain", "dispatch-unknown", "settlement-receipt-store-unavailable", false, pending.operationId));
|
|
491
|
+
}
|
|
492
|
+
#acceptPending(): void {
|
|
493
|
+
const pending = this.#pending; if (!pending) return;
|
|
494
|
+
clearTimeout(pending.timer); this.#pending = null;
|
|
495
|
+
if (!this.#binding) return pending.resolve(this.#rejection(pending.command, "dispatch-unknown", "bridge-unbound", "Dispatch acceptance is unavailable.", "uncertain"));
|
|
496
|
+
const receipt = this.#receipt(pending.command, pending.before, "accepted", "dispatch-requested", null, false, pending.operationId);
|
|
497
|
+
if (this.#record(receipt, pending.command.payload.messageRequestId, pending.command.payload.contentDigest, pending.command.payload.attachmentRefs)) pending.resolve(receipt);
|
|
498
|
+
else pending.resolve(this.#receipt(pending.command, pending.before, "uncertain", "dispatch-unknown", "acceptance-receipt-store-unavailable", false, pending.operationId));
|
|
499
|
+
}
|
|
500
|
+
}
|