@raytrace-cli/cli 0.21.0 → 0.22.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.
@@ -6,8 +6,8 @@
6
6
  <title>RayTrace — Agent trace forensics</title>
7
7
  <meta name="description" content="Evidence-backed traces and live counterfactual forks for coding agents." />
8
8
  <link rel="icon" href="/favicon.svg?v=raytrace-cube" type="image/svg+xml" />
9
- <script type="module" crossorigin src="/assets/index-BUzKpPr2.js"></script>
10
- <link rel="stylesheet" crossorigin href="/assets/index-CKf_5Rwt.css">
9
+ <script type="module" crossorigin src="/assets/index-Cfg6OwVA.js"></script>
10
+ <link rel="stylesheet" crossorigin href="/assets/index-Ci_pHYqV.css">
11
11
  </head>
12
12
  <body class="antialiased">
13
13
  <div id="root"></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raytrace-cli/cli",
3
- "version": "0.21.0",
3
+ "version": "0.22.1",
4
4
  "mcpName": "io.github.Godcreatebugs/raytrace",
5
5
  "description": "See what your coding agent did: traces, tool calls, cost and step-by-step evidence for Claude Code and Codex.",
6
6
  "license": "MIT",
@@ -34,6 +34,7 @@ import { recapOutline, recapRequest, recapText, parseRecap, DEFAULT_OBSERVER } f
34
34
  import { groupByCall, assessmentRequests, combineGroup, rulesOnly, withProbabilities } from './call-assessment.mjs';
35
35
  import { prepareStep, attributionKey, proposerRequest, parseProposals, candidates, jevRequests, combine, withoutJev } from './step-attribution.mjs';
36
36
  import { STAR_ACTIONS, recordStarPromptState, starPromptStatus } from './star-prompt.mjs';
37
+ import { recordSignupPromptState, signupPromptStatus, validEmail } from './signup-prompt.mjs';
37
38
 
38
39
  try { loadEnvFile(); } catch (error) { if (error.code !== 'ENOENT') throw error; }
39
40
  const routing = providerConfig();
@@ -44,7 +45,7 @@ const summaryModel = process.env.RAYTACE_SUMMARY_MODEL
44
45
  : (routing.models.oss || routing.defaultModel);
45
46
  // Bumped whenever the dashboard needs endpoints an older proxy lacks; the
46
47
  // CLI restarts a proxy it started that reports less (src/proxy-process.mjs).
47
- const PROXY_API = 6;
48
+ const PROXY_API = 7;
48
49
  const fallbackSession = { session_id: randomUUID(), session_started_at: new Date().toISOString() };
49
50
 
50
51
  const port = Number(process.env.RAYTACE_PORT || 8797);
