@linxiraos/pi-agent-core 1.5.13 → 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 +51 -47
  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
@@ -29,14 +29,20 @@ import * as AIError from "@linxiraos/pi-ai/error";
29
29
  import { createOpenAICodexCompactionRequestContext } from "@linxiraos/pi-ai/providers/openai-codex-compaction";
30
30
  import type { OpenAICodexCompactionBody } from "@linxiraos/pi-ai/providers/openai-codex-responses";
31
31
  import type { InputItem as CodexInputItem } from "@linxiraos/pi-ai/providers/openai-codex/request-transformer";
32
- import { buildResponsesInput, resolveOpenAICompatPolicy } from "@linxiraos/pi-ai/providers/openai-shared";
32
+ import {
33
+ buildResponsesInput,
34
+ calculateOpenAIUsageAccounting,
35
+ resolveOpenAICompatPolicy,
36
+ } from "@linxiraos/pi-ai/providers/openai-shared";
33
37
  import { isSurvivingAssistant } from "@linxiraos/pi-ai/providers/transform-messages";
34
38
  import { stripOpenAIResponsesOutputOnlyStatusesForReplay } from "@linxiraos/pi-ai/utils";
35
39
  import { resolveCatalogPolicy } from "@linxiraos/pi-catalog/compat/catalog-policy";
40
+ import { calculateCost } from "@linxiraos/pi-catalog/models";
36
41
  import { preferredDialect } from "@linxiraos/pi-catalog/identity";
37
42
  import { clampThinkingLevelForModel } from "@linxiraos/pi-catalog/model-thinking";
38
43
  import { isRecord, logger, prompt, withLoopPhase } from "@linxiraos/pi-utils";
39
44
  import * as snapcompact from "@linxiraos/zeta-compact";
45
+ import { countContextOverrun } from "../output-budget";
40
46
  import { type AgentTelemetry, instrumentedCompleteSimple } from "../telemetry";
41
47
  import { ThinkingLevel } from "../thinking";
42
48
  import { Tokenizer } from "../tokenizer";
