@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
@@ -43,6 +43,8 @@ export const USAGE_RETRY = { attempts: 6, delayMs: 250, minSettleMs: 500 };
43
43
  export const TRANSCRIPT_TAIL_BYTES = 4 * 1024 * 1024;
44
44
  /** Payload key every supported agent reports its transcript path under. */
45
45
  export const TRANSCRIPT_PATH_KEY = 'transcript_path';
46
+ /** Marker of a closed turn; no `.json`, so it is never read as a record (AWT-701). */
47
+ export const CLOSED_TURN_PREFIX = 'closed-turn--';
46
48
  /** Prefix distinguishing usage-claim files from turn records in a session dir. */
47
49
  export const USAGE_CLAIM_PREFIX = 'usage-claim--';
48
50
  /**
@@ -50,6 +52,11 @@ export const USAGE_CLAIM_PREFIX = 'usage-claim--';
50
52
  * session is on, so a later hook's gate can state it.
51
53
  */
52
54
  export const SESSION_MODEL_FILE = 'session.json';
55
+ /**
56
+ * The mode the agent named when the session started: `{ mode?, isCloudAgent? }`.
57
+ * Cursor says it on sessionStart alone, and every turn summary of the session carries it.
58
+ */
59
+ export const SESSION_MODE_FILE = 'session-mode.json';
53
60
  /** The folder the session started in, written once by its first hook: `{ cwd }`. */
54
61
  export const SESSION_START_FILE = 'session-start.json';
55
62
  /**
@@ -74,11 +81,13 @@ export const INHERITED_CHECKOUT_FILE = 'inherited-checkout.json';
74
81
  * prompt can never move the session. Local only; the keys ride the summary.
75
82
  */
76
83
  export const PROMPT_TICKETS_FILE = 'prompt-tickets.json';
84
+ /** Session files SessionEnd keeps for a resume under the same id: the opening prompt's keys and the session mode. */
85
+ export const SESSION_RESUME_FILES = new Set([PROMPT_TICKETS_FILE, SESSION_MODE_FILE]);
77
86
  /**
78
- * Files that say nothing about whether a session is still running. The prompt
79
- * memo outlives SessionEnd on purpose, so it must not keep the session live.
87
+ * Files that say nothing about whether a session is still running. The resume
88
+ * memos outlive SessionEnd on purpose, so they must not keep the session live.
80
89
  */
81
- export const LIVENESS_IGNORED_FILES = new Set([PROMPT_TICKETS_FILE]);
90
+ export const LIVENESS_IGNORED_FILES = SESSION_RESUME_FILES;
82
91
  /** Directory of the state root indexing live agent pids to their session: `<pid>.json`. Not a session. */
83
92
  export const AGENT_PIDS_DIR = 'agent-pids';
84
93
  /** Prefix of the once-per-session notice marker a checkout takes: `untraced-<root hash>.json`. Not a turn record. */
