@parcha/agentrun-serve 0.1.0-beta.33 → 0.1.0-beta.35

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 (466) hide show
  1. package/CHANGELOG.md +368 -0
  2. package/README.md +341 -208
  3. package/dist/adapters.d.ts +3 -4
  4. package/dist/adapters.js +18 -15
  5. package/dist/agent-rows.d.ts +99 -0
  6. package/dist/agent-rows.js +1 -0
  7. package/dist/agents-store.d.ts +6 -2
  8. package/dist/agents-store.js +75 -25
  9. package/dist/agents.d.ts +9 -125
  10. package/dist/agents.js +15 -305
  11. package/dist/answer-json.d.ts +23 -0
  12. package/dist/answer-json.js +58 -0
  13. package/dist/api-only.d.ts +1 -1
  14. package/dist/api-only.js +2 -2
  15. package/dist/archil-settings.d.ts +11 -1
  16. package/dist/archil-settings.js +10 -0
  17. package/dist/bash-read-only.d.ts +35 -0
  18. package/dist/bash-read-only.js +778 -0
  19. package/dist/box-settings.d.ts +3 -23
  20. package/dist/box-settings.js +7 -51
  21. package/dist/boxes.d.ts +17 -0
  22. package/dist/boxes.js +27 -20
  23. package/dist/browser-commands.d.ts +5 -2
  24. package/dist/browser-commands.js +4 -4
  25. package/dist/browser-computer.d.ts +5 -0
  26. package/dist/browser-computer.js +21 -0
  27. package/dist/browser-cost.d.ts +9 -6
  28. package/dist/browser-cost.js +95 -51
  29. package/dist/browser-live.d.ts +7 -20
  30. package/dist/browser-live.js +15 -93
  31. package/dist/browser-person.d.ts +18 -51
  32. package/dist/browser-person.js +94 -277
  33. package/dist/budget.d.ts +0 -5
  34. package/dist/budget.js +0 -5
  35. package/dist/cap.d.ts +14 -8
  36. package/dist/cap.js +19 -9
  37. package/dist/cli.js +71 -18
  38. package/dist/closed-pipes.d.ts +2 -0
  39. package/dist/closed-pipes.js +13 -0
  40. package/dist/computer-commands.d.ts +2 -0
  41. package/dist/computer-commands.js +2 -0
  42. package/dist/computer-keys.d.ts +20 -10
  43. package/dist/computer-keys.js +36 -54
  44. package/dist/computer-setting.d.ts +20 -3
  45. package/dist/computer-setting.js +58 -10
  46. package/dist/computers.d.ts +35 -2
  47. package/dist/computers.js +72 -11
  48. package/dist/confine.d.ts +120 -0
  49. package/dist/confine.js +436 -0
  50. package/dist/console/assets/index-B7NKTU8E.css +1 -0
  51. package/dist/console/assets/index-CXZMgJE7.js +550 -0
  52. package/dist/console/index.html +2 -2
  53. package/dist/content-filter.d.ts +7 -0
  54. package/dist/content-filter.js +23 -0
  55. package/dist/decision-cap.d.ts +7 -29
  56. package/dist/decision-cap.js +3 -94
  57. package/dist/decision-rows.d.ts +1 -1
  58. package/dist/decision-rows.js +1 -1
  59. package/dist/docker-daemon.d.ts +31 -0
  60. package/dist/docker-daemon.js +56 -0
  61. package/dist/effort-guidance.js +4 -3
  62. package/dist/environment.d.ts +0 -3
  63. package/dist/environment.js +3 -5
  64. package/dist/errors.d.ts +1 -2
  65. package/dist/errors.js +9 -9
  66. package/dist/explain.js +3 -1
  67. package/dist/filed-answer.d.ts +32 -0
  68. package/dist/filed-answer.js +160 -0
  69. package/dist/files.d.ts +1 -3
  70. package/dist/files.js +2 -4
  71. package/dist/github-connection.d.ts +1 -1
  72. package/dist/github-connection.js +25 -7
  73. package/dist/github-faux.d.ts +26 -0
  74. package/dist/github-faux.js +76 -0
  75. package/dist/github.d.ts +6 -2
  76. package/dist/github.js +5 -3
  77. package/dist/graph-served.d.ts +5 -3
  78. package/dist/graph-served.js +14 -6
  79. package/dist/graph-view.d.ts +3 -5
  80. package/dist/graph-view.js +9 -16
  81. package/dist/handed-values.d.ts +9 -0
  82. package/dist/handed-values.js +26 -0
  83. package/dist/harness-install.d.ts +1 -7
  84. package/dist/harness-install.js +1 -18
  85. package/dist/harness-opencode/adapter.d.ts +7 -0
  86. package/dist/harness-opencode/adapter.js +23 -6
  87. package/dist/harness-opencode/harness.js +0 -1
  88. package/dist/harness-opencode/host/policy.js +2 -2
  89. package/dist/harness-opencode/index.d.ts +1 -1
  90. package/dist/harness-opencode/index.js +1 -1
  91. package/dist/harness-opencode/verify.d.ts +17 -0
  92. package/dist/harness-opencode/verify.js +30 -10
  93. package/dist/harness-table.js +6 -1
  94. package/dist/heard.js +1 -1
  95. package/dist/held-fd.d.ts +5 -0
  96. package/dist/held-fd.js +14 -0
  97. package/dist/host-calls.d.ts +20 -0
  98. package/dist/host-calls.js +12 -0
  99. package/dist/host-tools.d.ts +4 -21
  100. package/dist/host-tools.js +4 -61
  101. package/dist/host.d.ts +2 -4
  102. package/dist/host.js +2 -7
  103. package/dist/import-summary.d.ts +1 -5
  104. package/dist/import-summary.js +0 -21
  105. package/dist/import.d.ts +6 -6
  106. package/dist/import.js +14 -15
  107. package/dist/index.d.ts +1 -0
  108. package/dist/index.js +1 -0
  109. package/dist/key-refusal.d.ts +5 -1
  110. package/dist/key-refusal.js +19 -4
  111. package/dist/learn/check.d.ts +8 -2
  112. package/dist/learn/check.js +85 -31
  113. package/dist/learn/folder.d.ts +11 -4
  114. package/dist/learn/folder.js +17 -19
  115. package/dist/learn/grade.d.ts +18 -1
  116. package/dist/learn/grade.js +108 -14
  117. package/dist/learn/index.d.ts +5 -5
  118. package/dist/learn/index.js +5 -5
  119. package/dist/learn/learning.sh +1 -14
  120. package/dist/learn/notes.d.ts +14 -3
  121. package/dist/learn/notes.js +16 -6
  122. package/dist/learn/reflect.d.ts +31 -2
  123. package/dist/learn/reflect.js +83 -6
  124. package/dist/learn/relevance.d.ts +24 -0
  125. package/dist/learn/relevance.js +91 -0
  126. package/dist/learn/secrets.d.ts +7 -1
  127. package/dist/learn/secrets.js +86 -19
  128. package/dist/learn/skills.d.ts +159 -18
  129. package/dist/learn/skills.js +644 -64
  130. package/dist/learned-nodes.d.ts +14 -0
  131. package/dist/learned-nodes.js +8 -0
  132. package/dist/learned-workflow.d.ts +41 -6
  133. package/dist/learned-workflow.js +153 -18
  134. package/dist/learning-routes.d.ts +49 -4
  135. package/dist/learning-routes.js +113 -31
  136. package/dist/learning-run.d.ts +16 -31
  137. package/dist/learning-run.js +31 -38
  138. package/dist/learning-words.d.ts +12 -5
  139. package/dist/learning-words.js +18 -9
  140. package/dist/learning.d.ts +91 -97
  141. package/dist/learning.js +176 -320
  142. package/dist/live/stream.js +1 -1
  143. package/dist/live/translate.js +12 -2
  144. package/dist/llm.d.ts +4 -1
  145. package/dist/llm.js +4 -2
  146. package/dist/local-models.d.ts +11 -5
  147. package/dist/local-models.js +13 -8
  148. package/dist/mcp-gateway.d.ts +17 -49
  149. package/dist/mcp-gateway.js +55 -136
  150. package/dist/mcp-oauth.d.ts +10 -14
  151. package/dist/mcp-oauth.js +14 -32
  152. package/dist/mcp-probe.d.ts +0 -7
  153. package/dist/mcp-probe.js +4 -10
  154. package/dist/mcp-servers-store.d.ts +18 -18
  155. package/dist/mcp-servers-store.js +12 -14
  156. package/dist/mcp-store.js +3 -4
  157. package/dist/mcp.js +4 -3
  158. package/dist/model.d.ts +9 -7
  159. package/dist/model.js +51 -27
  160. package/dist/monid.d.ts +0 -2
  161. package/dist/monid.js +3 -6
  162. package/dist/openapi.d.ts +8 -1
  163. package/dist/openapi.js +156 -58
  164. package/dist/page.d.ts +1 -3
  165. package/dist/page.js +6 -18
  166. package/dist/paid-calls.d.ts +21 -27
  167. package/dist/paid-calls.js +26 -61
  168. package/dist/pause.d.ts +2 -19
  169. package/dist/pause.js +5 -74
  170. package/dist/port-models.d.ts +10 -3
  171. package/dist/port-models.js +26 -6
  172. package/dist/propose.d.ts +2 -0
  173. package/dist/propose.js +80 -45
  174. package/dist/push-handler.d.ts +1 -1
  175. package/dist/reflect-range.d.ts +25 -0
  176. package/dist/reflect-range.js +30 -0
  177. package/dist/refusal-words.d.ts +5 -1
  178. package/dist/refusal-words.js +5 -1
  179. package/dist/rows.d.ts +1 -1
  180. package/dist/run-cut.d.ts +0 -6
  181. package/dist/run-cut.js +0 -6
  182. package/dist/run-db.d.ts +2 -11
  183. package/dist/run-db.js +2 -37
  184. package/dist/run-launch.d.ts +21 -2
  185. package/dist/run-launch.js +14 -5
  186. package/dist/run-learning-served.d.ts +21 -4
  187. package/dist/run-learning-served.js +23 -13
  188. package/dist/run-reads-over-store.d.ts +5 -3
  189. package/dist/run-reads-over-store.js +25 -14
  190. package/dist/run-secrets.d.ts +1 -1
  191. package/dist/run-timeline-served.d.ts +5 -1
  192. package/dist/run-timeline-served.js +27 -6
  193. package/dist/run-view.d.ts +37 -22
  194. package/dist/run-view.js +85 -38
  195. package/dist/runnable.d.ts +21 -10
  196. package/dist/runnable.js +35 -12
  197. package/dist/runner/adapter-loop.d.ts +36 -5
  198. package/dist/runner/adapter-loop.js +663 -69
  199. package/dist/runner/adapter-run-spec.d.ts +42 -8
  200. package/dist/runner/adapter-run-spec.js +186 -52
  201. package/dist/runner/adapters/index.js +11 -1
  202. package/dist/runner/adapters/pi.d.ts +40 -2
  203. package/dist/runner/adapters/pi.js +110 -27
  204. package/dist/runner/beside.d.ts +38 -3
  205. package/dist/runner/beside.js +54 -5
  206. package/dist/runner/claim-secrets.d.ts +16 -1
  207. package/dist/runner/claim-secrets.js +62 -14
  208. package/dist/runner/cli-run-spec.d.ts +5 -0
  209. package/dist/runner/cli-run-spec.js +159 -41
  210. package/dist/runner/commands.js +1 -1
  211. package/dist/runner/computer-journal.d.ts +15 -2
  212. package/dist/runner/computer-journal.js +41 -5
  213. package/dist/runner/conformance/harness.d.ts +1 -0
  214. package/dist/runner/conformance/harness.js +123 -13
  215. package/dist/runner/conformance/subject.d.ts +4 -1
  216. package/dist/runner/dispatch.d.ts +8 -1
  217. package/dist/runner/dispatch.js +81 -7
  218. package/dist/runner/end-of-run.d.ts +8 -2
  219. package/dist/runner/end-of-run.js +10 -4
  220. package/dist/runner/github-app.d.ts +7 -2
  221. package/dist/runner/github-app.js +47 -16
  222. package/dist/runner/harness-loops.d.ts +15 -2
  223. package/dist/runner/harness-loops.js +38 -2
  224. package/dist/runner/journal-kinds.d.ts +60 -6
  225. package/dist/runner/journal-kinds.js +43 -5
  226. package/dist/runner/journal-reader.d.ts +1 -1
  227. package/dist/runner/journal-reader.js +2 -2
  228. package/dist/runner/learning-ask.d.ts +4 -0
  229. package/dist/runner/learning-ask.js +15 -1
  230. package/dist/runner/learning-end.d.ts +18 -3
  231. package/dist/runner/learning-end.js +194 -20
  232. package/dist/runner/learning-loop.d.ts +7 -0
  233. package/dist/runner/learning-loop.js +36 -8
  234. package/dist/runner/learning-seed.d.ts +6 -0
  235. package/dist/runner/learning-seed.js +6 -0
  236. package/dist/runner/loop-contract.d.ts +4 -0
  237. package/dist/runner/main.d.ts +61 -9
  238. package/dist/runner/main.js +144 -20
  239. package/dist/runner/mcp-claim.d.ts +3 -0
  240. package/dist/runner/mcp-claim.js +7 -3
  241. package/dist/runner/mcp-github.d.ts +11 -2
  242. package/dist/runner/mcp-github.js +55 -4
  243. package/dist/runner/mcp-run.d.ts +2 -0
  244. package/dist/runner/mcp-run.js +16 -5
  245. package/dist/runner/memory-claim.d.ts +9 -0
  246. package/dist/runner/memory-claim.js +25 -0
  247. package/dist/runner/metrics.d.ts +46 -1
  248. package/dist/runner/metrics.js +156 -1
  249. package/dist/runner/model-route.d.ts +16 -0
  250. package/dist/runner/model-route.js +134 -10
  251. package/dist/runner/reflect-hook.d.ts +12 -1
  252. package/dist/runner/reflect-hook.js +33 -3
  253. package/dist/runner/runner.d.ts +20 -0
  254. package/dist/runner/runner.js +146 -18
  255. package/dist/runner/spec-holds.d.ts +7 -2
  256. package/dist/runner/spec-holds.js +4 -3
  257. package/dist/runner/store-port.d.ts +1 -1
  258. package/dist/runner/store-secrets.d.ts +3 -3
  259. package/dist/runner/store-secrets.js +8 -12
  260. package/dist/runner/text-tools.d.ts +44 -0
  261. package/dist/runner/text-tools.js +237 -0
  262. package/dist/runner/workflow-host.d.ts +7 -2
  263. package/dist/runner/workflow-host.js +3 -1
  264. package/dist/runner/workflow-loop.d.ts +10 -1
  265. package/dist/runner/workflow-loop.js +14 -6
  266. package/dist/runner/workflow-spec.d.ts +21 -0
  267. package/dist/runner/workflow-spec.js +217 -93
  268. package/dist/runs-over-store.d.ts +14 -3
  269. package/dist/runs-over-store.js +100 -23
  270. package/dist/seal-key.d.ts +0 -2
  271. package/dist/seal-key.js +5 -45
  272. package/dist/sealed-settings-store.d.ts +19 -4
  273. package/dist/sealed-settings-store.js +9 -9
  274. package/dist/sealing.d.ts +4 -0
  275. package/dist/sealing.js +20 -0
  276. package/dist/secret-cut.d.ts +1 -1
  277. package/dist/secret-cut.js +1 -1
  278. package/dist/secret-name.d.ts +9 -0
  279. package/dist/secret-name.js +15 -0
  280. package/dist/secret-writes.d.ts +0 -1
  281. package/dist/secret-writes.js +0 -1
  282. package/dist/server-fs.d.ts +4 -0
  283. package/dist/server-fs.js +8 -2
  284. package/dist/server-lock.d.ts +0 -24
  285. package/dist/server-lock.js +5 -85
  286. package/dist/server-secrets-store.d.ts +4 -4
  287. package/dist/server-secrets-store.js +9 -31
  288. package/dist/server-secrets.d.ts +4 -9
  289. package/dist/server-secrets.js +12 -36
  290. package/dist/server.d.ts +37 -56
  291. package/dist/server.js +322 -134
  292. package/dist/sign-ins-store.d.ts +34 -36
  293. package/dist/sign-ins-store.js +27 -38
  294. package/dist/sign-ins.d.ts +2 -119
  295. package/dist/sign-ins.js +5 -311
  296. package/dist/standard-webhooks.d.ts +1 -1
  297. package/dist/standard-webhooks.js +1 -1
  298. package/dist/stats.d.ts +3 -2
  299. package/dist/stats.js +1 -1
  300. package/dist/stop-signals.d.ts +4 -2
  301. package/dist/stop-signals.js +5 -3
  302. package/dist/store/agent-body.d.ts +12 -2
  303. package/dist/store/agent-body.js +22 -4
  304. package/dist/store/deadline.d.ts +18 -0
  305. package/dist/store/deadline.js +45 -0
  306. package/dist/store/index.d.ts +2 -2
  307. package/dist/store/index.js +2 -2
  308. package/dist/store/open.d.ts +6 -3
  309. package/dist/store/open.js +2 -2
  310. package/dist/store/postgres/connection.d.ts +22 -2
  311. package/dist/store/postgres/connection.js +211 -41
  312. package/dist/store/postgres/migrate.d.ts +4 -0
  313. package/dist/store/postgres/migrate.js +9 -2
  314. package/dist/store/postgres/migrations/0003_commands_one_answer.check.sql +19 -0
  315. package/dist/store/postgres/migrations/0003_commands_one_answer.sql +13 -0
  316. package/dist/store/postgres/store.d.ts +9 -2
  317. package/dist/store/postgres/store.js +9 -0
  318. package/dist/store/schema.js +1 -1
  319. package/dist/store/seal.js +2 -2
  320. package/dist/store/sqlite/connection.js +14 -5
  321. package/dist/store/sqlite/run-patch.d.ts +3 -0
  322. package/dist/store/sqlite/run-patch.js +3 -0
  323. package/dist/store/sqlite/store.js +41 -12
  324. package/dist/store/store.d.ts +35 -6
  325. package/dist/store/store.js +12 -2
  326. package/dist/store-reads/cap.d.ts +1 -1
  327. package/dist/store-reads/cap.js +22 -4
  328. package/dist/store-reads/journal.d.ts +9 -6
  329. package/dist/store-reads/journal.js +129 -18
  330. package/dist/store-reads/learning.d.ts +82 -8
  331. package/dist/store-reads/learning.js +184 -11
  332. package/dist/store-reads/workflow.d.ts +1 -1
  333. package/dist/store-reads/workflow.js +1 -1
  334. package/dist/store-view.d.ts +19 -1
  335. package/dist/store-view.js +95 -27
  336. package/dist/template-eval.d.ts +60 -4
  337. package/dist/template-eval.js +120 -54
  338. package/dist/templates.d.ts +33 -14
  339. package/dist/templates.js +82 -46
  340. package/dist/timeline/group.d.ts +33 -0
  341. package/dist/timeline/group.js +77 -0
  342. package/dist/timeline/index.d.ts +7 -0
  343. package/dist/timeline/index.js +7 -0
  344. package/dist/timeline/labels.d.ts +79 -0
  345. package/dist/timeline/labels.js +150 -0
  346. package/dist/timeline/origin.d.ts +56 -0
  347. package/dist/timeline/origin.js +92 -0
  348. package/dist/timeline/render-text.d.ts +11 -0
  349. package/dist/timeline/render-text.js +62 -0
  350. package/dist/timeline/timeline.d.ts +282 -0
  351. package/dist/timeline/timeline.js +1308 -0
  352. package/dist/timeline/util.d.ts +17 -0
  353. package/dist/timeline/util.js +49 -0
  354. package/dist/tool-budget.d.ts +18 -0
  355. package/dist/tool-budget.js +50 -0
  356. package/dist/tool-gate.d.ts +47 -218
  357. package/dist/tool-gate.js +87 -545
  358. package/dist/tool-keys-store.d.ts +11 -12
  359. package/dist/tool-keys-store.js +24 -31
  360. package/dist/tool-keys.d.ts +5 -101
  361. package/dist/tool-keys.js +8 -267
  362. package/dist/tool-plane.d.ts +23 -52
  363. package/dist/tool-plane.js +23 -81
  364. package/dist/tool-settings-store.d.ts +1 -2
  365. package/dist/tool-settings-store.js +5 -8
  366. package/dist/tools.d.ts +67 -25
  367. package/dist/tools.js +170 -119
  368. package/dist/trigger-adapter.d.ts +2 -2
  369. package/dist/trigger-targets.d.ts +13 -1
  370. package/dist/trigger-targets.js +31 -1
  371. package/dist/triggers.d.ts +2 -2
  372. package/dist/triggers.js +3 -3
  373. package/dist/turn-end.d.ts +1 -1
  374. package/dist/turn-end.js +1 -1
  375. package/dist/turns.d.ts +0 -6
  376. package/dist/turns.js +0 -19
  377. package/dist/uploads.d.ts +28 -5
  378. package/dist/uploads.js +83 -10
  379. package/dist/usage.d.ts +1 -49
  380. package/dist/usage.js +3 -84
  381. package/dist/validate.d.ts +4 -0
  382. package/dist/validate.js +33 -14
  383. package/dist/webhooks.d.ts +102 -76
  384. package/dist/webhooks.js +266 -233
  385. package/dist/workflow-run.d.ts +114 -0
  386. package/dist/workflow-run.js +144 -0
  387. package/dist/workspace/archil-claim.d.ts +2 -2
  388. package/dist/workspace/archil-claim.js +4 -3
  389. package/dist/workspace/archil-disk.d.ts +10 -1
  390. package/dist/workspace/archil-disk.js +4 -0
  391. package/dist/workspace/archil-exec.d.ts +12 -2
  392. package/dist/workspace/archil-exec.js +16 -0
  393. package/dist/workspace/archil.d.ts +2 -2
  394. package/dist/workspace/archil.js +25 -5
  395. package/dist/workspace/attach.js +2 -0
  396. package/dist/workspace/beneath.d.ts +19 -0
  397. package/dist/workspace/beneath.js +106 -0
  398. package/dist/workspace/computer-deps.d.ts +26 -9
  399. package/dist/workspace/computer-deps.js +144 -43
  400. package/dist/workspace/computer-for-claim.d.ts +17 -14
  401. package/dist/workspace/computer-for-claim.js +99 -26
  402. package/dist/workspace/computer-hold.d.ts +6 -1
  403. package/dist/workspace/computer-hold.js +6 -1
  404. package/dist/workspace/computer-janitor.d.ts +47 -0
  405. package/dist/workspace/computer-janitor.js +182 -0
  406. package/dist/workspace/computer-ledger.d.ts +1 -8
  407. package/dist/workspace/computer-ledger.js +0 -3
  408. package/dist/workspace/computer-providers.d.ts +5 -3
  409. package/dist/workspace/computer-providers.js +11 -9
  410. package/dist/workspace/grep-worker.d.ts +5 -0
  411. package/dist/workspace/grep-worker.js +9 -6
  412. package/dist/workspace/hands.d.ts +5 -2
  413. package/dist/workspace/hands.js +4 -3
  414. package/dist/workspace/index.d.ts +6 -5
  415. package/dist/workspace/index.js +4 -4
  416. package/dist/workspace/local.d.ts +14 -2
  417. package/dist/workspace/local.js +170 -43
  418. package/dist/workspace/paths.js +3 -2
  419. package/dist/workspace/pi-env.d.ts +4 -0
  420. package/dist/workspace/pi-env.js +3 -2
  421. package/dist/workspace/resolve-computer.d.ts +55 -10
  422. package/dist/workspace/resolve-computer.js +66 -14
  423. package/dist/workspace/run-tools.d.ts +15 -31
  424. package/dist/workspace/run-tools.js +19 -30
  425. package/dist/workspace/workspace.d.ts +5 -0
  426. package/dist/workspace-paths.d.ts +0 -17
  427. package/dist/workspace-paths.js +1 -41
  428. package/dist/workspace.d.ts +0 -17
  429. package/dist/workspace.js +4 -110
  430. package/package.json +14 -14
  431. package/skills/agentrun-serve/SKILL.md +1 -1
  432. package/templates/README.md +11 -5
  433. package/templates/code-review/evals/mentions-defused/case.yaml +15 -0
  434. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +254 -0
  435. package/templates/code-review/evals/mentions-defused/graders/no-pings.md +16 -0
  436. package/templates/code-review/evals/mentions-defused/graders/posted-a-review.md +5 -0
  437. package/templates/code-review/evals/mentions-defused/graders/schema.md +5 -0
  438. package/templates/code-review/evals/mentions-defused/prompt.md +10 -0
  439. package/templates/kyb/evals/clean-public-company/graders/no-opensanctions.md +5 -0
  440. package/templates/kyb/evals/opensanctions-on/case.yaml +5 -0
  441. package/templates/kyb/evals/opensanctions-on/graders/licence-and-evidence.md +18 -0
  442. package/templates/kyb/evals/opensanctions-on/graders/schema.md +5 -0
  443. package/templates/kyb/evals/opensanctions-on/prompt.md +11 -0
  444. package/templates/market-monitor/agent.md +2 -2
  445. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  446. package/templates/release-notes/agent.md +11 -0
  447. package/dist/bound-files.d.ts +0 -4
  448. package/dist/bound-files.js +0 -164
  449. package/dist/coding-tools.d.ts +0 -47
  450. package/dist/coding-tools.js +0 -189
  451. package/dist/computer-adb.d.ts +0 -12
  452. package/dist/computer-adb.js +0 -14
  453. package/dist/console/assets/index-Dn0ngwG9.js +0 -535
  454. package/dist/console/assets/index-DvW6Aled.css +0 -1
  455. package/dist/grade.d.ts +0 -63
  456. package/dist/grade.js +0 -150
  457. package/dist/mcp-servers.d.ts +0 -269
  458. package/dist/mcp-servers.js +0 -456
  459. package/dist/packs.d.ts +0 -71
  460. package/dist/packs.js +0 -180
  461. package/dist/sealed-settings.d.ts +0 -60
  462. package/dist/sealed-settings.js +0 -171
  463. package/dist/sessions.d.ts +0 -6
  464. package/dist/sessions.js +0 -109
  465. package/dist/workspace/computer-serves.d.ts +0 -12
  466. package/dist/workspace/computer-serves.js +0 -15
