@commonlyai/cli 0.1.395 → 0.1.397

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.395",
3
+ "version": "0.1.397",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -68,6 +68,7 @@ import {
68
68
  import { catchUpBeforeTurn } from '../lib/pod-catch-up.js';
69
69
  import { readLongTerm, syncBack } from '../lib/memory-bridge.js';
70
70
  import { pollRetryPolicy } from '../lib/poll-retry.js';
71
+ import { clampHoldToLiveness, longPollWaitMs, wasHeld } from '../lib/long-poll.js';
71
72
  import {
72
73
  createIdleHeartbeat, createPollLiveness, formatStall, resolveIdleLineMs, resolvePollLivenessMs,
73
74
  } from '../lib/poll-liveness.js';
@@ -2275,6 +2276,10 @@ export const performRun = ({
2275
2276
  // How often a seat that keeps polling and finds nothing says so. Undefined
2276
2277
  // reads COMMONLY_IDLE_LINE_MS, then ten minutes (lib/poll-liveness.js).
2277
2278
  idleLineMs,
2279
+ // F597: the wait an empty inbox poll asks the server to hold it for
2280
+ // (lib/long-poll.js). Undefined derives it from the read timeout; 0 turns
2281
+ // the long-poll off. Tests pin a small value.
2282
+ longPollWaitMs: longPollWaitOverride,
2278
2283
  }) => {
2279
2284
  const stateKey = localKey || agentName;
2280
2285
  const supervising = superviseRuns ?? superviseRunsByDefault(adapter?.name);
@@ -4677,6 +4682,28 @@ export const performRun = ({
4677
4682
  // a 15-minute circuit wait otherwise stays alive until the timer fires,
4678
4683
  // which is why a walk on 2026-11-05 needed repeated signals to end it.
4679
4684
  let tickTimer = null;
4685
+ // F597: an idle seat's inbox poll is held by the server up to this long.
4686
+ // Never so long that the poll-liveness clock reads the hold as a wedge.
4687
+ const longPollWait = clampHoldToLiveness(
4688
+ longPollWaitOverride ?? longPollWaitMs(),
4689
+ resolvePollLivenessMs(pollLivenessMs),
4690
+ );
4691
+ // The held poll in flight, so stop() can end it instead of waiting it out.
4692
+ let holdAbort = null;
4693
+ const STOPPED_HOLD = Symbol('stopped-hold');
4694
+ const heldInboxPoll = async (holdMs) => {
4695
+ holdAbort = new AbortController();
4696
+ try {
4697
+ return await client.get('/api/agents/runtime/events', { ...inboxQuery(), waitMs: holdMs }, {
4698
+ signal: holdAbort.signal,
4699
+ });
4700
+ } catch (error) {
4701
+ if (!running && holdAbort.signal.aborted) return STOPPED_HOLD;
4702
+ throw error;
4703
+ } finally {
4704
+ holdAbort = null;
4705
+ }
4706
+ };
4680
4707
  let tickInFlight = false;
4681
4708
  // stop() returns this: it resolves once the hand-back has answered, whether
4682
4709
  // the idle stop or the in-flight tick's end performs it.
@@ -4721,14 +4748,26 @@ export const performRun = ({
4721
4748
  // Only wake events count: the server's page cap is on wakes, and a
4722
4749
  // carried digest row takes no body (CodeRabbit on #3511).
4723
4750
  // F237: a full carry in an outage claims nothing new (inboxQuery).
4724
- const page = await client.get('/api/agents/runtime/events', inboxQuery());
4751
+ // F597: with nothing carried, an empty inbox asks the server to hold the
4752
+ // poll (long-poll). A carry is never held: its retry runs on this tick.
4753
+ const holdMs = heldRetry.length || heldGreeting.length ? 0 : longPollWait;
4754
+ const pollStartedAt = Date.now();
4755
+ const page = holdMs > 0 ? await heldInboxPoll(holdMs) : await client.get('/api/agents/runtime/events', inboxQuery());
4725
4756
  pollLiveness.arm();
4726
4757
  // A stall fired while this request hung: the loop has already given up on
4727
4758
  // it, and `agent run` exits in onStall, so its page is left to the requeue.
4728
4759
  // A plain stop() falls through instead, to the group loop's own `running`
4729
4760
  // check, which hands the page back.
4730
4761
  if (pollStalled) return;
4762
+ // stop() ended a held poll: nothing was claimed, nothing to hand back.
4763
+ if (page === STOPPED_HOLD) return;
4731
4764
  const { events = [], inboxCount } = page;
4765
+ // An empty answer the server held: the next poll goes at once, since the
4766
+ // hold was the wait. One that came back fast (an older server that
4767
+ // ignores waitMs) keeps the ordinary interval, so the loop never spins.
4768
+ if (!events.length && wasHeld({ requestedMs: holdMs, elapsedMs: Date.now() - pollStartedAt })) {
4769
+ nextPollDelayMs = 0;
4770
+ }
4732
4771
  consecutiveAuthErrors = 0;
4733
4772
  consecutivePollFailures = 0;
4734
4773
  // A deployed CLI can briefly run against an older server that still
@@ -5301,6 +5340,8 @@ export const performRun = ({
5301
5340
  running = false;
5302
5341
  pollLiveness.stop();
5303
5342
  clearHeldRenewal();
5343
+ // A held poll would otherwise keep the stop waiting for up to its wait.
5344
+ holdAbort?.abort();
5304
5345
  if (tickTimer !== null) {
5305
5346
  clearTimeoutImpl(tickTimer);
5306
5347
  tickTimer = null;
package/src/lib/api.js CHANGED
@@ -7,6 +7,7 @@
7
7
 
8
8
  import { resolveInstanceUrl, getToken, resolveInstance } from './config.js';
9
9
  import { CLI } from './cli-hint.js';
10
+ import { capTimeoutMs } from './cap-timeout.js';
10
11
 
11
12
  const headers = (token, extra = {}) => ({
12
13
  'Content-Type': 'application/json',
@@ -65,17 +66,9 @@ const handleResponse = async (res, session = null) => {
65
66
  // (TASK-025) only handles a fetch that throws, so a timeout throws: it is an
66
67
  // ordinary failed request, retried with backoff, and never an ack.
67
68
  //
68
- // Reads get the base timeout; writes and uploads carry a body and a server-side
69
- // write, so they get a multiple of it. COMMONLY_CAP_TIMEOUT_MS sets the base.
70
- export const CAP_TIMEOUT_DEFAULT_MS = 30_000;
71
- const TIMEOUT_SCALE = { read: 1, write: 2, upload: 4 };
72
-
73
- export const capTimeoutMs = (kind, { baseMs, env = process.env } = {}) => {
74
- const fromEnv = Number(env.COMMONLY_CAP_TIMEOUT_MS);
75
- const base = [baseMs, fromEnv].find((value) => Number.isFinite(value) && value > 0)
76
- ?? CAP_TIMEOUT_DEFAULT_MS;
77
- return Math.min(base * (TIMEOUT_SCALE[kind] || 1), 2_147_483_647);
78
- };
69
+ // The numbers live in cap-timeout.js: reads get the base timeout, writes and
70
+ // uploads a multiple of it, and COMMONLY_CAP_TIMEOUT_MS sets the base.
71
+ export { CAP_TIMEOUT_DEFAULT_MS, capTimeoutMs } from './cap-timeout.js';
79
72
 
80
73
  // A caller's own signal (doctor, and the 5s identity and skills reads in the
81
74
  // run loop) still applies; the hard timeout is added beside it, never instead.
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The CAP request timeout (TASK-338), on its own so modules that only need the
3
+ * number (the long-poll's wait, lib/long-poll.js) don't import the HTTP client.
4
+ * api.js re-exports both names; see its comment for why every request has one.
5
+ *
6
+ * Reads get the base timeout; writes and uploads carry a body and a server-side
7
+ * write, so they get a multiple of it. COMMONLY_CAP_TIMEOUT_MS sets the base.
8
+ */
9
+ export const CAP_TIMEOUT_DEFAULT_MS = 30_000;
10
+ const TIMEOUT_SCALE = { read: 1, write: 2, upload: 4 };
11
+
12
+ export const capTimeoutMs = (kind, { baseMs, env = process.env } = {}) => {
13
+ const fromEnv = Number(env.COMMONLY_CAP_TIMEOUT_MS);
14
+ const base = [baseMs, fromEnv].find((value) => Number.isFinite(value) && value > 0)
15
+ ?? CAP_TIMEOUT_DEFAULT_MS;
16
+ return Math.min(base * (TIMEOUT_SCALE[kind] || 1), 2_147_483_647);
17
+ };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * F597: the events poll's long-poll (`GET /api/agents/runtime/events?waitMs=`).
3
+ *
4
+ * A current server holds an empty poll open up to `waitMs` (at most 25 s) and
5
+ * answers as soon as an event can be claimed, so an idle agent asks about once
6
+ * per 25 s instead of every ~5 s, and a new event still arrives at once.
7
+ *
8
+ * An older server ignores the parameter and answers an empty poll at once.
9
+ * The loop must then keep its normal interval, never spin: an empty answer
10
+ * that came back in well under the requested wait was not held, and is
11
+ * treated exactly like today's empty poll.
12
+ */
13
+ import { capTimeoutMs } from './cap-timeout.js';
14
+
15
+ export const LONG_POLL_MAX_WAIT_MS = 25_000;
16
+ // The hold must end, and its answer arrive, before the request's own timeout.
17
+ export const LONG_POLL_TIMEOUT_MARGIN_MS = 5_000;
18
+ // Below this the hold buys nothing over the ordinary interval.
19
+ const LONG_POLL_MIN_WAIT_MS = 1_000;
20
+
21
+ /** The wait to ask for: 0 (no long-poll) when the read timeout leaves no room. */
22
+ export const longPollWaitMs = ({ env = process.env } = {}) => {
23
+ const room = capTimeoutMs('read', { env }) - LONG_POLL_TIMEOUT_MARGIN_MS;
24
+ const wait = Math.min(LONG_POLL_MAX_WAIT_MS, room);
25
+ return wait >= LONG_POLL_MIN_WAIT_MS ? wait : 0;
26
+ };
27
+
28
+ /**
29
+ * The hold a loop may ask for under its poll-liveness limit
30
+ * (lib/poll-liveness.js): the liveness clock runs while the poll is in flight,
31
+ * so a hold near the limit would read as a wedged loop and stop the run. The
32
+ * hold ends a margin before the limit (5 s or a quarter of it, whichever is
33
+ * larger); if what is left is under LONG_POLL_MIN_LIVENESS_HOLD_MS, no hold.
34
+ */
35
+ export const LONG_POLL_MIN_LIVENESS_HOLD_MS = 3_000;
36
+ export const clampHoldToLiveness = (holdMs, livenessMs) => {
37
+ if (!(holdMs > 0)) return 0;
38
+ if (!Number.isFinite(livenessMs) || livenessMs <= 0) return holdMs;
39
+ const room = Math.floor(livenessMs - Math.max(5_000, livenessMs / 4));
40
+ return room >= LONG_POLL_MIN_LIVENESS_HOLD_MS ? Math.min(holdMs, room) : 0;
41
+ };
42
+
43
+ /**
44
+ * Whether an empty answer was a held one, so the next poll can go at once.
45
+ * Half the requested wait is the line: an old server answers in milliseconds,
46
+ * a held poll that timed out answers at about the full wait.
47
+ */
48
+ export const wasHeld = ({ requestedMs, elapsedMs }) => (
49
+ requestedMs > 0 && elapsedMs >= requestedMs / 2
50
+ );
package/src/lib/poller.js CHANGED
@@ -11,6 +11,7 @@ import { formatDigestFrame } from './digest-frame.js';
11
11
  import { EMPTY_OUTPUT } from './claim-outcome.js';
12
12
  import { createPollLiveness, formatStall, resolvePollLivenessMs } from './poll-liveness.js';
13
13
  import { CLI } from './cli-hint.js';
14
+ import { clampHoldToLiveness, longPollWaitMs as defaultLongPollWaitMs, wasHeld } from './long-poll.js';
14
15
 
15
16
  // Delivery failures that must stop a consumer rather than fall through to the
16
17
  // normal at-least-once retry path. A stale delivery belongs to a replacement
@@ -44,6 +45,9 @@ export const startPoller = ({
44
45
  pollLivenessMs, // TASK-338: see lib/poll-liveness.js
45
46
  pollLivenessCheckMs,
46
47
  onPollStalled, // ({ stalledMs }) => void; the connect command exits on it
48
+ // F597: how long an empty poll asks the server to hold it (lib/long-poll.js).
49
+ // Undefined derives it from the read timeout; 0 turns the long-poll off.
50
+ longPollWaitMs,
47
51
  }) => {
48
52
  const client = createClient({ instance: instanceUrl, token });
49
53
  let running = true;
@@ -55,6 +59,10 @@ export const startPoller = ({
55
59
  let consecutiveAuthErrors = 0;
56
60
  const MAX_AUTH_ERRORS = 3;
57
61
  let pollStalled = false;
62
+ // Never so long that the poll-liveness clock reads the hold as a wedge.
63
+ const holdMs = clampHoldToLiveness(longPollWaitMs ?? defaultLongPollWaitMs(), resolvePollLivenessMs(pollLivenessMs));
64
+ // The poll in flight, so stop() ends a held one instead of waiting it out.
65
+ let pollAbort = null;
58
66
  const pollLiveness = createPollLiveness({
59
67
  limitMs: resolvePollLivenessMs(pollLivenessMs),
60
68
  checkEveryMs: pollLivenessCheckMs,
@@ -68,21 +76,41 @@ export const startPoller = ({
68
76
  },
69
77
  });
70
78
 
79
+ let nextDelayMs = intervalMs;
71
80
  const poll = async () => {
72
81
  if (!running) return;
82
+ nextDelayMs = intervalMs;
73
83
 
74
84
  try {
75
85
  // Same clock as `agent run`: running from here to the scheduled wait,
76
86
  // paused while the local handler takes the event.
77
87
  pollLiveness.arm();
78
- const page = await client.get('/api/agents/runtime/events', {
79
- agentName,
80
- instanceId,
81
- limit: 10,
82
- });
88
+ pollAbort = new AbortController();
89
+ const pollStartedAt = Date.now();
90
+ let page;
91
+ try {
92
+ page = await client.get('/api/agents/runtime/events', {
93
+ agentName,
94
+ instanceId,
95
+ limit: 10,
96
+ ...(holdMs > 0 ? { waitMs: holdMs } : {}),
97
+ }, { signal: pollAbort.signal });
98
+ } catch (pollErr) {
99
+ // stop() ended a held poll: not a failure, and nothing was claimed.
100
+ if (!running && pollAbort.signal.aborted) return;
101
+ throw pollErr;
102
+ } finally {
103
+ pollAbort = null;
104
+ }
83
105
  pollLiveness.arm();
84
106
  if (pollStalled) return;
85
107
  const { events = [] } = page;
108
+ // An empty answer the server held (F597): poll again at once, the hold
109
+ // was the wait. A fast empty answer (an older server ignores waitMs)
110
+ // keeps the ordinary interval, so the loop never spins.
111
+ nextDelayMs = !events.length && wasHeld({ requestedMs: holdMs, elapsedMs: Date.now() - pollStartedAt })
112
+ ? 0
113
+ : intervalMs;
86
114
 
87
115
  // A digest is received context, not a webhook invocation. The runtime
88
116
  // inbox claims it only alongside a wake from the same pod.
@@ -185,7 +213,7 @@ export const startPoller = ({
185
213
  }
186
214
 
187
215
  pollLiveness.pause();
188
- if (running) setTimeout(poll, intervalMs);
216
+ if (running) setTimeout(poll, nextDelayMs);
189
217
  };
190
218
 
191
219
  // Start immediately
@@ -195,6 +223,7 @@ export const startPoller = ({
195
223
  stop: () => {
196
224
  running = false;
197
225
  pollLiveness.stop();
226
+ pollAbort?.abort();
198
227
  },
199
228
  };
200
229
  };
@@ -137,7 +137,13 @@ export const startMcpBridge = async ({
137
137
  return;
138
138
  }
139
139
  children.add(child);
140
- child.on('error', () => socket.destroy());
140
+ // A spawn that fails (a missing command) emits 'error' with no pid and
141
+ // never 'exit', so it frees its session slot here. A running child that
142
+ // errors keeps its slot until it exits.
143
+ child.on('error', () => {
144
+ if (child.pid === undefined) children.delete(child);
145
+ socket.destroy();
146
+ });
141
147
  child.on('exit', () => { children.delete(child); socket.end(); });
142
148
  child.stdin.on('error', () => {});
143
149
  if (rest.length) child.stdin.write(rest);
@@ -31,7 +31,7 @@ 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, readdir, rename, rm, stat, writeFile,
34
+ chmod, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile,
35
35
  } from 'fs/promises';
36
36
  import { homedir, tmpdir } from 'os';
37
37
  import { join } from 'path';
@@ -201,11 +201,14 @@ const defaultExtract = (archive, dir, env = process.env) => spawnSync(
201
201
  * first time. A hash mismatch, a failed download or an archive without msb.exe
202
202
  * refuses and leaves nothing runnable behind.
203
203
  */
204
+ export const MSB_DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;
205
+
204
206
  export const ensureMsb = async ({
205
207
  root = microsandboxRoot(),
206
208
  asset = msbAsset(),
207
209
  fetchImpl = globalThis.fetch,
208
210
  extract = defaultExtract,
211
+ timeoutMs = MSB_DOWNLOAD_TIMEOUT_MS,
209
212
  } = {}) => {
210
213
  const binary = join(root, 'msb.exe');
211
214
  const marker = join(root, '.verified');
@@ -221,9 +224,19 @@ export const ensureMsb = async ({
221
224
  const archive = join(root, `.download-${tag}.zip`);
222
225
  const staging = join(root, `.staging-${tag}`);
223
226
  try {
224
- const response = await fetchImpl(msbReleaseUrl(asset), { redirect: 'follow' });
225
- if (!response?.ok) throw new Error(`downloading microsandbox ${MSB_PIN.version} failed (HTTP ${response?.status})`);
226
- const bytes = Buffer.from(await response.arrayBuffer());
227
+ // One deadline for the request and the body, so a stalled connection
228
+ // can't hold the install lock indefinitely.
229
+ let bytes;
230
+ try {
231
+ const response = await fetchImpl(msbReleaseUrl(asset), { redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) });
232
+ if (!response?.ok) throw new Error(`downloading microsandbox ${MSB_PIN.version} failed (HTTP ${response?.status})`);
233
+ bytes = Buffer.from(await response.arrayBuffer());
234
+ } catch (error) {
235
+ if (error?.name === 'TimeoutError' || error?.name === 'AbortError') {
236
+ throw new Error(`downloading microsandbox ${MSB_PIN.version} took longer than ${Math.round(timeoutMs / 1000)} s; try again`);
237
+ }
238
+ throw error;
239
+ }
227
240
  const actual = sha256(bytes);
228
241
  if (actual !== asset.sha256) {
229
242
  throw new Error(`microsandbox ${asset.name} has SHA-256 ${actual}, not the pinned ${asset.sha256}; refusing to run it`);
@@ -430,29 +443,111 @@ export const startMicrovmTurn = async ({
430
443
  };
431
444
 
432
445
  const INSTALL_LOCK_STALE_MS = 15 * 60 * 1000;
446
+ // Longer than the slowest install can run (a 5-minute download, the volume
447
+ // probe and a 10-minute npm install), so a lock older than this was leaked by
448
+ // its holder, or names a pid since reused, and is taken over even though that
449
+ // pid is alive.
450
+ const INSTALL_LOCK_MAX_MS = 60 * 60 * 1000;
451
+
452
+ const defaultPidAlive = (pid) => {
453
+ try {
454
+ process.kill(pid, 0);
455
+ return true;
456
+ } catch (error) {
457
+ // EPERM: the process exists, owned by someone else.
458
+ return error?.code === 'EPERM';
459
+ }
460
+ };
461
+
462
+ /**
463
+ * Whether a lock whose file reads `content` can be taken over. The lock lives
464
+ * in this user's %LOCALAPPDATA%, so its holder ran on this machine: it is
465
+ * abandoned once that process is gone, and a slow install is not cut in on
466
+ * while it runs. Past INSTALL_LOCK_MAX_MS it is abandoned whatever the pid, so
467
+ * a lock a live process leaked, or one naming a reused pid, can't wedge every
468
+ * later install. A lock that names no process falls back to the shorter age.
469
+ */
470
+ const lockAbandoned = (content, mtimeMs, { now, pidAlive }) => {
471
+ const age = now() - mtimeMs;
472
+ 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;
475
+ };
476
+
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;
480
+
481
+ /**
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.
485
+ */
486
+ const withLockGuard = async (guard, fn, { now }) => {
487
+ for (;;) {
488
+ try {
489
+ // eslint-disable-next-line no-await-in-loop
490
+ await writeFile(guard, `${process.pid}\n`, { flag: 'wx' });
491
+ break;
492
+ } catch (error) {
493
+ if (error?.code !== 'EEXIST') throw error;
494
+ // eslint-disable-next-line no-await-in-loop
495
+ const held = await stat(guard).catch(() => null);
496
+ if (held && now() - held.mtimeMs > INSTALL_LOCK_GUARD_STALE_MS) {
497
+ // eslint-disable-next-line no-await-in-loop
498
+ await rm(guard, { force: true });
499
+ } else {
500
+ // eslint-disable-next-line no-await-in-loop
501
+ await new Promise((resolve) => { setTimeout(resolve, 20); });
502
+ }
503
+ }
504
+ }
505
+ try {
506
+ return await fn();
507
+ } finally {
508
+ await rm(guard, { force: true }).catch(() => {});
509
+ }
510
+ };
433
511
 
434
512
  /**
435
513
  * Runs `fn` holding this version's install lock, so two first turns never
436
514
  * unpack msb or install into the volume (mounted writable then) at once.
515
+ *
516
+ * The lock names its holder (`<pid> <token>`, the token unique to each take).
517
+ * Only an exclusive create takes it. A waiter takes over a lock whose process
518
+ * has exited, or one past INSTALL_LOCK_MAX_MS, by deleting it and trying the
519
+ * create again. Every deletion, a takeover or the holder's release, runs under
520
+ * a guard lock and re-reads the lock first, deleting only the exact lock it
521
+ * judged (same token). So a takeover can never delete a lock another waiter
522
+ * took after the judgement, and the lock's path is never free while a live
523
+ * holder's lock is displaced. The holder also removes a lock it can't read at
524
+ * all, so an unreadable lock is never left behind.
437
525
  */
438
526
  export const withInstallLock = async (root, fn, {
439
- waitMs = INSTALL_LOCK_STALE_MS, pollMs = 500, now = Date.now,
527
+ waitMs = INSTALL_LOCK_STALE_MS, pollMs = 500, now = Date.now, pidAlive = defaultPidAlive,
440
528
  } = {}) => {
441
529
  await mkdir(root, { recursive: true });
442
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`;
443
533
  const deadline = now() + waitMs;
444
534
  for (;;) {
445
535
  try {
446
536
  // eslint-disable-next-line no-await-in-loop
447
- await writeFile(lock, `${process.pid}\n`, { flag: 'wx' });
537
+ await writeFile(lock, mine, { flag: 'wx' });
448
538
  break;
449
539
  } catch (error) {
450
540
  if (error?.code !== 'EEXIST') throw error;
451
541
  // eslint-disable-next-line no-await-in-loop
452
542
  const held = await stat(lock).catch(() => null);
453
- if (held && now() - held.mtimeMs > INSTALL_LOCK_STALE_MS) {
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 })) {
454
546
  // eslint-disable-next-line no-await-in-loop
455
- await rm(lock, { force: true });
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 });
456
551
  } else if (now() > deadline) {
457
552
  throw new Error(`another turn is still installing the microVM sandbox (${lock}); try again shortly`);
458
553
  } else {
@@ -464,7 +559,12 @@ export const withInstallLock = async (root, fn, {
464
559
  try {
465
560
  return await fn();
466
561
  } finally {
467
- await rm(lock, { force: true }).catch(() => {});
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(() => {});
468
568
  }
469
569
  };
470
570