@cortexkit/pi-anthropic-auth 2.12.0 → 2.13.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,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, getMaxSameAccountWait, getPersistedLogLevel, getRoutingMode, isCache1hPersistentlyEnabled, isCacheKeepAlways, isCacheKeepHybridActive, isCacheKeepPersistentlyEnabled, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isPrimePersistentlyEnabled, isVaultHosted, nativeAccountCanServe, setDumpEnabled, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from '@cortexkit/anthropic-auth-core';
2
+ import { authorize, buildClaudeQuotaSummary, buildPrimeAccountStatuses, claudeGatewayStatusNotes, DEFAULT_KILLSWITCH_THRESHOLDS, exchange, executeCacheKeepCommand, executePrimeCommand, formatEnrollmentStatus, formatNativeAccountState, formatOAuthAccountTier, getCache1hPersistentMode, getCacheKeepWindow, getMaxSameAccountWait, getPersistedLogLevel, getRoutingMode, isCache1hPersistentlyEnabled, isCacheKeepAlways, isCacheKeepHybridActive, isCacheKeepPersistentlyEnabled, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isPrimePersistentlyEnabled, isVaultHosted, nativeAccountCanServe, setDumpEnabled, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } 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';
@@ -293,8 +293,9 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
293
293
  const storage = snapshot.policyStorage;