@@ -99,6 +108,7 @@ export const BILLING_SENT_FILE = 'billing-sent.json';
99
108
  export const SESSION_FILES = new Set([
100
109
  BILLING_SENT_FILE,
101
110
  SESSION_MODEL_FILE,
111
+ SESSION_MODE_FILE,
102
112
  SESSION_TITLE_FILE,
103
113
  SESSION_START_FILE,
104
114
  WORK_CHECKOUT_FILE,
@@ -112,16 +122,6 @@ export const CHECKOUT_RECORD_PREFIX = 'checkout--';
112
122
  export const CHECKOUT_KEY_HASH_LENGTH = 16;
113
123
  /** Checkouts one turn may name; past it, new ones are ignored (seven days of real turns peak at five). */
114
124
  export const MAX_TURN_CHECKOUTS = 8;
115
- /** Public provider labels; the internal id is an implementation detail. */
116
- export const PROVIDER_LABELS = {
117
- claude: 'claude-code',
118
- codex: 'codex',
119
- cursor: 'cursor',
120
- gemini: 'gemini',
121
- antigravity: 'antigravity'
122
- };
123
- /** Providers whose sessions run inside an editor rather than a terminal. */
124
- export const IDE_SURFACE_PROVIDERS = new Set(['cursor', 'antigravity']);
125
125
  /**
126
126
  * The session id of the agent session that launched this one, set by the
127
127
  * launcher (a spinoff in a new terminal tab, a review bot). Hooks inherit the
@@ -130,15 +130,11 @@ export const IDE_SURFACE_PROVIDERS = new Set(['cursor', 'antigravity']);
130
130
  export const PARENT_SESSION_VAR = 'AGENTWATCH_PARENT_SESSION';
131
131
  /** What a declared parent session id may look like: a provider session id, never free text. */
132
132
  export const RE_PARENT_SESSION_ID = /^[\w.:-]{1,200}$/;
133
- /** Claude Code reports its own surface here. */
134
- export const CLAUDE_ENTRYPOINT_VAR = 'CLAUDE_CODE_ENTRYPOINT';
135
133
  export const DEFAULT_SURFACE = 'cli';
136
134
  export const EXEC_SURFACE = 'exec';
137
- /** `session_meta.originator` Codex writes for a headless `codex exec` run. */
138
- export const CODEX_EXEC_ORIGINATOR = 'codex_exec';
139
- /** How much of a Codex transcript to read for its `session_meta` line (about 20 KB in practice). */
140
- export const CODEX_META_HEAD_BYTES = 256 * 1024;
141
135
  export const IDE_SURFACE = 'ide';
136
+ /** A session the agent runs in the vendor's cloud (`session.isCloudAgent`), whichever agent it is. */
137
+ export const CLOUD_SURFACE = 'cloud';
142
138
  /**
143
139
  * Cap on `files_touched` and `files_read`, matching the platform's own limit on
144
140
  * either list.
@@ -1,4 +1,4 @@
1
- import type { ReadTurnUsageRetry, TurnUsage } from './types/transcript.types.js';
1
+ import type { ReadTurnUsageRetry, TranscriptUsageEntry, TurnUsage } from './types/transcript.types.js';
2
2
  /**
3
3
  * Per-turn token usage from a Gemini CLI chat file
4
4
  * (`~/.gemini/tmp/<project>/chats/session-*.jsonl`).
@@ -28,3 +28,21 @@ import type { ReadTurnUsageRetry, TurnUsage } from './types/transcript.types.js'
28
28
  * @returns The turn's usage, or undefined when the file reports none.
29
29
  */
30
30
  export declare function readGeminiTurnUsage(transcriptPath: string, sinceIso: string, retry?: ReadTurnUsageRetry, untilIso?: string, excludeMessageIds?: ReadonlySet<string>): Promise<TurnUsage | undefined>;
31
+ /**
32
+ * The usage one chat-file record carries, when it is a reply with `tokens`.
33
+ *
34
+ * Shared with replay, which reads whole chat files, so both count a reply the same way.
35
+ *
36
+ * @param row - One message record.
37
+ * @returns The reply's model and counts, or undefined for any other record.
38
+ */
39
+ export declare function geminiReplyUsage(row: Readonly<Record<string, unknown>>): TranscriptUsageEntry | undefined;
40
+ /**
41
+ * The message records one chat-file line carries: the line itself, or, for a
42
+ * `{"$set": {"messages": [...]}}` snapshot (a resumed or rewritten session),
43
+ * each message inside it.
44
+ *
45
+ * @param row - The parsed line.
46
+ * @returns The records to look at.
47
+ */
48
+ export declare function replyRows(row: Record<string, unknown> | undefined): readonly Record<string, unknown>[];
@@ -1,6 +1,6 @@
1
1
  import { asRecord, firstStringOf } from '../core/object.js';
2
2
  import { finiteOrZero } from '../core/number.js';
3
- import { accumulateUsage, parseJsonLine, readTranscriptTail, readUntilSettled } from './transcript.js';
3
+ import { accumulateUsage, parseJsonLine, readUntilSettled, readWindowedTail } from './transcript.js';
4
4
  import { GEMINI_REPLY_TYPE, GEMINI_TOKENS, TRANSCRIPT_CACHE_READ_TOKENS, TRANSCRIPT_INPUT_TOKENS, TRANSCRIPT_OUTPUT_TOKENS } from './constants/turns.constants.js';
5
5
  /**
6
6
  * Per-turn token usage from a Gemini CLI chat file
@@ -43,38 +43,49 @@ export async function readGeminiTurnUsage(transcriptPath, sinceIso, retry, until
43
43
  * @returns The usage found in this pass.
44
44
  */
45
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)
46
+ const tail = await readWindowedTail(transcriptPath, sinceIso, untilIso);
47
+ if (tail === undefined)
52
48
  return undefined;
49
+ const { raw, since, until } = tail;
53
50
  // Later rows with the same id replace earlier ones: the rewrite is the one with tokens.
54
51
  const byId = new Map();
55
52
  for (const line of raw.split('\n')) {
56
53
  if (!line.includes(`"${GEMINI_TOKENS}"`))
57
54
  continue;
58
55
  for (const row of replyRows(parseJsonLine(line))) {
59
- const tokens = asRecord(row[GEMINI_TOKENS]);
56
+ const entry = geminiReplyUsage(row);
60
57
  const id = firstStringOf(row['id']);
61
58
  const timestamp = typeof row['timestamp'] === 'string' ? Date.parse(row['timestamp']) : NaN;
62
- if (!tokens || !id || row['type'] !== GEMINI_REPLY_TYPE)
59
+ if (!entry || !id)
63
60
  continue;
64
61
  if (Number.isNaN(timestamp) || timestamp < since || timestamp > until || excludeMessageIds?.has(id))
65
62
  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
- });
63
+ byId.set(id, entry);
74
64
  }
