@cortexkit/opencode-openai-auth 1.9.4 → 1.9.6

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 (78) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/{codex-request-By530v1D.d.ts → codex-request-CZ16goZ6.d.ts} +20 -4
  3. package/dist/index-1kbr03m0.js +2 -0
  4. package/dist/{index-rrtsaz80.js → index-3mmdgz6r.js} +1 -1
  5. package/dist/index-5xs8nfcx.js +63 -0
  6. package/dist/index-7bv7pgy8.js +12 -0
  7. package/dist/{index-v1ztg103.js → index-cf0mrvqj.js} +1 -1
  8. package/dist/index-jqqeynjm.js +91 -0
  9. package/dist/index-qn927h9w.js +76 -0
  10. package/dist/{index-2bf808fw.js → index-s52j2h64.js} +1 -1
  11. package/dist/{index-7bjgmbx4.js → index-se7mn1wg.js} +1 -1
  12. package/dist/index-t52k32ab.js +8 -0
  13. package/dist/{index-jej9cfk7.js → index-tcaef7wq.js} +1 -1
  14. package/dist/{index-cmybrjbd.js → index-x8qjasc7.js} +1 -1
  15. package/dist/{index-g3gbp1m4.js → index-y4j7y8b8.js} +1 -1
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/{port-file-DXCxv8tU.d.ts → port-file-CEjki7bM.d.ts} +6 -1
  19. package/dist/rpc/port-file.d.ts +1 -1
  20. package/dist/rpc/port-file.js +1 -1
  21. package/dist/rpc/protocol.js +1 -1
  22. package/dist/rpc/rpc-client.d.ts +1 -1
  23. package/dist/rpc/rpc-client.js +1 -1
  24. package/dist/rpc/rpc-dir.js +1 -1
  25. package/dist/{rpc-client-CmaZW1by.d.ts → rpc-client-rWuV04C-.d.ts} +1 -1
  26. package/dist/sidebar-state.js +1 -1
  27. package/dist/{token-dcr3tgsk.js → token-djwdynff.js} +1 -1
  28. package/dist/token-util-0xt1ws82.js +1 -0
  29. package/dist/tui-preferences.js +1 -1
  30. package/dist/tui.d.ts +1 -1
  31. package/dist/v2/server.d.ts +1 -1
  32. package/dist/v2/server.js +3 -3
  33. package/package.json +5 -5
  34. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +74 -9
  35. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +36 -0
  36. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +2 -0
  37. package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +8 -0
  38. package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +7 -0
  39. package/src/tui-compiled/raw/shared/45bf5343bbbf9add-admission.js +17 -7
  40. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +2 -5
  41. package/src/tui-compiled/raw/shared/4ede5af6a878a14e-usage.js +145 -0
  42. package/src/tui-compiled/raw/shared/5f8cc863449a6c85-limits-namespace.js +34 -0
  43. package/src/tui-compiled/raw/shared/754d6017f8e419cf-builtins.js +38 -0
  44. package/src/tui-compiled/raw/shared/836fc615de6afbd9-settings.js +11 -4
  45. package/src/tui-compiled/raw/shared/97484d9bb98c705b-provider-state.js +5 -5
  46. package/src/tui-compiled/raw/shared/9d3fc9e37456504e-refresh.js +1 -1
  47. package/src/tui-compiled/raw/shared/9deae3c4da4fd63b-hooks.js +20 -5
  48. package/src/tui-compiled/raw/shared/a62a27a204266acd-attribution.js +3 -2
  49. package/src/tui-compiled/raw/shared/c14988621dc60a75-port-file.js +46 -4
  50. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +2 -0
  51. package/src/tui-compiled/raw/shared/cd94316a888b0a8e-schema.js +9 -4
  52. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +142 -47
  53. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +74 -9
  54. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +36 -0
  55. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +2 -0
  56. package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +8 -0
  57. package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +7 -0
  58. package/src/tui-compiled/runtime/shared/45bf5343bbbf9add-admission.js +17 -7
  59. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +2 -5
  60. package/src/tui-compiled/runtime/shared/4ede5af6a878a14e-usage.js +145 -0
  61. package/src/tui-compiled/runtime/shared/5f8cc863449a6c85-limits-namespace.js +34 -0
  62. package/src/tui-compiled/runtime/shared/754d6017f8e419cf-builtins.js +38 -0
  63. package/src/tui-compiled/runtime/shared/836fc615de6afbd9-settings.js +11 -4
  64. package/src/tui-compiled/runtime/shared/97484d9bb98c705b-provider-state.js +5 -5
  65. package/src/tui-compiled/runtime/shared/9d3fc9e37456504e-refresh.js +1 -1
  66. package/src/tui-compiled/runtime/shared/9deae3c4da4fd63b-hooks.js +20 -5
  67. package/src/tui-compiled/runtime/shared/a62a27a204266acd-attribution.js +3 -2
  68. package/src/tui-compiled/runtime/shared/c14988621dc60a75-port-file.js +46 -4
  69. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +2 -0
  70. package/src/tui-compiled/runtime/shared/cd94316a888b0a8e-schema.js +9 -4
  71. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +142 -47
  72. package/dist/index-2esezxst.js +0 -12
  73. package/dist/index-4p45bmbz.js +0 -63
  74. package/dist/index-6xz3n4qh.js +0 -91
  75. package/dist/index-81yvwra9.js +0 -8
  76. package/dist/index-hz6f9gpq.js +0 -2
  77. package/dist/index-xx3k2qbv.js +0 -76
  78. package/dist/token-util-gbd7jw6d.js +0 -1
