@skrr-ai/cli 0.1.211 → 0.1.213

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.
@@ -12,16 +12,22 @@ export const MANAGED_WORK_ACP_MANAGER = 'managed_work_acp_manager_v1';
12
12
  export const MANAGED_WORK_ACP_WORKER = 'managed_work_acp_worker_v1';
13
13
  export const MANAGED_WORK_ACP_RECORDS = 'managed_work_acp_task_records_v1';
14
14
  /**
15
- * `taskCoordinator` marks an adapter that can run a Task coordinator turn: the `task_coordinator`
16
- * interaction role with NO tool offered to the model. An adapter without it is refused the role by
17
- * the server and by the daemon, and the caller sends the platform's template instead. The
18
- * first-party ACP engine accepts a closed list of manager roles that does not hold this one, so it
19
- * stays unmarked until a release of the engine does.
15
+ * The interaction roles in which the model is offered NO tool and answers once: a Task coordinator
16
+ * turn (`task_coordinator`) and a glance at a message beside running work (`chat_glance`). Neither
17
+ * is implied by the manager profile an adapter enforces, so each adapter names the ones it runs
18
+ * (`answerOnlyRoles`). An adapter that does not name a role is refused it by the server and by the
19
+ * daemon, and the caller falls back: a coordinator to the platform's template, a glance to a cloud
20
+ * reply when its owner allowed one, otherwise the message is held until the work ends.
21
+ *
22
+ * The first-party ACP engine names none. Its manager profile is a closed role enum, which in
23
+ * 0.1.0-rc.13 is `main_manager`, `task_reporter` and `task_discussion`, so it rejects both of these
24
+ * before its model runs. Add a role here only with an engine release whose enum holds it.
20
25
  */
