@agent-watch-ai/edge 0.2.5

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 (364) hide show
  1. package/CHANGELOG.md +251 -0
  2. package/LICENSE +21 -0
  3. package/README.md +168 -0
  4. package/dist/billing/billing-mode.d.ts +16 -0
  5. package/dist/billing/billing-mode.js +139 -0
  6. package/dist/billing/constants/billing.constants.d.ts +37 -0
  7. package/dist/billing/constants/billing.constants.js +38 -0
  8. package/dist/billing/index.d.ts +6 -0
  9. package/dist/billing/index.js +6 -0
  10. package/dist/cli/args.d.ts +29 -0
  11. package/dist/cli/args.js +61 -0
  12. package/dist/cli/constants/cli.constants.d.ts +60 -0
  13. package/dist/cli/constants/cli.constants.js +60 -0
  14. package/dist/cli/context.d.ts +51 -0
  15. package/dist/cli/context.js +108 -0
  16. package/dist/cli/doctor.d.ts +15 -0
  17. package/dist/cli/doctor.js +416 -0
  18. package/dist/cli/hook.d.ts +20 -0
  19. package/dist/cli/hook.js +166 -0
  20. package/dist/cli/index.d.ts +13 -0
  21. package/dist/cli/index.js +8 -0
  22. package/dist/cli/misc.d.ts +31 -0
  23. package/dist/cli/misc.js +63 -0
  24. package/dist/cli/setup.d.ts +32 -0
  25. package/dist/cli/setup.js +298 -0
  26. package/dist/cli/status.d.ts +11 -0
  27. package/dist/cli/status.js +174 -0
  28. package/dist/cli/types/cli.types.d.ts +69 -0
  29. package/dist/cli/types/cli.types.js +1 -0
  30. package/dist/cli/ui.d.ts +41 -0
  31. package/dist/cli/ui.js +78 -0
  32. package/dist/cli/uninstall.d.ts +13 -0
  33. package/dist/cli/uninstall.js +83 -0
  34. package/dist/cli.d.ts +2 -0
  35. package/dist/cli.js +124 -0
  36. package/dist/config/config-store.d.ts +29 -0
  37. package/dist/config/config-store.js +75 -0
  38. package/dist/config/config.d.ts +73 -0
  39. package/dist/config/config.js +115 -0
  40. package/dist/config/constants/config.constants.d.ts +62 -0
  41. package/dist/config/constants/config.constants.js +70 -0
  42. package/dist/config/index.d.ts +10 -0
  43. package/dist/config/index.js +5 -0
  44. package/dist/config/repo-config.d.ts +37 -0
  45. package/dist/config/repo-config.js +178 -0
  46. package/dist/config/schemas/config.schema.d.ts +409 -0
  47. package/dist/config/schemas/config.schema.js +97 -0
  48. package/dist/config/types/config.types.d.ts +33 -0
  49. package/dist/config/types/config.types.js +1 -0
  50. package/dist/core/async.d.ts +20 -0
  51. package/dist/core/async.js +32 -0
  52. package/dist/core/constants/core.constants.d.ts +18 -0
  53. package/dist/core/constants/core.constants.js +18 -0
  54. package/dist/core/env.d.ts +12 -0
  55. package/dist/core/env.js +20 -0
  56. package/dist/core/index.d.ts +13 -0
  57. package/dist/core/index.js +8 -0
  58. package/dist/core/logger.d.ts +27 -0
  59. package/dist/core/logger.js +82 -0
  60. package/dist/core/number.d.ts +33 -0
  61. package/dist/core/number.js +47 -0
  62. package/dist/core/object.d.ts +78 -0
  63. package/dist/core/object.js +127 -0
  64. package/dist/core/pipe.d.ts +55 -0
  65. package/dist/core/pipe.js +81 -0
  66. package/dist/core/types/core.types.d.ts +54 -0
  67. package/dist/core/types/core.types.js +4 -0
  68. package/dist/core/version.d.ts +19 -0
  69. package/dist/core/version.js +35 -0
  70. package/dist/core/which.d.ts +13 -0
  71. package/dist/core/which.js +57 -0
  72. package/dist/enforcement/constants/enforcement.constants.d.ts +23 -0
  73. package/dist/enforcement/constants/enforcement.constants.js +22 -0
  74. package/dist/enforcement/decision-cache.d.ts +57 -0
  75. package/dist/enforcement/decision-cache.js +138 -0
  76. package/dist/enforcement/decision-client.d.ts +14 -0
  77. package/dist/enforcement/decision-client.js +84 -0
  78. package/dist/enforcement/enforcement.d.ts +17 -0
  79. package/dist/enforcement/enforcement.js +90 -0
  80. package/dist/enforcement/index.d.ts +11 -0
  81. package/dist/enforcement/index.js +10 -0
  82. package/dist/enforcement/schemas/enforcement.schema.d.ts +30 -0
  83. package/dist/enforcement/schemas/enforcement.schema.js +36 -0
  84. package/dist/enforcement/types/enforcement.types.d.ts +59 -0
  85. package/dist/enforcement/types/enforcement.types.js +1 -0
  86. package/dist/enrollment/constants/enrollment.constants.d.ts +6 -0
  87. package/dist/enrollment/constants/enrollment.constants.js +6 -0
  88. package/dist/enrollment/enrollment-provider.d.ts +5 -0
  89. package/dist/enrollment/enrollment-provider.js +1 -0
  90. package/dist/enrollment/index.d.ts +7 -0
  91. package/dist/enrollment/index.js +1 -0
  92. package/dist/enrollment/manual-enrollment.d.ts +32 -0
  93. package/dist/enrollment/manual-enrollment.js +72 -0
  94. package/dist/enrollment/types/enrollment.types.d.ts +25 -0
  95. package/dist/enrollment/types/enrollment.types.js +1 -0
  96. package/dist/events/canonical-event.d.ts +10 -0
  97. package/dist/events/canonical-event.js +9 -0
  98. package/dist/events/constants/enrich.constants.d.ts +14 -0
  99. package/dist/events/constants/enrich.constants.js +15 -0
  100. package/dist/events/constants/events.constants.d.ts +35 -0
  101. package/dist/events/constants/events.constants.js +57 -0
  102. package/dist/events/enrich.d.ts +16 -0
  103. package/dist/events/enrich.js +226 -0
  104. package/dist/events/event-id.d.ts +32 -0
  105. package/dist/events/event-id.js +49 -0
  106. package/dist/events/index.d.ts +14 -0
  107. package/dist/events/index.js +5 -0
  108. package/dist/events/llm-call.d.ts +14 -0
  109. package/dist/events/llm-call.js +84 -0
  110. package/dist/events/product-event.d.ts +39 -0
  111. package/dist/events/product-event.js +19 -0
  112. package/dist/events/types/enrich.types.d.ts +25 -0
  113. package/dist/events/types/enrich.types.js +1 -0
  114. package/dist/events/types/events.types.d.ts +112 -0
  115. package/dist/events/types/events.types.js +1 -0
  116. package/dist/events/types/llm-call.types.d.ts +79 -0
  117. package/dist/events/types/llm-call.types.js +1 -0
  118. package/dist/events/types/repo-snapshot.types.d.ts +32 -0
  119. package/dist/events/types/repo-snapshot.types.js +1 -0
  120. package/dist/feature/constants/feature.constants.d.ts +10 -0
  121. package/dist/feature/constants/feature.constants.js +10 -0
  122. package/dist/feature/index.d.ts +6 -0
  123. package/dist/feature/index.js +6 -0
  124. package/dist/feature/ticket-candidates.d.ts +13 -0
  125. package/dist/feature/ticket-candidates.js +26 -0
  126. package/dist/git/constants/git.constants.d.ts +84 -0
  127. package/dist/git/constants/git.constants.js +113 -0
  128. package/dist/git/git-context.d.ts +52 -0
  129. package/dist/git/git-context.js +226 -0
  130. package/dist/git/index.d.ts +9 -0
  131. package/dist/git/index.js +3 -0
  132. package/dist/git/remote-sanitize.d.ts +26 -0
  133. package/dist/git/remote-sanitize.js +92 -0
  134. package/dist/git/repo-snapshot.d.ts +40 -0
  135. package/dist/git/repo-snapshot.js +95 -0
  136. package/dist/git/types/git.types.d.ts +36 -0
  137. package/dist/git/types/git.types.js +1 -0
  138. package/dist/git/types/snapshot.types.d.ts +25 -0
  139. package/dist/git/types/snapshot.types.js +1 -0
  140. package/dist/otlp/constants/otlp.constants.d.ts +84 -0
  141. package/dist/otlp/constants/otlp.constants.js +99 -0
  142. package/dist/otlp/http.d.ts +24 -0
  143. package/dist/otlp/http.js +37 -0
  144. package/dist/otlp/index.d.ts +9 -0
  145. package/dist/otlp/index.js +3 -0
  146. package/dist/otlp/normalize.d.ts +14 -0
  147. package/dist/otlp/normalize.js +404 -0
  148. package/dist/otlp/types/otlp.types.d.ts +69 -0
  149. package/dist/otlp/types/otlp.types.js +1 -0
  150. package/dist/pipeline/constants/pipeline.constants.d.ts +23 -0
  151. package/dist/pipeline/constants/pipeline.constants.js +22 -0
  152. package/dist/pipeline/hook-pipeline.d.ts +14 -0
  153. package/dist/pipeline/hook-pipeline.js +297 -0
  154. package/dist/pipeline/index.d.ts +6 -0
  155. package/dist/pipeline/index.js +1 -0
  156. package/dist/pipeline/types/pipeline.types.d.ts +48 -0
  157. package/dist/pipeline/types/pipeline.types.js +1 -0
  158. package/dist/privacy/constants/privacy.constants.d.ts +23 -0
  159. package/dist/privacy/constants/privacy.constants.js +38 -0
  160. package/dist/privacy/index.d.ts +7 -0
  161. package/dist/privacy/index.js +2 -0
  162. package/dist/privacy/sanitizer.d.ts +20 -0
  163. package/dist/privacy/sanitizer.js +52 -0
  164. package/dist/privacy/types/privacy.types.d.ts +13 -0
  165. package/dist/privacy/types/privacy.types.js +1 -0
  166. package/dist/providers/antigravity/antigravity.adapter.d.ts +54 -0
  167. package/dist/providers/antigravity/antigravity.adapter.js +311 -0
  168. package/dist/providers/antigravity/antigravity.detect.d.ts +25 -0
  169. package/dist/providers/antigravity/antigravity.detect.js +64 -0
  170. package/dist/providers/antigravity/antigravity.hooks.d.ts +24 -0
  171. package/dist/providers/antigravity/antigravity.hooks.js +126 -0
  172. package/dist/providers/antigravity/antigravity.provider.d.ts +2 -0
  173. package/dist/providers/antigravity/antigravity.provider.js +22 -0
  174. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +72 -0
  175. package/dist/providers/antigravity/constants/antigravity.constants.js +75 -0
  176. package/dist/providers/antigravity/schemas/antigravity.schema.d.ts +521 -0
  177. package/dist/providers/antigravity/schemas/antigravity.schema.js +64 -0
  178. package/dist/providers/antigravity/types/antigravity.types.d.ts +13 -0
  179. package/dist/providers/antigravity/types/antigravity.types.js +1 -0
  180. package/dist/providers/claude/claude.adapter.d.ts +15 -0
  181. package/dist/providers/claude/claude.adapter.js +141 -0
  182. package/dist/providers/claude/claude.detect.d.ts +20 -0
  183. package/dist/providers/claude/claude.detect.js +57 -0
  184. package/dist/providers/claude/claude.hooks.d.ts +23 -0
  185. package/dist/providers/claude/claude.hooks.js +94 -0
  186. package/dist/providers/claude/claude.otel.d.ts +95 -0
  187. package/dist/providers/claude/claude.otel.js +331 -0
  188. package/dist/providers/claude/claude.provider.d.ts +2 -0
  189. package/dist/providers/claude/claude.provider.js +26 -0
  190. package/dist/providers/claude/constants/claude.constants.d.ts +34 -0
  191. package/dist/providers/claude/constants/claude.constants.js +54 -0
  192. package/dist/providers/claude/constants/claude.otel.constants.d.ts +17 -0
  193. package/dist/providers/claude/constants/claude.otel.constants.js +17 -0
  194. package/dist/providers/claude/schemas/claude.schema.d.ts +72 -0
  195. package/dist/providers/claude/schemas/claude.schema.js +32 -0
  196. package/dist/providers/claude/types/claude.types.d.ts +3 -0
  197. package/dist/providers/claude/types/claude.types.js +1 -0
  198. package/dist/providers/codex/codex.adapter.d.ts +11 -0
  199. package/dist/providers/codex/codex.adapter.js +106 -0
  200. package/dist/providers/codex/codex.detect.d.ts +30 -0
  201. package/dist/providers/codex/codex.detect.js +58 -0
  202. package/dist/providers/codex/codex.hooks.d.ts +27 -0
  203. package/dist/providers/codex/codex.hooks.js +129 -0
  204. package/dist/providers/codex/codex.otel.d.ts +51 -0
  205. package/dist/providers/codex/codex.otel.js +325 -0
  206. package/dist/providers/codex/codex.provider.d.ts +2 -0
  207. package/dist/providers/codex/codex.provider.js +25 -0
  208. package/dist/providers/codex/constants/codex.constants.d.ts +41 -0
  209. package/dist/providers/codex/constants/codex.constants.js +62 -0
  210. package/dist/providers/codex/constants/codex.otel.constants.d.ts +22 -0
  211. package/dist/providers/codex/constants/codex.otel.constants.js +22 -0
  212. package/dist/providers/codex/schemas/codex.schema.d.ts +70 -0
  213. package/dist/providers/codex/schemas/codex.schema.js +32 -0
  214. package/dist/providers/codex/types/codex.types.d.ts +3 -0
  215. package/dist/providers/codex/types/codex.types.js +1 -0
  216. package/dist/providers/constants/provider.constants.d.ts +33 -0
  217. package/dist/providers/constants/provider.constants.js +33 -0
  218. package/dist/providers/cursor/constants/cursor.constants.d.ts +58 -0
  219. package/dist/providers/cursor/constants/cursor.constants.js +95 -0
  220. package/dist/providers/cursor/cursor.adapter.d.ts +11 -0
  221. package/dist/providers/cursor/cursor.adapter.js +331 -0
  222. package/dist/providers/cursor/cursor.detect.d.ts +23 -0
  223. package/dist/providers/cursor/cursor.detect.js +66 -0
  224. package/dist/providers/cursor/cursor.hooks.d.ts +25 -0
  225. package/dist/providers/cursor/cursor.hooks.js +95 -0
  226. package/dist/providers/cursor/cursor.provider.d.ts +2 -0
  227. package/dist/providers/cursor/cursor.provider.js +27 -0
  228. package/dist/providers/cursor/schemas/cursor.schema.d.ts +130 -0
  229. package/dist/providers/cursor/schemas/cursor.schema.js +62 -0
  230. package/dist/providers/cursor/types/cursor.types.d.ts +3 -0
  231. package/dist/providers/cursor/types/cursor.types.js +1 -0
  232. package/dist/providers/gemini/constants/gemini.constants.d.ts +36 -0
  233. package/dist/providers/gemini/constants/gemini.constants.js +58 -0
  234. package/dist/providers/gemini/constants/gemini.otel.constants.d.ts +34 -0
  235. package/dist/providers/gemini/constants/gemini.otel.constants.js +48 -0
  236. package/dist/providers/gemini/gemini.adapter.d.ts +15 -0
  237. package/dist/providers/gemini/gemini.adapter.js +146 -0
  238. package/dist/providers/gemini/gemini.detect.d.ts +23 -0
  239. package/dist/providers/gemini/gemini.detect.js +78 -0
  240. package/dist/providers/gemini/gemini.hooks.d.ts +22 -0
  241. package/dist/providers/gemini/gemini.hooks.js +93 -0
  242. package/dist/providers/gemini/gemini.otel.d.ts +62 -0
  243. package/dist/providers/gemini/gemini.otel.js +274 -0
  244. package/dist/providers/gemini/gemini.provider.d.ts +2 -0
  245. package/dist/providers/gemini/gemini.provider.js +22 -0
  246. package/dist/providers/gemini/schemas/gemini.schema.d.ts +81 -0
  247. package/dist/providers/gemini/schemas/gemini.schema.js +35 -0
  248. package/dist/providers/gemini/types/gemini.types.d.ts +3 -0
  249. package/dist/providers/gemini/types/gemini.types.js +1 -0
  250. package/dist/providers/index.d.ts +14 -0
  251. package/dist/providers/index.js +8 -0
  252. package/dist/providers/provider.d.ts +16 -0
  253. package/dist/providers/provider.js +149 -0
  254. package/dist/providers/registry.d.ts +12 -0
  255. package/dist/providers/registry.js +23 -0
  256. package/dist/providers/shared/constants/hook-refusal.constants.d.ts +6 -0
  257. package/dist/providers/shared/constants/hook-refusal.constants.js +6 -0
  258. package/dist/providers/shared/constants/tooling.constants.d.ts +25 -0
  259. package/dist/providers/shared/constants/tooling.constants.js +25 -0
  260. package/dist/providers/shared/event-builder.d.ts +85 -0
  261. package/dist/providers/shared/event-builder.js +166 -0
  262. package/dist/providers/shared/hook-config.d.ts +80 -0
  263. package/dist/providers/shared/hook-config.js +164 -0
  264. package/dist/providers/shared/hook-refusal.d.ts +16 -0
  265. package/dist/providers/shared/hook-refusal.js +33 -0
  266. package/dist/providers/shared/install-record.d.ts +75 -0
  267. package/dist/providers/shared/install-record.js +113 -0
  268. package/dist/providers/shared/tooling.d.ts +58 -0
  269. package/dist/providers/shared/tooling.js +103 -0
  270. package/dist/providers/shared/types/adapter.types.d.ts +54 -0
  271. package/dist/providers/shared/types/adapter.types.js +1 -0
  272. package/dist/providers/shared/types/hook-config.types.d.ts +32 -0
  273. package/dist/providers/shared/types/hook-config.types.js +1 -0
  274. package/dist/providers/types/provider.types.d.ts +98 -0
  275. package/dist/providers/types/provider.types.js +1 -0
  276. package/dist/snapshot/branch-selection.d.ts +37 -0
  277. package/dist/snapshot/branch-selection.js +69 -0
  278. package/dist/snapshot/budget.d.ts +41 -0
  279. package/dist/snapshot/budget.js +67 -0
  280. package/dist/snapshot/constants/snapshot-stages.constants.d.ts +11 -0
  281. package/dist/snapshot/constants/snapshot-stages.constants.js +11 -0
  282. package/dist/snapshot/constants/snapshot.constants.d.ts +56 -0
  283. package/dist/snapshot/constants/snapshot.constants.js +56 -0
  284. package/dist/snapshot/index.d.ts +16 -0
  285. package/dist/snapshot/index.js +6 -0
  286. package/dist/snapshot/snapshot-event.d.ts +17 -0
  287. package/dist/snapshot/snapshot-event.js +66 -0
  288. package/dist/snapshot/snapshot-pipeline.d.ts +14 -0
  289. package/dist/snapshot/snapshot-pipeline.js +163 -0
  290. package/dist/snapshot/snapshot-state.d.ts +55 -0
  291. package/dist/snapshot/snapshot-state.js +100 -0
  292. package/dist/snapshot/types/snapshot.types.d.ts +86 -0
  293. package/dist/snapshot/types/snapshot.types.js +1 -0
  294. package/dist/storage/atomic-file.d.ts +25 -0
  295. package/dist/storage/atomic-file.js +76 -0
  296. package/dist/storage/constants/storage.constants.d.ts +34 -0
  297. package/dist/storage/constants/storage.constants.js +35 -0
  298. package/dist/storage/index.d.ts +10 -0
  299. package/dist/storage/index.js +5 -0
  300. package/dist/storage/install-state.d.ts +20 -0
  301. package/dist/storage/install-state.js +40 -0
  302. package/dist/storage/json-file.d.ts +13 -0
  303. package/dist/storage/json-file.js +31 -0
  304. package/dist/storage/lock.d.ts +15 -0
  305. package/dist/storage/lock.js +70 -0
  306. package/dist/storage/paths.d.ts +14 -0
  307. package/dist/storage/paths.js +42 -0
  308. package/dist/storage/schemas/storage.schema.d.ts +128 -0
  309. package/dist/storage/schemas/storage.schema.js +27 -0
  310. package/dist/storage/types/storage.types.d.ts +36 -0
  311. package/dist/storage/types/storage.types.js +1 -0
  312. package/dist/transport/constants/transport.constants.d.ts +47 -0
  313. package/dist/transport/constants/transport.constants.js +47 -0
  314. package/dist/transport/cooldown.d.ts +35 -0
  315. package/dist/transport/cooldown.js +62 -0
  316. package/dist/transport/delivery-stats.d.ts +65 -0
  317. package/dist/transport/delivery-stats.js +186 -0
  318. package/dist/transport/delivery.d.ts +26 -0
  319. package/dist/transport/delivery.js +80 -0
  320. package/dist/transport/headers.d.ts +12 -0
  321. package/dist/transport/headers.js +19 -0
  322. package/dist/transport/http-transport.d.ts +39 -0
  323. package/dist/transport/http-transport.js +106 -0
  324. package/dist/transport/index.d.ts +13 -0
  325. package/dist/transport/index.js +7 -0
  326. package/dist/transport/queue.d.ts +177 -0
  327. package/dist/transport/queue.js +474 -0
  328. package/dist/transport/schemas/queue.schema.d.ts +30 -0
  329. package/dist/transport/schemas/queue.schema.js +18 -0
  330. package/dist/transport/transport.d.ts +6 -0
  331. package/dist/transport/transport.js +1 -0
  332. package/dist/transport/types/transport.types.d.ts +102 -0
  333. package/dist/transport/types/transport.types.js +1 -0
  334. package/dist/turns/aggregate-usage.d.ts +20 -0
  335. package/dist/turns/aggregate-usage.js +269 -0
  336. package/dist/turns/claude-transcript.d.ts +18 -0
  337. package/dist/turns/claude-transcript.js +80 -0
  338. package/dist/turns/constants/turns.constants.d.ts +69 -0
  339. package/dist/turns/constants/turns.constants.js +86 -0
  340. package/dist/turns/cursor-transcript.d.ts +21 -0
  341. package/dist/turns/cursor-transcript.js +66 -0
  342. package/dist/turns/index.d.ts +17 -0
  343. package/dist/turns/index.js +7 -0
  344. package/dist/turns/transcript.d.ts +74 -0
  345. package/dist/turns/transcript.js +188 -0
  346. package/dist/turns/turn-state.d.ts +94 -0
  347. package/dist/turns/turn-state.js +234 -0
  348. package/dist/turns/turn-summary.d.ts +27 -0
  349. package/dist/turns/turn-summary.js +164 -0
  350. package/dist/turns/turn-tracker.d.ts +14 -0
  351. package/dist/turns/turn-tracker.js +521 -0
  352. package/dist/turns/types/aggregate-usage.types.d.ts +26 -0
  353. package/dist/turns/types/aggregate-usage.types.js +1 -0
  354. package/dist/turns/types/transcript.types.d.ts +41 -0
  355. package/dist/turns/types/transcript.types.js +1 -0
  356. package/dist/turns/types/turn-state.types.d.ts +37 -0
  357. package/dist/turns/types/turn-state.types.js +1 -0
  358. package/dist/turns/types/turn-summary.types.d.ts +106 -0
  359. package/dist/turns/types/turn-summary.types.js +1 -0
  360. package/dist/turns/types/turn-tracker.types.d.ts +27 -0
  361. package/dist/turns/types/turn-tracker.types.js +1 -0
  362. package/example/README.md +43 -0
  363. package/example/server.mjs +240 -0
  364. package/package.json +89 -0
