@cortexkit/pi-anthropic-auth 2.11.1 → 2.11.3

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
@@ -40,6 +40,8 @@ export declare function createClaudeCodeToolNameMap(tools: readonly Tool[]): Rea
40
40
  * executable host tool.
41
41
  */
42
42
  export declare function fromClaudeCodeToolName(name: string, requestedToolNames: ReadonlyMap<string, string>): string;
43
+ /** Replace only the system cache marker, preserving the tool and message markers. */
44
+ export declare function piThreadCacheSlot(body: Record<string, unknown>): Record<string, unknown> | undefined;
43
45
  export declare function buildAnthropicRequest(modelId: string, context: Context, options: SimpleStreamOptions | undefined, cache: {
44
46
  enabled: boolean;
45
47
  mode: Cache1hMode;
package/dist/convert.js CHANGED
@@ -479,6 +479,12 @@ function applyCacheMode(body, enabled, mode) {
479
479
  holder.cache_control.ttl = '1h';
480
480
  });
481
481
  }
482
+ /** Replace only the system cache marker, preserving the tool and message markers. */
483
+ export function piThreadCacheSlot(body) {
484
+ if (body.cache_control || !Array.isArray(body.system))
485
+ return undefined;
486
+ return body.system.findLast((block) => block && typeof block === 'object' && block.cache_control);
487
+ }
482
488
  export async function buildAnthropicRequest(modelId, context, options, cache, fastModeEnabled = false, identity, controls = {}) {
483
489
  // Pi 0.86 passes a normalized transcript to providers, and later system
484
490
  // messages can change the prompt, its named sections and the tool set. Resolve
package/dist/native.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type NativeAccountRuntime, type NativeAccountRuntimeOptions, type NativeAccountSnapshot, type NativeCustodyClient, type NativeCustodyReceipt, type NativeCustodyReporterSource, type NativeRefreshResult, type RoutingChoice } from '@cortexkit/anthropic-auth-core';
1
+ import { type NativeAccountRuntime, type NativeAccountRuntimeOptions, type NativeAccountSnapshot, type NativeCustodyClient, type NativeCustodyReceipt, type NativeCustodyReporterSource, type NativeLocalExternalPolicy, type NativeRefreshResult, type RoutingChoice } from '@cortexkit/anthropic-auth-core';
2
2
  import { type PiPrimeLease, type PiPrimeOptions } from './prime.ts';
3
3
  export type PiNativeAttempt = {
4
4
  source: 'local';
@@ -12,6 +12,9 @@ export type PiNativeAttempt = {
12
12
  receipt: NativeCustodyReceipt;
13
13
  };
14
14
  export declare function piAttemptAccessToken(attempt: PiNativeAttempt): string;
15
+ declare function requestPolicy(routeId: string, modelId?: string, routingChoice?: RoutingChoice): (account: NativeAccountSnapshot['accounts'][number], current: NativeAccountSnapshot) => NativeLocalExternalPolicy;
16
+ /** Exercise request admission against an isolated policy snapshot in tests. */
17
+ export declare const __piRequestPolicyForTest: typeof requestPolicy;
15
18
  /**
16
19
  * Core's refusal for an install that offline setup has never migrated, such
17
20
  * as a 1.x install upgraded in place. Core does not export the error class,
@@ -94,3 +97,4 @@ export declare function getPiNativeRuntime(storagePath?: string, options?: {
94
97
  prime?: PiPrimeOptions;
95
98
  }): PiNativeRuntime;
96
99
  export declare function closePiNativeRuntime(storagePath?: string): Promise<void>;
100
+ export {};
package/dist/native.js CHANGED
@@ -31,6 +31,8 @@ function requestPolicy(routeId, modelId, routingChoice) {
31
31
  : { status: 'allowed' };
32
32
  };
33
33
  }
34
+ /** Exercise request admission against an isolated policy snapshot in tests. */
35
+ export const __piRequestPolicyForTest = requestPolicy;
34
36
  const runtimes = new Map();
35
37
  const RUNTIME_LIMIT = 16;
36
38
  const closingRuntimes = new Map();
@@ -8,6 +8,7 @@ export type PiAccountHold = {
8
8
  accountId: string;
9
9
  accountIdentity?: string;
10
10
  resetAt: number;
11
+ reason?: 'account_limit' | 'routing_hold';
11
12
  };
12
13
  export declare function markPiAccountHold(response: Response, hold: PiAccountHold): Response;
13
14
  /** Own one bounded wait inside a Pi stream, rather than asking Pi's text-based retry loop. */
@@ -16,4 +17,5 @@ export declare function withPiQuotaWait(input: {
16
17
  resume: (hold: PiAccountHold | undefined) => Promise<Response>;
17
18
  signal?: AbortSignal;
18
19
  wait?: PiQuotaWaitOptions;
20
+ sessionId?: string;
19
21
  }): Promise<Response>;
@@ -1,4 +1,4 @@
1
- import { clampHostRetryMs, createQuotaRefusalResponse, hostRetryResponse, quotaRefusalDetails, } from '@cortexkit/anthropic-auth-core';
1
+ import { clampHostRetryMs, createQuotaRefusalResponse, hostRetryResponse, quotaRefusalDetails, startRoutingWait, } from '@cortexkit/anthropic-auth-core';
2
2
  const holds = new WeakMap();
3
3
  export function markPiAccountHold(response, hold) {
4
4
  holds.set(response, hold);
@@ -56,26 +56,45 @@ export async function withPiQuotaWait(input) {
56
56
  resetAt: undefined,
57
57
  retryAfterSeconds: undefined,
58
58
  });
59
- await waitForReset(clampHostRetryMs(delay), hold?.resetAt ?? refusal?.timing.resetAt, input.signal, options);
60
- input.signal?.throwIfAborted();
61
- let next;
59
+ const endWait = startRoutingWait({
60
+ sessionId: input.sessionId,
61
+ reason: hold?.reason ?? (hold ? 'account_limit' : 'account_free'),
62
+ delayMs: clampHostRetryMs(delay),
63
+ nextMs: (options.now?.() ?? Date.now()) + clampHostRetryMs(delay),
64
+ });
65
+ let outcome = 'abandoned';
62
66
  try {
63
- next = await input.resume(hold);
64
- if (next.ok || next.status === 401)
65
- return hostRetryResponse(next, options.now?.() ?? Date.now());
67
+ await waitForReset(clampHostRetryMs(delay), hold?.resetAt ?? refusal?.timing.resetAt, input.signal, options);
68
+ input.signal?.throwIfAborted();
69
+ let next;
70
+ try {
71
+ next = await input.resume(hold);
72
+ if (next.ok || next.status === 401) {
73
+ outcome = 'resumed';
74
+ return hostRetryResponse(next, options.now?.() ?? Date.now());
75
+ }
76
+ }
77
+ catch (error) {
78
+ if (input.signal?.aborted)
79
+ throw error;
80
+ }
81
+ const latest = next && quotaRefusalDetails(next);
82
+ void next?.body?.cancel().catch(() => { });
83
+ // Do not leak a rate-limit code or retry guidance into Pi's final error classifier.
84
+ return createQuotaRefusalResponse(latest?.reason ??
85
+ refusal?.reason ??
86
+ 'The selected OAuth account cannot serve this request. Open /claude to review account availability.', {
87
+ resetAt: latest?.timing.resetAt ?? refusal?.timing.resetAt ?? hold?.resetAt,
88
+ limitName: latest?.timing.limitName ?? refusal?.timing.limitName,
89
+ retryAfterSeconds: undefined,
90
+ }, options.now?.() ?? Date.now(), { retry: 'manual' });
66
91
  }
67
92
  catch (error) {
68
93
  if (input.signal?.aborted)
69
- throw error;
94
+ outcome = 'cancelled';
95
+ throw error;
96
+ }
97
+ finally {
98
+ endWait?.(outcome);
70
99
  }
71
- const latest = next && quotaRefusalDetails(next);
72
- void next?.body?.cancel().catch(() => { });
73
- // Do not leak a rate-limit code or retry guidance into Pi's final error classifier.
74
- return createQuotaRefusalResponse(latest?.reason ??
75
- refusal?.reason ??
76
- 'The selected OAuth account cannot serve this request. Open /claude to review account availability.', {
77
- resetAt: latest?.timing.resetAt ?? refusal?.timing.resetAt ?? hold?.resetAt,
78
- limitName: latest?.timing.limitName ?? refusal?.timing.limitName,
79
- retryAfterSeconds: undefined,
80
- }, options.now?.() ?? Date.now(), { retry: 'manual' });
81
100
  }
