@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.
@@ -62,7 +62,9 @@ exports.postFileToStorage = postFileToStorage;
62
62
  * evidence reference that named the local hash would pin a version of the
63
63
  * file that was never stored (OSK-10120). The local hash is computed only
64
64
  * where the protocol needs it — declaring a direct upload, which storage then
65
- * enforces — and never leaves this module as a claim about the asset.
65
+ * enforces — and never leaves this module as a claim about the asset. The
66
+ * name and MIME type it reports are the server's for the same reason: the
67
+ * server decides them from the bytes, not from the extension (OSK-33381).
66
68
  */
67
69
  const fs = __importStar(require("node:fs"));
68
70
  const http = __importStar(require("node:http"));
@@ -86,6 +88,9 @@ function storedDigest(asset) {
86
88
  const value = asset.contentSha256;
87
89
  return typeof value === 'string' && SHA256_HEX.test(value) ? value.toLowerCase() : undefined;
88
90
  }
91
+ function storedText(value) {
92
+ return typeof value === 'string' && value.trim() ? value : undefined;
93
+ }
89
94
  /**
90
95
  * Read the Task an upload targets, through the same credential the upload
91
96
  * will use. In a session the task comes from the claim, so the read is the
@@ -106,8 +111,10 @@ async function readTaskForUpload(taskId) {
106
111
  async function uploadTaskAssetFile(opts) {
107
112
  const { taskId, filePath, role, ledger } = opts;
108
113
  if (opts.resumeAttachmentId !== undefined &&
109
- (!opts.resumeAttachmentId || opts.resumeAttachmentId.trim() !== opts.resumeAttachmentId ||
110
- opts.resumeAttachmentId.length > 200 || ledger !== undefined)) {
114
+ (!opts.resumeAttachmentId ||
115
+ opts.resumeAttachmentId.trim() !== opts.resumeAttachmentId ||
116
+ opts.resumeAttachmentId.length > 200 ||
117
+ ledger !== undefined)) {
111
118
  throw new Error('Resume requires one exact attachment id and retains its original ledger declaration.');
112
119
  }
113
120
  if (!fs.existsSync(filePath)) {
@@ -132,8 +139,7 @@ async function uploadTaskAssetFile(opts) {
132
139
  let result;
133
140
  try {
134
141
  if (opts.resumeAttachmentId !== undefined) {
135
- result = await resumeDirectUpload({ taskId, filePath, size, filename, mimeType, role,
136
- attachmentId: opts.resumeAttachmentId }, sessionTarget);
142
+ result = await resumeDirectUpload({ taskId, filePath, size, filename, mimeType, role, attachmentId: opts.resumeAttachmentId }, sessionTarget);
137
143
  }
138
144
  else if (sessionTarget) {
139
145
  result = direct
@@ -154,8 +160,8 @@ async function uploadTaskAssetFile(opts) {
154
160
  status: 'ready',
155
161
  id: String(result.id ?? result._id),
156
162
  digest: storedDigest(result),
157
- filename,
158
- mimeType,
163
+ filename: storedText(result.originalName) ?? filename,
164
+ mimeType: storedText(result.mimeType) ?? mimeType,
159
165
  deduplicated: result.deduplicated === true,
160
166
  ...(result.resourceReceipt ? { resourceReceipt: result.resourceReceipt } : {}),
161
167
  };
@@ -315,13 +321,19 @@ function directUploadProtocol(taskId, attachmentId, target) {
315
321
  credential: target.credential,
316
322
  }),
317
323
  sign: (partNumbers) => (0, api_fetch_1.apiFetch)(`${uploadPath}/upload-parts/sign`, {
318
- method: 'POST', credential: target.credential, body: { partNumbers },
324
+ method: 'POST',
325
+ credential: target.credential,
326
+ body: { partNumbers },
319
327
  }),
320
328
  record: (part) => (0, api_fetch_1.apiFetch)(`${uploadPath}/upload-parts/complete`, {
321
- method: 'POST', credential: target.credential, body: part,
329
+ method: 'POST',
330
+ credential: target.credential,
331
+ body: part,
322
332
  }),
323
333
  complete: () => (0, api_fetch_1.apiFetch)(`${target.path}/complete`, {
324
- method: 'POST', credential: target.credential, body: { attachmentId },
334
+ method: 'POST',
335
+ credential: target.credential,
336
+ body: { attachmentId },
325
337
  }),
326
338
  };
327
339
  }
@@ -330,40 +342,59 @@ function taskAssetUploadRecovery(error) {
330
342
  if (!error || typeof error !== 'object')
331
343
  return undefined;
332
344
  const value = error.uploadRecovery;
333
- if (!value || typeof value.taskId !== 'string' || typeof value.attachmentId !== 'string' ||
345
+ if (!value ||
346
+ typeof value.taskId !== 'string' ||
347
+ typeof value.attachmentId !== 'string' ||
334
348
  value.transport !== 'multipart')
335
349
  return undefined;
336
- return { taskId: value.taskId, attachmentId: value.attachmentId, transport: 'multipart',
337
- ...(typeof value.sessionId === 'string' ? { sessionId: value.sessionId } : {}) };
350
+ return {
351
+ taskId: value.taskId,
352
+ attachmentId: value.attachmentId,
353
+ transport: 'multipart',
354
+ ...(typeof value.sessionId === 'string' ? { sessionId: value.sessionId } : {}),
355
+ };
338
356
  }
339
357
  function resumeHint(attachmentId) {
340
- return `Upload attachment ${attachmentId} is not confirmed complete. ` +
341
- `Use --resume-attachment ${attachmentId} with tasks attachments upload and the same file to recover this exact upload.`;
358
+ return (`Upload attachment ${attachmentId} is not confirmed complete. ` +
359
+ `Use --resume-attachment ${attachmentId} with tasks attachments upload and the same file to recover this exact upload.`);
342
360
  }
343
361
  async function resumeDirectUpload(file, target) {
344
362
  const taskId = target?.taskId ?? file.taskId;
345
363
  const protocol = directUploadProtocol(taskId, file.attachmentId, target);
346
364
  const progress = await protocol.status();
347
- const rawDeclaration = progress?.declaredAttachment;
365
+ const rawDeclaration = progress
366
+ ?.declaredAttachment;
348
367
  const declaration = rawDeclaration && typeof rawDeclaration === 'object' && !Array.isArray(rawDeclaration)
349
- ? rawDeclaration : undefined;
368
+ ? rawDeclaration
369
+ : undefined;
350
370
  const sha256 = await sha256OfFile(file.filePath);
351
- if (!declaration || file.size < 1 || declaration.basis !== 'declared_upload_intent' ||
352
- declaration.attachmentId !== file.attachmentId || declaration.taskId !== taskId ||
353
- declaration.filename !== file.filename || declaration.mimeType !== file.mimeType ||
354
- declaration.sizeBytes !== file.size || declaration.sha256 !== sha256 ||
355
- typeof declaration.role !== 'string' || !['input', 'evidence', 'deliverable'].includes(declaration.role) ||
371
+ if (!declaration ||
372
+ file.size < 1 ||
373
+ declaration.basis !== 'declared_upload_intent' ||
374
+ declaration.attachmentId !== file.attachmentId ||
375
+ declaration.taskId !== taskId ||
376
+ declaration.filename !== file.filename ||
377
+ declaration.mimeType !== file.mimeType ||
378
+ declaration.sizeBytes !== file.size ||
379
+ declaration.sha256 !== sha256 ||
380
+ typeof declaration.role !== 'string' ||
381
+ !['input', 'evidence', 'deliverable'].includes(declaration.role) ||
356
382
  (file.role !== undefined && declaration.role !== file.role)) {
357
383
  throw new Error('This file does not match the existing upload declaration, or the server cannot verify it. No replacement upload was created.');
358
384
  }
359
- if (progress.transport !== 'multipart' || typeof progress.expiresAt !== 'string' ||
385
+ if (progress.transport !== 'multipart' ||
386
+ typeof progress.expiresAt !== 'string' ||
360
387
  !Number.isFinite(Date.parse(progress.expiresAt)) ||
361
388
  Date.parse(progress.expiresAt) <= Date.now()) {
362
389
  throw new Error('Only an unexpired multipart upload can be resumed. No replacement upload was created.');
363
390
  }
364
391
  const intent = {
365
- attachment: { id: file.attachmentId, status: 'pending' }, uploadUrl: null, uploadFields: null,
366
- uploadTransport: 'multipart', partSize: progress.partSize, partCount: progress.expectedParts,
392
+ attachment: { id: file.attachmentId, status: 'pending' },
393
+ uploadUrl: null,
394
+ uploadFields: null,
395
+ uploadTransport: 'multipart',
396
+ partSize: progress.partSize,
397
+ partCount: progress.expectedParts,
367
398
  };
368
399
  // Even a ready session goes through canonical completion to recover its
369
400
  // verified attachment and original ledger receipt, never its declaration.
@@ -382,7 +413,8 @@ async function uploadDirectIntent(file, intent, protocol) {
382
413
  if (intent.attachment.status === 'ready')
383
414
  return intent.attachment;
384
415
  if ((intent.attachment.status !== undefined && intent.attachment.status !== 'pending') ||
385
- (intent.uploadTransport !== undefined && !['single', 'multipart'].includes(intent.uploadTransport))) {
416
+ (intent.uploadTransport !== undefined &&
417
+ !['single', 'multipart'].includes(intent.uploadTransport))) {
386
418
  throw new Error('The server returned an unusable Task attachment upload intent.');
387
419
  }
388
420
  try {
@@ -393,7 +425,11 @@ async function uploadDirectIntent(file, intent, protocol) {
393
425
  if (!intent.uploadUrl || !intent.uploadFields) {
394
426
  throw new Error('The pending Task attachment has no usable storage grant; it was not uploaded.');
395
427
  }
396
- await postFileToStorage({ ...file, uploadUrl: intent.uploadUrl, uploadFields: intent.uploadFields });
428
+ await postFileToStorage({
429
+ ...file,
430
+ uploadUrl: intent.uploadUrl,
431
+ uploadFields: intent.uploadFields,
432
+ });
397
433
  }
398
434
  const completed = await protocol.complete();
399
435
  requireReadyAsset(completed);
@@ -423,19 +459,35 @@ async function uploadMultipartFile(file, intent, protocol) {
423
459
  const lengthOf = (partNumber) => Math.min(partSize, file.size - (partNumber - 1) * partSize);
424
460
  let sessionId;
425
461
  const inspect = (progress) => {
426
- if (!progress || typeof progress.sessionId !== 'string' || !progress.sessionId ||
427
- (sessionId && progress.sessionId !== sessionId) || progress.transport !== 'multipart' ||
428
- progress.partSize !== partSize || progress.expectedSize !== file.size ||
429
- progress.expectedParts !== partCount || !Array.isArray(progress.receivedParts) ||
430
- !['created', 'receiving', 'landed', 'verified', 'scanning', 'canonicalizing', 'ready'].includes(progress.state)) {
462
+ if (!progress ||
463
+ typeof progress.sessionId !== 'string' ||
464
+ !progress.sessionId ||
465
+ (sessionId && progress.sessionId !== sessionId) ||
466
+ progress.transport !== 'multipart' ||
467
+ progress.partSize !== partSize ||
468
+ progress.expectedSize !== file.size ||
469
+ progress.expectedParts !== partCount ||
470
+ !Array.isArray(progress.receivedParts) ||
471
+ ![
472
+ 'created',
473
+ 'receiving',
474
+ 'landed',
475
+ 'verified',
476
+ 'scanning',
477
+ 'canonicalizing',
478
+ 'ready',
479
+ ].includes(progress.state)) {
431
480
  throw new Error('The server returned inconsistent multipart upload progress.');
432
481
  }
433
482
  sessionId = progress.sessionId;
434
483
  const received = new Set();
435
484
  let bytes = 0;
436
485
  for (const part of progress.receivedParts) {
437
- if (!Number.isInteger(part.partNumber) || part.partNumber < 1 || part.partNumber > partCount ||
438
- received.has(part.partNumber) || part.byteLength !== lengthOf(part.partNumber)) {
486
+ if (!Number.isInteger(part.partNumber) ||
487
+ part.partNumber < 1 ||
488
+ part.partNumber > partCount ||
489
+ received.has(part.partNumber) ||
490
+ part.byteLength !== lengthOf(part.partNumber)) {
439
491
  throw new Error('The server returned an invalid multipart part receipt.');
440
492
  }
441
493
  received.add(part.partNumber);
@@ -457,13 +509,18 @@ async function uploadMultipartFile(file, intent, protocol) {
457
509
  }
458
510
  const signed = await protocol.sign([partNumber]);
459
511
  inspect(signed?.progress);
460
- if (signed.sessionId !== sessionId || !Array.isArray(signed.parts) || signed.parts.length !== 1 ||
461
- signed.parts[0].partNumber !== partNumber || typeof signed.parts[0].url !== 'string') {
512
+ if (signed.sessionId !== sessionId ||
513
+ !Array.isArray(signed.parts) ||
514
+ signed.parts.length !== 1 ||
515
+ signed.parts[0].partNumber !== partNumber ||
516
+ typeof signed.parts[0].url !== 'string') {
462
517
  throw new Error('The server did not grant the requested multipart part.');
463
518
  }
464
519
  const receipt = await putFilePartToStorage({
465
- uploadUrl: signed.parts[0].url, filePath: file.filePath,
466
- offset: (partNumber - 1) * partSize, byteLength: lengthOf(partNumber),
520
+ uploadUrl: signed.parts[0].url,
521
+ filePath: file.filePath,
522
+ offset: (partNumber - 1) * partSize,
523
+ byteLength: lengthOf(partNumber),
467
524
  });
468
525
  const recorded = await protocol.record({ partNumber, ...receipt });
469
526
  const landed = inspect(recorded?.progress);
@@ -473,7 +530,8 @@ async function uploadMultipartFile(file, intent, protocol) {
473
530
  progress = recorded.progress;
474
531
  }
475
532
  const final = await protocol.status();
476
- if (inspect(final).size !== partCount || final.uploadedBytes !== file.size ||
533
+ if (inspect(final).size !== partCount ||
534
+ final.uploadedBytes !== file.size ||
477
535
  fs.statSync(file.filePath).size !== file.size) {
478
536
  throw new Error('The multipart upload is incomplete or the file changed during upload.');
479
537
  }
@@ -488,7 +546,10 @@ async function putFilePartToStorage(p) {
488
546
  let sent = 0;
489
547
  let ended = false;
490
548
  let etag;
491
- const stream = fs.createReadStream(p.filePath, { start: p.offset, end: p.offset + p.byteLength - 1 });
549
+ const stream = fs.createReadStream(p.filePath, {
550
+ start: p.offset,
551
+ end: p.offset + p.byteLength - 1,
552
+ });
492
553
  const fail = (message) => {
493
554
  if (settled)
494
555
  return;
@@ -506,7 +567,8 @@ async function putFilePartToStorage(p) {
506
567
  resolve({ etag, byteLength: sent });
507
568
  };
508
569
  const req = (url.protocol === 'http:' ? http : https).request(url, {
509
- method: 'PUT', headers: { 'Content-Length': String(p.byteLength) },
570
+ method: 'PUT',
571
+ headers: { 'Content-Length': String(p.byteLength) },
510
572
  }, (res) => {
511
573
  const status = res.statusCode ?? 0;
512
574
  const actualEtag = res.headers.etag;
@@ -517,14 +579,22 @@ async function putFilePartToStorage(p) {
517
579
  }
518
580
  res.on('error', () => fail('Storage multipart response failed.'));
519
581
  res.on('aborted', () => fail('Storage multipart response was interrupted.'));
520
- res.on('end', () => { etag = actualEtag; done(); });
582
+ res.on('end', () => {
583
+ etag = actualEtag;
584
+ done();
585
+ });
521
586
  res.resume();
522
587
  });
523
588
  req.on('error', () => fail('Storage multipart upload failed.'));
524
589
  req.setTimeout(60000, () => fail('Storage multipart upload timed out.'));
525
- stream.on('data', (chunk) => { sent += chunk.length; });
590
+ stream.on('data', (chunk) => {
591
+ sent += chunk.length;
592
+ });
526
593
  stream.on('error', () => fail('The multipart file could not be read.'));
527
- stream.on('end', () => { ended = true; done(); });
594
+ stream.on('end', () => {
595
+ ended = true;
596
+ done();
597
+ });
528
598
  stream.pipe(req);
529
599
  });
530
600
  }
@@ -30,6 +30,22 @@ type TaskActionContext = {
30
30
  * `assignTaskRemedies`), so a renderer lists every entry, not only the first.
31
31
  */
