@linxiraos/pi-agent-core 1.5.14 → 1.5.15

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.
Files changed (46) hide show
  1. package/CHANGELOG.md +47 -49
  2. package/README.md +7 -9
  3. package/THIRD-PARTY-NOTICES.txt +1 -1
  4. package/dist/types/agent-loop.d.ts +22 -0
  5. package/dist/types/agent.d.ts +21 -10
  6. package/dist/types/compaction/anthropic.d.ts +5 -6
  7. package/dist/types/compaction/bedrock.d.ts +3 -2
  8. package/dist/types/compaction/compaction-v2-streaming.d.ts +7 -3
  9. package/dist/types/compaction/compaction.d.ts +14 -2
  10. package/dist/types/compaction/entries.d.ts +2 -0
  11. package/dist/types/compaction/messages.d.ts +5 -2
  12. package/dist/types/compaction/openai.d.ts +3 -0
  13. package/dist/types/compaction/tool-protection.d.ts +1 -1
  14. package/dist/types/output-budget.d.ts +13 -0
  15. package/dist/types/replay-policy.d.ts +15 -1
  16. package/dist/types/sent-tool-definitions.d.ts +6 -3
  17. package/dist/types/telemetry.d.ts +2 -2
  18. package/dist/types/tool-arguments.d.ts +2 -1
  19. package/dist/types/types.d.ts +55 -26
  20. package/package.json +43 -43
  21. package/src/agent-loop.ts +120 -47
  22. package/src/agent.ts +103 -55
  23. package/src/compaction/anthropic.ts +26 -8
  24. package/src/compaction/bedrock.ts +6 -13
  25. package/src/compaction/branch-summarization.ts +2 -0
  26. package/src/compaction/compaction-v2-streaming.ts +22 -12
  27. package/src/compaction/compaction.ts +83 -7
  28. package/src/compaction/entries.ts +2 -0
  29. package/src/compaction/messages.ts +8 -2
  30. package/src/compaction/openai.ts +28 -24
  31. package/src/compaction/prompts/branch-summary.md +6 -0
  32. package/src/compaction/prompts/compaction-summary.md +9 -0
  33. package/src/compaction/prompts/compaction-turn-prefix.md +2 -0
  34. package/src/compaction/prompts/compaction-update-summary.md +10 -0
  35. package/src/compaction/prompts/handoff-document.md +9 -0
  36. package/src/compaction/prompts/handoff-summary-context.md +2 -1
  37. package/src/compaction/tool-protection.ts +8 -4
  38. package/src/compaction/utils.ts +1 -1
  39. package/src/output-budget.ts +31 -2
  40. package/src/replay-policy.ts +38 -3
  41. package/src/sent-tool-definitions.ts +20 -10
  42. package/src/speculative-execution.ts +29 -5
  43. package/src/telemetry.ts +31 -23
  44. package/src/tokenizer.ts +8 -1
  45. package/src/tool-arguments.ts +2 -1
  46. package/src/types.ts +54 -22
package/src/agent.ts CHANGED
@@ -23,15 +23,19 @@ import {
23
23
  type ToolResultMessage,
24
24
  } from "@linxiraos/pi-ai";
25
25
  import type { Dialect } from "@linxiraos/pi-ai/dialect";
26
+ import * as AIError from "@linxiraos/pi-ai/error";
26
27
  import { openAIResponsesReplaysNativeHistory } from "@linxiraos/pi-ai/providers/openai-responses-state";
27
28
  import type { HarmonyAuditEvent } from "@linxiraos/pi-ai/utils/harmony-leak";
28
29
  import { getBundledModel } from "@linxiraos/pi-catalog/models";
29
30
  import { logger } from "@linxiraos/pi-utils";
