@agent-watch-ai/edge 0.6.0 → 0.7.1

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 (309) hide show
  1. package/CHANGELOG.md +288 -9
  2. package/README.md +307 -5
  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 +7 -3
  10. package/dist/billing/session-billing.js +34 -13
  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 +503 -0
  16. package/dist/capture/constants/capture.constants.d.ts +85 -0
  17. package/dist/capture/constants/capture.constants.js +87 -0
  18. package/dist/capture/launched-runs.d.ts +43 -0
  19. package/dist/capture/launched-runs.js +157 -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 +832 -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/capture/venv-loader.d.ts +68 -0
  27. package/dist/capture/venv-loader.js +189 -0
  28. package/dist/cli/constants/cli.constants.d.ts +23 -6
  29. package/dist/cli/constants/cli.constants.js +24 -7
  30. package/dist/cli/context.d.ts +19 -22
  31. package/dist/cli/context.js +23 -54
  32. package/dist/cli/doctor-run-capture.d.ts +21 -0
  33. package/dist/cli/doctor-run-capture.js +33 -0
  34. package/dist/cli/doctor.js +21 -68
  35. package/dist/cli/hook-check.d.ts +7 -2
  36. package/dist/cli/hook-check.js +30 -15
  37. package/dist/cli/hook.d.ts +14 -0
  38. package/dist/cli/hook.js +82 -1
  39. package/dist/cli/index.d.ts +1 -1
  40. package/dist/cli/index.js +1 -1
  41. package/dist/cli/misc.js +10 -2
  42. package/dist/cli/npm-global.d.ts +24 -0
  43. package/dist/cli/npm-global.js +77 -0
  44. package/dist/cli/npx-install.js +22 -6
  45. package/dist/cli/replay.d.ts +33 -0
  46. package/dist/cli/replay.js +228 -0
  47. package/dist/cli/setup.d.ts +10 -2
  48. package/dist/cli/setup.js +200 -31
  49. package/dist/cli/status.js +45 -5
  50. package/dist/cli/toggle.js +10 -0
  51. package/dist/cli/types/cli.types.d.ts +15 -1
  52. package/dist/cli/uninstall.js +42 -23
  53. package/dist/cli/update.js +3 -2
  54. package/dist/cli.js +104 -17
  55. package/dist/config/config-store.d.ts +15 -4
  56. package/dist/config/config-store.js +31 -7
  57. package/dist/config/config.d.ts +0 -2
  58. package/dist/config/config.js +0 -1
  59. package/dist/config/constants/config.constants.d.ts +8 -1
  60. package/dist/config/constants/config.constants.js +10 -1
  61. package/dist/config/events-transport.d.ts +15 -0
  62. package/dist/config/events-transport.js +29 -0
  63. package/dist/config/index.d.ts +2 -1
  64. package/dist/config/index.js +1 -0
  65. package/dist/config/root-config.d.ts +12 -0
  66. package/dist/config/root-config.js +24 -0
  67. package/dist/config/schemas/config.schema.d.ts +15 -2
  68. package/dist/config/schemas/config.schema.js +52 -8
  69. package/dist/config/types/config.types.d.ts +7 -0
  70. package/dist/core/index.d.ts +1 -1
  71. package/dist/core/index.js +1 -1
  72. package/dist/core/version.d.ts +9 -0
  73. package/dist/core/version.js +14 -0
  74. package/dist/core/which.d.ts +11 -0
  75. package/dist/core/which.js +18 -0
  76. package/dist/credentials/cloud-claim.d.ts +34 -0
  77. package/dist/credentials/cloud-claim.js +61 -0
  78. package/dist/credentials/constants/credentials.constants.d.ts +16 -1
  79. package/dist/credentials/constants/credentials.constants.js +17 -2
  80. package/dist/credentials/credential-status.js +1 -1
  81. package/dist/credentials/credentials.d.ts +3 -3
  82. package/dist/credentials/credentials.js +26 -12
  83. package/dist/credentials/device-api.d.ts +15 -1
  84. package/dist/credentials/device-api.js +12 -1
  85. package/dist/credentials/identity.d.ts +2 -2
  86. package/dist/credentials/identity.js +2 -2
  87. package/dist/credentials/install-key.d.ts +31 -0
  88. package/dist/credentials/install-key.js +58 -0
  89. package/dist/credentials/migration.d.ts +9 -7
  90. package/dist/credentials/migration.js +58 -18
  91. package/dist/credentials/secret-store.d.ts +12 -0
  92. package/dist/credentials/secret-store.js +18 -1
  93. package/dist/credentials/sign-in.d.ts +27 -0
  94. package/dist/credentials/sign-in.js +31 -1
  95. package/dist/credentials/token-refresher.d.ts +5 -1
  96. package/dist/credentials/token-refresher.js +10 -2
  97. package/dist/enforcement/enforcement.js +1 -1
  98. package/dist/events/constants/events.constants.d.ts +5 -2
  99. package/dist/events/constants/events.constants.js +4 -1
  100. package/dist/events/enrich.d.ts +14 -0
  101. package/dist/events/enrich.js +1 -1
  102. package/dist/events/index.d.ts +1 -0
  103. package/dist/events/product-event.d.ts +6 -3
  104. package/dist/events/types/events.types.d.ts +6 -0
  105. package/dist/events/types/replay-progress.types.d.ts +26 -0
  106. package/dist/events/types/replay-progress.types.js +1 -0
  107. package/dist/events/types/repo-tree.types.d.ts +2 -1
  108. package/dist/feature/ticket-candidates.d.ts +1 -1
  109. package/dist/git/checkout-root.d.ts +15 -0
  110. package/dist/git/checkout-root.js +18 -0
  111. package/dist/git/code-state.d.ts +2 -16
  112. package/dist/git/code-state.js +11 -12
  113. package/dist/git/constants/git.constants.d.ts +33 -11
  114. package/dist/git/constants/git.constants.js +45 -12
  115. package/dist/git/fingerprint.d.ts +3 -6
  116. package/dist/git/fingerprint.js +5 -8
  117. package/dist/git/git-context.js +5 -1
  118. package/dist/git/index.d.ts +1 -2
  119. package/dist/git/index.js +1 -1
  120. package/dist/git/repo-snapshot.d.ts +13 -4
  121. package/dist/git/repo-snapshot.js +53 -9
  122. package/dist/git/types/snapshot.types.d.ts +6 -0
  123. package/dist/pipeline/constants/pipeline.constants.d.ts +3 -0
  124. package/dist/pipeline/constants/pipeline.constants.js +3 -0
  125. package/dist/pipeline/hook-pipeline.js +82 -57
  126. package/dist/privacy/product-capture.js +2 -0
  127. package/dist/providers/antigravity/antigravity.capture.d.ts +2 -0
  128. package/dist/providers/antigravity/antigravity.capture.js +5 -0
  129. package/dist/providers/antigravity/antigravity.detect.js +8 -22
  130. package/dist/providers/antigravity/antigravity.provider.js +10 -3
  131. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +1 -0
  132. package/dist/providers/antigravity/constants/antigravity.constants.js +1 -0
  133. package/dist/providers/claude/claude.adapter.js +9 -6
  134. package/dist/providers/claude/claude.detect.js +2 -17
  135. package/dist/providers/claude/claude.otel.d.ts +21 -3
  136. package/dist/providers/claude/claude.otel.js +216 -61
  137. package/dist/providers/claude/claude.provider.js +21 -1
  138. package/dist/providers/claude/claude.version.d.ts +9 -0
  139. package/dist/providers/claude/claude.version.js +28 -0
  140. package/dist/providers/claude/constants/claude.constants.d.ts +27 -0
  141. package/dist/providers/claude/constants/claude.constants.js +27 -0
  142. package/dist/providers/claude/constants/claude.otel.constants.d.ts +27 -0
  143. package/dist/providers/claude/constants/claude.otel.constants.js +45 -5
  144. package/dist/providers/claude/types/claude.types.d.ts +13 -0
  145. package/dist/providers/codex/codex.capture.d.ts +76 -0
  146. package/dist/providers/codex/codex.capture.js +454 -0
  147. package/dist/providers/codex/codex.detect.js +2 -4
  148. package/dist/providers/codex/codex.otel.d.ts +38 -2
  149. package/dist/providers/codex/codex.otel.js +50 -6
  150. package/dist/providers/codex/codex.provider.js +8 -0
  151. package/dist/providers/codex/codex.surface.d.ts +9 -0
  152. package/dist/{turns/codex-originator.js → providers/codex/codex.surface.js} +17 -3
  153. package/dist/providers/codex/codex.titles.d.ts +14 -0
  154. package/dist/providers/codex/codex.titles.js +35 -0
  155. package/dist/providers/codex/constants/codex.constants.d.ts +4 -0
  156. package/dist/providers/codex/constants/codex.constants.js +4 -0
  157. package/dist/providers/cursor/constants/cursor.constants.d.ts +17 -4
  158. package/dist/providers/cursor/constants/cursor.constants.js +25 -5
  159. package/dist/providers/cursor/cursor-mcp-memo.d.ts +34 -0
  160. package/dist/providers/cursor/cursor-mcp-memo.js +94 -0
  161. package/dist/providers/cursor/cursor.adapter.js +20 -82
  162. package/dist/providers/cursor/cursor.capture.d.ts +1 -0
  163. package/dist/providers/cursor/cursor.capture.js +4 -0
  164. package/dist/providers/cursor/cursor.detect.d.ts +5 -1
  165. package/dist/providers/cursor/cursor.detect.js +11 -26
  166. package/dist/providers/cursor/cursor.hooks.js +2 -2
  167. package/dist/providers/cursor/cursor.provider.js +16 -7
  168. package/dist/providers/cursor/cursor.titles.d.ts +14 -0
  169. package/dist/providers/cursor/cursor.titles.js +20 -0
  170. package/dist/providers/cursor/schemas/cursor.schema.d.ts +3 -3
  171. package/dist/providers/cursor/schemas/cursor.schema.js +5 -3
  172. package/dist/providers/gemini/constants/gemini.constants.d.ts +16 -0
  173. package/dist/providers/gemini/constants/gemini.constants.js +17 -0
  174. package/dist/providers/gemini/gemini.capture.d.ts +81 -0
  175. package/dist/providers/gemini/gemini.capture.js +210 -0
  176. package/dist/providers/gemini/gemini.detect.js +57 -24
  177. package/dist/providers/gemini/gemini.otel.d.ts +38 -2
  178. package/dist/providers/gemini/gemini.otel.js +56 -125
  179. package/dist/providers/gemini/gemini.provider.js +5 -0
  180. package/dist/providers/index.d.ts +1 -0
  181. package/dist/providers/index.js +1 -0
  182. package/dist/providers/provider.d.ts +8 -0
  183. package/dist/providers/provider.js +9 -0
  184. package/dist/providers/registry.d.ts +14 -0
  185. package/dist/providers/registry.js +14 -0
  186. package/dist/providers/shared/constants/hook-config.constants.d.ts +2 -0
  187. package/dist/providers/shared/constants/hook-config.constants.js +2 -0
  188. package/dist/providers/shared/constants/terminal-capture.constants.d.ts +6 -0
  189. package/dist/providers/shared/constants/terminal-capture.constants.js +6 -0
  190. package/dist/providers/shared/editor-paths.d.ts +8 -0
  191. package/dist/providers/shared/editor-paths.js +18 -0
  192. package/dist/providers/shared/hook-config.d.ts +5 -0
  193. package/dist/providers/shared/hook-config.js +39 -1
  194. package/dist/providers/shared/hooks-marker.d.ts +14 -0
  195. package/dist/providers/shared/hooks-marker.js +23 -0
  196. package/dist/providers/shared/install-record.d.ts +29 -0
  197. package/dist/providers/shared/install-record.js +52 -0
  198. package/dist/providers/shared/session-title-store.d.ts +23 -0
  199. package/dist/providers/shared/session-title-store.js +50 -0
  200. package/dist/providers/shared/terminal-capture.d.ts +41 -0
  201. package/dist/providers/shared/terminal-capture.js +109 -0
  202. package/dist/providers/shared/tooling.d.ts +21 -0
  203. package/dist/providers/shared/tooling.js +36 -1
  204. package/dist/providers/types/provider.types.d.ts +57 -4
  205. package/dist/replay/checkout-resolver.d.ts +56 -0
  206. package/dist/replay/checkout-resolver.js +173 -0
  207. package/dist/replay/codex-turns.d.ts +24 -0
  208. package/dist/replay/codex-turns.js +221 -0
  209. package/dist/replay/constants/replay.constants.d.ts +99 -0
  210. package/dist/replay/constants/replay.constants.js +102 -0
  211. package/dist/replay/describe.d.ts +10 -0
  212. package/dist/replay/describe.js +31 -0
  213. package/dist/replay/gemini-turns.d.ts +36 -0
  214. package/dist/replay/gemini-turns.js +192 -0
  215. package/dist/replay/machine.d.ts +34 -0
  216. package/dist/replay/machine.js +68 -0
  217. package/dist/replay/progress-event.d.ts +21 -0
  218. package/dist/replay/progress-event.js +45 -0
  219. package/dist/replay/replay-runner.d.ts +60 -0
  220. package/dist/replay/replay-runner.js +581 -0
  221. package/dist/replay/replay-scan.d.ts +84 -0
  222. package/dist/replay/replay-scan.js +182 -0
  223. package/dist/replay/replay-state.d.ts +108 -0
  224. package/dist/replay/replay-state.js +199 -0
  225. package/dist/replay/resume.d.ts +18 -0
  226. package/dist/replay/resume.js +34 -0
  227. package/dist/replay/start.d.ts +23 -0
  228. package/dist/replay/start.js +39 -0
  229. package/dist/replay/throttle.d.ts +36 -0
  230. package/dist/replay/throttle.js +44 -0
  231. package/dist/replay/transcript-turns.d.ts +35 -0
  232. package/dist/replay/transcript-turns.js +241 -0
  233. package/dist/replay/turn-event.d.ts +40 -0
  234. package/dist/replay/turn-event.js +127 -0
  235. package/dist/replay/types/replay.types.d.ts +198 -0
  236. package/dist/replay/types/replay.types.js +1 -0
  237. package/dist/replay/window.d.ts +28 -0
  238. package/dist/replay/window.js +41 -0
  239. package/dist/replay/worktree-map.d.ts +42 -0
  240. package/dist/replay/worktree-map.js +134 -0
  241. package/dist/snapshot/branch-selection.d.ts +40 -23
  242. package/dist/snapshot/branch-selection.js +71 -41
  243. package/dist/snapshot/constants/snapshot-stages.constants.d.ts +3 -1
  244. package/dist/snapshot/constants/snapshot-stages.constants.js +3 -1
  245. package/dist/snapshot/constants/snapshot.constants.d.ts +34 -7
  246. package/dist/snapshot/constants/snapshot.constants.js +34 -7
  247. package/dist/snapshot/index.d.ts +2 -2
  248. package/dist/snapshot/index.js +1 -1
  249. package/dist/snapshot/snapshot-pipeline.js +100 -26
  250. package/dist/snapshot/snapshot-state.js +6 -2
  251. package/dist/snapshot/tree-pipeline.d.ts +1 -1
  252. package/dist/snapshot/tree-pipeline.js +34 -15
  253. package/dist/snapshot/types/snapshot.types.d.ts +22 -3
  254. package/dist/storage/schemas/storage.schema.d.ts +2 -0
  255. package/dist/storage/schemas/storage.schema.js +6 -0
  256. package/dist/transport/delivery-stats.d.ts +13 -1
  257. package/dist/transport/delivery-stats.js +18 -2
  258. package/dist/transport/delivery.d.ts +4 -3
  259. package/dist/transport/delivery.js +21 -7
  260. package/dist/transport/identity-delivery.d.ts +20 -0
  261. package/dist/transport/identity-delivery.js +41 -0
  262. package/dist/transport/index.d.ts +2 -0
  263. package/dist/transport/index.js +1 -0
  264. package/dist/transport/types/delivery-flow.types.d.ts +7 -0
  265. package/dist/turns/claude-transcript.js +4 -12
  266. package/dist/turns/codex-transcript.d.ts +9 -0
  267. package/dist/turns/codex-transcript.js +27 -19
  268. package/dist/turns/constants/turns.constants.d.ts +29 -12
  269. package/dist/turns/constants/turns.constants.js +31 -19
  270. package/dist/turns/gemini-transcript.d.ts +19 -1
  271. package/dist/turns/gemini-transcript.js +29 -18
  272. package/dist/turns/index.d.ts +3 -4
  273. package/dist/turns/index.js +2 -3
  274. package/dist/turns/run-state.d.ts +71 -0
  275. package/dist/turns/run-state.js +114 -0
  276. package/dist/turns/tool-events.d.ts +11 -1
  277. package/dist/turns/tool-events.js +32 -9
  278. package/dist/turns/transcript.d.ts +15 -14
  279. package/dist/turns/transcript.js +23 -4
  280. package/dist/turns/turn-state.d.ts +82 -7
  281. package/dist/turns/turn-state.js +157 -10
  282. package/dist/turns/turn-summary.js +7 -2
  283. package/dist/turns/turn-tracker.d.ts +9 -16
  284. package/dist/turns/turn-tracker.js +163 -87
  285. package/dist/turns/types/transcript.types.d.ts +11 -1
  286. package/dist/turns/types/turn-provider.types.d.ts +33 -0
  287. package/dist/turns/types/turn-provider.types.js +1 -0
  288. package/dist/turns/types/turn-state.types.d.ts +9 -0
  289. package/dist/turns/types/turn-summary.types.d.ts +17 -1
  290. package/dist/turns/types/turn-tracker.types.d.ts +3 -1
  291. package/dist/turns/work-checkout.js +1 -2
  292. package/docs/AUDIT_PROMPT.md +10 -0
  293. package/docs/DATA_HANDLING.md +201 -13
  294. package/docs/ENTERPRISE_DEPLOYMENT.md +3 -3
  295. package/docs/PERFORMANCE.md +10 -0
  296. package/package.json +3 -2
  297. package/dist/events/canonical-event.d.ts +0 -10
  298. package/dist/events/canonical-event.js +0 -9
  299. package/dist/git/repository-root.d.ts +0 -39
  300. package/dist/git/repository-root.js +0 -131
  301. package/dist/git/types/repository-root.types.d.ts +0 -11
  302. package/dist/transport/transport.d.ts +0 -6
  303. package/dist/turns/codex-originator.d.ts +0 -11
  304. package/dist/turns/cursor-transcript.d.ts +0 -21
  305. package/dist/turns/cursor-transcript.js +0 -66
  306. package/dist/turns/native-session-titles.d.ts +0 -26
  307. package/dist/turns/native-session-titles.js +0 -102
  308. /package/dist/{git/types/repository-root.types.js → billing/types/billing.types.js} +0 -0
  309. /package/dist/{transport/transport.js → capture/types/capture.types.js} +0 -0
