@cortexkit/pi-anthropic-auth 2.10.1 → 2.11.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.
- package/dist/native.d.ts +3 -3
- package/dist/native.js +13 -9
- package/dist/stream.d.ts +3 -1
- package/dist/stream.js +64 -12
- package/package.json +2 -2
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
|
-
|
|
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)
|
|
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)
|
|
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 ||
|
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, 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, 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
|
-
|
|
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:
|
|
1381
|
-
|
|
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,
|
|
@@ -1421,15 +1459,20 @@ async function executeWithFallback(options) {
|
|
|
1421
1459
|
const sendRoute = (selected) => sendAnthropicRequest({
|
|
1422
1460
|
...options,
|
|
1423
1461
|
oauthAccountId: selected.id,
|
|
1462
|
+
routingChoice: selected.id === advisedAccountId
|
|
1463
|
+
? (advice ?? undefined)
|
|
1464
|
+
: undefined,
|
|
1424
1465
|
route: `sticky:${selected.id}`,
|
|
1425
1466
|
});
|
|
1426
1467
|
const completeRoute = async (_selected, response, _markUsed = true) => response;
|
|
1427
1468
|
const heldAccountId = route.id;
|
|
1428
1469
|
const heldAccountIdentity = accountView(route.id)?.accountIdentity;
|
|
1429
|
-
const holdResponse = (retryAfterSeconds, upstream) => {
|
|
1470
|
+
const holdResponse = (retryAfterSeconds, upstream, routingHold = false) => {
|
|
1430
1471
|
const headers = new Headers(upstream);
|
|
1431
1472
|
headers.set('content-type', 'application/json');
|
|
1432
|
-
headers.set('retry-after', String(
|
|
1473
|
+
headers.set('retry-after', String(routingHold
|
|
1474
|
+
? retryAfterSeconds
|
|
1475
|
+
: stickyRetryAfterWithJitter(sessionId, retryAfterSeconds)));
|
|
1433
1476
|
return markPiAccountHold(new Response(JSON.stringify({
|
|
1434
1477
|
type: 'error',
|
|
1435
1478
|
error: {
|
|
@@ -1442,7 +1485,10 @@ async function executeWithFallback(options) {
|
|
|
1442
1485
|
resetAt: Date.now() + retryAfterSeconds * 1000,
|
|
1443
1486
|
});
|
|
1444
1487
|
};
|
|
1445
|
-
|
|
1488
|
+
if (advisedAccountId && advice?.hold)
|
|
1489
|
+
return holdResponse(Math.ceil(advice.hold.retry_after_ms / 1000), undefined, true);
|
|
1490
|
+
const proactiveQuotaDecision = !advisedAccountId &&
|
|
1491
|
+
stickyQuotaSnapshotIsFresh(route.quota, storage, Date.now(), options.model.id)
|
|
1446
1492
|
? decideStickyQuotaFailure({
|
|
1447
1493
|
quota: route.quota,
|
|
1448
1494
|
modelId: options.model.id,
|
|
@@ -1525,7 +1571,8 @@ async function executeWithFallback(options) {
|
|
|
1525
1571
|
return completeRoute(route, await sendRoute(route));
|
|
1526
1572
|
}
|
|
1527
1573
|
}
|
|
1528
|
-
if (
|
|
1574
|
+
if (!(advice && !advisedAccountId) &&
|
|
1575
|
+
primaryResponseAllowsApiFallback(preflight) &&
|
|
1529
1576
|
(await primaryQuotaRefreshConfirmsExhausted())) {
|
|
1530
1577
|
if (preflight instanceof Response) {
|
|
1531
1578
|
await preflight.body?.cancel().catch(() => { });
|
|
@@ -1670,6 +1717,8 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1670
1717
|
toolNames = names;
|
|
1671
1718
|
},
|
|
1672
1719
|
};
|
|
1720
|
+
const routingState = { relay: createRoutingRelay() };
|
|
1721
|
+
Object.assign(request, { routingState });
|
|
1673
1722
|
const response = await runWithRequestSignal(options?.signal, () => withPiQuotaWait({
|
|
1674
1723
|
signal: options?.signal,
|
|
1675
1724
|
wait,
|
|
@@ -1693,6 +1742,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1693
1742
|
try {
|
|
1694
1743
|
const quota = await runtime.fetchQuota(account.id, fetchPiOAuth, options?.signal, undefined, 'admission');
|
|
1695
1744
|
if (hold &&
|
|
1745
|
+
!routingState.relay.admitted(options?.sessionId ?? '', account) &&
|
|
1696
1746
|
decideStickyQuotaFailure({ quota, modelId: model.id })
|
|
1697
1747
|
.action === 'migrate')
|
|
1698
1748
|
heldStillBlocked = true;
|
|
@@ -1711,6 +1761,8 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1711
1761
|
...request,
|
|
1712
1762
|
oauthAccountId: hold.accountId,
|
|
1713
1763
|
expectedAccountIdentity: hold.accountIdentity,
|
|
1764
|
+
routingRelay: routingState.relay,
|
|
1765
|
+
routingChoice: (await routingState.advice) ?? undefined,
|
|
1714
1766
|
}));
|
|
1715
1767
|
if (inspected.preflight instanceof Response)
|
|
1716
1768
|
return inspected.preflight;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/pi-anthropic-auth",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.11.0",
|
|
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.
|
|
39
|
+
"@cortexkit/anthropic-auth-core": "2.11.0"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"@earendil-works/pi-ai": ">=0.86.1 <2",
|