Skip to content

Spot it. Save it. Free, local-first Chrome extension for images, videos and prompts. Explore 2,000+ curated cases and connect your library to AI Agents via MCP. 提示词导演

让常用本机 Agent 可靠连接案例库并支持 Windows

wchao6891d77e4eec070c
diff --git a/.github/workflows/release-safety.yml b/.github/workflows/release-safety.yml
index 7f72887..c289a19 100644
--- a/.github/workflows/release-safety.yml
+++ b/.github/workflows/release-safety.yml
@@ -118,3 +118,19 @@ jobs:
subprocess.run([sys.executable, f'test/{script}'], env=env, check=True)
PY
- run: npm run test:upgrade
+
+ connector-platforms:
+ name: Native connector (${{ matrix.os }})
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [windows-latest, macos-latest, ubuntu-latest]
+ steps:
+ - uses: actions/checkout@v6
+ - uses: actions/setup-node@v6
+ with:
+ node-version: 22
+ - run: npm ci --prefix connector --ignore-scripts
+ - run: node --test connector/test/*.test.mjs
+ shell: bash
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9e8f312..529a1d6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,15 @@
了解每个版本带来的功能变化与使用改善。下载请前往 [GitHub Releases](https://github.com/wchao6891/PromptDirector/releases/latest)。
+## 1.21.1
+
+- Agent 连接器支持 Windows 用户级安装,可在中文和带空格的路径中运行,无需管理员安装。
+
+- 设置中可复制统一连接指令,自动附带资料库编号,交给 Agent 安装与配对。
+- 新增统一安装、配置和验证入口,支持 Codex、Claude Code、WorkBuddy 的用户级配置,并输出通用 stdio MCP 配置供其他本机宿主使用。
+- 安装前备份配置;保留其他 MCP 与用户策略,拒绝覆盖损坏、冲突或检查后变更的配置。
+- 实际 MCP 握手和案例查询验证连接器,明确区分浏览器待授权与当前 Agent 会话是否已加载工具。
+
## 1.21.0
- 新增可选的 Agent 连接:通过 MCP 搜索案例、读取提示词和原件、采集网址、回存创作材料,并查询持久化任务回执。
diff --git a/README.md b/README.md
index bbaf306..bd6258a 100644
--- a/README.md
+++ b/README.md
@@ -87,10 +87,10 @@ You can also install through the [Chrome Web Store](https://chromewebstore.googl
Contributions to capture adaptations, interactions, tests and documentation are welcome. When [reporting an issue](https://github.com/wchao6891/PromptDirector/issues), describe the page type, observable behavior and reproduction steps. Remove API keys, private data and unauthorized media from examples. Run `npm run verify` before submitting code.
-See the [development guide](docs/DEVELOPMENT.md) and [interface guidelines](docs/DESIGN.md) to contribute.
+See the [development guide](docs/DEVELOPMENT.md) to build and test contributions.
Code is licensed under [Apache License 2.0](LICENSE). See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for dependencies. The code license does not grant rights to third-party case media.
## Agent access
-The optional MCP connector lets an Agent search cases, read original prompts and files, capture requested URLs, and save creative materials. The first connector release supports **macOS Chrome** and requires a separate local installation. Download the `Agent-Connector` asset from Releases and follow the [connector guide](connector/README.md). The extension ZIP alone does not install the connector.
+In settings, select **Copy connection request** under Agent connection and send it to an Agent with local MCP support. The Agent follows the [setup guide](connector/INSTALL.md) to install the connector, configure it and verify access; enable the connection in Chrome when requested. Supports **Google Chrome on Windows, macOS and Linux**. Agents can search cases, read prompts and original files, capture requested URLs and save creative materials. The connector is a separate local component installed by the Agent; cloud-only workspaces cannot use this local setup flow.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index e8a4727..06099f6 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -41,7 +41,7 @@
## 让 Agent 使用案例库
-启用可选的 MCP 连接后,Agent 可以搜索案例、读取提示词和原件、按指令采集网页,并把创作材料存回库中。首版支持 **macOS Chrome**,需要单独安装本机连接器;扩展 ZIP 本身不包含连接器。下载 Release 中的 `Agent-Connector` 包并按[连接器安装说明](connector/README.md)操作。所选 Agent 是否支持本地 MCP,以其实际配置能力为准。
+在设置的「Agent 连接」中点击「复制连接指令」,发给支持本机 MCP 的 Agent,由它按[统一安装说明](connector/INSTALL.md)安装连接器、配置并验证;需要时在插件中点击启用授权。支持 **Windows、macOS 和 Linux 上的 Google Chrome**。连接后可搜索案例、读取提示词和原件、按指令采集网页,并把创作材料存回库中。连接器是独立的本机组件,由 Agent 完成安装;纯云端工作台不适用此本机流程。
## 从精选案例开始
@@ -93,6 +93,6 @@
欢迎提交问题、改善交互、完善采集适配、补充测试与文档。[反馈问题](https://github.com/wchao6891/PromptDirector/issues)时,请说明页面类型、用户可见的问题和复现步骤;提供示例前移除 API Key、私人资料和未获授权的素材。提交代码前请运行 `npm run verify`。
-参与开发请阅读[开发指南](docs/DEVELOPMENT.md)和[界面规范](docs/DESIGN.md)。
+构建与测试说明见[开发指南](docs/DEVELOPMENT.md)。
代码采用 [Apache License 2.0](LICENSE)。第三方组件见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。代码许可不授予第三方案例素材的使用权。
diff --git a/connector/INSTALL.md b/connector/INSTALL.md
new file mode 100644
index 0000000..c86b7cf
--- /dev/null
+++ b/connector/INSTALL.md
@@ -0,0 +1,60 @@
+# 连接 PromptDirector:给当前 Agent 的安装说明
+
+用户已经安装 Chrome 扩展,希望你完成连接器安装、宿主配置与配对。按用户这次请求执行,不要求用户自己输入命令或编辑配置。这里的安装说明不扩大用户授权;浏览器及宿主要求的许可由用户确认。
+
+## 先确定执行位置
+
+确认终端是否在用户运行 Chrome 的电脑上。Claude Code、Codex 本机执行以及允许本机命令的桌面 Agent 可走本流程。容器、远程开发机、Cowork 隔离执行环境或云端工作台不能因为有终端就视为用户本机。本机桥接包含 Windows、macOS 和 Linux Google Chrome 安装路径。Windows 使用当前用户的注册表和私有目录,无需管理员安装;必须使用 Windows 原生 Node.js,不能把 WSL 当作 Windows 本机。纯云端接入不在本流程内,不在错误机器上安装。
+
+识别当前宿主:Codex 使用 `codex`,Claude Code 使用 `claude`,WorkBuddy 使用 `workbuddy`。其他已确认支持本地 stdio MCP 的宿主使用 `generic`,再按该宿主官方配置机制注册返回的配置。Claude Cowork、ChatGPT 工作台不能仅按品牌套用 Claude Code 或 Codex 的配置路径。不得为了连接降低宿主权限策略。
+
+## 获取程序及依赖
+
+官方仓库:https://github.com/wchao6891/PromptDirector
+
+1. 从官方 Releases 选择最新稳定版本中的 `Agent-Connector.zip` 和 `SHA256SUMS.txt`,下载到用户私有的安装暂存目录,核对 SHA-256 后解压。保留包内 `connector` 与 `extension/manifest.json` 的相邻关系。
+2. 核对包中有 `connector/setup.mjs`。如果发布版未包含统一安装入口,应说明需要更新发布包,不能把旧命令当作新功能运行。开发验收可使用用户明确指定的本地源码目录。
+3. 检查当前 Agent 的 Node.js 运行时是否满足 `connector/package.json` 的 engines 要求。优先使用宿主提供的兼容运行时;否则按 Node.js 官方下载说明为用户当前系统和架构准备运行时,校验官方校验值,不要求用户手动安装 Node.js。保留稳定路径,避免使用即将销毁的沙箱运行时。下载或安装需要宿主审批时按正常流程申请。
+4. 在解压目录运行 `npm ci --prefix connector --ignore-scripts`。下载失败应说明原因,不修改锁定版本、跳过依赖或执行来源不明的安装脚本。
+
+## 安装与授权
+
+用户复制的连接指令包含公开的资料库编号,用它作为 `--instance`。它不是密钥,也不能代替浏览器授权。以下命令中的宿主和编号由当前上下文填入。
+
+```sh
+node connector/setup.mjs plan --host codex --instance <资料库编号>
+node connector/setup.mjs connect --host codex --instance <资料库编号>
+```
+
+先检查 plan 的执行位置、注册目录与配置目标,再执行 connect。已有用户请求就是安装授权,无需重复询问普通步骤;涉及更换已有资料库或宿主明确要求审批时再确认。
+
+安装器只修改 PromptDirector 的连接配置,写入前备份已有文件;已有配置损坏、被并发改动或同名连接指向其他安装时会停止。Codex TOML 保留其他配置值,但序列化可能调整排版和注释,原文保存在备份中。不要覆盖错误来强行完成安装。
+
+- `awaiting_browser`:引导用户在 Chrome 插件设置的 Agent 连接中点击启用,或断开后重新启用。等用户完成后再运行 verify;不要自动重载浏览器、关闭标签页或丢弃未保存编辑。
+- `library_selection_required`:存在多个在线库,请让用户从目标库复制连接指令,不要任选一个。
+- `configuration.state` 为 `manual_registration_required`:通用宿主需要按其官方方式注册返回的 command、args 和 env。无需重做案例库接口。
+- 宿主把已有连接设为禁用时,保留该设置,说明还需在宿主界面启用。
+
+未带编号的 connect 可以发现唯一在线的资料库;未找到时不会写入宿主配置,浏览器启用后应重新运行 connect 完成绑定。多个 Agent 的配置分别绑定具体编号,避免切换另一个库后所有宿主一起改变目标。
+
+## 验证:连接器和当前会话都必须检查
+
+```sh
+node connector/setup.mjs verify --instance <资料库编号>
+```
+
+`connector_verified` 表示独立 MCP 客户端已成功握手、确认目标编号并实际搜索案例库;不是当前 Agent 会话已经加载工具。继续按当前宿主正常机制刷新连接。需要用户重新打开会话时明确告知,保留已完成步骤,不谎报当前会话已连通。
+
+在当前会话实际调用 `promptdirector_status` 和 `promptdirector_search_cases`。已有案例时显示少量候选;需要展示图片时调用 `promptdirector_read_media` 并用宿主工具查看返回的本地原件。空库连接同样可以成功,应说明库为空,不编造案例。安装验收不写入或删除用户案例。
+
+只有当前会话确实调用成功后,才能回复“已连接,可以使用你的案例库了”。安装出错、浏览器待授权、连接器验证成功但会话未加载,要分别说明。不要打印连接密钥、宿主完整配置或用户凭据。
+
+业务使用规则见同目录 `SKILL.md`。普通资料查询不必强制全库分析,也不额外调用模型服务。
+
+## 官方配置依据
+
+- Codex:https://developers.openai.com/codex/mcp
+- Claude Code:https://code.claude.com/docs/en/mcp
+- WorkBuddy:https://www.workbuddy.ai/docs/zh/workbuddy/From-Beginner-to-Expert-Guide/Function-Description/MCP-Guide
+- Chrome Native Messaging:https://developer.chrome.com/docs/extensions/develop/concepts/native-messaging
+- Node.js:https://nodejs.org/en/download
diff --git a/connector/README.md b/connector/README.md
index 86014d1..b5ba53f 100644
--- a/connector/README.md
+++ b/connector/README.md
@@ -1,6 +1,6 @@
# PromptDirector Agent 连接器
-首版提供查、取、存、回存七个 MCP 工具,支持本机 macOS Chrome。连接器和扩展必须同时安装,Chrome 需要保持运行。这里的代码和自动测试不代表已在日常安装版或微信会话中通过验收。
+提供查、取、存、回存七个 MCP 工具,支持本机 Windows、macOS 和 Linux Google Chrome。连接器和扩展需要同时安装,Chrome 需要保持运行。
## 工具
@@ -20,23 +20,15 @@
回存使用现有文件格式识别、文档提取、媒体存储和项目归属逻辑。`files[].originalPrompt` 与该附件绑定。`sourceCaseIds` 保存来源标题、网址和原资料库身份下的案例编号快照;分享包中的来源快照不代表接收方资料库中的可点击关联。Markdown 图片引用不会自动下载,原图需同时作为附件提供。长正文可通过 `bodyFile` 提交;内联正文长度受协议单消息容量约束,文件使用分块,不需要缩短正文或压缩原件。
-文件导入沿用插件现有格式和容量检查。`forceImport` 仅用于用户同意插件报告的大图片风险后的导入,不跳过空间不足、损坏或格式检查。浏览器仍受实际可用存储空间约束;尚未完成 GB 级安装版性能验收。
+文件导入沿用插件现有格式和容量检查。`forceImport` 仅用于用户同意插件报告的大图片风险后的导入,不跳过空间不足、损坏或格式检查。浏览器仍受实际可用存储空间约束。
-## 首次安装
+## 一句话连接
-在项目根目录运行以下检查和准备步骤。安装会写入当前用户的本机连接器目录及 Chrome Native Messaging 注册目录,不修改案例数据。
+在 Chrome 插件设置的 Agent 连接处点击“复制连接指令”,粘贴给当前 Agent。它会按 [统一安装说明](INSTALL.md)检查环境、安装、配置并验证;需要时由用户在浏览器启用连接。
-```sh
-npm ci --prefix connector --ignore-scripts
-node connector/install.mjs plan
-node connector/install.mjs install
-```
+统一入口为 `node connector/setup.mjs plan|connect|verify`。安装程序直接支持 Codex、Claude Code、WorkBuddy 的用户级配置,其他本地 stdio MCP 宿主使用 `generic` 输出标准配置。本机桥接包含 Windows、macOS、Linux Google Chrome 的安装路径。Windows 使用用户级注册表、私有目录和命名管道;需使用 Windows 原生 Node.js。纯云端接入不在本流程内。不同桌面工作台的隔离环境需分别检查,不能仅凭品牌推断兼容。
-1. 使用包含本功能的 PromptDirector 扩展。既有用户应沿用原扩展身份升级,保留案例库。
-2. 打开设置 → 界面与资料库 → Agent 连接,点击启用,授予本机通信和网页采集权限。
-3. 使用页面显示的配对编号运行 `node connector/install.mjs pair <配对编号>`。输出包含 MCP 的 command、args 和 env,里面没有连接密钥。
-4. 将输出配置注册到支持 stdio MCP 的 Agent。OpenClaw 使用出站 `mcp add` / `mcp set`;先检查同名配置,避免重复注册。`SKILL.md` 提供工具使用与任务续查规则。
-5. 用 OpenClaw 的 `mcp doctor promptdirector --probe` 检查握手及工具发现,再在实际目标 Agent 会话确认工具可用。CLI 的 `mcp reload` 不能代替 Gateway 的配置生效验收。
+配置写入前保留备份,不覆盖损坏文件或其他同名连接。验证会通过实际 MCP 握手和案例查询确认连接器工作,随后仍需当前 Agent 会话调用工具,才能宣布用户已经连通。详细步骤与安装依赖由 Agent 按 INSTALL.md 执行,用户无需编辑配置文件。
默认连接目录为当前用户主目录下的 `.promptdirector`。`PROMPTDIRECTOR_CONNECTOR_HOME` 可指定其他用户私有目录,安装器与 Agent 配置必须一致。多 Chrome profile 各有配对编号;`PROMPTDIRECTOR_INSTANCE` 可为不同 Agent 显式指定实例,未指定则使用配对选择。
@@ -44,15 +36,15 @@ node connector/install.mjs install
## 数据和连接
-连接使用 Chrome Native Messaging 与用户私有 Unix socket,没有网络监听端口。Chrome 校验扩展身份,连接器再校验实例编号和本机密钥。MCP 只开放明确的业务操作,不提供任意内部消息或任意脚本执行入口,不返回 AI 服务密钥。
+连接使用 Chrome Native Messaging 与 Windows 命名管道或用户私有 Unix socket,没有网络监听端口。Chrome 校验扩展身份,连接器再校验实例编号和本机密钥。MCP 只开放明确的业务操作,不提供任意内部消息或任意脚本执行入口,不返回 AI 服务密钥。
原件副本保存在连接目录的 `files` 中,传输记录和任务回执保留在扩展本地存储。断开只停止新请求,已提交任务继续处理;Chrome 关闭导致的未完成任务会在下一次查询报告中断。网络或客户端超时后沿用原请求编号查询,不能把失去响应当作未入库。
-待提交文件在入库前暂存,完整性通过后才进入案例。未完成文件不会自动清理,避免错误删除断线任务的原件;当前可由内部传输操作明确丢弃未提交记录,图形化清理属于后续扩展。已入库素材由原资料库管理。
+待提交文件在入库前暂存,完整性通过后才进入案例。未完成文件不会自动清理,避免错误删除断线任务的原件。已入库素材由原资料库管理。
Agent 获取的材料是否发送到模型或其他服务,取决于宿主设置和用户指令。首次启用前应理解这一数据流。工具不绕过浏览器、宿主或网站限制;需要登录或人工验证时返回实际错误。
-## 验证与扩展
+## 运行测试
```sh
node --test test/agent-connector.test.js
@@ -60,10 +52,8 @@ npm test --prefix connector
npm run check
```
-连接器测试使用真实 SDK stdio 握手与真实本机 socket,插件端是明确标注的测试替身。它不能替代真实 Chrome、网站采集和微信最终回复验收。
-
-依赖方向为:MCP 工具 → 本机通信 → 扩展业务操作 → 现有资料库。新增业务能力应实现独立模块,再注册明确的工具参数、返回值、权限与测试;不将界面按钮逐个映射为工具,不预先开放尚未实现的能力。协议版本在连接时校验,未知操作会拒绝。后续管理、分类、分析、批量和 Skill 可按真实需求扩展这一层。
+测试使用隔离目录和模拟案例,不读取用户日常资料库。
## Release 安装包
-下载并解压 `PromptDirector-版本号-Agent-Connector.zip`,在解压后的文件夹打开终端,执行本文的 `npm ci --prefix connector --ignore-scripts` 及安装命令。包中 `extension/manifest.json` 仅用于校验插件身份;实际扩展请使用同版本 `FIXED-ID-DEV` 包升级。连接器当前为 0.1.0,随 PromptDirector 1.21.0 提供;不包含 Node.js,需要预先安装 Node.js 22.13 或更新版本。
+下载并解压 `PromptDirector-版本号-Agent-Connector.zip`,让 Agent 在解压后的文件夹按 `INSTALL.md` 执行安装与连接检查。包中 `extension/manifest.json` 仅用于校验插件身份;实际扩展请使用同版本 `FIXED-ID-DEV` 包升级。连接器当前为 0.2.0,对应 PromptDirector 1.21.1;安装包不包含 Node.js;Agent 会按统一安装说明检查并准备兼容运行时。
diff --git a/connector/bridge-client.mjs b/connector/bridge-client.mjs
index d92e5a8..337e834 100644
--- a/connector/bridge-client.mjs
+++ b/connector/bridge-client.mjs
@@ -4,13 +4,18 @@ import { join } from "node:path";
import { connectorRoot, instancePaths, readJson, ensurePrivateRoot } from "./paths.mjs";
import { encodeFrame, frameDecoder } from "./framing.mjs";
-export async function callExtension(operation, input = {}, { root = connectorRoot(), timeoutMs = 30000 } = {}) {
+export async function callExtension(operation, input = {}, { root = connectorRoot(), timeoutMs = 30000, instanceId } = {}) {
await ensurePrivateRoot(root);
let instance;
- try { instance = process.env.PROMPTDIRECTOR_INSTANCE || (await readJson(join(root, "selected.json"))).instanceId; }
+ try { instance = instanceId || process.env.PROMPTDIRECTOR_INSTANCE || (await readJson(join(root, "selected.json"))).instanceId; }
catch { throw new Error("尚未配对资料库,请在插件启用 Agent 连接后运行连接器配对。"); }
const paths = instancePaths(root, instance);
- const record = await readJson(paths.record);
+ let record;
+ try { record = await readJson(paths.record); }
+ catch (error) {
+ if (error.code === 'ENOENT') throw error;
+ throw Object.assign(new Error('资料库配对记录无法读取,请检查本机连接器记录。'), { code: 'invalid_pairing_record' });
+ }
return new Promise((resolve, reject) => {
const id = randomUUID();
const socket = net.connect(paths.socket);
@@ -19,7 +24,7 @@ export async function callExtension(operation, input = {}, { root = connectorRoo
if (settled) return; settled = true; clearTimeout(timer); socket.destroy();
if (error) reject(error); else resolve(value);
};
- const timer = setTimeout(() => finish(new Error("插件响应超时;写入任务请按原请求编号查询,不要重新提交不同编号。")), timeoutMs);
+ const timer = setTimeout(() => finish(Object.assign(new Error("插件响应超时;写入任务请按原请求编号查询,不要重新提交不同编号。"), { code: "connector_timeout" })), timeoutMs);
const decode = frameDecoder(message => {
if (message.type === "ready") {
if (message.instanceId !== instance || message.protocolVersion !== 1) return finish(new Error("连接的资料库或协议不匹配。"));
@@ -30,7 +35,7 @@ export async function callExtension(operation, input = {}, { root = connectorRoo
});
socket.once("connect", () => socket.write(encodeFrame({ type: "authenticate", secret: record.secret })));
socket.on("data", data => { try { decode(data); } catch (error) { finish(error); } });
- socket.on("error", () => finish(new Error("未连接到指定资料库,请确认 Chrome 已运行且插件的 Agent 连接已启用。")));
- socket.on("close", () => finish(new Error("插件连接已断开;重新连接后可用原请求编号查询写入结果。")));
+ socket.on("error", () => finish(Object.assign(new Error("未连接到指定资料库,请确认 Chrome 已运行且插件的 Agent 连接已启用。"), { code: "connector_offline" })));
+ socket.on("close", () => finish(Object.assign(new Error("插件连接已断开;重新连接后可用原请求编号查询写入结果。"), { code: "connector_offline" })));
});
}
diff --git a/connector/discovery.mjs b/connector/discovery.mjs
new file mode 100644
index 0000000..ac48571
--- /dev/null
+++ b/connector/discovery.mjs
@@ -0,0 +1,21 @@
+import { readdir } from 'node:fs/promises';
+import { callExtension } from './bridge-client.mjs';
+import { connectorRoot } from './paths.mjs';
+
+export async function discoverLibraries({ root = connectorRoot(), instanceId, call = callExtension } = {}) {
+ const names = instanceId ? [`${instanceId}.json`] : await readdir(root).catch(e => { if (e.code === 'ENOENT') return []; throw e; });
+ const ids = names.filter(name => /^[a-f0-9-]{36}\.json$/u.test(name)).map(name => name.slice(0, -5));
+ if (instanceId && ids.length !== 1) throw new Error('无效的资料库编号。');
+ const candidates = await Promise.all(ids.map(async id => {
+ try {
+ const status = await call('status', {}, { root, instanceId: id });
+ if (status.instanceId !== id || status.protocolVersion !== 1) throw new Error('连接的资料库身份或协议不匹配,请检查插件与连接器版本。');
+ if (!status.enabled) return null;
+ return { instanceId: id, extensionVersion: status.extensionVersion, status: status.status };
+ } catch (error) {
+ if (['ENOENT', 'connector_offline'].includes(error.code)) return null;
+ throw error;
+ }
+ }));
+ return candidates.filter(Boolean);
+}
diff --git a/connector/host-config.mjs b/connector/host-config.mjs
new file mode 100644
index 0000000..8ccfee9
--- /dev/null
+++ b/connector/host-config.mjs
@@ -0,0 +1,76 @@
+import { readFile, writeFile, mkdir, rename, unlink, open, lstat } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { isDeepStrictEqual } from 'node:util';
+import { parse, stringify } from 'smol-toml';
+
+// Paths and formats follow the host documentation linked in INSTALL.md.
+export function hostConfiguration(host, { home = homedir(), env = process.env } = {}) {
+ switch (host) {
+ case 'codex': return { host, path: join(env.CODEX_HOME || join(home, '.codex'), 'config.toml'), format: 'toml', key: 'mcp_servers' };
+ case 'claude': return { host, path: env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, '.claude.json') : join(home, '.claude.json'), format: 'json', key: 'mcpServers' };
+ case 'workbuddy': return { host, path: join(home, '.workbuddy/mcp.json'), format: 'json', key: 'mcpServers' };
+ case 'generic': return { host };
+ default: throw new Error('请由当前 Agent 指定 codex、claude、workbuddy 或 generic;云端会话不能直接安装本机连接器。');
+ }
+}
+function object(value) { return value && typeof value === 'object' && !Array.isArray(value); }
+function decode(text, format) {
+ const value = format === 'toml' ? parse(text, { integersAsBigInt: true }) : JSON.parse(text);
+ if (!object(value)) throw new Error('Agent 配置必须是一个对象,原文件未改动。');
+ return value;
+}
+export async function configurationPlan(target, mcp) {
+ if (!target.path) return { ...target, mcp, changed: false, state: 'manual_registration_required' };
+ let original = null; let mode = 0o600;
+ try {
+ const info = await lstat(target.path);
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error('配置路径不是普通文件,请先确认实际配置位置。');
+ mode = info.mode & 0o777;
+ original = await readFile(target.path, 'utf8');
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
+ let config;
+ try { config = original === null ? {} : decode(original, target.format); }
+ catch { throw new Error('现有 Agent 配置无法解析,已保留原文件;请先修复配置,再重试连接。'); }
+ const servers = config[target.key] ?? {};
+ if (!object(servers)) throw new Error('现有 MCP 配置结构无效,原文件未改动。');
+ const prior = servers.promptdirector;
+ if (prior !== undefined) {
+ if (!object(prior) || prior.command !== mcp.command || !isDeepStrictEqual(prior.args, mcp.args) || prior.url ||
+ (prior.env?.PROMPTDIRECTOR_INSTANCE && prior.env.PROMPTDIRECTOR_INSTANCE !== mcp.env.PROMPTDIRECTOR_INSTANCE)) {
+ throw new Error('已有不同的 PromptDirector 连接,未覆盖。请确认要使用的资料库或已有安装。');
+ }
+ }
+ const entry = { ...prior, ...mcp, env: { ...prior?.env, ...mcp.env } };
+ if (target.format === 'json') entry.type = 'stdio';
+ const changed = !isDeepStrictEqual(prior, entry);
+ config[target.key] = { ...servers, promptdirector: entry };
+ const content = changed ? (target.format === 'toml' ? stringify(config, { numbersAsFloat: true }) : JSON.stringify(config, null, 2) + '\n') : original;
+ // Parse the serialized document before writing; preserve all unrelated values.
+ if (changed && !isDeepStrictEqual(decode(content, target.format), config)) throw new Error('配置序列化校验失败,原文件未改动。');
+ return { ...target, original, content, changed, mode, mcp, state: 'configured', hostEnabled: entry.enabled !== false && entry.disabled !== true };
+}
+export async function writeConfiguration(plan) {
+ if (!plan.changed) return { path: plan.path, changed: false, state: plan.state, hostEnabled: plan.hostEnabled };
+ await mkdir(dirname(plan.path), { recursive: true });
+ const lockPath = `${plan.path}.promptdirector-lock`;
+ const lock = await open(lockPath, 'wx', 0o600).catch(() => { throw new Error('配置正在被其他安装任务使用;原配置未改动,请稍后重试。'); });
+ const temp = `${plan.path}.${randomUUID()}.tmp`;
+ let backup;
+ try {
+ let current = null;
+ try { current = await readFile(plan.path, 'utf8'); } catch (e) { if (e.code !== 'ENOENT') throw e; }
+ if (current !== plan.original) throw new Error('检查后 Agent 配置发生变化,已停止写入,请重新执行。');
+ if (current !== null) {
+ backup = `${plan.path}.promptdirector-backup-${randomUUID()}`;
+ await writeFile(backup, current, { mode: 0o600, flag: 'wx' });
+ }
+ await writeFile(temp, plan.content, { mode: plan.mode, flag: 'wx' });
+ await rename(temp, plan.path);
+ return { path: resolve(plan.path), backup, changed: true, state: 'configured', hostEnabled: plan.hostEnabled };
+ } finally {
+ await unlink(temp).catch(e => { if (e.code !== 'ENOENT') throw e; });
+ await lock.close(); await unlink(lockPath);
+ }
+}
diff --git a/connector/install.mjs b/connector/install.mjs
index 646c1bd..3cfae06 100644
--- a/connector/install.mjs
+++ b/connector/install.mjs
@@ -1,13 +1,23 @@
import { isMain } from "./is-main.mjs";
-import { mkdir, writeFile, readFile, readdir, cp, rename, lstat } from 'node:fs/promises';
+import { mkdir, writeFile, readdir, cp, rename } from 'node:fs/promises';
import { createHash, randomUUID } from 'node:crypto';
import { homedir } from 'node:os';
import { join, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { connectorRoot, ensurePrivateRoot, instancePaths, readJson } from './paths.mjs';
+import { windowsLauncher, registerWindowsHost, nativeRegistryKey } from './windows.mjs';
const source = dirname(fileURLToPath(import.meta.url));
const shellQuote = value => `'${value.replaceAll("'", "'\\''")}'`;
-export async function installationPlan({ root = connectorRoot(), nativeDirectory = join(homedir(), 'Library/Application Support/Google/Chrome/NativeMessagingHosts'), extensionId } = {}) {
+export async function installationPlan({ root = connectorRoot(), nativeDirectory, extensionId } = {}) {
+ if (process.platform === 'linux' && process.env.WSL_INTEROP && !nativeDirectory) {
+ throw new Error('检测到 WSL;连接 Windows Chrome 时请使用 Windows 原生 Node.js 运行安装入口。');
+ }
+ if (!nativeDirectory) {
+ if (process.platform === 'darwin') nativeDirectory = join(homedir(), 'Library/Application Support/Google/Chrome/NativeMessagingHosts');
+ else if (process.platform === 'linux') nativeDirectory = join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'google-chrome/NativeMessagingHosts');
+ else if (process.platform === 'win32') nativeDirectory = join(root, 'NativeMessagingHosts');
+ else throw new Error('当前本机桥接尚未支持此操作系统;未写入 Chrome 或 Agent 配置。');
+ }
if (!extensionId) {
const manifest = await readJson(resolve(source, '../extension/manifest.json'));
extensionId = [...createHash('sha256').update(Buffer.from(manifest.key, 'base64')).digest().subarray(0, 16)]
@@ -15,14 +25,15 @@ export async function installationPlan({ root = connectorRoot(), nativeDirectory
}
if (!/^[a-p]{32}$/.test(extensionId)) throw new Error('无效的 Chrome 扩展编号。');
return { root: resolve(root), nativeDirectory: resolve(nativeDirectory), extensionId,
- runtime: join(resolve(root), 'runtime'), launcher: join(resolve(root), 'native-host'),
+ runtime: join(resolve(root), 'runtime'), launcher: join(resolve(root), process.platform === 'win32' ? 'native-host.cmd' : 'native-host'),
+ ...(process.platform === 'win32' ? { registryKey: nativeRegistryKey } : {}),
registration: join(resolve(nativeDirectory), 'com.promptdirector.connector.json'), node: process.execPath };
}
async function atomicWrite(path, text, mode = 0o600) {
const temp = `${path}.${randomUUID()}.tmp`;
await writeFile(temp, text, { mode, flag: 'wx' }); await rename(temp, path);
}
-export async function install(plan) {
+export async function install(plan, { register = registerWindowsHost } = {}) {
await ensurePrivateRoot(plan.root);
// A stable private runtime survives moving the development checkout. Copy
// dependencies without install scripts; the lockfile identifies their source.
@@ -33,10 +44,11 @@ export async function install(plan) {
}
}
await atomicWrite(join(plan.root, 'config.json'), JSON.stringify({ extensionId: plan.extensionId }));
- await atomicWrite(plan.launcher, `#!/bin/sh\nexport PROMPTDIRECTOR_CONNECTOR_HOME=${shellQuote(plan.root)}\nexec ${shellQuote(plan.node)} ${shellQuote(join(plan.runtime, 'native-host.mjs'))} "$@"\n`, 0o700);
+ await atomicWrite(plan.launcher, process.platform === 'win32' ? windowsLauncher(plan) : `#!/bin/sh\nexport PROMPTDIRECTOR_CONNECTOR_HOME=${shellQuote(plan.root)}\nexec ${shellQuote(plan.node)} ${shellQuote(join(plan.runtime, 'native-host.mjs'))} "$@"\n`, 0o700);
await mkdir(plan.nativeDirectory, { recursive: true });
await atomicWrite(plan.registration, JSON.stringify({ name: 'com.promptdirector.connector', description: 'PromptDirector local Agent connector',
path: plan.launcher, type: 'stdio', allowed_origins: [`chrome-extension://${plan.extensionId}/`] }, null, 2));
+ if (process.platform === 'win32') await register(plan.registration);
return { ...plan, next: '在插件设置启用 Agent 连接,再用配对编号运行 pair。' };
}
export async function pair(instanceId, root = connectorRoot()) {
diff --git a/connector/is-main.mjs b/connector/is-main.mjs
index 5a70f3e..d921031 100644
--- a/connector/is-main.mjs
+++ b/connector/is-main.mjs
@@ -2,5 +2,5 @@ import { realpathSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
export function isMain(url) {
if (!process.argv[1]) return false;
- try { return realpathSync(process.argv[1]) === fileURLToPath(url); } catch { return false; }
+ try { return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(url)); } catch { return false; }
}
diff --git a/connector/mcp.mjs b/connector/mcp.mjs
index a948c45..86282a7 100644
--- a/connector/mcp.mjs
+++ b/connector/mcp.mjs
@@ -1,3 +1,4 @@
+import packageInfo from './package.json' with { type: 'json' };
import { isMain } from "./is-main.mjs";
import { McpServer } from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
@@ -8,7 +9,7 @@ import { receiveMedia, stageFiles } from './transfers.mjs';
const requestId = z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/);
const project = z.string().optional();
export function createServer(call = callExtension) {
- const server = new McpServer({ name: 'promptdirector', version: '0.1.0' }, {
+ const server = new McpServer({ name: 'promptdirector', version: packageInfo.version }, {
instructions: '日常用简短自然语言说明结果和必要缺失。案例 ID、任务编号及协议状态在内部保留,仅在用户明确要求诊断时展示。处理中不等于已保存,必须核对最终回执;失败说明影响和下一步,不隐瞒问题。'
});
function tool(name, description, inputSchema, readonly, handler) {
diff --git a/connector/native-host.mjs b/connector/native-host.mjs
index 321ccc5..9c0f264 100644
--- a/connector/native-host.mjs
+++ b/connector/native-host.mjs
@@ -24,7 +24,7 @@ export async function startNativeHost({ root = connectorRoot(), origin, input =
for (const socket of sockets) socket.destroy();
pending.clear();
if (server) await new Promise(resolve => server.close(resolve));
- if (ownsSocket) await unlink(paths.socket).catch(error => { if (error.code !== "ENOENT") throw error; });
+ if (ownsSocket && process.platform !== "win32") await unlink(paths.socket).catch(error => { if (error.code !== "ENOENT") throw error; });
}
async function initialize(message) {
if (initializing || server) throw new Error("Duplicate native handshake.");
@@ -42,7 +42,7 @@ export async function startNativeHost({ root = connectorRoot(), origin, input =
if (closed) return;
// Do not unlink an existing live profile endpoint. Only a verified stale
// socket owned by this user may be removed after an ECONNREFUSED probe.
- try {
+ if (process.platform !== "win32") try {
const info = await lstat(paths.socket);
if (!info.isSocket() || info.uid !== process.getuid()) throw new Error("Unsafe connector endpoint.");
await new Promise((resolve, reject) => {
@@ -81,8 +81,8 @@ export async function startNativeHost({ root = connectorRoot(), origin, input =
});
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(paths.socket, resolve); });
ownsSocket = true;
- if (closed) { server.close(); await unlink(paths.socket).catch(() => {}); return; }
- await chmod(paths.socket, 0o600);
+ if (closed) { server.close(); if (process.platform !== "win32") await unlink(paths.socket).catch(() => {}); return; }
+ if (process.platform !== "win32") await chmod(paths.socket, 0o600);
send({ type: "ready" });
}
const decode = frameDecoder(message => {
diff --git a/connector/package-lock.json b/connector/package-lock.json
index 8af063d..15304a4 100644
--- a/connector/package-lock.json
+++ b/connector/package-lock.json
@@ -1,15 +1,16 @@
{
"name": "promptdirector-mcp",
- "version": "0.1.0",
+ "version": "0.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "promptdirector-mcp",
- "version": "0.1.0",
+ "version": "0.2.0",
"dependencies": {
"@modelcontextprotocol/client": "2.0.0",
"@modelcontextprotocol/server": "2.0.0",
+ "smol-toml": "1.8.0",
"zod": "4.6.2"
},
"engines": {
@@ -148,6 +149,18 @@
"node": ">=8"
}
},
+ "node_modules/smol-toml": {
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.8.0.tgz",
+ "integrity": "sha512-kCZr2V3ch9i00x8zXRhjUNVcjG9ijES5dDudkXvUVCT5QlJNQWElSJdZqyPemffHoLNUYwOcou0Fy+ojN0uHSQ==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/cyyynthia"
+ }
+ },
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
diff --git a/connector/package.json b/connector/package.json
index 9e64f58..28e5168 100644
--- a/connector/package.json
+++ b/connector/package.json
@@ -1,6 +1,6 @@
{
"name": "promptdirector-mcp",
- "version": "0.1.0",
+ "version": "0.2.0",
"private": true,
"type": "module",
"engines": {
@@ -13,6 +13,7 @@
"dependencies": {
"@modelcontextprotocol/client": "2.0.0",
"@modelcontextprotocol/server": "2.0.0",
+ "smol-toml": "1.8.0",
"zod": "4.6.2"
}
}
diff --git a/connector/paths.mjs b/connector/paths.mjs
index 22b5a7e..8a482a1 100644
--- a/connector/paths.mjs
+++ b/connector/paths.mjs
@@ -1,22 +1,31 @@
import { homedir } from "node:os";
-import { join } from "node:path";
+import { join, resolve } from "node:path";
import { createHash } from "node:crypto";
import { mkdir, lstat, readFile } from "node:fs/promises";
+import { privateWindowsDirectory } from "./windows.mjs";
+
export function connectorRoot() {
return process.env.PROMPTDIRECTOR_CONNECTOR_HOME || join(homedir(), ".promptdirector");
}
-export function instancePaths(root, instance) {
+export function instancePaths(root, instance, platform = process.platform) {
if (!/^[a-f0-9-]{36}$/u.test(instance || "")) throw new Error("请在连接器中配对插件显示的实例编号。");
const name = createHash("sha256").update(instance).digest("hex").slice(0, 24);
- const socket = join(root, `${name}.sock`);
+ const socket = platform === "win32"
+ ? `\\\\.\\pipe\\promptdirector-${createHash("sha256").update(resolve(root).toLowerCase()).digest("hex").slice(0, 24)}-${name}`
+ : join(root, `${name}.sock`);
// macOS sockaddr_un.sun_path capacity, including terminating NUL.
- if (Buffer.byteLength(socket) > 103) throw new Error("连接目录路径过长,请选择较短的用户私有目录。");
+ if (platform !== "win32" && Buffer.byteLength(socket) > 103) throw new Error("连接目录路径过长,请选择较短的用户私有目录。");
return { socket, record: join(root, `${instance}.json`) };
}
export async function ensurePrivateRoot(root) {
await mkdir(root, { recursive: true, mode: 0o700 });
const info = await lstat(root);
+ if (process.platform === "win32") {
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("连接目录必须是当前用户的私有目录。");
+ await privateWindowsDirectory(root);
+ return;
+ }
if (!info.isDirectory() || info.uid !== process.getuid() || (info.mode & 0o077)) {
throw new Error("连接目录必须归当前用户所有,且仅当前用户可访问。");
}
diff --git a/connector/setup.mjs b/connector/setup.mjs
new file mode 100644
index 0000000..de757f7
--- /dev/null
+++ b/connector/setup.mjs
@@ -0,0 +1,100 @@
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+import { installationPlan, install } from './install.mjs';
+import { hostConfiguration, configurationPlan, writeConfiguration } from './host-config.mjs';
+import { discoverLibraries } from './discovery.mjs';
+import { connectorRoot, instancePaths } from './paths.mjs';
+import { isMain } from './is-main.mjs';
+
+export function mcpConfiguration(root, instanceId) {
+ if (instanceId) instancePaths(root, instanceId);
+ return { command: process.execPath, args: [join(root, 'runtime/mcp.mjs')],
+ env: { PROMPTDIRECTOR_CONNECTOR_HOME: root, ...(instanceId ? { PROMPTDIRECTOR_INSTANCE: instanceId } : {}) } };
+}
+export async function setupPlan({ host, root = connectorRoot(), instanceId, home = homedir(), env = process.env, nativeDirectory, extensionId } = {}) {
+ const installation = await installationPlan({ root, nativeDirectory, extensionId });
+ const mcp = mcpConfiguration(installation.root, instanceId);
+ const configuration = await configurationPlan(hostConfiguration(host, { home, env }), mcp);
+ return { installation, configuration, instanceId, mcp };
+}
+function value(result) {
+ const text = result.content?.filter(item => item.type === 'text').map(item => item.text).join('');
+ if (result.isError) throw new Error(text || 'MCP 调用失败');
+ return JSON.parse(text);
+}
+export async function verifyConnection({ root = connectorRoot(), instanceId, probe = discoverLibraries, onProgress = stage => { if (process.env.PROMPTDIRECTOR_DEBUG) console.error(`[PromptDirector verify] ${stage}`); } } = {}) {
+ onProgress('library-discovery');
+ const libraries = await probe({ root, instanceId });
+ if (!libraries.length) return { state: 'awaiting_browser', connected: false,
+ next: '在已安装 PromptDirector 的 Chrome 中打开设置 → Agent 连接 → 启用。若已启用请断开再启用;浏览器要求重新加载时先保存未完成编辑,然后重试 verify。' };
+ if (libraries.length > 1) return { state: 'library_selection_required', connected: false, libraries,
+ next: '请从目标案例库复制连接指令,使用其中的 instance 参数;不要猜测用户要连接哪个资料库。' };
+ const selected = libraries[0].instanceId;
+ const mcp = mcpConfiguration(root, selected);
+ const client = new Client({ name: 'promptdirector-setup-check', version: '1' });
+ try {
+ onProgress('mcp-start');
+ await client.connect(new StdioClientTransport({ ...mcp, env: { ...mcp.env, ...(process.env.PROMPTDIRECTOR_DEBUG ? { PROMPTDIRECTOR_DEBUG: process.env.PROMPTDIRECTOR_DEBUG } : {}) } }));
+ onProgress('mcp-tools');
+ const listed = await client.listTools();
+ const names = listed.tools.map(tool => tool.name);
+ for (const required of ['promptdirector_status', 'promptdirector_search_cases', 'promptdirector_read_case', 'promptdirector_read_media']) {
+ if (!names.includes(required)) throw new Error(`MCP 缺少所需能力:${required}`);
+ }
+ onProgress('library-status');
+ const status = value(await client.callTool({ name: 'promptdirector_status', arguments: {} }));
+ if (status.instanceId !== selected || !status.enabled || status.status !== 'connected') throw new Error('MCP 返回的资料库与目标不一致或尚未连接。');
+ onProgress('library-search');
+ const result = value(await client.callTool({ name: 'promptdirector_search_cases', arguments: { query: '', limit: 3 } }));
+ if (!Array.isArray(result.cases) || !Number.isInteger(result.total)) throw new Error('案例搜索未返回有效结果。');
+ return { state: 'connector_verified', connected: true, instanceId: selected, mcp,
+ extensionVersion: status.extensionVersion, caseCount: result.total, sampleCases: result.cases,
+ hostSessionVerified: false,
+ next: '连接器已实际查询案例库。还需在当前 Agent 会话发现 promptdirector 工具并调用 status/search_cases;如需重载请使用宿主正常入口。只有当前会话实际调用成功后才报告已连接;需要展示案例时按返回的媒体编号读取原件。' };
+ } finally { onProgress('mcp-close'); await client.close(); onProgress('mcp-closed'); }
+}
+export async function connect(options, { installRuntime = install, verify = verifyConnection } = {}) {
+ const plan = await setupPlan(options);
+ await installRuntime(plan.installation);
+ const configured = plan.instanceId ? await writeConfiguration(plan.configuration)
+ : { changed: false, state: 'awaiting_pairing' };
+ const checked = await verify({ root: plan.installation.root, instanceId: plan.instanceId });
+ // Bind a discovered single library explicitly so another Chrome profile cannot
+ // later redirect this host through the global selected.json preference.
+ let finalConfiguration = configured;
+ if (!plan.instanceId && checked.connected) {
+ finalConfiguration = await writeConfiguration(await configurationPlan(
+ hostConfiguration(options.host, { home: options.home, env: options.env }), checked.mcp));
+ }
+ return { ...checked, configuration: finalConfiguration, mcp: checked.mcp || (plan.instanceId ? plan.mcp : undefined),
+ skill: join(plan.installation.runtime, 'SKILL.md') };
+}
+function optionsFrom(args) {
+ const options = {};
+ const keys = { '--host': 'host', '--instance': 'instanceId', '--root': 'root' };
+ for (let index = 0; index < args.length; index += 2) {
+ const key = keys[args[index]];
+ if (!key || !args[index + 1] || args[index + 1].startsWith('--')) throw new Error('用法:node connector/setup.mjs plan|connect|verify --host codex|claude|workbuddy|generic [--instance 编号] [--root 私有目录]');
+ options[key] = args[index + 1];
+ }
+ return options;
+}
+if (isMain(import.meta.url)) {
+ try {
+ const [command = 'plan', ...args] = process.argv.slice(2);
+ const options = optionsFrom(args);
+ let result;
+ if (command === 'plan') {
+ const plan = await setupPlan(options);
+ result = { installation: plan.installation, configuration: { path: plan.configuration.path, changed: plan.configuration.changed, host: plan.configuration.host }, mcp: plan.instanceId ? plan.mcp : undefined };
+ } else if (command === 'connect') result = await connect(options);
+ else if (command === 'verify') result = await verifyConnection(options);
+ else throw new Error('未知命令,请使用 plan、connect 或 verify。');
+ console.log(JSON.stringify(result, null, 2));
+ } catch (error) {
+ // Configuration files can contain credentials. Never echo their contents.
+ console.error(JSON.stringify({ state: 'failed', connected: false, message: error.message })); process.exitCode = 1;
+ }
+}
diff --git a/connector/test/connector.test.mjs b/connector/test/connector.test.mjs
index 3118251..6894ae5 100644
--- a/connector/test/connector.test.mjs
+++ b/connector/test/connector.test.mjs
@@ -4,6 +4,7 @@ import { mkdtemp, writeFile, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
import { once } from 'node:events';
import { PassThrough } from 'node:stream';
import { randomUUID, createHash } from 'node:crypto';
@@ -22,7 +23,7 @@ test('native framing preserves split Unicode messages and refuses oversized fram
assert.throws(() => encodeFrame({ text: '12345' }, 3));
});
-test('real native broker binds one library, authenticates and forwards response', { timeout: 5000 }, async () => {
+test('real native broker binds one library, authenticates and forwards response', { timeout: process.platform === 'win32' ? 30000 : 5000 }, async () => {
const root = await mkdtemp(join(tmpdir(), 'pd-'));
const input = new PassThrough(), output = new PassThrough();
const extensionId = 'a'.repeat(32), instanceId = randomUUID();
@@ -40,7 +41,7 @@ test('real native broker binds one library, authenticates and forwards response'
assert.deepEqual(await callExtension('search', { query: '案例' }, { root }), { operation: 'search', input: { query: '案例' } });
const client = new Client({ name: 'full-path-test', version: '1' });
try {
- await client.connect(new StdioClientTransport({ command: process.execPath, args: [new URL('../mcp.mjs', import.meta.url).pathname], env: { ...process.env, PROMPTDIRECTOR_CONNECTOR_HOME: root } }));
+ await client.connect(new StdioClientTransport({ command: process.execPath, args: [fileURLToPath(new URL('../mcp.mjs', import.meta.url))], env: { ...process.env, PROMPTDIRECTOR_CONNECTOR_HOME: root } }));
const response = await client.callTool({ name: 'promptdirector_search_cases', arguments: { query: '素材' } });
const content = JSON.parse(response.content[0].text);
assert.equal(content.operation, 'search'); assert.equal(content.input.query, '素材');
@@ -51,7 +52,7 @@ test('real native broker binds one library, authenticates and forwards response'
test('SDK client performs real stdio MCP handshake and discovers bounded tools', async () => {
const client = new Client({ name: 'connector-test', version: '1' });
- const transport = new StdioClientTransport({ command: process.execPath, args: [new URL('../mcp.mjs', import.meta.url).pathname] });
+ const transport = new StdioClientTransport({ command: process.execPath, args: [fileURLToPath(new URL('../mcp.mjs', import.meta.url))] });
try {
await client.connect(transport);
const list = await client.listTools();
@@ -90,13 +91,14 @@ test('file staging resumes exact bytes and keeps each original prompt tied to it
} finally { await rm(root, { recursive: true, force: true }); }
});
-test('installer creates a reviewable private runtime and origin-bound registration in an isolated directory', { timeout: 10000 }, async () => {
+test('installer creates a reviewable private runtime and origin-bound registration in an isolated directory', { timeout: process.platform === 'win32' ? 60000 : 10000 }, async () => {
const { installationPlan, install, pair } = await import('../install.mjs');
- const root = await mkdtemp(join(tmpdir(), 'pd-'));
+ const root = await mkdtemp(join(tmpdir(), process.platform === 'win32' ? 'pd 案例 ! 100% ' : 'pd-'));
const extensionId = 'c'.repeat(32), instanceId = randomUUID();
try {
const plan = await installationPlan({ root, nativeDirectory: join(root, 'registration'), extensionId });
- await install(plan);
+ await install(plan, { register: async () => {} });
+ await install(plan, { register: async () => {} }); // Updating keeps the same runtime and pairing location.
const manifest = JSON.parse(await readFile(plan.registration, 'utf8'));
assert.deepEqual(manifest.allowed_origins, [`chrome-extension://${extensionId}/`]);
assert.equal(manifest.path, plan.launcher);
@@ -104,7 +106,9 @@ test('installer creates a reviewable private runtime and origin-bound registrati
const { instancePaths } = await import('../paths.mjs');
await writeFile(instancePaths(root, instanceId).record, JSON.stringify({ instanceId, secret: 'a'.repeat(64) }));
const paired = await pair(instanceId, root); assert.equal(paired.instanceId, instanceId);
- const native = spawn(plan.launcher, [`chrome-extension://${extensionId}/`], { stdio: ['pipe', 'pipe', 'pipe'] });
+ const native = process.platform === 'win32'
+ ? spawn(process.env.ComSpec, ['/d', '/s', '/c', `""${plan.launcher}" chrome-extension://${extensionId}/"`], { windowsVerbatimArguments: true, stdio: ['pipe', 'pipe', 'pipe'] })
+ : spawn(plan.launcher, [`chrome-extension://${extensionId}/`], { stdio: ['pipe', 'pipe', 'pipe'] });
const exited = once(native, 'exit');
let onReady; const ready = new Promise(resolve => { onReady = resolve; });
native.stdout.on('data', frameDecoder(message => {
diff --git a/connector/test/setup.test.mjs b/connector/test/setup.test.mjs
new file mode 100644
index 0000000..7912b6c
--- /dev/null
+++ b/connector/test/setup.test.mjs
@@ -0,0 +1,135 @@
+import { install } from '../install.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, writeFile, readFile, rm, readdir } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { PassThrough } from 'node:stream';
+import { parse } from 'smol-toml';
+import { hostConfiguration, configurationPlan, writeConfiguration } from '../host-config.mjs';
+import { discoverLibraries } from '../discovery.mjs';
+import { connect, mcpConfiguration, verifyConnection } from '../setup.mjs';
+import { startNativeHost } from '../native-host.mjs';
+import { encodeFrame, frameDecoder } from '../framing.mjs';
+
+async function temporary(fn) { const root = await mkdtemp(join(tmpdir(), 'pd-onboard-')); try { await fn(root); } finally { await rm(root, { recursive: true, force: true }); } }
+const entry = root => mcpConfiguration(root, '11111111-1111-4111-8111-111111111111');
+
+test('host paths use documented user scope and explicit runtime roots', () => {
+ assert.equal(hostConfiguration('codex', { home: '/example', env: { CODEX_HOME: '/portable' } }).path, join('/portable', 'config.toml'));
+ assert.equal(hostConfiguration('claude', { home: '/example', env: {} }).path, join('/example', '.claude.json'));
+ assert.equal(hostConfiguration('workbuddy', { home: '/example', env: {} }).path, join('/example', '.workbuddy/mcp.json'));
+ assert.deepEqual(hostConfiguration('generic'), { host: 'generic' });
+ assert.throws(() => hostConfiguration('chatgpt-cloud'), /云端/);
+});
+
+for (const format of ['json', 'toml']) test(`${format} install preserves unrelated MCP settings, backs up and is repeatable`, () => temporary(async root => {
+ const original = format === 'json' ? '{"preference":"keep","mcpServers":{"other":{"command":"other","env":{"TOKEN":"test-only"}}}}' : '# retained in backup\npreference="keep"\n[mcp_servers.other]\ncommand="other"\n[mcp_servers.other.env]\nTOKEN="test-only"\n';
+ const path = join(root, `config.${format}`), key = format === 'json' ? 'mcpServers' : 'mcp_servers';
+ await writeFile(path, original);
+ const target = { path, key, format };
+ const plan = await configurationPlan(target, entry(root));
+ const result = await writeConfiguration(plan);
+ assert.equal(await readFile(result.backup, 'utf8'), original);
+ const updated = format === 'json' ? JSON.parse(await readFile(path, 'utf8')) : parse(await readFile(path, 'utf8'));
+ assert.equal(updated.preference, 'keep'); assert.equal(updated[key].other.env.TOKEN, 'test-only');
+ assert.equal(updated[key].promptdirector.env.PROMPTDIRECTOR_INSTANCE, entry(root).env.PROMPTDIRECTOR_INSTANCE);
+ const again = await configurationPlan(target, entry(root)); assert.equal(again.changed, false);
+ assert.equal((await writeConfiguration(again)).changed, false);
+}));
+
+test('invalid, conflicting and concurrently changed config files are never overwritten', () => temporary(async root => {
+ const path = join(root, 'config.json'), target = { path, key: 'mcpServers', format: 'json' };
+ await writeFile(path, '{broken');
+ await assert.rejects(configurationPlan(target, entry(root)), /无法解析/);
+ assert.equal(await readFile(path, 'utf8'), '{broken');
+ await writeFile(path, JSON.stringify({ mcpServers: { promptdirector: { command: 'another' } } }));
+ await assert.rejects(configurationPlan(target, entry(root)), /未覆盖/);
+ await writeFile(path, '{}'); const plan = await configurationPlan(target, entry(root));
+ await writeFile(path, '{"edited":true}'); await assert.rejects(writeConfiguration(plan), /发生变化/);
+ assert.equal(await readFile(path, 'utf8'), '{"edited":true}');
+ assert(!(await readdir(root)).some(name => name.endsWith('lock')));
+}));
+
+test('discovery excludes stale profiles and never selects among multiple online libraries', () => temporary(async root => {
+ const one = randomUUID(), two = randomUUID();
+ await writeFile(join(root, one + '.json'), '{}'); await writeFile(join(root, two + '.json'), '{}');
+ const probe = opts => discoverLibraries({ ...opts, call: async (_op, _input, { instanceId }) => ({ instanceId, protocolVersion: 1, enabled: true, status: 'connected' }) });
+ assert.equal((await verifyConnection({ root, probe })).state, 'library_selection_required');
+ assert.equal((await discoverLibraries({ root, instanceId: one, call: async () => { throw Object.assign(new Error('offline'), { code: 'connector_offline' }); } })).length, 0);
+}));
+
+test('offline setup reports browser action without claiming host session success', () => temporary(async root => {
+ const result = await connect({ root, home: root, env: {}, host: 'workbuddy', instanceId: randomUUID(), nativeDirectory: join(root, 'registration'), extensionId: 'a'.repeat(32) }, {
+ installRuntime: async () => {}, verify: async () => ({ state: 'awaiting_browser', connected: false })
+ });
+ assert.equal(result.state, 'awaiting_browser'); assert.equal(result.connected, false);
+ assert.equal(result.configuration.state, 'configured');
+}));
+
+test('full installed SDK verification reads the bound library and distinguishes the host session', { timeout: process.platform === 'win32' ? 60000 : 15000 }, t => temporary(async root => {
+ const instanceId = randomUUID(), extensionId = 'a'.repeat(32);
+ const options = { root, instanceId, host: 'codex', home: root, env: {}, nativeDirectory: join(root, 'registration'), extensionId };
+ // Install a real connector into a private directory. Chrome's native stream is
+ // a fixture here; MCP client, installed server, broker and file config are real.
+ process.env.PROMPTDIRECTOR_DEBUG = '1';
+ t.diagnostic('installing isolated runtime');
+ const initial = await connect(options, { installRuntime: plan => install(plan, { register: async () => {} }) });
+ t.diagnostic(`initial state: ${initial.state}`);
+ assert.equal(initial.state, 'awaiting_browser');
+ const input = new PassThrough(), output = new PassThrough();
+ let ready; const readiness = new Promise(resolve => { ready = resolve; });
+ output.on('data', frameDecoder(message => {
+ if (message.type === 'ready') { ready(); return; }
+ if (message.type !== 'request') return;
+ const result = message.operation === 'status'
+ ? { instanceId, protocolVersion: 1, enabled: true, status: 'connected', extensionVersion: 'fixture' }
+ : { cases: [{ caseId: 'fixture-case', title: 'Fixture original prompt' }], total: 1 };
+ input.write(encodeFrame({ type: 'response', id: message.id, result }));
+ }));
+ t.diagnostic('starting broker fixture');
+ const native = await startNativeHost({ root, origin: `chrome-extension://${extensionId}/`, input, output });
+ try {
+ input.write(encodeFrame({ type: 'hello', protocolVersion: 1, extensionId, instanceId })); await readiness;
+ t.diagnostic('broker ready; verifying installed MCP');
+ const verified = await verifyConnection({ root, instanceId, onProgress: stage => t.diagnostic(`${new Date().toISOString()} ${stage}`) });
+ t.diagnostic(`verified state: ${verified.state}`);
+ assert.equal(verified.state, 'connector_verified'); assert.equal(verified.hostSessionVerified, false);
+ assert.equal(verified.caseCount, 1); assert.equal(verified.sampleCases[0].caseId, 'fixture-case');
+ t.diagnostic('checking repeated connection');
+ const repeat = await connect(options, { installRuntime: async () => {} });
+ assert.equal(repeat.connected, true); assert.equal(repeat.configuration.changed, false);
+ assert(!JSON.stringify(verified).includes('secret'));
+ } catch (error) { t.diagnostic(error.stack); throw error; }
+ finally { t.diagnostic('closing broker'); await native.close(); input.destroy(); output.destroy(); t.diagnostic('broker closed'); delete process.env.PROMPTDIRECTOR_DEBUG; }
+}));
+
+
+test('TOML edits preserve integer precision and float types', () => temporary(async root => {
+ const path = join(root, 'config.toml');
+ await writeFile(path, 'ratio=1.0\nlarge=9223372036854775807\n');
+ const plan = await configurationPlan({ path, key: 'mcp_servers', format: 'toml' }, entry(root));
+ await writeConfiguration(plan);
+ const value = parse(await readFile(path, 'utf8'), { integersAsBigInt: true });
+ assert.equal(value.ratio, 1); assert.equal(value.large, 9223372036854775807n);
+}));
+
+test('a disabled host entry and existing tool policy stay under user control', () => temporary(async root => {
+ const path = join(root, 'config.json'), mcp = entry(root);
+ await writeFile(path, JSON.stringify({ mcpServers: { promptdirector: { ...mcp, disabled: true, disabledTools: ['promptdirector_save_material'] } } }));
+ const plan = await configurationPlan({ path, key: 'mcpServers', format: 'json' }, mcp);
+ assert.equal(plan.hostEnabled, false);
+ await writeConfiguration(plan);
+ const saved = JSON.parse(await readFile(path, 'utf8')).mcpServers.promptdirector;
+ assert.deepEqual(saved.disabledTools, ['promptdirector_save_material']); assert.equal(saved.disabled, true);
+}));
+
+
+test('an unpaired installation never registers an unbound host configuration', () => temporary(async root => {
+ const result = await connect({ root, home: root, env: {}, host: 'workbuddy', nativeDirectory: join(root, 'registration'), extensionId: 'a'.repeat(32) }, {
+ installRuntime: async () => {}, verify: async () => ({ state: 'library_selection_required', connected: false, libraries: [{instanceId: randomUUID()}, {instanceId: randomUUID()}] })
+ });
+ assert.equal(result.configuration.state, 'awaiting_pairing'); assert.equal(result.mcp, undefined);
+ await assert.rejects(readFile(join(root, '.workbuddy/mcp.json')), {code: 'ENOENT'});
+}));
diff --git a/connector/test/windows.test.mjs b/connector/test/windows.test.mjs
new file mode 100644
index 0000000..427ca49
--- /dev/null
+++ b/connector/test/windows.test.mjs
@@ -0,0 +1,45 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { randomUUID } from 'node:crypto';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { promisify } from 'node:util';
+import { execFile } from 'node:child_process';
+import { instancePaths, ensurePrivateRoot } from '../paths.mjs';
+import { windowsLauncher, windowsCommand, registerWindowsHost } from '../windows.mjs';
+const execute = promisify(execFile);
+
+test('Windows pipes distinguish private roots without imposing Unix path limits', () => {
+ const id = randomUUID();
+ const a = instancePaths(join(tmpdir(), 'a'.repeat(180)), id, 'win32');
+ assert(a.socket.startsWith('\\\\.\\pipe\\promptdirector-'));
+ assert.notEqual(a.socket, instancePaths(join(tmpdir(), 'b'), id, 'win32').socket);
+ assert.equal(a.socket, instancePaths(join(tmpdir(), 'a'.repeat(180)), id, 'win32').socket);
+});
+
+test('Windows launcher preserves Unicode, spaces, percent and literal exclamation paths', () => {
+ const text = windowsLauncher({ root: 'C:\\Users\\案例 100% !\\库', node: 'C:\\Program Files\\nodejs\\node.exe', runtime: 'C:\\Users\\案例 100% !\\库\\runtime' });
+ assert(text.includes('DisableDelayedExpansion\r\nchcp 65001 >nul'));
+ assert(text.includes('案例 100%% !'));
+ assert(text.includes('"C:\\Program Files\\nodejs\\node.exe"'));
+ assert.throws(() => windowsLauncher({ root: 'bad\npath' }), /路径/);
+ assert.throws(() => windowsCommand('reg.exe', {}), /系统目录/);
+});
+
+test('Windows registration preserves Chinese manifest paths and private ACL in real OS', { skip: process.platform !== 'win32', timeout: 30000 }, async () => {
+ const root = await mkdtemp(join(tmpdir(), 'pd 注册 ! 100% '));
+ const key = `HKCU\\Software\\PromptDirector-Test-${randomUUID()}`;
+ const registration = join(root, '注册文件.json');
+ try {
+ await ensurePrivateRoot(root);
+ await ensurePrivateRoot(root);
+ // Each call performs registry readback. The test never touches Chrome's real key.
+ await registerWindowsHost(registration, { key });
+ await registerWindowsHost(registration, { key });
+ } finally {
+ const script = `$ErrorActionPreference='Stop'; Remove-Item -LiteralPath ('Registry::'+$env:PROMPTDIRECTOR_TEST_KEY.Replace('HKCU\\','HKEY_CURRENT_USER\\')) -Recurse -Force -ErrorAction SilentlyContinue`;
+ await execute(windowsCommand('WindowsPowerShell\\v1.0\\powershell.exe'), ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], { env: { ...process.env, PROMPTDIRECTOR_TEST_KEY: key }, windowsHide: true });
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/connector/windows.mjs b/connector/windows.mjs
new file mode 100644
index 0000000..2c018ea
--- /dev/null
+++ b/connector/windows.mjs
@@ -0,0 +1,73 @@
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { win32 } from 'node:path';
+const execute = promisify(execFile);
+export const nativeRegistryKey = 'HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts\\com.promptdirector.connector';
+export function windowsCommand(name, env = process.env) {
+ if (!env.SystemRoot) throw new Error('Windows 系统目录不可用,无法安全调用系统安装工具。');
+ return win32.join(env.SystemRoot, 'System32', name);
+}
+export async function privateWindowsDirectory(root) {
+ // Use Windows .NET ACL APIs directly: PowerShell command autoload can stall
+ // in filtered MCP environments. Paths remain data, never executable code.
+ const script = `$ErrorActionPreference='Stop'
+function Trace($stage) { if ($env:PROMPTDIRECTOR_DEBUG) { [Console]::Error.WriteLine(([DateTime]::UtcNow.ToString('o'))+' '+$stage) } }
+Trace 'script-start'
+$p=$env:PROMPTDIRECTOR_PRIVATE_DIRECTORY
+Trace 'directory-info'
+$item=[IO.DirectoryInfo]::new($p)
+Trace 'identity'
+if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'Connector directory cannot be a reparse point' }
+$sid=[Security.Principal.WindowsIdentity]::GetCurrent().User
+Trace 'get-acl'
+$acl=$item.GetAccessControl()
+Trace 'acl-read'
+$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier])
+if ($owner.Value -ne $sid.Value) { throw 'Connector directory must belong to current user' }
+$rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]))
+$inheritance=[Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'
+if ($acl.AreAccessRulesProtected -and $rules.Count -eq 1) {
+ $r=$rules[0]
+ if ($r.IdentityReference.Value -eq $sid.Value -and
+ $r.AccessControlType -eq 'Allow' -and
+ $r.FileSystemRights -eq [Security.AccessControl.FileSystemRights]::FullControl -and
+ $r.InheritanceFlags -eq $inheritance -and
+ $r.PropagationFlags -eq [Security.AccessControl.PropagationFlags]::None) { return }
+}
+$private=[Security.AccessControl.DirectorySecurity]::new()
+$private.SetOwner($sid)
+$private.SetAccessRuleProtection($true,$false)
+$rule=[Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow')
+$private.AddAccessRule($rule)
+$item.SetAccessControl($private)
+$actual=$item.GetAccessControl()
+if (!$actual.AreAccessRulesProtected) { throw 'Private directory permissions were not applied' }
+foreach($r in $actual.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
+ if ($r.AccessControlType -eq 'Allow' -and $r.IdentityReference.Value -ne $sid.Value) { throw 'Unexpected directory access' }
+}`;
+ const started = Date.now();
+ if (process.env.PROMPTDIRECTOR_DEBUG) console.error('[PromptDirector permissions] start');
+ try {
+ const result = await execute(windowsCommand('WindowsPowerShell\\v1.0\\powershell.exe'), ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], {
+ windowsHide: true, env: { ...process.env, PROMPTDIRECTOR_PRIVATE_DIRECTORY: root }
+ });
+ if (process.env.PROMPTDIRECTOR_DEBUG) console.error(`[PromptDirector permissions] ${Date.now() - started}ms\n${result.stderr}`);
+ } catch { throw new Error('无法保护 Windows 连接目录,请确认目录属于当前用户且允许设置私有访问权限。'); }
+}
+export function windowsLauncher(plan) {
+ const quote = value => {
+ if (/["\r\n]/u.test(value)) throw new Error('Windows 安装路径含无效字符。');
+ return value.replaceAll('%', '%%');
+ };
+ return `@echo off\r\nsetlocal DisableDelayedExpansion\r\nchcp 65001 >nul\r\nset "PROMPTDIRECTOR_CONNECTOR_HOME=${quote(plan.root)}"\r\n"${quote(plan.node)}" "${quote(win32.join(plan.runtime, 'native-host.mjs'))}" %*\r\n`;
+}
+export async function registerWindowsHost(registration, { key = nativeRegistryKey, run = execute } = {}) {
+ const script = `$ErrorActionPreference='Stop'
+$p='Registry::'+$env:PROMPTDIRECTOR_REGISTRY_KEY.Replace('HKCU\\','HKEY_CURRENT_USER\\')
+New-Item -Path $p -Force | Out-Null
+Set-Item -LiteralPath $p -Value $env:PROMPTDIRECTOR_NATIVE_MANIFEST
+if ((Get-Item -LiteralPath $p).GetValue('') -cne $env:PROMPTDIRECTOR_NATIVE_MANIFEST) { throw 'Chrome registration readback mismatch' }`;
+ await run(windowsCommand('WindowsPowerShell\\v1.0\\powershell.exe'), ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], {
+ windowsHide: true, env: { ...process.env, PROMPTDIRECTOR_REGISTRY_KEY: key, PROMPTDIRECTOR_NATIVE_MANIFEST: registration }
+ });
+}
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
deleted file mode 100644
index bc2cac9..0000000
--- a/docs/DESIGN.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# PromptDirector UX visual QA
-
-## 当前设计与验收原则
-
-这些原则用于评审界面贡献,保证视觉调整与原有操作流程一同验收。
-
-- **先保留构图,再做减法。** 以已认可页面为基线,保留品牌、字体、图标和有层级价值的英文装饰标题。精简重复文案时,同时保留原有居中容器、分栏比例和视觉重心。
-- **组内紧邻,整页均衡。** 名称、状态和对应操作组成完整功能组;根据内容使用均衡分栏或就地排列。同级按钮尺寸与对齐一致,避免对象与操作被大片空白隔开,也避免全部控件堆在左侧。
-- **区分控件与正文。** 短按钮文字保持单行;空间不足时调整整组布局。用户正文、名称和标签保持完整可读,不靠缩小字体或截断内容制造简洁。图标、状态徽标文字和相邻按钮分别检查垂直中心。
-- **按熟悉程度使用图标。** 复制、编辑、保存、刷新等使用现有图标、明确提示、无障碍名称和键盘操作;陌生功能保留简短文字。当前主要任务突出一个主动作,辅助操作保持轻量。
-- **减少说明,保留判断依据。** 删除重复标题、无内容提示框和常驻的显然说明;帮助与诊断按需展开。权限、付费、公开发送、失败与不可逆后果在相关操作触发处明确展示。
-- **高频操作直接可达。** 人工标签输入与确认直接可见;来源不同的采集动作清楚区分。补充内容、取消和重试围绕同一草稿继续,保留用户已选内容和编辑。
-- **先确认效果,再实施。** 展示同一基准的当前版与优化版,覆盖受影响页面的桌面、窄屏、明暗主题、中英文、长名称及适用任务状态。整批已确认的页面按稿实施,局部反馈只调整相关区域;改变方案时再确认。
-- **视觉与行为分别验证。** 无溢出不等于排版合格;对照最终实现实屏,检查视觉重心、按钮一致性、徽标居中和阅读路径。再验证原候选、提交参数、错误反馈,以及切换、关闭、取消后的草稿、选择和阅读位置;页面重载另列测试与结论。
-- **边界与证据可追溯。** 实施前列明可改与保留区域,限定样式影响范围。前端整理沿用原业务流程,资料连续性遵循[数据兼容说明](DATA_COMPATIBILITY.md)。原型、源码验证、隔离安装、日用安装及最终发布包分别记录,截图关联实际源码状态;后续修改使相关截图失效时重新核验。
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index ef3829c..175a85e 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -4,6 +4,7 @@ Requires Node.js 22.13 or later. Run commands from the repository root.
```sh
npm ci
+npm ci --prefix connector --ignore-scripts
npm run verify:source
npm run package
```
diff --git a/docs/KNOWN_LIMITATIONS.md b/docs/KNOWN_LIMITATIONS.md
index 599cdbc..2d00759 100644
--- a/docs/KNOWN_LIMITATIONS.md
+++ b/docs/KNOWN_LIMITATIONS.md
@@ -1,4 +1,4 @@
-# 已知限制与后续增强
+# 已知限制
## 浏览器无法直接解码的 MPEG-4 视频
diff --git a/extension/agent-connection.js b/extension/agent-connection.js
index c4c9952..5a18e60 100644
--- a/extension/agent-connection.js
+++ b/extension/agent-connection.js
@@ -6,6 +6,7 @@ export function createAgentConnection({ chromeApi, execute }) {
let error = "";
let starting = null;
let generation = 0;
+ let preparing = null;
const alarm = "agent-connection-retry";
const publish = () => { void chromeApi.storage.session?.set({ agentConnectionStatus: { status, error } }).catch(() => {}); };
const getSettings = async () => (await chromeApi.storage.local.get(AGENT_SETTINGS_KEY))[AGENT_SETTINGS_KEY] || {};
@@ -14,6 +15,17 @@ export function createAgentConnection({ chromeApi, execute }) {
return { enabled: settings.enabled === true, instanceId: settings.instanceId || "", status, error, protocolVersion: AGENT_PROTOCOL_VERSION };
};
+ async function prepare() {
+ preparing ??= (async () => {
+ const settings = await getSettings();
+ if (!settings.instanceId) await chromeApi.storage.local.set({ [AGENT_SETTINGS_KEY]: {
+ ...settings, enabled: settings.enabled === true, instanceId: crypto.randomUUID()
+ } });
+ return snapshot();
+ })().finally(() => { preparing = null; });
+ return preparing;
+ }
+
async function connect() {
if (port) return;
const epoch = generation;
@@ -73,6 +85,7 @@ export function createAgentConnection({ chromeApi, execute }) {
}
async function setEnabled(enabled) {
generation++;
+ await prepare();
const settings = await getSettings();
await chromeApi.storage.local.set({ [AGENT_SETTINGS_KEY]: {
enabled: enabled === true, instanceId: settings.instanceId || crypto.randomUUID()
@@ -84,5 +97,5 @@ export function createAgentConnection({ chromeApi, execute }) {
} else await start();
return snapshot();
}
- return { start, snapshot, setEnabled };
+ return { start, snapshot, setEnabled, prepare };
}
diff --git a/extension/agent-onboarding.js b/extension/agent-onboarding.js
new file mode 100644
index 0000000..7eff74c
--- /dev/null
+++ b/extension/agent-onboarding.js
@@ -0,0 +1,10 @@
+// Public instance identity scopes pairing; the request never contains the local
+// authentication secret or grants browser access by itself.
+export function agentConnectionRequest(instanceId, locale, homepage) {
+ if (!/^[a-f0-9-]{36}$/u.test(instanceId || '')) throw new Error('无效的资料库编号');
+ const repository = new URL(homepage);
+ const guide = `${repository.href.replace(/\/$/u, '')}/blob/main/connector/INSTALL.md`;
+ return locale === 'en'
+ ? `Connect my installed PromptDirector case library. Follow the official setup guide: ${guide}\nLibrary instance: ${instanceId}\nIdentify your host and whether you can run on my computer, install and configure the connector while preserving other MCP settings, then verify with a real library search. Ask me to enable the connection in Chrome when necessary. Do not report success from configuration alone.`
+ : `帮我连接已安装的 PromptDirector 案例库。请按官方安装说明完成:${guide}\n资料库编号:${instanceId}\n请识别当前 Agent 和本机执行环境,自动安装与配置连接器,保留其他 MCP 设置;需要浏览器授权时引导我在插件中启用。最后实际搜索一次案例库验证连接,不能只写好配置就报告成功。`;
+}
diff --git a/extension/agent-settings.js b/extension/agent-settings.js
index 272e54a..296e9c8 100644
--- a/extension/agent-settings.js
+++ b/extension/agent-settings.js
@@ -1,4 +1,5 @@
import { currentLocale } from './i18n.js';
+import { agentConnectionRequest } from './agent-onboarding.js';
const button = document.getElementById('toggle-agent-connection');
const status = document.getElementById('agent-connection-status');
@@ -10,14 +11,22 @@ async function refresh() {
const result = await chrome.runtime.sendMessage({ type: 'GET_AGENT_CONNECTION' });
if (!result?.ok) throw new Error(result?.message || copy('无法读取连接状态', 'Cannot read connection status'));
connection = result.connection;
- status.textContent = connection.status === 'connected' ? copy('已连接', 'Connected')
+ status.textContent = connection.status === 'connected' ? copy('连接器就绪', 'Connector ready')
: connection.status === 'connecting' ? copy('连接中…', 'Connecting…')
: connection.status === 'error' ? copy('连接异常', 'Connection error') : copy('未连接', 'Disconnected');
button.textContent = connection.enabled ? copy('断开', 'Disconnect') : copy('启用', 'Enable');
const connected = connection.status === 'connected';
help.hidden = connected;
- feedback.textContent = connected ? '' : [connection.error, connection.instanceId && copy(`配对编号:${connection.instanceId}`, `Pairing ID: ${connection.instanceId}`)].filter(Boolean).join(' · ');
+ feedback.textContent = connected ? '' : connection.error || '';
}
+document.getElementById('copy-agent-connection').addEventListener('click', async () => {
+ try {
+ const result = await chrome.runtime.sendMessage({ type: 'PREPARE_AGENT_CONNECTION' });
+ if (!result?.ok) throw new Error(result?.message || copy('无法准备连接', 'Cannot prepare connection'));
+ await navigator.clipboard.writeText(agentConnectionRequest(result.connection.instanceId, currentLocale(), chrome.runtime.getManifest().homepage_url));
+ feedback.textContent = copy('已复制。粘贴给你的 Agent,让它安装并连接;需要时在这里点击启用完成授权。', 'Copied. Paste into your Agent to install and connect. Enable here when browser permission is needed.');
+ } catch (error) { feedback.textContent = error.message; }
+});
button.addEventListener('click', async () => {
button.disabled = true;
try {
diff --git a/extension/background.js b/extension/background.js
index 7258d8a..274fe99 100644
--- a/extension/background.js
+++ b/extension/background.js
@@ -694,13 +694,15 @@ function openCreativeResultSidePanel(message, sender) {
async function handleMessage(message, interaction = {}) {
switch (message?.type) {
+ case "PREPARE_AGENT_CONNECTION":
case "GET_AGENT_CONNECTION":
case "SET_AGENT_CONNECTION": {
if (interaction.sender?.id !== chrome.runtime.id || !interaction.sender?.url?.startsWith(chrome.runtime.getURL(""))) {
throw new Error("Agent 连接只能在插件设置中管理");
}
return { ok: true, connection: message.type === "SET_AGENT_CONNECTION"
- ? await agentConnection.setEnabled(message.enabled === true) : await agentConnection.snapshot() };
+ ? await agentConnection.setEnabled(message.enabled === true)
+ : message.type === "PREPARE_AGENT_CONNECTION" ? await agentConnection.prepare() : await agentConnection.snapshot() };
}
case "GET_STATE": {
return enqueue(async () => ({ ok: true, ...publicLibraryState(await readState()) }));
diff --git a/extension/i18n.js b/extension/i18n.js
index 8aeb8f6..03654c2 100644
--- a/extension/i18n.js
+++ b/extension/i18n.js
@@ -4,8 +4,9 @@ const EN = Object.freeze({
"文章内案例": "Cases within article",
"已拆分 {count} 个案例,另有 {review} 组内容需要核对。": "Split into {count} cases; {review} additional groups need review.",
"未识别到可靠的多个案例边界,请保留整篇文章或手动选择内容": "No reliable boundaries between multiple cases were found. Keep the full article or select content manually.",
+ "复制连接指令": "Copy connection request",
"Agent 连接": "Agent connection",
- "安装本机连接器后启用,允许配对的 Agent 查询资料、读取原件和入库。网页采集需要网站访问权限;断开后停止接收新请求,已提交任务继续处理。": "Enable after installing the local connector. A paired Agent can search cases, read originals and save materials. Web capture requires website access. Disconnecting stops new requests; submitted tasks continue.",
+ "复制连接指令发给你的 Agent,由它完成安装和配对。需要浏览器授权时点击启用;断开后停止接收新请求,已提交任务继续处理。": "Copy the connection request to your Agent to install and pair. Enable when browser permission is needed. Disconnect stops new requests; submitted tasks continue.",
"案例库:按需;仅在你要求查询或参考时使用,点击关闭": "Library: on demand. Used only when you ask to search or reference it. Click to turn off.",
"案例库:关闭,点击开启": "Library: off. Click to enable.",
"当前模型未声明工具能力,可通过选择案例手动查询;点击关闭案例库": "Tool support is not declared for this model. Search manually using Select cases. Click to disable the library.",
diff --git a/extension/library.css b/extension/library.css
index df1b797..c738508 100644
--- a/extension/library.css
+++ b/extension/library.css
@@ -883,6 +883,8 @@ details:not([open]) > .selection-menu-panel { display: none; }
.setting-row .field-span { grid-column: 2 / -1; }
.capture-permission-list { display: flex; flex-wrap: wrap; gap: 8px 32px; }
.capture-permission-row { display: flex; align-items: center; gap: 12px; min-height: 36px; }
+.agent-connection-row { flex-wrap: wrap; }
+.agent-connection-actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.capture-permission-row strong { color: var(--ink); font-size: 12px; font-weight: 500; }
.capture-permission-row span { color: var(--muted); font-size: 11px; }
.capture-permission-row span.is-granted { color: var(--success); }
diff --git a/extension/library.html b/extension/library.html
index 68e8350..476392c 100644
--- a/extension/library.html
+++ b/extension/library.html
@@ -310,8 +310,8 @@
<p id="capture-permission-settings-feedback" class="data-safety-feedback" role="status" aria-live="polite"></p>
</section>
<section class="setting-section">
- <div class="capture-permission-row"><strong data-i18n="Agent 连接">Agent 连接</strong><span id="agent-connection-status" role="status" data-i18n="未连接">未连接</span><button id="toggle-agent-connection" class="button-secondary" type="button" data-i18n="启用">启用</button></div>
- <p id="agent-connection-help" class="data-safety-feedback" hidden data-i18n="安装本机连接器后启用,允许配对的 Agent 查询资料、读取原件和入库。网页采集需要网站访问权限;断开后停止接收新请求,已提交任务继续处理。">安装本机连接器后启用,允许配对的 Agent 查询资料、读取原件和入库。网页采集需要网站访问权限;断开后停止接收新请求,已提交任务继续处理。</p>
+ <div class="capture-permission-row agent-connection-row"><strong data-i18n="Agent 连接">Agent 连接</strong><span id="agent-connection-status" role="status" data-i18n="未连接">未连接</span><div class="agent-connection-actions"><button id="copy-agent-connection" class="button-secondary" type="button" data-i18n="复制连接指令">复制连接指令</button><button id="toggle-agent-connection" class="button-secondary" type="button" data-i18n="启用">启用</button></div></div>
+ <p id="agent-connection-help" class="data-safety-feedback" hidden data-i18n="复制连接指令发给你的 Agent,由它完成安装和配对。需要浏览器授权时点击启用;断开后停止接收新请求,已提交任务继续处理。">复制连接指令发给你的 Agent,由它完成安装和配对。需要浏览器授权时点击启用;断开后停止接收新请求,已提交任务继续处理。</p>
<p id="agent-connection-feedback" class="data-safety-feedback" role="status" aria-live="polite"></p>
</section>
<section id="data-safety-dialog" class="setting-section settings-data-safety">
diff --git a/extension/manifest.json b/extension/manifest.json
index d0bbaf6..5c36bef 100644
--- a/extension/manifest.json
+++ b/extension/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "__MSG_extensionName__",
- "version": "1.21.0",
+ "version": "1.21.1",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq2m8W9ACXJTkJqPAd36sPrtzonmHhOYU34uS7c+D7DXX6ggWNMwB4xZapGFJ4ScBQJv71PeG9KfsEnhcXFZ9RoX/X3wY+57evL19hf6woNX1xxhKOe1rtx5QmzWCEYIr99TzW50k/N9U6tS9Ri+2DHKYA85ssXTC8B2yRQ5zUXhsAWZe/HDU18UFuvUKXYt3ZdIUi31c2vIlgFFBfsyKbIUMny9LlxL/smb4vJzU/+A3LwJDjjvOtS/lmQ2vHoQGjHJItO18bYI6h67fIEvmWk+HJKtO08Ca+5RLS8TYhI+K7l7S0RyDVNujyVWtvhAULot1H0BvteYL87fKu3SNywIDAQAB",
"homepage_url": "https://github.com/wchao6891/PromptDirector",
"default_locale": "zh_CN",
diff --git a/package-lock.json b/package-lock.json
index ef10358..06eca99 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "prompt-case-collector",
- "version": "1.21.0",
+ "version": "1.21.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "prompt-case-collector",
- "version": "1.21.0",
+ "version": "1.21.1",
"license": "Apache-2.0",
"dependencies": {
"@jonahschulte/rtf-toolkit": "0.5.0",
diff --git a/package.json b/package.json
index 212df61..64835bb 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "prompt-case-collector",
- "version": "1.21.0",
+ "version": "1.21.1",
"private": false,
"license": "Apache-2.0",
"repository": "https://github.com/wchao6891/PromptDirector",
diff --git a/store/CHROME_WEB_STORE_SUBMISSION.md b/store/DISTRIBUTION.md
similarity index 89%
rename from store/CHROME_WEB_STORE_SUBMISSION.md
rename to store/DISTRIBUTION.md
index 22e6867..5f35328 100644
--- a/store/CHROME_WEB_STORE_SUBMISSION.md
+++ b/store/DISTRIBUTION.md
@@ -1,13 +1,13 @@
-# Chrome Web Store submission worksheet
+# Distribution and permissions
-This file is the source-of-truth worksheet for the current PromptDirector manifest. Do not submit a package if `npm run check:store` or the full browser suite is red.
+Public distribution formats and the permissions used by PromptDirector.
## Stable Web Store identity
- Chrome Web Store item public key: stored in the source `manifest.json` for local identity verification only; `package:release` removes `key` from the upload manifest.
- Expected extension ID: `iahakaahijddcjjldidbclicedibgpjm`.
-- Current upload artifact: `dist/PromptDirector-1.21.0.zip`. The GitHub `FIXED-ID-DEV` artifact is for local installations only.
-- Generate a candidate only with `npm run package:release`; the command verifies the source public key against the expected identity, then removes `key` from the Web Store upload manifest and excludes the local program installer. Record the generated ZIP size and SHA-256 from the final release assets.
+- Current upload artifact: `dist/PromptDirector-1.21.1.zip`. The GitHub `FIXED-ID-DEV` artifact is for local installations only.
+- Generate a candidate only with `npm run package:release`; the command verifies the source public key against the expected identity, then removes `key` from the Web Store upload manifest and excludes the local program installer.
## Store listing
@@ -27,7 +27,7 @@ This file is the source-of-truth worksheet for the current PromptDirector manife
Help visual creators capture web visuals with their prompts, media, and notes as a searchable, reusable local creative archive.
-Chinese Dashboard value:
+中文用途说明:
> 帮助视觉创作者在用户主动操作下,将网页画面、提示词、媒体和笔记保存为可检索、可复用的本地创作资料,并以这些资料创建创作 Skill 和提示词。
@@ -86,16 +86,4 @@ Data types handled, including local-only handling:
- Website content and resources: user-selected text, images, videos, documents, and screenshots.
- User-generated content: prompts, notes, cases, projects, tags, Skills, and creative requests.
-Do not select personally identifiable information, health information, financial or payment information, location, personal communications, or generic user activity; PromptDirector does not intentionally handle these as product data.
-
-## Final local gate
-
-Run, in order:
-
-```text
-npm run verify
-npm run test:e2e
-npm run package:release
-```
-
-Then load the exact release candidate in a clean Chrome profile and visibly verify capture, library search/read-back, Skill creation, Composer, backup/restore, and extension identity before submitting for review.
+See the privacy policy for the data handled by user-triggered operations.
diff --git a/test/LOCAL_EXTENSION_LAB.md b/test/LOCAL_EXTENSION_LAB.md
deleted file mode 100644
index bbd2d92..0000000
--- a/test/LOCAL_EXTENSION_LAB.md
+++ /dev/null
@@ -1,38 +0,0 @@
-# PromptDirector 本地插件实验室
-
-本模块把正式打包出的固定 ID 开发插件解压后,加载到 Chrome for Testing 的全新隔离资料中,再运行现有完整浏览器回归。它不会读取或修改用户日常 Chrome 资料,也不会使用真实 API Key。
-
-## 运行
-
-```bash
-npm run test:local-extension
-```
-
-Chrome for Testing 是 Chrome 官方为自动化提供的可复现浏览器。正式品牌版 Chrome 已移除命令行侧载扩展所需的开关,因此本模块不会把无法稳定复现的用户 Chrome 环境伪装成自动化能力。
-
-## 每次运行会证明什么
-
-- 测试对象来自 `npm run package` 生成的 `FIXED-ID-DEV` 插件包,不直接加载源码目录。
-- Manifest 公钥、扩展 ID、版本、Service Worker 和三个核心页面来自同一份运行文件。
-- 测试浏览器、用户代理和每次运行的结果写入收据,可追溯当时使用的自动化运行时。
-- 每条浏览器场景使用全新隔离资料,避免历史状态让结果随机通过或失败。
-- 实验室模式默认阻断所有未被场景显式 mock 的外部 HTTPS 请求;漏写 mock 会直接失败,不会误连真实服务或消耗真实额度。
-- 收据强制要求模型注册、文字与图片分析、创作台生成、视频生成、异步任务恢复,以及智谱 GLM 五项分析任务与创作台规划链路存在且通过;测试清单若误删关键场景,整次实验室运行会失败。
-- 现有本地模型模拟服务会继续覆盖成功、失败、异步轮询和恢复,不消耗真实模型额度。
-- 运行结束生成机器可读收据、完整日志和核心页面截图。
-
-证据默认保存在:
-
-```text
-dist/local-extension-lab/runs/<运行时间>/
-```
-
-`dist/local-extension-lab/latest.json` 指向最近一次结果。整个目录属于可重建产物,不进入 Git。
-
-## 它不能证明什么
-
-- 用户当前安装的 Chrome 插件包和本地实验室完全相同。
-- 智谱、OpenAI、Gemini 等真实账号当前可用、计费正确或模型质量达标。
-- GitHub Release、Chrome Web Store 上传、审核或线上分发状态。
-
-这些证据必须继续单独记录;本地实验室通过时只能称为“打包插件在 Chrome for Testing 自动验收通过”。
diff --git a/test/agent-connector.test.js b/test/agent-connector.test.js
index 10d9c5e..eda0d6c 100644
--- a/test/agent-connector.test.js
+++ b/test/agent-connector.test.js
@@ -149,3 +149,20 @@ test('first native permission grant without a worker binding requests manual rel
assert.equal((await restarted.snapshot()).status, 'connected');
assert.equal((await restarted.snapshot()).instanceId, instanceId);
});
+
+
+test('copying connection instructions creates stable identity without granting access', async () => {
+ const store = storage();
+ const event = { addListener() {} };
+ const connection = createAgentConnection({ chromeApi: {
+ storage: { local: store }, runtime: { onStartup: event },
+ alarms: { onAlarm: event }, permissions: { onRemoved: event }
+ }, execute() { assert.fail('copy does not execute library operations'); } });
+ const results = await Promise.all([connection.prepare(), connection.prepare()]);
+ assert.equal(results[0].instanceId, results[1].instanceId);
+ assert.equal(results[0].enabled, false);
+ const { agentConnectionRequest } = await import('../extension/agent-onboarding.js');
+ const request = agentConnectionRequest(results[0].instanceId, 'zh_CN', 'https://github.com/example/project');
+ assert(request.includes(results[0].instanceId)); assert(request.includes('/blob/main/connector/INSTALL.md'));
+ assert.equal((await connection.prepare()).instanceId, results[0].instanceId);
+});
diff --git a/test/agent_library_e2e.py b/test/agent_library_e2e.py
index 5ba481d..dded183 100644
--- a/test/agent_library_e2e.py
+++ b/test/agent_library_e2e.py
@@ -4,6 +4,7 @@ Native transport is covered separately; this is not native permission acceptance
import base64
import hashlib
import json
+import os
import tempfile
import time
from pathlib import Path
@@ -62,6 +63,26 @@ def main():
page.wait_for_function("async () => (await chrome.runtime.sendMessage({type:'GET_STATE'})).entries.length === 1")
assert page.locator('#toggle-agent-connection').count() == 1
assert page.locator('#agent-connection-help').count() == 1
+ run.seed_storage(page, {'capturePermissionOnboarding': {'version': 1, 'acknowledgedAt': '2026-09-12T00:00:00Z', 'clipboardIncluded': True}})
+ page.evaluate("() => { if (!document.querySelector('#settings-dialog').open) document.querySelector('#open-settings').click(); }")
+ page.locator('[data-settings-tab="general"]').click()
+ # Clipboard is isolated to the test; clicking still runs the actual
+ # instance preparation and builds the same user-facing request.
+ page.evaluate("() => { navigator.clipboard.writeText = async text => { window.copiedAgentRequest = text; }; }")
+ page.locator('#copy-agent-connection').click()
+ page.wait_for_function('() => !!window.copiedAgentRequest')
+ copied = page.evaluate('window.copiedAgentRequest')
+ connection = page.evaluate("async () => (await chrome.runtime.sendMessage({type:'GET_AGENT_CONNECTION'})).connection")
+ assert connection['instanceId'] in copied and 'connector/INSTALL.md' in copied
+ assert connection['enabled'] is False, connection
+ page.locator('#copy-agent-connection').click()
+ assert page.evaluate('window.copiedAgentRequest') == copied
+ page.locator('#copy-agent-connection').scroll_into_view_if_needed()
+ evidence = Path(os.environ.get('PROMPTDIRECTOR_LAB_EVIDENCE_DIR', str(ext)))
+ evidence.mkdir(parents=True, exist_ok=True)
+ page.screenshot(path=str(evidence / 'agent-onboarding.png'))
+ page.set_viewport_size({'width': 390, 'height': 844})
+ page.screenshot(path=str(evidence / 'agent-onboarding-mobile.png'))
print('PASS: actual worker, offscreen document preparation, original bytes, prompt association, search/read, retry and persistent library')
if __name__ == '__main__':
diff --git a/test/composer_library_knowledge_e2e.py b/test/composer_library_knowledge_e2e.py
index 52cec09..0f9be77 100644
--- a/test/composer_library_knowledge_e2e.py
+++ b/test/composer_library_knowledge_e2e.py
@@ -96,8 +96,11 @@ def main() -> None:
expect(page.locator("#composer-reference-count")).to_have_text("0")
cover = page.locator('.composer-library-candidate img').first
expect(cover).to_be_visible()
+ # An img with no src is already complete; wait for the managed fixture
+ # to load and decode, including when the candidate is rendered again.
+ expect(cover).to_have_js_property('naturalWidth', 1)
+ expect(cover).to_have_js_property('naturalHeight', 1)
expect(cover).to_have_js_property('complete', True)
- assert cover.evaluate('node => node.naturalWidth') > 0
assert 'data:image' not in json.dumps(requests[-1]) and 'blob:' not in json.dumps(requests[-1])
expect(page.locator(".composer-retrieved-source")).to_have_count(0)
expect(page.locator("#composer-send-note")).to_contain_text("本轮已请求 2 次")
diff --git a/tools/check-store-readiness.mjs b/tools/check-store-readiness.mjs
index 680991d..a3189d7 100644
--- a/tools/check-store-readiness.mjs
+++ b/tools/check-store-readiness.mjs
@@ -27,7 +27,7 @@ for (const phrase of ["Chrome Web Store User Data Policy", "Limited Use", "不
const listingZh = await text("store/LISTING_ZH_CN.md");
const listingEn = await text("store/LISTING_EN.md");
-const submission = await text("store/CHROME_WEB_STORE_SUBMISSION.md");
+const submission = await text("store/DISTRIBUTION.md");
requireText(submission, `dist/PromptDirector-${manifest.version}.zip`, "商店提交清单版本与 manifest 不一致");
requireText(listingZh, locales.zh_CN.extensionName.message, "中文商店名称与 manifest 不一致");
requireText(listingEn, locales.en.extensionName.message, "英文商店名称与 manifest 不一致");
diff --git a/tools/package-connector.mjs b/tools/package-connector.mjs
index 53ee621..ac1e486 100644
--- a/tools/package-connector.mjs
+++ b/tools/package-connector.mjs
@@ -8,7 +8,7 @@ const manifest = JSON.parse(await readFile(join(root, 'extension/manifest.json')
// Ship reviewable source and pinned dependencies, never a maintainer's runtime
// directory, pairing records, downloaded originals or node_modules.
const names = (await readdir(join(root, 'connector'), { withFileTypes: true }))
- .filter(item => item.isFile() && (item.name.endsWith('.mjs') || ['README.md', 'SKILL.md', 'package.json', 'package-lock.json'].includes(item.name)))
+ .filter(item => item.isFile() && (item.name.endsWith('.mjs') || ['README.md', 'INSTALL.md', 'SKILL.md', 'package.json', 'package-lock.json'].includes(item.name)))
.map(item => `connector/${item.name}`);
names.push('extension/manifest.json', 'LICENSE', 'NOTICE', 'THIRD_PARTY_NOTICES.md');
const files = await Promise.all(names.sort().map(async name => ({ name, data: await readFile(join(root, name)) })));
diff --git a/tools/validate-public-source.mjs b/tools/validate-public-source.mjs
index 093bcfd..b5c10e1 100644
--- a/tools/validate-public-source.mjs
+++ b/tools/validate-public-source.mjs
@@ -14,7 +14,7 @@ const privateWorkspaceDirectories = [
join("docs", "research")
];
-const privateWorkspaceFiles = ["CONTEXT.md", "context.md"];
+const privateWorkspaceFiles = ["CONTEXT.md", "context.md", "docs/DESIGN.md", "test/LOCAL_EXTENSION_LAB.md", "store/CHROME_WEB_STORE_SUBMISSION.md"];
const presentPrivateDirectories = [];
for (const path of privateWorkspaceDirectories) {