@cortexkit/opencode-openai-auth 1.12.0 → 1.14.0

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 (55) hide show
  1. package/dist/bin.js +9 -9
  2. package/dist/{codex-request-DFeGDzpN.d.ts → codex-request-Cl6zEfsR.d.ts} +21 -3
  3. package/dist/{index-5p6vw484.js → index-1abcvt9p.js} +1 -1
  4. package/dist/{index-2xsz3z63.js → index-3c9pk6zn.js} +2 -2
  5. package/dist/{index-dcvxs9xj.js → index-4tpttpjw.js} +1 -1
  6. package/dist/index-4zpxwh8y.js +91 -0
  7. package/dist/{index-7p1s64b4.js → index-a9tzfpxy.js} +1 -1
  8. package/dist/index-bc2d4vma.js +64 -0
  9. package/dist/{index-wtmxk263.js → index-f7t7cc9b.js} +2 -2
  10. package/dist/{index-7qztyb1b.js → index-nfbmjq6g.js} +2 -2
  11. package/dist/{index-3pm1cvhy.js → index-q111b2h5.js} +1 -1
  12. package/dist/{index-3nwj0h10.js → index-wap9mf5f.js} +2 -2
  13. package/dist/{index-p4qaa85r.js → index-xxmaf5ks.js} +2 -2
  14. package/dist/index-yew3mp47.js +76 -0
  15. package/dist/index-zcpher1w.js +8 -0
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/rpc/port-file.js +1 -1
  19. package/dist/rpc/protocol.js +1 -1
  20. package/dist/rpc/rpc-client.js +1 -1
  21. package/dist/rpc/rpc-dir.js +1 -1
  22. package/dist/sidebar-state.js +1 -1
  23. package/dist/{token-dr80qm6g.js → token-6x4q5r2r.js} +1 -1
  24. package/dist/token-util-54mhq85x.js +1 -0
  25. package/dist/tui-preferences.js +1 -1
  26. package/dist/v2/server.d.ts +1 -1
  27. package/dist/v2/server.js +3 -3
  28. package/package.json +8 -7
  29. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +89 -31
  30. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +19 -13
  31. package/src/tui-compiled/raw/shared/549daf371622c304-index.tsx +49 -607
  32. package/src/tui-compiled/raw/shared/723b00f96290a097-lock-record.js +55 -0
  33. package/src/tui-compiled/raw/shared/94f53cfd572ba4bb-availability.js +9 -1
  34. package/src/tui-compiled/raw/shared/a75d0d866c227b3f-index.tsx +681 -0
  35. package/src/tui-compiled/raw/shared/abd062d633e29fd2-pool-routing.js +21 -15
  36. package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +110 -2
  37. package/src/tui-compiled/raw/shared/c97089ed4243981c-host.js +11 -7
  38. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +148 -92
  39. package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +1 -1
  40. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +89 -31
  41. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +19 -13
  42. package/src/tui-compiled/runtime/shared/549daf371622c304-index.js +36 -674
  43. package/src/tui-compiled/runtime/shared/723b00f96290a097-lock-record.js +55 -0
  44. package/src/tui-compiled/runtime/shared/94f53cfd572ba4bb-availability.js +9 -1
  45. package/src/tui-compiled/runtime/shared/a75d0d866c227b3f-index.js +678 -0
  46. package/src/tui-compiled/runtime/shared/abd062d633e29fd2-pool-routing.js +21 -15
  47. package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +110 -2
  48. package/src/tui-compiled/runtime/shared/c97089ed4243981c-host.js +11 -7
  49. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +148 -92
  50. package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +1 -1
  51. package/dist/index-2egbrywb.js +0 -8
  52. package/dist/index-dqk0c7wr.js +0 -64
  53. package/dist/index-n5jtwtrs.js +0 -76
  54. package/dist/index-phgm1zwn.js +0 -91
  55. package/dist/token-util-97td5ex3.js +0 -1
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { link, lstat, mkdir, open, readFile, rename, rm, stat, } from "node:fs/promises";
3
3
  import { dirname, join } from "node:path";