75
65
  }
76
66
  return accumulateUsage(byId);
77
67
  }
68
+ /**
69
+ * The usage one chat-file record carries, when it is a reply with `tokens`.
70
+ *
71
+ * Shared with replay, which reads whole chat files, so both count a reply the same way.
72
+ *
73
+ * @param row - One message record.
74
+ * @returns The reply's model and counts, or undefined for any other record.
75
+ */
76
+ export function geminiReplyUsage(row) {
77
+ const tokens = asRecord(row[GEMINI_TOKENS]);
78
+ if (!tokens || row['type'] !== GEMINI_REPLY_TYPE)
79
+ return undefined;
80
+ return {
81
+ model: firstStringOf(row['model']),
82
+ usage: {
83
+ [TRANSCRIPT_INPUT_TOKENS]: finiteOrZero(tokens['input']) + finiteOrZero(tokens['tool']),
84
+ [TRANSCRIPT_OUTPUT_TOKENS]: finiteOrZero(tokens['output']) + finiteOrZero(tokens['thoughts']),
85
+ [TRANSCRIPT_CACHE_READ_TOKENS]: finiteOrZero(tokens['cached'])
86
+ }
87
+ };
88
+ }
78
89
  /**
79
90
  * The message records one chat-file line carries: the line itself, or, for a
80
91
  * `{"$set": {"messages": [...]}}` snapshot (a resumed or rewritten session),
@@ -83,7 +94,7 @@ async function readOnce(transcriptPath, sinceIso, untilIso, excludeMessageIds) {
83
94
  * @param row - The parsed line.
84
95
  * @returns The records to look at.
85
96
  */