32
32
  export declare function taskActionRemedies(action: string, taskId: string, targetId: string | undefined, bin?: string, context?: TaskActionContext): TaskActionRemedy[];
33
+ /**
34
+ * The commands that settle a submitted Result waiting on a Review (`review_required`).
35
+ *
36
+ * The server offers `complete_task` and `request_changes` there, and neither maps through the
37
+ * table above. `request_changes` targets the Task, while `tasks review` needs the exact Result
38
+ * (`--result-id`), so the table leaves it unmapped; and `tasks complete` submits a NEW Result,
39
+ * where this one only needs closing. A caller that holds the Task passes its `currentResultId`,
40
+ * and gets the Review itself plus, when the server offers closing, the owner's close past it
41
+ * (OSK-33352).
42
+ *
43
+ * Accepting closes the Task. Its submitter cannot accept it (`TASK_REVIEW_SELF_ACCEPTANCE`), and a
44
+ * Task that requires the Review closes without one only for its owner, so each says who it is for.
45
+ */
46
+ export declare function reviewDecisionRemedies(taskId: string, resultId: string | undefined, bin?: string, options?: {
47
+ closable?: boolean;
48
+ }): TaskActionRemedy[];
33
49
  /** One row per remedy: the command, then what it does, with the notes lined up. */
