@agent-watch-ai/edge 0.7.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 (82) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +4 -1
  3. package/dist/billing/session-billing.d.ts +5 -2
  4. package/dist/billing/session-billing.js +27 -6
  5. package/dist/capture/captured-step.js +24 -0
  6. package/dist/capture/constants/capture.constants.d.ts +15 -0
  7. package/dist/capture/constants/capture.constants.js +15 -0
  8. package/dist/capture/launched-runs.d.ts +27 -0
  9. package/dist/capture/launched-runs.js +15 -9
  10. package/dist/capture/python/sitecustomize.py +11 -2
  11. package/dist/capture/venv-loader.d.ts +68 -0
  12. package/dist/capture/venv-loader.js +189 -0
  13. package/dist/cli/constants/cli.constants.d.ts +21 -0
  14. package/dist/cli/constants/cli.constants.js +21 -0
  15. package/dist/cli/doctor-run-capture.d.ts +8 -0
  16. package/dist/cli/doctor-run-capture.js +14 -0
  17. package/dist/cli/doctor.js +6 -2
  18. package/dist/cli/hook-check.d.ts +7 -2
  19. package/dist/cli/hook-check.js +30 -15
  20. package/dist/cli/hook.js +44 -3
  21. package/dist/cli/npm-global.d.ts +24 -0
  22. package/dist/cli/npm-global.js +77 -0
  23. package/dist/cli/npx-install.js +22 -6
  24. package/dist/cli/replay.js +42 -7
  25. package/dist/cli/setup.js +47 -6
  26. package/dist/cli/uninstall.js +34 -1
  27. package/dist/cli/update.js +3 -2
  28. package/dist/config/config-store.d.ts +15 -4
  29. package/dist/config/config-store.js +31 -7
  30. package/dist/config/constants/config.constants.d.ts +8 -1
  31. package/dist/config/constants/config.constants.js +8 -1
  32. package/dist/config/schemas/config.schema.d.ts +2 -2
  33. package/dist/config/schemas/config.schema.js +10 -2
  34. package/dist/credentials/cloud-claim.d.ts +2 -0
  35. package/dist/credentials/cloud-claim.js +21 -2
  36. package/dist/credentials/constants/credentials.constants.d.ts +8 -0
  37. package/dist/credentials/constants/credentials.constants.js +8 -0
  38. package/dist/credentials/credential-status.js +1 -1
  39. package/dist/credentials/credentials.d.ts +3 -3
  40. package/dist/credentials/credentials.js +26 -12
  41. package/dist/credentials/identity.d.ts +2 -2
  42. package/dist/credentials/identity.js +2 -2
  43. package/dist/credentials/install-key.d.ts +31 -0
  44. package/dist/credentials/install-key.js +58 -0
  45. package/dist/credentials/migration.d.ts +9 -7
  46. package/dist/credentials/migration.js +58 -18
  47. package/dist/credentials/secret-store.d.ts +12 -0
  48. package/dist/credentials/secret-store.js +18 -1
  49. package/dist/enforcement/enforcement.js +1 -1
  50. package/dist/events/enrich.d.ts +14 -0
  51. package/dist/events/enrich.js +1 -1
  52. package/dist/git/constants/git.constants.d.ts +2 -0
  53. package/dist/git/constants/git.constants.js +9 -0
  54. package/dist/git/repo-snapshot.js +8 -2
  55. package/dist/git/types/snapshot.types.d.ts +4 -0
  56. package/dist/pipeline/hook-pipeline.js +2 -1
  57. package/dist/providers/claude/claude.provider.js +9 -5
  58. package/dist/providers/types/provider.types.d.ts +5 -5
  59. package/dist/replay/checkout-resolver.d.ts +41 -14
  60. package/dist/replay/checkout-resolver.js +134 -30
  61. package/dist/replay/replay-runner.d.ts +3 -1
  62. package/dist/replay/replay-runner.js +74 -22
  63. package/dist/replay/replay-scan.d.ts +2 -1
  64. package/dist/replay/replay-scan.js +14 -2
  65. package/dist/replay/throttle.d.ts +2 -1
  66. package/dist/replay/throttle.js +4 -1
  67. package/dist/replay/transcript-turns.js +29 -3
  68. package/dist/replay/turn-event.d.ts +4 -2
  69. package/dist/replay/turn-event.js +22 -11
  70. package/dist/replay/types/replay.types.d.ts +39 -3
  71. package/dist/replay/worktree-map.d.ts +42 -0
  72. package/dist/replay/worktree-map.js +134 -0
  73. package/dist/snapshot/snapshot-pipeline.js +15 -4
  74. package/dist/snapshot/types/snapshot.types.d.ts +2 -0
  75. package/dist/turns/constants/turns.constants.d.ts +16 -0
  76. package/dist/turns/constants/turns.constants.js +16 -0
  77. package/dist/turns/turn-state.d.ts +33 -0
  78. package/dist/turns/turn-state.js +80 -1
  79. package/dist/turns/turn-tracker.js +2 -2
  80. package/docs/DATA_HANDLING.md +8 -6
  81. package/docs/ENTERPRISE_DEPLOYMENT.md +2 -2
  82. package/package.json +1 -1
