@agent-watch-ai/edge 0.6.0 → 0.7.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 (282) hide show
  1. package/CHANGELOG.md +219 -9
  2. package/README.md +303 -4
  3. package/dist/billing/billing-mode.d.ts +37 -5
  4. package/dist/billing/billing-mode.js +28 -19
  5. package/dist/billing/constants/billing.constants.d.ts +0 -2
  6. package/dist/billing/constants/billing.constants.js +0 -2
  7. package/dist/billing/index.d.ts +2 -1
  8. package/dist/billing/index.js +1 -1
  9. package/dist/billing/session-billing.d.ts +3 -2
  10. package/dist/billing/session-billing.js +8 -8
  11. package/dist/billing/types/billing.types.d.ts +7 -0
  12. package/dist/capture/capture-env.d.ts +147 -0
  13. package/dist/capture/capture-env.js +301 -0
  14. package/dist/capture/captured-step.d.ts +88 -0
  15. package/dist/capture/captured-step.js +479 -0
  16. package/dist/capture/constants/capture.constants.d.ts +70 -0
  17. package/dist/capture/constants/capture.constants.js +72 -0
  18. package/dist/capture/launched-runs.d.ts +16 -0
  19. package/dist/capture/launched-runs.js +151 -0
  20. package/dist/capture/node.cjs +697 -0
  21. package/dist/capture/node.d.cts +32 -0
  22. package/dist/capture/python/sitecustomize.py +823 -0
  23. package/dist/capture/schemas/capture.schema.d.ts +35 -0
  24. package/dist/capture/schemas/capture.schema.js +31 -0
  25. package/dist/capture/types/capture.types.d.ts +20 -0
  26. package/dist/cli/constants/cli.constants.d.ts +2 -6
  27. package/dist/cli/constants/cli.constants.js +3 -7
  28. package/dist/cli/context.d.ts +19 -22
  29. package/dist/cli/context.js +23 -54
  30. package/dist/cli/doctor-run-capture.d.ts +13 -0
  31. package/dist/cli/doctor-run-capture.js +19 -0
  32. package/dist/cli/doctor.js +16 -67
  33. package/dist/cli/hook.d.ts +14 -0
  34. package/dist/cli/hook.js +40 -0
  35. package/dist/cli/index.d.ts +1 -1
  36. package/dist/cli/index.js +1 -1
  37. package/dist/cli/misc.js +10 -2
  38. package/dist/cli/replay.d.ts +33 -0
  39. package/dist/cli/replay.js +193 -0
  40. package/dist/cli/setup.d.ts +10 -2
  41. package/dist/cli/setup.js +154 -26
  42. package/dist/cli/status.js +45 -5
  43. package/dist/cli/toggle.js +10 -0
  44. package/dist/cli/types/cli.types.d.ts +15 -1
  45. package/dist/cli/uninstall.js +8 -22
  46. package/dist/cli.js +104 -17
  47. package/dist/config/config.d.ts +0 -2
  48. package/dist/config/config.js +0 -1
  49. package/dist/config/constants/config.constants.js +2 -0
  50. package/dist/config/events-transport.d.ts +15 -0
  51. package/dist/config/events-transport.js +29 -0
  52. package/dist/config/index.d.ts +2 -1
  53. package/dist/config/index.js +1 -0
  54. package/dist/config/root-config.d.ts +12 -0
  55. package/dist/config/root-config.js +24 -0
  56. package/dist/config/schemas/config.schema.d.ts +13 -0
  57. package/dist/config/schemas/config.schema.js +42 -6
  58. package/dist/config/types/config.types.d.ts +7 -0
  59. package/dist/core/index.d.ts +1 -1
  60. package/dist/core/index.js +1 -1
  61. package/dist/core/version.d.ts +9 -0
  62. package/dist/core/version.js +14 -0
  63. package/dist/core/which.d.ts +11 -0
  64. package/dist/core/which.js +18 -0
  65. package/dist/credentials/cloud-claim.d.ts +32 -0
  66. package/dist/credentials/cloud-claim.js +42 -0
  67. package/dist/credentials/constants/credentials.constants.d.ts +8 -1
  68. package/dist/credentials/constants/credentials.constants.js +9 -2
  69. package/dist/credentials/device-api.d.ts +15 -1
  70. package/dist/credentials/device-api.js +12 -1
  71. package/dist/credentials/sign-in.d.ts +27 -0
  72. package/dist/credentials/sign-in.js +31 -1
  73. package/dist/credentials/token-refresher.d.ts +5 -1
  74. package/dist/credentials/token-refresher.js +10 -2
  75. package/dist/events/constants/events.constants.d.ts +5 -2
  76. package/dist/events/constants/events.constants.js +4 -1
  77. package/dist/events/index.d.ts +1 -0
  78. package/dist/events/product-event.d.ts +6 -3
  79. package/dist/events/types/events.types.d.ts +6 -0
  80. package/dist/events/types/replay-progress.types.d.ts +26 -0
  81. package/dist/events/types/replay-progress.types.js +1 -0
  82. package/dist/events/types/repo-tree.types.d.ts +2 -1
  83. package/dist/feature/ticket-candidates.d.ts +1 -1
  84. package/dist/git/checkout-root.d.ts +15 -0
  85. package/dist/git/checkout-root.js +18 -0
  86. package/dist/git/code-state.d.ts +2 -16
  87. package/dist/git/code-state.js +11 -12
  88. package/dist/git/constants/git.constants.d.ts +31 -11
  89. package/dist/git/constants/git.constants.js +36 -12
  90. package/dist/git/fingerprint.d.ts +3 -6
  91. package/dist/git/fingerprint.js +5 -8
  92. package/dist/git/git-context.js +5 -1
  93. package/dist/git/index.d.ts +1 -2
  94. package/dist/git/index.js +1 -1
  95. package/dist/git/repo-snapshot.d.ts +13 -4
  96. package/dist/git/repo-snapshot.js +47 -9
  97. package/dist/git/types/snapshot.types.d.ts +2 -0
  98. package/dist/pipeline/constants/pipeline.constants.d.ts +3 -0
  99. package/dist/pipeline/constants/pipeline.constants.js +3 -0
  100. package/dist/pipeline/hook-pipeline.js +81 -57
  101. package/dist/privacy/product-capture.js +2 -0
  102. package/dist/providers/antigravity/antigravity.capture.d.ts +2 -0
  103. package/dist/providers/antigravity/antigravity.capture.js +5 -0
  104. package/dist/providers/antigravity/antigravity.detect.js +8 -22
  105. package/dist/providers/antigravity/antigravity.provider.js +10 -3
  106. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +1 -0
  107. package/dist/providers/antigravity/constants/antigravity.constants.js +1 -0
  108. package/dist/providers/claude/claude.adapter.js +9 -6
  109. package/dist/providers/claude/claude.detect.js +2 -17
  110. package/dist/providers/claude/claude.otel.d.ts +21 -3
  111. package/dist/providers/claude/claude.otel.js +216 -61
  112. package/dist/providers/claude/claude.provider.js +17 -1
  113. package/dist/providers/claude/claude.version.d.ts +9 -0
  114. package/dist/providers/claude/claude.version.js +28 -0
  115. package/dist/providers/claude/constants/claude.constants.d.ts +27 -0
  116. package/dist/providers/claude/constants/claude.constants.js +27 -0
  117. package/dist/providers/claude/constants/claude.otel.constants.d.ts +27 -0
  118. package/dist/providers/claude/constants/claude.otel.constants.js +45 -5
  119. package/dist/providers/claude/types/claude.types.d.ts +13 -0
  120. package/dist/providers/codex/codex.capture.d.ts +76 -0
  121. package/dist/providers/codex/codex.capture.js +454 -0
  122. package/dist/providers/codex/codex.detect.js +2 -4
  123. package/dist/providers/codex/codex.otel.d.ts +38 -2
  124. package/dist/providers/codex/codex.otel.js +50 -6
  125. package/dist/providers/codex/codex.provider.js +8 -0
  126. package/dist/providers/codex/codex.surface.d.ts +9 -0
  127. package/dist/{turns/codex-originator.js → providers/codex/codex.surface.js} +17 -3
  128. package/dist/providers/codex/codex.titles.d.ts +14 -0
  129. package/dist/providers/codex/codex.titles.js +35 -0
  130. package/dist/providers/codex/constants/codex.constants.d.ts +4 -0
  131. package/dist/providers/codex/constants/codex.constants.js +4 -0
  132. package/dist/providers/cursor/constants/cursor.constants.d.ts +17 -4
  133. package/dist/providers/cursor/constants/cursor.constants.js +25 -5
  134. package/dist/providers/cursor/cursor-mcp-memo.d.ts +34 -0
  135. package/dist/providers/cursor/cursor-mcp-memo.js +94 -0
  136. package/dist/providers/cursor/cursor.adapter.js +20 -82
  137. package/dist/providers/cursor/cursor.capture.d.ts +1 -0
  138. package/dist/providers/cursor/cursor.capture.js +4 -0
  139. package/dist/providers/cursor/cursor.detect.d.ts +5 -1
  140. package/dist/providers/cursor/cursor.detect.js +11 -26
  141. package/dist/providers/cursor/cursor.hooks.js +2 -2
  142. package/dist/providers/cursor/cursor.provider.js +16 -7
  143. package/dist/providers/cursor/cursor.titles.d.ts +14 -0
  144. package/dist/providers/cursor/cursor.titles.js +20 -0
  145. package/dist/providers/cursor/schemas/cursor.schema.d.ts +3 -3
  146. package/dist/providers/cursor/schemas/cursor.schema.js +5 -3
  147. package/dist/providers/gemini/constants/gemini.constants.d.ts +16 -0
  148. package/dist/providers/gemini/constants/gemini.constants.js +17 -0
  149. package/dist/providers/gemini/gemini.capture.d.ts +81 -0
  150. package/dist/providers/gemini/gemini.capture.js +210 -0
  151. package/dist/providers/gemini/gemini.detect.js +57 -24
  152. package/dist/providers/gemini/gemini.otel.d.ts +38 -2
  153. package/dist/providers/gemini/gemini.otel.js +56 -125
  154. package/dist/providers/gemini/gemini.provider.js +5 -0
  155. package/dist/providers/index.d.ts +1 -0
  156. package/dist/providers/index.js +1 -0
  157. package/dist/providers/provider.d.ts +8 -0
  158. package/dist/providers/provider.js +9 -0
  159. package/dist/providers/registry.d.ts +14 -0
  160. package/dist/providers/registry.js +14 -0
  161. package/dist/providers/shared/constants/hook-config.constants.d.ts +2 -0
  162. package/dist/providers/shared/constants/hook-config.constants.js +2 -0
  163. package/dist/providers/shared/constants/terminal-capture.constants.d.ts +6 -0
  164. package/dist/providers/shared/constants/terminal-capture.constants.js +6 -0
  165. package/dist/providers/shared/editor-paths.d.ts +8 -0
  166. package/dist/providers/shared/editor-paths.js +18 -0
  167. package/dist/providers/shared/hook-config.d.ts +5 -0
  168. package/dist/providers/shared/hook-config.js +39 -1
  169. package/dist/providers/shared/hooks-marker.d.ts +14 -0
  170. package/dist/providers/shared/hooks-marker.js +23 -0
  171. package/dist/providers/shared/install-record.d.ts +29 -0
  172. package/dist/providers/shared/install-record.js +52 -0
  173. package/dist/providers/shared/session-title-store.d.ts +23 -0
  174. package/dist/providers/shared/session-title-store.js +50 -0
  175. package/dist/providers/shared/terminal-capture.d.ts +41 -0
  176. package/dist/providers/shared/terminal-capture.js +109 -0
  177. package/dist/providers/shared/tooling.d.ts +21 -0
  178. package/dist/providers/shared/tooling.js +36 -1
  179. package/dist/providers/types/provider.types.d.ts +57 -4
  180. package/dist/replay/checkout-resolver.d.ts +29 -0
  181. package/dist/replay/checkout-resolver.js +69 -0
  182. package/dist/replay/codex-turns.d.ts +24 -0
  183. package/dist/replay/codex-turns.js +221 -0
  184. package/dist/replay/constants/replay.constants.d.ts +99 -0
  185. package/dist/replay/constants/replay.constants.js +102 -0
  186. package/dist/replay/describe.d.ts +10 -0
  187. package/dist/replay/describe.js +31 -0
  188. package/dist/replay/gemini-turns.d.ts +36 -0
  189. package/dist/replay/gemini-turns.js +192 -0
  190. package/dist/replay/machine.d.ts +34 -0
  191. package/dist/replay/machine.js +68 -0
  192. package/dist/replay/progress-event.d.ts +21 -0
  193. package/dist/replay/progress-event.js +45 -0
  194. package/dist/replay/replay-runner.d.ts +58 -0
  195. package/dist/replay/replay-runner.js +529 -0
  196. package/dist/replay/replay-scan.d.ts +83 -0
  197. package/dist/replay/replay-scan.js +170 -0
  198. package/dist/replay/replay-state.d.ts +108 -0
  199. package/dist/replay/replay-state.js +199 -0
  200. package/dist/replay/resume.d.ts +18 -0
  201. package/dist/replay/resume.js +34 -0
  202. package/dist/replay/start.d.ts +23 -0
  203. package/dist/replay/start.js +39 -0
  204. package/dist/replay/throttle.d.ts +35 -0
  205. package/dist/replay/throttle.js +41 -0
  206. package/dist/replay/transcript-turns.d.ts +35 -0
  207. package/dist/replay/transcript-turns.js +215 -0
  208. package/dist/replay/turn-event.d.ts +38 -0
  209. package/dist/replay/turn-event.js +116 -0
  210. package/dist/replay/types/replay.types.d.ts +162 -0
  211. package/dist/replay/types/replay.types.js +1 -0
  212. package/dist/replay/window.d.ts +28 -0
  213. package/dist/replay/window.js +41 -0
  214. package/dist/snapshot/branch-selection.d.ts +40 -23
  215. package/dist/snapshot/branch-selection.js +71 -41
  216. package/dist/snapshot/constants/snapshot-stages.constants.d.ts +3 -1
  217. package/dist/snapshot/constants/snapshot-stages.constants.js +3 -1
  218. package/dist/snapshot/constants/snapshot.constants.d.ts +34 -7
  219. package/dist/snapshot/constants/snapshot.constants.js +34 -7
  220. package/dist/snapshot/index.d.ts +2 -2
  221. package/dist/snapshot/index.js +1 -1
  222. package/dist/snapshot/snapshot-pipeline.js +89 -26
  223. package/dist/snapshot/snapshot-state.js +6 -2
  224. package/dist/snapshot/tree-pipeline.d.ts +1 -1
  225. package/dist/snapshot/tree-pipeline.js +34 -15
  226. package/dist/snapshot/types/snapshot.types.d.ts +20 -3
  227. package/dist/storage/schemas/storage.schema.d.ts +2 -0
  228. package/dist/storage/schemas/storage.schema.js +6 -0
  229. package/dist/transport/delivery-stats.d.ts +13 -1
  230. package/dist/transport/delivery-stats.js +18 -2
  231. package/dist/transport/delivery.d.ts +4 -3
  232. package/dist/transport/delivery.js +21 -7
  233. package/dist/transport/identity-delivery.d.ts +20 -0
  234. package/dist/transport/identity-delivery.js +41 -0
  235. package/dist/transport/index.d.ts +2 -0
  236. package/dist/transport/index.js +1 -0
  237. package/dist/transport/types/delivery-flow.types.d.ts +7 -0
  238. package/dist/turns/claude-transcript.js +4 -12
  239. package/dist/turns/codex-transcript.d.ts +9 -0
  240. package/dist/turns/codex-transcript.js +27 -19
  241. package/dist/turns/constants/turns.constants.d.ts +13 -12
  242. package/dist/turns/constants/turns.constants.js +15 -19
  243. package/dist/turns/gemini-transcript.d.ts +19 -1
  244. package/dist/turns/gemini-transcript.js +29 -18
  245. package/dist/turns/index.d.ts +3 -4
  246. package/dist/turns/index.js +2 -3
  247. package/dist/turns/run-state.d.ts +71 -0
  248. package/dist/turns/run-state.js +114 -0
  249. package/dist/turns/tool-events.d.ts +11 -1
  250. package/dist/turns/tool-events.js +32 -9
  251. package/dist/turns/transcript.d.ts +15 -14
  252. package/dist/turns/transcript.js +23 -4
  253. package/dist/turns/turn-state.d.ts +49 -7
  254. package/dist/turns/turn-state.js +78 -10
  255. package/dist/turns/turn-summary.js +7 -2
  256. package/dist/turns/turn-tracker.d.ts +9 -16
  257. package/dist/turns/turn-tracker.js +162 -86
  258. package/dist/turns/types/transcript.types.d.ts +11 -1
  259. package/dist/turns/types/turn-provider.types.d.ts +33 -0
  260. package/dist/turns/types/turn-provider.types.js +1 -0
  261. package/dist/turns/types/turn-state.types.d.ts +9 -0
  262. package/dist/turns/types/turn-summary.types.d.ts +17 -1
  263. package/dist/turns/types/turn-tracker.types.d.ts +3 -1
  264. package/dist/turns/work-checkout.js +1 -2
  265. package/docs/AUDIT_PROMPT.md +10 -0
  266. package/docs/DATA_HANDLING.md +193 -7
  267. package/docs/ENTERPRISE_DEPLOYMENT.md +1 -1
  268. package/docs/PERFORMANCE.md +10 -0
  269. package/package.json +3 -2
  270. package/dist/events/canonical-event.d.ts +0 -10
  271. package/dist/events/canonical-event.js +0 -9
  272. package/dist/git/repository-root.d.ts +0 -39
  273. package/dist/git/repository-root.js +0 -131
  274. package/dist/git/types/repository-root.types.d.ts +0 -11
  275. package/dist/transport/transport.d.ts +0 -6
  276. package/dist/turns/codex-originator.d.ts +0 -11
  277. package/dist/turns/cursor-transcript.d.ts +0 -21
  278. package/dist/turns/cursor-transcript.js +0 -66
  279. package/dist/turns/native-session-titles.d.ts +0 -26
  280. package/dist/turns/native-session-titles.js +0 -102
  281. /package/dist/{git/types/repository-root.types.js → billing/types/billing.types.js} +0 -0
  282. /package/dist/{transport/transport.js → capture/types/capture.types.js} +0 -0
