Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat(context-edit): clear old tool screenshots to fix 413 on long age…
…ntic sessions

A browser-harness loop emits one screenshot per step, and the stateless wire
re-sends the whole history every turn, so cumulative base64 grows until Copilot's
gateway rejects the request body at the HTTP layer (413 Request Entity Too Large,
relayed as 502). This is a byte-size limit, distinct from the token limit the
image-downscale fix targets — per-image resize alone can't satisfy it.

The real Anthropic backend handles this server-side via context editing
(clear_tool_uses_20250919): keep the most recent few tool results, replace older
ones with a placeholder. Claude Code relies on it and keeps sending full history;
Copilot has no such layer. We now sit where that layer would:

- new core/context-edit.ts keeps the most recent 3 tool screenshots at full
  fidelity and clears older ones oldest-first (image -> placeholder text) once the
  cumulative image payload exceeds a ~6MB budget, only as much as needed. Lossless
  no-op when under budget; never touches top-level user-attached images.
- wired AFTER resize on all send paths (/anthropic/v1/messages,
  /openai/chat/completions, /openai/responses) AND count_tokens, so the estimate
  matches what's sent.
- errorHint gains a 413 branch (request too large -> /compact or fewer images).

Tests: new tests/core/context-edit.test.ts (7 cases) + 413 hint case + hermetic
http-e2e (12 accumulated screenshots under the per-image cap, count_tokens lands
far below raw sum -> proves clearing not resizing). 588 unit green; docker
http-e2e ALL PASSED (63); tsc clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
  • Loading branch information
wangcansunking and claude committed Jul 2, 2026
commit 3cdeeab9147e772e8d939953d019b7b481a7f231
4 changes: 4 additions & 0 deletions .changes/1783003569850-context-editing-images.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
bump: minor
---
Context editing for images: clear old tool screenshots before they reach Copilot, fixing `413 Request Entity Too Large` (relayed as a 502) on long browser-harness / agentic sessions. A stateless wire re-sends the whole history every turn, so a loop that screenshots each step accretes base64 until Copilot's gateway rejects the request body at the HTTP layer — a byte-size limit that per-image downscaling alone can't satisfy. The worker now does what Anthropic's backend does server-side (`clear_tool_uses_20250919`): keep the most recent 3 tool screenshots at full fidelity and replace older ones with a placeholder once the cumulative image payload exceeds budget, oldest-first and only as much as needed. Runs on both the Anthropic and OpenAI send paths (and `count_tokens`, so the estimate matches what's sent). Also adds a 413 hint pointing the user at `/compact` / fewer images.
20 changes: 20 additions & 0 deletions e2e/RESULTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,26 @@
Latest run of the end-to-end suite. Regenerate after every code change with `npm run test:e2e`
and update this file (paste the summary).

- **2026-07-02 (context editing — fixes `413 Request Entity Too Large` (relayed 502) on long
browser-harness / agentic sessions)** — a browser-harness loop emits one screenshot per step, and the
stateless wire re-sends the WHOLE history every turn, so cumulative base64 grows until Copilot's
gateway rejects the request body at the HTTP layer (a byte-size limit, distinct from the token limit
the image-downscale fix targets — per-image resize alone can't satisfy it). The real Anthropic backend
handles this server-side via context editing (`clear_tool_uses_20250919`): keep the most recent few
tool results, replace older ones with a placeholder. Claude Code relies on it and keeps sending the
full history; Copilot has no such layer. We now sit where that layer would: new `core/context-edit.ts`
keeps the most recent 3 tool screenshots at full fidelity and, once the cumulative image payload
exceeds a ~6MB budget, clears older ones oldest-first (image → placeholder text) and only as much as
needed — lossless no-op when under budget, and it never touches top-level (user-attached) images, only
tool results. Wired AFTER resize on all send paths (`/anthropic/v1/messages`, `/openai/chat/completions`,
`/openai/responses`) AND `count_tokens`, so the estimate matches what's sent. Also adds a 413
`errorHint` (`request too large — /compact or send fewer/smaller images`). New unit suite
`tests/core/context-edit.test.ts` (7 cases: no-op under budget, keep-floor, oldest-first, minimal
edit, multi-image unit clear, top-level untouched, idempotent) + a 413 hint case + a hermetic http-e2e
check (12 accumulated screenshots, each under the per-image cap, `count_tokens` lands far below the raw
sum — proving clearing, not resizing). 588 unit tests green; docker http-e2e ALL PASSED (63); `tsc`
clean.

- **2026-07-01 (image downscale — fixes `model_max_prompt_tokens_exceeded` 502 on pasted/tool images)**
— a large image came through as a multi-MB base64 data URL that Copilot's `/chat` bills as PLAIN TEXT
(~char/4, it has no vision tiler for Claude models), so one ~9MB image ≈ 2.3M tokens overflowed the
Expand Down
8 changes: 8 additions & 0 deletions e2e/cases.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,14 @@ whose long edge is already within the pixel cap but whose bytes are huge, assert
proving the gate is on bytes, not dimensions. Quota-free (no upstream call), so all run on the dummy
token.

It also asserts **context editing** (fixes `413 Request Entity Too Large` on long browser-harness
sessions): 12 screenshot turns, each already UNDER the per-image resize cap (so resize passes them
through untouched) but collectively far over the ~6MB cumulative budget, are posted to `count_tokens`.
The estimate must land far below the raw sum of all screenshots — proving old tool screenshots were
CLEARED (replaced with a placeholder, most-recent-3 kept), not merely resized. A precondition check
confirms each screenshot really was under the resize cap, so what shrank the count was clearing, not
per-image downscaling.

This black-box path caught two bugs nothing else did: a Codex tool-translation `400` (a `custom`/
`tool_search` tool forwarded nameless → Copilot rejects → "stream closed before response.completed"),
and empty terminal Responses events (`output_*.done` carried no text → Codex rendered nothing).
Expand Down
32 changes: 32 additions & 0 deletions e2e/docker/http-e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,38 @@ async function main() {
const hBody = JSON.stringify({ model: "claude-opus-4-8[1m]", messages: [{ role: "user", content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: hb64 } }] }] });
const hTokens = JSON.parse((await jpost(wrkUrl("/anthropic/v1/messages/count_tokens"), hBody)).t).input_tokens;
check("within-edge but heavy image is still shrunk (byte gate, not pixel gate)", hTokens > 0 && hTokens < hRaw / 2, `shrunk=${hTokens} raw=${hRaw}`);