package/dist/stream.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type ApiKeyAccount, type CacheKeepManager, createAnthropicStreamCompletion, createRoutingRelay, type MidConversationEffortTransition, type NativeAccountView, type QuotaManagerOptions, type RoutingChoice } from '@cortexkit/anthropic-auth-core';
1
+ import { type AccountStorage, type ApiKeyAccount, type CacheKeepManager, createAnthropicStreamCompletion, createRoutingRelay, type MidConversationEffortTransition, type NativeAccountSnapshot, type NativeAccountView, type OAuthAccount, QuotaManager, type QuotaManagerOptions, type RoutingChoice } from '@cortexkit/anthropic-auth-core';
2
2
  import { type Api, type AssistantMessageEventStream, type Context, type Model, type SimpleStreamOptions } from '@earendil-works/pi-ai';
3
3
  import { type PiNativeAttempt, type PiNativeRuntime } from './native.ts';
4
4
  import { type PiPrimeSendOptions } from './prime.ts';
@@ -9,6 +9,14 @@ export declare function forgetPiMessageThread(sessionId: string): void;
9
9
  export declare function clearPiStickyQuotaRetries(storagePath: string, sessionId: string): void;
10
10
  /** Set or clear the test replacement for the wait between quota usage polls. */
11
11
  export declare function __setPiQuotaCallPauseForTest(pause: QuotaManagerOptions['pauseBetweenQuotaCalls']): void;
12
+ declare function getPiRoutingServices(storagePath: string, snapshot: NativeAccountSnapshot): {
13
+ quotaManager: QuotaManager;
14
+ getUsableFallbackAccounts: (current: AccountStorage, options?: {
15
+ modelId?: string;
16
+ }) => Promise<OAuthAccount[]>;
17
+ };
18
+ /** Exercise fallback eligibility without authorizing or sending a request. */
19
+ export declare const __getPiRoutingServicesForTest: typeof getPiRoutingServices;
12
20
  export declare function clearPiStickyRoutingSession(storagePath: string, sessionId: string): Promise<void>;
13
21
  export declare function startPiCacheKeepSession(storagePath: string, sessionId: string): Promise<void>;
14
22
  export declare function stopPiCacheKeep(): Promise<void>;
@@ -73,5 +81,21 @@ export declare function firstStreamingError(response: Response): Promise<{
73
81
  response: Response;
74
82
  preflight: Response | 'rate_limit_error';
75
83
  }>;
84
+ declare function executeWithFallback(options: {
85
+ model: Model<Api>;
86
+ context: Context;
87
+ streamOptions?: SimpleStreamOptions;
88
+ requestOrigin?: 'agent-loop' | 'direct';
89
+ storagePath: string;
90
+ effortTransitions?: readonly MidConversationEffortTransition[];
91
+ onResolvedToolNames?: (toolNames: ReadonlyMap<string, string>) => void;
92
+ onThreadPrepared?: (fail: () => void) => void;
93
+ routingRelay?: ReturnType<typeof createRoutingRelay>;
94
+ routingState?: {
95
+ relay: ReturnType<typeof createRoutingRelay>;
96
+ advice?: Promise<RoutingChoice | null>;
97
+ };
98
+ }): Promise<Response>;
99
+ export declare const __executePiWithFallbackForTest: typeof executeWithFallback;
76
100
  export declare function streamCortexKitAnthropic(model: Model<Api>, context: Context, options?: SimpleStreamOptions, effortTransitions?: readonly MidConversationEffortTransition[], wait?: PiQuotaWaitOptions, requestOrigin?: 'agent-loop' | 'direct'): AssistantMessageEventStream;
77
101
  export {};
