Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(claude): fold old images only on a custom Anthropic-compatible endpoint, and keep a backup

milind-sonifebb10046ef9
diff --git a/server/drivers/claude-transcript-images.test.ts b/server/drivers/claude-transcript-images.test.ts
index f3061861d9..7de6cac8ca 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, realpathSync, statSync, symlinkSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, statSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, dirname, join } from "node:path";
import { test } from "vitest";
-import { CLAUDE_IMAGE_KEEP, CLAUDE_IMAGE_LIMIT, foldTranscriptImages, imagesToKeep, transcriptImagesOver, transcriptPath } from "./claude-transcript-images.ts";
+import { CLAUDE_IMAGE_KEEP, CLAUDE_IMAGE_LIMIT, FOLD_BACKUP_SUFFIX, foldTranscriptImages, imageFoldTarget, 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}` });
@@ -138,7 +138,61 @@ test("the transcript is found where Claude Code writes it: a linked working dire
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
+ mkdirSync(transcriptPath(options.configDir, options.cwd, "dir")); // something there, but not a file
assert.equal(transcriptImagesOver(unreadable, 25), false);
- assert.equal(foldTranscriptImages(unreadable).skipped, "unreadable");
+ assert.equal(foldTranscriptImages(unreadable).skipped, "missing");
+});
+
+test("only a custom Anthropic-compatible endpoint is folded: never first-party Anthropic, Bedrock, company access or a Claude account", () => {
+ const endpoint = { endpointModels: ["deepseek-chat"], configDir: "/data/providers/claude-1" };
+ const env = { ANTHROPIC_BASE_URL: "https://api.deepseek.com/anthropic", CLAUDE_CONFIG_DIR: "/data/providers/claude-1" };
+ assert.deepEqual(imageFoldTarget(endpoint, env, "/work"), { configDir: "/data/providers/claude-1", cwd: "/work" });
+ // an endpoint entry pointed at Anthropic itself, in any spelling
+ for (const url of ["https://api.anthropic.com", "https://API.Anthropic.com/", "https://api.anthropic.com./v1", "https://anthropic.com"]) {
+ assert.equal(imageFoldTarget(endpoint, { ...env, ANTHROPIC_BASE_URL: url }, "/work"), undefined, url);
+ }
+ assert.equal(imageFoldTarget(endpoint, { ...env, ANTHROPIC_BASE_URL: undefined }, "/work"), undefined);
+ assert.equal(imageFoldTarget(endpoint, { ...env, ANTHROPIC_BASE_URL: "not a url" }, "/work"), undefined);
+ assert.equal(imageFoldTarget({ ...endpoint, bedrock: true }, env, "/work"), undefined);
+ assert.equal(imageFoldTarget({ ...endpoint, managed: true }, env, "/work"), undefined);
+ // a Claude account with its own folder, or the default Claude, even with a base URL in its environment
+ assert.equal(imageFoldTarget({ configDir: "/data/providers/claude-1" }, env, "/work"), undefined);
+ assert.equal(imageFoldTarget({}, env, "/work"), undefined);
+ assert.equal(imageFoldTarget(endpoint, { ...env, CLAUDE_CONFIG_DIR: undefined }, "/work"), undefined);
+});
+
+test("a fold keeps the transcript as it was beside it, rewrites only the rows that lost an image, and leaves no temp file", () => {
+ // the CLI's own spacing and key order, which a rewrite of every row would lose
+ const plain = (n: number) => `{"type":"assistant", "message":{"content":[{"type":"text","text":"answer ${n}"}]}}`;
+ const rows = Array.from({ length: 21 }, (_, i) => [userRow([image(i)], i), plain(i)]).flat();
+ const { file, ...options } = setup(rows);
+ const before = readFileSync(file, "utf8");
+ assert.equal(foldTranscriptImages(options).folded, 21 - CLAUDE_IMAGE_KEEP);
+ assert.equal(readFileSync(`${file}${FOLD_BACKUP_SUFFIX}`, "utf8"), before);
+ assert.ok(!`${file}${FOLD_BACKUP_SUFFIX}`.endsWith(".jsonl"));
+ const after = readFileSync(file, "utf8").split("\n"), was = before.split("\n");
+ assert.equal(after.length, was.length);
+ const differ = after.flatMap((line, index) => (line === was[index] ? [] : [index]));
+ // only the first five user rows (even lines) changed; every assistant row is byte for byte the same
+ assert.deepEqual(differ, [0, 2, 4, 6, 8]);
+ assert.deepEqual(readdirSync(dirname(file)).sort(), [`${options.sessionId}.jsonl`, `${options.sessionId}.jsonl${FOLD_BACKUP_SUFFIX}`].sort());
+ assert.equal(statSync(file).mode, statSync(`${file}${FOLD_BACKUP_SUFFIX}`).mode);
+});
+
+test("counts only the images a request sends: the copy the CLI keeps beside a tool result is neither counted nor changed", () => {
+ const mirrored = (n: number) => JSON.stringify({ type: "user", message: { role: "user", content: [{ type: "tool_result", tool_use_id: `t${n}`, content: [image(n)] }] }, toolUseResult: [image(n)] });
+ const at = setup(Array.from({ length: CLAUDE_IMAGE_LIMIT }, (_, i) => mirrored(i)));
+ assert.equal(transcriptImagesOver(at), false);
+ const over = setup(Array.from({ length: CLAUDE_IMAGE_LIMIT + 1 }, (_, i) => mirrored(i)));
+ assert.equal(foldTranscriptImages(over).folded, CLAUDE_IMAGE_LIMIT + 1 - CLAUDE_IMAGE_KEEP);
+ const first = JSON.parse(readFileSync(over.file, "utf8").split("\n")[0]!);
+ assert.match(first.message.content[0].content[0].text, /Earlier image/);
+ assert.equal(first.toolUseResult[0].type, "image");
+});
+
+test("a session id that is not one is never looked up", () => {
+ const { configDir, cwd } = setup(Array.from({ length: 25 }, (_, i) => userRow([image(i)], i)));
+ assert.equal(foldTranscriptImages({ configDir, cwd, sessionId: "../s1" }).skipped, "missing");
+ assert.equal(transcriptImagesOver({ configDir, cwd, sessionId: "../s1" }, 25), false);
+ assert.ok(!existsSync(join(configDir, "projects", `s1.jsonl${FOLD_BACKUP_SUFFIX}`)));
});
diff --git a/server/drivers/claude-transcript-images.ts b/server/drivers/claude-transcript-images.ts
index bf65c57f99..00bbeb00ec 100644
--- a/server/drivers/claude-transcript-images.ts
+++ b/server/drivers/claude-transcript-images.ts
@@ -1,14 +1,21 @@
-// 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
+// Some 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 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
+// Only for a custom Anthropic-compatible endpoint (imageFoldTarget): first-party Anthropic takes far more images per
+// request, so its threads keep every image and its warm processes are reused as before. For such an endpoint, 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";
+//
+// The rewrite is careful: the file as it was is first copied beside it (`<session>.jsonl.before-image-fold`, which the
+// CLI never reads as a session), only the rows that held a folded image are written anew, the new file is synced and
+// renamed over the old one, and nothing is replaced when the transcript changed while it was being read.
+import { randomUUID } from "node:crypto";
+import { closeSync, fsyncSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync, type Stats } from "node:fs";
import { dirname, join } from "node:path";
/** What one request may carry (the endpoints' own limit). */
@@ -17,14 +24,16 @@ export const CLAUDE_IMAGE_LIMIT = 20;
export const CLAUDE_IMAGE_KEEP = 16;
/** 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;
+/** The copy of a transcript as it was before its latest fold. */
+export const FOLD_BACKUP_SUFFIX = ".before-image-fold";
const counted = new Map<string, { stamp: string; total: number }>();
export interface FoldResult {
total: number;
folded: number;
- /** Why nothing was read, when nothing was. */
- skipped?: "missing" | "unreadable";
+ /** Why nothing was read or replaced, when nothing was. */
+ skipped?: "missing" | "unreadable" | "changed";
}
interface TranscriptOptions {
@@ -33,6 +42,30 @@ interface TranscriptOptions {
sessionId: string;
}
+/** Whether a base URL points at a host other than Anthropic's own. */
+function customHost(url: string | undefined): boolean {
+ if (!url?.trim()) return false;
+ try {
+ const host = new URL(url.trim()).hostname.toLowerCase().replace(/\.$/u, "");
+ return host !== "anthropic.com" && !host.endsWith(".anthropic.com");
+ } catch {
+ return false;
+ }
+}
+
+/** Where to fold images, or undefined to leave the thread alone: only a custom endpoint instance (Settings > Custom
+ * endpoint: not Bedrock, not company model access, not a Claude account) pointed at a host that isn't Anthropic's,
+ * whose transcripts live in that endpoint's own config folder. */
+export function imageFoldTarget(
+ config: { endpointModels?: unknown; bedrock?: boolean; managed?: boolean; configDir?: string },
+ env: { ANTHROPIC_BASE_URL?: string; CLAUDE_CONFIG_DIR?: string },
+ cwd: string,
+): { configDir: string; cwd: string } | undefined {
+ if (!Array.isArray(config.endpointModels) || config.bedrock === true || config.managed === true || !config.configDir) return undefined;
+ const configDir = env.CLAUDE_CONFIG_DIR?.trim();
+ return configDir && customHost(env.ANTHROPIC_BASE_URL) ? { configDir, cwd } : undefined;
+}
+
/** Where Claude Code keeps one session's transcript, as its own code names it: the resolved working directory with
* everything but letters and digits turned into '-', cut at 200 characters plus a base-36 hash of the resolved path
* when longer (checked against the installed CLI: the hash runs over the path as resolved, not as given). */
@@ -56,9 +89,11 @@ const folderHash = (path: string) => {
/** The transcript for one session: the folder the CLI names after the resolved working directory. */
function findTranscript(options: TranscriptOptions): { file: string; stat: Stats } | undefined {
+ if (!/^[A-Za-z0-9-]+$/u.test(options.sessionId)) return undefined;
const file = transcriptPath(options.configDir, options.cwd, options.sessionId);
try {
- return { file, stat: statSync(file) };
+ const stat = statSync(file);
+ return stat.isFile() ? { file, stat } : undefined;
} catch { /* no transcript under the resolved name, or the name as given when the directory is gone */ }
return undefined;
}
@@ -97,6 +132,7 @@ export function transcriptImagesOver(options: TranscriptOptions, incoming = 0):
type ImageSlot = { container: unknown[]; index: number };
+/** The image blocks a row sends: only its `message.content`, never the copies the CLI keeps beside it for itself. */
function imageSlots(row: unknown): ImageSlot[] {
const slots: ImageSlot[] = [];
const walk = (value: unknown, depth: number) => {
@@ -110,7 +146,8 @@ function imageSlots(row: unknown): ImageSlot[] {
}
for (const entry of Object.values(value as Record<string, unknown>)) walk(entry, depth + 1);
};
- walk(row, 0);
+ const content = (row as { message?: { content?: unknown } } | null)?.message?.content;
+ if (Array.isArray(content)) walk(content, 0);
return slots;
}
@@ -122,8 +159,8 @@ interface FoldOptions extends TranscriptOptions {
}
/** 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. */
+ * Returns what it found; never throws: an unreadable transcript must not cost the turn, and a failed rewrite leaves the
+ * transcript as it was. */
export function foldTranscriptImages(options: FoldOptions): FoldResult {
try {
return fold(options);
@@ -132,6 +169,22 @@ export function foldTranscriptImages(options: FoldOptions): FoldResult {
}
}
+/** Writes `text` to a new file beside `file`, synced to disk, and returns its path. */
+function writeBeside(file: string, text: string, mode: number): string {
+ const temp = join(dirname(file), `.${randomUUID()}.image-fold.tmp`);
+ const fd = openSync(temp, "wx", mode & 0o777);
+ try {
+ writeFileSync(fd, text);
+ fsyncSync(fd);
+ } catch (error) {
+ closeSync(fd);
+ try { unlinkSync(temp); } catch { /* already gone */ }
+ throw error;
+ }
+ closeSync(fd);
+ return temp;
+}
+
function fold(options: FoldOptions): FoldResult {
const keep = imagesToKeep(options.incoming);
const found = findTranscript(options);
@@ -140,24 +193,39 @@ function fold(options: FoldOptions): FoldResult {
const total = imagesIn(file, stat);
if (total <= keep) return { total, folded: 0 };
- const parsed: Array<{ line: string; row?: unknown }> = readFileSync(file, "utf8").split("\n").map((line) => {
- if (!line.includes('"image"')) return { line };
+ const original = readFileSync(file, "utf8");
+ const parsed: Array<{ line: string; row?: unknown; slots: ImageSlot[] }> = original.split("\n").map((line) => {
+ if (!line.includes('"image"')) return { line, slots: [] };
try {
- return { line, row: JSON.parse(line) as unknown };
+ const row = JSON.parse(line) as unknown;
+ return { line, row, slots: imageSlots(row) };
} catch {
- return { line }; // a half-written last line, or a format this code does not know: left as it was
+ return { line, slots: [] }; // 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));
+ const slots = parsed.flatMap((entry) => entry.slots);
const folded = Math.max(0, slots.length - keep);
if (!folded) return { total: slots.length, folded: 0 };
+ const changed = new Set(slots.slice(0, folded));
slots.slice(0, folded).forEach((slot, index) => { slot.container[slot.index] = note(index + 1, keep); });
+ // Only a row that lost an image is written anew; every other line stays byte for byte as the CLI wrote it.
+ const out = parsed.map((entry) => (entry.slots.some((slot) => changed.has(slot)) ? JSON.stringify(entry.row) : entry.line)).join("\n");
- 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 temp = writeBeside(file, out, stat.mode);
+ try {
+ const backup = writeBeside(file, original, stat.mode);
+ renameSync(backup, `${file}${FOLD_BACKUP_SUFFIX}`);
+ // The CLI may have written while this ran: then nothing is replaced, and the next resume looks again.
+ const now = statSync(file);
+ if (now.size !== Buffer.byteLength(original) || stampOf(now) !== stampOf(stat)) {
+ unlinkSync(temp);
+ return { total: slots.length, folded: 0, skipped: "changed" };
+ }
+ renameSync(temp, file);
+ } catch (error) {
+ try { unlinkSync(temp); } catch { /* renamed, or already gone */ }
+ throw error;
+ }
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.ts
index 4955569168..e5beea541b 100644
--- a/server/drivers/claude.test.ts
+++ b/server/drivers/claude.test.ts
@@ -3,7 +3,7 @@ import { createServer as createHttpServer, type IncomingHttpHeaders } from "node
import { 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_LIMIT, transcriptPath } from "./claude-transcript-images.ts";
+import { CLAUDE_IMAGE_LIMIT, FOLD_BACKUP_SUFFIX, transcriptPath } from "./claude-transcript-images.ts";
import { fileURLToPath } from "node:url";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -3870,12 +3870,15 @@ 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 () => {
+ /** A thread whose transcript gains a page image every turn, on a custom endpoint or first-party Anthropic. */
+ const imageThread = async (endpoint: boolean) => {
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 create(undefined, endpoint ? { ANTHROPIC_BASE_URL: "https://endpoint.example.test", ANTHROPIC_API_KEY: "endpoint-token", ANTHROPIC_AUTH_TOKEN: "endpoint-token" } : {},
+ endpoint ? { configDir, requireApiKey: true, endpointModels: ["deepseek-chat"] } : { configDir });
+ const threadId = `t-images-${endpoint ? "endpoint" : "anthropic"}`;
+ await instance.adapter.sendTurn({ threadId, 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
@@ -3883,22 +3886,44 @@ describe("ClaudeDriver turns (fake CLI)", () => {
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);
- // 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 write = (count: number) => writeFileSync(file, Array.from({ length: count }, (_, 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)
+ const turn = async (text: string, images = 0) => {
+ const sent = await instance.adapter.sendTurn({ threadId, text, cwd, resumeCursor: announced,
+ ...(images ? { images: Array.from({ length: images }, () => ({ path: imagePath, mime: "image/png", bytes: 4 })) } : {}) });
+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === sent.turnId);
+ };
+ const closes = () => readFileSync(join(NATIVE_DIR, `${threadId}.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");
+ return { file, write, turn, closes };
+ };
+
+ it("on a custom endpoint, does not reuse a warm process whose next request would carry more than 20 images: a fresh one resumes the folded transcript", async () => {
+ const t = await imageThread(true);
+ t.write(19);
+ // 19 held + none new: still the warm process
+ await t.turn("two");
+ expect(t.closes()).toEqual([]);
+ // 16 held + 5 new: over, so a fresh process resumes a transcript that leaves room for this turn's own
+ t.write(16);
+ const before = readFileSync(t.file, "utf8");
+ await t.turn("three", 5);
+ expect(t.closes()).toEqual(["images over the request limit"]);
+ const kept = readFileSync(t.file, "utf8");
expect(kept.split('"type":"image"').length - 1).toBe(CLAUDE_IMAGE_LIMIT - 5);
+ // the transcript as it was stays beside it
+ expect(readFileSync(`${t.file}${FOLD_BACKUP_SUFFIX}`, "utf8")).toBe(before);
+ }, 20_000);
+
+ it("on first-party Anthropic, keeps every image and the warm process, and never touches the transcript", async () => {
+ const t = await imageThread(false);
+ t.write(25);
+ const before = readFileSync(t.file);
+ await t.turn("two", 5);
+ expect(t.closes()).toEqual([]);
+ expect(readFileSync(t.file).equals(before)).toBe(true);
+ expect(existsSync(`${t.file}${FOLD_BACKUP_SUFFIX}`)).toBe(false);
}, 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.ts
index a733401724..0ef193231c 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -61,7 +61,7 @@ import type { KeepWarmContract } from "./claude-keepwarm.ts"; import { claudeFor
import { BACKGROUND_CALL_TIMEOUT_MS, backgroundCallArgs, spawnBackgroundCall } from "./claude-background.ts"; import { withEndpointFolder } from "./claude-endpoint-folder.ts";
import { 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 { extractMcpImages } from "../mcp-tool-images.ts"; import { claudeToolDraft } from "./tool-progress.ts"; import { redactSecretsInText } from "../../shared/redact.ts"; import { foldTranscriptImages, imageFoldTarget, transcriptImagesOver } from "./claude-transcript-images.ts";
import {
ASK_USER_QUESTION_TOOL,
ASK_USER_TOOL,
@@ -1160,7 +1160,7 @@ 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), transcript = { configDir: env.CLAUDE_CONFIG_DIR?.trim() || resolveClaudeConfigDir(undefined, env), cwd }, imagesOver = !turn.sessionReset && !!sessionId && live?.sessionId === sessionId && !live.turn && transcriptImagesOver({ ...transcript, sessionId }, turn.images?.length ?? 0);
+ const live = sessions.get(threadId), transcript = imageFoldTarget(config, env, cwd), imagesOver = !!transcript && !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 idle
if (live.spare) { live.spare = false; live.take?.(turnId); appendNative(threadId, { dir: "out", source: "claude.session", msg: { took: "prestarted" } }); }
@@ -1277,7 +1277,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (authSettingsPath) {
writeFileSync(authSettingsPath, JSON.stringify(settings), { mode: 0o600 });
}
- if (sessionId) { foldTranscriptImages({ ...transcript, sessionId, incoming: turn.images?.length ?? 0 }); args.push("--resume", sessionId); } // a resumed thread resends every past image: older ones become a note, leaving room for this turn's own
+ if (sessionId) { if (transcript) foldTranscriptImages({ ...transcript, sessionId, incoming: turn.images?.length ?? 0 }); args.push("--resume", sessionId); } // on a custom endpoint a resumed thread resends every past image: older ones become a note, leaving room for this turn's own
else args.push("--session-id", newSessionId!);
} catch (error) {
cleanupUnownedLaunch();