@oh-my-pi/pi-agent-core 18.22.2 → 19.0.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/CHANGELOG.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [19.0.0] - 2026-11-18
6
+
7
+ ### Added
8
+
9
+ - Added support for excluding custom messages from model context and compaction or branch summaries, while allowing queued steering and follow-up messages to continue correctly after excluded messages.
10
+
5
11
  ## [18.22.1] - 2026-11-17
6
12
 
7
13
  ### Added
@@ -50,6 +50,15 @@ export declare function resolveOwnedDialectFromEnv(value: string | undefined): D
50
50
  * The prompt is added to the context and events are emitted for it.
51
51
  */
52
52
  export declare function agentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn): EventStream<AgentEvent, AgentMessage[]>;
53
+ /**
54
+ * Whether `message` is kept out of model context: drawn and saved, never sent (a `!!` bash run, a
55
+ * custom row sent with `excludeFromContext`).
56
+ */
57
+ export declare function isExcludedFromContext(message: AgentMessage): boolean;
58
+ /** Index of the last message the model sees, or -1; rows kept out of context after it do not change the request tail. */
59
+ export declare function lastContextIndex(messages: readonly AgentMessage[]): number;
60
+ /** The last message the model sees (see {@link lastContextIndex}). */
61
+ export declare function lastContextMessage(messages: readonly AgentMessage[]): AgentMessage | undefined;
53
62
  /**
54
63
  * Trailing assistant message whose runnable tool calls have no results yet.
55
64
  *
@@ -15,12 +15,14 @@ export declare const V2_RETAINED_MESSAGE_TOKEN_BUDGET = 64000;
15
15
  export declare const V2_COMPACTION_MAX_RETRIES = 2;
16
16
  /** Timeout for V2 streaming compaction (5 minutes, same as V1). */
17
17
  export declare const V2_COMPACTION_TIMEOUT_MS = 300000;
18
- /** Token usage reported by the streamed V2 Responses completion. */
19
- export interface CompactionV2Usage {
18
+ /** Token usage a Responses compaction request reported: the V1 `/responses/compact` body, or the V2 stream's completed response. */
19
+ export interface ResponsesCompactionUsage {
20
20
  inputTokens: number;
21
21
  outputTokens: number;
22
22
  totalTokens: number;
23
23
  cachedInputTokens?: number;
24
+ /** Input tokens the request wrote to the prompt cache; part of `inputTokens`. */
25
+ cacheWriteTokens?: number;
24
26
  reasoningOutputTokens?: number;
25
27
  }
26
28
  /** Provider-ready Responses body and local state needed for V2 compaction. */
@@ -38,7 +40,7 @@ export interface CompactionV2Response {
38
40
  compactionItem: Record<string, unknown>;
39
41
  replacementHistory: Array<Record<string, unknown>>;
40
42
  usedTokens: number;
41
- usage?: CompactionV2Usage;
43
+ usage?: ResponsesCompactionUsage;
42
44
  retainedImageCount: number;
43
45
  }
44
46
  /** Resolve the streaming Responses endpoint for a V2-capable model. */
@@ -87,6 +89,8 @@ export declare function requestCompactionV2Streaming(model: Model, apiKey: strin
87
89
  preferWebsockets?: boolean;
88
90
  codexAccessPrograms?: boolean;
89
91
  }): Promise<CompactionV2Response>;
92
+ /** A Responses `usage` object; undefined when it is missing or lacks the token totals. */
93
+ export declare function parseResponsesCompactionUsage(usage: unknown): ResponsesCompactionUsage | undefined;
90
94
  /** Build Codex-style V2 replacement history from retention candidates plus compaction output. */
