observability-toolkit-hooks 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (305) hide show
  1. package/CONFIG.md +144 -0
  2. package/README.md +201 -2
  3. package/dist/handlers/compact.js +38 -0
  4. package/dist/handlers/mcp-status.js +66 -0
  5. package/dist/handlers/notification.js +45 -0
  6. package/dist/handlers/post-tool-agent.js +157 -0
  7. package/dist/handlers/post-tool-changelog-sync.js +148 -0
  8. package/dist/handlers/post-tool-code-structure.js +116 -0
  9. package/dist/handlers/post-tool-edit-ledger.js +15 -0
  10. package/dist/handlers/post-tool-failure.js +83 -0
  11. package/dist/handlers/post-tool-git.js +79 -0
  12. package/dist/handlers/post-tool-mcp.js +105 -0
  13. package/dist/handlers/post-tool-outcome.js +48 -0
  14. package/dist/handlers/post-tool-task-state.js +74 -0
  15. package/dist/handlers/post-tool.js +132 -0
  16. package/dist/handlers/pre-tool-agent.js +192 -0
  17. package/dist/handlers/pre-tool.js +218 -0
  18. package/dist/handlers/session-end.js +39 -0
  19. package/dist/handlers/session-start.js +262 -0
  20. package/dist/handlers/stop-error-reminder.js +195 -0
  21. package/dist/handlers/stop-quality-evaluation.js +58 -0
  22. package/dist/handlers/stop-session-summary.js +62 -0
  23. package/dist/handlers/stop-token-metrics.js +83 -0
  24. package/dist/handlers/stop.js +25 -0
  25. package/dist/handlers/subagent.js +105 -0
  26. package/dist/handlers/tool-event-router.js +39 -0
  27. package/dist/handlers/user-prompt.js +218 -0
  28. package/dist/hook-runner.js +10 -0
  29. package/dist/hook-runner.js.map +7 -0
  30. package/dist/lib/agent/agent-context.js +123 -0
  31. package/dist/lib/agent/agent-evaluations.js +155 -0
  32. package/dist/lib/agent/agent-file-budget.js +65 -0
  33. package/dist/lib/agent/agent-sources.js +165 -0
  34. package/dist/lib/agent/synth-spans.js +51 -0
  35. package/dist/lib/core/bounded-label.js +6 -0
  36. package/dist/lib/core/category-rules.js +11 -0
  37. package/dist/lib/core/child-result.js +19 -0
  38. package/dist/lib/core/config-dir-recovery.js +22 -0
  39. package/dist/lib/core/constants.js +171 -0
  40. package/dist/lib/core/detached-runner.js +55 -0
  41. package/dist/lib/core/file-utils.js +353 -0
  42. package/dist/lib/core/format-utils.js +51 -0
  43. package/dist/lib/core/http-utils.js +74 -0
  44. package/dist/lib/core/http1-fetch.js +14 -0
  45. package/dist/lib/core/identity-key-resolver.js +149 -0
  46. package/dist/lib/core/jsonl-tail.js +207 -0
  47. package/dist/lib/core/load-envrc.js +72 -0
  48. package/dist/lib/core/parsers.js +43 -0
  49. package/dist/lib/core/regex.js +27 -0
  50. package/dist/lib/core/settings-env.js +31 -0
  51. package/dist/lib/core/shell-command.js +122 -0
  52. package/dist/lib/core/units.js +97 -0
  53. package/dist/lib/git/git-cache.js +158 -0
  54. package/dist/lib/git/git-commit.js +189 -0
  55. package/dist/lib/git/git-exec.js +30 -0
  56. package/dist/lib/mcp/mcp-completeness.js +40 -0
  57. package/dist/lib/mcp/mcp-config.js +118 -0
  58. package/dist/lib/mcp/mcp-failure-latch.js +22 -0
  59. package/dist/lib/mcp/mcp-identity-launcher.js +43 -0
  60. package/dist/lib/otel/attributes.js +322 -0
  61. package/dist/lib/otel/evaluation-attrs.js +51 -0
  62. package/dist/lib/otel/file-exporters.js +169 -0
  63. package/dist/lib/otel/host-resource.js +61 -0
  64. package/dist/lib/otel/otel-headers-helper.js +26 -0
  65. package/dist/lib/otel/otel-monitor.js +181 -0
  66. package/dist/lib/otel/otel.js +235 -0
  67. package/dist/lib/otel/otlp-headers.js +101 -0
  68. package/dist/lib/otel/otlp-post.js +122 -0
  69. package/dist/lib/otel/otlp-serialize.js +142 -0
  70. package/dist/lib/otel/otlp-signal.js +2 -0
  71. package/dist/lib/otel/remote-spans.js +142 -0
  72. package/dist/lib/otel/service-identity.js +10 -0
  73. package/dist/lib/otel/telemetry-alerts.js +43 -0
  74. package/dist/lib/otel/token-metrics.js +122 -0
  75. package/dist/lib/otel/trace-context.js +81 -0
  76. package/dist/lib/quality/judge-meta-eval.js +70 -0
  77. package/dist/lib/quality/judge-prompts.js +104 -0
  78. package/dist/lib/quality/judge-providers.js +193 -0
  79. package/dist/lib/quality/judge-transport.js +93 -0
  80. package/dist/lib/quality/llm-judge.js +170 -0
  81. package/dist/lib/quality/quality-budget.js +99 -0
  82. package/dist/lib/quality/quality-degradation.js +156 -0
  83. package/dist/lib/quality/quality-eval-handoff.js +74 -0
  84. package/dist/lib/quality/quality-evaluator.js +178 -0
  85. package/dist/lib/quality/quality-sampler.js +43 -0
  86. package/dist/lib/quality/quality-signals.js +150 -0
  87. package/dist/lib/runtime/categorizers.js +101 -0
  88. package/dist/lib/runtime/hook-input.js +16 -0
  89. package/dist/lib/runtime/hook-output.js +50 -0
  90. package/dist/lib/runtime/output-analyzer.js +160 -0
  91. package/dist/lib/runtime/run-handlers.js +32 -0
  92. package/dist/lib/runtime/tool-input.js +111 -0
  93. package/dist/lib/runtime/tool-output.js +44 -0
  94. package/dist/lib/runtime/unknown-tool.js +32 -0
  95. package/dist/lib/session/edit-ledger.js +29 -0
  96. package/dist/lib/session/forked-skill.js +39 -0
  97. package/dist/lib/session/handoffs.js +77 -0
  98. package/dist/lib/session/session-state.js +169 -0
  99. package/dist/lib/session/skill-rules.js +196 -0
  100. package/dist/lib/session/task-tracker.js +83 -0
  101. package/dist/lib/shipper/shipper-credentials.js +38 -0
  102. package/dist/lib/shipper/shipper-cursor.js +89 -0
  103. package/dist/lib/shipper/shipper-status.js +174 -0
  104. package/dist/lib/shipper/span-shipper.js +272 -0
  105. package/dist/lib/shipper/telemetry-shipper.js +39 -0
  106. package/dist/lib/transcript/agent-transcript-metrics.js +34 -0
  107. package/dist/lib/transcript/context-breakdown.js +134 -0
  108. package/dist/lib/transcript/context-history.js +69 -0
  109. package/dist/lib/transcript/context-tracker.js +226 -0
  110. package/dist/lib/transcript/message-count.js +49 -0
  111. package/dist/lib/transcript/model-ids.js +36 -0
  112. package/dist/lib/transcript/model-pricing.js +153 -0
  113. package/dist/lib/transcript/token-metrics-checkpoint.js +152 -0
  114. package/dist/lib/transcript/tool-call-durations.js +64 -0
  115. package/dist/lib/transcript/transcript-entry.js +67 -0
  116. package/dist/lib/transcript/transcript-fold.js +130 -0
  117. package/dist/lib/transcript/transcript-layout.js +39 -0
  118. package/dist/lib/transcript/transcript-parser.js +117 -0
  119. package/dist/runner/agent-context-4XTCLMLZ.js +23 -0
  120. package/dist/runner/agent-context-4XTCLMLZ.js.map +7 -0
  121. package/dist/runner/agent-file-budget-Q33ESBBE.js +68 -0
  122. package/dist/runner/agent-file-budget-Q33ESBBE.js.map +7 -0
  123. package/dist/runner/agent-transcript-metrics-W5CZZFMI.js +39 -0
  124. package/dist/runner/agent-transcript-metrics-W5CZZFMI.js.map +7 -0
  125. package/dist/runner/chunk-2NTNAJZE.js +49 -0
  126. package/dist/runner/chunk-2NTNAJZE.js.map +7 -0
  127. package/dist/runner/chunk-4KWBQTTG.js +78 -0
  128. package/dist/runner/chunk-4KWBQTTG.js.map +7 -0
  129. package/dist/runner/chunk-52RY6LQT.js +699 -0
  130. package/dist/runner/chunk-52RY6LQT.js.map +7 -0
  131. package/dist/runner/chunk-7OM5CYES.js +8695 -0
  132. package/dist/runner/chunk-7OM5CYES.js.map +7 -0
  133. package/dist/runner/chunk-7PEOKGYR.js +1568 -0
  134. package/dist/runner/chunk-7PEOKGYR.js.map +7 -0
  135. package/dist/runner/chunk-AGSGKELQ.js +126 -0
  136. package/dist/runner/chunk-AGSGKELQ.js.map +7 -0
  137. package/dist/runner/chunk-AVM7PJFW.js +12 -0
  138. package/dist/runner/chunk-AVM7PJFW.js.map +7 -0
  139. package/dist/runner/chunk-C3WHUMU5.js +178 -0
  140. package/dist/runner/chunk-C3WHUMU5.js.map +7 -0
  141. package/dist/runner/chunk-DGB4NSSD.js +157 -0
  142. package/dist/runner/chunk-DGB4NSSD.js.map +7 -0
  143. package/dist/runner/chunk-DNSTWC26.js +151 -0
  144. package/dist/runner/chunk-DNSTWC26.js.map +7 -0
  145. package/dist/runner/chunk-FDJJ3TYU.js +449 -0
  146. package/dist/runner/chunk-FDJJ3TYU.js.map +7 -0
  147. package/dist/runner/chunk-FGKYDQHZ.js +137 -0
  148. package/dist/runner/chunk-FGKYDQHZ.js.map +7 -0
  149. package/dist/runner/chunk-GG2I4TGI.js +582 -0
  150. package/dist/runner/chunk-GG2I4TGI.js.map +7 -0
  151. package/dist/runner/chunk-GNNKUMRF.js +60 -0
  152. package/dist/runner/chunk-GNNKUMRF.js.map +7 -0
  153. package/dist/runner/chunk-I7TD2QVR.js +118 -0
  154. package/dist/runner/chunk-I7TD2QVR.js.map +7 -0
  155. package/dist/runner/chunk-IJ4SLUBV.js +78 -0
  156. package/dist/runner/chunk-IJ4SLUBV.js.map +7 -0
  157. package/dist/runner/chunk-IY7AP7NA.js +32 -0
  158. package/dist/runner/chunk-IY7AP7NA.js.map +7 -0
  159. package/dist/runner/chunk-J3F3Z3EQ.js +177 -0
  160. package/dist/runner/chunk-J3F3Z3EQ.js.map +7 -0
  161. package/dist/runner/chunk-JLEO5OHU.js +104 -0
  162. package/dist/runner/chunk-JLEO5OHU.js.map +7 -0
  163. package/dist/runner/chunk-JRNNLOPR.js +168 -0
  164. package/dist/runner/chunk-JRNNLOPR.js.map +7 -0
  165. package/dist/runner/chunk-KGSA5JYP.js +82 -0
  166. package/dist/runner/chunk-KGSA5JYP.js.map +7 -0
  167. package/dist/runner/chunk-LBCZAYFR.js +125 -0
  168. package/dist/runner/chunk-LBCZAYFR.js.map +7 -0
  169. package/dist/runner/chunk-LHWRXY2G.js +41 -0
  170. package/dist/runner/chunk-LHWRXY2G.js.map +7 -0
  171. package/dist/runner/chunk-LQ2LGUYJ.js +41 -0
  172. package/dist/runner/chunk-LQ2LGUYJ.js.map +7 -0
  173. package/dist/runner/chunk-LYY6RCIE.js +158 -0
  174. package/dist/runner/chunk-LYY6RCIE.js.map +7 -0
  175. package/dist/runner/chunk-M4R4QIQH.js +41 -0
  176. package/dist/runner/chunk-M4R4QIQH.js.map +7 -0
  177. package/dist/runner/chunk-MC75VXMX.js +207 -0
  178. package/dist/runner/chunk-MC75VXMX.js.map +7 -0
  179. package/dist/runner/chunk-NKZU4RRG.js +104 -0
  180. package/dist/runner/chunk-NKZU4RRG.js.map +7 -0
  181. package/dist/runner/chunk-PJHWHJ3K.js +56 -0
  182. package/dist/runner/chunk-PJHWHJ3K.js.map +7 -0
  183. package/dist/runner/chunk-RIGVYJ2O.js +114 -0
  184. package/dist/runner/chunk-RIGVYJ2O.js.map +7 -0
  185. package/dist/runner/chunk-RWRGC7ZK.js +93 -0
  186. package/dist/runner/chunk-RWRGC7ZK.js.map +7 -0
  187. package/dist/runner/chunk-SRMAJQMV.js +54 -0
  188. package/dist/runner/chunk-SRMAJQMV.js.map +7 -0
  189. package/dist/runner/chunk-TRMFD36J.js +47 -0
  190. package/dist/runner/chunk-TRMFD36J.js.map +7 -0
  191. package/dist/runner/chunk-U4IOZYQ3.js +21 -0
  192. package/dist/runner/chunk-U4IOZYQ3.js.map +7 -0
  193. package/dist/runner/chunk-UEXDE3WP.js +83 -0
  194. package/dist/runner/chunk-UEXDE3WP.js.map +7 -0
  195. package/dist/runner/chunk-UW3GQZSM.js +50 -0
  196. package/dist/runner/chunk-UW3GQZSM.js.map +7 -0
  197. package/dist/runner/chunk-V2GSP6VR.js +46 -0
  198. package/dist/runner/chunk-V2GSP6VR.js.map +7 -0
  199. package/dist/runner/chunk-VOV4Y5VU.js +81 -0
  200. package/dist/runner/chunk-VOV4Y5VU.js.map +7 -0
  201. package/dist/runner/chunk-VT5T6OEI.js +65 -0
  202. package/dist/runner/chunk-VT5T6OEI.js.map +7 -0
  203. package/dist/runner/chunk-VUYVFWIN.js +12 -0
  204. package/dist/runner/chunk-VUYVFWIN.js.map +7 -0
  205. package/dist/runner/chunk-VVGOPPEN.js +36 -0
  206. package/dist/runner/chunk-VVGOPPEN.js.map +7 -0
  207. package/dist/runner/chunk-VXFSLM6P.js +14 -0
  208. package/dist/runner/chunk-VXFSLM6P.js.map +7 -0
  209. package/dist/runner/chunk-W3EK7JUT.js +26125 -0
  210. package/dist/runner/chunk-W3EK7JUT.js.map +7 -0
  211. package/dist/runner/chunk-WJHNCOUF.js +52 -0
  212. package/dist/runner/chunk-WJHNCOUF.js.map +7 -0
  213. package/dist/runner/chunk-WU7ANGCW.js +269 -0
  214. package/dist/runner/chunk-WU7ANGCW.js.map +7 -0
  215. package/dist/runner/chunk-X7XLMSZX.js +44 -0
  216. package/dist/runner/chunk-X7XLMSZX.js.map +7 -0
  217. package/dist/runner/chunk-XSO3B4QN.js +124 -0
  218. package/dist/runner/chunk-XSO3B4QN.js.map +7 -0
  219. package/dist/runner/chunk-YGFN3LN2.js +174 -0
  220. package/dist/runner/chunk-YGFN3LN2.js.map +7 -0
  221. package/dist/runner/chunk-YHYDBLVB.js +33 -0
  222. package/dist/runner/chunk-YHYDBLVB.js.map +7 -0
  223. package/dist/runner/compact-36NP3PKT.js +60 -0
  224. package/dist/runner/compact-36NP3PKT.js.map +7 -0
  225. package/dist/runner/getMachineId-bsd-AGENNHN6.js +42 -0
  226. package/dist/runner/getMachineId-bsd-AGENNHN6.js.map +7 -0
  227. package/dist/runner/getMachineId-bsd-I5WZGCL4.js +33 -0
  228. package/dist/runner/getMachineId-bsd-I5WZGCL4.js.map +7 -0
  229. package/dist/runner/getMachineId-bsd-ZXK225P7.js +33 -0
  230. package/dist/runner/getMachineId-bsd-ZXK225P7.js.map +7 -0
  231. package/dist/runner/getMachineId-darwin-47GDLEXL.js +42 -0
  232. package/dist/runner/getMachineId-darwin-47GDLEXL.js.map +7 -0
  233. package/dist/runner/getMachineId-darwin-5CRLMDD6.js +33 -0
  234. package/dist/runner/getMachineId-darwin-5CRLMDD6.js.map +7 -0
  235. package/dist/runner/getMachineId-darwin-ADG4I32N.js +33 -0
  236. package/dist/runner/getMachineId-darwin-ADG4I32N.js.map +7 -0
  237. package/dist/runner/getMachineId-linux-5KVS3T2M.js +27 -0
  238. package/dist/runner/getMachineId-linux-5KVS3T2M.js.map +7 -0
  239. package/dist/runner/getMachineId-linux-GDFB5GSO.js +34 -0
  240. package/dist/runner/getMachineId-linux-GDFB5GSO.js.map +7 -0
  241. package/dist/runner/getMachineId-linux-NQMWCRO3.js +27 -0
  242. package/dist/runner/getMachineId-linux-NQMWCRO3.js.map +7 -0
  243. package/dist/runner/getMachineId-unsupported-5PFIGMVX.js +18 -0
  244. package/dist/runner/getMachineId-unsupported-5PFIGMVX.js.map +7 -0
  245. package/dist/runner/getMachineId-unsupported-DW27K3ZX.js +18 -0
  246. package/dist/runner/getMachineId-unsupported-DW27K3ZX.js.map +7 -0
  247. package/dist/runner/getMachineId-unsupported-XV3FHTHD.js +25 -0
  248. package/dist/runner/getMachineId-unsupported-XV3FHTHD.js.map +7 -0
  249. package/dist/runner/getMachineId-win-5JVMW3EI.js +44 -0
  250. package/dist/runner/getMachineId-win-5JVMW3EI.js.map +7 -0
  251. package/dist/runner/getMachineId-win-SNESQF7R.js +35 -0
  252. package/dist/runner/getMachineId-win-SNESQF7R.js.map +7 -0
  253. package/dist/runner/getMachineId-win-UJYHSBM2.js +35 -0
  254. package/dist/runner/getMachineId-win-UJYHSBM2.js.map +7 -0
  255. package/dist/runner/git-commit-BA53DOJQ.js +30 -0
  256. package/dist/runner/git-commit-BA53DOJQ.js.map +7 -0
  257. package/dist/runner/hook-runner-JHH6PGKE.js +220 -0
  258. package/dist/runner/hook-runner-JHH6PGKE.js.map +7 -0
  259. package/dist/runner/judge-transport-R4TF5LEH.js +91 -0
  260. package/dist/runner/judge-transport-R4TF5LEH.js.map +7 -0
  261. package/dist/runner/mcp-status-QEUH2KGX.js +89 -0
  262. package/dist/runner/mcp-status-QEUH2KGX.js.map +7 -0
  263. package/dist/runner/notification-FKMBCSXF.js +69 -0
  264. package/dist/runner/notification-FKMBCSXF.js.map +7 -0
  265. package/dist/runner/post-tool-3MRHTBKH.js +192 -0
  266. package/dist/runner/post-tool-3MRHTBKH.js.map +7 -0
  267. package/dist/runner/post-tool-agent-BB34MNHI.js +370 -0
  268. package/dist/runner/post-tool-agent-BB34MNHI.js.map +7 -0
  269. package/dist/runner/post-tool-changelog-sync-OP2TT2I7.js +147 -0
  270. package/dist/runner/post-tool-changelog-sync-OP2TT2I7.js.map +7 -0
  271. package/dist/runner/post-tool-code-structure-LE7J2SC2.js +130 -0
  272. package/dist/runner/post-tool-code-structure-LE7J2SC2.js.map +7 -0
  273. package/dist/runner/post-tool-edit-ledger-IJMEYHKF.js +30 -0
  274. package/dist/runner/post-tool-edit-ledger-IJMEYHKF.js.map +7 -0
  275. package/dist/runner/post-tool-failure-XTH2I2Z7.js +111 -0
  276. package/dist/runner/post-tool-failure-XTH2I2Z7.js.map +7 -0
  277. package/dist/runner/post-tool-git-E46HZGZO.js +94 -0
  278. package/dist/runner/post-tool-git-E46HZGZO.js.map +7 -0
  279. package/dist/runner/post-tool-mcp-AMCDY5GH.js +144 -0
  280. package/dist/runner/post-tool-mcp-AMCDY5GH.js.map +7 -0
  281. package/dist/runner/post-tool-task-state-TLDOI33H.js +100 -0
  282. package/dist/runner/post-tool-task-state-TLDOI33H.js.map +7 -0
  283. package/dist/runner/pre-tool-SQE2FZQO.js +245 -0
  284. package/dist/runner/pre-tool-SQE2FZQO.js.map +7 -0
  285. package/dist/runner/pre-tool-agent-OZUPVFUI.js +218 -0
  286. package/dist/runner/pre-tool-agent-OZUPVFUI.js.map +7 -0
  287. package/dist/runner/quality-evaluator-XYNDKDRG.js +901 -0
  288. package/dist/runner/quality-evaluator-XYNDKDRG.js.map +7 -0
  289. package/dist/runner/session-end-3MJTDLLA.js +57 -0
  290. package/dist/runner/session-end-3MJTDLLA.js.map +7 -0
  291. package/dist/runner/session-start-5ZMCLKBS.js +352 -0
  292. package/dist/runner/session-start-5ZMCLKBS.js.map +7 -0
  293. package/dist/runner/shipper-status-MADX6SPG.js +37 -0
  294. package/dist/runner/shipper-status-MADX6SPG.js.map +7 -0
  295. package/dist/runner/span-shipper-4HQDHC47.js +3408 -0
  296. package/dist/runner/span-shipper-4HQDHC47.js.map +7 -0
  297. package/dist/runner/stop-RTKSIYJV.js +596 -0
  298. package/dist/runner/stop-RTKSIYJV.js.map +7 -0
  299. package/dist/runner/subagent-CBCG4OLZ.js +116 -0
  300. package/dist/runner/subagent-CBCG4OLZ.js.map +7 -0
  301. package/dist/runner/token-metrics-AD2RAFGM.js +31 -0
  302. package/dist/runner/token-metrics-AD2RAFGM.js.map +7 -0
  303. package/dist/runner/user-prompt-T5NZ2UJD.js +376 -0
  304. package/dist/runner/user-prompt-T5NZ2UJD.js.map +7 -0
  305. package/package.json +68 -5
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Per-session { byte offset, running totals } checkpoint, so each Stop reads only the bytes
3
+ * appended since the last; the same walk pairs `tool_use` → `tool_result`.
4
+ *
5
+ * Rebuild triggers: version mismatch, structural invalidity, a shrunk transcript, or a different
6
+ * transcript file (another spelling of the same file resumes); never age. A transcript rewritten to at least its old size is not detected.
7
+ * A rebuild re-reports the whole transcript as growth, so bump the version only when needed.
8
+ */
9
+ import { statSync } from 'node:fs';
10
+ import { isJsonObject } from '../core/file-utils.js';
11
+ import { isNonNegativeInteger } from '../core/units.js';
12
+ import { resumeOffset, transcriptCheckpointStore } from '../session/session-state.js';
13
+ import { emptyAccumulator, emptyModelTotals, emptyStats, foldTranscriptFrom, TOKEN_TOTAL_FIELDS, USAGE_FIELD_NAMES, } from './transcript-fold.js';
14
+ const CHECKPOINT_FILE = 'token-metrics.json';
15
+ /** Incremented when the checkpoint schema changes in a backward-incompatible way; mismatches trigger a one-time full rebuild. */
16
+ const CHECKPOINT_VERSION = 2;
17
+ // --- Totals arithmetic ---
18
+ function emptyDelta() {
19
+ return { ...emptyModelTotals(), messageCount: 0 };
20
+ }
21
+ /** Undefined until a line has carried the field, so no reasoning counter is recorded. */
22
+ function diffReasoning(current, previous) {
23
+ return current === undefined ? undefined : current - (previous ?? 0);
24
+ }
25
+ function diffTotals(current, previous) {
26
+ const delta = emptyModelTotals();
27
+ for (const field of TOKEN_TOTAL_FIELDS)
28
+ delta[field] = current[field] - previous[field];
29
+ const reasoning = diffReasoning(current.totalReasoningTokens, previous.totalReasoningTokens);
30
+ if (reasoning !== undefined)
31
+ delta.totalReasoningTokens = reasoning;
32
+ return delta;
33
+ }
34
+ function diffStats(current, previous) {
35
+ return {
36
+ ...diffTotals(current, previous),
37
+ messageCount: current.messageCount - previous.messageCount,
38
+ };
39
+ }
40
+ function hasTotalsGrowth(delta) {
41
+ return TOKEN_TOTAL_FIELDS.some((field) => delta[field] !== 0) || (delta.totalReasoningTokens ?? 0) !== 0;
42
+ }
43
+ function diffModelTotals(current, previous) {
44
+ const deltas = [];
45
+ for (const [model, totals] of current) {
46
+ const delta = diffTotals(totals, previous.get(model) ?? emptyModelTotals());
47
+ if (hasTotalsGrowth(delta))
48
+ deltas.push([model, delta]);
49
+ }
50
+ return deltas;
51
+ }
52
+ /** A straddled response grows the totals without a new message. A fresh start (no live checkpoint) is always a change, even when empty. */
53
+ function isChanged(delta, fresh) {
54
+ return delta.messageCount !== 0 || hasTotalsGrowth(delta) || fresh;
55
+ }
56
+ // --- Checkpoint validation ---
57
+ /** Every `fields` entry is a token count; `optionalField`, a reasoning count absent until a line carries thinking tokens, is one or absent. */
58
+ function hasTokenCounts(fields, optionalField) {
59
+ return (value) => isJsonObject(value)
60
+ && fields.every((field) => isNonNegativeInteger(value[field]))
61
+ && (value[optionalField] === undefined || isNonNegativeInteger(value[optionalField]));
62
+ }
63
+ const isUsageHWM = hasTokenCounts(USAGE_FIELD_NAMES, 'thinking_tokens');
64
+ const isModelTotals = hasTokenCounts(TOKEN_TOTAL_FIELDS, 'totalReasoningTokens');
65
+ function isValidStats(value) {
66
+ if (!isJsonObject(value))
67
+ return false;
68
+ const { messageCount, model } = value;
69
+ return isModelTotals(value) && typeof messageCount === 'number' && typeof model === 'string';
70
+ }
71
+ function isValidEntriesOf(value, isValidValue) {
72
+ if (!Array.isArray(value))
73
+ return false;
74
+ return value.every((entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === 'string' && isValidValue(entry[1]));
75
+ }
76
+ function isValidOpenToolCalls(value) {
77
+ return isJsonObject(value) && Object.values(value).every((call) => isJsonObject(call) && typeof call.startMs === 'number' && typeof call.tool === 'string');
78
+ }
79
+ const checkpoints = transcriptCheckpointStore({
80
+ file: CHECKPOINT_FILE,
81
+ version: CHECKPOINT_VERSION,
82
+ isValidBody: (value) => isNonNegativeInteger(value.offset)
83
+ && isValidStats(value.stats)
84
+ && isValidOpenToolCalls(value.openToolCalls)
85
+ && isValidEntriesOf(value.countedMessages, isUsageHWM)
86
+ && isValidEntriesOf(value.byModel, isModelTotals),
87
+ });
88
+ function saveCheckpoint(sessionId, transcriptPath, offset, acc) {
89
+ checkpoints.save(sessionId, transcriptPath, {
90
+ offset,
91
+ stats: acc.stats,
92
+ openToolCalls: acc.openToolCalls,
93
+ countedMessages: [...acc.countedUsage],
94
+ byModel: [...acc.modelTotals],
95
+ });
96
+ }
97
+ function resumedAccumulator(resume) {
98
+ if (resume === null)
99
+ return emptyAccumulator();
100
+ // Shallow-copy stats and each model-totals entry: addUsage mutates them in place, and
101
+ // deltasSinceResume compares acc.stats against resume.stats after the walk.
102
+ return {
103
+ stats: { ...resume.stats },
104
+ modelTotals: new Map(resume.byModel.map(([m, t]) => [m, { ...t }])),
105
+ countedUsage: new Map(resume.countedMessages),
106
+ openToolCalls: Object.fromEntries(Object.entries(resume.openToolCalls).map(([id, call]) => [id, { ...call }])),
107
+ toolDurations: [],
108
+ toolCalls: 0,
109
+ };
110
+ }
111
+ // --- Entry point ---
112
+ function deltasSinceResume(acc, resume) {
113
+ const baselineStats = resume?.stats ?? emptyStats();
114
+ const baselineModelTotals = resume ? new Map(resume.byModel) : new Map();
115
+ return {
116
+ delta: diffStats(acc.stats, baselineStats),
117
+ deltaByModel: diffModelTotals(acc.modelTotals, baselineModelTotals),
118
+ };
119
+ }
120
+ /** Full parse when no valid checkpoint exists, the transcript shrank or it is a different file. */
121
+ export function extractTokenStats(transcriptPath, sessionId) {
122
+ try {
123
+ const fileSize = statSync(transcriptPath).size;
124
+ const checkpoint = checkpoints.load(sessionId, transcriptPath);
125
+ if (fileSize === checkpoint?.offset) {
126
+ return {
127
+ stats: checkpoint.stats,
128
+ changed: false,
129
+ delta: emptyDelta(),
130
+ deltaByModel: [],
131
+ toolDurations: [],
132
+ };
133
+ }
134
+ const start = resumeOffset(checkpoint, fileSize);
135
+ const fresh = start === 0;
136
+ const resume = fresh ? null : checkpoint;
137
+ const acc = resumedAccumulator(resume);
138
+ const consumed = foldTranscriptFrom(transcriptPath, start, acc);
139
+ const { delta, deltaByModel } = deltasSinceResume(acc, resume);
140
+ saveCheckpoint(sessionId, transcriptPath, consumed, acc);
141
+ return {
142
+ stats: acc.stats,
143
+ changed: isChanged(delta, fresh),
144
+ delta,
145
+ deltaByModel,
146
+ toolDurations: acc.toolDurations,
147
+ };
148
+ }
149
+ catch {
150
+ return null;
151
+ }
152
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Tool-call pairing: open calls keyed by `tool_use` id, closed by their
3
+ * `tool_result`. Shared between agent-transcript-metrics.ts (subagent reads)
4
+ * and token-metrics-checkpoint.ts (main-loop Stop reads). The open-call state
5
+ * is a plain object so it survives the checkpoint's JSON round trip.
6
+ */
7
+ import { UNKNOWN_TOOL_NAME } from '../core/constants.js';
8
+ import { TIME_MS } from '../core/units.js';
9
+ import { ASSISTANT_RECORD_TYPE, USER_RECORD_TYPE, toBlocks } from './transcript-entry.js';
10
+ /** The transcript records only that a tool failed, not how. */
11
+ export const TOOL_ERROR_TYPE = 'tool_error';
12
+ function toEpochMs(timestamp) {
13
+ if (!timestamp)
14
+ return undefined;
15
+ const ms = Date.parse(timestamp);
16
+ return Number.isNaN(ms) ? undefined : ms;
17
+ }
18
+ function openCalls(entry, blocks, open) {
19
+ const startMs = toEpochMs(entry.timestamp);
20
+ let toolUses = 0;
21
+ for (const block of blocks) {
22
+ if (block.type !== 'tool_use')
23
+ continue;
24
+ toolUses++;
25
+ if (block.id && startMs !== undefined)
26
+ open[block.id] = { startMs, tool: block.name || UNKNOWN_TOOL_NAME };
27
+ }
28
+ return toolUses;
29
+ }
30
+ function closeCalls(entry, blocks, open, durations) {
31
+ const endMs = toEpochMs(entry.timestamp);
32
+ if (endMs === undefined)
33
+ return;
34
+ for (const block of blocks) {
35
+ if (block.type !== 'tool_result' || !block.tool_use_id)
36
+ continue;
37
+ const call = open[block.tool_use_id];
38
+ if (!call)
39
+ continue;
40
+ delete open[block.tool_use_id];
41
+ // Clamped: the two timestamps come from different processes.
42
+ durations.push({
43
+ tool: call.tool,
44
+ seconds: Math.max(0, endMs - call.startMs) / TIME_MS.SECOND,
45
+ ...(call.turnCrossed ? { crossTurn: true } : {}),
46
+ ...(block.is_error === true ? { failed: true } : {}),
47
+ });
48
+ }
49
+ }
50
+ /** Returns the entry's `tool_use` count. */
51
+ export function collectToolCalls(entry, open, durations) {
52
+ const blocks = toBlocks(entry.message?.content);
53
+ if (entry.type === ASSISTANT_RECORD_TYPE)
54
+ return openCalls(entry, blocks, open);
55
+ if (entry.type === USER_RECORD_TYPE)
56
+ closeCalls(entry, blocks, open, durations);
57
+ return 0;
58
+ }
59
+ /** Marks all currently open calls as having crossed a turn boundary. Called when a `turn_duration` record is seen. */
60
+ export function markTurnBoundary(open) {
61
+ for (const call of Object.values(open)) {
62
+ call.turnCrossed = true;
63
+ }
64
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The Claude Code transcript JSONL record, shared by every transcript reader. A line's
3
+ * role is its record `type`, never `message.role`: `api-request-blob` replays carry a
4
+ * `message.role` and are not conversation.
5
+ */
6
+ import { SYNTHETIC_MODEL } from '../core/constants.js';
7
+ import { isJsonObject } from '../core/file-utils.js';
8
+ import { alternation } from '../core/regex.js';
9
+ export const SYSTEM_RECORD_TYPE = 'system';
10
+ export const TURN_DURATION_SUBTYPE = 'turn_duration';
11
+ export const USER_RECORD_TYPE = 'user';
12
+ export const ASSISTANT_RECORD_TYPE = 'assistant';
13
+ export const CONVERSATION_RECORD_TYPES = new Set([USER_RECORD_TYPE, ASSISTANT_RECORD_TYPE]);
14
+ /** Both spacing variants the JSON serializer emits for a `"key": "value"` field. */
15
+ export function fieldMarkers(field, value) {
16
+ return [`"${field}":"${value}"`, `"${field}": "${value}"`];
17
+ }
18
+ /** Matches a conversation record type as a JSON string token, wherever its field sits; one regex pass is ~8x cheaper than one `includes` per type. */
19
+ const CONVERSATION_TYPE_TOKEN = new RegExp(`"${alternation([...CONVERSATION_RECORD_TYPES])}"`);
20
+ /** Skips parsing the attachment, snapshot and system lines that make up most of a transcript. */
21
+ export function mayBeConversational(line) {
22
+ return CONVERSATION_TYPE_TOKEN.test(line);
23
+ }
24
+ export function toBlocks(content) {
25
+ if (!Array.isArray(content))
26
+ return [];
27
+ return content.filter((block) => isJsonObject(block));
28
+ }
29
+ export function classifyEntry(entry) {
30
+ if (entry.type === USER_RECORD_TYPE)
31
+ return 'prompt';
32
+ if (entry.type !== ASSISTANT_RECORD_TYPE)
33
+ return 'other';
34
+ return entry.message?.model === SYNTHETIC_MODEL ? 'notice' : 'response';
35
+ }
36
+ export function isModelResponse(entry) {
37
+ return classifyEntry(entry) === 'response';
38
+ }
39
+ /** A billed response's usage record; undefined for a notice, a prompt, or a response without one. */
40
+ export function responseUsage(entry) {
41
+ return isModelResponse(entry) ? entry.message?.usage : undefined;
42
+ }
43
+ /** A conversation record Claude Code flagged for a request that was never answered (rate limit, server error, login). */
44
+ export function isFailedRequest(entry) {
45
+ return entry.type !== undefined && CONVERSATION_RECORD_TYPES.has(entry.type) && entry.isApiErrorMessage === true;
46
+ }
47
+ /** A missing or non-finite count reads as 0. */
48
+ export function tokenCount(value) {
49
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
50
+ }
51
+ /** Input as the semconv counts it: "input (prompt) tokens used, including cached tokens", written or read. */
52
+ export function inputTokensIncludingCache(inputTokens, cacheCreationTokens, cacheReadTokens) {
53
+ return inputTokens + cacheCreationTokens + cacheReadTokens;
54
+ }
55
+ export function usageCounts(usage) {
56
+ return {
57
+ inputTokens: tokenCount(usage.input_tokens),
58
+ cacheCreationTokens: tokenCount(usage.cache_creation_input_tokens),
59
+ cacheReadTokens: tokenCount(usage.cache_read_input_tokens),
60
+ outputTokens: tokenCount(usage.output_tokens),
61
+ };
62
+ }
63
+ /** Everything one call read as input, from its raw usage record. */
64
+ export function promptTokens(usage) {
65
+ const counts = usageCounts(usage);
66
+ return inputTokensIncludingCache(counts.inputTokens, counts.cacheCreationTokens, counts.cacheReadTokens);
67
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * One fold over transcript lines, shared by the Stop checkpoint (resumed from persisted state,
3
+ * read from the last offset) and the subagent reader (empty state, read from offset 0). It owns
4
+ * the rules both report: which line is a response, how a response's repeated usage counts once,
5
+ * which model a line is billed to, and `tool_use` → `tool_result` pairing.
6
+ */
7
+ import { THRESHOLDS } from '../core/constants.js';
8
+ import { byteMarkers, consumeLines, hasAnyMarker, parseJsonLine, readLinesFrom } from '../core/jsonl-tail.js';
9
+ import { collectToolCalls, markTurnBoundary } from './tool-call-durations.js';
10
+ import { responseUsage, SYSTEM_RECORD_TYPE, tokenCount, TURN_DURATION_SUBTYPE, } from './transcript-entry.js';
11
+ /** A line carrying none of these is skipped unparsed. */
12
+ const RELEVANT_LINE_KEYS = ['"usage"', '"tool_use"', '"tool_result"', '"turn_duration"'];
13
+ /** Only the newest responses can still be growing, so `rememberUsage` evicts older ids. */
14
+ export const COUNTED_MESSAGE_IDS_MAX = 64;
15
+ /** `stats.model` until a response names one. */
16
+ export const INITIAL_MODEL = 'unknown';
17
+ /** Usage-record field → `SessionTokenStats` total field: the four counted fields, in a stable order. */
18
+ const USAGE_TOTAL_FIELDS = [
19
+ ['input_tokens', 'totalInputTokens'],
20
+ ['output_tokens', 'totalOutputTokens'],
21
+ ['cache_read_input_tokens', 'totalCacheReadTokens'],
22
+ ['cache_creation_input_tokens', 'totalCacheCreationTokens'],
23
+ ];
24
+ export const USAGE_FIELD_NAMES = USAGE_TOTAL_FIELDS.map(([usage]) => usage);
25
+ export const TOKEN_TOTAL_FIELDS = USAGE_TOTAL_FIELDS.map(([, total]) => total);
26
+ export function emptyModelTotals() {
27
+ return Object.fromEntries(TOKEN_TOTAL_FIELDS.map((field) => [field, 0]));
28
+ }
29
+ export function emptyStats() {
30
+ return { ...emptyModelTotals(), messageCount: 0, model: INITIAL_MODEL };
31
+ }
32
+ export function emptyAccumulator() {
33
+ return { stats: emptyStats(), modelTotals: new Map(), countedUsage: new Map(), openToolCalls: {}, toolDurations: [], toolCalls: 0 };
34
+ }
35
+ function modelTotalsFor(totals, model) {
36
+ let modelTotals = totals.get(model);
37
+ if (modelTotals === undefined) {
38
+ modelTotals = emptyModelTotals();
39
+ totals.set(model, modelTotals);
40
+ }
41
+ return modelTotals;
42
+ }
43
+ // --- Usage accumulation ---
44
+ export function emptyUsageHWM() {
45
+ return Object.fromEntries(USAGE_FIELD_NAMES.map((field) => [field, 0]));
46
+ }
47
+ /**
48
+ * Per-field growth of `usage` over `hwm`, and the raised HWM: a field counts only what it adds
49
+ * over the most an earlier line of the same response carried. `delta.thinking_tokens` is set only
50
+ * on positive growth; a later line that drops the field does not lower the HWM.
51
+ */
52
+ export function computeUsageGrowth(usage, hwm) {
53
+ const newHwm = emptyUsageHWM();
54
+ const delta = emptyUsageHWM();
55
+ for (const field of USAGE_FIELD_NAMES) {
56
+ const before = hwm?.[field] ?? 0;
57
+ newHwm[field] = Math.max(tokenCount(usage[field]), before);
58
+ delta[field] = newHwm[field] - before;
59
+ }
60
+ const thinking = usage.output_tokens_details?.thinking_tokens;
61
+ const prevThinking = hwm?.thinking_tokens;
62
+ if (thinking !== undefined || prevThinking !== undefined) {
63
+ newHwm.thinking_tokens = Math.max(tokenCount(thinking), prevThinking ?? 0);
64
+ const thinkingGrowth = newHwm.thinking_tokens - (prevThinking ?? 0);
65
+ if (thinkingGrowth > 0)
66
+ delta.thinking_tokens = thinkingGrowth;
67
+ }
68
+ return { delta, newHwm };
69
+ }
70
+ /** Re-inserts `id` newest and evicts the oldest past the cap. A response's lines are contiguous; one split by more than the cap's worth of other ids would be re-added in full. */
71
+ function rememberUsage(counted, id, hwm) {
72
+ counted.delete(id);
73
+ counted.set(id, hwm);
74
+ if (counted.size <= COUNTED_MESSAGE_IDS_MAX)
75
+ return;
76
+ const oldest = counted.keys().next();
77
+ if (!oldest.done)
78
+ counted.delete(oldest.value);
79
+ }
80
+ /** Applies per-field growth of `usage` over the existing HWM to every target; returns the new HWM. */
81
+ function addUsageGrowth(targets, usage, hwm) {
82
+ const { delta, newHwm } = computeUsageGrowth(usage, hwm);
83
+ for (const [field, total] of USAGE_TOTAL_FIELDS) {
84
+ for (const target of targets)
85
+ target[total] += delta[field];
86
+ }
87
+ if (delta.thinking_tokens !== undefined) {
88
+ for (const target of targets)
89
+ target.totalReasoningTokens = (target.totalReasoningTokens ?? 0) + delta.thinking_tokens;
90
+ }
91
+ return newHwm;
92
+ }
93
+ /** A response spans several lines under one `message.id`, each repeating its usage, and can straddle two Stop reads: each field adds only its growth over what the id already contributed. A line without `model` is billed to the last model seen. */
94
+ function addUsage(acc, entry) {
95
+ const usage = responseUsage(entry);
96
+ if (!usage)
97
+ return;
98
+ const id = entry.message?.id;
99
+ const counted = id === undefined ? undefined : acc.countedUsage.get(id);
100
+ if (entry.message?.model)
101
+ acc.stats.model = entry.message.model;
102
+ const merged = addUsageGrowth([acc.stats, modelTotalsFor(acc.modelTotals, acc.stats.model)], usage, counted);
103
+ if (counted === undefined)
104
+ acc.stats.messageCount++;
105
+ if (id !== undefined)
106
+ rememberUsage(acc.countedUsage, id, merged);
107
+ }
108
+ // --- Line walk ---
109
+ const RELEVANT_LINE_MARKERS = byteMarkers(RELEVANT_LINE_KEYS);
110
+ function consumeEntry(entry, acc) {
111
+ addUsage(acc, entry);
112
+ if (entry.type === SYSTEM_RECORD_TYPE && entry.subtype === TURN_DURATION_SUBTYPE) {
113
+ markTurnBoundary(acc.openToolCalls);
114
+ }
115
+ acc.toolCalls += collectToolCalls(entry, acc.openToolCalls, acc.toolDurations);
116
+ }
117
+ function consumeLine(bytes, acc) {
118
+ if (!hasAnyMarker(bytes, RELEVANT_LINE_MARKERS))
119
+ return;
120
+ const entry = parseJsonLine(bytes.toString('utf-8'));
121
+ if (entry !== undefined)
122
+ consumeEntry(entry, acc);
123
+ }
124
+ /** Parsed here so an irrelevant fragment still proves complete (cursor advances past it); relevance is checked later in consumeLine. */
125
+ const acceptFragment = (bytes) => parseJsonLine(bytes.toString('utf-8')) !== undefined;
126
+ /** Folds every complete line from `start` into `acc`, plus a trailing fragment that parses; returns the offset consumed through. */
127
+ export function foldTranscriptFrom(transcriptPath, start, acc) {
128
+ const lines = readLinesFrom(transcriptPath, start, THRESHOLDS.MESSAGE_COUNT_MAX_READ_BYTES, acceptFragment);
129
+ return consumeLines(lines, start, (bytes) => consumeLine(bytes, acc));
130
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Where Claude Code keeps a session's transcript: `projects/{slug}/{session-id}.jsonl`.
3
+ * Deliberately exports no cwd-to-slug encoder: the slug algorithm is Claude Code's
4
+ * private detail (`/` and `.` both map to `-`). Scanning for the session id is
5
+ * verified truth. Prefer the payload's `transcript_path`.
6
+ */
7
+ import { existsSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { CLAUDE_HOME } from '../core/constants.js';
10
+ import { readdirOrEmpty } from '../core/file-utils.js';
11
+ import { SESSION_ID_PATTERN } from '../core/regex.js';
12
+ /** Root holding one directory per project. */
13
+ export function projectsDir(home = CLAUDE_HOME) {
14
+ return join(home, 'projects');
15
+ }
16
+ /** Every project directory under {@link projectsDir}; empty when the root is missing. */
17
+ export function projectDirPaths(home = CLAUDE_HOME) {
18
+ const root = projectsDir(home);
19
+ return readdirOrEmpty(root).map(project => join(root, project));
20
+ }
21
+ const SUBAGENTS_DIR = 'subagents';
22
+ /** Prefix of every per-agent file in {@link subagentsDir}: `agent-<id>.jsonl`, `.meta.json`, `.forked-skill.json`. */
23
+ export const AGENT_FILE_PREFIX = 'agent-';
24
+ /** Where Claude Code writes a session's subagent files, beside its transcript in `projectDir`. */
25
+ export function subagentsDir(projectDir, sessionId) {
26
+ return join(projectDir, sessionId, SUBAGENTS_DIR);
27
+ }
28
+ /** Locate the transcript by scanning project directories; undefined when malformed or absent. */
29
+ export function findTranscriptPath(sessionId, home = CLAUDE_HOME) {
30
+ // Validate before the path join (path traversal).
31
+ if (!SESSION_ID_PATTERN.test(sessionId))
32
+ return undefined;
33
+ for (const dir of projectDirPaths(home)) {
34
+ const candidate = join(dir, `${sessionId}.jsonl`);
35
+ if (existsSync(candidate))
36
+ return candidate;
37
+ }
38
+ return undefined;
39
+ }
@@ -0,0 +1,117 @@
1
+ /** Turns from Claude Code transcript JSONL, for the T2 judge. */
2
+ import { createHash } from 'node:crypto';
3
+ import { truncate } from '../core/format-utils.js';
4
+ import { parseJsonLines, readFileSlice } from '../core/jsonl-tail.js';
5
+ import { isByteCount } from '../core/units.js';
6
+ import { classifyEntry, isFailedRequest, mayBeConversational, toBlocks, } from './transcript-entry.js';
7
+ // --- Constants ---
8
+ export const MAX_TEXT_LENGTH = 8000;
9
+ export const MAX_TOOL_RESULTS_PER_TURN = 20;
10
+ export const MAX_TOOL_RESULT_LENGTH = 500;
11
+ // --- Content blocks ---
12
+ /** `thinking` and `tool_use` blocks carry no `text` and drop out. */
13
+ function extractTextContent(content) {
14
+ if (typeof content === 'string')
15
+ return content;
16
+ return toBlocks(content)
17
+ .filter((block) => typeof block.text === 'string')
18
+ .map(block => block.text)
19
+ .join('\n');
20
+ }
21
+ /** `tool_result` blocks arrive inside the USER entry that follows the `tool_use`. */
22
+ function extractToolResults(content, limit) {
23
+ return toBlocks(content)
24
+ .filter(block => block.type === 'tool_result')
25
+ .slice(0, limit)
26
+ .map(block => truncate(extractTextContent(block.content), MAX_TOOL_RESULT_LENGTH));
27
+ }
28
+ // --- Turn extraction ---
29
+ /** A turn being built, untruncated until `toTurn`. */
30
+ function newDraft(userText) {
31
+ return { userText, assistantText: '', toolResults: [] };
32
+ }
33
+ /** Stops past `MAX_TEXT_LENGTH`, which `toTurn` truncates to anyway. */
34
+ function appendAssistantText(draft, text) {
35
+ if (!text || draft.assistantText.length > MAX_TEXT_LENGTH)
36
+ return;
37
+ draft.assistantText = draft.assistantText ? `${draft.assistantText}\n${text}` : text;
38
+ }
39
+ /** `cutOffBy` and `responseId` are only ever set to defined values, so the spread adds no undefined keys. */
40
+ function toTurn(draft) {
41
+ if (!draft.userText || !draft.assistantText)
42
+ return null;
43
+ return {
44
+ ...draft,
45
+ userText: truncate(draft.userText, MAX_TEXT_LENGTH),
46
+ assistantText: truncate(draft.assistantText, MAX_TEXT_LENGTH),
47
+ };
48
+ }
49
+ function readTranscript(transcriptPath, maxBytes) {
50
+ try {
51
+ return readFileSlice(transcriptPath, maxBytes);
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
57
+ /** Reads only the first `maxBytes`, so turns appended after that size are not drawn. Throws on a bad `maxBytes`. */
58
+ export function extractTurns(transcriptPath, maxBytes) {
59
+ // Outside the read's catch, so a caller that drops the count fails instead of drawing no turns.
60
+ if (!isByteCount(maxBytes)) {
61
+ throw new RangeError(`extractTurns: maxBytes must be a non-negative integer, got ${String(maxBytes)}`);
62
+ }
63
+ const content = readTranscript(transcriptPath, maxBytes);
64
+ if (content === null)
65
+ return [];
66
+ const turns = [];
67
+ let draft = newDraft('');
68
+ const emit = () => {
69
+ const turn = toTurn(draft);
70
+ if (turn)
71
+ turns.push(turn);
72
+ };
73
+ for (const entry of parseJsonLines(content, mayBeConversational)) {
74
+ const rawContent = entry.message?.content;
75
+ const kind = classifyEntry(entry);
76
+ if (kind === 'prompt') {
77
+ // Tool output answers the turn in progress, so a tool-result-only entry must not end it.
78
+ const remainingToolSlots = MAX_TOOL_RESULTS_PER_TURN - draft.toolResults.length;
79
+ draft.toolResults.push(...extractToolResults(rawContent, remainingToolSlots));
80
+ const text = extractTextContent(rawContent);
81
+ if (text.trim()) {
82
+ emit();
83
+ draft = newDraft(text);
84
+ }
85
+ }
86
+ else if (isFailedRequest(entry)) {
87
+ draft.cutOffBy = 'api_error';
88
+ }
89
+ else if (kind === 'response') {
90
+ appendAssistantText(draft, extractTextContent(rawContent));
91
+ if (entry.message?.id)
92
+ draft.responseId = entry.message.id;
93
+ }
94
+ // Any other notice ("No response requested.") is Claude Code's text, not the model's: the judge never scores it.
95
+ }
96
+ emit();
97
+ return turns;
98
+ }
99
+ /** Indexes are assigned before filtering, so `turn.index` is a transcript position regardless of what was dropped. */
100
+ export function sampleTurns(turns, maxTurns) {
101
+ const eligible = turns.flatMap((turn, index) => (turn.cutOffBy ? [] : [{ ...turn, index }]));
102
+ if (eligible.length <= maxTurns)
103
+ return eligible;
104
+ // Partial Fisher-Yates: the first `maxTurns` slots end up a uniform sample.
105
+ for (let i = 0; i < maxTurns; i++) {
106
+ const j = i + Math.floor(Math.random() * (eligible.length - i));
107
+ const [picked, displaced] = [eligible[j], eligible[i]];
108
+ if (picked !== undefined && displaced !== undefined)
109
+ [eligible[i], eligible[j]] = [picked, displaced];
110
+ }
111
+ return eligible.slice(0, maxTurns).sort((a, b) => a.index - b.index);
112
+ }
113
+ const TURN_USER_TEXT_HASH_ALGORITHM = 'sha256';
114
+ /** Of the truncated `userText`, so the judged turn can be confirmed without storing transcript text. */
115
+ export function hashTurnUserText(userText) {
116
+ return createHash(TURN_USER_TEXT_HASH_ALGORITHM).update(userText).digest('hex');
117
+ }
@@ -0,0 +1,23 @@
1
+ import { createRequire as __hookRunnerCreateRequire } from 'node:module';
2
+ const require = __hookRunnerCreateRequire(import.meta.url);
3
+ import {
4
+ PENDING_AGENT_TTL_MS,
5
+ clearSession,
6
+ generateHex,
7
+ getAgentStateSizes,
8
+ popPendingAgent,
9
+ savePendingAgent
10
+ } from "./chunk-I7TD2QVR.js";
11
+ import "./chunk-DNSTWC26.js";
12
+ import "./chunk-52RY6LQT.js";
13
+ import "./chunk-RWRGC7ZK.js";
14
+ import "./chunk-GNNKUMRF.js";
15
+ export {
16
+ PENDING_AGENT_TTL_MS,
17
+ clearSession,
18
+ generateHex,
19
+ getAgentStateSizes,
20
+ popPendingAgent,
21
+ savePendingAgent
22
+ };
23
+ //# sourceMappingURL=agent-context-4XTCLMLZ.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -0,0 +1,68 @@
1
+ import { createRequire as __hookRunnerCreateRequire } from 'node:module';
2
+ const require = __hookRunnerCreateRequire(import.meta.url);
3
+ import {
4
+ sessionStateDir
5
+ } from "./chunk-DNSTWC26.js";
6
+ import {
7
+ loadJson,
8
+ withFileLock,
9
+ writeJsonAtomic
10
+ } from "./chunk-52RY6LQT.js";
11
+ import "./chunk-RWRGC7ZK.js";
12
+ import "./chunk-GNNKUMRF.js";
13
+
14
+ // lib/agent/agent-file-budget.ts
15
+ import { join } from "node:path";
16
+ var AUTO_ERROR_RESOLVER_FILE_BUDGET = 3;
17
+ var BUDGET_FILE = "agent-file-budget.json";
18
+ var LOCK_FILE = "agent-file-budget.lock";
19
+ function budgetFilePath(sessionId) {
20
+ return join(sessionStateDir(sessionId), BUDGET_FILE);
21
+ }
22
+ function lockFilePath(sessionId) {
23
+ return join(sessionStateDir(sessionId), LOCK_FILE);
24
+ }
25
+ function mutateBudgetStore(sessionId, fn) {
26
+ return withFileLock(lockFilePath(sessionId), () => {
27
+ const storePath = budgetFilePath(sessionId);
28
+ const store = loadJson(storePath) ?? {};
29
+ const { result, changed } = fn(store);
30
+ if (changed) writeJsonAtomic(storePath, store, { silent: true });
31
+ return result;
32
+ });
33
+ }
34
+ function resetAgentFileBudget(sessionId, agentType) {
35
+ if (!sessionId || !agentType) return;
36
+ try {
37
+ mutateBudgetStore(sessionId, (store) => {
38
+ delete store[agentType];
39
+ return { result: void 0, changed: true };
40
+ });
41
+ } catch {
42
+ }
43
+ }
44
+ function checkAndRecordFilePath(sessionId, agentType, filePath, budget) {
45
+ if (!sessionId || !agentType || !filePath) return { allowed: true, count: 0 };
46
+ try {
47
+ return mutateBudgetStore(sessionId, (store) => {
48
+ const entry = store[agentType] ?? { filePaths: [] };
49
+ if (entry.filePaths.includes(filePath)) {
50
+ return { result: { allowed: true, count: entry.filePaths.length }, changed: false };
51
+ }
52
+ if (entry.filePaths.length >= budget) {
53
+ return { result: { allowed: false, count: entry.filePaths.length }, changed: false };
54
+ }
55
+ entry.filePaths = [...entry.filePaths, filePath];
56
+ store[agentType] = entry;
57
+ return { result: { allowed: true, count: entry.filePaths.length }, changed: true };
58
+ });
59
+ } catch {
60
+ return { allowed: true, count: 0 };
61
+ }
62
+ }
63
+ export {
64
+ AUTO_ERROR_RESOLVER_FILE_BUDGET,
65
+ checkAndRecordFilePath,
66
+ resetAgentFileBudget
67
+ };
68
+ //# sourceMappingURL=agent-file-budget-Q33ESBBE.js.map