@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
package/dist/cli/misc.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import process from 'node:process';
2
2
  import { eventsUrl, otlpBaseUrl, sharesOtlpCollector } from '../config/config.js';
3
3
  import { loadEffectiveConfig } from '../config/repo-config.js';
4
- import { applyRootOverride, credentialScope } from '../config/root-config.js';
4
+ import { applyRootOverride, credentialScope, isIgnoredRoot } from '../config/root-config.js';
5
5
  import { isAllowedHost } from '../config/schemas/config.schema.js';
6
6
  import { resolveBearer } from '../credentials/credentials.js';
7
7
  import { claudeExporterTargets, claudeOverrideTargets } from '../providers/claude/claude.otel.js';
@@ -99,7 +99,15 @@ export async function runOtelHeaders(env) {
99
99
  // The current access token, refreshed here whenever it would not outlast
100
100
  // Claude Code's debounce on this helper: what it prints is reused until then.
101
101
  // An install key still in the config is exchanged first.
102
- const shared = !context.disabled && sharesOtlpCollector(context.config, rooted) && (await exportsWhereConfigured(env, context.config));
102
+ // An ignored folder gets no bearer and no installation id: the exporter is the
103
+ // agent's own and goes straight to the backend, so a headerless export (401) is
104
+ // the only way this machine can make it hear nothing from that folder.
105
+ // ponytail: Claude Code runs this once per ~29 min, in the folder it runs in; a
106
+ // call already exported with a cached bearer, or a session whose folder changes
107
+ // mid-way, is not recalled. Codex and Gemini hold a static bearer in a config
108
+ // file and cannot be gated per folder from here.
109
+ const ignored = isIgnoredRoot(context.config.ignoredRoots, env.cwd);
110
+ const shared = !context.disabled && !ignored && sharesOtlpCollector(context.config, rooted) && (await exportsWhereConfigured(env, context.config));
103
111
  const token = shared ? await resolveBearer({ env, paths: context.paths, timeoutMs: rooted.delivery.timeoutMs, scope: credentialScope(root), minRemainingMs: OTEL_HEADERS_MIN_TOKEN_LIFE_MS }, rooted) : undefined;
104
112
  // The installation id rides with the bearer and on the same condition: an
105
113
  // export that carries no credential names no machine either. It is what lets
@@ -0,0 +1,24 @@
1
+ /**
2
+ * npm's global `node_modules`, with any part npm masked found again.
3
+ *
4
+ * npm 11 masks what looks like a secret in everything it prints, and a UUID
5
+ * looks like an old npm token: a prefix under `/tmp/<uuid>/` or a CI runner's
6
+ * work folder comes back from `npm root -g` as `/tmp/***`. Read as printed,
7
+ * that path does not exist, so the npx hand-off crashed and `update` called a
8
+ * global install not one. Under `npx` the prefix is taken from npm's own
9
+ * environment, which is never masked; elsewhere a masked segment is matched
10
+ * against the folder's real entries.
11
+ *
12
+ * @param vars - The environment.
13
+ * @param shell - Whether npm needs a shell to resolve (Windows).
14
+ * @returns The absolute folder, or undefined when npm cannot say or it cannot be found.
15
+ */
16
+ export declare function npmGlobalRoot(vars: NodeJS.ProcessEnv, shell: boolean): string | undefined;
17
+ /**
18
+ * The one existing path a masked path can stand for.
19
+ *
20
+ * @param printed - A path as npm printed it.
21
+ * @returns The path, unchanged when nothing is masked; undefined when it is not
22
+ * absolute, or no existing path or more than one matches it.
23
+ */
24
+ export declare function unmaskPath(printed: string): string | undefined;
@@ -0,0 +1,77 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, readdirSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { NPM_GLOBAL_PREFIX_VAR, NPM_REDACTION, RE_PATH_SEPARATORS, RE_UUID } from './constants/cli.constants.js';
5
+ /**
6
+ * npm's global `node_modules`, with any part npm masked found again.
7
+ *
8
+ * npm 11 masks what looks like a secret in everything it prints, and a UUID
9
+ * looks like an old npm token: a prefix under `/tmp/<uuid>/` or a CI runner's
10
+ * work folder comes back from `npm root -g` as `/tmp/***`. Read as printed,
11
+ * that path does not exist, so the npx hand-off crashed and `update` called a
12
+ * global install not one. Under `npx` the prefix is taken from npm's own
13
+ * environment, which is never masked; elsewhere a masked segment is matched
14
+ * against the folder's real entries.
15
+ *
16
+ * @param vars - The environment.
17
+ * @param shell - Whether npm needs a shell to resolve (Windows).
18
+ * @returns The absolute folder, or undefined when npm cannot say or it cannot be found.
19
+ */
20
+ export function npmGlobalRoot(vars, shell) {
21
+ const prefix = vars[NPM_GLOBAL_PREFIX_VAR];
22
+ // npm's layout: <prefix>/node_modules on Windows, <prefix>/lib/node_modules elsewhere.
23
+ if (prefix && path.isAbsolute(prefix))
24
+ return shell ? path.join(prefix, 'node_modules') : path.join(prefix, 'lib', 'node_modules');
25
+ const printed = spawnSync('npm', ['root', '-g'], { encoding: 'utf8', shell }).stdout?.trim();
26
+ return printed ? unmaskPath(printed) : undefined;
27
+ }
28
+ /**
29
+ * The one existing path a masked path can stand for.
30
+ *
31
+ * @param printed - A path as npm printed it.
32
+ * @returns The path, unchanged when nothing is masked; undefined when it is not
33
+ * absolute, or no existing path or more than one matches it.
34
+ */
35
+ export function unmaskPath(printed) {
36
+ if (!path.isAbsolute(printed))
37
+ return undefined;
38
+ if (!printed.includes(NPM_REDACTION))
39
+ return printed;
40
+ const { root } = path.parse(printed);
41
+ const found = existingPaths(root, printed.slice(root.length).split(RE_PATH_SEPARATORS).filter(Boolean));
42
+ return found.length === 1 ? found[0] : undefined;
43
+ }
44
+ /**
45
+ * Every existing path under `dir` the segments can name. An entry fits a
46
+ * masked segment when masking its UUIDs the way npm does gives that segment.
47
+ * Several matching folders under one parent are common (one per CI job), so a
48
+ * segment is not decided before the rest of the path is.
49
+ *
50
+ * @param dir - Folder resolved so far.
51
+ * @param segments - The rest of the printed path.
52
+ * @returns The matching paths, at most two (enough to call it ambiguous).
53
+ */
54
+ function existingPaths(dir, segments) {
55
+ const [segment, ...rest] = segments;
56
+ if (segment === undefined)
57
+ return existsSync(dir) ? [dir] : [];
58
+ if (!segment.includes(NPM_REDACTION))
59
+ return existingPaths(path.join(dir, segment), rest);
60
+ const found = [];
61
+ for (const entry of entriesOf(dir)) {
62
+ if (entry.replace(RE_UUID, NPM_REDACTION) !== segment)
63
+ continue;
64
+ found.push(...existingPaths(path.join(dir, entry), rest));
65
+ if (found.length > 1)
66
+ break;
67
+ }
68
+ return found;
69
+ }
70
+ function entriesOf(dir) {
71
+ try {
72
+ return readdirSync(dir);
73
+ }
74
+ catch {
75
+ return [];
76
+ }
77
+ }
@@ -1,7 +1,9 @@
1
1
  import { spawnSync } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
2
3
  import { createRequire } from 'node:module';
3
4
  import path from 'node:path';
4
5
  import { NPX_CACHE_SEGMENT, NPX_HANDOFF_VAR } from './constants/cli.constants.js';
6
+ import { npmGlobalRoot } from './npm-global.js';
5
7
  import { printErrln, symbols } from './ui.js';
6
8
  /**
7
9
  * Whether this process runs from npx's download cache, and has not already
@@ -58,18 +60,24 @@ export function installGloballyAndHandOff(setupArgs) {
58
60
  printErrln(`${symbols.fail} could not install ${spec} globally; ${manual}`);
59
61
  return 1;
60
62
  }
61
- const prefix = spawnSync('npm', ['prefix', '-g'], { encoding: 'utf8', shell }).stdout?.trim();
62
- const root = spawnSync('npm', ['root', '-g'], { encoding: 'utf8', shell }).stdout?.trim();
63
- if (!prefix || !root || !path.isAbsolute(prefix) || !path.isAbsolute(root)) {
63
+ const root = npmGlobalRoot(process.env, shell);
64
+ if (!root) {
64
65
  printErrln(`${symbols.fail} could not find npm's global folder; ${manual}`);
65
66
  return 1;
66
67
  }
67
- // Windows puts the global shims in the prefix itself; everything else in prefix/bin.
68
- const globalBin = shell ? prefix : path.join(prefix, 'bin');
69
- const env = { ...process.env, PATH: handoffPath(process.env['PATH'] ?? '', globalBin), [NPX_HANDOFF_VAR]: '1' };
70
68
  // The installed entry point under node, never a shim through a shell: the
71
69
  // arguments carry the token, and cmd.exe would interpret them.
72
70
  const cli = path.join(root, pkg.name, 'dist', 'cli.js');
71
+ // The prefix npx was run with may belong to another npm than the one on PATH
72
+ // that just installed: hand off only to the version installed here.
73
+ if (!existsSync(cli) || installedVersion(path.join(root, pkg.name)) !== pkg.version) {
74
+ printErrln(`${symbols.fail} installed ${spec} but did not find it in ${root}; ${manual}`);
75
+ return 1;
76
+ }
77
+ // npm's global root is <prefix>/node_modules on Windows, with the shims in the
78
+ // prefix itself; elsewhere <prefix>/lib/node_modules, with the shims in <prefix>/bin.
79
+ const globalBin = shell ? path.dirname(root) : path.join(root, '..', '..', 'bin');
80
+ const env = { ...process.env, PATH: handoffPath(process.env['PATH'] ?? '', globalBin), [NPX_HANDOFF_VAR]: '1' };
73
81
  const setup = spawnSync(process.execPath, [cli, ...setupArgs], { stdio: 'inherit', env });
74
82
  if (setup.error || setup.status === null) {
75
83
  printErrln(`${symbols.fail} installed ${spec} but could not start it; ${manual}`);
@@ -77,3 +85,11 @@ export function installGloballyAndHandOff(setupArgs) {
77
85
  }
78
86
  return setup.status;
79
87
  }
88
+ function installedVersion(dir) {
89
+ try {
90
+ return JSON.parse(readFileSync(path.join(dir, 'package.json'), 'utf8')).version;
91
+ }
92
+ catch {
93
+ return undefined;
94
+ }
95
+ }
@@ -0,0 +1,33 @@
1
+ import type { Env } from '../core/types/core.types.js';
2
+ /** What `agentwatch replay` was given. */
3
+ export interface ReplayCommandOptions {
4
+ readonly env: Env;
5
+ /** Select the machine identity regardless of the shell's directory. */
6
+ readonly machine?: boolean;
7
+ /** Select the configured identity governing this root regardless of the shell's directory. */
8
+ readonly root?: string;
9
+ /** `--replay-days`, as typed. */
10
+ readonly days?: string;
11
+ /** `--resume`: continue an unfinished replay; begin none. */
12
+ readonly resume: boolean;
13
+ /** `--stop`: end the replay. */
14
+ readonly stop: boolean;
15
+ /** `--dry-run`: build and count, send and write nothing. */
16
+ readonly dryRun: boolean;
17
+ /** Internal: setup's start, which never repeats an earlier replay attempt. */
18
+ readonly skipIfExisting: boolean;
19
+ /** Internal: atomically consume the machine's one automatic replay. */
20
+ readonly claimAutomatic?: boolean;
21
+ }
22
+ /**
23
+ * `agentwatch replay` — send this developer's earlier Claude Code, Codex and Gemini CLI sessions to the backend, slowly.
24
+ *
25
+ * Setup starts it in the background; run by hand it works in the foreground
26
+ * and can be interrupted (a rerun or `--resume` carries on from the last
27
+ * finished transcript). What it sends is exactly what the hooks send for a
28
+ * turn, from the transcripts on disk (see docs/DATA_HANDLING.md).
29
+ *
30
+ * @param options - The flags.
31
+ * @returns 0, or 1 when it could not start.
32
+ */
33
+ export declare function runReplayCommand(options: ReplayCommandOptions): Promise<number>;
@@ -0,0 +1,228 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import process from 'node:process';
4
+ import { sleep } from '../core/async.js';
5
+ import { hasCredential, identityFingerprint, identityOf } from '../credentials/identity.js';
6
+ import { billingModeOf } from '../billing/billing-mode.js';
7
+ import { claudeProvider } from '../providers/claude/claude.provider.js';
8
+ import { loadProvider } from '../providers/loaders.js';
9
+ import { isIgnoredRoot, selectRoot } from '../config/root-config.js';
10
+ import { loadEffectiveConfig } from '../config/repo-config.js';
11
+ import { developerDisplayName, developerIdentity } from '../git/git-context.js';
12
+ import { createCheckoutResolver } from '../replay/checkout-resolver.js';
13
+ import { learnWorktrees } from '../replay/worktree-map.js';
14
+ import { REPLAY_BATTERY_CHECK_MS, REPLAY_SEND_TIMEOUT_MS } from '../replay/constants/replay.constants.js';
15
+ import { hookAgeMs, readLoad, readOnBattery } from '../replay/machine.js';
16
+ import { claimAutomaticReplay, replayStateFile } from '../replay/replay-state.js';
17
+ import { codexHome } from '../providers/codex/codex.detect.js';
18
+ import { GEMINI_PROVIDER_ID } from '../providers/gemini/constants/gemini.constants.js';
19
+ import { geminiSettingsPath } from '../providers/gemini/gemini.detect.js';
20
+ import { codexSource } from '../replay/codex-turns.js';
21
+ import { geminiSource } from '../replay/gemini-turns.js';
22
+ import { claudeProjectsDir, claudeSource } from '../replay/replay-scan.js';
23
+ import { runReplay, stopReplay } from '../replay/replay-runner.js';
24
+ import { parseReplayDays } from '../replay/window.js';
25
+ import { identityPaths } from '../transport/queue-partition.js';
26
+ import { buildCliContext, buildTransport, openIdentityDelivery, quoteArg, resolveContextBearer } from './context.js';
27
+ import { bold, dim, println, symbols } from './ui.js';
28
+ /**
29
+ * `agentwatch replay` — send this developer's earlier Claude Code, Codex and Gemini CLI sessions to the backend, slowly.
30
+ *
31
+ * Setup starts it in the background; run by hand it works in the foreground
32
+ * and can be interrupted (a rerun or `--resume` carries on from the last
33
+ * finished transcript). What it sends is exactly what the hooks send for a
34
+ * turn, from the transcripts on disk (see docs/DATA_HANDLING.md).
35
+ *
36
+ * @param options - The flags.
37
+ * @returns 0, or 1 when it could not start.
38
+ */
39
+ export async function runReplayCommand(options) {
40
+ const days = parseReplayDays(options.days);
41
+ // Setup's automatic replay inherits the shell's environment; an operator window is never meant for it.
42
+ const window = options.claimAutomatic === true ? undefined : operatorWindow(options.env.vars);
43
+ if (days === undefined) {
44
+ println(`${symbols.fail} invalid --replay-days "${options.days}" (expected a whole number of days, 1 to 366)`);
45
+ return 1;
46
+ }
47
+ if (typeof window === 'string') {
48
+ println(`${symbols.fail} ${window}`);
49
+ return 1;
50
+ }
51
+ if (options.machine === true && options.root !== undefined) {
52
+ println(`${symbols.fail} choose either --machine or --root, not both`);
53
+ return 1;
54
+ }
55
+ let identityAt;
56
+ if (options.machine === true)
57
+ identityAt = null;
58
+ if (options.root !== undefined)
59
+ identityAt = path.resolve(options.env.cwd, options.root);
60
+ const context = await buildCliContext(options.env, identityAt);
61
+ if (options.root !== undefined && context.identityRoot === undefined) {
62
+ println(`${symbols.fail} no replay identity is configured for root ${identityAt}`);
63
+ return 1;
64
+ }
65
+ let replayCommand = 'agentwatch replay';
66
+ if (options.machine === true)
67
+ replayCommand = 'agentwatch replay --machine';
68
+ if (context.identityRoot !== undefined)
69
+ replayCommand = `agentwatch replay --root ${quoteArg(context.identityRoot)}`;
70
+ const ports = await buildPorts(context, options.dryRun);
71
+ if (typeof ports === 'string') {
72
+ println(`${symbols.fail} ${ports}`);
73
+ return 1;
74
+ }
75
+ if (options.stop)
76
+ return report(await stopReplay(ports), replayCommand);
77
+ if (options.dryRun)
78
+ return runDry(ports, days, window);
79
+ if (options.claimAutomatic === true && !(await claimAutomaticReplay(context.paths.configDir, context.paths.dataDir))) {
80
+ println(`${symbols.off} automatic historical replay was already attempted on this machine`);
81
+ return 0;
82
+ }
83
+ const period = window ? `${window.start.toISOString()} to ${window.end.toISOString()}` : `the last ${days} days`;
84
+ if (!options.resume)
85
+ println(`Replaying ${period} of Claude Code, Codex and Gemini CLI sessions. ${dim(`Ctrl-C stops it; \`${replayCommand} --resume\` carries on.`)}`);
86
+ return report(await runReplay(ports, { days, window, resume: options.resume, dryRun: false, skipIfExisting: options.skipIfExisting }), replayCommand);
87
+ }
88
+ /**
89
+ * Count what a replay would send, and what that cost this machine.
90
+ *
91
+ * @param ports - The machine.
92
+ * @param days - The window.
93
+ * @returns 0.
94
+ */
95
+ async function runDry(ports, days, window) {
96
+ const started = performance.now();
97
+ const result = await runReplay(ports, { days, window, resume: false, dryRun: true, skipIfExisting: false });
98
+ const wallMs = performance.now() - started;
99
+ const usage = process.resourceUsage();
100
+ println(bold('Replay dry run — nothing was sent or written'));
101
+ println(`window: ${result.record?.windowStart} to ${result.record?.windowEnd}`);
102
+ println(`transcripts: ${result.dry?.files ?? 0}`);
103
+ println(`turns counted ahead of sending: ${result.dry?.estimate ?? 0}`);
104
+ println(`turns that would be sent: ${result.dry?.turns ?? 0}`);
105
+ println(`repositories: ${result.dry?.repositories ?? 0}`);
106
+ for (const [agent, counts] of Object.entries(result.dry?.agents ?? {}))
107
+ println(` ${agent}: ${counts.files} files, ${counts.turns} turns`);
108
+ println(`wall ${(wallMs / 1000).toFixed(1)} s, cpu ${((usage.userCPUTime + usage.systemCPUTime) / 1e6).toFixed(1)} s, peak memory ${(usage.maxRSS / 1024).toFixed(0)} MB`);
109
+ return 0;
110
+ }
111
+ function operatorWindow(vars) {
112
+ const from = vars.AGENTWATCH_OPERATOR_REPLAY_FROM;
113
+ const until = vars.AGENTWATCH_OPERATOR_REPLAY_UNTIL;
114
+ if (from === undefined && until === undefined)
115
+ return undefined;
116
+ if (from === undefined || until === undefined)
117
+ return 'operator replay needs both window bounds';
118
+ const start = new Date(from);
119
+ const end = new Date(until);
120
+ if (!Number.isFinite(start.getTime()) || !Number.isFinite(end.getTime()) || start >= end)
121
+ return 'operator replay window is invalid';
122
+ return { start, end };
123
+ }
124
+ function report(result, replayCommand) {
125
+ println(`${result.outcome === 'skipped' ? symbols.off : symbols.ok} ${result.message.replace('agentwatch replay', replayCommand)}`);
126
+ return 0;
127
+ }
128
+ /**
129
+ * Everything a run takes from this machine, or why it cannot run.
130
+ *
131
+ * @param context - Resolved CLI context.
132
+ * @param dryRun - A dry run needs no backend and no credential.
133
+ * @returns The ports, or a sentence saying what is missing.
134
+ */
135
+ async function buildPorts(context, dryRun) {
136
+ const { env } = context;
137
+ const config = context.identityConfig;
138
+ const token = identityOf(config);
139
+ if (!dryRun) {
140
+ if (context.disabled)
141
+ return 'AgentWatch is disabled; run `agentwatch on` first';
142
+ if (context.configState === 'invalid')
143
+ return `the config at ${context.paths.configFile} is invalid`;
144
+ if (!hasCredential(config) || !config.endpoint)
145
+ return 'no backend is configured here; run `agentwatch setup`';
146
+ }
147
+ const developerId = (await developerIdentity(config.developerEmail, env.cwd, { home: env.home })) ?? (dryRun ? 'dry-run' : undefined);
148
+ if (!developerId)
149
+ return 'no developer identity: pass --developer-email to `agentwatch setup`, or set git user.email';
150
+ const paths = identityPaths(context.paths, token);
151
+ const opened = openIdentityDelivery(context);
152
+ let battery;
153
+ const worktrees = new Map();
154
+ const checkout = createCheckoutResolver(worktrees);
155
+ return {
156
+ env,
157
+ paths: context.paths,
158
+ config,
159
+ stateFile: replayStateFile(paths.statsFile),
160
+ identity: token ? identityFingerprint(token) : 'dry-run',
161
+ developerId,
162
+ developerName: await developerDisplayName(config.developerName, env.cwd, { home: env.home }),
163
+ installationId: config.installationId,
164
+ billingMode: await billingModeOf(claudeProvider, env),
165
+ sources: await replaySources(context),
166
+ transport: async () => (dryRun ? undefined : buildTransport(context, REPLAY_SEND_TIMEOUT_MS, await resolveContextBearer(context, REPLAY_SEND_TIMEOUT_MS))),
167
+ queue: opened.queue,
168
+ authBlock: opened.authBlock,
169
+ cooldown: opened.cooldown,
170
+ inScope: (cwd) => !isIgnoredRoot(context.config.ignoredRoots, cwd) && selectRoot(context.config.roots, cwd)?.path === context.identityRoot,
171
+ checkout,
172
+ learnWorktrees: (learned) => learnWorktrees(worktrees, learned),
173
+ localCheckouts: async () => childCheckouts(context.identityRoot, checkout),
174
+ captureFor: cachedCaptureFor(async (cwd) => (await loadEffectiveConfig(context.paths, cwd)).config.capture),
175
+ machine: async () => {
176
+ const nowMs = env.now().getTime();
177
+ // `pmset` is a process start: asked every few minutes, not every batch.
178
+ if (!battery || nowMs - battery.at >= REPLAY_BATTERY_CHECK_MS)
179
+ battery = { at: nowMs, on: await readOnBattery(env.platform) };
180
+ return { ...readLoad(), onBattery: battery.on, hookAgeMs: await hookAgeMs(context.paths, nowMs) };
181
+ },
182
+ sleep,
183
+ log: (line) => println(dim(line))
184
+ };
185
+ }
186
+ async function childCheckouts(root, checkout) {
187
+ if (!root)
188
+ return [];
189
+ const entries = await fs.readdir(root, { withFileTypes: true }).catch(() => []);
190
+ const found = await Promise.all(entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith('.')).map((entry) => checkout(path.join(root, entry.name))));
191
+ // ponytail: rooted replay scans direct children only. That covers the workspace layout without
192
+ // walking node_modules; a future repository index can replace this if nested repos become common.
193
+ return [...new Map(found.filter((item) => item !== undefined).map((item) => [item.root, item])).values()];
194
+ }
195
+ /**
196
+ * The agents whose transcripts a replay reads, each where its provider looks for them, with its billing mode.
197
+ *
198
+ * @param context - Resolved CLI context.
199
+ * @returns Claude Code, Codex and Gemini CLI.
200
+ */
201
+ async function replaySources(context) {
202
+ const { env } = context;
203
+ const firstInstalledAt = context.installState.agents[GEMINI_PROVIDER_ID]?.hooksFirstInstalledAt;
204
+ const firstInstalledMs = firstInstalledAt === undefined ? undefined : Date.parse(firstInstalledAt);
205
+ const sources = [
206
+ claudeSource(claudeProjectsDir(env.home), env.home),
207
+ codexSource(codexHome(env)),
208
+ geminiSource(path.dirname(geminiSettingsPath(env)), Number.isNaN(firstInstalledMs) ? undefined : firstInstalledMs)
209
+ ];
210
+ return Promise.all(sources.map(async (source) => {
211
+ const provider = await loadProvider(source.agent);
212
+ return { ...source, billingMode: await billingModeOf(provider, env) };
213
+ }));
214
+ }
215
+ /**
216
+ * Remember each folder's answer for the run: the repo file is read once per folder, not once per turn.
217
+ *
218
+ * @param read - Reads the capture flags in force for a folder.
219
+ * @returns The same question, answered from memory after the first time.
220
+ */
221
+ function cachedCaptureFor(read) {
222
+ const answers = new Map();
223
+ return (cwd) => {
224
+ const known = answers.get(cwd) ?? read(cwd);
225
+ answers.set(cwd, known);
226
+ return known;
227
+ };
228
+ }
@@ -10,10 +10,18 @@ export type { SetupOptions } from './types/cli.types.js';
10
10
  * a missing token fails the run before the first file is touched. No endpoint
11
11
  * at all means the production Agent Watch backend.
12
12
  *
13
+ * `--cloud` is the managed SessionStart hook of a Claude Code cloud VM: it
14
+ * claims a device from the organization's managed settings and then runs the
15
+ * same config write and agent install. It returns 0 on every path, so a cloud
16
+ * session never fails over Agent Watch; a VM that already has a credential,
17
+ * or is no cloud session, returns at once.
18
+ *
13
19
  * @param options - Environment and flags.
14
- * @returns 0 when every step succeeded, else 1.
20
+ * @returns 0 when every step succeeded, else 1 (always 0 with `cloud`).
15
21
  */
16
- export declare function runSetup(options: SetupOptions): Promise<number>;
22
+ export declare function runSetup(options: SetupOptions & {
23
+ readonly cloud?: boolean;
24
+ }): Promise<number>;
17
25
  /**
18
26
  * What to call this developer: the flag, then the config, then `git config
19
27
  * user.name`.