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
feat(codex,dsh): keep working after a provider switch; dsh plugin as a bundle
chipfighter3272e9c8ee51
diff --git a/plugin/src/adapters/codex/codexconfig.ts b/plugin/src/adapters/codex/codexconfig.tsindex 7532903..5fac3b8 100644--- a/plugin/src/adapters/codex/codexconfig.ts+++ b/plugin/src/adapters/codex/codexconfig.ts@@ -285,6 +285,23 @@ export function proxyStatus(text: string): { enabled: boolean; url: string | nul};}+// v0.11: whether Codex's requests reach the engine: the managed block is there, and every endpoint setting points at+// the engine (its legacy path or a registered route). A tool that switches providers (cc-switch) rewrites the provider+// table and drops openai_base_url, which leaves the block's remains but sends Codex straight to the new provider.+export function routedThroughEngine(text: string): boolean {+ const { body, eol } = parts(text);+ const lines = body.split(eol);+ if (!lines.some((line) => line.trim() === BEGIN)) return false;+ const endpoints = upstreamSettings(lines);+ const engine = (value: string) => {+ try {+ const url = new URL(value);+ return url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) && (url.pathname.startsWith("/__cam/routes/") || url.pathname.startsWith("/backend-api/"));+ } catch { return false; }+ };+ return endpoints.some((setting) => setting.topLevel) && endpoints.every((setting) => engine(setting.line.value));+}+const LOOPBACK = ["localhost", "127.0.0.1", "::1"];const NO_PROXY_LINE = /^\s*(export\s+)?no_proxy\s*=/i;diff --git a/plugin/src/adapters/codex/setup.ts b/plugin/src/adapters/codex/setup.tsindex 95e28d5..8df16ec 100644--- a/plugin/src/adapters/codex/setup.ts+++ b/plugin/src/adapters/codex/setup.ts@@ -7,7 +7,7 @@import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";import { join } from "node:path";-import { codexHome, persistedEnv, proxyStatus } from "./codexconfig.ts";+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";@@ -63,10 +63,21 @@ export function planEngine(port: number, persistRoutes = false): Plan {});}+// 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;}@@ -74,11 +85,29 @@ export function useEngine(port: number): Plan {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 {diff --git a/plugin/src/adapters/dsh/cordis.patch.yml b/plugin/src/adapters/dsh/cordis.patch.ymlnew file mode 100644index 0000000..99a45ef--- /dev/null+++ b/plugin/src/adapters/dsh/cordis.patch.yml@@ -0,0 +1,10 @@+# Context Attachment Manager for DeepSeek Harness (index.js). dsh's own image offload (the dsh-base row+# `image-offload`) is turned off: this plugin does what it does, and also offloads earlier turns' images+# when a new turn starts. Both register the same message projection, so only one of them may run.++- id: image-offload+ disabled: true++- insert:+ - id: context-attachment-manager+ name: dsh-context-attachment-managerdiff --git a/plugin/src/adapters/dsh/index.js b/plugin/src/adapters/dsh/index.jsnew file mode 100644index 0000000..5697f67--- /dev/null+++ b/plugin/src/adapters/dsh/index.js@@ -0,0 +1,43 @@+// Purpose: v0.11 — DeepSeek Harness (dsh): automatic selection as a dsh plugin, in place of dsh's own+// `@deepseek-ai/dsh-compaction-image-offload` (docs/v0.11/plan.md 3.9). dsh keeps an image's offload as a durable mark+// in the session log (an `image/offload` event); every later request shows that image to the model as text naming the+// attachment and a read-only path it can read the image back from. dsh's plugin marks the oldest images only when a+// route refuses a request as over its image budget. This one does the same, and also, as a new turn starts, marks every+// image of the turns before it — what automatic selection does on the other platforms. The model reads an image back+// through its path when it needs it; what it reads is a new occurrence, kept for that turn and marked when the next one+// starts. Marks never revert, so the provider's cached prefix only moves forward. No request goes through the engine.+// Packaged as a dsh bundle (package.json, cordis.patch.yml): installing it turns dsh's own row off and adds this one.+// JavaScript, not TypeScript: dsh loads it with its own runtime. Written against dsh's docs and the source of its+// image-offload plugin (agent/pre-step, agent/request-error, compaction/summary-error, image/offload); not tested live.+// Input: dsh's events. Output: image/offload events in the session log.++import { IMAGE_OFFLOAD_REQUIRED_CODE, LlmError } from "@deepseek-ai/dsh-llm";+import { imageOffloadProjection } from "@deepseek-ai/dsh-compaction-image-offload/projection";+import { offloadImages, startsTurn } from "./offload.js";++export const name = "context-attachment-manager";+export const inject = ["agents", "sessions"];++export function apply(ctx) {+ ctx.sessions.registerMessageProjection(imageOffloadProjection);+ // The turn each agent was last in: a different one means a new turn starts, and its user messages are not on the+ // surface yet, so every image there belongs to an earlier turn (on a resumed session too).+ const turnOf = new WeakMap();+ ctx.on("agent/pre-step", ({ agent, turn, signal }, next) => {+ if (!signal.aborted && startsTurn(turnOf, agent, turn)) offloadImages(agent.session, agent.session.surface.nodes, Number.POSITIVE_INFINITY);+ return next();+ });+ // As dsh's own plugin: a route that refuses the request as over its image budget names how many more to mark. Kept,+ // because one turn alone (a browser driven step by step) can pass the budget.+ ctx.on("agent/request-error", ({ agent, failure, signal }, next) => {+ if (failure.code !== IMAGE_OFFLOAD_REQUIRED_CODE || failure.offloadImages === undefined || signal.aborted) return next();+ if (!offloadImages(agent.session, agent.session.surface.nodes, failure.offloadImages)) return next();+ return Promise.resolve({ kind: "retry" });+ });+ ctx.on("compaction/summary-error", ({ session, sourceEventSeqs, error, signal }, next) => {+ if (!(error instanceof LlmError) || error.code !== IMAGE_OFFLOAD_REQUIRED_CODE || error.failure?.offloadImages === undefined) return next();+ signal?.throwIfAborted();+ if (!offloadImages(session, sourceEventSeqs, error.failure.offloadImages)) return next();+ return true;+ });+}diff --git a/plugin/src/adapters/dsh/offload.js b/plugin/src/adapters/dsh/offload.jsnew file mode 100644index 0000000..2f93c2b--- /dev/null+++ b/plugin/src/adapters/dsh/offload.js@@ -0,0 +1,37 @@+// Purpose: v0.11 — what the dsh plugin (index.js) decides, apart from dsh itself so it can be tested without it: which+// image occurrences to mark as offloaded, and whether a step starts a new turn.+// Input: a dsh session (eventAt, deriveEventMessage, append) and its surface's event sequence numbers. Output: one+// image/offload event.++// Marks up to `count` retained input images, in request order (assistant messages hold no input images). Image indexes+// count every image of a message, marked ones included, as dsh's own plugin does. False when none was left.+export function offloadImages(session, seqs, count) {+ const targets = [];+ for (const seq of seqs) {+ if (count <= 0) break;+ const event = session.eventAt(seq);+ if (!event || (event.type !== "user/message" && event.type !== "tool/result")) continue;+ const message = session.deriveEventMessage(event);+ if (!message) continue;+ const imageIndexes = [];+ let index = 0;+ for (const block of message.content) {+ if (count <= 0) break;+ if (block.type !== "image") continue;+ if (block.offloaded !== true) { imageIndexes.push(index); count--; }+ index++;+ }+ if (imageIndexes.length) targets.push({ seq, imageIndexes });+ }+ if (!targets.length) return false;+ session.append("image/offload", { targets });+ return true;+}++// A new turn starts when the agent's turn differs from the one it was last in (the first step seen counts too: on a+// resumed session every image on the surface is from before).+export function startsTurn(turnOf, agent, turn) {+ if (turnOf.get(agent) === turn) return false;+ turnOf.set(agent, turn);+ return true;+}diff --git a/plugin/src/adapters/dsh/package.json b/plugin/src/adapters/dsh/package.jsonnew file mode 100644index 0000000..1109744--- /dev/null+++ b/plugin/src/adapters/dsh/package.json@@ -0,0 +1,19 @@+{+ "name": "dsh-context-attachment-manager",+ "version": "0.11.0",+ "description": "Context Attachment Manager for DeepSeek Harness: earlier turns' images leave the request at each new turn; the model reads one back when it needs it.",+ "type": "module",+ "main": "index.js",+ "files": ["index.js", "offload.js", "cordis.patch.yml"],+ "license": "MIT",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/chipfighter/context-attachment-manager.git",+ "directory": "plugin/src/adapters/dsh"+ },+ "peerDependencies": {+ "@deepseek-ai/dsh-llm": "*",+ "@deepseek-ai/dsh-compaction-image-offload": "*"+ },+ "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }+}diff --git a/plugin/src/adapters/dsh/plugin.ts b/plugin/src/adapters/dsh/plugin.tsdeleted file mode 100644index 6650cb3..0000000--- a/plugin/src/adapters/dsh/plugin.ts+++ /dev/null@@ -1,84 +0,0 @@-// Purpose: v0.11 — DeepSeek Harness (dsh): automatic selection as a dsh plugin, mounted in place of dsh's own-// `@deepseek-ai/dsh-compaction-image-offload` (docs/v0.11/plan.md 3.9). dsh keeps an image's offload as a durable mark-// in the session log (an `image/offload` event); every later request shows that image to the model as text naming the-// attachment and a read-only path it can read the image back from. dsh's plugin marks the oldest images only when a-// route refuses a request as over its image budget. This one does the same, and also, as a new turn starts, marks every-// image of the turns before it — what automatic selection does on the other platforms. The model reads an image back-// through its path when it needs it; what it reads is a new occurrence, kept for that turn and marked when the next one-// starts. Marks never revert, so the provider's cached prefix only moves forward. No request goes through the engine.-// Written against dsh's docs and the source of its image-offload plugin (agent/pre-step, agent/request-error,-// compaction/summary-error, image/offload); not tested live.-// Use: in the dsh composition (cordis.yml), replace the `@deepseek-ai/dsh-compaction-image-offload` row with one whose-// `name` is the path to this file (dsh loads a local plugin by its path: `name: './…/plugin.ts'`).-// Input: dsh's events. Output: image/offload events in the session log.--import { IMAGE_OFFLOAD_REQUIRED_CODE, LlmError } from "@deepseek-ai/dsh-llm";-import { imageOffloadProjection } from "@deepseek-ai/dsh-compaction-image-offload/projection";--type Seq = number;-type Block = { type: string; offloaded?: true };-type Session = {- eventAt(seq: Seq): { type: string } | undefined;- deriveEventMessage(event: { type: string }): { content: Block[] } | undefined;- append(type: "image/offload", payload: { targets: Array<{ seq: Seq; imageIndexes: number[] }> }): void;- surface: { nodes: readonly Seq[] };-};-type Agent = { session: Session };-type Context = {- sessions: { registerMessageProjection(projection: unknown): void };- on(event: string, listener: (payload: any, next: () => any) => any): void;-};--export const name = "context-attachment-manager";-export const inject = ["agents", "sessions"];--// Marks up to `count` retained input images, in request order (assistant messages hold no input images). Image indexes-// count every image of a message, marked ones included, as dsh's own plugin does. False when none was left.-export function offloadImages(session: Session, seqs: readonly Seq[], count: number): boolean {- const targets: Array<{ seq: Seq; imageIndexes: number[] }> = [];- for (const seq of seqs) {- if (count <= 0) break;- const event = session.eventAt(seq);- if (!event || (event.type !== "user/message" && event.type !== "tool/result")) continue;- const message = session.deriveEventMessage(event);- if (!message) continue;- const imageIndexes: number[] = [];- let index = 0;- for (const block of message.content) {- if (count <= 0) break;- if (block.type !== "image") continue;- if (block.offloaded !== true) { imageIndexes.push(index); count--; }- index++;- }- if (imageIndexes.length) targets.push({ seq, imageIndexes });- }- if (!targets.length) return false;- session.append("image/offload", { targets });- return true;-}--export function apply(ctx: Context): void {- ctx.sessions.registerMessageProjection(imageOffloadProjection);- // The turn each agent was last in: a different one means a new turn starts, and its user messages are not on the- // surface yet, so every image there belongs to an earlier turn (on a resumed session too).- const turnOf = new WeakMap<object, number>();- ctx.on("agent/pre-step", ({ agent, turn, signal }: { agent: Agent; turn: number; signal: AbortSignal }, next) => {- if (!signal.aborted && turnOf.get(agent) !== turn) {- turnOf.set(agent, turn);- offloadImages(agent.session, agent.session.surface.nodes, Number.POSITIVE_INFINITY);- }- return next();- });- // As dsh's own plugin: a route that refuses the request as over its image budget names how many more to mark.- ctx.on("agent/request-error", ({ agent, failure, signal }: { agent: Agent; failure: { code: string; offloadImages?: number }; signal: AbortSignal }, next) => {- if (failure.code !== IMAGE_OFFLOAD_REQUIRED_CODE || failure.offloadImages === undefined || signal.aborted) return next();- if (!offloadImages(agent.session, agent.session.surface.nodes, failure.offloadImages)) return next();- return Promise.resolve({ kind: "retry" });- });- ctx.on("compaction/summary-error", ({ session, sourceEventSeqs, error, signal }: { session: Session; sourceEventSeqs: readonly Seq[]; error: unknown; signal?: AbortSignal }, next) => {- if (!(error instanceof LlmError) || (error as any).code !== IMAGE_OFFLOAD_REQUIRED_CODE || (error as any).failure?.offloadImages === undefined) return next();- signal?.throwIfAborted();- if (!offloadImages(session, sourceEventSeqs, (error as any).failure.offloadImages)) return next();- return true;- });-}diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.tsindex ac96bdd..64dd18c 100644--- a/plugin/src/proxy.ts+++ b/plugin/src/proxy.ts@@ -22,7 +22,7 @@import http, { type IncomingHttpHeaders } from "node:http";import type net from "node:net";-import { mkdirSync, writeFileSync } from "node:fs";+import { mkdirSync, watch, writeFileSync } from "node:fs";import { join } from "node:path";import type { Duplex } from "node:stream";import { setTimeout as sleep } from "node:timers/promises";@@ -32,7 +32,7 @@ import { CLAUDE_HOST, claudeConversationRequest, claudeIdentity, claudeImageSizeimport { claudePanelApi, claudePanelPage, PANEL_PAGE_CSP } from "./adapters/claude/panel-web.ts";import { codexHome } from "./adapters/codex/codexconfig.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 { connectDirectly, keepRouted, pluginGone, usesEngine } from "./adapters/codex/setup.ts";import { setPixelCache } from "./core/pixels.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";@@ -215,7 +215,27 @@ async function main(): Promise<void> {log({ at: new Date().toISOString(), event: "plugin-check-failed", pid: process.pid, error: String(error) });}};- setInterval(() => checkPlugin(false), 15_000).unref();+ // v0.11: a provider switcher (cc-switch) wrote its provider over the engine's address: Codex is pointed at the engine+ // again, with a route to the provider the user picked (adapters/codex/setup.ts, keepRouted). Checked as soon as+ // config.toml changes, at start, and with the plugin check.+ const rerouted: number[] = [];+ let lastRerouteError = "";+ const reroute = (why: string) => {+ const result = keepRouted(port, rerouted);+ if (result.rerouted) log({ at: new Date().toISOString(), event: "codex-reroute", pid: process.pid, why });+ if (result.error && result.error !== lastRerouteError) log({ at: new Date().toISOString(), event: "codex-reroute-failed", pid: process.pid, why, error: result.error });+ lastRerouteError = result.error ?? "";+ };+ reroute("start");+ let settling: NodeJS.Timeout | null = null;+ try {+ watch(codexHome(), (_event, name) => {+ if (name !== "config.toml") return;+ if (settling) clearTimeout(settling);+ settling = setTimeout(() => { settling = null; reroute("config changed"); }, 1000);+ }).unref();+ } catch { /* no folder to watch yet: the periodic check still runs */ }+ setInterval(() => { checkPlugin(false); reroute("check"); }, 15_000).unref();watchForClients(() => {checkPlugin(true);log({ at: new Date().toISOString(), event: "engine-exit", pid: process.pid, reason: "no Codex or Claude Code process left, and no plugin service checked in" });diff --git a/spike/src/codexconfig.test.ts b/spike/src/codexconfig.test.tsindex 68f6683..54dd6da 100644--- a/spike/src/codexconfig.test.ts+++ b/spike/src/codexconfig.test.ts@@ -4,7 +4,8 @@import assert from "node:assert/strict";import test from "node:test";-import { coversLoopback, disableMcpServer, disableProxy, enableMcpServer, enableNoProxy, enableProxy, noProxyStatus, noProxyValue, proxyStatus } from "../../plugin/src/adapters/codex/codexconfig.ts";+import { coversLoopback, disableMcpServer, disableProxy, enableMcpServer, enableNoProxy, enableProxy, noProxyStatus, noProxyValue, proxyStatus, routedThroughEngine, BEGIN } from "../../plugin/src/adapters/codex/codexconfig.ts";+import { shouldReroute } from "../../plugin/src/adapters/codex/setup.ts";const URL = "http://localhost:17891/backend-api/codex";const withFeatures = 'model = "gpt-6-sol"\n\n[features]\nview_image = true\n\n[mcp_servers.demo]\ncommand = "node"\n';@@ -239,3 +240,36 @@ test("unsupported endpoint syntax fails before enabling or registering any proviassert.equal(proxyStatus(original).enabled, false);}});++// v0.11: cc-switch, on switching Codex's provider, deletes the top-level openai_base_url and writes its own+// [model_providers.custom] table whole (cc-switch live/project/codex.rs); the block's remains stay.+test("v0.11: a provider switcher's rewrite is seen as not routed; routing again keeps the provider it picked", () => {+ const route = (target: string) => `http://localhost:17892/__cam/routes/${target.includes("second") ? "b".repeat(32) : "a".repeat(32)}`;+ const user = 'model = "gpt-6"\nmodel_provider = "custom"\n\n[model_providers.custom]\nname = "custom"\nbase_url = "https://first.example/v1"\nexperimental_bearer_token = "sk-x"\n';+ const installed = enableProxy(user, URL, route).text;+ assert.equal(routedThroughEngine(installed), true);+ assert.equal(routedThroughEngine(user), false, "never installed");+ // What the switch leaves: our top line gone with openai_base_url, the provider table replaced.+ const switched = installed+ .split("\n").filter((line) => !line.startsWith("openai_base_url") && line !== BEGIN).join("\n")+ .replace(/\[model_providers\.custom\][^]*$/, '[model_providers.custom]\nname = "custom"\nbase_url = "https://second.example/v1"\nexperimental_bearer_token = "sk-y"\n');+ assert.equal(routedThroughEngine(switched), false);+ const again = enableProxy(switched, URL, route).text;+ assert.equal(routedThroughEngine(again), true);+ assert.ok(again.includes("https://second.example/v1"), "the provider the user picked is kept beside its route");+ assert.ok(again.includes(route("second")), "and requests go to it through the engine");+ assert.ok(again.includes('experimental_bearer_token = "sk-y"'), "its key stays where the switcher put it");+ assert.equal(routedThroughEngine(again.replace(`base_url = "${route("second")}"`, `base_url = "https://elsewhere.example/v1"`)), false, "one endpoint not through the engine is enough");+});++test("v0.11: Codex is routed again only when the user wants it, the plugin is there, and the config does not keep changing back", () => {+ const now = Date.now();+ const base = { wants: true as boolean | null, gone: null as string | null, routed: false, recent: [] as number[] };+ assert.equal(shouldReroute(base, now), true);+ assert.equal(shouldReroute({ ...base, routed: true }, now), false);+ assert.equal(shouldReroute({ ...base, wants: false }, now), false, "disabled in the panel");+ assert.equal(shouldReroute({ ...base, wants: null }, now), false, "never enabled");+ assert.equal(shouldReroute({ ...base, gone: "removed" }, now), false);+ assert.equal(shouldReroute({ ...base, recent: [now - 1000, now - 2000, now - 3000] }, now), false, "three times in ten minutes: something keeps changing it back");+ assert.equal(shouldReroute({ ...base, recent: [now - 11 * 60_000, now - 12 * 60_000, now - 13 * 60_000] }, now), true);+});diff --git a/spike/src/dsh.test.ts b/spike/src/dsh.test.tsnew file mode 100644index 0000000..04940ec--- /dev/null+++ b/spike/src/dsh.test.ts@@ -0,0 +1,50 @@+// Purpose: v0.11 — the DeepSeek Harness plugin's decisions (plugin/src/adapters/dsh/offload.js), on a fake dsh session:+// at a new turn every retained input image is marked, in request order, with dsh's own image indexes; a budget refusal+// marks only as many as it names; a step of the same turn marks nothing.+// Input: a fake session. Output: test results.+import assert from "node:assert/strict";+import test from "node:test";+import { offloadImages, startsTurn } from "../../plugin/src/adapters/dsh/offload.js";++type Block = { type: string; offloaded?: true };+const fakeSession = (events: Record<number, { type: string; content: Block[] }>) => {+ const appended: unknown[] = [];+ return {+ appended,+ session: {+ eventAt: (seq: number) => events[seq],+ deriveEventMessage: (event: { content: Block[] }) => ({ content: event.content }),+ append: (_type: string, payload: unknown) => appended.push(payload),+ },+ };+};+const image = (offloaded = false): Block => (offloaded ? { type: "image", offloaded: true } : { type: "image" });+const events = () => ({+ 1: { type: "user/message", content: [{ type: "text" }, image(true), image()] },+ 2: { type: "assistant/message", content: [image()] },+ 3: { type: "tool/result", content: [image(), { type: "text" }, image()] },+});++test("a new turn marks every retained input image, with indexes counting the ones already marked", () => {+ const { session, appended } = fakeSession(events());+ assert.equal(offloadImages(session, [1, 2, 3], Number.POSITIVE_INFINITY), true);+ assert.deepEqual(appended, [{ targets: [{ seq: 1, imageIndexes: [1] }, { seq: 3, imageIndexes: [0, 1] }] }]);+});++test("a budget refusal marks only as many as it names, oldest first; none left means no event", () => {+ const some = fakeSession(events());+ offloadImages(some.session, [1, 2, 3], 2);+ assert.deepEqual(some.appended, [{ targets: [{ seq: 1, imageIndexes: [1] }, { seq: 3, imageIndexes: [0] }] }]);+ const none = fakeSession({ 1: { type: "user/message", content: [image(true)] } });+ assert.equal(offloadImages(none.session, [1], Number.POSITIVE_INFINITY), false);+ assert.deepEqual(none.appended, []);+});++test("only the first step of a turn starts it", () => {+ const turns = new WeakMap<object, number>();+ const agent = {};+ assert.equal(startsTurn(turns, agent, 4), true, "the first step seen (a resumed session too)");+ assert.equal(startsTurn(turns, agent, 4), false, "a later step of the same turn");+ assert.equal(startsTurn(turns, agent, 5), true);+ assert.equal(startsTurn(turns, {}, 5), true, "each agent its own");+});diff --git a/spike/src/setup.test.ts b/spike/src/setup.test.tsindex a467d0f..ab37efd 100644--- a/spike/src/setup.test.ts+++ b/spike/src/setup.test.ts@@ -148,3 +148,27 @@ test("engine preflight rejects unsafe configuration without creating route data"assert.deepEqual(readdirSync(data), []);}});++// v0.11 (user 2026-11-02): a provider switcher (cc-switch) may rewrite config.toml; the engine routes Codex again,+// to the provider the switch picked, as long as the user wants the engine.+test("v0.11: after a provider switch rewrote config.toml, Codex goes through the engine again, to the new provider", (t) => {+ const { home } = tempHome(t);+ mkdirSync(join(home, "plugins", "cache", "codex-attachment-manager", "codex-attachment-manager", "0.11.0"), { recursive: true });+ writeFileSync(join(home, "config.toml"), CONFIG);+ useEngine(17891);+ assert.equal(setup.wantsEngine(), true);+ const recent: number[] = [];+ assert.deepEqual(setup.keepRouted(17891, recent), { rerouted: false }, "nothing to do while routed");+ // The switch: our lines gone, its provider in.+ const switched = readFileSync(join(home, "config.toml"), "utf8").split("\n").filter((line) => !line.startsWith("# >>>") && !line.startsWith("openai_base_url")).join("\n")+ + '\nmodel_provider = "custom"\n[model_providers.custom]\nname = "custom"\nbase_url = "https://picked.example/v1"\n';+ writeFileSync(join(home, "config.toml"), switched);+ assert.equal(setup.keepRouted(17891, recent).rerouted, true);+ const now = readFileSync(join(home, "config.toml"), "utf8");+ assert.match(now, /base_url = "http:\/\/localhost:17892\/__cam\/routes\/[0-9a-f]{32}"/);+ assert.ok(now.includes("https://picked.example/v1"), "the picked provider is kept as the route's destination");+ connectDirectly();+ assert.equal(setup.wantsEngine(), false);+ writeFileSync(join(home, "config.toml"), switched);+ assert.equal(setup.keepRouted(17891, recent).rerouted, false, "disabled by the user: left alone");+});