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(proxy): 隔离平台路由并支持自定义中转
chipfighterb1c034a95c8b
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 7fb1e42..8b07d6d 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "codex-attachment-manager","displayName": "Context Attachment Manager",- "version": "0.8.3",+ "version": "0.9.0","description": "Choose which images from a Claude Code session's history go out with the next message. Unchecked images become short placeholders; the session and the conversation stay the same.","author": {"name": "chipfighter"diff --git a/.github/ISSUE_TEMPLATE/2-bug-report.yml b/.github/ISSUE_TEMPLATE/2-bug-report.ymlindex 79c99ea..f73673e 100644--- a/.github/ISSUE_TEMPLATE/2-bug-report.yml+++ b/.github/ISSUE_TEMPLATE/2-bug-report.yml@@ -37,7 +37,7 @@ body:id: pluginattributes:label: 插件版本 / Plugin version- placeholder: "0.8.3"+ placeholder: "0.9.0"- type: textareaid: whatattributes:diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 4c43b4c..7542416 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -43,4 +43,4 @@ jobs:run: node spike/src/plugin-smoke.ts# The one-line install and uninstall scripts of this platform, against a throwaway Codex home.- name: Install script smoke test- run: node spike/src/scripts-smoke.ts+ run: node spike/src/scripts-smoke.ts --upgradediff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8613581..300041b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,29 @@When a version is released, its section here becomes the GitHub release notes.+## [Unreleased]++Target: 0.9.0.++### Features++- Image management now works through compatible custom endpoints in Codex and Claude Desktop's Code tab. Codex's configured provider endpoints and Claude Code's original endpoint are preserved behind separate local routes, including their port, base path and query parameters. Model names and authentication remain with the client.+- Disabling Codex restores the original endpoint lines while preserving addresses the user changed afterwards. Claude Code only restores process variables it still manages.++### Fixes++- Claude requests outside `/v1/` no longer fall through to ChatGPT with their credentials. Unknown or conflicting requests are rejected locally. Fixes #10.+- Custom Claude endpoints use the Claude image rewrite rules regardless of their domain. HTTP and WebSocket forwarding follow the same provider binding and credential isolation.+- Registered routes use a separate loopback listener, so an older plugin copy cannot accept their requests after only one platform has been updated. Route bindings survive engine replacement.+- Upgrades preserve earlier runtime files that Codex's cache cleanup can partially remove while a Windows process is still using them. Installation no longer removes the working plugin before adding its replacement, and uses the install result to select the new version.++### Notes++- Supports Responses-compatible Codex endpoints and Anthropic-compatible Claude Code endpoints. This does not translate API protocols or add Bedrock, Vertex or Foundry transports.+- Codex reads endpoint settings in its user `config.toml`. Unsupported endpoint syntax stops setup before changing configuration. If another tool changes provider endpoints later, enable the plugin again and restart Codex to bind the new addresses. External profile files and environment overrides are not automatically rewritten.+- Verified on Windows with synthetic conversations, images, credentials and local upstreams. Live model calls through third-party gateways have not been tested.+- The real Windows install scripts were tested through installation, an upgrade with the old runtime directory held open, and uninstall. The old runtime remained intact and the user's configuration was restored.+## [0.8.3] - 2026-10-22A fix for Codex logged in with an API key.diff --git a/INSTALL.md b/INSTALL.mdindex 97c3122..d525b86 100644--- a/INSTALL.md+++ b/INSTALL.md@@ -34,7 +34,8 @@ What it changes in Codex:- Adds a marked proxy block to `~/.codex/config.toml`, after backing the file up.- If a proxy is set in your environment variables, adds a marked `NO_PROXY` block with local addresses only to `~/.codex/.env`.-- Nothing else. If you have set `openai_base_url` yourself, it stops without writing anything.+- If you use a custom `openai_base_url` or provider `base_url`, keeps the original endpoint beside a marked local route. Disabling restores it without replacing changes you made later.+- Leaves the provider's model, authentication and other settings in place.### Without a terminal@@ -58,6 +59,15 @@ Instead of the second command, you can also install it in the Code tab: click **Then start a new session in the Code tab. There is nothing to set up: the plugin doesn't edit any settings, and only points that session's own Claude Code process at the engine while it runs.+## Custom endpoints++Configure your gateway in the client first, as you would without this plugin. It must support image inputs, tool calls and the client's native API: Responses for Codex, or Anthropic Messages for Claude Code. The plugin manages images and forwards requests to that same endpoint; it does not convert between API formats. Claude support applies to the desktop app's **Code** tab.++- **Codex:** supports single-line `openai_base_url` and `model_providers.<name>.base_url` settings in your user `config.toml`, including normal provider tables and dotted keys. Unsupported endpoint syntax stops setup without changing the configuration. External profile files and environment overrides are not automatically rewritten. After a switching tool changes provider addresses, enable the plugin again (or run the install command again), then restart Codex.+- **Claude Code:** uses the process's original `ANTHROPIC_BASE_URL`, or Anthropic's official endpoint when absent. Start a new Code session after changing the endpoint. Bedrock, Vertex and Foundry keep their own transport and are not managed.++The engine listens only on loopback: port 17891 serves the panel and existing official connections; port 17892 serves registered provider routes. Both belong to the same engine process. With a custom engine port, provider routes use the next port. Keep both ports available. An older plugin copy cannot serve the registered routes; update both platform plugins for normal operation.+## Open the panel- **Codex**: open a task, click **Toggle side panel** at the top right, open a new tab with **+**, and choose **Context Assets** under **Plugins and MCPs**. If it isn't there, restart Codex once.diff --git a/README.md b/README.mdindex 9b546f9..14dd77c 100644--- a/README.md+++ b/README.md@@ -45,6 +45,8 @@ So I made a panel that keeps the conversation and drops the weight.Then just keep chatting. From the start, the model picks earlier images on its own; to pin one, click it and check **Send every turn**. To choose yourself, turn off **Auto-select** at the bottom of the panel.+Using a gateway? Compatible Codex and Claude Code endpoints can use image management too. Requests continue to the endpoint you configured, with the client's model and credentials. The gateway must support the client's API format, image inputs and tool calls; see [endpoint support](INSTALL.md#custom-endpoints).+## InstallPaste this to Codex, or to Claude in Claude Desktop's Code tab:diff --git a/README_CN.md b/README_CN.mdindex 9a69262..be64686 100644--- a/README_CN.md+++ b/README_CN.md@@ -45,6 +45,8 @@然后照常聊天就行。一开始,模型就会自己挑之前的图;想固定某张,点开它,勾上**每轮都发**。想自己选,就关掉面板底部的**自动选图**。+使用中转站时,兼容 Codex 或 Claude Code 的服务地址也能管理图片。请求仍发给你配置的服务,沿用客户端的模型和认证方式。中转站需要支持对应接口、图片输入和工具调用,详见 [服务地址支持范围](INSTALL.md#custom-endpoints)(英文)。+## 安装把这句话发给 Codex,或者 Claude 桌面版 Code 标签页里的 Claude:diff --git a/SECURITY.md b/SECURITY.mdindex 1854e31..eb7cc0e 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -12,8 +12,8 @@ Please include what you found, how to reproduce it, and the plugin version and p## What to look at-The plugin runs a local proxy (the engine) between Codex and OpenAI, and on install it edits `~/.codex/config.toml` (and `~/.codex/.env` when needed). Problems like these are especially worth reporting:+The plugin runs a local proxy (the engine) between Codex or Claude Code and the official or custom endpoint configured by the user. On install it edits `~/.codex/config.toml` (and `~/.codex/.env` when needed). Problems like these are especially worth reporting:-- The engine accepts connections from other machines, or forwards requests anywhere other than OpenAI.-- Credentials or conversation content end up in logs or in the data directory.+- The engine accepts connections from other machines, sends credentials to the other client's service, or forwards requests to a destination the user did not configure.+- Authentication headers or conversation content end up in logs or saved route records.- The install or uninstall scripts change more than INSTALL.md says.diff --git a/hooks/register.js b/hooks/register.jsindex 5821d7c..96e3dea 100644--- a/hooks/register.js+++ b/hooks/register.js@@ -1,10 +1,10 @@// Purpose: v0.4 — the Claude plugin's mod (docs/v0.4/plan.md). Two jobs; the rest is the plugin service's// (plugin/src/plugin-server.ts, CAM_HOST=claude) and the engine's:// 1. Routing. Claude Desktop starts Code sessions with ANTHROPIC_BASE_URL set and ignores settings files for it, so-// the mod points this Claude Code process at the engine with $.env.set once the engine answers and forwards Claude's-// requests (its health lists api.anthropic.com), before the first request where it can, and puts the original back-// when the process ends. It leaves a session alone that already uses another endpoint or a third-party provider.-// The subscription login is untouched: the engine forwards the same headers to api.anthropic.com.+// the mod registers this process's original upstream with the engine, then points this process at that explicit+// route with $.env.set, before the first request where it can. Official and Anthropic-compatible relay endpoints+// both work; Bedrock, Vertex and Foundry keep their native transport. Process-local settings are restored only+// while they still have the values this mod installed. Authentication stays with the registered upstream.// 2. The way to the panel. The panel is the Codex panel itself (plugin/src/panel.html), served by the engine as a page// for this session (proxy.ts, /__cam/panel): a mod draws only its own simple elements (no web page), and Claude// Code opens no MCP app for the user. /cam opens the page in Claude Desktop's own browser, beside the conversation@@ -27,6 +27,8 @@const PLUGIN = 'codex-attachment-manager'// The engine's port (engine.ts, DEFAULT_PORT); the plugin's MCP server starts the engine on it.const ENGINE_PORT = 17891+// Registered routes use a separate listener that an older engine cannot mistake for a ChatGPT request.+const ROUTING_PORT = ENGINE_PORT + 1const PANE = 'cam'const ROUTING = { plugin: 'codex-attachment-manager', key: 'routing' }// The model's image fetch, as Claude Code names the tool of this plugin's MCP server (.claude-plugin/plugin.json).@@ -50,7 +52,7 @@ const WORDS = {waiting: '正在等待本机引擎启动…','other-endpoint': '本会话使用别的服务地址,没有接管:勾选不会生效',provider: '本会话使用第三方模型服务,没有接管:勾选不会生效',- 'engine-old': '运行中的引擎版本较旧,不能转发 Claude 的请求:关掉 Codex 后运行 cam install,再开新会话',+ 'engine-old': '运行中的引擎版本较旧,不支持独立线路:关掉 Codex 后运行 cam install,再开新会话','no-engine': '本机引擎没有启动,本会话直连:勾选不会生效',failed: '切换请求地址没有成功,本会话直连:勾选不会生效',},@@ -66,7 +68,7 @@ const WORDS = {waiting: 'Waiting for the local engine…','other-endpoint': 'This session uses another endpoint and is left alone: checks have no effect',provider: 'This session uses a third-party provider and is left alone: checks have no effect',- 'engine-old': 'The running engine is too old to forward Claude requests: close Codex, run cam install, then start a new session',+ 'engine-old': 'The running engine is too old to use separate routes: close Codex, run cam install, then start a new session','no-engine': 'The local engine is not running; this session connects directly: checks have no effect',failed: 'Switching the endpoint failed; this session connects directly: checks have no effect',},@@ -121,21 +123,22 @@ const idle = (reason) => ({ active: false, port: null, originalBaseUrl: null, orasync function startRouting($, attempts = 60) {const saved = await readRouting($)// Already switched in this process (the module was reloaded): keep what it saved.- if (saved?.active) { routingState = saved; return true }+ if (saved?.active && saved.managedBaseUrl) { routingState = saved; return true }+ // An older mod pointed at the bare engine URL. Recover its upstream before registering an explicit route.+ if (saved?.active) await restoreRouting($)const current = await $.env.get('ANTHROPIC_BASE_URL')- if (current && !/^https:\/\/api\.anthropic\.com\/?$/.test(current)) { await writeRouting($, idle('other-endpoint')); return true }const providers = [await $.env.get('CLAUDE_CODE_USE_BEDROCK'), await $.env.get('CLAUDE_CODE_USE_VERTEX'), await $.env.get('CLAUDE_CODE_USE_FOUNDRY')]if (providers.some((value) => value && value !== '0')) { await writeRouting($, idle('provider')); return true }await writeRouting($, idle('waiting'))// The plugin's MCP server starts the engine with the session; wait for it to answer. An engine started by an older- // copy of the plugin (Codex's, not updated yet) does not forward Claude's requests: leave the session alone then.+ // copy of the plugin may only guess the upstream from the URL path: leave the session alone then.let port = nulllet reason = 'no-engine'for (let attempt = 0; attempt < attempts && port === null && reason !== 'engine-old'; attempt++) {try {const health = await $.http.fetch(`http://127.0.0.1:${ENGINE_PORT}/__cam/health`)const body = health.ok ? JSON.parse(health.text) : null- if (body?.service === PLUGIN && Array.isArray(body.upstreams) && body.upstreams.includes('api.anthropic.com')) port = ENGINE_PORT+ if (body?.service === PLUGIN && body.routingVersion >= 1 && body.routingPort === ROUTING_PORT) port = ENGINE_PORTelse if (body?.service === PLUGIN) reason = 'engine-old'} catch { /* the engine is still starting */ }if (port === null && reason !== 'engine-old') await $.clock.sleep(500)@@ -145,15 +148,34 @@ async function startRouting($, attempts = 60) {await writeRouting($, idle(reason))return true}+ let route+ try {+ const response = await $.http.fetch(`http://127.0.0.1:${port}/__cam/routes`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'x-cam-panel': '1' },+ body: JSON.stringify({ platform: 'claude', baseUrl: current || 'https://api.anthropic.com' }),+ })+ if (!response.ok) throw new Error('route registration failed')+ route = JSON.parse(response.text)+ if (typeof route.id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(route.id) || route.baseUrl !== `http://127.0.0.1:${ROUTING_PORT}/__cam/routes/${route.id}`) throw new Error('invalid route response')+ } catch {+ await writeRouting($, idle('failed'))+ return true+ }const originalNoProxy = await $.env.get('NO_PROXY')const originalNoProxyLower = await $.env.get('no_proxy')- const saving = { active: true, port, originalBaseUrl: current ?? null, originalNoProxy: originalNoProxy ?? null, originalNoProxyLower: originalNoProxyLower ?? null, reason: null }+ const saving = {+ active: true, port: ROUTING_PORT,+ originalBaseUrl: current ?? null, originalNoProxy: originalNoProxy ?? null, originalNoProxyLower: originalNoProxyLower ?? null,+ managedBaseUrl: route.baseUrl, managedNoProxy: loopbackAdded(originalNoProxy), managedNoProxyLower: loopbackAdded(originalNoProxyLower),+ reason: null,+ }await writeRouting($, saving)try {// Requests to the engine must not go through a system proxy.- await $.env.set('NO_PROXY', loopbackAdded(originalNoProxy))- await $.env.set('no_proxy', loopbackAdded(originalNoProxyLower))- await $.env.set('ANTHROPIC_BASE_URL', `http://127.0.0.1:${port}`)+ await $.env.set('NO_PROXY', saving.managedNoProxy)+ await $.env.set('no_proxy', saving.managedNoProxyLower)+ await $.env.set('ANTHROPIC_BASE_URL', saving.managedBaseUrl)} catch {await restoreRouting($)await writeRouting($, { ...saving, active: false, reason: 'failed' })@@ -164,9 +186,12 @@ async function startRouting($, attempts = 60) {async function restoreRouting($) {const saved = await readRouting($)if (!saved?.active) return- await $.env.set('ANTHROPIC_BASE_URL', saved.originalBaseUrl ?? undefined)- await $.env.set('NO_PROXY', saved.originalNoProxy ?? undefined)- await $.env.set('no_proxy', saved.originalNoProxyLower ?? undefined)+ const restore = async (name, managed, original) => {+ if (await $.env.get(name) === managed) await $.env.set(name, original ?? undefined)+ }+ await restore('ANTHROPIC_BASE_URL', saved.managedBaseUrl ?? `http://127.0.0.1:${saved.port}`, saved.originalBaseUrl)+ await restore('NO_PROXY', saved.managedNoProxy ?? loopbackAdded(saved.originalNoProxy), saved.originalNoProxy)+ await restore('no_proxy', saved.managedNoProxyLower ?? loopbackAdded(saved.originalNoProxyLower), saved.originalNoProxyLower)routingState = { ...saved, active: false, reason: null }await $.state.set(ROUTING, routingState)}diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.jsonindex 5f18c5a..edb4b52 100644--- a/plugin/.codex-plugin/plugin.json+++ b/plugin/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "codex-attachment-manager",- "version": "0.8.3",+ "version": "0.9.0","description": "Choose which images from a Codex task's history go out with the next message. Unchecked images become short placeholders; the task and the conversation stay the same.","author": {"name": "chipfighter"diff --git a/plugin/src/cam.ts b/plugin/src/cam.tsindex 7f82e8f..9ce835b 100644--- a/plugin/src/cam.ts+++ b/plugin/src/cam.ts@@ -23,10 +23,11 @@ import { isEntryPoint } from "./entry.ts";import { codexUiLocale, currentLang, storedLang, systemLang } from "./language.ts";import { say, type MessageKey } from "./messages.ts";import { migrateDataOnce } from "./migrate-data.ts";-import { MARKETPLACE, PLUGIN, PLUGIN_ID, planInstall, pluginStatus } from "./install.ts";+import { MARKETPLACE, PLUGIN, PLUGIN_ID, pluginStatus } from "./install.ts";import { applySelection, loadPanelState, type PanelState } from "./panel-state.ts";import { dataDir, selectionDirOf } from "./paths.ts";-import { backupConfig, connectDirectly, readConfig, readEnv, useEngine, userProxyEnv } from "./setup.ts";+import { preservingPluginCache } from "./plugin-cache.ts";+import { backupConfig, connectDirectly, planEngine, readConfig, readEnv, useEngine } from "./setup.ts";type Json = Record<string, any>;const lang = systemLang();@@ -146,15 +147,17 @@ async function main(): Promise<void> {const cli = findCodexCli();if (!cli) throw new Error(t("cli.noCli"));// A conflict with the user's own settings stops everything before anything changes.- try { planInstall({ configText: readConfig(), envText: readEnv(), env: userProxyEnv(), port }); } catch (error) { throw localized(error); }+ try { planEngine(port); } catch (error) { throw localized(error); }backupConfig();const steps: string[] = [];- const registered = pluginStatus(readConfig()).marketplace;- if (registered && !samePath(registered, repository)) { codex(cli, ["plugin", "marketplace", "remove", MARKETPLACE]); steps.push(t("cli.step.oldMarketplace")); }- if (!registered || !samePath(registered, repository)) { codex(cli, ["plugin", "marketplace", "add", repository]); steps.push(t("cli.step.addMarketplace")); }- // Installed afresh every time, so Codex's copy matches this checkout.- if (pluginStatus(readConfig()).installed) { codex(cli, ["plugin", "remove", PLUGIN_ID]); steps.push(t("cli.step.oldPlugin")); }- codex(cli, ["plugin", "add", PLUGIN_ID]);+ // Install the target version first. Removing first can partially delete a Windows runtime still in use.+ const cacheRoot = join(codexHome(), "plugins", "cache", MARKETPLACE, PLUGIN);+ preservingPluginCache(cacheRoot, pluginVersion(), () => {+ const registered = pluginStatus(readConfig()).marketplace;+ if (registered && !samePath(registered, repository)) { codex(cli, ["plugin", "marketplace", "remove", MARKETPLACE]); steps.push(t("cli.step.oldMarketplace")); }+ if (!registered || !samePath(registered, repository)) { codex(cli, ["plugin", "marketplace", "add", repository]); steps.push(t("cli.step.addMarketplace")); }+ codex(cli, ["plugin", "add", PLUGIN_ID]);+ });steps.push(t("cli.step.install"));const installed = pluginCacheDir(pluginVersion());const test = await selfTest(installed);diff --git a/plugin/src/codexconfig.ts b/plugin/src/codexconfig.tsindex 5f47369..7532903 100644--- a/plugin/src/codexconfig.ts+++ b/plugin/src/codexconfig.ts@@ -17,6 +17,8 @@ const conflict = (message: string, key: string, vars: Record<string, string> = {export const BEGIN = "# >>> codex-attachment-manager: managed proxy setting, remove it with the tool >>>";export const END = "# <<< codex-attachment-manager <<<";+// Original endpoint lines stay in config.toml, beside their temporary local route. No credentials are copied.+export const UPSTREAM_BEGIN = "# >>> codex-attachment-manager: managed upstream setting >>>";function parts(text: string): { bom: string; body: string; eol: string } {const bom = text.startsWith("") ? "" : "";@@ -28,16 +30,28 @@ const isTable = (line: string) => /^\s*\[/.test(line);// TOML top-level keys end at the first table header; a second top-level key would be a duplicate.function topLevelValue(lines: string[], key: string): string | null {+ let multiline: string | null = null;for (const line of lines) {- if (isTable(line)) return null;- const match = line.match(new RegExp(`^\\s*${key.replaceAll(".", "\\.")}\\s*=\\s*(.+?)\\s*(#.*)?$`));+ const inside = multiline !== null;+ const scanned = scanLine(line, multiline);+ multiline = scanned.multiline;+ if (inside) continue;+ if (isTable(scanned.code)) return null;+ const match = scanned.code.match(new RegExp(`^\\s*${key.replaceAll(".", "\\.")}\\s*=\\s*(.+?)\\s*$`));if (match) return match[1];}return null;}function featuresHeader(lines: string[]): number {- return lines.findIndex((line) => /^\s*\[features\]\s*(#.*)?$/.test(line));+ let multiline: string | null = null;+ for (let i = 0; i < lines.length; i++) {+ const inside = multiline !== null;+ const scanned = scanLine(lines[i], multiline);+ multiline = scanned.multiline;+ if (!inside && /^\s*\[features\]\s*$/.test(scanned.code)) return i;+ }+ return -1;}// The user's own respect_system_proxy, as a top-level dotted key or inside [features]; null when absent.@@ -60,7 +74,145 @@ export const MCP_BEGIN = "# >>> codex-attachment-manager: managed MCP server, re// Removes every managed block; the blank line enable adds after the top block goes with it.export function disableProxy(text: string): { text: string; changed: boolean } {- return removeBlocks(text, BEGIN);+ const restored = restoreUpstreams(text);+ const removed = removeBlocks(restored, BEGIN);+ return { text: removed.text, changed: removed.text !== text };+}++type EndpointLine = { prefix: string; key: string[]; value: string; suffix: string };+type AssignmentLine = Omit<EndpointLine, "value"> & { rawValue: string };++function stringValue(text: string): string | null {+ if (/^'[^']*'$/.test(text)) return text.slice(1, -1);+ if (!/^"(?:[^"\\]|\\.)*"$/.test(text)) return null;+ try { return JSON.parse(text); } catch { return null; }+}++function keyPath(text: string): string[] | null {+ const path: string[] = [];+ let rest = text.trim();+ while (rest) {+ const key = /^(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')/.exec(rest)?.[0];+ if (!key) return null;+ path.push(key[0] === '"' || key[0] === "'" ? stringValue(key)! : key);+ rest = rest.slice(key.length).trim();+ if (!rest) return path;+ if (rest[0] !== ".") return null;+ rest = rest.slice(1).trim();+ if (!rest) return null;+ }+ return null;+}++// Only scalar endpoint settings are edited, but surrounding multiline strings and comments must be recognized.+function scanLine(line: string, multiline: string | null): { code: string; multiline: string | null } {+ for (let i = 0; i < line.length; i++) {+ if (multiline) {+ const at = line.indexOf(multiline, i);+ if (at < 0) return { code: line, multiline };+ i = at + 2;+ multiline = null;+ } else if (line[i] === "#") return { code: line.slice(0, i), multiline };+ else if (line.startsWith('"""', i) || line.startsWith("'''", i)) { multiline = line.slice(i, i + 3); i += 2; }+ else if (line[i] === '"' || line[i] === "'") {+ const quote = line[i];+ while (++i < line.length) {+ if (quote === '"' && line[i] === "\\") i++;+ else if (line[i] === quote) break;+ }+ }+ }+ return { code: line, multiline };+}++function assignmentLine(line: string): AssignmentLine | null {+ const code = scanLine(line, null).code;+ // Find '=' outside quoted keys (a quoted provider name may itself contain '=').+ let equals = -1;+ let quote: string | null = null;+ for (let i = 0; i < code.length; i++) {+ if (quote) {+ if (quote === '"' && code[i] === "\\") i++;+ else if (code[i] === quote) quote = null;+ } else if (code[i] === '"' || code[i] === "'") quote = code[i];+ else if (code[i] === "=") { equals = i; break; }+ }+ if (equals < 0) return null;+ const key = keyPath(code.slice(0, equals));+ if (!key) return null;+ return { prefix: code.slice(0, equals + 1), key, rawValue: code.slice(equals + 1).trim(), suffix: line.slice(code.trimEnd().length) };+}++function endpointLine(line: string): EndpointLine | null {+ const assignment = assignmentLine(line);+ if (!assignment) return null;+ const value = stringValue(assignment.rawValue);+ if (value === null) return null;+ return { prefix: assignment.prefix, key: assignment.key, value, suffix: assignment.suffix };+}++function restoreUpstreams(text: string): string {+ const { bom, body, eol } = parts(text);+ const lines = body.split(eol);+ const kept: string[] = [];+ for (let i = 0; i < lines.length; i++) {+ if (lines[i].trim() !== UPSTREAM_BEGIN) { kept.push(lines[i]); continue; }+ const end = lines.findIndex((line, at) => at > i && line.trim() === END);+ if (end < 0) throw conflict("a managed upstream setting has no end marker", "conflict.noEnd");+ let original: string;+ let managed: string;+ try {+ original = JSON.parse(lines[i + 1].replace(/^# original: /, ""));+ managed = JSON.parse(lines[i + 2].replace(/^# managed: /, ""));+ if (typeof original !== "string" || typeof managed !== "string") throw new Error("invalid metadata");+ } catch { throw conflict("a managed upstream setting has invalid metadata", "conflict.noEnd"); }+ const current = lines.slice(i + 3, end);+ const expected = endpointLine(managed);+ for (const line of current) {+ const actual = endpointLine(line);+ if (actual && expected && actual.value === expected.value && JSON.stringify(actual.key) === JSON.stringify(expected.key)) kept.push(original);+ else kept.push(line); // The user's changed endpoint or additional lines win.+ }+ i = end;+ }+ return bom + kept.join(eol);+}++function upstreamSettings(lines: string[], strict = false): { index: number; line: EndpointLine; topLevel: boolean }[] {+ const found: { index: number; line: EndpointLine; topLevel: boolean }[] = [];+ let table: string[] = [];+ let multiline: string | null = null;+ for (let i = 0; i < lines.length; i++) {+ const wasMultiline = multiline !== null;+ const scanned = scanLine(lines[i], multiline);+ multiline = scanned.multiline;+ if (wasMultiline) continue;+ // An array table also ends the preceding provider table; its entries are not provider settings.+ if (/^\s*\[\[/.test(scanned.code)) { table = ["<array-table>"]; continue; }+ const header = /^\s*\[([^\[].*)\]\s*$/.exec(scanned.code.trim());+ if (header) { table = keyPath(header[1]) ?? []; continue; }+ const assignment = assignmentLine(lines[i]);+ if (!assignment) continue;+ const path = [...table, ...assignment.key];+ const endpoint = (path.length === 1 && path[0] === "openai_base_url") || (path.length === 3 && path[0] === "model_providers" && path[2] === "base_url");+ const inlineProvider = path[0] === "model_providers" && path.length < 3;+ const line = endpoint ? endpointLine(lines[i]) : null;+ if (strict && (inlineProvider || (endpoint && !line))) throw conflict("unsupported provider endpoint syntax; use a single-line endpoint setting", "conflict.endpointSyntax");+ if (!line) continue;+ found.push({ index: i, line, topLevel: path.length === 1 });+ }+ return found;+}++function routeUpstreams(lines: string[], route: (upstream: string) => string): void {+ let added = 0;+ for (const { index, line } of upstreamSettings(lines)) {+ const i = index + added;+ const managed = `${line.prefix} ${JSON.stringify(route(line.value))}${line.suffix}`;+ const block = [UPSTREAM_BEGIN, `# original: ${JSON.stringify(lines[i])}`, `# managed: ${JSON.stringify(managed)}`, managed, END];+ lines.splice(i, 1, ...block);+ added += block.length - 1;+ }}export function disableMcpServer(text: string): { text: string; changed: boolean } {@@ -95,17 +247,22 @@ function removeBlocks(text: string, begin: string): { text: string; changed: boo// Codex needs two settings to reach the proxy on Windows: openai_base_url (top level, so it goes first in the// file) and features.respect_system_proxy, without which Codex sends even localhost through HTTP(S)_PROXY.-export function enableProxy(text: string, url: string): { text: string; changed: boolean } {+export function enableProxy(text: string, url: string, routeBaseUrl?: (upstream: string) => string): { text: string; changed: boolean } {const { bom, body, eol } = parts(disableProxy(text).text);const lines = body.split(eol);- if (topLevelValue(lines, "openai_base_url") !== null) throw conflict("config.toml already sets openai_base_url; not overwriting it", "conflict.baseUrl");+ // Validate every relevant assignment before registering any route or emitting a managed config block.+ if (routeBaseUrl) upstreamSettings(lines, true);+ const customBaseUrl = topLevelValue(lines, "openai_base_url") !== null || upstreamSettings(lines).some((setting) => setting.topLevel);+ if (customBaseUrl && !routeBaseUrl) throw conflict("config.toml already sets openai_base_url; not overwriting it", "conflict.baseUrl");const own = userRespectSystemProxy(lines);if (own !== null && own !== "true") throw conflict("config.toml turns respect_system_proxy off; not overriding it", "conflict.systemProxy");const header = featuresHeader(lines);- const top = [BEGIN, `openai_base_url = "${url}"`];+ const top = [BEGIN];+ if (!customBaseUrl) top.push(`openai_base_url = "${url}"`);if (own === null && header < 0) top.push("features.respect_system_proxy = true");top.push(END, "");if (own === null && header >= 0) lines.splice(header + 1, 0, BEGIN, "respect_system_proxy = true", END);+ if (routeBaseUrl) routeUpstreams(lines, routeBaseUrl);const next = bom + top.join(eol) + eol + lines.join(eol);return { text: next, changed: next !== text };}@@ -115,15 +272,15 @@ export function proxyStatus(text: string): { enabled: boolean; url: string | nulconst lines = body.split(eol);const enabled = lines.some((line) => line.trim() === BEGIN);const begin = lines.findIndex((line) => line.trim() === BEGIN);- const urlLine = begin >= 0 ? lines.slice(begin).find((line) => /^\s*openai_base_url\s*=/.test(line)) : undefined;+ const endpoint = enabled ? upstreamSettings(lines).find((setting) => setting.topLevel)?.line.value : null;const base = parts(disableProxy(text).text);const baseLines = base.body.split(base.eol);const own = userRespectSystemProxy(baseLines);const managedRsp = enabled && lines.some((line, i) => /respect_system_proxy\s*=\s*true/.test(line) && lines.slice(0, i).reverse().find((l) => l.trim() === BEGIN || l.trim() === END)?.trim() === BEGIN);return {enabled,- url: urlLine ? (/"([^"]*)"/.exec(urlLine)?.[1] ?? null) : null,- conflict: topLevelValue(baseLines, "openai_base_url") !== null,+ url: endpoint ?? null,+ conflict: !enabled && (topLevelValue(baseLines, "openai_base_url") !== null || upstreamSettings(baseLines).some((setting) => setting.topLevel)),respectSystemProxy: managedRsp ? "managed" : own === "true" ? "user" : own !== null ? "off" : "absent",};}diff --git a/plugin/src/engine.ts b/plugin/src/engine.tsindex 2187dee..241a1cf 100644--- a/plugin/src/engine.ts+++ b/plugin/src/engine.ts@@ -18,7 +18,7 @@ export const DEFAULT_PORT = 17891;const here = dirname(fileURLToPath(import.meta.url));// build and version are missing on engines from before v0.1-3.-export type Health = { ok: true; service: string; pid: number; startedAt: string; port: number; build?: string | null; version?: string | null };+export type Health = { ok: true; service: string; pid: number; startedAt: string; port: number; build?: string | null; version?: string | null; routingVersion?: number; routingPort?: number };export type EngineState = "running" | "started" | "replaced" | "failed";export function isEngineHealth(value: unknown): value is Health {diff --git a/plugin/src/install.ts b/plugin/src/install.tsindex 64b9724..aed62f9 100644--- a/plugin/src/install.ts+++ b/plugin/src/install.ts@@ -23,9 +23,9 @@ export function needsNoProxy(env: UserProxyEnv): boolean {return !!env.httpProxy && !coversLoopback(env.noProxy);}-export function planInstall(input: { configText: string; envText: string | null; env: UserProxyEnv; port: number }): Plan {+export function planInstall(input: { configText: string; envText: string | null; env: UserProxyEnv; port: number; routeBaseUrl?: (upstream: string) => string }): Plan {const notes: string[] = [];- const proxied = enableProxy(input.configText, `http://localhost:${input.port}/backend-api/codex`);+ const proxied = enableProxy(input.configText, `http://localhost:${input.port}/backend-api/codex`, input.routeBaseUrl);const legacy = disableMcpServer(proxied.text);if (legacy.changed) notes.push(say(systemLang(), "note.legacyMcp"));let envText = input.envText;diff --git a/plugin/src/messages.ts b/plugin/src/messages.tsindex 710f2c2..3afe4ad 100644--- a/plugin/src/messages.ts+++ b/plugin/src/messages.ts@@ -37,6 +37,12 @@ const zh = {"call.imageNone": "无法显示",// A setting of the user's that the tool does not overwrite (codexconfig.ts)."conflict.baseUrl": "config.toml 里已经设置了 openai_base_url,没有覆盖它。",+ "conflict.endpointSyntax": "无法安全接管这种供应商配置写法,配置未修改。请使用单行服务地址设置。",+ "conflict.proxyLoop": "服务地址指向插件引擎自身,配置未修改。",+ "conflict.endpointUrl": "服务地址无效,配置未修改。请使用不含账号密码和片段标记的 HTTP 或 HTTPS 地址。",+ "proxy.unknownRoute": "无法识别服务线路,或请求的平台标识与线路不一致。",+ "proxy.invalidRoute": "服务线路登记无效。",+ "proxy.isolatedRoute": "此服务线路需要使用独立的本机入口。","conflict.systemProxy": "config.toml 关掉了 respect_system_proxy,没有改动它。","conflict.noProxy": ".env 里已经设置了 NO_PROXY,没有覆盖它。","conflict.mcpServer": "config.toml 里已经有名为 {name} 的 MCP 服务,没有覆盖它。",@@ -106,6 +112,12 @@ const en: Record<keyof typeof zh, string> = {"call.imageOk": "ok","call.imageNone": "cannot be shown","conflict.baseUrl": "config.toml already sets openai_base_url; it was left as it is.",+ "conflict.endpointSyntax": "This provider configuration cannot be safely routed; nothing was changed. Use a single-line endpoint setting.",+ "conflict.proxyLoop": "The endpoint points back to the plugin engine; nothing was changed.",+ "conflict.endpointUrl": "Invalid endpoint; nothing was changed. Use an HTTP or HTTPS URL without embedded credentials or a fragment.",+ "proxy.unknownRoute": "Unrecognized provider route or conflicting client identity.",+ "proxy.invalidRoute": "Invalid provider route registration.",+ "proxy.isolatedRoute": "This provider route requires its dedicated local listener.","conflict.systemProxy": "config.toml turns respect_system_proxy off; it was left as it is.","conflict.noProxy": ".env already sets NO_PROXY; it was left as it is.","conflict.mcpServer": "config.toml already has an MCP server named {name}; it was left as it is.",diff --git a/plugin/src/panel.html b/plugin/src/panel.htmlindex 5297493..ee1a01c 100644--- a/plugin/src/panel.html+++ b/plugin/src/panel.html@@ -1435,7 +1435,7 @@// ---- start: handshake, then Codex sends its own cam_panel result; poll so new images show up ----if (window.matchMedia?.("(prefers-color-scheme: dark)").matches) document.documentElement.dataset.theme = "dark";applyLanguage();- request("ui/initialize", { protocolVersion: "2026-01-26", appInfo: { name: "codex-attachment-manager", version: "0.8.3" }, appCapabilities: {} })+ request("ui/initialize", { protocolVersion: "2026-01-26", appInfo: { name: "codex-attachment-manager", version: "0.9.0" }, appCapabilities: {} }).then((init) => { applyHost(init?.hostContext); post({ method: "ui/notifications/initialized", params: {} }); reportFrame(); }).catch(() => {}).finally(() => setTimeout(() => { if (!S.data) refresh(); }, 1200));diff --git a/plugin/src/plugin-cache.ts b/plugin/src/plugin-cache.tsnew file mode 100644index 0000000..10a80eb--- /dev/null+++ b/plugin/src/plugin-cache.ts@@ -0,0 +1,23 @@+// Codex may clean old cache contents even when Windows prevents removing the directory of a running plugin.+// Preserve program files before installation; restore older runtimes and restore the target too on failure.+import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++export function preservingPluginCache<T>(root: string, targetVersion: string, install: () => T): T {+ const versions = existsSync(root) ? readdirSync(root, { withFileTypes: true }).filter(entry => entry.isDirectory() && /^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(entry.name)).map(entry => entry.name) : [];+ const backup = versions.length ? mkdtempSync(join(tmpdir(), "cam-runtime-backup-")) : null;+ for (const version of versions) cpSync(join(root, version), join(backup!, version), { recursive: true });+ let succeeded = false;+ try {+ const result = install();+ succeeded = true;+ return result;+ } finally {+ for (const version of versions) {+ if (succeeded && version === targetVersion) continue;+ mkdirSync(join(root, version), { recursive: true });+ cpSync(join(backup!, version), join(root, version), { recursive: true, force: true });+ }+ }+}diff --git a/plugin/src/plugin-server.ts b/plugin/src/plugin-server.tsindex bc3e3ac..fabdedc 100644--- a/plugin/src/plugin-server.ts+++ b/plugin/src/plugin-server.ts@@ -116,7 +116,7 @@ const icon = (theme: "light" | "dark", color: string) => ({src: `data:image/svg+xml;base64,${Buffer.from(ICON_SVG.replace("currentColor", color)).toString("base64")}`,mimeType: "image/svg+xml", sizes: ["any"], theme,});-export const serverInfo = (lang: Lang) => ({ name: "codex-attachment-manager", title: say(lang, "server.title"), version: "0.8.3", icons: [icon("light", "#5d5d5d"), icon("dark", "#cdcdcd")] });+export const serverInfo = (lang: Lang) => ({ name: "codex-attachment-manager", title: say(lang, "server.title"), version: "0.9.0", icons: [icon("light", "#5d5d5d"), icon("dark", "#cdcdcd")] });export function readResource(uri: string): Json {if (uri !== PANEL_URI) throw new Error(`unknown resource ${uri}`);diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.tsindex 2be4a8a..60b6dd5 100644--- a/plugin/src/proxy.ts+++ b/plugin/src/proxy.ts@@ -8,9 +8,9 @@// v0.1-14: the text for the model is in the language the panel last reported (Codex's interface language).// v0.3: automatic selection — a thread with it on leaves out the images of earlier turns that are not pinned, and a// copy the model fetched is sent in its own turn only (spec v0.3).-// v0.4: Claude Code too (the plugin's mod points ANTHROPIC_BASE_URL here): its /v1/… requests go to api.anthropic.com,-// everything else to chatgpt.com as before. A Claude session is told apart by x-claude-code-session-id.+// v0.4: Claude Code too. Older clients are recognized by their own headers; ambiguous legacy requests are refused.// 2026-10-22: Codex logged in with an API key goes to api.openai.com/v1 instead (see routeOf).+// v0.9: registered providers bind the client protocol and original endpoint, with a separate listener for new routes.// Only metadata is logged (never auth headers or conversation content).// Input: [--port 17891] [--stay (no auto-exit)] [--force-http] [--dump-requests (synthetic test threads only)];// the outbound proxy is taken from HTTPS_PROXY/HTTP_PROXY or the system proxy settings (Windows, macOS).@@ -36,9 +36,11 @@ import { findImages, type ImageRef } from "./images.ts";import { isEntryPoint } from "./entry.ts";import { currentLang } from "./language.ts";import { migrateDataOnce } from "./migrate-data.ts";+import { say } from "./messages.ts";import { applyClaudeSelection, claudeImageFor, loadClaudePanelState, type ClaudePanelOptions } from "./panel-state.ts";import { claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, pixelCacheDirOf, proxyLogDirOf, selectionDirOf } from "./paths.ts";import { recordRequest } from "./request-stats.ts";+import { readRoute, registerRoute, routeBaseUrl, routingPort, validateBaseUrl, type Platform } from "./routes.ts";import { rewriteItems, type Described } from "./rewrite.ts";import { connectDirectly, pluginGone, usesEngine } from "./setup.ts";import { claudeSelection, effectiveSelection, ensureAutoDefault, selectionDir, sideChatSelection } from "./selection.ts";@@ -54,19 +56,37 @@ 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's requests all start with /backend-api/ (its base URL ends in /backend-api/codex); Claude Code's with /v1/.-export function upstreamOf(path: string): string {- return path.startsWith("/v1/") ? CLAUDE_HOST : UPSTREAM_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/// becoming /v1/ (2026-10-22, seen with a fake key against a local server). The request bodies are the same Responses// requests, so they are rewritten as before.-export function routeOf(url: string, headers: IncomingHttpHeaders): { host: string; url: string } {+export type ForwardRoute = { host: string; url: string; platform?: Platform; protocol?: string; port?: number; clientPath?: string };+export function routeOf(url: string, headers: IncomingHttpHeaders, root = dataDir()): ForwardRoute | null {+ const claude = !!(headers["x-claude-code-session-id"] || headers["anthropic-version"] || headers["anthropic-beta"] || /^Bearer sk-ant-/i.test(String(headers.authorization ?? "")));+ const codex = !!(headers["chatgpt-account-id"] || headers["x-codex-turn-metadata"] || headers["x-codex-window-id"]);+ if (!url.startsWith("/") || /[\r\n\\]/.test(url)) return null;+ if (url.startsWith("/__cam/routes/")) {+ const match = /^\/__cam\/routes\/([a-f0-9]{32})(\/[^]*|\?[^]*|$)/.exec(url);+ const registered = match ? readRoute(match[1], root) : null;+ if (!registered || (registered.platform === "codex" && !!headers["x-claude-code-session-id"]) || (registered.platform === "claude" && codex)) return null;+ const target = validateBaseUrl(registered.baseUrl);+ const suffix = match![2] || "/";+ const at = suffix.indexOf("?");+ const clientPath = at < 0 ? suffix : suffix.slice(0, at) || "/";+ const query = [target.search.slice(1), at < 0 ? "" : suffix.slice(at + 1)].filter(Boolean).join("&");+ const path = `${target.pathname.replace(/\/$/, "")}/${clientPath.replace(/^\//, "")}`;+ return { host: target.hostname.replace(/^\[|\]$/g, ""), url: path + (query ? `?${query}` : ""), platform: registered.platform, protocol: target.protocol, port: Number(target.port || (target.protocol === "https:" ? 443 : 80)), clientPath };+ }+ if ((claude || headers["x-api-key"]) && codex) return null;+ if (claude || headers["x-api-key"]) {+ if (url.startsWith("/backend-api/")) return null;+ return { host: CLAUDE_HOST, url };+ }+ if (url.startsWith("/v1/")) return null;+ if (!url.startsWith("/backend-api/")) return null;const apiKey = /^Bearer sk-/i.test(String(headers.authorization ?? "")) && !headers["chatgpt-account-id"];if (apiKey && url.startsWith(CODEX_BASE)) return { host: OPENAI_API_HOST, url: `/v1/${url.slice(CODEX_BASE.length)}` };- return { host: upstreamOf(url.split("?")[0]), url };+ return { host: UPSTREAM_HOST, url };}// Outbound proxy: environment first, then the system setting (Windows per-user, macOS); NO_PROXY is honoured for the@@ -108,18 +128,25 @@ export function macProxy(scutil: string): string | null {return null;}-function connectUpstream(via: { host: string; port: number } | null, upstream = UPSTREAM_HOST, signal?: AbortSignal): Promise<tls.TLSSocket> {- const startTls = (socket?: net.Socket) => new Promise<tls.TLSSocket>((ok, fail) => {+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 secure = tls.connect({ socket, host: socket ? undefined : upstream, port: 443, servername: upstream, ALPNProtocols: ["http/1.1"] }, () => { cleanup(); ok(secure); });- const abort = () => { cleanup(); secure.destroy(); socket?.destroy(); fail(new Error("upstream connection cancelled")); };- secure.once("error", (error) => { cleanup(); fail(error); });+ 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 socket = net.connect({ port: via.port, host: via.host, signal }, () => socket.write(`CONNECT ${upstream}:443 HTTP/1.1\r\nHost: ${upstream}:443\r\n\r\n`));+ 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]);@@ -135,9 +162,11 @@ function connectUpstream(via: { host: string; port: number } | null, upstream =});}-export function forwardHeaders(headers: IncomingHttpHeaders, upstream = UPSTREAM_HOST): Record<string, string | string[]> {+export function forwardHeaders(headers: IncomingHttpHeaders, upstream = UPSTREAM_HOST, platform?: Platform): Record<string, string | string[]> {const out: Record<string, string | string[]> = {};- for (const [name, value] of Object.entries(headers)) if (value !== undefined && !HOP_BY_HOP.has(name)) out[name] = value;+ const client = platform ?? (upstream === CLAUDE_HOST ? "claude" : "codex");+ const removed = new Set(client === "claude" ? ["chatgpt-account-id"] : ["anthropic-beta", "anthropic-version", "x-claude-code-session-id", "x-claude-code-agent-id", ...(!platform ? ["x-api-key"] : [])]);+ for (const [name, value] of Object.entries(headers)) if (value !== undefined && !HOP_BY_HOP.has(name) && !removed.has(name) && !name.startsWith("x-cam-")) out[name] = value;out.host = upstream;return out;}@@ -536,6 +565,7 @@ async function main(): Promise<void> {ensureAutoDefault(claudeSelectionDirOf());const portIndex = process.argv.indexOf("--port");const port = Number(portIndex >= 0 ? process.argv[portIndex + 1] : DEFAULT_PORT);+ const providerPort = routingPort(port);// One engine per machine: a second start leaves the running one alone.const running = await engineHealth(port);if (running) {@@ -550,7 +580,10 @@ async function main(): Promise<void> {const via = outboundProxy();// 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) => (vias.has(upstream) ? vias.get(upstream)! : via);+ const viaOf = (upstream: string) => {+ if (!vias.has(upstream)) vias.set(upstream, outboundProxy(process.env, readSystemProxy, upstream));+ return vias.get(upstream)!;+ };const startedAt = new Date().toISOString();// v0.1-3: which code this engine runs, so the plugin can tell when an update needs a new engine.const build = buildOf();@@ -600,7 +633,7 @@ async function main(): Promise<void> {}// Open WebSocket connections per thread. Over WebSocket Codex only sends new items and the server keeps the rest,// so a thread with unchecked images must move to HTTP: its idle connections are closed, and its next upgrade gets 426.- type Live = { client: Duplex; socket: tls.TLSSocket; last: number; closedForSelection: boolean; activeWhileUnchecked: boolean; path: string; identity: Json };+ type Live = { client: Duplex; socket: net.Socket; last: number; closedForSelection: boolean; activeWhileUnchecked: boolean; path: string; identity: Json };const live = new Map<string, Set<Live>>();// v0.1-3: a newer plugin's engine takes over. This one stops listening at once, lets idle connections go (Codex// reconnects to the new engine), keeps serving requests and WebSocket turns already under way, then exits.@@ -649,7 +682,26 @@ async function main(): Promise<void> {const onRequest = (req: http.IncomingMessage, res: http.ServerResponse) => {if (req.url === "/__cam/health") {res.writeHead(200, { "content-type": "application/json" });- res.end(JSON.stringify({ ok: true, service: ENGINE_SERVICE, pid: process.pid, startedAt, port, build, version, upstream: UPSTREAM_HOST, upstreams: [UPSTREAM_HOST, CLAUDE_HOST, OPENAI_API_HOST], via: via ? `${via.host}:${via.port}` : "direct" }));+ res.end(JSON.stringify({ ok: true, service: ENGINE_SERVICE, pid: process.pid, startedAt, port, build, version, routingVersion: 1, routingPort: providerPort, upstream: UPSTREAM_HOST, upstreams: [UPSTREAM_HOST, CLAUDE_HOST, OPENAI_API_HOST], via: via ? `${via.host}:${via.port}` : "direct" }));+ return;+ }+ if (req.url === "/__cam/routes") {+ if (req.method !== "POST" || !ownRequest(req.headers) || req.headers.origin !== undefined || req.headers["x-cam-panel"] !== "1") {+ req.resume(); res.writeHead(403, { "content-type": "application/json" }); res.end(JSON.stringify({ error: "forbidden" })); return;+ }+ const chunks: Buffer[] = [];+ let size = 0;+ req.on("data", (chunk: Buffer) => { size += chunk.length; if (size <= 8192) chunks.push(chunk); });+ req.on("end", () => {+ try {+ if (size > 8192) { res.writeHead(413); res.end(); return; }+ const input = JSON.parse(Buffer.concat(chunks).toString("utf8"));+ validateBaseUrl(input.baseUrl, port);+ const route = registerRoute(input);+ res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });+ res.end(JSON.stringify({ id: route.id, baseUrl: routeBaseUrl(port, route.id).replace("localhost", "127.0.0.1") }));+ } catch { res.writeHead(400, { "content-type": "application/json" }); res.end(JSON.stringify({ error: say(currentLang(), "proxy.invalidRoute") })); }+ });return;}if (req.url === "/__cam/retire" && req.method === "POST") {@@ -690,14 +742,20 @@ async function main(): Promise<void> {if (retiredAt !== null) res.shouldKeepAlive = false;const id = ++sequence;const started = Date.now();- const path = (req.url ?? "/").split("?")[0];const route = routeOf(req.url ?? "/", req.headers);+ if (!route) {+ req.resume(); res.writeHead(421, { "content-type": "text/plain; charset=utf-8" }); res.end(say(currentLang(), "proxy.unknownRoute"));+ log({ at: new Date(started).toISOString(), id, transport: "http", status: 421, reason: "unrecognized or conflicting provider route" });+ return;+ }+ const path = route.clientPath ?? (req.url ?? "/").split("?")[0];const upstream = route.host;+ const platform = route.platform ?? (upstream === CLAUDE_HOST ? "claude" : "codex");const identity = requestIdentity(req.headers);- const rewrite = req.method === "POST" && /\/responses(\/compact)?$/.test(path) && needsRewrite(identity.threadId, selectionDir, sessionsDir, identity.forkedFrom);+ const rewrite = platform === "codex" && req.method === "POST" && /\/responses(\/compact)?$/.test(path) && needsRewrite(identity.threadId, selectionDir, sessionsDir, identity.forkedFrom);// v0.4: a Claude Code request of a session's main conversation (a subagent's loop has its own); rewritten like a// Codex thread's once something is unchecked there.- const claude = upstream === CLAUDE_HOST ? claudeIdentity(req.headers) : null;+ const claude = platform === "claude" ? claudeIdentity(req.headers) : null;const claudeSession = claude?.sessionId && !claude.agentId && req.method === "POST" && path === "/v1/messages" ? claude.sessionId : null;// Once the engine has sent the session a changed history, every request of it is looked at, even with nothing left// out now: thinking made after a changed history no longer fits the history as it was.@@ -755,11 +813,13 @@ async function main(): Promise<void> {});const send = (attempts: Attempt[], at = 0): void => {if (res.destroyed) return;- connectUpstream(viaOf(upstream), upstream, connecting.signal).then((socket) => {+ connectUpstream(viaOf(upstream), upstream, connecting.signal, route.port, route.protocol !== "http:").then((socket) => {// The client can cancel while CONNECT/TLS is still in progress.if (res.destroyed) { socket.destroy(); return; }const attempt = attempts[at];- const outgoing = forwardHeaders(req.headers, upstream);+ const outgoing = forwardHeaders(req.headers, upstream, route.platform);+ const hostname = upstream.includes(":") ? `[${upstream}]` : upstream;+ outgoing.host = route.port && route.port !== (route.protocol === "http:" ? 80 : 443) ? `${hostname}:${route.port}` : hostname;if (attempt.body) outgoing["content-length"] = String(attempt.body.length);const beta = attempt.report?.experiment?.beta;if (beta) outgoing["anthropic-beta"] = [String(outgoing["anthropic-beta"] ?? ""), beta].filter(Boolean).join(",");@@ -849,11 +909,17 @@ async function main(): Promise<void> {const onUpgrade = (req: http.IncomingMessage, client: Duplex, head: Buffer) => {const id = ++sequence;const started = Date.now();- const path = (req.url ?? "/").split("?")[0];+ const route = routeOf(req.url ?? "/", req.headers);+ const path = route?.clientPath ?? (req.url ?? "/").split("?")[0];const identity = requestIdentity(req.headers);// Node takes its own 'error' listener off an upgraded socket. Without one, a client resetting the connection (Codex// can, right after a 426) throws and stops the engine (2026-10-19: four probe engines at once).client.on("error", () => {});+ if (!route) {+ client.end("HTTP/1.1 421 Misdirected Request\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");+ log({ at: new Date(started).toISOString(), id, transport: "websocket", declined: 421, reason: "unrecognized or conflicting provider route" });+ return;+ }// A retired engine takes no new WebSocket; Codex opens it again, on the new engine.if (retiredAt !== null) {client.end("HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");@@ -867,8 +933,7 @@ async function main(): Promise<void> {let up = head.length;let down = 0;let upstreamStatus: string | null = null;- const route = routeOf(req.url ?? "/", req.headers);- connectUpstream(viaOf(route.host), route.host).then((socket) => {+ connectUpstream(viaOf(route.host), route.host, undefined, route.port, route.protocol !== "http:").then((socket) => {// The client went away while the upstream connected: its close has passed, nothing would close this one.if (client.destroyed) { socket.destroy(); return; }const connection: Live = { client, socket, last: Date.now(), closedForSelection: false, activeWhileUnchecked: false, path, identity };@@ -883,10 +948,12 @@ async function main(): Promise<void> {recordRequest(identity.threadId, opened);noteChild(identity, opened.at);const lines = [`${req.method} ${route.url} HTTP/1.1`];- for (let i = 0; i < req.rawHeaders.length; i += 2) {- const name = req.rawHeaders[i];- lines.push(`${name}: ${name.toLowerCase() === "host" ? route.host : req.rawHeaders[i + 1]}`);- }+ const outgoing = forwardHeaders(req.headers, route.host, route.platform);+ const hostname = route.host.includes(":") ? `[${route.host}]` : route.host;+ outgoing.host = route.port && route.port !== (route.protocol === "http:" ? 80 : 443) ? `${hostname}:${route.port}` : hostname;+ outgoing.connection = "Upgrade";+ outgoing.upgrade = String(req.headers.upgrade ?? "websocket");+ for (const [name, value] of Object.entries(outgoing)) for (const entry of Array.isArray(value) ? value : [value]) lines.push(`${name}: ${entry}`);socket.write(`${lines.join("\r\n")}\r\n\r\n`);if (head.length) socket.write(head);socket.once("data", (chunk: Buffer) => { upstreamStatus = chunk.toString("latin1", 0, Math.min(chunk.length, 40)).split("\r\n")[0]; });@@ -912,33 +979,43 @@ async function main(): Promise<void> {client.on("error", close);}, (error) => {client.end("HTTP/1.1 502 Bad Gateway\r\n\r\n");- log({ at: new Date(started).toISOString(), id, transport: "websocket", path: req.url, error: String(error), ...requestIdentity(req.headers) });+ log({ at: new Date(started).toISOString(), id, transport: "websocket", path, error: String(error), ...requestIdentity(req.headers) });});};// Codex may resolve "localhost" to either loopback address, so listen on both (and only on loopback), one after the// other: an engine that loses a start race never holds half of the port. A busy port is tried again for a few// seconds, since an engine retiring for this one may still be letting go of it.- const listen = (host: string, attempt = 0): Promise<boolean> => new Promise((resolve) => {- const server = http.createServer(onRequest);- server.on("upgrade", onUpgrade);+ const listen = (host: string, listenPort: number, attempt = 0): Promise<boolean> => new Promise((resolve) => {+ const allowed = (url: string) => url === "/__cam/health" || url.startsWith("/__cam/routes/") === (listenPort === providerPort);+ const server = http.createServer((req, res) => {+ if (allowed(req.url ?? "/")) { onRequest(req, res); return; }+ req.resume(); res.writeHead(421, { "content-type": "text/plain; charset=utf-8" }); res.end(say(currentLang(), "proxy.isolatedRoute"));+ });+ server.on("upgrade", (req, client, head) => {+ if (allowed(req.url ?? "/") && req.url !== "/__cam/health") { onUpgrade(req, client, head); return; }+ client.on("error", () => {});+ client.end("HTTP/1.1 421 Misdirected Request\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");+ });server.requestTimeout = 0;server.once("error", (error: NodeJS.ErrnoException) => {- if (error.code === "EADDRINUSE" && attempt < 20) { setTimeout(() => resolve(listen(host, attempt + 1)), 150); return; }+ if (error.code === "EADDRINUSE" && attempt < 20) { setTimeout(() => resolve(listen(host, listenPort, attempt + 1)), 150); return; }console.error(JSON.stringify({ host, error: String(error) }));// Loopback IPv6 may be missing; that is fine. A port another program holds is not.- resolve(error.code !== "EADDRINUSE");+ resolve(host === "::1" && ["EAFNOSUPPORT", "EADDRNOTAVAIL"].includes(error.code ?? ""));});- server.listen(port, host, () => {+ server.listen(listenPort, host, () => {servers.push(server);server.on("error", (error) => console.error(JSON.stringify({ host, error: String(error) })));- console.log(JSON.stringify({ listening: `http://${host.includes(":") ? `[${host}]` : host}:${port}/backend-api/codex`, upstream: UPSTREAM_HOST, via: via ? `${via.host}:${via.port}` : "direct" }));+ console.log(JSON.stringify({ listening: `http://${host.includes(":") ? `[${host}]` : host}:${listenPort}/${listenPort === providerPort ? "__cam/routes" : "backend-api/codex"}`, upstream: UPSTREAM_HOST, via: via ? `${via.host}:${via.port}` : "direct" }));resolve(true);});});- for (const host of ["127.0.0.1", "::1"]) {- if (await listen(host)) continue;- log({ at: new Date().toISOString(), event: "engine-exit", pid: process.pid, reason: `port ${port} in use on ${host}` });+ // Bind the provider listener before advertising readiness on the legacy port. Older plugin copies never start+ // this listener, so they cannot misroute the persisted provider URLs after a mixed-version restart.+ for (const listenPort of [providerPort, port]) for (const host of ["127.0.0.1", "::1"]) {+ if (await listen(host, listenPort)) continue;+ log({ at: new Date().toISOString(), event: "engine-exit", pid: process.pid, reason: `port ${listenPort} unavailable on ${host}` });process.exit(1);}}diff --git a/plugin/src/routes.ts b/plugin/src/routes.tsnew file mode 100644index 0000000..faed1cd--- /dev/null+++ b/plugin/src/routes.ts@@ -0,0 +1,63 @@+// Provider routes bind a client protocol to its configured destination. Local URLs contain only an opaque id;+// credentials stay in the client's request. Bindings survive engine replacement and are immutable once registered.+import { createHmac, randomBytes } from "node:crypto";+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { dataDir } from "./paths.ts";++export type Platform = "codex" | "claude";+export type ProviderRoute = { id: string; platform: Platform; baseUrl: string };+const ID = /^[a-f0-9]{32}$/;++export const routingPort = (enginePort: number): number => {+ if (!Number.isInteger(enginePort) || enginePort < 1 || enginePort > 65534) throw new Error("invalid engine port");+ return enginePort + 1;+};++export function validateBaseUrl(value: string, enginePort?: number): URL {+ const invalid = () => Object.assign(new Error("invalid provider URL"), { key: "conflict.endpointUrl" });+ if (typeof value !== "string" || /[\r\n\t]/.test(value)) throw invalid();+ let url: URL;+ try { url = new URL(value); } catch { throw invalid(); }+ if (!["http:", "https:"].includes(url.protocol) || !url.hostname || url.username || url.password || url.hash || url.pathname.startsWith("/__cam/")) throw invalid();+ if (enginePort !== undefined && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) && [enginePort, routingPort(enginePort)].includes(Number(url.port || (url.protocol === "https:" ? 443 : 80)))) {+ throw Object.assign(new Error("provider endpoint points to the engine"), { key: "conflict.proxyLoop" });+ }+ return url;+}++export function registerRoute(input: { platform: Platform; baseUrl: string }, root = dataDir()): ProviderRoute {+ if (input.platform !== "codex" && input.platform !== "claude") throw new Error("invalid provider platform");+ const baseUrl = validateBaseUrl(input.baseUrl).href;+ const dir = join(root, "routes");+ mkdirSync(dir, { recursive: true });+ // wx prevents simultaneous plugin processes from replacing the shared signing key.+ const keyFile = join(dir, "key");+ try { writeFileSync(keyFile, randomBytes(32).toString("hex"), { flag: "wx", mode: 0o600 }); }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }+ const key = readFileSync(keyFile, "utf8");+ if (!/^[a-f0-9]{64}$/.test(key)) throw new Error("invalid provider route key");+ const id = createHmac("sha256", key).update(`${input.platform}\n${baseUrl}`).digest("hex").slice(0, 32);+ const route = { id, platform: input.platform, baseUrl };+ try { writeFileSync(join(dir, `${id}.json`), JSON.stringify(route), { flag: "wx", mode: 0o600 }); }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;+ const existing = readRoute(id, root);+ if (!existing || existing.platform !== route.platform || existing.baseUrl !== baseUrl) throw new Error("invalid provider route record");+ }+ return route;+}++export function readRoute(id: string, root = dataDir()): ProviderRoute | null {+ if (!ID.test(id)) return null;+ try {+ const value = JSON.parse(readFileSync(join(root, "routes", `${id}.json`), "utf8"));+ if (value.id !== id || !["codex", "claude"].includes(value.platform)) return null;+ return { id, platform: value.platform, baseUrl: validateBaseUrl(value.baseUrl).href };+ } catch { return null; }+}++export const routeBaseUrl = (port: number, id: string): string => {+ if (!ID.test(id)) throw new Error("invalid provider route id");+ return `http://localhost:${routingPort(port)}/__cam/routes/${id}`;+};diff --git a/plugin/src/setup.ts b/plugin/src/setup.tsindex 808556f..c248bf9 100644--- a/plugin/src/setup.ts+++ b/plugin/src/setup.ts@@ -10,6 +10,7 @@ import { join } from "node:path";import { codexHome, persistedEnv, proxyStatus } from "./codexconfig.ts";import { MARKETPLACE, PLUGIN, planInstall, planUninstall, pluginStatus, type Plan, type UserProxyEnv } from "./install.ts";import { dataDir } from "./paths.ts";+import { registerRoute, routeBaseUrl, validateBaseUrl } from "./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") : "");@@ -49,9 +50,22 @@ export function applyPlan(plan: Plan): void {}}+// 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);+ },+ });+}+// 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 = planInstall({ configText: readConfig(), envText: readEnv(), env: userProxyEnv(), port });+ const plan = planEngine(port, true);applyPlan(plan);return plan;}diff --git a/scripts/install.ps1 b/scripts/install.ps1index 69587ed..0167523 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -28,10 +28,12 @@}# Codex prints warnings on stderr; they are not failures.- function Invoke-Codex([string[]]$CodexArgs, [switch]$AllowFailure) {+ function Invoke-Codex([string[]]$CodexArgs, [switch]$AllowFailure, [switch]$PassThru) {$ErrorActionPreference = 'Continue'- $output = (& $codex @CodexArgs 2>&1 | ForEach-Object { "$_" }) -join "`n"- if ($LASTEXITCODE -ne 0 -and -not $AllowFailure) { throw "codex $($CodexArgs -join ' ') failed: $output" }+ $stderrFile = [IO.Path]::GetTempFileName()+ $output = (& $codex @CodexArgs 2>$stderrFile | ForEach-Object { "$_" }) -join "`n"+ if ($LASTEXITCODE -ne 0 -and -not $AllowFailure) { throw "codex $($CodexArgs -join ' ') failed: $output $(Get-Content -LiteralPath $stderrFile -Raw)" }+ if ($PassThru) { return $output }}$codex = Find-Codex@@ -41,17 +43,31 @@$source = if ($env:CAM_SOURCE) { $env:CAM_SOURCE } else { $repo }Write-Host "Installing the plugin with $codex ..."- # Added afresh, so the marketplace follows the release this script came with.- Invoke-Codex @('plugin', 'remove', $plugin) -AllowFailure- Invoke-Codex @('plugin', 'marketplace', 'remove', $name) -AllowFailure- $add = @('plugin', 'marketplace', 'add', $source)- if ($ref -and -not $env:CAM_SOURCE) { $add += @('--ref', $ref) }- Invoke-Codex $add- Invoke-Codex @('plugin', 'add', $plugin)-$root = Join-Path $codexHome "plugins\cache\$name\$name"- $installed = Get-ChildItem -LiteralPath $root -Directory -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1- if (-not $installed) { throw "The plugin did not arrive in $root." }+ # Codex may clean old cache files even when Windows keeps a running plugin's directory locked.+ $cached = @(Get-ChildItem -LiteralPath $root -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -match '^\d+\.\d+\.\d+([-+][\w.-]+)?$' })+ $cacheBackup = Join-Path ([IO.Path]::GetTempPath()) ("cam-runtime-backup-" + [guid]::NewGuid().ToString('N'))+ New-Item -ItemType Directory -Path $cacheBackup | Out-Null+ foreach ($entry in $cached) { Copy-Item -LiteralPath $entry.FullName -Destination $cacheBackup -Recurse -Force }+ $installed = $null+ try {+ # Refresh marketplace metadata without deleting the working plugin first.+ Invoke-Codex @('plugin', 'marketplace', 'remove', $name) -AllowFailure+ $add = @('plugin', 'marketplace', 'add', $source)+ if ($ref -and -not $env:CAM_SOURCE) { $add += @('--ref', $ref) }+ Invoke-Codex $add+ $result = Invoke-Codex @('plugin', 'add', '--json', $plugin) -PassThru | ConvertFrom-Json+ if ($result.version -notmatch '^\d+\.\d+\.\d+([-+][\w.-]+)?$') { throw 'Invalid installed plugin version.' }+ $installed = Get-Item -LiteralPath (Join-Path $root $result.version)+ if (-not (Test-Path -LiteralPath (Join-Path $installed.FullName 'src\cam.ts'))) { $installed = $null; throw 'The new plugin runtime is incomplete.' }+ } finally {+ foreach ($entry in $cached) {+ if ($installed -and $entry.Name -eq $installed.Name) { continue }+ $target = Join-Path $root $entry.Name+ New-Item -ItemType Directory -Path $target -Force | Out-Null+ Get-ChildItem -LiteralPath (Join-Path $cacheBackup $entry.Name) -Force | ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination $target -Recurse -Force }+ }+ }# The installed plugin writes the proxy settings itself (checking for conflicts first) and starts its engine.Write-Host 'Pointing Codex at the local engine ...'& cmd.exe /d /s /c call "$($installed.FullName)\scripts\launch.cmd" "$($installed.FullName)\src\cam.ts" setupdiff --git a/scripts/install.sh b/scripts/install.shindex 1e44c32..8e9931c 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -37,22 +37,39 @@ case "$ref" in __*) ref= ;; esacsource=${CAM_SOURCE:-$repo}printf 'Installing the plugin with %s ...\n' "$codex"-# Added afresh, so the marketplace follows the release this script came with.-"$codex" plugin remove "$plugin" >/dev/null 2>&1 || true+# Keep older runtimes usable if Codex's cache cleanup meets files still in use.+cache_root="$codex_home/plugins/cache/$name/$name"+cache_backup=$(mktemp -d "${TMPDIR:-/tmp}/cam-runtime-backup-XXXXXXXX")+if [ -d "$cache_root" ]; then cp -R "$cache_root/." "$cache_backup/"; fi+installed_version=+restore_caches() {+ for saved in "$cache_backup"/*; do+ [ -d "$saved" ] || continue+ saved_version=${saved##*/}+ [ "$saved_version" != "$installed_version" ] || continue+ mkdir -p "$cache_root/$saved_version"+ cp -R "$saved/." "$cache_root/$saved_version/"+ done+}+trap restore_caches 0+# Refresh marketplace metadata without deleting the working plugin first."$codex" plugin marketplace remove "$name" >/dev/null 2>&1 || trueif [ -n "${CAM_SOURCE:-}" ] || [ -z "$ref" ]; then"$codex" plugin marketplace add "$source"else"$codex" plugin marketplace add "$source" --ref "$ref"fi-"$codex" plugin add "$plugin"--installed=$(ls -dt "$codex_home/plugins/cache/$name/$name"/*/ 2>/dev/null | head -n 1)-installed=${installed%/}-if [ -z "$installed" ]; then- printf 'The plugin did not arrive in %s.\n' "$codex_home/plugins/cache/$name/$name" >&2+"$codex" plugin add --json "$plugin" > "$cache_backup/install-result.json"+version=$(sed -n 's/^[[:space:]]*"version":[[:space:]]*"\([^"]*\)".*/\1/p' "$cache_backup/install-result.json")+case "$version" in ''|*[!0-9A-Za-z.+-]*) printf '%s\n' 'Invalid installed plugin version.' >&2; exit 1 ;; esac+installed="$cache_root/$version"+if [ ! -f "$installed/src/cam.ts" ]; then+ printf 'The plugin did not arrive in %s.\n' "$installed" >&2exit 1fi+installed_version=$version+restore_caches+trap - 0# The installed plugin writes the proxy settings itself (checking for conflicts first) and starts its engine.printf '%s\n' 'Pointing Codex at the local engine ...'if ! "$installed/scripts/launch" "$installed/src/cam.ts" setup; thendiff --git a/spike/src/claude-routing.test.ts b/spike/src/claude-routing.test.tsnew file mode 100644index 0000000..54b4ba0--- /dev/null+++ b/spike/src/claude-routing.test.ts@@ -0,0 +1,173 @@+// The real Claude mod handlers, with only the host's process environment and HTTP API replaced.+import assert from "node:assert/strict";+import test from "node:test";++let instance = 0;+const engine = "http://127.0.0.1:17891";+const routing = "http://127.0.0.1:17892";+const original = { ANTHROPIC_BASE_URL: "https://relay.example/anthropic", NO_PROXY: "example.test", no_proxy: "internal.test" };++async function mod(values: Record<string, string> = {}, options: { routeOk?: boolean; routingVersion?: number; routingPort?: number; responsePort?: number; routeBaseUrl?: string; failBaseSet?: boolean } = {}) {+ const { register } = await import(new URL(`../../hooks/register.js?test=${++instance}`, import.meta.url).href);+ const env = new Map(Object.entries(values));+ const states = new Map<string, any>();+ const requests: { url: string; options: any }[] = [];+ const writes: [string, string | undefined][] = [];+ const handlers = new Map<string, any>();+ const id = `synthetic-route-${instance}`;+ const baseUrl = `${routing}/__cam/routes/${id}`;+ let failedBase = false;+ register((name: string, ...args: any[]) => {+ handlers.set(name, args.at(-1));+ return { catch() {} };+ });+ const $ = {+ env: {+ get: async (name: string) => env.get(name),+ set: async (name: string, value: string | undefined) => {+ if (options.failBaseSet && name === "ANTHROPIC_BASE_URL" && value === baseUrl && !failedBase) { failedBase = true; throw new Error("synthetic env failure"); }+ writes.push([name, value]);+ if (value === undefined) env.delete(name); else env.set(name, value);+ },+ },+ state: {+ get: async (key: any) => ({ value: states.get(key.key) }),+ set: async (key: any, value: any) => { states.set(key.key, structuredClone(value)); },+ },+ http: {+ fetch: async (url: string, request: any) => {+ requests.push({ url, options: request });+ if (url === `${engine}/__cam/health`) return { ok: true, text: JSON.stringify({ service: "codex-attachment-manager", upstreams: ["api.anthropic.com"], routingVersion: options.routingVersion ?? 1, routingPort: options.routingPort ?? 17892 }) };+ if (url === `${engine}/__cam/routes`) return { ok: options.routeOk ?? true, text: JSON.stringify({ id, baseUrl: options.routeBaseUrl ?? `http://127.0.0.1:${options.responsePort ?? 17892}/__cam/routes/${id}` }) };+ throw new Error(`unexpected synthetic request ${url}`);+ },+ },+ command: { register: async () => {} },+ ui: { invalidate: async () => {} },+ clock: { after: () => ({ cancel() {} }), sleep: async () => {} },+ };+ const next = async (event: any) => event;+ return {+ env, states, requests, writes, baseUrl,+ start: () => handlers.get("session.start")($, {}, next),+ end: (reason = "exit") => handlers.get("session.end")($, { reason }, next),+ };+}++test("Claude registers its official upstream before switching this process to its own route", async () => {+ const m = await mod();+ await m.start();+ assert.equal(m.env.get("ANTHROPIC_BASE_URL"), m.baseUrl);+ const registration = m.requests.find((entry) => entry.url === `${engine}/__cam/routes`)!;+ assert.ok(registration, "an explicit route must be registered");+ assert.equal(registration.options.method, "POST");+ assert.equal(registration.options.headers["x-cam-panel"], "1");+ assert.deepEqual(JSON.parse(registration.options.body), { platform: "claude", baseUrl: "https://api.anthropic.com" });+ assert.equal(m.states.get("routing").active, true);+ await m.end();+ assert.equal(m.env.has("ANTHROPIC_BASE_URL"), false);+ assert.equal(m.env.has("NO_PROXY"), false);+ assert.equal(m.env.has("no_proxy"), false);+});++test("two Claude processes register separate relay and official routes without sharing their targets", async () => {+ const relay = await mod(original);+ const official = await mod({ ANTHROPIC_BASE_URL: "https://api.anthropic.com/" });+ await Promise.all([relay.start(), official.start()]);+ const requestOf = (m: typeof relay) => {+ const registration = m.requests.find((entry) => entry.url.endsWith("/__cam/routes"));+ assert.ok(registration, "the upstream must be registered before takeover");+ return JSON.parse(registration.options.body);+ };+ assert.deepEqual(requestOf(relay), { platform: "claude", baseUrl: original.ANTHROPIC_BASE_URL });+ assert.deepEqual(requestOf(official), { platform: "claude", baseUrl: "https://api.anthropic.com/" });+ assert.equal(relay.env.get("ANTHROPIC_BASE_URL"), relay.baseUrl);+ assert.equal(official.env.get("ANTHROPIC_BASE_URL"), official.baseUrl);+ assert.notEqual(relay.baseUrl, official.baseUrl);+ await relay.end();+ assert.deepEqual(Object.fromEntries(relay.env), original);+ assert.equal(official.env.get("ANTHROPIC_BASE_URL"), official.baseUrl);+});++test("failed route registration preserves the original endpoint and proxy variables", async () => {+ const m = await mod(original, { routeOk: false });+ await m.start();+ assert.deepEqual(Object.fromEntries(m.env), original);+ assert.equal(m.states.get("routing").active, false);+ assert.equal(m.states.get("routing").reason, "failed");+ assert.equal(m.writes.length, 0);+});++test("an engine without explicit routing support cannot take over a Claude process", async () => {+ const m = await mod(original, { routingVersion: 0 });+ await m.start();+ assert.deepEqual(Object.fromEntries(m.env), original);+ assert.equal(m.states.get("routing").reason, "engine-old");+ assert.equal(m.requests.some((entry) => entry.url.endsWith("/__cam/routes")), false);+});++test("health must advertise the isolated routing port before Claude can be taken over", async () => {+ const m = await mod(original, { routingPort: 17891 });+ await m.start();+ assert.deepEqual(Object.fromEntries(m.env), original);+ assert.equal(m.states.get("routing").reason, "engine-old");+ assert.equal(m.requests.some((entry) => entry.url.endsWith("/__cam/routes")), false);+});++test("a route returned on the legacy engine port is rejected to prevent downgrade misrouting", async () => {+ const m = await mod(original, { responsePort: 17891 });+ await m.start();+ assert.deepEqual(Object.fromEntries(m.env), original);+ assert.equal(m.states.get("routing").reason, "failed");+ assert.equal(m.writes.length, 0);+});++test("restoring routing does not overwrite endpoint or proxy settings changed after takeover", async () => {+ const m = await mod(original);+ await m.start();+ assert.equal(m.env.get("ANTHROPIC_BASE_URL"), m.baseUrl, "first take over this relay process");+ m.env.set("ANTHROPIC_BASE_URL", "https://replacement.example/api");+ m.env.set("NO_PROXY", "replacement.test");+ m.env.set("no_proxy", "changed.test");+ await m.end();+ assert.deepEqual(Object.fromEntries(m.env), { ANTHROPIC_BASE_URL: "https://replacement.example/api", NO_PROXY: "replacement.test", no_proxy: "changed.test" });+ assert.equal(m.states.get("routing").active, false);+});++test("an environment-write failure rolls back the variables already changed", async () => {+ const m = await mod(original, { failBaseSet: true });+ await m.start();+ assert.deepEqual(Object.fromEntries(m.env), original);+ assert.equal(m.states.get("routing").active, false);+ assert.equal(m.states.get("routing").reason, "failed");+});++test("a malformed route response cannot redirect Claude to a different endpoint", async () => {+ const m = await mod(original, { routeBaseUrl: "https://unexpected.example" });+ await m.start();+ assert.deepEqual(Object.fromEntries(m.env), original);+ assert.equal(m.states.get("routing").reason, "failed");+});++test("Bedrock, Vertex and Foundry keep their original native transport", async () => {+ for (const name of ["CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY"]) {+ const values = { ...original, [name]: "1" };+ const m = await mod(values);+ await m.start();+ assert.deepEqual(Object.fromEntries(m.env), values);+ assert.equal(m.states.get("routing").reason, "provider");+ assert.equal(m.requests.length, 0);+ }+});++test("a reloaded mod upgrades an earlier unscoped engine URL using its saved original upstream", async () => {+ const m = await mod({ ANTHROPIC_BASE_URL: engine, NO_PROXY: "example.test,127.0.0.1,localhost,::1", no_proxy: "internal.test,127.0.0.1,localhost,::1" });+ m.states.set("routing", { active: true, port: 17891, originalBaseUrl: original.ANTHROPIC_BASE_URL, originalNoProxy: original.NO_PROXY, originalNoProxyLower: original.no_proxy });+ await m.start();+ assert.equal(m.env.get("ANTHROPIC_BASE_URL"), m.baseUrl);+ const registration = m.requests.find((entry) => entry.url.endsWith("/__cam/routes"));+ assert.ok(registration);+ assert.equal(JSON.parse(registration.options.body).baseUrl, original.ANTHROPIC_BASE_URL);+ await m.end();+ assert.deepEqual(Object.fromEntries(m.env), original);+});diff --git a/spike/src/codexconfig.test.ts b/spike/src/codexconfig.test.tsindex 5a8e5e0..0e451cd 100644--- a/spike/src/codexconfig.test.ts+++ b/spike/src/codexconfig.test.ts@@ -156,3 +156,86 @@ test("MCP server: a user's own table with the same name is never overwritten", (assert.throws(() => enableMcpServer(mine, "cam_probe", NODE, [SCRIPT]), /already defines mcp_servers\.cam_probe/);assert.equal(enableMcpServer(mine, "other", NODE, [SCRIPT]).changed, true);});++// v0.9: keep the user's provider and credentials; only its endpoint gets a local route.+test("a custom top-level endpoint is routed and restored in place without changing its formatting", () => {+ const original = "\uFEFFopenai_base_url = 'https://relay.example:444/prefix/v1' # my endpoint\r\nmodel = \"other-model\"\r\n[features]\r\nview_image = true";+ const seen: string[] = [];+ let result: ReturnType<typeof enableProxy>;+ assert.doesNotThrow(() => { result = enableProxy(original, URL, (upstream: string) => { seen.push(upstream); return "http://localhost:17891/__cam/routes/relay"; }); });+ assert.deepEqual(seen, ["https://relay.example:444/prefix/v1"]);+ assert.match(result!.text, /^openai_base_url = "http:\/\/localhost:17891\/__cam\/routes\/relay"/m);+ assert.equal(result!.text.match(/^openai_base_url\s*=/gm)?.length, 1);+ assert.doesNotMatch(result!.text.replaceAll("\r\n", ""), /\n/);+ assert.equal(proxyStatus(result!.text).url, "http://localhost:17891/__cam/routes/relay");+ assert.equal(proxyStatus(result!.text).conflict, false);+ assert.equal(disableProxy(result!.text).text, original);+});++test("provider base URLs have independent routes and keep authentication, headers, queries and model selection", () => {+ const original = 'model_provider = "work.relay"\nmodel = "vision-model"\n\n[model_providers."work.relay"]\nname = "Work"\nbase_url = "https://first.example/prefix/v1"\nwire_api = "responses"\nenv_key = "RELAY_KEY"\nhttp_headers = { "x-provider" = "work" }\nquery_params = { version = "1" }\n\n[model_providers.local]\nbase_url = \'http://127.0.0.1:9123/api/v1\'\n\n[mcp_servers.other]\nbase_url = "https://unrelated.example"\n';+ const endpoints: string[] = [];+ const route = (upstream: string) => { endpoints.push(upstream); return `http://localhost:17891/__cam/routes/${upstream.startsWith("https:") ? "first" : "local"}`; };+ const result = enableProxy(original, URL, route);+ assert.deepEqual(endpoints, ["https://first.example/prefix/v1", "http://127.0.0.1:9123/api/v1"]);+ assert.match(result.text, /^base_url = "http:\/\/localhost:17891\/__cam\/routes\/first"$/m);+ assert.match(result.text, /^base_url = "http:\/\/localhost:17891\/__cam\/routes\/local"$/m);+ for (const line of ['model_provider = "work.relay"', 'env_key = "RELAY_KEY"', 'http_headers = { "x-provider" = "work" }', 'query_params = { version = "1" }', 'base_url = "https://unrelated.example"']) assert.ok(result.text.includes(line));+ assert.equal(disableProxy(result.text).text, original);+ assert.deepEqual(enableProxy(result.text, URL, route), { text: result.text, changed: false });+});++test("uninstall keeps an endpoint the user changed after installation, and re-enable binds that new endpoint", () => {+ const original = 'model_provider = "relay"\n[model_providers.relay]\nbase_url = "https://old.example/v1" # existing\n';+ const route = () => "http://localhost:17891/__cam/routes/relay";+ const installed = enableProxy(original, URL, route).text;+ const changed = installed.replace(/^base_url = .*$/m, 'base_url = "https://new.example/v2" # changed by user');+ assert.equal(disableProxy(changed).text, original.replace('base_url = "https://old.example/v1" # existing', 'base_url = "https://new.example/v2" # changed by user'));+ const targets: string[] = [];+ enableProxy(changed, URL, (target: string) => { targets.push(target); return route(); });+ assert.deepEqual(targets, ["https://new.example/v2"]);+});++test("dotted provider keys are routed, and provider-looking text inside multiline strings is untouched", () => {+ const original = 'model_providers.relay.base_url = "https://relay.example/v1"\ninstructions = """\n[model_providers.fake]\nbase_url = "https://not-a-setting.example"\n"""\n';+ const targets: string[] = [];+ const result = enableProxy(original, URL, (target: string) => { targets.push(target); return "http://localhost:17891/__cam/routes/dotted"; });+ assert.deepEqual(targets, ["https://relay.example/v1"]);+ assert.match(result.text, /^model_providers\.relay\.base_url = "http:\/\/localhost:17891\/__cam\/routes\/dotted"$/m);+ assert.ok(result.text.includes('base_url = "https://not-a-setting.example"'));+ assert.equal(disableProxy(result.text).text, original);+});++test("a multiline instruction does not hide a later top-level endpoint, and array tables end provider scope", () => {+ const original = 'instructions = """\n[fake.table]\n"""\nopenai_base_url = "https://top.example/v1"\n[model_providers.relay]\nbase_url = "https://relay.example/v1"\n[[unrelated]]\nbase_url = "https://unrelated.example"\n';+ const targets: string[] = [];+ const result = enableProxy(original, URL, (target: string) => { targets.push(target); return `http://localhost:17891/__cam/routes/${targets.length}`; });+ assert.deepEqual(targets, ["https://top.example/v1", "https://relay.example/v1"]);+ assert.equal(result.text.match(/^openai_base_url\s*=/gm)?.length, 1);+ assert.equal(disableProxy(result.text).text, original);+});++test("quoted top-level keys report the routed endpoint, and comments added inside its block survive uninstall", () => {+ const original = '\"openai_base_url\" = "https://relay.example/v1"\n';+ const local = "http://localhost:17891/__cam/routes/quoted";+ const installed = enableProxy(original, URL, () => local).text;+ assert.equal(proxyStatus(installed).url, local);+ const edited = installed.replace(/^"openai_base_url" = .*$/m, '# added by user\n"openai_base_url" = "' + local + '"');+ assert.equal(disableProxy(edited).text, '# added by user\n' + original);+});++test("unsupported endpoint syntax fails before enabling or registering any provider", () => {+ for (const original of [+ 'openai_base_url = """https://relay.example/v1"""\n',+ '[model_providers.relay]\nbase_url = \'\'\'https://relay.example/v1\'\'\'\n',+ 'model_provider = "relay"\nmodel_providers = { relay = { base_url = "https://relay.example/v1", name = "Relay" } }\n',+ '[model_providers]\nrelay = { base_url = "https://relay.example/v1", name = "Relay" }\n',+ 'model_providers.relay = { base_url = "https://relay.example/v1", name = "Relay" }\n',+ '[model_providers.good]\nbase_url = "https://good.example/v1"\n[model_providers.bad]\nbase_url = """https://bad.example/v1"""\n',+ ]) {+ const targets: string[] = [];+ assert.throws(() => enableProxy(original, URL, (target) => { targets.push(target); return "http://localhost:17891/__cam/routes/example"; }), (error: any) => error.key === "conflict.endpointSyntax");+ assert.deepEqual(targets, []);+ assert.equal(proxyStatus(original).enabled, false);+ }+});diff --git a/spike/src/install.test.ts b/spike/src/install.test.tsindex d4d0f84..33f6019 100644--- a/spike/src/install.test.ts+++ b/spike/src/install.test.ts@@ -74,3 +74,13 @@ test("the plugin's marketplace and install state are read from what Codex wrote"assert.deepEqual(pluginStatus(written), { marketplace: "\\\\?\\D:\\repos\\cam", installed: true, enabled: true });assert.equal(pluginStatus(written.replace("enabled = true", "enabled = false")).enabled, false);});++test("installation registers custom endpoints before replacing them and uninstall restores them", () => {+ const config = 'openai_base_url = "https://relay.example/custom/v1"\n' + CONFIG;+ const targets: string[] = [];+ let installed: ReturnType<typeof planInstall>;+ assert.doesNotThrow(() => { installed = planInstall({ ...base, configText: config, envText: null, env: direct, routeBaseUrl: (target: string) => { targets.push(target); return "http://localhost:17891/__cam/routes/relay"; } }); });+ assert.deepEqual(targets, ["https://relay.example/custom/v1"]);+ assert.match(installed!.configText, /^openai_base_url = "http:\/\/localhost:17891\/__cam\/routes\/relay"$/m);+ assert.equal(planUninstall({ configText: installed!.configText, envText: null }).configText, config);+});diff --git a/spike/src/plugin-cache.test.ts b/spike/src/plugin-cache.test.tsnew file mode 100644index 0000000..90883b7--- /dev/null+++ b/spike/src/plugin-cache.test.ts@@ -0,0 +1,31 @@+import assert from "node:assert/strict";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { tmpdir } from "node:os";+import test from "node:test";++test("installing a new cache preserves the older runtime even when Codex cleans its contents", async () => {+ const mod = await import("../../plugin/src/plugin-cache.ts").catch(() => null);+ assert.ok(mod, "installation protects existing runtime copies");+ const root = mkdtempSync(join(tmpdir(), "cam-cache-test-"));+ const old = join(root, "0.8.3"); mkdirSync(old);+ writeFileSync(join(old, "runtime.ts"), "old runtime");+ mod.preservingPluginCache(root, "0.9.0", () => {+ rmSync(join(old, "runtime.ts")); // Codex's best-effort old-version cleanup can stop after this.+ mkdirSync(join(root, "0.9.0")); writeFileSync(join(root, "0.9.0", "runtime.ts"), "new runtime");+ });+ assert.equal(readFileSync(join(old, "runtime.ts"), "utf8"), "old runtime");+ assert.equal(readFileSync(join(root, "0.9.0", "runtime.ts"), "utf8"), "new runtime");+});++test("a failed reinstall restores missing files in the existing version", async () => {+ const mod = await import("../../plugin/src/plugin-cache.ts").catch(() => null);+ assert.ok(mod, "installation protects existing runtime copies");+ const root = mkdtempSync(join(tmpdir(), "cam-cache-test-"));+ const current = join(root, "0.9.0"); mkdirSync(current);+ writeFileSync(join(current, "runtime.ts"), "working runtime");+ assert.throws(() => mod.preservingPluginCache(root, "0.9.0", () => {+ rmSync(join(current, "runtime.ts")); throw new Error("synthetic sharing violation");+ }), /synthetic sharing violation/);+ assert.equal(readFileSync(join(current, "runtime.ts"), "utf8"), "working runtime");+});diff --git a/spike/src/proxy-http.test.ts b/spike/src/proxy-http.test.tsindex 6c6329f..a5721af 100644--- a/spike/src/proxy-http.test.ts+++ b/spike/src/proxy-http.test.ts@@ -9,6 +9,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import test, { type TestContext } from "node:test";import { fileURLToPath } from "node:url";+import { engineTestPort } from "./proxy-test-ports.ts";async function bounded<T>(promise: Promise<T>, message: string, ms = 2000): Promise<T> {let timer: NodeJS.Timeout;@@ -22,10 +23,7 @@ async function fixture(t: TestContext, handler: http.RequestListener, connectDelconst upstream = http.createServer(handler);await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));const upstreamPort = (upstream.address() as { port: number }).port;- const reservation = http.createServer();- await new Promise<void>((resolve) => reservation.listen(0, "127.0.0.1", resolve));- const port = (reservation.address() as { port: number }).port;- await new Promise<void>((resolve) => reservation.close(() => resolve()));+ const port = await engineTestPort();const child = spawn(process.execPath, [fileURLToPath(new URL("./proxy-http-fixture.ts", import.meta.url))], {env: { ...process.env, CAM_DATA_DIR: root, CAM_TEST_PROXY_PORT: String(port), CAM_TEST_UPSTREAM_PORT: String(upstreamPort), CAM_TEST_CONNECT_DELAY: String(connectDelay), CAM_TEST_ENGINE_ARGS: engineArgs.join(" "), NO_PROXY: "*", no_proxy: "*" },stdio: ["ignore", "pipe", "pipe"],diff --git a/spike/src/proxy-provider-http.test.ts b/spike/src/proxy-provider-http.test.tsnew file mode 100644index 0000000..a36bcf6--- /dev/null+++ b/spike/src/proxy-provider-http.test.ts@@ -0,0 +1,142 @@+// Real engine, fake credentials and loopback upstreams only.+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from "node:fs";+import http from "node:http";+import net from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test, { type TestContext } from "node:test";+import { fileURLToPath } from "node:url";+import { image, pngA, pngB, text, transcript } from "./claude-fixtures.ts";+import { assistant, line, red, turn, upload, THREAD } from "./testfixtures.ts";+import { writeSelection } from "../../plugin/src/selection.ts";+import { engineTestPort } from "./proxy-test-ports.ts";++async function bounded<T>(value: Promise<T>, ms = 8000): Promise<T> {+ let timer: NodeJS.Timeout;+ try { return await Promise.race([value, new Promise<never>((_, fail) => { timer = setTimeout(() => fail(new Error("synthetic request timed out")), ms); })]); }+ finally { clearTimeout(timer!); }+}+async function engine(t: TestContext) {+ const root = mkdtempSync(join(tmpdir(), "cam-provider-http-"));+ const seen: { url?: string; headers: http.IncomingHttpHeaders; body: string }[] = [];+ const upstream = http.createServer((req, res) => {+ const chunks: Buffer[] = [];+ req.on("data", chunk => chunks.push(chunk));+ req.on("end", () => { seen.push({ url: req.url, headers: req.headers, body: Buffer.concat(chunks).toString() }); res.end("{}"); });+ });+ await new Promise<void>(ok => upstream.listen(0, "127.0.0.1", ok));+ const upstreamPort = (upstream.address() as net.AddressInfo).port;+ const port = await engineTestPort();+ const child = spawn(process.execPath, [fileURLToPath(new URL("./proxy-http-fixture.ts", import.meta.url))], {+ env: { ...process.env, CAM_DATA_DIR: root, CODEX_HOME: join(root, "codex"), CLAUDE_CONFIG_DIR: join(root, "claude"), LOCALAPPDATA: join(root, "empty-appdata"), CAM_TEST_PROXY_PORT: String(port), CAM_TEST_UPSTREAM_PORT: String(upstreamPort), NO_PROXY: "*", no_proxy: "*" },+ stdio: ["ignore", "pipe", "pipe"],+ });+ let output = "";+ const exited = new Promise<void>(ok => child.once("exit", () => ok()));+ t.after(async () => { child.kill(); await bounded(exited); upstream.closeAllConnections(); await new Promise<void>(ok => upstream.close(() => ok())); });+ await bounded(new Promise<void>((ok, fail) => {+ child.on("error", fail);+ child.on("exit", code => fail(new Error(`engine exited ${code}: ${output}`)));+ child.stderr.on("data", chunk => { output += chunk; });+ child.stdout.on("data", chunk => { output += chunk; if (output.includes(`http://127.0.0.1:${port}/`)) ok(); });+ }));+ const request = (path: string, headers: Record<string, string> = {}, body?: unknown, overridePort?: number) => bounded(new Promise<{ status: number; body: string }>((ok, fail) => {+ const data = body === undefined ? "" : JSON.stringify(body);+ const req = http.request({ hostname: "127.0.0.1", port: overridePort ?? (path.startsWith("/__cam/routes/") ? port + 1 : port), path, method: body === undefined ? "GET" : "POST", agent: false, headers: { ...(body === undefined ? {} : { "content-type": "application/json", "content-length": String(Buffer.byteLength(data)) }), ...headers } }, res => {+ const chunks: Buffer[] = [];+ res.on("data", chunk => chunks.push(chunk));+ res.on("error", fail);+ res.on("end", () => ok({ status: res.statusCode!, body: Buffer.concat(chunks).toString() }));+ });+ req.on("error", fail); req.end(data);+ }));+ const register = async (platform: string, baseUrl: string) => {+ const result = await request("/__cam/routes", { "x-cam-panel": "1" }, { platform, baseUrl });+ assert.equal(result.status, 200, result.body);+ return new URL(JSON.parse(result.body).baseUrl).pathname;+ };+ return { root, port, upstream, upstreamPort, seen, request, register };+}++test("two registered providers retain destinations, credentials and native bodies over HTTP", async t => {+ const e = await engine(t);+ const codex = await e.register("codex", `http://127.0.0.1:${e.upstreamPort}/gateway/v1?tenant=one`);+ const claude = await e.register("claude", "https://claude-relay.example:9443/anthropic");+ const cbody = { input: [], model: "synthetic-vision" };+ const abody = { messages: [{ role: "user", content: "synthetic" }], model: "synthetic-vision" };+ assert.equal((await e.request(`${codex}/responses?beta=1`, { authorization: "Bearer synthetic-codex", "x-api-key": "synthetic-relay" }, cbody)).status, 200);+ assert.equal((await e.request(`${claude}/v1/messages`, { authorization: "Bearer synthetic-claude", "x-api-key": "synthetic-anthropic", "anthropic-version": "2023-06-01" }, abody)).status, 200);+ assert.equal(e.seen[0].url, "/gateway/v1/responses?tenant=one&beta=1");+ assert.equal(e.seen[0].headers.host, `127.0.0.1:${e.upstreamPort}`);+ assert.equal(e.seen[0].headers["x-api-key"], "synthetic-relay");+ assert.deepEqual(JSON.parse(e.seen[0].body), cbody);+ assert.equal(e.seen[1].url, "/anthropic/v1/messages");+ assert.equal(e.seen[1].headers.host, "claude-relay.example:9443");+ assert.equal(e.seen[1].headers.authorization, "Bearer synthetic-claude");+ assert.deepEqual(JSON.parse(e.seen[1].body), abody);+ assert.equal((await e.request(`${claude}/future-endpoint`, { "x-api-key": "synthetic-anthropic" })).status, 200);+ assert.equal(e.seen.at(-1)?.headers.host, "claude-relay.example:9443");+});++test("unknown, contradictory and recursive routes are refused without forwarding credentials", async t => {+ const e = await engine(t);+ const codex = await e.register("codex", `http://127.0.0.1:${e.upstreamPort}/v1`);+ const claude = await e.register("claude", "https://claude-relay.example");+ assert.equal((await e.request("/unknown", { "x-api-key": "synthetic", "chatgpt-account-id": "mixed" })).status, 421);+ assert.equal((await e.request(`/__cam/routes/${"0".repeat(32)}/v1/messages`, { authorization: "Bearer synthetic" })).status, 421);+ assert.equal((await e.request(`${codex}/responses`, { "x-claude-code-session-id": "synthetic" })).status, 421);+ assert.equal((await e.request(`${claude}/v1/messages`, { "chatgpt-account-id": "synthetic" })).status, 421);+ assert.equal((await e.request("/__cam/routes", { "x-cam-panel": "1" }, { platform: "claude", baseUrl: `http://localhost:${e.port}` })).status, 400);+ assert.equal((await e.request("/__cam/routes", { origin: "https://evil.example", "x-cam-panel": "1" }, { platform: "claude", baseUrl: "https://relay.example" })).status, 403);+ assert.equal((await e.request("/__cam/routes", {}, { platform: "claude", baseUrl: "https://relay.example" })).status, 403);+ assert.equal((await e.request(`${codex}/responses`, { authorization: "Bearer synthetic" }, undefined, e.port)).status, 421, "registered requests cannot use a port shared with old engines");+ assert.equal((await e.request("/backend-api/codex/responses", { authorization: "Bearer synthetic" }, undefined, e.port + 1)).status, 421, "legacy requests cannot enter a registered route");+ assert.equal(e.seen.length, 0);+});++test("registered Codex WebSocket upgrades preserve their destination without carrying internal headers", async t => {+ const e = await engine(t);+ const codex = await e.register("codex", `http://127.0.0.1:${e.upstreamPort}/v1`);+ const seen = new Promise<http.IncomingMessage>(ok => e.upstream.once("upgrade", (req, socket) => { socket.on("error", () => {}); socket.end("HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n"); ok(req); }));+ const socket = net.connect(e.port + 1, "127.0.0.1");+ socket.on("error", () => {}); t.after(() => socket.destroy());+ socket.write([`GET ${codex}/responses HTTP/1.1`, `Host: 127.0.0.1:${e.port}`, "Authorization: Bearer synthetic-key", "X-Cam-Panel: 1", "Connection: Upgrade", "Upgrade: websocket", "Sec-WebSocket-Version: 13", "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==", "", ""].join("\r\n"));+ const got = await bounded(seen);+ assert.equal(got.url, "/v1/responses");+ assert.equal(got.headers.host, `127.0.0.1:${e.upstreamPort}`);+ assert.equal(got.headers.authorization, "Bearer synthetic-key");+ assert.equal(got.headers["x-cam-panel"], undefined);+});++test("both custom providers still rewrite unchecked images using their native protocol", async t => {+ const e = await engine(t);+ const codex = await e.register("codex", `http://127.0.0.1:${e.upstreamPort}/gateway/v1`);+ const claude = await e.register("claude", "https://claude-relay.example/anthropic");+ const session = "11111111-2222-4333-8444-555555555555";+ const cdir = join(e.root, "codex", "sessions", "2026", "09", "24");+ mkdirSync(cdir, { recursive: true });+ const message = JSON.parse(upload("msg_1", "t1", [["a.png", red]])).payload;+ writeFileSync(join(cdir, `rollout-2026-09-24T10-00-00-${THREAD}.jsonl`), line("session_meta", { id: THREAD }) + turn("t1") + line("response_item", message) + assistant("synthetic", "t1"));+ writeSelection({ threadId: THREAD, unchecked: { "msg_1#0": { id: "IMG-001", at: "2026-09-24T10:00:00Z" } }, auto: false }, join(e.root, "selection"));+ assert.equal((await e.request(`${codex}/responses`, { authorization: "Bearer synthetic-codex", "x-codex-turn-metadata": JSON.stringify({ thread_id: THREAD, turn_id: "t2" }) }, { model: "synthetic", input: [message] })).status, 200);+ assert.doesNotMatch(e.seen[0].body, new RegExp(red.toString("base64").slice(30, 80)));+ assert.match(e.seen[0].body, /IMG-001/);+ assert.equal(e.seen[0].url, "/gateway/v1/responses");+ const history = transcript();+ const first = history.prompt([image(pngA), image(pngB), text("synthetic")]);+ history.assistant(text("synthetic"));+ const adir = join(e.root, "claude", "projects", "synthetic");+ mkdirSync(adir, { recursive: true });+ writeFileSync(join(adir, `${session}.jsonl`), history.records.map(value => JSON.stringify(value)).join("\n") + "\n");+ writeSelection({ threadId: session, unchecked: { [`${first}#0`]: { id: "IMG-001", at: "2026-09-24T10:00:00Z" } }, auto: false }, join(e.root, "claude", "selection"));+ const body = { model: "synthetic", messages: [{ role: "user", content: [image(pngA), image(pngB), text("synthetic")] }, { role: "assistant", content: [text("synthetic")] }, { role: "user", content: [text("next")] }] };+ assert.equal((await e.request(`${claude}/v1/messages`, { "x-claude-code-session-id": session, "x-api-key": "synthetic" }, body)).status, 200);+ assert.ok(!e.seen[1].body.includes(pngA));+ assert.ok(e.seen[1].body.includes(pngB));+ assert.match(e.seen[1].body, /IMG-001/);+ assert.equal(e.seen[1].url, "/anthropic/v1/messages");+ const logs = readdirSync(join(e.root, "proxy")).map(name => readFileSync(join(e.root, "proxy", name), "utf8")).join("");+ assert.ok(!logs.includes("synthetic-codex") && !logs.includes(pngA));+});diff --git a/spike/src/proxy-test-ports.ts b/spike/src/proxy-test-ports.tsnew file mode 100644index 0000000..729097e--- /dev/null+++ b/spike/src/proxy-test-ports.ts@@ -0,0 +1,19 @@+// Windows can reserve individual ephemeral ports. Reserve both engine listeners before starting a fixture.+import http from "node:http";++export async function engineTestPort(): Promise<number> {+ for (let attempt = 0; attempt < 50; attempt++) {+ const first = http.createServer();+ await new Promise<void>((ok, fail) => { first.once("error", fail); first.listen(0, "127.0.0.1", ok); });+ const port = (first.address() as { port: number }).port;+ const second = http.createServer();+ const available = port < 65535 && await new Promise<boolean>(ok => {+ second.once("error", () => ok(false));+ second.listen(port + 1, "127.0.0.1", () => ok(true));+ });+ if (available) await new Promise<void>(ok => second.close(() => ok()));+ await new Promise<void>(ok => first.close(() => ok()));+ if (available) return port;+ }+ throw new Error("no adjacent loopback ports available for the synthetic engine");+}diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.tsindex 08460b1..9f41eeb 100644--- a/spike/src/proxy.test.ts+++ b/spike/src/proxy.test.ts@@ -8,7 +8,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import test from "node:test";import zlib from "node:zlib";-import { claudeIdentity, describeBody, forwardHeaders, hasUnchecked, hasUnsafeInteger, imageSizesOf, macProxy, needsRewrite, outboundProxy, redactImages, rewriteBody, requestIdentity, routeOf, upstreamOf } from "../../plugin/src/proxy.ts";+import { claudeIdentity, describeBody, forwardHeaders, hasUnchecked, hasUnsafeInteger, imageSizesOf, macProxy, needsRewrite, outboundProxy, redactImages, rewriteBody, requestIdentity, routeOf } from "../../plugin/src/proxy.ts";import { writeSelection } from "../../plugin/src/selection.ts";import { png } from "./testkit.ts";@@ -166,11 +166,12 @@ test("with automatic selection, rewriteBody leaves out earlier turns' images tha});// v0.4: Claude Code through the same engine.-test("Claude Code's /v1/ requests go to api.anthropic.com, everything else to chatgpt.com as before", () => {- assert.equal(upstreamOf("/v1/messages"), "api.anthropic.com");- assert.equal(upstreamOf("/v1/messages/count_tokens"), "api.anthropic.com");- assert.equal(upstreamOf("/backend-api/codex/responses"), "chatgpt.com");- assert.equal(upstreamOf("/backend-api/codex/images/generations"), "chatgpt.com");+test("legacy Claude requests retain their native destination and Codex paths retain theirs", () => {+ const claude = { "anthropic-version": "2023-06-01" };+ assert.equal(routeOf("/v1/messages", claude)?.host, "api.anthropic.com");+ assert.equal(routeOf("/v1/messages/count_tokens", claude)?.host, "api.anthropic.com");+ assert.equal(routeOf("/backend-api/codex/responses", {})?.host, "chatgpt.com");+ assert.equal(routeOf("/backend-api/codex/images/generations", {})?.host, "chatgpt.com");assert.equal(forwardHeaders({ host: "127.0.0.1:17891", "anthropic-beta": "oauth-2025-04-20", connection: "keep-alive" }, "api.anthropic.com").host, "api.anthropic.com");assert.equal(forwardHeaders({ authorization: "Bearer x" }, "api.anthropic.com").authorization, "Bearer x");assert.equal(forwardHeaders({ connection: "keep-alive" }, "api.anthropic.com").connection, undefined);@@ -192,6 +193,16 @@ test("Codex's API-key requests go to api.openai.com/v1, its ChatGPT-login and Classert.deepEqual(routeOf("/v1/messages?beta=true", { authorization: "Bearer sk-ant-oat01-synthetic" }), { host: "api.anthropic.com", url: "/v1/messages?beta=true" });});+test("Claude credentials never fall through to a Codex destination when its request path changes", () => {+ const headers = { "x-claude-code-session-id": "synthetic", "anthropic-version": "2023-06-01", authorization: "Bearer sk-ant-oat01-synthetic", "x-api-key": "sk-ant-synthetic" };+ assert.deepEqual(routeOf("/new-endpoint?beta=true", headers), { host: "api.anthropic.com", url: "/new-endpoint?beta=true" });+ assert.equal(routeOf("/backend-api/codex/responses", headers), null, "a contradictory legacy endpoint is refused");+ assert.equal(routeOf("/unknown", {}), null, "unknown requests are refused locally");+ assert.equal(routeOf("/v1/responses", { authorization: "Bearer sk-proj-synthetic" }), null, "an OpenAI key is not sent to Anthropic based only on /v1/");+ assert.equal(forwardHeaders({ "chatgpt-account-id": "synthetic" }, "api.anthropic.com")["chatgpt-account-id"], undefined);+ assert.equal(forwardHeaders({ "x-api-key": "sk-ant-synthetic" }, "chatgpt.com")["x-api-key"], undefined);+});+test("NO_PROXY is checked against each upstream host on its own", () => {const env = { HTTPS_PROXY: "http://127.0.0.1:8888", NO_PROXY: "chatgpt.com" };assert.equal(outboundProxy(env, none, "chatgpt.com"), null);diff --git a/spike/src/routes.test.ts b/spike/src/routes.test.tsnew file mode 100644index 0000000..231b299--- /dev/null+++ b/spike/src/routes.test.ts@@ -0,0 +1,47 @@+import assert from "node:assert/strict";+import { execFileSync } from "node:child_process";+import { mkdtempSync, readFileSync, readdirSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { routeOf } from "../../plugin/src/proxy.ts";++test("registered providers retain their platform, origin, port, base path and query without exposing the target in the local URL", async () => {+ const routes = await import("../../plugin/src/routes.ts").catch(() => null);+ assert.ok(routes, "persistent provider routes are available");+ const root = mkdtempSync(join(tmpdir(), "cam-routes-"));+ const codex = routes.registerRoute({ platform: "codex", baseUrl: "http://127.0.0.1:12345/provider/v1?tenant=one" }, root);+ const claude = routes.registerRoute({ platform: "claude", baseUrl: "https://relay.example/anthropic" }, root);+ assert.notEqual(codex.id, claude.id);+ assert.deepEqual(routes.registerRoute({ platform: "codex", baseUrl: codex.baseUrl }, root), codex);+ const script = `import { registerRoute } from ${JSON.stringify(new URL("../../plugin/src/routes.ts", import.meta.url).href)}; process.stdout.write(registerRoute(${JSON.stringify({ platform: "codex", baseUrl: codex.baseUrl })}, ${JSON.stringify(root)}).id);`;+ assert.equal(execFileSync(process.execPath, ["--input-type=module", "-e", script], { encoding: "utf8" }), codex.id, "a fresh process uses the existing binding after an engine replacement");+ assert.match(routes.routeBaseUrl(17891, codex.id), /^http:\/\/localhost:17892\/__cam\/routes\/[a-f0-9]{32}$/, "registered traffic uses a port older engines never listen on");+ const forwarded = routeOf(`/__cam/routes/${codex.id}/responses?beta=1`, { "x-api-key": "synthetic-relay-key" }, root);+ assert.equal(forwarded?.host, "127.0.0.1");+ assert.equal(forwarded?.port, 12345);+ assert.equal(forwarded?.protocol, "http:");+ assert.equal(forwarded?.url, "/provider/v1/responses?tenant=one&beta=1");+ assert.equal(forwarded?.platform, "codex");+ assert.equal(routeOf(`/__cam/routes/${codex.id}/responses`, { authorization: "Bearer sk-ant-synthetic-relay" }, root)?.platform, "codex", "a relay's key format does not select its client platform");+ const other = routeOf(`/__cam/routes/${claude.id}/new-endpoint`, { "x-claude-code-session-id": "s" }, root);+ assert.equal(other?.host, "relay.example");+ assert.equal(other?.url, "/anthropic/new-endpoint");+ assert.equal(other?.platform, "claude");+ assert.equal(routeOf(`/__cam/routes/${codex.id}/responses`, { "x-claude-code-session-id": "s" }, root), null);+ assert.equal(routeOf(`/__cam/routes/${claude.id}/v1/messages`, { "chatgpt-account-id": "a" }, root), null);+ assert.equal(routeOf(`/__cam/routes/${"0".repeat(32)}/v1/messages`, {}, root), null);+ for (const name of readdirSync(join(root, "routes"))) {+ assert.ok(!readFileSync(join(root, "routes", name), "utf8").includes("synthetic-relay-key"));+ }+});++test("route registration refuses non-HTTP targets, embedded credentials and recursive engine routes", async () => {+ const routes = await import("../../plugin/src/routes.ts").catch(() => null);+ assert.ok(routes, "persistent provider routes are available");+ const root = mkdtempSync(join(tmpdir(), "cam-routes-"));+ for (const baseUrl of ["file:///etc/passwd", "https://user:[email protected]/v1", "https://relay.example/v1#fragment", "http://localhost:17891/__cam/routes/abc", "https://relay.example/\r\nx"]) {+ assert.throws(() => routes.registerRoute({ platform: "claude", baseUrl }, root));+ }+ assert.equal(routes.readRoute("../outside", root), null);+});diff --git a/spike/src/scripts-smoke.ts b/spike/src/scripts-smoke.tsindex 7508463..e44f12d 100644--- a/spike/src/scripts-smoke.ts+++ b/spike/src/scripts-smoke.ts@@ -6,7 +6,7 @@// engine. Output: a JSON summary on stdout; exit code 1 when a check fails.import { spawn } from "node:child_process";-import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { setTimeout as sleep } from "node:timers/promises";@@ -41,12 +41,25 @@ async function main(): Promise<boolean> {for (const dir of [home, data]) mkdirSync(dir, { recursive: true });const cli = findCodexCli();if (!cli) throw new Error("no Codex command line found (set CODEX_CLI_PATH or put codex on PATH)");+ const version = JSON.parse(readFileSync(join(root, "plugin", ".codex-plugin", "plugin.json"), "utf8")).version;+ const upgrade = process.argv.includes("--upgrade");+ let source = root;+ if (upgrade) {+ source = join(scratch, "old-marketplace");+ mkdirSync(join(source, ".agents", "plugins"), { recursive: true });+ cpSync(join(root, ".agents", "plugins", "marketplace.json"), join(source, ".agents", "plugins", "marketplace.json"));+ cpSync(join(root, "plugin"), join(source, "plugin"), { recursive: true });+ const manifest = join(source, "plugin", ".codex-plugin", "plugin.json");+ const old = JSON.parse(readFileSync(manifest, "utf8")); old.version = "0.8.3";+ writeFileSync(manifest, JSON.stringify(old));+ writeFileSync(join(source, "plugin", "src", "upgrade-sentinel.ts"), "// synthetic earlier build\n");+ }// The user's own settings, in this platform's line endings; they must come back byte for byte.const config = ['model = "gpt-6-sol"', "", "[features]", "view_image = true", ""].join(eol);const dotenv = `OTHER_SETTING=1${eol}`;writeFileSync(join(home, "config.toml"), config);writeFileSync(join(home, ".env"), dotenv);- const env = { ...process.env, CODEX_HOME: home, CAM_DATA_DIR: data, CAM_ENGINE_PORT: String(port), CAM_SOURCE: root, CODEX_CLI_PATH: cli };+ const env = { ...process.env, CODEX_HOME: home, CAM_DATA_DIR: data, CAM_ENGINE_PORT: String(port), CAM_SOURCE: source, CODEX_CLI_PATH: cli };const summary: Json = { platform: process.platform, cli, scratch, checks: {} };const checks: Record<string, boolean> = summary.checks;@@ -62,7 +75,21 @@ async function main(): Promise<boolean> {health = await engineHealth(port);if (!health) await sleep(250);}- const version = JSON.parse(readFileSync(join(root, "plugin", ".codex-plugin", "plugin.json"), "utf8")).version;+ if (upgrade) {+ const oldCache = join(cache, "0.8.3");+ const holding = spawn(process.execPath, ["-e", "console.log('ready');setInterval(()=>{},1000)"], { cwd: oldCache, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });+ const exited = new Promise<void>(resolve => holding.once("exit", () => resolve()));+ await new Promise<void>((resolve, reject) => { holding.once("error", reject); holding.stdout.once("data", () => resolve()); });+ try {+ env.CAM_SOURCE = root;+ const updated = await run("install", env);+ summary.upgrade = updated.output.split(/\r?\n/).slice(-12);+ checks.upgradeWithOldRuntimeOpen = updated.ok;+ checks.oldRuntimePreserved = existsSync(join(oldCache, "src", "cam.ts")) && existsSync(join(oldCache, "scripts", "launch.cmd"));+ checks.newRuntimeInstalled = existsSync(join(cache, version, "src", "cam.ts"));+ health = await engineHealth(port);+ } finally { holding.kill(); await exited; }+ }summary.engine = health ? { pid: health.pid, build: health.build, installedBuild: buildOf(join(cache, version, "src")) } : null;checks.engineFromInstalledCopy = !!health && health.build === buildOf(join(cache, version, "src"));diff --git a/spike/src/setup.test.ts b/spike/src/setup.test.tsindex c9c1d00..b9cfc01 100644--- a/spike/src/setup.test.ts+++ b/spike/src/setup.test.ts@@ -10,6 +10,7 @@ import { join } from "node:path";import test, { type TestContext } from "node:test";import { callTool, resetSetupBaseline } from "../../plugin/src/plugin-server.ts";import { connectDirectly, pluginGone, useEngine, usesEngine } from "../../plugin/src/setup.ts";+import * as setup from "../../plugin/src/setup.ts";import { sampleSessions, THREAD } from "./testfixtures.ts";// These tests check the Chinese wording: the language is fixed, so neither the system's language nor one a panel@@ -77,3 +78,73 @@ test("the plugin counts as gone only when its cache folder is missing or config.writeFileSync(join(home, "config.toml"), 'model = "gpt-6-sol"\n');assert.equal(pluginGone(), null, "an entry written some other way is not taken as a removal");});++test("custom provider setup persists its target before pointing Codex at the local route", (t) => {+ const { home, data } = tempHome(t);+ const original = 'model_provider = "relay"\n[model_providers.relay]\nbase_url = "https://relay.example:8443/prefix/v1"\nenv_key = "RELAY_API_KEY"\nwire_api = "responses"\n';+ writeFileSync(join(home, "config.toml"), original);+ useEngine(17891);+ const installed = readFileSync(join(home, "config.toml"), "utf8");+ assert.match(installed, /^base_url = "http:\/\/localhost:17892\/__cam\/routes\/[a-zA-Z0-9_-]+"$/m);+ const routes = join(data, "routes");+ assert.equal(existsSync(routes), true, "the upstream binding is already persisted when the config is written");+ const records = readdirSync(routes).filter((file) => file.endsWith(".json")).map((file) => JSON.parse(readFileSync(join(routes, file), "utf8")));+ assert.ok(records.some((record) => record.platform === "codex" && record.baseUrl === "https://relay.example:8443/prefix/v1"));+ assert.equal(useEngine(17891).configChanged, false);+ connectDirectly();+ assert.equal(readFileSync(join(home, "config.toml"), "utf8"), original);+});++test("unsupported provider syntax leaves config and env unchanged and creates no backup", (t) => {+ const { home, data } = tempHome(t);+ for (const original of [+ 'openai_base_url = """https://relay.example/v1"""\n',+ 'model_provider = "relay"\nmodel_providers = { relay = { base_url = "https://relay.example/v1", name = "Relay" } }\n',+ ]) {+ writeFileSync(join(home, "config.toml"), original);+ writeFileSync(join(home, ".env"), "OTHER=unchanged\n");+ assert.throws(() => useEngine(17891), (error: any) => error.key === "conflict.endpointSyntax");+ assert.equal(readFileSync(join(home, "config.toml"), "utf8"), original);+ assert.equal(readFileSync(join(home, ".env"), "utf8"), "OTHER=unchanged\n");+ assert.equal(existsSync(join(data, "config-backup")), false);+ assert.equal(existsSync(join(data, "routes")), false);+ }+});++test("setup rejects a provider pointing back at the engine on any path without changing files", (t) => {+ const { home, data } = tempHome(t);+ for (const target of ["http://localhost:17891/v1", "http://127.0.0.1:17891/other", "http://[::1]:17891/api", "https://localhost:17891/prefix", "http://localhost:17892/v1"]) {+ const original = `[model_providers.relay]\nbase_url = "${target}"\n`;+ writeFileSync(join(home, "config.toml"), original);+ assert.throws(() => useEngine(17891), (error: any) => error.key === "conflict.proxyLoop");+ assert.equal(readFileSync(join(home, "config.toml"), "utf8"), original);+ assert.equal(existsSync(join(data, "config-backup")), false);+ assert.equal(existsSync(join(data, "routes")), false);+ }+});++test("engine preflight plans custom routes without writing config, route records or backups", (t) => {+ const { home, data } = tempHome(t);+ const original = 'openai_base_url = "https://relay.example:8443/prefix/v1"\n';+ writeFileSync(join(home, "config.toml"), original);+ writeFileSync(join(home, ".env"), "OTHER=unchanged\n");+ const plan = setup.planEngine(17891);+ assert.equal(plan.configChanged, true);+ assert.match(plan.configText, /^openai_base_url = "http:\/\/localhost:17892\/__cam\/routes\/0{32}"$/m);+ assert.equal(readFileSync(join(home, "config.toml"), "utf8"), original);+ assert.equal(readFileSync(join(home, ".env"), "utf8"), "OTHER=unchanged\n");+ assert.deepEqual(readdirSync(data), []);+});++test("engine preflight rejects unsafe configuration without creating route data", (t) => {+ const { home, data } = tempHome(t);+ for (const [original, key] of [+ ['openai_base_url = """https://relay.example/v1"""\n', "conflict.endpointSyntax"],+ ['openai_base_url = "http://localhost:17891/v1"\n', "conflict.proxyLoop"],+ ]) {+ writeFileSync(join(home, "config.toml"), original);+ assert.throws(() => setup.planEngine(17891), (error: any) => error.key === key);+ assert.equal(readFileSync(join(home, "config.toml"), "utf8"), original);+ assert.deepEqual(readdirSync(data), []);+ }+});