@@ -55,6 +55,12 @@ export declare const BACKEND_PROBE_TIMEOUT_MS = 4000;
55
55
  /** What the gateway answers an authenticated `{ events: [] }`: it checks the credential first. */
56
56
  export declare const EMPTY_BATCH_REFUSED_STATUS = 422;
57
57
  export declare const GIT_VERSION_TIMEOUT_MS = 2000;
58
+ /**
59
+ * The installed hook command's `--version` probe. A healthy one took up to
60
+ * 2.7 s on a loaded Mac, where `node -e 0` alone took about 1 s: only a hung
61
+ * install should fail it. Probed once per doctor run, not once per agent.
62
+ */
63
+ export declare const HOOK_VERSION_TIMEOUT_MS = 10000;
58
64
  /** Longer than the hook path's budget: status is not on anyone's critical path. */
59
65
  export declare const STATUS_SEND_TIMEOUT_MS = 3000;
60
66
  /** Backlog age past which `doctor` starts warning. */
@@ -102,3 +108,18 @@ export declare const BROWSER_OPENERS: Partial<Record<NodeJS.Platform, readonly s
102
108
  export declare const DEFAULT_BROWSER_OPENER: readonly string[];
103
109
  /** The only link schemes setup hands to a browser opener: the gateway chose the link. */
104
110
  export declare const OPENABLE_PROTOCOLS: ReadonlySet<string>;
111
+ /** What npm 11 prints in place of anything that looks like a secret, a UUID included. */
112
+ export declare const NPM_REDACTION = "***";
113
+ /**
114
+ * A UUID, which npm masks in a path because it looks like a legacy npm token.
115
+ * npm also masks `npm_` tokens and URL passwords; those are not found again and
116
+ * get the manual message. Global flag: use with `replace` only, never `test`.
117
+ */
118
+ export declare const RE_UUID: RegExp;
119
+ /** Both separators: on Windows npm may print either. */
120
+ export declare const RE_PATH_SEPARATORS: RegExp;
121
+ /**
122
+ * Set by npm in the environment of what `npx` runs: the global prefix in full,
123
+ * never masked the way npm's printed output is.
124
+ */
125
+ export declare const NPM_GLOBAL_PREFIX_VAR = "npm_config_global_prefix";
@@ -55,6 +55,12 @@ export const BACKEND_PROBE_TIMEOUT_MS = 4_000;
55
55
  /** What the gateway answers an authenticated `{ events: [] }`: it checks the credential first. */
56
56
  export const EMPTY_BATCH_REFUSED_STATUS = 422;
57
57
  export const GIT_VERSION_TIMEOUT_MS = 2_000;
58
+ /**
59
+ * The installed hook command's `--version` probe. A healthy one took up to
60
+ * 2.7 s on a loaded Mac, where `node -e 0` alone took about 1 s: only a hung
61
+ * install should fail it. Probed once per doctor run, not once per agent.
62
+ */
63
+ export const HOOK_VERSION_TIMEOUT_MS = 10_000;
58
64
  /** Longer than the hook path's budget: status is not on anyone's critical path. */
