@cortexkit/pi-anthropic-auth 2.10.1 → 2.11.1

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.
package/dist/native.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type NativeAccountRuntime, type NativeAccountRuntimeOptions, type NativeAccountSnapshot, type NativeCustodyClient, type NativeCustodyReceipt, type NativeCustodyReporterSource, type NativeRefreshResult } from '@cortexkit/anthropic-auth-core';
1
+ import { type NativeAccountRuntime, type NativeAccountRuntimeOptions, type NativeAccountSnapshot, type NativeCustodyClient, type NativeCustodyReceipt, type NativeCustodyReporterSource, type NativeRefreshResult, type RoutingChoice } from '@cortexkit/anthropic-auth-core';
2
2
  import { type PiPrimeLease, type PiPrimeOptions } from './prime.ts';
3
3
  export type PiNativeAttempt = {
4
4
  source: 'local';
@@ -79,8 +79,8 @@ export declare class PiNativeRuntime {
79
79
  view(signal?: AbortSignal): Promise<NativeAccountSnapshot>;
80
80
  /** Admit a model request without rediscovering a healthy roster. */
81
81
  requestView(signal?: AbortSignal): Promise<NativeAccountSnapshot>;
82
- authorize(routeId: string, signal?: AbortSignal, modelId?: string, intent?: 'serve' | 'cachekeep'): Promise<PiNativeAttempt>;
83
- retry(routeId: string, served: PiNativeAttempt, signal?: AbortSignal, modelId?: string): Promise<PiNativeAttempt | undefined>;
82
+ authorize(routeId: string, signal?: AbortSignal, modelId?: string, intent?: 'serve' | 'cachekeep', routingChoice?: RoutingChoice): Promise<PiNativeAttempt>;
83
+ retry(routeId: string, served: PiNativeAttempt, signal?: AbortSignal, modelId?: string, routingChoice?: RoutingChoice): Promise<PiNativeAttempt | undefined>;
84
84
  report(served: PiNativeAttempt, status: number, source: NativeCustodyReporterSource): Promise<void>;
85
85
  markUsed(served: PiNativeAttempt, servingRuntime?: NativeAccountRuntime): Promise<void>;
86
86
  close(): Promise<void>;
package/dist/native.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { resolve } from 'node:path';
2
- import { acquireNativeAccountRuntime, createNativeUsagePublisher, decidePiStateLayout, getAccountStatePath, getHostClaustrumEnrollmentPaths, getPersistedLogLevel, isKillswitchEnabled, isVaultHosted, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, logger, NativeAccountRefusal, nativeAccountCanServe, nativeAccountRefusal, nativeLocalAccountRefusal, nativeMigrationAuthorityPhase, nativeRuntimeOptionIdentity, quotaSnapshotHasStandardWindows, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, readNativeAccountsForRequest, readNativeMigrationJournal, resolveClaustrumConnectionPath, resolveLocalRoutingDestination, resolveNativePoolPaths, setLogLevel, } from '@cortexkit/anthropic-auth-core';
2
+ import { acquireNativeAccountRuntime, createNativeUsagePublisher, decidePiStateLayout, getAccountStatePath, getHostClaustrumEnrollmentPaths, getPersistedLogLevel, isKillswitchEnabled, isVaultHosted, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, logger, NativeAccountRefusal, nativeAccountCanServe, nativeAccountRefusal, nativeLocalAccountRefusal, nativeMigrationAuthorityPhase, nativeRuntimeOptionIdentity, quotaSnapshotHasStandardWindows, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, readNativeAccountsForRequest, readNativeMigrationJournal, resolveClaustrumConnectionPath, resolveLocalRoutingDestination, resolveNativePoolPaths, routingChoiceMatches, setLogLevel, } from '@cortexkit/anthropic-auth-core';
3
3
  import { getPiAccountStoragePath, getPiClaustrumConnectionOptions, getPiConfigDir, requirePiNativeHostAuth, } from './paths.js';
4
4
  import { acquirePiPrime, } from './prime.js';
5
5
  export function piAttemptAccessToken(attempt) {
@@ -7,12 +7,14 @@ export function piAttemptAccessToken(attempt) {
7
7
  ? attempt.receipt.accessToken
8
8
  : attempt.admission.access;
9
9
  }
10
- function requestPolicy(routeId, modelId) {
10
+ function requestPolicy(routeId, modelId, routingChoice) {
11
11
  return (account, current) => {
12
12
  if (!nativeAccountCanServe(account))
13
13
  return { status: 'blocked', reason: 'account-disabled' };
14
14
  if (account.source === 'local' && current.mode !== 'local')
15
15
  return { status: 'blocked', reason: 'local-mode-unavailable' };
16
+ if (routingChoice && routingChoiceMatches(routingChoice, account))
17
+ return { status: 'allowed' };
16
18
  const storage = current.policyStorage;
17
19
  const needsQuotaPolicy = quotaSnapshotHasStandardWindows(account.quota) &&
18
20
  (account.source !== 'vault' ||
@@ -239,7 +241,7 @@ export class PiNativeRuntime {
239
241
  const runtime = await this.service();
240
242
  return readNativeAccountsForRequest(runtime, signal);
241
243
  }
242
- async authorize(routeId, signal, modelId, intent = 'serve') {
244
+ async authorize(routeId, signal, modelId, intent = 'serve', routingChoice) {
243
245
  const background = intent === 'cachekeep';
244
246
  const runtime = await this.service();
245
247
  const snapshot = await runtime.read();
@@ -248,7 +250,7 @@ export class PiNativeRuntime {
248
250
  throw background
249
251
  ? new NativeAccountRefusal('account-unavailable')
250
252
  : new Error('Pi native OAuth route is unavailable');
251
- const policy = requestPolicy(routeId, modelId);
253
+ const policy = requestPolicy(routeId, modelId, routingChoice);
252
254
  if (policy(account, snapshot).status === 'blocked')
253
255
  throw background
254
256
  ? new NativeAccountRefusal('account-policy')
@@ -271,7 +273,7 @@ export class PiNativeRuntime {
271
273
  if (!admitted ||
272
274
  current.mode !== 'claustrum' ||
273
275
  admitted.accountIdentity !== receipt.assertedAccountIdentity ||
274
- requestPolicy(routeId, modelId)(admitted, current).status === 'blocked')
276
+ policy(admitted, current).status === 'blocked')
275
277
  throw background
276
278
  ? new NativeAccountRefusal(!admitted || current.mode !== 'claustrum'
277
279
  ? 'account-unavailable'
@@ -302,14 +304,15 @@ export class PiNativeRuntime {
302
304
  admission,
303
305
  };
304
306
  }
305
- async retry(routeId, served, signal, modelId) {
307
+ async retry(routeId, served, signal, modelId, routingChoice) {
306
308
  const runtime = await this.service();
307
309
  if (served.source === 'vault') {
308
310
  const current = await runtime.read();
309
311
  const account = current.accounts.find((candidate) => candidate.id === routeId);
310
312
  if (!account ||
311
313
  current.mode !== 'claustrum' ||
312
- requestPolicy(routeId, modelId)(account, current).status === 'blocked')
314
+ requestPolicy(routeId, modelId, routingChoice)(account, current)
315
+ .status === 'blocked')
313
316
  return undefined;
314
317
  const decision = await runtime.vault.prepareRetry(served.receipt, signal);
315
318
  logger.debug('native-auth', 'Pi 401 retry decision', {
@@ -328,7 +331,8 @@ export class PiNativeRuntime {
328
331
  if (!admitted ||
329
332
  after.mode !== 'claustrum' ||
330
333
  admitted.accountIdentity !== decision.receipt.assertedAccountIdentity ||
331
- requestPolicy(routeId, modelId)(admitted, after).status === 'blocked')
334
+ requestPolicy(routeId, modelId, routingChoice)(admitted, after)
335
+ .status === 'blocked')
332
336
  return undefined;
333
337
  return {
334
338
  source: 'vault',
@@ -340,7 +344,7 @@ export class PiNativeRuntime {
340
344
  intent: 'refresh',
341
345
  rejectedAccessToken: served.admission.access,
342
346
  signal,
343
- policy: requestPolicy(routeId, modelId),
347
+ policy: requestPolicy(routeId, modelId, routingChoice),
344
348
  });
345
349
  if (admission.status !== 'usable' ||
346
350
  admission.binding.identity !== served.accountIdentity ||
@@ -1,4 +1,4 @@
1
- import { createQuotaRefusalResponse, quotaRefusalDetails, } from '@cortexkit/anthropic-auth-core';
1
+ import { clampHostRetryMs, createQuotaRefusalResponse, hostRetryResponse, quotaRefusalDetails, } from '@cortexkit/anthropic-auth-core';
2
2
  const holds = new WeakMap();
3
3
  export function markPiAccountHold(response, hold) {
4
4
  holds.set(response, hold);
@@ -9,13 +9,14 @@ async function waitForReset(delayMs, resetAt, signal, options) {
9
9
  const set = options.setTimeout ?? globalThis.setTimeout;
10
10
  const clear = options.clearTimeout ?? globalThis.clearTimeout;
11
11
  const when = resetAt ?? (options.now?.() ?? Date.now()) + delayMs;
12
- const time = new Date(when).toLocaleTimeString(undefined, {
12
+ const time = new Date(when).toLocaleTimeString('en-GB', {
13
13
  hour: '2-digit',
14
14
  minute: '2-digit',
15
15
  hour12: false,
16
+ timeZone: 'UTC',
16
17
  });
17
18
  try {
18
- options.setWorkingMessage?.(`Waiting for the account to reset at ${time} · Esc to cancel`);
19
+ options.setWorkingMessage?.(`Checking account availability in ${Math.max(1, Math.ceil(delayMs / 60_000))} min (reset at ${time} UTC) · Esc to cancel`);
19
20
  await new Promise((resolve, reject) => {
20
21
  const abort = () => {
21
22
  clear(timer);
@@ -36,9 +37,10 @@ async function waitForReset(delayMs, resetAt, signal, options) {
36
37
  }
37
38
  /** Own one bounded wait inside a Pi stream, rather than asking Pi's text-based retry loop. */
38
39
  export async function withPiQuotaWait(input) {
39
- const response = await input.run();
40
- const hold = holds.get(response);
41
- const refusal = quotaRefusalDetails(response);
40
+ const original = await input.run();
41
+ const hold = holds.get(original);
42
+ const refusal = quotaRefusalDetails(original);
43
+ const response = hostRetryResponse(original, input.wait?.now?.() ?? Date.now());
42
44
  const delay = Number(response.headers.get('retry-after')) * 1000;
43
45
  if ((!hold && !refusal) ||
44
46
  !response.headers.has('retry-after') ||
@@ -54,13 +56,13 @@ export async function withPiQuotaWait(input) {
54
56
  resetAt: undefined,
55
57
  retryAfterSeconds: undefined,
56
58
  });
57
- await waitForReset(delay, hold?.resetAt ?? refusal?.timing.resetAt, input.signal, options);
59
+ await waitForReset(clampHostRetryMs(delay), hold?.resetAt ?? refusal?.timing.resetAt, input.signal, options);
58
60
  input.signal?.throwIfAborted();
59
61
  let next;
60
62
  try {
61
63
  next = await input.resume(hold);
62
64
  if (next.ok || next.status === 401)
63
- return next;
65
+ return hostRetryResponse(next, options.now?.() ?? Date.now());
64
66
  }
65
67
  catch (error) {
66
68
  if (input.signal?.aborted)
@@ -73,6 +75,7 @@ export async function withPiQuotaWait(input) {
73
75
  refusal?.reason ??
74
76
  'The selected OAuth account cannot serve this request. Open /claude to review account availability.', {
75
77
  resetAt: latest?.timing.resetAt ?? refusal?.timing.resetAt ?? hold?.resetAt,
78
+ limitName: latest?.timing.limitName ?? refusal?.timing.limitName,
76
79
  retryAfterSeconds: undefined,
77
- }, options.now?.() ?? Date.now());
80
+ }, options.now?.() ?? Date.now(), { retry: 'manual' });
78
81
  }
package/dist/stream.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type ApiKeyAccount, type CacheKeepManager, createAnthropicStreamCompletion, type MidConversationEffortTransition, type NativeAccountView, type QuotaManagerOptions } from '@cortexkit/anthropic-auth-core';
1
+ import { type ApiKeyAccount, type CacheKeepManager, createAnthropicStreamCompletion, createRoutingRelay, type MidConversationEffortTransition, type NativeAccountView, type QuotaManagerOptions, type RoutingChoice } from '@cortexkit/anthropic-auth-core';
2
2
  import { type Api, type AssistantMessageEventStream, type Context, type Model, type SimpleStreamOptions } from '@earendil-works/pi-ai';
3
3
  import { type PiNativeAttempt, type PiNativeRuntime } from './native.ts';
4
4
  import { type PiPrimeSendOptions } from './prime.ts';
@@ -40,6 +40,8 @@ declare function sendAnthropicRequest(options: {
40
40
  apiAccount?: NativeAccountView;
41
41
  storagePath: string;
42
42
  oauthAccountId?: string;
43
+ routingChoice?: RoutingChoice;
44
+ routingRelay?: ReturnType<typeof createRoutingRelay>;
43
45
  expectedAccountIdentity?: string;
44
46
  route?: string;
45
47
  effortTransitions?: readonly MidConversationEffortTransition[];
package/dist/stream.js CHANGED
@@ -1,4 +1,4 @@
1
- import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, buildPrimeRequestBody, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, CLAUDE_CODE_ACCEPT_ENCODING, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, copyStreamResponseTiming, createAnthropicStreamCompletion, createDumpResponseObserver, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createSseFramer, createStickyNoRouteResponse, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, dumpResponseArtifact, effectiveRelayTransport, FAST_MODE_BETA, getCache1hPersistentMode, getCacheKeepRegistryDirectories, getClaudeCodeIdentityForVerifiedAccount, getFallbackReauthLabels, getMaxSameAccountWait, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, isCache1hPersistentlyEnabled, isCacheKeepHybridActive, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isNativeTransientAccountError, isOAuthAccount, isPermanentRefreshError, isValidApiBaseURL, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, localMessageThreadCredential, logger, MessageThreadTracker, mergeAnthropicBetas, NativeAccountRefusal, nativeAccountCanServe, orderClaudeCodeBody, PROMPT_CACHE_DEFAULT_TTL_MS, parseSseFrame, prepareMessageThreadRequest, QuotaManager, quotaBackoffActive, quotaExhaustionFromHeaders, quotaRefusalTiming, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, readSessionCachePolicy, reportRoutingResponse, reportSessionCacheTouch, requestCacheLifetimeMs, resolveNativePoolPaths, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, stickyQuotaSnapshotIsFresh, stickyRetryAfterWithJitter, stickyRouteFamilyForModel, withAnthropicBilling, } from '@cortexkit/anthropic-auth-core';
1
+ import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, buildPrimeRequestBody, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, CLAUDE_CODE_ACCEPT_ENCODING, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, copyStreamResponseTiming, createAnthropicStreamCompletion, createDumpResponseObserver, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createRoutingRelay, createSseFramer, createStickyNoRouteResponse, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, dumpResponseArtifact, effectiveRelayTransport, FAST_MODE_BETA, getCache1hPersistentMode, getCacheKeepRegistryDirectories, getClaudeCodeIdentityForVerifiedAccount, getFallbackReauthLabels, getMaxSameAccountWait, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, hostRetryHeaders, hostRetryResponse, isCache1hPersistentlyEnabled, isCacheKeepHybridActive, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isNativeTransientAccountError, isOAuthAccount, isPermanentRefreshError, isValidApiBaseURL, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, localMessageThreadCredential, logger, MessageThreadTracker, mergeAnthropicBetas, NativeAccountRefusal, nativeAccountCanServe, orderClaudeCodeBody, PROMPT_CACHE_DEFAULT_TTL_MS, parseSseFrame, prepareMessageThreadRequest, QuotaManager, quotaBackoffActive, quotaExhaustionFromHeaders, quotaRefusalTiming, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, readSessionCachePolicy, reportRoutingResponse, reportSessionCacheTouch, requestCacheLifetimeMs, resolveNativePoolPaths, routingCandidates, routingChoiceMatches, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, stickyQuotaSnapshotIsFresh, stickyRetryAfterWithJitter, stickyRouteCandidateWeight, stickyRouteFamilyForModel, withAnthropicBilling, } from '@cortexkit/anthropic-auth-core';
2
2
  import { calculateCost, createAssistantMessageEventStream, } from '@earendil-works/pi-ai';
3
3
  import { PiCacheKeep } from './cachekeep.js';
4
4
  import { buildAnthropicRequest, fromClaudeCodeToolName } from './convert.js';
@@ -528,7 +528,7 @@ async function sendAnthropicRequest(options, deps = {}) {
528
528
  throw new Error('Pi vault route identity is unasserted');
529
529
  // Validation can learn the UUID of an account that has no verified identity.
530
530
  // This lookup returns only that UUID; the model send authorizes the credential again.
531
- verifiedUuid = (await native.authorize(routeId, options.streamOptions?.signal, options.model.id)).accountIdentity;
531
+ verifiedUuid = (await native.authorize(routeId, options.streamOptions?.signal, options.model.id, 'serve', options.routingChoice)).accountIdentity;
532
532
  }
533
533
  let nextAttempt;
534
534
  const identity = verifiedUuid
@@ -574,6 +574,9 @@ async function sendAnthropicRequest(options, deps = {}) {
574
574
  const reportRoutingHeaders = (attempt, responseHeaders, status) => {
575
575
  if (options.prime || !relayAffinity)
576
576
  return;
577
+ if (options.routingRelay &&
578
+ !options.routingRelay.shouldReport(relayAffinity))
579
+ return;
577
580
  const payer = piBillingPayer(attempt);
578
581
  reportRoutingResponse(relayAffinity, { accountIdentity: payer.accountId, credentialId: payer.credentialId }, responseHeaders, status, typeof body.model === 'string' ? body.model : options.model.id, status < 400, async () => selected?.accountIdentity === payer.accountId
579
582
  ? selected.quota
@@ -688,7 +691,7 @@ async function sendAnthropicRequest(options, deps = {}) {
688
691
  };
689
692
  const takeAttempt = async () => {
690
693
  const attempt = nextAttempt ??
691
- (await native.authorize(routeId, init.signal ?? undefined, options.model.id));
694
+ (await native.authorize(routeId, init.signal ?? undefined, options.model.id, 'serve', options.routingChoice));
692
695
  nextAttempt = undefined;
693
696
  if (attempt.accountIdentity !== verifiedUuid)
694
697
  throw new Error('Pi native OAuth route identity changed');
@@ -794,7 +797,7 @@ async function sendAnthropicRequest(options, deps = {}) {
794
797
  await report(attempt, response.status, 'direct');
795
798
  const rotated = !retried401 && !init.signal?.aborted
796
799
  ? await native
797
- .retry(routeId, attempt, init.signal ?? undefined, options.model.id)
800
+ .retry(routeId, attempt, init.signal ?? undefined, options.model.id, options.routingChoice)
798
801
  .catch(() => undefined)
799
802
  : undefined;
800
803
  if (rotated) {
@@ -936,7 +939,7 @@ async function sendAnthropicRequest(options, deps = {}) {
936
939
  !retried401 &&
937
940
  !init.signal?.aborted) {
938
941
  const rotated = await native
939
- .retry(routeId, relay401Attempt, init.signal ?? undefined, options.model.id)
942
+ .retry(routeId, relay401Attempt, init.signal ?? undefined, options.model.id, options.routingChoice)
940
943
  .catch(() => undefined);
941
944
  if (rotated) {
942
945
  retried401 = true;
@@ -1123,6 +1126,11 @@ export async function firstStreamingError(response) {
1123
1126
  return { response: inspected, preflight: inspected };
1124
1127
  }
1125
1128
  async function executeWithFallback(options) {
1129
+ const routingState = options.routingState ?? {
1130
+ relay: createRoutingRelay(),
1131
+ advice: undefined,
1132
+ };
1133
+ options = { ...options, routingRelay: routingState.relay };
1126
1134
  const native = getPiNativeRuntime(options.storagePath);
1127
1135
  let snapshot = await native.requestView(options.streamOptions?.signal);
1128
1136
  let storage = snapshot.policyStorage;
@@ -1362,11 +1370,28 @@ async function executeWithFallback(options) {
1362
1370
  return null;
1363
1371
  }
1364
1372
  const routingMode = getRoutingMode(storage);
1365
- if (routingMode === 'sticky-balanced' && options.streamOptions?.sessionId) {
1373
+ const routingRelay = routingState.relay;
1374
+ const routingSessionId = options.streamOptions?.sessionId;
1375
+ if (routingSessionId && !routingState.advice) {
1376
+ routingState.advice = routingRelay.accountFor(routingSessionId, options.model.id, routingCandidates(snapshot.accounts));
1377
+ }
1378
+ const advice = await routingState.advice;
1379
+ let advisedAccountId = advice
1380
+ ? snapshot.accounts.find((account) => routingChoiceMatches(advice, account) && nativeReady(account.id))?.id
1381
+ : undefined;
1382
+ if (advice && !advisedAccountId)
1383
+ routingRelay.override(routingSessionId ?? '', 'account unavailable');
1384
+ if ((routingMode === 'sticky-balanced' || advisedAccountId) &&
1385
+ options.streamOptions?.sessionId) {
1366
1386
  const sessionId = options.streamOptions.sessionId;
1367
1387
  const router = await getPiStickyRouter(options.storagePath);
1368
1388
  const initialInputBytes = Math.max(1, Buffer.byteLength(JSON.stringify(options.context)));
1369
1389
  let routes = await buildStickyRoutes(options.model.id);
1390
+ if (advisedAccountId &&
1391
+ !routes.allRoutes.some((route) => route.id === advisedAccountId)) {
1392
+ routingRelay.override(sessionId, 'account unavailable');
1393
+ advisedAccountId = undefined;
1394
+ }
1370
1395
  const mainPermanentlyUnavailable = !primaryAvailable();
1371
1396
  const incompleteQuotaPool = (routes.allRoutes.length === 0 && !mainPermanentlyUnavailable) ||
1372
1397
  routes.allRoutes.some((candidate) => !quotaObservationIsFresh(candidate.quota, options.model.id));
@@ -1377,8 +1402,21 @@ async function executeWithFallback(options) {
1377
1402
  affinityModelId: options.model.id,
1378
1403
  // Keep an existing route after a temporary quota poll failure, but do not
1379
1404
  // choose a new balanced route until the account pool has current quota data.
1380
- candidates: incompleteQuotaPool ? [] : routes.candidates,
1381
- retainAccountIds: routes.retainAccountIds,
1405
+ candidates: advisedAccountId
1406
+ ? routes.allRoutes
1407
+ .filter((route) => route.id === advisedAccountId)
1408
+ .map((route) => ({
1409
+ accountId: route.id,
1410
+ order: route.order,
1411
+ quota: route.quota ?? { kind: 'unknown' },
1412
+ }))
1413
+ : incompleteQuotaPool
1414
+ ? []
1415
+ : routes.candidates,
1416
+ retainAccountIds: advisedAccountId
1417
+ ? new Set([advisedAccountId])
1418
+ : routes.retainAccountIds,
1419
+ ...(advisedAccountId && { routingAccountId: advisedAccountId }),
1382
1420
  accountIdentities: vaultAccountIdentities(),
1383
1421
  storage,
1384
1422
  inputBytes: initialInputBytes,
@@ -1393,7 +1431,7 @@ async function executeWithFallback(options) {
1393
1431
  });
1394
1432
  throw error;
1395
1433
  }
1396
- if (!resolution) {
1434
+ const noRouteResponse = async () => {
1397
1435
  if (snapshot.mode === 'claustrum')
1398
1436
  return createNativeVaultNoRouteResponse({
1399
1437
  snapshot: await native.view(),
@@ -1415,34 +1453,44 @@ async function executeWithFallback(options) {
1415
1453
  sessionId,
1416
1454
  modelId: options.model.id,
1417
1455
  });
1418
- }
1456
+ };
1457
+ if (!resolution)
1458
+ return noRouteResponse();
1419
1459
  let route = routes.allRoutes.find((candidate) => candidate.id === resolution?.accountId);
1420
1460
  if (resolution && route) {
1421
1461
  const sendRoute = (selected) => sendAnthropicRequest({
1422
1462
  ...options,
1423
1463
  oauthAccountId: selected.id,
1464
+ routingChoice: selected.id === advisedAccountId
1465
+ ? (advice ?? undefined)
1466
+ : undefined,
1424
1467
  route: `sticky:${selected.id}`,
1425
1468
  });
1426
- const completeRoute = async (_selected, response, _markUsed = true) => response;
1469
+ const completeRoute = async (_selected, response, _markUsed = true) => hostRetryResponse(response);
1427
1470
  const heldAccountId = route.id;
1428
1471
  const heldAccountIdentity = accountView(route.id)?.accountIdentity;
1429
- const holdResponse = (retryAfterSeconds, upstream) => {
1472
+ const holdResponse = (retryAfterSeconds, upstream, routingHold = false) => {
1430
1473
  const headers = new Headers(upstream);
1431
1474
  headers.set('content-type', 'application/json');
1432
- headers.set('retry-after', String(stickyRetryAfterWithJitter(sessionId, retryAfterSeconds)));
1475
+ headers.set('retry-after', String(routingHold
1476
+ ? retryAfterSeconds
1477
+ : stickyRetryAfterWithJitter(sessionId, retryAfterSeconds)));
1433
1478
  return markPiAccountHold(new Response(JSON.stringify({
1434
1479
  type: 'error',
1435
1480
  error: {
1436
1481
  type: 'rate_limit_error',
1437
1482
  message: 'Sticky OAuth account quota resets shortly; retaining session affinity.',
1438
1483
  },
1439
- }), { status: 429, headers }), {
1484
+ }), { status: 429, headers: hostRetryHeaders(headers) }), {
1440
1485
  accountId: heldAccountId,
1441
1486
  accountIdentity: heldAccountIdentity,
1442
1487
  resetAt: Date.now() + retryAfterSeconds * 1000,
1443
1488
  });
1444
1489
  };
1445
- const proactiveQuotaDecision = stickyQuotaSnapshotIsFresh(route.quota, storage, Date.now(), options.model.id)
1490
+ if (advisedAccountId && advice?.hold)
1491
+ return holdResponse(Math.ceil(advice.hold.retry_after_ms / 1000), undefined, true);
1492
+ const proactiveQuotaDecision = !advisedAccountId &&
1493
+ stickyQuotaSnapshotIsFresh(route.quota, storage, Date.now(), options.model.id)
1446
1494
  ? decideStickyQuotaFailure({
1447
1495
  quota: route.quota,
1448
1496
  modelId: options.model.id,
@@ -1525,7 +1573,8 @@ async function executeWithFallback(options) {
1525
1573
  return completeRoute(route, await sendRoute(route));
1526
1574
  }
1527
1575
  }
1528
- if (primaryResponseAllowsApiFallback(preflight) &&
1576
+ if (!(advice && !advisedAccountId) &&
1577
+ primaryResponseAllowsApiFallback(preflight) &&
1529
1578
  (await primaryQuotaRefreshConfirmsExhausted())) {
1530
1579
  if (preflight instanceof Response) {
1531
1580
  await preflight.body?.cancel().catch(() => { });
@@ -1541,8 +1590,23 @@ async function executeWithFallback(options) {
1541
1590
  clearPiStickyQuotaRetries(options.storagePath, sessionId);
1542
1591
  return apiFallback;
1543
1592
  }
1593
+ routes = await buildStickyRoutes(options.model.id);
1544
1594
  }
1545
1595
  }
1596
+ if (primaryResponseAllowsApiFallback(preflight) &&
1597
+ routes.candidates.every((candidate) => stickyRouteCandidateWeight({
1598
+ candidate,
1599
+ family: stickyRouteFamilyForModel(options.model.id),
1600
+ modelId: options.model.id,
1601
+ storage,
1602
+ }) === 0) &&
1603
+ routes.allRoutes.length > 0 &&
1604
+ routes.allRoutes.every((candidate) => quotaObservationIsFresh(candidate.quota, options.model.id))) {
1605
+ void response.body?.cancel().catch(() => { });
1606
+ if (preflight instanceof Response)
1607
+ void preflight.body?.cancel().catch(() => { });
1608
+ return noRouteResponse();
1609
+ }
1546
1610
  return completeRoute(route, preflight instanceof Response ? preflight : response);
1547
1611
  }
1548
1612
  }
@@ -1670,6 +1734,8 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1670
1734
  toolNames = names;
1671
1735
  },
1672
1736
  };
1737
+ const routingState = { relay: createRoutingRelay() };
1738
+ Object.assign(request, { routingState });
1673
1739
  const response = await runWithRequestSignal(options?.signal, () => withPiQuotaWait({
1674
1740
  signal: options?.signal,
1675
1741
  wait,
@@ -1693,6 +1759,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1693
1759
  try {
1694
1760
  const quota = await runtime.fetchQuota(account.id, fetchPiOAuth, options?.signal, undefined, 'admission');
1695
1761
  if (hold &&
1762
+ !routingState.relay.admitted(options?.sessionId ?? '', account) &&
1696
1763
  decideStickyQuotaFailure({ quota, modelId: model.id })
1697
1764
  .action === 'migrate')
1698
1765
  heldStillBlocked = true;
@@ -1711,6 +1778,8 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1711
1778
  ...request,
1712
1779
  oauthAccountId: hold.accountId,
1713
1780
  expectedAccountIdentity: hold.accountIdentity,
1781
+ routingRelay: routingState.relay,
1782
+ routingChoice: (await routingState.advice) ?? undefined,
1714
1783
  }));
1715
1784
  if (inspected.preflight instanceof Response)
1716
1785
  return inspected.preflight;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.10.1",
3
+ "version": "2.11.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -36,7 +36,7 @@
36
36
  "prepublishOnly": "bun run build"
37
37
  },
38
38
  "dependencies": {
39
- "@cortexkit/anthropic-auth-core": "2.10.1"
39
+ "@cortexkit/anthropic-auth-core": "2.11.1"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",