@@ -0,0 +1,269 @@
1
+ import { compact } from '../core/object.js';
2
+ import { sumPresent } from '../core/number.js';
3
+ /**
4
+ * Finalize a turn exclusively from its atomic llm.call ledger.
5
+ *
6
+ * Three rules make the result trustworthy. Calls are deduplicated by
7
+ * (provider, call_id) before summing, so OTLP retries cannot inflate usage. A
8
+ * call is attributed to exactly one turn — by turn id, or by the arbitrated
9
+ * window join — so overlapping turns cannot double-count. And a ledger that
10
+ * matched calls but carries no usage never overwrites provisional transcript
11
+ * totals or claims a completeness it cannot back.
12
+ *
13
+ * @param summary - The turn summary to finalize.
14
+ * @param calls - Ledger rows to consider; may span the whole session.
15
+ * @param options - Terminal signal and the session's other summaries.
16
+ * @returns The finalized summary, or the original when no rows matched.
17
+ */
18
+ export function aggregateTurnUsage(summary, calls, options = {}) {
19
+ const accepted = acceptCalls(summary, calls, options);
20
+ // No matching ledger rows means the turn is not finalized yet. Preserve
21
+ // pending/provisional usage rather than replacing it with an empty total and
22
+ // incorrectly declaring it complete.
23
+ if (accepted.length === 0)
24
+ return summary;
25
+ const totals = sumCalls(accepted);
26
+ const ledgerHasUsage = reportsAnyUsage(totals);
27
+ return compact({
28
+ ...summary,
29
+ // Spread whether or not each field is present: the ledger replaces
30
+ // provisional transcript totals wholesale, so a class the ledger does not
31
+ // report has to be *removed*, not left at its transcript value.
32
+ ...(ledgerHasUsage ? totals : {}),
33
+ llm_calls: accepted.length,
34
+ agent_usage: perAgentUsage(accepted),
35
+ usage_status: resolveUsageStatus(summary.usage_status, ledgerHasUsage, options.complete)
36
+ });
37
+ }
38
+ /**
39
+ * The ledger rows that belong to this turn, deduplicated.
40
+ *
41
+ * @param summary - The turn being finalized.
42
+ * @param calls - Candidate rows.
43
+ * @param options - Session context for the window join.
44
+ * @returns One row per unique call.
45
+ */
46
+ function acceptCalls(summary, calls, options) {
47
+ const unique = new Map();
48
+ for (const call of calls) {
49
+ if (!belongsToTurn(summary, call, options))
50
+ continue;
51
+ const key = `${call.provider}:${call.call_id}`;
52
+ const previous = unique.get(key);
53
+ unique.set(key, previous ? mergeCallObservations(previous, call) : call);
54
+ }
55
+ return [...unique.values()];
56
+ }
57
+ /**
58
+ * Whether one ledger row is this turn's.
59
+ *
60
+ * @param summary - The turn being finalized.
61
+ * @param call - Candidate row.
62
+ * @param options - Session context for the window join.
63
+ * @returns True when the row belongs to this turn.
64
+ */
65
+ function belongsToTurn(summary, call, options) {
66
+ if (summary.session_id && call.session_id !== summary.session_id)
67
+ return false;
68
+ if (summary.turn_id && call.turn_id && call.turn_id !== summary.turn_id)
69
+ return false;
70
+ // Both sides carry the same turn id: an exact match, nothing to arbitrate.
71
+ if (summary.turn_id && call.turn_id)
72
+ return true;
73
+ // Without an exact turn match on both sides (session-only correlation,
74
+ // legacy records) the call joins through the turn's time window; skipping it
75
+ // outright would leave its usage attributed to no turn at all.
76
+ return ownsWindowJoin(summary, call, options.sessionSummaries);
77
+ }
78
+ /**
79
+ * Decide whether `summary` is the turn a window-joined call belongs to.
80
+ *
81
+ * The owner is the containing summary with the latest start — matching the
82
+ * transcript path, which attributes an ambiguous overlap to the newer prompt —
83
+ * and summaries without a lower bound only claim calls no bounded summary
84
+ * contains. Ownership can only be arbitrated across the session's full summary
85
+ * set: a lone summary claiming every call its window contains would
86
+ * double-count overlapping turns, so without `sessionSummaries` the window
87
+ * join is disabled entirely.
88
+ *
89
+ * @param summary - The turn being finalized.
90
+ * @param call - Candidate row.
91
+ * @param sessionSummaries - Every summary of the session.
92
+ * @returns True when this summary owns the call.
93
+ */
94
+ function ownsWindowJoin(summary, call, sessionSummaries) {
95
+ if (!sessionSummaries || sessionSummaries.length === 0)
96
+ return false;
97
+ const callAt = Date.parse(call.ended_at);
98
+ // A call with an unusable timestamp cannot be placed in any window; it can
99
+ // still reach a summary through an exact turn_id match.
100
+ if (!Number.isFinite(callAt))
101
+ return false;
102
+ if (!containsCall(summary, callAt))
103
+ return false;
104
+ const pool = sessionSummaries.some((candidate) => candidate.id === summary.id) ? sessionSummaries : [...sessionSummaries, summary];
105
+ // A call carrying a turn id joins its own turn exactly; it must not also be
106
+ // window-claimed by a summary that lacks one.
107
+ if (call.turn_id && pool.some((candidate) => candidate.turn_id === call.turn_id))
108
+ return false;
109
+ const owner = pool.filter((candidate) => containsCall(candidate, callAt)).sort(compareOwnership)[0];
110
+ return owner !== undefined && owner.id === summary.id;
111
+ }
112
+ /**
113
+ * Whether a call's timestamp falls inside a summary's window.
114
+ *
115
+ * Open lower bound: a summary without started_at contains anything earlier.
116
+ *
117
+ * @param summary - Candidate owner.
118
+ * @param callAt - Call timestamp, epoch ms.
119
+ * @returns True when the window contains it.
120
+ */
121
+ function containsCall(summary, callAt) {
122
+ const endedAt = Date.parse(summary.ended_at);
123
+ if (!Number.isFinite(endedAt) || callAt > endedAt)
124
+ return false;
125
+ const startedAt = summary.started_at ? Date.parse(summary.started_at) : NaN;
126
+ return !Number.isFinite(startedAt) || callAt >= startedAt;
127
+ }
128
+ /**
129
+ * Ordering that puts the best owner of an ambiguous call first.
130
+ *
131
+ * Latest start wins; then the earliest stop; then id, so the outcome is
132
+ * deterministic whatever order the summaries arrived in.
133
+ *
134
+ * @param a - One summary.
135
+ * @param b - The other.
136
+ * @returns Standard comparator result.
137
+ */
138
+ function compareOwnership(a, b) {
139
+ const aStart = a.started_at ? Date.parse(a.started_at) : Number.NEGATIVE_INFINITY;
140
+ const bStart = b.started_at ? Date.parse(b.started_at) : Number.NEGATIVE_INFINITY;
141
+ if (aStart !== bStart)
142
+ return bStart - aStart;
143
+ const aEnd = Date.parse(a.ended_at);
144
+ const bEnd = Date.parse(b.ended_at);
145
+ if (aEnd !== bEnd)
146
+ return aEnd - bEnd;
147
+ return a.id.localeCompare(b.id);
148
+ }
149
+ /**
150
+ * Combine two observations of one request.
151
+ *
152
+ * A request may appear in both an API-request log and a completion log, each
153
+ * carrying part of the picture.
154
+ *
155
+ * @param first - Earlier observation.
156
+ * @param latest - Later observation, which wins per field.
157
+ * @returns The merged row.
158
+ */
159
+ function mergeCallObservations(first, latest) {
160
+ return compact({
161
+ ...first,
162
+ ...latest,
163
+ event: { ...first.event, ...latest.event },
164
+ agent: { ...first.agent, ...latest.agent },
165
+ session: { ...first.session, ...latest.session },
166
+ git: first.git || latest.git ? { ...first.git, ...latest.git } : undefined,
167
+ feature: first.feature || latest.feature ? { ...first.feature, ...latest.feature } : undefined
168
+ });
169
+ }
170
+ /**
171
+ * Usage broken down per agent that took part in the turn.
172
+ *
173
+ * @param calls - Accepted ledger rows.
174
+ * @returns One entry per agent, or undefined when there is nothing to report.
175
+ */
176
+ function perAgentUsage(calls) {
177
+ const groups = new Map();
178
+ for (const call of calls) {
179
+ const key = agentKey(call);
180
+ const group = groups.get(key);
181
+ if (group) {
182
+ group.push(call);
183
+ continue;
184
+ }
185
+ groups.set(key, [call]);
186
+ }
187
+ const usage = [];
188
+ for (const group of groups.values()) {
189
+ const first = group[0];
190
+ usage.push(compact({
191
+ agent_id: first.agent_id,
192
+ parent_agent_id: first.parent_agent_id,
193
+ agent_type: first.agent_type,
194
+ llm_calls: group.length,
195
+ ...sumCalls(group)
196
+ }));
197
+ }
198
+ return usage.length > 0 ? usage : undefined;
199
+ }
200
+ /**
201
+ * Grouping key for per-agent usage: a concrete instance when the provider gave
202
+ * one, else its role, else the unattributed bucket.
203
+ *
204
+ * @param call - Ledger row.
205
+ * @returns The group key.
206
+ */
207
+ function agentKey(call) {
208
+ if (call.agent_id)
209
+ return `id:${call.agent_id}`;
210
+ if (call.agent_type)
211
+ return `type:${call.agent_type}`;
212
+ return 'unattributed';
213
+ }
214
+ /**
215
+ * How settled the turn's usage is after this aggregation.
216
+ *
217
+ * 'complete' requires the caller's explicit terminal signal: a first batch
218
+ * says nothing about whether more are coming.
219
+ *
220
+ * @param current - Status the summary arrived with.
221
+ * @param ledgerHasUsage - Whether the matched rows carried any usage.
222
+ * @param complete - The caller's terminal signal, when it has one.
223
+ * @returns The status to stamp.
224
+ */
225
+ function resolveUsageStatus(current, ledgerHasUsage, complete) {
226
+ if (ledgerHasUsage)
227
+ return complete === true ? 'complete' : 'partial';
228
+ if (complete === false)
229
+ return 'partial';
230
+ return current;
231
+ }
232
+ /**
233
+ * Token and cost totals across a set of calls.
234
+ *
235
+ * Every field is present, undefined when no call reported that class: callers
236
+ * spread this over a summary to replace its usage wholesale, and a missing key
237
+ * would silently leave a stale transcript value in place.
238
+ *
239
+ * @param calls - Ledger rows to sum.
240
+ * @returns The totals, one entry per token class.
241
+ */
242
+ function sumCalls(calls) {
243
+ return {
244
+ input_tokens: sumPresent(calls.map((call) => call.input_tokens)),
245
+ cached_input_tokens: sumPresent(calls.map((call) => call.cached_input_tokens)),
246
+ cache_creation_input_tokens: sumPresent(calls.map((call) => call.cache_creation_input_tokens)),
247
+ output_tokens: sumPresent(calls.map((call) => call.output_tokens)),
248
+ reasoning_output_tokens: sumPresent(calls.map((call) => call.reasoning_output_tokens)),
249
+ total_tokens: sumPresent(calls.map((call) => call.total_tokens)),
250
+ cost_usd: sumPresent(calls.map((call) => call.cost_usd))
251
+ };
252
+ }
253
+ /**
254
+ * Whether the ledger actually carried usage.
255
+ *
256
+ * Matched calls without any token or cost data (failed requests, token-less
257
+ * telemetry) must not erase provisional transcript totals or stamp a
258
+ * completeness the ledger cannot back.
259
+ *
260
+ * @param totals - Summed totals.
261
+ * @returns True when at least one class was reported.
262
+ */
263
+ function reportsAnyUsage(totals) {
264
+ for (const value of Object.values(totals)) {
265
+ if (value !== undefined)
266
+ return true;
267
+ }
268
+ return false;
269
+ }
@@ -0,0 +1,18 @@
1
+ import type { ReadTurnUsageRetry, TurnUsage } from './types/transcript.types.js';
2
+ export type { ReadTurnUsageRetry, TranscriptUsageEntry, TurnUsage } from './types/transcript.types.js';
3
+ /**
4
+ * Authoritative per-turn token usage from Claude Code's transcript JSONL.
5
+ *
6
+ * Sums the usage of assistant messages recorded inside the turn's window,
7
+ * deduplicating by message id — a multi-block message repeats the same usage on
8
+ * every line, and counting those twice would double the turn's cost. Any
9
+ * read or parse problem degrades to "no usage"; it never throws.
10
+ *
11
+ * @param transcriptPath - Path Claude Code reported in the hook payload.
12
+ * @param sinceIso - When the turn started; earlier entries are another turn's.
13
+ * @param retry - How long to wait for the transcript flush to settle.
14
+ * @param untilIso - Upper bound, keeping a racing next prompt's entries out.
15
+ * @param excludeMessageIds - Messages another turn already claimed.
16
+ * @returns The turn's usage, or undefined when the transcript reports none.
17
+ */
18
+ export declare function readTurnUsage(transcriptPath: string, sinceIso: string, retry?: ReadTurnUsageRetry, untilIso?: string, excludeMessageIds?: ReadonlySet<string>): Promise<TurnUsage | undefined>;
@@ -0,0 +1,80 @@
1
+ import { asRecord } from '../core/object.js';
2
+ import { accumulateUsage, messageIdFor, parseJsonLine, readTranscriptTail, readUntilSettled } from './transcript.js';
3
+ /**
4
+ * Authoritative per-turn token usage from Claude Code's transcript JSONL.
5
+ *
6
+ * Sums the usage of assistant messages recorded inside the turn's window,
7
+ * deduplicating by message id — a multi-block message repeats the same usage on
8
+ * every line, and counting those twice would double the turn's cost. Any
9
+ * read or parse problem degrades to "no usage"; it never throws.
10
+ *
11
+ * @param transcriptPath - Path Claude Code reported in the hook payload.
12
+ * @param sinceIso - When the turn started; earlier entries are another turn's.
13
+ * @param retry - How long to wait for the transcript flush to settle.
14
+ * @param untilIso - Upper bound, keeping a racing next prompt's entries out.
15
+ * @param excludeMessageIds - Messages another turn already claimed.
16
+ * @returns The turn's usage, or undefined when the transcript reports none.
17
+ */
18
+ export async function readTurnUsage(transcriptPath, sinceIso, retry, untilIso, excludeMessageIds) {
19
+ return readUntilSettled(() => readOnce(transcriptPath, sinceIso, untilIso, excludeMessageIds), retry);
20
+ }
21
+ /**
22
+ * One pass over the transcript tail.
23
+ *
24
+ * @param transcriptPath - Transcript file.
25
+ * @param sinceIso - Lower bound of the turn's window.
26
+ * @param untilIso - Upper bound, or undefined for "no upper bound".
27
+ * @param excludeMessageIds - Messages another turn already claimed.
28
+ * @returns The usage found in this pass.
29
+ */
30
+ async function readOnce(transcriptPath, sinceIso, untilIso, excludeMessageIds) {
31
+ const since = Date.parse(sinceIso);
32
+ if (Number.isNaN(since))
33
+ return undefined;
34
+ // Entries after `until` belong to the next prompt racing into the same file.
35
+ // A late FLUSH of *this* turn's entry still passes, because its own message
36
+ // timestamp predates the Stop.
37
+ const until = untilIso === undefined ? Number.POSITIVE_INFINITY : Date.parse(untilIso);
38
+ if (Number.isNaN(until))
39
+ return undefined;
40
+ const raw = await readTranscriptTail(transcriptPath);
41
+ if (raw === undefined)
42
+ return undefined;
43
+ const byMessageId = new Map();
44
+ for (const line of raw.split('\n')) {
45
+ if (!line.trim())
46
+ continue;
47
+ const entry = assistantUsageEntry(line, since, until, excludeMessageIds);
48
+ if (entry)
49
+ byMessageId.set(entry.id, entry.value);
50
+ }
51
+ return accumulateUsage(byMessageId);
52
+ }
53
+ /**
54
+ * The usage of one transcript line, when it is an assistant message inside the
55
+ * window that no other turn has claimed.
56
+ *
57
+ * @param line - Verbatim JSONL line.
58
+ * @param since - Window lower bound, epoch ms.
59
+ * @param until - Window upper bound, epoch ms.
60
+ * @param excludeMessageIds - Messages another turn already claimed.
61
+ * @returns The entry, or undefined when the line does not qualify.
62
+ */
63
+ function assistantUsageEntry(line, since, until, excludeMessageIds) {
64
+ const entry = parseJsonLine(line);
65
+ if (!entry || entry['type'] !== 'assistant')
66
+ return undefined;
67
+ const timestamp = typeof entry['timestamp'] === 'string' ? Date.parse(entry['timestamp']) : NaN;
68
+ if (Number.isNaN(timestamp) || timestamp < since || timestamp > until)
69
+ return undefined;
70
+ const message = asRecord(entry['message']);
71
+ const usage = asRecord(message?.['usage']);
72
+ if (!usage)
73
+ return undefined;
74
+ const rawId = typeof message?.['id'] === 'string' ? message['id'] : undefined;
75
+ const id = messageIdFor(rawId, line);
76
+ if (excludeMessageIds?.has(id))
77
+ return undefined;
78
+ const model = typeof message?.['model'] === 'string' ? message['model'] : undefined;
79
+ return { id, value: { model, usage } };
80
+ }
@@ -0,0 +1,69 @@
1
+ import type { ReadTurnUsageRetry } from '../types/transcript.types.js';
2
+ /** Canonical event types that mean "a tool finished doing something". */
3
+ export declare const TOOL_COMPLETION_TYPES: ReadonlySet<string>;
4
+ /** Orphaned turn state (a crash without Stop/SessionEnd) is deleted after this. */
5
+ export declare const TURN_STATE_TTL_MS: number;
6
+ /** Overlapping Stop hooks serialize only transcript usage allocation. */
7
+ export declare const USAGE_LOCK_WAIT_MS = 5000;
8
+ export declare const USAGE_LOCK_POLL_MS = 25;
9
+ /**
10
+ * Stop can fire before the agent flushes its final assistant entry to the
11
+ * transcript, so the reader keeps looking. The settle window guards multi-tool
12
+ * turns, where early usage entries look stable long before the last one lands.
13
+ */
14
+ export declare const USAGE_RETRY: ReadTurnUsageRetry;
15
+ /**
16
+ * Only the tail of a transcript is read: the turn's entries are at the end of
17
+ * the JSONL and the retry loop re-reads the file several times per Stop, so
18
+ * parsing tens of megabytes each pass would be pure waste on long sessions.
19
+ */
20
+ export declare const TRANSCRIPT_TAIL_BYTES: number;
21
+ /** Payload key every supported agent reports its transcript path under. */
22
+ export declare const TRANSCRIPT_PATH_KEY = "transcript_path";
23
+ /** Prefix distinguishing usage-claim files from turn records in a session dir. */
24
+ export declare const USAGE_CLAIM_PREFIX = "usage-claim--";
25
+ /** Public provider labels; the internal id is an implementation detail. */
26
+ export declare const PROVIDER_LABELS: Readonly<Record<string, string>>;
27
+ /** Providers whose sessions run inside an editor rather than a terminal. */
28
+ export declare const IDE_SURFACE_PROVIDERS: ReadonlySet<string>;
29
+ /** Claude Code reports its own surface here. */
30
+ export declare const CLAUDE_ENTRYPOINT_VAR = "CLAUDE_CODE_ENTRYPOINT";
31
+ export declare const DEFAULT_SURFACE = "cli";
32
+ export declare const IDE_SURFACE = "ide";
33
+ /** Separator between several prompts collapsed into one turn. */
34
+ export declare const PROMPT_JOIN_SEPARATOR = "\n---\n";
35
+ /**
36
+ * Cap on `files_touched` and `files_read`, matching the platform's own limit on
37
+ * either list.
38
+ *
39
+ * This is a delivery guarantee, not a payload-size preference. The backend
40
+ * validates the whole summary against one schema: a list one entry over its
41
+ * bound fails that schema, the batch answers 422, and 422 is not retryable —
42
+ * so an exploratory turn that read 501 files used to lose its tokens, its cost
43
+ * and its ticket keys along with the file list. A long turn's file list is
44
+ * truncated instead; that is a truncated list, not a lost turn.
45
+ */
46
+ export declare const MAX_TURN_FILES = 500;
47
+ /** Fallback tool name for a call the provider did not name. */
48
+ export declare const UNKNOWN_TOOL_NAME = "unknown";
49
+ /** Metadata keys the tracker reads off canonical events. */
50
+ export declare const PROMPT_TEXT_KEY = "promptText";
51
+ export declare const PROMPT_EVIDENCE_KEY = "prompt";
52
+ export declare const RESPONSE_TEXT_KEY = "responseText";
53
+ export declare const RESPONSE_EVIDENCE_KEY = "response";
54
+ export declare const FILE_PATH_KEY = "filePath";
55
+ /** Length of the hashed session directory name. */
56
+ export declare const SESSION_DIR_HASH_LENGTH = 32;
57
+ /** Length of the hashed lock names, which must be filesystem-safe. */
58
+ export declare const LOCK_KEY_HASH_LENGTH = 16;
59
+ /** Characters unsafe in a per-record filename. */
60
+ export declare const RE_UNSAFE_NAME_CHARS: RegExp;
61
+ /** Transcript usage field names, as the agents write them. */
62
+ export declare const TRANSCRIPT_INPUT_TOKENS = "input_tokens";
63
+ export declare const TRANSCRIPT_OUTPUT_TOKENS = "output_tokens";
64
+ export declare const TRANSCRIPT_CACHE_READ_TOKENS = "cache_read_input_tokens";
65
+ export declare const TRANSCRIPT_CACHE_CREATION_TOKENS = "cache_creation_input_tokens";
66
+ /** Every transcript token field, for weighting which model dominated a turn. */
67
+ export declare const TRANSCRIPT_TOKEN_FIELDS: readonly ["input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"];
68
+ /** Prefix for the content-hash id given to a transcript entry without one. */
69
+ export declare const ANONYMOUS_MESSAGE_ID_PREFIX = "anon-";
@@ -0,0 +1,86 @@
1
+ /** Canonical event types that mean "a tool finished doing something". */
2
+ export const TOOL_COMPLETION_TYPES = new Set([
3
+ 'tool.completed',
4
+ 'tool.failed',
5
+ 'shell.completed',
6
+ 'mcp.completed',
7
+ 'file.read',
8
+ 'file.edited'
9
+ ]);
10
+ /** Orphaned turn state (a crash without Stop/SessionEnd) is deleted after this. */
11
+ export const TURN_STATE_TTL_MS = 24 * 60 * 60 * 1000;
12
+ /** Overlapping Stop hooks serialize only transcript usage allocation. */
13
+ export const USAGE_LOCK_WAIT_MS = 5_000;
14
+ export const USAGE_LOCK_POLL_MS = 25;
15
+ /**
16
+ * Stop can fire before the agent flushes its final assistant entry to the
17
+ * transcript, so the reader keeps looking. The settle window guards multi-tool
18
+ * turns, where early usage entries look stable long before the last one lands.
19
+ */
20
+ export const USAGE_RETRY = { attempts: 6, delayMs: 250, minSettleMs: 500 };
21
+ /**
22
+ * Only the tail of a transcript is read: the turn's entries are at the end of
23
+ * the JSONL and the retry loop re-reads the file several times per Stop, so
24
+ * parsing tens of megabytes each pass would be pure waste on long sessions.
25
+ */
26
+ export const TRANSCRIPT_TAIL_BYTES = 4 * 1024 * 1024;
27
+ /** Payload key every supported agent reports its transcript path under. */
28
+ export const TRANSCRIPT_PATH_KEY = 'transcript_path';
29
+ /** Prefix distinguishing usage-claim files from turn records in a session dir. */
30
+ export const USAGE_CLAIM_PREFIX = 'usage-claim--';
31
+ /** Public provider labels; the internal id is an implementation detail. */
32
+ export const PROVIDER_LABELS = {
33
+ claude: 'claude-code',
34
+ codex: 'codex',
35
+ cursor: 'cursor',
36
+ gemini: 'gemini',
37
+ antigravity: 'antigravity'
38
+ };
39
+ /** Providers whose sessions run inside an editor rather than a terminal. */
40
+ export const IDE_SURFACE_PROVIDERS = new Set(['cursor', 'antigravity']);
41
+ /** Claude Code reports its own surface here. */
42
+ export const CLAUDE_ENTRYPOINT_VAR = 'CLAUDE_CODE_ENTRYPOINT';
43
+ export const DEFAULT_SURFACE = 'cli';
44
+ export const IDE_SURFACE = 'ide';
45
+ /** Separator between several prompts collapsed into one turn. */
46
+ export const PROMPT_JOIN_SEPARATOR = '\n---\n';
47
+ /**
48
+ * Cap on `files_touched` and `files_read`, matching the platform's own limit on
49
+ * either list.
50
+ *
51
+ * This is a delivery guarantee, not a payload-size preference. The backend
52
+ * validates the whole summary against one schema: a list one entry over its
53
+ * bound fails that schema, the batch answers 422, and 422 is not retryable —
54
+ * so an exploratory turn that read 501 files used to lose its tokens, its cost
55
+ * and its ticket keys along with the file list. A long turn's file list is
56
+ * truncated instead; that is a truncated list, not a lost turn.
57
+ */
58
+ export const MAX_TURN_FILES = 500;
59
+ /** Fallback tool name for a call the provider did not name. */
60
+ export const UNKNOWN_TOOL_NAME = 'unknown';
61
+ /** Metadata keys the tracker reads off canonical events. */
62
+ export const PROMPT_TEXT_KEY = 'promptText';
63
+ export const PROMPT_EVIDENCE_KEY = 'prompt';
64
+ export const RESPONSE_TEXT_KEY = 'responseText';
65
+ export const RESPONSE_EVIDENCE_KEY = 'response';
66
+ export const FILE_PATH_KEY = 'filePath';
67
+ /** Length of the hashed session directory name. */
68
+ export const SESSION_DIR_HASH_LENGTH = 32;
69
+ /** Length of the hashed lock names, which must be filesystem-safe. */
70
+ export const LOCK_KEY_HASH_LENGTH = 16;
71
+ /** Characters unsafe in a per-record filename. */
72
+ export const RE_UNSAFE_NAME_CHARS = /[^A-Za-z0-9._-]/g;
73
+ /** Transcript usage field names, as the agents write them. */
74
+ export const TRANSCRIPT_INPUT_TOKENS = 'input_tokens';
75
+ export const TRANSCRIPT_OUTPUT_TOKENS = 'output_tokens';
76
+ export const TRANSCRIPT_CACHE_READ_TOKENS = 'cache_read_input_tokens';
77
+ export const TRANSCRIPT_CACHE_CREATION_TOKENS = 'cache_creation_input_tokens';
78
+ /** Every transcript token field, for weighting which model dominated a turn. */
79
+ export const TRANSCRIPT_TOKEN_FIELDS = [
80
+ TRANSCRIPT_INPUT_TOKENS,
81
+ TRANSCRIPT_OUTPUT_TOKENS,
82
+ TRANSCRIPT_CACHE_READ_TOKENS,
83
+ TRANSCRIPT_CACHE_CREATION_TOKENS
84
+ ];
85
+ /** Prefix for the content-hash id given to a transcript entry without one. */
86
+ export const ANONYMOUS_MESSAGE_ID_PREFIX = 'anon-';
@@ -0,0 +1,21 @@
1
+ import type { ReadTurnUsageRetry, TurnUsage } from './types/transcript.types.js';
2
+ /**
3
+ * Forward-compatible token usage from Cursor's transcript JSONL.
4
+ *
5
+ * Today (verified 2026-08) Cursor transcript rows carry only role/message with
6
+ * tool_use blocks — no usage, no timestamps, no message ids — so this reader
7
+ * returns undefined and Cursor turn summaries stay usage_status=pending. Cursor
8
+ * has logged the enrichment request; the parser already accepts `usage` and
9
+ * `message.usage` objects with Anthropic-style token fields, so tokens will
10
+ * appear here without a code change once the format grows them.
11
+ *
12
+ * Rows have no timestamps, so unlike the Claude reader there is no time window:
13
+ * a turn claims every not-yet-claimed usage row, and exactly-once attribution
14
+ * rests entirely on the persisted message-id ledger.
15
+ *
16
+ * @param transcriptPath - Path Cursor reported in the hook payload.
17
+ * @param retry - How long to wait for the transcript flush to settle.
18
+ * @param excludeMessageIds - Rows another turn already claimed.
19
+ * @returns The turn's usage, or undefined while the format carries none.
20
+ */
21
+ export declare function readCursorTurnUsage(transcriptPath: string, retry?: ReadTurnUsageRetry, excludeMessageIds?: ReadonlySet<string>): Promise<TurnUsage | undefined>;
@@ -0,0 +1,66 @@
1
+ import { asRecord, firstStringOf } from '../core/object.js';
2
+ import { accumulateUsage, messageIdFor, parseJsonLine, readTranscriptTail, readUntilSettled } from './transcript.js';
3
+ /**
4
+ * Forward-compatible token usage from Cursor's transcript JSONL.
5
+ *
6
+ * Today (verified 2026-08) Cursor transcript rows carry only role/message with
7
+ * tool_use blocks — no usage, no timestamps, no message ids — so this reader
8
+ * returns undefined and Cursor turn summaries stay usage_status=pending. Cursor
9
+ * has logged the enrichment request; the parser already accepts `usage` and
10
+ * `message.usage` objects with Anthropic-style token fields, so tokens will
11
+ * appear here without a code change once the format grows them.
12
+ *
13
+ * Rows have no timestamps, so unlike the Claude reader there is no time window:
14
+ * a turn claims every not-yet-claimed usage row, and exactly-once attribution
15
+ * rests entirely on the persisted message-id ledger.
16
+ *
17
+ * @param transcriptPath - Path Cursor reported in the hook payload.
18
+ * @param retry - How long to wait for the transcript flush to settle.
19
+ * @param excludeMessageIds - Rows another turn already claimed.
20
+ * @returns The turn's usage, or undefined while the format carries none.
21
+ */
22
+ export async function readCursorTurnUsage(transcriptPath, retry, excludeMessageIds) {
23
+ return readUntilSettled(() => readOnce(transcriptPath, excludeMessageIds), retry, { bailOnFirstEmpty: true });
24
+ }
25
+ /**
26
+ * One pass over the transcript tail.
27
+ *
28
+ * @param transcriptPath - Transcript file.
29
+ * @param excludeMessageIds - Rows another turn already claimed.
30
+ * @returns The usage found in this pass.
31
+ */
32
+ async function readOnce(transcriptPath, excludeMessageIds) {
33
+ const raw = await readTranscriptTail(transcriptPath);
34
+ if (raw === undefined)
35
+ return undefined;
36
+ const byMessageId = new Map();
37
+ for (const line of raw.split('\n')) {
38
+ if (!line.trim())
39
+ continue;
40
+ const entry = usageRow(line, excludeMessageIds);
41
+ if (entry)
42
+ byMessageId.set(entry.id, entry.value);
43
+ }
44
+ return accumulateUsage(byMessageId);
45
+ }
46
+ /**
47
+ * The usage of one transcript row, when it reports any and no other turn has
48
+ * claimed it.
49
+ *
50
+ * @param line - Verbatim JSONL line.
51
+ * @param excludeMessageIds - Rows another turn already claimed.
52
+ * @returns The entry, or undefined when the row carries no usage.
53
+ */
54
+ function usageRow(line, excludeMessageIds) {
55
+ const entry = parseJsonLine(line);
56
+ if (!entry)
57
+ return undefined;
58
+ const message = asRecord(entry['message']);
59
+ const usage = asRecord(entry['usage']) ?? asRecord(message?.['usage']);
60
+ if (!usage)
61
+ return undefined;
62
+ const id = messageIdFor(firstStringOf(message?.['id'], entry['id'], entry['message_id']), line);
63
+ if (excludeMessageIds?.has(id))
64
+ return undefined;
65
+ return { id, value: { model: firstStringOf(message?.['model'], entry['model']), usage } };
66
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Turn assembly: lifecycle events accumulate into per-session state, a Stop
3
+ * closes the turn into one flat summary, and the backend finalizes its usage
4
+ * from the atomic llm.call ledger.
5
+ */
6
+ export type { AgentUsageSummary, BuildTurnSummaryInput, TouchedFiles, TurnResponse, TurnSummaryEvent, TurnUsageStatus } from './types/turn-summary.types.js';
7
+ export type { PromptRecord, ResponseRecord, ToolRecord, TurnRecord, TurnStateEntry } from './types/turn-state.types.js';
8
+ export type { ReadTurnUsageRetry, TranscriptReader, TranscriptUsageEntry, TurnUsage } from './types/transcript.types.js';
9
+ export type { TrackTurnOptions, TurnWindow } from './types/turn-tracker.types.js';
10
+ export type { AggregateTurnUsageOptions, UsageTotals } from './types/aggregate-usage.types.js';
11
+ export { PROVIDER_LABELS, TURN_STATE_TTL_MS, USAGE_RETRY } from './constants/turns.constants.js';
12
+ export { alignContentEvidence, buildTurnSummary } from './turn-summary.js';
13
+ export { TurnStateStore } from './turn-state.js';
14
+ export { readTurnUsage } from './claude-transcript.js';
15
+ export { readCursorTurnUsage } from './cursor-transcript.js';
16
+ export { trackTurn } from './turn-tracker.js';
17
+ export { aggregateTurnUsage } from './aggregate-usage.js';
@@ -0,0 +1,7 @@
1
+ export { PROVIDER_LABELS, TURN_STATE_TTL_MS, USAGE_RETRY } from './constants/turns.constants.js';
2
+ export { alignContentEvidence, buildTurnSummary } from './turn-summary.js';
3
+ export { TurnStateStore } from './turn-state.js';
4
+ export { readTurnUsage } from './claude-transcript.js';
5
+ export { readCursorTurnUsage } from './cursor-transcript.js';
6
+ export { trackTurn } from './turn-tracker.js';
7
+ export { aggregateTurnUsage } from './aggregate-usage.js';