@cortexkit/opencode-antigravity-auth 3.0.41 → 3.1.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 (113) hide show
  1. package/README.md +11 -0
  2. package/dist/cli.js +1316 -1124
  3. package/dist/cli.js.map +4 -4
  4. package/dist/cli.meta.json +116 -106
  5. package/dist/index.js +1257 -720
  6. package/dist/index.js.map +4 -4
  7. package/dist/index.meta.json +187 -169
  8. package/dist/server.js +1310 -773
  9. package/dist/server.js.map +4 -4
  10. package/dist/server.meta.json +1 -1
  11. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +4 -0
  12. package/dist/src/common-auth-embedded/claustrum/custody.js +147 -2
  13. package/dist/src/common-auth-embedded/claustrum/hub.js +47 -1
  14. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  15. package/dist/src/common-auth-embedded/claustrum/index.js +1 -1
  16. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +13 -9
  17. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +65 -12
  18. package/dist/src/common-auth-embedded/routing-accessor/index.js +114 -15
  19. package/dist/src/common-auth-embedded/settings/edit.d.ts +1 -0
  20. package/dist/src/common-auth-embedded/settings/edit.js +48 -2
  21. package/dist/src/common-auth-embedded/settings/handle.d.ts +2 -1
  22. package/dist/src/common-auth-embedded/settings/index.d.ts +1 -0
  23. package/dist/src/common-auth-embedded/settings/update.d.ts +14 -0
  24. package/dist/src/common-auth-embedded/settings/update.js +28 -9
  25. package/dist/src/common-auth-embedded/source-output.json +55 -46
  26. package/dist/src/plugin/__fixtures__/release-model-ids.d.ts.map +1 -1
  27. package/dist/src/plugin/__fixtures__/release-model-ids.js +1 -0
  28. package/dist/src/plugin/__fixtures__/release-model-ids.js.map +1 -1
  29. package/dist/src/plugin/__fixtures__/verified-store.d.ts +1 -1
  30. package/dist/src/plugin/__fixtures__/verified-store.js +4 -4
  31. package/dist/src/plugin/account-access.js +1 -1
  32. package/dist/src/plugin/account-access.js.map +1 -1
  33. package/dist/src/plugin/catalog.d.ts.map +1 -1
  34. package/dist/src/plugin/catalog.js +4 -2
  35. package/dist/src/plugin/catalog.js.map +1 -1
  36. package/dist/src/plugin/config/models.d.ts +9 -0
  37. package/dist/src/plugin/config/models.d.ts.map +1 -1
  38. package/dist/src/plugin/config/models.js +18 -0
  39. package/dist/src/plugin/config/models.js.map +1 -1
  40. package/dist/src/plugin/config/updater.js +2 -2
  41. package/dist/src/plugin/config/updater.js.map +1 -1
  42. package/dist/src/plugin/core/streaming/terminal-event.d.ts +14 -0
  43. package/dist/src/plugin/core/streaming/terminal-event.d.ts.map +1 -0
  44. package/dist/src/plugin/core/streaming/terminal-event.js +39 -0
  45. package/dist/src/plugin/core/streaming/terminal-event.js.map +1 -0
  46. package/dist/src/plugin/core/streaming/transformer.d.ts.map +1 -1
  47. package/dist/src/plugin/core/streaming/transformer.js +1 -13
  48. package/dist/src/plugin/core/streaming/transformer.js.map +1 -1
  49. package/dist/src/plugin/ga-location-services.js +1 -1
  50. package/dist/src/plugin/ga-location-services.js.map +1 -1
  51. package/dist/src/plugin/index.js +1 -1
  52. package/dist/src/plugin/index.js.map +1 -1
  53. package/dist/src/plugin/request-helpers.d.ts +10 -0
  54. package/dist/src/plugin/request-helpers.d.ts.map +1 -1
  55. package/dist/src/plugin/request-helpers.js +6 -0
  56. package/dist/src/plugin/request-helpers.js.map +1 -1
  57. package/dist/src/plugin/request.d.ts.map +1 -1
  58. package/dist/src/plugin/request.js +101 -47
  59. package/dist/src/plugin/request.js.map +1 -1
  60. package/dist/src/plugin/search.d.ts +7 -0
  61. package/dist/src/plugin/search.d.ts.map +1 -1
  62. package/dist/src/plugin/search.js +9 -15
  63. package/dist/src/plugin/search.js.map +1 -1
  64. package/dist/src/plugin/session-context.d.ts +1 -1
  65. package/dist/src/plugin/session-context.d.ts.map +1 -1
  66. package/dist/src/plugin/session-context.js +2 -5
  67. package/dist/src/plugin/session-context.js.map +1 -1
  68. package/dist/src/plugin/shared/request-services.d.ts +8 -1
  69. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  70. package/dist/src/plugin/shared/request-services.js +98 -11
  71. package/dist/src/plugin/shared/request-services.js.map +1 -1
  72. package/dist/src/plugin/shared/vault-routing.d.ts +9 -1
  73. package/dist/src/plugin/shared/vault-routing.d.ts.map +1 -1
  74. package/dist/src/plugin/shared/vault-routing.js +34 -12
  75. package/dist/src/plugin/shared/vault-routing.js.map +1 -1
  76. package/dist/tui-build-map.json +1 -1
  77. package/dist/tui-ga-build-map.json +1 -1
  78. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +4 -0
  79. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  80. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +65 -12
  81. package/dist/types/src/plugin/catalog.d.ts.map +1 -1
  82. package/dist/types/src/plugin/config/models.d.ts +9 -0
  83. package/dist/types/src/plugin/config/models.d.ts.map +1 -1
  84. package/dist/types/src/plugin/core/streaming/terminal-event.d.ts +14 -0
  85. package/dist/types/src/plugin/core/streaming/terminal-event.d.ts.map +1 -0
  86. package/dist/types/src/plugin/core/streaming/transformer.d.ts.map +1 -1
  87. package/dist/types/src/plugin/request-helpers.d.ts +10 -0
  88. package/dist/types/src/plugin/request-helpers.d.ts.map +1 -1
  89. package/dist/types/src/plugin/request.d.ts.map +1 -1
  90. package/dist/types/src/plugin/search.d.ts +7 -0
  91. package/dist/types/src/plugin/search.d.ts.map +1 -1
  92. package/dist/types/src/plugin/session-context.d.ts +1 -1
  93. package/dist/types/src/plugin/session-context.d.ts.map +1 -1
  94. package/dist/types/src/plugin/shared/request-services.d.ts +8 -1
  95. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  96. package/dist/types/src/plugin/shared/vault-routing.d.ts +9 -1
  97. package/dist/types/src/plugin/shared/vault-routing.d.ts.map +1 -1
  98. package/package.json +2 -2
  99. package/src/common-auth-embedded/claustrum/custody.d.ts +4 -0
  100. package/src/common-auth-embedded/claustrum/custody.js +147 -2
  101. package/src/common-auth-embedded/claustrum/hub.js +47 -1
  102. package/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  103. package/src/common-auth-embedded/claustrum/index.js +1 -1
  104. package/src/common-auth-embedded/fs/refresh-file-lock.js +13 -9
  105. package/src/common-auth-embedded/routing-accessor/index.d.ts +65 -12
  106. package/src/common-auth-embedded/routing-accessor/index.js +114 -15
  107. package/src/common-auth-embedded/settings/edit.d.ts +1 -0
  108. package/src/common-auth-embedded/settings/edit.js +48 -2
  109. package/src/common-auth-embedded/settings/handle.d.ts +2 -1
  110. package/src/common-auth-embedded/settings/index.d.ts +1 -0
  111. package/src/common-auth-embedded/settings/update.d.ts +14 -0
  112. package/src/common-auth-embedded/settings/update.js +28 -9
  113. package/src/common-auth-embedded/source-output.json +55 -46
