@cortexkit/pi-anthropic-auth 2.4.12 → 2.4.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/convert.d.ts +23 -2
- package/dist/convert.js +70 -10
- package/dist/index.d.ts +2 -0
- package/dist/index.js +33 -3
- package/dist/native-commands.js +7 -2
- package/dist/quota-wait.d.ts +19 -0
- package/dist/quota-wait.js +78 -0
- package/dist/stream.d.ts +5 -3
- package/dist/stream.js +146 -61
- package/package.json +2 -2
package/dist/convert.d.ts
CHANGED
|
@@ -26,7 +26,20 @@ export type AnthropicRequestBody = {
|
|
|
26
26
|
};
|
|
27
27
|
speed?: 'fast';
|
|
28
28
|
};
|
|
29
|
-
|
|
29
|
+
/**
|
|
30
|
+
* Snapshot the wire name sent for each host tool in one request.
|
|
31
|
+
*
|
|
32
|
+
* Claude Code aliases are case-insensitive, so two host tools can collapse onto
|
|
33
|
+
* one wire name; that request fails before dispatch rather than letting the
|
|
34
|
+
* response decoder pick either tool.
|
|
35
|
+
*/
|
|
36
|
+
export declare function createClaudeCodeToolNameMap(tools: readonly Tool[]): ReadonlyMap<string, string>;
|
|
37
|
+
/**
|
|
38
|
+
* Map a response tool name back through the exact snapshot sent with the
|
|
39
|
+
* request. Unknown names stay unknown instead of being case-folded onto an
|
|
40
|
+
* executable host tool.
|
|
41
|
+
*/
|
|
42
|
+
export declare function fromClaudeCodeToolName(name: string, requestedToolNames: ReadonlyMap<string, string>): string;
|
|
30
43
|
export declare function buildAnthropicRequest(modelId: string, context: Context, options: SimpleStreamOptions | undefined, cache: {
|
|
31
44
|
enabled: boolean;
|
|
32
45
|
mode: Cache1hMode;
|
|
@@ -36,8 +49,16 @@ export declare function buildAnthropicRequest(modelId: string, context: Context,
|
|
|
36
49
|
turnEndNote?: {
|
|
37
50
|
tools: string[];
|
|
38
51
|
};
|
|
52
|
+
/**
|
|
53
|
+
* Pi's `options.onPayload`, bound to the dispatched model. Pi's provider
|
|
54
|
+
* contract: call it before sending and send any replacement it returns. It
|
|
55
|
+
* sees the body with this provider's cache breakpoints placed and runs
|
|
56
|
+
* before signing, so the billing signature covers what is sent.
|
|
57
|
+
*/
|
|
58
|
+
onPayload?: (body: AnthropicRequestBody) => unknown | Promise<unknown>;
|
|
39
59
|
}): Promise<{
|
|
40
60
|
body: AnthropicRequestBody;
|
|
41
61
|
bodyText: string;
|
|
42
|
-
|
|
62
|
+
toolNames: ReadonlyMap<string, string>;
|
|
63
|
+
cacheTtlMs: number;
|
|
43
64
|
}>;
|
package/dist/convert.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { applyClaudeCodeMetadata, applyMidConversationOutputConfig, applyThinkingBindingControls, applyTurnEndNotes, assertNoMeaningfulTrailingAssistant, buildBillingHeaderValue, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, CLAUDE_FABLE_MYTHOS_5_SUMMARIZED_THINKING, CLAUDE_HAIKU_5_5_ADAPTIVE_THINKING, CLAUDE_OPUS_5_5_ADAPTIVE_THINKING, CLAUDE_OPUS_5_ADAPTIVE_THINKING, CLAUDE_SONNET_5_5_ADAPTIVE_THINKING, CLAUDE_SONNET_5_ADAPTIVE_THINKING, ClaudeCodeFirstUserTextTracker, isClaudeFableOrMythos5Model, isClaudeHaiku55Model, isClaudeOpus5Model, isClaudeOpus55Model, isClaudeSonnet5Model, isClaudeSonnet55Model, isFastModeSupportedModel, isOpenAIReasoningSignature, orderClaudeCodeBody, signRequestBody, stripEmptyTrailingAssistantMessages, } from '@cortexkit/anthropic-auth-core';
|
|
1
|
+
import { applyClaudeCodeMetadata, applyMidConversationOutputConfig, applyThinkingBindingControls, applyTurnEndNotes, assertNoMeaningfulTrailingAssistant, buildBillingHeaderValue, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, CLAUDE_FABLE_MYTHOS_5_SUMMARIZED_THINKING, CLAUDE_HAIKU_5_5_ADAPTIVE_THINKING, CLAUDE_OPUS_5_5_ADAPTIVE_THINKING, CLAUDE_OPUS_5_ADAPTIVE_THINKING, CLAUDE_SONNET_5_5_ADAPTIVE_THINKING, CLAUDE_SONNET_5_ADAPTIVE_THINKING, ClaudeCodeFirstUserTextTracker, isClaudeFableOrMythos5Model, isClaudeHaiku55Model, isClaudeOpus5Model, isClaudeOpus55Model, isClaudeSonnet5Model, isClaudeSonnet55Model, isFastModeSupportedModel, isOpenAIReasoningSignature, orderClaudeCodeBody, PROMPT_CACHE_1H_TTL_MS, PROMPT_CACHE_DEFAULT_TTL_MS, signRequestBody, stripEmptyTrailingAssistantMessages, } from '@cortexkit/anthropic-auth-core';
|
|
2
2
|
import { collapseSystemMessages, getCurrentSystemPrompt, getCurrentTools, normalizeContext, } from './transcript.js';
|
|
3
3
|
// Anchor identifying Pi's documentation paragraph — the only part of the prompt
|
|
4
4
|
// that Anthropic currently rejects in system[]. Unknown prompt shapes take the
|
|
@@ -47,9 +47,32 @@ function sanitizeToolId(id) {
|
|
|
47
47
|
function toClaudeCodeToolName(name) {
|
|
48
48
|
return CLAUDE_CODE_TOOLS.get(name.toLowerCase()) ?? name;
|
|
49
49
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
50
|
+
/**
|
|
51
|
+
* Snapshot the wire name sent for each host tool in one request.
|
|
52
|
+
*
|
|
53
|
+
* Claude Code aliases are case-insensitive, so two host tools can collapse onto
|
|
54
|
+
* one wire name; that request fails before dispatch rather than letting the
|
|
55
|
+
* response decoder pick either tool.
|
|
56
|
+
*/
|
|
57
|
+
export function createClaudeCodeToolNameMap(tools) {
|
|
58
|
+
const names = new Map();
|
|
59
|
+
for (const tool of tools) {
|
|
60
|
+
const wireName = toClaudeCodeToolName(tool.name);
|
|
61
|
+
const existing = names.get(wireName);
|
|
62
|
+
if (existing !== undefined) {
|
|
63
|
+
throw new Error(`Anthropic tool name collision: "${existing}" and "${tool.name}" both map to "${wireName}"`);
|
|
64
|
+
}
|
|
65
|
+
names.set(wireName, tool.name);
|
|
66
|
+
}
|
|
67
|
+
return names;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Map a response tool name back through the exact snapshot sent with the
|
|
71
|
+
* request. Unknown names stay unknown instead of being case-folded onto an
|
|
72
|
+
* executable host tool.
|
|
73
|
+
*/
|
|
74
|
+
export function fromClaudeCodeToolName(name, requestedToolNames) {
|
|
75
|
+
return requestedToolNames.get(name) ?? name;
|
|
53
76
|
}
|
|
54
77
|
function getAssistantToolCallIds(message) {
|
|
55
78
|
const ids = new Set();
|
|
@@ -124,9 +147,19 @@ function convertMessages(messages, targetModelId, visibleReplies) {
|
|
|
124
147
|
}
|
|
125
148
|
}
|
|
126
149
|
else {
|
|
150
|
+
const parts = message.content;
|
|
151
|
+
// A text-only user message with several parts keeps them as separate
|
|
152
|
+
// blocks, as Pi's own Anthropic provider sends them, so a host's block
|
|
153
|
+
// boundaries (and the cache breakpoints it places between them) survive.
|
|
154
|
+
const blocks = parts.some((item) => item.type === 'image')
|
|
155
|
+
? []
|
|
156
|
+
: parts
|
|
157
|
+
.filter((item) => item.type === 'text')
|
|
158
|
+
.map((item) => ({ type: 'text', text: sanitize(item.text) }))
|
|
159
|
+
.filter((block) => block.text.trim());
|
|
127
160
|
result.push({
|
|
128
161
|
role: 'user',
|
|
129
|
-
content: convertTextAndImages(
|
|
162
|
+
content: blocks.length > 1 ? blocks : convertTextAndImages(parts),
|
|
130
163
|
});
|
|
131
164
|
}
|
|
132
165
|
continue;
|
|
@@ -273,6 +306,7 @@ function convertTools(tools) {
|
|
|
273
306
|
if (!tools?.length)
|
|
274
307
|
return undefined;
|
|
275
308
|
return tools.map((tool) => ({
|
|
309
|
+
// Names are checked for collisions by createClaudeCodeToolNameMap first.
|
|
276
310
|
name: toClaudeCodeToolName(tool.name),
|
|
277
311
|
description: tool.description,
|
|
278
312
|
input_schema: {
|
|
@@ -507,13 +541,14 @@ export async function buildAnthropicRequest(modelId, context, options, cache, fa
|
|
|
507
541
|
}
|
|
508
542
|
prependCachedPromptBlock(messages, prompt.messageText);
|
|
509
543
|
}
|
|
510
|
-
|
|
544
|
+
let body = {
|
|
511
545
|
model: modelId,
|
|
512
546
|
max_tokens: options?.maxTokens ?? 16_384,
|
|
513
547
|
stream: true,
|
|
514
548
|
system,
|
|
515
549
|
messages,
|
|
516
550
|
};
|
|
551
|
+
const declaredToolNames = createClaudeCodeToolNameMap(context.tools ?? []);
|
|
517
552
|
const tools = convertTools(context.tools);
|
|
518
553
|
if (tools?.length)
|
|
519
554
|
body.tools = tools;
|
|
@@ -590,10 +625,35 @@ export async function buildAnthropicRequest(modelId, context, options, cache, fa
|
|
|
590
625
|
applyThinkingBindingControls(body, controls.thinkingPrefixMismatchBehavior ?? 'account-default');
|
|
591
626
|
applyClaudeCodeMetadata(body, identity);
|
|
592
627
|
}
|
|
628
|
+
const replaced = controls.onPayload
|
|
629
|
+
? await controls.onPayload(body)
|
|
630
|
+
: undefined;
|
|
631
|
+
if (replaced !== undefined)
|
|
632
|
+
body = { ...replaced, stream: true };
|
|
633
|
+
// As in Pi's native adapter, replacements must still request SSE. Hooks own
|
|
634
|
+
// the validity of their other edits and must not add a fifth cache breakpoint:
|
|
635
|
+
// the provider's existing layout may already use Anthropic's four slots.
|
|
636
|
+
let breakpoints = 0;
|
|
637
|
+
walkCacheControlHolders(body, () => {
|
|
638
|
+
breakpoints += 1;
|
|
639
|
+
});
|
|
640
|
+
if (breakpoints > 4)
|
|
641
|
+
throw new Error(`Anthropic accepts at most 4 cache breakpoints; the onPayload hook left ${breakpoints}`);
|
|
593
642
|
const unsigned = JSON.stringify(orderClaudeCodeBody(body));
|
|
594
643
|
const bodyText = await signRequestBody(unsigned);
|
|
595
|
-
//
|
|
596
|
-
//
|
|
597
|
-
//
|
|
598
|
-
|
|
644
|
+
// Translate only known host/wire pairs that survived the hook and JSON
|
|
645
|
+
// serialization. Hook-added or renamed tools must not acquire an alias, and
|
|
646
|
+
// response decoding must never change outgoing names or signed history.
|
|
647
|
+
const sentBody = JSON.parse(bodyText);
|
|
648
|
+
const sentNames = new Set(sentBody.tools?.map((tool) => tool.name));
|
|
649
|
+
const toolNames = new Map([...declaredToolNames].filter(([wireName]) => sentNames.has(wireName)));
|
|
650
|
+
// Sticky routing uses the longest TTL actually sent to bound how long a
|
|
651
|
+
// session waits on its account. Include hook edits, not the account setting;
|
|
652
|
+
// a cache_control key inside tool data is not a cache breakpoint.
|
|
653
|
+
let cacheTtlMs = PROMPT_CACHE_DEFAULT_TTL_MS;
|
|
654
|
+
walkCacheControlHolders(sentBody, (holder) => {
|
|
655
|
+
if (holder.cache_control.ttl === '1h')
|
|
656
|
+
cacheTtlMs = PROMPT_CACHE_1H_TTL_MS;
|
|
657
|
+
});
|
|
658
|
+
return { body, bodyText, toolNames, cacheTtlMs };
|
|
599
659
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { type NativeCustodyClient } from '@cortexkit/anthropic-auth-core';
|
|
2
2
|
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
import type { PiQuotaWaitOptions } from './quota-wait.ts';
|
|
3
4
|
export default function cortexKitPiAnthropicAuth(pi: ExtensionAPI, options?: {
|
|
4
5
|
connectScoped?: () => Promise<NativeCustodyClient>;
|
|
6
|
+
quotaWait?: PiQuotaWaitOptions;
|
|
5
7
|
}): Promise<void>;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CLAUDE_FABLE_MYTHOS_5_MODEL_SPECS, CLAUDE_HAIKU_5_5_CONTEXT_WINDOW, CLAUDE_HAIKU_5_5_LONG_CONTEXT_PRICING, CLAUDE_HAIKU_5_5_LONG_CONTEXT_THRESHOLD, CLAUDE_HAIKU_5_5_MAX_OUTPUT_TOKENS, CLAUDE_HAIKU_5_5_MODEL_ID, CLAUDE_HAIKU_5_5_PRICING, CLAUDE_SONNET_5_5_CONTEXT_WINDOW, CLAUDE_SONNET_5_5_MAX_OUTPUT_TOKENS, CLAUDE_SONNET_5_5_MODEL_ID, CLAUDE_SONNET_5_5_PRICING, defaultAdaptiveEffort, getClaudeModelCatalogue, nativeAccountCanServe, readNativeEnrollmentMode, } from '@cortexkit/anthropic-auth-core';
|
|
1
|
+
import { CLAUDE_FABLE_MYTHOS_5_MODEL_SPECS, CLAUDE_HAIKU_5_5_CONTEXT_WINDOW, CLAUDE_HAIKU_5_5_LONG_CONTEXT_PRICING, CLAUDE_HAIKU_5_5_LONG_CONTEXT_THRESHOLD, CLAUDE_HAIKU_5_5_MAX_OUTPUT_TOKENS, CLAUDE_HAIKU_5_5_MODEL_ID, CLAUDE_HAIKU_5_5_PRICING, CLAUDE_SONNET_5_5_CONTEXT_WINDOW, CLAUDE_SONNET_5_5_MAX_OUTPUT_TOKENS, CLAUDE_SONNET_5_5_MODEL_ID, CLAUDE_SONNET_5_5_PRICING, defaultAdaptiveEffort, getClaudeModelCatalogue, nativeAccountCanServe, readNativeEnrollmentMode, sessionCacheActivity, } from '@cortexkit/anthropic-auth-core';
|
|
2
2
|
import { registerCommands } from './commands.js';
|
|
3
3
|
import { collectPiEffortHistory, deriveContextEntries, } from './effort-history.js';
|
|
4
4
|
import { closePiNativeRuntime, getPiNativeRuntime, isNativeMigrationRequired, } from './native.js';
|
|
@@ -34,15 +34,28 @@ function refuseUnmigratedPrompts(pi, storagePath) {
|
|
|
34
34
|
}
|
|
35
35
|
export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
|
|
36
36
|
const storagePath = getPiAccountStoragePath();
|
|
37
|
+
const quotaWait = options.quotaWait;
|
|
37
38
|
getPiNativeRuntime(storagePath, {
|
|
38
39
|
...(options.connectScoped && { connect: options.connectScoped }),
|
|
39
40
|
});
|
|
40
41
|
registerCommands(pi, createPiNativeCommands(storagePath));
|
|
41
42
|
const effortHistoryBySession = new Map();
|
|
43
|
+
const workingMessageBySession = new Map();
|
|
42
44
|
pi.on('turn_start', async (_event, ctx) => {
|
|
43
45
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
44
46
|
if (!sessionId)
|
|
45
47
|
return;
|
|
48
|
+
if (ctx.hasUI) {
|
|
49
|
+
workingMessageBySession.set(sessionId, (message) => {
|
|
50
|
+
if (ctx.sessionManager.getSessionId() === sessionId)
|
|
51
|
+
ctx.ui.setWorkingMessage(message);
|
|
52
|
+
});
|
|
53
|
+
if (workingMessageBySession.size > 128) {
|
|
54
|
+
const oldest = workingMessageBySession.keys().next().value;
|
|
55
|
+
if (oldest !== undefined)
|
|
56
|
+
workingMessageBySession.delete(oldest);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
46
59
|
// This hook collects effort history for the per-message effort markers
|
|
47
60
|
// that core adds to Fable 5.1, Opus 5.5 and Sonnet 5.5 requests. A host
|
|
48
61
|
// whose session entries do not match what this reads must cost the
|
|
@@ -74,8 +87,11 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
|
|
|
74
87
|
});
|
|
75
88
|
pi.on('session_shutdown', async (_event, ctx) => {
|
|
76
89
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
77
|
-
if (sessionId)
|
|
90
|
+
if (sessionId) {
|
|
78
91
|
effortHistoryBySession.delete(sessionId);
|
|
92
|
+
workingMessageBySession.delete(sessionId);
|
|
93
|
+
sessionCacheActivity.forget(sessionId);
|
|
94
|
+
}
|
|
79
95
|
await closePiNativeRuntime(storagePath);
|
|
80
96
|
});
|
|
81
97
|
// Keep the catalog chat-only even when Pi also accepts image/classifier models.
|
|
@@ -106,6 +122,15 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
|
|
|
106
122
|
id: 'claude-opus-5-5',
|
|
107
123
|
name: 'Claude Opus 5.5',
|
|
108
124
|
reasoning: true,
|
|
125
|
+
// Opus 5.5 always uses adaptive thinking: it cannot disable thinking or
|
|
126
|
+
// honor a generic `minimal` effort. Advertise only the API's effort
|
|
127
|
+
// choices, including the extended levels, as for Sonnet/Haiku 5.5.
|
|
128
|
+
thinkingLevelMap: {
|
|
129
|
+
off: null,
|
|
130
|
+
minimal: null,
|
|
131
|
+
xhigh: 'xhigh',
|
|
132
|
+
max: 'max',
|
|
133
|
+
},
|
|
109
134
|
input: textImageInput(),
|
|
110
135
|
cost: { input: 4, output: 20, cacheRead: 0.2, cacheWrite: 8 },
|
|
111
136
|
contextWindow: 1_000_000,
|
|
@@ -208,7 +233,12 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
|
|
|
208
233
|
],
|
|
209
234
|
streamSimple: (model, context, options) => streamCortexKitAnthropic(model, context, options, options?.sessionId
|
|
210
235
|
? effortHistoryBySession.get(options.sessionId)
|
|
211
|
-
: undefined
|
|
236
|
+
: undefined, {
|
|
237
|
+
...quotaWait,
|
|
238
|
+
setWorkingMessage: (options?.sessionId
|
|
239
|
+
? workingMessageBySession.get(options.sessionId)
|
|
240
|
+
: undefined) ?? quotaWait?.setWorkingMessage,
|
|
241
|
+
}),
|
|
212
242
|
};
|
|
213
243
|
async function configureProvider() {
|
|
214
244
|
const streamSimple = configuration.streamSimple;
|
package/dist/native-commands.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { authorize, buildClaudeQuotaSummary, buildPrimeAccountStatuses, DEFAULT_KILLSWITCH_THRESHOLDS, exchange, executeCacheKeepCommand, executePrimeCommand, formatEnrollmentStatus, formatNativeAccountState, formatOAuthAccountTier, getCache1hPersistentMode, getCacheKeepWindow, getPersistedLogLevel, getRoutingMode, isCache1hPersistentlyEnabled, isCacheKeepAlways, isCacheKeepHybridActive, isCacheKeepPersistentlyEnabled, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isPrimePersistentlyEnabled, nativeAccountCanServe, setDumpEnabled, } from '@cortexkit/anthropic-auth-core';
|
|
2
|
+
import { authorize, buildClaudeQuotaSummary, buildPrimeAccountStatuses, DEFAULT_KILLSWITCH_THRESHOLDS, exchange, executeCacheKeepCommand, executePrimeCommand, formatEnrollmentStatus, formatNativeAccountState, formatOAuthAccountTier, getCache1hPersistentMode, getCacheKeepWindow, getMaxSameAccountWait, getPersistedLogLevel, getRoutingMode, isCache1hPersistentlyEnabled, isCacheKeepAlways, isCacheKeepHybridActive, isCacheKeepPersistentlyEnabled, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isPrimePersistentlyEnabled, nativeAccountCanServe, setDumpEnabled, } from '@cortexkit/anthropic-auth-core';
|
|
3
3
|
import { createPiCustodyCommands } from './custody.js';
|
|
4
4
|
import { getPiNativeRuntime } from './native.js';
|
|
5
5
|
import { getPiAccountStoragePath } from './paths.js';
|
|
@@ -184,6 +184,11 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
|
|
|
184
184
|
case 'routing-mode':
|
|
185
185
|
await setSection('routing', { mode: request.values.mode });
|
|
186
186
|
return { ok: true, text: 'Native routing mode updated.' };
|
|
187
|
+
case 'routing-max-same-account-wait':
|
|
188
|
+
await setSection('routing', {
|
|
189
|
+
maxSameAccountWait: request.values.maxSameAccountWait,
|
|
190
|
+
});
|
|
191
|
+
return { ok: true, text: 'Longest wait on the same account updated.' };
|
|
187
192
|
case 'routing-reset':
|
|
188
193
|
await clearPiStickyRoutingSession(storagePath, request.sessionId);
|
|
189
194
|
return {
|
|
@@ -295,7 +300,7 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
|
|
|
295
300
|
})),
|
|
296
301
|
});
|
|
297
302
|
case 'routing':
|
|
298
|
-
return `Routing: ${getRoutingMode(storage)}`;
|
|
303
|
+
return `Routing: ${getRoutingMode(storage)}\nLongest wait on the same account: ${getMaxSameAccountWait(storage)}`;
|
|
299
304
|
case 'killswitch':
|
|
300
305
|
return `Killswitch: ${isKillswitchEnabled(storage) ? 'enabled' : 'disabled'}\n${JSON.stringify(storage.killswitch ?? {})}`;
|
|
301
306
|
case 'cache':
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export type PiQuotaWaitOptions = {
|
|
2
|
+
now?: () => number;
|
|
3
|
+
setTimeout?: typeof globalThis.setTimeout;
|
|
4
|
+
clearTimeout?: typeof globalThis.clearTimeout;
|
|
5
|
+
setWorkingMessage?: (message?: string) => void;
|
|
6
|
+
};
|
|
7
|
+
export type PiAccountHold = {
|
|
8
|
+
accountId: string;
|
|
9
|
+
accountIdentity?: string;
|
|
10
|
+
resetAt: number;
|
|
11
|
+
};
|
|
12
|
+
export declare function markPiAccountHold(response: Response, hold: PiAccountHold): Response;
|
|
13
|
+
/** Own one bounded wait inside a Pi stream, rather than asking Pi's text-based retry loop. */
|
|
14
|
+
export declare function withPiQuotaWait(input: {
|
|
15
|
+
run: () => Promise<Response>;
|
|
16
|
+
resume: (hold: PiAccountHold | undefined) => Promise<Response>;
|
|
17
|
+
signal?: AbortSignal;
|
|
18
|
+
wait?: PiQuotaWaitOptions;
|
|
19
|
+
}): Promise<Response>;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { createQuotaRefusalResponse, quotaRefusalDetails, } from '@cortexkit/anthropic-auth-core';
|
|
2
|
+
const holds = new WeakMap();
|
|
3
|
+
export function markPiAccountHold(response, hold) {
|
|
4
|
+
holds.set(response, hold);
|
|
5
|
+
return response;
|
|
6
|
+
}
|
|
7
|
+
async function waitForReset(delayMs, resetAt, signal, options) {
|
|
8
|
+
signal?.throwIfAborted();
|
|
9
|
+
const set = options.setTimeout ?? globalThis.setTimeout;
|
|
10
|
+
const clear = options.clearTimeout ?? globalThis.clearTimeout;
|
|
11
|
+
const when = resetAt ?? (options.now?.() ?? Date.now()) + delayMs;
|
|
12
|
+
const time = new Date(when).toLocaleTimeString(undefined, {
|
|
13
|
+
hour: '2-digit',
|
|
14
|
+
minute: '2-digit',
|
|
15
|
+
hour12: false,
|
|
16
|
+
});
|
|
17
|
+
try {
|
|
18
|
+
options.setWorkingMessage?.(`Waiting for the account to reset at ${time} · Esc to cancel`);
|
|
19
|
+
await new Promise((resolve, reject) => {
|
|
20
|
+
const abort = () => {
|
|
21
|
+
clear(timer);
|
|
22
|
+
reject(new DOMException('Aborted', 'AbortError'));
|
|
23
|
+
};
|
|
24
|
+
const timer = set(() => {
|
|
25
|
+
signal?.removeEventListener('abort', abort);
|
|
26
|
+
resolve();
|
|
27
|
+
}, delayMs);
|
|
28
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
29
|
+
if (signal?.aborted)
|
|
30
|
+
abort();
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
finally {
|
|
34
|
+
options.setWorkingMessage?.();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** Own one bounded wait inside a Pi stream, rather than asking Pi's text-based retry loop. */
|
|
38
|
+
export async function withPiQuotaWait(input) {
|
|
39
|
+
const response = await input.run();
|
|
40
|
+
const hold = holds.get(response);
|
|
41
|
+
const refusal = quotaRefusalDetails(response);
|
|
42
|
+
const delay = Number(response.headers.get('retry-after')) * 1000;
|
|
43
|
+
if ((!hold && !refusal) ||
|
|
44
|
+
!response.headers.has('retry-after') ||
|
|
45
|
+
!Number.isFinite(delay) ||
|
|
46
|
+
delay <= 0)
|
|
47
|
+
return response;
|
|
48
|
+
const options = input.wait ?? {};
|
|
49
|
+
void response.body?.cancel().catch(() => { });
|
|
50
|
+
input.signal?.throwIfAborted();
|
|
51
|
+
// An unknown reset's retry hint is not evidence that waiting can help this request.
|
|
52
|
+
if (!hold && refusal && refusal.timing.resetAt === undefined)
|
|
53
|
+
return createQuotaRefusalResponse(refusal.reason, {
|
|
54
|
+
resetAt: undefined,
|
|
55
|
+
retryAfterSeconds: undefined,
|
|
56
|
+
});
|
|
57
|
+
await waitForReset(delay, hold?.resetAt ?? refusal?.timing.resetAt, input.signal, options);
|
|
58
|
+
input.signal?.throwIfAborted();
|
|
59
|
+
let next;
|
|
60
|
+
try {
|
|
61
|
+
next = await input.resume(hold);
|
|
62
|
+
if (next.ok || next.status === 401)
|
|
63
|
+
return next;
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (input.signal?.aborted)
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
const latest = next && quotaRefusalDetails(next);
|
|
70
|
+
void next?.body?.cancel().catch(() => { });
|
|
71
|
+
// Do not leak a rate-limit code or retry guidance into Pi's final error classifier.
|
|
72
|
+
return createQuotaRefusalResponse(latest?.reason ??
|
|
73
|
+
refusal?.reason ??
|
|
74
|
+
'The selected OAuth account cannot serve this request. Open /claude to review account availability.', {
|
|
75
|
+
resetAt: latest?.timing.resetAt ?? refusal?.timing.resetAt ?? hold?.resetAt,
|
|
76
|
+
retryAfterSeconds: undefined,
|
|
77
|
+
}, options.now?.() ?? Date.now());
|
|
78
|
+
}
|
package/dist/stream.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type ApiKeyAccount, CacheKeepManager, type MidConversationEffortTransition, type NativeAccountView, type QuotaManagerOptions } from '@cortexkit/anthropic-auth-core';
|
|
2
|
-
import { type Api, type AssistantMessageEventStream, type Context, type Model, type SimpleStreamOptions
|
|
2
|
+
import { type Api, type AssistantMessageEventStream, type Context, type Model, type SimpleStreamOptions } from '@earendil-works/pi-ai';
|
|
3
|
+
import { type PiQuotaWaitOptions } from './quota-wait.ts';
|
|
3
4
|
/** Set or clear the test replacement for the wait between quota usage polls. */
|
|
4
5
|
export declare function __setPiQuotaCallPauseForTest(pause: QuotaManagerOptions['pauseBetweenQuotaCalls']): void;
|
|
5
6
|
export declare function clearPiStickyRoutingSession(storagePath: string, sessionId: string): Promise<void>;
|
|
@@ -27,9 +28,10 @@ declare function sendAnthropicRequest(options: {
|
|
|
27
28
|
apiAccount?: NativeAccountView;
|
|
28
29
|
storagePath: string;
|
|
29
30
|
oauthAccountId?: string;
|
|
31
|
+
expectedAccountIdentity?: string;
|
|
30
32
|
route?: string;
|
|
31
33
|
effortTransitions?: readonly MidConversationEffortTransition[];
|
|
32
|
-
|
|
34
|
+
onResolvedToolNames?: (toolNames: ReadonlyMap<string, string>) => void;
|
|
33
35
|
}, deps?: {
|
|
34
36
|
fetch?: typeof fetch;
|
|
35
37
|
cacheKeep?: CacheKeepManager;
|
|
@@ -50,5 +52,5 @@ export declare function firstStreamingError(response: Response): Promise<{
|
|
|
50
52
|
response: Response;
|
|
51
53
|
preflight: Response | 'rate_limit_error';
|
|
52
54
|
}>;
|
|
53
|
-
export declare function streamCortexKitAnthropic(model: Model<Api>, context: Context, options?: SimpleStreamOptions, effortTransitions?: readonly MidConversationEffortTransition[]): AssistantMessageEventStream;
|
|
55
|
+
export declare function streamCortexKitAnthropic(model: Model<Api>, context: Context, options?: SimpleStreamOptions, effortTransitions?: readonly MidConversationEffortTransition[], wait?: PiQuotaWaitOptions): AssistantMessageEventStream;
|
|
54
56
|
export {};
|
package/dist/stream.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { applyClaudeCodeHeaders, applyCustomHeaders, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepManager, CacheKeepSessionRegistry, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createSseFramer, createStickyNoRouteResponse, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, FAST_MODE_BETA, getCache1hPersistentMode, getClaudeCodeIdentityForVerifiedAccount, getDefaultCacheKeepRegistryDirectory, getFallbackReauthLabels, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, isCache1hPersistentlyEnabled, isCacheKeepHybridActive, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isNativeTransientAccountError, isOAuthAccount, isPermanentRefreshError, isValidApiBaseURL, killswitchPassesPolicy, logger, mergeAnthropicBetas, NativeAccountRefusal, nativeAccountCanServe, parseSseFrame, QuotaManager, quotaBackoffActive, quotaExhaustionFromHeaders, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickySessionRouter, sendViaRelay, sendWithRequestGzip, 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, 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';
|
|
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
|
+
import { markPiAccountHold, withPiQuotaWait, } from './quota-wait.js';
|
|
6
7
|
import { buildPiOAuthMessagesUrl, fetchPiOAuth, requirePiOAuthOrigin, } from './transport.js';
|
|
7
8
|
/** Dump label for a physical send that failed before any response arrived. */
|
|
8
9
|
const PHYSICAL_SEND_FAILED = 'physical send failed before a response';
|
|
@@ -123,6 +124,7 @@ async function getPiStickyRouter(storagePath) {
|
|
|
123
124
|
return router;
|
|
124
125
|
}
|
|
125
126
|
export async function clearPiStickyRoutingSession(storagePath, sessionId) {
|
|
127
|
+
sessionCacheActivity.forget(sessionId);
|
|
126
128
|
await (await getPiStickyRouter(storagePath)).clear(sessionId);
|
|
127
129
|
}
|
|
128
130
|
function getPiCacheKeepRegistry() {
|
|
@@ -203,8 +205,14 @@ const cacheKeepManager = new CacheKeepManager({
|
|
|
203
205
|
});
|
|
204
206
|
return rotatedHeaders;
|
|
205
207
|
},
|
|
206
|
-
onResponse: async ({ attempt, status }) => {
|
|
208
|
+
onResponse: async ({ target, attempt, status, receivedAt }) => {
|
|
207
209
|
const entry = nativePrewarmAttempts.get(attempt.id);
|
|
210
|
+
if (entry &&
|
|
211
|
+
status >= 200 &&
|
|
212
|
+
status < 300 &&
|
|
213
|
+
!attempt.signal?.aborted &&
|
|
214
|
+
!target.sourceWarm)
|
|
215
|
+
sessionCacheActivity.recordPrewarm(target.id, target.oauthAccountId ?? STICKY_ROUTING_MAIN_ACCOUNT_ID, receivedAt);
|
|
208
216
|
if (entry && status === 401 && !entry.reported)
|
|
209
217
|
await entry.runtime.report(entry.served, status, 'direct').catch(() => {
|
|
210
218
|
logger.warn('native-auth', 'Pi CacheKeep auth-failure report unavailable');
|
|
@@ -348,6 +356,9 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
348
356
|
const routeId = options.oauthAccountId ?? STICKY_ROUTING_MAIN_ACCOUNT_ID;
|
|
349
357
|
const selected = snapshot.accounts.find((account) => account.id === routeId);
|
|
350
358
|
let verifiedUuid = options.apiAccount ? undefined : selected?.accountIdentity;
|
|
359
|
+
if (options.expectedAccountIdentity &&
|
|
360
|
+
verifiedUuid !== options.expectedAccountIdentity)
|
|
361
|
+
throw new Error('The selected OAuth account changed while waiting.');
|
|
351
362
|
if (!options.apiAccount && !verifiedUuid) {
|
|
352
363
|
if (selected?.source === 'vault')
|
|
353
364
|
throw new Error('Pi vault route identity is unasserted');
|
|
@@ -361,8 +372,14 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
361
372
|
? (storage.mainAccountId ?? routeId)
|
|
362
373
|
: routeId, verifiedUuid)
|
|
363
374
|
: undefined;
|
|
364
|
-
|
|
365
|
-
|
|
375
|
+
// Pi's per-request `cacheRetention: 'long'` asks for the provider's longest
|
|
376
|
+
// retention (Anthropic's one-hour TTL), as Pi's own Anthropic provider
|
|
377
|
+
// honours it; the account setting still enables it for all requests. Cache
|
|
378
|
+
// activity below follows the final serialized body, since hooks can edit TTLs.
|
|
379
|
+
const oneHourCache = isCache1hPersistentlyEnabled(storage) ||
|
|
380
|
+
options.streamOptions?.cacheRetention === 'long';
|
|
381
|
+
const { body, bodyText, toolNames, cacheTtlMs } = await buildAnthropicRequest(options.model.id, options.context, options.streamOptions, {
|
|
382
|
+
enabled: oneHourCache,
|
|
366
383
|
mode: getCache1hPersistentMode(storage),
|
|
367
384
|
}, isFastModePersistentlyEnabled(storage), identity, {
|
|
368
385
|
effortTransitions: options.apiAccount ? [] : options.effortTransitions,
|
|
@@ -370,8 +387,11 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
370
387
|
thinkingPrefixMismatchBehavior: options.apiAccount
|
|
371
388
|
? 'account-default'
|
|
372
389
|
: getThinkingPrefixMismatchBehavior(storage),
|
|
390
|
+
...(options.streamOptions?.onPayload && {
|
|
391
|
+
onPayload: (payload) => options.streamOptions?.onPayload?.(payload, options.model),
|
|
392
|
+
}),
|
|
373
393
|
});
|
|
374
|
-
options.
|
|
394
|
+
options.onResolvedToolNames?.(toolNames);
|
|
375
395
|
const fastMode = body.speed === 'fast';
|
|
376
396
|
const headers = options.apiAccount
|
|
377
397
|
? new Headers()
|
|
@@ -390,6 +410,8 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
390
410
|
const trackAcceptedRequest = () => {
|
|
391
411
|
if (options.apiAccount || init.signal?.aborted)
|
|
392
412
|
return;
|
|
413
|
+
if (relayAffinity)
|
|
414
|
+
sessionCacheActivity.record(relayAffinity, routeId, cacheTtlMs);
|
|
393
415
|
keep.track({
|
|
394
416
|
sessionId: relayAffinity,
|
|
395
417
|
url: input.toString(),
|
|
@@ -852,8 +874,12 @@ async function executeWithFallback(options) {
|
|
|
852
874
|
if (isPermanentRefreshError(refreshError))
|
|
853
875
|
return [];
|
|
854
876
|
if (stickyQuotaSnapshotIsFresh(route.quota, storage, Date.now(), modelId) &&
|
|
855
|
-
decideStickyQuotaFailure({
|
|
856
|
-
|
|
877
|
+
decideStickyQuotaFailure({
|
|
878
|
+
quota: route.quota,
|
|
879
|
+
modelId,
|
|
880
|
+
sessionId: options.streamOptions?.sessionId,
|
|
881
|
+
holdUntil: sessionCacheActivity.holdUntil(options.streamOptions?.sessionId, route.id, Date.now(), getMaxSameAccountWait(storage)),
|
|
882
|
+
}).action === 'migrate') {
|
|
857
883
|
return [];
|
|
858
884
|
}
|
|
859
885
|
if (isKillswitchEnabled(storage) &&
|
|
@@ -1021,11 +1047,20 @@ async function executeWithFallback(options) {
|
|
|
1021
1047
|
snapshot: await native.view(),
|
|
1022
1048
|
modelId: options.model.id,
|
|
1023
1049
|
sticky: true,
|
|
1050
|
+
sessionId,
|
|
1024
1051
|
});
|
|
1025
1052
|
return createStickyNoRouteResponse({
|
|
1026
1053
|
mainRefreshError: storage?.refresh?.mainLastRefreshError,
|
|
1027
1054
|
fallbackReauthLabels: getFallbackReauthLabels(storage),
|
|
1028
1055
|
routeQuotas: routes.allRoutes.flatMap((route) => route.quota ? [route.quota] : []),
|
|
1056
|
+
routeIdentities: routes.allRoutes
|
|
1057
|
+
.filter((route) => route.quota)
|
|
1058
|
+
.map((route) => accountView(route.id)?.accountIdentity),
|
|
1059
|
+
routeAccountIds: routes.allRoutes
|
|
1060
|
+
.filter((route) => route.quota)
|
|
1061
|
+
.map((route) => route.id),
|
|
1062
|
+
storage,
|
|
1063
|
+
sessionId,
|
|
1029
1064
|
modelId: options.model.id,
|
|
1030
1065
|
});
|
|
1031
1066
|
}
|
|
@@ -1037,27 +1072,34 @@ async function executeWithFallback(options) {
|
|
|
1037
1072
|
route: `sticky:${selected.id}`,
|
|
1038
1073
|
});
|
|
1039
1074
|
const completeRoute = async (_selected, response, _markUsed = true) => response;
|
|
1075
|
+
const heldAccountId = route.id;
|
|
1076
|
+
const heldAccountIdentity = accountView(route.id)?.accountIdentity;
|
|
1077
|
+
const holdResponse = (retryAfterSeconds, upstream) => {
|
|
1078
|
+
const headers = new Headers(upstream);
|
|
1079
|
+
headers.set('content-type', 'application/json');
|
|
1080
|
+
headers.set('retry-after', String(stickyRetryAfterWithJitter(sessionId, retryAfterSeconds)));
|
|
1081
|
+
return markPiAccountHold(new Response(JSON.stringify({
|
|
1082
|
+
type: 'error',
|
|
1083
|
+
error: {
|
|
1084
|
+
type: 'rate_limit_error',
|
|
1085
|
+
message: 'Sticky OAuth account quota resets shortly; retaining session affinity.',
|
|
1086
|
+
},
|
|
1087
|
+
}), { status: 429, headers }), {
|
|
1088
|
+
accountId: heldAccountId,
|
|
1089
|
+
accountIdentity: heldAccountIdentity,
|
|
1090
|
+
resetAt: Date.now() + retryAfterSeconds * 1000,
|
|
1091
|
+
});
|
|
1092
|
+
};
|
|
1040
1093
|
const proactiveQuotaDecision = stickyQuotaSnapshotIsFresh(route.quota, storage, Date.now(), options.model.id)
|
|
1041
1094
|
? decideStickyQuotaFailure({
|
|
1042
1095
|
quota: route.quota,
|
|
1043
1096
|
modelId: options.model.id,
|
|
1097
|
+
sessionId,
|
|
1098
|
+
holdUntil: sessionCacheActivity.holdUntil(sessionId, route.id, Date.now(), getMaxSameAccountWait(storage)),
|
|
1044
1099
|
})
|
|
1045
1100
|
: undefined;
|
|
1046
|
-
if (proactiveQuotaDecision?.action === 'hold')
|
|
1047
|
-
return
|
|
1048
|
-
type: 'error',
|
|
1049
|
-
error: {
|
|
1050
|
-
type: 'rate_limit_error',
|
|
1051
|
-
message: 'Sticky OAuth account quota resets shortly; retaining session affinity.',
|
|
1052
|
-
},
|
|
1053
|
-
}), {
|
|
1054
|
-
status: 429,
|
|
1055
|
-
headers: {
|
|
1056
|
-
'content-type': 'application/json',
|
|
1057
|
-
'retry-after': String(stickyRetryAfterWithJitter(sessionId, proactiveQuotaDecision.retryAfterSeconds)),
|
|
1058
|
-
},
|
|
1059
|
-
}), false);
|
|
1060
|
-
}
|
|
1101
|
+
if (proactiveQuotaDecision?.action === 'hold')
|
|
1102
|
+
return holdResponse(proactiveQuotaDecision.retryAfterSeconds);
|
|
1061
1103
|
const { response, preflight } = await firstStreamingError(await sendRoute(route));
|
|
1062
1104
|
if (preflight instanceof Response && preflight.ok) {
|
|
1063
1105
|
return completeRoute(route, preflight);
|
|
@@ -1086,28 +1128,12 @@ async function executeWithFallback(options) {
|
|
|
1086
1128
|
quota,
|
|
1087
1129
|
modelId: options.model.id,
|
|
1088
1130
|
responseHeaders,
|
|
1131
|
+
sessionId,
|
|
1132
|
+
holdUntil: sessionCacheActivity.holdUntil(sessionId, route.id, Date.now(), getMaxSameAccountWait(storage)),
|
|
1089
1133
|
});
|
|
1090
1134
|
if (decision.action === 'hold') {
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
: response.headers);
|
|
1094
|
-
headers.set('retry-after', String(stickyRetryAfterWithJitter(sessionId, decision.retryAfterSeconds)));
|
|
1095
|
-
if (preflight instanceof Response) {
|
|
1096
|
-
return completeRoute(route, new Response(preflight.body, {
|
|
1097
|
-
status: preflight.status,
|
|
1098
|
-
statusText: preflight.statusText,
|
|
1099
|
-
headers,
|
|
1100
|
-
}));
|
|
1101
|
-
}
|
|
1102
|
-
await response.body?.cancel().catch(() => { });
|
|
1103
|
-
headers.set('content-type', 'application/json');
|
|
1104
|
-
return completeRoute(route, new Response(JSON.stringify({
|
|
1105
|
-
type: 'error',
|
|
1106
|
-
error: {
|
|
1107
|
-
type: 'rate_limit_error',
|
|
1108
|
-
message: 'Sticky OAuth account quota resets shortly; retaining session affinity.',
|
|
1109
|
-
},
|
|
1110
|
-
}), { status: 429, headers }));
|
|
1135
|
+
void response.body?.cancel().catch(() => { });
|
|
1136
|
+
return holdResponse(decision.retryAfterSeconds, responseHeaders);
|
|
1111
1137
|
}
|
|
1112
1138
|
migrate = decision.action === 'migrate';
|
|
1113
1139
|
}
|
|
@@ -1182,11 +1208,22 @@ async function executeWithFallback(options) {
|
|
|
1182
1208
|
return createNativeVaultNoRouteResponse({
|
|
1183
1209
|
snapshot: await native.view(),
|
|
1184
1210
|
modelId: options.model.id,
|
|
1211
|
+
sessionId: options.streamOptions?.sessionId,
|
|
1185
1212
|
});
|
|
1186
1213
|
return createStickyNoRouteResponse({
|
|
1187
1214
|
routeQuotas: (storage?.accounts ?? [])
|
|
1188
1215
|
.filter(isOAuthAccount)
|
|
1189
1216
|
.flatMap((account) => (account.quota ? [account.quota] : [])),
|
|
1217
|
+
routeIdentities: (storage?.accounts ?? [])
|
|
1218
|
+
.filter(isOAuthAccount)
|
|
1219
|
+
.filter((account) => account.quota)
|
|
1220
|
+
.map((account) => accountView(account.id)?.accountIdentity),
|
|
1221
|
+
routeAccountIds: (storage?.accounts ?? [])
|
|
1222
|
+
.filter(isOAuthAccount)
|
|
1223
|
+
.filter((account) => account.quota)
|
|
1224
|
+
.map((account) => account.id),
|
|
1225
|
+
storage,
|
|
1226
|
+
sessionId: options.streamOptions?.sessionId,
|
|
1190
1227
|
modelId: options.model.id,
|
|
1191
1228
|
});
|
|
1192
1229
|
}
|
|
@@ -1204,19 +1241,19 @@ async function executeWithFallback(options) {
|
|
|
1204
1241
|
if (fallback)
|
|
1205
1242
|
return fallback;
|
|
1206
1243
|
}
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
type
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
});
|
|
1244
|
+
const current = await native.view();
|
|
1245
|
+
return createQuotaRefusalResponse('Killswitch blocked all OAuth routes', quotaRefusalTiming({
|
|
1246
|
+
readings: current.accounts
|
|
1247
|
+
.filter((account) => account.type === 'oauth' && nativeAccountCanServe(account))
|
|
1248
|
+
.map((account) => ({
|
|
1249
|
+
quota: account.quota,
|
|
1250
|
+
accountIdentity: account.accountIdentity,
|
|
1251
|
+
accountId: account.id,
|
|
1252
|
+
})),
|
|
1253
|
+
storage: current.policyStorage,
|
|
1254
|
+
modelId: options.model.id,
|
|
1255
|
+
sessionTtlMs: sessionCacheActivity.ttlMs(options.streamOptions?.sessionId),
|
|
1256
|
+
}));
|
|
1220
1257
|
}
|
|
1221
1258
|
}
|
|
1222
1259
|
const { response: primary, preflight: primaryPreflight } = await firstStreamingError(await sendAnthropicRequest({
|
|
@@ -1244,7 +1281,7 @@ async function executeWithFallback(options) {
|
|
|
1244
1281
|
}
|
|
1245
1282
|
return primaryPreflight instanceof Response ? primaryPreflight : primary;
|
|
1246
1283
|
}
|
|
1247
|
-
export function streamCortexKitAnthropic(model, context, options, effortTransitions) {
|
|
1284
|
+
export function streamCortexKitAnthropic(model, context, options, effortTransitions, wait) {
|
|
1248
1285
|
const stream = createAssistantMessageEventStream();
|
|
1249
1286
|
void (async () => {
|
|
1250
1287
|
const output = createOutput(model);
|
|
@@ -1252,15 +1289,63 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1252
1289
|
try {
|
|
1253
1290
|
buildPiOAuthMessagesUrl(model.baseUrl);
|
|
1254
1291
|
const storagePath = getPiAccountStoragePath();
|
|
1255
|
-
let
|
|
1256
|
-
const
|
|
1292
|
+
let toolNames = new Map();
|
|
1293
|
+
const request = {
|
|
1257
1294
|
model,
|
|
1258
1295
|
context,
|
|
1259
1296
|
streamOptions: options,
|
|
1260
1297
|
storagePath,
|
|
1261
1298
|
effortTransitions,
|
|
1262
|
-
|
|
1263
|
-
|
|
1299
|
+
onResolvedToolNames: (names) => {
|
|
1300
|
+
toolNames = names;
|
|
1301
|
+
},
|
|
1302
|
+
};
|
|
1303
|
+
const response = await runWithRequestSignal(options?.signal, () => withPiQuotaWait({
|
|
1304
|
+
signal: options?.signal,
|
|
1305
|
+
wait,
|
|
1306
|
+
run: () => executeWithFallback(request),
|
|
1307
|
+
resume: async (hold) => {
|
|
1308
|
+
const native = getPiNativeRuntime(storagePath);
|
|
1309
|
+
const before = await native.requestView(options?.signal);
|
|
1310
|
+
if (hold &&
|
|
1311
|
+
(!hold.accountIdentity ||
|
|
1312
|
+
before.accounts.find((account) => account.id === hold.accountId)
|
|
1313
|
+
?.accountIdentity !== hold.accountIdentity))
|
|
1314
|
+
throw new Error('The selected OAuth account changed while waiting.');
|
|
1315
|
+
const runtime = await native.service();
|
|
1316
|
+
let heldStillBlocked = false;
|
|
1317
|
+
for (const account of before.accounts) {
|
|
1318
|
+
if (account.type !== 'oauth' ||
|
|
1319
|
+
!nativeAccountCanServe(account) ||
|
|
1320
|
+
(hold && account.id !== hold.accountId))
|
|
1321
|
+
continue;
|
|
1322
|
+
options?.signal?.throwIfAborted();
|
|
1323
|
+
try {
|
|
1324
|
+
const quota = await runtime.fetchQuota(account.id, fetchPiOAuth, options?.signal, undefined, 'admission');
|
|
1325
|
+
if (hold &&
|
|
1326
|
+
decideStickyQuotaFailure({ quota, modelId: model.id })
|
|
1327
|
+
.action === 'migrate')
|
|
1328
|
+
heldStillBlocked = true;
|
|
1329
|
+
}
|
|
1330
|
+
catch (error) {
|
|
1331
|
+
if (options?.signal?.aborted)
|
|
1332
|
+
throw error;
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
options?.signal?.throwIfAborted();
|
|
1336
|
+
if (heldStillBlocked)
|
|
1337
|
+
throw new Error('The selected OAuth account cannot serve this request.');
|
|
1338
|
+
if (!hold)
|
|
1339
|
+
return executeWithFallback(request);
|
|
1340
|
+
const inspected = await firstStreamingError(await sendAnthropicRequest({
|
|
1341
|
+
...request,
|
|
1342
|
+
oauthAccountId: hold.accountId,
|
|
1343
|
+
expectedAccountIdentity: hold.accountIdentity,
|
|
1344
|
+
}));
|
|
1345
|
+
if (inspected.preflight instanceof Response)
|
|
1346
|
+
return inspected.preflight;
|
|
1347
|
+
void inspected.response.body?.cancel().catch(() => { });
|
|
1348
|
+
return new Response(null, { status: 429 });
|
|
1264
1349
|
},
|
|
1265
1350
|
}));
|
|
1266
1351
|
if (!response.ok) {
|
|
@@ -1316,7 +1401,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1316
1401
|
output.content.push({
|
|
1317
1402
|
type: 'toolCall',
|
|
1318
1403
|
id: String(block.id),
|
|
1319
|
-
name: fromClaudeCodeToolName(String(block.name),
|
|
1404
|
+
name: fromClaudeCodeToolName(String(block.name), toolNames),
|
|
1320
1405
|
arguments: {},
|
|
1321
1406
|
partialJson: '',
|
|
1322
1407
|
index: event.index,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/pi-anthropic-auth",
|
|
3
|
-
"version": "2.4.
|
|
3
|
+
"version": "2.4.13",
|
|
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.4.
|
|
39
|
+
"@cortexkit/anthropic-auth-core": "2.4.13"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"@earendil-works/pi-ai": ">=0.86.1 <2",
|