@cortexkit/pi-anthropic-auth 2.5.7 → 2.6.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/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,14 @@ declare function sendAnthropicRequest(options: {
40
44
  effortTransitions?: readonly MidConversationEffortTransition[];
41
45
  onResolvedToolNames?: (toolNames: ReadonlyMap<string, string>) => void;
42
46
  onThreadPrepared?: (fail: () => void) => void;
47
+ prime?: {
48
+ beforeSend: () => Promise<void>;
49
+ onServed: (attempt: PiNativeAttempt) => void;
50
+ };
43
51
  }, deps?: {
44
52
  fetch?: typeof fetch;
45
53
  cacheKeep?: CacheKeepManager;
54
+ native?: PiNativeRuntime;
46
55
  }): Promise<Response>;
47
56
  /** Exercise one native send with isolated transport and scheduling in tests. */
48
57
  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, 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';
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]));
@@ -403,10 +405,57 @@ export async function* parseSse(response) {
403
405
  reader.releaseLock();
404
406
  }
405
407
  }
408
+ function buildPiPrimeBody(identity) {
409
+ const prime = buildPrimeRequestBody();
410
+ const body = {
411
+ ...prime,
412
+ system: [
413
+ {
414
+ type: 'text',
415
+ text: buildBillingHeaderValue(prime.messages, undefined, CLAUDE_CODE_ENTRYPOINT),
416
+ },
417
+ { type: 'text', text: CLAUDE_CODE_IDENTITY },
418
+ { type: 'text', text: prime.system },
419
+ ],
420
+ };
421
+ if (identity)
422
+ applyClaudeCodeMetadata(body, identity);
423
+ return {
424
+ body,
425
+ bodyText: JSON.stringify(orderClaudeCodeBody(body)),
426
+ toolNames: new Map(),
427
+ cacheTtlMs: 0,
428
+ };
429
+ }
430
+ /** Prime uses the model transport without a conversation, thread or cache target. */
431
+ export function sendPiPrimeRequest(options) {
432
+ return sendAnthropicRequest({
433
+ model: {
434
+ id: buildPrimeRequestBody().model,
435
+ name: 'Prime',
436
+ api: 'anthropic-messages',
437
+ provider: 'anthropic',
438
+ baseUrl: 'https://api.anthropic.com',
439
+ reasoning: false,
440
+ input: ['text'],
441
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
442
+ contextWindow: 200_000,
443
+ maxTokens: 1,
444
+ },
445
+ context: { messages: [] },
446
+ storagePath: options.storagePath,
447
+ oauthAccountId: options.accountId,
448
+ streamOptions: { signal: options.signal },
449
+ route: 'prime',
450
+ prime: options,
451
+ }, { native: options.native, fetch: options.fetch });
452
+ }
453
+ registerPiPrimeSender(sendPiPrimeRequest);
406
454
  async function sendAnthropicRequest(options, deps = {}) {
455
+ assertHostAuthorityStable();
407
456
  const fetchImpl = deps.fetch ?? globalThis.fetch;
408
457
  const keep = deps.cacheKeep ?? cacheKeepManager;
409
- const native = getPiNativeRuntime(options.storagePath);
458
+ const native = deps.native ?? getPiNativeRuntime(options.storagePath);
410
459
  // Capture the serving service while authorization is open. Shutdown rejects
411
460
  // new serving work immediately but drains writes for already-served attempts.
412
461
  const servingRuntime = await native.service();
@@ -438,26 +487,34 @@ async function sendAnthropicRequest(options, deps = {}) {
438
487
  // activity below follows the final serialized body, since hooks can edit TTLs.
439
488
  const oneHourCache = isCache1hPersistentlyEnabled(storage) ||
440
489
  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
- });
490
+ const { body, bodyText, toolNames, cacheTtlMs } = options.prime
491
+ ? buildPiPrimeBody(identity)
492
+ : await buildAnthropicRequest(options.model.id, options.context, options.streamOptions, {
493
+ enabled: oneHourCache,
494
+ mode: getCache1hPersistentMode(storage),
495
+ }, isFastModePersistentlyEnabled(storage), identity, {
496
+ deferSigning: true,
497
+ effortTransitions: options.apiAccount
498
+ ? []
499
+ : options.effortTransitions,
500
+ turnEndNote: storage.turnEndNote,
501
+ thinkingPrefixMismatchBehavior: options.apiAccount
502
+ ? 'account-default'
503
+ : getThinkingPrefixMismatchBehavior(storage),
504
+ ...(options.streamOptions?.onPayload && {
505
+ onPayload: (payload) => options.streamOptions?.onPayload?.(payload, options.model),
506
+ }),
507
+ });
455
508
  let wireBodyText = bodyText;
456
509
  options.onResolvedToolNames?.(toolNames);
457
510
  const fastMode = body.speed === 'fast';
458
511
  const headers = options.apiAccount
459
512
  ? new Headers()
460
- : applyPiOAuthRequestHeaders(new Headers(), '', { body, identity });
513
+ : applyPiOAuthRequestHeaders(new Headers(), '', {
514
+ body,
515
+ identity,
516
+ ...(options.prime && { requestClass: 'auxiliary' }),
517
+ });
461
518
  const relayAffinity = options.streamOptions?.sessionId ?? null;
462
519
  let input = options.apiAccount
