@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.
Files changed (301) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +3 -3
  3. package/architecture/layers.json +96 -1
  4. package/docs/README.md +1 -0
  5. package/docs/architecture.md +1 -0
  6. package/docs/authority-manifest.md +1 -0
  7. package/docs/auto-delegation-policy.md +1 -0
  8. package/docs/capability-packs.md +1 -0
  9. package/docs/command-reference-vietnamese.md +5 -4
  10. package/docs/context-engine.md +1 -0
  11. package/docs/context-window-policy.md +1 -0
  12. package/docs/distribution-standard.md +8 -7
  13. package/docs/herdr-workflow.md +1 -0
  14. package/docs/mcp-and-tools.md +14 -9
  15. package/docs/memory-policy.md +1 -0
  16. package/docs/model-options.md +1 -0
  17. package/docs/oauth-providers.md +1 -0
  18. package/docs/operator-manual-vietnamese.md +15 -12
  19. package/docs/package-architecture-notes.md +1 -0
  20. package/docs/project-adapters.md +1 -0
  21. package/docs/project-onboarding.md +1 -0
  22. package/docs/publishing-for-teams.md +1 -0
  23. package/docs/quality-benchmark.md +1 -0
  24. package/docs/quickstart-vietnamese.md +3 -2
  25. package/docs/release-install-policy.md +7 -6
  26. package/docs/runtime-harness-standard.md +1 -0
  27. package/docs/runtime-policy-design.md +1 -0
  28. package/docs/runtime-quality-baseline.md +1 -0
  29. package/docs/security-redaction-benchmark.md +1 -0
  30. package/docs/security-threat-model.md +2 -1
  31. package/docs/subagent-orchestration-capabilities.md +1 -0
  32. package/docs/subagents-and-multiagent.md +1 -0
  33. package/docs/task-implementation-contract.md +1 -0
  34. package/docs/task-lifecycle-vietnamese.md +1 -0
  35. package/docs/team-onboarding.md +3 -2
  36. package/docs/third-party-neutrality.md +26 -0
  37. package/docs/usage-observability.md +1 -0
  38. package/docs/vercel-docs-site.md +1 -0
  39. package/docs/workflow-recipes.md +1 -0
  40. package/docs-site/architecture.html +1 -1
  41. package/docs-site/benchmark.html +1 -1
  42. package/docs-site/commands.html +1 -1
  43. package/docs-site/context-engine.html +1 -1
  44. package/docs-site/en/architecture.html +1 -1
  45. package/docs-site/en/benchmark.html +1 -1
  46. package/docs-site/en/commands.html +1 -1
  47. package/docs-site/en/context-engine.html +1 -1
  48. package/docs-site/en/index.html +1 -1
  49. package/docs-site/en/mcp-approval.html +1 -1
  50. package/docs-site/en/mcp-auth.html +1 -1
  51. package/docs-site/en/mcp-servers.html +1 -1
  52. package/docs-site/en/mcp.html +1 -1
  53. package/docs-site/en/permissions.html +1 -1
  54. package/docs-site/en/profiles.html +1 -1
  55. package/docs-site/en/quickstart.html +1 -1
  56. package/docs-site/en/runtime.html +1 -1
  57. package/docs-site/en/scope.html +1 -1
  58. package/docs-site/en/security.html +1 -1
  59. package/docs-site/en/team.html +1 -1
  60. package/docs-site/en/whats-new.html +1 -1
  61. package/docs-site/en/workflows.html +1 -1
  62. package/docs-site/index.html +1 -1
  63. package/docs-site/mcp-approval.html +1 -1
  64. package/docs-site/mcp-auth.html +1 -1
  65. package/docs-site/mcp-servers.html +1 -1
  66. package/docs-site/mcp.html +1 -1
  67. package/docs-site/permissions.html +1 -1
  68. package/docs-site/profiles.html +1 -1
  69. package/docs-site/quickstart.html +1 -1
  70. package/docs-site/runtime.html +1 -1
  71. package/docs-site/scope.html +1 -1
  72. package/docs-site/security.html +1 -1
  73. package/docs-site/team.html +1 -1
  74. package/docs-site/whats-new.html +1 -1
  75. package/docs-site/workflows.html +1 -1
  76. package/evals/fixtures/mutation-provenance-record.invalid.json +17 -0
  77. package/evals/fixtures/mutation-provenance-record.valid.json +27 -0
  78. package/evals/fixtures/piagent-webui/approval-v1.invalid.json +54 -0
  79. package/evals/fixtures/piagent-webui/approval-v1.valid.json +58 -0
  80. package/evals/fixtures/piagent-webui/attachment-v1.invalid.json +25 -0
  81. package/evals/fixtures/piagent-webui/attachment-v1.valid.json +25 -0
  82. package/evals/fixtures/piagent-webui/capabilities-v1.invalid.json +51 -0
  83. package/evals/fixtures/piagent-webui/capabilities-v1.valid.json +122 -0
  84. package/evals/fixtures/piagent-webui/commit-summary-v1.invalid.json +10 -0
  85. package/evals/fixtures/piagent-webui/commit-summary-v1.valid.json +25 -0
  86. package/evals/fixtures/piagent-webui/control-command-v1.invalid.json +37 -0
  87. package/evals/fixtures/piagent-webui/control-command-v1.valid.json +35 -0
  88. package/evals/fixtures/piagent-webui/diff-v1.invalid.json +13 -0
  89. package/evals/fixtures/piagent-webui/diff-v1.valid.json +141 -0
  90. package/evals/fixtures/piagent-webui/gateway-capabilities-v1.invalid.json +35 -0
  91. package/evals/fixtures/piagent-webui/gateway-capabilities-v1.valid.json +35 -0
  92. package/evals/fixtures/piagent-webui/gateway-protocol-v1.invalid.json +14 -0
  93. package/evals/fixtures/piagent-webui/gateway-protocol-v1.valid.json +14 -0
  94. package/evals/fixtures/piagent-webui/handoff-history-v1.invalid.json +16 -0
  95. package/evals/fixtures/piagent-webui/handoff-history-v1.valid.json +16 -0
  96. package/evals/fixtures/piagent-webui/model-catalog-v1.invalid.json +31 -0
  97. package/evals/fixtures/piagent-webui/model-catalog-v1.valid.json +43 -0
  98. package/evals/fixtures/piagent-webui/queue-v1.invalid.json +29 -0
  99. package/evals/fixtures/piagent-webui/queue-v1.valid.json +44 -0
  100. package/evals/fixtures/piagent-webui/recovery-history-v1.invalid.json +17 -0
  101. package/evals/fixtures/piagent-webui/recovery-history-v1.valid.json +20 -0
  102. package/evals/fixtures/piagent-webui/release-monitor-v1.invalid.json +12 -0
  103. package/evals/fixtures/piagent-webui/release-monitor-v1.valid.json +29 -0
  104. package/evals/fixtures/piagent-webui/review-state-v1.invalid.json +25 -0
  105. package/evals/fixtures/piagent-webui/review-state-v1.valid.json +38 -0
  106. package/evals/fixtures/piagent-webui/runtime-event-v2.invalid.json +49 -0
  107. package/evals/fixtures/piagent-webui/runtime-event-v2.valid.json +49 -0
  108. package/evals/fixtures/piagent-webui/session-catalog-v1.invalid.json +17 -0
  109. package/evals/fixtures/piagent-webui/session-catalog-v1.valid.json +58 -0
  110. package/evals/fixtures/piagent-webui/session-command-v1.invalid.json +19 -0
  111. package/evals/fixtures/piagent-webui/session-command-v1.valid.json +19 -0
  112. package/evals/fixtures/piagent-webui/snapshot-v1.invalid.json +5 -0
  113. package/evals/fixtures/piagent-webui/snapshot-v1.valid.json +191 -0
  114. package/evals/fixtures/piagent-webui/source-change-v1.invalid.json +57 -0
  115. package/evals/fixtures/piagent-webui/source-change-v1.valid.json +98 -0
  116. package/evals/fixtures/piagent-webui/source-mutation-v1.invalid.json +19 -0
  117. package/evals/fixtures/piagent-webui/source-mutation-v1.valid.json +38 -0
  118. package/evals/fixtures/piagent-webui/source-revert-v1.invalid.json +20 -0
  119. package/evals/fixtures/piagent-webui/source-revert-v1.valid.json +62 -0
  120. package/evals/fixtures/piagent-webui/subagent-tree-v1.invalid.json +26 -0
  121. package/evals/fixtures/piagent-webui/subagent-tree-v1.valid.json +39 -0
  122. package/evals/fixtures/piagent-webui/task-index-v1.invalid.json +15 -0
  123. package/evals/fixtures/piagent-webui/task-index-v1.valid.json +15 -0
  124. package/evals/fixtures/piagent-webui/task-timeline-v1.invalid.json +14 -0
  125. package/evals/fixtures/piagent-webui/task-timeline-v1.valid.json +16 -0
  126. package/evals/fixtures/piagent-webui/transcript-v1.invalid.json +35 -0
  127. package/evals/fixtures/piagent-webui/transcript-v1.valid.json +55 -0
  128. package/evals/fixtures/task-baseline-manifest.invalid.json +16 -0
  129. package/evals/fixtures/task-baseline-manifest.valid.json +41 -0
  130. package/evals/fixtures/verifier-file-snapshot.invalid.json +21 -0
  131. package/evals/fixtures/verifier-file-snapshot.valid.json +21 -0
  132. package/package.json +30 -3
  133. package/packages/piagent-core/benchmark/benchmark-candidate.d.ts +1 -0
  134. package/packages/piagent-core/benchmark/benchmark-forensics.d.ts +1 -0
  135. package/packages/piagent-core/benchmark/benchmark-ledger.d.ts +4 -0
  136. package/packages/piagent-core/benchmark/benchmark-record-validation.d.ts +1 -0
  137. package/packages/piagent-core/benchmark/benchmark-runtime.d.ts +1 -0
  138. package/packages/piagent-core/capabilities/capability-core.js +2 -2
  139. package/packages/piagent-core/capabilities/runtime-integrity.js +143 -0
  140. package/packages/piagent-core/extensions/piagent-guard.ts +62 -37
  141. package/packages/piagent-core/extensions/redaction-core.d.ts +2 -0
  142. package/packages/piagent-core/extensions/task-journal.js +30 -1
  143. package/packages/piagent-core/extensions/task-state.js +33 -36
  144. package/packages/piagent-core/mcp/mcp-server-catalog.js +5 -5
  145. package/packages/piagent-core/package.json +1 -1
  146. package/packages/piagent-core/runtime/hooks/session-start-hook.ts +2 -2
  147. package/packages/piagent-core/runtime/hooks/tool-call-hook.ts +5 -2
  148. package/packages/piagent-core/runtime/hooks/tool-result-hook.ts +20 -19
  149. package/packages/piagent-core/runtime/hooks/tool-result-metadata.ts +13 -0
  150. package/packages/piagent-core/runtime/input/chat-images.ts +2 -2
  151. package/packages/piagent-core/runtime/inspection/activity-event-adapter.ts +94 -0
  152. package/packages/piagent-core/runtime/inspection/approval-broker.ts +318 -0
  153. package/packages/piagent-core/runtime/inspection/commit-summary-projection.ts +59 -0
  154. package/packages/piagent-core/runtime/inspection/context-telemetry-inspection.ts +37 -0
  155. package/packages/piagent-core/runtime/inspection/criteria-links.ts +295 -0
  156. package/packages/piagent-core/runtime/inspection/diff-projection.ts +499 -0
  157. package/packages/piagent-core/runtime/inspection/git-filter-safety.ts +38 -0
  158. package/packages/piagent-core/runtime/inspection/git-numstat-adapter.ts +71 -0
  159. package/packages/piagent-core/runtime/inspection/git-status-adapter.ts +493 -0
  160. package/packages/piagent-core/runtime/inspection/git-tree-adapter.ts +108 -0
  161. package/packages/piagent-core/runtime/inspection/mcp-control.ts +10 -0
  162. package/packages/piagent-core/runtime/inspection/mutation-provenance-contract.ts +131 -0
  163. package/packages/piagent-core/runtime/inspection/mutation-provenance-recorder.ts +48 -0
  164. package/packages/piagent-core/runtime/inspection/mutation-provenance-store.ts +161 -0
  165. package/packages/piagent-core/runtime/inspection/project-runtime-inspection.ts +36 -0
  166. package/packages/piagent-core/runtime/inspection/review-state-contract.ts +108 -0
  167. package/packages/piagent-core/runtime/inspection/review-state-projection.ts +93 -0
  168. package/packages/piagent-core/runtime/inspection/review-state-store.ts +112 -0
  169. package/packages/piagent-core/runtime/inspection/runtime-event-store.ts +262 -0
  170. package/packages/piagent-core/runtime/inspection/same-process-bridge-proof.ts +103 -0
  171. package/packages/piagent-core/runtime/inspection/source-change-projection.ts +471 -0
  172. package/packages/piagent-core/runtime/inspection/source-evidence-contract.ts +139 -0
  173. package/packages/piagent-core/runtime/inspection/source-evidence-store.ts +315 -0
  174. package/packages/piagent-core/runtime/inspection/source-handoff-store.ts +70 -0
  175. package/packages/piagent-core/runtime/inspection/source-inspection-plan.ts +34 -0
  176. package/packages/piagent-core/runtime/inspection/source-mutation-projection.ts +164 -0
  177. package/packages/piagent-core/runtime/inspection/source-mutation-store.ts +168 -0
  178. package/packages/piagent-core/runtime/inspection/source-open-target.ts +38 -0
  179. package/packages/piagent-core/runtime/inspection/source-revert-projection.ts +147 -0
  180. package/packages/piagent-core/runtime/inspection/task-baseline-start-capture.ts +22 -0
  181. package/packages/piagent-core/runtime/inspection/task-compaction-history.ts +160 -0
  182. package/packages/piagent-core/runtime/inspection/task-control-journal.ts +131 -0
  183. package/packages/piagent-core/runtime/inspection/task-handoff-history.ts +95 -0
  184. package/packages/piagent-core/runtime/inspection/task-provenance-projection.ts +60 -0
  185. package/packages/piagent-core/runtime/inspection/task-recovery-timeline.ts +88 -0
  186. package/packages/piagent-core/runtime/inspection/task-run-index.ts +87 -0
  187. package/packages/piagent-core/runtime/inspection/task-source-projection.ts +401 -0
  188. package/packages/piagent-core/runtime/inspection/task-subagent-tree.ts +101 -0
  189. package/packages/piagent-core/runtime/inspection/text-diff.ts +60 -0
  190. package/packages/piagent-core/runtime/inspection/verifier-snapshot-contract.ts +114 -0
  191. package/packages/piagent-core/runtime/inspection/verifier-snapshot-store.ts +189 -0
  192. package/packages/piagent-core/runtime/inspection/webui-snapshot.ts +320 -0
  193. package/packages/piagent-core/runtime/inspection/workspace-file-reader.ts +132 -0
  194. package/packages/piagent-core/runtime/inspection/workspace-source-projection.ts +96 -0
  195. package/packages/piagent-core/runtime/inspection/zero-turn-conformance.ts +175 -0
  196. package/packages/piagent-core/runtime/orchestration/owned-work-budget.ts +68 -4
  197. package/packages/piagent-core/runtime/policy/source-index-transaction.ts +173 -0
  198. package/packages/piagent-core/runtime/policy/source-mutation-guard-binding.ts +42 -0
  199. package/packages/piagent-core/runtime/policy/source-mutation-guard.ts +184 -0
  200. package/packages/piagent-core/runtime/policy/source-worktree-transaction.ts +105 -0
  201. package/packages/piagent-core/runtime/product/activity-inspector-footer.ts +5 -3
  202. package/packages/piagent-core/runtime/product/activity-inspector.ts +85 -343
  203. package/packages/piagent-core/runtime/recovery/resume-state.ts +38 -1
  204. package/packages/piagent-core/runtime/registration/activity-inspector-command.ts +68 -14
  205. package/packages/piagent-core/runtime/registration/task-start-tool.ts +13 -14
  206. package/packages/piagent-core/runtime/session/model-authorship-state.ts +31 -3
  207. package/packages/piagent-core/runtime/session/runtime-state.ts +11 -1
  208. package/packages/piagent-webui/dist/client/assets/index-DjMntaK5.js +172 -0
  209. package/packages/piagent-webui/dist/client/assets/index-DwKCWbwd.css +1 -0
  210. package/packages/piagent-webui/dist/client/index.html +16 -0
  211. package/packages/piagent-webui/extension/attachment-store.ts +323 -0
  212. package/packages/piagent-webui/extension/held-message-queue.ts +311 -0
  213. package/packages/piagent-webui/extension/lifecycle-controller.ts +408 -0
  214. package/packages/piagent-webui/extension/lifecycle-event-adapter.ts +23 -0
  215. package/packages/piagent-webui/extension/piagent-webui.ts +470 -0
  216. package/packages/piagent-webui/extension/review-controller.ts +160 -0
  217. package/packages/piagent-webui/extension/same-session-bridge.ts +500 -0
  218. package/packages/piagent-webui/extension/session-options-controller.ts +281 -0
  219. package/packages/piagent-webui/extension/session-stream-adapter.ts +249 -0
  220. package/packages/piagent-webui/extension/source-mutation-controller.ts +215 -0
  221. package/packages/piagent-webui/extension/source-open-controller.ts +136 -0
  222. package/packages/piagent-webui/extension/source-revert-controller.ts +189 -0
  223. package/packages/piagent-webui/extension/terminal-session-adapter.ts +73 -0
  224. package/packages/piagent-webui/extension/vscode-handoff.ts +51 -0
  225. package/packages/piagent-webui/gateway/control-socket.ts +92 -0
  226. package/packages/piagent-webui/gateway/gateway-events.ts +60 -0
  227. package/packages/piagent-webui/gateway/gateway-protocol-service.ts +64 -0
  228. package/packages/piagent-webui/gateway/gateway-service.ts +215 -0
  229. package/packages/piagent-webui/gateway/gateway-session-stream.ts +110 -0
  230. package/packages/piagent-webui/gateway/mcp-auth-broker.ts +158 -0
  231. package/packages/piagent-webui/gateway/native-project-picker.ts +29 -0
  232. package/packages/piagent-webui/gateway/pi-host.ts +41 -0
  233. package/packages/piagent-webui/gateway/profile-state.ts +1 -0
  234. package/packages/piagent-webui/gateway/project-registry.ts +108 -0
  235. package/packages/piagent-webui/gateway/provider-auth-broker.ts +172 -0
  236. package/packages/piagent-webui/gateway/session-catalog.ts +128 -0
  237. package/packages/piagent-webui/gateway/session-command-controller.ts +237 -0
  238. package/packages/piagent-webui/gateway/session-command-store.ts +224 -0
  239. package/packages/piagent-webui/gateway/session-inspection-registry.ts +204 -0
  240. package/packages/piagent-webui/gateway/session-lease-store.ts +1 -0
  241. package/packages/piagent-webui/gateway/session-metadata-store.ts +152 -0
  242. package/packages/piagent-webui/gateway/session-runtime-supervisor.ts +485 -0
  243. package/packages/piagent-webui/ownership/gateway-runtime-context.ts +8 -0
  244. package/packages/piagent-webui/ownership/profile-state.ts +117 -0
  245. package/packages/piagent-webui/ownership/session-lease-store.ts +329 -0
  246. package/packages/piagent-webui/ownership/session-refs.ts +8 -0
  247. package/packages/piagent-webui/package.json +33 -0
  248. package/packages/piagent-webui/server/README.md +4 -0
  249. package/packages/piagent-webui/server/benchmark-release-monitor.ts +230 -0
  250. package/packages/piagent-webui/server/core-inspection-provider.ts +403 -0
  251. package/packages/piagent-webui/server/gateway-websocket.ts +143 -0
  252. package/packages/piagent-webui/server/http-security.ts +27 -0
  253. package/packages/piagent-webui/server/ipc-read-model-client.ts +89 -0
  254. package/packages/piagent-webui/server/loopback-server.ts +368 -0
  255. package/packages/piagent-webui/server/read-model-provider.ts +37 -0
  256. package/packages/piagent-webui/server/read-only-router.ts +105 -0
  257. package/packages/piagent-webui/server/session-auth.ts +88 -0
  258. package/packages/piagent-webui/server/sidecar-main.ts +86 -0
  259. package/packages/piagent-webui/server/sse-hub.ts +76 -0
  260. package/packages/piagent-webui/server/static-bundle.ts +40 -0
  261. package/packages/piagent-webui/server/transcript-projection.ts +110 -0
  262. package/schemas/mutation-provenance-record.schema.json +100 -0
  263. package/schemas/piagent-webui/approval-v1.schema.json +654 -0
  264. package/schemas/piagent-webui/attachment-v1.schema.json +267 -0
  265. package/schemas/piagent-webui/capabilities-v1.schema.json +729 -0
  266. package/schemas/piagent-webui/catalog-v1.json +240 -0
  267. package/schemas/piagent-webui/commit-summary-v1.schema.json +63 -0
  268. package/schemas/piagent-webui/common-v1.schema.json +479 -0
  269. package/schemas/piagent-webui/control-command-v1.schema.json +1780 -0
  270. package/schemas/piagent-webui/diff-v1.schema.json +826 -0
  271. package/schemas/piagent-webui/gateway-capabilities-v1.schema.json +136 -0
  272. package/schemas/piagent-webui/gateway-protocol-v1.schema.json +456 -0
  273. package/schemas/piagent-webui/handoff-history-v1.schema.json +92 -0
  274. package/schemas/piagent-webui/model-catalog-v1.schema.json +95 -0
  275. package/schemas/piagent-webui/queue-v1.schema.json +99 -0
  276. package/schemas/piagent-webui/recovery-history-v1.schema.json +144 -0
  277. package/schemas/piagent-webui/release-monitor-v1.schema.json +173 -0
  278. package/schemas/piagent-webui/review-state-v1.schema.json +206 -0
  279. package/schemas/piagent-webui/runtime-event-v2.schema.json +5206 -0
  280. package/schemas/piagent-webui/session-catalog-v1.schema.json +222 -0
  281. package/schemas/piagent-webui/session-command-v1.schema.json +390 -0
  282. package/schemas/piagent-webui/snapshot-v1.schema.json +2622 -0
  283. package/schemas/piagent-webui/source-change-v1.schema.json +763 -0
  284. package/schemas/piagent-webui/source-mutation-v1.schema.json +96 -0
  285. package/schemas/piagent-webui/source-revert-v1.schema.json +130 -0
  286. package/schemas/piagent-webui/subagent-tree-v1.schema.json +88 -0
  287. package/schemas/piagent-webui/task-index-v1.schema.json +74 -0
  288. package/schemas/piagent-webui/task-timeline-v1.schema.json +49 -0
  289. package/schemas/piagent-webui/transcript-v1.schema.json +243 -0
  290. package/schemas/task-baseline-manifest.schema.json +122 -0
  291. package/schemas/verifier-file-snapshot.schema.json +81 -0
  292. package/scripts/check-architecture.mjs +1 -0
  293. package/scripts/check-doc-languages.mjs +19 -2
  294. package/scripts/check-third-party-neutrality.mjs +43 -0
  295. package/scripts/install-global.sh +1 -1
  296. package/scripts/piagent-cli.mjs +17 -3
  297. package/scripts/piagent-dashboard.mjs +208 -0
  298. package/scripts/piagent-webui-launcher.mjs +121 -0
  299. package/scripts/typescript-loader.mjs +26 -1
  300. package/scripts/verify-local.sh +253 -0
  301. package/scripts/verify-release-identity.mjs +4 -1
