@piagent/platform 1.3.1 → 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 +39 -0
- 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 +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/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 +7 -6
- 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/runtime-integrity.js +143 -0
- package/packages/piagent-core/extensions/piagent-guard.ts +62 -37
- package/packages/piagent-core/extensions/redaction-core.d.ts +2 -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-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,408 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
|
|
4
|
+
import { inspectTaskResumeState } from "../../piagent-core/runtime/recovery/resume-state.ts";
|
|
5
|
+
import { appendTaskControlTransition, inspectTaskControlState, readTaskControlReceipt, recordTaskControlReceipt,
|
|
6
|
+
type DurableControlState } from "../../piagent-core/runtime/inspection/task-control-journal.ts";
|
|
7
|
+
import { chatContentDigest, controlActionDigest, type BridgeIdentity, type BridgeRevisions, type ChatReceipt,
|
|
8
|
+
type NewOperationChatCommand, type SameSessionPiBridge } from "./same-session-bridge.ts";
|
|
9
|
+
|
|
10
|
+
const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/, PUBLIC_REF = /^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/,
|
|
11
|
+
REVISION = /^[A-Za-z0-9][A-Za-z0-9._:~-]{0,159}$/, IDEMPOTENCY = /^[A-Za-z0-9._~-]{32,128}$/,
|
|
12
|
+
DIGEST = /^sha256:[a-f0-9]{64}$/;
|
|
13
|
+
type Task = { taskId: string; taskRunId: string; sessionId: string; trace: { outcome: string }; [key: string]: any };
|
|
14
|
+
type LifecycleAction = "lifecycle.stop" | "lifecycle.pause" | "lifecycle.resume" | "lifecycle.resume-and-continue";
|
|
15
|
+
type Command = { schemaVersion: 1; version: "piagent-webui-control-v1"; messageType: "command"; commandId: string; idempotencyKey: string;
|
|
16
|
+
requestedAt: string; expiresAt: string; capabilityScope: "control.lifecycle" | "control.resumeAndContinue"; action: LifecycleAction; actionDigest: string;
|
|
17
|
+
identity: BridgeIdentity; expectedRevisions: BridgeRevisions & { workspacePreimage: null; indexPreimage: null; patchPreimage: null };
|
|
18
|
+
payload: Record<string, unknown> };
|
|
19
|
+
type Receipt = { schemaVersion: 1; version: "piagent-webui-control-v1"; messageType: "receipt"; commandId: string;
|
|
20
|
+
idempotencyKeyDigest: string; action: LifecycleAction; actionDigest: string; identity: BridgeIdentity;
|
|
21
|
+
phase: "accepted" | "settled" | "rejected" | "uncertain"; resultCode: string; requestedAt: string; settledAt: string | null;
|
|
22
|
+
observedRevisionsBefore: BridgeRevisions; observedRevisionsAfter: BridgeRevisions; deduplicated: boolean; auditRef: string | null;
|
|
23
|
+
settlementEvidenceRef: string | null; error: { code: string; message: string; retryable: boolean } | null };
|
|
24
|
+
type PendingStop = { task: Task | null; command: Command; operationId: string; pauseState: DurableControlState; resolved: boolean;
|
|
25
|
+
resolve(value: Receipt): void; timer: NodeJS.Timeout };
|
|
26
|
+
type PendingPause = { task: Task; command: Command; epoch: number; abortIssued: boolean; preTreeDigest: string | null };
|
|
27
|
+
export type LifecycleEvent = { kind: "control.changed" | "command.receipt"; action: LifecycleAction | null; resultCode: string;
|
|
28
|
+
controlState: DurableControlState; commandId: string | null; receipt?: Receipt; fact?: string; fromControlState?: DurableControlState;
|
|
29
|
+
toControlState?: DurableControlState; requestSequence?: number; parentSequence?: number | null; expectedControlRevision?: string;
|
|
30
|
+
idempotencyKeyDigest?: string; agentOperationId?: string | null; preWorkingTreeDigest?: string | null; postWorkingTreeDigest?: string | null };
|
|
31
|
+
|
|
32
|
+
function canonical(value: unknown): string { if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
33
|
+
if (!value || typeof value !== "object") return JSON.stringify(value); return `{${Object.entries(value as Record<string, unknown>)
|
|
34
|
+
.sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`; }
|
|
35
|
+
function same(left: unknown, right: unknown): boolean { return canonical(left) === canonical(right); }
|
|
36
|
+
function sha(value: string): string { return `sha256:${createHash("sha256").update(value).digest("hex")}`; }
|
|
37
|
+
function derivedRef(prefix: string, command: Command): string {
|
|
38
|
+
return `${prefix}.${createHash("sha256").update(`${command.commandId}\0${command.actionDigest}`).digest("hex")}`;
|
|
39
|
+
}
|
|
40
|
+
function evidence(value: unknown): string { return `control-state.${createHash("sha256").update(canonical(value)).digest("hex")}`; }
|
|
41
|
+
function exactKeys(value: unknown, keys: string[]): boolean { return Boolean(value && typeof value === "object" && !Array.isArray(value)
|
|
42
|
+
&& same(Object.keys(value as Record<string, unknown>).sort(), [...keys].sort())); }
|
|
43
|
+
function timestamp(value: unknown): value is string { if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) return false;
|
|
44
|
+
const parsed = Date.parse(value); return Number.isFinite(parsed) && new Date(parsed).toISOString() === value; }
|
|
45
|
+
function clone<T>(value: T): T { return structuredClone(value); }
|
|
46
|
+
function wireRevisions(value: BridgeRevisions): BridgeRevisions { return { runtimeRevision: value.runtimeRevision, taskRevision: value.taskRevision,
|
|
47
|
+
controlRevision: value.controlRevision, workspaceRevision: value.workspaceRevision, indexRevision: value.indexRevision,
|
|
48
|
+
approvalRevision: value.approvalRevision, sessionOptionRevision: value.sessionOptionRevision, queueRevision: value.queueRevision }; }
|
|
49
|
+
function storedReceipt(value: unknown): value is Receipt {
|
|
50
|
+
if (!exactKeys(value, ["schemaVersion", "version", "messageType", "commandId", "idempotencyKeyDigest", "action", "actionDigest", "identity",
|
|
51
|
+
"phase", "resultCode", "requestedAt", "settledAt", "observedRevisionsBefore", "observedRevisionsAfter", "deduplicated", "auditRef",
|
|
52
|
+
"settlementEvidenceRef", "error"])) return false;
|
|
53
|
+
const item = value as Receipt, revisions = (candidate: unknown) => { if (!exactKeys(candidate,
|
|
54
|
+
["runtimeRevision", "taskRevision", "controlRevision", "workspaceRevision", "indexRevision", "approvalRevision", "sessionOptionRevision", "queueRevision"])) return false;
|
|
55
|
+
const current = candidate as Record<string, unknown>; return REVISION.test(String(current.runtimeRevision ?? ""))
|
|
56
|
+
&& Object.entries(current).filter(([key]) => key !== "runtimeRevision").every(([, item]) => item === null || REVISION.test(String(item))); };
|
|
57
|
+
const identity = item.identity, validIdentity = exactKeys(identity,
|
|
58
|
+
["projectRef", "runtimeInstanceId", "sessionRef", "taskId", "taskRunId", "agentOperationId", "toolCallId"])
|
|
59
|
+
&& [identity.projectRef, identity.runtimeInstanceId, identity.sessionRef].every((entry) => REF.test(String(entry)))
|
|
60
|
+
&& (identity.taskId === null || PUBLIC_REF.test(String(identity.taskId))) && (identity.taskRunId === null || PUBLIC_REF.test(String(identity.taskRunId)))
|
|
61
|
+
&& (identity.agentOperationId === null || REF.test(String(identity.agentOperationId))) && identity.toolCallId === null;
|
|
62
|
+
if (item.schemaVersion !== 1 || item.version !== "piagent-webui-control-v1" || item.messageType !== "receipt" || !REF.test(item.commandId)
|
|
63
|
+
|| !DIGEST.test(item.idempotencyKeyDigest) || !DIGEST.test(item.actionDigest) || !timestamp(item.requestedAt)
|
|
64
|
+
|| !["lifecycle.stop", "lifecycle.pause", "lifecycle.resume", "lifecycle.resume-and-continue"].includes(item.action) || !revisions(item.observedRevisionsBefore)
|
|
65
|
+
|| !revisions(item.observedRevisionsAfter) || !validIdentity || typeof item.deduplicated !== "boolean"
|
|
66
|
+
|| !(item.auditRef === null || REF.test(item.auditRef))) return false;
|
|
67
|
+
if (item.phase === "accepted") return (item.action === "lifecycle.pause" && item.resultCode === "pause-requested"
|
|
68
|
+
|| item.action === "lifecycle.resume-and-continue" && item.resultCode === "dispatch-requested") && item.settledAt === null
|
|
69
|
+
&& item.settlementEvidenceRef === null && item.error === null;
|
|
70
|
+
if (!timestamp(item.settledAt)) return false;
|
|
71
|
+
const results = item.action === "lifecycle.stop" ? ["stopped", "emergency-stop"]
|
|
72
|
+
: item.action === "lifecycle.pause" ? ["paused", "already-pausing", "already-paused"]
|
|
73
|
+
: item.action === "lifecycle.resume" ? ["resumed", "already-active", "pause-cancelled"] : ["dispatch-observed"];
|
|
74
|
+
if (item.phase === "settled") return results.includes(item.resultCode) && item.error === null
|
|
75
|
+
&& typeof item.settlementEvidenceRef === "string" && REF.test(item.settlementEvidenceRef);
|
|
76
|
+
const validError = Boolean(item.error && /^[a-z0-9][a-z0-9.-]{0,95}$/.test(item.error.code)
|
|
77
|
+
&& item.error.message.length > 0 && item.error.message.length <= 500 && typeof item.error.retryable === "boolean");
|
|
78
|
+
return item.settlementEvidenceRef === null && validError && (item.phase === "uncertain" && item.action === "lifecycle.stop"
|
|
79
|
+
&& item.resultCode === "settlement-unknown" || item.phase === "rejected" && item.action === "lifecycle.resume" && item.resultCode === "resume-rejected"
|
|
80
|
+
|| item.phase === "uncertain" && item.action === "lifecycle.resume-and-continue"
|
|
81
|
+
&& ["dispatch-unknown", "resumed-not-dispatched"].includes(item.resultCode));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export class LifecycleController {
|
|
85
|
+
readonly #bridge: SameSessionPiBridge;
|
|
86
|
+
readonly #runtimeInstanceId: string;
|
|
87
|
+
readonly #task: (ctx: ExtensionContext) => Task | null;
|
|
88
|
+
readonly #abort: (ctx: ExtensionContext) => void;
|
|
89
|
+
readonly #cancelApprovals: (ctx: ExtensionContext, taskRunId: string) => void;
|
|
90
|
+
readonly #treeDigest: (ctx: ExtensionContext) => string | null;
|
|
91
|
+
readonly #listeners = new Set<(event: LifecycleEvent) => void>();
|
|
92
|
+
#ctx: ExtensionContext | null = null;
|
|
93
|
+
#toolDepth = 0;
|
|
94
|
+
#phase: "idle" | "model" | "tool" | "other" | "unknown" = "unknown";
|
|
95
|
+
#pauseGeneration = 0;
|
|
96
|
+
#pendingPause: PendingPause | null = null;
|
|
97
|
+
#pendingStop: PendingStop | null = null;
|
|
98
|
+
readonly #ephemeralReceipts = new Map<string, Receipt>();
|
|
99
|
+
#serial: Promise<unknown> = Promise.resolve();
|
|
100
|
+
|
|
101
|
+
constructor(input: { bridge: SameSessionPiBridge; runtimeInstanceId: string; task(ctx: ExtensionContext): Task | null;
|
|
102
|
+
abort(ctx: ExtensionContext): void; cancelApprovals(ctx: ExtensionContext, taskRunId: string): void; treeDigest?(ctx: ExtensionContext): string | null }) {
|
|
103
|
+
this.#bridge = input.bridge; this.#runtimeInstanceId = input.runtimeInstanceId; this.#task = input.task;
|
|
104
|
+
this.#abort = input.abort; this.#cancelApprovals = input.cancelApprovals; this.#treeDigest = input.treeDigest ?? (() => null);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
bind(ctx: ExtensionContext): void { this.#ctx = ctx; this.#toolDepth = 0; this.#phase = ctx.isIdle() ? "idle" : "other";
|
|
108
|
+
this.#pendingPause = null; this.#clearStop(false); this.#pauseGeneration += 1; }
|
|
109
|
+
replacementPending(): void { this.#pauseGeneration += 1; this.#pendingPause = null; this.#clearStop(true); this.#phase = "unknown"; }
|
|
110
|
+
shutdown(): void { this.#pauseGeneration += 1; this.#pendingPause = null; this.#clearStop(true); this.#ctx = null; this.#phase = "unknown"; }
|
|
111
|
+
subscribe(listener: (event: LifecycleEvent) => void): () => void { this.#listeners.add(listener); return () => this.#listeners.delete(listener); }
|
|
112
|
+
#emit(event: LifecycleEvent): void { for (const listener of this.#listeners) { try { listener(clone(event)); } catch { /* projection is fail-soft */ } } }
|
|
113
|
+
#sameSession(ctx: ExtensionContext): boolean { return Boolean(this.#ctx && this.#ctx.cwd === ctx.cwd
|
|
114
|
+
&& this.#ctx.sessionManager.getSessionId() === ctx.sessionManager.getSessionId()); }
|
|
115
|
+
|
|
116
|
+
snapshot(): { state: DurableControlState; controlRevision: string | null; dispatchBlocked: boolean; currentPhase: string; pauseEpoch: number;
|
|
117
|
+
actions: { stop: boolean; pause: boolean; resume: boolean } } {
|
|
118
|
+
const ctx = this.#ctx, task = ctx ? this.#task(ctx) : null;
|
|
119
|
+
if (!ctx || !task) return { state: task?.trace.outcome === "pending" ? "unknown" : "active", controlRevision: null,
|
|
120
|
+
dispatchBlocked: Boolean(this.#pendingStop), currentPhase: this.#phase, pauseEpoch: 0, actions: { stop: false, pause: false, resume: false } };
|
|
121
|
+
const control = inspectTaskControlState(ctx.cwd, task);
|
|
122
|
+
const running = this.#bridge.snapshot().liveness === "running";
|
|
123
|
+
return { ...control, dispatchBlocked: control.dispatchBlocked || Boolean(this.#pendingStop), currentPhase: this.#phase,
|
|
124
|
+
actions: { stop: running && Boolean(this.#bridge.snapshot().identity?.agentOperationId), pause: control.state === "active",
|
|
125
|
+
resume: control.state === "paused" || control.state === "pause-requested" } };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
dispatchAllowed(ctx?: ExtensionContext): boolean {
|
|
129
|
+
const current = ctx ?? this.#ctx; if (!current || !this.#sameSession(current)) return false;
|
|
130
|
+
const task = this.#task(current); if (!task) return !this.#pendingStop;
|
|
131
|
+
return !inspectTaskControlState(current.cwd, task).dispatchBlocked && !this.#pendingStop;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
observeAgentStart(ctx: ExtensionContext): void { if (!this.#sameSession(ctx)) return; this.#phase = "model"; }
|
|
135
|
+
observeToolStart(ctx: ExtensionContext): void { if (!this.#sameSession(ctx)) return; this.#toolDepth += 1; this.#phase = "tool"; }
|
|
136
|
+
observeToolEnd(ctx: ExtensionContext): void { if (!this.#sameSession(ctx)) return; this.#toolDepth = Math.max(0, this.#toolDepth - 1);
|
|
137
|
+
this.#phase = this.#toolDepth ? "tool" : "model"; if (!this.#toolDepth) this.#advancePause(); }
|
|
138
|
+
observeAgentSettled(ctx: ExtensionContext, operationId: string | null): void {
|
|
139
|
+
if (!this.#sameSession(ctx)) return; this.#phase = "idle";
|
|
140
|
+
if (this.#pendingStop && operationId === this.#pendingStop.operationId) this.#settleStop();
|
|
141
|
+
if (this.#pendingPause) this.#settlePause();
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
execute(value: unknown): Promise<Receipt> { const run = this.#serial.then(() => this.#execute(value), () => this.#execute(value));
|
|
145
|
+
this.#serial = run.catch(() => undefined); return run; }
|
|
146
|
+
async #execute(value: unknown): Promise<Receipt> {
|
|
147
|
+
const ctx = this.#ctx, command = value as Command, structural = this.#validate(value), bridge = this.#bridge.snapshot();
|
|
148
|
+
if (!ctx || bridge.state !== "ready" || !bridge.identity || !bridge.revisions) return this.#reject(command, "resync-required", "lifecycle-binding-unavailable");
|
|
149
|
+
if (structural) return this.#reject(command, "invalid-command", structural);
|
|
150
|
+
const task = this.#task(ctx), keyDigest = sha(command.idempotencyKey);
|
|
151
|
+
const durable = task ? readTaskControlReceipt(ctx.cwd, task, { commandId: command.commandId, idempotencyKeyDigest: keyDigest,
|
|
152
|
+
actionDigest: command.actionDigest }) : null;
|
|
153
|
+
const ephemeral = task ? null : [...this.#ephemeralReceipts.values()].find((item) => item.commandId === command.commandId
|
|
154
|
+
|| item.idempotencyKeyDigest === keyDigest) ?? null;
|
|
155
|
+
if (durable?.invalid || durable && !storedReceipt(durable.receipt)) return this.#reject(command, "resync-required", "task-control-receipt-corrupt");
|
|
156
|
+
if (durable?.conflict || ephemeral && (ephemeral.actionDigest !== command.actionDigest || ephemeral.commandId === command.commandId
|
|
157
|
+
&& ephemeral.idempotencyKeyDigest !== keyDigest)) return this.#reject(command, "idempotency-payload-mismatch", "idempotency-payload-mismatch");
|
|
158
|
+
const stored = durable?.receipt as Receipt | undefined ?? ephemeral;
|
|
159
|
+
if (stored) {
|
|
160
|
+
const current = bridge.identity, prior = stored.identity;
|
|
161
|
+
if (prior.projectRef !== current.projectRef || prior.runtimeInstanceId !== current.runtimeInstanceId || prior.sessionRef !== current.sessionRef
|
|
162
|
+
|| prior.taskId !== current.taskId || prior.taskRunId !== current.taskRunId) return this.#reject(command, "identity-mismatch", "runtime-or-session-replaced");
|
|
163
|
+
return { ...stored, deduplicated: true };
|
|
164
|
+
}
|
|
165
|
+
const now = Date.now();
|
|
166
|
+
if (Date.parse(command.requestedAt) > now + 30_000) return this.#reject(command, "invalid-command", "requested-at-in-future");
|
|
167
|
+
if (now > Date.parse(command.expiresAt)) return this.#reject(command, "expired", "command-expired");
|
|
168
|
+
if (!same(command.identity, bridge.identity)) return this.#reject(command, "identity-mismatch", "identity-mismatch");
|
|
169
|
+
const lifecycleRevisions = command.action === "lifecycle.stop" && !task ? ["runtimeRevision"] as const
|
|
170
|
+
: ["runtimeRevision", "taskRevision", "controlRevision"] as const;
|
|
171
|
+
if (lifecycleRevisions.some((name) => command.expectedRevisions[name] !== bridge.revisions![name]))
|
|
172
|
+
return this.#reject(command, "stale-revision", "stale-revision");
|
|
173
|
+
if (command.action !== "lifecycle.stop" && (!task || task.taskId !== command.identity.taskId || task.taskRunId !== command.identity.taskRunId))
|
|
174
|
+
return this.#reject(command, "identity-mismatch", "task-identity-mismatch");
|
|
175
|
+
if (command.action === "lifecycle.stop") return this.#stop(ctx, task?.trace.outcome === "pending" ? task : null, command);
|
|
176
|
+
if (task && task.trace.outcome !== "pending") return this.#reject(command, "capability-unavailable", "task-terminal");
|
|
177
|
+
if (!task) return this.#reject(command, "identity-mismatch", "task-identity-mismatch");
|
|
178
|
+
if (command.action === "lifecycle.pause") return this.#pause(ctx, task, command);
|
|
179
|
+
if (command.action === "lifecycle.resume-and-continue") return this.#resumeAndContinue(ctx, task, command);
|
|
180
|
+
return this.#resume(ctx, task, command);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async #resumeAndContinue(ctx: ExtensionContext, task: Task, command: Command): Promise<Receipt> {
|
|
184
|
+
const control = inspectTaskControlState(ctx.cwd, task), before = this.#bridge.snapshot();
|
|
185
|
+
if (!["paused", "pause-requested"].includes(control.state))
|
|
186
|
+
return this.#reject(command, "capability-unavailable", `control-state-${control.state}`);
|
|
187
|
+
if (before.liveness !== "idle" || before.identity?.agentOperationId)
|
|
188
|
+
return this.#reject(command, "capability-unavailable", "agent-not-idle");
|
|
189
|
+
const resumeCommand: Command = { ...clone(command), commandId: derivedRef("compound-resume", command),
|
|
190
|
+
idempotencyKey: derivedRef("compound-resume-key", command), capabilityScope: "control.lifecycle", action: "lifecycle.resume", payload: {} };
|
|
191
|
+
resumeCommand.actionDigest = controlActionDigest(resumeCommand);
|
|
192
|
+
const resume = this.#resume(ctx, task, resumeCommand);
|
|
193
|
+
if (resume.phase !== "settled" || !["resumed", "pause-cancelled", "already-active"].includes(resume.resultCode))
|
|
194
|
+
return this.#reject(command, "capability-unavailable", resume.error?.code ?? "resume-before-dispatch-failed");
|
|
195
|
+
const ready = this.#bridge.snapshot();
|
|
196
|
+
if (ready.state !== "ready" || ready.liveness !== "idle" || !ready.identity || !ready.revisions
|
|
197
|
+
|| ready.taskState !== "active" || ready.identity.agentOperationId)
|
|
198
|
+
return this.#finish(task, this.#receipt(command, "uncertain", "resumed-not-dispatched", null,
|
|
199
|
+
"post-resume-dispatch-gate-closed", false));
|
|
200
|
+
const chat: NewOperationChatCommand = { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "command",
|
|
201
|
+
commandId: derivedRef("compound-chat", command), idempotencyKey: derivedRef("compound-chat-key", command),
|
|
202
|
+
requestedAt: command.requestedAt, expiresAt: command.expiresAt, capabilityScope: "control.chat", action: "chat.send", actionDigest: "",
|
|
203
|
+
identity: clone(ready.identity), expectedRevisions: { ...clone(ready.revisions), workspacePreimage: null, indexPreimage: null, patchPreimage: null },
|
|
204
|
+
payload: command.payload as NewOperationChatCommand["payload"] };
|
|
205
|
+
chat.actionDigest = controlActionDigest(chat);
|
|
206
|
+
const dispatched = await this.#bridge.execute(chat);
|
|
207
|
+
if (dispatched.resultCode === "dispatch-observed" && dispatched.phase === "settled")
|
|
208
|
+
return this.#finish(task, this.#receipt(command, "settled", "dispatch-observed", dispatched.settlementEvidenceRef,
|
|
209
|
+
null, false, dispatched.identity));
|
|
210
|
+
if (dispatched.resultCode === "dispatch-requested" && ["requested", "accepted"].includes(dispatched.phase))
|
|
211
|
+
return this.#finish(task, this.#receipt(command, "accepted", "dispatch-requested", null, null, false, dispatched.identity));
|
|
212
|
+
if (dispatched.resultCode === "dispatch-unknown" || dispatched.phase === "uncertain")
|
|
213
|
+
return this.#finish(task, this.#receipt(command, "uncertain", "dispatch-unknown", null,
|
|
214
|
+
dispatched.error?.code ?? "dispatch-acknowledgement-ambiguous", false, dispatched.identity));
|
|
215
|
+
return this.#finish(task, this.#receipt(command, "uncertain", "resumed-not-dispatched", null,
|
|
216
|
+
dispatched.error?.code ?? "dispatch-after-resume-rejected", false));
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
#stop(ctx: ExtensionContext, task: Task | null, command: Command): Promise<Receipt> {
|
|
220
|
+
const bridge = this.#bridge.snapshot(), operationId = bridge.identity?.agentOperationId;
|
|
221
|
+
if (!operationId || bridge.liveness !== "running") return Promise.resolve(this.#reject(command, "capability-unavailable", "agent-not-running"));
|
|
222
|
+
if (this.#pendingStop) return Promise.resolve(this.#reject(command, "capability-unavailable", "stop-already-pending"));
|
|
223
|
+
const control = task ? inspectTaskControlState(ctx.cwd, task) : { state: "active" as const, pauseEpoch: 0 };
|
|
224
|
+
const transition = task ? this.#transition(task, command, "task-control.stop-requested", "stop",
|
|
225
|
+
[control.state], control.state, "stop-requested", operationId, control.pauseEpoch) : { ok: true, reasonCode: null };
|
|
226
|
+
if (!transition.ok) return Promise.resolve(this.#reject(command, transition.reasonCode === "stale-control-revision" ? "stale-revision" : "capability-unavailable", transition.reasonCode ?? "stop-request-rejected"));
|
|
227
|
+
return new Promise<Receipt>((resolve) => {
|
|
228
|
+
const timer = setTimeout(() => { if (!this.#pendingStop || this.#pendingStop.resolved) return; this.#pendingStop.resolved = true;
|
|
229
|
+
const receipt = this.#receipt(command, "uncertain", "settlement-unknown", null, "stop-settlement-not-observed", false);
|
|
230
|
+
this.#store(task, receipt); this.#emitReceipt(receipt); resolve(receipt); }, 5_000); timer.unref();
|
|
231
|
+
this.#pendingStop = { task, command: clone(command), operationId, pauseState: control.state, resolved: false, resolve, timer };
|
|
232
|
+
try { this.#abort(ctx); } catch { this.#settleStop("abort-rejected"); }
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
#pause(ctx: ExtensionContext, task: Task, command: Command): Receipt {
|
|
237
|
+
const control = inspectTaskControlState(ctx.cwd, task);
|
|
238
|
+
if (control.state === "pause-requested") return this.#finish(task, this.#receipt(command, "settled", "already-pausing", control.journalHead ?? evidence(control), null, false));
|
|
239
|
+
if (control.state === "paused") return this.#finish(task, this.#receipt(command, "settled", "already-paused", control.journalHead ?? evidence(control), null, false));
|
|
240
|
+
if (control.state !== "active") return this.#reject(command, "capability-unavailable", control.reasonCode ?? `control-state-${control.state}`);
|
|
241
|
+
const epoch = control.pauseEpoch + 1, preTreeDigest = this.#treeDigest(ctx), transition = this.#transition(task, command,
|
|
242
|
+
"task-control.pause-requested", "pause", ["active"], "pause-requested", "pause-requested", command.identity.agentOperationId, epoch,
|
|
243
|
+
null, { preWorkingTreeDigest: preTreeDigest, postWorkingTreeDigest: null });
|
|
244
|
+
if (!transition.ok) return this.#reject(command, transition.reasonCode === "stale-control-revision" ? "stale-revision" : "capability-unavailable", transition.reasonCode ?? "pause-request-rejected");
|
|
245
|
+
const generation = ++this.#pauseGeneration; this.#pendingPause = { task, command: clone(command), epoch, abortIssued: false,
|
|
246
|
+
preTreeDigest };
|
|
247
|
+
this.#cancelApprovals(ctx, task.taskRunId);
|
|
248
|
+
if (generation !== this.#pauseGeneration || !this.#pendingPause) return this.#reject(command, "resync-required", "pause-worker-cancelled");
|
|
249
|
+
const bridge = this.#bridge.snapshot(), safeNow = bridge.liveness === "idle" && this.#toolDepth === 0
|
|
250
|
+
&& !(typeof ctx.hasPendingMessages === "function" && ctx.hasPendingMessages());
|
|
251
|
+
if (safeNow) { const settled = this.#settlePause(); if (settled) return settled; }
|
|
252
|
+
else this.#advancePause();
|
|
253
|
+
return this.#finish(task, this.#receipt(command, "accepted", "pause-requested", null, null, false));
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
#resume(ctx: ExtensionContext, task: Task, command: Command): Receipt {
|
|
257
|
+
const control = inspectTaskControlState(ctx.cwd, task);
|
|
258
|
+
if (control.state === "active") return this.#finish(task, this.#receipt(command, "settled", "already-active", control.journalHead ?? evidence(control), null, false));
|
|
259
|
+
if (control.state === "pause-requested") {
|
|
260
|
+
this.#pauseGeneration += 1; this.#pendingPause = null;
|
|
261
|
+
const transition = this.#transition(task, command, "task-control.pause-cancelled", "resume", ["pause-requested"], "active",
|
|
262
|
+
"pause-cancelled", command.identity.agentOperationId, control.pauseEpoch);
|
|
263
|
+
return transition.ok ? this.#finish(task, this.#receipt(command, "settled", "pause-cancelled", transition.evidenceRef, null, false))
|
|
264
|
+
: this.#reject(command, transition.reasonCode === "stale-control-revision" ? "stale-revision" : "resume-rejected", transition.reasonCode ?? "pause-cancel-rejected");
|
|
265
|
+
}
|
|
266
|
+
if (control.state !== "paused") return this.#reject(command, "resume-rejected", control.reasonCode ?? `control-state-${control.state}`);
|
|
267
|
+
const resumeTreeDigest = this.#treeDigest(ctx), requested = this.#transition(task, command, "task-control.resume-requested", "resume", ["paused"], "paused",
|
|
268
|
+
"resume-requested", command.identity.agentOperationId, control.pauseEpoch, null, { preWorkingTreeDigest: resumeTreeDigest });
|
|
269
|
+
if (!requested.ok) return this.#reject(command, requested.reasonCode === "stale-control-revision" ? "stale-revision" : "resume-rejected", requested.reasonCode ?? "resume-request-rejected");
|
|
270
|
+
let recovery: ReturnType<typeof inspectTaskResumeState>;
|
|
271
|
+
try { recovery = inspectTaskResumeState(ctx.cwd, task as any, task.sessionId); }
|
|
272
|
+
catch { recovery = { enforcementSafe: false, decision: "blocked", reason: "Resume evidence is unavailable" } as any; }
|
|
273
|
+
const current = inspectTaskControlState(ctx.cwd, task);
|
|
274
|
+
if (!recovery.enforcementSafe || !["resume", "retry"].includes(recovery.decision)) {
|
|
275
|
+
this.#transition(task, { ...command, expectedRevisions: { ...command.expectedRevisions, controlRevision: current.controlRevision } },
|
|
276
|
+
"task-control.resume-rejected", "resume", ["paused"], "paused", "resume-rejected", command.identity.agentOperationId, control.pauseEpoch,
|
|
277
|
+
String(recovery.reason ?? "resume-evidence-unsafe"));
|
|
278
|
+
return this.#finish(task, this.#receipt(command, "rejected", "resume-rejected", null, "resume-evidence-unsafe", false));
|
|
279
|
+
}
|
|
280
|
+
const resumed = this.#transition(task, { ...command, expectedRevisions: { ...command.expectedRevisions, controlRevision: current.controlRevision } },
|
|
281
|
+
"task-control.resumed", "resume", ["paused"], "active", "resumed", command.identity.agentOperationId, control.pauseEpoch, null,
|
|
282
|
+
{ preWorkingTreeDigest: resumeTreeDigest, postWorkingTreeDigest: this.#treeDigest(ctx) });
|
|
283
|
+
return resumed.ok ? this.#finish(task, this.#receipt(command, "settled", "resumed", resumed.evidenceRef, null, false))
|
|
284
|
+
: this.#reject(command, "resume-rejected", resumed.reasonCode ?? "resume-commit-rejected");
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
#advancePause(): void {
|
|
288
|
+
const pending = this.#pendingPause, ctx = this.#ctx; if (!pending || !ctx || pending.abortIssued || this.#toolDepth > 0) return;
|
|
289
|
+
const current = inspectTaskControlState(ctx.cwd, pending.task);
|
|
290
|
+
if (current.state !== "pause-requested" || current.pauseEpoch !== pending.epoch) { this.#pendingPause = null; return; }
|
|
291
|
+
pending.abortIssued = true;
|
|
292
|
+
try { this.#abort(ctx); } catch { /* state stays pause-requested until a safe point is proved */ }
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
#settlePause(): Receipt | null {
|
|
296
|
+
const pending = this.#pendingPause, ctx = this.#ctx; if (!pending || !ctx) return null;
|
|
297
|
+
const current = inspectTaskControlState(ctx.cwd, pending.task);
|
|
298
|
+
if (current.state !== "pause-requested" || current.pauseEpoch !== pending.epoch) { this.#pendingPause = null; return null; }
|
|
299
|
+
const command = { ...pending.command, expectedRevisions: { ...pending.command.expectedRevisions, controlRevision: current.controlRevision } };
|
|
300
|
+
const postTreeDigest = this.#treeDigest(ctx); if (!postTreeDigest) return null;
|
|
301
|
+
const transition = this.#transition(pending.task, command, "task-control.paused", "pause", ["pause-requested"], "paused",
|
|
302
|
+
"paused", pending.command.identity.agentOperationId, pending.epoch, null,
|
|
303
|
+
{ preWorkingTreeDigest: pending.preTreeDigest, postWorkingTreeDigest: postTreeDigest });
|
|
304
|
+
if (!transition.ok) return null;
|
|
305
|
+
this.#pendingPause = null; const receipt = this.#finish(pending.task, this.#receipt(pending.command, "settled", "paused", transition.evidenceRef, null, false));
|
|
306
|
+
this.#emit({ kind: "control.changed", action: "lifecycle.pause", resultCode: "paused", controlState: "paused", commandId: pending.command.commandId });
|
|
307
|
+
return receipt;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
#settleStop(reason?: string): void {
|
|
311
|
+
const pending = this.#pendingStop; if (!pending) return;
|
|
312
|
+
clearTimeout(pending.timer); const current = pending.task ? inspectTaskControlState(this.#ctx?.cwd ?? "", pending.task) : null;
|
|
313
|
+
const command = current ? { ...pending.command, expectedRevisions: { ...pending.command.expectedRevisions, controlRevision: current.controlRevision } } : pending.command;
|
|
314
|
+
const transition = this.#ctx && pending.task && current ? this.#transition(pending.task, command, "task-control.stop-settled", "stop", [current.state], current.state,
|
|
315
|
+
reason ? "settlement-unknown" : "stopped", pending.operationId, current.pauseEpoch, reason ?? null) : null;
|
|
316
|
+
const success = !reason && (!pending.task || transition?.ok);
|
|
317
|
+
const receipt = success ? this.#receipt(pending.command, "settled", pending.task ? "stopped" : "emergency-stop",
|
|
318
|
+
transition?.evidenceRef ?? evidence([pending.operationId, "emergency-stop"]), null, false)
|
|
319
|
+
: this.#receipt(pending.command, "uncertain", "settlement-unknown", null, reason ?? "stop-settlement-unavailable", false);
|
|
320
|
+
this.#store(pending.task, receipt); this.#emitReceipt(receipt); if (!pending.resolved) pending.resolve(receipt);
|
|
321
|
+
this.#pendingStop = null;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
#transition(task: Task, command: Command, fact: string, action: "stop" | "pause" | "resume", expectedStates: DurableControlState[],
|
|
325
|
+
toState: DurableControlState, resultCode: string, operationId: string | null, pauseEpoch: number, reasonCode: string | null = null,
|
|
326
|
+
tree: { preWorkingTreeDigest?: string | null; postWorkingTreeDigest?: string | null } = {}) {
|
|
327
|
+
const result = appendTaskControlTransition({ cwd: this.#ctx!.cwd, task, runtimeInstanceId: this.#runtimeInstanceId, commandId: command.commandId,
|
|
328
|
+
idempotencyKeyDigest: sha(command.idempotencyKey), actionDigest: command.actionDigest, fact, action,
|
|
329
|
+
expectedControlRevision: command.expectedRevisions.controlRevision!, expectedStates, toState, agentOperationId: operationId,
|
|
330
|
+
resultCode, reasonCode, pauseEpoch, ...tree });
|
|
331
|
+
if (result.ok && !result.duplicate) this.#emit({ kind: "control.changed", action: command.action, resultCode,
|
|
332
|
+
controlState: result.after.state, commandId: command.commandId, fact: fact.replace("task-control.", ""), fromControlState: result.before.state,
|
|
333
|
+
toControlState: result.after.state, requestSequence: fact.endsWith("-requested") ? result.after.sequence : result.before.sequence,
|
|
334
|
+
parentSequence: fact.endsWith("-requested") ? null : result.before.sequence, expectedControlRevision: command.expectedRevisions.controlRevision!,
|
|
335
|
+
idempotencyKeyDigest: sha(command.idempotencyKey), agentOperationId: operationId,
|
|
336
|
+
preWorkingTreeDigest: tree.preWorkingTreeDigest ?? null, postWorkingTreeDigest: tree.postWorkingTreeDigest ?? null });
|
|
337
|
+
return result;
|
|
338
|
+
}
|
|
339
|
+
#finish(task: Task, receipt: Receipt): Receipt { this.#store(task, receipt); this.#emitReceipt(receipt); return receipt; }
|
|
340
|
+
#store(task: Task | null, receipt: Receipt): void { if (!task) { this.#ephemeralReceipts.set(receipt.commandId, clone(receipt));
|
|
341
|
+
if (this.#ephemeralReceipts.size > 256) this.#ephemeralReceipts.delete(this.#ephemeralReceipts.keys().next().value as string); return; }
|
|
342
|
+
try { recordTaskControlReceipt(this.#ctx!.cwd, task, receipt.commandId, receipt.idempotencyKeyDigest, receipt.actionDigest,
|
|
343
|
+
receipt as unknown as Record<string, unknown>); } catch { /* transition evidence remains authoritative */ } }
|
|
344
|
+
#emitReceipt(receipt: Receipt): void { this.#emit({ kind: "command.receipt", action: receipt.action, resultCode: receipt.resultCode,
|
|
345
|
+
controlState: this.snapshot().state, commandId: receipt.commandId, receipt }); }
|
|
346
|
+
#clearStop(resolve: boolean): void { if (!this.#pendingStop) return; clearTimeout(this.#pendingStop.timer);
|
|
347
|
+
if (resolve && !this.#pendingStop.resolved) this.#pendingStop.resolve(this.#receipt(this.#pendingStop.command, "uncertain", "settlement-unknown", null, "runtime-replaced", false));
|
|
348
|
+
this.#pendingStop = null; }
|
|
349
|
+
|
|
350
|
+
#receipt(command: Command, phase: Receipt["phase"], resultCode: string, evidenceRef: string | null, errorCode: string | null,
|
|
351
|
+
deduplicated: boolean, identityOverride?: BridgeIdentity): Receipt {
|
|
352
|
+
const snapshot = this.#bridge.snapshot(), after = snapshot.revisions ?? command.expectedRevisions;
|
|
353
|
+
const settled = phase === "accepted" ? null : new Date().toISOString();
|
|
354
|
+
return { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "receipt", commandId: command.commandId,
|
|
355
|
+
idempotencyKeyDigest: sha(command.idempotencyKey), action: command.action, actionDigest: command.actionDigest,
|
|
356
|
+
identity: clone(identityOverride ?? command.identity),
|
|
357
|
+
phase, resultCode, requestedAt: command.requestedAt, settledAt: settled, observedRevisionsBefore: wireRevisions(command.expectedRevisions),
|
|
358
|
+
observedRevisionsAfter: wireRevisions(after), deduplicated, auditRef: evidenceRef, settlementEvidenceRef: phase === "settled" ? evidenceRef : null,
|
|
359
|
+
error: errorCode ? { code: errorCode.replace(/[^a-z0-9.-]/g, "-").slice(0, 96) || "lifecycle-error",
|
|
360
|
+
message: `Lifecycle control could not complete: ${errorCode.replace(/[-.]/g, " ").slice(0, 400)}`, retryable: false } : null };
|
|
361
|
+
}
|
|
362
|
+
#reject(value: Partial<Command> | undefined, resultCode: string, errorCode: string): Receipt {
|
|
363
|
+
const snapshot = this.#bridge.snapshot(), fallbackIdentity = snapshot.identity ?? { projectRef: "project.unavailable", runtimeInstanceId: this.#runtimeInstanceId,
|
|
364
|
+
sessionRef: "session.unavailable", taskId: null, taskRunId: null, agentOperationId: null, toolCallId: null };
|
|
365
|
+
const fallbackRevisions = snapshot.revisions ?? { runtimeRevision: "runtime-rev.unavailable", taskRevision: null, controlRevision: null,
|
|
366
|
+
workspaceRevision: null, indexRevision: null, approvalRevision: null, sessionOptionRevision: null, queueRevision: null };
|
|
367
|
+
const action: LifecycleAction = ["lifecycle.stop", "lifecycle.pause", "lifecycle.resume", "lifecycle.resume-and-continue"].includes(String(value?.action))
|
|
368
|
+
? value!.action as LifecycleAction : "lifecycle.pause";
|
|
369
|
+
const identity = value?.identity && exactKeys(value.identity, ["projectRef", "runtimeInstanceId", "sessionRef", "taskId", "taskRunId", "agentOperationId", "toolCallId"])
|
|
370
|
+
? value.identity : fallbackIdentity;
|
|
371
|
+
const command = { commandId: REF.test(String(value?.commandId ?? "")) ? String(value!.commandId) : "command.invalid",
|
|
372
|
+
idempotencyKey: IDEMPOTENCY.test(String(value?.idempotencyKey ?? "")) ? String(value!.idempotencyKey) : "invalid-command-key-0000000000000000",
|
|
373
|
+
requestedAt: timestamp(value?.requestedAt) ? value!.requestedAt : new Date().toISOString(), action,
|
|
374
|
+
actionDigest: /^sha256:[a-f0-9]{64}$/.test(String(value?.actionDigest ?? "")) ? String(value!.actionDigest) : sha(canonical(value ?? null)),
|
|
375
|
+
identity, expectedRevisions: fallbackRevisions } as Command;
|
|
376
|
+
const receipt = this.#receipt(command, "rejected", resultCode, null, errorCode, false); this.#emitReceipt(receipt); return receipt;
|
|
377
|
+
}
|
|
378
|
+
#validate(value: unknown): string | null {
|
|
379
|
+
if (!exactKeys(value, ["schemaVersion", "version", "messageType", "commandId", "idempotencyKey", "requestedAt", "expiresAt", "capabilityScope", "action", "actionDigest", "identity", "expectedRevisions", "payload"])) return "unknown-command-field";
|
|
380
|
+
const command = value as Command;
|
|
381
|
+
if (command.schemaVersion !== 1 || command.version !== "piagent-webui-control-v1" || command.messageType !== "command"
|
|
382
|
+
|| !["lifecycle.stop", "lifecycle.pause", "lifecycle.resume", "lifecycle.resume-and-continue"].includes(command.action)
|
|
383
|
+
|| command.capabilityScope !== (command.action === "lifecycle.resume-and-continue" ? "control.resumeAndContinue" : "control.lifecycle")) return "unsupported-command-shape";
|
|
384
|
+
if (!REF.test(command.commandId) || !IDEMPOTENCY.test(command.idempotencyKey) || !timestamp(command.requestedAt) || !timestamp(command.expiresAt)
|
|
385
|
+
|| Date.parse(command.requestedAt) > Date.parse(command.expiresAt) || Date.parse(command.expiresAt) - Date.parse(command.requestedAt) > 300_000) return "invalid-command-metadata";
|
|
386
|
+
if (!exactKeys(command.identity, ["projectRef", "runtimeInstanceId", "sessionRef", "taskId", "taskRunId", "agentOperationId", "toolCallId"])
|
|
387
|
+
|| !exactKeys(command.expectedRevisions, ["runtimeRevision", "taskRevision", "controlRevision", "workspaceRevision", "indexRevision", "approvalRevision", "sessionOptionRevision", "queueRevision", "workspacePreimage", "indexPreimage", "patchPreimage"])) return "invalid-authority-binding";
|
|
388
|
+
if (command.expectedRevisions.workspacePreimage !== null || command.expectedRevisions.indexPreimage !== null || command.expectedRevisions.patchPreimage !== null
|
|
389
|
+
|| command.action !== "lifecycle.stop" && (command.expectedRevisions.taskRevision === null || command.expectedRevisions.controlRevision === null)) return "invalid-authority-binding";
|
|
390
|
+
if (command.actionDigest !== controlActionDigest(command)) return "action-digest-mismatch";
|
|
391
|
+
if (command.action === "lifecycle.stop") return exactKeys(command.payload, ["requestedScope"]) && command.payload.requestedScope === "current-agent-operation"
|
|
392
|
+
&& REF.test(String(command.identity.agentOperationId ?? "")) ? null : "invalid-stop-payload";
|
|
393
|
+
if (!command.identity.taskId || !command.identity.taskRunId) return "task-identity-required";
|
|
394
|
+
if (command.action === "lifecycle.pause") return exactKeys(command.payload, ["safePointPolicy"])
|
|
395
|
+
&& command.payload.safePointPolicy === "after-current-atomic-unit" ? null : "invalid-pause-payload";
|
|
396
|
+
if (command.action === "lifecycle.resume-and-continue") {
|
|
397
|
+
const payload = command.payload as NewOperationChatCommand["payload"];
|
|
398
|
+
return exactKeys(payload, ["messageRequestId", "capabilityAction", "delivery", "text", "attachmentRefs", "contentDigest"])
|
|
399
|
+
&& REF.test(String(payload.messageRequestId ?? "")) && payload.capabilityAction === "send" && payload.delivery === "new-operation"
|
|
400
|
+
&& typeof payload.text === "string" && payload.text.length > 0 && Buffer.byteLength(payload.text) <= 65_536 && !payload.text.includes("\0")
|
|
401
|
+
&& Array.isArray(payload.attachmentRefs) && payload.attachmentRefs.length <= 4
|
|
402
|
+
&& new Set(payload.attachmentRefs).size === payload.attachmentRefs.length && payload.attachmentRefs.every((item) => REF.test(String(item)))
|
|
403
|
+
&& payload.contentDigest === chatContentDigest(payload) && command.expectedRevisions.queueRevision !== null
|
|
404
|
+
&& command.identity.agentOperationId === null ? null : "invalid-resume-and-continue-payload";
|
|
405
|
+
}
|
|
406
|
+
return exactKeys(command.payload, []) ? null : "invalid-resume-payload";
|
|
407
|
+
}
|
|
408
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { RuntimeEventDraft } from "../../piagent-core/runtime/inspection/runtime-event-store.ts";
|
|
2
|
+
import type { BridgeSnapshot } from "./same-session-bridge.ts";
|
|
3
|
+
import type { LifecycleEvent } from "./lifecycle-controller.ts";
|
|
4
|
+
|
|
5
|
+
export function lifecycleRuntimeDraft(event: LifecycleEvent, snapshot: BridgeSnapshot, observedAt = new Date().toISOString()): RuntimeEventDraft | null {
|
|
6
|
+
if (event.kind !== "control.changed" || !event.fact) return null;
|
|
7
|
+
const identity = snapshot.identity, revisions = snapshot.revisions;
|
|
8
|
+
if (!identity?.taskId || !identity.taskRunId || !revisions || !event.commandId || !event.idempotencyKeyDigest
|
|
9
|
+
|| !event.fromControlState || !event.toControlState || !event.expectedControlRevision || event.requestSequence === undefined) return null;
|
|
10
|
+
const operationId = event.agentOperationId ?? identity.agentOperationId;
|
|
11
|
+
if (event.fact.startsWith("stop-") && !operationId) return null;
|
|
12
|
+
return { sourceObservedAt: observedAt, projectRef: identity.projectRef, runtimeInstanceId: identity.runtimeInstanceId,
|
|
13
|
+
sessionRef: identity.sessionRef, taskId: identity.taskId, taskRunId: identity.taskRunId, agentOperationId: operationId,
|
|
14
|
+
turnIndex: null, messageRef: null, toolCallId: null, revision: revisions, kind: `task-control.${event.fact}` as RuntimeEventDraft["kind"],
|
|
15
|
+
correlation: { commandId: event.commandId, messageRequestId: null, replacementId: null, approvalRequestId: null,
|
|
16
|
+
causationEventId: null, idempotencyKeyDigest: event.idempotencyKeyDigest }, evidence: "observed",
|
|
17
|
+
payload: { action: event.action?.replace("lifecycle.", ""), fact: event.fact, fromControlState: event.fromControlState,
|
|
18
|
+
toControlState: event.toControlState, taskOutcome: "pending", resultCode: event.resultCode, requestSequence: event.requestSequence,
|
|
19
|
+
parentSequence: event.parentSequence ?? null, expectedControlRevision: event.expectedControlRevision,
|
|
20
|
+
preWorkingTreeDigest: event.preWorkingTreeDigest ?? null, postWorkingTreeDigest: event.postWorkingTreeDigest ?? null,
|
|
21
|
+
dispatchState: event.fact === "resume-rejected" ? "rejected" : "none" },
|
|
22
|
+
redaction: { applied: false, valuesRemoved: 0, truncated: false } };
|
|
23
|
+
}
|