Skip to content

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

feat(install): an agent finds its platform and installs the right adapter

chipfighter3a0794828c12
diff --git a/ADAPTERS.md b/ADAPTERS.md
index 14ffe35..f96b332 100644
--- a/ADAPTERS.md
+++ b/ADAPTERS.md
@@ -10,51 +10,22 @@ The panel (pick images, pin, search) is only in Codex and Claude Desktop. Every
## Agents you can connect now
-These adapters were written from each agent's code and docs and are **not tested live yet**. If one does not work for you, please [open an issue](https://github.com/chipfighter/context-attachment-manager/issues) with what you saw.
+WorkBuddy, OpenCode, Gemini CLI, pi and DeepSeek Harness. These adapters were written from each agent's code and docs and are **not tested live yet**. If one does not work for you, please [open an issue](https://github.com/chipfighter/context-attachment-manager/issues) with what you saw.
-All of them need this repository on your computer and Node.js 24 or later. From the repository folder, run `cam connect <agent>` (`cam.cmd` on Windows). It registers a route in the local engine, from a local address to where the agent's requests go now, and prints the exact settings to change. It changes no file of the agent's.
+How to install, step by step (also for an AI doing it for you): [INSTALL.md, Other agents](INSTALL.md#other-agents). In short, from a clone of this repository:
-### WorkBuddy
+- `cam detect` tells which agent a shell runs in, from the variables each agent sets for its commands, and prints the next command.
+- `cam connect <agent> --apply` registers a route in the local engine, from a local address to where the agent's requests go now, and writes the agent's settings: that address, and the MCP server for `cam_view_image`. Files are backed up first, and what was written is recorded.
+- `cam disconnect <agent>` puts back what was there, except settings changed since.
+- `cam connect <agent>` without `--apply` only prints the steps.
-```bash
-cam connect workbuddy
-```
-
-WorkBuddy's agent sends OpenAI Chat Completions requests to `CODEBUDDY_BASE_URL`, by default `https://www.workbuddy.cn/v2`. The command prints the local address to put in `~/.workbuddy/settings.json` under `env`, and the MCP server to add for `cam_view_image`. Sessions come from WorkBuddy's `x-conversation-id` header; its side requests (`x-agent-type: auxiliary`) pass unchanged.
-
-### OpenCode
-
-```bash
-cam connect opencode --base-url https://api.anthropic.com/v1
-```
-
-Give the address your provider uses now (Anthropic, OpenAI, an OpenAI-compatible service, Google). Put the printed address in `opencode.json` as that provider's `options.baseURL`, and add the printed MCP server under `mcp`. OpenCode's requests name no session the engine can read, so sessions are told apart by their first prompt.
-
-### Gemini CLI
-
-```bash
-cam connect gemini-cli
-```
-
-For an API key sign-in: set `GOOGLE_GEMINI_BASE_URL` to the printed address in `~/.gemini/.env`. For a Google sign-in: run `cam connect gemini-cli --base-url https://cloudcode-pa.googleapis.com` and set `CODE_ASSIST_ENDPOINT` instead. Add the printed MCP server under `mcpServers` in `~/.gemini/settings.json`.
-
-### pi
-
-```bash
-cam connect pi --base-url https://api.anthropic.com
-```
-
-Give the address your provider uses now. Put the printed address in `~/.pi/agent/models.json` as that provider's `baseUrl`, and load our extension (`plugin/src/adapters/pi/extension.ts`, with `pi -e` or in `~/.pi/agent/extensions/`). The extension names each request's session and registers the MCP server.
-
-### DeepSeek Harness
-
-DeepSeek Harness needs no route: `plugin/src/adapters/dsh/plugin.ts` is a dsh plugin. In your composition's `cordis.yml`, replace the `@deepseek-ai/dsh-compaction-image-offload` row with one whose `name` is the path to that file. It keeps what dsh's own plugin does (offloading the oldest images when a route refuses a request as over its image budget) and adds auto-select: when a new turn starts, it offloads every image of the turns before. dsh shows an offloaded image as text with a read-only path, and the model reads it back from there.
+DeepSeek Harness needs no route: `plugin/src/adapters/dsh` is a dsh bundle, installed with `dsh plugin --profile <profile> add <folder>`. It turns dsh's own image offload (`@deepseek-ai/dsh-compaction-image-offload`) off and does what it did, offloading the oldest images when a route refuses a request as over its image budget, and also offloads every earlier turn's images when a new turn starts. dsh shows an offloaded image as text with a read-only path, and the model reads it back from there.
## Adding your agent
A pull request that adds an agent touches these places:
-1. **`plugin/src/adapters/<name>/platform.ts`**: the agent's entry, a `CorePlatform` (`plugin/src/core/platform.ts`). WorkBuddy's whole adapter:
+1. **`plugin/src/adapters/<name>/platform.ts`**: the agent's entry, a `CorePlatform` (`plugin/src/core/platform.ts`). WorkBuddy's adapter, in short:
```ts
export const workbuddy: CorePlatform = {
@@ -63,12 +34,14 @@ A pull request that adds an agent touches these places:
upstream: "https://www.workbuddy.cn/v2",
sessionOf: (headers) => headerOf(headers, "x-conversation-id"),
sideRequest: (headers) => headerOf(headers, "x-agent-type") === "auxiliary",
+ detect: (env) => env.CODEBUDDY === "1" && /* WorkBuddy's own marks */ true,
+ setup: ({ home, env }) => ({ current, fallback, edits }), // what cam connect --apply writes
connect: ({ url, mcp }) => [/* the steps cam connect prints */],
};
```
2. **`plugin/src/platforms.ts`**: one line in `CORE_PLATFORMS`.
-3. **Tests** in `spike/src/platforms.test.ts`: a request as your agent sends it, rewritten as expected. Run `node --test` from the repository root.
+3. **Tests**: in `spike/src/platforms.test.ts`, a request as your agent sends it, rewritten as expected; in `spike/src/connect.test.ts`, what `detect` and `setup` read and write. Run `node --test` from the repository root.
4. **The "Works with" table** at the bottom of `README.md` (and `README_CN.md`, `README_JA.md` if you can; we will fill them in otherwise): one row with a link, one line on what your agent is, and how far it is tested.
What the engine needs from an agent:
@@ -76,6 +49,8 @@ What the engine needs from an agent:
- **A way to send its model requests through the engine.** Usually a base URL setting; `cam connect` registers the route. The engine keeps every header except its own (`x-cam-*`), and the credentials stay in the agent's requests.
- **A request format the translators know.** The engine tells it by the path: `/chat/completions`, `/responses`, `/messages`, `:generateContent`, `:streamGenerateContent`. A new format is a new translator in `plugin/src/adapters/protocols/<format>/` and an entry in `spike/src/contract.test.ts`, which checks every translator the same way.
- **A session id, if it has one.** Name the header in `sessionOf`. An agent with extensions can add `x-cam-session` to each request instead (see the pi extension). Without either, sessions are told apart by their first prompt, which works but can merge two sessions that start with the same words.
+- **A variable it sets for the shell commands it runs** (`detect`), so `cam detect` and an AI installing the plugin pick your agent and no other.
+- **Settings files `cam connect --apply` can write** (`setup`): where the base URL and the MCP servers go. Plain JSON or `NAME=value` lines; without `setup`, the steps are only printed.
- **An MCP server**, so the model has `cam_view_image`: `node plugin/src/plugin-server.ts` with `CAM_HOST=<name>`. It also keeps the engine running while the agent runs.
An agent that runs plugins inside its own process, like DeepSeek Harness, can do auto-select there instead of going through the engine. Keep its rule the same: when a new turn starts, earlier turns' images leave the request, and the model has a way to get one back.
diff --git a/INSTALL.md b/INSTALL.md
index d525b86..491f44e 100644
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -1,6 +1,6 @@
# Install
-The easy way: paste this to Codex, or to Claude in Claude Desktop's Code tab, and let it do the steps below for you.
+The easy way: paste this to your agent (Codex, Claude Desktop's Code tab, WorkBuddy, OpenCode, Gemini CLI, pi or DeepSeek Harness) and let it do the steps below for you.
```text
Install the Context Attachment Manager plugin for me, following https://github.com/chipfighter/context-attachment-manager/blob/main/INSTALL.md
@@ -8,9 +8,23 @@ Install the Context Attachment Manager plugin for me, following https://github.c
## For AI assistants
-- Install for the app the user is talking to you in: the Codex desktop app, or Claude Desktop's Code tab. Install for both only if the user asks.
-- Follow that app's section below and run the commands yourself.
-- When you are done, tell the user the one step left for them: restart Codex, or start a new session in Claude Desktop's Code tab. Then tell them how to open the panel (see [Open the panel](#open-the-panel)).
+Install for the agent the user is talking to you in, and only that one. Which agent that is does not depend on the model you are: a DeepSeek model running in WorkBuddy installs for WorkBuddy.
+
+1. **Find the agent.** Run `env` (`Get-ChildItem Env:` in PowerShell) and look for these variables, which each agent sets for the commands you run:
+
+ | Variable | Agent | Section |
+ |---|---|---|
+ | `CODEX_THREAD_ID` | Codex | [Codex](#codex) |
+ | `CLAUDECODE=1` | Claude Code | [Claude Desktop](#claude-desktop) |
+ | `CODEBUDDY=1` | WorkBuddy (CodeBuddy's agent) | [Other agents](#other-agents) |
+ | `OPENCODE=1` | OpenCode | [Other agents](#other-agents) |
+ | `GEMINI_CLI=1` | Gemini CLI | [Other agents](#other-agents) |
+ | `PI_SESSION_ID` | pi | [Other agents](#other-agents) |
+ | `DSH_SHELL=1` | DeepSeek Harness | [Other agents](#other-agents) |
+
+ If none matches, or more than one, ask the user which agent this is. For the other agents, `cam detect` (below) checks the same variables and prints the exact command to run next.
+2. **Follow that section only**, and run the commands yourself. Do not edit the agent's settings by hand: the commands back them up and record what they wrote, so they can be undone.
+3. **When you are done**, tell the user the one step left for them: restart the agent (in Claude Desktop, start a new session in the Code tab). For Codex and Claude Desktop, also tell them how to open the panel (see [Open the panel](#open-the-panel)); the other agents have no panel, and there is nothing to open.
## Codex
@@ -59,11 +73,37 @@ 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.
+## Other agents
+
+WorkBuddy, OpenCode, Gemini CLI, pi and DeepSeek Harness get auto-select without a panel: earlier turns' images go out as short placeholders, and the model pulls back the one it needs by its id. These adapters are new and were not tested on the agents themselves yet; please [open an issue](https://github.com/chipfighter/context-attachment-manager/issues) if one does not work for you.
+
+They need [Node.js 24 or later](https://nodejs.org) (`node --version`) and the plugin's code in a folder where it can stay (the agent runs it from there):
+
+```bash
+git clone --depth 1 https://github.com/chipfighter/context-attachment-manager.git "$HOME/context-attachment-manager"
+```
+
+Then let it find the agent and print the command to run:
+
+```bash
+node "$HOME/context-attachment-manager/plugin/src/cam.ts" detect
+```
+
+Run the command it prints under `next`, then restart the agent. What that command does for each agent:
+
+- **WorkBuddy**: `cam connect workbuddy --apply` sets `CODEBUDDY_BASE_URL` under `env` in `~/.workbuddy/settings.json` and adds the plugin's MCP server to `~/.workbuddy/.mcp.json`. A relay address set there before stays the destination.
+- **OpenCode**: `cam connect opencode --apply` sets `options.baseURL` of the provider your `model` uses (or `--provider <id>`) in `~/.config/opencode/opencode.json`, and adds the MCP server under `mcp`. A config file with comments is not changed; the command says so, and `cam connect opencode` without `--apply` prints the steps instead.
+- **Gemini CLI**: `cam connect gemini-cli --apply` sets `GOOGLE_GEMINI_BASE_URL` (API key sign-in) or `CODE_ASSIST_ENDPOINT` (Google sign-in) in `~/.gemini/.env`, and adds the MCP server to `~/.gemini/settings.json`. A `.env` in your project folder that sets the same variable wins over it. Vertex AI is not supported.
+- **pi**: `cam connect pi --apply` sets `baseUrl` of the provider pi uses now (or `--provider <name>`) in `~/.pi/agent/models.json`, and lists the plugin's pi extension under `extensions` in `~/.pi/agent/settings.json`. The extension adds the MCP server.
+- **DeepSeek Harness**: `dsh plugin --profile <profile> add "<folder>/plugin/src/adapters/dsh"` installs the plugin as a dsh bundle. It turns dsh's own image offload off and does what it did, and also offloads earlier turns' images when a new turn starts. The model reads an offloaded image back from the path its placeholder names.
+
+Each `cam connect --apply` backs the files up first (in the data folder, see [Your data](#your-data)), and keeps the address the agent used before as the destination: requests go there through the engine. Run it again after an update; it keeps what it found the first time.
+
## 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.
+- **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. When a switching tool such as cc-switch writes another provider's address, the engine notices within a moment and points Codex at it through the engine again, so you can keep switching models; restart Codex as the switching tool asks. If Codex was closed during the switch, the first start after it connects directly, and the next one goes through the engine again. Disable the plugin in the panel to stop this.
- **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.
@@ -104,6 +144,18 @@ curl -fsSL https://github.com/chipfighter/context-attachment-manager/releases/la
Uninstall it with **Manage plugins** under **+** → **Plugins** in the Code tab, or with `claude plugin uninstall codex-attachment-manager@codex-attachment-manager`. New sessions then connect directly; there is nothing to restore.
+### Other agents
+
+Undo the settings first, then restart the agent and delete the folder:
+
+```bash
+node "$HOME/context-attachment-manager/plugin/src/cam.ts" disconnect <agent>
+```
+
+`<agent>` is `workbuddy`, `opencode`, `gemini-cli` or `pi`. It puts back what was there before, except settings you changed since. For DeepSeek Harness: `dsh plugin --profile <profile> remove dsh-context-attachment-manager`.
+
+Remove the plugin only after this: an agent still pointed at the engine cannot connect once nothing starts it.
+
### Your data
Your selections and logs stay in the data folder: `%USERPROFILE%\.codex-attachment-manager` on Windows, `~/Library/Application Support/codex-attachment-manager` on macOS, `~/.local/share/codex-attachment-manager` on Linux. It holds selections, request statistics (sizes and counts, never content), logs (no conversation content or credentials) and the backup of `config.toml`. Delete it if you don't need it.
diff --git a/README.md b/README.md
index 901621b..067126d 100644
--- a/README.md
+++ b/README.md
@@ -62,13 +62,13 @@ Using a gateway? Compatible Codex and Claude Code endpoints can use image manage
## Install
-Paste this to Codex, or to Claude in Claude Desktop's Code tab:
+Paste this to your agent (Codex, Claude Desktop's Code tab, or any agent in [Works with](#works-with)). It finds out which agent it runs in and installs for that one:
```text
Install the Context Attachment Manager plugin for me, following https://github.com/chipfighter/context-attachment-manager/blob/main/INSTALL.md
```
-Then restart Codex, or start a new session in Claude. To install or uninstall it yourself, see [INSTALL.md](INSTALL.md). Using another agent? See [Works with](#works-with) at the bottom.
+Then restart the agent (in Claude Desktop, start a new session). To install or uninstall it yourself, see [INSTALL.md](INSTALL.md).
## Privacy
@@ -95,6 +95,6 @@ The plugin's core knows no platform; each one gets a thin adapter. The panel is
| [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) | DeepSeek's agent harness where everything is a plugin | Auto-select (dsh plugin), new, feedback welcome |
| **Your agent** | A thin adapter; the core stays as it is | Send a PR and add your agent here: [ADAPTERS.md](ADAPTERS.md) |
-To connect one of the new ones, see [ADAPTERS.md](ADAPTERS.md): `cam connect <agent>` prints the settings to change. Something off? [Open an issue](https://github.com/chipfighter/context-attachment-manager/issues).
+To install on any of them, paste the sentence in [Install](#install) to that agent; how each one is connected is in [INSTALL.md](INSTALL.md#other-agents). Something off? [Open an issue](https://github.com/chipfighter/context-attachment-manager/issues).
<p align="center"><sub><a href="CHANGELOG.md">Changelog</a> · <a href="CONTRIBUTING.md">Contributing</a> · <a href="LICENSE">MIT License</a></sub></p>
diff --git a/README_CN.md b/README_CN.md
index b502df7..13ed78b 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -62,13 +62,13 @@ https://github.com/user-attachments/assets/b9767a20-8ca4-4a33-86bc-5e0a16a2ed13
## 安装
-把这句话发给 Codex,或者 Claude 桌面版 Code 标签页里的 Claude:
+把这句话发给你的 Agent(Codex、Claude 桌面版的 Code 标签页,或者[支持的平台](#支持的平台)里的任何一个)。它会先认出自己在哪个平台,再装对应的那一份:
```text
帮我安装 Context Attachment Manager 插件,按这里的说明来:https://github.com/chipfighter/context-attachment-manager/blob/main/INSTALL.md
```
-装好后重启 Codex,或者在 Claude 里新建一个会话。想自己动手安装或卸载,看 [INSTALL.md](INSTALL.md)(英文)。用的是别的 Agent?见页面底部的[支持的平台](#支持的平台)。
+装好后重启这个 Agent(Claude 桌面版是新建一个会话)。想自己动手安装或卸载,看 [INSTALL.md](INSTALL.md)(英文)。
## 隐私
@@ -95,6 +95,6 @@ https://github.com/user-attachments/assets/b9767a20-8ca4-4a33-86bc-5e0a16a2ed13
| [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) | DeepSeek 的智能体框架,一切皆插件 | 自动选图(dsh 插件),新接入,欢迎反馈 |
| **你的 Agent** | 写一层薄薄的接入,核心一行不用改 | 提个 PR,把你的平台加到这里:[接入说明](ADAPTERS.md)(英文) |
-新接入的平台怎么接上,见 [ADAPTERS.md](ADAPTERS.md):一条 `cam connect <平台>` 命令给出要改的设置。用下来有问题,欢迎[提 issue](https://github.com/chipfighter/context-attachment-manager/issues)。
+在哪个平台上装,就把[安装](#安装)里那句话发给那个平台的 Agent;各平台具体改了什么,见 [INSTALL.md](INSTALL.md#other-agents)(英文)。用下来有问题,欢迎[提 issue](https://github.com/chipfighter/context-attachment-manager/issues)。
<p align="center"><sub><a href="CHANGELOG.md">更新记录</a> · <a href="CONTRIBUTING.md">参与开发</a> · <a href="LICENSE">MIT 许可证</a></sub></p>
diff --git a/README_JA.md b/README_JA.md
index 3df356b..2fd90eb 100644
--- a/README_JA.md
+++ b/README_JA.md
@@ -47,13 +47,13 @@
## インストール
-次の文を Codex、または Claude Desktop の **Code** タブにいる Claude に送ってください。
+次の文をお使いのエージェント(Codex、Claude Desktop の **Code** タブ、または[対応エージェント](#対応エージェント)のいずれか)に送ってください。エージェントは自分がどれかを確かめてから、それに合わせてインストールします。
```text
次の手順に従って、Context Attachment Manager プラグインをインストールしてください:https://github.com/chipfighter/context-attachment-manager/blob/main/INSTALL.md
```
-インストール後は Codex を再起動してください。Claude Desktop では **Code** タブで新しいセッションを始めてください。手動でのインストール、更新、アンインストールの手順は、共通の [INSTALL.md](INSTALL.md)(英語)にあります。ほかのエージェントをお使いの場合は、ページ下部の[対応エージェント](#対応エージェント)をご覧ください。
+インストール後はエージェントを再起動してください(Claude Desktop では **Code** タブで新しいセッションを始めてください)。手動でのインストール、更新、アンインストールの手順は、共通の [INSTALL.md](INSTALL.md)(英語)にあります。
## パネルを開く
@@ -97,6 +97,6 @@ Codex で短編ドラマのキーフレーム 9 枚、合計約 32 MB の画像
| [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) | すべてがプラグインの DeepSeek のエージェント基盤 | 自動選択(dsh プラグイン)、新規対応、フィードバック歓迎 |
| **あなたのエージェント** | 薄い接続層を書くだけで、コアは変更不要 | PR を送って、ここに追加してください:[ADAPTERS.md](ADAPTERS.md)(英語) |
-新しく対応したエージェントの接続方法は [ADAPTERS.md](ADAPTERS.md)(英語)にあります。`cam connect <エージェント>` で変更する設定が表示されます。問題があれば [issue](https://github.com/chipfighter/context-attachment-manager/issues) でお知らせください。
+どのエージェントでも、[インストール](#インストール)の文をそのエージェントに送ればインストールできます。各エージェントで何を変更するかは [INSTALL.md](INSTALL.md#other-agents)(英語)にあります。問題があれば [issue](https://github.com/chipfighter/context-attachment-manager/issues) でお知らせください。
<p align="center"><sub><a href="CHANGELOG.md">変更履歴(英語)</a> · <a href="CONTRIBUTING.md">開発への参加(英語)</a> · <a href="LICENSE">MIT ライセンス</a></sub></p>
diff --git a/docs/design.md b/docs/design.md
index 9a0e630..594c4aa 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -32,7 +32,9 @@ v0.11 起代码分成三层([v0.11/plan.md](v0.11/plan.md)):`core/` 是不
| Claude 思考记录和提示缓存(v0.4、v0.10) | `adapters/protocols/anthropic-messages/thinking.ts`、`adapters/protocols/anthropic-messages/cache.ts` | 账号校验思考记录时,去掉和实际发出的历史对不上的思考;改过历史后,让提示缓存仍能读到 |
| 面板页(v0.4) | `panel/panel-web.js`、`panel/panel-language.ts`、`adapters/claude/panel-web.ts` | 引擎把 `panel.html` 作为网页提供时,代替 MCP 应用的宿主 |
| 只接核心的平台(v0.11) | `platforms.ts`、`core/platform.ts`、`core/request-index.ts`、`adapters/protocols/any.ts`、`adapters/protocols/openai-chat/rewrite.ts`、`adapters/protocols/gemini/rewrite.ts`、`adapters/{workbuddy,opencode,gemini-cli,pi}/platform.ts`、`adapters/pi/extension.ts` | 平台登记表和每个平台的条目;按路径认格式,从请求本身认图、按内容编号、存原图,自动选图一直开着;`cam connect` 登记线路;pi 的扩展加会话头、注册取图服务 |
-| DeepSeek Harness(v0.11) | `adapters/dsh/plugin.ts` | dsh 插件,顶替官方的图片卸载插件:新一轮开始时卸载之前各轮的图,图片超预算时照旧卸载最旧的 |
+| DeepSeek Harness(v0.11) | `adapters/dsh/index.js`、`adapters/dsh/offload.js`、`adapters/dsh/package.json`、`adapters/dsh/cordis.patch.yml` | dsh 插件包:装上时停掉官方的图片卸载行,新一轮开始时卸载之前各轮的图,图片超预算时照旧卸载最旧的 |
+| 安装到其他平台(v0.11) | `platforms.ts`(`detectPlatform`)、`core/config-edit.ts`、各平台条目的 `detect` 和 `setup`、`cam.ts`(`detect`、`connect --apply`、`disconnect`) | 按环境变量认平台;改平台的设置文件,先备份、记下改动,撤回时只动还保持原样的设置 |
+| 换模型后接回 Codex(v0.11) | `adapters/codex/setup.ts`(`wantsEngine`、`keepRouted`)、`adapters/codex/codexconfig.ts`(`routedThroughEngine`)、`proxy.ts` | config.toml 被 cc-switch 之类改写后,引擎重新接上,线路指向用户新选的服务商 |
引擎和插件服务之间只通过数据目录里的文件共享状态,任何一方不在,另一方都照常工作。
diff --git a/docs/spec.md b/docs/spec.md
index 8ae50ff..424da07 100644
--- a/docs/spec.md
+++ b/docs/spec.md
@@ -365,6 +365,8 @@ v0.1 之前的阶段验收(阶段 0 的重建路线、代理路线 P2)都已
3. 有对外的接入接口文档(英文)和契约测试;面板在文档里是可选的一节,新平台默认不接。
4. 其他平台只接核心、不带面板:WorkBuddy、OpenCode、Gemini CLI、pi 的请求经过引擎,之前各轮的图按自动选图省略,模型能按编号取回;DeepSeek Harness 用顶替官方插件的 dsh 插件,新一轮开始时卸载之前各轮的图。用户 2026-11-02 定不在本机实跑:按各平台的代码和文档写接入,用合成请求测试,README 的平台表标明没实测,等用户反馈。
5. README 开头改成多模态税的口径,删掉“为什么做这个”,底部有平台表(简介和接入情况);`ADAPTERS.md` 写各平台的接法和怎么加新平台。
+6. 安装:用户把 README 里那句话发给所在平台的 Agent,Agent 照 INSTALL.md 装对平台。平台由各平台给命令设的环境变量认出(`cam detect`),认不出或认出多个就问用户;只接核心的平台由 `cam connect <平台> --apply` 改设置(先备份、记下改动),`cam disconnect` 撤回,用户之后改过的设置不动。
+7. Codex 被换模型的工具(如 cc-switch)改写服务地址后,引擎重新接上,请求经过引擎发往用户新选的服务商;用户停用了插件就不再接。
## 5. 待定问题
diff --git a/docs/v0.11/plan.md b/docs/v0.11/plan.md
index 76139e2..c35651e 100644
--- a/docs/v0.11/plan.md
+++ b/docs/v0.11/plan.md
@@ -1,6 +1,6 @@
# v0.11 方案:拆成接入层、核心层、面板层,接入其他 Agent 平台
-> 状态:用户 2026-11-02 确认方案(第 7 节)。第 1–8 步已做完,在本机 main 上,没有推送;剩 Claude 桌面版实测和发布。规格以 [spec.md](../spec.md) 为准,实现见 [design.md](../design.md),对外的接入说明是 [ADAPTERS.md](../../ADAPTERS.md)。本机的摸底记录和参考项目的笔记只在 `local/`,不进仓库。
+> 状态:用户 2026-11-02 确认方案(第 7 节)。第 1–8 步已做完,在本机 main 上,没有推送;剩 Claude 桌面版实测和发布,之后改 README、定仓库名字、简介、标签,做视频和图片(第 7 节)。规格以 [spec.md](../spec.md) 为准,实现见 [design.md](../design.md),对外的接入说明是 [ADAPTERS.md](../../ADAPTERS.md)。本机的摸底记录和参考项目的笔记只在 `local/`,不进仓库。
## 1. 背景与目标
@@ -43,7 +43,7 @@ plugin/src/
protocols/ 请求格式的翻译器:openai-responses、anthropic-messages、openai-chat、gemini;any.ts 给只接核心的平台用
codex/、claude/ 带面板的两个平台,各自读本地记录、改配置、开面板
workbuddy/、opencode/、gemini-cli/、pi/ 只接核心的平台,每个一个 platform.ts(pi 另有扩展)
- dsh/ DeepSeek Harness 的 dsh 插件
+ dsh/ DeepSeek Harness 的 dsh 插件包(index.js、offload.js、package.json、cordis.patch.yml)
```
- 宿主规定位置的文件(`.codex-plugin/`、`.claude-plugin/`、`hooks/`、`.mcp.json`、启动脚本)留在原处,只改它们指向的入口。
@@ -62,10 +62,11 @@ plugin/src/
- **带面板的平台**(Codex、Claude Code):接入层读平台自己的本地记录(任务记录、会话记录),认会话、轮次、子代理和旁聊、压缩,改平台的配置,打开面板,还有平台特有的处理(Codex 的 WebSocket 降级、API key 线路;Claude 的思考签名重试、提示缓存)。这两份接入是厚的,因为面板要用这些信息。
- **只接核心的平台**(其余所有平台):接入层只填一个条目(`core/platform.ts` 的 `CorePlatform`):
1. **名字**;
- 2. **原地址**:它的模型请求本来发去哪(按服务商填地址的平台,由用户在 `cam connect` 时给出);
+ 2. **原地址**:它的模型请求本来发去哪(按服务商填地址的平台,从它的设置里读,或用户在 `cam connect` 时给出);
3. **认会话**(可选):哪个请求头是会话编号;
4. **旁路请求**(可选):哪些请求不改(起标题、润色提示之类);
- 5. **接法**:用户要改哪些设置,`cam connect` 打出来。
+ 5. **认平台**:平台给它跑的命令设的环境变量(`cam detect` 用);
+ 6. **装法**:要改哪些设置文件、改成什么(`cam connect --apply` 照着写),以及给人看的步骤。
平台加一行进 `platforms.ts` 就接上了。请求格式、哪几张图、省略哪些,都由核心和翻译器从请求本身算出来(第 3.8 节)。
@@ -92,7 +93,8 @@ plugin/src/
### 3.7 发布
- 仍是一个版本、一份内容。全机只有一个引擎,所有平台共用;各平台装不同版本时,引擎会互相请对方退役,Codex 和 Claude 两份副本之间已经出现过(design 第 5 节)。所以不按平台拆成不同的包。
-- 每个平台按它自己的方式装:Codex、Claude 照旧走各自的插件市场和安装命令;只接核心的平台在仓库里运行 `cam connect <平台>`,它登记线路、打出要改的设置,不替用户改平台的文件(没实测过,不自动改别人的配置)。
+- 每个平台按它自己的方式装:Codex、Claude 照旧走各自的插件市场和安装命令;只接核心的平台把仓库克隆到一个固定的文件夹,`cam detect` 认出平台,`cam connect <平台> --apply` 登记线路并改好平台的设置,`cam disconnect` 撤回;DeepSeek Harness 用 `dsh plugin add` 装 dsh 包。
+- 用户 2026-11-02 定:用户把一句话发给自己的 Agent,Agent 看仓库就能在对应的平台上装好,而且不会装错(例如 WorkBuddy 里的 DeepSeek 模型要装 WorkBuddy 的那一份)。所以平台由各平台给命令设的环境变量来认,不靠模型自己猜;改设置由命令来做,不让模型手改:先备份,记下改了什么、原来是什么,`cam disconnect` 只撤回还保持原样的设置。带注释的 JSON 不改,只打出步骤。
- 面板文件随包一起发,只有 Codex 桌面版和 Claude 桌面版的接入打开它。
- 拆的过程中插件版本号不动,免得 Codex 中途从工作区自动重装;全部做完再升到 0.11.0 发布。
@@ -110,10 +112,11 @@ plugin/src/
### 3.9 DeepSeek Harness(用户 2026-11-02 定:在接入层里顶替它官方的插件)
-DSH 的请求可能用 DeepSeek 的文件模式发图(请求里是文件引用,不是图片数据),走引擎改不了,所以做成 dsh 插件(`adapters/dsh/plugin.ts`),在 `cordis.yml` 里顶替官方的 `@deepseek-ai/dsh-compaction-image-offload`:
+DSH 的请求可能用 DeepSeek 的文件模式发图(请求里是文件引用,不是图片数据),走引擎改不了,所以做成 dsh 插件包(`adapters/dsh/`),用 `dsh plugin --profile <配置档> add` 装。包里的补丁按 `id` 把官方底包的 `image-offload` 行停掉(两者注册同一个消息投影,只能留一个),再插上我们的(用户 2026-11-02 问能不能直接停掉官方的:能,装包时自动停):
- 保留官方插件做的事:服务因图片超预算拒绝请求时,标记最旧的几张卸载,然后重试。
- 加上自动选图:新一轮开始时(`agent/pre-step` 里轮次变了),把之前各轮还留着的图全部标记卸载。
+- 官方的超预算卸载留在我们的插件里当兜底:一轮里就可能超预算(一步一张截图地控制浏览器),没有它请求会报错、这一轮结束。
- 卸载是 DSH 自己的机制:写进会话日志、永不撤回,模型看到的是写着附件名和只读路径的文字,需要时自己读回原图。所以不需要我们的取图工具,提示缓存的前缀也只往前走。
## 4. WorkBuddy 摸底(2026-11-02,本机 5.9.3,只看代码,没跑对话)
@@ -137,14 +140,14 @@ DSH 的请求可能用 DeepSeek 的文件模式发图(请求里是文件引用
5. 拆面板:`panel-state.ts` 只读核心接口;插件服务里的面板工具和取图工具分开。
6. 拆安装:Codex 的配置和命令行、Claude 的 Mod 进各自的接入。
7. 写 `ADAPTERS.md`(英文,对外)和契约测试;在 Codex 和 Claude 里跑一遍模型自测(gpt-6-sol,中英文)。
-8. 接其他平台:平台登记表(自动选图的规则收进核心、会话编号不限 UUID、引擎认所有平台的探活);openai-chat、gemini 两个翻译器;核心从请求建清单;WorkBuddy、OpenCode、Gemini CLI、pi 的条目,pi 的扩展,DSH 的插件;`cam connect`;README 底部的平台表。不带面板,不实跑(第 7 节)。
+8. 接其他平台:平台登记表(自动选图的规则收进核心、会话编号不限 UUID、引擎认所有平台的探活);openai-chat、gemini 两个翻译器;核心从请求建清单;WorkBuddy、OpenCode、Gemini CLI、pi 的条目,pi 的扩展,DSH 的插件包;`cam detect`、`cam connect --apply`、`cam disconnect`;INSTALL.md 按平台写;Codex 在 cc-switch 切换后自动接回;README 底部的平台表。不带面板,不实跑(第 7 节)。
9. Claude 桌面版实跑一轮,然后推送、发 0.11.0。
## 6. 风险
- 第 2、3 步动的是每个请求都经过的代码,最容易出回归。靠逐字节对照测试兜底。
- 只接核心的五个平台都没实跑过,只有合成请求的测试。README 的平台表写明“新接入,欢迎反馈”,和实测过的 Codex、Claude 分开。
-- cc-switch(切换 Claude Code、Codex 等的服务地址)每次切 Codex 的服务商,会删掉顶层的 `openai_base_url`、重写 `[model_providers.custom]`,把插件对 Codex 的接管抹掉,之后 Codex 直连,直到在面板里重新启用或重跑 `cam install`。Claude Code 不受影响:插件每个会话开始时重新读地址。
+- cc-switch(切换 Claude Code、Codex 等的服务地址)每次切 Codex 的服务商,会删掉顶层的 `openai_base_url`、重写 `[model_providers.custom]`,把插件对 Codex 的接管抹掉。用户 2026-11-02 定:用户要能随便换模型,插件也照样起作用。所以引擎盯着 config.toml,一被改写就重新接上,线路指向用户刚选的服务商,切换照样生效(`adapters/codex/setup.ts` 的 `keepRouted`)。只在用户想用引擎(启用过、没停用,记在数据目录,不看 config.toml)且插件还在时做;十分钟里被改回三次就停手,免得和别的工具来回改。Codex 关着时切换的,下次启动先直连一次,再下次才经过引擎。Claude Code 不受影响:插件每个会话开始时重新读地址。没和真的 cc-switch 一起跑过。
- 文件搬家后,已安装的副本要靠 `cam install` 更新;启动脚本里的入口路径要一起改,不能让已安装的配置指向不存在的文件。
## 7. 用户的决定(2026-11-02)
@@ -157,3 +160,7 @@ DSH 的请求可能用 DeepSeek 的文件模式发图(请求里是文件引用
6. WorkBuddy 不再测;其余平台也不在本机实跑,按代码和文档写接入,对外展示,等别人提 issue 和 PR。
7. 接入的平台:WorkBuddy、OpenCode、Gemini CLI、pi 写进接入层;DeepSeek Harness 在接入层里顶替它官方的插件,接不进就先不要;Antigravity 不写。
8. README:删掉“为什么做这个”;开头改成多模态税的口径(多模态上下文的自动管理工具,装上就不用管),场景写短;最底下放平台表(各平台的简介和接入情况),不挡上面的展示内容,用来和其他平台双向引流。
+9. 用户换模型(cc-switch 等)后插件要照样起作用(第 6 节)。
+10. 安装:Agent 看仓库就能在所在平台装对,平台靠环境变量认,设置由命令改(第 3.7 节)。
+11. DeepSeek Harness 直接停掉官方的图片卸载,用我们的(第 3.9 节)。
+12. 这几个平台接完以后,再改 README、定新的仓库名字、简介、标签,做新的视频和图片,调整宣传口径。
diff --git a/plugin/src/adapters/gemini-cli/platform.ts b/plugin/src/adapters/gemini-cli/platform.ts
index 3f9053e..72af0af 100644
--- a/plugin/src/adapters/gemini-cli/platform.ts
+++ b/plugin/src/adapters/gemini-cli/platform.ts
@@ -1,20 +1,42 @@
// Purpose: v0.11 — Gemini CLI: the core alone, no panel. Signed in with an API key it sends Gemini generateContent
// requests to GOOGLE_GEMINI_BASE_URL (by default https://generativelanguage.googleapis.com); signed in with Google, the
-// same contents wrapped in `request` to CODE_ASSIST_ENDPOINT (by default https://cloudcode-pa.googleapis.com), which
-// takes a route of its own (`cam connect gemini-cli --base-url https://cloudcode-pa.googleapis.com`). Its requests name
-// no session the engine knows, so sessions are told apart by their first prompt. MCP servers go under "mcpServers" in
-// ~/.gemini/settings.json. Not tested live.
-// Input: none. Output: the platform's entry for the engine (core/platform.ts).
+// same contents wrapped in `request` to CODE_ASSIST_ENDPOINT (by default https://cloudcode-pa.googleapis.com). Which one
+// is `security.auth.selectedType` in ~/.gemini/settings.json; Vertex AI is not handled. Gemini CLI loads the first .env
+// it finds from the project folder upward, then ~/.gemini/.env. Its requests name no session the engine knows, so
+// sessions are told apart by their first prompt. MCP servers go under "mcpServers" in ~/.gemini/settings.json; shell
+// commands run with GEMINI_CLI=1. Not tested live.
+// Input: the environment, the settings files. Output: the platform's entry (core/platform.ts).
-import type { CorePlatform } from "../../core/platform.ts";
+import { join } from "node:path";
+import { envAt, jsonAt } from "../../core/config-edit.ts";
+import { MCP_NAME, type CorePlatform } from "../../core/platform.ts";
export const geminiCli: CorePlatform = {
name: "gemini-cli",
title: "Gemini CLI",
upstream: "https://generativelanguage.googleapis.com",
+ detect: (env) => env.GEMINI_CLI === "1",
+ setup: ({ home, env }) => {
+ const dir = join(home, ".gemini");
+ const settings = join(dir, "settings.json");
+ const auth = jsonAt(settings, ["security", "auth", "selectedType"]) ?? jsonAt(settings, ["selectedAuthType"]);
+ if (auth !== undefined && auth !== "gemini-api-key" && auth !== "oauth-personal") throw new Error(`Gemini CLI signs in with ${String(auth)}; only an API key or a Google sign-in can go through the engine`);
+ const google = auth === "oauth-personal";
+ const name = google ? "CODE_ASSIST_ENDPOINT" : "GOOGLE_GEMINI_BASE_URL";
+ const envFile = join(dir, ".env");
+ return {
+ current: envAt(envFile, name) ?? env[name]?.trim() ?? null,
+ fallback: google ? "https://cloudcode-pa.googleapis.com" : "https://generativelanguage.googleapis.com",
+ edits: ({ url, mcp }) => [
+ { file: envFile, env: name, value: url },
+ { file: settings, json: ["mcpServers", MCP_NAME], value: { command: mcp.command, args: mcp.args, env: mcp.env } },
+ ],
+ note: `A .env in your project folder that sets ${name} too wins over ~/.gemini/.env.`,
+ };
+ },
connect: ({ url, mcp }) => [
`In ~/.gemini/.env, set GOOGLE_GEMINI_BASE_URL=${url} (signed in with Google instead: CODE_ASSIST_ENDPOINT, with a route made by --base-url https://cloudcode-pa.googleapis.com)`,
- `In ~/.gemini/settings.json, add: "mcpServers": { "context-attachment-manager": { "command": ${JSON.stringify(mcp.command)}, "args": ${JSON.stringify(mcp.args)}, "env": ${JSON.stringify(mcp.env)} } }`,
+ `In ~/.gemini/settings.json, add: "mcpServers": { "${MCP_NAME}": { "command": ${JSON.stringify(mcp.command)}, "args": ${JSON.stringify(mcp.args)}, "env": ${JSON.stringify(mcp.env)} } }`,
"Restart Gemini CLI.",
],
};
diff --git a/plugin/src/adapters/opencode/platform.ts b/plugin/src/adapters/opencode/platform.ts
index f97a179..732ece4 100644
--- a/plugin/src/adapters/opencode/platform.ts
+++ b/plugin/src/adapters/opencode/platform.ts
@@ -1,19 +1,53 @@
// Purpose: v0.11 — OpenCode: the core alone, no panel. Each provider in opencode.json takes its own base URL
-// (`options.baseURL`), so the route is registered for the provider the user picks, with that provider's address; the
-// request format follows the provider (Anthropic Messages, OpenAI Responses or Chat Completions, Gemini). Its requests
-// name no session the engine knows, so sessions are told apart by their first prompt; a plugin of OpenCode's own could
-// add `x-cam-session` in its `model.request` hook. MCP servers go under "mcp" in opencode.json. Not tested live.
-// Input: none. Output: the platform's entry for the engine (core/platform.ts).
+// (`provider.<id>.options.baseURL`), so the route is for one provider: the one named, else the one of the configured
+// `model` ("anthropic/…"); without a baseURL of its own a provider uses its SDK's address (the defaults below). The
+// request format follows the provider. Its requests name no session the engine knows, so sessions are told apart by
+// their first prompt; a plugin of OpenCode's own could add `x-cam-session` in its `model.request` hook. MCP servers go
+// under "mcp"; the global config is in ~/.config/opencode (OPENCODE_CONFIG_DIR moves it); shell commands run with
+// OPENCODE=1. Not tested live.
+// Input: the environment, the config file. Output: the platform's entry (core/platform.ts).
-import type { CorePlatform } from "../../core/platform.ts";
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+import { jsonAt } from "../../core/config-edit.ts";
+import { MCP_NAME, type CorePlatform } from "../../core/platform.ts";
+
+// The AI SDK providers' own addresses.
+const DEFAULTS: Record<string, string> = {
+ anthropic: "https://api.anthropic.com/v1",
+ openai: "https://api.openai.com/v1",
+ google: "https://generativelanguage.googleapis.com/v1beta",
+};
+
+function configFile(home: string, env: NodeJS.ProcessEnv): string {
+ const dir = env.OPENCODE_CONFIG_DIR?.trim() || join(home, ".config", "opencode");
+ const jsonc = join(dir, "opencode.jsonc");
+ return !existsSync(join(dir, "opencode.json")) && existsSync(jsonc) ? jsonc : join(dir, "opencode.json");
+}
export const opencode: CorePlatform = {
name: "opencode",
title: "OpenCode",
upstream: null,
+ detect: (env) => env.OPENCODE === "1",
+ setup: ({ home, env, provider }) => {
+ const file = configFile(home, env);
+ const model = jsonAt(file, ["model"]);
+ const name = provider ?? (typeof model === "string" && model.includes("/") ? model.split("/")[0] : null);
+ if (!name) throw new Error("OpenCode: name the provider whose requests should go through the engine, e.g. --provider anthropic");
+ const set = jsonAt(file, ["provider", name, "options", "baseURL"]);
+ return {
+ current: typeof set === "string" ? set : null,
+ fallback: DEFAULTS[name] ?? null,
+ edits: ({ url, mcp }) => [
+ { file, json: ["provider", name, "options", "baseURL"], value: url },
+ { file, json: ["mcp", MCP_NAME], value: { type: "local", command: [mcp.command, ...mcp.args], environment: mcp.env, enabled: true } },
+ ],
+ };
+ },
connect: ({ url, mcp }) => [
`In opencode.json, set your provider's base URL: "provider": { "<provider id>": { "options": { "baseURL": "${url}" } } }`,
- `Add the MCP server: "mcp": { "context-attachment-manager": { "type": "local", "command": ${JSON.stringify([mcp.command, ...mcp.args])}, "environment": ${JSON.stringify(mcp.env)} } }`,
+ `Add the MCP server: "mcp": { "${MCP_NAME}": { "type": "local", "command": ${JSON.stringify([mcp.command, ...mcp.args])}, "environment": ${JSON.stringify(mcp.env)} } }`,
"Restart OpenCode.",
],
};
diff --git a/plugin/src/adapters/pi/platform.ts b/plugin/src/adapters/pi/platform.ts
index 048da97..9e79a3c 100644
--- a/plugin/src/adapters/pi/platform.ts
+++ b/plugin/src/adapters/pi/platform.ts
@@ -1,19 +1,47 @@
// Purpose: v0.11 — pi (earendil-works/pi): the core alone, no panel. Each provider in ~/.pi/agent/models.json takes
-// its own `baseUrl`, so the route is registered for the provider the user picks, with that provider's address; the
-// request format follows the provider. Our pi extension (extension.ts) names each request's session in
-// `x-cam-session` and registers the plugin's MCP service, so pi needs no other setting. Not tested live.
-// Input: none. Output: the platform's entry for the engine (core/platform.ts).
+// its own `baseUrl`, so the route is for one provider: the one named, else the one pi uses now (PI_PROVIDER, which pi
+// sets for shell commands with PI_SESSION_ID); without a baseUrl of its own a provider uses pi's built-in address (the
+// defaults below, from pi's provider code). The request format follows the provider. Our pi extension (extension.ts),
+// listed under "extensions" in ~/.pi/agent/settings.json, names each request's session in `x-cam-session` and registers
+// the plugin's MCP service. Not tested live.
+// Input: the environment, the settings files. Output: the platform's entry (core/platform.ts).
+import { join } from "node:path";
import { fileURLToPath } from "node:url";
+import { jsonAt } from "../../core/config-edit.ts";
import type { CorePlatform } from "../../core/platform.ts";
+const DEFAULTS: Record<string, string> = {
+ anthropic: "https://api.anthropic.com",
+ openai: "https://api.openai.com/v1",
+ google: "https://generativelanguage.googleapis.com/v1beta",
+ deepseek: "https://api.deepseek.com",
+};
+const extension = () => fileURLToPath(new URL("./extension.ts", import.meta.url));
+
export const pi: CorePlatform = {
name: "pi",
title: "pi",
upstream: null,
+ detect: (env) => !!(env.PI_SESSION_ID || env.PI_PROVIDER),
+ setup: ({ home, env, provider }) => {
+ const dir = join(home, ".pi", "agent");
+ const name = provider ?? env.PI_PROVIDER?.trim() ?? null;
+ if (!name) throw new Error("pi: name the provider whose requests should go through the engine, e.g. --provider anthropic");
+ const models = join(dir, "models.json");
+ const set = jsonAt(models, ["providers", name, "baseUrl"]);
+ return {
+ current: typeof set === "string" ? set : null,
+ fallback: DEFAULTS[name] ?? null,
+ edits: ({ url }) => [
+ { file: models, json: ["providers", name, "baseUrl"], value: url },
+ { file: join(dir, "settings.json"), add: ["extensions"], value: extension() },
+ ],
+ };
+ },
connect: ({ url }) => [
`In ~/.pi/agent/models.json, set your provider's "baseUrl": "${url}"`,
- `Load the extension: pi -e ${JSON.stringify(fileURLToPath(new URL("./extension.ts", import.meta.url)))} (or copy it to ~/.pi/agent/extensions/)`,
+ `In ~/.pi/agent/settings.json, add to "extensions": ${JSON.stringify(extension())}`,
"Restart pi.",
],
};
diff --git a/plugin/src/adapters/workbuddy/platform.ts b/plugin/src/adapters/workbuddy/platform.ts
index 22f0e2b..59af149 100644
--- a/plugin/src/adapters/workbuddy/platform.ts
+++ b/plugin/src/adapters/workbuddy/platform.ts
@@ -2,10 +2,16 @@
// panel. Its agent sends OpenAI Chat Completions requests to CODEBUDDY_BASE_URL + /chat/completions, which by default
// is WorkBuddy's own service under /v2 (a capture on 2026-11-02: without /v2 the service answers 405). Each request
// names its conversation in `x-conversation-id`; side requests (prompt enhancement and the like) say
-// `x-agent-type: auxiliary`. `env` in ~/.workbuddy/settings.json reaches the agent's environment. Not tested live.
-// Input: request headers. Output: the platform's entry for the engine (core/platform.ts).
+// `x-agent-type: auxiliary`. `env` in ~/.workbuddy/settings.json reaches the agent's environment (WORKBUDDY_CONFIG_DIR
+// moves the folder); user MCP servers go in ~/.workbuddy/.mcp.json, as in CodeBuddy's docs for ~/.codebuddy. Its shell
+// commands run with CODEBUDDY=1, as do the CodeBuddy CLI's; WorkBuddy's own paths tell the two apart. Not tested live.
+// Input: request headers, the environment, the settings files. Output: the platform's entry (core/platform.ts).
-import { headerOf, type CorePlatform } from "../../core/platform.ts";
+import { join } from "node:path";
+import { jsonAt } from "../../core/config-edit.ts";
+import { headerOf, MCP_NAME, type CorePlatform } from "../../core/platform.ts";
+
+const configDir = (home: string, env: NodeJS.ProcessEnv) => env.WORKBUDDY_CONFIG_DIR?.trim() || join(home, ".workbuddy");
export const workbuddy: CorePlatform = {
name: "workbuddy",
@@ -13,9 +19,24 @@ export const workbuddy: CorePlatform = {
upstream: "https://www.workbuddy.cn/v2",
sessionOf: (headers) => headerOf(headers, "x-conversation-id"),
sideRequest: (headers) => headerOf(headers, "x-agent-type") === "auxiliary",
+ // Any WORKBUDDY_ variable, or a CodeBuddy path inside WorkBuddy's folders.
+ detect: (env) => env.CODEBUDDY === "1" && (Object.keys(env).some((name) => name.startsWith("WORKBUDDY_")) || /workbuddy/i.test([env.CODEBUDDY_CONFIG_DIR, env.CODEBUDDY_NODE_BIN, env.ACC_PRODUCT_CONFIG_PATH].join(" "))),
+ setup: ({ home, env }) => {
+ const dir = configDir(home, env);
+ const settings = join(dir, "settings.json");
+ const set = jsonAt(settings, ["env", "CODEBUDDY_BASE_URL"]);
+ return {
+ current: typeof set === "string" ? set : env.CODEBUDDY_BASE_URL?.trim() || null,
+ fallback: "https://www.workbuddy.cn/v2",
+ edits: ({ url, mcp }) => [
+ { file: settings, json: ["env", "CODEBUDDY_BASE_URL"], value: url },
+ { file: join(dir, ".mcp.json"), json: ["mcpServers", MCP_NAME], value: { type: "stdio", command: mcp.command, args: mcp.args, env: mcp.env } },
+ ],
+ };
+ },
connect: ({ url, mcp }) => [
`In ~/.workbuddy/settings.json, add to "env": "CODEBUDDY_BASE_URL": "${url}"`,
- `Add an MCP server in WorkBuddy (stdio): command ${JSON.stringify(mcp.command)}, args ${JSON.stringify(mcp.args)}, env ${JSON.stringify(mcp.env)}`,
+ `In ~/.workbuddy/.mcp.json, add to "mcpServers": "${MCP_NAME}": ${JSON.stringify({ type: "stdio", command: mcp.command, args: mcp.args, env: mcp.env })}`,
"Restart WorkBuddy.",
],
};
diff --git a/plugin/src/cam.ts b/plugin/src/cam.ts
index 5afcadd..c8d5ef5 100644
--- a/plugin/src/cam.ts
+++ b/plugin/src/cam.ts
@@ -14,9 +14,9 @@
// printed: it may hold credentials), the plugin cache (through Codex's command line), the selection files, and a
// summary on stdout. Rollouts are only read.
-import { spawn } from "node:child_process";
+import { execFileSync, spawn } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync } from "node:fs";
-import { tmpdir } from "node:os";
+import { homedir, tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { findCodexCli, runCodex } from "./adapters/codex/codexcli.ts";
import { codexHome, MCP_BEGIN, noProxyStatus, proxyStatus } from "./adapters/codex/codexconfig.ts";
@@ -32,8 +32,9 @@ import type { PanelState } from "./panel/panel-state.ts";
import { dataDir, selectionDirOf } from "./core/paths.ts";
import { preservingPluginCache } from "./adapters/codex/plugin-cache.ts";
import { backupConfig, connectDirectly, planEngine, readConfig, readEnv, useEngine } from "./adapters/codex/setup.ts";
-import { registerRoute, routeBaseUrl, validateBaseUrl } from "./core/routes.ts";
-import { CORE_PLATFORMS, corePlatformOf } from "./platforms.ts";
+import { readRoute, registerRoute, routeBaseUrl, validateBaseUrl } from "./core/routes.ts";
+import { applyEdits, undoEdits } from "./core/config-edit.ts";
+import { CORE_PLATFORMS, corePlatformOf, detectPlatform } from "./platforms.ts";
type Json = Record<string, any>;
const lang = systemLang();
@@ -127,6 +128,16 @@ export function selfTest(dir: string, timeoutMs = 20_000): Promise<{ ok: boolean
});
}
+// v0.11: the Node a platform's MCP service is started with: the one on PATH when it is 24 or later (it stays where it is),
+// else this one (the cam script may run Codex's own Node, whose folder changes with each Codex update).
+function stableNode(): string {
+ try {
+ const found = execFileSync("node", ["-p", "Number(process.versions.node.split('.')[0]) >= 24 ? process.execPath : ''"], { encoding: "utf8", windowsHide: true, timeout: 5000 }).trim();
+ if (found) return found;
+ } catch { /* no node on PATH */ }
+ return process.execPath;
+}
+
// Selections made before P5 lived in the repository's local/ folder; they move along once, never overwriting.
function migrateSelections(): number {
const legacy = join(repository, "local", "selection");
@@ -219,22 +230,51 @@ async function main(): Promise<void> {
}, null, 2));
return;
}
+ // v0.11 (user 2026-11-02: an AI reading this repository installs for the platform it runs in, and never the wrong
+ // one): which platform this shell runs in (platforms.ts), and what to run next.
+ if (command === "detect") {
+ const found = detectPlatform();
+ const next = !found.platform ? (found.matches.includes("codebuddy") ? `CodeBuddy's agent, without WorkBuddy's marks. In WorkBuddy: node "${join(import.meta.dirname, "cam.ts")}" connect workbuddy --apply. The CodeBuddy CLI on its own has no adapter yet; ask the user which it is.` : "Not sure which agent this is: ask the user, then follow that agent's section of INSTALL.md.")
+ : found.platform === "codex" ? "Follow the Codex section of INSTALL.md."
+ : found.platform === "claude" ? "Follow the Claude Desktop section of INSTALL.md."
+ : found.platform === "dsh" ? `dsh plugin --profile ${process.env.DSH_PROFILE || "<your profile>"} add "${join(import.meta.dirname, "adapters", "dsh")}"`
+ : `node "${join(import.meta.dirname, "cam.ts")}" connect ${found.platform} --apply`;
+ console.log(JSON.stringify({ command, platform: found.platform, matches: found.matches, next }, null, 2));
+ return;
+ }
// v0.11: a platform using the core alone (platforms.ts, ADAPTERS.md): registers the route from the engine to where its
- // requests go, and says what to set in the platform. Changes no file of the platform's.
- if (command === "connect") {
+ // requests go now, and prints what to set in the platform; with --apply, sets it (backed up, recorded for
+ // `disconnect`). --base-url names that address; --provider the provider, for a platform with one per provider.
+ if (command === "connect" || command === "disconnect") {
const platform = corePlatformOf(threadId);
- if (!platform) throw new Error(`usage: cam.ts connect <${CORE_PLATFORMS.map((one) => one.name).join("|")}> [--base-url URL]`);
- const baseUrl = process.argv.includes("--base-url") ? process.argv[process.argv.indexOf("--base-url") + 1] : platform.upstream;
+ if (!platform) throw new Error(`usage: cam.ts ${command} <${CORE_PLATFORMS.map((one) => one.name).join("|")}> [--apply] [--provider NAME] [--base-url URL]`);
+ if (command === "disconnect") {
+ const undone = undoEdits(platform.name, dataDir());
+ console.log([`${platform.title}: settings put back in ${undone.files.length ? undone.files.join(", ") : "no file (nothing was applied)"}.`, ...undone.kept.map((setting) => `Left as you changed it: ${setting}`), `Restart ${platform.title}.`].join("\n"));
+ return;
+ }
+ const flag = (name: string) => (process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] ?? null : null);
+ const apply = process.argv.includes("--apply");
+ const plan = apply || platform.setup ? platform.setup?.({ home: homedir(), env: process.env, provider: flag("--provider") }) ?? null : null;
+ // Connected before: the address stays where that route goes.
+ const ours = plan?.current ? /^http:\/\/(?:127\.0\.0\.1|localhost):\d+\/__cam\/routes\/([a-f0-9]{32})/.exec(plan.current) : null;
+ const baseUrl = flag("--base-url") ?? (ours ? readRoute(ours[1])?.baseUrl ?? null : plan?.current) ?? plan?.fallback ?? platform.upstream;
if (!baseUrl) throw new Error(`${platform.title}: give the address its requests go to now, with --base-url (e.g. https://api.anthropic.com/v1)`);
try { validateBaseUrl(baseUrl, port); } catch (error) { throw localized(error); }
const route = registerRoute({ platform: platform.name, baseUrl });
const url = routeBaseUrl(port, route.id).replace("localhost", "127.0.0.1");
- const mcp = { command: process.execPath, args: [join(import.meta.dirname, "plugin-server.ts")], env: { CAM_HOST: platform.name } };
+ const mcp = { command: stableNode(), args: [join(import.meta.dirname, "plugin-server.ts")], env: { CAM_HOST: platform.name } };
+ if (apply) {
+ if (!plan) throw new Error(`${platform.title}: its settings cannot be written yet; set them by hand: cam connect ${platform.name}`);
+ const files = applyEdits(platform.name, plan.edits({ url, mcp }), dataDir());
+ console.log([`${platform.title}: requests go through the engine to ${baseUrl}.`, `Changed (backed up first): ${files.join(", ")}`, ...(plan.note ? [plan.note] : []), `Restart ${platform.title}. To undo: cam disconnect ${platform.name}`].join("\n"));
+ return;
+ }
// Plain lines, to copy from: inside JSON the paths' backslashes would be escaped twice.
console.log([`${platform.title}: ${url} -> ${baseUrl}`, ...platform.connect({ url, mcp }).map((step, at) => `${at + 1}. ${step}`)].join("\n"));
return;
}
- if (!command || !threadId) throw new Error("usage: cam.ts install [--port N] | setup [--port N] | uninstall | status | connect <platform> [--base-url URL] | list|uncheck|check|check-all <thread id> [IMG-…]");
+ if (!command || !threadId) throw new Error("usage: cam.ts install [--port N] | setup [--port N] | uninstall | status | detect | connect|disconnect <platform> [--apply] [--provider NAME] [--base-url URL] | list|uncheck|check|check-all <thread id> [IMG-…]");
const options = { sessionsDir: join(codexHome(), "sessions") };
if (command === "list") console.log(table(loadPanelState(threadId, options)));
else if (command === "uncheck") console.log(table(applySelection(threadId, { uncheck: ids }, options)));
diff --git a/plugin/src/core/config-edit.ts b/plugin/src/core/config-edit.ts
new file mode 100644
index 0000000..06cfac4
--- /dev/null
+++ b/plugin/src/core/config-edit.ts
@@ -0,0 +1,184 @@
+// Purpose: v0.11 — `cam connect --apply` writes a platform's own settings (docs/v0.11/plan.md 3.8): a value at a path
+// in a JSON file, an item in a JSON list, or a NAME=value line in an env file. A file that does not parse as plain JSON
+// (comments, say) is left alone and the command says so. Each file is backed up before the first change; what was
+// written, and what was there before, is recorded, and `cam disconnect` puts back only what still holds the value
+// written, so changes the user made since stay.
+// Input: the edits a platform's entry asks for (core/platform.ts). Output: the files, backups under
+// <data dir>/config-backup/<platform>/, and <data dir>/platforms/<platform>/connected.json.
+
+import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
+import { basename, dirname, join } from "node:path";
+import { platformDirOf } from "./request-index.ts";
+
+type Json = Record<string, any>;
+// json: the value at that path. add: one item in the list at that path. env: a NAME=value line.
+export type ConfigEdit = { file: string; json: string[]; value: unknown } | { file: string; add: string[]; value: unknown } | { file: string; env: string; value: string };
+type Recorded = ConfigEdit & { before?: unknown; had: boolean };
+
+const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
+
+export function readJson(file: string): Json {
+ if (!existsSync(file)) return {};
+ const text = readFileSync(file, "utf8").replace(/^/, "");
+ if (!text.trim()) return {};
+ try {
+ const value = JSON.parse(text);
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
+ } catch { /* below */ }
+ throw new Error(`${file} is not plain JSON (comments?); change it by hand with the printed steps`);
+}
+
+export function jsonAt(file: string, path: string[]): unknown {
+ try {
+ let node: any = readJson(file);
+ for (const key of path) node = node?.[key];
+ return node;
+ } catch {
+ return undefined;
+ }
+}
+
+const ENV_LINE = (name: string) => new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=\\s*(.*?)\\s*$`);
+const unquote = (value: string) => value.replace(/^(["'])(.*)\1$/, "$2");
+
+export function envAt(file: string, name: string): string | undefined {
+ if (!existsSync(file)) return undefined;
+ for (const line of readFileSync(file, "utf8").split(/\r?\n/)) {
+ const match = ENV_LINE(name).exec(line);
+ if (match) return unquote(match[1]);
+ }
+ return undefined;
+}
+
+const writeWhole = (file: string, text: string) => {
+ mkdirSync(dirname(file), { recursive: true });
+ writeFileSync(`${file}.cam-tmp`, text);
+ renameSync(`${file}.cam-tmp`, file);
+};
+
+const parentOf = (root: Json, path: string[], create: boolean): Json | null => {
+ let node = root;
+ for (const key of path.slice(0, -1)) {
+ if (node[key] === undefined && create) node[key] = {};
+ if (!node[key] || typeof node[key] !== "object" || Array.isArray(node[key])) return null;
+ node = node[key];
+ }
+ return node;
+};
+
+// One file's edits, in order; returns what each found before.
+function applyTo(file: string, edits: ConfigEdit[]): Recorded[] {
+ const recorded: Recorded[] = [];
+ if (edits.every((edit) => "env" in edit)) {
+ const eol = existsSync(file) && readFileSync(file, "utf8").includes("\r\n") ? "\r\n" : "\n";
+ const lines = existsSync(file) ? readFileSync(file, "utf8").split(/\r?\n/) : [];
+ for (const edit of edits as Array<Extract<ConfigEdit, { env: string }>>) {
+ const at = lines.findIndex((line) => ENV_LINE(edit.env).test(line));
+ const before = at < 0 ? undefined : unquote(ENV_LINE(edit.env).exec(lines[at])![1]);
+ recorded.push({ ...edit, had: at >= 0, ...(at >= 0 ? { before } : {}) });
+ if (at >= 0) lines[at] = `${edit.env}=${edit.value}`;
+ else {
+ if (lines.length && lines[lines.length - 1] === "") lines.pop();
+ lines.push(`${edit.env}=${edit.value}`, "");
+ }
+ }
+ writeWhole(file, lines.join(eol));
+ return recorded;
+ }
+ const root = readJson(file);
+ for (const edit of edits) {
+ if ("env" in edit) throw new Error(`${file}: env lines and JSON in one file`);
+ const path = "json" in edit ? edit.json : edit.add;
+ const parent = parentOf(root, path, true);
+ if (!parent) throw new Error(`${file}: ${path.join(".")} is not where a setting can go`);
+ const key = path[path.length - 1];
+ if ("json" in edit) {
+ recorded.push({ ...edit, had: key in parent, ...(key in parent ? { before: parent[key] } : {}) });
+ parent[key] = edit.value;
+ } else {
+ const list = parent[key] === undefined ? (parent[key] = []) : parent[key];
+ if (!Array.isArray(list)) throw new Error(`${file}: ${path.join(".")} is not a list`);
+ const had = list.some((item: unknown) => same(item, edit.value));
+ recorded.push({ ...edit, had });
+ if (!had) list.push(edit.value);
+ }
+ }
+ writeWhole(file, `${JSON.stringify(root, null, 2)}\n`);
+ return recorded;
+}
+
+const recordFile = (root: string, platform: string) => join(platformDirOf(root, platform), "connected.json");
+
+export function applyEdits(platform: string, edits: ConfigEdit[], root: string, now = new Date()): string[] {
+ const files = [...new Set(edits.map((edit) => edit.file))];
+ // Everything is read and checked before the first file is written.
+ for (const file of files) if (!edits.some((edit) => edit.file === file && "env" in edit)) readJson(file);
+ const backups = join(root, "config-backup", platform);
+ const stamp = now.toISOString().replaceAll(":", "-");
+ const recorded: Recorded[] = [];
+ for (const file of files) {
+ if (existsSync(file)) {
+ mkdirSync(backups, { recursive: true });
+ copyFileSync(file, join(backups, `${basename(file)}.${stamp}`));
+ }
+ recorded.push(...applyTo(file, edits.filter((edit) => edit.file === file)));
+ }
+ // A second connect keeps what was there before the first one.
+ const earlier = readRecord(platform, root);
+ const kept = recorded.map((entry) => {
+ const first = earlier.find((old) => old.file === entry.file && same(pathOf(old), pathOf(entry)) && kind(old) === kind(entry));
+ return first ? { ...entry, had: first.had, ...(first.had ? { before: first.before } : { before: undefined }) } : entry;
+ });
+ writeWhole(recordFile(root, platform), `${JSON.stringify({ at: now.toISOString(), edits: kept }, null, 2)}\n`);
+ return files;
+}
+
+const kind = (edit: ConfigEdit) => ("json" in edit ? "json" : "add" in edit ? "add" : "env");
+const pathOf = (edit: ConfigEdit) => ("json" in edit ? edit.json : "add" in edit ? edit.add : [edit.env]);
+
+function readRecord(platform: string, root: string): Recorded[] {
+ try { return JSON.parse(readFileSync(recordFile(root, platform), "utf8")).edits ?? []; } catch { return []; }
+}
+
+// Puts back what connect changed, where it still holds the value connect wrote. Returns the settings left as the user
+// changed them since.
+export function undoEdits(platform: string, root: string): { files: string[]; kept: string[] } {
+ const recorded = readRecord(platform, root);
+ const kept: string[] = [];
+ const files = [...new Set(recorded.map((edit) => edit.file))];
+ for (const file of files) {
+ if (!existsSync(file)) continue;
+ const mine = recorded.filter((edit) => edit.file === file);
+ if (mine.every((edit) => "env" in edit)) {
+ const eol = readFileSync(file, "utf8").includes("\r\n") ? "\r\n" : "\n";
+ let lines = readFileSync(file, "utf8").split(/\r?\n/);
+ for (const edit of mine as Array<Recorded & { env: string; value: string }>) {
+ const at = lines.findIndex((line) => ENV_LINE(edit.env).test(line));
+ if (at < 0 || unquote(ENV_LINE(edit.env).exec(lines[at])![1]) !== edit.value) { kept.push(`${file}: ${edit.env}`); continue; }
+ if (edit.had) lines[at] = `${edit.env}=${edit.before}`;
+ else lines = lines.filter((_, index) => index !== at);
+ }
+ writeWhole(file, lines.join(eol));
+ continue;
+ }
+ let doc: Json;
+ try { doc = readJson(file); } catch { kept.push(file); continue; }
+ for (const edit of mine) {
+ if ("env" in edit) continue;
+ const path = "json" in edit ? edit.json : edit.add;
+ const parent = parentOf(doc, path, false);
+ const key = path[path.length - 1];
+ if (!parent) { kept.push(`${file}: ${path.join(".")}`); continue; }
+ if ("json" in edit) {
+ if (!same(parent[key], edit.value)) { kept.push(`${file}: ${path.join(".")}`); continue; }
+ if (edit.had) parent[key] = edit.before;
+ else delete parent[key];
+ } else if (Array.isArray(parent[key]) && !edit.had) {
+ parent[key] = parent[key].filter((item: unknown) => !same(item, edit.value));
+ }
+ }
+ writeWhole(file, `${JSON.stringify(doc, null, 2)}\n`);
+ }
+ if (recorded.length) writeWhole(recordFile(root, platform), `${JSON.stringify({ at: new Date().toISOString(), edits: [] }, null, 2)}\n`);
+ return { files, kept };
+}
diff --git a/plugin/src/core/platform.ts b/plugin/src/core/platform.ts
index e12a821..ef492dd 100644
--- a/plugin/src/core/platform.ts
+++ b/plugin/src/core/platform.ts
@@ -5,6 +5,7 @@
// Input: none (types only). Output: the contract each adapters/<name>/platform.ts fills in.
import type { IncomingHttpHeaders } from "node:http";
+import type { ConfigEdit } from "./config-edit.ts";
export type ConnectInfo = {
// The local address the platform is pointed at, and the command that starts the plugin's MCP service for it.
@@ -12,6 +13,16 @@ export type ConnectInfo = {
mcp: { command: string; args: string[]; env: Record<string, string> };
};
+// v0.11: what `cam connect --apply` needs, read from the platform's own settings now. current: the address its
+// requests go to as set now (a route of ours, when connected before), fallback: where they go when nothing is set.
+// edits: what to write (core/config-edit.ts). provider: for a platform with one address per model provider, the one
+// the user named (or the platform's shell said).
+export type SetupContext = { home: string; env: NodeJS.ProcessEnv; provider: string | null };
+export type SetupPlan = { current: string | null; fallback: string | null; edits: (info: ConnectInfo) => ConfigEdit[]; note?: string };
+
+// The name of the plugin's MCP server in a platform's settings.
+export const MCP_NAME = "context-attachment-manager";
+
export type CorePlatform = {
// As in routes and data folders: lowercase letters, digits, hyphens.
name: string;
@@ -25,6 +36,11 @@ export type CorePlatform = {
sideRequest?: (headers: IncomingHttpHeaders) => boolean;
// What the user does to connect it, one step per line (English, as in ADAPTERS.md).
connect: (info: ConnectInfo) => string[];
+ // v0.11: whether a shell command runs inside this platform, from the variables the platform sets for it (`cam
+ // detect`, so an AI installing the plugin picks the right platform).
+ detect?: (env: NodeJS.ProcessEnv) => boolean;
+ // v0.11: the settings `cam connect --apply` writes; without it the steps are only printed.
+ setup?: (context: SetupContext) => SetupPlan;
};
export const headerOf = (headers: IncomingHttpHeaders, name: string): string | null => {
diff --git a/plugin/src/platforms.ts b/plugin/src/platforms.ts
index dd9e217..2acb4d2 100644
--- a/plugin/src/platforms.ts
+++ b/plugin/src/platforms.ts
@@ -1,9 +1,9 @@
// Purpose: v0.11 — the platforms the plugin connects (docs/v0.11/plan.md 3.8; ADAPTERS.md). Codex and Claude Code have
// adapters of their own, with the panel (adapters/codex, adapters/claude). The others use the core alone: their entry
// (core/platform.ts) is all the engine, the plugin's MCP service and `cam connect` need. A new platform adds its
-// adapters/<name>/platform.ts and one line here. DeepSeek Harness is a dsh plugin of its own (adapters/dsh/plugin.ts),
-// no route, so it is not listed.
-// Input: none. Output: the registry.
+// adapters/<name>/platform.ts and one line here. DeepSeek Harness is a dsh plugin of its own (adapters/dsh), no route,
+// so it is not in CORE_PLATFORMS; `cam detect` still names it.
+// Input: none. Output: the registry, and which platform a shell command runs in.
import { geminiCli } from "./adapters/gemini-cli/platform.ts";
import { opencode } from "./adapters/opencode/platform.ts";
@@ -16,3 +16,20 @@ export const PANEL_PLATFORMS = ["codex", "claude"] as const;
export const corePlatformOf = (name: string | null | undefined): CorePlatform | null => CORE_PLATFORMS.find((platform) => platform.name === name) ?? null;
export const isPlatform = (name: unknown): name is string => typeof name === "string" && ((PANEL_PLATFORMS as readonly string[]).includes(name) || !!corePlatformOf(name));
+
+// v0.11: the variables each platform sets for the shell commands its agent runs (checked in each one's code,
+// 2026-11-02): Codex CODEX_THREAD_ID, Claude Code CLAUDECODE=1, DeepSeek Harness DSH_SHELL=1, and the core platforms'
+// own (their `detect`). An agent started from another's shell carries both; then the user is asked.
+const SIGNALS: Array<{ platform: string; test: (env: NodeJS.ProcessEnv) => boolean }> = [
+ ...CORE_PLATFORMS.flatMap((platform) => (platform.detect ? [{ platform: platform.name, test: platform.detect }] : [])),
+ { platform: "dsh", test: (env) => env.DSH_SHELL === "1" },
+ { platform: "claude", test: (env) => env.CLAUDECODE === "1" },
+ { platform: "codex", test: (env) => !!env.CODEX_THREAD_ID },
+];
+
+// The platform when exactly one matches; `codebuddy` names CodeBuddy's agent outside WorkBuddy, which has no adapter.
+export function detectPlatform(env: NodeJS.ProcessEnv = process.env): { platform: string | null; matches: string[] } {
+ const matches = SIGNALS.filter((signal) => signal.test(env)).map((signal) => signal.platform);
+ if (env.CODEBUDDY === "1" && !matches.includes("workbuddy")) matches.push("codebuddy");
+ return { platform: matches.length === 1 && matches[0] !== "codebuddy" ? matches[0] : null, matches };
+}
diff --git a/spike/src/connect.test.ts b/spike/src/connect.test.ts
new file mode 100644
index 0000000..613bc4e
--- /dev/null
+++ b/spike/src/connect.test.ts
@@ -0,0 +1,100 @@
+// Purpose: v0.11 — installing on a platform that uses the core alone (docs/v0.11/plan.md 3.8): which platform a shell
+// runs in, what `cam connect --apply` writes to the platform's settings and what `cam disconnect` puts back, and what
+// each platform's entry reads from its settings.
+// Input: temporary folders and environments. Output: test results.
+import assert from "node:assert/strict";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { geminiCli } from "../../plugin/src/adapters/gemini-cli/platform.ts";
+import { opencode } from "../../plugin/src/adapters/opencode/platform.ts";
+import { pi } from "../../plugin/src/adapters/pi/platform.ts";
+import { workbuddy } from "../../plugin/src/adapters/workbuddy/platform.ts";
+import { applyEdits, undoEdits } from "../../plugin/src/core/config-edit.ts";
+import { detectPlatform } from "../../plugin/src/platforms.ts";
+
+const temp = () => mkdtempSync(join(tmpdir(), "cam-connect-"));
+const json = (file: string) => JSON.parse(readFileSync(file, "utf8"));
+const info = { url: "http://127.0.0.1:17892/__cam/routes/" + "a".repeat(32), mcp: { command: "node", args: ["/x/plugin-server.ts"], env: { CAM_HOST: "test" } } };
+
+test("which platform a shell command runs in, from the variables each one sets", () => {
+ assert.deepEqual(detectPlatform({ GEMINI_CLI: "1" }), { platform: "gemini-cli", matches: ["gemini-cli"] });
+ assert.equal(detectPlatform({ OPENCODE: "1" }).platform, "opencode");
+ assert.equal(detectPlatform({ PI_SESSION_ID: "s", PI_PROVIDER: "anthropic" }).platform, "pi");
+ assert.equal(detectPlatform({ DSH_SHELL: "1" }).platform, "dsh");
+ assert.equal(detectPlatform({ CLAUDECODE: "1" }).platform, "claude");
+ assert.equal(detectPlatform({ CODEX_THREAD_ID: "t" }).platform, "codex");
+ assert.equal(detectPlatform({ CODEBUDDY: "1", WORKBUDDY_EXTRA_PATHS: "x" }).platform, "workbuddy");
+ assert.equal(detectPlatform({ CODEBUDDY: "1", CODEBUDDY_NODE_BIN: "E:\\Tools\\WorkBuddy\\WorkBuddy.exe" }).platform, "workbuddy");
+ assert.deepEqual(detectPlatform({ CODEBUDDY: "1" }), { platform: null, matches: ["codebuddy"] }, "CodeBuddy without WorkBuddy's marks: ask");
+ assert.deepEqual(detectPlatform({}), { platform: null, matches: [] });
+ assert.deepEqual(detectPlatform({ CLAUDECODE: "1", CODEX_THREAD_ID: "t" }).platform, null, "one agent started from another's shell: ask");
+});
+
+test("connect writes JSON values, list items and env lines with a backup; disconnect puts back what was there", () => {
+ const dir = temp();
+ const data = temp();
+ const settings = join(dir, "settings.json");
+ const env = join(dir, ".env");
+ writeFileSync(settings, JSON.stringify({ keep: true, env: { BASE: "https://relay.example" }, extensions: ["mine.ts"] }));
+ writeFileSync(env, "KEY=secret\r\nBASE=https://old.example\r\n");
+ const edits = [
+ { file: settings, json: ["env", "BASE"], value: info.url },
+ { file: settings, json: ["mcpServers", "cam"], value: { command: "node" } },
+ { file: settings, add: ["extensions"], value: "/x/extension.ts" },
+ { file: env, env: "BASE", value: info.url },
+ { file: env, env: "NEW", value: "1" },
+ ];
+ applyEdits("workbuddy", edits, data);
+ assert.deepEqual(json(settings), { keep: true, env: { BASE: info.url }, extensions: ["mine.ts", "/x/extension.ts"], mcpServers: { cam: { command: "node" } } });
+ assert.equal(readFileSync(env, "utf8"), `KEY=secret\r\nBASE=${info.url}\r\nNEW=1\r\n`, "line endings kept, the key untouched");
+ assert.equal(readdirSync(join(data, "config-backup", "workbuddy")).length, 2);
+ applyEdits("workbuddy", edits, data); // a second connect remembers what was there before the first
+ undoEdits("workbuddy", data);
+ assert.deepEqual(json(settings), { keep: true, env: { BASE: "https://relay.example" }, extensions: ["mine.ts"], mcpServers: {} });
+ assert.equal(readFileSync(env, "utf8"), "KEY=secret\r\nBASE=https://old.example\r\n");
+});
+
+test("disconnect leaves a setting the user changed since; connect refuses a file that is not plain JSON and writes nothing", () => {
+ const dir = temp();
+ const data = temp();
+ const settings = join(dir, "settings.json");
+ applyEdits("pi", [{ file: settings, json: ["providers", "anthropic", "baseUrl"], value: info.url }], data);
+ writeFileSync(settings, JSON.stringify({ providers: { anthropic: { baseUrl: "https://mine.example" } } }));
+ const undone = undoEdits("pi", data);
+ assert.equal(undone.kept.length, 1);
+ assert.equal(json(settings).providers.anthropic.baseUrl, "https://mine.example");
+ const commented = join(dir, "opencode.jsonc");
+ writeFileSync(commented, '{\n // mine\n "model": "anthropic/x"\n}\n');
+ const other = join(dir, "other.json");
+ assert.throws(() => applyEdits("opencode", [{ file: other, json: ["a"], value: 1 }, { file: commented, json: ["b"], value: 2 }], data), /not plain JSON/);
+ assert.equal(existsSync(other), false, "checked before anything is written");
+});
+
+test("each platform reads where its requests go now and what to write", () => {
+ const home = temp();
+ mkdirSync(join(home, ".workbuddy"));
+ writeFileSync(join(home, ".workbuddy", "settings.json"), JSON.stringify({ env: { CODEBUDDY_BASE_URL: "https://relay.example/v2" } }));
+ const wb = workbuddy.setup!({ home, env: {}, provider: null });
+ assert.equal(wb.current, "https://relay.example/v2", "a relay set before is kept as the destination");
+ assert.deepEqual(wb.edits(info).map((edit) => edit.file.split(/[\\/]/).slice(-2).join("/")), [".workbuddy/settings.json", ".workbuddy/.mcp.json"]);
+
+ mkdirSync(join(home, ".gemini"));
+ writeFileSync(join(home, ".gemini", "settings.json"), JSON.stringify({ security: { auth: { selectedType: "gemini-api-key" } } }));
+ const gemini = geminiCli.setup!({ home, env: {}, provider: null });
+ assert.equal(gemini.fallback, "https://generativelanguage.googleapis.com");
+ assert.deepEqual(gemini.edits(info)[0], { file: join(home, ".gemini", ".env"), env: "GOOGLE_GEMINI_BASE_URL", value: info.url });
+ writeFileSync(join(home, ".gemini", "settings.json"), JSON.stringify({ security: { auth: { selectedType: "vertex-ai" } } }));
+ assert.throws(() => geminiCli.setup!({ home, env: {}, provider: null }), /vertex-ai/);
+
+ mkdirSync(join(home, ".config", "opencode"), { recursive: true });
+ writeFileSync(join(home, ".config", "opencode", "opencode.json"), JSON.stringify({ model: "openai/gpt-x" }));
+ const oc = opencode.setup!({ home, env: {}, provider: null });
+ assert.equal(oc.fallback, "https://api.openai.com/v1", "the provider of the configured model");
+ assert.deepEqual((oc.edits(info)[0] as { json: string[] }).json, ["provider", "openai", "options", "baseURL"]);
+
+ assert.throws(() => pi.setup!({ home, env: {}, provider: null }), /name the provider/);
+ const p = pi.setup!({ home, env: { PI_PROVIDER: "anthropic" }, provider: null });
+ assert.equal(p.fallback, "https://api.anthropic.com", "the provider pi uses now, from its shell");
+});