@cortexkit/pi-anthropic-auth 2.9.1 → 2.10.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.
@@ -1,4 +1,4 @@
1
- import { CacheKeepManager, type CacheKeepStoreOptions, type HolderLiveness, type NativeAccountSnapshot } from '@cortexkit/anthropic-auth-core';
1
+ import { CacheKeepManager, type CacheKeepStoreOptions, type HolderLiveness, type NativeAccountSnapshot, type StickySessionRouter } from '@cortexkit/anthropic-auth-core';
2
2
  type TrackInput = Parameters<CacheKeepManager['track']>[0];
3
3
  type ManagerOptions = ConstructorParameters<typeof CacheKeepManager>[0];
4
4
  /** One Pi process owns only the sessions its lifecycle actually opened. */
@@ -20,6 +20,10 @@ export declare class PiCacheKeep {
20
20
  constructor(managerOptions: ManagerOptions, options: {
21
21
  storageId: (storagePath: string) => Promise<string>;
22
22
  read: (storagePath: string) => Promise<NativeAccountSnapshot>;
23
+ routing?: (storagePath: string) => {
24
+ snapshot: NativeAccountSnapshot | undefined;
25
+ router?: StickySessionRouter;
26
+ };
23
27
  persistence?: Partial<Pick<CacheKeepStoreOptions, 'root' | 'ownerOnly'>>;
24
28
  liveness?: HolderLiveness;
25
29
  restoreDelay?: (ms: number, signal?: AbortSignal) => Promise<void>;
package/dist/cachekeep.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { setTimeout as delay } from 'node:timers/promises';
3
- import { CacheKeepManager, CacheKeepStore, isCacheKeepSubagentsEnabled, logger, nativeAccountCanServe, readSessionCachePolicy, } from '@cortexkit/anthropic-auth-core';
3
+ import { CacheKeepManager, CacheKeepStore, isCacheKeepSubagentsEnabled, logger, nativeAccountCanServe, peekRoutingAccount, readSessionCachePolicy, remapModelId, } from '@cortexkit/anthropic-auth-core';
4
4
  import { version as pluginVersion } from '../package.json';
5
5
  import { PiCacheKeepClaim } from './cachekeep-claim.js';
6
6
  function accountKey(account) {
@@ -47,6 +47,17 @@ export class PiCacheKeep {
47
47
  };
48
48
  this.manager = new CacheKeepManager({
49
49
  ...managerOptions,
50
+ peekRoutingAccount: (target, route) => {
51
+ const session = this.sessions.get(route.sessionId);
52
+ const routing = this.options.routing?.(session?.storagePath ?? target.accountStoragePath ?? '');
53
+ return routing
54
+ ? peekRoutingAccount({
55
+ ...routing,
56
+ ...route,
57
+ modelId: route.modelId ? remapModelId(route.modelId) : undefined,
58
+ })
59
+ : managerOptions.peekRoutingAccount?.(target, route);
60
+ },
50
61
  setIntervalImpl: ((_callback, ms) => schedule(() => {
51
62
  this.ticking = this.manager
52
63
  .tick()
package/dist/native.d.ts CHANGED
@@ -28,6 +28,7 @@ export interface PiVaultPollOptions {
28
28
  clearInterval?: typeof globalThis.clearInterval;
29
29
  }
30
30
  export declare class PiNativeRuntime {
31
+ private publishedRuntime?;
31
32
  private readonly pendingReports;
32
33
  /** Join started failure reports, never model sends waiting for headers. */
33
34
  drainReports(): Promise<void>;
@@ -59,6 +60,8 @@ export declare class PiNativeRuntime {
59
60
  prime?: PiPrimeOptions;
60
61
  });
61
62
  service(): Promise<NativeAccountRuntime>;
63
+ /** Inspect only a completed runtime read; initialization is never awaited. */
64
+ peek(): NativeAccountSnapshot | undefined;
62
65
  routingPath(): Promise<string>;
63
66
  routingStorage(): Promise<{
64
67
  path: string;
@@ -82,6 +85,8 @@ export declare class PiNativeRuntime {
82
85
  markUsed(served: PiNativeAttempt, servingRuntime?: NativeAccountRuntime): Promise<void>;
83
86
  close(): Promise<void>;
84
87
  }
88
+ /** Inspect an existing context without creating a runtime or starting its I/O. */
89
+ export declare function peekPiNativeSnapshot(storagePath?: string): NativeAccountSnapshot | undefined;
85
90
  export declare function getPiNativeRuntime(storagePath?: string, options?: {
86
91
  connect?: () => Promise<NativeCustodyClient>;
87
92
  local?: NativeAccountRuntimeOptions['local'];
package/dist/native.js CHANGED
@@ -72,6 +72,7 @@ export function isNativeMigrationRequired(error) {
72
72
  /** How often Pi asks the vault for account changes, matching OpenCode's default. Model requests no longer rediscover a healthy roster, so this poll is how Pi notices a re-login or a newly added account. */
73
73
  export const PI_VAULT_POLL_INTERVAL_MS = 2000;
74
74
  export class PiNativeRuntime {
75
+ publishedRuntime;
75
76
  pendingReports = new Set();
76
77
  /** Join started failure reports, never model sends waiting for headers. */
77
78
  async drainReports() {
@@ -166,6 +167,7 @@ export class PiNativeRuntime {
166
167
  // the next poll or a request's bounded refresh retries it.
167
168
  void this.vaultWatch.ready.catch(() => { });
168
169
  }
170
+ this.publishedRuntime = runtime;
169
171
  return runtime;
170
172
  });
171
173
  // Initialization is lazy from the host's perspective; a path failure is
@@ -181,6 +183,10 @@ export class PiNativeRuntime {
181
183
  throw new Error('Pi native authentication is closed');
182
184
  return runtime;
183
185
  }
186
+ /** Inspect only a completed runtime read; initialization is never awaited. */
187
+ peek() {
188
+ return this.closed ? undefined : this.publishedRuntime?.peek?.();
189
+ }
184
190
  async routingPath() {
185
191
  return (await this.routingStorage()).path;
186
192
  }
@@ -390,6 +396,13 @@ export class PiNativeRuntime {
390
396
  return this.closing;
391
397
  }
392
398
  }
399
+ /** Inspect an existing context without creating a runtime or starting its I/O. */
400
+ export function peekPiNativeSnapshot(storagePath = getPiAccountStoragePath()) {
401
+ const contextKey = runtimeCacheKey(storagePath);
402
+ return [...runtimes.values()]
403
+ .find((entry) => entry.contextKey === contextKey)
404
+ ?.runtime.peek();
405
+ }
393
406
  export function getPiNativeRuntime(storagePath = getPiAccountStoragePath(), options = {}) {
394
407
  const contextKey = runtimeCacheKey(storagePath);
395
408
  const key = JSON.stringify([
package/dist/stream.js CHANGED
@@ -1,8 +1,8 @@
1
- import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, buildPrimeRequestBody, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, copyStreamResponseTiming, createAnthropicStreamCompletion, createDumpResponseObserver, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, 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, reportSessionCacheTouch, requestCacheLifetimeMs, resolveNativePoolPaths, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, stickyQuotaSnapshotIsFresh, stickyRetryAfterWithJitter, stickyRouteFamilyForModel, } from '@cortexkit/anthropic-auth-core';
1
+ import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, buildPrimeRequestBody, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, copyStreamResponseTiming, createAnthropicStreamCompletion, createDumpResponseObserver, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, 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, reportSessionCacheTouch, requestCacheLifetimeMs, resolveNativePoolPaths, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, stickyQuotaSnapshotIsFresh, stickyRetryAfterWithJitter, 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';
5
- import { getPiNativeRuntime, piAttemptAccessToken, } from './native.js';
5
+ import { getPiNativeRuntime, peekPiNativeSnapshot, piAttemptAccessToken, } 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';
@@ -198,8 +198,32 @@ function applyPiOAuthRequestHeaders(headers, accessToken, options) {
198
198
  headers.set('anthropic-beta', mergeAnthropicBetas(headers.get('anthropic-beta'), [FAST_MODE_BETA]));
199
199
  return headers;
200
200
  }
201
+ function piBillingPayer(attempt) {
202
+ return {
203
+ credentialId: attempt.source === 'vault'
204
+ ? attempt.receipt.credentialId
205
+ : localMessageThreadCredential(attempt.admission.binding),
206
+ accountId: attempt.accountIdentity,
207
+ };
208
+ }
201
209
  const nativePrewarmAttempts = new Map();
202
210
  const piCacheKeep = new PiCacheKeep({
211
+ billingRequest(target, attempt) {
212
+ const entry = nativePrewarmAttempts.get(attempt.id);
213
+ if (!entry)
214
+ return undefined;
215
+ return {
216
+ ...piBillingPayer(entry.served),
217
+ sessionId: target.policyState?.ownerSessionId ?? target.id,
218
+ model: JSON.parse(target.bodyText).model,
219
+ requestKind: 'keep_warm',
220
+ chargeBasis: 'subscription_included',
221
+ cache: {
222
+ ttlMs: requestCacheLifetimeMs(target.bodyText),
223
+ warming: { on: true },
224
+ },
225
+ };
226
+ },
203
227
  fetchImpl: fetchPiOAuth,
204
228
  loadStorage: async () => (await getPiNativeRuntime().view()).policyStorage,
205
229
  onTrackedSessionsChanged: (sessions) => getPiCacheKeepRegistry().publish(sessions),
@@ -272,6 +296,15 @@ const piCacheKeep = new PiCacheKeep({
272
296
  }, {
273
297
  storageId: async (storagePath) => (await resolveNativePoolPaths(storagePath, undefined, LEGACY_STATE_LAYOUT)).storageId,
274
298
  read: (storagePath) => getPiNativeRuntime(storagePath).view(),
299
+ routing: (storagePath) => {
300
+ const snapshot = peekPiNativeSnapshot(storagePath);
301
+ return {
302
+ snapshot,
303
+ router: snapshot?.routingPath
304
+ ? stickyRouters.get(snapshot.routingPath)
305
+ : undefined,
306
+ };
307
+ },
275
308
  });
276
309
  const cacheKeepManager = piCacheKeep.manager;
277
310
  export function startPiCacheKeepSession(storagePath, sessionId) {
@@ -538,6 +571,26 @@ async function sendAnthropicRequest(options, deps = {}) {
538
571
  ...(options.prime && { requestClass: 'auxiliary' }),
539
572
  });
540
573
  const relayAffinity = options.streamOptions?.sessionId ?? null;
574
+ const billingInput = (attempt, apiSubject) => {
575
+ // The session runner matches billing reports to session transcripts, and
576
+ // Prime is account-wide with no session, so it sends no billing report.
577
+ if (options.prime || !relayAffinity || (!attempt && !apiSubject))
578
+ return undefined;
579
+ const credentialId = attempt
580
+ ? piBillingPayer(attempt).credentialId
581
+ : apiSubject?.credentialFingerprint;
582
+ if (!credentialId)
583
+ return undefined;
584
+ const ttlMs = requestCacheLifetimeMs(wireBodyText);
585
+ return {
586
+ ...(attempt ? piBillingPayer(attempt) : { credentialId }),
587
+ sessionId: relayAffinity,
588
+ model: typeof body.model === 'string' ? body.model : options.model.id,
589
+ requestKind: options.requestOrigin === 'direct' ? 'generate' : 'primary',
590
+ chargeBasis: options.apiAccount ? 'metered_api' : 'subscription_included',
591
+ ...(ttlMs > 0 ? { cache: { ttlMs } } : {}),
592
+ };
593
+ };
541
594
  let input = options.apiAccount
542
595
  ? new URL('https://api.anthropic.com/v1/messages')
543
596
  : buildPiOAuthMessagesUrl(options.model.baseUrl);
@@ -684,7 +737,7 @@ async function sendAnthropicRequest(options, deps = {}) {
684
737
  // OAuth bodies go gzipped as Claude Code sends them; `bodyText` stays
685
738
  // the signed identity text for dumps and CacheKeep.
686
739
  if (options.apiAccount || typeof init.body !== 'string')
687
- return scope.redactResponse(await fetchResponse(input, init));
740
+ return scope.redactResponse(await physicalFetch(() => fetchResponse(input, init)));
688
741
  return scope.redactResponse(await sendWithRequestGzip({
689
742
  url: input,
690
743
  body: init.body,
@@ -694,14 +747,18 @@ async function sendAnthropicRequest(options, deps = {}) {
694
747
  await options.prime?.beforeSend();
695
748
  init.signal?.throwIfAborted();
696
749
  assertHostAuthorityStable();
697
- return fetchResponse(input, {
750
+ return physicalFetch(() => fetchResponse(input, {
698
751
  ...init,
699
752
  body: wireBody,
700
753
  headers: wireHeaders,
701
- });
754
+ }));
702
755
  },
703
756
  }));
704
757
  };
758
+ const physicalFetch = (send) => {
759
+ const billing = billingInput(attempt, apiSubject);
760
+ return billing ? withAnthropicBilling(billing, send) : send();
761
+ };
705
762
  let response;
706
763
  try {
707
764
  response = await send();
@@ -821,6 +878,7 @@ async function sendAnthropicRequest(options, deps = {}) {
821
878
  authorizedHeaders.set('authorization', `Bearer ${access}`);
822
879
  return {
823
880
  headers: authorizedHeaders,
881
+ billing: billingInput(attempt),
824
882
  errorSecrets: [access],
825
883
  onUpstreamStatus: (status) => {
826
884
  if (status >= 200 && status < 300)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.9.1",
3
+ "version": "2.10.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.9.1"
39
+ "@cortexkit/anthropic-auth-core": "2.10.0"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",