@@ -53,6 +59,8 @@ import {
53
59
  buildCompactionV2Request,
54
60
  buildCompactionV2RequestFromBody,
55
61
  getCompactionV2PreserveData,
62
+ type ResponsesCompactionUsage,
63
+ remoteCompactionPolicyModel,
56
64
  requestCompactionV2Streaming,
57
65
  shouldUseCompactionV2Streaming,
58
66
  storeCompactionV2PreserveData,
@@ -468,8 +476,9 @@ function findValidCutPoints(entries: SessionEntry[], startIndex: number, endInde
468
476
  case "custom_message":
469
477
  case "label":
470
478
  }
471
- // branch_summary and custom_message are user-role messages, valid cut points
472
- if (entry.type === "branch_summary" || entry.type === "custom_message") {
479
+ // branch_summary and custom_message are user-role messages, valid cut points; a row kept out of
480
+ // context is not one, so keeping it must not move the cut past the reply before it.
481
+ if (entry.type === "branch_summary" || (entry.type === "custom_message" && !entry.excludeFromContext)) {
473
482
  cutPoints.push(i);
474
483
  }
475
484
  }
@@ -483,7 +492,7 @@ function findValidCutPoints(entries: SessionEntry[], startIndex: number, endInde
483
492
  * transcript's orphan-head trim all share this boundary definition.
484
493
  */
485
494
  export function isTurnStartEntry(entry: SessionEntry): boolean {
486
- if (entry.type === "branch_summary" || entry.type === "custom_message") {
495
+ if (entry.type === "branch_summary" || (entry.type === "custom_message" && !entry.excludeFromContext)) {
487
496
  return true;
488
497
  }
489
498
  if (entry.type === "message") {
@@ -726,7 +735,7 @@ export interface SummaryOptions {
726
735
  /**
727
736
  * Optional telemetry handle. When provided, every LLM call emitted during
728
737
  * compaction is wrapped in an OTEL chat span tagged with
729
- * `zeta.gen_ai.oneshot.kind` (`compaction_summary`, `compaction_short_summary`,
738
+ * `omp.gen_ai.oneshot.kind` (`compaction_summary`, `compaction_short_summary`,
730
739
  * or `compaction_turn_prefix`). `undefined` keeps the call paths zero-cost.
731
740
  */
732
741
  telemetry?: AgentTelemetry;
@@ -760,6 +769,11 @@ export interface SummaryOptions {
760
769
  codexCompaction?: CodexCompactionContext;
761
770
  /** Provider-visible tools for remote compaction transports that replay native tool history. */
762
771
  tools?: Tool[];
772
+ /**
773
+ * Leave other models' reasoning out of the native compaction request, as the
774
+ * live turns stopped replaying it after a `reasoning_extraction` refusal.
775
+ */
776
+ omitDemotedReasoning?: boolean;
763
777
  /** Optional fetch implementation threaded into remote compaction calls. */
764
778
  fetch?: FetchImpl;
765
779
  /** Inspect or replace a generic remote-compaction payload before it is sent. */
@@ -777,6 +791,13 @@ export interface SummaryOptions {
777
791
  ctx: Context,
778
792
  options: SimpleStreamOptions,
779
793
  ) => Promise<AssistantMessage>;
794
+ /**
795
+ * Receives each OpenAI remote compaction request (V1 `/responses/compact`,
796
+ * V2 streaming) whose response reported usage. Those transports bypass
797
+ * {@link completeImpl}, so this is the only record of their spend: a
798
+ * content-less assistant message carrying the priced usage and duration.
799
+ */
800
+ onRemoteUsage?: (message: AssistantMessage) => void;
780
801
  /**
781
802
  * Transient-failure retry for the summarization oneshots (`generateSummary`,
782
803
  * `generateShortSummary`, `generateTurnPrefixSummary`).
@@ -793,6 +814,42 @@ export interface SummaryOptions {
793
814
  oneshotRetry?: OneshotRetryOptions | false;
794
815
  }
795
816
 
817
+ /**
818
+ * The record {@link SummaryOptions.onRemoteUsage} receives for one OpenAI
819
+ * remote compaction request, priced at `model`'s catalog rates (a
820
+ * `remoteCompaction.model` override is recorded by id; it has no rates here).
821
+ */
822
+ function remoteCompactionUsageMessage(
823
+ model: Model,
824
+ usage: ResponsesCompactionUsage,
825
+ startedAt: number,
826
+ ): AssistantMessage {
827
+ const target = remoteCompactionPolicyModel(model);
828
+ const tokens = calculateOpenAIUsageAccounting({
829
+ promptTokens: usage.inputTokens,
830
+ outputTokens: usage.outputTokens,
831
+ cachedTokens: usage.cachedInputTokens ?? 0,
832
+ reasoningTokens: usage.reasoningOutputTokens ?? 0,
833
+ cacheWriteOpenRouter: usage.cacheWriteTokens,
834
+ cacheWriteDeepSeek: undefined,
835
+ hasDeepSeekCacheHitAndMiss: false,
836
+ });
837
+ const billed: Usage = { ...tokens, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
838
+ billed.cost = calculateCost(model, billed);
839
+ const now = Date.now();
840
+ return {
841
+ role: "assistant",
842
+ content: [],
843
+ api: target.api,
844
+ provider: model.provider,
845
+ model: target.id,
846
+ usage: billed,
847
+ stopReason: "stop",
848
+ timestamp: now,
849
+ duration: now - startedAt,
850
+ };
851
+ }
852
+
796
853
  /**
797
854
  * Resolve the oneshot retry policy for a summarization call. Enabled by default
798
855
  * so a lone transient blip cannot abort compaction; `false` opts out for callers
@@ -1108,7 +1165,7 @@ export interface HandoffOptions {
1108
1165
  metadata?: Record<string, unknown>;
1109
1166
  /**
1110
1167
  * Optional telemetry handle. When provided, the handoff LLM call is
1111
- * wrapped in an OTEL chat span tagged with `zeta.gen_ai.oneshot.kind = "handoff"`.
1168
+ * wrapped in an OTEL chat span tagged with `omp.gen_ai.oneshot.kind = "handoff"`.
1112
1169
  */
1113
1170
  telemetry?: AgentTelemetry;
1114
1171
  /**
@@ -1168,6 +1225,13 @@ export async function generateHandoffFromContext(
1168
1225
  model: Model,
1169
1226
  options: HandoffFromContextOptions,
1170
1227
  ): Promise<string> {
1228
+ const overrun = countContextOverrun(context, model, new Tokenizer(model));
1229
+ if (overrun !== undefined) {
1230
+ throw new Error(
1231
+ `Handoff input does not fit ${model.provider}/${model.id}: at least ${overrun} prompt tokens ` +
1232
+ `leave no room for output in its ${model.contextWindow}-token window`,
1233
+ );
1234
+ }
1171
1235
  const requestOptions = {
1172
1236
  ...options.streamOptions,
1173
1237
  reasoning: resolveCompactionEffort(model, options.thinkingLevel),
@@ -1817,9 +1881,11 @@ export async function compact(
1817
1881
  codexAccessPrograms: options?.codexAccessPrograms,
1818
1882
  codexCompaction: options?.codexCompaction,
1819
1883
  tools: options?.tools,
1884
+ omitDemotedReasoning: options?.omitDemotedReasoning,
1820
1885
  fetch: options?.fetch,
1821
1886
  onPayload: options?.onPayload,
1822
1887
  completeImpl: options?.completeImpl,
1888
+ onRemoteUsage: options?.onRemoteUsage,
1823
1889
  // The caller's opt-out must reach every summarization oneshot, otherwise
1824
1890
  // an outer retry loop multiplies with the inner one (see SummaryOptions).
1825
1891
  oneshotRetry: options?.oneshotRetry,
@@ -1893,6 +1959,11 @@ export async function compact(
1893
1959
  * rewrite the tail's trailing tool outputs: the prefix keeps them intact.
1894
1960
  */
1895
1961
  const canCompactBeforeTail = lastSummarizedEntryId !== undefined && recentMessages.length > 0;
1962
+ const reportRemoteUsage = (usage: ResponsesCompactionUsage | undefined, startedAt: number): void => {
1963
+ if (usage && summaryOptions.onRemoteUsage) {
1964
+ summaryOptions.onRemoteUsage(remoteCompactionUsageMessage(model, usage, startedAt));
1965
+ }
1966
+ };
1896
1967
  const sendRemoteCompaction = async (
1897
1968
  sendWhole: () => Promise<void>,
1898
1969
  sendPrefix: () => Promise<boolean>,
@@ -2052,6 +2123,7 @@ export async function compact(
2052
2123
  tools,
2053
2124
  reasoning: buildCompactionV2Reasoning(model, summaryOptions.thinkingLevel),
2054
2125
  });
2126
+ const startedAt = Date.now();
2055
2127
  const remote = await withAuth(
2056
2128
  apiKey,
2057
2129
  key =>
@@ -2064,6 +2136,7 @@ export async function compact(
2064
2136
  }),
2065
2137
  { signal },
2066
2138
  );
2139
+ reportRemoteUsage(remote.usage, startedAt);
2067
2140
  preserveData = { ...preserveData, ...storeCompactionV2PreserveData(remote, model) };
2068
2141
  };
2069
2142
  const whole = await buildV2Input(true);
@@ -2112,7 +2185,8 @@ export async function compact(
2112
2185
  const convertToLlm = summaryOptions.convertToLlm ?? defaultConvertToLlm;
2113
2186
  const supportsOriginalDetail = openAiCompatSupportsImageDetailOriginal(model);
2114
2187
  const sendV1 = async (remoteHistory: Array<Record<string, unknown>>, rewriteOutputs: boolean): Promise<void> => {
2115
- const remote = await withAuth(
2188
+ const startedAt = Date.now();
2189
+ const { usage, ...remote } = await withAuth(
2116
2190
  apiKey,
2117
2191
  key =>
2118
2192
  requestOpenAiRemoteCompaction(
@@ -2132,6 +2206,7 @@ export async function compact(
2132
2206
  ),
2133
2207
  { signal },
2134
2208
  );
2209
+ reportRemoteUsage(usage, startedAt);
2135
2210
  preserveData = withOpenAiRemoteCompactionPreserveData(preserveData, remote);
2136
2211
  };
2137
2212
  const whole = buildOpenAiNativeHistory(
@@ -2299,6 +2374,7 @@ export async function compact(
2299
2374
  sessionId: summaryOptions.sessionId,
2300
2375
  promptCacheKey: summaryOptions.promptCacheKey,
2301
2376
  providerSessionState: summaryOptions.providerSessionState,
2377
+ omitDemotedReasoning: summaryOptions.omitDemotedReasoning,
2302
2378
  completeImpl: summaryOptions.completeImpl,
2303
2379
  telemetry: summaryOptions.telemetry,
2304
2380
  retry: summaryOneshotRetry(summaryOptions),
@@ -78,6 +78,8 @@ export interface CustomMessageEntry<T = unknown> extends SessionEntryBase {
78
78
  display: boolean;
79
79
  /** Who initiated this message for billing/attribution semantics. */
80
80
  attribution?: MessageAttribution;
81
+ /** Rendered and saved, never sent to the model (like `!!` bash rows). */
82
+ excludeFromContext?: boolean;
81
83
  }
82
84
 
83
85
  export interface CustomEntry<T = unknown> extends SessionEntryBase {
@@ -25,6 +25,8 @@ export interface CustomMessage<T = unknown> {
25
25
  details?: T;
26
26
  /** Who initiated this message for billing/attribution semantics. */
27
27
  attribution?: MessageAttribution;
28
+ /** Rendered and saved, never sent to the model (like `!!` bash rows). */
29
+ excludeFromContext?: boolean;
28
30
  timestamp: number;
29
31
  }
30
32
 
@@ -180,6 +182,7 @@ export function createCustomMessage(
180
182
  details: unknown | undefined,
181
183
  timestamp: string,
182
184
  attribution?: MessageAttribution,
185
+ excludeFromContext?: boolean,
183
186
  ): CustomMessage {
184
187
  return {
185
188
  role: "custom",
@@ -188,6 +191,7 @@ export function createCustomMessage(
188
191
  display,
189
192
  details,
190
193
  attribution,
194
+ ...(excludeFromContext ? { excludeFromContext: true } : {}),
191
195
  timestamp: new Date(timestamp).getTime(),
192
196
  };
193
197
  }
@@ -216,6 +220,7 @@ export function convertMessageToLlm(message: AgentMessage): Message | undefined
216
220
  switch (message.role) {
217
221
  case "custom":
218
222
  case "hookMessage": {
223
+ if (message.role === "custom" && message.excludeFromContext) return undefined;
219
224
  const content =
220
225
  typeof message.content === "string"
221
226
  ? [{ type: "text" as const, text: message.content }]
@@ -295,13 +300,14 @@ export function defaultConvertToLlm(messages: AgentMessage[]): Message[] {
295
300
 
296
301
  /**
297
302
  * The context message a session entry contributes, or `undefined` for entries
298
- * that don't reach the LLM (compaction markers, labels, model changes, ...).
303
+ * that don't reach the LLM (compaction markers, labels, model changes, rows
304
+ * kept out of context, ...).
299
305
  */
300
306
  export function getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {
301
307
  if (entry.type === "message") {
302
308
  return entry.message;
303
309
  }
304
- if (entry.type === "custom_message") {
310
+ if (entry.type === "custom_message" && !entry.excludeFromContext) {
305
311
  return createCustomMessage(
306
312
  entry.customType,
307
313
  entry.content,
@@ -18,7 +18,11 @@
18
18
  import { attach, create, Flag, ProviderHttpError } from "@linxiraos/pi-ai/error";
19
19
  import { getCodexAttestationHeader } from "@linxiraos/pi-ai/providers/openai-codex-attestation";
20
20
  import { createOpenAICodexCompactionRequestContext } from "@linxiraos/pi-ai/providers/openai-codex-compaction";
21
- import { applyCodexResponsesLiteShape } from "@linxiraos/pi-ai/providers/openai-codex/request-transformer";
21
+ import {
22
+ applyCodexResponsesLiteShape,
23
+ moveCodexInstructionsToInput,
24
+ withCodexRoutingFieldsFirst,
25
+ } from "@linxiraos/pi-ai/providers/openai-codex/request-transformer";
22
26
  import {
23
27
  applyInferenceHeaders,
24
28
  applySessionHeader,
@@ -51,6 +55,7 @@ import {
51
55
  truncateResponseItemId,
52
56
  } from "@linxiraos/pi-ai/utils";
53
57
  import { captureOpenAIHttpError } from "@linxiraos/pi-ai/utils/openai-http";
58
+ import { withResolvedHeaders } from "@linxiraos/pi-ai/utils/model-headers";
54
59
  import { isBedrockOpenAIUrl } from "@linxiraos/pi-catalog/hosts";
55
60
  import {
56
61
  applyCodexResidencyHeader,
@@ -60,21 +65,17 @@ import {
60
65
  OPENAI_HEADER_VALUES,
61
66
  OPENAI_HEADERS,
62
67
  } from "@linxiraos/pi-catalog/wire/codex";
63
- import {
64
- $env,
65
- isRecord,
66
- logger,
67
- prompt,
68
- ptree,
69
- stringifyJson,
70
- structuredCloneJSON,
71
- untilAborted,
72
- } from "@linxiraos/pi-utils";
68
+ import { $env, isRecord, logger, prompt, ptree, stringifyJson, structuredCloneJSON } from "@linxiraos/pi-utils";
73
69
  import { dataUrlImageSize } from "../image-tokens";
74
70
  import { Tokenizer } from "../tokenizer";
75
71
  import { appendAzureApiVersion, resolveAzureOpenAiBaseUrl } from "./azure-openai-endpoint";
76
72
  import { prepareBedrockCompactionRequest } from "./bedrock";
77
- import { isOpenAiRemoteCompactionApi, remoteCompactionPolicyModel } from "./compaction-v2-streaming";
73
+ import {
74
+ isOpenAiRemoteCompactionApi,
75
+ parseResponsesCompactionUsage,
76
+ type ResponsesCompactionUsage,
77
+ remoteCompactionPolicyModel,
78
+ } from "./compaction-v2-streaming";
78
79
  import contextWindowTruncatedOutputPrompt from "./prompts/context-window-truncated-output.md" with { type: "text" };
79
80
 
80
81
  export * from "./compaction-v2-streaming";
@@ -382,7 +383,10 @@ export interface OpenAiRemoteCompactionRequest {
382
383
  include?: string[];
383
384
  }
384
385
 
385
- export interface OpenAiRemoteCompactionResponse extends OpenAiRemoteCompactionPreserveData {}
386
+ /** A `/responses/compact` result: the history to preserve, plus the usage the body reported. */
387
+ export interface OpenAiRemoteCompactionResponse extends OpenAiRemoteCompactionPreserveData {
388
+ usage?: ResponsesCompactionUsage;
389
+ }
386
390
 
387
391
  export interface RemoteCompactionRequest {
388
392
  systemPrompt: string;
@@ -889,6 +893,7 @@ export async function requestOpenAiRemoteCompaction(
889
893
  rewriteOutputs?: boolean;
890
894
  },
891
895
  ): Promise<OpenAiRemoteCompactionResponse> {
896
+ model = await withResolvedHeaders(model, signal);
892
897
  let fetchImpl: FetchImpl = opts?.fetch ?? fetch;
893
898
  if (isBedrockOpenAIUrl(model.baseUrl)) {
894
899
  ({ model, apiKey, fetch: fetchImpl } = await prepareBedrockCompactionRequest(model, apiKey, opts?.fetch, signal));
@@ -953,6 +958,7 @@ export async function requestOpenAiRemoteCompaction(
953
958
  providerType: model.providerType,
954
959
  protocol: "openai",
955
960
  sessionId: opts?.sessionId,
961
+ compat: model.compat,
956
962
  cacheAffinity: resolveOpenCodeGoCacheAffinity(
957
963
  remoteCompactionPolicyModel(model),
958
964
  opts?.promptCacheKey ? promptCacheSessionId : undefined,
@@ -991,9 +997,10 @@ export async function requestOpenAiRemoteCompaction(
991
997
  includeInstallationHeader: true,
992
998
  }).headers,
993
999
  );
994
- // Responses Lite models take the same rewrite on `/responses/compact`:
995
- // instructions ride as an input item and the lite marker header is set
996
- // (codex-rs routes compaction through `build_responses_request`).
1000
+ // codex-rs routes `/responses/compact` through `build_responses_request`:
1001
+ // instructions always ride as a leading input item, and Responses Lite
1002
+ // models additionally take the Lite rewrite and marker header.
1003
+ moveCodexInstructionsToInput(request);
997
1004
  if (model.useResponsesLite) {
998
1005
  applyCodexResponsesLiteShape(request);
999
1006
  headers[OPENAI_HEADERS.RESPONSES_LITE] = "true";
@@ -1008,7 +1015,7 @@ export async function requestOpenAiRemoteCompaction(
1008
1015
  const response = await fetchImpl(endpoint, {
1009
1016
  method: "POST",
1010
1017
  headers,
1011
- body: stringifyJson(request),
1018
+ body: stringifyJson(isCodexResponses ? withCodexRoutingFieldsFirst(request) : request),
1012
1019
  signal: ptree.combineSignals(signal, opts?.timeoutMs ?? REMOTE_COMPACTION_TIMEOUT_MS),
1013
1020
  });
1014
1021
 
@@ -1030,7 +1037,7 @@ export async function requestOpenAiRemoteCompaction(
1030
1037
  );
1031
1038
  }
1032
1039
 
1033
- const data = (await response.json()) as { output?: unknown[] } | undefined;
1040
+ const data = (await response.json()) as { output?: unknown[]; usage?: unknown } | undefined;
1034
1041
  const rawOutput = data?.output ?? [];
1035
1042
  const replacementHistory = rawOutput.filter(
1036
1043
  (item): item is Record<string, unknown> =>
@@ -1055,7 +1062,8 @@ export async function requestOpenAiRemoteCompaction(
1055
1062
  });
1056
1063
  throw new Error("Remote compaction response missing compaction item");
1057
1064
  }
1058
- return { provider: model.provider, replacementHistory, compactionItem };
1065
+ const usage = parseResponsesCompactionUsage(data?.usage);
1066
+ return { provider: model.provider, replacementHistory, compactionItem, ...(usage ? { usage } : {}) };
1059
1067
  }
1060
1068
 
1061
1069
  /**
@@ -1098,11 +1106,7 @@ export async function requestRemoteCompaction(
1098
1106
  if (isChatCompletions) {
1099
1107
  if (opts?.apiKey) headers.set("Authorization", `Bearer ${opts.apiKey}`);
1100
1108
  const model = opts?.model;
1101
- const resolveHeaders = model?.resolveHeaders;
1102
- const configuredHeaders = resolveHeaders
1103
- ? await untilAborted(signal, () => resolveHeaders(signal))
1104
- : model?.headers;
1105
- signal?.throwIfAborted();
1109
+ const configuredHeaders = model ? (await withResolvedHeaders(model, signal)).headers : undefined;
1106
1110
  // `set` replaces case-insensitively, so a configured `authorization` overrides the default bearer.
1107
1111
  if (configuredHeaders) {
1108
1112
  for (const name in configuredHeaders) headers.set(name, configuredHeaders[name]!);
@@ -7,24 +7,30 @@ You MUST use EXACT format:
7
7
  [What is the user trying to accomplish in this branch?]
8
8
 
9
9
  ## Constraints & Preferences
10
+
10
11
  - [Constraints, preferences, requirements mentioned]
11
12
  - [(none) if none mentioned]
12
13
 
13
14
  ## Progress
14
15
 
15
16
  ### Done
17
+
16
18
  - [x] [Completed tasks/changes]
17
19
 
18
20
  ### In Progress
21
+
19
22
  - [ ] [Work started but not finished]
20
23
 
21
24
  ### Blocked
25
+
22
26
  - [Issues preventing progress]
23
27
 
24
28
  ## Key Decisions
29
+
25
30
  - **[Decision]**: [Brief rationale]
26
31
 
27
32
  ## Next Steps
33
+
28
34
  1. [What should happen next to continue]
29
35
 
30
36
  Sections MUST be kept concise. You MUST preserve exact file paths, function names, error messages.
@@ -5,32 +5,41 @@ IMPORTANT: If the conversation ends with an unanswered question or a request awa
5
5
  You MUST use this format (sections can be omitted if not applicable):
6
6
 
7
7
  ## Goal
8
+
8
9
  [User goals; list multiple if session covers different tasks.]
9
10
 
10
11
  ## Constraints & Preferences
12
+
11
13
  - [Constraints or requirements mentioned]
12
14
 
13
15
  ## Progress
14
16
 
15
17
  ### Done
18
+
16
19
  - [x] [Completed tasks/changes]
17
20
 
18
21
  ### In Progress
22
+
19
23
  - [ ] [Current work]
20
24
 
21
25
  ### Blocked
26
+
22
27
  - [Issues preventing progress]
23
28
 
24
29
  ## Key Decisions
30
+
25
31
  - **[Decision]**: [Brief rationale]
26
32
 
27
33
  ## Next Steps
34
+
28
35
  1. [Ordered list of next actions]
29
36
 
30
37
  ## Critical Context
38
+
31
39
  - [Important data, pending questions, references]
32
40
 
33
41
  ## Additional Notes
42
+
34
43
  [Anything else important not covered above]
35
44
 
36
45
  You MUST output only the structured summary; you NEVER include extra text.
@@ -7,9 +7,11 @@ MUST summarize prefix for retained suffix:
7
7
  [What did the user ask for in this turn?]
8
8
 
9
9
  ## Early Progress
10
+
10
11
  - [Key decisions and work done in the prefix]
11
12
 
12
13
  ## Context for Suffix
14
+
13
15
  - [Information needed to understand the retained recent work]
14
16
 
15
17
  MUST output only the structured summary; NEVER extra text.
@@ -1,6 +1,7 @@
1
1
  Update existing handoff summary in <previous-summary> tags from new messages above for another LLM to resume.
2
2
 
3
3
  MUST:
4
+
4
5
  - preserve all previous-summary information; add new progress, decisions, context.
5
6
  - Progress: move completed "In Progress" items to "Done".
6
7
  - update "Next Steps" for completed work.
@@ -15,30 +16,39 @@ MUST:
15
16
  Format (omit inapplicable sections):
16
17
 
17
18
  ## Goal
19
+
18
20
  [Preserve existing goals; add new ones if task expanded]
19
21
 
20
22
  ## Constraints & Preferences
23
+
21
24
  - [Preserve existing; add new ones discovered]
22
25
 
23
26
  ## Progress
24
27
 
25
28
  ### Done
29
+
26
30
  - [x] [Include previously done and newly completed items]
27
31
 
28
32
  ### In Progress
33
+
29
34
  - [ ] [Current work—update based on progress]
30
35
 
31
36
  ### Blocked
37
+
32
38
  - [Current blockers—remove if resolved]
33
39
 
34
40
  ## Key Decisions
41
+
35
42
  - **[Decision]**: [Brief rationale] (preserve all previous, add new)
36
43
 
37
44
  ## Next Steps
45
+
38
46
  1. [Update based on current state]
39
47
 
40
48
  ## Critical Context
49
+
41
50
  - [Preserve important context; add new if needed]
42
51
 
43
52
  ## Additional Notes
53
+
44
54
  [Other important info not fitting above]
@@ -18,29 +18,38 @@ The handoff mechanism is invisible to the document: NEVER list writing, generati
18
18
  Use exactly this structure:
19
19
 
20
20
  ## Goal
21
+
21
22
  [What the user is trying to accomplish]
22
23
 
23
24
  ## Constraints & Preferences
25
+
24
26
  - [Any constraints, preferences, or requirements mentioned]
25
27
 
26
28
  ## Progress
29
+
27
30
  ### Done
31
+
28
32
  - [x] [Completed tasks with specifics]
29
33
 
30
34
  ### In Progress
35
+
31
36
  - [ ] [Current work if any]
32
37
 
33
38
  ### Pending
39
+
34
40
  - [ ] [Tasks mentioned but not started]
35
41
 
36
42
  ## Key Decisions
43
+
37
44
  - **[Decision]**: [Rationale]
38
45
 
39
46
  ## Critical Context
47
+
40
48
  - Code snippets, file paths, function/type names, error messages, data essential to continue
41
49
  - Repository state if relevant
42
50
 
43
51
  ## Next Steps
52
+
44
53
  1. [What should happen next]
45
54
  </output>
46
55
 
@@ -1,8 +1,9 @@
1
1
  Context replaced. The <handoff> below is a handoff document a prior instance of you wrote from the full conversation. It is your own working memory, not user input.
2
+
2
3
  - First person inside it refers to you (the prior instance).
3
4
  - "Next Steps" is your own resumed plan; re-check it against the latest user message before acting.
4
5
  - The handoff already exists and is complete: NEVER write another handoff document unless the user explicitly asks.
5
- MUST build on prior work; NEVER duplicate prior work.
6
+ MUST build on prior work; NEVER duplicate prior work.
6
7
 
7
8
  <handoff>
8
9
  {{summary}}
@@ -1,4 +1,5 @@
1
1
  import type { ToolResultMessage } from "@linxiraos/pi-ai";
2
+ import { parseSpillUrl } from "@linxiraos/pi-utils";
2
3
  import type { AgentMessage, AgentToolCall } from "../types";
3
4
  import type { SessionEntry } from "./entries";
4
5
 
@@ -53,14 +54,17 @@ export function isSkillReadToolResult(context: ProtectedToolContext): boolean {
53
54
  return getReadToolPath(context)?.startsWith(SKILL_INTERNAL_URL_PREFIX) ?? false;
54
55
  }
55
56
 
56
- const ARTIFACT_INTERNAL_URL_PREFIX = "artifact://";
57
+ /** Whether `path` reads a session spill (`local://N.log`, with or without a selector). */
58
+ function isSpillPath(path: string | undefined): boolean {
59
+ return path !== undefined && parseSpillUrl(path) !== undefined;
60
+ }
57
61
 
58
- /** Recovery reads of session artifacts — eliding one only mints another artifact and can repeat indefinitely. */
62
+ /** Recovery reads of session spills — eliding one only mints another spill and can repeat indefinitely. */
59
63
  export function isArtifactRecoveryToolResult(context: ProtectedToolContext): boolean {
60
- if (getReadToolPath(context)?.startsWith(ARTIFACT_INTERNAL_URL_PREFIX)) return true;
64
+ if (isSpillPath(getReadToolPath(context))) return true;
61
65
  const meta = (context.toolResult.details as { meta?: { source?: { type?: string; value?: string } } } | undefined)
62
66
  ?.meta;
63
- return meta?.source?.type === "internal" && (meta.source.value?.startsWith(ARTIFACT_INTERNAL_URL_PREFIX) ?? false);
67
+ return meta?.source?.type === "internal" && isSpillPath(meta.source.value);
64
68
  }
65
69
 
66
70
  export function isProtectedToolResult(
@@ -109,7 +109,7 @@ export function extractFileOpsFromMessage(message: AgentMessage, fileOps: snapco
109
109
  const path = typeof args.path === "string" ? args.path : undefined;
110
110
  if (!path) continue;
111
111
 
112
- // Internal URIs (conflict://, artifact://, local://, history://, …) and
112
+ // Internal URIs (conflict://, local://, history://, …) and
113
113
  // web URLs are not re-groundable files — keep them out of `<files>`.
114
114
  if (snapcompact.isUrlSchemePath(path)) continue;
115
115
 
@@ -144,12 +144,41 @@ function countPromptTokens(context: Context, tokenizer: Tokenizer): number {
144
144
  }
145
145
 
146
146
  function countContextTokens(context: Context, tokenizer: Tokenizer): number {
147
+ return countFramingTokens(context, tokenizer) + tokenizer.countMessages(context.messages);
148
+ }
149
+
150
+ /** System prompt and tool schemas: the request prefix outside `messages`. */
151
+ function countFramingTokens(context: Context, tokenizer: Tokenizer): number {
147
152
  const { systemPrompt, tools, inactiveTools } = context;
148
153
  return (
149
154
  countFraming(systemPrompt, tokenizer, () => [...(systemPrompt ?? [])]) +
150
155
  countFraming(tools, tokenizer, () => toolFragments(tools ?? [])) +
151
156
  // Anthropic replays retired tool definitions, so they are prompt too.
152
- countFraming(inactiveTools, tokenizer, () => toolFragments(inactiveTools ?? [])) +
153
- tokenizer.countMessages(context.messages)
157
+ countFraming(inactiveTools, tokenizer, () => toolFragments(inactiveTools ?? []))
154
158
  );
155
159
  }
160
+
161
+ /**
162
+ * Local prompt count of `context` when it leaves `model` no room for the
163
+ * smallest output the transport requests, else `undefined` (also when the
164
+ * window is unknown). Counting stops at the first message past the window, so
165
+ * the count is a floor.
166
+ *
167
+ * Unlike {@link fitOutputTokensToContextWindow}, no usage anchor is trusted:
168
+ * history re-expanded behind a native compaction the model cannot replay
169
+ * carries reports describing the compacted prefix. Nor is a tokenizer margin
170
+ * added: a caller refuses on this verdict, so only a clear overrun counts, and
171
+ * a near-full request is still left to the provider.
172
+ */
173
+ export function countContextOverrun(context: Context, model: Model, tokenizer: Tokenizer): number | undefined {
174
+ const contextWindow = model.contextWindow;
175
+ if (!contextWindow || contextWindow <= 0) return undefined;
176
+ const budget = contextWindow - OUTPUT_FIT_HEADWAY_TOKENS - MIN_FITTED_OUTPUT_TOKENS;
177
+ let tokens = countFramingTokens(context, tokenizer);
178
+ for (const message of context.messages) {
179
+ if (tokens > budget) break;
180
+ // Encrypted reasoning bytes overstate what the provider bills; a floor leaves them out.
181
+ tokens += tokenizer.countMessage(message, { excludeEncryptedReasoning: true });
182
+ }
183
+ return tokens > budget ? tokens : undefined;
184
+ }