Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(claude): keep requests under the endpoints' 20-image limit on long threads
刘伟29bd206ac525
diff --git a/scripts/testing/file-size-ratchet.test.ts b/scripts/testing/file-size-ratchet.test.tsindex 50e360ff4a..9d0c2523d2 100644--- a/scripts/testing/file-size-ratchet.test.ts+++ b/scripts/testing/file-size-ratchet.test.ts@@ -21,7 +21,7 @@ const LINES: Record<string, number> = {"electron/main.mjs": 3124,"server/store.ts": 2265,"src/components/Sidebar.tsx": 1674,- "server/drivers/claude.ts": 2069,+ "server/drivers/claude.ts": 2073,"server/drivers/acp/core.ts": 1654,"server/drivers/codex.ts": 1593,"server/routines.ts": 1553,diff --git a/server/drivers/claude-transcript-images.test.ts b/server/drivers/claude-transcript-images.test.tsnew file mode 100644index 0000000000..731e5e43b0--- /dev/null+++ b/server/drivers/claude-transcript-images.test.ts@@ -0,0 +1,79 @@+import assert from "node:assert/strict";+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { test } from "vitest";++import { CLAUDE_IMAGE_KEEP, CLAUDE_IMAGE_LIMIT, foldTranscriptImages, transcriptImagesOver, transcriptPath } from "./claude-transcript-images.ts";++const image = (n: number) => ({ type: "image", source: { type: "base64", media_type: "image/png", data: `img${n}` } });+const userRow = (blocks: unknown[], n: number) => JSON.stringify({ type: "user", message: { role: "user", content: blocks }, uuid: `u${n}` });++function setup(rows: string[]): { configDir: string; cwd: string; sessionId: string; file: string } {+ const base = mkdtempSync(join(tmpdir(), "claude-images-"));+ const configDir = join(base, ".claude-api");+ const cwd = "/home/user/projects/thread-abc";+ const sessionId = "s1";+ const file = transcriptPath(configDir, cwd, sessionId);+ mkdirSync(join(file, ".."), { recursive: true });+ writeFileSync(file, rows.join("\n") + "\n");+ return { configDir, cwd, sessionId, file };+}++const count = (text: string, needle: string) => text.split(needle).length - 1;++test("a resumed thread keeps its newest images: older ones become a note, the engine's JSONL stays one row per message", () => {+ const rows = Array.from({ length: 25 }, (_, i) => userRow([{ type: "text", text: `page ${i + 1}` }, image(i + 1)], i + 1));+ const { configDir, cwd, sessionId, file } = setup(rows);+ const result = foldTranscriptImages({ configDir, cwd, sessionId, minBytes: 0 });+ assert.deepEqual(result, { total: 25, folded: 25 - CLAUDE_IMAGE_KEEP });+ const text = readFileSync(file, "utf8");+ assert.equal(count(text, '"type":"image"'), CLAUDE_IMAGE_KEEP);+ assert.equal(count(text, "Earlier image"), 25 - CLAUDE_IMAGE_KEEP);+ assert.equal(text.trim().split("\n").length, 25);+ // the newest pages are the ones still attached+ const last = JSON.parse(text.trim().split("\n").at(-1)!);+ assert.equal(last.message.content[1].source.data, "img25");+ // the folded rows keep their own text+ const first = JSON.parse(text.trim().split("\n")[0]);+ assert.equal(first.message.content[0].text, "page 1");+ assert.match(first.message.content[1].text, /Earlier image/);+});++test("tool-result images count too, and a transcript already under the limit is left untouched", () => {+ const toolResult = (n: number) => JSON.stringify({ type: "user", message: { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: [image(n)] }] } });+ const few = setup([toolResult(1), toolResult(2)]);+ assert.deepEqual(foldTranscriptImages({ configDir: few.configDir, cwd: few.cwd, sessionId: few.sessionId, minBytes: 0 }), { total: 2, folded: 0 });+ const before = readFileSync(few.file, "utf8");++ const many = setup(Array.from({ length: 20 }, (_, i) => toolResult(i + 1)));+ assert.equal(foldTranscriptImages({ configDir: many.configDir, cwd: many.cwd, sessionId: many.sessionId, minBytes: 0 }).folded, 20 - CLAUDE_IMAGE_KEEP);+ assert.equal(count(readFileSync(many.file, "utf8"), '"type":"image"'), CLAUDE_IMAGE_KEEP);+ assert.equal(readFileSync(few.file, "utf8"), before);+});++test("a missing transcript is a no-op, and the same file is not parsed twice", () => {+ const { configDir, cwd } = setup([]);+ assert.equal(foldTranscriptImages({ configDir, cwd, sessionId: "nope", minBytes: 0 }).skipped, "missing");++ const rows = Array.from({ length: 21 }, (_, i) => userRow([image(i)], i));+ const one = setup(rows);+ assert.equal(foldTranscriptImages({ configDir: one.configDir, cwd: one.cwd, sessionId: one.sessionId, minBytes: 0 }).folded, 21 - CLAUDE_IMAGE_KEEP);+ assert.equal(foldTranscriptImages({ configDir: one.configDir, cwd: one.cwd, sessionId: one.sessionId, minBytes: 0 }).skipped, "unchanged");+});++test("a warm process is over the limit once what it holds plus this turn's images passes 20", () => {+ const rows = (n: number) => Array.from({ length: n }, (_, i) => userRow([{ type: "text", text: `page ${i}` }, image(i)], i));+ const at = setup(rows(CLAUDE_IMAGE_LIMIT));+ assert.equal(transcriptImagesOver(at), false);+ assert.equal(transcriptImagesOver(at, 1), true);+ const under = setup(rows(CLAUDE_IMAGE_LIMIT - 2));+ assert.equal(transcriptImagesOver(under, 2), false);+ assert.equal(transcriptImagesOver({ ...under, sessionId: "nope" }, 50), false);+ // after the fold the same session has room again+ foldTranscriptImages({ ...at, minBytes: 0 });+ assert.equal(transcriptImagesOver(at, CLAUDE_IMAGE_LIMIT - CLAUDE_IMAGE_KEEP), false);+ // the word "image" in text is not an image+ const words = setup([userRow([{ type: "text", text: '"image" '.repeat(30) }], 1)]);+ assert.equal(transcriptImagesOver(words, 0), false);+});diff --git a/server/drivers/claude-transcript-images.ts b/server/drivers/claude-transcript-images.tsnew file mode 100644index 0000000000..93facedfef--- /dev/null+++ b/server/drivers/claude-transcript-images.ts@@ -0,0 +1,140 @@+// Anthropic-compatible endpoints take at most 20 images per request. Claude Code sends the whole conversation on every+// turn, so a long thread that keeps adding screenshots (a patent page per turn) crosses that line and every later turn,+// text-only or not, is refused with HTTP 400 "Total number of images exceeds the maximum allowed of 20" (seen+// 2026-11-13 on a patent-extraction thread: 81k tokens, page images from earlier turns).+//+// Before a resumed turn, keep the newest images and turn the older ones into a one-line note in the transcript Claude+// Code reads. A warm process holds the conversation in memory and never rereads that file, so once its next request+// would go over the limit it is not reused: the turn starts a process that resumes the folded transcript instead+// (transcriptImagesOver). The engine's own JSONL is the only place both sides share; nothing else about the conversation changes,+// and a folded image is still described by the text around it.+import { readFileSync, renameSync, statSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";++/** What one request may carry (the endpoints' own limit). */+export const CLAUDE_IMAGE_LIMIT = 20;+/** How many the transcript keeps: room for this turn's new images under the limit. */+export const CLAUDE_IMAGE_KEEP = 16;+/** Under this size a transcript cannot hold 20 images; skip parsing it on every turn. */+const MIN_BYTES = 256 * 1024;++const lastSeen = new Map<string, string>();+const counted = new Map<string, { stamp: string; total: number }>();++export interface FoldResult {+ total: number;+ folded: number;+ /** Why nothing was done, when it was not a fold. */+ skipped?: "small" | "unchanged" | "missing" | "unreadable";+}++/** Where Claude Code keeps one session's transcript. The folder is the working directory with everything but letters+ * and digits turned into '-', as its own code does. */+export function transcriptPath(configDir: string, cwd: string, sessionId: string): string {+ return join(configDir, "projects", cwd.replace(/[^A-Za-z0-9]/g, "-"), `${sessionId}.jsonl`);+}++type ImageSlot = { container: unknown[]; index: number };++/** Whether a warm process on this session would send more than the limit with `incoming` new images: its transcript+ * already holds everything it will resend. Counted once per version of the file; false when there is no transcript. */+export function transcriptImagesOver(options: { configDir: string; cwd: string; sessionId: string }, incoming = 0): boolean {+ const file = transcriptPath(options.configDir, options.cwd, options.sessionId);+ let stat;+ try {+ stat = statSync(file);+ } catch {+ return false;+ }+ const stamp = `${stat.size}:${stat.mtimeMs}`;+ let total = counted.get(file)?.stamp === stamp ? counted.get(file)!.total : -1;+ if (total < 0) {+ total = 0;+ for (const line of readFileSync(file, "utf8").split("\n")) {+ if (!line.includes('"image"')) continue;+ try {+ total += imageSlots(JSON.parse(line)).length;+ } catch { /* a half-written last line */ }+ }+ counted.set(file, { stamp, total });+ }+ return total + incoming > CLAUDE_IMAGE_LIMIT;+}++function imageSlots(row: unknown): ImageSlot[] {+ const slots: ImageSlot[] = [];+ const walk = (value: unknown, depth: number) => {+ if (!value || typeof value !== "object" || depth > 8) return;+ if (Array.isArray(value)) {+ value.forEach((entry, index) => {+ if (entry && typeof entry === "object" && (entry as { type?: unknown }).type === "image") slots.push({ container: value, index });+ else walk(entry, depth + 1);+ });+ return;+ }+ for (const entry of Object.values(value as Record<string, unknown>)) walk(entry, depth + 1);+ };+ walk(row, 0);+ return slots;+}++const note = (n: number) => ({ type: "text", text: `[Earlier image ${n} omitted: a request carries at most ${CLAUDE_IMAGE_LIMIT} images, so only the newest ${CLAUDE_IMAGE_KEEP} are kept]` });++/** Keep the newest `keep` images of one transcript, replacing older ones with a text note. Atomic: a new file is written+ * beside it and renamed over. Returns what it found; never throws: an unreadable transcript must not cost the turn. */+export function foldTranscriptImages(options: FoldOptions): FoldResult {+ try {+ return fold(options);+ } catch {+ return { total: 0, folded: 0, skipped: "unreadable" };+ }+}++interface FoldOptions {+ configDir: string;+ cwd: string;+ sessionId: string;+ keep?: number;+ /** The gate that skips small transcripts; 0 when the transcript is known to be over the limit. */+ minBytes?: number;+}++function fold(options: FoldOptions): FoldResult {+ const keep = Math.max(1, Math.min(options.keep ?? CLAUDE_IMAGE_KEEP, CLAUDE_IMAGE_LIMIT));+ const file = transcriptPath(options.configDir, options.cwd, options.sessionId);+ let stat;+ try {+ stat = statSync(file);+ } catch {+ return { total: 0, folded: 0, skipped: "missing" };+ }+ if (stat.size < (options.minBytes ?? MIN_BYTES)) return { total: 0, folded: 0, skipped: "small" };+ const stamp = `${stat.size}:${stat.mtimeMs}`;+ if (lastSeen.get(file) === stamp) return { total: 0, folded: 0, skipped: "unchanged" };++ const lines = readFileSync(file, "utf8").split("\n");+ const parsed: Array<{ line: string; row?: unknown }> = lines.map((line) => {+ if (!line.trim()) return { line };+ try {+ return { line, row: JSON.parse(line) as unknown };+ } catch {+ return { line }; // a half-written last line, or a format this code does not know: left as it was+ }+ });+ const slots: ImageSlot[] = [];+ for (const entry of parsed) if (entry.row !== undefined) slots.push(...imageSlots(entry.row));+ if (slots.length <= keep) {+ lastSeen.set(file, stamp);+ return { total: slots.length, folded: 0 };+ }+ const fold = slots.slice(0, slots.length - keep);+ fold.forEach((slot, index) => { slot.container[slot.index] = note(index + 1); });++ const out = parsed.map((entry) => (entry.row === undefined ? entry.line : JSON.stringify(entry.row))).join("\n");+ const temp = join(dirname(file), `.${options.sessionId}.images.tmp`);+ writeFileSync(temp, out, { mode: stat.mode });+ renameSync(temp, file);+ const after = statSync(file);+ lastSeen.set(file, `${after.size}:${after.mtimeMs}`);+ return { total: slots.length, folded: fold.length };+}diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.tsindex 3c06fc1c5e..c249f19e3a 100644--- a/server/drivers/claude.test.ts+++ b/server/drivers/claude.test.ts@@ -3,6 +3,7 @@ import { createServer as createHttpServer, type IncomingHttpHeaders } from "nodeimport { connect, createServer as createNetServer, type AddressInfo, type Socket } from "node:net";import { homedir, tmpdir } from "node:os";import { dirname, join, relative } from "node:path";+import { CLAUDE_IMAGE_KEEP, transcriptPath } from "./claude-transcript-images.ts";import { fileURLToPath } from "node:url";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -3807,6 +3808,33 @@ describe("ClaudeDriver turns (fake CLI)", () => {expect(dump.argv).toContain("claude-other");});+ it("does not reuse a warm process whose next request would carry more than 20 images: a fresh one resumes the folded transcript", async () => {+ const configDir = join(scratch, "claude-config");+ const cwd = join(scratch, "work");+ mkdirSync(cwd, { recursive: true });+ await create(undefined, { CLAUDE_CONFIG_DIR: configDir });+ await instance.adapter.sendTurn({ threadId: "t-images", text: "one", cwd });+ await recorder.until((e) => e.type === "turn.completed");+ const announced = (recorder.events.find((e) => e.type === "session.started") as { sessionId: string }).sessionId;+ // what Claude Code itself would have written: a page image on every turn+ const file = transcriptPath(configDir, cwd, announced);+ mkdirSync(dirname(file), { recursive: true });+ const row = (n: number) => JSON.stringify({ type: "user", message: { role: "user", content: [{ type: "text", text: `page ${n}` },+ { type: "image", source: { type: "base64", media_type: "image/png", data: `img${n}` } }] } });+ writeFileSync(file, Array.from({ length: 19 }, (_, i) => row(i)).join("\n") + "\n");+ // 19 held + none new: still the warm process+ const second = await instance.adapter.sendTurn({ threadId: "t-images", text: "two", cwd, resumeCursor: announced });+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === second.turnId);+ writeFileSync(file, Array.from({ length: 25 }, (_, i) => row(i)).join("\n") + "\n");+ const third = await instance.adapter.sendTurn({ threadId: "t-images", text: "three", cwd, resumeCursor: announced });+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === third.turnId);+ const closes = readFileSync(join(NATIVE_DIR, "t-images.ndjson"), "utf8").split("\n").filter(Boolean)+ .map((line) => { try { return JSON.parse(line).msg?.close; } catch { return undefined; } }).filter(Boolean);+ expect(closes).toEqual(["images over the request limit"]);+ const kept = readFileSync(file, "utf8");+ expect(kept.split('"type":"image"').length - 1).toBe(CLAUDE_IMAGE_KEEP);+ }, 20_000);+it("names the changed contract fields when a warm process is replaced", async () => {await create();await instance.adapter.sendTurn({diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex 95bdb015d1..a2503114d2 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -61,6 +61,7 @@ import { BACKGROUND_CALL_TIMEOUT_MS, backgroundCallArgs, spawnBackgroundCall } fimport { permissionLaunchCwd, shellRequest } from "./permission-command.ts"; import { readToolPaths } from "../own-file-reads.ts";import { SPAWNED_PROXIES } from "../proxy-paths.ts"; import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";import { extractMcpImages } from "../mcp-tool-images.ts"; import { claudeToolDraft } from "./tool-progress.ts"; import { redactSecretsInText } from "../../shared/redact.ts";+import { foldTranscriptImages, transcriptImagesOver } from "./claude-transcript-images.ts";import {ASK_USER_QUESTION_TOOL,ASK_USER_TOOL,@@ -1213,8 +1214,10 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {// A process started ahead is taken once it has started up and has listed again the tools the harness serves only during a turn.const ahead = sessions.get(threadId);if (!spare && ahead?.spare && !ahead.closing && ahead.argsKey === argsKey && !(ahead.tools?.ready && await ahead.tools.relist(Object.keys(mcpServers)))) closeSession(threadId, "never used");- const live = sessions.get(threadId);- if (!turn.sessionReset && live && !live.turn && !live.closing && live.child.exitCode === null && live.argsKey === argsKey && (!sessionId || sessionId === live.sessionId)) {+ const live = sessions.get(threadId), transcript = { configDir: env.CLAUDE_CONFIG_DIR?.trim() || resolveClaudeConfigDir(undefined, env), cwd };+ // A warm process resends every image it holds: past the endpoints' limit a fresh one resumes the folded transcript (claude-transcript-images.ts).+ const imagesOver = !turn.sessionReset && !!sessionId && live?.sessionId === sessionId && !live.turn && transcriptImagesOver({ ...transcript, sessionId }, turn.images?.length ?? 0);+ if (!turn.sessionReset && !imagesOver && live && !live.turn && !live.closing && live.child.exitCode === null && live.argsKey === argsKey && (!sessionId || sessionId === live.sessionId)) {stopIdleClose(`${instanceId}\0${threadId}`, live.idleTimer); // busy again: no longer idleif (live.spare) { live.spare = false; live.take?.(turnId); appendNative(threadId, { dir: "out", source: "claude.session", msg: { took: "prestarted" } }); }live.turn = { turnId, input: turn, retryAbort, settled: false, sawStreamDelta: false, awaitingInit: true, pendingSteers: new Set(), deferred: null, continuationGrace: null, continuationSilence: null };@@ -1242,7 +1245,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {return { turnId };}// The old process and its tree end before the new one starts, so two never share the session.- if (live) { closeSession(threadId, turn.sessionReset ? "context reset" : "spawn contract changed", turn.sessionReset ? undefined : spawnContractDiff(live.argsKey, argsKey)); await (live.spare ? stopEngineTree(live.child, 0, 0) : stopEngineTree(live.child)); } // an unused spare has nothing to save: no wait for it to leave by itself+ if (live) { closeSession(threadId, turn.sessionReset ? "context reset" : imagesOver ? "images over the request limit" : "spawn contract changed", turn.sessionReset || imagesOver ? undefined : spawnContractDiff(live.argsKey, argsKey)); await (live.spare ? stopEngineTree(live.child, 0, 0) : stopEngineTree(live.child)); } // an unused spare has nothing to save: no wait for it to leave by itself// A new process gets the stable half only; the volatile half rides its first message, so a relaunch reuses the cached prefix.const halves = promptHalves(turn);const launchSystem = halves.stable ?? turn.system;@@ -1330,7 +1333,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {if (authSettingsPath) {writeFileSync(authSettingsPath, JSON.stringify(settings), { mode: 0o600 });}- if (sessionId) args.push("--resume", sessionId);+ // A resumed thread resends every image of its past turns: older ones become a note under the endpoints' limit.+ if (sessionId) { foldTranscriptImages({ ...transcript, sessionId, ...(imagesOver ? { minBytes: 0 } : {}) }); args.push("--resume", sessionId); }else args.push("--session-id", newSessionId!);} catch (error) {cleanupUnownedLaunch();