86
- function replyRows(row) {
97
+ export function replyRows(row) {
87
98
  if (!row)
88
99
  return [];
89
100
  const snapshot = asRecord(row['$set'])?.['messages'];
@@ -6,13 +6,12 @@
6
6
  export type { AgentUsageSummary, BuildTurnSummaryInput, ToolEvent, TouchedFiles, TurnSummaryEvent, TurnUsageStatus } from './types/turn-summary.types.js';
7
7
  export type { PromptRecord, ResponseRecord, SessionModelRecord, ToolRecord, ToolStartRecord, TurnRecord, TurnStateEntry } from './types/turn-state.types.js';
8
8
  export type { ReadTurnUsageRetry, TranscriptReader, TranscriptUsageEntry, TurnUsage } from './types/transcript.types.js';
9
- export type { TrackTurnOptions, TurnWindow } from './types/turn-tracker.types.js';
9
+ export type { TrackTurnOptions, TurnOutcome, TurnWindow } from './types/turn-tracker.types.js';
10
10
  export type { AggregateTurnUsageOptions, UsageTotals } from './types/aggregate-usage.types.js';
11
- export { PROVIDER_LABELS, TURN_STATE_TTL_MS, USAGE_RETRY } from './constants/turns.constants.js';
11
+ export { TURN_STATE_TTL_MS, USAGE_RETRY } from './constants/turns.constants.js';
12
12
  export { buildToolEvents } from './tool-events.js';
13
13
  export { buildTurnSummary } from './turn-summary.js';
14
14
  export { TurnStateStore } from './turn-state.js';
15
15
  export { readTurnUsage } from './claude-transcript.js';
16
- export { readCursorTurnUsage } from './cursor-transcript.js';
17
- export { trackTurn } from './turn-tracker.js';
16
+ export { trackTurnOutcome } from './turn-tracker.js';
18
17
  export { aggregateTurnUsage } from './aggregate-usage.js';
@@ -1,8 +1,7 @@
1
- export { PROVIDER_LABELS, TURN_STATE_TTL_MS, USAGE_RETRY } from './constants/turns.constants.js';
1
+ export { TURN_STATE_TTL_MS, USAGE_RETRY } from './constants/turns.constants.js';
2
2
  export { buildToolEvents } from './tool-events.js';
3
3
  export { buildTurnSummary } from './turn-summary.js';
4
4
  export { TurnStateStore } from './turn-state.js';
5
5
  export { readTurnUsage } from './claude-transcript.js';
6
- export { readCursorTurnUsage } from './cursor-transcript.js';
7
- export { trackTurn } from './turn-tracker.js';
6
+ export { trackTurnOutcome } from './turn-tracker.js';
8
7
  export { aggregateTurnUsage } from './aggregate-usage.js';
@@ -0,0 +1,71 @@
1
+ import type { LaunchedRun } from '../capture/types/capture.types.js';
2
+ import type { TurnStateStore } from './turn-state.js';
3
+ /**
4
+ * The run a process belongs to: the newest one naming its script, else the newest one.
5
+ *
6
+ * Time alone cannot tell. An agent runs a message's shell calls concurrently, so a
7
+ * `python a.py` and a `sed` beside it both have their hooks done before either starts,
8
+ * and "newest" reads `sed`. The script's name settles it, and gets a little slack past
9
+ * the process's start for the same race. Without a match (`make eval` running
10
+ * `eval.py`, `python -c`) it falls back to time.
11
+ *
12
+ * ponytail: two concurrent runs of one script, or a nameless process beside another
13
+ * run, can still pick the neighbour.
14
+ *
15
+ * @param runs - A session's runs.
16
+ * @param at - The process's ISO start time.
17
+ * @param script - The file name the process says it runs, when it has one.
18
+ * @returns The run, or undefined when none is that old.
19
+ */
20
+ export declare function latestRunIn(runs: readonly LaunchedRun[], at: string, script?: string): LaunchedRun | undefined;
21
+ /**
22
+ * The runs a session launched, and when a captured call of one was last seen.
23
+ *
24
+ * Beside `TurnStateStore`, in the session's own folder, so the session's end and
25
+ * the expiry sweep take them with everything else.
26
+ */
27
+ export declare class RunStateStore {
28
+ private readonly store;
29
+ /**
30
+ * Bind to the session state store.
31
+ *
32
+ * @param store - The store that owns the session folders.
33
+ */
34
+ constructor(store: TurnStateStore);
35
+ /**
36
+ * Remember a shell call, one small append.
37
+ *
38
+ * @param sessionId - Provider session id.
39
+ * @param run - The turn, the entry file and the time.
40
+ */
41
+ rememberRun(sessionId: string, run: LaunchedRun): Promise<void>;
42
+ /**
43
+ * The newest run started at or before a time.
44
+ *
45
+ * @param sessionId - Provider session id.
46
+ * @param at - ISO time.
47
+ * @returns The run, or undefined when none is that old.
48
+ */
49
+ latestRunBefore(sessionId: string, at: string): Promise<LaunchedRun | undefined>;
50
+ /**
51
+ * Note that a captured call of this session was attached.
52
+ *
53
+ * @param sessionId - Provider session id.
54
+ * @param at - The call's ISO time.
55
+ */
56
+ rememberCaptured(sessionId: string, at: string): Promise<void>;
57
+ /**
58
+ * When a captured call of this session was last attached.
59
+ *
60
+ * @param sessionId - Provider session id.
61
+ * @returns The ISO time, or undefined when none was.
62
+ */
63
+ lastCaptured(sessionId: string): Promise<string | undefined>;
64
+ /**
65
+ * Every run the session remembers, oldest first.
66
+ *
67
+ * @param sessionId - Provider session id.
68
+ * @returns The runs; empty when there are none.
69
+ */
70
+ runs(sessionId: string): Promise<LaunchedRun[]>;
71
+ }
@@ -0,0 +1,114 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { SECRET_FILE_MODE } from '../storage/constants/storage.constants.js';
4
+ /** Not `.json`: the turn assembler reads every `.json` in a session's folder as a record. */
5
+ const RUNS_FILE = 'runs.jsonl';
6
+ const LAST_CAPTURED_FILE = 'captured-at.txt';
7
+ const CONCURRENT_RUN_SLACK_MS = 2000;
8
+ /**
9
+ * The run a process belongs to: the newest one naming its script, else the newest one.
10
+ *
11
+ * Time alone cannot tell. An agent runs a message's shell calls concurrently, so a
12
+ * `python a.py` and a `sed` beside it both have their hooks done before either starts,
13
+ * and "newest" reads `sed`. The script's name settles it, and gets a little slack past
14
+ * the process's start for the same race. Without a match (`make eval` running
15
+ * `eval.py`, `python -c`) it falls back to time.
16
+ *
17
+ * ponytail: two concurrent runs of one script, or a nameless process beside another
18
+ * run, can still pick the neighbour.
19
+ *
20
+ * @param runs - A session's runs.
21
+ * @param at - The process's ISO start time.
22
+ * @param script - The file name the process says it runs, when it has one.
23
+ * @returns The run, or undefined when none is that old.
24
+ */
25
+ export function latestRunIn(runs, at, script) {
26
+ const limit = Date.parse(at);
27
+ let latest;
28
+ let named;
29
+ for (const run of runs) {
30
+ const when = Date.parse(run.at);
31
+ if (when <= limit && (latest === undefined || when >= Date.parse(latest.at)))
32
+ latest = run;
33
+ if (script !== undefined && when <= limit + CONCURRENT_RUN_SLACK_MS && path.basename(run.entry) === script && (named === undefined || when >= Date.parse(named.at)))
34
+ named = run;
35
+ }
36
+ return named ?? latest;
37
+ }
38
+ /**
39
+ * The runs a session launched, and when a captured call of one was last seen.
40
+ *
41
+ * Beside `TurnStateStore`, in the session's own folder, so the session's end and
42
+ * the expiry sweep take them with everything else.
43
+ */
44
+ export class RunStateStore {
45
+ store;
46
+ /**
47
+ * Bind to the session state store.
48
+ *
49
+ * @param store - The store that owns the session folders.
50
+ */
51
+ constructor(store) {
52
+ this.store = store;
53
+ }
54
+ /**
55
+ * Remember a shell call, one small append.
56
+ *
57
+ * @param sessionId - Provider session id.
58
+ * @param run - The turn, the entry file and the time.
59
+ */
60
+ async rememberRun(sessionId, run) {
61
+ const dir = this.store.sessionDir(sessionId);
62
+ await fs.mkdir(dir, { recursive: true });
63
+ await fs.appendFile(path.join(dir, RUNS_FILE), `${JSON.stringify(run)}\n`, { mode: SECRET_FILE_MODE });
64
+ }
65
+ /**
66
+ * The newest run started at or before a time.
67
+ *
68
+ * @param sessionId - Provider session id.
69
+ * @param at - ISO time.
70
+ * @returns The run, or undefined when none is that old.
71
+ */
72
+ async latestRunBefore(sessionId, at) {
73
+ return latestRunIn(await this.runs(sessionId), at);
74
+ }
75
+ /**
76
+ * Note that a captured call of this session was attached.
77
+ *
78
+ * @param sessionId - Provider session id.
79
+ * @param at - The call's ISO time.
80
+ */
81
+ async rememberCaptured(sessionId, at) {
82
+ await fs.writeFile(path.join(this.store.sessionDir(sessionId), LAST_CAPTURED_FILE), at, { mode: SECRET_FILE_MODE });
83
+ }
84
+ /**
85
+ * When a captured call of this session was last attached.
86
+ *
87
+ * @param sessionId - Provider session id.
88
+ * @returns The ISO time, or undefined when none was.
89
+ */
90
+ async lastCaptured(sessionId) {
91
+ return fs.readFile(path.join(this.store.sessionDir(sessionId), LAST_CAPTURED_FILE), 'utf8').catch(() => undefined);
92
+ }
93
+ /**
94
+ * Every run the session remembers, oldest first.
95
+ *
96
+ * @param sessionId - Provider session id.
97
+ * @returns The runs; empty when there are none.
98
+ */
99
+ async runs(sessionId) {
100
+ const text = await fs.readFile(path.join(this.store.sessionDir(sessionId), RUNS_FILE), 'utf8').catch(() => '');
101
+ const runs = [];
102
+ for (const line of text.split('\n')) {
103
+ if (line === '')
104
+ continue;
105
+ try {
106
+ runs.push(JSON.parse(line));
107
+ }
108
+ catch {
109
+ // A line a crash cut short names no run.
110
+ }
111
+ }
112
+ return runs;
113
+ }
114
+ }
@@ -2,7 +2,7 @@ import type { TurnRecord } from './types/turn-state.types.js';
2
2
  import type { ToolEvent } from './types/turn-summary.types.js';
3
3
  /**
4
4
  * The turn's tool calls as `tool_events`: each completion dated by its start,
5
- * in call order, the first {@link MAX_TURN_TOOL_EVENTS} only.
5
+ * in call order, at most {@link MAX_TURN_TOOL_EVENTS}, checks first.
6
6
  *
7
7
  * Pure over the turn's records, so a duplicate Stop sends the same list. A
8
8
  * completion with no status was written by an older release and sends no
@@ -13,3 +13,13 @@ import type { ToolEvent } from './types/turn-summary.types.js';
13
13
  * @returns The events, possibly empty.
14
14
  */
15
15
  export declare function buildToolEvents(records: readonly TurnRecord[]): ToolEvent[];
16
+ /**
17
+ * What pairs a start with its completion: the pairing key within its turn.
18
+ * Some agents' keys are unique only within a turn (Antigravity's step index),
19
+ * and a closing turn can carry another turn's late records (AWT-701).
20
+ *
21
+ * @param turnId - The record's turn id, if any.
22
+ * @param pairingKey - The record's pairing key.
23
+ * @returns The key.
24
+ */
25
+ export declare function callKey(turnId: string | undefined, pairingKey: string): string;
@@ -2,7 +2,7 @@ import { compact } from '../core/object.js';
2
2
  import { MAX_TOOL_EVENT_ID_LENGTH, MAX_TURN_TOOL_EVENTS, UNKNOWN_TOOL_NAME } from './constants/turns.constants.js';
3
3
  /**
4
4
  * The turn's tool calls as `tool_events`: each completion dated by its start,
5
- * in call order, the first {@link MAX_TURN_TOOL_EVENTS} only.
5
+ * in call order, at most {@link MAX_TURN_TOOL_EVENTS}, checks first.
6
6
  *
7
7
  * Pure over the turn's records, so a duplicate Stop sends the same list. A
8
8
  * completion with no status was written by an older release and sends no
@@ -16,27 +16,49 @@ export function buildToolEvents(records) {
16
16
  const starts = new Map();
17
17
  const calls = [];
18
18
  for (const record of records) {
19
- if (record.kind !== 'tool-start' || starts.has(record.pairingKey))
19
+ if (record.kind !== 'tool-start' || starts.has(callKey(record.turnId, record.pairingKey)))
20
20
  continue;
21
- starts.set(record.pairingKey, record.at);
21
+ starts.set(callKey(record.turnId, record.pairingKey), record.at);
22
22
  }
23
23
  for (const record of records) {
24
24
  if (record.kind !== 'tool' || record.status === undefined)
25
25
  continue;
26
- const start = record.startedAt ?? (record.pairingKey === undefined ? undefined : starts.get(record.pairingKey));
26
+ const start = record.startedAt ?? (record.pairingKey === undefined ? undefined : starts.get(callKey(record.turnId, record.pairingKey)));
27
27
  calls.push({ record, startedAt: start !== undefined && start <= record.at ? start : undefined });
28
28
  }
29
29
  // Call order is start order; a call with no start sorts by its end. Stable,
30
30
  // so calls that tie keep the order their records were written in.
31
31
  calls.sort((a, b) => (a.startedAt ?? a.record.at).localeCompare(b.startedAt ?? b.record.at));
32
32
  const events = [];
33
- for (const { record, startedAt } of calls) {
34
- if (events.length >= MAX_TURN_TOOL_EVENTS)
35
- break;
33
+ for (const { record, startedAt } of capped(calls))
36
34
  events.push(toolEvent(record, startedAt, events.length));
37
- }
38
35
  return events;
39
36
  }
37
+ /**
38
+ * What pairs a start with its completion: the pairing key within its turn.
39
+ * Some agents' keys are unique only within a turn (Antigravity's step index),
40
+ * and a closing turn can carry another turn's late records (AWT-701).
41
+ *
42
+ * @param turnId - The record's turn id, if any.
43
+ * @param pairingKey - The record's pairing key.
44
+ * @returns The key.
45
+ */
46
+ export function callKey(turnId, pairingKey) {
47
+ return `${turnId ?? ''}\u0000${pairingKey}`;
48
+ }
49
+ /**
50
+ * At most {@link MAX_TURN_TOOL_EVENTS} calls, checks first: an orchestrating
51
+ * turn runs hundreds of calls and verifies last, so the first ones alone would
52
+ * drop exactly the calls workflow waste reads (AWT-701). Call order is kept.
53
+ */
54
+ function capped(calls) {
55
+ if (calls.length <= MAX_TURN_TOOL_EVENTS)
56
+ return calls;
57
+ const isCheck = (call) => call.record.check === true && call.startedAt !== undefined;
58
+ const room = MAX_TURN_TOOL_EVENTS - calls.filter(isCheck).length;
59
+ let others = 0;
60
+ return calls.filter((call) => isCheck(call) || others++ < room).slice(0, MAX_TURN_TOOL_EVENTS);
61
+ }
40
62
  /**
41
63
  * One record on the wire, by field: never a spread, so nothing a record
42
64
  * holds besides these fields (its paths, its input) can ride along.
@@ -54,6 +76,7 @@ function toolEvent(record, startedAt, seq) {
54
76
  // A check needs its start: without one it ran for no known time.
55
77
  check: record.check === true && startedAt !== undefined ? true : undefined,
56
78
  commit: record.commit,
57
- diff_fp: record.diffFp
79
+ diff_fp: record.diffFp,
80
+ skill: record.skill
58
81
  });
59
82
  }
@@ -1,17 +1,6 @@
1
- import type { ReadTurnUsageRetry, TranscriptUsageEntry, TurnUsage } from './types/transcript.types.js';
1
+ import type { ReadTurnUsageRetry, TranscriptUsageEntry, TurnUsage, WindowedTail } from './types/transcript.types.js';
2
2
  /** One read pass over a transcript. */
3
3
  type TranscriptPass = () => Promise<TurnUsage | undefined>;
4
- /** How the settle loop should treat a transcript that reports no usage at all. */
5
- interface SettleOptions {
6
- /**
7
- * Stop immediately when the very first pass finds nothing.
8
- *
9
- * For a provider whose transcript format carries no usage today, retrying
10
- * cannot change the answer, and the settle loop would add attempts×delay of
11
- * pure latency to every Stop.
12
- */
13
- readonly bailOnFirstEmpty?: boolean;
14
- }
15
4
  /**
16
5
  * Re-read until two consecutive passes agree, or the attempts run out.
17
6
  *
@@ -23,10 +12,9 @@ interface SettleOptions {
23
12
  *
24
13
  * @param pass - Reads the transcript once.
25
14
  * @param retry - Attempt count, delay and settle window.
26
- * @param options - Provider-specific early-exit behaviour.
27
15
  * @returns The settled usage, or the last thing read.
28
16
  */
29
- export declare function readUntilSettled(pass: TranscriptPass, retry?: ReadTurnUsageRetry, options?: SettleOptions): Promise<TurnUsage | undefined>;
17
+ export declare function readUntilSettled(pass: TranscriptPass, retry?: ReadTurnUsageRetry): Promise<TurnUsage | undefined>;
30
18
  /**
31
19
  * Read the tail of a transcript file.
32
20
  *
@@ -38,6 +26,19 @@ export declare function readUntilSettled(pass: TranscriptPass, retry?: ReadTurnU
38
26
  * @returns The tail text, or undefined when the file cannot be read.
39
27
  */
40
28
  export declare function readTranscriptTail(transcriptPath: string): Promise<string | undefined>;
29
+ /**
30
+ * A transcript tail with its turn window parsed: the start of every usage pass.
31
+ *
32
+ * Entries after `until` belong to the next prompt racing into the same file.
33
+ * A late flush of *this* turn's entry still passes, because its own timestamp
34
+ * predates the Stop.
35
+ *
36
+ * @param transcriptPath - Path the provider reported.
37
+ * @param sinceIso - When the turn started.
38
+ * @param untilIso - Upper bound, or undefined for "no upper bound".
39
+ * @returns The tail and both bounds, or undefined when a bound is not a date or the file cannot be read.
40
+ */
41
+ export declare function readWindowedTail(transcriptPath: string, sinceIso: string, untilIso?: string): Promise<WindowedTail | undefined>;
41
42
  /**
42
43
  * Stable identity for a transcript entry.
43
44
  *
@@ -15,18 +15,15 @@ import { ANONYMOUS_MESSAGE_ID_PREFIX, TRANSCRIPT_CACHE_CREATION_TOKENS, TRANSCRI
15
15
  *
16
16
  * @param pass - Reads the transcript once.
17
17
  * @param retry - Attempt count, delay and settle window.
18
- * @param options - Provider-specific early-exit behaviour.
19
18
  * @returns The settled usage, or the last thing read.
20
19
  */
21
- export async function readUntilSettled(pass, retry, options = {}) {
20
+ export async function readUntilSettled(pass, retry) {
22
21
  const attempts = Math.max(1, retry?.attempts ?? 1);
23
22
  const delayMs = retry?.delayMs ?? 0;
24
23
  const minSettleMs = retry?.minSettleMs ?? 0;
25
24
  let previous;
26
25
  for (let attempt = 0; attempt < attempts; attempt++) {
27
26
  const usage = await pass();
28
- if (options.bailOnFirstEmpty && usage === undefined && previous === undefined)
29
- return undefined;
30
27
  const settled = attempt * delayMs >= minSettleMs;
31
28
  if (settled && usage && previous && sameUsage(usage, previous))
32
29
  return usage;
@@ -57,6 +54,28 @@ export async function readTranscriptTail(transcriptPath) {
57
54
  return undefined;
58
55
  }
59
56
  }
57
+ /**
58
+ * A transcript tail with its turn window parsed: the start of every usage pass.
59
+ *
60
+ * Entries after `until` belong to the next prompt racing into the same file.
61
+ * A late flush of *this* turn's entry still passes, because its own timestamp
62
+ * predates the Stop.
63
+ *
64
+ * @param transcriptPath - Path the provider reported.
65
+ * @param sinceIso - When the turn started.
66
+ * @param untilIso - Upper bound, or undefined for "no upper bound".
67
+ * @returns The tail and both bounds, or undefined when a bound is not a date or the file cannot be read.
68
+ */
69
+ export async function readWindowedTail(transcriptPath, sinceIso, untilIso) {
70
+ const since = Date.parse(sinceIso);
71
+ const until = untilIso === undefined ? Number.POSITIVE_INFINITY : Date.parse(untilIso);
72
+ if (Number.isNaN(since) || Number.isNaN(until))
73
+ return undefined;
74
+ const raw = await readTranscriptTail(transcriptPath);
75
+ if (raw === undefined)
76
+ return undefined;
77
+ return { raw, since, until };
78
+ }
60
79
  /**
61
80
  * Stable identity for a transcript entry.
62
81
  *