91
95
  export declare function buildCompactionV2ReplacementHistory(input: unknown[], compactionItem: Record<string, unknown>, retainedMessageBudget?: number): {
92
96
  replacementHistory: Array<Record<string, unknown>>;
@@ -277,6 +277,13 @@ export interface SummaryOptions {
277
277
  * the live agent turn also bracket compaction HTTP requests.
278
278
  */
279
279
  completeImpl?: <TApi extends Api>(model: Model<TApi>, ctx: Context, options: SimpleStreamOptions) => Promise<AssistantMessage>;
280
+ /**
281
+ * Receives each OpenAI remote compaction request (V1 `/responses/compact`,
282
+ * V2 streaming) whose response reported usage. Those transports bypass
283
+ * {@link completeImpl}, so this is the only record of their spend: a
284
+ * content-less assistant message carrying the priced usage and duration.
285
+ */
286
+ onRemoteUsage?: (message: AssistantMessage) => void;
280
287
  /**
281
288
  * Transient-failure retry for the summarization oneshots (`generateSummary`,
282
289
  * `generateShortSummary`, `generateTurnPrefixSummary`).
@@ -63,6 +63,8 @@ export interface CustomMessageEntry<T = unknown> extends SessionEntryBase {
63
63
  display: boolean;
64
64
  /** Who initiated this message for billing/attribution semantics. */
65
65
  attribution?: MessageAttribution;
66
+ /** Rendered and saved, never sent to the model (like `!!` bash rows). */
67
+ excludeFromContext?: boolean;
66
68
  }
67
69
  export interface CustomEntry<T = unknown> extends SessionEntryBase {
68
70
  type: "custom";
@@ -9,6 +9,8 @@ export interface CustomMessage<T = unknown> {
9
9
  details?: T;
10
10
  /** Who initiated this message for billing/attribution semantics. */
11
11
  attribution?: MessageAttribution;
12
+ /** Rendered and saved, never sent to the model (like `!!` bash rows). */
13
+ excludeFromContext?: boolean;
12
14
  timestamp: number;
13
15
  }
14
16
  /** Legacy hook message type (pre-extensions). Kept for session migration. */
@@ -91,7 +93,7 @@ export interface CompactionSummaryMessageOptions {
91
93
  historyRewriteAt?: number;
92
94
  }
93
95
  export declare function createCompactionSummaryMessage(summary: string, tokensBefore: number, timestamp: string, options?: CompactionSummaryMessageOptions): CompactionSummaryMessage;
94
- export declare function createCustomMessage(customType: string, content: string | (TextContent | ImageContent)[], display: boolean, details: unknown | undefined, timestamp: string, attribution?: MessageAttribution): CustomMessage;
96
+ export declare function createCustomMessage(customType: string, content: string | (TextContent | ImageContent)[], display: boolean, details: unknown | undefined, timestamp: string, attribution?: MessageAttribution, excludeFromContext?: boolean): CustomMessage;
95
97
  /**
96
98
  * Transform a single core-domain agent message to its LLM form; `undefined`
97
99
  * drops it from the provider request.
@@ -113,6 +115,7 @@ export declare function convertMessageToLlm(message: AgentMessage): Message | un
113
115
  export declare function defaultConvertToLlm(messages: AgentMessage[]): Message[];
114
116
  /**
115
117
  * The context message a session entry contributes, or `undefined` for entries
116
- * that don't reach the LLM (compaction markers, labels, model changes, ...).
118
+ * that don't reach the LLM (compaction markers, labels, model changes, rows
119
+ * kept out of context, ...).
117
120
  */
118
121
  export declare function getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined;
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import type { CodexCompactionContext, FetchImpl, Message, Model, ProviderSessionState, SimpleStreamOptions } from "@oh-my-pi/pi-ai/types";
18
18
  import { Tokenizer } from "../tokenizer.js";
19
+ import { type ResponsesCompactionUsage } from "./compaction-v2-streaming.js";
19
20
  export * from "./compaction-v2-streaming.js";
20
21
  export declare const OPENAI_REMOTE_COMPACTION_PRESERVE_KEY = "openaiRemoteCompaction";
21
22
  /**
@@ -100,7 +101,9 @@ export interface OpenAiRemoteCompactionRequest {
100
101
  };
101
102
  include?: string[];
102
103
  }
104
+ /** A `/responses/compact` result: the history to preserve, plus the usage the body reported. */
103
105
  export interface OpenAiRemoteCompactionResponse extends OpenAiRemoteCompactionPreserveData {
106
+ usage?: ResponsesCompactionUsage;
104
107
  }
105
108
  export interface RemoteCompactionRequest {
106
109
  systemPrompt: string;
@@ -17,6 +17,6 @@ export declare function getToolResultMessage(entry: SessionEntry): ToolResultMes
17
17
  */
18
18
  export declare function getReadToolPath({ toolResult, toolCall }: ProtectedToolContext): string | undefined;
19
19
  export declare function isSkillReadToolResult(context: ProtectedToolContext): boolean;
20
- /** Recovery reads of session artifacts — eliding one only mints another artifact and can repeat indefinitely. */
20
+ /** Recovery reads of session spills — eliding one only mints another spill and can repeat indefinitely. */
21
21
  export declare function isArtifactRecoveryToolResult(context: ProtectedToolContext): boolean;
22
22
  export declare function isProtectedToolResult(toolResult: ToolResultMessage, toolCall: AgentToolCall | undefined, matchers: readonly ProtectedToolMatcher[]): boolean;
@@ -280,8 +280,9 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
280
280
  */
281
281
  hasIrcInterrupts?: () => boolean | Promise<boolean>;
282
282
  /**
283
- * Peeks whether a background completion (finished job, exited supervised
284
- * process) is queued for aside injection at the next boundary.
283
+ * Peeks whether a background notice (finished job, exited supervised
284
+ * process, output a running job was asked to report) is queued for aside
285
+ * injection at the next boundary.
285
286
  *
286
287
  * Same rules as {@link hasIrcInterrupts}: non-consuming, only cuts
287
288
  * *interruptible* waits short, in either interruptMode. Without
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@oh-my-pi/pi-agent-core",
4
- "version": "18.22.2",
4
+ "version": "19.0.0",
5
5
  "description": "General-purpose agent with transport abstraction, state management, and attachment support",
6
6
  "homepage": "https://omp.sh",
7
7
  "author": {
@@ -38,16 +38,16 @@
38
38
  "fmt": "oxfmt --no-error-on-unmatched-pattern 'src/**/*.{ts,tsx}' '{test,bench,examples,scripts}/**/*.ts' '*.ts'"
39
39
  },
40
40
  "dependencies": {
41
- "@oh-my-pi/pi-ai": "18.22.2",
42
- "@oh-my-pi/pi-catalog": "18.22.2",
43
- "@oh-my-pi/pi-natives": "18.22.2",
44
- "@oh-my-pi/pi-utils": "18.22.2",
45
- "@oh-my-pi/pi-wire": "18.22.2",
46
- "@oh-my-pi/snapcompact": "18.22.2",
41
+ "@oh-my-pi/pi-ai": "19.0.0",
42
+ "@oh-my-pi/pi-catalog": "19.0.0",
43
+ "@oh-my-pi/pi-natives": "19.0.0",
44
+ "@oh-my-pi/pi-utils": "19.0.0",
45
+ "@oh-my-pi/pi-wire": "19.0.0",
46
+ "@oh-my-pi/snapcompact": "19.0.0",
47
47
  "@opentelemetry/api": "^1.9.1"
48
48
  },
49
49
  "devDependencies": {
50
- "@oh-my-pi/omptype": "18.22.2",
50
+ "@oh-my-pi/omptype": "19.0.0",
51
51
  "@opentelemetry/context-async-hooks": "2.9.0",
52
52
  "@opentelemetry/sdk-trace-base": "2.9.0",
53
53
  "@types/bun": "^1.3.14"
package/src/agent-loop.ts CHANGED
@@ -683,6 +683,26 @@ export function agentLoop(
683
683
  return stream;
684
684
  }
685
685
 
686
+ /**
687
+ * Whether `message` is kept out of model context: drawn and saved, never sent (a `!!` bash run, a
688
+ * custom row sent with `excludeFromContext`).
689
+ */
690
+ export function isExcludedFromContext(message: AgentMessage): boolean {
691
+ return "excludeFromContext" in message && message.excludeFromContext === true;
692
+ }
693
+
694
+ /** Index of the last message the model sees, or -1; rows kept out of context after it do not change the request tail. */
695
+ export function lastContextIndex(messages: readonly AgentMessage[]): number {
696
+ let i = messages.length - 1;
697
+ while (i >= 0 && isExcludedFromContext(messages[i])) i--;
698
+ return i;
699
+ }
700
+
701
+ /** The last message the model sees (see {@link lastContextIndex}). */
702
+ export function lastContextMessage(messages: readonly AgentMessage[]): AgentMessage | undefined {
703
+ return messages[lastContextIndex(messages)];
704
+ }
705
+
686
706
  /**
687
707
  * Trailing assistant message whose runnable tool calls have no results yet.
688
708
  *
package/src/agent.ts CHANGED
@@ -32,6 +32,7 @@ import {
32
32
  agentLoop,
33
33
  agentLoopContinue,
34
34
  createSyntheticToolResultMessage,
35
+ lastContextMessage,
35
36
  normalizeMessagesForProvider,
36
37
  normalizeTools,
37
38
  resolveOwnedDialectFromEnv,
@@ -1825,37 +1826,27 @@ export class Agent {
1825
1826
  try {
1826
1827
  const dequeueSignal = this.#continuationDequeueSignal(signal) ?? continuationAbortController.signal;
1827
1828
  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") {
1829
+ const literalTail = messages.at(-1);
1830
+ // Rows kept out of context (`!!` runs, excluded extension rows) may trail the last message the
1831
+ // model sees. A queued steer/follow-up is delivered as if they were absent; with nothing queued,
1832
+ // continue from them as before and leave the tail to the caller's recovery.
1833
+ const tail = lastContextMessage(messages);
1834
+ if (!tail || tail.role === "assistant") {
1850
1835
  // A tail with unpaired runnable tool calls resumes by re-executing
1851
1836
  // them (see `unpairedToolCallTail` in agent-loop). This must win over
1852
1837
  // queued-message delivery: injecting a message between the tool_use
1853
1838
  // blocks and their results would break the provider's pairing
1854
1839
  // invariant. Queued messages drain inside the resumed loop instead.
1855
- if (unpairedToolCallTail(messages)) {
1840
+ if (tail && unpairedToolCallTail([tail])) {
1856
1841
  await this.#runLoop(undefined, undefined, signal, true);
1857
1842
  return;
1858
1843
  }
1844
+ // An empty transcript has nothing to resume, but a queued steer/follow-up
1845
+ // must still be delivered as the opening turn. Throwing here leaves the
1846
+ // message undeliverable, and idle-drain callers
1847
+ // (AgentSession#scheduleQueuedMessageDrain) re-arm continue() on every
1848
+ // microtask because hasQueuedMessages() never clears, spinning an unbounded
1849
+ // allocation loop until OOM (issue #6344).
1859
1850
  const queuedSteering = await this.#dequeueSteeringMessagesAfterHooks(dequeueSignal);
1860
1851
  if (this.#abortController !== continuationAbortController) return;
1861
1852
  if (queuedSteering.length > 0) {
@@ -1870,7 +1861,8 @@ export class Agent {
1870
1861
  return;
1871
1862
  }
1872
1863
 
1873
- throw new Error("Cannot continue from message role: assistant");
1864
+ if (!literalTail) throw new Error("No messages to continue from");
1865
+ if (literalTail === tail) throw new Error("Cannot continue from message role: assistant");
1874
1866
  }
1875
1867
 
1876
1868
  await this.#runLoop(undefined, undefined, signal, true);
@@ -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,
@@ -68,12 +68,14 @@ const CONTEXTUAL_USER_PREFIXES = [
68
68
  "<model_switch>",
69
69
  ];
70
70
 
71
- /** Token usage reported by the streamed V2 Responses completion. */
72
- 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 {
73
73
  inputTokens: number;
74
74
  outputTokens: number;
75
75
  totalTokens: number;
76
76
  cachedInputTokens?: number;
77
+ /** Input tokens the request wrote to the prompt cache; part of `inputTokens`. */
78
+ cacheWriteTokens?: number;
77
79
  reasoningOutputTokens?: number;
78
80
  }
79
81
 
@@ -93,7 +95,7 @@ export interface CompactionV2Response {
93
95
  compactionItem: Record<string, unknown>;
94
96
  replacementHistory: Array<Record<string, unknown>>;
95
97
  usedTokens: number;
96
- usage?: CompactionV2Usage;
98
+ usage?: ResponsesCompactionUsage;
97
99
  retainedImageCount: number;
98
100
  }
99
101
 
@@ -496,7 +498,7 @@ interface CompactionV2CollectionState {
496
498
  outputItemCount: number;
497
499
  compactionItems: Array<Record<string, unknown>>;
498
500
  sawCompleted: boolean;
499
- usage: CompactionV2Usage | undefined;
501
+ usage: ResponsesCompactionUsage | undefined;
500
502
  }
501
503
 
502
504
  function createCompactionV2CollectionState(): CompactionV2CollectionState {
@@ -638,7 +640,7 @@ function handleCompactionV2Event(
638
640
 
639
641
  if (type === "response.completed" || type === "response.done") {
640
642
  state.sawCompleted = true;
641
- state.usage = parseCompactionV2Usage(event);
643
+ state.usage = parseResponsesCompactionUsage(isRecord(event.response) ? event.response.usage : undefined);
642
644
  return;
643
645
  }
644
646
 
@@ -655,10 +657,9 @@ function handleCompactionV2Event(
655
657
  }
656
658
  }
657
659
 
658
- function parseCompactionV2Usage(event: Record<string, unknown>): CompactionV2Usage | undefined {
659
- const response = isRecord(event.response) ? event.response : undefined;
660
- const usage = response && isRecord(response.usage) ? response.usage : undefined;
661
- if (!usage) return undefined;
660
+ /** A Responses `usage` object; undefined when it is missing or lacks the token totals. */
661
+ export function parseResponsesCompactionUsage(usage: unknown): ResponsesCompactionUsage | undefined {
662
+ if (!isRecord(usage)) return undefined;
662
663
 
663
664
  const inputTokens = numberField(usage, "input_tokens");
664
665
  const outputTokens = numberField(usage, "output_tokens");
@@ -668,12 +669,14 @@ function parseCompactionV2Usage(event: Record<string, unknown>): CompactionV2Usa
668
669
  const inputDetails = isRecord(usage.input_tokens_details) ? usage.input_tokens_details : undefined;
669
670
  const outputDetails = isRecord(usage.output_tokens_details) ? usage.output_tokens_details : undefined;
670
671
  const cachedInputTokens = inputDetails ? numberField(inputDetails, "cached_tokens") : undefined;
672
+ const cacheWriteTokens = inputDetails ? numberField(inputDetails, "cache_write_tokens") : undefined;
671
673
  const reasoningOutputTokens = outputDetails ? numberField(outputDetails, "reasoning_tokens") : undefined;
672
674
  return {
673
675
  inputTokens,
674
676
  outputTokens,
675
677
  totalTokens,
676
678
  ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
679
+ ...(cacheWriteTokens !== undefined ? { cacheWriteTokens } : {}),
677
680
  ...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),
678
681
  };
679
682
  }
@@ -29,10 +29,15 @@ import * as AIError from "@oh-my-pi/pi-ai/error";
29
29
  import { createOpenAICodexCompactionRequestContext } from "@oh-my-pi/pi-ai/providers/openai-codex-compaction";
30
30
  import type { OpenAICodexCompactionBody } from "@oh-my-pi/pi-ai/providers/openai-codex-responses";
31
31
  import type { InputItem as CodexInputItem } from "@oh-my-pi/pi-ai/providers/openai-codex/request-transformer";
32
- import { buildResponsesInput, resolveOpenAICompatPolicy } from "@oh-my-pi/pi-ai/providers/openai-shared";
32
+ import {
33
+ buildResponsesInput,
34
+ calculateOpenAIUsageAccounting,
35
+ resolveOpenAICompatPolicy,
36
+ } from "@oh-my-pi/pi-ai/providers/openai-shared";
33
37
  import { isSurvivingAssistant } from "@oh-my-pi/pi-ai/providers/transform-messages";
34
38
  import { stripOpenAIResponsesOutputOnlyStatusesForReplay } from "@oh-my-pi/pi-ai/utils";
35
39
  import { resolveCatalogPolicy } from "@oh-my-pi/pi-catalog/compat/catalog-policy";
40
+ import { calculateCost } from "@oh-my-pi/pi-catalog/models";
36
41
  import { preferredDialect } from "@oh-my-pi/pi-catalog/identity";
37
42
  import { clampThinkingLevelForModel } from "@oh-my-pi/pi-catalog/model-thinking";
38
43
  import { isRecord, logger, prompt, withLoopPhase } from "@oh-my-pi/pi-utils";
@@ -53,6 +58,8 @@ import {
53
58
  buildCompactionV2Request,
54
59
  buildCompactionV2RequestFromBody,
55
60
  getCompactionV2PreserveData,
61
+ type ResponsesCompactionUsage,
62
+ remoteCompactionPolicyModel,
56
63
  requestCompactionV2Streaming,
57
64
  shouldUseCompactionV2Streaming,
58
65
  storeCompactionV2PreserveData,
@@ -468,8 +475,9 @@ function findValidCutPoints(entries: SessionEntry[], startIndex: number, endInde
468
475
  case "custom_message":
469
476
  case "label":
470
477
  }
471
- // branch_summary and custom_message are user-role messages, valid cut points
472
- if (entry.type === "branch_summary" || entry.type === "custom_message") {
478
+ // branch_summary and custom_message are user-role messages, valid cut points; a row kept out of
479
+ // context is not one, so keeping it must not move the cut past the reply before it.
480
+ if (entry.type === "branch_summary" || (entry.type === "custom_message" && !entry.excludeFromContext)) {
473
481
  cutPoints.push(i);
474
482
  }
475
483
  }
@@ -483,7 +491,7 @@ function findValidCutPoints(entries: SessionEntry[], startIndex: number, endInde
483
491
  * transcript's orphan-head trim all share this boundary definition.
484
492
  */
485
493
  export function isTurnStartEntry(entry: SessionEntry): boolean {
486
- if (entry.type === "branch_summary" || entry.type === "custom_message") {
494
+ if (entry.type === "branch_summary" || (entry.type === "custom_message" && !entry.excludeFromContext)) {
487
495
  return true;
488
496
  }
489
497
  if (entry.type === "message") {
@@ -777,6 +785,13 @@ export interface SummaryOptions {
777
785
  ctx: Context,
778
786
  options: SimpleStreamOptions,
779
787
  ) => Promise<AssistantMessage>;
788
+ /**
789
+ * Receives each OpenAI remote compaction request (V1 `/responses/compact`,
790
+ * V2 streaming) whose response reported usage. Those transports bypass
791
+ * {@link completeImpl}, so this is the only record of their spend: a
792
+ * content-less assistant message carrying the priced usage and duration.
793
+ */
794
+ onRemoteUsage?: (message: AssistantMessage) => void;
780
795
  /**
781
796
  * Transient-failure retry for the summarization oneshots (`generateSummary`,
782
797
  * `generateShortSummary`, `generateTurnPrefixSummary`).
@@ -793,6 +808,42 @@ export interface SummaryOptions {
793
808
  oneshotRetry?: OneshotRetryOptions | false;
794
809
  }
795
810
 
811
+ /**
812
+ * The record {@link SummaryOptions.onRemoteUsage} receives for one OpenAI
813
+ * remote compaction request, priced at `model`'s catalog rates (a
814
+ * `remoteCompaction.model` override is recorded by id; it has no rates here).
815
+ */
816
+ function remoteCompactionUsageMessage(
817
+ model: Model,
818
+ usage: ResponsesCompactionUsage,
819
+ startedAt: number,
820
+ ): AssistantMessage {
821
+ const target = remoteCompactionPolicyModel(model);
822
+ const tokens = calculateOpenAIUsageAccounting({
823
+ promptTokens: usage.inputTokens,
824
+ outputTokens: usage.outputTokens,
825
+ cachedTokens: usage.cachedInputTokens ?? 0,
826
+ reasoningTokens: usage.reasoningOutputTokens ?? 0,
827
+ cacheWriteOpenRouter: usage.cacheWriteTokens,
828
+ cacheWriteDeepSeek: undefined,
829
+ hasDeepSeekCacheHitAndMiss: false,
830
+ });
831
+ const billed: Usage = { ...tokens, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
832
+ billed.cost = calculateCost(model, billed);
833
+ const now = Date.now();
834
+ return {
835
+ role: "assistant",
836
+ content: [],
837
+ api: target.api,
838
+ provider: model.provider,
839
+ model: target.id,
840
+ usage: billed,
841
+ stopReason: "stop",
842
+ timestamp: now,
843
+ duration: now - startedAt,
844
+ };
845
+ }
846
+
796
847
  /**
797
848
  * Resolve the oneshot retry policy for a summarization call. Enabled by default
798
849
  * so a lone transient blip cannot abort compaction; `false` opts out for callers
@@ -1820,6 +1871,7 @@ export async function compact(
1820
1871
  fetch: options?.fetch,
1821
1872
  onPayload: options?.onPayload,
1822
1873
  completeImpl: options?.completeImpl,
1874
+ onRemoteUsage: options?.onRemoteUsage,
1823
1875
  // The caller's opt-out must reach every summarization oneshot, otherwise
1824
1876
  // an outer retry loop multiplies with the inner one (see SummaryOptions).
1825
1877
  oneshotRetry: options?.oneshotRetry,
@@ -1893,6 +1945,11 @@ export async function compact(
1893
1945
  * rewrite the tail's trailing tool outputs: the prefix keeps them intact.
1894
1946
  */
1895
1947
  const canCompactBeforeTail = lastSummarizedEntryId !== undefined && recentMessages.length > 0;
1948
+ const reportRemoteUsage = (usage: ResponsesCompactionUsage | undefined, startedAt: number): void => {
1949
+ if (usage && summaryOptions.onRemoteUsage) {
1950
+ summaryOptions.onRemoteUsage(remoteCompactionUsageMessage(model, usage, startedAt));
1951
+ }
1952
+ };
1896
1953
  const sendRemoteCompaction = async (
1897
1954
  sendWhole: () => Promise<void>,
1898
1955
  sendPrefix: () => Promise<boolean>,
@@ -2052,6 +2109,7 @@ export async function compact(
2052
2109
  tools,
2053
2110
  reasoning: buildCompactionV2Reasoning(model, summaryOptions.thinkingLevel),
2054
2111
  });
2112
+ const startedAt = Date.now();
2055
2113
  const remote = await withAuth(
2056
2114
  apiKey,
2057
2115
  key =>
@@ -2064,6 +2122,7 @@ export async function compact(
2064
2122
  }),
2065
2123
  { signal },
2066
2124
  );
2125
+ reportRemoteUsage(remote.usage, startedAt);
2067
2126
  preserveData = { ...preserveData, ...storeCompactionV2PreserveData(remote, model) };
2068
2127
  };
2069
2128
  const whole = await buildV2Input(true);
@@ -2112,7 +2171,8 @@ export async function compact(
2112
2171
  const convertToLlm = summaryOptions.convertToLlm ?? defaultConvertToLlm;
2113
2172
  const supportsOriginalDetail = openAiCompatSupportsImageDetailOriginal(model);
2114
2173
  const sendV1 = async (remoteHistory: Array<Record<string, unknown>>, rewriteOutputs: boolean): Promise<void> => {
2115
- const remote = await withAuth(
2174
+ const startedAt = Date.now();
2175
+ const { usage, ...remote } = await withAuth(
2116
2176
  apiKey,
2117
2177
  key =>
2118
2178
  requestOpenAiRemoteCompaction(
@@ -2132,6 +2192,7 @@ export async function compact(
2132
2192
  ),
2133
2193
  { signal },
2134
2194
  );
2195
+ reportRemoteUsage(usage, startedAt);
2135
2196
  preserveData = withOpenAiRemoteCompactionPreserveData(preserveData, remote);
2136
2197
  };
2137
2198
  const whole = buildOpenAiNativeHistory(
@@ -71,6 +71,8 @@ export interface CustomMessageEntry<T = unknown> extends SessionEntryBase {
71
71
  display: boolean;
72
72
  /** Who initiated this message for billing/attribution semantics. */
73
73
  attribution?: MessageAttribution;
74
+ /** Rendered and saved, never sent to the model (like `!!` bash rows). */
75
+ excludeFromContext?: boolean;
74
76
  }
75
77
 
76
78
  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,
@@ -70,7 +70,12 @@ import { dataUrlImageSize } from "../image-tokens";
70
70
  import { Tokenizer } from "../tokenizer";
71
71
  import { appendAzureApiVersion, resolveAzureOpenAiBaseUrl } from "./azure-openai-endpoint";
72
72
  import { prepareBedrockCompactionRequest } from "./bedrock";
73
- import { isOpenAiRemoteCompactionApi, remoteCompactionPolicyModel } from "./compaction-v2-streaming";
73
+ import {
74
+ isOpenAiRemoteCompactionApi,
75
+ parseResponsesCompactionUsage,
76
+ type ResponsesCompactionUsage,
77
+ remoteCompactionPolicyModel,
78
+ } from "./compaction-v2-streaming";
74
79
  import contextWindowTruncatedOutputPrompt from "./prompts/context-window-truncated-output.md" with { type: "text" };
75
80
 
76
81
  export * from "./compaction-v2-streaming";
@@ -378,7 +383,10 @@ export interface OpenAiRemoteCompactionRequest {
378
383
  include?: string[];
379
384
  }
380
385
 
381
- 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
+ }
382
390
 
383
391
  export interface RemoteCompactionRequest {
384
392
  systemPrompt: string;
@@ -1028,7 +1036,7 @@ export async function requestOpenAiRemoteCompaction(
1028
1036
  );
1029
1037
  }
1030
1038
 
1031
- const data = (await response.json()) as { output?: unknown[] } | undefined;
1039
+ const data = (await response.json()) as { output?: unknown[]; usage?: unknown } | undefined;
1032
1040
  const rawOutput = data?.output ?? [];
1033
1041
  const replacementHistory = rawOutput.filter(
1034
1042
  (item): item is Record<string, unknown> =>
@@ -1053,7 +1061,8 @@ export async function requestOpenAiRemoteCompaction(
1053
1061
  });
1054
1062
  throw new Error("Remote compaction response missing compaction item");
1055
1063
  }
1056
- return { provider: model.provider, replacementHistory, compactionItem };
1064
+ const usage = parseResponsesCompactionUsage(data?.usage);
1065
+ return { provider: model.provider, replacementHistory, compactionItem, ...(usage ? { usage } : {}) };
1057
1066
  }
1058
1067
 
1059
1068
  /**
@@ -1,4 +1,5 @@
1
1
  import type { ToolResultMessage } from "@oh-my-pi/pi-ai";
2
+ import { parseSpillUrl } from "@oh-my-pi/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
 
package/src/types.ts CHANGED
@@ -345,8 +345,9 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
345
345
  */
346
346
  hasIrcInterrupts?: () => boolean | Promise<boolean>;
347
347
  /**
348
- * Peeks whether a background completion (finished job, exited supervised
349
- * process) is queued for aside injection at the next boundary.
348
+ * Peeks whether a background notice (finished job, exited supervised
349
+ * process, output a running job was asked to report) is queued for aside
350
+ * injection at the next boundary.
350
351
  *
351
352
  * Same rules as {@link hasIrcInterrupts}: non-consuming, only cuts
352
353
  * *interruptible* waits short, in either interruptMode. Without