pi-better-server 0.4.0 → 0.6.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 (597) hide show
  1. package/package.json +8 -1
  2. package/scripts/copy-pi-test-providers.mjs +10 -0
  3. package/scripts/event-publication/README.md +26 -0
  4. package/scripts/event-publication/commit.mjs +21 -0
  5. package/scripts/event-publication/measure.mjs +87 -0
  6. package/scripts/event-publication/writer.mjs +6 -0
  7. package/scripts/measure-full-runtime/frontend.ts +24 -0
  8. package/scripts/measure-full-runtime/hosted-extension.ts +28 -0
  9. package/scripts/measure-full-runtime/probe.mjs +29 -0
  10. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  11. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  12. package/scripts/measure-full-runtime.mjs +146 -0
  13. package/scripts/measure-shared-reads/probe.mjs +26 -2
  14. package/scripts/measure-shared-reads.mjs +44 -9
  15. package/scripts/private-runtime/package-lock.json +66 -4
  16. package/scripts/private-runtime/package.json +10 -2
  17. package/scripts/source-provenance.mjs +31 -0
  18. package/scripts/test-on-pi.sh +3 -9
  19. package/src/handshake.ts +1 -1
  20. package/src/hosted-session.ts +32 -4
  21. package/src/maintenance.ts +35 -7
  22. package/src/registry.ts +28 -4
  23. package/src/runtime/attempt-invalidation.ts +54 -0
  24. package/src/runtime/background-history.ts +151 -45
  25. package/src/runtime/background-policy.ts +27 -0
  26. package/src/runtime/background-tools.ts +389 -0
  27. package/src/runtime/background.ts +410 -48
  28. package/src/runtime/cancellation.ts +28 -7
  29. package/src/runtime/catalog-sources.ts +199 -0
  30. package/src/runtime/catalog.ts +53 -21
  31. package/src/runtime/client.ts +22 -2
  32. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  33. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  34. package/src/runtime/domain/assignment-observation.mjs +71 -33
  35. package/src/runtime/domain/background/process-identity.mjs +20 -2
  36. package/src/runtime/domain/background/process.mjs +3 -3
  37. package/src/runtime/domain/background/registry.mjs +89 -4
  38. package/src/runtime/domain/background/types.mjs +1 -0
  39. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +83 -0
  40. package/src/runtime/domain/background-service/adapter-contract.ts +70 -0
  41. package/src/runtime/domain/background-service/batch.domain.mjs +91 -0
  42. package/src/runtime/domain/background-service/batch.ts +111 -0
  43. package/src/runtime/domain/background-service/conditions.domain.mjs +94 -0
  44. package/src/runtime/domain/background-service/conditions.ts +99 -0
  45. package/src/runtime/domain/background-service/delivery-observer.domain.mjs +37 -0
  46. package/src/runtime/domain/background-service/delivery-observer.ts +42 -0
  47. package/src/runtime/domain/background-service/failures.domain.mjs +209 -0
  48. package/src/runtime/domain/background-service/failures.ts +212 -0
  49. package/src/runtime/domain/background-service/goal-provider.domain.mjs +193 -0
  50. package/src/runtime/domain/background-service/goal-provider.ts +209 -0
  51. package/src/runtime/domain/background-service/index.domain.mjs +54 -0
  52. package/src/runtime/domain/background-service/index.ts +55 -0
  53. package/src/runtime/domain/background-service/logs.domain.mjs +129 -0
  54. package/src/runtime/domain/background-service/logs.ts +134 -0
  55. package/src/runtime/domain/background-service/maintenance.domain.mjs +95 -0
  56. package/src/runtime/domain/background-service/maintenance.ts +98 -0
  57. package/src/runtime/domain/background-service/managed-authority.domain.mjs +32 -0
  58. package/src/runtime/domain/background-service/managed-authority.ts +30 -0
  59. package/src/runtime/domain/background-service/managed-client.domain.mjs +79 -0
  60. package/src/runtime/domain/background-service/managed-client.ts +73 -0
  61. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +225 -0
  62. package/src/runtime/domain/background-service/managed-frontend.ts +176 -0
  63. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +492 -0
  64. package/src/runtime/domain/background-service/navigator-provider.ts +485 -0
  65. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  66. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  67. package/src/runtime/domain/background-service/observed-waits.domain.mjs +4080 -0
  68. package/src/runtime/domain/background-service/observed-waits.ts +4513 -0
  69. package/src/runtime/domain/background-service/output.domain.mjs +867 -0
  70. package/src/runtime/domain/background-service/output.ts +952 -0
  71. package/src/runtime/domain/background-service/process-identity.domain.mjs +129 -0
  72. package/src/runtime/domain/background-service/process-identity.ts +134 -0
  73. package/src/runtime/domain/background-service/process.domain.mjs +512 -0
  74. package/src/runtime/domain/background-service/process.ts +532 -0
  75. package/src/runtime/domain/background-service/prompt.domain.mjs +58 -0
  76. package/src/runtime/domain/background-service/prompt.ts +72 -0
  77. package/src/runtime/domain/background-service/registry.domain.mjs +460 -0
  78. package/src/runtime/domain/background-service/registry.ts +450 -0
  79. package/src/runtime/domain/background-service/remote-task-preset.domain.mjs +67 -0
  80. package/src/runtime/domain/background-service/remote-task-preset.ts +127 -0
  81. package/src/runtime/domain/background-service/runtime.domain.mjs +1511 -0
  82. package/src/runtime/domain/background-service/runtime.ts +1636 -0
  83. package/src/runtime/domain/background-service/sandbox.domain.mjs +735 -0
  84. package/src/runtime/domain/background-service/sandbox.ts +913 -0
  85. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +777 -0
  86. package/src/runtime/domain/background-service/shared-callback-batcher.ts +956 -0
  87. package/src/runtime/domain/background-service/shared-execution-policy.domain.mjs +50 -0
  88. package/src/runtime/domain/background-service/shared-execution-policy.ts +61 -0
  89. package/src/runtime/domain/background-service/shared-failure-observations.domain.mjs +1078 -0
  90. package/src/runtime/domain/background-service/shared-failure-observations.ts +1166 -0
  91. package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +126 -0
  92. package/src/runtime/domain/background-service/shared-harness-settings.ts +116 -0
  93. package/src/runtime/domain/background-service/shared-log-utils.domain.mjs +1223 -0
  94. package/src/runtime/domain/background-service/shared-log-utils.ts +1492 -0
  95. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +289 -0
  96. package/src/runtime/domain/background-service/shared-navigator-panels.ts +272 -0
  97. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +1930 -0
  98. package/src/runtime/domain/background-service/shared-navigator.ts +1962 -0
  99. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  100. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +189 -0
  101. package/src/runtime/domain/background-service/shared-operation-coordinator/index.domain.mjs +51 -0
  102. package/src/runtime/domain/background-service/shared-operation-coordinator/index.ts +122 -0
  103. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  104. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  105. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +163 -0
  106. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +174 -0
  107. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +66 -0
  108. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  109. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +87 -0
  110. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +90 -0
  111. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +97 -0
  112. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +139 -0
  113. package/src/runtime/domain/background-service/shared-operation-coordinator/src/errors.domain.mjs +12 -0
  114. package/src/runtime/domain/background-service/shared-operation-coordinator/src/errors.ts +79 -0
  115. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +342 -0
  116. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +513 -0
  117. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +283 -0
  118. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +458 -0
  119. package/src/runtime/domain/background-service/shared-operation-coordinator/src/recovery.domain.mjs +52 -0
  120. package/src/runtime/domain/background-service/shared-operation-coordinator/src/recovery.ts +55 -0
  121. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +114 -0
  122. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +140 -0
  123. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +280 -0
  124. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +442 -0
  125. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +420 -0
  126. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +441 -0
  127. package/src/runtime/domain/background-service/shared-operation-coordinator/src/sqlite.domain.mjs +194 -0
  128. package/src/runtime/domain/background-service/shared-operation-coordinator/src/sqlite.ts +239 -0
  129. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +275 -0
  130. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +585 -0
  131. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +120 -0
  132. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +142 -0
  133. package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-cancellation.domain.mjs +188 -0
  134. package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  135. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +25 -0
  136. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +707 -0
  137. package/src/runtime/domain/background-service/shared-operation-coordinator/src/upgrade.domain.mjs +22 -0
  138. package/src/runtime/domain/background-service/shared-operation-coordinator/src/upgrade.ts +22 -0
  139. package/src/runtime/domain/background-service/shared-operation-coordinator/src/validate.domain.mjs +234 -0
  140. package/src/runtime/domain/background-service/shared-operation-coordinator/src/validate.ts +241 -0
  141. package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.domain.mjs +851 -0
  142. package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.ts +1424 -0
  143. package/src/runtime/domain/background-service/shared-permission-blocker.domain.mjs +40 -0
  144. package/src/runtime/domain/background-service/shared-permission-blocker.ts +48 -0
  145. package/src/runtime/domain/background-service/shared-render-scheduler.domain.mjs +41 -0
  146. package/src/runtime/domain/background-service/shared-render-scheduler.ts +47 -0
  147. package/src/runtime/domain/background-service/shared-sandbox-core.domain.mjs +1531 -0
  148. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1757 -0
  149. package/src/runtime/domain/background-service/shared-sandbox-diagnostics.domain.mjs +591 -0
  150. package/src/runtime/domain/background-service/shared-sandbox-diagnostics.ts +491 -0
  151. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +698 -0
  152. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +979 -0
  153. package/src/runtime/domain/background-service/shared-stall-detector.domain.mjs +37 -0
  154. package/src/runtime/domain/background-service/shared-stall-detector.ts +69 -0
  155. package/src/runtime/domain/background-service/shared-work-client.mjs +303 -0
  156. package/src/runtime/domain/background-service/stall-attention.domain.mjs +29 -0
  157. package/src/runtime/domain/background-service/stall-attention.ts +31 -0
  158. package/src/runtime/domain/background-service/stall.domain.mjs +57 -0
  159. package/src/runtime/domain/background-service/stall.ts +57 -0
  160. package/src/runtime/domain/background-service/supervisor/README.md +111 -0
  161. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +90 -0
  162. package/src/runtime/domain/background-service/supervisor/generated/conditions.mjs +96 -0
  163. package/src/runtime/domain/background-service/supervisor/generated/identity.mjs +95 -0
  164. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +131 -0
  165. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +514 -0
  166. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +872 -0
  167. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +609 -0
  168. package/src/runtime/domain/background-service/supervisor/generated/types.mjs +50 -0
  169. package/src/runtime/domain/background-service/supervisor/identity.domain.mjs +93 -0
  170. package/src/runtime/domain/background-service/supervisor/identity.ts +99 -0
  171. package/src/runtime/domain/background-service/supervisor/index.domain.mjs +22 -0
  172. package/src/runtime/domain/background-service/supervisor/index.ts +37 -0
  173. package/src/runtime/domain/background-service/supervisor/invocation.domain.mjs +30 -0
  174. package/src/runtime/domain/background-service/supervisor/invocation.ts +44 -0
  175. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +870 -0
  176. package/src/runtime/domain/background-service/supervisor/runner.ts +982 -0
  177. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +605 -0
  178. package/src/runtime/domain/background-service/supervisor/store.ts +651 -0
  179. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +721 -0
  180. package/src/runtime/domain/background-service/supervisor/supervisor.ts +804 -0
  181. package/src/runtime/domain/background-service/supervisor/types.domain.mjs +48 -0
  182. package/src/runtime/domain/background-service/supervisor/types.ts +394 -0
  183. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +60 -0
  184. package/src/runtime/domain/background-service/task-diagnostics.ts +71 -0
  185. package/src/runtime/domain/background-service/tools.domain.mjs +1050 -0
  186. package/src/runtime/domain/background-service/tools.ts +1142 -0
  187. package/src/runtime/domain/background-service/types.domain.mjs +5 -0
  188. package/src/runtime/domain/background-service/types.ts +236 -0
  189. package/src/runtime/domain/background-service/work-observation.domain.mjs +176 -0
  190. package/src/runtime/domain/background-service/work-observation.ts +144 -0
  191. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  192. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  193. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  194. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  195. package/src/runtime/domain/coordinator/src/background-parent-callbacks.mjs +65 -0
  196. package/src/runtime/domain/coordinator/src/background-requests.mjs +86 -0
  197. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  198. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  199. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  200. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  201. package/src/runtime/domain/coordinator/src/schema.mjs +73 -21
  202. package/src/runtime/domain/coordinator/src/store.mjs +32 -3
  203. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +119 -0
  204. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  205. package/src/runtime/domain/coordinator/src/upgrade.mjs +22 -0
  206. package/src/runtime/domain/health-observation.d.mts +3 -1
  207. package/src/runtime/domain/health-observation.mjs +189 -190
  208. package/src/runtime/domain/log-cursor.d.mts +2 -0
  209. package/src/runtime/domain/log-cursor.mjs +85 -16
  210. package/src/runtime/domain/parse.d.mts +4 -1
  211. package/src/runtime/domain/parse.mjs +50 -5
  212. package/src/runtime/domain/sandbox-policy/README.md +633 -0
  213. package/src/runtime/domain/sandbox-policy/background-admission.domain.mjs +83 -0
  214. package/src/runtime/domain/sandbox-policy/background-admission.ts +75 -0
  215. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +245 -0
  216. package/src/runtime/domain/sandbox-policy/commands.ts +336 -0
  217. package/src/runtime/domain/sandbox-policy/deny-rules.domain.mjs +440 -0
  218. package/src/runtime/domain/sandbox-policy/deny-rules.ts +620 -0
  219. package/src/runtime/domain/sandbox-policy/diagnostics-command.domain.mjs +30 -0
  220. package/src/runtime/domain/sandbox-policy/diagnostics-command.ts +27 -0
  221. package/src/runtime/domain/sandbox-policy/events.domain.mjs +49 -0
  222. package/src/runtime/domain/sandbox-policy/events.ts +85 -0
  223. package/src/runtime/domain/sandbox-policy/files.domain.mjs +153 -0
  224. package/src/runtime/domain/sandbox-policy/files.ts +224 -0
  225. package/src/runtime/domain/sandbox-policy/index.domain.mjs +289 -0
  226. package/src/runtime/domain/sandbox-policy/index.ts +386 -0
  227. package/src/runtime/domain/sandbox-policy/package.json +66 -0
  228. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +36 -0
  229. package/src/runtime/domain/sandbox-policy/permission-settings.ts +46 -0
  230. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +309 -0
  231. package/src/runtime/domain/sandbox-policy/permissions-page.ts +295 -0
  232. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +98 -0
  233. package/src/runtime/domain/sandbox-policy/permissions.ts +125 -0
  234. package/src/runtime/domain/sandbox-policy/policy.domain.mjs +80 -0
  235. package/src/runtime/domain/sandbox-policy/policy.ts +102 -0
  236. package/src/runtime/domain/sandbox-policy/preferences.domain.mjs +55 -0
  237. package/src/runtime/domain/sandbox-policy/preferences.ts +82 -0
  238. package/src/runtime/domain/sandbox-policy/rules-page.domain.mjs +138 -0
  239. package/src/runtime/domain/sandbox-policy/rules-page.ts +176 -0
  240. package/src/runtime/domain/sandbox-policy/session-permissions.domain.mjs +22 -0
  241. package/src/runtime/domain/sandbox-policy/session-permissions.ts +24 -0
  242. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +126 -0
  243. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +116 -0
  244. package/src/runtime/domain/sandbox-policy/shared-permission-blocker.domain.mjs +40 -0
  245. package/src/runtime/domain/sandbox-policy/shared-permission-blocker.ts +48 -0
  246. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.domain.mjs +1531 -0
  247. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1757 -0
  248. package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.domain.mjs +591 -0
  249. package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.ts +491 -0
  250. package/src/runtime/domain/sandbox-policy/shared-task-application.domain.mjs +185 -0
  251. package/src/runtime/domain/sandbox-policy/shared-task-application.ts +185 -0
  252. package/src/runtime/domain/sandbox-policy/shared-task-apply-patch.domain.mjs +416 -0
  253. package/src/runtime/domain/sandbox-policy/shared-task-apply-patch.ts +409 -0
  254. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +325 -0
  255. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +335 -0
  256. package/src/runtime/domain/sandbox-policy/shared-task-files.domain.mjs +346 -0
  257. package/src/runtime/domain/sandbox-policy/shared-task-files.ts +342 -0
  258. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  259. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  260. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +220 -0
  261. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +209 -0
  262. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +227 -0
  263. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +224 -0
  264. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +92 -0
  265. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +123 -0
  266. package/src/runtime/domain/sandbox-policy/shell.domain.mjs +93 -0
  267. package/src/runtime/domain/sandbox-policy/shell.ts +129 -0
  268. package/src/runtime/domain/sandbox-policy/state.domain.mjs +307 -0
  269. package/src/runtime/domain/sandbox-policy/state.ts +408 -0
  270. package/src/runtime/domain/sandbox-policy/status.domain.mjs +64 -0
  271. package/src/runtime/domain/sandbox-policy/status.ts +76 -0
  272. package/src/runtime/domain/sandbox-policy/subagent-admission.domain.mjs +69 -0
  273. package/src/runtime/domain/sandbox-policy/subagent-admission.ts +60 -0
  274. package/src/runtime/domain/subagents/CONTEXT.md +202 -0
  275. package/src/runtime/domain/subagents/PRODUCT.md +49 -0
  276. package/src/runtime/domain/subagents/README.md +201 -0
  277. package/src/runtime/domain/subagents/agent-catalog.mjs +64 -0
  278. package/src/runtime/domain/subagents/agent-commands.domain.mjs +822 -0
  279. package/src/runtime/domain/subagents/agent-commands.ts +905 -0
  280. package/src/runtime/domain/subagents/agent-inspection.domain.mjs +398 -0
  281. package/src/runtime/domain/subagents/agent-inspection.ts +574 -0
  282. package/src/runtime/domain/subagents/agent-operations.domain.mjs +40 -0
  283. package/src/runtime/domain/subagents/agent-operations.ts +61 -0
  284. package/src/runtime/domain/subagents/agent-session-settings.domain.mjs +112 -0
  285. package/src/runtime/domain/subagents/agent-session-settings.ts +118 -0
  286. package/src/runtime/domain/subagents/agents-catalog-tool.domain.mjs +84 -0
  287. package/src/runtime/domain/subagents/agents-catalog-tool.ts +118 -0
  288. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +276 -0
  289. package/src/runtime/domain/subagents/assignment-outcomes.ts +212 -0
  290. package/src/runtime/domain/subagents/assignment-projection.mjs +261 -0
  291. package/src/runtime/domain/subagents/assignment-report.domain.mjs +174 -0
  292. package/src/runtime/domain/subagents/assignment-report.ts +156 -0
  293. package/src/runtime/domain/subagents/batch.mjs +275 -0
  294. package/src/runtime/domain/subagents/callback-fields.domain.mjs +72 -0
  295. package/src/runtime/domain/subagents/callback-fields.ts +95 -0
  296. package/src/runtime/domain/subagents/capacity.mjs +108 -0
  297. package/src/runtime/domain/subagents/catalog-editor.domain.mjs +98 -0
  298. package/src/runtime/domain/subagents/catalog-editor.ts +125 -0
  299. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +104 -0
  300. package/src/runtime/domain/subagents/catalog-host-admission.ts +85 -0
  301. package/src/runtime/domain/subagents/catalog-identity.domain.mjs +222 -0
  302. package/src/runtime/domain/subagents/catalog-identity.ts +258 -0
  303. package/src/runtime/domain/subagents/catalog-overlay.domain.mjs +9 -0
  304. package/src/runtime/domain/subagents/catalog-overlay.ts +10 -0
  305. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +164 -0
  306. package/src/runtime/domain/subagents/catalog-preferences.ts +139 -0
  307. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +366 -0
  308. package/src/runtime/domain/subagents/catalog-resolver.ts +540 -0
  309. package/src/runtime/domain/subagents/catalog-runtime.domain.mjs +570 -0
  310. package/src/runtime/domain/subagents/catalog-runtime.ts +680 -0
  311. package/src/runtime/domain/subagents/catalog-schema.domain.mjs +1331 -0
  312. package/src/runtime/domain/subagents/catalog-schema.ts +1563 -0
  313. package/src/runtime/domain/subagents/catalog-skill-edits.domain.mjs +95 -0
  314. package/src/runtime/domain/subagents/catalog-skill-edits.ts +116 -0
  315. package/src/runtime/domain/subagents/catalog-store.domain.mjs +808 -0
  316. package/src/runtime/domain/subagents/catalog-store.ts +1006 -0
  317. package/src/runtime/domain/subagents/catalog-ui.domain.mjs +651 -0
  318. package/src/runtime/domain/subagents/catalog-ui.ts +611 -0
  319. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  320. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  321. package/src/runtime/domain/subagents/child-codemode.domain.mjs +16 -0
  322. package/src/runtime/domain/subagents/child-codemode.ts +17 -0
  323. package/src/runtime/domain/subagents/child-dependencies.mjs +193 -0
  324. package/src/runtime/domain/subagents/child-incidents.domain.mjs +170 -0
  325. package/src/runtime/domain/subagents/child-incidents.ts +169 -0
  326. package/src/runtime/domain/subagents/child-operations.domain.mjs +986 -0
  327. package/src/runtime/domain/subagents/child-operations.ts +1191 -0
  328. package/src/runtime/domain/subagents/child-ownership.domain.mjs +205 -0
  329. package/src/runtime/domain/subagents/child-ownership.ts +160 -0
  330. package/src/runtime/domain/subagents/child-preflight.mjs +38 -0
  331. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  332. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  333. package/src/runtime/domain/subagents/child-runtime.mjs +67 -0
  334. package/src/runtime/domain/subagents/child-steer.domain.mjs +109 -0
  335. package/src/runtime/domain/subagents/child-steer.ts +102 -0
  336. package/src/runtime/domain/subagents/cleanup.domain.mjs +818 -0
  337. package/src/runtime/domain/subagents/cleanup.ts +1017 -0
  338. package/src/runtime/domain/subagents/codex-import.domain.mjs +575 -0
  339. package/src/runtime/domain/subagents/codex-import.ts +717 -0
  340. package/src/runtime/domain/subagents/completion.domain.mjs +6 -0
  341. package/src/runtime/domain/subagents/completion.mjs +152 -0
  342. package/src/runtime/domain/subagents/completion.ts +11 -0
  343. package/src/runtime/domain/subagents/config.domain.mjs +248 -0
  344. package/src/runtime/domain/subagents/config.json +15 -0
  345. package/src/runtime/domain/subagents/config.ts +328 -0
  346. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +38 -0
  347. package/src/runtime/domain/subagents/continuation-authority.ts +31 -0
  348. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  349. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  350. package/src/runtime/domain/subagents/continuation.domain.mjs +942 -0
  351. package/src/runtime/domain/subagents/continuation.ts +1051 -0
  352. package/src/runtime/domain/subagents/delegation.domain.mjs +19 -0
  353. package/src/runtime/domain/subagents/delegation.ts +24 -0
  354. package/src/runtime/domain/subagents/effective-settings.domain.mjs +130 -0
  355. package/src/runtime/domain/subagents/effective-settings.ts +184 -0
  356. package/src/runtime/domain/subagents/extensions.domain.mjs +6 -0
  357. package/src/runtime/domain/subagents/extensions.mjs +164 -0
  358. package/src/runtime/domain/subagents/extensions.ts +19 -0
  359. package/src/runtime/domain/subagents/failures.domain.mjs +362 -0
  360. package/src/runtime/domain/subagents/failures.ts +319 -0
  361. package/src/runtime/domain/subagents/finalization.domain.mjs +168 -0
  362. package/src/runtime/domain/subagents/finalization.ts +218 -0
  363. package/src/runtime/domain/subagents/git-remotes.domain.mjs +351 -0
  364. package/src/runtime/domain/subagents/git-remotes.ts +413 -0
  365. package/src/runtime/domain/subagents/git-workspace.domain.mjs +337 -0
  366. package/src/runtime/domain/subagents/git-workspace.ts +430 -0
  367. package/src/runtime/domain/subagents/goal-provider.domain.mjs +125 -0
  368. package/src/runtime/domain/subagents/goal-provider.ts +132 -0
  369. package/src/runtime/domain/subagents/health-observation.domain.mjs +617 -0
  370. package/src/runtime/domain/subagents/health-observation.ts +818 -0
  371. package/src/runtime/domain/subagents/health-surface.mjs +284 -0
  372. package/src/runtime/domain/subagents/health.domain.mjs +261 -0
  373. package/src/runtime/domain/subagents/health.ts +343 -0
  374. package/src/runtime/domain/subagents/historical-attention.domain.mjs +37 -0
  375. package/src/runtime/domain/subagents/historical-attention.ts +35 -0
  376. package/src/runtime/domain/subagents/incident-model.domain.mjs +322 -0
  377. package/src/runtime/domain/subagents/incident-model.ts +358 -0
  378. package/src/runtime/domain/subagents/index.domain.mjs +4731 -0
  379. package/src/runtime/domain/subagents/index.ts +4781 -0
  380. package/src/runtime/domain/subagents/launch-abort.domain.mjs +13 -0
  381. package/src/runtime/domain/subagents/launch-abort.ts +21 -0
  382. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  383. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  384. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  385. package/src/runtime/domain/subagents/lifecycle.domain.mjs +265 -0
  386. package/src/runtime/domain/subagents/lifecycle.ts +360 -0
  387. package/src/runtime/domain/subagents/list.domain.mjs +2 -0
  388. package/src/runtime/domain/subagents/list.mjs +152 -0
  389. package/src/runtime/domain/subagents/list.ts +19 -0
  390. package/src/runtime/domain/subagents/log-cursor.domain.mjs +217 -0
  391. package/src/runtime/domain/subagents/log-cursor.ts +268 -0
  392. package/src/runtime/domain/subagents/managed-background-capability.domain.mjs +10 -0
  393. package/src/runtime/domain/subagents/managed-background-capability.ts +9 -0
  394. package/src/runtime/domain/subagents/managed-failure-worker.mjs +36 -0
  395. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +48 -0
  396. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +75 -0
  397. package/src/runtime/domain/subagents/managed-launch-client.ts +59 -0
  398. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +627 -0
  399. package/src/runtime/domain/subagents/managed-launch-host.ts +504 -0
  400. package/src/runtime/domain/subagents/managed-launch-journal.mjs +17 -0
  401. package/src/runtime/domain/subagents/managed-launch-ownership.domain.mjs +29 -0
  402. package/src/runtime/domain/subagents/managed-launch-ownership.ts +22 -0
  403. package/src/runtime/domain/subagents/managed-launch-port.domain.mjs +2 -0
  404. package/src/runtime/domain/subagents/managed-launch-port.ts +25 -0
  405. package/src/runtime/domain/subagents/managed-launch-recovery.domain.mjs +29 -0
  406. package/src/runtime/domain/subagents/managed-launch-recovery.ts +45 -0
  407. package/src/runtime/domain/subagents/managed-worker-bridge.domain.mjs +63 -0
  408. package/src/runtime/domain/subagents/managed-worker-bridge.ts +48 -0
  409. package/src/runtime/domain/subagents/managed-worker.mjs +13 -0
  410. package/src/runtime/domain/subagents/model-resolution-core.domain.mjs +822 -0
  411. package/src/runtime/domain/subagents/model-resolution-core.ts +1074 -0
  412. package/src/runtime/domain/subagents/model-resolution.domain.mjs +22 -0
  413. package/src/runtime/domain/subagents/model-resolution.ts +32 -0
  414. package/src/runtime/domain/subagents/navigator.domain.mjs +6 -0
  415. package/src/runtime/domain/subagents/navigator.mjs +1233 -0
  416. package/src/runtime/domain/subagents/navigator.ts +39 -0
  417. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +1012 -0
  418. package/src/runtime/domain/subagents/operation-bridge-types.ts +1156 -0
  419. package/src/runtime/domain/subagents/outage-observations.domain.mjs +84 -0
  420. package/src/runtime/domain/subagents/outage-observations.ts +73 -0
  421. package/src/runtime/domain/subagents/output-payload.domain.mjs +767 -0
  422. package/src/runtime/domain/subagents/output-payload.ts +987 -0
  423. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  424. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  425. package/src/runtime/domain/subagents/package.json +86 -0
  426. package/src/runtime/domain/subagents/park-checkpoint.domain.mjs +55 -0
  427. package/src/runtime/domain/subagents/park-checkpoint.ts +61 -0
  428. package/src/runtime/domain/subagents/parse.domain.mjs +1218 -0
  429. package/src/runtime/domain/subagents/parse.ts +1451 -0
  430. package/src/runtime/domain/subagents/permission-policy.domain.mjs +232 -0
  431. package/src/runtime/domain/subagents/permission-policy.ts +291 -0
  432. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  433. package/src/runtime/domain/subagents/registry.domain.mjs +1584 -0
  434. package/src/runtime/domain/subagents/registry.ts +1904 -0
  435. package/src/runtime/domain/subagents/role-assignment.domain.mjs +104 -0
  436. package/src/runtime/domain/subagents/role-assignment.ts +141 -0
  437. package/src/runtime/domain/subagents/roles/role.architect.md +13 -0
  438. package/src/runtime/domain/subagents/roles/role.developer.md +16 -0
  439. package/src/runtime/domain/subagents/roles/role.explorer.md +13 -0
  440. package/src/runtime/domain/subagents/roles/role.product-manager.md +13 -0
  441. package/src/runtime/domain/subagents/roles/role.researcher.md +13 -0
  442. package/src/runtime/domain/subagents/roles/role.reviewer.md +13 -0
  443. package/src/runtime/domain/subagents/roles/role.writer.md +12 -0
  444. package/src/runtime/domain/subagents/sandbox.domain.mjs +64 -0
  445. package/src/runtime/domain/subagents/sandbox.ts +92 -0
  446. package/src/runtime/domain/subagents/session-selection.domain.mjs +32 -0
  447. package/src/runtime/domain/subagents/session-selection.ts +35 -0
  448. package/src/runtime/domain/subagents/session-store.domain.mjs +489 -0
  449. package/src/runtime/domain/subagents/session-store.ts +468 -0
  450. package/src/runtime/domain/subagents/settings-page.domain.mjs +313 -0
  451. package/src/runtime/domain/subagents/settings-page.ts +363 -0
  452. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +777 -0
  453. package/src/runtime/domain/subagents/shared-callback-batcher.ts +956 -0
  454. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +70 -0
  455. package/src/runtime/domain/subagents/shared-catalog.ts +61 -0
  456. package/src/runtime/domain/subagents/shared-execution-policy.domain.mjs +50 -0
  457. package/src/runtime/domain/subagents/shared-execution-policy.ts +61 -0
  458. package/src/runtime/domain/subagents/shared-failure-observations.domain.mjs +1078 -0
  459. package/src/runtime/domain/subagents/shared-failure-observations.ts +1166 -0
  460. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +126 -0
  461. package/src/runtime/domain/subagents/shared-harness-settings.ts +116 -0
  462. package/src/runtime/domain/subagents/shared-log-utils.domain.mjs +1223 -0
  463. package/src/runtime/domain/subagents/shared-log-utils.ts +1492 -0
  464. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +289 -0
  465. package/src/runtime/domain/subagents/shared-navigator-panels.ts +272 -0
  466. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +1930 -0
  467. package/src/runtime/domain/subagents/shared-navigator.ts +1962 -0
  468. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  469. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +189 -0
  470. package/src/runtime/domain/subagents/shared-operation-coordinator/index.domain.mjs +51 -0
  471. package/src/runtime/domain/subagents/shared-operation-coordinator/index.ts +122 -0
  472. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  473. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  474. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +163 -0
  475. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +174 -0
  476. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +66 -0
  477. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  478. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +87 -0
  479. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +90 -0
  480. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +97 -0
  481. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +139 -0
  482. package/src/runtime/domain/subagents/shared-operation-coordinator/src/errors.domain.mjs +12 -0
  483. package/src/runtime/domain/subagents/shared-operation-coordinator/src/errors.ts +79 -0
  484. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +342 -0
  485. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +513 -0
  486. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +283 -0
  487. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +458 -0
  488. package/src/runtime/domain/subagents/shared-operation-coordinator/src/recovery.domain.mjs +52 -0
  489. package/src/runtime/domain/subagents/shared-operation-coordinator/src/recovery.ts +55 -0
  490. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +114 -0
  491. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +140 -0
  492. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +280 -0
  493. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +442 -0
  494. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +420 -0
  495. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +441 -0
  496. package/src/runtime/domain/subagents/shared-operation-coordinator/src/sqlite.domain.mjs +194 -0
  497. package/src/runtime/domain/subagents/shared-operation-coordinator/src/sqlite.ts +239 -0
  498. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +275 -0
  499. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +585 -0
  500. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +120 -0
  501. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +142 -0
  502. package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-cancellation.domain.mjs +188 -0
  503. package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  504. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +25 -0
  505. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +707 -0
  506. package/src/runtime/domain/subagents/shared-operation-coordinator/src/upgrade.domain.mjs +22 -0
  507. package/src/runtime/domain/subagents/shared-operation-coordinator/src/upgrade.ts +22 -0
  508. package/src/runtime/domain/subagents/shared-operation-coordinator/src/validate.domain.mjs +234 -0
  509. package/src/runtime/domain/subagents/shared-operation-coordinator/src/validate.ts +241 -0
  510. package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.domain.mjs +851 -0
  511. package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.ts +1424 -0
  512. package/src/runtime/domain/subagents/shared-permission-blocker.domain.mjs +40 -0
  513. package/src/runtime/domain/subagents/shared-permission-blocker.ts +48 -0
  514. package/src/runtime/domain/subagents/shared-render-scheduler.domain.mjs +41 -0
  515. package/src/runtime/domain/subagents/shared-render-scheduler.ts +47 -0
  516. package/src/runtime/domain/subagents/shared-sandbox-core.domain.mjs +1531 -0
  517. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1757 -0
  518. package/src/runtime/domain/subagents/shared-sandbox-diagnostics.domain.mjs +591 -0
  519. package/src/runtime/domain/subagents/shared-sandbox-diagnostics.ts +491 -0
  520. package/src/runtime/domain/subagents/shared-stall-detector.domain.mjs +37 -0
  521. package/src/runtime/domain/subagents/shared-stall-detector.ts +69 -0
  522. package/src/runtime/domain/subagents/shared-task-application.domain.mjs +185 -0
  523. package/src/runtime/domain/subagents/shared-task-application.ts +185 -0
  524. package/src/runtime/domain/subagents/shared-task-apply-patch.domain.mjs +416 -0
  525. package/src/runtime/domain/subagents/shared-task-apply-patch.ts +409 -0
  526. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +325 -0
  527. package/src/runtime/domain/subagents/shared-task-exec.ts +335 -0
  528. package/src/runtime/domain/subagents/shared-task-files.domain.mjs +346 -0
  529. package/src/runtime/domain/subagents/shared-task-files.ts +342 -0
  530. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  531. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  532. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +220 -0
  533. package/src/runtime/domain/subagents/shared-task-process-list.ts +209 -0
  534. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +227 -0
  535. package/src/runtime/domain/subagents/shared-task-sandbox.ts +224 -0
  536. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +92 -0
  537. package/src/runtime/domain/subagents/shared-task-tools.ts +123 -0
  538. package/src/runtime/domain/subagents/shared-work-client.mjs +303 -0
  539. package/src/runtime/domain/subagents/shared-worktree-context.domain.mjs +142 -0
  540. package/src/runtime/domain/subagents/shared-worktree-context.ts +158 -0
  541. package/src/runtime/domain/subagents/skill-picker.domain.mjs +316 -0
  542. package/src/runtime/domain/subagents/skill-picker.ts +353 -0
  543. package/src/runtime/domain/subagents/skills.domain.mjs +138 -0
  544. package/src/runtime/domain/subagents/skills.ts +183 -0
  545. package/src/runtime/domain/subagents/spawn.domain.mjs +72 -0
  546. package/src/runtime/domain/subagents/spawn.ts +80 -0
  547. package/src/runtime/domain/subagents/stop.domain.mjs +184 -0
  548. package/src/runtime/domain/subagents/stop.ts +217 -0
  549. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +101 -0
  550. package/src/runtime/domain/subagents/subagent-tools.ts +137 -0
  551. package/src/runtime/domain/subagents/task-guard.domain.mjs +163 -0
  552. package/src/runtime/domain/subagents/task-guard.ts +144 -0
  553. package/src/runtime/domain/subagents/task-policy.domain.mjs +201 -0
  554. package/src/runtime/domain/subagents/task-policy.ts +236 -0
  555. package/src/runtime/domain/subagents/task-runtime.mjs +53 -0
  556. package/src/runtime/domain/subagents/task-tool-owner.domain.mjs +18 -0
  557. package/src/runtime/domain/subagents/task-tool-owner.ts +21 -0
  558. package/src/runtime/domain/subagents/thinking.domain.mjs +22 -0
  559. package/src/runtime/domain/subagents/thinking.ts +28 -0
  560. package/src/runtime/domain/subagents/tier-policy.domain.mjs +75 -0
  561. package/src/runtime/domain/subagents/tier-policy.ts +126 -0
  562. package/src/runtime/domain/subagents/timing-notifications.domain.mjs +51 -0
  563. package/src/runtime/domain/subagents/timing-notifications.ts +37 -0
  564. package/src/runtime/domain/subagents/timing.domain.mjs +487 -0
  565. package/src/runtime/domain/subagents/timing.ts +634 -0
  566. package/src/runtime/domain/subagents/tools.domain.mjs +558 -0
  567. package/src/runtime/domain/subagents/tools.ts +629 -0
  568. package/src/runtime/domain/subagents/widget.domain.mjs +6 -0
  569. package/src/runtime/domain/subagents/widget.mjs +246 -0
  570. package/src/runtime/domain/subagents/widget.ts +30 -0
  571. package/src/runtime/domain/subagents/work-observation.domain.mjs +316 -0
  572. package/src/runtime/domain/subagents/work-observation.ts +248 -0
  573. package/src/runtime/domain/subagents/worker-catalog.domain.mjs +120 -0
  574. package/src/runtime/domain/subagents/worker-catalog.ts +162 -0
  575. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +1009 -0
  576. package/src/runtime/domain/subagents/worker-operations-host.ts +1238 -0
  577. package/src/runtime/domain/subagents/worker-waits.domain.mjs +2336 -0
  578. package/src/runtime/domain/subagents/worker-waits.ts +2878 -0
  579. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +52 -0
  580. package/src/runtime/domain/subagents/workspace-scope.ts +50 -0
  581. package/src/runtime/health-config.ts +27 -11
  582. package/src/runtime/log-checkpoints.ts +117 -0
  583. package/src/runtime/mutation-store.ts +5 -4
  584. package/src/runtime/queries.ts +27 -3
  585. package/src/runtime/query-executor.ts +178 -34
  586. package/src/runtime/query-worker.mjs +119 -22
  587. package/src/runtime/read-model.ts +939 -113
  588. package/src/runtime/read-watchdog-probe.ts +4 -0
  589. package/src/runtime/result-supervision.ts +188 -16
  590. package/src/runtime/source-watch.ts +175 -0
  591. package/src/runtime/subagent-launch.ts +73 -0
  592. package/src/runtime/work-budget.ts +130 -0
  593. package/src/runtime/work-client.d.mts +8 -0
  594. package/src/runtime/work-client.mjs +150 -7
  595. package/src/server.ts +185 -22
  596. package/src/session-activity.ts +26 -4
  597. package/src/version.ts +1 -1
