@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,521 @@
1
+ import { pollUntil } from '../core/async.js';
2
+ import { debugLog } from '../core/logger.js';
3
+ import { asRecord } from '../core/object.js';
4
+ import { detectBillingMode } from '../billing/billing-mode.js';
5
+ import { sha256Hex } from '../events/event-id.js';
6
+ import { developerIdentity } from '../git/git-context.js';
7
+ import { sanitizeValue } from '../privacy/sanitizer.js';
8
+ import { acquireLock } from '../storage/lock.js';
9
+ import { readTurnUsage } from './claude-transcript.js';
10
+ import { readCursorTurnUsage } from './cursor-transcript.js';
11
+ import { CLAUDE_ENTRYPOINT_VAR, DEFAULT_SURFACE, FILE_PATH_KEY, IDE_SURFACE, IDE_SURFACE_PROVIDERS, LOCK_KEY_HASH_LENGTH, PROMPT_EVIDENCE_KEY, PROMPT_TEXT_KEY, RESPONSE_EVIDENCE_KEY, RESPONSE_TEXT_KEY, TOOL_COMPLETION_TYPES, TRANSCRIPT_PATH_KEY, TURN_STATE_TTL_MS, USAGE_LOCK_POLL_MS, USAGE_LOCK_WAIT_MS, USAGE_RETRY } from './constants/turns.constants.js';
12
+ import { TurnStateStore } from './turn-state.js';
13
+ import { alignContentEvidence, buildTurnSummary } from './turn-summary.js';
14
+ /**
15
+ * Providers whose transcript can be read for token usage.
16
+ *
17
+ * Claude windows by message timestamps; Cursor rows carry none, so its reader
18
+ * relies solely on the exactly-once message-id ledger (today Cursor rows also
19
+ * carry no usage — the reader returns undefined and the summary stays pending).
20
+ */
21
+ const TRANSCRIPT_READERS = {
22
+ claude: (transcriptPath, startedAt, untilIso, excludeMessageIds) => readTurnUsage(transcriptPath, startedAt, USAGE_RETRY, untilIso, excludeMessageIds),
23
+ cursor: (transcriptPath, _startedAt, _untilIso, excludeMessageIds) => readCursorTurnUsage(transcriptPath, USAGE_RETRY, excludeMessageIds)
24
+ };
25
+ /**
26
+ * Accumulate turn state across hook invocations and close the turn on
27
+ * `generation.completed`, producing one flat summary.
28
+ *
29
+ * Best-effort by design: hooks run inside the coding agent, so every failure
30
+ * path here ends in "no summary" or a degraded one, never in a thrown error.
31
+ *
32
+ * @param options - The payload's events, config, paths and clock.
33
+ * @returns The turn summary when this payload closed a turn.
34
+ */
35
+ export async function trackTurn(options) {
36
+ const store = new TurnStateStore(options.turnsDir);
37
+ let summary;
38
+ for (const event of options.events) {
39
+ const sessionId = event.session.id;
40
+ if (!sessionId)
41
+ continue;
42
+ try {
43
+ summary = (await processEvent(store, sessionId, event, options)) ?? summary;
44
+ }
45
+ catch (error) {
46
+ debugLog('turn tracking failed:', error);
47
+ // Closing failed (corrupt turn state, unreadable transcript, IO error):
48
+ // the turn must still reach the backend rather than silently vanish.
49
+ if (event.event.type === 'generation.completed' && !summary) {
50
+ summary = fallbackSummary(sessionId, event, options);
51
+ }
52
+ }
53
+ }
54
+ return summary;
55
+ }
56
+ /**
57
+ * Apply one canonical event to the accumulator.
58
+ *
59
+ * @param store - Per-session state store.
60
+ * @param sessionId - Provider session id.
61
+ * @param event - The event to apply.
62
+ * @param options - Tracking options.
63
+ * @returns A summary when this event closed a turn.
64
+ */
65
+ async function processEvent(store, sessionId, event, options) {
66
+ const type = event.event.type;
67
+ // A dry run previews the close and touches nothing: no appends, no consumed
68
+ // records, no usage claims, no sweep.
69
+ if (options.readOnly) {
70
+ if (type !== 'generation.completed')
71
+ return undefined;
72
+ return closeTurnLocked(store, sessionId, event, options, true);
73
+ }
74
+ const record = recordFor(event);
75
+ if (record)
76
+ await store.append(sessionId, recordKeyFor(event), record);
77
+ if (type === 'generation.completed') {
78
+ const summary = await closeTurn(store, sessionId, event, options);
79
+ await store.sweep(TURN_STATE_TTL_MS);
80
+ return summary;
81
+ }
82
+ if (type === 'session.ended') {
83
+ await store.clear(sessionId);
84
+ await store.sweep(TURN_STATE_TTL_MS);
85
+ }
86
+ return undefined;
87
+ }
88
+ /**
89
+ * The turn record one event should be persisted as, if any.
90
+ *
91
+ * @param event - Canonical event.
92
+ * @returns The record, or undefined when the event carries no turn state.
93
+ */
94
+ function recordFor(event) {
95
+ const type = event.event.type;
96
+ if (type === 'prompt.submitted')
97
+ return promptRecord(event);
98
+ if (TOOL_COMPLETION_TYPES.has(type))
99
+ return toolRecord(event);
100
+ // Cursor delivers the response text in its own hook (afterAgentResponse)
101
+ // instead of on Stop; keep it as turn state until the turn closes.
102
+ if (type === 'agent.other' && responseFrom(event) !== undefined)
103
+ return responseRecord(event);
104
+ return undefined;
105
+ }
106
+ /**
107
+ * Filename an event's record is stored under.
108
+ *
109
+ * Event ids are payload-derived, so on old Claude versions without a prompt id
110
+ * two identical prompts share one id. Without a turn id the record file must
111
+ * therefore be distinct per submission, or the second append overwrites the
112
+ * first and the second turn closes with no state at all. With a turn id the id
113
+ * already separates turns, and collapsing repeats inside one turn is exactly
114
+ * right: Antigravity has no prompt hook, so the prompt is recorded from the
115
+ * execution's first invocation and a re-fired invocation must not append it
116
+ * twice.
117
+ *
118
+ * @param event - Canonical event.
119
+ * @returns The record key.
120
+ */
121
+ function recordKeyFor(event) {
122
+ if (event.event.type === 'prompt.submitted' && event.session.turnId)
123
+ return event.id;
124
+ if (event.event.type === 'prompt.submitted' || event.event.type === 'agent.other') {
125
+ return `${event.id}-${event.timestamp}`;
126
+ }
127
+ return event.id;
128
+ }
129
+ /**
130
+ * Close a turn under a per-turn lock.
131
+ *
132
+ * Claude can fire duplicate Stops, and two unserialized closers would read the
133
+ * same snapshot and emit the summary twice. Keyed by session+turn so different
134
+ * prompts of one session still close independently.
135
+ *
136
+ * @param store - Per-session state store.
137
+ * @param sessionId - Provider session id.
138
+ * @param stopEvent - The closing event.
139
+ * @param options - Tracking options.
140
+ * @returns The summary, or undefined when another closer holds the lock.
141
+ */
142
+ async function closeTurn(store, sessionId, stopEvent, options) {
143
+ const lockKey = sha256Hex(`${sessionId}::${stopEvent.session.turnId ?? ''}`).slice(0, LOCK_KEY_HASH_LENGTH);
144
+ const release = await acquireLock(options.locksDir, `turn-close-${lockKey}`, options.env.now);
145
+ if (!release)
146
+ return undefined;
147
+ try {
148
+ return await closeTurnLocked(store, sessionId, stopEvent, options);
149
+ }
150
+ finally {
151
+ await release();
152
+ }
153
+ }
154
+ /**
155
+ * Build the summary for a closing turn.
156
+ *
157
+ * Reads as the sequence it is: pick this turn's records, work out the usage
158
+ * window, claim transcript usage, re-collect what landed while we waited, then
159
+ * flatten it all into one summary.
160
+ *
161
+ * @param store - Per-session state store.
162
+ * @param sessionId - Provider session id.
163
+ * @param stopEvent - The closing event.
164
+ * @param options - Tracking options.
165
+ * @param readOnly - Preview only: consume and claim nothing.
166
+ * @returns The summary, or undefined when there is nothing to summarize.
167
+ */
168
+ async function closeTurnLocked(store, sessionId, stopEvent, options, readOnly = false) {
169
+ const stopTurnId = stopEvent.session.turnId;
170
+ // Consume only this prompt's records: a racing next prompt keeps its state
171
+ // for its own Stop. Records without a turn id are legacy and belong to any
172
+ // Stop. Nothing to summarize (a repeated Stop after a stop hook continued
173
+ // the turn) means no empty duplicate.
174
+ const all = await store.collectEntries(sessionId);
175
+ const firstPass = filterTurn(all, stopTurnId);
176
+ if (firstPass.length === 0)
177
+ return undefined;
178
+ const window = resolveWindow(all, firstPass, stopEvent.timestamp);
179
+ const usage = await resolveAndClaimUsage(store, sessionId, stopEvent, options, window, readOnly);
180
+ const billingMode = await detectBillingMode(options.agentId, options.env);
181
+ // Re-collect after the settle wait: a tool completion that landed while we
182
+ // watched the transcript still belongs to this turn.
183
+ const mine = filterTurn(await store.collectEntries(sessionId), stopTurnId);
184
+ const records = mine.map((entry) => entry.record);
185
+ // Usage is mirrored onto a *copy* of the Stop event: the summary's model
186
+ // should come from the transcript when the transcript knows better, and
187
+ // rewriting an event another stage may still be reading is not an option.
188
+ const resolvedStop = withResolvedUsage(stopEvent, usage, billingMode);
189
+ const summary = buildTurnSummary({
190
+ provider: stopEvent.agent.provider,
191
+ surface: resolveSurface(stopEvent.agent.provider, options.env),
192
+ sessionId,
193
+ turnId: stopTurnId,
194
+ developerId: await developerIdentity(options.config.developerEmail, options.cwd, { home: options.env.home }),
195
+ installationId: options.config.installationId,
196
+ git: stopEvent.git,
197
+ featureCandidates: stopEvent.feature?.candidates,
198
+ prompts: recordsOfKind(records, 'prompt'),
199
+ tools: recordsOfKind(records, 'tool'),
200
+ response: resolveResponse(stopEvent, records),
201
+ usage,
202
+ model: resolvedStop.ai?.model,
203
+ billingMode,
204
+ endedAt: stopEvent.timestamp
205
+ });
206
+ // Consume exactly what went into the summary; other prompts' records stay.
207
+ if (!readOnly)
208
+ await store.remove(mine.map((entry) => entry.file));
209
+ return alignContentEvidence(sanitizeValue(summary));
210
+ }
211
+ /**
212
+ * Degraded close: a summary built from the Stop event alone.
213
+ *
214
+ * No prompts, tools, or transcript usage, and it stays `pending` so the backend
215
+ * finalizes usage from the llm.call ledger — via the turn id when present, else
216
+ * the session-wide ownership join. A thin record beats a missing turn.
217
+ *
218
+ * @param sessionId - Provider session id.
219
+ * @param stopEvent - The closing event.
220
+ * @param options - Tracking options.
221
+ * @returns The degraded summary, or undefined when even that failed.
222
+ */
223
+ function fallbackSummary(sessionId, stopEvent, options) {
224
+ try {
225
+ const summary = buildTurnSummary({
226
+ provider: stopEvent.agent.provider,
227
+ surface: resolveSurface(stopEvent.agent.provider, options.env),
228
+ sessionId,
229
+ turnId: stopEvent.session.turnId,
230
+ developerId: options.config.developerEmail,
231
+ installationId: options.config.installationId,
232
+ git: stopEvent.git,
233
+ featureCandidates: stopEvent.feature?.candidates,
234
+ prompts: [],
235
+ tools: [],
236
+ response: responseFrom(stopEvent),
237
+ model: stopEvent.ai?.model,
238
+ endedAt: stopEvent.timestamp
239
+ });
240
+ return alignContentEvidence(sanitizeValue(summary));
241
+ }
242
+ catch (error) {
243
+ debugLog('fallback turn summary failed:', error);
244
+ return undefined;
245
+ }
246
+ }
247
+ /**
248
+ * The window this turn may claim transcript usage from.
249
+ *
250
+ * Transcript entries carry no prompt id, so if another prompt started inside
251
+ * our window every entry after its start is ambiguous. The window is cut
252
+ * there: those tokens belong to — and are counted by — the other turn, which is
253
+ * what keeps attribution exactly-once instead of doubled.
254
+ *
255
+ * @param all - Every record of the session.
256
+ * @param mine - This turn's records.
257
+ * @param stopAt - Timestamp of the closing event.
258
+ * @returns The window bounds.
259
+ */
260
+ function resolveWindow(all, mine, stopAt) {
261
+ const startedAt = mine.find(({ record }) => record.kind === 'prompt')?.record.at;
262
+ if (startedAt === undefined)
263
+ return { startedAt, untilIso: stopAt };
264
+ const mineSet = new Set(mine);
265
+ let nextPromptAt;
266
+ for (const entry of all) {
267
+ if (mineSet.has(entry) || entry.record.kind !== 'prompt' || entry.record.at <= startedAt)
268
+ continue;
269
+ if (nextPromptAt === undefined || entry.record.at < nextPromptAt)
270
+ nextPromptAt = entry.record.at;
271
+ }
272
+ const untilIso = nextPromptAt !== undefined && nextPromptAt < stopAt ? nextPromptAt : stopAt;
273
+ return { startedAt, untilIso };
274
+ }
275
+ /**
276
+ * Read transcript usage for this turn and persist the claim.
277
+ *
278
+ * Per-turn close locks prevent duplicate Stops for one prompt, but *different*
279
+ * prompts close concurrently. The session usage lock therefore covers the whole
280
+ * read-claims → read-transcript → persist-claim transaction. When the bounded
281
+ * wait expires the transcript usage is omitted rather than risking double
282
+ * attribution; native OTel remains authoritative either way.
283
+ *
284
+ * @param store - Per-session state store.
285
+ * @param sessionId - Provider session id.
286
+ * @param stopEvent - The closing event.
287
+ * @param options - Tracking options.
288
+ * @param window - Bounds this turn may claim from.
289
+ * @param readOnly - Preview only: read claims but never write one.
290
+ * @returns The usage, or undefined when none could be claimed.
291
+ */
292
+ async function resolveAndClaimUsage(store, sessionId, stopEvent, options, window, readOnly) {
293
+ if (!TRANSCRIPT_READERS[options.agentId] || window.startedAt === undefined)
294
+ return undefined;
295
+ if (readOnly) {
296
+ return readTranscriptUsage(options, window, await store.claimedMessageIds(sessionId));
297
+ }
298
+ const lockName = `turn-usage-${sha256Hex(sessionId).slice(0, LOCK_KEY_HASH_LENGTH)}`;
299
+ const release = await waitForUsageLock(options, lockName);
300
+ if (!release) {
301
+ debugLog('turn usage lock timed out; omitting transcript usage');
302
+ return undefined;
303
+ }
304
+ try {
305
+ const claimed = await store.claimedMessageIds(sessionId);
306
+ const usage = await readTranscriptUsage(options, window, claimed);
307
+ if (usage?.messageIds && usage.messageIds.length > 0) {
308
+ // Old Claude versions have no prompt id; the Stop event id still gives
309
+ // every completed turn a distinct ledger file.
310
+ await store.claimUsage(sessionId, stopEvent.session.turnId ?? stopEvent.id, usage.messageIds);
311
+ }
312
+ return usage;
313
+ }
314
+ finally {
315
+ await release();
316
+ }
317
+ }
318
+ /**
319
+ * Acquire the session usage lock, waiting a bounded time.
320
+ *
321
+ * @param options - Tracking options supplying the locks directory and clock.
322
+ * @param lockName - Session-scoped lock name.
323
+ * @returns The release function, or undefined on timeout.
324
+ */
325
+ function waitForUsageLock(options, lockName) {
326
+ return pollUntil(() => acquireLock(options.locksDir, lockName, options.env.now), USAGE_LOCK_WAIT_MS, USAGE_LOCK_POLL_MS);
327
+ }
328
+ /**
329
+ * Run this provider's transcript reader over the turn's window.
330
+ *
331
+ * @param options - Tracking options carrying the raw payload.
332
+ * @param window - Bounds this turn may claim from.
333
+ * @param excludeMessageIds - Messages other turns already claimed.
334
+ * @returns The usage, or undefined when the provider reports none.
335
+ */
336
+ async function readTranscriptUsage(options, window, excludeMessageIds) {
337
+ const reader = TRANSCRIPT_READERS[options.agentId];
338
+ const transcriptPath = asRecord(options.rawPayload)?.[TRANSCRIPT_PATH_KEY];
339
+ if (!reader || window.startedAt === undefined || typeof transcriptPath !== 'string')
340
+ return undefined;
341
+ return reader(transcriptPath, window.startedAt, window.untilIso, excludeMessageIds);
342
+ }
343
+ /**
344
+ * The records of one kind, narrowed.
345
+ *
346
+ * @param records - Every record of the turn.
347
+ * @param kind - Kind to keep.
348
+ * @returns The matching records, in order.
349
+ */
350
+ function recordsOfKind(records, kind) {
351
+ return records.filter((record) => record.kind === kind);
352
+ }
353
+ /**
354
+ * This turn's records out of the session's.
355
+ *
356
+ * @param entries - Every entry of the session.
357
+ * @param stopTurnId - Turn id of the closing event, when it has one.
358
+ * @returns The entries this Stop owns.
359
+ */
360
+ function filterTurn(entries, stopTurnId) {
361
+ return entries.filter(({ record }) => stopTurnId === undefined || record.turnId === undefined || record.turnId === stopTurnId);
362
+ }
363
+ /**
364
+ * The response the user saw.
365
+ *
366
+ * A Stop-supplied response (Claude) wins; otherwise the turn's last recorded
367
+ * response event (Cursor's afterAgentResponse) is the answer that was shown.
368
+ *
369
+ * @param stopEvent - The closing event.
370
+ * @param records - The turn's records.
371
+ * @returns The response, or undefined when none was captured.
372
+ */
373
+ function resolveResponse(stopEvent, records) {
374
+ const fromStop = responseFrom(stopEvent);
375
+ if (fromStop)
376
+ return fromStop;
377
+ const last = recordsOfKind(records, 'response').at(-1);
378
+ if (!last)
379
+ return undefined;
380
+ return { text: last.text, evidence: last.evidence };
381
+ }
382
+ /**
383
+ * A copy of the closing event carrying the usage we resolved for it.
384
+ *
385
+ * @param stopEvent - The closing event; left untouched.
386
+ * @param usage - Transcript usage, when any was claimed.
387
+ * @param billingMode - Detected billing mode.
388
+ * @returns The event with `ai` filled in.
389
+ */
390
+ function withResolvedUsage(stopEvent, usage, billingMode) {
391
+ if (!usage && billingMode === 'unknown')
392
+ return stopEvent;
393
+ return {
394
+ ...stopEvent,
395
+ ai: {
396
+ ...stopEvent.ai,
397
+ model: usage?.model ?? stopEvent.ai?.model,
398
+ billingMode: billingMode === 'unknown' ? stopEvent.ai?.billingMode : billingMode,
399
+ usage: usage
400
+ ? {
401
+ inputTokens: usage.inputTokens,
402
+ outputTokens: usage.outputTokens,
403
+ cachedInputTokens: usage.cachedInputTokens,
404
+ cacheCreationInputTokens: usage.cacheCreationInputTokens,
405
+ source: 'transcript'
406
+ }
407
+ : stopEvent.ai?.usage
408
+ }
409
+ };
410
+ }
411
+ /**
412
+ * A prompt record from a prompt event.
413
+ *
414
+ * @param event - The prompt event.
415
+ * @returns The record.
416
+ */
417
+ function promptRecord(event) {
418
+ const metadata = event.metadata ?? {};
419
+ return {
420
+ kind: 'prompt',
421
+ at: event.timestamp,
422
+ turnId: event.session.turnId,
423
+ text: typeof metadata[PROMPT_TEXT_KEY] === 'string' ? metadata[PROMPT_TEXT_KEY] : undefined,
424
+ evidence: asEvidence(metadata[PROMPT_EVIDENCE_KEY])
425
+ };
426
+ }
427
+ /**
428
+ * A tool record from a tool-completion event.
429
+ *
430
+ * @param event - The tool event.
431
+ * @returns The record.
432
+ */
433
+ function toolRecord(event) {
434
+ const filePath = event.metadata?.[FILE_PATH_KEY];
435
+ return {
436
+ kind: 'tool',
437
+ at: event.timestamp,
438
+ turnId: event.session.turnId,
439
+ tool: event.tool?.name,
440
+ filePath: typeof filePath === 'string' ? filePath : undefined,
441
+ access: accessFor(event.event.type)
442
+ };
443
+ }
444
+ /**
445
+ * Whether a tool event read or modified its file.
446
+ *
447
+ * Reads and edits are different product signals: files the agent merely read
448
+ * must not appear in the summary's files_touched (modified) list.
449
+ *
450
+ * @param type - Canonical event type.
451
+ * @returns The access kind, or undefined when the event implies neither.
452
+ */
453
+ function accessFor(type) {
454
+ if (type === 'file.read')
455
+ return 'read';
456
+ if (type === 'file.edited')
457
+ return 'edit';
458
+ return undefined;
459
+ }
460
+ /**
461
+ * A response record from an out-of-band response event.
462
+ *
463
+ * @param event - The response-bearing event.
464
+ * @returns The record.
465
+ */
466
+ function responseRecord(event) {
467
+ const response = responseFrom(event);
468
+ return {
469
+ kind: 'response',
470
+ at: event.timestamp,
471
+ turnId: event.session.turnId,
472
+ text: response?.text,
473
+ evidence: response?.evidence
474
+ };
475
+ }
476
+ /**
477
+ * Response text and evidence carried on an event's metadata.
478
+ *
479
+ * @param event - Any canonical event.
480
+ * @returns The response, or undefined when the event carries none.
481
+ */
482
+ function responseFrom(event) {
483
+ const metadata = event.metadata ?? {};
484
+ const text = typeof metadata[RESPONSE_TEXT_KEY] === 'string' ? metadata[RESPONSE_TEXT_KEY] : undefined;
485
+ const evidence = asEvidence(metadata[RESPONSE_EVIDENCE_KEY]);
486
+ if (text === undefined && evidence === undefined)
487
+ return undefined;
488
+ return { text, evidence };
489
+ }
490
+ /**
491
+ * Content evidence out of an untrusted metadata value.
492
+ *
493
+ * @param value - Metadata value of unknown shape.
494
+ * @returns The evidence, or undefined when the shape does not match.
495
+ */
496
+ function asEvidence(value) {
497
+ const record = asRecord(value);
498
+ if (typeof record?.['length'] !== 'number' || typeof record['sha256'] !== 'string')
499
+ return undefined;
500
+ return { length: record['length'], sha256: record['sha256'] };
501
+ }
502
+ /**
503
+ * Which surface the turn happened on.
504
+ *
505
+ * @param provider - Internal provider id.
506
+ * @param env - Environment; Claude Code reports its own entrypoint there.
507
+ * @returns The surface label.
508
+ */
509
+ function resolveSurface(provider, env) {
510
+ if (provider === 'claude') {
511
+ const entrypoint = env.vars[CLAUDE_ENTRYPOINT_VAR];
512
+ if (entrypoint)
513
+ return entrypoint;
514
+ }
515
+ // Cursor and Antigravity hooks fire from an editor agent. Cursor's
516
+ // is_background_agent is only available on sessionStart, not on Stop, so v1
517
+ // reports a single surface for them.
518
+ if (IDE_SURFACE_PROVIDERS.has(provider))
519
+ return IDE_SURFACE;
520
+ return DEFAULT_SURFACE;
521
+ }
@@ -0,0 +1,26 @@
1
+ import type { TurnSummaryEvent } from './turn-summary.types.js';
2
+ export interface AggregateTurnUsageOptions {
3
+ /**
4
+ * True only when the backend has decided no further OTLP batches can arrive
5
+ * for this turn (watermark / quiet period / session end). OTLP delivery is
6
+ * asynchronous and retried, so the first non-empty batch proves nothing
7
+ * about completeness — without this explicit terminal signal the summary is
8
+ * finalized as 'partial', never 'complete'.
9
+ */
10
+ readonly complete?: boolean;
11
+ /**
12
+ * All turn summaries of the same session, including the one being finalized.
13
+ *
14
+ * With this context every window-joined call is attributed to exactly one
15
+ * summary of the session — the best-matching owner — so overlapping windows
16
+ * cannot double-count and degraded summaries without a started_at can still
17
+ * be finalized. Without it there is no window join at all: per-summary
18
+ * containment alone cannot arbitrate overlapping windows, and letting each
19
+ * summary claim every contained call would double-count usage and cost
20
+ * across successive finalizations. Calls then match only through an exact
21
+ * turn id.
22
+ */
23
+ readonly sessionSummaries?: readonly TurnSummaryEvent[];
24
+ }
25
+ /** Token and cost totals, as summed from a set of calls. */
26
+ export type UsageTotals = Pick<TurnSummaryEvent, 'input_tokens' | 'cached_input_tokens' | 'cache_creation_input_tokens' | 'output_tokens' | 'reasoning_output_tokens' | 'total_tokens' | 'cost_usd'>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,41 @@
1
+ /** Token usage read out of an agent's own transcript. */
2
+ export interface TurnUsage {
3
+ readonly model?: string;
4
+ readonly inputTokens?: number;
5
+ readonly outputTokens?: number;
6
+ readonly cachedInputTokens?: number;
7
+ readonly cacheCreationInputTokens?: number;
8
+ /** Transcript message ids summed into this usage; the exactly-once ledger. */
9
+ readonly messageIds?: readonly string[];
10
+ }
11
+ /**
12
+ * How hard to try before trusting a transcript snapshot.
13
+ *
14
+ * Agents flush their transcript asynchronously, so the final assistant entry
15
+ * may not be on disk when the Stop hook fires.
16
+ */
17
+ export interface ReadTurnUsageRetry {
18
+ /** Total read attempts, including the first one. */
19
+ readonly attempts: number;
20
+ readonly delayMs: number;
21
+ /**
22
+ * A stable snapshot is only trusted after this much time has passed: early
23
+ * usage in a multi-tool turn stabilizes instantly while the final entry may
24
+ * still be seconds away.
25
+ */
26
+ readonly minSettleMs?: number;
27
+ }
28
+ /**
29
+ * Reads one turn's usage from a provider transcript.
30
+ *
31
+ * @param transcriptPath - Path the provider reported.
32
+ * @param startedAt - ISO timestamp the turn began at.
33
+ * @param untilIso - Upper bound; entries after it belong to another turn.
34
+ * @param excludeMessageIds - Messages another turn has already claimed.
35
+ */
36
+ export type TranscriptReader = (transcriptPath: string, startedAt: string, untilIso: string, excludeMessageIds: ReadonlySet<string>) => Promise<TurnUsage | undefined>;
37
+ /** One assistant entry's usage, keyed by message id during accumulation. */
38
+ export interface TranscriptUsageEntry {
39
+ readonly model?: string;
40
+ readonly usage: Readonly<Record<string, unknown>>;
41
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,37 @@
1
+ import type { ContentEvidence } from '../../events/types/events.types.js';
2
+ /** A prompt the developer submitted. */
3
+ export interface PromptRecord {
4
+ readonly kind: 'prompt';
5
+ readonly at: string;
6
+ readonly turnId?: string;
7
+ readonly text?: string;
8
+ readonly evidence?: ContentEvidence;
9
+ }
10
+ /** One tool call the agent completed. */
11
+ export interface ToolRecord {
12
+ readonly kind: 'tool';
13
+ readonly at: string;
14
+ readonly turnId?: string;
15
+ readonly tool?: string;
16
+ readonly filePath?: string;
17
+ /**
18
+ * Reads and edits are different product signals: a file the agent merely
19
+ * read must not appear in the summary's files_touched (modified) list.
20
+ */
21
+ readonly access?: 'read' | 'edit';
22
+ }
23
+ /** Response text delivered outside the Stop event (Cursor's afterAgentResponse). */
24
+ export interface ResponseRecord {
25
+ readonly kind: 'response';
26
+ readonly at: string;
27
+ readonly turnId?: string;
28
+ readonly text?: string;
29
+ readonly evidence?: ContentEvidence;
30
+ }
31
+ /** Anything the accumulator persists between hook invocations. */
32
+ export type TurnRecord = PromptRecord | ToolRecord | ResponseRecord;
33
+ /** A record together with the file it was read from, so it can be consumed. */
34
+ export interface TurnStateEntry {
35
+ readonly file: string;
36
+ readonly record: TurnRecord;
37
+ }
@@ -0,0 +1 @@
1
+ export {};