26
+ export const MANAGED_WORK_ANSWER_ONLY_ROLES = ['task_coordinator', 'chat_glance'];
21
27
  const adapters = {
22
28
  claude: {
23
29
  engine: 'sdk',
24
- taskCoordinator: true,
30
+ answerOnlyRoles: MANAGED_WORK_ANSWER_ONLY_ROLES,
25
31
  manager: ['native_interaction_profiles_v1', 'sdk_pre_tool_use_exact_allowlist'],
26
32
  worker: ['native_task_work_controls_v1', 'sdk_pre_tool_use_task_work_controls'],
27
33
  taskRecords: [
@@ -38,7 +44,7 @@ const adapters = {
38
44
  },
39
45
  codex: {
40
46
  engine: 'app-server',
41
- taskCoordinator: true,
47
+ answerOnlyRoles: MANAGED_WORK_ANSWER_ONLY_ROLES,
42
48
  freshSession: true,
43
49
  toolTransport: 'daemon_rpc',
44
50
  manager: ['managed_work_codex_manager_v1', 'app_server_scoped_dynamic_tools'],
@@ -47,7 +53,7 @@ const adapters = {
47
53
  },
48
54
  pi: {
49
55
  engine: 'rpc',
50
- taskCoordinator: true,
56
+ answerOnlyRoles: MANAGED_WORK_ANSWER_ONLY_ROLES,
51
57
  freshSession: true,
52
58
  toolTransport: 'daemon_rpc',
53
59
  manager: ['managed_work_pi_manager_v1', 'pi_rpc_exact_tool_scope'],
@@ -63,10 +69,20 @@ export function managedWorkAdapter(provider) {
63
69
  : canonicalHarnessProvider(provider);
64
70
  return Object.hasOwn(adapters, name) ? adapters[name] : undefined;
65
71
  }
72
+ /** Whether this harness can run `role`, one of the answer-only roles, with no tool offered to its model. */
73
+ export function managedWorkSupportsAnswerOnlyRole(provider, role) {
74
+ const adapter = managedWorkAdapter(provider);
75
+ if (!adapter || !('answerOnlyRoles' in adapter))
76
+ return false;
77
+ return adapter.answerOnlyRoles.includes(role);
78
+ }
66
79
  /** Whether this harness can run a Task coordinator turn with no tool offered to its model. */
67
80
  export function managedWorkSupportsTaskCoordinator(provider) {
68
- const adapter = managedWorkAdapter(provider);
69
- return Boolean(adapter && 'taskCoordinator' in adapter);
81
+ return managedWorkSupportsAnswerOnlyRole(provider, 'task_coordinator');
82
+ }
83
+ /** Whether this harness can run a glance (`chat_glance`) with no tool offered to its model. */
84
+ export function managedWorkSupportsChatGlance(provider) {
85
+ return managedWorkSupportsAnswerOnlyRole(provider, 'chat_glance');
70
86
  }
71
87
  export function managedWorkCapabilities(provider) {
72
88
  const adapter = managedWorkAdapter(provider);
@@ -1,4 +1,42 @@
1
+ import fs from 'node:fs';
1
2
  import { type ReauthState, type TokenPair } from './types.js';
3
+ interface PendingLockFsCall {
4
+ op: string;
5
+ path?: string;
6
+ startedAt: number;
7
+ }
8
+ interface LockAcquireState {
9
+ /** Callback-style calls proper-lockfile made whose callback has not run. */
10
+ pending: Set<PendingLockFsCall>;
11
+ /** Set when the deadline passes; from then on it makes no file-system call. */
12
+ abandoned: boolean;
13
+ /**
14
+ * mkdir calls of the lock directory: one per retry attempt, plus one more
15
+ * inside an attempt after a stale takeover or a stat that found no directory.
16
+ */
17
+ mkdirCalls: number;
18
+ /** When it started, which is when its deadline started. */
19
+ startedAt: number;
20
+ }
21
+ export declare const __authLockTesting: {
22
+ acquireDeadlineMs: number;
23
+ asyncFsProbeMs: number;
24
+ /**
25
+ * The `fs` proper-lockfile uses: Node's own. Its default, graceful-fs 4.2,
26
+ * retries EMFILE only for open, readFile, writeFile, appendFile, copyFile and
27
+ * readdir, none of which it calls; for realpath, mkdir, stat, utimes and
28
+ * rmdir graceful-fs changes only how `stat` reports a negative uid or gid.
29
+ */
30
+ fs: typeof fs;
31
+ lockPaths: Map<string, {
32
+ blockers: Set<unknown>;
33
+ passedOver: Set<unknown>;
34
+ waiters: Set<unknown>;
35
+ }>;
36
+ probes: Map<string, unknown>;
37
+ /** The wrapper every proper-lockfile call goes through (`trackedLockFs`). */
38
+ trackFs(base: typeof fs, state: LockAcquireState, onPendingChange: () => void): typeof fs;
39
+ };
2
40
  declare function authLockPath(): string;
3
41
  declare function reauthFlagPath(): string;
4
42
  /**
@@ -89,8 +127,9 @@ export interface LockExitHandlerOptions {
89
127
  export declare function installLockExitHandlers(options?: LockExitHandlerOptions): void;
90
128
  /**
91
129
  * Acquire the cross-process auth lock, run the body, release on `finally`.
92
- * Throws if the lock can't be acquired within
93
- * `LOCK_MAX_RETRIES × LOCK_RETRY_MS`.
130
+ * Throws ELOCKED once proper-lockfile's retries are spent (about 19 s), and a
131
+ * `TransientAuthFailure` if the acquire is still pending at
132
+ * `LOCK_ACQUIRE_DEADLINE_MS` (OSK-33422).
94
133
  *
95
134
  * We lock a sentinel file (auth.lock) that we create/touch if missing —
96
135
  * locking the real auth.json would race with atomic-rename writes.
@@ -25,7 +25,7 @@ import fs from 'node:fs';
25
25
  import path from 'node:path';
26
26
  import lockfile from 'proper-lockfile';
27
27
  import { getAuthLogger, getAuthConfigDir, emitAuthTelemetry, notifyResponseObserver, } from './runtime.js';
28
- import { rethrowIfLiveStateRefusal } from './liveState.js';
28
+ import { assertMayMutateLiveState, rethrowIfLiveStateRefusal } from './liveState.js';
29
29
  import { permanentReasonForRefreshCode } from './refreshClassification.js';
30
30
  import { ensureStateDir, removeStateFile, writeStateFile } from './stateFiles.js';
31
31
  import { PermanentAuthFailure, TransientAuthFailure, } from './types.js';
@@ -42,7 +42,456 @@ const REVOKE_DAEMON_REFRESH_SESSION_REPORTED_RE = /\/+$/;
42
42
  */
43
43
  const LOCK_STALE_MS = 5_000;
44
44
  const LOCK_RETRY_MS = 100;
45
- const LOCK_MAX_RETRIES = 50; // ~5 s total wait before giving up
45
+ // 100, 150, 225, 338 ms, then 400 ms for the rest: about 19 s of retrying
46
+ // before proper-lockfile gives up with ELOCKED.
47
+ const LOCK_MAX_RETRIES = 50;
48
+ /**
49
+ * OSK-33422 — the longest `withAuthLock` waits for the lock itself.
50
+ *
51
+ * proper-lockfile's retries give up in about 19 s, but only once each of its
52
+ * file-system calls has answered. Measured on a launchd daemon, twice: the
53
+ * acquire for a proactive refresh stayed pending for 35 and 65 minutes while
54
+ * the process's main thread and timers kept running, and settled seconds after
55
+ * the next user input. The token expired meanwhile, and the Duty Run that
56
+ * needed a fresh one never started and was held for review. Nothing was
57
+ * logged, because nothing had failed.
58
+ *
59
+ * Past this deadline the acquire is abandoned and the caller gets a
60
+ * `TransientAuthFailure` naming the file-system calls still pending, how many
61
+ * times it called mkdir on the lock directory, and, when a call is pending,
62
+ * whether a fresh async `stat` of the auth config directory answers. That says
63
+ * which call was stuck the next time it happens. A caller that gave up while
64
+ * waiting behind a stuck acquire (see `lockPaths`) names that acquire's pending
65
+ * calls instead. Either also names the calls of an acquire already passed over
66
+ * while one is, since no second is passed over until those answer.
67
+ *
68
+ * 60 s is above the slowest acquire that is still working. proper-lockfile's
69
+ * own budget is about 19 s of backoff plus a realpath and two calls per
70
+ * attempt (51 attempts), so it ends contention in ELOCKED first even at about
71
+ * 350 ms per call (about 55 s); a held lock is not reported as a stall. The deadline runs from when a
72
+ * caller starts its own acquire, not from when it began waiting behind a stuck
73
+ * one. (The refresh's `INFLIGHT_REAP_MS`
74
+ * timer starts inside the lock, so it does not bound this wait.)
75
+ */
76
+ const LOCK_ACQUIRE_DEADLINE_MS = 60_000;
77
+ /** How long the abandoned acquire's async file-system probe may take. */
78
+ const LOCK_ASYNC_FS_PROBE_MS = 1_000;
79
+ /**
80
+ * Calls whose late answer can undo the next holder's lock. A stale-lock
81
+ * `rmdir` that lands after someone else created the directory removes theirs.
82
+ * A `utimes` changes the mtime proper-lockfile checks its own lock by, so the
83
+ * holder's next refresh calls its lock compromised (by default, a throw in a
84
+ * timer). A late `mkdir` meets the holder's directory (EEXIST) or leaves one
85
+ * that goes stale; a late `stat` or `realpath` changes nothing.
86
+ */
87
+ const CALLS_UNSAFE_TO_OUTLIVE = new Set(['rmdir', 'utimes']);
88
+ /** How many abandoned acquires may stop holding others back with a call still pending. */
89
+ const MAX_PASSED_OVER = 1;
90
+ /**
91
+ * Per lock path in this process (OSK-33422): which abandoned acquires still
92
+ * wait on a file-system call, and who waits for them.
93
+ *
94
+ * Acquires run side by side, as they always did, so ordinary contention ends
95
+ * in ELOCKED for each caller after proper-lockfile's own retries. Only an
96
+ * 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
98
+ * stuck file system or libuv's four-thread pool, which every async fs, dns and
99
+ * crypto call shares. On 2026-11-28 three independent acquires (started
100
+ * 16:07:00, 16:30:06 and 16:41:02, before this existed) all stayed pending,
101
+ * and all completed between 17:12:09.6 and 17:12:10.7: starting more did not
102
+ * help.
103
+ *
104
+ * A blocker stops holding others back when its last pending call answers, or
105
+ * sooner when a fresh async `stat` of the auth config directory answers: the
106
+ * file system works, so its call is lost rather than stuck, and one lost
107
+ * callback must not keep the lock from this process until a restart. Two
108
+ * limits keep that safe. It stays a blocker while a call in
109
+ * `CALLS_UNSAFE_TO_OUTLIVE` is pending. And at most `MAX_PASSED_OVER` acquire
110
+ * may be passed over with a call pending: a `stat` can be answered from a
111
+ * cache while writes hang, so passing every blocker over would add one stuck
112
+ * call per deadline again.
113
+ *
114
+ * A waiter waits one deadline. Then it probes, passes blockers over where those
115
+ * rules allow, and either starts its own acquire with a full deadline or gives
116
+ * up, naming the calls the oldest blocker waits on.
117
+ *
118
+ * An abandoned acquire never registers in proper-lockfile's module-wide lock
119
+ * table (`trackedLockFs`), so passing one over cannot leave two holders there.
120
+ *
121
+ * Known limit: a passed-over acquire whose call is lost for good keeps its slot
122
+ * until the process restarts, so a second lost call on the same path then
123
+ * holds new acquires back until a restart too. That takes two lost callbacks,
124
+ * and it is the price of never stacking stuck calls on a file system that
125
+ * answers reads but not writes.
126
+ */
127
+ const lockPaths = new Map();
128
+ /**
129
+ * The async `stat` each probe races, by directory, until it settles. A probe
130
+ * that loses its race leaves its call pending, and every later probe of that
131
+ * directory reuses it until it answers: a stuck file system gets one probe
132
+ * call, never one per timeout. The cost: a probe call lost for good answers
133
+ * "no answer" for the rest of the process, so a blocker on that path stops
134
+ * holding others back only when its own pending call answers.
135
+ */
136
+ const probeStats = new Map();
137
+ export const __authLockTesting = {
138
+ acquireDeadlineMs: LOCK_ACQUIRE_DEADLINE_MS,
139
+ asyncFsProbeMs: LOCK_ASYNC_FS_PROBE_MS,
140
+ fs,
141
+ lockPaths,
142
+ probes: probeStats,
143
+ trackFs: (base, state, onPendingChange) => trackedLockFs(base, state, onPendingChange),
144
+ };
145
+ function abandonedError(op) {
146
+ return Object.assign(new Error(`The auth lock acquire was abandoned at its deadline (${op})`), {
147
+ code: 'EABANDONED',
148
+ });
149
+ }
150
+ /**
151
+ * The `fs` proper-lockfile uses, with every callback-style call recorded in
152
+ * `state.pending` until its callback runs. Synchronous calls pass straight
153
+ * through. proper-lockfile calls realpath, mkdir, stat, utimes and rmdir.
154
+ * `onPendingChange` runs whenever a call is added or answered.
155
+ *
156
+ * Once `state.abandoned` is set, the acquire makes no further file-system
157
+ * call: a new one fails at once (EABANDONED), and the answer to a call made
158
+ * before the deadline is replaced by the same failure. So it never takes the
159
+ * lock, and never starts a stale takeover of a lock someone else holds. A call
160
+ * the operating system has already accepted cannot be recalled, though: one
161
+ * stuck before the deadline still completes whenever the file system recovers.
162
+ *
163
+ * It does not clean up either. A lock directory its mkdir created stays behind
164
+ * until it is `LOCK_STALE_MS` old, as one from a crashed holder does, and the
165
+ * next acquirer takes it over then, well inside its own retry budget. Removing
166
+ * it sooner is not safe: a removal queued behind stuck calls can land after
167
+ * another holder has taken the directory over.
168
+ *
169
+ * These lock-directory writes are proper-lockfile's own, as before OSK-33422.
170
+ * `acquireAuthLock` checks the live-state boundary for them before it starts.
171
+ */
172
+ function trackedLockFs(base, state, onPendingChange) {
173
+ return new Proxy(base, {
174
+ get(target, prop, receiver) {
175
+ const value = Reflect.get(target, prop, receiver);
176
+ if (typeof value !== 'function')
177
+ return value;
178
+ return (...args) => {
179
+ const callback = args[args.length - 1];
180
+ if (typeof callback !== 'function')
181
+ return Reflect.apply(value, target, args);
182
+ const op = String(prop);
183
+ const answer = callback;
184
+ if (state.abandoned) {
185
+ process.nextTick(answer, abandonedError(op));
186
+ return undefined;
187
+ }
188
+ if (op === 'mkdir')
189
+ state.mkdirCalls += 1;
190
+ const call = {
191
+ op,
192
+ ...(typeof args[0] === 'string' ? { path: args[0] } : {}),
193
+ startedAt: Date.now(),
194
+ };
195
+ state.pending.add(call);
196
+ const settle = () => {
197
+ state.pending.delete(call);
198
+ onPendingChange();
199
+ };
200
+ args[args.length - 1] = (...result) => {
201
+ settle();
202
+ if (state.abandoned) {
203
+ answer(abandonedError(op));
204
+ return;
205
+ }
206
+ answer(...result);
207
+ };
208
+ try {
209
+ return Reflect.apply(value, target, args);
210
+ }
211
+ catch (err) {
212
+ settle();
213
+ throw err;
214
+ }
215
+ };
216
+ },
217
+ });
218
+ }
219
+ /**
220
+ * Whether an async `stat` of `dir` answers within `ms`. At most one such call is
221
+ * in flight per directory (see `probeStats`).
222
+ */
223
+ async function probeAsyncFs(base, dir, ms) {
224
+ let probe = probeStats.get(dir);
225
+ const reusedAfterMs = probe ? Date.now() - probe.startedAt : null;
226
+ if (!probe) {
227
+ const started = {
228
+ answer: base.promises.stat(dir).then(() => 'answered', () => 'failed'),
229
+ startedAt: Date.now(),
230
+ };
231
+ probeStats.set(dir, started);
232
+ void started.answer.then(() => {
233
+ if (probeStats.get(dir) === started)
234
+ probeStats.delete(dir);
235
+ });
236
+ probe = started;
237
+ }
238
+ let timer;
239
+ const noAnswer = new Promise((resolve) => {
240
+ timer = setTimeout(() => resolve('no_answer'), ms);
241
+ });
242
+ try {
243
+ return { result: await Promise.race([probe.answer, noAnswer]), reusedAfterMs };
244
+ }
245
+ finally {
246
+ clearTimeout(timer);
247
+ }
248
+ }
249
+ function asyncFsProbeText(probe, ms) {
250
+ if (probe.result === 'answered')
251
+ return 'an async stat of the auth config directory answered';
252
+ if (probe.result === 'failed')
253
+ return 'an async stat of the auth config directory failed';
254
+ return probe.reusedAfterMs === null
255
+ ? `a fresh async stat of the auth config directory did not answer within ${ms} ms`
256
+ : `an async stat of the auth config directory started ${formatLockWait(probe.reusedAfterMs)} ` +
257
+ 'ago has still not answered';
258
+ }
259
+ /**
260
+ * Pending calls, oldest first. Telemetry and the message carry a file name, not
261
+ * a path: a path under the account's home includes its user name.
262
+ */
263
+ function describePendingCalls(pending, now) {
264
+ const calls = [...pending]
265
+ .sort((a, b) => a.startedAt - b.startedAt)
266
+ .map((call) => ({
267
+ op: call.op,
268
+ ...(call.path ? { file: path.basename(call.path) } : {}),
269
+ pendingMs: now - call.startedAt,
270
+ }));
271
+ const text = calls
272
+ .map((call) => `${call.op}${call.file ? ` ${call.file}` : ''} (${call.pendingMs} ms)`)
273
+ .join(', ');
274
+ return { calls, text };
275
+ }
276
+ /**
277
+ * Take the proper-lockfile lock on `lockPath`, or throw a
278
+ * `TransientAuthFailure` once `__authLockTesting.acquireDeadlineMs` has passed
279
+ * (OSK-33422), whether this acquire was still pending or still waiting behind a
280
+ * stuck one in this process (see `lockPaths`). ELOCKED and every other refusal
281
+ * from proper-lockfile propagate unchanged.
282
+ */
283
+ async function acquireAuthLock(lockPath, daemonId) {
284
+ const { acquireDeadlineMs, asyncFsProbeMs, fs: baseFs } = __authLockTesting;
285
+ assertMayMutateLiveState(`${lockPath}.lock`, 'take the auth lock');
286
+ const arrivedAt = Date.now();
287
+ const probe = () => probeAsyncFs(baseFs, path.dirname(lockPath), asyncFsProbeMs);
288
+ const pathState = lockPaths.get(lockPath) ?? {
289
+ blockers: new Set(),
290
+ passedOver: new Set(),
291
+ waiters: new Set(),
292
+ };
293
+ lockPaths.set(lockPath, pathState);
294
+ if (pathState.blockers.size > 0) {
295
+ const outcome = await waitForBlockers(pathState, acquireDeadlineMs, probe);
296
+ if (outcome !== 'clear') {
297
+ const waitedMs = Date.now() - arrivedAt;
298
+ throw lockAcquireTimeout({
299
+ lockPath,
300
+ daemonId,
301
+ waitedMs,
302
+ queuedMs: waitedMs,
303
+ mkdirCalls: 0,
304
+ pending: outcome.pending,
305
+ asyncFs: outcome.asyncFs,
306
+ passedOver: outcome.passedOver,
307
+ waitedBehindEarlier: true,
308
+ acquireDeadlineMs,
309
+ asyncFsProbeMs,
310
+ });
311
+ }
312
+ }
313
+ // The deadline starts here, not when the caller began waiting.
314
+ const state = {
315
+ pending: new Set(),
316
+ abandoned: false,
317
+ mkdirCalls: 0,
318
+ startedAt: Date.now(),
319
+ };
320
+ const acquiring = lockfile.lock(lockPath, {
321
+ stale: LOCK_STALE_MS,
322
+ retries: {
323
+ retries: LOCK_MAX_RETRIES,
324
+ minTimeout: LOCK_RETRY_MS,
325
+ maxTimeout: LOCK_RETRY_MS * 4,
326
+ factor: 1.5,
327
+ // The deadline timer keeps a waiting CLI alive. After the deadline, an
328
+ // abandoned acquire's remaining retries (each refused without a
329
+ // file-system call) must not.
330
+ unref: true,
331
+ },
332
+ fs: trackedLockFs(baseFs, state, () => {
333
+ if (state.abandoned && state.pending.size === 0)
334
+ clearBlocker(pathState, state);
335
+ }),
336
+ });
337
+ // An abandoned acquire's leftover retries end in a rejection nobody awaits.
338
+ void acquiring.catch(() => undefined);
339
+ // Not unref'd: a CLI awaiting the lock must not exit silently mid-wait.
340
+ let timer;
341
+ const deadline = new Promise((resolve) => {
342
+ timer = setTimeout(() => resolve('deadline'), acquireDeadlineMs);
343
+ });
344
+ let result;
345
+ try {
346
+ result = await Promise.race([acquiring, deadline]);
347
+ }
348
+ finally {
349
+ clearTimeout(timer);
350
+ }
351
+ if (result !== 'deadline')
352
+ return result;
353
+ state.abandoned = true;
354
+ const waitedMs = Date.now() - arrivedAt;
355
+ const pending = describePendingCalls(state.pending, Date.now());
356
+ // Only an acquire with a call still pending holds others back, so only then
357
+ // is the probe worth waiting for. One abandoned between retries throws at once.
358
+ let asyncFs = null;
359
+ if (state.pending.size > 0) {
360
+ pathState.blockers.add(state);
361
+ asyncFs = await probe();
362
+ passOver(pathState, state, asyncFs.result);
363
+ }
364
+ throw lockAcquireTimeout({
365
+ lockPath,
366
+ daemonId,
367
+ waitedMs,
368
+ queuedMs: state.startedAt - arrivedAt,
369
+ mkdirCalls: state.mkdirCalls,
370
+ pending,
371
+ asyncFs,
372
+ passedOver: pathState.blockers.has(state) ? passedOverCalls(pathState) : null,
373
+ waitedBehindEarlier: false,
374
+ acquireDeadlineMs,
375
+ asyncFsProbeMs,
376
+ });
377
+ }
378
+ /** Forgets an abandoned acquire whose last pending call has answered. */
379
+ function clearBlocker(pathState, state) {
380
+ pathState.passedOver.delete(state);
381
+ if (pathState.blockers.delete(state))
382
+ releaseWaitersIfClear(pathState);
383
+ }
384
+ /**
385
+ * Stops `state` holding new acquires back if the file system answered `asyncFs`
386
+ * and the limits in `lockPaths` allow it.
387
+ */
388
+ function passOver(pathState, state, asyncFs) {
389
+ if (!pathState.blockers.has(state) || asyncFs === 'no_answer')
390
+ return;
391
+ if ([...state.pending].some((call) => CALLS_UNSAFE_TO_OUTLIVE.has(call.op)))
392
+ return;
393
+ if (pathState.passedOver.size >= MAX_PASSED_OVER)
394
+ return;
395
+ pathState.blockers.delete(state);
396
+ pathState.passedOver.add(state);
397
+ releaseWaitersIfClear(pathState);
398
+ }
399
+ /**
400
+ * The pending calls of the acquire already passed over, if there is one. While
401
+ * it waits, no other blocker is passed over (`MAX_PASSED_OVER`), so a timeout
402
+ * that leaves a blocker names it: if its call is lost for good, new acquires
403
+ * on this path wait until a restart.
404
+ */
405
+ function passedOverCalls(pathState) {
406
+ const [held] = pathState.passedOver;
407
+ return held ? describePendingCalls(held.pending, Date.now()) : null;
408
+ }
409
+ function releaseWaitersIfClear(pathState) {
410
+ if (pathState.blockers.size > 0)
411
+ return;
412
+ const waiters = [...pathState.waiters];
413
+ pathState.waiters.clear();
414
+ for (const waiter of waiters)
415
+ waiter.release();
416
+ }
417
+ /**
418
+ * Waits until no abandoned acquire on this path holds new ones back, for at most
419
+ * `deadlineMs`. Then it probes and passes blockers over where `passOver`
420
+ * allows. Resolves `'clear'` once none is left, or with what it saw when it
421
+ * gave up.
422
+ */
423
+ function waitForBlockers(pathState, deadlineMs, probe) {
424
+ return new Promise((resolve) => {
425
+ const giveUp = async () => {
426
+ const asyncFs = await probe();
427
+ for (const blocker of [...pathState.blockers])
428
+ passOver(pathState, blocker, asyncFs.result);
429
+ // Released while it probed, or by passing the last blocker over.
430
+ if (!pathState.waiters.has(waiter))
431
+ return;
432
+ pathState.waiters.delete(waiter);
433
+ // Read after passing over, so it names an acquire that still holds new ones back.
434
+ const [oldest] = pathState.blockers;
435
+ resolve({
436
+ pending: describePendingCalls(oldest?.pending ?? new Set(), Date.now()),
437
+ asyncFs,
438
+ passedOver: passedOverCalls(pathState),
439
+ });
440
+ };
441
+ // Not unref'd, like the deadline timer.
442
+ const timer = setTimeout(() => void giveUp(), deadlineMs);
443
+ const waiter = {
444
+ release: () => {
445
+ clearTimeout(timer);
446
+ resolve('clear');
447
+ },
448
+ };
449
+ pathState.waiters.add(waiter);
450
+ });
451
+ }
452
+ /** `ms` as `N ms` below a second, else as whole seconds. */
453
+ function formatLockWait(ms) {
454
+ return ms < 1_000 ? `${ms} ms` : `${Math.round(ms / 1_000)} s`;
455
+ }
456
+ /** Emits `refresh_lock_acquire_timeout`, warns, and returns the failure to throw. */
457
+ function lockAcquireTimeout(options) {
458
+ const { lockPath, daemonId, mkdirCalls, waitedBehindEarlier, asyncFs, passedOver } = options;
459
+ const { calls, text } = options.pending;
460
+ emitAuthTelemetry({
461
+ timestamp: new Date().toISOString(),
462
+ eventType: 'auth',
463
+ success: false,
464
+ metadata: {
465
+ event: 'refresh_lock_acquire_timeout',
466
+ waitedMs: options.waitedMs,
467
+ queuedMs: options.queuedMs,
468
+ mkdirCalls,
469
+ waitedBehindEarlier,
470
+ pendingFsCalls: calls,
471
+ asyncFsProbe: asyncFs?.result ?? 'not_run',
472
+ asyncFsProbeReused: asyncFs ? asyncFs.reusedAfterMs !== null : false,
473
+ passedOverPendingFsCalls: passedOver?.calls ?? [],
474
+ ...(daemonId ? { daemonId } : {}),
475
+ },
476
+ });
477
+ const lockFile = path.basename(lockPath);
478
+ const probeText = asyncFs ? `; ${asyncFsProbeText(asyncFs, options.asyncFsProbeMs)}` : '';
479
+ const passedOverText = passedOver
480
+ ? ` An acquire this process already passed over is still waiting on ${passedOver.text}, and ` +
481
+ 'no other is passed over while it waits, so new acquires wait until one of these calls ' +
482
+ 'answers or the process restarts.'
483
+ : '';
484
+ const message = waitedBehindEarlier
485
+ ? `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 ` +
487
+ `${text || 'no file-system call'}${probeText}.${passedOverText}`
488
+ : `The auth lock (${lockFile}) was not acquired within ${formatLockWait(options.acquireDeadlineMs)} ` +
489
+ `(${mkdirCalls} mkdir call${mkdirCalls === 1 ? '' : 's'} on the lock directory). ` +
490
+ `Pending file-system calls: ${calls.length ? text : 'none (it was between retries)'}` +
491
+ `${probeText}.${passedOverText}`;
492
+ getAuthLogger().warn(`[auth/refresh] ${message}`);
493
+ return new TransientAuthFailure(message);
494
+ }
46
495
  /**
47
496
  * P1-6: Module-level guard so registering process-exit handlers is
48
497
  * idempotent. A second import (or a unit test that re-requires the
@@ -54,8 +503,8 @@ let _exitHandlersInstalled = false;
54
503
  *
55
504
  * `proper-lockfile` is NOT re-entrant within a process: a second
56
505
  * `lockfile.lock()` call on the same file from the same process will
57
- * block until `LOCK_STALE_MS` (5 s) elapses and treat itself as stale —
58
- * effectively a 5 s deadlock. Several call sites legitimately nest:
506
+ * retry against its own holder, which keeps the lock fresh, until ELOCKED
507
+ * (about 19 s) or the acquire deadline. Several call sites legitimately nest:
59
508
  *
60
509
  * performRefresh → withAuthLock → saveToken → withAuthLock (new)
61
510
  * consumeFdAuth → saveToken → withAuthLock (new, no outer lock)
@@ -235,8 +684,9 @@ export function installLockExitHandlers(options = {}) {
235
684
  }
236
685
  /**
237
686
  * Acquire the cross-process auth lock, run the body, release on `finally`.
238
- * Throws if the lock can't be acquired within
239
- * `LOCK_MAX_RETRIES × LOCK_RETRY_MS`.
687
+ * Throws ELOCKED once proper-lockfile's retries are spent (about 19 s), and a
688
+ * `TransientAuthFailure` if the acquire is still pending at
689
+ * `LOCK_ACQUIRE_DEADLINE_MS` (OSK-33422).
240
690
  *
241
691
  * We lock a sentinel file (auth.lock) that we create/touch if missing —
242
692
  * locking the real auth.json would race with atomic-rename writes.
@@ -247,9 +697,9 @@ export function installLockExitHandlers(options = {}) {
247
697
  export async function withAuthLock(body, daemonId) {
248
698
  // D-4 — Re-entrancy guard. If the current async context already holds
249
699
  // the auth lock (e.g. performRefresh → withAuthLock → saveToken →
250
- // withAuthLock), skip the proper-lockfile acquire to avoid the 5 s
251
- // deadlock that would occur because proper-lockfile is not re-entrant
252
- // within a process. Cross-process callers each have their own ALS store
700
+ // withAuthLock), skip the proper-lockfile acquire: proper-lockfile is not
701
+ // re-entrant within a process, so a nested acquire would wait on its own
702
+ // holder until ELOCKED (about 19 s). Cross-process callers each have their own ALS store
253
703
  // and always go through the real file lock.
254
704
  if (_authLockHeld.getStore() === true) {
255
705
  return body();
@@ -268,15 +718,7 @@ export async function withAuthLock(body, daemonId) {
268
718
  success: true,
269
719
  metadata: { event: 'refresh_lock_acquiring', ...(daemonId ? { daemonId } : {}) },
270
720
  });
271
- const release = await lockfile.lock(lockPath, {
272
- stale: LOCK_STALE_MS,
273
- retries: {
274
- retries: LOCK_MAX_RETRIES,
275
- minTimeout: LOCK_RETRY_MS,
276
- maxTimeout: LOCK_RETRY_MS * 4,
277
- factor: 1.5,
278
- },
279
- });
721
+ const release = await acquireAuthLock(lockPath, daemonId);
280
722
  const acquiredAt = Date.now();
281
723
  emitAuthTelemetry({
282
724
  timestamp: new Date().toISOString(),
@@ -28,6 +28,11 @@ export interface AuthKillSwitches {
28
28
  * refresh_lock_acquired — {daemonId, waitedMs}
29
29
  * refresh_lock_retry — {daemonId, attempt, errorCode}
30
30
  * refresh_lock_released — {daemonId, heldForMs}
31
+ * refresh_lock_acquire_timeout — {daemonId, waitedMs, queuedMs, mkdirCalls,
32
+ * waitedBehindEarlier, pendingFsCalls: [{op, file?,
33
+ * pendingMs}], asyncFsProbe: answered|failed|no_answer|
34
+ * not_run, asyncFsProbeReused: boolean,
35
+ * passedOverPendingFsCalls: [{op, file?, pendingMs}]}
31
36
  * refresh_race_resolved — {daemonId, sourceTokenAdopted: boolean}
32
37
  */
33
38
  export interface AuthTelemetryEvent {