@cortexkit/common-auth 0.47.0 → 0.48.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.
@@ -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,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';
@@ -30,6 +31,8 @@ export interface AskRoutingInput<Candidate extends RoutingCandidate = RoutingCan
30
31
  * routing's default cap in force.
31
32
  */
32
33
  holdWaitMaxS?: number;
34
+ /** Plugin sticky choice's vault credential id; an eligible-account hint, not a pin. */
35
+ warmCredentialId?: string;
33
36
  }
34
37
  export interface RoutingHold {
35
38
  /** Uncapped advice from routing. The plugin must apply its own hold cap. */
@@ -66,6 +69,9 @@ export interface BillingUsage {
66
69
  reasoning?: number;
67
70
  reasoningIncludedInOutput?: boolean;
68
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];
69
75
  export type ReportRoutingInput = (RoutingReportIdentity & ({
70
76
  outcome: 'served';
71
77
  /**
@@ -114,6 +120,18 @@ export type ReportRoutingInput = (RoutingReportIdentity & ({
114
120
  kind: 'turn_note_skipped';
115
121
  after_tool_use_id: string;
116
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';
117
135
  } | {
118
136
  sessionId: string;
119
137
  kind: 'billing';
@@ -156,14 +174,21 @@ export declare function turnNotes(sessionId: string): readonly {
156
174
  /**
157
175
  * Ask routing for an eligible vault route. Any failure or unfamiliar answer
158
176
  * yields undefined so the plugin can keep its own choice. Opted-in routing
159
- * refusals instead stop the request. This does not admit routes: callers must
160
- * exclude vault refusals and killswitch-blocked accounts.
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.
161
186
  */
162
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>;
163
188
  /**
164
- * Report a vault request, billing result or turn-note event without waiting for
165
- * routing. Only contract fields are sent, and all accessor failures are ignored.
166
- * Headers must already be limited to rate-limit headers by the caller; values
167
- * 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.
168
193
  */
169
194
  export declare function reportRouting(input: ReportRoutingInput): void;
@@ -1,11 +1,21 @@
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 { isCacheWarmStopReason, } from './cache-policy.js';
7
8
  import { routingHandle } from './handle.js';
8
9
  export { CACHE_WARM_STOP_REASONS, isCacheWarmStopReason, reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
10
+ /** Keep this closed list aligned with the routing contract when adding a reason. */
11
+ export const PLUGIN_WAIT_REASONS = [
12
+ 'account_limit',
13
+ 'account_free',
14
+ 'rate_limited',
15
+ 'server_busy',
16
+ 'quota_reading',
17
+ 'routing_hold',
18
+ ];
9
19
  function isObject(value) {
10
20
  return typeof value === 'object' && value !== null;
11
21
  }
@@ -192,6 +202,13 @@ export async function askRouting(input) {
192
202
  }
193
203
  if (input.refusals === true)
194
204
  request.refusals = true;
205
+ const warmCredentialId = input.warmCredentialId;
206
+ if (isNonEmptyString(warmCredentialId) &&
207
+ warmCredentialId.length <= 256 &&
208
+ !/\p{Cc}/u.test(warmCredentialId) &&
209
+ input.candidates.some((candidate) => candidate.credentialId === warmCredentialId)) {
210
+ request.warm_credential = warmCredentialId;
211
+ }
195
212
  const pending = accountFor.call(handle, request, { deadlineMs });
196
213
  if (!isObject(pending) || typeof pending.then !== 'function')
197
214
  return undefined;
@@ -210,14 +227,15 @@ export async function askRouting(input) {
210
227
  }
211
228
  }
212
229
  /**
213
- * Report a vault request, billing result or turn-note event without waiting for
214
- * routing. Only contract fields are sent, and all accessor failures are ignored.
215
- * Headers must already be limited to rate-limit headers by the caller; values
216
- * are not filtered or redacted here.
230
+ * Report a vault request, billing result, plugin wait or turn-note event without
231
+ * waiting for routing. Only contract fields are sent, and all accessor failures
232
+ * are ignored. Headers must already be limited to rate-limit headers by the
233
+ * caller; values are not filtered or redacted here.
217
234
  */
218
235
  export function reportRouting(input) {
219
236
  try {
220
- const handle = routingHandle(input.sessionId);
237
+ const sessionId = input.sessionId;
238
+ const handle = routingHandle(sessionId);
221
239
  if (!handle)
222
240
  return;
223
241
  const report = handle.report;
@@ -226,6 +244,45 @@ export function reportRouting(input) {
226
244
  let payload;
227
245
  if ('kind' in input) {
228
246
  switch (input.kind) {
247
+ case 'wait': {
248
+ const { phase, waitId, reason, nextMs, attempt, message, outcome } = input;
249
+ if (!isNonEmptyString(sessionId) ||
250
+ (phase !== 'start' && phase !== 'end') ||
251
+ !isNonEmptyString(waitId) ||
252
+ waitId.length > 64 ||
253
+ /[^A-Za-z0-9._:-]/.test(waitId) ||
254
+ !PLUGIN_WAIT_REASONS.includes(reason))
255
+ return;
256
+ payload = {
257
+ kind: 'wait',
258
+ phase,
259
+ wait_id: waitId,
260
+ reason,
261
+ ...(typeof nextMs === 'number' &&
262
+ Number.isSafeInteger(nextMs) &&
263
+ nextMs > 0
264
+ ? { next_ms: nextMs }
265
+ : {}),
266
+ ...(typeof attempt === 'number' &&
267
+ Number.isInteger(attempt) &&
268
+ attempt >= 1
269
+ ? { attempt }
270
+ : {}),
271
+ ...(typeof message === 'string' &&
272
+ message.length >= 1 &&
273
+ message.length <= 160 &&
274
+ !/\p{Cc}/u.test(message)
275
+ ? { message }
276
+ : {}),
277
+ ...(phase === 'end' &&
278
+ (outcome === 'resumed' ||
279
+ outcome === 'cancelled' ||
280
+ outcome === 'abandoned')
281
+ ? { outcome }
282
+ : {}),
283
+ };
284
+ break;
285
+ }
229
286
  case 'billing': {
230
287
  const { attemptId, requestKind, credentialId, provider, model, outcome, accountId, providerRequestId, providerResponseId, userMessageId, status, attempt, chargeBasis, usage: inputUsage, usageByModel: inputUsageByModel, cache: inputCache, } = input;
231
288
  if (!isNonEmptyString(attemptId) ||
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.47.0",
3
+ "version": "0.48.0",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {