@commonlyai/cli 0.1.398 → 0.1.400

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.
@@ -31,11 +31,13 @@ import { createHash, randomBytes } from 'crypto';
31
31
  import { spawnSync } from 'child_process';
32
32
  import { existsSync, readFileSync, writeFileSync } from 'fs';
33
33
  import {
34
- chmod, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile,
34
+ chmod, link, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile,
35
35
  } from 'fs/promises';
36
36
  import { homedir, tmpdir } from 'os';
37
- import { join } from 'path';
37
+ import { basename, dirname, join } from 'path';
38
38
 
39
+ import { isShippedCommonlyMcpCommand } from '../declared-mcp-guard.js';
40
+ import { describeMcpCommand } from '../mcp-server-version.js';
39
41
  import {
40
42
  MCP_BRIDGE_ENV, MCP_BRIDGE_SECRET_ENV, MCP_SHIM_SOURCE, hostMcpServers, startMcpBridge,
41
43
  } from './microsandbox-mcp-bridge.js';
@@ -71,6 +73,11 @@ export const GUEST_VOLUME = 'commonly-agents';
71
73
  export const GUEST_VOLUME_SPEC = `${GUEST_VOLUME}:/opt/agents:kind=disk,size=4G`;
72
74
  export const GUEST_VOLUME_TURN_SPEC = `${GUEST_VOLUME_SPEC},ro`;
73
75
  export const GUEST_CLAUDE = '/opt/agents/bin/claude';
76
+ // Codex beside it on the same volume, from its own npm package (the musl Linux
77
+ // binary rides in as an optional dependency). The spike ran this version in
78
+ // the guest, through the provider proxy, with only DNS and two ports open.
79
+ export const GUEST_CODEX_VERSION = '0.172.0';
80
+ export const GUEST_CODEX = '/opt/agents/bin/codex';
74
81
  export const GUEST_HOST = 'host.microsandbox.internal';
75
82
  export const GUEST_TURN_DIR = '/run/commonly';
76
83
  export const GUEST_WORKSPACE = '/workspace';