@@ -5,24 +5,25 @@ import { collectRepoTree, resolveTreeSha } from '../git/repo-tree.js';
5
5
  import { sanitizeValue } from '../privacy/sanitizer.js';
6
6
  import { budgetedRunner, remainingMs, withinBudget } from './budget.js';
7
7
  import { TREE_RETRY_INTERVAL_MS } from './constants/snapshot.constants.js';
8
- import { STAGE_ENQUEUE, STAGE_SANITIZE, STAGE_TREE_COLLECT, STAGE_TREE_DUE, STAGE_TREE_RESOLVE, STOP_BUDGET_SPENT, STOP_NO_EVENT, STOP_TREE_NOT_DUE, STOP_TREE_NO_TRUNK, STOP_TREE_SENT, STOP_TREE_UNLISTED } from './constants/snapshot-stages.constants.js';
8
+ import { STAGE_ENQUEUE, STAGE_SANITIZE, STAGE_TREE_CHANGED, STAGE_TREE_COLLECT, STAGE_TREE_DUE, STAGE_TREE_RESOLVE, STOP_BUDGET_SPENT, STOP_NO_EVENT, STOP_TREE_NOT_DUE, STOP_TREE_NO_TRUNK, STOP_TREE_SENT, STOP_TREE_UNLISTED } from './constants/snapshot-stages.constants.js';
9
9
  import { emptyState } from './snapshot-state.js';
