@skrr-ai/cli 0.1.213 → 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.
Files changed (33) hide show
  1. package/dist/commands/agents/relationship/clear.d.ts +12 -0
  2. package/dist/commands/agents/relationship/clear.js +26 -0
  3. package/dist/commands/agents/relationship/edit.d.ts +15 -0
  4. package/dist/commands/agents/relationship/edit.js +40 -0
  5. package/dist/commands/agents/relationship/show.d.ts +12 -0
  6. package/dist/commands/agents/relationship/show.js +35 -0
  7. package/dist/commands/tasks/ask.d.ts +3 -2
  8. package/dist/commands/tasks/ask.js +4 -3
  9. package/dist/commands/tasks/chat/exchange.d.ts +3 -2
  10. package/dist/commands/tasks/chat/exchange.js +18 -6
  11. package/dist/commands/tasks/chat/rotate.js +5 -2
  12. package/dist/commands/tasks/show.d.ts +6 -1
  13. package/dist/commands/tasks/show.js +19 -5
  14. package/dist/generated/agent-guides.json +20 -20
  15. package/dist/lib/inbound-messages.js +7 -0
  16. package/dist/lib/task-asset-upload.d.ts +7 -0
  17. package/dist/lib/task-asset-upload.js +114 -44
  18. package/dist/lib/task-operations.d.ts +16 -0
  19. package/dist/lib/task-operations.js +39 -0
  20. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/personAskWindow.d.ts +23 -0
  21. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/personAskWindow.js +28 -0
  22. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/refresh.d.ts +16 -2
  23. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/refresh.js +110 -15
  24. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/runtime.d.ts +7 -2
  25. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/personAskWindow.d.ts +23 -0
  26. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/personAskWindow.js +23 -0
  27. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/refresh.d.ts +16 -2
  28. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/refresh.js +179 -17
  29. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/runtime.d.ts +7 -2
  30. package/dist/node_modules/@skrr-ai/auth-core/package.json +10 -0
  31. package/dist/node_modules/@skrr-ai/data-provider/index.js +10767 -10760
  32. package/oclif.manifest.json +265 -7
  33. package/package.json +2 -2
@@ -61,6 +61,7 @@ const LOCK_RETRY_MS = 100;
61
61
  const LOCK_MAX_RETRIES = 50;
62
62
  const LOCK_ACQUIRE_DEADLINE_MS = 6e4;
63
63
  const LOCK_ASYNC_FS_PROBE_MS = 1e3;
64
+ const LOCK_RELEASE_DEADLINE_MS = 1e4;
64
65
  const CALLS_UNSAFE_TO_OUTLIVE = /* @__PURE__ */ new Set(["rmdir", "utimes"]);
65
66
  const MAX_PASSED_OVER = 1;
66
67
  const lockPaths = /* @__PURE__ */ new Map();
@@ -68,6 +69,7 @@ const probeStats = /* @__PURE__ */ new Map();
68
69
  const __authLockTesting = {
69
70
  acquireDeadlineMs: LOCK_ACQUIRE_DEADLINE_MS,
70
71
  asyncFsProbeMs: LOCK_ASYNC_FS_PROBE_MS,
72
+ releaseDeadlineMs: LOCK_RELEASE_DEADLINE_MS,
71
73
  fs: import_node_fs.default,
72
74
  lockPaths,
73
75
  probes: probeStats,
@@ -78,6 +80,9 @@ function abandonedError(op) {
78
80
  code: "EABANDONED"
79
81
  });
80
82
  }