@@ -159,6 +166,9 @@ export const probeWhp = ({ platform = process.platform, run = spawnSync, env = p
159
166
  return parseWhpProbe(result?.stdout);
160
167
  };
161
168
 
169
+ // The adapters that run a turn inside the VM. Every other one refuses the mode.
170
+ export const MICROVM_ADAPTERS = new Set(['claude', 'codex']);
171
+
162
172
  /**
163
173
  * Attach-time check for `sandbox.mode=microvm`. Throws the reason a person can
164
174
  * act on; returns nothing when the mode can run here.
@@ -170,8 +180,9 @@ export const checkMicrovmAttach = ({
170
180
  if (!microvmFlagOn(env)) {
171
181
  throw new Error(`sandbox.mode=microvm is opt-in: set ${MICROVM_FLAG_ENV}=1 in the environment that runs this CLI.`);
172
182
  }
173
- if (adapterName !== 'claude') {
174
- throw new Error(`sandbox.mode=microvm supports only the claude adapter for now, not ${adapterName || 'this one'}.`);
183
+ if (!MICROVM_ADAPTERS.has(adapterName)) {
184
+ throw new Error('sandbox.mode=microvm supports only the claude adapter and the codex adapter for now, '
185
+ + `not ${adapterName || 'this one'}.`);
175
186
  }
176
187
  const whp = probe({ platform, env });
177
188
  if (!whp.available) {
@@ -184,6 +195,31 @@ export const checkMicrovmAttach = ({
184
195
  }
185
196
  };
186
197
 
198
+ /**
199
+ * Refuses an MCP declaration the microVM Codex turn can never run: anything
200
+ * but a stdio server with a command (an HTTP or SSE server, the grant broker
201
+ * included), and any stdio server that is not the Commonly MCP server (the
202
+ * shipped `npx -y @commonlyai/mcp` spec, or a build whose package.json names
203
+ * it). Run at attach, before any registry write, and on every turn. The turn
204
+ * resolves only the shipped spec to a home build (mcp-home.js planMcpSpawn),
205
+ * so judging the declared command here refuses the same set it would.
206
+ */
207
+ export const refuseMicrovmMcpDeclarations = (servers, { describe = describeMcpCommand } = {}) => {
208
+ for (const server of servers || []) {
209
+ if (!server?.name) continue;
210
+ const transport = typeof server.transport === 'string' ? server.transport.trim().toLowerCase() : 'stdio';
211
+ if (transport !== 'stdio' || !Array.isArray(server.command) || !server.command.length) {
212
+ throw new Error(`The microVM sandbox runs only the Commonly MCP server, over stdio, and ${server.name} `
213
+ + `is ${transport === 'stdio' ? 'declared without a command' : `a ${transport} server`}. `
214
+ + 'Remove it to run this seat in the microVM.');
215
+ }
216
+ if (!(isShippedCommonlyMcpCommand(server.command) || Boolean(describe(server.command)?.isCommonly))) {
217
+ throw new Error(`The microVM sandbox runs only the Commonly MCP server, on this computer, and ${server.name} `
218
+ + 'is another server: it would run outside the VM. Remove it to run this seat in the microVM.');
219
+ }
220
+ }
221
+ };
222
+
187
223
  // ── msb, pinned ─────────────────────────────────────────────────────────────
188
224
 
189
225
  const sha256 = (buffer) => createHash('sha256').update(buffer).digest('hex');
@@ -277,40 +313,70 @@ export const ensureMsb = async ({
277
313
 
278
314
  // ── the agent install volume ────────────────────────────────────────────────
279
315
 
316
+ // The agents a turn can run, each installed once onto the volume from npm at
317
+ // its pinned version. Both share the volume's npm prefix, so installing one
318
+ // leaves the other in place.
319
+ export const GUEST_AGENTS = Object.freeze({
320
+ claude: Object.freeze({
321
+ label: 'Claude Code', pkg: '@anthropic-ai/claude-code', version: GUEST_CLAUDE_VERSION, bin: GUEST_CLAUDE,
322
+ }),
323
+ codex: Object.freeze({
324
+ label: 'Codex', pkg: '@openai/codex', version: GUEST_CODEX_VERSION, bin: GUEST_CODEX,
325
+ }),
326
+ });
327
+
280
328
  /**
281
- * Claude Code inside the guest, on the named disk volume, at the pinned
282
- * version. The install sandbox has microsandbox's default network (the public
283
- * internet, nothing on the host) and no secrets; every turn after runs fenced.
329
+ * An agent inside the guest, on the named disk volume, at its pinned version.
330
+ * The install sandbox has microsandbox's default network (the public internet,
331
+ * nothing on the host) and no secrets; every turn after runs fenced.
284
332
  */
285
- export const ensureGuestClaude = ({
286
- msb, root = microsandboxRoot(), run = spawnSync, log = () => {},
333
+ /**
334
+ * Whether `--version` output reports exactly `version`: some line's version
335
+ * token (`2.1.331 (Claude Code)`, `codex-cli 0.172.0`) equals it, so
336
+ * `10.172.0` or `0.172.01` never passes for `0.172.0`.
337
+ */
338
+ export const reportsVersion = (stdout, version) => String(stdout || '').split(/\r?\n/).some((line) => {
339
+ const token = /(?:^|\s)v?(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)(?=\s|$)/.exec(line.trim());
340
+ return token?.[1] === version;
341
+ });
342
+
343
+ export const ensureGuestAgent = ({
344
+ agent = 'claude', msb, root = microsandboxRoot(), run = spawnSync, log = () => {},
287
345
  }) => {
346
+ const spec = GUEST_AGENTS[agent];
347
+ if (!spec) throw new Error(`the microVM sandbox has no guest install for ${agent}`);
288
348
  // The volume outlives this CLI's folder only if someone removes the folder,
289
349
  // so a marker beside msb says the install already passed once.
290
- const marker = join(root, `.guest-claude-${GUEST_CLAUDE_VERSION}`);
350
+ const marker = join(root, `.guest-${agent}-${spec.version}`);
291
351
  if (existsSync(marker)) return { installed: false };
292
352
  const runGuest = (command, timeout) => run(msb, [
293
353
  'run', '--mount-named', GUEST_VOLUME_SPEC, GUEST_IMAGE, '--', 'sh', '-c', command,
294
354
  ], { encoding: 'utf8', timeout, windowsHide: true });
295
- const probe = runGuest(`${GUEST_CLAUDE} --version 2>/dev/null || true`, 180000);
296
- if (String(probe?.stdout || '').includes(GUEST_CLAUDE_VERSION)) {
355
+ const probe = runGuest(`${spec.bin} --version 2>/dev/null || true`, 180000);
356
+ if (reportsVersion(probe?.stdout, spec.version)) {
297
357
  writeFileSync(marker, `${GUEST_IMAGE}\n`);
298
358
  return { installed: false };
299
359
  }
300
- log(`microvm: installing Claude Code ${GUEST_CLAUDE_VERSION} into the ${GUEST_VOLUME} volume (once)`);
360
+ log(`microvm: installing ${spec.label} ${spec.version} into the ${GUEST_VOLUME} volume (once)`);
301
361
  const install = runGuest(
302
- `npm --prefix /opt/agents i -g --no-fund --no-audit @anthropic-ai/claude-code@${GUEST_CLAUDE_VERSION} >/tmp/npm.log 2>&1`
303
- + ` && ${GUEST_CLAUDE} --version || (tail -20 /tmp/npm.log; exit 1)`,
362
+ `npm --prefix /opt/agents i -g --no-fund --no-audit ${spec.pkg}@${spec.version} >/tmp/npm.log 2>&1`
363
+ + ` && ${spec.bin} --version || (tail -20 /tmp/npm.log; exit 1)`,
304
364
  600000,
305
365
  );
306
- if (install?.error || install?.status !== 0 || !String(install?.stdout || '').includes(GUEST_CLAUDE_VERSION)) {
307
- throw new Error(`installing Claude Code into the microVM volume failed: ${install?.error?.message
366
+ if (install?.error || install?.status !== 0 || !reportsVersion(install?.stdout, spec.version)) {
367
+ throw new Error(`installing ${spec.label} into the microVM volume failed: ${install?.error?.message
308
368
  || String(install?.stdout || install?.stderr || '').trim().slice(-600) || `exit ${install?.status}`}`);
309
369
  }
310
370
  writeFileSync(marker, `${GUEST_IMAGE}\n`);
311
371
  return { installed: true };
312
372
  };
313
373
 
374
+ /** Claude Code on the volume (ensureGuestAgent for claude). */
375
+ export const ensureGuestClaude = (options) => ensureGuestAgent({ ...options, agent: 'claude' });
376
+
377
+ /** Codex on the volume (ensureGuestAgent for codex). */
378
+ export const ensureGuestCodex = (options) => ensureGuestAgent({ ...options, agent: 'codex' });
379
+
314
380
  // ── one turn ────────────────────────────────────────────────────────────────
315
381
 
316
382
  // msb splits SOURCE:DEST[:OPTIONS] on colons other than a drive letter's, and
@@ -326,12 +392,15 @@ const mountSource = (path, label) => {
326
392
 
327
393
  // The workspace is always read-only here: a writable one would hand the guest
328
394
  // the project's .git, whose hooks and config the host's own git later runs.
395
+ // `labels`: KEY=VALUE pairs msb keeps on the VM, so a later turn can find this
396
+ // one by its seat (ensureNoSeatVm). Only the Codex turn passes one.
329
397
  export const buildMicrovmRunArgs = ({
330
- ports, turnDir, workspace, home, cpus = 2, memory = '2G',
398
+ ports, turnDir, workspace, home, cpus = 2, memory = '2G', labels = [],
331
399
  }) => [
332
400
  'run',
333
401
  '--cpus', String(cpus),
334
402
  '--memory', memory,
403
+ ...labels.flatMap((label) => ['--label', label]),
335
404
  ...buildMicrovmFence(ports),
336
405
  '--mount-named', GUEST_VOLUME_TURN_SPEC,
337
406
  '--mount-dir', `${mountSource(turnDir, 'turn folder')}:${GUEST_TURN_DIR}:ro`,
@@ -343,6 +412,138 @@ export const buildMicrovmRunArgs = ({
343
412
  'node', `${GUEST_TURN_DIR}/entry.js`,
344
413
  ];
345
414
 
415
+ // ── one seat, one VM ────────────────────────────────────────────────────────
416
+
417
+ // The host checks every path under a seat HOME before it touches it, which is
418
+ // sound only while no VM has that HOME mounted. Killing msb.exe (a timeout, a
419
+ // cancel) does not stop the VM: msb runs it as a process of its own and stops
420
+ // it only on its own exit path. So each Codex turn's VM carries its seat's
421
+ // label, and before the host touches the HOME it asks msb for every VM with
422
+ // that label, force-stops any still alive, and asks again.
423
+
424
+ export const MICROVM_SEAT_LABEL_KEY = 'commonly-seat';
425
+
426
+ /** The label of a seat's VMs: the seat HOME's folder name (a hash and the trust). */
427
+ export const microvmSeatLabel = (home) => `${MICROVM_SEAT_LABEL_KEY}=${basename(String(home || ''))}`;
428
+
429
+ // msb's settled statuses (SandboxStatus); a VM in any other may hold the mount.
430
+ const MICROVM_SETTLED_STATUSES = new Set(['Stopped', 'Crashed']);
431
+
432
+ const seatBusy = (message) => Object.assign(
433
+ new Error(`the microVM sandbox will not touch this seat's HOME: ${message}`),
434
+ { code: 'microvm_seat_busy' },
435
+ );
436
+
437
+ /**
438
+ * Confirms no VM of this seat is alive, force-stopping any that is, by msb's
439
+ * own record: `msb list --label` (which checks each VM's process is alive)
440
+ * and `msb stop --force` (which kills the VM's process and waits for it to
441
+ * exit). Throws `microvm_seat_busy` whenever it can't confirm: msb fails, its
442
+ * answer can't be read, or a VM is still alive after the stop. Another seat's
443
+ * VMs carry another label and are never listed or stopped.
444
+ */
445
+ export const ensureNoSeatVm = ({
446
+ msb, label, run = spawnSync, env = process.env, log = () => {}, timeoutMs = 60000,
447
+ }) => {
448
+ if (!msb || !label || !label.startsWith(`${MICROVM_SEAT_LABEL_KEY}=`) || label.endsWith('=')) {
449
+ throw seatBusy('there is no msb or no seat label to look its VMs up by');
450
+ }
451
+ const options = {
452
+ encoding: 'utf8', env, timeout: timeoutMs, windowsHide: true,
453
+ };
454
+ const live = () => {
455
+ const listed = run(msb, ['list', '--label', label, '--format', 'json'], options);
456
+ if (listed?.error || listed?.status !== 0) {
457
+ throw seatBusy(`msb could not list its VMs (${listed?.error?.message
458
+ || String(listed?.stderr || '').trim().slice(-300) || `exit ${listed?.status}`})`);
459
+ }
460
+ let entries;
461
+ try {
462
+ // msb list --format json prints an array even when nothing matches, so a
463
+ // blank answer is no inventory, never an empty one.
464
+ entries = JSON.parse(String(listed.stdout || '').trim());
465
+ } catch {
466
+ entries = null;
467
+ }
468
+ if (!Array.isArray(entries)) throw seatBusy('msb\'s list of VMs could not be read');
469
+ return entries.filter((entry) => !MICROVM_SETTLED_STATUSES.has(String(entry?.status)));
470
+ };
471
+ const before = live();
472
+ if (!before.length) return { stopped: [] };
473
+ const names = before.map((entry) => String(entry?.name || ''));
474
+ if (names.some((name) => !name)) throw seatBusy('msb listed a VM of this seat with no name to stop it by');
475
+ for (const name of names) {
476
+ log(`microvm: stopping ${name}, a VM of this seat still running from an earlier turn`);
477
+ run(msb, ['stop', '--force', '--quiet', '--', name], options);
478
+ }
479
+ const after = live();
480
+ if (after.length) {
481
+ throw seatBusy(`${after.map((entry) => `${entry?.name} (${entry?.status})`).join(', ')} is still `
482
+ + 'running after msb stop --force; stop or remove it (msb stop, msb rm) and the next turn runs');
483
+ }
484
+ return { stopped: names };
485
+ };
486
+
487
+ // Every msb.exe on this computer with its command line, as a JSON array
488
+ // (`[]` when there is none, so a blank answer is never read as "none").
489
+ export const MSB_PROCESS_LIST_SCRIPT = "$ErrorActionPreference = 'Stop'; "
490
+ + 'ConvertTo-Json -Compress -Depth 2 -InputObject @(Get-CimInstance Win32_Process '
491
+ + "-Filter \"Name='msb.exe'\" | Select-Object ProcessId,CommandLine)";
492
+
493
+ const sleepSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
494
+
495
+ /**
496
+ * Kills every msb.exe whose command line names this seat (its label, or its
497
+ * HOME as a mount source), and confirms they are gone. Such a process is an
498
+ * `msb run` whose `agent run` died (a hard kill): it takes no seat lock and
499
+ * could boot a VM after ensureNoSeatVm has looked. Called under the seat lock,
500
+ * before that check, so once it returns nothing can start a VM of the seat.
501
+ * Windows only (the mode runs nowhere else); the listing goes through
502
+ * PowerShell's Get-CimInstance, and a listing that fails or can't be read
503
+ * refuses the turn (`microvm_seat_busy`).
504
+ */
505
+ export const stopOrphanSeatMsb = ({
506
+ label, home, platform = process.platform, run = spawnSync, kill = (pid) => process.kill(pid),
507
+ env = process.env, log = () => {}, attempts = 25, pollMs = 200,
508
+ }) => {
509
+ if (platform !== 'win32') return { stopped: [] };
510
+ if (!label || !home) throw seatBusy('there is no seat label or HOME to find its msb processes by');
511
+ const powershell = join(env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
512
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
513
+ const names = new RegExp(`(?:${escape(label)}(?=$|[\\s"'])|${escape(home)}(?=[:"'\\s]))`, 'i');
514
+ const seatMsb = () => {
515
+ const listed = run(powershell, [
516
+ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', MSB_PROCESS_LIST_SCRIPT,
517
+ ], { encoding: 'utf8', timeout: 30000, windowsHide: true });
518
+ if (listed?.error || listed?.status !== 0) {
519
+ throw seatBusy(`the msb processes could not be listed (${listed?.error?.message
520
+ || String(listed?.stderr || '').trim().slice(-300) || `exit ${listed?.status}`})`);
521
+ }
522
+ let entries = null;
523
+ try {
524
+ entries = JSON.parse(String(listed.stdout || '').trim());
525
+ } catch { /* below */ }
526
+ if (!Array.isArray(entries)) throw seatBusy('the list of msb processes could not be read');
527
+ return entries
528
+ .filter((entry) => names.test(String(entry?.CommandLine || '')))
529
+ .map((entry) => Number(entry?.ProcessId))
530
+ .filter((pid) => Number.isInteger(pid) && pid > 0 && pid !== process.pid);
531
+ };
532
+ const found = seatMsb();
533
+ if (!found.length) return { stopped: [] };
534
+ for (const pid of found) {
535
+ log(`microvm: killing msb.exe ${pid}, left running for this seat by an earlier agent run`);
536
+ try { kill(pid); } catch { /* confirmed below */ }
537
+ }
538
+ let left = seatMsb();
539
+ for (let i = 1; i < attempts && left.length; i += 1) {
540
+ sleepSync(pollMs);
541
+ left = seatMsb();
542
+ }
543
+ if (left.length) throw seatBusy(`msb.exe ${left.join(', ')} of this seat is still running after being killed`);
544
+ return { stopped: found };
545
+ };
546
+
346
547
  // Runs inside the guest. Reads the turn, starts the agent with exactly that
347
548
  // env, and exits with its code. Kept tiny: it is the only code we put in the VM.
348
549
  export const GUEST_ENTRY_SOURCE = `'use strict';
@@ -467,45 +668,128 @@ const defaultPidAlive = (pid) => {
467
668
  * a lock a live process leaked, or one naming a reused pid, can't wedge every
468
669
  * later install. A lock that names no process falls back to the shorter age.
469
670
  */
470
- const lockAbandoned = (content, mtimeMs, { now, pidAlive }) => {
671
+ const lockAbandoned = (content, mtimeMs, {
672
+ now, pidAlive, maxMs = INSTALL_LOCK_MAX_MS, staleMs = INSTALL_LOCK_STALE_MS,
673
+ }) => {
471
674
  const age = now() - mtimeMs;
472
675
  const pid = Number.parseInt(String(content).split(/\s+/)[0], 10);
473
- if (Number.isInteger(pid) && pid > 0) return age > INSTALL_LOCK_MAX_MS || !pidAlive(pid);
474
- return age > INSTALL_LOCK_STALE_MS;
676
+ if (Number.isInteger(pid) && pid > 0) return age > maxMs || !pidAlive(pid);
677
+ return age > staleMs;
475
678
  };
476
679
 
477
- // The guard is held only for a read and an unlink, so one older than this was
478
- // left by a process that died inside that window.
479
- const INSTALL_LOCK_GUARD_STALE_MS = 30 * 1000;
680
+ // How long a release keeps trying a lock or guard that Windows won't move
681
+ // (another handle on it, an antivirus scan say) before leaving it to the
682
+ // next waiter's takeover rules.
683
+ const LOCK_RELEASE_RETRY_MS = 5 * 1000;
684
+
685
+ // How long a guard holder may act: it is held only for a read and a removal.
686
+ // The guard reads `<pid> <token> <deadline>`, and its holder acts on the lock
687
+ // only before that deadline.
688
+ const LOCK_GUARD_HOLD_MS = 30 * 1000;
689
+
690
+ /**
691
+ * Removes `path` only if the file there is the one `isJudged(content, stat)`
692
+ * accepts. The file is first moved, atomically, to a name only this call
693
+ * knows, and judged there, so the file judged is the file removed. One that
694
+ * is not the judged file is put back with a no-clobber link; if the path was
695
+ * taken meanwhile, the moved file is dropped (its holder's own release then
696
+ * finds a lock that is not its own and leaves it). Returns 'gone' (nothing
697
+ * there), 'busy' (Windows would not move it now), 'removed' or 'kept'.
698
+ */
699
+ export const removeIfJudged = async (path, isJudged, { io = { rename, stat, readFile, link, rm } } = {}) => {
700
+ const aside = `${path}.${randomBytes(8).toString('hex')}.aside`;
701
+ try {
702
+ await io.rename(path, aside);
703
+ } catch (error) {
704
+ if (error?.code === 'ENOENT') return 'gone';
705
+ if (['EPERM', 'EBUSY', 'EACCES'].includes(error?.code)) return 'busy';
706
+ throw error;
707
+ }
708
+ const held = await io.stat(aside).catch(() => null);
709
+ const content = await io.readFile(aside, 'utf8').catch(() => null);
710
+ if (isJudged(content, held)) {
711
+ await io.rm(aside, { recursive: true, force: true });
712
+ return 'removed';
713
+ }
714
+ try {
715
+ await io.link(aside, path);
716
+ } catch (error) {
717
+ if (error?.code !== 'EEXIST') {
718
+ // No hard links on this filesystem: move it back if the path is still free.
719
+ const free = await io.stat(path).then(() => false, (e) => e?.code === 'ENOENT');
720
+ if (free) {
721
+ await io.rename(aside, path).catch(() => {});
722
+ return 'kept';
723
+ }
724
+ }
725
+ }
726
+ await io.rm(aside, { recursive: true, force: true });
727
+ return 'kept';
728
+ };
480
729
 
481
730
  /**
482
- * Runs `fn` holding `guard`, a short-lived lock that serialises every removal
483
- * of the install lock (a takeover or a release), so no removal can act on a
484
- * lock that changed after it was read.
731
+ * Runs `fn(stillMine)` holding `guard`, a short-lived lock that serialises
732
+ * every removal of the lock (a takeover or a release). A guard is taken over
733
+ * only as seatLockAbandoned says (its pid gone, or its own deadline passed;
734
+ * never on age while its holder may act), through removeIfJudged, so a
735
+ * waiter never removes a guard another waiter has just taken. `stillMine()`
736
+ * is false once this holder's deadline has passed, and the holder then
737
+ * removes nothing. Past `until` (when given), a waiter stops with `busy()`.
485
738
  */
486
- const withLockGuard = async (guard, fn, { now }) => {
739
+ const withLockGuard = async (guard, fn, {
740
+ now, pidAlive = defaultPidAlive, until = Infinity, busy = () => new Error(`${guard} is held`), remove = removeIfJudged,
741
+ }) => {
742
+ const token = randomBytes(8).toString('hex');
743
+ let mine;
744
+ let deadline;
487
745
  for (;;) {
746
+ deadline = now() + LOCK_GUARD_HOLD_MS;
747
+ mine = `${process.pid} ${token} ${deadline}\n`;
488
748
  try {
489
749
  // eslint-disable-next-line no-await-in-loop
490
- await writeFile(guard, `${process.pid}\n`, { flag: 'wx' });
750
+ await writeFile(guard, mine, { flag: 'wx' });
491
751
  break;
492
752
  } catch (error) {
493
753
  if (error?.code !== 'EEXIST') throw error;
494
754
  // eslint-disable-next-line no-await-in-loop
495
755
  const held = await stat(guard).catch(() => null);
496
- if (held && now() - held.mtimeMs > INSTALL_LOCK_GUARD_STALE_MS) {
756
+ // eslint-disable-next-line no-await-in-loop
757
+ const content = held ? await readFile(guard, 'utf8').catch(() => null) : null;
758
+ if (held && content !== null && seatLockAbandoned(content, held.mtimeMs, {
759
+ now, pidAlive, graceMs: LOCK_GUARD_HOLD_MS,
760
+ })) {
497
761
  // eslint-disable-next-line no-await-in-loop
498
- await rm(guard, { force: true });
762
+ const removal = await remove(guard, (c, st) => c === content && st?.ino === held.ino);
763
+ // Windows wouldn't move it now (another handle on it): wait like a
764
+ // live holder, within `until`, rather than spin on it.
765
+ if (removal === 'busy') {
766
+ if (now() > until) throw busy();
767
+ // eslint-disable-next-line no-await-in-loop
768
+ await new Promise((resolve) => { setTimeout(resolve, 20); });
769
+ }
770
+ } else if (now() > until) {
771
+ throw busy();
499
772
  } else {
500
773
  // eslint-disable-next-line no-await-in-loop
501
774
  await new Promise((resolve) => { setTimeout(resolve, 20); });
502
775
  }
503
776
  }
504
777
  }
778
+ const stillMine = () => now() <= deadline;
505
779
  try {
506
- return await fn();
780
+ return await fn(stillMine);
507
781
  } finally {
508
- await rm(guard, { force: true }).catch(() => {});
782
+ // Past its deadline the guard may be another's already: leave it. A guard
783
+ // Windows won't move now is tried again for a few seconds, each attempt
784
+ // judging it afresh as ours.
785
+ const releaseUntil = now() + LOCK_RELEASE_RETRY_MS;
786
+ while (stillMine()) {
787
+ // eslint-disable-next-line no-await-in-loop
788
+ const released = await remove(guard, (c) => c === mine).catch(() => 'failed');
789
+ if (released !== 'busy' || now() > releaseUntil) break;
790
+ // eslint-disable-next-line no-await-in-loop
791
+ await new Promise((resolve) => { setTimeout(resolve, 20); });
792
+ }
509
793
  }
510
794
  };
511
795
 
@@ -523,33 +807,75 @@ const withLockGuard = async (guard, fn, { now }) => {
523
807
  * holder's lock is displaced. The holder also removes a lock it can't read at
524
808
  * all, so an unreadable lock is never left behind.
525
809
  */
526
- export const withInstallLock = async (root, fn, {
527
- waitMs = INSTALL_LOCK_STALE_MS, pollMs = 500, now = Date.now, pidAlive = defaultPidAlive,
528
- } = {}) => {
810
+ export const withInstallLock = (root, fn, {
811
+ waitMs = INSTALL_LOCK_STALE_MS, pollMs = 500, now = Date.now, pidAlive = defaultPidAlive, _remove,
812
+ } = {}) => withFileLock(root, '.install.lock', fn, {
813
+ waitMs,
814
+ pollMs,
815
+ now,
816
+ pidAlive,
817
+ ...(_remove ? { remove: _remove } : {}),
818
+ abandoned: (content, mtimeMs) => lockAbandoned(content, mtimeMs, { now, pidAlive }),
819
+ busy: (lock) => new Error(`another turn is still installing the microVM sandbox (${lock}); try again shortly`),
820
+ });
821
+
822
+ // The lock withInstallLock describes, at `<root>/<name>`. `abandoned(content,
823
+ // mtimeMs)` judges a held lock; `busy(lock)` is the error once `waitMs` has
824
+ // passed; `suffix` is extra holder text after `<pid> <token>`.
825
+ //
826
+ // A takeover judges the lock twice: once unguarded, then again under the guard
827
+ // from a fresh stat and read of the same file, and it deletes only when the
828
+ // guarded pair is still abandoned and reads exactly what was judged. So the age
829
+ // of a lock that was replaced in between (its new holder still writing an
830
+ // empty file) is never applied to the replacement.
831
+ const withFileLock = async (root, name, fn, {
832
+ waitMs, pollMs = 500, now = Date.now, busy, abandoned, suffix = () => '', pidAlive = defaultPidAlive,
833
+ remove = removeIfJudged,
834
+ }) => {
529
835
  await mkdir(root, { recursive: true });
530
- const lock = join(root, '.install.lock');
531
- const guard = join(root, '.install.lock.guard');
532
- const mine = `${process.pid} ${randomBytes(8).toString('hex')}\n`;
836
+ const lock = join(root, name);
837
+ const guard = join(root, `${name}.guard`);
838
+ const token = randomBytes(8).toString('hex');
839
+ let mine = null;
533
840
  const deadline = now() + waitMs;
841
+ const observe = async () => {
842
+ const held = await stat(lock).catch(() => null);
843
+ const content = held ? await readFile(lock, 'utf8').catch(() => null) : null;
844
+ return held && content !== null ? { held, content } : null;
845
+ };
534
846
  for (;;) {
535
847
  try {
848
+ // Built at each try, so a suffix naming a time counts from the take.
849
+ mine = `${process.pid} ${token}${suffix()}\n`;
536
850
  // eslint-disable-next-line no-await-in-loop
537
851
  await writeFile(lock, mine, { flag: 'wx' });
538
852
  break;
539
853
  } catch (error) {
540
854
  if (error?.code !== 'EEXIST') throw error;
541
855
  // eslint-disable-next-line no-await-in-loop
542
- const held = await stat(lock).catch(() => null);
543
- // eslint-disable-next-line no-await-in-loop
544
- const judged = held ? await readFile(lock, 'utf8').catch(() => null) : null;
545
- if (held && judged !== null && lockAbandoned(judged, held.mtimeMs, { now, pidAlive })) {
856
+ const seen = await observe();
857
+ if (seen && abandoned(seen.content, seen.held.mtimeMs)) {
858
+ // The file judged is the file removed: removeIfJudged moves it aside
859
+ // and checks it there against the judgement.
860
+ const isJudged = (content, held) => content === seen.content && held?.ino === seen.held.ino
861
+ && held.mtimeMs === seen.held.mtimeMs && abandoned(content, held.mtimeMs);
546
862
  // eslint-disable-next-line no-await-in-loop
547
- await withLockGuard(guard, async () => {
548
- const current = await readFile(lock, 'utf8').catch(() => null);
549
- if (current === judged) await rm(lock, { force: true });
550
- }, { now });
863
+ const removal = await withLockGuard(guard, async (stillMine) => {
864
+ const again = await observe();
865
+ if (again && isJudged(again.content, again.held) && stillMine()) return remove(lock, isJudged);
866
+ return 'kept';
867
+ }, {
868
+ now, pidAlive, until: deadline, busy: () => busy(lock), remove,
869
+ });
870
+ // Windows wouldn't move the abandoned lock now (another handle on it):
871
+ // wait and judge it again, within `waitMs`, rather than spin on it.
872
+ if (removal === 'busy') {
873
+ if (now() > deadline) throw busy(lock);
874
+ // eslint-disable-next-line no-await-in-loop
875
+ await new Promise((resolve) => { setTimeout(resolve, pollMs); });
876
+ }
551
877
  } else if (now() > deadline) {
552
- throw new Error(`another turn is still installing the microVM sandbox (${lock}); try again shortly`);
878
+ throw busy(lock);
553
879
  } else {
554
880
  // eslint-disable-next-line no-await-in-loop
555
881
  await new Promise((resolve) => { setTimeout(resolve, pollMs); });
@@ -559,19 +885,109 @@ export const withInstallLock = async (root, fn, {
559
885
  try {
560
886
  return await fn();
561
887
  } finally {
562
- await withLockGuard(guard, async () => {
563
- const current = await readFile(lock, 'utf8').then((text) => text, (error) => error);
564
- // Not `instanceof Error`: fs errors can come from another realm (a test VM).
565
- const unreadable = typeof current !== 'string' && current?.code !== 'ENOENT';
566
- if (current === mine || unreadable) await rm(lock, { recursive: true, force: true });
567
- }, { now }).catch(() => {});
888
+ // The release, under the guard. The lock is read first, and only a file
889
+ // read as ours, or one that can't be read at all (never left behind), is
890
+ // moved aside, and is judged again there. A lock that is not ours (a
891
+ // successor's, after a takeover) is never renamed: moving it would free
892
+ // the path for a moment, and a third turn's create could win it. Every
893
+ // removal runs under the guard, so nothing replaces the lock between this
894
+ // read and the move. Windows refusing the move ('busy') is retried for a
895
+ // few seconds, each attempt reading afresh.
896
+ const releaseUntil = now() + LOCK_RELEASE_RETRY_MS;
897
+ for (;;) {
898
+ // eslint-disable-next-line no-await-in-loop
899
+ const released = await withLockGuard(guard, async (stillMine) => {
900
+ if (!stillMine()) return 'kept';
901
+ const held = await stat(lock).catch((error) => error);
902
+ if (held?.code === 'ENOENT') return 'gone';
903
+ const read = await readFile(lock, 'utf8').then((text) => ({ text }), (error) => ({ error }));
904
+ if (['EBUSY', 'EPERM', 'EACCES'].includes(read.error?.code)) return 'busy';
905
+ const unreadable = Boolean(read.error);
906
+ if (!unreadable && read.text !== mine) return 'kept';
907
+ return remove(lock, (content, st) => (unreadable ? content === null : content === mine)
908
+ && (typeof held?.ino !== 'number' || st?.ino === held.ino));
909
+ }, {
910
+ // A guard another holds frees within its 30-second deadline: wait that out.
911
+ now, pidAlive, remove, until: releaseUntil + LOCK_GUARD_HOLD_MS,
912
+ }).catch(() => 'failed');
913
+ if (released !== 'busy' || now() > releaseUntil) break;
914
+ // eslint-disable-next-line no-await-in-loop
915
+ await new Promise((resolve) => { setTimeout(resolve, Math.min(pollMs, 100)); });
916
+ }
568
917
  }
569
918
  };
570
919
 
571
- /** msb and the guest's Claude, ready to run a turn. */
572
- export const prepareMicrovmHost = async ({ log, root = microsandboxRoot() } = {}) => withInstallLock(root, async () => {
920
+ // How long a second turn of a seat waits for the first before refusing.
921
+ export const SEAT_LOCK_WAIT_MS = 2 * 60 * 1000;
922
+
923
+ // A lock file that names no holder yet is one whose holder is between its
924
+ // exclusive create and its write; only past this age is it taken as left by a
925
+ // process that died in that window.
926
+ const SEAT_LOCK_EMPTY_GRACE_MS = 60 * 1000;
927
+
928
+ /**
929
+ * Whether a seat lock reading `content` can be taken over. Never on age alone,
930
+ * and never from a holder that may still act on the HOME:
931
+ * - its pid is gone (pidAlive false; EPERM counts as alive), or
932
+ * - the deadline the holder wrote has passed. The holder itself never touches
933
+ * the HOME after its own deadline (withSeatLock hands it `pastDeadline`), so
934
+ * a live pid past it is a reused pid or a holder that has stopped acting.
935
+ * A lock with no readable pid is abandoned only past SEAT_LOCK_EMPTY_GRACE_MS
936
+ * (a holder still writing it).
937
+ */
938
+ export const seatLockAbandoned = (content, mtimeMs, {
939
+ now = Date.now, pidAlive = defaultPidAlive, graceMs = SEAT_LOCK_EMPTY_GRACE_MS,
940
+ } = {}) => {
941
+ const [pidText, , deadlineText] = String(content).trim().split(/\s+/);
942
+ const pid = Number.parseInt(pidText, 10);
943
+ if (!(Number.isInteger(pid) && pid > 0)) return now() - mtimeMs > graceMs;
944
+ let alive = true;
945
+ try { alive = pidAlive(pid); } catch { alive = true; }
946
+ if (!alive) return true;
947
+ const deadline = Number.parseInt(deadlineText, 10);
948
+ return Number.isInteger(deadline) && deadline > 0 && now() > deadline;
949
+ };
950
+
951
+ /**
952
+ * Runs `fn({ pastDeadline })` holding the seat's turn lock, so two `agent run`
953
+ * processes of one seat (the daemon's and a foreground one) never interleave
954
+ * their HOME steps with each other's VM. The lock sits beside the HOME, in the
955
+ * host-owned seats folder the guest never mounts, as `.<seat folder>.lock`,
956
+ * reading `<pid> <token> <deadline>`. `holdMs` sets the deadline; the caller
957
+ * checks `pastDeadline()` before every HOME step and stops touching the HOME
958
+ * once it is true. A waiter reclaims the lock only as seatLockAbandoned says,
959
+ * by the guarded re-check withFileLock makes, and past `waitMs` refuses with
960
+ * `microvm_seat_busy`: it never runs unlocked.
961
+ */
962
+ export const withSeatLock = (home, fn, {
963
+ waitMs = SEAT_LOCK_WAIT_MS, holdMs = INSTALL_LOCK_MAX_MS, pollMs = 250, now = Date.now, pidAlive = defaultPidAlive,
964
+ _remove,
965
+ } = {}) => {
966
+ let deadline = 0;
967
+ return withFileLock(dirname(home), `.${basename(home)}.lock`, () => fn({ pastDeadline: () => now() > deadline }), {
968
+ waitMs,
969
+ pollMs,
970
+ now,
971
+ pidAlive,
972
+ ...(_remove ? { remove: _remove } : {}),
973
+ suffix: () => {
974
+ deadline = now() + holdMs;
975
+ return ` ${deadline}`;
976
+ },
977
+ abandoned: (content, mtimeMs) => seatLockAbandoned(content, mtimeMs, { now, pidAlive }),
978
+ busy: (lock) => Object.assign(new Error(`the microVM sandbox will not touch this seat's HOME: another turn `
979
+ + `of this seat still holds ${lock}; try again when it ends`), { code: 'microvm_seat_busy' }),
980
+ });
981
+ };
982
+
983
+ /** msb and the guest's agent (Claude unless named), ready to run a turn. */
984
+ export const prepareMicrovmHost = async ({
985
+ log, root = microsandboxRoot(), agent = 'claude',
986
+ } = {}) => withInstallLock(root, async () => {
573
987
  const msb = await ensureMsb({ root });
574
- ensureGuestClaude({ msb, root, log });
988
+ ensureGuestAgent({
989
+ agent, msb, root, log,
990
+ });
575
991
  return { msb };
576
992
  });
577
993
 
@@ -595,7 +1011,9 @@ export default {
595
1011
  buildMicrovmFence,
596
1012
  buildMicrovmRunArgs,
597
1013
  checkMicrovmAttach,
1014
+ ensureGuestAgent,
598
1015
  ensureGuestClaude,
1016
+ ensureGuestCodex,
599
1017
  ensureMsb,
600
1018
  microvmFlagOn,
601
1019
  probeWhp,