@cortexkit/pi-anthropic-auth 2.14.0 → 2.15.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/convert.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type Cache1hMode, type ClaudeCodeIdentity, type MidConversationEffortTransition, type ThinkingPrefixMismatchBehavior } from '@cortexkit/anthropic-auth-core';
2
2
  import type { Context, SimpleStreamOptions, Tool } from '@earendil-works/pi-ai';
3
+ import { type PiForkEffortHint } from './forks.ts';
3
4
  export type AnthropicRequestBody = {
4
5
  model: string;
5
6
  max_tokens: number;
@@ -47,6 +48,9 @@ export declare function buildAnthropicRequest(modelId: string, context: Context,
47
48
  mode: Cache1hMode;
48
49
  }, fastModeEnabled?: boolean, identity?: ClaudeCodeIdentity, controls?: {
49
50
  effortTransitions?: readonly MidConversationEffortTransition[];
51
+ forkBaseMessageCount?: number;
52
+ /** A fork's lower answer effort, applied to its question turn only. */
53
+ forkEffort?: PiForkEffortHint;
50
54
  /** Leave the billing signature placeholder for the transport to finalize. */
51
55
  deferSigning?: boolean;
52
56
  thinkingPrefixMismatchBehavior?: ThinkingPrefixMismatchBehavior;
@@ -65,4 +69,6 @@ export declare function buildAnthropicRequest(modelId: string, context: Context,
65
69
  bodyText: string;
66
70
  toolNames: ReadonlyMap<string, string>;
67
71
  cacheTtlMs: number;
72
+ /** Set only when `controls.forkEffort` changed the request. */
73
+ forkEffortApplied?: PiForkEffortHint;
68
74
  }>;
package/dist/convert.js CHANGED
@@ -1,4 +1,5 @@
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';
1
+ import { applyClaudeCodeMetadata, 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
+ import { applyPiForkEffort, PiForkRefusal, piForkHeadSession, } from './forks.js';
2
3
  import { collapseSystemMessages, getCurrentSystemPrompt, getCurrentTools, normalizeContext, } from './transcript.js';
3
4
  // Anchor identifying Pi's documentation paragraph — the only part of the prompt
4
5
  // that Anthropic currently rejects in system[]. Unknown prompt shapes take the
@@ -446,6 +447,55 @@ function walkCacheControlHolders(body, visit) {
446
447
  visit(record);
447
448
  }
448
449
  }
450
+ function applyForkCacheBridge(body, baseIndex) {
451
+ if (baseIndex < 0)
452
+ return;
453
+ const base = body.messages[baseIndex];
454
+ const blocks = body.messages.flatMap((message) => Array.isArray(message.content)
455
+ ? message.content
456
+ : typeof message.content === 'string'
457
+ ? [message]
458
+ : []);
459
+ const baseBlock = Array.isArray(base?.content)
460
+ ? base.content.at(-1)
461
+ : undefined;
462
+ if (!baseBlock || baseBlock.cache_control)
463
+ return;
464
+ const newest = body.cache_control
465
+ ? body
466
+ : blocks.findLast((block) => block.cache_control);
467
+ const newestPosition = newest === body ? blocks.length - 1 : blocks.indexOf(newest ?? {});
468
+ if (!newest || newestPosition - blocks.indexOf(baseBlock) <= 20)
469
+ return;
470
+ const control = newest.cache_control;
471
+ const holders = [];
472
+ walkCacheControlHolders(body, (holder) => holders.push(holder));
473
+ const ttl = (holder) => holder.cache_control?.ttl === '1h'
474
+ ? 3_600_000
475
+ : 300_000;
476
+ const basePosition = blocks.indexOf(baseBlock);
477
+ // Tools and system precede messages on the wire. Never insert a long-lived
478
+ // marker after a short-lived one, including markers a payload hook supplied.
479
+ if (holders.some((holder) => {
480
+ if (holder === body)
481
+ return false;
482
+ const index = blocks.indexOf(holder);
483
+ return index < 0 || index < basePosition
484
+ ? ttl(holder) < ttl(newest)
485
+ : ttl(holder) > ttl(newest);
486
+ }))
487
+ return;
488
+ const systemAnchor = body.system?.findLast((block) => block.cache_control);
489
+ const removable = holders.find((holder) => holder !== systemAnchor && holder !== newest && blocks.includes(holder)) ?? holders.find((holder) => body.tools?.includes(holder));
490
+ if (holders.length >= 4 && !removable)
491
+ return;
492
+ // Drop the oldest ordinary message marker (normally the prompt paragraph),
493
+ // or the tool marker if none exists. The protected system anchor still covers
494
+ // the fixed prefix; preserving the frozen base outranks those extra anchors.
495
+ if (holders.length >= 4 && removable)
496
+ delete removable.cache_control;
497
+ baseBlock.cache_control = { ...control };
498
+ }
449
499
  /**
450
500
  * Anthropic accepts at most four cache breakpoints per request. This provider
451
501
  * composes its own body and has already placed exactly four
@@ -486,6 +536,13 @@ export function piThreadCacheSlot(body) {
486
536
  return body.system.findLast((block) => block && typeof block === 'object' && block.cache_control);
487
537
  }
488
538
  export async function buildAnthropicRequest(modelId, context, options, cache, fastModeEnabled = false, identity, controls = {}) {
539
+ const forkBase = controls.forkBaseMessageCount === undefined
540
+ ? undefined
541
+ : collapseSystemMessages(normalizeContext({
542
+ ...context,
543
+ systemPrompt: systemPromptText(context.systemPrompt),
544
+ messages: context.messages.slice(0, controls.forkBaseMessageCount),
545
+ }));
489
546
  // Pi 0.86 passes a normalized transcript to providers, and later system
490
547
  // messages can change the prompt, its named sections and the tool set. Resolve
491
548
  // them through the local replay port; raw host prompts (including ordered OMP
@@ -506,11 +563,26 @@ export async function buildAnthropicRequest(modelId, context, options, cache, fa
506
563
  const visibleReplies = new WeakMap();
507
564
  const messages = convertMessages(context.messages, modelId, visibleReplies);
508
565
  stripEmptyTrailingAssistantMessages(messages);
566
+ const baseLastMessage = forkBase
567
+ ? messages[convertMessages(forkBase.messages, modelId, new WeakMap()).length - 1]
568
+ : undefined;
569
+ // The head's final user block was an array so it could carry its cache
570
+ // marker. Keep that block shape when it is no longer the fork's newest user.
571
+ if (baseLastMessage && typeof baseLastMessage.content === 'string')
572
+ baseLastMessage.content = [{ type: 'text', text: baseLastMessage.content }];
573
+ const forkHead = piForkHeadSession(options);
574
+ const forkFirstUserText = forkHead
575
+ ? firstUserTextTracker.peek(forkHead)
576
+ : undefined;
577
+ if (forkHead && forkFirstUserText === undefined)
578
+ throw new PiForkRefusal('base');
509
579
  const system = [
510
580
  {
511
581
  type: 'text',
512
582
  text: buildBillingHeaderValue(messages, undefined, CLAUDE_CODE_ENTRYPOINT, options?.sessionId
513
- ? firstUserTextTracker.resolve(options.sessionId, messages)
583
+ ? forkHead
584
+ ? forkFirstUserText
585
+ : firstUserTextTracker.resolve(options.sessionId, messages)
514
586
  : undefined),
515
587
  },
516
588
  { type: 'text', text: CLAUDE_CODE_IDENTITY },
@@ -617,7 +689,7 @@ export async function buildAnthropicRequest(modelId, context, options, cache, fa
617
689
  };
618
690
  }
619
691
  }
620
- applyMidConversationOutputConfig(body, controls.effortTransitions ?? []);
692
+ const forkEffortApplied = applyPiForkEffort(body, controls.effortTransitions ?? [], controls.forkEffort);
621
693
  if (identity) {
622
694
  applyTurnEndNotes(body, {
623
695
  tools: controls.turnEndNote?.tools,
@@ -637,12 +709,17 @@ export async function buildAnthropicRequest(modelId, context, options, cache, fa
637
709
  applyThinkingBindingControls(body, controls.thinkingPrefixMismatchBehavior ?? 'account-default');
638
710
  applyClaudeCodeMetadata(body, identity);
639
711
  }
712
+ const baseBoundary = baseLastMessage
713
+ ? body.messages.indexOf(baseLastMessage)
714
+ : -1;
640
715
  const replaced = controls.onPayload
641
716
  ? await controls.onPayload(body)
642
717
  : undefined;
643
718
  if (replaced !== undefined)
644
719
  body = { ...replaced, stream: true };
645
720
  applySessionCacheTtl(body, cachePolicy?.ttl);
721
+ if (baseBoundary >= 0)
722
+ applyForkCacheBridge(body, baseBoundary);
646
723
  // As in Pi's native adapter, replacements must still request SSE. Hooks own
647
724
  // the validity of their other edits and must not add a fifth cache breakpoint:
648
725
  // the provider's existing layout may already use Anthropic's four slots.
@@ -666,5 +743,11 @@ export async function buildAnthropicRequest(modelId, context, options, cache, fa
666
743
  // session waits on its account. Include hook edits, not the account setting;
667
744
  // a cache_control key inside tool data is not a cache breakpoint.
668
745
  const cacheTtlMs = requestCacheLifetimeMs(sentBody);
669
- return { body, bodyText, toolNames, cacheTtlMs };
746
+ return {
747
+ body,
748
+ bodyText,
749
+ toolNames,
750
+ cacheTtlMs,
751
+ ...(forkEffortApplied && { forkEffortApplied }),
752
+ };
670
753
  }
@@ -0,0 +1,48 @@
1
+ import { type MidConversationEffortTransition } from '@cortexkit/anthropic-auth-core';
2
+ import type { Context, SimpleStreamOptions } from '@earendil-works/pi-ai';
3
+ /** Unknown Pi options survive provider dispatch; only a distinct, named fork opts in. */
4
+ export declare function piForkHeadSession(options?: SimpleStreamOptions): string | undefined;
5
+ /** Effort levels Agent Runner may ask a fork to answer at. It can only lower effort. */
6
+ export type PiForkEffortHint = 'low' | 'medium' | 'high';
7
+ /**
8
+ * The fork's requested answer effort, or undefined when the request is not a
9
+ * valid fork or the value is not one of the levels Agent Runner defines.
10
+ */
11
+ export declare function piForkEffortHint(options?: SimpleStreamOptions): PiForkEffortHint | undefined;
12
+ /** Set on a fork's reply only when its effort hint changed the request. */
13
+ export type PiForkReplyReport = {
14
+ cortexkitFork?: {
15
+ effortApplied: PiForkEffortHint;
16
+ };
17
+ };
18
+ /**
19
+ * Apply the fork base's effort history to `body`, as a head request would, and
20
+ * lower the effort of the fork's question (its last message) to `hint` when
21
+ * that is safe. Returns the hint only when it changed the request.
22
+ *
23
+ * The hint becomes one more effort transition at the question's user turn, so
24
+ * the model receives it exactly as a head's own mid-conversation effort change.
25
+ * It applies only when it is lower than the effort in force at the question,
26
+ * and only on models that accept a per-message effort without moving the
27
+ * top-level effort. Every message before the question and the top-level effort
28
+ * must come out identical to the request without the hint, because the fork
29
+ * reads the head's prompt cache; otherwise the hint is dropped.
30
+ *
31
+ * Like the base history, this decides on Pi's own body before the host's
32
+ * `onPayload` hook runs.
33
+ */
34
+ export declare function applyPiForkEffort(body: Record<string, unknown>, transitions: readonly MidConversationEffortTransition[], hint?: PiForkEffortHint): PiForkEffortHint | undefined;
35
+ export declare class PiForkRefusal extends Error {
36
+ constructor(kind: 'routing' | 'account' | 'limit' | 'failed' | 'base');
37
+ }
38
+ /** Retain provenance, not prompts: a later head turn must not reshape an older fork base. */
39
+ export declare class PiForkEffortSnapshots {
40
+ private readonly sessions;
41
+ record(sessionId: string, context: Context, transitions?: readonly MidConversationEffortTransition[]): void;
42
+ match(headSessionId: string, context: Context): {
43
+ messageCount: number;
44
+ transitions: readonly MidConversationEffortTransition[];
45
+ };
46
+ forget(sessionId: string): void;
47
+ }
48
+ export declare const piForkEffortSnapshots: PiForkEffortSnapshots;
package/dist/forks.js ADDED
@@ -0,0 +1,181 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { applyMidConversationOutputConfig, defaultAdaptiveEffort, normalizeAdaptiveEffort, supportsPerMessageEffort, } from '@cortexkit/anthropic-auth-core';
3
+ /** Unknown Pi options survive provider dispatch; only a distinct, named fork opts in. */
4
+ export function piForkHeadSession(options) {
5
+ const fork = options
6
+ ?.cortexkitFork;
7
+ if (!options?.sessionId || !fork || typeof fork !== 'object')
8
+ return undefined;
9
+ const head = fork.headSessionId;
10
+ return typeof head === 'string' &&
11
+ head.trim().length > 0 &&
12
+ head !== options.sessionId
13
+ ? head
14
+ : undefined;
15
+ }
16
+ /**
17
+ * The fork's requested answer effort, or undefined when the request is not a
18
+ * valid fork or the value is not one of the levels Agent Runner defines.
19
+ */
20
+ export function piForkEffortHint(options) {
21
+ if (!piForkHeadSession(options))
22
+ return undefined;
23
+ const effort = options?.cortexkitFork?.effort;
24
+ return effort === 'low' || effort === 'medium' || effort === 'high'
25
+ ? effort
26
+ : undefined;
27
+ }
28
+ const EFFORT_RANK = {
29
+ low: 0,
30
+ medium: 1,
31
+ high: 2,
32
+ xhigh: 3,
33
+ max: 4,
34
+ };
35
+ function isRecord(value) {
36
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
37
+ }
38
+ function topLevelEffort(body) {
39
+ return (normalizeAdaptiveEffort(isRecord(body.output_config) ? body.output_config.effort : undefined) ?? defaultAdaptiveEffort(body.model));
40
+ }
41
+ /**
42
+ * Apply the fork base's effort history to `body`, as a head request would, and
43
+ * lower the effort of the fork's question (its last message) to `hint` when
44
+ * that is safe. Returns the hint only when it changed the request.
45
+ *
46
+ * The hint becomes one more effort transition at the question's user turn, so
47
+ * the model receives it exactly as a head's own mid-conversation effort change.
48
+ * It applies only when it is lower than the effort in force at the question,
49
+ * and only on models that accept a per-message effort without moving the
50
+ * top-level effort. Every message before the question and the top-level effort
51
+ * must come out identical to the request without the hint, because the fork
52
+ * reads the head's prompt cache; otherwise the hint is dropped.
53
+ *
54
+ * Like the base history, this decides on Pi's own body before the host's
55
+ * `onPayload` hook runs.
56
+ */
57
+ export function applyPiForkEffort(body, transitions, hint) {
58
+ if (!hint) {
59
+ applyMidConversationOutputConfig(body, transitions);
60
+ return undefined;
61
+ }
62
+ // applyMidConversationOutputConfig replaces `messages` and `output_config`
63
+ // rather than editing them, so shallow copies keep `body` untouched.
64
+ const base = { ...body };
65
+ const baseResult = applyMidConversationOutputConfig(base, transitions);
66
+ const lowered = loweredQuestionEffort(base, body, transitions, baseResult, hint);
67
+ Object.assign(body, lowered ?? base);
68
+ return lowered ? hint : undefined;
69
+ }
70
+ function loweredQuestionEffort(base, original, transitions, baseResult, hint) {
71
+ if (!supportsPerMessageEffort(original) || !Array.isArray(base.messages))
72
+ return undefined;
73
+ const baseMessages = base.messages;
74
+ const question = baseMessages.at(-1);
75
+ const previous = baseMessages.at(-2);
76
+ // A marker lands before the first user message after an assistant reply. If
77
+ // the question is not that message, the marker would land earlier and change
78
+ // bytes the head already cached.
79
+ if (!isRecord(question) ||
80
+ question.role !== 'user' ||
81
+ !isRecord(previous) ||
82
+ previous.role !== 'assistant')
83
+ return undefined;
84
+ const topLevel = topLevelEffort(base);
85
+ let inForce = topLevel;
86
+ for (const message of baseMessages) {
87
+ if (isRecord(message) &&
88
+ message.role === 'system' &&
89
+ isRecord(message.output_config))
90
+ inForce = normalizeAdaptiveEffort(message.output_config.effort) ?? inForce;
91
+ }
92
+ if (EFFORT_RANK[hint] >= EFFORT_RANK[inForce])
93
+ return undefined;
94
+ const questionBoundary = baseMessages.filter((message) => isRecord(message) && message.role === 'assistant').length;
95
+ // Start from the top-level effort the base request sends. Base transitions
96
+ // only count when they changed that request; otherwise the top-level effort
97
+ // was in force throughout.
98
+ const lowered = { ...original };
99
+ const result = applyMidConversationOutputConfig(lowered, [
100
+ { afterAssistantMessages: 0, effort: topLevel },
101
+ ...(baseResult.applied ? transitions : []),
102
+ { afterAssistantMessages: questionBoundary, effort: hint },
103
+ ]);
104
+ const messages = lowered.messages;
105
+ const marker = messages.at(-2);
106
+ if (!result.applied ||
107
+ messages.length !== baseMessages.length + 1 ||
108
+ messages.at(-1) !== question ||
109
+ !isRecord(marker) ||
110
+ marker.role !== 'system' ||
111
+ !isRecord(marker.output_config) ||
112
+ marker.output_config.effort !== hint ||
113
+ JSON.stringify(lowered.output_config) !==
114
+ JSON.stringify(base.output_config) ||
115
+ JSON.stringify(messages.slice(0, -2)) !==
116
+ JSON.stringify(baseMessages.slice(0, -1)))
117
+ return undefined;
118
+ return lowered;
119
+ }
120
+ export class PiForkRefusal extends Error {
121
+ constructor(kind) {
122
+ super({
123
+ routing: 'Shared routing has no admission for this fork request.',
124
+ account: 'The admitted account cannot serve this fork request.',
125
+ limit: 'The admitted account declined this fork request.',
126
+ // Upstream errors and transport failures are not account problems.
127
+ failed: 'The fork request failed before an answer arrived.',
128
+ base: 'The retained head request is unavailable for this fork (fork_base_unavailable).',
129
+ }[kind]);
130
+ }
131
+ }
132
+ function canonical(value) {
133
+ if (Array.isArray(value))
134
+ return value.map(canonical);
135
+ if (value && typeof value === 'object')
136
+ return Object.fromEntries(Object.entries(value)
137
+ .sort(([a], [b]) => a.localeCompare(b))
138
+ .map(([key, item]) => [key, canonical(item)]));
139
+ return value;
140
+ }
141
+ function messageDigests(context) {
142
+ return context.messages.map((message) => createHash('sha256')
143
+ .update(JSON.stringify(canonical(message)))
144
+ .digest('hex'));
145
+ }
146
+ /** Retain provenance, not prompts: a later head turn must not reshape an older fork base. */
147
+ export class PiForkEffortSnapshots {
148
+ sessions = new Map();
149
+ record(sessionId, context, transitions = []) {
150
+ const snapshots = this.sessions.get(sessionId) ?? [];
151
+ snapshots.push({
152
+ digests: messageDigests(context),
153
+ transitions: transitions.map((item) => ({ ...item })),
154
+ });
155
+ this.sessions.delete(sessionId);
156
+ this.sessions.set(sessionId, snapshots.slice(-8));
157
+ const oldest = this.sessions.keys().next().value;
158
+ if (this.sessions.size > 128 && oldest !== undefined)
159
+ this.sessions.delete(oldest);
160
+ }
161
+ match(headSessionId, context) {
162
+ const digests = messageDigests(context);
163
+ let snapshot;
164
+ for (const candidate of this.sessions.get(headSessionId) ?? []) {
165
+ if ((!snapshot || candidate.digests.length >= snapshot.digests.length) &&
166
+ candidate.digests.length <= digests.length &&
167
+ candidate.digests.every((digest, index) => digest === digests[index]))
168
+ snapshot = candidate;
169
+ }
170
+ if (!snapshot)
171
+ throw new PiForkRefusal('base');
172
+ return {
173
+ messageCount: snapshot.digests.length,
174
+ transitions: snapshot.transitions,
175
+ };
176
+ }
177
+ forget(sessionId) {
178
+ this.sessions.delete(sessionId);
179
+ }
180
+ }
181
+ export const piForkEffortSnapshots = new PiForkEffortSnapshots();
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
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
+ import { piForkEffortSnapshots, piForkHeadSession } from './forks.js';
4
5
  import { closePiNativeRuntime, getPiNativeRuntime, isNativeMigrationRequired, } from './native.js';
5
6
  import { createPiNativeCommands } from './native-commands.js';
6
7
  import { getPiAccountStoragePath, PI_HOSTED_LOGIN_REFUSAL, requirePiNativeHostAuth, } from './paths.js';
@@ -139,6 +140,7 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
139
140
  if (sessionId) {
140
141
  clearPiStickyQuotaRetries(storagePath, sessionId);
141
142
  effortHistoryBySession.delete(sessionId);
143
+ piForkEffortSnapshots.forget(sessionId);
142
144
  workingMessageBySession.delete(sessionId);
143
145
  sessionCacheActivity.forget(sessionId);
144
146
  forgetPiMessageThread(sessionId);
@@ -286,7 +288,7 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
286
288
  // Stock Pi's simplified calls share the session's whole-turn lease. Core
287
289
  // checks the exact history and retained reply before continuing any anchor.
288
290
  streamSimple: (model, context, options, origin = 'agent-loop') => streamCortexKitAnthropic(model, context, options, options?.sessionId
289
- ? effortHistoryBySession.get(options.sessionId)
291
+ ? effortHistoryBySession.get(piForkHeadSession(options) ?? options.sessionId)
290
292
  : undefined, {
291
293
  ...quotaWait,
292
294
  setWorkingMessage: (options?.sessionId
@@ -293,12 +293,18 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
293
293
  const storage = snapshot.policyStorage;
294
294
  const settingsStatus = (summary) => {
295
295
  const status = runtime.getSettingsStatus?.();
296
+ const modeStatus = runtime.getSettingsModeStatus?.();
296
297
  const relayNotes = runtime.getRelayStatusNotes?.() ?? [];
297
298
  if (!status)
298
- return [summary, ...relayNotes].join('\n');
299
+ return [
300
+ summary,
301
+ ...(modeStatus ? [modeStatus] : []),
302
+ ...relayNotes,
303
+ ].join('\n');
299
304
  const { file } = status;
300
305
  return [
301
306
  summary,
307
+ ...(modeStatus ? [modeStatus] : []),
302
308
  `Settings file: ${file.file}`,
303
309
  ...(file.missing
304
310
  ? ['Settings file is missing; a menu write will recreate it.']
package/dist/native.js CHANGED
@@ -157,6 +157,7 @@ export class PiNativeRuntime {
157
157
  settingsFallback: settings.fallback,
158
158
  settingsReopen: settings.reopen,
159
159
  settingsMode: () => settings.mode,
160
+ settingsDiagnostic: settings.diagnostic,
160
161
  settingsAuthority: options.settings?.authority,
161
162
  });
162
163
  try {
package/dist/stream.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type AccountStorage, type ApiKeyAccount, type CacheKeepManager, createAnthropicStreamCompletion, createRoutingRelay, type MidConversationEffortTransition, type NativeAccountSnapshot, type NativeAccountView, type OAuthAccount, QuotaManager, type QuotaManagerOptions, type RoutingChoice } 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 PiForkEffortHint } from './forks.ts';
3
4
  import { type PiNativeAttempt, type PiNativeRuntime } from './native.ts';
4
5
  import { type PiPrimeSendOptions } from './prime.ts';
5
6
  import { type PiQuotaWaitOptions } from './quota-wait.ts';
@@ -56,6 +57,7 @@ declare function sendAnthropicRequestAttempt(options: {
56
57
  route?: string;
57
58
  effortTransitions?: readonly MidConversationEffortTransition[];
58
59
  onResolvedToolNames?: (toolNames: ReadonlyMap<string, string>) => void;
60
+ onForkEffortApplied?: (effort: PiForkEffortHint | undefined) => void;
59
61
  onThreadPrepared?: (fail: () => void) => void;
60
62
  onCacheUsageRecorder?: (record: (usage?: Record<string, number>) => void) => void;
61
63
  prime?: {
@@ -91,6 +93,7 @@ declare function executeWithFallback(options: {
91
93
  storagePath: string;
92
94
  effortTransitions?: readonly MidConversationEffortTransition[];
93
95
  onResolvedToolNames?: (toolNames: ReadonlyMap<string, string>) => void;
96
+ onForkEffortApplied?: (effort: PiForkEffortHint | undefined) => void;
94
97
  onThreadPrepared?: (fail: () => void) => void;
95
98
  routingRelay?: ReturnType<typeof createRoutingRelay>;
96
99
  routingState?: {
package/dist/stream.js CHANGED
@@ -1,7 +1,8 @@
1
- import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyClaudeGatewayHeaders, applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, buildPrimeRequestBody, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, CLAUDE_CODE_ACCEPT_ENCODING, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, claudeGatewayHeaderValues, claudeGatewayModelUrl, copyStreamResponseTiming, createAnthropicStreamCompletion, createDumpResponseObserver, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createRoutingRelay, createSseFramer, createStickyNoRouteResponse, currentCacheKeepRealTurn, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, dumpResponseArtifact, effectiveRelayTransport, FAST_MODE_BETA, getCache1hPersistentMode, getCacheKeepRegistryDirectories, getClaudeCodeIdentityForVerifiedAccount, getFallbackReauthLabels, getMaxSameAccountWait, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, hostRetryHeaders, hostRetryResponse, isCache1hPersistentlyEnabled, isCacheKeepHybridActive, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isNativeTransientAccountError, isOAuthAccount, isPermanentRefreshError, isValidApiBaseURL, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, localMessageThreadCredential, logger, MessageThreadTracker, mergeAnthropicBetas, NativeAccountRefusal, nativeAccountCanServe, orderClaudeCodeBody, PROMPT_CACHE_DEFAULT_TTL_MS, parseSseFrame, prepareMessageThreadRequest, QuotaManager, quotaBackoffActive, quotaExhaustionFromHeaders, quotaRefusalTiming, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, readSessionCachePolicy, reportRoutingResponse, reportSessionCacheTouch, requestCacheLifetimeMs, requestShortestCacheLifetimeMs, resolveNativePoolPaths, routingCandidates, routingChoiceMatches, routingWarmCredential, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, startRoutingWait, stickyQuotaSnapshotIsFresh, stickyRetainRetryHeaders, stickyRetryAfterWithJitter, stickyRouteCandidateWeight, stickyRouteFamilyForModel, warnClaudeGatewayRelayIgnored, withAnthropicBilling, withCacheKeepRealTurn, } from '@cortexkit/anthropic-auth-core';
1
+ import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyClaudeGatewayHeaders, applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, buildPrimeRequestBody, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, CLAUDE_CODE_ACCEPT_ENCODING, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, claudeGatewayHeaderValues, claudeGatewayModelUrl, copyStreamResponseTiming, createAnthropicStreamCompletion, createDumpResponseObserver, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createRoutingRelay, createSseFramer, createStickyNoRouteResponse, currentCacheKeepRealTurn, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, dumpResponseArtifact, effectiveRelayTransport, FAST_MODE_BETA, getCache1hPersistentMode, getCacheKeepRegistryDirectories, getClaudeCodeIdentityForVerifiedAccount, getFallbackReauthLabels, getMaxSameAccountWait, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, hostRetryHeaders, hostRetryResponse, isCache1hPersistentlyEnabled, isCacheKeepHybridActive, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isNativeTransientAccountError, isOAuthAccount, isPermanentRefreshError, isValidApiBaseURL, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, localMessageThreadCredential, logger, MessageThreadTracker, mergeAnthropicBetas, NativeAccountRefusal, nativeAccountCanServe, orderClaudeCodeBody, PROMPT_CACHE_DEFAULT_TTL_MS, parseSseFrame, prepareMessageThreadRequest, QuotaManager, quotaBackoffActive, quotaExhaustionFromHeaders, quotaRefusalTiming, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, raceWithSignal, readSessionCachePolicy, reportRoutingResponse, reportSessionCacheTouch, requestCacheLifetimeMs, requestShortestCacheLifetimeMs, resolveNativePoolPaths, routingCandidates, routingChoiceMatches, routingWarmCredential, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, startRoutingWait, stickyQuotaSnapshotIsFresh, stickyRetainRetryHeaders, stickyRetryAfterWithJitter, stickyRouteCandidateWeight, stickyRouteFamilyForModel, warnClaudeGatewayRelayIgnored, withAnthropicBilling, withCacheKeepRealTurn, } from '@cortexkit/anthropic-auth-core';
2
2
  import { calculateCost, createAssistantMessageEventStream, } from '@earendil-works/pi-ai';
3
3
  import { PiCacheKeep } from './cachekeep.js';
4
4
  import { buildAnthropicRequest, fromClaudeCodeToolName, piThreadCacheSlot, } from './convert.js';
5
+ import { PiForkRefusal, piForkEffortHint, piForkEffortSnapshots, piForkHeadSession, } from './forks.js';
5
6
  import { getPiNativeRuntime, peekPiNativeSnapshot, piAttemptAccessToken, piClaudeGatewayFromMemory, resolvePiSettingsFromMemory, } from './native.js';
6
7
  import { getPiAccountStoragePath } from './paths.js';
7
8
  import { registerPiPrimeSender } from './prime.js';
@@ -386,6 +387,11 @@ function updateUsage(model, output, usage) {
386
387
  usage.cache_read_input_tokens ?? output.usage.cacheRead;
387
388
  output.usage.cacheWrite =
388
389
  usage.cache_creation_input_tokens ?? output.usage.cacheWrite;
390
+ // Pi prices `cacheWrite1h` (a subset of `cacheWrite`) at the one-hour rate;
391
+ // without it every cache write is priced as a five-minute write.
392
+ const longWrite = usage.cache_creation?.ephemeral_1h_input_tokens;
393
+ if (typeof longWrite === 'number')
394
+ output.usage.cacheWrite1h = longWrite;
389
395
  output.usage.totalTokens =
390
396
  output.usage.input +
391
397
  output.usage.output +
@@ -519,10 +525,14 @@ export function sendPiPrimeRequest(options) {
519
525
  registerPiPrimeSender(sendPiPrimeRequest);
520
526
  async function sendAnthropicRequest(...args) {
521
527
  const [options, deps = {}] = args;
522
- const inherited = currentCacheKeepRealTurn();
528
+ const forkHead = piForkHeadSession(options.streamOptions);
529
+ const inherited = forkHead ? undefined : currentCacheKeepRealTurn();
523
530
  let turn = inherited;
524
531
  try {
525
- if (!turn && !options.prime && options.streamOptions?.sessionId)
532
+ if (!turn &&
533
+ !forkHead &&
534
+ !options.prime &&
535
+ options.streamOptions?.sessionId)
526
536
  turn = deps.cacheKeep
527
537
  ? deps.cacheKeep.beginRealTurn(options.streamOptions.sessionId)
528
538
  : piCacheKeep.requestTurn(options.streamOptions.sessionId);
@@ -548,7 +558,8 @@ async function sendAnthropicRequestAttempt(options, deps = {}) {
548
558
  };
549
559
  const keep = deps.cacheKeep ?? cacheKeepManager;
550
560
  const realSession = options.streamOptions?.sessionId;
551
- if (!options.prime && realSession) {
561
+ const forkHead = piForkHeadSession(options.streamOptions);
562
+ if (!options.prime && !forkHead && realSession) {
552
563
  if (options.apiAccount || !options.storagePath) {
553
564
  try {
554
565
  realTurn?.finish();
@@ -589,26 +600,41 @@ async function sendAnthropicRequestAttempt(options, deps = {}) {
589
600
  // activity below follows the final serialized body, since hooks can edit TTLs.
590
601
  const oneHourCache = isCache1hPersistentlyEnabled(storage) ||
591
602
  options.streamOptions?.cacheRetention === 'long';
592
- const { body, bodyText, toolNames, cacheTtlMs } = options.prime
603
+ const forkBase = forkHead
604
+ ? piForkEffortSnapshots.match(forkHead, options.context)
605
+ : undefined;
606
+ const { body, bodyText, toolNames, cacheTtlMs, ...built } = options.prime
593
607
  ? buildPiPrimeBody(identity)
594
608
  : await buildAnthropicRequest(options.model.id, options.context, options.streamOptions, {
595
609
  enabled: oneHourCache,
596
610
  mode: getCache1hPersistentMode(storage),
597
611
  }, isFastModePersistentlyEnabled(storage), identity, {
598
612
  deferSigning: true,
613
+ forkBaseMessageCount: forkBase?.messageCount,
614
+ // API-key routes send no effort history, so no fork hint either.
615
+ forkEffort: options.apiAccount
616
+ ? undefined
617
+ : piForkEffortHint(options.streamOptions),
599
618
  effortTransitions: options.apiAccount
600
619
  ? []
601
- : options.effortTransitions,
620
+ : forkBase
621
+ ? forkBase.transitions
622
+ : options.effortTransitions,
602
623
  turnEndNote: storage.turnEndNote,
603
624
  thinkingPrefixMismatchBehavior: options.apiAccount
604
625
  ? 'account-default'
605
626
  : getThinkingPrefixMismatchBehavior(storage),
606
627
  ...(options.streamOptions?.onPayload && {
607
- onPayload: (payload) => options.streamOptions?.onPayload?.(payload, options.model),
628
+ onPayload: (payload) => forkHead
629
+ ? raceWithSignal(options.streamOptions?.signal, async () => options.streamOptions?.onPayload?.(payload, options.model))
630
+ : options.streamOptions?.onPayload?.(payload, options.model),
608
631
  }),
609
632
  });
633
+ if (!options.prime && !forkHead && realSession && !options.apiAccount)
634
+ piForkEffortSnapshots.record(realSession, options.context, options.effortTransitions);
610
635
  let wireBodyText = bodyText;
611
636
  options.onResolvedToolNames?.(toolNames);
637
+ options.onForkEffortApplied?.('forkEffortApplied' in built ? built.forkEffortApplied : undefined);
612
638
  const fastMode = body.speed === 'fast';
613
639
  const headers = options.apiAccount
614
640
  ? new Headers()
@@ -630,9 +656,13 @@ async function sendAnthropicRequestAttempt(options, deps = {}) {
630
656
  : undefined);
631
657
  };
632
658
  const billingInput = (attempt, apiSubject) => {
633
- // The session runner matches billing reports to session transcripts, and
634
- // Prime is account-wide with no session, so it sends no billing report.
635
- if (options.prime || !relayAffinity || (!attempt && !apiSubject))
659
+ // Prime (the five-hour window starter) has no session transcript, and
660
+ // Agent Runner bills a fork's answer itself from the answer's usage, so
661
+ // neither request may emit a session billing report here.
662
+ if (options.prime ||
663
+ forkHead ||
664
+ !relayAffinity ||
665
+ (!attempt && !apiSubject))
636
666
  return undefined;
637
667
  const credentialId = attempt
638
668
  ? piBillingPayer(attempt).credentialId
@@ -691,6 +721,10 @@ async function sendAnthropicRequestAttempt(options, deps = {}) {
691
721
  cacheAccepted.add(attempt);
692
722
  const at = Date.now();
693
723
  const appliedTtl = requestCacheLifetimeMs(sentBody);
724
+ if (forkHead) {
725
+ sessionCacheActivity.record(forkHead, routeId, appliedTtl);
726
+ return;
727
+ }
694
728
  const localTtl = readSessionCachePolicy(relayAffinity, true)?.ttl !== undefined
695
729
  ? appliedTtl
696
730
  : cacheTtlMs || PROMPT_CACHE_DEFAULT_TTL_MS;
@@ -730,6 +764,7 @@ async function sendAnthropicRequestAttempt(options, deps = {}) {
730
764
  };
731
765
  const reported = new Set();
732
766
  let retried401 = false;
767
+ let forkCredential;
733
768
  let lastTransport;
734
769
  const used = new Set();
735
770
  const report = async (attempt, status, source) => {
@@ -753,6 +788,21 @@ async function sendAnthropicRequestAttempt(options, deps = {}) {
753
788
  nextAttempt = undefined;
754
789
  if (attempt.accountIdentity !== verifiedUuid)
755
790
  throw new Error('Pi native OAuth route identity changed');
791
+ if (forkHead &&
792
+ options.routingChoice &&
793
+ !routingChoiceMatches(options.routingChoice, {
794
+ accountIdentity: attempt.accountIdentity,
795
+ credentialId: attempt.source === 'vault' ? attempt.receipt.credentialId : 'local',
796
+ }))
797
+ throw new PiForkRefusal('account');
798
+ if (forkHead) {
799
+ const credential = attempt.source === 'vault'
800
+ ? attempt.receipt.credentialId
801
+ : localMessageThreadCredential(attempt.admission.binding);
802
+ if (forkCredential && forkCredential !== credential)
803
+ throw new PiForkRefusal('account');
804
+ forkCredential = credential;
805
+ }
756
806
  return attempt;
757
807
  };
758
808
  let relayConfig = options.apiAccount
@@ -767,6 +817,7 @@ async function sendAnthropicRequestAttempt(options, deps = {}) {
767
817
  let threadRequest;
768
818
  if (!options.apiAccount &&
769
819
  !options.prime &&
820
+ !forkHead &&
770
821
  // Gateways may refuse the thread route: send full requests.
771
822
  !gateway &&
772
823
  isPiPrimaryThreadRequest(options.storagePath, options.streamOptions, options.requestOrigin) &&
@@ -872,12 +923,23 @@ async function sendAnthropicRequestAttempt(options, deps = {}) {
872
923
  if (attempt && response.status === 401) {
873
924
  // Report the rejected credential version before retrying, even if its replacement later succeeds.
874
925
  await report(attempt, response.status, 'direct');
875
- const rotated = !retried401 && !init.signal?.aborted
926
+ const rotated = !retried401 &&
927
+ !init.signal?.aborted &&
928
+ (!forkHead || attempt.source === 'vault')
876
929
  ? await native
877
930
  .retry(routeId, attempt, init.signal ?? undefined, options.model.id, options.routingChoice)
878
931
  .catch(() => undefined)
879
932
  : undefined;
880
933
  if (rotated) {
934
+ if (forkHead &&
935
+ options.routingChoice &&
936
+ !routingChoiceMatches(options.routingChoice, {
937
+ accountIdentity: rotated.accountIdentity,
938
+ credentialId: rotated.source === 'vault'
939
+ ? rotated.receipt.credentialId
940
+ : 'local',
941
+ }))
942
+ throw new PiForkRefusal('account');
881
943
  retried401 = true;
882
944
  await dumpDirectRequest({
883
945
  affinity: relayAffinity,
@@ -1016,6 +1078,7 @@ async function sendAnthropicRequestAttempt(options, deps = {}) {
1016
1078
  if (relay401Attempt &&
1017
1079
  response.status === 401 &&
1018
1080
  !retried401 &&
1081
+ (!forkHead || relay401Attempt.source === 'vault') &&
1019
1082
  !init.signal?.aborted) {
1020
1083
  const rotated = await native
1021
1084
  .retry(routeId, relay401Attempt, init.signal ?? undefined, options.model.id, options.routingChoice)
@@ -1451,6 +1514,76 @@ async function executeWithFallback(options) {
1451
1514
  const routingMode = getRoutingMode(storage);
1452
1515
  const routingRelay = routingState.relay;
1453
1516
  const routingSessionId = options.streamOptions?.sessionId;
1517
+ if (piForkHeadSession(options.streamOptions) && routingSessionId) {
1518
+ const signal = options.streamOptions?.signal;
1519
+ // The account comes only from the shared routing answer for the fork's
1520
+ // session, which names the head's account (whose cache the fork reads).
1521
+ // Bypass local session-account assignments so neither the head nor the
1522
+ // fork moves.
1523
+ const advice = await raceWithSignal(signal, () => (routingState.advice ??= routingRelay.accountFor(routingSessionId, options.model.id, routingCandidates(snapshot.accounts))));
1524
+ signal?.throwIfAborted();
1525
+ if (!advice)
1526
+ throw new PiForkRefusal('routing');
1527
+ const account = snapshot.accounts.find((candidate) => routingChoiceMatches(advice, candidate));
1528
+ if (!account || !nativeReady(account.id) || advice.hold)
1529
+ throw new PiForkRefusal('account');
1530
+ try {
1531
+ const inspected = await raceWithSignal(signal, async () => firstStreamingError(await sendAnthropicRequest({
1532
+ ...options,
1533
+ oauthAccountId: account.id,
1534
+ expectedAccountIdentity: account.accountIdentity,
1535
+ routingChoice: advice,
1536
+ })));
1537
+ signal?.throwIfAborted();
1538
+ const response = inspected.preflight instanceof Response
1539
+ ? inspected.preflight
1540
+ : inspected.response;
1541
+ if (inspected.preflight instanceof Response && response.ok)
1542
+ return response;
1543
+ if (response.status === 429) {
1544
+ let quota = quotaExhaustionFromHeaders(response.headers, options.model.id);
1545
+ if (Object.keys(quota).length === 0) {
1546
+ try {
1547
+ quota = await raceWithSignal(signal, () => account.id === STICKY_ROUTING_MAIN_ACCOUNT_ID
1548
+ ? quotaManager.refreshMain(mainAccountId, '')
1549
+ : quotaManager.refreshFallback(account.id, '', storage.accounts.find((candidate) => candidate.id === account.id &&
1550
+ isOAuthAccount(candidate))));
1551
+ }
1552
+ catch {
1553
+ quota = undefined;
1554
+ }
1555
+ }
1556
+ signal?.throwIfAborted();
1557
+ const decision = decideStickyQuotaFailure({
1558
+ quota,
1559
+ modelId: options.model.id,
1560
+ responseHeaders: response.headers,
1561
+ unconfirmedRetry: {
1562
+ counter: stickyQuotaRetries,
1563
+ sessionId: JSON.stringify([options.storagePath, routingSessionId]),
1564
+ turnId: String(options.context.messages.findLast((message) => message.role === 'user')?.timestamp ?? routingSessionId),
1565
+ accountId: account.id,
1566
+ },
1567
+ });
1568
+ if (decision.action === 'retain') {
1569
+ return hostRetryResponse(new Response(response.body, {
1570
+ status: 429,
1571
+ headers: stickyRetainRetryHeaders(response.headers),
1572
+ }));
1573
+ }
1574
+ void response.body?.cancel().catch(() => { });
1575
+ throw new PiForkRefusal('limit');
1576
+ }
1577
+ void response.body?.cancel().catch(() => { });
1578
+ throw new PiForkRefusal('failed');
1579
+ }
1580
+ catch (error) {
1581
+ signal?.throwIfAborted();
1582
+ if (error instanceof PiForkRefusal)
1583
+ throw error;
1584
+ throw new PiForkRefusal('failed');
1585
+ }
1586
+ }
1454
1587
  if (routingSessionId && !routingState.advice) {
1455
1588
  routingState.advice = (async () => {
1456
1589
  const router = await getPiStickyRouter(options.storagePath);
@@ -1814,7 +1947,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1814
1947
  const stream = createAssistantMessageEventStream();
1815
1948
  let turn;
1816
1949
  try {
1817
- if (options?.sessionId)
1950
+ if (options?.sessionId && !piForkHeadSession(options))
1818
1951
  turn = piCacheKeep.requestTurn(options.sessionId);
1819
1952
  }
1820
1953
  catch { }
@@ -1843,6 +1976,14 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1843
1976
  onResolvedToolNames: (names) => {
1844
1977
  toolNames = names;
1845
1978
  },
1979
+ // The last request built is the one sent; report only what it carried.
1980
+ onForkEffortApplied: (effort) => {
1981
+ const reply = output;
1982
+ if (effort)
1983
+ reply.cortexkitFork = { effortApplied: effort };
1984
+ else
1985
+ delete reply.cortexkitFork;
1986
+ },
1846
1987
  };
1847
1988
  const routingState = { relay: createRoutingRelay() };
1848
1989
  Object.assign(request, { routingState });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.14.0",
3
+ "version": "2.15.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.14.0"
39
+ "@cortexkit/anthropic-auth-core": "2.15.0"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",