@@ -0,0 +1,13 @@
1
+ export function patchLineStats(details: unknown): { additions?: number; deletions?: number } {
2
+ if (!details || typeof details !== "object") return {};
3
+ const patch = (details as Record<string, unknown>).patch;
4
+ if (typeof patch !== "string" || !patch.trim()) return {};
5
+ let additions = 0;
6
+ let deletions = 0;
7
+ for (const line of patch.split(/\r?\n/)) {
8
+ if (line.startsWith("+++ ") || line.startsWith("--- ")) continue;
9
+ if (line.startsWith("+")) additions += 1;
10
+ else if (line.startsWith("-")) deletions += 1;
11
+ }
12
+ return { additions, deletions };
13
+ }
@@ -32,7 +32,7 @@ function escapeRegExp(input: string): string {
32
32
  return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
33
33
  }
34
34
 
35
- function supportedImageMimeType(bytes: Buffer): string | undefined {
35
+ export function supportedChatImageMimeType(bytes: Buffer): string | undefined {
36
36
  if (
37
37
  bytes.length >= 24
38
38
  && bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
@@ -236,7 +236,7 @@ export function readChatImage(
236
236
  offset += read;
237
237
  }
238
238
  if (offset !== bytes.length) return { status: "error", reason: "file changed while it was being read" };
239
- const mimeType = supportedImageMimeType(bytes);
239
+ const mimeType = supportedChatImageMimeType(bytes);
240
240
  if (!mimeType) return { status: "error", reason: "file bytes are not a supported image" };
241
241
  return { status: "ok", absolutePath: canonicalPath, bytes, mimeType };
242
242
  } finally {
@@ -0,0 +1,94 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ import { redactSensitiveText } from "../../extensions/redaction-core.js";
4
+ import type { ActivityInspectorEvent } from "../product/activity-inspector.ts";
5
+ import type { RuntimeEventDraft, RuntimeEventRevision } from "./runtime-event-store.ts";
6
+
7
+ export type RuntimeEventIdentity = {
8
+ projectRef: string;
9
+ runtimeInstanceId: string;
10
+ sessionRef: string;
11
+ taskId: string | null;
12
+ taskRunId: string | null;
13
+ agentOperationId?: string | null;
14
+ };
15
+ export type ActivityEventAdapterInput = {
16
+ event: ActivityInspectorEvent & Record<string, unknown>;
17
+ identity: RuntimeEventIdentity;
18
+ revision: RuntimeEventRevision;
19
+ };
20
+
21
+ const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
22
+ function hash(value: string): string { return createHash("sha256").update(value).digest("hex"); }
23
+ function opaque(prefix: string, value: unknown): string { return `${prefix}.${hash(String(value ?? "unknown"))}`; }
24
+ function digest(value: unknown): string | null {
25
+ const candidate = String(value ?? "");
26
+ return /^[a-f0-9]{64}$/.test(candidate) ? `sha256:${candidate}` : /^sha256:[a-f0-9]{64}$/.test(candidate) ? candidate : null;
27
+ }
28
+ function safeText(value: unknown, maximum = 4000): { text: string; redacted: number } {
29
+ const source = String(value ?? "");
30
+ const redaction = redactSensitiveText(source);
31
+ const text = redaction.text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim().slice(0, maximum);
32
+ return { text, redacted: redaction.redacted ? 1 : 0 };
33
+ }
34
+ function correlation() {
35
+ return { commandId: null, messageRequestId: null, replacementId: null, approvalRequestId: null, causationEventId: null, idempotencyKeyDigest: null };
36
+ }
37
+ function base(identity: RuntimeEventIdentity, revision: RuntimeEventRevision, sourceObservedAt: string): Omit<RuntimeEventDraft, "kind" | "payload" | "evidence" | "redaction"> {
38
+ return { sourceObservedAt, projectRef: identity.projectRef, runtimeInstanceId: identity.runtimeInstanceId, sessionRef: identity.sessionRef,
39
+ taskId: identity.taskId, taskRunId: identity.taskRunId, agentOperationId: null, turnIndex: null, messageRef: null, toolCallId: null,
40
+ revision, correlation: correlation() };
41
+ }
42
+
43
+ export function adaptActivityTelemetryEvent(input: ActivityEventAdapterInput): RuntimeEventDraft | null {
44
+ const event = input.event, observedAt = String(event.recordedAt ?? "");
45
+ if (!TIMESTAMP.test(observedAt)) return null;
46
+ const eventName = String(event.event ?? "");
47
+ if (!["tool_call", "tool_result", "tool_decision"].includes(eventName)) return null;
48
+ if (eventName === "tool_decision" && event.decision !== "blocked") return null;
49
+ const toolName = safeText(event.toolName ?? "unknown", 80).text.replace(/[^A-Za-z0-9._:@~-]/g, "-") || "unknown";
50
+ const rawToolCall = String(event.toolCallId ?? event.activityId ?? `${observedAt}:${toolName}`);
51
+ const hasOperation = typeof input.identity.agentOperationId === "string" && input.identity.agentOperationId.length > 0;
52
+ const operationRef = hasOperation ? opaque("operation", input.identity.agentOperationId) : null;
53
+ const toolCallRef = hasOperation ? opaque("tool", rawToolCall) : null;
54
+ const activityType = hasOperation ? "tool" : ["bash", "shell", "exec"].includes(toolName) ? "command" : "other";
55
+ const failed = eventName === "tool_result" && (event.isError === true || typeof event.exitCode === "number" && event.exitCode !== 0);
56
+ const blocked = eventName === "tool_decision";
57
+ const state = eventName === "tool_call" ? "started" : blocked ? "blocked" : failed ? "failed" : "finished";
58
+ const kind = `activity.${state}`;
59
+ const previewValue = blocked ? event.reason : event.command ?? event.targetPath ?? event.toolName;
60
+ const preview = safeText(previewValue, 4000);
61
+ const storedRedactions = typeof event.sensitiveValuesRedacted === "number" && Number.isInteger(event.sensitiveValuesRedacted)
62
+ ? Math.max(0, Math.min(10_000, event.sensitiveValuesRedacted)) : 0;
63
+ const reasonCode = blocked ? "policy-blocked" : failed ? "tool-result-failed" : null;
64
+ return {
65
+ ...base(input.identity, input.revision, observedAt), agentOperationId: operationRef, toolCallId: toolCallRef,
66
+ kind, evidence: "derived",
67
+ payload: {
68
+ state, activityType, activityRef: opaque("activity", `${input.identity.runtimeInstanceId}\0${input.identity.sessionRef}\0${rawToolCall}`),
69
+ toolName, inputDigest: digest((event as any).inputHash), outputDigest: digest((event as any).outputHash),
70
+ preview: preview.text || null, previewKind: preview.text ? "summary" : "none",
71
+ outputBytes: Number.isInteger((event as any).outputBytes) && (event as any).outputBytes >= 0 ? Math.min(1_000_000_000, (event as any).outputBytes) : null,
72
+ outputLines: Number.isInteger((event as any).outputLines) && (event as any).outputLines >= 0 ? Math.min(1_000_000_000, (event as any).outputLines) : null,
73
+ exitCode: typeof event.exitCode === "number" && Number.isInteger(event.exitCode) ? event.exitCode : null,
74
+ isError: eventName === "tool_result" ? failed : null,
75
+ affectedFileRefs: [], criterionIds: [], verifierAttemptIds: [], reasonCode
76
+ },
77
+ redaction: { applied: preview.redacted + storedRedactions > 0, valuesRemoved: Math.min(10_000, preview.redacted + storedRedactions), truncated: String(previewValue ?? "").length > 4000 }
78
+ };
79
+ }
80
+
81
+ export function runtimeStartedEventDraft(input: {
82
+ identity: Pick<RuntimeEventIdentity, "projectRef" | "runtimeInstanceId" | "sessionRef">;
83
+ revision: RuntimeEventRevision;
84
+ sourceObservedAt: string;
85
+ buildRef: string;
86
+ capabilitySnapshotRef: string;
87
+ }): RuntimeEventDraft {
88
+ return {
89
+ ...base({ ...input.identity, taskId: null, taskRunId: null }, input.revision, input.sourceObservedAt),
90
+ kind: "runtime.started", evidence: "observed",
91
+ payload: { connectionState: "connected", operationState: "idle", buildRef: input.buildRef, capabilitySnapshotRef: input.capabilitySnapshotRef, reasonCode: null },
92
+ redaction: { applied: false, valuesRemoved: 0, truncated: false }
93
+ };
94
+ }
@@ -0,0 +1,318 @@
1
+ import { createHmac, randomBytes, randomUUID } from "node:crypto";
2
+ import path from "node:path";
3
+
4
+ import { redactSensitiveText } from "../../extensions/redaction-core.js";
5
+
6
+ const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;
7
+ const PUBLIC_REF = /^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/;
8
+ const REVISION = /^[A-Za-z0-9][A-Za-z0-9._:~-]{0,159}$/;
9
+ const DIGEST = /^sha256:[a-f0-9]{64}$/;
10
+ const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
11
+ const MAX_PENDING = 32, MAX_RECENT = 64, DEFAULT_TTL_MS = 5 * 60_000;
12
+
13
+ type Identity = { projectRef: string; runtimeInstanceId: string; sessionRef: string; taskId: string; taskRunId: string;
14
+ agentOperationId: string; toolCallId: string };
15
+ type TreePrecondition = { workspaceRevision: string; indexRevision: string | null; preimageDigest: string };
16
+ type Revisions = { runtimeRevision: string; taskRevision: string; controlRevision: string; approvalRevision: string;
17
+ treePrecondition: TreePrecondition | null };
18
+ type ReceiptRevisions = Omit<Revisions, "treePrecondition">;
19
+ export type ApprovalAuthority = { identity: Omit<Identity, "toolCallId">; revisions: Omit<ReceiptRevisions, "approvalRevision">;
20
+ taskState: "active" | "terminal" } | null;
21
+ export type ApprovalActionDraft = {
22
+ kind: "external-provider-action" | "filesystem-write" | "filesystem-delete" | "workspace-patch" | "source-stage" | "source-unstage" | "source-revert";
23
+ preconditionClass: "runtime-only" | "workspace-tree" | "workspace-index";
24
+ toolName: string; rawAction: unknown; commandPreview?: string | null; parameterPreview?: string; targetPaths?: string[];
25
+ targetSummaries?: string[]; provider?: string | null; urlOrigin?: string | null; requestedScope: string; reason: string;
26
+ riskClass: "low" | "medium" | "high" | "critical"; allowConsequence: string; denyConsequence: string;
27
+ treePrecondition?: TreePrecondition | null;
28
+ };
29
+ type Request = { schemaVersion: 1; version: "piagent-webui-approval-v1"; recordType: "request"; approvalRef: string; decisionToken: string;
30
+ identity: Identity; action: Record<string, unknown>; expectedRevisions: Revisions; state: "waiting"; requestedAt: string; expiresAt: string;
31
+ executor: "pi-guard"; directExecution: false };
32
+ type Receipt = { schemaVersion: 1; version: "piagent-webui-approval-v1"; recordType: "receipt"; approvalRef: string; decisionId: string | null;
33
+ identity: Identity; actionDigest: string; state: "resolved" | "expired" | "cancelled"; decision: "allow" | "deny" | null;
34
+ winnerSurface: "webui" | "terminal" | "runtime-expiry" | "runtime-control" | "runtime-restart"; resolutionReason: string | null;
35
+ resolvedAt: string; preRevisions: Revisions; postRevisions: ReceiptRevisions; permit: Record<string, unknown>; deduplicated: boolean;
36
+ auditRef: string; executor: "pi-guard"; directExecution: false };
37
+ type Binding = { cwd: string; rawSessionId: string; runtimeInstanceId: string; secret: Buffer; authority(): ApprovalAuthority;
38
+ listeners: Set<(event: ApprovalBrokerEvent) => void>; pending: Map<string, Pending>; requests: Map<string, Request>; recent: Receipt[];
39
+ approvalCounter: number; approvalRevision: string };
40
+ type Pending = { request: Request; resolve(value: ApprovalGuardDecision): void; receipt: Receipt | null; timer: NodeJS.Timeout;
41
+ finalWaiters: Array<(receipt: Receipt) => void>; recheck(): boolean };
42
+ export type ApprovalBrokerEvent = { kind: "requested" | "resolved" | "expired" | "cancelled"; approvalRef: string; request?: Request; receipt?: Receipt };
43
+ export type ApprovalGuardDecision = { allowed: boolean; brokered: boolean; receipt: Receipt | null;
44
+ consume(): boolean; cancel(reasonCode?: string): void };
45
+
46
+ function canonical(value: unknown): string {
47
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
48
+ if (!value || typeof value !== "object") return JSON.stringify(value);
49
+ return `{${Object.entries(value as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b))
50
+ .map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;
51
+ }
52
+ function exactTimestamp(value: unknown): value is string {
53
+ if (typeof value !== "string" || !TIMESTAMP.test(value)) return false;
54
+ const parsed = Date.parse(value); return Number.isFinite(parsed) && new Date(parsed).toISOString() === value;
55
+ }
56
+ function exactKeys(value: unknown, keys: string[]): boolean {
57
+ return Boolean(value && typeof value === "object" && !Array.isArray(value)
58
+ && canonical(Object.keys(value as Record<string, unknown>).sort()) === canonical([...keys].sort()));
59
+ }
60
+ function ref(prefix: string, secret: Buffer, value: unknown): string {
61
+ return `${prefix}.${createHmac("sha256", secret).update(canonical(value)).digest("hex")}`;
62
+ }
63
+ function digest(secret: Buffer, value: unknown): string { return `sha256:${createHmac("sha256", secret).update(canonical(value)).digest("hex")}`; }
64
+ function safe(value: unknown, maximum: number): { text: string; redacted: boolean; truncated: boolean } {
65
+ const raw = String(value ?? ""); const redacted = redactSensitiveText(raw);
66
+ const clean = redacted.text.replace(/\u001b(?:[@-_]|\[[0-?]*[ -/]*[@-~])/g, "").replace(/[\u0000-\u001f\u007f-\u009f]/g, " ")
67
+ .replace(/\s+/g, " ").trim();
68
+ return { text: clean.slice(0, maximum), redacted: redacted.redacted, truncated: clean.length > maximum };
69
+ }
70
+ function publicId(value: string): string { const clean = safe(value, 160).text.replace(/[^A-Za-z0-9._:@~-]/g, "-"); return PUBLIC_REF.test(clean) ? clean : "unknown"; }
71
+ function reasonCode(value: string, fallback: string): string { const clean = safe(value, 96).text.toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^-+|-+$/g, ""); return clean || fallback; }
72
+ function key(cwd: string, rawSessionId: string): string { return `${cwd}\0${rawSessionId}`; }
73
+ function clone<T>(value: T): T { return structuredClone(value); }
74
+
75
+ export class PiApprovalBroker {
76
+ readonly #bindings = new Map<string, Binding>();
77
+
78
+ bind(input: { cwd: string; rawSessionId: string; runtimeInstanceId: string; authority(): ApprovalAuthority }): () => void {
79
+ const bindingKey = key(input.cwd, input.rawSessionId), prior = this.#bindings.get(bindingKey);
80
+ if (prior && prior.runtimeInstanceId !== input.runtimeInstanceId) this.#cancelBinding(prior, "runtime-replaced", "runtime-restart");
81
+ if (prior?.runtimeInstanceId === input.runtimeInstanceId) { prior.authority = input.authority; return () => this.unbind(input); }
82
+ const secret = randomBytes(32);
83
+ const binding: Binding = { ...input, secret, listeners: new Set(), pending: new Map(), requests: new Map(), recent: [], approvalCounter: 0,
84
+ approvalRevision: ref("approval-rev", secret, [input.runtimeInstanceId, 0]) };
85
+ this.#bindings.set(bindingKey, binding);
86
+ return () => this.unbind(input);
87
+ }
88
+
89
+ unbind(input: { cwd: string; rawSessionId: string; runtimeInstanceId: string }): void {
90
+ const bindingKey = key(input.cwd, input.rawSessionId), binding = this.#bindings.get(bindingKey);
91
+ if (!binding || binding.runtimeInstanceId !== input.runtimeInstanceId) return;
92
+ this.#cancelBinding(binding, "runtime-stopped", "runtime-restart"); this.#bindings.delete(bindingKey);
93
+ }
94
+
95
+ subscribe(cwd: string, rawSessionId: string, listener: (event: ApprovalBrokerEvent) => void): () => void {
96
+ const binding = this.#bindings.get(key(cwd, rawSessionId)); if (!binding) return () => undefined;
97
+ binding.listeners.add(listener); return () => binding.listeners.delete(listener);
98
+ }
99
+
100
+ cancelForControl(cwd: string, rawSessionId: string, taskRunId: string, reason = "task-pausing"): number {
101
+ const binding = this.#bindings.get(key(cwd, rawSessionId)); if (!binding) return 0;
102
+ const targets = [...binding.pending.entries()].filter(([, pending]) => pending.request.identity.taskRunId === taskRunId);
103
+ for (const [approvalRef] of targets) this.#cancelPending(binding, approvalRef, reason, "runtime-control", "cancelled");
104
+ return targets.length;
105
+ }
106
+
107
+ projection(cwd: string, rawSessionId: string): { revision: string | null; summary: Record<string, unknown> } {
108
+ const binding = this.#bindings.get(key(cwd, rawSessionId));
109
+ if (!binding) return { revision: null, summary: { state: "unknown", pending: [], recent: [],
110
+ health: { state: "unavailable", reasonCode: "approval-broker-unavailable", message: "Approval broker is unavailable" } } };
111
+ const pending = [...binding.pending.values()].filter((item) => !item.receipt).map((item) => this.#summary(item.request));
112
+ const recent = binding.recent.slice(-MAX_RECENT).reverse().map((item) => this.#summary(item));
113
+ const latest = binding.recent.at(-1);
114
+ const state = pending.length ? "waiting" : !latest ? "none" : latest.state === "expired" ? "expired" : "resolved";
115
+ return { revision: binding.approvalRevision, summary: { state, pending, recent: state === "none" ? [] : recent,
116
+ health: { state: "ok", reasonCode: null, message: null } } };
117
+ }
118
+
119
+ detail(cwd: string, rawSessionId: string, approvalRef: string): Request | null {
120
+ if (!REF.test(approvalRef)) return null;
121
+ const pending = this.#bindings.get(key(cwd, rawSessionId))?.pending.get(approvalRef);
122
+ return pending && !pending.receipt ? clone(pending.request) : null;
123
+ }
124
+
125
+ async request(input: { cwd: string; rawSessionId: string; toolCallId: string; action: ApprovalActionDraft;
126
+ expectedTask?: { taskId: string; taskRunId: string } | null; terminalConfirm(): Promise<boolean>; recheck?(): boolean; ttlMs?: number }): Promise<ApprovalGuardDecision> {
127
+ const binding = this.#bindings.get(key(input.cwd, input.rawSessionId));
128
+ const authority = binding?.authority();
129
+ if (!binding || !authority || authority.taskState !== "active" || input.expectedTask && (authority.identity.taskId !== input.expectedTask.taskId || authority.identity.taskRunId !== input.expectedTask.taskRunId)
130
+ || !REF.test(authority.identity.agentOperationId)
131
+ || !REF.test(input.toolCallId) || binding.pending.size >= MAX_PENDING) return this.#terminalOnly(input.terminalConfirm);
132
+ const now = Date.now(), requestedAt = new Date(now).toISOString(), expiresAt = new Date(now + Math.min(Math.max(input.ttlMs ?? DEFAULT_TTL_MS, 5_000), DEFAULT_TTL_MS)).toISOString();
133
+ const approvalRef = ref("approval", binding.secret, [input.toolCallId, now, randomUUID()]);
134
+ const decisionToken = randomBytes(32).toString("base64url");
135
+ const nextRevision = this.#nextRevision(binding, "requested", approvalRef);
136
+ const identity: Identity = { ...authority.identity, toolCallId: input.toolCallId };
137
+ const action = this.#action(binding, input.action, input.cwd);
138
+ const expectedRevisions: Revisions = { ...authority.revisions, approvalRevision: nextRevision,
139
+ treePrecondition: input.action.preconditionClass === "runtime-only" ? null : input.action.treePrecondition ?? null };
140
+ if ((input.action.preconditionClass !== "runtime-only" && !expectedRevisions.treePrecondition)
141
+ || !this.#validTree(expectedRevisions.treePrecondition)) return this.#terminalOnly(input.terminalConfirm);
142
+ const request: Request = { schemaVersion: 1, version: "piagent-webui-approval-v1", recordType: "request", approvalRef, decisionToken,
143
+ identity, action, expectedRevisions, state: "waiting", requestedAt, expiresAt, executor: "pi-guard", directExecution: false };
144
+ const result = new Promise<ApprovalGuardDecision>((resolve) => {
145
+ const timer = setTimeout(() => this.#expire(binding, approvalRef), Date.parse(expiresAt) - Date.now()); timer.unref();
146
+ binding.pending.set(approvalRef, { request, resolve, receipt: null, timer, finalWaiters: [], recheck: input.recheck ?? (() => true) }); binding.requests.set(approvalRef, request);
147
+ while (binding.requests.size > MAX_PENDING + MAX_RECENT) binding.requests.delete(binding.requests.keys().next().value as string);
148
+ });
149
+ this.#emit(binding, { kind: "requested", approvalRef, request: clone(request) });
150
+ void Promise.resolve().then(input.terminalConfirm).then(
151
+ (allow) => this.#settle(binding, approvalRef, allow ? "allow" : "deny", "terminal", ref("decision", binding.secret, [approvalRef, "terminal", now])),
152
+ () => this.#settle(binding, approvalRef, "deny", "terminal", ref("decision", binding.secret, [approvalRef, "terminal-error", now]))
153
+ );
154
+ return result;
155
+ }
156
+
157
+ async decide(cwd: string, rawSessionId: string, approvalRef: string, value: unknown): Promise<Receipt> {
158
+ const binding = this.#bindings.get(key(cwd, rawSessionId)); if (!binding || !REF.test(approvalRef)) throw new Error("approval-unavailable");
159
+ const pending = binding.pending.get(approvalRef);
160
+ if (!pending) {
161
+ const prior = binding.recent.find((item) => item.approvalRef === approvalRef);
162
+ const request = binding.requests.get(approvalRef);
163
+ if (prior && request && this.#validDecision(value, request, null) && (value as any).decisionId === prior.decisionId) return { ...clone(prior), deduplicated: true };
164
+ throw new Error("approval-not-pending");
165
+ }
166
+ if (!this.#validDecision(value, pending.request, null)) throw new Error("approval-decision-invalid");
167
+ const decision = value as any;
168
+ if (pending.receipt) {
169
+ if (decision.decisionId !== pending.receipt.decisionId) throw new Error("approval-already-resolved");
170
+ if (pending.receipt.permit.status === "provisional") return new Promise<Receipt>((resolve) => pending.finalWaiters.push((receipt) => resolve({ ...receipt, deduplicated: true })));
171
+ return { ...clone(pending.receipt), deduplicated: true };
172
+ }
173
+ if (Date.now() >= Date.parse(pending.request.expiresAt)) { this.#expire(binding, approvalRef); throw new Error("approval-expired"); }
174
+ const final = new Promise<Receipt>((resolve) => pending.finalWaiters.push(resolve));
175
+ this.#settle(binding, approvalRef, decision.decision, "webui", decision.decisionId);
176
+ if (decision.decision === "deny") return clone(binding.recent.at(-1)!);
177
+ return final;
178
+ }
179
+
180
+ #terminalOnly(confirm: () => Promise<boolean>): Promise<ApprovalGuardDecision> {
181
+ return Promise.resolve().then(confirm).then((allowed) => ({ allowed, brokered: false, receipt: null,
182
+ consume: () => allowed, cancel: () => undefined }), () => ({ allowed: false, brokered: false, receipt: null,
183
+ consume: () => false, cancel: () => undefined }));
184
+ }
185
+
186
+ #action(binding: Binding, draft: ApprovalActionDraft, cwd: string): Record<string, unknown> {
187
+ const command = draft.commandPreview === null || draft.commandPreview === undefined ? null : safe(draft.commandPreview, 4_000);
188
+ const parameter = safe(draft.parameterPreview ?? "No additional parameters", 4_000);
189
+ const targetPaths = (draft.targetPaths ?? []).slice(0, 32).map((item) => safe(item, 500)).filter((item) => item.text).map((item) => item.text);
190
+ const targetSummaries = (draft.targetSummaries ?? []).slice(0, 32).map((item) => safe(item, 500)).filter((item) => item.text).map((item) => item.text);
191
+ const removed = [command, parameter].filter((item) => item?.redacted).length;
192
+ const truncated = Boolean(command?.truncated || parameter.truncated || (draft.targetPaths?.length ?? 0) > 32 || (draft.targetSummaries?.length ?? 0) > 32);
193
+ const provider = draft.provider ? safe(draft.provider, 160).text : "";
194
+ const targetProvided = targetPaths.length > 0 || targetSummaries.length > 0;
195
+ return { kind: draft.kind, preconditionClass: draft.preconditionClass, toolName: publicId(draft.toolName),
196
+ actionDigest: digest(binding.secret, draft.rawAction), canonicalization: "digest-bound-action-v1", previewPolicy: "redacted-no-secrets-v1",
197
+ commandPreview: command?.text || null, parameterPreview: parameter.text || "No additional parameters",
198
+ targetEvidence: targetProvided ? { state: "provided", reasonCode: null } : { state: "redacted", reasonCode: "target-not-exposed" },
199
+ cwdRef: ref("cwd", binding.secret, cwd), cwdDisplay: safe(path.basename(cwd), 500).text || null,
200
+ targetRefs: [], targetPaths, targetSummaries, providerRef: provider ? ref("provider", binding.secret, provider) : null,
201
+ urlOrigin: /^https?:\/\/(?:[A-Za-z0-9-]+\.)*[A-Za-z0-9-]+(?::[0-9]{1,5})?$/.test(draft.urlOrigin ?? "") ? draft.urlOrigin : null,
202
+ requestedScope: reasonCode(draft.requestedScope, "one-action"), reason: safe(draft.reason, 500).text || "Human confirmation is required",
203
+ riskClass: draft.riskClass, consequences: { allow: safe(draft.allowConsequence, 500).text || "Allow this exact action once",
204
+ deny: safe(draft.denyConsequence, 500).text || "Block this action" },
205
+ redaction: { applied: removed > 0, valuesRemoved: removed, truncated } };
206
+ }
207
+
208
+ #validDecision(value: unknown, request?: Request, receipt?: Receipt | null): boolean {
209
+ if (!exactKeys(value, ["schemaVersion", "version", "recordType", "approvalRef", "decisionId", "decisionToken", "identity", "actionDigest",
210
+ "expectedRevisions", "decision", "reason", "decidedAt", "expiresAt", "decisionSurface", "executor", "directExecution"])) return false;
211
+ const item = value as any;
212
+ if (item.schemaVersion !== 1 || item.version !== "piagent-webui-approval-v1" || item.recordType !== "decision"
213
+ || !REF.test(item.approvalRef) || !REF.test(item.decisionId) || typeof item.decisionToken !== "string" || item.decisionToken.length < 32
214
+ || !["allow", "deny"].includes(item.decision) || !exactTimestamp(item.decidedAt) || !exactTimestamp(item.expiresAt)
215
+ || item.decisionSurface !== "webui" || item.executor !== "pi-guard" || item.directExecution !== false
216
+ || !(item.reason === null || typeof item.reason === "string" && item.reason.length <= 500)) return false;
217
+ if (request) return item.approvalRef === request.approvalRef && item.decisionToken === request.decisionToken
218
+ && item.actionDigest === request.action.actionDigest && canonical(item.identity) === canonical(request.identity)
219
+ && canonical(item.expectedRevisions) === canonical(request.expectedRevisions) && item.expiresAt === request.expiresAt
220
+ && Date.parse(item.decidedAt) >= Date.parse(request.requestedAt) - 1_000 && Date.parse(item.decidedAt) <= Date.now() + 1_000;
221
+ return Boolean(receipt && item.approvalRef === receipt.approvalRef && item.decisionId === receipt.decisionId
222
+ && item.actionDigest === receipt.actionDigest && canonical(item.identity) === canonical(receipt.identity));
223
+ }
224
+
225
+ #validTree(value: TreePrecondition | null): boolean {
226
+ return value === null || Boolean(REVISION.test(value.workspaceRevision) && (value.indexRevision === null || REVISION.test(value.indexRevision)) && DIGEST.test(value.preimageDigest));
227
+ }
228
+
229
+ #settle(binding: Binding, approvalRef: string, decision: "allow" | "deny", surface: "webui" | "terminal", decisionId: string): void {
230
+ const pending = binding.pending.get(approvalRef); if (!pending || pending.receipt) return;
231
+ clearTimeout(pending.timer); const resolvedAt = new Date().toISOString();
232
+ const postRevision = this.#nextRevision(binding, "resolved", [approvalRef, decision, surface]);
233
+ const receipt: Receipt = { schemaVersion: 1, version: "piagent-webui-approval-v1", recordType: "receipt", approvalRef, decisionId,
234
+ identity: clone(pending.request.identity), actionDigest: String(pending.request.action.actionDigest), state: "resolved", decision,
235
+ winnerSurface: surface, resolutionReason: null, resolvedAt, preRevisions: clone(pending.request.expectedRevisions),
236
+ postRevisions: { runtimeRevision: pending.request.expectedRevisions.runtimeRevision, taskRevision: pending.request.expectedRevisions.taskRevision,
237
+ controlRevision: pending.request.expectedRevisions.controlRevision, approvalRevision: postRevision },
238
+ permit: decision === "allow" ? { status: "provisional", issuedAt: resolvedAt, consumedAt: null, reasonCode: null }
239
+ : { status: "not-issued", issuedAt: null, consumedAt: null, reasonCode: null }, deduplicated: false,
240
+ auditRef: ref("approval-audit", binding.secret, [approvalRef, resolvedAt, surface, decision]), executor: "pi-guard", directExecution: false };
241
+ pending.receipt = receipt; binding.recent.push(receipt); binding.recent = binding.recent.slice(-MAX_RECENT);
242
+ this.#emit(binding, { kind: "resolved", approvalRef, receipt: clone(receipt) });
243
+ const decisionResult: ApprovalGuardDecision = { allowed: decision === "allow", brokered: true, receipt: clone(receipt),
244
+ consume: () => this.#consume(binding, receipt), cancel: (reason = "guard-cancelled") => this.#cancelPermit(binding, receipt, reason) };
245
+ pending.resolve(decisionResult);
246
+ if (decision === "deny") this.#finish(binding, pending, receipt);
247
+ }
248
+
249
+ #consume(binding: Binding, receipt: Receipt): boolean {
250
+ if (receipt.permit.status !== "provisional") return receipt.permit.status === "consumed";
251
+ const authority = binding.authority();
252
+ const pending = binding.pending.get(receipt.approvalRef);
253
+ const expectedIdentity = { projectRef: receipt.identity.projectRef, runtimeInstanceId: receipt.identity.runtimeInstanceId,
254
+ sessionRef: receipt.identity.sessionRef, taskId: receipt.identity.taskId, taskRunId: receipt.identity.taskRunId,
255
+ agentOperationId: receipt.identity.agentOperationId };
256
+ if (!authority || authority.taskState !== "active" || !pending?.recheck() || canonical(authority.identity) !== canonical(expectedIdentity)) {
257
+ this.#cancelPermit(binding, receipt, "authority-changed"); return false;
258
+ }
259
+ const expected = receipt.preRevisions;
260
+ if (authority.revisions.runtimeRevision !== expected.runtimeRevision || authority.revisions.taskRevision !== expected.taskRevision
261
+ || authority.revisions.controlRevision !== expected.controlRevision || binding.approvalRevision !== receipt.postRevisions.approvalRevision) {
262
+ this.#cancelPermit(binding, receipt, "revision-changed"); return false;
263
+ }
264
+ const consumedAt = new Date().toISOString(); receipt.permit = { status: "consumed", issuedAt: receipt.permit.issuedAt, consumedAt, reasonCode: null };
265
+ receipt.postRevisions.approvalRevision = this.#nextRevision(binding, "permit-consumed", receipt.approvalRef);
266
+ if (pending) this.#finish(binding, pending, receipt);
267
+ this.#emit(binding, { kind: "resolved", approvalRef: receipt.approvalRef, receipt: clone(receipt) }); return true;
268
+ }
269
+
270
+ #cancelPermit(binding: Binding, receipt: Receipt, reason: string): void {
271
+ if (receipt.permit.status !== "provisional") return;
272
+ receipt.permit = { status: "cancelled", issuedAt: receipt.permit.issuedAt, consumedAt: null, reasonCode: reasonCode(reason, "guard-cancelled") };
273
+ receipt.postRevisions.approvalRevision = this.#nextRevision(binding, "permit-cancelled", [receipt.approvalRef, reason]);
274
+ const pending = binding.pending.get(receipt.approvalRef); if (pending) this.#finish(binding, pending, receipt);
275
+ this.#emit(binding, { kind: "cancelled", approvalRef: receipt.approvalRef, receipt: clone(receipt) });
276
+ }
277
+
278
+ #expire(binding: Binding, approvalRef: string): void { this.#cancelPending(binding, approvalRef, "approval-expired", "runtime-expiry", "expired"); }
279
+ #cancelBinding(binding: Binding, reason: string, surface: "runtime-restart" | "runtime-control"): void {
280
+ for (const approvalRef of [...binding.pending.keys()]) this.#cancelPending(binding, approvalRef, reason, surface, "cancelled");
281
+ }
282
+ #cancelPending(binding: Binding, approvalRef: string, reason: string, surface: "runtime-expiry" | "runtime-restart" | "runtime-control", state: "expired" | "cancelled"): void {
283
+ const pending = binding.pending.get(approvalRef); if (!pending || pending.receipt) return; clearTimeout(pending.timer);
284
+ const resolvedAt = new Date().toISOString(), post = this.#nextRevision(binding, state, approvalRef);
285
+ const receipt: Receipt = { schemaVersion: 1, version: "piagent-webui-approval-v1", recordType: "receipt", approvalRef, decisionId: null,
286
+ identity: clone(pending.request.identity), actionDigest: String(pending.request.action.actionDigest), state, decision: null, winnerSurface: surface,
287
+ resolutionReason: reasonCode(reason, "approval-cancelled"), resolvedAt, preRevisions: clone(pending.request.expectedRevisions),
288
+ postRevisions: { runtimeRevision: pending.request.expectedRevisions.runtimeRevision, taskRevision: pending.request.expectedRevisions.taskRevision,
289
+ controlRevision: pending.request.expectedRevisions.controlRevision, approvalRevision: post },
290
+ permit: { status: state === "expired" ? "expired" : "cancelled", issuedAt: null, consumedAt: null, reasonCode: reasonCode(reason, "approval-cancelled") },
291
+ deduplicated: false, auditRef: ref("approval-audit", binding.secret, [approvalRef, resolvedAt, surface]), executor: "pi-guard", directExecution: false };
292
+ pending.receipt = receipt; binding.recent.push(receipt); binding.recent = binding.recent.slice(-MAX_RECENT);
293
+ this.#emit(binding, { kind: state === "expired" ? "expired" : "cancelled", approvalRef, receipt: clone(receipt) });
294
+ pending.resolve({ allowed: false, brokered: true, receipt: clone(receipt), consume: () => false, cancel: () => undefined }); this.#finish(binding, pending, receipt);
295
+ }
296
+
297
+ #finish(binding: Binding, pending: Pending, receipt: Receipt): void {
298
+ binding.pending.delete(receipt.approvalRef); for (const resolve of pending.finalWaiters.splice(0)) resolve(clone(receipt));
299
+ }
300
+ #nextRevision(binding: Binding, kind: string, value: unknown): string {
301
+ binding.approvalCounter += 1; binding.approvalRevision = ref("approval-rev", binding.secret, [binding.runtimeInstanceId, binding.approvalCounter, kind, value]);
302
+ return binding.approvalRevision;
303
+ }
304
+ #emit(binding: Binding, event: ApprovalBrokerEvent): void { for (const listener of binding.listeners) { try { listener(clone(event)); } catch { /* projection listeners are fail-soft */ } } }
305
+ #summary(value: Request | Receipt): Record<string, unknown> {
306
+ if (value.recordType === "request") return { approvalRef: value.approvalRef, state: "waiting", resolution: null,
307
+ actionSummary: safe(`${value.action.toolName}: ${value.action.reason}`, 500).text || "Approval required", toolCallId: value.identity.toolCallId,
308
+ expiresAt: value.expiresAt, reasonCode: null };
309
+ return { approvalRef: value.approvalRef, state: value.state === "expired" ? "expired" : "resolved",
310
+ resolution: value.state === "expired" ? "expired" : value.state === "cancelled" ? "cancelled" : value.decision,
311
+ actionSummary: safe(`${value.identity.toolCallId}: ${value.decision ?? value.state}`, 500).text || "Approval resolved",
312
+ toolCallId: value.identity.toolCallId, expiresAt: null, reasonCode: value.state === "expired" ? value.resolutionReason : null };
313
+ }
314
+ }
315
+
316
+ const BROKER_KEY = Symbol.for("piagent.webui.approval-broker.v1");
317
+ const root = globalThis as typeof globalThis & { [BROKER_KEY]?: PiApprovalBroker };
318
+ export const piApprovalBroker = root[BROKER_KEY] ??= new PiApprovalBroker();
@@ -0,0 +1,59 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ import { redactSensitiveText } from "../../extensions/redaction-core.js";
4
+ import { canonicalReviewValue } from "./review-state-contract.ts";
5
+ import type { SourceChangeDocument, WebUiIdentity } from "./source-change-projection.ts";
6
+
7
+ const MAX_FILES = 300, MAX_BODY_FILES = 12;
8
+ type Status = "A" | "M" | "D" | "R" | "C";
9
+ const ACTION: Record<Status, string> = { A: "Add", M: "Update", D: "Remove", R: "Rename", C: "Resolve conflict in" };
10
+
11
+ function token(value: unknown): string { return `commit-summary.${createHash("sha256").update(canonicalReviewValue(value)).digest("hex")}`; }
12
+ function safe(value: unknown, maximum: number): { text: string; redacted: boolean } {
13
+ const raw = String(value ?? "").replace(/[\u0000-\u001F\u007F]/g, " ").replace(/\s+/g, " ").trim();
14
+ const result = redactSensitiveText(raw); return { text: result.text.slice(0, maximum).trim(), redacted: result.redacted };
15
+ }
16
+ function unavailable(identity: WebUiIdentity, generatedAt: string, reasonCode: string) {
17
+ return { schemaVersion: 1 as const, version: "piagent-webui-commit-summary-v1" as const, generatedAt, identity,
18
+ state: "unavailable" as const, summary: null, reasonCode,
19
+ health: { state: "unavailable" as const, reasonCode, message: "A current non-empty staged projection is required." } };
20
+ }
21
+
22
+ export function projectDeterministicCommitSummary(options: { identity: WebUiIdentity; sourceView: SourceChangeDocument;
23
+ taskRevision: string; indexRevision: string; generatedAt?: string }) {
24
+ const generatedAt = options.generatedAt ?? new Date().toISOString(), identity = { ...options.identity, agentOperationId: null, toolCallId: null };
25
+ if (!identity.taskId || !identity.taskRunId || options.sourceView.view !== "staged"
26
+ || options.sourceView.availability.state !== "current") return unavailable(identity, generatedAt, "staged-projection-unavailable");
27
+ const files = options.sourceView.files.slice(0, MAX_FILES) as Array<Record<string, any>>;
28
+ const total = Math.min(2_000, Number((options.sourceView.page as any)?.total ?? files.length));
29
+ if (total < 1 || files.length < 1) return unavailable(identity, generatedAt, "no-staged-changes");
30
+ const statusCounts: Record<Status, number> = { A: 0, M: 0, D: 0, R: 0, C: 0 }, lines: string[] = [];
31
+ let protectedFileCount = 0, redacted = false, additions = 0, deletions = 0, exactStats = total === files.length;
32
+ const commitments: unknown[] = [];
33
+ for (const file of files) {
34
+ const status = ["A", "M", "D", "R", "C"].includes(file.status) ? file.status as Status : "M";
35
+ statusCounts[status] += 1; commitments.push([file.fileRef, file.fileRevision, status, file.currentDigest, file.baseDigest]);
36
+ const restricted = file.content?.access !== "available" || file.pathDisplay !== "exact-safe";
37
+ if (restricted) { protectedFileCount += 1; exactStats = false; continue; }
38
+ const display = safe(file.path, 300); redacted ||= display.redacted;
39
+ const label = display.redacted || !display.text ? "[redacted staged file]" : display.text;
40
+ const statsExact = file.stats?.state === "exact" && Number.isInteger(file.stats.additions) && Number.isInteger(file.stats.deletions);
41
+ if (statsExact) { additions += file.stats.additions; deletions += file.stats.deletions; } else exactStats = false;
42
+ if (lines.length < MAX_BODY_FILES) lines.push(`- ${ACTION[status]} ${label}${statsExact ? ` (+${file.stats.additions}/-${file.stats.deletions})` : ""}`);
43
+ }
44
+ if (protectedFileCount) lines.push(`- ${protectedFileCount} protected staged file${protectedFileCount === 1 ? "" : "s"} (names omitted)`);
45
+ const omitted = Math.max(0, total - Math.min(files.length, MAX_BODY_FILES + protectedFileCount));
46
+ if (omitted) lines.push(`- ${omitted} additional staged file${omitted === 1 ? "" : "s"} omitted from this bounded preview`);
47
+ lines.push(exactStats ? `- Staged changes: +${additions} / -${deletions}` : "- Staged line totals are incomplete");
48
+ const singleVisible = total === 1 && protectedFileCount === 0 && lines[0]?.startsWith("- ") ? lines[0].replace(/^- /, "").replace(/ \(\+\d+\/-\d+\)$/, "") : null;
49
+ const title = safe(singleVisible ?? `Update ${total} staged files`, 160).text || `Update ${total} staged files`;
50
+ const summaryRef = token({ taskRevision: options.taskRevision, indexRevision: options.indexRevision, total, commitments, lines, title });
51
+ const modelPrompt = ["Write a concise Git commit message from the exact staged summary below.",
52
+ "Return one title of at most 72 characters, then optional bullet points. Do not claim that a commit or push was executed.",
53
+ `Index revision: ${options.indexRevision}`, `Deterministic title: ${title}`, ...lines].join("\n").slice(0, 8_000);
54
+ return { schemaVersion: 1 as const, version: "piagent-webui-commit-summary-v1" as const, generatedAt, identity, state: "ready" as const,
55
+ summary: { summaryRef, taskRevision: options.taskRevision, indexRevision: options.indexRevision, title, bodyLines: lines,
56
+ modelPrompt, fileCount: total, returnedFiles: files.length, statusCounts, additions: exactStats ? additions : null,
57
+ deletions: exactStats ? deletions : null, protectedFileCount, redacted, truncated: Boolean((options.sourceView.page as any)?.truncated) || omitted > 0 },
58
+ reasonCode: null, health: { state: "ok" as const, reasonCode: null, message: null } };
59
+ }
@@ -0,0 +1,37 @@
1
+ import fs from "node:fs";
2
+
3
+ import { contextEnginePaths } from "../../extensions/context-engine.js";
4
+ import { resolveLocalStatePath } from "../../extensions/local-state-path.js";
5
+
6
+ function tailText(file: string, maximumBytes: number): { text: string; truncated: boolean } {
7
+ const descriptor = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
8
+ try {
9
+ const stat = fs.fstatSync(descriptor), start = Math.max(0, stat.size - maximumBytes);
10
+ const buffer = Buffer.allocUnsafe(stat.size - start); fs.readSync(descriptor, buffer, 0, buffer.length, start);
11
+ let text = buffer.toString("utf8"); if (start > 0) text = text.slice(Math.max(0, text.indexOf("\n") + 1));
12
+ return { text, truncated: start > 0 };
13
+ } finally { fs.closeSync(descriptor); }
14
+ }
15
+
16
+ export function inspectBoundedContextTelemetry(cwd: string, options: { limit?: number; maximumBytes?: number } = {}) {
17
+ const limit = Math.max(1, Math.min(50_000, options.limit ?? 5_000));
18
+ const maximumBytes = Math.max(64 * 1024, Math.min(256 * 1024 * 1024, options.maximumBytes ?? 32 * 1024 * 1024));
19
+ const target = contextEnginePaths(cwd).telemetry, rows: Record<string, unknown>[] = [];
20
+ let exists = false, corruptions = 0, recoverableTailBytes = 0, inputTruncated = false;
21
+ for (const source of [`${target}.1`, target]) {
22
+ const safe = resolveLocalStatePath(cwd, source, { label: "Context telemetry" });
23
+ try {
24
+ const stat = fs.lstatSync(safe); if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("Context telemetry must be a regular file");
25
+ exists = true;
26
+ } catch (error: any) { if (error?.code === "ENOENT") continue; throw error; }
27
+ const read = tailText(safe, maximumBytes); inputTruncated ||= read.truncated;
28
+ const complete = read.text.endsWith("\n") || read.text.endsWith("\r"), lines = read.text.split(/\r?\n/);
29
+ for (let index = 0; index < lines.length; index += 1) {
30
+ const line = lines[index]; if (!line) continue;
31
+ try { const row = JSON.parse(line); if (row && typeof row === "object" && !Array.isArray(row)) rows.push(row); else corruptions += 1; }
32
+ catch { if (!complete && index === lines.length - 1) recoverableTailBytes += Buffer.byteLength(line); else corruptions += 1; }
33
+ }
34
+ }
35
+ return { records: rows.slice(-limit), exists, corruptions, recoverableTailBytes,
36
+ inputTruncated: inputTruncated || rows.length > limit };
37
+ }