@agent-watch-ai/edge 0.2.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (348) hide show
  1. package/CHANGELOG.md +558 -0
  2. package/README.md +222 -97
  3. package/SECURITY.md +72 -0
  4. package/dist/billing/session-billing.d.ts +19 -0
  5. package/dist/billing/session-billing.js +52 -0
  6. package/dist/cli/args.d.ts +10 -0
  7. package/dist/cli/args.js +20 -0
  8. package/dist/cli/constants/cli.constants.d.ts +52 -4
  9. package/dist/cli/constants/cli.constants.js +56 -5
  10. package/dist/cli/context.d.ts +33 -2
  11. package/dist/cli/context.js +84 -14
  12. package/dist/cli/doctor.js +321 -33
  13. package/dist/cli/hook-check.d.ts +23 -0
  14. package/dist/cli/hook-check.js +114 -0
  15. package/dist/cli/hook.js +118 -7
  16. package/dist/cli/index.d.ts +3 -1
  17. package/dist/cli/index.js +3 -1
  18. package/dist/cli/misc.d.ts +11 -0
  19. package/dist/cli/misc.js +80 -4
  20. package/dist/cli/npx-install.d.ts +37 -0
  21. package/dist/cli/npx-install.js +79 -0
  22. package/dist/cli/open-browser.d.ts +39 -0
  23. package/dist/cli/open-browser.js +62 -0
  24. package/dist/cli/setup.d.ts +17 -8
  25. package/dist/cli/setup.js +553 -103
  26. package/dist/cli/status.js +82 -13
  27. package/dist/cli/toggle.d.ts +9 -0
  28. package/dist/cli/toggle.js +117 -0
  29. package/dist/cli/types/cli.types.d.ts +43 -3
  30. package/dist/cli/ui.d.ts +7 -0
  31. package/dist/cli/ui.js +10 -1
  32. package/dist/cli/uninstall.js +39 -2
  33. package/dist/cli/update.d.ts +17 -0
  34. package/dist/cli/update.js +76 -0
  35. package/dist/cli.js +110 -12
  36. package/dist/config/config-store.d.ts +57 -0
  37. package/dist/config/config-store.js +250 -12
  38. package/dist/config/config.d.ts +53 -6
  39. package/dist/config/config.js +66 -6
  40. package/dist/config/constants/config.constants.d.ts +116 -6
  41. package/dist/config/constants/config.constants.js +131 -8
  42. package/dist/config/destination.d.ts +24 -0
  43. package/dist/config/destination.js +33 -0
  44. package/dist/config/index.d.ts +7 -4
  45. package/dist/config/index.js +5 -3
  46. package/dist/config/repo-config.d.ts +11 -7
  47. package/dist/config/repo-config.js +64 -15
  48. package/dist/config/root-config.d.ts +72 -0
  49. package/dist/config/root-config.js +170 -0
  50. package/dist/config/schemas/config.schema.d.ts +831 -84
  51. package/dist/config/schemas/config.schema.js +398 -16
  52. package/dist/config/types/config.types.d.ts +15 -1
  53. package/dist/config/types/destination.types.d.ts +8 -0
  54. package/dist/core/async.d.ts +36 -0
  55. package/dist/core/async.js +68 -0
  56. package/dist/core/index.d.ts +1 -1
  57. package/dist/core/index.js +1 -1
  58. package/dist/core/object.d.ts +5 -0
  59. package/dist/core/object.js +9 -4
  60. package/dist/core/pipe.d.ts +0 -13
  61. package/dist/core/pipe.js +1 -9
  62. package/dist/core/types/core.types.d.ts +9 -0
  63. package/dist/core/types/core.types.js +0 -3
  64. package/dist/core/which.d.ts +14 -0
  65. package/dist/core/which.js +43 -3
  66. package/dist/credentials/budget.d.ts +9 -0
  67. package/dist/credentials/budget.js +16 -0
  68. package/dist/credentials/command-runner.d.ts +16 -0
  69. package/dist/credentials/command-runner.js +37 -0
  70. package/dist/credentials/constants/credentials.constants.d.ts +119 -0
  71. package/dist/credentials/constants/credentials.constants.js +120 -0
  72. package/dist/credentials/credential-status.d.ts +14 -0
  73. package/dist/credentials/credential-status.js +38 -0
  74. package/dist/credentials/credentials.d.ts +86 -0
  75. package/dist/credentials/credentials.js +278 -0
  76. package/dist/credentials/device-api.d.ts +73 -0
  77. package/dist/credentials/device-api.js +161 -0
  78. package/dist/credentials/device-state.d.ts +31 -0
  79. package/dist/credentials/device-state.js +51 -0
  80. package/dist/credentials/identity.d.ts +73 -0
  81. package/dist/credentials/identity.js +101 -0
  82. package/dist/credentials/index.d.ts +7 -0
  83. package/dist/credentials/index.js +5 -0
  84. package/dist/credentials/migration.d.ts +46 -0
  85. package/dist/credentials/migration.js +164 -0
  86. package/dist/credentials/schemas/device-api.schema.d.ts +77 -0
  87. package/dist/credentials/schemas/device-api.schema.js +33 -0
  88. package/dist/credentials/schemas/device-state.schema.d.ts +51 -0
  89. package/dist/credentials/schemas/device-state.schema.js +20 -0
  90. package/dist/credentials/secret-store.d.ts +54 -0
  91. package/dist/credentials/secret-store.js +217 -0
  92. package/dist/credentials/sign-in.d.ts +31 -0
  93. package/dist/credentials/sign-in.js +105 -0
  94. package/dist/credentials/token-refresher.d.ts +39 -0
  95. package/dist/credentials/token-refresher.js +185 -0
  96. package/dist/credentials/types/credentials.types.d.ts +206 -0
  97. package/dist/credentials/types/credentials.types.js +1 -0
  98. package/dist/enforcement/constants/enforcement.constants.d.ts +47 -1
  99. package/dist/enforcement/constants/enforcement.constants.js +56 -0
  100. package/dist/enforcement/decision-cache.d.ts +20 -1
  101. package/dist/enforcement/decision-cache.js +65 -2
  102. package/dist/enforcement/decision-client.d.ts +9 -8
  103. package/dist/enforcement/decision-client.js +64 -17
  104. package/dist/enforcement/enforcement.d.ts +23 -2
  105. package/dist/enforcement/enforcement.js +107 -17
  106. package/dist/enforcement/index.d.ts +4 -3
  107. package/dist/enforcement/index.js +3 -2
  108. package/dist/enforcement/types/enforcement.types.d.ts +66 -2
  109. package/dist/enrollment/constants/enrollment.constants.d.ts +2 -6
  110. package/dist/enrollment/constants/enrollment.constants.js +2 -6
  111. package/dist/enrollment/enrollment.d.ts +16 -0
  112. package/dist/enrollment/enrollment.js +54 -0
  113. package/dist/enrollment/index.d.ts +3 -7
  114. package/dist/enrollment/index.js +1 -1
  115. package/dist/enrollment/types/enrollment.types.d.ts +9 -13
  116. package/dist/events/constants/enrich.constants.d.ts +15 -0
  117. package/dist/events/constants/enrich.constants.js +15 -0
  118. package/dist/events/constants/events.constants.d.ts +6 -2
  119. package/dist/events/constants/events.constants.js +5 -1
  120. package/dist/events/enrich.js +92 -10
  121. package/dist/events/event-id.d.ts +0 -8
  122. package/dist/events/event-id.js +0 -10
  123. package/dist/events/index.d.ts +2 -2
  124. package/dist/events/index.js +1 -1
  125. package/dist/events/product-event.d.ts +9 -6
  126. package/dist/events/types/repo-snapshot.types.d.ts +7 -0
  127. package/dist/events/types/session-billing.types.d.ts +16 -0
  128. package/dist/events/types/session-billing.types.js +1 -0
  129. package/dist/feature/constants/feature.constants.d.ts +7 -0
  130. package/dist/feature/constants/feature.constants.js +7 -0
  131. package/dist/feature/index.d.ts +1 -1
  132. package/dist/feature/index.js +1 -1
  133. package/dist/feature/ticket-candidates.d.ts +14 -0
  134. package/dist/feature/ticket-candidates.js +26 -8
  135. package/dist/git/blob-hash.d.ts +21 -0
  136. package/dist/git/blob-hash.js +69 -0
  137. package/dist/git/checkout-root.d.ts +27 -0
  138. package/dist/git/checkout-root.js +75 -0
  139. package/dist/git/constants/git.constants.d.ts +160 -0
  140. package/dist/git/constants/git.constants.js +181 -0
  141. package/dist/git/fingerprint.d.ts +74 -0
  142. package/dist/git/fingerprint.js +219 -0
  143. package/dist/git/gate-checkout.d.ts +44 -0
  144. package/dist/git/gate-checkout.js +201 -0
  145. package/dist/git/git-context.d.ts +45 -0
  146. package/dist/git/git-context.js +61 -3
  147. package/dist/git/index.d.ts +4 -2
  148. package/dist/git/index.js +2 -1
  149. package/dist/git/manifest-repository.d.ts +13 -0
  150. package/dist/git/manifest-repository.js +92 -0
  151. package/dist/git/repo-snapshot.d.ts +29 -3
  152. package/dist/git/repo-snapshot.js +110 -7
  153. package/dist/git/repository-root.d.ts +39 -0
  154. package/dist/git/repository-root.js +131 -0
  155. package/dist/git/types/git.types.d.ts +55 -0
  156. package/dist/git/types/repository-root.types.d.ts +11 -0
  157. package/dist/git/types/repository-root.types.js +1 -0
  158. package/dist/git/types/snapshot.types.d.ts +9 -0
  159. package/dist/pipeline/constants/pipeline.constants.d.ts +10 -0
  160. package/dist/pipeline/constants/pipeline.constants.js +10 -0
  161. package/dist/pipeline/hook-pipeline.js +410 -33
  162. package/dist/pipeline/types/pipeline.types.d.ts +39 -4
  163. package/dist/privacy/constants/privacy.constants.js +15 -1
  164. package/dist/privacy/index.d.ts +1 -0
  165. package/dist/privacy/index.js +1 -0
  166. package/dist/privacy/product-capture.d.ts +12 -0
  167. package/dist/privacy/product-capture.js +75 -0
  168. package/dist/privacy/sanitizer.d.ts +21 -3
  169. package/dist/privacy/sanitizer.js +52 -8
  170. package/dist/process/ancestors.d.ts +39 -0
  171. package/dist/process/ancestors.js +121 -0
  172. package/dist/process/constants/process.constants.d.ts +34 -0
  173. package/dist/process/constants/process.constants.js +34 -0
  174. package/dist/process/index.d.ts +7 -0
  175. package/dist/process/index.js +2 -0
  176. package/dist/process/types/process.types.d.ts +23 -0
  177. package/dist/process/types/process.types.js +1 -0
  178. package/dist/providers/antigravity/antigravity.adapter.d.ts +12 -1
  179. package/dist/providers/antigravity/antigravity.adapter.js +21 -3
  180. package/dist/providers/antigravity/antigravity.detect.d.ts +0 -9
  181. package/dist/providers/antigravity/antigravity.detect.js +1 -1
  182. package/dist/providers/antigravity/antigravity.provider.js +3 -2
  183. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +2 -0
  184. package/dist/providers/antigravity/constants/antigravity.constants.js +2 -0
  185. package/dist/providers/claude/claude.adapter.d.ts +11 -1
  186. package/dist/providers/claude/claude.adapter.js +26 -5
  187. package/dist/providers/claude/claude.otel.d.ts +32 -18
  188. package/dist/providers/claude/claude.otel.js +81 -6
  189. package/dist/providers/claude/claude.provider.js +5 -2
  190. package/dist/providers/claude/constants/claude.constants.d.ts +2 -0
  191. package/dist/providers/claude/constants/claude.constants.js +2 -0
  192. package/dist/providers/claude/constants/claude.otel.constants.d.ts +4 -0
  193. package/dist/providers/claude/constants/claude.otel.constants.js +8 -0
  194. package/dist/providers/codex/codex.adapter.d.ts +15 -1
  195. package/dist/providers/codex/codex.adapter.js +29 -5
  196. package/dist/providers/codex/codex.otel.d.ts +36 -3
  197. package/dist/providers/codex/codex.otel.js +199 -32
  198. package/dist/providers/codex/codex.provider.js +5 -2
  199. package/dist/providers/codex/constants/codex.constants.d.ts +2 -0
  200. package/dist/providers/codex/constants/codex.constants.js +16 -0
  201. package/dist/providers/codex/constants/codex.otel.constants.d.ts +10 -0
  202. package/dist/providers/codex/constants/codex.otel.constants.js +10 -0
  203. package/dist/providers/constants/provider.constants.d.ts +8 -3
  204. package/dist/providers/constants/provider.constants.js +8 -3
  205. package/dist/providers/cursor/constants/cursor.constants.d.ts +9 -0
  206. package/dist/providers/cursor/constants/cursor.constants.js +9 -0
  207. package/dist/providers/cursor/cursor.adapter.d.ts +33 -1
  208. package/dist/providers/cursor/cursor.adapter.js +129 -4
  209. package/dist/providers/cursor/cursor.detect.d.ts +0 -7
  210. package/dist/providers/cursor/cursor.detect.js +1 -1
  211. package/dist/providers/cursor/cursor.provider.js +5 -2
  212. package/dist/providers/gemini/constants/gemini.constants.d.ts +9 -0
  213. package/dist/providers/gemini/constants/gemini.constants.js +9 -0
  214. package/dist/providers/gemini/constants/gemini.otel.constants.d.ts +9 -1
  215. package/dist/providers/gemini/constants/gemini.otel.constants.js +9 -0
  216. package/dist/providers/gemini/gemini.adapter.d.ts +14 -1
  217. package/dist/providers/gemini/gemini.adapter.js +25 -5
  218. package/dist/providers/gemini/gemini.detect.d.ts +0 -7
  219. package/dist/providers/gemini/gemini.detect.js +1 -1
  220. package/dist/providers/gemini/gemini.otel.d.ts +30 -21
  221. package/dist/providers/gemini/gemini.otel.js +166 -22
  222. package/dist/providers/gemini/gemini.provider.js +2 -1
  223. package/dist/providers/index.d.ts +1 -1
  224. package/dist/providers/index.js +1 -1
  225. package/dist/providers/loaders.d.ts +10 -0
  226. package/dist/providers/loaders.js +40 -0
  227. package/dist/providers/provider.d.ts +11 -0
  228. package/dist/providers/provider.js +1 -1
  229. package/dist/providers/registry.d.ts +11 -8
  230. package/dist/providers/registry.js +11 -15
  231. package/dist/providers/shared/bearer-rewrite.d.ts +19 -0
  232. package/dist/providers/shared/bearer-rewrite.js +46 -0
  233. package/dist/providers/shared/constants/hook-refusal.constants.d.ts +7 -0
  234. package/dist/providers/shared/constants/hook-refusal.constants.js +7 -0
  235. package/dist/providers/shared/constants/shell-directories.constants.d.ts +30 -0
  236. package/dist/providers/shared/constants/shell-directories.constants.js +39 -0
  237. package/dist/providers/shared/constants/tooling.constants.d.ts +24 -2
  238. package/dist/providers/shared/constants/tooling.constants.js +25 -3
  239. package/dist/providers/shared/event-builder.d.ts +12 -14
  240. package/dist/providers/shared/event-builder.js +20 -14
  241. package/dist/providers/shared/exporter-allowlist.d.ts +20 -0
  242. package/dist/providers/shared/exporter-allowlist.js +49 -0
  243. package/dist/providers/shared/hook-config.d.ts +2 -21
  244. package/dist/providers/shared/hook-config.js +5 -4
  245. package/dist/providers/shared/hook-refusal.d.ts +12 -0
  246. package/dist/providers/shared/hook-refusal.js +17 -1
  247. package/dist/providers/shared/install-record.d.ts +12 -2
  248. package/dist/providers/shared/install-record.js +5 -2
  249. package/dist/providers/shared/shell-directories.d.ts +24 -0
  250. package/dist/providers/shared/shell-directories.js +90 -0
  251. package/dist/providers/shared/tooling.d.ts +40 -1
  252. package/dist/providers/shared/tooling.js +70 -1
  253. package/dist/providers/shared/types/adapter.types.d.ts +1 -2
  254. package/dist/providers/types/provider.types.d.ts +81 -1
  255. package/dist/snapshot/constants/snapshot.constants.d.ts +32 -0
  256. package/dist/snapshot/constants/snapshot.constants.js +33 -0
  257. package/dist/snapshot/snapshot-event.js +52 -11
  258. package/dist/snapshot/snapshot-pipeline.js +1 -1
  259. package/dist/snapshot/types/snapshot.types.d.ts +2 -0
  260. package/dist/storage/atomic-file.d.ts +21 -0
  261. package/dist/storage/atomic-file.js +20 -1
  262. package/dist/storage/constants/storage.constants.d.ts +19 -0
  263. package/dist/storage/constants/storage.constants.js +19 -0
  264. package/dist/storage/disabled.d.ts +13 -0
  265. package/dist/storage/disabled.js +24 -0
  266. package/dist/storage/index.d.ts +2 -0
  267. package/dist/storage/index.js +2 -0
  268. package/dist/storage/paths.js +3 -2
  269. package/dist/storage/schemas/storage.schema.d.ts +72 -0
  270. package/dist/storage/schemas/storage.schema.js +6 -0
  271. package/dist/storage/sweep-marker.d.ts +19 -0
  272. package/dist/storage/sweep-marker.js +55 -0
  273. package/dist/storage/types/storage.types.d.ts +2 -0
  274. package/dist/storage/uninstalled.d.ts +58 -0
  275. package/dist/storage/uninstalled.js +107 -0
  276. package/dist/transport/auth-block.d.ts +66 -0
  277. package/dist/transport/auth-block.js +129 -0
  278. package/dist/transport/constants/transport.constants.d.ts +82 -3
  279. package/dist/transport/constants/transport.constants.js +83 -4
  280. package/dist/transport/cooldown.js +8 -1
  281. package/dist/transport/delivery.d.ts +14 -6
  282. package/dist/transport/delivery.js +80 -55
  283. package/dist/transport/http-transport.d.ts +1 -0
  284. package/dist/transport/http-transport.js +52 -10
  285. package/dist/transport/index.d.ts +6 -3
  286. package/dist/transport/index.js +3 -0
  287. package/dist/transport/queue-partition.d.ts +91 -0
  288. package/dist/transport/queue-partition.js +143 -0
  289. package/dist/transport/queue.d.ts +99 -20
  290. package/dist/transport/queue.js +210 -69
  291. package/dist/transport/response-body.d.ts +25 -0
  292. package/dist/transport/response-body.js +64 -0
  293. package/dist/transport/send.d.ts +11 -0
  294. package/dist/transport/send.js +17 -0
  295. package/dist/transport/types/delivery-flow.types.d.ts +19 -0
  296. package/dist/transport/types/delivery-flow.types.js +1 -0
  297. package/dist/transport/types/transport.types.d.ts +45 -0
  298. package/dist/turns/claude-transcript.d.ts +19 -1
  299. package/dist/turns/claude-transcript.js +46 -1
  300. package/dist/turns/codex-originator.d.ts +11 -0
  301. package/dist/turns/codex-originator.js +31 -0
  302. package/dist/turns/codex-transcript.d.ts +30 -0
  303. package/dist/turns/codex-transcript.js +88 -0
  304. package/dist/turns/constants/turns.constants.d.ts +141 -5
  305. package/dist/turns/constants/turns.constants.js +155 -5
  306. package/dist/turns/file-identity.d.ts +27 -0
  307. package/dist/turns/file-identity.js +48 -0
  308. package/dist/turns/gemini-transcript.d.ts +30 -0
  309. package/dist/turns/gemini-transcript.js +96 -0
  310. package/dist/turns/index.d.ts +3 -3
  311. package/dist/turns/index.js +1 -1
  312. package/dist/turns/inherited-checkout.d.ts +54 -0
  313. package/dist/turns/inherited-checkout.js +155 -0
  314. package/dist/turns/native-session-titles.d.ts +26 -0
  315. package/dist/turns/native-session-titles.js +102 -0
  316. package/dist/turns/transcript.d.ts +3 -2
  317. package/dist/turns/transcript.js +5 -1
  318. package/dist/turns/turn-state.d.ts +224 -3
  319. package/dist/turns/turn-state.js +456 -21
  320. package/dist/turns/turn-summary.d.ts +1 -14
  321. package/dist/turns/turn-summary.js +87 -51
  322. package/dist/turns/turn-tracker.d.ts +21 -2
  323. package/dist/turns/turn-tracker.js +379 -56
  324. package/dist/turns/types/transcript.types.d.ts +5 -0
  325. package/dist/turns/types/turn-state.types.d.ts +116 -5
  326. package/dist/turns/types/turn-summary.types.d.ts +64 -14
  327. package/dist/turns/types/turn-tracker.types.d.ts +27 -1
  328. package/dist/turns/work-checkout.d.ts +67 -0
  329. package/dist/turns/work-checkout.js +700 -0
  330. package/dist/untraced/constants/untraced.constants.d.ts +31 -0
  331. package/dist/untraced/constants/untraced.constants.js +63 -0
  332. package/dist/untraced/untraced.d.ts +35 -0
  333. package/dist/untraced/untraced.js +105 -0
  334. package/dist/update/constants/update.constants.d.ts +18 -0
  335. package/dist/update/constants/update.constants.js +20 -0
  336. package/dist/update/update-check.d.ts +52 -0
  337. package/dist/update/update-check.js +113 -0
  338. package/docs/AUDIT_PROMPT.md +129 -0
  339. package/docs/DATA_HANDLING.md +655 -0
  340. package/docs/ENTERPRISE_DEPLOYMENT.md +194 -0
  341. package/docs/PERFORMANCE.md +81 -0
  342. package/package.json +14 -4
  343. package/dist/enrollment/enrollment-provider.d.ts +0 -5
  344. package/dist/enrollment/manual-enrollment.d.ts +0 -32
  345. package/dist/enrollment/manual-enrollment.js +0 -72
  346. package/example/README.md +0 -43
  347. package/example/server.mjs +0 -240
  348. /package/dist/{enrollment/enrollment-provider.js → config/types/destination.types.js} +0 -0