// Context editing (clear old tool screenshots): a browser-harness loop emits one screenshot per
// step and the stateless wire re-sends ALL of them every turn, so cumulative base64 eventually
// trips Copilot's request entity limit (413 → relayed 502). The worker now does what Anthropic's
// backend does server-side — keep the most recent few screenshots, replace older ones with a
// placeholder. Prove it quota-free through count_tokens: build MANY screenshots each already under
// the per-image resize cap (so resize passes them through untouched) but collectively far over the
// cumulative budget, and assert the estimate lands far below the raw sum — i.e. old images were
// cleared, not merely resized. Each image ~1MB base64 (430×430 noise), 12 turns ≈ 12MB → the ~6MB
// budget forces roughly half to be cleared.
{
const one = new Jimp({ width: 430, height: 430, color: 0 });
randomFillSync(one.bitmap.data);
const sb64 = (await one.getBuffer(JimpMime.png)).toString("base64");
const shotLen = `data:image/png;base64,${sb64}`.length;
const TURNS = 12;
const msgs = [];
for (let i = 0; i < TURNS; i++) {
msgs.push({ role: "assistant", content: [{ type: "tool_use", id: `s${i}`, name: "screenshot", input: {} }] });
msgs.push({ role: "user", content: [{ type: "tool_result", tool_use_id: `s${i}`, content: [
{ type: "text", text: `step ${i}` },
{ type: "image", source: { type: "base64", media_type: "image/png", data: sb64 } },
] }] });
}
const rawAll = Math.ceil((shotLen * TURNS) / 4); // tokens if EVERY screenshot were kept
const ceBody = JSON.stringify({ model: "claude-opus-4-8[1m]", messages: msgs });
const ceTokens = JSON.parse((await jpost(wrkUrl("/anthropic/v1/messages/count_tokens"), ceBody)).t).input_tokens;
check("old tool screenshots are context-edited out (tokens << all-screenshots raw)", ceTokens > 0 && ceTokens < rawAll * 0.6, `edited=${ceTokens} rawAll=${rawAll} perShot=${Math.ceil(shotLen / 4)}`);
// Precondition guard: each screenshot really was under the per-image resize cap, so what shrank
// the count was CLEARING (context editing), not per-image downscaling.
check("context-edit precondition: each screenshot is under the per-image resize cap", shotLen < 1_500_000, `shotLen=${shotLen}`);
}
}

// Reasoning effort (#33) is resolved and echoed in the x-copilot-reverse-effort response header
Expand Down
89 changes: 89 additions & 0 deletions src/core/context-edit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import type { CanonicalMessage, ToolResultBlock } from "./canonical.js";
import { MAX_IMAGE_BYTES } from "./image-resize.js";

