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.
TypeScript ai-agentsclaude-codeclaude-code-plugincodexcodex-plugincontext-managementdeveloper-toolsimage-generationmcpmultimodal
// Purpose: v0.1-5 — switch Codex between going through the engine and connecting directly. Shared by the command line
// (cam install / setup / uninstall), the panel's 启用 / 停用 buttons, and the engine's own check after the plugin was
// removed without 停用. Every change backs up config.toml first and replaces the file whole (write, then rename), so
// Codex never reads half a file. .env may hold credentials: it is never copied or printed.
// Input: ~/.codex/config.toml and ~/.codex/.env; the proxy variables Codex inherits; the plugin's folder in Codex's
// cache. Output: the same two files, and a backup under <data dir>/config-backup/.
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { codexHome, persistedEnv, proxyStatus, routedThroughEngine } from "./codexconfig.ts";
import { MARKETPLACE, PLUGIN, planInstall, planUninstall, pluginStatus, type Plan, type UserProxyEnv } from "./install.ts";
import { dataDir } from "../../core/paths.ts";
import { registerRoute, routeBaseUrl, validateBaseUrl } from "../../core/routes.ts";
export const codexFiles = () => ({ configFile: join(codexHome(), "config.toml"), envFile: join(codexHome(), ".env") });
export const readConfig = (): string => (existsSync(codexFiles().configFile) ? readFileSync(codexFiles().configFile, "utf8") : "");
export const readEnv = (): string | null => (existsSync(codexFiles().envFile) ? readFileSync(codexFiles().envFile, "utf8") : null);
// The proxy variables Codex will start with (the Windows registry; elsewhere the current environment).
export const userProxyEnv = (): UserProxyEnv => ({ httpProxy: persistedEnv("HTTPS_PROXY") ?? persistedEnv("HTTP_PROXY") ?? persistedEnv("ALL_PROXY"), noProxy: persistedEnv("NO_PROXY") });
export function backupConfig(): void {
const { configFile } = codexFiles();
if (!existsSync(configFile)) return;
const backups = join(dataDir(), "config-backup");
mkdirSync(backups, { recursive: true });
copyFileSync(configFile, join(backups, `config.toml.${new Date().toISOString().replaceAll(":", "-")}`));
}
function replaceFile(file: string, text: string): void {
writeFileSync(`${file}.cam-tmp`, text, "utf8");
try {
renameSync(`${file}.cam-tmp`, file);
} catch {
// Windows refuses the rename while another program has the file open; write it in place then.
writeFileSync(file, text, "utf8");
rmSync(`${file}.cam-tmp`, { force: true });
}
}
export function applyPlan(plan: Plan): void {
const { configFile, envFile } = codexFiles();
if (plan.configChanged) {
backupConfig();
replaceFile(configFile, plan.configText);
}
if (plan.envChanged) {
if (plan.envText === null) rmSync(envFile, { force: true });
else replaceFile(envFile, plan.envText);
}
}
// The install command validates before installing the plugin. A preview registers nothing and writes nothing.
export function planEngine(port: number, persistRoutes = false): Plan {
return planInstall({
configText: readConfig(), envText: readEnv(), env: userProxyEnv(), port,
// Persist the upstream before any config references its local URL. Auth settings stay with the provider.
routeBaseUrl: (baseUrl) => {
validateBaseUrl(baseUrl, port);
const id = persistRoutes ? registerRoute({ platform: "codex", baseUrl }).id : "0".repeat(32);
return routeBaseUrl(port, id);
},
});
}
// v0.11: whether the user wants Codex to go through the engine (enabled in the panel or by cam install, and not disabled
// since), kept apart from config.toml, which a provider switcher may rewrite (keepRouted).
const intentFile = () => join(dataDir(), "codex-engine.json");
export function wantsEngine(): boolean | null {
try { const on = JSON.parse(readFileSync(intentFile(), "utf8")).on; return typeof on === "boolean" ? on : null; } catch { return null; }
}
function rememberWish(on: boolean): void {
try { mkdirSync(dataDir(), { recursive: true }); writeFileSync(intentFile(), JSON.stringify({ on, at: new Date().toISOString() })); } catch { /* the next enable writes it again */ }
}
// Codex goes through the engine from its next start. Throws, changing nothing, when the user's own settings conflict.
export function useEngine(port: number): Plan {
const plan = planEngine(port, true);
applyPlan(plan);
rememberWish(true);
return plan;
}
// Codex connects directly again from its next start; only what this tool wrote is removed.
export function connectDirectly(): Plan {
const plan = planUninstall({ configText: readConfig(), envText: readEnv() });
applyPlan(plan);
rememberWish(false);
return plan;
}
export const usesEngine = (): boolean => proxyStatus(readConfig()).enabled;
// v0.11 (user 2026-11-02: switching models with a tool such as cc-switch must keep working, and so must the plugin): a
// switcher writes the new provider's address over ours. Codex is then pointed at the engine again, with a route to the
// provider the user just picked, so the switch stands and its requests still go through the engine. Only where the user
// wants the engine and the plugin is still there; a config that keeps changing back stops it (`recent`, the times it was
// done here lately: three in ten minutes).
export function shouldReroute(state: { wants: boolean | null; gone: string | null; routed: boolean; recent: number[] }, now = Date.now()): boolean {
if (state.wants !== true || state.gone || state.routed) return false;
return state.recent.filter((at) => now - at < 10 * 60_000).length < 3;
}
export function keepRouted(port: number, recent: number[]): { rerouted: boolean; error?: string } {
// An install from before v0.11 has no wish written: one routed now counts as wanted.
if (wantsEngine() === null && usesEngine()) rememberWish(true);
if (!shouldReroute({ wants: wantsEngine(), gone: pluginGone(), routed: routedThroughEngine(readConfig()), recent })) return { rerouted: false };
recent.push(Date.now());
try { useEngine(port); return { rerouted: true }; } catch (error) { return { rerouted: false, error: String(error) }; }
}
// Whether Codex no longer runs the plugin, judged only from clear signs: its folder in Codex's cache is gone
// (uninstalled), or config.toml turns it off. An entry Codex may some day write differently is not taken as a removal.
export function pluginGone(): "removed" | "disabled" | null {
const root = join(codexHome(), "plugins", "cache", MARKETPLACE, PLUGIN);
if (!existsSync(root) || !readdirSync(root).length) return "removed";
const status = pluginStatus(readConfig());
return status.installed && !status.enabled ? "disabled" : null;
}