@@ -0,0 +1,27 @@
1
+ import type { ContentHash } from '../git/types/git.types.js';
2
+ import type { AgentWatchEvent } from '../events/types/events.types.js';
3
+ import type { ToolRecord } from './types/turn-state.types.js';
4
+ import type { TurnStateStore } from './turn-state.js';
5
+ import type { TrackTurnOptions } from './types/turn-tracker.types.js';
6
+ /** What a turn in a folder with no git says about its files, for Agent Watch to match. */
7
+ export interface FileIdentity {
8
+ readonly contentHashes?: readonly ContentHash[];
9
+ readonly manifestRepository?: string;
10
+ }
11
+ /**
12
+ * Content ids of the files the turn's tools named, and the repository address
13
+ * its project manifest names, when the folder has no git context.
14
+ *
15
+ * Runs in the Stop hook only. ponytail: "no git" is the closing event carrying
16
+ * no repository, and with `capture.git` off that is true everywhere, so such a
17
+ * machine reports nothing; telling the two apart would cost the git lookup the
18
+ * flag turned off.
19
+ *
20
+ * @param store - Per-session state store, for the session's start folder.
21
+ * @param sessionId - Provider session id.
22
+ * @param tools - The turn's tool records, in the order they ran.
23
+ * @param stopEvent - The enriched closing event.
24
+ * @param options - Tracking options.
25
+ * @returns The fields to add; empty when files are off, git is present or nothing was found.
26
+ */
27
+ export declare function resolveFileIdentity(store: TurnStateStore, sessionId: string, tools: readonly ToolRecord[], stopEvent: AgentWatchEvent, options: TrackTurnOptions): Promise<FileIdentity>;
@@ -0,0 +1,48 @@
1
+ import path from 'node:path';
2
+ import { withinBudget } from '../core/async.js';
3
+ import { HOME_PLACEHOLDER_PREFIX } from '../events/constants/enrich.constants.js';
4
+ import { contentHashes } from '../git/blob-hash.js';
5
+ import { HASH_BUDGET_MS } from '../git/constants/git.constants.js';
6
+ import { manifestRepository } from '../git/manifest-repository.js';
7
+ /** The contract's bound on `manifest_repository` (AWT-227). */
8
+ const MAX_MANIFEST_REPOSITORY_LENGTH = 500;
9
+ /**
10
+ * Content ids of the files the turn's tools named, and the repository address
11
+ * its project manifest names, when the folder has no git context.
12
+ *
13
+ * Runs in the Stop hook only. ponytail: "no git" is the closing event carrying
14
+ * no repository, and with `capture.git` off that is true everywhere, so such a
15
+ * machine reports nothing; telling the two apart would cost the git lookup the
16
+ * flag turned off.
17
+ *
18
+ * @param store - Per-session state store, for the session's start folder.
19
+ * @param sessionId - Provider session id.
20
+ * @param tools - The turn's tool records, in the order they ran.
21
+ * @param stopEvent - The enriched closing event.
22
+ * @param options - Tracking options.
23
+ * @returns The fields to add; empty when files are off, git is present or nothing was found.
24
+ */
25
+ export async function resolveFileIdentity(store, sessionId, tools, stopEvent, options) {
26
+ const { capture } = options.config;
27
+ if (!capture.files || !capture.git || stopEvent.git?.repository)
28
+ return {};
29
+ // `externalPath` is the file's place outside every checkout (home-relative as
30
+ // `~/x`, else absolute); it is the only absolute-ish path turn state keeps.
31
+ const absolute = (tool) => {
32
+ const external = tool.externalPath;
33
+ if (!external)
34
+ return undefined;
35
+ return external.startsWith(HOME_PLACEHOLDER_PREFIX) ? path.join(options.env.home, external.slice(HOME_PLACEHOLDER_PREFIX.length)) : external;
36
+ };
37
+ // Edits first, then reads, each in first-seen order.
38
+ const ordered = [...tools.filter((tool) => tool.access !== 'read'), ...tools.filter((tool) => tool.access === 'read')]
39
+ .map(absolute)
40
+ .filter((file) => file !== undefined);
41
+ // The session folder, not the Stop hook's cwd: a mid-session `cd` must not
42
+ // change what the paths are relative to (SPEC §5.7).
43
+ const root = (await store.readStart(sessionId)) ?? options.cwd;
44
+ // The manifest walk gets the hashing's budget too: on a slow mount the hook
45
+ // sends without an address rather than wait for one.
46
+ const [hashes, address] = await Promise.all([contentHashes(ordered, root), withinBudget(manifestRepository(root, options.env.home), HASH_BUDGET_MS)]);
47
+ return { contentHashes: hashes.length > 0 ? hashes : undefined, manifestRepository: address?.slice(0, MAX_MANIFEST_REPOSITORY_LENGTH) };
48
+ }
@@ -0,0 +1,30 @@
1
+ import type { ReadTurnUsageRetry, TurnUsage } from './types/transcript.types.js';
2
+ /**
3
+ * Per-turn token usage from a Gemini CLI chat file
4
+ * (`~/.gemini/tmp/<project>/chats/session-*.jsonl`).
5
+ *
6
+ * Gemini CLI appends a row per reply message and appends it again, same `id`,
7
+ * once the response's `usageMetadata` arrives, adding `tokens: {input, output,
8
+ * cached, thoughts, tool, total}` (gemini-cli 0.46.0, `ChatRecordingService`).
9
+ * Only those numbers, the model name and the row's id and timestamp are read;
10
+ * user rows, thoughts and tool calls are never looked at, so nothing a
11
+ * developer wrote leaves this function.
12
+ *
13
+ * This is how Gemini usage reaches the platform on a metadata-only install,
14
+ * where its native OTel stays off because those logs carry tool content.
15
+ *
16
+ * Counts keep Google's meaning: `input` (promptTokenCount) includes the cached
17
+ * part, which `cachedInputTokens` repeats; thinking tokens are billed as output
18
+ * and tool-use prompt tokens as input, so both are folded in.
19
+ *
20
+ * ponytail: reads the same 4 MiB tail as the Claude reader; a turn longer than
21
+ * that undercounts. Upgrade path: remember the byte offset each Stop read to.
22
+ *
23
+ * @param transcriptPath - Path Gemini reported in the hook payload.
24
+ * @param sinceIso - When the turn started; earlier replies are another turn's.
25
+ * @param retry - How long to wait for the chat file flush to settle.
26
+ * @param untilIso - Upper bound, keeping a racing next prompt's replies out.
27
+ * @param excludeMessageIds - Replies another turn already claimed.
28
+ * @returns The turn's usage, or undefined when the file reports none.
29
+ */
30
+ export declare function readGeminiTurnUsage(transcriptPath: string, sinceIso: string, retry?: ReadTurnUsageRetry, untilIso?: string, excludeMessageIds?: ReadonlySet<string>): Promise<TurnUsage | undefined>;
@@ -0,0 +1,96 @@
1
+ import { asRecord, firstStringOf } from '../core/object.js';
2
+ import { finiteOrZero } from '../core/number.js';
3
+ import { accumulateUsage, parseJsonLine, readTranscriptTail, readUntilSettled } from './transcript.js';
4
+ import { GEMINI_REPLY_TYPE, GEMINI_TOKENS, TRANSCRIPT_CACHE_READ_TOKENS, TRANSCRIPT_INPUT_TOKENS, TRANSCRIPT_OUTPUT_TOKENS } from './constants/turns.constants.js';
5
+ /**
6
+ * Per-turn token usage from a Gemini CLI chat file
7
+ * (`~/.gemini/tmp/<project>/chats/session-*.jsonl`).
8
+ *
9
+ * Gemini CLI appends a row per reply message and appends it again, same `id`,
10
+ * once the response's `usageMetadata` arrives, adding `tokens: {input, output,
11
+ * cached, thoughts, tool, total}` (gemini-cli 0.46.0, `ChatRecordingService`).
12
+ * Only those numbers, the model name and the row's id and timestamp are read;
13
+ * user rows, thoughts and tool calls are never looked at, so nothing a
14
+ * developer wrote leaves this function.
15
+ *
16
+ * This is how Gemini usage reaches the platform on a metadata-only install,
17
+ * where its native OTel stays off because those logs carry tool content.
18
+ *
19
+ * Counts keep Google's meaning: `input` (promptTokenCount) includes the cached
20
+ * part, which `cachedInputTokens` repeats; thinking tokens are billed as output
21
+ * and tool-use prompt tokens as input, so both are folded in.
22
+ *
23
+ * ponytail: reads the same 4 MiB tail as the Claude reader; a turn longer than
24
+ * that undercounts. Upgrade path: remember the byte offset each Stop read to.
25
+ *
26
+ * @param transcriptPath - Path Gemini reported in the hook payload.
27
+ * @param sinceIso - When the turn started; earlier replies are another turn's.
28
+ * @param retry - How long to wait for the chat file flush to settle.
29
+ * @param untilIso - Upper bound, keeping a racing next prompt's replies out.
30
+ * @param excludeMessageIds - Replies another turn already claimed.
31
+ * @returns The turn's usage, or undefined when the file reports none.
32
+ */
33
+ export async function readGeminiTurnUsage(transcriptPath, sinceIso, retry, untilIso, excludeMessageIds) {
34
+ return readUntilSettled(() => readOnce(transcriptPath, sinceIso, untilIso, excludeMessageIds), retry);
35
+ }
36
+ /**
37
+ * One pass over the chat file tail.
38
+ *
39
+ * @param transcriptPath - Chat file.
40
+ * @param sinceIso - Lower bound of the turn's window.
41
+ * @param untilIso - Upper bound, or undefined for "no upper bound".
42
+ * @param excludeMessageIds - Replies another turn already claimed.
43
+ * @returns The usage found in this pass.
44
+ */
45
+ async function readOnce(transcriptPath, sinceIso, untilIso, excludeMessageIds) {
46
+ const since = Date.parse(sinceIso);
47
+ const until = untilIso === undefined ? Number.POSITIVE_INFINITY : Date.parse(untilIso);
48
+ if (Number.isNaN(since) || Number.isNaN(until))
49
+ return undefined;
50
+ const raw = await readTranscriptTail(transcriptPath);
51
+ if (raw === undefined)
52
+ return undefined;
53
+ // Later rows with the same id replace earlier ones: the rewrite is the one with tokens.
54
+ const byId = new Map();
55
+ for (const line of raw.split('\n')) {
56
+ if (!line.includes(`"${GEMINI_TOKENS}"`))
57
+ continue;
58
+ for (const row of replyRows(parseJsonLine(line))) {
59
+ const tokens = asRecord(row[GEMINI_TOKENS]);
60
+ const id = firstStringOf(row['id']);
61
+ const timestamp = typeof row['timestamp'] === 'string' ? Date.parse(row['timestamp']) : NaN;
62
+ if (!tokens || !id || row['type'] !== GEMINI_REPLY_TYPE)
63
+ continue;
64
+ if (Number.isNaN(timestamp) || timestamp < since || timestamp > until || excludeMessageIds?.has(id))
65
+ continue;
66
+ byId.set(id, {
67
+ model: firstStringOf(row['model']),
68
+ usage: {
69
+ [TRANSCRIPT_INPUT_TOKENS]: finiteOrZero(tokens['input']) + finiteOrZero(tokens['tool']),
70
+ [TRANSCRIPT_OUTPUT_TOKENS]: finiteOrZero(tokens['output']) + finiteOrZero(tokens['thoughts']),
71
+ [TRANSCRIPT_CACHE_READ_TOKENS]: finiteOrZero(tokens['cached'])
72
+ }
73
+ });
74
+ }
75
+ }
76
+ return accumulateUsage(byId);
77
+ }
78
+ /**
79
+ * The message records one chat-file line carries: the line itself, or, for a
80
+ * `{"$set": {"messages": [...]}}` snapshot (a resumed or rewritten session),
81
+ * each message inside it.
82
+ *
83
+ * @param row - The parsed line.
84
+ * @returns The records to look at.
85
+ */
86
+ function replyRows(row) {
87
+ if (!row)
88
+ return [];
89
+ const snapshot = asRecord(row['$set'])?.['messages'];
90
+ if (!Array.isArray(snapshot))
91
+ return [row];
92
+ return snapshot.flatMap((message) => {
93
+ const record = asRecord(message);
94
+ return record ? [record] : [];
95
+ });
96
+ }
@@ -3,13 +3,13 @@
3
3
  * closes the turn into one flat summary, and the backend finalizes its usage
