@piagent/platform 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (304) hide show
  1. package/CHANGELOG.md +56 -3
  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 +10 -2
  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 +11 -7
  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/capability-verification-cache.js +280 -0
  140. package/packages/piagent-core/capabilities/runtime-integrity.js +153 -1
  141. package/packages/piagent-core/extensions/document-intake.ts +24 -10
  142. package/packages/piagent-core/extensions/piagent-guard.ts +90 -73
  143. package/packages/piagent-core/extensions/redaction-core.d.ts +2 -0
  144. package/packages/piagent-core/extensions/state-retention.js +77 -44
  145. package/packages/piagent-core/extensions/task-journal.js +30 -1
  146. package/packages/piagent-core/extensions/task-state.js +33 -36
  147. package/packages/piagent-core/mcp/mcp-server-catalog.js +5 -5
  148. package/packages/piagent-core/package.json +1 -1
  149. package/packages/piagent-core/runtime/hooks/session-start-hook.ts +2 -2
  150. package/packages/piagent-core/runtime/hooks/tool-call-hook.ts +5 -2
  151. package/packages/piagent-core/runtime/hooks/tool-result-hook.ts +20 -19
  152. package/packages/piagent-core/runtime/hooks/tool-result-metadata.ts +13 -0
  153. package/packages/piagent-core/runtime/input/chat-images.ts +2 -2
  154. package/packages/piagent-core/runtime/inspection/activity-event-adapter.ts +94 -0
  155. package/packages/piagent-core/runtime/inspection/approval-broker.ts +318 -0
  156. package/packages/piagent-core/runtime/inspection/commit-summary-projection.ts +59 -0
  157. package/packages/piagent-core/runtime/inspection/context-telemetry-inspection.ts +37 -0
  158. package/packages/piagent-core/runtime/inspection/criteria-links.ts +295 -0
  159. package/packages/piagent-core/runtime/inspection/diff-projection.ts +499 -0
  160. package/packages/piagent-core/runtime/inspection/git-filter-safety.ts +38 -0
  161. package/packages/piagent-core/runtime/inspection/git-numstat-adapter.ts +71 -0
  162. package/packages/piagent-core/runtime/inspection/git-status-adapter.ts +493 -0
  163. package/packages/piagent-core/runtime/inspection/git-tree-adapter.ts +108 -0
  164. package/packages/piagent-core/runtime/inspection/mcp-control.ts +10 -0
  165. package/packages/piagent-core/runtime/inspection/mutation-provenance-contract.ts +131 -0
  166. package/packages/piagent-core/runtime/inspection/mutation-provenance-recorder.ts +48 -0
  167. package/packages/piagent-core/runtime/inspection/mutation-provenance-store.ts +161 -0
  168. package/packages/piagent-core/runtime/inspection/project-runtime-inspection.ts +36 -0
  169. package/packages/piagent-core/runtime/inspection/review-state-contract.ts +108 -0
  170. package/packages/piagent-core/runtime/inspection/review-state-projection.ts +93 -0
  171. package/packages/piagent-core/runtime/inspection/review-state-store.ts +112 -0
  172. package/packages/piagent-core/runtime/inspection/runtime-event-store.ts +262 -0
  173. package/packages/piagent-core/runtime/inspection/same-process-bridge-proof.ts +103 -0
  174. package/packages/piagent-core/runtime/inspection/source-change-projection.ts +471 -0
  175. package/packages/piagent-core/runtime/inspection/source-evidence-contract.ts +139 -0
  176. package/packages/piagent-core/runtime/inspection/source-evidence-store.ts +315 -0
  177. package/packages/piagent-core/runtime/inspection/source-handoff-store.ts +70 -0
  178. package/packages/piagent-core/runtime/inspection/source-inspection-plan.ts +34 -0
  179. package/packages/piagent-core/runtime/inspection/source-mutation-projection.ts +164 -0
  180. package/packages/piagent-core/runtime/inspection/source-mutation-store.ts +168 -0
  181. package/packages/piagent-core/runtime/inspection/source-open-target.ts +38 -0
  182. package/packages/piagent-core/runtime/inspection/source-revert-projection.ts +147 -0
  183. package/packages/piagent-core/runtime/inspection/task-baseline-start-capture.ts +22 -0
  184. package/packages/piagent-core/runtime/inspection/task-compaction-history.ts +160 -0
  185. package/packages/piagent-core/runtime/inspection/task-control-journal.ts +131 -0
  186. package/packages/piagent-core/runtime/inspection/task-handoff-history.ts +95 -0
  187. package/packages/piagent-core/runtime/inspection/task-provenance-projection.ts +60 -0
  188. package/packages/piagent-core/runtime/inspection/task-recovery-timeline.ts +88 -0
  189. package/packages/piagent-core/runtime/inspection/task-run-index.ts +87 -0
  190. package/packages/piagent-core/runtime/inspection/task-source-projection.ts +401 -0
  191. package/packages/piagent-core/runtime/inspection/task-subagent-tree.ts +101 -0
  192. package/packages/piagent-core/runtime/inspection/text-diff.ts +60 -0
  193. package/packages/piagent-core/runtime/inspection/verifier-snapshot-contract.ts +114 -0
  194. package/packages/piagent-core/runtime/inspection/verifier-snapshot-store.ts +189 -0
  195. package/packages/piagent-core/runtime/inspection/webui-snapshot.ts +320 -0
  196. package/packages/piagent-core/runtime/inspection/workspace-file-reader.ts +132 -0
  197. package/packages/piagent-core/runtime/inspection/workspace-source-projection.ts +96 -0
  198. package/packages/piagent-core/runtime/inspection/zero-turn-conformance.ts +175 -0
  199. package/packages/piagent-core/runtime/orchestration/owned-work-budget.ts +68 -4
  200. package/packages/piagent-core/runtime/policy/source-index-transaction.ts +173 -0
  201. package/packages/piagent-core/runtime/policy/source-mutation-guard-binding.ts +42 -0
  202. package/packages/piagent-core/runtime/policy/source-mutation-guard.ts +184 -0
  203. package/packages/piagent-core/runtime/policy/source-worktree-transaction.ts +105 -0
  204. package/packages/piagent-core/runtime/product/activity-inspector-footer.ts +5 -3
  205. package/packages/piagent-core/runtime/product/activity-inspector.ts +85 -343
  206. package/packages/piagent-core/runtime/recovery/resume-state.ts +38 -1
  207. package/packages/piagent-core/runtime/registration/activity-inspector-command.ts +68 -14
  208. package/packages/piagent-core/runtime/registration/task-start-tool.ts +13 -14
  209. package/packages/piagent-core/runtime/session/model-authorship-state.ts +31 -3
  210. package/packages/piagent-core/runtime/session/runtime-state.ts +11 -1
  211. package/packages/piagent-webui/dist/client/assets/index-DjMntaK5.js +172 -0
  212. package/packages/piagent-webui/dist/client/assets/index-DwKCWbwd.css +1 -0
  213. package/packages/piagent-webui/dist/client/index.html +16 -0
  214. package/packages/piagent-webui/extension/attachment-store.ts +323 -0
  215. package/packages/piagent-webui/extension/held-message-queue.ts +311 -0
  216. package/packages/piagent-webui/extension/lifecycle-controller.ts +408 -0
  217. package/packages/piagent-webui/extension/lifecycle-event-adapter.ts +23 -0
  218. package/packages/piagent-webui/extension/piagent-webui.ts +470 -0
  219. package/packages/piagent-webui/extension/review-controller.ts +160 -0
  220. package/packages/piagent-webui/extension/same-session-bridge.ts +500 -0
  221. package/packages/piagent-webui/extension/session-options-controller.ts +281 -0
  222. package/packages/piagent-webui/extension/session-stream-adapter.ts +249 -0
  223. package/packages/piagent-webui/extension/source-mutation-controller.ts +215 -0
  224. package/packages/piagent-webui/extension/source-open-controller.ts +136 -0
  225. package/packages/piagent-webui/extension/source-revert-controller.ts +189 -0
  226. package/packages/piagent-webui/extension/terminal-session-adapter.ts +73 -0
  227. package/packages/piagent-webui/extension/vscode-handoff.ts +51 -0
  228. package/packages/piagent-webui/gateway/control-socket.ts +92 -0
  229. package/packages/piagent-webui/gateway/gateway-events.ts +60 -0
  230. package/packages/piagent-webui/gateway/gateway-protocol-service.ts +64 -0
  231. package/packages/piagent-webui/gateway/gateway-service.ts +215 -0
  232. package/packages/piagent-webui/gateway/gateway-session-stream.ts +110 -0
  233. package/packages/piagent-webui/gateway/mcp-auth-broker.ts +158 -0
  234. package/packages/piagent-webui/gateway/native-project-picker.ts +29 -0
  235. package/packages/piagent-webui/gateway/pi-host.ts +41 -0
  236. package/packages/piagent-webui/gateway/profile-state.ts +1 -0
  237. package/packages/piagent-webui/gateway/project-registry.ts +108 -0
  238. package/packages/piagent-webui/gateway/provider-auth-broker.ts +172 -0
  239. package/packages/piagent-webui/gateway/session-catalog.ts +128 -0
  240. package/packages/piagent-webui/gateway/session-command-controller.ts +237 -0
  241. package/packages/piagent-webui/gateway/session-command-store.ts +224 -0
  242. package/packages/piagent-webui/gateway/session-inspection-registry.ts +204 -0
  243. package/packages/piagent-webui/gateway/session-lease-store.ts +1 -0
  244. package/packages/piagent-webui/gateway/session-metadata-store.ts +152 -0
  245. package/packages/piagent-webui/gateway/session-runtime-supervisor.ts +485 -0
  246. package/packages/piagent-webui/ownership/gateway-runtime-context.ts +8 -0
  247. package/packages/piagent-webui/ownership/profile-state.ts +117 -0
  248. package/packages/piagent-webui/ownership/session-lease-store.ts +329 -0
  249. package/packages/piagent-webui/ownership/session-refs.ts +8 -0
  250. package/packages/piagent-webui/package.json +33 -0
  251. package/packages/piagent-webui/server/README.md +4 -0
  252. package/packages/piagent-webui/server/benchmark-release-monitor.ts +230 -0
  253. package/packages/piagent-webui/server/core-inspection-provider.ts +403 -0
  254. package/packages/piagent-webui/server/gateway-websocket.ts +143 -0
  255. package/packages/piagent-webui/server/http-security.ts +27 -0
  256. package/packages/piagent-webui/server/ipc-read-model-client.ts +89 -0
  257. package/packages/piagent-webui/server/loopback-server.ts +368 -0
  258. package/packages/piagent-webui/server/read-model-provider.ts +37 -0
  259. package/packages/piagent-webui/server/read-only-router.ts +105 -0
  260. package/packages/piagent-webui/server/session-auth.ts +88 -0
  261. package/packages/piagent-webui/server/sidecar-main.ts +86 -0
  262. package/packages/piagent-webui/server/sse-hub.ts +76 -0
  263. package/packages/piagent-webui/server/static-bundle.ts +40 -0
  264. package/packages/piagent-webui/server/transcript-projection.ts +110 -0
  265. package/schemas/mutation-provenance-record.schema.json +100 -0
  266. package/schemas/piagent-webui/approval-v1.schema.json +654 -0
  267. package/schemas/piagent-webui/attachment-v1.schema.json +267 -0
  268. package/schemas/piagent-webui/capabilities-v1.schema.json +729 -0
  269. package/schemas/piagent-webui/catalog-v1.json +240 -0
  270. package/schemas/piagent-webui/commit-summary-v1.schema.json +63 -0
  271. package/schemas/piagent-webui/common-v1.schema.json +479 -0
  272. package/schemas/piagent-webui/control-command-v1.schema.json +1780 -0
  273. package/schemas/piagent-webui/diff-v1.schema.json +826 -0
  274. package/schemas/piagent-webui/gateway-capabilities-v1.schema.json +136 -0
  275. package/schemas/piagent-webui/gateway-protocol-v1.schema.json +456 -0
  276. package/schemas/piagent-webui/handoff-history-v1.schema.json +92 -0
  277. package/schemas/piagent-webui/model-catalog-v1.schema.json +95 -0
  278. package/schemas/piagent-webui/queue-v1.schema.json +99 -0
  279. package/schemas/piagent-webui/recovery-history-v1.schema.json +144 -0
  280. package/schemas/piagent-webui/release-monitor-v1.schema.json +173 -0
  281. package/schemas/piagent-webui/review-state-v1.schema.json +206 -0
  282. package/schemas/piagent-webui/runtime-event-v2.schema.json +5206 -0
  283. package/schemas/piagent-webui/session-catalog-v1.schema.json +222 -0
  284. package/schemas/piagent-webui/session-command-v1.schema.json +390 -0
  285. package/schemas/piagent-webui/snapshot-v1.schema.json +2622 -0
  286. package/schemas/piagent-webui/source-change-v1.schema.json +763 -0
  287. package/schemas/piagent-webui/source-mutation-v1.schema.json +96 -0
  288. package/schemas/piagent-webui/source-revert-v1.schema.json +130 -0
  289. package/schemas/piagent-webui/subagent-tree-v1.schema.json +88 -0
  290. package/schemas/piagent-webui/task-index-v1.schema.json +74 -0
  291. package/schemas/piagent-webui/task-timeline-v1.schema.json +49 -0
  292. package/schemas/piagent-webui/transcript-v1.schema.json +243 -0
  293. package/schemas/task-baseline-manifest.schema.json +122 -0
  294. package/schemas/verifier-file-snapshot.schema.json +81 -0
  295. package/scripts/check-architecture.mjs +1 -0
  296. package/scripts/check-doc-languages.mjs +19 -2
  297. package/scripts/check-third-party-neutrality.mjs +43 -0
  298. package/scripts/install-global.sh +1 -1
  299. package/scripts/piagent-cli.mjs +17 -3
  300. package/scripts/piagent-dashboard.mjs +208 -0
  301. package/scripts/piagent-webui-launcher.mjs +121 -0
  302. package/scripts/typescript-loader.mjs +26 -1
  303. package/scripts/verify-local.sh +253 -0
  304. package/scripts/verify-release-identity.mjs +4 -1
