@blackbelt-technology/pi-agent-dashboard 0.11.0 → 0.12.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 (337) hide show
  1. package/AGENTS.md +2 -0
  2. package/README.md +17 -12
  3. package/docs/architecture.md +973 -224
  4. package/package.json +29 -18
  5. package/packages/extension/package.json +16 -9
  6. package/packages/extension/src/bridge-context.ts +6 -0
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +54 -69
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
  9. package/packages/extension/src/bridge-handlers/instance.ts +21 -12
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +84 -40
  11. package/packages/extension/src/bridge-shutdown.ts +44 -0
  12. package/packages/extension/src/bridge.ts +272 -260
  13. package/packages/extension/src/command-handler.ts +26 -31
  14. package/packages/extension/src/connection.ts +123 -31
  15. package/packages/extension/src/credential-guard.ts +300 -0
  16. package/packages/extension/src/custom-entry-forward.ts +27 -18
  17. package/packages/extension/src/default-model-apply.ts +83 -0
  18. package/packages/extension/src/flow-event-wiring.ts +19 -95
  19. package/packages/extension/src/followup-drain.ts +19 -5
  20. package/packages/extension/src/path-gate/decide.ts +68 -5
  21. package/packages/extension/src/path-gate/handler.ts +16 -8
  22. package/packages/extension/src/path-gate/index.ts +2 -2
  23. package/packages/extension/src/path-gate/roots.ts +15 -3
  24. package/packages/extension/src/path-gate/suppression.ts +3 -0
  25. package/packages/extension/src/pi-env.d.ts +8 -1
  26. package/packages/extension/src/pi-retry-settings.ts +11 -2
  27. package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
  28. package/packages/extension/src/preview-path-link.ts +151 -0
  29. package/packages/extension/src/project-init/scaffold.ts +98 -35
  30. package/packages/extension/src/project-trust.ts +24 -15
  31. package/packages/extension/src/provider-model-cache.ts +118 -0
  32. package/packages/extension/src/provider-register.ts +428 -28
  33. package/packages/extension/src/retry-tracker.ts +90 -7
  34. package/packages/extension/src/role-manager.ts +4 -2
  35. package/packages/extension/src/role-model-tools.ts +21 -4
  36. package/packages/extension/src/server-auto-start.ts +68 -2
  37. package/packages/extension/src/server-launcher.ts +26 -8
  38. package/packages/extension/src/session-sync.ts +11 -12
  39. package/packages/extension/src/spawn-new-session.ts +22 -0
  40. package/packages/extension/src/steer-buffer.ts +164 -0
  41. package/packages/extension/src/stream-forward-buffer.ts +64 -15
  42. package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
  43. package/packages/extension/src/sudo-askpass/controller.ts +405 -0
  44. package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
  45. package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
  46. package/packages/extension/src/sudo-askpass/index.ts +11 -0
  47. package/packages/extension/src/sudo-askpass/install.ts +143 -0
  48. package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
  49. package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
  50. package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
  51. package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
  52. package/packages/extension/src/terminal-reload.ts +19 -5
  53. package/packages/extension/src/tool-update-filter-registry.ts +210 -0
  54. package/packages/extension/src/vault-redaction.ts +4 -3
  55. package/packages/server/package.json +17 -14
  56. package/packages/server/src/access/access-denials.ts +8 -0
  57. package/packages/server/src/access/access-grants.ts +244 -58
  58. package/packages/server/src/access/access-plane.ts +7 -0
  59. package/packages/server/src/access/containment-gate.ts +66 -21
  60. package/packages/server/src/access/denial-hold.ts +3 -0
  61. package/packages/server/src/access/grant-coordinator.ts +17 -1
  62. package/packages/server/src/access/named-grant.ts +3 -0
  63. package/packages/server/src/access/pending-grant-registry.ts +32 -5
  64. package/packages/server/src/access/pi-trust-mirror-service.ts +7 -1
  65. package/packages/server/src/access/planes.ts +1 -0
  66. package/packages/server/src/access/verified-read.ts +24 -7
  67. package/packages/server/src/acp-bridge/acp-session-adapter.ts +10 -2
  68. package/packages/server/src/acp-bridge/server-requests.ts +10 -4
  69. package/packages/server/src/agent-events/agent-event-hub.ts +1 -1
  70. package/packages/server/src/auth/audit-log.ts +28 -0
  71. package/packages/server/src/auth/auth-plugin.ts +188 -15
  72. package/packages/server/src/auth/auth.ts +80 -0
  73. package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
  74. package/packages/server/src/auth/cors-origin.ts +14 -1
  75. package/packages/server/src/auth/credential-envelope.ts +233 -0
  76. package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
  77. package/packages/server/src/auth/credential-key-worker.mjs +108 -0
  78. package/packages/server/src/auth/credential-key.ts +479 -0
  79. package/packages/server/src/auth/credential-migration.ts +162 -0
  80. package/packages/server/src/auth/csp-report-paths.ts +0 -5
  81. package/packages/server/src/auth/csp.ts +74 -36
  82. package/packages/server/src/auth/device-proof.ts +202 -0
  83. package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
  84. package/packages/server/src/auth/host-admission.ts +7 -0
  85. package/packages/server/src/auth/host-gate.ts +13 -2
  86. package/packages/server/src/auth/localhost-guard.ts +50 -23
  87. package/packages/server/src/auth/locked-json-file.ts +68 -6
  88. package/packages/server/src/auth/models-json-store.ts +269 -0
  89. package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
  90. package/packages/server/src/auth/node-guard.ts +36 -49
  91. package/packages/server/src/auth/plugin-credential-store.ts +81 -10
  92. package/packages/server/src/auth/provider-auth-storage.ts +208 -11
  93. package/packages/server/src/auth/provider-block-checks.ts +321 -0
  94. package/packages/server/src/auth/provider-host-detect.ts +151 -0
  95. package/packages/server/src/auth/provider-key-file.ts +71 -0
  96. package/packages/server/src/auth/provider-readiness.ts +91 -0
  97. package/packages/server/src/auth/route-tier-gate.ts +3 -2
  98. package/packages/server/src/auth/vertex-key-check.ts +140 -0
  99. package/packages/server/src/auth/ws-ticket.ts +1 -1
  100. package/packages/server/src/browse.ts +73 -20
  101. package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
  102. package/packages/server/src/browser-handlers/directory-handler.ts +11 -24
  103. package/packages/server/src/browser-handlers/session-action-handler.ts +158 -62
  104. package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
  105. package/packages/server/src/browser-handlers/subscription-handler.ts +46 -1
  106. package/packages/server/src/build-plugin-send-prompt.ts +18 -0
  107. package/packages/server/src/cli/credentials-command.ts +555 -0
  108. package/packages/server/src/cli.ts +21 -16
  109. package/packages/server/src/config-api.ts +34 -38
  110. package/packages/server/src/config-snapshot.ts +149 -0
  111. package/packages/server/src/directory-service.ts +33 -14
  112. package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
  113. package/packages/server/src/event-wiring.ts +181 -101
  114. package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
  115. package/packages/server/src/git-worktree/git-operations.ts +1 -1
  116. package/packages/server/src/git-worktree/repo-lock.ts +42 -0
  117. package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
  118. package/packages/server/src/git-worktree/worktree-init.ts +5 -1
  119. package/packages/server/src/identity/http-road-classification.ts +5 -1
  120. package/packages/server/src/identity/identity-floor.ts +5 -2
  121. package/packages/server/src/identity/ws-message-scope.ts +10 -3
  122. package/packages/server/src/identity/ws-road-classification.ts +2 -1
  123. package/packages/server/src/lib/browse-roots.ts +13 -2
  124. package/packages/server/src/lib/content-disposition.ts +20 -0
  125. package/packages/server/src/lib/dashboard-state-guard.ts +304 -21
  126. package/packages/server/src/lib/eml.ts +2 -2
  127. package/packages/server/src/lib/frame-policy-probe.ts +308 -0
  128. package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
  129. package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
  130. package/packages/server/src/lib/grep.ts +4 -1
  131. package/packages/server/src/lib/index-html.ts +2 -2
  132. package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
  133. package/packages/server/src/lib/office-preview.ts +47 -10
  134. package/packages/server/src/lib/path-containment.ts +45 -12
  135. package/packages/server/src/lib/resolve-file-mention.ts +230 -38
  136. package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
  137. package/packages/server/src/lib/writable-handler-target.ts +4 -0
  138. package/packages/server/src/lib/writable-md-target.ts +22 -0
  139. package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
  140. package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
  141. package/packages/server/src/lifecycle/exit-signal.ts +43 -0
  142. package/packages/server/src/live-server/capability-redact.ts +21 -5
  143. package/packages/server/src/live-server/live-capability.ts +416 -52
  144. package/packages/server/src/live-server/live-csp-report.ts +1 -1
  145. package/packages/server/src/live-server/live-csp.ts +64 -16
  146. package/packages/server/src/live-server/live-log.ts +5 -1
  147. package/packages/server/src/live-server/live-server-manager.ts +11 -0
  148. package/packages/server/src/live-server/live-server-proxy.ts +268 -52
  149. package/packages/server/src/live-server/live-static.ts +4 -1
  150. package/packages/server/src/live-server/preview-dispatch.ts +286 -0
  151. package/packages/server/src/live-server/preview-observe.ts +53 -0
  152. package/packages/server/src/live-server/preview-origin.ts +182 -0
  153. package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
  154. package/packages/server/src/live-server/preview-path-store.ts +420 -0
  155. package/packages/server/src/live-server/preview-path.ts +40 -0
  156. package/packages/server/src/live-server/preview-pool.ts +385 -0
  157. package/packages/server/src/live-server/preview-preflight.ts +41 -0
  158. package/packages/server/src/live-server/preview-reserve.ts +44 -0
  159. package/packages/server/src/live-server/preview-tier.ts +217 -0
  160. package/packages/server/src/live-server/preview-viewers.ts +54 -0
  161. package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
  162. package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
  163. package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
  164. package/packages/server/src/model-proxy/internal-registry.ts +283 -21
  165. package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
  166. package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
  167. package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
  168. package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
  169. package/packages/server/src/openspec/readiness.ts +1 -1
  170. package/packages/server/src/package/provider-probe.ts +194 -5
  171. package/packages/server/src/pairing/browser-gateway.ts +140 -42
  172. package/packages/server/src/pairing/device-key-intake.ts +120 -0
  173. package/packages/server/src/pairing/paired-devices.ts +370 -8
  174. package/packages/server/src/pairing/pairing.ts +69 -7
  175. package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
  176. package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
  177. package/packages/server/src/pending/pending-attach-registry.ts +15 -0
  178. package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
  179. package/packages/server/src/persistence/memory-event-store.ts +251 -296
  180. package/packages/server/src/persistence/preferences-store.ts +52 -2
  181. package/packages/server/src/pi/bridge-contention.ts +84 -2
  182. package/packages/server/src/pi/host-project-trust.ts +15 -9
  183. package/packages/server/src/pi/pi-gateway.ts +208 -21
  184. package/packages/server/src/pi/provisional-registration.ts +4 -1
  185. package/packages/server/src/pi/resource-toggle-trust.ts +17 -6
  186. package/packages/server/src/pi-agent-settings.ts +95 -301
  187. package/packages/server/src/pi-default-remirror.ts +89 -0
  188. package/packages/server/src/plugin-append-event.ts +35 -0
  189. package/packages/server/src/plugin-entry-stats.ts +61 -0
  190. package/packages/server/src/plugin-local-request.ts +207 -0
  191. package/packages/server/src/plugin-ownership.ts +111 -0
  192. package/packages/server/src/plugin-policy-registry.ts +297 -0
  193. package/packages/server/src/plugin-request-lane.ts +92 -16
  194. package/packages/server/src/preferences-relay.ts +20 -0
  195. package/packages/server/src/project-seed.ts +347 -0
  196. package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
  197. package/packages/server/src/questions/question-store.ts +3 -2
  198. package/packages/server/src/routes/access-routes.ts +23 -6
  199. package/packages/server/src/routes/acme-routes.ts +14 -4
  200. package/packages/server/src/routes/agent-event-stream-routes.ts +1 -1
  201. package/packages/server/src/routes/file-routes.ts +327 -86
  202. package/packages/server/src/routes/file-write-binary-routes.ts +20 -4
  203. package/packages/server/src/routes/frame-policy-routes.ts +215 -0
  204. package/packages/server/src/routes/git-routes.ts +29 -78
  205. package/packages/server/src/routes/grep-routes.ts +26 -0
  206. package/packages/server/src/routes/live-server-routes.ts +198 -4
  207. package/packages/server/src/routes/models-introspection-routes.ts +1 -1
  208. package/packages/server/src/routes/openspec-routes.ts +17 -3
  209. package/packages/server/src/routes/pairing-routes.ts +200 -11
  210. package/packages/server/src/routes/pi-settings-routes.ts +2 -0
  211. package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
  212. package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
  213. package/packages/server/src/routes/provider-auth-routes.ts +167 -9
  214. package/packages/server/src/routes/provider-override-routes.ts +158 -0
  215. package/packages/server/src/routes/provider-routes.ts +348 -86
  216. package/packages/server/src/routes/session-routes.ts +25 -22
  217. package/packages/server/src/routes/system-routes.ts +87 -39
  218. package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
  219. package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
  220. package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
  221. package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
  222. package/packages/server/src/server.ts +512 -175
  223. package/packages/server/src/services/cli-service.ts +59 -10
  224. package/packages/server/src/services/secrets-resolver.ts +46 -30
  225. package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
  226. package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
  227. package/packages/server/src/session/death-reason.ts +11 -7
  228. package/packages/server/src/session/event-status-extraction.ts +5 -1
  229. package/packages/server/src/session/memory-session-manager.ts +24 -2
  230. package/packages/server/src/session/open-tool-calls.ts +81 -47
  231. package/packages/server/src/session/pid-target.ts +127 -0
  232. package/packages/server/src/session/replay-compaction.ts +18 -5
  233. package/packages/server/src/session/seed-discovered-history.ts +85 -0
  234. package/packages/server/src/session/server-pid-context.ts +14 -0
  235. package/packages/server/src/session/session-api.ts +78 -29
  236. package/packages/server/src/session/session-archive.ts +7 -0
  237. package/packages/server/src/session/session-bootstrap.ts +9 -54
  238. package/packages/server/src/session/session-load-worker-pool.ts +11 -1
  239. package/packages/server/src/session/session-load-worker.ts +22 -3
  240. package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
  241. package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
  242. package/packages/server/src/spawn-process/headless-pid-registry.ts +383 -72
  243. package/packages/server/src/spawn-process/link-register.ts +42 -0
  244. package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
  245. package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
  246. package/packages/server/src/spawn-process/process-classifier.ts +8 -3
  247. package/packages/server/src/spawn-process/process-manager.ts +61 -6
  248. package/packages/server/src/spawn-process/restored-identity.ts +112 -0
  249. package/packages/server/src/spawn-process/session-terminator.ts +179 -18
  250. package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
  251. package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
  252. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
  253. package/packages/server/src/sudo-credential/relay.ts +337 -0
  254. package/packages/server/src/terminal/terminal-gateway.ts +10 -0
  255. package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
  256. package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
  257. package/packages/server/src/vault/vault-delivery-hub.ts +17 -1
  258. package/packages/server/src/vault/vault-routes.ts +9 -2
  259. package/packages/server/src/vault/vault-store.ts +87 -24
  260. package/packages/server/vendor/xlsx/LICENSE +201 -0
  261. package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
  262. package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
  263. package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
  264. package/packages/shared/package.json +4 -2
  265. package/packages/shared/src/agent-credential-files.ts +32 -0
  266. package/packages/shared/src/browser-protocol.ts +137 -57
  267. package/packages/shared/src/canvas-detect.ts +1 -1
  268. package/packages/shared/src/canvas-types.ts +2 -2
  269. package/packages/shared/src/config.ts +73 -136
  270. package/packages/shared/src/containment-guard.ts +14 -4
  271. package/packages/shared/src/credential-encryption.ts +87 -0
  272. package/packages/shared/src/custom-event-groups.ts +2 -0
  273. package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
  274. package/packages/shared/src/dashboard-plugin/host-api.ts +1 -1
  275. package/packages/shared/src/dashboard-plugin/manifest-types.ts +46 -0
  276. package/packages/shared/src/dashboard-plugin/plugin-status.ts +4 -3
  277. package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
  278. package/packages/shared/src/dashboard-plugin/slot-props.ts +2 -0
  279. package/packages/shared/src/dashboard-plugin/slot-types.ts +1 -1
  280. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +11 -3
  281. package/packages/shared/src/device-key-proof.ts +309 -0
  282. package/packages/shared/src/event-forward-declaration.ts +85 -12
  283. package/packages/shared/src/forbidden-subjects.ts +126 -14
  284. package/packages/shared/src/heap-limits.ts +0 -30
  285. package/packages/shared/src/host-admission.ts +2 -1
  286. package/packages/shared/src/index.ts +7 -6
  287. package/packages/shared/src/live-server.ts +20 -0
  288. package/packages/shared/src/mcp/verb-tiers.generated.ts +1 -3
  289. package/packages/shared/src/models-json-reader.ts +41 -0
  290. package/packages/shared/src/network-denial-signal.ts +15 -0
  291. package/packages/shared/src/node-version.ts +63 -60
  292. package/packages/shared/src/pairing-knock-client.ts +92 -8
  293. package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
  294. package/packages/shared/src/pi-path-compare.ts +31 -0
  295. package/packages/shared/src/pi-settings-schema.ts +52 -9
  296. package/packages/shared/src/pi-trust-mirror-snapshot.ts +16 -4
  297. package/packages/shared/src/pi-trust-mirror-types.ts +2 -0
  298. package/packages/shared/src/pi-trust-mirror.ts +18 -8
  299. package/packages/shared/src/pi-trust-resource-digest.ts +18 -12
  300. package/packages/shared/src/pid-namespace.ts +86 -0
  301. package/packages/shared/src/platform/native-ts-register.mjs +1 -1
  302. package/packages/shared/src/platform/process.ts +404 -1
  303. package/packages/shared/src/platform/resolve-pi-shell.ts +38 -9
  304. package/packages/shared/src/platform/spawn-runtime.ts +193 -7
  305. package/packages/shared/src/preview-egress.ts +56 -2
  306. package/packages/shared/src/preview-origins.ts +398 -0
  307. package/packages/shared/src/prompt-answer.ts +9 -5
  308. package/packages/shared/src/protocol.ts +147 -85
  309. package/packages/shared/src/provider-env-catalog.ts +413 -0
  310. package/packages/shared/src/provider-overrides.ts +112 -0
  311. package/packages/shared/src/question-types.ts +6 -0
  312. package/packages/shared/src/recommended-extensions.ts +79 -26
  313. package/packages/shared/src/renderer-by-ext.ts +5 -2
  314. package/packages/shared/src/rest-api.ts +93 -3
  315. package/packages/shared/src/role-schema.ts +24 -0
  316. package/packages/shared/src/route-tiers.ts +94 -3
  317. package/packages/shared/src/runtime-overlay/compat.ts +70 -6
  318. package/packages/shared/src/secret-patterns.ts +49 -0
  319. package/packages/shared/src/source-matching.ts +2 -2
  320. package/packages/shared/src/state-replay.ts +40 -24
  321. package/packages/shared/src/sudo-credential.ts +71 -0
  322. package/packages/shared/src/tool-path-resolve.ts +16 -1
  323. package/packages/shared/src/tool-registry/strategies.ts +1 -1
  324. package/packages/shared/src/tool-workdir.ts +56 -0
  325. package/packages/shared/src/trusted-types-mode.ts +72 -0
  326. package/packages/shared/src/types.ts +68 -109
  327. package/packages/shared/src/vertex-regions.ts +81 -0
  328. package/packages/shared/src/ws-message-tiers.ts +10 -3
  329. package/packages/extension/src/subagent-fanout-admission.ts +0 -234
  330. package/packages/extension/src/subagent-forward-sites.ts +0 -69
  331. package/packages/extension/src/subagent-frame-buffer.ts +0 -245
  332. package/packages/extension/src/subagent-frame-strip.ts +0 -109
  333. package/packages/extension/src/subagent-saturation.ts +0 -196
  334. package/packages/extension/src/subagent-tick-throttle.ts +0 -252
  335. package/packages/shared/src/anthropic-messages-source.ts +0 -8
  336. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +0 -9
  337. package/packages/shared/src/dashboard-plugin/subagent-types.ts +0 -219