package/dist/stream.js CHANGED
@@ -1,7 +1,7 @@
1
- import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, buildPrimeRequestBody, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, CLAUDE_CODE_ACCEPT_ENCODING, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, copyStreamResponseTiming, createAnthropicStreamCompletion, createDumpResponseObserver, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createRoutingRelay, createSseFramer, createStickyNoRouteResponse, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, dumpResponseArtifact, effectiveRelayTransport, FAST_MODE_BETA, getCache1hPersistentMode, getCacheKeepRegistryDirectories, getClaudeCodeIdentityForVerifiedAccount, getFallbackReauthLabels, getMaxSameAccountWait, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, hostRetryHeaders, hostRetryResponse, isCache1hPersistentlyEnabled, isCacheKeepHybridActive, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isNativeTransientAccountError, isOAuthAccount, isPermanentRefreshError, isValidApiBaseURL, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, localMessageThreadCredential, logger, MessageThreadTracker, mergeAnthropicBetas, NativeAccountRefusal, nativeAccountCanServe, orderClaudeCodeBody, PROMPT_CACHE_DEFAULT_TTL_MS, parseSseFrame, prepareMessageThreadRequest, QuotaManager, quotaBackoffActive, quotaExhaustionFromHeaders, quotaRefusalTiming, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, readSessionCachePolicy, reportRoutingResponse, reportSessionCacheTouch, requestCacheLifetimeMs, resolveNativePoolPaths, routingCandidates, routingChoiceMatches, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, stickyQuotaSnapshotIsFresh, stickyRetryAfterWithJitter, stickyRouteCandidateWeight, stickyRouteFamilyForModel, withAnthropicBilling, } from '@cortexkit/anthropic-auth-core';
1
+ import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, buildPrimeRequestBody, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, CLAUDE_CODE_ACCEPT_ENCODING, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, copyStreamResponseTiming, createAnthropicStreamCompletion, createDumpResponseObserver, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createRoutingRelay, createSseFramer, createStickyNoRouteResponse, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, dumpResponseArtifact, effectiveRelayTransport, FAST_MODE_BETA, getCache1hPersistentMode, getCacheKeepRegistryDirectories, getClaudeCodeIdentityForVerifiedAccount, getFallbackReauthLabels, getMaxSameAccountWait, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, hostRetryHeaders, hostRetryResponse, isCache1hPersistentlyEnabled, isCacheKeepHybridActive, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isNativeTransientAccountError, isOAuthAccount, isPermanentRefreshError, isValidApiBaseURL, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, localMessageThreadCredential, logger, MessageThreadTracker, mergeAnthropicBetas, NativeAccountRefusal, nativeAccountCanServe, orderClaudeCodeBody, PROMPT_CACHE_DEFAULT_TTL_MS, parseSseFrame, prepareMessageThreadRequest, QuotaManager, quotaBackoffActive, quotaExhaustionFromHeaders, quotaRefusalTiming, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, readSessionCachePolicy, reportRoutingResponse, reportSessionCacheTouch, requestCacheLifetimeMs, resolveNativePoolPaths, routingCandidates, routingChoiceMatches, routingWarmCredential, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, startRoutingWait, stickyQuotaSnapshotIsFresh, stickyRetainRetryHeaders, stickyRetryAfterWithJitter, stickyRouteCandidateWeight, stickyRouteFamilyForModel, withAnthropicBilling, } from '@cortexkit/anthropic-auth-core';
2
2
  import { calculateCost, createAssistantMessageEventStream, } from '@earendil-works/pi-ai';
3
3
  import { PiCacheKeep } from './cachekeep.js';
4
- import { buildAnthropicRequest, fromClaudeCodeToolName } from './convert.js';
4
+ import { buildAnthropicRequest, fromClaudeCodeToolName, piThreadCacheSlot, } from './convert.js';
5
5
  import { getPiNativeRuntime, peekPiNativeSnapshot, piAttemptAccessToken, } from './native.js';
6
6
  import { getPiAccountStoragePath } from './paths.js';
7
7
  import { registerPiPrimeSender } from './prime.js';
@@ -147,6 +147,8 @@ function getPiRoutingServices(storagePath, snapshot) {
147
147
  };
148
148
  return { quotaManager, getUsableFallbackAccounts };
149
149
  }
150
+ /** Exercise fallback eligibility without authorizing or sending a request. */
151
+ export const __getPiRoutingServicesForTest = getPiRoutingServices;
150
152
  async function getPiStickyRouter(storagePath) {
151
153
  const { path, vaultSeed } = await getPiNativeRuntime(storagePath).routingStorage();
152
154
  let router = stickyRouters.get(path);
@@ -716,6 +718,7 @@ async function sendAnthropicRequest(options, deps = {}) {
716
718
  : localMessageThreadCredential(nextAttempt.admission.binding),
717
719
  bodyText,
718
720
  replyToolNames: toolNames,
721
+ cacheSlot: piThreadCacheSlot,
719
722
  headers,
720
723
  signal: init.signal ?? undefined,
721
724
  });
