@cortexkit/anthropic-auth-core 2.4.11 → 2.4.13

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.
@@ -180,6 +180,7 @@ export type AccountStorage = {
180
180
  };
181
181
  routing?: {
182
182
  mode?: RoutingMode;
183
+ maxSameAccountWait?: import('./routing.ts').MaxSameAccountWait;
183
184
  };
184
185
  fallbackOn?: number[];
185
186
  refresh?: {
@@ -420,19 +421,29 @@ export declare function getKillswitchThresholdsForAccount(storage: AccountStorag
420
421
  * 5h/7d check. A model with no matching scoped window is unaffected.
421
422
  */
422
423
  export declare function killswitchPassesPolicy(quota: OAuthQuotaSnapshot | undefined, storage: AccountStorage | null, accountId?: string, modelId?: string): boolean;
423
- /**
424
- * Find the earliest reset time across all accounts' quota windows.
425
- * Returns seconds from `now` until that reset, or 300 as a fallback.
426
- *
427
- * When `scopedModelId` is provided, ONLY the matched scoped window's
428
- * `resetsAt` is considered — the 5h/7d resets are intentionally ignored
429
- * so the retry hint reflects the weekly reset, not the sooner 5h reset
430
- * (which would cause a retry-storm against a block that won't clear for
431
- * days). With `scopedModelId` undefined, the 5h/7d behavior is unchanged.
432
- */
433
- export declare function killswitchRetryAfterSeconds(mainQuota: OAuthQuotaSnapshot | undefined, fallbackAccounts: Array<{
424
+ export type QuotaResetEvidence = {
434
425
  quota?: OAuthQuotaSnapshot;
435
- }>, now: number, scopedModelId?: string): number;
426
+ accountIdentity?: string;
427
+ accountId?: string;
428
+ };
429
+ /** Only current, identity-bound readings can justify waiting for a stored reset. */
430
+ export declare function quotaRefusalTiming(input: {
431
+ readings: readonly QuotaResetEvidence[];
432
+ storage?: AccountStorage | null;
433
+ scopedModelId?: string;
434
+ modelId?: string;
435
+ sessionTtlMs?: number;
436
+ now?: number;
437
+ }): {
438
+ resetAt: number | undefined;
439
+ retryAfterSeconds: number | undefined;
440
+ };
441
+ /** Compatibility accessor for callers that need only the capped retry delay. */
442
+ export declare function killswitchRetryAfterSeconds(mainQuota: OAuthQuotaSnapshot | undefined, fallbackAccounts: Array<QuotaResetEvidence>, now: number, scopedModelId?: string, options?: {
443
+ storage?: AccountStorage | null;
444
+ mainAccountIdentity?: string;
445
+ sessionTtlMs?: number;
446
+ }): number;
436
447
  export declare function getKillswitchConfig(storage: AccountStorage | null): KillswitchConfig;
437
448
  export declare function getQuotaNextRefreshAt(quota: OAuthQuotaSnapshot | undefined, storage: AccountStorage | null, now: number): number;
438
449
  export declare function fetchOAuthQuotaSnapshot(input: {
package/dist/index.d.ts CHANGED
@@ -84,6 +84,7 @@ export { renameWithWindowsSharingRetry } from './publication-rename.ts';
84
84
  export * from './quota-header-feed.ts';
85
85
  export * from './quota-headers.ts';
86
86
  export * from './quota-manager.ts';
87
+ export * from './quota-refusal.ts';
87
88
  export * from './quotas.ts';
88
89
  export * from './relay.ts';
89
90
  export * from './relocation-guard.ts';
@@ -91,6 +92,7 @@ export * from './request-abort.ts';
91
92
  export * from './request-gzip.ts';
92
93
  export * from './request-history.ts';
93
94
  export * from './routing.ts';
95
+ export * from './session-cache-activity.ts';
94
96
  export type { SseEvent, SseFramer, SseFramerOptions } from './sse.ts';
95
97
  export { createSseFramer, DEFAULT_SSE_MAX_FRAME_BYTES, decodeSseFrame, isSseCandidateFrame, isTerminatedSseFrame, parseSseFrame, SseFrameTooLargeError, } from './sse.ts';
96
98
  export * from './start.ts';
package/dist/index.js CHANGED
@@ -4571,6 +4571,102 @@ async function exchange(input, verifier, redirectUri, expectedState) {
4571
4571
  return exchangeCode(callback, verifier, redirectUri);
4572
4572
  }
4573
4573
 
4574
+ // src/routing.ts
4575
+ var CLAUDE_ROUTING_COMMAND_NAME = "claude-routing";
4576
+ var ROUTING_MODES = [
4577
+ "main-first",
4578
+ "fallback-first",
4579
+ "sticky-balanced"
4580
+ ];
4581
+ var DEFAULT_ROUTING_MODE = "main-first";
4582
+ var MAX_SAME_ACCOUNT_WAITS = ["0", "15", "max"];
4583
+ var DEFAULT_MAX_SAME_ACCOUNT_WAIT = "15";
4584
+ function getMaxSameAccountWait(storage) {
4585
+ const value = storage?.routing?.maxSameAccountWait;
4586
+ return MAX_SAME_ACCOUNT_WAITS.includes(value) ? value : DEFAULT_MAX_SAME_ACCOUNT_WAIT;
4587
+ }
4588
+ var ROUTING_USAGE = "Usage: `/claude-routing`, `/claude-routing main-first`, `/claude-routing fallback-first`, `/claude-routing sticky-balanced`, or `/claude-routing reset`.";
4589
+ function normalizeRoutingMode(value) {
4590
+ return typeof value === "string" && ROUTING_MODES.includes(value) ? value : DEFAULT_ROUTING_MODE;
4591
+ }
4592
+ function getRoutingMode(storage) {
4593
+ return normalizeRoutingMode(storage?.routing?.mode);
4594
+ }
4595
+ function parseRoutingCommandAction(argumentsText) {
4596
+ const tokens = argumentsText.trim().toLowerCase().split(/\s+/).filter(Boolean);
4597
+ if (tokens.length === 0)
4598
+ return { type: "status" };
4599
+ if (tokens.length === 1 && tokens[0] === "reset")
4600
+ return { type: "reset" };
4601
+ if (tokens.length === 1 && ROUTING_MODES.includes(tokens[0])) {
4602
+ return { type: "mode", mode: tokens[0] };
4603
+ }
4604
+ if (tokens.length === 2 && tokens[0] === "mode" && ROUTING_MODES.includes(tokens[1])) {
4605
+ return { type: "mode", mode: tokens[1] };
4606
+ }
4607
+ return { type: "usage" };
4608
+ }
4609
+ function routingDescription(mode) {
4610
+ if (mode === "fallback-first") {
4611
+ return "Try usable fallback accounts before the main account. If no fallback succeeds, try the main account.";
4612
+ }
4613
+ if (mode === "sticky-balanced") {
4614
+ return "Assign each session to a quota-weighted OAuth account, keep it sticky across transient failures, and migrate only for confirmed long-lived exhaustion or permanent account failure.";
4615
+ }
4616
+ return "Try the main account first. Use fallback accounts only when quota policy or fallback errors require it.";
4617
+ }
4618
+ function buildRoutingStatusSummary(input) {
4619
+ const mode = input?.mode ?? DEFAULT_ROUTING_MODE;
4620
+ return [
4621
+ "## Claude Routing Status",
4622
+ "",
4623
+ `- Mode: \`${mode}\``,
4624
+ `- Longest wait on the same account: \`${input?.maxSameAccountWait ?? DEFAULT_MAX_SAME_ACCOUNT_WAIT}\``,
4625
+ `- Behavior: ${routingDescription(mode)}`,
4626
+ "",
4627
+ ROUTING_USAGE
4628
+ ].join(`
4629
+ `);
4630
+ }
4631
+ function executeRoutingCommand(input) {
4632
+ const action = parseRoutingCommandAction(input.argumentsText);
4633
+ const mode = input.mode ?? DEFAULT_ROUTING_MODE;
4634
+ const maxSameAccountWait = input.maxSameAccountWait;
4635
+ if (action.type === "status")
4636
+ return buildRoutingStatusSummary({ mode, maxSameAccountWait });
4637
+ if (action.type === "mode") {
4638
+ return [
4639
+ "## Claude Routing Updated",
4640
+ "",
4641
+ `Mode updated to \`${action.mode}\`.`,
4642
+ "",
4643
+ ...buildRoutingStatusSummary({ mode: action.mode, maxSameAccountWait }).split(`
4644
+ `).slice(2)
4645
+ ].join(`
4646
+ `);
4647
+ }
4648
+ if (action.type === "reset") {
4649
+ return [
4650
+ "## Claude Routing Assignment Reset",
4651
+ "",
4652
+ "The current session will be assigned again on its next request.",
4653
+ "",
4654
+ ...buildRoutingStatusSummary({ mode, maxSameAccountWait }).split(`
4655
+ `).slice(2)
4656
+ ].join(`
4657
+ `);
4658
+ }
4659
+ return [
4660
+ "## Claude Routing Usage",
4661
+ "",
4662
+ ROUTING_USAGE,
4663
+ "",
4664
+ ...buildRoutingStatusSummary({ mode, maxSameAccountWait }).split(`
4665
+ `).slice(2)
4666
+ ].join(`
4667
+ `);
4668
+ }
4669
+
4574
4670
  // src/accounts.ts
4575
4671
  var setRefreshLockRenewalTimeout2 = globalThis.setTimeout.bind(globalThis);
4576
4672
  var clearRefreshLockRenewalTimeout2 = globalThis.clearTimeout.bind(globalThis);
@@ -5261,34 +5357,75 @@ function killswitchPassesPolicy(quota, storage, accountId, modelId) {
5261
5357
  return !failClosedOnUnknownQuota(storage);
5262
5358
  return true;
5263
5359
  }
5264
- function killswitchRetryAfterSeconds(mainQuota, fallbackAccounts, now, scopedModelId) {
5360
+ function quotaRefusalTiming(input) {
5361
+ const now = input.now ?? Date.now();
5362
+ const maxAge = getQuotaCheckIntervalMs(input.storage ?? null);
5363
+ const fresh = (window) => Boolean(window && Number.isFinite(window.checkedAt) && window.checkedAt <= now && now - window.checkedAt < maxAge);
5265
5364
  const resetTimes = [];
5266
- const allQuotas = [mainQuota, ...fallbackAccounts.map((a) => a.quota)];
5267
- for (const quota of allQuotas) {
5268
- if (scopedModelId) {
5269
- const scopedWindow = getScopedQuotaWindowForModel(quota, scopedModelId);
5270
- const resetStr = scopedWindow?.resetsAt;
5271
- if (!resetStr)
5365
+ const storage = input.storage ?? null;
5366
+ const modelId = input.modelId ?? input.scopedModelId;
5367
+ const floors = quotaEnabled(storage) ? getQuotaMinimumRemainingThresholds(storage) : { five_hour: 0, seven_day: 0 };
5368
+ for (const { quota, accountIdentity, accountId } of input.readings) {
5369
+ if (!accountIdentity || quota?.accountIdentity !== accountIdentity)
5370
+ continue;
5371
+ const killswitch = isKillswitchEnabled(storage) ? getKillswitchThresholdsForAccount(storage, accountId === "main" ? undefined : accountId) : { five_hour: 0, seven_day: 0, scoped: 0 };
5372
+ const scoped = getScopedQuotaWindowForModel(quota, modelId);
5373
+ if (!quotaSnapshotHasStandardWindows(quota) || !fresh(quota.seven_day) || !quotaSnapshotOmitsFiveHour(quota) && !fresh(quota.five_hour) || scoped && !fresh(scoped) || modelId && killswitch.scoped > 0 && quota.scoped === undefined)
5374
+ continue;
5375
+ const blockers = [];
5376
+ let unknown = false;
5377
+ for (const key of ["five_hour", "seven_day"]) {
5378
+ if (key === "five_hour" && quotaSnapshotOmitsFiveHour(quota))
5272
5379
  continue;
5273
- const resetTime = Date.parse(resetStr);
5274
- if (Number.isFinite(resetTime) && resetTime > now) {
5275
- resetTimes.push(resetTime);
5380
+ const window = quota[key];
5381
+ if (!window || !Number.isFinite(window.remainingPercent)) {
5382
+ unknown = true;
5383
+ break;
5276
5384
  }
5277
- } else {
5278
- for (const key of ["five_hour", "seven_day"]) {
5279
- const resetStr = quota?.[key]?.resetsAt;
5280
- if (!resetStr)
5281
- continue;
5282
- const resetTime = Date.parse(resetStr);
5283
- if (Number.isFinite(resetTime) && resetTime > now) {
5284
- resetTimes.push(resetTime);
5285
- }
5385
+ if (window.remainingPercent <= 0 || window.remainingPercent < Math.max(floors[key], killswitch[key]))
5386
+ blockers.push(window);
5387
+ }
5388
+ if (scoped) {
5389
+ if (!Number.isFinite(scoped.remainingPercent))
5390
+ unknown = true;
5391
+ else if (scoped.remainingPercent <= killswitch.scoped)
5392
+ blockers.push(scoped);
5393
+ }
5394
+ let usableAt;
5395
+ for (const window of blockers) {
5396
+ const resetAt2 = Date.parse(window?.resetsAt ?? "");
5397
+ if (!Number.isFinite(resetAt2) || resetAt2 <= now) {
5398
+ unknown = true;
5399
+ break;
5286
5400
  }
5401
+ usableAt = Math.max(usableAt ?? resetAt2, resetAt2);
5287
5402
  }
5403
+ if (!unknown && usableAt !== undefined)
5404
+ resetTimes.push(usableAt);
5288
5405
  }
5289
- if (!resetTimes.length)
5290
- return 300;
5291
- return Math.max(1, Math.ceil((Math.min(...resetTimes) - now) / 1000)) + 60;
5406
+ const resetAt = resetTimes.length ? Math.min(...resetTimes) : undefined;
5407
+ const wait = getMaxSameAccountWait(input.storage ?? null);
5408
+ const ttlMs = input.sessionTtlMs && input.sessionTtlMs > 0 && Number.isFinite(input.sessionTtlMs) ? input.sessionTtlMs : 300000;
5409
+ const capMs = wait === "max" ? ttlMs : Number(wait) * 60000;
5410
+ return {
5411
+ resetAt,
5412
+ retryAfterSeconds: wait === "0" ? undefined : Math.max(1, Math.ceil(Math.min(resetAt === undefined ? 300000 : resetAt - now, capMs) / 1000))
5413
+ };
5414
+ }
5415
+ function killswitchRetryAfterSeconds(mainQuota, fallbackAccounts, now, scopedModelId, options) {
5416
+ return quotaRefusalTiming({
5417
+ ...options,
5418
+ now,
5419
+ scopedModelId,
5420
+ readings: [
5421
+ {
5422
+ quota: mainQuota,
5423
+ accountIdentity: options?.mainAccountIdentity,
5424
+ accountId: "main"
5425
+ },
5426
+ ...fallbackAccounts
5427
+ ]
5428
+ }).retryAfterSeconds ?? 0;
5292
5429
  }
5293
5430
  function getKillswitchConfig(storage) {
5294
5431
  return storage?.killswitch ?? { enabled: false };
@@ -20123,7 +20260,7 @@ function pick(source2, keys4) {
20123
20260
  return Object.fromEntries(keys4.filter((key) => Object.hasOwn(source2, key)).map((key) => [key, source2[key]]));
20124
20261
  }
20125
20262
  var settingFields = {
20126
- routing: ["mode"],
20263
+ routing: ["mode", "maxSameAccountWait"],
20127
20264
  refresh: ["enabled", "intervalMinutes", "refreshBeforeExpiryMinutes"],
20128
20265
  quota: [
20129
20266
  "enabled",
@@ -20150,6 +20287,7 @@ function validateNativeMigrationSettings(settings) {
20150
20287
  const threshold = (value) => record6(value) && Object.entries(value).every(([key, amount]) => ["five_hour", "seven_day", "5h", "1w", "scoped"].includes(key) && typeof amount === "number" && Number.isFinite(amount) && amount >= 0 && amount <= 100);
20151
20288
  const enums = {
20152
20289
  "routing.mode": ["main-first", "fallback-first", "sticky-balanced"],
20290
+ "routing.maxSameAccountWait": ["0", "15", "max"],
20153
20291
  "claudeCache.mode": CACHE_1H_MODES,
20154
20292
  "logging.level": ["debug", "info", "warn", "error", "trace"],
20155
20293
  "thinkingBinding.prefixMismatchBehavior": [
@@ -20577,7 +20715,7 @@ async function nativeVaultFileAbsent(path2) {
20577
20715
  }
20578
20716
  }
20579
20717
  var preferenceFields = {
20580
- routing: ["mode"],
20718
+ routing: ["mode", "maxSameAccountWait"],
20581
20719
  claudeCache: ["enabled", "mode"],
20582
20720
  cacheKeep: ["enabled", "always", "startHour", "endHour", "subagents"],
20583
20721
  quota: [
@@ -20816,9 +20954,84 @@ function mergeHeaderQuotaSnapshot(existing, incoming) {
20816
20954
  };
20817
20955
  }
20818
20956
 
20957
+ // src/quota-refusal.ts
20958
+ var details = new WeakMap;
20959
+ var quotaRefusalDetails = (response) => details.get(response);
20960
+ function createQuotaRefusalResponse(reason, timing, _now) {
20961
+ const reset = timing.resetAt === undefined ? "Reset time is unknown." : `Reset at ${new Intl.DateTimeFormat("en-US", {
20962
+ month: "long",
20963
+ day: "numeric",
20964
+ hour: "2-digit",
20965
+ minute: "2-digit",
20966
+ timeZoneName: "short"
20967
+ }).format(timing.resetAt)}.`;
20968
+ const seconds = timing.retryAfterSeconds;
20969
+ const retry = seconds === undefined ? "" : ` Retry in ${Math.floor(seconds / 60)}m ${seconds % 60}s.`;
20970
+ const response = new Response(JSON.stringify({
20971
+ type: "error",
20972
+ error: {
20973
+ type: timing.retryAfterSeconds === undefined ? "FAILED_PRECONDITION" : "rate_limit_error",
20974
+ message: `${reason}${retry} ${reset}`
20975
+ }
20976
+ }), {
20977
+ status: timing.retryAfterSeconds === undefined ? 412 : 429,
20978
+ headers: {
20979
+ "content-type": "application/json",
20980
+ ...timing.retryAfterSeconds === undefined ? {} : { "retry-after": String(timing.retryAfterSeconds) }
20981
+ }
20982
+ });
20983
+ details.set(response, { reason, timing });
20984
+ return response;
20985
+ }
20986
+
20987
+ // src/session-cache-activity.ts
20988
+ var PROMPT_CACHE_DEFAULT_TTL_MS = 5 * 60000;
20989
+ var PROMPT_CACHE_1H_TTL_MS = 60 * 60000;
20990
+
20991
+ class SessionCacheActivity {
20992
+ maxSessions;
20993
+ entries = new Map;
20994
+ constructor(maxSessions = 4096) {
20995
+ this.maxSessions = maxSessions;
20996
+ }
20997
+ record(sessionId, accountId, ttlMs, lastAcceptedAt = Date.now()) {
20998
+ this.entries.delete(sessionId);
20999
+ this.entries.set(sessionId, {
21000
+ accountId,
21001
+ lastAcceptedAt,
21002
+ ttlMs: ttlMs && Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : PROMPT_CACHE_DEFAULT_TTL_MS
21003
+ });
21004
+ if (this.entries.size > this.maxSessions) {
21005
+ const oldest = this.entries.keys().next().value;
21006
+ if (oldest !== undefined)
21007
+ this.entries.delete(oldest);
21008
+ }
21009
+ }
21010
+ holdUntil(sessionId, accountId, now = Date.now(), maxWait = "15") {
21011
+ if (!sessionId)
21012
+ return;
21013
+ const activity = this.entries.get(sessionId);
21014
+ if (!activity || activity.accountId !== accountId)
21015
+ return;
21016
+ return Math.min(activity.lastAcceptedAt + activity.ttlMs, maxWait === "max" ? Infinity : now + Number(maxWait) * 60000);
21017
+ }
21018
+ recordPrewarm(sessionId, accountId, acceptedAt = Date.now()) {
21019
+ const activity = this.entries.get(sessionId);
21020
+ if (activity && activity.accountId !== accountId)
21021
+ return;
21022
+ this.record(sessionId, accountId, PROMPT_CACHE_1H_TTL_MS, acceptedAt);
21023
+ }
21024
+ forget(sessionId) {
21025
+ this.entries.delete(sessionId);
21026
+ }
21027
+ ttlMs(sessionId) {
21028
+ return sessionId && this.entries.get(sessionId)?.ttlMs || PROMPT_CACHE_DEFAULT_TTL_MS;
21029
+ }
21030
+ }
21031
+ var sessionCacheActivity = new SessionCacheActivity;
21032
+
20819
21033
  // src/sticky-routing.ts
20820
21034
  var STICKY_ROUTING_MAIN_ACCOUNT_ID = "main";
20821
- var STICKY_ROUTING_SHORT_RESET_GRACE_MS = 15 * 60000;
20822
21035
  var STICKY_ROUTING_ASSIGNMENT_TTL_MS = 7 * 24 * 60 * 60000;
20823
21036
  var STICKY_ROUTING_TOUCH_INTERVAL_MS = 60 * 60000;
20824
21037
  var STICKY_ROUTING_LOCK_TTL_MS = 1e4;
@@ -20849,23 +21062,21 @@ function createStickyNoRouteResponse(input) {
20849
21062
  });
20850
21063
  }
20851
21064
  const scopedBlocked = Boolean(modelId && input.routeQuotas.length > 0 && input.routeQuotas.every((quota2) => !quotaSnapshotPassesModelScope(quota2, modelId)));
20852
- const [firstQuota, ...remainingQuotas] = input.routeQuotas;
20853
- const retryAfter = killswitchRetryAfterSeconds(firstQuota, remainingQuotas.map((quota2) => ({ quota: quota2 })), input.now ?? Date.now(), scopedBlocked ? modelId : undefined);
20854
- const minutes = Math.floor(retryAfter / 60);
20855
- const seconds = retryAfter % 60;
21065
+ const now = input.now ?? Date.now();
21066
+ const timing = quotaRefusalTiming({
21067
+ readings: input.routeQuotas.map((quota2, index) => ({
21068
+ quota: quota2,
21069
+ accountIdentity: input.routeIdentities?.[index],
21070
+ accountId: input.routeAccountIds?.[index]
21071
+ })),
21072
+ storage: input.storage,
21073
+ modelId,
21074
+ now,
21075
+ sessionTtlMs: sessionCacheActivity.ttlMs(input.sessionId)
21076
+ });
20856
21077
  const limitNames = input.vaultPolicyLimits?.map((limit) => limit === "model-scoped" ? `${modelName ?? "Model"} scoped limit` : limit === "killswitch" ? "killswitch limit" : "quota floor");
20857
21078
  const reason = limitNames ? `No vault account currently satisfies quota policy: ${limitNames.join(", ")}. Open /claude → Killswitch / Quota to change these limits.` : scopedBlocked && modelName ? `${modelName} weekly limit reached, no routable OAuth accounts.` : "No OAuth account currently satisfies sticky-balanced quota policy.";
20858
- const message = `${reason} Retry in ${minutes}m ${seconds}s.`;
20859
- return new Response(JSON.stringify({
20860
- type: "error",
20861
- error: { type: "rate_limit_error", message }
20862
- }), {
20863
- status: 429,
20864
- headers: {
20865
- "content-type": "application/json",
20866
- "retry-after": String(retryAfter)
20867
- }
20868
- });
21079
+ return createQuotaRefusalResponse(reason, timing, now);
20869
21080
  }
20870
21081
  function isRecord11(value) {
20871
21082
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
@@ -21078,7 +21289,8 @@ function decideStickyQuotaFailure(input) {
21078
21289
  }
21079
21290
  if (!blocking)
21080
21291
  return { action: "retain", reason: "not-exhausted" };
21081
- if (blocking.resetAt - now <= STICKY_ROUTING_SHORT_RESET_GRACE_MS) {
21292
+ const jitterMs = input.sessionId ? (stickyRetryAfterWithJitter(input.sessionId, 1) - 1) * 1000 : 0;
21293
+ if (input.holdUntil !== undefined && blocking.resetAt + jitterMs <= input.holdUntil) {
21082
21294
  return {
21083
21295
  action: "hold",
21084
21296
  reason: `${blocking.reason}-short-reset`,
@@ -24149,7 +24361,7 @@ function nativeVaultPrimaryRow(roster, pin) {
24149
24361
  return roster?.rows.find((row) => row.routeId === pin.routeId && row.accountIdentity === pin.accountIdentity && (row.credentialId === pin.credentialId || row.aliases?.includes(pin.credentialId)));
24150
24362
  }
24151
24363
  var settingFields2 = {
24152
- routing: ["mode"],
24364
+ routing: ["mode", "maxSameAccountWait"],
24153
24365
  refresh: ["enabled", "intervalMinutes", "refreshBeforeExpiryMinutes"],
24154
24366
  quota: [
24155
24367
  "enabled",
@@ -33589,6 +33801,21 @@ var actions = Object.freeze([
33589
33801
  label: "Reset routing session",
33590
33802
  parameters: []
33591
33803
  },
33804
+ {
33805
+ ...ordinary,
33806
+ id: "routing-max-same-account-wait",
33807
+ command: "routing",
33808
+ group: "Routing",
33809
+ label: "Longest wait on the same account",
33810
+ parameters: [
33811
+ {
33812
+ id: "maxSameAccountWait",
33813
+ kind: "choice",
33814
+ required: true,
33815
+ choices: ["0", "15", "max"]
33816
+ }
33817
+ ]
33818
+ },
33592
33819
  {
33593
33820
  ...ordinary,
33594
33821
  id: "killswitch-on",
@@ -34620,10 +34847,17 @@ function knob(parameter) {
34620
34847
  return {
34621
34848
  kind: "choice",
34622
34849
  id: parameter.id,
34623
- label: parameter.id,
34850
+ label: parameter.id === "maxSameAccountWait" ? "Longest wait on the same account" : parameter.id,
34624
34851
  choices: [
34625
34852
  ...!parameter.required ? [{ value: "", label: "Default" }] : [],
34626
- ...parameter.choices.map((value) => ({ value, label: value }))
34853
+ ...parameter.choices.map((value) => ({
34854
+ value,
34855
+ label: parameter.id === "maxSameAccountWait" ? {
34856
+ "0": "Don't wait",
34857
+ "15": "15 minutes",
34858
+ max: "Until the cache expires"
34859
+ }[value] : value
34860
+ }))
34627
34861
  ]
34628
34862
  };
34629
34863
  case "number":
@@ -35627,6 +35861,10 @@ function createNativeVaultNoRouteResponse(input) {
35627
35861
  return createStickyNoRouteResponse({
35628
35862
  routeQuotas: active2.flatMap((account) => account.quota ? [account.quota] : []),
35629
35863
  modelId,
35864
+ routeIdentities: active2.filter((account) => account.quota).map((account) => account.accountIdentity),
35865
+ routeAccountIds: active2.filter((account) => account.quota).map((account) => account.id),
35866
+ storage: snapshot.policyStorage,
35867
+ sessionId: input.sessionId,
35630
35868
  vaultPolicyLimits: [...limits]
35631
35869
  });
35632
35870
  }
@@ -35635,7 +35873,7 @@ class NativeVaultQuotaPolicyError extends Error {
35635
35873
  response;
35636
35874
  body;
35637
35875
  kind = "quota-policy";
35638
- status = 429;
35876
+ status;
35639
35877
  headers;
35640
35878
  retryAfter;
35641
35879
  constructor(response, body) {
@@ -35643,6 +35881,7 @@ class NativeVaultQuotaPolicyError extends Error {
35643
35881
  this.response = response;
35644
35882
  this.body = body;
35645
35883
  this.name = "NativeVaultQuotaPolicyError";
35884
+ this.status = response.status;
35646
35885
  this.headers = new Headers(response.headers);
35647
35886
  this.retryAfter = Number(this.headers.get("retry-after"));
35648
35887
  }
@@ -37109,9 +37348,9 @@ var TRAILING_ASSISTANT_HISTORY_MESSAGE = "Cannot send this request: the history
37109
37348
  class TrailingAssistantHistoryError extends Error {
37110
37349
  details;
37111
37350
  check = "meaningful_trailing_assistant";
37112
- constructor(details) {
37351
+ constructor(details2) {
37113
37352
  super(TRAILING_ASSISTANT_HISTORY_MESSAGE);
37114
- this.details = details;
37353
+ this.details = details2;
37115
37354
  this.name = "TrailingAssistantHistoryError";
37116
37355
  }
37117
37356
  }
@@ -37175,93 +37414,6 @@ function stripEmptyTrailingAssistantMessages(messages) {
37175
37414
  messages.length -= removed;
37176
37415
  return removed;
37177
37416
  }
37178
- // src/routing.ts
37179
- var CLAUDE_ROUTING_COMMAND_NAME = "claude-routing";
37180
- var ROUTING_MODES = [
37181
- "main-first",
37182
- "fallback-first",
37183
- "sticky-balanced"
37184
- ];
37185
- var DEFAULT_ROUTING_MODE = "main-first";
37186
- var ROUTING_USAGE = "Usage: `/claude-routing`, `/claude-routing main-first`, `/claude-routing fallback-first`, `/claude-routing sticky-balanced`, or `/claude-routing reset`.";
37187
- function normalizeRoutingMode(value) {
37188
- return typeof value === "string" && ROUTING_MODES.includes(value) ? value : DEFAULT_ROUTING_MODE;
37189
- }
37190
- function getRoutingMode(storage) {
37191
- return normalizeRoutingMode(storage?.routing?.mode);
37192
- }
37193
- function parseRoutingCommandAction(argumentsText) {
37194
- const tokens = argumentsText.trim().toLowerCase().split(/\s+/).filter(Boolean);
37195
- if (tokens.length === 0)
37196
- return { type: "status" };
37197
- if (tokens.length === 1 && tokens[0] === "reset")
37198
- return { type: "reset" };
37199
- if (tokens.length === 1 && ROUTING_MODES.includes(tokens[0])) {
37200
- return { type: "mode", mode: tokens[0] };
37201
- }
37202
- if (tokens.length === 2 && tokens[0] === "mode" && ROUTING_MODES.includes(tokens[1])) {
37203
- return { type: "mode", mode: tokens[1] };
37204
- }
37205
- return { type: "usage" };
37206
- }
37207
- function routingDescription(mode) {
37208
- if (mode === "fallback-first") {
37209
- return "Try usable fallback accounts before the main account. If no fallback succeeds, try the main account.";
37210
- }
37211
- if (mode === "sticky-balanced") {
37212
- return "Assign each session to a quota-weighted OAuth account, keep it sticky across transient failures, and migrate only for confirmed long-lived exhaustion or permanent account failure.";
37213
- }
37214
- return "Try the main account first. Use fallback accounts only when quota policy or fallback errors require it.";
37215
- }
37216
- function buildRoutingStatusSummary(input) {
37217
- const mode = input?.mode ?? DEFAULT_ROUTING_MODE;
37218
- return [
37219
- "## Claude Routing Status",
37220
- "",
37221
- `- Mode: \`${mode}\``,
37222
- `- Behavior: ${routingDescription(mode)}`,
37223
- "",
37224
- ROUTING_USAGE
37225
- ].join(`
37226
- `);
37227
- }
37228
- function executeRoutingCommand(input) {
37229
- const action = parseRoutingCommandAction(input.argumentsText);
37230
- const mode = input.mode ?? DEFAULT_ROUTING_MODE;
37231
- if (action.type === "status")
37232
- return buildRoutingStatusSummary({ mode });
37233
- if (action.type === "mode") {
37234
- return [
37235
- "## Claude Routing Updated",
37236
- "",
37237
- `Mode updated to \`${action.mode}\`.`,
37238
- "",
37239
- ...buildRoutingStatusSummary({ mode: action.mode }).split(`
37240
- `).slice(2)
37241
- ].join(`
37242
- `);
37243
- }
37244
- if (action.type === "reset") {
37245
- return [
37246
- "## Claude Routing Assignment Reset",
37247
- "",
37248
- "The current session will be assigned again on its next request.",
37249
- "",
37250
- ...buildRoutingStatusSummary({ mode }).split(`
37251
- `).slice(2)
37252
- ].join(`
37253
- `);
37254
- }
37255
- return [
37256
- "## Claude Routing Usage",
37257
- "",
37258
- ROUTING_USAGE,
37259
- "",
37260
- ...buildRoutingStatusSummary({ mode }).split(`
37261
- `).slice(2)
37262
- ].join(`
37263
- `);
37264
- }
37265
37417
  // src/start.ts
37266
37418
  var CLAUDE_START_COMMAND_NAME = "claude-start";
37267
37419
  var START_STATUS_TITLE = "## Claude Lane Start Status";
@@ -39536,6 +39688,7 @@ export {
39536
39688
  setCache1hMode,
39537
39689
  setCache1hEnabled,
39538
39690
  setBounded,
39691
+ sessionCacheActivity,
39539
39692
  sendsPerTurnControlBeta,
39540
39693
  sendWithRequestGzip,
39541
39694
  sendViaRelay,
@@ -39599,6 +39752,8 @@ export {
39599
39752
  quotaSnapshotModelScopeIsExhausted,
39600
39753
  quotaSnapshotHasStandardWindows,
39601
39754
  quotaSnapshotCheckedAt,
39755
+ quotaRefusalTiming,
39756
+ quotaRefusalDetails,
39602
39757
  quotaFieldSource,
39603
39758
  quotaExhaustionFromHeaders,
39604
39759
  quotaDisplayProjection,
@@ -39743,6 +39898,7 @@ export {
39743
39898
  getPersistedLogLevel,
39744
39899
  getOpenCodeConfigDir,
39745
39900
  getNativeMenuModel,
39901
+ getMaxSameAccountWait,
39746
39902
  getLogLevel,
39747
39903
  getLogFilePath,
39748
39904
  getKillswitchThresholdsForAccount,
@@ -39828,6 +39984,7 @@ export {
39828
39984
  createStickyNoRouteResponse,
39829
39985
  createSseFramer,
39830
39986
  createRelocationGuard,
39987
+ createQuotaRefusalResponse,
39831
39988
  createProviderErrorResponseScope,
39832
39989
  createProviderErrorRedactor,
39833
39990
  createProcessFence,
@@ -39910,7 +40067,7 @@ export {
39910
40067
  StateLayoutRefusalError,
39911
40068
  StateLayoutFileError,
39912
40069
  SseFrameTooLargeError,
39913
- STICKY_ROUTING_SHORT_RESET_GRACE_MS,
40070
+ SessionCacheActivity,
39914
40071
  STICKY_ROUTING_MAIN_ACCOUNT_ID,
39915
40072
  STICKY_ROUTING_ASSIGNMENT_TTL_MS,
39916
40073
  STATE_LAYOUT_REFUSAL_PUBLIC_MESSAGES,
@@ -39935,6 +40092,8 @@ export {
39935
40092
  QUOTA_HEADER_FEED_LEASE_MS,
39936
40093
  QUOTA_FIELD_NAMES,
39937
40094
  PrimeManager,
40095
+ PROMPT_CACHE_DEFAULT_TTL_MS,
40096
+ PROMPT_CACHE_1H_TTL_MS,
39938
40097
  PROFILE_TTL_MS,
39939
40098
  PRODUCTION_CLAUSTRUM_CONNECTION_FILE_NAME,
39940
40099
  PRIVATE_FILES_UNAVAILABLE_MESSAGE,
@@ -39962,6 +40121,7 @@ export {
39962
40121
  NativeCustodyActivationError,
39963
40122
  NativeAccountRefusal,
39964
40123
  NATIVE_VAULT_NO_ACCOUNT_MESSAGE,
40124
+ MAX_SAME_ACCOUNT_WAITS,
39965
40125
  LOGGING_LEVELS,
39966
40126
  LEGACY_STATE_LAYOUT,
39967
40127
  KILLSWITCH_COMMAND_NAME,
@@ -39977,6 +40137,7 @@ export {
39977
40137
  FALLBACK_BACKGROUND_TICK_MS,
39978
40138
  DEFAULT_SSE_MAX_FRAME_BYTES,
39979
40139
  DEFAULT_ROUTING_MODE,
40140
+ DEFAULT_MAX_SAME_ACCOUNT_WAIT,
39980
40141
  DEFAULT_KILLSWITCH_THRESHOLDS,
39981
40142
  DEFAULT_CACHE_1H_MODE,
39982
40143
  CustodyTombstoneRefreshError,
@@ -1,4 +1,4 @@
1
- import { type NativeMenuActionId, type NativeMenuCacheMode, type NativeMenuCustodyMode, type NativeMenuHost, type NativeMenuLogLevel, type NativeMenuParameterId, type NativeMenuRefusalCode, type NativeMenuRoutingMode } from './native-menu-model.ts';
1
+ import { type NativeMenuActionId, type NativeMenuCacheMode, type NativeMenuCustodyMode, type NativeMenuHost, type NativeMenuLogLevel, type NativeMenuMaxSameAccountWait, type NativeMenuParameterId, type NativeMenuRefusalCode, type NativeMenuRoutingMode } from './native-menu-model.ts';
2
2
  /**
3
3
  * Typed input checking and safety gating for native menu actions.
4
4
  *
@@ -74,6 +74,9 @@ export type NativeMenuActionValues = {
74
74
  readonly 'routing-mode': {
75
75
  readonly mode: NativeMenuRoutingMode;
76
76
  };
77
+ readonly 'routing-max-same-account-wait': {
78
+ readonly maxSameAccountWait: NativeMenuMaxSameAccountWait;
79
+ };
77
80
  readonly 'routing-reset': NativeMenuNoValues;
78
81
  readonly 'killswitch-on': NativeMenuNoValues;
79
82
  readonly 'killswitch-off': NativeMenuNoValues;
@@ -8,8 +8,9 @@ export type NativeMenuRefusalCode = 'interactive-required' | 'offline-required';
8
8
  export type NativeMenuCustodyMode = 'local' | 'claustrum';
9
9
  export type NativeMenuRoutingMode = 'main-first' | 'fallback-first' | 'sticky-balanced';
10
10
  export type NativeMenuCacheMode = 'explicit' | 'automatic' | 'hybrid';
11
+ export type NativeMenuMaxSameAccountWait = '0' | '15' | 'max';
11
12
  export type NativeMenuLogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace';
12
- export type NativeMenuParameterId = 'id' | 'apiKey' | 'label' | 'baseURL' | 'authHeader' | 'code' | 'mode' | 'entries' | 'startHour' | 'endHour' | 'enabled' | 'level';
13
+ export type NativeMenuParameterId = 'id' | 'apiKey' | 'label' | 'baseURL' | 'authHeader' | 'code' | 'mode' | 'maxSameAccountWait' | 'entries' | 'startHour' | 'endHour' | 'enabled' | 'level';
13
14
  export type NativeMenuChoiceParameter<Id extends NativeMenuParameterId = NativeMenuParameterId, Choice extends string = string> = {
14
15
  readonly id: Id;
15
16
  readonly kind: 'choice';
@@ -26,7 +27,7 @@ export type NativeMenuParameter = {
26
27
  readonly kind: 'text';
27
28
  readonly required: boolean;
28
29
  readonly protectedEntry: boolean;
29
- } | NativeMenuChoiceParameter<'mode', NativeMenuCustodyMode> | NativeMenuChoiceParameter<'mode', NativeMenuRoutingMode> | NativeMenuChoiceParameter<'mode', NativeMenuCacheMode> | NativeMenuChoiceParameter<'authHeader', 'authorization-bearer' | 'x-api-key'> | NativeMenuChoiceParameter<'enabled', 'on' | 'off'> | NativeMenuChoiceParameter<'level', NativeMenuLogLevel> | {
30
+ } | NativeMenuChoiceParameter<'mode', NativeMenuCustodyMode> | NativeMenuChoiceParameter<'mode', NativeMenuRoutingMode> | NativeMenuChoiceParameter<'maxSameAccountWait', NativeMenuMaxSameAccountWait> | NativeMenuChoiceParameter<'mode', NativeMenuCacheMode> | NativeMenuChoiceParameter<'authHeader', 'authorization-bearer' | 'x-api-key'> | NativeMenuChoiceParameter<'enabled', 'on' | 'off'> | NativeMenuChoiceParameter<'level', NativeMenuLogLevel> | {
30
31
  readonly id: 'startHour' | 'endHour';
31
32
  readonly kind: 'number';
32
33
  readonly required: true;
@@ -36,7 +37,7 @@ export type NativeMenuParameter = {
36
37
  readonly required: true;
37
38
  readonly fields: readonly ['account', 'fh', 'sd', 'scoped?'];
38
39
  };
39
- export type NativeMenuActionId = 'enable' | 'disable' | 'remove' | 'move-up' | 'move-down' | 'reset-backoff' | 'enrollment-reset' | 'add-apikey' | 'add-oauth-start' | 'add-oauth-finish' | 'custody-mode' | 'vault-disconnect' | 'quota-refresh' | 'routing-mode' | 'routing-reset' | 'killswitch-on' | 'killswitch-off' | 'killswitch-set' | 'cache-on' | 'cache-off' | 'cache-mode' | 'cachekeep-always' | 'cachekeep-off' | 'cachekeep-window' | 'cachekeep-subagents' | 'dump-on' | 'dump-off' | 'logging-level' | 'fast-on' | 'fast-off' | 'prime-on' | 'prime-off' | 'start-fire';
40
+ export type NativeMenuActionId = 'enable' | 'disable' | 'remove' | 'move-up' | 'move-down' | 'reset-backoff' | 'enrollment-reset' | 'add-apikey' | 'add-oauth-start' | 'add-oauth-finish' | 'custody-mode' | 'vault-disconnect' | 'quota-refresh' | 'routing-mode' | 'routing-max-same-account-wait' | 'routing-reset' | 'killswitch-on' | 'killswitch-off' | 'killswitch-set' | 'cache-on' | 'cache-off' | 'cache-mode' | 'cachekeep-always' | 'cachekeep-off' | 'cachekeep-window' | 'cachekeep-subagents' | 'dump-on' | 'dump-off' | 'logging-level' | 'fast-on' | 'fast-off' | 'prime-on' | 'prime-off' | 'start-fire';
40
41
  type DestructiveId = 'remove' | 'enrollment-reset' | 'vault-disconnect';
41
42
  type InteractiveId = 'add-apikey' | 'add-oauth-start' | 'add-oauth-finish' | 'custody-mode' | 'vault-disconnect';
42
43
  type ActionSafety<Id extends NativeMenuActionId> = (Id extends DestructiveId ? {
@@ -6,11 +6,12 @@ export declare function createNativeVaultNoRouteResponse(input: {
6
6
  modelId?: string;
7
7
  policies?: ReadonlyMap<string, NativeAccountPolicy>;
8
8
  sticky?: boolean;
9
+ sessionId?: string | null;
9
10
  }): Response;
10
11
  type QuotaPolicyBody = {
11
12
  type: 'error';
12
13
  error: {
13
- type: 'rate_limit_error';
14
+ type: 'rate_limit_error' | 'FAILED_PRECONDITION';
14
15
  message: string;
15
16
  };
16
17
  };
@@ -19,7 +20,7 @@ export declare class NativeVaultQuotaPolicyError extends Error {
19
20
  readonly response: Response;
20
21
  readonly body: QuotaPolicyBody;
21
22
  readonly kind = "quota-policy";
22
- readonly status = 429;
23
+ readonly status: number;
23
24
  readonly headers: Headers;
24
25
  readonly retryAfter: number;
25
26
  private constructor();
@@ -0,0 +1,6 @@
1
+ import type { quotaRefusalTiming } from './accounts.ts';
2
+ export declare const quotaRefusalDetails: (response: Response) => {
3
+ reason: string;
4
+ timing: ReturnType<typeof quotaRefusalTiming>;
5
+ } | undefined;
6
+ export declare function createQuotaRefusalResponse(reason: string, timing: ReturnType<typeof quotaRefusalTiming>, _now?: number): Response;
package/dist/routing.d.ts CHANGED
@@ -2,6 +2,10 @@ import type { AccountStorage, RoutingMode } from './accounts.ts';
2
2
  export declare const CLAUDE_ROUTING_COMMAND_NAME = "claude-routing";
3
3
  export declare const ROUTING_MODES: readonly ['main-first', 'fallback-first', 'sticky-balanced'];
4
4
  export declare const DEFAULT_ROUTING_MODE: RoutingMode;
5
+ export declare const MAX_SAME_ACCOUNT_WAITS: readonly ['0', '15', 'max'];
6
+ export type MaxSameAccountWait = (typeof MAX_SAME_ACCOUNT_WAITS)[number];
7
+ export declare const DEFAULT_MAX_SAME_ACCOUNT_WAIT: MaxSameAccountWait;
8
+ export declare function getMaxSameAccountWait(storage: AccountStorage | null): MaxSameAccountWait;
5
9
  type RoutingCommandAction = {
6
10
  type: 'status';
7
11
  } | {
@@ -16,9 +20,11 @@ export declare function getRoutingMode(storage: AccountStorage | null): RoutingM
16
20
  export declare function parseRoutingCommandAction(argumentsText: string): RoutingCommandAction;
17
21
  export declare function buildRoutingStatusSummary(input?: {
18
22
  mode?: RoutingMode;
23
+ maxSameAccountWait?: MaxSameAccountWait;
19
24
  }): string;
20
25
  export declare function executeRoutingCommand(input: {
21
26
  argumentsText: string;
22
27
  mode?: RoutingMode;
28
+ maxSameAccountWait?: MaxSameAccountWait;
23
29
  }): string;
24
30
  export {};
@@ -0,0 +1,16 @@
1
+ import type { MaxSameAccountWait } from './routing.ts';
2
+ export declare const PROMPT_CACHE_DEFAULT_TTL_MS: number;
3
+ export declare const PROMPT_CACHE_1H_TTL_MS: number;
4
+ /** Process-local cache lifetime evidence; failures and waits never extend it. */
5
+ export declare class SessionCacheActivity {
6
+ private readonly maxSessions;
7
+ private readonly entries;
8
+ constructor(maxSessions?: number);
9
+ record(sessionId: string, accountId: string, ttlMs: number | undefined, lastAcceptedAt?: number): void;
10
+ holdUntil(sessionId: string | null | undefined, accountId: string, now?: number, maxWait?: MaxSameAccountWait): number | undefined;
11
+ /** A late keep-warm send must not replace a newer turn on a different account. */
12
+ recordPrewarm(sessionId: string, accountId: string, acceptedAt?: number): void;
13
+ forget(sessionId: string): void;
14
+ ttlMs(sessionId: string | null | undefined): number;
15
+ }
16
+ export declare const sessionCacheActivity: SessionCacheActivity;
@@ -4,7 +4,6 @@ import { type NativeLockEvent } from './native-lock-observer.ts';
4
4
  import type { NativeVaultRosterDocument } from './native-roster-seed.ts';
5
5
  import { type NativeVaultRoutingSeed } from './native-vault-seed.ts';
6
6
  export declare const STICKY_ROUTING_MAIN_ACCOUNT_ID = "main";
7
- export declare const STICKY_ROUTING_SHORT_RESET_GRACE_MS: number;
8
7
  export declare const STICKY_ROUTING_ASSIGNMENT_TTL_MS: number;
9
8
  export type StickyRouteFamily = 'fable' | 'opus' | 'general';
10
9
  export type IdentityState = {
@@ -61,6 +60,10 @@ export declare function createStickyNoRouteResponse(input: {
61
60
  mainRefreshError?: AccountOperationError;
62
61
  fallbackReauthLabels?: readonly string[];
63
62
  routeQuotas: readonly OAuthQuotaSnapshot[];
63
+ routeIdentities?: readonly (string | undefined)[];
64
+ routeAccountIds?: readonly string[];
65
+ storage?: AccountStorage | null;
66
+ sessionId?: string | null;
64
67
  vaultPolicyLimits?: readonly NativeQuotaPolicyLimit[];
65
68
  modelId?: string;
66
69
  now?: number;
@@ -96,6 +99,8 @@ export declare function decideStickyQuotaFailure(input: {
96
99
  responseHeaders?: Headers;
97
100
  modelId?: string;
98
101
  now?: number;
102
+ sessionId?: string;
103
+ holdUntil?: number;
99
104
  }): StickyQuotaFailureDecision;
100
105
  /** Bound an unconfirmed 429's host retry while preserving any shorter upstream wait. */
101
106
  export declare function stickyRetainRetryHeaders(upstream: Headers, now?: number): Headers;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/anthropic-auth-core",
3
- "version": "2.4.11",
3
+ "version": "2.4.13",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",