@piagent/platform 1.3.1 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (329) hide show
  1. package/CHANGELOG.md +132 -0
  2. package/README.md +10 -4
  3. package/README.vi.md +27 -0
  4. package/architecture/layers.json +96 -1
  5. package/docs/README.md +1 -0
  6. package/docs/architecture.md +1 -0
  7. package/docs/authority-manifest.md +1 -0
  8. package/docs/auto-delegation-policy.md +1 -0
  9. package/docs/capability-packs.md +1 -0
  10. package/docs/command-reference-vietnamese.md +5 -4
  11. package/docs/context-engine.md +1 -0
  12. package/docs/context-window-policy.md +1 -0
  13. package/docs/distribution-standard.md +8 -7
  14. package/docs/en/architecture.md +13 -0
  15. package/docs/herdr-workflow.md +1 -0
  16. package/docs/languages.json +20 -4
  17. package/docs/mcp-and-tools.md +125 -9
  18. package/docs/memory-policy.md +1 -0
  19. package/docs/model-options.md +1 -0
  20. package/docs/oauth-providers.md +1 -0
  21. package/docs/operator-manual-vietnamese.md +15 -12
  22. package/docs/package-architecture-notes.md +1 -0
  23. package/docs/project-adapters.md +1 -0
  24. package/docs/project-onboarding.md +1 -0
  25. package/docs/publishing-for-teams.md +37 -0
  26. package/docs/quality-benchmark.md +1 -0
  27. package/docs/quickstart-vietnamese.md +3 -2
  28. package/docs/release-install-policy.md +22 -8
  29. package/docs/runtime-harness-standard.md +2 -1
  30. package/docs/runtime-policy-design.md +1 -0
  31. package/docs/runtime-quality-baseline.md +1 -0
  32. package/docs/security-redaction-benchmark.md +1 -0
  33. package/docs/security-threat-model.md +2 -1
  34. package/docs/subagent-orchestration-capabilities.md +1 -0
  35. package/docs/subagents-and-multiagent.md +1 -0
  36. package/docs/task-implementation-contract.md +12 -4
  37. package/docs/task-lifecycle-vietnamese.md +1 -0
  38. package/docs/team-onboarding.md +3 -2
  39. package/docs/third-party-neutrality.md +26 -0
  40. package/docs/usage-observability.md +71 -0
  41. package/docs/vercel-docs-site.md +1 -0
  42. package/docs/vi/architecture.md +13 -0
  43. package/docs/workflow-recipes.md +1 -0
  44. package/docs-site/architecture.html +5 -1
  45. package/docs-site/benchmark.html +5 -1
  46. package/docs-site/commands.html +5 -1
  47. package/docs-site/content/en/index.html +49 -0
  48. package/docs-site/content/en/runtime.html +13 -0
  49. package/docs-site/content/index.html +49 -0
  50. package/docs-site/content/runtime.html +28 -0
  51. package/docs-site/context-engine.html +5 -1
  52. package/docs-site/en/architecture.html +5 -1
  53. package/docs-site/en/benchmark.html +5 -1
  54. package/docs-site/en/commands.html +5 -1
  55. package/docs-site/en/context-engine.html +5 -1
  56. package/docs-site/en/index.html +54 -1
  57. package/docs-site/en/mcp-approval.html +5 -1
  58. package/docs-site/en/mcp-auth.html +5 -1
  59. package/docs-site/en/mcp-servers.html +5 -1
  60. package/docs-site/en/mcp.html +5 -1
  61. package/docs-site/en/permissions.html +5 -1
  62. package/docs-site/en/profiles.html +5 -1
  63. package/docs-site/en/quickstart.html +5 -1
  64. package/docs-site/en/runtime.html +18 -1
  65. package/docs-site/en/scope.html +5 -1
  66. package/docs-site/en/security.html +5 -1
  67. package/docs-site/en/team.html +5 -1
  68. package/docs-site/en/whats-new.html +5 -1
  69. package/docs-site/en/workflows.html +5 -1
  70. package/docs-site/index.html +54 -1
  71. package/docs-site/mcp-approval.html +5 -1
  72. package/docs-site/mcp-auth.html +5 -1
  73. package/docs-site/mcp-servers.html +5 -1
  74. package/docs-site/mcp.html +5 -1
  75. package/docs-site/permissions.html +5 -1
  76. package/docs-site/profiles.html +5 -1
  77. package/docs-site/quickstart.html +5 -1
  78. package/docs-site/runtime.html +33 -1
  79. package/docs-site/scope.html +5 -1
  80. package/docs-site/security.html +5 -1
  81. package/docs-site/team.html +5 -1
  82. package/docs-site/whats-new.html +5 -1
  83. package/docs-site/workflows.html +5 -1
  84. package/evals/fixtures/mutation-provenance-record.invalid.json +17 -0
  85. package/evals/fixtures/mutation-provenance-record.valid.json +27 -0
  86. package/evals/fixtures/piagent-webui/approval-v1.invalid.json +54 -0
  87. package/evals/fixtures/piagent-webui/approval-v1.valid.json +58 -0
  88. package/evals/fixtures/piagent-webui/attachment-v1.invalid.json +25 -0
  89. package/evals/fixtures/piagent-webui/attachment-v1.valid.json +25 -0
  90. package/evals/fixtures/piagent-webui/capabilities-v1.invalid.json +51 -0
  91. package/evals/fixtures/piagent-webui/capabilities-v1.valid.json +122 -0
  92. package/evals/fixtures/piagent-webui/commit-summary-v1.invalid.json +10 -0
  93. package/evals/fixtures/piagent-webui/commit-summary-v1.valid.json +25 -0
  94. package/evals/fixtures/piagent-webui/control-command-v1.invalid.json +37 -0
  95. package/evals/fixtures/piagent-webui/control-command-v1.valid.json +35 -0
  96. package/evals/fixtures/piagent-webui/diff-v1.invalid.json +13 -0
  97. package/evals/fixtures/piagent-webui/diff-v1.valid.json +141 -0
  98. package/evals/fixtures/piagent-webui/gateway-capabilities-v1.invalid.json +35 -0
  99. package/evals/fixtures/piagent-webui/gateway-capabilities-v1.valid.json +35 -0
  100. package/evals/fixtures/piagent-webui/gateway-protocol-v1.invalid.json +14 -0
  101. package/evals/fixtures/piagent-webui/gateway-protocol-v1.valid.json +14 -0
  102. package/evals/fixtures/piagent-webui/handoff-history-v1.invalid.json +16 -0
  103. package/evals/fixtures/piagent-webui/handoff-history-v1.valid.json +16 -0
  104. package/evals/fixtures/piagent-webui/model-catalog-v1.invalid.json +31 -0
  105. package/evals/fixtures/piagent-webui/model-catalog-v1.valid.json +43 -0
  106. package/evals/fixtures/piagent-webui/queue-v1.invalid.json +29 -0
  107. package/evals/fixtures/piagent-webui/queue-v1.valid.json +44 -0
  108. package/evals/fixtures/piagent-webui/recovery-history-v1.invalid.json +17 -0
  109. package/evals/fixtures/piagent-webui/recovery-history-v1.valid.json +20 -0
  110. package/evals/fixtures/piagent-webui/release-monitor-v1.invalid.json +12 -0
  111. package/evals/fixtures/piagent-webui/release-monitor-v1.valid.json +29 -0
  112. package/evals/fixtures/piagent-webui/review-state-v1.invalid.json +25 -0
  113. package/evals/fixtures/piagent-webui/review-state-v1.valid.json +38 -0
  114. package/evals/fixtures/piagent-webui/runtime-event-v2.invalid.json +49 -0
  115. package/evals/fixtures/piagent-webui/runtime-event-v2.valid.json +49 -0
  116. package/evals/fixtures/piagent-webui/session-catalog-v1.invalid.json +17 -0
  117. package/evals/fixtures/piagent-webui/session-catalog-v1.valid.json +58 -0
  118. package/evals/fixtures/piagent-webui/session-command-v1.invalid.json +19 -0
  119. package/evals/fixtures/piagent-webui/session-command-v1.valid.json +19 -0
  120. package/evals/fixtures/piagent-webui/snapshot-v1.invalid.json +5 -0
  121. package/evals/fixtures/piagent-webui/snapshot-v1.valid.json +191 -0
  122. package/evals/fixtures/piagent-webui/source-change-v1.invalid.json +57 -0
  123. package/evals/fixtures/piagent-webui/source-change-v1.valid.json +98 -0
  124. package/evals/fixtures/piagent-webui/source-mutation-v1.invalid.json +19 -0
  125. package/evals/fixtures/piagent-webui/source-mutation-v1.valid.json +38 -0
  126. package/evals/fixtures/piagent-webui/source-revert-v1.invalid.json +20 -0
  127. package/evals/fixtures/piagent-webui/source-revert-v1.valid.json +62 -0
  128. package/evals/fixtures/piagent-webui/subagent-tree-v1.invalid.json +26 -0
  129. package/evals/fixtures/piagent-webui/subagent-tree-v1.valid.json +39 -0
  130. package/evals/fixtures/piagent-webui/task-index-v1.invalid.json +15 -0
  131. package/evals/fixtures/piagent-webui/task-index-v1.valid.json +15 -0
  132. package/evals/fixtures/piagent-webui/task-timeline-v1.invalid.json +14 -0
  133. package/evals/fixtures/piagent-webui/task-timeline-v1.valid.json +16 -0
  134. package/evals/fixtures/piagent-webui/transcript-v1.invalid.json +35 -0
  135. package/evals/fixtures/piagent-webui/transcript-v1.valid.json +55 -0
  136. package/evals/fixtures/task-baseline-manifest.invalid.json +16 -0
  137. package/evals/fixtures/task-baseline-manifest.valid.json +41 -0
  138. package/evals/fixtures/verifier-file-snapshot.invalid.json +21 -0
  139. package/evals/fixtures/verifier-file-snapshot.valid.json +21 -0
  140. package/package.json +43 -4
  141. package/packages/piagent-core/README.md +3 -2
  142. package/packages/piagent-core/benchmark/benchmark-candidate.d.ts +1 -0
  143. package/packages/piagent-core/benchmark/benchmark-forensics.d.ts +1 -0
  144. package/packages/piagent-core/benchmark/benchmark-ledger.d.ts +4 -0
  145. package/packages/piagent-core/benchmark/benchmark-record-validation.d.ts +1 -0
  146. package/packages/piagent-core/benchmark/benchmark-runtime.d.ts +1 -0
  147. package/packages/piagent-core/capabilities/capability-core.js +2 -2
  148. package/packages/piagent-core/capabilities/capability-verification-cache.js +17 -7
  149. package/packages/piagent-core/capabilities/runtime-integrity.js +190 -0
  150. package/packages/piagent-core/extensions/piagent-guard.ts +80 -272
  151. package/packages/piagent-core/extensions/redaction-core.d.ts +2 -0
  152. package/packages/piagent-core/extensions/runtime-evidence.js +12 -1
  153. package/packages/piagent-core/extensions/shell-reach.ts +250 -0
  154. package/packages/piagent-core/extensions/task-journal.js +30 -1
  155. package/packages/piagent-core/extensions/task-state.js +33 -36
  156. package/packages/piagent-core/mcp/mcp-command-actions.js +1 -1
  157. package/packages/piagent-core/mcp/mcp-server-catalog.js +139 -9
  158. package/packages/piagent-core/package.json +1 -1
  159. package/packages/piagent-core/runtime/hooks/session-start-hook.ts +2 -2
  160. package/packages/piagent-core/runtime/hooks/tool-call-hook.ts +12 -2
  161. package/packages/piagent-core/runtime/hooks/tool-result-hook.ts +20 -19
  162. package/packages/piagent-core/runtime/hooks/tool-result-metadata.ts +13 -0
  163. package/packages/piagent-core/runtime/input/chat-images.ts +2 -2
  164. package/packages/piagent-core/runtime/inspection/activity-event-adapter.ts +94 -0
  165. package/packages/piagent-core/runtime/inspection/approval-broker.ts +318 -0
  166. package/packages/piagent-core/runtime/inspection/commit-summary-projection.ts +59 -0
  167. package/packages/piagent-core/runtime/inspection/context-telemetry-inspection.ts +37 -0
  168. package/packages/piagent-core/runtime/inspection/criteria-links.ts +295 -0
  169. package/packages/piagent-core/runtime/inspection/diff-projection.ts +499 -0
  170. package/packages/piagent-core/runtime/inspection/git-filter-safety.ts +38 -0
  171. package/packages/piagent-core/runtime/inspection/git-numstat-adapter.ts +71 -0
  172. package/packages/piagent-core/runtime/inspection/git-status-adapter.ts +493 -0
  173. package/packages/piagent-core/runtime/inspection/git-tree-adapter.ts +108 -0
  174. package/packages/piagent-core/runtime/inspection/mcp-control.ts +10 -0
  175. package/packages/piagent-core/runtime/inspection/mutation-provenance-contract.ts +131 -0
  176. package/packages/piagent-core/runtime/inspection/mutation-provenance-recorder.ts +48 -0
  177. package/packages/piagent-core/runtime/inspection/mutation-provenance-store.ts +161 -0
  178. package/packages/piagent-core/runtime/inspection/project-runtime-inspection.ts +36 -0
  179. package/packages/piagent-core/runtime/inspection/review-state-contract.ts +108 -0
  180. package/packages/piagent-core/runtime/inspection/review-state-projection.ts +93 -0
  181. package/packages/piagent-core/runtime/inspection/review-state-store.ts +112 -0
  182. package/packages/piagent-core/runtime/inspection/runtime-event-store.ts +262 -0
  183. package/packages/piagent-core/runtime/inspection/same-process-bridge-proof.ts +103 -0
  184. package/packages/piagent-core/runtime/inspection/source-change-projection.ts +471 -0
  185. package/packages/piagent-core/runtime/inspection/source-evidence-contract.ts +139 -0
  186. package/packages/piagent-core/runtime/inspection/source-evidence-store.ts +315 -0
  187. package/packages/piagent-core/runtime/inspection/source-handoff-store.ts +70 -0
  188. package/packages/piagent-core/runtime/inspection/source-inspection-plan.ts +34 -0
  189. package/packages/piagent-core/runtime/inspection/source-mutation-projection.ts +164 -0
  190. package/packages/piagent-core/runtime/inspection/source-mutation-store.ts +168 -0
  191. package/packages/piagent-core/runtime/inspection/source-open-target.ts +38 -0
  192. package/packages/piagent-core/runtime/inspection/source-revert-projection.ts +147 -0
  193. package/packages/piagent-core/runtime/inspection/task-baseline-start-capture.ts +22 -0
  194. package/packages/piagent-core/runtime/inspection/task-compaction-history.ts +160 -0
  195. package/packages/piagent-core/runtime/inspection/task-control-journal.ts +131 -0
  196. package/packages/piagent-core/runtime/inspection/task-handoff-history.ts +95 -0
  197. package/packages/piagent-core/runtime/inspection/task-provenance-projection.ts +60 -0
  198. package/packages/piagent-core/runtime/inspection/task-recovery-timeline.ts +88 -0
  199. package/packages/piagent-core/runtime/inspection/task-run-index.ts +87 -0
  200. package/packages/piagent-core/runtime/inspection/task-source-projection.ts +401 -0
  201. package/packages/piagent-core/runtime/inspection/task-subagent-tree.ts +101 -0
  202. package/packages/piagent-core/runtime/inspection/text-diff.ts +60 -0
  203. package/packages/piagent-core/runtime/inspection/verifier-snapshot-contract.ts +114 -0
  204. package/packages/piagent-core/runtime/inspection/verifier-snapshot-store.ts +189 -0
  205. package/packages/piagent-core/runtime/inspection/webui-snapshot.ts +320 -0
  206. package/packages/piagent-core/runtime/inspection/workspace-file-reader.ts +132 -0
  207. package/packages/piagent-core/runtime/inspection/workspace-source-projection.ts +96 -0
  208. package/packages/piagent-core/runtime/inspection/zero-turn-conformance.ts +175 -0
  209. package/packages/piagent-core/runtime/orchestration/owned-work-budget.ts +93 -6
  210. package/packages/piagent-core/runtime/policy/block-remedy.ts +139 -0
  211. package/packages/piagent-core/runtime/policy/source-index-transaction.ts +173 -0
  212. package/packages/piagent-core/runtime/policy/source-mutation-guard-binding.ts +42 -0
  213. package/packages/piagent-core/runtime/policy/source-mutation-guard.ts +184 -0
  214. package/packages/piagent-core/runtime/policy/source-worktree-transaction.ts +105 -0
  215. package/packages/piagent-core/runtime/product/activity-inspector-footer.ts +5 -3
  216. package/packages/piagent-core/runtime/product/activity-inspector.ts +85 -343
  217. package/packages/piagent-core/runtime/recovery/resume-state.ts +38 -1
  218. package/packages/piagent-core/runtime/registration/activity-inspector-command.ts +68 -14
  219. package/packages/piagent-core/runtime/registration/task-start-tool.ts +22 -27
  220. package/packages/piagent-core/runtime/session/model-authorship-state.ts +31 -3
  221. package/packages/piagent-core/runtime/session/runtime-state.ts +11 -1
  222. package/packages/piagent-core/runtime/session/token-economics.js +34 -0
  223. package/packages/piagent-core/runtime/tools/phase-tool-runtime.ts +2 -1
  224. package/packages/piagent-core/runtime/workflows/task-intake.ts +5 -0
  225. package/packages/piagent-core/security/sensitive-data.js +7 -0
  226. package/packages/piagent-webui/dist/client/assets/index-DwKCWbwd.css +1 -0
  227. package/packages/piagent-webui/dist/client/assets/index-bu7XpD9Q.js +172 -0
  228. package/packages/piagent-webui/dist/client/index.html +16 -0
  229. package/packages/piagent-webui/extension/attachment-store.ts +323 -0
  230. package/packages/piagent-webui/extension/held-message-queue.ts +311 -0
  231. package/packages/piagent-webui/extension/lifecycle-controller.ts +423 -0
  232. package/packages/piagent-webui/extension/lifecycle-event-adapter.ts +23 -0
  233. package/packages/piagent-webui/extension/piagent-webui.ts +470 -0
  234. package/packages/piagent-webui/extension/review-controller.ts +160 -0
  235. package/packages/piagent-webui/extension/same-session-bridge.ts +500 -0
  236. package/packages/piagent-webui/extension/session-options-controller.ts +281 -0
  237. package/packages/piagent-webui/extension/session-stream-adapter.ts +249 -0
  238. package/packages/piagent-webui/extension/source-mutation-controller.ts +215 -0
  239. package/packages/piagent-webui/extension/source-open-controller.ts +136 -0
  240. package/packages/piagent-webui/extension/source-revert-controller.ts +189 -0
  241. package/packages/piagent-webui/extension/terminal-session-adapter.ts +73 -0
  242. package/packages/piagent-webui/extension/vscode-handoff.ts +51 -0
  243. package/packages/piagent-webui/gateway/control-socket.ts +92 -0
  244. package/packages/piagent-webui/gateway/extension-authority.ts +47 -0
  245. package/packages/piagent-webui/gateway/gateway-events.ts +60 -0
  246. package/packages/piagent-webui/gateway/gateway-protocol-service.ts +64 -0
  247. package/packages/piagent-webui/gateway/gateway-service.ts +215 -0
  248. package/packages/piagent-webui/gateway/gateway-session-stream.ts +110 -0
  249. package/packages/piagent-webui/gateway/mcp-auth-broker.ts +158 -0
  250. package/packages/piagent-webui/gateway/native-project-picker.ts +29 -0
  251. package/packages/piagent-webui/gateway/pi-host.ts +41 -0
  252. package/packages/piagent-webui/gateway/profile-state.ts +1 -0
  253. package/packages/piagent-webui/gateway/project-registry.ts +108 -0
  254. package/packages/piagent-webui/gateway/provider-auth-broker.ts +172 -0
  255. package/packages/piagent-webui/gateway/session-catalog.ts +128 -0
  256. package/packages/piagent-webui/gateway/session-command-controller.ts +237 -0
  257. package/packages/piagent-webui/gateway/session-command-store.ts +224 -0
  258. package/packages/piagent-webui/gateway/session-inspection-registry.ts +239 -0
  259. package/packages/piagent-webui/gateway/session-lease-store.ts +1 -0
  260. package/packages/piagent-webui/gateway/session-metadata-store.ts +152 -0
  261. package/packages/piagent-webui/gateway/session-runtime-supervisor.ts +489 -0
  262. package/packages/piagent-webui/ownership/gateway-runtime-context.ts +8 -0
  263. package/packages/piagent-webui/ownership/profile-state.ts +117 -0
  264. package/packages/piagent-webui/ownership/session-lease-store.ts +329 -0
  265. package/packages/piagent-webui/ownership/session-refs.ts +8 -0
  266. package/packages/piagent-webui/package.json +33 -0
  267. package/packages/piagent-webui/server/README.md +4 -0
  268. package/packages/piagent-webui/server/benchmark-release-monitor.ts +230 -0
  269. package/packages/piagent-webui/server/core-inspection-provider.ts +403 -0
  270. package/packages/piagent-webui/server/gateway-websocket.ts +143 -0
  271. package/packages/piagent-webui/server/http-security.ts +27 -0
  272. package/packages/piagent-webui/server/ipc-read-model-client.ts +89 -0
  273. package/packages/piagent-webui/server/loopback-server.ts +368 -0
  274. package/packages/piagent-webui/server/read-model-provider.ts +37 -0
  275. package/packages/piagent-webui/server/read-only-router.ts +105 -0
  276. package/packages/piagent-webui/server/session-auth.ts +88 -0
  277. package/packages/piagent-webui/server/sidecar-main.ts +86 -0
  278. package/packages/piagent-webui/server/sse-hub.ts +76 -0
  279. package/packages/piagent-webui/server/static-bundle.ts +40 -0
  280. package/packages/piagent-webui/server/transcript-projection.ts +125 -0
  281. package/schemas/mutation-provenance-record.schema.json +100 -0
  282. package/schemas/piagent-webui/approval-v1.schema.json +654 -0
  283. package/schemas/piagent-webui/attachment-v1.schema.json +267 -0
  284. package/schemas/piagent-webui/capabilities-v1.schema.json +729 -0
  285. package/schemas/piagent-webui/catalog-v1.json +240 -0
  286. package/schemas/piagent-webui/commit-summary-v1.schema.json +63 -0
  287. package/schemas/piagent-webui/common-v1.schema.json +479 -0
  288. package/schemas/piagent-webui/control-command-v1.schema.json +1780 -0
  289. package/schemas/piagent-webui/diff-v1.schema.json +826 -0
  290. package/schemas/piagent-webui/gateway-capabilities-v1.schema.json +136 -0
  291. package/schemas/piagent-webui/gateway-protocol-v1.schema.json +456 -0
  292. package/schemas/piagent-webui/handoff-history-v1.schema.json +92 -0
  293. package/schemas/piagent-webui/model-catalog-v1.schema.json +95 -0
  294. package/schemas/piagent-webui/queue-v1.schema.json +99 -0
  295. package/schemas/piagent-webui/recovery-history-v1.schema.json +144 -0
  296. package/schemas/piagent-webui/release-monitor-v1.schema.json +173 -0
  297. package/schemas/piagent-webui/review-state-v1.schema.json +206 -0
  298. package/schemas/piagent-webui/runtime-event-v2.schema.json +5206 -0
  299. package/schemas/piagent-webui/session-catalog-v1.schema.json +222 -0
  300. package/schemas/piagent-webui/session-command-v1.schema.json +390 -0
  301. package/schemas/piagent-webui/snapshot-v1.schema.json +2622 -0
  302. package/schemas/piagent-webui/source-change-v1.schema.json +763 -0
  303. package/schemas/piagent-webui/source-mutation-v1.schema.json +96 -0
  304. package/schemas/piagent-webui/source-revert-v1.schema.json +130 -0
  305. package/schemas/piagent-webui/subagent-tree-v1.schema.json +88 -0
  306. package/schemas/piagent-webui/task-index-v1.schema.json +74 -0
  307. package/schemas/piagent-webui/task-timeline-v1.schema.json +49 -0
  308. package/schemas/piagent-webui/transcript-v1.schema.json +243 -0
  309. package/schemas/task-baseline-manifest.schema.json +122 -0
  310. package/schemas/verifier-file-snapshot.schema.json +81 -0
  311. package/scripts/build-docs-site.mjs +21 -1
  312. package/scripts/check-architecture.mjs +1 -0
  313. package/scripts/check-doc-languages.mjs +19 -2
  314. package/scripts/check-third-party-neutrality.mjs +43 -0
  315. package/scripts/explain-command.mjs +240 -0
  316. package/scripts/install-global.sh +105 -4
  317. package/scripts/mcp-manage.mjs +17 -4
  318. package/scripts/pi-session-stats.sh +10 -2
  319. package/scripts/piagent-cli.mjs +30 -3
  320. package/scripts/piagent-dashboard.mjs +261 -0
  321. package/scripts/piagent-webui-launcher.mjs +121 -0
  322. package/scripts/setup.sh +69 -33
  323. package/scripts/traffic-snapshot.mjs +214 -0
  324. package/scripts/typescript-loader.mjs +42 -1
  325. package/scripts/uninstall-global.sh +53 -2
  326. package/scripts/update-global.mjs +33 -1
  327. package/scripts/verify-local.sh +257 -0
  328. package/scripts/verify-release-identity.mjs +4 -1
  329. package/scripts/verify-translation-pairing.mjs +121 -0