463
520
  ? new URL('https://api.anthropic.com/v1/messages')
@@ -470,7 +527,7 @@ async function sendAnthropicRequest(options, deps = {}) {
470
527
  ...(!options.apiAccount && { redirect: 'error' }),
471
528
  };
472
529
  const trackAcceptedRequest = () => {
473
- if (options.apiAccount || init.signal?.aborted)
530
+ if (options.prime || options.apiAccount || init.signal?.aborted)
474
531
  return;
475
532
  if (relayAffinity)
476
533
  sessionCacheActivity.record(relayAffinity, routeId, cacheTtlMs);
@@ -504,6 +561,7 @@ async function sendAnthropicRequest(options, deps = {}) {
504
561
  });
505
562
  };
506
563
  const markServed = (attempt) => {
564
+ options.prime?.onServed(attempt);
507
565
  if (used.has(attempt))
508
566
  return;
509
567
  used.add(attempt);
@@ -522,6 +580,7 @@ async function sendAnthropicRequest(options, deps = {}) {
522
580
  : await (await native.service()).getRelayConfig();
523
581
  let threadRequest;
524
582
  if (!options.apiAccount &&
583
+ !options.prime &&
525
584
  isPiPrimaryThreadRequest(options.storagePath, options.streamOptions, options.requestOrigin) &&
526
585
  (!relayConfig ||
527
586
  effectiveRelayTransport(relayConfig.transport, relayConfig.url) !==
@@ -530,7 +589,9 @@ async function sendAnthropicRequest(options, deps = {}) {
530
589
  threadRequest = await prepareMessageThreadRequest(messageThreads, {
531
590
  session: relayAffinity ?? undefined,
532
591
  account: nextAttempt.accountIdentity,
533
- credential: piAttemptAccessToken(nextAttempt),
592
+ credential: nextAttempt.source === 'vault'
593
+ ? nextAttempt.receipt.credentialId
594
+ : localMessageThreadCredential(nextAttempt.admission.binding),
534
595
  bodyText,
535
596
  replyToolNames: toolNames,
536
597
  headers,
@@ -571,6 +632,9 @@ async function sendAnthropicRequest(options, deps = {}) {
571
632
  // it is reported, dumped or cancelled.
572
633
  const physical = {};
573
634
  const send = async () => {
635
+ await options.prime?.beforeSend();
636
+ init.signal?.throwIfAborted();
637
+ assertHostAuthorityStable();
574
638
  const scope = createProviderErrorResponseScope([secret], 'event-stream');
575
639
  physical.scope = scope;
576
640
  // OAuth bodies go gzipped as Claude Code sends them; `bodyText` stays
@@ -582,7 +646,16 @@ async function sendAnthropicRequest(options, deps = {}) {
582
646
  body: init.body,
583
647
  headers,
584
648
  latch: getRequestGzipLatch(getRequestGzipLatchPath(options.storagePath)),
585
- send: (wireBody, wireHeaders) => fetchImpl(input, { ...init, body: wireBody, headers: wireHeaders }),
649
+ send: async (wireBody, wireHeaders) => {
650
+ await options.prime?.beforeSend();
651
+ init.signal?.throwIfAborted();
652
+ assertHostAuthorityStable();
653
+ return fetchImpl(input, {
654
+ ...init,
655
+ body: wireBody,
656
+ headers: wireHeaders,
657
+ });
658
+ },
586
659
  }));
587
660
  };
588
661
  let response;
@@ -656,7 +729,7 @@ async function sendAnthropicRequest(options, deps = {}) {
656
729
  }
657
730
  if (apiSubject && response.ok) {
658
731
  const subject = apiSubject;
659
- native.usagePublications.publish(() => servingRuntime.publishApi(subject, { lastUsed: Date.now() }));
732
+ native.usagePublications.publish(() => servingRuntime.publishApi(subject, { lastUsed: Date.now() }, native.usagePublications.signal));
660
733
  }
661
734
  if (attempt && response.ok) {
662
735
  trackAcceptedRequest();
@@ -682,6 +755,9 @@ async function sendAnthropicRequest(options, deps = {}) {
682
755
  affinity: relayAffinity,
683
756
  authorizeAttempt: async () => {
684
757
  const attempt = await takeAttempt();
758
+ await options.prime?.beforeSend();
759
+ init.signal?.throwIfAborted();
760
+ assertHostAuthorityStable();
685
761
  relayAttempt = attempt;
686
762
  lastTransport = 'relay';
687
763
  const authorizedHeaders = new Headers(headers);
@@ -733,6 +809,11 @@ async function sendAnthropicRequest(options, deps = {}) {
733
809
  response = threadRequest.observe(response);
734
810
  }
735
811
  if (response.ok && lastTransport === 'relay' && relayAttempt) {
812
+ if (options.prime &&
813
+ !/^req_[A-Za-z0-9_-]+$/.test(response.headers.get('request-id') ?? '')) {
814
+ void response.body?.cancel().catch(() => { });
815
+ throw new Error('Pi Prime relay response has no upstream provenance');
816
+ }
736
817
  trackAcceptedRequest();
737
818
  markServed(relayAttempt);
738
819
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.5.7",
3
+ "version": "2.6.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.7"
39
+ "@cortexkit/anthropic-auth-core": "2.6.0"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",