Skip to content

A local plugin for image-heavy chats in Codex, Claude Code and other agents: earlier images stop going out with every message, and the model fetches the one it needs by its ID, also after compaction.

refactor(engine): split the engine's platform parts out of proxy.ts

chipfighter14f720272241
diff --git a/docs/design.md b/docs/design.md
index 6b9ad2b..aa23f4f 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -20,9 +20,9 @@ v0.11 起代码分成三层([v0.11/plan.md](v0.11/plan.md)):`core/` 是不
| 部分 | 代码(`plugin/src`) | 作用 |
|---|---|---|
-| 引擎 | `proxy.ts`、`engine.ts`、`core/routes.ts` | 本机代理:按绑定线路转发、改写请求、记录每个任务最近一次请求的统计;全机只有一个 |
+| 引擎 | `proxy.ts`(入口)、`core/engine/transport.ts`、`adapters/codex/engine.ts`、`adapters/claude/engine.ts`、`engine.ts`、`core/routes.ts` | 本机代理:按绑定线路转发、改写请求、记录每个任务最近一次请求的统计;全机只有一个 |
| 插件服务 | `plugin-server.ts` | Codex 为每个会话启动的 MCP 服务:拉起并看守引擎,给面板提供数据;v0.3 起还给模型提供取图工具 |
-| 面板 | `panel/panel.html`、`panel/panel-state.ts` | 侧边面板里的 MCP 应用,以及它要显示的数据 |
+| 面板 | `panel/panel.html`、`panel/page.ts`、`panel/panel-state.ts` | 侧边面板里的 MCP 应用,以及它要显示的数据 |
| 任务索引 | `adapters/codex/thread-index.ts`、`adapters/protocols/openai-responses/images.ts`、`core/images.ts`、`core/thumbnail.ts`、`core/png.ts`、`adapters/codex/thread-names.ts` | 从 Codex 的任务记录里只读地找出图片和它的来源、编号、生成缩略图、读任务名 |
| 改写 | `core/plan.ts`、`core/words.ts`、`adapters/protocols/openai-responses/rewrite.ts`、`selection.ts`、`core/request-stats.ts`、`core/notes.ts` | 每张图发不发、换成什么字(两个平台共用);发给模型的全部文字;把决定落进 Responses 请求;勾选状态;请求统计;特征行 |
| 接入和安装 | `adapters/codex/`:`codexconfig.ts`、`setup.ts`、`install.ts`、`codexcli.ts`、`plugin-cache.ts`、`binding.ts`;`cam.ts` | 管理 Codex 配置里带标记的块;用 Codex 的命令行装卸插件;保护升级中的旧运行文件;新任务绑定;`cam` 命令行 |
@@ -30,7 +30,7 @@ v0.11 起代码分成三层([v0.11/plan.md](v0.11/plan.md)):`core/` 是不
| Claude 接入(v0.4) | `hooks/register.js`(Mod,不在 `plugin/src`) | 把会话的请求地址指向引擎;`/cam` 打开面板(v0.6 起有图时自动打开);取图工具免确认 |
| Claude 会话索引和改写(v0.4) | `adapters/claude/claude-index.ts`、`adapters/claude/claude-rewrite.ts`、`adapters/protocols/anthropic-messages/rewrite.ts` | 从 Claude Code 的会话记录找图、编号,把请求里的图对上记录;把决定落进 Anthropic Messages 请求 |
| Claude 思考记录和提示缓存(v0.4、v0.10) | `adapters/protocols/anthropic-messages/thinking.ts`、`adapters/protocols/anthropic-messages/cache.ts` | 账号校验思考记录时,去掉和实际发出的历史对不上的思考;改过历史后,让提示缓存仍能读到 |
-| 面板页(v0.4) | `panel/panel-web.js`、`panel/panel-language.ts` | 引擎把 `panel.html` 作为网页提供时,代替 MCP 应用的宿主 |
+| 面板页(v0.4) | `panel/panel-web.js`、`panel/panel-language.ts`、`adapters/claude/panel-web.ts` | 引擎把 `panel.html` 作为网页提供时,代替 MCP 应用的宿主 |
引擎和插件服务之间只通过数据目录里的文件共享状态,任何一方不在,另一方都照常工作。
diff --git a/plugin/src/adapters/claude/engine.ts b/plugin/src/adapters/claude/engine.ts
new file mode 100644
index 0000000..d061e1a
--- /dev/null
+++ b/plugin/src/adapters/claude/engine.ts
@@ -0,0 +1,192 @@
+// Purpose: the engine's part for Claude Code (v0.11: split from proxy.ts, docs/v0.11/plan.md): which session a request
+// belongs to (Claude Code's own headers), whether its requests are rewritten, and the rewrite of an Anthropic Messages
+// body with the session's transcript and selection: what to send, and what next when Anthropic refuses the thinking
+// after the changed history.
+// v0.4: Claude Code. v0.5: images put back after a compaction. v0.8: feature lines. v0.10: cache marks, late images.
+// Input: request headers and bodies, the session's transcript and selection. Output: attempts to send and a report.
+
+import type { IncomingHttpHeaders } from "node:http";
+import { decodeBody, encodeBody, hasUnsafeInteger } from "../../core/engine/transport.ts";
+import { claudeSelectionDirOf } from "../../core/paths.ts";
+import { currentLang } from "../../language.ts";
+import { claudeSelection, stableIdsSince } from "../../selection.ts";
+import { awaitingLine, pixelHashOfData } from "../codex/thread-index.ts";
+import { keepCacheRead, marksOutside, sentPrefixOf, type SentPrefix } from "../protocols/anthropic-messages/cache.ts";
+import { addCompacted, summaryAt, type RequestImage, type Resend } from "../protocols/anthropic-messages/rewrite.ts";
+import { chainOf, fitThinking, type ThinkingRecord } from "../protocols/anthropic-messages/thinking.ts";
+import { claudeHome, claudeImageData, claudeStartedAt, loadClaudeIndex, type ClaudeIndex } from "./claude-index.ts";
+import { findRequestImages, rewriteMessages } from "./claude-rewrite.ts";
+
+type Json = Record<string, any>;
+// v0.4: Claude Code's API host.
+export const CLAUDE_HOST = "api.anthropic.com";
+
+// v0.4: which Claude Code session a request belongs to, and whether a subagent's loop sent it (its own conversation).
+export function claudeIdentity(headers: IncomingHttpHeaders): { sessionId: string | null; agentId: string | null } {
+ const one = (value: string | string[] | undefined) => (Array.isArray(value) ? value[0] : value) || null;
+ return { sessionId: one(headers["x-claude-code-session-id"]), agentId: one(headers["x-claude-code-agent-id"]) };
+}
+
+// v0.4: the requests the panel's "last request" line is about: the session's conversation as the model works on it,
+// Claude Code's main loop, which always carries its tools. Claude Desktop also sends side requests in the session (a
+// status summary while the user is away, auto mode's safety check): no tools and none of the conversation's images.
+// They are rewritten like the rest; only the line leaves them out (2026-10-10: it said "nothing replaced" after a turn
+// whose four images had all been left out).
+export const claudeConversationRequest = (details: Json): boolean => details.kind === "messages" && details.tools > 0;
+
+// v0.4: a Claude Code session's requests are rewritten once something is unchecked there, or automatic selection was
+// used (copies the model fetched may be in its history from then on). v0.5: or once it was compacted with images
+// before the compaction, which the user may keep sending. v0.8: or once it has any image, for the feature line note
+// and the ids (Claude Code sends the whole history every time, so this costs no upload; docs/v0.8/plan.md).
+export function claudeNeedsRewrite(sessionId: string | null, dir = claudeSelectionDirOf(), home = claudeHome()): boolean {
+ if (!sessionId) return false;
+ let index: ClaudeIndex | null = null;
+ try { index = loadClaudeIndex(sessionId, home, stableIdsSince(dir)); } catch { /* the selection still decides */ }
+ try {
+ const selection = claudeSelection(sessionId, dir, index ? claudeStartedAt(index) : null, index?.previous ?? []);
+ if (Object.keys(selection.unchecked).length > 0 || selection.autoSince) return true;
+ } catch { /* the transcript still decides */ }
+ return !!index?.images.length;
+}
+
+// The images a Claude Code request carried, by index key, with the base64 characters each took (the panel's
+// baseline); images not in the transcript yet are left out.
+export function claudeImageSizes(messages: Json[], index: ClaudeIndex): Record<string, number> {
+ return Object.fromEntries(findRequestImages(messages, index).filter((ref) => ref.key).map((ref) => [ref.key!, ref.base64Chars]));
+}
+
+// Anthropic refuses a request whose earlier content changed under the thinking that followed it (accounts created from
+// 2026-08-31, or a request that asks for it): docs/v0.4/plan.md §2.2. The engine then sends the original instead.
+export function thinkingRejected(status: number, body: string): boolean {
+ return status === 400 && /thinking/i.test(body) && /signature|bound to a different conversation|prefix/i.test(body);
+}
+
+// v0.4: what to send for a Claude Code request, each next one when Anthropic refuses the thinking after the changed
+// history (thinkingRejected): the rewrite with all its thinking (an account that lets it through); the rewrite without
+// the thinking that no longer fits (anthropic-messages/thinking.ts), first once the account is known to refuse it; the rewrite
+// without any thinking, always accepted; the original as Claude Code built it. history/sent: the chains to remember
+// once the attempt goes through (null: not the session's conversation); made: the histories its thinking was made
+// after; sure: the record says all its thinking fits, so a refusal means the record misses what went out.
+// prefix: where its cache marks are, to remember once it is sent (anthropic-messages/cache.ts).
+export type ClaudeAttempt = { body: Buffer; report: Json; history: string | null; sent: string | null; made: string[]; sure: boolean; prefix?: SentPrefix };
+// v0.10: how long a request waits for its newest images to reach the transcript (a long-task eval caught 3 of a turn's
+// images going out without ids, the transcript written a moment after the request; the user's logs had 119 such of
+// 8904 requests). A request whose images never reach it waits the whole time once.
+export const LATE_WAIT_MS = 1500;
+export const LATE_STEP_MS = 100;
+
+// v0.4: the same rules as rewriteBody, for a Claude Code request (Anthropic Messages, anthropic-messages/rewrite.ts). The current
+// turn is the transcript's latest prompt: Claude Code writes it before it sends the request.
+// CAM_EXPERIMENT_BLOCK_BINDING (experiments only, docs/v0.4/tasks.md T04-01): asks Anthropic to check thinking with
+// that prefix_mismatch_behavior, as for an account created from 2026-08-31; the report names the beta header to add.
+export function rewriteClaudeBody(original: Buffer, encoding: string | undefined, sessionId: string, dir = claudeSelectionDirOf(), home = claudeHome(), env = process.env, thinking: ThinkingRecord | null = null, previous: SentPrefix[] = []): { body: Buffer; report: Json; attempts: ClaudeAttempt[]; prefix?: SentPrefix } {
+ const asIs = (report: Json) => ({ body: original, report, attempts: [] });
+ const decoded = decodeBody(original, encoding);
+ if (!decoded) return asIs({ skipped: "undecodable body" });
+ const text = decoded.toString("utf8");
+ let json: Json;
+ try { json = JSON.parse(text); } catch { return asIs({ skipped: "unparsable body" }); }
+ if (!Array.isArray(json.messages)) return asIs({ skipped: "no messages array" });
+ if (hasUnsafeInteger(text)) return asIs({ skipped: "integer beyond 2^53 would change when re-serialized" });
+ let index: ClaudeIndex;
+ try { index = loadClaudeIndex(sessionId, home, stableIdsSince(dir)); } catch (error) { return asIs({ skipped: `thread index: ${String(error)}` }); }
+ const selection = claudeSelection(sessionId, dir, claudeStartedAt(index), index.previous);
+ const current = index.turns;
+ const copies = new Map([...index.copies.values()].filter((copy) => copy.turn === null || copy.turn < current).map((copy) => [copy.key, copy.of]));
+ let leaveOut = new Set(Object.keys(selection.unchecked));
+ // v0.10: images of an interrupted turn without a feature line yet are sent once more (awaitingLine).
+ const awaiting = new Set(selection.auto ? index.images.filter((image) => awaitingLine(index, image, current)).map((image) => image.key) : []);
+ if (selection.auto) {
+ const pinned = selection.pinned ?? {};
+ leaveOut = new Set(index.images.filter((image) => image.replaceable && image.turn !== null && image.turn < current && !pinned[image.key] && !awaiting.has(image.key)).map((image) => image.key));
+ }
+ const pixels = (ref: RequestImage) => (ref.key ? index.byKey.get(ref.key)?.pixelSha256 : undefined) ?? pixelHashOfData(ref, ref.block.source.data);
+ const lang = currentLang();
+ // v0.5: after a compaction, the images from before it go back right after the summary (anthropic-messages/rewrite.ts): the ones
+ // the user keeps sending (checked, or pinned with automatic selection) read from the transcript, the others as
+ // placeholders. With any of those, the full note follows the summary, and later messages get only their short notes.
+ // v0.8: each with what the model noted about it, for its placeholder.
+ const compactedImages = index.images.filter((image) => image.compacted).map((image) => {
+ // v0.10: as they stood at the compaction, so the list stays the same until the next one (claude-index.ts).
+ const notes = index.compactedNotes.get(image.id);
+ return notes ? { ...image, notes } : image;
+ });
+ const summaryIn = index.summary && compactedImages.length ? summaryAt(json.messages, index.summary) : null;
+ const resend: Resend[] = summaryIn === null ? [] : compactedImages.filter((image) => !leaveOut.has(image.key)).flatMap((image) => {
+ const data = claudeImageData(index, image);
+ return data && image.mime ? [{ image, block: { type: "image", source: { type: "base64", media_type: image.mime, data } } }] : [];
+ });
+ const compactedOut = summaryIn !== null && resend.length < compactedImages.length;
+ // v0.8: feature lines in every main conversation (a subagent's requests do not come here).
+ const rewrote = rewriteMessages(json.messages, index, leaveOut, pixels, { lang, copies, noted: compactedOut, features: true, awaiting, ...(selection.auto ? { auto: { currentTurn: current } } : {}) });
+ const report = rewrote.report;
+ let messages = rewrote.messages;
+ let compacted: Json | null = null;
+ if (summaryIn !== null) {
+ const added = addCompacted(messages, index.summary!, compactedImages, resend, { lang, auto: !!selection.auto });
+ if (added.at !== null) {
+ messages = added.messages;
+ // The note's place: after the summary when it holds placeholders; a later one moves down with a message added.
+ if (compactedOut) report.noteAt = added.at + 1;
+ else if (added.inserted && report.noteAt !== undefined && report.noteAt > added.at) report.noteAt += 1;
+ if (added.inserted && report.featureAt !== undefined && report.featureAt > added.at) report.featureAt += 1;
+ compacted = { at: added.at, listed: compactedImages.length, resent: resend.map(({ image }) => image.id) };
+ }
+ }
+ const summary: Json = {
+ images: report.images,
+ replaced: report.replaced.map(({ key: _key, ...rest }) => rest),
+ locked: report.locked,
+ sentImageHashes: report.sentContentIds.map((id) => id.slice(0, 16)),
+ thinkingBlocks: json.messages.reduce((sum: number, message: Json) => sum + (Array.isArray(message?.content) ? message.content.filter((block: Json) => block?.type === "thinking" || block?.type === "redacted_thinking").length : 0), 0),
+ ...(report.noteAt !== undefined ? { noteAt: report.noteAt } : {}),
+ ...(selection.auto ? { auto: true } : {}),
+ ...(report.copies.length ? { copies: report.copies } : {}),
+ ...(compacted ? { compacted } : {}),
+ ...(report.featureAt !== undefined ? { featureAt: report.featureAt, labeled: report.labeled ?? 0 } : {}),
+ ...(report.unknown ? { unknown: report.unknown } : {}),
+ ...(report.late ? { late: report.late } : {}),
+ };
+ const changed = report.replaced.length > 0 || report.copies.length > 0 || compacted !== null || report.featureAt !== undefined;
+ // Once the engine has sent the session a changed history, thinking made after it may be in every later request, even
+ // with nothing left out now (an image checked again).
+ // Side requests (no tools: the desktop's status summary, auto mode's check) are not the conversation.
+ const conversation = Array.isArray(json.tools) && json.tools.length > 0;
+ if (!changed && !thinking?.edited) return { body: original, report: summary, attempts: [], ...(conversation ? { prefix: sentPrefixOf(json.messages) } : {}) };
+ const rewritten = changed ? messages : json.messages;
+ const fit = thinking ? fitThinking(json.messages, rewritten, thinking) : null;
+ const history = fit && conversation ? fit.history : null;
+ const experiment = env.CAM_EXPERIMENT_BLOCK_BINDING?.trim();
+ // v0.10: the cache marks placed so this request reads what the ones before wrote, and the next one can read this
+ // one after the images still sent as originals are left out (anthropic-messages/cache.ts): with automatic selection, the first
+ // such image that is not pinned.
+ const pinnedNow = selection.pinned ?? {};
+ const volatileIn = (list: Json[]) => {
+ const ref = selection.auto ? findRequestImages(list, index).find((found) => !(found.key && pinnedNow[found.key])) : undefined;
+ return ref ? { message: ref.msg, block: ref.part } : null;
+ };
+ const encode = (list: Json[], extra: Json) => {
+ const placed = conversation ? keepCacheRead(list, previous, marksOutside(json), volatileIn(list)) : { messages: list, marks: null };
+ const out: Json = { ...json, messages: placed.messages };
+ const asked = experiment && json.thinking && typeof json.thinking === "object";
+ if (asked) out.thinking = { ...json.thinking, block_binding: { prefix_mismatch_behavior: experiment } };
+ const next = Buffer.from(JSON.stringify(out), "utf8");
+ const body = encodeBody(next, encoding);
+ return { body, report: { ...summary, ...extra, ...(placed.marks ? { cacheMarks: placed.marks } : {}), ...(asked ? { experiment: { blockBinding: experiment, beta: "thinking-binding-controls-2026-08-01" } } : {}), decodedBefore: decoded.length, decodedAfter: next.length, encodedBefore: original.length, encodedAfter: body.length }, ...(conversation ? { prefix: sentPrefixOf(placed.messages) } : {}) };
+ };
+ const attempts: ClaudeAttempt[] = [];
+ const made = fit?.made ?? [];
+ const add = (list: Json[], extra: Json, sent: string, sure: boolean) => attempts.push({ ...encode(list, extra), history, sent: history ? sent : null, made, sure });
+ const asBuilt = (extra: Json, sure: boolean) => attempts.push({ body: original, report: { ...summary, ...extra }, history, sent: history, made, sure, ...(conversation ? { prefix: sentPrefixOf(json.messages) } : {}) });
+ if (!thinking?.strict) {
+ if (changed) add(rewritten, {}, chainOf(rewritten), fit?.left === 0);
+ else asBuilt({}, fit!.left === 0);
+ }
+ if (fit && (thinking!.strict || fit.left)) add(fit.messages, { thinking: { kept: fit.kept, left: fit.left }, ...(thinking!.strict ? {} : { retry: "thinking-signature" }) }, fit.sent, true);
+ if (fit?.kept) {
+ const bare = fitThinking(json.messages, rewritten, thinking!, false);
+ add(bare.messages, { thinking: { kept: 0, left: bare.left }, retry: "thinking-signature" }, bare.sent, false);
+ }
+ if (changed || thinking?.strict) asBuilt(changed ? { fallback: "thinking-signature" } : {}, false);
+ return { body: attempts[0].body, report: attempts[0].report, attempts };
+}
diff --git a/plugin/src/adapters/claude/panel-web.ts b/plugin/src/adapters/claude/panel-web.ts
new file mode 100644
index 0000000..6a04a4c
--- /dev/null
+++ b/plugin/src/adapters/claude/panel-web.ts
@@ -0,0 +1,49 @@
+// Purpose: v0.4 — the panel of a Claude Code session, served by the engine (v0.11: split from proxy.ts,
+// docs/v0.11/plan.md): the page (the Codex panel with panel-web.js standing in for its host) and its local API.
+// Input: requests to /__cam/panel and /__cam/claude/*. Output: the page, JSON answers.
+
+import type { IncomingHttpHeaders } from "node:http";
+import { ownRequest } from "../../core/engine/transport.ts";
+import { webPanelPage } from "../../panel/page.ts";
+import { claudePanelLanguage } from "../../panel/panel-language.ts";
+import { applyClaudeSelection, claudeImageFor, loadClaudePanelState, type ClaudePanelOptions } from "../../panel/panel-state.ts";
+
+type Json = Record<string, any>;
+
+// v0.4: a Claude Code session's panel reads and changes its images here: the panel page the engine serves
+// (/__cam/panel, panel.html with panel-web.js) and the Claude plugin's mod. The Codex panel goes through the plugin's
+// MCP server; under Claude Code that is not open to a panel (a mod reaches it only through Claude Code's tool
+// permissions, a prompt for every call, and Claude Code registers no app-only tool), so the engine, the one local HTTP
+// service, serves the panel. Loopback only, like everything the engine serves; only a request naming the engine by a
+// loopback name (no other site rebinding its name to 127.0.0.1), carrying our header, and coming from no other site's
+// page (a browser's Origin, when sent, is the engine's own).
+const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+
+// The panel page for a Claude Code session: the same panel.html as in Codex, with panel-web.js before its own script.
+export const claudePanelPage = () => webPanelPage();
+export const PANEL_PAGE_CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
+
+export function claudePanelApi(method: string, url: string, headers: IncomingHttpHeaders, body: string | null, options: ClaudePanelOptions & { panelLocaleFiles?: readonly string[] } = {}): { status: number; body: Json } {
+ if (!ownRequest(headers) || headers["x-cam-panel"] !== "1") return { status: 403, body: { error: "forbidden" } };
+ const parsed = new URL(url, "http://localhost");
+ const session = parsed.searchParams.get("session") ?? "";
+ if (!SESSION_ID.test(session)) return { status: 400, body: { error: "no session" } };
+ const lang = claudePanelLanguage({ settingsFiles: options.panelLocaleFiles });
+ try {
+ if (method === "GET" && parsed.pathname === "/__cam/claude/panel") return { status: 200, body: { ...loadClaudePanelState(session, options), lang } };
+ if (method === "GET" && parsed.pathname === "/__cam/claude/image") {
+ const max = Number(parsed.searchParams.get("max") ?? 160);
+ return { status: 200, body: claudeImageFor(session, String(parsed.searchParams.get("id") ?? ""), Number.isFinite(max) && max > 0 ? max : 160, options) };
+ }
+ if (method === "POST" && parsed.pathname === "/__cam/claude/select") {
+ if (body === null) return { status: 413, body: { error: "too large" } };
+ const change = JSON.parse(body || "{}");
+ const list = (value: unknown) => (Array.isArray(value) ? value.map(String) : undefined);
+ const state = applyClaudeSelection(session, { uncheck: list(change.uncheck), check: list(change.check), checkAll: change.checkAll === true, auto: typeof change.auto === "boolean" ? change.auto : undefined, mode: change.mode === "auto" ? "auto" : "manual" }, options);
+ return { status: 200, body: { ...state, lang } };
+ }
+ return { status: 404, body: { error: "not found" } };
+ } catch (error) {
+ return { status: 400, body: { error: error instanceof Error ? error.message : String(error) } };
+ }
+}
diff --git a/plugin/src/adapters/codex/engine.ts b/plugin/src/adapters/codex/engine.ts
new file mode 100644
index 0000000..50fc573
--- /dev/null
+++ b/plugin/src/adapters/codex/engine.ts
@@ -0,0 +1,142 @@
+// Purpose: the engine's part for Codex (v0.11: split from proxy.ts, docs/v0.11/plan.md): where its requests go, which
+// task and turn a request belongs to (Codex's own headers), whether the task's requests are rewritten (and so sent
+// over HTTP), and the rewrite of a Responses request body with the task's index and selection.
+// P2: requests of threads with unchecked images are rewritten. v0.3: automatic selection. v0.7: subagents and side
+// chats. v0.8: feature lines. v0.10: images put back after a compaction. 2026-10-22: Codex logged in with an API key
+// goes to api.openai.com/v1.
+// Input: request headers and bodies, the thread's rollout and selection. Output: the body to send and a report.
+
+import type { IncomingHttpHeaders } from "node:http";
+import { join } from "node:path";
+import { decodeBody, encodeBody, hasUnsafeInteger } from "../../core/engine/transport.ts";
+import type { Described } from "../../core/words.ts";
+import { currentLang } from "../../language.ts";
+import { effectiveSelection, selectionDir, sideChatSelection } from "../../selection.ts";
+import { findImages, type ImageRef } from "../protocols/openai-responses/images.ts";
+import { addCodexCompacted, rewriteItems } from "../protocols/openai-responses/rewrite.ts";
+import { codexHome } from "./codexconfig.ts";
+import { awaitingLine, imageData, loadThreadIndex, pixelHashOf, sideChatOrigin, writesNotes, type ThreadIndex } from "./thread-index.ts";
+
+type Json = Record<string, any>;
+export const UPSTREAM_HOST = "chatgpt.com";
+// Where Codex logged in with an API key sends its requests without the plugin (its base URL https://api.openai.com/v1).
+export const OPENAI_API_HOST = "api.openai.com";
+export const CODEX_BASE = "/backend-api/codex/";
+
+// Which task a request belongs to, from Codex's own turn metadata header.
+// v0.7: and where that task came from: a side chat (a fork Codex keeps in memory only) names the task it was forked
+// from, a subagent its parent (also in Codex's own header).
+export type RequestIdentity = { threadId: string | null; turnId: string | null; windowId: string | null; forkedFrom: string | null; parentThreadId: string | null; subagentKind: string | null; turnTrigger: string | null };
+export function requestIdentity(headers: IncomingHttpHeaders): RequestIdentity {
+ let meta: Json = {};
+ try { meta = JSON.parse(String(headers["x-codex-turn-metadata"] ?? "{}")); } catch { /* not JSON */ }
+ const header = (name: string) => { const value = headers[name]; return (Array.isArray(value) ? value[0] : value) || null; };
+ return {
+ threadId: meta.thread_id ?? meta.session_id ?? null, turnId: meta.turn_id ?? null, windowId: header("x-codex-window-id"),
+ forkedFrom: meta.forked_from_thread_id ?? null, parentThreadId: meta.parent_thread_id ?? header("x-codex-parent-thread-id"), subagentKind: meta.subagent_kind ?? null,
+ turnTrigger: meta.turn_trigger ?? null,
+ };
+}
+
+// The images a request carried and the base64 characters each took, under the same keys as the thread index.
+export function imageSizesOf(input: Json[]): Record<string, number> {
+ return Object.fromEntries(findImages(input).map((ref) => [ref.key, ref.base64Chars]));
+}
+
+// Whether a thread's requests go through the rewrite (and so over HTTP): something unchecked, or automatic selection
+// used at some point (v0.3), since from then on the history may hold copies the model fetched, left out of later turns.
+// v0.7: a side chat's, always (v0.8: the switch for subagents and side chats is gone).
+export function needsRewrite(threadId: string | null, dir = selectionDir, sessionsDir = join(codexHome(), "sessions"), forkedFrom: string | null = null): boolean {
+ if (!threadId) return false;
+ try {
+ if (sideChatOrigin(threadId, forkedFrom, sessionsDir)) return true;
+ const selection = effectiveSelection(threadId, sessionsDir, dir);
+ return Object.keys(selection.unchecked).length > 0 || !!selection.autoSince;
+ } catch { return false; }
+}
+
+// The turn a request belongs to, as numbered in the index; a turn not written to the rollout yet comes after the last.
+// Without a turn id the last one counts as current, so its images are sent rather than left out.
+export function currentTurnOf(index: ThreadIndex, turnId: string | null): number {
+ if (!turnId) return index.turns;
+ return index.turnNumbers.get(turnId) ?? index.turns + 1;
+}
+
+// P2: replace the thread's unchecked images with placeholders. Whenever the body cannot be handled safely it is
+// forwarded unchanged and the reason is logged; the report never contains conversation content.
+// v0.3: with automatic selection on, the images of earlier turns that are not pinned instead; in either mode, copies
+// the model fetched in an earlier turn.
+// v0.7: a side chat's request carries the history of the task it came from: that task's index, with every one of its
+// turns counting as earlier (sideChatSelection).
+export function rewriteBody(original: Buffer, encoding: string | undefined, threadId: string, sessionsDir: string, dir = selectionDir, turnId: string | null = null, forkedFrom: string | null = null): { body: Buffer; report: Json } {
+ const origin = sideChatOrigin(threadId, forkedFrom, sessionsDir);
+ const side = origin ? sideChatSelection(origin, sessionsDir, dir) : null;
+ const decoded = decodeBody(original, encoding);
+ if (!decoded) return { body: original, report: { skipped: "undecodable body" } };
+ const text = decoded.toString("utf8");
+ let json: Json;
+ try { json = JSON.parse(text); } catch { return { body: original, report: { skipped: "unparsable body" } }; }
+ if (!Array.isArray(json.input)) return { body: original, report: { skipped: "no input array" } };
+ if (hasUnsafeInteger(text)) return { body: original, report: { skipped: "integer beyond 2^53 would change when re-serialized" } };
+ let index: ThreadIndex;
+ try { index = loadThreadIndex(sessionsDir, origin ?? threadId); } catch (error) { return { body: original, report: { skipped: `thread index: ${String(error)}` } }; }
+ const selection = side ?? effectiveSelection(threadId, sessionsDir, dir);
+ // v0.10: images sent once more for their feature line (awaitingLine), marked in their labels.
+ const awaiting = new Set<string>();
+ const describe = (ref: ImageRef): Described | undefined => {
+ const known = index.byKey.get(ref.key);
+ // v0.8: with what the model noted about it, for its placeholder.
+ const notes = known ? index.notes.get(known.id) : undefined;
+ if (known) return { ...known, ...(notes ? { notes } : {}), ...(awaiting.has(known.key) ? { awaiting: true } : {}) };
+ const stored = selection.unchecked[ref.key];
+ return stored ? { id: stored.id, name: ref.name, label: ref.label, kind: ref.kind, turn: null, width: ref.width, height: ref.height } : undefined;
+ };
+ const pixels = (ref: ImageRef) => index.byKey.get(ref.key)?.pixelSha256 ?? pixelHashOf(json.input, ref);
+ const current = side ? index.turns + 1 : currentTurnOf(index, turnId);
+ const copies = new Map([...index.copies.values()].filter((copy) => copy.turn === null || copy.turn < current).map((copy) => [copy.key, copy.of]));
+ let leaveOut = new Set(Object.keys(selection.unchecked));
+ // v0.8: feature lines in a task's own requests, not a side chat's or a subagent's.
+ const features = !origin && writesNotes(sessionsDir, threadId);
+ if (selection.auto) {
+ const pinned = selection.pinned ?? {};
+ for (const image of index.images) if (features && awaitingLine(index, image, current)) awaiting.add(image.key);
+ leaveOut = new Set(index.images.filter((image) => image.replaceable && image.turn !== null && image.turn < current && !pinned[image.key] && !awaiting.has(image.key)).map((image) => image.key));
+ }
+ const rewritten = rewriteItems(json.input, describe, leaveOut, pixels, { lang: currentLang(), copies, features, ...(selection.auto ? { auto: { currentTurn: current } } : {}) });
+ const { report } = rewritten;
+ let items = rewritten.items;
+ // v0.10: after Codex compacted the task, the images its compaction did not keep (thread-index.ts), right after its
+ // compaction item: pinned ones (in manual mode, checked ones) as originals, the others one line each.
+ let compacted: Json | null = null;
+ const dropped = features ? index.images.filter((image) => image.compacted) : [];
+ if (dropped.length) {
+ const inRequest = new Set(findImages(json.input).map((ref) => ref.key));
+ const listed = dropped.filter((image) => !inRequest.has(image.key) && !copies.has(image.key)).map((image) => describe(image)!).filter(Boolean);
+ const resend = dropped.filter((image) => !inRequest.has(image.key) && !leaveOut.has(image.key) && !copies.has(image.key)).flatMap((image) => {
+ const data = index.items ? imageData(index.items, image) : null;
+ return data ? [{ image: describe(image)!, url: `data:${image.mime ?? "image/png"};base64,${data}` }] : [];
+ });
+ const added = addCodexCompacted(items, listed, resend, { lang: currentLang(), auto: !!selection.auto });
+ if (added.at !== null) {
+ items = added.items;
+ compacted = { at: added.at, listed: listed.length, resent: resend.map(({ image }) => image.id) };
+ }
+ }
+ const summary: Json = {
+ images: report.images,
+ replaced: report.replaced.map(({ key: _key, ...rest }) => rest),
+ locked: report.locked,
+ sentImageHashes: report.sentContentIds.map((id) => id.slice(0, 16)),
+ ...(selection.auto ? { auto: true } : {}),
+ ...(report.copies.length ? { copies: report.copies } : {}),
+ ...(origin ? { sideChatOf: origin } : {}),
+ ...(report.featureAt !== undefined ? { featureAt: report.featureAt, labeled: report.labeled ?? 0 } : {}),
+ ...(report.unknown ? { unknown: report.unknown } : {}),
+ ...(compacted ? { compacted } : {}),
+ };
+ if (!report.replaced.length && !report.copies.length && report.featureAt === undefined && !compacted) return { body: original, report: summary };
+ json.input = items;
+ const next = Buffer.from(JSON.stringify(json), "utf8");
+ const body = encodeBody(next, encoding);
+ return { body, report: { ...summary, decodedBefore: decoded.length, decodedAfter: next.length, encodedBefore: original.length, encodedAfter: body.length } };
+}
diff --git a/plugin/src/core/engine/transport.ts b/plugin/src/core/engine/transport.ts
new file mode 100644
index 0000000..789db23
--- /dev/null
+++ b/plugin/src/core/engine/transport.ts
@@ -0,0 +1,145 @@
+// Purpose: the engine's way to the services, whatever the platform (v0.11: split from proxy.ts, docs/v0.11/plan.md):
+// the outbound proxy (HTTPS_PROXY/HTTP_PROXY, else the system setting on Windows and macOS; NO_PROXY honoured per
+// upstream host), a TLS connection through it, request bodies decoded and encoded again (zstd, gzip, br), the guard
+// against integers JSON cannot carry, the log (metadata only), and whether a request comes from this machine's own
+// pages.
+// Output: sockets, buffers; <data dir>/proxy/<date>.jsonl.
+
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { appendFileSync, mkdirSync } from "node:fs";
+import type { IncomingHttpHeaders } from "node:http";
+import net from "node:net";
+import { join } from "node:path";
+import tls from "node:tls";
+import zlib from "node:zlib";
+import { proxyLogDirOf } from "../paths.ts";
+
+type Json = Record<string, any>;
+export const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-connection", "transfer-encoding", "te", "trailer", "upgrade", "host"]);
+
+// Outbound proxy: environment first, then the system setting (Windows per-user, macOS); NO_PROXY is honoured for the
+// upstream host.
+export function outboundProxy(env = process.env, systemSetting = readSystemProxy, upstream = ""): { host: string; port: number } | null {
+ const noProxy = (env.NO_PROXY ?? env.no_proxy ?? "").split(",").map((s) => s.trim().replace(/^\./, "")).filter(Boolean);
+ if (noProxy.some((entry) => entry === "*" || upstream === entry || upstream.endsWith(`.${entry}`))) return null;
+ const fromEnv = env.HTTPS_PROXY ?? env.https_proxy ?? env.HTTP_PROXY ?? env.http_proxy;
+ let value = fromEnv || systemSetting();
+ if (!value) return null;
+ // Windows may store per-protocol entries: "http=host:port;https=host:port".
+ if (value.includes("=")) value = /https=([^;]+)/.exec(value)?.[1] ?? /http=([^;]+)/.exec(value)?.[1] ?? "";
+ if (!value) return null;
+ const url = new URL(/^[a-z]+:\/\//i.test(value) ? value : `http://${value}`);
+ return { host: url.hostname, port: Number(url.port || 80) };
+}
+
+export function readSystemProxy(): string | null {
+ try {
+ if (process.platform === "win32") {
+ const out = execFileSync("reg", ["query", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"], { encoding: "utf8" });
+ if (!/ProxyEnable\s+REG_DWORD\s+0x1/.test(out)) return null;
+ return /ProxyServer\s+REG_SZ\s+(\S+)/.exec(out)?.[1] ?? null;
+ }
+ if (process.platform === "darwin") return macProxy(execFileSync("scutil", ["--proxy"], { encoding: "utf8" }));
+ } catch { /* no setting readable: connect directly */ }
+ return null;
+}
+
+// v0.1: `scutil --proxy` lists the macOS system proxies as "Key : value" lines. Only HTTP(S) proxies are usable here
+// (the engine tunnels with CONNECT); PAC files and SOCKS are not read. Linux has no system setting beyond the
+// environment.
+export function macProxy(scutil: string): string | null {
+ const field = (key: string) => scutil.match(new RegExp(`^\\s*${key}\\s*:\\s*(\\S+)\\s*$`, "m"))?.[1] ?? null;
+ for (const scheme of ["HTTPS", "HTTP"]) {
+ const host = field(`${scheme}Proxy`);
+ if (field(`${scheme}Enable`) === "1" && host) return `${host}:${field(`${scheme}Port`) ?? "80"}`;
+ }
+ return null;
+}
+
+export function connectUpstream(via: { host: string; port: number } | null, upstream: string, signal?: AbortSignal, port = 443, secure = true): Promise<net.Socket> {
+ const startTls = (socket?: net.Socket) => new Promise<net.Socket>((ok, fail) => {
+ if (!secure) {
+ if (socket) { ok(socket); return; }
+ const plain = net.connect({ host: upstream, port, signal }, () => ok(plain));
+ plain.once("error", fail);
+ return;
+ }
+ const cleanup = () => signal?.removeEventListener("abort", abort);
+ const connection = tls.connect({ socket, host: socket ? undefined : upstream, port, servername: net.isIP(upstream) ? undefined : upstream, ALPNProtocols: ["http/1.1"] }, () => { cleanup(); ok(connection); });
+ const abort = () => { cleanup(); connection.destroy(); socket?.destroy(); fail(new Error("upstream connection cancelled")); };
+ connection.once("error", (error) => { cleanup(); fail(error); });
+ signal?.addEventListener("abort", abort, { once: true });
+ if (signal?.aborted) abort();
+ });
+ if (!via) return startTls();
+ return new Promise((ok, fail) => {
+ const authority = `${upstream.includes(":") ? `[${upstream}]` : upstream}:${port}`;
+ const socket = net.connect({ port: via.port, host: via.host, signal }, () => socket.write(`CONNECT ${authority} HTTP/1.1\r\nHost: ${authority}\r\n\r\n`));
+ let buffered = Buffer.alloc(0);
+ const onData = (chunk: Buffer) => {
+ buffered = Buffer.concat([buffered, chunk]);
+ const end = buffered.indexOf("\r\n\r\n");
+ if (end < 0) return;
+ socket.off("data", onData);
+ const status = buffered.toString("latin1", 0, end).split(" ")[1];
+ if (status !== "200") { socket.destroy(); fail(new Error(`outbound proxy refused CONNECT (${status})`)); return; }
+ startTls(socket).then(ok, fail);
+ };
+ socket.on("data", onData);
+ socket.once("error", fail);
+ });
+}
+
+export function decodeBody(body: Buffer, encoding: string | undefined): Buffer | null {
+ try {
+ if (!encoding || encoding === "identity") return body;
+ if (encoding === "zstd") return zlib.zstdDecompressSync(body);
+ if (encoding === "gzip") return zlib.gunzipSync(body);
+ if (encoding === "br") return zlib.brotliDecompressSync(body);
+ } catch { /* fall through */ }
+ return null;
+}
+
+export function log(entry: Json): void {
+ const dir = proxyLogDirOf();
+ mkdirSync(dir, { recursive: true });
+ appendFileSync(join(dir, `${new Date().toISOString().slice(0, 10)}.jsonl`), `${JSON.stringify(entry)}\n`);
+}
+
+// P2-1 debugging aid for synthetic test threads only: the request with every inline image reduced to its hash and size.
+export function redactImages(value: unknown, key = ""): unknown {
+ if (typeof value === "string") {
+ const inline = /^data:([^;,]+);base64,/.exec(value);
+ // v0.4: an Anthropic image block keeps its base64 in source.data; a thinking block's signature is opaque too.
+ const raw = inline ? value.slice(inline[0].length) : (key === "result" || key === "data" || key === "signature") && value.length > 256 ? value : null;
+ if (raw === null) return value;
+ const digest = createHash("sha256").update(raw).digest("hex").slice(0, 16);
+ return `${inline ? `data:${inline[1]};base64,` : ""}<sha256:${digest} chars:${raw.length}>`;
+ }
+ if (Array.isArray(value)) return value.map((item) => redactImages(item));
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name, child]) => [name, redactImages(child, name)]));
+ return value;
+}
+
+export function encodeBody(body: Buffer, encoding: string | undefined): Buffer {
+ if (encoding === "zstd") return zlib.zstdCompressSync(body);
+ if (encoding === "gzip") return zlib.gzipSync(body);
+ if (encoding === "br") return zlib.brotliCompressSync(body);
+ return body;
+}
+
+// Number tokens outside strings that JavaScript cannot represent exactly.
+export function hasUnsafeInteger(json: string): boolean {
+ for (const match of json.matchAll(/"(?:[^"\\]|\\.)*"|(?<![\d.eE+-])(-?\d+)(?![.\deE])/g)) {
+ if (match[1] && !Number.isSafeInteger(Number(match[1]))) return true;
+ }
+ return false;
+}
+
+const LOOPBACK_HOST = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/;
+export function ownRequest(headers: IncomingHttpHeaders): boolean {
+ const host = String(headers.host ?? "");
+ if (!LOOPBACK_HOST.test(host)) return false;
+ return headers.origin === undefined || headers.origin === `http://${host}`;
+}
diff --git a/plugin/src/panel/page.ts b/plugin/src/panel/page.ts
new file mode 100644
index 0000000..1123241
--- /dev/null
+++ b/plugin/src/panel/page.ts
@@ -0,0 +1,20 @@
+// Purpose: the panel page itself (v0.11: the panel layer reads its own files, docs/v0.11/plan.md). Codex shows
+// panel.html as an MCP app; Claude Desktop opens it as a page the engine serves, with panel-web.js before its own script
+// standing in for the MCP app host (v0.4).
+// Output: the page's HTML.
+
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+
+export const panelHtml = (): string => readFileSync(join(here, "panel.html"), "utf8");
+
+export function webPanelPage(): string {
+ const page = panelHtml();
+ const bridge = readFileSync(join(here, "panel-web.js"), "utf8");
+ const at = page.indexOf("<script>");
+ if (at < 0) throw new Error("panel.html has no script");
+ return `${page.slice(0, at)}<script>\n${bridge}\n</script>\n${page.slice(at)}`;
+}
diff --git a/plugin/src/plugin-server.ts b/plugin/src/plugin-server.ts
index a3eb200..071897e 100644
--- a/plugin/src/plugin-server.ts
+++ b/plugin/src/plugin-server.ts
@@ -23,10 +23,9 @@
// Input: MCP JSON-RPC over stdio. Env: CAM_ENGINE_PORT (default 17891), CAM_NO_ENGINE=1 (tests), CAM_DATA_DIR,
// CAM_HOST. Output: tool results; <data dir>/plugin-server.jsonl (events and counts only, no conversation content).
-import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
-import { dirname, join } from "node:path";
+import { appendFileSync, mkdirSync } from "node:fs";
+import { join } from "node:path";
import { createInterface } from "node:readline";
-import { fileURLToPath } from "node:url";
import { codexHome } from "./adapters/codex/codexconfig.ts";
import { bindThread, isUserThread, newThreads, resolveThread } from "./adapters/codex/binding.ts";
import { claudeStartedAt, loadClaudeIndex } from "./adapters/claude/claude-index.ts";
@@ -35,6 +34,7 @@ import { isEntryPoint } from "./core/entry.ts";
import { currentLang, langOf, rememberLang, type Lang } from "./language.ts";
import { say } from "./messages.ts";
import { migrateDataOnce } from "./core/migrate-data.ts";
+import { panelHtml } from "./panel/page.ts";
import { applySelection, claudeImageFor, imageFor, loadPanelState, type ClaudePanelOptions, type PanelState } from "./panel/panel-state.ts";
import { claudeSelectionDirOf, dataDir, pixelCacheDirOf, selectionDirOf } from "./core/paths.ts";
import { fetchedLabel, fetchWords } from "./core/words.ts";
@@ -44,7 +44,6 @@ import { hasRollout, loadThreadIndex, readThreadHistory, sessionMetaOf, setPixel
import { threadTitle } from "./adapters/codex/thread-names.ts";
type Json = Record<string, any>;
-const here = dirname(fileURLToPath(import.meta.url));
// Kept fixed: Codex Desktop on Windows may show a blank panel after a resource URI changes (openai/codex#47512).
export const PANEL_URI = "ui://codex-attachment-manager/panel.html";
export const PANEL_MIME = "text/html;profile=mcp-app";
@@ -120,7 +119,7 @@ export const serverInfo = (lang: Lang) => ({ name: "codex-attachment-manager", t
export function readResource(uri: string): Json {
if (uri !== PANEL_URI) throw new Error(`unknown resource ${uri}`);
- const text = readFileSync(join(here, "panel", "panel.html"), "utf8");
+ const text = panelHtml();
// The page is self-contained: images arrive as data URLs through tool calls, nothing is fetched.
return { contents: [{ uri, mimeType: PANEL_MIME, text, _meta: { ui: { csp: { connectDomains: [], resourceDomains: [] }, prefersBorder: false } } }] };
}
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index 69b821c..615a591 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -16,50 +16,38 @@
// the outbound proxy is taken from HTTPS_PROXY/HTTP_PROXY or the system proxy settings (Windows, macOS).
// Output: responses streamed back to Codex; <data dir>/proxy/<date>.jsonl; <data dir>/state/requests/<thread>.json.
-import { execFileSync } from "node:child_process";
-import { createHash } from "node:crypto";
-import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+// v0.11: this file is the engine's entry (docs/v0.11/plan.md): the server, routing and the order of a request's steps.
+// The way to the services is core/engine/transport.ts; what is particular to Codex and to Claude Code is in
+// adapters/codex/engine.ts, adapters/claude/engine.ts and adapters/claude/panel-web.ts.
+
import http, { type IncomingHttpHeaders } from "node:http";
-import net from "node:net";
-import { dirname, join } from "node:path";
+import type net from "node:net";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
import type { Duplex } from "node:stream";
import { setTimeout as sleep } from "node:timers/promises";
-import tls from "node:tls";
-import { fileURLToPath } from "node:url";
-import zlib from "node:zlib";
import { childOf, recordChild } from "./children.ts";
-import { claudeHome, claudeImageData, claudeStartedAt, loadClaudeIndex, type ClaudeIndex } from "./adapters/claude/claude-index.ts";
-import { addCompacted, summaryAt, type RequestImage, type Resend } from "./adapters/protocols/anthropic-messages/rewrite.ts";
-import { findRequestImages, rewriteMessages } from "./adapters/claude/claude-rewrite.ts";
-import { keepCacheRead, marksOutside, REMEMBERED, sentPrefixOf, type SentPrefix } from "./adapters/protocols/anthropic-messages/cache.ts";
-import { chainOf, fitThinking, readThinkingRecord, recordSent, writeThinkingRecord, type ThinkingRecord } from "./adapters/protocols/anthropic-messages/thinking.ts";
+import { claudeHome, loadClaudeIndex } from "./adapters/claude/claude-index.ts";
+import { CLAUDE_HOST, claudeConversationRequest, claudeIdentity, claudeImageSizes, claudeNeedsRewrite, LATE_STEP_MS, LATE_WAIT_MS, rewriteClaudeBody, thinkingRejected, type ClaudeAttempt } from "./adapters/claude/engine.ts";
+import { claudePanelApi, claudePanelPage, PANEL_PAGE_CSP } from "./adapters/claude/panel-web.ts";
import { codexHome } from "./adapters/codex/codexconfig.ts";
-import { buildOf, DEFAULT_PORT, ENGINE_SERVICE, engineHealth, versionOf, watchForCodex } from "./engine.ts";
-import { findImages, type ImageRef } from "./adapters/protocols/openai-responses/images.ts";
+import { CODEX_BASE, imageSizesOf, needsRewrite, OPENAI_API_HOST, requestIdentity, rewriteBody, UPSTREAM_HOST, type RequestIdentity } from "./adapters/codex/engine.ts";
+import { connectDirectly, pluginGone, usesEngine } from "./adapters/codex/setup.ts";
+import { setPixelCache } from "./adapters/codex/thread-index.ts";
+import { REMEMBERED, type SentPrefix } from "./adapters/protocols/anthropic-messages/cache.ts";
+import { readThinkingRecord, recordSent, writeThinkingRecord, type ThinkingRecord } from "./adapters/protocols/anthropic-messages/thinking.ts";
+import { connectUpstream, decodeBody, HOP_BY_HOP, log, outboundProxy, ownRequest, readSystemProxy, redactImages } from "./core/engine/transport.ts";
import { isEntryPoint } from "./core/entry.ts";
-import { currentLang } from "./language.ts";
import { migrateDataOnce } from "./core/migrate-data.ts";
-import { say } from "./messages.ts";
-import { claudePanelLanguage } from "./panel/panel-language.ts";
-import { applyClaudeSelection, claudeImageFor, loadClaudePanelState, type ClaudePanelOptions } from "./panel/panel-state.ts";
-import { claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, pixelCacheDirOf, proxyLogDirOf, selectionDirOf } from "./core/paths.ts";
+import { claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, pixelCacheDirOf, selectionDirOf } from "./core/paths.ts";
import { recordRequest } from "./core/request-stats.ts";
import { readRoute, registerRoute, routeBaseUrl, routingPort, validateBaseUrl, type Platform } from "./core/routes.ts";
-import { addCodexCompacted, rewriteItems } from "./adapters/protocols/openai-responses/rewrite.ts";
-import type { Described } from "./core/words.ts";
-import { connectDirectly, pluginGone, usesEngine } from "./adapters/codex/setup.ts";
-import { claudeSelection, effectiveSelection, ensureAutoDefault, ensureStableIds, selectionDir, sideChatSelection, stableIdsSince } from "./selection.ts";
-import { awaitingLine, imageData, loadThreadIndex, pixelHashOf, pixelHashOfData, setPixelCache, sideChatOrigin, writesNotes, type ThreadIndex } from "./adapters/codex/thread-index.ts";
+import { buildOf, DEFAULT_PORT, ENGINE_SERVICE, engineHealth, versionOf, watchForCodex } from "./engine.ts";
+import { currentLang } from "./language.ts";
+import { say } from "./messages.ts";
+import { ensureAutoDefault, ensureStableIds, selectionDir, stableIdsSince } from "./selection.ts";
type Json = Record<string, any>;
-const here = dirname(fileURLToPath(import.meta.url));
-const UPSTREAM_HOST = "chatgpt.com";
-// v0.4: Claude Code's API host.
-export const CLAUDE_HOST = "api.anthropic.com";
-// Where Codex logged in with an API key sends its requests without the plugin (its base URL https://api.openai.com/v1).
-const OPENAI_API_HOST = "api.openai.com";
-const CODEX_BASE = "/backend-api/codex/";
-const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-connection", "transfer-encoding", "te", "trailer", "upgrade", "host"]);
// Codex logged in with an API key keeps the base URL the plugin set and sends its key (Bearer sk-…, no
// chatgpt-account-id), which chatgpt.com does not take: those requests go to api.openai.com, /backend-api/codex/
@@ -94,79 +82,6 @@ export function routeOf(url: string, headers: IncomingHttpHeaders, root = dataDi
return { host: UPSTREAM_HOST, url };
}
-// Outbound proxy: environment first, then the system setting (Windows per-user, macOS); NO_PROXY is honoured for the
-// upstream host.
-export function outboundProxy(env = process.env, systemSetting = readSystemProxy, upstream = UPSTREAM_HOST): { host: string; port: number } | null {
- const noProxy = (env.NO_PROXY ?? env.no_proxy ?? "").split(",").map((s) => s.trim().replace(/^\./, "")).filter(Boolean);
- if (noProxy.some((entry) => entry === "*" || upstream === entry || upstream.endsWith(`.${entry}`))) return null;
- const fromEnv = env.HTTPS_PROXY ?? env.https_proxy ?? env.HTTP_PROXY ?? env.http_proxy;
- let value = fromEnv || systemSetting();
- if (!value) return null;
- // Windows may store per-protocol entries: "http=host:port;https=host:port".
- if (value.includes("=")) value = /https=([^;]+)/.exec(value)?.[1] ?? /http=([^;]+)/.exec(value)?.[1] ?? "";
- if (!value) return null;
- const url = new URL(/^[a-z]+:\/\//i.test(value) ? value : `http://${value}`);
- return { host: url.hostname, port: Number(url.port || 80) };
-}
-
-function readSystemProxy(): string | null {
- try {
- if (process.platform === "win32") {
- const out = execFileSync("reg", ["query", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"], { encoding: "utf8" });
- if (!/ProxyEnable\s+REG_DWORD\s+0x1/.test(out)) return null;
- return /ProxyServer\s+REG_SZ\s+(\S+)/.exec(out)?.[1] ?? null;
- }
- if (process.platform === "darwin") return macProxy(execFileSync("scutil", ["--proxy"], { encoding: "utf8" }));
- } catch { /* no setting readable: connect directly */ }
- return null;
-}
-
-// v0.1: `scutil --proxy` lists the macOS system proxies as "Key : value" lines. Only HTTP(S) proxies are usable here
-// (the engine tunnels with CONNECT); PAC files and SOCKS are not read. Linux has no system setting beyond the
-// environment.
-export function macProxy(scutil: string): string | null {
- const field = (key: string) => scutil.match(new RegExp(`^\\s*${key}\\s*:\\s*(\\S+)\\s*$`, "m"))?.[1] ?? null;
- for (const scheme of ["HTTPS", "HTTP"]) {
- const host = field(`${scheme}Proxy`);
- if (field(`${scheme}Enable`) === "1" && host) return `${host}:${field(`${scheme}Port`) ?? "80"}`;
- }
- return null;
-}
-
-function connectUpstream(via: { host: string; port: number } | null, upstream = UPSTREAM_HOST, signal?: AbortSignal, port = 443, secure = true): Promise<net.Socket> {
- const startTls = (socket?: net.Socket) => new Promise<net.Socket>((ok, fail) => {
- if (!secure) {
- if (socket) { ok(socket); return; }
- const plain = net.connect({ host: upstream, port, signal }, () => ok(plain));
- plain.once("error", fail);
- return;
- }
- const cleanup = () => signal?.removeEventListener("abort", abort);
- const connection = tls.connect({ socket, host: socket ? undefined : upstream, port, servername: net.isIP(upstream) ? undefined : upstream, ALPNProtocols: ["http/1.1"] }, () => { cleanup(); ok(connection); });
- const abort = () => { cleanup(); connection.destroy(); socket?.destroy(); fail(new Error("upstream connection cancelled")); };
- connection.once("error", (error) => { cleanup(); fail(error); });
- signal?.addEventListener("abort", abort, { once: true });
- if (signal?.aborted) abort();
- });
- if (!via) return startTls();
- return new Promise((ok, fail) => {
- const authority = `${upstream.includes(":") ? `[${upstream}]` : upstream}:${port}`;
- const socket = net.connect({ port: via.port, host: via.host, signal }, () => socket.write(`CONNECT ${authority} HTTP/1.1\r\nHost: ${authority}\r\n\r\n`));
- let buffered = Buffer.alloc(0);
- const onData = (chunk: Buffer) => {
- buffered = Buffer.concat([buffered, chunk]);
- const end = buffered.indexOf("\r\n\r\n");
- if (end < 0) return;
- socket.off("data", onData);
- const status = buffered.toString("latin1", 0, end).split(" ")[1];
- if (status !== "200") { socket.destroy(); fail(new Error(`outbound proxy refused CONNECT (${status})`)); return; }
- startTls(socket).then(ok, fail);
- };
- socket.on("data", onData);
- socket.once("error", fail);
- });
-}
-
export function forwardHeaders(headers: IncomingHttpHeaders, upstream = UPSTREAM_HOST, platform?: Platform): Record<string, string | string[]> {
const out: Record<string, string | string[]> = {};
const client = platform ?? (upstream === CLAUDE_HOST ? "claude" : "codex");
@@ -176,37 +91,6 @@ export function forwardHeaders(headers: IncomingHttpHeaders, upstream = UPSTREAM
return out;
}
-// Which task a request belongs to, from Codex's own turn metadata header.
-// v0.7: and where that task came from: a side chat (a fork Codex keeps in memory only) names the task it was forked
-// from, a subagent its parent (also in Codex's own header).
-export type RequestIdentity = { threadId: string | null; turnId: string | null; windowId: string | null; forkedFrom: string | null; parentThreadId: string | null; subagentKind: string | null; turnTrigger: string | null };
-export function requestIdentity(headers: IncomingHttpHeaders): RequestIdentity {
- let meta: Json = {};
- try { meta = JSON.parse(String(headers["x-codex-turn-metadata"] ?? "{}")); } catch { /* not JSON */ }
- const header = (name: string) => { const value = headers[name]; return (Array.isArray(value) ? value[0] : value) || null; };
- return {
- threadId: meta.thread_id ?? meta.session_id ?? null, turnId: meta.turn_id ?? null, windowId: header("x-codex-window-id"),
- forkedFrom: meta.forked_from_thread_id ?? null, parentThreadId: meta.parent_thread_id ?? header("x-codex-parent-thread-id"), subagentKind: meta.subagent_kind ?? null,
- turnTrigger: meta.turn_trigger ?? null,
- };
-}
-
-// v0.4: which Claude Code session a request belongs to, and whether a subagent's loop sent it (its own conversation).
-export function claudeIdentity(headers: IncomingHttpHeaders): { sessionId: string | null; agentId: string | null } {
- const one = (value: string | string[] | undefined) => (Array.isArray(value) ? value[0] : value) || null;
- return { sessionId: one(headers["x-claude-code-session-id"]), agentId: one(headers["x-claude-code-agent-id"]) };
-}
-
-function decodeBody(body: Buffer, encoding: string | undefined): Buffer | null {
- try {
- if (!encoding || encoding === "identity") return body;
- if (encoding === "zstd") return zlib.zstdDecompressSync(body);
- if (encoding === "gzip") return zlib.gunzipSync(body);
- if (encoding === "br") return zlib.brotliDecompressSync(body);
- } catch { /* fall through */ }
- return null;
-}
-
// Metadata only: counts and sizes, never text or image content.
export function describeBody(path: string, json: Json): Json {
if (/\/responses$/.test(path)) {
@@ -247,359 +131,6 @@ export function describeBody(path: string, json: Json): Json {
return { kind: "other" };
}
-// v0.4: the requests the panel's "last request" line is about: the session's conversation as the model works on it,
-// Claude Code's main loop, which always carries its tools. Claude Desktop also sends side requests in the session (a
-// status summary while the user is away, auto mode's safety check): no tools and none of the conversation's images.
-// They are rewritten like the rest; only the line leaves them out (2026-10-10: it said "nothing replaced" after a turn
-// whose four images had all been left out).
-export const claudeConversationRequest = (details: Json): boolean => details.kind === "messages" && details.tools > 0;
-
-function log(entry: Json): void {
- const dir = proxyLogDirOf();
- mkdirSync(dir, { recursive: true });
- appendFileSync(join(dir, `${new Date().toISOString().slice(0, 10)}.jsonl`), `${JSON.stringify(entry)}\n`);
-}
-
-// The images a request carried and the base64 characters each took, under the same keys as the thread index.
-export function imageSizesOf(input: Json[]): Record<string, number> {
- return Object.fromEntries(findImages(input).map((ref) => [ref.key, ref.base64Chars]));
-}
-
-// P2-1 debugging aid for synthetic test threads only: the request with every inline image reduced to its hash and size.
-export function redactImages(value: unknown, key = ""): unknown {
- if (typeof value === "string") {
- const inline = /^data:([^;,]+);base64,/.exec(value);
- // v0.4: an Anthropic image block keeps its base64 in source.data; a thinking block's signature is opaque too.
- const raw = inline ? value.slice(inline[0].length) : (key === "result" || key === "data" || key === "signature") && value.length > 256 ? value : null;
- if (raw === null) return value;
- const digest = createHash("sha256").update(raw).digest("hex").slice(0, 16);
- return `${inline ? `data:${inline[1]};base64,` : ""}<sha256:${digest} chars:${raw.length}>`;
- }
- if (Array.isArray(value)) return value.map((item) => redactImages(item));
- if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name, child]) => [name, redactImages(child, name)]));
- return value;
-}
-
-function encodeBody(body: Buffer, encoding: string | undefined): Buffer {
- if (encoding === "zstd") return zlib.zstdCompressSync(body);
- if (encoding === "gzip") return zlib.gzipSync(body);
- if (encoding === "br") return zlib.brotliCompressSync(body);
- return body;
-}
-
-// Number tokens outside strings that JavaScript cannot represent exactly.
-export function hasUnsafeInteger(json: string): boolean {
- for (const match of json.matchAll(/"(?:[^"\\]|\\.)*"|(?<![\d.eE+-])(-?\d+)(?![.\deE])/g)) {
- if (match[1] && !Number.isSafeInteger(Number(match[1]))) return true;
- }
- return false;
-}
-
-// Whether a thread's requests go through the rewrite (and so over HTTP): something unchecked, or automatic selection
-// used at some point (v0.3), since from then on the history may hold copies the model fetched, left out of later turns.
-// v0.7: a side chat's, always (v0.8: the switch for subagents and side chats is gone).
-export function needsRewrite(threadId: string | null, dir = selectionDir, sessionsDir = join(codexHome(), "sessions"), forkedFrom: string | null = null): boolean {
- if (!threadId) return false;
- try {
- if (sideChatOrigin(threadId, forkedFrom, sessionsDir)) return true;
- const selection = effectiveSelection(threadId, sessionsDir, dir);
- return Object.keys(selection.unchecked).length > 0 || !!selection.autoSince;
- } catch { return false; }
-}
-
-// The turn a request belongs to, as numbered in the index; a turn not written to the rollout yet comes after the last.
-// Without a turn id the last one counts as current, so its images are sent rather than left out.
-export function currentTurnOf(index: ThreadIndex, turnId: string | null): number {
- if (!turnId) return index.turns;
- return index.turnNumbers.get(turnId) ?? index.turns + 1;
-}
-
-// P2: replace the thread's unchecked images with placeholders. Whenever the body cannot be handled safely it is
-// forwarded unchanged and the reason is logged; the report never contains conversation content.
-// v0.3: with automatic selection on, the images of earlier turns that are not pinned instead; in either mode, copies
-// the model fetched in an earlier turn.
-// v0.7: a side chat's request carries the history of the task it came from: that task's index, with every one of its
-// turns counting as earlier (sideChatSelection).
-export function rewriteBody(original: Buffer, encoding: string | undefined, threadId: string, sessionsDir: string, dir = selectionDir, turnId: string | null = null, forkedFrom: string | null = null): { body: Buffer; report: Json } {
- const origin = sideChatOrigin(threadId, forkedFrom, sessionsDir);
- const side = origin ? sideChatSelection(origin, sessionsDir, dir) : null;
- const decoded = decodeBody(original, encoding);
- if (!decoded) return { body: original, report: { skipped: "undecodable body" } };
- const text = decoded.toString("utf8");
- let json: Json;
- try { json = JSON.parse(text); } catch { return { body: original, report: { skipped: "unparsable body" } }; }
- if (!Array.isArray(json.input)) return { body: original, report: { skipped: "no input array" } };
- if (hasUnsafeInteger(text)) return { body: original, report: { skipped: "integer beyond 2^53 would change when re-serialized" } };
- let index: ThreadIndex;
- try { index = loadThreadIndex(sessionsDir, origin ?? threadId); } catch (error) { return { body: original, report: { skipped: `thread index: ${String(error)}` } }; }
- const selection = side ?? effectiveSelection(threadId, sessionsDir, dir);
- // v0.10: images sent once more for their feature line (awaitingLine), marked in their labels.
- const awaiting = new Set<string>();
- const describe = (ref: ImageRef): Described | undefined => {
- const known = index.byKey.get(ref.key);
- // v0.8: with what the model noted about it, for its placeholder.
- const notes = known ? index.notes.get(known.id) : undefined;
- if (known) return { ...known, ...(notes ? { notes } : {}), ...(awaiting.has(known.key) ? { awaiting: true } : {}) };
- const stored = selection.unchecked[ref.key];
- return stored ? { id: stored.id, name: ref.name, label: ref.label, kind: ref.kind, turn: null, width: ref.width, height: ref.height } : undefined;
- };
- const pixels = (ref: ImageRef) => index.byKey.get(ref.key)?.pixelSha256 ?? pixelHashOf(json.input, ref);
- const current = side ? index.turns + 1 : currentTurnOf(index, turnId);
- const copies = new Map([...index.copies.values()].filter((copy) => copy.turn === null || copy.turn < current).map((copy) => [copy.key, copy.of]));
- let leaveOut = new Set(Object.keys(selection.unchecked));
- // v0.8: feature lines in a task's own requests, not a side chat's or a subagent's.
- const features = !origin && writesNotes(sessionsDir, threadId);
- if (selection.auto) {
- const pinned = selection.pinned ?? {};
- for (const image of index.images) if (features && awaitingLine(index, image, current)) awaiting.add(image.key);
- leaveOut = new Set(index.images.filter((image) => image.replaceable && image.turn !== null && image.turn < current && !pinned[image.key] && !awaiting.has(image.key)).map((image) => image.key));
- }
- const rewritten = rewriteItems(json.input, describe, leaveOut, pixels, { lang: currentLang(), copies, features, ...(selection.auto ? { auto: { currentTurn: current } } : {}) });
- const { report } = rewritten;
- let items = rewritten.items;
- // v0.10: after Codex compacted the task, the images its compaction did not keep (thread-index.ts), right after its
- // compaction item: pinned ones (in manual mode, checked ones) as originals, the others one line each.
- let compacted: Json | null = null;
- const dropped = features ? index.images.filter((image) => image.compacted) : [];
- if (dropped.length) {
- const inRequest = new Set(findImages(json.input).map((ref) => ref.key));
- const listed = dropped.filter((image) => !inRequest.has(image.key) && !copies.has(image.key)).map((image) => describe(image)!).filter(Boolean);
- const resend = dropped.filter((image) => !inRequest.has(image.key) && !leaveOut.has(image.key) && !copies.has(image.key)).flatMap((image) => {
- const data = index.items ? imageData(index.items, image) : null;
- return data ? [{ image: describe(image)!, url: `data:${image.mime ?? "image/png"};base64,${data}` }] : [];
- });
- const added = addCodexCompacted(items, listed, resend, { lang: currentLang(), auto: !!selection.auto });
- if (added.at !== null) {
- items = added.items;
- compacted = { at: added.at, listed: listed.length, resent: resend.map(({ image }) => image.id) };
- }
- }
- const summary: Json = {
- images: report.images,
- replaced: report.replaced.map(({ key: _key, ...rest }) => rest),
- locked: report.locked,
- sentImageHashes: report.sentContentIds.map((id) => id.slice(0, 16)),
- ...(selection.auto ? { auto: true } : {}),
- ...(report.copies.length ? { copies: report.copies } : {}),
- ...(origin ? { sideChatOf: origin } : {}),
- ...(report.featureAt !== undefined ? { featureAt: report.featureAt, labeled: report.labeled ?? 0 } : {}),
- ...(report.unknown ? { unknown: report.unknown } : {}),
- ...(compacted ? { compacted } : {}),
- };
- if (!report.replaced.length && !report.copies.length && report.featureAt === undefined && !compacted) return { body: original, report: summary };
- json.input = items;
- const next = Buffer.from(JSON.stringify(json), "utf8");
- const body = encodeBody(next, encoding);
- return { body, report: { ...summary, decodedBefore: decoded.length, decodedAfter: next.length, encodedBefore: original.length, encodedAfter: body.length } };
-}
-
-// v0.4: a Claude Code session's requests are rewritten once something is unchecked there, or automatic selection was
-// used (copies the model fetched may be in its history from then on). v0.5: or once it was compacted with images
-// before the compaction, which the user may keep sending. v0.8: or once it has any image, for the feature line note
-// and the ids (Claude Code sends the whole history every time, so this costs no upload; docs/v0.8/plan.md).
-export function claudeNeedsRewrite(sessionId: string | null, dir = claudeSelectionDirOf(), home = claudeHome()): boolean {
- if (!sessionId) return false;
- let index: ClaudeIndex | null = null;
- try { index = loadClaudeIndex(sessionId, home, stableIdsSince(dir)); } catch { /* the selection still decides */ }
- try {
- const selection = claudeSelection(sessionId, dir, index ? claudeStartedAt(index) : null, index?.previous ?? []);
- if (Object.keys(selection.unchecked).length > 0 || selection.autoSince) return true;
- } catch { /* the transcript still decides */ }
- return !!index?.images.length;
-}
-
-// The images a Claude Code request carried, by index key, with the base64 characters each took (the panel's
-// baseline); images not in the transcript yet are left out.
-export function claudeImageSizes(messages: Json[], index: ClaudeIndex): Record<string, number> {
- return Object.fromEntries(findRequestImages(messages, index).filter((ref) => ref.key).map((ref) => [ref.key!, ref.base64Chars]));
-}
-
-// Anthropic refuses a request whose earlier content changed under the thinking that followed it (accounts created from
-// 2026-08-31, or a request that asks for it): docs/v0.4/plan.md §2.2. The engine then sends the original instead.
-export function thinkingRejected(status: number, body: string): boolean {
- return status === 400 && /thinking/i.test(body) && /signature|bound to a different conversation|prefix/i.test(body);
-}
-
-// v0.4: what to send for a Claude Code request, each next one when Anthropic refuses the thinking after the changed
-// history (thinkingRejected): the rewrite with all its thinking (an account that lets it through); the rewrite without
-// the thinking that no longer fits (anthropic-messages/thinking.ts), first once the account is known to refuse it; the rewrite
-// without any thinking, always accepted; the original as Claude Code built it. history/sent: the chains to remember
-// once the attempt goes through (null: not the session's conversation); made: the histories its thinking was made
-// after; sure: the record says all its thinking fits, so a refusal means the record misses what went out.
-// prefix: where its cache marks are, to remember once it is sent (anthropic-messages/cache.ts).
-export type ClaudeAttempt = { body: Buffer; report: Json; history: string | null; sent: string | null; made: string[]; sure: boolean; prefix?: SentPrefix };
-// v0.10: how long a request waits for its newest images to reach the transcript (a long-task eval caught 3 of a turn's
-// images going out without ids, the transcript written a moment after the request; the user's logs had 119 such of
-// 8904 requests). A request whose images never reach it waits the whole time once.
-const LATE_WAIT_MS = 1500;
-const LATE_STEP_MS = 100;
-
-// v0.4: the same rules as rewriteBody, for a Claude Code request (Anthropic Messages, anthropic-messages/rewrite.ts). The current
-// turn is the transcript's latest prompt: Claude Code writes it before it sends the request.
-// CAM_EXPERIMENT_BLOCK_BINDING (experiments only, docs/v0.4/tasks.md T04-01): asks Anthropic to check thinking with
-// that prefix_mismatch_behavior, as for an account created from 2026-08-31; the report names the beta header to add.
-export function rewriteClaudeBody(original: Buffer, encoding: string | undefined, sessionId: string, dir = claudeSelectionDirOf(), home = claudeHome(), env = process.env, thinking: ThinkingRecord | null = null, previous: SentPrefix[] = []): { body: Buffer; report: Json; attempts: ClaudeAttempt[]; prefix?: SentPrefix } {
- const asIs = (report: Json) => ({ body: original, report, attempts: [] });
- const decoded = decodeBody(original, encoding);
- if (!decoded) return asIs({ skipped: "undecodable body" });
- const text = decoded.toString("utf8");
- let json: Json;
- try { json = JSON.parse(text); } catch { return asIs({ skipped: "unparsable body" }); }
- if (!Array.isArray(json.messages)) return asIs({ skipped: "no messages array" });
- if (hasUnsafeInteger(text)) return asIs({ skipped: "integer beyond 2^53 would change when re-serialized" });
- let index: ClaudeIndex;
- try { index = loadClaudeIndex(sessionId, home, stableIdsSince(dir)); } catch (error) { return asIs({ skipped: `thread index: ${String(error)}` }); }
- const selection = claudeSelection(sessionId, dir, claudeStartedAt(index), index.previous);
- const current = index.turns;
- const copies = new Map([...index.copies.values()].filter((copy) => copy.turn === null || copy.turn < current).map((copy) => [copy.key, copy.of]));
- let leaveOut = new Set(Object.keys(selection.unchecked));
- // v0.10: images of an interrupted turn without a feature line yet are sent once more (awaitingLine).
- const awaiting = new Set(selection.auto ? index.images.filter((image) => awaitingLine(index, image, current)).map((image) => image.key) : []);
- if (selection.auto) {
- const pinned = selection.pinned ?? {};
- leaveOut = new Set(index.images.filter((image) => image.replaceable && image.turn !== null && image.turn < current && !pinned[image.key] && !awaiting.has(image.key)).map((image) => image.key));
- }
- const pixels = (ref: RequestImage) => (ref.key ? index.byKey.get(ref.key)?.pixelSha256 : undefined) ?? pixelHashOfData(ref, ref.block.source.data);
- const lang = currentLang();
- // v0.5: after a compaction, the images from before it go back right after the summary (anthropic-messages/rewrite.ts): the ones
- // the user keeps sending (checked, or pinned with automatic selection) read from the transcript, the others as
- // placeholders. With any of those, the full note follows the summary, and later messages get only their short notes.
- // v0.8: each with what the model noted about it, for its placeholder.
- const compactedImages = index.images.filter((image) => image.compacted).map((image) => {
- // v0.10: as they stood at the compaction, so the list stays the same until the next one (claude-index.ts).
- const notes = index.compactedNotes.get(image.id);
- return notes ? { ...image, notes } : image;
- });
- const summaryIn = index.summary && compactedImages.length ? summaryAt(json.messages, index.summary) : null;
- const resend: Resend[] = summaryIn === null ? [] : compactedImages.filter((image) => !leaveOut.has(image.key)).flatMap((image) => {
- const data = claudeImageData(index, image);
- return data && image.mime ? [{ image, block: { type: "image", source: { type: "base64", media_type: image.mime, data } } }] : [];
- });
- const compactedOut = summaryIn !== null && resend.length < compactedImages.length;
- // v0.8: feature lines in every main conversation (a subagent's requests do not come here).
- const rewrote = rewriteMessages(json.messages, index, leaveOut, pixels, { lang, copies, noted: compactedOut, features: true, awaiting, ...(selection.auto ? { auto: { currentTurn: current } } : {}) });
- const report = rewrote.report;
- let messages = rewrote.messages;
- let compacted: Json | null = null;
- if (summaryIn !== null) {
- const added = addCompacted(messages, index.summary!, compactedImages, resend, { lang, auto: !!selection.auto });
- if (added.at !== null) {
- messages = added.messages;
- // The note's place: after the summary when it holds placeholders; a later one moves down with a message added.
- if (compactedOut) report.noteAt = added.at + 1;
- else if (added.inserted && report.noteAt !== undefined && report.noteAt > added.at) report.noteAt += 1;
- if (added.inserted && report.featureAt !== undefined && report.featureAt > added.at) report.featureAt += 1;
- compacted = { at: added.at, listed: compactedImages.length, resent: resend.map(({ image }) => image.id) };
- }
- }
- const summary: Json = {
- images: report.images,
- replaced: report.replaced.map(({ key: _key, ...rest }) => rest),
- locked: report.locked,
- sentImageHashes: report.sentContentIds.map((id) => id.slice(0, 16)),
- thinkingBlocks: json.messages.reduce((sum: number, message: Json) => sum + (Array.isArray(message?.content) ? message.content.filter((block: Json) => block?.type === "thinking" || block?.type === "redacted_thinking").length : 0), 0),
- ...(report.noteAt !== undefined ? { noteAt: report.noteAt } : {}),
- ...(selection.auto ? { auto: true } : {}),
- ...(report.copies.length ? { copies: report.copies } : {}),
- ...(compacted ? { compacted } : {}),
- ...(report.featureAt !== undefined ? { featureAt: report.featureAt, labeled: report.labeled ?? 0 } : {}),
- ...(report.unknown ? { unknown: report.unknown } : {}),
- ...(report.late ? { late: report.late } : {}),
- };
- const changed = report.replaced.length > 0 || report.copies.length > 0 || compacted !== null || report.featureAt !== undefined;
- // Once the engine has sent the session a changed history, thinking made after it may be in every later request, even
- // with nothing left out now (an image checked again).
- // Side requests (no tools: the desktop's status summary, auto mode's check) are not the conversation.
- const conversation = Array.isArray(json.tools) && json.tools.length > 0;
- if (!changed && !thinking?.edited) return { body: original, report: summary, attempts: [], ...(conversation ? { prefix: sentPrefixOf(json.messages) } : {}) };
- const rewritten = changed ? messages : json.messages;
- const fit = thinking ? fitThinking(json.messages, rewritten, thinking) : null;
- const history = fit && conversation ? fit.history : null;
- const experiment = env.CAM_EXPERIMENT_BLOCK_BINDING?.trim();
- // v0.10: the cache marks placed so this request reads what the ones before wrote, and the next one can read this
- // one after the images still sent as originals are left out (anthropic-messages/cache.ts): with automatic selection, the first
- // such image that is not pinned.
- const pinnedNow = selection.pinned ?? {};
- const volatileIn = (list: Json[]) => {
- const ref = selection.auto ? findRequestImages(list, index).find((found) => !(found.key && pinnedNow[found.key])) : undefined;
- return ref ? { message: ref.msg, block: ref.part } : null;
- };
- const encode = (list: Json[], extra: Json) => {
- const placed = conversation ? keepCacheRead(list, previous, marksOutside(json), volatileIn(list)) : { messages: list, marks: null };
- const out: Json = { ...json, messages: placed.messages };
- const asked = experiment && json.thinking && typeof json.thinking === "object";
- if (asked) out.thinking = { ...json.thinking, block_binding: { prefix_mismatch_behavior: experiment } };
- const next = Buffer.from(JSON.stringify(out), "utf8");
- const body = encodeBody(next, encoding);
- return { body, report: { ...summary, ...extra, ...(placed.marks ? { cacheMarks: placed.marks } : {}), ...(asked ? { experiment: { blockBinding: experiment, beta: "thinking-binding-controls-2026-08-01" } } : {}), decodedBefore: decoded.length, decodedAfter: next.length, encodedBefore: original.length, encodedAfter: body.length }, ...(conversation ? { prefix: sentPrefixOf(placed.messages) } : {}) };
- };
- const attempts: ClaudeAttempt[] = [];
- const made = fit?.made ?? [];
- const add = (list: Json[], extra: Json, sent: string, sure: boolean) => attempts.push({ ...encode(list, extra), history, sent: history ? sent : null, made, sure });
- const asBuilt = (extra: Json, sure: boolean) => attempts.push({ body: original, report: { ...summary, ...extra }, history, sent: history, made, sure, ...(conversation ? { prefix: sentPrefixOf(json.messages) } : {}) });
- if (!thinking?.strict) {
- if (changed) add(rewritten, {}, chainOf(rewritten), fit?.left === 0);
- else asBuilt({}, fit!.left === 0);
- }
- if (fit && (thinking!.strict || fit.left)) add(fit.messages, { thinking: { kept: fit.kept, left: fit.left }, ...(thinking!.strict ? {} : { retry: "thinking-signature" }) }, fit.sent, true);
- if (fit?.kept) {
- const bare = fitThinking(json.messages, rewritten, thinking!, false);
- add(bare.messages, { thinking: { kept: 0, left: bare.left }, retry: "thinking-signature" }, bare.sent, false);
- }
- if (changed || thinking?.strict) asBuilt(changed ? { fallback: "thinking-signature" } : {}, false);
- return { body: attempts[0].body, report: attempts[0].report, attempts };
-}
-
-// v0.4: a Claude Code session's panel reads and changes its images here: the panel page the engine serves
-// (/__cam/panel, panel.html with panel-web.js) and the Claude plugin's mod. The Codex panel goes through the plugin's
-// MCP server; under Claude Code that is not open to a panel (a mod reaches it only through Claude Code's tool
-// permissions, a prompt for every call, and Claude Code registers no app-only tool), so the engine, the one local HTTP
-// service, serves the panel. Loopback only, like everything the engine serves; only a request naming the engine by a
-// loopback name (no other site rebinding its name to 127.0.0.1), carrying our header, and coming from no other site's
-// page (a browser's Origin, when sent, is the engine's own).
-const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
-const LOOPBACK_HOST = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/;
-export function ownRequest(headers: IncomingHttpHeaders): boolean {
- const host = String(headers.host ?? "");
- if (!LOOPBACK_HOST.test(host)) return false;
- return headers.origin === undefined || headers.origin === `http://${host}`;
-}
-
-// The panel page for a Claude Code session: the same panel.html as in Codex, with panel-web.js before its own script.
-export function claudePanelPage(dir = here): string {
- const page = readFileSync(join(dir, "panel", "panel.html"), "utf8");
- const bridge = readFileSync(join(dir, "panel", "panel-web.js"), "utf8");
- const at = page.indexOf("<script>");
- if (at < 0) throw new Error("panel.html has no script");
- return `${page.slice(0, at)}<script>\n${bridge}\n</script>\n${page.slice(at)}`;
-}
-export const PANEL_PAGE_CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
-
-export function claudePanelApi(method: string, url: string, headers: IncomingHttpHeaders, body: string | null, options: ClaudePanelOptions & { panelLocaleFiles?: readonly string[] } = {}): { status: number; body: Json } {
- if (!ownRequest(headers) || headers["x-cam-panel"] !== "1") return { status: 403, body: { error: "forbidden" } };
- const parsed = new URL(url, "http://localhost");
- const session = parsed.searchParams.get("session") ?? "";
- if (!SESSION_ID.test(session)) return { status: 400, body: { error: "no session" } };
- const lang = claudePanelLanguage({ settingsFiles: options.panelLocaleFiles });
- try {
- if (method === "GET" && parsed.pathname === "/__cam/claude/panel") return { status: 200, body: { ...loadClaudePanelState(session, options), lang } };
- if (method === "GET" && parsed.pathname === "/__cam/claude/image") {
- const max = Number(parsed.searchParams.get("max") ?? 160);
- return { status: 200, body: claudeImageFor(session, String(parsed.searchParams.get("id") ?? ""), Number.isFinite(max) && max > 0 ? max : 160, options) };
- }
- if (method === "POST" && parsed.pathname === "/__cam/claude/select") {
- if (body === null) return { status: 413, body: { error: "too large" } };
- const change = JSON.parse(body || "{}");
- const list = (value: unknown) => (Array.isArray(value) ? value.map(String) : undefined);
- const state = applyClaudeSelection(session, { uncheck: list(change.uncheck), check: list(change.check), checkAll: change.checkAll === true, auto: typeof change.auto === "boolean" ? change.auto : undefined, mode: change.mode === "auto" ? "auto" : "manual" }, options);
- return { status: 200, body: { ...state, lang } };
- }
- return { status: 404, body: { error: "not found" } };
- } catch (error) {
- return { status: 400, body: { error: error instanceof Error ? error.message : String(error) } };
- }
-}
-
async function main(): Promise<void> {
migrateDataOnce(); // v0.1-15: Windows moved the data folder
// v0.6: tasks and sessions started from now on have automatic selection on by default (selection.ts).
@@ -621,7 +152,7 @@ async function main(): Promise<void> {
const dumpDir = process.argv.includes("--dump-requests") ? join(dataDir(), "p2", "requests") : null;
const sessionsDir = join(codexHome(), "sessions");
setPixelCache(pixelCacheDirOf());
- const via = outboundProxy();
+ const via = outboundProxy(process.env, readSystemProxy, UPSTREAM_HOST);
// v0.4: NO_PROXY may name one upstream host and not the other.
const vias = new Map([CLAUDE_HOST, OPENAI_API_HOST].map((host) => [host, outboundProxy(process.env, readSystemProxy, host)]));
const viaOf = (upstream: string) => {
diff --git a/spike/src/claude-panel.test.ts b/spike/src/claude-panel.test.ts
index a5eaeb3..6309740 100644
--- a/spike/src/claude-panel.test.ts
+++ b/spike/src/claude-panel.test.ts
@@ -11,7 +11,9 @@ import { join } from "node:path";
import test from "node:test";
import { claudeSelectionDirOf } from "../../plugin/src/core/paths.ts";
import { callClaudeTool, claudeToolsFor } from "../../plugin/src/plugin-server.ts";
-import { claudeNeedsRewrite, claudePanelApi, claudePanelPage, ownRequest, rewriteClaudeBody } from "../../plugin/src/proxy.ts";
+import { claudeNeedsRewrite, rewriteClaudeBody } from "../../plugin/src/adapters/claude/engine.ts";
+import { claudePanelApi, claudePanelPage } from "../../plugin/src/adapters/claude/panel-web.ts";
+import { ownRequest } from "../../plugin/src/core/engine/transport.ts";
import { ensureAutoDefault } from "../../plugin/src/selection.ts";
import { pngC, usualRequest, usualSession } from "./claude-fixtures.ts";
diff --git a/spike/src/codex-compaction.test.ts b/spike/src/codex-compaction.test.ts
index 29bf6fc..2d8c6e5 100644
--- a/spike/src/codex-compaction.test.ts
+++ b/spike/src/codex-compaction.test.ts
@@ -10,7 +10,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import zlib from "node:zlib";
-import { rewriteBody } from "../../plugin/src/proxy.ts";
+import { rewriteBody } from "../../plugin/src/adapters/codex/engine.ts";
import { addCodexCompacted } from "../../plugin/src/adapters/protocols/openai-responses/rewrite.ts";
import { compactList } from "../../plugin/src/core/words.ts";
import { writeSelection } from "../../plugin/src/selection.ts";
diff --git a/spike/src/feature-backfill.test.ts b/spike/src/feature-backfill.test.ts
index 580836a..acbf10c 100644
--- a/spike/src/feature-backfill.test.ts
+++ b/spike/src/feature-backfill.test.ts
@@ -10,7 +10,8 @@ import { join } from "node:path";
import test from "node:test";
import zlib from "node:zlib";
import { buildClaudeIndex } from "../../plugin/src/adapters/claude/claude-index.ts";
-import { rewriteBody, rewriteClaudeBody } from "../../plugin/src/proxy.ts";
+import { rewriteBody } from "../../plugin/src/adapters/codex/engine.ts";
+import { rewriteClaudeBody } from "../../plugin/src/adapters/claude/engine.ts";
import { featureNote } from "../../plugin/src/core/words.ts";
import { writeSelection } from "../../plugin/src/selection.ts";
import { awaitingLine, loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
diff --git a/spike/src/layers.test.ts b/spike/src/layers.test.ts
index a929d04..eeae1f8 100644
--- a/spike/src/layers.test.ts
+++ b/spike/src/layers.test.ts
@@ -1,7 +1,8 @@
// Purpose: v0.11 — keeps the plugin's three layers apart (docs/v0.11/plan.md 3.6). The core imports only the core;
// the panel only the core; a request-format translator (adapters/protocols) the core and other translators; a
-// platform (adapters/<name>) the core, the translators and its own files. Files at the top of plugin/src are the
-// entry points and the ones not sorted yet; they may import anything.
+// platform (adapters/<name>) the core, the translators and its own files, and the panel when it shows one (Codex
+// desktop, Claude Desktop). Files at the top of plugin/src are the entry points and the ones not sorted yet; they may
+// import anything.
// PENDING lists the imports that still break a rule while the split goes on. It may only shrink: a new break fails,
// and so does an entry that no longer occurs, so the list never keeps a stale exception.
// Input: the source files of plugin/src. Output: test results.
@@ -15,6 +16,11 @@ const src = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "plugin",
const PENDING = new Set<string>([
"adapters/claude/claude-index.ts -> adapters/codex/thread-index.ts",
+ "adapters/claude/engine.ts -> adapters/codex/thread-index.ts",
+ "adapters/claude/engine.ts -> language.ts",
+ "adapters/claude/engine.ts -> selection.ts",
+ "adapters/codex/engine.ts -> language.ts",
+ "adapters/codex/engine.ts -> selection.ts",
"adapters/codex/install.ts -> language.ts",
"adapters/codex/install.ts -> messages.ts",
"panel/panel-state.ts -> adapters/claude/claude-index.ts",
@@ -37,7 +43,8 @@ export function layerOf(file: string): Layer {
export function allowed(from: Layer, to: Layer): boolean {
if (from === "top") return true;
if (to === "core") return true;
- if (from === "protocols" || from.startsWith("adapter:")) return to === "protocols" || to === from;
+ if (from === "protocols") return to === "protocols";
+ if (from.startsWith("adapter:")) return to === "protocols" || to === "panel" || to === from;
return false;
}
@@ -71,6 +78,8 @@ test("layers: each folder is the layer the plan says", () => {
assert.equal(allowed("adapter:claude", "adapter:codex"), false);
assert.equal(allowed("adapter:claude", "protocols"), true);
assert.equal(allowed("protocols", "adapter:codex"), false);
+ assert.equal(allowed("protocols", "panel"), false);
+ assert.equal(allowed("adapter:claude", "panel"), true);
assert.equal(allowed("adapter:codex", "top"), false);
});
diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.ts
index 28a8c48..12e7c76 100644
--- a/spike/src/proxy.test.ts
+++ b/spike/src/proxy.test.ts
@@ -8,7 +8,10 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import zlib from "node:zlib";
-import { claudeIdentity, describeBody, forwardHeaders, hasUnsafeInteger, imageSizesOf, macProxy, needsRewrite, outboundProxy, redactImages, rewriteBody, requestIdentity, routeOf } from "../../plugin/src/proxy.ts";
+import { claudeIdentity } from "../../plugin/src/adapters/claude/engine.ts";
+import { describeBody, forwardHeaders, routeOf } from "../../plugin/src/proxy.ts";
+import { hasUnsafeInteger, macProxy, outboundProxy, redactImages } from "../../plugin/src/core/engine/transport.ts";
+import { imageSizesOf, needsRewrite, rewriteBody, requestIdentity } from "../../plugin/src/adapters/codex/engine.ts";
import { writeSelection } from "../../plugin/src/selection.ts";
import { png } from "./testkit.ts";
@@ -35,7 +38,7 @@ test("the macOS system proxy is read from scutil: HTTPS first, then HTTP, only w
test("NO_PROXY entries covering the upstream host mean a direct connection", () => {
for (const entry of ["chatgpt.com", ".chatgpt.com", "*"]) {
- assert.equal(outboundProxy({ HTTPS_PROXY: "http://127.0.0.1:8888", NO_PROXY: `localhost,${entry}` }, none), null);
+ assert.equal(outboundProxy({ HTTPS_PROXY: "http://127.0.0.1:8888", NO_PROXY: `localhost,${entry}` }, none, "chatgpt.com"), null);
}
});
@@ -232,7 +235,7 @@ test("Messages metadata counts images in user messages and tool results, and thi
});
test("the panel's last request is the session's conversation, not Claude Desktop's side requests in it", async () => {
- const { claudeConversationRequest } = await import("../../plugin/src/proxy.ts");
+ const { claudeConversationRequest } = await import("../../plugin/src/adapters/claude/engine.ts");
const tool = { name: "Read", description: "", input_schema: { type: "object" } };
// Claude Code's main loop: the conversation, with its tools.
const main = describeBody("/v1/messages", { model: "claude-sonnet-5-5", stream: true, tools: [tool, tool], messages: [{ role: "user", content: "hi" }] });
@@ -246,7 +249,7 @@ test("the panel's last request is the session's conversation, not Claude Desktop
test("v0.10: once the engine changes the history, a cache mark moves to where the request sent before had one", async () => {
const { usualSession, usualRequest } = await import("./claude-fixtures.ts");
- const { rewriteClaudeBody } = await import("../../plugin/src/proxy.ts");
+ const { rewriteClaudeBody } = await import("../../plugin/src/adapters/claude/engine.ts");
const home = mkdtempSync(join(tmpdir(), "cam-claude-home-"));
const dir = mkdtempSync(join(tmpdir(), "cam-claude-sel-"));
const session = "11111111-2222-4333-8444-555555555556";
@@ -279,7 +282,7 @@ test("v0.10: once the engine changes the history, a cache mark moves to where th
test("a Claude Code request is rewritten from the session's transcript and selection, with images also with nothing unchecked", async () => {
const { usualSession, usualRequest } = await import("./claude-fixtures.ts");
- const { claudeNeedsRewrite, rewriteClaudeBody, claudeImageSizes } = await import("../../plugin/src/proxy.ts");
+ const { claudeNeedsRewrite, rewriteClaudeBody, claudeImageSizes } = await import("../../plugin/src/adapters/claude/engine.ts");
const { buildClaudeIndex } = await import("../../plugin/src/adapters/claude/claude-index.ts");
const home = mkdtempSync(join(tmpdir(), "cam-claude-home-"));
const dir = mkdtempSync(join(tmpdir(), "cam-claude-sel-"));
@@ -317,7 +320,7 @@ test("a Claude Code request is rewritten from the session's transcript and selec
test("an account that refuses thinking after an edited history gets the rewrite without the thinking that no longer fits", async () => {
const { usualSession, usualRequest, text } = await import("./claude-fixtures.ts");
- const { rewriteClaudeBody } = await import("../../plugin/src/proxy.ts");
+ const { rewriteClaudeBody } = await import("../../plugin/src/adapters/claude/engine.ts");
const { newThinkingRecord, recordSent } = await import("../../plugin/src/adapters/protocols/anthropic-messages/thinking.ts");
const home = mkdtempSync(join(tmpdir(), "cam-claude-home-"));
const dir = mkdtempSync(join(tmpdir(), "cam-claude-sel-"));
@@ -375,7 +378,7 @@ test("an account that refuses thinking after an edited history gets the rewrite
});
test("Anthropic refusing the thinking after an edited history is told apart from other 400s", async () => {
- const { thinkingRejected } = await import("../../plugin/src/proxy.ts");
+ const { thinkingRejected } = await import("../../plugin/src/adapters/claude/engine.ts");
const rejected = JSON.stringify({ type: "error", error: { type: "invalid_request_error", message: "messages.3.content.0: Invalid `signature` in `thinking` block. The block is bound to a different conversation." } });
assert.equal(thinkingRejected(400, rejected), true);
assert.equal(thinkingRejected(400, JSON.stringify({ error: { message: "max_tokens: too large" } })), false);
@@ -384,7 +387,7 @@ test("Anthropic refusing the thinking after an edited history is told apart from
test("v0.5: after a compaction, the images from before it go back after the summary: sent again when kept, else placeholders", async () => {
const { image, pngA, pngB, pngC, text, transcript } = await import("./claude-fixtures.ts");
- const { claudeNeedsRewrite, rewriteClaudeBody } = await import("../../plugin/src/proxy.ts");
+ const { claudeNeedsRewrite, rewriteClaudeBody } = await import("../../plugin/src/adapters/claude/engine.ts");
const home = mkdtempSync(join(tmpdir(), "cam-claude-home-"));
const dir = mkdtempSync(join(tmpdir(), "cam-claude-sel-"));
const session = "11111111-2222-4333-8444-555555555555";
@@ -448,7 +451,7 @@ test("v0.5: after a compaction, the images from before it go back after the summ
test("v0.5: the request writing a second summary is rewritten as usual; after it, the images from before both go back", async () => {
const { image, pngA, pngB, text, transcript } = await import("./claude-fixtures.ts");
- const { rewriteClaudeBody } = await import("../../plugin/src/proxy.ts");
+ const { rewriteClaudeBody } = await import("../../plugin/src/adapters/claude/engine.ts");
const home = mkdtempSync(join(tmpdir(), "cam-claude-home-"));
const dir = mkdtempSync(join(tmpdir(), "cam-claude-sel-"));
const session = "11111111-2222-4333-8444-666666666666";
diff --git a/spike/src/selection.test.ts b/spike/src/selection.test.ts
index 61199e0..9764bf0 100644
--- a/spike/src/selection.test.ts
+++ b/spike/src/selection.test.ts
@@ -7,7 +7,7 @@ import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { needsRewrite } from "../../plugin/src/proxy.ts";
+import { needsRewrite } from "../../plugin/src/adapters/codex/engine.ts";
import { autoDefaultSince, effectiveSelection, ensureAutoDefault, ensureStableIds, mainTaskOf, readSelection, sideChatSelection, stableIdsSince, writeSelection } from "../../plugin/src/selection.ts";
import { startThread } from "./testfixtures.ts";