Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(claude): fold to leave room for the turn's images; find the transcript where the CLI writes it
刘伟d661d0aa2146
diff --git a/server/drivers/claude-transcript-images.test.ts b/server/drivers/claude-transcript-images.test.tsindex 731e5e43b0..f5434787bb 100644--- a/server/drivers/claude-transcript-images.test.ts+++ b/server/drivers/claude-transcript-images.test.ts@@ -1,10 +1,10 @@import assert from "node:assert/strict";-import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, statSync, symlinkSync, 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";+import { CLAUDE_IMAGE_KEEP, CLAUDE_IMAGE_LIMIT, foldTranscriptImages, imagesToKeep, 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}` });@@ -25,7 +25,7 @@ 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 });+ const result = foldTranscriptImages({ configDir, cwd, sessionId });assert.deepEqual(result, { total: 25, folded: 25 - CLAUDE_IMAGE_KEEP });const text = readFileSync(file, "utf8");assert.equal(count(text, '"type":"image"'), CLAUDE_IMAGE_KEEP);@@ -43,23 +43,24 @@ test("a resumed thread keeps its newest images: older ones become a note, the entest("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 });+ assert.deepEqual(foldTranscriptImages({ configDir: few.configDir, cwd: few.cwd, sessionId: few.sessionId }), { 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(foldTranscriptImages({ configDir: many.configDir, cwd: many.cwd, sessionId: many.sessionId }).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", () => {+test("a missing transcript is a no-op, and a folded one is not folded again", () => {const { configDir, cwd } = setup([]);- assert.equal(foldTranscriptImages({ configDir, cwd, sessionId: "nope", minBytes: 0 }).skipped, "missing");+ assert.equal(foldTranscriptImages({ configDir, cwd, sessionId: "nope" }).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");+ assert.equal(foldTranscriptImages({ configDir: one.configDir, cwd: one.cwd, sessionId: one.sessionId }).folded, 21 - CLAUDE_IMAGE_KEEP);+ const again = foldTranscriptImages({ configDir: one.configDir, cwd: one.cwd, sessionId: one.sessionId });+ assert.deepEqual(again, { total: CLAUDE_IMAGE_KEEP, folded: 0 });});test("a warm process is over the limit once what it holds plus this turn's images passes 20", () => {@@ -71,9 +72,53 @@ test("a warm process is over the limit once what it holds plus this turn's imageassert.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 });+ foldTranscriptImages({ ...at });assert.equal(transcriptImagesOver(at, CLAUDE_IMAGE_LIMIT - CLAUDE_IMAGE_KEEP), false);// the word "image" in text is not an imageconst words = setup([userRow([{ type: "text", text: '"image" '.repeat(30) }], 1)]);assert.equal(transcriptImagesOver(words, 0), false);});++test("a small transcript is folded too: size says nothing about how many images it holds", () => {+ const { file, ...options } = setup(Array.from({ length: 25 }, (_, i) => userRow([image(i)], i)));+ assert.ok(statSync(file).size < 16 * 1024);+ assert.equal(foldTranscriptImages(options).folded, 25 - CLAUDE_IMAGE_KEEP);+});++test("the turn's own images get room: 16 held and 5 new keep 15, even after a fold that kept 16", () => {+ const { file, ...options } = setup(Array.from({ length: CLAUDE_IMAGE_KEEP + 2 }, (_, i) => userRow([image(i)], i)));+ assert.equal(foldTranscriptImages(options).folded, 2);+ assert.equal(transcriptImagesOver(options, 5), true);+ assert.deepEqual(foldTranscriptImages({ ...options, incoming: 5 }), { total: CLAUDE_IMAGE_KEEP, folded: 1 });+ assert.equal(count(readFileSync(file, "utf8"), '"type":"image"'), CLAUDE_IMAGE_LIMIT - 5);+ assert.equal(transcriptImagesOver(options, 5), false);+ assert.equal(imagesToKeep(0), CLAUDE_IMAGE_KEEP);+ assert.equal(imagesToKeep(30), 0);+});++test("the transcript is found where Claude Code writes it: a linked working directory, and a path over 200 characters", () => {+ const base = mkdtempSync(join(tmpdir(), "claude-images-"));+ const configDir = join(base, ".claude-api");+ const rows = Array.from({ length: 21 }, (_, i) => userRow([image(i)], i)).join("\n");+ // the folder named after the resolved directory, built here by the CLI's own rule rather than through transcriptPath+ const real = join(base, "real");+ mkdirSync(real);+ const link = join(base, "link");+ symlinkSync(real, link);+ const linked = join(configDir, "projects", real.replace(/[^A-Za-z0-9]/g, "-"));+ mkdirSync(linked, { recursive: true });+ writeFileSync(join(linked, "s1.jsonl"), rows);+ assert.equal(transcriptImagesOver({ configDir, cwd: link, sessionId: "s1" }), true);+ assert.equal(foldTranscriptImages({ configDir, cwd: link, sessionId: "s1" }).folded, 21 - CLAUDE_IMAGE_KEEP);+ // a long working directory: cut at 200 characters, then '-' and the CLI's hash of the full path+ const long = "/" + "deep/".repeat(50) + "thread";+ assert.equal(transcriptPath(configDir, long, "s1"), join(configDir, "projects", `${long.replace(/[^A-Za-z0-9]/g, "-").slice(0, 200)}-h0oumx`, "s1.jsonl"));+});++test("a transcript that cannot be read keeps the warm process and costs the turn nothing", () => {+ const options = setup([]);+ const unreadable = { configDir: options.configDir, cwd: options.cwd, sessionId: "dir" };+ mkdirSync(transcriptPath(options.configDir, options.cwd, "dir")); // stat works, read does not+ assert.equal(transcriptImagesOver(unreadable, 25), false);+ assert.equal(foldTranscriptImages(unreadable).skipped, "unreadable");+});diff --git a/server/drivers/claude-transcript-images.ts b/server/drivers/claude-transcript-images.tsindex 93facedfef..1c4dda762f 100644--- a/server/drivers/claude-transcript-images.ts+++ b/server/drivers/claude-transcript-images.ts@@ -3,64 +3,98 @@// 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";+// Before a resumed turn, keep the newest images that fit beside the turn's own 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, realpathSync, renameSync, statSync, writeFileSync, type Stats } 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. */+/** How many the transcript keeps at most: room for a few 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;+/** Claude Code's cap on a project folder's name; a longer one is cut and given a hash of the full path. */+const PROJECT_DIR_MAX = 200;-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";+ /** Why nothing was read, when nothing was. */+ skipped?: "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. */+interface TranscriptOptions {+ configDir: string;+ cwd: string;+ sessionId: string;+}++/** Where Claude Code keeps one session's transcript, as its own code names it: the working directory with everything but+ * letters and digits turned into '-', cut at 200 characters plus a hash of the full path when longer. */export function transcriptPath(configDir: string, cwd: string, sessionId: string): string {- return join(configDir, "projects", cwd.replace(/[^A-Za-z0-9]/g, "-"), `${sessionId}.jsonl`);+ let name = cwd.replace(/[^A-Za-z0-9]/g, "-");+ if (name.length > PROJECT_DIR_MAX) {+ let hash = 0;+ for (let i = 0; i < cwd.length; i++) hash = ((hash << 5) - hash + cwd.charCodeAt(i)) | 0;+ name = `${name.slice(0, PROJECT_DIR_MAX)}-${Math.abs(hash).toString(36)}`;+ }+ return join(configDir, "projects", name, `${sessionId}.jsonl`);}-type ImageSlot = { container: unknown[]; index: number };+/** The transcript under the working directory as given, or as resolved when it is reached through a link. */+function findTranscript(options: TranscriptOptions): { file: string; stat: Stats } | undefined {+ const dirs = [options.cwd];+ try {+ const real = realpathSync(options.cwd);+ if (real !== options.cwd) dirs.push(real);+ } catch { /* a working directory that is gone: only the name given */ }+ for (const dir of dirs) {+ const file = transcriptPath(options.configDir, dir, options.sessionId);+ try {+ return { file, stat: statSync(file) };+ } catch { /* not under this name */ }+ }+ return undefined;+}++const stampOf = (stat: Stats) => `${stat.size}:${stat.mtimeMs}`;++/** Images in one version of a transcript, counted once per version; rows that never say "image" are not parsed. */+function imagesIn(file: string, stat: Stats): number {+ const stamp = stampOf(stat), seen = counted.get(file);+ if (seen?.stamp === stamp) return seen.total;+ let 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;+}++/** How many past images a request can keep beside the `incoming` new ones. */+export const imagesToKeep = (incoming = 0) => Math.max(0, Math.min(CLAUDE_IMAGE_KEEP, CLAUDE_IMAGE_LIMIT - incoming));/** 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;+ * already holds everything it will resend. False when there is no transcript, and when it cannot be read: the warm+ * process then keeps the turn, as it did before this check. */+export function transcriptImagesOver(options: TranscriptOptions, incoming = 0): boolean {try {- stat = statSync(file);+ const found = findTranscript(options);+ return !!found && imagesIn(found.file, found.stat) + incoming > CLAUDE_IMAGE_LIMIT;} 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;}+type ImageSlot = { container: unknown[]; index: number };+function imageSlots(row: unknown): ImageSlot[] {const slots: ImageSlot[] = [];const walk = (value: unknown, depth: number) => {@@ -78,10 +112,16 @@ function imageSlots(row: unknown): ImageSlot[] {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]` });+const note = (n: number, keep: number) => ({ type: "text", text: `[Earlier image ${n} omitted: a request carries at most ${CLAUDE_IMAGE_LIMIT} images, so only the newest ${keep} are kept]` });++interface FoldOptions extends TranscriptOptions {+ /** Images the turn itself adds: the transcript keeps only what fits beside them. */+ incoming?: number;+}-/** 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. */+/** Keep the newest images of one transcript that fit beside the turn's own, 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);@@ -90,31 +130,16 @@ export function foldTranscriptImages(options: FoldOptions): FoldResult {}}-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 keep = imagesToKeep(options.incoming);+ const found = findTranscript(options);+ if (!found) return { total: 0, folded: 0, skipped: "missing" };+ const { file, stat } = found;+ const total = imagesIn(file, stat);+ if (total <= keep) return { total, folded: 0 };- const lines = readFileSync(file, "utf8").split("\n");- const parsed: Array<{ line: string; row?: unknown }> = lines.map((line) => {- if (!line.trim()) return { line };+ const parsed: Array<{ line: string; row?: unknown }> = readFileSync(file, "utf8").split("\n").map((line) => {+ if (!line.includes('"image"')) return { line };try {return { line, row: JSON.parse(line) as unknown };} catch {@@ -123,18 +148,14 @@ function fold(options: FoldOptions): FoldResult {});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 folded = Math.max(0, slots.length - keep);+ if (!folded) return { total: slots.length, folded: 0 };+ slots.slice(0, folded).forEach((slot, index) => { slot.container[slot.index] = note(index + 1, keep); });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 };+ counted.set(file, { stamp: stampOf(statSync(file)), total: slots.length - folded });+ return { total: slots.length, folded };}diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.tsindex c249f19e3a..4b1da56115 100644--- a/server/drivers/claude.test.ts+++ b/server/drivers/claude.test.ts@@ -3,7 +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 { CLAUDE_IMAGE_LIMIT, transcriptPath } from "./claude-transcript-images.ts";import { fileURLToPath } from "node:url";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -3825,14 +3825,18 @@ describe("ClaudeDriver turns (fake CLI)", () => {// 19 held + none new: still the warm processconst 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 });+ // 16 held + 5 new: over, so a fresh process resumes a transcript that leaves room for this turn's own+ writeFileSync(file, Array.from({ length: 16 }, (_, i) => row(i)).join("\n") + "\n");+ const imagePath = join(scratch, "page.png");+ writeFileSync(imagePath, Buffer.from([0x89, 0x50, 0x4e, 0x47]));+ const images = Array.from({ length: 5 }, () => ({ path: imagePath, mime: "image/png", bytes: 4 }));+ const third = await instance.adapter.sendTurn({ threadId: "t-images", text: "three", images, 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);+ expect(kept.split('"type":"image"').length - 1).toBe(CLAUDE_IMAGE_LIMIT - 5);}, 20_000);it("names the changed contract fields when a warm process is replaced", async () => {diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex a2503114d2..a7ddf01326 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -1333,8 +1333,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {if (authSettingsPath) {writeFileSync(authSettingsPath, JSON.stringify(settings), { mode: 0o600 });}- // 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); }+ // A resumed thread resends every image of its past turns: older ones become a note, leaving room for this turn's own.+ if (sessionId) { foldTranscriptImages({ ...transcript, sessionId, incoming: turn.images?.length ?? 0 }); args.push("--resume", sessionId); }else args.push("--session-id", newSessionId!);} catch (error) {cleanupUnownedLaunch();