@cortexkit/pi-anthropic-auth 2.4.12 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/convert.d.ts CHANGED
@@ -26,18 +26,41 @@ 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;
33
46
  }, fastModeEnabled?: boolean, identity?: ClaudeCodeIdentity, controls?: {
34
47
  effortTransitions?: readonly MidConversationEffortTransition[];
48
+ /** Leave the billing signature placeholder for the transport to finalize. */
49
+ deferSigning?: boolean;
35
50
  thinkingPrefixMismatchBehavior?: ThinkingPrefixMismatchBehavior;
36
51
  turnEndNote?: {
37
52
  tools: string[];
38
53
  };
54
+ /**
55
+ * Pi's `options.onPayload`, bound to the dispatched model. Pi's provider
56
+ * contract: call it before sending and send any replacement it returns. It
57
+ * sees the body with this provider's cache breakpoints placed and runs
58
+ * before signing, so the billing signature covers what is sent.
59
+ */
60
+ onPayload?: (body: AnthropicRequestBody) => unknown | Promise<unknown>;
39
61
  }): Promise<{
40
62
  body: AnthropicRequestBody;
41
63
  bodyText: string;
42
- hostTools: Tool[];
64
+ toolNames: ReadonlyMap<string, string>;
65
+ cacheTtlMs: number;
43
66
  }>;
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,37 @@ 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
- 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 ?? [] };
643
+ const bodyText = controls.deferSigning
644
+ ? unsigned
645
+ : await signRequestBody(unsigned);
646
+ // Translate only known host/wire pairs that survived the hook and JSON
647
+ // serialization. Hook-added or renamed tools must not acquire an alias, and
648
+ // response decoding must never change outgoing names or signed history.
649
+ const sentBody = JSON.parse(bodyText);
650
+ const sentNames = new Set(sentBody.tools?.map((tool) => tool.name));
651
+ const toolNames = new Map([...declaredToolNames].filter(([wireName]) => sentNames.has(wireName)));
652
+ // Sticky routing uses the longest TTL actually sent to bound how long a
653
+ // session waits on its account. Include hook edits, not the account setting;
654
+ // a cache_control key inside tool data is not a cache breakpoint.
655
+ let cacheTtlMs = PROMPT_CACHE_DEFAULT_TTL_MS;
656
+ walkCacheControlHolders(sentBody, (holder) => {
657
+ if (holder.cache_control.ttl === '1h')
658
+ cacheTtlMs = PROMPT_CACHE_1H_TTL_MS;
659
+ });
660
+ return { body, bodyText, toolNames, cacheTtlMs };
599
661
  }
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,10 +1,10 @@
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';
5
5
  import { createPiNativeCommands } from './native-commands.js';
6
6
  import { getPiAccountStoragePath, requirePiNativeHostAuth } from './paths.js';
7
- import { streamCortexKitAnthropic } from './stream.js';
7
+ import { beginPiPrimaryTurn, clearPiStickyQuotaRetries, endPiPrimaryTurn, forgetPiMessageThread, streamCortexKitAnthropic, } from './stream.js';
8
8
  function textImageInput() {
9
9
  return ['text', 'image'];
10
10
  }
@@ -34,15 +34,29 @@ 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();
46
+ beginPiPrimaryTurn(storagePath, sessionId);
44
47
  if (!sessionId)
45
48
  return;
49
+ if (ctx.hasUI) {
50
+ workingMessageBySession.set(sessionId, (message) => {
51
+ if (ctx.sessionManager.getSessionId() === sessionId)
52
+ ctx.ui.setWorkingMessage(message);
53
+ });
54
+ if (workingMessageBySession.size > 128) {
55
+ const oldest = workingMessageBySession.keys().next().value;
56
+ if (oldest !== undefined)
57
+ workingMessageBySession.delete(oldest);
58
+ }
59
+ }
46
60
  // This hook collects effort history for the per-message effort markers
47
61
  // that core adds to Fable 5.1, Opus 5.5 and Sonnet 5.5 requests. A host
48
62
  // whose session entries do not match what this reads must cost the
@@ -72,10 +86,22 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
72
86
  break;
73
87
  }
74
88
  });