4
+ import { DisappearedLockRecordError, isWindowsAccessDeniedCreate, isWindowsAccessDeniedRead, readLockRecord, } from "./723b00f96290a097-lock-record.js";
4
5
  import { createPrivateBytes, createPrivateDirectoryExclusive, ensurePrivateDirectory, isWindowsSharingViolation, PrivateFileError, privateOperation, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from "./375d9cca2def037d-private-files.js";
5
6
  import { LockOwnershipError, lockPathFor } from "./4825e03209d6ae3e-with-lock.js";
6
7
  let leaseCreationTestHooks;
@@ -192,17 +193,22 @@ export async function acquireRefreshFileLockWithClock(options) {
192
193
  const evictOwnerId = randomUUID();
193
194
  const EVICT_TTL = 5_000;
194
195
  const MAX_STEAL_ATTEMPTS = 8;
196
+ function isChangingLockCreate(error) {
197
+ return (windowsPrivateFiles &&
198
+ (isWindowsAccessDeniedCreate(error, [lockPath], 'create') ||
199
+ isWindowsAccessDeniedCreate(error, [evictPath], 'directory-create')));
200
+ }
195
201
  async function readOwner() {
196
202
  if (windowsPrivateFiles) {
197
203
  try {
198
- return JSON.parse(await readPrivateText(lockPath, true));
204
+ return JSON.parse(await readLockRecord(lockPath, () => readPrivateText(lockPath, true)));
199
205
  }
200
206
  catch (error) {
201
207
  if (error.code !== 'EISDIR' &&
202
208
  error.reason !== 'wrong-kind')
203
209
  throw error;
204
- await verifyPrivate(lockPath, 'directory', true);
205
- return JSON.parse(await readPrivateText(legacyOwnerPath, true));
210
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, 'directory', true));
211
+ return JSON.parse(await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true)));
206
212
  }
207
213
  }
208
214
  try {
@@ -280,8 +286,8 @@ export async function acquireRefreshFileLockWithClock(options) {
280
286
  await options.onStep('lease-contention-read-ready');
281
287
  try {
282
288
  if (code === 'EISDIR') {
283
- await verifyPrivate(lockPath, 'directory', true);
284
- await readPrivateText(legacyOwnerPath, true);
289
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, 'directory', true));
290
+ await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true));
285
291
  }
286
292
  else
287
293
  await readOwner();
@@ -337,6 +343,10 @@ export async function acquireRefreshFileLockWithClock(options) {
337
343
  owner = await readOwner();
338
344
  }
