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.

refactor(layout): sort plugin/src into core, panel and adapters

chipfighterf3b1f132bafb
diff --git a/AGENTS.md b/AGENTS.md
index 3ae7a4b..cead2ab 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -30,7 +30,7 @@ Context Attachment Manager(上下文素材管理器,2026-10-11 前叫 Codex
- 先在 Windows 上开发和测试。技术栈用 TypeScript/Node。
- 界面开发:Claude 自己截图检查效果;做到界面的关键节点时,截图给用户看,停下来等反馈再继续(用户 2026-09-24 确认)。
- 测试时调用模型一律用 `gpt-6-sol`,推理强度 `low`,包括脚本自测和桌面版测试,为了省 token(用户 2026-09-24 要求)。
-- 界面和提示文字分简体中文、英文两份:面板的在 `plugin/src/panel.html` 的文字表里,插件服务和命令行的在 `plugin/src/messages.ts`。新增或修改文字时两份一起改,单元测试会检查条目一一对应。改发给模型的占位符和说明(`plugin/src/rewrite.ts`)时,中文、英文(`--lang en`)各跑一次 `spike/src/v01-placeholder-selftest.ts`(用户 2026-09-25 要求)和 `spike/src/v01-needs-selftest.ts`(没有名字的工具截图全部取消后,模型能不能按编号要图、面板能不能认出来;用户 2026-09-26 要求);改的是自动选图的文字(自动版的占位符和说明、`cam_view_image` 的说明和返回的文字)时,再跑 `spike/src/v03-auto-selftest.ts`(模型该取图时会不会取、不该取时会不会不取;用户 2026-10-06 要求);改的是特征行说明时,再跑 `spike/src/v08-features-selftest.ts`(模型会不会给新图写特征行、照原话记评价、正文里不提,压缩后能不能靠特征行拿对图;v0.8);改的是压缩后放回的说明和清单时,再跑 `spike/src/v10-compaction-selftest.ts`(Codex 压缩之后,模型能不能靠清单认出之前的图、要看原图时按编号取对;v0.10)。这些自测三个 GPT-6 模型都要跑:`gpt-6-sol`、`gpt-6-luna`、`gpt-6-astra`,推理强度 low,用环境变量 `CAM_TEST_MODEL` 切换(用户 2026-09-28 要求)。自测在用户的 Codex 里建的任务,测完由脚本自动归档,不留给用户手动整理(用户 2026-09-28 要求);遗留的可以用 `spike/scripts/archive-test-threads.ts` 归档。
+- 界面和提示文字分简体中文、英文两份:面板的在 `plugin/src/panel/panel.html` 的文字表里,插件服务和命令行的在 `plugin/src/messages.ts`。新增或修改文字时两份一起改,单元测试会检查条目一一对应。改发给模型的占位符和说明(`plugin/src/rewrite.ts`)时,中文、英文(`--lang en`)各跑一次 `spike/src/v01-placeholder-selftest.ts`(用户 2026-09-25 要求)和 `spike/src/v01-needs-selftest.ts`(没有名字的工具截图全部取消后,模型能不能按编号要图、面板能不能认出来;用户 2026-09-26 要求);改的是自动选图的文字(自动版的占位符和说明、`cam_view_image` 的说明和返回的文字)时,再跑 `spike/src/v03-auto-selftest.ts`(模型该取图时会不会取、不该取时会不会不取;用户 2026-10-06 要求);改的是特征行说明时,再跑 `spike/src/v08-features-selftest.ts`(模型会不会给新图写特征行、照原话记评价、正文里不提,压缩后能不能靠特征行拿对图;v0.8);改的是压缩后放回的说明和清单时,再跑 `spike/src/v10-compaction-selftest.ts`(Codex 压缩之后,模型能不能靠清单认出之前的图、要看原图时按编号取对;v0.10)。这些自测三个 GPT-6 模型都要跑:`gpt-6-sol`、`gpt-6-luna`、`gpt-6-astra`,推理强度 low,用环境变量 `CAM_TEST_MODEL` 切换(用户 2026-09-28 要求)。自测在用户的 Codex 里建的任务,测完由脚本自动归档,不留给用户手动整理(用户 2026-09-28 要求);遗留的可以用 `spike/scripts/archive-test-threads.ts` 归档。
- 分工:Claude 维护 `docs/` 下的规格和方案,并负责开发和测试(阶段 0 的 T0–T2 由 Codex 完成;测试需要在 Codex 之外启动 app-server,所以从 T3 起改由 Claude 执行)。其他协作者不修改 spec.md 和 design.md。
## Git 规范
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 05de541..555825b 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -23,7 +23,7 @@ Bug reports, ideas and pull requests are all welcome. For a bug, an [issue](http
- Install from source into your Codex: quit Codex, run `cam install` in the repository (`./cam install` on macOS and Linux), then start Codex. `cam status` shows the installation, `cam uninstall` removes it. Run `cam install` again after changing runtime code, so Codex's copy of the plugin is updated.
- Run the tests with Node 24 or later: `cd spike && node --test`. CI runs them on Windows, macOS and Linux, then installs the plugin with Codex's CLI and runs the install and uninstall scripts.
- Work on the panel without Codex: `node spike/scripts/panel-dev.ts`, then open `http://127.0.0.1:17895/?solo=1`, or `?solo=1&thread=v08` for a task with the model's notes (add `&lang=en` for English). The page uses synthetic images and a temporary Codex folder, so your real data is never read or changed.
-- Text in the panel and the command line comes in English and Simplified Chinese: the panel's in the string table of `plugin/src/panel.html`, the rest in `plugin/src/messages.ts`. Change both; a unit test checks that they match.
+- Text in the panel and the command line comes in English and Simplified Chinese: the panel's in the string table of `plugin/src/panel/panel.html`, the rest in `plugin/src/messages.ts`. Change both; a unit test checks that they match.
- When you change the text the model sees (`plugin/src/rewrite.ts`), run the self-tests in `spike/src/v01-placeholder-selftest.ts` and `spike/src/v01-needs-selftest.ts`, and for Auto-select's wording `spike/src/v03-auto-selftest.ts`, in Chinese and with `--lang en`; `spike/src/v07-children-selftest.ts` covers subagents and side chats, and `spike/src/v08-features-selftest.ts` the model's notes, including after a compaction. They start their own engine and app-server, use your Codex account, and archive the test tasks they create.
## Pull requests
diff --git a/docs/design.md b/docs/design.md
index c71a20e..f8ea5c5 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -16,19 +16,21 @@
另一条路线是在新任务里重建历史(阶段 0 验证过,技术上可行)。没有采用,因为用户要在同一个任务里看到连续的对话,见 [history/v0.1/phase0-report.md](history/v0.1/phase0-report.md)。
+v0.11 起代码分成三层([v0.11/plan.md](v0.11/plan.md)):`core/` 是不认识任何平台的核心,`panel/` 是面板,`adapters/<平台>/` 是各平台的接入;`plugin/src` 顶层放入口(`plugin-server.ts`、`proxy.ts`、`cam.ts`)和还没拆完的文件。分层规则由 `spike/src/layers.test.ts` 检查。
+
| 部分 | 代码(`plugin/src`) | 作用 |
|---|---|---|
-| 引擎 | `proxy.ts`、`engine.ts`、`routes.ts` | 本机代理:按绑定线路转发、改写请求、记录每个任务最近一次请求的统计;全机只有一个 |
+| 引擎 | `proxy.ts`、`engine.ts`、`core/routes.ts` | 本机代理:按绑定线路转发、改写请求、记录每个任务最近一次请求的统计;全机只有一个 |
| 插件服务 | `plugin-server.ts` | Codex 为每个会话启动的 MCP 服务:拉起并看守引擎,给面板提供数据;v0.3 起还给模型提供取图工具 |
-| 面板 | `panel.html`、`panel-state.ts` | 侧边面板里的 MCP 应用,以及它要显示的数据 |
-| 任务索引 | `thread-index.ts`、`images.ts`、`thumbnail.ts`、`png.ts`、`thread-names.ts` | 从 Codex 的任务记录里只读地找出图片和它的来源、编号、生成缩略图、读任务名 |
-| 改写 | `rewrite.ts`、`selection.ts`、`request-stats.ts` | 占位符、说明和标签;勾选状态;请求统计 |
-| 接入和安装 | `codexconfig.ts`、`setup.ts`、`install.ts`、`codexcli.ts`、`cam.ts`、`plugin-cache.ts` | 管理 Codex 配置里带标记的块;用 Codex 的命令行装卸插件;保护升级中的旧运行文件;`cam` 命令行 |
-| 其他 | `language.ts`、`messages.ts`、`paths.ts`、`migrate-data.ts`、`binding.ts`、`entry.ts` | 语言、文字表、数据目录、旧数据迁移、新任务绑定 |
+| 面板 | `panel/panel.html`、`panel/panel-state.ts` | 侧边面板里的 MCP 应用,以及它要显示的数据 |
+| 任务索引 | `adapters/codex/thread-index.ts`、`images.ts`、`core/thumbnail.ts`、`core/png.ts`、`adapters/codex/thread-names.ts` | 从 Codex 的任务记录里只读地找出图片和它的来源、编号、生成缩略图、读任务名 |
+| 改写 | `rewrite.ts`、`selection.ts`、`core/request-stats.ts`、`core/notes.ts` | 占位符、说明和标签;勾选状态;请求统计;特征行 |
+| 接入和安装 | `adapters/codex/`:`codexconfig.ts`、`setup.ts`、`install.ts`、`codexcli.ts`、`plugin-cache.ts`、`binding.ts`;`cam.ts` | 管理 Codex 配置里带标记的块;用 Codex 的命令行装卸插件;保护升级中的旧运行文件;新任务绑定;`cam` 命令行 |
+| 其他 | `language.ts`、`messages.ts`、`core/paths.ts`、`core/migrate-data.ts`、`core/entry.ts` | 语言、文字表、数据目录、旧数据迁移 |
| Claude 接入(v0.4) | `hooks/register.js`(Mod,不在 `plugin/src`) | 把会话的请求地址指向引擎;`/cam` 打开面板(v0.6 起有图时自动打开);取图工具免确认 |
-| Claude 会话索引和改写(v0.4) | `claude-index.ts`、`claude-rewrite.ts` | 从 Claude Code 的会话记录找图、编号;改写 Anthropic Messages 请求 |
+| Claude 会话索引和改写(v0.4) | `adapters/claude/claude-index.ts`、`claude-rewrite.ts` | 从 Claude Code 的会话记录找图、编号;改写 Anthropic Messages 请求 |
| Claude 思考记录(v0.4) | `claude-thinking.ts` | 账号校验思考记录时,去掉和实际发出的历史对不上的思考 |
-| 面板页(v0.4) | `panel-web.js` | 引擎把 `panel.html` 作为网页提供时,代替 MCP 应用的宿主 |
+| 面板页(v0.4) | `panel/panel-web.js`、`panel/panel-language.ts` | 引擎把 `panel.html` 作为网页提供时,代替 MCP 应用的宿主 |
引擎和插件服务之间只通过数据目录里的文件共享状态,任何一方不在,另一方都照常工作。
diff --git a/hooks/register.js b/hooks/register.js
index 0009bbb..4400a54 100644
--- a/hooks/register.js
+++ b/hooks/register.js
@@ -5,7 +5,7 @@
// 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
+// 2. The way to the panel. The panel is the Codex panel itself (plugin/src/panel/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
// (user 2026-10-10). A small pane comes up only when there is something to say: the page could not open there (the
diff --git a/plugin/src/claude-index.ts b/plugin/src/adapters/claude/claude-index.ts
similarity index 99%
rename from plugin/src/claude-index.ts
rename to plugin/src/adapters/claude/claude-index.ts
index 2cbf2b3..498dd93 100644
--- a/plugin/src/claude-index.ts
+++ b/plugin/src/adapters/claude/claude-index.ts
@@ -22,9 +22,9 @@
import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { basename, dirname, join, resolve, sep } from "node:path";
-import { baseName, FETCHED_STATE, imageDigest, type ImageKind, type ImageRef } from "./images.ts";
-import { addNotes, copyNotes, type Notes } from "./notes.ts";
-import { pixelHashOfData, type FetchedCopy, type IndexedImage, type ThreadIndex } from "./thread-index.ts";
+import { baseName, FETCHED_STATE, imageDigest, type ImageKind, type ImageRef } from "../../images.ts";
+import { addNotes, copyNotes, type Notes } from "../../core/notes.ts";
+import { pixelHashOfData, type FetchedCopy, type IndexedImage, type ThreadIndex } from "../codex/thread-index.ts";
type Json = Record<string, any>;
export type ClaudeRecord = Json & { type: string; uuid?: string; parentUuid?: string | null; logicalParentUuid?: string | null };
diff --git a/plugin/src/binding.ts b/plugin/src/adapters/codex/binding.ts
similarity index 99%
rename from plugin/src/binding.ts
rename to plugin/src/adapters/codex/binding.ts
index a26915b..de068be 100644
--- a/plugin/src/binding.ts
+++ b/plugin/src/adapters/codex/binding.ts
@@ -10,7 +10,7 @@
import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
-import { bindingsDirOf } from "./paths.ts";
+import { bindingsDirOf } from "../../core/paths.ts";
import { hasRollout, threadsStartedSince } from "./thread-index.ts";
type Json = Record<string, any>;
diff --git a/plugin/src/codexcli.ts b/plugin/src/adapters/codex/codexcli.ts
similarity index 100%
rename from plugin/src/codexcli.ts
rename to plugin/src/adapters/codex/codexcli.ts
diff --git a/plugin/src/codexconfig.ts b/plugin/src/adapters/codex/codexconfig.ts
similarity index 100%
rename from plugin/src/codexconfig.ts
rename to plugin/src/adapters/codex/codexconfig.ts
diff --git a/plugin/src/install.ts b/plugin/src/adapters/codex/install.ts
similarity index 98%
rename from plugin/src/install.ts
rename to plugin/src/adapters/codex/install.ts
index aed62f9..73dfd16 100644
--- a/plugin/src/install.ts
+++ b/plugin/src/adapters/codex/install.ts
@@ -6,8 +6,8 @@
// Input: current texts and the user's persisted proxy variables. Output: next texts (envText null = delete the file).
import { coversLoopback, disableMcpServer, disableProxy, enableNoProxy, enableProxy, noProxyValue } from "./codexconfig.ts";
-import { systemLang } from "./language.ts";
-import { say } from "./messages.ts";
+import { systemLang } from "../../language.ts";
+import { say } from "../../messages.ts";
export const PLUGIN = "codex-attachment-manager";
export const MARKETPLACE = "codex-attachment-manager";
diff --git a/plugin/src/plugin-cache.ts b/plugin/src/adapters/codex/plugin-cache.ts
similarity index 100%
rename from plugin/src/plugin-cache.ts
rename to plugin/src/adapters/codex/plugin-cache.ts
diff --git a/plugin/src/setup.ts b/plugin/src/adapters/codex/setup.ts
similarity index 97%
rename from plugin/src/setup.ts
rename to plugin/src/adapters/codex/setup.ts
index c248bf9..95e28d5 100644
--- a/plugin/src/setup.ts
+++ b/plugin/src/adapters/codex/setup.ts
@@ -9,8 +9,8 @@ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameS
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";
+import { dataDir } from "../../core/paths.ts";
+import { registerRoute, routeBaseUrl, validateBaseUrl } from "../../core/routes.ts";
export const codexFiles = () => ({ configFile: join(codexHome(), "config.toml"), envFile: join(codexHome(), ".env") });
export const readConfig = (): string => (existsSync(codexFiles().configFile) ? readFileSync(codexFiles().configFile, "utf8") : "");
diff --git a/plugin/src/thread-index.ts b/plugin/src/adapters/codex/thread-index.ts
similarity index 99%
rename from plugin/src/thread-index.ts
rename to plugin/src/adapters/codex/thread-index.ts
index 746b73a..038506c 100644
--- a/plugin/src/thread-index.ts
+++ b/plugin/src/adapters/codex/thread-index.ts
@@ -16,9 +16,9 @@
import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
import { basename, dirname, join } from "node:path";
import { zstdDecompressSync } from "node:zlib";
-import { findImages, type ImageRef } from "./images.ts";
-import { addNotes, type Notes } from "./notes.ts";
-import { decodePng } from "./png.ts";
+import { findImages, type ImageRef } from "../../images.ts";
+import { addNotes, type Notes } from "../../core/notes.ts";
+import { decodePng } from "../../core/png.ts";
type Json = Record<string, any>;
// v0.10: compacted, before Codex last compacted the thread and not in the history it kept (its tool outputs): the
diff --git a/plugin/src/thread-names.ts b/plugin/src/adapters/codex/thread-names.ts
similarity index 100%
rename from plugin/src/thread-names.ts
rename to plugin/src/adapters/codex/thread-names.ts
diff --git a/plugin/src/cam.ts b/plugin/src/cam.ts
index 9ce835b..1a28163 100644
--- a/plugin/src/cam.ts
+++ b/plugin/src/cam.ts
@@ -16,18 +16,18 @@ import { spawn } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
-import { findCodexCli, runCodex } from "./codexcli.ts";
-import { codexHome, MCP_BEGIN, noProxyStatus, proxyStatus } from "./codexconfig.ts";
+import { findCodexCli, runCodex } from "./adapters/codex/codexcli.ts";
+import { codexHome, MCP_BEGIN, noProxyStatus, proxyStatus } from "./adapters/codex/codexconfig.ts";
import { buildOf, DEFAULT_PORT, engineHealth, ensureEngine } from "./engine.ts";
-import { isEntryPoint } from "./entry.ts";
+import { isEntryPoint } from "./core/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, pluginStatus } from "./install.ts";
-import { applySelection, loadPanelState, type PanelState } from "./panel-state.ts";
-import { dataDir, selectionDirOf } from "./paths.ts";
-import { preservingPluginCache } from "./plugin-cache.ts";
-import { backupConfig, connectDirectly, planEngine, readConfig, readEnv, useEngine } from "./setup.ts";
+import { migrateDataOnce } from "./core/migrate-data.ts";
+import { MARKETPLACE, PLUGIN, PLUGIN_ID, pluginStatus } from "./adapters/codex/install.ts";
+import { applySelection, loadPanelState, 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";
type Json = Record<string, any>;
const lang = systemLang();
diff --git a/plugin/src/children.ts b/plugin/src/children.ts
index ff6ad06..9a0a195 100644
--- a/plugin/src/children.ts
+++ b/plugin/src/children.ts
@@ -6,9 +6,9 @@
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { join } from "node:path";
-import { childrenDirOf } from "./paths.ts";
+import { childrenDirOf } from "./core/paths.ts";
import { mainTaskOf } from "./selection.ts";
-import { sideChatOrigin, spawnParent } from "./thread-index.ts";
+import { sideChatOrigin, spawnParent } from "./adapters/codex/thread-index.ts";
export type Child = { kind: "subagent" | "side"; from: string; at: string };
const THREAD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
diff --git a/plugin/src/claude-rewrite.ts b/plugin/src/claude-rewrite.ts
index e8f9128..9a7bf10 100644
--- a/plugin/src/claude-rewrite.ts
+++ b/plugin/src/claude-rewrite.ts
@@ -14,10 +14,10 @@
// turn; placeholders carry what the model noted.
// Input: the request's messages, the session's index, the keys to leave out. Output: new messages plus a report.
-import type { ClaudeIndex, ClaudeImage } from "./claude-index.ts";
+import type { ClaudeIndex, ClaudeImage } from "./adapters/claude/claude-index.ts";
import { imageDigest, type ImageDigest, type ImageKind } from "./images.ts";
import type { Lang } from "./language.ts";
-import { notesBy } from "./notes.ts";
+import { notesBy } from "./core/notes.ts";
import { autoPlaceholder, claudeNote, compactedNote, compactList, copyNote, duplicatePlaceholder, featureNote, hereNote, includedLabel, newImageWord, plainPlaceholder, type Described, type RewriteReport } from "./rewrite.ts";
type Json = Record<string, any>;
diff --git a/plugin/src/claude-thinking.ts b/plugin/src/claude-thinking.ts
index cda90d1..e3efeea 100644
--- a/plugin/src/claude-thinking.ts
+++ b/plugin/src/claude-thinking.ts
@@ -12,7 +12,7 @@
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { join } from "node:path";
-import { claudeThinkingDirOf } from "./paths.ts";
+import { claudeThinkingDirOf } from "./core/paths.ts";
type Json = Record<string, any>;
const THINKING = new Set(["thinking", "redacted_thinking"]);
diff --git a/plugin/src/entry.ts b/plugin/src/core/entry.ts
similarity index 100%
rename from plugin/src/entry.ts
rename to plugin/src/core/entry.ts
diff --git a/plugin/src/migrate-data.ts b/plugin/src/core/migrate-data.ts
similarity index 100%
rename from plugin/src/migrate-data.ts
rename to plugin/src/core/migrate-data.ts
diff --git a/plugin/src/notes.ts b/plugin/src/core/notes.ts
similarity index 100%
rename from plugin/src/notes.ts
rename to plugin/src/core/notes.ts
diff --git a/plugin/src/paths.ts b/plugin/src/core/paths.ts
similarity index 100%
rename from plugin/src/paths.ts
rename to plugin/src/core/paths.ts
diff --git a/plugin/src/png.ts b/plugin/src/core/png.ts
similarity index 100%
rename from plugin/src/png.ts
rename to plugin/src/core/png.ts
diff --git a/plugin/src/request-stats.ts b/plugin/src/core/request-stats.ts
similarity index 100%
rename from plugin/src/request-stats.ts
rename to plugin/src/core/request-stats.ts
diff --git a/plugin/src/routes.ts b/plugin/src/core/routes.ts
similarity index 100%
rename from plugin/src/routes.ts
rename to plugin/src/core/routes.ts
diff --git a/plugin/src/thumbnail.ts b/plugin/src/core/thumbnail.ts
similarity index 100%
rename from plugin/src/thumbnail.ts
rename to plugin/src/core/thumbnail.ts
diff --git a/plugin/src/engine.ts b/plugin/src/engine.ts
index 241a1cf..34fb63e 100644
--- a/plugin/src/engine.ts
+++ b/plugin/src/engine.ts
@@ -37,12 +37,14 @@ export async function engineHealth(port = DEFAULT_PORT, timeoutMs = 800): Promis
}
}
-// Which code a runtime folder holds: a hash of its .ts files, line endings normalised (a copy made from a Windows
-// checkout has CRLF). null when the folder is gone, e.g. a plugin version Codex has removed.
+// Which code a runtime folder holds: a hash of its .ts files, subfolders included (v0.11), line endings normalised (a
+// copy made from a Windows checkout has CRLF). A flat folder hashes as before. null when the folder is gone, e.g. a
+// plugin version Codex has removed.
export function buildOf(dir = here): string | null {
try {
const hash = createHash("sha256");
- for (const name of readdirSync(dir).filter((file) => file.endsWith(".ts")).sort()) {
+ const names = readdirSync(dir, { recursive: true, encoding: "utf8" }).map((name) => name.replaceAll("\\", "/"));
+ for (const name of names.filter((file) => file.endsWith(".ts")).sort()) {
hash.update(`${name}\0${readFileSync(join(dir, name), "utf8").replaceAll("\r\n", "\n")}\0`);
}
return hash.digest("hex").slice(0, 12);
diff --git a/plugin/src/language.ts b/plugin/src/language.ts
index 71ccf86..731a764 100644
--- a/plugin/src/language.ts
+++ b/plugin/src/language.ts
@@ -13,8 +13,8 @@
import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import { codexHome } from "./codexconfig.ts";
-import { dataDir } from "./paths.ts";
+import { codexHome } from "./adapters/codex/codexconfig.ts";
+import { dataDir } from "./core/paths.ts";
export type Lang = "zh" | "en";
// codex: the panel got Codex's interface language; system: it only had the system's.
diff --git a/plugin/src/panel-language.ts b/plugin/src/panel/panel-language.ts
similarity index 100%
rename from plugin/src/panel-language.ts
rename to plugin/src/panel/panel-language.ts
diff --git a/plugin/src/panel-state.ts b/plugin/src/panel/panel-state.ts
similarity index 97%
rename from plugin/src/panel-state.ts
rename to plugin/src/panel/panel-state.ts
index 61342bb..a8b1bd4 100644
--- a/plugin/src/panel-state.ts
+++ b/plugin/src/panel/panel-state.ts
@@ -13,16 +13,16 @@
// Input: thread id, the sessions directory (rollouts are only read) and the tool's data directory.
// Output: PanelState as plain JSON; selection changes are written to <data dir>/selection/.
-import { readChildren } from "./children.ts";
-import { claudeHome, claudeImageData, claudeStartedAt, isPrompt, loadClaudeIndex, type ClaudeIndex, type ClaudeRecord } from "./claude-index.ts";
-import type { ImageSource } from "./images.ts";
-import { sceneOf, withoutRecords } from "./notes.ts";
-import { childrenDirOf, claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, requestStatsDirOf, selectionDirOf } from "./paths.ts";
-import { readRequestStats, type RequestStats } from "./request-stats.ts";
-import { claudeSelection, effectiveSelection, stableIdsSince, writeSelection, type Mark, type Selection } from "./selection.ts";
-import { buildIndex, imageData, readThreadHistory, sessionMetaOf, type IndexedImage, type ThreadIndex } from "./thread-index.ts";
-import { threadTitle } from "./thread-names.ts";
-import { pngThumbnail } from "./thumbnail.ts";
+import { readChildren } from "../children.ts";
+import { claudeHome, claudeImageData, claudeStartedAt, isPrompt, loadClaudeIndex, type ClaudeIndex, type ClaudeRecord } from "../adapters/claude/claude-index.ts";
+import type { ImageSource } from "../images.ts";
+import { sceneOf, withoutRecords } from "../core/notes.ts";
+import { childrenDirOf, claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, requestStatsDirOf, selectionDirOf } from "../core/paths.ts";
+import { readRequestStats, type RequestStats } from "../core/request-stats.ts";
+import { claudeSelection, effectiveSelection, stableIdsSince, writeSelection, type Mark, type Selection } from "../selection.ts";
+import { buildIndex, imageData, readThreadHistory, sessionMetaOf, type IndexedImage, type ThreadIndex } from "../adapters/codex/thread-index.ts";
+import { threadTitle } from "../adapters/codex/thread-names.ts";
+import { pngThumbnail } from "../core/thumbnail.ts";
type Json = Record<string, any>;
type Record_ = { type: string; payload: Json };
diff --git a/plugin/src/panel-web.js b/plugin/src/panel/panel-web.js
similarity index 100%
rename from plugin/src/panel-web.js
rename to plugin/src/panel/panel-web.js
diff --git a/plugin/src/panel.html b/plugin/src/panel/panel.html
similarity index 100%
rename from plugin/src/panel.html
rename to plugin/src/panel/panel.html
diff --git a/plugin/src/plugin-server.ts b/plugin/src/plugin-server.ts
index b32a01a..4d1a52c 100644
--- a/plugin/src/plugin-server.ts
+++ b/plugin/src/plugin-server.ts
@@ -27,21 +27,21 @@ import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
-import { codexHome } from "./codexconfig.ts";
-import { bindThread, isUserThread, newThreads, resolveThread } from "./binding.ts";
-import { claudeStartedAt, loadClaudeIndex } from "./claude-index.ts";
+import { codexHome } from "./adapters/codex/codexconfig.ts";
+import { bindThread, isUserThread, newThreads, resolveThread } from "./adapters/codex/binding.ts";
+import { claudeStartedAt, loadClaudeIndex } from "./adapters/claude/claude-index.ts";
import { DEFAULT_PORT, ensureEngine } from "./engine.ts";
-import { isEntryPoint } from "./entry.ts";
+import { isEntryPoint } from "./core/entry.ts";
import { currentLang, langOf, rememberLang, type Lang } from "./language.ts";
import { say } from "./messages.ts";
-import { migrateDataOnce } from "./migrate-data.ts";
-import { applySelection, claudeImageFor, imageFor, loadPanelState, type ClaudePanelOptions, type PanelState } from "./panel-state.ts";
-import { claudeSelectionDirOf, dataDir, pixelCacheDirOf, selectionDirOf } from "./paths.ts";
+import { migrateDataOnce } from "./core/migrate-data.ts";
+import { applySelection, claudeImageFor, imageFor, loadPanelState, type ClaudePanelOptions, type PanelState } from "./panel/panel-state.ts";
+import { claudeSelectionDirOf, dataDir, pixelCacheDirOf, selectionDirOf } from "./core/paths.ts";
import { fetchedLabel, fetchWords } from "./rewrite.ts";
import { claudeSelection, effectiveSelection, ensureAutoDefault, ensureStableIds, stableIdsSince } from "./selection.ts";
-import { connectDirectly, useEngine, usesEngine } from "./setup.ts";
-import { hasRollout, loadThreadIndex, readThreadHistory, sessionMetaOf, setPixelCache, sideChatOrigin } from "./thread-index.ts";
-import { threadTitle } from "./thread-names.ts";
+import { connectDirectly, useEngine, usesEngine } from "./adapters/codex/setup.ts";
+import { hasRollout, loadThreadIndex, readThreadHistory, sessionMetaOf, setPixelCache, sideChatOrigin } from "./adapters/codex/thread-index.ts";
+import { threadTitle } from "./adapters/codex/thread-names.ts";
type Json = Record<string, any>;
const here = dirname(fileURLToPath(import.meta.url));
@@ -120,7 +120,7 @@ export const serverInfo = (lang: Lang) => ({ name: "codex-attachment-manager", t
export function readResource(uri: string): Json {
if (uri !== PANEL_URI) throw new Error(`unknown resource ${uri}`);
- const text = readFileSync(join(here, "panel.html"), "utf8");
+ const text = readFileSync(join(here, "panel", "panel.html"), "utf8");
// The page is self-contained: images arrive as data URLs through tool calls, nothing is fetched.
return { contents: [{ uri, mimeType: PANEL_MIME, text, _meta: { ui: { csp: { connectDomains: [], resourceDomains: [] }, prefersBorder: false } } }] };
}
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index 285a889..1dfc1b2 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -28,26 +28,26 @@ import tls from "node:tls";
import { fileURLToPath } from "node:url";
import zlib from "node:zlib";
import { childOf, recordChild } from "./children.ts";
-import { claudeHome, claudeImageData, claudeStartedAt, loadClaudeIndex, type ClaudeIndex } from "./claude-index.ts";
+import { claudeHome, claudeImageData, claudeStartedAt, loadClaudeIndex, type ClaudeIndex } from "./adapters/claude/claude-index.ts";
import { addCompacted, findRequestImages, rewriteMessages, summaryAt, type RequestImage, type Resend } from "./claude-rewrite.ts";
import { keepCacheRead, marksOutside, REMEMBERED, sentPrefixOf, type SentPrefix } from "./claude-cache.ts";
import { chainOf, fitThinking, readThinkingRecord, recordSent, writeThinkingRecord, type ThinkingRecord } from "./claude-thinking.ts";
-import { codexHome } from "./codexconfig.ts";
+import { codexHome } from "./adapters/codex/codexconfig.ts";
import { buildOf, DEFAULT_PORT, ENGINE_SERVICE, engineHealth, versionOf, watchForCodex } from "./engine.ts";
import { findImages, type ImageRef } from "./images.ts";
-import { isEntryPoint } from "./entry.ts";
+import { isEntryPoint } from "./core/entry.ts";
import { currentLang } from "./language.ts";
-import { migrateDataOnce } from "./migrate-data.ts";
+import { migrateDataOnce } from "./core/migrate-data.ts";
import { say } from "./messages.ts";
-import { claudePanelLanguage } from "./panel-language.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 { claudePanelLanguage } from "./panel/panel-language.ts";
+import { applyClaudeSelection, claudeImageFor, loadClaudePanelState, type ClaudePanelOptions } from "./panel/panel-state.ts";
+import { claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, pixelCacheDirOf, proxyLogDirOf, selectionDirOf } from "./core/paths.ts";
+import { recordRequest } from "./core/request-stats.ts";
+import { readRoute, registerRoute, routeBaseUrl, routingPort, validateBaseUrl, type Platform } from "./core/routes.ts";
import { addCodexCompacted, rewriteItems, type Described } from "./rewrite.ts";
-import { connectDirectly, pluginGone, usesEngine } from "./setup.ts";
+import { connectDirectly, pluginGone, usesEngine } from "./adapters/codex/setup.ts";
import { claudeSelection, effectiveSelection, ensureAutoDefault, ensureStableIds, selectionDir, sideChatSelection, stableIdsSince } from "./selection.ts";
-import { awaitingLine, imageData, loadThreadIndex, pixelHashOf, pixelHashOfData, setPixelCache, sideChatOrigin, writesNotes, type ThreadIndex } from "./thread-index.ts";
+import { awaitingLine, imageData, loadThreadIndex, pixelHashOf, pixelHashOfData, setPixelCache, sideChatOrigin, writesNotes, type ThreadIndex } from "./adapters/codex/thread-index.ts";
type Json = Record<string, any>;
const here = dirname(fileURLToPath(import.meta.url));
@@ -293,11 +293,6 @@ export function hasUnsafeInteger(json: string): boolean {
return false;
}
-export function hasUnchecked(threadId: string | null, dir = selectionDir, sessionsDir = join(codexHome(), "sessions")): boolean {
- if (!threadId) return false;
- try { return Object.keys(effectiveSelection(threadId, sessionsDir, dir).unchecked).length > 0; } catch { return false; }
-}
-
// Whether a thread's requests go through the rewrite (and so over HTTP): something unchecked, or automatic selection
// used at some point (v0.3), since from then on the history may hold copies the model fetched, left out of later turns.
// v0.7: a side chat's, always (v0.8: the switch for subagents and side chats is gone).
@@ -570,8 +565,8 @@ export function ownRequest(headers: IncomingHttpHeaders): boolean {
// The panel page for a Claude Code session: the same panel.html as in Codex, with panel-web.js before its own script.
export function claudePanelPage(dir = here): string {
- const page = readFileSync(join(dir, "panel.html"), "utf8");
- const bridge = readFileSync(join(dir, "panel-web.js"), "utf8");
+ const page = readFileSync(join(dir, "panel", "panel.html"), "utf8");
+ const bridge = readFileSync(join(dir, "panel", "panel-web.js"), "utf8");
const at = page.indexOf("<script>");
if (at < 0) throw new Error("panel.html has no script");
return `${page.slice(0, at)}<script>\n${bridge}\n</script>\n${page.slice(at)}`;
diff --git a/plugin/src/rewrite.ts b/plugin/src/rewrite.ts
index 03e8d3a..67c81f0 100644
--- a/plugin/src/rewrite.ts
+++ b/plugin/src/rewrite.ts
@@ -19,7 +19,7 @@
import { FETCHED_STATE, findImages, type ImageKind, type ImageRef } from "./images.ts";
import type { Lang } from "./language.ts";
-import type { Notes, Rating } from "./notes.ts";
+import type { Notes, Rating } from "./core/notes.ts";
type Json = Record<string, any>;
// notes (v0.8): what the model noted about the image, shown in its placeholder. awaiting (v0.10): an image of an
diff --git a/plugin/src/selection.ts b/plugin/src/selection.ts
index 784bc4b..99aad7a 100644
--- a/plugin/src/selection.ts
+++ b/plugin/src/selection.ts
@@ -18,8 +18,8 @@
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
-import { selectionDirOf } from "./paths.ts";
-import { forkOrigin, spawnParent, threadStartedAt } from "./thread-index.ts";
+import { selectionDirOf } from "./core/paths.ts";
+import { forkOrigin, spawnParent, threadStartedAt } from "./adapters/codex/thread-index.ts";
export type Mark = { id: string; at: string };
export type Selection = { threadId: string; unchecked: Record<string, Mark>; auto?: boolean; autoAt?: string; autoSince?: string; pinned?: Record<string, Mark>; inheritedFrom?: string };
diff --git a/spike/package.json b/spike/package.json
index 94a16d6..893a910 100644
--- a/spike/package.json
+++ b/spike/package.json
@@ -1,13 +1,11 @@
{
- "name": "codex-attachment-manager-phase0",
+ "name": "codex-attachment-manager-spike",
"private": true,
"type": "module",
"engines": {
"node": ">=24"
},
"scripts": {
- "test": "node --test",
- "index": "node src/index.ts",
- "match": "node src/match.ts"
+ "test": "node --test"
}
}
diff --git a/spike/scripts/archive-test-threads.ts b/spike/scripts/archive-test-threads.ts
index 2454835..bbd0f93 100644
--- a/spike/scripts/archive-test-threads.ts
+++ b/spike/scripts/archive-test-threads.ts
@@ -5,7 +5,7 @@
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
-import { codexHome } from "../../plugin/src/codexconfig.ts";
+import { codexHome } from "../../plugin/src/adapters/codex/codexconfig.ts";
import { AppServer, findBundledCodex } from "../src/appserver.ts";
import { archiveThreads } from "../src/testkit.ts";
diff --git a/spike/scripts/capture-codex.ps1 b/spike/scripts/capture-codex.ps1
deleted file mode 100644
index 3959e34..0000000
--- a/spike/scripts/capture-codex.ps1
+++ /dev/null
@@ -1,40 +0,0 @@
-# Purpose: P3 — capture only the Codex Desktop window to a PNG for UI checks, even when other windows cover it
-# (PrintWindow with PW_RENDERFULLCONTENT). The desktop app's process is ChatGPT.exe inside the OpenAI.Codex package.
-# Input: -Out <path.png>. Output: the PNG file and one line with its size.
-param([Parameter(Mandatory = $true)] [string] $Out)
-
-Add-Type -AssemblyName System.Drawing
-Add-Type @"
-using System;
-using System.Runtime.InteropServices;
-public static class CamWindow {
- [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
- [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
- [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
- [DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdc, uint flags);
- [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd);
-}
-"@
-# Physical pixels, so the window is not cropped on scaled displays.
-[void][CamWindow]::SetProcessDPIAware()
-
-$process = Get-Process | Where-Object { $_.MainWindowHandle -ne 0 -and $_.Path -like '*\OpenAI.Codex_*' } | Select-Object -First 1
-if (-not $process) { throw 'Codex Desktop window not found' }
-$handle = $process.MainWindowHandle
-if ([CamWindow]::IsIconic($handle)) { throw 'the Codex window is minimized' }
-
-$rect = New-Object CamWindow+RECT
-[void][CamWindow]::GetWindowRect($handle, [ref]$rect)
-$width = $rect.Right - $rect.Left
-$height = $rect.Bottom - $rect.Top
-$bitmap = New-Object System.Drawing.Bitmap $width, $height
-$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
-$hdc = $graphics.GetHdc()
-# 2 = PW_RENDERFULLCONTENT: needed for Chromium/Electron content.
-$rendered = [CamWindow]::PrintWindow($handle, $hdc, 2)
-$graphics.ReleaseHdc($hdc)
-$graphics.Dispose()
-New-Item -ItemType Directory -Force -Path (Split-Path -Parent $Out) | Out-Null
-$bitmap.Save($Out, [System.Drawing.Imaging.ImageFormat]::Png)
-$bitmap.Dispose()
-"{0}x{1} rendered={2}" -f $width, $height, $rendered
diff --git a/spike/scripts/panel-dev.ts b/spike/scripts/panel-dev.ts
index 2afaee7..9893308 100644
--- a/spike/scripts/panel-dev.ts
+++ b/spike/scripts/panel-dev.ts
@@ -316,9 +316,9 @@ function startTasks(count: number): void {
const { callTool, resetSetupBaseline } = await import("../../plugin/src/plugin-server.ts");
const { imageSizesOf } = await import("../../plugin/src/proxy.ts");
-const { recordRequest } = await import("../../plugin/src/request-stats.ts");
-const { connectDirectly, useEngine } = await import("../../plugin/src/setup.ts");
-const { requestStatsDirOf } = await import("../../plugin/src/paths.ts");
+const { recordRequest } = await import("../../plugin/src/core/request-stats.ts");
+const { connectDirectly, useEngine } = await import("../../plugin/src/adapters/codex/setup.ts");
+const { requestStatsDirOf } = await import("../../plugin/src/core/paths.ts");
const sessionsDir = join(root, "sessions");
const meta = { threadId: THREAD, thread_id: THREAD };
// Start with the red square, the copy of the blue circle and the large noise image unchecked, so both placeholder
@@ -369,7 +369,7 @@ function writeStats(kind: string): void {
// v0.8: the two copies' last requests (turn 7), and a subagent and a side chat of the auto one.
{
const { recordChild } = await import("../../plugin/src/children.ts");
- const { childrenDirOf } = await import("../../plugin/src/paths.ts");
+ const { childrenDirOf } = await import("../../plugin/src/core/paths.ts");
const stats = requestStatsDirOf(process.env.CAM_DATA_DIR);
for (const [id, file, auto] of V08_TASKS.flatMap(([main, manual]) => [[main, `rollout-2026-09-24T13-00-00-${main}.jsonl`, true], [manual, `rollout-2026-09-24T13-30-00-${manual}.jsonl`, false]] as const)) {
const items = readFileSync(join(day, file), "utf8").trim().split("\n").map((raw) => JSON.parse(raw)).filter((record) => record.type === "response_item").map((record) => record.payload);
@@ -462,7 +462,7 @@ let extra = 0;
createServer((request, response) => {
const reply = (status: number, type: string, body: string) => { response.writeHead(status, { "content-type": type, "cache-control": "no-store" }); response.end(body); };
if (request.method === "GET" && (request.url === "/" || request.url?.startsWith("/?"))) return reply(200, "text/html; charset=utf-8", HOST);
- if (request.method === "GET" && request.url === "/panel.html") return reply(200, "text/html; charset=utf-8", readFileSync(join(here, "..", "..", "plugin", "src", "panel.html"), "utf8"));
+ if (request.method === "GET" && request.url === "/panel.html") return reply(200, "text/html; charset=utf-8", readFileSync(join(here, "..", "..", "plugin", "src", "panel", "panel.html"), "utf8"));
if (request.method === "POST" && request.url?.startsWith("/stats")) {
writeStats(new URL(request.url, "http://x").searchParams.get("kind") ?? "normal");
return reply(200, "application/json", "{}");
diff --git a/spike/src/binding.test.ts b/spike/src/binding.test.ts
index b78347b..b118dfc 100644
--- a/spike/src/binding.test.ts
+++ b/spike/src/binding.test.ts
@@ -8,7 +8,7 @@ import { existsSync, mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "n
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { bindThread, boundThread, isUserThread, newThreads, resolveThread, type Shown } from "../../plugin/src/binding.ts";
+import { bindThread, boundThread, isUserThread, newThreads, resolveThread, type Shown } from "../../plugin/src/adapters/codex/binding.ts";
import { startThread } from "./testfixtures.ts";
const PANEL = "01a0d301-0000-7000-8000-00000000f00d";
diff --git a/spike/src/claude-compaction.test.ts b/spike/src/claude-compaction.test.ts
index 7d42919..a229043 100644
--- a/spike/src/claude-compaction.test.ts
+++ b/spike/src/claude-compaction.test.ts
@@ -9,7 +9,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { buildClaudeIndex, claudeImageData, loadClaudeIndex, readHistoryTranscript } from "../../plugin/src/claude-index.ts";
+import { buildClaudeIndex, claudeImageData, loadClaudeIndex, readHistoryTranscript } from "../../plugin/src/adapters/claude/claude-index.ts";
import { claudeSelection, writeSelection } from "../../plugin/src/selection.ts";
import { image, pngA, pngB, pngC, text, transcript } from "./claude-fixtures.ts";
import { png } from "./testkit.ts";
diff --git a/spike/src/claude-index.test.ts b/spike/src/claude-index.test.ts
index 6d892e4..3311036 100644
--- a/spike/src/claude-index.test.ts
+++ b/spike/src/claude-index.test.ts
@@ -7,7 +7,7 @@ import { appendFileSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { activeChain, buildClaudeIndex, claudeImageData, loadClaudeIndex, transcriptOf } from "../../plugin/src/claude-index.ts";
+import { activeChain, buildClaudeIndex, claudeImageData, loadClaudeIndex, transcriptOf } from "../../plugin/src/adapters/claude/claude-index.ts";
import { image, pngA, pngB, pngC, text, transcript, usualSession } from "./claude-fixtures.ts";
test("images get ids in conversation order: pasted ones by record, tool ones by tool_use_id", () => {
diff --git a/spike/src/claude-panel.test.ts b/spike/src/claude-panel.test.ts
index 76c57a0..a5eaeb3 100644
--- a/spike/src/claude-panel.test.ts
+++ b/spike/src/claude-panel.test.ts
@@ -9,7 +9,7 @@ import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { claudeSelectionDirOf } from "../../plugin/src/paths.ts";
+import { claudeSelectionDirOf } from "../../plugin/src/core/paths.ts";
import { callClaudeTool, claudeToolsFor } from "../../plugin/src/plugin-server.ts";
import { claudeNeedsRewrite, claudePanelApi, claudePanelPage, ownRequest, rewriteClaudeBody } from "../../plugin/src/proxy.ts";
import { ensureAutoDefault } from "../../plugin/src/selection.ts";
@@ -149,7 +149,7 @@ test("the panel page is the Codex panel.html with the engine bridge before its o
});
test("the Claude browser bridge uses the app language and notifies an already open panel when it changes", async () => {
- const script = readFileSync(new URL("../../plugin/src/panel-web.js", import.meta.url), "utf8");
+ const script = readFileSync(new URL("../../plugin/src/panel/panel-web.js", import.meta.url), "utf8");
let language = "ja";
const messages: any[] = [];
const window = {
diff --git a/spike/src/claude-rewrite.test.ts b/spike/src/claude-rewrite.test.ts
index 4bfa152..defa124 100644
--- a/spike/src/claude-rewrite.test.ts
+++ b/spike/src/claude-rewrite.test.ts
@@ -7,7 +7,7 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { buildClaudeIndex } from "../../plugin/src/claude-index.ts";
+import { buildClaudeIndex } from "../../plugin/src/adapters/claude/claude-index.ts";
import { addCompacted, findRequestImages, rewriteMessages, summaryAt } from "../../plugin/src/claude-rewrite.ts";
import { autoPlaceholder, claudeNote, compactedNote, compactLine, compactList, hereNote, includedLabel, plainPlaceholder } from "../../plugin/src/rewrite.ts";
import { image, pngA, pngB, pngC, text, transcript, usualRequest, usualSession } from "./claude-fixtures.ts";
diff --git a/spike/src/codex-compaction.test.ts b/spike/src/codex-compaction.test.ts
index 4b6bda2..9d220ed 100644
--- a/spike/src/codex-compaction.test.ts
+++ b/spike/src/codex-compaction.test.ts
@@ -13,7 +13,7 @@ import zlib from "node:zlib";
import { rewriteBody } from "../../plugin/src/proxy.ts";
import { addCodexCompacted, compactList } from "../../plugin/src/rewrite.ts";
import { writeSelection } from "../../plugin/src/selection.ts";
-import { loadThreadIndex } from "../../plugin/src/thread-index.ts";
+import { loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
import { png } from "./testkit.ts";
// These tests check the Chinese wording: the language is fixed, so neither the system's language nor one a panel
diff --git a/spike/src/codexconfig.test.ts b/spike/src/codexconfig.test.ts
index 0e451cd..68f6683 100644
--- a/spike/src/codexconfig.test.ts
+++ b/spike/src/codexconfig.test.ts
@@ -4,7 +4,7 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { coversLoopback, disableMcpServer, disableProxy, enableMcpServer, enableNoProxy, enableProxy, noProxyStatus, noProxyValue, proxyStatus } from "../../plugin/src/codexconfig.ts";
+import { coversLoopback, disableMcpServer, disableProxy, enableMcpServer, enableNoProxy, enableProxy, noProxyStatus, noProxyValue, proxyStatus } from "../../plugin/src/adapters/codex/codexconfig.ts";
const URL = "http://localhost:17891/backend-api/codex";
const withFeatures = 'model = "gpt-6-sol"\n\n[features]\nview_image = true\n\n[mcp_servers.demo]\ncommand = "node"\n';
diff --git a/spike/src/engine.test.ts b/spike/src/engine.test.ts
index acc1bd1..ded8fed 100644
--- a/spike/src/engine.test.ts
+++ b/spike/src/engine.test.ts
@@ -14,8 +14,8 @@ import test from "node:test";
import { setTimeout as sleep } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { buildOf, compareVersions, countClaudeInPs, countClaudeProcesses, countCodexInPs, countCodexProcesses, engineHealth, ensureEngine, isEngineHealth, shouldReplace, watchForCodex, type Health } from "../../plugin/src/engine.ts";
-import { selectionDirOf } from "../../plugin/src/paths.ts";
-import { readRequestStats, recordRequest } from "../../plugin/src/request-stats.ts";
+import { selectionDirOf } from "../../plugin/src/core/paths.ts";
+import { readRequestStats, recordRequest } from "../../plugin/src/core/request-stats.ts";
import { autoDefaultSince, writeSelection } from "../../plugin/src/selection.ts";
const here = dirname(fileURLToPath(import.meta.url));
diff --git a/spike/src/eval-keyframes.ts b/spike/src/eval-keyframes.ts
index 1001723..14a695c 100644
--- a/spike/src/eval-keyframes.ts
+++ b/spike/src/eval-keyframes.ts
@@ -29,11 +29,11 @@ import { dirname, join, resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { AppServer, findBundledCodex } from "./appserver.ts";
-import { codexHome } from "../../plugin/src/codexconfig.ts";
+import { codexHome } from "../../plugin/src/adapters/codex/codexconfig.ts";
import { engineHealth } from "../../plugin/src/engine.ts";
import { languageFileOf, rememberLang } from "../../plugin/src/language.ts";
-import { selectionDirOf } from "../../plugin/src/paths.ts";
-import { loadThreadIndex } from "../../plugin/src/thread-index.ts";
+import { selectionDirOf } from "../../plugin/src/core/paths.ts";
+import { loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
import { archiveThreads, png, TEST_EFFORT, TEST_MODEL, text } from "./testkit.ts";
type Json = Record<string, any>;
diff --git a/spike/src/eval-summary.ts b/spike/src/eval-summary.ts
index b2dec3b..d37ddd8 100644
--- a/spike/src/eval-summary.ts
+++ b/spike/src/eval-summary.ts
@@ -7,8 +7,8 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
-import { codexHome } from "../../plugin/src/codexconfig.ts";
-import { loadThreadIndex } from "../../plugin/src/thread-index.ts";
+import { codexHome } from "../../plugin/src/adapters/codex/codexconfig.ts";
+import { loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
type Json = Record<string, any>;
const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
diff --git a/spike/src/feature-backfill.test.ts b/spike/src/feature-backfill.test.ts
index d62219d..7e024dc 100644
--- a/spike/src/feature-backfill.test.ts
+++ b/spike/src/feature-backfill.test.ts
@@ -9,11 +9,11 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import zlib from "node:zlib";
-import { buildClaudeIndex } from "../../plugin/src/claude-index.ts";
+import { buildClaudeIndex } from "../../plugin/src/adapters/claude/claude-index.ts";
import { rewriteBody, rewriteClaudeBody } from "../../plugin/src/proxy.ts";
import { featureNote } from "../../plugin/src/rewrite.ts";
import { writeSelection } from "../../plugin/src/selection.ts";
-import { awaitingLine, loadThreadIndex } from "../../plugin/src/thread-index.ts";
+import { awaitingLine, loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
import { image, pngA, pngB, text, transcript } from "./claude-fixtures.ts";
import { png } from "./testkit.ts";
diff --git a/spike/src/history.ts b/spike/src/history.ts
deleted file mode 100644
index 7a34596..0000000
--- a/spike/src/history.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-// Purpose: read a thread's effective model-visible history from paginated rollout segments (read-only)
-// and estimate how many bytes of history a model request carries.
-// Input: the sessions directory and a thread or segment id. Output: records and byte estimates (in memory).
-
-import { createHash } from "node:crypto";
-import { readdirSync, readFileSync } from "node:fs";
-import { basename, join } from "node:path";
-
-type Json = Record<string, any>;
-export type RolloutRecord = { file: string; line: number; offset: number; ordinal: number | null; type: string; payload: Json };
-
-function walk(directory: string): string[] {
- return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
- const full = join(directory, entry.name);
- return entry.isDirectory() ? walk(full) : entry.isFile() ? [full] : [];
- });
-}
-
-// A segment id is the UUID suffix after the thread id in the file name; the first segment uses the thread id itself.
-export function indexSegments(sessionsDir: string): Map<string, string> {
- const segments = new Map<string, string>();
- for (const file of walk(sessionsDir)) {
- const match = /rollout-[0-9T:-]+-([0-9a-f-]{36})(?:_([0-9a-f-]{36}))?\.jsonl$/.exec(basename(file));
- if (match) segments.set(match[2] ?? match[1], file);
- }
- return segments;
-}
-
-function ownRecords(file: string, endOffset: number): { meta: Json; records: RolloutRecord[] } {
- const buffer = readFileSync(file);
- const records: RolloutRecord[] = [];
- let meta: Json = {};
- let offset = 0;
- let line = 0;
- while (offset < buffer.length && offset < endOffset) {
- let end = buffer.indexOf(0x0a, offset);
- if (end < 0) end = buffer.length;
- line++;
- const text = buffer.toString("utf8", offset, end).replace(/\r$/, "");
- if (text.trim()) {
- const record = JSON.parse(text);
- if (record.type === "session_meta" && line === 1) meta = record.payload ?? {};
- records.push({ file, line, offset, ordinal: record.ordinal ?? null, type: record.type, payload: record.payload ?? {} });
- }
- offset = end + 1;
- }
- return { meta, records };
-}
-
-// Effective history = the base segment's records before history_base.end_byte_offset (recursively) + this segment's records.
-export function effectiveRecords(segments: Map<string, string>, segmentId: string, endOffset = Number.POSITIVE_INFINITY): RolloutRecord[] {
- const file = segments.get(segmentId);
- if (!file) throw new Error(`rollout segment not found: ${segmentId}`);
- const { meta, records } = ownRecords(file, endOffset);
- const base = meta.history_base;
- const inherited = base ? effectiveRecords(segments, base.thread_id, base.end_byte_offset) : [];
- return [...inherited, ...records];
-}
-
-// The newest segment of a thread is the one no other segment of that thread uses as its base.
-export function latestSegment(segments: Map<string, string>, threadId: string): string {
- const own = [...segments.entries()].filter(([, file]) => basename(file).includes(threadId));
- const bases = new Set<string>();
- for (const [, file] of own) {
- const first = readFileSync(file, "utf8").split("\n", 1)[0];
- const base = JSON.parse(first).payload?.history_base?.thread_id;
- if (base) bases.add(base);
- }
- const heads = own.filter(([id]) => !bases.has(id)).map(([id]) => id);
- if (heads.length !== 1) throw new Error(`expected one latest segment for ${threadId}, found ${heads.length}`);
- return heads[0];
-}
-
-export type InlineImage = { sha256: string; bytes: number; dataUrlChars: number; record: RolloutRecord };
-
-export function inlineImages(records: RolloutRecord[]): InlineImage[] {
- const images: InlineImage[] = [];
- for (const record of records) {
- if (record.type !== "response_item") continue;
- const parts = Array.isArray(record.payload.content) ? record.payload.content : Array.isArray(record.payload.output) ? record.payload.output : [];
- for (const part of parts) {
- const url = part?.image_url;
- const match = typeof url === "string" ? /^data:[^;,]+;base64,(.+)$/s.exec(url) : null;
- if (!match) continue;
- const bytes = Buffer.from(match[1], "base64");
- images.push({ sha256: createHash("sha256").update(bytes).digest("hex"), bytes: bytes.length, dataUrlChars: url.length, record });
- }
- }
- return images;
-}
-
-// Bytes of the history items a request would carry: every response_item payload serialized as UTF-8 JSON.
-export function historyBytes(records: RolloutRecord[]): { items: number; bytes: number } {
- let bytes = 0;
- let items = 0;
- for (const record of records) {
- if (record.type !== "response_item") continue;
- items++;
- bytes += Buffer.byteLength(JSON.stringify(record.payload), "utf8");
- }
- return { items, bytes };
-}
diff --git a/spike/src/index.ts b/spike/src/index.ts
deleted file mode 100644
index dba70a8..0000000
--- a/spike/src/index.ts
+++ /dev/null
@@ -1,243 +0,0 @@
-// Purpose: read sample Codex rollout JSONL files and build a local-only image timeline.
-// Input: --sessions <directory> --threads <id,id>; output: local/assets.json and local/assets.md.
-
-import { createHash } from "node:crypto";
-import { createReadStream, existsSync, mkdirSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
-import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
-import { createInterface } from "node:readline";
-import { fileURLToPath } from "node:url";
-import { decodePng } from "../../plugin/src/png.ts";
-import { fileSha256, pathForViewedImage } from "./viewpaths.ts";
-
-type Json = Record<string, any>;
-type Occurrence = {
- threadId: string;
- turnId: string | null;
- turnNumber: number | null;
- timestamp: string;
- source: "user_upload" | "view_image" | "tool_output";
- byteLength: number;
- byteSha256: string;
- pixelSha256: string | null;
- width: number | null;
- height: number | null;
- mime: string;
- knownLocalPath: string | null;
- rolloutFile: string;
- line: number;
- contentIndex: number;
- assetId: string;
-};
-
-const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
-const localRoot = join(repoRoot, "local");
-
-function argument(name: string): string {
- const index = process.argv.indexOf(name);
- const value = process.argv[index + 1];
- if (index < 0 || !value || value.startsWith("--")) throw new Error(`missing ${name}`);
- return value;
-}
-
-function walk(directory: string): string[] {
- return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
- const full = join(directory, entry.name);
- return entry.isDirectory() ? walk(full) : entry.isFile() ? [full] : [];
- });
-}
-
-function localPathFromText(text: unknown): string | null {
- if (typeof text !== "string") return null;
- const found = text.match(/\bpath\s*=\s*["']([^"']+)["']/i)?.[1];
- if (!found) return null;
- if (found.startsWith("file://")) {
- try { return fileURLToPath(found); } catch { return null; }
- }
- return isAbsolute(found) ? found : null;
-}
-
-function pathBefore(content: Json[], index: number): string | null {
- for (let i = index - 1; i >= 0; i--) {
- const found = localPathFromText(content[i]?.text);
- if (found) return found;
- }
- return null;
-}
-
-function imageParts(item: Json): Array<{ image: Json; index: number; path: string | null }> {
- const content: Json[] = Array.isArray(item.content) ? item.content : Array.isArray(item.output) ? item.output : [];
- return content.flatMap((part, index) =>
- part?.type === "input_image" || part?.type === "output_image"
- ? [{ image: part, index, path: pathBefore(content, index) }]
- : [],
- );
-}
-
-function pathFromImageView(uri: unknown): string | null {
- if (typeof uri !== "string") return null;
- if (uri.startsWith("file://")) {
- try { return fileURLToPath(uri); } catch { return null; }
- }
- return isAbsolute(uri) ? uri : null;
-}
-
-function markdownCell(value: unknown): string {
- return String(value ?? "—").replaceAll("|", "\\|").replaceAll("\n", " ");
-}
-
-async function main(): Promise<void> {
- const sessions = resolve(argument("--sessions"));
- const threadIds = argument("--threads").split(",").filter(Boolean);
- if (!threadIds.length || !existsSync(sessions)) throw new Error("sessions directory or thread ids unavailable");
- mkdirSync(localRoot, { recursive: true });
- const actualLocal = realpathSync(localRoot);
- if (relative(repoRoot, actualLocal).startsWith("..")) throw new Error("local output points outside the repository");
-
- const files = walk(sessions)
- .filter((file) => file.endsWith(".jsonl") && threadIds.some((id) => basename(file).includes(id)))
- .sort();
- if (!files.length) throw new Error("no sample rollout files found");
- const before = new Map<string, string>();
- for (const file of files) before.set(file, await fileSha256(file));
-
- const occurrences: Occurrence[] = [];
- const unrecognized: Json[] = [];
- const turns: Array<{ threadId: string; turnId: string; timestamp: string }> = [];
- const decoded = new Map<string, { pixelSha256: string; width: number; height: number }>();
- const viewedFileHashes = new Map<string, string | null>();
- for (const file of files) {
- let lineNumber = 0;
- let threadId: string | null = null;
- let activeTurn: string | null = null;
- const calls = new Map<string, Json>();
- let pendingViews: string[] = [];
- const input = createInterface({ input: createReadStream(file, { encoding: "utf8" }), crlfDelay: Infinity });
- for await (const line of input) {
- lineNumber++;
- let record: Json;
- try { record = JSON.parse(line); }
- catch {
- unrecognized.push({ rolloutFile: basename(file), line: lineNumber, reason: "invalid_json" });
- continue;
- }
- const payload: Json = record.payload ?? {};
- if (record.type === "session_meta") {
- threadId = payload.id ?? null;
- continue;
- }
- if (!threadId || !threadIds.includes(threadId)) continue;
- if (record.type === "event_msg" && payload.type === "task_started") {
- activeTurn = payload.turn_id ?? null;
- if (activeTurn) turns.push({ threadId, turnId: activeTurn, timestamp: record.timestamp });
- }
- if (record.type === "event_msg" && payload.type === "item_completed" && payload.item?.type === "ImageView") {
- const viewedPath = pathFromImageView(payload.item.path);
- if (viewedPath) pendingViews.push(viewedPath);
- else unrecognized.push({ rolloutFile: basename(file), line: lineNumber, reason: "image_view_path_unreadable" });
- }
- if (record.type !== "response_item") continue;
- if (payload.type === "custom_tool_call") {
- calls.set(payload.call_id, { name: payload.name, input: payload.input });
- continue;
- }
- const parts = imageParts(payload);
- if (!parts.length) continue;
- const call = calls.get(payload.call_id);
- const source: Occurrence["source"] = payload.type === "message" && payload.role === "user"
- ? "user_upload"
- : String(call?.input ?? "").includes("view_image") ? "view_image" : "tool_output";
- const viewCandidates = source === "view_image" ? pendingViews.splice(0, parts.length) : [];
- for (const { image, index, path } of parts) {
- const url = image.image_url ?? image.url;
- const match = typeof url === "string" ? /^data:([^;,]+);base64,(.+)$/s.exec(url) : null;
- if (!match) {
- unrecognized.push({ rolloutFile: basename(file), line: lineNumber, contentIndex: index, reason: "image_without_inline_data" });
- continue;
- }
- const bytes = Buffer.from(match[2], "base64");
- const byteSha256 = createHash("sha256").update(bytes).digest("hex");
- let info = decoded.get(byteSha256);
- if (!info && match[1] === "image/png") {
- try {
- const png = decodePng(bytes);
- info = { pixelSha256: png.pixelSha256, width: png.width, height: png.height };
- decoded.set(byteSha256, info);
- } catch (error) {
- unrecognized.push({ rolloutFile: basename(file), line: lineNumber, contentIndex: index, reason: "pixel_decode_failed", detail: String(error) });
- }
- }
- if (match[1] !== "image/png") {
- unrecognized.push({ rolloutFile: basename(file), line: lineNumber, contentIndex: index, reason: "unsupported_image_mime", mime: match[1] });
- }
- occurrences.push({
- threadId,
- turnId: payload.internal_chat_message_metadata_passthrough?.turn_id ?? activeTurn,
- turnNumber: null,
- timestamp: record.timestamp,
- source,
- byteLength: bytes.length,
- byteSha256,
- pixelSha256: info?.pixelSha256 ?? null,
- width: info?.width ?? null,
- height: info?.height ?? null,
- mime: match[1],
- knownLocalPath: source === "view_image" ? await pathForViewedImage(viewCandidates, byteSha256, viewedFileHashes) : path,
- rolloutFile: basename(file),
- line: lineNumber,
- contentIndex: index,
- assetId: "",
- });
- }
- }
- for (const viewedPath of pendingViews) {
- unrecognized.push({ rolloutFile: basename(file), reason: "image_view_without_inline_result", knownLocalPath: viewedPath });
- }
- }
-
- const turnNumbers = new Map<string, number>();
- for (const id of threadIds) {
- const sorted = turns.filter((turn) => turn.threadId === id).sort((a, b) => a.timestamp.localeCompare(b.timestamp));
- for (const turn of sorted) {
- const key = `${id}:${turn.turnId}`;
- if (!turnNumbers.has(key)) turnNumbers.set(key, [...turnNumbers.keys()].filter((value) => value.startsWith(`${id}:`)).length + 1);
- }
- }
- occurrences.sort((a, b) => a.timestamp.localeCompare(b.timestamp) || a.rolloutFile.localeCompare(b.rolloutFile) || a.line - b.line || a.contentIndex - b.contentIndex);
- const assets: Array<Json> = [];
- const groups = new Map<string, Json>();
- for (const occurrence of occurrences) {
- occurrence.turnNumber = occurrence.turnId ? turnNumbers.get(`${occurrence.threadId}:${occurrence.turnId}`) ?? null : null;
- const groupKey = occurrence.pixelSha256 ? `pixel:${occurrence.pixelSha256}` : `byte:${occurrence.byteSha256}`;
- let asset = groups.get(groupKey);
- if (!asset) {
- asset = { assetId: `IMG-${String(assets.length + 1).padStart(3, "0")}`, pixelSha256: occurrence.pixelSha256, width: occurrence.width, height: occurrence.height, byteHashes: [], occurrenceCount: 0, threadIds: [] };
- groups.set(groupKey, asset);
- assets.push(asset);
- }
- occurrence.assetId = asset.assetId;
- asset.occurrenceCount++;
- if (!asset.byteHashes.includes(occurrence.byteSha256)) asset.byteHashes.push(occurrence.byteSha256);
- if (!asset.threadIds.includes(occurrence.threadId)) asset.threadIds.push(occurrence.threadId);
- }
-
- const sourceFiles = [];
- for (const file of files) {
- const afterSha256 = await fileSha256(file);
- sourceFiles.push({ path: file, bytes: statSync(file).size, beforeSha256: before.get(file), afterSha256, unchanged: before.get(file) === afterSha256 });
- }
- const manifest = { createdAt: new Date().toISOString(), threadIds, sourceFiles, originalFilesUnchanged: sourceFiles.every((source) => source.unchanged), assets, occurrences, unrecognized };
- writeFileSync(join(localRoot, "assets.json"), JSON.stringify(manifest, null, 2));
-
- const rows = occurrences.map((o) => `| ${markdownCell(o.threadId.slice(0, 8))} | ${markdownCell(o.turnNumber)} | ${markdownCell(o.timestamp)} | ${markdownCell(o.source)} | ${o.assetId} | ${o.byteLength} | ${o.byteSha256.slice(0, 12)} | ${markdownCell(o.pixelSha256?.slice(0, 12))} | ${markdownCell(o.width && o.height ? `${o.width}×${o.height}` : null)} | ${markdownCell(o.knownLocalPath)} | ${markdownCell(`${o.rolloutFile}:${o.line}:${o.contentIndex}`)} |`);
- const report = [
- "# 阶段 0 素材清单(仅本机)", "",
- `记录文件:${files.length};图片出现记录:${occurrences.length};素材:${assets.length};无法识别:${unrecognized.length};原文件哈希不变:${manifest.originalFilesUnchanged}`, "",
- "| 任务 | 轮次 | 时间 UTC | 来源 | 素材 | 图片字节 | 字节 SHA 前缀 | 像素 SHA 前缀 | 尺寸 | 已知本地路径 | 记录位置 |",
- "| --- | ---: | --- | --- | --- | ---: | --- | --- | --- | --- | --- |",
- ...rows, "", "## 无法识别的项目", "", "```json", JSON.stringify(unrecognized, null, 2), "```", "",
- ].join("\n");
- writeFileSync(join(localRoot, "assets.md"), report);
- console.log(JSON.stringify({ files: files.length, occurrences: occurrences.length, assets: assets.length, unrecognized: unrecognized.length, originalFilesUnchanged: manifest.originalFilesUnchanged, byThread: Object.fromEntries(threadIds.map((id) => [id, { occurrences: occurrences.filter((o) => o.threadId === id).length, assets: new Set(occurrences.filter((o) => o.threadId === id).map((o) => o.assetId)).size }])) }));
-}
-
-await main();
diff --git a/spike/src/install.test.ts b/spike/src/install.test.ts
index 33f6019..ce6a8ce 100644
--- a/spike/src/install.test.ts
+++ b/spike/src/install.test.ts
@@ -6,8 +6,8 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { enableMcpServer } from "../../plugin/src/codexconfig.ts";
-import { needsNoProxy, planInstall, planUninstall, pluginStatus, SERVER_NAME } from "../../plugin/src/install.ts";
+import { enableMcpServer } from "../../plugin/src/adapters/codex/codexconfig.ts";
+import { needsNoProxy, planInstall, planUninstall, pluginStatus, SERVER_NAME } from "../../plugin/src/adapters/codex/install.ts";
// These tests check the Chinese wording: the language is fixed, so neither the system's language nor one a panel
// reported on this machine decides it (v0.1-14).
diff --git a/spike/src/language.test.ts b/spike/src/language.test.ts
index db98b9f..a85cc80 100644
--- a/spike/src/language.test.ts
+++ b/spike/src/language.test.ts
@@ -95,7 +95,7 @@ test("the plugin's texts exist in both languages with the same {values}", () =>
});
test("the panel's texts exist in both languages with the same {values}; English may add a form for one", () => {
- const page = readFileSync(join(here, "..", "..", "plugin", "src", "panel.html"), "utf8");
+ const page = readFileSync(join(here, "..", "..", "plugin", "src", "panel", "panel.html"), "utf8");
const table = JSON.parse(/<script type="application\/json" id="messages">([\s\S]*?)<\/script>/.exec(page)![1]);
const base = (keys: string[]) => keys.filter((key) => !key.endsWith("_one")).sort();
assert.deepEqual(base(Object.keys(table.en)), base(Object.keys(table.zh)));
diff --git a/spike/src/layers.test.ts b/spike/src/layers.test.ts
new file mode 100644
index 0000000..39ebc92
--- /dev/null
+++ b/spike/src/layers.test.ts
@@ -0,0 +1,84 @@
+// Purpose: v0.11 — keeps the plugin's three layers apart (docs/v0.11/plan.md 3.6). The core imports only the core;
+// the panel only the core; a request-format translator (adapters/protocols) the core and other translators; a
+// platform (adapters/<name>) the core, the translators and its own files. Files at the top of plugin/src are the
+// entry points and the ones not sorted yet; they may import anything.
+// PENDING lists the imports that still break a rule while the split goes on. It may only shrink: a new break fails,
+// and so does an entry that no longer occurs, so the list never keeps a stale exception.
+// Input: the source files of plugin/src. Output: test results.
+import assert from "node:assert/strict";
+import { readdirSync, readFileSync } from "node:fs";
+import { dirname, join, posix } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const src = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "plugin", "src");
+
+const PENDING = new Set<string>([
+ "adapters/claude/claude-index.ts -> adapters/codex/thread-index.ts",
+ "adapters/claude/claude-index.ts -> images.ts",
+ "adapters/codex/install.ts -> language.ts",
+ "adapters/codex/install.ts -> messages.ts",
+ "adapters/codex/thread-index.ts -> images.ts",
+ "panel/panel-state.ts -> adapters/claude/claude-index.ts",
+ "panel/panel-state.ts -> adapters/codex/thread-index.ts",
+ "panel/panel-state.ts -> adapters/codex/thread-names.ts",
+ "panel/panel-state.ts -> children.ts",
+ "panel/panel-state.ts -> images.ts",
+ "panel/panel-state.ts -> selection.ts",
+]);
+
+type Layer = "core" | "panel" | "protocols" | `adapter:${string}` | "top";
+
+export function layerOf(file: string): Layer {
+ const [first, second] = file.split("/");
+ if (first === "core" || first === "panel") return first;
+ if (first === "adapters" && second === "protocols") return "protocols";
+ if (first === "adapters" && second && file.split("/").length > 2) return `adapter:${second}`;
+ return "top";
+}
+
+export function allowed(from: Layer, to: Layer): boolean {
+ if (from === "top") return true;
+ if (to === "core") return true;
+ if (from === "protocols" || from.startsWith("adapter:")) return to === "protocols" || to === from;
+ return false;
+}
+
+function sources(): string[] {
+ return readdirSync(src, { recursive: true, encoding: "utf8" }).map((name) => name.replaceAll("\\", "/")).filter((name) => /\.(ts|js)$/.test(name)).sort();
+}
+
+function importsOf(file: string): string[] {
+ const text = readFileSync(join(src, file), "utf8");
+ const found = new Set<string>();
+ for (const match of text.matchAll(/(?:\bfrom|\bimport)\s*\(?\s*["'](\.{1,2}\/[^"']+)["']/g)) found.add(posix.normalize(posix.join(posix.dirname(file), match[1])));
+ return [...found];
+}
+
+export function breaks(): string[] {
+ const out: string[] = [];
+ for (const file of sources()) {
+ for (const target of importsOf(file)) if (!allowed(layerOf(file), layerOf(target))) out.push(`${file} -> ${target}`);
+ }
+ return out.sort();
+}
+
+test("layers: each folder is the layer the plan says", () => {
+ assert.equal(layerOf("core/notes.ts"), "core");
+ assert.equal(layerOf("panel/panel-state.ts"), "panel");
+ assert.equal(layerOf("adapters/protocols/openai-chat/read.ts"), "protocols");
+ assert.equal(layerOf("adapters/codex/thread-index.ts"), "adapter:codex");
+ assert.equal(layerOf("proxy.ts"), "top");
+ assert.equal(allowed("core", "panel"), false);
+ assert.equal(allowed("panel", "adapter:codex"), false);
+ assert.equal(allowed("adapter:claude", "adapter:codex"), false);
+ assert.equal(allowed("adapter:claude", "protocols"), true);
+ assert.equal(allowed("protocols", "adapter:codex"), false);
+ assert.equal(allowed("adapter:codex", "top"), false);
+});
+
+test("layers: no import breaks the rules beyond the pending list, and the list has nothing stale", () => {
+ const now = breaks();
+ assert.deepEqual(now.filter((line) => !PENDING.has(line)), [], "new imports across layers");
+ assert.deepEqual([...PENDING].filter((line) => !now.includes(line)), [], "pending entries that no longer occur: remove them");
+});
diff --git a/spike/src/match.ts b/spike/src/match.ts
deleted file mode 100644
index ece4030..0000000
--- a/spike/src/match.ts
+++ /dev/null
@@ -1,175 +0,0 @@
-// Purpose: match indexed images to read-only local originals and cache inline-only copies.
-// Input: local/assets.json plus --project and --generated image directories.
-// Output: local/matches.json, local/matches.md, and exact inline copies under local/cache/.
-
-import { createHash } from "node:crypto";
-import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
-import { basename, dirname, extname, join, resolve } from "node:path";
-import { createInterface } from "node:readline";
-import { fileURLToPath } from "node:url";
-import { decodePng, type DecodedPng } from "../../plugin/src/png.ts";
-
-type Json = Record<string, any>;
-const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
-const localRoot = join(repoRoot, "local");
-
-function argument(name: string): string {
- const i = process.argv.indexOf(name);
- if (i < 0 || !process.argv[i + 1]) throw new Error(`missing ${name}`);
- return resolve(process.argv[i + 1]);
-}
-
-function walk(directory: string): string[] {
- if (!existsSync(directory)) return [];
- return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
- const full = join(directory, entry.name);
- return entry.isDirectory() ? walk(full) : entry.isFile() ? [full] : [];
- });
-}
-
-async function sha256File(file: string): Promise<string> {
- const hash = createHash("sha256");
- for await (const chunk of createReadStream(file)) hash.update(chunk);
- return hash.digest("hex");
-}
-
-async function inlineImage(occurrence: Json, sourceFiles: Json[]): Promise<Buffer> {
- const source = sourceFiles.find((entry) => basename(entry.path) === occurrence.rolloutFile);
- if (!source) throw new Error(`missing rollout source for ${occurrence.assetId}`);
- let number = 0;
- const lines = createInterface({ input: createReadStream(source.path, { encoding: "utf8" }), crlfDelay: Infinity });
- for await (const line of lines) {
- if (++number !== occurrence.line) continue;
- const item = JSON.parse(line).payload;
- const parts = Array.isArray(item.content) ? item.content : item.output;
- const image = parts?.[occurrence.contentIndex];
- const match = /^data:[^;,]+;base64,(.+)$/s.exec(image?.image_url ?? image?.url ?? "");
- if (!match) throw new Error(`inline image missing for ${occurrence.assetId}`);
- const bytes = Buffer.from(match[1], "base64");
- if (createHash("sha256").update(bytes).digest("hex") !== occurrence.byteSha256) {
- throw new Error(`inline image hash changed for ${occurrence.assetId}`);
- }
- lines.close();
- return bytes;
- }
- throw new Error(`rollout line missing for ${occurrence.assetId}`);
-}
-
-function resizedSimilarity(source: DecodedPng, target: DecodedPng): number {
- let difference = 0;
- const sourcePixels = source.pixels;
- const targetPixels = target.pixels;
- for (let y = 0; y < target.height; y++) {
- const sy = Math.max(0, Math.min(source.height - 1, (y + 0.5) * source.height / target.height - 0.5));
- const y0 = Math.floor(sy), y1 = Math.min(source.height - 1, y0 + 1), fy = sy - y0;
- for (let x = 0; x < target.width; x++) {
- const sx = Math.max(0, Math.min(source.width - 1, (x + 0.5) * source.width / target.width - 0.5));
- const x0 = Math.floor(sx), x1 = Math.min(source.width - 1, x0 + 1), fx = sx - x0;
- const dest = (y * target.width + x) * 4;
- for (let channel = 0; channel < 3; channel++) {
- const a = sourcePixels[(y0 * source.width + x0) * 4 + channel];
- const b = sourcePixels[(y0 * source.width + x1) * 4 + channel];
- const c = sourcePixels[(y1 * source.width + x0) * 4 + channel];
- const d = sourcePixels[(y1 * source.width + x1) * 4 + channel];
- const interpolated = (a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy;
- difference += Math.abs(interpolated - targetPixels[dest + channel]);
- }
- }
- }
- return 1 - difference / (target.width * target.height * 3 * 255);
-}
-
-async function main(): Promise<void> {
- const project = argument("--project");
- const generated = argument("--generated");
- const inventory: Json = JSON.parse(readFileSync(join(localRoot, "assets.json"), "utf8"));
- const candidateMap = new Map<string, { path: string; sources: string[] }>();
- for (const [source, files] of [
- ["project", walk(project)],
- ["generated_images", walk(generated)],
- ["known_path", inventory.occurrences.map((item: Json) => item.knownLocalPath).filter(Boolean)],
- ] as Array<[string, string[]]>) {
- for (const file of files) {
- if (!existsSync(file) || !/\.(png|jpg|jpeg|webp)$/i.test(extname(file))) continue;
- const key = resolve(file).toLowerCase();
- let candidate = candidateMap.get(key);
- if (!candidate) {
- candidate = { path: resolve(file), sources: [] };
- candidateMap.set(key, candidate);
- }
- if (!candidate.sources.includes(source)) candidate.sources.push(source);
- }
- }
-
- const candidates = [];
- for (const candidate of candidateMap.values()) {
- candidates.push({ ...candidate, bytes: statSync(candidate.path).size, byteSha256: await sha256File(candidate.path) });
- }
- const matches = [];
- const realFileHashesBefore = new Map<string, string>();
- mkdirSync(join(localRoot, "cache"), { recursive: true });
- for (const asset of inventory.assets) {
- const first: Json = inventory.occurrences.find((item: Json) => item.assetId === asset.assetId);
- const exact = candidates.filter((candidate) => asset.byteHashes.includes(candidate.byteSha256));
- const preferred = exact.find((candidate) => candidate.sources.includes("project"))
- ?? exact.find((candidate) => candidate.sources.includes("generated_images"))
- ?? exact[0];
- const record: Json = { assetId: asset.assetId, exactMatches: exact, attachmentPath: null, attachmentKind: null, resizedCandidate: null };
- if (preferred) {
- record.attachmentPath = preferred.path;
- record.attachmentKind = "exact_local_file";
- realFileHashesBefore.set(preferred.path, preferred.byteSha256);
- } else {
- const inline = await inlineImage(first, inventory.sourceFiles);
- const cachePath = join(localRoot, "cache", `${asset.assetId}.png`);
- if (existsSync(cachePath)) {
- if (await sha256File(cachePath) !== first.byteSha256) throw new Error(`existing cache differs for ${asset.assetId}`);
- } else {
- writeFileSync(cachePath, inline, { flag: "wx" });
- }
- record.attachmentPath = cachePath;
- record.attachmentKind = "exact_inline_cache";
- const known = candidates.find((candidate) => candidate.path.toLowerCase() === resolve(first.knownLocalPath ?? "").toLowerCase());
- if (known?.path.toLowerCase().endsWith(".png")) {
- const source = decodePng(readFileSync(known.path));
- const target = decodePng(inline);
- const similarity = resizedSimilarity(source, target);
- record.resizedCandidate = {
- path: known.path,
- sourceDimensions: [source.width, source.height],
- targetDimensions: [target.width, target.height],
- similarity: Number(similarity.toFixed(6)),
- status: "待确认",
- };
- realFileHashesBefore.set(known.path, known.byteSha256);
- }
- }
- matches.push(record);
- }
- const realFilesUnchanged = [];
- for (const [file, beforeSha256] of realFileHashesBefore) {
- const afterSha256 = await sha256File(file);
- realFilesUnchanged.push({ path: file, beforeSha256, afterSha256, unchanged: beforeSha256 === afterSha256 });
- }
- const report = {
- createdAt: new Date().toISOString(),
- candidateFilesScanned: candidates.length,
- exactLocalFiles: matches.filter((item) => item.attachmentKind === "exact_local_file").length,
- exactInlineCaches: matches.filter((item) => item.attachmentKind === "exact_inline_cache").length,
- resizedCandidatesPending: matches.filter((item) => item.resizedCandidate).length,
- realFilesUnchanged,
- allRealFilesUnchanged: realFilesUnchanged.every((item) => item.unchanged),
- matches,
- };
- writeFileSync(join(localRoot, "matches.json"), JSON.stringify(report, null, 2));
- const rows = matches.map((item) => `| ${item.assetId} | ${item.attachmentKind} | ${item.attachmentPath} | ${item.exactMatches.length} | ${item.resizedCandidate ? `${item.resizedCandidate.similarity}(待确认)` : "—"} |`);
- writeFileSync(join(localRoot, "matches.md"), [
- "# 阶段 0 磁盘素材匹配(仅本机)", "",
- `候选文件:${candidates.length};精确原件:${report.exactLocalFiles};内联缓存:${report.exactInlineCaches};缩放候选:${report.resizedCandidatesPending};真实文件哈希不变:${report.allRealFilesUnchanged}`, "",
- "| 素材 | 可用附件来源 | 路径 | 精确副本数 | 缩放相似度 |",
- "| --- | --- | --- | ---: | --- |", ...rows, "",
- ].join("\n"));
- console.log(JSON.stringify({ candidateFilesScanned: report.candidateFilesScanned, exactLocalFiles: report.exactLocalFiles, exactInlineCaches: report.exactInlineCaches, resizedCandidatesPending: report.resizedCandidatesPending, allRealFilesUnchanged: report.allRealFilesUnchanged }));
-}
-
-await main();
diff --git a/spike/src/mcp-probe.ts b/spike/src/mcp-probe.ts
deleted file mode 100644
index 6e7ef02..0000000
--- a/spike/src/mcp-probe.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-// Purpose: T9b — a minimal stdio MCP server with one `ping` tool that records what Codex sends in tools/call,
-// including `_meta`, so we can see whether a local MCP server learns which thread called it.
-// Input: MCP JSON-RPC over stdio (newline-delimited); CAM_PROBE_LOG env var names the output file.
-// Output: one JSON line per tools/call appended to that file (local only).
-
-import { appendFileSync } from "node:fs";
-import { createInterface } from "node:readline";
-
-const log = process.env.CAM_PROBE_LOG;
-const send = (message: Record<string, unknown>) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);
-
-createInterface({ input: process.stdin, crlfDelay: Infinity }).on("line", (line) => {
- if (!line.trim()) return;
- const message = JSON.parse(line);
- if (message.id === undefined) return;
- switch (message.method) {
- case "initialize":
- send({ id: message.id, result: { protocolVersion: message.params?.protocolVersion ?? "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "cam_probe", version: "0.0.0" } } });
- break;
- case "tools/list":
- send({ id: message.id, result: { tools: [{ name: "ping", description: "Phase 0 probe: returns pong.", inputSchema: { type: "object", properties: {} } }] } });
- break;
- case "tools/call":
- if (log) appendFileSync(log, `${JSON.stringify({ at: new Date().toISOString(), params: message.params })}\n`);
- send({ id: message.id, result: { content: [{ type: "text", text: "pong" }] } });
- break;
- default:
- send({ id: message.id, error: { code: -32601, message: `unsupported: ${message.method}` } });
- }
-});
diff --git a/spike/src/migrate-data.test.ts b/spike/src/migrate-data.test.ts
index 788631d..fb3dab8 100644
--- a/spike/src/migrate-data.test.ts
+++ b/spike/src/migrate-data.test.ts
@@ -8,7 +8,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, statSync, utimesSync,
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import test from "node:test";
-import { migrateWindowsData, oldWindowsFolders } from "../../plugin/src/migrate-data.ts";
+import { migrateWindowsData, oldWindowsFolders } from "../../plugin/src/core/migrate-data.ts";
const NAME = "codex-attachment-manager";
diff --git a/spike/src/migrate.test.ts b/spike/src/migrate.test.ts
deleted file mode 100644
index 451afdb..0000000
--- a/spike/src/migrate.test.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-// Purpose: check the migration rules from docs/spec.md on synthetic turns (no real session data).
-// Input: synthetic UI-level turns; output: Node test assertions only.
-
-import assert from "node:assert/strict";
-import test from "node:test";
-import { buildMigration, redactPaths, type AssetInfo } from "./migrate.ts";
-
-const assets: Record<string, AssetInfo> = {
- "C:\\work\\shots\\bridge.png": { assetId: "IMG-001", name: "bridge.png", width: 1672, height: 941, bytes: 2_336_942 },
- "C:\\work\\shots\\lake.png": { assetId: "IMG-002", name: "lake.png", width: 1672, height: 941, bytes: 2_869_595 },
-};
-const resolve = (path: string) => assets[path] ?? null;
-
-const turns = [
- {
- status: "completed",
- items: [
- { type: "userMessage", content: [{ type: "text", text: "参考这张桥的照片" }, { type: "localImage", path: "C:\\work\\shots\\bridge.png" }] },
- { type: "reasoning", summary: ["secret chain of thought"] },
- { type: "commandExecution", command: "rg -n title 'C:\\work\\shots\\notes.md'", exitCode: 0 },
- { type: "agentMessage", text: "好的,我看过了。" },
- ],
- },
- {
- status: "failed",
- items: [
- { type: "userMessage", content: [{ type: "text", text: "再看看湖" }, { type: "localImage", path: "C:\\work\\shots\\lake.png" }] },
- { type: "imageView", path: "C:\\work\\shots\\bridge.png" },
- ],
- },
-];
-
-const texts = (items: Array<Record<string, any>>) => items.map((item) => item.content[0].text as string);
-
-test("omitted, repeated and attached images follow the placeholder rules", () => {
- const migration = buildMigration(turns, resolve, { sourceName: "测试任务", attachments: new Map([["IMG-002", 1]]) });
- const all = texts(migration.items);
- const bridge = all.find((text) => text.includes("[素材 IMG-001"))!;
- assert.match(bridge, /bridge\.png/);
- assert.match(bridge, /不能据此判断画面细节/);
- assert.match(bridge, /需要 IMG-001/);
- const lake = all.find((text) => text.includes("[素材 IMG-002"))!;
- assert.match(lake, /作为附件 1 提供/);
- assert.ok(all.some((text) => text.includes("与 IMG-001 为同一素材")), "repeat view is a short reference");
- assert.equal(migration.imageOccurrences, 3);
- assert.equal(migration.unresolvedImages, 0);
-});
-
-test("history keeps text, drops reasoning, records tools and failed turns", () => {
- const migration = buildMigration(turns, resolve, { sourceName: "测试任务", attachments: new Map() });
- const [index, ...history] = migration.items;
- assert.equal(index.role, "developer");
- assert.match(index.content[0].text, /IMG-001|bridge\.png/);
- assert.deepEqual(history.map((item) => item.role), ["user", "assistant", "assistant", "user", "assistant", "assistant"]);
- const all = texts(migration.items).join("\n");
- assert.doesNotMatch(all, /secret chain of thought/);
- assert.match(all, /执行命令(退出码 0):rg -n title 'notes\.md'/);
- assert.match(all, /\[此轮未完成:失败\]/);
- assert.doesNotMatch(all, /C:\\work/, "no absolute path reaches the model");
-});
-
-test("redactPaths keeps only file names, including quoted paths with spaces", () => {
- assert.equal(redactPaths("rg -n x 'C:\\my docs\\a b\\c.md'"), "rg -n x 'c.md'");
- assert.equal(redactPaths('view "C:\\my docs\\shot 1.png" now'), 'view "shot 1.png" now');
- assert.equal(redactPaths("type C:\\work\\x.txt"), "type x.txt");
- assert.equal(redactPaths("cat /home/me/notes/x.md"), "cat x.md");
-});
-
-test("file changes under folders with spaces record only the file name", () => {
- const migration = buildMigration(
- [{ status: "completed", items: [{ type: "userMessage", content: [{ type: "text", text: "改一下" }] }, { type: "fileChange", changes: [{ path: "C:\\my docs\\Go To\\spec.md" }] }] }],
- resolve,
- { sourceName: "测试任务", attachments: new Map() },
- );
- const all = texts(migration.items).join("\n");
- assert.match(all, /修改文件:spec\.md/);
- assert.doesNotMatch(all, /my docs|Go To/);
-});
diff --git a/spike/src/migrate.ts b/spike/src/migrate.ts
deleted file mode 100644
index 16166f3..0000000
--- a/spike/src/migrate.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-// Purpose: turn a source thread's UI-level turns (app-server thread/turns/list) into the raw Responses items
-// injected into a rebuilt thread: text is kept, images become placeholders, tool calls become one-line records.
-// Input: turns, an image resolver, and the selection. Output: items plus bookkeeping (pure, no I/O).
-
-type Json = Record<string, any>;
-export type AssetInfo = { assetId: string; name: string; width: number | null; height: number | null; bytes: number };
-export type ResolveImage = (pathOrUrl: string) => AssetInfo | null;
-export type MigrationOptions = {
- sourceName: string;
- // Asset id -> attachment number in the first new turn; assets not listed are omitted.
- attachments: Map<string, number>;
-};
-export type FirstSeen = { asset: AssetInfo; turn: number; source: string };
-export type Migration = { items: Json[]; firstSeen: FirstSeen[]; imageOccurrences: number; unresolvedImages: number };
-
-const message = (role: "user" | "assistant" | "developer", text: string): Json => ({
- type: "message",
- role,
- content: [{ type: role === "assistant" ? "output_text" : "input_text", text }],
-});
-
-const clip = (text: string, max: number) => (text.length > max ? `${text.slice(0, max)}…` : text);
-const megabytes = (bytes: number) => (bytes / 1_048_576).toFixed(1);
-const dimensions = (asset: AssetInfo) => (asset.width && asset.height ? `${asset.width}×${asset.height}` : "尺寸未知");
-
-export const baseName = (path: string) => path.split(/[\\/]/).filter(Boolean).pop() ?? path;
-
-// Tool records keep file names but never absolute paths, so the model is not pointed at omitted files.
-// Quoted paths may contain spaces and are replaced whole; unquoted paths end at whitespace.
-export function redactPaths(text: string): string {
- return text
- .replace(/(['"])([A-Za-z]:\\[^'"]*|\/[^'"]*\/[^'"]*)\1/g, (_match, quote: string, path: string) => `${quote}${baseName(path)}${quote}`)
- .replace(/[A-Za-z]:\\[^\s'"]+/g, (path) => baseName(path))
- .replace(/(?<![\w.])\/(?:[^/\s'"]+\/)+[^/\s'"]+/g, (path) => baseName(path));
-}
-
-function placeholder(asset: AssetInfo, turn: number, source: string, note: string, attachment: number | undefined): string {
- const header = `[素材 ${asset.assetId}|图片|${asset.name}|${dimensions(asset)}|${megabytes(asset.bytes)} MB|原任务第 ${turn} 轮${source}]`;
- const status = attachment !== undefined
- ? `状态:已在新任务中作为附件 ${attachment} 提供。`
- : `状态:本轮未提供图像内容(为控制上下文而省略),不能据此判断画面细节。如需查看,请回复“需要 ${asset.assetId}”,用户勾选后会在下一轮作为附件提供。`;
- return `${header}\n来源说明:${note}\n${status}`;
-}
-
-function toolRecord(item: Json, imageText: (path: string) => string): string | null {
- switch (item.type) {
- case "reasoning": return null;
- case "commandExecution": return `执行命令(退出码 ${item.exitCode ?? "未知"}):${clip(redactPaths(String(item.command ?? "")), 80)}`;
- case "webSearch": return `网页搜索:${clip(String(item.query ?? ""), 60)}`;
- case "fileChange": return `修改文件:${(item.changes ?? []).map((change: Json) => baseName(String(change.path ?? ""))).join("、")}`;
- case "mcpToolCall": return `调用工具 ${item.server}.${item.tool}`;
- case "imageView": return `用看图工具查看了图片 ${imageText(item.path)}`;
- default: return `${item.type}`;
- }
-}
-
-export function buildMigration(turns: Json[], resolve: ResolveImage, options: MigrationOptions): Migration {
- const history: Json[] = [];
- const firstSeen: FirstSeen[] = [];
- const seen = new Set<string>();
- let imageOccurrences = 0;
- let unresolvedImages = 0;
-
- const imageText = (pathOrUrl: string, turn: number, source: string, note: string): string => {
- imageOccurrences++;
- const asset = resolve(pathOrUrl);
- if (!asset) {
- unresolvedImages++;
- return `[记录 #${imageOccurrences}:一张未能识别的图片(${source}),本轮未提供图像内容,不能据此判断画面细节]`;
- }
- if (seen.has(asset.assetId)) return `[记录 #${imageOccurrences}:与 ${asset.assetId} 为同一素材,此处不重复提供]`;
- seen.add(asset.assetId);
- firstSeen.push({ asset, turn, source });
- return placeholder(asset, turn, source, note, options.attachments.get(asset.assetId));
- };
-
- for (const [index, turn] of turns.entries()) {
- const number = index + 1;
- let records: string[] = [];
- const flush = () => {
- if (records.length) history.push(message("assistant", `[工具记录] ${records.join(";")}`));
- records = [];
- };
- for (const item of turn.items ?? []) {
- if (item.type === "userMessage") {
- flush();
- const text = (item.content ?? []).filter((part: Json) => part.type === "text").map((part: Json) => part.text).join("\n");
- const parts = [`【原任务第 ${number} 轮】`];
- for (const part of item.content ?? []) {
- if (part.type === "text") parts.push(part.text);
- else if (part.type === "localImage" || part.type === "image") {
- parts.push(imageText(part.path ?? part.url, number, "用户上传", `用户随附的话:“${clip(text.replace(/\s+/g, " ").trim(), 60)}”`));
- } else parts.push(`[${part.type}]`);
- }
- history.push(message("user", parts.join("\n")));
- } else if (item.type === "agentMessage") {
- flush();
- history.push(message("assistant", item.text ?? ""));
- } else {
- const record = toolRecord(item, (path) => imageText(path, number, "看图工具查看", "模型用看图工具查看"));
- if (record) records.push(record);
- }
- }
- flush();
- if (turn.status && turn.status !== "completed") {
- const label = turn.status === "failed" ? "失败" : turn.status === "interrupted" ? "被中断" : turn.status;
- history.push(message("assistant", `[此轮未完成:${label}]`));
- }
- }
-
- const table = firstSeen.map(({ asset, turn, source }) => {
- const attachment = options.attachments.get(asset.assetId);
- const status = attachment !== undefined ? `新任务第 1 轮附件 ${attachment}` : "未提供";
- return `- ${asset.assetId}|${asset.name}|${dimensions(asset)}|${megabytes(asset.bytes)} MB|首次出现:原任务第 ${turn} 轮(${source})|${status}`;
- });
- const index = message("developer", [
- "[Codex 附件管理器 · 重建说明]",
- `这个任务由 Codex 附件管理器从原任务「${options.sourceName}」重建。原任务的历史图片以内联数据随每次请求重复发送,请求过大后无法继续。`,
- "下面是原任务的对话文字;图片不直接附带,用素材编号和占位符表示;工具调用只保留一行记录。",
- "规则:",
- "1. 标为“未提供”的素材,你没有看到它的画面,不能据此描述或判断任何画面细节。",
- "2. 需要查看某个素材时,请直接回复“需要 IMG-xxx”,由用户勾选后在下一轮作为附件提供。不要用工具自行读取这些图片文件。",
- "3. 用户附带素材时会注明“附件 k = IMG-xxx”,此后你就能看到该素材。",
- "素材表:",
- ...table,
- ].join("\n"));
-
- return { items: [index, ...history], firstSeen, imageOccurrences, unresolvedImages };
-}
diff --git a/spike/src/notes.test.ts b/spike/src/notes.test.ts
index e586d94..bc81a16 100644
--- a/spike/src/notes.test.ts
+++ b/spike/src/notes.test.ts
@@ -7,13 +7,13 @@ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { buildClaudeIndex } from "../../plugin/src/claude-index.ts";
+import { buildClaudeIndex } from "../../plugin/src/adapters/claude/claude-index.ts";
import { rewriteMessages } from "../../plugin/src/claude-rewrite.ts";
import { findImages, type ImageRef } from "../../plugin/src/images.ts";
-import { addNotes, notesBy, sceneOf, type Notes } from "../../plugin/src/notes.ts";
+import { addNotes, notesBy, sceneOf, type Notes } from "../../plugin/src/core/notes.ts";
import { autoPlaceholder, clip, featureNote, plainPlaceholder, rewriteItems, type Described } from "../../plugin/src/rewrite.ts";
-import { buildIndex, writesNotes, type Parsed } from "../../plugin/src/thread-index.ts";
-import { claudeTurnTexts, loadPanelState, panelStateOf } from "../../plugin/src/panel-state.ts";
+import { buildIndex, writesNotes, type Parsed } from "../../plugin/src/adapters/codex/thread-index.ts";
+import { claudeTurnTexts, loadPanelState, panelStateOf } from "../../plugin/src/panel/panel-state.ts";
import { image, pngA, pngB, text, transcript } from "./claude-fixtures.ts";
import { assistant, line, sampleSessions, THREAD, turn } from "./testfixtures.ts";
import { png } from "./testkit.ts";
diff --git a/spike/src/p1-selftest.ts b/spike/src/p1-selftest.ts
deleted file mode 100644
index 78e9540..0000000
--- a/spike/src/p1-selftest.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-// Purpose: P1-3 — run text, attached image, image generation and image edit through our own app-server pointed at
-// the local proxy (`-c openai_base_url`, the user's config.toml is not touched), then match the proxy log.
-// Input: [--port 17891] [--host localhost] [--desktop-env] [--only-text] [--label name]; the proxy must already be running.
-// --desktop-env drops NO_PROXY so the app-server sees the same proxy environment as the desktop app;
-// --respect-system-proxy turns on features.respect_system_proxy, as the managed config.toml does.
-// Output: local/p1-selftest-<label>.json and a console summary.
-
-import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
-import { dirname, join, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-import zlib from "node:zlib";
-import { AppServer, findBundledCodex } from "./appserver.ts";
-import { TEST_MODEL } from "./testkit.ts";
-
-type Json = Record<string, any>;
-const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
-
-// A synthetic 256×256 RGB gradient, so no user material is sent for the attachment test.
-function testPattern(): Buffer {
- const width = 256;
- const height = 256;
- const raw = Buffer.alloc((width * 3 + 1) * height);
- for (let y = 0; y < height; y++) {
- const row = y * (width * 3 + 1);
- for (let x = 0; x < width; x++) {
- raw[row + 1 + x * 3] = x;
- raw[row + 2 + x * 3] = y;
- raw[row + 3 + x * 3] = 160;
- }
- }
- const chunk = (type: string, data: Buffer) => {
- const length = Buffer.alloc(4);
- length.writeUInt32BE(data.length);
- const crc = Buffer.alloc(4);
- crc.writeUInt32BE(zlib.crc32(Buffer.concat([Buffer.from(type, "ascii"), data])));
- return Buffer.concat([length, Buffer.from(type, "ascii"), data, crc]);
- };
- const header = Buffer.alloc(13);
- header.writeUInt32BE(width, 0);
- header.writeUInt32BE(height, 4);
- header[8] = 8;
- header[9] = 2;
- return Buffer.concat([Buffer.from("89504e470d0a1a0a", "hex"), chunk("IHDR", header), chunk("IDAT", zlib.deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);
-}
-
-async function turn(server: AppServer, threadId: string, input: Json[]): Promise<Json> {
- const started = Date.now();
- const before = server.notifications.length;
- const { turn } = await server.request<{ turn: Json }>("turn/start", { threadId, input, effort: "low" }, 120_000);
- const done = await server.waitFor((n) => n.method === "turn/completed" && n.params.turn?.id === turn.id, 20 * 60_000);
- const mine = server.notifications.slice(before).filter((n) => n.params?.turnId === turn.id || n.params?.turn?.id === turn.id);
- const items = mine.filter((n) => n.method === "item/completed").map((n) => n.params.item);
- return {
- turnId: turn.id,
- status: done.params.turn.status,
- error: done.params.turn.error ?? null,
- ms: Date.now() - started,
- tools: items.filter((item) => !["agentMessage", "reasoning", "userMessage"].includes(item.type)).map((item) => `${item.type}:${item.status ?? ""}`),
- reply: items.filter((item) => item.type === "agentMessage").map((item) => item.text).join(" ").slice(0, 200),
- errors: mine.filter((n) => n.method === "error").map((n) => n.params.error?.message ?? "error"),
- };
-}
-
-async function main(): Promise<void> {
- const option = (name: string, fallback: string) => (process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : fallback);
- const port = Number(option("--port", "17891"));
- const host = option("--host", "localhost");
- const label = option("--label", "default");
- const desktopEnv = process.argv.includes("--desktop-env");
- const onlyText = process.argv.includes("--only-text");
- const workDir = join(localRoot, "p1");
- mkdirSync(join(localRoot, "logs"), { recursive: true });
- mkdirSync(workDir, { recursive: true });
- const pattern = join(workDir, "test-pattern.png");
- writeFileSync(pattern, testPattern());
-
- const startedAt = new Date().toISOString();
- const env = desktopEnv ? { NO_PROXY: undefined, no_proxy: undefined } : {};
- const extra = process.argv.includes("--respect-system-proxy") ? ["-c", "features.respect_system_proxy=true"] : [];
- const server = new AppServer(findBundledCodex(), ["-c", `openai_base_url="http://${host}:${port}/backend-api/codex"`, ...extra], env, join(localRoot, "logs", `p1-selftest-${label}-appserver-${startedAt.replaceAll(":", "-")}.log`));
- const results: Json = {};
- let threadId = "";
- try {
- await server.initialize();
- const started = await server.request<{ thread: Json }>("thread/start", { model: TEST_MODEL, cwd: workDir, approvalPolicy: "never", sandbox: "read-only", ephemeral: true });
- threadId = started.thread.id;
- const text = (value: string) => ({ type: "text", text: value, text_elements: [] });
- results.text = await turn(server, threadId, [text("请只回复“收到”两个字。")]);
- if (onlyText) return;
- results.attachment = await turn(server, threadId, [text("附件里是什么图案?用一句话回答,不需要调用任何工具。"), { type: "localImage", path: pattern }]);
- results.imageGeneration = await turn(server, threadId, [text("请用内置的生图工具生成一张简单的图片:浅蓝色背景,正中间一个黄色圆形。生成 1 张即可。")]);
- results.imageEdit = await turn(server, threadId, [text("请用内置的生图工具修改刚才那张图:把黄色圆形改成红色,其余保持不变。生成 1 张即可。")]);
- } finally {
- await server.stop();
- await summarize(threadId, startedAt, { host, port, desktopEnv, respectSystemProxy: extra.length > 0, onlyText, label }, results);
- }
-}
-
-async function summarize(threadId: string, startedAt: string, options: Json, results: Json): Promise<void> {
- const logFile = join(localRoot, "proxy", `${new Date().toISOString().slice(0, 10)}.jsonl`);
- const entries = readFileSync(logFile, "utf8").trim().split("\n").map((line) => JSON.parse(line)).filter((entry: Json) => entry.at >= startedAt);
- const forThread = entries.filter((entry: Json) => entry.threadId === threadId);
- const summary = Object.values(forThread.reduce((groups: Record<string, Json>, entry: Json) => {
- const key = `${entry.transport} ${entry.method ?? "GET"} ${entry.path} ${entry.status ?? entry.upstreamStatus ?? ""}`;
- groups[key] ??= { request: key, count: 0 };
- groups[key].count++;
- return groups;
- }, {}));
- const report = { createdAt: new Date().toISOString(), options, threadId, results, proxyEntriesInWindow: entries.length, proxyEntriesForThread: forThread.length, summary, otherThreadIds: [...new Set(entries.map((e: Json) => e.threadId).filter((id: string | null) => id && id !== threadId))] };
- writeFileSync(join(localRoot, `p1-selftest-${options.label}.json`), JSON.stringify(report, null, 2));
- console.log(JSON.stringify({ options, results, summary, proxyEntriesInWindow: entries.length, proxyEntriesForThread: forThread.length }, null, 2));
-}
-
-await main();
diff --git a/spike/src/p2-bench.ts b/spike/src/p2-bench.ts
deleted file mode 100644
index 3538b18..0000000
--- a/spike/src/p2-bench.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-// Purpose: P2 — measure on this machine how long content fingerprints, the thread index and a full request rewrite
-// take for a real thread. The rollout is only read; nothing but timings and counts is written.
-// Input: --thread <id> [--label name]. Output: local/p2/bench-<label>.json and a console summary.
-
-import { createHash } from "node:crypto";
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { dirname, join, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-import zlib from "node:zlib";
-import { codexHome } from "../../plugin/src/codexconfig.ts";
-import { findImages } from "../../plugin/src/images.ts";
-import { decodePng } from "../../plugin/src/png.ts";
-import { hasUnsafeInteger, rewriteBody } from "../../plugin/src/proxy.ts";
-import { rewriteItems } from "../../plugin/src/rewrite.ts";
-import { writeSelection } from "../../plugin/src/selection.ts";
-import { imageData, loadThreadIndex, readThreadHistory } from "../../plugin/src/thread-index.ts";
-
-type Json = Record<string, any>;
-const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
-const round = (ms: number) => Math.round(ms * 10) / 10;
-
-function time<T>(fn: () => T): [T, number] {
- const started = performance.now();
- const result = fn();
- return [result, round(performance.now() - started)];
-}
-
-function main(): void {
- const option = (name: string, fallback?: string) => (process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : fallback);
- const threadId = option("--thread");
- if (!threadId) throw new Error("usage: p2-bench.ts --thread <id> [--label name]");
- const label = option("--label", "default")!;
- const sessions = join(codexHome(), "sessions");
-
- const [index, indexColdMs] = time(() => loadThreadIndex(sessions, threadId));
- const [, indexWarmMs] = time(() => loadThreadIndex(sessions, threadId));
- const items: Json[] = readThreadHistory(sessions, threadId).filter((record) => record.type === "response_item").map((record) => record.payload);
-
- // Fresh per-image costs, outside every cache.
- const perImage = findImages(items).map((ref) => {
- const value = imageData(items, ref) ?? "";
- const [, sha256Ms] = time(() => createHash("sha256").update(value).digest("hex"));
- let pixelMs: number | null = null;
- if (ref.mime === "image/png") [, pixelMs] = time(() => decodePng(Buffer.from(value, "base64")).pixelSha256);
- return { size: ref.width && ref.height ? `${ref.width}x${ref.height}` : null, mb: round(ref.base64Chars / 1e6), sha256Ms, pixelMs };
- });
-
- // A request carrying the whole history, the way Codex sends it over HTTP, with the first image unchecked.
- const text = JSON.stringify({ model: "bench", input: items, stream: true });
- const [original, codexCompressMs] = time(() => zlib.zstdCompressSync(Buffer.from(text)));
- const selections = mkdtempSync(join(tmpdir(), "cam-bench-"));
- const first = index.images.find((image) => image.replaceable)!;
- writeSelection({ threadId, unchecked: { [first.key]: { id: first.id, at: new Date().toISOString() } } }, selections);
- const steps: Json = {};
- const [decoded, decompressMs] = time(() => zlib.zstdDecompressSync(original));
- steps.decompressMs = decompressMs;
- const [json, parseMs] = time(() => JSON.parse(decoded.toString("utf8")));
- steps.parseMs = parseMs;
- [, steps.unsafeIntegerScanMs] = time(() => hasUnsafeInteger(text));
- [, steps.findImagesMs] = time(() => findImages(json.input));
- const byKey = index.byKey;
- const [rewritten, replaceMs] = time(() => rewriteItems(json.input, (ref) => byKey.get(ref.key), new Set([first.key]), (ref) => byKey.get(ref.key)?.pixelSha256 ?? null));
- steps.replaceMs = replaceMs;
- json.input = rewritten.items;
- const [next, stringifyMs] = time(() => Buffer.from(JSON.stringify(json)));
- steps.stringifyMs = stringifyMs;
- [, steps.compressMs] = time(() => zlib.zstdCompressSync(next));
- const [out, rewriteBodyMs] = time(() => rewriteBody(original, "zstd", threadId, sessions, selections));
- rmSync(selections, { recursive: true, force: true });
-
- const result = {
- createdAt: new Date().toISOString(),
- images: index.images.length,
- distinctContents: new Set(index.images.map((image) => image.contentId)).size,
- indexColdMs,
- indexWarmMs,
- perImage,
- request: { decodedMB: round(text.length / 1e6), zstdMB: round(original.length / 1e6), codexCompressMs, afterZstdMB: round(out.body.length / 1e6), replaced: out.report.replaced?.map((r: Json) => r.id), skipped: out.report.skipped ?? null },
- rewriteSteps: steps,
- rewriteBodyMs,
- };
- mkdirSync(join(localRoot, "p2"), { recursive: true });
- writeFileSync(join(localRoot, "p2", `bench-${label}.json`), JSON.stringify(result, null, 2));
- console.log(JSON.stringify(result, null, 2));
-}
-
-main();
diff --git a/spike/src/p2-capture.ts b/spike/src/p2-capture.ts
deleted file mode 100644
index 0d16157..0000000
--- a/spike/src/p2-capture.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-// Purpose: P2-1 — produce Responses requests that contain every kind of image (uploads incl. a renamed byte copy,
-// a view_image result, a generated image) in a synthetic test thread, so the proxy's --dump-requests output shows
-// where images sit in the request. The proxy must already run with --force-http --dump-requests.
-// Input: [--port 17891] [--label name]. Output: local/p2/capture-<label>.json; request dumps come from the proxy.
-
-import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
-import { dirname, join, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-import { AppServer, findBundledCodex } from "./appserver.ts";
-import { runTurn, TEST_MODEL, testImages, text } from "./testkit.ts";
-
-type Json = Record<string, any>;
-const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
-
-async function main(): Promise<void> {
- const option = (name: string, fallback: string) => (process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : fallback);
- const port = Number(option("--port", "17891"));
- const label = option("--label", "default");
- const workDir = join(localRoot, "p2", "work");
- mkdirSync(workDir, { recursive: true });
- mkdirSync(join(localRoot, "logs"), { recursive: true });
- const file = (name: string) => join(workDir, name);
- writeFileSync(file("a.png"), testImages.redSquare());
- writeFileSync(file("b.png"), testImages.blueCircle());
- copyFileSync(file("b.png"), file("b-copy.png"));
- writeFileSync(file("c.png"), testImages.whiteTriangle());
-
- const startedAt = new Date().toISOString();
- const server = new AppServer(findBundledCodex(), ["-c", `openai_base_url="http://localhost:${port}/backend-api/codex"`, "-c", "features.respect_system_proxy=true"], {}, join(localRoot, "logs", `p2-capture-${label}-${startedAt.replaceAll(":", "-")}.log`));
- const result: Json = { createdAt: startedAt, label, turns: {} };
- try {
- await server.initialize();
- const { thread } = await server.request<{ thread: Json }>("thread/start", { model: TEST_MODEL, cwd: workDir, approvalPolicy: "never", sandbox: "read-only", ephemeral: false });
- result.threadId = thread.id;
- await server.request("thread/name/set", { threadId: thread.id, name: `[CAM测试] P2-1 请求结构 ${label}` });
- result.turns.upload = await runTurn(server, thread.id, [text("这是三张测试图,先不用描述,只回复“收到”。"), ...["a.png", "b.png", "b-copy.png"].map((name) => ({ type: "localImage", path: file(name) }))]);
- result.turns.viewImage = await runTurn(server, thread.id, [text(`请用 view_image 工具查看这个文件:${file("c.png")},然后用一句话说出它的背景色和主要形状。`)]);
- result.turns.generate = await runTurn(server, thread.id, [text("请用内置的生图工具生成一张简单的图片:浅绿色背景,正中间一个橙色正方形。生成 1 张即可。")]);
- result.turns.last = await runTurn(server, thread.id, [text("请只回复“好的”。")]);
- } finally {
- await server.stop();
- writeFileSync(join(localRoot, "p2", `capture-${label}.json`), JSON.stringify(result, null, 2));
- console.log(JSON.stringify(result, (key, value) => (key === "reply" && typeof value === "string" ? value.slice(0, 160) : value), 2));
- }
-}
-
-await main();
diff --git a/spike/src/p2-selftest.ts b/spike/src/p2-selftest.ts
deleted file mode 100644
index cf1d43b..0000000
--- a/spike/src/p2-selftest.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-// Purpose: P2-5 — end-to-end check of rewriting in one thread with our own app-server in the desktop's environment
-// (NO_PROXY removed, respect_system_proxy on, localhost base URL; config.toml untouched):
-// upload four synthetic images (one a renamed byte copy, one ~3 MB of noise) → uncheck the original, the copy and the
-// large one → ask about the first two → re-check the original → ask again → check everything → one more turn.
-// The proxy must already run (no flags).
-// Input: [--port 17891] [--label name]. Output: local/p2/selftest-<label>.json (synthetic test thread only).
-
-import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
-import { dirname, join, resolve } from "node:path";
-import { setTimeout as sleep } from "node:timers/promises";
-import { fileURLToPath } from "node:url";
-import { AppServer, findBundledCodex } from "./appserver.ts";
-import { codexHome } from "../../plugin/src/codexconfig.ts";
-import { readSelection, writeSelection } from "../../plugin/src/selection.ts";
-import { runTurn, TEST_MODEL, testImages, text } from "./testkit.ts";
-import { loadThreadIndex } from "../../plugin/src/thread-index.ts";
-
-type Json = Record<string, any>;
-const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
-
-function setChecked(threadId: string, keys: Record<string, string>, uncheck: string[]): void {
- writeSelection({ threadId, unchecked: Object.fromEntries(uncheck.map((id) => [keys[id], { id, at: new Date().toISOString() }])), auto: false });
-}
-
-async function main(): Promise<void> {
- const option = (name: string, fallback: string) => (process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : fallback);
- const port = Number(option("--port", "17891"));
- const label = option("--label", "default");
- const workDir = join(localRoot, "p2", "work");
- mkdirSync(workDir, { recursive: true });
- const file = (name: string) => join(workDir, name);
- writeFileSync(file("a.png"), testImages.redSquare());
- writeFileSync(file("b.png"), testImages.blueCircle());
- copyFileSync(file("b.png"), file("b-copy.png"));
- writeFileSync(file("noise.png"), testImages.noise());
-
- const startedAt = new Date().toISOString();
- const server = new AppServer(findBundledCodex(), ["-c", `openai_base_url="http://localhost:${port}/backend-api/codex"`, "-c", "features.respect_system_proxy=true"], { NO_PROXY: undefined, no_proxy: undefined }, join(localRoot, "logs", `p2-selftest-${label}-${startedAt.replaceAll(":", "-")}.log`));
- const result: Json = { createdAt: startedAt, label, turns: {} };
- let threadId = "";
- try {
- await server.initialize();
- const { thread } = await server.request<{ thread: Json }>("thread/start", { model: TEST_MODEL, cwd: workDir, approvalPolicy: "never", sandbox: "read-only", ephemeral: false });
- threadId = thread.id;
- result.threadId = threadId;
- await server.request("thread/name/set", { threadId, name: `[CAM测试] P2 改写自测 ${label}` });
-
- result.turns.upload = await runTurn(server, threadId, [text("这是四张测试图,先不用描述,只回复“收到”。"), ...["a.png", "b.png", "b-copy.png", "noise.png"].map((name) => ({ type: "localImage", path: file(name) }))]);
- const index = loadThreadIndex(join(codexHome(), "sessions"), threadId);
- result.index = index.images.map((image) => ({ id: image.id, name: image.name, kind: image.kind, turn: image.turn, contentHash: image.contentId.slice(0, 16) }));
- const keys = Object.fromEntries(index.images.map((image) => [image.id, image.key]));
-
- setChecked(threadId, keys, ["IMG-001", "IMG-003", "IMG-004"]);
- result.selectionAfterUncheck = Object.values(readSelection(threadId).unchecked).map((entry) => entry.id);
- await sleep(3000);
- const question = "请分别回答:1)第一张图 a.png 是什么背景色、什么主要形状,角落里有什么小标记,在哪个角?2)第三张图 b-copy.png 呢?不要调用任何工具。";
- result.turns.unchecked = await runTurn(server, threadId, [text(question)]);
-
- setChecked(threadId, keys, ["IMG-003", "IMG-004"]);
- result.turns.rechecked = await runTurn(server, threadId, [text("我重新提供了 a.png。请再回答一次第 1 个问题:它是什么背景色、什么主要形状,角落里有什么小标记,在哪个角?不要调用任何工具。")]);
-
- setChecked(threadId, keys, []);
- result.turns.allChecked = await runTurn(server, threadId, [text("请只回复“好的”。")]);
-
- const read = await server.request<{ thread: Json }>("thread/read", { threadId, includeTurns: true });
- result.threadTurns = read.thread.turns?.length ?? null;
- } finally {
- await server.stop();
- }
-
- const entries: Json[] = readFileSync(join(localRoot, "proxy", `${new Date().toISOString().slice(0, 10)}.jsonl`), "utf8")
- .trim().split("\n").map((line) => JSON.parse(line)).filter((entry) => entry.at >= startedAt && entry.threadId === threadId);
- const turnIds = Object.fromEntries(Object.entries(result.turns as Record<string, Json>).map(([name, turn]) => [turn.turnId, name]));
- result.proxy = entries.map((entry) => ({
- turn: turnIds[entry.turnId] ?? entry.turnId,
- transport: entry.transport,
- what: entry.declined ? `declined ${entry.declined}` : entry.transport === "websocket" ? `${entry.upstreamStatus} closedForSelection=${entry.closedForSelection}` : `${entry.method} ${entry.path.split("/").pop()} ${entry.status}`,
- rewrite: entry.rewrite ? { replaced: entry.rewrite.replaced?.map((r: Json) => `${r.id}:${r.mode}${r.sameAs ? `->${r.sameAs}` : ""}`), sent: entry.rewrite.sentImageHashes, skipped: entry.rewrite.skipped, decoded: [entry.rewrite.decodedBefore, entry.rewrite.decodedAfter], encoded: [entry.rewrite.encodedBefore, entry.rewrite.encodedAfter] } : null,
- requestBytes: entry.requestBytes ?? entry.upBytes,
- }));
-
- const hash = (id: string) => (result.index as Json[]).find((image) => image.id === id)?.contentHash;
- const posts = (turn: string) => (result.proxy as Json[]).filter((entry) => entry.turn === turn && entry.transport === "http" && /responses/.test(entry.what));
- const turn2 = posts("unchecked");
- const turn3 = posts("rechecked");
- const turn4 = posts("allChecked");
- result.checks = {
- indexFoundCopy: JSON.stringify((result.index as Json[]).map((image) => image.name)) === JSON.stringify(["a.png", "b.png", "b-copy.png", "noise.png"]) && hash("IMG-002") === hash("IMG-003"),
- websocketClosedAfterUncheck: (result.proxy as Json[]).some((entry) => /closedForSelection=true/.test(entry.what)) || !(result.proxy as Json[]).some((entry) => entry.transport === "websocket" && entry.turn === "upload"),
- turn2Rewritten: turn2.length > 0 && turn2.every((entry) => JSON.stringify(entry.rewrite?.replaced) === JSON.stringify(["IMG-001:plain", "IMG-003:duplicate->IMG-002", "IMG-004:plain"]) && !entry.rewrite.sent.includes(hash("IMG-001")) && !entry.rewrite.sent.includes(hash("IMG-004"))),
- turn2Smaller: turn2.length > 0 && turn2.every((entry) => entry.rewrite.encoded[1] < entry.rewrite.encoded[0] - 1_000_000),
- turn2AsksForImage: /IMG-001/.test(result.turns.unchecked.reply),
- turn3SendsImageAgain: turn3.length > 0 && turn3.every((entry) => JSON.stringify(entry.rewrite?.replaced) === JSON.stringify(["IMG-003:duplicate->IMG-002", "IMG-004:plain"]) && entry.rewrite.sent.includes(hash("IMG-001"))),
- turn3SeesImage: /红/.test(result.turns.rechecked.reply) && /黑/.test(result.turns.rechecked.reply),
- turn4PassThrough: turn4.length > 0 && turn4.every((entry) => entry.rewrite === null),
- noErrors: Object.values(result.turns as Record<string, Json>).every((turn) => turn.status === "completed" && !turn.errors.length),
- sameThreadAllTurns: result.threadTurns === 4,
- };
- writeFileSync(join(localRoot, "p2", `selftest-${label}.json`), JSON.stringify(result, null, 2));
- console.log(JSON.stringify({ threadId, checks: result.checks, replies: Object.fromEntries(Object.entries(result.turns as Record<string, Json>).map(([name, turn]) => [name, turn.reply])), proxy: result.proxy }, null, 2));
-}
-
-await main();
diff --git a/spike/src/p3-lifecycle.ts b/spike/src/p3-lifecycle.ts
deleted file mode 100644
index 647fd68..0000000
--- a/spike/src/p3-lifecycle.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-// Purpose: P3-5 — how the engine's life is tied to Codex: does it survive when the plugin-server instance that started
-// it is ended (Codex ends some instances right after startup), and does it end when the app-server exits?
-// No model calls: starting a thread is enough for Codex to launch the plugin server.
-// Input: none. Output: console summary; local/p3/lifecycle.json.
-
-import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
-import { dirname, join } from "node:path";
-import { setTimeout as sleep } from "node:timers/promises";
-import { fileURLToPath } from "node:url";
-import { AppServer, findBundledCodex } from "./appserver.ts";
-import { engineHealth } from "../../plugin/src/engine.ts";
-import { SERVER_NAME } from "../../plugin/src/install.ts";
-import { dataDir } from "../../plugin/src/paths.ts";
-import { TEST_MODEL } from "./testkit.ts";
-
-type Json = Record<string, any>;
-const here = dirname(fileURLToPath(import.meta.url));
-
-async function waitFor<T>(probe: () => Promise<T | null>, timeoutMs: number): Promise<T | null> {
- const started = Date.now();
- while (Date.now() - started < timeoutMs) {
- const value = await probe();
- if (value) return value;
- await sleep(250);
- }
- return null;
-}
-
-async function main(): Promise<void> {
- const result: Json = {};
- const running = await engineHealth();
- if (running) { process.kill(running.pid); await sleep(1000); }
- const startedAt = new Date().toISOString();
- const server = new AppServer(findBundledCodex(), [
- "-c", `mcp_servers.${SERVER_NAME}.command=${JSON.stringify(process.execPath)}`,
- "-c", `mcp_servers.${SERVER_NAME}.args=${JSON.stringify([join(here, "..", "..", "plugin", "src", "plugin-server.ts")])}`,
- ], { NO_PROXY: undefined, no_proxy: undefined }, join(dataDir(), "logs", `p3-lifecycle-${startedAt.replaceAll(":", "-")}.log`));
- try {
- await server.initialize();
- await server.request("thread/start", { model: TEST_MODEL, cwd: dataDir(), approvalPolicy: "never", sandbox: "read-only", ephemeral: true });
- const engine = await waitFor(() => engineHealth(), 20_000);
- result.engineStarted = engine?.pid ?? null;
- const starters = readFileSync(join(dataDir(), "plugin-server.jsonl"), "utf8").trim().split("\n").map((line) => JSON.parse(line))
- .filter((entry) => entry.at >= startedAt && entry.event === "engine" && entry.state === "started" && entry.enginePid === engine?.pid);
- const starter = starters[0]?.pid ?? null;
- result.startedByPluginServer = starter;
- if (starter) {
- process.kill(starter);
- await sleep(2500);
- const after = await engineHealth();
- result.engineAfterStarterKilled = after ? (after.pid === engine?.pid ? "same engine still running" : `replaced by ${after.pid}`) : "gone";
- }
- } finally {
- await server.stop();
- }
- await sleep(3000);
- const afterStop = await engineHealth();
- result.engineAfterAppServerStopped = afterStop ? `still running (${afterStop.pid})` : "gone";
- const exits = readFileSync(join(dataDir(), "proxy", `${new Date().toISOString().slice(0, 10)}.jsonl`), "utf8").trim().split("\n").map((line) => JSON.parse(line))
- .filter((entry) => entry.at >= startedAt && entry.event === "engine-exit");
- result.loggedExits = exits.map((entry) => `${entry.pid}: ${entry.reason}`);
- if (afterStop) process.kill(afterStop.pid);
- mkdirSync(join(dataDir(), "p3"), { recursive: true });
- writeFileSync(join(dataDir(), "p3", "lifecycle.json"), JSON.stringify(result, null, 2));
- console.log(JSON.stringify(result, null, 2));
-}
-
-await main();
diff --git a/spike/src/p3-selftest.ts b/spike/src/p3-selftest.ts
deleted file mode 100644
index 9c3af91..0000000
--- a/spike/src/p3-selftest.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-// Purpose: P3-5 — stability of the core with our own app-server in the desktop's environment, configured exactly as an
-// install would (openai_base_url, respect_system_proxy, the plugin's MCP server) but through -c overrides, so the
-// user's config.toml is untouched. Scenarios: the plugin server starts the engine; two threads with different
-// selections; the engine crashes and comes back; compaction of a thread with an unchecked image; a forked thread.
-// Input: [--label name]. Output: local/p3/selftest-<label>.json (synthetic test threads only).
-
-import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";
-import { dirname, join, resolve } from "node:path";
-import { setTimeout as sleep } from "node:timers/promises";
-import { fileURLToPath } from "node:url";
-import { AppServer, findBundledCodex } from "./appserver.ts";
-import { codexHome } from "../../plugin/src/codexconfig.ts";
-import { DEFAULT_PORT, engineHealth } from "../../plugin/src/engine.ts";
-import { SERVER_NAME } from "../../plugin/src/install.ts";
-import { applySelection } from "../../plugin/src/panel-state.ts";
-import { dataDir, proxyLogDirOf, requestStatsDirOf } from "../../plugin/src/paths.ts";
-import { runTurn, TEST_MODEL, testImages, text } from "./testkit.ts";
-
-type Json = Record<string, any>;
-const here = dirname(fileURLToPath(import.meta.url));
-
-async function waitFor<T>(probe: () => Promise<T | null>, timeoutMs: number): Promise<{ value: T | null; ms: number }> {
- const started = Date.now();
- while (Date.now() - started < timeoutMs) {
- const value = await probe();
- if (value) return { value, ms: Date.now() - started };
- await sleep(250);
- }
- return { value: null, ms: Date.now() - started };
-}
-
-function proxyEntries(since: string, threadIds: string[]): Json[] {
- const file = join(proxyLogDirOf(), `${new Date().toISOString().slice(0, 10)}.jsonl`);
- if (!existsSync(file)) return [];
- return readFileSync(file, "utf8").trim().split("\n").map((line) => JSON.parse(line)).filter((entry) => entry.at >= since && threadIds.includes(entry.threadId));
-}
-
-const shortEntry = (entry: Json) => ({
- at: entry.at.slice(11, 19), thread: String(entry.threadId).slice(-4), transport: entry.transport,
- what: entry.declined ? `426` : entry.transport === "websocket" ? `ws ${entry.upstreamStatus ?? ""}`.trim() : `${entry.method} ${String(entry.path).split("/").pop()} ${entry.status}`,
- replaced: entry.rewrite?.replaced?.map((r: Json) => `${r.id}:${r.mode}`) ?? null, skipped: entry.rewrite?.skipped ?? null, error: entry.error ?? null,
-});
-
-async function main(): Promise<void> {
- const label = process.argv.includes("--label") ? process.argv[process.argv.indexOf("--label") + 1] : "default";
- const workDir = join(dataDir(), "p3", "work");
- mkdirSync(workDir, { recursive: true });
- const file = (name: string) => join(workDir, name);
- writeFileSync(file("a.png"), testImages.redSquare());
- writeFileSync(file("b.png"), testImages.blueCircle());
- writeFileSync(file("c.png"), testImages.whiteTriangle());
- const result: Json = { label, checks: {} };
-
- // Scenario A needs the engine down, so the plugin server has to start it.
- const before = await engineHealth();
- if (before) { process.kill(before.pid); await waitFor(async () => ((await engineHealth()) ? null : true), 5000); }
- result.engineBefore = before ? `killed ${before.pid}` : "not running";
-
- const startedAt = new Date().toISOString();
- const server = new AppServer(findBundledCodex(), [
- "-c", `openai_base_url="http://localhost:${DEFAULT_PORT}/backend-api/codex"`,
- "-c", "features.respect_system_proxy=true",
- "-c", `mcp_servers.${SERVER_NAME}.command=${JSON.stringify(process.execPath)}`,
- "-c", `mcp_servers.${SERVER_NAME}.args=${JSON.stringify([join(here, "..", "..", "plugin", "src", "plugin-server.ts")])}`,
- "-c", `mcp_servers.${SERVER_NAME}.default_tools_approval_mode="approve"`,
- ], { NO_PROXY: undefined, no_proxy: undefined }, join(dataDir(), "logs", `p3-selftest-${label}-${startedAt.replaceAll(":", "-")}.log`));
- const threads: Json = {};
- try {
- await server.initialize();
- const start = async (name: string) => {
- const { thread } = await server.request<{ thread: Json }>("thread/start", { model: TEST_MODEL, cwd: workDir, approvalPolicy: "never", sandbox: "read-only", ephemeral: false });
- await server.request("thread/name/set", { threadId: thread.id, name: `[CAM测试] P3 稳定性 ${label} ${name}` });
- threads[name] = thread.id;
- return thread.id as string;
- };
-
- // A — the plugin server (started by Codex with the thread) brings the engine up.
- const t1 = await start("T1");
- const engineUp = await waitFor(() => engineHealth(), 20_000);
- result.checks.pluginServerStartsEngine = !!engineUp.value;
- result.engineStartMs = engineUp.ms;
- const firstPid = engineUp.value?.pid ?? null;
-
- // B — two threads; only T1 unchecks an image.
- const t2 = await start("T2");
- const ok = (turn: Json) => turn.status === "completed" && !turn.errors.length;
- const turns: Json = {};
- turns.t1Upload = await runTurn(server, t1, [text("这是两张测试图,先不用描述,只回复“收到”。"), { type: "localImage", path: file("a.png") }, { type: "localImage", path: file("b.png") }]);
- turns.t2Upload = await runTurn(server, t2, [text("这是一张测试图,先不用描述,只回复“收到”。"), { type: "localImage", path: file("c.png") }]);
- applySelection(t1, { uncheck: ["IMG-001"], auto: false }, { sessionsDir: join(codexHome(), "sessions") });
- await sleep(2500);
- turns.t1AfterUncheck = await runTurn(server, t1, [text("请只回复“好的”。")]);
- turns.t2Normal = await runTurn(server, t2, [text("请只回复“好的”。")]);
-
- // C — the engine dies; the plugin server's watchdog brings it back.
- if (firstPid) process.kill(firstPid);
- const back = await waitFor(async () => { const health = await engineHealth(); return health && health.pid !== firstPid ? health : null; }, 30_000);
- result.checks.engineRestarted = !!back.value;
- result.engineRestartMs = back.ms;
- turns.t1AfterRestart = await runTurn(server, t1, [text("请只回复“好的”。")]);
-
- // D — compaction of a thread with an unchecked image, then ask about that image.
- const compactFrom = new Date().toISOString();
- const known = new Set(Object.values(turns).map((t: Json) => t.turnId));
- const before = server.notifications.length;
- await server.request("thread/compact/start", { threadId: t1 });
- // Compaction runs as its own turn: find that turn, then wait for it to finish before the next turn.
- const isNew = (n: { params: Json }) => server.notifications.indexOf(n as any) >= before && n.params?.threadId === t1 && !known.has(n.params.turn?.id);
- const compactTurn = await server.waitFor((n) => n.method === "turn/started" && isNew(n), 60_000).then((n) => n.params.turn.id as string, () => null);
- const compacted = compactTurn ? await server.waitFor((n) => n.method === "turn/completed" && n.params.turn?.id === compactTurn, 5 * 60_000).then((n) => n.params.turn.status, () => "timeout") : "no compaction turn";
- result.compactionFinished = compacted;
- result.compactionRequests = proxyEntries(compactFrom, [t1]).map(shortEntry);
- turns.t1AfterCompaction = await runTurn(server, t1, [text("第一张图 a.png 是什么颜色、什么形状?不要调用任何工具。")]);
-
- // F — a fork gets its own selection.
- const { thread: fork } = await server.request<{ thread: Json }>("thread/fork", { threadId: t1 });
- threads.T1fork = fork.id;
- turns.forkTurn = await runTurn(server, fork.id, [text("请只回复“好的”。")]);
-
- result.turns = Object.fromEntries(Object.entries(turns).map(([name, turn]: [string, Json]) => [name, { status: turn.status, errors: turn.errors, reply: String(turn.reply).slice(0, 120) }]));
- result.checks.allTurnsClean = Object.values(turns).every(ok);
- } finally {
- await server.stop();
- }
-
- const entries = proxyEntries(startedAt, Object.values(threads));
- result.proxy = entries.map(shortEntry);
- const posts = (thread: string) => entries.filter((entry) => entry.threadId === thread && entry.transport === "http" && /responses$/.test(entry.path));
- const t1Posts = posts(threads.T1);
- result.checks.t1Rewritten = t1Posts.length > 0 && t1Posts.every((entry) => entry.rewrite?.replaced?.some((r: Json) => r.id === "IMG-001"));
- const t2Entries = entries.filter((entry) => entry.threadId === threads.T2);
- result.checks.t2Untouched = t2Entries.length > 0 && t2Entries.every((entry) => !entry.rewrite && !entry.declined);
- result.checks.compactionRewritten = (result.compactionRequests as Json[]).some((entry) => entry.replaced?.includes("IMG-001:plain"));
- result.checks.stillHiddenAfterCompaction = /IMG-001|看不到|无法|没有提供/.test(result.turns?.t1AfterCompaction?.reply ?? "");
- result.forkRequests = entries.filter((entry) => entry.threadId === threads.T1fork).map(shortEntry);
- result.statsFiles = Object.fromEntries(Object.entries(threads).map(([name, id]) => [name, existsSync(join(requestStatsDirOf(), `${id}.json`))]));
- result.threads = threads;
- mkdirSync(join(dataDir(), "p3"), { recursive: true });
- writeFileSync(join(dataDir(), "p3", `selftest-${label}.json`), JSON.stringify(result, null, 2));
- console.log(JSON.stringify(result, null, 2));
-}
-
-await main();
diff --git a/spike/src/p3-toolcheck.ts b/spike/src/p3-toolcheck.ts
deleted file mode 100644
index 7606e27..0000000
--- a/spike/src/p3-toolcheck.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-// Purpose: P3-1 — see whether and how the panel's MCP tool reaches the model: run one turn ("打开素材面板") through our
-// own app-server, which loads the same config.toml (including the managed probe server). The proxy must run with
-// --force-http --dump-requests, so the request (tool list included) is saved under local/p2/requests/.
-// Input: [--port 17891]. Output: console summary of the turn (tool calls and reply).
-
-import { mkdirSync } from "node:fs";
-import { dirname, join, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-import { AppServer, findBundledCodex } from "./appserver.ts";
-import { runTurn, TEST_MODEL, text } from "./testkit.ts";
-
-type Json = Record<string, any>;
-const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
-
-async function main(): Promise<void> {
- const port = Number(process.argv.includes("--port") ? process.argv[process.argv.indexOf("--port") + 1] : 17891);
- const workDir = join(localRoot, "p3", "work");
- mkdirSync(workDir, { recursive: true });
- const startedAt = new Date().toISOString();
- const server = new AppServer(findBundledCodex(), ["-c", `openai_base_url="http://localhost:${port}/backend-api/codex"`, "-c", "features.respect_system_proxy=true"], {}, join(localRoot, "logs", `p3-toolcheck-${startedAt.replaceAll(":", "-")}.log`));
- try {
- await server.initialize();
- const { thread } = await server.request<{ thread: Json }>("thread/start", { model: TEST_MODEL, cwd: workDir, approvalPolicy: "never", sandbox: "read-only", ephemeral: true });
- const turn = await runTurn(server, thread.id, [text("打开素材面板")]);
- const items = server.notifications.filter((n) => n.method === "item/completed" && n.params.turnId === turn.turnId).map((n) => n.params.item);
- console.log(JSON.stringify({ startedAt, threadId: thread.id, status: turn.status, reply: turn.reply, tools: items.filter((i) => !["agentMessage", "reasoning", "userMessage"].includes(i.type)).map((i) => ({ type: i.type, server: i.server ?? null, tool: i.tool ?? null, status: i.status ?? null, mcpAppUi: i.mcpAppUi ?? null })) }, null, 2));
- } finally {
- await server.stop();
- }
-}
-
-await main();
diff --git a/spike/src/panel-language.test.ts b/spike/src/panel-language.test.ts
index cb6ba36..78e5bb3 100644
--- a/spike/src/panel-language.test.ts
+++ b/spike/src/panel-language.test.ts
@@ -5,7 +5,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-const page = readFileSync(new URL("../../plugin/src/panel.html", import.meta.url), "utf8");
+const page = readFileSync(new URL("../../plugin/src/panel/panel.html", import.meta.url), "utf8");
const texts = JSON.parse(/<script type="application\/json" id="messages">([\s\S]*?)<\/script>/.exec(page)![1]);
test("the panel recognizes Japanese host locales without changing the model language parser", async () => {
@@ -35,7 +35,7 @@ test("Claude's fallback pane also has a complete Japanese interface", () => {
});
test("Claude uses its own locale, rereads changes, and leaves the settings read-only", async () => {
- const { claudePanelLanguage } = await import("../../plugin/src/panel-language.ts");
+ const { claudePanelLanguage } = await import("../../plugin/src/panel/panel-language.ts");
const root = mkdtempSync(join(tmpdir(), "cam-panel-locale-"));
const config = join(root, "config.json");
const options = { settingsFiles: [config], env: { LANG: "en_US.UTF-8", CAM_LANG: "zh" }, home: root };
@@ -52,7 +52,7 @@ test("Claude uses its own locale, rereads changes, and leaves the settings read-
});
test("Claude desktop settings are located for Windows, macOS and Linux", async () => {
- const { claudePanelLanguage } = await import("../../plugin/src/panel-language.ts");
+ const { claudePanelLanguage } = await import("../../plugin/src/panel/panel-language.ts");
const home = mkdtempSync(join(tmpdir(), "cam-desktop-locale-"));
const local = join(home, "local"), roaming = join(home, "roaming"), xdg = join(home, "xdg");
const cases = [
diff --git a/spike/src/panel-probe.html b/spike/src/panel-probe.html
deleted file mode 100644
index 00f13e2..0000000
--- a/spike/src/panel-probe.html
+++ /dev/null
@@ -1,113 +0,0 @@
-<!doctype html>
-<html lang="zh-CN">
-<head>
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width, initial-scale=1">
-<title>素材面板试验</title>
-<style>
- :root { color-scheme: light dark; font: 13px/1.5 system-ui, "Microsoft YaHei", sans-serif; }
- body { margin: 0; padding: 12px 14px; }
- h1 { font-size: 15px; margin: 0 0 8px; }
- .row { display: flex; gap: 8px; align-items: center; margin: 3px 0; }
- .label { min-width: 9em; opacity: .75; }
- .ok { color: #1a7f37; } .bad { color: #cf222e; }
- pre { font-size: 11px; white-space: pre-wrap; word-break: break-all; max-height: 220px; overflow: auto; background: rgba(127,127,127,.12); padding: 8px; border-radius: 6px; }
- button { font: inherit; padding: 3px 10px; }
- img { width: 40px; height: 40px; border-radius: 6px; border: 1px solid rgba(127,127,127,.4); }
-</style>
-</head>
-<body>
-<h1>素材管理器 · 界面试验</h1>
-<div class="row"><span class="label">静态页面</span><b class="ok">已加载</b></div>
-<div class="row"><span class="label">缩略图(data URL)</span><img id="thumb" alt=""><b id="thumbState">加载中…</b></div>
-<div class="row"><span class="label">与 Codex 握手</span><b id="handshake">进行中…</b></div>
-<div class="row"><span class="label">回调插件服务</span><b id="ping">未开始</b></div>
-<div class="row"><span class="label">访问本机地址</span><b id="fetch">未开始</b></div>
-<div class="row"><button id="again">再回调一次</button><button id="fullscreen">请求全屏</button></div>
-<pre id="log"></pre>
-<script>
-(() => {
- const $ = (id) => document.getElementById(id);
- const lines = [];
- const log = (line) => { lines.push(line); $("log").textContent = lines.join("\n"); resize(); };
- const set = (id, text, ok) => { $(id).textContent = text; $(id).className = ok ? "ok" : "bad"; resize(); };
- const report = { windowOpenai: typeof window.openai === "object" && window.openai ? Object.keys(window.openai) : null, received: [], csp: [] };
- let nextId = 1;
- const pending = new Map();
- const post = (message) => window.parent.postMessage({ jsonrpc: "2.0", ...message }, "*");
- const request = (method, params, timeoutMs = 10000) => new Promise((resolve, reject) => {
- const id = nextId++;
- const timer = setTimeout(() => { pending.delete(id); reject(new Error(method + " 超时")); }, timeoutMs);
- pending.set(id, { resolve: (value) => { clearTimeout(timer); resolve(value); }, reject: (error) => { clearTimeout(timer); reject(error); } });
- post({ id, method, params });
- });
- function resize() {
- post({ method: "ui/notifications/size-changed", params: { width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight } });
- }
- document.addEventListener("securitypolicyviolation", (event) => {
- report.csp.push(event.violatedDirective + " " + event.blockedURI);
- log("CSP 拦截:" + event.violatedDirective + " " + event.blockedURI);
- });
- window.addEventListener("message", (event) => {
- const message = event.data;
- if (!message || typeof message !== "object") return;
- if (message.id !== undefined && pending.has(message.id) && ("result" in message || "error" in message)) {
- const waiter = pending.get(message.id);
- pending.delete(message.id);
- if (message.error) waiter.reject(new Error(JSON.stringify(message.error))); else waiter.resolve(message.result);
- return;
- }
- report.received.push(message.method || "reply");
- log("收到:" + (message.method || "reply") + " " + JSON.stringify(message.params ?? message.result ?? {}).slice(0, 160));
- });
- log("window.openai:" + JSON.stringify(report.windowOpenai));
-
- // A data-URL image drawn on a canvas stands in for a thumbnail.
- const canvas = document.createElement("canvas");
- canvas.width = canvas.height = 40;
- const ctx = canvas.getContext("2d");
- ctx.fillStyle = "#fad23c"; ctx.fillRect(0, 0, 40, 40);
- ctx.fillStyle = "#2846d2"; ctx.beginPath(); ctx.arc(20, 20, 11, 0, Math.PI * 2); ctx.fill();
- $("thumb").onload = () => { set("thumbState", "显示正常", true); report.thumb = "ok"; };
- $("thumb").onerror = () => { set("thumbState", "显示失败", false); report.thumb = "error"; };
- $("thumb").src = canvas.toDataURL("image/png");
-
- const ping = async (reason) => {
- try {
- const result = await request("tools/call", { name: "cam_probe_ping", arguments: { reason, report } });
- set("ping", "成功:" + JSON.stringify(result.structuredContent ?? result.content).slice(0, 100), true);
- } catch (error) { set("ping", "失败:" + error.message, false); }
- };
- $("again").onclick = () => ping("button");
- $("fullscreen").onclick = async () => {
- try { log("全屏:" + JSON.stringify(await request("ui/request-display-mode", { mode: "fullscreen" }))); }
- catch (error) { log("全屏失败:" + error.message); }
- };
-
- (async () => {
- try {
- const init = await request("ui/initialize", { protocolVersion: "2026-01-26", appInfo: { name: "codex-attachment-manager-probe", version: "0.0.1" }, appCapabilities: {} });
- const context = init.hostContext || {};
- report.host = { protocolVersion: init.protocolVersion, hostInfo: init.hostInfo, hostCapabilities: init.hostCapabilities, contextKeys: Object.keys(context), displayMode: context.displayMode, availableDisplayModes: context.availableDisplayModes, theme: context.theme, locale: context.locale };
- post({ method: "ui/notifications/initialized", params: {} });
- set("handshake", "成功 " + JSON.stringify(report.host.hostInfo ?? {}).slice(0, 80), true);
- log("握手结果:" + JSON.stringify(report.host).slice(0, 600));
- } catch (error) {
- report.handshakeError = error.message;
- set("handshake", "失败:" + error.message, false);
- }
- try {
- const response = await fetch("http://localhost:17891/__cam/health");
- report.fetch = "status " + response.status;
- set("fetch", "成功(" + response.status + ")", true);
- } catch (error) {
- report.fetch = String(error);
- set("fetch", "失败:" + error.message, false);
- }
- await ping("load");
- })();
- resize();
-})();
-</script>
-</body>
-</html>
diff --git a/spike/src/panel-probe.ts b/spike/src/panel-probe.ts
deleted file mode 100644
index 4000669..0000000
--- a/spike/src/panel-probe.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-// Purpose: P3-1 — probe what Codex Desktop offers an MCP App on Windows: whether the widget renders, finishes the
-// MCP Apps handshake, calls back into this server, shows data-URL images and reaches localhost; and when and how often
-// Codex starts this server (per thread or shared).
-// Input: MCP JSON-RPC over stdio (newline-delimited); the widget page is panel-probe.html next to this file.
-// Output: one JSON line per event in local/p3/panel-probe.jsonl (local only; no conversation content is logged).
-
-import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
-import { dirname, join, resolve } from "node:path";
-import { createInterface } from "node:readline";
-import { fileURLToPath } from "node:url";
-
-type Json = Record<string, any>;
-const here = dirname(fileURLToPath(import.meta.url));
-const logDir = join(resolve(here, "../.."), "local", "p3");
-const RESOURCE = "ui://codex-attachment-manager/probe.html";
-const MIME = "text/html;profile=mcp-app";
-let calls = 0;
-
-function log(entry: Json): void {
- mkdirSync(logDir, { recursive: true });
- appendFileSync(join(logDir, "panel-probe.jsonl"), `${JSON.stringify({ at: new Date().toISOString(), pid: process.pid, ...entry })}\n`);
-}
-
-const send = (message: Json) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);
-
-const TOOLS = [
- {
- name: "cam_panel_probe",
- title: "素材面板(试验)",
- description: "打开 Codex 素材管理器的界面试验面板。用户要求打开素材面板时调用,不需要参数。",
- inputSchema: { type: "object", properties: {}, additionalProperties: false },
- _meta: { ui: { resourceUri: RESOURCE }, "openai/ui": { preferredModelDisplayMode: "inline" } },
- },
- {
- name: "cam_probe_ping",
- title: "素材面板回调(试验)",
- description: "素材面板内部使用:面板页面回调插件服务。模型不需要调用。",
- inputSchema: { type: "object", properties: { reason: { type: "string" }, report: { type: "object" } } },
- _meta: { ui: { resourceUri: RESOURCE, visibility: ["app"] } },
- },
-];
-
-function handle(message: Json): void {
- const { id, method, params = {} } = message;
- if (method === "initialize") {
- log({ event: "initialize", client: params.clientInfo ?? null, protocolVersion: params.protocolVersion ?? null, capabilities: params.capabilities ?? null });
- send({ id, result: { protocolVersion: params.protocolVersion ?? "2025-06-18", capabilities: { tools: {}, resources: {} }, serverInfo: { name: "codex-attachment-manager-probe", version: "0.0.1" } } });
- } else if (method === "tools/list") {
- send({ id, result: { tools: TOOLS } });
- } else if (method === "tools/call") {
- calls++;
- log({ event: "tools/call", name: params.name, arguments: params.arguments ?? null, meta: params._meta ?? null });
- const meta = params._meta ?? {};
- const threadId = meta.threadId ?? meta.thread_id ?? null;
- if (params.name === "cam_panel_probe") {
- send({ id, result: { content: [{ type: "text", text: "已打开素材面板(试验版)。" }], structuredContent: { pid: process.pid, threadId, calls } } });
- } else if (params.name === "cam_probe_ping") {
- send({ id, result: { content: [{ type: "text", text: "pong" }], structuredContent: { pid: process.pid, calls, at: new Date().toISOString() } } });
- } else {
- send({ id, error: { code: -32602, message: `unknown tool ${params.name}` } });
- }
- } else if (method === "resources/list") {
- send({ id, result: { resources: [{ uri: RESOURCE, name: "素材面板(试验)", mimeType: MIME }] } });
- } else if (method === "resources/templates/list") {
- send({ id, result: { resourceTemplates: [] } });
- } else if (method === "resources/read") {
- log({ event: "resources/read", uri: params.uri ?? null });
- const text = readFileSync(join(here, "panel-probe.html"), "utf8");
- send({ id, result: { contents: [{ uri: RESOURCE, mimeType: MIME, text, _meta: { ui: { csp: { connectDomains: ["http://localhost:17891"], resourceDomains: [] }, prefersBorder: true } } }] } });
- } else if (method === "ping") {
- send({ id, result: {} });
- } else if (id !== undefined) {
- log({ event: "unsupported", method });
- send({ id, error: { code: -32601, message: `unsupported: ${method}` } });
- }
-}
-
-// Which process started us, and whether Codex passes thread identity in the environment (names and ids only).
-log({ event: "start", ppid: process.ppid, argv: process.argv.slice(1), env: Object.fromEntries(Object.entries(process.env).filter(([name]) => /THREAD|SESSION/i.test(name) && !/TOKEN|KEY|SECRET/i.test(name))) });
-process.stdin.on("close", () => { log({ event: "stdin-closed", calls }); process.exit(0); });
-createInterface({ input: process.stdin, crlfDelay: Infinity }).on("line", (line) => {
- if (!line.trim()) return;
- try { handle(JSON.parse(line)); } catch (error) { log({ event: "error", error: String(error) }); }
-});
diff --git a/spike/src/panel-state.test.ts b/spike/src/panel-state.test.ts
index 6026563..d1f6bec 100644
--- a/spike/src/panel-state.test.ts
+++ b/spike/src/panel-state.test.ts
@@ -7,14 +7,14 @@ import assert from "node:assert/strict";
import { readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import test from "node:test";
-import { decodePng } from "../../plugin/src/png.ts";
-import { applySelection, imageFor, loadPanelState, panelStateOf, requestedIds, sendInfo } from "../../plugin/src/panel-state.ts";
-import { childrenDirOf, requestStatsDirOf } from "../../plugin/src/paths.ts";
+import { decodePng } from "../../plugin/src/core/png.ts";
+import { applySelection, imageFor, loadPanelState, panelStateOf, requestedIds, sendInfo } from "../../plugin/src/panel/panel-state.ts";
+import { childrenDirOf, requestStatsDirOf } from "../../plugin/src/core/paths.ts";
import { recordChild } from "../../plugin/src/children.ts";
-import { recordRequest } from "../../plugin/src/request-stats.ts";
+import { recordRequest } from "../../plugin/src/core/request-stats.ts";
import { readSelection, writeSelection } from "../../plugin/src/selection.ts";
import { assistant, line, red, sampleSessions, startThread, THREAD, turn, upload } from "./testfixtures.ts";
-import { shrink } from "../../plugin/src/thumbnail.ts";
+import { shrink } from "../../plugin/src/core/thumbnail.ts";
import { png } from "./testkit.ts";
const records = (text: string) => text.trim().split("\n").map((raw) => JSON.parse(raw));
@@ -131,7 +131,7 @@ test("v0.4: the panel is told when the engine left out thinking that no longer f
test("v0.5: images from before a Claude Code compaction go out again when checked, and are marked as such", async () => {
const { image, pngA, text, transcript } = await import("./claude-fixtures.ts");
- const { buildClaudeIndex } = await import("../../plugin/src/claude-index.ts");
+ const { buildClaudeIndex } = await import("../../plugin/src/adapters/claude/claude-index.ts");
const t = transcript();
const p1 = t.prompt([image(pngA), text("first")]);
t.assistant(text("ok"));
@@ -263,7 +263,7 @@ test("the task's panel lists its subagents and side chats with their last reques
});
test("the image preview supports Ctrl+wheel zoom and preserves keyboard and backdrop behavior", async () => {
- const html = readFileSync(join(import.meta.dirname, "..", "..", "plugin", "src", "panel.html"), "utf8");
+ const html = readFileSync(join(import.meta.dirname, "..", "..", "plugin", "src", "panel", "panel.html"), "utf8");
const messagesJson = /<script type="application\/json" id="messages">([\s\S]*?)<\/script>/.exec(html)![1];
const scriptCode = /<script>\s*(\(\(\) => \{[\s\S]*?\}\)\(\);)\s*<\/script>/.exec(html)![1];
diff --git a/spike/src/platform.test.ts b/spike/src/platform.test.ts
index 3493995..6ebf975 100644
--- a/spike/src/platform.test.ts
+++ b/spike/src/platform.test.ts
@@ -6,8 +6,8 @@ import assert from "node:assert/strict";
import { join } from "node:path";
import test from "node:test";
import { launcher } from "../../plugin/src/cam.ts";
-import { cliCandidates } from "../../plugin/src/codexcli.ts";
-import { dataDir } from "../../plugin/src/paths.ts";
+import { cliCandidates } from "../../plugin/src/adapters/codex/codexcli.ts";
+import { dataDir } from "../../plugin/src/core/paths.ts";
const home = join("/", "home", "someone");
diff --git a/spike/src/plugin-cache.test.ts b/spike/src/plugin-cache.test.ts
index 90883b7..3ac2852 100644
--- a/spike/src/plugin-cache.test.ts
+++ b/spike/src/plugin-cache.test.ts
@@ -5,7 +5,7 @@ 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);
+ const mod = await import("../../plugin/src/adapters/codex/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);
@@ -19,7 +19,7 @@ test("installing a new cache preserves the older runtime even when Codex cleans
});
test("a failed reinstall restores missing files in the existing version", async () => {
- const mod = await import("../../plugin/src/plugin-cache.ts").catch(() => null);
+ const mod = await import("../../plugin/src/adapters/codex/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);
diff --git a/spike/src/plugin-smoke.ts b/spike/src/plugin-smoke.ts
index 0b044ad..f1b8f52 100644
--- a/spike/src/plugin-smoke.ts
+++ b/spike/src/plugin-smoke.ts
@@ -11,9 +11,9 @@ import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { AppServer, type Notification } from "./appserver.ts";
-import { findCodexCli, runCodex } from "../../plugin/src/codexcli.ts";
+import { findCodexCli, runCodex } from "../../plugin/src/adapters/codex/codexcli.ts";
import { engineHealth, type Health } from "../../plugin/src/engine.ts";
-import { MARKETPLACE, PLUGIN, PLUGIN_ID, SERVER_NAME } from "../../plugin/src/install.ts";
+import { MARKETPLACE, PLUGIN, PLUGIN_ID, SERVER_NAME } from "../../plugin/src/adapters/codex/install.ts";
type Json = Record<string, any>;
const root = resolve(import.meta.dirname, "..", "..");
diff --git a/spike/src/png.test.ts b/spike/src/png.test.ts
index c2e54af..501a2b4 100644
--- a/spike/src/png.test.ts
+++ b/spike/src/png.test.ts
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import test from "node:test";
import { deflateSync } from "node:zlib";
-import { decodePng } from "../../plugin/src/png.ts";
+import { decodePng } from "../../plugin/src/core/png.ts";
function chunk(type: string, data: Buffer): Buffer {
const length = Buffer.alloc(4);
diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.ts
index d211809..5a67a5a 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 } from "../../plugin/src/proxy.ts";
+import { claudeIdentity, describeBody, forwardHeaders, 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";
@@ -112,9 +112,7 @@ function fixture() {
test("rewriteBody swaps the unchecked image for a placeholder and re-encodes the body", () => {
const { threadId, sessions, selections, red, blue, body } = fixture();
- assert.equal(hasUnchecked(threadId, selections), false);
writeSelection({ threadId, unchecked: { "msg_1#0": { id: "IMG-001", at: "2026-09-24T10:00:00Z" } } }, selections);
- assert.equal(hasUnchecked(threadId, selections), true);
const original = body();
const { body: out, report } = rewriteBody(original, "zstd", threadId, sessions, selections);
const text = zlib.zstdDecompressSync(out).toString("utf8");
@@ -282,7 +280,7 @@ test("v0.10: once the engine changes the history, a cache mark moves to where th
test("a Claude Code request is rewritten from the session's transcript and selection, with images also with nothing unchecked", async () => {
const { usualSession, usualRequest } = await import("./claude-fixtures.ts");
const { claudeNeedsRewrite, rewriteClaudeBody, claudeImageSizes } = await import("../../plugin/src/proxy.ts");
- const { buildClaudeIndex } = await import("../../plugin/src/claude-index.ts");
+ const { buildClaudeIndex } = await import("../../plugin/src/adapters/claude/claude-index.ts");
const home = mkdtempSync(join(tmpdir(), "cam-claude-home-"));
const dir = mkdtempSync(join(tmpdir(), "cam-claude-sel-"));
const session = "11111111-2222-4333-8444-555555555555";
diff --git a/spike/src/rebuild.ts b/spike/src/rebuild.ts
deleted file mode 100644
index 18d3f74..0000000
--- a/spike/src/rebuild.ts
+++ /dev/null
@@ -1,224 +0,0 @@
-// Purpose: T4–T8 — rebuild a thread through app-server: inject migrated history, then run turns with chosen attachments.
-// Input: subcommands
-// preview --source <threadId> --select IMG-a,IMG-b
-// create --source <threadId> --select IMG-a,IMG-b --prompt <text> [--effort medium]
-// turn --thread <threadId> [--attach IMG-c] --prompt <text> --label <name> [--disable <feature>] [--effort medium]
-// probe --source <threadId> --prompt <text> --label <name> [--disable <feature>] [--config key=value]… (ephemeral thread)
-// Output: local/rebuild-preview.{json,md}, local/t4-rebuild.json, local/turn-<label>.json, local/probe-<label>.json
-// (local only, never committed).
-
-import { createHash } from "node:crypto";
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
-import { dirname, join, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-import { AppServer, findBundledCodex, type Notification } from "./appserver.ts";
-import { baseName, buildMigration, type AssetInfo } from "./migrate.ts";
-import { decodePng } from "../../plugin/src/png.ts";
-
-type Json = Record<string, any>;
-const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
-
-function option(name: string, fallback?: string): string {
- const index = process.argv.indexOf(name);
- const value = index >= 0 ? process.argv[index + 1] : undefined;
- if (value !== undefined) return value;
- if (fallback !== undefined) return fallback;
- throw new Error(`missing ${name}`);
-}
-
-// Resolves an image path to an indexed asset by content (bytes first, then pixels). When Codex resized an upload,
-// content no longer matches, so user uploads fall back to the path recorded next to the image in the same message.
-function loadAssets(): { resolveImage: (path: string) => AssetInfo | null; attachmentPath: (assetId: string) => string } {
- const inventory: Json = JSON.parse(readFileSync(join(localRoot, "assets.json"), "utf8"));
- const matches: Json = JSON.parse(readFileSync(join(localRoot, "matches.json"), "utf8"));
- const byByte = new Map<string, string>();
- const byPixel = new Map<string, string>();
- const info = new Map<string, AssetInfo>();
- for (const asset of inventory.assets) {
- for (const hash of asset.byteHashes) byByte.set(hash, asset.assetId);
- if (asset.pixelSha256) byPixel.set(asset.pixelSha256, asset.assetId);
- const occurrences = inventory.occurrences.filter((o: Json) => o.assetId === asset.assetId);
- const named = occurrences.map((o: Json) => o.knownLocalPath).find((path: string | null) => path && !/codex-clipboard-/.test(path));
- info.set(asset.assetId, { assetId: asset.assetId, name: named ? baseName(named) : "剪贴板图片", width: asset.width, height: asset.height, bytes: occurrences[0].byteLength });
- }
- const byUploadPath = new Map<string, string>();
- for (const occurrence of inventory.occurrences) {
- if (occurrence.source === "user_upload" && occurrence.knownLocalPath) byUploadPath.set(occurrence.knownLocalPath.toLowerCase(), occurrence.assetId);
- }
- const cache = new Map<string, AssetInfo | null>();
- const resolveImage = (path: string): AssetInfo | null => {
- if (cache.has(path)) return cache.get(path)!;
- let found: string | undefined;
- if (path && existsSync(path)) {
- const bytes = readFileSync(path);
- found = byByte.get(createHash("sha256").update(bytes).digest("hex"));
- if (!found) { try { found = byPixel.get(decodePng(bytes).pixelSha256); } catch { /* not a decodable PNG */ } }
- }
- found ??= path ? byUploadPath.get(path.toLowerCase()) : undefined;
- const result = found ? info.get(found)! : null;
- cache.set(path, result);
- return result;
- };
- const attachmentPath = (assetId: string): string => {
- const match = matches.matches.find((m: Json) => m.assetId === assetId);
- if (!match?.attachmentPath) throw new Error(`no attachment file for ${assetId}`);
- return match.attachmentPath;
- };
- return { resolveImage, attachmentPath };
-}
-
-function options(name: string): string[] {
- return process.argv.flatMap((arg, i) => (arg === name && process.argv[i + 1] !== undefined ? [process.argv[i + 1]] : []));
-}
-
-function startServer(label: string, extraArgs: string[] = [], serverRequests: Json[] = []): AppServer {
- mkdirSync(join(localRoot, "logs"), { recursive: true });
- const stamp = new Date().toISOString().replaceAll(":", "-");
- // Server requests are recorded so experiments can show what the app-server asked for; the default decline still applies.
- return new AppServer(findBundledCodex(), extraArgs, {}, join(localRoot, "logs", `${label}-appserver-${stamp}.log`), (method, params) => {
- serverRequests.push({ method, params });
- return undefined;
- });
-}
-
-async function sourceTurns(server: AppServer, threadId: string): Promise<{ thread: Json; turns: Json[] }> {
- const { thread } = await server.request<{ thread: Json }>("thread/read", { threadId, includeTurns: false });
- const turns: Json[] = [];
- let cursor: string | null = null;
- do {
- const page: Json = await server.request("thread/turns/list", { threadId, cursor, limit: 50, sortDirection: "asc", itemsView: "full" }, 300_000);
- turns.push(...page.data);
- cursor = page.nextCursor;
- } while (cursor);
- return { thread, turns };
-}
-
-function attachmentInput(assetIds: string[], attachmentPath: (id: string) => string, prompt: string): Json[] {
- const legend = assetIds.length ? `【附件管理器】本轮附件:${assetIds.map((id, i) => `附件 ${i + 1} = ${id}`).join(",")}。\n` : "";
- return [
- { type: "text", text: `${legend}${prompt}`, text_elements: [] },
- ...assetIds.map((id) => ({ type: "localImage", path: attachmentPath(id) })),
- ];
-}
-
-// Runs one turn and waits for its completion notification; returns what the turn produced.
-async function runTurn(server: AppServer, threadId: string, input: Json[], effort: string): Promise<Json> {
- const startedAt = Date.now();
- const before = server.notifications.length;
- const { turn } = await server.request<{ turn: Json }>("turn/start", { threadId, input, effort }, 120_000);
- const done: Notification = await server.waitFor((n) => n.method === "turn/completed" && n.params.turn?.id === turn.id, 20 * 60_000);
- const mine = server.notifications.slice(before).filter((n) => n.params?.turnId === turn.id || n.params?.turn?.id === turn.id);
- const items = mine.filter((n) => n.method === "item/completed").map((n) => n.params.item);
- return {
- turnId: turn.id,
- status: done.params.turn.status,
- error: done.params.turn.error ?? null,
- wallMs: Date.now() - startedAt,
- itemTypes: items.map((item) => item.type),
- agentText: items.filter((item) => item.type === "agentMessage").map((item) => item.text).join("\n\n"),
- toolItems: items.filter((item) => !["agentMessage", "reasoning", "userMessage"].includes(item.type)).map((item) => ({
- type: item.type, status: item.status, path: item.path, server: item.server, tool: item.tool, command: item.command,
- // Content types only (never data), to see whether a tool returned an image into history.
- resultContentTypes: Array.isArray(item.result?.content) ? item.result.content.map((part: Json) => part.type) : undefined,
- })),
- errors: mine.filter((n) => n.method === "error").map((n) => n.params),
- tokenUsage: mine.filter((n) => n.method === "thread/tokenUsage/updated").map((n) => n.params.tokenUsage).at(-1) ?? null,
- };
-}
-
-async function preview(server: AppServer, sourceId: string, selected: string[]) {
- const { resolveImage, attachmentPath } = loadAssets();
- const { thread, turns } = await sourceTurns(server, sourceId);
- const attachments = new Map(selected.map((id, i) => [id, i + 1]));
- const migration = buildMigration(turns, resolveImage, { sourceName: thread.name ?? thread.preview, attachments });
- const injectedBytes = Buffer.byteLength(JSON.stringify(migration.items), "utf8");
- const summary = {
- sourceThreadId: sourceId,
- sourceName: thread.name,
- sourceTurns: turns.length,
- injectedItems: migration.items.length,
- injectedBytes,
- imageOccurrences: migration.imageOccurrences,
- unresolvedImages: migration.unresolvedImages,
- assetsInHistory: migration.firstSeen.map(({ asset, turn, source }) => ({ assetId: asset.assetId, name: asset.name, turn, source, selected: attachments.has(asset.assetId) })),
- selected: selected.map((id) => ({ assetId: id, attachmentPath: attachmentPath(id) })),
- };
- writeFileSync(join(localRoot, "rebuild-preview.json"), JSON.stringify({ ...summary, items: migration.items }, null, 2));
- writeFileSync(join(localRoot, "rebuild-preview.md"), [
- "# 重建预览(仅本机)", "",
- "```json", JSON.stringify(summary, null, 2), "```", "",
- ...migration.items.map((item, i) => `## ${i + 1}. ${item.role}\n\n${item.content[0].text}\n`),
- ].join("\n"));
- return { thread, migration, summary, attachmentPath };
-}
-
-async function main(): Promise<void> {
- const command = process.argv[2];
- const effort = option("--effort", "medium");
- if (command === "preview" || command === "create") {
- const sourceId = option("--source");
- const selected = option("--select", "").split(",").filter(Boolean);
- const server = startServer(command === "preview" ? "preview" : "t4");
- try {
- await server.initialize();
- const { thread, migration, summary, attachmentPath } = await preview(server, sourceId, selected);
- console.log(JSON.stringify({ ...summary, selected: summary.selected.map((s) => s.assetId) }, null, 2));
- if (command === "preview") return;
- const started = await server.request<{ thread: Json }>("thread/start", {
- model: thread.model, cwd: thread.cwd, approvalPolicy: "never", sandbox: "read-only", ephemeral: false,
- });
- const threadId = started.thread.id;
- await server.request("thread/inject_items", { threadId, items: migration.items }, 120_000);
- const name = `[CAM测试] ${thread.name ?? "重建任务"}`;
- await server.request("thread/name/set", { threadId, name });
- const turn = await runTurn(server, threadId, attachmentInput(selected, attachmentPath, option("--prompt")), effort);
- const result = { createdAt: new Date().toISOString(), threadId, name, model: thread.model, effort, selected, preview: summary, turn };
- writeFileSync(join(localRoot, "t4-rebuild.json"), JSON.stringify(result, null, 2));
- console.log(JSON.stringify({ threadId, name, turn: { ...turn, agentText: turn.agentText.slice(0, 600) } }, null, 2));
- } finally {
- console.log(`app-server exit code: ${await server.stop()}`);
- }
- return;
- }
- if (command === "turn") {
- const threadId = option("--thread");
- const label = option("--label");
- const attach = option("--attach", "").split(",").filter(Boolean);
- const disabled = option("--disable", "").split(",").filter(Boolean);
- const { attachmentPath } = loadAssets();
- const server = startServer(`turn-${label}`, disabled.flatMap((feature) => ["--disable", feature]));
- try {
- await server.initialize();
- await server.request("thread/resume", { threadId, approvalPolicy: "never", sandbox: "read-only" }, 300_000);
- const turn = await runTurn(server, threadId, attachmentInput(attach, attachmentPath, option("--prompt")), effort);
- const result = { createdAt: new Date().toISOString(), threadId, label, attach, disabled, effort, turn };
- writeFileSync(join(localRoot, `turn-${label}.json`), JSON.stringify(result, null, 2));
- console.log(JSON.stringify({ label, turn: { ...turn, agentText: turn.agentText.slice(0, 800) } }, null, 2));
- } finally {
- console.log(`app-server exit code: ${await server.stop()}`);
- }
- return;
- }
- if (command === "probe") {
- const label = option("--label");
- const disabled = option("--disable", "").split(",").filter(Boolean);
- const configs = options("--config");
- const serverRequests: Json[] = [];
- const server = startServer(`probe-${label}`, [...disabled.flatMap((f) => ["--disable", f]), ...configs.flatMap((c) => ["-c", c])], serverRequests);
- try {
- await server.initialize();
- const { thread } = await server.request<{ thread: Json }>("thread/read", { threadId: option("--source"), includeTurns: false });
- const started = await server.request<{ thread: Json }>("thread/start", { model: thread.model, cwd: thread.cwd, approvalPolicy: "never", sandbox: "read-only", ephemeral: true });
- const turn = await runTurn(server, started.thread.id, [{ type: "text", text: option("--prompt"), text_elements: [] }], effort);
- const result = { createdAt: new Date().toISOString(), label, disabled, configs, ephemeralThreadId: started.thread.id, turn, serverRequests };
- writeFileSync(join(localRoot, `probe-${label}.json`), JSON.stringify(result, null, 2));
- console.log(JSON.stringify({ label, serverRequests: serverRequests.map((r) => r.method), turn: { ...turn, agentText: turn.agentText.slice(0, 800) } }, null, 2));
- } finally {
- console.log(`app-server exit code: ${await server.stop()}`);
- }
- return;
- }
- throw new Error("usage: rebuild.ts preview|create|turn|probe …");
-}
-
-await main();
diff --git a/spike/src/routes.test.ts b/spike/src/routes.test.ts
index 231b299..f385de1 100644
--- a/spike/src/routes.test.ts
+++ b/spike/src/routes.test.ts
@@ -7,14 +7,14 @@ 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);
+ const routes = await import("../../plugin/src/core/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);`;
+ const script = `import { registerRoute } from ${JSON.stringify(new URL("../../plugin/src/core/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);
@@ -37,7 +37,7 @@ test("registered providers retain their platform, origin, port, base path and qu
});
test("route registration refuses non-HTTP targets, embedded credentials and recursive engine routes", async () => {
- const routes = await import("../../plugin/src/routes.ts").catch(() => null);
+ const routes = await import("../../plugin/src/core/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"]) {
diff --git a/spike/src/scripts-smoke.ts b/spike/src/scripts-smoke.ts
index e44f12d..a0bb9d7 100644
--- a/spike/src/scripts-smoke.ts
+++ b/spike/src/scripts-smoke.ts
@@ -10,9 +10,9 @@ import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
-import { findCodexCli } from "../../plugin/src/codexcli.ts";
+import { findCodexCli } from "../../plugin/src/adapters/codex/codexcli.ts";
import { buildOf, engineHealth } from "../../plugin/src/engine.ts";
-import { MARKETPLACE, PLUGIN, pluginStatus } from "../../plugin/src/install.ts";
+import { MARKETPLACE, PLUGIN, pluginStatus } from "../../plugin/src/adapters/codex/install.ts";
type Json = Record<string, any>;
const root = resolve(import.meta.dirname, "..", "..");
diff --git a/spike/src/selection.test.ts b/spike/src/selection.test.ts
index 78b88f6..61199e0 100644
--- a/spike/src/selection.test.ts
+++ b/spike/src/selection.test.ts
@@ -7,7 +7,7 @@ import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { hasUnchecked, needsRewrite } from "../../plugin/src/proxy.ts";
+import { needsRewrite } from "../../plugin/src/proxy.ts";
import { autoDefaultSince, effectiveSelection, ensureAutoDefault, ensureStableIds, mainTaskOf, readSelection, sideChatSelection, stableIdsSince, writeSelection } from "../../plugin/src/selection.ts";
import { startThread } from "./testfixtures.ts";
@@ -38,7 +38,7 @@ test("a fork takes what its parent had unchecked by the time of the fork, and ke
assert.deepEqual(Object.values(fork.unchecked).map((entry) => entry.id), ["IMG-001"], "IMG-002 was unchecked after the fork");
assert.equal(fork.inheritedFrom, PARENT);
assert.equal(existsSync(join(dir, `${FORK}.json`)), true);
- assert.equal(hasUnchecked(FORK, dir, sessionsDir), true);
+ assert.equal(needsRewrite(FORK, dir, sessionsDir), true);
});
test("after the fork the two selections are independent", () => {
@@ -56,7 +56,7 @@ test("a fork of a fork asks its own parent; ordinary threads stay empty and get
assert.deepEqual(Object.values(effectiveSelection(FORK2, sessionsDir, dir).unchecked).map((entry) => entry.id), ["IMG-001"]);
assert.deepEqual(effectiveSelection(PLAIN, sessionsDir, dir).unchecked, {});
assert.equal(existsSync(join(dir, `${PLAIN}.json`)), false);
- assert.equal(hasUnchecked(PLAIN, dir, sessionsDir), false);
+ assert.equal(needsRewrite(PLAIN, dir, sessionsDir), false);
});
test("a thread whose rollout is not written yet is looked up again later", () => {
diff --git a/spike/src/setup.test.ts b/spike/src/setup.test.ts
index b9cfc01..a467d0f 100644
--- a/spike/src/setup.test.ts
+++ b/spike/src/setup.test.ts
@@ -9,8 +9,8 @@ import { tmpdir } from "node:os";
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 { connectDirectly, pluginGone, useEngine, usesEngine } from "../../plugin/src/adapters/codex/setup.ts";
+import * as setup from "../../plugin/src/adapters/codex/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
diff --git a/spike/src/t3-connect.ts b/spike/src/t3-connect.ts
deleted file mode 100644
index d9a34d5..0000000
--- a/spike/src/t3-connect.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-// Purpose: T3 — start an independent app-server with the desktop-bundled codex.exe and make read-only calls.
-// Input: --threads <id,id>; output: local/t3-connect.json (thread metadata only, no conversation content).
-
-import { execFileSync } from "node:child_process";
-import { mkdirSync, writeFileSync } from "node:fs";
-import { dirname, join, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-import { AppServer, findBundledCodex } from "./appserver.ts";
-
-const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
-
-function argument(name: string): string {
- const index = process.argv.indexOf(name);
- const value = process.argv[index + 1];
- if (index < 0 || !value) throw new Error(`missing ${name}`);
- return value;
-}
-
-function summary(thread: Record<string, any>): Record<string, unknown> {
- const { id, name, forkedFromId, historyMode, modelProvider, model, reasoningEffort, status, cliVersion, source, originator, createdAt, updatedAt, ephemeral, cwd } = thread;
- return { id, name, preview: String(thread.preview ?? "").slice(0, 40), forkedFromId, historyMode, modelProvider, model, reasoningEffort, status, cliVersion, source, originator, createdAt, updatedAt, ephemeral, cwd };
-}
-
-async function main(): Promise<void> {
- const threadIds = argument("--threads").split(",").filter(Boolean);
- const codex = findBundledCodex();
- const codexVersion = execFileSync(codex, ["--version"]).toString().trim();
- mkdirSync(join(localRoot, "logs"), { recursive: true });
- const stamp = new Date().toISOString().replaceAll(":", "-");
- const server = new AppServer(codex, [], {}, join(localRoot, "logs", `t3-appserver-${stamp}.log`));
- try {
- const init = await server.initialize();
- const threads = [];
- for (const threadId of threadIds) {
- const response = await server.request<{ thread: Record<string, any> }>("thread/read", { threadId, includeTurns: false });
- threads.push(summary(response.thread));
- }
- const listedIds: string[] = [];
- let cursor: string | null = null;
- let pages = 0;
- do {
- const page: { data: Array<{ id: string }>; nextCursor: string | null } = await server.request("thread/list", { cursor, limit: 100 });
- listedIds.push(...page.data.map((thread) => thread.id));
- cursor = page.nextCursor;
- pages++;
- } while (cursor && pages < 20 && !threadIds.every((id) => listedIds.includes(id)));
- const result = {
- createdAt: new Date().toISOString(),
- codexVersion,
- platformFamily: init.platformFamily,
- threads,
- listed: Object.fromEntries(threadIds.map((id) => [id, listedIds.includes(id)])),
- listPagesScanned: pages,
- notificationsSeen: [...new Set(server.notifications.map((n) => n.method))],
- };
- writeFileSync(join(localRoot, "t3-connect.json"), JSON.stringify(result, null, 2));
- console.log(JSON.stringify({ ...result, threads: threads.map(({ cwd, ...rest }) => rest) }, null, 2));
- } finally {
- console.log(`app-server exit code: ${await server.stop()}`);
- }
-}
-
-await main();
diff --git a/spike/src/t7-calibrate.ts b/spike/src/t7-calibrate.ts
deleted file mode 100644
index 2a02c21..0000000
--- a/spike/src/t7-calibrate.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-// Purpose: T7 prerequisite — check that the rollout-based request estimate matches real request sizes
-// that Codex logged (pre_compression_bytes) for the sample threads.
-// Input: --sessions <dir>; sample thread ids and logged sizes come from local/sample.json (never committed).
-// Output: local/t7-calibration.json and a console table.
-
-import { readFileSync, writeFileSync } from "node:fs";
-import { dirname, join, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-import { effectiveRecords, historyBytes, indexSegments, inlineImages, latestSegment, type RolloutRecord } from "./history.ts";
-
-type CalibrationCase = { name: string; thread: "original" | "fork"; segment: "fork" | "latest"; lastLine: number | null; logged: number };
-const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
-
-function argument(name: string): string {
- const index = process.argv.indexOf(name);
- if (index < 0 || !process.argv[index + 1]) throw new Error(`missing ${name}`);
- return process.argv[index + 1];
-}
-
-// Keep inherited records plus the named segment's records up to and including `lastLine`.
-function upTo(records: RolloutRecord[], segmentFileSuffix: string, lastLine: number): RolloutRecord[] {
- return records.filter((record) => !record.file.endsWith(segmentFileSuffix) || record.line <= lastLine);
-}
-
-function main(): void {
- const sample = JSON.parse(readFileSync(join(localRoot, "sample.json"), "utf8"));
- const threads: Record<string, string> = { original: sample.originalThreadId, fork: sample.forkThreadId };
- const segments = indexSegments(argument("--sessions"));
- const rows = (sample.calibration as CalibrationCase[]).map(({ name, thread, segment, lastLine, logged }) => {
- const threadId = threads[thread];
- const segmentId = segment === "latest" ? latestSegment(segments, threadId) : threadId;
- const all = effectiveRecords(segments, segmentId);
- const records = lastLine === null ? all : upTo(all, `${threadId}.jsonl`, lastLine);
- const { items, bytes } = historyBytes(records);
- const images = inlineImages(records);
- return {
- name,
- logged,
- historyItems: items,
- historyBytes: bytes,
- overheadBytes: logged - bytes,
- ratio: Number((bytes / logged).toFixed(4)),
- inlineImages: images.length,
- inlineImageDataUrlBytes: images.reduce((sum, image) => sum + image.dataUrlChars, 0),
- };
- });
- writeFileSync(join(localRoot, "t7-calibration.json"), JSON.stringify({ createdAt: new Date().toISOString(), rows }, null, 2));
- console.table(rows);
-}
-
-main();
diff --git a/spike/src/t7-measure.ts b/spike/src/t7-measure.ts
deleted file mode 100644
index e2f2b09..0000000
--- a/spike/src/t7-measure.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-// Purpose: T7 — measure the rebuilt thread: which images its history carries and how large each request was,
-// using the rollout-based estimate calibrated against real logged request sizes (see t7-calibrate.ts).
-// Input: --sessions <dir>; the rebuilt thread comes from local/t4-rebuild.json, later attachments from local/turn-*.json,
-// assets from local/assets.json and the baseline from local/sample.json.
-// Output: local/t7-measure.json and a console table.
-
-import { readdirSync, readFileSync, writeFileSync } from "node:fs";
-import { dirname, join, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-import { effectiveRecords, historyBytes, indexSegments, inlineImages, latestSegment, type RolloutRecord } from "./history.ts";
-
-type Json = Record<string, any>;
-const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
-
-function argument(name: string): string {
- const index = process.argv.indexOf(name);
- if (index < 0 || !process.argv[index + 1]) throw new Error(`missing ${name}`);
- return process.argv[index + 1];
-}
-
-const isModelOutput = (record: RolloutRecord) =>
- record.type === "response_item" &&
- (record.payload.type === "reasoning" || (record.payload.type === "message" && record.payload.role === "assistant") || /call$/.test(record.payload.type ?? ""));
-
-function main(): void {
- const rebuilt: Json = JSON.parse(readFileSync(join(localRoot, "t4-rebuild.json"), "utf8"));
- const inventory: Json = JSON.parse(readFileSync(join(localRoot, "assets.json"), "utf8"));
- const assetByHash = new Map<string, string>();
- for (const asset of inventory.assets) for (const hash of asset.byteHashes) assetByHash.set(hash, asset.assetId);
-
- const segments = indexSegments(argument("--sessions"));
- const records = effectiveRecords(segments, latestSegment(segments, rebuilt.threadId));
-
- // First request of each turn = every history item recorded before the model's first output in that turn.
- const requests: Array<{ turn: number; historyItems: number; historyBytes: number; inlineImages: string[] }> = [];
- let turn = 0;
- let awaitingFirstOutput = false;
- for (const [index, record] of records.entries()) {
- if (record.type === "event_msg" && record.payload.type === "task_started") { turn++; awaitingFirstOutput = true; continue; }
- if (awaitingFirstOutput && isModelOutput(record)) {
- const before = records.slice(0, index);
- const { items, bytes } = historyBytes(before);
- requests.push({ turn, historyItems: items, historyBytes: bytes, inlineImages: inlineImages(before).map((image) => assetByHash.get(image.sha256) ?? `new:${image.sha256.slice(0, 8)}`) });
- awaitingFirstOutput = false;
- }
- }
- const final = historyBytes(records);
- const images = inlineImages(records).map((image) => ({ asset: assetByHash.get(image.sha256) ?? "not in index (resized or generated)", sha256: image.sha256.slice(0, 12), bytes: image.bytes, dataUrlBytes: image.dataUrlChars }));
- const carried = new Set(images.map((image) => image.asset));
- // Every asset ever attached: the rebuild selection plus any later turn's attachments on this thread.
- const attached = new Set<string>(rebuilt.selected);
- for (const file of readdirSync(localRoot).filter((name) => /^turn-.+\.json$/.test(name))) {
- const turn: Json = JSON.parse(readFileSync(join(localRoot, file), "utf8"));
- if (turn.threadId === rebuilt.threadId) for (const id of turn.attach ?? []) attached.add(id);
- }
- const neverSelected = inventory.assets.map((asset: Json) => asset.assetId).filter((id: string) => !attached.has(id));
- const sample: Json = JSON.parse(readFileSync(join(localRoot, "sample.json"), "utf8"));
- const result = {
- createdAt: new Date().toISOString(),
- threadId: rebuilt.threadId,
- requests,
- finalHistory: { items: final.items, bytes: final.bytes },
- inlineImages: images,
- neverSelected,
- unselectedCarried: neverSelected.filter((id: string) => carried.has(id)),
- attached: [...attached],
- baselineLoggedBytes: Math.max(...sample.calibration.map((c: Json) => c.logged)),
- };
- writeFileSync(join(localRoot, "t7-measure.json"), JSON.stringify(result, null, 2));
- console.table(requests.map((r) => ({ ...r, inlineImages: r.inlineImages.join(" "), vsBaseline: `${((r.historyBytes / result.baselineLoggedBytes) * 100).toFixed(1)}%` })));
- console.table(images);
- console.log(JSON.stringify({ finalHistory: result.finalHistory, neverSelected, unselectedCarried: result.unselectedCarried }));
-}
-
-main();
diff --git a/spike/src/t9c-handoff.ts b/spike/src/t9c-handoff.ts
deleted file mode 100644
index 6747599..0000000
--- a/spike/src/t9c-handoff.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-// Purpose: T9c — build a route B handoff package: the migrated conversation as Markdown plus copies of the selected images,
-// for a user who starts a new Codex task by hand.
-// Input: local/rebuild-preview.json (from `rebuild.ts preview`) and local/matches.json. Output: local/handoff/<stamp>/.
-
-import { copyFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
-import { dirname, extname, join, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-
-const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
-
-function main(): void {
- const preview = JSON.parse(readFileSync(join(localRoot, "rebuild-preview.json"), "utf8"));
- const stamp = new Date().toISOString().replaceAll(":", "-").slice(0, 19);
- const out = join(localRoot, "handoff", stamp);
- mkdirSync(out, { recursive: true });
- const files = preview.selected.map((selected: { assetId: string; attachmentPath: string }) => {
- const name = `${selected.assetId}${extname(selected.attachmentPath)}`;
- copyFileSync(selected.attachmentPath, join(out, name));
- return name;
- });
- const roleLabel: Record<string, string> = { developer: "说明", user: "用户", assistant: "助手" };
- const markdown = [
- `# 交接包:${preview.sourceName}`,
- "",
- "使用方法:在 Codex 里新建任务,把本文件和下列图片一起附上,然后告诉 Codex“先读交接说明,再继续原任务”。",
- "",
- `随附图片:${files.map((file: string) => `\`${file}\``).join("、")}(附件编号按这个顺序:${files.map((file: string, i: number) => `附件 ${i + 1} = ${file.replace(extname(file), "")}`).join(",")})`,
- "",
- ...preview.items.map((item: { role: string; content: Array<{ text: string }> }) => `## ${roleLabel[item.role] ?? item.role}\n\n${item.content[0].text}\n`),
- ].join("\n");
- writeFileSync(join(out, "交接说明.md"), markdown);
- const bytes = statSync(join(out, "交接说明.md")).size;
- console.log(JSON.stringify({ folder: `local/handoff/${stamp}`, files: ["交接说明.md", ...files], markdownBytes: bytes }, null, 2));
-}
-
-main();
diff --git a/spike/src/thread-index.test.ts b/spike/src/thread-index.test.ts
index 2f6e91e..8d7327e 100644
--- a/spike/src/thread-index.test.ts
+++ b/spike/src/thread-index.test.ts
@@ -12,7 +12,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { zstdCompressSync } from "node:zlib";
-import { buildIndex, forkOrigin, hasRollout, loadThreadIndex, readThreadHistory, setPixelCache, spawnParent, threadStartedAt, threadsStartedSince } from "../../plugin/src/thread-index.ts";
+import { buildIndex, forkOrigin, hasRollout, loadThreadIndex, readThreadHistory, setPixelCache, spawnParent, threadStartedAt, threadsStartedSince } from "../../plugin/src/adapters/codex/thread-index.ts";
import { startThread, todayFolder } from "./testfixtures.ts";
import { png } from "./testkit.ts";
diff --git a/spike/src/thread-names.test.ts b/spike/src/thread-names.test.ts
index 232cb8d..296c58c 100644
--- a/spike/src/thread-names.test.ts
+++ b/spike/src/thread-names.test.ts
@@ -7,7 +7,7 @@ import { appendFileSync, mkdirSync, mkdtempSync, renameSync, writeFileSync } fro
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import test from "node:test";
-import { firstMessage, sessionIndexOf, threadName, threadTitle } from "../../plugin/src/thread-names.ts";
+import { firstMessage, sessionIndexOf, threadName, threadTitle } from "../../plugin/src/adapters/codex/thread-names.ts";
const A = "01a0d301-0000-7000-8000-0000000000a1";
const B = "01a0d301-0000-7000-8000-0000000000b2";
diff --git a/spike/src/v01-needs-selftest.ts b/spike/src/v01-needs-selftest.ts
index ee83d56..a2eebd3 100644
--- a/spike/src/v01-needs-selftest.ts
+++ b/spike/src/v01-needs-selftest.ts
@@ -16,14 +16,14 @@ import { dirname, join, resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { AppServer, findBundledCodex } from "./appserver.ts";
-import { codexHome } from "../../plugin/src/codexconfig.ts";
+import { codexHome } from "../../plugin/src/adapters/codex/codexconfig.ts";
import { engineHealth } from "../../plugin/src/engine.ts";
import { languageFileOf, rememberLang } from "../../plugin/src/language.ts";
-import { askedIn } from "../../plugin/src/panel-state.ts";
-import { selectionDirOf } from "../../plugin/src/paths.ts";
-import { readRequestStats } from "../../plugin/src/request-stats.ts";
+import { askedIn } from "../../plugin/src/panel/panel-state.ts";
+import { selectionDirOf } from "../../plugin/src/core/paths.ts";
+import { readRequestStats } from "../../plugin/src/core/request-stats.ts";
import { writeSelection } from "../../plugin/src/selection.ts";
-import { loadThreadIndex } from "../../plugin/src/thread-index.ts";
+import { loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
import { archiveThreads, png, runTurn, TEST_EFFORT, TEST_MODEL, text } from "./testkit.ts";
type Json = Record<string, any>;
diff --git a/spike/src/v01-placeholder-selftest.ts b/spike/src/v01-placeholder-selftest.ts
index daebf03..c1cec48 100644
--- a/spike/src/v01-placeholder-selftest.ts
+++ b/spike/src/v01-placeholder-selftest.ts
@@ -15,14 +15,14 @@ import { dirname, join, resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { AppServer, findBundledCodex } from "./appserver.ts";
-import { codexHome } from "../../plugin/src/codexconfig.ts";
+import { codexHome } from "../../plugin/src/adapters/codex/codexconfig.ts";
import { engineHealth } from "../../plugin/src/engine.ts";
import { languageFileOf, rememberLang } from "../../plugin/src/language.ts";
-import { selectionDirOf } from "../../plugin/src/paths.ts";
-import { readRequestStats } from "../../plugin/src/request-stats.ts";
+import { selectionDirOf } from "../../plugin/src/core/paths.ts";
+import { readRequestStats } from "../../plugin/src/core/request-stats.ts";
import { writeSelection } from "../../plugin/src/selection.ts";
import { archiveThreads, runTurn, TEST_EFFORT, TEST_MODEL, testImages, text } from "./testkit.ts";
-import { loadThreadIndex } from "../../plugin/src/thread-index.ts";
+import { loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
type Json = Record<string, any>;
const here = dirname(fileURLToPath(import.meta.url));
diff --git a/spike/src/v03-auto-selftest.ts b/spike/src/v03-auto-selftest.ts
index 4a1086e..b6588b3 100644
--- a/spike/src/v03-auto-selftest.ts
+++ b/spike/src/v03-auto-selftest.ts
@@ -22,13 +22,13 @@ import { dirname, join, resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { AppServer, findBundledCodex } from "./appserver.ts";
-import { codexHome } from "../../plugin/src/codexconfig.ts";
+import { codexHome } from "../../plugin/src/adapters/codex/codexconfig.ts";
import { engineHealth } from "../../plugin/src/engine.ts";
import { languageFileOf, rememberLang, type Lang } from "../../plugin/src/language.ts";
-import { requestStatsDirOf, selectionDirOf } from "../../plugin/src/paths.ts";
-import { readRequestStats } from "../../plugin/src/request-stats.ts";
+import { requestStatsDirOf, selectionDirOf } from "../../plugin/src/core/paths.ts";
+import { readRequestStats } from "../../plugin/src/core/request-stats.ts";
import { writeSelection } from "../../plugin/src/selection.ts";
-import { loadThreadIndex } from "../../plugin/src/thread-index.ts";
+import { loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
import { archiveThreads, CORNER_IMAGES, runTurn, says, TEST_EFFORT, TEST_MODEL, text } from "./testkit.ts";
type Json = Record<string, any>;
diff --git a/spike/src/v07-children-selftest.ts b/spike/src/v07-children-selftest.ts
index cf309b7..9e0c5e8 100644
--- a/spike/src/v07-children-selftest.ts
+++ b/spike/src/v07-children-selftest.ts
@@ -19,13 +19,13 @@ import { dirname, join, resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { AppServer, findBundledCodex } from "./appserver.ts";
-import { codexHome } from "../../plugin/src/codexconfig.ts";
+import { codexHome } from "../../plugin/src/adapters/codex/codexconfig.ts";
import { engineHealth } from "../../plugin/src/engine.ts";
import { languageFileOf, rememberLang, type Lang } from "../../plugin/src/language.ts";
-import { loadPanelState } from "../../plugin/src/panel-state.ts";
-import { requestStatsDirOf } from "../../plugin/src/paths.ts";
-import { readRequestStats } from "../../plugin/src/request-stats.ts";
-import { loadThreadIndex, threadsStartedSince } from "../../plugin/src/thread-index.ts";
+import { loadPanelState } from "../../plugin/src/panel/panel-state.ts";
+import { requestStatsDirOf } from "../../plugin/src/core/paths.ts";
+import { readRequestStats } from "../../plugin/src/core/request-stats.ts";
+import { loadThreadIndex, threadsStartedSince } from "../../plugin/src/adapters/codex/thread-index.ts";
import { archiveThreads, CORNER_IMAGES, runTurn, says, TEST_EFFORT, TEST_MODEL, text } from "./testkit.ts";
type Json = Record<string, any>;
diff --git a/spike/src/v08-features-selftest.ts b/spike/src/v08-features-selftest.ts
index a15ad38..13b99f9 100644
--- a/spike/src/v08-features-selftest.ts
+++ b/spike/src/v08-features-selftest.ts
@@ -6,7 +6,7 @@
// Set up like v03-auto-selftest.ts: a test engine of this checkout (its own port and data folder, --dump-requests for
// the bodies it sent), this checkout's plugin server attached to the test app-server for cam_view_image, the tools that
// act on the machine off, a read-only sandbox, the tasks archived at the end. Automatic selection is on by default
-// (v0.6), so no switch is set. The compaction is Codex's own (thread/compact/start), as p3-selftest.ts does it.
+// (v0.6), so no switch is set. The compaction is Codex's own (thread/compact/start).
// Thread F: an upload; an upload and an image opened with the image viewer; the user's ratings; a question about all
// three, answered from their placeholders. Thread K: a character's medium shot; two other assets; the close-up the user
// calls the best; a compaction; which image to take for the facial features; what the other two look like.
@@ -22,11 +22,11 @@ import { dirname, join, resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { AppServer, findBundledCodex } from "./appserver.ts";
-import { codexHome } from "../../plugin/src/codexconfig.ts";
+import { codexHome } from "../../plugin/src/adapters/codex/codexconfig.ts";
import { engineHealth } from "../../plugin/src/engine.ts";
import { languageFileOf, rememberLang, type Lang } from "../../plugin/src/language.ts";
-import { sceneOf } from "../../plugin/src/notes.ts";
-import { loadThreadIndex } from "../../plugin/src/thread-index.ts";
+import { sceneOf } from "../../plugin/src/core/notes.ts";
+import { loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
import { archiveThreads, CORNER_IMAGES, png, runTurn, TEST_EFFORT, TEST_MODEL, text } from "./testkit.ts";
type Json = Record<string, any>;
diff --git a/spike/src/v10-compaction-selftest.ts b/spike/src/v10-compaction-selftest.ts
index 2185c66..f64d068 100644
--- a/spike/src/v10-compaction-selftest.ts
+++ b/spike/src/v10-compaction-selftest.ts
@@ -16,10 +16,10 @@ import { dirname, join, resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { AppServer, findBundledCodex } from "./appserver.ts";
-import { codexHome } from "../../plugin/src/codexconfig.ts";
+import { codexHome } from "../../plugin/src/adapters/codex/codexconfig.ts";
import { engineHealth } from "../../plugin/src/engine.ts";
import { languageFileOf, rememberLang, type Lang } from "../../plugin/src/language.ts";
-import { loadThreadIndex } from "../../plugin/src/thread-index.ts";
+import { loadThreadIndex } from "../../plugin/src/adapters/codex/thread-index.ts";
import { archiveThreads, CORNER_IMAGES, png, runTurn, says, TEST_EFFORT, TEST_MODEL, text } from "./testkit.ts";
type Json = Record<string, any>;
diff --git a/spike/src/viewpaths.test.ts b/spike/src/viewpaths.test.ts
deleted file mode 100644
index 135176f..0000000
--- a/spike/src/viewpaths.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-// Purpose: regression test for view_image path attribution when parallel calls finish out of order.
-// Input: temporary synthetic files; output: Node test assertions only.
-
-import assert from "node:assert/strict";
-import { createHash } from "node:crypto";
-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import test from "node:test";
-import { pathForViewedImage } from "./viewpaths.ts";
-
-const sha256 = (data: string) => createHash("sha256").update(data).digest("hex");
-
-test("each output image gets the path whose bytes match, whatever the event order", async () => {
- const dir = mkdtempSync(join(tmpdir(), "cam-viewpaths-"));
- try {
- const bridge = join(dir, "bridge.png");
- const timelapse = join(dir, "timelapse.png");
- writeFileSync(bridge, "bridge-bytes");
- writeFileSync(timelapse, "timelapse-bytes");
- // Events arrived as [bridge, timelapse] while the tool output listed timelapse first.
- const candidates = [bridge, timelapse];
- const cache = new Map<string, string | null>();
- assert.equal(await pathForViewedImage(candidates, sha256("timelapse-bytes"), cache), timelapse);
- assert.equal(await pathForViewedImage(candidates, sha256("bridge-bytes"), cache), bridge);
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
-});
-
-test("an image whose bytes match no candidate gets no path", async () => {
- const dir = mkdtempSync(join(tmpdir(), "cam-viewpaths-"));
- try {
- const only = join(dir, "only.png");
- writeFileSync(only, "only-bytes");
- assert.equal(await pathForViewedImage([only, join(dir, "missing.png")], sha256("resized-bytes"), new Map()), null);
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
-});
diff --git a/spike/src/viewpaths.ts b/spike/src/viewpaths.ts
deleted file mode 100644
index cab3b8d..0000000
--- a/spike/src/viewpaths.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-// Purpose: attribute a view_image output image to the file it came from.
-// Input: candidate paths from the same call's ImageView events and the image's byte SHA-256.
-// Output: the matching path, or null when no candidate file has the same bytes.
-
-import { createHash } from "node:crypto";
-import { createReadStream, existsSync } from "node:fs";
-
-export async function fileSha256(file: string): Promise<string> {
- const hash = createHash("sha256");
- for await (const chunk of createReadStream(file)) hash.update(chunk);
- return hash.digest("hex");
-}
-
-// Parallel view_image calls complete out of order, so event order cannot be trusted for pairing.
-export async function pathForViewedImage(candidates: string[], byteSha256: string, fileHashes: Map<string, string | null>): Promise<string | null> {
- for (const candidate of candidates) {
- if (!fileHashes.has(candidate)) fileHashes.set(candidate, existsSync(candidate) ? await fileSha256(candidate) : null);
- if (fileHashes.get(candidate) === byteSha256) return candidate;
- }
- return null;
-}