Skip to content

Stop paying the multimodal tax. Your AI agent keeps every image it has seen but only sends the ones it needs: lighter chats, no endless reconnecting, no starting over. Works with Codex, Claude Code, Cline, Gemini CLI, OpenCode, WorkBuddy and more. Install once, forget it.

feat(plugin): 插件服务的 Claude Code 模式

chipfighter9037f1ad931a
diff --git a/plugin/src/panel-state.ts b/plugin/src/panel-state.ts
index f885c0f..3de7b5c 100644
--- a/plugin/src/panel-state.ts
+++ b/plugin/src/panel-state.ts
@@ -9,10 +9,11 @@
// Input: thread id, the sessions directory (rollouts are only read) and the tool's data directory.
// Output: PanelState as plain JSON; selection changes are written to <data dir>/selection/.
+import { claudeHome, claudeImageData, loadClaudeIndex, type ClaudeIndex } from "./claude-index.ts";
import type { ImageSource } from "./images.ts";
-import { dataDir, requestStatsDirOf, selectionDirOf } from "./paths.ts";
+import { claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, requestStatsDirOf, selectionDirOf } from "./paths.ts";
import { readRequestStats, type RequestStats } from "./request-stats.ts";
-import { effectiveSelection, writeSelection, type Mark, type Selection } from "./selection.ts";
+import { effectiveSelection, readSelection, writeSelection, type Mark, type Selection } from "./selection.ts";
import { buildIndex, imageData, readThreadHistory, type IndexedImage, type ThreadIndex } from "./thread-index.ts";
import { threadTitle } from "./thread-names.ts";
import { pngThumbnail } from "./thumbnail.ts";
@@ -129,7 +130,12 @@ export function sameContent(index: ThreadIndex, image: IndexedImage): string[] {
// `unchecked`: the keys whose box is not ticked (v0.3: with automatic selection on, every image not pinned).
export function panelState(threadId: string, history: Record_[], index: ThreadIndex, unchecked: Set<string>, stats: RequestStats | null, title: string | null = null, auto = false): PanelState {
- const requested = requestedIds(history);
+ return panelStateOf(threadId, index, unchecked, stats, title, auto, requestedIds(history), history.length > 0);
+}
+
+// v0.4: the same for any index: Codex's (from a rollout) or Claude Code's (claude-index.ts), with the ids the model's
+// latest reply asked for and whether the conversation has started.
+export function panelStateOf(threadId: string, index: ThreadIndex, unchecked: Set<string>, stats: RequestStats | null, title: string | null, auto: boolean, requested: string[], started: boolean): PanelState {
const fetched = [...new Set([...index.copies.values()].filter((copy) => copy.turn !== null && copy.turn === index.turns).map((copy) => copy.of))];
const carried: Record<string, number> | null = stats?.lastHttp?.imageSizes ?? null;
// Images after the last one that request carried, or from a later turn, were added since and go out next time.
@@ -151,7 +157,7 @@ export function panelState(threadId: string, history: Record_[], index: ThreadIn
};
});
return {
- threadId, title, started: history.length > 0, historyMissing: false, turns: index.turns, images, requested, auto, fetched,
+ threadId, title, started, historyMissing: false, turns: index.turns, images, requested, auto, fetched,
totals: {
images: images.length,
unchecked: images.filter((image) => !image.checked).length,
@@ -199,8 +205,16 @@ export function loadPanelState(threadId: string, options: PanelOptions): PanelSt
// v0.3: `auto` switches automatic selection; with `mode: "auto"` a tick pins an image instead of sending it, each kept
// in its own record, so switching back finds the manual checks as they were.
-export function applySelection(threadId: string, change: { uncheck?: string[]; check?: string[]; checkAll?: boolean; auto?: boolean; mode?: "manual" | "auto" }, options: PanelOptions): PanelState {
+export type SelectionChange = { uncheck?: string[]; check?: string[]; checkAll?: boolean; auto?: boolean; mode?: "manual" | "auto" };
+export function applySelection(threadId: string, change: SelectionChange, options: PanelOptions): PanelState {
const { root, history, index, selection, stats, title, historyMissing } = load(threadId, options);
+ const next = changedSelection(threadId, index, selection, change);
+ writeSelection(next, selectionDirOf(root));
+ return { ...panelState(threadId, history, index, offKeys(index, next), stats, title, !!next.auto), historyMissing };
+}
+
+// The selection after a change; nothing is written.
+export function changedSelection(threadId: string, index: ThreadIndex, selection: Selection, change: SelectionChange): Selection {
const now = new Date().toISOString();
let next: Selection = { ...selection, threadId };
// Switched on for the first time, the thread is marked: from then on its history may hold copies the model fetched.
@@ -222,9 +236,7 @@ export function applySelection(threadId: string, change: { uncheck?: string[]; c
const image = imageOf(id);
if (pins) marks[image.key] = { id, at: now }; else delete marks[image.key];
}
- next = pins ? { ...next, pinned: marks } : { ...next, unchecked: marks };
- writeSelection(next, selectionDirOf(root));
- return { ...panelState(threadId, history, index, offKeys(index, next), stats, title, !!next.auto), historyMissing };
+ return pins ? { ...next, pinned: marks } : { ...next, unchecked: marks };
}
// One image for the panel: a PNG larger than maxSide is scaled down; smaller PNGs and other formats (which the
@@ -242,3 +254,41 @@ export function imageFor(threadId: string, id: string, maxSide: number, options:
// A PNG our decoder cannot read (e.g. interlaced) is still shown, just not scaled down first.
return { id, dataUrl: large ? pngThumbnail(data, maxSide) ?? original : original };
}
+
+// v0.4: the same for a Claude Code session, from its transcript (claude-index.ts) and the selection and statistics
+// kept for Claude sessions (paths.ts).
+export type ClaudePanelOptions = { dataRoot?: string; home?: string };
+
+function loadClaude(sessionId: string, options: ClaudePanelOptions) {
+ const root = options.dataRoot ?? dataDir();
+ const index = loadClaudeIndex(sessionId, options.home ?? claudeHome());
+ const selection = readSelection(sessionId, claudeSelectionDirOf(root));
+ const stats = readRequestStats(sessionId, claudeRequestStatsDirOf(root));
+ return { root, index, selection, stats };
+}
+
+const claudeState = (sessionId: string, index: ClaudeIndex, selection: Selection, stats: RequestStats | null): PanelState =>
+ panelStateOf(sessionId, index, offKeys(index, selection), stats, index.title, !!selection.auto, [...new Set(index.replies.flatMap(askedIn))], index.chain.length > 0);
+
+export function loadClaudePanelState(sessionId: string, options: ClaudePanelOptions = {}): PanelState {
+ const { index, selection, stats } = loadClaude(sessionId, options);
+ return claudeState(sessionId, index, selection, stats);
+}
+
+export function applyClaudeSelection(sessionId: string, change: SelectionChange, options: ClaudePanelOptions = {}): PanelState {
+ const { root, index, selection, stats } = loadClaude(sessionId, options);
+ const next = changedSelection(sessionId, index, selection, change);
+ writeSelection(next, claudeSelectionDirOf(root));
+ return claudeState(sessionId, index, next, stats);
+}
+
+export function claudeImageFor(sessionId: string, id: string, maxSide: number, options: ClaudePanelOptions = {}): { id: string; dataUrl: string | null } {
+ const index = loadClaudeIndex(sessionId, options.home ?? claudeHome());
+ const image = index.images.find((candidate) => candidate.id === id);
+ if (!image) throw new Error(`${id} is not an image of this session`);
+ const data = claudeImageData(index, image);
+ if (!data || !image.mime?.startsWith("image/")) return { id, dataUrl: null };
+ const original = `data:${image.mime};base64,${data}`;
+ const large = image.mime === "image/png" && Math.max(image.width ?? 0, image.height ?? 0) > maxSide;
+ return { id, dataUrl: large ? pngThumbnail(data, maxSide) ?? original : original };
+}
diff --git a/plugin/src/plugin-server.ts b/plugin/src/plugin-server.ts
index 85c4675..b332027 100644
--- a/plugin/src/plugin-server.ts
+++ b/plugin/src/plugin-server.ts
@@ -14,8 +14,12 @@
// v0.3 — cam_view_image, the one tool for the model: in a thread with automatic selection on, it returns the originals
// of images by id, each after a line naming it (rewrite.ts), so the index knows them as copies. Codex's code mode does
// not list plugin tools to the model; the model learns its name from the context note and looks it up.
-// Input: MCP JSON-RPC over stdio. Env: CAM_ENGINE_PORT (default 17891), CAM_NO_ENGINE=1 (tests), CAM_DATA_DIR.
-// Output: tool results; <data dir>/plugin-server.jsonl (events and counts only, no conversation content).
+// v0.4 — the same service under Claude Code (CAM_HOST=claude, set by the Claude plugin's manifest): it keeps the same
+// engine running, and serves the Claude plugin's mod (its panel and its routing, hooks/register.js) and the model's
+// cam_view_image for a Claude Code session, read from that session's transcript (claude-index.ts). The session is the
+// one the call names (the mod passes it), else the one Claude Code started this service for (CLAUDE_CODE_SESSION_ID).
+// 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";
@@ -23,15 +27,16 @@ import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
import { codexHome } from "./codexconfig.ts";
import { bindThread, isUserThread, newThreads, resolveThread } from "./binding.ts";
-import { DEFAULT_PORT, ensureEngine } from "./engine.ts";
+import { loadClaudeIndex } from "./claude-index.ts";
+import { DEFAULT_PORT, ensureEngine, type Health } from "./engine.ts";
import { isEntryPoint } from "./entry.ts";
import { currentLang, langOf, rememberLang, type Lang } from "./language.ts";
import { say } from "./messages.ts";
import { migrateDataOnce } from "./migrate-data.ts";
-import { applySelection, imageFor, loadPanelState, type PanelState } from "./panel-state.ts";
-import { dataDir, pixelCacheDirOf, selectionDirOf } from "./paths.ts";
+import { applyClaudeSelection, applySelection, claudeImageFor, imageFor, loadClaudePanelState, loadPanelState, type ClaudePanelOptions, type PanelState } from "./panel-state.ts";
+import { claudeSelectionDirOf, dataDir, pixelCacheDirOf, selectionDirOf } from "./paths.ts";
import { fetchedLabel, fetchWords } from "./rewrite.ts";
-import { effectiveSelection } from "./selection.ts";
+import { effectiveSelection, readSelection } from "./selection.ts";
import { connectDirectly, useEngine, usesEngine } from "./setup.ts";
import { hasRollout, loadThreadIndex, readThreadHistory, sessionMetaOf, setPixelCache } from "./thread-index.ts";
import { threadTitle } from "./thread-names.ts";
@@ -97,6 +102,11 @@ export function toolsFor(lang: Lang) {
}
export const TOOLS = toolsFor("zh");
+// v0.4: under Claude Code. Claude Code lists a plugin's tools to the model, so only the fetch tool is listed; the mod
+// calls the panel's tools (and cam_engine) by name, and the model cannot change the user's selection.
+export const HOST: "codex" | "claude" = process.env.CAM_HOST === "claude" ? "claude" : "codex";
+export const claudeToolsFor = (lang: Lang) => toolsFor(lang).filter((tool) => tool.name === "cam_view_image");
+
// A stack of pictures, drawn for light and dark themes (Codex takes https or data URLs only).
const ICON_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="6" width="14" height="14" rx="2.5"/><path d="M7 3h10.5A3.5 3.5 0 0 1 21 6.5V16"/><circle cx="8" cy="11" r="1.5"/><path d="m3.5 18 4.5-4.5 3 3 2-2 3.5 3.5"/></svg>';
const icon = (theme: "light" | "dark", color: string) => ({
@@ -112,8 +122,10 @@ export function readResource(uri: string): Json {
return { contents: [{ uri, mimeType: PANEL_MIME, text, _meta: { ui: { csp: { connectDomains: [], resourceDomains: [] }, prefersBorder: false } } }] };
}
-// Whether this instance last found the engine running; null until the first check (and in tests).
+// Whether this instance last found the engine running; null until the first check (and in tests). v0.4: and what the
+// engine said about itself then (the Claude plugin's mod switches only to an engine that forwards Claude's requests).
let engineRunning: boolean | null = null;
+let lastHealth: Health | null = null;
const enginePort = Number(process.env.CAM_ENGINE_PORT ?? DEFAULT_PORT);
// v0.1-5: whether config.toml points Codex at the engine, and whether that differs from what it said when this instance
// started (about when Codex read it): only a difference waits for a restart, so 停用 then 启用 again needs none.
@@ -229,6 +241,51 @@ export function callTool(name: string, args: Json, meta: Json | undefined, sessi
throw new Error(`unknown tool ${name}`);
}
+// v0.4: the tools under Claude Code. The mod reads results as JSON text: Claude Code hands a mod the content blocks,
+// and structuredContent only for tools that declare an output schema.
+const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+const asJson = (data: Json) => ({ content: [{ type: "text", text: JSON.stringify(data) }], structuredContent: data });
+
+export function callClaudeTool(name: string, args: Json, options: ClaudePanelOptions = {}, env: NodeJS.ProcessEnv = process.env): Json {
+ const lang = langOf(args.lang) ?? currentLang();
+ if (name === "cam_engine") return asJson({ port: enginePort, running: engineRunning, health: lastHealth, lang });
+ const sessionId = String(args.sessionId ?? env.CLAUDE_CODE_SESSION_ID ?? "");
+ if (!SESSION_ID.test(sessionId)) throw new Error(say(lang, "call.noThread"));
+ const panel = (state: PanelState) => asJson({ ...state, engineRunning, port: enginePort, lang });
+ if (name === "cam_panel") return panel(loadClaudePanelState(sessionId, options));
+ if (name === "cam_set_selection") {
+ return panel(applyClaudeSelection(sessionId, { uncheck: args.uncheck, check: args.check, checkAll: args.checkAll, auto: typeof args.auto === "boolean" ? args.auto : undefined, mode: args.mode === "auto" ? "auto" : "manual" }, options));
+ }
+ if (name === "cam_image") {
+ const image = claudeImageFor(sessionId, String(args.id), Number(args.maxSide ?? 160), options);
+ return asJson({ id: image.id, available: image.dataUrl !== null, dataUrl: image.dataUrl });
+ }
+ if (name === "cam_view_image") {
+ const words = fetchWords(lang);
+ const ids: string[] = Array.isArray(args.ids) ? args.ids.map(String) : typeof args.id === "string" ? [args.id] : [];
+ if (!readSelection(sessionId, claudeSelectionDirOf(options.dataRoot ?? dataDir())).auto) {
+ log({ event: "fetch", host: "claude", sessionId, ids, refused: "automatic selection is off" });
+ return { content: [{ type: "text", text: words.off }], isError: true };
+ }
+ const index = loadClaudeIndex(sessionId, options.home);
+ const content: Json[] = [];
+ const found: string[] = [];
+ for (const asked of ids) {
+ const id = asked.trim().toUpperCase();
+ const image = index.images.find((candidate) => candidate.id === id);
+ if (!image) { content.push({ type: "text", text: words.missing(asked) }); continue; }
+ const { dataUrl } = claudeImageFor(sessionId, id, Number.MAX_SAFE_INTEGER, options);
+ const parts = dataUrl ? /^data:([^;,]+);base64,(.*)$/s.exec(dataUrl) : null;
+ if (!parts) { content.push({ type: "text", text: words.unavailable(id) }); continue; }
+ content.push({ type: "text", text: fetchedLabel(image, lang) }, { type: "image", data: parts[2], mimeType: parts[1] });
+ found.push(id);
+ }
+ log({ event: "fetch", host: "claude", sessionId, ids, found });
+ return { content, isError: ids.length > 0 && !found.length };
+ }
+ throw new Error(`unknown tool ${name}`);
+}
+
function main(): void {
migrateDataOnce(); // v0.1-15: Windows moved the data folder
const send = (message: Json) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);
@@ -237,11 +294,12 @@ function main(): void {
if (process.env.CAM_NO_ENGINE === "1") return;
const result = await ensureEngine({ port: enginePort });
const replaced = result.replaced ? { replacedPid: result.replaced.pid, replacedBuild: result.replaced.build ?? null } : {};
- if (result.state !== "running" || engineState !== "running") log({ event: "engine", state: result.state, enginePid: result.health?.pid ?? null, build: result.health?.build ?? null, ...replaced });
+ if (result.state !== "running" || engineState !== "running") log({ event: "engine", host: HOST, state: result.state, enginePid: result.health?.pid ?? null, build: result.health?.build ?? null, ...replaced });
engineState = result.state;
engineRunning = result.state !== "failed";
+ lastHealth = result.health;
};
- log({ event: "start", ppid: process.ppid });
+ log({ event: "start", ppid: process.ppid, host: HOST });
setupState(); // what Codex read when it started this session
setPixelCache(pixelCacheDirOf());
// Codex starts several instances at once; a little jitter keeps them from racing to start the engine.
@@ -257,7 +315,7 @@ function main(): void {
if (method === "initialize") {
send({ id, result: { protocolVersion: params.protocolVersion ?? "2025-06-18", capabilities: { tools: {}, resources: {} }, serverInfo: serverInfo(currentLang()) } });
} else if (method === "tools/list") {
- send({ id, result: { tools: toolsFor(currentLang()) } });
+ send({ id, result: { tools: HOST === "claude" ? claudeToolsFor(currentLang()) : toolsFor(currentLang()) } });
} else if (method === "resources/list") {
send({ id, result: { resources: [{ uri: PANEL_URI, name: say(currentLang(), "resource.name"), mimeType: PANEL_MIME }] } });
} else if (method === "resources/templates/list") {
@@ -272,7 +330,7 @@ function main(): void {
} else if (method === "tools/call") {
const started = performance.now();
try {
- const result = callTool(params.name, params.arguments ?? {}, params._meta);
+ const result = HOST === "claude" ? callClaudeTool(params.name, params.arguments ?? {}) : callTool(params.name, params.arguments ?? {}, params._meta);
const ms = Math.round(performance.now() - started);
// The open panel reads its state every few seconds and loads each image once; only changes, and slow calls
// (v0.1-11), are worth a line.
diff --git a/spike/src/claude-panel.test.ts b/spike/src/claude-panel.test.ts
new file mode 100644
index 0000000..a893777
--- /dev/null
+++ b/spike/src/claude-panel.test.ts
@@ -0,0 +1,78 @@
+// Purpose: v0.4 — the plugin service under Claude Code (callClaudeTool in plugin-server.ts): the panel's data for a
+// session, checking and unchecking, images for thumbnails, automatic selection and the model's cam_view_image, all
+// from the session's transcript and the selection kept for Claude sessions.
+// Input: a synthetic transcript under a temporary Claude config dir and a temporary data dir; output: assertions only.
+
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { callClaudeTool, claudeToolsFor } from "../../plugin/src/plugin-server.ts";
+import { claudeSelectionDirOf } from "../../plugin/src/paths.ts";
+import { pngC, usualSession } from "./claude-fixtures.ts";
+
+process.env.CAM_LANG = "zh";
+const session = "11111111-2222-4333-8444-555555555555";
+
+function setup() {
+ const home = mkdtempSync(join(tmpdir(), "cam-claude-home-"));
+ const dataRoot = mkdtempSync(join(tmpdir(), "cam-claude-data-"));
+ const { t, p1 } = usualSession();
+ mkdirSync(join(home, "projects", "D--work"), { recursive: true });
+ writeFileSync(join(home, "projects", "D--work", `${session}.jsonl`), t.records.map((record) => JSON.stringify(record)).join("\n") + "\n");
+ return { options: { home, dataRoot }, p1 };
+}
+const json = (result: any) => JSON.parse(result.content[0].text);
+
+test("under Claude Code only the fetch tool is listed for the model", () => {
+ assert.deepEqual(claudeToolsFor("zh").map((tool) => tool.name), ["cam_view_image"]);
+});
+
+test("the panel's data for a session: images, turns, title, the ids the reply asked for", () => {
+ const { options } = setup();
+ const state = json(callClaudeTool("cam_panel", { sessionId: session }, options));
+ assert.deepEqual(state.images.map((image: any) => [image.id, image.kind, image.turn, image.checked]), [["IMG-001", "upload", 1, true], ["IMG-002", "upload", 1, true], ["IMG-003", "view", 2, true], ["IMG-004", "upload", 3, true]]);
+ assert.equal(state.title, "What are these?");
+ assert.equal(state.started, true);
+ assert.deepEqual(state.images[0].sameAs, ["IMG-004"]);
+ assert.equal(state.turns, 3);
+ assert.equal(state.auto, false);
+});
+
+test("unchecking and checking again are written to the Claude selection, by key", () => {
+ const { options, p1 } = setup();
+ const state = json(callClaudeTool("cam_set_selection", { sessionId: session, uncheck: ["IMG-002"] }, options));
+ assert.equal(state.totals.unchecked, 1);
+ const file = JSON.parse(readFileSync(join(claudeSelectionDirOf(options.dataRoot), `${session}.json`), "utf8"));
+ assert.deepEqual(Object.keys(file.unchecked), [`${p1}#1`]);
+ assert.equal(json(callClaudeTool("cam_set_selection", { sessionId: session, check: ["IMG-002"] }, options)).totals.unchecked, 0);
+ assert.throws(() => callClaudeTool("cam_panel", { sessionId: "not-a-session" }, options));
+});
+
+test("images for thumbnails come from the transcript", () => {
+ const { options } = setup();
+ const image = json(callClaudeTool("cam_image", { sessionId: session, id: "IMG-003", maxSide: 160 }, options));
+ assert.equal(image.available, true);
+ assert.equal(image.dataUrl, `data:image/png;base64,${pngC}`);
+});
+
+test("cam_view_image works only with automatic selection on, and returns the original after its label", () => {
+ const { options } = setup();
+ const off = callClaudeTool("cam_view_image", { sessionId: session, ids: ["IMG-003"] }, options);
+ assert.equal(off.isError, true);
+ assert.match(off.content[0].text, /没有开自动选图/);
+ callClaudeTool("cam_set_selection", { sessionId: session, auto: true }, options);
+ const on = callClaudeTool("cam_view_image", { sessionId: session, ids: ["img-003", "IMG-099"] }, options);
+ assert.equal(on.isError, false);
+ assert.match(on.content[0].text, /^\[图片 IMG-003 取回的原图|c\.png|工具查看的图片|第 2 轮|16×8\]$/);
+ assert.deepEqual(on.content[1], { type: "image", data: pngC, mimeType: "image/png" });
+ assert.match(on.content[2].text, /没有 IMG-099/);
+});
+
+test("the session comes from the call, else from the session Claude Code started the service for", () => {
+ const { options } = setup();
+ assert.equal(json(callClaudeTool("cam_panel", {}, options, { CLAUDE_CODE_SESSION_ID: session })).images.length, 4);
+ const engine = json(callClaudeTool("cam_engine", {}, options));
+ assert.equal(typeof engine.port, "number");
+});