@cortexkit/pi-anthropic-auth 2.10.0 → 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 +4 -1
- package/dist/stream.js +147 -57
- package/dist/transport.d.ts +1 -0
- package/dist/transport.js +90 -1
- 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';
|
|
@@ -22,6 +22,7 @@ type AnthropicEvent = {
|
|
|
22
22
|
delta?: Record<string, unknown>;
|
|
23
23
|
error?: Record<string, unknown>;
|
|
24
24
|
message?: {
|
|
25
|
+
id?: string;
|
|
25
26
|
usage?: Record<string, number>;
|
|
26
27
|
};
|
|
27
28
|
usage?: Record<string, number>;
|
|
@@ -39,6 +40,8 @@ declare function sendAnthropicRequest(options: {
|
|
|
39
40
|
apiAccount?: NativeAccountView;
|
|
40
41
|
storagePath: string;
|
|
41
42
|
oauthAccountId?: string;
|
|
43
|
+
routingChoice?: RoutingChoice;
|
|
44
|
+
routingRelay?: ReturnType<typeof createRoutingRelay>;
|
|
42
45
|
expectedAccountIdentity?: string;
|
|
43
46
|
route?: string;
|
|
44
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_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, 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';
|
|
@@ -6,7 +6,7 @@ import { getPiNativeRuntime, peekPiNativeSnapshot, piAttemptAccessToken, } from
|
|
|
6
6
|
import { getPiAccountStoragePath } from './paths.js';
|
|
7
7
|
import { registerPiPrimeSender } from './prime.js';
|
|
8
8
|
import { markPiAccountHold, withPiQuotaWait, } from './quota-wait.js';
|
|
9
|
-
import { buildPiOAuthMessagesUrl, fetchPiOAuth, requirePiOAuthOrigin, } from './transport.js';
|
|
9
|
+
import { buildPiOAuthMessagesUrl, fetchPiOAuth, fetchPiStreamResponse, requirePiOAuthOrigin, } from './transport.js';
|
|
10
10
|
const messageThreads = new MessageThreadTracker();
|
|
11
11
|
const dumpResponseObservers = new WeakMap();
|
|
12
12
|
// Each session owns its lease; storage identifies which host may end it.
|
|
@@ -194,6 +194,8 @@ function applyPiOAuthRequestHeaders(headers, accessToken, options) {
|
|
|
194
194
|
extraBetas: options.leadingBetas,
|
|
195
195
|
requestClass: options.requestClass,
|
|
196
196
|
});
|
|
197
|
+
// Pi runs on undici, whose default encoding order differs from Claude Code's.
|
|
198
|
+
headers.set('accept-encoding', CLAUDE_CODE_ACCEPT_ENCODING);
|
|
197
199
|
if (body.speed === 'fast')
|
|
198
200
|
headers.set('anthropic-beta', mergeAnthropicBetas(headers.get('anthropic-beta'), [FAST_MODE_BETA]));
|
|
199
201
|
return headers;
|
|
@@ -504,9 +506,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
504
506
|
assertHostAuthorityStable();
|
|
505
507
|
const fetchImpl = deps.fetch ?? globalThis.fetch;
|
|
506
508
|
const fetchResponse = async (input, init) => {
|
|
507
|
-
|
|
508
|
-
const response = await fetchImpl(input, init);
|
|
509
|
-
return copyStreamResponseTiming(response, response, sentAt);
|
|
509
|
+
return fetchPiStreamResponse(input, init, fetchImpl);
|
|
510
510
|
};
|
|
511
511
|
const keep = deps.cacheKeep ?? cacheKeepManager;
|
|
512
512
|
const native = deps.native ?? getPiNativeRuntime(options.storagePath);
|
|
@@ -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
|
|
@@ -571,6 +571,17 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
571
571
|
...(options.prime && { requestClass: 'auxiliary' }),
|
|
572
572
|
});
|
|
573
573
|
const relayAffinity = options.streamOptions?.sessionId ?? null;
|
|
574
|
+
const reportRoutingHeaders = (attempt, responseHeaders, status) => {
|
|
575
|
+
if (options.prime || !relayAffinity)
|
|
576
|
+
return;
|
|
577
|
+
if (options.routingRelay &&
|
|
578
|
+
!options.routingRelay.shouldReport(relayAffinity))
|
|
579
|
+
return;
|
|
580
|
+
const payer = piBillingPayer(attempt);
|
|
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
|
|
582
|
+
? selected.quota
|
|
583
|
+
: undefined);
|
|
584
|
+
};
|
|
574
585
|
const billingInput = (attempt, apiSubject) => {
|
|
575
586
|
// The session runner matches billing reports to session transcripts, and
|
|
576
587
|
// Prime is account-wide with no session, so it sends no billing report.
|
|
@@ -582,13 +593,24 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
582
593
|
if (!credentialId)
|
|
583
594
|
return undefined;
|
|
584
595
|
const ttlMs = requestCacheLifetimeMs(wireBodyText);
|
|
596
|
+
const sessionId = relayAffinity;
|
|
585
597
|
return {
|
|
586
598
|
...(attempt ? piBillingPayer(attempt) : { credentialId }),
|
|
587
|
-
sessionId
|
|
599
|
+
sessionId,
|
|
588
600
|
model: typeof body.model === 'string' ? body.model : options.model.id,
|
|
589
601
|
requestKind: options.requestOrigin === 'direct' ? 'generate' : 'primary',
|
|
590
602
|
chargeBasis: options.apiAccount ? 'metered_api' : 'subscription_included',
|
|
591
603
|
...(ttlMs > 0 ? { cache: { ttlMs } } : {}),
|
|
604
|
+
// Read when the response finishes. API-key routes are never warmed. An
|
|
605
|
+
// OAuth answer waits for nothing: until this attempt's CacheKeep
|
|
606
|
+
// tracking has settled, the state is left out.
|
|
607
|
+
cacheWarming: () => {
|
|
608
|
+
if (options.apiAccount)
|
|
609
|
+
return { on: false };
|
|
610
|
+
if (!attempt || cacheTracking.get(attempt) !== 'settled')
|
|
611
|
+
return undefined;
|
|
612
|
+
return keep.warming(sessionId);
|
|
613
|
+
},
|
|
592
614
|
};
|
|
593
615
|
};
|
|
594
616
|
let input = options.apiAccount
|
|
@@ -602,6 +624,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
602
624
|
...(!options.apiAccount && { redirect: 'error' }),
|
|
603
625
|
};
|
|
604
626
|
const cacheAccepted = new Set();
|
|
627
|
+
const cacheTracking = new Map();
|
|
605
628
|
const trackAcceptedRequest = (attempt, sentBody = wireBodyText) => {
|
|
606
629
|
if (options.prime || options.apiAccount || init.signal?.aborted)
|
|
607
630
|
return;
|
|
@@ -636,6 +659,8 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
636
659
|
const tracked = deps.cacheKeep
|
|
637
660
|
? Promise.resolve(keep.track(target))
|
|
638
661
|
: piCacheKeep.trackAccepted(target, snapshot);
|
|
662
|
+
cacheTracking.set(attempt, 'pending');
|
|
663
|
+
void tracked.then(() => cacheTracking.set(attempt, 'settled'), () => { });
|
|
639
664
|
let latestUsage = {};
|
|
640
665
|
options.onCacheUsageRecorder?.((usage) => {
|
|
641
666
|
if (!usage || init.signal?.aborted || !relayAffinity)
|
|
@@ -666,7 +691,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
666
691
|
};
|
|
667
692
|
const takeAttempt = async () => {
|
|
668
693
|
const attempt = nextAttempt ??
|
|
669
|
-
(await native.authorize(routeId, init.signal ?? undefined, options.model.id));
|
|
694
|
+
(await native.authorize(routeId, init.signal ?? undefined, options.model.id, 'serve', options.routingChoice));
|
|
670
695
|
nextAttempt = undefined;
|
|
671
696
|
if (attempt.accountIdentity !== verifiedUuid)
|
|
672
697
|
throw new Error('Pi native OAuth route identity changed');
|
|
@@ -755,9 +780,14 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
755
780
|
},
|
|
756
781
|
}));
|
|
757
782
|
};
|
|
758
|
-
const physicalFetch = (send) => {
|
|
783
|
+
const physicalFetch = async (send) => {
|
|
759
784
|
const billing = billingInput(attempt, apiSubject);
|
|
760
|
-
|
|
785
|
+
const response = await (billing
|
|
786
|
+
? withAnthropicBilling(billing, send)
|
|
787
|
+
: send());
|
|
788
|
+
if (attempt)
|
|
789
|
+
reportRoutingHeaders(attempt, response.headers, response.status);
|
|
790
|
+
return response;
|
|
761
791
|
};
|
|
762
792
|
let response;
|
|
763
793
|
try {
|
|
@@ -767,7 +797,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
767
797
|
await report(attempt, response.status, 'direct');
|
|
768
798
|
const rotated = !retried401 && !init.signal?.aborted
|
|
769
799
|
? await native
|
|
770
|
-
.retry(routeId, attempt, init.signal ?? undefined, options.model.id)
|
|
800
|
+
.retry(routeId, attempt, init.signal ?? undefined, options.model.id, options.routingChoice)
|
|
771
801
|
.catch(() => undefined)
|
|
772
802
|
: undefined;
|
|
773
803
|
if (rotated) {
|
|
@@ -854,44 +884,54 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
854
884
|
// The relay scrubs each physical relay attempt's responses and errors with
|
|
855
885
|
// that attempt's own credentials and the relay token; a direct fallback is
|
|
856
886
|
// scrubbed by directFetch.
|
|
857
|
-
const sendRelayAttempt = async () =>
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
887
|
+
const sendRelayAttempt = async () => {
|
|
888
|
+
let upstream;
|
|
889
|
+
return sendViaRelay({
|
|
890
|
+
config: relayConfig,
|
|
891
|
+
input,
|
|
892
|
+
init,
|
|
893
|
+
headers,
|
|
894
|
+
body: wireBodyText,
|
|
895
|
+
fallback: directFetch,
|
|
896
|
+
affinity: relayAffinity,
|
|
897
|
+
// Some relay streams start before the provider answers. Report the
|
|
898
|
+
// provider's actual status and headers, not that early placeholder.
|
|
899
|
+
onResponseHeaders: (responseHeaders) => {
|
|
900
|
+
if (upstream)
|
|
901
|
+
reportRoutingHeaders(upstream.attempt, responseHeaders, upstream.status);
|
|
902
|
+
},
|
|
903
|
+
onDumpCreated: (handle) => {
|
|
904
|
+
dumpHandle = handle;
|
|
905
|
+
},
|
|
906
|
+
authorizeAttempt: async () => {
|
|
907
|
+
const attempt = await takeAttempt();
|
|
908
|
+
await options.prime?.beforeSend();
|
|
909
|
+
init.signal?.throwIfAborted();
|
|
910
|
+
assertHostAuthorityStable();
|
|
911
|
+
relayAttempt = attempt;
|
|
912
|
+
lastTransport = 'relay';
|
|
913
|
+
const authorizedHeaders = new Headers(headers);
|
|
914
|
+
const sentBody = wireBodyText;
|
|
915
|
+
const access = piAttemptAccessToken(attempt);
|
|
916
|
+
authorizedHeaders.set('authorization', `Bearer ${access}`);
|
|
917
|
+
return {
|
|
918
|
+
headers: authorizedHeaders,
|
|
919
|
+
billing: billingInput(attempt),
|
|
920
|
+
errorSecrets: [access],
|
|
921
|
+
onUpstreamStatus: (status) => {
|
|
922
|
+
upstream = { attempt, status };
|
|
923
|
+
if (status >= 200 && status < 300)
|
|
924
|
+
trackAcceptedRequest(attempt, sentBody);
|
|
925
|
+
if (status === 401) {
|
|
926
|
+
relay401Attempt = attempt;
|
|
927
|
+
// The relay can report an upstream 401 after returning the streaming response.
|
|
928
|
+
relayReports.push(report(attempt, status, 'relay_status_field'));
|
|
929
|
+
}
|
|
930
|
+
},
|
|
931
|
+
};
|
|
932
|
+
},
|
|
933
|
+
});
|
|
934
|
+
};
|
|
895
935
|
let response = await sendRelayAttempt();
|
|
896
936
|
await Promise.all(relayReports);
|
|
897
937
|
if (relay401Attempt &&
|
|
@@ -899,7 +939,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
899
939
|
!retried401 &&
|
|
900
940
|
!init.signal?.aborted) {
|
|
901
941
|
const rotated = await native
|
|
902
|
-
.retry(routeId, relay401Attempt, init.signal ?? undefined, options.model.id)
|
|
942
|
+
.retry(routeId, relay401Attempt, init.signal ?? undefined, options.model.id, options.routingChoice)
|
|
903
943
|
.catch(() => undefined);
|
|
904
944
|
if (rotated) {
|
|
905
945
|
retried401 = true;
|
|
@@ -1086,6 +1126,11 @@ export async function firstStreamingError(response) {
|
|
|
1086
1126
|
return { response: inspected, preflight: inspected };
|
|
1087
1127
|
}
|
|
1088
1128
|
async function executeWithFallback(options) {
|
|
1129
|
+
const routingState = options.routingState ?? {
|
|
1130
|
+
relay: createRoutingRelay(),
|
|
1131
|
+
advice: undefined,
|
|
1132
|
+
};
|
|
1133
|
+
options = { ...options, routingRelay: routingState.relay };
|
|
1089
1134
|
const native = getPiNativeRuntime(options.storagePath);
|
|
1090
1135
|
let snapshot = await native.requestView(options.streamOptions?.signal);
|
|
1091
1136
|
let storage = snapshot.policyStorage;
|
|
@@ -1325,11 +1370,28 @@ async function executeWithFallback(options) {
|
|
|
1325
1370
|
return null;
|
|
1326
1371
|
}
|
|
1327
1372
|
const routingMode = getRoutingMode(storage);
|
|
1328
|
-
|
|
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) {
|
|
1329
1386
|
const sessionId = options.streamOptions.sessionId;
|
|
1330
1387
|
const router = await getPiStickyRouter(options.storagePath);
|
|
1331
1388
|
const initialInputBytes = Math.max(1, Buffer.byteLength(JSON.stringify(options.context)));
|
|
1332
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
|
+
}
|
|
1333
1395
|
const mainPermanentlyUnavailable = !primaryAvailable();
|
|
1334
1396
|
const incompleteQuotaPool = (routes.allRoutes.length === 0 && !mainPermanentlyUnavailable) ||
|
|
1335
1397
|
routes.allRoutes.some((candidate) => !quotaObservationIsFresh(candidate.quota, options.model.id));
|
|
@@ -1340,8 +1402,21 @@ async function executeWithFallback(options) {
|
|
|
1340
1402
|
affinityModelId: options.model.id,
|
|
1341
1403
|
// Keep an existing route after a temporary quota poll failure, but do not
|
|
1342
1404
|
// choose a new balanced route until the account pool has current quota data.
|
|
1343
|
-
candidates:
|
|
1344
|
-
|
|
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 }),
|
|
1345
1420
|
accountIdentities: vaultAccountIdentities(),
|
|
1346
1421
|
storage,
|
|
1347
1422
|
inputBytes: initialInputBytes,
|
|
@@ -1384,15 +1459,20 @@ async function executeWithFallback(options) {
|
|
|
1384
1459
|
const sendRoute = (selected) => sendAnthropicRequest({
|
|
1385
1460
|
...options,
|
|
1386
1461
|
oauthAccountId: selected.id,
|
|
1462
|
+
routingChoice: selected.id === advisedAccountId
|
|
1463
|
+
? (advice ?? undefined)
|
|
1464
|
+
: undefined,
|
|
1387
1465
|
route: `sticky:${selected.id}`,
|
|
1388
1466
|
});
|
|
1389
1467
|
const completeRoute = async (_selected, response, _markUsed = true) => response;
|
|
1390
1468
|
const heldAccountId = route.id;
|
|
1391
1469
|
const heldAccountIdentity = accountView(route.id)?.accountIdentity;
|
|
1392
|
-
const holdResponse = (retryAfterSeconds, upstream) => {
|
|
1470
|
+
const holdResponse = (retryAfterSeconds, upstream, routingHold = false) => {
|
|
1393
1471
|
const headers = new Headers(upstream);
|
|
1394
1472
|
headers.set('content-type', 'application/json');
|
|
1395
|
-
headers.set('retry-after', String(
|
|
1473
|
+
headers.set('retry-after', String(routingHold
|
|
1474
|
+
? retryAfterSeconds
|
|
1475
|
+
: stickyRetryAfterWithJitter(sessionId, retryAfterSeconds)));
|
|
1396
1476
|
return markPiAccountHold(new Response(JSON.stringify({
|
|
1397
1477
|
type: 'error',
|
|
1398
1478
|
error: {
|
|
@@ -1405,7 +1485,10 @@ async function executeWithFallback(options) {
|
|
|
1405
1485
|
resetAt: Date.now() + retryAfterSeconds * 1000,
|
|
1406
1486
|
});
|
|
1407
1487
|
};
|
|
1408
|
-
|
|
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)
|
|
1409
1492
|
? decideStickyQuotaFailure({
|
|
1410
1493
|
quota: route.quota,
|
|
1411
1494
|
modelId: options.model.id,
|
|
@@ -1488,7 +1571,8 @@ async function executeWithFallback(options) {
|
|
|
1488
1571
|
return completeRoute(route, await sendRoute(route));
|
|
1489
1572
|
}
|
|
1490
1573
|
}
|
|
1491
|
-
if (
|
|
1574
|
+
if (!(advice && !advisedAccountId) &&
|
|
1575
|
+
primaryResponseAllowsApiFallback(preflight) &&
|
|
1492
1576
|
(await primaryQuotaRefreshConfirmsExhausted())) {
|
|
1493
1577
|
if (preflight instanceof Response) {
|
|
1494
1578
|
await preflight.body?.cancel().catch(() => { });
|
|
@@ -1633,6 +1717,8 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1633
1717
|
toolNames = names;
|
|
1634
1718
|
},
|
|
1635
1719
|
};
|
|
1720
|
+
const routingState = { relay: createRoutingRelay() };
|
|
1721
|
+
Object.assign(request, { routingState });
|
|
1636
1722
|
const response = await runWithRequestSignal(options?.signal, () => withPiQuotaWait({
|
|
1637
1723
|
signal: options?.signal,
|
|
1638
1724
|
wait,
|
|
@@ -1656,6 +1742,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1656
1742
|
try {
|
|
1657
1743
|
const quota = await runtime.fetchQuota(account.id, fetchPiOAuth, options?.signal, undefined, 'admission');
|
|
1658
1744
|
if (hold &&
|
|
1745
|
+
!routingState.relay.admitted(options?.sessionId ?? '', account) &&
|
|
1659
1746
|
decideStickyQuotaFailure({ quota, modelId: model.id })
|
|
1660
1747
|
.action === 'migrate')
|
|
1661
1748
|
heldStillBlocked = true;
|
|
@@ -1674,6 +1761,8 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1674
1761
|
...request,
|
|
1675
1762
|
oauthAccountId: hold.accountId,
|
|
1676
1763
|
expectedAccountIdentity: hold.accountIdentity,
|
|
1764
|
+
routingRelay: routingState.relay,
|
|
1765
|
+
routingChoice: (await routingState.advice) ?? undefined,
|
|
1677
1766
|
}));
|
|
1678
1767
|
if (inspected.preflight instanceof Response)
|
|
1679
1768
|
return inspected.preflight;
|
|
@@ -1688,6 +1777,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1688
1777
|
const completion = createAnthropicStreamCompletion(response);
|
|
1689
1778
|
for await (const event of parseSse(response, completion)) {
|
|
1690
1779
|
if (event.type === 'message_start') {
|
|
1780
|
+
output.responseId = event.message?.id;
|
|
1691
1781
|
recordCacheUsage?.(event.message?.usage);
|
|
1692
1782
|
updateUsage(model, output, event.message?.usage);
|
|
1693
1783
|
}
|
package/dist/transport.d.ts
CHANGED
|
@@ -3,3 +3,4 @@ export declare function requirePiOAuthOrigin(value: string): URL;
|
|
|
3
3
|
export declare function buildPiOAuthMessagesUrl(baseUrl: string): URL;
|
|
4
4
|
/** Reject redirects rather than letting an approved OAuth destination forward the request. */
|
|
5
5
|
export declare const fetchPiOAuth: typeof fetch;
|
|
6
|
+
export declare function fetchPiStreamResponse(input: Parameters<typeof fetch>[0], init: Parameters<typeof fetch>[1], fetchImpl?: typeof fetch): Promise<Response>;
|
package/dist/transport.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { PerformanceObserver, } from 'node:perf_hooks';
|
|
2
|
+
import { copyStreamResponseTiming, createAnthropicOAuthFetch, requireAnthropicOAuthOrigin, } from '@cortexkit/anthropic-auth-core';
|
|
2
3
|
// Pi keeps its own refusal wording; Core supplies the origin rule itself.
|
|
3
4
|
const PI_OAUTH_ORIGIN = {
|
|
4
5
|
refusal: (reason) => new Error(reason === 'unparseable'
|
|
@@ -14,3 +15,91 @@ export function buildPiOAuthMessagesUrl(baseUrl) {
|
|
|
14
15
|
}
|
|
15
16
|
/** Reject redirects rather than letting an approved OAuth destination forward the request. */
|
|
16
17
|
export const fetchPiOAuth = createAnthropicOAuthFetch(PI_OAUTH_ORIGIN);
|
|
18
|
+
export async function fetchPiStreamResponse(input, init, fetchImpl = globalThis.fetch) {
|
|
19
|
+
const sentAt = performance.now();
|
|
20
|
+
let invokedUntil = Infinity;
|
|
21
|
+
const url = input instanceof Request ? input.url : String(input);
|
|
22
|
+
let sizes;
|
|
23
|
+
const collect = (entries) => {
|
|
24
|
+
const entry = entries.find((entry) => entry.name === url &&
|
|
25
|
+
entry.startTime >= sentAt &&
|
|
26
|
+
entry.startTime <= invokedUntil &&
|
|
27
|
+
entry.initiatorType === 'fetch');
|
|
28
|
+
if (!entry)
|
|
29
|
+
return;
|
|
30
|
+
sizes = {
|
|
31
|
+
encoded_body_bytes: entry.encodedBodySize,
|
|
32
|
+
decoded_body_bytes: entry.decodedBodySize,
|
|
33
|
+
};
|
|
34
|
+
observer?.disconnect();
|
|
35
|
+
};
|
|
36
|
+
// Observers have private queues, so concurrent fetches cannot consume each
|
|
37
|
+
// other's timing. Leave the runtime's bounded global timeline untouched.
|
|
38
|
+
const observer = process.versions.bun
|
|
39
|
+
? undefined
|
|
40
|
+
: new PerformanceObserver((list) => collect(list.getEntries()));
|
|
41
|
+
observer?.observe({ type: 'resource' });
|
|
42
|
+
const settle = () => {
|
|
43
|
+
if (observer)
|
|
44
|
+
collect(observer.takeRecords());
|
|
45
|
+
observer?.disconnect();
|
|
46
|
+
};
|
|
47
|
+
try {
|
|
48
|
+
// Resource startTime is recorded synchronously inside this physical fetch,
|
|
49
|
+
// not while awaiting headers; another same-URL send has a different window.
|
|
50
|
+
let pending;
|
|
51
|
+
try {
|
|
52
|
+
pending = fetchImpl(input, init);
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
invokedUntil = performance.now();
|
|
56
|
+
}
|
|
57
|
+
const response = await pending;
|
|
58
|
+
copyStreamResponseTiming(response, response, sentAt, 'physical_fetch', () => sizes);
|
|
59
|
+
if (!observer || !response.body) {
|
|
60
|
+
settle();
|
|
61
|
+
return response;
|
|
62
|
+
}
|
|
63
|
+
const reader = response.body.getReader();
|
|
64
|
+
const body = new ReadableStream({
|
|
65
|
+
async pull(controller) {
|
|
66
|
+
try {
|
|
67
|
+
const { done, value } = await reader.read();
|
|
68
|
+
if (done) {
|
|
69
|
+
// Undici publishes resource timing after resolving the final read.
|
|
70
|
+
// Let that end-of-body task run before closing the observed stream.
|
|
71
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
72
|
+
settle();
|
|
73
|
+
reader.releaseLock();
|
|
74
|
+
controller.close();
|
|
75
|
+
}
|
|
76
|
+
else
|
|
77
|
+
controller.enqueue(value);
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
settle();
|
|
81
|
+
reader.releaseLock();
|
|
82
|
+
controller.error(error);
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
async cancel(reason) {
|
|
86
|
+
try {
|
|
87
|
+
await reader.cancel(reason);
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
settle();
|
|
91
|
+
reader.releaseLock();
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
return copyStreamResponseTiming(response, new Response(body, {
|
|
96
|
+
status: response.status,
|
|
97
|
+
statusText: response.statusText,
|
|
98
|
+
headers: response.headers,
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
settle();
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
}
|
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",
|