@@ -0,0 +1,128 @@
1
+ import { createHmac } from "node:crypto";
2
+ import path from "node:path";
3
+
4
+ import { redactSensitiveText } from "../../piagent-core/security/sensitive-data.js";
5
+ import type { Catalog, SessionRow } from "../contracts/generated/session-catalog-v1.ts";
6
+ import type { MetadataSnapshot, SessionMetadata } from "./session-metadata-store.ts";
7
+ import { projectRefForCwd, sessionRefForPath } from "../ownership/session-refs.ts";
8
+
9
+ export { projectRefForCwd, sessionRefForPath } from "../ownership/session-refs.ts";
10
+
11
+ export type PiSessionInfo = {
12
+ path: string;
13
+ id: string;
14
+ cwd: string;
15
+ name?: string;
16
+ created: Date;
17
+ modified: Date;
18
+ messageCount: number;
19
+ firstMessage: string;
20
+ allMessagesText: string;
21
+ };
22
+
23
+ function catalogRef(key: Buffer, namespace: string, value: string): string {
24
+ return `${namespace}_${createHmac("sha256", key).update(value).digest("base64url").slice(0, 43)}`;
25
+ }
26
+
27
+ export type SessionOwnerProjection = Pick<SessionRow, "state" | "liveState" | "composerAvailable" | "needsAttention" | "owner" | "reasonCode">;
28
+ export type SessionOptionProjection = Pick<SessionRow, "modelLabel" | "thinkingLevel">;
29
+
30
+ function display(value: unknown, maximum: number, fallback: string): string {
31
+ const clean = redactSensitiveText(String(value ?? "")).text
32
+ .replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
33
+ return (clean || fallback).slice(0, maximum);
34
+ }
35
+
36
+ function revision(key: Buffer, value: unknown): string {
37
+ return `rev_${createHmac("sha256", key).update(JSON.stringify(value)).digest("hex")}`;
38
+ }
39
+
40
+ function row(key: Buffer, info: PiSessionInfo, metadata: SessionMetadata | undefined, metadataReason: string | null,
41
+ ownership?: SessionOwnerProjection, sessionOptions?: SessionOptionProjection): SessionRow {
42
+ const projectLabel = display(info.cwd ? path.basename(info.cwd) : "", 120, "Unknown project");
43
+ const first = info.firstMessage === "(no messages)" ? "" : info.firstMessage;
44
+ const suppliedName = display(info.name, 500, "").replace(/^pi:\s*/i, "");
45
+ const normalizedName = suppliedName.toLowerCase();
46
+ const genericName = !suppliedName || normalizedName === projectLabel.toLowerCase()
47
+ || ["working", "pi agent platform", "new conversation"].includes(normalizedName);
48
+ const title = display(genericName && first ? first : suppliedName || first, 500, "New conversation").replace(/^pi:\s*/i, "") || "New conversation";
49
+ return {
50
+ sessionRef: sessionRefForPath(key, info.path),
51
+ projectRef: projectRefForCwd(key, info.cwd),
52
+ title,
53
+ projectLabel,
54
+ preview: display(first, 280, "No messages yet"),
55
+ createdAt: info.created.toISOString(),
56
+ updatedAt: info.modified.toISOString(),
57
+ state: metadata?.archived ? "archived" : ownership?.state ?? "offline",
58
+ liveState: metadata?.archived ? "offline" : ownership?.liveState ?? "offline",
59
+ pinned: metadata?.pinned ?? false,
60
+ archived: metadata?.archived ?? false,
61
+ unread: metadata?.unread ?? false,
62
+ composerAvailable: metadata?.archived ? false : ownership?.composerAvailable ?? false,
63
+ needsAttention: metadata?.archived ? false : ownership?.needsAttention ?? false,
64
+ modelLabel: sessionOptions?.modelLabel ?? null,
65
+ thinkingLevel: sessionOptions?.thinkingLevel ?? "unknown",
66
+ contextUsage: { usedTokens: null, contextWindow: null, ratio: null, state: "unknown" },
67
+ task: null,
68
+ owner: metadata?.archived
69
+ ? { kind: "none", ownerEpoch: null, gatewayInstanceRef: null, runtimeInstanceRef: null, continuity: "released" }
70
+ : ownership?.owner ?? { kind: "none", ownerEpoch: null, gatewayInstanceRef: null, runtimeInstanceRef: null, continuity: "unknown" },
71
+ sessionRevision: revision(key, [info.path, info.modified.toISOString(), info.messageCount, info.name ?? null, metadata?.revision ?? null,
72
+ sessionOptions?.modelLabel ?? null, sessionOptions?.thinkingLevel ?? "unknown",
73
+ metadata?.archived ? "archived" : ownership ? [ownership.state, ownership.liveState, ownership.owner.kind,
74
+ ownership.owner.ownerEpoch, ownership.owner.runtimeInstanceRef, ownership.reasonCode] : "offline"]),
75
+ reasonCode: metadata?.archived ? metadataReason : ownership?.reasonCode ?? metadataReason
76
+ };
77
+ }
78
+
79
+ export async function buildSessionCatalog(options: {
80
+ gatewayInstanceRef: string;
81
+ key: Buffer;
82
+ listSessions(): Promise<PiSessionInfo[]>;
83
+ readMetadata?(): MetadataSnapshot;
84
+ readOwnership?(sessionRef: string): SessionOwnerProjection;
85
+ readSessionOptions?(info: PiSessionInfo): SessionOptionProjection;
86
+ limit?: number;
87
+ }): Promise<Catalog> {
88
+ const limit = Math.max(1, Math.min(200, options.limit ?? 200));
89
+ try {
90
+ const found = await options.listSessions();
91
+ const metadata = options.readMetadata?.() ?? { state: "ready", revision: null, sessions: new Map(), reasonCode: null };
92
+ const sessions = found.map((info) => {
93
+ const sessionRef = sessionRefForPath(options.key, info.path);
94
+ return row(options.key, info, metadata.sessions.get(sessionRef), metadata.reasonCode, options.readOwnership?.(sessionRef),
95
+ options.readSessionOptions?.(info));
96
+ }).sort((left, right) => Number(right.pinned) - Number(left.pinned)
97
+ || Date.parse(right.updatedAt) - Date.parse(left.updatedAt)).slice(0, limit);
98
+ return {
99
+ schemaVersion: 1,
100
+ version: "piagent-session-catalog-v1",
101
+ generatedAt: new Date().toISOString(),
102
+ gatewayInstanceRef: options.gatewayInstanceRef,
103
+ state: "ready",
104
+ catalogRevision: revision(options.key, [metadata.revision, sessions.map((item) => [item.sessionRef, item.sessionRevision])]),
105
+ sessions,
106
+ page: {
107
+ limit,
108
+ returned: sessions.length,
109
+ total: Math.min(1_000_000, found.length),
110
+ nextCursor: found.length > sessions.length ? catalogRef(options.key, "cursor", sessions.at(-1)?.sessionRef ?? "empty") : null,
111
+ truncated: found.length > sessions.length
112
+ },
113
+ reasonCode: null
114
+ };
115
+ } catch {
116
+ return {
117
+ schemaVersion: 1,
118
+ version: "piagent-session-catalog-v1",
119
+ generatedAt: new Date().toISOString(),
120
+ gatewayInstanceRef: options.gatewayInstanceRef,
121
+ state: "unavailable",
122
+ catalogRevision: null,
123
+ sessions: [],
124
+ page: { limit, returned: 0, total: 0, nextCursor: null, truncated: false },
125
+ reasonCode: "catalog-read-failed"
126
+ };
127
+ }
128
+ }
@@ -0,0 +1,237 @@
1
+ import { randomBytes } from "node:crypto";
2
+
3
+ import type { Catalog, SessionRow } from "../contracts/generated/session-catalog-v1.ts";
4
+ import type { Receipt } from "../contracts/generated/session-command-v1.ts";
5
+ import { GatewayEventStore } from "./gateway-events.ts";
6
+ import { SessionCommandStore, type SessionAction, type SessionCommandIdentity } from "./session-command-store.ts";
7
+ import { SessionRuntimeSupervisor } from "./session-runtime-supervisor.ts";
8
+ import { SessionMetadataStore } from "./session-metadata-store.ts";
9
+
10
+ const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;
11
+ const REVISION = /^[A-Za-z0-9][A-Za-z0-9._:~-]{0,159}$/;
12
+ const IDEMPOTENCY = /^[A-Za-z0-9_-]{22,96}$/;
13
+ const ACTIONS: SessionAction[] = ["session.create", "session.send", "session.abort", "session.set-model", "session.set-thinking", "session.set-permission", "session.rename", "session.pin", "session.archive",
14
+ "session.unarchive", "session.fork", "session.acquire", "session.release"];
15
+
16
+ type SessionCommand = SessionCommandIdentity & {
17
+ schemaVersion: 1;
18
+ version: "piagent-session-command-v1";
19
+ messageType: "command";
20
+ expiresAt: string;
21
+ expectedCatalogRevision: string;
22
+ expectedSessionRevision: string | null;
23
+ payload: Record<string, unknown>;
24
+ };
25
+
26
+ function record(value: unknown): value is Record<string, unknown> { return Boolean(value) && typeof value === "object" && !Array.isArray(value); }
27
+ function exactKeys(value: Record<string, unknown>, keys: string[]): boolean {
28
+ const found = Object.keys(value); return found.length === keys.length && found.every((key) => keys.includes(key));
29
+ }
30
+ function exactTimestamp(value: unknown): value is string {
31
+ return typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)
32
+ && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
33
+ }
34
+ function nullableRef(value: unknown): value is string | null { return value === null || typeof value === "string" && REF.test(value); }
35
+
36
+ function validPayload(action: SessionAction, payload: Record<string, unknown>): boolean {
37
+ if (["session.archive", "session.unarchive", "session.acquire", "session.release"].includes(action)) return exactKeys(payload, []);
38
+ if (action === "session.send") return exactKeys(payload, ["delivery", "message", "messageRequestId", "expectedOperationRef"])
39
+ && ["new-operation", "follow-up", "steer"].includes(String(payload.delivery)) && typeof payload.message === "string"
40
+ && payload.message.length >= 1 && payload.message.length <= 32_768 && !payload.message.includes("\0") && REF.test(String(payload.messageRequestId))
41
+ && nullableRef(payload.expectedOperationRef) && (payload.delivery === "new-operation" ? payload.expectedOperationRef === null : payload.expectedOperationRef !== null);
42
+ if (action === "session.abort") return exactKeys(payload, ["operationRef", "clearQueued"])
43
+ && REF.test(String(payload.operationRef)) && typeof payload.clearQueued === "boolean";
44
+ if (action === "session.set-model") return exactKeys(payload, ["modelRef"]) && REF.test(String(payload.modelRef));
45
+ if (action === "session.set-thinking") return exactKeys(payload, ["thinkingLevel"])
46
+ && ["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(String(payload.thinkingLevel));
47
+ if (action === "session.set-permission") return exactKeys(payload, ["permissionMode"])
48
+ && ["read-only", "workspace-write", "trusted-full-access"].includes(String(payload.permissionMode));
49
+ if (action === "session.rename") return exactKeys(payload, ["title"]) && typeof payload.title === "string"
50
+ && payload.title.length >= 1 && payload.title.length <= 500 && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(payload.title);
51
+ if (action === "session.pin") return exactKeys(payload, ["pinned"]) && typeof payload.pinned === "boolean";
52
+ if (action === "session.fork") return exactKeys(payload, ["entryRef", "title"]) && nullableRef(payload.entryRef)
53
+ && (payload.title === null || typeof payload.title === "string" && payload.title.length >= 1 && payload.title.length <= 500
54
+ && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(payload.title));
55
+ return exactKeys(payload, ["projectRef", "placeRef", "modelRef", "thinkingLevel", "message", "messageRequestId"])
56
+ && REF.test(String(payload.projectRef)) && REF.test(String(payload.placeRef)) && nullableRef(payload.modelRef)
57
+ && ["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(String(payload.thinkingLevel))
58
+ && typeof payload.message === "string" && payload.message.length >= 1 && payload.message.length <= 32_768 && !payload.message.includes("\0")
59
+ && REF.test(String(payload.messageRequestId));
60
+ }
61
+
62
+ function parseCommand(value: unknown): SessionCommand | null {
63
+ if (!record(value) || !exactKeys(value, ["schemaVersion", "version", "messageType", "commandId", "idempotencyKey", "action",
64
+ "requestedAt", "expiresAt", "sessionRef", "expectedCatalogRevision", "expectedSessionRevision", "payload"])) return null;
65
+ const action = value.action as SessionAction;
66
+ if (value.schemaVersion !== 1 || value.version !== "piagent-session-command-v1" || value.messageType !== "command"
67
+ || typeof value.commandId !== "string" || !REF.test(value.commandId) || typeof value.idempotencyKey !== "string" || !IDEMPOTENCY.test(value.idempotencyKey)
68
+ || !ACTIONS.includes(action) || !exactTimestamp(value.requestedAt) || !exactTimestamp(value.expiresAt)
69
+ || Date.parse(value.requestedAt) > Date.parse(value.expiresAt) || Date.parse(value.expiresAt) - Date.parse(value.requestedAt) > 300_000
70
+ || !nullableRef(value.sessionRef) || typeof value.expectedCatalogRevision !== "string" || !REVISION.test(value.expectedCatalogRevision)
71
+ || !(value.expectedSessionRevision === null || typeof value.expectedSessionRevision === "string" && REVISION.test(value.expectedSessionRevision))
72
+ || !record(value.payload) || !validPayload(action, value.payload)) return null;
73
+ if (action === "session.create") {
74
+ if (value.sessionRef !== null || value.expectedSessionRevision !== null) return null;
75
+ } else if (value.sessionRef === null || value.expectedSessionRevision === null) return null;
76
+ return value as SessionCommand;
77
+ }
78
+
79
+ function error(code: string, message: string) { return { code, message }; }
80
+
81
+ export class SessionCommandController {
82
+ readonly #catalog: () => Promise<Catalog>;
83
+ readonly #runtimes: SessionRuntimeSupervisor;
84
+ readonly #store: SessionCommandStore;
85
+ readonly #events: GatewayEventStore;
86
+ readonly #metadata: SessionMetadataStore | null;
87
+ readonly #now: () => Date;
88
+ readonly #chains = new Map<string, Promise<unknown>>();
89
+
90
+ constructor(options: { catalog(): Promise<Catalog>; runtimes: SessionRuntimeSupervisor; store: SessionCommandStore; events: GatewayEventStore;
91
+ metadata?: SessionMetadataStore;
92
+ now?: () => Date }) {
93
+ this.#catalog = options.catalog; this.#runtimes = options.runtimes; this.#store = options.store; this.#events = options.events;
94
+ this.#metadata = options.metadata ?? null;
95
+ this.#now = options.now ?? (() => new Date());
96
+ }
97
+
98
+ execute(input: unknown): Promise<Receipt> {
99
+ const command = parseCommand(input);
100
+ if (!command) return Promise.reject(new Error("invalid-session-command"));
101
+ const key = command.sessionRef ?? "session-create";
102
+ const prior = this.#chains.get(key) ?? Promise.resolve();
103
+ const run = prior.then(() => this.#execute(command), () => this.#execute(command));
104
+ const tail = run.catch(() => undefined);
105
+ this.#chains.set(key, tail);
106
+ return run.finally(() => { if (this.#chains.get(key) === tail) this.#chains.delete(key); });
107
+ }
108
+
109
+ async #execute(command: SessionCommand): Promise<Receipt> {
110
+ const current = await this.#readyCatalog(), row = command.sessionRef ? current.sessions.find((item) => item.sessionRef === command.sessionRef) : null;
111
+ const replay = this.#store.lookup(command);
112
+ if (replay.state === "settled") return { ...replay.receipt!, deduplicated: true };
113
+ if (replay.state === "conflict") return this.#rejected(command, current, row, "invalid-command", "idempotency-payload-mismatch");
114
+ if (replay.state === "unavailable") return this.#rejected(command, current, row, "unavailable", "session-command-journal-unavailable");
115
+ if (replay.state === "pending") {
116
+ const uncertain = this.#uncertain(command, current, row, "session-command-effect-unknown");
117
+ try { this.#store.settle(command, uncertain, this.#now()); } catch { /* returning uncertainty is still safer than replay */ }
118
+ return uncertain;
119
+ }
120
+ const now = this.#now().getTime();
121
+ if (Date.parse(command.requestedAt) > now + 30_000) return this.#rejected(command, current, row, "invalid-command", "requested-at-in-future");
122
+ if (now > Date.parse(command.expiresAt)) return this.#rejected(command, current, row, "expired", "session-command-expired");
123
+ const stale = command.expectedCatalogRevision !== current.catalogRevision || (command.action === "session.create"
124
+ ? command.expectedSessionRevision !== null : !row || command.expectedSessionRevision !== row.sessionRevision);
125
+ if (stale) {
126
+ return this.#rejected(command, current, row, "stale-revision", "session-revision-stale");
127
+ }
128
+ if (row?.archived && command.action !== "session.unarchive") return this.#rejected(command, current, row, "unavailable", "session-archived");
129
+ try { this.#store.admit(command, this.#now()); }
130
+ catch { return this.#rejected(command, current, row, "unavailable", "session-command-admission-failed"); }
131
+ let targetSessionRef = command.sessionRef;
132
+ try {
133
+ let resultCode: "acquired" | "released" | "started" | "queued" | "steered" | "aborted" | "model-changed" | "thinking-changed" | "permission-changed"
134
+ | "renamed" | "pinned" | "unpinned" | "archived" | "unarchived" | "forked" | "no-change",
135
+ operationRef: string | null = null;
136
+ if (command.action === "session.create") {
137
+ targetSessionRef = await this.#runtimes.create(String(command.payload.projectRef), String(command.payload.placeRef),
138
+ command.payload.modelRef === null ? null : String(command.payload.modelRef), String(command.payload.thinkingLevel));
139
+ const created = await this.#readyCatalog(), createdRow = created.sessions.find((item) => item.sessionRef === targetSessionRef);
140
+ if (!createdRow) throw new Error("session-catalog-refresh-failed");
141
+ const sent = await this.#runtimes.send(targetSessionRef, { delivery: "new-operation", message: String(command.payload.message),
142
+ expectedOperationRef: null }, createdRow.sessionRevision);
143
+ resultCode = sent.resultCode === "started" ? "started" : sent.resultCode; operationRef = sent.operationRef;
144
+ } else if (command.action === "session.acquire") { await this.#runtimes.acquire(command.sessionRef!); resultCode = "acquired"; }
145
+ else if (command.action === "session.release") { await this.#runtimes.release(command.sessionRef!); resultCode = "released"; }
146
+ else if (command.action === "session.send") {
147
+ await this.#runtimes.acquire(command.sessionRef!);
148
+ const acquired = await this.#readyCatalog(), acquiredRow = acquired.sessions.find((item) => item.sessionRef === command.sessionRef);
149
+ if (!acquiredRow) throw new Error("session-catalog-refresh-failed");
150
+ const sent = await this.#runtimes.send(command.sessionRef!, command.payload as {
151
+ delivery: "new-operation" | "follow-up" | "steer"; message: string; expectedOperationRef: string | null
152
+ }, acquiredRow.sessionRevision);
153
+ resultCode = sent.resultCode; operationRef = sent.operationRef;
154
+ } else if (command.action === "session.abort") {
155
+ operationRef = String(command.payload.operationRef);
156
+ await this.#runtimes.abort(command.sessionRef!, operationRef, command.payload.clearQueued === true);
157
+ resultCode = "aborted";
158
+ } else if (command.action === "session.set-model") {
159
+ resultCode = await this.#runtimes.setModel(command.sessionRef!, String(command.payload.modelRef));
160
+ } else if (command.action === "session.set-thinking") {
161
+ resultCode = await this.#runtimes.setThinking(command.sessionRef!, String(command.payload.thinkingLevel));
162
+ } else if (command.action === "session.set-permission") {
163
+ resultCode = await this.#runtimes.setPermission(command.sessionRef!, String(command.payload.permissionMode) as
164
+ "read-only" | "workspace-write" | "trusted-full-access");
165
+ } else if (command.action === "session.rename") {
166
+ resultCode = await this.#runtimes.rename(command.sessionRef!, String(command.payload.title).trim());
167
+ } else if (command.action === "session.fork") {
168
+ targetSessionRef = await this.#runtimes.fork(command.sessionRef!, command.payload.entryRef === null ? null : String(command.payload.entryRef),
169
+ command.payload.title === null ? null : String(command.payload.title).trim());
170
+ resultCode = "forked";
171
+ } else {
172
+ if (!this.#metadata) throw new Error("session-metadata-unavailable");
173
+ if (command.action === "session.archive") await this.#runtimes.release(command.sessionRef!);
174
+ const snapshot = this.#metadata.read();
175
+ if (snapshot.state !== "ready") throw new Error(snapshot.reasonCode ?? "session-metadata-unavailable");
176
+ const prior = snapshot.sessions.get(command.sessionRef!), expected = prior?.revision ?? null;
177
+ if (command.action === "session.pin") {
178
+ const pinned = command.payload.pinned === true;
179
+ if ((prior?.pinned ?? false) === pinned) resultCode = "no-change";
180
+ else { this.#metadata.update(command.sessionRef!, expected, { pinned }, this.#now()); resultCode = pinned ? "pinned" : "unpinned"; }
181
+ } else if (command.action === "session.archive") {
182
+ if (prior?.archived) resultCode = "no-change";
183
+ else { this.#metadata.update(command.sessionRef!, expected, { archived: true }, this.#now()); resultCode = "archived"; }
184
+ } else {
185
+ if (!prior?.archived) resultCode = "no-change";
186
+ else { this.#metadata.update(command.sessionRef!, expected, { archived: false }, this.#now()); resultCode = "unarchived"; }
187
+ }
188
+ }
189
+ const after = await this.#readyCatalog(), afterRow = after.sessions.find((item) => item.sessionRef === targetSessionRef);
190
+ if (!afterRow) throw new Error("session-catalog-refresh-failed");
191
+ const receipt = this.#settled(command, after, afterRow, resultCode, operationRef);
192
+ try { this.#store.settle(command, receipt, this.#now()); }
193
+ catch { return this.#uncertain(command, after, afterRow, "session-command-settlement-not-durable"); }
194
+ this.#events.publish("session.changed", { catalogRevision: after.catalogRevision, session: afterRow });
195
+ return receipt;
196
+ } catch (cause) {
197
+ const after = await this.#readyCatalog(), afterRow = after.sessions.find((item) => item.sessionRef === targetSessionRef) ?? row;
198
+ const code = cause instanceof Error && /recovery/.test(cause.message) ? "recovery-required"
199
+ : cause instanceof Error && /(owner-conflict|operation-conflict|runtime-busy)/.test(cause.message) ? "owner-conflict" : "effect-unknown";
200
+ const receipt = code === "effect-unknown" ? this.#uncertain(command, after, afterRow, "session-command-effect-unknown")
201
+ : this.#rejected(command, after, afterRow, code, cause instanceof Error ? cause.message : "session-command-failed");
202
+ try { this.#store.settle(command, receipt, this.#now()); } catch { /* intent remains uncertain */ }
203
+ return receipt;
204
+ }
205
+ }
206
+
207
+ async #readyCatalog(): Promise<Catalog> {
208
+ const catalog = await this.#catalog();
209
+ if (catalog.state !== "ready" || !catalog.catalogRevision) throw new Error(catalog.reasonCode ?? "catalog-unavailable");
210
+ return catalog;
211
+ }
212
+
213
+ #base(command: SessionCommand, catalog: Catalog, row: SessionRow | null) {
214
+ return { schemaVersion: 1 as const, version: "piagent-session-receipt-v1" as const, messageType: "receipt" as const,
215
+ commandId: command.commandId, idempotencyKeyDigest: this.#store.idempotencyDigest(command.idempotencyKey), action: command.action,
216
+ requestedAt: command.requestedAt, sessionRef: command.action === "session.create" || command.action === "session.fork"
217
+ ? row?.sessionRef ?? null : command.sessionRef,
218
+ operationRef: null, catalogRevisionAfter: catalog.catalogRevision!,
219
+ sessionRevisionAfter: row?.sessionRevision ?? null, deduplicated: false };
220
+ }
221
+ #settled(command: SessionCommand, catalog: Catalog, row: SessionRow,
222
+ resultCode: "acquired" | "released" | "started" | "queued" | "steered" | "aborted" | "model-changed" | "thinking-changed" | "permission-changed"
223
+ | "renamed" | "pinned" | "unpinned" | "archived" | "unarchived" | "forked" | "no-change",
224
+ operationRef: string | null): Receipt {
225
+ return { ...this.#base(command, catalog, row), operationRef, phase: "settled", resultCode, settledAt: this.#now().toISOString(),
226
+ evidenceRef: `evidence_${randomBytes(24).toString("base64url")}`, error: null };
227
+ }
228
+ #uncertain(command: SessionCommand, catalog: Catalog, row: SessionRow | null, code: string): Receipt {
229
+ return { ...this.#base(command, catalog, row), phase: "uncertain", resultCode: "effect-unknown", settledAt: this.#now().toISOString(),
230
+ evidenceRef: null, error: error(code, "The command effect cannot be proven. It will not be replayed automatically.") };
231
+ }
232
+ #rejected(command: SessionCommand, catalog: Catalog, row: SessionRow | null,
233
+ resultCode: "stale-revision" | "owner-conflict" | "recovery-required" | "invalid-command" | "expired" | "unavailable", code: string): Receipt {
234
+ return { ...this.#base(command, catalog, row), phase: "rejected", resultCode, settledAt: this.#now().toISOString(), evidenceRef: null,
235
+ error: error(code.replace(/[^a-z0-9.-]/g, "-").slice(0, 96) || "session-command-rejected", "The session command was rejected.") };
236
+ }
237
+ }
@@ -0,0 +1,224 @@
1
+ import { createHmac } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ import type { Receipt } from "../contracts/generated/session-command-v1.ts";
6
+
7
+ const FILE_LIMIT = 8 * 1024 * 1024;
8
+ const RECORD_LIMIT = 16 * 1024;
9
+ const ENTRY_LIMIT = 20_000;
10
+ const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;
11
+ const REVISION = /^[A-Za-z0-9][A-Za-z0-9._:~-]{0,159}$/;
12
+ const REASON = /^[a-z0-9][a-z0-9.-]{0,95}$/;
13
+ const DIGEST = /^sha256:[a-f0-9]{64}$/;
14
+ const ACTIONS = ["session.create", "session.send", "session.abort", "session.set-model", "session.set-thinking", "session.set-permission", "session.rename", "session.pin", "session.archive",
15
+ "session.unarchive", "session.fork", "session.acquire", "session.release"] as const;
16
+
17
+ export type SessionAction = typeof ACTIONS[number];
18
+ export type SessionCommandIdentity = { commandId: string; idempotencyKey: string; action: SessionAction; sessionRef: string | null; requestedAt: string };
19
+ type JournalRecord = {
20
+ version: "piagent-session-command-journal-v1";
21
+ sequence: number;
22
+ recordedAt: string;
23
+ recordType: "intent" | "receipt";
24
+ commandId: string;
25
+ idempotencyKeyDigest: string;
26
+ actionDigest: string;
27
+ action: SessionAction;
28
+ sessionRef: string | null;
29
+ requestedAt: string;
30
+ receipt: Receipt | null;
31
+ previousDigest: string | null;
32
+ recordDigest: string;
33
+ };
34
+
35
+ type CommandBinding = { intent: JournalRecord; receipt: Receipt | null };
36
+
37
+ function exactTimestamp(value: unknown): value is string {
38
+ return typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)
39
+ && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
40
+ }
41
+ function exactKeys(value: object, keys: string[]): boolean {
42
+ const found = Object.keys(value);
43
+ return found.length === keys.length && found.every((key) => keys.includes(key));
44
+ }
45
+ function canonical(value: unknown): string {
46
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
47
+ if (value && typeof value === "object") return `{${Object.entries(value as Record<string, unknown>).sort(([left], [right]) => left.localeCompare(right))
48
+ .map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;
49
+ return JSON.stringify(value);
50
+ }
51
+ function unsigned(record: JournalRecord): Omit<JournalRecord, "recordDigest"> {
52
+ const { recordDigest: _ignored, ...value } = record;
53
+ return value;
54
+ }
55
+ function validError(value: unknown): boolean {
56
+ return Boolean(value && typeof value === "object" && !Array.isArray(value)
57
+ && exactKeys(value as object, ["code", "message"]) && REASON.test(String((value as any).code))
58
+ && typeof (value as any).message === "string" && (value as any).message.length >= 1 && (value as any).message.length <= 500
59
+ && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test((value as any).message));
60
+ }
61
+
62
+ export function validSessionReceipt(value: unknown): value is Receipt {
63
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
64
+ const receipt = value as Receipt;
65
+ if (!exactKeys(receipt, ["schemaVersion", "version", "messageType", "commandId", "idempotencyKeyDigest", "action", "phase",
66
+ "resultCode", "requestedAt", "settledAt", "sessionRef", "operationRef", "catalogRevisionAfter", "sessionRevisionAfter",
67
+ "deduplicated", "evidenceRef", "error"]) || receipt.schemaVersion !== 1 || receipt.version !== "piagent-session-receipt-v1"
68
+ || receipt.messageType !== "receipt" || !REF.test(receipt.commandId) || !DIGEST.test(receipt.idempotencyKeyDigest)
69
+ || !ACTIONS.includes(receipt.action) || !exactTimestamp(receipt.requestedAt) || !REVISION.test(receipt.catalogRevisionAfter)
70
+ || !(receipt.sessionRef === null || REF.test(receipt.sessionRef)) || !(receipt.operationRef === null || REF.test(receipt.operationRef))
71
+ || !(receipt.sessionRevisionAfter === null || REVISION.test(receipt.sessionRevisionAfter)) || typeof receipt.deduplicated !== "boolean") return false;
72
+ const settled = exactTimestamp(receipt.settledAt), evidence = typeof receipt.evidenceRef === "string" && REF.test(receipt.evidenceRef);
73
+ if (receipt.phase === "accepted") return receipt.resultCode === "accepted" && receipt.settledAt === null && receipt.evidenceRef === null && receipt.error === null;
74
+ if (receipt.phase === "settled") {
75
+ const results = ["created", "started", "queued", "steered", "aborted", "model-changed", "thinking-changed", "permission-changed", "renamed", "pinned", "unpinned", "archived", "unarchived",
76
+ "forked", "acquired", "released", "no-change"];
77
+ const actionResults: Partial<Record<SessionAction, string[]>> = {
78
+ "session.create": ["created", "started"],
79
+ "session.acquire": ["acquired", "no-change"], "session.release": ["released", "no-change"],
80
+ "session.send": ["started", "queued", "steered"], "session.abort": ["aborted", "no-change"],
81
+ "session.set-model": ["model-changed", "no-change"], "session.set-thinking": ["thinking-changed", "no-change"],
82
+ "session.set-permission": ["permission-changed", "no-change"], "session.rename": ["renamed", "no-change"],
83
+ "session.pin": ["pinned", "unpinned", "no-change"], "session.archive": ["archived", "no-change"],
84
+ "session.unarchive": ["unarchived", "no-change"], "session.fork": ["forked"]
85
+ };
86
+ return settled && evidence && receipt.error === null && results.includes(receipt.resultCode)
87
+ && (!actionResults[receipt.action] || actionResults[receipt.action]!.includes(receipt.resultCode))
88
+ && (receipt.action === "session.create" ? (receipt.resultCode === "started" ? receipt.operationRef !== null : receipt.operationRef === null)
89
+ : ["session.send", "session.abort"].includes(receipt.action) ? receipt.operationRef !== null : receipt.operationRef === null)
90
+ && (receipt.action !== "session.create" || ["created", "started"].includes(receipt.resultCode) && receipt.sessionRef !== null
91
+ && receipt.sessionRevisionAfter !== null)
92
+ && (receipt.action !== "session.fork" || receipt.resultCode === "forked" && receipt.sessionRef !== null
93
+ && receipt.sessionRevisionAfter !== null);
94
+ }
95
+ if (receipt.phase === "uncertain") return settled && receipt.resultCode === "effect-unknown" && validError(receipt.error)
96
+ && (receipt.evidenceRef === null || evidence);
97
+ return receipt.phase === "rejected" && settled && ["stale-revision", "owner-conflict", "recovery-required", "invalid-command", "expired", "unavailable"]
98
+ .includes(receipt.resultCode) && receipt.evidenceRef === null && validError(receipt.error);
99
+ }
100
+
101
+ export class SessionCommandStore {
102
+ readonly directory: string;
103
+ readonly file: string;
104
+ readonly #key: Buffer;
105
+
106
+ constructor(root: string, key: Buffer) {
107
+ this.directory = path.join(root, "commands");
108
+ this.file = path.join(this.directory, "admission.jsonl");
109
+ this.#key = key;
110
+ fs.mkdirSync(this.directory, { recursive: true, mode: 0o700 });
111
+ const stat = fs.lstatSync(this.directory);
112
+ if (!stat.isDirectory() || stat.isSymbolicLink()
113
+ || (typeof process.getuid === "function" && stat.uid !== process.getuid())) throw new Error("session-command-root-invalid");
114
+ fs.chmodSync(this.directory, 0o700);
115
+ }
116
+
117
+ #digest(namespace: string, value: unknown): string {
118
+ return `sha256:${createHmac("sha256", this.#key).update(namespace).update("\0").update(canonical(value)).digest("hex")}`;
119
+ }
120
+ idempotencyDigest(key: string): string { return this.#digest("idempotency", key); }
121
+ actionDigest(command: unknown): string { return this.#digest("action", command); }
122
+
123
+ #valid(record: unknown, index: number, previousDigest: string | null): record is JournalRecord {
124
+ if (!record || typeof record !== "object" || Array.isArray(record)) return false;
125
+ const value = record as JournalRecord;
126
+ if (!exactKeys(value, ["version", "sequence", "recordedAt", "recordType", "commandId", "idempotencyKeyDigest", "actionDigest",
127
+ "action", "sessionRef", "requestedAt", "receipt", "previousDigest", "recordDigest"]) || value.version !== "piagent-session-command-journal-v1"
128
+ || value.sequence !== index + 1 || !exactTimestamp(value.recordedAt) || !["intent", "receipt"].includes(value.recordType)
129
+ || !REF.test(value.commandId) || !DIGEST.test(value.idempotencyKeyDigest) || !DIGEST.test(value.actionDigest)
130
+ || !ACTIONS.includes(value.action) || !(value.sessionRef === null || REF.test(value.sessionRef)) || !exactTimestamp(value.requestedAt)
131
+ || value.previousDigest !== previousDigest || !DIGEST.test(value.recordDigest)) return false;
132
+ if (value.recordType === "intent" ? value.receipt !== null : !validSessionReceipt(value.receipt)) return false;
133
+ const createsSession = value.action === "session.create" || value.action === "session.fork";
134
+ const receiptSessionBound = !value.receipt ? true : !createsSession ? value.receipt.sessionRef === value.sessionRef
135
+ : value.receipt.phase === "settled" ? value.receipt.sessionRef !== null
136
+ : value.receipt.phase === "rejected" ? value.receipt.sessionRef === value.sessionRef : true;
137
+ if (value.receipt && (value.receipt.commandId !== value.commandId || value.receipt.idempotencyKeyDigest !== value.idempotencyKeyDigest
138
+ || value.receipt.action !== value.action || value.receipt.requestedAt !== value.requestedAt || !receiptSessionBound)) return false;
139
+ return value.recordDigest === this.#digest("record", unsigned(value));
140
+ }
141
+
142
+ #read(): JournalRecord[] {
143
+ let stat: fs.Stats;
144
+ try { stat = fs.lstatSync(this.file); } catch (error) {
145
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return [];
146
+ throw error;
147
+ }
148
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > FILE_LIMIT) throw new Error("session-command-file-invalid");
149
+ const descriptor = fs.openSync(this.file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
150
+ try {
151
+ const opened = fs.fstatSync(descriptor);
152
+ if (opened.dev !== stat.dev || opened.ino !== stat.ino || opened.size !== stat.size) throw new Error("session-command-file-race");
153
+ const lines = fs.readFileSync(descriptor, "utf8").split("\n"); if (lines.at(-1) === "") lines.pop();
154
+ if (lines.length > ENTRY_LIMIT) throw new Error("session-command-entry-limit");
155
+ const records: JournalRecord[] = [];
156
+ for (const [index, line] of lines.entries()) {
157
+ if (!line || Buffer.byteLength(line) > RECORD_LIMIT) throw new Error("session-command-record-limit");
158
+ let value: unknown; try { value = JSON.parse(line); } catch { throw new Error("session-command-record-invalid"); }
159
+ if (!this.#valid(value, index, records.at(-1)?.recordDigest ?? null)) throw new Error("session-command-record-invalid");
160
+ records.push(value);
161
+ }
162
+ const byCommand = new Map<string, JournalRecord>(), byKey = new Map<string, JournalRecord>(), settled = new Set<string>();
163
+ for (const record of records) {
164
+ if (record.recordType === "intent") {
165
+ if (byCommand.has(record.commandId) || byKey.has(record.idempotencyKeyDigest)) throw new Error("session-command-binding-duplicate");
166
+ byCommand.set(record.commandId, record); byKey.set(record.idempotencyKeyDigest, record);
167
+ } else {
168
+ const intent = byCommand.get(record.commandId);
169
+ if (!intent || intent.idempotencyKeyDigest !== record.idempotencyKeyDigest || intent.actionDigest !== record.actionDigest
170
+ || settled.has(record.commandId)) {
171
+ throw new Error("session-command-chain-invalid");
172
+ }
173
+ settled.add(record.commandId);
174
+ }
175
+ }
176
+ return records;
177
+ } finally { fs.closeSync(descriptor); }
178
+ }
179
+
180
+ #append(value: Omit<JournalRecord, "version" | "sequence" | "recordedAt" | "previousDigest" | "recordDigest">, now = new Date()): JournalRecord {
181
+ if (!Number.isFinite(now.getTime())) throw new Error("session-command-time-invalid");
182
+ const records = this.#read(); if (records.length >= ENTRY_LIMIT) throw new Error("session-command-entry-limit");
183
+ const partial = { version: "piagent-session-command-journal-v1" as const, sequence: records.length + 1, recordedAt: now.toISOString(),
184
+ previousDigest: records.at(-1)?.recordDigest ?? null, ...value };
185
+ const record: JournalRecord = { ...partial, recordDigest: this.#digest("record", partial) };
186
+ const body = Buffer.from(`${JSON.stringify(record)}\n`); if (body.length > RECORD_LIMIT) throw new Error("session-command-record-limit");
187
+ let stat: fs.Stats | null = null; try { stat = fs.lstatSync(this.file); } catch { /* first record */ }
188
+ if (stat && (!stat.isFile() || stat.isSymbolicLink() || stat.size + body.length > FILE_LIMIT)) throw new Error("session-command-file-invalid");
189
+ const descriptor = fs.openSync(this.file, fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT
190
+ | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
191
+ try { fs.writeFileSync(descriptor, body); fs.fsyncSync(descriptor); } finally { fs.closeSync(descriptor); }
192
+ fs.chmodSync(this.file, 0o600); return record;
193
+ }
194
+
195
+ lookup(command: SessionCommandIdentity): { state: "none" | "pending" | "settled" | "conflict" | "unavailable"; receipt?: Receipt } {
196
+ try {
197
+ const records = this.#read(), keyDigest = this.idempotencyDigest(command.idempotencyKey), actionDigest = this.actionDigest(command);
198
+ const intent = records.find((record) => record.recordType === "intent"
199
+ && (record.commandId === command.commandId || record.idempotencyKeyDigest === keyDigest));
200
+ if (!intent) return { state: "none" };
201
+ if (intent.commandId !== command.commandId || intent.idempotencyKeyDigest !== keyDigest || intent.actionDigest !== actionDigest) return { state: "conflict" };
202
+ const receipt = records.find((record) => record.recordType === "receipt" && record.commandId === command.commandId)?.receipt ?? null;
203
+ return receipt ? { state: "settled", receipt: structuredClone(receipt) } : { state: "pending" };
204
+ } catch { return { state: "unavailable" }; }
205
+ }
206
+
207
+ admit(command: SessionCommandIdentity, now = new Date()): { idempotencyKeyDigest: string; actionDigest: string } {
208
+ const existing = this.lookup(command);
209
+ if (existing.state !== "none") throw new Error(`session-command-${existing.state}`);
210
+ const idempotencyKeyDigest = this.idempotencyDigest(command.idempotencyKey), actionDigest = this.actionDigest(command);
211
+ this.#append({ recordType: "intent", commandId: command.commandId, idempotencyKeyDigest, actionDigest, action: command.action,
212
+ sessionRef: command.sessionRef, requestedAt: command.requestedAt, receipt: null }, now);
213
+ return { idempotencyKeyDigest, actionDigest };
214
+ }
215
+
216
+ settle(command: SessionCommandIdentity, receipt: Receipt, now = new Date()): void {
217
+ if (!validSessionReceipt(receipt)) throw new Error("session-command-receipt-invalid");
218
+ const existing = this.lookup(command);
219
+ if (existing.state !== "pending") throw new Error(`session-command-${existing.state}`);
220
+ this.#append({ recordType: "receipt", commandId: command.commandId, idempotencyKeyDigest: this.idempotencyDigest(command.idempotencyKey),
221
+ actionDigest: this.actionDigest(command), action: command.action, sessionRef: command.sessionRef, requestedAt: command.requestedAt,
222
+ receipt: structuredClone(receipt) }, now);
223
+ }
224
+ }