@@ -0,0 +1,1308 @@
1
+ import { BROWSER_OPENERS, BROWSER_STEPS, callFailed, endsTurn, failedWith, inputPreview, labelOf, outcomeOf, refusedLabel, savedPaths } from "./labels.js";
2
+ import { cut, firstLine, firstSentence, json, obj, scrubUrls, str, utf8Bytes } from "./util.js";
3
+ import { BESIDE_SUFFIX, NOTE_SUFFIX, originMatcher, TRIGGER_LABELS } from "./origin.js";
4
+ /** Grep's caps, so a row is the same on both sides. `thinking` cuts the first sentence of a thinking summary. */
5
+ export const CAPS = { summary: 500, preview: 500, text: 2000, thinking: 100 };
6
+ /** A host's marks of a model request: as it leaves (written before it does), and as its stream ends aborted. A request
7
+ * that answered or failed has a `pi.assistant` entry; one aborted before its first content has none; a start with no
8
+ * end and no entry is in flight when it is the latest, unless the run is settled, and was cut by a crash when a later
9
+ * one followed it or the run settled without it. A cut request's cost is unknown. */
10
+ export const REQUEST_STARTED = "agentrun.request_started";
11
+ /** An end with `unsent: true` withdraws its start: the request was refused after its mark, and never left. */
12
+ export const REQUEST_ENDED = "agentrun.request_ended";
13
+ /** What a request with no `pi.assistant` entry of its own cost (a side request, marked with a `request` label: pi's
14
+ * compaction summary, `"compaction"`, or a tool's own model request, such as a web search's): `usd`, or null when
15
+ * unknown. It closes that request, as an entry closes a generation's. `failed`: the request failed, and its counts are
16
+ * taken as they are, as a failed answer's are. */
17
+ export const REQUEST_COST = "agentrun.request_cost";
18
+ /** A request the host refused before it left (the run was cancelled): pi answers it with an error entry, which is not a
19
+ * request and not a failure to show, so the timeline skips the error entry that answers each refusal. */
20
+ export const REQUEST_REFUSED = "agentrun.request_refused";
21
+ /** The key a host sets in a tool result's `details` (which only a reader of the result sees, never the model) when the
22
+ * call was refused before it ran (a gate's deny, a person's): `{ [CALL_REFUSED]: true }`. Its rows read as refused, the
23
+ * call in plain words ("Refused: write deny.md"), never as a call that ran and failed ("Wrote deny.md failed"). */
24
+ export const CALL_REFUSED = "agentrun.refused";
25
+ /** Whether pi's error for a request is the model proxy's own refusal of it for the run's spend cap, before it was sent:
26
+ * the proxy's JSON body after the HTTP status pi-ai puts first, read by its fields (`type` "agentrun_proxy", `code`
27
+ * "spend_cap_reached", as the proxy writes them), never by its words. Any other error, a provider's 400 included, is not. */
28
+ function proxyCapRefusal(errorMessage) {
29
+ if (typeof errorMessage !== "string")
30
+ return false;
31
+ const at = errorMessage.indexOf("{");
32
+ if (at < 0 || !/^\d{3}\s*$/.test(errorMessage.slice(0, at)))
33
+ return false;
34
+ try {
35
+ const error = JSON.parse(errorMessage.slice(at))?.error;
36
+ return error?.type === "agentrun_proxy" && error.code === "spend_cap_reached";
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ }
42
+ /** Written right after an answer whose cost was not in when it was written (a harness's proxy books a response after
43
+ * answering it): that answer's cost is still to come, as a REQUEST_COST_LATE. Until it comes the cost is unknown. */
44
+ export const REQUEST_COST_PENDING = "agentrun.request_cost_pending";
45
+ /** The cost (`usd`, or null when unknown) of an answer written earlier with its cost pending: it closes one pending cost
46
+ * and adds to the run's cost. It is not a request of its own: the answer already counted that. */
47
+ export const REQUEST_COST_LATE = "agentrun.request_cost_late";
48
+ /** What a paid tool's call charged, written apart from any request as the tool reports it: `tool` and `charged_by` name
49
+ * it, `usd` is the charge, or null when the call may have charged and did not say how much. It adds to the run's cost,
50
+ * which is then unknown on a null, and shows as a row of its own; it is no model request. The usage row counts paid
51
+ * tool calls by `call`: a call that books several charges (a browser call, and its session's release under it) is one
52
+ * paid tool call, and one charge not priced when any of them is unknown. A browser charge (BROWSER_CHARGE) shows on its
53
+ * call's row instead. */
54
+ export const TOOL_COST = "agentrun.tool_cost";
55
+ /** The `tool` of a browser session's charge (serve's browser-cost.ts: `call`, the call it ran under, or for a release the
56
+ * session's last call; `tag`, the session; `conversation`, the browser's conversation). It makes no row: it folds into
57
+ * that call's `tool_use` row, as its `usage`, else into the last browser call charged for its session, else into its
58
+ * conversation's last browser call; only a charge with none of these (its calls compacted away) keeps a row of its own.
59
+ * A charge booked after the row was shown (a release after the answer) changes that row, by its id. */
60
+ export const BROWSER_CHARGE = "browser";
61
+ /** The tool whose charge a row carries, for a host that sums a run's paid tools from its rows: a charge row's tool (a
62
+ * `phase` with `usage`), `browser` for a browser step's call row (`tool_name` in BROWSER_STEPS) with its folded charges;
63
+ * undefined for any other row: another tool's call row, whatever it carries, and the usage row. */
64
+ export const chargedTool = (row) => !row.usage ? undefined : row.kind === "phase" ? (row.tool_name ?? undefined) : row.kind === "tool_use" && row.tool_name !== null && BROWSER_STEPS.has(row.tool_name) ? BROWSER_CHARGE : undefined;
65
+ /** The spend cap's wrap-up (serve's cap.ts): the run's model was told once, near its cap, to finish (`words`, what it was
66
+ * told). A row of its own, the server's ("AgentRun: …"); no request, no cost. */
67
+ export const CAP_WRAPUP = "agentrun.cap_wrapup";
68
+ /** A tool call with no price, run outside the run's cost and its cap (an MCP tool its owner set no price for): `tool`,
69
+ * `charged_by` and `call` name it. It shows as a row of its own, "not metered", and the usage row counts it
70
+ * (`not_metered`); it is no charge and never makes the cost unknown. */
71
+ export const TOOL_UNMETERED = "agentrun.tool_unmetered";
72
+ /** A paid tool's call marked before it is sent (`call`, and `heldUsd`, the most it is held to charge): the TOOL_COST of
73
+ * the same `call` settles it. Unsettled, it is in flight while the run is; once the run is settled it was cut (a crash),
74
+ * and the cost is unknown, as for a cut model request: what it charged no one knows, and its held figure is the cap's
75
+ * bound (serve's cap.ts), never a charge. */
76
+ export const TOOL_STARTED = "agentrun.tool_started";
77
+ /** Written right before a `pi.assistant` that continues the answer before it: a call that answer asked for, written once
78
+ * the answer's own entry was already in (a harness reports each call as it runs it, and its host writes an answer at its
79
+ * first call's end). It shows as that answer's, and is no request: no count, no cost, no tokens. */
80
+ export const REQUEST_CONTINUED = "agentrun.request_continued";
81
+ /** A host's own step, in its words (`summary`), such as a box waiting for its image: one `phase` row with that summary,
82
+ * cut at CAPS.summary, at `at` (ms) when the host gave the time it happened, else at the time of the log before it. No
83
+ * request, no cost; one without a summary shows nothing. */
84
+ export const HOST_PHASE = "agentrun.phase";
85
+ const COMPACTION = "compaction";
86
+ const isCompaction = (entry) => obj(entry.data)?.request === COMPACTION;
87
+ /** A side request's mark: its `request` is a label (a generation's, a harness's request number, is not). */
88
+ const isSide = (entry) => typeof obj(entry.data)?.request === "string";
89
+ const unsent = (entry) => obj(entry.data)?.unsent === true;
90
+ /** A tool result an abort wrote (pi-durable's `aborted` diagnostic): the call was cut by a stop or a cancel, which ended
91
+ * its turn, not failed on its own. */
92
+ const abortedCall = (entry) => {
93
+ const diagnostics = obj(entry.data)?.diagnostics;
94
+ return Array.isArray(diagnostics) && diagnostics.some((diagnostic) => obj(diagnostic)?.code === "aborted");
95
+ };
96
+ /** Written on the root as a run's process opens to go on with a run its last process left unfinished: `after` is `crash`
97
+ * (that process died holding the run), `server_stop` (it drained as the server stopped) or `runner_lost` (a runner took
98
+ * the run over once the runner holding it, named by `runner`, let its lease run out), `generation` the new process's,
99
+ * `at` when it opened. A phase row of its own, at that time; no request. */
100
+ export const RUN_RESUMED = "agentrun.run_resumed";
101
+ /** The end of a turn on another harness (claude-agent, codex), written on a run's root by serve as the turn's last entry:
102
+ * `{ key, status, ... }`. No row. The turn is over, so the next message is the person's next one, never a steer, even
103
+ * when the turn's last entry was a tool's result (a stop that came after it, before the next model request). */
104
+ export const TURN_END = "adapter.turn_end";
105
+ /** How runMetricsOf keeps the names a run's entries hold, which a model writes and may make up: each is one the agent
106
+ * store takes (non-empty, at most `max` UTF-16 units, no lone surrogate), the same name always the same key. A longer
107
+ * one is cut to its first `max - 1` units and "…". A run keeps its `kept` busiest tools and models (the first seen of a
108
+ * tie); the rest are summed under `otherTools` or `otherModels`, and a tool result with no name counts under
109
+ * `unnamedTool`. Those three start with one "…", and no entry's name does: one that starts with "…" gets another. */
110
+ export const METRIC_NAMES = Object.freeze({ max: 256, kept: 100, otherTools: "…other tools", otherModels: "…other models", unnamedTool: "…unnamed tool" });
111
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
112
+ /** A name from an entry, non-empty, as runMetricsOf keeps it (METRIC_NAMES). */
113
+ function metricName(name) {
114
+ const whole = (name.startsWith("…") ? `…${name}` : name).replace(LONE_SURROGATE, "\uFFFD");
115
+ if (whole.length <= METRIC_NAMES.max)
116
+ return whole;
117
+ const kept = whole.slice(0, METRIC_NAMES.max - 1);
118
+ return `${/[\uD800-\uDBFF]$/.test(kept) ? kept.slice(0, -1) : kept}…`;
119
+ }
120
+ /** `counts` as a record of its METRIC_NAMES.kept busiest names (the first seen of a tie), the rest summed under `other`. */
121
+ function keepBusiest(counts, size, sum, other) {
122
+ if (counts.size <= METRIC_NAMES.kept)
123
+ return Object.fromEntries(counts);
124
+ const ranked = [...counts].sort(([, a], [, b]) => size(b) - size(a));
125
+ return Object.fromEntries([...ranked.slice(0, METRIC_NAMES.kept), [other, ranked.slice(METRIC_NAMES.kept).map(([, value]) => value).reduce(sum)]]);
126
+ }
127
+ const tokenCount = (value) => (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined);
128
+ /** A usage's tokens: undefined unless it has an input and an output count (a cache count it omits is 0), and unless it
129
+ * has some input. A request that reached a model always sent some, so a usage with none is a writer's zeros for a
130
+ * request it did not measure (an imported transcript's, a harness answer's written with no booking): unknown, never 0.
131
+ * `failed`: a failed request's counts are taken as they are, as its cost is. */
132
+ function tokensOf(usage, failed = false) {
133
+ const u = obj(usage);
134
+ const [input, output, cacheRead, cacheWrite] = [tokenCount(u?.input), tokenCount(u?.output), u?.cacheRead === undefined ? 0 : tokenCount(u.cacheRead), u?.cacheWrite === undefined ? 0 : tokenCount(u.cacheWrite)];
135
+ if (input === undefined || output === undefined || cacheRead === undefined || cacheWrite === undefined)
136
+ return undefined;
137
+ return failed || input + cacheRead + cacheWrite > 0 ? { input, cacheRead, cacheWrite, output } : undefined;
138
+ }
139
+ /** A run's model requests as its entries mark them: how many, what they cost and the tokens they used. The usage row
140
+ * and runMetricsOf count through it. `push` says what an entry was: an answer (a `pi.assistant` that is a request), a
141
+ * continuation of the answer before it (shown with it, not a request), a mark (a request's mark or cost, or pi's answer
142
+ * to a request that never left: nothing to show), or neither. */
143
+ function createMeter() {
144
+ let requests = 0;
145
+ // The run's cost: the known sum, the costs no one knows, and the costs written as pending, still to come (each with
146
+ // whether its answer's tokens were unknown: its late cost's usage then stands in for them).
147
+ let known = 0;
148
+ let unknown = 0;
149
+ // Paid tool calls whose charges are in the cost (TOOL_COST), each once however many it booked (paidCallOf), and calls
150
+ // with no price, run outside it (TOOL_UNMETERED).
151
+ const paidCalls = new Set();
152
+ // Of those, the calls with a charge whose cost is unknown: each one charge not priced, however many it booked.
153
+ const unpricedCalls = new Set();
154
+ // The call each browser session was last charged under (BROWSER_CHARGE's `tag`): a charge of it with no call of its
155
+ // own, a release after the run's last call, is that call's.
156
+ const sessionCall = new Map();
157
+ let notMetered = 0;
158
+ /** The paid call a TOOL_COST is for: its `call`; a browser charge with none (a release a reopened process made), the
159
+ * call its session was last charged under; else a call of its own, as an older entry with no `call` is. */
160
+ const paidCallOf = (data) => {
161
+ const [call, tag] = [str(data?.call), data?.tool === BROWSER_CHARGE ? str(data?.tag) : undefined];
162
+ if (call && tag)
163
+ sessionCall.set(tag, call);
164
+ return call ?? (tag ? sessionCall.get(tag) : undefined) ?? `#${(unplaced += 1)}`;
165
+ };
166
+ // Charges that name no call the run can place: each a call of its own.
167
+ let unplaced = 0;
168
+ // Paid tool calls marked and not yet settled, by call.
169
+ const held = new Map();
170
+ const pending = [];
171
+ const addCost = (cost) => (typeof cost === "number" && Number.isFinite(cost) ? (known += cost) : (unknown += 1));
172
+ let marked = 0;
173
+ let inFlight = false;
174
+ let refused = 0;
175
+ // Requests a host's spend cap refused (a start mark of their own, `capRefused`), still to be answered by pi's error
176
+ // entry: never sent, so no request, no cost and no figure. A request started after one means its entry never came.
177
+ let capRefusals = 0;
178
+ // Whether the cap refused one: a run with no request but that refusal says so on its usage line.
179
+ let refusedAny = false;
180
+ // What the cap limited the latest generation request's output to, when it did (its start mark's `clamp`).
181
+ let lastClamp;
182
+ // Continuations of an answer still to come (REQUEST_CONTINUED): each next pi.assistant shows and is not counted.
183
+ let continued = 0;
184
+ // Answers to marked requests: those after the first mark (a request is marked before it leaves, so before its
185
+ // answer). Earlier answers are a run's from before requests were marked.
186
+ let answered = 0;
187
+ // Side requests (compactions, a tool's own requests), apart: one may run beside a generation. Each closes with its
188
+ // cost, or with an end when aborted.
189
+ let compactions = 0;
190
+ let compacting = 0;
191
+ // How many are in flight: two side requests (a turn's parallel searches) may be.
192
+ let sidesOpen = 0;
193
+ const tokens = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 };
194
+ // Requests whose tokens are unknown, and whether the latest answer's were.
195
+ let unmetered = 0;
196
+ let lastUnmetered = false;
197
+ const addTokens = (counted) => {
198
+ if (!counted)
199
+ return void (unmetered += 1);
200
+ for (const key of ["input", "cacheRead", "cacheWrite", "output"])
201
+ tokens[key] += counted[key];
202
+ };
203
+ const models = new Map();
204
+ function push(entry) {
205
+ const message = entry.model?.[0];
206
+ const data = obj(entry.data);
207
+ if (entry.kind === REQUEST_REFUSED) {
208
+ refused += 1;
209
+ }
210
+ else if (entry.kind === "pi.assistant" && refused > 0 && message?.stopReason === "error") {
211
+ // pi's answer to a request that never left: nothing to count or show.
212
+ refused -= 1;
213
+ }
214
+ else if (entry.kind === REQUEST_CONTINUED) {
215
+ continued += 1;
216
+ }
217
+ else if (entry.kind === "pi.assistant" && continued > 0 && message) {
218
+ // The answer before it, continued: shown, never counted again.
219
+ continued -= 1;
220
+ return "continued";
221
+ }
222
+ else if (entry.kind === REQUEST_STARTED && isSide(entry)) {
223
+ compacting += 1;
224
+ sidesOpen += 1;
225
+ }
226
+ else if (entry.kind === REQUEST_ENDED && isSide(entry)) {
227
+ if (unsent(entry))
228
+ compacting -= 1;
229
+ sidesOpen = Math.max(0, sidesOpen - 1);
230
+ }
231
+ else if (entry.kind === REQUEST_COST) {
232
+ compactions += 1;
233
+ sidesOpen = Math.max(0, sidesOpen - 1);
234
+ addCost(data?.usd);
235
+ addTokens(tokensOf(data?.usage, data?.failed === true));
236
+ }
237
+ else if (entry.kind === TOOL_STARTED) {
238
+ held.set(str(data?.call) ?? `#${held.size}`, data?.heldUsd);
239
+ }
240
+ else if (entry.kind === TOOL_COST) {
241
+ held.delete(str(data?.call) ?? "");
242
+ const call = paidCallOf(data);
243
+ paidCalls.add(call);
244
+ // Its cost joins the run's; an unknown one makes it unknown, counted once for its call.
245
+ const usd = data?.usd;
246
+ if (typeof usd === "number" && Number.isFinite(usd))
247
+ known += usd;
248
+ else if (!unpricedCalls.has(call))
249
+ (unpricedCalls.add(call), (unknown += 1));
250
+ return "charge";
251
+ }
252
+ else if (entry.kind === TOOL_UNMETERED) {
253
+ notMetered += 1;
254
+ return "unmetered";
255
+ }
256
+ else if (entry.kind === REQUEST_COST_PENDING) {
257
+ // The answer just before it was counted as a cost unknown: it is one still to come.
258
+ if (unknown > 0)
259
+ (unknown -= 1), pending.push(lastUnmetered);
260
+ }
261
+ else if (entry.kind === REQUEST_COST_LATE) {
262
+ // The answer it prices was written before its usage came in: its usage, when it has one, is that answer's tokens.
263
+ const late = tokensOf(data?.usage);
264
+ if (pending.shift() && late)
265
+ (unmetered -= 1), addTokens(late);
266
+ addCost(data?.usd);
267
+ }
268
+ else if (entry.kind === REQUEST_STARTED && data?.capRefused === true) {
269
+ // Its own mark, written before pi's entry for it: a request that never left marks nothing and holds nothing.
270
+ capRefusals += 1;
271
+ }
272
+ else if (entry.kind === "pi.assistant" && capRefusals > 0 && message?.stopReason === "error") {
273
+ // pi's entry for a request the cap refused: shown as the refusal, never counted.
274
+ capRefusals -= 1;
275
+ refusedAny = true;
276
+ return "refusal";
277
+ }
278
+ else if (entry.kind === "pi.assistant" && message?.stopReason === "error" && proxyCapRefusal(message.errorMessage)) {
279
+ // pi's entry for a request the model proxy refused for the run's spend cap before sending it: no request, no cost,
280
+ // and no row (the run's park at its cap says what happened).
281
+ refusedAny = true;
282
+ }
283
+ else if (entry.kind === REQUEST_STARTED) {
284
+ capRefusals = 0;
285
+ marked += 1;
286
+ inFlight = true;
287
+ lastClamp = clampOf(data?.clamp);
288
+ }
289
+ else if (entry.kind === REQUEST_ENDED) {
290
+ if (unsent(entry))
291
+ marked -= 1;
292
+ inFlight = false;
293
+ }
294
+ else if (entry.kind === "pi.assistant" && message) {
295
+ requests += 1;
296
+ if (marked > 0)
297
+ answered += 1;
298
+ const name = str(message.model);
299
+ if (name) {
300
+ const key = metricName(str(message.provider) ? `${str(message.provider)}/${name}` : name);
301
+ models.set(key, (models.get(key) ?? 0) + 1);
302
+ }
303
+ // A request cut before its end has no final usage: its stream had reported none (the Responses API reports it at
304
+ // the end) or only the start (Anthropic's input and first token), never what the provider charged. Unknown.
305
+ const aborted = message.stopReason === "aborted";
306
+ addCost(aborted ? undefined : obj(obj(message.usage)?.cost)?.total);
307
+ const counted = aborted ? undefined : tokensOf(message.usage, message.stopReason === "error");
308
+ lastUnmetered = !counted;
309
+ addTokens(counted);
310
+ return "answer";
311
+ }
312
+ else
313
+ return undefined;
314
+ return "mark";
315
+ }
316
+ /** The usage row's count and cost; undefined while there is nothing to count. `settled`: nothing is running. While the
317
+ * cost is unknown, `so_far_usd` is the sum of the charges whose cost is known and `unpriced` how many have none: each
318
+ * cost no one knows (an answer or summary with none, a stopped request's, a paid tool charge), each still pending, each
319
+ * request cut before any answer, and each paid tool call a settled run never settled. No ceiling is claimed. */
320
+ function usage(settled) {
321
+ // A request marked as it left with no entry for it, other than one still in flight: counted, at a cost no one knows.
322
+ // One in flight alone makes no row yet, so the row appears where it did before requests were marked.
323
+ // A settled run has nothing in flight: its last request with no entry, or its open compaction, was cut by the
324
+ // process that ended.
325
+ const open = (flying) => (flying && !settled ? 1 : 0);
326
+ const cut = marked - open(inFlight) > answered || compacting - (settled ? 0 : sidesOpen) > compactions;
327
+ // A paid tool call cut by a crash: its charge is unknown, so the cost is.
328
+ const cutCalls = settled ? held.size : 0;
329
+ const unmetered = notMetered ? { not_metered: notMetered } : {};
330
+ if (!requests && !compactions && !cut && !paidCalls.size && !cutCalls)
331
+ return refusedAny || notMetered ? { usd: 0, requests: 0, charges: 0, ...unmetered } : undefined;
332
+ const count = requests + Math.max(0, marked - answered) + Math.max(compactions, compacting);
333
+ const usd = unknown > 0 || pending.length > 0 || cut || cutCalls > 0 ? null : Math.round(known * 1e6) / 1e6;
334
+ const unpriced = unknown + pending.length + Math.max(0, marked - open(inFlight) - answered) + Math.max(0, compacting - (settled ? 0 : sidesOpen) - compactions) + cutCalls;
335
+ return { usd, requests: count, charges: paidCalls.size + cutCalls, ...(usd === null && unpriced > 0 ? { so_far_usd: Math.round(known * 1e6) / 1e6, unpriced } : {}), ...unmetered };
336
+ }
337
+ // A workflow's decision requests (Jev, Parallel), from its receipts: requests of their own, beside its entries'.
338
+ let decided = 0;
339
+ function decide(row) {
340
+ decided += 1;
341
+ const name = str(row.model);
342
+ if (name) {
343
+ const key = metricName(str(row.provider) ? `${str(row.provider)}/${name}` : name);
344
+ models.set(key, (models.get(key) ?? 0) + 1);
345
+ }
346
+ // A cancelled request's tokens are unknown, as an aborted answer's are; so are those of one whose spend its driver's
347
+ // state keeps, which no record here holds.
348
+ const u = obj(row.usage);
349
+ addTokens(row.status === "cancelled" || row.driver_spend === true || !u ? undefined : tokensOf({ input: u.input_tokens, output: u.output_tokens }, row.status === "failed"));
350
+ }
351
+ /** The counts of a run that ended: a request it cut has unknown tokens. */
352
+ function settled() {
353
+ const all = (usage(true)?.requests ?? 0) + decided;
354
+ const cut = Math.max(0, marked - answered) + Math.max(0, compacting - compactions);
355
+ let model;
356
+ for (const [key, n] of models)
357
+ if (model === undefined || n > models.get(model))
358
+ model = key;
359
+ const kept = keepBusiest(models, (n) => n, (a, b) => a + b, METRIC_NAMES.otherModels);
360
+ return { ...tokens, requests: all, unmetered: Math.min(all, unmetered + cut), models: kept, ...(model !== undefined ? { model } : {}) };
361
+ }
362
+ return { push, decide, usage, clamp: () => lastClamp, settled };
363
+ }
364
+ const TAG = /^[\w.-]{1,64}$/;
365
+ const blocksOf = (message) => {
366
+ const content = message?.content;
367
+ return Array.isArray(content) ? content.flatMap((block) => { const one = obj(block); return one ? [one] : []; }) : typeof content === "string" ? [{ type: "text", text: content }] : [];
368
+ };
369
+ const textOf = (message, type = "text", field = "text") => blocksOf(message).filter((block) => block.type === type).map((block) => str(block[field]) ?? "").join("\n").trim();
370
+ /** Every string a row shows goes through here: a URL keeps its origin, path and query keys, then the text is cut. */
371
+ const clean = (text, max) => cut(scrubUrls(text), max);
372
+ /** The rows that show words as a person or the agent wrote them: cut, never scrubbed. */
373
+ const WHOLE = new Set(["user_message", "text_block", "final_answer"]);
374
+ /** An error's whole text as the host's `redact` makes it, before its first line becomes a summary or either is cut, so
375
+ * neither keeps part of what the whole text's redaction takes out. */
376
+ const redactOf = (options) => (text) => (options.redact ? options.redact(text) : text);
377
+ const dollars = (usd) => (usd === 0 ? "$0" : `$${usd.toFixed(4)}`);
378
+ function clampOf(value) {
379
+ const clamp = obj(value);
380
+ const [tokens, leftUsd, capUsd] = [clamp?.tokens, clamp?.leftUsd, clamp?.capUsd];
381
+ const amount = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0;
382
+ return Number.isSafeInteger(tokens) && tokens > 0 && amount(leftUsd) && amount(capUsd) ? { tokens: tokens, leftUsd, capUsd } : undefined;
383
+ }
384
+ /** An amount in words: two decimals, or as many as it takes (up to six) to show it. */
385
+ function amount(usd) {
386
+ for (let digits = 2; digits < 6; digits++)
387
+ if (Number(usd.toFixed(digits)) === Number(usd.toFixed(6)))
388
+ return `$${usd.toFixed(digits)}`;
389
+ return `$${usd.toFixed(6)}`;
390
+ }
391
+ /** What a reply the cap's clamp cut short says. */
392
+ const clampSaid = (clamp) => `The reply stopped at ${clamp.tokens.toLocaleString("en-US")} tokens: all that the ${amount(clamp.leftUsd)} left of the run's ${amount(clamp.capUsd)} cap could buy.`;
393
+ /** The message of a result that is only the harness's diagnostics block (`<harness>`, then `[error] …` lines), as a
394
+ * call that threw or named a tool its run does not offer answers: its first error's, else its first line's, without
395
+ * the severity. Undefined for any other text, whose own first line says what happened. */
396
+ function diagnosticOf(text) {
397
+ const lines = text.trim().split("\n").map((line) => line.trim());
398
+ if (lines[0] !== "<harness>")
399
+ return undefined;
400
+ const end = lines.indexOf("</harness>");
401
+ const inner = lines.slice(1, end < 0 ? undefined : end).filter(Boolean);
402
+ const said = inner.map((line) => /^\[(\w+)\]\s*(.*)$/.exec(line)).filter((match) => match !== null);
403
+ const first = said.find((match) => match[1] === "error") ?? said[0];
404
+ return first ? (first[2] ?? "") : (inner[0] ?? "");
405
+ }
406
+ /** A browser call that waited for the person to hand the browser back (pi-browser's `waited_for_person_ms` in its
407
+ * result's details) says so first, and for how long: its row spans the person's take-over, and without it the call
408
+ * reads as the agent acting while the person had the browser. "then <what it did>" only for a call that succeeded: one
409
+ * that failed after its wait reads "Waited for you 11 s: <its label> failed: …", never as having acted. */
410
+ const WAITED_FOR_PERSON = "waited_for_person_ms";
411
+ /** A browser act the person's take made stale (pi-browser's `page_changed_while_held` in its result's details): the person
412
+ * drove the page while the call waited, so the call did nothing and the agent takes a new look. Its rows say so in these
413
+ * words, neutral, never as a failure. */
414
+ const PAGE_CHANGED_WHILE_HELD = "page_changed_while_held";
415
+ export const PAGE_CHANGED_ROW = "The page changed while you had the browser; the agent takes a new look";
416
+ const pageChanged = (tool, result) => BROWSER_STEPS.has(tool) && obj(result?.details)?.[PAGE_CHANGED_WHILE_HELD] === true;
417
+ const waitedFirst = (tool, result, said) => {
418
+ const ms = obj(result?.details)?.[WAITED_FOR_PERSON];
419
+ if (!BROWSER_STEPS.has(tool) || typeof ms !== "number" || !Number.isFinite(ms) || ms <= 0)
420
+ return said;
421
+ const long = ms < 1000 ? `${Math.round(ms)} ms` : `${Math.round(ms / 1000)} s`;
422
+ if (callFailed(tool, result))
423
+ return `Waited for you ${long}: ${said}`;
424
+ return `Waited for you ${long}, then ${said.charAt(0).toLowerCase()}${said.slice(1)}`;
425
+ };
426
+ /** One place turns entries into rows, whether they come from a released store or from live events. */
427
+ function createProjector(options) {
428
+ const redactedWhy = redactOf(options);
429
+ const caps = { ...CAPS, ...options.caps };
430
+ /** A call's arguments as its rows name them: its file path as the host names it (`options.path`). */
431
+ const shown = (args) => {
432
+ if (!options.path)
433
+ return args;
434
+ const named = (value) => (typeof value === "string" && value ? options.path(value) : value);
435
+ return "path" in args || "file_path" in args ? { ...args, ...("path" in args ? { path: named(args.path) } : {}), ...("file_path" in args ? { file_path: named(args.file_path) } : {}) } : args;
436
+ };
437
+ const label = (tool, args, result) => (pageChanged(tool, result) ? PAGE_CHANGED_ROW : waitedFirst(tool, result, labelOf(tool, shown(args), result, options.labels)));
438
+ const seen = new Set();
439
+ const calls = new Map();
440
+ // Results stored before their call (a harness bridge once wrote a result before the answer holding its call), by
441
+ // `conversation:id`: the call, when it comes, takes its result and is done.
442
+ const early = new Map();
443
+ const previous = new Map();
444
+ // Whether every tool of the conversation's latest round ends the turn, or a turn's end (TURN_END) came after it: then
445
+ // the turn is over, and what comes next is the person's next message, not a steer.
446
+ const ended = new Map();
447
+ // Conversations whose turn an abort cut since their latest tool round (a stop, a cancel): an aborted tool, or a model
448
+ // request that had left and was aborted. That turn is over too, so the next message comes in a new turn, never a steer.
449
+ const cutTurns = new Set();
450
+ const systems = new Set();
451
+ const browsers = new Set();
452
+ // Browser charges (BROWSER_CHARGE), folded into their call's row: what each row's charges sum to, the call each session
453
+ // was last charged under, and each conversation's latest browser call.
454
+ const folded = new Map();
455
+ const sessionCalls = new Map();
456
+ const browserCalls = new Map();
457
+ const children = new Map();
458
+ const rows = [];
459
+ let seq = 0;
460
+ let stamp = 0;
461
+ let root;
462
+ let current = options.conversationId ?? 0;
463
+ const meter = createMeter();
464
+ // Each conversation's latest answer, by entry id: a continuation's calls show under it.
465
+ const answers = new Map();
466
+ // Per conversation, the text answer that ended its request, until its turn shows whether it was the last thing said: a
467
+ // later answer, or a continuation, with text or a call makes it a text_block (a harness's commentary before a tool of
468
+ // its own, which its host never sees as a call); a person's message settles it. A later answer of the same turn, an
469
+ // empty one too, takes its place, so the earlier one is a text_block then.
470
+ const provisional = new Map();
471
+ /** Which user entries the server wrote (origin.ts): each shows as the server's, never as the person's. */
472
+ const origins = originMatcher();
473
+ function make(kind, conv, id, fields = {}) {
474
+ const timestamp = new Date(stamp).toISOString();
475
+ const next = seq++;
476
+ const row = {
477
+ id, timestamp, created_at: timestamp, kind, summary: null, agent_label: options.agentLabel?.(conv) ?? null,
478
+ tool_name: null, tool_use_id: null, tool_status: null, tool_input_preview: null, tool_result_preview: null,
479
+ tool_result_size_bytes: null, text: null, conversation_id: conv, ...fields, seq: fields.seq ?? next,
480
+ };
481
+ const parent = fields.parent_tool_use_id ?? children.get(conv);
482
+ if (parent !== undefined)
483
+ row.parent_tool_use_id = parent;
484
+ if (kind === "error" && options.redact) {
485
+ if (row.summary !== null)
486
+ row.summary = options.redact(row.summary);
487
+ if (row.text !== null)
488
+ row.text = options.redact(row.text);
489
+ }
490
+ // A person's own message and the agent's own words (its text, its answer) show as written, their held keys redacted
491
+ // (readMessage): a URL in them keeps its fragment and query values. scrubUrls is for the URLs of what the model read
492
+ // (a tool's result, a page's title, a call's arguments) and for its thinking.
493
+ const whole = WHOLE.has(kind);
494
+ if (row.summary !== null)
495
+ row.summary = whole ? cut(row.summary, caps.summary) : clean(row.summary, caps.summary);
496
+ if (row.tool_input_preview !== null)
497
+ row.tool_input_preview = clean(row.tool_input_preview, caps.preview);
498
+ if (row.tool_result_preview !== null)
499
+ row.tool_result_preview = clean(row.tool_result_preview, caps.preview);
500
+ if (row.text !== null)
501
+ row.text = whole ? cut(row.text, caps.text) : clean(row.text, caps.text);
502
+ for (const key of ["round", "parent_tool_use_id", "session", "path", "usage", "origin"])
503
+ if (row[key] === undefined)
504
+ delete row[key];
505
+ return row;
506
+ }
507
+ const viewOf = (message) => ({ text: textOf(message), details: message.details, isError: message.isError === true });
508
+ /** Text as the host's `redact` makes it (as given without one). */
509
+ const redactText = (text) => (options.redact && text ? options.redact(text) : text);
510
+ /** A value (a call's arguments, a result's details) with each of its strings as the host's `redact` makes it, so a
511
+ * label, a preview or an answer taken from it holds none of what redaction takes out. */
512
+ const redactValue = (value) => {
513
+ if (!options.redact)
514
+ return value;
515
+ if (typeof value === "string")
516
+ return redactText(value);
517
+ if (Array.isArray(value))
518
+ return value.map(redactValue);
519
+ if (value && typeof value === "object")
520
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redactValue(item)]));
521
+ return value;
522
+ };
523
+ /** A call's arguments as its rows may show them: redacted once, where the call is first seen (redactValue). */
524
+ const argsOf = (args) => (options.redact ? redactValue(args) : args);
525
+ /** An outcome's words as the summary shows them: its verdict (`failed:`, `refused:`) as read, and only what follows it
526
+ * redacted, so a redaction that takes the whole detail still leaves the verdict, as the row's status says. */
527
+ const saidOf = (text) => {
528
+ const verdict = /^(\w+): /.exec(text);
529
+ return verdict ? `${verdict[1]}: ${scrubUrls(firstLine(redactText(text.slice(verdict[0].length))))}` : scrubUrls(firstLine(redactText(text)));
530
+ };
531
+ /** A result as its rows show it: its whole output redacted once, which its label, summary and preview are all taken
532
+ * from (resultRow); its details and error flag as they came. */
533
+ const shownOf = (view) => options.redact ? { ...view, text: view.text ? options.redact(view.text) : view.text, details: redactValue(view.details) } : view;
534
+ const failure = (text) => scrubUrls(firstLine(str(json(text)?.message) ?? diagnosticOf(text) ?? text)) || "no detail";
535
+ /** Whether a result is a call's refusal before it ran: an error its host marked so in its details (CALL_REFUSED),
536
+ * read by that field, never by its words. */
537
+ const refused = (view) => view.isError && obj(view.details)?.[CALL_REFUSED] === true;
538
+ /** A call's name on its rows: a refused one's in plain words (refusedLabel), else its label. */
539
+ const nameFor = (tool, args, view, result) => (refused(view) ? refusedLabel(tool, shown(args)) : label(tool, args, result));
540
+ /** The `tool_use` row of a call; `fields` is what differs between a stored call and a nested one. */
541
+ const useRow = (conv, rowId, callId, name, args, fields) => make("tool_use", conv, rowId, { summary: label(name, args), tool_name: name, tool_use_id: callId, tool_input_preview: inputPreview(args, caps.preview), ...fields });
542
+ /** The `tool_result` row of a finished call, named `named`; `parent` is a nested call's caller. */
543
+ /** A call that returned but whose result says it did not do its work (a refused fetch) reads as that, failed. Its
544
+ * outcome is read once, for the summary and the status both. */
545
+ /** A tool's output, like an error, can carry a key its provider echoed. What its rows show of it (the call's label, the
546
+ * result's summary and preview) comes from `shown`, its whole text as the host's `redact` makes it (shownOf, once per
547
+ * result), before any of it is taken or cut, so none keeps a piece of a key. Whether it failed, and why, is read from
548
+ * the output as it came (`view`), as its status is; only the words the summary shows of that are redacted. */
549
+ const resultRow = (conv, rowId, tool, named, view, shown, parent) => {
550
+ const outcome = outcomeOf(tool.name, view);
551
+ // A call refused before it ran is named refused already (refusedLabel): its row says why, never that it failed.
552
+ const failedSummary = refused(view) ? `${named}: ${failure(shown.text)}` : `${named} failed: ${failure(shown.text)}`;
553
+ return make("tool_result", conv, rowId, {
554
+ summary: !view.isError && pageChanged(tool.name, view) ? PAGE_CHANGED_ROW : view.isError ? failedSummary : outcome ? `${named}: ${saidOf(outcome.text)}` : `${named}: ok`, tool_name: tool.name, tool_use_id: tool.callId,
555
+ tool_status: failedWith(view, outcome) ? "failed" : "success", tool_result_preview: shown.text ? cut(scrubUrls(shown.text), caps.preview) : null,
556
+ tool_result_size_bytes: utf8Bytes(view.text), round: tool.round, parent_tool_use_id: parent,
557
+ });
558
+ };
559
+ /** The call a browser charge belongs to (BROWSER_CHARGE): the one it names, else its session's last charged call, else
560
+ * its conversation's latest browser call. Only a browser step's call (BROWSER_STEPS), so every row a charge folds into
561
+ * is one chargedTool names the browser's. Undefined when none is in these rows. */
562
+ function browserCallOf(data) {
563
+ const [id, tag] = [str(data?.call), str(data?.tag)];
564
+ const conv = typeof data?.conversation === "number" ? data.conversation : undefined;
565
+ const found = id ? ((conv === undefined ? undefined : calls.get(`${conv}:${id}`)) ?? [...calls.values()].find((call) => call.use.tool_use_id === id)) : undefined;
566
+ const named = found && BROWSER_STEPS.has(found.name) ? found : undefined;
567
+ const call = named ?? (tag ? sessionCalls.get(tag) : undefined) ?? (conv === undefined ? undefined : browserCalls.get(conv));
568
+ if (call && tag)
569
+ sessionCalls.set(tag, call);
570
+ return call;
571
+ }
572
+ /** Adds a browser charge (`usd`, null when unknown) to the `usage` of its call's row, which is returned. The row is one
573
+ * call, so a charge with no price makes it one not priced (`unpriced: 1`) however many it booked, as the usage row
574
+ * counts a paid call once. */
575
+ function foldCharge(row, usd) {
576
+ const sum = folded.get(row) ?? { known: 0, unpriced: false };
577
+ if (usd === null)
578
+ sum.unpriced = true;
579
+ else
580
+ sum.known += usd;
581
+ folded.set(row, sum);
582
+ const known = Math.round(sum.known * 1e12) / 1e12;
583
+ row.usage = sum.unpriced ? { usd: null, requests: 0, so_far_usd: known, unpriced: 1 } : { usd: known, requests: 0 };
584
+ return row;
585
+ }
586
+ /** A call that spawned a conversation: its rows, and the child's, now name it as their parent. */
587
+ function adopt(conv, child, callId, args, fallback) {
588
+ if (children.has(child) || child === conv)
589
+ return [];
590
+ children.set(child, callId);
591
+ const patched = rows.filter((row) => row.conversation_id === child);
592
+ for (const row of patched)
593
+ row.parent_tool_use_id ??= callId;
594
+ const task = str(args.task) ?? str(args.prompt) ?? str(args.description) ?? fallback;
595
+ const started = make("subagent_started", conv, `${conv}:sub:${callId}`, { summary: `Subagent: ${firstLine(task)}`, tool_use_id: callId });
596
+ rows.push(started);
597
+ return [...patched, started];
598
+ }
599
+ function push(entry) {
600
+ const conv = entry.conversationId ?? options.conversationId ?? 0;
601
+ if (entry.id !== undefined) {
602
+ const key = `${conv}:${entry.id}`;
603
+ if (seen.has(key))
604
+ return [];
605
+ seen.add(key);
606
+ }
607
+ root ??= conv;
608
+ current = conv;
609
+ const message = entry.model?.[0];
610
+ const origin = origins({ ...entry, conversationId: conv });
611
+ const at = message?.timestamp;
612
+ if (typeof at === "number" && Math.abs(at) <= 8.64e15)
613
+ stamp = at;
614
+ const base = `${conv}:${entry.id ?? seq}`;
615
+ const out = [];
616
+ const add = (row) => { rows.push(row); out.push(row); };
617
+ const touch = (row) => { if (!out.includes(row))
618
+ out.push(row); };
619
+ if (entry.kind === CAP_WRAPUP) {
620
+ // What the run's model was told near its cap: the server's row (`origin: "server"`, in the words of its other rows),
621
+ // no request, no cost, and no message any turn took (its id ends in NOTE_SUFFIX, which isMessageRow passes over).
622
+ const words = str(obj(entry.data)?.words);
623
+ if (words)
624
+ add(make("phase", conv, `${base}${NOTE_SUFFIX}`, { summary: `AgentRun: ${words}`, text: words, origin: "server" }));
625
+ return out;
626
+ }
627
+ const metered = meter.push(entry);
628
+ if (metered === "mark") {
629
+ // A request's mark or cost, or pi's answer to a request that never left: counted, nothing to show.
630
+ }
631
+ else if (metered === "refusal" && message) {
632
+ // A request the run's cap refused, never sent: no request. Its text is the error as written (a host reads its code
633
+ // from it), its summary the cap's own words, after the code ("Not sent: ...").
634
+ const why = redactedWhy(str(message.errorMessage) ?? "spend_cap_reached: Not sent: the run's spend cap refused the request.");
635
+ const words = why.replace(/^spend_cap_reached(?: \([^)]*\))?: /, "");
636
+ add(make("error", conv, base, { summary: firstLine(words.startsWith("Not sent:") ? words : `Not sent: ${words}`), text: why }));
637
+ }
638
+ else if (metered === "charge") {
639
+ // A paid tool's charge: counted in the cost, and shown on a line of its own, or a browser's on its call's row.
640
+ const data = obj(entry.data);
641
+ const [tool, by, usd] = [str(data?.tool) ?? "a tool", str(data?.charged_by) ?? "its provider", data?.usd];
642
+ const amount = typeof usd === "number" && Number.isFinite(usd) ? dollars(usd) : "an unknown amount";
643
+ // Its `usage` is the charge alone (no request): a host sums a run's paid tools from the same rows as its cost.
644
+ const charge = typeof usd === "number" && Number.isFinite(usd) ? usd : null;
645
+ const call = tool === BROWSER_CHARGE ? browserCallOf(data) : undefined;
646
+ if (call)
647
+ touch(foldCharge(call.use, charge));
648
+ else
649
+ add(make("phase", conv, base, { summary: `Tool cost: ${by} charged ${amount} for ${tool}`, tool_name: tool, tool_use_id: str(data?.call) ?? null, usage: { usd: charge, requests: 0 } }));
650
+ }
651
+ else if (metered === "unmetered") {
652
+ // A call with no price: shown, never counted in the cost.
653
+ const data = obj(entry.data);
654
+ const tool = str(data?.tool) ?? "a tool";
655
+ add(make("phase", conv, base, { summary: `Not metered: ${tool} has no price set, so it is outside the run's cost`, tool_name: tool, tool_use_id: str(data?.call) ?? null }));
656
+ }
657
+ else if ((metered === "answer" || metered === "continued") && message) {
658
+ const round = metered === "continued" && answers.has(conv) ? answers.get(conv) : entry.id;
659
+ if (metered === "answer")
660
+ answers.set(conv, entry.id);
661
+ if (message.stopReason === "error") {
662
+ const why = redactedWhy(str(message.errorMessage) ?? "unknown error");
663
+ add(make("error", conv, base, { summary: `Model request failed: ${firstLine(why)}`, text: why }));
664
+ }
665
+ else if (message.stopReason !== "aborted") {
666
+ const blocks = blocksOf(message);
667
+ const settled = provisional.get(conv);
668
+ if (settled && (textOf(message) || blocks.some((block) => block.type === "toolCall"))) {
669
+ settled.kind = "text_block";
670
+ touch(settled);
671
+ provisional.delete(conv);
672
+ }
673
+ const first = (type) => blocks.findIndex((block) => block.type === type);
674
+ const thinking = scrubUrls(redactText(textOf(message, "thinking", "thinking")));
675
+ if (thinking)
676
+ add(make("thinking", conv, `${base}:${first("thinking")}`, { summary: `Thinking: ${cut(firstSentence(thinking), caps.thinking)}`, text: thinking }));
677
+ const text = redactText(textOf(message));
678
+ const final = message.stopReason === "stop" && !blocks.some((block) => block.type === "toolCall");
679
+ // A final stop's text block is its answer even when empty: the model ended its turn on purpose, with nothing to
680
+ // say. A message with no text block (a request the adapter bridge writes without content) shows none.
681
+ // An answer its turn goes on from is a text_block (provisional, below), an empty one too.
682
+ if (text || (final && first("text") >= 0)) {
683
+ const row = make(final ? "final_answer" : "text_block", conv, `${base}:${first("text")}`, { summary: firstLine(text), text });
684
+ add(row);
685
+ if (final) {
686
+ const earlier = provisional.get(conv);
687
+ if (earlier) {
688
+ earlier.kind = "text_block";
689
+ touch(earlier);
690
+ }
691
+ provisional.set(conv, row);
692
+ }
693
+ }
694
+ // A reply that stopped at the output its request's cap limited it to says so, with the numbers.
695
+ const clamp = metered === "answer" && message.stopReason === "length" ? meter.clamp() : undefined;
696
+ if (clamp)
697
+ add(make("phase", conv, `${base}:clamp`, { summary: clampSaid(clamp) }));
698
+ blocks.forEach((block, index) => {
699
+ const [id, name] = [str(block.id), str(block.name)];
700
+ if (block.type !== "toolCall" || !id || !name)
701
+ return;
702
+ const args = argsOf(obj(block.arguments) ?? {});
703
+ if (BROWSER_OPENERS.has(name) && !browsers.has(conv)) {
704
+ browsers.add(conv);
705
+ add(make("phase", conv, `${base}:${index}:session`, { summary: "A live browser session started" }));
706
+ }
707
+ const use = useRow(conv, `${base}:${index}`, id, name, args, { round });
708
+ const before = early.get(`${conv}:${id}`);
709
+ const opened = { conv, name, args, round, use, done: before !== undefined };
710
+ calls.set(`${conv}:${id}`, opened);
711
+ if (BROWSER_STEPS.has(name))
712
+ browserCalls.set(conv, opened);
713
+ add(use);
714
+ // Its result came first: it is this call's, so it reads with the call's label and sits right after it.
715
+ if (before) {
716
+ early.delete(`${conv}:${id}`);
717
+ const named = nameFor(name, args, before.view, before.shown);
718
+ use.summary = clean(named, caps.summary);
719
+ const fresh = resultRow(conv, before.row.id, { name, callId: id, round }, named, before.view, before.shown);
720
+ Object.assign(before.row, { summary: fresh.summary, tool_name: fresh.tool_name, tool_status: fresh.tool_status, seq: (use.seq ?? 0) + 0.5, ...(round === undefined ? {} : { round }) });
721
+ rows.splice(rows.indexOf(before.row), 1);
722
+ rows.splice(rows.indexOf(use) + 1, 0, before.row);
723
+ touch(before.row);
724
+ }
725
+ });
726
+ }
727
+ }
728
+ else if (entry.kind === "pi.tool-result" && message) {
729
+ const id = str(message.toolCallId) ?? "";
730
+ const call = calls.get(`${conv}:${id}`);
731
+ const name = call?.name ?? str(message.toolName) ?? "tool";
732
+ const view = viewOf(message);
733
+ const shown = shownOf(view);
734
+ // A call that failed ended nothing: the agent goes on after it, so a message then is still a steer.
735
+ ended.set(conv, (previous.get(conv) !== "pi.tool-result" || ended.get(conv) === true) && endsTurn(name) && !view.isError);
736
+ // One an abort cut did end the turn. A round's results come in as its calls end, so one that ended before the abort
737
+ // comes first and never clears it.
738
+ if (abortedCall(entry))
739
+ cutTurns.add(conv);
740
+ else
741
+ cutTurns.delete(conv);
742
+ const args = call?.args ?? {};
743
+ const named = nameFor(name, args, view, shown);
744
+ if (call) {
745
+ call.done = true;
746
+ call.use.summary = clean(named, caps.summary);
747
+ touch(call.use);
748
+ }
749
+ const row = resultRow(conv, base, { name, callId: id || null, round: call?.round }, named, view, shown);
750
+ if (!call && id)
751
+ early.set(`${conv}:${id}`, { row, view, shown });
752
+ add(row);
753
+ if (!view.isError) {
754
+ const answer = str(args.answer);
755
+ if (name === "submit" && answer !== undefined)
756
+ add(make("final_answer", conv, `${base}:answer`, { summary: firstLine(answer), text: answer }));
757
+ if (name === "request_sign_in") {
758
+ const reason = str(args.reason);
759
+ add(make("waiting", conv, `${base}:waiting`, { summary: `Waiting for you: ${reason ? firstLine(reason) : "sign in on the live browser"}` }));
760
+ }
761
+ if (name === "browser_release") {
762
+ browsers.delete(conv);
763
+ add(make("phase", conv, `${base}:phase`, { summary: "Released the browser session" }));
764
+ }
765
+ savedPaths(name, args, view).map((file) => (options.path ? options.path(file) : file)).forEach((file, index) => add(make("phase", conv, `${base}:saved:${index}`, { summary: `Saved ${file}`, path: file })));
766
+ const child = obj(message.details)?.conversationId;
767
+ if (typeof child === "number") {
768
+ for (const row of adopt(conv, child, id, args, named))
769
+ touch(row);
770
+ add(make("subagent_completed", conv, `${conv}:done:${id}`, { summary: `Subagent done: ${scrubUrls(firstLine(shown.text))}`, tool_use_id: id }));
771
+ }
772
+ }
773
+ }
774
+ else if (entry.kind === "pi.system") {
775
+ if (systems.has(conv))
776
+ add(make("phase", conv, base, { summary: "Tools changed" }));
777
+ systems.add(conv);
778
+ }
779
+ else if (entry.kind === "pi.reset") {
780
+ add(make("phase", conv, base, { summary: "Context reset", text: textOf(message) || null }));
781
+ }
782
+ else if (entry.kind === "pi.compaction") {
783
+ add(make("phase", conv, base, { summary: "Summarized older context", text: textOf(message) || null }));
784
+ }
785
+ else if (entry.kind === HOST_PHASE) {
786
+ // A step the host stamped (`at`, ms) shows at that time: written as it happened, it can sit after a message whose time
787
+ // is earlier (a model request's start), and the time of the log before it would not be its own.
788
+ const at = obj(entry.data)?.at;
789
+ if (typeof at === "number" && Math.abs(at) <= 8.64e15)
790
+ stamp = at;
791
+ const summary = str(obj(entry.data)?.summary);
792
+ if (summary)
793
+ add(make("phase", conv, base, { summary: firstLine(summary) }));
794
+ }
795
+ else if (entry.kind === RUN_RESUMED) {
796
+ const data = obj(entry.data);
797
+ if (typeof data?.at === "number" && Math.abs(data.at) <= 8.64e15)
798
+ stamp = data.at;
799
+ // `runner_lost`: another runner (or the same one, its claim lost) took the run over once its runner's lease ran out.
800
+ const lostRunner = data?.after === "runner_lost" ? firstLine(str(data?.runner) ?? "").slice(0, 100) : undefined;
801
+ const summary = data?.after === "crash" ? "Resumed after a crash" : lostRunner !== undefined ? `Resumed after its runner${lostRunner ? ` (${lostRunner})` : ""} was lost` : "Resumed after the server stopped";
802
+ add(make("phase", conv, base, { summary }));
803
+ }
804
+ else if (entry.kind === "agent.handover") {
805
+ const data = obj(entry.data);
806
+ const [state, tag] = [str(data?.state), str(data?.session)];
807
+ // The model's words (what it asks the person to do), so redacted as its call's arguments are: a held value it echoes
808
+ // never shows.
809
+ const reason = str(data?.reason) && redactText(str(data?.reason));
810
+ const session = tag && TAG.test(tag) ? tag : undefined;
811
+ // An answer that names its ask (`id`: the person's hand-back, a cancel, an expiry) is the hand-over's record: the
812
+ // run's process writes that action's own row, so this entry shows none. A done naming its session alone is a sign-in.
813
+ const answersAsk = state !== "waiting" && typeof data?.id === "string";
814
+ if (state === "waiting")
815
+ add(make("waiting", conv, base, { summary: `Waiting for you: ${reason ? firstLine(reason) : "sign in on the live browser"}`, session }));
816
+ else if (state === "done" && !answersAsk)
817
+ add(make("user_message", conv, base, { summary: "You signed in", session }));
818
+ else if (state === "declined" && !answersAsk)
819
+ add(make("user_message", conv, base, { summary: "You declined to sign in", session }));
820
+ }
821
+ else if (origin) {
822
+ // A message the server wrote (a raised cap's follow-up, an approval's resume): the model reads it as it reads any,
823
+ // and the row says it is the server's. Its whole text is redacted as a person's is (a resume's later lines hold the
824
+ // call's result, where a held key can be), then its first line is taken, scrubbed and cut as a phase's. No `path`:
825
+ // a phase row with one folds into the tool row before it.
826
+ const text = redactText(textOf(message));
827
+ // A person's message that declined the call: their words are the message the turn took, a row of theirs under a
828
+ // person's rules, with the entry's own id; the server's resume beside it is the server's (`origin: "server"`) but
829
+ // not a message (an id of its own, BESIDE_SUFFIX, which isMessageRow passes over). Any other: the server's row is
830
+ // that message, with the entry's id and `origin: "server"`. A trigger's message: "<its source's label> <its id>: …"
831
+ // (TRIGGER_LABELS; serve names the trigger as it is now), `origin: "trigger"`, never the person's.
832
+ if (origin.kind === "trigger")
833
+ add(make("phase", conv, base, { summary: `${TRIGGER_LABELS[origin.source]} ${origin.trigger_id}: ${firstLine(text)}`, text, origin: "trigger", trigger: { id: origin.trigger_id, source: origin.source, owner: origin.owner } }));
834
+ else if (origin.reason === "approval_declined") {
835
+ const said = redactText(origin.said.trim());
836
+ add(make("phase", conv, `${base}${BESIDE_SUFFIX}`, { summary: `AgentRun: ${firstLine(text)}`, text, origin: "server" }));
837
+ add(make("user_message", conv, base, { summary: `You: ${firstLine(said)}`, text: said }));
838
+ }
839
+ else
840
+ add(make("phase", conv, base, { summary: `AgentRun: ${firstLine(text)}`, text, origin: "server" }));
841
+ provisional.delete(conv);
842
+ }
843
+ else if (message?.role === "user" && (entry.kind === "pi.user" || !entry.kind.startsWith("pi."))) {
844
+ const author = str(obj(entry.data)?.author);
845
+ const steer = previous.get(conv) === "pi.tool-result" && !ended.get(conv) && !cutTurns.has(conv);
846
+ // A person can paste a held key: their row shows it redacted, as the host's `redact` makes it. The entry, which the
847
+ // model reads, keeps what they typed.
848
+ const text = redactText(textOf(message));
849
+ add(make("user_message", conv, base, { summary: `${author ?? "You"}${steer ? " (steer)" : ""}: ${firstLine(text)}`, text }));
850
+ provisional.delete(conv);
851
+ }
852
+ if (["pi.user", "pi.assistant", "pi.tool-result"].includes(entry.kind))
853
+ previous.set(conv, entry.kind);
854
+ // A model request an abort cut after the round: its end mark is written only for an aborted request (not a withdrawn
855
+ // one, nor a compaction's). The turn it would have gone on with is over.
856
+ else if (entry.kind === REQUEST_ENDED && !unsent(entry) && !isCompaction(entry))
857
+ cutTurns.add(conv);
858
+ else if (entry.kind === TURN_END)
859
+ ended.set(conv, true);
860
+ return out;
861
+ }
862
+ /** A nested call: seen live only, since pi drops its result when the caller settles. */
863
+ function nested(conv, id, parent, name, raw) {
864
+ const args = argsOf(raw);
865
+ const round = calls.get(`${conv}:${parent}`)?.round;
866
+ const use = useRow(conv, `${conv}:n:${id}`, id, name, args, { round, parent_tool_use_id: parent });
867
+ calls.set(`${conv}:${id}`, { conv, name, args, round, use, done: false });
868
+ rows.push(use);
869
+ return use;
870
+ }
871
+ function nestedEnd(conv, id, parent, result) {
872
+ const call = calls.get(`${conv}:${id}`);
873
+ if (!call)
874
+ return [];
875
+ const output = result.structuredOutput;
876
+ const diagnostic = Array.isArray(result.diagnostics) ? str(obj(result.diagnostics[0])?.message) : undefined;
877
+ const text = typeof output === "string" ? output : output !== undefined ? JSON.stringify(output) : (diagnostic ?? "");
878
+ const failed = result.isError === true;
879
+ const view = { text, details: result.details, isError: failed };
880
+ const shown = shownOf(view);
881
+ const named = nameFor(call.name, call.args, view, shown);
882
+ call.done = true;
883
+ call.use.summary = clean(named, caps.summary);
884
+ const row = resultRow(conv, `${conv}:n:${id}:result`, { name: call.name, callId: id, round: call.round }, named, view, shown, parent);
885
+ rows.push(row);
886
+ return [call.use, row];
887
+ }
888
+ /** A call with no result that will never get one. Its row takes the call's place, right after it, whenever the
889
+ * interruption is found: at this turn's end, or at a later process's (a call a stop or a crash cut off, which the next
890
+ * process resumes past) or a settled read. What came after the call, such as that process's answer, stays after it. */
891
+ function interrupt(call, id) {
892
+ call.done = true;
893
+ const row = make("tool_result", call.conv, `${call.conv}:interrupted:${id}`, {
894
+ summary: `${label(call.name, call.args)} interrupted`, tool_name: call.name, tool_use_id: id, tool_status: "failed", round: call.round,
895
+ parent_tool_use_id: call.use.parent_tool_use_id, seq: call.use.seq,
896
+ });
897
+ const at = rows.indexOf(call.use);
898
+ rows.splice(at < 0 ? rows.length : at + 1, 0, row);
899
+ return row;
900
+ }
901
+ function open(conv) {
902
+ return [...calls].filter(([, call]) => (conv === undefined || call.conv === conv) && !call.done).map(([key, call]) => [key.slice(key.indexOf(":") + 1), call]);
903
+ }
904
+ /** The usage row. `nothingInFlight`: read as a settled run is, a request marked with no answer being cut, for a host that
905
+ * knows its turn is over while its process lives on (a stopped turn). */
906
+ function usage(nothingInFlight = false) {
907
+ const counted = meter.usage(options.settled === true || nothingInFlight);
908
+ if (!counted || root === undefined)
909
+ return undefined;
910
+ const { usd, requests, charges, so_far_usd, unpriced, not_metered } = counted;
911
+ const paid = `${charges ? ` and ${charges} paid tool call${charges === 1 ? "" : "s"}` : ""}${not_metered ? `; ${not_metered} tool call${not_metered === 1 ? "" : "s"} not metered` : ""}`;
912
+ const spent = usd !== null ? dollars(usd) : so_far_usd !== undefined && unpriced !== undefined ? `${dollars(so_far_usd)} known, ${unpriced} not priced,` : "unknown";
913
+ return make("usage", root, `${root}:usage`, {
914
+ // A run whose only request its cap refused sent none, and says so; otherwise what is known so far (costsofar/1).
915
+ summary: requests === 0 && !charges ? "no model request sent" : `${costLabel(options.ended === true)}: ${spent} over ${requests} model request${requests === 1 ? "" : "s"}${paid}`,
916
+ // The contract's TimelineUsage and its costsofar/1 fields, while the cost is unknown: no other of the meter's reaches it.
917
+ usage: { usd, requests, ...(so_far_usd !== undefined && unpriced !== undefined ? { so_far_usd, unpriced } : {}), ...(not_metered ? { not_metered } : {}) },
918
+ });
919
+ }
920
+ return {
921
+ push, nested, nestedEnd, interrupt, open, usage,
922
+ call: (conv, id) => calls.get(`${conv}:${id}`),
923
+ adoptLive: (conv, id, child) => {
924
+ const call = calls.get(`${conv}:${id}`);
925
+ return call ? adopt(conv, child, id, call.args, call.use.summary ?? "") : [];
926
+ },
927
+ live: (kind, id, fields) => make(kind, current, id, fields),
928
+ rows: () => rows,
929
+ conv: () => current,
930
+ };
931
+ }
932
+ /** The usage row's label: a run that has ended says its cost, one still going (or paused) what it has cost so far. */
933
+ export const COST_SO_FAR = "Cost so far";
934
+ export const COST_ENDED = "Cost";
935
+ export const costLabel = (ended) => (ended ? COST_ENDED : COST_SO_FAR);
936
+ /** `row` as an ended run's: a usage row made while it ran ("Cost so far: …") says its cost ("Cost: …"); any other row as
937
+ * it is. For a host that keeps rows read before the run ended. */
938
+ export function endedUsage(row) {
939
+ const head = `${COST_SO_FAR}: `;
940
+ return row.kind === "usage" && typeof row.summary === "string" && row.summary.startsWith(head) ? { ...row, summary: `${COST_ENDED}: ${row.summary.slice(head.length)}` } : row;
941
+ }
942
+ /** Rows of a stored conversation, in log order. Pure: the same entries give the same rows. */
943
+ export function timelineOf(entries, options = {}) {
944
+ const projector = createProjector(options);
945
+ for (const entry of entries)
946
+ projector.push(entry);
947
+ if (options.settled)
948
+ for (const [id, call] of projector.open())
949
+ projector.interrupt(call, id);
950
+ const usage = projector.usage();
951
+ return usage ? [...projector.rows(), usage] : [...projector.rows()];
952
+ }
953
+ /** The id of the call a run's turn ended waiting on a person by, or undefined: its last meaningful row is a successful tool
954
+ * result for a tool that ends its turn (registerTurnEnding — ask_person is serve's). This is the one rule the view reads a
955
+ * run `input_required` on a question by (the waiting row withAsks appends sits right after this same result), so the
956
+ * runner's loop parks on exactly the turn ends the view would call waiting, and the two can never disagree; the id is the
957
+ * call the park entry names. Truthy when it waits, undefined when it does not. */
958
+ export function endedOnTurnEndingTool(entries) {
959
+ const last = timelineOf(entries, { settled: true }).findLast((row) => row.kind !== "usage" && row.kind !== "phase");
960
+ if (last?.kind !== "tool_result" || last.tool_name === null || last.tool_status !== "success" || !endsTurn(last.tool_name))
961
+ return undefined;
962
+ return last.tool_use_id ?? undefined;
963
+ }
964
+ /** What a run that ended used, from the entries of every conversation of its store, in log order (`SELECT record FROM
965
+ * entries ORDER BY id`): its model requests and their tokens, counted as its usage row counts them (a cut request's
966
+ * tokens are unknown), and its tool calls. One parameter, so `.map(runMetricsOf)` is safe. Pure, like timelineOf. */
967
+ export function runMetricsOf(records) {
968
+ return runMetricsWithDecisions(records, []);
969
+ }
970
+ /** runMetricsOf, with a workflow run's decision receipts beside its entries: each a request, its `usage`
971
+ * (`input_tokens`, `output_tokens`) in the token sums, and one with none, or cancelled, unmetered. */
972
+ export function runMetricsWithDecisions(records, decisions) {
973
+ const meter = createMeter();
974
+ const seen = new Set();
975
+ // Each call by `conversation:id`, its tool's name as kept and as called, and whether a result closed it, as the timeline
976
+ // pairs them.
977
+ const calls = new Map();
978
+ // Results stored before their call, by `conversation:id`: each counts once its call comes, under its name and rule.
979
+ const early = new Map();
980
+ const tools = new Map();
981
+ // Each tool's place by its first call, or its first result with no call: a tie for the last kept place goes by it.
982
+ const order = new Map();
983
+ // Each record's place: a tool's place is the record that first named it, though it counts later.
984
+ let at = 0;
985
+ const see = (name, place = at) => void (order.has(name) || order.set(name, [place, order.size]));
986
+ const tally = (name, failed) => {
987
+ see(name);
988
+ const tool = tools.get(name) ?? { calls: 0, errors: 0 };
989
+ tool.calls += 1;
990
+ if (failed)
991
+ tool.errors += 1;
992
+ tools.set(name, tool);
993
+ };
994
+ for (const entry of records) {
995
+ at += 1;
996
+ const conv = entry.conversationId ?? 0;
997
+ if (entry.id !== undefined) {
998
+ if (seen.has(`${conv}:${entry.id}`))
999
+ continue;
1000
+ seen.add(`${conv}:${entry.id}`);
1001
+ }
1002
+ const message = entry.model?.[0];
1003
+ const metered = meter.push(entry);
1004
+ if ((metered === "answer" || metered === "continued") && message && message.stopReason !== "error" && message.stopReason !== "aborted") {
1005
+ for (const block of blocksOf(message)) {
1006
+ const [id, name] = [str(block.id), str(block.name)];
1007
+ if (block.type !== "toolCall" || !id || !name)
1008
+ continue;
1009
+ const key = metricName(name);
1010
+ // Its result came first: it counts now, once, under this call's name and by this call's tool's rule.
1011
+ const before = early.get(`${conv}:${id}`);
1012
+ early.delete(`${conv}:${id}`);
1013
+ calls.set(`${conv}:${id}`, { name: key, called: name, done: before !== undefined });
1014
+ see(key);
1015
+ if (before)
1016
+ tally(key, callFailed(name, before.result));
1017
+ }
1018
+ }
1019
+ else if (entry.kind === "pi.tool-result" && message) {
1020
+ const id = str(message.toolCallId);
1021
+ const call = calls.get(`${conv}:${id ?? ""}`);
1022
+ const named = str(message.toolName);
1023
+ // The text is read only by a tool that tells its outcome (most tell none; a fetch's is its whole page).
1024
+ const result = { get text() { return textOf(message); }, isError: message.isError === true };
1025
+ // A result before its call waits for it, to count under its name and by its rule.
1026
+ if (!call && id) {
1027
+ early.set(`${conv}:${id}`, { named, result, place: at });
1028
+ continue;
1029
+ }
1030
+ if (call)
1031
+ call.done = true;
1032
+ // Failed as the call's row reads it (callFailed): an error, or a result its tool reads as failed (a refused fetch).
1033
+ const called = call?.called ?? named ?? "";
1034
+ tally(call?.name ?? (named ? metricName(named) : METRIC_NAMES.unnamedTool), callFailed(called, result));
1035
+ }
1036
+ }
1037
+ for (const call of calls.values())
1038
+ if (!call.done)
1039
+ tally(call.name, true);
1040
+ // A result whose call never came counts by its own name, as any result without a call does.
1041
+ for (const { named, result, place } of early.values()) {
1042
+ const name = named ? metricName(named) : METRIC_NAMES.unnamedTool;
1043
+ see(name, place);
1044
+ tally(name, callFailed(named ?? "", result));
1045
+ }
1046
+ for (const row of decisions)
1047
+ meter.decide(row);
1048
+ const ordered = new Map([...tools].sort(([a], [b]) => order.get(a)[0] - order.get(b)[0] || order.get(a)[1] - order.get(b)[1]));
1049
+ return { ...meter.settled(), tools: keepBusiest(ordered, (t) => t.calls, (a, b) => ({ calls: a.calls + b.calls, errors: a.errors + b.errors }), METRIC_NAMES.otherTools) };
1050
+ }
1051
+ const roleOf = (entry) => {
1052
+ const model = obj(entry)?.model;
1053
+ return Array.isArray(model) ? obj(model[0])?.role : undefined;
1054
+ };
1055
+ const modelName = (agent) => {
1056
+ const model = obj(obj(agent)?.model);
1057
+ return model && str(model.modelId) ? `${str(model.provider) ?? "model"}/${str(model.modelId)}` : undefined;
1058
+ };
1059
+ /** Live rows from `watchEvents` batches. Committed entries go through the same projector `timelineOf` uses. */
1060
+ export function timelineReducer(options = {}) {
1061
+ const redactedWhy = redactOf(options);
1062
+ // Ids of live rows: events made them, and they go when they end (timelineReducer's isLive).
1063
+ const liveIds = new Set();
1064
+ const now = options.now ?? Date.now;
1065
+ const thinkingCap = options.caps?.thinking ?? CAPS.thinking;
1066
+ let projector = createProjector(options);
1067
+ const store = new Map();
1068
+ const streams = { thinking: new Map(), text_block: new Map() };
1069
+ let model;
1070
+ function apply(events) {
1071
+ const changed = new Map();
1072
+ const dropped = new Set();
1073
+ const put = (row) => { store.set(row.id, row); changed.set(row.id, row); dropped.delete(row.id); };
1074
+ const del = (id) => { if (store.delete(id)) {
1075
+ changed.delete(id);
1076
+ dropped.add(id);
1077
+ } };
1078
+ const live = (kind, id, summary, fields = {}) => {
1079
+ liveIds.add(id);
1080
+ const old = store.get(id);
1081
+ if (summary === undefined)
1082
+ return del(id);
1083
+ if (old && old.summary === summary && old.text === (fields.text ?? null))
1084
+ return;
1085
+ put(projector.live(kind, id, { summary, ...fields, seq: old?.seq }));
1086
+ };
1087
+ let committed = false;
1088
+ const entry = (value) => {
1089
+ const e = obj(value);
1090
+ if (!e || typeof e.kind !== "string")
1091
+ return;
1092
+ for (const row of projector.push(e))
1093
+ put(row);
1094
+ committed = true;
1095
+ };
1096
+ const conv = () => projector.conv();
1097
+ const showStreams = () => {
1098
+ for (const kind of ["thinking", "text_block"]) {
1099
+ // All that has streamed so far, as the host shows a streaming block (redactLive: redacted whole, a tail held back),
1100
+ // before a summary or a cut is taken. With only `redact`: redacted whole, then its trailing word held back until
1101
+ // whitespace follows it or the block ends, since it may be the head of a key whose tail has not streamed yet.
1102
+ const joined = [...streams[kind].values()].join("");
1103
+ const raw = joined.trim();
1104
+ const fallback = () => {
1105
+ const red = redactedWhy(raw);
1106
+ return options.redact && /\S$/.test(joined) ? red.replace(/\S+$/, "").trimEnd() : red;
1107
+ };
1108
+ const shown = options.redactLive ? options.redactLive(raw) : fallback();
1109
+ // The agent's text streams as it will settle, its URLs whole; its thinking is scrubbed, as when it settles.
1110
+ const text = kind === "thinking" ? scrubUrls(shown) : shown;
1111
+ const summary = kind === "thinking" ? `Thinking: ${cut(firstSentence(text), thinkingCap)}` : firstLine(text);
1112
+ live(kind, `${conv()}:live:${kind}`, text ? summary : undefined, { text });
1113
+ }
1114
+ };
1115
+ const endStreams = () => {
1116
+ streams.thinking.clear();
1117
+ streams.text_block.clear();
1118
+ showStreams();
1119
+ wait("poll", undefined);
1120
+ };
1121
+ const readMessage = (message) => {
1122
+ streams.thinking.clear();
1123
+ streams.text_block.clear();
1124
+ blocksOf(message).forEach((block, index) => {
1125
+ if (block.type === "thinking")
1126
+ streams.thinking.set(index, str(block.thinking) ?? "");
1127
+ else if (block.type === "text")
1128
+ streams.text_block.set(index, str(block.text) ?? "");
1129
+ });
1130
+ };
1131
+ const change = (c) => {
1132
+ const index = typeof c.contentIndex === "number" ? c.contentIndex : 0;
1133
+ const block = obj(c.block);
1134
+ const append = (map) => map.set(index, (map.get(index) ?? "") + (str(c.delta) ?? ""));
1135
+ if (c.type === "text_delta")
1136
+ append(streams.text_block);
1137
+ else if (c.type === "thinking_delta")
1138
+ append(streams.thinking);
1139
+ else if (c.type === "text_start" || (c.type === "block" && block?.type === "text"))
1140
+ streams.text_block.set(index, str(block?.text) ?? "");
1141
+ else if (c.type === "thinking_start" || (c.type === "block" && block?.type === "thinking"))
1142
+ streams.thinking.set(index, str(block?.thinking) ?? "");
1143
+ else if (c.type === "message")
1144
+ readMessage(obj(c.message));
1145
+ };
1146
+ const wait = (slot, summary) => live("waiting", `${conv()}:waiting:${slot}`, summary);
1147
+ const seconds = (at) => Math.max(0, Math.round(((typeof at === "number" ? at : now()) - now()) / 1000));
1148
+ const nestedStart = (id, parent, name, args) => {
1149
+ if (!projector.call(conv(), id))
1150
+ put(projector.nested(conv(), id, parent, name, args));
1151
+ };
1152
+ for (const event of events) {
1153
+ switch (event.type) {
1154
+ case "snapshot": {
1155
+ for (const id of store.keys())
1156
+ dropped.add(id);
1157
+ store.clear();
1158
+ changed.clear();
1159
+ projector = createProjector(options);
1160
+ streams.thinking.clear();
1161
+ streams.text_block.clear();
1162
+ model = modelName(event.agent);
1163
+ for (const value of Array.isArray(event.entries) ? event.entries : [])
1164
+ entry(value);
1165
+ const generation = obj(event.generation);
1166
+ const retry = obj(generation?.retry);
1167
+ if (generation?.message) {
1168
+ readMessage(obj(generation.message));
1169
+ showStreams();
1170
+ }
1171
+ if (retry)
1172
+ wait("retry", `Retrying in ${seconds(retry.at)} s: ${firstLine(str(retry.error) ?? "")}`);
1173
+ if (obj(generation?.deferred))
1174
+ wait("poll", "Waiting for the model provider");
1175
+ if (Array.isArray(event.inbox) && event.inbox.length)
1176
+ wait("queue", `${event.inbox.length} message${event.inbox.length === 1 ? "" : "s"} queued`);
1177
+ for (const slot of Array.isArray(event.nestedTools) ? event.nestedTools : []) {
1178
+ const s = obj(slot);
1179
+ const [callId, parentCallId, name] = [str(s?.callId), str(s?.parentCallId), str(s?.name)];
1180
+ if (s && callId && parentCallId && name)
1181
+ nestedStart(callId, parentCallId, name, obj(s.arguments) ?? {});
1182
+ }
1183
+ break;
1184
+ }
1185
+ case "message_start":
1186
+ if (obj(event.message)?.role === "assistant")
1187
+ endStreams();
1188
+ break;
1189
+ case "message_update":
1190
+ for (const c of Array.isArray(event.changes) ? event.changes : [])
1191
+ change(obj(c) ?? {});
1192
+ showStreams();
1193
+ break;
1194
+ case "message_end": {
1195
+ entry(event.entry);
1196
+ if (roleOf(event.entry) === "assistant")
1197
+ endStreams();
1198
+ break;
1199
+ }
1200
+ case "entry_appended":
1201
+ entry(event.entry);
1202
+ break;
1203
+ case "tool_execution_start": {
1204
+ const [parent, callId] = [str(event.parentToolCallId), str(event.toolCallId)];
1205
+ if (parent && callId)
1206
+ nestedStart(callId, parent, str(event.toolName) ?? "tool", obj(event.args) ?? {});
1207
+ break;
1208
+ }
1209
+ case "tool_execution_end": {
1210
+ const id = str(event.toolCallId) ?? "";
1211
+ if (event.entry)
1212
+ entry(event.entry);
1213
+ else if (obj(event.result))
1214
+ for (const row of projector.nestedEnd(conv(), id, str(event.parentToolCallId), obj(event.result)))
1215
+ put(row);
1216
+ else {
1217
+ const call = projector.call(conv(), id);
1218
+ if (call && !call.done)
1219
+ put(projector.interrupt(call, id));
1220
+ }
1221
+ break;
1222
+ }
1223
+ case "run_start":
1224
+ live("phase", `${conv()}:run:start`, "Run started");
1225
+ break;
1226
+ case "run_end":
1227
+ for (const [id, call] of projector.open(conv()))
1228
+ put(projector.interrupt(call, id));
1229
+ wait("poll", undefined);
1230
+ wait("retry", undefined);
1231
+ live("phase", `${conv()}:run:end`, "Run finished");
1232
+ break;
1233
+ case "inbox_update": {
1234
+ const n = Array.isArray(event.items) ? event.items.length : 0;
1235
+ wait("queue", n ? `${n} message${n === 1 ? "" : "s"} queued` : undefined);
1236
+ break;
1237
+ }
1238
+ case "auto_retry_start":
1239
+ wait("poll", undefined);
1240
+ wait("retry", `Retrying in ${seconds(event.at)} s (attempt ${String(event.attempt)}): ${firstLine(str(event.errorMessage) ?? "")}`);
1241
+ break;
1242
+ case "auto_retry_end":
1243
+ wait("retry", undefined);
1244
+ break;
1245
+ case "deferred_poll":
1246
+ wait("poll", `Waiting for the model provider (next check in ${seconds(event.pollAt)} s)`);
1247
+ break;
1248
+ case "agent_changed": {
1249
+ const next = modelName(event.agent);
1250
+ if (next && model && next !== model)
1251
+ live("phase", `${conv()}:model:${next}`, `Model changed to ${next}`);
1252
+ model = next ?? model;
1253
+ break;
1254
+ }
1255
+ case "task_failed":
1256
+ wait("poll", undefined);
1257
+ {
1258
+ const why = str(event.message) === undefined ? undefined : redactedWhy(str(event.message));
1259
+ live("error", `${conv()}:task:${String(event.taskId)}`, `Task failed: ${firstLine(why ?? "")}`, { text: why ?? null });
1260
+ }
1261
+ break;
1262
+ case "compaction_start":
1263
+ live("phase", `${conv()}:compaction:${String(event.taskId)}`, "Summarizing older context");
1264
+ break;
1265
+ case "compaction_end": {
1266
+ del(`${conv()}:compaction:${String(event.taskId)}`);
1267
+ const failed = str(event.error);
1268
+ if (failed) {
1269
+ const why = redactedWhy(failed);
1270
+ live("error", `${conv()}:compaction:${String(event.taskId)}:error`, `Compaction failed: ${firstLine(why)}`, { text: why });
1271
+ }
1272
+ break;
1273
+ }
1274
+ case "tool_execution_update": {
1275
+ const child = obj(event.details)?.conversationId;
1276
+ const id = str(event.toolCallId);
1277
+ if (typeof child === "number" && id)
1278
+ for (const row of projector.adoptLive(conv(), id, child))
1279
+ put(row);
1280
+ break;
1281
+ }
1282
+ default:
1283
+ break;
1284
+ }
1285
+ }
1286
+ const usage = committed ? projector.usage() : undefined;
1287
+ if (usage)
1288
+ put(usage);
1289
+ return { rows: [...changed.values()].sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0)), drop: [...dropped] };
1290
+ }
1291
+ return {
1292
+ apply,
1293
+ /** Every row now, in log order. */
1294
+ rows: () => [...store.values()].sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0)),
1295
+ /** The usage row read with nothing in flight, put in place of the live one: for a host whose turn was stopped and is
1296
+ * over, so a request it cut counts as a charge with no price, as a settled read counts it. Undefined with no row. */
1297
+ idle: () => {
1298
+ const usage = projector.usage(true);
1299
+ if (usage)
1300
+ store.set(usage.id, usage);
1301
+ return usage;
1302
+ },
1303
+ /** Whether `id` is a live row (one the events made: a stream, a wait, a phase), not one a committed entry made.
1304
+ * A live row ends when it is gone; a committed one was shown and stays, though a snapshot of a compacted
1305
+ * conversation no longer holds it. */
1306
+ isLive: (id) => liveIds.has(id),
1307
+ };
1308
+ }