83
+ function releasedLockGoneError() {
84
+ return Object.assign(new Error("ENOENT: the auth lock was released"), { code: "ENOENT" });
85
+ }
81
86
  function trackedLockFs(base, state, onPendingChange) {
82
87
  return new Proxy(base, {
83
88
  get(target, prop, receiver) {
@@ -112,6 +117,10 @@ function trackedLockFs(base, state, onPendingChange) {
112
117
  answer(abandonedError(op));
113
118
  return;
114
119
  }
120
+ if (state.releasing && op === "stat") {
121
+ answer(releasedLockGoneError());
122
+ return;
123
+ }
115
124
  answer(...result);
116
125
  };
117
126
  try {
@@ -190,6 +199,7 @@ async function acquireAuthLock(lockPath, daemonId) {
190
199
  asyncFs: outcome.asyncFs,
191
200
  passedOver: outcome.passedOver,
192
201
  waitedBehindEarlier: true,
202
+ blockerReleasing: outcome.blockerReleasing,
193
203
  acquireDeadlineMs,
194
204
  asyncFsProbeMs
195
205
  });
@@ -199,10 +209,14 @@ async function acquireAuthLock(lockPath, daemonId) {
199
209
  pending: /* @__PURE__ */ new Set(),
200
210
  abandoned: false,
201
211
  mkdirCalls: 0,
202
- startedAt: Date.now()
212
+ startedAt: Date.now(),
213
+ releasing: false,
214
+ releaseTimedOut: false
203
215
  };
204
216
  const acquiring = import_proper_lockfile.default.lock(lockPath, {
205
217
  stale: LOCK_STALE_MS,
218
+ // proper-lockfile's default throws, in a timer, which ends the process.
219
+ onCompromised: (err) => onLockCompromised(err, state, lockPath, daemonId),
206
220
  retries: {
207
221
  retries: LOCK_MAX_RETRIES,
208
222
  minTimeout: LOCK_RETRY_MS,
@@ -216,6 +230,8 @@ async function acquireAuthLock(lockPath, daemonId) {
216
230
  fs: trackedLockFs(baseFs, state, () => {
217
231
  if (state.abandoned && state.pending.size === 0)
218
232
  clearBlocker(pathState, state);
233
+ else if (state.releaseTimedOut && !hasUnsafePendingCall(state))
234
+ clearBlocker(pathState, state);
219
235
  })
220
236
  });
221
237
  void acquiring.catch(() => void 0);
@@ -229,8 +245,10 @@ async function acquireAuthLock(lockPath, daemonId) {
229
245
  } finally {
230
246
  clearTimeout(timer);
231
247
  }
232
- if (result !== "deadline")
233
- return result;
248
+ if (result !== "deadline") {
249
+ const release = result;
250
+ return () => releaseAuthLock(release, { lockPath, daemonId, state, pathState });
251
+ }
234
252
  state.abandoned = true;
235
253
  const waitedMs = Date.now() - arrivedAt;
236
254
  const pending = describePendingCalls(state.pending, Date.now());
@@ -250,10 +268,82 @@ async function acquireAuthLock(lockPath, daemonId) {
250
268
  asyncFs,
251
269
  passedOver: pathState.blockers.has(state) ? passedOverCalls(pathState) : null,
252
270
  waitedBehindEarlier: false,
271
+ blockerReleasing: false,
253
272
  acquireDeadlineMs,
254
273
  asyncFsProbeMs
255
274
  });
256
275
  }
276
+ function hasUnsafePendingCall(state) {
277
+ return [...state.pending].some((call) => CALLS_UNSAFE_TO_OUTLIVE.has(call.op));
278
+ }
279
+ async function releaseAuthLock(release, options) {
280
+ const { lockPath, daemonId, state, pathState } = options;
281
+ const { releaseDeadlineMs } = __authLockTesting;
282
+ const startedAt = Date.now();
283
+ state.releasing = true;
284
+ const releasing = release();
285
+ void releasing.catch(() => void 0);
286
+ let timer;
287
+ const deadline = new Promise((resolve) => {
288
+ timer = setTimeout(() => resolve("deadline"), releaseDeadlineMs);
289
+ });
290
+ let result;
291
+ try {
292
+ result = await Promise.race([releasing.then(() => "released"), deadline]);
293
+ } finally {
294
+ clearTimeout(timer);
295
+ }
296
+ if (result === "released")
297
+ return "released";
298
+ if (!hasUnsafePendingCall(state))
299
+ return "released";
300
+ state.releaseTimedOut = true;
301
+ pathState.blockers.add(state);
302
+ const waitedMs = Date.now() - startedAt;
303
+ const { calls, text } = describePendingCalls(state.pending, Date.now());
304
+ (0, import_runtime.emitAuthTelemetry)({
305
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
306
+ eventType: "auth",
307
+ success: false,
308
+ metadata: {
309
+ event: "refresh_lock_release_timeout",
310
+ waitedMs,
311
+ pendingFsCalls: calls,
312
+ ...daemonId ? { daemonId } : {}
313
+ }
314
+ });
315
+ (0, import_runtime.getAuthLogger)().warn(`[auth/refresh] The auth lock (${import_node_path.default.basename(lockPath)}) was not released within ${formatLockWait(releaseDeadlineMs)}. Pending file-system calls: ${text}. The caller went on without waiting, the lock directory is not removed again, and new acquires in this process wait until that call answers. Another process takes the lock over once it is stale, and the pending call can still remove its lock if it lands after that.`);
316
+ return "timed_out";
317
+ }
318
+ function onLockCompromised(err, state, lockPath, daemonId) {
319
+ const lockFile = import_node_path.default.basename(lockPath);
320
+ const message = String(err?.message ?? "");
321
+ let cause = "refresh_failed";
322
+ if (message.startsWith("ENOENT"))
323
+ cause = "removed";
324
+ else if (message.includes("stale threshold"))
325
+ cause = "taken_over";
326
+ if (state.releasing) {
327
+ (0, import_runtime.getAuthLogger)().debug(`[auth/refresh] The auth lock (${lockFile}) read as compromised (${cause}) after its release began.`);
328
+ return;
329
+ }
330
+ const what = {
331
+ removed: "its directory was removed",
332
+ taken_over: "its mtime changed, so another process took it over",
333
+ refresh_failed: "its mtime could not be refreshed within the stale threshold"
334
+ }[cause];
335
+ (0, import_runtime.getAuthLogger)().warn(`[auth/refresh] The auth lock (${lockFile}) was lost while held: ${what}. The holder goes on; another process may hold the lock now.`);
336
+ (0, import_runtime.emitAuthTelemetry)({
337
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
338
+ eventType: "auth",
339
+ success: false,
340
+ metadata: {
341
+ event: "refresh_lock_compromised",
342
+ cause,
343
+ ...daemonId ? { daemonId } : {}
344
+ }
345
+ });
346
+ }
257
347
  function clearBlocker(pathState, state) {
258
348
  pathState.passedOver.delete(state);
259
349
  if (pathState.blockers.delete(state))
@@ -294,6 +384,7 @@ function waitForBlockers(pathState, deadlineMs, probe) {
294
384
  const [oldest] = pathState.blockers;
295
385
  resolve({
296
386
  pending: describePendingCalls(oldest?.pending ?? /* @__PURE__ */ new Set(), Date.now()),
387
+ blockerReleasing: oldest?.releasing ?? false,
297
388
  asyncFs,
298
389
  passedOver: passedOverCalls(pathState)
299
390
  });
@@ -324,6 +415,7 @@ function lockAcquireTimeout(options) {
324
415
  queuedMs: options.queuedMs,
325
416
  mkdirCalls,
326
417
  waitedBehindEarlier,
418
+ waitedBehindRelease: waitedBehindEarlier && options.blockerReleasing,
327
419
  pendingFsCalls: calls,
328
420
  asyncFsProbe: asyncFs?.result ?? "not_run",
329
421
  asyncFsProbeReused: asyncFs ? asyncFs.reusedAfterMs !== null : false,
@@ -334,7 +426,7 @@ function lockAcquireTimeout(options) {
334
426
  const lockFile = import_node_path.default.basename(lockPath);
335
427
  const probeText = asyncFs ? `; ${asyncFsProbeText(asyncFs, options.asyncFsProbeMs)}` : "";
336
428
  const passedOverText = passedOver ? ` An acquire this process already passed over is still waiting on ${passedOver.text}, and no other is passed over while it waits, so new acquires wait until one of these calls answers or the process restarts.` : "";
337
- const message = waitedBehindEarlier ? `The auth lock (${lockFile}) was not acquired: it waited ${formatLockWait(options.waitedMs)} behind an earlier acquire in this process, which is still waiting on ${text || "no file-system call"}${probeText}.${passedOverText}` : `The auth lock (${lockFile}) was not acquired within ${formatLockWait(options.acquireDeadlineMs)} (${mkdirCalls} mkdir call${mkdirCalls === 1 ? "" : "s"} on the lock directory). Pending file-system calls: ${calls.length ? text : "none (it was between retries)"}${probeText}.${passedOverText}`;
429
+ const message = waitedBehindEarlier ? `The auth lock (${lockFile}) was not acquired: it waited ${formatLockWait(options.waitedMs)} behind an earlier ${options.blockerReleasing ? "release" : "acquire"} in this process, which is still waiting on ${text || "no file-system call"}${probeText}.${passedOverText}` : `The auth lock (${lockFile}) was not acquired within ${formatLockWait(options.acquireDeadlineMs)} (${mkdirCalls} mkdir call${mkdirCalls === 1 ? "" : "s"} on the lock directory). Pending file-system calls: ${calls.length ? text : "none (it was between retries)"}${probeText}.${passedOverText}`;
338
430
  (0, import_runtime.getAuthLogger)().warn(`[auth/refresh] ${message}`);
339
431
  return new import_types.TransientAuthFailure(message);
340
432
  }
@@ -437,21 +529,24 @@ async function withAuthLock(body, daemonId) {
437
529
  return await body();
438
530
  } finally {
439
531
  const heldForMs = Date.now() - acquiredAt;
440
- (0, import_runtime.emitAuthTelemetry)({
441
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
442
- eventType: "auth",
443
- success: true,
444
- metadata: {
445
- event: "refresh_lock_released",
446
- heldForMs,
447
- ...daemonId ? { daemonId } : {}
448
- }
449
- });
532
+ let outcome = "released";
450
533
  try {
451
- await release();
534
+ outcome = await release();
452
535
  } catch (err) {
453
536
  (0, import_runtime.getAuthLogger)().debug(`[auth/refresh] lock release failed: ${err?.message}`);
454
537
  }
538
+ if (outcome === "released") {
539
+ (0, import_runtime.emitAuthTelemetry)({
540
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
541
+ eventType: "auth",
542
+ success: true,
543
+ metadata: {
544
+ event: "refresh_lock_released",
545
+ heldForMs,
546
+ ...daemonId ? { daemonId } : {}
547
+ }
548
+ });
549
+ }
455
550
  }
456
551
  });
457
552
  }
@@ -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 {
@@ -0,0 +1,23 @@
1
+ /**
2
+ * How long an agent's question or approval waits for its person (OSK-33439).
3
+ *
4
+ * ONE number for every place an agent asks a person and waits: a cloud turn's
5
+ * approval and question (the API's `AgentWorker/permissionWindow.js`) and a
6
+ * session that runs natively on the person's machine (the daemon's permissions
7
+ * bridge, `DEFAULT_PERMISSION_TIMEOUT_MS`). Before this the daemon kept its own
8
+ * copy, five minutes, under a comment saying it matched the server. The server
9
+ * had moved to ten minutes on 2026-10-22, so the same person got ten minutes when
10
+ * the agent ran in the cloud and five when it ran on their machine, and nothing
11
+ * on screen said why.
12
+ *
13
+ * Why ten minutes (owner decision 2026-10-22): answers arrive in under a second
14
+ * when someone is there, so the window is for a person who stepped away, and an
15
+ * open ask keeps its turn's spend reserved for as long as it waits. A 72-hour
16
+ * window once left three abandoned cards holding $9.9 of a $10 balance
17
+ * (OSK-17926). Expiry is an answer the run finishes with, not an error.
18
+ *
19
+ * A harness whose own runtime gives up on an ask sooner keeps that shorter bound,
20
+ * because a card that outlives the wait behind it would take an answer nothing
21
+ * reads (the daemon's ACP permission authority, `acp-permission/authority.ts`).
22
+ */
23
+ export declare const PERSON_ASK_WINDOW_MS: number;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * How long an agent's question or approval waits for its person (OSK-33439).
3
+ *
4
+ * ONE number for every place an agent asks a person and waits: a cloud turn's
5
+ * approval and question (the API's `AgentWorker/permissionWindow.js`) and a
6
+ * session that runs natively on the person's machine (the daemon's permissions
7
+ * bridge, `DEFAULT_PERMISSION_TIMEOUT_MS`). Before this the daemon kept its own
8
+ * copy, five minutes, under a comment saying it matched the server. The server
9
+ * had moved to ten minutes on 2026-10-22, so the same person got ten minutes when
10
+ * the agent ran in the cloud and five when it ran on their machine, and nothing
11
+ * on screen said why.
12
+ *
13
+ * Why ten minutes (owner decision 2026-10-22): answers arrive in under a second
14
+ * when someone is there, so the window is for a person who stepped away, and an
15
+ * open ask keeps its turn's spend reserved for as long as it waits. A 72-hour
16
+ * window once left three abandoned cards holding $9.9 of a $10 balance
17
+ * (OSK-17926). Expiry is an answer the run finishes with, not an error.
18
+ *
19
+ * A harness whose own runtime gives up on an ask sooner keeps that shorter bound,
20
+ * because a card that outlives the wait behind it would take an answer nothing
21
+ * reads (the daemon's ACP permission authority, `acp-permission/authority.ts`).
22
+ */
23
+ export const PERSON_ASK_WINDOW_MS = 10 * 60 * 1000;
@@ -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 {