@cortexkit/pi-anthropic-auth 2.13.1 → 2.14.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.
@@ -14,5 +14,6 @@ export declare class PiCacheKeepClaim {
14
14
  private read;
15
15
  acquire(): Promise<boolean>;
16
16
  private tryAcquire;
17
+ isCurrent(): Promise<boolean>;
17
18
  release(): Promise<void>;
18
19
  }
@@ -100,6 +100,16 @@ export class PiCacheKeepClaim {
100
100
  }
101
101
  });
102
102
  }
103
+ async isCurrent() {
104
+ if (!this.held)
105
+ return false;
106
+ try {
107
+ return (await this.read())?.token === this.token;
108
+ }
109
+ catch {
110
+ return false;
111
+ }
112
+ }
103
113
  async release() {
104
114
  if (!this.held)
105
115
  return;
@@ -1,9 +1,12 @@
1
- import { CacheKeepManager, type CacheKeepStoreOptions, type HolderLiveness, type NativeAccountSnapshot, type StickySessionRouter } from '@cortexkit/anthropic-auth-core';
1
+ import { CacheKeepManager, type CacheKeepRealTurn, 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. */
5
5
  export declare class PiCacheKeep {
6
6
  private readonly options;
7
+ private readonly realTurns;
8
+ private readonly turnStarts;
9
+ private readonly pendingTurns;
7
10
  readonly manager: CacheKeepManager;
8
11
  private readonly stores;
9
12
  private readonly sessions;
@@ -12,7 +15,6 @@ export declare class PiCacheKeep {
12
15
  private readonly restored;
13
16
  private readonly tracking;
14
17
  private stopping;
15
- private ticking?;
16
18
  private cleaning?;
17
19
  private cleanupTimer?;
18
20
  private readonly schedule;
@@ -35,7 +37,11 @@ export declare class PiCacheKeep {
35
37
  private access;
36
38
  private startCleanup;
37
39
  startSession(storagePath: string, sessionId: string): Promise<void>;
38
- trackAccepted(input: TrackInput, snapshot: NativeAccountSnapshot): Promise<void | {
40
+ realTurn(sessionId: string): CacheKeepRealTurn | undefined;
41
+ requestTurn(sessionId: string): CacheKeepRealTurn | undefined;
42
+ endTurn(sessionId: string): void;
43
+ finishTurn(turn: CacheKeepRealTurn | undefined): void;
44
+ trackAccepted(input: TrackInput, snapshot: NativeAccountSnapshot, requestTurn?: CacheKeepRealTurn): Promise<void | {
39
45
  tracked: true;
40
46
  } | {
41
47
  tracked: false;
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, peekRoutingAccount, readSessionCachePolicy, remapModelId, } from '@cortexkit/anthropic-auth-core';
3
+ import { CacheKeepManager, CacheKeepStore, currentCacheKeepRealTurn, 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) {
@@ -17,6 +17,10 @@ function accountKey(account) {
17
17
  /** One Pi process owns only the sessions its lifecycle actually opened. */
18
18
  export class PiCacheKeep {
19
19
  options;
20
+ // A current request outranks restart data that is still being read in the background.
21
+ realTurns = new Set();
22
+ turnStarts = new Map();
23
+ pendingTurns = new Set();
20
24
  manager;
21
25
  stores = new Map();
22
26
  sessions = new Map();
@@ -25,7 +29,6 @@ export class PiCacheKeep {
25
29
  restored = new Map();
26
30
  tracking = new Set();
27
31
  stopping = false;
28
- ticking;
29
32
  cleaning;
30
33
  cleanupTimer;
31
34
  schedule;
@@ -38,11 +41,12 @@ export class PiCacheKeep {
38
41
  this.cancel = managerOptions.clearIntervalImpl ?? clearInterval;
39
42
  const persistWarm = async (target) => {
40
43
  const session = this.sessions.get(target.id);
41
- if (this.stopping || !session?.identity)
44
+ const identity = target.hostMetadata?.accountIdentity;
45
+ if (this.stopping || !session || typeof identity !== 'string')
42
46
  return false;
43
47
  return session.store.reserveWarm({
44
48
  ...target,
45
- oauthAccountIdentity: session.identity,
49
+ oauthAccountIdentity: identity,
46
50
  });
47
51
  };
48
52
  this.manager = new CacheKeepManager({
@@ -58,18 +62,13 @@ export class PiCacheKeep {
58
62
  })
59
63
  : managerOptions.peekRoutingAccount?.(target, route);
60
64
  },
61
- setIntervalImpl: ((_callback, ms) => schedule(() => {
62
- this.ticking = this.manager
63
- .tick()
64
- .catch(() => logger.warn('cachekeep', 'tick failed'));
65
- return this.ticking;
66
- }, ms)),
67
65
  onTargetChanged: (target) => {
68
66
  const session = this.sessions.get(target.id);
69
- if (session?.identity)
67
+ const identity = target.hostMetadata?.accountIdentity;
68
+ if (session && typeof identity === 'string')
70
69
  session.store.changed({
71
70
  ...target,
72
- oauthAccountIdentity: session.identity,
71
+ oauthAccountIdentity: identity,
73
72
  });
74
73
  managerOptions.onTargetChanged?.(target);
75
74
  },
@@ -79,8 +78,7 @@ export class PiCacheKeep {
79
78
  : Promise.resolve(false),
80
79
  onTargetRemoved: (id) => {
81
80
  this.restored.delete(id);
82
- if (!this.stopping)
83
- this.sessions.get(id)?.store.removed(id);
81
+ this.sessions.get(id)?.store.removed(id);
84
82
  managerOptions.onTargetRemoved?.(id);
85
83
  },
86
84
  prepareHeaders: async (headers, target, attempt) => {
@@ -96,13 +94,15 @@ export class PiCacheKeep {
96
94
  if (target.cacheExpiresAt <= this.now())
97
95
  return undefined;
98
96
  }
97
+ attempt.signal?.throwIfAborted();
99
98
  if (this.stopping && this.manager.trackedRequest(target.id))
100
99
  return undefined;
101
100
  const session = this.sessions.get(target.id);
101
+ const identity = target.hostMetadata?.accountIdentity;
102
102
  // One-off prewarmNow probes are not restart targets and have no claim.
103
- if (session?.identity) {
103
+ if (session && typeof identity === 'string') {
104
104
  const snapshot = await this.options.read(session.storagePath);
105
- const account = snapshot.accounts.find((row) => accountKey(row) === session.identity);
105
+ const account = snapshot.accounts.find((row) => accountKey(row) === identity);
106
106
  if (!account || !nativeAccountCanServe(account))
107
107
  return undefined;
108
108
  }
@@ -168,7 +168,10 @@ export class PiCacheKeep {
168
168
  // The manager expires local targets. Cleanup must not race its queued
169
169
  // writes; only the initial restore reads a locally claimed record.
170
170
  return restoreOwn && !this.manager.trackedRequest(id)
171
- ? async () => { }
171
+ ? Object.assign(async () => { }, {
172
+ canRemove: async () => (await owned.claim.isCurrent()) &&
173
+ !this.manager.trackedRequest(id),
174
+ })
172
175
  : undefined;
173
176
  }
174
177
  const cleanup = new PiCacheKeepClaim(store.directory, hash, {
@@ -178,7 +181,15 @@ export class PiCacheKeep {
178
181
  });
179
182
  if (!(await cleanup.acquire()))
180
183
  return undefined;
181
- return () => cleanup.release();
184
+ const canRemove = async () => (await cleanup.isCurrent()) &&
185
+ !this.stopping &&
186
+ ![...this.claims.keys()].some((id) => createHash('sha256').update(id).digest('hex') === hash) &&
187
+ ![...this.sessions.keys()].some((id) => createHash('sha256').update(id).digest('hex') === hash);
188
+ if (!(await canRemove())) {
189
+ await cleanup.release();
190
+ return undefined;
191
+ }
192
+ return Object.assign(() => cleanup.release(), { canRemove });
182
193
  }
183
194
  startCleanup() {
184
195
  if (this.cleanupTimer || this.stopping)
@@ -189,7 +200,8 @@ export class PiCacheKeep {
189
200
  this.cleaning ??= (async () => {
190
201
  for (const store of this.stores.values()) {
191
202
  const current = await store;
192
- await current.load(this.now(), () => undefined, (hash) => this.access(current, hash));
203
+ const now = this.now();
204
+ await current.load(now, (entry) => (entry.cacheExpiresAt <= now ? 'expired' : undefined), (hash) => this.access(current, hash));
193
205
  }
194
206
  })()
195
207
  .catch(() => logger.warn('cachekeep', 'restart cleanup failed'))
@@ -216,10 +228,15 @@ export class PiCacheKeep {
216
228
  : undefined;
217
229
  const now = this.now();
218
230
  await store.load(now, (entry) => {
219
- if (!session ||
220
- entry.id !== sessionId ||
221
- this.stopping ||
222
- this.manager.trackedRequest(entry.id))
231
+ if (this.manager.trackedRequest(entry?.id))
232
+ return undefined;
233
+ if (this.realTurns.has(entry.id))
234
+ return 'invalid';
235
+ if (this.stopping)
236
+ return undefined;
237
+ if (entry.cacheExpiresAt <= now)
238
+ return 'expired';
239
+ if (!session || entry.id !== sessionId)
223
240
  return undefined;
224
241
  if (!snapshot)
225
242
  return 'invalid';
@@ -229,10 +246,10 @@ export class PiCacheKeep {
229
246
  if (account.type !== 'oauth' || !nativeAccountCanServe(account))
230
247
  return 'account-gone';
231
248
  if (entry.isSubagent &&
249
+ !entry.policyState?.planned &&
232
250
  readSessionCachePolicy(entry.policyState?.ownerSessionId ?? entry.id, true)?.keep_warm === undefined &&
233
251
  !isCacheKeepSubagentsEnabled(snapshot.policyStorage))
234
252
  return 'invalid';
235
- session.identity = accountKey(account);
236
253
  const result = this.manager.track({
237
254
  sessionId,
238
255
  url: entry.url,
@@ -242,6 +259,7 @@ export class PiCacheKeep {
242
259
  cacheMode: 'hybrid',
243
260
  oauthAccountId: account.id,
244
261
  oauthAccountIdentity: account.accountIdentity,
262
+ hostMetadata: { accountIdentity: accountKey(account) },
245
263
  accountStoragePath: storagePath,
246
264
  isSubagent: entry.isSubagent,
247
265
  retained: {
@@ -253,6 +271,8 @@ export class PiCacheKeep {
253
271
  this.restored.set(entry.id, 1000 + Math.floor(Math.random() * 2000));
254
272
  return result.tracked ? true : 'invalid';
255
273
  }, (hash) => this.access(store, hash, true));
274
+ if (!this.stopping && this.manager.trackedCount())
275
+ this.manager.start();
256
276
  this.startCleanup();
257
277
  completed = !!session;
258
278
  })()
@@ -264,12 +284,66 @@ export class PiCacheKeep {
264
284
  this.starts.set(sessionId, starting);
265
285
  return starting;
266
286
  }
267
- trackAccepted(input, snapshot) {
268
- if (this.stopping || !input.sessionId || !input.accountStoragePath)
287
+ realTurn(sessionId) {
288
+ this.realTurns.add(sessionId);
289
+ try {
290
+ const previous = this.turnStarts.get(sessionId);
291
+ if (previous && !previous.claimed)
292
+ previous.turn.finish();
293
+ const turn = this.manager.beginRealTurn(sessionId);
294
+ this.turnStarts.set(sessionId, { turn, claimed: false });
295
+ return turn;
296
+ }
297
+ catch {
298
+ return undefined;
299
+ }
300
+ }
301
+ requestTurn(sessionId) {
302
+ const pending = this.turnStarts.get(sessionId);
303
+ if (pending && !pending.claimed && pending.turn.active) {
304
+ pending.claimed = true;
305
+ return pending.turn;
306
+ }
307
+ const turn = this.realTurn(sessionId);
308
+ const entry = this.turnStarts.get(sessionId);
309
+ if (entry)
310
+ entry.claimed = true;
311
+ return turn;
312
+ }
313
+ endTurn(sessionId) {
314
+ const pending = this.turnStarts.get(sessionId);
315
+ this.turnStarts.delete(sessionId);
316
+ try {
317
+ if (pending && !pending.claimed)
318
+ pending.turn.finish();
319
+ }
320
+ catch { }
321
+ }
322
+ finishTurn(turn) {
323
+ try {
324
+ if (turn && !this.pendingTurns.has(turn))
325
+ turn.finish();
326
+ }
327
+ catch { }
328
+ }
329
+ trackAccepted(input, snapshot, requestTurn) {
330
+ let turn = requestTurn ?? currentCacheKeepRealTurn();
331
+ try {
332
+ turn ??= input.sessionId ? this.requestTurn(input.sessionId) : undefined;
333
+ }
334
+ catch { }
335
+ if (this.stopping || !input.sessionId || !input.accountStoragePath) {
336
+ try {
337
+ turn?.finish();
338
+ }
339
+ catch { }
269
340
  return Promise.resolve();
341
+ }
270
342
  const sessionId = input.sessionId;
271
343
  const storagePath = input.accountStoragePath;
272
344
  const acceptedAt = this.now();
345
+ if (turn)
346
+ this.pendingTurns.add(turn);
273
347
  const tracking = (async () => {
274
348
  const session = await this.claim(storagePath, sessionId);
275
349
  if (!session)
@@ -278,21 +352,31 @@ export class PiCacheKeep {
278
352
  snapshot.accounts.find((row) => row.accountIdentity === input.oauthAccountIdentity);
279
353
  if (account?.type !== 'oauth' ||
280
354
  !nativeAccountCanServe(account) ||
281
- account.accountIdentity !== input.oauthAccountIdentity)
355
+ account.accountIdentity !== input.oauthAccountIdentity) {
282
356
  return;
283
- session.identity = accountKey(account);
357
+ }
284
358
  // Claim I/O may finish after the response, or even during shutdown. Keep
285
359
  // that accepted body, but never grant the cache the time spent waiting.
286
- const result = this.manager.track({
360
+ const result = turn?.track({
287
361
  ...input,
288
362
  acceptedAt,
363
+ hostMetadata: { accountIdentity: accountKey(account) },
289
364
  });
290
- if (result.tracked)
365
+ if (result?.tracked)
291
366
  this.restored.delete(sessionId);
292
367
  if (this.stopping)
293
368
  this.manager.stop();
294
369
  return result;
295
- })().catch(() => logger.warn('cachekeep', 'accepted response tracking failed'));
370
+ })()
371
+ .finally(() => {
372
+ if (turn)
373
+ this.pendingTurns.delete(turn);
374
+ try {
375
+ turn?.finish();
376
+ }
377
+ catch { }
378
+ })
379
+ .catch(() => logger.warn('cachekeep', 'accepted response tracking failed'));
296
380
  this.tracking.add(tracking);
297
381
  void tracking.then(() => this.tracking.delete(tracking));
298
382
  return tracking;
@@ -303,19 +387,22 @@ export class PiCacheKeep {
303
387
  this.cancel(this.cleanupTimer);
304
388
  this.cleanupTimer = undefined;
305
389
  this.manager.stop();
390
+ this.manager.abortWarms();
306
391
  await Promise.all(this.starts.values());
307
392
  await Promise.all(this.claims.values());
308
393
  await Promise.all(this.tracking);
309
394
  this.manager.stop();
310
- await this.ticking;
395
+ await this.manager.drain();
311
396
  await this.cleaning;
312
397
  // Drain before releasing claims so a successor can never read an older body.
313
398
  for (const store of this.stores.values())
314
399
  await (await store).drain();
315
- for (const session of this.manager.trackedSessions())
316
- this.manager.untrack(session.id);
317
400
  for (const session of this.sessions.values())
318
401
  await session.claim.release();
402
+ await this.manager.dispose();
403
+ this.realTurns.clear();
404
+ this.turnStarts.clear();
405
+ this.pendingTurns.clear();
319
406
  this.sessions.clear();
320
407
  this.claims.clear();
321
408
  this.starts.clear();
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import { collectPiEffortHistory, deriveContextEntries, } from './effort-history.
4
4
  import { closePiNativeRuntime, getPiNativeRuntime, isNativeMigrationRequired, } from './native.js';
5
5
  import { createPiNativeCommands } from './native-commands.js';
6
6
  import { getPiAccountStoragePath, PI_HOSTED_LOGIN_REFUSAL, requirePiNativeHostAuth, } from './paths.js';
7
- import { beginPiPrimaryTurn, clearPiStickyQuotaRetries, endPiPrimaryTurn, forgetPiMessageThread, startPiCacheKeepSession, stopPiCacheKeep, streamCortexKitAnthropic, } from './stream.js';
7
+ import { beginPiPrimaryTurn, clearPiStickyQuotaRetries, endPiPrimaryTurn, forgetPiMessageThread, startPiCacheKeepSession, stopPiCacheKeep, streamCortexKitAnthropic, untrackPiCacheKeepTurn, } from './stream.js';
8
8
  function textImageInput() {
9
9
  return ['text', 'image'];
10
10
  }
@@ -53,6 +53,16 @@ function refuseHostedPiLoginPrompts(pi) {
53
53
  }
54
54
  });
55
55
  }
56
+ function trackPiCacheKeepRoute(pi) {
57
+ pi.on('input', async (_event, ctx) => {
58
+ try {
59
+ if (ctx.model?.provider && ctx.model.provider !== 'anthropic')
60
+ untrackPiCacheKeepTurn(ctx.sessionManager?.getSessionId());
61
+ }
62
+ catch { }
63
+ return { action: 'continue' };
64
+ });
65
+ }
56
66
  export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
57
67
  const storagePath = getPiAccountStoragePath();
58
68
  const quotaWait = options.quotaWait;
@@ -360,4 +370,5 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
360
370
  await configureProvider();
361
371
  if (isVaultHosted())
362
372
  refuseHostedPiLoginPrompts(pi);
373
+ trackPiCacheKeepRoute(pi);
363
374
  }
package/dist/stream.d.ts CHANGED
@@ -5,6 +5,7 @@ import { type PiPrimeSendOptions } from './prime.ts';
5
5
  import { type PiQuotaWaitOptions } from './quota-wait.ts';
6
6
  export declare function beginPiPrimaryTurn(storagePath: string, sessionId?: string): void;
7
7
  export declare function endPiPrimaryTurn(storagePath: string, sessionId?: string): void;
8
+ export declare function untrackPiCacheKeepTurn(sessionId?: string): void;
8
9
  export declare function forgetPiMessageThread(sessionId: string): void;
9
10
  export declare function clearPiStickyQuotaRetries(storagePath: string, sessionId: string): void;
10
11
  /** Set or clear the test replacement for the wait between quota usage polls. */
@@ -40,7 +41,8 @@ export declare function configureApiRouteHeaders(account: ApiKeyAccount, fastMod
40
41
  export declare function parseSse(response: Response, completion?: ReturnType<typeof createAnthropicStreamCompletion>): AsyncGenerator<AnthropicEvent>;
41
42
  /** Prime uses the model transport without a conversation, thread or cache target. */
42
43
  export declare function sendPiPrimeRequest(options: PiPrimeSendOptions): Promise<Response>;
43
- declare function sendAnthropicRequest(options: {
44
+ declare function sendAnthropicRequest(...args: Parameters<typeof sendAnthropicRequestAttempt>): Promise<Response>;
45
+ declare function sendAnthropicRequestAttempt(options: {
44
46
  model: Model<Api>;
45
47
  context: Context;
46
48
  streamOptions?: SimpleStreamOptions;
package/dist/stream.js CHANGED
@@ -1,4 +1,4 @@
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';
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, currentCacheKeepRealTurn, 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, withCacheKeepRealTurn, } 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';
@@ -14,6 +14,7 @@ const primaryTurns = new Map();
14
14
  export function beginPiPrimaryTurn(storagePath, sessionId) {
15
15
  if (!sessionId)
16
16
  return;
17
+ piCacheKeep.realTurn(sessionId);
17
18
  primaryTurns.delete(sessionId);
18
19
  primaryTurns.set(sessionId, storagePath);
19
20
  while (primaryTurns.size > 128) {
@@ -26,6 +27,15 @@ export function beginPiPrimaryTurn(storagePath, sessionId) {
26
27
  export function endPiPrimaryTurn(storagePath, sessionId) {
27
28
  if (sessionId && primaryTurns.get(sessionId) === storagePath)
28
29
  primaryTurns.delete(sessionId);
30
+ if (sessionId)
31
+ piCacheKeep.endTurn(sessionId);
32
+ }
33
+ export function untrackPiCacheKeepTurn(sessionId) {
34
+ try {
35
+ if (sessionId)
36
+ piCacheKeep.requestTurn(sessionId)?.finish();
37
+ }
38
+ catch { }
29
39
  }
30
40
  function isPiPrimaryThreadRequest(storagePath, options, origin) {
31
41
  // SDK summaries disable caching; SDK cache warms request exactly one token.
@@ -507,7 +517,29 @@ export function sendPiPrimeRequest(options) {
507
517
  }, { native: options.native, fetch: options.fetch });
508
518
  }
509
519
  registerPiPrimeSender(sendPiPrimeRequest);
510
- async function sendAnthropicRequest(options, deps = {}) {
520
+ async function sendAnthropicRequest(...args) {
521
+ const [options, deps = {}] = args;
522
+ const inherited = currentCacheKeepRealTurn();
523
+ let turn = inherited;
524
+ try {
525
+ if (!turn && !options.prime && options.streamOptions?.sessionId)
526
+ turn = deps.cacheKeep
527
+ ? deps.cacheKeep.beginRealTurn(options.streamOptions.sessionId)
528
+ : piCacheKeep.requestTurn(options.streamOptions.sessionId);
529
+ }
530
+ catch { }
531
+ try {
532
+ return await withCacheKeepRealTurn(turn, () => sendAnthropicRequestAttempt(...args));
533
+ }
534
+ finally {
535
+ if (!inherited)
536
+ piCacheKeep.finishTurn(turn);
537
+ }
538
+ }
539
+ async function sendAnthropicRequestAttempt(options, deps = {}) {
540
+ // Relay callbacks may run outside the request's async context. Keep the
541
+ // request-owned lease with the callback rather than looking it up later.
542
+ const realTurn = currentCacheKeepRealTurn();
511
543
  options.onCacheUsageRecorder?.(() => { });
512
544
  assertHostAuthorityStable();
513
545
  const fetchImpl = deps.fetch ?? globalThis.fetch;
@@ -515,6 +547,15 @@ async function sendAnthropicRequest(options, deps = {}) {
515
547
  return fetchPiStreamResponse(input, init, fetchImpl);
516
548
  };
517
549
  const keep = deps.cacheKeep ?? cacheKeepManager;
550
+ const realSession = options.streamOptions?.sessionId;
551
+ if (!options.prime && realSession) {
552
+ if (options.apiAccount || !options.storagePath) {
553
+ try {
554
+ realTurn?.finish();
555
+ }
556
+ catch { }
557
+ }
558
+ }
518
559
  const native = deps.native ?? getPiNativeRuntime(options.storagePath);
519
560
  let dumpHandle = null;
520
561
  // Capture the serving service while authorization is open. Shutdown rejects
@@ -674,8 +715,8 @@ async function sendAnthropicRequest(options, deps = {}) {
674
715
  accountStoragePath: options.storagePath,
675
716
  };
676
717
  const tracked = deps.cacheKeep
677
- ? Promise.resolve(keep.track(target))
678
- : piCacheKeep.trackAccepted(target, snapshot);
718
+ ? Promise.resolve(realTurn?.track(target) ?? keep.track(target))
719
+ : piCacheKeep.trackAccepted(target, snapshot, realTurn);
679
720
  cacheTracking.set(attempt, 'pending');
680
721
  void tracked.then(() => cacheTracking.set(attempt, 'settled'), () => { });
681
722
  let latestUsage = {};
@@ -1771,7 +1812,13 @@ async function executeWithFallback(options) {
1771
1812
  export const __executePiWithFallbackForTest = executeWithFallback;
1772
1813
  export function streamCortexKitAnthropic(model, context, options, effortTransitions, wait, requestOrigin = 'direct') {
1773
1814
  const stream = createAssistantMessageEventStream();
1774
- void (async () => {
1815
+ let turn;
1816
+ try {
1817
+ if (options?.sessionId)
1818
+ turn = piCacheKeep.requestTurn(options.sessionId);
1819
+ }
1820
+ catch { }
1821
+ void withCacheKeepRealTurn(turn, async () => {
1775
1822
  const output = createOutput(model);
1776
1823
  let failThread;
1777
1824
  stream.push({ type: 'start', partial: output });
@@ -2064,6 +2111,9 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
2064
2111
  stream.push({ type: 'error', reason: output.stopReason, error: output });
2065
2112
  stream.end();
2066
2113
  }
2067
- })();
2114
+ finally {
2115
+ piCacheKeep.finishTurn(turn);
2116
+ }
2117
+ });
2068
2118
  return stream;
2069
2119
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.13.1",
3
+ "version": "2.14.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.13.1"
39
+ "@cortexkit/anthropic-auth-core": "2.14.1"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",