Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
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.
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Guidance for Claude Code when working in this repo.
- At the start of a feature/bugfix task, create a worktree (use the `EnterWorktree` tool, or `git worktree add`) and do all work there on a new branch.
- Keep `master` clean; open a PR from the worktree branch to merge.
- Small, single-file edits, docs-only tweaks, or quick investigations don't need a worktree — use judgment.
- **Before merging any worktree branch, run the real CLI e2e (`cli-e2e`) against live Copilot and confirm it passes.** Build the image and run it with your token mounted read-only (see [`e2e/docker/README.md`](e2e/docker/README.md)) — on Windows/Git Bash that's `MSYS_NO_PATHCONV=1 docker run --rm -v "C:/Users/<you>/.copilot-reverse/creds.json:/root/.copilot-reverse/creds.json:ro" <image>`. This is the fidelity gate a merge must clear; the hermetic http-e2e alone is not sufficient. Skip only when nothing observable changed (pure docs/refactor).
- When the work is merged or abandoned, remove the worktree.
- **After a PR merges:** exit the worktree, `git push origin --delete <branch>`, remove the worktree, delete the local branch, then fast-forward `master` to the merged commit (`git fetch origin && git merge --ff-only origin/master`) so the next task branches from latest.

Expand Down
22 changes: 22 additions & 0 deletions e2e/RESULTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,28 @@
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). Plus a **real-CLI docker case**: an 11-screenshot browser-loop
history posted to live Copilot never 413s AND Claude still reads the most-recent (green) screenshot —
proving old cleared, recent kept, end-to-end. 588 unit tests green; docker http-e2e ALL PASSED (63);
`tsc` clean. (The same real-CLI run shows the 5 pre-existing FAILs documented in the PR #48 entry
below — codex tool loop, 2× vision OCR, 2× unknown-model — untouched by this change.)
- **2026-07-02 (capability-driven 1M badge + generalised model names — PR #48)** — the picker's `[1m]`
badge now follows each model's real upstream context window (`fetchModelOneMSupport`, injected into
`toCanonical` as an `is1M` oracle) instead of a hardcoded set, and the friendly-name regex accepts any
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
42 changes: 42 additions & 0 deletions e2e/docker/cli-e2e.sh
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,48 @@ else
check "codex native web_search returns a grounded answer" 'false' "expected a 1.x version, got \`${CODEX_WEB_LINE}\`"
fi

# --- 16) context editing: a browser-harness-style pile of screenshots does NOT 413 ----------------
# The exact failure a user reported: browser-harness screenshots accumulate in history, the stateless
# wire re-sends them ALL every turn, and Copilot's gateway rejects the oversized body with 413 (relayed
# as a 502). The fix (core/context-edit.ts) clears OLD tool screenshots before send — keep the most
# recent 3, replace older with a placeholder — so the body stays under the gateway's entity limit.
# Reproduce it the way it actually happens: MANY tool_result screenshots (a browser loop) followed by a
# fresh question about the LATEST screenshot. Each image is a real, distinct-coloured 200x200 PNG big
# enough that, unedited, the pile would trip the limit. Two assertions:
# (a) the turn NEVER returns a 413 / entity-too-large (context editing kept the body small enough), and
# (b) Claude still correctly reads the MOST RECENT screenshot (green) — proving we cleared the OLD ones
# and preserved the recent ones, so the conversation still works. A naive "drop all images" would
# fail (b); a no-op would fail (a).
note "context editing -> a pile of history screenshots does not 413, latest image still readable"
CE_RESP=$(node -e '
const zlib=require("zlib");
function chunk(t,d){const l=Buffer.alloc(4);l.writeUInt32BE(d.length);const ty=Buffer.from(t);const cb=Buffer.concat([ty,d]);
let c=~0;for(const b of cb){c^=b;for(let i=0;i<8;i++)c=(c>>>1)^(0xEDB88320&-(c&1));}c=~c>>>0;const cr=Buffer.alloc(4);cr.writeUInt32BE(c>>>0);return Buffer.concat([l,ty,d,cr]);}
function png(W,H,r,g,b){const sig=Buffer.from([137,80,78,71,13,10,26,10]);const ihdr=Buffer.alloc(13);ihdr.writeUInt32BE(W,0);ihdr.writeUInt32BE(H,4);ihdr[8]=8;ihdr[9]=2;
const raw=Buffer.alloc(H*(1+W*3));for(let y=0;y<H;y++){const o=y*(1+W*3);raw[o]=0;for(let x=0;x<W;x++){const p=o+1+x*3;raw[p]=r;raw[p+1]=g;raw[p+2]=b;}}
return Buffer.concat([sig,chunk("IHDR",ihdr),chunk("IDAT",zlib.deflateSync(raw)),chunk("IEND",Buffer.alloc(0))]).toString("base64");}
// A browser loop: an initial user turn kicks it off, then each step is assistant(tool_use) ->
// user(tool_result with a screenshot). 10 older screenshots are grey; the newest is solid GREEN — the
// one we ask about. The leading user turn matters: Anthropic rejects a tool_result that is not preceded
// by an assistant tool_use, and messages[0] may not be a tool_result.
const msgs=[{role:"user",content:[{type:"text",text:"Drive a browser and screenshot each step."}]}];
for(let i=0;i<10;i++){
msgs.push({role:"assistant",content:[{type:"text",text:"step "+i},{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:png(200,200,128,128,128)}}]}]});
}
msgs.push({role:"assistant",content:[{type:"text",text:"final step"},{type:"tool_use",id:"slast",name:"screenshot",input:{}}]});
msgs.push({role:"user",content:[{type:"tool_result",tool_use_id:"slast",content:[{type:"text",text:"final step"},{type:"image",source:{type:"base64",media_type:"image/png",data:png(200,200,30,200,30)}}]}]});
msgs.push({role:"user",content:[{type:"text",text:"What colour is the most recent screenshot? Reply with one word."}]});
const body=JSON.stringify({model:"claude-opus-4-8[1m]",max_tokens:64,messages:msgs});
fetch("http://127.0.0.1:'"$PORT"'/anthropic/v1/messages",{method:"POST",headers:{"content-type":"application/json"},body}).then(r=>r.text()).then(t=>process.stdout.write(t)).catch(e=>process.stdout.write(JSON.stringify({error:{message:String(e)}})));
' 2>/dev/null)
CE_TEXT=$(echo "$CE_RESP" | jq -r '[.content[]?|select(.type=="text")|.text]|join("")' 2>/dev/null)
CE_ERR=$(echo "$CE_RESP" | jq -r '.error.message // empty' 2>/dev/null)
echo " context-edit turn result: ${CE_TEXT:-<err: $CE_ERR>}"
check "screenshot pile is a VALID request (no 4xx body-shape error masking the 413 check)" '! echo "$CE_RESP" | grep -qiE "invalid_request_body|400 —"' "request must be well-formed so the 413 check is meaningful; got err: \`${CE_ERR:-<none>}\`"
check "screenshot pile never 413s (context editing kept the body under the gateway limit)" '! echo "$CE_RESP" | grep -qiE "413|entity too large|too large"' "no 413/entity-too-large for a 11-screenshot history; got err: \`${CE_ERR:-<none>}\`"
check "latest screenshot still readable after clearing old ones (answers green)" 'echo "$CE_TEXT" | grep -qi "green"' "claude read the MOST RECENT (green) screenshot: \`${CE_TEXT:-<err: $CE_ERR>}\` — old ones cleared, recent kept"

# --- teardown -----------------------------------------------------------------------------------
kill "$WPID" 2>/dev/null

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 @@ -165,6 +165,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 };
}
Loading
Loading