@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
@@ -0,0 +1,35 @@
1
+ import type { ReplayTurn } from './types/replay.types.js';
2
+ /** What a prompt line says, when it is a prompt a person typed. */
3
+ interface PromptLine {
4
+ readonly sessionId: string;
5
+ readonly turnId: string;
6
+ readonly at: string;
7
+ readonly text: string;
8
+ }
9
+ /**
10
+ * Stream a Claude Code transcript as the turns the live hooks would have closed.
11
+ *
12
+ * A turn opens at a prompt a person typed and runs to the next one, as the hook
13
+ * path cuts it. One file at a time and one turn in memory: the readers the
14
+ * hooks use look only at a file's tail, and a month of sessions is megabytes
15
+ * per file. Sub-agent (`isSidechain`) lines never open a turn; their tokens
16
+ * count in the turn that ran them, as they do live, where the window is read
17
+ * from the same file. A turn with no assistant line did nothing and is not
18
+ * yielded.
19
+ *
20
+ * @param filePath - A `~/.claude/projects/<cwd>/<session>.jsonl` file.
21
+ * @param promptText - Whether to keep the prompt's text; off unless the config allows it.
22
+ * @yields Turns, oldest first.
23
+ */
24
+ export declare function readTranscriptTurns(filePath: string, promptText: boolean): AsyncGenerator<ReplayTurn>;
25
+ /**
26
+ * The prompt a user line carries, when a person typed it.
27
+ *
28
+ * Tool results are user lines too, and so are slash commands, compaction
29
+ * summaries and the interrupt marker; none is a turn.
30
+ *
31
+ * @param entry - A parsed transcript line.
32
+ * @returns The prompt, or undefined for any other line.
33
+ */
34
+ export declare function promptOf(entry: Readonly<Record<string, unknown>>): PromptLine | undefined;
35
+ export {};
@@ -0,0 +1,215 @@
1
+ import fs from 'node:fs';
2
+ import readline from 'node:readline';
3
+ import { asRecord } from '../core/object.js';
4
+ import { sha256Hex } from '../events/event-id.js';
5
+ import { CLAUDE_PROVIDER_ID } from '../providers/claude/constants/claude.constants.js';
6
+ import { classifyTool, extractFilePath } from '../providers/shared/tooling.js';
7
+ import { RE_HARNESS_BLOCK } from '../providers/shared/constants/tooling.constants.js';
8
+ import { accumulateUsage, messageIdFor, parseJsonLine } from '../turns/transcript.js';
9
+ import { DETACHED_BRANCH, RE_NOT_A_PROMPT, RE_USER_OR_ASSISTANT_LINE, REPLAY_FALLBACK_TURN_PREFIX } from './constants/replay.constants.js';
10
+ /** Which tool kinds name a file, and whether they read or modify it. */
11
+ const ACCESS_OF_KIND = { 'file-read': 'read', 'file-edit': 'edit' };
12
+ /**
13
+ * Stream a Claude Code transcript as the turns the live hooks would have closed.
14
+ *
15
+ * A turn opens at a prompt a person typed and runs to the next one, as the hook
16
+ * path cuts it. One file at a time and one turn in memory: the readers the
17
+ * hooks use look only at a file's tail, and a month of sessions is megabytes
18
+ * per file. Sub-agent (`isSidechain`) lines never open a turn; their tokens
19
+ * count in the turn that ran them, as they do live, where the window is read
20
+ * from the same file. A turn with no assistant line did nothing and is not
21
+ * yielded.
22
+ *
23
+ * @param filePath - A `~/.claude/projects/<cwd>/<session>.jsonl` file.
24
+ * @param promptText - Whether to keep the prompt's text; off unless the config allows it.
25
+ * @yields Turns, oldest first.
26
+ */
27
+ export async function* readTranscriptTurns(filePath, promptText) {
28
+ const lines = readline.createInterface({ input: fs.createReadStream(filePath, { encoding: 'utf8' }), crlfDelay: Infinity });
29
+ let open;
30
+ try {
31
+ for await (const line of lines) {
32
+ if (!RE_USER_OR_ASSISTANT_LINE.test(line))
33
+ continue;
34
+ const entry = parseJsonLine(line);
35
+ if (!entry)
36
+ continue;
37
+ const prompt = promptOf(entry);
38
+ if (prompt) {
39
+ // Claude Code can record several typed lines under one prompt id: that is one turn, as the
40
+ // live hook closes one per id. Folding them keeps every reply's tokens in the one record.
41
+ if (open?.prompt.sessionId === prompt.sessionId && open.prompt.turnId === prompt.turnId)
42
+ continue;
43
+ const closed = open && closeTurn(open);
44
+ if (closed)
45
+ yield closed;
46
+ open = { prompt, endedAt: prompt.at, assistantLines: 0, usage: new Map(), tools: [], toolIds: new Set(), keepText: promptText };
47
+ continue;
48
+ }
49
+ if (open)
50
+ open = extendTurn(open, entry, line);
51
+ }
52
+ }
53
+ finally {
54
+ lines.close();
55
+ }
56
+ const last = open && closeTurn(open);
57
+ if (last)
58
+ yield last;
59
+ }
60
+ /**
61
+ * The prompt a user line carries, when a person typed it.
62
+ *
63
+ * Tool results are user lines too, and so are slash commands, compaction
64
+ * summaries and the interrupt marker; none is a turn.
65
+ *
66
+ * @param entry - A parsed transcript line.
67
+ * @returns The prompt, or undefined for any other line.
68
+ */
69
+ export function promptOf(entry) {
70
+ if (entry['type'] !== 'user' || entry['isSidechain'] === true || entry['isMeta'] === true || entry['isCompactSummary'] === true)
71
+ return undefined;
72
+ const sessionId = entry['sessionId'];
73
+ const at = entry['timestamp'];
74
+ if (typeof sessionId !== 'string' || typeof at !== 'string')
75
+ return undefined;
76
+ const typed = typedText(asRecord(entry['message'])?.['content']);
77
+ if (typed === undefined)
78
+ return undefined;
79
+ const promptId = entry['promptId'];
80
+ const uuid = typeof entry['uuid'] === 'string' ? entry['uuid'] : at;
81
+ // A transcript from before prompt ids: stable per session and first line, so a second replay agrees with the first.
82
+ const turnId = typeof promptId === 'string' && promptId ? promptId : REPLAY_FALLBACK_TURN_PREFIX + sha256Hex(`${sessionId}${uuid}`).slice(0, 32);
83
+ return { sessionId, turnId, at, text: typed };
84
+ }
85
+ /**
86
+ * The text of a user message when it is a prompt, undefined when it is a tool result or a record.
87
+ *
88
+ * @param content - The message's `content`: a string, or blocks.
89
+ * @returns The typed text (empty for an image-only prompt), or undefined.
90
+ */
91
+ function typedText(content) {
92
+ if (typeof content === 'string') {
93
+ const text = content.trim();
94
+ return text && !RE_NOT_A_PROMPT.test(text) ? content : undefined;
95
+ }
96
+ if (!Array.isArray(content))
97
+ return undefined;
98
+ const texts = [];
99
+ for (const block of content) {
100
+ const record = asRecord(block);
101
+ if (record?.['type'] === 'tool_result')
102
+ return undefined;
103
+ if (record?.['type'] === 'text' && typeof record['text'] === 'string')
104
+ texts.push(record['text']);
105
+ }
106
+ const joined = texts.join('\n');
107
+ return RE_NOT_A_PROMPT.test(joined.trim()) ? undefined : joined;
108
+ }
109
+ /**
110
+ * The turn a run of lines has become.
111
+ *
112
+ * @param open - The turn read so far.
113
+ * @returns The turn, or undefined when the agent never answered.
114
+ */
115
+ function closeTurn(open) {
116
+ if (open.assistantLines === 0)
117
+ return undefined;
118
+ const text = open.keepText ? open.prompt.text.replace(RE_HARNESS_BLOCK, '').trim() : '';
119
+ return {
120
+ provider: CLAUDE_PROVIDER_ID,
121
+ sessionId: open.prompt.sessionId,
122
+ turnId: open.prompt.turnId,
123
+ startedAt: open.prompt.at,
124
+ endedAt: open.endedAt,
125
+ cwd: open.cwd,
126
+ branch: open.branch,
127
+ surface: open.surface,
128
+ usage: accumulateUsage(open.usage),
129
+ tools: open.tools,
130
+ promptText: text || undefined
131
+ };
132
+ }
133
+ /**
134
+ * Fold one non-prompt line into the open turn.
135
+ *
136
+ * @param open - The turn read so far.
137
+ * @param entry - The parsed line.
138
+ * @param line - The verbatim line, for the id an anonymous message falls back to.
139
+ * @returns The turn with the line in it.
140
+ */
141
+ function extendTurn(open, entry, line) {
142
+ // Only the agent's own lines date the turn and place it: a slash command typed after the
143
+ // answer, or a line another process appended, is not where the turn ended.
144
+ if (entry['type'] !== 'assistant')
145
+ return open;
146
+ const at = entry['timestamp'];
147
+ const timed = typeof at === 'string' && at > open.endedAt ? { ...open, endedAt: at } : open;
148
+ const placed = entry['isSidechain'] === true ? timed : withWhere(timed, entry);
149
+ return withAssistant({ ...placed, assistantLines: placed.assistantLines + 1 }, entry, line);
150
+ }
151
+ /**
152
+ * The turn with the folder and branch a line reported.
153
+ *
154
+ * @param open - The turn read so far.
155
+ * @param entry - The parsed line.
156
+ * @returns The turn, moved to where the line says the agent was.
157
+ */
158
+ function withWhere(open, entry) {
159
+ const cwd = entry['cwd'];
160
+ if (typeof cwd !== 'string' || !cwd)
161
+ return open;
162
+ const branch = entry['gitBranch'];
163
+ const entrypoint = entry['entrypoint'];
164
+ return {
165
+ ...open,
166
+ cwd,
167
+ branch: typeof branch === 'string' && branch && branch !== DETACHED_BRANCH ? branch : undefined,
168
+ surface: typeof entrypoint === 'string' ? entrypoint : open.surface
169
+ };
170
+ }
171
+ /**
172
+ * The turn with an assistant line's usage and tool calls.
173
+ *
174
+ * @param open - The turn read so far.
175
+ * @param entry - The parsed assistant line.
176
+ * @param line - The verbatim line.
177
+ * @returns The turn with them folded in.
178
+ */
179
+ function withAssistant(open, entry, line) {
180
+ const message = asRecord(entry['message']);
181
+ const usage = asRecord(message?.['usage']);
182
+ const rawId = typeof message?.['id'] === 'string' ? message['id'] : undefined;
183
+ const model = typeof message?.['model'] === 'string' ? message['model'] : undefined;
184
+ const counted = usage ? new Map(open.usage).set(messageIdFor(rawId, line), { model, usage }) : open.usage;
185
+ const content = message?.['content'];
186
+ if (!Array.isArray(content))
187
+ return { ...open, usage: counted };
188
+ const tools = [...open.tools];
189
+ const toolIds = new Set(open.toolIds);
190
+ for (const block of content) {
191
+ const call = toolUseOf(asRecord(block));
192
+ if (!call || (call.id !== undefined && toolIds.has(call.id)))
193
+ continue;
194
+ if (call.id !== undefined)
195
+ toolIds.add(call.id);
196
+ tools.push(call.tool);
197
+ }
198
+ return { ...open, usage: counted, tools, toolIds };
199
+ }
200
+ /**
201
+ * A tool call out of a content block, with the id that makes it countable once.
202
+ *
203
+ * @param block - A message content block.
204
+ * @returns The call, or undefined for any other block.
205
+ */
206
+ function toolUseOf(block) {
207
+ if (block?.['type'] !== 'tool_use' || typeof block['name'] !== 'string')
208
+ return undefined;
209
+ const kind = classifyTool(block['name']);
210
+ const access = ACCESS_OF_KIND[kind];
211
+ return {
212
+ id: typeof block['id'] === 'string' ? block['id'] : undefined,
213
+ tool: { name: block['name'], access, path: access ? extractFilePath(block['input']) : undefined }
214
+ };
215
+ }
@@ -0,0 +1,38 @@
1
+ import type { CaptureConfig } from '../config/types/config.types.js';
2
+ import type { UsageBillingMode } from '../events/types/events.types.js';
3
+ import type { TurnSummaryEvent } from '../turns/types/turn-summary.types.js';
4
+ import type { ReplayCheckout, ReplayTurn } from './types/replay.types.js';
5
+ /** What every replayed turn of one run shares. */
6
+ export interface ReplayTurnContext {
7
+ readonly developerId: string;
8
+ readonly developerName?: string;
9
+ readonly installationId?: string;
10
+ /** The effective capture flags, consent gate applied: the same ones a live hook obeys. */
11
+ readonly capture: CaptureConfig;
12
+ readonly billingMode?: UsageBillingMode;
13
+ }
14
+ /**
15
+ * The `turn.summary` a transcript turn becomes: the live hook's record, built by the live hook's builder.
16
+ *
17
+ * It differs from a live one only where a transcript knows less: no commit (the
18
+ * transcript does not say which commit the branch was at; only a Codex rollout's session-start commit rides along, for a folder that is gone), no tool events, no
19
+ * session titles, and a repository and branch read from the turn's last
20
+ * folder and `gitBranch`, not from the checkout as it is now. The record's
21
+ * `turn_id` is the transcript's prompt id, which is the live hook's turn id,
22
+ * so the backend upserts a replayed turn and a live one into the same row.
23
+ * The event id is derived from the same two values, so a second replay
24
+ * produces the same records. Its `usage_status` is always `pending` (see below).
25
+ *
26
+ * @param turn - A turn out of a transcript.
27
+ * @param checkout - The checkout its folder resolved to, when it still resolves.
28
+ * @param context - Developer, capture flags and billing shared by the run.
29
+ * @returns The summary, ready for the same capture gate every record passes at send.
30
+ */
31
+ export declare function buildReplayTurnEvent(turn: ReplayTurn, checkout: ReplayCheckout | undefined, context: ReplayTurnContext): TurnSummaryEvent;
32
+ /**
33
+ * The event id of a replayed turn: its session and its turn id, nothing that varies between runs.
34
+ *
35
+ * @param turn - The turn.
36
+ * @returns The `evt_` id.
37
+ */
38
+ export declare function replayEventId(turn: Pick<ReplayTurn, 'provider' | 'sessionId' | 'turnId'>): string;
@@ -0,0 +1,116 @@
1
+ import path from 'node:path';
2
+ import { compact } from '../core/object.js';
3
+ import { deriveEventId, sha256Hex } from '../events/event-id.js';
4
+ import { repositoryIdentity } from '../git/git-context.js';
5
+ import { featureCandidatesFromBranch } from '../feature/ticket-candidates.js';
6
+ import { sanitizeText } from '../privacy/sanitizer.js';
7
+ import { DEFAULT_SURFACE, MAX_PROMPT_TEXT_LENGTH } from '../turns/constants/turns.constants.js';
8
+ import { buildTurnSummary } from '../turns/turn-summary.js';
9
+ /**
10
+ * The `turn.summary` a transcript turn becomes: the live hook's record, built by the live hook's builder.
11
+ *
12
+ * It differs from a live one only where a transcript knows less: no commit (the
13
+ * transcript does not say which commit the branch was at; only a Codex rollout's session-start commit rides along, for a folder that is gone), no tool events, no
14
+ * session titles, and a repository and branch read from the turn's last
15
+ * folder and `gitBranch`, not from the checkout as it is now. The record's
16
+ * `turn_id` is the transcript's prompt id, which is the live hook's turn id,
17
+ * so the backend upserts a replayed turn and a live one into the same row.
18
+ * The event id is derived from the same two values, so a second replay
19
+ * produces the same records. Its `usage_status` is always `pending` (see below).
20
+ *
21
+ * @param turn - A turn out of a transcript.
22
+ * @param checkout - The checkout its folder resolved to, when it still resolves.
23
+ * @param context - Developer, capture flags and billing shared by the run.
24
+ * @returns The summary, ready for the same capture gate every record passes at send.
25
+ */
26
+ export function buildReplayTurnEvent(turn, checkout, context) {
27
+ // No checkout (the folder is gone): the remote the rollout recorded still names the repository.
28
+ const repository = checkout?.repository ?? (turn.remote ? repositoryIdentity('', turn.remote).remote : undefined);
29
+ const git = context.capture.git === false || !repository ? undefined : { repository, branch: checkout?.evidence ? undefined : turn.branch, commit: checkout ? undefined : turn.commit };
30
+ const summary = buildTurnSummary({
31
+ provider: turn.provider,
32
+ surface: turn.surface ?? DEFAULT_SURFACE,
33
+ sessionId: turn.sessionId,
34
+ turnId: turn.turnId,
35
+ developerId: context.developerId,
36
+ developerName: context.developerName,
37
+ installationId: context.installationId,
38
+ git,
39
+ featureCandidates: featureCandidatesFromBranch(git?.branch),
40
+ workEvidence: git ? (checkout?.evidence ?? 'cwd') : undefined,
41
+ prompts: [{ kind: 'prompt', at: turn.startedAt, turnId: turn.turnId, text: promptText(turn, context.capture) }],
42
+ tools: toolRecords(turn, context.capture.files === false ? undefined : checkout),
43
+ usage: turn.usage,
44
+ model: turn.usage?.model,
45
+ billingMode: context.billingMode,
46
+ endedAt: turn.endedAt
47
+ });
48
+ // `pending`, with the tokens: core's turn upsert keeps the higher status, and a live turn is
49
+ // `provisional`, so a replayed `provisional` one would overwrite what the hook sent. The
50
+ // tokens ride on either way; the status only feeds that guard.
51
+ return compact({ ...summary, id: replayEventId(turn), usage_status: 'pending' });
52
+ }
53
+ /**
54
+ * The event id of a replayed turn: its session and its turn id, nothing that varies between runs.
55
+ *
56
+ * @param turn - The turn.
57
+ * @returns The `evt_` id.
58
+ */
59
+ export function replayEventId(turn) {
60
+ return deriveEventId({
61
+ // A Claude turn's id is unchanged: its provider was always `claude`.
62
+ provider: turn.provider,
63
+ providerEventType: 'turn.summary',
64
+ sessionId: turn.sessionId,
65
+ turnId: turn.turnId,
66
+ payloadFingerprint: sha256Hex('replay')
67
+ });
68
+ }
69
+ /**
70
+ * The prompt text to send: only when the config allows it, scrubbed whole and then cut, as the live path does.
71
+ *
72
+ * @param turn - The turn.
73
+ * @param capture - The effective capture flags.
74
+ * @returns The text, or undefined.
75
+ */
76
+ function promptText(turn, capture) {
77
+ if (capture.promptText !== true || !turn.promptText)
78
+ return undefined;
79
+ return sanitizeText(turn.promptText).slice(0, MAX_PROMPT_TEXT_LENGTH) || undefined;
80
+ }
81
+ /**
82
+ * The turn's tool calls as the builder takes them: a name, and a path inside the checkout.
83
+ *
84
+ * A file outside the checkout, or any file when the folder has no checkout,
85
+ * is left out: the live hook sends a bare basename for those, and a basename
86
+ * says nothing the backend can place.
87
+ *
88
+ * @param turn - The turn.
89
+ * @param checkout - The checkout paths are made relative to; undefined drops paths.
90
+ * @returns One record per call.
91
+ */
92
+ function toolRecords(turn, checkout) {
93
+ return turn.tools.map((tool) => ({
94
+ kind: 'tool',
95
+ at: turn.endedAt,
96
+ turnId: turn.turnId,
97
+ tool: tool.name,
98
+ access: tool.access,
99
+ filePath: checkout ? relativeTo(checkout.root, tool) : undefined
100
+ }));
101
+ }
102
+ /**
103
+ * A tool's file as a slash-separated path inside a checkout.
104
+ *
105
+ * @param root - The checkout root.
106
+ * @param tool - The call.
107
+ * @returns The path, or undefined when the file is not inside the root.
108
+ */
109
+ function relativeTo(root, tool) {
110
+ if (!tool.path || !path.isAbsolute(tool.path))
111
+ return undefined;
112
+ const relative = path.relative(root, tool.path);
113
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative))
114
+ return undefined;
115
+ return relative.split(path.sep).join('/');
116
+ }
@@ -0,0 +1,162 @@
1
+ import type { ReplayProgressState } from '../../events/types/replay-progress.types.js';
2
+ import type { AgentWatchConfig, CaptureConfig } from '../../config/types/config.types.js';
3
+ import type { Env } from '../../core/types/core.types.js';
4
+ import type { UsageBillingMode } from '../../events/types/events.types.js';
5
+ import type { AgentWatchPaths } from '../../storage/types/storage.types.js';
6
+ import type { BackendAuthBlock } from '../../transport/auth-block.js';
7
+ import type { BackendCooldown } from '../../transport/cooldown.js';
8
+ import type { EventQueue } from '../../transport/queue.js';
9
+ import type { EventTransport } from '../../transport/types/transport.types.js';
10
+ import type { TurnUsage } from '../../turns/types/transcript.types.js';
11
+ import type { CheckoutResolver } from '../checkout-resolver.js';
12
+ /** The span of time a replay may send turns from. */
13
+ export interface ReplayWindow {
14
+ readonly start: Date;
15
+ readonly end: Date;
16
+ }
17
+ /** One tool call read out of a transcript: its name and the absolute file it named, if any. */
18
+ export interface ReplayTool {
19
+ readonly name: string;
20
+ readonly access?: 'read' | 'edit';
21
+ /** Absolute, as the agent wrote it; made checkout-relative when the event is built. */
22
+ readonly path?: string;
23
+ }
24
+ /** What a transcript says about the folder a session ran in: its repository's remote, the commit and the branch, when it recorded them. */
25
+ export interface ReplayIdentity {
26
+ readonly cwd: string;
27
+ readonly remote?: string;
28
+ readonly commit?: string;
29
+ readonly branch?: string;
30
+ }
31
+ /** One prompt and everything the agent did before the next one, as a transcript recorded it. */
32
+ export interface ReplayTurn {
33
+ /** The agent that ran it, as its live hook names itself: `claude`, `codex`, `gemini`. */
34
+ readonly provider: string;
35
+ readonly sessionId: string;
36
+ /** The live hook's `turn_id` where the file records it (Claude's `promptId`, Codex's `turn_id`); derived otherwise. */
37
+ readonly turnId: string;
38
+ readonly startedAt: string;
39
+ readonly endedAt: string;
40
+ /** Where the agent sat at the turn's last line, and the branch git reported there then. */
41
+ readonly cwd?: string;
42
+ readonly branch?: string;
43
+ /** The remote the session started in, when the file records it (Codex `session_meta.git.repository_url`); used when the folder is gone. */
44
+ readonly remote?: string;
45
+ /** The full commit the session started at (Codex `session_meta.git.commit_hash`); sent only when the folder is gone. */
46
+ readonly commit?: string;
47
+ readonly surface?: string;
48
+ readonly usage?: TurnUsage;
49
+ readonly tools: readonly ReplayTool[];
50
+ /** The prompt as typed; read only when the effective config allows prompt text. */
51
+ readonly promptText?: string;
52
+ }
53
+ /** The checkout a turn's `cwd` resolved to, cached per directory. */
54
+ export interface ReplayCheckout {
55
+ readonly root: string;
56
+ readonly repository: string;
57
+ /** How it was found when not by the turn's folder: `changed`, by a file a tool edited. Absent: the folder (`cwd`). */
58
+ readonly evidence?: 'changed';
59
+ }
60
+ /** What one transcript file looked like when it was counted. */
61
+ export interface ReplayFileEntry {
62
+ readonly mtimeMs: number;
63
+ readonly size: number;
64
+ readonly turns: number;
65
+ readonly done: boolean;
66
+ /** The session the file's turns belong to; sessions are counted from it, because a resumed Codex session has one file per resume. */
67
+ readonly session?: string;
68
+ /** The source that listed it; absent in a record from before Codex and Gemini replay, which listed Claude Code only. */
69
+ readonly agent?: string;
70
+ }
71
+ /** One transcript file and what a stat says about it. */
72
+ export interface TranscriptFile {
73
+ readonly file: string;
74
+ readonly mtimeMs: number;
75
+ readonly size: number;
76
+ }
77
+ /** One agent's transcripts on this machine: where they are, how to count them cheaply, how to read them as turns. */
78
+ export interface ReplaySource {
79
+ /** The provider id its turns carry. */
80
+ readonly agent: string;
81
+ /** How the developer pays for this agent; the run's `billingMode` when absent. */
82
+ readonly billingMode?: UsageBillingMode;
83
+ /** The files that may hold a turn from the window. */
84
+ list(sinceMs: number): Promise<TranscriptFile[]>;
85
+ /** About how many turns a file holds from the window, without parsing it. */
86
+ estimate(file: string, sinceMs: number): Promise<number>;
87
+ /** What the file says about its folder, from its first rows, without reading the turns; undefined when it says nothing. */
88
+ identity?(file: string): Promise<ReplayIdentity | undefined>;
89
+ /** The file's turns, oldest first. */
90
+ read(file: string, promptText: boolean): AsyncIterable<ReplayTurn>;
91
+ }
92
+ /** Why a running replay is waiting. */
93
+ export type ReplayPause = 'busy' | 'battery' | 'agent-active' | 'backend' | 'budget';
94
+ /** A replay's persisted state: the one file `status`, a resumed run and the progress record read. */
95
+ export interface ReplayRecord {
96
+ readonly replayId: string;
97
+ /** Fingerprint of the identity it sends as; another identity starts over. */
98
+ readonly identity: string;
99
+ readonly state: ReplayProgressState;
100
+ readonly windowStart: string;
101
+ readonly windowEnd: string;
102
+ readonly startedAt: string;
103
+ readonly updatedAt: string;
104
+ readonly pid?: number;
105
+ readonly heartbeatAt?: string;
106
+ readonly pause?: ReplayPause;
107
+ readonly turnsTotal: number;
108
+ readonly turnsSent: number;
109
+ readonly sessionsTotal: number;
110
+ readonly sessionsSent: number;
111
+ readonly batches: number;
112
+ /** Turns the backend refused outright (a 4xx that retrying cannot fix); never counted as sent. */
113
+ readonly refused: number;
114
+ /** Repositories whose snapshot has been queued. */
115
+ readonly snapshotted: readonly string[];
116
+ readonly files: Readonly<Record<string, ReplayFileEntry>>;
117
+ /** The sources a fresh run listed; absent in a record from before Codex and Gemini replay. */
118
+ readonly agents?: readonly string[];
119
+ }
120
+ /** What the machine says about itself, as the throttle reads it. */
121
+ export interface MachineLoad {
122
+ readonly load1: number;
123
+ readonly cores: number;
124
+ readonly onBattery: boolean;
125
+ /** Milliseconds since a hook last closed a turn; Infinity when none ever did. */
126
+ readonly hookAgeMs: number;
127
+ }
128
+ /**
129
+ * What a replay run needs from the machine it runs on, handed in whole so the
130
+ * run itself touches nothing it was not given (and a test hands it a fake).
131
+ */
132
+ export interface ReplayPorts {
133
+ readonly env: Env;
134
+ readonly paths: AgentWatchPaths;
135
+ readonly config: AgentWatchConfig;
136
+ /** The identity's replay state file. */
137
+ readonly stateFile: string;
138
+ /** Fingerprint of the credential the run sends as. */
139
+ readonly identity: string;
140
+ readonly developerId: string;
141
+ readonly developerName?: string;
142
+ readonly installationId?: string;
143
+ readonly billingMode?: UsageBillingMode;
144
+ /** One per agent whose transcripts are replayed: Claude Code, Codex, Gemini CLI. */
145
+ readonly sources: readonly ReplaySource[];
146
+ /** A transport with a fresh bearer, or undefined when nothing can be sent (no backend, disabled). */
147
+ transport(): Promise<EventTransport | undefined>;
148
+ /** The offline queue snapshots and a final progress record go through. */
149
+ readonly queue: EventQueue;
150
+ readonly authBlock: BackendAuthBlock;
151
+ readonly cooldown: BackendCooldown;
152
+ /** Whether a turn that ran in this folder belongs to the identity the run sends as. */
153
+ inScope(cwd: string): boolean;
154
+ checkout: CheckoutResolver;
155
+ /** The capture flags in force for a folder: the global ones, narrowed by the folder's `.agentwatch.json`, as a live hook there would read them. */
156
+ captureFor: (cwd: string) => Promise<CaptureConfig>;
157
+ machine(): Promise<MachineLoad>;
158
+ sleep(ms: number): Promise<void>;
159
+ /** Whether a pid exists. */
160
+ alive?(pid: number): boolean;
161
+ log(line: string): void;
162
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,28 @@
1
+ import type { ReplayWindow } from './types/replay.types.js';
2
+ /**
3
+ * The earliest instant whose charge period is not finalized.
4
+ *
5
+ * A copy of core's `firstOpenInstant` (packages/types/src/period-month.ts): the
6
+ * start of this UTC month from the grace day on, of last month before it. Spend
7
+ * before it sits in a month the monthly close may already have frozen, so
8
+ * nothing may arrive for it late: replay never sends a turn from before it.
9
+ *
10
+ * @param now - The clock.
11
+ * @returns The first instant a replayed turn may be from.
12
+ */
13
+ export declare function firstOpenInstant(now: Date): Date;
14
+ /**
15
+ * The span a replay of `days` days may send, cut at the open charge period.
16
+ *
17
+ * @param now - The clock.
18
+ * @param days - How far back the developer asked to go.
19
+ * @returns The window; its start is never before {@link firstOpenInstant}.
20
+ */
21
+ export declare function replayWindow(now: Date, days: number): ReplayWindow;
22
+ /**
23
+ * `--replay-days` as a count of days.
24
+ *
25
+ * @param raw - The flag's value, when given.
26
+ * @returns The default when absent, the integer when it is one from 1 to 366, undefined when it is anything else.
27
+ */
28
+ export declare function parseReplayDays(raw: string | undefined): number | undefined;
@@ -0,0 +1,41 @@
1
+ import { REPLAY_DEFAULT_DAYS, REPLAY_FINALIZATION_GRACE_DAYS, REPLAY_MAX_DAYS } from './constants/replay.constants.js';
2
+ const DAY_MS = 86_400_000;
3
+ /**
4
+ * The earliest instant whose charge period is not finalized.
5
+ *
6
+ * A copy of core's `firstOpenInstant` (packages/types/src/period-month.ts): the
7
+ * start of this UTC month from the grace day on, of last month before it. Spend
8
+ * before it sits in a month the monthly close may already have frozen, so
9
+ * nothing may arrive for it late: replay never sends a turn from before it.
10
+ *
11
+ * @param now - The clock.
12
+ * @returns The first instant a replayed turn may be from.
13
+ */
14
+ export function firstOpenInstant(now) {
15
+ const back = now.getUTCDate() >= REPLAY_FINALIZATION_GRACE_DAYS ? 0 : 1;
16
+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - back, 1));
17
+ }
18
+ /**
19
+ * The span a replay of `days` days may send, cut at the open charge period.
20
+ *
21
+ * @param now - The clock.
22
+ * @param days - How far back the developer asked to go.
23
+ * @returns The window; its start is never before {@link firstOpenInstant}.
24
+ */
25
+ export function replayWindow(now, days) {
26
+ const asked = now.getTime() - days * DAY_MS;
27
+ const open = firstOpenInstant(now).getTime();
28
+ return { start: new Date(Math.max(asked, open)), end: now };
29
+ }
30
+ /**
31
+ * `--replay-days` as a count of days.
32
+ *
33
+ * @param raw - The flag's value, when given.
34
+ * @returns The default when absent, the integer when it is one from 1 to 366, undefined when it is anything else.
35
+ */
36
+ export function parseReplayDays(raw) {
37
+ if (raw === undefined)
38
+ return REPLAY_DEFAULT_DAYS;
39
+ const days = Number(raw);
40
+ return Number.isInteger(days) && days >= 1 && days <= REPLAY_MAX_DAYS ? days : undefined;
41
+ }