@agent-watch-ai/edge 0.7.0 → 0.7.2

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 (118) hide show
  1. package/CHANGELOG.md +92 -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/capture-env.d.ts +3 -3
  6. package/dist/capture/capture-env.js +5 -5
  7. package/dist/capture/captured-step.js +24 -0
  8. package/dist/capture/constants/capture.constants.d.ts +15 -0
  9. package/dist/capture/constants/capture.constants.js +15 -0
  10. package/dist/capture/launched-runs.d.ts +27 -0
  11. package/dist/capture/launched-runs.js +15 -9
  12. package/dist/capture/python/sitecustomize.py +11 -2
  13. package/dist/capture/venv-loader.d.ts +68 -0
  14. package/dist/capture/venv-loader.js +189 -0
  15. package/dist/cli/constants/cli.constants.d.ts +21 -0
  16. package/dist/cli/constants/cli.constants.js +22 -1
  17. package/dist/cli/doctor-run-capture.d.ts +8 -0
  18. package/dist/cli/doctor-run-capture.js +14 -0
  19. package/dist/cli/doctor.js +6 -2
  20. package/dist/cli/hook-check.d.ts +7 -2
  21. package/dist/cli/hook-check.js +30 -15
  22. package/dist/cli/hook.js +44 -3
  23. package/dist/cli/npm-global.d.ts +24 -0
  24. package/dist/cli/npm-global.js +77 -0
  25. package/dist/cli/npx-install.js +22 -6
  26. package/dist/cli/replay.js +42 -7
  27. package/dist/cli/setup.js +71 -7
  28. package/dist/cli/types/cli.types.d.ts +2 -0
  29. package/dist/cli/uninstall.js +34 -1
  30. package/dist/cli/update.js +3 -2
  31. package/dist/cli.js +4 -1
  32. package/dist/config/config-store.d.ts +15 -4
  33. package/dist/config/config-store.js +31 -7
  34. package/dist/config/config.d.ts +8 -0
  35. package/dist/config/config.js +10 -0
  36. package/dist/config/constants/config.constants.d.ts +13 -1
  37. package/dist/config/constants/config.constants.js +13 -1
  38. package/dist/config/repo-config.js +7 -2
  39. package/dist/config/schemas/config.schema.d.ts +6 -2
  40. package/dist/config/schemas/config.schema.js +17 -3
  41. package/dist/credentials/cloud-claim.d.ts +2 -0
  42. package/dist/credentials/cloud-claim.js +21 -2
  43. package/dist/credentials/constants/credentials.constants.d.ts +8 -0
  44. package/dist/credentials/constants/credentials.constants.js +8 -0
  45. package/dist/credentials/credential-status.js +1 -1
  46. package/dist/credentials/credentials.d.ts +3 -3
  47. package/dist/credentials/credentials.js +26 -12
  48. package/dist/credentials/identity.d.ts +2 -2
  49. package/dist/credentials/identity.js +2 -2
  50. package/dist/credentials/install-key.d.ts +31 -0
  51. package/dist/credentials/install-key.js +58 -0
  52. package/dist/credentials/migration.d.ts +9 -7
  53. package/dist/credentials/migration.js +58 -18
  54. package/dist/credentials/secret-store.d.ts +12 -0
  55. package/dist/credentials/secret-store.js +18 -1
  56. package/dist/enforcement/enforcement.js +1 -1
  57. package/dist/events/enrich.d.ts +14 -0
  58. package/dist/events/enrich.js +1 -1
  59. package/dist/git/constants/git.constants.d.ts +2 -0
  60. package/dist/git/constants/git.constants.js +9 -0
  61. package/dist/git/repo-snapshot.js +8 -2
  62. package/dist/git/types/snapshot.types.d.ts +4 -0
  63. package/dist/pipeline/hook-pipeline.js +5 -2
  64. package/dist/providers/antigravity/antigravity.adapter.d.ts +14 -0
  65. package/dist/providers/antigravity/antigravity.adapter.js +86 -18
  66. package/dist/providers/antigravity/antigravity.provider.js +7 -4
  67. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +10 -0
  68. package/dist/providers/antigravity/constants/antigravity.constants.js +10 -0
  69. package/dist/providers/antigravity/schemas/antigravity.schema.js +7 -13
  70. package/dist/providers/claude/claude.otel.d.ts +33 -1
  71. package/dist/providers/claude/claude.otel.js +81 -12
  72. package/dist/providers/claude/claude.provider.js +12 -6
  73. package/dist/providers/codex/codex.capture.d.ts +1 -1
  74. package/dist/providers/codex/codex.capture.js +3 -3
  75. package/dist/providers/codex/codex.otel.js +2 -2
  76. package/dist/providers/codex/codex.provider.js +2 -1
  77. package/dist/providers/gemini/gemini.capture.js +2 -2
  78. package/dist/providers/gemini/gemini.otel.js +2 -2
  79. package/dist/providers/gemini/gemini.provider.js +2 -1
  80. package/dist/providers/shared/terminal-capture.js +3 -3
  81. package/dist/providers/types/provider.types.d.ts +5 -5
  82. package/dist/replay/checkout-resolver.d.ts +41 -14
  83. package/dist/replay/checkout-resolver.js +134 -30
  84. package/dist/replay/replay-runner.d.ts +3 -1
  85. package/dist/replay/replay-runner.js +74 -22
  86. package/dist/replay/replay-scan.d.ts +2 -1
  87. package/dist/replay/replay-scan.js +14 -2
  88. package/dist/replay/throttle.d.ts +2 -1
  89. package/dist/replay/throttle.js +4 -1
  90. package/dist/replay/transcript-turns.js +29 -3
  91. package/dist/replay/turn-event.d.ts +4 -2
  92. package/dist/replay/turn-event.js +22 -11
  93. package/dist/replay/types/replay.types.d.ts +39 -3
  94. package/dist/replay/worktree-map.d.ts +42 -0
  95. package/dist/replay/worktree-map.js +134 -0
  96. package/dist/snapshot/snapshot-pipeline.js +15 -4
  97. package/dist/snapshot/types/snapshot.types.d.ts +2 -0
  98. package/dist/turns/antigravity-transcript.d.ts +40 -0
  99. package/dist/turns/antigravity-transcript.js +102 -0
  100. package/dist/turns/claude-transcript.d.ts +35 -1
  101. package/dist/turns/claude-transcript.js +185 -2
  102. package/dist/turns/codex-transcript.d.ts +22 -1
  103. package/dist/turns/codex-transcript.js +161 -2
  104. package/dist/turns/constants/turns.constants.d.ts +67 -0
  105. package/dist/turns/constants/turns.constants.js +67 -0
  106. package/dist/turns/gemini-transcript.d.ts +17 -1
  107. package/dist/turns/gemini-transcript.js +36 -2
  108. package/dist/turns/transcript.d.ts +31 -1
  109. package/dist/turns/transcript.js +74 -0
  110. package/dist/turns/turn-state.d.ts +51 -1
  111. package/dist/turns/turn-state.js +124 -10
  112. package/dist/turns/turn-tracker.js +156 -18
  113. package/dist/turns/types/transcript.types.d.ts +25 -0
  114. package/dist/turns/types/turn-provider.types.d.ts +18 -1
  115. package/dist/turns/types/turn-state.types.d.ts +10 -0
  116. package/docs/DATA_HANDLING.md +11 -6
  117. package/docs/ENTERPRISE_DEPLOYMENT.md +2 -2
  118. package/package.json +1 -1