@@ -1,196 +0,0 @@
1
- /**
2
- * SubagentSaturation — the private resource-load sampler the subagent-fanout
3
- * admission gate reads.
4
- *
5
- * Why it exists rather than reusing `process-metrics.ts`: `collectMetrics()` is
6
- * a DESTRUCTIVE read — it resets the event-loop-delay histogram and the CPU
7
- * delta on every call — and its sole caller is the 15 s bridge heartbeat.
8
- * Reading it from admission would reset the window mid-interval, so the
9
- * heartbeat that recorded a 143 s stall would under-report exactly the failure
10
- * this capability mitigates. Merely reading the same histogram non-destructively
11
- * is also wrong: that histogram is reset every 15 s, so the gate would see a
12
- * window of 0–15 s depending on phase and flap the effective cap on the
13
- * telemetry period.
14
- *
15
- * The sampler therefore OWNS its state: a dedicated `monitorEventLoopDelay`
16
- * histogram over a fixed 5 s window (so a spike clears well inside one heartbeat)
17
- * plus its own CPU baseline. Hysteresis — enter at the threshold, leave below
18
- * 80 % of it — keeps consecutive decisions in one preflight batch agreeing.
19
- *
20
- * Domains differ and are stated: `process.cpuUsage()` observes this process
21
- * only; `os.loadavg()` observes the machine. The observed deaths are
22
- * machine-level saturation caused by many resident sessions, where a parent's
23
- * own CPU can read low — so the two are separate thresholds, never conflated.
24
- *
25
- * See change: bound-subagent-fanout-under-host-pressure (D5).
26
- */
27
-
28
- import os from "node:os";
29
- import { monitorEventLoopDelay, type IntervalHistogram } from "node:perf_hooks";
30
- import type { SubagentSaturationThresholds } from "@blackbelt-technology/pi-dashboard-shared/config.js";
31
-
32
- /** Fixed rolling window (ms). Chosen so a spike clears inside one 15 s heartbeat. */
33
- export const SATURATION_WINDOW_MS = 5_000;
34
- /** Exit hysteresis: leave the narrowed state only below 80 % of the entry threshold. */
35
- export const SATURATION_EXIT_RATIO = 0.8;
36
- const ELD_RESOLUTION_MS = 20;
37
-
38
- export type SaturationThresholds = SubagentSaturationThresholds;
39
-
40
- /** One sample. A missing metric means "no signal", never "zero load". */
41
- export interface SaturationReading {
42
- /** PROCESS domain. */
43
- eventLoopDelayMs?: number;
44
- /** PROCESS domain. */
45
- cpuPercent?: number;
46
- /** MACHINE domain. */
47
- loadAvg1m?: number;
48
- }
49
-
50
- export interface SaturationSnapshot {
51
- /** Post-hysteresis verdict the decision function consumes. */
52
- saturated: boolean;
53
- reading: SaturationReading;
54
- }
55
-
56
- /** True when `reading` is a usable number at/above `threshold * ratio`. */
57
- function atOrAbove(reading: unknown, threshold: unknown, ratio: number): boolean {
58
- if (typeof reading !== "number" || !Number.isFinite(reading)) return false;
59
- if (typeof threshold !== "number" || !Number.isFinite(threshold) || threshold <= 0) return false;
60
- return reading >= threshold * ratio;
61
- }
62
-
63
- /** Any configured metric at/above `ratio` × its threshold. Missing metric → no signal. */
64
- export function anyMetricAtOrAbove(
65
- reading: SaturationReading,
66
- thresholds: SaturationThresholds,
67
- ratio: number,
68
- ): boolean {
69
- return (
70
- atOrAbove(reading.eventLoopDelayMs, thresholds.eventLoopDelayMs, ratio) ||
71
- atOrAbove(reading.cpuPercent, thresholds.cpuPercent, ratio) ||
72
- atOrAbove(reading.loadAvg1m, thresholds.loadAvg1m, ratio)
73
- );
74
- }
75
-
76
- /**
77
- * Pure hysteresis transition. Enter the narrowed state at/above a threshold;
78
- * leave it only once EVERY metric has fallen below 80 % of its threshold.
79
- */
80
- export function nextSaturationState(
81
- prev: boolean,
82
- reading: SaturationReading,
83
- thresholds: SaturationThresholds,
84
- ): boolean {
85
- if (anyMetricAtOrAbove(reading, thresholds, 1)) return true;
86
- if (!prev) return false;
87
- return anyMetricAtOrAbove(reading, thresholds, SATURATION_EXIT_RATIO);
88
- }
89
-
90
- export interface SaturationSamplerOptions {
91
- /** Rolling window override (tests). */
92
- windowMs?: number;
93
- /** Injectable clock. */
94
- now?: () => number;
95
- /** Injectable CPU source (process domain). */
96
- cpuUsage?: () => NodeJS.CpuUsage;
97
- /** Injectable machine load source. */
98
- loadAvg1m?: () => number;
99
- /**
100
- * Injectable event-loop-delay source (ms) — bypasses the owned histogram
101
- * entirely. Tests only; production omits it and owns a private histogram.
102
- */
103
- eventLoopDelayMs?: () => number | undefined;
104
- }
105
-
106
- /**
107
- * Owns a private rolling-window event-loop-delay histogram, a CPU baseline and
108
- * the post-hysteresis saturation latch. Never touches `process-metrics.ts`.
109
- */
110
- export class SaturationSampler {
111
- private readonly windowMs: number;
112
- private readonly now: () => number;
113
- private readonly cpuUsage: () => NodeJS.CpuUsage;
114
- private readonly loadAvg1m: () => number;
115
- private readonly injectedEld?: () => number | undefined;
116
- private readonly eld?: IntervalHistogram;
117
- private windowStart: number;
118
- private lastCpu?: NodeJS.CpuUsage;
119
- private lastCpuTime?: number;
120
- private saturated = false;
121
-
122
- constructor(opts: SaturationSamplerOptions = {}) {
123
- this.windowMs = opts.windowMs ?? SATURATION_WINDOW_MS;
124
- this.now = opts.now ?? Date.now;
125
- this.cpuUsage = opts.cpuUsage ?? (() => process.cpuUsage());
126
- this.loadAvg1m = opts.loadAvg1m ?? (() => os.loadavg()[0]);
127
- this.injectedEld = opts.eventLoopDelayMs;
128
- if (!opts.eventLoopDelayMs) {
129
- let histogram: IntervalHistogram | undefined;
130
- try {
131
- histogram = monitorEventLoopDelay({ resolution: ELD_RESOLUTION_MS });
132
- histogram.enable();
133
- } catch {
134
- histogram = undefined;
135
- }
136
- this.eld = histogram;
137
- }
138
- this.windowStart = this.now();
139
- }
140
-
141
- /** The current post-hysteresis verdict (last `read`'s saturated value). */
142
- get isSaturated(): boolean {
143
- return this.saturated;
144
- }
145
-
146
- /** Sample once and fold the reading through hysteresis. Synchronous by design. */
147
- read(thresholds: SaturationThresholds): SaturationSnapshot {
148
- const now = this.now();
149
-
150
- const cpuPercent = this.sampleCpu(now);
151
- const reading: SaturationReading = {
152
- eventLoopDelayMs: this.sampleEventLoopDelayMs(),
153
- cpuPercent,
154
- loadAvg1m: Math.round(this.loadAvg1m() * 100) / 100,
155
- };
156
-
157
- this.maybeRollWindow(now);
158
- this.saturated = nextSaturationState(this.saturated, reading, thresholds);
159
- return { saturated: this.saturated, reading };
160
- }
161
-
162
- /** Disable the owned histogram (bridge shutdown / test teardown). */
163
- dispose(): void {
164
- this.eld?.disable();
165
- }
166
-
167
- private sampleEventLoopDelayMs(): number | undefined {
168
- if (this.injectedEld) return this.injectedEld();
169
- if (!this.eld) return undefined;
170
- // `max` is nanoseconds since the last reset; the reset happens on window roll.
171
- return Math.round(this.eld.max / 1_000_000);
172
- }
173
-
174
- private sampleCpu(now: number): number | undefined {
175
- const cpu = this.cpuUsage();
176
- let cpuPercent: number | undefined;
177
- if (this.lastCpu && this.lastCpuTime !== undefined) {
178
- const elapsedMs = now - this.lastCpuTime;
179
- if (elapsedMs > 0) {
180
- const deltaMicros =
181
- cpu.user - this.lastCpu.user + (cpu.system - this.lastCpu.system);
182
- cpuPercent = Math.round((deltaMicros / (elapsedMs * 1000)) * 1000) / 10;
183
- }
184
- }
185
- this.lastCpu = cpu;
186
- this.lastCpuTime = now;
187
- return cpuPercent;
188
- }
189
-
190
- /** Roll the window once it has elapsed. Reset only in production (owned histogram). */
191
- private maybeRollWindow(now: number): void {
192
- if (now - this.windowStart < this.windowMs) return;
193
- this.windowStart = now;
194
- this.eld?.reset();
195
- }
196
- }
@@ -1,252 +0,0 @@
1
- /**
2
- * SubagentTickThrottle — bounds the rate of subagent `Agent` ticks on the
3
- * `tool_execution_update` carrier.
4
- *
5
- * Background: a running subagent feeds the dashboard over TWO carriers fed by
6
- * one `snapshotDetails()` object in the producer. The `subagents:*` carrier is
7
- * already coalesced to 250 ms by the producer's own emitter; the
8
- * `tool_execution_update` carrier has no throttle anywhere on its path, so its
9
- * rate is the subagent's RAW session-event rate (streaming `message_update`
10
- * deltas included) against a payload carrying the cumulative timeline.
11
- *
12
- * This class is that missing throttle, applied at the bridge (our code, seeing
13
- * every frame, downstream of every producer version in the wild — no producer
14
- * release needed). Semantics mirror the producer's proven `createProgressEmitter`
15
- * shape: leading edge fires immediately, within the window only the LATEST
16
- * frame is retained (safe because every frame is a FULL snapshot), and a
17
- * trailing timer emits it at window end.
18
- *
19
- * Two properties are load-bearing and easy to lose:
20
- *
21
- * - **Nothing after terminal.** On `tool_execution_end` a HELD frame is
22
- * DISCARDED, not flushed. This carrier never carries terminal state, so the
23
- * pending frame is a strictly stale intermediate snapshot; flushing it would
24
- * race the very overwrite the discard prevents (a stale tick landing after
25
- * the end event visibly re-opens a finished tool row).
26
- * - **Gates are re-checked at FIRE time, not at hold time.** `sessionReady`,
27
- * bridge liveness and the session id can all move while a frame is held, and
28
- * the send must go over the LIVE connection rather than a captured
29
- * reference. A failed gate drops the frame and counts it — that loss is
30
- * acceptable only because this carrier is not the recovery path (the
31
- * ephemeral carrier's retained snapshot is), and only because the counter
32
- * makes it visible.
33
- *
34
- * The key map is bounded independently of the terminal hook by an idle TTL, so
35
- * a run whose end event never arrived (e.g. dropped at the not-ready gate)
36
- * cannot leak one dead entry per run into a long session.
37
- *
38
- * See change: reduce-bridge-tick-bandwidth (D2/D3/D4/D6).
39
- */
40
-
41
- /** Counters for the throttle's two visible actions and two loss modes. */
42
- export interface SubagentTickThrottleStats {
43
- /** Ticks that reached the wire (leading edge + trailing sends). */
44
- tickForwarded: number;
45
- /** Held ticks superseded by a newer one within the same window (never sent). */
46
- tickCoalesced: number;
47
- /** Held ticks discarded because their run ended first. */
48
- tickDiscardedAtTerminal: number;
49
- /** Held ticks dropped at fire time by a gate (not ready / superseded / drift). */
50
- tickDroppedNotReady: number;
51
- }
52
-
53
- /** Idle-TTL default: two orders of magnitude above the 500 ms window, so it can
54
- * never sweep a live run, yet short enough that back-to-back subagent runs over
55
- * hours hold a handful of keys. */
56
- export const DEFAULT_TICK_IDLE_TTL_MS = 60_000;
57
-
58
- interface TickEntry<M> {
59
- /** Timestamp of the last tick that actually went out for this key. */
60
- lastSent: number;
61
- /** Timestamp of the last tick OBSERVED for this key (drives the idle TTL). */
62
- lastSeen: number;
63
- /** The single retained (latest-wins) frame waiting for the window to close. */
64
- pending?: { msg: M; sessionId: string };
65
- /** Armed trailing timer, if a frame is pending. */
66
- timer?: ReturnType<typeof setTimeout>;
67
- }
68
-
69
- export interface SubagentTickThrottleOptions<M> {
70
- /** Coalescing window in ms. `<= 0` disables the throttle entirely. */
71
- windowMs: number;
72
- /**
73
- * Emit a held frame. MUST resolve the live connection at call time — never
74
- * close over a connection captured when the frame was held.
75
- */
76
- send: (msg: M) => void;
77
- /**
78
- * Fire-time gate: bridge still active AND session ready AND the frame's
79
- * session id still current. False → the frame is dropped and counted.
80
- */
81
- canSend: (sessionId: string) => boolean;
82
- /** Idle TTL before an un-terminated key is swept. */
83
- idleTtlMs?: number;
84
- /** Injectable clock (tests). */
85
- now?: () => number;
86
- }
87
-
88
- export class SubagentTickThrottle<M = unknown> {
89
- private readonly entries = new Map<string, TickEntry<M>>();
90
- private sweepTimer?: ReturnType<typeof setTimeout>;
91
-
92
- readonly stats: SubagentTickThrottleStats = {
93
- tickForwarded: 0,
94
- tickCoalesced: 0,
95
- tickDiscardedAtTerminal: 0,
96
- tickDroppedNotReady: 0,
97
- };
98
-
99
- private readonly windowMs: number;
100
- private readonly idleTtlMs: number;
101
- private readonly now: () => number;
102
- private readonly opts: SubagentTickThrottleOptions<M>;
103
-
104
- constructor(opts: SubagentTickThrottleOptions<M>) {
105
- this.opts = opts;
106
- this.windowMs = opts.windowMs;
107
- this.idleTtlMs = opts.idleTtlMs ?? DEFAULT_TICK_IDLE_TTL_MS;
108
- this.now = opts.now ?? Date.now;
109
- }
110
-
111
- /** Whether the throttle is doing anything at all (config `0` => rollback path). */
112
- get enabled(): boolean {
113
- return this.windowMs > 0;
114
- }
115
-
116
- /** Distinct keys currently tracked (bounded by the terminal hook + idle TTL). */
117
- get size(): number {
118
- return this.entries.size;
119
- }
120
-
121
- /**
122
- * Offer a tick for `key` (the run's `toolCallId`).
123
- *
124
- * @returns `true` when the CALLER should send `msg` synchronously (leading
125
- * edge, or the throttle disabled); `false` when the throttle has taken
126
- * ownership of the frame and will send it (or discard it) later.
127
- */
128
- offer(key: string, msg: M, sessionId: string): boolean {
129
- if (!this.enabled) {
130
- this.stats.tickForwarded += 1;
131
- return true;
132
- }
133
- const now = this.now();
134
- const entry = this.entries.get(key);
135
-
136
- if (!entry || now - entry.lastSent >= this.windowMs) {
137
- // Leading edge. Under fake timers the trailing timer always fires on the
138
- // boundary, so a key at/past its window has no armed timer. In production
139
- // an I/O-driven `offer` can beat a DUE-but-unfired trailing timer: the
140
- // existing entry can still hold a `pending` frame + an armed `timer`. That
141
- // pending frame is superseded by this newer leading edge (latest-wins), so
142
- // count it as coalesced and cancel its stale timer — otherwise the counter
143
- // undercounts and the abandoned timer could later fire the fresh entry's
144
- // frame early.
145
- if (entry) {
146
- if (entry.timer) clearTimeout(entry.timer);
147
- if (entry.pending) this.stats.tickCoalesced += 1;
148
- }
149
- this.entries.set(key, { lastSent: now, lastSeen: now });
150
- this.stats.tickForwarded += 1;
151
- this.scheduleSweep();
152
- return true;
153
- }
154
-
155
- entry.lastSeen = now;
156
- // Latest-wins: an already-held frame is superseded and never sent. Safe
157
- // only because each frame is a FULL snapshot.
158
- if (entry.pending) this.stats.tickCoalesced += 1;
159
- entry.pending = { msg, sessionId };
160
- if (!entry.timer) {
161
- const delay = entry.lastSent + this.windowMs - now;
162
- entry.timer = setTimeout(() => this.fire(key), Math.max(0, delay));
163
- }
164
- this.scheduleSweep();
165
- return false;
166
- }
167
-
168
- /**
169
- * A run reached `tool_execution_end`. Discard (never flush) its held frame,
170
- * clear its timer and drop the key.
171
- */
172
- onTerminal(key: string): void {
173
- const entry = this.entries.get(key);
174
- if (!entry) return;
175
- if (entry.timer) clearTimeout(entry.timer);
176
- if (entry.pending) this.stats.tickDiscardedAtTerminal += 1;
177
- this.entries.delete(key);
178
- }
179
-
180
- /** Session change / shutdown: clear every timer, drop every held frame. */
181
- reset(): void {
182
- for (const entry of this.entries.values()) {
183
- if (entry.timer) clearTimeout(entry.timer);
184
- }
185
- this.entries.clear();
186
- if (this.sweepTimer) {
187
- clearTimeout(this.sweepTimer);
188
- this.sweepTimer = undefined;
189
- }
190
- }
191
-
192
- /** Trailing-edge send for `key`, gated at FIRE time. */
193
- private fire(key: string): void {
194
- const entry = this.entries.get(key);
195
- if (!entry) return;
196
- entry.timer = undefined;
197
- const held = entry.pending;
198
- entry.pending = undefined;
199
- if (!held) return;
200
- entry.lastSent = this.now();
201
- if (!this.opts.canSend(held.sessionId)) {
202
- this.stats.tickDroppedNotReady += 1;
203
- return;
204
- }
205
- this.stats.tickForwarded += 1;
206
- this.opts.send(held.msg);
207
- }
208
-
209
- /**
210
- * Keep exactly one sweep timer armed while any key is tracked. Re-armed from
211
- * the sweep itself, so an idle key is always reached within one TTL of its
212
- * last tick even if no further ticks arrive to drive a lazy sweep.
213
- */
214
- private scheduleSweep(): void {
215
- if (this.sweepTimer || this.entries.size === 0) return;
216
- this.sweepTimer = setTimeout(() => {
217
- this.sweepTimer = undefined;
218
- this.sweep();
219
- this.scheduleSweep();
220
- }, this.idleTtlMs);
221
- }
222
-
223
- private sweep(): void {
224
- const now = this.now();
225
- for (const [key, entry] of this.entries) {
226
- if (now - entry.lastSeen < this.idleTtlMs) continue;
227
- if (entry.timer) clearTimeout(entry.timer);
228
- this.entries.delete(key);
229
- }
230
- }
231
- }
232
-
233
- /**
234
- * The D2 scope predicate: is this `tool_execution_update` a SUBAGENT tick?
235
- *
236
- * Deliberately an allowlist of the same self-selecting pair the client's
237
- * durable hydration block keys on (`toolName === "Agent"` AND a
238
- * `partialResult.details.agentId`). A `Bash` update carrying an
239
- * agentId-lookalike, or an `Agent` update without one, is NOT throttled: an
240
- * over-matching predicate would silently rate-limit an unrelated streaming
241
- * tool, and the D6 counters are the tripwire for exactly that.
242
- */
243
- export function isSubagentTick(event: {
244
- toolName?: unknown;
245
- partialResult?: unknown;
246
- }): boolean {
247
- if (event.toolName !== "Agent") return false;
248
- const partial = event.partialResult as { details?: unknown } | undefined;
249
- if (!partial || typeof partial !== "object") return false;
250
- const details = partial.details as { agentId?: unknown } | undefined;
251
- return Boolean(details && typeof details === "object" && typeof details.agentId === "string");
252
- }
@@ -1,8 +0,0 @@
1
- /**
2
- * Install source of the required `pi-anthropic-messages` peer — its own tiny
3
- * module so the client's cold-landing peer probe (`anthropic-peer.ts`) can
4
- * read it without pulling `recommended-extensions.ts` (every entry's
5
- * description) into the gzipped index chunk (mdi-chunk-size cap). Bundlers
6
- * keep a module whole, so a sibling export of the manifest would not help.
7
- */
8
- export const ANTHROPIC_MESSAGES_SOURCE = "npm:@blackbelt-technology/pi-anthropic-messages";
@@ -1,9 +0,0 @@
1
- /**
2
- * Peer-probe key for the `pi-anthropic-messages` peer. Lives in shared so core
3
- * (client) and the flows-anthropic-bridge plugin read one constant without a
4
- * core→plugin import. The plugin re-exports it.
5
- * See change: decouple-plugins-from-core (task 2.1).
6
- */
7
-
8
- /** Legacy pre-rescope module name — also the only key the bridge's `probeAll` emits. */
9
- export const PEER_AM_LEGACY = "@pi/anthropic-messages";
@@ -1,219 +0,0 @@
1
- /**
2
- * Subagent wire-contract types + the pure helpers that fold subagent frames
3
- * into a `SubagentState`. Lives in shared (a non-plugin package) so the core
4
- * client reducer and the subagents plugin read one definition without a
5
- * core→plugin import; the plugin re-exports it.
6
- *
7
- * Producer of the contract: pi-dashboard-subagents extension
8
- * (https://github.com/BlackBeltTechnology/pi-dashboard-agents)
9
- *
10
- * See change: decouple-plugins-from-core (task 2.7); earlier: add-subagent-inspector.
11
- */
12
-
13
- /** A single entry in a subagent's run timeline. */
14
- export type SubagentTimelineEntry =
15
- | { kind: "tool"; toolName: string; input: unknown; output?: unknown; isError?: boolean; ts: number }
16
- | { kind: "text"; text: string; ts: number }
17
- | { kind: "thinking"; text: string; ts: number }
18
- | { kind: "error"; text: string; ts: number };
19
-
20
- /**
21
- * Bounded tail of a subagent's currently streaming block. `kind: "none"` means
22
- * nothing is streaming. See change: stream-subagent-reasoning-and-stable-card.
23
- */
24
- export type SubagentLiveTail = { kind: "thinking" | "text" | "none"; text: string };
25
-
26
- /** In-progress block from the delta stream. See change: add-plugin-bridge-contributions. */
27
- export type SubagentLiveBlock = {
28
- blockId: number;
29
- kind: "thinking" | "text";
30
- text: string;
31
- end: number;
32
- gap: boolean;
33
- };
34
-
35
- /** Per-subagent state held in SessionState.subagents. */
36
- export interface SubagentState {
37
- id: string;
38
- /**
39
- * Runner session id (v7) minted by the producer for the in-memory subagent
40
- * session, distinct from the v4 `id` (agentId). Optional: absent with an
41
- * older producer (< 0.2.3). When present, the reducer dual-indexes the state
42
- * under both this id and `id`. See change: resolve-subagent-inspector-by-session-id.
43
- */
44
- agentSessionId?: string;
45
- type: string;
46
- description: string;
47
- status: "created" | "running" | "completed" | "failed";
48
- /**
49
- * Client-only (never sent by the producer): the heal marker that produced the
50
- * CURRENT terminal `status` (e.g. `"session_ended"`); absent for a real
51
- * terminal or a running state. Lets a live tick revive a subagent a
52
- * fabricated `session_ended` heal failed, without reviving a real failure.
53
- * See change: fix-replay-fabricates-orphan-end-for-live-calls (D5).
54
- */
55
- healedBy?: string;
56
- result?: string;
57
- error?: string;
58
- durationMs?: number;
59
- tokens?: { input: number; output: number; total: number };
60
- toolUses?: number;
61
- /** Full per-step timeline. Producer: pi-dashboard-subagents extension. */
62
- entries?: SubagentTimelineEntry[];
63
- /** Live current-activity string (e.g. "reading src/foo.ts"). */
64
- activity?: string;
65
- /** Live tail of the streaming thinking/text block (producer ≥ 0.2.7). */
66
- liveTail?: SubagentLiveTail;
67
- /**
68
- * In-progress block assembled from `subagent_delta` pieces (producer ≥ 0.4.0).
69
- * `text` is the display text (may carry gap markers); `end` is the LOGICAL
70
- * block offset reached, so offsets stay exact across gaps. Cleared by the
71
- * block's `subagent_entry` (same `blockId`) or a terminal state.
72
- * See change: add-plugin-bridge-contributions (D7).
73
- */
74
- liveBlock?: SubagentLiveBlock;
75
- /** Highest `blockId` already finished — later pieces of it are ignored (D7 tombstone). */
76
- closedBlockMax?: number;
77
- /** Producer step count (`details.entryCount`, ≥ 0.3.0); stream-complete when filled steps reach it. */
78
- entryCount?: number;
79
- /** Display name for the agent (e.g. "code-reviewer"). Falls back to `type`. */
80
- displayName?: string;
81
- /** Short model name if different from parent. */
82
- modelName?: string;
83
- /** Effective thinking level of the child (producer ≥ 0.2.7), e.g. "high". */
84
- thinkingLevel?: string;
85
- /** Subagent type (e.g. "general-purpose"). May duplicate `type`. */
86
- subagentType?: string;
87
- /** Started-at epoch ms (set on subagent_started). */
88
- startedAt?: number;
89
- /**
90
- * Absolute filesystem path to the agent's `.md` definition file
91
- * (e.g. `~/.pi/agent/agents/Explore.md`). Producer sets it when the
92
- * subagent was sourced from a file. Rendered read-only in the inspector
93
- * header. See change: add-subagent-inspector §15.
94
- */
95
- agentMdPath?: string;
96
- }
97
-
98
- /** Max chars of a subagent live tail kept in client state. */
99
- const LIVE_TAIL_MAX = 280;
100
- const CLEARED_LIVE_TAIL: SubagentLiveTail = { kind: "none", text: "" };
101
-
102
- /**
103
- * Normalize a wire `details.liveTail`, never rejecting. Any plain object
104
- * overwrites: a valid thinking/text tail is kept (text capped at 280), every
105
- * other object — sentinel, malformed, future shape — becomes the cleared tail.
106
- * Non-objects return undefined (key ignored, prior state kept).
107
- * Also used by `AgentToolRenderer` for its session-less `details.liveTail`
108
- * fallback, so both paths normalize identically.
109
- * See change: stream-subagent-reasoning-and-stable-card (D8).
110
- */
111
- export function readLiveTail(raw: unknown): SubagentLiveTail | undefined {
112
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
113
- const { kind, text } = raw as Record<string, unknown>;
114
- if ((kind === "thinking" || kind === "text") && typeof text === "string") {
115
- return { kind, text: text.length > LIVE_TAIL_MAX ? text.slice(-LIVE_TAIL_MAX) : text };
116
- }
117
- return CLEARED_LIVE_TAIL;
118
- }
119
-
120
- /**
121
- * Pull optional Phase-2 fields (`entries`, `activity`, `displayName`, model,
122
- * etc.) from a streamed `AgentDetails`-shaped object. Returns a partial that
123
- * spreads into a `SubagentState`. All fields are optional; absent keys yield
124
- * `undefined` which leaves any existing value intact when used as a `...spread`.
125
- *
126
- * See change: add-subagent-inspector.
127
- */
128
- export function readSubagentDetails(
129
- details: Record<string, unknown> | undefined,
130
- ): Partial<SubagentState> {
131
- if (!details) return {};
132
- const out: Partial<SubagentState> = {};
133
- // D3 empty-array overwrite guard: only replace `entries` when the incoming
134
- // array is non-empty. An incoming `[]` (initial subagent_started, or a
135
- // late/reordered frame) omits the key so the `...spread` merge preserves any
136
- // already-populated timeline. Entries only ever grow within a run, so a
137
- // legitimate transition to zero entries never occurs.
138
- // See change: fix-subagent-live-detail-reliability (D3).
139
- if (Array.isArray(details.entries) && details.entries.length > 0) {
140
- out.entries = details.entries as SubagentTimelineEntry[];
141
- }
142
- if (typeof details.entryCount === "number" && Number.isSafeInteger(details.entryCount) && details.entryCount >= 0) {
143
- out.entryCount = details.entryCount;
144
- }
145
- if (typeof details.activity === "string") out.activity = details.activity;
146
- const liveTail = readLiveTail(details.liveTail);
147
- if (liveTail) out.liveTail = liveTail;
148
- if (typeof details.displayName === "string") out.displayName = details.displayName;
149
- if (typeof details.modelName === "string") out.modelName = details.modelName;
150
- if (typeof details.thinkingLevel === "string" && details.thinkingLevel) out.thinkingLevel = details.thinkingLevel;
151
- if (typeof details.subagentType === "string") out.subagentType = details.subagentType;
152
- if (typeof details.toolUses === "number") out.toolUses = details.toolUses;
153
- if (typeof details.durationMs === "number") out.durationMs = details.durationMs;
154
- if (typeof details.agentMdPath === "string") out.agentMdPath = details.agentMdPath;
155
- // Runner session id (v7): when the producer supplies it, persist it so the
156
- // reducer can dual-index the state under both the agentId and this id.
157
- // Absent with an older producer (< 0.2.3) → single-key, as today.
158
- // See change: resolve-subagent-inspector-by-session-id (D1/D2).
159
- if (typeof details.agentSessionId === "string") out.agentSessionId = details.agentSessionId;
160
- return out;
161
- }
162
-
163
- /** Filled step count of a (possibly sparse) streamed timeline. */
164
- export function countSteps(entries: SubagentTimelineEntry[] | undefined): number {
165
- if (!entries) return 0;
166
- let n = 0;
167
- for (const e of entries) if (e) n++;
168
- return n;
169
- }
170
-
171
- /** Display marker inserted where a streamed block lost a piece. */
172
- export const LIVE_BLOCK_GAP_MARKER = " … ";
173
-
174
- /**
175
- * Apply one `subagent_delta` piece to the in-progress block (D7): append when
176
- * contiguous, ignore a fully covered duplicate, append the uncovered tail of a
177
- * partial overlap, and mark a gap when the piece starts past the logical end.
178
- * Returns undefined when the piece must be ignored (closed block / stale id).
179
- */
180
- export function applyLiveBlockPiece(
181
- prev: SubagentState | undefined,
182
- piece: { blockId: number; kind: "thinking" | "text"; offset: number; text: string },
183
- ): SubagentLiveBlock | undefined {
184
- if (prev?.status === "completed" || prev?.status === "failed") return undefined;
185
- if (prev?.closedBlockMax !== undefined && piece.blockId <= prev.closedBlockMax) return undefined;
186
- let lb = prev?.liveBlock;
187
- if (lb && piece.blockId < lb.blockId) return undefined;
188
- if (!lb || lb.blockId !== piece.blockId) lb = { blockId: piece.blockId, kind: piece.kind, text: "", end: 0, gap: false };
189
- const { offset, text } = piece;
190
- const pieceEnd = offset + text.length;
191
- if (pieceEnd <= lb.end) return lb; // covered duplicate
192
- if (offset > lb.end) {
193
- return { ...lb, text: lb.text + (lb.text ? LIVE_BLOCK_GAP_MARKER : "") + text, end: pieceEnd, gap: true };
194
- }
195
- return { ...lb, text: lb.text + text.slice(lb.end - offset), end: pieceEnd };
196
- }
197
-
198
- /**
199
- * Dual-index a subagent state into the `subagents` map. Always sets the
200
- * canonical `state.id` (v4 agentId) key; when `state.agentSessionId` (v7) is
201
- * present, ALSO sets that key to the SAME reference so a lookup by either id
202
- * resolves the run. Both keys are a PAIR pointing at one object — any future
203
- * change deleting one on completion MUST delete the other (paired-key
204
- * invariant, design N1). Do NOT enumerate this map with `.values()/.entries()`
205
- * without de-duping by `state.id`: a dual-indexed agent appears under two keys.
206
- * See change: resolve-subagent-inspector-by-session-id (D2).
207
- */
208
- export function setSubagentState(map: Map<string, SubagentState>, state: SubagentState): void {
209
- // A streamed timeline (subagent_entry) never shrinks: a later tick or terminal
210
- // frame whose `entries` is empty or holds fewer steps keeps the resident list.
211
- // A legacy frame with at least as many steps still replaces it.
212
- // See change: add-plugin-bridge-contributions (D7).
213
- const prev = map.get(state.id);
214
- if (prev?.entries && prev.entries !== state.entries && countSteps(state.entries) < countSteps(prev.entries)) {
215
- state = { ...state, entries: prev.entries };
216
- }
217
- map.set(state.id, state);
218
- if (state.agentSessionId) map.set(state.agentSessionId, state);
219
- }