10
10
  import { buildRepoTree } from './tree-event.js';
11
11
  /**
12
12
  * The tree flow, as the list of stages it is.
13
13
  *
14
- * Cheapest first: the stored state costs no git at all, and once the tree has
15
- * been sent it is the only stage that ever runs again.
14
+ * Cheapest first: the stored state costs no git at all, and between hourly
15
+ * checks of a sent tree it is the only stage that runs.
16
16
  */
17
17
  const TREE_STAGES = [
18
18
  step(STAGE_TREE_DUE, due),
19
19
  step(STAGE_TREE_RESOLVE, resolve),
20
+ step(STAGE_TREE_CHANGED, changed),
20
21
  step(STAGE_TREE_COLLECT, collect),
21
22
  step(STAGE_SANITIZE, sanitize),
22
23
  step(STAGE_ENQUEUE, enqueue)
23
24
  ];
24
25
  /**
25
- * Send the default branch's source paths and declaration names, once per repository and identity.
26
+ * Send the default branch's source paths and declaration names, and again whenever the trunk's tree changes.
26
27
  *
27
28
  * Shares the snapshot's deadline and never outlives it: an overrun stops
28
29
  * without recording anything, so the next turn tries again. Never throws.
@@ -44,15 +45,16 @@ export function runTreePipeline(pipeline) {
44
45
  });
45
46
  }
46
47
  /**
47
- * Whether this repository still owes its one tree.
48
+ * Whether this repository owes a tree, or a check of the one it sent.
48
49
  *
49
- * Once per repository per identity: after the first tree is queued nothing
50
- * here runs again, so an ordinary turn pays one small state read and no git
51
- * process. The files a session changes arrive in its turn summaries and branch
52
- * snapshots anyway. A new identity — a re-setup with a new credential, a
53
- * different account — owes the tree again. An attempt that failed waits out
54
- * {@link TREE_RETRY_INTERVAL_MS}, so a repository the budget cannot list costs
55
- * its second once an hour, not on every turn.
50
+ * A tree not yet sent for this identity is owed — a new identity (a re-setup
51
+ * with a new credential, a different account) owes it again. A sent tree is
52
+ * owed again when the trunk's tree oid moved, which only git can tell: so the
53
+ * oid is compared at most once per {@link TREE_RETRY_INTERVAL_MS} since the
54
+ * last send or check, and every other turn pays one small state read and no
55
+ * git process. State without a stored oid is checked once. An attempt that
56
+ * failed waits out the same interval, so a repository the budget cannot list
57
+ * costs its second once an hour, not on every turn.
56
58
  *
57
59
  * @param state - Current flow state.
58
60
  * @returns The state with what was stored, or a stop when nothing is owed yet.
@@ -60,9 +62,12 @@ export function runTreePipeline(pipeline) {
60
62
  async function due(state) {
61
63
  const stored = await state.store.read(state.input.repository);
62
64
  const tree = stored.tree;
63
- if (tree?.sentAt !== undefined && tree.sentFor === state.input.identity)
65
+ const sent = tree?.sentAt !== undefined && tree.sentFor === state.input.identity;
66
+ const now = Date.parse(state.input.capturedAt);
67
+ const waiting = now - Math.max(tree?.sentAt ?? 0, tree?.checkedAt ?? 0, tree?.triedAt ?? 0) < TREE_RETRY_INTERVAL_MS;
68
+ if (sent && tree?.sha !== undefined && waiting)
64
69
  return stop({ ...state, stored }, STOP_TREE_SENT);
65
- if (tree?.triedAt !== undefined && Date.parse(state.input.capturedAt) - tree.triedAt < TREE_RETRY_INTERVAL_MS)
70
+ if (tree?.triedAt !== undefined && (tree.triedFor ?? state.input.identity) === state.input.identity && !(sent && tree.sha !== undefined) && now - tree.triedAt < TREE_RETRY_INTERVAL_MS)
66
71
  return stop({ ...state, stored }, STOP_TREE_NOT_DUE);
67
72
  return next({ ...state, stored });
68
73
  }
@@ -80,6 +85,20 @@ async function resolve(state) {
80
85
  return stop(await triedNow(state), STOP_TREE_NO_TRUNK);
81
86
  return next({ ...state, treeSha });
82
87
  }
88
+ /**
89
+ * Stop when the trunk's tree is the one already sent, noting the check so the next one waits an hour.
90
+ *
91
+ * @param state - Current flow state, with the resolved tree oid.
92
+ * @returns The state, or a stop when the sent tree is still the trunk's.
93
+ */
94
+ async function changed(state) {
95
+ const tree = state.stored?.tree;
96
+ if (tree?.sentAt === undefined || tree.sentFor !== state.input.identity || tree.sha !== state.treeSha)
97
+ return next(state);
98
+ const stored = state.stored ?? emptyState();
99
+ await state.store.write(state.input.repository, { ...stored, tree: { ...tree, checkedAt: Date.parse(state.input.capturedAt) } }).catch(() => undefined);
100
+ return stop(state, STOP_TREE_SENT);
101
+ }
83
102
  /**
84
103
  * List the tree and search it for declaration names.
85
104
  *
@@ -115,7 +134,7 @@ async function collect(state) {
115
134
  */