@@ -0,0 +1,1078 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/shared-failure-observations.ts. Do not edit directly.
2
+ // Generated from packages/failure-observations/index.ts. Do not edit directly.
3
+ import { appendFileSync, closeSync, existsSync, openSync, readFileSync, mkdirSync, statSync } from "node:fs";
4
+ import { dirname } from "node:path";
5
+ import { createHash } from "node:crypto";
6
+ import { isPermissionBlocker, permissionBlockerKey } from "./shared-permission-blocker.domain.mjs";
7
+ export const INCIDENT_DISPOSITIONS = Object.freeze(["recovered", "superseded", "expected", "open"]);
8
+ export function emptyFailureState() {
9
+ return { version: 1, seen: [], observations: {}, delivered: {} };
10
+ }
11
+ export function failureIdentity(...parts) {
12
+ return createHash("sha256").update(JSON.stringify(parts)).digest("hex").slice(0, 32);
13
+ }
14
+ function text(value, fallback) {
15
+ // The 400-unit cut can split a surrogate pair; a lone half would render as U+FFFD (#332).
16
+ return dropLoneSurrogates((value || fallback).replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 400));
17
+ }
18
+ /** Agent tool attempts: the agent handles its own tool errors, so one failure is not yet actionable. */
19
+ export const AGENT_TOOL_CATEGORY = "tool";
20
+ /** A command the confined intent bash refused before running (malformed or reused intent). Agent-owned, never grouped. */
21
+ export const REJECTED_INTENT_CATEGORY = "rejected-intent";
22
+ /** The same unresolved agent tool operation failing this many times is treated as stuck. */
23
+ export const REPEATED_FAILURE_THRESHOLD = 3;
24
+ /** Caller-chosen intent identifiers: short, printable, no whitespace. */
25
+ export const INTENT_ID_PATTERN = "^[A-Za-z0-9][A-Za-z0-9._:/-]{0,63}$";
26
+ const INTENT_ID = new RegExp(INTENT_ID_PATTERN);
27
+ export const MAX_EXPECTED_EXIT_CODES = 16;
28
+ const INTENT_FIELDS = ["operationId", "attemptId", "expectedExitCodes"];
29
+ /**
30
+ * Pi's own argument coercion for the intent fields (pi-ai `validateToolArguments` against the confined
31
+ * bash schema, where each field is `anyOf: [field schema, null]`). Pi applies it before execute, but the
32
+ * process log and session record keep the raw arguments; mirroring it lets the parent's replay read
33
+ * the declaration the child executed with (#332).
34
+ * - ids: a number or boolean becomes its string; `""` fails the pattern and falls through to null.
35
+ * - exit codes: array items that read as integers become integers (null -> 0, true -> 1);
36
+ * a scalar `0`, `""`, or `false` falls through to null.
37
+ */
38
+ function coerceInteger(value) {
39
+ if (value === null)
40
+ return 0;
41
+ if (typeof value === "string" && value.trim() !== "" && Number.isInteger(Number(value)))
42
+ return Number(value);
43
+ if (typeof value === "boolean")
44
+ return value ? 1 : 0;
45
+ return value;
46
+ }
47
+ function normalizeIntentField(key, value) {
48
+ if (value == null)
49
+ return undefined;
50
+ if (key === "expectedExitCodes") {
51
+ if (value === 0 || value === "" || value === false)
52
+ return undefined;
53
+ if (!Array.isArray(value))
54
+ return value;
55
+ // 0 is a no-op declaration: exit 0 is already success. A list of only zeros declares nothing.
56
+ const codes = value.map(coerceInteger).filter((code) => code !== 0);
57
+ if (codes.length === 0 && value.length > 0)
58
+ return undefined;
59
+ return codes.length === value.length && codes.every((code, index) => code === value[index]) ? value : codes;
60
+ }
61
+ if (value === "")
62
+ return undefined;
63
+ return typeof value === "number" || typeof value === "boolean" ? String(value) : value;
64
+ }
65
+ /**
66
+ * The one normalization of intent-bearing arguments. An explicit `null` intent field means "not
67
+ * declared", exactly like an omitted one: models routinely send optional fields as null, and Pi's
68
+ * argument validation drops or nulls them before a tool runs, while the process log and session
69
+ * record keep the raw arguments. Values Pi would coerce are coerced the same way, and `0` is dropped
70
+ * from `expectedExitCodes`. Every reader of intent, the executing tool and the replay alike, and the
71
+ * exact operation identity go through this, so all see the same declaration from the same input.
72
+ * Malformed values are kept as they are for the validator to refuse.
73
+ */
74
+ export function withoutAbsentIntent(args) {
75
+ if (!args || typeof args !== "object" || Array.isArray(args))
76
+ return args;
77
+ const input = args;
78
+ let out;
79
+ for (const key of INTENT_FIELDS) {
80
+ if (!(key in input))
81
+ continue;
82
+ const value = normalizeIntentField(key, input[key]);
83
+ if (value === input[key])
84
+ continue;
85
+ out ??= { ...input };
86
+ if (value === undefined)
87
+ delete out[key];
88
+ else
89
+ out[key] = value;
90
+ }
91
+ return (out ?? args);
92
+ }
93
+ /**
94
+ * Validate structured intent fields after `withoutAbsentIntent`. Absent fields are fine; malformed
95
+ * ones are an error, and the caller must not run the command. `names` renames fields in the error
96
+ * (e.g. snake_case parameters). `0` in `expectedExitCodes` is accepted and dropped (#332).
97
+ */
98
+ export function readCommandIntent(args, names = {}) {
99
+ const input = withoutAbsentIntent((args && typeof args === "object" ? args : {}));
100
+ const intent = {};
101
+ for (const key of ["operationId", "attemptId"]) {
102
+ const value = input[key];
103
+ if (value === undefined)
104
+ continue;
105
+ if (typeof value !== "string" || !INTENT_ID.test(value)) {
106
+ return { intent: {}, error: `${names[key] ?? key} must match ${INTENT_ID_PATTERN}` };
107
+ }
108
+ intent[key] = value;
109
+ }
110
+ const codes = input.expectedExitCodes;
111
+ if (codes !== undefined) {
112
+ if (!Array.isArray(codes) || codes.length === 0 || codes.length > MAX_EXPECTED_EXIT_CODES ||
113
+ !codes.every((code) => Number.isInteger(code) && code >= 1 && code <= 255) || new Set(codes).size !== codes.length) {
114
+ return { intent: {}, error: `${names.expectedExitCodes ?? "expectedExitCodes"} must be 1-${MAX_EXPECTED_EXIT_CODES} distinct integers from 1 to 255 (0 is allowed and ignored)` };
115
+ }
116
+ intent.expectedExitCodes = [...codes];
117
+ }
118
+ return { intent };
119
+ }
120
+ /** The one current incident with this id, if it is still in the reduced state. */
121
+ export function findIncident(state, id) {
122
+ return Object.values(state.observations).find((item) => item.id === id);
123
+ }
124
+ /**
125
+ * Current actionability, derived only from reduced structured state. Lifecycle is not an input.
126
+ * Agent tool failures need an explicit `open` disposition or a repeated failure of the same
127
+ * operation; other producer failures (exit, model, supervision, watch) are actionable at once.
128
+ */
129
+ export function requiresAction(x) {
130
+ if (x.status !== "unresolved" || x.category === "observation-incomplete")
131
+ return false;
132
+ if (x.category !== AGENT_TOOL_CATEGORY && x.category !== REJECTED_INTENT_CATEGORY)
133
+ return true;
134
+ return x.disposition?.disposition === "open" || x.count >= REPEATED_FAILURE_THRESHOLD;
135
+ }
136
+ export function failureLabel(x) {
137
+ if (x.category === "observation-incomplete")
138
+ return "Observation incomplete";
139
+ if (x.status === "expected")
140
+ return "Expected failure";
141
+ if (x.status === "resolved")
142
+ return "Recovered";
143
+ if (x.status === "superseded")
144
+ return "Superseded";
145
+ return requiresAction(x) ? "Action required" : "Unclassified failure observation";
146
+ }
147
+ /**
148
+ * Whether an incident needs someone's action now: an unresolved `Action required` incident
149
+ * (non-tool failure, repeated tool failure, or disposed `open`) or an observation gap. Unclassified
150
+ * and expected failures are history: counted on every surface, listed only on explicit request.
151
+ */
152
+ export function needsAction(x) {
153
+ return x.status === "unresolved" && (x.category === "observation-incomplete" || requiresAction(x));
154
+ }
155
+ /** Validate a disposition against the reduced state. Returns the rejection reason, or undefined. */
156
+ export function validateDisposition(state, event) {
157
+ if (event.kind !== "disposition")
158
+ return "Not a disposition event";
159
+ if (!event.disposition || !INCIDENT_DISPOSITIONS.includes(event.disposition))
160
+ return `Unknown disposition ${JSON.stringify(event.disposition ?? "")}`;
161
+ const ids = event.incidents;
162
+ if (!Array.isArray(ids) || ids.length === 0)
163
+ return "A disposition must name at least one incident";
164
+ if (ids.some((id) => typeof id !== "string" || !id))
165
+ return "Incident ids must be non-empty strings";
166
+ if (new Set(ids).size !== ids.length)
167
+ return "A disposition names the same incident more than once";
168
+ if (typeof event.reason !== "string" || !event.reason.trim())
169
+ return "A disposition requires a reason";
170
+ if ((event.disposition === "recovered" || event.disposition === "superseded") && (typeof event.evidence !== "string" || !event.evidence.trim())) {
171
+ return `A ${event.disposition} disposition requires evidence`;
172
+ }
173
+ for (const id of ids) {
174
+ const current = findIncident(state, id);
175
+ if (!current) {
176
+ return Object.hasOwn(state.history ?? {}, id) || Object.hasOwn(state.resolved ?? {}, id)
177
+ ? `Incident ${id} is already disposed` : `Unknown incident ${id}`;
178
+ }
179
+ if (current.category === "observation-incomplete")
180
+ return `Incident ${id} is an observation gap; it cannot be disposed`;
181
+ if (current.status !== "unresolved")
182
+ return `Incident ${id} is already disposed (${failureLabel(current).toLowerCase()})`;
183
+ if (event.disposition === "open" && current.disposition?.disposition === "open")
184
+ return `Incident ${id} is already open`;
185
+ }
186
+ if (event.permissionBlockers !== undefined) {
187
+ if (event.disposition !== "open" || !Array.isArray(event.permissionBlockers) || !event.permissionBlockers.length ||
188
+ event.permissionBlockers.length > 20 || !event.permissionBlockers.every(isPermissionBlocker))
189
+ return "Invalid permission blocker metadata";
190
+ const bound = new Set();
191
+ for (const blocker of event.permissionBlockers) {
192
+ const current = blocker.incidentId ? findIncident(state, blocker.incidentId) : undefined;
193
+ if (!current || !ids.includes(current.id) || current.category !== "tool" || current.operation !== blocker.operation ||
194
+ blocker.context !== "worker" || blocker.basis !== "agent-reported" || blocker.remoteOutcome !== "unknown" ||
195
+ blocker.policySnapshotId !== undefined || bound.has(current.id))
196
+ return "Permission blocker must name an unresolved failed worker attempt";
197
+ bound.add(current.id);
198
+ }
199
+ if (bound.size !== ids.length)
200
+ return "Permission blocker metadata must cover every target";
201
+ }
202
+ return undefined;
203
+ }
204
+ /** Pure transition. Lifecycle is deliberately not an input or an output. */
205
+ export function reduceFailure(state, event, observedAt) {
206
+ if (state.seen.includes(event.id))
207
+ return state;
208
+ if (event.permissionBlockers !== undefined && event.kind !== "disposition")
209
+ return state;
210
+ // Invalid dispositions fail closed: nothing changes and the id is not consumed.
211
+ if (event.kind === "disposition" && validateDisposition(state, event))
212
+ return state;
213
+ const next = { ...state, seen: [...state.seen, event.id],
214
+ observations: { ...state.observations }, delivered: { ...state.delivered } };
215
+ if (event.kind === "delivered") {
216
+ for (const id of event.incidents ?? [])
217
+ next.delivered = { ...next.delivered, [id]: observedAt };
218
+ return next;
219
+ }
220
+ if (event.kind === "disposition") {
221
+ const at = event.at ?? observedAt;
222
+ const record = { eventId: event.id, disposition: event.disposition, incidents: [...event.incidents],
223
+ reason: text(event.reason, ""), ...(event.evidence ? { evidence: text(event.evidence, "") } : {}), at };
224
+ if (event.permissionBlockers)
225
+ record.permissionBlockers = event.permissionBlockers.map(x => ({ ...x }));
226
+ for (const id of record.incidents) {
227
+ const [key, current] = Object.entries(next.observations).find(([, item]) => item.id === id);
228
+ const status = record.disposition === "recovered" ? "resolved" : record.disposition === "superseded" ? "superseded"
229
+ : record.disposition === "expected" ? "expected" : current.status;
230
+ next.observations[key] = { ...current, status, disposition: record,
231
+ ...(record.permissionBlockers ? { permissionBlockers: record.permissionBlockers.filter(x => x.incidentId === id) } : {}),
232
+ ...(status === "resolved" || status === "superseded" ? { resolvedAt: at } : {}) };
233
+ if (status === "resolved" || status === "superseded")
234
+ next.resolved = { ...next.resolved, [id]: at };
235
+ }
236
+ next.dispositions = [...(state.dispositions ?? []), record];
237
+ return next;
238
+ }
239
+ const key = failureIdentity(event.operation);
240
+ const previous = state.observations[key];
241
+ if (event.kind === "recovered") {
242
+ // Only an unresolved incident recovers; an expected one keeps its classification.
243
+ if (previous && previous.status === "unresolved" && event.incidents?.includes(previous.id)) {
244
+ next.observations[key] = { ...previous, status: "resolved", resolvedAt: event.at ?? observedAt };
245
+ next.resolved = { ...state.resolved, [previous.id]: event.at ?? observedAt };
246
+ }
247
+ return next;
248
+ }
249
+ const active = previous && previous.status !== "resolved" && previous.status !== "superseded" &&
250
+ !(previous.status === "expected" && !event.expected);
251
+ if (previous && !active)
252
+ next.history = { ...state.history, [previous.id]: previous };
253
+ next.observations[key] = {
254
+ id: active ? previous.id : event.id, operation: event.operation,
255
+ status: active ? previous.status : event.expected ? "expected" : "unresolved",
256
+ category: event.kind === "incomplete" ? "observation-incomplete" : event.category ?? "operation",
257
+ summary: text(event.summary, "Operation failed"), evidence: event.evidence,
258
+ firstObservedAt: active ? previous.firstObservedAt : observedAt,
259
+ lastObservedAt: observedAt, lastSequence: next.seen.length, at: event.at,
260
+ count: active ? previous.count + 1 : 1,
261
+ ...(active && previous.disposition ? { disposition: previous.disposition } : {}),
262
+ ...(active && previous.permissionBlockers ? { permissionBlockers: previous.permissionBlockers } : {}),
263
+ };
264
+ return next;
265
+ }
266
+ function priority(x) {
267
+ if (x.category === "observation-incomplete")
268
+ return 0;
269
+ if (x.status === "expected")
270
+ return 3;
271
+ return requiresAction(x) ? 1 : 2;
272
+ }
273
+ /** Current (not recovered or superseded) incidents in priority order. History is excluded. */
274
+ export function activeFailures(state) {
275
+ return Object.values(state.observations).filter((x) => x.status !== "resolved" && x.status !== "superseded")
276
+ .sort((a, b) => priority(a) - priority(b) || (b.lastSequence ?? 0) - (a.lastSequence ?? 0) || b.lastObservedAt - a.lastObservedAt);
277
+ }
278
+ /** Incidents that need action now, priority order. */
279
+ export function actionableFailures(state) {
280
+ return activeFailures(state).filter(needsAction);
281
+ }
282
+ /** Only currently actionable reports, not closed history or arbitrary tool-result claims. */
283
+ export function actionablePermissionBlockers(state) {
284
+ const unique = new Map();
285
+ for (const incident of actionableFailures(state)) {
286
+ for (const blocker of incident.permissionBlockers ?? []) {
287
+ if (isPermissionBlocker(blocker))
288
+ unique.set(permissionBlockerKey(blocker), { ...blocker });
289
+ }
290
+ }
291
+ return [...unique.values()];
292
+ }
293
+ function closedOrder(a, b) {
294
+ return (b.lastSequence ?? 0) - (a.lastSequence ?? 0) || b.lastObservedAt - a.lastObservedAt;
295
+ }
296
+ /** The incidents a scope lists, in the order rows render. */
297
+ export function scopedFailures(state, scope = "actionable") {
298
+ if (scope !== "all")
299
+ return actionableFailures(state);
300
+ const active = activeFailures(state);
301
+ const closed = failureHistory(state).filter((x) => x.status === "resolved" || x.status === "superseded").sort(closedOrder);
302
+ return [...active, ...closed];
303
+ }
304
+ /** Every incident ever reduced, current and closed. Nothing is removed. */
305
+ export function failureHistory(state) {
306
+ return [...Object.values(state.history ?? {}), ...Object.values(state.observations)];
307
+ }
308
+ /** Separate facts: current actionability, retained classification, and closed history. */
309
+ export function failureCounts(state) {
310
+ const counts = { actionRequired: 0, unclassified: 0, expected: 0, incomplete: 0, recovered: 0, superseded: 0 };
311
+ for (const x of failureHistory(state)) {
312
+ if (x.status === "resolved")
313
+ counts.recovered += 1;
314
+ else if (x.status === "superseded")
315
+ counts.superseded += 1;
316
+ else if (x.category === "observation-incomplete")
317
+ counts.incomplete += 1;
318
+ else if (x.status === "expected")
319
+ counts.expected += 1;
320
+ else if (requiresAction(x))
321
+ counts.actionRequired += 1;
322
+ else
323
+ counts.unclassified += 1;
324
+ }
325
+ return counts;
326
+ }
327
+ function plural(count, one, many = `${one}s`) {
328
+ return `${count} ${count === 1 ? one : many}`;
329
+ }
330
+ /**
331
+ * Counts of incidents that do not need action, as one short fragment, or undefined when there are
332
+ * none: e.g. `8 unclassified tool errors · 2 expected · 1 recovered`.
333
+ */
334
+ export function historyCountsText(state) {
335
+ const counts = failureCounts(state);
336
+ const parts = [
337
+ counts.unclassified ? plural(counts.unclassified, "unclassified tool error") : "",
338
+ counts.expected ? `${counts.expected} expected` : "",
339
+ counts.recovered ? `${counts.recovered} recovered` : "",
340
+ counts.superseded ? `${counts.superseded} superseded` : "",
341
+ ].filter(Boolean);
342
+ return parts.length ? parts.join(" · ") : undefined;
343
+ }
344
+ /** One line for a run where nothing needs action but history exists. No cursor: history is explicit. */
345
+ export function quietFailureLine(state) {
346
+ if (actionableFailures(state).length)
347
+ return undefined;
348
+ const counts = failureCounts(state);
349
+ // Closed incidents alone are not worth a line on every surface; they ride along with current ones.
350
+ if (!counts.unclassified && !counts.expected)
351
+ return undefined;
352
+ const history = historyCountsText(state);
353
+ return history ? `No failures need action · ${history} (history)` : undefined;
354
+ }
355
+ /** Trailing history count after actionable rows, or undefined when there is none. */
356
+ export function historyTailLine(state) {
357
+ const history = historyCountsText(state);
358
+ return history ? `Also in history: ${history}` : undefined;
359
+ }
360
+ /**
361
+ * Current incident cursor prefix. The prefix is the cursor format: it replaced
362
+ * the in-payload `x` version field so that two position witnesses fit in the
363
+ * same space (these cursors are printed inside 1 KiB incident summaries, where
364
+ * every byte competes with the count line). `i1.` cursors are still recognised
365
+ * for routing but decode as stale.
366
+ */
367
+ const INCIDENT_CURSOR_PREFIX = "i2.";
368
+ const LEGACY_INCIDENT_CURSOR_PREFIXES = ["i1."];
369
+ const encoder = new TextEncoder();
370
+ /** Longest summary or disposition-reason excerpt a compact row shows, in UTF-8 bytes. */
371
+ export const COMPACT_EXCERPT_BYTES = 120;
372
+ const TOOL_RESULT_WRAPPER = /\{"content":\[\{"type":"text","text":"/;
373
+ const JSON_ESCAPES = { '"': '"', "\\": "\\", "/": "/", b: " ", f: " ", n: " ", r: " ", t: " " };
374
+ /** Remove unpaired UTF-16 surrogates, which would otherwise encode as U+FFFD. */
375
+ function dropLoneSurrogates(value) {
376
+ return value.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "");
377
+ }
378
+ /**
379
+ * A tool error recorded as its raw result JSON (`{"content":[{"type":"text","text":"…"}]}`, often
380
+ * already cut mid-string) rendered as the text it carries. Decoding is tolerant of the cut; text
381
+ * before the wrapper (e.g. `read failed: `) is kept.
382
+ */
383
+ export function unwrapToolResultText(value) {
384
+ const match = TOOL_RESULT_WRAPPER.exec(value);
385
+ if (!match)
386
+ return value;
387
+ let out = "";
388
+ let i = match.index + match[0].length;
389
+ while (i < value.length) {
390
+ const ch = value[i];
391
+ if (ch === '"')
392
+ break;
393
+ if (ch !== "\\") {
394
+ out += ch;
395
+ i += 1;
396
+ continue;
397
+ }
398
+ const next = value[i + 1];
399
+ if (next === "u") {
400
+ const hex = value.slice(i + 2, i + 6);
401
+ if (!/^[0-9a-fA-F]{4}$/.test(hex))
402
+ break;
403
+ out += String.fromCharCode(parseInt(hex, 16));
404
+ i += 6;
405
+ continue;
406
+ }
407
+ if (next === undefined || !(next in JSON_ESCAPES))
408
+ break;
409
+ out += JSON_ESCAPES[next];
410
+ i += 2;
411
+ }
412
+ // A wrapper cut inside a surrogate pair, or an escape of one half, leaves a lone surrogate
413
+ // (rendered as U+FFFD); decoded control characters (e.g. an escaped NUL) are not shown either.
414
+ const decoded = dropLoneSurrogates(out).replace(/[\x00-\x1f\x7f]/g, " ");
415
+ return `${value.slice(0, match.index)}${decoded}`.replace(/\s+/g, " ").trim();
416
+ }
417
+ /** At most `max` UTF-8 bytes of `value`, whole code points, ending in `…` when cut. */
418
+ export function capUtf8(value, max) {
419
+ const bytes = encoder.encode(value);
420
+ if (bytes.length <= max)
421
+ return value;
422
+ const ellipsis = "…";
423
+ const cut = utf8Prefix(bytes, Math.max(0, max - utf8Length(ellipsis)));
424
+ return `${Buffer.from(bytes.subarray(0, cut)).toString("utf8").trimEnd()}${ellipsis}`;
425
+ }
426
+ /**
427
+ * Evidence reference as a compact row shows it: an absolute path loses its directories
428
+ * (`/private/var/…/runs/<id>/output.log#byte=N` → `output.log#byte=N`); the run or task id already
429
+ * names the log. Full rows and the journal keep the whole reference.
430
+ */
431
+ export function shortEvidence(evidence) {
432
+ const match = /^(?:[A-Za-z]:)?[\\/](?:[^#]*[\\/])?([^\\/#]+)(#.*)?$/.exec(evidence);
433
+ return match ? `${match[1]}${match[2] ?? ""}` : evidence;
434
+ }
435
+ function failureRow(x, detail = "compact") {
436
+ const time = x.at === undefined ? `observed ${new Date(x.firstObservedAt).toISOString()}` : new Date(x.at).toISOString();
437
+ const compact = detail !== "full";
438
+ const permission = Boolean(x.permissionBlockers?.length);
439
+ let annotation = "";
440
+ if (x.permissionBlockers?.length) {
441
+ const resources = x.permissionBlockers.map(b => b.resource).join(", ");
442
+ annotation = ` · Worker permission blocker: ${resources} (agent-reported; remote outcome unknown; not a foreground denial). No remote authorization or successful validation inferred.`;
443
+ if (needsAction(x))
444
+ annotation += " Changed worker settings require a fresh launch.";
445
+ }
446
+ // Full rows (raw evidence) show the journal summary verbatim; compact rows unwrap and cap it.
447
+ const summary = compact && permission ? "Permission access failure" : compact ? capUtf8(dropLoneSurrogates(unwrapToolResultText(x.summary)).replace(/\s+/g, " ").trim(), COMPACT_EXCERPT_BYTES) : x.summary;
448
+ const reason = x.disposition ? text(x.disposition.reason, "") : "";
449
+ const disposition = x.disposition ? ` · ${x.disposition.disposition}${compact && permission ? "" : `: ${compact ? capUtf8(reason, COMPACT_EXCERPT_BYTES) : reason}`}` : "";
450
+ const evidence = x.evidence && !(compact && permission) ? text(x.evidence, "") : "";
451
+ const proof = !compact && permission && x.disposition?.evidence ? ` · disposition evidence: ${text(x.disposition.evidence, "")}` : "";
452
+ return `${failureLabel(x)} · ${time} · ${summary}${x.count > 1 ? ` (${x.count} occurrences)` : ""}${disposition}${evidence ? ` · evidence: ${compact ? shortEvidence(evidence) : evidence}` : ""}${proof}${annotation}`;
453
+ }
454
+ /**
455
+ * Incident rows in priority order. By default, only incidents that need action, as compact rows;
456
+ * `scope: "all"` lists history too and `detail: "full"` keeps whole excerpts and evidence paths.
457
+ * Consumers page these; they are not a lossy summary.
458
+ */
459
+ export function formatFailureLines(state, options = {}) {
460
+ return scopedFailures(state, options.scope).map((x) => failureRow(x, options.detail));
461
+ }
462
+ function closedHistoryLine(state) {
463
+ const counts = failureCounts(state);
464
+ if (!counts.recovered && !counts.superseded)
465
+ return undefined;
466
+ const parts = [counts.recovered ? `${counts.recovered} recovered` : "", counts.superseded ? `${counts.superseded} superseded` : ""].filter(Boolean);
467
+ return `Closed incidents retained in history: ${parts.join(" · ")}.`;
468
+ }
469
+ /** Shared priority text, placed BEFORE assistant progress on every consumer surface. */
470
+ export function formatFailureSummary(state) {
471
+ const lines = formatFailureLines(state);
472
+ if (!lines.length)
473
+ return quietFailureLine(state) ?? "";
474
+ const rows = lines.slice(0, 5);
475
+ if (lines.length > 5)
476
+ rows.push(`${lines.length - 5} additional active failure observations retained in the failure journal.`);
477
+ const history = historyTailLine(state);
478
+ if (history)
479
+ rows.push(history);
480
+ return rows.join("\n");
481
+ }
482
+ /** Incident rows for exactly `incidents`, priority order. Unknown ids fail closed. */
483
+ export function pendingAttentionRows(state, incidents) {
484
+ const wanted = new Set(incidents);
485
+ const rows = activeFailures(state).filter((x) => wanted.has(x.id));
486
+ if (rows.length !== wanted.size)
487
+ throw new Error("Failure incident evidence is unavailable; defer notification delivery");
488
+ return rows.map((x) => failureRow(x));
489
+ }
490
+ /** Count of other active incidents, which a notification references but never re-lists. */
491
+ export function pendingAttentionNote(state, incidents) {
492
+ const wanted = new Set(incidents);
493
+ const others = activeFailures(state).filter((x) => !wanted.has(x.id)).length;
494
+ return others > 0 ? `${others} other active failure observation${others === 1 ? " was" : "s were"} reported earlier or not actionable; not repeated here.` : undefined;
495
+ }
496
+ /**
497
+ * Attention text for exactly `incidents` (normally `pending.incidents`). Earlier delivered or
498
+ * non-actionable incidents are counted, never re-listed. Unknown ids fail closed.
499
+ */
500
+ export function formatPendingAttention(state, incidents, options = {}) {
501
+ const rows = pendingAttentionRows(state, incidents);
502
+ const max = options.maxRows ?? 5;
503
+ const lines = rows.slice(0, max);
504
+ if (rows.length > max)
505
+ lines.push(`${rows.length - max} additional pending incidents retained in the failure journal.`);
506
+ const note = pendingAttentionNote(state, incidents);
507
+ if (note)
508
+ lines.push(note);
509
+ return lines.join("\n");
510
+ }
511
+ /** The terminal fact that lifecycle success is not evidence of correct work. Kept whenever it fits and never cut mid-sentence (#325). */
512
+ export const CORRECTNESS_NOTE = "Work correctness was not inferred from lifecycle alone.";
513
+ /**
514
+ * Terminal/completion facts: actionable and incomplete incidents from `incidents` as rows,
515
+ * unclassified agent tool failures as a count. Lifecycle is reported by the caller, separately.
516
+ */
517
+ export function terminalFailureParts(state, incidents = []) {
518
+ const wanted = new Set(incidents);
519
+ const reportable = (x) => requiresAction(x) || x.category === "observation-incomplete";
520
+ const rows = activeFailures(state).filter((x) => wanted.has(x.id) && reportable(x)).map((x) => failureRow(x));
521
+ const notes = [];
522
+ const earlier = activeFailures(state).filter((x) => !wanted.has(x.id) && reportable(x)).length;
523
+ if (earlier)
524
+ notes.push(`${earlier} actionable incident${earlier === 1 ? " was" : "s were"} reported earlier; not repeated here.`);
525
+ const counts = failureCounts(state);
526
+ const unclassifiedNote = counts.unclassified
527
+ ? `${counts.unclassified} earlier tool failure${counts.unclassified === 1 ? "" : "s"} remain${counts.unclassified === 1 ? "s" : ""} unclassified.` : undefined;
528
+ if (unclassifiedNote)
529
+ notes.push(unclassifiedNote);
530
+ if (counts.expected)
531
+ notes.push(`${counts.expected} expected failure${counts.expected === 1 ? "" : "s"} recorded.`);
532
+ const history = closedHistoryLine(state);
533
+ if (history)
534
+ notes.push(history);
535
+ if (counts.unclassified || counts.actionRequired)
536
+ notes.push(CORRECTNESS_NOTE);
537
+ return { rows, notes, ...(unclassifiedNote ? { unclassifiedNote } : {}) };
538
+ }
539
+ export function formatTerminalFailureFacts(state, incidents = []) {
540
+ const { rows, notes } = terminalFailureParts(state, incidents);
541
+ const lines = rows.slice(0, 5);
542
+ if (rows.length > 5)
543
+ lines.push(`${rows.length - 5} additional actionable incidents retained in the failure journal.`);
544
+ return [...lines, ...notes].join("\n");
545
+ }
546
+ /**
547
+ * Signature of every observation's reportable state. A change here is a
548
+ * failure-only change even when log bytes are unchanged; receipts and replay
549
+ * bookkeeping do not change it.
550
+ */
551
+ export function failureRevision(state) {
552
+ return failureIdentity(Object.values(state.observations)
553
+ .map((item) => [item.id, item.status, item.category, item.count, item.lastSequence ?? 0, item.summary, item.evidence ?? "",
554
+ ...(item.permissionBlockers ? [item.permissionBlockers.map(permissionBlockerKey).sort()] : [])])
555
+ .sort((a, b) => String(a[0]).localeCompare(String(b[0]))));
556
+ }
557
+ /** Digest of the rows a cursor pages. Scope and detail are part of it: the same incidents render different bytes. */
558
+ function incidentRevision(state, scope = "actionable", detail = "compact") {
559
+ return failureIdentity(scope, detail, scopedFailures(state, scope).map((item) => [item.id, item.status, item.count, item.summary, item.evidence ?? "",
560
+ ...(item.permissionBlockers ? [item.permissionBlockers.map(permissionBlockerKey).sort()] : [])])).slice(0, 16);
561
+ }
562
+ /** Cursors carry a digest of their resource/scope, not the scope text. */
563
+ function resourceTag(resource) {
564
+ return resource === undefined ? undefined : createHash("sha256").update(resource).digest("base64url").slice(0, 16);
565
+ }
566
+ function incidentDigest(domain, revision, o, b) {
567
+ return createHash("sha256").update(`${domain}\0${revision}\0${o}\0${b}`).digest("base64url");
568
+ }
569
+ /** Digest of this page set at this row and byte offset. */
570
+ function incidentPositionDigest(revision, o, b) {
571
+ return incidentDigest("v", revision, o, b).slice(0, 16);
572
+ }
573
+ /** Independent witness of the same position, so damage to either digest alone stays usable. */
574
+ function incidentPositionWitness(revision, o, b) {
575
+ return incidentDigest("w", revision, b, o).slice(0, 4);
576
+ }
577
+ function incidentCursorTag(payload) {
578
+ const { q: _ignored, ...rest } = payload;
579
+ return createHash("sha256").update(JSON.stringify(rest)).digest("base64url").slice(0, 4);
580
+ }
581
+ function encodeIncidentCursor(cursor) {
582
+ const payload = { o: cursor.o, ...(cursor.b ? { b: cursor.b } : {}), v: cursor.v, n: cursor.n,
583
+ ...(cursor.r !== undefined ? { r: cursor.r } : {}), ...(cursor.h ? { h: 1 } : {}),
584
+ ...(cursor.f ? { f: 1 } : {}), w: cursor.w };
585
+ return INCIDENT_CURSOR_PREFIX + Buffer.from(JSON.stringify({ ...payload, q: incidentCursorTag(payload) }), "utf8").toString("base64url");
586
+ }
587
+ function decodeIncidentCursor(cursor) {
588
+ if (!cursor || !cursor.startsWith(INCIDENT_CURSOR_PREFIX))
589
+ return undefined;
590
+ try {
591
+ const parsed = JSON.parse(Buffer.from(cursor.slice(INCIDENT_CURSOR_PREFIX.length), "base64url").toString("utf8"));
592
+ if (typeof parsed?.v === "string" && typeof parsed.w === "string") {
593
+ return { corrupt: typeof parsed.q !== "string" || parsed.q !== incidentCursorTag(parsed), cursor: {
594
+ o: Math.max(0, Math.floor(parsed.o ?? 0)), b: Math.max(0, Math.floor(parsed.b ?? 0)), v: parsed.v, w: parsed.w,
595
+ n: Math.max(0, Math.floor(parsed.n ?? 0)), ...(typeof parsed.r === "string" ? { r: parsed.r } : {}),
596
+ ...(parsed.h === 1 ? { h: 1 } : {}), ...(parsed.f === 1 ? { f: 1 } : {})
597
+ } };
598
+ }
599
+ }
600
+ catch { /* stale */ }
601
+ return undefined;
602
+ }
603
+ export function isIncidentCursor(cursor) {
604
+ if (!cursor)
605
+ return false;
606
+ return cursor.startsWith(INCIDENT_CURSOR_PREFIX) || LEGACY_INCIDENT_CURSOR_PREFIXES.some((prefix) => cursor.startsWith(prefix));
607
+ }
608
+ /** The scope an incident cursor pages, or undefined for anything that is not an incident cursor. */
609
+ export function incidentCursorScope(cursor) {
610
+ const parsed = decodeIncidentCursor(cursor)?.cursor;
611
+ return parsed ? (parsed.h ? "all" : "actionable") : undefined;
612
+ }
613
+ function utf8Length(value) {
614
+ return encoder.encode(value).byteLength;
615
+ }
616
+ /** Largest prefix of `bytes` within `room` that does not split a code point. */
617
+ function utf8Prefix(bytes, room) {
618
+ if (room <= 0)
619
+ return 0;
620
+ if (room >= bytes.length)
621
+ return bytes.length;
622
+ let end = room;
623
+ while (end > 0 && (bytes[end] & 0xc0) === 0x80)
624
+ end -= 1;
625
+ return end;
626
+ }
627
+ /**
628
+ * Caller-owned incident pages. Whole rows are preferred; a row larger than the
629
+ * page is split at a code-point boundary and resumes at that byte, so pages
630
+ * reconstruct formatFailureLines() exactly (join with "\n" except after a page
631
+ * that `endsPartial`). A page never exceeds `maxBytes`, so one smaller than the
632
+ * next code point (up to 4 bytes) returns no text, `hasMore`, and a `nextCursor`
633
+ * equal to `cursor`: the caller retries with a larger page, as with
634
+ * pageVerbatimText. Consumers never ask for fewer than 4 bytes.
635
+ */
636
+ export function pageFailureIncidents(state, request = {}) {
637
+ // A cursor carries its view: following a history cursor stays in history without the flag.
638
+ const decoded = request.cursor ? decodeIncidentCursor(request.cursor) : undefined;
639
+ const parsed = decoded?.cursor;
640
+ const scope = request.scope ?? (parsed?.h ? "all" : "actionable");
641
+ const detail = request.detail ?? (parsed?.f ? "full" : "compact");
642
+ const lines = formatFailureLines(state, { scope, detail });
643
+ const revision = incidentRevision(state, scope, detail);
644
+ const total = lines.length;
645
+ const resource = resourceTag(request.resource);
646
+ let offset = 0;
647
+ let byte = 0;
648
+ let reset;
649
+ if (request.cursor) {
650
+ const corrupt = decoded?.corrupt === true;
651
+ if (!parsed || parsed.r !== resource || Boolean(parsed.h) !== (scope === "all") || Boolean(parsed.f) !== (detail === "full")) {
652
+ reset = corrupt ? "cursor-corrupt" : "stale-cursor";
653
+ }
654
+ else if (corrupt) {
655
+ // A hand-copied cursor is corruption, not a replaced source (#617), and
656
+ // its offset is never trusted on the payload's word. It resumes only
657
+ // when a witness recomputed from the current rows proves this exact
658
+ // position in this exact page set; otherwise it restarts at the first
659
+ // row, so a failure inserted ahead of the cursor is not skipped.
660
+ reset = "cursor-corrupt";
661
+ const witnessed = parsed.o <= total
662
+ && (parsed.v === incidentPositionDigest(revision, parsed.o, parsed.b)
663
+ || parsed.w === incidentPositionWitness(revision, parsed.o, parsed.b));
664
+ if (witnessed) {
665
+ offset = parsed.o;
666
+ byte = offset < total ? parsed.b : 0;
667
+ }
668
+ }
669
+ else if (parsed.v !== incidentPositionDigest(revision, parsed.o, parsed.b))
670
+ reset = "source-replaced";
671
+ else {
672
+ offset = Math.min(total, parsed.o);
673
+ byte = offset < total ? parsed.b : 0;
674
+ }
675
+ }
676
+ const maxBytes = Number.isFinite(request.maxBytes) && (request.maxBytes ?? -1) >= 0
677
+ ? Math.floor(request.maxBytes)
678
+ : 2 * 1024;
679
+ const mint = (o, b) => encodeIncidentCursor({ o, b, v: incidentPositionDigest(revision, o, b),
680
+ w: incidentPositionWitness(revision, o, b), n: total, ...(resource !== undefined ? { r: resource } : {}),
681
+ ...(scope === "all" ? { h: 1 } : {}), ...(detail === "full" ? { f: 1 } : {}) });
682
+ const parts = [];
683
+ let used = 0;
684
+ let nextRow = offset;
685
+ let nextByte = byte;
686
+ let endsPartial = false;
687
+ for (let i = offset; i < total; i += 1) {
688
+ const encoded = encoder.encode(lines[i]);
689
+ const from = i === offset ? Math.min(byte, encoded.length) : 0;
690
+ const rest = encoded.subarray(from);
691
+ const sep = parts.length ? 1 : 0;
692
+ if (used + sep + rest.length <= maxBytes) {
693
+ parts.push(Buffer.from(rest).toString("utf8"));
694
+ used += sep + rest.length;
695
+ nextRow = i + 1;
696
+ nextByte = 0;
697
+ continue;
698
+ }
699
+ if (parts.length === 0) {
700
+ const cut = utf8Prefix(rest, maxBytes);
701
+ if (cut > 0) {
702
+ parts.push(Buffer.from(rest.subarray(0, cut)).toString("utf8"));
703
+ used += cut;
704
+ nextRow = i;
705
+ nextByte = from + cut;
706
+ endsPartial = true;
707
+ }
708
+ }
709
+ break;
710
+ }
711
+ const startsPartial = byte > 0 && offset < total;
712
+ const represented = Math.max(0, nextRow - offset);
713
+ return {
714
+ text: parts.join("\n"),
715
+ total,
716
+ represented,
717
+ omitted: Math.max(0, total - nextRow),
718
+ cursor: mint(offset, byte),
719
+ nextCursor: mint(nextRow, nextByte),
720
+ hasMore: nextRow < total,
721
+ ...(reset ? { reset } : {}),
722
+ startsPartial,
723
+ endsPartial,
724
+ };
725
+ }
726
+ /** Cursor resource for one task/run's incidents in one session scope. */
727
+ export function incidentResource(scopeKey, id) {
728
+ return `incidents:${scopeKey}:${id}`;
729
+ }
730
+ /** Heading for an explicit incident page. */
731
+ export function incidentPageHeading(total, scope = "actionable") {
732
+ return scope === "all"
733
+ ? `History page of ${total} failure observation${total === 1 ? "" : "s"} (all, including those that need no action).`
734
+ : `Incident page of ${total} active failure observation${total === 1 ? "" : "s"}.`;
735
+ }
736
+ /**
737
+ * One explicit incident page shaped as an envelope verbatim page (log-utils
738
+ * `VerbatimPage`): the shared body of every consumer's `incidentCursor`
739
+ * response. Omitted counts are rows, never bytes.
740
+ */
741
+ export function incidentVerbatimPage(state, request = {}) {
742
+ const page = pageFailureIncidents(state, request);
743
+ const scope = request.scope ?? incidentCursorScope(request.cursor) ?? "actionable";
744
+ const empty = scope === "all" ? "No failure observations recorded."
745
+ : [quietFailureLine(state) ? "No failures need action." : "No active failure observations.", historyCountsText(state) ? "Pass history:true to list history." : ""].filter(Boolean).join(" ");
746
+ return {
747
+ text: page.text || (page.total === 0 ? empty : ""),
748
+ hasMore: page.hasMore,
749
+ cursor: page.cursor,
750
+ nextCursor: page.nextCursor,
751
+ omittedBytes: 0,
752
+ omittedRows: page.omitted,
753
+ ...(page.reset ? { reset: page.reset } : {}),
754
+ };
755
+ }
756
+ /**
757
+ * Cheap change fingerprint of a failure journal: the file's identity and size
758
+ * (or its read error), whether the durable existence marker is present, and
759
+ * how many records are still awaiting persistence in this process. Every
760
+ * journal append, truncation, deletion, or pending in-memory record changes
761
+ * it, so a cache keyed by it never serves stale incident counts.
762
+ */
763
+ export function failureJournalFingerprint(path) {
764
+ return `${fileChangeIdentity(path)}|${existsSync(`${path}.observed`) ? 1 : 0}|${pendingWrites.get(path)?.length ?? 0}`;
765
+ }
766
+ /**
767
+ * A file's identity and change stamp (device, inode, size, and nanosecond mtime/ctime), or its read
768
+ * error. Any append, rewrite, replacement, or deletion changes it; for cache keys, never for trust.
769
+ */
770
+ export function fileChangeIdentity(path) {
771
+ try {
772
+ const stats = statSync(path, { bigint: true });
773
+ return `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`;
774
+ }
775
+ catch (error) {
776
+ return `unreadable:${error.code ?? "error"}`;
777
+ }
778
+ }
779
+ export function incidentCursorAt(state, offset, resource, options = {}) {
780
+ const scope = options.scope ?? "actionable";
781
+ const detail = options.detail ?? "compact";
782
+ const lines = formatFailureLines(state, { scope, detail });
783
+ const revision = incidentRevision(state, scope, detail);
784
+ const o = Math.max(0, Math.floor(offset));
785
+ const tag = resourceTag(resource);
786
+ return encodeIncidentCursor({ o, b: 0, v: incidentPositionDigest(revision, o, 0), w: incidentPositionWitness(revision, o, 0),
787
+ n: lines.length, ...(tag !== undefined ? { r: tag } : {}), ...(scope === "all" ? { h: 1 } : {}),
788
+ ...(options.detail === "full" ? { f: 1 } : {}) });
789
+ }
790
+ const MIN_PARTIAL_ROW_BYTES = 96;
791
+ export function formatIncidentSummary(state, options) {
792
+ const maxBytes = Math.max(0, Math.floor(options.maxBytes));
793
+ const summary = actionableIncidentSummary(state, options);
794
+ // Nothing needs action: one short line, no cursor. History is listed only on request.
795
+ if (summary.total === 0) {
796
+ const quiet = quietFailureLine(state);
797
+ return { text: quiet && utf8Length(quiet) <= maxBytes ? quiet : "", total: 0, represented: 0, omitted: 0 };
798
+ }
799
+ const tail = historyTailLine(state);
800
+ if (tail && summary.text && utf8Length(summary.text) + 1 + utf8Length(tail) <= maxBytes)
801
+ return { ...summary, text: `${summary.text}\n${tail}` };
802
+ return summary;
803
+ }
804
+ function actionableIncidentSummary(state, options) {
805
+ const maxBytes = Math.max(0, Math.floor(options.maxBytes));
806
+ const whole = pageFailureIncidents(state, { maxBytes, resource: options.resource, detail: options.detail });
807
+ if (whole.total === 0)
808
+ return { text: "", total: 0, represented: 0, omitted: 0 };
809
+ if (!whole.hasMore)
810
+ return { text: whole.text, total: whole.total, represented: whole.represented, omitted: 0 };
811
+ const header = (page) => `${page.total} active failure observation${page.total === 1 ? "" : "s"} · ${page.represented} shown · ${page.omitted} omitted` +
812
+ ` · incidentCursor=${page.nextCursor}${options.retrieval ? ` (${options.retrieval})` : ""}`;
813
+ let rowBudget = maxBytes - utf8Length(header(whole)) - 1;
814
+ for (let attempt = 0; attempt < 6; attempt += 1) {
815
+ let page = pageFailureIncidents(state, { maxBytes: Math.max(0, rowBudget), resource: options.resource, detail: options.detail });
816
+ // A few bytes of a clipped row are noise; show the count line alone and
817
+ // let the cursor start at that row.
818
+ if (page.represented === 0 && page.endsPartial && utf8Length(page.text) < MIN_PARTIAL_ROW_BYTES) {
819
+ page = pageFailureIncidents(state, { maxBytes: 0, resource: options.resource, detail: options.detail });
820
+ }
821
+ const line = header(page);
822
+ const text = page.text ? `${line}\n${page.text}` : line;
823
+ const overflow = utf8Length(text) - maxBytes;
824
+ if (overflow <= 0) {
825
+ return { text, total: page.total, represented: page.represented, omitted: page.omitted, nextCursor: page.nextCursor };
826
+ }
827
+ if (rowBudget <= 0)
828
+ break;
829
+ rowBudget -= overflow;
830
+ }
831
+ // Not even the count line with its cursor fits. Never emit a clipped cursor:
832
+ // keep the exact counts and drop the cursor token whole, saying so.
833
+ const empty = pageFailureIncidents(state, { maxBytes: 0, resource: options.resource, detail: options.detail });
834
+ const withCursor = header(empty);
835
+ if (utf8Length(withCursor) <= maxBytes) {
836
+ return { text: withCursor, total: empty.total, represented: 0, omitted: empty.total, nextCursor: empty.nextCursor };
837
+ }
838
+ const plural = empty.total === 1 ? "" : "s";
839
+ for (const candidate of [
840
+ `${empty.total} active failure observation${plural} · 0 shown · ${empty.total} omitted · incident cursor not shown (page too small; retry with a larger maxBytes${options.retrieval ? ` or ${options.retrieval}` : ""})`,
841
+ `${empty.total} active failure observation${plural} · 0 shown · ${empty.total} omitted · incident cursor not shown (page too small)`,
842
+ `${empty.total} active failure observation${plural} (page too small for details)`,
843
+ ]) {
844
+ if (utf8Length(candidate) <= maxBytes)
845
+ return { text: candidate, total: empty.total, represented: 0, omitted: empty.total };
846
+ }
847
+ return { text: "", total: empty.total, represented: 0, omitted: empty.total };
848
+ }
849
+ /**
850
+ * Terminal failure section for a byte budget (#315): lifecycle-independent facts. Actionable and
851
+ * observation-incomplete incidents (which lead the priority order) are shown as whole rows;
852
+ * unclassified, expected, and closed incidents are counts. When any active row is not shown, a
853
+ * count line gives the exact total, shown, omitted, and an incident cursor at the first unshown row.
854
+ *
855
+ * The result never exceeds `maxBytes` and is made of whole lines (#325). Under a tight budget it
856
+ * drops, in order: incident rows; the lower-priority notes (closed history, expected, earlier
857
+ * reported); the cursor's retrieval hint; the unclassified count; the cursor; the count line.
858
+ * The correctness note goes last, and only when it alone does not fit: it is never cut mid-sentence.
859
+ */
860
+ export function formatTerminalIncidentSummary(state, options) {
861
+ const active = activeFailures(state);
862
+ // Counts, rows, and the cursor cover only incidents that need action; the rest is history.
863
+ const lines = formatFailureLines(state, { detail: options.detail });
864
+ const total = lines.length;
865
+ const parts = terminalFailureParts(state, active.map((x) => x.id));
866
+ const quiet = quietFailureLine(state);
867
+ // Nothing needs action: one short history line (no cursor) and, when tool failures stay
868
+ // unclassified, the correctness note.
869
+ const notes = total === 0 && quiet ? [quiet, ...parts.notes.filter((x) => x === CORRECTNESS_NOTE)] : parts.notes;
870
+ if (total === 0 && notes.length === 0)
871
+ return { text: "", total: 0, represented: 0, omitted: 0 };
872
+ const maxBytes = Math.max(0, Math.floor(options.maxBytes));
873
+ const fits = (parts) => utf8Length(parts.filter(Boolean).join("\n")) <= maxBytes;
874
+ const header = (shown, mode) => shown >= total ? undefined :
875
+ `${total} active failure observation${total === 1 ? "" : "s"} · ${shown} shown · ${total - shown} omitted` +
876
+ (mode === "none" ? " · incident cursor not shown (page too small)"
877
+ : ` · incidentCursor=${incidentCursorAt(state, shown, options.resource, { detail: options.detail })}${mode === "full" && options.retrieval ? ` (${options.retrieval})` : ""}`);
878
+ const done = (parts, shown, mode) => {
879
+ const omitted = total - shown;
880
+ return { text: parts.filter((x) => Boolean(x)).join("\n"), total, represented: shown, omitted,
881
+ ...(omitted > 0 && mode !== "none" ? { nextCursor: incidentCursorAt(state, shown, options.resource, { detail: options.detail }) } : {}) };
882
+ };
883
+ // 1. Drop incident rows, lowest priority first, keeping every note and the count line with its cursor.
884
+ for (let shown = lines.length; shown >= 0; shown -= 1) {
885
+ const parts = [header(shown, "full"), ...lines.slice(0, shown), ...notes];
886
+ if (fits(parts))
887
+ return done(parts, shown, "full");
888
+ }
889
+ // 2. No rows. Then, in order: the lower-priority notes (history, expected, earlier reported), the
890
+ // cursor's retrieval hint, the unclassified count, the cursor, and the count line. The
891
+ // correctness note goes last, and only when it alone does not fit.
892
+ const correctness = notes.filter((x) => x === CORRECTNESS_NOTE);
893
+ const unclassified = notes.filter((x) => x === parts.unclassifiedNote);
894
+ const low = notes.filter((x) => !correctness.includes(x) && !unclassified.includes(x));
895
+ const ladder = [];
896
+ for (let keep = low.length - 1; keep >= 0; keep -= 1)
897
+ ladder.push({ mode: "full", notes: [...low.slice(0, keep), ...unclassified, ...correctness] });
898
+ ladder.push({ mode: "bare", notes: [...unclassified, ...correctness] });
899
+ ladder.push({ mode: "bare", notes: correctness });
900
+ ladder.push({ mode: "none", notes: correctness });
901
+ ladder.push({ mode: undefined, notes: correctness });
902
+ for (const step of ladder) {
903
+ const parts = [step.mode ? header(0, step.mode) : undefined, ...step.notes];
904
+ if (parts.some(Boolean) && fits(parts))
905
+ return done(parts, 0, step.mode ?? "none");
906
+ }
907
+ return done([], 0, "none");
908
+ }
909
+ /**
910
+ * Incidents due for a notification. Terminal: every current unresolved incident not yet delivered
911
+ * (reported once, then receipted). Running: observation gaps immediately (unless the consumer
912
+ * defers them to its terminal/health callback), actionable incidents after the grace period;
913
+ * a single agent tool failure is left to the agent that owns it.
914
+ */
915
+ export function pendingFailureAttention(state, now, options = {}) {
916
+ const due = activeFailures(state).filter((x) => x.status === "unresolved" && !Object.hasOwn(state.delivered, x.id) &&
917
+ (options.terminal || (x.category === "observation-incomplete" ? !options.deferObservationGaps
918
+ : requiresAction(x) && now - x.firstObservedAt >= (options.graceMs ?? 60_000))));
919
+ if (!due.length)
920
+ return undefined;
921
+ const incidents = due.map((x) => x.id).sort();
922
+ return { key: failureIdentity(incidents), incidents,
923
+ summary: due.map((x) => x.summary).join("; ").slice(0, 800) };
924
+ }
925
+ function storageProblem(state, summary) {
926
+ return reduceFailure(state, { id: failureIdentity("storage", summary), operation: "failure-observation-storage",
927
+ kind: "incomplete", summary }, Date.now());
928
+ }
929
+ const pendingWrites = new Map();
930
+ const knownJournals = new Map();
931
+ function appendRecord(path, record) {
932
+ mkdirSync(dirname(path), { recursive: true });
933
+ // A durable existence marker distinguishes a lost journal from a run that has
934
+ // never observed a failure, including after a process restart.
935
+ try {
936
+ closeSync(openSync(`${path}.observed`, "wx", 0o600));
937
+ }
938
+ catch (error) {
939
+ if (error.code !== "EEXIST")
940
+ throw error;
941
+ }
942
+ appendFileSync(path, "\n" + JSON.stringify(record) + "\n", { mode: 0o600 });
943
+ }
944
+ /** Retry unpersisted evidence and receipts on every observation/read. Pending
945
+ * receipts count as handed off in this process, preventing notification storms. */
946
+ export function readFailureState(path) {
947
+ const pending = pendingWrites.get(path);
948
+ while (pending?.length) {
949
+ try {
950
+ appendRecord(path, pending[0]);
951
+ pending.shift();
952
+ }
953
+ catch {
954
+ break;
955
+ }
956
+ }
957
+ if (!pending?.length)
958
+ pendingWrites.delete(path);
959
+ let state = readStoredState(path);
960
+ const remaining = pendingWrites.get(path);
961
+ for (const record of remaining ?? [])
962
+ state = reduceFailure(state, record.event, record.observedAt);
963
+ return remaining?.length ? storageProblem(state, "Failure evidence could not be persisted") : state;
964
+ }
965
+ /** Read-only projection: never retries or appends process-local pending writes. */
966
+ export function readFailureStateReadOnly(path) { return readStoredState(path); }
967
+ function readStoredState(path) {
968
+ let source;
969
+ try {
970
+ source = readFileSync(path, "utf8");
971
+ }
972
+ catch (error) {
973
+ if (error.code === "ENOENT" && !knownJournals.has(path) && !existsSync(`${path}.observed`))
974
+ return emptyFailureState();
975
+ return storageProblem(emptyFailureState(), "Failure journal could not be read");
976
+ }
977
+ const bytes = Buffer.byteLength(source);
978
+ const truncated = bytes < (knownJournals.get(path) ?? 0);
979
+ if (bytes || knownJournals.has(path))
980
+ knownJournals.set(path, bytes);
981
+ let state = truncated ? storageProblem(emptyFailureState(), "Failure journal was truncated; observations may be incomplete") : emptyFailureState();
982
+ for (const line of source.split("\n")) {
983
+ if (!line)
984
+ continue;
985
+ try {
986
+ const row = JSON.parse(line);
987
+ const e = row.event;
988
+ if (!e || typeof e.id !== "string" || !e.id || typeof e.operation !== "string" || !e.operation ||
989
+ (e.expected !== undefined && typeof e.expected !== "boolean") ||
990
+ !["failure", "incomplete", "recovered", "delivered", "disposition"].includes(e.kind) ||
991
+ (e.disposition !== undefined && !INCIDENT_DISPOSITIONS.includes(e.disposition)) ||
992
+ !Number.isFinite(row.observedAt) || Math.abs(row.observedAt) > 8.64e15 ||
993
+ (e.at !== undefined && (!Number.isFinite(e.at) || Math.abs(e.at) > 8.64e15)) ||
994
+ (e.incidents !== undefined && (!Array.isArray(e.incidents) || !e.incidents.every((id) => typeof id === "string"))) ||
995
+ (e.permissionBlockers !== undefined && (e.kind !== "disposition" ||
996
+ (!state.seen.includes(e.id) && validateDisposition(state, e) !== undefined))) ||
997
+ [e.summary, e.category, e.evidence, e.reason].some((v) => v !== undefined && typeof v !== "string"))
998
+ throw new Error("invalid record");
999
+ state = reduceFailure(state, e, row.observedAt);
1000
+ }
1001
+ catch {
1002
+ state = storageProblem(state, "Failure journal contains unreadable records; observations may be incomplete");
1003
+ }
1004
+ }
1005
+ if (truncated) {
1006
+ const summary = "Failure journal was truncated; observations may be incomplete";
1007
+ const record = { event: { id: failureIdentity("storage", summary), operation: "failure-observation-storage", kind: "incomplete", summary }, observedAt: Date.now() };
1008
+ try {
1009
+ appendRecord(path, record);
1010
+ }
1011
+ catch {
1012
+ pendingWrites.set(path, [...(pendingWrites.get(path) ?? []), record]);
1013
+ }
1014
+ }
1015
+ return state;
1016
+ }
1017
+ export function observeFailures(path, events, now = Date.now()) {
1018
+ let state = readFailureState(path);
1019
+ for (const raw of events) {
1020
+ if (state.seen.includes(raw.id))
1021
+ continue;
1022
+ if (raw.kind === "recovered") {
1023
+ const prior = state.observations[failureIdentity(raw.operation)];
1024
+ if (!prior || prior.status !== "unresolved" || !raw.incidents?.includes(prior.id))
1025
+ continue;
1026
+ }
1027
+ // Rejected dispositions are never journaled or marked seen.
1028
+ if (raw.kind === "disposition" && validateDisposition(state, raw))
1029
+ continue;
1030
+ if (raw.permissionBlockers !== undefined && raw.kind !== "disposition")
1031
+ continue;
1032
+ const event = { ...raw, ...(raw.summary ? { summary: text(raw.summary, "") } : {}),
1033
+ ...(raw.evidence ? { evidence: text(raw.evidence, "") } : {}), ...(raw.reason ? { reason: text(raw.reason, "") } : {}) };
1034
+ try {
1035
+ if (pendingWrites.has(path))
1036
+ throw new Error("Earlier evidence is awaiting persistence");
1037
+ appendRecord(path, { event, observedAt: now });
1038
+ state = reduceFailure(state, event, now);
1039
+ }
1040
+ catch {
1041
+ const pending = pendingWrites.get(path) ?? [];
1042
+ pending.push({ event, observedAt: now });
1043
+ pendingWrites.set(path, pending);
1044
+ state = storageProblem(reduceFailure(state, event, now), "Failure evidence could not be persisted");
1045
+ }
1046
+ }
1047
+ return state;
1048
+ }
1049
+ export function failureAttentionHandled(state, incidents) {
1050
+ return incidents.every((id) => {
1051
+ if (Object.hasOwn(state.delivered, id) || Object.hasOwn(state.resolved ?? {}, id))
1052
+ return true;
1053
+ const observation = Object.values(state.observations).find((item) => item.id === id);
1054
+ if (!observation)
1055
+ throw new Error("Failure incident evidence is unavailable; defer notification delivery");
1056
+ return observation.status !== "unresolved";
1057
+ });
1058
+ }
1059
+ export function markFailureAttentionDelivered(path, pending, at = Date.now()) {
1060
+ return observeFailures(path, [{ id: `delivered:${pending.key}`, operation: "attention-delivery", kind: "delivered", incidents: pending.incidents }], at);
1061
+ }
1062
+ /**
1063
+ * Append one explicit disposition. Validation happens before the journal write; a rejected
1064
+ * request (unknown, already disposed, missing reason or evidence) writes nothing. Replaying an
1065
+ * already accepted event id is an idempotent success.
1066
+ */
1067
+ export function disposeIncidents(path, event, now = Date.now()) {
1068
+ const state = readFailureState(path);
1069
+ if (event.kind !== "disposition")
1070
+ return { accepted: false, error: "Not a disposition event", state };
1071
+ if (state.seen.includes(event.id))
1072
+ return { accepted: true, state };
1073
+ const error = validateDisposition(state, event);
1074
+ if (error)
1075
+ return { accepted: false, error, state };
1076
+ const next = observeFailures(path, [event], now);
1077
+ return next.seen.includes(event.id) ? { accepted: true, state: next } : { accepted: false, error: "Disposition was not recorded", state: next };
1078
+ }