@piagent/platform 1.3.1 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (329) hide show
  1. package/CHANGELOG.md +132 -0
  2. package/README.md +10 -4
  3. package/README.vi.md +27 -0
  4. package/architecture/layers.json +96 -1
  5. package/docs/README.md +1 -0
  6. package/docs/architecture.md +1 -0
  7. package/docs/authority-manifest.md +1 -0
  8. package/docs/auto-delegation-policy.md +1 -0
  9. package/docs/capability-packs.md +1 -0
  10. package/docs/command-reference-vietnamese.md +5 -4
  11. package/docs/context-engine.md +1 -0
  12. package/docs/context-window-policy.md +1 -0
  13. package/docs/distribution-standard.md +8 -7
  14. package/docs/en/architecture.md +13 -0
  15. package/docs/herdr-workflow.md +1 -0
  16. package/docs/languages.json +20 -4
  17. package/docs/mcp-and-tools.md +125 -9
  18. package/docs/memory-policy.md +1 -0
  19. package/docs/model-options.md +1 -0
  20. package/docs/oauth-providers.md +1 -0
  21. package/docs/operator-manual-vietnamese.md +15 -12
  22. package/docs/package-architecture-notes.md +1 -0
  23. package/docs/project-adapters.md +1 -0
  24. package/docs/project-onboarding.md +1 -0
  25. package/docs/publishing-for-teams.md +37 -0
  26. package/docs/quality-benchmark.md +1 -0
  27. package/docs/quickstart-vietnamese.md +3 -2
  28. package/docs/release-install-policy.md +22 -8
  29. package/docs/runtime-harness-standard.md +2 -1
  30. package/docs/runtime-policy-design.md +1 -0
  31. package/docs/runtime-quality-baseline.md +1 -0
  32. package/docs/security-redaction-benchmark.md +1 -0
  33. package/docs/security-threat-model.md +2 -1
  34. package/docs/subagent-orchestration-capabilities.md +1 -0
  35. package/docs/subagents-and-multiagent.md +1 -0
  36. package/docs/task-implementation-contract.md +12 -4
  37. package/docs/task-lifecycle-vietnamese.md +1 -0
  38. package/docs/team-onboarding.md +3 -2
  39. package/docs/third-party-neutrality.md +26 -0
  40. package/docs/usage-observability.md +71 -0
  41. package/docs/vercel-docs-site.md +1 -0
  42. package/docs/vi/architecture.md +13 -0
  43. package/docs/workflow-recipes.md +1 -0
  44. package/docs-site/architecture.html +5 -1
  45. package/docs-site/benchmark.html +5 -1
  46. package/docs-site/commands.html +5 -1
  47. package/docs-site/content/en/index.html +49 -0
  48. package/docs-site/content/en/runtime.html +13 -0
  49. package/docs-site/content/index.html +49 -0
  50. package/docs-site/content/runtime.html +28 -0
  51. package/docs-site/context-engine.html +5 -1
  52. package/docs-site/en/architecture.html +5 -1
  53. package/docs-site/en/benchmark.html +5 -1
  54. package/docs-site/en/commands.html +5 -1
  55. package/docs-site/en/context-engine.html +5 -1
  56. package/docs-site/en/index.html +54 -1
  57. package/docs-site/en/mcp-approval.html +5 -1
  58. package/docs-site/en/mcp-auth.html +5 -1
  59. package/docs-site/en/mcp-servers.html +5 -1
  60. package/docs-site/en/mcp.html +5 -1
  61. package/docs-site/en/permissions.html +5 -1
  62. package/docs-site/en/profiles.html +5 -1
  63. package/docs-site/en/quickstart.html +5 -1
  64. package/docs-site/en/runtime.html +18 -1
  65. package/docs-site/en/scope.html +5 -1
  66. package/docs-site/en/security.html +5 -1
  67. package/docs-site/en/team.html +5 -1
  68. package/docs-site/en/whats-new.html +5 -1
  69. package/docs-site/en/workflows.html +5 -1
  70. package/docs-site/index.html +54 -1
  71. package/docs-site/mcp-approval.html +5 -1
  72. package/docs-site/mcp-auth.html +5 -1
  73. package/docs-site/mcp-servers.html +5 -1
  74. package/docs-site/mcp.html +5 -1
  75. package/docs-site/permissions.html +5 -1
  76. package/docs-site/profiles.html +5 -1
  77. package/docs-site/quickstart.html +5 -1
  78. package/docs-site/runtime.html +33 -1
  79. package/docs-site/scope.html +5 -1
  80. package/docs-site/security.html +5 -1
  81. package/docs-site/team.html +5 -1
  82. package/docs-site/whats-new.html +5 -1
  83. package/docs-site/workflows.html +5 -1
  84. package/evals/fixtures/mutation-provenance-record.invalid.json +17 -0
  85. package/evals/fixtures/mutation-provenance-record.valid.json +27 -0
  86. package/evals/fixtures/piagent-webui/approval-v1.invalid.json +54 -0
  87. package/evals/fixtures/piagent-webui/approval-v1.valid.json +58 -0
  88. package/evals/fixtures/piagent-webui/attachment-v1.invalid.json +25 -0
  89. package/evals/fixtures/piagent-webui/attachment-v1.valid.json +25 -0
  90. package/evals/fixtures/piagent-webui/capabilities-v1.invalid.json +51 -0
  91. package/evals/fixtures/piagent-webui/capabilities-v1.valid.json +122 -0
  92. package/evals/fixtures/piagent-webui/commit-summary-v1.invalid.json +10 -0
  93. package/evals/fixtures/piagent-webui/commit-summary-v1.valid.json +25 -0
  94. package/evals/fixtures/piagent-webui/control-command-v1.invalid.json +37 -0
  95. package/evals/fixtures/piagent-webui/control-command-v1.valid.json +35 -0
  96. package/evals/fixtures/piagent-webui/diff-v1.invalid.json +13 -0
  97. package/evals/fixtures/piagent-webui/diff-v1.valid.json +141 -0
  98. package/evals/fixtures/piagent-webui/gateway-capabilities-v1.invalid.json +35 -0
  99. package/evals/fixtures/piagent-webui/gateway-capabilities-v1.valid.json +35 -0
  100. package/evals/fixtures/piagent-webui/gateway-protocol-v1.invalid.json +14 -0
  101. package/evals/fixtures/piagent-webui/gateway-protocol-v1.valid.json +14 -0
  102. package/evals/fixtures/piagent-webui/handoff-history-v1.invalid.json +16 -0
  103. package/evals/fixtures/piagent-webui/handoff-history-v1.valid.json +16 -0
  104. package/evals/fixtures/piagent-webui/model-catalog-v1.invalid.json +31 -0
  105. package/evals/fixtures/piagent-webui/model-catalog-v1.valid.json +43 -0
  106. package/evals/fixtures/piagent-webui/queue-v1.invalid.json +29 -0
  107. package/evals/fixtures/piagent-webui/queue-v1.valid.json +44 -0
  108. package/evals/fixtures/piagent-webui/recovery-history-v1.invalid.json +17 -0
  109. package/evals/fixtures/piagent-webui/recovery-history-v1.valid.json +20 -0
  110. package/evals/fixtures/piagent-webui/release-monitor-v1.invalid.json +12 -0
  111. package/evals/fixtures/piagent-webui/release-monitor-v1.valid.json +29 -0
  112. package/evals/fixtures/piagent-webui/review-state-v1.invalid.json +25 -0
  113. package/evals/fixtures/piagent-webui/review-state-v1.valid.json +38 -0
  114. package/evals/fixtures/piagent-webui/runtime-event-v2.invalid.json +49 -0
  115. package/evals/fixtures/piagent-webui/runtime-event-v2.valid.json +49 -0
  116. package/evals/fixtures/piagent-webui/session-catalog-v1.invalid.json +17 -0
  117. package/evals/fixtures/piagent-webui/session-catalog-v1.valid.json +58 -0
  118. package/evals/fixtures/piagent-webui/session-command-v1.invalid.json +19 -0
  119. package/evals/fixtures/piagent-webui/session-command-v1.valid.json +19 -0
  120. package/evals/fixtures/piagent-webui/snapshot-v1.invalid.json +5 -0
  121. package/evals/fixtures/piagent-webui/snapshot-v1.valid.json +191 -0
  122. package/evals/fixtures/piagent-webui/source-change-v1.invalid.json +57 -0
  123. package/evals/fixtures/piagent-webui/source-change-v1.valid.json +98 -0
  124. package/evals/fixtures/piagent-webui/source-mutation-v1.invalid.json +19 -0
  125. package/evals/fixtures/piagent-webui/source-mutation-v1.valid.json +38 -0
  126. package/evals/fixtures/piagent-webui/source-revert-v1.invalid.json +20 -0
  127. package/evals/fixtures/piagent-webui/source-revert-v1.valid.json +62 -0
  128. package/evals/fixtures/piagent-webui/subagent-tree-v1.invalid.json +26 -0
  129. package/evals/fixtures/piagent-webui/subagent-tree-v1.valid.json +39 -0
  130. package/evals/fixtures/piagent-webui/task-index-v1.invalid.json +15 -0
  131. package/evals/fixtures/piagent-webui/task-index-v1.valid.json +15 -0
  132. package/evals/fixtures/piagent-webui/task-timeline-v1.invalid.json +14 -0
  133. package/evals/fixtures/piagent-webui/task-timeline-v1.valid.json +16 -0
  134. package/evals/fixtures/piagent-webui/transcript-v1.invalid.json +35 -0
  135. package/evals/fixtures/piagent-webui/transcript-v1.valid.json +55 -0
  136. package/evals/fixtures/task-baseline-manifest.invalid.json +16 -0
  137. package/evals/fixtures/task-baseline-manifest.valid.json +41 -0
  138. package/evals/fixtures/verifier-file-snapshot.invalid.json +21 -0
  139. package/evals/fixtures/verifier-file-snapshot.valid.json +21 -0
  140. package/package.json +43 -4
  141. package/packages/piagent-core/README.md +3 -2
  142. package/packages/piagent-core/benchmark/benchmark-candidate.d.ts +1 -0
  143. package/packages/piagent-core/benchmark/benchmark-forensics.d.ts +1 -0
  144. package/packages/piagent-core/benchmark/benchmark-ledger.d.ts +4 -0
  145. package/packages/piagent-core/benchmark/benchmark-record-validation.d.ts +1 -0
  146. package/packages/piagent-core/benchmark/benchmark-runtime.d.ts +1 -0
  147. package/packages/piagent-core/capabilities/capability-core.js +2 -2
  148. package/packages/piagent-core/capabilities/capability-verification-cache.js +17 -7
  149. package/packages/piagent-core/capabilities/runtime-integrity.js +190 -0
  150. package/packages/piagent-core/extensions/piagent-guard.ts +80 -272
  151. package/packages/piagent-core/extensions/redaction-core.d.ts +2 -0
  152. package/packages/piagent-core/extensions/runtime-evidence.js +12 -1
  153. package/packages/piagent-core/extensions/shell-reach.ts +250 -0
  154. package/packages/piagent-core/extensions/task-journal.js +30 -1
  155. package/packages/piagent-core/extensions/task-state.js +33 -36
  156. package/packages/piagent-core/mcp/mcp-command-actions.js +1 -1
  157. package/packages/piagent-core/mcp/mcp-server-catalog.js +139 -9
  158. package/packages/piagent-core/package.json +1 -1
  159. package/packages/piagent-core/runtime/hooks/session-start-hook.ts +2 -2
  160. package/packages/piagent-core/runtime/hooks/tool-call-hook.ts +12 -2
  161. package/packages/piagent-core/runtime/hooks/tool-result-hook.ts +20 -19
  162. package/packages/piagent-core/runtime/hooks/tool-result-metadata.ts +13 -0
  163. package/packages/piagent-core/runtime/input/chat-images.ts +2 -2
  164. package/packages/piagent-core/runtime/inspection/activity-event-adapter.ts +94 -0
  165. package/packages/piagent-core/runtime/inspection/approval-broker.ts +318 -0
  166. package/packages/piagent-core/runtime/inspection/commit-summary-projection.ts +59 -0
  167. package/packages/piagent-core/runtime/inspection/context-telemetry-inspection.ts +37 -0
  168. package/packages/piagent-core/runtime/inspection/criteria-links.ts +295 -0
  169. package/packages/piagent-core/runtime/inspection/diff-projection.ts +499 -0
  170. package/packages/piagent-core/runtime/inspection/git-filter-safety.ts +38 -0
  171. package/packages/piagent-core/runtime/inspection/git-numstat-adapter.ts +71 -0
  172. package/packages/piagent-core/runtime/inspection/git-status-adapter.ts +493 -0
  173. package/packages/piagent-core/runtime/inspection/git-tree-adapter.ts +108 -0
  174. package/packages/piagent-core/runtime/inspection/mcp-control.ts +10 -0
  175. package/packages/piagent-core/runtime/inspection/mutation-provenance-contract.ts +131 -0
  176. package/packages/piagent-core/runtime/inspection/mutation-provenance-recorder.ts +48 -0
  177. package/packages/piagent-core/runtime/inspection/mutation-provenance-store.ts +161 -0
  178. package/packages/piagent-core/runtime/inspection/project-runtime-inspection.ts +36 -0
  179. package/packages/piagent-core/runtime/inspection/review-state-contract.ts +108 -0
  180. package/packages/piagent-core/runtime/inspection/review-state-projection.ts +93 -0
  181. package/packages/piagent-core/runtime/inspection/review-state-store.ts +112 -0
  182. package/packages/piagent-core/runtime/inspection/runtime-event-store.ts +262 -0
  183. package/packages/piagent-core/runtime/inspection/same-process-bridge-proof.ts +103 -0
  184. package/packages/piagent-core/runtime/inspection/source-change-projection.ts +471 -0
  185. package/packages/piagent-core/runtime/inspection/source-evidence-contract.ts +139 -0
  186. package/packages/piagent-core/runtime/inspection/source-evidence-store.ts +315 -0
  187. package/packages/piagent-core/runtime/inspection/source-handoff-store.ts +70 -0
  188. package/packages/piagent-core/runtime/inspection/source-inspection-plan.ts +34 -0
  189. package/packages/piagent-core/runtime/inspection/source-mutation-projection.ts +164 -0
  190. package/packages/piagent-core/runtime/inspection/source-mutation-store.ts +168 -0
  191. package/packages/piagent-core/runtime/inspection/source-open-target.ts +38 -0
  192. package/packages/piagent-core/runtime/inspection/source-revert-projection.ts +147 -0
  193. package/packages/piagent-core/runtime/inspection/task-baseline-start-capture.ts +22 -0
  194. package/packages/piagent-core/runtime/inspection/task-compaction-history.ts +160 -0
  195. package/packages/piagent-core/runtime/inspection/task-control-journal.ts +131 -0
  196. package/packages/piagent-core/runtime/inspection/task-handoff-history.ts +95 -0
  197. package/packages/piagent-core/runtime/inspection/task-provenance-projection.ts +60 -0
  198. package/packages/piagent-core/runtime/inspection/task-recovery-timeline.ts +88 -0
  199. package/packages/piagent-core/runtime/inspection/task-run-index.ts +87 -0
  200. package/packages/piagent-core/runtime/inspection/task-source-projection.ts +401 -0
  201. package/packages/piagent-core/runtime/inspection/task-subagent-tree.ts +101 -0
  202. package/packages/piagent-core/runtime/inspection/text-diff.ts +60 -0
  203. package/packages/piagent-core/runtime/inspection/verifier-snapshot-contract.ts +114 -0
  204. package/packages/piagent-core/runtime/inspection/verifier-snapshot-store.ts +189 -0
  205. package/packages/piagent-core/runtime/inspection/webui-snapshot.ts +320 -0
  206. package/packages/piagent-core/runtime/inspection/workspace-file-reader.ts +132 -0
  207. package/packages/piagent-core/runtime/inspection/workspace-source-projection.ts +96 -0
  208. package/packages/piagent-core/runtime/inspection/zero-turn-conformance.ts +175 -0
  209. package/packages/piagent-core/runtime/orchestration/owned-work-budget.ts +93 -6
  210. package/packages/piagent-core/runtime/policy/block-remedy.ts +139 -0
  211. package/packages/piagent-core/runtime/policy/source-index-transaction.ts +173 -0
  212. package/packages/piagent-core/runtime/policy/source-mutation-guard-binding.ts +42 -0
  213. package/packages/piagent-core/runtime/policy/source-mutation-guard.ts +184 -0
  214. package/packages/piagent-core/runtime/policy/source-worktree-transaction.ts +105 -0
  215. package/packages/piagent-core/runtime/product/activity-inspector-footer.ts +5 -3
  216. package/packages/piagent-core/runtime/product/activity-inspector.ts +85 -343
  217. package/packages/piagent-core/runtime/recovery/resume-state.ts +38 -1
  218. package/packages/piagent-core/runtime/registration/activity-inspector-command.ts +68 -14
  219. package/packages/piagent-core/runtime/registration/task-start-tool.ts +22 -27
  220. package/packages/piagent-core/runtime/session/model-authorship-state.ts +31 -3
  221. package/packages/piagent-core/runtime/session/runtime-state.ts +11 -1
  222. package/packages/piagent-core/runtime/session/token-economics.js +34 -0
  223. package/packages/piagent-core/runtime/tools/phase-tool-runtime.ts +2 -1
  224. package/packages/piagent-core/runtime/workflows/task-intake.ts +5 -0
  225. package/packages/piagent-core/security/sensitive-data.js +7 -0
  226. package/packages/piagent-webui/dist/client/assets/index-DwKCWbwd.css +1 -0
  227. package/packages/piagent-webui/dist/client/assets/index-bu7XpD9Q.js +172 -0
  228. package/packages/piagent-webui/dist/client/index.html +16 -0
  229. package/packages/piagent-webui/extension/attachment-store.ts +323 -0
  230. package/packages/piagent-webui/extension/held-message-queue.ts +311 -0
  231. package/packages/piagent-webui/extension/lifecycle-controller.ts +423 -0
  232. package/packages/piagent-webui/extension/lifecycle-event-adapter.ts +23 -0
  233. package/packages/piagent-webui/extension/piagent-webui.ts +470 -0
  234. package/packages/piagent-webui/extension/review-controller.ts +160 -0
  235. package/packages/piagent-webui/extension/same-session-bridge.ts +500 -0
  236. package/packages/piagent-webui/extension/session-options-controller.ts +281 -0
  237. package/packages/piagent-webui/extension/session-stream-adapter.ts +249 -0
  238. package/packages/piagent-webui/extension/source-mutation-controller.ts +215 -0
  239. package/packages/piagent-webui/extension/source-open-controller.ts +136 -0
  240. package/packages/piagent-webui/extension/source-revert-controller.ts +189 -0
  241. package/packages/piagent-webui/extension/terminal-session-adapter.ts +73 -0
  242. package/packages/piagent-webui/extension/vscode-handoff.ts +51 -0
  243. package/packages/piagent-webui/gateway/control-socket.ts +92 -0
  244. package/packages/piagent-webui/gateway/extension-authority.ts +47 -0
  245. package/packages/piagent-webui/gateway/gateway-events.ts +60 -0
  246. package/packages/piagent-webui/gateway/gateway-protocol-service.ts +64 -0
  247. package/packages/piagent-webui/gateway/gateway-service.ts +215 -0
  248. package/packages/piagent-webui/gateway/gateway-session-stream.ts +110 -0
  249. package/packages/piagent-webui/gateway/mcp-auth-broker.ts +158 -0
  250. package/packages/piagent-webui/gateway/native-project-picker.ts +29 -0
  251. package/packages/piagent-webui/gateway/pi-host.ts +41 -0
  252. package/packages/piagent-webui/gateway/profile-state.ts +1 -0
  253. package/packages/piagent-webui/gateway/project-registry.ts +108 -0
  254. package/packages/piagent-webui/gateway/provider-auth-broker.ts +172 -0
  255. package/packages/piagent-webui/gateway/session-catalog.ts +128 -0
  256. package/packages/piagent-webui/gateway/session-command-controller.ts +237 -0
  257. package/packages/piagent-webui/gateway/session-command-store.ts +224 -0
  258. package/packages/piagent-webui/gateway/session-inspection-registry.ts +239 -0
  259. package/packages/piagent-webui/gateway/session-lease-store.ts +1 -0
  260. package/packages/piagent-webui/gateway/session-metadata-store.ts +152 -0
  261. package/packages/piagent-webui/gateway/session-runtime-supervisor.ts +489 -0
  262. package/packages/piagent-webui/ownership/gateway-runtime-context.ts +8 -0
  263. package/packages/piagent-webui/ownership/profile-state.ts +117 -0
  264. package/packages/piagent-webui/ownership/session-lease-store.ts +329 -0
  265. package/packages/piagent-webui/ownership/session-refs.ts +8 -0
  266. package/packages/piagent-webui/package.json +33 -0
  267. package/packages/piagent-webui/server/README.md +4 -0
  268. package/packages/piagent-webui/server/benchmark-release-monitor.ts +230 -0
  269. package/packages/piagent-webui/server/core-inspection-provider.ts +403 -0
  270. package/packages/piagent-webui/server/gateway-websocket.ts +143 -0
  271. package/packages/piagent-webui/server/http-security.ts +27 -0
  272. package/packages/piagent-webui/server/ipc-read-model-client.ts +89 -0
  273. package/packages/piagent-webui/server/loopback-server.ts +368 -0
  274. package/packages/piagent-webui/server/read-model-provider.ts +37 -0
  275. package/packages/piagent-webui/server/read-only-router.ts +105 -0
  276. package/packages/piagent-webui/server/session-auth.ts +88 -0
  277. package/packages/piagent-webui/server/sidecar-main.ts +86 -0
  278. package/packages/piagent-webui/server/sse-hub.ts +76 -0
  279. package/packages/piagent-webui/server/static-bundle.ts +40 -0
  280. package/packages/piagent-webui/server/transcript-projection.ts +125 -0
  281. package/schemas/mutation-provenance-record.schema.json +100 -0
  282. package/schemas/piagent-webui/approval-v1.schema.json +654 -0
  283. package/schemas/piagent-webui/attachment-v1.schema.json +267 -0
  284. package/schemas/piagent-webui/capabilities-v1.schema.json +729 -0
  285. package/schemas/piagent-webui/catalog-v1.json +240 -0
  286. package/schemas/piagent-webui/commit-summary-v1.schema.json +63 -0
  287. package/schemas/piagent-webui/common-v1.schema.json +479 -0
  288. package/schemas/piagent-webui/control-command-v1.schema.json +1780 -0
  289. package/schemas/piagent-webui/diff-v1.schema.json +826 -0
  290. package/schemas/piagent-webui/gateway-capabilities-v1.schema.json +136 -0
  291. package/schemas/piagent-webui/gateway-protocol-v1.schema.json +456 -0
  292. package/schemas/piagent-webui/handoff-history-v1.schema.json +92 -0
  293. package/schemas/piagent-webui/model-catalog-v1.schema.json +95 -0
  294. package/schemas/piagent-webui/queue-v1.schema.json +99 -0
  295. package/schemas/piagent-webui/recovery-history-v1.schema.json +144 -0
  296. package/schemas/piagent-webui/release-monitor-v1.schema.json +173 -0
  297. package/schemas/piagent-webui/review-state-v1.schema.json +206 -0
  298. package/schemas/piagent-webui/runtime-event-v2.schema.json +5206 -0
  299. package/schemas/piagent-webui/session-catalog-v1.schema.json +222 -0
  300. package/schemas/piagent-webui/session-command-v1.schema.json +390 -0
  301. package/schemas/piagent-webui/snapshot-v1.schema.json +2622 -0
  302. package/schemas/piagent-webui/source-change-v1.schema.json +763 -0
  303. package/schemas/piagent-webui/source-mutation-v1.schema.json +96 -0
  304. package/schemas/piagent-webui/source-revert-v1.schema.json +130 -0
  305. package/schemas/piagent-webui/subagent-tree-v1.schema.json +88 -0
  306. package/schemas/piagent-webui/task-index-v1.schema.json +74 -0
  307. package/schemas/piagent-webui/task-timeline-v1.schema.json +49 -0
  308. package/schemas/piagent-webui/transcript-v1.schema.json +243 -0
  309. package/schemas/task-baseline-manifest.schema.json +122 -0
  310. package/schemas/verifier-file-snapshot.schema.json +81 -0
  311. package/scripts/build-docs-site.mjs +21 -1
  312. package/scripts/check-architecture.mjs +1 -0
  313. package/scripts/check-doc-languages.mjs +19 -2
  314. package/scripts/check-third-party-neutrality.mjs +43 -0
  315. package/scripts/explain-command.mjs +240 -0
  316. package/scripts/install-global.sh +105 -4
  317. package/scripts/mcp-manage.mjs +17 -4
  318. package/scripts/pi-session-stats.sh +10 -2
  319. package/scripts/piagent-cli.mjs +30 -3
  320. package/scripts/piagent-dashboard.mjs +261 -0
  321. package/scripts/piagent-webui-launcher.mjs +121 -0
  322. package/scripts/setup.sh +69 -33
  323. package/scripts/traffic-snapshot.mjs +214 -0
  324. package/scripts/typescript-loader.mjs +42 -1
  325. package/scripts/uninstall-global.sh +53 -2
  326. package/scripts/update-global.mjs +33 -1
  327. package/scripts/verify-local.sh +257 -0
  328. package/scripts/verify-release-identity.mjs +4 -1
  329. package/scripts/verify-translation-pairing.mjs +121 -0