@@ -0,0 +1,189 @@
1
+ import { createHash } from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { debugLog } from '../core/logger.js';
5
+ import { writeFileAtomic } from '../storage/atomic-file.js';
6
+ import { PYTHON_SHIM_FILE, RE_ASCII_PATH, RE_PYTHON, RE_SITE_PACKAGES_PARENT, VENV_CONFIG_FILE, VENV_LOADER_FILE, VENV_LOADER_MARK, VENV_LOADER_MODE, VENV_RECORDS_DIR } from './constants/capture.constants.js';
7
+ import { afterCds, segmentsOf, wordsOf } from './launched-runs.js';
8
+ /**
9
+ * The interpreters a shell command runs by path (`venv/bin/python -I x.py`, `cd app && .venv/bin/python3 x.py`),
10
+ * resolved against where each runs. A bare `python` is looked up on a PATH this hook cannot see, so it is left out.
11
+ *
12
+ * @param command - The shell command, read in memory only.
13
+ * @param directory - Where it runs.
14
+ * @returns Absolute interpreter paths, possibly none.
15
+ */
16
+ export function pythonInterpreters(command, directory) {
17
+ const segments = segmentsOf(command);
18
+ const found = new Set();
19
+ for (const [index, segment] of segments.entries()) {
20
+ const program = wordsOf(segment)[0];
21
+ if (program === undefined || !program.includes('/') || !RE_PYTHON.test(path.basename(program)))
22
+ continue;
23
+ found.add(path.resolve(afterCds(segments, index, directory), program));
24
+ }
25
+ return [...found];
26
+ }
27
+ async function isFile(file) {
28
+ return (await fs.stat(file).catch(() => undefined))?.isFile() ?? false;
29
+ }
30
+ /**
31
+ * The site-packages folders of the venv an interpreter belongs to, by its `pyvenv.cfg`
32
+ * beside it or one level up. Not resolved through links: a venv's `python` links to the
33
+ * system one, whose site-packages is never ours to write.
34
+ *
35
+ * @param interpreter - The interpreter's absolute path, as the command named it.
36
+ * @returns The folders, real and inside the venv; none for an interpreter outside one.
37
+ */
38
+ export async function venvSitePackages(interpreter) {
39
+ const bin = path.dirname(interpreter);
40
+ const candidates = [bin, path.dirname(bin)];
41
+ let root;
42
+ for (const candidate of candidates) {
43
+ if (await isFile(path.join(candidate, VENV_CONFIG_FILE))) {
44
+ root = candidate;
45
+ break;
46
+ }
47
+ }
48
+ if (root === undefined)
49
+ return [];
50
+ const realRoot = await fs.realpath(root);
51
+ const versions = await fs.readdir(path.join(root, 'lib')).catch(() => []);
52
+ const folders = [];
53
+ for (const version of versions) {
54
+ if (!RE_SITE_PACKAGES_PARENT.test(version))
55
+ continue;
56
+ const folder = path.join(root, 'lib', version, 'site-packages');
57
+ const real = await fs.realpath(folder).catch(() => undefined);
58
+ // Never outside the venv: a site-packages linked elsewhere is someone else's.
59
+ if (real !== undefined && real.startsWith(realRoot + path.sep) && (await fs.stat(real)).isDirectory())
60
+ folders.push(real);
61
+ }
62
+ return folders;
63
+ }
64
+ /**
65
+ * The one line Python runs from the `.pth` at startup.
66
+ *
67
+ * It acts only when Python ignored the environment (`-I`, `-E`): otherwise PYTHONPATH loads
68
+ * the shim the usual way. And only when the process's environment names the capture folder
69
+ * in PYTHONPATH, which only an agent's environment does: `-I` stops Python from reading the
70
+ * variable, not the process from holding it. The developer running the same venv from their
71
+ * own terminal gets nothing. It loads nothing itself: a one-shot finder answers site's own
72
+ * `import sitecustomize`, which comes after every `.pth`, so the shim runs the developer's
73
+ * `sitecustomize` next on the full `sys.path`. Any fault is swallowed, since site prints a
74
+ * failing `.pth` line, or a failing `sitecustomize`, into the customer's stderr.
75
+ *
76
+ * ponytail: rides on `.pth` import lines. CPython's docs for 3.15 reportedly deprecate them
77
+ * (ignored from 3.18); 3.14 still runs them silently. When they go, a `-I` run on that
78
+ * Python is uncaptured again, and the upgrade is whatever startup hook replaces them.
79
+ *
80
+ * @param shimDir - The capture copy's python folder.
81
+ * @returns The file's contents, or undefined for a path that is not plain ASCII.
82
+ */
83
+ export function venvLoader(shimDir) {
84
+ // ponytail: a non-ASCII data dir gets no loader; JSON's \u escapes split astral characters in Python.
85
+ if (!RE_ASCII_PATH.test(shimDir))
86
+ return undefined;
87
+ const code = [
88
+ 'try:',
89
+ ` d = ${JSON.stringify(shimDir)}`,
90
+ ` f = os.path.join(d, ${JSON.stringify(PYTHON_SHIM_FILE)})`,
91
+ " if sys.flags.ignore_environment and d in os.environ.get('PYTHONPATH', '').split(os.pathsep) and os.path.isfile(f):",
92
+ ' import importlib.util',
93
+ ' class AgentWatchCapture:',
94
+ ' def find_spec(self, name, path=None, target=None):',
95
+ " if name != 'sitecustomize':",
96
+ ' return None',
97
+ ' try:',
98
+ ' sys.meta_path.remove(self)',
99
+ " return importlib.util.spec_from_file_location('sitecustomize', f)",
100
+ ' except Exception:',
101
+ ' return None',
102
+ ' sys.meta_path.insert(0, AgentWatchCapture())',
103
+ 'except Exception:',
104
+ ' pass',
105
+ ''
106
+ ].join('\n');
107
+ // Its own globals: site runs the line inside a function, whose locals a class's methods cannot see.
108
+ return `${VENV_LOADER_MARK}\nimport os, sys; exec(${JSON.stringify(code)}, {'os': os, 'sys': sys})\n`;
109
+ }
110
+ function recordFile(dataDir, folder) {
111
+ return path.join(dataDir, VENV_RECORDS_DIR, `${createHash('sha256').update(folder).digest('hex').slice(0, 16)}.txt`);
112
+ }
113
+ /**
114
+ * Leave the loader in the venv of every interpreter a shell command runs by path, so a
115
+ * `python -I` run is captured too. Recorded first, so a file written is always one
116
+ * uninstall can find. Never throws: a venv it cannot write is skipped.
117
+ *
118
+ * @param command - The shell command, read in memory only.
119
+ * @param directory - Where it runs.
120
+ * @param dataDir - The data dir.
121
+ * @param shimDir - The capture copy's python folder.
122
+ * @returns The site-packages folders that now hold the loader.
123
+ */
124
+ export async function armVenvLoaders(command, directory, dataDir, shimDir) {
125
+ const contents = venvLoader(shimDir);
126
+ if (contents === undefined || !(await isFile(path.join(shimDir, PYTHON_SHIM_FILE))))
127
+ return [];
128
+ const armed = [];
129
+ for (const interpreter of pythonInterpreters(command, directory)) {
130
+ for (const folder of await venvSitePackages(interpreter).catch(() => [])) {
131
+ const file = path.join(folder, VENV_LOADER_FILE);
132
+ try {
133
+ const current = await fs.readFile(file, 'utf8').catch(() => undefined);
134
+ // A file of that name Edge did not write is the developer's: left, and not armed.
135
+ if (current !== undefined && !current.startsWith(VENV_LOADER_MARK))
136
+ continue;
137
+ const record = recordFile(dataDir, folder);
138
+ // Recorded even when the loader is already there: a purge can take the record and leave the file.
139
+ if (current !== contents || !(await isFile(record)))
140
+ await writeFileAtomic(record, folder, 0o600);
141
+ if (current !== contents)
142
+ await writeFileAtomic(file, contents, VENV_LOADER_MODE);
143
+ armed.push(folder);
144
+ }
145
+ catch {
146
+ // A fixed sentence: the error could quote a path.
147
+ debugLog('capture: could not write a venv loader; that venv is skipped');
148
+ }
149
+ }
150
+ }
151
+ return armed;
152
+ }
153
+ /**
154
+ * The site-packages folders Edge has left a loader in, as recorded.
155
+ *
156
+ * @param dataDir - The data dir.
157
+ * @returns The folders, whether or not the loader is still there.
158
+ */
159
+ export async function recordedVenvs(dataDir) {
160
+ const dir = path.join(dataDir, VENV_RECORDS_DIR);
161
+ const names = await fs.readdir(dir).catch(() => []);
162
+ const folders = await Promise.all(names.map((name) => fs.readFile(path.join(dir, name), 'utf8').catch(() => '')));
163
+ return folders.filter((folder) => path.isAbsolute(folder));
164
+ }
165
+ /**
166
+ * Remove every loader Edge recorded, and its record. A file that no longer carries our
167
+ * mark is the developer's now and stays.
168
+ *
169
+ * @param dataDir - The data dir.
170
+ * @returns The folders a loader was removed from, and those whose loader could not be.
171
+ */
172
+ export async function removeVenvLoaders(dataDir) {
173
+ const removed = [];
174
+ const left = [];
175
+ for (const folder of await recordedVenvs(dataDir)) {
176
+ const file = path.join(folder, VENV_LOADER_FILE);
177
+ const contents = await fs.readFile(file, 'utf8').catch(() => undefined);
178
+ const ours = contents?.startsWith(VENV_LOADER_MARK) === true;
179
+ // A loader it could not remove keeps its record, for the next uninstall.
180
+ if (ours && !(await fs.rm(file).then(() => true, () => false))) {
181
+ left.push(folder);
182
+ continue;
183
+ }
184
+ if (ours)
185
+ removed.push(folder);
186
+ await fs.rm(recordFile(dataDir, folder), { force: true }).catch(() => undefined);
187
+ }
188
+ return { removed, left };
189
+ }
@@ -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";
@@ -5,7 +5,7 @@
5
5
  * itself into a boolean — which is how `--otel none` once ignored the selection
6
6
  * entirely.
7
7
  */
8
- export const VALUE_FLAGS = new Set(['agent', 'endpoint', 'token', 'enrollment-code', 'developer-email', 'developer-name', 'otel', 'root', 'replay-days']);
8
+ export const VALUE_FLAGS = new Set(['agent', 'endpoint', 'token', 'enrollment-code', 'developer-email', 'developer-name', 'otel', 'capture-runs', 'root', 'replay-days']);
9
9
  /** The commands that take `--agent`; the help names the same three. Any other command refuses it. */
10
10
  export const AGENT_COMMANDS = new Set(['setup', 'uninstall', 'hook']);
11
11
  export const FLAG_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
+ }