59
65
  export const STATUS_SEND_TIMEOUT_MS = 3_000;
60
66
  /** Backlog age past which `doctor` starts warning. */
@@ -105,3 +111,18 @@ export const BROWSER_OPENERS = {
105
111
  export const DEFAULT_BROWSER_OPENER = ['xdg-open'];
106
112
  /** The only link schemes setup hands to a browser opener: the gateway chose the link. */
107
113
  export const OPENABLE_PROTOCOLS = new Set(['http:', 'https:']);
114
+ /** What npm 11 prints in place of anything that looks like a secret, a UUID included. */
115
+ export const NPM_REDACTION = '***';
116
+ /**
117
+ * A UUID, which npm masks in a path because it looks like a legacy npm token.
118
+ * npm also masks `npm_` tokens and URL passwords; those are not found again and
119
+ * get the manual message. Global flag: use with `replace` only, never `test`.
120
+ */
121
+ export const RE_UUID = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
122
+ /** Both separators: on Windows npm may print either. */
123
+ export const RE_PATH_SEPARATORS = /[\\/]/;
124
+ /**
125
+ * Set by npm in the environment of what `npx` runs: the global prefix in full,
126
+ * never masked the way npm's printed output is.
127
+ */
128
+ export const NPM_GLOBAL_PREFIX_VAR = 'npm_config_global_prefix';
@@ -11,3 +11,11 @@ import type { Check } from './types/cli.types.js';
11
11
  * @returns The check.
12
12
  */
13
13
  export declare function runCaptureCheck(provider: AgentProvider, context: SetupContext): Promise<Check>;
14
+ /**
15
+ * The virtual environments holding Edge's loader for `python -I` runs, so a developer who
16
+ * finds the `.pth` in their venv can see where it came from and that uninstall takes it.
17
+ *
18
+ * @param dataDir - The data dir.
19
+ * @returns The check, or undefined when no venv holds one.
20
+ */
21
+ export declare function venvLoaderCheck(dataDir: string): Promise<Check | undefined>;
@@ -1,3 +1,4 @@
1
+ import { recordedVenvs } from '../capture/venv-loader.js';
1
2
  import { runCaptureRoute } from '../providers/provider.js';
2
3
  /**
3
4
  * Whether one agent's environment route is in place, and what is missing when not.
@@ -17,3 +18,16 @@ export async function runCaptureCheck(provider, context) {
17
18
  return { name, level: 'warn', detail: `off: ${status.reason ?? 'unknown'}` };
18
19
  return status.warning ? { name, level: 'warn', detail: `on: ${status.warning}` } : { name, level: 'ok', detail: 'on' };
19
20
  }
21
+ /**
22
+ * The virtual environments holding Edge's loader for `python -I` runs, so a developer who
23
+ * finds the `.pth` in their venv can see where it came from and that uninstall takes it.
24
+ *
25
+ * @param dataDir - The data dir.
26
+ * @returns The check, or undefined when no venv holds one.
27
+ */
28
+ export async function venvLoaderCheck(dataDir) {
29
+ const folders = await recordedVenvs(dataDir);
30
+ if (folders.length === 0)
31
+ return undefined;
32
+ return { name: 'Python run capture loaders', level: 'ok', detail: `${folders.length} venv(s), removed by \`agentwatch uninstall\`: ${folders.join(', ')}` };
33
+ }
@@ -21,7 +21,7 @@ import { discardResponseBody } from '../transport/response-body.js';
21
21
  import { edgeHeaders } from '../transport/headers.js';
22
22
  import { DEVICE_SOURCE_BATCH_CODE } from '../credentials/constants/credentials.constants.js';
23
23
  import { buildCliContext, buildHookCommand, buildQueue, openIdentityDelivery, resolveContextBearer } from './context.js';
24
- import { runCaptureCheck } from './doctor-run-capture.js';
24
+ import { runCaptureCheck, venvLoaderCheck } from './doctor-run-capture.js';
25
25
  import { installedHookChecks } from './hook-check.js';
26
26
  import { BACKEND_CONNECTIVITY_CHECK, BACKEND_PROBE_TIMEOUT_MS, EMPTY_BATCH_REFUSED_STATUS, DEVELOPER_IDENTITY_CHECK, DEVELOPER_IDENTITY_REMEDIES, DEVELOPER_NAME_REMEDIES, GIT_VERSION_TIMEOUT_MS, MIN_NODE_MAJOR, NO_DEVELOPER_IDENTITY, NO_DEVELOPER_NAME, STALE_QUEUE_AGE_MS } from './constants/cli.constants.js';
27
27
  import { bold, customEndpointOverride, dim, levelSymbol, println } from './ui.js';
@@ -420,9 +420,10 @@ async function gitCheck() {
420
420
  */
421
421
  async function agentChecks(env, context) {
422
422
  const checks = [];
423
+ const probes = new Map();
423
424
  for (const provider of providers) {
424
425
  const detection = await provider.detect(env);
425
- checks.push(...(await installedHookChecks(detection.hookConfigPath, env)).map((check) => ({ ...check, name: `${provider.displayName} ${check.name}` })));
426
+ checks.push(...(await installedHookChecks(detection.hookConfigPath, env, probes)).map((check) => ({ ...check, name: `${provider.displayName} ${check.name}` })));
426
427
  if (!detection.detected) {
427
428
  checks.push({ name: provider.displayName, level: 'warn', detail: 'not detected' });
428
429
  continue;
@@ -439,6 +440,9 @@ async function agentChecks(env, context) {
439
440
  if (!context.disabled)
440
441
  checks.push(await runCaptureCheck(provider, { env, paths: context.paths, config: context.identityConfig, hookCommand: buildHookCommand(env, provider.id), installState: context.installState }));
441
442
  }
443
+ const loaders = await venvLoaderCheck(context.paths.dataDir);
444
+ if (loaders)
445
+ checks.push(loaders);
442
446
  return checks;
443
447
  }
444
448
  /**
@@ -9,15 +9,20 @@ import type { Check } from './types/cli.types.js';
9
9
  *
10
10
  * @param file - User hook configuration path.
11
11
  * @param env - Launch environment to validate.
12
+ * @param probes - Version probes already run, shared across one doctor run:
13
+ * every agent's hook runs the same CLI, so it is probed once.
12
14
  * @returns A finding for every distinct managed command.
13
15
  */
14
- export declare function installedHookChecks(file: string, env: Env): Promise<Check[]>;
16
+ export declare function installedHookChecks(file: string, env: Env, probes?: Map<string, Promise<ProbeResult>>): Promise<Check[]>;
15
17
  /**
16
18
  * Validate a recognized hook without invoking a shell or an unknown installation.
17
19
  * @param command - Command from a user-scoped hook file.
18
20
  * @param env - Coding agent launch environment.
19
21
  * @param currentCli - Trusted running CLI, injectable for isolated tests.
20
22
  * @param timeoutMs - Maximum version probe duration.
23
+ * @param probes - Version probes already run, by runtime and CLI.
21
24
  * @returns A diagnostic without command output or credential values.
22
25
  */
23
- export declare function checkHookCommand(command: string, env: Env, currentCli?: string, timeoutMs?: number): Promise<Check>;
26
+ export declare function checkHookCommand(command: string, env: Env, currentCli?: string, timeoutMs?: number, probes?: Map<string, Promise<ProbeResult>>): Promise<Check>;
27
+ /** What a `--version` probe of the installed CLI came back with. */
28
+ export type ProbeResult = 'ok' | 'failed' | 'timeout';
@@ -6,8 +6,8 @@ import { asRecord } from '../core/object.js';
6
6
  import { findExecutable } from '../core/which.js';
7
7
  import { isAgentWatchHookCommand, tokenizeHookCommand } from '../providers/provider.js';
8
8
  import { readJsonFile } from '../storage/json-file.js';
9
+ import { HOOK_VERSION_TIMEOUT_MS } from './constants/cli.constants.js';
9
10
  const CLI_PATH = fileURLToPath(new URL('../cli.js', import.meta.url));
10
- const VERSION_TIMEOUT_MS = 1500;
11
11
  const VERSION_MANAGER_PATH = /(?:\.nvm|\.fnm|fnm_multishells|\.asdf|\.volta)[/\\]/;
12
12
  const NODE_NAME = /^node(?:[\d.]*|js)?(?:\.exe)?$/;
13
13
  const VERSION_OUTPUT = /^\d+\.\d+\.\d+(?:[-+][\w.-]+)?\s*$/;
@@ -21,14 +21,16 @@ const REMEDY = 'Install Node.js 20+ on the coding agent launch PATH, reinstall @
21
21
  *
22
22
  * @param file - User hook configuration path.
23
23
  * @param env - Launch environment to validate.
24
+ * @param probes - Version probes already run, shared across one doctor run:
25
+ * every agent's hook runs the same CLI, so it is probed once.
24
26
  * @returns A finding for every distinct managed command.
25
27
  */
26
- export async function installedHookChecks(file, env) {
28
+ export async function installedHookChecks(file, env, probes = new Map()) {
27
29
  const read = await readJsonFile(file);
28
30
  if (read.state !== 'ok')
29
31
  return [];
30
32
  const commands = new Set(collectCommands(read.value));
31
- return Promise.all([...commands].map((command) => checkHookCommand(command, env)));
33
+ return Promise.all([...commands].map((command) => checkHookCommand(command, env, CLI_PATH, HOOK_VERSION_TIMEOUT_MS, probes)));
32
34
  }
33
35
  /**
34
36
  * Validate a recognized hook without invoking a shell or an unknown installation.
@@ -36,9 +38,10 @@ export async function installedHookChecks(file, env) {
36
38
  * @param env - Coding agent launch environment.
37
39
  * @param currentCli - Trusted running CLI, injectable for isolated tests.
38
40
  * @param timeoutMs - Maximum version probe duration.
41
+ * @param probes - Version probes already run, by runtime and CLI.
39
42
  * @returns A diagnostic without command output or credential values.
40
43
  */
41
- export async function checkHookCommand(command, env, currentCli = CLI_PATH, timeoutMs = VERSION_TIMEOUT_MS) {
44
+ export async function checkHookCommand(command, env, currentCli = CLI_PATH, timeoutMs = HOOK_VERSION_TIMEOUT_MS, probes = new Map()) {
42
45
  const name = 'installed hook command';
43
46
  const fail = (detail) => ({ name, level: 'fail', detail: `${detail}. ${REMEDY}` });
44
47
  if (!isAgentWatchHookCommand(command))
@@ -67,17 +70,14 @@ export async function checkHookCommand(command, env, currentCli = CLI_PATH, time
67
70
  if (prefix.length === 2 && !NODE_NAME.test(path.basename(runtime)))
68
71
  return fail('Unsupported runtime; version probe skipped');
69
72
  // Only our verified CLI runs; the original shell command is never executed.
70
- const ok = await new Promise((resolve) => {
71
- execFile(runtime, [actual, '--version'], {
72
- timeout: timeoutMs,
73
- killSignal: 'SIGKILL',
74
- maxBuffer: 4096,
75
- cwd: env.home,
76
- env: { PATH: env.vars['PATH'] ?? '', HOME: env.home }
77
- }, (error, stdout) => resolve(!error && VERSION_OUTPUT.test(stdout)));
78
- });
79
- if (!ok)
80
- return fail('Hook --version failed or timed out');
73
+ const key = `${runtime}\0${actual}`;
74
+ const probe = probes.get(key) ?? probeVersion(runtime, actual, env, timeoutMs);
75
+ probes.set(key, probe);
76
+ const result = await probe;
77
+ if (result === 'timeout')
78
+ return fail(`Hook --version did not answer within ${timeoutMs / 1000} s`);
79
+ if (result === 'failed')
80
+ return fail('Hook --version failed');
81
81
  const versionManaged = VERSION_MANAGER_PATH.test(executable);
82
82
  return {
83
83
  name,
@@ -87,6 +87,21 @@ export async function checkHookCommand(command, env, currentCli = CLI_PATH, time
87
87
  : 'CLI and Node.js resolve; bounded --version passed. Repeat doctor with the GUI agent launch PATH if it differs.'
88
88
  };
89
89
  }
90
+ function probeVersion(runtime, cli, env, timeoutMs) {
91
+ return new Promise((resolve) => {
92
+ execFile(runtime, [cli, '--version'], {
93
+ timeout: timeoutMs,
94
+ killSignal: 'SIGKILL',
95
+ maxBuffer: 4096,
96
+ cwd: env.home,
97
+ env: { PATH: env.vars['PATH'] ?? '', HOME: env.home }
98
+ }, (error, stdout) => {
99
+ if (error?.killed)
100
+ return resolve('timeout');
101
+ resolve(!error && VERSION_OUTPUT.test(stdout) ? 'ok' : 'failed');
102
+ });
103
+ });
104
+ }
90
105
  function collectCommands(value) {
91
106
  if (Array.isArray(value))
92
107
  return value.flatMap(collectCommands);
package/dist/cli/hook.js CHANGED
@@ -13,6 +13,7 @@ import { isDisabled } from '../storage/disabled.js';
13
13
  import { loadInstallState, saveInstallState } from '../storage/install-state.js';
14
14
  import { resolvePaths } from '../storage/paths.js';
15
15
  import { claimSweep } from '../storage/sweep-marker.js';
16
+ import { TurnStateStore } from '../turns/turn-state.js';
16
17
  import { EXPORTER_SWEEP_BUDGET_MS, EXPORTER_SWEEP_INTERVAL_MS, EXPORTER_SWEEP_MARKER_FILE, MAX_STDIN_BYTES, STDIN_TIMEOUT_MS } from './constants/cli.constants.js';
17
18
  /**
18
19
  * The `hook` command: read stdin, run the flow, answer the agent.
@@ -37,9 +38,15 @@ export async function runHook(agentId, options) {
37
38
  warnLog(`unknown agent "${agentId}"; passing through`);
38
39
  return 0;
39
40
  }
40
- const disabled = await isDisabled(resolvePaths(options.env));
41
+ const paths = resolvePaths(options.env);
42
+ const disabled = await isDisabled(paths);
41
43
  const payload = await readPayload(options);
44
+ const store = new TurnStateStore(paths.turnsDir);
45
+ // The session whose turn close this payload makes, when a detached process does it.
46
+ let closing;
47
+ let handedOff = false;
42
48
  try {
49
+ closing = payload === undefined ? undefined : provider.detachedSession?.(payload, options.env);
43
50
  // Disabled: answer the agent and do nothing else. The payload is read but
44
51
  // never parsed, enriched, queued or sent — it is read because the answer
45
52
  // depends on which hook fired. Antigravity's Stop wants `stop`, its PreToolUse
@@ -57,9 +64,9 @@ export async function runHook(agentId, options) {
57
64
  }
58
65
  // A turn's close answers nothing, so the agent need not wait for its send:
59
66
  // a detached process does the work and outlives this one.
60
- if (payload !== undefined && options.handOff && provider.runsDetached?.(payload, options.env) && (await options.handOff(agentId, JSON.stringify(payload)))) {
67
+ handedOff = closing !== undefined && options.handOff !== undefined && (await handOffClose(agentId, store, closing, payload, options.handOff));
68
+ if (handedOff)
61
69
  return provider.getHookResponse(payload).exitCode;
62
- }
63
70
  const result = payload === undefined ? undefined : await processPayload(provider, payload, options);
64
71
  const response = respondToDecision(provider, payload, result);
65
72
  if (response.stdout)
@@ -74,6 +81,40 @@ export async function runHook(agentId, options) {
74
81
  debugLog('hook processing failed:', error);
75
82
  return answerSafely(provider, payload, options);
76
83
  }
84
+ finally {
85
+ // Whoever runs a close (the detached child, or this process when the hand-off
86
+ // failed) finishes it on every path, a disabled machine and a failed flow
87
+ // included: takes its marker away, and clears the session when its
88
+ // `SessionEnd` came meanwhile. A dry run touches no state.
89
+ if (closing !== undefined && !handedOff && !options.dryRun)
90
+ await store.finishClosing(closing, JSON.stringify(payload)).catch((error) => debugLog('could not finish the turn close:', error));
91
+ }
92
+ }
93
+ /**
94
+ * Mark a turn close pending, then hand it to a detached process.
95
+ *
96
+ * The mark comes first: a `SessionEnd` right behind the Stop (`/exit`, a
97
+ * scripted run) would otherwise clear the records the close still has to read,
98
+ * and the turn would be lost. Unmarked, nothing is handed off.
99
+ *
100
+ * @param agentId - Value of `--agent`, for the detached child.
101
+ * @param store - Turn state of this machine.
102
+ * @param sessionId - The session whose turn closes.
103
+ * @param payload - Decoded hook payload.
104
+ * @param handOff - Starts the detached child.
105
+ * @returns True when the child took the payload.
106
+ */
107
+ async function handOffClose(agentId, store, sessionId, payload, handOff) {
108
+ const input = JSON.stringify(payload);
109
+ try {
110
+ await store.markClosing(sessionId, input);
111
+ }
112
+ catch (error) {
113
+ debugLog('could not mark the turn close pending; processing in place:', error);
114
+ return false;
115
+ }
116
+ // A hand-off that throws took nothing: the close runs here, and finishes its marker.
117
+ return handOff(agentId, input).catch(() => false);
77
118
  }
78
119
  /**
79
120
  * Start `agentwatch hook --agent <id> --attached` detached, with the payload on
@@ -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
+ }
@@ -1,3 +1,4 @@
1
+ import fs from 'node:fs/promises';
1
2
  import path from 'node:path';
2
3
  import process from 'node:process';
3
4
  import { sleep } from '../core/async.js';
@@ -9,6 +10,7 @@ import { isIgnoredRoot, selectRoot } from '../config/root-config.js';
9
10
  import { loadEffectiveConfig } from '../config/repo-config.js';
10
11
  import { developerDisplayName, developerIdentity } from '../git/git-context.js';
11
12
  import { createCheckoutResolver } from '../replay/checkout-resolver.js';
13
+ import { learnWorktrees } from '../replay/worktree-map.js';
12
14
  import { REPLAY_BATTERY_CHECK_MS, REPLAY_SEND_TIMEOUT_MS } from '../replay/constants/replay.constants.js';
13
15
  import { hookAgeMs, readLoad, readOnBattery } from '../replay/machine.js';
14
16
  import { claimAutomaticReplay, replayStateFile } from '../replay/replay-state.js';
@@ -36,10 +38,16 @@ import { bold, dim, println, symbols } from './ui.js';
36
38
  */
37
39
  export async function runReplayCommand(options) {
38
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);
39
43
  if (days === undefined) {
40
44
  println(`${symbols.fail} invalid --replay-days "${options.days}" (expected a whole number of days, 1 to 366)`);
41
45
  return 1;
42
46
  }
47
+ if (typeof window === 'string') {
48
+ println(`${symbols.fail} ${window}`);
49
+ return 1;
50
+ }
43
51
  if (options.machine === true && options.root !== undefined) {
44
52
  println(`${symbols.fail} choose either --machine or --root, not both`);
45
53
  return 1;
@@ -67,14 +75,15 @@ export async function runReplayCommand(options) {
67
75
  if (options.stop)
68
76
  return report(await stopReplay(ports), replayCommand);
69
77
  if (options.dryRun)
70
- return runDry(ports, days);
78
+ return runDry(ports, days, window);
71
79
  if (options.claimAutomatic === true && !(await claimAutomaticReplay(context.paths.configDir, context.paths.dataDir))) {
72
80
  println(`${symbols.off} automatic historical replay was already attempted on this machine`);
73
81
  return 0;
74
82
  }
83
+ const period = window ? `${window.start.toISOString()} to ${window.end.toISOString()}` : `the last ${days} days`;
75
84
  if (!options.resume)
76
- println(`Replaying the last ${days} days of Claude Code, Codex and Gemini CLI sessions. ${dim(`Ctrl-C stops it; \`${replayCommand} --resume\` carries on.`)}`);
77
- return report(await runReplay(ports, { days, resume: options.resume, dryRun: false, skipIfExisting: options.skipIfExisting }), replayCommand);
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);
78
87
  }
79
88
  /**
80
89
  * Count what a replay would send, and what that cost this machine.
@@ -83,9 +92,9 @@ export async function runReplayCommand(options) {
83
92
  * @param days - The window.
84
93
  * @returns 0.
85
94
  */
86
- async function runDry(ports, days) {
95
+ async function runDry(ports, days, window) {
87
96
  const started = performance.now();
88
- const result = await runReplay(ports, { days, resume: false, dryRun: true, skipIfExisting: false });
97
+ const result = await runReplay(ports, { days, window, resume: false, dryRun: true, skipIfExisting: false });
89
98
  const wallMs = performance.now() - started;
90
99
  const usage = process.resourceUsage();
91
100
  println(bold('Replay dry run — nothing was sent or written'));
@@ -99,6 +108,19 @@ async function runDry(ports, days) {
99
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`);
100
109
  return 0;
101
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
+ }
102
124
  function report(result, replayCommand) {
103
125
  println(`${result.outcome === 'skipped' ? symbols.off : symbols.ok} ${result.message.replace('agentwatch replay', replayCommand)}`);
104
126
  return 0;
@@ -128,6 +150,8 @@ async function buildPorts(context, dryRun) {
128
150
  const paths = identityPaths(context.paths, token);
129
151
  const opened = openIdentityDelivery(context);
130
152
  let battery;
153
+ const worktrees = new Map();
154
+ const checkout = createCheckoutResolver(worktrees);
131
155
  return {
132
156
  env,
133
157
  paths: context.paths,
@@ -144,7 +168,9 @@ async function buildPorts(context, dryRun) {
144
168
  authBlock: opened.authBlock,
145
169
  cooldown: opened.cooldown,
146
170
  inScope: (cwd) => !isIgnoredRoot(context.config.ignoredRoots, cwd) && selectRoot(context.config.roots, cwd)?.path === context.identityRoot,
147
- checkout: createCheckoutResolver(),
171
+ checkout,
172
+ learnWorktrees: (learned) => learnWorktrees(worktrees, learned),
173
+ localCheckouts: async () => childCheckouts(context.identityRoot, checkout),
148
174
  captureFor: cachedCaptureFor(async (cwd) => (await loadEffectiveConfig(context.paths, cwd)).config.capture),
149
175
  machine: async () => {
150
176
  const nowMs = env.now().getTime();
@@ -157,6 +183,15 @@ async function buildPorts(context, dryRun) {
157
183
  log: (line) => println(dim(line))
158
184
  };
159
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
+ }
160
195
  /**
161
196
  * The agents whose transcripts a replay reads, each where its provider looks for them, with its billing mode.
162
197
  *
@@ -168,7 +203,7 @@ async function replaySources(context) {
168
203
  const firstInstalledAt = context.installState.agents[GEMINI_PROVIDER_ID]?.hooksFirstInstalledAt;
169
204
  const firstInstalledMs = firstInstalledAt === undefined ? undefined : Date.parse(firstInstalledAt);
170
205
  const sources = [
171
- claudeSource(claudeProjectsDir(env.home)),
206
+ claudeSource(claudeProjectsDir(env.home), env.home),
172
207
  codexSource(codexHome(env)),
173
208
  geminiSource(path.dirname(geminiSettingsPath(env)), Number.isNaN(firstInstalledMs) ? undefined : firstInstalledMs)
174
209
  ];