294
294
  const settingsStatus = (summary) => {
295
295
  const status = runtime.getSettingsStatus?.();
296
+ const relayNotes = runtime.getRelayStatusNotes?.() ?? [];
296
297
  if (!status)
297
- return summary;
298
+ return [summary, ...relayNotes].join('\n');
298
299
  const { file } = status;
299
300
  return [
300
301
  summary,
@@ -308,6 +309,8 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
308
309
  ...file.invalidKeys.map((key) => `Invalid setting: ${key}`),
309
310
  ...file.ignoredModelKeys.map(({ setting, model }) => `Ignored model key: ${setting}.${model}`),
310
311
  ...file.duplicateKeys.map((key) => `Duplicate setting: ${key}`),
312
+ ...claudeGatewayStatusNotes(file.gatewayIgnored, status.values.gateway),
313
+ ...relayNotes,
311
314
  'Settings (no model):',
312
315
  ...Object.entries(status.values).map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`),
313
316
  ...Object.entries(status.modelOverrides).flatMap(([key, rows]) => (rows ?? []).map(({ model, value }) => ` ${key} [${model}]: ${JSON.stringify(value)}`)),
package/dist/native.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type AccountStorage, type NativeAccountRuntime, type NativeAccountRuntimeOptions, type NativeAccountSnapshot, type NativeCustodyClient, type NativeCustodyReceipt, type NativeCustodyReporterSource, type NativeLocalExternalPolicy, type NativeRefreshResult, type RoutingChoice } from '@cortexkit/anthropic-auth-core';
1
+ import { type AccountStorage, type ClaudeGateway, 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
  import { type PiSettingsOptions } from './settings.ts';
4
4
  export type PiNativeAttempt = {
@@ -70,6 +70,8 @@ export declare class PiNativeRuntime {
70
70
  peek(): NativeAccountSnapshot | undefined;
71
71
  /** Resolve target settings from the initialized service without request I/O. */
72
72
  resolveSettings(stored: AccountStorage, model?: string): AccountStorage;
73
+ /** The user's gateway for OAuth model requests, from memory only. */
74
+ claudeGateway(): ClaudeGateway | undefined;
73
75
  routingPath(): Promise<string>;
74
76
  routingStorage(): Promise<{
75
77
  path: string;
@@ -105,4 +107,6 @@ export declare function getPiNativeRuntime(storagePath?: string, options?: {
105
107
  settings?: PiSettingsOptions;
106
108
  }): PiNativeRuntime;
107
109
  export declare function closePiNativeRuntime(storagePath?: string): Promise<void>;
110
+ /** The gateway for a context's model requests, without starting account I/O. */
111
+ export declare function piClaudeGatewayFromMemory(storagePath?: string): ClaudeGateway | undefined;
108
112
  export {};
package/dist/native.js CHANGED
@@ -222,6 +222,10 @@ export class PiNativeRuntime {
222
222
  resolveSettings(stored, model) {
223
223
  return this.publishedRuntime?.resolveSettings?.(stored, model) ?? stored;
224
224
  }
225
+ /** The user's gateway for OAuth model requests, from memory only. */
226
+ claudeGateway() {
227
+ return this.closed ? undefined : this.publishedRuntime?.getClaudeGateway?.();
228
+ }
225
229
  async routingPath() {
226
230
  return (await this.routingStorage()).path;
227
231
  }
@@ -497,3 +501,7 @@ export function closePiNativeRuntime(storagePath = getPiAccountStoragePath()) {
497
501
  // must also join those closes, not only the runtimes still in the cache.
498
502
  return Promise.all(closingRuntimes.get(resolve(storagePath)) ?? []).then(() => { });
499
503
  }
504
+ /** The gateway for a context's model requests, without starting account I/O. */
505
+ export function piClaudeGatewayFromMemory(storagePath = getPiAccountStoragePath()) {
506
+ return cachedPiNativeRuntime(storagePath)?.claudeGateway();
507
+ }
package/dist/stream.js CHANGED
@@ -1,12 +1,12 @@
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';
1
+ import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyClaudeGatewayHeaders, applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, buildPrimeRequestBody, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, CLAUDE_CODE_ACCEPT_ENCODING, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, claudeGatewayHeaderValues, claudeGatewayModelUrl, 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, requestShortestCacheLifetimeMs, resolveNativePoolPaths, routingCandidates, routingChoiceMatches, routingWarmCredential, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, startRoutingWait, stickyQuotaSnapshotIsFresh, stickyRetainRetryHeaders, stickyRetryAfterWithJitter, stickyRouteCandidateWeight, stickyRouteFamilyForModel, warnClaudeGatewayRelayIgnored, 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, piThreadCacheSlot, } from './convert.js';
5
- import { getPiNativeRuntime, peekPiNativeSnapshot, piAttemptAccessToken, resolvePiSettingsFromMemory, } from './native.js';
5
+ import { getPiNativeRuntime, peekPiNativeSnapshot, piAttemptAccessToken, piClaudeGatewayFromMemory, resolvePiSettingsFromMemory, } from './native.js';
6
6
  import { getPiAccountStoragePath } from './paths.js';
7
7
  import { registerPiPrimeSender } from './prime.js';
8
8
  import { markPiAccountHold, withPiQuotaWait, } from './quota-wait.js';
9
- import { buildPiOAuthMessagesUrl, fetchPiOAuth, fetchPiStreamResponse, requirePiOAuthOrigin, } from './transport.js';
9
+ import { buildPiOAuthMessagesUrl, createPiOAuthModelFetch, fetchPiOAuth, fetchPiStreamResponse, requirePiOAuthOrigin, } from './transport.js';
10
10
  const messageThreads = new MessageThreadTracker();
11
11
  const dumpResponseObservers = new WeakMap();
12
12
  // Each session owns its lease; storage identifies which host may end it.
@@ -223,12 +223,15 @@ const piCacheKeep = new PiCacheKeep({
223
223
  requestKind: 'keep_warm',
224
224
  chargeBasis: 'subscription_included',
225
225
  cache: {
226
- ttlMs: requestCacheLifetimeMs(target.bodyText),
226
+ ttlMs: requestShortestCacheLifetimeMs(target.bodyText),
227
227
  warming: { on: true },
228
228
  },
229
229
  };
230
230
  },
231
231
  fetchImpl: fetchPiOAuth,
232
+ // A keep-warm is a model request, so it follows the current gateway of
233
+ // the target's own runtime.
234
+ fetchForTarget: (target) => createPiOAuthModelFetch(() => piClaudeGatewayFromMemory(target.accountStoragePath ?? getPiAccountStoragePath())),
232
235
  loadStorage: async () => (await getPiNativeRuntime().view()).policyStorage,
233
236
  resolveSettings: resolvePiSettingsFromMemory,
234
237
  onTrackedSessionsChanged: (sessions) => getPiCacheKeepRegistry().publish(sessions),
@@ -595,7 +598,7 @@ async function sendAnthropicRequest(options, deps = {}) {
595
598
  : apiSubject?.credentialFingerprint;
596
599
  if (!credentialId)
597
600
  return undefined;
598
- const ttlMs = requestCacheLifetimeMs(wireBodyText);
601
+ const ttlMs = requestShortestCacheLifetimeMs(wireBodyText);
599
602
  const sessionId = relayAffinity;
600
603
  return {
601
604
  ...(attempt ? piBillingPayer(attempt) : { credentialId }),
@@ -619,6 +622,17 @@ async function sendAnthropicRequest(options, deps = {}) {
619
622
  let input = options.apiAccount
620
623
  ? new URL('https://api.anthropic.com/v1/messages')
621
624
  : buildPiOAuthMessagesUrl(options.model.baseUrl);
625
+ // The user's gateway from their own settings file takes OAuth model
626
+ // requests, Prime included. It is read once, so the relay, thread, gzip and
627
+ // URL choices below agree. `input` stays the Anthropic URL for CacheKeep,
628
+ // which applies the gateway current at each warm.
629
+ const configuredGateway = options.apiAccount
630
+ ? undefined
631
+ : servingRuntime.getClaudeGateway?.();
632
+ const gatewayUrl = configuredGateway
633
+ ? claudeGatewayModelUrl(input, configuredGateway)
634
+ : undefined;
635
+ const gateway = gatewayUrl ? configuredGateway : undefined;
622
636
  const init = {
623
637
  method: 'POST',
624
638
  headers,
@@ -700,12 +714,20 @@ async function sendAnthropicRequest(options, deps = {}) {
700
714
  throw new Error('Pi native OAuth route identity changed');
701
715
  return attempt;
702
716
  };
703
- const relayConfig = options.apiAccount
717
+ let relayConfig = options.apiAccount
704
718
  ? null
705
719
  : await (await native.service()).getRelayConfig();
720
+ // A gateway takes the request instead of the relay, with no relay attempt
721
+ // and no fallback to api.anthropic.com.
722
+ if (gateway && relayConfig) {
723
+ warnClaudeGatewayRelayIgnored(gateway);
724
+ relayConfig = null;
725
+ }
706
726
  let threadRequest;
707
727
  if (!options.apiAccount &&
708
728
  !options.prime &&
729
+ // Gateways may refuse the thread route: send full requests.
730
+ !gateway &&
709
731
  isPiPrimaryThreadRequest(options.storagePath, options.streamOptions, options.requestOrigin) &&
710
732
  (!relayConfig ||
711
733
  effectiveRelayTransport(relayConfig.transport, relayConfig.url) !==
@@ -761,8 +783,18 @@ async function sendAnthropicRequest(options, deps = {}) {
761
783
  await options.prime?.beforeSend();
762
784
  init.signal?.throwIfAborted();
763
785
  assertHostAuthorityStable();
764
- const scope = createProviderErrorResponseScope([secret], 'event-stream');
786
+ const scope = createProviderErrorResponseScope(
787
+ // A gateway error may echo the gateway's own header values.
788
+ [secret, ...claudeGatewayHeaderValues(gateway)], 'event-stream');
765
789
  physical.scope = scope;
790
+ // Only the destination and the gateway's own headers change; the body
791
+ // goes uncompressed, as Claude Code compresses only to
792
+ // api.anthropic.com.
793
+ if (gateway && gatewayUrl) {
794
+ requirePiOAuthOrigin(gatewayUrl.toString(), gateway);
795
+ const gatewayHeaders = applyClaudeGatewayHeaders(new Headers(headers), gateway);
796
+ return scope.redactResponse(await physicalFetch(() => fetchResponse(gatewayUrl, { ...init, headers: gatewayHeaders })));
797
+ }
766
798
  // OAuth bodies go gzipped as Claude Code sends them; `bodyText` stays
767
799
  // the signed identity text for dumps and CacheKeep.
768
800
  if (options.apiAccount || typeof init.body !== 'string')
@@ -846,7 +878,9 @@ async function sendAnthropicRequest(options, deps = {}) {
846
878
  catch (caught) {
847
879
  // No response leaves this send, so its credentials retire here.
848
880
  physical.scope?.dispose();
849
- const scope = createProviderErrorResponseScope([secret], 'event-stream');
881
+ const scope = createProviderErrorResponseScope(
882
+ // A gateway error may echo the gateway's own header values.
883
+ [secret, ...claudeGatewayHeaderValues(gateway)], 'event-stream');
850
884
  const error = scope.redactError(caught);
851
885
  scope.dispose();
852
886
  await dumpDirectRequest({
@@ -1,6 +1,17 @@
1
- /** Model base URLs and remembered cache-warm URLs must send OAuth tokens only to Anthropic’s HTTPS server. */
2
- export declare function requirePiOAuthOrigin(value: string): URL;
1
+ import { type ClaudeGateway } from '@cortexkit/anthropic-auth-core';
2
+ /**
3
+ * Model base URLs and remembered cache-warm URLs must send OAuth tokens only
4
+ * to Anthropic’s HTTPS server. Pass `gateway` only for a model request: it is
5
+ * the user's gateway from their own settings file, never provider config.
6
+ */
7
+ export declare function requirePiOAuthOrigin(value: string, gateway?: ClaudeGateway): URL;
3
8
  export declare function buildPiOAuthMessagesUrl(baseUrl: string): URL;
4
9
  /** Reject redirects rather than letting an approved OAuth destination forward the request. */
5
10
  export declare const fetchPiOAuth: typeof fetch;
6
11
  export declare function fetchPiStreamResponse(input: Parameters<typeof fetch>[0], init: Parameters<typeof fetch>[1], fetchImpl?: typeof fetch): Promise<Response>;
12
+ /**
13
+ * Fetch for OAuth model requests: like fetchPiOAuth, but a model request to
14
+ * api.anthropic.com goes to the user's gateway, read on every call, with its
15
+ * headers. Keep-warm sends use it, so they follow the current settings.
16
+ */
17
+ export declare function createPiOAuthModelFetch(gateway: () => ClaudeGateway | undefined): typeof fetch;
package/dist/transport.js CHANGED
@@ -1,14 +1,18 @@
1
1
  import { PerformanceObserver, } from 'node:perf_hooks';
2
- import { copyStreamResponseTiming, createAnthropicOAuthFetch, requireAnthropicOAuthOrigin, } from '@cortexkit/anthropic-auth-core';
2
+ import { copyStreamResponseTiming, createAnthropicOAuthFetch, createClaudeModelFetch, requireAnthropicOAuthOrigin, } from '@cortexkit/anthropic-auth-core';
3
3
  // Pi keeps its own refusal wording; Core supplies the origin rule itself.
4
4
  const PI_OAUTH_ORIGIN = {
5
5
  refusal: (reason) => new Error(reason === 'unparseable'
6
6
  ? 'Native OAuth requires the official Anthropic HTTPS origin'
7
7
  : 'Native OAuth requires the official Anthropic HTTPS origin without URL userinfo'),
8
8
  };
9
- /** Model base URLs and remembered cache-warm URLs must send OAuth tokens only to Anthropic’s HTTPS server. */
10
- export function requirePiOAuthOrigin(value) {
11
- return requireAnthropicOAuthOrigin(value, PI_OAUTH_ORIGIN);
9
+ /**
10
+ * Model base URLs and remembered cache-warm URLs must send OAuth tokens only
11
+ * to Anthropic’s HTTPS server. Pass `gateway` only for a model request: it is
12
+ * the user's gateway from their own settings file, never provider config.
13
+ */
14
+ export function requirePiOAuthOrigin(value, gateway) {
15
+ return requireAnthropicOAuthOrigin(value, gateway ? { ...PI_OAUTH_ORIGIN, gateway } : PI_OAUTH_ORIGIN);
12
16
  }
13
17
  export function buildPiOAuthMessagesUrl(baseUrl) {
14
18
  return new URL('/v1/messages?beta=true', requirePiOAuthOrigin(baseUrl));
@@ -103,3 +107,11 @@ export async function fetchPiStreamResponse(input, init, fetchImpl = globalThis.
103
107
  throw error;
104
108
  }
105
109
  }
110
+ /**
111
+ * Fetch for OAuth model requests: like fetchPiOAuth, but a model request to
112
+ * api.anthropic.com goes to the user's gateway, read on every call, with its
113
+ * headers. Keep-warm sends use it, so they follow the current settings.
114
+ */
115
+ export function createPiOAuthModelFetch(gateway) {
116
+ return createClaudeModelFetch({ origin: PI_OAUTH_ORIGIN, gateway });
117
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.12.0",
3
+ "version": "2.13.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.12.0"
39
+ "@cortexkit/anthropic-auth-core": "2.13.1"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",