75
- pi.on('session_shutdown', async (_event, ctx) => {
89
+ pi.on('agent_settled', async (_event, ctx) => {
76
90
  const sessionId = ctx.sessionManager.getSessionId();
91
+ endPiPrimaryTurn(storagePath, sessionId);
77
92
  if (sessionId)
93
+ clearPiStickyQuotaRetries(storagePath, sessionId);
94
+ });
95
+ pi.on('session_shutdown', async (_event, ctx) => {
96
+ const sessionId = ctx.sessionManager.getSessionId();
97
+ endPiPrimaryTurn(storagePath, sessionId);
98
+ if (sessionId) {
99
+ clearPiStickyQuotaRetries(storagePath, sessionId);
78
100
  effortHistoryBySession.delete(sessionId);
101
+ workingMessageBySession.delete(sessionId);
102
+ sessionCacheActivity.forget(sessionId);
103
+ forgetPiMessageThread(sessionId);
104
+ }
79
105
  await closePiNativeRuntime(storagePath);
80
106
  });
81
107
  // Keep the catalog chat-only even when Pi also accepts image/classifier models.
@@ -106,6 +132,15 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
106
132
  id: 'claude-opus-5-5',
107
133
  name: 'Claude Opus 5.5',
108
134
  reasoning: true,
135
+ // Opus 5.5 always uses adaptive thinking: it cannot disable thinking or
136
+ // honor a generic `minimal` effort. Advertise only the API's effort
137
+ // choices, including the extended levels, as for Sonnet/Haiku 5.5.
138
+ thinkingLevelMap: {
139
+ off: null,
140
+ minimal: null,
141
+ xhigh: 'xhigh',
142
+ max: 'max',
143
+ },
109
144
  input: textImageInput(),
110
145
  cost: { input: 4, output: 20, cacheRead: 0.2, cacheWrite: 8 },
111
146
  contextWindow: 1_000_000,
@@ -206,9 +241,16 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
206
241
  maxTokens: CLAUDE_SONNET_5_5_MAX_OUTPUT_TOKENS,
207
242
  },
208
243
  ],
209
- streamSimple: (model, context, options) => streamCortexKitAnthropic(model, context, options, options?.sessionId
244
+ // Stock Pi's simplified calls share the session's whole-turn lease. Core
245
+ // checks the exact history and retained reply before continuing any anchor.
246
+ streamSimple: (model, context, options, origin = 'agent-loop') => streamCortexKitAnthropic(model, context, options, options?.sessionId
210
247
  ? effortHistoryBySession.get(options.sessionId)
211
- : undefined),
248
+ : undefined, {
249
+ ...quotaWait,
250
+ setWorkingMessage: (options?.sessionId
251
+ ? workingMessageBySession.get(options.sessionId)
252
+ : undefined) ?? quotaWait?.setWorkingMessage,
253
+ }, origin),
212
254
  };
213
255
  async function configureProvider() {
214
256
  const streamSimple = configuration.streamSimple;
@@ -278,7 +320,7 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
278
320
  baseUrl: configuration.baseUrl,
279
321
  })),
280
322
  // Preserve the legacy provider's simplified option surface for raw calls.
281
- stream: (model, context, options) => streamSimple(model, context, options),
323
+ stream: (model, context, options) => streamSimple(model, context, options, 'direct'),
282
324
  streamSimple,
283
325
  };
284
326
  pi.registerProvider(provider);
@@ -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,10 @@
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, type Tool } from '@earendil-works/pi-ai';
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';
4
+ export declare function beginPiPrimaryTurn(storagePath: string, sessionId?: string): void;
5
+ export declare function endPiPrimaryTurn(storagePath: string, sessionId?: string): void;
6
+ export declare function forgetPiMessageThread(sessionId: string): void;
7
+ export declare function clearPiStickyQuotaRetries(storagePath: string, sessionId: string): void;
3
8
  /** Set or clear the test replacement for the wait between quota usage polls. */
4
9
  export declare function __setPiQuotaCallPauseForTest(pause: QuotaManagerOptions['pauseBetweenQuotaCalls']): void;
5
10
  export declare function clearPiStickyRoutingSession(storagePath: string, sessionId: string): Promise<void>;