@@ -583,6 +584,7 @@ const server = createServer(async (req, res) => {
583
584
  // after an upgrade (src/proxy-process.mjs PROXY_API) and replace it.
584
585
  if (req.method === 'GET' && req.url === '/raytace/version') return json(200, { api: PROXY_API });
585
586
  if (req.method === 'GET' && req.url === '/raytace/star-prompt') return json(200, starPromptStatus({ dataDir, prompts: db.turnCount() }));
587
+ if (req.method === 'GET' && req.url === '/raytace/signup-prompt') return json(200, signupPromptStatus({ dataDir, prompts: db.turnCount() }));
586
588
  if (req.method === 'GET' && req.url === '/raytace/account') return json(200, { signed_in: false, plan: 'free', features: [] });
587
589
  if (req.method === 'GET' && req.url === '/raytace/models') return json(200, { models: routing.mode === 'openrouter' ? Object.entries(routing.models).map(([alias, id]) => ({ alias, id })) : [], execution_available: routing.mode === 'openrouter' });
588
590
  const stepRoute = req.url?.match(/^\/raytace\/steps\/([a-f0-9-]+)\/(\d+)$/);
@@ -692,7 +694,7 @@ const server = createServer(async (req, res) => {
692
694
  ingestClaudeCode(path, { final: CLAUDE_CODE_FINAL_EVENTS.has(note.hook_event_name) && note.more !== true });
693
695
  return;
694
696
  }
695
- if (localApi && (req.method !== 'POST' || !['/raytace/experiments', '/raytace/step-runs','/raytace/explanations', '/raytace/attribution', '/raytace/summaries', '/raytace/prompt-context/summary', '/raytace/forks', '/raytace/recap', '/raytace/star-prompt'].includes(req.url))) return json(404, { error: 'Unknown local endpoint.' });
697
+ if (localApi && (req.method !== 'POST' || !['/raytace/experiments', '/raytace/step-runs','/raytace/explanations', '/raytace/attribution', '/raytace/summaries', '/raytace/prompt-context/summary', '/raytace/forks', '/raytace/recap', '/raytace/star-prompt', '/raytace/signup-prompt'].includes(req.url))) return json(404, { error: 'Unknown local endpoint.' });
696
698
  if (localApi && (req.headers['x-raytace-experiment'] !== '1' || !req.headers['content-type']?.includes('application/json'))) return json(403, { error: 'Use the experiment control in the dashboard.' });
697
699
  const parts = []; let bytes = 0;
698
700
  for await (const part of req) { bytes += part.length; if (bytes > (localApi ? 600_000 : 20_000_000)) return json(413, { error: 'Request too large.' }); parts.push(part); }
@@ -706,6 +708,39 @@ const server = createServer(async (req, res) => {
706
708
  return json(200, { ok: true, state: recordStarPromptState(dataDir, action, source) });
707
709
  } catch (error) { return json(400, { error: error.message }); }
708
710
  }
711
+ if (req.method === 'POST' && req.url === '/raytace/signup-prompt') {
712
+ try {
713
+ const body = JSON.parse(requestBody);
714
+ const action = String(body?.action ?? '');
715
+ if (action === 'clicked_signup' || action === 'dismissed') {
716
+ return json(200, { ok: true, state: recordSignupPromptState(dataDir, action, 'local-dashboard') });
717
+ }
718
+ if (action === 'subscribe') {
719
+ const email = validEmail(body?.email);
720
+ if (!email) return json(400, { error: 'Please enter a valid email address.' });
721
+ const apiBase = (process.env.RAYTRACE_API_URL || 'https://api.raytracer.si').replace(/\/$/, '');
722
+ let upstream;
723
+ try {
724
+ // Forward ONLY email and source — never any local trace, path, or machine metadata.
725
+ upstream = await fetch(`${apiBase}/v1/newsletter/subscribe`, {
726
+ method: 'POST',
727
+ headers: { 'content-type': 'application/json', accept: 'application/json', 'user-agent': 'raytrace-cli' },
728
+ body: JSON.stringify({ email, source: 'local-dashboard' }),
729
+ signal: AbortSignal.timeout(10_000),
730
+ });
731
+ } catch {
732
+ return json(502, { error: 'Could not reach RayTrace right now. Please try again later.' });
733
+ }
734
+ const data = await upstream.json().catch(() => ({}));
735
+ if (!upstream.ok) {
736
+ const status = upstream.status >= 400 && upstream.status < 500 ? upstream.status : 502;
737
+ return json(status, { error: data.error || 'Could not subscribe right now. Please try again later.' });
738
+ }
739
+ return json(200, { ok: true, state: recordSignupPromptState(dataDir, 'subscribed', 'local-dashboard') });
740
+ }
741
+ return json(400, { error: 'Unknown signup prompt action.' });
742
+ } catch (error) { return json(400, { error: error.message }); }
743
+ }
709
744
  if (req.method === 'POST' && req.url === '/raytace/forks') {
710
745
  try { return json(202, await playground.create(JSON.parse(requestBody))); }
711
746
  catch (error) { return json(400, { error: error.message }); }
@@ -0,0 +1,86 @@
1
+ // Shared state and eligibility for the Phase 2 local dashboard card:
2
+ // primary CTA to create a free RayTrace account, with a lightweight weekly
3
+ // newsletter email fallback. Shown at most once per machine, only after >= 10
4
+ // prompts AND >= 24 hours after the Phase 1 star prompt was resolved, and
5
+ // never if this machine has already signed into RayTrace Cloud.
6
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { readStarPromptState, starPromptOptedOut } from './star-prompt.mjs';
9
+
10
+ export const SIGNUP_URL = 'https://raytracer.si/sign-in.html?src=local-dashboard';
11
+ export const SIGNUP_PROMPT_THRESHOLD = 10;
12
+ export const STAR_COOLDOWN_MS = 24 * 60 * 60 * 1000;
13
+ export const SIGNUP_PROMPT_FILE = 'signup-prompt.json';
14
+ export const ACCOUNT_LINKED_FILE = 'account-linked';
15
+ export const CREDENTIALS_FILE = 'credentials.json';
16
+ export const SIGNUP_ACTIONS = new Set(['clicked_signup', 'subscribed', 'dismissed']);
17
+
18
+ const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
19
+
20
+ export function validEmail(value) {
21
+ const clean = String(value ?? '').trim().toLowerCase();
22
+ return clean.length <= 254 && EMAIL_RE.test(clean) ? clean : null;
23
+ }
24
+
25
+ /** True when this machine has ever signed into RayTrace Cloud via the CLI. */
26
+ export function hasLinkedAccount(dataDir) {
27
+ if (!dataDir) return false;
28
+ return existsSync(join(dataDir, ACCOUNT_LINKED_FILE)) || existsSync(join(dataDir, CREDENTIALS_FILE));
29
+ }
30
+
31
+ /** Read saved signup-prompt state from `dataDir`, or null when pending/missing. */
32
+ export function readSignupPromptState(dataDir) {
33
+ if (!dataDir) return null;
34
+ const file = join(dataDir, SIGNUP_PROMPT_FILE);
35
+ if (!existsSync(file)) return null;
36
+ try {
37
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
38
+ if (!parsed || typeof parsed !== 'object' || !SIGNUP_ACTIONS.has(parsed.status)) return null;
39
+ return {
40
+ status: parsed.status,
41
+ source: typeof parsed.source === 'string' ? parsed.source : 'local-dashboard',
42
+ at: typeof parsed.at === 'string' ? parsed.at : null,
43
+ };
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ /** Persist the user's signup/newsletter card choice in `dataDir` with 0600 permissions. */
50
+ export function recordSignupPromptState(dataDir, action, source = 'local-dashboard', now = Date.now()) {
51
+ if (!SIGNUP_ACTIONS.has(action)) throw new Error(`Invalid signup prompt action: ${action}`);
52
+ const state = { status: action, source, at: new Date(now).toISOString() };
53
+ mkdirSync(dataDir, { recursive: true });
54
+ const file = join(dataDir, SIGNUP_PROMPT_FILE);
55
+ writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
56
+ try { chmodSync(file, 0o600); } catch { /* filesystem without POSIX modes */ }
57
+ return state;
58
+ }
59
+
60
+ /** Eligibility and metadata for the Phase 2 local dashboard card. */
61
+ export function signupPromptStatus({
62
+ dataDir,
63
+ prompts = 0,
64
+ threshold = SIGNUP_PROMPT_THRESHOLD,
65
+ cooldownMs = STAR_COOLDOWN_MS,
66
+ env = process.env,
67
+ now = Date.now(),
68
+ } = {}) {
69
+ const count = Math.max(0, Math.floor(Number(prompts) || 0));
70
+ const state = readSignupPromptState(dataDir);
71
+ const starState = readStarPromptState(dataDir);
72
+ const starAt = starState?.at ? Date.parse(starState.at) : NaN;
73
+ const starCooledDown = Number.isFinite(starAt) && (now - starAt) >= cooldownMs;
74
+ const eligible = !starPromptOptedOut(env)
75
+ && !state
76
+ && !hasLinkedAccount(dataDir)
77
+ && count >= threshold
78
+ && starCooledDown;
79
+ return {
80
+ eligible,
81
+ prompts: count,
82
+ threshold,
83
+ status: state?.status ?? 'pending',
84
+ signup_url: SIGNUP_URL,
85
+ };
86
+ }
@@ -5,15 +5,15 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'n
5
5
  import { join } from 'node:path';
6
6
 
7
7
  export const STAR_URL = 'https://github.com/Godcreatebugs/raytrace-cli';
8
- export const WEBSITE_URL = 'https://raytracer.si';
8
+ export const WEBSITE_URL = 'https://raytracer.si/sign-in.html?src=star-thanks';
9
9
  export const STAR_PROMPT_THRESHOLD = 3;
10
10
  export const STAR_PROMPT_FILE = 'star-prompt.json';
11
11
  export const STAR_ACTIONS = new Set(['opened', 'already_starred', 'dismissed']);
12
12
  const STAR_SOURCES = new Set(['cli', 'dashboard', 'sidebar']);
13
13
 
14
14
  export function starPromptOptedOut(env = process.env) {
15
- const value = env?.RAYTRACE_NO_STAR_PROMPT;
16
- return value === '1' || value === 'true';
15
+ const off = (v) => v === '1' || v === 'true';
16
+ return off(env?.RAYTRACE_NO_STAR_PROMPT) || off(env?.RAYTRACE_NO_PROMPTS);
17
17
  }
18
18
 
19
19
  /** Read the saved star-prompt state from `dataDir`, or null when pending/missing. */
package/src/api.mjs CHANGED
@@ -47,7 +47,7 @@ export async function call(method, path, { body, headers = {}, autoLogin = true
47
47
  const { url, key } = await api({ autoLogin });
48
48
  let response;
49
49
  try {
50
- response = await fetch(new URL(path, url), { method, body, headers: { authorization: `Bearer ${key}`, ...headers } });
50
+ response = await fetch(new URL(path, url), { method, body, headers: { 'user-agent': 'raytrace-cli', authorization: `Bearer ${key}`, ...headers } });
51
51
  } catch {
52
52
  throw unreachable(url);
53
53
  }
package/src/auth.mjs CHANGED
@@ -17,10 +17,22 @@ export const CLIENT_ID = process.env.RAYTRACE_WORKOS_CLIENT_ID || 'client_01M4BC
17
17
  const SERVICE = 'raytrace-cli';
18
18
  const ACCOUNT = 'raytrace';
19
19
  const FILE = join(paths.home, 'credentials.json');
20
+ const ACCOUNT_LINKED = () => join(paths.home, 'account-linked');
21
+
22
+ function markAccountLinked() {
23
+ const file = ACCOUNT_LINKED();
24
+ if (existsSync(file)) return;
25
+ try {
26
+ mkdirSync(paths.home, { recursive: true });
27
+ writeFileSync(file, `${JSON.stringify({ linked: true, at: new Date().toISOString() }, null, 2)}\n`, { mode: 0o600 });
28
+ chmodSync(file, 0o600);
29
+ } catch { /* non-fatal: local proxy only reads this as a hint */ }
30
+ }
20
31
 
21
32
  // ------------------------------------------------------------- storage
22
33
 
23
34
  function save(session) {
35
+ markAccountLinked();
24
36
  const value = Buffer.from(JSON.stringify(session)).toString('base64');
25
37
  if (process.platform === 'darwin') {
26
38
  // `security -i` reads its command from stdin, so the token never shows in a process list.
@@ -47,7 +59,11 @@ function load() {
47
59
  }
48
60
  if (!value && existsSync(FILE)) value = readFileSync(FILE, 'utf8').trim();
49
61
  if (!value) return null;
50
- try { return JSON.parse(Buffer.from(value, 'base64').toString('utf8')); } catch { return null; }
62
+ try {
63
+ const parsed = JSON.parse(Buffer.from(value, 'base64').toString('utf8'));
64
+ if (parsed?.access_token) markAccountLinked();
65
+ return parsed;
66
+ } catch { return null; }
51
67
  }
52
68
 
53
69
  function forget() {
@@ -13,7 +13,7 @@ import { readToken } from '../proxy/local-token.mjs';
13
13
 
14
14
  // The proxy API this CLI's dashboard needs (proxy/raytace-proxy.mjs PROXY_API).
15
15
  // A proxy from an older install answers without it, or with less.
16
- export const PROXY_API = 6;
16
+ export const PROXY_API = 7;
17
17
 
18
18
  /** The running proxy's API version: 0 for one from before it said. */
19
19
  export async function proxyApi(port) {
@@ -117,6 +117,11 @@ ALIAS_WINDOW = 5_000_000_000 # ns before a change within which an open of ano
117
117
  # naming a folder (a script given its working folder) says nothing of them.
118
118
  FOLDER_TOOLS = frozenset(['rm', 'rmdir', 'mv', 'cp', 'chmod', 'chown', 'chgrp', 'find', 'rsync', 'shred', 'unlink', 'truncate'])
119
119
  PACKAGE_TOOLS = frozenset(['npm', 'npx', 'pnpm', 'yarn', 'bun', 'pip', 'pip3', 'uv', 'poetry'])
120
+ PIP_BIN = re.compile(r'^pip(?:\d+(?:\.\d+)*)?$')
121
+ PYTHON_BIN = re.compile(r'^python(?:\d+(?:\.\d+)*)?$')
122
+ VENV_BIN_PREFIX = re.compile(r'^(.+)/bin/(?:python(?:\d+(?:\.\d+)*)?|pip(?:\d+(?:\.\d+)*)?)$')
123
+ SYSTEM_PREFIXES = frozenset(['', '/', '/usr', '/usr/local'])
124
+ DIST_INFO_FILES = frozenset(['METADATA', 'RECORD', 'WHEEL', 'INSTALLER'])
120
125
  REGISTRIES = frozenset(['registry.npmjs.org', 'registry.yarnpkg.com', 'pypi.org', 'files.pythonhosted.org'])
121
126
  MAX_PACKAGES = 400
122
127
  REJECTED = [ipaddress.ip_network(block) for block in network.REJECTED]
@@ -239,10 +244,8 @@ def change(before, after, events, flags):
239
244
  return 'changed'
240
245
 
241
246
 
242
- def project_path(event):
243
- """The project file an open names, relative to the project, or None when
244
- it is outside it. Worked out from the text of the path: links inside the
245
- project are not followed, which a fact says as `resolution: lexical`."""
247
+ def observed_path(event):
248
+ """Normalized absolute path inside the container an open names, or None."""
246
249
  name = event.get('pathname') or ''
247
250
  if not name:
248
251
  return None
@@ -251,46 +254,154 @@ def project_path(event):
251
254
  if not base or not base.startswith('/'):
252
255
  return None
253
256
  name = base + '/' + name
254
- name = posixpath.normpath(name)
255
- return name[len(WORKSPACE):] if name.startswith(WORKSPACE) else None
257
+ return posixpath.normpath(name)
258
+
259
+
260
+ def project_path(event):
261
+ """The project file an open names, relative to the project, or None when
262
+ it is outside it. Worked out from the text of the path: links inside the
263
+ project are not followed, which a fact says as `resolution: lexical`."""
264
+ name = observed_path(event)
265
+ return name[len(WORKSPACE):] if name and name.startswith(WORKSPACE) else None
266
+
267
+
268
+ def dist_info_from_path(path):
269
+ """If `path` is a Python package metadata file inside a `*.dist-info`
270
+ folder anywhere in the container (including `/tmp/venv`), return
271
+ `('pip', package, version)`; else None."""
272
+ if not path:
273
+ return None
274
+ folder, leaf = posixpath.split(path)
275
+ if leaf not in DIST_INFO_FILES:
276
+ return None
277
+ dist = posixpath.basename(folder)
278
+ if not dist.endswith('.dist-info') or '-' not in dist:
279
+ return None
280
+ package, _, version = dist[:-len('.dist-info')].rpartition('-')
281
+ if not package or not version or package.startswith('.'):
282
+ return None
283
+ return ('pip', package[:200], version[:80])
284
+
256
285
 
286
+ def is_package_manager(argv):
287
+ """Whether `argv` is a package-manager invocation (npm/pip/uv/poetry,
288
+ `python ... -m pip`, `python ... -m ensurepip`, `*/bin/pip*`, or `get-pip.py`)."""
289
+ if not argv:
290
+ return False
291
+ bases = [posixpath.basename(part) for part in argv if isinstance(part, str) and part]
292
+ if not bases:
293
+ return False
294
+ if PACKAGE_TOOLS.intersection(bases[:4]):
295
+ return True
296
+ if any(PIP_BIN.match(base) or base == 'get-pip.py' for base in bases):
297
+ return True
298
+ if PYTHON_BIN.match(bases[0]):
299
+ for index, part in enumerate(argv[1:], start=1):
300
+ if part == '-m' and index + 1 < len(argv) and argv[index + 1] in ('pip', 'ensurepip'):
301
+ return True
302
+ if isinstance(part, str) and part in ('-mpip', '-mensurepip'):
303
+ return True
304
+ return False
305
+
306
+
307
+ def package_prefixes(argv):
308
+ """Container venv/target prefixes named in `argv` (e.g. `/tmp/venv` from
309
+ `/tmp/venv/bin/python`, or `--prefix` / `--target` / `-t`)."""
310
+ if not argv:
311
+ return []
312
+ found = []
313
+ first = posixpath.normpath(argv[0]) if isinstance(argv[0], str) and argv[0].startswith('/') else ''
314
+ match = VENV_BIN_PREFIX.match(first)
315
+ if match and match.group(1) not in SYSTEM_PREFIXES:
316
+ found.append(match.group(1))
317
+ for index, part in enumerate(argv[1:], start=1):
318
+ if not isinstance(part, str):
319
+ continue
320
+ value = None
321
+ if part in ('--prefix', '--target', '-t') and index + 1 < len(argv) and isinstance(argv[index + 1], str):
322
+ value = argv[index + 1]
323
+ elif part.startswith('--prefix='):
324
+ value = part[len('--prefix='):]
325
+ elif part.startswith('--target='):
326
+ value = part[len('--target='):]
327
+ if value:
328
+ norm = posixpath.normpath(value if value.startswith('/') else WORKSPACE + value)
329
+ if norm not in SYSTEM_PREFIXES and norm not in found:
330
+ found.append(norm)
331
+ return found
257
332
 
258
- def installed(workspace, home):
333
+
334
+ def _scan_pip_site(found, volume, site):
335
+ for name in names_inside(volume, site):
336
+ if name.endswith('.dist-info') and '-' in name:
337
+ package, _, version = name[:-len('.dist-info')].rpartition('-')
338
+ if package and version:
339
+ found[('pip', package[:200], version[:80])] = None
340
+
341
+
342
+ def installed(workspace, home, extra_prefixes=()):
259
343
  """{(manager, name, version): where it came from} as the package managers'
260
- own records on the volume have it. The agent can write those files, so a
261
- fact drawn from them is `reported`, not seen."""
344
+ own records on the host-mounted volumes have it. The agent can write those
345
+ files, so a fact drawn from them is `reported`, not seen.
346
+
347
+ `extra_prefixes` may name container prefixes (e.g. `/workspace/custom-env`
348
+ or `/home/node/myenv`) extracted from package-manager argv; only prefixes
349
+ inside the sandbox's own workspace or home volume are walked from the host.
350
+ Container-ephemeral paths like `/tmp/venv` are observed directly via open
351
+ syscalls (`dist_info_from_path`)."""
262
352
  found = {}
263
- roots = [''] + [name for name in names_inside(workspace, '') if name not in SKIPPED and not name.startswith('.')][:50]
264
- for root in roots:
265
- modules = posixpath.join(root, 'node_modules')
266
- lock = read_inside(workspace, posixpath.join(modules, '.package-lock.json'), 32 * 1024 * 1024)
267
- try:
268
- listed = json.loads(lock)['packages'] if lock else None
269
- except (ValueError, KeyError, TypeError):
270
- listed = None
271
- if isinstance(listed, dict):
272
- for key, entry in listed.items():
273
- if isinstance(key, str) and isinstance(entry, dict) and isinstance(entry.get('version'), str):
274
- found[('npm', key.rsplit('node_modules/', 1)[-1][:200], entry['version'][:80])] = str(entry.get('resolved') or '')[:300] or None
353
+ if workspace:
354
+ roots = [''] + [name for name in names_inside(workspace, '') if name not in SKIPPED and not name.startswith('.')][:50]
355
+ for root in roots:
356
+ modules = posixpath.join(root, 'node_modules')
357
+ lock = read_inside(workspace, posixpath.join(modules, '.package-lock.json'), 32 * 1024 * 1024)
358
+ try:
359
+ listed = json.loads(lock)['packages'] if lock else None
360
+ except (ValueError, KeyError, TypeError):
361
+ listed = None
362
+ if isinstance(listed, dict):
363
+ for key, entry in listed.items():
364
+ if isinstance(key, str) and isinstance(entry, dict) and isinstance(entry.get('version'), str):
365
+ found[('npm', key.rsplit('node_modules/', 1)[-1][:200], entry['version'][:80])] = str(entry.get('resolved') or '')[:300] or None
366
+ continue
367
+ # No npm record (yarn, pnpm, bun): the packages at the top of node_modules.
368
+ for name in names_inside(workspace, modules)[:1000]:
369
+ for package in ([posixpath.join(name, inner) for inner in names_inside(workspace, posixpath.join(modules, name))[:200]]
370
+ if name.startswith('@') else [name]):
371
+ text = read_inside(workspace, posixpath.join(modules, package, 'package.json'), 1024 * 1024)
372
+ try:
373
+ version = json.loads(text)['version'] if text else None
374
+ except (ValueError, KeyError, TypeError):
375
+ version = None
376
+ if isinstance(version, str):
377
+ found[('node', package[:200], version[:80])] = None
378
+ sites = ([(workspace, posixpath.join(env, 'lib')) for env in ('.venv', 'venv')] if workspace else []) + ([(home, '.local/lib')] if home else [])
379
+ direct_sites = []
380
+ for prefix in extra_prefixes or ():
381
+ if not isinstance(prefix, str) or not prefix:
275
382
  continue
276
- # No npm record (yarn, pnpm, bun): the packages at the top of node_modules.
277
- for name in names_inside(workspace, modules)[:1000]:
278
- for package in ([posixpath.join(name, inner) for inner in names_inside(workspace, posixpath.join(modules, name))[:200]]
279
- if name.startswith('@') else [name]):
280
- text = read_inside(workspace, posixpath.join(modules, package, 'package.json'), 1024 * 1024)
281
- try:
282
- version = json.loads(text)['version'] if text else None
283
- except (ValueError, KeyError, TypeError):
284
- version = None
285
- if isinstance(version, str):
286
- found[('node', package[:200], version[:80])] = None
287
- sites = [(workspace, posixpath.join(env, 'lib')) for env in ('.venv', 'venv')] + ([(home, '.local/lib')] if home else [])
383
+ norm = posixpath.normpath(prefix)
384
+ if workspace and (norm == WORKSPACE.rstrip('/') or norm.startswith(WORKSPACE)):
385
+ rel = norm[len(WORKSPACE):] if norm.startswith(WORKSPACE) else ''
386
+ lib = posixpath.join(rel, 'lib') if rel else 'lib'
387
+ if (workspace, lib) not in sites:
388
+ sites.append((workspace, lib))
389
+ if rel and (workspace, rel) not in direct_sites:
390
+ direct_sites.append((workspace, rel))
391
+ elif home and norm.startswith('/home/'):
392
+ parts = PurePosixPath(norm).parts # ('/', 'home', '<user>', ...)
393
+ if len(parts) >= 4:
394
+ rel = posixpath.join(*parts[3:])
395
+ lib = posixpath.join(rel, 'lib')
396
+ if (home, lib) not in sites:
397
+ sites.append((home, lib))
398
+ if (home, rel) not in direct_sites:
399
+ direct_sites.append((home, rel))
288
400
  for volume, lib in sites:
289
401
  for python in names_inside(volume, lib)[:10]:
290
- for name in names_inside(volume, posixpath.join(lib, python, 'site-packages')):
291
- if name.endswith('.dist-info') and '-' in name:
292
- package, _, version = name[:-len('.dist-info')].rpartition('-')
293
- found[('pip', package[:200], version[:80])] = None
402
+ _scan_pip_site(found, volume, posixpath.join(lib, python, 'site-packages'))
403
+ for volume, site in direct_sites:
404
+ _scan_pip_site(found, volume, site)
294
405
  return found
295
406
 
296
407
 
@@ -361,6 +472,8 @@ class Sandbox:
361
472
  self.watches = {} # folder -> inotify watch
362
473
  self.counts = {} # step -> opens that were only counted
363
474
  self.packages = None # what was installed when last looked
475
+ self.package_prefixes = set() # extra venv/target prefixes seen in package-manager argv
476
+ self.observed_packages = {} # {(manager, name, version): None} seen via open syscalls (e.g. /tmp/venv)
364
477
  self.package_due = self.package_who = None
365
478
  self.registry_at = float('-inf') # when a package registry was last connected to
366
479
  self.gap_at = float('-inf') # when events were last lost
@@ -685,8 +798,12 @@ class Engine(threading.Thread):
685
798
  and writer['who'].get('start_ns') in (None, event.get('process_start_ns'))):
686
799
  writer['gone'] = True
687
800
  box.due[path] = min(box.due.get(path, now + SETTLE), now + SETTLE)
688
- if gone and box.workspace and PACKAGE_TOOLS & {posixpath.basename(part) for part in gone['argv'][:4]}:
689
- # A package manager finished: see what it left, once it has settled.
801
+ if gone and is_package_manager(gone.get('argv')):
802
+ # A package manager finished: record any venv/target prefix it named
803
+ # and inspect what it left once writes have settled.
804
+ for prefix in package_prefixes(gone.get('argv')):
805
+ if len(box.package_prefixes) < 64:
806
+ box.package_prefixes.add(prefix)
690
807
  box.package_due = self.clock() + 1
691
808
  box.package_who = self.who(box, event, gone)
692
809
 
@@ -790,11 +907,21 @@ class Engine(threading.Thread):
790
907
  def opened(self, box, event):
791
908
  at_ns = int(event.get('timestamp_ns') or 0) or time.time_ns()
792
909
  who = self.who(box, event)
910
+ flags, errno = event.get('flags', 0), event.get('errno', 0)
911
+ writing = (flags & O_ACCMODE) != 0 or bool(flags & (O_CREAT | O_TRUNC))
912
+ if writing and not errno and not who.get('own'):
913
+ pkg = dist_info_from_path(observed_path(event))
914
+ if pkg and pkg not in box.observed_packages:
915
+ box.observed_packages[pkg] = None
916
+ if len(box.observed_packages) > 5000:
917
+ box.observed_packages.pop(next(iter(box.observed_packages)))
918
+ due = self.clock() + 1
919
+ box.package_due = min(box.package_due, due) if box.package_due else due
920
+ if not box.package_who or who.get('call_id'):
921
+ box.package_who = who
793
922
  path = project_path(event)
794
923
  if path is None or not box.workspace:
795
924
  return self.counted(box, who, '(outside the project)', at_ns)
796
- flags, errno = event.get('flags', 0), event.get('errno', 0)
797
- writing = (flags & O_ACCMODE) != 0 or bool(flags & (O_CREAT | O_TRUNC))
798
925
  guard = box.guarded.get(path)
799
926
  top = path.split('/', 1)[0] if '/' in path else '(project root)'
800
927
  if guard is None:
@@ -1187,9 +1314,9 @@ class Engine(threading.Thread):
1187
1314
 
1188
1315
  def packages(self, box):
1189
1316
  """What a package manager left that was not there before."""
1190
- if not box.workspace:
1317
+ if not box.workspace and not box.observed_packages:
1191
1318
  return
1192
- now = installed(box.workspace, box.home)
1319
+ now = {**installed(box.workspace, box.home, extra_prefixes=box.package_prefixes), **box.observed_packages}
1193
1320
  before, box.packages = box.packages or {}, now
1194
1321
  fresh = sorted(key for key in now if key not in before)
1195
1322
  if not fresh: