@vellumai/assistant 0.10.4-dev.202607022033.68350d5 → 0.10.4-dev.202607022130.febf41d

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.4-dev.202607022033.68350d5",
3
+ "version": "0.10.4-dev.202607022130.febf41d",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -0,0 +1,177 @@
1
+ import { describe, expect, mock, test } from "bun:test";
2
+
3
+ function makeLoggerStub(): Record<string, unknown> {
4
+ const stub: Record<string, unknown> = {};
5
+ for (const m of [
6
+ "info",
7
+ "warn",
8
+ "error",
9
+ "debug",
10
+ "trace",
11
+ "fatal",
12
+ "silent",
13
+ "child",
14
+ ]) {
15
+ stub[m] = m === "child" ? () => makeLoggerStub() : () => {};
16
+ }
17
+ return stub;
18
+ }
19
+
20
+ mock.module("../util/logger.js", () => ({
21
+ getLogger: () => makeLoggerStub(),
22
+ }));
23
+
24
+ mock.module("../persistence/conversation-crud.js", () => ({
25
+ setConversationProcessingStartedAt: () => {},
26
+ isConversationProcessing: () => false,
27
+ getMessages: () => [],
28
+ reserveMessage: mock(async () => ({ id: "msg-reserve" })),
29
+ }));
30
+
31
+ mock.module("../persistence/attachments-store.js", () => ({
32
+ getAttachmentMetadataForMessage: () => [],
33
+ getAttachmentContent: () => null,
34
+ }));
35
+
36
+ import { runAssistantDrivenCompaction } from "../context/compactor.js";
37
+ import type { Message, Provider } from "../providers/types.js";
38
+
39
+ const TAIL_TIMESTAMP =
40
+ "2026-05-21 (Thursday) 10:00:00 -05:00 (America/Chicago)";
41
+
42
+ const compactionResponse = `
43
+ <compaction_result>
44
+ <summary>
45
+ Earlier turns summarized here.
46
+ </summary>
47
+
48
+ <key_state>
49
+ - Nothing critical pending.
50
+ </key_state>
51
+
52
+ <tail_start timestamp="${TAIL_TIMESTAMP}" preview="tail anchor message" />
53
+ </compaction_result>
54
+ `;
55
+
56
+ const OLD_SCREENSHOT_DATA = "b64-old-screenshot-bytes";
57
+ const LATEST_SCREENSHOT_DATA = "b64-latest-screenshot-bytes";
58
+ const USER_ATTACHED_IMAGE_DATA = "b64-user-attached-bytes";
59
+
60
+ const userTextWithTurnContext = (text: string, timestamp: string): Message => ({
61
+ role: "user",
62
+ content: [
63
+ {
64
+ type: "text",
65
+ text: `<turn_context>\ncurrent_time: ${timestamp}\n</turn_context>\n${text}`,
66
+ },
67
+ ],
68
+ });
69
+
70
+ const assistantToolUse = (id: string): Message => ({
71
+ role: "assistant",
72
+ content: [{ type: "tool_use", id, name: "screenshot", input: {} }],
73
+ });
74
+
75
+ const toolResultWithImage = (id: string, data: string): Message => ({
76
+ role: "user",
77
+ content: [
78
+ {
79
+ type: "tool_result",
80
+ tool_use_id: id,
81
+ content: "captured",
82
+ contentBlocks: [
83
+ {
84
+ type: "image",
85
+ source: { type: "base64", media_type: "image/png", data },
86
+ },
87
+ ],
88
+ },
89
+ ],
90
+ });
91
+
92
+ const userWithAttachedImage = (): Message => ({
93
+ role: "user",
94
+ content: [
95
+ { type: "text", text: "here is a mockup" },
96
+ {
97
+ type: "image",
98
+ source: {
99
+ type: "base64",
100
+ media_type: "image/png",
101
+ data: USER_ATTACHED_IMAGE_DATA,
102
+ },
103
+ },
104
+ ],
105
+ });
106
+
107
+ function serializeBlocks(messages: Message[]): string {
108
+ return JSON.stringify(messages);
109
+ }
110
+
111
+ // Records the exact message list the provider is asked to summarize.
112
+ function recordingProvider(sink: { sent: Message[] }): Provider {
113
+ return {
114
+ name: "mock-provider",
115
+ sendMessage: async (msgs: Message[]) => {
116
+ sink.sent = msgs;
117
+ return {
118
+ content: [{ type: "text", text: compactionResponse }],
119
+ model: "mock-model",
120
+ usage: { inputTokens: 100, outputTokens: 50 },
121
+ stopReason: "end_turn",
122
+ };
123
+ },
124
+ };
125
+ }
126
+
127
+ // The summary request must carry the same media-stripped projection the agent
128
+ // loop sends on its own model calls. An unsanitized history resends every
129
+ // screenshot in the conversation; enough of them cross Anthropic's many-image
130
+ // threshold, where a stricter per-image dimension cap rejects the whole
131
+ // summary call (and trips the compaction circuit breaker).
132
+ describe("compaction summary calls — old tool-result media stripping", () => {
133
+ test("runAssistantDrivenCompaction strips images from older tool results, keeps the latest turn's image and user-attached images, and leaves durable history untouched", async () => {
134
+ // GIVEN a screenshot-heavy history: older tool results with images, a
135
+ // user-attached image, and a most-recent tool result with an image
136
+ const messages: Message[] = [
137
+ userWithAttachedImage(),
138
+ assistantToolUse("tu_old_1"),
139
+ toolResultWithImage("tu_old_1", OLD_SCREENSHOT_DATA),
140
+ userTextWithTurnContext("tail anchor message", TAIL_TIMESTAMP),
141
+ assistantToolUse("tu_latest"),
142
+ toolResultWithImage("tu_latest", LATEST_SCREENSHOT_DATA),
143
+ ];
144
+
145
+ // AND a snapshot of the caller's array so we can assert it is not mutated
146
+ const inputSnapshot = serializeBlocks(messages);
147
+ const sink = { sent: [] as Message[] };
148
+
149
+ // WHEN compaction runs over that history
150
+ const result = await runAssistantDrivenCompaction({
151
+ conversationId: "conv-media-strip",
152
+ messages,
153
+ provider: recordingProvider(sink),
154
+ systemPrompt: "system",
155
+ compaction: { enabled: true, autoThreshold: 0.7 },
156
+ // Large budget so the request is not front-truncated — this test
157
+ // exercises the media-strip sanitizer, not the truncation fallback.
158
+ maxInputTokens: 100000,
159
+ previousEstimatedInputTokens: 90000,
160
+ });
161
+
162
+ // THEN older tool-result screenshots are replaced with a text marker
163
+ const sentSerialized = serializeBlocks(sink.sent);
164
+ expect(sentSerialized).not.toContain(OLD_SCREENSHOT_DATA);
165
+ expect(sentSerialized).toContain("binary data removed to save context");
166
+
167
+ // AND the most recent tool-result turn keeps its image (the model may
168
+ // still need it), as do images the user attached directly
169
+ expect(sentSerialized).toContain(LATEST_SCREENSHOT_DATA);
170
+ expect(sentSerialized).toContain(USER_ATTACHED_IMAGE_DATA);
171
+
172
+ // AND the caller's durable history array is left byte-for-byte untouched,
173
+ // so persisted messages keep the original rich blocks
174
+ expect(serializeBlocks(messages)).toBe(inputSnapshot);
175
+ expect(result.compacted).toBe(true);
176
+ });
177
+ });
@@ -622,6 +622,13 @@ describe("web_search_tool_result structural guard", () => {
622
622
  "context/post-turn-tool-result-truncation.ts",
623
623
  "context/tool-result-spool.ts",
624
624
 
625
+ // Outbound sanitize bundle: the media-strip and AX-tree transforms
626
+ // operate on locally-executed tool results (media contentBlocks and
627
+ // <ax-tree> text), which web_search_tool_result blocks never carry.
628
+ // Web-search blocks are handled by the bundle's own third transform
629
+ // (stripHistoricalWebSearchResults), so nothing is silently dropped.
630
+ "context/outbound-sanitize.ts",
631
+
625
632
  // Anthropic provider type guards define API-specific discriminants.
626
633
  // It has a separate isWebSearchToolResultBlock for the other type.
627
634
  "providers/anthropic/client.ts",
@@ -1,6 +1,6 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
 
3
- import { preModelCallSanitize } from "../agent/loop.js";
3
+ import { preModelCallSanitize } from "../context/outbound-sanitize.js";
4
4
  import type { Message } from "../providers/types.js";
5
5
 
6
6
  /**
@@ -1,7 +1,10 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
 
3
+ import {
4
+ compactAxTreeHistory,
5
+ escapeAxTreeContent,
6
+ } from "../context/outbound-sanitize.js";
3
7
  import type { Message } from "../providers/types.js";
4
- import { compactAxTreeHistory, escapeAxTreeContent } from "./loop.js";
5
8
 
6
9
  // ---------------------------------------------------------------------------
7
10
  // Helpers
package/src/agent/loop.ts CHANGED
@@ -4,6 +4,7 @@ import { getConfig } from "../config/loader.js";
4
4
  import { isMemoryV3Live } from "../config/memory-v3-gate.js";
5
5
  import type { LLMCallSite } from "../config/schemas/llm.js";
6
6
  import { recordEstimate } from "../context/estimator-calibration.js";
7
+ import { preModelCallSanitize } from "../context/outbound-sanitize.js";
7
8
  import {
8
9
  estimatePromptTokensRaw,
9
10
  estimatePromptTokensWithTools,
@@ -14,7 +15,6 @@ import { spoolAndStubOversizedToolResults } from "../context/tool-result-spool.j
14
15
  import type { ToolActivityMetadata } from "../daemon/message-types/web-activity.js";
15
16
  import { parseActualTokensFromError } from "../daemon/parse-actual-tokens-from-error.js";
16
17
  import type { TrustContext } from "../daemon/trust-context.js";
17
- import { stripHistoricalWebSearchResults } from "../daemon/web-search-history.js";
18
18
  import {
19
19
  timeSyncSection,
20
20
  traceAsyncSection,
@@ -2520,178 +2520,3 @@ export class AgentLoop {
2520
2520
  };
2521
2521
  }
2522
2522
  }
2523
-
2524
- /** Number of most-recent AX tree snapshots to keep in conversation history. */
2525
- const MAX_AX_TREES_IN_HISTORY = 2;
2526
-
2527
- /** Regex that matches the `<ax-tree>...</ax-tree>` markers. */
2528
- const AX_TREE_PATTERN = /<ax-tree>[\s\S]*?<\/ax-tree>/g;
2529
- const AX_TREE_PLACEHOLDER = "<ax_tree_omitted />";
2530
-
2531
- /**
2532
- * Escapes any literal `</ax-tree>` occurrences inside AX tree content so
2533
- * that the non-greedy compaction regex (`AX_TREE_PATTERN`) does not stop
2534
- * prematurely when the user happens to be viewing XML/HTML source that
2535
- * contains the closing tag. The escaped content does not need to be
2536
- * unescaped because compaction replaces the entire block with a placeholder.
2537
- */
2538
- export function escapeAxTreeContent(content: string): string {
2539
- return content.replace(/<\/ax-tree>/gi, "&lt;/ax-tree&gt;");
2540
- }
2541
-
2542
- /**
2543
- * Returns a shallow copy of `messages` where all but the most recent
2544
- * `MAX_AX_TREES_IN_HISTORY` `<ax-tree>` blocks have been replaced with a
2545
- * short placeholder. This keeps the conversation context small so that
2546
- * TTFT does not grow linearly with step count in computer-use sessions.
2547
- *
2548
- * Counting is per-block, not per-message — a single user message can
2549
- * contain multiple tool_result blocks each with their own AX tree snapshot.
2550
- */
2551
- export function compactAxTreeHistory(messages: Message[]): Message[] {
2552
- // Collect (messageIndex, blockIndex) for every tool_result block with <ax-tree>
2553
- const axBlocks: Array<{ msgIdx: number; blockIdx: number }> = [];
2554
- for (let i = 0; i < messages.length; i++) {
2555
- const msg = messages[i];
2556
- if (msg.role !== "user") continue;
2557
- for (let j = 0; j < msg.content.length; j++) {
2558
- const block = msg.content[j];
2559
- if (
2560
- block.type === "tool_result" &&
2561
- typeof block.content === "string" &&
2562
- block.content.includes("<ax-tree>")
2563
- ) {
2564
- axBlocks.push({ msgIdx: i, blockIdx: j });
2565
- }
2566
- }
2567
- }
2568
-
2569
- if (axBlocks.length <= MAX_AX_TREES_IN_HISTORY) {
2570
- return messages;
2571
- }
2572
-
2573
- // Build a set of "msgIdx:blockIdx" keys for blocks that should be stripped
2574
- const toStrip = new Set(
2575
- axBlocks
2576
- .slice(0, -MAX_AX_TREES_IN_HISTORY)
2577
- .map((b) => `${b.msgIdx}:${b.blockIdx}`),
2578
- );
2579
-
2580
- return messages.map((msg, idx) => {
2581
- // Quick check: does this message have any blocks to strip?
2582
- const hasStripTarget = msg.content.some((_, j) =>
2583
- toStrip.has(`${idx}:${j}`),
2584
- );
2585
- if (!hasStripTarget) return msg;
2586
-
2587
- return {
2588
- ...msg,
2589
- content: msg.content.map((block, j) => {
2590
- if (
2591
- toStrip.has(`${idx}:${j}`) &&
2592
- block.type === "tool_result" &&
2593
- typeof block.content === "string"
2594
- ) {
2595
- return {
2596
- ...block,
2597
- content: block.content.replace(
2598
- AX_TREE_PATTERN,
2599
- AX_TREE_PLACEHOLDER,
2600
- ),
2601
- };
2602
- }
2603
- return block;
2604
- }),
2605
- };
2606
- });
2607
- }
2608
-
2609
- /**
2610
- * Strip image contentBlocks from all tool_result blocks except those in the
2611
- * most recent user message that contains tool_result blocks. This prevents
2612
- * screenshots from accumulating in the context window — each image is seen
2613
- * once by the LLM on the turn it was captured, then replaced with a text
2614
- * placeholder on subsequent turns.
2615
- *
2616
- * We target the last user message with tool_results (not just the last user
2617
- * message) because a plain-text user message may follow the tool-result
2618
- * turn. Using the last user message unconditionally would leave the most
2619
- * recent tool screenshots unprotected from stripping.
2620
- */
2621
- function stripOldMediaBlocks(history: Message[]): Message[] {
2622
- // Find the last user message that contains tool_result blocks.
2623
- let lastToolResultUserIdx = -1;
2624
- for (let i = history.length - 1; i >= 0; i--) {
2625
- if (
2626
- history[i].role === "user" &&
2627
- history[i].content.some((b) => b.type === "tool_result")
2628
- ) {
2629
- lastToolResultUserIdx = i;
2630
- break;
2631
- }
2632
- }
2633
-
2634
- return history.map((msg, idx) => {
2635
- // Keep the most recent tool-result user message intact (current turn)
2636
- if (idx === lastToolResultUserIdx || msg.role !== "user") return msg;
2637
-
2638
- // Check if any tool_result blocks carry embedded media (image or audio).
2639
- const isMedia = (cb: ContentBlock) =>
2640
- cb.type === "image" || cb.type === "file";
2641
- const hasMedia = msg.content.some(
2642
- (b) =>
2643
- b.type === "tool_result" &&
2644
- (b as ToolResultContent).contentBlocks?.some(isMedia),
2645
- );
2646
- if (!hasMedia) return msg;
2647
-
2648
- // Strip media from tool_result blocks, replacing with a text marker. The
2649
- // model already saw/heard the media in the turn it was captured; resending
2650
- // the bytes every turn (a 12 MB audio clip isn't optimized like images)
2651
- // bloats the request until compaction.
2652
- return {
2653
- ...msg,
2654
- content: msg.content.map((b) => {
2655
- if (b.type !== "tool_result") return b;
2656
- const tr = b as ToolResultContent;
2657
- if (!tr.contentBlocks?.some(isMedia)) return b;
2658
- return {
2659
- ...tr,
2660
- contentBlocks: undefined,
2661
- content:
2662
- (tr.content || "") +
2663
- "\n[Media (image/audio) was captured and shown previously — binary data removed to save context.]",
2664
- };
2665
- }),
2666
- };
2667
- });
2668
- }
2669
-
2670
- /**
2671
- * Sanitize the outbound history immediately before a provider call, bundling
2672
- * the pre-send transforms the loop applies to every request:
2673
- * - {@link stripOldMediaBlocks} drops accumulated screenshot/audio bytes from
2674
- * older tool results — the model saw the media on the turn it was captured.
2675
- * - {@link compactAxTreeHistory} collapses all but the most recent few
2676
- * `<ax-tree>` snapshots so TTFT does not grow linearly with step count.
2677
- * - {@link stripHistoricalWebSearchResults} converts historical
2678
- * `web_search_tool_result` blocks to text summaries; Anthropic's opaque
2679
- * `encrypted_content` tokens expire / are route-scoped, and replaying a stale
2680
- * one is rejected with `Invalid encrypted_content in search_result block`.
2681
- *
2682
- * Transforms the outbound copy only — the durable history keeps the rich
2683
- * originals and each send re-derives the sanitized projection (every transform
2684
- * is idempotent). Because it runs unconditionally before every provider call,
2685
- * it is the single place where oversized media and expired web-search tokens
2686
- * are guaranteed to be removed from a request.
2687
- *
2688
- * This is outbound-request preparation and should eventually move to a default
2689
- * `pre-model-call` plugin hook ({@link HOOKS.PRE_MODEL_CALL}) once that hook's
2690
- * context carries the outbound message list; for now it lives inline next to
2691
- * the provider call it guards.
2692
- */
2693
- export function preModelCallSanitize(history: Message[]): Message[] {
2694
- const mediaStripped = stripOldMediaBlocks(history);
2695
- const axCompacted = compactAxTreeHistory(mediaStripped);
2696
- return stripHistoricalWebSearchResults(axCompacted).messages;
2697
- }
@@ -22,7 +22,6 @@ import { optimizeImageForTransport } from "../agent/image-optimize.js";
22
22
  import type { CompactionConfig } from "../config/schemas/compaction.js";
23
23
  import type { LLMCallSite } from "../config/schemas/llm.js";
24
24
  import { filterMessagesForUntrustedActor } from "../daemon/message-provenance.js";
25
- import { stripHistoricalWebSearchResults } from "../daemon/web-search-history.js";
26
25
  import {
27
26
  getAttachmentContent,
28
27
  getAttachmentMetadataForMessage,
@@ -40,6 +39,7 @@ import type {
40
39
  import { type TrustClass } from "../runtime/actor-trust-resolver.js";
41
40
  import { resolveCapabilities } from "../runtime/capabilities.js";
42
41
  import { getLogger } from "../util/logger.js";
42
+ import { preModelCallSanitize } from "./outbound-sanitize.js";
43
43
  import { stripInjectionsForCompaction } from "./strip-injections.js";
44
44
  import {
45
45
  estimatePromptTokens,
@@ -826,14 +826,20 @@ function extractTextFromResponse(content: ContentBlock[]): string {
826
826
  .join("\n");
827
827
  }
828
828
 
829
- // Build the outbound message list for a compaction provider call: convert
830
- // historical web_search_tool_result blocks to text, then append the
831
- // summarization instruction at the tail.
829
+ // Build the outbound message list for a compaction provider call: apply the
830
+ // same pre-send sanitization bundle as the agent loop's model calls
831
+ // (`preModelCallSanitize` — old tool-result media stripped, AX trees
832
+ // collapsed, historical web-search results converted to text), then append
833
+ // the summarization instruction at the tail.
832
834
  //
833
- // Anthropic's opaque `encrypted_content` tokens are route-scoped and expire, so
834
- // replaying a stale one is rejected with `Invalid encrypted_content in
835
- // search_result block`. Sanitizing here — the single seam every compaction
836
- // provider call funnels through — keeps that error away from both the
835
+ // Matching the loop's projection matters for two reasons. First, the summary
836
+ // call's prefix stays byte-aligned with the agent's warm prompt cache — an
837
+ // unsanitized history diverges from what the loop actually sent at the first
838
+ // stripped block. Second, an unsanitized history carries every screenshot in
839
+ // the conversation; enough images cross Anthropic's many-image threshold,
840
+ // where a stricter per-image dimension cap applies and a single large
841
+ // screenshot rejects the whole summary call. Sanitizing here — the single
842
+ // seam every compaction provider call funnels through — covers both the
837
843
  // assistant-driven and emergency summarization calls. Only this outbound copy
838
844
  // is sanitized; tail resolution and the persisted compaction result read the
839
845
  // caller's original messages, so durable history keeps the rich blocks. The
@@ -842,7 +848,7 @@ function buildCompactionRequest(
842
848
  history: Message[],
843
849
  instruction: Message,
844
850
  ): Message[] {
845
- return [...stripHistoricalWebSearchResults(history).messages, instruction];
851
+ return [...preModelCallSanitize(history), instruction];
846
852
  }
847
853
 
848
854
  // Token headroom a compaction summary call reserves on top of its history: room
@@ -945,11 +951,14 @@ export async function runAssistantDrivenCompaction(
945
951
  // Bound the summary call's own input to the context window. With no tool
946
952
  // pair to anchor an emergency split, an overflow recovery routes the full
947
953
  // history straight here, so the summary call must front-truncate itself or
948
- // it overflows in turn. `args.messages` stays intact for tail resolution
949
- // below — only the outbound request is truncated. A below-budget history is
950
- // returned untouched, keeping the prefix aligned with the agent's warm cache.
954
+ // it overflows in turn. Truncation operates on the sanitized projection
955
+ // (what the request actually carries) so the budget estimate is honest —
956
+ // estimating on raw history would count media bytes the request strips.
957
+ // `args.messages` stays intact for tail resolution below — only the
958
+ // outbound request is truncated. A below-budget history is returned
959
+ // untouched, keeping the prefix aligned with the agent's warm cache.
951
960
  const summaryHistory = truncateHistoryToBudget({
952
- messages: args.messages,
961
+ messages: preModelCallSanitize(args.messages),
953
962
  systemPrompt: args.systemPrompt,
954
963
  budgetTokens: compactionPrefixBudget(args.maxInputTokens),
955
964
  providerName: args.provider.tokenEstimationProvider ?? args.provider.name,
@@ -1371,9 +1380,14 @@ export async function runEmergencyCompaction(
1371
1380
  );
1372
1381
  // Bound the prefix to the context window so the summary call fits, reserving
1373
1382
  // budget for the instruction message and the emitted summary. Truncates from
1374
- // the front, keeping the recent portion the summary most needs.
1383
+ // the front, keeping the recent portion the summary most needs. The prefix
1384
+ // is sliced from the sanitized projection (sanitize-then-slice, matching the
1385
+ // agent's own sends byte-for-byte for cache alignment) so the budget
1386
+ // estimate counts what the request actually carries. All sanitize
1387
+ // transforms are 1:1 per message, so `splitIndex` maps onto the sanitized
1388
+ // array unchanged.
1375
1389
  const prefix = truncateHistoryToBudget({
1376
- messages: args.messages.slice(0, splitIndex),
1390
+ messages: preModelCallSanitize(args.messages).slice(0, splitIndex),
1377
1391
  systemPrompt: args.systemPrompt,
1378
1392
  budgetTokens: compactionPrefixBudget(args.maxInputTokens),
1379
1393
  providerName: args.provider.tokenEstimationProvider ?? args.provider.name,
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Outbound-request history sanitization shared by every provider call that
3
+ * sends conversation history: the agent loop's model calls and the
4
+ * compactor's summary calls. Each transform derives a sanitized projection of
5
+ * the outbound copy only — durable history keeps the rich originals, and every
6
+ * transform is idempotent so each send re-derives the same projection.
7
+ */
8
+
9
+ import { stripHistoricalWebSearchResults } from "../daemon/web-search-history.js";
10
+ import type {
11
+ ContentBlock,
12
+ Message,
13
+ ToolResultContent,
14
+ } from "../providers/types.js";
15
+
16
+ /** Number of most-recent AX tree snapshots to keep in conversation history. */
17
+ const MAX_AX_TREES_IN_HISTORY = 2;
18
+
19
+ /** Regex that matches the `<ax-tree>...</ax-tree>` markers. */
20
+ const AX_TREE_PATTERN = /<ax-tree>[\s\S]*?<\/ax-tree>/g;
21
+ const AX_TREE_PLACEHOLDER = "<ax_tree_omitted />";
22
+
23
+ /**
24
+ * Escapes any literal `</ax-tree>` occurrences inside AX tree content so
25
+ * that the non-greedy compaction regex (`AX_TREE_PATTERN`) does not stop
26
+ * prematurely when the user happens to be viewing XML/HTML source that
27
+ * contains the closing tag. The escaped content does not need to be
28
+ * unescaped because compaction replaces the entire block with a placeholder.
29
+ */
30
+ export function escapeAxTreeContent(content: string): string {
31
+ return content.replace(/<\/ax-tree>/gi, "&lt;/ax-tree&gt;");
32
+ }
33
+
34
+ /**
35
+ * Returns a shallow copy of `messages` where all but the most recent
36
+ * `MAX_AX_TREES_IN_HISTORY` `<ax-tree>` blocks have been replaced with a
37
+ * short placeholder. This keeps the conversation context small so that
38
+ * TTFT does not grow linearly with step count in computer-use sessions.
39
+ *
40
+ * Counting is per-block, not per-message — a single user message can
41
+ * contain multiple tool_result blocks each with their own AX tree snapshot.
42
+ */
43
+ export function compactAxTreeHistory(messages: Message[]): Message[] {
44
+ // Collect (messageIndex, blockIndex) for every tool_result block with <ax-tree>
45
+ const axBlocks: Array<{ msgIdx: number; blockIdx: number }> = [];
46
+ for (let i = 0; i < messages.length; i++) {
47
+ const msg = messages[i];
48
+ if (msg.role !== "user") {
49
+ continue;
50
+ }
51
+ for (let j = 0; j < msg.content.length; j++) {
52
+ const block = msg.content[j];
53
+ if (
54
+ block.type === "tool_result" &&
55
+ typeof block.content === "string" &&
56
+ block.content.includes("<ax-tree>")
57
+ ) {
58
+ axBlocks.push({ msgIdx: i, blockIdx: j });
59
+ }
60
+ }
61
+ }
62
+
63
+ if (axBlocks.length <= MAX_AX_TREES_IN_HISTORY) {
64
+ return messages;
65
+ }
66
+
67
+ // Build a set of "msgIdx:blockIdx" keys for blocks that should be stripped
68
+ const toStrip = new Set(
69
+ axBlocks
70
+ .slice(0, -MAX_AX_TREES_IN_HISTORY)
71
+ .map((b) => `${b.msgIdx}:${b.blockIdx}`),
72
+ );
73
+
74
+ return messages.map((msg, idx) => {
75
+ // Quick check: does this message have any blocks to strip?
76
+ const hasStripTarget = msg.content.some((_, j) =>
77
+ toStrip.has(`${idx}:${j}`),
78
+ );
79
+ if (!hasStripTarget) {
80
+ return msg;
81
+ }
82
+
83
+ return {
84
+ ...msg,
85
+ content: msg.content.map((block, j) => {
86
+ if (
87
+ toStrip.has(`${idx}:${j}`) &&
88
+ block.type === "tool_result" &&
89
+ typeof block.content === "string"
90
+ ) {
91
+ return {
92
+ ...block,
93
+ content: block.content.replace(
94
+ AX_TREE_PATTERN,
95
+ AX_TREE_PLACEHOLDER,
96
+ ),
97
+ };
98
+ }
99
+ return block;
100
+ }),
101
+ };
102
+ });
103
+ }
104
+
105
+ /**
106
+ * Strip image contentBlocks from all tool_result blocks except those in the
107
+ * most recent user message that contains tool_result blocks. This prevents
108
+ * screenshots from accumulating in the context window — each image is seen
109
+ * once by the LLM on the turn it was captured, then replaced with a text
110
+ * placeholder on subsequent turns.
111
+ *
112
+ * We target the last user message with tool_results (not just the last user
113
+ * message) because a plain-text user message may follow the tool-result
114
+ * turn. Using the last user message unconditionally would leave the most
115
+ * recent tool screenshots unprotected from stripping.
116
+ */
117
+ function stripOldMediaBlocks(history: Message[]): Message[] {
118
+ // Find the last user message that contains tool_result blocks.
119
+ let lastToolResultUserIdx = -1;
120
+ for (let i = history.length - 1; i >= 0; i--) {
121
+ if (
122
+ history[i].role === "user" &&
123
+ history[i].content.some((b) => b.type === "tool_result")
124
+ ) {
125
+ lastToolResultUserIdx = i;
126
+ break;
127
+ }
128
+ }
129
+
130
+ return history.map((msg, idx) => {
131
+ // Keep the most recent tool-result user message intact (current turn)
132
+ if (idx === lastToolResultUserIdx || msg.role !== "user") {
133
+ return msg;
134
+ }
135
+
136
+ // Check if any tool_result blocks carry embedded media (image or audio).
137
+ const isMedia = (cb: ContentBlock) =>
138
+ cb.type === "image" || cb.type === "file";
139
+ const hasMedia = msg.content.some(
140
+ (b) =>
141
+ b.type === "tool_result" &&
142
+ (b as ToolResultContent).contentBlocks?.some(isMedia),
143
+ );
144
+ if (!hasMedia) {
145
+ return msg;
146
+ }
147
+
148
+ // Strip media from tool_result blocks, replacing with a text marker. The
149
+ // model already saw/heard the media in the turn it was captured; resending
150
+ // the bytes every turn (a 12 MB audio clip isn't optimized like images)
151
+ // bloats the request until compaction.
152
+ return {
153
+ ...msg,
154
+ content: msg.content.map((b) => {
155
+ if (b.type !== "tool_result") {
156
+ return b;
157
+ }
158
+ const tr = b as ToolResultContent;
159
+ if (!tr.contentBlocks?.some(isMedia)) {
160
+ return b;
161
+ }
162
+ return {
163
+ ...tr,
164
+ contentBlocks: undefined,
165
+ content:
166
+ (tr.content || "") +
167
+ "\n[Media (image/audio) was captured and shown previously — binary data removed to save context.]",
168
+ };
169
+ }),
170
+ };
171
+ });
172
+ }
173
+
174
+ /**
175
+ * Sanitize the outbound history immediately before a provider call, bundling
176
+ * the pre-send transforms applied to every request that carries conversation
177
+ * history:
178
+ * - {@link stripOldMediaBlocks} drops accumulated screenshot/audio bytes from
179
+ * older tool results — the model saw the media on the turn it was captured.
180
+ * Beyond context bloat, unstripped history can carry enough images to cross
181
+ * Anthropic's many-image threshold, where a stricter per-image dimension
182
+ * cap applies and a single large screenshot rejects the whole request.
183
+ * - {@link compactAxTreeHistory} collapses all but the most recent few
184
+ * `<ax-tree>` snapshots so TTFT does not grow linearly with step count.
185
+ * - {@link stripHistoricalWebSearchResults} converts historical
186
+ * `web_search_tool_result` blocks to text summaries; Anthropic's opaque
187
+ * `encrypted_content` tokens expire / are route-scoped, and replaying a stale
188
+ * one is rejected with `Invalid encrypted_content in search_result block`.
189
+ *
190
+ * Transforms the outbound copy only — the durable history keeps the rich
191
+ * originals and each send re-derives the sanitized projection (every transform
192
+ * is idempotent). Both the agent loop's model calls and the compactor's
193
+ * summary calls funnel through this bundle, so their request prefixes stay
194
+ * byte-aligned (the summary call reuses the agent's warm prompt cache) and
195
+ * oversized media and expired web-search tokens are guaranteed to be removed
196
+ * from every request.
197
+ */
198
+ export function preModelCallSanitize(history: Message[]): Message[] {
199
+ const mediaStripped = stripOldMediaBlocks(history);
200
+ const axCompacted = compactAxTreeHistory(mediaStripped);
201
+ return stripHistoricalWebSearchResults(axCompacted).messages;
202
+ }
@@ -16,8 +16,8 @@
16
16
 
17
17
  import { v4 as uuid } from "uuid";
18
18
 
19
- import { escapeAxTreeContent } from "../agent/loop.js";
20
19
  import { loadConfig } from "../config/loader.js";
20
+ import { escapeAxTreeContent } from "../context/outbound-sanitize.js";
21
21
  import type { ContentBlock } from "../providers/types.js";
22
22
  import {
23
23
  assistantEventHub,