@cortexkit/pi-anthropic-auth 2.4.13 → 2.5.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/convert.d.ts +2 -0
- package/dist/convert.js +3 -1
- package/dist/index.js +16 -4
- package/dist/stream.d.ts +7 -1
- package/dist/stream.js +101 -8
- package/package.json +2 -2
package/dist/convert.d.ts
CHANGED
|
@@ -45,6 +45,8 @@ export declare function buildAnthropicRequest(modelId: string, context: Context,
|
|
|
45
45
|
mode: Cache1hMode;
|
|
46
46
|
}, fastModeEnabled?: boolean, identity?: ClaudeCodeIdentity, controls?: {
|
|
47
47
|
effortTransitions?: readonly MidConversationEffortTransition[];
|
|
48
|
+
/** Leave the billing signature placeholder for the transport to finalize. */
|
|
49
|
+
deferSigning?: boolean;
|
|
48
50
|
thinkingPrefixMismatchBehavior?: ThinkingPrefixMismatchBehavior;
|
|
49
51
|
turnEndNote?: {
|
|
50
52
|
tools: string[];
|
package/dist/convert.js
CHANGED
|
@@ -640,7 +640,9 @@ export async function buildAnthropicRequest(modelId, context, options, cache, fa
|
|
|
640
640
|
if (breakpoints > 4)
|
|
641
641
|
throw new Error(`Anthropic accepts at most 4 cache breakpoints; the onPayload hook left ${breakpoints}`);
|
|
642
642
|
const unsigned = JSON.stringify(orderClaudeCodeBody(body));
|
|
643
|
-
const bodyText =
|
|
643
|
+
const bodyText = controls.deferSigning
|
|
644
|
+
? unsigned
|
|
645
|
+
: await signRequestBody(unsigned);
|
|
644
646
|
// Translate only known host/wire pairs that survived the hook and JSON
|
|
645
647
|
// serialization. Hook-added or renamed tools must not acquire an alias, and
|
|
646
648
|
// response decoding must never change outgoing names or signed history.
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import { collectPiEffortHistory, deriveContextEntries, } from './effort-history.
|
|
|
4
4
|
import { closePiNativeRuntime, getPiNativeRuntime, isNativeMigrationRequired, } from './native.js';
|
|
5
5
|
import { createPiNativeCommands } from './native-commands.js';
|
|
6
6
|
import { getPiAccountStoragePath, requirePiNativeHostAuth } from './paths.js';
|
|
7
|
-
import { streamCortexKitAnthropic } from './stream.js';
|
|
7
|
+
import { beginPiPrimaryTurn, clearPiStickyQuotaRetries, endPiPrimaryTurn, forgetPiMessageThread, streamCortexKitAnthropic, } from './stream.js';
|
|
8
8
|
function textImageInput() {
|
|
9
9
|
return ['text', 'image'];
|
|
10
10
|
}
|
|
@@ -43,6 +43,7 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
|
|
|
43
43
|
const workingMessageBySession = new Map();
|
|
44
44
|
pi.on('turn_start', async (_event, ctx) => {
|
|
45
45
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
46
|
+
beginPiPrimaryTurn(storagePath, sessionId);
|
|
46
47
|
if (!sessionId)
|
|
47
48
|
return;
|
|
48
49
|
if (ctx.hasUI) {
|
|
@@ -85,12 +86,21 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
|
|
|
85
86
|
break;
|
|
86
87
|
}
|
|
87
88
|
});
|
|
89
|
+
pi.on('agent_settled', async (_event, ctx) => {
|
|
90
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
91
|
+
endPiPrimaryTurn(storagePath, sessionId);
|
|
92
|
+
if (sessionId)
|
|
93
|
+
clearPiStickyQuotaRetries(storagePath, sessionId);
|
|
94
|
+
});
|
|
88
95
|
pi.on('session_shutdown', async (_event, ctx) => {
|
|
89
96
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
97
|
+
endPiPrimaryTurn(storagePath, sessionId);
|
|
90
98
|
if (sessionId) {
|
|
99
|
+
clearPiStickyQuotaRetries(storagePath, sessionId);
|
|
91
100
|
effortHistoryBySession.delete(sessionId);
|
|
92
101
|
workingMessageBySession.delete(sessionId);
|
|
93
102
|
sessionCacheActivity.forget(sessionId);
|
|
103
|
+
forgetPiMessageThread(sessionId);
|
|
94
104
|
}
|
|
95
105
|
await closePiNativeRuntime(storagePath);
|
|
96
106
|
});
|
|
@@ -231,14 +241,16 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
|
|
|
231
241
|
maxTokens: CLAUDE_SONNET_5_5_MAX_OUTPUT_TOKENS,
|
|
232
242
|
},
|
|
233
243
|
],
|
|
234
|
-
|
|
244
|
+
// Stock Pi's simplified calls share the session's whole-turn lease. Core
|
|
245
|
+
// checks the exact history and retained reply before continuing any anchor.
|
|
246
|
+
streamSimple: (model, context, options, origin = 'agent-loop') => streamCortexKitAnthropic(model, context, options, options?.sessionId
|
|
235
247
|
? effortHistoryBySession.get(options.sessionId)
|
|
236
248
|
: undefined, {
|
|
237
249
|
...quotaWait,
|
|
238
250
|
setWorkingMessage: (options?.sessionId
|
|
239
251
|
? workingMessageBySession.get(options.sessionId)
|
|
240
252
|
: undefined) ?? quotaWait?.setWorkingMessage,
|
|
241
|
-
}),
|
|
253
|
+
}, origin),
|
|
242
254
|
};
|
|
243
255
|
async function configureProvider() {
|
|
244
256
|
const streamSimple = configuration.streamSimple;
|
|
@@ -308,7 +320,7 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
|
|
|
308
320
|
baseUrl: configuration.baseUrl,
|
|
309
321
|
})),
|
|
310
322
|
// Preserve the legacy provider's simplified option surface for raw calls.
|
|
311
|
-
stream: (model, context, options) => streamSimple(model, context, options),
|
|
323
|
+
stream: (model, context, options) => streamSimple(model, context, options, 'direct'),
|
|
312
324
|
streamSimple,
|
|
313
325
|
};
|
|
314
326
|
pi.registerProvider(provider);
|
package/dist/stream.d.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { type ApiKeyAccount, CacheKeepManager, type MidConversationEffortTransition, type NativeAccountView, type QuotaManagerOptions } 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 PiQuotaWaitOptions } from './quota-wait.ts';
|
|
4
|
+
export declare function beginPiPrimaryTurn(storagePath: string, sessionId?: string): void;
|
|
5
|
+
export declare function endPiPrimaryTurn(storagePath: string, sessionId?: string): void;
|
|
6
|
+
export declare function forgetPiMessageThread(sessionId: string): void;
|
|
7
|
+
export declare function clearPiStickyQuotaRetries(storagePath: string, sessionId: string): void;
|
|
4
8
|
/** Set or clear the test replacement for the wait between quota usage polls. */
|
|
5
9
|
export declare function __setPiQuotaCallPauseForTest(pause: QuotaManagerOptions['pauseBetweenQuotaCalls']): void;
|
|
6
10
|
export declare function clearPiStickyRoutingSession(storagePath: string, sessionId: string): Promise<void>;
|
|
@@ -25,6 +29,7 @@ declare function sendAnthropicRequest(options: {
|
|
|
25
29
|
model: Model<Api>;
|
|
26
30
|
context: Context;
|
|
27
31
|
streamOptions?: SimpleStreamOptions;
|
|
32
|
+
requestOrigin?: 'agent-loop' | 'direct';
|
|
28
33
|
apiAccount?: NativeAccountView;
|
|
29
34
|
storagePath: string;
|
|
30
35
|
oauthAccountId?: string;
|
|
@@ -32,6 +37,7 @@ declare function sendAnthropicRequest(options: {
|
|
|
32
37
|
route?: string;
|
|
33
38
|
effortTransitions?: readonly MidConversationEffortTransition[];
|
|
34
39
|
onResolvedToolNames?: (toolNames: ReadonlyMap<string, string>) => void;
|
|
40
|
+
onThreadPrepared?: (fail: () => void) => void;
|
|
35
41
|
}, deps?: {
|
|
36
42
|
fetch?: typeof fetch;
|
|
37
43
|
cacheKeep?: CacheKeepManager;
|
|
@@ -52,5 +58,5 @@ export declare function firstStreamingError(response: Response): Promise<{
|
|
|
52
58
|
response: Response;
|
|
53
59
|
preflight: Response | 'rate_limit_error';
|
|
54
60
|
}>;
|
|
55
|
-
export declare function streamCortexKitAnthropic(model: Model<Api>, context: Context, options?: SimpleStreamOptions, effortTransitions?: readonly MidConversationEffortTransition[], wait?: PiQuotaWaitOptions): AssistantMessageEventStream;
|
|
61
|
+
export declare function streamCortexKitAnthropic(model: Model<Api>, context: Context, options?: SimpleStreamOptions, effortTransitions?: readonly MidConversationEffortTransition[], wait?: PiQuotaWaitOptions, requestOrigin?: 'agent-loop' | 'direct'): AssistantMessageEventStream;
|
|
56
62
|
export {};
|
package/dist/stream.js
CHANGED
|
@@ -1,15 +1,53 @@
|
|
|
1
|
-
import { applyClaudeCodeHeaders, applyCustomHeaders, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepManager, CacheKeepSessionRegistry, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createSseFramer, createStickyNoRouteResponse, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, FAST_MODE_BETA, getCache1hPersistentMode, getClaudeCodeIdentityForVerifiedAccount, getDefaultCacheKeepRegistryDirectory, getFallbackReauthLabels, getMaxSameAccountWait, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, isCache1hPersistentlyEnabled, isCacheKeepHybridActive, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isNativeTransientAccountError, isOAuthAccount, isPermanentRefreshError, isValidApiBaseURL, killswitchPassesPolicy, logger, mergeAnthropicBetas, NativeAccountRefusal, nativeAccountCanServe, parseSseFrame, QuotaManager, quotaBackoffActive, quotaExhaustionFromHeaders, quotaRefusalTiming, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, stickyQuotaSnapshotIsFresh, stickyRetryAfterWithJitter, stickyRouteFamilyForModel, } from '@cortexkit/anthropic-auth-core';
|
|
1
|
+
import { applyClaudeCodeHeaders, applyCustomHeaders, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepManager, CacheKeepSessionRegistry, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createSseFramer, createStickyNoRouteResponse, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, effectiveRelayTransport, FAST_MODE_BETA, getCache1hPersistentMode, getClaudeCodeIdentityForVerifiedAccount, getDefaultCacheKeepRegistryDirectory, getFallbackReauthLabels, getMaxSameAccountWait, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, isCache1hPersistentlyEnabled, isCacheKeepHybridActive, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isNativeTransientAccountError, isOAuthAccount, isPermanentRefreshError, isValidApiBaseURL, killswitchPassesPolicy, logger, MessageThreadTracker, mergeAnthropicBetas, NativeAccountRefusal, nativeAccountCanServe, parseSseFrame, prepareMessageThreadRequest, QuotaManager, quotaBackoffActive, quotaExhaustionFromHeaders, quotaRefusalTiming, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, stickyQuotaSnapshotIsFresh, stickyRetryAfterWithJitter, stickyRouteFamilyForModel, } from '@cortexkit/anthropic-auth-core';
|
|
2
2
|
import { calculateCost, createAssistantMessageEventStream, } from '@earendil-works/pi-ai';
|
|
3
3
|
import { buildAnthropicRequest, fromClaudeCodeToolName } from './convert.js';
|
|
4
4
|
import { getPiNativeRuntime, piAttemptAccessToken, } from './native.js';
|
|
5
5
|
import { getPiAccountStoragePath } from './paths.js';
|
|
6
6
|
import { markPiAccountHold, withPiQuotaWait, } from './quota-wait.js';
|
|
7
7
|
import { buildPiOAuthMessagesUrl, fetchPiOAuth, requirePiOAuthOrigin, } from './transport.js';
|
|
8
|
+
const messageThreads = new MessageThreadTracker();
|
|
9
|
+
// Each session owns its lease; storage identifies which host may end it.
|
|
10
|
+
const primaryTurns = new Map();
|
|
11
|
+
export function beginPiPrimaryTurn(storagePath, sessionId) {
|
|
12
|
+
if (!sessionId)
|
|
13
|
+
return;
|
|
14
|
+
primaryTurns.delete(sessionId);
|
|
15
|
+
primaryTurns.set(sessionId, storagePath);
|
|
16
|
+
while (primaryTurns.size > 128) {
|
|
17
|
+
const oldest = primaryTurns.keys().next().value;
|
|
18
|
+
if (oldest === undefined)
|
|
19
|
+
break;
|
|
20
|
+
primaryTurns.delete(oldest);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export function endPiPrimaryTurn(storagePath, sessionId) {
|
|
24
|
+
if (sessionId && primaryTurns.get(sessionId) === storagePath)
|
|
25
|
+
primaryTurns.delete(sessionId);
|
|
26
|
+
}
|
|
27
|
+
function isPiPrimaryThreadRequest(storagePath, options, origin) {
|
|
28
|
+
// SDK summaries disable caching; SDK cache warms request exactly one token.
|
|
29
|
+
if (origin !== 'agent-loop' ||
|
|
30
|
+
options?.cacheRetention === 'none' ||
|
|
31
|
+
options?.maxTokens === 1)
|
|
32
|
+
return false;
|
|
33
|
+
return Boolean(options?.sessionId &&
|
|
34
|
+
primaryTurns.get(options.sessionId) === storagePath &&
|
|
35
|
+
typeof options.onPayload === 'function' &&
|
|
36
|
+
typeof options.onResponse === 'function' &&
|
|
37
|
+
typeof options.onProviderStreamEvent === 'function');
|
|
38
|
+
}
|
|
39
|
+
export function forgetPiMessageThread(sessionId) {
|
|
40
|
+
messageThreads.forget(sessionId);
|
|
41
|
+
}
|
|
8
42
|
/** Dump label for a physical send that failed before any response arrived. */
|
|
9
43
|
const PHYSICAL_SEND_FAILED = 'physical send failed before a response';
|
|
10
44
|
let cacheKeepRegistry;
|
|
11
45
|
let cacheKeepRegistryDirectory;
|
|
12
46
|
const stickyRouters = new Map();
|
|
47
|
+
const stickyQuotaRetries = new StickyQuotaRetryCounter();
|
|
48
|
+
export function clearPiStickyQuotaRetries(storagePath, sessionId) {
|
|
49
|
+
stickyQuotaRetries.clear(JSON.stringify([storagePath, sessionId]));
|
|
50
|
+
}
|
|
13
51
|
const quotaManagers = new Map();
|
|
14
52
|
const PI_SERVICE_CACHE_LIMIT = 16;
|
|
15
53
|
/**
|
|
@@ -125,6 +163,7 @@ async function getPiStickyRouter(storagePath) {
|
|
|
125
163
|
}
|
|
126
164
|
export async function clearPiStickyRoutingSession(storagePath, sessionId) {
|
|
127
165
|
sessionCacheActivity.forget(sessionId);
|
|
166
|
+
clearPiStickyQuotaRetries(storagePath, sessionId);
|
|
128
167
|
await (await getPiStickyRouter(storagePath)).clear(sessionId);
|
|
129
168
|
}
|
|
130
169
|
function getPiCacheKeepRegistry() {
|
|
@@ -382,6 +421,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
382
421
|
enabled: oneHourCache,
|
|
383
422
|
mode: getCache1hPersistentMode(storage),
|
|
384
423
|
}, isFastModePersistentlyEnabled(storage), identity, {
|
|
424
|
+
deferSigning: true,
|
|
385
425
|
effortTransitions: options.apiAccount ? [] : options.effortTransitions,
|
|
386
426
|
turnEndNote: storage.turnEndNote,
|
|
387
427
|
thinkingPrefixMismatchBehavior: options.apiAccount
|
|
@@ -391,6 +431,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
391
431
|
onPayload: (payload) => options.streamOptions?.onPayload?.(payload, options.model),
|
|
392
432
|
}),
|
|
393
433
|
});
|
|
434
|
+
let wireBodyText = bodyText;
|
|
394
435
|
options.onResolvedToolNames?.(toolNames);
|
|
395
436
|
const fastMode = body.speed === 'fast';
|
|
396
437
|
const headers = options.apiAccount
|
|
@@ -450,6 +491,33 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
450
491
|
throw new Error('Pi native OAuth route identity changed');
|
|
451
492
|
return attempt;
|
|
452
493
|
};
|
|
494
|
+
const relayConfig = options.apiAccount
|
|
495
|
+
? null
|
|
496
|
+
: await (await native.service()).getRelayConfig();
|
|
497
|
+
let threadRequest;
|
|
498
|
+
if (!options.apiAccount &&
|
|
499
|
+
isPiPrimaryThreadRequest(options.storagePath, options.streamOptions, options.requestOrigin) &&
|
|
500
|
+
(!relayConfig ||
|
|
501
|
+
effectiveRelayTransport(relayConfig.transport, relayConfig.url) !==
|
|
502
|
+
'websocket')) {
|
|
503
|
+
nextAttempt = await takeAttempt();
|
|
504
|
+
threadRequest = await prepareMessageThreadRequest(messageThreads, {
|
|
505
|
+
session: relayAffinity ?? undefined,
|
|
506
|
+
account: nextAttempt.accountIdentity,
|
|
507
|
+
credential: piAttemptAccessToken(nextAttempt),
|
|
508
|
+
bodyText,
|
|
509
|
+
replyToolNames: toolNames,
|
|
510
|
+
headers,
|
|
511
|
+
signal: init.signal ?? undefined,
|
|
512
|
+
});
|
|
513
|
+
options.onThreadPrepared?.(threadRequest.fail);
|
|
514
|
+
wireBodyText = threadRequest.bodyText;
|
|
515
|
+
init.body = wireBodyText;
|
|
516
|
+
}
|
|
517
|
+
else {
|
|
518
|
+
wireBodyText = await signRequestBody(bodyText);
|
|
519
|
+
init.body = wireBodyText;
|
|
520
|
+
}
|
|
453
521
|
const directFetch = async () => {
|
|
454
522
|
let attempt;
|
|
455
523
|
let apiSubject;
|
|
@@ -508,7 +576,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
508
576
|
affinity: relayAffinity,
|
|
509
577
|
route: options.route ?? 'oauth',
|
|
510
578
|
status: response.status,
|
|
511
|
-
bodyText,
|
|
579
|
+
bodyText: wireBodyText,
|
|
512
580
|
url: input.toString(),
|
|
513
581
|
method: init.method,
|
|
514
582
|
headers,
|
|
@@ -535,7 +603,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
535
603
|
route: options.route ??
|
|
536
604
|
(options.apiAccount ? `api:${options.apiAccount.id}` : 'oauth'),
|
|
537
605
|
status: response.status,
|
|
538
|
-
bodyText,
|
|
606
|
+
bodyText: wireBodyText,
|
|
539
607
|
url: input.toString(),
|
|
540
608
|
method: init.method,
|
|
541
609
|
headers: init.headers,
|
|
@@ -553,7 +621,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
553
621
|
(options.apiAccount ? `api:${options.apiAccount.id}` : 'oauth'),
|
|
554
622
|
// A fixed label: the error text can repeat provider output or a credential.
|
|
555
623
|
error: PHYSICAL_SEND_FAILED,
|
|
556
|
-
bodyText,
|
|
624
|
+
bodyText: wireBodyText,
|
|
557
625
|
url: input.toString(),
|
|
558
626
|
method: init.method,
|
|
559
627
|
headers: init.headers,
|
|
@@ -579,11 +647,11 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
579
647
|
// that attempt's own credentials and the relay token; a direct fallback is
|
|
580
648
|
// scrubbed by directFetch.
|
|
581
649
|
const sendRelayAttempt = async () => sendViaRelay({
|
|
582
|
-
config:
|
|
650
|
+
config: relayConfig,
|
|
583
651
|
input,
|
|
584
652
|
init,
|
|
585
653
|
headers,
|
|
586
|
-
body:
|
|
654
|
+
body: wireBodyText,
|
|
587
655
|
fallback: directFetch,
|
|
588
656
|
affinity: relayAffinity,
|
|
589
657
|
authorizeAttempt: async () => {
|
|
@@ -630,6 +698,14 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
630
698
|
// If the request was cancelled since, end it as cancelled here.
|
|
631
699
|
if (relay401Attempt && response.status === 401)
|
|
632
700
|
await endIfCancelled(response, init.signal);
|
|
701
|
+
if (threadRequest) {
|
|
702
|
+
response = await threadRequest.recover(response, async (createBody) => {
|
|
703
|
+
wireBodyText = createBody;
|
|
704
|
+
init.body = createBody;
|
|
705
|
+
return sendRelayAttempt();
|
|
706
|
+
});
|
|
707
|
+
response = threadRequest.observe(response);
|
|
708
|
+
}
|
|
633
709
|
if (response.ok && lastTransport === 'relay' && relayAttempt) {
|
|
634
710
|
trackAcceptedRequest();
|
|
635
711
|
markServed(relayAttempt);
|
|
@@ -1033,6 +1109,8 @@ async function executeWithFallback(options) {
|
|
|
1033
1109
|
storage,
|
|
1034
1110
|
inputBytes: initialInputBytes,
|
|
1035
1111
|
});
|
|
1112
|
+
if (resolution?.migrated)
|
|
1113
|
+
clearPiStickyQuotaRetries(options.storagePath, sessionId);
|
|
1036
1114
|
if (!resolution && incompleteQuotaPool) {
|
|
1037
1115
|
const error = new Error('Sticky-balanced routing is waiting for current OAuth quota snapshots');
|
|
1038
1116
|
Object.assign(error, {
|
|
@@ -1129,6 +1207,12 @@ async function executeWithFallback(options) {
|
|
|
1129
1207
|
modelId: options.model.id,
|
|
1130
1208
|
responseHeaders,
|
|
1131
1209
|
sessionId,
|
|
1210
|
+
unconfirmedRetry: {
|
|
1211
|
+
counter: stickyQuotaRetries,
|
|
1212
|
+
sessionId: JSON.stringify([options.storagePath, sessionId]),
|
|
1213
|
+
turnId: String(options.context.messages.findLast((message) => message.role === 'user')?.timestamp ?? sessionId),
|
|
1214
|
+
accountId: route.id,
|
|
1215
|
+
},
|
|
1132
1216
|
holdUntil: sessionCacheActivity.holdUntil(sessionId, route.id, Date.now(), getMaxSameAccountWait(storage)),
|
|
1133
1217
|
});
|
|
1134
1218
|
if (decision.action === 'hold') {
|
|
@@ -1162,6 +1246,7 @@ async function executeWithFallback(options) {
|
|
|
1162
1246
|
});
|
|
1163
1247
|
const migrated = routes.allRoutes.find((candidate) => candidate.id === resolution?.accountId);
|
|
1164
1248
|
if (resolution && migrated) {
|
|
1249
|
+
clearPiStickyQuotaRetries(options.storagePath, sessionId);
|
|
1165
1250
|
route = migrated;
|
|
1166
1251
|
return completeRoute(route, await sendRoute(route));
|
|
1167
1252
|
}
|
|
@@ -1178,8 +1263,10 @@ async function executeWithFallback(options) {
|
|
|
1178
1263
|
includeApiRoutes: true,
|
|
1179
1264
|
apiOnly: true,
|
|
1180
1265
|
});
|
|
1181
|
-
if (apiFallback)
|
|
1266
|
+
if (apiFallback) {
|
|
1267
|
+
clearPiStickyQuotaRetries(options.storagePath, sessionId);
|
|
1182
1268
|
return apiFallback;
|
|
1269
|
+
}
|
|
1183
1270
|
}
|
|
1184
1271
|
}
|
|
1185
1272
|
return completeRoute(route, preflight instanceof Response ? preflight : response);
|
|
@@ -1281,10 +1368,11 @@ async function executeWithFallback(options) {
|
|
|
1281
1368
|
}
|
|
1282
1369
|
return primaryPreflight instanceof Response ? primaryPreflight : primary;
|
|
1283
1370
|
}
|
|
1284
|
-
export function streamCortexKitAnthropic(model, context, options, effortTransitions, wait) {
|
|
1371
|
+
export function streamCortexKitAnthropic(model, context, options, effortTransitions, wait, requestOrigin = 'direct') {
|
|
1285
1372
|
const stream = createAssistantMessageEventStream();
|
|
1286
1373
|
void (async () => {
|
|
1287
1374
|
const output = createOutput(model);
|
|
1375
|
+
let failThread;
|
|
1288
1376
|
stream.push({ type: 'start', partial: output });
|
|
1289
1377
|
try {
|
|
1290
1378
|
buildPiOAuthMessagesUrl(model.baseUrl);
|
|
@@ -1294,7 +1382,11 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1294
1382
|
model,
|
|
1295
1383
|
context,
|
|
1296
1384
|
streamOptions: options,
|
|
1385
|
+
requestOrigin,
|
|
1297
1386
|
storagePath,
|
|
1387
|
+
onThreadPrepared: (fail) => {
|
|
1388
|
+
failThread = fail;
|
|
1389
|
+
},
|
|
1298
1390
|
effortTransitions,
|
|
1299
1391
|
onResolvedToolNames: (names) => {
|
|
1300
1392
|
toolNames = names;
|
|
@@ -1515,6 +1607,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1515
1607
|
stream.end();
|
|
1516
1608
|
}
|
|
1517
1609
|
catch (error) {
|
|
1610
|
+
failThread?.();
|
|
1518
1611
|
for (const block of output.content)
|
|
1519
1612
|
delete block.index;
|
|
1520
1613
|
output.stopReason = options?.signal?.aborted ? 'aborted' : 'error';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/pi-anthropic-auth",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.5.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.
|
|
39
|
+
"@cortexkit/anthropic-auth-core": "2.5.1"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"@earendil-works/pi-ai": ">=0.86.1 <2",
|