@@ -1,4 +1,5 @@
1
1
  import { recordQuota } from "./a62a27a204266acd-attribution.js";
2
+ import { updatePoolLimitsNamespace, } from "./5f8cc863449a6c85-limits-namespace.js";
2
3
  import { initializePool, readPool, } from "./458b934e92490331-mutate.js";
3
4
  import { updateProviderStateRow, } from "./97484d9bb98c705b-provider-state.js";
4
5
  import { publication, publishRoster, } from "./83068c0dbe8a6f13-publication.js";
@@ -126,6 +127,7 @@ export function openPoolStore(options) {
126
127
  reorder: (ids, callOptions) => reorderRows(rt, ids, callOptions),
127
128
  readSettings: () => readPoolSettings(rt),
128
129
  updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
130
+ updateLimitsNamespace: (mutator) => updatePoolLimitsNamespace(rt, mutator),
129
131
  recordIdentity: (id, identity, attribution, callOptions) => recordRowIdentity(rt, id, identity, attribution, callOptions),
130
132
  refresh: (id, provider, callOptions) => refreshRow(rt, id, provider, callOptions),
131
133
  recordQuota: record,
@@ -1,4 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { runInsideCodec } from "./9deae3c4da4fd63b-hooks.js";
2
3
  /** Top-level key of the config file that holds everything the pool adds. */
3
4
  export const POOL_KEY = 'commonAuthPool';
4
5
  /** The pool schema this library reads and writes. */
@@ -182,7 +183,9 @@ export function stampFor(credential, credentialEpoch, binding, options = {}) {
182
183
  * digest the store writes.
183
184
  */
184
185
  export function providerStateDigest(codec, value) {
185
- const bound = codec?.credentialBound ? codec.credentialBound(value) : value;
186
+ const bound = codec?.credentialBound
187
+ ? runInsideCodec(() => codec.credentialBound?.(value))
188
+ : value;
186
189
  return createHash('sha256')
187
190
  .update(`provider-state\0${JSON.stringify(bound ?? null)}`)
188
191
  .digest('hex');
@@ -420,8 +423,10 @@ function parseEntry(raw, codec) {
420
423
  return undefined;
421
424
  if ('disabledReason' in raw && typeof raw.disabledReason !== 'string')
422
425
  return undefined;
423
- const quota = 'quota' in raw && codec.decode ? codec.decode(raw.quota) : raw.quota;
424
- if ('quota' in raw && !codec.validate(quota))
426
+ const quota = 'quota' in raw && codec.decode
427
+ ? runInsideCodec(() => codec.decode?.(raw.quota))
428
+ : raw.quota;
429
+ if ('quota' in raw && !runInsideCodec(() => codec.validate(quota)))
425
430
  return undefined;
426
431
  if ('staged' in raw && !parseReservation(raw.staged))
427
432
  return undefined;
@@ -666,7 +671,7 @@ function providerStateFields(account, credential, credentialEpoch, identity, cod
666
671
  const value = account[PROVIDER_STATE_KEY];
667
672
  // The value is validated before it is projected, so the projection only
668
673
  // ever sees a value of the shape the codec accepts.
669
- if (!codec?.validate(value))
674
+ if (!codec || !runInsideCodec(() => codec.validate(value)))
670
675
  return { providerStateDropped: 'invalid' };
671
676
  if (providerStateDigest(codec, value) !== digest)
672
677
  return { providerStateDropped: 'uncovered' };
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { lstat, mkdir, open, readFile, rename, rm, stat, } from "node:fs/promises";
3
3
  import { dirname, join } from "node:path";
4
- import { createPrivateBytes, createPrivateDirectoryExclusive, ensurePrivateDirectory, PrivateFileError, privateOperation, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from "./375d9cca2def037d-private-files.js";
4
+ import { createPrivateBytes, createPrivateDirectoryExclusive, ensurePrivateDirectory, isWindowsSharingViolation, PrivateFileError, privateOperation, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from "./375d9cca2def037d-private-files.js";
5
5
  import { LockOwnershipError, lockPathFor } from "./4825e03209d6ae3e-with-lock.js";
6
6
  /**
7
7
  * Create a new owner-only file and write `text` into it, failing with EEXIST if
@@ -367,54 +367,109 @@ export async function acquireRefreshFileLockWithClock(options) {
367
367
  else
368
368
  await rm(path, { recursive: true, force: true }).catch(() => { });
369
369
  }
370
- async function releaseEvictionMarker() {
371
- if (await ownsEvictionMarker()) {
372
- await removeLeaseObject(evictPath);
370
+ function isRetryableRemoval(error, path) {
371
+ if (!windowsPrivateFiles ||
372
+ !(error instanceof PrivateFileError) ||
373
+ error.stage !== 'remove' ||
374
+ error.path !== path)
375
+ return false;
376
+ // Native sharing/delete-pending errors use isWindowsSharingViolation.
377
+ // node:fs rm supplies only errno: EBUSY/EPERM can also mean a sharing refusal.
378
+ return (isWindowsSharingViolation(error) ||
379
+ (error.win32Code === undefined &&
380
+ error.reason === undefined &&
381
+ (error.code === 'EBUSY' || error.code === 'EPERM')));
382
+ }
383
+ async function removeOwnedLeaseObject(path, stillOwned, deadline = performance.now() + EVICT_TTL + 1_000) {
384
+ let original;
385
+ let delayMs = 5;
386
+ while (await stillOwned()) {
387
+ try {
388
+ await removeLeaseObject(path);
389
+ return;
390
+ }
391
+ catch (error) {
392
+ if (!isRetryableRemoval(error, path))
393
+ throw error;
394
+ original ??= error;
395
+ }
396
+ const remainingMs = deadline - performance.now();
397
+ if (remainingMs <= 0)
398
+ throw original;
399
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delayMs, remainingMs)));
400
+ if (performance.now() >= deadline)
401
+ throw original;
402
+ delayMs = Math.min(delayMs * 2, 50);
373
403
  }
374
404
  }
405
+ async function releaseEvictionMarker(deadline) {
406
+ let ownedDirectory;
407
+ await removeOwnedLeaseObject(evictPath, async () => {
408
+ if (!windowsPrivateFiles)
409
+ return ownsEvictionMarker();
410
+ const current = await lstat(evictPath).catch((error) => {
411
+ if (error.code !== 'ENOENT')
412
+ throw error;
413
+ return undefined;
414
+ });
415
+ if (!current ||
416
+ (ownedDirectory && !sameMarkerDirectory(ownedDirectory, current)))
417
+ return false;
418
+ if (await ownsEvictionMarker()) {
419
+ ownedDirectory = current;
420
+ return true;
421
+ }
422
+ if (!ownedDirectory)
423
+ return false;
424
+ // Recursive rm can delete owner.json before the directory delete fails.
425
+ // Only that same, now-ownerless directory is still ours to clean up.
426
+ try {
427
+ await stat(evictOwnerPath);
428
+ return false;
429
+ }
430
+ catch (error) {
431
+ if (error.code !== 'ENOENT')
432
+ throw error;
433
+ return true;
434
+ }
435
+ }, deadline);
436
+ }
375
437
  // Returns whether the directory at the marker path was still the one this
376
438
  // process created when its owner write failed. Only then is the failure ours
377
439
  // to report: a gone or replaced directory is a lost race.
378
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
440
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
379
441
  // Best effort only: never throws, so the original owner-write error below
380
442
  // keeps explaining the failure. Removes the directory this process just
381
443
  // created when its owner write failed, and leaves a contender's
382
444
  // replacement alone when the identities differ.
383
445
  if (!created)
384
446
  return false;
385
- let current;
386
- try {
387
- const st = await lstat(evictPath);
388
- current = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
389
- }
390
- catch {
391
- // Renamed away by a contender's steal: nothing of ours left to clean.
392
- return false;
393
- }
394
- if (!sameMarkerDirectory(created, current))
395
- return false;
396
- // Remove only an ownerless directory. An owner file that appeared after
397
- // our failed write belongs to someone: ours goes through
398
- // releaseEvictionMarker in the caller, and a contender's must stay, since
399
- // it may be holding the marker right now.
447
+ let stillOurs = false;
400
448
  try {
401
- await stat(evictOwnerPath);
402
- return true;
403
- }
404
- catch (error) {
405
- if (error.code !== 'ENOENT')
406
- return true;
407
- }
408
- try {
409
- await removeLeaseObject(evictPath);
449
+ await removeOwnedLeaseObject(evictPath, async () => {
450
+ stillOurs = false;
451
+ const st = await lstat(evictPath).catch(() => undefined);
452
+ if (!st || !sameMarkerDirectory(created, st))
453
+ return false;
454
+ stillOurs = true;
455
+ // Recheck both identity and absence of an owner before every attempt;
456
+ // a contender's replacement or newly published owner must stay.
457
+ try {
458
+ await stat(evictOwnerPath);
459
+ return false;
460
+ }
461
+ catch (error) {
462
+ return error.code === 'ENOENT';
463
+ }
464
+ }, deadline);
410
465
  }
411
466
  catch {
412
467
  // A removal failure keeps the stale marker recoverable later; it must
413
468
  // never mask the original owner-write error.
414
469
  }
415
- return true;
470
+ return stillOurs;
416
471
  }
417
- async function tryAcquireEvictionMarker() {
472
+ async function tryAcquireEvictionMarker(deadline) {
418
473
  if (windowsPrivateFiles)
419
474
  await createPrivateDirectoryExclusive(evictPath);
420
475
  else
@@ -455,11 +510,11 @@ export async function acquireRefreshFileLockWithClock(options) {
455
510
  // A race code while our own directory is still in place is not a lost
456
511
  // race but a write that fails here every time: report it, rather than
457
512
  // retrying the same failure until a deadline hides the cause.
458
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
513
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
459
514
  if (isLostMarkerRaceError(error) && !stillOurs)
460
515
  return false;
461
516
  try {
462
- await releaseEvictionMarker();
517
+ await releaseEvictionMarker(deadline);
463
518
  }
464
519
  catch {
465
520
  // Removal must never mask the original owner-write error.
@@ -470,7 +525,7 @@ export async function acquireRefreshFileLockWithClock(options) {
470
525
  await options.onStep('eviction-marker-acquired');
471
526
  return true;
472
527
  }
473
- async function recoverStaleEvictionMarker() {
528
+ async function recoverStaleEvictionMarker(deadline) {
474
529
  let evictStat;
475
530
  try {
476
531
  evictStat = await stat(evictPath);
@@ -529,12 +584,26 @@ export async function acquireRefreshFileLockWithClock(options) {
529
584
  }
530
585
  if (options.onStep)
531
586
  await options.onStep('stale-marker-claimed');
532
- await removeLeaseObject(claimedPath);
587
+ const claimedIdentity = windowsPrivateFiles
588
+ ? await lstat(claimedPath)
589
+ : undefined;
590
+ // The unique renamed claim is ours, not the current marker path where a
591
+ // successor may already be working.
592
+ await removeOwnedLeaseObject(claimedPath, async () => {
593
+ if (!claimedIdentity)
594
+ return true;
595
+ const current = await lstat(claimedPath).catch((error) => {
596
+ if (error.code !== 'ENOENT')
597
+ throw error;
598
+ return undefined;
599
+ });
600
+ return !!current && sameMarkerDirectory(claimedIdentity, current);
601
+ }, deadline);
533
602
  return 'recovered';
534
603
  }
535
- async function withEvictionMarker(action) {
604
+ async function withEvictionMarker(action, deadline) {
536
605
  try {
537
- if (!(await tryAcquireEvictionMarker()))
606
+ if (!(await tryAcquireEvictionMarker(deadline)))
538
607
  return false;
539
608
  }
540
609
  catch (error) {
@@ -555,12 +624,28 @@ export async function acquireRefreshFileLockWithClock(options) {
555
624
  }
556
625
  throw error;
557
626
  }
627
+ let actionFailed = false;
628
+ let actionError;
558
629
  try {
559
630
  await action();
560
631
  }
561
- finally {
562
- await releaseEvictionMarker();
632
+ catch (error) {
633
+ actionFailed = true;
634
+ actionError = error;
635
+ }
636
+ try {
637
+ await releaseEvictionMarker(deadline);
638
+ }
639
+ catch (error) {
640
+ // Cleanup sharing failures must not replace the lock's original
641
+ // sharing refusal when both removals exhaust the same deadline.
642
+ if (isRetryableRemoval(actionError, lockPath) &&
643
+ isRetryableRemoval(error, evictPath))
644
+ throw actionError;
645
+ throw error;
563
646
  }
647
+ if (actionFailed)
648
+ throw actionError;
564
649
  return true;
565
650
  }
566
651
  // Marker loss after a write may mean another contender has taken over.
@@ -847,6 +932,7 @@ export async function acquireRefreshFileLockWithClock(options) {
847
932
  // wall-clock adjustments cannot extend the retry deadline.
848
933
  const deadline = performance.now() + EVICT_TTL + 1_000;
849
934
  let delayMs = 5;
935
+ let removalError;
850
936
  for (;;) {
851
937
  try {
852
938
  let removalConfirmed = false;
@@ -873,7 +959,7 @@ export async function acquireRefreshFileLockWithClock(options) {
873
959
  return;
874
960
  await removeLeaseObject(lockPath);
875
961
  removalConfirmed = true;
876
- });
962
+ }, deadline);
877
963
  if (markerAcquired) {
878
964
  if (windowsPrivateFiles && !removalConfirmed)
879
965
  throw new PrivateFileError(lockPath, 'release-not-confirmed', {
@@ -884,25 +970,34 @@ export async function acquireRefreshFileLockWithClock(options) {
884
970
  }
885
971
  if (signal?.aborted)
886
972
  return;
887
- await recoverStaleEvictionMarker();
973
+ await recoverStaleEvictionMarker(deadline);
888
974
  }
889
975
  catch (error) {
890
- if (windowsPrivateFiles)
891
- throw error;
892
- return;
976
+ if (!isRetryableRemoval(error, lockPath)) {
977
+ if (windowsPrivateFiles)
978
+ throw error;
979
+ return;
980
+ }
981
+ // Like rename, a fenced delete can be refused by a reader's Windows
982
+ // handle without invalidating ownership. Drop the marker, back off,
983
+ // and re-confirm the owner under a new marker before trying again.
984
+ removalError ??= error;
893
985
  }
894
986
  const remainingMs = deadline - performance.now();
895
987
  if (remainingMs <= 0)
896
988
  break;
897
989
  await new Promise((resolve) => setTimeout(resolve, Math.min(delayMs, remainingMs)));
990
+ if (windowsPrivateFiles && performance.now() >= deadline)
991
+ break;
898
992
  delayMs = Math.min(delayMs * 2, 50);
899
993
  }
900
994
  // Do not delete by pathname without the marker: bounded retries leave the
901
995
  // lease to expire rather than risking removal of a successor's lock.
902
996
  if (windowsPrivateFiles)
903
- throw new PrivateFileError(lockPath, 'release-not-confirmed', {
904
- code: 'ETIMEDOUT',
905
- });
997
+ throw (removalError ??
998
+ new PrivateFileError(lockPath, 'release-not-confirmed', {
999
+ code: 'ETIMEDOUT',
1000
+ }));
906
1001
  },
907
1002
  };
908
1003
  }
@@ -6,6 +6,7 @@ import { readClaustrumEnrollmentToken } from "./b9588ad4725c1d10-enrollment.js";
6
6
  import { ClaustrumConsumerError } from "./ca0fccaba1d87af4-errors.js";
7
7
  import { CUSTODY_PLACEHOLDER_PREFIX } from "./d9d2892a4c371301-host-slot.js";
8
8
  import { drainShutdown, shutdownWarning } from "./a670cb7f5987bc1b-shutdown.js";
9
+ import { ScopedUsageReporter, } from "./4ede5af6a878a14e-usage.js";
9
10
  import { ScopedRosterWatch, } from "./dc9290c2a7552ba6-watch.js";
10
11
  /** Only a new version of the same account may replace an in-flight 401. */
11
12
  export function isScopedCredentialRotation(served, current) {
@@ -28,6 +29,14 @@ function scopedRetryReason(served, current) {
28
29
  return 'rotated';
29
30
  }
30
31
  const defaultLogger = createLogger('claustrum');
32
+ function checkedEnrollmentToken(value) {
33
+ if (!/^[0-9a-f]{64}$/.test(value.token) ||
34
+ !Number.isSafeInteger(value.token_generation) ||
35
+ value.token_generation < 1) {
36
+ throw new ClaustrumConsumerError('invalid-token', 'Invalid Claustrum enrollment token');
37
+ }
38
+ return value.token;
39
+ }
31
40
  // Opt-in diagnostics let tests retain wait phases without logging each vault read.
32
41
  const phaseDiagnostics = channel('common-auth.claustrum.phases');
33
42
  /**
@@ -183,6 +192,8 @@ export class ClaustrumScopedCustody {
183
192
  #reports = new WeakMap();
184
193
  #kept = new Map();
185
194
  #keptAttempts = new WeakMap();
195
+ #usage;
196
+ #usageServed = new Map();
186
197
  #setTimeout;
187
198
  #clearTimeout;
188
199
  #outage = false;
@@ -197,6 +208,7 @@ export class ClaustrumScopedCustody {
197
208
  #watches = new Set();
198
209
  #tokenReads = new Set();
199
210
  #warnShutdown;
211
+ #onDrainTimeout;
200
212
  #disposing;
201
213
  constructor(options) {
202
214
  const tokenPath = options.tokenPath;
@@ -218,6 +230,14 @@ export class ClaustrumScopedCustody {
218
230
  this.#warnShutdown = shutdownWarning(this.#logger);
219
231
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
220
232
  this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
233
+ this.#usage = new ScopedUsageReporter({
234
+ client: this.#client,
235
+ owns: (id) => this.#usageServed.has(id),
236
+ token: async () => checkedEnrollmentToken(await this.#readToken()),
237
+ logger: this.#logger,
238
+ setTimeout: this.#setTimeout,
239
+ clearTimeout: this.#clearTimeout,
240
+ });
221
241
  }
222
242
  /** A watch losing its transport is the same outage as an unreachable read. */
223
243
  transportLost(error) {
@@ -303,12 +323,7 @@ export class ClaustrumScopedCustody {
303
323
  });
304
324
  }
305
325
  this.#check(signal);
306
- if (!/^[0-9a-f]{64}$/.test(value.token) ||
307
- !Number.isSafeInteger(value.token_generation) ||
308
- value.token_generation < 1) {
309
- throw new ClaustrumConsumerError('invalid-token', 'Invalid Claustrum enrollment token');
310
- }
311
- return value.token;
326
+ return checkedEnrollmentToken(value);
312
327
  }
313
328
  async #call(operation, signal) {
314
329
  this.#check(signal);
@@ -370,6 +385,7 @@ export class ClaustrumScopedCustody {
370
385
  }
371
386
  catch (error) {
372
387
  this.#kept.clear();
388
+ this.#clearUsageOwnership();
373
389
  throw error;
374
390
  }
375
391
  if (phaseDiagnostics.hasSubscribers)
@@ -473,11 +489,19 @@ export class ClaustrumScopedCustody {
473
489
  else {
474
490
  this.reachable();
475
491
  this.#kept.clear();
492
+ this.#clearUsageOwnership();
476
493
  }
477
494
  }
478
495
  /** Discard bearer material when a route is removed, declined or rebound. */
479
496
  forget(credentialId) {
480
497
  this.#kept.delete(credentialId);
498
+ this.#usageServed.delete(credentialId);
499
+ this.#usage.forget(credentialId);
500
+ }
501
+ #clearUsageOwnership() {
502
+ for (const id of this.#usageServed.keys())
503
+ this.#usage.forget(id);
504
+ this.#usageServed.clear();
481
505
  }
482
506
  /** Apply an already-held roster; this never fetches credentials or writes it. */
483
507
  retain(identities) {
@@ -490,6 +514,14 @@ export class ClaustrumScopedCustody {
490
514
  identity.accountIdentity !== kept.attempt.expectedAccountIdentity)
491
515
  this.forget(id);
492
516
  }
517
+ for (const [id, served] of this.#usageServed) {
518
+ const identity = current.get(id);
519
+ if (!identity?.enabled ||
520
+ identity.state !== 'active' ||
521
+ identity.credentialType !== served.credentialType ||
522
+ identity.accountIdentity !== served.accountIdentity)
523
+ this.forget(id);
524
+ }
493
525
  }
494
526
  /** A frozen, non-secret summary for a plugin's status display. */
495
527
  keptReceiptState() {
@@ -527,6 +559,7 @@ export class ClaustrumScopedCustody {
527
559
  }
528
560
  catch (error) {
529
561
  this.#kept.clear();
562
+ this.#clearUsageOwnership();
530
563
  throw error;
531
564
  }
532
565
  if (this.#outage && kept) {
@@ -536,6 +569,7 @@ export class ClaustrumScopedCustody {
536
569
  try {
537
570
  const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
538
571
  this.#kept.set(credentialId, { attempt, routeId, since: null });
572
+ this.#usageServed.set(credentialId, { ...identity });
539
573
  return attempt;
540
574
  }
541
575
  catch (error) {
@@ -750,6 +784,25 @@ export class ClaustrumScopedCustody {
750
784
  },
751
785
  };
752
786
  }
787
+ /**
788
+ * Queue reply quota metadata and return synchronously. Pass rate-limit
789
+ * headers only, never tokens: the library does not filter header names.
790
+ * Only credentials served by this custody and retained in its roster report.
791
+ * Hosts managing their own roster must call retain() when that roster changes.
792
+ */
793
+ reportUsage(input) {
794
+ if (this.#closed)
795
+ return;
796
+ try {
797
+ this.#usage.report(input.credentialId, input.reading);
798
+ }
799
+ catch {
800
+ // Quota bookkeeping must never reject a provider request.
801
+ }
802
+ }
803
+ usageReportState() {
804
+ return this.#usage.state();
805
+ }
753
806
  close() {
754
807
  if (this.#closed)
755
808
  return;
@@ -761,12 +814,24 @@ export class ClaustrumScopedCustody {
761
814
  watch.stop();
762
815
  this.#watches.clear();
763
816
  this.#kept.clear();
764
- this.#client.close();
817
+ const usage = this.#usage.close();
818
+ if (usage) {
819
+ this.#tokenReads.add(usage);
820
+ void usage.then(() => this.#tokenReads.delete(usage));
821
+ }
822
+ else
823
+ this.#client.close();
824
+ this.#disposing = drainShutdown(this.#tokenReads, (count) => (this.#onDrainTimeout ?? this.#warnShutdown)(count)).finally(() => {
825
+ this.#usage.drop();
826
+ this.#usageServed.clear();
827
+ if (usage)
828
+ this.#client.close();
829
+ });
765
830
  }
766
- /** Stop immediately; allow token reads 2 s and share an owner's timeout warning. */
831
+ /** Stop accepting work; give token reads and reply reports one shared 2 s drain. */
767
832
  async dispose(onTimeout = this.#warnShutdown) {
833
+ this.#onDrainTimeout = onTimeout;
768
834
  this.close();
769
- this.#disposing ??= drainShutdown(this.#tokenReads, onTimeout);
770
835
  await this.#disposing;
771
836
  }
772
837
  }
@@ -738,6 +738,42 @@ export class ClaustrumConsumer {
738
738
  combined.dispose();
739
739
  }
740
740
  }
741
+ /**
742
+ * Queue reply quota metadata without waiting or throwing. Pass rate-limit
743
+ * headers only, never tokens: the library does not filter header names.
744
+ * The credential must have been served by this host and still belong to the route.
745
+ */
746
+ reportUsage(input) {
747
+ if (this.#shutdown.signal.aborted)
748
+ return;
749
+ try {
750
+ const row = this.#roster?.rows.find((row) => row.routeId === input.routeId);
751
+ if (!row?.enabled ||
752
+ row.state !== 'active' ||
753
+ (row.credentialId !== input.credentialId &&
754
+ !row.aliases?.includes(input.credentialId)))
755
+ return;
756
+ if (this.#hub) {
757
+ if (this.#lease && this.#hub.leaseLive(this.#lease))
758
+ this.#lease.custody.reportUsage(input);
759
+ }
760
+ else
761
+ this.#custody?.reportUsage(input);
762
+ }
763
+ catch {
764
+ // Quota bookkeeping must never reject a provider request.
765
+ }
766
+ }
767
+ usageReportState() {
768
+ try {
769
+ return ((this.#hub
770
+ ? this.#lease?.custody
771
+ : this.#custody)?.usageReportState() ?? { pending: 0, inFlight: false, dropped: 0 });
772
+ }
773
+ catch {
774
+ return { pending: 0, inFlight: false, dropped: 0 };
775
+ }
776
+ }
741
777
  async reportFailure(attempt, status, source) {
742
778
  this.#assertOpen();
743
779
  if (this.#hub) {
@@ -209,6 +209,7 @@ export function projectVaultRoster(previous, inventory, options = {}) {
209
209
  return {
210
210
  version: 1,
211
211
  view: inventory.view,
212
+ ...(previous?.limits !== undefined && { limits: previous.limits }),
212
213
  complete,
213
214
  ...(!complete && {
214
215
  rejected: inventory.skipped.map((record) => ({
@@ -319,6 +320,7 @@ function decodeRoster(value) {
319
320
  // that was used whole, so it reads as complete.
320
321
  complete: value.complete !== false,
321
322
  ...(rejected && { rejected }),
323
+ ...(value.limits !== undefined && { limits: value.limits }),
322
324
  rows,
323
325
  declined,
324
326
  };
@@ -523,6 +523,14 @@ export class ClaustrumDiscoveryHub {
523
523
  check();
524
524
  return custody.reportFailure(attempt, status, source);
525
525
  },
526
+ reportUsage: (input) => {
527
+ if (!state.released && !generation.ended)
528
+ custody.reportUsage(input);
529
+ },
530
+ usageReportState: () => {
531
+ check();
532
+ return custody.usageReportState();
533
+ },
526
534
  forget: (credentialId) => {
527
535
  check();
528
536
  custody.forget(credentialId);
@@ -93,6 +93,13 @@ export class PrivateFileError extends Error {
93
93
  this.reason = detail?.reason;
94
94
  }
95
95
  }
96
+ /** Native sharing and delete-pending errors reveal neither ownership nor expiry. */
97
+ export function isWindowsSharingViolation(error) {
98
+ return (windowsPrivateFiles &&
99
+ error instanceof PrivateFileError &&
100
+ error.reason === 'io-error' &&
101
+ (error.win32Code === 32 || error.win32Code === 303));
102
+ }
96
103
  export async function privateOperation(path, stage, operation) {
97
104
  try {
98
105
  return await operation();