34
50
  export declare function taskActionRemedyRows(remedies: readonly TaskActionRemedy[]): string[];
35
51
  /** The first command for an action. A renderer should list `taskActionRemedies` instead. */
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.taskActionRemedies = taskActionRemedies;
4
+ exports.reviewDecisionRemedies = reviewDecisionRemedies;
4
5
  exports.taskActionRemedyRows = taskActionRemedyRows;
5
6
  exports.taskActionCommand = taskActionCommand;
6
7
  const data_provider_1 = require("@skrr-ai/data-provider");
@@ -52,6 +53,44 @@ function taskActionRemedies(action, taskId, targetId, bin = 'skrr', context = {}
52
53
  };
53
54
  return commands[action] ? [{ command: `${bin} ${commands[action]}` }] : [];
54
55
  }
56
+ /**
57
+ * The commands that settle a submitted Result waiting on a Review (`review_required`).
58
+ *
59
+ * The server offers `complete_task` and `request_changes` there, and neither maps through the
60
+ * table above. `request_changes` targets the Task, while `tasks review` needs the exact Result
61
+ * (`--result-id`), so the table leaves it unmapped; and `tasks complete` submits a NEW Result,
62
+ * where this one only needs closing. A caller that holds the Task passes its `currentResultId`,
63
+ * and gets the Review itself plus, when the server offers closing, the owner's close past it
64
+ * (OSK-33352).
65
+ *
66
+ * Accepting closes the Task. Its submitter cannot accept it (`TASK_REVIEW_SELF_ACCEPTANCE`), and a
67
+ * Task that requires the Review closes without one only for its owner, so each says who it is for.
68
+ */
69
+ function reviewDecisionRemedies(taskId, resultId, bin = 'skrr', options = {}) {
70
+ const task = (0, shell_quote_1.shellQuoteArg)(taskId);
71
+ const result = resultId ? (0, shell_quote_1.shellQuoteArg)(resultId) : '<result-id>';
72
+ const review = `${bin} tasks review ${task} --result-id ${result}`;
73
+ // `--rationale` is named in the note rather than the command: a quoted placeholder would make that
74
+ // command the widest by far, and the aligned notes would pad every other row out to it.
75
+ return [
76
+ {
77
+ command: `${review} --decision accepted`,
78
+ what: 'accept it and close the Task (not its submitter)',
79
+ },
80
+ {
81
+ command: `${review} --decision changes_requested`,
82
+ what: 'request changes (say what with --rationale)',
83
+ },
84
+ ...(options.closable
85
+ ? [
86
+ {
87
+ command: `${bin} tasks move ${task} --status done`,
88
+ what: 'its owner closes it without a Review',
89
+ },
90
+ ]
91
+ : []),
92
+ ];
93
+ }
55
94
  /** One row per remedy: the command, then what it does, with the notes lined up. */
56
95
  function taskActionRemedyRows(remedies) {
57
96
  const width = Math.max(0, ...remedies.filter((r) => r.what).map((r) => r.command.length));
@@ -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
  /**
@@ -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 {