@@ -24,12 +29,15 @@ declare function sendAnthropicRequest(options: {
24
29
  model: Model<Api>;
25
30
  context: Context;
26
31
  streamOptions?: SimpleStreamOptions;
32
+ requestOrigin?: 'agent-loop' | 'direct';
27
33
  apiAccount?: NativeAccountView;
28
34
  storagePath: string;
29
35
  oauthAccountId?: string;
36
+ expectedAccountIdentity?: string;
30
37
  route?: string;
31
38
  effortTransitions?: readonly MidConversationEffortTransition[];
32
- onResolvedTools?: (tools: Tool[]) => void;
39
+ onResolvedToolNames?: (toolNames: ReadonlyMap<string, string>) => void;
40
+ onThreadPrepared?: (fail: () => void) => void;
33
41
  }, deps?: {
34
42
  fetch?: typeof fetch;
35
43
  cacheKeep?: CacheKeepManager;
@@ -50,5 +58,5 @@ export declare function firstStreamingError(response: Response): Promise<{
50
58
  response: Response;
51
59
  preflight: Response | 'rate_limit_error';
52
60
  }>;
53
- export declare function streamCortexKitAnthropic(model: Model<Api>, context: Context, options?: SimpleStreamOptions, effortTransitions?: readonly MidConversationEffortTransition[]): AssistantMessageEventStream;
61
+ export declare function streamCortexKitAnthropic(model: Model<Api>, context: Context, options?: SimpleStreamOptions, effortTransitions?: readonly MidConversationEffortTransition[], wait?: PiQuotaWaitOptions, requestOrigin?: 'agent-loop' | 'direct'): AssistantMessageEventStream;
54
62
  export {};
package/dist/stream.js CHANGED
@@ -1,14 +1,53 @@
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, effectiveRelayTransport, FAST_MODE_BETA, getCache1hPersistentMode, getClaudeCodeIdentityForVerifiedAccount, getDefaultCacheKeepRegistryDirectory, getFallbackReauthLabels, getMaxSameAccountWait, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, isCache1hPersistentlyEnabled, isCacheKeepHybridActive, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isNativeTransientAccountError, isOAuthAccount, isPermanentRefreshError, isValidApiBaseURL, killswitchPassesPolicy, logger, MessageThreadTracker, mergeAnthropicBetas, NativeAccountRefusal, nativeAccountCanServe, parseSseFrame, prepareMessageThreadRequest, QuotaManager, quotaBackoffActive, quotaExhaustionFromHeaders, quotaRefusalTiming, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, stickyQuotaSnapshotIsFresh, stickyRetryAfterWithJitter, stickyRouteFamilyForModel, } from '@cortexkit/anthropic-auth-core';
2
2
  import { calculateCost, createAssistantMessageEventStream, } from '@earendil-works/pi-ai';
3
3
  import { buildAnthropicRequest, fromClaudeCodeToolName } from './convert.js';
4
4
  import { getPiNativeRuntime, piAttemptAccessToken, } from './native.js';
5
5
  import { getPiAccountStoragePath } from './paths.js';
6
+ import { markPiAccountHold, withPiQuotaWait, } from './quota-wait.js';
6
7
  import { buildPiOAuthMessagesUrl, fetchPiOAuth, requirePiOAuthOrigin, } from './transport.js';
8
+ const messageThreads = new MessageThreadTracker();
9
+ // Each session owns its lease; storage identifies which host may end it.
10
+ const primaryTurns = new Map();
11
+ export function beginPiPrimaryTurn(storagePath, sessionId) {
12
+ if (!sessionId)
13
+ return;
14
+ primaryTurns.delete(sessionId);
15
+ primaryTurns.set(sessionId, storagePath);
16
+ while (primaryTurns.size > 128) {
17
+ const oldest = primaryTurns.keys().next().value;
18
+ if (oldest === undefined)
19
+ break;
20
+ primaryTurns.delete(oldest);
21
+ }
22
+ }
23
+ export function endPiPrimaryTurn(storagePath, sessionId) {
24
+ if (sessionId && primaryTurns.get(sessionId) === storagePath)
25
+ primaryTurns.delete(sessionId);
26
+ }
27
+ function isPiPrimaryThreadRequest(storagePath, options, origin) {
28
+ // SDK summaries disable caching; SDK cache warms request exactly one token.
29
+ if (origin !== 'agent-loop' ||
30
+ options?.cacheRetention === 'none' ||
31
+ options?.maxTokens === 1)
32
+ return false;
33
+ return Boolean(options?.sessionId &&
34
+ primaryTurns.get(options.sessionId) === storagePath &&
35
+ typeof options.onPayload === 'function' &&
36
+ typeof options.onResponse === 'function' &&
37
+ typeof options.onProviderStreamEvent === 'function');
38
+ }
39
+ export function forgetPiMessageThread(sessionId) {
40
+ messageThreads.forget(sessionId);
41
+ }
7
42
  /** Dump label for a physical send that failed before any response arrived. */
8
43
  const PHYSICAL_SEND_FAILED = 'physical send failed before a response';
9
44
  let cacheKeepRegistry;
10
45
  let cacheKeepRegistryDirectory;
11
46
  const stickyRouters = new Map();
47
+ const stickyQuotaRetries = new StickyQuotaRetryCounter();
48
+ export function clearPiStickyQuotaRetries(storagePath, sessionId) {
49
+ stickyQuotaRetries.clear(JSON.stringify([storagePath, sessionId]));
50
+ }
12
51
  const quotaManagers = new Map();
13
52
  const PI_SERVICE_CACHE_LIMIT = 16;
14
53
  /**
@@ -123,6 +162,8 @@ async function getPiStickyRouter(storagePath) {
123
162
  return router;
124
163
  }
125
164
  export async function clearPiStickyRoutingSession(storagePath, sessionId) {
165
+ sessionCacheActivity.forget(sessionId);
166
+ clearPiStickyQuotaRetries(storagePath, sessionId);
126
167
  await (await getPiStickyRouter(storagePath)).clear(sessionId);
127
168
  }
128
169
  function getPiCacheKeepRegistry() {
@@ -203,8 +244,14 @@ const cacheKeepManager = new CacheKeepManager({
203
244
  });
204
245
  return rotatedHeaders;
205
246
  },
206
- onResponse: async ({ attempt, status }) => {
247
+ onResponse: async ({ target, attempt, status, receivedAt }) => {
207
248
  const entry = nativePrewarmAttempts.get(attempt.id);
249
+ if (entry &&
250
+ status >= 200 &&
251
+ status < 300 &&
252
+ !attempt.signal?.aborted &&
253
+ !target.sourceWarm)
254
+ sessionCacheActivity.recordPrewarm(target.id, target.oauthAccountId ?? STICKY_ROUTING_MAIN_ACCOUNT_ID, receivedAt);
208
255
  if (entry && status === 401 && !entry.reported)
209
256
  await entry.runtime.report(entry.served, status, 'direct').catch(() => {
210
257
  logger.warn('native-auth', 'Pi CacheKeep auth-failure report unavailable');
@@ -348,6 +395,9 @@ async function sendAnthropicRequest(options, deps = {}) {
348
395
  const routeId = options.oauthAccountId ?? STICKY_ROUTING_MAIN_ACCOUNT_ID;
349
396
  const selected = snapshot.accounts.find((account) => account.id === routeId);
350
397
  let verifiedUuid = options.apiAccount ? undefined : selected?.accountIdentity;
398
+ if (options.expectedAccountIdentity &&
399
+ verifiedUuid !== options.expectedAccountIdentity)
400
+ throw new Error('The selected OAuth account changed while waiting.');
351
401
  if (!options.apiAccount && !verifiedUuid) {
352
402
  if (selected?.source === 'vault')
353
403
  throw new Error('Pi vault route identity is unasserted');
@@ -361,17 +411,28 @@ async function sendAnthropicRequest(options, deps = {}) {
361
411
  ? (storage.mainAccountId ?? routeId)
362
412
  : routeId, verifiedUuid)
363
413
  : undefined;
364
- const { body, bodyText, hostTools } = await buildAnthropicRequest(options.model.id, options.context, options.streamOptions, {
365
- enabled: isCache1hPersistentlyEnabled(storage),
414
+ // Pi's per-request `cacheRetention: 'long'` asks for the provider's longest
415
+ // retention (Anthropic's one-hour TTL), as Pi's own Anthropic provider
416
+ // honours it; the account setting still enables it for all requests. Cache
417
+ // activity below follows the final serialized body, since hooks can edit TTLs.
418
+ const oneHourCache = isCache1hPersistentlyEnabled(storage) ||
419
+ options.streamOptions?.cacheRetention === 'long';
420
+ const { body, bodyText, toolNames, cacheTtlMs } = await buildAnthropicRequest(options.model.id, options.context, options.streamOptions, {
421
+ enabled: oneHourCache,
366
422
  mode: getCache1hPersistentMode(storage),
367
423
  }, isFastModePersistentlyEnabled(storage), identity, {
424
+ deferSigning: true,
368
425
  effortTransitions: options.apiAccount ? [] : options.effortTransitions,
369
426
  turnEndNote: storage.turnEndNote,
370
427
  thinkingPrefixMismatchBehavior: options.apiAccount
371
428
  ? 'account-default'
372
429
  : getThinkingPrefixMismatchBehavior(storage),
430
+ ...(options.streamOptions?.onPayload && {
431
+ onPayload: (payload) => options.streamOptions?.onPayload?.(payload, options.model),
432
+ }),
373
433
  });
374
- options.onResolvedTools?.(hostTools);
434
+ let wireBodyText = bodyText;
435
+ options.onResolvedToolNames?.(toolNames);
375
436
  const fastMode = body.speed === 'fast';
376
437
  const headers = options.apiAccount
377
438
  ? new Headers()
@@ -390,6 +451,8 @@ async function sendAnthropicRequest(options, deps = {}) {
390
451
  const trackAcceptedRequest = () => {
391
452
  if (options.apiAccount || init.signal?.aborted)
392
453
  return;
454
+ if (relayAffinity)
455
+ sessionCacheActivity.record(relayAffinity, routeId, cacheTtlMs);
393
456
  keep.track({
394
457
  sessionId: relayAffinity,
395
458
  url: input.toString(),
@@ -428,6 +491,33 @@ async function sendAnthropicRequest(options, deps = {}) {
428
491
  throw new Error('Pi native OAuth route identity changed');
429
492
  return attempt;
430
493
  };
494
+ const relayConfig = options.apiAccount
495
+ ? null
496
+ : await (await native.service()).getRelayConfig();
497
+ let threadRequest;
498
+ if (!options.apiAccount &&
499
+ isPiPrimaryThreadRequest(options.storagePath, options.streamOptions, options.requestOrigin) &&
500
+ (!relayConfig ||
501
+ effectiveRelayTransport(relayConfig.transport, relayConfig.url) !==
502
+ 'websocket')) {
503
+ nextAttempt = await takeAttempt();
504
+ threadRequest = await prepareMessageThreadRequest(messageThreads, {
505
+ session: relayAffinity ?? undefined,
506
+ account: nextAttempt.accountIdentity,
507
+ credential: piAttemptAccessToken(nextAttempt),
508
+ bodyText,
509
+ replyToolNames: toolNames,
510
+ headers,
511
+ signal: init.signal ?? undefined,
512
+ });
513
+ options.onThreadPrepared?.(threadRequest.fail);
514
+ wireBodyText = threadRequest.bodyText;
515
+ init.body = wireBodyText;
516
+ }
517
+ else {
518
+ wireBodyText = await signRequestBody(bodyText);
519
+ init.body = wireBodyText;
520
+ }
431
521
  const directFetch = async () => {
432
522
  let attempt;
433
523
  let apiSubject;
@@ -486,7 +576,7 @@ async function sendAnthropicRequest(options, deps = {}) {
486
576
  affinity: relayAffinity,
487
577
  route: options.route ?? 'oauth',
488
578
  status: response.status,
489
- bodyText,
579
+ bodyText: wireBodyText,
490
580
  url: input.toString(),
491
581
  method: init.method,
492
582
  headers,
@@ -513,7 +603,7 @@ async function sendAnthropicRequest(options, deps = {}) {
513
603
  route: options.route ??
514
604
  (options.apiAccount ? `api:${options.apiAccount.id}` : 'oauth'),
515
605
  status: response.status,
516
- bodyText,
606
+ bodyText: wireBodyText,
517
607
  url: input.toString(),
518
608
  method: init.method,
519
609
  headers: init.headers,
@@ -531,7 +621,7 @@ async function sendAnthropicRequest(options, deps = {}) {
531
621
  (options.apiAccount ? `api:${options.apiAccount.id}` : 'oauth'),
532
622
  // A fixed label: the error text can repeat provider output or a credential.
533
623
  error: PHYSICAL_SEND_FAILED,
534
- bodyText,
624
+ bodyText: wireBodyText,
535
625
  url: input.toString(),
536
626
  method: init.method,
537
627
  headers: init.headers,
@@ -557,11 +647,11 @@ async function sendAnthropicRequest(options, deps = {}) {
557
647
  // that attempt's own credentials and the relay token; a direct fallback is
558
648
  // scrubbed by directFetch.
559
649
  const sendRelayAttempt = async () => sendViaRelay({
560
- config: await (await native.service()).getRelayConfig(),
650
+ config: relayConfig,
561
651
  input,
562
652
  init,
563
653
  headers,
564
- body: bodyText,
654
+ body: wireBodyText,
565
655
  fallback: directFetch,
566
656
  affinity: relayAffinity,
567
657
  authorizeAttempt: async () => {
@@ -608,6 +698,14 @@ async function sendAnthropicRequest(options, deps = {}) {
608
698
  // If the request was cancelled since, end it as cancelled here.
609
699
  if (relay401Attempt && response.status === 401)
610
700
  await endIfCancelled(response, init.signal);
701
+ if (threadRequest) {
702
+ response = await threadRequest.recover(response, async (createBody) => {
703
+ wireBodyText = createBody;
704
+ init.body = createBody;
705
+ return sendRelayAttempt();
706
+ });
707
+ response = threadRequest.observe(response);
708
+ }
611
709
  if (response.ok && lastTransport === 'relay' && relayAttempt) {
612
710
  trackAcceptedRequest();
613
711
  markServed(relayAttempt);
@@ -852,8 +950,12 @@ async function executeWithFallback(options) {
852
950
  if (isPermanentRefreshError(refreshError))
853
951
  return [];
854
952
  if (stickyQuotaSnapshotIsFresh(route.quota, storage, Date.now(), modelId) &&
855
- decideStickyQuotaFailure({ quota: route.quota, modelId }).action ===
856
- 'migrate') {
953
+ decideStickyQuotaFailure({
954
+ quota: route.quota,
955
+ modelId,
956
+ sessionId: options.streamOptions?.sessionId,
957
+ holdUntil: sessionCacheActivity.holdUntil(options.streamOptions?.sessionId, route.id, Date.now(), getMaxSameAccountWait(storage)),
958
+ }).action === 'migrate') {
857
959
  return [];
858
960
  }
859
961
  if (isKillswitchEnabled(storage) &&
@@ -1007,6 +1109,8 @@ async function executeWithFallback(options) {
1007
1109
  storage,
1008
1110
  inputBytes: initialInputBytes,
1009
1111
  });
1112
+ if (resolution?.migrated)
1113
+ clearPiStickyQuotaRetries(options.storagePath, sessionId);
1010
1114
  if (!resolution && incompleteQuotaPool) {
1011
1115
  const error = new Error('Sticky-balanced routing is waiting for current OAuth quota snapshots');
1012
1116
  Object.assign(error, {
@@ -1021,11 +1125,20 @@ async function executeWithFallback(options) {
1021
1125
  snapshot: await native.view(),
1022
1126
  modelId: options.model.id,
1023
1127
  sticky: true,
1128
+ sessionId,
1024
1129
  });
1025
1130
  return createStickyNoRouteResponse({
1026
1131
  mainRefreshError: storage?.refresh?.mainLastRefreshError,
1027
1132
  fallbackReauthLabels: getFallbackReauthLabels(storage),
1028
1133
  routeQuotas: routes.allRoutes.flatMap((route) => route.quota ? [route.quota] : []),
1134
+ routeIdentities: routes.allRoutes
1135
+ .filter((route) => route.quota)
1136
+ .map((route) => accountView(route.id)?.accountIdentity),
1137
+ routeAccountIds: routes.allRoutes
1138
+ .filter((route) => route.quota)
1139
+ .map((route) => route.id),
1140
+ storage,
1141
+ sessionId,
1029
1142
  modelId: options.model.id,
1030
1143
  });
1031
1144
  }
@@ -1037,27 +1150,34 @@ async function executeWithFallback(options) {
1037
1150
  route: `sticky:${selected.id}`,
1038
1151
  });
1039
1152
  const completeRoute = async (_selected, response, _markUsed = true) => response;
1153
+ const heldAccountId = route.id;
1154
+ const heldAccountIdentity = accountView(route.id)?.accountIdentity;
1155
+ const holdResponse = (retryAfterSeconds, upstream) => {
1156
+ const headers = new Headers(upstream);
1157
+ headers.set('content-type', 'application/json');
1158
+ headers.set('retry-after', String(stickyRetryAfterWithJitter(sessionId, retryAfterSeconds)));
1159
+ return markPiAccountHold(new Response(JSON.stringify({
1160
+ type: 'error',
1161
+ error: {
1162
+ type: 'rate_limit_error',
1163
+ message: 'Sticky OAuth account quota resets shortly; retaining session affinity.',
1164
+ },
1165
+ }), { status: 429, headers }), {
1166
+ accountId: heldAccountId,
1167
+ accountIdentity: heldAccountIdentity,
1168
+ resetAt: Date.now() + retryAfterSeconds * 1000,
1169
+ });
1170
+ };
1040
1171
  const proactiveQuotaDecision = stickyQuotaSnapshotIsFresh(route.quota, storage, Date.now(), options.model.id)
1041
1172
  ? decideStickyQuotaFailure({
1042
1173
  quota: route.quota,
1043
1174
  modelId: options.model.id,
1175
+ sessionId,
1176
+ holdUntil: sessionCacheActivity.holdUntil(sessionId, route.id, Date.now(), getMaxSameAccountWait(storage)),
1044
1177
  })
1045
1178
  : undefined;
1046
- if (proactiveQuotaDecision?.action === 'hold') {
1047
- return completeRoute(route, new Response(JSON.stringify({
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
- }
1179
+ if (proactiveQuotaDecision?.action === 'hold')
1180
+ return holdResponse(proactiveQuotaDecision.retryAfterSeconds);
1061
1181
  const { response, preflight } = await firstStreamingError(await sendRoute(route));
1062
1182
  if (preflight instanceof Response && preflight.ok) {
1063
1183
  return completeRoute(route, preflight);
@@ -1086,28 +1206,18 @@ async function executeWithFallback(options) {
1086
1206
  quota,
1087
1207
  modelId: options.model.id,
1088
1208
  responseHeaders,
1209
+ sessionId,
1210
+ unconfirmedRetry: {
1211
+ counter: stickyQuotaRetries,
1212
+ sessionId: JSON.stringify([options.storagePath, sessionId]),
1213
+ turnId: String(options.context.messages.findLast((message) => message.role === 'user')?.timestamp ?? sessionId),
1214
+ accountId: route.id,
1215
+ },
1216
+ holdUntil: sessionCacheActivity.holdUntil(sessionId, route.id, Date.now(), getMaxSameAccountWait(storage)),
1089
1217
  });
1090
1218
  if (decision.action === 'hold') {
1091
- const headers = new Headers(preflight instanceof Response
1092
- ? preflight.headers
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 }));
1219
+ void response.body?.cancel().catch(() => { });
1220
+ return holdResponse(decision.retryAfterSeconds, responseHeaders);
1111
1221
  }
1112
1222
  migrate = decision.action === 'migrate';
1113
1223
  }
@@ -1136,6 +1246,7 @@ async function executeWithFallback(options) {
1136
1246
  });
1137
1247
  const migrated = routes.allRoutes.find((candidate) => candidate.id === resolution?.accountId);
1138
1248
  if (resolution && migrated) {
1249
+ clearPiStickyQuotaRetries(options.storagePath, sessionId);
1139
1250
  route = migrated;
1140
1251
  return completeRoute(route, await sendRoute(route));
1141
1252
  }
@@ -1152,8 +1263,10 @@ async function executeWithFallback(options) {
1152
1263
  includeApiRoutes: true,
1153
1264
  apiOnly: true,
1154
1265
  });
1155
- if (apiFallback)
1266
+ if (apiFallback) {
1267
+ clearPiStickyQuotaRetries(options.storagePath, sessionId);
1156
1268
  return apiFallback;
1269
+ }
1157
1270
  }
1158
1271
  }
1159
1272
  return completeRoute(route, preflight instanceof Response ? preflight : response);
@@ -1182,11 +1295,22 @@ async function executeWithFallback(options) {
1182
1295
  return createNativeVaultNoRouteResponse({
1183
1296
  snapshot: await native.view(),
1184
1297
  modelId: options.model.id,
1298
+ sessionId: options.streamOptions?.sessionId,
1185
1299
  });
1186
1300
  return createStickyNoRouteResponse({
1187
1301
  routeQuotas: (storage?.accounts ?? [])
1188
1302
  .filter(isOAuthAccount)
1189
1303
  .flatMap((account) => (account.quota ? [account.quota] : [])),
1304
+ routeIdentities: (storage?.accounts ?? [])
1305
+ .filter(isOAuthAccount)
1306
+ .filter((account) => account.quota)
1307
+ .map((account) => accountView(account.id)?.accountIdentity),
1308
+ routeAccountIds: (storage?.accounts ?? [])
1309
+ .filter(isOAuthAccount)
1310
+ .filter((account) => account.quota)
1311
+ .map((account) => account.id),
1312
+ storage,
1313
+ sessionId: options.streamOptions?.sessionId,
1190
1314
  modelId: options.model.id,
1191
1315
  });
1192
1316
  }
@@ -1204,19 +1328,19 @@ async function executeWithFallback(options) {
1204
1328
  if (fallback)
1205
1329
  return fallback;
1206
1330
  }
1207
- return new Response(JSON.stringify({
1208
- type: 'error',
1209
- error: {
1210
- type: 'rate_limit_error',
1211
- message: 'Killswitch blocked all OAuth routes',
1212
- },
1213
- }), {
1214
- status: 429,
1215
- headers: {
1216
- 'content-type': 'application/json',
1217
- 'retry-after': '60',
1218
- },
1219
- });
1331
+ const current = await native.view();
1332
+ return createQuotaRefusalResponse('Killswitch blocked all OAuth routes', quotaRefusalTiming({
1333
+ readings: current.accounts
1334
+ .filter((account) => account.type === 'oauth' && nativeAccountCanServe(account))
1335
+ .map((account) => ({
1336
+ quota: account.quota,
1337
+ accountIdentity: account.accountIdentity,
1338
+ accountId: account.id,
1339
+ })),
1340
+ storage: current.policyStorage,
1341
+ modelId: options.model.id,
1342
+ sessionTtlMs: sessionCacheActivity.ttlMs(options.streamOptions?.sessionId),
1343
+ }));
1220
1344
  }
1221
1345
  }
1222
1346
  const { response: primary, preflight: primaryPreflight } = await firstStreamingError(await sendAnthropicRequest({
@@ -1244,23 +1368,76 @@ async function executeWithFallback(options) {
1244
1368
  }
1245
1369
  return primaryPreflight instanceof Response ? primaryPreflight : primary;
1246
1370
  }
1247
- export function streamCortexKitAnthropic(model, context, options, effortTransitions) {
1371
+ export function streamCortexKitAnthropic(model, context, options, effortTransitions, wait, requestOrigin = 'direct') {
1248
1372
  const stream = createAssistantMessageEventStream();
1249
1373
  void (async () => {
1250
1374
  const output = createOutput(model);
1375
+ let failThread;
1251
1376
  stream.push({ type: 'start', partial: output });
1252
1377
  try {
1253
1378
  buildPiOAuthMessagesUrl(model.baseUrl);
1254
1379
  const storagePath = getPiAccountStoragePath();
1255
- let hostTools = [];
1256
- const response = await runWithRequestSignal(options?.signal, () => executeWithFallback({
1380
+ let toolNames = new Map();
1381
+ const request = {
1257
1382
  model,
1258
1383
  context,
1259
1384
  streamOptions: options,
1385
+ requestOrigin,
1260
1386
  storagePath,
1387
+ onThreadPrepared: (fail) => {
1388
+ failThread = fail;
1389
+ },
1261
1390
  effortTransitions,
1262
- onResolvedTools: (tools) => {
1263
- hostTools = tools;
1391
+ onResolvedToolNames: (names) => {
1392
+ toolNames = names;
1393
+ },
1394
+ };
1395
+ const response = await runWithRequestSignal(options?.signal, () => withPiQuotaWait({
1396
+ signal: options?.signal,
1397
+ wait,
1398
+ run: () => executeWithFallback(request),
1399
+ resume: async (hold) => {
1400
+ const native = getPiNativeRuntime(storagePath);
1401
+ const before = await native.requestView(options?.signal);
1402
+ if (hold &&
1403
+ (!hold.accountIdentity ||
1404
+ before.accounts.find((account) => account.id === hold.accountId)
1405
+ ?.accountIdentity !== hold.accountIdentity))
1406
+ throw new Error('The selected OAuth account changed while waiting.');
1407
+ const runtime = await native.service();
1408
+ let heldStillBlocked = false;
1409
+ for (const account of before.accounts) {
1410
+ if (account.type !== 'oauth' ||
1411
+ !nativeAccountCanServe(account) ||
1412
+ (hold && account.id !== hold.accountId))
1413
+ continue;
1414
+ options?.signal?.throwIfAborted();
1415
+ try {
1416
+ const quota = await runtime.fetchQuota(account.id, fetchPiOAuth, options?.signal, undefined, 'admission');
1417
+ if (hold &&
1418
+ decideStickyQuotaFailure({ quota, modelId: model.id })
1419
+ .action === 'migrate')
1420
+ heldStillBlocked = true;
1421
+ }
1422
+ catch (error) {
1423
+ if (options?.signal?.aborted)
1424
+ throw error;
1425
+ }
1426
+ }
1427
+ options?.signal?.throwIfAborted();
1428
+ if (heldStillBlocked)
1429
+ throw new Error('The selected OAuth account cannot serve this request.');
1430
+ if (!hold)
1431
+ return executeWithFallback(request);
1432
+ const inspected = await firstStreamingError(await sendAnthropicRequest({
1433
+ ...request,
1434
+ oauthAccountId: hold.accountId,
1435
+ expectedAccountIdentity: hold.accountIdentity,
1436
+ }));
1437
+ if (inspected.preflight instanceof Response)
1438
+ return inspected.preflight;
1439
+ void inspected.response.body?.cancel().catch(() => { });
1440
+ return new Response(null, { status: 429 });
1264
1441
  },
1265
1442
  }));
1266
1443
  if (!response.ok) {
@@ -1316,7 +1493,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1316
1493
  output.content.push({
1317
1494
  type: 'toolCall',
1318
1495
  id: String(block.id),
1319
- name: fromClaudeCodeToolName(String(block.name), hostTools),
1496
+ name: fromClaudeCodeToolName(String(block.name), toolNames),
1320
1497
  arguments: {},
1321
1498
  partialJson: '',
1322
1499
  index: event.index,
@@ -1430,6 +1607,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1430
1607
  stream.end();
1431
1608
  }
1432
1609
  catch (error) {
1610
+ failThread?.();
1433
1611
  for (const block of output.content)
1434
1612
  delete block.index;
1435
1613
  output.stopReason = options?.signal?.aborted ? 'aborted' : 'error';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.4.12",
3
+ "version": "2.5.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -36,7 +36,7 @@
36
36
  "prepublishOnly": "bun run build"
37
37
  },
38
38
  "dependencies": {
39
- "@cortexkit/anthropic-auth-core": "2.4.12"
39
+ "@cortexkit/anthropic-auth-core": "2.5.0"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",