4
4
  * from the atomic llm.call ledger.
5
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';
6
+ export type { AgentUsageSummary, BuildTurnSummaryInput, TouchedFiles, TurnSummaryEvent, TurnUsageStatus } from './types/turn-summary.types.js';
7
+ export type { PromptRecord, ResponseRecord, SessionModelRecord, ToolRecord, TurnRecord, TurnStateEntry } from './types/turn-state.types.js';
8
8
  export type { ReadTurnUsageRetry, TranscriptReader, TranscriptUsageEntry, TurnUsage } from './types/transcript.types.js';
9
9
  export type { TrackTurnOptions, TurnWindow } from './types/turn-tracker.types.js';
10
10
  export type { AggregateTurnUsageOptions, UsageTotals } from './types/aggregate-usage.types.js';
11
11
  export { PROVIDER_LABELS, TURN_STATE_TTL_MS, USAGE_RETRY } from './constants/turns.constants.js';
12
- export { alignContentEvidence, buildTurnSummary } from './turn-summary.js';
12
+ export { buildTurnSummary } from './turn-summary.js';
13
13
  export { TurnStateStore } from './turn-state.js';
14
14
  export { readTurnUsage } from './claude-transcript.js';
15
15
  export { readCursorTurnUsage } from './cursor-transcript.js';
