@skrr-ai/cli 0.1.214 → 0.1.215

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.
@@ -17,10 +17,21 @@ interface LockAcquireState {
17
17
  mkdirCalls: number;
18
18
  /** When it started, which is when its deadline started. */
19
19
  startedAt: number;
20
+ /** Set once it took the lock and its holder began releasing it (OSK-33430). */
21
+ releasing: boolean;
22
+ /**
23
+ * Set when that release passed its bound with an `rmdir` or `utimes` still
24
+ * pending. Unlike `abandoned`, it refuses no call and replaces no answer
25
+ * (EABANDONED delivered to proper-lockfile's mtime-refresh `stat` callback
26
+ * throws in a timer; see `trackedLockFs`). It only keeps this release a
27
+ * blocker.
28
+ */
29
+ releaseTimedOut: boolean;
20
30
  }
21
31
  export declare const __authLockTesting: {
22
32
  acquireDeadlineMs: number;
23
33
  asyncFsProbeMs: number;
34
+ releaseDeadlineMs: number;
24
35
  /**
25
36
  * The `fs` proper-lockfile uses: Node's own. Its default, graceful-fs 4.2,
26
37
  * retries EMFILE only for open, readFile, writeFile, appendFile, copyFile and
@@ -129,13 +140,16 @@ export declare function installLockExitHandlers(options?: LockExitHandlerOptions
129
140
  * Acquire the cross-process auth lock, run the body, release on `finally`.
130
141
  * Throws ELOCKED once proper-lockfile's retries are spent (about 19 s), and a
131
142
  * `TransientAuthFailure` if the acquire is still pending at
132
- * `LOCK_ACQUIRE_DEADLINE_MS` (OSK-33422).
143
+ * `LOCK_ACQUIRE_DEADLINE_MS` (OSK-33422). Returns the body's result once the
144
+ * release has answered or waited `LOCK_RELEASE_DEADLINE_MS` (OSK-33430).
133
145
  *
134
146
  * We lock a sentinel file (auth.lock) that we create/touch if missing —
135
147
  * locking the real auth.json would race with atomic-rename writes.
136
148
  *
137
149
  * @param daemonId When supplied, lock-lifecycle telemetry events are emitted:
138
- * refresh_lock_acquiring, refresh_lock_acquired, refresh_lock_released.
150
+ * refresh_lock_acquiring, refresh_lock_acquired, then refresh_lock_released
151
+ * once the release answers, or refresh_lock_release_timeout when it does not
152
+ * answer in time.
139
153
  */
140
154
  export declare function withAuthLock<T>(body: () => Promise<T>, daemonId?: string): Promise<T>;
141
155
  /**
@@ -76,6 +76,22 @@ const LOCK_MAX_RETRIES = 50;
76
76
  const LOCK_ACQUIRE_DEADLINE_MS = 60_000;
77
77
  /** How long the abandoned acquire's async file-system probe may take. */
78
78
  const LOCK_ASYNC_FS_PROBE_MS = 1_000;
79
+ /**
80
+ * OSK-33430 — the longest `withAuthLock` waits for the lock's release.
81
+ *
82
+ * Releasing is one `rmdir` of the lock directory: proper-lockfile has already
83
+ * stopped refreshing its mtime and dropped the lock from its table. If that
84
+ * call never answers, the body has finished (for a refresh, the rotated token
85
+ * is already saved) and the caller would wait forever with nothing logged.
86
+ * Past this bound it returns, and `refresh_lock_release_timeout` names the
87
+ * pending call. 10 s is far above a working `rmdir`.
88
+ *
89
+ * What the bound cannot do: recall that `rmdir`. Another process takes the
90
+ * directory over once it is stale (`LOCK_STALE_MS` after its last refresh),
91
+ * and if the stuck call lands after that, it removes the other process's lock.
92
+ * That was as true while the caller hung; the timeout at least says so.
93
+ */
94
+ const LOCK_RELEASE_DEADLINE_MS = 10_000;
79
95
  /**
80
96
  * Calls whose late answer can undo the next holder's lock. A stale-lock
81
97
  * `rmdir` that lands after someone else created the directory removes theirs.
@@ -94,7 +110,8 @@ const MAX_PASSED_OVER = 1;
94
110
  * Acquires run side by side, as they always did, so ordinary contention ends
95
111
  * in ELOCKED for each caller after proper-lockfile's own retries. Only an
96
112
  * acquire abandoned at its deadline with a call still pending holds new ones
97
- * back (a blocker). New callers wait for it instead of adding calls behind a
113
+ * back (a blocker), and so does a release that passed its bound with its
114
+ * `rmdir` pending (`releaseAuthLock`). New callers wait for it instead of adding calls behind a
98
115
  * stuck file system or libuv's four-thread pool, which every async fs, dns and
99
116
  * crypto call shares. On 2026-11-28 three independent acquires (started
100
117
  * 16:07:00, 16:30:06 and 16:41:02, before this existed) all stayed pending,
@@ -137,6 +154,7 @@ const probeStats = new Map();
137
154
  export const __authLockTesting = {
138
155
  acquireDeadlineMs: LOCK_ACQUIRE_DEADLINE_MS,
139
156
  asyncFsProbeMs: LOCK_ASYNC_FS_PROBE_MS,
157
+ releaseDeadlineMs: LOCK_RELEASE_DEADLINE_MS,
140
158
  fs,
141
159
  lockPaths,
142
160
  probes: probeStats,
@@ -147,6 +165,10 @@ function abandonedError(op) {
147
165
  code: 'EABANDONED',
148
166
  });
149
167
  }
168
+ /** What a released lock's in-flight mtime-refresh `stat` answers (`trackedLockFs`). */
169
+ function releasedLockGoneError() {
170
+ return Object.assign(new Error('ENOENT: the auth lock was released'), { code: 'ENOENT' });
171
+ }
150
172
  /**
151
173
  * The `fs` proper-lockfile uses, with every callback-style call recorded in
152
174
  * `state.pending` until its callback runs. Synchronous calls pass straight
@@ -203,6 +225,17 @@ function trackedLockFs(base, state, onPendingChange) {
203
225
  answer(abandonedError(op));
204
226
  return;
205
227
  }
228
+ // Once the release has begun, the only `stat` left is an mtime
229
+ // refresh that was in flight, and proper-lockfile's callback for it
230
+ // does not check that the lock was released: any error but ENOENT
231
+ // re-arms a refresh for a lock no longer in its table (a TypeError
232
+ // in a timer), and a success issues a `utimes` on a directory that
233
+ // may already be another holder's. ENOENT ends it as compromised,
234
+ // which `onLockCompromised` logs at debug.
235
+ if (state.releasing && op === 'stat') {
236
+ answer(releasedLockGoneError());
237
+ return;
238
+ }
206
239
  answer(...result);
207
240
  };
208
241
  try {
@@ -305,6 +338,7 @@ async function acquireAuthLock(lockPath, daemonId) {
305
338
  asyncFs: outcome.asyncFs,
306
339
  passedOver: outcome.passedOver,
307
340
  waitedBehindEarlier: true,
341
+ blockerReleasing: outcome.blockerReleasing,
308
342
  acquireDeadlineMs,
309
343
  asyncFsProbeMs,
310
344
  });
@@ -316,9 +350,13 @@ async function acquireAuthLock(lockPath, daemonId) {
316
350
  abandoned: false,
317
351
  mkdirCalls: 0,
318
352
  startedAt: Date.now(),
353
+ releasing: false,
354
+ releaseTimedOut: false,
319
355
  };
320
356
  const acquiring = lockfile.lock(lockPath, {
321
357
  stale: LOCK_STALE_MS,
358
+ // proper-lockfile's default throws, in a timer, which ends the process.
359
+ onCompromised: (err) => onLockCompromised(err, state, lockPath, daemonId),
322
360
  retries: {
323
361
  retries: LOCK_MAX_RETRIES,
324
362
  minTimeout: LOCK_RETRY_MS,
@@ -332,6 +370,8 @@ async function acquireAuthLock(lockPath, daemonId) {
332
370
  fs: trackedLockFs(baseFs, state, () => {
333
371
  if (state.abandoned && state.pending.size === 0)
334
372
  clearBlocker(pathState, state);
373
+ else if (state.releaseTimedOut && !hasUnsafePendingCall(state))
374
+ clearBlocker(pathState, state);
335
375
  }),
336
376
  });
337
377
  // An abandoned acquire's leftover retries end in a rejection nobody awaits.
@@ -348,8 +388,10 @@ async function acquireAuthLock(lockPath, daemonId) {
348
388
  finally {
349
389
  clearTimeout(timer);
350
390
  }
351
- if (result !== 'deadline')
352
- return result;
391
+ if (result !== 'deadline') {
392
+ const release = result;
393
+ return () => releaseAuthLock(release, { lockPath, daemonId, state, pathState });
394
+ }
353
395
  state.abandoned = true;
354
396
  const waitedMs = Date.now() - arrivedAt;
355
397
  const pending = describePendingCalls(state.pending, Date.now());
@@ -371,10 +413,119 @@ async function acquireAuthLock(lockPath, daemonId) {
371
413
  asyncFs,
372
414
  passedOver: pathState.blockers.has(state) ? passedOverCalls(pathState) : null,
373
415
  waitedBehindEarlier: false,
416
+ blockerReleasing: false,
374
417
  acquireDeadlineMs,
375
418
  asyncFsProbeMs,
376
419
  });
377
420
  }
421
+ /** Whether a call whose late answer can undo the next holder's lock is still pending. */
422
+ function hasUnsafePendingCall(state) {
423
+ return [...state.pending].some((call) => CALLS_UNSAFE_TO_OUTLIVE.has(call.op));
424
+ }
425
+ /**
426
+ * Releases the lock, or returns `'timed_out'` once
427
+ * `__authLockTesting.releaseDeadlineMs` has passed with its `rmdir` (or an
428
+ * mtime-refresh `utimes`) still pending (OSK-33430), emitting
429
+ * `refresh_lock_release_timeout` with the pending calls. A release that fails
430
+ * before the bound rejects, as before.
431
+ *
432
+ * It never removes the directory a second time: a removal queued behind stuck
433
+ * calls can land after another holder has taken the directory over. The
434
+ * pending `rmdir` can land late too, and cannot be recalled, so until it (and
435
+ * any pending `utimes`) answers, this release holds new acquires in this
436
+ * process back, as an abandoned acquire with such a call does (`lockPaths`,
437
+ * `CALLS_UNSAFE_TO_OUTLIVE`): one that took the directory over would lose it
438
+ * to that late removal. Every late answer reaches proper-lockfile unchanged
439
+ * (see `releaseTimedOut`), and nothing awaits the release's own.
440
+ */
441
+ async function releaseAuthLock(release, options) {
442
+ const { lockPath, daemonId, state, pathState } = options;
443
+ const { releaseDeadlineMs } = __authLockTesting;
444
+ const startedAt = Date.now();
445
+ state.releasing = true;
446
+ const releasing = release();
447
+ // After the bound, its answer has no reader.
448
+ void releasing.catch(() => undefined);
449
+ // Not unref'd, like the acquire deadline: a CLI must not exit mid-release.
450
+ let timer;
451
+ const deadline = new Promise((resolve) => {
452
+ timer = setTimeout(() => resolve('deadline'), releaseDeadlineMs);
453
+ });
454
+ let result;
455
+ try {
456
+ result = await Promise.race([releasing.then(() => 'released'), deadline]);
457
+ }
458
+ finally {
459
+ clearTimeout(timer);
460
+ }
461
+ if (result === 'released')
462
+ return 'released';
463
+ // Its rmdir answered as the bound passed: the release is completing, and a
464
+ // pending mtime-refresh `stat` holds nobody back.
465
+ if (!hasUnsafePendingCall(state))
466
+ return 'released';
467
+ state.releaseTimedOut = true;
468
+ pathState.blockers.add(state);
469
+ const waitedMs = Date.now() - startedAt;
470
+ const { calls, text } = describePendingCalls(state.pending, Date.now());
471
+ emitAuthTelemetry({
472
+ timestamp: new Date().toISOString(),
473
+ eventType: 'auth',
474
+ success: false,
475
+ metadata: {
476
+ event: 'refresh_lock_release_timeout',
477
+ waitedMs,
478
+ pendingFsCalls: calls,
479
+ ...(daemonId ? { daemonId } : {}),
480
+ },
481
+ });
482
+ getAuthLogger().warn(`[auth/refresh] The auth lock (${path.basename(lockPath)}) was not released within ` +
483
+ `${formatLockWait(releaseDeadlineMs)}. Pending file-system calls: ${text}. The caller ` +
484
+ 'went on without waiting, the lock directory is not removed again, and new acquires in ' +
485
+ 'this process wait until that call answers. Another process takes the lock over once it ' +
486
+ 'is stale, and the pending call can still remove its lock if it lands after that.');
487
+ return 'timed_out';
488
+ }
489
+ /**
490
+ * proper-lockfile's `onCompromised`: the lock directory vanished, or its mtime
491
+ * stopped being ours, while the lock was held or being released. Its default
492
+ * throws in a timer and ends the process, which loses whatever the body was
493
+ * doing (a rotated token not yet saved signs the account out). Logged instead.
494
+ * Once the release has begun, the lock is no longer ours to lose: a late
495
+ * mtime-refresh answer that finds the directory gone is expected.
496
+ */
497
+ function onLockCompromised(err, state, lockPath, daemonId) {
498
+ const lockFile = path.basename(lockPath);
499
+ // Words, not `err.message`: an ENOENT message carries the full path.
500
+ const message = String(err?.message ?? '');
501
+ let cause = 'refresh_failed';
502
+ if (message.startsWith('ENOENT'))
503
+ cause = 'removed';
504
+ else if (message.includes('stale threshold'))
505
+ cause = 'taken_over';
506
+ if (state.releasing) {
507
+ getAuthLogger().debug(`[auth/refresh] The auth lock (${lockFile}) read as compromised (${cause}) after its ` +
508
+ 'release began.');
509
+ return;
510
+ }
511
+ const what = {
512
+ removed: 'its directory was removed',
513
+ taken_over: 'its mtime changed, so another process took it over',
514
+ refresh_failed: 'its mtime could not be refreshed within the stale threshold',
515
+ }[cause];
516
+ getAuthLogger().warn(`[auth/refresh] The auth lock (${lockFile}) was lost while held: ${what}. The holder ` +
517
+ 'goes on; another process may hold the lock now.');
518
+ emitAuthTelemetry({
519
+ timestamp: new Date().toISOString(),
520
+ eventType: 'auth',
521
+ success: false,
522
+ metadata: {
523
+ event: 'refresh_lock_compromised',
524
+ cause,
525
+ ...(daemonId ? { daemonId } : {}),
526
+ },
527
+ });
528
+ }
378
529
  /** Forgets an abandoned acquire whose last pending call has answered. */
379
530
  function clearBlocker(pathState, state) {
380
531
  pathState.passedOver.delete(state);
@@ -434,6 +585,7 @@ function waitForBlockers(pathState, deadlineMs, probe) {
434
585
  const [oldest] = pathState.blockers;
435
586
  resolve({
436
587
  pending: describePendingCalls(oldest?.pending ?? new Set(), Date.now()),
588
+ blockerReleasing: oldest?.releasing ?? false,
437
589
  asyncFs,
438
590
  passedOver: passedOverCalls(pathState),
439
591
  });
@@ -467,6 +619,7 @@ function lockAcquireTimeout(options) {
467
619
  queuedMs: options.queuedMs,
468
620
  mkdirCalls,
469
621
  waitedBehindEarlier,
622
+ waitedBehindRelease: waitedBehindEarlier && options.blockerReleasing,
470
623
  pendingFsCalls: calls,
471
624
  asyncFsProbe: asyncFs?.result ?? 'not_run',
472
625
  asyncFsProbeReused: asyncFs ? asyncFs.reusedAfterMs !== null : false,
@@ -483,7 +636,8 @@ function lockAcquireTimeout(options) {
483
636
  : '';
484
637
  const message = waitedBehindEarlier
485
638
  ? `The auth lock (${lockFile}) was not acquired: it waited ${formatLockWait(options.waitedMs)} ` +
486
- `behind an earlier acquire in this process, which is still waiting on ` +
639
+ `behind an earlier ${options.blockerReleasing ? 'release' : 'acquire'} in this process, ` +
640
+ 'which is still waiting on ' +
487
641
  `${text || 'no file-system call'}${probeText}.${passedOverText}`
488
642
  : `The auth lock (${lockFile}) was not acquired within ${formatLockWait(options.acquireDeadlineMs)} ` +
489
643
  `(${mkdirCalls} mkdir call${mkdirCalls === 1 ? '' : 's'} on the lock directory). ` +
@@ -686,13 +840,16 @@ export function installLockExitHandlers(options = {}) {
686
840
  * Acquire the cross-process auth lock, run the body, release on `finally`.
687
841
  * Throws ELOCKED once proper-lockfile's retries are spent (about 19 s), and a
688
842
  * `TransientAuthFailure` if the acquire is still pending at
689
- * `LOCK_ACQUIRE_DEADLINE_MS` (OSK-33422).
843
+ * `LOCK_ACQUIRE_DEADLINE_MS` (OSK-33422). Returns the body's result once the
844
+ * release has answered or waited `LOCK_RELEASE_DEADLINE_MS` (OSK-33430).
690
845
  *
691
846
  * We lock a sentinel file (auth.lock) that we create/touch if missing —
692
847
  * locking the real auth.json would race with atomic-rename writes.
693
848
  *
694
849
  * @param daemonId When supplied, lock-lifecycle telemetry events are emitted:
695
- * refresh_lock_acquiring, refresh_lock_acquired, refresh_lock_released.
850
+ * refresh_lock_acquiring, refresh_lock_acquired, then refresh_lock_released
851
+ * once the release answers, or refresh_lock_release_timeout when it does not
852
+ * answer in time.
696
853
  */
697
854
  export async function withAuthLock(body, daemonId) {
698
855
  // D-4 — Re-entrancy guard. If the current async context already holds
@@ -737,22 +894,27 @@ export async function withAuthLock(body, daemonId) {
737
894
  }
738
895
  finally {
739
896
  const heldForMs = Date.now() - acquiredAt;
740
- emitAuthTelemetry({
741
- timestamp: new Date().toISOString(),
742
- eventType: 'auth',
743
- success: true,
744
- metadata: {
745
- event: 'refresh_lock_released',
746
- heldForMs,
747
- ...(daemonId ? { daemonId } : {}),
748
- },
749
- });
897
+ // Emitted once the release has answered, so a release that passed its
898
+ // bound reads `refresh_lock_release_timeout` and never `released` too.
899
+ let outcome = 'released';
750
900
  try {
751
- await release();
901
+ outcome = await release();
752
902
  }
753
903
  catch (err) {
754
904
  getAuthLogger().debug(`[auth/refresh] lock release failed: ${err?.message}`);
755
905
  }
906
+ if (outcome === 'released') {
907
+ emitAuthTelemetry({
908
+ timestamp: new Date().toISOString(),
909
+ eventType: 'auth',
910
+ success: true,
911
+ metadata: {
912
+ event: 'refresh_lock_released',
913
+ heldForMs,
914
+ ...(daemonId ? { daemonId } : {}),
915
+ },
916
+ });
917
+ }
756
918
  }
757
919
  });
758
920
  }
@@ -27,12 +27,17 @@ export interface AuthKillSwitches {
27
27
  * refresh_lock_acquiring — {daemonId}
28
28
  * refresh_lock_acquired — {daemonId, waitedMs}
29
29
  * refresh_lock_retry — {daemonId, attempt, errorCode}
30
- * refresh_lock_released — {daemonId, heldForMs}
30
+ * refresh_lock_released — {daemonId, heldForMs} (after the release answers)
31
31
  * refresh_lock_acquire_timeout — {daemonId, waitedMs, queuedMs, mkdirCalls,
32
- * waitedBehindEarlier, pendingFsCalls: [{op, file?,
32
+ * waitedBehindEarlier, waitedBehindRelease,
33
+ * pendingFsCalls: [{op, file?,
33
34
  * pendingMs}], asyncFsProbe: answered|failed|no_answer|
34
35
  * not_run, asyncFsProbeReused: boolean,
35
36
  * passedOverPendingFsCalls: [{op, file?, pendingMs}]}
37
+ * refresh_lock_release_timeout — {daemonId, waitedMs, pendingFsCalls: [{op,
38
+ * file?, pendingMs}]} (OSK-33430)
39
+ * refresh_lock_compromised — {daemonId, cause: removed|taken_over|refresh_failed}
40
+ * (the lock was lost while held)
36
41
  * refresh_race_resolved — {daemonId, sourceTokenAdopted: boolean}
37
42
  */
38
43
  export interface AuthTelemetryEvent {