@@ -1373,7 +1376,11 @@ async function executeWithFallback(options) {
1373
1376
  const routingRelay = routingState.relay;
1374
1377
  const routingSessionId = options.streamOptions?.sessionId;
1375
1378
  if (routingSessionId && !routingState.advice) {
1376
- routingState.advice = routingRelay.accountFor(routingSessionId, options.model.id, routingCandidates(snapshot.accounts));
1379
+ routingState.advice = (async () => {
1380
+ const router = await getPiStickyRouter(options.storagePath);
1381
+ const assignment = await router.readAssignment(routingSessionId);
1382
+ return routingRelay.accountFor(routingSessionId, options.model.id, routingCandidates(snapshot.accounts), routingWarmCredential(snapshot.accounts, assignment));
1383
+ })();
1377
1384
  }
1378
1385
  const advice = await routingState.advice;
1379
1386
  let advisedAccountId = advice
@@ -1485,6 +1492,7 @@ async function executeWithFallback(options) {
1485
1492
  accountId: heldAccountId,
1486
1493
  accountIdentity: heldAccountIdentity,
1487
1494
  resetAt: Date.now() + retryAfterSeconds * 1000,
1495
+ reason: routingHold ? 'routing_hold' : 'account_limit',
1488
1496
  });
1489
1497
  };
1490
1498
  if (advisedAccountId && advice?.hold)
@@ -1505,6 +1513,7 @@ async function executeWithFallback(options) {
1505
1513
  return completeRoute(route, preflight);
1506
1514
  }
1507
1515
  const permanentAuthFailure = preflight instanceof Response && preflight.status === 401;
1516
+ let retainedResponse;
1508
1517
  let migrate = (preflight instanceof Response && preflight.status === 403) ||
1509
1518
  permanentAuthFailure;
1510
1519
  if (primaryResponseAllowsApiFallback(preflight)) {
@@ -1541,6 +1550,23 @@ async function executeWithFallback(options) {
1541
1550
  void response.body?.cancel().catch(() => { });
1542
1551
  return holdResponse(decision.retryAfterSeconds, responseHeaders);
1543
1552
  }
1553
+ if (decision.action === 'retain') {
1554
+ const now = Date.now();
1555
+ const headers = stickyRetainRetryHeaders(responseHeaders, now);
1556
+ const delayMs = Number(headers.get('retry-after-ms'));
1557
+ retainedResponse = new Response(response.body, {
1558
+ status: response.status,
1559
+ statusText: response.statusText,
1560
+ headers,
1561
+ });
1562
+ startRoutingWait({
1563
+ sessionId,
1564
+ reason: 'rate_limited',
1565
+ delayMs,
1566
+ nextMs: now + delayMs,
1567
+ attempt: stickyQuotaRetries.attempt(JSON.stringify([options.storagePath, sessionId])),
1568
+ });
1569
+ }
1544
1570
  migrate = decision.action === 'migrate';
1545
1571
  }
1546
1572
  if (migrate) {
@@ -1607,7 +1633,8 @@ async function executeWithFallback(options) {
1607
1633
  void preflight.body?.cancel().catch(() => { });
1608
1634
  return noRouteResponse();
1609
1635
  }
1610
- return completeRoute(route, preflight instanceof Response ? preflight : response);
1636
+ return completeRoute(route, retainedResponse ??
1637
+ (preflight instanceof Response ? preflight : response));
1611
1638
  }
1612
1639
  }
1613
1640
  const fallbackFirst = routingMode === 'fallback-first';
@@ -1706,6 +1733,7 @@ async function executeWithFallback(options) {
1706
1733
  }
1707
1734
  return primaryPreflight instanceof Response ? primaryPreflight : primary;
1708
1735
  }
1736
+ export const __executePiWithFallbackForTest = executeWithFallback;
1709
1737
  export function streamCortexKitAnthropic(model, context, options, effortTransitions, wait, requestOrigin = 'direct') {
1710
1738
  const stream = createAssistantMessageEventStream();
1711
1739
  void (async () => {
@@ -1738,6 +1766,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1738
1766
  Object.assign(request, { routingState });
1739
1767
  const response = await runWithRequestSignal(options?.signal, () => withPiQuotaWait({
1740
1768
  signal: options?.signal,
1769
+ sessionId: options?.sessionId,
1741
1770
  wait,
1742
1771
  run: () => executeWithFallback(request),
1743
1772
  resume: async (hold) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.11.1",
3
+ "version": "2.11.3",
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.11.1"
39
+ "@cortexkit/anthropic-auth-core": "2.11.3"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",