@cortexkit/pi-anthropic-auth 2.4.11 → 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 CHANGED
@@ -26,7 +26,20 @@ export type AnthropicRequestBody = {
26
26
  };
27
27
  speed?: 'fast';
28
28
  };
29
- export declare function fromClaudeCodeToolName(name: string, tools?: Tool[]): string;
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
- hostTools: Tool[];
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
- export function fromClaudeCodeToolName(name, tools) {
51
- const lower = name.toLowerCase();
52
- return tools?.find((tool) => tool.name.toLowerCase() === lower)?.name ?? name;
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(message.content),
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
- const body = {
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
- // The stream decoder must use the exact tool set that produced this body.
596
- // Pi 0.86's transcript has no top-level context.tools, and normalizing it
597
- // again after dispatch would duplicate work and risk a different mapping.
598
- return { body, bodyText, hostTools: context.tools ?? [] };
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;
@@ -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
- import { type ApiKeyAccount, CacheKeepManager, type MidConversationEffortTransition, type QuotaManagerOptions } from '@cortexkit/anthropic-auth-core';
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
+ 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>;
@@ -20,6 +21,23 @@ type AnthropicEvent = {
20
21
  export declare function buildExplicitBaseMessagesUrl(baseURL: string): URL;
21
22
  export declare function configureApiRouteHeaders(account: ApiKeyAccount, fastMode: boolean): Headers;
22
23
  export declare function parseSse(response: Response): AsyncGenerator<AnthropicEvent>;
24
+ declare function sendAnthropicRequest(options: {
25
+ model: Model<Api>;
26
+ context: Context;
27
+ streamOptions?: SimpleStreamOptions;
28
+ apiAccount?: NativeAccountView;
29
+ storagePath: string;
30
+ oauthAccountId?: string;
31
+ expectedAccountIdentity?: string;
32
+ route?: string;
33
+ effortTransitions?: readonly MidConversationEffortTransition[];
34
+ onResolvedToolNames?: (toolNames: ReadonlyMap<string, string>) => void;
35
+ }, deps?: {
36
+ fetch?: typeof fetch;
37
+ cacheKeep?: CacheKeepManager;
38
+ }): Promise<Response>;
39
+ /** Exercise one native send with isolated transport and scheduling in tests. */
40
+ export declare const __sendPiAnthropicRequestForTest: typeof sendAnthropicRequest;
23
41
  export declare function primaryResponseAllowsApiFallback(preflight: Response | string): boolean;
24
42
  /**
25
43
  * Classify a successful stream by its first event without a tee: the bytes
@@ -34,5 +52,5 @@ export declare function firstStreamingError(response: Response): Promise<{
34
52
  response: Response;
35
53
  preflight: Response | 'rate_limit_error';
36
54
  }>;
37
- 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;
38
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');
@@ -335,7 +343,9 @@ export async function* parseSse(response) {
335
343
  reader.releaseLock();
336
344
  }
337
345
  }
338
- async function sendAnthropicRequest(options) {
346
+ async function sendAnthropicRequest(options, deps = {}) {
347
+ const fetchImpl = deps.fetch ?? globalThis.fetch;
348
+ const keep = deps.cacheKeep ?? cacheKeepManager;
339
349
  const native = getPiNativeRuntime(options.storagePath);
340
350
  // Capture the serving service while authorization is open. Shutdown rejects
341
351
  // new serving work immediately but drains writes for already-served attempts.
@@ -346,6 +356,9 @@ async function sendAnthropicRequest(options) {
346
356
  const routeId = options.oauthAccountId ?? STICKY_ROUTING_MAIN_ACCOUNT_ID;
347
357
  const selected = snapshot.accounts.find((account) => account.id === routeId);
348
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.');
349
362
  if (!options.apiAccount && !verifiedUuid) {
350
363
  if (selected?.source === 'vault')
351
364
  throw new Error('Pi vault route identity is unasserted');
@@ -359,8 +372,14 @@ async function sendAnthropicRequest(options) {
359
372
  ? (storage.mainAccountId ?? routeId)
360
373
  : routeId, verifiedUuid)
361
374
  : undefined;
362
- const { body, bodyText, hostTools } = await buildAnthropicRequest(options.model.id, options.context, options.streamOptions, {
363
- enabled: isCache1hPersistentlyEnabled(storage),
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,
364
383
  mode: getCache1hPersistentMode(storage),
365
384
  }, isFastModePersistentlyEnabled(storage), identity, {
366
385
  effortTransitions: options.apiAccount ? [] : options.effortTransitions,
@@ -368,8 +387,11 @@ async function sendAnthropicRequest(options) {
368
387
  thinkingPrefixMismatchBehavior: options.apiAccount
369
388
  ? 'account-default'
370
389
  : getThinkingPrefixMismatchBehavior(storage),
390
+ ...(options.streamOptions?.onPayload && {
391
+ onPayload: (payload) => options.streamOptions?.onPayload?.(payload, options.model),
392
+ }),
371
393
  });
372
- options.onResolvedTools?.(hostTools);
394
+ options.onResolvedToolNames?.(toolNames);
373
395
  const fastMode = body.speed === 'fast';
374
396
  const headers = options.apiAccount
375
397
  ? new Headers()
@@ -385,8 +407,12 @@ async function sendAnthropicRequest(options) {
385
407
  signal: options.streamOptions?.signal,
386
408
  ...(!options.apiAccount && { redirect: 'error' }),
387
409
  };
388
- if (!options.apiAccount)
389
- await cacheKeepManager.track({
410
+ const trackAcceptedRequest = () => {
411
+ if (options.apiAccount || init.signal?.aborted)
412
+ return;
413
+ if (relayAffinity)
414
+ sessionCacheActivity.record(relayAffinity, routeId, cacheTtlMs);
415
+ keep.track({
390
416
  sessionId: relayAffinity,
391
417
  url: input.toString(),
392
418
  headers,
@@ -397,6 +423,7 @@ async function sendAnthropicRequest(options) {
397
423
  oauthAccountIdentity: verifiedUuid,
398
424
  accountStoragePath: options.storagePath,
399
425
  });
426
+ };
400
427
  const reported = new Set();
401
428
  let retried401 = false;
402
429
  let lastTransport;
@@ -455,13 +482,13 @@ async function sendAnthropicRequest(options) {
455
482
  // OAuth bodies go gzipped as Claude Code sends them; `bodyText` stays
456
483
  // the signed identity text for dumps and CacheKeep.
457
484
  if (options.apiAccount || typeof init.body !== 'string')
458
- return scope.redactResponse(await fetch(input, init));
485
+ return scope.redactResponse(await fetchImpl(input, init));
459
486
  return scope.redactResponse(await sendWithRequestGzip({
460
487
  url: input,
461
488
  body: init.body,
462
489
  headers,
463
490
  latch: getRequestGzipLatch(getRequestGzipLatchPath(options.storagePath)),
464
- send: (wireBody, wireHeaders) => fetch(input, { ...init, body: wireBody, headers: wireHeaders }),
491
+ send: (wireBody, wireHeaders) => fetchImpl(input, { ...init, body: wireBody, headers: wireHeaders }),
465
492
  }));
466
493
  };
467
494
  let response;
@@ -537,8 +564,10 @@ async function sendAnthropicRequest(options) {
537
564
  const subject = apiSubject;
538
565
  native.usagePublications.publish(() => servingRuntime.publishApi(subject, { lastUsed: Date.now() }));
539
566
  }
540
- if (attempt && response.ok)
567
+ if (attempt && response.ok) {
568
+ trackAcceptedRequest();
541
569
  markServed(attempt);
570
+ }
542
571
  return response;
543
572
  };
544
573
  if (options.apiAccount)
@@ -601,10 +630,14 @@ async function sendAnthropicRequest(options) {
601
630
  // If the request was cancelled since, end it as cancelled here.
602
631
  if (relay401Attempt && response.status === 401)
603
632
  await endIfCancelled(response, init.signal);
604
- if (response.ok && lastTransport === 'relay' && relayAttempt)
633
+ if (response.ok && lastTransport === 'relay' && relayAttempt) {
634
+ trackAcceptedRequest();
605
635
  markServed(relayAttempt);
636
+ }
606
637
  return response;
607
638
  }
639
+ /** Exercise one native send with isolated transport and scheduling in tests. */
640
+ export const __sendPiAnthropicRequestForTest = sendAnthropicRequest;
608
641
  /**
609
642
  * If the request's signal is aborted, cancels the response body and throws the
610
643
  * signal's abort error; otherwise does nothing. Call it before a rejected
@@ -841,8 +874,12 @@ async function executeWithFallback(options) {
841
874
  if (isPermanentRefreshError(refreshError))
842
875
  return [];
843
876
  if (stickyQuotaSnapshotIsFresh(route.quota, storage, Date.now(), modelId) &&
844
- decideStickyQuotaFailure({ quota: route.quota, modelId }).action ===
845
- 'migrate') {
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') {
846
883
  return [];
847
884
  }
848
885
  if (isKillswitchEnabled(storage) &&
@@ -1010,11 +1047,20 @@ async function executeWithFallback(options) {
1010
1047
  snapshot: await native.view(),
1011
1048
  modelId: options.model.id,
1012
1049
  sticky: true,
1050
+ sessionId,
1013
1051
  });
1014
1052
  return createStickyNoRouteResponse({
1015
1053
  mainRefreshError: storage?.refresh?.mainLastRefreshError,
1016
1054
  fallbackReauthLabels: getFallbackReauthLabels(storage),
1017
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,
1018
1064
  modelId: options.model.id,
1019
1065
  });
1020
1066
  }
@@ -1026,27 +1072,34 @@ async function executeWithFallback(options) {
1026
1072
  route: `sticky:${selected.id}`,
1027
1073
  });
1028
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
+ };
1029
1093
  const proactiveQuotaDecision = stickyQuotaSnapshotIsFresh(route.quota, storage, Date.now(), options.model.id)
1030
1094
  ? decideStickyQuotaFailure({
1031
1095
  quota: route.quota,
1032
1096
  modelId: options.model.id,
1097
+ sessionId,
1098
+ holdUntil: sessionCacheActivity.holdUntil(sessionId, route.id, Date.now(), getMaxSameAccountWait(storage)),
1033
1099
  })
1034
1100
  : undefined;
1035
- if (proactiveQuotaDecision?.action === 'hold') {
1036
- return completeRoute(route, new Response(JSON.stringify({
1037
- type: 'error',
1038
- error: {
1039
- type: 'rate_limit_error',
1040
- message: 'Sticky OAuth account quota resets shortly; retaining session affinity.',
1041
- },
1042
- }), {
1043
- status: 429,
1044
- headers: {
1045
- 'content-type': 'application/json',
1046
- 'retry-after': String(stickyRetryAfterWithJitter(sessionId, proactiveQuotaDecision.retryAfterSeconds)),
1047
- },
1048
- }), false);
1049
- }
1101
+ if (proactiveQuotaDecision?.action === 'hold')
1102
+ return holdResponse(proactiveQuotaDecision.retryAfterSeconds);
1050
1103
  const { response, preflight } = await firstStreamingError(await sendRoute(route));
1051
1104
  if (preflight instanceof Response && preflight.ok) {
1052
1105
  return completeRoute(route, preflight);
@@ -1075,28 +1128,12 @@ async function executeWithFallback(options) {
1075
1128
  quota,
1076
1129
  modelId: options.model.id,
1077
1130
  responseHeaders,
1131
+ sessionId,
1132
+ holdUntil: sessionCacheActivity.holdUntil(sessionId, route.id, Date.now(), getMaxSameAccountWait(storage)),
1078
1133
  });
1079
1134
  if (decision.action === 'hold') {
1080
- const headers = new Headers(preflight instanceof Response
1081
- ? preflight.headers
1082
- : response.headers);
1083
- headers.set('retry-after', String(stickyRetryAfterWithJitter(sessionId, decision.retryAfterSeconds)));
1084
- if (preflight instanceof Response) {
1085
- return completeRoute(route, new Response(preflight.body, {
1086
- status: preflight.status,
1087
- statusText: preflight.statusText,
1088
- headers,
1089
- }));
1090
- }
1091
- await response.body?.cancel().catch(() => { });
1092
- headers.set('content-type', 'application/json');
1093
- return completeRoute(route, new Response(JSON.stringify({
1094
- type: 'error',
1095
- error: {
1096
- type: 'rate_limit_error',
1097
- message: 'Sticky OAuth account quota resets shortly; retaining session affinity.',
1098
- },
1099
- }), { status: 429, headers }));
1135
+ void response.body?.cancel().catch(() => { });
1136
+ return holdResponse(decision.retryAfterSeconds, responseHeaders);
1100
1137
  }
1101
1138
  migrate = decision.action === 'migrate';
1102
1139
  }
@@ -1171,11 +1208,22 @@ async function executeWithFallback(options) {
1171
1208
  return createNativeVaultNoRouteResponse({
1172
1209
  snapshot: await native.view(),
1173
1210
  modelId: options.model.id,
1211
+ sessionId: options.streamOptions?.sessionId,
1174
1212
  });
1175
1213
  return createStickyNoRouteResponse({
1176
1214
  routeQuotas: (storage?.accounts ?? [])
1177
1215
  .filter(isOAuthAccount)
1178
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,
1179
1227
  modelId: options.model.id,
1180
1228
  });
1181
1229
  }
@@ -1193,19 +1241,19 @@ async function executeWithFallback(options) {
1193
1241
  if (fallback)
1194
1242
  return fallback;
1195
1243
  }
1196
- return new Response(JSON.stringify({
1197
- type: 'error',
1198
- error: {
1199
- type: 'rate_limit_error',
1200
- message: 'Killswitch blocked all OAuth routes',
1201
- },
1202
- }), {
1203
- status: 429,
1204
- headers: {
1205
- 'content-type': 'application/json',
1206
- 'retry-after': '60',
1207
- },
1208
- });
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
+ }));
1209
1257
  }
1210
1258
  }
1211
1259
  const { response: primary, preflight: primaryPreflight } = await firstStreamingError(await sendAnthropicRequest({
@@ -1233,7 +1281,7 @@ async function executeWithFallback(options) {
1233
1281
  }
1234
1282
  return primaryPreflight instanceof Response ? primaryPreflight : primary;
1235
1283
  }
1236
- export function streamCortexKitAnthropic(model, context, options, effortTransitions) {
1284
+ export function streamCortexKitAnthropic(model, context, options, effortTransitions, wait) {
1237
1285
  const stream = createAssistantMessageEventStream();
1238
1286
  void (async () => {
1239
1287
  const output = createOutput(model);
@@ -1241,15 +1289,63 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1241
1289
  try {
1242
1290
  buildPiOAuthMessagesUrl(model.baseUrl);
1243
1291
  const storagePath = getPiAccountStoragePath();
1244
- let hostTools = [];
1245
- const response = await runWithRequestSignal(options?.signal, () => executeWithFallback({
1292
+ let toolNames = new Map();
1293
+ const request = {
1246
1294
  model,
1247
1295
  context,
1248
1296
  streamOptions: options,
1249
1297
  storagePath,
1250
1298
  effortTransitions,
1251
- onResolvedTools: (tools) => {
1252
- hostTools = tools;
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 });
1253
1349
  },
1254
1350
  }));
1255
1351
  if (!response.ok) {
@@ -1305,7 +1401,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1305
1401
  output.content.push({
1306
1402
  type: 'toolCall',
1307
1403
  id: String(block.id),
1308
- name: fromClaudeCodeToolName(String(block.name), hostTools),
1404
+ name: fromClaudeCodeToolName(String(block.name), toolNames),
1309
1405
  arguments: {},
1310
1406
  partialJson: '',
1311
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.11",
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.11"
39
+ "@cortexkit/anthropic-auth-core": "2.4.13"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",