@@ -247,6 +247,10 @@ export declare function decideScopedRetryAfter401(site: string, served: Claustru
247
247
  export declare const SERVING_MARGIN_MS = 300000;
248
248
  /** A kept receipt needs a minute of headroom, not the vault's refresh demand. */
249
249
  export declare const KEPT_RECEIPT_MARGIN_MS = 60000;
250
+ /** Maximum request-path wait for a vault read without a usable kept receipt. */
251
+ export declare const VAULT_RECEIPT_WAIT_MS = 10000;
252
+ /** Only the first minute of each observed outage earns a request-path wait. */
253
+ export declare const VAULT_YOUNG_OUTAGE_MS = 60000;
250
254
  /**
251
255
  * Reads this consumer's vault credentials (list, fetch, 401 report), with the
252
256
  * enrollment token or the host's grant as authorization. Used by every host of a
@@ -65,6 +65,10 @@ export function decideScopedRetryAfter401(site, served, current, logger = defaul
65
65
  export const SERVING_MARGIN_MS = 300_000;
66
66
  /** A kept receipt needs a minute of headroom, not the vault's refresh demand. */
67
67
  export const KEPT_RECEIPT_MARGIN_MS = 60_000;
68
+ /** Maximum request-path wait for a vault read without a usable kept receipt. */
69
+ export const VAULT_RECEIPT_WAIT_MS = 10_000;
70
+ /** Only the first minute of each observed outage earns a request-path wait. */
71
+ export const VAULT_YOUNG_OUTAGE_MS = 60_000;
68
72
  function invalidMaterial() {
69
73
  return new ClaustrumConsumerError('invalid-material', 'Claustrum returned invalid credential material');
70
74
  }
@@ -198,7 +202,10 @@ export class ClaustrumScopedCustody {
198
202
  #setTimeout;
199
203
  #clearTimeout;
200
204
  #outage = false;
205
+ #outageSince = 0;
206
+ #outageWaitSpent = false;
201
207
  #outageError = new ClaustrumUnreachableError();
208
+ #receiptWaits = new Map();
202
209
  #probeTimer;
203
210
  #probing = false;
204
211
  #lastProbeAt = -Infinity;
@@ -277,6 +284,8 @@ export class ClaustrumScopedCustody {
277
284
  if (this.#closed || this.#outage)
278
285
  return;
279
286
  this.#outage = true;
287
+ this.#outageSince = this.#now();
288
+ this.#outageWaitSpent = false;
280
289
  this.#outageError =
281
290
  error instanceof ClaustrumCredentialError
282
291
  ? error
@@ -582,11 +591,13 @@ export class ClaustrumScopedCustody {
582
591
  /** Ask the vault while reachable; retain one validated receipt in memory only. */
583
592
  async authorize(identity, signal, routeId = 'vault') {
584
593
  this.#check(signal);
594
+ const startedAt = this.#now();
585
595
  const { credentialId, credentialType, accountIdentity } = identity;
586
596
  let kept = this.#kept.get(credentialId);
587
597
  if (kept &&
588
598
  (kept.attempt.credentialType !== credentialType ||
589
- kept.attempt.expectedAccountIdentity !== accountIdentity)) {
599
+ kept.attempt.expectedAccountIdentity !== accountIdentity ||
600
+ !this.#usable(kept.attempt))) {
590
601
  this.forget(credentialId);
591
602
  kept = undefined;
592
603
  }
@@ -605,7 +616,22 @@ export class ClaustrumScopedCustody {
605
616
  return this.#serveKept(credentialId, kept, token, routeId);
606
617
  }
607
618
  try {
608
- const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
619
+ let attempt;
620
+ try {
621
+ // Once recovery is in flight, later arrivals join it rather than
622
+ // issuing another immediate read into the same known outage.
623
+ const recovering = this.#outage &&
624
+ this.#receiptWaits.has(this.#receiptWaitKey({ credentialId, credentialType, accountIdentity }, token));
625
+ if (recovering)
626
+ throw this.#outageError;
627
+ attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
628
+ }
629
+ catch (error) {
630
+ this.#check(signal);
631
+ if (classifyVaultFailure(error) !== 'unreachable' || kept)
632
+ throw error;
633
+ attempt = await this.#waitForReceipt({ credentialId, credentialType, accountIdentity }, token, startedAt, error, signal);
634
+ }
609
635
  this.#kept.set(credentialId, { attempt, routeId, since: null });
610
636
  this.#usageServed.set(credentialId, { ...identity });
611
637
  return attempt;
@@ -619,6 +645,122 @@ export class ClaustrumScopedCustody {
619
645
  return this.#serveKept(credentialId, kept, token, routeId, error);
620
646
  }
621
647
  }
648
+ #receiptWaitKey(identity, token) {
649
+ // Never share authorization across a changed enrollment or account binding.
650
+ return JSON.stringify([
651
+ identity.credentialId,
652
+ identity.credentialType,
653
+ identity.accountIdentity,
654
+ token,
655
+ ]);
656
+ }
657
+ async #waitForReceipt(identity, token, startedAt, error, signal) {
658
+ // Measure from the first unreachable observation, even at cold start.
659
+ // Otherwise a process that never connected would charge every request 10 s
660
+ // for an arbitrarily long outage. Any vault answer starts a new window.
661
+ // Once one wait has run out in this outage, the outage has outlasted the
662
+ // bound: later cold reads fail at once. Without that, a host that tries its
663
+ // accounts in turn would pay the full wait once per account.
664
+ const remaining = VAULT_RECEIPT_WAIT_MS - (this.#now() - startedAt);
665
+ if (remaining <= 0 ||
666
+ this.#outageWaitSpent ||
667
+ this.#now() - this.#outageSince >= VAULT_YOUNG_OUTAGE_MS)
668
+ throw error;
669
+ const key = this.#receiptWaitKey(identity, token);
670
+ let wait = this.#receiptWaits.get(key);
671
+ if (!wait) {
672
+ const controller = new AbortController();
673
+ const created = {
674
+ controller,
675
+ users: 0,
676
+ error,
677
+ pending: Promise.resolve().then(async () => {
678
+ let delay = 250;
679
+ for (;;) {
680
+ await this.#receiptBackoff(delay, controller.signal);
681
+ try {
682
+ return await this.#authorizeFresh(identity, token, controller.signal);
683
+ }
684
+ catch (failure) {
685
+ this.#check(controller.signal);
686
+ if (classifyVaultFailure(failure) !== 'unreachable')
687
+ throw failure;
688
+ created.error = failure;
689
+ delay = Math.min(delay * 2, 1_000);
690
+ }
691
+ }
692
+ }),
693
+ };
694
+ wait = created;
695
+ this.#receiptWaits.set(key, wait);
696
+ const remove = () => {
697
+ if (this.#receiptWaits.get(key) === created)
698
+ this.#receiptWaits.delete(key);
699
+ };
700
+ void wait.pending.then(remove, remove);
701
+ }
702
+ const shared = wait;
703
+ shared.users++;
704
+ let timer;
705
+ let abort;
706
+ try {
707
+ const attempt = await Promise.race([
708
+ shared.pending,
709
+ new Promise((_resolve, reject) => {
710
+ timer = this.#setTimeout(() => {
711
+ if (this.#outage)
712
+ this.#outageWaitSpent = true;
713
+ reject(shared.error);
714
+ }, remaining);
715
+ timer.unref?.();
716
+ if (signal) {
717
+ abort = () => reject(signal.reason);
718
+ signal.addEventListener('abort', abort, { once: true });
719
+ if (signal.aborted)
720
+ abort();
721
+ }
722
+ }),
723
+ ]);
724
+ this.#check(signal);
725
+ // Each physical send owns its receipt and later failure report, even
726
+ // when several requests shared the same recovery read.
727
+ const receipt = Object.freeze(Object.defineProperty({ ...attempt }, 'accessToken', {
728
+ value: attempt.accessToken,
729
+ enumerable: false,
730
+ }));
731
+ this.#provenance.set(receipt, { token });
732
+ return receipt;
733
+ }
734
+ finally {
735
+ if (timer)
736
+ this.#clearTimeout(timer);
737
+ if (abort)
738
+ signal?.removeEventListener('abort', abort);
739
+ if (--shared.users === 0) {
740
+ shared.controller.abort();
741
+ if (this.#receiptWaits.get(key) === shared)
742
+ this.#receiptWaits.delete(key);
743
+ }
744
+ }
745
+ }
746
+ #receiptBackoff(delay, signal) {
747
+ this.#check(signal);
748
+ return new Promise((resolve, reject) => {
749
+ const abort = () => {
750
+ this.#clearTimeout(timer);
751
+ signal.removeEventListener('abort', abort);
752
+ reject(signal.reason);
753
+ };
754
+ const timer = this.#setTimeout(() => {
755
+ signal.removeEventListener('abort', abort);
756
+ resolve();
757
+ }, delay);
758
+ timer.unref?.();
759
+ signal.addEventListener('abort', abort, { once: true });
760
+ if (signal.aborted)
761
+ abort();
762
+ });
763
+ }
622
764
  #serveKept(credentialId, kept, token, routeId, error = this.#outageError) {
623
765
  // A concurrent refusal or 401 may already have discarded this entry.
624
766
  if (!kept ||
@@ -876,6 +1018,9 @@ export class ClaustrumScopedCustody {
876
1018
  if (this.#closed)
877
1019
  return;
878
1020
  this.#closed = true;
1021
+ for (const wait of this.#receiptWaits.values())
1022
+ wait.controller.abort();
1023
+ this.#receiptWaits.clear();
879
1024
  if (this.#probeTimer)
880
1025
  this.#clearTimeout(this.#probeTimer);
881
1026
  this.#probeTimer = undefined;
@@ -159,6 +159,13 @@ export class ClaustrumDiscoveryHub {
159
159
  #own;
160
160
  #watch;
161
161
  #run;
162
+ /**
163
+ * Member commit fan-outs still running, each until every one of its
164
+ * commits has settled. Only a run whose generation ended can leave one
165
+ * behind while another run starts; `#discover` waits for them before it
166
+ * reads the files it lists over.
167
+ */
168
+ #fanOuts = new Set();
162
169
  /** The hub's last authority read; undefined before the first one. */
163
170
  #active;
164
171
  /** Counts inactive transitions, so local work started before one stops. */
@@ -665,6 +672,15 @@ export class ClaustrumDiscoveryHub {
665
672
  // Folders that could not be made owner-only fail every member's commit,
666
673
  // as an unreadable base fails its member's: each is marked pending.
667
674
  const folders = await this.#ensureRosterDirectories().then(() => undefined, (error) => error instanceof Error ? error : new Error(String(error)));
675
+ // A generation that ended may still have member commits in flight. A
676
+ // commit that passed its last generation check just before vault mode
677
+ // went off still renames its file afterwards, so its older listing can
678
+ // land after this run read that file. The base-view rule below would
679
+ // then take it for another process's newer commit and keep it over this
680
+ // list. The files are read only once every such commit has settled.
681
+ await this.#settleFanOuts();
682
+ if (!this.#live(generation))
683
+ return undefined;
668
684
  // What each member's file held before the list. Another process may
669
685
  // commit while this list runs; the base-view rule then keeps its newer
670
686
  // roster rather than replacing it with this older listing. Each file is
@@ -696,9 +712,17 @@ export class ClaustrumDiscoveryHub {
696
712
  // does), so no commit ever holds two members' locks and no order between
697
713
  // members is needed. The results are then published in member order.
698
714
  const members = this.#open();
699
- const commits = await Promise.all(members.map((entry) => entry.hooks && !entry.closed
715
+ const fanOut = Promise.all(members.map((entry) => entry.hooks && !entry.closed
700
716
  ? this.#commit(entry, entry.hooks, inventory, folders ?? bases.get(entry), generation)
701
717
  : undefined));
718
+ this.#fanOuts.add(fanOut);
719
+ let commits;
720
+ try {
721
+ commits = await fanOut;
722
+ }
723
+ finally {
724
+ this.#fanOuts.delete(fanOut);
725
+ }
702
726
  if (!this.#live(generation))
703
727
  return undefined;
704
728
  const errors = new Map();
@@ -813,6 +837,28 @@ export class ClaustrumDiscoveryHub {
813
837
  return { error };
814
838
  }
815
839
  }
840
+ /**
841
+ * Wait until no member commit fan-out of an earlier run is still running.
842
+ * Each of them belongs to a generation that ended, so its commits fail or
843
+ * finish at their next generation check and this wait stays short.
844
+ */
845
+ async #settleFanOuts() {
846
+ if (!this.#fanOuts.size)
847
+ return;
848
+ const phaseDiagnostics = channel('common-auth.claustrum.phases');
849
+ const phase = (name) => {
850
+ if (phaseDiagnostics.hasSubscribers)
851
+ phaseDiagnostics.publish({ logger: this.#logger, phase: name });
852
+ };
853
+ phase('earlier fan-out drain begin');
854
+ try {
855
+ while (this.#fanOuts.size)
856
+ await Promise.allSettled([...this.#fanOuts]);
857
+ }
858
+ finally {
859
+ phase('earlier fan-out drain end');
860
+ }
861
+ }
816
862
  /**
817
863
  * Create the roster folders under the state folder (`rosters`, this host
818
864
  * generation and this key) owner-only, as every other Claustrum private
@@ -3,7 +3,7 @@ import type { ClaustrumScopedClient } from './custody.js';
3
3
  export { ClaustrumCredentialError, type ClaustrumReporterSource, type EnrollmentTokenFile, } from '@cortexkit/claustrum-client';
4
4
  export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, type VaultFailureClass, } from './availability.js';
5
5
  export { ClaustrumConsumer, type ClaustrumConsumerOptions, type ClaustrumWatchState, DEFAULT_CONNECT_TIMEOUT_MS, type SendOptions, } from './consumer.js';
6
- export { type AccountIdentitySource, type ClassifyingClaustrumFamily, type ClaustrumFamily, type ClaustrumFamilyInput, type ClaustrumRosterWatch, type ClaustrumRosterWatchOptions, type ClaustrumScopedAttempt, type ClaustrumScopedClient, ClaustrumScopedCustody, type ClaustrumScopedIdentity, decideScopedRetryAfter401, type IdentityParser, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, type KeptReceiptState, type ScopedRetryReason, SERVING_MARGIN_MS, type SkippedVaultReason, type SkippedVaultRecord, type VaultCredential, type VaultCredentialType, type VaultGrantReach, type VaultGrantTuple, type VaultInventory, type VaultRowFacts, } from './custody.js';
6
+ export { type AccountIdentitySource, type ClassifyingClaustrumFamily, type ClaustrumFamily, type ClaustrumFamilyInput, type ClaustrumRosterWatch, type ClaustrumRosterWatchOptions, type ClaustrumScopedAttempt, type ClaustrumScopedClient, ClaustrumScopedCustody, type ClaustrumScopedIdentity, decideScopedRetryAfter401, type IdentityParser, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, type KeptReceiptState, type ScopedRetryReason, SERVING_MARGIN_MS, type SkippedVaultReason, type SkippedVaultRecord, VAULT_RECEIPT_WAIT_MS, VAULT_YOUNG_OUTAGE_MS, type VaultCredential, type VaultCredentialType, type VaultGrantReach, type VaultGrantTuple, type VaultInventory, type VaultRowFacts, } from './custody.js';
7
7
  export { type ClaustrumEnrollmentClient, type ClaustrumEnrollmentConnection, type ClaustrumEnrollmentDisconnectResult, ClaustrumEnrollmentManager, type ClaustrumEnrollmentPaths, type ClaustrumEnrollmentResetResult, type ClaustrumEnrollmentStatus, type ClaustrumRequestedGrant, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, type EnrollmentDisposition, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, validEnrollmentDisplayName, validEnrollmentRequestedGrants, vaultAuthority, } from './enrollment.js';
8
8
  export { ClaustrumConsumerError, type ClaustrumConsumerFailureKind, type ClaustrumLogger, } from './errors.js';
9
9
  export { connectVaultHost, hasVaultHost, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from './host.js';
@@ -9,7 +9,7 @@ import { insulaUsageTransport } from './insula.js';
9
9
  export { ClaustrumCredentialError, } from '@cortexkit/claustrum-client';
10
10
  export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, } from './availability.js';
11
11
  export { ClaustrumConsumer, DEFAULT_CONNECT_TIMEOUT_MS, } from './consumer.js';
12
- export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, SERVING_MARGIN_MS, } from './custody.js';
12
+ export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, SERVING_MARGIN_MS, VAULT_RECEIPT_WAIT_MS, VAULT_YOUNG_OUTAGE_MS, } from './custody.js';
13
13
  export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, validEnrollmentDisplayName, validEnrollmentRequestedGrants, vaultAuthority, } from './enrollment.js';
14
14
  export { ClaustrumConsumerError, } from './errors.js';
15
15
  export { connectVaultHost, hasVaultHost, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from './host.js';
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { link, lstat, mkdir, open, readdir, readFile, rename, rm, stat, unlink, } from 'node:fs/promises';
3
3
  import { basename, dirname, join } from 'node:path';
4
+ import { createLogger } from '../logger/index.js';
4
5
  import { DisappearedLockRecordError, isWindowsAccessDeniedCreate, isWindowsAccessDeniedRead, readLockRecord, } from './lock-record.js';
5
6
  import { createPrivateBytes, createPrivateDirectoryExclusive, ensurePrivateDirectory, isWindowsSharingViolation, PrivateFileError, privateOperation, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from './private-files.js';
6
7
  import { LockOwnershipError, lockPathFor } from './with-lock.js';
@@ -1191,17 +1192,17 @@ export async function acquireRefreshFileLockWithClock(options) {
1191
1192
  removalConfirmed = true;
1192
1193
  }, deadline);
1193
1194
  changingRecordError = undefined;
1194
- if (markerAcquired) {
1195
- if (windowsPrivateFiles && !removalConfirmed)
1196
- throw new PrivateFileError(lockPath, 'release-not-confirmed', {
1197
- code: 'EIO',
1198
- });
1199
- releaseConfirmed = removalConfirmed;
1195
+ // Acquiring the marker does not confirm removal: stale-marker
1196
+ // recovery can take it away after the lease owner was checked.
1197
+ if (markerAcquired && removalConfirmed) {
1198
+ releaseConfirmed = true;
1200
1199
  return;
1201
1200
  }
1202
- if (signal?.aborted)
1203
- return;
1204
- await recoverStaleEvictionMarker(deadline);
1201
+ if (!markerAcquired) {
1202
+ if (signal?.aborted)
1203
+ return;
1204
+ await recoverStaleEvictionMarker(deadline);
1205
+ }
1205
1206
  }
1206
1207
  catch (error) {
1207
1208
  const changingRecord = windowsPrivateFiles &&
@@ -1242,6 +1243,9 @@ export async function acquireRefreshFileLockWithClock(options) {
1242
1243
  new PrivateFileError(lockPath, 'release-not-confirmed', {
1243
1244
  code: 'ETIMEDOUT',
1244
1245
  }));
1246
+ createLogger('fs').warn('File lock release deadline expired', {
1247
+ lockPath,
1248
+ });
1245
1249
  },
1246
1250
  };
1247
1251
  }
@@ -1,7 +1,8 @@
1
1
  /**
2
- * Optional THALAMUS routing for vault mode and advisory turn notes for request
3
- * shaping. Account ids are vault account ids, not local pool rows. Nothing is
4
- * persisted here; plugins on routes the runner does not serve get no turn notes.
2
+ * Optional THALAMUS routing for vault mode, plugin wait reports and advisory turn
3
+ * notes for request shaping. Account ids are vault account ids, not local pool
4
+ * rows. Nothing is persisted here; plugins on routes the runner does not serve
5
+ * get no turn notes.
5
6
  */
6
7
  import { type CacheWarmStopReason } from './cache-policy.js';
7
8
  export type { CacheTouchInput, CacheWarmStoppedInput, CacheWarmStopReason, SessionCacheHours, SessionCachePolicy, SessionCacheTtl, SessionKeepWarmMode, SessionToolWait, } from './cache-policy.js';
@@ -12,14 +13,16 @@ export interface RoutingCandidate {
12
13
  accountId: string;
13
14
  credentialId: string;
14
15
  }
15
- export interface AskRoutingInput<Candidate extends RoutingCandidate = RoutingCandidate> {
16
+ export interface AskRoutingInput<Candidate extends RoutingCandidate = RoutingCandidate, Refusals extends boolean = false> {
16
17
  sessionId: string;
17
18
  provider: string;
18
19
  modelId: string;
19
20
  /** Only routes already eligible under the plugin's vault and killswitch rules. */
20
21
  candidates: readonly Candidate[];
21
- /** Defaults to 500 ms, clamped to 1–2000 ms. */
22
+ /** Defaults to 1500 ms, above routing's normal tail; clamped to 1–2000 ms. */
22
23
  deadlineMs?: number;
24
+ /** Opt in to refusals, which stop the request instead of using a local choice. */
25
+ refusals?: Refusals;
23
26
  /**
24
27
  * Longest same-account hold, in seconds, that routing may advise. The
25
28
  * holdWaitMaxS helper from `./limits` caps it by the setting and the current
@@ -28,6 +31,8 @@ export interface AskRoutingInput<Candidate extends RoutingCandidate = RoutingCan
28
31
  * routing's default cap in force.
29
32
  */
30
33
  holdWaitMaxS?: number;
34
+ /** Plugin sticky choice's vault credential id; an eligible-account hint, not a pin. */
35
+ warmCredentialId?: string;
31
36
  }
32
37
  export interface RoutingHold {
33
38
  /** Uncapped advice from routing. The plugin must apply its own hold cap. */
@@ -38,6 +43,14 @@ export interface RoutingSelection<Candidate extends RoutingCandidate = RoutingCa
38
43
  candidate: Candidate;
39
44
  hold?: RoutingHold;
40
45
  }
46
+ export type RoutingRefusal = {
47
+ refused: {
48
+ code: 'account_limit_exhausted' | 'account_selection_refused' | 'account_selection_final';
49
+ routingCode?: string;
50
+ retryAfterSecs?: number;
51
+ resetsAtMs?: number;
52
+ };
53
+ };
41
54
  interface RoutingReportIdentity {
42
55
  sessionId: string;
43
56
  accountId: string;
@@ -56,6 +69,9 @@ export interface BillingUsage {
56
69
  reasoning?: number;
57
70
  reasoningIncludedInOutput?: boolean;
58
71
  }
72
+ /** Keep this closed list aligned with the routing contract when adding a reason. */
73
+ export declare const PLUGIN_WAIT_REASONS: readonly ['account_limit', 'account_free', 'rate_limited', 'server_busy', 'quota_reading', 'routing_hold'];
74
+ export type PluginWaitReason = (typeof PLUGIN_WAIT_REASONS)[number];
59
75
  export type ReportRoutingInput = (RoutingReportIdentity & ({
60
76
  outcome: 'served';
61
77
  /**
@@ -77,6 +93,23 @@ export type ReportRoutingInput = (RoutingReportIdentity & ({
77
93
  pool?: string;
78
94
  /** Optional reset time in epoch milliseconds. */
79
95
  resetsAt?: number;
96
+ } | {
97
+ /**
98
+ * A provider's typed refusal that condemns the API key until it is
99
+ * topped up, such as an exhausted prepaid balance. Never use for
100
+ * 401, 403 or short rate limits.
101
+ */
102
+ outcome: 'credential_refused';
103
+ credentialId: string;
104
+ /**
105
+ * What the provider actually sent: its own code from the structured
106
+ * error (OpenRouter's `openrouter_credits`). When the body carries
107
+ * no code, `http_<status>`, but only for a status the provider
108
+ * documents with a single balance meaning (DeepSeek's `http_402`).
109
+ * Never message text, and never a status with several meanings such
110
+ * as 403 or 429. Must match `^[a-z0-9._-]{1,64}$`.
111
+ */
112
+ providerCode: string;
80
113
  })) | {
81
114
  sessionId: string;
82
115
  kind: 'turn_notes_supported';
@@ -87,6 +120,18 @@ export type ReportRoutingInput = (RoutingReportIdentity & ({
87
120
  kind: 'turn_note_skipped';
88
121
  after_tool_use_id: string;
89
122
  reason: 'anchor_missing' | 'before_user_message' | 'unsupported_model' | 'not_oauth';
123
+ } | {
124
+ sessionId: string;
125
+ kind: 'wait';
126
+ phase: 'start' | 'end';
127
+ waitId: string;
128
+ reason: PluginWaitReason;
129
+ /** Absolute epoch-millisecond time of the next attempt. */
130
+ nextMs?: number;
131
+ attempt?: number;
132
+ /** Fixed plugin text, never provider text, an account label or an id. */
133
+ message?: string;
134
+ outcome?: 'resumed' | 'cancelled' | 'abandoned';
90
135
  } | {
91
136
  sessionId: string;
92
137
  kind: 'billing';
@@ -128,14 +173,22 @@ export declare function turnNotes(sessionId: string): readonly {
128
173
  }[];
129
174
  /**
130
175
  * Ask routing for an eligible vault route. Any failure or unfamiliar answer
131
- * yields undefined so the plugin can keep its own choice. This does not admit
132
- * routes: callers must exclude vault refusals and killswitch-blocked accounts.
176
+ * yields undefined so the plugin can keep its own choice. Opted-in routing
177
+ * refusals instead stop the request. This does not admit routes. Callers never
178
+ * pass an account the vault refused. A plugin may also leave out accounts its
179
+ * user's own eligibility rules exclude, such as a per-model account list. Each
180
+ * plugin decides whether its quota floors (a minimum share of a quota window
181
+ * an account must keep) also filter candidates; routing keeps its own reserve
182
+ * of each window.
183
+ * Routing's pick among the candidates is final. Don't reject it under a local
184
+ * floor, and don't add floors of the plugin's own that duplicate routing's
185
+ * reserves.
133
186
  */
134
- export declare function askRouting<Candidate extends RoutingCandidate>(input: AskRoutingInput<Candidate>): Promise<RoutingSelection<Candidate> | undefined>;
187
+ export declare function askRouting<Candidate extends RoutingCandidate, Refusals extends boolean = false>(input: AskRoutingInput<Candidate, Refusals>): Promise<RoutingSelection<Candidate> | (Refusals extends true ? RoutingRefusal : never) | undefined>;
135
188
  /**
136
- * Report a vault request, billing result or turn-note event without waiting for
137
- * routing. Only contract fields are sent, and all accessor failures are ignored.
138
- * Headers must already be limited to rate-limit headers by the caller; values
139
- * are not filtered or redacted here.
189
+ * Report a vault request, billing result, plugin wait or turn-note event without
190
+ * waiting for routing. Only contract fields are sent, and all accessor failures
191
+ * are ignored. Headers must already be limited to rate-limit headers by the
192
+ * caller; values are not filtered or redacted here.
140
193
  */
141
194
  export declare function reportRouting(input: ReportRoutingInput): void;