@@ -0,0 +1,215 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ import { appendSourceMutationEvidence, readSourceMutationEvidence, type SourceMutationEvidenceRecord } from "../../piagent-core/runtime/inspection/source-mutation-store.ts";
4
+ import { canonicalReviewValue, reviewDigest } from "../../piagent-core/runtime/inspection/review-state-contract.ts";
5
+ import type { SourceMutationAction, SourceMutationAuthority, SourceMutationProjection, SourceMutationTarget } from "../../piagent-core/runtime/inspection/source-mutation-projection.ts";
6
+ import type { SourceIndexTransactionResult } from "../../piagent-core/runtime/policy/source-index-transaction.ts";
7
+ import { controlActionDigest, type BridgeIdentity, type BridgeRevisions, type SameSessionPiBridge } from "./same-session-bridge.ts";
8
+
9
+ const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/, PUBLIC_REF = /^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/,
10
+ REVISION = /^[A-Za-z0-9][A-Za-z0-9._:~-]{0,159}$/, DIGEST = /^sha256:[a-f0-9]{64}$/,
11
+ WORKSPACE = /^wt-content-v2:[a-f0-9]{64}$/, IDEMPOTENCY = /^[A-Za-z0-9._~-]{32,128}$/;
12
+ const REVISION_KEYS = ["runtimeRevision", "taskRevision", "controlRevision", "workspaceRevision", "indexRevision", "approvalRevision", "sessionOptionRevision", "queueRevision"];
13
+
14
+ type MutationCommand = {
15
+ schemaVersion: 1; version: "piagent-webui-control-v1"; messageType: "command"; commandId: string; idempotencyKey: string;
16
+ requestedAt: string; expiresAt: string; capabilityScope: "reviewActions"; action: SourceMutationAction; actionDigest: string;
17
+ identity: BridgeIdentity; expectedRevisions: BridgeRevisions & { workspacePreimage: string; indexPreimage: string; patchPreimage: string };
18
+ payload: { fileRef: string; hunkRefs: string[]; contentDigest: string };
19
+ };
20
+ export type SourceMutationReceipt = {
21
+ schemaVersion: 1; version: "piagent-webui-control-v1"; messageType: "receipt"; commandId: string; idempotencyKeyDigest: string;
22
+ action: SourceMutationAction; actionDigest: string; identity: BridgeIdentity; phase: "settled" | "rejected" | "uncertain";
23
+ resultCode: "staged" | "unstaged" | "effect-unknown" | "stale-revision" | "identity-mismatch" | "capability-unavailable"
24
+ | "idempotency-payload-mismatch" | "expired" | "invalid-command" | "resync-required" | "terminal-task";
25
+ requestedAt: string; settledAt: string; observedRevisionsBefore: BridgeRevisions; observedRevisionsAfter: BridgeRevisions;
26
+ deduplicated: boolean; auditRef: string | null; settlementEvidenceRef: string | null;
27
+ error: { code: string; message: string; retryable: boolean } | null;
28
+ };
29
+
30
+ function sha(value: string): string { return `sha256:${createHash("sha256").update(value).digest("hex")}`; }
31
+ function same(left: unknown, right: unknown): boolean { return canonicalReviewValue(left) === canonicalReviewValue(right); }
32
+ function exactKeys(value: unknown, keys: string[]): boolean { return Boolean(value && typeof value === "object" && !Array.isArray(value)
33
+ && same(Object.keys(value as object).sort(), [...keys].sort())); }
34
+ function timestamp(value: unknown): value is string {
35
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) return false;
36
+ const parsed = Date.parse(value); return Number.isFinite(parsed) && new Date(parsed).toISOString() === value;
37
+ }
38
+ function wireIdentity(value: BridgeIdentity): BridgeIdentity { return { projectRef: value.projectRef, runtimeInstanceId: value.runtimeInstanceId,
39
+ sessionRef: value.sessionRef, taskId: value.taskId, taskRunId: value.taskRunId, agentOperationId: null, toolCallId: null }; }
40
+ function wireRevisions(value: Record<string, any>): BridgeRevisions { return { runtimeRevision: value.runtimeRevision, taskRevision: value.taskRevision,
41
+ controlRevision: value.controlRevision, workspaceRevision: value.workspaceRevision, indexRevision: value.indexRevision,
42
+ approvalRevision: value.approvalRevision, sessionOptionRevision: value.sessionOptionRevision, queueRevision: value.queueRevision }; }
43
+
44
+ function receiptFromRecord(record: SourceMutationEvidenceRecord, deduplicated: boolean): SourceMutationReceipt {
45
+ if (record.action === "source.revert") throw new Error("source-mutation-evidence-action-mismatch");
46
+ const action: SourceMutationAction = record.action;
47
+ const identity = { projectRef: record.projectRef, runtimeInstanceId: record.runtimeInstanceId, sessionRef: record.sessionRef,
48
+ taskId: record.taskId, taskRunId: record.taskRunId, agentOperationId: null, toolCallId: null } as BridgeIdentity;
49
+ const before = wireRevisions(record.observedRevisionsBefore), after = wireRevisions(record.observedRevisionsAfter ?? record.observedRevisionsBefore);
50
+ if (record.phase === "settled") return { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "receipt", commandId: record.commandId,
51
+ idempotencyKeyDigest: record.idempotencyKeyDigest, action, actionDigest: record.actionDigest, identity, phase: "settled",
52
+ resultCode: action === "source.stage" ? "staged" : "unstaged", requestedAt: record.requestedAt, settledAt: record.recordedAt,
53
+ observedRevisionsBefore: before, observedRevisionsAfter: after, deduplicated, auditRef: record.evidenceRef,
54
+ settlementEvidenceRef: record.evidenceRef, error: null };
55
+ if (record.phase === "rejected") {
56
+ const stale = record.failureCode === "mutation-preimage-stale" || record.failureCode === "mutation-guard-precondition-stale";
57
+ return { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "receipt", commandId: record.commandId,
58
+ idempotencyKeyDigest: record.idempotencyKeyDigest, action, actionDigest: record.actionDigest, identity, phase: "rejected",
59
+ resultCode: stale ? "stale-revision" : "capability-unavailable", requestedAt: record.requestedAt, settledAt: record.recordedAt,
60
+ observedRevisionsBefore: before, observedRevisionsAfter: after, deduplicated, auditRef: record.evidenceRef,
61
+ settlementEvidenceRef: null, error: { code: record.failureCode ?? "source-mutation-rejected",
62
+ message: "The Pi guard rejected the selected-file Git index action before commit.", retryable: true } };
63
+ }
64
+ return { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "receipt", commandId: record.commandId,
65
+ idempotencyKeyDigest: record.idempotencyKeyDigest, action, actionDigest: record.actionDigest, identity, phase: "uncertain",
66
+ resultCode: "effect-unknown", requestedAt: record.requestedAt, settledAt: record.recordedAt,
67
+ observedRevisionsBefore: before, observedRevisionsAfter: after, deduplicated, auditRef: record.phase === "uncertain" ? record.evidenceRef : null,
68
+ settlementEvidenceRef: null, error: { code: "source-mutation-effect-unknown", message: "The exact Git index effect could not be confirmed.", retryable: false } };
69
+ }
70
+
71
+ export class SourceMutationController {
72
+ readonly #bridge: SameSessionPiBridge;
73
+ readonly #projectRoot: string;
74
+ readonly #resolve: (action: SourceMutationAction, fileRef: string) => Promise<{ projection: SourceMutationProjection; authority: SourceMutationAuthority | null }>;
75
+ readonly #revisions: () => Promise<Record<string, string | null>>;
76
+ readonly #mutate: (input: { identity: { projectRef: string; runtimeInstanceId: string; sessionRef: string; taskId: string; taskRunId: string };
77
+ action: SourceMutationAction; expectedTaskRevision: string; expectedControlRevision: string; expectedIndexPreimage: string;
78
+ expectedWorkspacePreimage: string; selectedHunkRefs: string[]; authority: SourceMutationAuthority }) => Promise<SourceIndexTransactionResult>;
79
+ readonly #now: () => Date;
80
+ #serial: Promise<unknown> = Promise.resolve();
81
+
82
+ constructor(options: { bridge: SameSessionPiBridge; projectRoot: string;
83
+ resolve(action: SourceMutationAction, fileRef: string): Promise<{ projection: SourceMutationProjection; authority: SourceMutationAuthority | null }>;
84
+ revisions(): Promise<Record<string, string | null>>;
85
+ mutate(input: { identity: { projectRef: string; runtimeInstanceId: string; sessionRef: string; taskId: string; taskRunId: string };
86
+ action: SourceMutationAction; expectedTaskRevision: string; expectedControlRevision: string; expectedIndexPreimage: string;
87
+ expectedWorkspacePreimage: string; selectedHunkRefs: string[]; authority: SourceMutationAuthority }): Promise<SourceIndexTransactionResult>;
88
+ now?: () => Date }) {
89
+ this.#bridge = options.bridge; this.#projectRoot = options.projectRoot; this.#resolve = options.resolve;
90
+ this.#revisions = options.revisions; this.#mutate = options.mutate; this.#now = options.now ?? (() => new Date());
91
+ }
92
+
93
+ execute(value: unknown): Promise<SourceMutationReceipt> {
94
+ const run = this.#serial.then(() => this.#execute(value), () => this.#execute(value)); this.#serial = run.catch(() => undefined); return run;
95
+ }
96
+
97
+ async #execute(value: unknown): Promise<SourceMutationReceipt> {
98
+ const command = value as MutationCommand, snapshot = this.#bridge.snapshot(), invalid = this.#validate(value);
99
+ if (snapshot.state !== "ready" || !snapshot.identity || !snapshot.revisions) return this.#reject(command, "resync-required", "mutation-binding-unavailable", true);
100
+ if (invalid) return this.#reject(command, "invalid-command", invalid, false);
101
+ const identity = wireIdentity(snapshot.identity), bridgeRevisions = wireRevisions(snapshot.revisions);
102
+ if (!identity.taskId || !identity.taskRunId || !bridgeRevisions.taskRevision) return this.#reject(command, "capability-unavailable", "active-task-required", false);
103
+ if (snapshot.taskState === "terminal") return this.#reject(command, "terminal-task", "task-terminal", false);
104
+ if (snapshot.liveness !== "idle") return this.#reject(command, "capability-unavailable", "agent-not-idle", true);
105
+ const evidence = readSourceMutationEvidence(this.#projectRoot, identity.taskRunId);
106
+ if (evidence.corruptions.length) return this.#reject(command, "resync-required", "mutation-evidence-corrupt", false);
107
+ const keyDigest = sha(command.idempotencyKey), prior = evidence.records.filter((record) => record.commandId === command.commandId
108
+ || record.idempotencyKeyDigest === keyDigest);
109
+ if (prior.length) {
110
+ if (prior.some((record) => record.commandId !== command.commandId || record.idempotencyKeyDigest !== keyDigest || record.actionDigest !== command.actionDigest
111
+ || record.action !== command.action)) return this.#reject(command, "idempotency-payload-mismatch", "idempotency-payload-mismatch", false);
112
+ if (prior.some((record) => record.runtimeInstanceId !== identity.runtimeInstanceId || record.sessionRef !== identity.sessionRef))
113
+ return this.#reject(command, "identity-mismatch", "runtime-or-session-replaced", false);
114
+ return receiptFromRecord(prior.at(-1)!, true);
115
+ }
116
+ const now = this.#now().getTime();
117
+ if (Date.parse(command.requestedAt) > now + 30_000) return this.#reject(command, "invalid-command", "requested-at-in-future", false);
118
+ if (now > Date.parse(command.expiresAt)) return this.#reject(command, "expired", "command-expired", false);
119
+ if (!same(command.identity, identity)) return this.#reject(command, "identity-mismatch", "identity-mismatch", false);
120
+ if (command.expectedRevisions.runtimeRevision !== bridgeRevisions.runtimeRevision || command.expectedRevisions.taskRevision !== bridgeRevisions.taskRevision
121
+ || command.expectedRevisions.controlRevision !== bridgeRevisions.controlRevision) return this.#reject(command, "stale-revision", "stale-task-control-revision", true);
122
+ let resolved: { projection: SourceMutationProjection; authority: SourceMutationAuthority | null };
123
+ try { resolved = await this.#resolve(command.action, command.payload.fileRef); }
124
+ catch { return this.#reject(command, "capability-unavailable", "mutation-preview-unavailable", true); }
125
+ if (!resolved.authority || resolved.projection.state !== "ready" || !resolved.projection.target)
126
+ return this.#reject(command, "capability-unavailable", resolved.projection.reasonCode ?? "mutation-preview-unavailable", true);
127
+ const target = resolved.projection.target;
128
+ if (!this.#matches(command, target)) return this.#reject(command, "stale-revision", "mutation-preview-stale", true);
129
+ const before = { ...bridgeRevisions, workspaceRevision: target.workspaceRevision, indexRevision: target.indexRevision };
130
+ let requested: SourceMutationEvidenceRecord;
131
+ try { requested = appendSourceMutationEvidence({ projectRoot: this.#projectRoot, projectRef: identity.projectRef,
132
+ runtimeInstanceId: identity.runtimeInstanceId, sessionRef: identity.sessionRef, taskId: identity.taskId, taskRunId: identity.taskRunId,
133
+ commandId: command.commandId, idempotencyKeyDigest: keyDigest, actionDigest: command.actionDigest, action: command.action, target,
134
+ selectedHunkRefs: [...command.payload.hunkRefs], phase: "requested", resultCode: "mutation-requested", failureCode: null,
135
+ requestedAt: command.requestedAt, recordedAt: this.#now().toISOString(),
136
+ beforeIndexPreimage: target.indexPreimage, afterIndexPreimage: null, beforeWorkspacePreimage: target.workspacePreimage,
137
+ afterWorkspacePreimage: null, observedRevisionsBefore: before, observedRevisionsAfter: null }); }
138
+ catch { return this.#reject(command, "capability-unavailable", "mutation-evidence-unavailable", false); }
139
+ let effect: SourceIndexTransactionResult;
140
+ try { effect = await this.#mutate({ identity: { projectRef: identity.projectRef, runtimeInstanceId: identity.runtimeInstanceId,
141
+ sessionRef: identity.sessionRef, taskId: identity.taskId, taskRunId: identity.taskRunId }, action: command.action,
142
+ expectedTaskRevision: target.taskRevision, expectedControlRevision: bridgeRevisions.controlRevision!,
143
+ expectedIndexPreimage: target.indexPreimage, expectedWorkspacePreimage: target.workspacePreimage,
144
+ selectedHunkRefs: [...command.payload.hunkRefs], authority: resolved.authority }); }
145
+ catch { effect = { state: "rejected", reasonCode: "mutation-guard-unavailable", beforeIndexPreimage: target.indexPreimage,
146
+ afterIndexPreimage: null, beforeWorkspacePreimage: target.workspacePreimage, afterWorkspacePreimage: null,
147
+ executor: "pi-guard", directExecution: false }; }
148
+ if (effect.executor !== "pi-guard" || effect.directExecution !== false) effect = { ...effect, state: "uncertain",
149
+ reasonCode: "mutation-executor-untrusted", afterIndexPreimage: null, afterWorkspacePreimage: null,
150
+ executor: "pi-guard", directExecution: false };
151
+ let after: BridgeRevisions;
152
+ try { after = wireRevisions(await this.#revisions()); } catch { after = before; }
153
+ const phase = effect.state, resultCode = effect.state === "settled" ? command.action === "source.stage" ? "staged" : "unstaged"
154
+ : effect.state === "rejected" ? "mutation-rejected" : "effect-unknown";
155
+ try {
156
+ const terminal = appendSourceMutationEvidence({ projectRoot: this.#projectRoot, projectRef: identity.projectRef,
157
+ runtimeInstanceId: identity.runtimeInstanceId, sessionRef: identity.sessionRef, taskId: identity.taskId, taskRunId: identity.taskRunId,
158
+ commandId: command.commandId, idempotencyKeyDigest: keyDigest, actionDigest: command.actionDigest, action: command.action, target,
159
+ selectedHunkRefs: [...command.payload.hunkRefs], phase, resultCode, failureCode: effect.reasonCode,
160
+ requestedAt: command.requestedAt, recordedAt: this.#now().toISOString(), beforeIndexPreimage: target.indexPreimage,
161
+ afterIndexPreimage: effect.afterIndexPreimage, beforeWorkspacePreimage: target.workspacePreimage,
162
+ afterWorkspacePreimage: effect.afterWorkspacePreimage, observedRevisionsBefore: before, observedRevisionsAfter: after });
163
+ return receiptFromRecord(terminal, false);
164
+ } catch { return receiptFromRecord(requested, false); }
165
+ }
166
+
167
+ #matches(command: MutationCommand, target: SourceMutationTarget): boolean {
168
+ return command.payload.fileRef === target.fileRef && command.payload.contentDigest === target.contentDigest
169
+ && same(command.payload.hunkRefs, target.hunkRefs.filter((hunkRef) => command.payload.hunkRefs.includes(hunkRef)))
170
+ && command.expectedRevisions.taskRevision === target.taskRevision && command.expectedRevisions.workspaceRevision === target.workspaceRevision
171
+ && command.expectedRevisions.indexRevision === target.indexRevision && command.expectedRevisions.workspacePreimage === target.workspacePreimage
172
+ && command.expectedRevisions.indexPreimage === target.indexPreimage && command.expectedRevisions.patchPreimage === target.patchPreimage;
173
+ }
174
+
175
+ #validate(value: unknown): string | null {
176
+ const command = value as MutationCommand;
177
+ if (!exactKeys(command, ["schemaVersion", "version", "messageType", "commandId", "idempotencyKey", "requestedAt", "expiresAt", "capabilityScope", "action", "actionDigest", "identity", "expectedRevisions", "payload"])
178
+ || command.schemaVersion !== 1 || command.version !== "piagent-webui-control-v1" || command.messageType !== "command" || command.capabilityScope !== "reviewActions"
179
+ || !["source.stage", "source.unstage"].includes(command.action) || !REF.test(command.commandId) || !IDEMPOTENCY.test(command.idempotencyKey)
180
+ || !timestamp(command.requestedAt) || !timestamp(command.expiresAt) || Date.parse(command.requestedAt) > Date.parse(command.expiresAt)
181
+ || Date.parse(command.expiresAt) - Date.parse(command.requestedAt) > 300_000) return "invalid-command-metadata";
182
+ if (!exactKeys(command.identity, ["projectRef", "runtimeInstanceId", "sessionRef", "taskId", "taskRunId", "agentOperationId", "toolCallId"])
183
+ || ![command.identity.projectRef, command.identity.runtimeInstanceId, command.identity.sessionRef].every((item) => REF.test(item))
184
+ || ![command.identity.taskId, command.identity.taskRunId].every((item) => typeof item === "string" && PUBLIC_REF.test(item))
185
+ || command.identity.agentOperationId !== null || command.identity.toolCallId !== null) return "invalid-command-identity";
186
+ const preimageKeys = [...REVISION_KEYS, "workspacePreimage", "indexPreimage", "patchPreimage"];
187
+ if (!exactKeys(command.expectedRevisions, preimageKeys) || !REVISION.test(command.expectedRevisions.runtimeRevision)
188
+ || !REVISION.test(command.expectedRevisions.taskRevision ?? "") || !REVISION.test(command.expectedRevisions.workspaceRevision ?? "")
189
+ || !REVISION.test(command.expectedRevisions.indexRevision ?? "") || !WORKSPACE.test(command.expectedRevisions.workspacePreimage)
190
+ || !DIGEST.test(command.expectedRevisions.indexPreimage) || !DIGEST.test(command.expectedRevisions.patchPreimage)) return "invalid-mutation-authority";
191
+ if (!exactKeys(command.payload, ["fileRef", "hunkRefs", "contentDigest"]) || !REF.test(command.payload.fileRef)
192
+ || !Array.isArray(command.payload.hunkRefs) || command.payload.hunkRefs.length > 128
193
+ || new Set(command.payload.hunkRefs).size !== command.payload.hunkRefs.length || command.payload.hunkRefs.some((item) => !REF.test(item))
194
+ || !DIGEST.test(command.payload.contentDigest)) return "invalid-mutation-payload";
195
+ if (!DIGEST.test(command.actionDigest) || command.actionDigest !== controlActionDigest(command)) return "action-digest-mismatch";
196
+ return null;
197
+ }
198
+
199
+ #reject(command: MutationCommand, resultCode: SourceMutationReceipt["resultCode"], code: string, retryable: boolean): SourceMutationReceipt {
200
+ const snapshot = this.#bridge.snapshot(), at = this.#now().toISOString(), observed = snapshot.identity ? wireIdentity(snapshot.identity) : null;
201
+ const identity = observed ? { ...observed, taskId: observed.taskId ?? "task.unavailable", taskRunId: observed.taskRunId ?? "task-run.unavailable" }
202
+ : { projectRef: "project.unavailable", runtimeInstanceId: "runtime.unavailable", sessionRef: "session.unavailable", taskId: "task.unavailable",
203
+ taskRunId: "task-run.unavailable", agentOperationId: null, toolCallId: null } as BridgeIdentity;
204
+ const revisions = snapshot.revisions ? wireRevisions(snapshot.revisions) : { runtimeRevision: "runtime.unavailable", taskRevision: null, controlRevision: null,
205
+ workspaceRevision: null, indexRevision: null, approvalRevision: null, sessionOptionRevision: null, queueRevision: null };
206
+ const action: SourceMutationAction = command?.action === "source.unstage" ? "source.unstage" : "source.stage";
207
+ return { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "receipt",
208
+ commandId: typeof command?.commandId === "string" && REF.test(command.commandId) ? command.commandId : `mutation-rejected.${reviewDigest(command ?? null).slice(7)}`,
209
+ idempotencyKeyDigest: sha(typeof command?.idempotencyKey === "string" ? command.idempotencyKey : canonicalReviewValue(command ?? null)), action,
210
+ actionDigest: typeof command?.actionDigest === "string" && DIGEST.test(command.actionDigest) ? command.actionDigest : sha(code), identity,
211
+ phase: "rejected", resultCode, requestedAt: timestamp(command?.requestedAt) ? command.requestedAt : at, settledAt: at,
212
+ observedRevisionsBefore: revisions, observedRevisionsAfter: revisions, deduplicated: false, auditRef: null, settlementEvidenceRef: null,
213
+ error: { code, message: "The exact selected-file Git index action could not be completed.", retryable } };
214
+ }
215
+ }
@@ -0,0 +1,136 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ import { appendSourceHandoffEvidence, readSourceHandoffEvidence, type SourceHandoffRecord } from "../../piagent-core/runtime/inspection/source-handoff-store.ts";
4
+ import { canonicalReviewValue, reviewDigest } from "../../piagent-core/runtime/inspection/review-state-contract.ts";
5
+ import type { SourceOpenAuthority } from "../../piagent-core/runtime/inspection/source-open-target.ts";
6
+ import { controlActionDigest, type BridgeIdentity, type BridgeRevisions, type SameSessionPiBridge } from "./same-session-bridge.ts";
7
+ import type { VSCodeHandoffResult } from "./vscode-handoff.ts";
8
+
9
+ const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/, PUBLIC_REF = /^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/,
10
+ REVISION = /^[A-Za-z0-9][A-Za-z0-9._:~-]{0,159}$/, DIGEST = /^sha256:[a-f0-9]{64}$/, IDEMPOTENCY = /^[A-Za-z0-9._~-]{32,128}$/;
11
+ const REVISION_KEYS = ["runtimeRevision", "taskRevision", "controlRevision", "workspaceRevision", "indexRevision", "approvalRevision", "sessionOptionRevision", "queueRevision"];
12
+ type OpenCommand = { schemaVersion: 1; version: "piagent-webui-control-v1"; messageType: "command"; commandId: string; idempotencyKey: string;
13
+ requestedAt: string; expiresAt: string; capabilityScope: "reviewActions"; action: "source.open-in-vscode"; actionDigest: string; identity: BridgeIdentity;
14
+ expectedRevisions: BridgeRevisions & { workspacePreimage: null; indexPreimage: null; patchPreimage: null };
15
+ payload: { fileRef: string; line: number | null; column: number | null } };
16
+ export type SourceOpenReceipt = { schemaVersion: 1; version: "piagent-webui-control-v1"; messageType: "receipt"; commandId: string;
17
+ idempotencyKeyDigest: string; action: "source.open-in-vscode"; actionDigest: string; identity: BridgeIdentity; phase: "settled" | "rejected" | "uncertain";
18
+ resultCode: "opened" | "effect-unknown" | "stale-revision" | "identity-mismatch" | "capability-unavailable" | "idempotency-payload-mismatch"
19
+ | "expired" | "invalid-command" | "resync-required"; requestedAt: string; settledAt: string; observedRevisionsBefore: BridgeRevisions;
20
+ observedRevisionsAfter: BridgeRevisions; deduplicated: boolean; auditRef: string | null; settlementEvidenceRef: string | null;
21
+ error: { code: string; message: string; retryable: boolean } | null };
22
+
23
+ function sha(value: string): string { return `sha256:${createHash("sha256").update(value).digest("hex")}`; }
24
+ function same(a: unknown, b: unknown): boolean { return canonicalReviewValue(a) === canonicalReviewValue(b); }
25
+ function exact(value: unknown, keys: string[]): boolean { return Boolean(value && typeof value === "object" && !Array.isArray(value)
26
+ && same(Object.keys(value as object).sort(), [...keys].sort())); }
27
+ 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;
28
+ const parsed = Date.parse(value); return Number.isFinite(parsed) && new Date(parsed).toISOString() === value; }
29
+ function nullableRevision(value: unknown): boolean { return value === null || typeof value === "string" && REVISION.test(value); }
30
+ function identity(value: BridgeIdentity): BridgeIdentity { return { projectRef: value.projectRef, runtimeInstanceId: value.runtimeInstanceId,
31
+ sessionRef: value.sessionRef, taskId: value.taskId, taskRunId: value.taskRunId, agentOperationId: null, toolCallId: null }; }
32
+ function revisions(value: Record<string, any>, record?: SourceHandoffRecord): BridgeRevisions { return { runtimeRevision: value.runtimeRevision,
33
+ taskRevision: record?.taskRevision ?? value.taskRevision, controlRevision: value.controlRevision,
34
+ workspaceRevision: record?.workspaceRevision ?? value.workspaceRevision, indexRevision: value.indexRevision,
35
+ approvalRevision: value.approvalRevision, sessionOptionRevision: value.sessionOptionRevision, queueRevision: value.queueRevision }; }
36
+
37
+ export class SourceOpenController {
38
+ readonly #bridge: SameSessionPiBridge; readonly #root: string; readonly #resolve: (fileRef: string) => Promise<SourceOpenAuthority | null>;
39
+ readonly #open: (absolutePath: string, line: number | null, column: number | null) => Promise<VSCodeHandoffResult>;
40
+ readonly #now: () => Date; #serial: Promise<unknown> = Promise.resolve();
41
+ constructor(options: { bridge: SameSessionPiBridge; projectRoot: string; resolve(fileRef: string): Promise<SourceOpenAuthority | null>;
42
+ open(absolutePath: string, line: number | null, column: number | null): Promise<VSCodeHandoffResult>; now?: () => Date }) {
43
+ this.#bridge = options.bridge; this.#root = options.projectRoot; this.#resolve = options.resolve; this.#open = options.open; this.#now = options.now ?? (() => new Date());
44
+ }
45
+ execute(value: unknown): Promise<SourceOpenReceipt> { const run = this.#serial.then(() => this.#execute(value), () => this.#execute(value));
46
+ this.#serial = run.catch(() => undefined); return run; }
47
+ async #execute(value: unknown): Promise<SourceOpenReceipt> {
48
+ const command = value as OpenCommand, snapshot = this.#bridge.snapshot(), invalid = this.#validate(value);
49
+ if (snapshot.state !== "ready" || !snapshot.identity || !snapshot.revisions) return this.#reject(command, "resync-required", "source-open-binding-unavailable", true);
50
+ if (invalid) return this.#reject(command, "invalid-command", invalid, false);
51
+ const currentIdentity = identity(snapshot.identity), currentRevisions = revisions(snapshot.revisions);
52
+ if (!currentIdentity.taskId || !currentIdentity.taskRunId || !currentRevisions.taskRevision) return this.#reject(command, "capability-unavailable", "active-task-required", false);
53
+ const ledger = readSourceHandoffEvidence(this.#root, currentIdentity.taskRunId); if (ledger.corruptions.length) return this.#reject(command, "resync-required", "source-handoff-evidence-corrupt", false);
54
+ const keyDigest = sha(command.idempotencyKey), prior = ledger.records.filter((record) => record.commandId === command.commandId || record.idempotencyKeyDigest === keyDigest);
55
+ if (prior.length) {
56
+ if (prior.some((record) => record.commandId !== command.commandId || record.idempotencyKeyDigest !== keyDigest || record.actionDigest !== command.actionDigest))
57
+ return this.#reject(command, "idempotency-payload-mismatch", "idempotency-payload-mismatch", false);
58
+ if (prior.some((record) => record.runtimeInstanceId !== currentIdentity.runtimeInstanceId || record.sessionRef !== currentIdentity.sessionRef))
59
+ return this.#reject(command, "identity-mismatch", "runtime-or-session-replaced", false);
60
+ const last = prior.at(-1)!; if (last.phase !== "requested") return this.#receipt(last, currentRevisions, true);
61
+ const uncertain = this.#append(command, currentIdentity, keyDigest, last, "uncertain", "effect-unknown", "source-open-outcome-unknown");
62
+ return this.#receipt(uncertain, currentRevisions, true);
63
+ }
64
+ const now = this.#now().getTime(); if (Date.parse(command.requestedAt) > now + 30_000) return this.#reject(command, "invalid-command", "requested-at-in-future", false);
65
+ if (now > Date.parse(command.expiresAt)) return this.#reject(command, "expired", "command-expired", false);
66
+ if (!same(command.identity, currentIdentity)) return this.#reject(command, "identity-mismatch", "identity-mismatch", false);
67
+ if (command.expectedRevisions.runtimeRevision !== currentRevisions.runtimeRevision || command.expectedRevisions.taskRevision !== currentRevisions.taskRevision)
68
+ return this.#reject(command, "stale-revision", "stale-source-open-revision", true);
69
+ let authority: SourceOpenAuthority | null; try { authority = await this.#resolve(command.payload.fileRef); } catch { authority = null; }
70
+ if (!authority) return this.#reject(command, "capability-unavailable", "source-open-target-unavailable", true);
71
+ if (authority.target.taskRevision !== command.expectedRevisions.taskRevision || authority.target.workspaceRevision !== command.expectedRevisions.workspaceRevision)
72
+ return this.#reject(command, "stale-revision", "source-open-target-stale", true);
73
+ let requested: SourceHandoffRecord; try { requested = this.#append(command, currentIdentity, keyDigest, authority.target, "requested", "handoff-requested", null); }
74
+ catch { return this.#reject(command, "capability-unavailable", "source-handoff-evidence-unavailable", false); }
75
+ let effect: VSCodeHandoffResult; try { effect = await this.#open(authority.absolutePath, command.payload.line, command.payload.column); }
76
+ catch { effect = { state: "rejected", reasonCode: "vscode-launch-failed" }; }
77
+ const resultCode = effect.state === "settled" ? "opened" : effect.state === "rejected" ? "handoff-rejected" : "effect-unknown";
78
+ try { return this.#receipt(this.#append(command, currentIdentity, keyDigest, authority.target, effect.state, resultCode, effect.reasonCode), currentRevisions, false); }
79
+ catch { return this.#receipt(requested, currentRevisions, false); }
80
+ }
81
+ #append(command: OpenCommand, current: BridgeIdentity, keyDigest: string, target: SourceOpenAuthority["target"] | SourceHandoffRecord,
82
+ phase: SourceHandoffRecord["phase"], resultCode: SourceHandoffRecord["resultCode"], failureCode: string | null): SourceHandoffRecord {
83
+ return appendSourceHandoffEvidence({ projectRoot: this.#root, projectRef: current.projectRef, runtimeInstanceId: current.runtimeInstanceId,
84
+ sessionRef: current.sessionRef, taskId: current.taskId!, taskRunId: current.taskRunId!, commandId: command.commandId,
85
+ idempotencyKeyDigest: keyDigest, actionDigest: command.actionDigest, fileRef: target.fileRef, line: command.payload.line,
86
+ column: command.payload.column, taskRevision: target.taskRevision, workspaceRevision: target.workspaceRevision,
87
+ contentDigest: target.contentDigest, phase, resultCode, failureCode, requestedAt: command.requestedAt, recordedAt: this.#now().toISOString() });
88
+ }
89
+ #receipt(record: SourceHandoffRecord, observed: BridgeRevisions, deduplicated: boolean): SourceOpenReceipt {
90
+ const before = revisions(observed, record), settled = record.phase === "settled", uncertain = record.phase === "uncertain" || record.phase === "requested";
91
+ return { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "receipt", commandId: record.commandId,
92
+ idempotencyKeyDigest: record.idempotencyKeyDigest, action: "source.open-in-vscode", actionDigest: record.actionDigest,
93
+ identity: { projectRef: record.projectRef, runtimeInstanceId: record.runtimeInstanceId, sessionRef: record.sessionRef, taskId: record.taskId,
94
+ taskRunId: record.taskRunId, agentOperationId: null, toolCallId: null }, phase: settled ? "settled" : uncertain ? "uncertain" : "rejected",
95
+ resultCode: settled ? "opened" : uncertain ? "effect-unknown" : "capability-unavailable", requestedAt: record.requestedAt,
96
+ settledAt: record.recordedAt, observedRevisionsBefore: before, observedRevisionsAfter: before, deduplicated,
97
+ auditRef: record.evidenceRef, settlementEvidenceRef: settled ? record.evidenceRef : null,
98
+ error: settled ? null : { code: record.failureCode ?? "source-open-effect-unknown", message: uncertain
99
+ ? "VS Code may have received the request; Piagent cannot confirm it." : "VS Code did not accept the file handoff.", retryable: !uncertain } };
100
+ }
101
+ #validate(value: unknown): string | null {
102
+ const command = value as OpenCommand;
103
+ if (!exact(command, ["schemaVersion", "version", "messageType", "commandId", "idempotencyKey", "requestedAt", "expiresAt", "capabilityScope", "action", "actionDigest", "identity", "expectedRevisions", "payload"])
104
+ || command.schemaVersion !== 1 || command.version !== "piagent-webui-control-v1" || command.messageType !== "command" || command.capabilityScope !== "reviewActions"
105
+ || command.action !== "source.open-in-vscode" || !REF.test(command.commandId) || !IDEMPOTENCY.test(command.idempotencyKey) || !timestamp(command.requestedAt)
106
+ || !timestamp(command.expiresAt) || Date.parse(command.requestedAt) > Date.parse(command.expiresAt) || Date.parse(command.expiresAt) - Date.parse(command.requestedAt) > 300_000) return "invalid-command-metadata";
107
+ if (!exact(command.identity, ["projectRef", "runtimeInstanceId", "sessionRef", "taskId", "taskRunId", "agentOperationId", "toolCallId"])
108
+ || ![command.identity.projectRef, command.identity.runtimeInstanceId, command.identity.sessionRef].every((item) => REF.test(item))
109
+ || ![command.identity.taskId, command.identity.taskRunId].every((item) => typeof item === "string" && PUBLIC_REF.test(item))
110
+ || command.identity.agentOperationId !== null || command.identity.toolCallId !== null) return "invalid-command-identity";
111
+ if (!exact(command.expectedRevisions, [...REVISION_KEYS, "workspacePreimage", "indexPreimage", "patchPreimage"])
112
+ || !REVISION.test(command.expectedRevisions.runtimeRevision) || !REVISION.test(command.expectedRevisions.taskRevision ?? "")
113
+ || !REVISION.test(command.expectedRevisions.workspaceRevision ?? "") || command.expectedRevisions.workspacePreimage !== null
114
+ || ![command.expectedRevisions.controlRevision, command.expectedRevisions.indexRevision, command.expectedRevisions.approvalRevision,
115
+ command.expectedRevisions.sessionOptionRevision, command.expectedRevisions.queueRevision].every(nullableRevision)
116
+ || command.expectedRevisions.indexPreimage !== null || command.expectedRevisions.patchPreimage !== null) return "invalid-source-open-authority";
117
+ if (!exact(command.payload, ["fileRef", "line", "column"]) || !REF.test(command.payload.fileRef)
118
+ || command.payload.line !== null && (!Number.isInteger(command.payload.line) || command.payload.line < 1 || command.payload.line > 100_000_000)
119
+ || command.payload.column !== null && (!Number.isInteger(command.payload.column) || command.payload.column < 1 || command.payload.column > 1_000_000)
120
+ || command.payload.column !== null && command.payload.line === null) return "invalid-source-open-payload";
121
+ if (!DIGEST.test(command.actionDigest) || command.actionDigest !== controlActionDigest(command)) return "action-digest-mismatch"; return null;
122
+ }
123
+ #reject(command: OpenCommand, resultCode: SourceOpenReceipt["resultCode"], code: string, retryable: boolean): SourceOpenReceipt {
124
+ const snapshot = this.#bridge.snapshot(), at = this.#now().toISOString(), current = snapshot.identity ? identity(snapshot.identity) : null;
125
+ const safeIdentity = current ? { ...current, taskId: current.taskId ?? "task.unavailable", taskRunId: current.taskRunId ?? "task-run.unavailable" }
126
+ : { projectRef: "project.unavailable", runtimeInstanceId: "runtime.unavailable", sessionRef: "session.unavailable", taskId: "task.unavailable", taskRunId: "task-run.unavailable", agentOperationId: null, toolCallId: null } as BridgeIdentity;
127
+ const observed = snapshot.revisions ? revisions(snapshot.revisions) : { runtimeRevision: "runtime.unavailable", taskRevision: null, controlRevision: null,
128
+ workspaceRevision: null, indexRevision: null, approvalRevision: null, sessionOptionRevision: null, queueRevision: null };
129
+ return { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "receipt", commandId: typeof command?.commandId === "string" && REF.test(command.commandId)
130
+ ? command.commandId : `source-open-rejected.${reviewDigest(command ?? null).slice(7)}`, idempotencyKeyDigest: sha(typeof command?.idempotencyKey === "string" ? command.idempotencyKey : canonicalReviewValue(command ?? null)),
131
+ action: "source.open-in-vscode", actionDigest: typeof command?.actionDigest === "string" && DIGEST.test(command.actionDigest) ? command.actionDigest : sha(code), identity: safeIdentity,
132
+ phase: "rejected", resultCode, requestedAt: timestamp(command?.requestedAt) ? command.requestedAt : at, settledAt: at,
133
+ observedRevisionsBefore: observed, observedRevisionsAfter: observed, deduplicated: false, auditRef: null, settlementEvidenceRef: null,
134
+ error: { code, message: "The selected source file could not be opened in VS Code.", retryable } };
135
+ }
136
+ }
@@ -0,0 +1,189 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ import { appendSourceMutationEvidence, readSourceMutationEvidence, type SourceMutationEvidenceRecord } from "../../piagent-core/runtime/inspection/source-mutation-store.ts";
4
+ import { canonicalReviewValue, reviewDigest } from "../../piagent-core/runtime/inspection/review-state-contract.ts";
5
+ import type { SourceRevertAuthority, SourceRevertProjection, SourceRevertTarget } from "../../piagent-core/runtime/inspection/source-revert-projection.ts";
6
+ import type { SourceIndexTransactionResult } from "../../piagent-core/runtime/policy/source-index-transaction.ts";
7
+ import { controlActionDigest, type BridgeIdentity, type BridgeRevisions, type SameSessionPiBridge } from "./same-session-bridge.ts";
8
+
9
+ const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/, PUBLIC_REF = /^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/,
10
+ REVISION = /^[A-Za-z0-9][A-Za-z0-9._:~-]{0,159}$/, DIGEST = /^sha256:[a-f0-9]{64}$/,
11
+ WORKSPACE = /^wt-content-v2:[a-f0-9]{64}$/, IDEMPOTENCY = /^[A-Za-z0-9._~-]{32,128}$/;
12
+ const REVISION_KEYS = ["runtimeRevision", "taskRevision", "controlRevision", "workspaceRevision", "indexRevision", "approvalRevision", "sessionOptionRevision", "queueRevision"];
13
+ type RevertCommand = { schemaVersion: 1; version: "piagent-webui-control-v1"; messageType: "command"; commandId: string; idempotencyKey: string;
14
+ requestedAt: string; expiresAt: string; capabilityScope: "reviewActions"; action: "source.revert"; actionDigest: string; identity: BridgeIdentity;
15
+ expectedRevisions: BridgeRevisions & { workspacePreimage: string; indexPreimage: string; patchPreimage: string };
16
+ payload: { fileRef: string; hunkRefs: string[]; previewRef: string; confirmedPreviewDigest: string; contentDigest: string } };
17
+ type RevertMutate = (input: { identity: { projectRef: string; runtimeInstanceId: string; sessionRef: string; taskId: string; taskRunId: string };
18
+ action: "source.revert"; expectedTaskRevision: string; expectedControlRevision: string; expectedIndexPreimage: string;
19
+ expectedWorkspacePreimage: string; previewRef: string; confirmedPreviewDigest: string;
20
+ authority: SourceRevertAuthority }) => Promise<SourceIndexTransactionResult>;
21
+ export type SourceRevertReceipt = { schemaVersion: 1; version: "piagent-webui-control-v1"; messageType: "receipt"; commandId: string;
22
+ idempotencyKeyDigest: string; action: "source.revert"; actionDigest: string; identity: BridgeIdentity; phase: "settled" | "rejected" | "uncertain";
23
+ resultCode: "reverted" | "effect-unknown" | "stale-revision" | "identity-mismatch" | "capability-unavailable" | "idempotency-payload-mismatch"
24
+ | "expired" | "invalid-command" | "resync-required" | "terminal-task"; requestedAt: string; settledAt: string;
25
+ observedRevisionsBefore: BridgeRevisions; observedRevisionsAfter: BridgeRevisions; deduplicated: boolean; auditRef: string | null;
26
+ settlementEvidenceRef: string | null; error: { code: string; message: string; retryable: boolean } | null };
27
+
28
+ function sha(value: string): string { return `sha256:${createHash("sha256").update(value).digest("hex")}`; }
29
+ function same(left: unknown, right: unknown): boolean { return canonicalReviewValue(left) === canonicalReviewValue(right); }
30
+ function exactKeys(value: unknown, keys: string[]): boolean { return Boolean(value && typeof value === "object" && !Array.isArray(value)
31
+ && same(Object.keys(value as object).sort(), [...keys].sort())); }
32
+ function timestamp(value: unknown): value is string {
33
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) return false;
34
+ const parsed = Date.parse(value); return Number.isFinite(parsed) && new Date(parsed).toISOString() === value;
35
+ }
36
+ function wireIdentity(value: BridgeIdentity): BridgeIdentity { return { projectRef: value.projectRef, runtimeInstanceId: value.runtimeInstanceId,
37
+ sessionRef: value.sessionRef, taskId: value.taskId, taskRunId: value.taskRunId, agentOperationId: null, toolCallId: null }; }
38
+ function wireRevisions(value: Record<string, any>): BridgeRevisions { return { runtimeRevision: value.runtimeRevision, taskRevision: value.taskRevision,
39
+ controlRevision: value.controlRevision, workspaceRevision: value.workspaceRevision, indexRevision: value.indexRevision,
40
+ approvalRevision: value.approvalRevision, sessionOptionRevision: value.sessionOptionRevision, queueRevision: value.queueRevision }; }
41
+ function receipt(record: SourceMutationEvidenceRecord, deduplicated: boolean): SourceRevertReceipt {
42
+ const identity = { projectRef: record.projectRef, runtimeInstanceId: record.runtimeInstanceId, sessionRef: record.sessionRef,
43
+ taskId: record.taskId, taskRunId: record.taskRunId, agentOperationId: null, toolCallId: null } as BridgeIdentity;
44
+ const before = wireRevisions(record.observedRevisionsBefore), after = wireRevisions(record.observedRevisionsAfter ?? record.observedRevisionsBefore);
45
+ if (record.phase === "settled") return { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "receipt", commandId: record.commandId,
46
+ idempotencyKeyDigest: record.idempotencyKeyDigest, action: "source.revert", actionDigest: record.actionDigest, identity, phase: "settled", resultCode: "reverted",
47
+ requestedAt: record.requestedAt, settledAt: record.recordedAt, observedRevisionsBefore: before, observedRevisionsAfter: after, deduplicated,
48
+ auditRef: record.evidenceRef, settlementEvidenceRef: record.evidenceRef, error: null };
49
+ if (record.phase === "rejected") {
50
+ const stale = ["mutation-preimage-stale", "mutation-guard-precondition-stale"].includes(record.failureCode ?? "");
51
+ return { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "receipt", commandId: record.commandId,
52
+ idempotencyKeyDigest: record.idempotencyKeyDigest, action: "source.revert", actionDigest: record.actionDigest, identity, phase: "rejected",
53
+ resultCode: stale ? "stale-revision" : "capability-unavailable", requestedAt: record.requestedAt, settledAt: record.recordedAt,
54
+ observedRevisionsBefore: before, observedRevisionsAfter: after, deduplicated, auditRef: record.evidenceRef, settlementEvidenceRef: null,
55
+ error: { code: record.failureCode ?? "source-revert-rejected", message: "The Pi guard rejected the confirmed source revert before commit.", retryable: true } };
56
+ }
57
+ return { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "receipt", commandId: record.commandId,
58
+ idempotencyKeyDigest: record.idempotencyKeyDigest, action: "source.revert", actionDigest: record.actionDigest, identity, phase: "uncertain",
59
+ resultCode: "effect-unknown", requestedAt: record.requestedAt, settledAt: record.recordedAt, observedRevisionsBefore: before,
60
+ observedRevisionsAfter: after, deduplicated, auditRef: record.phase === "uncertain" ? record.evidenceRef : null,
61
+ settlementEvidenceRef: null, error: { code: "source-revert-effect-unknown", message: "The worktree effect could not be confirmed. Inspect the source tabs.", retryable: false } };
62
+ }
63
+
64
+ export class SourceRevertController {
65
+ readonly #bridge: SameSessionPiBridge; readonly #projectRoot: string;
66
+ readonly #resolve: (fileRef: string, hunkRefs: string[]) => Promise<{ projection: SourceRevertProjection; authority: SourceRevertAuthority | null }>;
67
+ readonly #revisions: () => Promise<Record<string, string | null>>;
68
+ readonly #mutate: RevertMutate;
69
+ readonly #now: () => Date; #serial: Promise<unknown> = Promise.resolve();
70
+ constructor(options: { bridge: SameSessionPiBridge; projectRoot: string;
71
+ resolve(fileRef: string, hunkRefs: string[]): Promise<{ projection: SourceRevertProjection; authority: SourceRevertAuthority | null }>;
72
+ revisions(): Promise<Record<string, string | null>>; mutate: RevertMutate; now?: () => Date }) {
73
+ this.#bridge = options.bridge; this.#projectRoot = options.projectRoot; this.#resolve = options.resolve;
74
+ this.#revisions = options.revisions; this.#mutate = options.mutate; this.#now = options.now ?? (() => new Date());
75
+ }
76
+ execute(value: unknown): Promise<SourceRevertReceipt> {
77
+ const run = this.#serial.then(() => this.#execute(value), () => this.#execute(value)); this.#serial = run.catch(() => undefined); return run;
78
+ }
79
+ async #execute(value: unknown): Promise<SourceRevertReceipt> {
80
+ const command = value as RevertCommand, snapshot = this.#bridge.snapshot(), invalid = this.#validate(value);
81
+ if (snapshot.state !== "ready" || !snapshot.identity || !snapshot.revisions) return this.#reject(command, "resync-required", "revert-binding-unavailable", true);
82
+ if (invalid) return this.#reject(command, "invalid-command", invalid, false);
83
+ const identity = wireIdentity(snapshot.identity), bridgeRevisions = wireRevisions(snapshot.revisions);
84
+ if (!identity.taskId || !identity.taskRunId || !bridgeRevisions.taskRevision) return this.#reject(command, "capability-unavailable", "active-task-required", false);
85
+ if (snapshot.taskState === "terminal") return this.#reject(command, "terminal-task", "task-terminal", false);
86
+ if (snapshot.liveness !== "idle") return this.#reject(command, "capability-unavailable", "agent-not-idle", true);
87
+ const evidence = readSourceMutationEvidence(this.#projectRoot, identity.taskRunId);
88
+ if (evidence.corruptions.length) return this.#reject(command, "resync-required", "mutation-evidence-corrupt", false);
89
+ const keyDigest = sha(command.idempotencyKey), prior = evidence.records.filter((record) => record.commandId === command.commandId || record.idempotencyKeyDigest === keyDigest);
90
+ if (prior.length) {
91
+ if (prior.some((record) => record.commandId !== command.commandId || record.idempotencyKeyDigest !== keyDigest || record.actionDigest !== command.actionDigest
92
+ || record.action !== command.action)) return this.#reject(command, "idempotency-payload-mismatch", "idempotency-payload-mismatch", false);
93
+ if (prior.some((record) => record.runtimeInstanceId !== identity.runtimeInstanceId || record.sessionRef !== identity.sessionRef))
94
+ return this.#reject(command, "identity-mismatch", "runtime-or-session-replaced", false);
95
+ return receipt(prior.at(-1)!, true);
96
+ }
97
+ const now = this.#now().getTime();
98
+ if (Date.parse(command.requestedAt) > now + 30_000) return this.#reject(command, "invalid-command", "requested-at-in-future", false);
99
+ if (now > Date.parse(command.expiresAt)) return this.#reject(command, "expired", "command-expired", false);
100
+ if (!same(command.identity, identity)) return this.#reject(command, "identity-mismatch", "identity-mismatch", false);
101
+ if (command.expectedRevisions.runtimeRevision !== bridgeRevisions.runtimeRevision || command.expectedRevisions.taskRevision !== bridgeRevisions.taskRevision
102
+ || command.expectedRevisions.controlRevision !== bridgeRevisions.controlRevision) return this.#reject(command, "stale-revision", "stale-task-control-revision", true);
103
+ let resolved: { projection: SourceRevertProjection; authority: SourceRevertAuthority | null };
104
+ try { resolved = await this.#resolve(command.payload.fileRef, command.payload.hunkRefs); }
105
+ catch { return this.#reject(command, "capability-unavailable", "revert-preview-unavailable", true); }
106
+ if (!resolved.authority || resolved.projection.state !== "ready" || !resolved.projection.target)
107
+ return this.#reject(command, "capability-unavailable", resolved.projection.reasonCode ?? "revert-preview-unavailable", true);
108
+ const target = resolved.projection.target;
109
+ if (!this.#matches(command, target) || now > Date.parse(target.expiresAt)) return this.#reject(command, "stale-revision", "revert-preview-stale", true);
110
+ const before = { ...bridgeRevisions, workspaceRevision: target.workspaceRevision, indexRevision: target.indexRevision };
111
+ let requested: SourceMutationEvidenceRecord;
112
+ try { requested = appendSourceMutationEvidence({ projectRoot: this.#projectRoot, projectRef: identity.projectRef, runtimeInstanceId: identity.runtimeInstanceId,
113
+ sessionRef: identity.sessionRef, taskId: identity.taskId, taskRunId: identity.taskRunId, commandId: command.commandId, idempotencyKeyDigest: keyDigest,
114
+ actionDigest: command.actionDigest, action: "source.revert", target, selectedHunkRefs: [...command.payload.hunkRefs], phase: "requested",
115
+ resultCode: "mutation-requested", failureCode: null, requestedAt: command.requestedAt, recordedAt: this.#now().toISOString(),
116
+ beforeIndexPreimage: target.indexPreimage, afterIndexPreimage: null, beforeWorkspacePreimage: target.workspacePreimage,
117
+ afterWorkspacePreimage: null, observedRevisionsBefore: before, observedRevisionsAfter: null }); }
118
+ catch { return this.#reject(command, "capability-unavailable", "mutation-evidence-unavailable", false); }
119
+ let effect: SourceIndexTransactionResult;
120
+ try { effect = await this.#mutate({ identity: { projectRef: identity.projectRef, runtimeInstanceId: identity.runtimeInstanceId,
121
+ sessionRef: identity.sessionRef, taskId: identity.taskId, taskRunId: identity.taskRunId }, action: "source.revert",
122
+ expectedTaskRevision: target.taskRevision, expectedControlRevision: bridgeRevisions.controlRevision!, expectedIndexPreimage: target.indexPreimage,
123
+ expectedWorkspacePreimage: target.workspacePreimage, previewRef: target.previewRef, confirmedPreviewDigest: target.confirmedPreviewDigest,
124
+ authority: resolved.authority }); }
125
+ catch { effect = { state: "rejected", reasonCode: "mutation-guard-unavailable", beforeIndexPreimage: target.indexPreimage,
126
+ afterIndexPreimage: null, beforeWorkspacePreimage: target.workspacePreimage, afterWorkspacePreimage: null, executor: "pi-guard", directExecution: false }; }
127
+ if (effect.executor !== "pi-guard" || effect.directExecution !== false) effect = { ...effect, state: "uncertain", reasonCode: "mutation-executor-untrusted",
128
+ afterIndexPreimage: null, afterWorkspacePreimage: null, executor: "pi-guard", directExecution: false };
129
+ let after: BridgeRevisions; try { after = wireRevisions(await this.#revisions()); } catch { after = before; }
130
+ const phase = effect.state, resultCode = effect.state === "settled" ? "reverted" : effect.state === "rejected" ? "mutation-rejected" : "effect-unknown";
131
+ try { const terminal = appendSourceMutationEvidence({ projectRoot: this.#projectRoot, projectRef: identity.projectRef,
132
+ runtimeInstanceId: identity.runtimeInstanceId, sessionRef: identity.sessionRef, taskId: identity.taskId, taskRunId: identity.taskRunId,
133
+ commandId: command.commandId, idempotencyKeyDigest: keyDigest, actionDigest: command.actionDigest, action: "source.revert", target,
134
+ selectedHunkRefs: [...command.payload.hunkRefs], phase, resultCode, failureCode: effect.reasonCode, requestedAt: command.requestedAt,
135
+ recordedAt: this.#now().toISOString(), beforeIndexPreimage: target.indexPreimage, afterIndexPreimage: effect.afterIndexPreimage,
136
+ beforeWorkspacePreimage: target.workspacePreimage, afterWorkspacePreimage: effect.afterWorkspacePreimage,
137
+ observedRevisionsBefore: before, observedRevisionsAfter: after }); return receipt(terminal, false); }
138
+ catch { return receipt(requested, false); }
139
+ }
140
+ #matches(command: RevertCommand, target: SourceRevertTarget): boolean {
141
+ return command.payload.fileRef === target.fileRef && same(command.payload.hunkRefs, target.hunkRefs) && command.payload.previewRef === target.previewRef
142
+ && command.payload.confirmedPreviewDigest === target.confirmedPreviewDigest && command.payload.contentDigest === target.contentDigest
143
+ && command.expectedRevisions.taskRevision === target.taskRevision && command.expectedRevisions.workspaceRevision === target.workspaceRevision
144
+ && command.expectedRevisions.indexRevision === target.indexRevision && command.expectedRevisions.workspacePreimage === target.workspacePreimage
145
+ && command.expectedRevisions.indexPreimage === target.indexPreimage && command.expectedRevisions.patchPreimage === target.patchPreimage;
146
+ }
147
+ #validate(value: unknown): string | null {
148
+ const command = value as RevertCommand;
149
+ if (!exactKeys(command, ["schemaVersion", "version", "messageType", "commandId", "idempotencyKey", "requestedAt", "expiresAt", "capabilityScope", "action", "actionDigest", "identity", "expectedRevisions", "payload"])
150
+ || command.schemaVersion !== 1 || command.version !== "piagent-webui-control-v1" || command.messageType !== "command" || command.capabilityScope !== "reviewActions"
151
+ || command.action !== "source.revert" || !REF.test(command.commandId) || !IDEMPOTENCY.test(command.idempotencyKey) || !timestamp(command.requestedAt)
152
+ || !timestamp(command.expiresAt) || Date.parse(command.requestedAt) > Date.parse(command.expiresAt) || Date.parse(command.expiresAt) - Date.parse(command.requestedAt) > 300_000)
153
+ return "invalid-command-metadata";
154
+ if (!exactKeys(command.identity, ["projectRef", "runtimeInstanceId", "sessionRef", "taskId", "taskRunId", "agentOperationId", "toolCallId"])
155
+ || ![command.identity.projectRef, command.identity.runtimeInstanceId, command.identity.sessionRef].every((item) => REF.test(item))
156
+ || ![command.identity.taskId, command.identity.taskRunId].every((item) => typeof item === "string" && PUBLIC_REF.test(item))
157
+ || command.identity.agentOperationId !== null || command.identity.toolCallId !== null) return "invalid-command-identity";
158
+ if (!exactKeys(command.expectedRevisions, [...REVISION_KEYS, "workspacePreimage", "indexPreimage", "patchPreimage"])
159
+ || !REVISION.test(command.expectedRevisions.runtimeRevision) || !REVISION.test(command.expectedRevisions.taskRevision ?? "")
160
+ || !REVISION.test(command.expectedRevisions.controlRevision ?? "")
161
+ || !REVISION.test(command.expectedRevisions.workspaceRevision ?? "") || !REVISION.test(command.expectedRevisions.indexRevision ?? "")
162
+ || [command.expectedRevisions.approvalRevision, command.expectedRevisions.sessionOptionRevision, command.expectedRevisions.queueRevision]
163
+ .some((item) => item !== null && !REVISION.test(String(item)))
164
+ || !WORKSPACE.test(command.expectedRevisions.workspacePreimage) || !DIGEST.test(command.expectedRevisions.indexPreimage)
165
+ || !DIGEST.test(command.expectedRevisions.patchPreimage)) return "invalid-revert-authority";
166
+ if (!exactKeys(command.payload, ["fileRef", "hunkRefs", "previewRef", "confirmedPreviewDigest", "contentDigest"])
167
+ || !REF.test(command.payload.fileRef) || !REF.test(command.payload.previewRef) || !Array.isArray(command.payload.hunkRefs)
168
+ || command.payload.hunkRefs.length > 1 || new Set(command.payload.hunkRefs).size !== command.payload.hunkRefs.length
169
+ || command.payload.hunkRefs.some((item) => !REF.test(item)) || !DIGEST.test(command.payload.confirmedPreviewDigest)
170
+ || !DIGEST.test(command.payload.contentDigest)) return "invalid-revert-payload";
171
+ if (!DIGEST.test(command.actionDigest) || command.actionDigest !== controlActionDigest(command)) return "action-digest-mismatch";
172
+ return null;
173
+ }
174
+ #reject(command: RevertCommand, resultCode: SourceRevertReceipt["resultCode"], code: string, retryable: boolean): SourceRevertReceipt {
175
+ const snapshot = this.#bridge.snapshot(), at = this.#now().toISOString(), observed = snapshot.identity ? wireIdentity(snapshot.identity) : null;
176
+ const identity = observed ? { ...observed, taskId: observed.taskId ?? "task.unavailable", taskRunId: observed.taskRunId ?? "task-run.unavailable" }
177
+ : { projectRef: "project.unavailable", runtimeInstanceId: "runtime.unavailable", sessionRef: "session.unavailable", taskId: "task.unavailable",
178
+ taskRunId: "task-run.unavailable", agentOperationId: null, toolCallId: null } as BridgeIdentity;
179
+ const revisions = snapshot.revisions ? wireRevisions(snapshot.revisions) : { runtimeRevision: "runtime.unavailable", taskRevision: null, controlRevision: null,
180
+ workspaceRevision: null, indexRevision: null, approvalRevision: null, sessionOptionRevision: null, queueRevision: null };
181
+ return { schemaVersion: 1, version: "piagent-webui-control-v1", messageType: "receipt",
182
+ commandId: typeof command?.commandId === "string" && REF.test(command.commandId) ? command.commandId : `revert-rejected.${reviewDigest(command ?? null).slice(7)}`,
183
+ idempotencyKeyDigest: sha(typeof command?.idempotencyKey === "string" ? command.idempotencyKey : canonicalReviewValue(command ?? null)), action: "source.revert",
184
+ actionDigest: typeof command?.actionDigest === "string" && DIGEST.test(command.actionDigest) ? command.actionDigest : sha(code), identity,
185
+ phase: "rejected", resultCode, requestedAt: timestamp(command?.requestedAt) ? command.requestedAt : at, settledAt: at,
186
+ observedRevisionsBefore: revisions, observedRevisionsAfter: revisions, deduplicated: false, auditRef: null, settlementEvidenceRef: null,
187
+ error: { code, message: "The confirmed exact source revert could not be completed.", retryable } };
188
+ }
189
+ }