339
345
  catch (error) {
346
+ // A delete-pending owner that disappeared is a create opportunity,
347
+ // never an ownerless legacy directory eligible for stale eviction.
348
+ if (error instanceof DisappearedLockRecordError)
349
+ return { status: 'missing' };
340
350
  if (windowsPrivateFiles &&
341
351
  error.code !== 'ENOENT')
342
352
  throw error;
@@ -395,7 +405,7 @@ export async function acquireRefreshFileLockWithClock(options) {
395
405
  // Fail-closed: any read error means we do NOT own the marker.
396
406
  async function ownsEvictionMarker() {
397
407
  try {
398
- const owner = JSON.parse(await readPrivateText(evictOwnerPath, windowsPrivateFiles));
408
+ const owner = JSON.parse(await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, windowsPrivateFiles)));
399
409
  return owner?.ownerId === evictOwnerId;
400
410
  }
401
411
  catch (error) {
@@ -581,7 +591,7 @@ export async function acquireRefreshFileLockWithClock(options) {
581
591
  }
582
592
  if (windowsPrivateFiles) {
583
593
  try {
584
- await verifyPrivate(evictPath, 'directory', true);
594
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, 'directory', true));
585
595
  }
586
596
  catch (error) {
587
597
  // The marker's holder can remove it between the stat above and this
@@ -654,8 +664,8 @@ export async function acquireRefreshFileLockWithClock(options) {
654
664
  if (error.code === 'EEXIST') {
655
665
  if (windowsPrivateFiles) {
656
666
  try {
657
- await verifyPrivate(evictPath, 'directory', true);
658
- await readPrivateText(evictOwnerPath, true);
667
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, 'directory', true));
668
+ await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, true));
659
669
  }
660
670
  catch (ownerError) {
661
671
  // A marker removed by its holder after the failed create is free:
@@ -681,10 +691,16 @@ export async function acquireRefreshFileLockWithClock(options) {
681
691
  await releaseEvictionMarker(deadline);
682
692
  }
683
693
  catch (error) {
684
- // Cleanup sharing failures must not replace the lock's original
685
- // sharing refusal when both removals exhaust the same deadline.
686
- if (isRetryableRemoval(actionError, lockPath) &&
687
- isRetryableRemoval(error, evictPath))
694
+ // Cleanup IO failures must not replace the original lock refusal when
695
+ // both operations use the same deadline.
696
+ if ((isRetryableRemoval(actionError, lockPath) ||
697
+ isWindowsAccessDeniedRead(actionError, [
698
+ lockPath,
699
+ legacyOwnerPath,
700
+ evictOwnerPath,
701
+ ])) &&
702
+ (isRetryableRemoval(error, evictPath) ||
703
+ isWindowsAccessDeniedRead(error, [evictOwnerPath])))
688
704
  throw actionError;
689
705
  throw error;
690
706
  }
@@ -705,7 +721,8 @@ export async function acquireRefreshFileLockWithClock(options) {
705
721
  owner = await readOwner();
706
722
  }
707
723
  catch (error) {
708
- if (windowsPrivateFiles)
724
+ if (windowsPrivateFiles &&
725
+ !(error instanceof DisappearedLockRecordError))
709
726
  throw error;
710
727
  return;
711
728
  }
@@ -789,7 +806,9 @@ export async function acquireRefreshFileLockWithClock(options) {
789
806
  }
790
807
  }
791
808
  catch (error) {
792
- if (windowsPrivateFiles && error instanceof PrivateFileError) {
809
+ if (windowsPrivateFiles &&
810
+ error instanceof PrivateFileError &&
811
+ !isChangingLockCreate(error)) {
793
812
  terminalIOError = error;
794
813
  recordLoss('renewal-failed');
795
814
  shouldReschedule = false;
@@ -844,90 +863,112 @@ export async function acquireRefreshFileLockWithClock(options) {
844
863
  }
845
864
  return null;
846
865
  }
847
- let acquired = await tryAcquire();
866
+ let acquired = false;
867
+ let changingCreateError;
868
+ try {
869
+ acquired = await tryAcquire();
870
+ }
871
+ catch (error) {
872
+ if (!isChangingLockCreate(error))
873
+ throw error;
874
+ changingCreateError = error;
875
+ }
848
876
  if (!acquired) {
849
877
  for (let attempt = 0; attempt < MAX_STEAL_ATTEMPTS; attempt++) {
850
- acquired = await tryAcquire();
851
- if (acquired)
852
- break;
853
- const observed = await readLockState();
854
- if (observed.status === 'live')
855
- return contended();
856
- // Absence is a create opportunity, never evidence of an expired lease.
857
- if (observed.status === 'missing')
858
- continue;
859
- if (options.onStep)
860
- await options.onStep('stale-lock-observed');
861
878
  try {
862
- if (!(await tryAcquireEvictionMarker())) {
863
- await backoff();
864
- continue;
865
- }
866
- }
867
- catch (evictError) {
868
- const code = evictError.code;
869
- if (code !== 'EEXIST')
870
- throw evictError;
871
- const recovered = await recoverStaleEvictionMarker();
872
- if (recovered === 'fresh')
873
- return null;
874
- await backoff();
875
- continue;
876
- }
877
- try {
878
- const confirmed = await readLockState();
879
- if (confirmed.status === 'live')
879
+ acquired = await tryAcquire();
880
+ if (acquired)
881
+ break;
882
+ const observed = await readLockState();
883
+ if (observed.status === 'live')
880
884
  return contended();
881
- if (!sameStaleLock(observed.identity, confirmed))
885
+ // Absence is a create opportunity, never evidence of an expired lease.
886
+ if (observed.status === 'missing')
882
887
  continue;
883
- // Verify marker ownership before removing a lock found not live.
884
- if (!(await ownsEvictionMarker()))
885
- return null;
886
888
  if (options.onStep)
887
- await options.onStep('stale-lock-confirmed');
888
- // The onStep callback can pause while another contender renames
889
- // our marker, so verify ownership again after the callback.
890
- if (!(await ownsEvictionMarker()))
891
- return null;
892
- // Do not await a callback between this ownership check and the lock read.
893
- const current = await readLockState(false);
894
- if (!sameStaleLock(observed.identity, current))
889
+ await options.onStep('stale-lock-observed');
890
+ try {
891
+ if (!(await tryAcquireEvictionMarker())) {
892
+ await backoff();
893
+ continue;
894
+ }
895
+ }
896
+ catch (evictError) {
897
+ const code = evictError.code;
898
+ if (code !== 'EEXIST')
899
+ throw evictError;
900
+ const recovered = await recoverStaleEvictionMarker();
901
+ if (recovered === 'fresh')
902
+ return null;
903
+ await backoff();
895
904
  continue;
896
- // The final read and removal are not atomic. While this stale file
897
- // exists, wx cannot create a successor; the marker excludes other
898
- // evictors and release/renewal. An expired holder cannot renew: renewal
899
- // rechecks expiry and marker ownership immediately before publishing.
900
- // With the marker still owned, cooperating users cannot replace it in
901
- // this window. Arbitrary suspension across marker expiry or filesystem
902
- // changes still need a kernel lock for an atomic guarantee.
903
- await removeLeaseObject(lockPath);
904
- // Fence check 3: re-verify ownership after removing the stale lock.
905
- if (!(await ownsEvictionMarker()))
906
- return null;
907
- if (options.onStep)
908
- await options.onStep('stale-lock-removed');
909
- acquired = await tryAcquire();
910
- if (!acquired)
911
- return null;
912
- if (options.onStep)
913
- await options.onStep('stale-lock-recreated');
914
- // Fence check 4: re-verify ownership after acquiring the lock. If the
915
- // marker was stolen between tryAcquire and this check, release the
916
- // just-acquired lock and return null (fail-closed).
917
- if (!(await ownsEvictionMarker())) {
918
- await relinquishLockAfterMarkerLoss();
919
- acquired = false;
920
- return null;
921
905
  }
922
- break;
906
+ try {
907
+ const confirmed = await readLockState();
908
+ if (confirmed.status === 'live')
909
+ return contended();
910
+ if (!sameStaleLock(observed.identity, confirmed))
911
+ continue;
912
+ // Verify marker ownership before removing a lock found not live.
913
+ if (!(await ownsEvictionMarker()))
914
+ return null;
915
+ if (options.onStep)
916
+ await options.onStep('stale-lock-confirmed');
917
+ // The onStep callback can pause while another contender renames
918
+ // our marker, so verify ownership again after the callback.
919
+ if (!(await ownsEvictionMarker()))
920
+ return null;
921
+ // Do not await a callback between this ownership check and the lock read.
922
+ const current = await readLockState(false);
923
+ if (!sameStaleLock(observed.identity, current))
924
+ continue;
925
+ // The final read and removal are not atomic. While this stale file
926
+ // exists, exclusive creation cannot publish a successor; the marker
927
+ // excludes other evictors and release/renewal. An expired holder cannot
928
+ // renew: renewal rechecks expiry and marker ownership before publishing.
929
+ // With the marker still owned, cooperating users cannot replace it in
930
+ // this window. Arbitrary suspension across marker expiry or filesystem
931
+ // changes still need a kernel lock for an atomic guarantee.
932
+ await removeLeaseObject(lockPath);
933
+ // Fence check 3: re-verify ownership after removing the stale lock.
934
+ if (!(await ownsEvictionMarker()))
935
+ return null;
936
+ if (options.onStep)
937
+ await options.onStep('stale-lock-removed');
938
+ acquired = await tryAcquire();
939
+ if (!acquired)
940
+ return null;
941
+ if (options.onStep)
942
+ await options.onStep('stale-lock-recreated');
943
+ // Fence check 4: re-verify ownership after acquiring the lock. If the
944
+ // marker was stolen between tryAcquire and this check, release the
945
+ // just-acquired lock and return null (fail-closed).
946
+ if (!(await ownsEvictionMarker())) {
947
+ await relinquishLockAfterMarkerLoss();
948
+ acquired = false;
949
+ return null;
950
+ }
951
+ break;
952
+ }
953
+ finally {
954
+ await releaseEvictionMarker();
955
+ }
923
956
  }
924
- finally {
925
- await releaseEvictionMarker();
957
+ catch (error) {
958
+ if (!isChangingLockCreate(error))
959
+ throw error;
960
+ // A refused create is busy, not stale. Retry exclusive creation before
961
+ // any owner read or eviction, retaining the first persistent refusal.
962
+ changingCreateError ??= error;
963
+ await backoff();
926
964
  }
927
965
  }
928
966
  }
929
- if (!acquired)
967
+ if (!acquired) {
968
+ if (changingCreateError)
969
+ throw changingCreateError;
930
970
  return null;
971
+ }
931
972
  scheduleRenewal();
932
973
  return {
933
974
  ownerId,
@@ -977,6 +1018,7 @@ export async function acquireRefreshFileLockWithClock(options) {
977
1018
  const deadline = performance.now() + EVICT_TTL + 1_000;
978
1019
  let delayMs = 5;
979
1020
  let removalError;
1021
+ let changingRecordError;
980
1022
  for (;;) {
981
1023
  try {
982
1024
  let removalConfirmed = false;
@@ -1004,6 +1046,7 @@ export async function acquireRefreshFileLockWithClock(options) {
1004
1046
  await removeLeaseObject(lockPath);
1005
1047
  removalConfirmed = true;
1006
1048
  }, deadline);
1049
+ changingRecordError = undefined;
1007
1050
  if (markerAcquired) {
1008
1051
  if (windowsPrivateFiles && !removalConfirmed)
1009
1052
  throw new PrivateFileError(lockPath, 'release-not-confirmed', {
@@ -1017,15 +1060,27 @@ export async function acquireRefreshFileLockWithClock(options) {
1017
1060
  await recoverStaleEvictionMarker(deadline);
1018
1061
  }
1019
1062
  catch (error) {
1020
- if (!isRetryableRemoval(error, lockPath)) {
1063
+ const changingRecord = windowsPrivateFiles &&
1064
+ (isChangingLockCreate(error) ||
1065
+ isWindowsAccessDeniedRead(error, [
1066
+ lockPath,
1067
+ legacyOwnerPath,
1068
+ evictPath,
1069
+ evictOwnerPath,
1070
+ ]));
1071
+ if (!isRetryableRemoval(error, lockPath) && !changingRecord) {
1021
1072
  if (windowsPrivateFiles)
1022
1073
  throw error;
1023
1074
  return;
1024
1075
  }
1025
- // Like rename, a fenced delete can be refused by a reader's Windows
1026
- // handle without invalidating ownership. Drop the marker, back off,
1027
- // and re-confirm the owner under a new marker before trying again.
1028
- removalError ??= error;
1076
+ // Neither a refused delete nor an ambiguous record read or create
1077
+ // establishes loss or expiry. Back off under the release deadline and
1078
+ // re-confirm ownership before any removal; keep the original error
1079
+ // if the refusal persists.
1080
+ if (changingRecord)
1081
+ changingRecordError ??= error;
1082
+ else
1083
+ removalError ??= error;
1029
1084
  }
1030
1085
  const remainingMs = deadline - performance.now();
1031
1086
  if (remainingMs <= 0)
@@ -1038,7 +1093,8 @@ export async function acquireRefreshFileLockWithClock(options) {
1038
1093
  // Do not delete by pathname without the marker: bounded retries leave the
1039
1094
  // lease to expire rather than risking removal of a successor's lock.
1040
1095
  if (windowsPrivateFiles)
1041
- throw (removalError ??
1096
+ throw (changingRecordError ??
1097
+ removalError ??
1042
1098
  new PrivateFileError(lockPath, 'release-not-confirmed', {
1043
1099
  code: 'ETIMEDOUT',
1044
1100
  }));
@@ -10,7 +10,7 @@ export { ClaustrumCredentialError, } from "@cortexkit/claustrum-client";
10
10
  export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, } from "./94f53cfd572ba4bb-availability.js";
11
11
  export { ClaustrumConsumer, DEFAULT_CONNECT_TIMEOUT_MS, } from "./169b2b4bf30909bc-consumer.js";
12
12
  export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, SERVING_MARGIN_MS, } from "./0f77ebc3c914c9c6-custody.js";
13
- export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, vaultAuthority, } from "./b9588ad4725c1d10-enrollment.js";
13
+ export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, validEnrollmentDisplayName, validEnrollmentRequestedGrants, vaultAuthority, } from "./b9588ad4725c1d10-enrollment.js";
14
14
  export { ClaustrumConsumerError, } from "./ca0fccaba1d87af4-errors.js";
15
15
  export { connectVaultHost, hasVaultHost, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from "./c97089ed4243981c-host.js";
16
16
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, isCustodyPlaceholder, isCustodyPlaceholderValue, } from "./d9d2892a4c371301-host-slot.js";
@@ -238,8 +238,15 @@ export class ClaustrumScopedCustody {
238
238
  this.#warnShutdown = shutdownWarning(this.#logger);
239
239
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
240
240
  this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
241
+ const currentClient = () => this.#client;
241
242
  this.#usage = new ScopedUsageReporter({
242
- client: this.#client,
243
+ client: {
244
+ // Queued readings follow a replacement without losing client capability checks.
245
+ get reportUsageScoped() {
246
+ const client = currentClient();
247
+ return client.reportUsageScoped?.bind(client);
248
+ },
249
+ },
243
250
  owns: (id) => this.#usageServed.has(id),
244
251
  token: async () => hasVaultHost() ? '' : checkedEnrollmentToken(await this.#readToken()),
245
252
  logger: this.#logger,
@@ -247,6 +254,24 @@ export class ClaustrumScopedCustody {
247
254
  clearTimeout: this.#clearTimeout,
248
255
  });
249
256
  }
257
+ /**
258
+ * Replace the connection to the same vault without discarding receipts or
259
+ * their enrollment tokens. Open roster watches restart on the new client;
260
+ * their existing handles remain usable. Passing the current client does nothing.
261
+ * Neither client is closed here: the caller closes the old one, and custody's
262
+ * close()/dispose() still closes the client it holds at shutdown.
263
+ * While hosted, next must come from connectVaultHost, as in the constructor.
264
+ */
265
+ replaceClient(next) {
266
+ this.#check();
267
+ if (next === this.#client)
268
+ return;
269
+ if (hasVaultHost() && !isVaultHostClient(next))
270
+ throw new ClaustrumUnreachableError();
271
+ this.#client = next;
272
+ for (const watch of this.#watches)
273
+ watch.restart();
274
+ }
250
275
  /** A watch losing its transport is the same outage as an unreachable read. */
251
276
  transportLost(error) {
252
277
  if (this.#closed || this.#outage)
@@ -255,7 +280,9 @@ export class ClaustrumScopedCustody {
255
280
  this.#outageError =
256
281
  error instanceof ClaustrumCredentialError
257
282
  ? error
258
- : new ClaustrumUnreachableError();
283
+ : new ClaustrumUnreachableError(error instanceof ClaustrumUnreachableError
284
+ ? error.reason
285
+ : undefined);
259
286
  this.#logger.warn('serving kept vault receipt', { reason: 'unreachable' });
260
287
  this.#scheduleProbe();
261
288
  }
@@ -367,7 +394,7 @@ export class ClaustrumScopedCustody {
367
394
  if (error instanceof ClaustrumCredentialError)
368
395
  throw error;
369
396
  if (classifyVaultFailure(error) === 'unreachable')
370
- throw new ClaustrumUnreachableError();
397
+ throw new ClaustrumUnreachableError(error instanceof ClaustrumUnreachableError ? error.reason : undefined);
371
398
  throw new ClaustrumConsumerError('unavailable', 'Claustrum scoped operation unavailable');
372
399
  }
373
400
  finally {
@@ -603,7 +630,7 @@ export class ClaustrumScopedCustody {
603
630
  if (kept.since === null)
604
631
  kept.since = this.#now();
605
632
  const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, 'accessToken', { value: kept.attempt.accessToken, enumerable: false }));
606
- this.#provenance.set(attempt, this.#provenance.get(kept.attempt) ?? { token, client: this.#client });
633
+ this.#provenance.set(attempt, this.#provenance.get(kept.attempt) ?? { token });
607
634
  this.#keptAttempts.set(attempt, routeId);
608
635
  return attempt;
609
636
  }
@@ -684,15 +711,15 @@ export class ClaustrumScopedCustody {
684
711
  recordVersion: served.recordVersion,
685
712
  expiresAtMs,
686
713
  }, 'accessToken', { value: accessToken, enumerable: false }));
687
- this.#provenance.set(attempt, { token, client: this.#client });
714
+ this.#provenance.set(attempt, { token });
688
715
  return attempt;
689
716
  }
690
717
  /**
691
718
  * Report that a send this consumer actually made was rejected. Only a 401
692
719
  * is reported (the vault refuses 429, 402 and 5xx reports), addressed by
693
720
  * credential id with the exact record version that send was served, and
694
- * sent through the client and enrollment token that authorized it. A receipt
695
- * this custody did not issue is refused rather than reported.
721
+ * sent through the current client with the enrollment token that authorized
722
+ * it. A receipt this custody did not issue is refused rather than reported.
696
723
  */
697
724
  async reportFailure(attempt, status, reporterSource) {
698
725
  if (status !== 401)
@@ -719,7 +746,7 @@ export class ClaustrumScopedCustody {
719
746
  const pending = this.#reports.get(attempt);
720
747
  if (pending)
721
748
  return pending;
722
- const report = this.#call(() => provenance.client.reportAuthFailureScoped({
749
+ const report = this.#call(() => this.#client.reportAuthFailureScoped({
723
750
  credentialId: attempt.credentialId,
724
751
  enrollmentToken: provenance.token,
725
752
  providerStatus: 401,
@@ -761,36 +788,67 @@ export class ClaustrumScopedCustody {
761
788
  */
762
789
  watchRoster(options) {
763
790
  this.#check();
764
- const watch = new ScopedRosterWatch({
765
- client: this.#client,
766
- enrollmentToken: () => this.#token(),
767
- view: options.view ?? (() => this.#discoveredView),
768
- discover: async (view) => {
769
- await options.onView(view);
770
- },
771
- onRefused: (error) => {
772
- // Apply a refused watch as discover() applies a refused account
773
- // listing: every kept receipt is dropped.
774
- this.listFailed(error);
775
- options.onRefused?.(error);
791
+ const currentView = options.view ?? (() => this.#discoveredView);
792
+ let discovering;
793
+ let watch;
794
+ const create = (resubscribed = false) => {
795
+ const opened = new ScopedRosterWatch({
796
+ client: this.#client,
797
+ enrollmentToken: () => this.#token(),
798
+ // Nothing observed the gap between clients, even if the view is unchanged.
799
+ view: () => (resubscribed ? undefined : currentView()),
800
+ discover: async (view) => {
801
+ // An old watch's discovery may still be committing the host's roster.
802
+ while (discovering)
803
+ await discovering.catch(() => { });
804
+ if (watch !== opened)
805
+ return;
806
+ resubscribed = false;
807
+ discovering = Promise.resolve().then(() => options.onView(view));
808
+ try {
809
+ await discovering;
810
+ }
811
+ finally {
812
+ discovering = undefined;
813
+ }
814
+ },
815
+ onRefused: (error) => {
816
+ // Apply a refused watch as discover() applies a refused account
817
+ // listing: every kept receipt is dropped.
818
+ this.listFailed(error);
819
+ options.onRefused?.(error);
820
+ },
821
+ onTransportLost: () => this.transportLost(),
822
+ onReachable: () => this.reachable(),
823
+ onError: options.onError,
824
+ onMode: options.onMode,
825
+ logger: this.#logger,
826
+ now: this.#now,
827
+ setTimeoutImpl: this.#setTimeout,
828
+ clearTimeoutImpl: this.#clearTimeout,
829
+ });
830
+ return opened;
831
+ };
832
+ watch = create();
833
+ const tracked = {
834
+ restart: () => {
835
+ const previousMode = watch.mode;
836
+ watch.stop();
837
+ watch = create(true);
838
+ if (previousMode !== watch.mode)
839
+ options.onMode?.(watch.mode);
840
+ watch.start();
776
841
  },
777
- onTransportLost: () => this.transportLost(),
778
- onReachable: () => this.reachable(),
779
- onError: options.onError,
780
- onMode: options.onMode,
781
- logger: this.#logger,
782
- now: this.#now,
783
- setTimeoutImpl: this.#setTimeout,
784
- clearTimeoutImpl: this.#clearTimeout,
785
- });
786
- this.#watches.add(watch);
842
+ stop: () => watch.stop(),
843
+ };
844
+ this.#watches.add(tracked);
787
845
  watch.start();
788
846
  return {
789
847
  get mode() {
790
848
  return watch.mode;
791
849
  },
792
850
  close: () => {
793
- this.#watches.delete(watch);
851
+ this.#watches.delete(tracked);
794
852
  watch.stop();
795
853
  },
796
854
  };
@@ -1,5 +1,6 @@
1
1
  import { join, resolve } from "node:path";
2
- import { isWindowsSharingViolation, } from "./375d9cca2def037d-private-files.js";
2
+ import { isWindowsAccessDeniedCreate, isWindowsAccessDeniedRead, } from "./723b00f96290a097-lock-record.js";
3
+ import { isWindowsSharingViolation, windowsPrivateFiles, } from "./375d9cca2def037d-private-files.js";
3
4
  import { acquireRefreshFileLock } from "./e8cd4929507508d8-refresh-file-lock.js";
4
5
  export function lockPathFor(target, name) {
5
6
  return `${target}.${name}.lock`;
@@ -20,19 +21,23 @@ export class LockOwnershipError extends Error {
20
21
  this.details = details;
21
22
  }
22
23
  }
23
- function isChangingLockRead(error, target, name) {
24
- if (!isWindowsSharingViolation(error) ||
25
- (error.stage !== 'read' && error.stage !== 'verify'))
26
- return false;
24
+ function isChangingLockRecord(error, target, name) {
27
25
  const path = resolve(lockPathFor(target, name));
28
- return error.path === path || error.path === join(path, 'owner.json');
26
+ const paths = [path, join(path, 'owner.json')];
27
+ return (((isWindowsSharingViolation(error) ||
28
+ isWindowsAccessDeniedRead(error, paths)) &&
29
+ (error.stage === 'read' || error.stage === 'verify') &&
30
+ paths.includes(error.path)) ||
31
+ (windowsPrivateFiles &&
32
+ (isWindowsAccessDeniedCreate(error, [path], 'create') ||
33
+ isWindowsAccessDeniedCreate(error, [`${path}.evicting`], 'directory-create'))));
29
34
  }
30
35
  export async function withLock(target, options, fn) {
31
36
  const started = performance.now();
37
+ let changingRecordError;
32
38
  for (;;) {
33
39
  options.signal?.throwIfAborted();
34
40
  let lock;
35
- let changingReadError;
36
41
  try {
37
42
  lock = await acquireRefreshFileLock({
38
43
  path: target,
@@ -44,14 +49,15 @@ export async function withLock(target, options, fn) {
44
49
  ? { onRenewalTimer: options.onRenewalTimer }
45
50
  : {}),
46
51
  });
52
+ changingRecordError = undefined;
47
53
  }
48
54
  catch (error) {
49
- if (!isChangingLockRead(error, target, options.name))
55
+ if (!isChangingLockRecord(error, target, options.name))
50
56
  throw error;
51
- // Sharing violations (32) and delete-pending opens (303) do not reveal
52
- // ownership or expiry. Retry exclusive creation, never infer a stale lock.
57
+ // Ambiguous reads or creates reveal neither ownership nor expiry. Retry
58
+ // exclusive creation within the same deadline, never infer staleness from IO.
53
59
  lock = null;
54
- changingReadError = error;
60
+ changingRecordError ??= error;
55
61
  }
56
62
  if (lock) {
57
63
  try {
@@ -65,8 +71,8 @@ export async function withLock(target, options, fn) {
65
71
  const remaining = options.timeoutMs - (performance.now() - started);
66
72
  if (remaining <= 0) {
67
73
  // Keep persistent native IO failures distinguishable from a live holder.
68
- if (changingReadError)
69
- throw changingReadError;
74
+ if (changingRecordError)
75
+ throw changingRecordError;
70
76
  throw new LockContentionError({
71
77
  target,
72
78
  name: options.name,