@@ -1,5 +1,5 @@
1
1
  export { PROVIDER_LABELS, TURN_STATE_TTL_MS, USAGE_RETRY } from './constants/turns.constants.js';
2
- export { alignContentEvidence, buildTurnSummary } from './turn-summary.js';
2
+ export { buildTurnSummary } from './turn-summary.js';
3
3
  export { TurnStateStore } from './turn-state.js';
4
4
  export { readTurnUsage } from './claude-transcript.js';
5
5
  export { readCursorTurnUsage } from './cursor-transcript.js';
@@ -0,0 +1,54 @@
1
+ import type { TurnStateStore } from './turn-state.js';
2
+ import type { TrackTurnOptions } from './types/turn-tracker.types.js';
3
+ /** A checkout a session inherited, and the parent agent session it came from, when it came from one. */
4
+ export interface InheritedCheckout {
5
+ readonly root: string;
6
+ readonly parentSessionId?: string;
7
+ }
8
+ /**
9
+ * On a session's first hook: remember which process is its agent, and — when
10
+ * its folder is no checkout — what started that agent.
11
+ *
12
+ * Review bots, orchestrators and SDK apps start agents in folders with no git,
13
+ * and the process that started them usually knows the repository. The walk is
14
+ * one `ps` and, when no live parent session already answers, one `lsof`, all
15
+ * under one {@link WALK_DEADLINE_MS} deadline. A walk that ends, found or not,
16
+ * is final: the answer is written down. One the deadline cut is not (AWT-378):
17
+ * the cut is counted in the memo and {@link retryInheritance} walks again on
18
+ * the next hook. Process ids and folders stay in local state: only the
19
+ * checkout fields and the parent session id leave the machine, through the
20
+ * summary. Any failure leaves the session as it was.
21
+ *
22
+ * @param store - Per-session state store.
23
+ * @param sessionId - Provider session id.
24
+ * @param options - Tracking options.
25
+ * @param cuts - How many earlier walks the deadline cut.
26
+ */
27
+ export declare function rememberInheritance(store: TurnStateStore, sessionId: string, options: TrackTurnOptions, cuts?: number): Promise<void>;
28
+ /**
29
+ * Walk again when the session's last walk was cut by its deadline, or failed.
30
+ *
31
+ * A busy machine can push `ps` past the deadline, and a cut walk read as final
32
+ * leaves every turn of the session without its repository. Each retry has the
33
+ * same deadline as the first walk, at most one runs per hook, and after
34
+ * {@link MAX_WALK_ATTEMPTS} the session gives up. A session whose walk ended
35
+ * pays one small file read per hook and never walks again.
36
+ *
37
+ * @param store - Per-session state store.
38
+ * @param sessionId - Provider session id.
39
+ * @param options - Tracking options.
40
+ */
41
+ export declare function retryInheritance(store: TurnStateStore, sessionId: string, options: TrackTurnOptions): Promise<void>;
42
+ /**
43
+ * The checkout this session inherited, as of now.
44
+ *
45
+ * The nearest live parent agent session's last work checkout; failing that,
46
+ * the checkout the nearest ancestor's folder lay in. A parent that has ended or
47
+ * expired is skipped, and so is anything the caller does not admit.
48
+ *
49
+ * @param store - Per-session state store.
50
+ * @param sessionId - Provider session id.
51
+ * @param admits - The session's admission test for a checkout.
52
+ * @returns The checkout, or undefined when the session inherited none.
53
+ */
54
+ export declare function resolveInherited(store: TurnStateStore, sessionId: string, admits: (root: string) => boolean): Promise<InheritedCheckout | undefined>;
@@ -0,0 +1,155 @@
1
+ import path from 'node:path';
2
+ import { canonicalRoot } from '../config/root-config.js';
3
+ import { debugLog } from '../core/logger.js';
4
+ import { checkoutRootOf } from '../git/checkout-root.js';
5
+ import { MAX_WALK_ATTEMPTS, WALK_DEADLINE_MS, agentProcess, ancestorChain, systemProcessTable } from '../process/index.js';
6
+ import { TURN_STATE_TTL_MS } from './constants/turns.constants.js';
7
+ /**
8
+ * On a session's first hook: remember which process is its agent, and — when
9
+ * its folder is no checkout — what started that agent.
10
+ *
11
+ * Review bots, orchestrators and SDK apps start agents in folders with no git,
12
+ * and the process that started them usually knows the repository. The walk is
13
+ * one `ps` and, when no live parent session already answers, one `lsof`, all
14
+ * under one {@link WALK_DEADLINE_MS} deadline. A walk that ends, found or not,
15
+ * is final: the answer is written down. One the deadline cut is not (AWT-378):
16
+ * the cut is counted in the memo and {@link retryInheritance} walks again on
17
+ * the next hook. Process ids and folders stay in local state: only the
18
+ * checkout fields and the parent session id leave the machine, through the
19
+ * summary. Any failure leaves the session as it was.
20
+ *
21
+ * @param store - Per-session state store.
22
+ * @param sessionId - Provider session id.
23
+ * @param options - Tracking options.
24
+ * @param cuts - How many earlier walks the deadline cut.
25
+ */
26
+ export async function rememberInheritance(store, sessionId, options, cuts = 0) {
27
+ const deadline = new AbortController();
28
+ const timer = setTimeout(() => deadline.abort(), WALK_DEADLINE_MS);
29
+ let found;
30
+ let threw = false;
31
+ try {
32
+ // Raced, not merely checked: a `ps` that never answers must not hold the
33
+ // agent's hook. The deadline also kills the walk's `ps`/`lsof` children,
34
+ // and the abandoned walk writes nothing after it.
35
+ found = await Promise.race([walk(store, sessionId, options, deadline.signal), new Promise((resolve) => deadline.signal.addEventListener('abort', () => resolve(undefined)))]);
36
+ }
37
+ catch {
38
+ // A fixed sentence: the error could quote a path or a process.
39
+ debugLog('could not walk the processes above the agent');
40
+ threw = true;
41
+ }
42
+ finally {
43
+ clearTimeout(timer);
44
+ }
45
+ const cut = deadline.signal.aborted;
46
+ if (cut)
47
+ debugLog('the walk above the agent ran out of time');
48
+ // A cut or failed walk is counted, to be tried again; one that ended is
49
+ // final. A first walk that found nothing has nothing to write; a retry that
50
+ // found nothing still overwrites its count, so it is not walked again.
51
+ const memo = cut || threw ? { cuts: cuts + 1 } : (found ?? (cuts > 0 ? {} : undefined));
52
+ if (memo === undefined)
53
+ return;
54
+ try {
55
+ // ponytail: read-then-write, not a lock. Two hooks of one session racing
56
+ // their retries could both pass; the later one keeps its hands off an
57
+ // answer the other wrote. The window is one file read wide.
58
+ if (cuts > 0 && (await store.readInherited(sessionId))?.cuts !== cuts)
59
+ return;
60
+ await store.rememberInherited(sessionId, memo);
61
+ }
62
+ catch {
63
+ debugLog('could not remember what the session inherited');
64
+ }
65
+ }
66
+ /**
67
+ * Walk again when the session's last walk was cut by its deadline, or failed.
68
+ *
69
+ * A busy machine can push `ps` past the deadline, and a cut walk read as final
70
+ * leaves every turn of the session without its repository. Each retry has the
71
+ * same deadline as the first walk, at most one runs per hook, and after
72
+ * {@link MAX_WALK_ATTEMPTS} the session gives up. A session whose walk ended
73
+ * pays one small file read per hook and never walks again.
74
+ *
75
+ * @param store - Per-session state store.
76
+ * @param sessionId - Provider session id.
77
+ * @param options - Tracking options.
78
+ */
79
+ export async function retryInheritance(store, sessionId, options) {
80
+ const cuts = (await store.readInherited(sessionId).catch(() => undefined))?.cuts ?? 0;
81
+ if (cuts === 0 || cuts >= MAX_WALK_ATTEMPTS)
82
+ return;
83
+ // From where the session started, as the first walk was: the agent may have
84
+ // moved into a checkout since, and that must not decide what it inherited.
85
+ const start = await store.readStart(sessionId).catch(() => undefined);
86
+ await rememberInheritance(store, sessionId, { ...options, cwd: start ?? options.cwd }, cuts);
87
+ }
88
+ async function walk(store, sessionId, options, expired) {
89
+ const table = options.env.processes ?? systemProcessTable(expired);
90
+ const walks = options.config.capture.git && (await checkoutRootOf(options.cwd)) === undefined;
91
+ // Together: the listing and the agent's own line are two `ps` runs.
92
+ const [listing, agent] = await Promise.all([walks ? table.snapshot() : undefined, agentProcess(table)]);
93
+ if (!agent || expired.aborted)
94
+ return undefined;
95
+ await store.rememberAgentProcess(sessionId, { pid: agent.pid, started: agent.started });
96
+ // Checked again before each further lookup: past the deadline a `ps` would be spawned only to be killed.
97
+ if (!listing || expired.aborted)
98
+ return undefined;
99
+ const chain = ancestorChain(listing, agent.pid);
100
+ const parent = await liveParentOf(store, sessionId, chain, table);
101
+ // The parent's checkout is read again at the close, when it is freshest, but
102
+ // kept here too: a parent that ends first must not take the answer with it.
103
+ // The ancestors' folders are looked up only when the parent cannot answer.
104
+ const parentRoot = parent === undefined ? undefined : (await store.readWorkCheckout(parent))?.root;
105
+ const root = parentRoot ?? (expired.aborted ? undefined : await nearestCheckout(table.cwds.bind(table), chain.map((ancestor) => ancestor.pid)));
106
+ if (expired.aborted || (parent === undefined && root === undefined))
107
+ return undefined;
108
+ return { parent, root };
109
+ }
110
+ /**
111
+ * The checkout this session inherited, as of now.
112
+ *
113
+ * The nearest live parent agent session's last work checkout; failing that,
114
+ * the checkout the nearest ancestor's folder lay in. A parent that has ended or
115
+ * expired is skipped, and so is anything the caller does not admit.
116
+ *
117
+ * @param store - Per-session state store.
118
+ * @param sessionId - Provider session id.
119
+ * @param admits - The session's admission test for a checkout.
120
+ * @returns The checkout, or undefined when the session inherited none.
121
+ */
122
+ export async function resolveInherited(store, sessionId, admits) {
123
+ const memo = await store.readInherited(sessionId);
124
+ if (!memo)
125
+ return undefined;
126
+ const parentMemo = memo.parent !== undefined && (await store.isLive(memo.parent, TURN_STATE_TTL_MS)) ? await store.readWorkCheckout(memo.parent) : undefined;
127
+ if (parentMemo && admits(parentMemo.root))
128
+ return { root: canonicalRoot(parentMemo.root), parentSessionId: memo.parent };
129
+ if (memo.root === undefined || !path.isAbsolute(memo.root) || !admits(memo.root))
130
+ return undefined;
131
+ return { root: canonicalRoot(memo.root) };
132
+ }
133
+ async function liveParentOf(store, sessionId, chain, table) {
134
+ for (const ancestor of chain) {
135
+ const hit = await store.sessionOfAgent(ancestor.pid);
136
+ if (!hit || hit.sessionId === sessionId)
137
+ continue;
138
+ // The start time is asked only of a pid that was an agent: a reused one is not.
139
+ if (hit.started !== undefined && (await table.info(ancestor.pid))?.started !== hit.started)
140
+ continue;
141
+ if (await store.isLive(hit.sessionId, TURN_STATE_TTL_MS))
142
+ return hit.sessionId;
143
+ }
144
+ return undefined;
145
+ }
146
+ async function nearestCheckout(cwds, pids) {
147
+ const folders = await cwds(pids);
148
+ for (const pid of pids) {
149
+ const folder = folders.get(pid);
150
+ const root = folder !== undefined && path.isAbsolute(folder) ? await checkoutRootOf(folder) : undefined;
151
+ if (root !== undefined)
152
+ return root;
153
+ }
154
+ return undefined;
155
+ }
@@ -0,0 +1,26 @@
1
+ import type { Env } from '../core/types/core.types.js';
2
+ import type { SessionTitles } from './types/transcript.types.js';
3
+ /**
4
+ * Read the name and generated title Codex keeps for one thread.
5
+ *
6
+ * Codex does not put either value in its hook payload or rollout. Its own
7
+ * read-model database is therefore the source, opened read-only and queried by
8
+ * the hook's session id.
9
+ *
10
+ * @param env - Environment locating `$CODEX_HOME` or `~/.codex`.
11
+ * @param sessionId - Codex thread id from the hook payload.
12
+ * @returns Codex's latest name and generated title, or neither when unavailable.
13
+ */
14
+ export declare function readCodexSessionTitles(env: Env, sessionId: string): Promise<SessionTitles>;
15
+ /**
16
+ * Read Cursor's generated conversation title from its local search index.
17
+ *
18
+ * Cursor exposes no title in hooks or transcripts. The desktop app's search
19
+ * index keys the same conversation id the hook sends; Cursor keeps custom and
20
+ * generated titles in one display field, so it maps to `session_title`.
21
+ *
22
+ * @param env - Environment locating Cursor's platform data directory.
23
+ * @param sessionId - Cursor conversation id from the hook payload.
24
+ * @returns Cursor's display title, or neither when unavailable.
25
+ */
26
+ export declare function readCursorSessionTitles(env: Env, sessionId: string): Promise<SessionTitles>;
@@ -0,0 +1,102 @@
1
+ import fs from 'node:fs/promises';
2
+ import { createRequire } from 'node:module';
3
+ import path from 'node:path';
4
+ import { asRecord, compact } from '../core/object.js';
5
+ import { codexHome } from '../providers/codex/codex.detect.js';
6
+ const CODEX_STATE_DATABASE = /^state_(\d+)\.sqlite$/;
7
+ const require = createRequire(import.meta.url);
8
+ /**
9
+ * Read the name and generated title Codex keeps for one thread.
10
+ *
11
+ * Codex does not put either value in its hook payload or rollout. Its own
12
+ * read-model database is therefore the source, opened read-only and queried by
13
+ * the hook's session id.
14
+ *
15
+ * @param env - Environment locating `$CODEX_HOME` or `~/.codex`.
16
+ * @param sessionId - Codex thread id from the hook payload.
17
+ * @returns Codex's latest name and generated title, or neither when unavailable.
18
+ */
19
+ export async function readCodexSessionTitles(env, sessionId) {
20
+ const sqlite = sqliteModule();
21
+ if (!sqlite)
22
+ return {};
23
+ const home = codexHome(env);
24
+ const entries = await fs.readdir(home, { withFileTypes: true });
25
+ const databases = entries
26
+ .flatMap((entry) => {
27
+ const match = entry.isFile() && CODEX_STATE_DATABASE.exec(entry.name);
28
+ return match ? [{ path: path.join(home, entry.name), version: Number(match[1]) }] : [];
29
+ })
30
+ .sort((left, right) => right.version - left.version);
31
+ for (const database of databases) {
32
+ const titles = readTitles(sqlite, database.path, 'SELECT title, name FROM threads WHERE id = ?', sessionId);
33
+ if (titles.custom || titles.generated)
34
+ return titles;
35
+ }
36
+ return {};
37
+ }
38
+ /**
39
+ * Read Cursor's generated conversation title from its local search index.
40
+ *
41
+ * Cursor exposes no title in hooks or transcripts. The desktop app's search
42
+ * index keys the same conversation id the hook sends; Cursor keeps custom and
43
+ * generated titles in one display field, so it maps to `session_title`.
44
+ *
45
+ * @param env - Environment locating Cursor's platform data directory.
46
+ * @param sessionId - Cursor conversation id from the hook payload.
47
+ * @returns Cursor's display title, or neither when unavailable.
48
+ */
49
+ export async function readCursorSessionTitles(env, sessionId) {
50
+ const sqlite = sqliteModule();
51
+ const database = cursorSearchDatabase(env);
52
+ if (!sqlite || !database)
53
+ return {};
54
+ return readTitles(sqlite, database, "SELECT title FROM conversations WHERE source = 'local' AND scope = '' AND id = ?", sessionId);
55
+ }
56
+ /**
57
+ * Open one provider-owned read model and return only its title fields.
58
+ *
59
+ * ponytail: the synchronous stdlib query can briefly block one Stop hook; it is
60
+ * one indexed local lookup. Move it to a worker if measured hook latency makes
61
+ * that visible.
62
+ */
63
+ function readTitles(sqlite, databasePath, query, sessionId) {
64
+ let database;
65
+ try {
66
+ database = new sqlite.DatabaseSync(databasePath, { readOnly: true });
67
+ const row = asRecord(database.prepare(query).get(sessionId));
68
+ return compact({
69
+ custom: typeof row?.['name'] === 'string' ? row['name'] : undefined,
70
+ generated: typeof row?.['title'] === 'string' ? row['title'] : undefined
71
+ });
72
+ }
73
+ catch {
74
+ return {};
75
+ }
76
+ finally {
77
+ database?.close();
78
+ }
79
+ }
80
+ /** Node added enforced read-only SQLite opens in 22.12. */
81
+ function sqliteModule() {
82
+ const [major = 0, minor = 0] = process.versions.node.split('.').map(Number);
83
+ if (major < 22 || (major === 22 && minor < 12))
84
+ return undefined;
85
+ try {
86
+ return require('node:sqlite');
87
+ }
88
+ catch {
89
+ return undefined;
90
+ }
91
+ }
92
+ /** Cursor's search index path on each supported desktop platform. */
93
+ function cursorSearchDatabase(env) {
94
+ const suffix = ['Cursor', 'User', 'globalStorage', 'conversation-search.db'];
95
+ if (env.platform === 'darwin')
96
+ return path.join(env.home, 'Library', 'Application Support', ...suffix);
97
+ if (env.platform === 'linux')
98
+ return path.join(env.vars['XDG_CONFIG_HOME'] ?? path.join(env.home, '.config'), ...suffix);
99
+ if (env.platform === 'win32' && env.vars['APPDATA'])
100
+ return path.join(env.vars['APPDATA'], ...suffix);
101
+ return undefined;
102
+ }
@@ -1,8 +1,8 @@
1
1
  import type { ReadTurnUsageRetry, TranscriptUsageEntry, TurnUsage } from './types/transcript.types.js';