116
135
  async function triedNow(state) {
117
136
  const stored = state.stored ?? emptyState();
118
- await state.store.write(state.input.repository, { ...stored, tree: { ...stored.tree, triedAt: Date.parse(state.input.capturedAt) } }).catch(() => undefined);
137
+ await state.store.write(state.input.repository, { ...stored, tree: { ...stored.tree, triedAt: Date.parse(state.input.capturedAt), triedFor: state.input.identity } }).catch(() => undefined);
119
138
  return state;
120
139
  }
121
140
  /**
@@ -7,6 +7,15 @@ export interface SnapshotStateEntry {
7
7
  readonly headSha: string;
8
8
  /** Epoch milliseconds, so an unchanged branch is still re-offered eventually. */
9
9
  readonly lastSentAt: number;
10
+ /** The default branch it was checked against; absent on entries written before it was per branch. */
11
+ readonly base?: string;
12
+ /** Found already on the trunk: not sent, and not checked again until its head or base moves. */
13
+ readonly merged?: boolean;
14
+ }
15
+ /** One branch of the snapshot's walk, and whether it has to be checked. */
16
+ export interface SnapshotCandidate {
17
+ readonly ref: BranchRef;
18
+ readonly due: boolean;
10
19
  }
11
20
  /** What was last reported about one repository. */
