@cortexkit/pi-anthropic-auth 2.5.8 → 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/custody.js CHANGED
@@ -1,5 +1,7 @@
1
- import { CLAUSTRUM_PI_ENROLLMENT_NAME, getHostClaustrumEnrollmentPaths, readClaustrumEnrollmentStatus, resetClaustrumEnrollmentState, } from '@cortexkit/anthropic-auth-core';
1
+ import { CLAUSTRUM_PI_ENROLLMENT_NAME, getHostClaustrumEnrollmentPaths, isVaultHosted, readClaustrumEnrollmentStatus, resetClaustrumEnrollmentState, VAULT_HOST_CONNECT_REFUSAL, } from '@cortexkit/anthropic-auth-core';
2
2
  export async function requirePiEnrollment() {
3
+ if (isVaultHosted())
4
+ throw new Error(VAULT_HOST_CONNECT_REFUSAL);
3
5
  const status = await readClaustrumEnrollmentStatus(getHostClaustrumEnrollmentPaths('pi'), CLAUSTRUM_PI_ENROLLMENT_NAME);
4
6
  if (status.state !== 'approved' ||
5
7
  status.proposedName !== CLAUSTRUM_PI_ENROLLMENT_NAME) {
@@ -10,8 +12,14 @@ export async function requirePiEnrollment() {
10
12
  export function createPiCustodyCommands() {
11
13
  const paths = () => getHostClaustrumEnrollmentPaths('pi');
12
14
  return {
13
- status: () => readClaustrumEnrollmentStatus(paths(), CLAUSTRUM_PI_ENROLLMENT_NAME),
15
+ status: () => {
16
+ if (isVaultHosted())
17
+ throw new Error(VAULT_HOST_CONNECT_REFUSAL);
18
+ return readClaustrumEnrollmentStatus(paths(), CLAUSTRUM_PI_ENROLLMENT_NAME);
19
+ },
14
20
  async reset() {
21
+ if (isVaultHosted())
22
+ return { text: `Refused: ${VAULT_HOST_CONNECT_REFUSAL}` };
15
23
  const result = await resetClaustrumEnrollmentState(paths(), CLAUSTRUM_PI_ENROLLMENT_NAME);
16
24
  const messages = {
17
25
  reset: 'Terminal enrollment state cleared. Run setup to enroll Pi again.',
@@ -26,6 +34,8 @@ export function createPiCustodyCommands() {
26
34
  return { text: messages[result] };
27
35
  },
28
36
  async transition(mode) {
37
+ if (isVaultHosted())
38
+ return { text: `Refused: ${VAULT_HOST_CONNECT_REFUSAL}` };
29
39
  // Mode changes can remove host credentials and require offline consent.
30
40
  // A menu never enrolls, grants custody or writes the authority journal.
31
41
  return {
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import { CLAUDE_FABLE_MYTHOS_5_MODEL_SPECS, CLAUDE_HAIKU_5_5_CONTEXT_WINDOW, CLAUDE_HAIKU_5_5_LONG_CONTEXT_PRICING, CLAUDE_HAIKU_5_5_LONG_CONTEXT_THRESHOLD, CLAUDE_HAIKU_5_5_MAX_OUTPUT_TOKENS, CLAUDE_HAIKU_5_5_MODEL_ID, CLAUDE_HAIKU_5_5_PRICING, CLAUDE_SONNET_5_5_CONTEXT_WINDOW, CLAUDE_SONNET_5_5_MAX_OUTPUT_TOKENS, CLAUDE_SONNET_5_5_MODEL_ID, CLAUDE_SONNET_5_5_PRICING, defaultAdaptiveEffort, getClaudeModelCatalogue, nativeAccountCanServe, readNativeEnrollmentMode, sessionCacheActivity, } from '@cortexkit/anthropic-auth-core';
1
+ import { CLAUDE_FABLE_MYTHOS_5_MODEL_SPECS, CLAUDE_HAIKU_5_5_CONTEXT_WINDOW, CLAUDE_HAIKU_5_5_LONG_CONTEXT_PRICING, CLAUDE_HAIKU_5_5_LONG_CONTEXT_THRESHOLD, CLAUDE_HAIKU_5_5_MAX_OUTPUT_TOKENS, CLAUDE_HAIKU_5_5_MODEL_ID, CLAUDE_HAIKU_5_5_PRICING, CLAUDE_SONNET_5_5_CONTEXT_WINDOW, CLAUDE_SONNET_5_5_MAX_OUTPUT_TOKENS, CLAUDE_SONNET_5_5_MODEL_ID, CLAUDE_SONNET_5_5_PRICING, defaultAdaptiveEffort, getClaudeModelCatalogue, isVaultHosted, nativeAccountCanServe, readNativeEnrollmentMode, sessionCacheActivity, } from '@cortexkit/anthropic-auth-core';
2
2
  import { registerCommands } from './commands.js';
3
3
  import { collectPiEffortHistory, deriveContextEntries, } from './effort-history.js';
4
4
  import { closePiNativeRuntime, getPiNativeRuntime, isNativeMigrationRequired, } from './native.js';
5
5
  import { createPiNativeCommands } from './native-commands.js';
6
- import { getPiAccountStoragePath, requirePiNativeHostAuth } from './paths.js';
6
+ import { getPiAccountStoragePath, PI_HOSTED_LOGIN_REFUSAL, requirePiNativeHostAuth, } from './paths.js';
7
7
  import { beginPiPrimaryTurn, clearPiStickyQuotaRetries, endPiPrimaryTurn, forgetPiMessageThread, startPiCacheKeepSession, stopPiCacheKeep, streamCortexKitAnthropic, } from './stream.js';
8
8
  function textImageInput() {
9
9
  return ['text', 'image'];
@@ -32,10 +32,31 @@ function refuseUnmigratedPrompts(pi, storagePath) {
32
32
  return { action: 'handled' };
33
33
  });
34
34
  }
35
+ /** Pi rejects stored OAuth before calling our native provider. Report the Thalamus-owned slot refusal before Pi's generic authentication error, without inspecting or changing the slot at startup. */
36
+ function refuseHostedPiLoginPrompts(pi) {
37
+ pi.on('input', async (_event, ctx) => {
38
+ if (ctx.model?.provider !== 'anthropic')
39
+ return { action: 'continue' };
40
+ try {
41
+ if (!isVaultHosted())
42
+ return { action: 'continue' };
43
+ await requirePiNativeHostAuth();
44
+ return { action: 'continue' };
45
+ }
46
+ catch (error) {
47
+ const message = error instanceof Error ? error.message : PI_HOSTED_LOGIN_REFUSAL;
48
+ if (ctx.hasUI)
49
+ ctx.ui.notify(message, 'error');
50
+ else
51
+ process.stderr.write(`${message}\n`);
52
+ return { action: 'handled' };
53
+ }
54
+ });
55
+ }
35
56
  export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
36
57
  const storagePath = getPiAccountStoragePath();
37
58
  const quotaWait = options.quotaWait;
38
- getPiNativeRuntime(storagePath, {
59
+ const native = getPiNativeRuntime(storagePath, {
39
60
  ...(options.connectScoped && { connect: options.connectScoped }),
40
61
  });
41
62
  registerCommands(pi, createPiNativeCommands(storagePath));
@@ -102,6 +123,7 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
102
123
  clearPiStickyQuotaRetries(storagePath, sessionId);
103
124
  });
104
125
  pi.on('session_shutdown', async (_event, ctx) => {
126
+ native.prime?.stop();
105
127
  const sessionId = ctx.sessionManager.getSessionId();
106
128
  endPiPrimaryTurn(storagePath, sessionId);
107
129
  if (sessionId) {
@@ -336,4 +358,6 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
336
358
  pi.registerProvider(provider);
337
359
  }
338
360
  await configureProvider();
361
+ if (isVaultHosted())
362
+ refuseHostedPiLoginPrompts(pi);
339
363
  }
@@ -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, nativeAccountCanServe, setDumpEnabled, } from '@cortexkit/anthropic-auth-core';
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';
3
3
  import { createPiCustodyCommands } from './custody.js';
4
4
  import { getPiNativeRuntime } from './native.js';
5
5
  import { getPiAccountStoragePath } from './paths.js';
@@ -41,6 +41,14 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
41
41
  });
42
42
  };
43
43
  const dispatch = async (request, options) => {
44
+ if (isVaultHosted() &&
45
+ [
46
+ 'enrollment-reset',
47
+ 'add-oauth-start',
48
+ 'add-oauth-finish',
49
+ 'add-apikey',
50
+ ].includes(request.action))
51
+ return { ok: false, text: VAULT_HOST_CONNECT_REFUSAL };
44
52
  const runtime = await native.service();
45
53
  switch (request.action) {
46
54
  case 'enable':
@@ -261,10 +269,13 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
261
269
  return { ok: true, text: 'Native fast mode setting updated.' };
262
270
  case 'prime-on':
263
271
  case 'prime-off':
272
+ await setSection('prime', { enabled: request.action === 'prime-on' });
273
+ native.prime?.settingsChanged();
274
+ return { ok: true, text: 'Native Prime setting updated.' };
264
275
  case 'start-fire':
265
276
  return {
266
277
  ok: false,
267
- text: 'Pi supports Prime status only and has no lane-start action.',
278
+ text: 'Pi has no lane-start action.',
268
279
  };
269
280
  }
270
281
  };
@@ -282,7 +293,9 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
282
293
  return [
283
294
  `Custody: ${snapshot.mode}`,
284
295
  ...snapshot.accounts.map((account) => `${account.id}: ${account.label ?? account.id} (${account.type}, ${account.enabled ? 'enabled' : 'disabled'}, ${account.source}${account.state ? `, ${formatNativeAccountState(account)}` : ''}${formatOAuthAccountTier(account.profile) ? `, ${formatOAuthAccountTier(account.profile)}` : ''}); identity: ${account.accountIdentity ?? 'unverified'}${account.lastRefreshError ? `; refresh: ${account.lastRefreshError.permanent ? 'requires login' : 'backoff'}` : ''}`),
285
- ...formatEnrollmentStatus(await custody.status(), snapshot.mode === 'claustrum'),
296
+ ...(isVaultHosted()
297
+ ? [VAULT_HOST_STATUS]
298
+ : formatEnrollmentStatus(await custody.status(), snapshot.mode === 'claustrum')),
286
299
  ].join('\n');
287
300
  case 'quota':
288
301
  return buildClaudeQuotaSummary({
@@ -342,7 +355,8 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
342
355
  return executePrimeCommand({
343
356
  argumentsText: 'status',
344
357
  enabled: isPrimePersistentlyEnabled(storage),
345
- accounts: buildPrimeAccountStatuses(storage, { now: Date.now() }),
358
+ accounts: native.prime?.manager.stats(storage) ??
359
+ buildPrimeAccountStatuses(storage, { now: Date.now() }),
346
360
  }).text;
347
361
  }
348
362
  },
package/dist/native.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type NativeAccountRuntime, type NativeAccountRuntimeOptions, type NativeAccountSnapshot, type NativeCustodyClient, type NativeCustodyReceipt, type NativeCustodyReporterSource, type NativeRefreshResult } from '@cortexkit/anthropic-auth-core';
2
+ import { type PiPrimeLease, type PiPrimeOptions } from './prime.ts';
2
3
  export type PiNativeAttempt = {
3
4
  source: 'local';
4
5
  accountIdentity: string;
@@ -37,10 +38,14 @@ export declare class PiNativeRuntime {
37
38
  private vaultWatch;
38
39
  private closed;
39
40
  private closing;
41
+ prime: PiPrimeLease | undefined;
40
42
  readonly usagePublications: {
43
+ signal: AbortSignal;
44
+ hasPending: () => boolean;
41
45
  observe: (write: Promise<unknown>) => Promise<void>;
42
- publish(write: () => Promise<unknown>): void;
43
- drain(): Promise<void>;
46
+ publish(write: (signal: AbortSignal) => Promise<unknown>): void;
47
+ drain: () => Promise<void>;
48
+ close(): Promise<void>;
44
49
  };
45
50
  private readonly routingPublications;
46
51
  ownRoutingPublications(router: {
@@ -51,6 +56,7 @@ export declare class PiNativeRuntime {
51
56
  connect?: () => Promise<NativeCustodyClient>;
52
57
  local?: NativeAccountRuntimeOptions['local'];
53
58
  vaultPoll?: PiVaultPollOptions;
59
+ prime?: PiPrimeOptions;
54
60
  });
55
61
  service(): Promise<NativeAccountRuntime>;
56
62
  routingPath(): Promise<string>;
@@ -80,5 +86,6 @@ export declare function getPiNativeRuntime(storagePath?: string, options?: {
80
86
  connect?: () => Promise<NativeCustodyClient>;
81
87
  local?: NativeAccountRuntimeOptions['local'];
82
88
  vaultPoll?: PiVaultPollOptions;
89
+ prime?: PiPrimeOptions;
83
90
  }): PiNativeRuntime;
84
91
  export declare function closePiNativeRuntime(storagePath?: string): Promise<void>;
package/dist/native.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { resolve } from 'node:path';
2
- import { acquireNativeAccountRuntime, createNativeUsagePublisher, decidePiStateLayout, getAccountStatePath, getHostClaustrumEnrollmentPaths, getPersistedLogLevel, isKillswitchEnabled, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, logger, NativeAccountRefusal, nativeAccountCanServe, nativeAccountRefusal, nativeLocalAccountRefusal, nativeMigrationAuthorityPhase, nativeRuntimeOptionIdentity, quotaSnapshotHasStandardWindows, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, readNativeAccountsForRequest, readNativeMigrationJournal, resolveClaustrumConnectionPath, resolveLocalRoutingDestination, resolveNativePoolPaths, setLogLevel, } from '@cortexkit/anthropic-auth-core';
2
+ import { acquireNativeAccountRuntime, createNativeUsagePublisher, decidePiStateLayout, getAccountStatePath, getHostClaustrumEnrollmentPaths, getPersistedLogLevel, isKillswitchEnabled, isVaultHosted, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, logger, NativeAccountRefusal, nativeAccountCanServe, nativeAccountRefusal, nativeLocalAccountRefusal, nativeMigrationAuthorityPhase, nativeRuntimeOptionIdentity, quotaSnapshotHasStandardWindows, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, readNativeAccountsForRequest, readNativeMigrationJournal, resolveClaustrumConnectionPath, resolveLocalRoutingDestination, resolveNativePoolPaths, setLogLevel, } from '@cortexkit/anthropic-auth-core';
3
3
  import { getPiAccountStoragePath, getPiClaustrumConnectionOptions, getPiConfigDir, requirePiNativeHostAuth, } from './paths.js';
4
+ import { acquirePiPrime, } from './prime.js';
4
5
  export function piAttemptAccessToken(attempt) {
5
6
  return attempt.source === 'vault'
6
7
  ? attempt.receipt.accessToken
@@ -84,6 +85,7 @@ export class PiNativeRuntime {
84
85
  vaultWatch;
85
86
  closed = false;
86
87
  closing;
88
+ prime;
87
89
  usagePublications = createNativeUsagePublisher('native-auth');
88
90
  routingPublications = new Set();
89
91
  ownRoutingPublications(router) {
@@ -143,8 +145,17 @@ export class PiNativeRuntime {
143
145
  runtime.close();
144
146
  // Refresh returns at once while this host uses local accounts, so the
145
147
  // poll costs one enrollment read per tick outside vault custody.
146
- else if (poll.intervalMs > 0) {
148
+ else {
149
+ if (!this.closed)
150
+ this.prime = acquirePiPrime({ native: this, storagePath: paths.legacyConfig }, options.prime);
151
+ if (this.closed || poll.intervalMs <= 0)
152
+ return runtime;
147
153
  this.vaultWatch = runtime.vault.watch({
154
+ shouldRefresh: async () => {
155
+ if (isVaultHosted())
156
+ await requirePiNativeHostAuth();
157
+ return true;
158
+ },
148
159
  intervalMs: poll.intervalMs,
149
160
  setInterval: poll.setInterval,
150
161
  clearInterval: poll.clearInterval,
@@ -351,20 +362,24 @@ export class PiNativeRuntime {
351
362
  const runtime = servingRuntime ?? (await this.service());
352
363
  const patch = { lastUsed: Date.now() };
353
364
  if (served.source === 'vault')
354
- await runtime.vault.publish(served.receipt, patch);
365
+ await runtime.vault.publish(served.receipt, patch, this.usagePublications.signal);
355
366
  else
356
- await runtime.publishLocal(served.admission.subject, patch);
367
+ await runtime.publishLocal(served.admission.subject, patch, this.usagePublications.signal);
357
368
  }
358
369
  close() {
370
+ this.prime?.stop();
359
371
  this.closed = true;
360
372
  this.vaultWatch?.close();
361
373
  void this.holderRegistration.then((registration) => registration.close(), () => { });
362
374
  this.closing ??= (async () => {
363
- await this.usagePublications.drain();
375
+ await Promise.all([
376
+ this.usagePublications.close(),
377
+ this.initialization.then((runtime) => runtime.drainQuotaPublications(), () => { }),
378
+ ]);
364
379
  await this.drainRoutingPublications();
365
380
  this.routingPublications.clear();
366
381
  await this.initialization.then(async (runtime) => {
367
- await runtime.drainQuotaPublications();
382
+ await this.prime?.release();
368
383
  await runtime.drainRoutingPublications();
369
384
  await this.drainReports();
370
385
  await runtime.close();
package/dist/paths.d.ts CHANGED
@@ -13,3 +13,4 @@ export declare function getPiClaustrumConnectionOptions(storagePath?: string): {
13
13
  export declare function hasPiLocalAnthropicOAuth(): Promise<boolean>;
14
14
  /** The user must approve removing the host’s Anthropic OAuth credential before the shared account store can serve requests. */
15
15
  export declare function requirePiNativeHostAuth(): Promise<void>;
16
+ export declare const PI_HOSTED_LOGIN_REFUSAL = "This Thalamus-hosted head has its own Claude login. Remove it so Thalamus can serve Claude accounts, and let Thalamus install the vault placeholder.";
package/dist/paths.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { homedir } from 'node:os';
3
3
  import { join } from 'node:path';
4
- import { ACCOUNT_FILE_NAME, parseJsonRedacted, primeStorageFingerprint, } from '@cortexkit/anthropic-auth-core';
4
+ import { ACCOUNT_FILE_NAME, isVaultHosted, nativePiAuthSlotPaths, parseJsonRedacted, primeStorageFingerprint, } from '@cortexkit/anthropic-auth-core';
5
5
  export function getPiConfigDir() {
6
6
  return (process.env.PI_CODING_AGENT_DIR?.trim() ||
7
7
  process.env.PI_AGENT_DIR?.trim() ||
@@ -50,7 +50,34 @@ export async function hasPiLocalAnthropicOAuth() {
50
50
  }
51
51
  /** The user must approve removing the host’s Anthropic OAuth credential before the shared account store can serve requests. */
52
52
  export async function requirePiNativeHostAuth() {
53
+ if (isVaultHosted()) {
54
+ const authPath = join(getPiConfigDir(), 'auth.json');
55
+ let root;
56
+ try {
57
+ root = parseJsonRedacted(await readFile(authPath, 'utf8'));
58
+ }
59
+ catch (error) {
60
+ if (error.code === 'ENOENT')
61
+ return;
62
+ throw new Error('Cannot safely inspect Pi authentication metadata');
63
+ }
64
+ if (!root || typeof root !== 'object' || Array.isArray(root))
65
+ throw new Error('Cannot safely inspect Pi authentication metadata');
66
+ const entry = root.anthropic;
67
+ if (entry === undefined)
68
+ return;
69
+ const placeholder = nativePiAuthSlotPaths({ authPath }).placeholderKey;
70
+ if (entry &&
71
+ typeof entry === 'object' &&
72
+ !Array.isArray(entry) &&
73
+ Object.keys(entry).length === 2 &&
74
+ entry.type === 'api_key' &&
75
+ entry.key === placeholder)
76
+ return;
77
+ throw new Error(PI_HOSTED_LOGIN_REFUSAL);
78
+ }
53
79
  if (await hasPiLocalAnthropicOAuth()) {
54
80
  throw new Error('Pi still has a host Anthropic OAuth credential. Run offline setup to migrate it and approve its removal before using the native pool.');
55
81
  }
56
82
  }
83
+ export const PI_HOSTED_LOGIN_REFUSAL = 'This Thalamus-hosted head has its own Claude login. Remove it so Thalamus can serve Claude accounts, and let Thalamus install the vault placeholder.';
@@ -0,0 +1,30 @@
1
+ import { PrimeManager, type PrimeManagerOptions } from '@cortexkit/anthropic-auth-core';
2
+ import type { PiNativeAttempt, PiNativeRuntime } from './native.ts';
3
+ export type PiPrimeSendOptions = {
4
+ native: PiNativeRuntime;
5
+ storagePath: string;
6
+ accountId: string;
7
+ signal: AbortSignal;
8
+ beforeSend: () => Promise<void>;
9
+ onServed: (attempt: PiNativeAttempt) => void;
10
+ fetch?: typeof fetch;
11
+ };
12
+ type PiPrimeSender = (options: PiPrimeSendOptions) => Promise<Response>;
13
+ /** Stream installs its normal sender without making native startup load the keep-warm manager. */
14
+ export declare function registerPiPrimeSender(sender: PiPrimeSender): void;
15
+ export type PiPrimeOptions = Pick<PrimeManagerOptions, 'markerDir' | 'now' | 'setIntervalImpl' | 'clearIntervalImpl' | 'setTimeoutImpl' | 'clearTimeoutImpl'> & {
16
+ fetch?: typeof fetch;
17
+ };
18
+ type Owner = {
19
+ native: PiNativeRuntime;
20
+ storagePath: string;
21
+ };
22
+ /** Runtime leases share one scheduler for each canonical account-storage path. */
23
+ export declare function acquirePiPrime(owner: Owner, options?: PiPrimeOptions): {
24
+ manager: PrimeManager;
25
+ settingsChanged: () => void;
26
+ stop: () => void;
27
+ release(): Promise<void>;
28
+ };
29
+ export type PiPrimeLease = ReturnType<typeof acquirePiPrime>;
30
+ export {};
package/dist/prime.js ADDED
@@ -0,0 +1,181 @@
1
+ import { logger, PrimeManager, primeStorageFingerprint, tokenFingerprint, } from '@cortexkit/anthropic-auth-core';
2
+ let sendPrimeRequest;
3
+ /** Stream installs its normal sender without making native startup load the keep-warm manager. */
4
+ export function registerPiPrimeSender(sender) {
5
+ sendPrimeRequest = sender;
6
+ }
7
+ const primes = new Map();
8
+ class PiPrime {
9
+ manager;
10
+ owners = new Set();
11
+ abort = new AbortController();
12
+ sends = new Set();
13
+ constructor(owner, options) {
14
+ this.owners.add(owner);
15
+ this.manager = new PrimeManager({
16
+ ...options,
17
+ setIntervalImpl: ((tick, ms) => (options.setIntervalImpl ?? globalThis.setInterval)(() => this.tickIfEnabled(tick), ms)),
18
+ // The default marker root lets verified Claude accounts share claims
19
+ // across hosts, even when their local account files differ.
20
+ storagePath: owner.storagePath,
21
+ loadStorage: async () => (await this.owner().native.view()).policyStorage,
22
+ getAccountFingerprint: async (accountId) => {
23
+ if (!sendPrimeRequest)
24
+ return undefined;
25
+ const runtime = await this.owner().native.service();
26
+ const signal = this.abort.signal;
27
+ const account = (await runtime.read()).accounts.find((row) => row.id === accountId);
28
+ if (account?.type !== 'oauth')
29
+ return undefined;
30
+ const fence = account.source === 'vault'
31
+ ? await runtime.authorizeVault(accountId, signal)
32
+ : await runtime
33
+ .authorizeLocal(accountId, { signal })
34
+ .then((credential) => credential.status === 'usable'
35
+ ? credential.subject
36
+ : undefined);
37
+ if (!fence)
38
+ return undefined;
39
+ const lineage = await runtime.getOrCreateAuthLineage(accountId, fence);
40
+ return lineage ? tokenFingerprint(lineage) : undefined;
41
+ },
42
+ getAccountIdentity: async (accountId) => (await this.owner().native.view()).accounts.find((account) => account.id === accountId)?.accountIdentity,
43
+ refreshQuota: async (accountId) => ({
44
+ quota: await (await this.owner().native.service()).fetchQuota(accountId, options.fetch, this.abort.signal),
45
+ fresh: true,
46
+ }),
47
+ sendPrime: (accountId) => {
48
+ const pending = this.send(accountId, options.fetch);
49
+ this.sends.add(pending);
50
+ void pending.finally(() => this.sends.delete(pending));
51
+ return pending;
52
+ },
53
+ recordSuccess: async (accountId) => {
54
+ const account = (await this.owner().native.view()).accounts.find((row) => row.id === accountId);
55
+ if (!account?.prime)
56
+ throw new Error('Pi Prime counters are unavailable');
57
+ return account.prime;
58
+ },
59
+ });
60
+ this.manager.start();
61
+ }
62
+ owner() {
63
+ const owner = [...this.owners].at(-1);
64
+ if (!owner)
65
+ throw new Error('Pi Prime has no active runtime');
66
+ return owner;
67
+ }
68
+ async tickIfEnabled(tick) {
69
+ const signal = this.abort.signal;
70
+ if (signal.aborted || this.manager.isStopped() || !sendPrimeRequest)
71
+ return;
72
+ try {
73
+ const snapshot = await this.owner().native.view(signal);
74
+ // Keep the opt-in poll, but disabled Prime must not sweep claim markers,
75
+ // authorize an account or refresh quota alongside keep-warm restoration.
76
+ if (!signal.aborted && snapshot.policyStorage.prime?.enabled === true)
77
+ tick();
78
+ }
79
+ catch {
80
+ if (!signal.aborted)
81
+ logger.warn('prime', 'Pi settings check failed');
82
+ }
83
+ }
84
+ settingsChanged() {
85
+ this.manager.stop();
86
+ this.abort.abort();
87
+ this.abort = new AbortController();
88
+ // Leave a dormant tick while disabled: a settings edit in another process
89
+ // must be noticed without a new Pi session. The scheduler reloads opt-in
90
+ // every tick.
91
+ this.manager.start();
92
+ }
93
+ stop() {
94
+ this.manager.stop();
95
+ this.abort.abort();
96
+ }
97
+ async drain() {
98
+ await Promise.allSettled(this.sends);
99
+ }
100
+ async send(accountId, fetchImpl) {
101
+ const { native, storagePath } = this.owner();
102
+ const signal = this.abort.signal;
103
+ const started = performance.now();
104
+ let response;
105
+ try {
106
+ const send = sendPrimeRequest;
107
+ if (!send)
108
+ throw new Error('Pi Prime transport is unavailable');
109
+ const runtime = await native.service();
110
+ let served;
111
+ response = await send({
112
+ native,
113
+ storagePath,
114
+ accountId,
115
+ signal,
116
+ fetch: fetchImpl,
117
+ beforeSend: async () => {
118
+ const snapshot = await native.view(signal);
119
+ signal.throwIfAborted();
120
+ if (snapshot.policyStorage.prime?.enabled !== true)
121
+ throw new Error('Pi Prime is disabled');
122
+ },
123
+ onServed: (attempt) => {
124
+ served = attempt;
125
+ },
126
+ });
127
+ if (!response.ok || !served)
128
+ return {
129
+ ok: false,
130
+ status: response.status,
131
+ error: 'Pi Prime upstream refused the request',
132
+ };
133
+ const data = (await response.json());
134
+ const usage = {
135
+ inputTokens: data.usage?.input_tokens,
136
+ outputTokens: data.usage?.output_tokens,
137
+ };
138
+ const fence = served.source === 'vault' ? served.receipt : served.admission.subject;
139
+ if (!(await runtime.incrementPrimeUsage(accountId, fence, usage)))
140
+ throw new Error('Pi Prime counter attribution was superseded');
141
+ return {
142
+ ok: true,
143
+ status: response.status,
144
+ usage,
145
+ ms: performance.now() - started,
146
+ };
147
+ }
148
+ catch {
149
+ return {
150
+ ok: false,
151
+ error: 'Pi Prime was not completed',
152
+ ms: performance.now() - started,
153
+ };
154
+ }
155
+ finally {
156
+ void response?.body?.cancel().catch(() => { });
157
+ }
158
+ }
159
+ }
160
+ /** Runtime leases share one scheduler for each canonical account-storage path. */
161
+ export function acquirePiPrime(owner, options = {}) {
162
+ const key = primeStorageFingerprint(owner.storagePath);
163
+ const prime = primes.get(key) ?? new PiPrime(owner, options);
164
+ primes.set(key, prime);
165
+ prime.owners.add(owner);
166
+ return {
167
+ manager: prime.manager,
168
+ settingsChanged: () => prime.settingsChanged(),
169
+ stop: () => prime.stop(),
170
+ async release() {
171
+ prime.owners.delete(owner);
172
+ if (prime.owners.size) {
173
+ prime.settingsChanged();
174
+ return;
175
+ }
176
+ prime.stop();
177
+ primes.delete(key);
178
+ await prime.drain();
179
+ },
180
+ };
181
+ }
package/dist/stream.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type ApiKeyAccount, type CacheKeepManager, type MidConversationEffortTransition, type NativeAccountView, type QuotaManagerOptions } from '@cortexkit/anthropic-auth-core';
2
2
  import { type Api, type AssistantMessageEventStream, type Context, type Model, type SimpleStreamOptions } from '@earendil-works/pi-ai';
3
+ import { type PiNativeAttempt, type PiNativeRuntime } from './native.ts';
4
+ import { type PiPrimeSendOptions } from './prime.ts';
3
5
  import { type PiQuotaWaitOptions } from './quota-wait.ts';
4
6
  export declare function beginPiPrimaryTurn(storagePath: string, sessionId?: string): void;
5
7
  export declare function endPiPrimaryTurn(storagePath: string, sessionId?: string): void;
@@ -27,6 +29,8 @@ type AnthropicEvent = {
27
29
  export declare function buildExplicitBaseMessagesUrl(baseURL: string): URL;
28
30
  export declare function configureApiRouteHeaders(account: ApiKeyAccount, fastMode: boolean): Headers;
29
31
  export declare function parseSse(response: Response): AsyncGenerator<AnthropicEvent>;
32
+ /** Prime uses the model transport without a conversation, thread or cache target. */
33
+ export declare function sendPiPrimeRequest(options: PiPrimeSendOptions): Promise<Response>;
30
34
  declare function sendAnthropicRequest(options: {
31
35
  model: Model<Api>;
32
36
  context: Context;
@@ -40,9 +44,15 @@ declare function sendAnthropicRequest(options: {
40
44
  effortTransitions?: readonly MidConversationEffortTransition[];
41
45
  onResolvedToolNames?: (toolNames: ReadonlyMap<string, string>) => void;
42
46
  onThreadPrepared?: (fail: () => void) => void;
47
+ onCacheUsageRecorder?: (record: (usage?: Record<string, number>) => void) => void;
48
+ prime?: {
49
+ beforeSend: () => Promise<void>;
50
+ onServed: (attempt: PiNativeAttempt) => void;
51
+ };
43
52
  }, deps?: {
44
53
  fetch?: typeof fetch;
45
54
  cacheKeep?: CacheKeepManager;
55
+ native?: PiNativeRuntime;
46
56
  }): Promise<Response>;
47
57
  /** Exercise one native send with isolated transport and scheduling in tests. */
48
58
  export declare const __sendPiAnthropicRequestForTest: typeof sendAnthropicRequest;
package/dist/stream.js CHANGED
@@ -1,9 +1,10 @@
1
- import { applyClaudeCodeHeaders, applyCustomHeaders, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, 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, logger, MessageThreadTracker, mergeAnthropicBetas, NativeAccountRefusal, nativeAccountCanServe, 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';
5
5
  import { getPiNativeRuntime, piAttemptAccessToken, } from './native.js';
6
6
  import { getPiAccountStoragePath } from './paths.js';
7
+ import { registerPiPrimeSender } from './prime.js';
7
8
  import { markPiAccountHold, withPiQuotaWait, } from './quota-wait.js';
8
9
  import { buildPiOAuthMessagesUrl, fetchPiOAuth, requirePiOAuthOrigin, } from './transport.js';
9
10
  const messageThreads = new MessageThreadTracker();
@@ -190,6 +191,7 @@ function applyPiOAuthRequestHeaders(headers, accessToken, options) {
190
191
  body,
191
192
  identity: options.identity,
192
193
  extraBetas: options.leadingBetas,
194
+ requestClass: options.requestClass,
193
195
  });
194
196
  if (body.speed === 'fast')
195
197
  headers.set('anthropic-beta', mergeAnthropicBetas(headers.get('anthropic-beta'), [FAST_MODE_BETA]));
@@ -249,14 +251,15 @@ const piCacheKeep = new PiCacheKeep({
249
251
  });
250
252
  return rotatedHeaders;
251
253
  },
252
- onResponse: async ({ target, attempt, status, receivedAt }) => {
254
+ onResponse: async ({ target, attempt, status, receivedAt, bodyText }) => {
253
255
  const entry = nativePrewarmAttempts.get(attempt.id);
254
256
  if (entry &&
255
257
  status >= 200 &&
256
258
  status < 300 &&
257
259
  !attempt.signal?.aborted &&
258
- !target.sourceWarm)
259
- 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));
260
263
  if (entry && status === 401 && !entry.reported)
261
264
  await entry.runtime.report(entry.served, status, 'direct').catch(() => {
262
265
  logger.warn('native-auth', 'Pi CacheKeep auth-failure report unavailable');
@@ -403,10 +406,58 @@ export async function* parseSse(response) {
403
406
  reader.releaseLock();
404
407
  }
405
408
  }
409
+ function buildPiPrimeBody(identity) {
410
+ const prime = buildPrimeRequestBody();
411
+ const body = {
412
+ ...prime,
413
+ system: [
414
+ {
415
+ type: 'text',
416
+ text: buildBillingHeaderValue(prime.messages, undefined, CLAUDE_CODE_ENTRYPOINT),
417
+ },
418
+ { type: 'text', text: CLAUDE_CODE_IDENTITY },
419
+ { type: 'text', text: prime.system },
420
+ ],
421
+ };
422
+ if (identity)
423
+ applyClaudeCodeMetadata(body, identity);
424
+ return {
425
+ body,
426
+ bodyText: JSON.stringify(orderClaudeCodeBody(body)),
427
+ toolNames: new Map(),
428
+ cacheTtlMs: 0,
429
+ };
430
+ }
431
+ /** Prime uses the model transport without a conversation, thread or cache target. */
432
+ export function sendPiPrimeRequest(options) {
433
+ return sendAnthropicRequest({
434
+ model: {
435
+ id: buildPrimeRequestBody().model,
436
+ name: 'Prime',
437
+ api: 'anthropic-messages',
438
+ provider: 'anthropic',
439
+ baseUrl: 'https://api.anthropic.com',
440
+ reasoning: false,
441
+ input: ['text'],
442
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
443
+ contextWindow: 200_000,
444
+ maxTokens: 1,
445
+ },
446
+ context: { messages: [] },
447
+ storagePath: options.storagePath,
448
+ oauthAccountId: options.accountId,
449
+ streamOptions: { signal: options.signal },
450
+ route: 'prime',
451
+ prime: options,
452
+ }, { native: options.native, fetch: options.fetch });
453
+ }
454
+ registerPiPrimeSender(sendPiPrimeRequest);
406
455
  async function sendAnthropicRequest(options, deps = {}) {
456
+ options.onCacheUsageRecorder?.(() => { });
457
+ assertHostAuthorityStable();
407
458
  const fetchImpl = deps.fetch ?? globalThis.fetch;
408
459
  const keep = deps.cacheKeep ?? cacheKeepManager;
409
- const native = getPiNativeRuntime(options.storagePath);
460
+ const native = deps.native ?? getPiNativeRuntime(options.storagePath);
410
461
  // Capture the serving service while authorization is open. Shutdown rejects
411
462
  // new serving work immediately but drains writes for already-served attempts.
412
463
  const servingRuntime = await native.service();
@@ -438,26 +489,34 @@ async function sendAnthropicRequest(options, deps = {}) {
438
489
  // activity below follows the final serialized body, since hooks can edit TTLs.
439
490
  const oneHourCache = isCache1hPersistentlyEnabled(storage) ||
440
491
  options.streamOptions?.cacheRetention === 'long';
441
- const { body, bodyText, toolNames, cacheTtlMs } = await buildAnthropicRequest(options.model.id, options.context, options.streamOptions, {
442
- enabled: oneHourCache,
443
- mode: getCache1hPersistentMode(storage),
444
- }, isFastModePersistentlyEnabled(storage), identity, {
445
- deferSigning: true,
446
- effortTransitions: options.apiAccount ? [] : options.effortTransitions,
447
- turnEndNote: storage.turnEndNote,
448
- thinkingPrefixMismatchBehavior: options.apiAccount
449
- ? 'account-default'
450
- : getThinkingPrefixMismatchBehavior(storage),
451
- ...(options.streamOptions?.onPayload && {
452
- onPayload: (payload) => options.streamOptions?.onPayload?.(payload, options.model),
453
- }),
454
- });
492
+ const { body, bodyText, toolNames, cacheTtlMs } = options.prime
493
+ ? buildPiPrimeBody(identity)
494
+ : await buildAnthropicRequest(options.model.id, options.context, options.streamOptions, {
495
+ enabled: oneHourCache,
496
+ mode: getCache1hPersistentMode(storage),
497
+ }, isFastModePersistentlyEnabled(storage), identity, {
498
+ deferSigning: true,
499
+ effortTransitions: options.apiAccount
500
+ ? []
501
+ : options.effortTransitions,
502
+ turnEndNote: storage.turnEndNote,
503
+ thinkingPrefixMismatchBehavior: options.apiAccount
504
+ ? 'account-default'
505
+ : getThinkingPrefixMismatchBehavior(storage),
506
+ ...(options.streamOptions?.onPayload && {
507
+ onPayload: (payload) => options.streamOptions?.onPayload?.(payload, options.model),
508
+ }),
509
+ });
455
510
  let wireBodyText = bodyText;
456
511
  options.onResolvedToolNames?.(toolNames);
457
512
  const fastMode = body.speed === 'fast';
458
513
  const headers = options.apiAccount
459
514
  ? new Headers()
460
- : applyPiOAuthRequestHeaders(new Headers(), '', { body, identity });
515
+ : applyPiOAuthRequestHeaders(new Headers(), '', {
516
+ body,
517
+ identity,
518
+ ...(options.prime && { requestClass: 'auxiliary' }),
519
+ });
461
520
  const relayAffinity = options.streamOptions?.sessionId ?? null;
462
521
  let input = options.apiAccount
463
522
  ? new URL('https://api.anthropic.com/v1/messages')
@@ -469,11 +528,26 @@ async function sendAnthropicRequest(options, deps = {}) {
469
528
  signal: options.streamOptions?.signal,
470
529
  ...(!options.apiAccount && { redirect: 'error' }),
471
530
  };
472
- const trackAcceptedRequest = () => {
473
- if (options.apiAccount || init.signal?.aborted)
531
+ const cacheAccepted = new Set();
532
+ const trackAcceptedRequest = (attempt, sentBody = wireBodyText) => {
533
+ if (options.prime || options.apiAccount || init.signal?.aborted)
534
+ return;
535
+ if (cacheAccepted.has(attempt))
474
536
  return;
475
- if (relayAffinity)
476
- sessionCacheActivity.record(relayAffinity, routeId, cacheTtlMs);
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
+ }
477
551
  const target = {
478
552
  sessionId: relayAffinity,
479
553
  url: input.toString(),
@@ -481,15 +555,22 @@ async function sendAnthropicRequest(options, deps = {}) {
481
555
  bodyText,
482
556
  storage,
483
557
  cacheMode: isCacheKeepHybridActive(storage) ? 'hybrid' : 'disabled',
484
- ttlMs: cacheTtlMs,
558
+ ttlMs: localTtl,
485
559
  oauthAccountId: routeId,
486
560
  oauthAccountIdentity: verifiedUuid,
487
561
  accountStoragePath: options.storagePath,
488
562
  };
489
- if (deps.cacheKeep)
490
- keep.track(target);
491
- else
492
- 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
+ });
493
574
  };
494
575
  const reported = new Set();
495
576
  let retried401 = false;
@@ -504,6 +585,7 @@ async function sendAnthropicRequest(options, deps = {}) {
504
585
  });
505
586
  };
506
587
  const markServed = (attempt) => {
588
+ options.prime?.onServed(attempt);
507
589
  if (used.has(attempt))
508
590
  return;
509
591
  used.add(attempt);
@@ -522,6 +604,7 @@ async function sendAnthropicRequest(options, deps = {}) {
522
604
  : await (await native.service()).getRelayConfig();
523
605
  let threadRequest;
524
606
  if (!options.apiAccount &&
607
+ !options.prime &&
525
608
  isPiPrimaryThreadRequest(options.storagePath, options.streamOptions, options.requestOrigin) &&
526
609
  (!relayConfig ||
527
610
  effectiveRelayTransport(relayConfig.transport, relayConfig.url) !==
@@ -530,7 +613,9 @@ async function sendAnthropicRequest(options, deps = {}) {
530
613
  threadRequest = await prepareMessageThreadRequest(messageThreads, {
531
614
  session: relayAffinity ?? undefined,
532
615
  account: nextAttempt.accountIdentity,
533
- credential: piAttemptAccessToken(nextAttempt),
616
+ credential: nextAttempt.source === 'vault'
617
+ ? nextAttempt.receipt.credentialId
618
+ : localMessageThreadCredential(nextAttempt.admission.binding),
534
619
  bodyText,
535
620
  replyToolNames: toolNames,
536
621
  headers,
@@ -571,6 +656,9 @@ async function sendAnthropicRequest(options, deps = {}) {
571
656
  // it is reported, dumped or cancelled.
572
657
  const physical = {};
573
658
  const send = async () => {
659
+ await options.prime?.beforeSend();
660
+ init.signal?.throwIfAborted();
661
+ assertHostAuthorityStable();
574
662
  const scope = createProviderErrorResponseScope([secret], 'event-stream');
575
663
  physical.scope = scope;
576
664
  // OAuth bodies go gzipped as Claude Code sends them; `bodyText` stays
@@ -582,7 +670,16 @@ async function sendAnthropicRequest(options, deps = {}) {
582
670
  body: init.body,
583
671
  headers,
584
672
  latch: getRequestGzipLatch(getRequestGzipLatchPath(options.storagePath)),
585
- send: (wireBody, wireHeaders) => fetchImpl(input, { ...init, body: wireBody, headers: wireHeaders }),
673
+ send: async (wireBody, wireHeaders) => {
674
+ await options.prime?.beforeSend();
675
+ init.signal?.throwIfAborted();
676
+ assertHostAuthorityStable();
677
+ return fetchImpl(input, {
678
+ ...init,
679
+ body: wireBody,
680
+ headers: wireHeaders,
681
+ });
682
+ },
586
683
  }));
587
684
  };
588
685
  let response;
@@ -656,10 +753,10 @@ async function sendAnthropicRequest(options, deps = {}) {
656
753
  }
657
754
  if (apiSubject && response.ok) {
658
755
  const subject = apiSubject;
659
- native.usagePublications.publish(() => servingRuntime.publishApi(subject, { lastUsed: Date.now() }));
756
+ native.usagePublications.publish(() => servingRuntime.publishApi(subject, { lastUsed: Date.now() }, native.usagePublications.signal));
660
757
  }
661
758
  if (attempt && response.ok) {
662
- trackAcceptedRequest();
759
+ trackAcceptedRequest(attempt);
663
760
  markServed(attempt);
664
761
  }
665
762
  return response;
@@ -682,15 +779,21 @@ async function sendAnthropicRequest(options, deps = {}) {
682
779
  affinity: relayAffinity,
683
780
  authorizeAttempt: async () => {
684
781
  const attempt = await takeAttempt();
782
+ await options.prime?.beforeSend();
783
+ init.signal?.throwIfAborted();
784
+ assertHostAuthorityStable();
685
785
  relayAttempt = attempt;
686
786
  lastTransport = 'relay';
687
787
  const authorizedHeaders = new Headers(headers);
788
+ const sentBody = wireBodyText;
688
789
  const access = piAttemptAccessToken(attempt);
689
790
  authorizedHeaders.set('authorization', `Bearer ${access}`);
690
791
  return {
691
792
  headers: authorizedHeaders,
692
793
  errorSecrets: [access],
693
794
  onUpstreamStatus: (status) => {
795
+ if (status >= 200 && status < 300)
796
+ trackAcceptedRequest(attempt, sentBody);
694
797
  if (status === 401) {
695
798
  relay401Attempt = attempt;
696
799
  // The relay can report an upstream 401 after returning the streaming response.
@@ -733,7 +836,15 @@ async function sendAnthropicRequest(options, deps = {}) {
733
836
  response = threadRequest.observe(response);
734
837
  }
735
838
  if (response.ok && lastTransport === 'relay' && relayAttempt) {
736
- trackAcceptedRequest();
839
+ if (options.prime &&
840
+ !/^req_[A-Za-z0-9_-]+$/.test(response.headers.get('request-id') ?? '')) {
841
+ void response.body?.cancel().catch(() => { });
842
+ throw new Error('Pi Prime relay response has no upstream provenance');
843
+ }
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);
737
848
  markServed(relayAttempt);
738
849
  }
739
850
  return response;
@@ -1404,6 +1515,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1404
1515
  buildPiOAuthMessagesUrl(model.baseUrl);
1405
1516
  const storagePath = getPiAccountStoragePath();
1406
1517
  let toolNames = new Map();
1518
+ let recordCacheUsage;
1407
1519
  const request = {
1408
1520
  model,
1409
1521
  context,
@@ -1413,6 +1525,9 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1413
1525
  onThreadPrepared: (fail) => {
1414
1526
  failThread = fail;
1415
1527
  },
1528
+ onCacheUsageRecorder: (record) => {
1529
+ recordCacheUsage = record;
1530
+ },
1416
1531
  effortTransitions,
1417
1532
  onResolvedToolNames: (names) => {
1418
1533
  toolNames = names;
@@ -1472,6 +1587,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1472
1587
  const blocks = output.content;
1473
1588
  for await (const event of parseSse(response)) {
1474
1589
  if (event.type === 'message_start') {
1590
+ recordCacheUsage?.(event.message?.usage);
1475
1591
  updateUsage(model, output, event.message?.usage);
1476
1592
  }
1477
1593
  else if (event.type === 'content_block_start') {
@@ -1614,6 +1730,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1614
1730
  }
1615
1731
  }
1616
1732
  else if (event.type === 'message_delta') {
1733
+ recordCacheUsage?.(event.usage);
1617
1734
  output.stopReason = mapStopReason(String(event.delta?.stop_reason ?? ''));
1618
1735
  updateUsage(model, output, event.usage);
1619
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.5.8",
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.5.8"
39
+ "@cortexkit/anthropic-auth-core": "2.7.0"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",