@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,204 @@
1
+ import { createHash } from "node:crypto";
2
+ import path from "node:path";
3
+
4
+ import { readContextTelemetry } from "../../piagent-core/extensions/context-engine.js";
5
+ import { activeSessionTask } from "../../piagent-core/extensions/task-state.js";
6
+ import { runtimeConnectionDefinitions, runtimeProtectedPaths } from "../../piagent-core/runtime/inspection/project-runtime-inspection.ts";
7
+ import { setRuntimeMcpEnabled } from "../../piagent-core/runtime/inspection/mcp-control.ts";
8
+ import { webUiModelRef } from "../../piagent-core/runtime/inspection/webui-snapshot.ts";
9
+ import { redactSensitiveText } from "../../piagent-core/security/sensitive-data.js";
10
+ import { piApprovalBroker } from "../../piagent-core/runtime/inspection/approval-broker.ts";
11
+ import { CoreInspectionProvider } from "../server/core-inspection-provider.ts";
12
+ import { ReadModelNotFound, type WebUiReadModelProvider } from "../server/read-model-provider.ts";
13
+ import { projectRefForCwd, sessionRefForPath, type PiSessionInfo } from "./session-catalog.ts";
14
+ import { nativeProjectPickerAvailable } from "./native-project-picker.ts";
15
+ import type { McpAuthBroker } from "./mcp-auth-broker.ts";
16
+
17
+ type PiHost = {
18
+ SessionManager: {
19
+ listAll(): Promise<PiSessionInfo[]>;
20
+ open(file: string): {
21
+ getBranch(): unknown[];
22
+ buildSessionContext(): { model: { provider: string; modelId: string } | null; thinkingLevel: string };
23
+ };
24
+ };
25
+ };
26
+
27
+ type ModelRuntime = {
28
+ getModel(provider: string, modelId: string): Record<string, unknown> | undefined;
29
+ getAvailableSnapshot(): readonly Record<string, unknown>[];
30
+ };
31
+
32
+ type ProjectSource = { list(): Array<{ projectRef: string; placeRef: string; label: string }> };
33
+
34
+ const CACHE_LIMIT = 32;
35
+ const PUBLIC_MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/;
36
+ const EMPTY_REPLAY = {
37
+ state: "current" as const,
38
+ events: [],
39
+ nextCursor: "inspection-start",
40
+ latestCursor: "inspection-start",
41
+ reasonCode: null
42
+ };
43
+
44
+ function inspectionRuntimeRef(gatewayInstanceRef: string, sessionRef: string): string {
45
+ return `runtime.${createHash("sha256").update(`${gatewayInstanceRef}\0${sessionRef}`).digest("hex")}`;
46
+ }
47
+
48
+ function safeRead<T>(read: () => T, fallback: T): T {
49
+ try { return read(); } catch { return fallback; }
50
+ }
51
+
52
+ function safeName(value: unknown): string {
53
+ return redactSensitiveText(String(value ?? "")).text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 120)
54
+ || "Unnamed connection";
55
+ }
56
+
57
+ function safeModelId(value: unknown): string | null {
58
+ if (typeof value !== "string" || !PUBLIC_MODEL_ID.test(value)) return null;
59
+ return redactSensitiveText(value).redacted ? null : value;
60
+ }
61
+
62
+ export class SessionInspectionRegistry {
63
+ readonly #gatewayInstanceRef: string;
64
+ readonly #host: PiHost;
65
+ readonly #key: Buffer;
66
+ readonly #packageRoot: string;
67
+ readonly #models?: ModelRuntime;
68
+ readonly #projects?: ProjectSource;
69
+ readonly #mcpAuth?: McpAuthBroker;
70
+ readonly #providers = new Map<string, { modifiedAt: string; provider: CoreInspectionProvider }>();
71
+
72
+ constructor(options: { gatewayInstanceRef: string; host: PiHost; key: Buffer; packageRoot: string; models?: ModelRuntime; projects?: ProjectSource;
73
+ mcpAuth?: McpAuthBroker }) {
74
+ this.#gatewayInstanceRef = options.gatewayInstanceRef;
75
+ this.#host = options.host;
76
+ this.#key = options.key;
77
+ this.#packageRoot = options.packageRoot;
78
+ this.#models = options.models;
79
+ this.#projects = options.projects;
80
+ this.#mcpAuth = options.mcpAuth;
81
+ }
82
+
83
+ #connectionRef(server: { scope: string; origin: string; name: string }): string {
84
+ return `mcp.${createHash("sha256").update(`${server.scope}\0${server.origin}\0${server.name}`).digest("hex")}`;
85
+ }
86
+
87
+ async #sessionInfo(sessionRef: string): Promise<PiSessionInfo> {
88
+ const sessions = await this.#host.SessionManager.listAll();
89
+ const found = sessions.filter((candidate) => sessionRefForPath(this.#key, candidate.path) === sessionRef);
90
+ if (found.length !== 1) throw new ReadModelNotFound();
91
+ return found[0]!;
92
+ }
93
+
94
+ async connections(sessionRef: string): Promise<unknown> {
95
+ const info = await this.#sessionInfo(sessionRef);
96
+ const definitions = safeRead(() => runtimeConnectionDefinitions(info.cwd), { servers: [], unreadableLayerCount: 1 });
97
+ const servers = await Promise.all(definitions.servers.slice(0, 100).map(async (server) => {
98
+ const auth = await this.#mcpAuth?.describe(info.cwd, server.name) ?? { oauthSupported: false as const, authState: "unavailable" as const };
99
+ return { connectionRef: this.#connectionRef(server), name: safeName(server.name), kind: "mcp" as const, scope: server.scope,
100
+ origin: safeName(server.origin), transport: typeof server.entry.url === "string" ? "http" as const
101
+ : typeof server.entry.command === "string" ? "stdio" as const : "unknown" as const,
102
+ state: server.entry.enabled === false ? "disabled" as const : auth.authState === "connected" ? "connected" as const : "configured" as const,
103
+ requiresApproval: server.requiresApproval, oauthSupported: auth.oauthSupported, authState: auth.authState,
104
+ toggleSupported: !server.origin.startsWith("import:") };
105
+ }));
106
+ return {
107
+ schemaVersion: 1,
108
+ version: "piagent-session-connections-v1",
109
+ generatedAt: new Date().toISOString(),
110
+ sessionRef,
111
+ state: definitions.unreadableLayerCount ? "degraded" : "ready",
112
+ summary: { configured: servers.length, connected: null, approvalRequired: servers.filter((server) => server.requiresApproval).length },
113
+ connections: servers,
114
+ truncated: servers.length >= 100,
115
+ reasonCode: definitions.unreadableLayerCount ? "one-or-more-connection-layers-unreadable" : null
116
+ };
117
+ }
118
+
119
+ async executeConnectionCommand(input: unknown): Promise<unknown> {
120
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("mcp-command-invalid");
121
+ const command = input as Record<string, unknown>, keys = Object.keys(command);
122
+ if (!keys.every((key) => ["action", "sessionRef", "connectionRef"].includes(key)) || keys.length !== 3
123
+ || !["mcp.enable", "mcp.disable", "mcp.oauth"].includes(String(command.action))
124
+ || typeof command.sessionRef !== "string" || typeof command.connectionRef !== "string") throw new Error("mcp-command-invalid");
125
+ const info = await this.#sessionInfo(command.sessionRef), definitions = safeRead(() => runtimeConnectionDefinitions(info.cwd), { servers: [], unreadableLayerCount: 1 });
126
+ const matches = definitions.servers.filter((server) => this.#connectionRef(server) === command.connectionRef);
127
+ if (matches.length !== 1) throw new Error("mcp-connection-not-found");
128
+ const server = matches[0]!;
129
+ if (command.action === "mcp.oauth") {
130
+ if (!this.#mcpAuth) throw new Error("mcp-oauth-unavailable");
131
+ return await this.#mcpAuth.start({ sessionRef: command.sessionRef, connectionRef: command.connectionRef, cwd: info.cwd, name: server.name });
132
+ }
133
+ setRuntimeMcpEnabled({ projectPath: info.cwd, name: server.name, scope: server.scope, enabled: command.action === "mcp.enable" });
134
+ return await this.connections(command.sessionRef);
135
+ }
136
+
137
+ async creationOptions(): Promise<unknown> {
138
+ const sessions = await this.#host.SessionManager.listAll();
139
+ const projects = new Map<string, { projectRef: string; placeRef: string; label: string }>();
140
+ for (const info of sessions) {
141
+ if (!info.cwd) continue;
142
+ const projectRef = projectRefForCwd(this.#key, info.cwd);
143
+ if (!projects.has(projectRef)) projects.set(projectRef, { projectRef, placeRef: projectRef,
144
+ label: safeName(path.basename(info.cwd) || "Project") });
145
+ }
146
+ for (const project of safeRead(() => this.#projects?.list() ?? [], [])) {
147
+ if (!projects.has(project.projectRef)) projects.set(project.projectRef, project);
148
+ }
149
+ const models = (this.#models?.getAvailableSnapshot() ?? []).slice(0, 300).flatMap((value) => {
150
+ const provider = safeModelId(value.provider);
151
+ const modelId = safeModelId(value.id);
152
+ if (!provider || !modelId || typeof value.reasoning !== "boolean") return [];
153
+ const mapping = value.thinkingLevelMap && typeof value.thinkingLevelMap === "object"
154
+ ? value.thinkingLevelMap as Record<string, unknown> : {};
155
+ const thinkingLevels = value.reasoning ? ["off", "minimal", "low", "medium", "high", "xhigh", "max"]
156
+ .filter((level) => mapping[level] !== null && !(["xhigh", "max"].includes(level) && mapping[level] === undefined)) : ["off"];
157
+ return [{ modelRef: webUiModelRef(provider, modelId), provider, modelId, displayName: safeName(value.name ?? modelId),
158
+ reasoning: value.reasoning, thinkingLevels }];
159
+ });
160
+ return { schemaVersion: 1, version: "piagent-session-creation-options-v1", generatedAt: new Date().toISOString(),
161
+ projects: [...projects.values()].slice(0, 200), models,
162
+ projectImport: nativeProjectPickerAvailable() ? { status: "available", reasonCode: null }
163
+ : { status: "unavailable", reasonCode: "native-project-picker-unavailable" },
164
+ reasonCode: projects.size ? null : "no-known-project" };
165
+ }
166
+
167
+ async provider(sessionRef: string): Promise<WebUiReadModelProvider> {
168
+ const info = await this.#sessionInfo(sessionRef);
169
+ const modifiedAt = info.modified.toISOString();
170
+ const cached = this.#providers.get(sessionRef);
171
+ if (cached?.modifiedAt === modifiedAt) return cached.provider;
172
+
173
+ let manager: ReturnType<PiHost["SessionManager"]["open"]>;
174
+ try { manager = this.#host.SessionManager.open(info.path); }
175
+ catch { throw new ReadModelNotFound(); }
176
+ const context = safeRead(() => manager.buildSessionContext(), { model: null, thinkingLevel: "unknown" });
177
+ const model = context.model ? this.#models?.getModel(context.model.provider, context.model.modelId) : undefined;
178
+ const entries = safeRead(() => manager.getBranch(), []);
179
+ const eventStore = {
180
+ retention: () => ({ eventRetentionCount: 0, eventRetentionSeconds: 0 }),
181
+ currentCursor: () => null,
182
+ resyncRequired: () => false,
183
+ replay: () => EMPTY_REPLAY
184
+ };
185
+ const provider = new CoreInspectionProvider({
186
+ cwd: info.cwd,
187
+ sessionId: info.id,
188
+ runtimeInstanceId: inspectionRuntimeRef(this.#gatewayInstanceRef, sessionRef),
189
+ eventStore,
190
+ task: () => safeRead(() => activeSessionTask(info.cwd, info.id), undefined),
191
+ activityEvents: () => safeRead(() => readContextTelemetry(info.cwd, { limit: 5_000 }), []),
192
+ sessionEntries: () => entries,
193
+ protectedPaths: () => runtimeProtectedPaths(this.#packageRoot, info.cwd),
194
+ model: () => model,
195
+ thinkingLevel: () => context.thinkingLevel,
196
+ approvalProjection: () => piApprovalBroker.projection(info.cwd, info.id),
197
+ approvalDetail: (approvalRef) => piApprovalBroker.detail(info.cwd, info.id, approvalRef)
198
+ });
199
+ this.#providers.delete(sessionRef);
200
+ this.#providers.set(sessionRef, { modifiedAt, provider });
201
+ while (this.#providers.size > CACHE_LIMIT) this.#providers.delete(this.#providers.keys().next().value as string);
202
+ return provider;
203
+ }
204
+ }
@@ -0,0 +1 @@
1
+ export * from "../ownership/session-lease-store.ts";
@@ -0,0 +1,152 @@
1
+ import { createHmac } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ import { redactSensitiveText } from "../../piagent-core/security/sensitive-data.js";
6
+
7
+ const FILE_LIMIT = 4 * 1024 * 1024;
8
+ const RECORD_LIMIT = 8 * 1024;
9
+ const ENTRY_LIMIT = 10_000;
10
+ const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;
11
+
12
+ export type SessionMetadata = {
13
+ pinned: boolean;
14
+ archived: boolean;
15
+ unread: boolean;
16
+ projectGroup: string | null;
17
+ revision: string;
18
+ };
19
+
20
+ type MetadataRecord = {
21
+ version: "piagent-session-metadata-v1";
22
+ sequence: number;
23
+ recordedAt: string;
24
+ sessionRef: string;
25
+ previousRevision: string | null;
26
+ pinned: boolean;
27
+ archived: boolean;
28
+ unread: boolean;
29
+ projectGroup: string | null;
30
+ };
31
+
32
+ export type MetadataSnapshot = {
33
+ state: "ready" | "unavailable";
34
+ revision: string | null;
35
+ sessions: ReadonlyMap<string, SessionMetadata>;
36
+ reasonCode: string | null;
37
+ };
38
+
39
+ function digest(key: Buffer, namespace: string, value: unknown): string {
40
+ return `${namespace}_${createHmac("sha256", key).update(JSON.stringify(value)).digest("hex")}`;
41
+ }
42
+
43
+ function exactTimestamp(value: unknown): value is string {
44
+ return typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)
45
+ && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
46
+ }
47
+
48
+ function safeGroup(value: unknown): string | null {
49
+ if (value === null || value === undefined) return null;
50
+ if (typeof value !== "string") throw new Error("session-metadata-group-invalid");
51
+ const text = redactSensitiveText(value).text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
52
+ if (!text || text.length > 120) throw new Error("session-metadata-group-invalid");
53
+ return text;
54
+ }
55
+
56
+ function validRecord(value: unknown): value is MetadataRecord {
57
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
58
+ const record = value as Partial<MetadataRecord>;
59
+ return Object.keys(record).every((key) => ["version", "sequence", "recordedAt", "sessionRef", "previousRevision",
60
+ "pinned", "archived", "unread", "projectGroup"].includes(key))
61
+ && record.version === "piagent-session-metadata-v1"
62
+ && Number.isSafeInteger(record.sequence) && Number(record.sequence) > 0
63
+ && exactTimestamp(record.recordedAt) && typeof record.sessionRef === "string" && REF.test(record.sessionRef)
64
+ && (record.previousRevision === null || typeof record.previousRevision === "string" && REF.test(record.previousRevision))
65
+ && typeof record.pinned === "boolean" && typeof record.archived === "boolean" && typeof record.unread === "boolean"
66
+ && (record.projectGroup === null || typeof record.projectGroup === "string" && record.projectGroup.length > 0
67
+ && record.projectGroup.length <= 120 && !/[\u0000-\u001f\u007f]/.test(record.projectGroup));
68
+ }
69
+
70
+ export class SessionMetadataStore {
71
+ readonly directory: string;
72
+ readonly file: string;
73
+ readonly #key: Buffer;
74
+
75
+ constructor(root: string, key: Buffer) {
76
+ this.directory = path.join(root, "sessions");
77
+ this.file = path.join(this.directory, "index.jsonl");
78
+ this.#key = key;
79
+ fs.mkdirSync(this.directory, { recursive: true, mode: 0o700 });
80
+ const stat = fs.lstatSync(this.directory);
81
+ if (!stat.isDirectory() || stat.isSymbolicLink()
82
+ || (typeof process.getuid === "function" && stat.uid !== process.getuid())) throw new Error("session-metadata-root-invalid");
83
+ fs.chmodSync(this.directory, 0o700);
84
+ }
85
+
86
+ #readRecords(): MetadataRecord[] {
87
+ let stat: fs.Stats;
88
+ try { stat = fs.lstatSync(this.file); }
89
+ catch { return []; }
90
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > FILE_LIMIT) throw new Error("session-metadata-file-invalid");
91
+ const descriptor = fs.openSync(this.file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
92
+ try {
93
+ const opened = fs.fstatSync(descriptor);
94
+ if (opened.dev !== stat.dev || opened.ino !== stat.ino || opened.size !== stat.size) throw new Error("session-metadata-file-race");
95
+ const text = fs.readFileSync(descriptor, "utf8");
96
+ const lines = text ? text.split("\n") : [];
97
+ if (lines.at(-1) === "") lines.pop();
98
+ if (lines.length > ENTRY_LIMIT) throw new Error("session-metadata-entry-limit");
99
+ return lines.map((line, index) => {
100
+ if (!line || Buffer.byteLength(line) > RECORD_LIMIT) throw new Error("session-metadata-record-limit");
101
+ let value: unknown;
102
+ try { value = JSON.parse(line); } catch { throw new Error("session-metadata-record-invalid"); }
103
+ if (!validRecord(value) || value.sequence !== index + 1) throw new Error("session-metadata-record-invalid");
104
+ return value;
105
+ });
106
+ } finally { fs.closeSync(descriptor); }
107
+ }
108
+
109
+ read(): MetadataSnapshot {
110
+ try {
111
+ const records = this.#readRecords();
112
+ const sessions = new Map<string, SessionMetadata>();
113
+ for (const record of records) {
114
+ const prior = sessions.get(record.sessionRef);
115
+ if (record.previousRevision !== (prior?.revision ?? null)) throw new Error("session-metadata-chain-invalid");
116
+ sessions.set(record.sessionRef, {
117
+ pinned: record.pinned, archived: record.archived, unread: record.unread, projectGroup: record.projectGroup,
118
+ revision: digest(this.#key, "metadata-revision", record)
119
+ });
120
+ }
121
+ return { state: "ready", revision: digest(this.#key, "metadata-store", records), sessions, reasonCode: null };
122
+ } catch {
123
+ return { state: "unavailable", revision: null, sessions: new Map(), reasonCode: "metadata-overlay-unavailable" };
124
+ }
125
+ }
126
+
127
+ update(sessionRef: string, expectedRevision: string | null, patch: Partial<Pick<SessionMetadata, "pinned" | "archived" | "unread" | "projectGroup">>, now = new Date()): SessionMetadata {
128
+ if (!REF.test(sessionRef)) throw new Error("session-metadata-ref-invalid");
129
+ const snapshot = this.read();
130
+ if (snapshot.state !== "ready") throw new Error(snapshot.reasonCode ?? "session-metadata-unavailable");
131
+ const current = snapshot.sessions.get(sessionRef);
132
+ if ((current?.revision ?? null) !== expectedRevision) throw new Error("session-metadata-stale-revision");
133
+ if (!Number.isFinite(now.getTime())) throw new Error("session-metadata-time-invalid");
134
+ const record: MetadataRecord = {
135
+ version: "piagent-session-metadata-v1", sequence: this.#readRecords().length + 1, recordedAt: now.toISOString(), sessionRef,
136
+ previousRevision: current?.revision ?? null, pinned: patch.pinned ?? current?.pinned ?? false,
137
+ archived: patch.archived ?? current?.archived ?? false, unread: patch.unread ?? current?.unread ?? false,
138
+ projectGroup: "projectGroup" in patch ? safeGroup(patch.projectGroup) : current?.projectGroup ?? null
139
+ };
140
+ const body = Buffer.from(`${JSON.stringify(record)}\n`);
141
+ if (body.length > RECORD_LIMIT) throw new Error("session-metadata-record-limit");
142
+ let stat: fs.Stats | null = null;
143
+ try { stat = fs.lstatSync(this.file); } catch { /* first record */ }
144
+ if (stat && (!stat.isFile() || stat.isSymbolicLink() || stat.size + body.length > FILE_LIMIT)) throw new Error("session-metadata-file-invalid");
145
+ const descriptor = fs.openSync(this.file, fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT
146
+ | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
147
+ try { fs.writeFileSync(descriptor, body); fs.fsyncSync(descriptor); }
148
+ finally { fs.closeSync(descriptor); }
149
+ fs.chmodSync(this.file, 0o600);
150
+ return this.read().sessions.get(sessionRef)!;
151
+ }
152
+ }