30
31
  import {
32
+ AgentLoopError,
31
33
  abortReasonText,
32
34
  agentLoop,
33
35
  agentLoopContinue,
34
36
  createSyntheticToolResultMessage,
37
+ lastContextMessage,
38
+ type NormalizeToolsOptions,
35
39
  normalizeMessagesForProvider,
36
40
  normalizeTools,
37
41
  resolveOwnedDialectFromEnv,
@@ -40,7 +44,7 @@ import {
40
44
  } from "./agent-loop";
41
45
  import type { AppendOnlyContextManager } from "./append-only-context";
42
46
  import { agentPauseGate } from "./pause";
43
- import { isProviderRefusalMessage } from "./replay-policy";
47
+ import { filterProviderReplayMessages } from "./replay-policy";
44
48
  import { SentToolDefinitions } from "./sent-tool-definitions";
45
49
  import { identifyAgentMessage } from "./message-identity";
46
50
  import { Tokenizer } from "./tokenizer";
@@ -76,10 +80,12 @@ import { isSoftToolRequirement } from "./types";
76
80
  * Default convertToLlm: Keep only LLM-compatible replay messages.
77
81
  */
78
82
  function defaultConvertToLlm(messages: AgentMessage[]): Message[] {
79
- return messages.filter((m): m is Message => {
80
- if (m.role === "assistant") return !isProviderRefusalMessage(m);
81
- return m.role === "user" || m.role === "developer" || m.role === "toolResult";
82
- });
83
+ return filterProviderReplayMessages(
84
+ messages.filter(
85
+ (m): m is Message =>
86
+ m.role === "assistant" || m.role === "user" || m.role === "developer" || m.role === "toolResult",
87
+ ),
88
+ );
83
89
  }
84
90
 
85
91
  function refreshToolChoiceForActiveTools(
@@ -118,7 +124,7 @@ export interface AgentOptions {
118
124
  * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
119
125
  * Default filters to user/assistant/toolResult and converts attachments.
120
126
  */
121
- convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
127
+ convertToLlm?: AgentLoopConfig["convertToLlm"];
122
128
 
123
129
  /**
124
130
  * Optional transform applied to context before convertToLlm.
@@ -130,7 +136,7 @@ export interface AgentOptions {
130
136
  * Optional transform applied after provider context assembly and before
131
137
  * telemetry capture/provider send.
132
138
  */
133
- transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
139
+ transformProviderContext?: (context: Context, model: Model, signal?: AbortSignal) => Context | Promise<Context>;
134
140
 
135
141
  /**
136
142
  * Steering mode: "all" = send all steering messages at once, "one-at-a-time" = one per turn
@@ -267,15 +273,15 @@ export interface AgentOptions {
267
273
 
268
274
  /**
269
275
  * Resolve a tool call whose name matched no advertised tool. Lets hosts
270
- * route calls to tools exposed through side transports (e.g. `xd://`
271
- * device mounts) instead of failing with "Tool not found".
276
+ * route calls to tools reached through a side transport (e.g. mounted
277
+ * tool commands run through `bash`) instead of failing with "Tool not found".
272
278
  */
273
279
  resolveFallbackTool?: (name: string, advertised: readonly AgentTool<any>[]) => AgentTool<any> | undefined;
274
280
 
275
281
  /**
276
282
  * Names routable by {@link resolveFallbackTool} that the advertised set
277
- * omits (e.g. `xd://` device mounts), used only to suggest a target when a
278
- * call misses.
283
+ * omits (e.g. mounted tool commands run through `bash`), used only to
284
+ * suggest a target when a call misses.
279
285
  */
280
286
  suggestFallbackToolNames?: () => Iterable<string>;
281
287
 
@@ -309,9 +315,10 @@ export interface AgentOptions {
309
315
  onToolChoiceUnavailable?: () => void;
310
316
 
311
317
  /**
312
- * Cursor exec handlers for local tool execution.
318
+ * Cursor exec handlers for local tool execution, or a factory resolved on the first
319
+ * request dispatched to Cursor (including a mid-session model switch).
313
320
  */
314
- cursorExecHandlers?: CursorExecHandlers;
321
+ cursorExecHandlers?: CursorExecHandlers | (() => Promise<CursorExecHandlers>);
315
322
  /** Additional tools Cursor executes through its MCP request-context bridge, resolved before each provider call. */
316
323
  getCursorTools?: () => AgentTool[];
317
324
 
@@ -427,10 +434,13 @@ export class Agent {
427
434
  #streamingAssistantIdentity: object | undefined;
428
435
  #pauseListeners = new Set<(paused: boolean) => void>();
429
436
  #abortController?: AbortController;
430
- #convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
437
+ /** The running loop's `detachSignal` source; see {@link Agent.abort}. */
438
+ #detachController?: AbortController;
439
+ #convertToLlm: AgentLoopConfig["convertToLlm"];
431
440
  #transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
432
- #transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
441
+ #transformProviderContext?: (context: Context, model: Model, signal?: AbortSignal) => Context | Promise<Context>;
433
442
  #sentToolDefinitions = new SentToolDefinitions();
443
+ #standbyTools: AgentTool[] = [];
434
444
  #steeringQueue: AgentMessage[] = [];
435
445
  #followUpQueue: AgentMessage[] = [];
436
446
  #queuedMessageClaims: Partial<Record<QueuedMessageQueue, QueuedMessageClaim>> = {};
@@ -479,6 +489,7 @@ export class Agent {
479
489
  #maxRetryDelayMs?: number;
480
490
  #getToolContext?: (toolCall?: ToolCallContext) => AgentToolContext | undefined;
481
491
  #cursorExecHandlers?: CursorExecHandlers;
492
+ #loadCursorExecHandlers?: () => Promise<CursorExecHandlers>;
482
493
  #getCursorTools?: () => AgentTool[];
483
494
  #cursorOnToolResult?: CursorToolResultHandler;
484
495
  #cwd?: string;
@@ -603,7 +614,12 @@ export class Agent {
603
614
  this.#onResponse = opts.onResponse;
604
615
  this.#onSseEvent = opts.onSseEvent;
605
616
  this.#getToolContext = opts.getToolContext;
606
- this.#cursorExecHandlers = opts.cursorExecHandlers;
617
+ if (typeof opts.cursorExecHandlers === "function") {
618
+ const load = opts.cursorExecHandlers;
619
+ this.#loadCursorExecHandlers = async () => (this.#cursorExecHandlers ??= await load());
620
+ } else {
621
+ this.#cursorExecHandlers = opts.cursorExecHandlers;
622
+ }
607
623
  this.#getCursorTools = opts.getCursorTools;
608
624
  this.#cursorOnToolResult = opts.cursorOnToolResult;
609
625
  this.#cwd = opts.cwd;
@@ -980,24 +996,25 @@ export class Agent {
980
996
  async buildSideRequestContext(
981
997
  llmMessages: Message[],
982
998
  systemPrompt: string[] = this.#state.systemPrompt,
999
+ signal?: AbortSignal,
983
1000
  ): Promise<Context> {
984
1001
  const model = this.#state.model;
985
1002
  if (!model) throw new Error("No active model on agent");
986
1003
  const ownedDialect = this.#ownedDialect(model);
987
1004
  const messages = normalizeMessagesForProvider(llmMessages, model);
988
- const tools = ownedDialect
989
- ? []
990
- : (normalizeTools(this.#toolsForModel(model), {
991
- injectIntent: this.#intentTracing,
992
- intentDescription: this.#intentDescription,
993
- pruneDescriptions: this.#pruneToolDescriptions,
994
- }) ?? []);
1005
+ const toolOptions: NormalizeToolsOptions = {
1006
+ injectIntent: this.#intentTracing,
1007
+ intentDescription: this.#intentDescription,
1008
+ pruneDescriptions: this.#pruneToolDescriptions,
1009
+ };
1010
+ const tools = ownedDialect ? [] : (normalizeTools(this.#toolsForModel(model), toolOptions) ?? []);
1011
+ const standby = ownedDialect ? undefined : normalizeTools(this.#standbyTools, toolOptions);
995
1012
  let context: Context = { systemPrompt, messages, tools };
996
1013
  // Side requests reuse the main loop's sent definitions without recording their own; attached before the
997
1014
  // transform too, so a request-size clamp in it measures them.
998
- context = this.#sentToolDefinitions.withInactiveTools(context);
999
- if (this.#transformProviderContext) context = await this.#transformProviderContext(context, model);
1000
- context = this.#sentToolDefinitions.withInactiveTools(context);
1015
+ context = this.#sentToolDefinitions.withInactiveTools(context, standby);
1016
+ if (this.#transformProviderContext) context = await this.#transformProviderContext(context, model, signal);
1017
+ context = this.#sentToolDefinitions.withInactiveTools(context, context.inactiveTools);
1001
1018
  return context;
1002
1019
  }
1003
1020
 
@@ -1366,6 +1383,11 @@ export class Agent {
1366
1383
  this.#state.tools = t;
1367
1384
  }
1368
1385
 
1386
+ /** Set the inactive tools that may become active later ({@link AgentContext.standbyTools}). */
1387
+ setStandbyTools(tools: AgentTool[]) {
1388
+ this.#standbyTools = tools;
1389
+ }
1390
+
1369
1391
  replaceMessages(ms: AgentMessage[]) {
1370
1392
  // New array assignment is intentional: caller-owned `ms` may be mutated
1371
1393
  // after handoff; snapshot it so external mutations cannot leak in.
@@ -1686,7 +1708,14 @@ export class Agent {
1686
1708
  this.#state.messages.length = 0;
1687
1709
  }
1688
1710
 
1689
- abort(reason?: unknown) {
1711
+ /**
1712
+ * Abort the current run. `detachTools` first raises the running tool batch's
1713
+ * cooperative `steeringSignal` (see {@link AgentLoopConfig.detachSignal}), so
1714
+ * tools that can move their work into a background job do so instead of being
1715
+ * killed; they observe it before the abort.
1716
+ */
1717
+ abort(reason?: unknown, options?: { detachTools?: boolean }) {
1718
+ if (options?.detachTools) this.#detachController?.abort();
1690
1719
  this.#abortController?.abort(reason);
1691
1720
  }
1692
1721
 
@@ -1825,37 +1854,27 @@ export class Agent {
1825
1854
  try {
1826
1855
  const dequeueSignal = this.#continuationDequeueSignal(signal) ?? continuationAbortController.signal;
1827
1856
  const messages = this.#state.messages;
1828
- if (messages.length === 0) {
1829
- // An empty transcript has nothing to resume, but a queued steer/follow-up
1830
- // must still be delivered as the opening turn — mirroring the assistant-tail
1831
- // branch below. Throwing here leaves the message undeliverable, and idle-drain
1832
- // callers (AgentSession#scheduleQueuedMessageDrain) re-arm continue() on every
1833
- // microtask because hasQueuedMessages() never clears, spinning an unbounded
1834
- // allocation loop until OOM (issue #6344).
1835
- const queuedSteering = await this.#dequeueSteeringMessagesAfterHooks(dequeueSignal);
1836
- if (this.#abortController !== continuationAbortController) return;
1837
- if (queuedSteering.length > 0) {
1838
- await this.#runLoop(queuedSteering, { skipInitialSteeringPoll: true }, signal, true);
1839
- return;
1840
- }
1841
- const queuedFollowUp = await this.#dequeueFollowUpMessagesAfterHooks(dequeueSignal);
1842
- if (this.#abortController !== continuationAbortController) return;
1843
- if (queuedFollowUp.length > 0) {
1844
- await this.#runLoop(queuedFollowUp, undefined, signal, true);
1845
- return;
1846
- }
1847
- throw new Error("No messages to continue from");
1848
- }
1849
- if (messages[messages.length - 1].role === "assistant") {
1857
+ const literalTail = messages.at(-1);
1858
+ // Rows kept out of context (`!!` runs, excluded extension rows) may trail the last message the
1859
+ // model sees. A queued steer/follow-up is delivered as if they were absent; with nothing queued,
1860
+ // continue from them as before and leave the tail to the caller's recovery.
1861
+ const tail = lastContextMessage(messages);
1862
+ if (!tail || tail.role === "assistant") {
1850
1863
  // A tail with unpaired runnable tool calls resumes by re-executing
1851
1864
  // them (see `unpairedToolCallTail` in agent-loop). This must win over
1852
1865
  // queued-message delivery: injecting a message between the tool_use
1853
1866
  // blocks and their results would break the provider's pairing
1854
1867
  // invariant. Queued messages drain inside the resumed loop instead.
1855
- if (unpairedToolCallTail(messages)) {
1868
+ if (tail && unpairedToolCallTail([tail])) {
1856
1869
  await this.#runLoop(undefined, undefined, signal, true);
1857
1870
  return;
1858
1871
  }
1872
+ // An empty transcript has nothing to resume, but a queued steer/follow-up
1873
+ // must still be delivered as the opening turn. Throwing here leaves the
1874
+ // message undeliverable, and idle-drain callers
1875
+ // (AgentSession#scheduleQueuedMessageDrain) re-arm continue() on every
1876
+ // microtask because hasQueuedMessages() never clears, spinning an unbounded
1877
+ // allocation loop until OOM (issue #6344).
1859
1878
  const queuedSteering = await this.#dequeueSteeringMessagesAfterHooks(dequeueSignal);
1860
1879
  if (this.#abortController !== continuationAbortController) return;
1861
1880
  if (queuedSteering.length > 0) {
@@ -1870,7 +1889,8 @@ export class Agent {
1870
1889
  return;
1871
1890
  }
1872
1891
 
1873
- throw new Error("Cannot continue from message role: assistant");
1892
+ if (!literalTail) throw new Error("No messages to continue from");
1893
+ if (literalTail === tail) throw new Error("Cannot continue from message role: assistant");
1874
1894
  }
1875
1895
 
1876
1896
  await this.#runLoop(undefined, undefined, signal, true);
@@ -1922,6 +1942,8 @@ export class Agent {
1922
1942
  const loopSignal = continuationSignal
1923
1943
  ? AbortSignal.any([loopAbortController.signal, continuationSignal])
1924
1944
  : loopAbortController.signal;
1945
+ const detachController = new AbortController();
1946
+ this.#detachController = detachController;
1925
1947
  this.#state.isStreaming = true;
1926
1948
  this.#state.streamMessage = null;
1927
1949
  this.#state.error = undefined;
@@ -1936,6 +1958,7 @@ export class Agent {
1936
1958
  systemPrompt: this.#state.systemPrompt,
1937
1959
  messages: this.#state.messages.slice(),
1938
1960
  tools: this.#state.tools,
1961
+ standbyTools: this.#standbyTools,
1939
1962
  };
1940
1963
 
1941
1964
  // Installed unconditionally. Both `cursorExecHandlers` and
@@ -2026,6 +2049,7 @@ export class Agent {
2026
2049
  return refreshToolChoiceForActiveTools(options?.toolChoice, this.#state.tools);
2027
2050
  };
2028
2051
 
2052
+ let requestModel: Model | undefined;
2029
2053
  const config: AgentLoopConfig = {
2030
2054
  model,
2031
2055
  reasoning,
@@ -2039,6 +2063,7 @@ export class Agent {
2039
2063
  serviceTier: this.#serviceTier,
2040
2064
  hideThinkingSummary: this.#hideThinkingSummary,
2041
2065
  interruptMode: this.#interruptMode,
2066
+ detachSignal: detachController.signal,
2042
2067
  sessionId: this.#sessionId,
2043
2068
  deadline: this.#deadline,
2044
2069
  promptCacheKey: this.#promptCacheKey,
@@ -2066,6 +2091,7 @@ export class Agent {
2066
2091
  context.systemPrompt = this.#state.systemPrompt;
2067
2092
  this.#onModelCallSystemPrompt?.(context.systemPrompt);
2068
2093
  context.tools = this.#toolsForModel(this.#state.model ?? model);
2094
+ context.standbyTools = this.#standbyTools;
2069
2095
  },
2070
2096
  beforeModelCall:
2071
2097
  this.#beforeModelCall || this.#additionalBeforeModelCalls.size > 0
@@ -2080,6 +2106,7 @@ export class Agent {
2080
2106
  }
2081
2107
  : undefined,
2082
2108
  cursorExecHandlers: this.#cursorExecHandlers,
2109
+ loadCursorExecHandlers: this.#loadCursorExecHandlers,
2083
2110
  cursorOnToolResult,
2084
2111
  cwd: this.#cwd,
2085
2112
  getCwd: this.#cwdResolver,
@@ -2103,6 +2130,9 @@ export class Agent {
2103
2130
  onAssistantMessageEvent: this.#onAssistantMessageEvent,
2104
2131
  onHarmonyLeak: this.#onHarmonyLeak,
2105
2132
  onTurnEnd: (messages, signal, context) => this.#onTurnEnd?.(messages, signal, context),
2133
+ onTurnEndEmitted: () => {
2134
+ requestModel = undefined;
2135
+ },
2106
2136
  onPauseChange: paused => {
2107
2137
  if (this.#isPaused === paused) return;
2108
2138
  this.#isPaused = paused;
@@ -2113,7 +2143,10 @@ export class Agent {
2113
2143
  onToolChoiceRejected: () => {
2114
2144
  if (claimedToolChoice !== undefined) this.#deferredToolChoice = claimedToolChoice;
2115
2145
  },
2116
- getModel: () => this.#state.model ?? model,
2146
+ getModel: () => {
2147
+ requestModel = this.#state.model ?? model;
2148
+ return requestModel;
2149
+ },
2117
2150
  getReasoning: () => this.#state.thinkingLevel,
2118
2151
  getDisableReasoning: () => this.#state.disableReasoning,
2119
2152
  getServiceTier: this.#serviceTierResolver,
@@ -2243,6 +2276,14 @@ export class Agent {
2243
2276
  : err instanceof Error
2244
2277
  ? err.message
2245
2278
  : String(err);
2279
+ const errorModel = requestModel ?? this.#state.model ?? model;
2280
+ const errorStatus = stoppedForAbort ? undefined : AIError.status(err);
2281
+ const errorId = stoppedForAbort
2282
+ ? errorMessage === "Request was aborted"
2283
+ ? AIError.create(AIError.Flag.Abort)
2284
+ : AIError.classify(loopSignal.reason) || undefined
2285
+ : AIError.classify(err, errorModel.api) || undefined;
2286
+ const errorFromAgentLoop = (!stoppedForAbort && err instanceof AgentLoopError) || undefined;
2246
2287
  const shouldEmitVisibleError = !stoppedForAbort;
2247
2288
  const assistantPartial = partial?.role === "assistant" ? partial : undefined;
2248
2289
  const hadAssistantStart = assistantPartial !== undefined;
@@ -2270,13 +2311,16 @@ export class Agent {
2270
2311
  ),
2271
2312
  stopReason: "error",
2272
2313
  errorMessage,
2314
+ errorStatus,
2315
+ errorId,
2316
+ errorFromAgentLoop,
2273
2317
  }
2274
2318
  : {
2275
2319
  role: "assistant",
2276
2320
  content: [{ type: "text", text: "" }],
2277
- api: model.api,
2278
- provider: model.provider,
2279
- model: model.id,
2321
+ api: errorModel.api,
2322
+ provider: errorModel.provider,
2323
+ model: errorModel.id,
2280
2324
  usage: {
2281
2325
  input: 0,
2282
2326
  output: 0,
@@ -2287,6 +2331,9 @@ export class Agent {
2287
2331
  },
2288
2332
  stopReason: stoppedForAbort ? "aborted" : "error",
2289
2333
  errorMessage,
2334
+ errorStatus,
2335
+ errorId,
2336
+ errorFromAgentLoop,
2290
2337
  timestamp: Date.now(),
2291
2338
  };
2292
2339
 
@@ -2362,6 +2409,7 @@ export class Agent {
2362
2409
  this.#isPaused = false;
2363
2410
  this.#restoreUndeliveredQueuedMessages(loopAbortController);
2364
2411
  resolveRun?.();
2412
+ if (this.#detachController === detachController) this.#detachController = undefined;
2365
2413
  if (this.#abortController === loopAbortController) {
2366
2414
  this.#state.isStreaming = false;
2367
2415
  this.#state.streamMessage = null;
@@ -17,8 +17,10 @@ import type {
17
17
  SimpleStreamOptions,
18
18
  Usage,
19
19
  } from "@linxiraos/pi-ai";
20
+ import { isBuiltinApi } from "@linxiraos/pi-ai/api-registry";
20
21
  import * as AIError from "@linxiraos/pi-ai/error";
21
22
  import {
23
+ declaresAnthropicCompactionEndpoint,
22
24
  supportsAnthropicCompaction,
23
25
  supportsBedrockConverseCompaction,
24
26
  } from "@linxiraos/pi-ai/providers/anthropic-compaction";
@@ -59,6 +61,22 @@ function isBedrockConverseModel(model: Model): model is Model<"bedrock-converse-
59
61
  return model.api === "bedrock-converse-stream";
60
62
  }
61
63
 
64
+ /**
65
+ * Whether a custom api (an extension's `registerProvider` stream, never a
66
+ * built-in adapter) declares that it dispatches its model to Anthropic
67
+ * Messages with an endpoint that serves on-demand compaction
68
+ * (`declaresAnthropicCompactionEndpoint`). The request goes through the
69
+ * model's own api like any turn, so the custom stream shapes and
70
+ * authenticates it, and the Anthropic provider it delegates to still applies
71
+ * its own model and endpoint policy. The stream receives the caller's
72
+ * `reasoning` as is: it resolves the effort earlier controls left in force
73
+ * (`resolveAnthropicCompactionEffort`) on the Anthropic model it delegates to,
74
+ * which the agent never sees.
75
+ */
76
+ function declaresAnthropicCompaction(model: Model): boolean {
77
+ return !isBuiltinApi(model.api) && declaresAnthropicCompactionEndpoint(model);
78
+ }
79
+
62
80
  /**
63
81
  * Whether a model compacts through the Anthropic compaction beta. Model
64
82
  * eligibility is catalog policy (`compat.supportsServerCompaction`, the
@@ -66,17 +84,15 @@ function isBedrockConverseModel(model: Model): model is Model<"bedrock-converse-
66
84
  * provider routes requests, so a Foundry or `ANTHROPIC_BASE_URL` reroute of a
67
85
  * first-party model is excluded unless the route opted in with
68
86
  * `remoteCompaction.enabled`. Bedrock Converse models compact through a
69
- * Bedrock Runtime side request; their ordinary turns stay on Converse.
87
+ * Bedrock Runtime side request; their ordinary turns stay on Converse. A
88
+ * custom api qualifies through {@link declaresAnthropicCompaction}.
70
89
  */
71
- export function shouldUseAnthropicNativeCompaction(
72
- model: Model,
73
- ): model is Model<"anthropic-messages" | "bedrock-converse-stream"> {
90
+ export function shouldUseAnthropicNativeCompaction(model: Model): boolean {
74
91
  if (isAnthropicMessagesModel(model)) return supportsAnthropicCompaction(model);
75
- return isBedrockConverseModel(model) && supportsBedrockConverseCompaction(model);
92
+ if (isBedrockConverseModel(model)) return supportsBedrockConverseCompaction(model);
93
+ return declaresAnthropicCompaction(model);
76
94
  }
77
95
 
78
- type AnthropicNativeCompactionModel = Model<"anthropic-messages" | "bedrock-converse-stream">;
79
-
80
96
  export function getPreservedAnthropicCompactionData(
81
97
  preserveData: Record<string, unknown> | undefined,
82
98
  ): AnthropicCompactionPreserveData | undefined {
@@ -231,6 +247,7 @@ export interface AnthropicNativeCompactionOptions
231
247
  | "promptCacheKey"
232
248
  | "providerSessionState"
233
249
  | "maxInFlightRequests"
250
+ | "omitDemotedReasoning"
234
251
  >,
235
252
  Pick<InstrumentedChatSpanOptions, "completeImpl" | "telemetry" | "retry"> {}
236
253
 
@@ -244,7 +261,7 @@ export interface AnthropicNativeCompactionOptions
244
261
  * output limits; the configured method order can then choose a fallback.
245
262
  */
246
263
  export async function requestAnthropicNativeCompaction(
247
- model: AnthropicNativeCompactionModel,
264
+ model: Model,
248
265
  apiKey: ApiKey,
249
266
  request: AnthropicNativeCompactionRequest,
250
267
  signal: AbortSignal | undefined,
@@ -273,6 +290,7 @@ export async function requestAnthropicNativeCompaction(
273
290
  promptCacheKey: options.promptCacheKey,
274
291
  providerSessionState: options.providerSessionState,
275
292
  maxInFlightRequests: options.maxInFlightRequests,
293
+ omitDemotedReasoning: options.omitDemotedReasoning,
276
294
  anthropicCompaction: { instructions: request.instructions, filesDueBefore: request.filesDueBefore },
277
295
  },
278
296
  {
@@ -1,7 +1,6 @@
1
1
  import { getProviderDefinition } from "@linxiraos/pi-ai/registry";
2
2
  import type { FetchImpl, Model } from "@linxiraos/pi-ai/types";
3
3
  import { transportFetch } from "@linxiraos/pi-ai/utils/transport-fetch";
4
- import { untilAborted } from "@linxiraos/pi-utils";
5
4
 
6
5
  export interface BedrockCompactionRequest {
7
6
  model: Model;
@@ -12,8 +11,9 @@ export interface BedrockCompactionRequest {
12
11
  /**
13
12
  * Shape a native compaction request for Amazon Bedrock's OpenAI routes
14
13
  * (`isBedrockOpenAIUrl`) the way stream dispatch shapes a normal Bedrock turn:
15
- * configured headers, transport fetch (proxy, CA, User-Agent, request
16
- * recording), then the provider's model and request hooks. The bundled
14
+ * transport fetch (proxy, CA, User-Agent, request recording), then the
15
+ * provider's model and request hooks, on a model whose configured headers
16
+ * the caller already resolved (`withResolvedHeaders`). The bundled
17
17
  * `bedrock-mantle` provider's hook fills in `{region}` and picks bearer or
18
18
  * SigV4 auth; without it compaction targets an unresolved host.
19
19
  *
@@ -26,16 +26,9 @@ export async function prepareBedrockCompactionRequest(
26
26
  fetch: FetchImpl | undefined,
27
27
  signal: AbortSignal | undefined,
28
28
  ): Promise<BedrockCompactionRequest> {
29
- let resolvedModel = model;
30
- const resolveHeaders = model.resolveHeaders;
31
- if (resolveHeaders) {
32
- const headers = await untilAborted(signal, () => resolveHeaders(signal));
33
- signal?.throwIfAborted();
34
- resolvedModel = { ...model, resolveHeaders: undefined, headers: headers ? { ...headers } : undefined };
35
- }
36
- const baseFetch = transportFetch(resolvedModel, fetch);
37
- const provider = getProviderDefinition(resolvedModel.provider);
38
- const providerModel = provider?.prepareModel?.(resolvedModel) ?? resolvedModel;
29
+ const baseFetch = transportFetch(model, fetch);
30
+ const provider = getProviderDefinition(model.provider);
31
+ const providerModel = provider?.prepareModel?.(model) ?? model;
39
32
  const prepared = provider?.prepareRequest?.(providerModel, { apiKey, fetch: baseFetch, signal }) ?? {
40
33
  model: providerModel,
41
34
  options: { apiKey, fetch: baseFetch },
@@ -175,6 +175,8 @@ function getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {
175
175
  return entry.message;
176
176
 
177
177
  case "custom_message":
178
+ // A row kept out of context is not conversation: it must not use the summary's budget.
179
+ if (entry.excludeFromContext) return undefined;
178
180
  return createCustomMessage(
179
181
  entry.customType,
180
182
  entry.content,
@@ -10,7 +10,11 @@
10
10
  import type { Api, CodexCompactionContext, FetchImpl, Model, ProviderSessionState } from "@linxiraos/pi-ai";
11
11
  import * as AIError from "@linxiraos/pi-ai/error";
12
12
  import { createOpenAICodexCompactionRequestContext } from "@linxiraos/pi-ai/providers/openai-codex-compaction";
13
- import { applyCodexResponsesLiteShape } from "@linxiraos/pi-ai/providers/openai-codex/request-transformer";
13
+ import {
14
+ applyCodexResponsesLiteShape,
15
+ moveCodexInstructionsToInput,
16
+ withCodexRoutingFieldsFirst,
17
+ } from "@linxiraos/pi-ai/providers/openai-codex/request-transformer";
14
18
  import type {
15
19
  OpenAICodexCompactionBody,
16
20
  OpenAICodexCompatibilityMetadata,
@@ -22,6 +26,7 @@ import {
22
26
  resolveOpenAIRequestSetup,
23
27
  } from "@linxiraos/pi-ai/providers/openai-shared";
24
28
  import { captureOpenAIHttpError } from "@linxiraos/pi-ai/utils/openai-http";
29
+ import { withResolvedHeaders } from "@linxiraos/pi-ai/utils/model-headers";
25
30
  import type { CatalogPolicyInputs } from "@linxiraos/pi-catalog/types";
26
31
  import { isBedrockOpenAIUrl } from "@linxiraos/pi-catalog/hosts";
27
32
  import {
@@ -63,12 +68,14 @@ const CONTEXTUAL_USER_PREFIXES = [
63
68
  "<model_switch>",
64
69
  ];
65
70
 
66
- /** Token usage reported by the streamed V2 Responses completion. */
67
- export interface CompactionV2Usage {
71
+ /** Token usage a Responses compaction request reported: the V1 `/responses/compact` body, or the V2 stream's completed response. */
72
+ export interface ResponsesCompactionUsage {
68
73
  inputTokens: number;
69
74
  outputTokens: number;
70
75
  totalTokens: number;
71
76
  cachedInputTokens?: number;
77
+ /** Input tokens the request wrote to the prompt cache; part of `inputTokens`. */
78
+ cacheWriteTokens?: number;
72
79
  reasoningOutputTokens?: number;
73
80
  }
74
81
 
@@ -88,7 +95,7 @@ export interface CompactionV2Response {
88
95
  compactionItem: Record<string, unknown>;
89
96
  replacementHistory: Array<Record<string, unknown>>;
90
97
  usedTokens: number;
91
- usage?: CompactionV2Usage;
98
+ usage?: ResponsesCompactionUsage;
92
99
  retainedImageCount: number;
93
100
  }
94
101
 
@@ -231,6 +238,8 @@ export function buildCompactionV2Request(
231
238
  };
232
239
  if (model.useResponsesLite) {
233
240
  applyCodexResponsesLiteShape(body);
241
+ } else {
242
+ moveCodexInstructionsToInput(body);
234
243
  }
235
244
  return buildCompactionV2RequestFromBody(model, body, options);
236
245
  }
@@ -277,6 +286,7 @@ export async function requestCompactionV2Streaming(
277
286
  codexAccessPrograms?: boolean;
278
287
  },
279
288
  ): Promise<CompactionV2Response> {
289
+ model = await withResolvedHeaders(model, signal);
280
290
  let fetchImpl: FetchImpl = options?.fetch ?? globalThis.fetch;
281
291
  if (isBedrockOpenAIUrl(model.baseUrl)) {
282
292
  ({
@@ -393,7 +403,7 @@ async function attemptCompactionV2Streaming(
393
403
  const response = await fetchImpl(endpoint, {
394
404
  method: "POST",
395
405
  headers: buildCompactionV2Headers(model, apiKey, request, options.codexMetadata),
396
- body: stringifyJson(body),
406
+ body: stringifyJson(withCodexRoutingFieldsFirst(body)),
397
407
  signal,
398
408
  });
399
409
 
@@ -468,7 +478,6 @@ function buildCompactionV2Headers(
468
478
  }
469
479
  applyCodexResidencyHeader(headers, apiKey);
470
480
  if (routingSessionId) {
471
- headers[OPENAI_HEADERS.CONVERSATION_ID] = routingSessionId;
472
481
  headers[OPENAI_HEADERS.SESSION_ID] = routingSessionId;
473
482
  headers["x-client-request-id"] = routingSessionId;
474
483
  }
@@ -488,7 +497,7 @@ interface CompactionV2CollectionState {
488
497
  outputItemCount: number;
489
498
  compactionItems: Array<Record<string, unknown>>;
490
499
  sawCompleted: boolean;
491
- usage: CompactionV2Usage | undefined;
500
+ usage: ResponsesCompactionUsage | undefined;
492
501
  }
493
502
 
494
503
  function createCompactionV2CollectionState(): CompactionV2CollectionState {
@@ -630,7 +639,7 @@ function handleCompactionV2Event(
630
639
 
631
640
  if (type === "response.completed" || type === "response.done") {
632
641
  state.sawCompleted = true;
633
- state.usage = parseCompactionV2Usage(event);
642
+ state.usage = parseResponsesCompactionUsage(isRecord(event.response) ? event.response.usage : undefined);
634
643
  return;
635
644
  }
636
645
 
@@ -647,10 +656,9 @@ function handleCompactionV2Event(
647
656
  }
648
657
  }
649
658
 
650
- function parseCompactionV2Usage(event: Record<string, unknown>): CompactionV2Usage | undefined {
651
- const response = isRecord(event.response) ? event.response : undefined;
652
- const usage = response && isRecord(response.usage) ? response.usage : undefined;
653
- if (!usage) return undefined;
659
+ /** A Responses `usage` object; undefined when it is missing or lacks the token totals. */
660
+ export function parseResponsesCompactionUsage(usage: unknown): ResponsesCompactionUsage | undefined {
661
+ if (!isRecord(usage)) return undefined;
654
662
 
655
663
  const inputTokens = numberField(usage, "input_tokens");
656
664
  const outputTokens = numberField(usage, "output_tokens");
@@ -660,12 +668,14 @@ function parseCompactionV2Usage(event: Record<string, unknown>): CompactionV2Usa
660
668
  const inputDetails = isRecord(usage.input_tokens_details) ? usage.input_tokens_details : undefined;
661
669
  const outputDetails = isRecord(usage.output_tokens_details) ? usage.output_tokens_details : undefined;
662
670
  const cachedInputTokens = inputDetails ? numberField(inputDetails, "cached_tokens") : undefined;
671
+ const cacheWriteTokens = inputDetails ? numberField(inputDetails, "cache_write_tokens") : undefined;
663
672
  const reasoningOutputTokens = outputDetails ? numberField(outputDetails, "reasoning_tokens") : undefined;
664
673
  return {
665
674
  inputTokens,
666
675
  outputTokens,
667
676
  totalTokens,
668
677
  ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
678
+ ...(cacheWriteTokens !== undefined ? { cacheWriteTokens } : {}),
669
679
  ...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),
670
680
  };
671
681
  }