@cortexkit/pi-anthropic-auth 2.6.0 → 2.7.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/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 { CACHE_KEEP_PREWARM_LEAD_MS, CACHE_KEEP_TTL_MS, CacheKeepManager, CacheKeepStore, isCacheKeepHybridActive, isCacheKeepSubagentsEnabled, logger, nativeAccountCanServe, } from '@cortexkit/anthropic-auth-core';
3
+ import { CacheKeepManager, CacheKeepStore, isCacheKeepSubagentsEnabled, logger, nativeAccountCanServe, readSessionCachePolicy, } 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) {
@@ -36,6 +36,15 @@ export class PiCacheKeep {
36
36
  const schedule = managerOptions.setIntervalImpl ?? setInterval;
37
37
  this.schedule = schedule;
38
38
  this.cancel = managerOptions.clearIntervalImpl ?? clearInterval;
39
+ const persistWarm = async (target) => {
40
+ const session = this.sessions.get(target.id);
41
+ if (this.stopping || !session?.identity)
42
+ return false;
43
+ return session.store.reserveWarm({
44
+ ...target,
45
+ oauthAccountIdentity: session.identity,
46
+ });
47
+ };
39
48
  this.manager = new CacheKeepManager({
40
49
  ...managerOptions,
41
50
  setIntervalImpl: ((_callback, ms) => schedule(() => {
@@ -53,6 +62,10 @@ export class PiCacheKeep {
53
62
  });
54
63
  managerOptions.onTargetChanged?.(target);
55
64
  },
65
+ reserveWarm: persistWarm,
66
+ settleWarm: (target) => this.manager.isCurrentTarget(target)
67
+ ? persistWarm(target)
68
+ : Promise.resolve(false),
56
69
  onTargetRemoved: (id) => {
57
70
  this.restored.delete(id);
58
71
  if (!this.stopping)
@@ -197,7 +210,7 @@ export class PiCacheKeep {
197
210
  this.stopping ||
198
211
  this.manager.trackedRequest(entry.id))
199
212
  return undefined;
200
- if (!snapshot || !isCacheKeepHybridActive(snapshot.policyStorage))
213
+ if (!snapshot)
201
214
  return 'invalid';
202
215
  const account = snapshot.accounts.find((row) => accountKey(row) === entry.oauthAccountIdentity);
203
216
  if (!account)
@@ -205,6 +218,7 @@ export class PiCacheKeep {
205
218
  if (account.type !== 'oauth' || !nativeAccountCanServe(account))
206
219
  return 'account-gone';
207
220
  if (entry.isSubagent &&
221
+ readSessionCachePolicy(entry.policyState?.ownerSessionId ?? entry.id, true)?.keep_warm === undefined &&
208
222
  !isCacheKeepSubagentsEnabled(snapshot.policyStorage))
209
223
  return 'invalid';
210
224
  session.identity = accountKey(account);
@@ -258,16 +272,9 @@ export class PiCacheKeep {
258
272
  session.identity = accountKey(account);
259
273
  // Claim I/O may finish after the response, or even during shutdown. Keep
260
274
  // that accepted body, but never grant the cache the time spent waiting.
261
- const ttlMs = input.ttlMs ?? CACHE_KEEP_TTL_MS;
262
275
  const result = this.manager.track({
263
276
  ...input,
264
- retained: input.retained ?? {
265
- cacheExpiresAt: acceptedAt + ttlMs,
266
- nextPrewarmAt: acceptedAt + ttlMs - CACHE_KEEP_PREWARM_LEAD_MS,
267
- ttlMs,
268
- lastTouchAt: acceptedAt,
269
- lastTouchKind: 'response',
270
- },
277
+ acceptedAt,
271
278
  });
272
279
  if (result.tracked)
273
280
  this.restored.delete(sessionId);
package/dist/convert.js CHANGED
@@ -1,4 +1,4 @@
1
- import { applyClaudeCodeMetadata, applyMidConversationOutputConfig, applyRunnerTurnNotes, 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';
1
+ import { applyClaudeCodeMetadata, applyMidConversationOutputConfig, applyRunnerTurnNotes, applySessionCacheTtl, 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, readSessionCachePolicy, requestCacheLifetimeMs, 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
@@ -625,7 +625,8 @@ export async function buildAnthropicRequest(modelId, context, options, cache, fa
625
625
  isOAuth: !!identity,
626
626
  });
627
627
  addEphemeralCacheControl(body);
628
- applyCacheMode(body, cache.enabled, cache.mode);
628
+ const cachePolicy = readSessionCachePolicy(options?.sessionId, !!identity);
629
+ applyCacheMode(body, cachePolicy?.ttl !== undefined ? cachePolicy.ttl !== 'none' : cache.enabled, cache.mode);
629
630
  if (identity) {
630
631
  applyThinkingBindingControls(body, controls.thinkingPrefixMismatchBehavior ?? 'account-default');
631
632
  applyClaudeCodeMetadata(body, identity);
@@ -635,6 +636,7 @@ export async function buildAnthropicRequest(modelId, context, options, cache, fa
635
636
  : undefined;
636
637
  if (replaced !== undefined)
637
638
  body = { ...replaced, stream: true };
639
+ applySessionCacheTtl(body, cachePolicy?.ttl);
638
640
  // As in Pi's native adapter, replacements must still request SSE. Hooks own
639
641
  // the validity of their other edits and must not add a fifth cache breakpoint:
640
642
  // the provider's existing layout may already use Anthropic's four slots.
@@ -657,10 +659,6 @@ export async function buildAnthropicRequest(modelId, context, options, cache, fa
657
659
  // Sticky routing uses the longest TTL actually sent to bound how long a
658
660
  // session waits on its account. Include hook edits, not the account setting;
659
661
  // a cache_control key inside tool data is not a cache breakpoint.
660
- let cacheTtlMs = PROMPT_CACHE_DEFAULT_TTL_MS;
661
- walkCacheControlHolders(sentBody, (holder) => {
662
- if (holder.cache_control.ttl === '1h')
663
- cacheTtlMs = PROMPT_CACHE_1H_TTL_MS;
664
- });
662
+ const cacheTtlMs = requestCacheLifetimeMs(sentBody);
665
663
  return { body, bodyText, toolNames, cacheTtlMs };
666
664
  }
package/dist/stream.d.ts CHANGED
@@ -44,6 +44,7 @@ declare function sendAnthropicRequest(options: {
44
44
  effortTransitions?: readonly MidConversationEffortTransition[];
45
45
  onResolvedToolNames?: (toolNames: ReadonlyMap<string, string>) => void;
46
46
  onThreadPrepared?: (fail: () => void) => void;
47
+ onCacheUsageRecorder?: (record: (usage?: Record<string, number>) => void) => void;
47
48
  prime?: {
48
49
  beforeSend: () => Promise<void>;
49
50
  onServed: (attempt: PiNativeAttempt) => void;
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_ENTRYPOINT, CLAUDE_CODE_IDENTITY, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createSseFramer, createStickyNoRouteResponse, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, 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, parseSseFrame, prepareMessageThreadRequest, QuotaManager, quotaBackoffActive, quotaExhaustionFromHeaders, quotaRefusalTiming, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, 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, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createSseFramer, createStickyNoRouteResponse, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, 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';
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';
@@ -251,14 +251,15 @@ const piCacheKeep = new PiCacheKeep({
251
251
  });
252
252
  return rotatedHeaders;
253
253
  },
254
- onResponse: async ({ target, attempt, status, receivedAt }) => {
254
+ onResponse: async ({ target, attempt, status, receivedAt, bodyText }) => {
255
255
  const entry = nativePrewarmAttempts.get(attempt.id);
256
256
  if (entry &&
257
257
  status >= 200 &&
258
258
  status < 300 &&
259
259
  !attempt.signal?.aborted &&
260
- !target.sourceWarm)
261
- sessionCacheActivity.recordPrewarm(target.id, target.oauthAccountId ?? STICKY_ROUTING_MAIN_ACCOUNT_ID, receivedAt);
260
+ !target.sourceWarm &&
261
+ cacheKeepManager.isCurrentTarget(target))
262
+ sessionCacheActivity.recordPrewarm(target.id, target.oauthAccountId ?? STICKY_ROUTING_MAIN_ACCOUNT_ID, receivedAt, requestCacheLifetimeMs(bodyText));
262
263
  if (entry && status === 401 && !entry.reported)
263
264
  await entry.runtime.report(entry.served, status, 'direct').catch(() => {
264
265
  logger.warn('native-auth', 'Pi CacheKeep auth-failure report unavailable');
@@ -452,6 +453,7 @@ export function sendPiPrimeRequest(options) {
452
453
  }
453
454
  registerPiPrimeSender(sendPiPrimeRequest);
454
455
  async function sendAnthropicRequest(options, deps = {}) {
456
+ options.onCacheUsageRecorder?.(() => { });
455
457
  assertHostAuthorityStable();
456
458
  const fetchImpl = deps.fetch ?? globalThis.fetch;
457
459
  const keep = deps.cacheKeep ?? cacheKeepManager;
@@ -526,11 +528,26 @@ async function sendAnthropicRequest(options, deps = {}) {
526
528
  signal: options.streamOptions?.signal,
527
529
  ...(!options.apiAccount && { redirect: 'error' }),
528
530
  };
529
- const trackAcceptedRequest = () => {
531
+ const cacheAccepted = new Set();
532
+ const trackAcceptedRequest = (attempt, sentBody = wireBodyText) => {
530
533
  if (options.prime || options.apiAccount || init.signal?.aborted)
531
534
  return;
532
- if (relayAffinity)
533
- sessionCacheActivity.record(relayAffinity, routeId, cacheTtlMs);
535
+ if (cacheAccepted.has(attempt))
536
+ return;
537
+ cacheAccepted.add(attempt);
538
+ const at = Date.now();
539
+ const appliedTtl = requestCacheLifetimeMs(sentBody);
540
+ const localTtl = readSessionCachePolicy(relayAffinity, true)?.ttl !== undefined
541
+ ? appliedTtl
542
+ : cacheTtlMs || PROMPT_CACHE_DEFAULT_TTL_MS;
543
+ if (relayAffinity) {
544
+ sessionCacheActivity.record(relayAffinity, routeId, localTtl);
545
+ reportSessionCacheTouch(relayAffinity, {
546
+ at,
547
+ ttlMs: appliedTtl,
548
+ source: 'response',
549
+ });
550
+ }
534
551
  const target = {
535
552
  sessionId: relayAffinity,
536
553
  url: input.toString(),
@@ -538,15 +555,22 @@ async function sendAnthropicRequest(options, deps = {}) {
538
555
  bodyText,
539
556
  storage,
540
557
  cacheMode: isCacheKeepHybridActive(storage) ? 'hybrid' : 'disabled',
541
- ttlMs: cacheTtlMs,
558
+ ttlMs: localTtl,
542
559
  oauthAccountId: routeId,
543
560
  oauthAccountIdentity: verifiedUuid,
544
561
  accountStoragePath: options.storagePath,
545
562
  };
546
- if (deps.cacheKeep)
547
- keep.track(target);
548
- else
549
- void piCacheKeep.trackAccepted(target, snapshot);
563
+ const tracked = deps.cacheKeep
564
+ ? Promise.resolve(keep.track(target))
565
+ : piCacheKeep.trackAccepted(target, snapshot);
566
+ let latestUsage = {};
567
+ options.onCacheUsageRecorder?.((usage) => {
568
+ if (!usage || init.signal?.aborted || !relayAffinity)
569
+ return;
570
+ const merged = { ...latestUsage, ...usage };
571
+ latestUsage = merged;
572
+ void tracked.then(() => keep.recordAcceptedUsage(relayAffinity, bodyText, merged));
573
+ });
550
574
  };
551
575
  const reported = new Set();
552
576
  let retried401 = false;
@@ -732,7 +756,7 @@ async function sendAnthropicRequest(options, deps = {}) {
732
756
  native.usagePublications.publish(() => servingRuntime.publishApi(subject, { lastUsed: Date.now() }, native.usagePublications.signal));
733
757
  }
734
758
  if (attempt && response.ok) {
735
- trackAcceptedRequest();
759
+ trackAcceptedRequest(attempt);
736
760
  markServed(attempt);
737
761
  }
738
762
  return response;
@@ -761,12 +785,15 @@ async function sendAnthropicRequest(options, deps = {}) {
761
785
  relayAttempt = attempt;
762
786
  lastTransport = 'relay';
763
787
  const authorizedHeaders = new Headers(headers);
788
+ const sentBody = wireBodyText;
764
789
  const access = piAttemptAccessToken(attempt);
765
790
  authorizedHeaders.set('authorization', `Bearer ${access}`);
766
791
  return {
767
792
  headers: authorizedHeaders,
768
793
  errorSecrets: [access],
769
794
  onUpstreamStatus: (status) => {
795
+ if (status >= 200 && status < 300)
796
+ trackAcceptedRequest(attempt, sentBody);
770
797
  if (status === 401) {
771
798
  relay401Attempt = attempt;
772
799
  // The relay can report an upstream 401 after returning the streaming response.
@@ -814,7 +841,10 @@ async function sendAnthropicRequest(options, deps = {}) {
814
841
  void response.body?.cancel().catch(() => { });
815
842
  throw new Error('Pi Prime relay response has no upstream provenance');
816
843
  }
817
- trackAcceptedRequest();
844
+ // HTTP relays forward the accepted status even without a request-id.
845
+ // Optimistic WebSocket responses must wait for their real upstream status.
846
+ if (response.headers.get('x-cortexkit-relay-optimistic') !== 'true')
847
+ trackAcceptedRequest(relayAttempt);
818
848
  markServed(relayAttempt);
819
849
  }
820
850
  return response;
@@ -1485,6 +1515,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1485
1515
  buildPiOAuthMessagesUrl(model.baseUrl);
1486
1516
  const storagePath = getPiAccountStoragePath();
1487
1517
  let toolNames = new Map();
1518
+ let recordCacheUsage;
1488
1519
  const request = {
1489
1520
  model,
1490
1521
  context,
@@ -1494,6 +1525,9 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1494
1525
  onThreadPrepared: (fail) => {
1495
1526
  failThread = fail;
1496
1527
  },
1528
+ onCacheUsageRecorder: (record) => {
1529
+ recordCacheUsage = record;
1530
+ },
1497
1531
  effortTransitions,
1498
1532
  onResolvedToolNames: (names) => {
1499
1533
  toolNames = names;
@@ -1553,6 +1587,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1553
1587
  const blocks = output.content;
1554
1588
  for await (const event of parseSse(response)) {
1555
1589
  if (event.type === 'message_start') {
1590
+ recordCacheUsage?.(event.message?.usage);
1556
1591
  updateUsage(model, output, event.message?.usage);
1557
1592
  }
1558
1593
  else if (event.type === 'content_block_start') {
@@ -1695,6 +1730,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1695
1730
  }
1696
1731
  }
1697
1732
  else if (event.type === 'message_delta') {
1733
+ recordCacheUsage?.(event.usage);
1698
1734
  output.stopReason = mapStopReason(String(event.delta?.stop_reason ?? ''));
1699
1735
  updateUsage(model, output, event.usage);
1700
1736
  if (output.stopReason === 'error' && !output.errorMessage) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.6.0",
3
+ "version": "2.7.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.6.0"
39
+ "@cortexkit/anthropic-auth-core": "2.7.0"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",