@cortexkit/pi-anthropic-auth 2.11.0 → 2.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { createQuotaRefusalResponse, quotaRefusalDetails, } from '@cortexkit/anthropic-auth-core';
1
+ import { clampHostRetryMs, createQuotaRefusalResponse, hostRetryResponse, quotaRefusalDetails, } from '@cortexkit/anthropic-auth-core';
2
2
  const holds = new WeakMap();
3
3
  export function markPiAccountHold(response, hold) {
4
4
  holds.set(response, hold);
@@ -9,13 +9,14 @@ async function waitForReset(delayMs, resetAt, signal, options) {
9
9
  const set = options.setTimeout ?? globalThis.setTimeout;
10
10
  const clear = options.clearTimeout ?? globalThis.clearTimeout;
11
11
  const when = resetAt ?? (options.now?.() ?? Date.now()) + delayMs;
12
- const time = new Date(when).toLocaleTimeString(undefined, {
12
+ const time = new Date(when).toLocaleTimeString('en-GB', {
13
13
  hour: '2-digit',
14
14
  minute: '2-digit',
15
15
  hour12: false,
16
+ timeZone: 'UTC',
16
17
  });
17
18
  try {
18
- options.setWorkingMessage?.(`Waiting for the account to reset at ${time} · Esc to cancel`);
19
+ options.setWorkingMessage?.(`Checking account availability in ${Math.max(1, Math.ceil(delayMs / 60_000))} min (reset at ${time} UTC) · Esc to cancel`);
19
20
  await new Promise((resolve, reject) => {
20
21
  const abort = () => {
21
22
  clear(timer);
@@ -36,9 +37,10 @@ async function waitForReset(delayMs, resetAt, signal, options) {
36
37
  }
37
38
  /** Own one bounded wait inside a Pi stream, rather than asking Pi's text-based retry loop. */
38
39
  export async function withPiQuotaWait(input) {
39
- const response = await input.run();
40
- const hold = holds.get(response);
41
- const refusal = quotaRefusalDetails(response);
40
+ const original = await input.run();
41
+ const hold = holds.get(original);
42
+ const refusal = quotaRefusalDetails(original);
43
+ const response = hostRetryResponse(original, input.wait?.now?.() ?? Date.now());
42
44
  const delay = Number(response.headers.get('retry-after')) * 1000;
43
45
  if ((!hold && !refusal) ||
44
46
  !response.headers.has('retry-after') ||
@@ -54,13 +56,13 @@ export async function withPiQuotaWait(input) {
54
56
  resetAt: undefined,
55
57
  retryAfterSeconds: undefined,
56
58
  });
57
- await waitForReset(delay, hold?.resetAt ?? refusal?.timing.resetAt, input.signal, options);
59
+ await waitForReset(clampHostRetryMs(delay), hold?.resetAt ?? refusal?.timing.resetAt, input.signal, options);
58
60
  input.signal?.throwIfAborted();
59
61
  let next;
60
62
  try {
61
63
  next = await input.resume(hold);
62
64
  if (next.ok || next.status === 401)
63
- return next;
65
+ return hostRetryResponse(next, options.now?.() ?? Date.now());
64
66
  }
65
67
  catch (error) {
66
68
  if (input.signal?.aborted)
@@ -73,6 +75,7 @@ export async function withPiQuotaWait(input) {
73
75
  refusal?.reason ??
74
76
  'The selected OAuth account cannot serve this request. Open /claude to review account availability.', {
75
77
  resetAt: latest?.timing.resetAt ?? refusal?.timing.resetAt ?? hold?.resetAt,
78
+ limitName: latest?.timing.limitName ?? refusal?.timing.limitName,
76
79
  retryAfterSeconds: undefined,
77
- }, options.now?.() ?? Date.now());
80
+ }, options.now?.() ?? Date.now(), { retry: 'manual' });
78
81
  }
package/dist/stream.js CHANGED
@@ -1,4 +1,4 @@
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, 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, 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, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, stickyQuotaSnapshotIsFresh, 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
4
  import { buildAnthropicRequest, fromClaudeCodeToolName } from './convert.js';
@@ -1431,7 +1431,7 @@ async function executeWithFallback(options) {
1431
1431
  });
1432
1432
  throw error;
1433
1433
  }
1434
- if (!resolution) {
1434
+ const noRouteResponse = async () => {
1435
1435
  if (snapshot.mode === 'claustrum')
1436
1436
  return createNativeVaultNoRouteResponse({
1437
1437
  snapshot: await native.view(),
@@ -1453,7 +1453,9 @@ async function executeWithFallback(options) {
1453
1453
  sessionId,
1454
1454
  modelId: options.model.id,
1455
1455
  });
1456
- }
1456
+ };
1457
+ if (!resolution)
1458
+ return noRouteResponse();
1457
1459
  let route = routes.allRoutes.find((candidate) => candidate.id === resolution?.accountId);
1458
1460
  if (resolution && route) {
1459
1461
  const sendRoute = (selected) => sendAnthropicRequest({
@@ -1464,7 +1466,7 @@ async function executeWithFallback(options) {
1464
1466
  : undefined,
1465
1467
  route: `sticky:${selected.id}`,
1466
1468
  });
1467
- const completeRoute = async (_selected, response, _markUsed = true) => response;
1469
+ const completeRoute = async (_selected, response, _markUsed = true) => hostRetryResponse(response);
1468
1470
  const heldAccountId = route.id;
1469
1471
  const heldAccountIdentity = accountView(route.id)?.accountIdentity;
1470
1472
  const holdResponse = (retryAfterSeconds, upstream, routingHold = false) => {
@@ -1479,7 +1481,7 @@ async function executeWithFallback(options) {
1479
1481
  type: 'rate_limit_error',
1480
1482
  message: 'Sticky OAuth account quota resets shortly; retaining session affinity.',
1481
1483
  },
1482
- }), { status: 429, headers }), {
1484
+ }), { status: 429, headers: hostRetryHeaders(headers) }), {
1483
1485
  accountId: heldAccountId,
1484
1486
  accountIdentity: heldAccountIdentity,
1485
1487
  resetAt: Date.now() + retryAfterSeconds * 1000,
@@ -1588,8 +1590,23 @@ async function executeWithFallback(options) {
1588
1590
  clearPiStickyQuotaRetries(options.storagePath, sessionId);
1589
1591
  return apiFallback;
1590
1592
  }
1593
+ routes = await buildStickyRoutes(options.model.id);
1591
1594
  }
1592
1595
  }
1596
+ if (primaryResponseAllowsApiFallback(preflight) &&
1597
+ routes.candidates.every((candidate) => stickyRouteCandidateWeight({
1598
+ candidate,
1599
+ family: stickyRouteFamilyForModel(options.model.id),
1600
+ modelId: options.model.id,
1601
+ storage,
1602
+ }) === 0) &&
1603
+ routes.allRoutes.length > 0 &&
1604
+ routes.allRoutes.every((candidate) => quotaObservationIsFresh(candidate.quota, options.model.id))) {
1605
+ void response.body?.cancel().catch(() => { });
1606
+ if (preflight instanceof Response)
1607
+ void preflight.body?.cancel().catch(() => { });
1608
+ return noRouteResponse();
1609
+ }
1593
1610
  return completeRoute(route, preflight instanceof Response ? preflight : response);
1594
1611
  }
1595
1612
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.11.0",
3
+ "version": "2.11.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -36,7 +36,7 @@
36
36
  "prepublishOnly": "bun run build"
37
37
  },
38
38
  "dependencies": {
39
- "@cortexkit/anthropic-auth-core": "2.11.0"
39
+ "@cortexkit/anthropic-auth-core": "2.11.1"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",