12
21
  export interface SnapshotState {
@@ -24,14 +33,18 @@ export interface SnapshotState {
24
33
  }
25
34
  /** Whether one repository's trunk tree has been sent, and for whom, or when it was last tried. */
26
35
  export interface SnapshotTreeEntry {
27
- /** The tree that was sent; absent when none has been yet. */
36
+ /** The trunk tree oid that was sent; the next hourly check resends when the trunk's differs. Absent when none has been yet. */
28
37
  readonly sha?: string;
29
38
  /** Epoch milliseconds the tree was queued. */
30
39
  readonly sentAt?: number;
31
40
  /** The identity fingerprint it was sent as: a different identity owes the tree again. */
32
41
  readonly sentFor?: string;
42
+ /** When the trunk's tree oid was last compared with the sent one and found unchanged. */
43
+ readonly checkedAt?: number;
33
44
  /** When an attempt last failed, so the next waits out {@link TREE_RETRY_INTERVAL_MS}. */
34
45
  readonly triedAt?: number;
46
+ /** The identity that attempt was for, so another identity is not held back by it. */
47
+ readonly triedFor?: string;
35
48
  }
36
49
  /**
37
50
  * Who and where a snapshot is about: everything the event itself carries.
@@ -55,7 +68,7 @@ export interface SnapshotFlowInput extends SnapshotIdentity {
55
68
  readonly cwd: string;
56
69
  /** Whether the effective capture policy allows file names; when not, no files listing runs. */
57
70
  readonly files: boolean;
58
- /** Fingerprint of the identity events are sent as; the tree is sent once per repository and identity. */
71
+ /** Fingerprint of the identity events are sent as; the tree is owed again for a new identity, or when the trunk's tree changes. */
59
72
  readonly identity?: string;
60
73
  readonly deadline: number;
61
74
  readonly run: GitRunner;
@@ -112,7 +125,11 @@ export interface SnapshotFlowState {
112
125
  readonly stored?: SnapshotState;
113
126
  readonly defaultBranch?: string;
114
127
  readonly refs: readonly BranchRef[];
115
- readonly selected: readonly BranchRef[];
128
+ /** The walk, newest commit first, without the branches already known to be merged. */
129
+ readonly candidates: readonly SnapshotCandidate[];
130
+ /** The checked branches found already on the trunk. */
131
+ readonly merged: readonly BranchRef[];
132
+ /** The checked live branches, which the event describes. */
116
133
  readonly branches: readonly SnapshotBranch[];
117
134
  readonly event?: RepoSnapshotEvent;
118
135
  }
@@ -8,6 +8,7 @@ import { z } from 'zod';
8
8
  */
9
9
  export declare const agentInstallSchema: z.ZodObject<{
10
10
  hooksInstalledAt: z.ZodOptional<z.ZodString>;
11
+ hooksFirstInstalledAt: z.ZodOptional<z.ZodString>;
11
12
  hookConfigPath: z.ZodOptional<z.ZodString>;
12
13
  hookEvents: z.ZodDefault<z.ZodArray<z.ZodString>>;
13
14
  hookCommand: z.ZodOptional<z.ZodString>;
@@ -23,6 +24,7 @@ export declare const installStateSchema: z.ZodObject<{
23
24
  schemaVersion: z.ZodDefault<z.ZodLiteral<1>>;
24
25
  agents: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
25
26
  hooksInstalledAt: z.ZodOptional<z.ZodString>;
27
+ hooksFirstInstalledAt: z.ZodOptional<z.ZodString>;
26
28
  hookConfigPath: z.ZodOptional<z.ZodString>;
27
29
  hookEvents: z.ZodDefault<z.ZodArray<z.ZodString>>;
28
30
  hookCommand: z.ZodOptional<z.ZodString>;
@@ -9,6 +9,12 @@ import { z } from 'zod';
9
9
  export const agentInstallSchema = z
10
10
  .object({
11
11
  hooksInstalledAt: z.string().optional(),
12
+ /**
13
+ * When AgentWatch first installed this agent's hooks on this machine, kept
14
+ * on every later setup. Replay sends no Gemini turn after it: those went
15
+ * live. Absent on an agent hooked before this was recorded.
16
+ */
17
+ hooksFirstInstalledAt: z.string().optional(),
12
18
  hookConfigPath: z.string().optional(),
13
19
  hookEvents: z.array(z.string()).default([]),
14
20
  hookCommand: z.string().optional(),
@@ -1,5 +1,10 @@
1
1
  import type { DeliveryStatsSnapshot } from './types/transport.types.js';
2
2
  export type { DeliveryStatsSnapshot } from './types/transport.types.js';
3
+ /** The tally, with the captured calls that never became queue entries. */
4
+ export interface CapturedDeliveryStats extends DeliveryStatsSnapshot {
5
+ readonly totalCapturedDropped: number;
6
+ readonly lastCapturedDroppedAt: string;
7
+ }
3
8
  /**
4
9
  * Persisted tally of everything the local queue lost, and why.
5
10
  *
@@ -23,7 +28,7 @@ export declare class DeliveryStats {
23
28
  *
24
29
  * @returns The snapshot, or undefined when there is nothing recorded.
25
30
  */
26
- read(): Promise<DeliveryStatsSnapshot | undefined>;
31
+ read(): Promise<CapturedDeliveryStats | undefined>;
27
32
  /**
28
33
  * Note events the backend refused inside an accepted batch. Never throws.
29
34
  *
@@ -36,6 +41,13 @@ export declare class DeliveryStats {
36
41
  * @param count - How many were lost.
37
42
  */
38
43
  recordDropped(count: number): Promise<void>;
44
+ /**
45
+ * Note captured calls that could not be attached to a session's run, or that
46
+ * went past a process's spool limit. Never throws.
47
+ *
48
+ * @param count - How many were dropped.
49
+ */
50
+ recordCapturedDropped(count: number): Promise<void>;
39
51
  /**
40
52
  * Note a status the transport will not retry. Never throws.
41
53
  *
@@ -35,7 +35,7 @@ export class DeliveryStats {
35
35
  try {
36
36
  const raw = JSON.parse(await fs.readFile(this.file, 'utf8'));
37
37
  // A file written before the dropped/refusal counters existed still reads.
38
- if (typeof raw.totalRejected !== 'number' && typeof raw.totalDropped !== 'number' && typeof raw.lastRefusalStatus !== 'number') {
38
+ if (typeof raw.totalRejected !== 'number' && typeof raw.totalDropped !== 'number' && typeof raw.lastRefusalStatus !== 'number' && typeof raw.totalCapturedDropped !== 'number') {
39
39
  return undefined;
40
40
  }
41
41
  return {
@@ -46,7 +46,9 @@ export class DeliveryStats {
46
46
  lastDroppedCount: numberOr(raw.lastDroppedCount, 0),
47
47
  lastDroppedAt: stringOr(raw.lastDroppedAt),
48
48
  lastRefusalStatus: numberOr(raw.lastRefusalStatus, 0),
49
- lastRefusalAt: stringOr(raw.lastRefusalAt)
49
+ lastRefusalAt: stringOr(raw.lastRefusalAt),
50
+ totalCapturedDropped: numberOr(raw.totalCapturedDropped, 0),
51
+ lastCapturedDroppedAt: stringOr(raw.lastCapturedDroppedAt)
50
52
  };
51
53
  }
52
54
  catch {
@@ -77,6 +79,18 @@ export class DeliveryStats {
77
79
  lastDroppedAt: at
78
80
  }));
79
81
  }
82
+ /**
83
+ * Note captured calls that could not be attached to a session's run, or that
84
+ * went past a process's spool limit. Never throws.
85
+ *
86
+ * @param count - How many were dropped.
87
+ */
88
+ async recordCapturedDropped(count) {
89
+ await this.record(count, (current, at) => ({
90
+ totalCapturedDropped: (current?.totalCapturedDropped ?? 0) + count,
91
+ lastCapturedDroppedAt: at
92
+ }));
93
+ }
80
94
  /**
81
95
  * Note a status the transport will not retry. Never throws.
82
96
  *
@@ -155,6 +169,8 @@ async function releaseQuietly(release) {
155
169
  */
156
170
  function emptySnapshot() {
157
171
  return {
172
+ totalCapturedDropped: 0,
173
+ lastCapturedDroppedAt: '',
158
174
  totalRejected: 0,
159
175
  lastRejectedCount: 0,
160
176
  lastRejectedAt: '',
@@ -4,8 +4,8 @@ import type { BackendCooldown } from './cooldown.js';
4
4
  import type { DeliveryStats } from './delivery-stats.js';
5
5
  import type { EventQueue } from './queue.js';
6
6
  import type { DeliveryOutcome, EventTransport } from './types/transport.types.js';
7
- export { BACKEND_COOLDOWN_MS } from './constants/transport.constants.js';
8
- export type { DeliveryOutcome } from './types/transport.types.js';
7
+ /** Refreshes the device token and returns a transport carrying it, or undefined when there is nothing to retry with. */
8
+ export type RefreshTransport = () => Promise<EventTransport | undefined>;
9
9
  /**
10
10
  * Hook-path delivery: one quick direct send, then whatever the backlog allows.
11
11
  *
@@ -29,6 +29,7 @@ export type { DeliveryOutcome } from './types/transport.types.js';
29
29
  * @param cooldown - Persisted circuit breaker, when enabled.
30
30
  * @param stats - Sink for permanent losses, when enabled.
31
31
  * @param authBlock - Persisted credential refusal, when enabled.
32
+ * @param refresh - After a plain 401, asks for a transport on a new device token; used at most once per pass.
32
33
  * @returns What was delivered, queued, drained and rejected.
33
34
  */
34
- export declare function deliverEvents(events: readonly ProductEvent[], transport: EventTransport | undefined, queue: EventQueue, drainBatchSize: number, cooldown?: BackendCooldown, stats?: DeliveryStats, authBlock?: BackendAuthBlock): Promise<DeliveryOutcome>;
35
+ export declare function deliverEvents(events: readonly ProductEvent[], transport: EventTransport | undefined, queue: EventQueue, drainBatchSize: number, cooldown?: BackendCooldown, stats?: DeliveryStats, authBlock?: BackendAuthBlock, refresh?: RefreshTransport): Promise<DeliveryOutcome>;
@@ -2,7 +2,6 @@ import { debugLog } from '../core/logger.js';
2
2
  import { next, runFlow, step } from '../core/pipe.js';
3
3
  import { ANY_DESTINATION, AUTH_REJECTED_STATUSES, BACKEND_COOLDOWN_MS, DELIVERY_STAGE_NAMES } from './constants/transport.constants.js';
4
4
  import { sendEvents } from './send.js';
5
- export { BACKEND_COOLDOWN_MS } from './constants/transport.constants.js';
6
5
  const DELIVERY_STAGES = [
7
6
  step(DELIVERY_STAGE_NAMES.select, selectDelivery),
8
7
  step(DELIVERY_STAGE_NAMES.send, sendCurrent),
@@ -33,14 +32,18 @@ const DELIVERY_STAGES = [
33
32
  * @param cooldown - Persisted circuit breaker, when enabled.
34
33
  * @param stats - Sink for permanent losses, when enabled.
35
34
  * @param authBlock - Persisted credential refusal, when enabled.
35
+ * @param refresh - After a plain 401, asks for a transport on a new device token; used at most once per pass.
36
36
  * @returns What was delivered, queued, drained and rejected.
37
37
  */
38
- export async function deliverEvents(events, transport, queue, drainBatchSize, cooldown, stats, authBlock) {
39
- const flow = await runFlow(DELIVERY_STAGES, {
40
- events, transport, queue, drainBatchSize, cooldown, stats, authBlock,
38
+ export async function deliverEvents(events, transport, queue, drainBatchSize, cooldown, stats, authBlock, refresh) {
39
+ // ponytail: `refresh` rides on the flow state beside the typed fields (the
40
+ // state type file is not part of this change); a variable avoids the excess-property check.
41
+ const initial = {
42
+ events, transport, queue, drainBatchSize, cooldown, stats, authBlock, refresh,
41
43
  canSend: false,
42
44
  outcome: { delivered: 0, queued: 0, drained: 0, rejected: 0 }
43
- });
45
+ };
46
+ const flow = await runFlow(DELIVERY_STAGES, initial);
44
47
  // A failed filesystem write must remain observable to the enclosing hook
45
48
  // flow; returning a successful outcome would falsely claim durable delivery.
46
49
  if (!flow.completed)
@@ -60,9 +63,20 @@ async function selectDelivery(state) {
60
63
  async function sendCurrent(state) {
61
64
  if (!state.canSend || !state.transport || state.events.length === 0)
62
65
  return next(state);
63
- const result = await sendEvents(state.transport, state.events);
66
+ let transport = state.transport;
67
+ let result = await sendEvents(transport, state.events);
68
+ const { refresh } = state;
69
+ // A plain 401 (no reason) for a device token means the gateway dropped it,
70
+ // e.g. a second holder refreshed: refresh once and resend once.
71
+ if (!result.ok && result.status === 401 && !result.refusal && refresh) {
72
+ const renewed = await refresh().catch(() => undefined);
73
+ if (renewed) {
74
+ transport = renewed;
75
+ result = await sendEvents(transport, state.events);
76
+ }
77
+ }
64
78
  const outcome = result.ok ? { ...state.outcome, delivered: state.events.length, rejected: result.counters?.rejected ?? 0 } : state.outcome;
65
- return next({ ...state, result, outcome });
79
+ return next({ ...state, transport, result, outcome });
66
80
  }
67
81
  async function preserveUnsent(state) {
68
82
  if (state.events.length === 0 || state.result?.ok)
@@ -0,0 +1,20 @@
1
+ import type { AgentWatchConfig } from '../config/types/config.types.js';
2
+ import type { AgentWatchPaths } from '../storage/types/storage.types.js';
3
+ import type { IdentityDelivery } from './types/delivery-flow.types.js';
4
+ /**
5
+ * The per-identity state one delivery reads and writes: the offline queue
6
+ * partition, the loss tally, the backend cooldown and the auth block.
7
+ *
8
+ * Shared by the hook and the CLI so both open the same identity's files with
9
+ * the same limits, and so they cannot drift apart on whose block or cooldown
10
+ * they read. Construction writes nothing; settling a legacy backlog is the
11
+ * caller's call.
12
+ *
13
+ * @param paths - Resolved storage paths.
14
+ * @param token - The credential naming the identity (`identityOf`); its
15
+ * files are derived once here, from these same paths.
16
+ * @param delivery - The delivery limits that apply.
17
+ * @param now - Clock for record ages, the tally, the cooldown and the block.
18
+ * @returns The four handles.
19
+ */
20
+ export declare function identityDelivery(paths: AgentWatchPaths, token: string | undefined, delivery: AgentWatchConfig['delivery'], now: () => Date): IdentityDelivery;
@@ -0,0 +1,41 @@
1
+ import { BackendAuthBlock } from './auth-block.js';
2
+ import { BackendCooldown } from './cooldown.js';
3
+ import { DeliveryStats } from './delivery-stats.js';
4
+ import { EventQueue } from './queue.js';
5
+ import { identityPaths } from './queue-partition.js';
6
+ /**
7
+ * The per-identity state one delivery reads and writes: the offline queue
8
+ * partition, the loss tally, the backend cooldown and the auth block.
9
+ *
10
+ * Shared by the hook and the CLI so both open the same identity's files with
11
+ * the same limits, and so they cannot drift apart on whose block or cooldown
12
+ * they read. Construction writes nothing; settling a legacy backlog is the
13
+ * caller's call.
14
+ *
15
+ * @param paths - Resolved storage paths.
16
+ * @param token - The credential naming the identity (`identityOf`); its
17
+ * files are derived once here, from these same paths.
18
+ * @param delivery - The delivery limits that apply.
19
+ * @param now - Clock for record ages, the tally, the cooldown and the block.
20
+ * @returns The four handles.
21
+ */
22
+ export function identityDelivery(paths, token, delivery, now) {
23
+ const identity = identityPaths(paths, token);
24
+ const stats = new DeliveryStats(identity.statsFile, now, paths.locksDir);
25
+ return {
26
+ queue: new EventQueue({
27
+ queueDir: identity.queueDir,
28
+ locksDir: paths.locksDir,
29
+ maxEvents: delivery.maxQueueEvents,
30
+ maxAttempts: delivery.maxAttempts,
31
+ maxEventAgeDays: delivery.maxEventAgeDays,
32
+ now,
33
+ // So the entries the bound sacrifices are counted wherever an enqueue
34
+ // happens, the snapshot pipeline's included.
35
+ stats
36
+ }),
37
+ stats,
38
+ cooldown: new BackendCooldown(identity.cooldownFile, now),
39
+ authBlock: new BackendAuthBlock(identity.authBlockFile, now)
40
+ };
41
+ }
@@ -12,5 +12,7 @@ export type { IdentityPaths } from './queue-partition.js';
12
12
  export { BackendCooldown } from './cooldown.js';
13
13
  export { DeliveryStats } from './delivery-stats.js';
14
14
  export { deliverEvents } from './delivery.js';
15
+ export { identityDelivery } from './identity-delivery.js';
16
+ export type { IdentityDelivery } from './types/delivery-flow.types.js';
15
17
  export { sendEvents } from './send.js';
16
18
  export { discardResponseBody, readCappedJson } from './response-body.js';
@@ -6,5 +6,6 @@ export { identityPaths, queuePartition, settleLegacyQueue, unattributedCount, un
6
6
  export { BackendCooldown } from './cooldown.js';
7
7
  export { DeliveryStats } from './delivery-stats.js';
8
8
  export { deliverEvents } from './delivery.js';
9
+ export { identityDelivery } from './identity-delivery.js';
9
10
  export { sendEvents } from './send.js';
10
11
  export { discardResponseBody, readCappedJson } from './response-body.js';
@@ -17,3 +17,10 @@ export interface DeliveryFlowState {
17
17
  readonly result?: DeliveryResult;
18
18
  readonly outcome: DeliveryOutcome;
19
19
  }
20
+ /** One identity's delivery state, opened together so the hook and the CLI read the same files. */
21
+ export interface IdentityDelivery {
22
+ readonly queue: EventQueue;
23
+ readonly stats: DeliveryStats;
24
+ readonly cooldown: BackendCooldown;
25
+ readonly authBlock: BackendAuthBlock;
26
+ }
@@ -1,6 +1,6 @@
1
1
  import { asRecord, compact } from '../core/object.js';
2
2
  import { CLAUDE_CUSTOM_TITLE_FIELDS, CLAUDE_GENERATED_TITLE_FIELDS, RE_CLAUDE_TITLE_LINE } from './constants/turns.constants.js';
3
- import { accumulateUsage, messageIdFor, parseJsonLine, readTranscriptTail, readUntilSettled } from './transcript.js';
3
+ import { accumulateUsage, messageIdFor, parseJsonLine, readTranscriptTail, readUntilSettled, readWindowedTail } from './transcript.js';
4
4
  /**
5
5
  * Authoritative per-turn token usage from Claude Code's transcript JSONL.
6
6
  *
@@ -29,18 +29,10 @@ export async function readTurnUsage(transcriptPath, sinceIso, retry, untilIso, e
29
29
  * @returns The usage found in this pass.
30
30
  */
31
31
  async function readOnce(transcriptPath, sinceIso, untilIso, excludeMessageIds) {
32
- const since = Date.parse(sinceIso);
33
- if (Number.isNaN(since))
34
- return undefined;
35
- // Entries after `until` belong to the next prompt racing into the same file.
36
- // A late FLUSH of *this* turn's entry still passes, because its own message
37
- // timestamp predates the Stop.
38
- const until = untilIso === undefined ? Number.POSITIVE_INFINITY : Date.parse(untilIso);
39
- if (Number.isNaN(until))
40
- return undefined;
41
- const raw = await readTranscriptTail(transcriptPath);
42
- if (raw === undefined)
32
+ const tail = await readWindowedTail(transcriptPath, sinceIso, untilIso);
33
+ if (tail === undefined)
43
34
  return undefined;
35
+ const { raw, since, until } = tail;
44
36
  const byMessageId = new Map();
45
37
  for (const line of raw.split('\n')) {
46
38
  if (!line.trim())
@@ -28,3 +28,12 @@ import type { ReadTurnUsageRetry, TurnUsage } from './types/transcript.types.js'
28
28
  * @returns The turn's usage, or undefined when the rollout reports none.
29
29
  */
30
30
  export declare function readCodexTurnUsage(transcriptPath: string, sinceIso: string, retry?: ReadTurnUsageRetry, untilIso?: string, excludeMessageIds?: ReadonlySet<string>): Promise<TurnUsage | undefined>;
31
+ /**
32
+ * The counts one rollout row carries, when it is an `event_msg` / `token_count` row.
33
+ *
34
+ * Shared with replay, which reads whole rollouts, so both count a request the same way.
35
+ *
36
+ * @param payload - The row's `payload`.
37
+ * @returns The request's counts under the transcript field names, or undefined for any other row.
38
+ */
39
+ export declare function codexRowUsage(payload: Readonly<Record<string, unknown>>): Readonly<Record<string, unknown>> | undefined;
@@ -1,5 +1,5 @@
1
1
  import { asRecord, firstStringOf } from '../core/object.js';
2
- import { accumulateUsage, messageIdFor, parseJsonLine, readTranscriptTail, readUntilSettled } from './transcript.js';
2
+ import { accumulateUsage, messageIdFor, parseJsonLine, readUntilSettled, readWindowedTail } from './transcript.js';
3
3
  import { CODEX_CACHED_INPUT_TOKENS, CODEX_LAST_TOKEN_USAGE, CODEX_TOKEN_COUNT, CODEX_TURN_CONTEXT, TRANSCRIPT_CACHE_READ_TOKENS, TRANSCRIPT_INPUT_TOKENS, TRANSCRIPT_OUTPUT_TOKENS } from './constants/turns.constants.js';
4
4
  /**
5
5
  * Per-turn token usage from a Codex rollout (`~/.codex/sessions/…/rollout-*.jsonl`).
@@ -42,13 +42,10 @@ export async function readCodexTurnUsage(transcriptPath, sinceIso, retry, untilI
42
42
  * @returns The usage found in this pass.
43
43
  */
44
44
  async function readOnce(transcriptPath, sinceIso, untilIso, excludeMessageIds) {
45
- const since = Date.parse(sinceIso);
46
- const until = untilIso === undefined ? Number.POSITIVE_INFINITY : Date.parse(untilIso);
47
- if (Number.isNaN(since) || Number.isNaN(until))
48
- return undefined;
49
- const raw = await readTranscriptTail(transcriptPath);
50
- if (raw === undefined)
45
+ const tail = await readWindowedTail(transcriptPath, sinceIso, untilIso);
46
+ if (tail === undefined)
51
47
  return undefined;
48
+ const { raw, since, until } = tail;
52
49
  const byRowId = new Map();
53
50
  let model;
54
51
  for (const line of raw.split('\n')) {
@@ -63,11 +60,9 @@ async function readOnce(transcriptPath, sinceIso, untilIso, excludeMessageIds) {
63
60
  model = firstStringOf(payload['model']) ?? model;
64
61
  continue;
65
62
  }
66
- if (payload['type'] !== CODEX_TOKEN_COUNT)
67
- continue;
68
- const last = asRecord(asRecord(payload['info'])?.[CODEX_LAST_TOKEN_USAGE]);
63
+ const usage = codexRowUsage(payload);
69
64
  const timestamp = typeof row['timestamp'] === 'string' ? Date.parse(row['timestamp']) : NaN;
70
- if (!last || Number.isNaN(timestamp) || timestamp < since || timestamp > until)
65
+ if (!usage || Number.isNaN(timestamp) || timestamp < since || timestamp > until)
71
66
  continue;
72
67
  // No row id in the format; the line hash carries the row's millisecond
73
68
  // timestamp (and `ordinal`, which 0.150 writes), so it is unique per request
@@ -75,14 +70,27 @@ async function readOnce(transcriptPath, sinceIso, untilIso, excludeMessageIds) {
75
70
  const id = messageIdFor(undefined, line);
76
71
  if (excludeMessageIds?.has(id))
77
72
  continue;
78
- byRowId.set(id, {
79
- model,
80
- usage: {
81
- [TRANSCRIPT_INPUT_TOKENS]: last[TRANSCRIPT_INPUT_TOKENS],
82
- [TRANSCRIPT_OUTPUT_TOKENS]: last[TRANSCRIPT_OUTPUT_TOKENS],
83
- [TRANSCRIPT_CACHE_READ_TOKENS]: last[CODEX_CACHED_INPUT_TOKENS]
84
- }
85
- });
73
+ byRowId.set(id, { model, usage });
86
74
  }
87
75
  return accumulateUsage(byRowId);
88
76
  }
77
+ /**
78
+ * The counts one rollout row carries, when it is an `event_msg` / `token_count` row.
79
+ *
80
+ * Shared with replay, which reads whole rollouts, so both count a request the same way.
81
+ *
82
+ * @param payload - The row's `payload`.
83
+ * @returns The request's counts under the transcript field names, or undefined for any other row.
84
+ */
85
+ export function codexRowUsage(payload) {
86
+ if (payload['type'] !== CODEX_TOKEN_COUNT)
87
+ return undefined;
88
+ const last = asRecord(asRecord(payload['info'])?.[CODEX_LAST_TOKEN_USAGE]);
89
+ if (!last)
90
+ return undefined;
91
+ return {
92
+ [TRANSCRIPT_INPUT_TOKENS]: last[TRANSCRIPT_INPUT_TOKENS],
93
+ [TRANSCRIPT_OUTPUT_TOKENS]: last[TRANSCRIPT_OUTPUT_TOKENS],
94
+ [TRANSCRIPT_CACHE_READ_TOKENS]: last[CODEX_CACHED_INPUT_TOKENS]
95
+ };
96
+ }
@@ -37,6 +37,8 @@ export declare const USAGE_RETRY: ReadTurnUsageRetry;
37
37
  export declare const TRANSCRIPT_TAIL_BYTES: number;
38
38
  /** Payload key every supported agent reports its transcript path under. */
39
39
  export declare const TRANSCRIPT_PATH_KEY = "transcript_path";
40
+ /** Marker of a closed turn; no `.json`, so it is never read as a record (AWT-701). */
41
+ export declare const CLOSED_TURN_PREFIX = "closed-turn--";
40
42
  /** Prefix distinguishing usage-claim files from turn records in a session dir. */
41
43
  export declare const USAGE_CLAIM_PREFIX = "usage-claim--";
42
44
  /**
@@ -44,6 +46,11 @@ export declare const USAGE_CLAIM_PREFIX = "usage-claim--";
44
46
  * session is on, so a later hook's gate can state it.
45
47
  */
46
48
  export declare const SESSION_MODEL_FILE = "session.json";
49
+ /**
50
+ * The mode the agent named when the session started: `{ mode?, isCloudAgent? }`.
51
+ * Cursor says it on sessionStart alone, and every turn summary of the session carries it.
52
+ */
53
+ export declare const SESSION_MODE_FILE = "session-mode.json";
47
54
  /** The folder the session started in, written once by its first hook: `{ cwd }`. */
48
55
  export declare const SESSION_START_FILE = "session-start.json";
49
56
  /**
@@ -68,9 +75,11 @@ export declare const INHERITED_CHECKOUT_FILE = "inherited-checkout.json";
68
75
  * prompt can never move the session. Local only; the keys ride the summary.
69
76
  */
70
77
  export declare const PROMPT_TICKETS_FILE = "prompt-tickets.json";
78
+ /** Session files SessionEnd keeps for a resume under the same id: the opening prompt's keys and the session mode. */
79
+ export declare const SESSION_RESUME_FILES: ReadonlySet<string>;
71
80
  /**
72
- * Files that say nothing about whether a session is still running. The prompt
73
- * memo outlives SessionEnd on purpose, so it must not keep the session live.
81
+ * Files that say nothing about whether a session is still running. The resume
82
+ * memos outlive SessionEnd on purpose, so they must not keep the session live.
74
83
  */
75
84
  export declare const LIVENESS_IGNORED_FILES: ReadonlySet<string>;
76
85
  /** Directory of the state root indexing live agent pids to their session: `<pid>.json`. Not a session. */
@@ -97,10 +106,6 @@ export declare const CHECKOUT_RECORD_PREFIX = "checkout--";
97
106
  export declare const CHECKOUT_KEY_HASH_LENGTH = 16;
98
107
  /** Checkouts one turn may name; past it, new ones are ignored (seven days of real turns peak at five). */
99
108
  export declare const MAX_TURN_CHECKOUTS = 8;
100
- /** Public provider labels; the internal id is an implementation detail. */
101
- export declare const PROVIDER_LABELS: Readonly<Record<string, string>>;
102
- /** Providers whose sessions run inside an editor rather than a terminal. */
103
- export declare const IDE_SURFACE_PROVIDERS: ReadonlySet<string>;
104
109
  /**
105
110
  * The session id of the agent session that launched this one, set by the
106
111
  * launcher (a spinoff in a new terminal tab, a review bot). Hooks inherit the
@@ -109,15 +114,11 @@ export declare const IDE_SURFACE_PROVIDERS: ReadonlySet<string>;
109
114
  export declare const PARENT_SESSION_VAR = "AGENTWATCH_PARENT_SESSION";
110
115
  /** What a declared parent session id may look like: a provider session id, never free text. */
111
116
  export declare const RE_PARENT_SESSION_ID: RegExp;
112
- /** Claude Code reports its own surface here. */
113
- export declare const CLAUDE_ENTRYPOINT_VAR = "CLAUDE_CODE_ENTRYPOINT";
114
117
  export declare const DEFAULT_SURFACE = "cli";
115
118
  export declare const EXEC_SURFACE = "exec";
116
- /** `session_meta.originator` Codex writes for a headless `codex exec` run. */
117
- export declare const CODEX_EXEC_ORIGINATOR = "codex_exec";
118
- /** How much of a Codex transcript to read for its `session_meta` line (about 20 KB in practice). */
119
- export declare const CODEX_META_HEAD_BYTES: number;
120
119
  export declare const IDE_SURFACE = "ide";
120
+ /** A session the agent runs in the vendor's cloud (`session.isCloudAgent`), whichever agent it is. */
121
+ export declare const CLOUD_SURFACE = "cloud";
121
122
  /**
122
123
  * Cap on `files_touched` and `files_read`, matching the platform's own limit on
123
124
  * either list.