@@ -0,0 +1,39 @@
1
+ import { spawn, spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import process from 'node:process';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { REPLAY_NODE_FLAGS } from './constants/replay.constants.js';
6
+ /**
7
+ * Start `agentwatch replay …` as a process of its own, detached from the caller.
8
+ *
9
+ * Setup must not wait for a replay and a hook must not carry one, so the replay
10
+ * outlives both. Only from the built CLI: run from source there is nothing to
11
+ * start. A spawn that fails emits 'error'; unheard, it would crash the caller.
12
+ *
13
+ * @param env - Its `startDetached` when injected (tests); otherwise the built CLI is spawned.
14
+ * @param args - The arguments after `agentwatch`.
15
+ * @param cwd - Where to run: the replay picks its identity from it, as a hook does.
16
+ */
17
+ export function startReplayDetached(env, args, cwd) {
18
+ if (env.startDetached)
19
+ return env.startDetached(args);
20
+ const cli = fileURLToPath(new URL('../cli.js', import.meta.url));
21
+ if (!fs.existsSync(cli))
22
+ return;
23
+ spawn(process.execPath, [...REPLAY_NODE_FLAGS, cli, ...args], { cwd, detached: true, stdio: 'ignore', windowsHide: true }).on('error', () => undefined).unref();
24
+ }
25
+ /**
26
+ * Run this `agentwatch replay` again under {@link REPLAY_NODE_FLAGS}, when it was not started with them.
27
+ *
28
+ * The flags cannot be set from inside a running Node, and a replay started by
29
+ * hand should weigh what one started by setup does.
30
+ *
31
+ * @param argv - The arguments after `agentwatch`.
32
+ * @returns The child's exit code, or undefined when this process already has the flags (or there is no built CLI to run).
33
+ */
34
+ export function runWithSmallHeap(argv) {
35
+ const cli = fileURLToPath(new URL('../cli.js', import.meta.url));
36
+ if (REPLAY_NODE_FLAGS.every((flag) => process.execArgv.includes(flag)) || !fs.existsSync(cli))
37
+ return undefined;
38
+ return spawnSync(process.execPath, [...REPLAY_NODE_FLAGS, cli, ...argv], { stdio: 'inherit' }).status ?? 1;
39
+ }
@@ -0,0 +1,36 @@
1
+ import type { MachineLoad, ReplayPause } from './types/replay.types.js';
2
+ /** Whether replay may send now, and if not why and for how long. */
3
+ export type ThrottleVerdict = {
4
+ readonly go: true;
5
+ } | {
6
+ readonly go: false;
7
+ readonly pause: ReplayPause;
8
+ readonly waitMs: number;
9
+ };
10
+ /**
11
+ * Whether the machine can spare a batch right now.
12
+ *
13
+ * Checked before every batch, cheapest reason first. An agent closing a turn
14
+ * means a person is working: replay waits for the hook's quiet, not for the
15
+ * load to show it. Load and battery are the two things a laptop owner feels.
16
+ *
17
+ * @param machine - What the machine says about itself.
18
+ * @param operatorRun - Operator replays are foreground lab work, not polite background work.
19
+ * @returns Go, or the reason and the wait.
20
+ */
21
+ export declare function throttleVerdict(machine: MachineLoad, operatorRun?: boolean): ThrottleVerdict;
22
+ /**
23
+ * How long to wait after another failed request: 10 s, doubling, never over 5 minutes.
24
+ *
25
+ * @param previousMs - The wait that just failed, or undefined for the first failure.
26
+ * @returns The next wait.
27
+ */
28
+ export declare function nextBackoff(previousMs: number | undefined): number;
29
+ /**
30
+ * Whether a response is one to wait out rather than to give up on.
31
+ *
32
+ * @param status - The HTTP status, absent for a network failure.
33
+ * @param retryable - What the transport judged.
34
+ * @returns True for 429, 5xx, a timeout or a network error.
35
+ */
36
+ export declare function isWorthWaiting(status: number | undefined, retryable: boolean): boolean;
@@ -0,0 +1,44 @@
1
+ import { REPLAY_BASE_BACKOFF_MS, REPLAY_BUSY_LOAD_PER_CORE, REPLAY_BUSY_PAUSE_MS, REPLAY_HOOK_QUIET_MS, REPLAY_MAX_BACKOFF_MS } from './constants/replay.constants.js';
2
+ /**
3
+ * Whether the machine can spare a batch right now.
4
+ *
5
+ * Checked before every batch, cheapest reason first. An agent closing a turn
6
+ * means a person is working: replay waits for the hook's quiet, not for the
7
+ * load to show it. Load and battery are the two things a laptop owner feels.
8
+ *
9
+ * @param machine - What the machine says about itself.
10
+ * @param operatorRun - Operator replays are foreground lab work, not polite background work.
11
+ * @returns Go, or the reason and the wait.
12
+ */
13
+ export function throttleVerdict(machine, operatorRun = false) {
14
+ if (operatorRun)
15
+ return { go: true };
16
+ if (machine.hookAgeMs < REPLAY_HOOK_QUIET_MS)
17
+ return { go: false, pause: 'agent-active', waitMs: REPLAY_HOOK_QUIET_MS - machine.hookAgeMs };
18
+ if (machine.onBattery)
19
+ return { go: false, pause: 'battery', waitMs: REPLAY_BUSY_PAUSE_MS };
20
+ if (machine.load1 > machine.cores * REPLAY_BUSY_LOAD_PER_CORE)
21
+ return { go: false, pause: 'busy', waitMs: REPLAY_BUSY_PAUSE_MS };
22
+ return { go: true };
23
+ }
24
+ /**
25
+ * How long to wait after another failed request: 10 s, doubling, never over 5 minutes.
26
+ *
27
+ * @param previousMs - The wait that just failed, or undefined for the first failure.
28
+ * @returns The next wait.
29
+ */
30
+ export function nextBackoff(previousMs) {
31
+ if (previousMs === undefined)
32
+ return REPLAY_BASE_BACKOFF_MS;
33
+ return Math.min(previousMs * 2, REPLAY_MAX_BACKOFF_MS);
34
+ }
35
+ /**
36
+ * Whether a response is one to wait out rather than to give up on.
37
+ *
38
+ * @param status - The HTTP status, absent for a network failure.
39
+ * @param retryable - What the transport judged.
40
+ * @returns True for 429, 5xx, a timeout or a network error.
41
+ */
42
+ export function isWorthWaiting(status, retryable) {
43
+ return retryable || status === undefined || status === 429 || status >= 500;
44
+ }
@@ -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,241 @@
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: [], toolIdList: [], toolIds: new Set(), failedToolIds: 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.failedToolIds.size === 0 ? open.tools : open.tools.map((tool, index) => (open.failedToolIds.has(open.toolIdList[index] ?? '') ? { name: tool.name } : tool)),
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'] === 'user')
145
+ return withFailures(open, entry);
146
+ if (entry['type'] !== 'assistant')
147
+ return open;
148
+ const at = entry['timestamp'];
149
+ const timed = typeof at === 'string' && at > open.endedAt ? { ...open, endedAt: at } : open;
150
+ const placed = entry['isSidechain'] === true ? timed : withWhere(timed, entry);
151
+ return withAssistant({ ...placed, assistantLines: placed.assistantLines + 1 }, entry, line);
152
+ }
153
+ /**
154
+ * The turn with the folder and branch a line reported.
155
+ *
156
+ * @param open - The turn read so far.
157
+ * @param entry - The parsed line.
158
+ * @returns The turn, moved to where the line says the agent was.
159
+ */
160
+ function withWhere(open, entry) {
161
+ const cwd = entry['cwd'];
162
+ if (typeof cwd !== 'string' || !cwd)
163
+ return open;
164
+ const branch = entry['gitBranch'];
165
+ const entrypoint = entry['entrypoint'];
166
+ return {
167
+ ...open,
168
+ cwd,
169
+ branch: typeof branch === 'string' && branch && branch !== DETACHED_BRANCH ? branch : undefined,
170
+ surface: typeof entrypoint === 'string' ? entrypoint : open.surface
171
+ };
172
+ }
173
+ /**
174
+ * The turn with an assistant line's usage and tool calls.
175
+ *
176
+ * @param open - The turn read so far.
177
+ * @param entry - The parsed assistant line.
178
+ * @param line - The verbatim line.
179
+ * @returns The turn with them folded in.
180
+ */
181
+ function withAssistant(open, entry, line) {
182
+ const message = asRecord(entry['message']);
183
+ const usage = asRecord(message?.['usage']);
184
+ const rawId = typeof message?.['id'] === 'string' ? message['id'] : undefined;
185
+ const model = typeof message?.['model'] === 'string' ? message['model'] : undefined;
186
+ const counted = usage ? new Map(open.usage).set(messageIdFor(rawId, line), { model, usage }) : open.usage;
187
+ const content = message?.['content'];
188
+ if (!Array.isArray(content))
189
+ return { ...open, usage: counted };
190
+ const tools = [...open.tools];
191
+ const toolIdList = [...open.toolIdList];
192
+ const toolIds = new Set(open.toolIds);
193
+ for (const block of content) {
194
+ const call = toolUseOf(asRecord(block));
195
+ if (!call || (call.id !== undefined && toolIds.has(call.id)))
196
+ continue;
197
+ if (call.id !== undefined)
198
+ toolIds.add(call.id);
199
+ tools.push(call.tool);
200
+ toolIdList.push(call.id);
201
+ }
202
+ return { ...open, usage: counted, tools, toolIdList, toolIds };
203
+ }
204
+ /**
205
+ * The turn with the calls a tool-result line says failed.
206
+ *
207
+ * @param open - The turn read so far.
208
+ * @param entry - A parsed user line.
209
+ * @returns The turn, with those call ids marked.
210
+ */
211
+ function withFailures(open, entry) {
212
+ const content = asRecord(entry['message'])?.['content'];
213
+ if (!Array.isArray(content))
214
+ return open;
215
+ let failed;
216
+ for (const block of content) {
217
+ const result = asRecord(block);
218
+ const id = result?.['tool_use_id'];
219
+ if (result?.['type'] !== 'tool_result' || result['is_error'] !== true || typeof id !== 'string')
220
+ continue;
221
+ failed ??= new Set(open.failedToolIds);
222
+ failed.add(id);
223
+ }
224
+ return failed ? { ...open, failedToolIds: failed } : open;
225
+ }
226
+ /**
227
+ * A tool call out of a content block, with the id that makes it countable once.
228
+ *
229
+ * @param block - A message content block.
230
+ * @returns The call, or undefined for any other block.
231
+ */
232
+ function toolUseOf(block) {
233
+ if (block?.['type'] !== 'tool_use' || typeof block['name'] !== 'string')
234
+ return undefined;
235
+ const kind = classifyTool(block['name']);
236
+ const access = ACCESS_OF_KIND[kind];
237
+ return {
238
+ id: typeof block['id'] === 'string' ? block['id'] : undefined,
239
+ tool: { name: block['name'], access, path: access ? extractFilePath(block['input']) : undefined }
240
+ };
241
+ }
@@ -0,0 +1,40 @@
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
+ /** The developer's home, to send an outside file home-relative; without it no outside path is sent. */
14
+ readonly home?: string;
15
+ }
16
+ /**
17
+ * The `turn.summary` a transcript turn becomes: the live hook's record, built by the live hook's builder.
18
+ *
19
+ * It differs from a live one only where a transcript knows less: only a Codex
20
+ * rollout's session-start commit is known, no tool events, no
21
+ * session titles, and a repository and branch read from the turn's last
22
+ * folder and `gitBranch`, not from the checkout as it is now. The record's
23
+ * `turn_id` is the transcript's prompt id, which is the live hook's turn id,
24
+ * so the backend upserts a replayed turn and a live one into the same row.
25
+ * The event id is derived from the same two values, so a second replay
26
+ * produces the same records. Its `usage_status` is always `pending` (see below).
27
+ *
28
+ * @param turn - A turn out of a transcript.
29
+ * @param checkout - The checkout its folder resolved to, when it still resolves.
30
+ * @param context - Developer, capture flags and billing shared by the run.
31
+ * @returns The summary, ready for the same capture gate every record passes at send.
32
+ */
33
+ export declare function buildReplayTurnEvent(turn: ReplayTurn, checkout: ReplayCheckout | undefined, context: ReplayTurnContext): TurnSummaryEvent;
34
+ /**
35
+ * The event id of a replayed turn: its session and its turn id, nothing that varies between runs.
36
+ *
37
+ * @param turn - The turn.
38
+ * @returns The `evt_` id.
39
+ */
40
+ export declare function replayEventId(turn: Pick<ReplayTurn, 'provider' | 'sessionId' | 'turnId'>): string;
@@ -0,0 +1,127 @@
1
+ import path from 'node:path';
2
+ import { compact } from '../core/object.js';
3
+ import { deriveEventId, sha256Hex } from '../events/event-id.js';
4
+ import { externalPath } from '../events/enrich.js';
5
+ import { repositoryIdentity } from '../git/git-context.js';
6
+ import { featureCandidatesFromBranch } from '../feature/ticket-candidates.js';
7
+ import { sanitizeText } from '../privacy/sanitizer.js';
8
+ import { DEFAULT_SURFACE, MAX_PROMPT_TEXT_LENGTH } from '../turns/constants/turns.constants.js';
9
+ import { buildTurnSummary } from '../turns/turn-summary.js';
10
+ /**
11
+ * The `turn.summary` a transcript turn becomes: the live hook's record, built by the live hook's builder.
12
+ *
13
+ * It differs from a live one only where a transcript knows less: only a Codex
14
+ * rollout's session-start commit is known, no tool events, no
15
+ * session titles, and a repository and branch read from the turn's last
16
+ * folder and `gitBranch`, not from the checkout as it is now. The record's
17
+ * `turn_id` is the transcript's prompt id, which is the live hook's turn id,
18
+ * so the backend upserts a replayed turn and a live one into the same row.
19
+ * The event id is derived from the same two values, so a second replay
20
+ * produces the same records. Its `usage_status` is always `pending` (see below).
21
+ *
22
+ * @param turn - A turn out of a transcript.
23
+ * @param checkout - The checkout its folder resolved to, when it still resolves.
24
+ * @param context - Developer, capture flags and billing shared by the run.
25
+ * @returns The summary, ready for the same capture gate every record passes at send.
26
+ */
27
+ export function buildReplayTurnEvent(turn, checkout, context) {
28
+ // No checkout (the folder is gone): the remote the rollout recorded still names the repository.
29
+ const repository = checkout?.repository ?? (turn.remote ? repositoryIdentity('', turn.remote).remote : undefined);
30
+ // A Codex session records its commit once, at start: it belongs to the repository it recorded, not to one the session moved to.
31
+ const ownCommit = !checkout?.evidence && !(checkout && turn.remote && repositoryIdentity('', turn.remote).remote !== checkout.repository);
32
+ const git = context.capture.git === false || !repository ? undefined : { repository, branch: checkout?.branch ?? (checkout?.evidence ? undefined : turn.branch), commit: ownCommit ? turn.commit : undefined };
33
+ const summary = buildTurnSummary({
34
+ provider: turn.provider,
35
+ surface: turn.surface ?? DEFAULT_SURFACE,
36
+ sessionId: turn.sessionId,
37
+ turnId: turn.turnId,
38
+ developerId: context.developerId,
39
+ developerName: context.developerName,
40
+ installationId: context.installationId,
41
+ git,
42
+ featureCandidates: featureCandidatesFromBranch(git?.branch),
43
+ workEvidence: git ? (checkout?.evidence ?? 'cwd') : undefined,
44
+ prompts: [{ kind: 'prompt', at: turn.startedAt, turnId: turn.turnId, text: promptText(turn, context.capture) }],
45
+ tools: toolRecords(turn, checkout, context),
46
+ usage: turn.usage,
47
+ model: turn.usage?.model,
48
+ billingMode: context.billingMode,
49
+ endedAt: turn.endedAt
50
+ });
51
+ // `pending`, with the tokens: core's turn upsert keeps the higher status, and a live turn is
52
+ // `provisional`, so a replayed `provisional` one would overwrite what the hook sent. The
53
+ // tokens ride on either way; the status only feeds that guard.
54
+ return compact({ ...summary, id: replayEventId(turn), usage_status: 'pending' });
55
+ }
56
+ /**
57
+ * The event id of a replayed turn: its session and its turn id, nothing that varies between runs.
58
+ *
59
+ * @param turn - The turn.
60
+ * @returns The `evt_` id.
61
+ */
62
+ export function replayEventId(turn) {
63
+ return deriveEventId({
64
+ // A Claude turn's id is unchanged: its provider was always `claude`.
65
+ provider: turn.provider,
66
+ providerEventType: 'turn.summary',
67
+ sessionId: turn.sessionId,
68
+ turnId: turn.turnId,
69
+ payloadFingerprint: sha256Hex('replay')
70
+ });
71
+ }
72
+ /**
73
+ * The prompt text to send: only when the config allows it, scrubbed whole and then cut, as the live path does.
74
+ *
75
+ * @param turn - The turn.
76
+ * @param capture - The effective capture flags.
77
+ * @returns The text, or undefined.
78
+ */
79
+ function promptText(turn, capture) {
80
+ if (capture.promptText !== true || !turn.promptText)
81
+ return undefined;
82
+ return sanitizeText(turn.promptText).slice(0, MAX_PROMPT_TEXT_LENGTH) || undefined;
83
+ }
84
+ /**
85
+ * The turn's tool calls as the builder takes them: a name, a path inside the checkout, and, for a file in no checkout, what the live hook sends.
86
+ *
87
+ * A file in no checkout is a bare basename in the file lists (core's session-files subject and charge rung read those),
88
+ * and its home-relative path in the external lists (the Security page reads those). A file in another checkout is left out.
89
+ * `capture.files: false` withholds every path, and `capture.git: false` the external ones, as live.
90
+ *
91
+ * @param turn - The turn.
92
+ * @param checkout - The checkout paths are made relative to; undefined drops paths inside one.
93
+ * @param context - The capture flags and the home.
94
+ * @returns One record per call.
95
+ */
96
+ function toolRecords(turn, checkout, context) {
97
+ const files = context.capture.files !== false;
98
+ return turn.tools.map((tool) => ({
99
+ kind: 'tool',
100
+ at: turn.endedAt,
101
+ turnId: turn.turnId,
102
+ tool: tool.name,
103
+ access: tool.access,
104
+ filePath: files ? filePathOf(tool, checkout) : undefined,
105
+ externalPath: files && tool.outside && context.capture.git !== false ? externalPath(tool.path, undefined, context.home) : undefined
106
+ }));
107
+ }
108
+ function filePathOf(tool, checkout) {
109
+ if (tool.outside)
110
+ return path.basename(tool.path);
111
+ return checkout && relativeTo(checkout.root, tool);
112
+ }
113
+ /**
114
+ * A tool's file as a slash-separated path inside a checkout.
115
+ *
116
+ * @param root - The checkout root.
117
+ * @param tool - The call.
118
+ * @returns The path, or undefined when the file is not inside the root.
119
+ */
120
+ function relativeTo(root, tool) {
121
+ if (!tool.path || !path.isAbsolute(tool.path))
122
+ return undefined;
123
+ const relative = path.relative(root, tool.path);
124
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative))
125
+ return undefined;
126
+ return relative.split(path.sep).join('/');
127
+ }