2
2
  /** One read pass over a transcript. */
3
- export type TranscriptPass = () => Promise<TurnUsage | undefined>;
3
+ type TranscriptPass = () => Promise<TurnUsage | undefined>;
4
4
  /** How the settle loop should treat a transcript that reports no usage at all. */
5
- export interface SettleOptions {
5
+ interface SettleOptions {
6
6
  /**
7
7
  * Stop immediately when the very first pass finds nothing.
8
8
  *
@@ -72,3 +72,4 @@ export declare function accumulateUsage(entries: ReadonlyMap<string, TranscriptU
72
72
  * @returns The object, or undefined when the line is not one.
73
73
  */
74
74
  export declare function parseJsonLine(line: string): Record<string, unknown> | undefined;
75
+ export {};
@@ -120,7 +120,11 @@ export function accumulateUsage(entries) {
120
120
  async function readTailBytes(transcriptPath, size) {
121
121
  const handle = await fs.open(transcriptPath, 'r');
122
122
  try {
123
- const buffer = Buffer.alloc(TRANSCRIPT_TAIL_BYTES);
123
+ // Unzeroed: `read` fills [0, bytesRead) and only that slice is ever decoded,
124
+ // so no uninitialized byte can escape — and the settle loop runs this up to
125
+ // USAGE_RETRY.attempts times per Stop, each of which was zero-filling a
126
+ // whole tail buffer before overwriting it.
127
+ const buffer = Buffer.allocUnsafe(TRANSCRIPT_TAIL_BYTES);
124
128
  const { bytesRead } = await handle.read(buffer, 0, TRANSCRIPT_TAIL_BYTES, size - TRANSCRIPT_TAIL_BYTES);
125
129
  const raw = buffer.subarray(0, bytesRead).toString('utf8');
126
130
  // Drop the first, almost certainly partial, line.