@@ -0,0 +1,16 @@
1
+ <!doctype html>
2
+ <html lang="vi">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <meta name="color-scheme" content="dark" />
7
+ <meta name="csp-nonce" content="__PIAGENT_CSP_NONCE__" />
8
+ <meta name="piagent-webui-mode" content="__PIAGENT_WEBUI_MODE__" />
9
+ <title>Piagent WebUI</title>
10
+ <script type="module" crossorigin src="/assets/index-bu7XpD9Q.js"></script>
11
+ <link rel="stylesheet" crossorigin href="/assets/index-DwKCWbwd.css">
12
+ </head>
13
+ <body>
14
+ <div id="root"></div>
15
+ </body>
16
+ </html>
@@ -0,0 +1,323 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ import { redactSensitiveText } from "../../piagent-core/extensions/redaction-core.js";
7
+ import { supportedChatImageMimeType } from "../../piagent-core/runtime/input/chat-images.ts";
8
+ import type { BridgeIdentity, BridgeSnapshot } from "./same-session-bridge.ts";
9
+
10
+ export const ATTACHMENT_LIMITS = {
11
+ countPerMessage: 4,
12
+ imageBytes: 8 * 1024 * 1024,
13
+ textBytes: 256 * 1024,
14
+ totalBytesPerMessage: 16 * 1024 * 1024,
15
+ runtimeCount: 64,
16
+ runtimeBytes: 64 * 1024 * 1024,
17
+ ttlMs: 10 * 60_000
18
+ } as const;
19
+
20
+ const IMAGE_MIMES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp"]);
21
+ const TEXT_MIMES = new Set(["text/plain", "text/markdown", "application/json"]);
22
+ const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;
23
+ const PUBLIC_REF = /^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/;
24
+ const REVISION = /^[A-Za-z0-9][A-Za-z0-9._:~-]{0,159}$/;
25
+ const IDEMPOTENCY = /^[A-Za-z0-9._~-]{32,128}$/;
26
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
27
+ const OWNED_FILE = /^[a-f0-9]{48}\.bin$/;
28
+
29
+ type StoredAttachment = Attachment & {
30
+ projectRef: string;
31
+ runtimeInstanceId: string;
32
+ sessionRef: string;
33
+ absolutePath: string;
34
+ device: number;
35
+ inode: number;
36
+ };
37
+ type Attachment = { attachmentRef: string; messageRequestId: string; displayName: string; kind: "file" | "image";
38
+ mimeType: string; sizeBytes: number; expiresAt: string };
39
+ type StageCommand = { schemaVersion: 1; version: "piagent-webui-attachment-v1"; messageType: "stage-command"; commandId: string;
40
+ idempotencyKey: string; requestedAt: string; expiresAt: string; identity: BridgeIdentity; expectedRuntimeRevision: string;
41
+ messageRequestId: string; file: { displayName: string; declaredMimeType: string; dataBase64: string } };
42
+ type StageResultCode = "staged" | "invalid-command" | "identity-mismatch" | "stale-revision" | "expired" | "unsupported-type"
43
+ | "invalid-content" | "limit-exceeded" | "storage-unavailable" | "idempotency-payload-mismatch" | "capability-unavailable";
44
+ export type StageReceipt = { schemaVersion: 1; version: "piagent-webui-attachment-v1"; messageType: "stage-receipt"; commandId: string;
45
+ identity: BridgeIdentity; phase: "settled" | "rejected"; resultCode: StageResultCode; requestedAt: string; settledAt: string;
46
+ deduplicated: boolean; attachment: Attachment | null; error: { code: string; message: string; retryable: boolean } | null };
47
+ type DiscardCommand = Omit<StageCommand, "messageType" | "file"> & { messageType: "discard-command"; attachmentRef: string };
48
+ export type DiscardReceipt = Omit<StageReceipt, "messageType" | "resultCode" | "attachment"> & { messageType: "discard-receipt";
49
+ resultCode: "discarded" | "invalid-command" | "identity-mismatch" | "stale-revision" | "expired" | "attachment-unavailable"
50
+ | "idempotency-payload-mismatch" | "capability-unavailable"; attachmentRef: string | null };
51
+ type CachedStage = { fingerprint: string; receipt: StageReceipt; expiresAt: number };
52
+ type TextContent = { type: "text"; text: string };
53
+ type ImageContent = { type: "image"; data: string; mimeType: string };
54
+ export type PreparedAttachments = { content: string | Array<TextContent | ImageContent>; observedText: string };
55
+
56
+ function exactKeys(value: unknown, expected: string[]): boolean {
57
+ return Boolean(value && typeof value === "object" && !Array.isArray(value)
58
+ && JSON.stringify(Object.keys(value as Record<string, unknown>).sort()) === JSON.stringify([...expected].sort()));
59
+ }
60
+ function timestamp(value: unknown): value is string {
61
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) return false;
62
+ const parsed = Date.parse(value);
63
+ return Number.isFinite(parsed) && new Date(parsed).toISOString() === value;
64
+ }
65
+ function validIdentity(value: unknown): value is BridgeIdentity {
66
+ if (!exactKeys(value, ["projectRef", "runtimeInstanceId", "sessionRef", "taskId", "taskRunId", "agentOperationId", "toolCallId"])) return false;
67
+ const item = value as BridgeIdentity;
68
+ return [item.projectRef, item.runtimeInstanceId, item.sessionRef].every((part) => typeof part === "string" && REF.test(part))
69
+ && (item.taskId === null || typeof item.taskId === "string" && PUBLIC_REF.test(item.taskId))
70
+ && (item.taskRunId === null || typeof item.taskRunId === "string" && PUBLIC_REF.test(item.taskRunId))
71
+ && (item.taskRunId === null || item.taskId !== null)
72
+ && (item.agentOperationId === null || typeof item.agentOperationId === "string" && REF.test(item.agentOperationId))
73
+ && item.toolCallId === null;
74
+ }
75
+ function sameIdentity(left: BridgeIdentity, right: BridgeIdentity): boolean {
76
+ return left.projectRef === right.projectRef && left.runtimeInstanceId === right.runtimeInstanceId && left.sessionRef === right.sessionRef
77
+ && left.taskId === right.taskId && left.taskRunId === right.taskRunId && left.agentOperationId === right.agentOperationId && left.toolCallId === right.toolCallId;
78
+ }
79
+ function fingerprint(command: unknown): string {
80
+ return createHash("sha256").update(JSON.stringify(command)).digest("hex");
81
+ }
82
+ function safeName(value: unknown): string {
83
+ const basename = path.basename(String(value ?? "attachment").replace(/[\\/]/g, "_"));
84
+ return redactSensitiveText(basename).text.replace(/[\u0000-\u001F\u007F]/g, " ").replace(/\s+/g, " ").trim().slice(0, 160) || "attachment";
85
+ }
86
+ function errorMessage(code: StageReceipt["resultCode"]): string {
87
+ const messages: Partial<Record<StageReceipt["resultCode"], string>> = {
88
+ "invalid-command": "The attachment command is invalid.", "identity-mismatch": "The attachment targets a different Pi session.",
89
+ "stale-revision": "The Pi session changed before the attachment was staged.", expired: "The attachment command expired.",
90
+ "unsupported-type": "This file type is not supported.", "invalid-content": "The selected file content is invalid.",
91
+ "limit-exceeded": "The attachment limit was exceeded.", "storage-unavailable": "Private attachment storage is unavailable.",
92
+ "idempotency-payload-mismatch": "This upload key was already used for different content.",
93
+ "capability-unavailable": "The active Pi model cannot accept this attachment."
94
+ };
95
+ return messages[code] ?? "The attachment could not be staged.";
96
+ }
97
+
98
+ export class AttachmentStore {
99
+ readonly #runtimeInstanceId: string;
100
+ readonly #bridgeSnapshot: () => BridgeSnapshot;
101
+ readonly #modelSupportsImages: () => boolean;
102
+ readonly #now: () => Date;
103
+ #directory: string;
104
+ readonly #directoryDevice: number;
105
+ readonly #directoryInode: number;
106
+ readonly #records = new Map<string, StoredAttachment>();
107
+ readonly #cache = new Map<string, CachedStage>();
108
+ readonly #discardCache = new Map<string, { fingerprint: string; receipt: DiscardReceipt; expiresAt: number }>();
109
+ #closed = false;
110
+
111
+ constructor(options: { runtimeInstanceId: string; bridgeSnapshot: () => BridgeSnapshot; modelSupportsImages: () => boolean;
112
+ now?: () => Date; tempRoot?: string }) {
113
+ if (!REF.test(options.runtimeInstanceId)) throw new Error("webui-attachment-runtime-invalid");
114
+ this.#runtimeInstanceId = options.runtimeInstanceId; this.#bridgeSnapshot = options.bridgeSnapshot;
115
+ this.#modelSupportsImages = options.modelSupportsImages; this.#now = options.now ?? (() => new Date());
116
+ const parent = path.resolve(options.tempRoot ?? os.tmpdir());
117
+ this.#directory = fs.mkdtempSync(path.join(parent, "piagent-webui-attachments-"));
118
+ fs.chmodSync(this.#directory, 0o700);
119
+ const inspected = fs.lstatSync(this.#directory);
120
+ if (!inspected.isDirectory() || inspected.isSymbolicLink() || (inspected.mode & 0o077) !== 0) throw new Error("webui-attachment-storage-unsafe");
121
+ this.#directoryDevice = inspected.dev; this.#directoryInode = inspected.ino;
122
+ }
123
+
124
+ capability(): { kinds: Array<"file" | "image">; mimeTypes: string[] } {
125
+ const image = this.#modelSupportsImages();
126
+ return { kinds: image ? ["file", "image"] : ["file"], mimeTypes: [...TEXT_MIMES, ...(image ? IMAGE_MIMES : [])].sort() };
127
+ }
128
+
129
+ stage(input: unknown): StageReceipt {
130
+ const now = this.#now(); this.#cleanup(now.getTime());
131
+ const snapshot = this.#bridgeSnapshot(), command = input as StageCommand;
132
+ const invalid = this.#validate(command);
133
+ if (invalid) return this.#reject(command, snapshot, "invalid-command", invalid, now);
134
+ const key = command.idempotencyKey, found = this.#cache.get(key), commandFingerprint = fingerprint(command);
135
+ if (found) {
136
+ if (found.fingerprint !== commandFingerprint) return this.#reject(command, snapshot, "idempotency-payload-mismatch", null, now);
137
+ return { ...structuredClone(found.receipt), deduplicated: true };
138
+ }
139
+ if (this.#closed || snapshot.state !== "ready" || snapshot.taskState === "terminal" || !snapshot.identity || !snapshot.revisions)
140
+ return this.#reject(command, snapshot, "capability-unavailable", "attachment-store-not-ready", now);
141
+ if (Date.parse(command.requestedAt) > now.getTime() + 30_000) return this.#reject(command, snapshot, "invalid-command", "requested-at-in-future", now);
142
+ if (now.getTime() > Date.parse(command.expiresAt)) return this.#reject(command, snapshot, "expired", null, now);
143
+ if (!sameIdentity(command.identity, snapshot.identity)) return this.#reject(command, snapshot, "identity-mismatch", null, now);
144
+ if (command.expectedRuntimeRevision !== snapshot.revisions.runtimeRevision) return this.#reject(command, snapshot, "stale-revision", null, now);
145
+
146
+ let bytes: Buffer;
147
+ try { bytes = Buffer.from(command.file.dataBase64, "base64"); }
148
+ catch { return this.#reject(command, snapshot, "invalid-content", "base64-decode-failed", now); }
149
+ if (bytes.length < 1 || bytes.toString("base64") !== command.file.dataBase64) return this.#reject(command, snapshot, "invalid-content", "base64-noncanonical", now);
150
+ const declared = command.file.declaredMimeType, image = IMAGE_MIMES.has(declared), text = TEXT_MIMES.has(declared);
151
+ if (!image && !text) return this.#reject(command, snapshot, "unsupported-type", null, now);
152
+ let mimeType = declared;
153
+ if (image) {
154
+ if (!this.#modelSupportsImages()) return this.#reject(command, snapshot, "capability-unavailable", "model-image-input-unavailable", now);
155
+ const detected = supportedChatImageMimeType(bytes);
156
+ if (!detected || detected !== declared) return this.#reject(command, snapshot, "invalid-content", "image-mime-mismatch", now);
157
+ mimeType = detected;
158
+ if (bytes.length > ATTACHMENT_LIMITS.imageBytes) return this.#reject(command, snapshot, "limit-exceeded", "image-size-limit", now);
159
+ } else {
160
+ if (bytes.length > ATTACHMENT_LIMITS.textBytes) return this.#reject(command, snapshot, "limit-exceeded", "text-size-limit", now);
161
+ try {
162
+ const decoded = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
163
+ if (decoded.includes("\0")) throw new Error("nul");
164
+ if (declared === "application/json") JSON.parse(decoded);
165
+ } catch { return this.#reject(command, snapshot, "invalid-content", "text-content-invalid", now); }
166
+ }
167
+ const messageRecords = [...this.#records.values()].filter((item) => item.sessionRef === snapshot.identity!.sessionRef
168
+ && item.messageRequestId === command.messageRequestId);
169
+ if (messageRecords.length >= ATTACHMENT_LIMITS.countPerMessage
170
+ || messageRecords.reduce((sum, item) => sum + item.sizeBytes, 0) + bytes.length > ATTACHMENT_LIMITS.totalBytesPerMessage
171
+ || this.#records.size >= ATTACHMENT_LIMITS.runtimeCount
172
+ || [...this.#records.values()].reduce((sum, item) => sum + item.sizeBytes, 0) + bytes.length > ATTACHMENT_LIMITS.runtimeBytes)
173
+ return this.#reject(command, snapshot, "limit-exceeded", "attachment-capacity-limit", now);
174
+ const attachmentRef = `attachment.${randomBytes(24).toString("hex")}`, filename = `${randomBytes(24).toString("hex")}.bin`;
175
+ const absolutePath = path.join(this.#directory, filename), expiresAt = new Date(now.getTime() + ATTACHMENT_LIMITS.ttlMs).toISOString();
176
+ try {
177
+ if (!this.#safeDirectory()) throw new Error("unsafe-directory");
178
+ const descriptor = fs.openSync(absolutePath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
179
+ try { fs.writeFileSync(descriptor, bytes); fs.fsyncSync(descriptor); fs.fchmodSync(descriptor, 0o600); }
180
+ finally { fs.closeSync(descriptor); }
181
+ const inspected = fs.lstatSync(absolutePath);
182
+ if (!inspected.isFile() || inspected.isSymbolicLink() || inspected.size !== bytes.length || (inspected.mode & 0o077) !== 0) throw new Error("unsafe-file");
183
+ const attachment = { attachmentRef, messageRequestId: command.messageRequestId, displayName: safeName(command.file.displayName),
184
+ kind: image ? "image" as const : "file" as const, mimeType, sizeBytes: bytes.length, expiresAt };
185
+ this.#records.set(attachmentRef, { ...attachment, projectRef: snapshot.identity.projectRef, runtimeInstanceId: snapshot.identity.runtimeInstanceId,
186
+ sessionRef: snapshot.identity.sessionRef, absolutePath, device: inspected.dev, inode: inspected.ino });
187
+ const receipt = this.#receipt(command, snapshot.identity, "settled", "staged", attachment, null, now, false);
188
+ this.#cache.set(key, { fingerprint: commandFingerprint, receipt: structuredClone(receipt), expiresAt: Date.parse(expiresAt) });
189
+ return receipt;
190
+ } catch {
191
+ this.#deleteOwnedPath(absolutePath); return this.#reject(command, snapshot, "storage-unavailable", null, now);
192
+ }
193
+ }
194
+
195
+ execute(input: unknown): StageReceipt | DiscardReceipt {
196
+ return (input as { messageType?: unknown })?.messageType === "discard-command" ? this.discard(input) : this.stage(input);
197
+ }
198
+
199
+ discard(input: unknown): DiscardReceipt {
200
+ const now = this.#now(); this.#cleanup(now.getTime()); const snapshot = this.#bridgeSnapshot(), command = input as DiscardCommand;
201
+ const reject = (code: Exclude<DiscardReceipt["resultCode"], "discarded">, reason: string = code): DiscardReceipt => ({ schemaVersion: 1,
202
+ version: "piagent-webui-attachment-v1", messageType: "discard-receipt", commandId: typeof command?.commandId === "string" && REF.test(command.commandId)
203
+ ? command.commandId : `attachment-command.${createHash("sha256").update(reason).digest("hex")}`, identity: structuredClone(snapshot.identity ?? {
204
+ projectRef: `project.${"0".repeat(64)}`, runtimeInstanceId: this.#runtimeInstanceId, sessionRef: `session.${"0".repeat(64)}`,
205
+ taskId: null, taskRunId: null, agentOperationId: null, toolCallId: null }), phase: "rejected", resultCode: code,
206
+ requestedAt: timestamp(command?.requestedAt) ? command.requestedAt : now.toISOString(), settledAt: now.toISOString(), deduplicated: false,
207
+ attachmentRef: null, error: { code: reason, message: errorMessage(code === "attachment-unavailable" ? "capability-unavailable" : code as StageResultCode), retryable: false } });
208
+ if (!command || !exactKeys(command, ["schemaVersion", "version", "messageType", "commandId", "idempotencyKey", "requestedAt", "expiresAt", "identity",
209
+ "expectedRuntimeRevision", "messageRequestId", "attachmentRef"]) || command.schemaVersion !== 1 || command.version !== "piagent-webui-attachment-v1"
210
+ || command.messageType !== "discard-command" || !REF.test(command.commandId) || !IDEMPOTENCY.test(command.idempotencyKey) || !timestamp(command.requestedAt)
211
+ || !timestamp(command.expiresAt) || Date.parse(command.requestedAt) > Date.parse(command.expiresAt) || Date.parse(command.expiresAt) - Date.parse(command.requestedAt) > 300_000
212
+ || !validIdentity(command.identity) || !REVISION.test(command.expectedRuntimeRevision) || !REF.test(command.messageRequestId) || !REF.test(command.attachmentRef)) return reject("invalid-command");
213
+ const found = this.#discardCache.get(command.idempotencyKey), commandFingerprint = fingerprint(command);
214
+ if (found) return found.fingerprint === commandFingerprint ? { ...structuredClone(found.receipt), deduplicated: true } : reject("idempotency-payload-mismatch");
215
+ if (this.#closed || snapshot.state !== "ready" || !snapshot.identity || !snapshot.revisions) return reject("capability-unavailable");
216
+ if (Date.parse(command.requestedAt) > now.getTime() + 30_000) return reject("invalid-command", "requested-at-in-future");
217
+ if (now.getTime() > Date.parse(command.expiresAt)) return reject("expired");
218
+ if (!sameIdentity(command.identity, snapshot.identity)) return reject("identity-mismatch");
219
+ if (command.expectedRuntimeRevision !== snapshot.revisions.runtimeRevision) return reject("stale-revision");
220
+ const record = this.#records.get(command.attachmentRef);
221
+ if (!record || record.messageRequestId !== command.messageRequestId || record.sessionRef !== snapshot.identity.sessionRef) return reject("attachment-unavailable");
222
+ this.#consume(record);
223
+ const receipt = { schemaVersion: 1, version: "piagent-webui-attachment-v1", messageType: "discard-receipt", commandId: command.commandId,
224
+ identity: structuredClone(snapshot.identity), phase: "settled", resultCode: "discarded", requestedAt: command.requestedAt,
225
+ settledAt: now.toISOString(), deduplicated: false, attachmentRef: command.attachmentRef, error: null } satisfies DiscardReceipt;
226
+ this.#discardCache.set(command.idempotencyKey, { fingerprint: commandFingerprint, receipt: structuredClone(receipt), expiresAt: Date.parse(command.expiresAt) });
227
+ return receipt;
228
+ }
229
+
230
+ claim(refs: string[], messageRequestId: string, identity: BridgeIdentity, text: string): PreparedAttachments {
231
+ const now = this.#now().getTime(); this.#cleanup(now);
232
+ if (this.#closed || refs.length < 1 || refs.length > ATTACHMENT_LIMITS.countPerMessage || new Set(refs).size !== refs.length)
233
+ throw new Error("attachment-reference-invalid");
234
+ const records = refs.map((ref) => this.#records.get(ref));
235
+ if (records.some((record) => !record)) throw new Error("attachment-reference-unavailable");
236
+ const exact = records as StoredAttachment[];
237
+ if (exact.some((record) => record.messageRequestId !== messageRequestId || record.projectRef !== identity.projectRef
238
+ || record.runtimeInstanceId !== identity.runtimeInstanceId || record.sessionRef !== identity.sessionRef || Date.parse(record.expiresAt) < now)
239
+ || exact.reduce((sum, record) => sum + record.sizeBytes, 0) > ATTACHMENT_LIMITS.totalBytesPerMessage) throw new Error("attachment-authority-mismatch");
240
+ if (exact.some((record) => record.kind === "image") && !this.#modelSupportsImages()) throw new Error("model-image-input-unavailable");
241
+ const content: Array<TextContent | ImageContent> = [{ type: "text", text }], observedTexts = [text];
242
+ try {
243
+ for (const record of exact) {
244
+ const bytes = this.#readOwned(record);
245
+ if (record.kind === "image") content.push({ type: "image", data: bytes.toString("base64"), mimeType: record.mimeType });
246
+ else {
247
+ const body = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
248
+ const attachmentText = `[Attached file: ${record.displayName} (${record.mimeType}, ${record.sizeBytes} bytes)]\n${body}\n[End attached file]`;
249
+ content.push({ type: "text", text: attachmentText }); observedTexts.push(attachmentText);
250
+ }
251
+ }
252
+ } catch (error) {
253
+ exact.forEach((record) => this.#consume(record)); throw error;
254
+ }
255
+ exact.forEach((record) => this.#consume(record));
256
+ return { content, observedText: observedTexts.join("\n") };
257
+ }
258
+
259
+ close(): void {
260
+ if (this.#closed) return; this.#closed = true;
261
+ for (const record of this.#records.values()) this.#deleteOwnedPath(record.absolutePath);
262
+ this.#records.clear(); this.#cache.clear(); this.#discardCache.clear();
263
+ try { if (this.#safeDirectory()) fs.rmdirSync(this.#directory); } catch { /* never recurse beyond files owned by this store */ }
264
+ }
265
+
266
+ reset(): void {
267
+ for (const record of this.#records.values()) this.#deleteOwnedPath(record.absolutePath);
268
+ this.#records.clear(); this.#cache.clear(); this.#discardCache.clear();
269
+ }
270
+
271
+ #validate(command: StageCommand): string | null {
272
+ if (!command || typeof command !== "object" || command.schemaVersion !== 1 || command.version !== "piagent-webui-attachment-v1"
273
+ || command.messageType !== "stage-command" || !exactKeys(command, ["schemaVersion", "version", "messageType", "commandId", "idempotencyKey", "requestedAt", "expiresAt", "identity", "expectedRuntimeRevision", "messageRequestId", "file"])) return "unsupported-command-shape";
274
+ if (!REF.test(command.commandId) || !IDEMPOTENCY.test(command.idempotencyKey) || !timestamp(command.requestedAt) || !timestamp(command.expiresAt)
275
+ || Date.parse(command.requestedAt) > Date.parse(command.expiresAt) || Date.parse(command.expiresAt) - Date.parse(command.requestedAt) > 300_000
276
+ || !validIdentity(command.identity) || !REVISION.test(command.expectedRuntimeRevision) || !REF.test(command.messageRequestId)) return "invalid-command-metadata";
277
+ if (!exactKeys(command.file, ["displayName", "declaredMimeType", "dataBase64"]) || typeof command.file.displayName !== "string"
278
+ || command.file.displayName.length < 1 || command.file.displayName.length > 255 || /[\u0000-\u001F\u007F/\\]/.test(command.file.displayName)
279
+ || typeof command.file.declaredMimeType !== "string" || typeof command.file.dataBase64 !== "string"
280
+ || command.file.dataBase64.length < 4 || command.file.dataBase64.length > 11_184_812 || !BASE64.test(command.file.dataBase64)) return "invalid-file-payload";
281
+ return null;
282
+ }
283
+
284
+ #receipt(command: Partial<StageCommand>, identity: BridgeIdentity, phase: StageReceipt["phase"], resultCode: StageReceipt["resultCode"],
285
+ attachment: Attachment | null, reason: string | null, now: Date, deduplicated: boolean): StageReceipt {
286
+ return { schemaVersion: 1, version: "piagent-webui-attachment-v1", messageType: "stage-receipt",
287
+ commandId: typeof command.commandId === "string" && REF.test(command.commandId) ? command.commandId : `attachment-command.${createHash("sha256").update(reason ?? resultCode).digest("hex")}`,
288
+ identity: structuredClone(identity), phase, resultCode, requestedAt: timestamp(command.requestedAt) ? command.requestedAt : now.toISOString(),
289
+ settledAt: now.toISOString(), deduplicated, attachment, error: phase === "rejected" ? { code: reason ?? resultCode,
290
+ message: errorMessage(resultCode), retryable: resultCode === "storage-unavailable" } : null };
291
+ }
292
+ #reject(command: Partial<StageCommand>, snapshot: BridgeSnapshot, code: Exclude<StageReceipt["resultCode"], "staged">,
293
+ reason: string | null, now: Date): StageReceipt {
294
+ const identity = snapshot.identity ?? { projectRef: `project.${"0".repeat(64)}`, runtimeInstanceId: this.#runtimeInstanceId,
295
+ sessionRef: `session.${"0".repeat(64)}`, taskId: null, taskRunId: null, agentOperationId: null, toolCallId: null };
296
+ return this.#receipt(command, identity, "rejected", code, null, reason, now, false);
297
+ }
298
+ #readOwned(record: StoredAttachment): Buffer {
299
+ if (!this.#safeDirectory() || path.dirname(record.absolutePath) !== this.#directory || !OWNED_FILE.test(path.basename(record.absolutePath))) throw new Error("attachment-storage-boundary");
300
+ const descriptor = fs.openSync(record.absolutePath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
301
+ try {
302
+ const inspected = fs.fstatSync(descriptor);
303
+ if (!inspected.isFile() || inspected.dev !== record.device || inspected.ino !== record.inode || inspected.size !== record.sizeBytes) throw new Error("attachment-file-changed");
304
+ const bytes = Buffer.alloc(inspected.size); let offset = 0;
305
+ while (offset < bytes.length) { const read = fs.readSync(descriptor, bytes, offset, bytes.length - offset, offset); if (read <= 0) break; offset += read; }
306
+ if (offset !== bytes.length) throw new Error("attachment-file-short-read"); return bytes;
307
+ } finally { fs.closeSync(descriptor); }
308
+ }
309
+ #consume(record: StoredAttachment): void { this.#records.delete(record.attachmentRef); this.#deleteOwnedPath(record.absolutePath); }
310
+ #deleteOwnedPath(target: string): void {
311
+ if (!this.#safeDirectory() || path.dirname(target) !== this.#directory || !OWNED_FILE.test(path.basename(target))) return;
312
+ try { fs.unlinkSync(target); } catch { /* cleanup is bounded and best-effort */ }
313
+ }
314
+ #safeDirectory(): boolean {
315
+ try { const current = fs.lstatSync(this.#directory); return current.isDirectory() && !current.isSymbolicLink()
316
+ && current.dev === this.#directoryDevice && current.ino === this.#directoryInode && (current.mode & 0o077) === 0; } catch { return false; }
317
+ }
318
+ #cleanup(now: number): void {
319
+ for (const record of this.#records.values()) if (Date.parse(record.expiresAt) <= now) this.#consume(record);
320
+ for (const [key, cached] of this.#cache) if (cached.expiresAt <= now) this.#cache.delete(key);
321
+ for (const [key, cached] of this.#discardCache) if (cached.expiresAt <= now) this.#discardCache.delete(key);
322
+ }
323
+ }