// Context editing for images — our stand-in for Anthropic's server-side `clear_tool_uses_20250919`.
//
// Why this exists: the real Anthropic backend runs "context editing" (public beta, 2025-09) BEFORE the
// prompt reaches the model — as an agentic conversation grows, it clears the OLDEST tool results,
// replacing each with a placeholder, and keeps only the most recent few. Claude Code relies on this: it
// keeps sending the FULL, unmodified history every turn (the wire is stateless) and trusts the backend
// to trim. Copilot's backend has NO such layer, so a browser-harness loop — one screenshot per step,
// every screenshot re-sent every turn — accretes base64 until the request body trips Copilot's HTTP
// entity-size limit and comes back 413 ("Request Entity Too Large"), which we relay as a 502.
//
// We sit exactly where that backend layer would, so we do its job: keep the most recent `keep`
// screenshots at full fidelity and replace older ones with a short placeholder. This is distinct from
// image-resize.ts — that shrinks each image to fit the *token* budget (per-image), this bounds the
// *cumulative byte* payload across a long multi-turn conversation. Both run before send; resize first
// (so kept images are already small), then this clears the older ones that resize alone can't save.

// How many recent tool screenshots to always preserve at full fidelity — matches Anthropic's
// `clear_tool_uses` `keep` default of 3. Two or three recent screenshots are what an agent actually
// reasons over; older ones are almost always spent context.
export const KEEP_RECENT_SCREENSHOTS = 3;

// Cumulative byte budget for all tool-screenshot payloads in a single request. resize caps each image
// at MAX_IMAGE_BYTES (~1.5MB), so `keep` recent images sit safely under this; clearing only kicks in
// once ACCUMULATED history pushes past it. Set to 4× the per-image cap (~6MB) — headroom for the kept
// images plus conversation text, well below Copilot's gateway entity limit.
export const IMAGE_PAYLOAD_BUDGET = 4 * MAX_IMAGE_BYTES;

// Appended to a tool_result's text when its image(s) are cleared, so the model still knows a screenshot
// was there (mirrors Anthropic replacing cleared content with placeholder text). Also the idempotency
// marker: a result already bearing this is never counted or re-cleared.
export const CLEARED_SCREENSHOT_PLACEHOLDER = "[earlier screenshot removed to fit context]";

function byteLen(images: string[]): number {
let n = 0;
for (const img of images) n += img.length;
return n;
}

// Every tool_result across the message list that still carries image(s), in conversation order
// (oldest first). Top-level image blocks are intentionally excluded — Anthropic's clear_tool_uses only
// touches tool RESULTS; a user-attached image is deliberate context and is the resize layer's concern.
function screenshotResults(messages: CanonicalMessage[]): ToolResultBlock[] {
const out: ToolResultBlock[] = [];
for (const m of messages) {
for (const b of m.content) {
if (b.type === "tool_result" && b.images && b.images.length > 0) out.push(b);
}
}
return out;
}

export interface ContextEditResult {
clearedCount: number; // number of tool_result blocks whose images were cleared
clearedBytes: number; // total base64 bytes freed
}

// Clear old tool screenshots in place so the cumulative image payload fits IMAGE_PAYLOAD_BUDGET, always
// preserving the most recent `keep`. Oldest-first, and stops the moment we're back under budget — the
// minimal edit, so we never drop context we didn't have to. Lossless (no-op) when already under budget.
export function editImageContextInPlace(
messages: CanonicalMessage[],
keep: number = KEEP_RECENT_SCREENSHOTS,
budget: number = IMAGE_PAYLOAD_BUDGET,
): ContextEditResult {
const results = screenshotResults(messages);
let total = 0;
for (const r of results) total += byteLen(r.images!);
if (total <= budget) return { clearedCount: 0, clearedBytes: 0 };

// Candidates to clear: everything except the most recent `keep`. Clear oldest-first, stopping as soon
// as the running total is back within budget.
const clearable = results.slice(0, Math.max(0, results.length - keep));
let clearedCount = 0;
let clearedBytes = 0;
for (const r of clearable) {
if (total <= budget) break;
const freed = byteLen(r.images!);
total -= freed;
clearedBytes += freed;
clearedCount++;
// Replace the image(s) with a placeholder appended to the result text, then drop the images.
r.content = r.content ? `${r.content}\n${CLEARED_SCREENSHOT_PLACEHOLDER}` : CLEARED_SCREENSHOT_PLACEHOLDER;
delete r.images;
}
return { clearedCount, clearedBytes };
}
9 changes: 9 additions & 0 deletions src/worker/anthropic-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { MetricSink } from "./server.js";
import { anthropicRequestToCanonical, canonicalToAnthropicResponse } from "../core/anthropic-inbound.js";
import { estimateTokens } from "../core/tokens.js";
import { shrinkImagesInPlace } from "../core/image-resize.js";
import { editImageContextInPlace } from "../core/context-edit.js";
import { errorHint } from "./errors.js";
import { CopilotAuthError } from "../providers/copilot/token.js";
import { isGatewayTool, type GatewayToolRunner } from "../core/server-tools.js";
Expand Down Expand Up @@ -42,6 +43,10 @@ export function mountAnthropic(app: Express, router: Router, onMetric: MetricSin
app.post("/anthropic/v1/messages/count_tokens", async (req, res) => {
const canon = anthropicRequestToCanonical(req.body);
await shrinkImagesInPlace(canon.messages);
// Mirror the send path's context editing so the count reflects the payload we'll ACTUALLY send —
// if we cleared old screenshots before sending but counted them here, count_tokens would over-report
// and Claude Code would compact needlessly. Both paths must agree.
editImageContextInPlace(canon.messages);
res.json({ input_tokens: estimateTokens(canon) });
});

Expand All @@ -52,6 +57,10 @@ export function mountAnthropic(app: Express, router: Router, onMetric: MetricSin
// base64 payload can't blow past Copilot's prompt-token limit (it has no vision tiler on /chat and
// bills the data URL as plain text). Runs before count/send so both see the reduced payload.
await shrinkImagesInPlace(canon.messages);
// Then context-edit: clear OLD tool screenshots that resize alone can't save, so a long
// browser-harness conversation's cumulative image bytes don't trip Copilot's request entity limit
// (413 → relayed 502). Keeps the most recent few; the real Anthropic backend does this server-side.
editImageContextInPlace(canon.messages);
canon.model = router.resolveModel(canon.model);
const provider = router.pick(canon.model);
// Echo the resolved reasoning effort back as a response header — real observability (a user can
Expand Down
6 changes: 6 additions & 0 deletions src/worker/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ export function errorHint(message: string): string {
if (/context_length_exceeded|prompt is too long|maximum context|too many tokens|context window/.test(m)) {
return "context window exceeded — the conversation is too long; /compact or switch to a larger-context model";
}
// Copilot's gateway rejected the request body at the HTTP layer (byte size, not tokens) — most often a
// long agentic session that accreted many screenshots. Context editing clears old ones automatically,
// but a single huge turn can still trip it. Point the user at compaction / trimming attachments.
if (/\b413\b|request entity too large|payload too large|entity too large/.test(m)) {
return "request too large — the payload exceeded the gateway limit; /compact or send fewer/smaller images";
}
if (/not supported|unknown model|invalid model|model_not_found|does not support/.test(m)) {
return "model not supported — run /model to pick an available one";
}
Expand Down
5 changes: 5 additions & 0 deletions src/worker/openai-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { MetricSink } from "./server.js";
import { openaiRequestToCanonical, canonicalToOpenAIResponse, canonicalChunkToOpenAISSE } from "../core/openai-inbound.js";
import { responsesRequestToCanonical, canonicalToResponsesResponse, ResponsesSSE } from "../core/responses-inbound.js";
import { shrinkImagesInPlace } from "../core/image-resize.js";
import { editImageContextInPlace } from "../core/context-edit.js";
import { errorHint } from "./errors.js";
import { CopilotAuthError } from "../providers/copilot/token.js";
import { RunawayGuard } from "../core/stream-guard.js";
Expand All @@ -26,6 +27,9 @@ export function mountOpenAI(app: Express, router: Router, onMetric: MetricSink):
// Downscale oversized images before they reach Copilot — it bills an inline data URL as plain
// text, so a full-resolution screenshot would otherwise overflow the model's prompt-token limit.
await shrinkImagesInPlace(canon.messages);
// Then clear OLD tool screenshots so a long agentic conversation's cumulative image bytes stay
// under Copilot's request entity limit (413). Keeps the most recent few, like Anthropic's backend.
editImageContextInPlace(canon.messages);
canon.model = router.resolveModel(canon.model);
const provider = router.pick(canon.model);
const metric = (status: number, opts: { error?: string; tokensIn?: number; tokensOut?: number } = {}) => onMetric({ endpoint: "/openai/chat/completions", model: canon.model, status, latencyMs: Date.now() - start, tokensIn: opts.tokensIn, tokensOut: opts.tokensOut, error: opts.error });
Expand Down Expand Up @@ -78,6 +82,7 @@ export function mountOpenAI(app: Express, router: Router, onMetric: MetricSink):
const canon = responsesRequestToCanonical(req.body);
// Same image downscale as /chat: keep the base64 payload within the model's prompt budget.
await shrinkImagesInPlace(canon.messages);
editImageContextInPlace(canon.messages); // + clear old screenshots (cumulative-byte / 413 guard)
canon.model = router.resolveModel(canon.model);
const provider = router.pick(canon.model);
const metric = (status: number, opts: { error?: string; tokensIn?: number; tokensOut?: number } = {}) => onMetric({ endpoint: "/openai/responses", model: canon.model, status, latencyMs: Date.now() - start, tokensIn: opts.tokensIn, tokensOut: opts.tokensOut, error: opts.error });
Expand Down
Loading
Loading