Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

refactor(protocol): 本地化跨端协议包 (#2373)

bobob247c2d324a5
diff --git a/.easignore b/.easignore
index ca8da08182..44869b21f7 100644
--- a/.easignore
+++ b/.easignore
@@ -50,6 +50,8 @@ packages/*
!packages/auth-client/**
!packages/device-link
!packages/device-link/**
+!packages/device-link-protocol
+!packages/device-link-protocol/**
!packages/maker-shared
!packages/maker-shared/**
!packages/model-providers
@@ -57,10 +59,6 @@ packages/*
!packages/voice-input-core
!packages/voice-input-core/**
-# mobile 的 device-link 传递依赖 cindy-protocol submodule;EAS 上传必须带源码。
-!cindy-protocol
-!cindy-protocol/**
-
tools/*
!tools/shared
!tools/shared/fetch-with-timeout.mjs
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 8659e597a8..688aad3810 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -13,7 +13,9 @@
# 统一模型 registry 的协议、内置快照、远程加载与运行时投影是同一权威面。
# 最后匹配规则覆盖上面的通用 owner;任何改动都会显式请求 registry owner。
/.github/CODEOWNERS @zqchris
-/cindy-protocol @zqchris
+/packages/device-link-protocol/ @zqchris
+/packages/plugin-protocol/ @zqchris
+/packages/slack-hook-protocol/ @zqchris
/packages/model-providers/catalog/model-registry.json @zqchris
/packages/model-providers/src/catalog.ts @zqchris
/packages/model-providers/src/modelRegistry.ts @zqchris
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3c267f5c9a..0a0401aced 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -31,46 +31,12 @@ jobs:
timeout-minutes: 40
steps:
- # 主仓与公开 submodule 都使用 GitHub 默认的只读访问路径。
- name: Checkout client
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
lfs: true
- # .gitmodules 来自 PR 分支,fork PR 可以把 cindy-protocol 的 url / path 改成
- # 任意仓库。先钉死来源再 sync/update,避免 CI 拉取并 pnpm install 第三方仓库
- # 内容。gitlink 的 commit 同样来自 PR,但只能从 makecindy/cindy-protocol 拉取,
- # 外部无法向该仓库推送,所以来源钉死后取到的一定是本组织的历史。
- - name: Verify cindy-protocol submodule source
- run: |
- set -euo pipefail
- expected_url='https://github.com/makecindy/cindy-protocol.git'
- expected_path='cindy-protocol'
- actual_url="$(git config -f .gitmodules --get submodule.cindy-protocol.url || true)"
- actual_path="$(git config -f .gitmodules --get submodule.cindy-protocol.path || true)"
- if [ "$actual_url" != "$expected_url" ] || [ "$actual_path" != "$expected_path" ]; then
- echo "::error file=.gitmodules::cindy-protocol submodule 来源不符: url='$actual_url' path='$actual_path'(期望 url='$expected_url' path='$expected_path')"
- exit 1
- fi
- echo "cindy-protocol submodule 来源校验通过: $actual_url"
-
- # 本 job 只做本仓 typecheck / runner 自测 / 各类 guard。cindy-protocol 是公开的
- # workspace 依赖,需要 checkout 以供 pnpm install 解析,但不在本 job 运行
- # 协议仓自己的 CI。
- # 公开客户端不包含内建插件种子;相关单测只在 os.tmpdir 里自造夹具。
- # 公开仓不提供官方发布流程。
- - name: Fetch cindy-protocol submodule
- run: |
- git submodule sync -- cindy-protocol
- git submodule update --init --force --recursive -- cindy-protocol
-
- - name: Reject cindy-protocol rollback or divergence
- if: ${{ github.event_name == 'pull_request' }}
- env:
- CINDY_PROTOCOL_BASE_REF: ${{ github.event.pull_request.base.sha }}
- run: node scripts/check-submodule-forward.mjs
-
- name: Setup pnpm
uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6
with:
@@ -86,12 +52,6 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile
- # @cindy/model-access-protocol exposes only generated dist artifacts.
- # Build it before any consumer typecheck or test collection resolves the
- # workspace package.
- - name: Build model-access protocol
- run: pnpm --filter @cindy/model-access-protocol build
-
# test:unit 的 runner 自测不能跟着 Vitest 分片重复执行;在检查 job 中跑一次,
# 两个 Linux 单测分片只负责 workspace unit tier。
- name: Run test runner self-tests
@@ -156,32 +116,6 @@ jobs:
fetch-depth: 0
lfs: true
- - name: Verify cindy-protocol submodule source
- run: |
- set -euo pipefail
- expected_url='https://github.com/makecindy/cindy-protocol.git'
- expected_path='cindy-protocol'
- actual_url="$(git config -f .gitmodules --get submodule.cindy-protocol.url || true)"
- actual_path="$(git config -f .gitmodules --get submodule.cindy-protocol.path || true)"
- if [ "$actual_url" != "$expected_url" ] || [ "$actual_path" != "$expected_path" ]; then
- echo "::error file=.gitmodules::cindy-protocol source mismatch: url='$actual_url' path='$actual_path' (expected url='$expected_url' path='$expected_path')"
- exit 1
- fi
- echo "cindy-protocol submodule source verified: $actual_url"
-
- - name: Fetch cindy-protocol submodule
- run: |
- git submodule sync -- cindy-protocol
- git submodule update --init --force --recursive -- cindy-protocol
-
- # 分片会安装并执行 submodule 代码,不能只依赖并行的 verify-checks 最终阻断;
- # 每个分片都必须在安装依赖前独立拒绝回滚、分叉或未发布的 gitlink。
- - name: Reject cindy-protocol rollback or divergence
- if: ${{ github.event_name == 'pull_request' }}
- env:
- CINDY_PROTOCOL_BASE_REF: ${{ github.event.pull_request.base.sha }}
- run: node scripts/check-submodule-forward.mjs
-
- name: Setup pnpm
uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6
with:
@@ -197,9 +131,6 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile
- - name: Build model-access protocol
- run: pnpm --filter @cindy/model-access-protocol build
-
# XDT_SKIP_AGENT_BIN_INSTALL 跳过了 postinstall 的全部 agent 二进制,但
# runtime-configs.ts 模块顶层的 bundledRipgrepDir() 缺 rg 时直接 throw,
# 会让 apps/desktop 单测在收集阶段全挂——每个分片都必须单独装回来。
@@ -209,8 +140,7 @@ jobs:
run: pnpm install:ripgrep
- name: Run client and package unit test shard
- # 通过 pnpm 启动 runner,保留当前 pnpm 入口;否则嵌套的 protocol
- # workspace 无法从主仓根 node_modules 解析 Vitest。
+ # 通过 pnpm 启动 runner,保留当前 pnpm 入口与 workspace 解析语义。
run: pnpm exec node scripts/test-workspaces.mjs --tier unit
# 保留原 required check 名 verify;检查 job 或任一 Linux 分片失败、取消都阻断。
@@ -250,28 +180,6 @@ jobs:
fetch-depth: 0
lfs: true
- # GitHub-hosted Windows 带 Git Bash;复用 Linux job 的 fail-closed 来源校验,
- # 同时保留 win32 Node / 文件系统语义供后续单测覆盖。
- - name: Verify cindy-protocol submodule source
- shell: bash
- run: |
- set -euo pipefail
- expected_url='https://github.com/makecindy/cindy-protocol.git'
- expected_path='cindy-protocol'
- actual_url="$(git config -f .gitmodules --get submodule.cindy-protocol.url || true)"
- actual_path="$(git config -f .gitmodules --get submodule.cindy-protocol.path || true)"
- if [ "$actual_url" != "$expected_url" ] || [ "$actual_path" != "$expected_path" ]; then
- echo "::error file=.gitmodules::cindy-protocol source mismatch: url='$actual_url' path='$actual_path' (expected url='$expected_url' path='$expected_path')"
- exit 1
- fi
- echo "cindy-protocol submodule source verified: $actual_url"
-
- - name: Fetch cindy-protocol submodule
- shell: bash
- run: |
- git submodule sync -- cindy-protocol
- git submodule update --init --force --recursive -- cindy-protocol
-
- name: Setup pnpm
uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6
with:
@@ -287,9 +195,6 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile
- - name: Build model-access protocol
- run: pnpm --filter @cindy/model-access-protocol build
-
- name: Install bundled ripgrep
env:
GITHUB_TOKEN: ${{ github.token }}
@@ -322,26 +227,6 @@ jobs:
fetch-depth: 0
lfs: true
- # `.gitmodules` comes from the PR branch. Pin the public protocol source
- # before recursively initializing it, matching the verify job boundary.
- - name: Verify cindy-protocol submodule source
- run: |
- set -euo pipefail
- expected_url='https://github.com/makecindy/cindy-protocol.git'
- expected_path='cindy-protocol'
- actual_url="$(git config -f .gitmodules --get submodule.cindy-protocol.url || true)"
- actual_path="$(git config -f .gitmodules --get submodule.cindy-protocol.path || true)"
- if [ "$actual_url" != "$expected_url" ] || [ "$actual_path" != "$expected_path" ]; then
- echo "::error file=.gitmodules::cindy-protocol source mismatch: url='$actual_url' path='$actual_path' (expected url='$expected_url' path='$expected_path')"
- exit 1
- fi
- echo "cindy-protocol submodule source verified: $actual_url"
-
- - name: Fetch cindy-protocol submodule
- run: |
- git submodule sync -- cindy-protocol
- git submodule update --init --force --recursive -- cindy-protocol
-
- name: Setup pnpm
uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6
with:
diff --git a/.gitmodules b/.gitmodules
deleted file mode 100644
index cae9470645..0000000000
--- a/.gitmodules
+++ /dev/null
@@ -1,3 +0,0 @@
-[submodule "cindy-protocol"]
- path = cindy-protocol
- url = https://github.com/makecindy/cindy-protocol.git
diff --git a/AGENTS.md b/AGENTS.md
index 4bebbfe2d1..3564e8b3bf 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -103,9 +103,9 @@
(deny-by-default,不得改成黑名单——调试级别的功能日志是用户内容的主要泄漏源)、
**标记代次 + 原子清除**(并发实例下仅靠时间戳会误删另一实例刚写的新崩溃标记)。
脱敏规则**只增不减**,放宽任一条视为隐私变更、需重新评审。
-- 升级 `cindy-protocol`、修改插件分发来源边界或 device-link 协议/relay/隧道
+- 修改本地协议 package、插件分发来源边界或 device-link 协议/relay/隧道
payload/IPC allowlist,或任何改动跨端 wire protocol 前,必须先读
- `docs/dev-rules/protocol-and-submodules.md`。
+ `docs/dev-rules/protocol-compatibility.md`。
- 修改 package 依赖方向、main 进程模块加载方式,或主界面布局树结构前,必须先读
`docs/dev-rules/architecture-invariants.md`。
- 新增或修改 Settings UI、配置文件、本地偏好、运行时 profile,或 agent/MCP/provider
diff --git a/README.md b/README.md
index c6d1093d0d..73961d4951 100644
--- a/README.md
+++ b/README.md
@@ -63,7 +63,6 @@ Ready out of the box, never boxed in — start with
| `apps/mobile` | Expo / React Native mobile client |
| `packages/*` | Shared client capabilities (auth, device-link, agent orchestration, model providers, …) |
| `apps/*-bin` | Tool binaries shipped with the desktop app; none are committed — claude-code, codex, and ripgrep are downloaded per platform by `pnpm install`, and the Android platform-tools binaries are fetched (pinned version, sha256-verified) before Windows packaging |
-| `cindy-protocol/` | Wire protocol shared with the server (git submodule) |
**Not in this repo:** the backend service lives in a separate
repository and is not part of this monorepo.
@@ -81,18 +80,15 @@ repository and is not part of this monorepo.
## Getting started
-Contributor setup, public submodule initialization, Git LFS, dependency updates,
-and access requirements are maintained in
+Contributor setup, Git LFS, dependency updates, and access requirements are maintained in
[`CONTRIBUTING.en.md`](CONTRIBUTING.en.md).
-The public checkout only needs the protocol submodule; plugins are installed through
-SkillHub or manually.
+Plugins are installed through SkillHub or manually.
Minimal entry point:
```bash
git clone https://github.com/makecindy/cindy.git
cd cindy
-git submodule update --init --recursive cindy-protocol
git lfs pull
pnpm install
```
diff --git a/README.zh-CN.md b/README.zh-CN.md
index edcb4f4d4f..4f1caabe7f 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -62,7 +62,6 @@ monorepo 组织。
| `apps/mobile` | Expo / React Native 手机客户端 |
| `packages/*` | 客户端共享能力(鉴权、device-link、agent 编排、模型供应商等) |
| `apps/*-bin` | 桌面端附带的工具二进制,均不入库;claude-code / codex / ripgrep 由 `pnpm install` 按平台自动下载,Android platform-tools 在 Windows 打包前按 pin 版本下载并校验 sha256 |
-| `cindy-protocol/` | 与服务端共用的协议(git submodule) |
**服务端不在本仓库:** 服务端位于独立仓库,不属于本 monorepo。
@@ -79,16 +78,14 @@ monorepo 组织。
## 开始开发
-开发者安装、公开 submodule 初始化、Git LFS、依赖更新和权限说明统一见
-[`CONTRIBUTING.md`](CONTRIBUTING.md)。公开贡献者只需初始化公开的协议 submodule;
-插件通过 SkillHub 或手动安装,不要使用未列出的递归初始化命令。
+开发者安装、Git LFS、依赖更新和权限说明统一见
+[`CONTRIBUTING.md`](CONTRIBUTING.md)。插件通过 SkillHub 或手动安装。
最短入口:
```bash
git clone https://github.com/makecindy/cindy.git
cd cindy
-git submodule update --init --recursive cindy-protocol
git lfs pull
pnpm install
```
diff --git a/REVIEW.md b/REVIEW.md
index 1436a9d943..0fbbeb8f17 100644
--- a/REVIEW.md
+++ b/REVIEW.md
@@ -65,8 +65,8 @@ P1/P2。按下表转换,**不要**把仓库口径的 P2 改写成评论里
`apps/mobile/package.json`/`plugins/`/`modules/` 等进入 runtime fingerprint 的输入。
命中就在评论里点名——这类 PR 需要把关人对冷更单独确认。见
`docs/dev-rules/mobile-development.md`。
-- **协议兼容**:`cindy-protocol` 升级、device-link/relay/隧道 payload、IPC allowlist
- 等跨端 wire protocol 的向后兼容性。见 `docs/dev-rules/protocol-and-submodules.md`。
+- **协议兼容**:本地协议 package、device-link/relay/隧道 payload、IPC allowlist
+ 等跨端 wire protocol 的向后兼容性。见 `docs/dev-rules/protocol-compatibility.md`。
- **device-link 恢复动作的故障半径**:重试/超时/断链/重连路径的改动,恢复动作的
作用半径是否大于故障半径——被控端一条 relay 连接服务同账号全部控制端,单 peer
故障不得强拆整条共享连接;扩大半径必须在 PR 描述里给出明确理由,并有多控制端拓扑
@@ -96,8 +96,6 @@ P1/P2。按下表转换,**不要**把仓库口径的 P2 改写成评论里
## 5. 评审环境的已知限制
-- `cindy-protocol` submodule **未** checkout,该目录下的文件读不到。不要据此推断
- 文件缺失或引用失效。
- 只 checkout 了 PR 的 merge ref 与最近 100 条历史,更早的 `git log`/`git blame`
会不完整。
- 依赖未安装,无法运行测试或构建;结论只能来自静态阅读。
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index fe460f8e7d..67c256a1c6 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -51,7 +51,6 @@
"license": "Apache-2.0",
"dependencies": {
"@cindy/auth-client": "workspace:*",
- "@cindy/model-access-protocol": "workspace:*",
"@cindy/plugin-protocol": "workspace:*",
"@cindy/slack-hook-protocol": "workspace:*",
"@codemirror/commands": "^6.10.3",
diff --git a/apps/desktop/src/main/im/shared/__tests__/botCommands.test.ts b/apps/desktop/src/main/im/shared/__tests__/botCommands.test.ts
index fc6d6f9dd7..62fc9dd9ce 100644
--- a/apps/desktop/src/main/im/shared/__tests__/botCommands.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/botCommands.test.ts
@@ -21,7 +21,7 @@ import {
*
* 它**挡不住服务端单方面加减命令** —— 那边一改, 这边两份都不动, 测试照样绿。
* 真要防住跨仓漂移得有一份可消费的共享契约(把 `TELEGRAM_COMMANDS` 放进
- * `cindy-protocol`, 两侧都从它生成), 或者在服务端加反向校验; 两条路都要跨仓
+ * 两仓本地协议 package,两侧分别生成),或者在服务端加反向校验;两条路都要跨仓
* 改动与一次协议版本推进, 另立 PR。这里不宣称自己做到了那件事。
*/
const OFFICIAL_SERVER_COMMANDS = [
diff --git a/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts b/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts
index 2a2e888bec..c38f33248b 100644
--- a/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts
+++ b/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts
@@ -1,8 +1,8 @@
/**
* modelPlanePolicy —— 内置供应商模型平面的**表驱动 policy**(纯逻辑,零 IO)。
*
- * 三件事严格分离(2026-08-02 架构收敛定案,协议侧契约见 cindy-protocol
- * MODEL_REGISTRY.md「Presence, entitlement, and sale availability」):
+ * 三件事严格分离(2026-08-02 架构收敛定案,协议侧契约见本仓
+ * modelRegistryCanonical.ts 的「Presence, entitlement, and sale availability」):
* - roots:该供应商的 canonical 实体列表落在哪些 agent。实体化 / discovery /
* 本地 override 只作用于 root;派生端(bridge / Pi)永远重算,禁止直写。
* - membership:registry route.agents 声明「允许出现在哪些消费端」,不是 root
diff --git a/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts b/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
index 6f853bac04..22fa899264 100644
--- a/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
+++ b/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
@@ -16,6 +16,7 @@ describe('parseModelsSyncPayload', () => {
currency: 'CNY' as const,
agents: ['claude-code', 'codex'] as const,
mode: 'chat',
+ icon: 'deepseek',
modalities: { input: ['text'], output: ['text'] },
};
@@ -37,6 +38,34 @@ describe('parseModelsSyncPayload', () => {
});
});
+ it('preserves a missing legacy currency for the pricing fallback path', () => {
+ const { currency: _currency, ...modelWithoutCurrency } = baseModel;
+
+ expect(parseModelsSyncPayload({ schemaVersion: 2, models: [modelWithoutCurrency] })).toEqual({
+ ok: true,
+ models: [modelWithoutCurrency],
+ });
+ });
+
+ it('preserves missing agents and null effort defaults for existing catalog fallbacks', () => {
+ const { agents: _agents, ...modelWithoutAgents } = baseModel;
+ const legacyModel = { ...modelWithoutAgents, defaultEffort: null } as const;
+ const modelWithOverride = {
+ ...baseModel,
+ defaultEffort: null,
+ perAgent: { codex: { defaultEffort: null } },
+ } as const;
+
+ expect(parseModelsSyncPayload({ schemaVersion: 2, models: [legacyModel] })).toEqual({
+ ok: true,
+ models: [legacyModel],
+ });
+ expect(parseModelsSyncPayload({ schemaVersion: 2, models: [modelWithOverride] })).toEqual({
+ ok: true,
+ models: [modelWithOverride],
+ });
+ });
+
it.each([
{
label: 'unknown schema version',
diff --git a/apps/desktop/src/main/model-access/modelsSyncRefresh.ts b/apps/desktop/src/main/model-access/modelsSyncRefresh.ts
index 8b04eca8b9..aedea7580f 100644
--- a/apps/desktop/src/main/model-access/modelsSyncRefresh.ts
+++ b/apps/desktop/src/main/model-access/modelsSyncRefresh.ts
@@ -1,5 +1,9 @@
-import { parseListModelsResponse } from '@cindy/model-access-protocol';
-import type { ModelAccessGatewayModel, ModelAccessStatus } from '../../shared/modelAccess.js';
+import { parseListModelsResponse } from '@cindy/model-providers';
+import type {
+ ModelAccessGatewayModel,
+ ModelAccessModelsResponse,
+ ModelAccessStatus,
+} from '../../shared/modelAccess.js';
import type { CredentialsSync } from './credentialsSync.js';
/** Bound the shared single-flight so a black-hole connection cannot block later refreshes. */
@@ -10,13 +14,14 @@ export type ModelsSyncPayloadParseResult =
/**
* Validate the actual `/models` wire envelope before it can replace the last-known-good snapshot.
- * The shared protocol parser is the version boundary: it accepts the frozen v1 and current v2
+ * The client-owned parser is the version boundary: it accepts the frozen v1 and current v2
* contracts, and rejects unknown versions or fields instead of partially interpreting them.
*/
export function parseModelsSyncPayload(value: unknown): ModelsSyncPayloadParseResult {
const parsed = parseListModelsResponse(value);
if (!parsed.ok) return parsed;
- return { ok: true, models: parsed.value.models };
+ const response: ModelAccessModelsResponse = parsed.value;
+ return { ok: true, models: response.models };
}
/**
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx
index eb791cce2d..777dba5888 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx
@@ -41,6 +41,13 @@ beforeEach(() => {
afterEach(cleanup);
+async function waitForInitialDialogFocus(): Promise<void> {
+ const nameInput = screen.getByPlaceholderText(
+ 'settings.providers.custom.fields.namePlaceholder',
+ );
+ await waitFor(() => expect(document.activeElement).toBe(nameInput));
+}
+
describe('CustomProviderDialog accessibility', () => {
it('ignores consumed and IME Escape events, then restores focus after closing', async () => {
function Harness() {
@@ -144,6 +151,7 @@ describe('CustomProviderDialog accessibility', () => {
const baseUrl = screen.getByPlaceholderText(
'settings.providers.custom.fields.baseUrlPlaceholder',
);
+ await waitForInitialDialogFocus();
await user.clear(baseUrl);
await user.type(baseUrl, 'https://new.example.test/v1');
await waitFor(() => expect((apiKey as HTMLInputElement).value).toBe(''));
@@ -182,6 +190,7 @@ describe('CustomProviderDialog accessibility', () => {
'settings.providers.custom.fields.baseUrlPlaceholder',
);
+ await waitForInitialDialogFocus();
await user.clear(baseUrl);
await user.type(baseUrl, 'https://new.example.test/v1');
await waitFor(() => expect((apiKey as HTMLInputElement).value).toBe(''));
@@ -217,6 +226,7 @@ describe('CustomProviderDialog accessibility', () => {
const baseUrl = screen.getByPlaceholderText(
'settings.providers.custom.fields.baseUrlPlaceholder',
);
+ await waitForInitialDialogFocus();
await user.clear(baseUrl);
await user.type(baseUrl, 'https://new.example.test/v1');
await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));
@@ -256,6 +266,7 @@ describe('CustomProviderDialog accessibility', () => {
const baseUrl = screen.getByPlaceholderText(
'settings.providers.custom.fields.baseUrlPlaceholder',
);
+ await waitForInitialDialogFocus();
await user.clear(baseUrl);
await user.type(baseUrl, 'https://new.example.test/v1');
await user.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));
@@ -320,6 +331,7 @@ describe('CustomProviderDialog accessibility', () => {
'settings.providers.custom.fields.apiKeyEditPlaceholder',
);
+ await waitForInitialDialogFocus();
await user.clear(apiKey);
await user.type(apiKey, 'replacement-secret');
await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));
diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.ts
index 7800079bde..7e6bde70c3 100644
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@ -343,7 +343,7 @@ describe('ghost · 清单校验', () => {
}).ok).toBe(false);
});
- it('locale description / whenToUse 共用协议仓字符上限', () => {
+ it('locale description / whenToUse 共用本地协议包字符上限', () => {
const manifest = validateGhostManifest({
...goodManifest(),
description: 'Base description',
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 8a2158a69b..b416e71738 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -663,8 +663,8 @@ export interface GhostSecretExchangeDecl {
/**
* OAuth 凭证:scopes 条数上限(超出拒装;确认框逐条展示要可读)。
- * 数值正本在 cindy-protocol 的 plugin-protocol(manifest.ts,发布服务端同读),
- * 客户端只 re-export 不再手抄副本;调整上限一律改协议仓再 bump submodule。
+ * 数值正本在本仓 packages/plugin-protocol(manifest.ts),服务端仓维护兼容副本。
+ * 客户端只 re-export 不再手抄副本;调整上限须同步两仓并先确认 wire 兼容性。
* 本校验取值级"严出"(plugin-security-and-authoring.md §7):超上限的包在旧版
* 客户端拒装,插件市场铺开须等携带新上限的客户端先行发布。
*
diff --git a/apps/desktop/src/shared/hookControlIpc.ts b/apps/desktop/src/shared/hookControlIpc.ts
index 11d1c95808..6209dde6ba 100644
--- a/apps/desktop/src/shared/hookControlIpc.ts
+++ b/apps/desktop/src/shared/hookControlIpc.ts
@@ -108,7 +108,7 @@ export type HookProvider = 'slack' | 'telegram' | 'x';
/** provider-neutral 状态机(非 slack legacy 线)覆盖的 provider。 */
export type NeutralHookProvider = Exclude<HookProvider, 'slack'>;
-/** provider-neutral 绑定状态(与 cindy-protocol v1 严格同形)。 */
+/** provider-neutral 绑定状态(与本仓 slack-hook-protocol v1 严格同形)。 */
export type ProviderBindingState =
| 'none'
| 'pending'
diff --git a/apps/desktop/src/shared/modelAccess.ts b/apps/desktop/src/shared/modelAccess.ts
index 8abb0ec845..88aad2e787 100644
--- a/apps/desktop/src/shared/modelAccess.ts
+++ b/apps/desktop/src/shared/modelAccess.ts
@@ -207,3 +207,15 @@ export interface ModelAccessGatewayModel extends ModelGroupPricing {
/** per-tab 能力覆盖(基线字段之上按 agent 应用)。 */
perAgent?: Partial<Record<'claude-code' | 'codex', ModelAccessAgentOverride>>;
}
+
+/**
+ * Consumer-side Bean for `GET /api/model-access/models`.
+ *
+ * The client intentionally owns this tolerant view: legacy responses may omit
+ * fields that the current server always emits, while unknown schema versions
+ * remain a runtime-parser concern.
+ */
+export interface ModelAccessModelsResponse {
+ schemaVersion: 1 | 2;
+ models: ModelAccessGatewayModel[];
+}
diff --git a/apps/mobile/metro.config.js b/apps/mobile/metro.config.js
index 1c4dd13d94..6dba9a54ce 100644
--- a/apps/mobile/metro.config.js
+++ b/apps/mobile/metro.config.js
@@ -15,20 +15,11 @@ const workspaceTsSourcePackages = [
'model-providers',
];
-// cindy-protocol submodule 里的源码直发协议包中,源码内部用**显式 .js 扩展名**的那些
-// (为满足服务端 moduleResolution: node16 的类型检查)。esbuild / Vite 会自动把
-// ./x.js 回落到 ./x.ts,Metro 不会——所以这些包也必须走下方 .js→.ts 分流。
-// 边界:只列内部用 .js 扩展名的包。device-link-protocol 用无扩展名相对导入,
-// 走 Metro 默认解析即可,不在此列。
-const protocolTsSourcePackages = [
- 'model-access-protocol',
-];
-
config.resolver.disableHierarchicalLookup = true;
// 关掉层级查找后,Metro 只查显式列出的 node_modules。pnpm hoisted 布局(根 .npmrc
// node-linker=hoisted)下,workspace:* 依赖**不会**提升到根 node_modules,只链接在消费方包
// 自己的 node_modules 下(如 packages/device-link/node_modules/@cindy/device-link-protocol →
-// cindy-protocol submodule)——不把这些目录列进来,TS 源码包引用的任何 workspace 依赖在
+// packages/device-link-protocol)——不把这些目录列进来,TS 源码包引用的任何 workspace 依赖在
// 打 bundle 时都会 Unable to resolve(2026-07-16 iOS 冷更实踩)。
// 追加在末尾:常规依赖仍按 app → 根的原顺序命中,行为不变,只补此前查不到的路径。
// 边界:只覆盖这一层——若这些包的 workspace 依赖自己再新增 workspace 依赖(或新的 TS 源码包
@@ -44,7 +35,7 @@ config.resolver.extraNodeModules = {
...config.resolver.extraNodeModules,
'@cindy/device-link-protocol': path.join(
workspaceRoot,
- 'cindy-protocol/packages/device-link-protocol',
+ 'packages/device-link-protocol',
),
react: path.join(appNodeModules, 'react'),
'react-native': path.join(workspaceNodeModules, 'react-native'),
@@ -61,15 +52,8 @@ const defaultResolveRequest = config.resolver.resolveRequest;
const rnDevToolsSettingsManager = '../../src/private/devsupport/rndevtools/ReactDevToolsSettingsManager';
function isWorkspaceTsSourcePackage(originModulePath) {
- if (workspaceTsSourcePackages.some((packageName) => (
+ return workspaceTsSourcePackages.some((packageName) => (
originModulePath.includes(`${path.sep}packages${path.sep}${packageName}${path.sep}`)
- ))) {
- return true;
- }
- return protocolTsSourcePackages.some((packageName) => (
- originModulePath.includes(
- `${path.sep}cindy-protocol${path.sep}packages${path.sep}${packageName}${path.sep}`,
- )
));
}
diff --git a/apps/mobile/src/__tests__/easignoreWorkspaceClosure.test.ts b/apps/mobile/src/__tests__/easignoreWorkspaceClosure.test.ts
index 96de665892..fb003fcf70 100644
--- a/apps/mobile/src/__tests__/easignoreWorkspaceClosure.test.ts
+++ b/apps/mobile/src/__tests__/easignoreWorkspaceClosure.test.ts
@@ -76,8 +76,6 @@ describe('EAS .easignore covers apps/mobile workspace dependency closure', () =>
/^!scripts\/shared\/client-endpoint-build-env\.cjs$/m,
);
expect(easignore).toMatch(/^!tools\/shared\/fetch-with-timeout\.mjs$/m);
- expect(easignore).toMatch(/^!cindy-protocol$/m);
- expect(easignore).toMatch(/^!cindy-protocol\/\*\*$/m);
// beta EAS lane 已在 79013fcc 退役,eas.json 不再有 beta-base profile。
for (const profile of [
'store-cn-base',
diff --git a/apps/mobile/src/__tests__/nativeAppConfig.test.ts b/apps/mobile/src/__tests__/nativeAppConfig.test.ts
index 8abf3a5a90..5b59dc9cec 100644
--- a/apps/mobile/src/__tests__/nativeAppConfig.test.ts
+++ b/apps/mobile/src/__tests__/nativeAppConfig.test.ts
@@ -490,7 +490,7 @@ describe('mobile native app config', () => {
it('Metro nodeModulesPaths 覆盖 workspace TS 源码包各自的 node_modules(pnpm hoisted 布局下 workspace: 链接不提升到根,只在消费方包自己的 node_modules)', () => {
// 2026-07-16 iOS 冷更实踩:disableHierarchicalLookup 后漏列这些目录,
- // packages/device-link 引用的 @cindy/device-link-protocol(cindy-protocol submodule)
+ // packages/device-link 引用的仓内 @cindy/device-link-protocol
// 在 expo export:embed 打 bundle 时 Unable to resolve → ARCHIVE FAILED。
// 期望路径从 metro.config.js 自身位置推导(它内部用 __dirname 计算),不依赖测试进程 cwd。
const metroConfigPath = require.resolve('../../metro.config.js');
diff --git a/apps/mobile/src/notifications/pushRegistrationModel.ts b/apps/mobile/src/notifications/pushRegistrationModel.ts
index 6e9c279c29..61af31d0cd 100644
--- a/apps/mobile/src/notifications/pushRegistrationModel.ts
+++ b/apps/mobile/src/notifications/pushRegistrationModel.ts
@@ -3,7 +3,7 @@
*
* 链路:手机拿 APNs device token → PUT device-link server /push-token 注册;
* 桌面端任务终态发 notify 帧 → server 查账号 token → APNs 下发。
- * 契约见 cindy-server docs/device-link-server.md 与协议仓 device-link-protocol.md。
+ * 契约见本仓 packages/device-link-protocol 与 cindy-server docs/device-link-server.md。
*/
export type PushAppVariant = 'cn' | 'global';
diff --git a/cindy-protocol b/cindy-protocol
deleted file mode 160000
index dbbf169703..0000000000
--- a/cindy-protocol
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit dbbf1697037c6025541ab4bae38f906982628423
diff --git a/docs/README.md b/docs/README.md
index c9981c9082..4c71a149dc 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -25,7 +25,7 @@
| [cindy-updater.md](./dev-rules/cindy-updater.md) | 更新器规则 | authoritative | 客户端自动更新链路(`cindy-updater` + Electron 更新服务)的 owner 确认门禁 | — |
| [engineering-conventions.md](./dev-rules/engineering-conventions.md) | 通用工程规范 | authoritative | Desktop 日志、IPC 错误协议、main 侧测试、跨平台双端兼容与 UI 文案 i18n | — |
| [log-upload-and-redaction.md](./dev-rules/log-upload-and-redaction.md) | 日志上报规则 | authoritative | 客户端日志采集/脱敏/上报:记录边界不变量、来源白名单方向、标记代次与原子清除、区域绑定与崩溃时序 | — |
-| [protocol-and-submodules.md](./dev-rules/protocol-and-submodules.md) | 协议/submodule 规则 | authoritative | `cindy-protocol` 权威源、device-link relay 层、内建插件来源与 wire protocol 兼容 | — |
+| [protocol-compatibility.md](./dev-rules/protocol-compatibility.md) | 跨端协议规则 | authoritative | 两仓本地协议包、device-link relay 层与 wire protocol 兼容 | — |
| [architecture-invariants.md](./dev-rules/architecture-invariants.md) | 架构不变量 | authoritative | package 解耦、main 静态依赖、主界面布局树(`layoutTree`/`LayoutStore`/panel registry) | — |
| [configuration-and-overrides.md](./dev-rules/configuration-and-overrides.md) | 配置契约 | authoritative | 配置可见性分层、默认值+override 分离、迁移与恢复默认语义 | — |
| [remote-and-mobile-adaptation.md](./dev-rules/remote-and-mobile-adaptation.md) | 远程/手机版门禁 | authoritative | SSH 远程工作区、device-link allowlist、`apps/mobile` 入口与功能类 PR 三选一门禁 | — |
diff --git a/docs/dev-rules/README.md b/docs/dev-rules/README.md
index 6c013de7a0..3bf73d412a 100644
--- a/docs/dev-rules/README.md
+++ b/docs/dev-rules/README.md
@@ -43,8 +43,8 @@
- [`log-upload-and-redaction.md`](log-upload-and-redaction.md):客户端日志采集/脱敏/上报的
三条不变量(记录边界、白名单方向 deny-by-default、标记代次 + 原子清除)、四层收窄管道、
授权闸、区域绑定与崩溃时序。
-- [`protocol-and-submodules.md`](protocol-and-submodules.md):`cindy-protocol` 协议权威源、
- device-link relay 层、内建插件来源与 wire protocol 兼容。
+- [`protocol-compatibility.md`](protocol-compatibility.md):两仓本地协议实现、device-link
+ relay 层、插件来源与 wire protocol 兼容。
- [`architecture-invariants.md`](architecture-invariants.md):package 与 render/main 解耦、
main 进程静态依赖,以及主界面布局树不变量。
- [`configuration-and-overrides.md`](configuration-and-overrides.md):配置可见性分层、默认值
diff --git a/docs/dev-rules/environment-setup.md b/docs/dev-rules/environment-setup.md
index 6693692da9..4bf91507ec 100644
--- a/docs/dev-rules/environment-setup.md
+++ b/docs/dev-rules/environment-setup.md
@@ -17,12 +17,9 @@ git lfs version
## 安装
-公开贡献者只初始化普通开发必需且公开可访问的 submodule,不要索取、复制或写入凭证:
-
```bash
git clone https://github.com/makecindy/cindy.git
cd cindy
-git submodule update --init --recursive cindy-protocol
git lfs pull
pnpm install
```
@@ -63,10 +60,6 @@ sudo chmod 4755 chrome-sandbox
## 不变量
-- submodule 版本由父仓 gitlink 锁定;普通同步不得使用 `git submodule update --remote`。
-- 旧 checkout 拉到 `.gitmodules` URL 迁移后,开发脚本会先执行
- `git submodule sync -- cindy-protocol`;手动更新 submodule 前也应先执行同一命令,
- 避免继续使用 `.git/config` 缓存的旧仓库地址。
- 公开版本不包含内建插件种子;插件通过 SkillHub 或手动安装。不要把任何访问令牌写入
仓库、Git 配置或脚本。
- Desktop runtime 二进制(claude/codex/ripgrep/pi)的版本由仓库维护者统一判断与升级;贡献者和
diff --git a/docs/dev-rules/protocol-and-submodules.md b/docs/dev-rules/protocol-and-submodules.md
deleted file mode 100644
index f0a6d7b785..0000000000
--- a/docs/dev-rules/protocol-and-submodules.md
+++ /dev/null
@@ -1,65 +0,0 @@
-# 协议兼容与 submodule
-
-> **状态**:权威开发规则(authoritative)
-> **读取时机**:升级 `cindy-protocol`、修改插件分发来源边界、修改 device-link
-> 协议/relay/隧道 payload/IPC allowlist,或任何改动客户端与服务端之间 wire protocol
-> 的地方之前
-
-`cindy-protocol` 是客户端与服务端共享的存量 wire protocol 权威来源。协议仓的 package
-集合已经封闭,只会维护或减少现有 package,不再接收新 package。submodule 指针可以因
-兼容的分阶段升级而不同;真正危险的是单端改变 wire 语义或在不兼容变更中缺少协同,这类
-问题在本仓的 typecheck/单测里发现不了,只有真实连接时才暴露。device-link 的运行时约束另见
-[`remote-and-mobile-adaptation.md`](remote-and-mobile-adaptation.md),submodule 初始化命令见
-[`environment-setup.md`](environment-setup.md)。
-
-> **增量适用原则**:wire protocol 兼容对所有跨端改动生效,不因是小改而豁免。
-
-## 事实来源
-
-| 内容 | 权威来源 |
-|---|---|
-| 协议权威源 | 根 submodule `cindy-protocol`(`github.com/makecindy/cindy-protocol`) |
-| hook 双工任务协议 | `@cindy/slack-hook-protocol`;desktop hook-control 与 slack/telegram/x hook server 共同消费 |
-| device-link relay 层定义 | `@cindy/device-link-protocol`;客户端重连、IPC allowlist、隧道 payload 在 `packages/device-link` |
-| Plugin 交付与 manifest | `@cindy/plugin-protocol`;desktop、`packages/cindy-tools` 与 plugin-server 共同消费 |
-| 模型目录 | `@cindy/model-access-protocol`;desktop/mobile 与 model-access-server 共同消费 |
-| 插件来源 | 客户端不预装插件;一律通过 SkillHub 或用户手动安装 `.cindy` 包 |
-
-## 1. `cindy-protocol` 是协议权威源
-
-- 协议定义以 `cindy-protocol` submodule 为准;当前只保留
- `@cindy/slack-hook-protocol`、`@cindy/device-link-protocol`、
- `@cindy/plugin-protocol`、`@cindy/model-access-protocol` 四个有真实双端消费者的包。
- 客户端重连、IPC allowlist 与隧道 payload 留在 `packages/device-link`,不在客户端另造一套协议。
-- 协议仓是封闭、持续精简的存量仓库:不得新增 package、增加 package 数量,或把无关业务域
- 塞进现有 package 绕过限制。新业务域的契约在所属业务仓库处理,或另行做仓库外架构决策。
-- `makecindy/cindy-protocol` 以新历史公开;父仓锁定的 submodule commit 必须始终
- 可从公开仓拉取——合入协议仓 `main`,或打 `client-baseline-<sha>` tag,不允许只
- 停在 feature 分支上(分支删除会让 gitlink 失效)。历史 tag
- `client-baseline-436a45f` 仍可能被旧 checkout 依赖,不要删除。
-- append-only、带旧端降级路径的兼容变更允许客户端和服务端独立 pin、分阶段升级;只有实际
- 使用新字段/消息/校验能力的消费仓需要 bump。删除未被任何消费方引用的 package 也不要求
- 两仓同步部署。
-- 不兼容 wire 变更、device-link 新增 relay kind 等必须在协议 PR 中声明升级窗口,并协调所有
- 相关消费方;不能把“允许指针不同”误读成允许单端改变既有字段语义。
-
-## 2. 插件来源
-
-- 客户端不包含内建插件种子 submodule,不在安装包中预置插件,启动期也没有播种
- (provisioning)逻辑——预装机制已整体移除(2026-07)。
-- 插件运行时保留,用户通过 SkillHub 或手动安装 `.cindy` 包;没有任何插件时启动和
- 开发不应因此失败。
-- 不要重新引入预装/播种机制或私有种子 submodule;需要推荐插件时走 SkillHub 的
- 分发与安装确认流程。
-
-## Review 清单
-
-1. 改动是否触及跨端 wire protocol?是兼容独立升级,还是需要协调窗口的不兼容变更?
-2. submodule 目标 commit 是否已合入公开协议仓,旧端降级行为是否明确?
-3. 是否新增了 protocol package、扩大了 package 数量,或把无关领域塞进存量 package?这些均不允许。
-4. 客户端是否在 `packages/device-link` 之外另造了协议或绕过 relay 层定义?
-5. 插件能力是否通过 `.cindy` 包和 SkillHub/手动安装分发,而不是重新引入预装/播种
- 机制、私有种子 submodule 或绕过插件权限边界?
-
-协议改动按 [`desktop-development.md`](desktop-development.md) 跑相关测试,并与服务端确认
-兼容;submodule 相关操作见 [`environment-setup.md`](environment-setup.md)。
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
new file mode 100644
index 0000000000..928d78be56
--- /dev/null
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -0,0 +1,56 @@
+# 跨端协议兼容
+
+> **状态**:权威开发规则(authoritative)
+> **读取时机**:修改插件分发来源边界、device-link 协议/relay/隧道 payload/IPC
+> allowlist,或任何改动客户端与服务端之间 wire protocol 的地方之前
+
+客户端与服务端分别维护本仓所需的 wire Bean、validator、parser 与 builder,不共享代码仓库
+或发布节奏。真正危险的是单端改变既有 wire 语义,或在不兼容变更中缺少协同;这类问题在
+单仓 typecheck/单测里发现不了,只有真实连接时才暴露。device-link 的运行时约束另见
+[`remote-and-mobile-adaptation.md`](remote-and-mobile-adaptation.md)。
+
+> **增量适用原则**:wire protocol 兼容对所有跨端改动生效,不因是小改而豁免。
+
+## 事实来源
+
+| 内容 | 权威来源 |
+|---|---|
+| hook 双工任务协议 | 客户端 `packages/slack-hook-protocol`;服务端仓同名本地 package,desktop hook-control 与 slack/telegram/x hook server 分别消费本仓实现 |
+| device-link relay 层定义 | 客户端 `packages/device-link-protocol`;服务端仓同名本地 package,客户端重连、IPC allowlist、隧道 payload 在 `packages/device-link` |
+| Plugin 交付与 manifest | 客户端 `packages/plugin-protocol`;服务端仓同名本地 package,desktop、`packages/cindy-tools` 与 plugin-server 分别消费本仓实现 |
+| 模型目录 | 客户端由 `packages/model-providers/src/modelAccessBean.ts` 与 `modelAccessValidator.ts` 维护;model-access-server 在服务端仓维护对应 Bean/validator,双方只共享稳定 wire 语义,不共享实现 |
+| 插件来源 | 客户端不预装插件;一律通过 SkillHub 或用户手动安装 `.cindy` 包 |
+
+## 1. 两仓本地协议演进
+
+- 两仓同名协议 package 是各自消费者的本地实现,不允许跨仓源码 import、Git submodule 或
+ 运行时共享依赖。客户端重连、IPC allowlist 与隧道 payload 留在
+ `packages/device-link`,不在客户端另造一套协议。
+- append-only、带旧端降级路径的兼容变更允许客户端和服务端分阶段升级;只有实际使用新
+ 字段、消息或校验能力的消费仓需要发布。
+- 不兼容 wire 变更、device-link 新增 relay kind 等必须声明升级窗口,并协调所有相关
+ 消费方;不能把“两仓独立发布”误读成允许单端改变既有字段语义。
+- 改动一端协议实现时必须核对另一端同名实现和消费者。需要相同约束的 parser/validator
+ 应在两仓分别落地,并用相同的有效/无效 fixture 覆盖边界。
+- 新业务域的契约优先放进所属业务仓库;不要建立新的公共协议仓来重新引入发布耦合。
+
+## 2. 插件来源
+
+- 客户端不包含内建插件种子,不在安装包中预置插件,启动期也没有播种
+ (provisioning)逻辑。
+- 插件运行时保留,用户通过 SkillHub 或手动安装 `.cindy` 包;没有任何插件时启动和
+ 开发不应因此失败。
+- 不要重新引入预装/播种机制或私有种子 submodule;需要推荐插件时走 SkillHub 的
+ 分发与安装确认流程。
+
+## Review 清单
+
+1. 改动是否触及跨端 wire protocol?是兼容独立升级,还是需要协调窗口的不兼容变更?
+2. 两仓本地协议实现是否保持兼容,旧端降级行为与分阶段发布顺序是否明确?
+3. 是否把本可归属业务仓的代码放进协议 package,扩大了不必要的耦合面?
+4. 客户端是否在 `packages/device-link` 之外另造了协议或绕过 relay 层定义?
+5. 插件能力是否通过 `.cindy` 包和 SkillHub/手动安装分发,而不是重新引入预装、播种或
+ 绕过插件权限边界?
+
+协议改动按 [`desktop-development.md`](desktop-development.md) 跑相关测试,并与服务端确认
+兼容。
diff --git a/docs/dev-rules/repo-map.md b/docs/dev-rules/repo-map.md
index a2f8f396e6..49c0a44622 100644
--- a/docs/dev-rules/repo-map.md
+++ b/docs/dev-rules/repo-map.md
@@ -13,7 +13,6 @@
|---|---|
| `apps/` | 终端产品(desktop、mobile)与随包分发的二进制资产 |
| `packages/` | 客户端共享能力包(与 render/main 解耦,详见下表) |
-| `cindy-protocol/` | git submodule:客户端与服务端共享的存量 wire protocol 权威源;package 集合封闭且持续精简,当前保留 device-link、slack-hook、plugin、model-access 四包;升级规则见 [`protocol-and-submodules.md`](protocol-and-submodules.md) |
| `config/` | 运行期端点清单(`endpoint.json` / `endpoint.dev.json` / `endpoint.global.json`:auth、device-link 等线上 base URL) |
| `scripts/` | 仓库级工程脚本:dev 启动包装、agent 二进制拉取(`ensure-agent-binaries.mjs`)、i18n/endpoint/文档等校验 guard、worktree 管理 |
| `tools/` | claude/codex/ripgrep/pi 四个 Desktop runtime 的版本 pin(`latest.json`)与更新器(`update.mjs`) |
diff --git a/docs/ghost-progressive-discovery.md b/docs/ghost-progressive-discovery.md
index b851a7be6c..555b9dcc35 100644
--- a/docs/ghost-progressive-discovery.md
+++ b/docs/ghost-progressive-discovery.md
@@ -40,7 +40,7 @@ L0 花名册(system 段常驻召回)
- 每条 = `{id, name, command, recall}`;`recall = whenToUse ?? description`。
- 单条 recall 上限为协议常量 `GHOST_MANIFEST_SUMMARY_MAX_CHARS`(= 300,正本在
- 协议仓 `packages/plugin-protocol/src/manifest.ts`,desktop 经
+ 本仓 `packages/plugin-protocol/src/manifest.ts`,desktop 经
`apps/desktop/src/shared/ghost.ts` re-export)。
- 序列化前逐字段折叠空白(`replace(/\s+/g, " ")` + trim)并防御截断
(name ≤ 64、command ≤ 32、recall ≤ 300);条目按 id 排序;最多 16 条、
@@ -161,7 +161,7 @@ L0 花名册(system 段常驻召回)
`apps/desktop/src/main/mcp-integrations/ghost.ts`
- 可见性唯一真源:`apps/desktop/src/main/cindy-brain/ghostVisibility.ts`
- 作者契约(FORGE_GUIDE):`apps/desktop/src/main/cindy-brain/forge.ts`
-- 摘要上限常量:协议仓 `packages/plugin-protocol/src/manifest.ts`(desktop 经
+- 摘要上限常量:本仓 `packages/plugin-protocol/src/manifest.ts`(desktop 经
`apps/desktop/src/shared/ghost.ts` re-export)
- 三 harness 注入落点:`packages/maker-core/src/agents/claude-code/index.ts`
(buildQuery)、`packages/maker-core/src/agents/codex/index.ts`
diff --git a/docs/legal/README.md b/docs/legal/README.md
index 69754f8a3a..66065a7f15 100644
--- a/docs/legal/README.md
+++ b/docs/legal/README.md
@@ -39,7 +39,6 @@
| [`apps/desktop/native/sqlite-vec/LICENSE`](../../apps/desktop/native/sqlite-vec/LICENSE) | 上游 sqlite-vec | vendored 原生组件的上游许可证,随组件源码保留。 |
| [`apps/desktop/src/renderer/vendor/drawio/LICENSE`](../../apps/desktop/src/renderer/vendor/drawio/LICENSE)、[`tapdb/LICENSE`](../../apps/desktop/src/renderer/vendor/tapdb/LICENSE) | 各自上游项目 | vendored 前端资源的上游许可证,随资源分发。 |
| [`packages/browser-control-runtime/src/_generated/vendor/fs-safe/LICENSE`](../../packages/browser-control-runtime/src/_generated/vendor/fs-safe/LICENSE) | 上游 fs-safe | 生成或 vendored 代码旁的上游许可证,不能与代码拆开。 |
-| [`cindy-protocol/LICENSE`](../../cindy-protocol/LICENSE)、[`cindy-protocol/NOTICE`](../../cindy-protocol/NOTICE) | `cindy-protocol` submodule | 协议是独立仓库,由协议仓库维护;本仓只锁定 submodule commit,不复制真源。 |
固定路径文件如有变化,应在对应的 `docs/legal/` 说明或生成器中同步登记,而不是
再创建一份容易漂移的手工副本。
@@ -55,5 +54,3 @@
4. [`CONTRIBUTING.md`](../../CONTRIBUTING.md) 与 [`SECURITY.md`](../../SECURITY.md) 是
GitHub 识别的社区流程入口,不属于法务真源,因此继续保留在仓库根目录;它们
分别负责贡献流程和漏洞披露,并从这里作为相关入口查找。
-5. `cindy-protocol/` 的法律文件不在本仓库重排;需要修改时应在协议仓库单独提交,
- 再更新本仓库的 submodule 指针。
diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.md
index 31b009fa28..d52b4922d9 100644
--- a/docs/product-rules/telegram-bot-parity.md
+++ b/docs/product-rules/telegram-bot-parity.md
@@ -137,12 +137,12 @@ Cindy 有两个 Telegram bot,用户看到的是同一个产品:
| # | 缺口 | 现状 | 归属 |
|---|---|---|---|
| 1 | **个人 bot 缺 3 条命令** | `/unbind`(清当前 chat 的项目映射)、`/effort`(思考强度)、`/agent`(切 Agent)官方有、个人无,目前只能在桌面端改。注册表已显式登记并由 CI 拦住 | 每条各自独立 PR |
-| 1b | **官方命令镜像没有跨仓校验** | 注册表里官方那一半是手抄的声明性镜像,服务端单方面加减命令这边不会红。**别名维度是同一个洞的另一半,见 1c** | 待判:把 `TELEGRAM_COMMANDS` 放进 `cindy-protocol` 两侧生成,或在服务端加反向校验。要跨仓改动与一次协议版本推进 |
+| 1b | **官方命令镜像没有跨仓校验** | 注册表里官方那一半是手抄的声明性镜像,服务端单方面加减命令这边不会红。**别名维度是同一个洞的另一半,见 1c** | 待判:把 `TELEGRAM_COMMANDS` 分别放进两仓本地协议 package 并用同一 fixture 校验,或在服务端加反向校验。需要跨仓改动与一次协议版本推进 |
| 1c | **隐藏别名 `/exitctr` 只有个人 bot 认** | 个人:`botCommands.ts` 的 `exctr` 带 `aliases: ['exitctr']`,`tokenizeBotCommand` 归一化后走同一条 `executeDetach`(`botCommands.test.ts` 的归一化用例 + `slashCommands.test.ts` 的「`/exitctr` 与 `/exctr` 同路径」各钉一条)。它是**老拼写的向后兼容**——旧 switch 里的 `case '/exitctr':` 删掉后改用别名接住。官方:服务端 `controller.ts` 的 `handleCommand` 只精确匹配 `exctr`,`/exitctr` 一路落到函数末尾的兜底 `reply(t.help)`——**用户拿到一段帮助文案,而 session 接管并没有解除**。这比回一句「未知命令」更容易误判成已生效。**结构上也拦不住**:注册表的 `aliases` 没有 surface 维度(`surfaces` 只描述命令本身),CI 又只校验规范命令名,所以别名两侧不一致永远不会红 | 待判,**不在本 PR 改代码**。两条路:服务端也认这个拼写(`command === "exctr" \|\| command === "exitctr"`),或给注册表的 alias 加 surface 维度并纳入镜像校验——后者顺带把 1b 一起补上 |
| 2 | **msg.op 动词只接了一个** | 服务端全套动词在 `xindong/cindy-server#349`(未合);桌面侧目前只消费 `react`(ack 表情,见 `hook-control/ackReactions.ts` 的 `HOOK_FEATURE_MESSAGE_OPS` 判据)。`send` / `edit` / `delete` / `typing` / `media` 未接线 | #1855 第三刀。**这是把官方 bot 的出站改由桌面驱动的关键一步**——接完之后两侧的发射与收口才可能走同一份代码,而不是各写一套 |
| 2b | **NO_REPLY 哨兵官方只在 ambient 轮次生效** | 个人侧**全轮次**生效(`noReplyScope: 'all-turns'`):`streamingText.finalize` 的哨兵判定不带 ambient 门控。但**「零出站」只在惰性占位还没建过消息时成立**——哨兵前已经有正文流出的轮次消息已经发出去了,finalize 走的是**尽力撤回**:`deleteMessage` 失败被 `catch` 吞掉,那条停在过程态的消息就留在聊天里。官方只在 ambient 轮次生效,且删不掉时**不吞**——`discardProgressMessage` 返回 false,标 `retainAmbientCleanup` 并留给下一拍重试。`presentationCapabilities.ts` 把范围差异明写为**跨服务端 TODO**,即「想统一但要动服务端」,**不是**已裁决的产品差异,所以只登记在这里、不进第三节 | 待判:要统一得改服务端的哨兵判定。失败出口的差异(吞 vs 重试)一并判 |
-| 2c | **链接预览关闭两边各写一套,覆盖面还不一样** | 个人侧读契约 `linkPreviewDisabled: true`,driver 在**答案这条路**上全部消费——正文/过程消息的发送、分段发送、编辑,以及 HTML 解析失败后的纯文本回落;**卡片消息、陌生人提示、主人通知不带**。官方侧**不读这个契约**(在服务端仓 `telegram/client.ts` 里写死 `{ is_disabled: true }`),且只写在两处:`sendAdaptiveMessage` / `editAdaptiveMessage` 的 **HTML 回落**分支;纯文本的 `sendMessage` / `editMessageText`(权限卡、通知、附件转发、续跑提示,以及 adaptive 最后一层纯文本回落)都不带,链接预览按 Telegram 默认开着。两侧的 rich 主路径(`rich_message` payload)都不带这个参数,其预览行为**未核**——非公开 API | 待判:要么把参数补进官方的纯文本出站,要么把这条策略升进 `cindy-protocol` 两侧共用。跨仓 |
-| 2d | **行为配置(表情、回复引用、群参与模式)两边各写一套** | 档位形状与默认值两侧**逐字相同**:`emojiReactions` off/minimal/expressive 默认 minimal、`replyQuoteGroup` off/first/all 默认 first、`replyQuoteDm` off/first 默认 off、`groupActivation` per-chat mention/always **默认 mention**(个人 `?? 'mention'`;官方的协议注释写「只列偏离默认值的群,缺席 = mention」)。但声明与正本有两份——官方读 `cindy-protocol` 的 `DEFAULT_TELEGRAM_BEHAVIOR`,**正本存服务端**,桌面只负责写 override(`hook-control/manager.ts` 把 `mention` 表达成 `null` 清除)与投影设置卡的群清单(`hook-control/groupWindow.ts` 把已知群与 activation 合并),且 hydrate 失败时**故意留「未知」而不套基线**;个人读 `@cindy/im` 的 `TELEGRAM_DEFAULT_BEHAVIOR`,正本是本地 owner-scoped JSON(`im/telegram/behaviorStore.ts`)。**判 ambient 的也是不同一侧**:个人在客户端判(`packages/lizi-im/src/telegram/index.ts` 读 activation 打 ambient 标),官方在服务端判(`controller.ts` 算出 `ambient` 再下发)。值现在一样,但没有任何东西拦着它们分叉。注意:`turnPresenter.ts` / `presentationCapabilities.ts` 里「不含 replyQuote」的裁决说的是**不进共享能力契约**,不是「两个 bot 该长得不一样」——别把它读成有意差异 | 待判:个人侧能否直接改读 `cindy-protocol` 的 `DEFAULT_TELEGRAM_BEHAVIOR`(值一样,是最省事的一次真统一),先核 `@cindy/im` 对 `cindy-protocol` 的依赖方向允不允许(`docs/dev-rules/architecture-invariants.md`)。**与第 6 行分工**:那行是「何时打表情」的判据,这行是「档位的声明、默认值与正本存哪」 |
+| 2c | **链接预览关闭两边各写一套,覆盖面还不一样** | 个人侧读契约 `linkPreviewDisabled: true`,driver 在**答案这条路**上全部消费——正文/过程消息的发送、分段发送、编辑,以及 HTML 解析失败后的纯文本回落;**卡片消息、陌生人提示、主人通知不带**。官方侧**不读这个契约**(在服务端仓 `telegram/client.ts` 里写死 `{ is_disabled: true }`),且只写在两处:`sendAdaptiveMessage` / `editAdaptiveMessage` 的 **HTML 回落**分支;纯文本的 `sendMessage` / `editMessageText`(权限卡、通知、附件转发、续跑提示,以及 adaptive 最后一层纯文本回落)都不带,链接预览按 Telegram 默认开着。两侧的 rich 主路径(`rich_message` payload)都不带这个参数,其预览行为**未核**——非公开 API | 待判:要么把参数补进官方的纯文本出站,要么把这条策略分别升进两仓本地协议 package 并用同一 fixture 锁定。跨仓 |
+| 2d | **行为配置(表情、回复引用、群参与模式)两边各写一套** | 档位形状与默认值两侧**逐字相同**:`emojiReactions` off/minimal/expressive 默认 minimal、`replyQuoteGroup` off/first/all 默认 first、`replyQuoteDm` off/first 默认 off、`groupActivation` per-chat mention/always **默认 mention**(个人 `?? 'mention'`;官方的协议注释写「只列偏离默认值的群,缺席 = mention」)。但声明与正本有两份——官方读本仓 `slack-hook-protocol` 的 `DEFAULT_TELEGRAM_BEHAVIOR`,**正本存服务端**,桌面只负责写 override(`hook-control/manager.ts` 把 `mention` 表达成 `null` 清除)与投影设置卡的群清单(`hook-control/groupWindow.ts` 把已知群与 activation 合并),且 hydrate 失败时**故意留「未知」而不套基线**;个人读 `@cindy/im` 的 `TELEGRAM_DEFAULT_BEHAVIOR`,正本是本地 owner-scoped JSON(`im/telegram/behaviorStore.ts`)。**判 ambient 的也是不同一侧**:个人在客户端判(`packages/lizi-im/src/telegram/index.ts` 读 activation 打 ambient 标),官方在服务端判(`controller.ts` 算出 `ambient` 再下发)。值现在一样,但没有任何东西拦着它们分叉。注意:`turnPresenter.ts` / `presentationCapabilities.ts` 里「不含 replyQuote」的裁决说的是**不进共享能力契约**,不是「两个 bot 该长得不一样」——别把它读成有意差异 | 待判:个人侧能否直接改读本仓 `slack-hook-protocol` 的 `DEFAULT_TELEGRAM_BEHAVIOR`(值一样,是最省事的一次真统一),先核 `@cindy/im` 对该 package 的依赖方向允不允许(`docs/dev-rules/architecture-invariants.md`)。**与第 6 行分工**:那行是「何时打表情」的判据,这行是「档位的声明、默认值与正本存哪」 |
| 2e | **私聊里能不能跨群检索:个人有、官方没有** | **群轮次两侧一致**(都 lane-only,只查当前群/topic)。差别只在私聊。个人:`groupHistoryAccessFor` 在无 lane(即 DM)时给 `access: 'owner'`,owner 可以显式指定别的 lane,跨群查这个 bot 名下全部群历史。官方:私聊的 externalKey 不是群 lane,`groupHistoryAccessForExternalKey` 返回 `undefined`,MCP 直接以 `NO_ACTIVE_TELEGRAM_SCOPE` 拒绝——**官方 bot 私聊里这个工具根本不可用**(MCP 工具自己的说明也写着「只有主人触发的个人 Telegram 轮次可显式指定其它精确 lane」)。个人侧「群轮次一律 lane-only」有 2026-07-30 的明确裁决(群里的可控文本能借 owner 轮次把别的 lane 检索出来回帖泄漏,而检索类调用没有确认卡兜底);**官方私聊这一档没有对应裁决**——是没接,不是判过,所以归缺口不归第三节 | 待判,**不在本 PR 改代码**。补之前先答一个产品问题:官方 bot 绑的是一个主账号,它的私聊该不该看到该账号名下全部群的历史。答「该」才是接线问题(DM 的 externalKey 里有 principal,能推出 `telegram:<principalId>` 的 owner 档);答「不该」就把这行升进第三节当有意差异 |
| 2f | **群里开了「全响应」后,一轮失败:个人 bot 会往群里吐错误,官方静默** | 全响应(`always`)本身两侧行为一致:未被召唤的消息也进 turn 并打 ambient 标、**不 typing、不表情**、模型可用 NO_REPLY 闭嘴、纯媒体/无正文消息不进(个人 `if (!plain) return`,官方 `plain.length > 0`);连 ambient 提示词都逐字相同(各写一份,跨仓无校验)。**分歧只在这一轮失败的时候**:官方不发失败通知(`controller.ts` 的 `finalFailureNoticeSent !== true && !entry.ambient`),并把过程消息删掉、记一句「completed silently」;个人侧的 `im/shared/turnRunner.ts` **完全不认识 ambient**(全文没有这个词),错误一律走 `❌ 错误:…`——惰性占位这时会被真建出来,于是群里凭空多一条错误消息,而这一轮本来连话都不打算说。第二节的生命周期表已按「普通轮次 / ambient 轮次」拆成两行,别再写回一条无条件的失败收口结论 | 待判,**不在本 PR 改代码**。倾向跟官方一致做静默(与「ambient 不打扰群」的既有取舍同一个方向),但要保证错误不因此彻底消失——至少落桌面端日志与该会话,不能只是吞掉 |
| 2g | **交互卡挂太久:官方 30 分钟自动收口,个人一直等** | 三类卡(`ask_user_question` / `plan_review` / 权限)在两侧走的是同一个注册入口,差别只在**有没有定时器**。官方:`hook-control/interactions.ts` 的 `registerHookInteraction` 给每张卡挂一个 `HOOK_INTERACTION_TIMEOUT_MS = 30min`,到点取共享模型的安全默认(ask 空答 / plan deny + dismissed / permission deny)resolve,并回调 `onFallback` → `session-runner.ts` 的 `sendCancel(requestId, reason)` 把卡片收掉。个人:`im/shared/pendingInteractions.ts` **没有任何定时器**,只能靠按钮决策(`resolvePending`),或 turn 收口 / session 清理 / 抢跑时的 `dropInteractionCard` → `cancelPending`(安全默认与官方同源,并把卡片改成「卡片已过期」)。**而这一轮正卡在 `await` 这张卡上,它不会自己结束**;maker-core 的 turn stall 看门狗又明确把「等用户回应交互」排除在静默之外,也不会来救。结果:**个人 bot 的卡片会一直挂着,第二天点还能点,agent 也还在等** | 待判,**不在本 PR 改代码**。先答一个产品问题:个人 bot 的卡片挂着不动算不算问题——它是用户自己的 bot,晚点回来再点也说得通;官方 bot 经服务端中继,挂着的交互会长期占住 lane,动机不一样。补的话要连「超时后卡片显示什么」一起定。**顺带**:官方那个 30 分钟的注释理由(「必须短于整 turn 硬超时 60min」)已过期——那条硬超时 2026-08-01 撤了,定时器本身仍在生效,注释已随本 PR 改正 |
diff --git a/package.json b/package.json
index f3587a9786..e172fc9647 100644
--- a/package.json
+++ b/package.json
@@ -91,7 +91,7 @@
"install:ripgrep": "node scripts/ensure-agent-binaries.mjs --kinds=ripgrep",
"install:pi": "node scripts/ensure-agent-binaries.mjs --kinds=pi",
"install:agent-binaries": "node scripts/ensure-agent-binaries.mjs",
- "postinstall": "node scripts/ensure-agent-binaries.mjs --best-effort && node scripts/fix-node-pty-perms.mjs && pnpm --filter @cindy/model-access-protocol build",
+ "postinstall": "node scripts/ensure-agent-binaries.mjs --best-effort && node scripts/fix-node-pty-perms.mjs",
"dev:desktop": "node scripts/ensure-deps.mjs && node scripts/ensure-dev-runtime-assets.mjs && pnpm --filter desktop dev",
"dev:desktop:remote": "node scripts/ensure-deps.mjs && node scripts/ensure-dev-runtime-assets.mjs && pnpm --filter desktop dev:remote",
"restart:desktop:remote": "node scripts/desktop-restart-runner.mjs --wait-ready",
@@ -112,12 +112,11 @@
"check:endpoints": "node scripts/check-endpoint-literals.mjs",
"check:dev-docs": "node --test scripts/__tests__/dev-docs-contract.test.mjs",
"check:dco": "node scripts/check-dco.mjs",
- "check:submodule-forward": "node scripts/check-submodule-forward.mjs",
"dco:install-hook": "node scripts/install-dco-hook.mjs",
"licenses:generate": "node scripts/generate-third-party-notices.mjs",
"lint": "pnpm -r lint",
"format": "pnpm -r format",
- "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/check-submodule-forward.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs",
+ "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs",
"test:unit": "pnpm test:runner && node scripts/test-workspaces.mjs --tier unit",
"test:all": "pnpm test:runner && node scripts/test-workspaces.mjs --all",
"test:git-integration": "pnpm test:runner && node scripts/test-workspaces.mjs --tier git-integration",
diff --git a/packages/device-link-protocol/package.json b/packages/device-link-protocol/package.json
new file mode 100644
index 0000000000..1a6a2bd7dd
--- /dev/null
+++ b/packages/device-link-protocol/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@cindy/device-link-protocol",
+ "version": "0.0.0",
+ "private": true,
+ "description": "device-link relay-layer wire protocol (single source of truth): envelope, routing semantics, connection-layer payloads. Zero runtime deps",
+ "type": "module",
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "exports": {
+ ".": "./src/index.ts",
+ "./protocol": "./src/protocol.ts"
+ },
+ "scripts": {
+ "build": "tsc --noEmit"
+ },
+ "license": "Apache-2.0",
+ "devDependencies": {
+ "typescript": "^5.7.0"
+ }
+}
diff --git a/packages/device-link-protocol/src/index.ts b/packages/device-link-protocol/src/index.ts
new file mode 100644
index 0000000000..5380f57806
--- /dev/null
+++ b/packages/device-link-protocol/src/index.ts
@@ -0,0 +1,8 @@
+/**
+ * @cindy/device-link-protocol
+ * ---------------------------------------------------------------------------
+ * device-link 中继层(relay)协议的单一权威来源:信封、路由语义、连接层 payload。
+ * relay server 与客户端 device-link 包共同引用;详见 ./protocol.ts 头注。
+ */
+
+export * from './protocol';
diff --git a/packages/device-link-protocol/src/protocol.ts b/packages/device-link-protocol/src/protocol.ts
new file mode 100644
index 0000000000..5dfa5c8ac3
--- /dev/null
+++ b/packages/device-link-protocol/src/protocol.ts
@@ -0,0 +1,189 @@
+/**
+ * === device-link 中继层协议(单一权威来源)===
+ *
+ * 本包是 device-link「relay 中继层」协议的唯一权威定义,由两侧共同引用:
+ * - relay server(device-link-server):哑中继,只解析 envelope 的路由头
+ * (v / kind / id / src / dst)与连接层 payload;隧道层 payload(invoke 的
+ * channel/args、push 的事件内容等)对 relay 完全不透明。
+ * - 客户端完整协议包(desktop / mobile 共享的 device-link 包):在本包基础上
+ * extend 隧道层 payload 类型(LinkOpen / Invoke / Push / DeviceView 等)与
+ * 客户端本地错误码(DeviceLinkErrorCode = RelayErrorCode | 客户端局部码)。
+ *
+ * 准入边界:只有 relay 需要解析/校验的部分才进本包;纯客户端之间端到端、
+ * 对 relay 不透明的类型留在客户端协议包里。
+ *
+ * 本包只承载类型与常量:relay 侧的帧校验由消费方按本定义实现,客户端包在
+ * 本包基础上 extend 隧道层类型 —— PROTOCOL_VERSION 只此一处,两侧共同引用。
+ */
+
+/** 协议版本:整数,只升不降;不兼容改动 +1。 */
+export const PROTOCOL_VERSION = 1;
+
+/** 单帧最大字节数(超过即回 PAYLOAD_TOO_LARGE 并丢弃,不断连;发送方应先行拒绝/裁剪) */
+export const MAX_FRAME_BYTES = 2 * 1024 * 1024;
+
+/** ws 库层面的硬上限兜底(超过直接断连),留余量给协议层先行优雅拒绝 */
+export const WS_MAX_PAYLOAD_BYTES = 4 * 1024 * 1024;
+
+export type EnvelopeKind =
+ // —— 连接层(client ↔ server)——
+ | 'hello' // client→server: 上线注册 { deviceName, platform, appVersion, remoteControlEnabled, busy, deviceInfo? }
+ | 'hello-ack' // server→client: { serverProtocolVersion, deviceId, userId, capabilities? }
+ | 'presence-set' // client→server: 部分更新 { remoteControlEnabled?, busy? }
+ | 'presence-changed' // server→同账号在线设备广播: 单设备 presence 快照
+ | 'ping' // client→server: 应用层心跳(20s),server 借此刷 lastSeenAt / route TTL
+ | 'pong' // server→client
+ | 'notify' // client→server: 请求给本账号已注册推送 token 的移动设备发系统推送(server 消费,不转发)
+ // —— 隧道层(controller ↔ target,server 只转发)——
+ | 'link-open'
+ | 'link-accept'
+ | 'link-close'
+ | 'invoke'
+ | 'invoke-result'
+ | 'push'
+ // —— 错误(server→发送方)——
+ | 'relay-error';
+
+/** 所有帧的统一信封。src 由 server 填(client 传入值会被覆盖,防伪造)。 */
+export interface Envelope {
+ v: number;
+ kind: EnvelopeKind;
+ /** requestId(req/resp 配对;relay-error 回带原帧 id) */
+ id?: string;
+ /** 源 deviceId(server 在转发时填) */
+ src?: string;
+ /** 目标 deviceId(隧道层帧必填) */
+ dst?: string;
+ payload?: unknown;
+}
+
+/** 需要 server 按 dst 转发的帧 */
+export const ROUTED_KINDS: ReadonlySet<EnvelopeKind> = new Set([
+ 'link-open',
+ 'link-accept',
+ 'link-close',
+ 'invoke',
+ 'invoke-result',
+ 'push',
+]);
+
+/**
+ * 「发起控制」语义的帧:转发前 server 必须校验目标设备 remoteControlEnabled=true。
+ * link-accept / invoke-result / push 是被控端→控制端的回程帧,link-close 是双向解除,
+ * 这三类不受被控开关限制(开关关掉后回程帧仍需送达以收尾)。
+ */
+export const CONTROL_KINDS: ReadonlySet<EnvelopeKind> = new Set(['link-open', 'invoke']);
+
+/**
+ * relay-error 的错误码(relay 自身产生的错误)。
+ * 客户端协议包的 DeviceLinkErrorCode 是本类型的超集
+ * (追加 CHANNEL_NOT_ALLOWED / INVOKE_TIMEOUT 等客户端本地码)。
+ */
+export type RelayErrorCode =
+ | 'DEVICE_OFFLINE' // 目标设备不在线(或不属于本账号)
+ | 'REMOTE_DISABLED' // 目标设备「允许被控」开关关闭
+ | 'VERSION_MISMATCH' // 协议版本不一致
+ | 'PAYLOAD_TOO_LARGE' // 单帧超限
+ | 'RATE_LIMITED' // notify 频控命中。只会发给已声明 notify capability 的 server 的对话方——旧客户端不发 notify,不会收到本码
+ | 'BAD_REQUEST' // 帧格式非法
+ | 'INTERNAL'; // 中继内部错误
+
+export interface RelayErrorPayload {
+ code: RelayErrorCode;
+ message: string;
+ /** 路由失败时回带目标设备,便于控制端定位 */
+ dst?: string;
+}
+
+// ─── 连接层 payload(relay 需要解析) ─────────────────────────────────────────
+
+/** hello 帧 payload(client→server) */
+export interface HelloPayload {
+ deviceName: string;
+ platform: string;
+ appVersion: string;
+ remoteControlEnabled: boolean;
+ busy: boolean;
+ deviceInfo?: DeviceInfo;
+}
+
+/** hello-ack 帧 payload(server→client) */
+export interface HelloAckPayload {
+ serverProtocolVersion: number;
+ deviceId: string;
+ userId: string;
+ /**
+ * server 支持的可选能力集(append-only)。旧 server 缺省 = 空集;
+ * 客户端只有在能力集包含对应项时才发起该能力的帧(如 'notify'),
+ * 避免旧 server 对未知 kind 静默丢弃造成黑洞。
+ */
+ capabilities?: string[];
+}
+
+/** hello-ack.capabilities:server 支持 notify 帧(移动推送)。 */
+export const SERVER_CAPABILITY_NOTIFY = 'notify';
+
+/** presence-set 帧 payload(client→server,部分更新) */
+export interface PresenceSetPayload {
+ remoteControlEnabled?: boolean;
+ busy?: boolean;
+}
+
+// ─── notify(移动推送)────────────────────────────────────────────────────────
+
+/** notify 事件类别(会话终态语义,与桌面通知的 kind 对齐)。 */
+export type NotifyCategory = 'session-done' | 'session-error' | 'session-needs-reply';
+
+/** notify payload 的字段长度上限(server 超限即整帧 BAD_REQUEST,不静默截断)。 */
+export const NOTIFY_TITLE_MAX_LENGTH = 120;
+export const NOTIFY_BODY_MAX_LENGTH = 240;
+export const NOTIFY_DEEP_LINK_MAX_LENGTH = 512;
+export const NOTIFY_COLLAPSE_ID_MAX_LENGTH = 128;
+
+/**
+ * notify 帧 payload(client→server;server 消费,不转发)。
+ * server 查本账号已注册的推送 token(排除发送方自己),经 APNs/FCM 下发系统推送。
+ * 发送门槛:hello-ack.capabilities 含 SERVER_CAPABILITY_NOTIFY 才可发;
+ * 旧 server 收到未知 kind 会静默丢弃(黑洞),没有该能力声明时客户端不得发送。
+ * fire-and-forget:成功无响应;失败回 relay-error(RATE_LIMITED / BAD_REQUEST / INTERNAL)。
+ */
+export interface NotifyPayload {
+ category: NotifyCategory;
+ /** 通知标题(建议:会话标题) */
+ title: string;
+ /**
+ * 通知正文,可缺省。发送端可放内容摘要(如最近一条 assistant 回复)——
+ * 体验优先的产品决策;注意正文经 APNs/FCM 第三方通道,发送端自行裁剪长度
+ * 与敏感度,server 不落盘通知内容。
+ */
+ body?: string;
+ /** 点击通知的跳转深链,如 cindy://devices/<deviceId>/sessions/<sessionId> */
+ deepLink: string;
+ /** 系统层合并键(APNs collapse-id / thread-id):同键新通知顶替旧通知 */
+ collapseId: string;
+ /** 只推给指定设备;缺省 = 本账号全部已注册推送 token 的设备(不含发送方) */
+ targetDeviceId?: string;
+}
+
+/** 设备识别用的轻量硬件 / 系统信息。所有字段 best-effort,可缺省。 */
+export interface DeviceInfo {
+ cpuLabel?: string;
+ memoryGb?: number;
+ osVersion?: string;
+ modelLabel?: string;
+}
+
+/** presence-changed 广播 / REST 设备列表共用的设备快照 */
+export interface PresenceSnapshot {
+ deviceId: string;
+ online: boolean;
+ deviceName: string;
+ selfName?: string | null;
+ deviceInfo?: DeviceInfo | null;
+ platform: string;
+ appVersion: string;
+ /** unix ms */
+ lastSeenAt: number;
+ remoteControlEnabled: boolean;
+ busy: boolean;
+}
diff --git a/packages/device-link-protocol/tsconfig.json b/packages/device-link-protocol/tsconfig.json
new file mode 100644
index 0000000000..fefb71da01
--- /dev/null
+++ b/packages/device-link-protocol/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ESNext",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "noEmit": true,
+ "sourceMap": true,
+ "baseUrl": "."
+ },
+ "include": ["src/**/*"]
+}
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index 8a4cc0d26c..6babc5bf10 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -831,7 +831,7 @@ export class DeviceLinkClient {
/**
* 请求 server 给本账号已注册推送 token 的移动设备发系统推送(fire-and-forget)。
* 返回是否真的发出:离线或 server 未声明 notify capability 时静默跳过返回 false
- * (旧 server 对未知 kind 是静默黑洞,capability gate 是协议要求,见协议仓文档)。
+ * (旧 server 对未知 kind 是静默黑洞,capability gate 是本地协议包的兼容要求)。
* 失败(RATE_LIMITED / BAD_REQUEST)由 relay-error 帧回报,经 onFrame 交 host 记日志。
*/
sendNotify(payload: NotifyPayload): boolean {
diff --git a/packages/device-link/src/protocol.ts b/packages/device-link/src/protocol.ts
index b03e290b19..2f450dd47c 100644
--- a/packages/device-link/src/protocol.ts
+++ b/packages/device-link/src/protocol.ts
@@ -1,7 +1,7 @@
/**
* device-link 客户端完整协议(desktop / mobile 共享)。
*
- * relay 能理解的信封、连接层 payload 与错误码来自 cindy-protocol submodule;
+ * relay 能理解的信封、连接层 payload 与错误码来自本仓 device-link-protocol;
* 本文件只补充 relay 不解析的端到端隧道 payload、客户端本地错误与 REST 视图。
*/
import {
diff --git a/packages/model-providers/package.json b/packages/model-providers/package.json
index c5fdab1822..36b56f4312 100644
--- a/packages/model-providers/package.json
+++ b/packages/model-providers/package.json
@@ -27,9 +27,6 @@
"email": "[email protected]"
},
"license": "Apache-2.0",
- "dependencies": {
- "@cindy/model-access-protocol": "workspace:*"
- },
"devDependencies": {
"@types/node": "*",
"typescript": "^5.7.0",
diff --git a/packages/model-providers/src/__tests__/modelAccessValidator.test.ts b/packages/model-providers/src/__tests__/modelAccessValidator.test.ts
new file mode 100644
index 0000000000..93cb7c192f
--- /dev/null
+++ b/packages/model-providers/src/__tests__/modelAccessValidator.test.ts
@@ -0,0 +1,763 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION,
+ MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
+ MODEL_ACCESS_MODELS_PATH,
+ MODEL_REGISTRY_LEGACY_SCHEMA_VERSION,
+ MODEL_REGISTRY_SCHEMA_VERSION,
+ MODEL_REGISTRY_STATUSES,
+ modelRegistryCanonicalJson,
+ parseListModelsResponse,
+ parseModelRegistry,
+ type ListModelsResponse,
+ type ModelRegistry,
+} from '../index.js';
+
+const VALID_RESPONSE: ListModelsResponse = {
+ schemaVersion: MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
+ models: [
+ {
+ id: 'example-chat-model',
+ mode: 'chat',
+ currency: 'CNY',
+ agents: ['claude-code', 'codex'],
+ newSessionDefault: ['claude-code', 'codex'],
+ name: 'Example Chat Model',
+ icon: 'example',
+ contextWindow: 200_000,
+ modalities: { input: ['text', 'image'], output: ['text'] },
+ inputCostPerToken: 0.000_001,
+ outputCostPerToken: 0.000_002,
+ efforts: ['low', 'medium', 'high'],
+ defaultEffort: 'medium',
+ perAgent: {
+ 'claude-code': { supportsFastMode: false },
+ },
+ tieredPricing: [
+ {
+ range: [0, 200_000],
+ inputCostPerToken: 0.000_001,
+ outputCostPerToken: 0.000_002,
+ },
+ ],
+ },
+ ],
+};
+
+const VALID_REGISTRY: ModelRegistry = {
+ schemaVersion: MODEL_REGISTRY_SCHEMA_VERSION,
+ updatedAt: '2026-07-31T00:00:00.000Z',
+ models: [
+ {
+ id: 'example/model',
+ name: 'Example Model',
+ status: 'active',
+ contextWindow: 200_000,
+ efforts: ['low', 'medium', 'high'],
+ defaultEffort: 'medium',
+ routes: [
+ {
+ providerId: 'example',
+ modelId: 'example-model',
+ agents: ['claude-code', 'codex'],
+ referencePrices: [
+ {
+ currency: 'USD',
+ variant: 'standard',
+ inputPerMtok: 1,
+ outputPerMtok: 5,
+ cacheReadPerMtok: 0.1,
+ minInputTokens: 0,
+ maxInputTokens: 200_000,
+ effectiveFrom: '2026-07-01',
+ source: {
+ kind: 'provider-official',
+ url: 'https://example.com/pricing',
+ verifiedAt: '2026-07-31',
+ },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+};
+
+function expectReject(value: unknown, path: string): void {
+ const result = parseListModelsResponse(value);
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('unreachable');
+ expect(result.error).toContain(path);
+}
+
+describe('model access catalog contract', () => {
+ it('round-trips the versioned model catalog with its declared currency', () => {
+ const wire = JSON.parse(JSON.stringify(VALID_RESPONSE));
+ const result = parseListModelsResponse(wire);
+ expect(result).toEqual({ ok: true, value: VALID_RESPONSE });
+ expect(MODEL_ACCESS_MODELS_PATH).toBe('/api/model-access/models');
+ });
+
+ it('continues to parse v1 responses, while v1 rejects the v2-only default field', () => {
+ const { newSessionDefault: _newSessionDefault, ...legacyModel } = VALID_RESPONSE.models[0]!;
+ const legacy = {
+ ...VALID_RESPONSE,
+ schemaVersion: MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION,
+ models: [legacyModel],
+ };
+ expect(parseListModelsResponse(JSON.parse(JSON.stringify(legacy))).ok).toBe(true);
+ expectReject(
+ {
+ ...legacy,
+ models: [{ ...legacyModel, newSessionDefault: ['claude-code'] }],
+ },
+ 'response.models[0].newSessionDefault',
+ );
+ });
+
+ it('enforces the complete per-version ListModels allowlist', () => {
+ const { newSessionDefault: _newSessionDefault, ...legacyModel } = VALID_RESPONSE.models[0]!;
+ const versions = [
+ [MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION, legacyModel],
+ [MODEL_ACCESS_CATALOG_SCHEMA_VERSION, VALID_RESPONSE.models[0]!],
+ ] as const;
+
+ for (const [schemaVersion, model] of versions) {
+ const response = { schemaVersion, models: [model] };
+ const tier = model.tieredPricing![0]!;
+ const cases: [unknown, string][] = [
+ [{ ...response, producerRevision: 'stale-v2' }, 'response.producerRevision'],
+ [{ ...response, models: [{ ...model, family: 'example' }] }, 'response.models[0].family'],
+ [
+ { ...response, models: [{ ...model, provenance: { source: 'stale-v2' } }] },
+ 'response.models[0].provenance',
+ ],
+ [
+ {
+ ...response,
+ models: [
+ {
+ ...model,
+ perAgent: {
+ 'claude-code': { supportsFastMode: false, verified: true },
+ },
+ },
+ ],
+ },
+ 'response.models[0].perAgent.claude-code.verified',
+ ],
+ [
+ {
+ ...response,
+ models: [{ ...model, tieredPricing: [{ ...tier, provenance: 'stale-v2' }] }],
+ },
+ 'response.models[0].tieredPricing[0].provenance',
+ ],
+ [
+ {
+ ...response,
+ models: [
+ {
+ ...model,
+ modalities: { ...model.modalities!, source: 'stale-v2' },
+ },
+ ],
+ },
+ 'response.models[0].modalities.source',
+ ],
+ ];
+
+ for (const [value, path] of cases) expectReject(value, path);
+ }
+ });
+
+ it('rejects malformed v2 newSessionDefault values', () => {
+ const withDefault = (value: unknown) => ({
+ ...VALID_RESPONSE,
+ models: [{ ...VALID_RESPONSE.models[0], newSessionDefault: value }],
+ });
+ expectReject(withDefault([]), 'response.models[0].newSessionDefault');
+ expectReject(withDefault(['codex', 'codex']), 'response.models[0].newSessionDefault');
+ expectReject(withDefault(['pi']), 'response.models[0].newSessionDefault');
+ expectReject(
+ {
+ ...VALID_RESPONSE,
+ models: [
+ {
+ ...VALID_RESPONSE.models[0],
+ agents: ['claude-code'],
+ newSessionDefault: ['codex'],
+ },
+ ],
+ },
+ 'response.models[0].newSessionDefault',
+ );
+ });
+
+ it('validates existing mode and normalized modalities in both schema versions', () => {
+ const { newSessionDefault: _newSessionDefault, ...legacyModel } = VALID_RESPONSE.models[0]!;
+ for (const [schemaVersion, model] of [
+ [MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION, legacyModel],
+ [MODEL_ACCESS_CATALOG_SCHEMA_VERSION, VALID_RESPONSE.models[0]!],
+ ] as const) {
+ expect(parseListModelsResponse({ schemaVersion, models: [model] }).ok).toBe(true);
+ expectReject({ schemaVersion, models: [{ ...model, mode: 42 }] }, 'response.models[0].mode');
+ expectReject({ schemaVersion, models: [{ ...model, icon: ' ' }] }, 'response.models[0].icon');
+ expectReject({ schemaVersion, models: [{ ...model, icon: 42 }] }, 'response.models[0].icon');
+ expectReject(
+ {
+ schemaVersion,
+ models: [{ ...model, modalities: { input: ['text', 42], output: ['text'] } }],
+ },
+ 'response.models[0].modalities.input',
+ );
+ }
+ });
+
+ it.each(['CNY', 'USD'] as const)('accepts the supported %s currency', (currency) => {
+ const result = parseListModelsResponse({
+ ...VALID_RESPONSE,
+ models: [{ ...VALID_RESPONSE.models[0], currency }],
+ });
+ expect(result.ok).toBe(true);
+ });
+
+ it('accepts missing currency for legacy fallback and rejects unsupported explicit values', () => {
+ const { currency: _currency, ...withoutCurrency } = VALID_RESPONSE.models[0]!;
+ expect(
+ parseListModelsResponse({ ...VALID_RESPONSE, models: [withoutCurrency] }),
+ ).toEqual({
+ ok: true,
+ value: { ...VALID_RESPONSE, models: [withoutCurrency] },
+ });
+ expectReject(
+ {
+ ...VALID_RESPONSE,
+ models: [{ ...VALID_RESPONSE.models[0], currency: 'EUR' }],
+ },
+ 'response.models[0].currency',
+ );
+ });
+
+ it('accepts missing or empty legacy agents while rejecting unsupported explicit values', () => {
+ const {
+ agents: _agents,
+ newSessionDefault: _newSessionDefault,
+ perAgent: _perAgent,
+ ...withoutAgents
+ } = VALID_RESPONSE.models[0]!;
+
+ for (const model of [withoutAgents, { ...withoutAgents, agents: [] }]) {
+ expect(parseListModelsResponse({ ...VALID_RESPONSE, models: [model] }).ok).toBe(true);
+ }
+ expectReject(
+ {
+ ...VALID_RESPONSE,
+ models: [{ ...VALID_RESPONSE.models[0], agents: ['pi'] }],
+ },
+ 'response.models[0].agents',
+ );
+ });
+
+ it('accepts null defaults from Model Access at the model and agent-override levels', () => {
+ expect(
+ parseListModelsResponse({
+ ...VALID_RESPONSE,
+ models: [
+ {
+ ...VALID_RESPONSE.models[0],
+ defaultEffort: null,
+ perAgent: { codex: { defaultEffort: null } },
+ },
+ ],
+ }).ok,
+ ).toBe(true);
+ });
+
+ it('rejects unsupported schema versions and malformed nested pricing', () => {
+ expectReject({ ...VALID_RESPONSE, schemaVersion: 3 }, 'response.schemaVersion');
+ expectReject(
+ {
+ ...VALID_RESPONSE,
+ models: [
+ {
+ ...VALID_RESPONSE.models[0],
+ tieredPricing: [{ range: [200_000, 0] }],
+ },
+ ],
+ },
+ 'response.models[0].tieredPricing[0].range',
+ );
+ });
+
+ it('rejects defaults that are absent from the declared effort list', () => {
+ expectReject(
+ {
+ ...VALID_RESPONSE,
+ models: [{ ...VALID_RESPONSE.models[0], efforts: ['low'], defaultEffort: 'high' }],
+ },
+ 'response.models[0].defaultEffort',
+ );
+ expectReject(
+ {
+ ...VALID_RESPONSE,
+ models: [
+ {
+ ...VALID_RESPONSE.models[0],
+ perAgent: { codex: { efforts: ['low'], defaultEffort: 'high' } },
+ },
+ ],
+ },
+ 'response.models[0].perAgent.codex.defaultEffort',
+ );
+ });
+
+ it('rejects duplicate ids and overrides for unsupported agents', () => {
+ expectReject(
+ {
+ ...VALID_RESPONSE,
+ models: [{ ...VALID_RESPONSE.models[0] }, { ...VALID_RESPONSE.models[0] }],
+ },
+ 'response.models[1].id',
+ );
+ expectReject(
+ {
+ ...VALID_RESPONSE,
+ models: [
+ {
+ ...VALID_RESPONSE.models[0],
+ agents: ['claude-code'],
+ newSessionDefault: ['claude-code'],
+ perAgent: { codex: { supportsFastMode: true } },
+ },
+ ],
+ },
+ 'response.models[0].perAgent.codex',
+ );
+ });
+});
+
+function expectRegistryReject(value: unknown, path: string): void {
+ const result = parseModelRegistry(value);
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('unreachable');
+ expect(result.error).toContain(path);
+}
+
+describe('public model registry contract', () => {
+ it('round-trips canonical metadata, provider routes, and sourced reference prices', () => {
+ const wire = JSON.parse(JSON.stringify(VALID_REGISTRY));
+ expect(parseModelRegistry(wire)).toEqual({ ok: true, value: VALID_REGISTRY });
+ });
+
+ it('continues to parse legacy v1 registries, while v1 rejects the v2-only field', () => {
+ const legacy = {
+ ...VALID_REGISTRY,
+ schemaVersion: MODEL_REGISTRY_LEGACY_SCHEMA_VERSION,
+ };
+ expect(parseModelRegistry(JSON.parse(JSON.stringify(legacy))).ok).toBe(true);
+ expectRegistryReject(
+ {
+ ...legacy,
+ models: [{ ...legacy.models[0], newSessionDefault: ['claude-code'] }],
+ },
+ 'modelRegistry.models[0].newSessionDefault',
+ );
+ });
+
+ it('accepts newSessionDefault as a subset of the entry route agents', () => {
+ const entry = VALID_REGISTRY.models[0]!;
+ const wire = {
+ ...VALID_REGISTRY,
+ models: [{ ...entry, newSessionDefault: ['claude-code', 'codex'] }],
+ };
+ const result = parseModelRegistry(JSON.parse(JSON.stringify(wire)));
+ expect(result.ok).toBe(true);
+ if (!result.ok) throw new Error('unreachable');
+ expect(result.value.models[0]!.newSessionDefault).toEqual(['claude-code', 'codex']);
+ });
+
+ it('rejects a malformed newSessionDefault (empty / duplicate / unknown agent)', () => {
+ const entry = VALID_REGISTRY.models[0]!;
+ const withDefault = (v: unknown) => ({
+ ...VALID_REGISTRY,
+ models: [{ ...entry, newSessionDefault: v }],
+ });
+ expectRegistryReject(withDefault([]), 'modelRegistry.models[0].newSessionDefault');
+ expectRegistryReject(
+ withDefault(['claude-code', 'claude-code']),
+ 'modelRegistry.models[0].newSessionDefault',
+ );
+ expectRegistryReject(withDefault(['bogus-agent']), 'modelRegistry.models[0].newSessionDefault');
+ });
+
+ it('rejects newSessionDefault agents not backed by any route', () => {
+ const entry = VALID_REGISTRY.models[0]!;
+ const route = entry.routes[0]!;
+ const wire = {
+ ...VALID_REGISTRY,
+ models: [
+ { ...entry, routes: [{ ...route, agents: ['claude-code'] }], newSessionDefault: ['codex'] },
+ ],
+ };
+ expectRegistryReject(
+ JSON.parse(JSON.stringify(wire)),
+ 'modelRegistry.models[0].newSessionDefault',
+ );
+ });
+
+ it('rejects newSessionDefault on retired registry entries', () => {
+ const entry = VALID_REGISTRY.models[0]!;
+ expectRegistryReject(
+ {
+ ...VALID_REGISTRY,
+ models: [{ ...entry, status: 'retired', newSessionDefault: ['claude-code'] }],
+ },
+ 'modelRegistry.models[0].newSessionDefault',
+ );
+ });
+
+ it('rejects client provenance and every other field outside the versioned schema', () => {
+ const entry = VALID_REGISTRY.models[0]!;
+ const route = entry.routes[0]!;
+ const price = route.referencePrices![0]!;
+ const cases: [unknown, string][] = [
+ [{ ...VALID_REGISTRY, contextWindowVerified: true }, 'modelRegistry.contextWindowVerified'],
+ [
+ {
+ ...VALID_REGISTRY,
+ models: [{ ...entry, contextWindowExplicit: true }],
+ },
+ 'modelRegistry.models[0].contextWindowExplicit',
+ ],
+ [
+ {
+ ...VALID_REGISTRY,
+ models: [
+ {
+ ...entry,
+ routes: [{ ...route, discoveredAt: '2026-07-31T00:00:00.000Z' }],
+ },
+ ],
+ },
+ 'modelRegistry.models[0].routes[0].discoveredAt',
+ ],
+ [
+ {
+ ...VALID_REGISTRY,
+ models: [{ ...entry, perAgent: { codex: { verified: true } } }],
+ },
+ 'modelRegistry.models[0].perAgent.codex.verified',
+ ],
+ [
+ {
+ ...VALID_REGISTRY,
+ models: [
+ {
+ ...entry,
+ routes: [
+ {
+ ...route,
+ referencePrices: [{ ...price, userOverride: true }],
+ },
+ ],
+ },
+ ],
+ },
+ 'modelRegistry.models[0].routes[0].referencePrices[0].userOverride',
+ ],
+ [
+ {
+ ...VALID_REGISTRY,
+ models: [
+ {
+ ...entry,
+ routes: [
+ {
+ ...route,
+ referencePrices: [
+ {
+ ...price,
+ source: { ...price.source, internalNote: 'client-only' },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ 'modelRegistry.models[0].routes[0].referencePrices[0].source.internalNote',
+ ],
+ ];
+
+ for (const [value, path] of cases) expectRegistryReject(value, path);
+ });
+
+ it('rejects unsupported versions, duplicate canonical ids, and duplicate routes', () => {
+ expectRegistryReject({ ...VALID_REGISTRY, schemaVersion: 3 }, 'modelRegistry.schemaVersion');
+ expectRegistryReject(
+ { ...VALID_REGISTRY, models: [VALID_REGISTRY.models[0], VALID_REGISTRY.models[0]] },
+ 'modelRegistry.models[1].id',
+ );
+ expectRegistryReject(
+ {
+ ...VALID_REGISTRY,
+ models: [
+ {
+ ...VALID_REGISTRY.models[0],
+ routes: [VALID_REGISTRY.models[0]!.routes[0], VALID_REGISTRY.models[0]!.routes[0]],
+ },
+ ],
+ },
+ 'modelRegistry.models[0].routes[1]',
+ );
+ });
+
+ it('requires a canonical, calendar-valid UTC timestamp', () => {
+ for (const updatedAt of [
+ '2026-07-31',
+ 'July 31, 2026',
+ '2026-07-31T00:00:00Z',
+ '2026-02-29T00:00:00.000Z',
+ '2026-07-31T08:00:00.000+08:00',
+ ]) {
+ expectRegistryReject({ ...VALID_REGISTRY, updatedAt }, 'modelRegistry.updatedAt');
+ }
+ });
+
+ it('rejects malformed price bands and untraceable price sources', () => {
+ const baseRoute = VALID_REGISTRY.models[0]!.routes[0]!;
+ const basePrice = baseRoute.referencePrices![0]!;
+ expectRegistryReject(
+ {
+ ...VALID_REGISTRY,
+ models: [
+ {
+ ...VALID_REGISTRY.models[0],
+ routes: [
+ {
+ ...baseRoute,
+ referencePrices: [
+ { ...basePrice, minInputTokens: 200_000, maxInputTokens: 200_000 },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ 'maxInputTokens',
+ );
+ expectRegistryReject(
+ {
+ ...VALID_REGISTRY,
+ models: [
+ {
+ ...VALID_REGISTRY.models[0],
+ routes: [
+ {
+ ...baseRoute,
+ referencePrices: [
+ {
+ ...basePrice,
+ source: { ...basePrice.source, url: 'http://example.com/pricing' },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ 'source.url',
+ );
+ });
+
+ it('allows scheduled prices and agent-specific metadata only on supported routes', () => {
+ const baseRoute = VALID_REGISTRY.models[0]!.routes[0]!;
+ const basePrice = baseRoute.referencePrices![0]!;
+ expect(
+ parseModelRegistry({
+ ...VALID_REGISTRY,
+ models: [
+ {
+ ...VALID_REGISTRY.models[0],
+ perAgent: { codex: { contextWindow: 272_000 } },
+ routes: [
+ {
+ ...baseRoute,
+ referencePrices: [
+ { ...basePrice, effectiveUntil: '2026-09-01' },
+ {
+ ...basePrice,
+ inputPerMtok: 2,
+ outputPerMtok: 10,
+ effectiveFrom: '2026-09-01',
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ }).ok,
+ ).toBe(true);
+
+ expectRegistryReject(
+ {
+ ...VALID_REGISTRY,
+ models: [
+ {
+ ...VALID_REGISTRY.models[0],
+ routes: [{ ...baseRoute, agents: ['claude-code'] }],
+ perAgent: { codex: { contextWindow: 272_000 } },
+ },
+ ],
+ },
+ 'perAgent.codex',
+ );
+ });
+
+ it('carries a materialization-complete presence shape on the current v2 wire', () => {
+ // The exact shape a policy-based client requires before deriving a
+ // selectable entry (MODEL_REGISTRY.md "Presence, entitlement, and sale
+ // availability"): explicit status + self-consistent capability set +
+ // per-agent divergence.
+ expect(MODEL_REGISTRY_SCHEMA_VERSION).toBe(2);
+ const wire = {
+ ...VALID_REGISTRY,
+ models: [
+ {
+ ...VALID_REGISTRY.models[0],
+ status: 'preview',
+ maxOutputTokens: 64_000,
+ perAgent: {
+ codex: {
+ contextWindow: 272_000,
+ efforts: ['low', 'medium', 'high'],
+ defaultEffort: 'high',
+ },
+ },
+ },
+ ],
+ };
+ expect(parseModelRegistry(JSON.parse(JSON.stringify(wire))).ok).toBe(true);
+ });
+
+ it.each(MODEL_REGISTRY_STATUSES)('accepts the %s lifecycle status', (status) => {
+ expect(
+ parseModelRegistry({
+ ...VALID_REGISTRY,
+ models: [{ ...VALID_REGISTRY.models[0], status }],
+ }).ok,
+ ).toBe(true);
+ });
+
+ it('accepts a fixed-effort entry: empty efforts with no default', () => {
+ const { defaultEffort: _defaultEffort, ...entry } = VALID_REGISTRY.models[0]!;
+ expect(
+ parseModelRegistry({
+ ...VALID_REGISTRY,
+ models: [{ ...entry, efforts: [] }],
+ }).ok,
+ ).toBe(true);
+ });
+
+ it('canonicalizes object key order while preserving snapshot content changes', () => {
+ const reordered = {
+ models: VALID_REGISTRY.models,
+ updatedAt: VALID_REGISTRY.updatedAt,
+ schemaVersion: VALID_REGISTRY.schemaVersion,
+ };
+ expect(modelRegistryCanonicalJson(reordered)).toBe(modelRegistryCanonicalJson(VALID_REGISTRY));
+ expect(
+ modelRegistryCanonicalJson({
+ ...reordered,
+ models: reordered.models.slice(1),
+ }),
+ ).not.toBe(modelRegistryCanonicalJson(VALID_REGISTRY));
+
+ const secondModel = {
+ ...VALID_REGISTRY.models[0]!,
+ id: 'example/other-model',
+ routes: [
+ {
+ ...VALID_REGISTRY.models[0]!.routes[0]!,
+ modelId: 'other-model',
+ },
+ ],
+ };
+ const orderedModels = [VALID_REGISTRY.models[0]!, secondModel];
+ expect(modelRegistryCanonicalJson({ ...VALID_REGISTRY, models: orderedModels })).not.toBe(
+ modelRegistryCanonicalJson({ ...VALID_REGISTRY, models: [...orderedModels].reverse() }),
+ );
+ });
+
+ it('keeps availability and selectability out of the wire schema', () => {
+ // Presence is the only registry-owned signal; availability/selectability
+ // markers are foreign fields at every level.
+ const entry = VALID_REGISTRY.models[0]!;
+ const route = entry.routes[0]!;
+ const cases: [unknown, string][] = [
+ [{ ...entry, available: true }, 'modelRegistry.models[0].available'],
+ [{ ...entry, selectable: true }, 'modelRegistry.models[0].selectable'],
+ [
+ { ...entry, routes: [{ ...route, available: true }] },
+ 'modelRegistry.models[0].routes[0].available',
+ ],
+ ];
+ for (const [model, path] of cases) {
+ expectRegistryReject({ ...VALID_REGISTRY, models: [model] }, path);
+ }
+ });
+
+ it('rejects client-derived agent harnesses on routes and per-agent overrides', () => {
+ // Projection harnesses (for example a client-side pi tab) never appear on
+ // the wire; the closed agent enum keeps them client-owned.
+ const entry = VALID_REGISTRY.models[0]!;
+ const route = entry.routes[0]!;
+ const cases: [unknown, string][] = [
+ [
+ { ...entry, routes: [{ ...route, agents: ['claude-code', 'pi'] }] },
+ 'modelRegistry.models[0].routes[0].agents',
+ ],
+ [
+ { ...entry, perAgent: { pi: { contextWindow: 200_000 } } },
+ 'modelRegistry.models[0].perAgent.pi',
+ ],
+ ];
+ for (const [model, path] of cases) {
+ expectRegistryReject({ ...VALID_REGISTRY, models: [model] }, path);
+ }
+ });
+
+ it('rejects ambiguous overlapping reference prices for the same currency and variant', () => {
+ const baseRoute = VALID_REGISTRY.models[0]!.routes[0]!;
+ const basePrice = baseRoute.referencePrices![0]!;
+ for (const overlappingPrice of [
+ { ...basePrice },
+ { ...basePrice, minInputTokens: 100_000, maxInputTokens: 300_000 },
+ {
+ ...basePrice,
+ effectiveFrom: '2026-07-15',
+ effectiveUntil: '2026-08-01',
+ },
+ ]) {
+ expectRegistryReject(
+ {
+ ...VALID_REGISTRY,
+ models: [
+ {
+ ...VALID_REGISTRY.models[0],
+ routes: [
+ {
+ ...baseRoute,
+ referencePrices: [basePrice, overlappingPrice],
+ },
+ ],
+ },
+ ],
+ },
+ 'referencePrices[1] overlaps referencePrices[0]',
+ );
+ }
+ });
+});
diff --git a/packages/model-providers/src/__tests__/modelRegistryConsistency.test.ts b/packages/model-providers/src/__tests__/modelRegistryConsistency.test.ts
index b9ce779055..ab6ccf82d1 100644
--- a/packages/model-providers/src/__tests__/modelRegistryConsistency.test.ts
+++ b/packages/model-providers/src/__tests__/modelRegistryConsistency.test.ts
@@ -7,7 +7,7 @@ import type {
ModelRegistryEntry,
ModelRegistryRoute,
ModelReferencePrice,
-} from "@cindy/model-access-protocol";
+} from "../modelAccessBean.js";
/**
* model-registry.json 数据自一致性门禁(#1429 跟进)。
diff --git a/packages/model-providers/src/__tests__/source-registry.test.ts b/packages/model-providers/src/__tests__/source-registry.test.ts
index 56e2058e40..26f8213c1e 100644
--- a/packages/model-providers/src/__tests__/source-registry.test.ts
+++ b/packages/model-providers/src/__tests__/source-registry.test.ts
@@ -7,7 +7,7 @@
*/
import { describe, it, expect, vi } from 'vitest';
-import { modelRegistryCanonicalJson } from '@cindy/model-access-protocol';
+import { modelRegistryCanonicalJson } from '../modelRegistryCanonical.js';
import { BUNDLED_CATALOG } from '../catalog.js';
import {
diff --git a/packages/model-providers/src/builtin.ts b/packages/model-providers/src/builtin.ts
index 0c5a823515..ca6be02e9a 100644
--- a/packages/model-providers/src/builtin.ts
+++ b/packages/model-providers/src/builtin.ts
@@ -24,7 +24,7 @@
import catalogJson from '../catalog/providers.json' with { type: 'json' };
import modelRegistryJson from '../catalog/model-registry.json' with { type: 'json' };
-import type { ModelRegistry } from '@cindy/model-access-protocol';
+import type { ModelRegistry } from './modelAccessBean.js';
import type { Catalog, Provider } from './types.js';
/** 仓内 v2 目录文件(xai 清单 + presets;同一文件发布到 OSS `cfg/providers.json`)。 */
diff --git a/packages/model-providers/src/catalog.ts b/packages/model-providers/src/catalog.ts
index 50ea074cbb..70447c2469 100644
--- a/packages/model-providers/src/catalog.ts
+++ b/packages/model-providers/src/catalog.ts
@@ -8,7 +8,7 @@
* 所有跨端模型元数据统一进入严格版本化的 `modelRegistry`;目录顶层不接受旁路元数据块。
*/
-import { parseModelRegistry } from '@cindy/model-access-protocol';
+import { parseModelRegistry } from './modelAccessValidator.js';
import { PI_REASONING_EFFORTS } from './types.js';
import type {
diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.ts
index d83e480ae8..28c89d8b28 100644
--- a/packages/model-providers/src/index.ts
+++ b/packages/model-providers/src/index.ts
@@ -64,20 +64,19 @@ export {
findModelRegistryRoute,
resolveModelReferencePrice,
} from './modelRegistry.js';
-export { modelRegistryCanonicalJson } from '@cindy/model-access-protocol';
+export { modelRegistryCanonicalJson } from './modelRegistryCanonical.js';
+export {
+ isModelCurrency,
+ parseListModelsResponse,
+ parseModelRegistry,
+} from './modelAccessValidator.js';
export type {
ResolvedModelReferencePrice,
ResolveModelReferencePriceOptions,
ModelRegistryRevisionRelation,
ModelRegistrySnapshotDecision,
} from './modelRegistry.js';
-export type {
- ModelReferencePrice,
- ModelReferencePriceSource,
- ModelRegistry,
- ModelRegistryEntry,
- ModelRegistryRoute,
-} from '@cindy/model-access-protocol';
+export * from './modelAccessBean.js';
export type {
CatalogSourceConfig,
CatalogIO,
diff --git a/packages/model-providers/src/modelAccessBean.ts b/packages/model-providers/src/modelAccessBean.ts
new file mode 100644
index 0000000000..940877ff99
--- /dev/null
+++ b/packages/model-providers/src/modelAccessBean.ts
@@ -0,0 +1,221 @@
+/**
+ * Client-owned DTOs for the Model Access HTTP/catalog boundary.
+ *
+ * These types deliberately live with the client domain model instead of in a
+ * cross-repository package. Runtime parsing still uses the legacy shared
+ * validator during the migration; keeping the DTOs local lets the validator
+ * move independently in the next phase without changing the wire shape.
+ */
+
+export const MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION = 1 as const;
+export const MODEL_ACCESS_CATALOG_SCHEMA_VERSION = 2 as const;
+export const MODEL_ACCESS_MODELS_PATH = '/api/model-access/models' as const;
+
+export const MODEL_ACCESS_CURRENCIES = ['CNY', 'USD'] as const;
+export type ModelCurrency = (typeof MODEL_ACCESS_CURRENCIES)[number];
+
+export const MODEL_ACCESS_AGENTS = ['claude-code', 'codex'] as const;
+export type ModelAgent = (typeof MODEL_ACCESS_AGENTS)[number];
+
+export const MODEL_ACCESS_EFFORTS = [
+ 'minimal',
+ 'low',
+ 'medium',
+ 'high',
+ 'xhigh',
+ 'max',
+ 'ultra',
+] as const;
+export type ModelEffort = (typeof MODEL_ACCESS_EFFORTS)[number];
+
+export const MODEL_REGISTRY_LEGACY_SCHEMA_VERSION = 1 as const;
+export const MODEL_REGISTRY_SCHEMA_VERSION = 2 as const;
+export const MODEL_REGISTRY_STATUSES = ['preview', 'active', 'deprecated', 'retired'] as const;
+export type ModelRegistryStatus = (typeof MODEL_REGISTRY_STATUSES)[number];
+
+export const MODEL_PRICE_VARIANTS = ['standard', 'priority', 'batch', 'fast'] as const;
+export type ModelPriceVariant = (typeof MODEL_PRICE_VARIANTS)[number];
+
+export interface ModelReferencePriceSource {
+ kind: 'provider-official';
+ url: string;
+ verifiedAt: string;
+}
+
+export interface ModelReferencePrice {
+ currency: ModelCurrency;
+ variant: ModelPriceVariant;
+ inputPerMtok: number;
+ outputPerMtok: number;
+ cacheReadPerMtok?: number;
+ cacheWritePerMtok?: number;
+ cacheWrite1hPerMtok?: number;
+ minInputTokens?: number;
+ maxInputTokens?: number;
+ effectiveFrom: string;
+ effectiveUntil?: string;
+ source: ModelReferencePriceSource;
+}
+
+export interface ModelRegistryRoute {
+ providerId: string;
+ modelId: string;
+ agents: ModelAgent[];
+ referencePrices?: ModelReferencePrice[];
+}
+
+export interface ModelAgentOverride {
+ contextWindow?: number;
+ efforts?: ModelEffort[];
+ defaultEffort?: ModelEffort;
+ supportsFastMode?: boolean;
+ defaultEnabled?: boolean;
+}
+
+interface ModelRegistryEntryBase {
+ id: string;
+ name: string;
+ routes: ModelRegistryRoute[];
+ status?: ModelRegistryStatus;
+ group?: string;
+ description?: string;
+ contextWindow?: number;
+ maxOutputTokens?: number;
+ efforts?: ModelEffort[];
+ defaultEffort?: ModelEffort;
+ sortOrder?: number;
+ supportsFastMode?: boolean;
+ defaultEnabled?: boolean;
+ perAgent?: Partial<Record<ModelAgent, ModelAgentOverride>>;
+}
+
+export interface ModelRegistryEntryV1 extends ModelRegistryEntryBase {
+ newSessionDefault?: never;
+}
+
+export interface ModelRegistryEntry extends ModelRegistryEntryBase {
+ newSessionDefault?: ModelAgent[];
+}
+
+interface ModelRegistryBase {
+ updatedAt: string;
+}
+
+export interface ModelRegistry extends ModelRegistryBase {
+ schemaVersion: typeof MODEL_REGISTRY_LEGACY_SCHEMA_VERSION | typeof MODEL_REGISTRY_SCHEMA_VERSION;
+ models: ModelRegistryEntry[];
+}
+
+export interface ModelRegistryV1 extends ModelRegistryBase {
+ schemaVersion: typeof MODEL_REGISTRY_LEGACY_SCHEMA_VERSION;
+ models: ModelRegistryEntryV1[];
+}
+
+export interface ModelRegistryV2 extends ModelRegistry {
+ schemaVersion: typeof MODEL_REGISTRY_SCHEMA_VERSION;
+}
+
+export interface ModelTieredPricing {
+ range: [number, number];
+ inputCostPerToken?: number;
+ outputCostPerToken?: number;
+ cacheReadInputTokenCost?: number;
+ cacheCreationInputTokenCost?: number;
+}
+
+export interface ModelPricing {
+ costDiscount?: number;
+ inputCostPerToken?: number;
+ outputCostPerToken?: number;
+ inputCostPerTokenPriority?: number;
+ outputCostPerTokenPriority?: number;
+ cacheReadInputTokenCost?: number;
+ cacheReadInputTokenCostPriority?: number;
+ cacheCreationInputTokenCost?: number;
+ inputCostPerTokenAbove200kTokens?: number;
+ outputCostPerTokenAbove200kTokens?: number;
+ cacheReadInputTokenCostAbove200kTokens?: number;
+ inputCostPerTokenAbove200kTokensPriority?: number;
+ outputCostPerTokenAbove200kTokensPriority?: number;
+ cacheReadInputTokenCostAbove200kTokensPriority?: number;
+ inputCostPerTokenAbove272kTokens?: number;
+ outputCostPerTokenAbove272kTokens?: number;
+ cacheReadInputTokenCostAbove272kTokens?: number;
+ inputCostPerTokenAbove272kTokensPriority?: number;
+ outputCostPerTokenAbove272kTokensPriority?: number;
+ cacheReadInputTokenCostAbove272kTokensPriority?: number;
+ inputCostPerCharacter?: number;
+ outputCostPerCharacter?: number;
+ inputCostPerSecond?: number;
+ outputCostPerSecond?: number;
+ inputCostPerAudioToken?: number;
+ outputCostPerAudioToken?: number;
+ inputCostPerAudioPerSecond?: number;
+ outputCostPerAudioPerSecond?: number;
+ inputCostPerImage?: number;
+ outputCostPerImage?: number;
+ inputCostPerImageToken?: number;
+ outputCostPerImageToken?: number;
+ cacheReadInputImageTokenCost?: number;
+ inputCostPerVideoPerSecond?: number;
+ outputCostPerVideoPerSecond?: number;
+ tieredPricing?: ModelTieredPricing[];
+}
+
+export interface ModelModalities {
+ input: string[];
+ output: string[];
+}
+
+interface ModelCatalogAgentOverride extends Omit<ModelAgentOverride, 'defaultEffort'> {
+ /** Older Model Access responses use null to mean that no effort is preferred. */
+ defaultEffort?: ModelEffort | null;
+}
+
+interface ModelCatalogEntryBase extends ModelPricing {
+ id: string;
+ mode?: string;
+ /** Optional for compatibility with older Model Access responses. */
+ currency?: ModelCurrency;
+ /** Missing or empty legacy values default to claude-code in the Desktop catalog. */
+ agents?: ModelAgent[];
+ name?: string;
+ group?: string;
+ description?: string;
+ icon?: string;
+ contextWindow?: number;
+ maxOutputTokens?: number;
+ modalities?: ModelModalities;
+ efforts?: ModelEffort[];
+ defaultEffort?: ModelEffort | null;
+ sortOrder?: number;
+ supportsFastMode?: boolean;
+ defaultEnabled?: boolean;
+ perAgent?: Partial<Record<ModelAgent, ModelCatalogAgentOverride>>;
+}
+
+export interface ModelCatalogEntryV1 extends ModelCatalogEntryBase {
+ newSessionDefault?: never;
+}
+
+export interface ModelCatalogEntry extends ModelCatalogEntryBase {
+ newSessionDefault?: ModelAgent[];
+}
+
+export interface ListModelsResponse {
+ schemaVersion:
+ typeof MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION | typeof MODEL_ACCESS_CATALOG_SCHEMA_VERSION;
+ models: ModelCatalogEntry[];
+}
+
+export interface ListModelsResponseV1 {
+ schemaVersion: typeof MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION;
+ models: ModelCatalogEntryV1[];
+}
+
+export interface ListModelsResponseV2 extends ListModelsResponse {
+ schemaVersion: typeof MODEL_ACCESS_CATALOG_SCHEMA_VERSION;
+}
+
+/** Result returned by local Model Access boundary parsers. */
+export type ModelAccessParseResult<T> = { ok: true; value: T } | { ok: false; error: string };
diff --git a/packages/model-providers/src/modelAccessValidator.ts b/packages/model-providers/src/modelAccessValidator.ts
new file mode 100644
index 0000000000..29e0116e0e
--- /dev/null
+++ b/packages/model-providers/src/modelAccessValidator.ts
@@ -0,0 +1,764 @@
+import {
+ MODEL_ACCESS_AGENTS,
+ MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION,
+ MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
+ MODEL_ACCESS_CURRENCIES,
+ MODEL_ACCESS_EFFORTS,
+ MODEL_PRICE_VARIANTS,
+ MODEL_REGISTRY_LEGACY_SCHEMA_VERSION,
+ MODEL_REGISTRY_SCHEMA_VERSION,
+ MODEL_REGISTRY_STATUSES,
+ type ListModelsResponse,
+ type ModelAccessParseResult,
+ type ModelAgent,
+ type ModelCurrency,
+ type ModelEffort,
+ type ModelPriceVariant,
+ type ModelRegistry,
+ type ModelRegistryStatus,
+} from './modelAccessBean.js';
+
+/** Local strict validator for untrusted Model Access catalog and Registry payloads. */
+type PlainObject = Record<string, unknown>;
+
+const PRICING_FIELDS = [
+ 'costDiscount',
+ 'inputCostPerToken',
+ 'outputCostPerToken',
+ 'inputCostPerTokenPriority',
+ 'outputCostPerTokenPriority',
+ 'cacheReadInputTokenCost',
+ 'cacheReadInputTokenCostPriority',
+ 'cacheCreationInputTokenCost',
+ 'inputCostPerTokenAbove200kTokens',
+ 'outputCostPerTokenAbove200kTokens',
+ 'cacheReadInputTokenCostAbove200kTokens',
+ 'inputCostPerTokenAbove200kTokensPriority',
+ 'outputCostPerTokenAbove200kTokensPriority',
+ 'cacheReadInputTokenCostAbove200kTokensPriority',
+ 'inputCostPerTokenAbove272kTokens',
+ 'outputCostPerTokenAbove272kTokens',
+ 'cacheReadInputTokenCostAbove272kTokens',
+ 'inputCostPerTokenAbove272kTokensPriority',
+ 'outputCostPerTokenAbove272kTokensPriority',
+ 'cacheReadInputTokenCostAbove272kTokensPriority',
+ 'inputCostPerCharacter',
+ 'outputCostPerCharacter',
+ 'inputCostPerSecond',
+ 'outputCostPerSecond',
+ 'inputCostPerAudioToken',
+ 'outputCostPerAudioToken',
+ 'inputCostPerAudioPerSecond',
+ 'outputCostPerAudioPerSecond',
+ 'inputCostPerImage',
+ 'outputCostPerImage',
+ 'inputCostPerImageToken',
+ 'outputCostPerImageToken',
+ 'cacheReadInputImageTokenCost',
+ 'inputCostPerVideoPerSecond',
+ 'outputCostPerVideoPerSecond',
+] as const;
+
+const LIST_MODELS_RESPONSE_FIELDS = ['schemaVersion', 'models'] as const;
+// v1 is frozen at its deployed wire shape. `mode` and `modalities` predate this
+// shared parser and are listed explicitly so strict dual-reading does not reject
+// current producers while still preventing fields from a different schema from
+// being accepted under version 1.
+const MODEL_CATALOG_ENTRY_V1_FIELDS = [
+ 'id',
+ 'mode',
+ 'currency',
+ 'agents',
+ 'name',
+ 'group',
+ 'description',
+ 'icon',
+ 'contextWindow',
+ 'maxOutputTokens',
+ 'modalities',
+ 'efforts',
+ 'defaultEffort',
+ 'sortOrder',
+ 'supportsFastMode',
+ 'defaultEnabled',
+ 'perAgent',
+ ...PRICING_FIELDS,
+ 'tieredPricing',
+] as const;
+const MODEL_CATALOG_ENTRY_V2_FIELDS = [
+ ...MODEL_CATALOG_ENTRY_V1_FIELDS,
+ 'newSessionDefault',
+] as const;
+const MODEL_AGENT_OVERRIDE_FIELDS = [
+ 'contextWindow',
+ 'efforts',
+ 'defaultEffort',
+ 'supportsFastMode',
+ 'defaultEnabled',
+] as const;
+const MODEL_TIERED_PRICING_FIELDS = [
+ 'range',
+ 'inputCostPerToken',
+ 'outputCostPerToken',
+ 'cacheReadInputTokenCost',
+ 'cacheCreationInputTokenCost',
+] as const;
+const MODEL_MODALITIES_FIELDS = ['input', 'output'] as const;
+
+const MODEL_REGISTRY_FIELDS = ['schemaVersion', 'updatedAt', 'models'] as const;
+const MODEL_REGISTRY_ENTRY_V1_FIELDS = [
+ 'id',
+ 'name',
+ 'routes',
+ 'status',
+ 'group',
+ 'description',
+ 'contextWindow',
+ 'maxOutputTokens',
+ 'efforts',
+ 'defaultEffort',
+ 'sortOrder',
+ 'supportsFastMode',
+ 'defaultEnabled',
+ 'perAgent',
+] as const;
+const MODEL_REGISTRY_ENTRY_V2_FIELDS = [
+ ...MODEL_REGISTRY_ENTRY_V1_FIELDS,
+ 'newSessionDefault',
+] as const;
+const MODEL_REGISTRY_ROUTE_FIELDS = ['providerId', 'modelId', 'agents', 'referencePrices'] as const;
+const MODEL_REFERENCE_PRICE_FIELDS = [
+ 'currency',
+ 'variant',
+ 'inputPerMtok',
+ 'outputPerMtok',
+ 'cacheReadPerMtok',
+ 'cacheWritePerMtok',
+ 'cacheWrite1hPerMtok',
+ 'minInputTokens',
+ 'maxInputTokens',
+ 'effectiveFrom',
+ 'effectiveUntil',
+ 'source',
+] as const;
+const MODEL_REFERENCE_PRICE_SOURCE_FIELDS = ['kind', 'url', 'verifiedAt'] as const;
+
+function ok<T>(value: T): ModelAccessParseResult<T> {
+ return { ok: true, value };
+}
+
+function fail<T>(error: string): ModelAccessParseResult<T> {
+ return { ok: false, error };
+}
+
+function isPlainObject(value: unknown): value is PlainObject {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function unknownFieldError(
+ value: PlainObject,
+ allowedFields: readonly string[],
+ path: string,
+): string | null {
+ const allowed = new Set(allowedFields);
+ const unknown = Object.keys(value).find((field) => !allowed.has(field));
+ return unknown ? `${path}.${unknown} is not allowed by this schema version` : null;
+}
+
+export function isModelCurrency(value: unknown): value is ModelCurrency {
+ return typeof value === 'string' && MODEL_ACCESS_CURRENCIES.includes(value as ModelCurrency);
+}
+
+function isModelAgent(value: unknown): value is ModelAgent {
+ return typeof value === 'string' && MODEL_ACCESS_AGENTS.includes(value as ModelAgent);
+}
+
+function isModelEffort(value: unknown): value is ModelEffort {
+ return typeof value === 'string' && MODEL_ACCESS_EFFORTS.includes(value as ModelEffort);
+}
+
+function isModelRegistryStatus(value: unknown): value is ModelRegistryStatus {
+ return (
+ typeof value === 'string' && MODEL_REGISTRY_STATUSES.includes(value as ModelRegistryStatus)
+ );
+}
+
+function isModelPriceVariant(value: unknown): value is ModelPriceVariant {
+ return typeof value === 'string' && MODEL_PRICE_VARIANTS.includes(value as ModelPriceVariant);
+}
+
+function isIsoDate(value: unknown): value is string {
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
+ const parsed = new Date(`${value}T00:00:00.000Z`);
+ return Number.isFinite(parsed.getTime()) && parsed.toISOString().startsWith(value);
+}
+
+function isIsoTimestamp(value: unknown): value is string {
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) {
+ return false;
+ }
+ const parsed = new Date(value);
+ return Number.isFinite(parsed.getTime()) && parsed.toISOString() === value;
+}
+
+function referencePriceRangesOverlap(a: PlainObject, b: PlainObject): boolean {
+ if (a.currency !== b.currency || a.variant !== b.variant) return false;
+ const aMin = typeof a.minInputTokens === 'number' ? a.minInputTokens : 0;
+ const bMin = typeof b.minInputTokens === 'number' ? b.minInputTokens : 0;
+ const aMax = typeof a.maxInputTokens === 'number' ? a.maxInputTokens : Number.POSITIVE_INFINITY;
+ const bMax = typeof b.maxInputTokens === 'number' ? b.maxInputTokens : Number.POSITIVE_INFINITY;
+ const tokenRangesOverlap = aMin < bMax && bMin < aMax;
+ const aUntil = typeof a.effectiveUntil === 'string' ? a.effectiveUntil : null;
+ const bUntil = typeof b.effectiveUntil === 'string' ? b.effectiveUntil : null;
+ const dateRangesOverlap =
+ (bUntil === null || String(a.effectiveFrom) < bUntil) &&
+ (aUntil === null || String(b.effectiveFrom) < aUntil);
+ return tokenRangesOverlap && dateRangesOverlap;
+}
+
+function isSafeSlug(value: unknown): value is string {
+ return typeof value === 'string' && /^[a-zA-Z0-9_-]+$/.test(value);
+}
+
+function isHttpsUrl(value: unknown): value is string {
+ if (typeof value !== 'string') return false;
+ try {
+ const url = new URL(value);
+ return url.protocol === 'https:' && !url.username && !url.password;
+ } catch {
+ return false;
+ }
+}
+
+function optionalStringError(value: unknown, path: string, max: number): string | null {
+ if (value === undefined) return null;
+ if (typeof value !== 'string') return `${path} must be a string when present`;
+ if (value.length > max) return `${path} must contain at most ${max} characters`;
+ return null;
+}
+
+function optionalPositiveIntegerError(value: unknown, path: string): string | null {
+ if (value === undefined) return null;
+ if (!Number.isInteger(value) || (value as number) <= 0) {
+ return `${path} must be a positive integer when present`;
+ }
+ return null;
+}
+
+function optionalFiniteNumberError(
+ value: unknown,
+ path: string,
+ options: { nonNegative?: boolean } = {},
+): string | null {
+ if (value === undefined) return null;
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
+ return `${path} must be a finite number when present`;
+ }
+ if (options.nonNegative && value < 0) {
+ return `${path} must be non-negative when present`;
+ }
+ return null;
+}
+
+function effortListError(value: unknown, path: string): string | null {
+ if (value === undefined) return null;
+ if (!Array.isArray(value) || value.some((effort) => !isModelEffort(effort))) {
+ return `${path} must contain only supported effort values`;
+ }
+ return null;
+}
+
+function modelModalitiesError(value: unknown, path: string): string | null {
+ if (value === undefined) return null;
+ if (!isPlainObject(value)) return `${path} must be an object when present`;
+ const unknownField = unknownFieldError(value, MODEL_MODALITIES_FIELDS, path);
+ if (unknownField) return unknownField;
+ for (const direction of MODEL_MODALITIES_FIELDS) {
+ if (
+ !Array.isArray(value[direction]) ||
+ value[direction].some((item) => typeof item !== 'string')
+ ) {
+ return `${path}.${direction} must be an array of strings`;
+ }
+ }
+ return null;
+}
+
+function overrideError(
+ value: unknown,
+ path: string,
+ baseEfforts: readonly ModelEffort[] | undefined,
+ allowedFields?: readonly string[],
+ allowNullDefaultEffort = false,
+): string | null {
+ if (!isPlainObject(value)) return `${path} must be an object`;
+ let error = allowedFields ? unknownFieldError(value, allowedFields, path) : null;
+ if (error) return error;
+ error = optionalPositiveIntegerError(value.contextWindow, `${path}.contextWindow`);
+ if (error) return error;
+ error = effortListError(value.efforts, `${path}.efforts`);
+ if (error) return error;
+ if (
+ value.defaultEffort !== undefined &&
+ value.defaultEffort !== null &&
+ !isModelEffort(value.defaultEffort)
+ ) {
+ return `${path}.defaultEffort must be a supported effort value when present`;
+ }
+ if (value.defaultEffort === null && !allowNullDefaultEffort) {
+ return `${path}.defaultEffort must be a supported effort value when present`;
+ }
+ const effectiveEfforts =
+ Array.isArray(value.efforts) && value.efforts.every(isModelEffort)
+ ? (value.efforts as ModelEffort[])
+ : baseEfforts;
+ if (
+ isModelEffort(value.defaultEffort) &&
+ effectiveEfforts !== undefined &&
+ !effectiveEfforts.includes(value.defaultEffort)
+ ) {
+ return `${path}.defaultEffort must be included in ${path}.efforts or the base efforts`;
+ }
+ for (const key of ['supportsFastMode', 'defaultEnabled'] as const) {
+ if (value[key] !== undefined && typeof value[key] !== 'boolean') {
+ return `${path}.${key} must be a boolean when present`;
+ }
+ }
+ return null;
+}
+
+function tieredPricingError(value: unknown, path: string): string | null {
+ if (value === undefined) return null;
+ if (!Array.isArray(value)) return `${path} must be an array when present`;
+ for (const [index, tier] of value.entries()) {
+ const tierPath = `${path}[${index}]`;
+ if (!isPlainObject(tier)) return `${tierPath} must be an object`;
+ const unknownField = unknownFieldError(tier, MODEL_TIERED_PRICING_FIELDS, tierPath);
+ if (unknownField) return unknownField;
+ if (
+ !Array.isArray(tier.range) ||
+ tier.range.length !== 2 ||
+ tier.range.some((bound) => typeof bound !== 'number' || !Number.isFinite(bound)) ||
+ tier.range[0] < 0 ||
+ tier.range[1] < tier.range[0]
+ ) {
+ return `${tierPath}.range must be an ascending pair of non-negative finite numbers`;
+ }
+ for (const field of [
+ 'inputCostPerToken',
+ 'outputCostPerToken',
+ 'cacheReadInputTokenCost',
+ 'cacheCreationInputTokenCost',
+ ] as const) {
+ const error = optionalFiniteNumberError(tier[field], `${tierPath}.${field}`, {
+ nonNegative: true,
+ });
+ if (error) return error;
+ }
+ }
+ return null;
+}
+
+function newSessionDefaultError(
+ value: unknown,
+ path: string,
+ supportedAgents: ReadonlySet<ModelAgent>,
+): string | null {
+ if (value === undefined) return null;
+ if (!Array.isArray(value) || value.length === 0) {
+ return `${path} must be a non-empty array when present`;
+ }
+ const seen = new Set<ModelAgent>();
+ for (const agent of value) {
+ if (!isModelAgent(agent)) return `${path} must contain only supported agents`;
+ if (seen.has(agent)) return `${path} must not contain duplicates`;
+ seen.add(agent);
+ if (!supportedAgents.has(agent)) {
+ return `${path} agents must be supported by the model entry`;
+ }
+ }
+ return null;
+}
+
+function modelEntryError(
+ value: unknown,
+ path: string,
+ schemaVersion:
+ typeof MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION | typeof MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
+): string | null {
+ if (!isPlainObject(value)) return `${path} must be an object`;
+ let error = unknownFieldError(
+ value,
+ schemaVersion === MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION
+ ? MODEL_CATALOG_ENTRY_V1_FIELDS
+ : MODEL_CATALOG_ENTRY_V2_FIELDS,
+ path,
+ );
+ if (error) return error;
+ if (typeof value.id !== 'string' || value.id.length === 0 || value.id.length > 256) {
+ return `${path}.id must be a non-empty string of at most 256 characters`;
+ }
+ error = optionalStringError(value.mode, `${path}.mode`, 128);
+ if (error) return error;
+ if (value.currency !== undefined && !isModelCurrency(value.currency)) {
+ return `${path}.currency must be CNY or USD when present`;
+ }
+ if (
+ value.agents !== undefined &&
+ (!Array.isArray(value.agents) || value.agents.some((agent) => !isModelAgent(agent)))
+ ) {
+ return `${path}.agents must be an array of supported agents when present`;
+ }
+ const supportedAgents = Array.isArray(value.agents) ? (value.agents as ModelAgent[]) : [];
+ if (schemaVersion === MODEL_ACCESS_CATALOG_SCHEMA_VERSION) {
+ const defaultError = newSessionDefaultError(
+ value.newSessionDefault,
+ `${path}.newSessionDefault`,
+ new Set(supportedAgents),
+ );
+ if (defaultError) return defaultError;
+ }
+
+ for (const [key, max] of [
+ ['name', 256],
+ ['group', 128],
+ ['description', 2_000],
+ ] as const) {
+ const error = optionalStringError(value[key], `${path}.${key}`, max);
+ if (error) return error;
+ }
+ if (
+ value.icon !== undefined &&
+ (typeof value.icon !== 'string' || value.icon.trim().length === 0)
+ ) {
+ return `${path}.icon must be a non-empty string when present`;
+ }
+ for (const key of ['contextWindow', 'maxOutputTokens'] as const) {
+ const error = optionalPositiveIntegerError(value[key], `${path}.${key}`);
+ if (error) return error;
+ }
+ error = modelModalitiesError(value.modalities, `${path}.modalities`);
+ if (error) return error;
+ error = effortListError(value.efforts, `${path}.efforts`);
+ if (error) return error;
+ if (
+ value.defaultEffort !== undefined &&
+ value.defaultEffort !== null &&
+ !isModelEffort(value.defaultEffort)
+ ) {
+ return `${path}.defaultEffort must be a supported effort value when present`;
+ }
+ const efforts =
+ Array.isArray(value.efforts) && value.efforts.every(isModelEffort)
+ ? (value.efforts as ModelEffort[])
+ : undefined;
+ if (
+ isModelEffort(value.defaultEffort) &&
+ efforts !== undefined &&
+ !efforts.includes(value.defaultEffort)
+ ) {
+ return `${path}.defaultEffort must be included in ${path}.efforts`;
+ }
+ error = optionalFiniteNumberError(value.sortOrder, `${path}.sortOrder`);
+ if (error) return error;
+ for (const key of ['supportsFastMode', 'defaultEnabled'] as const) {
+ if (value[key] !== undefined && typeof value[key] !== 'boolean') {
+ return `${path}.${key} must be a boolean when present`;
+ }
+ }
+
+ for (const field of PRICING_FIELDS) {
+ error = optionalFiniteNumberError(value[field], `${path}.${field}`, {
+ nonNegative: field !== 'costDiscount',
+ });
+ if (error) return error;
+ }
+ error = tieredPricingError(value.tieredPricing, `${path}.tieredPricing`);
+ if (error) return error;
+
+ if (value.perAgent !== undefined) {
+ if (!isPlainObject(value.perAgent)) return `${path}.perAgent must be an object when present`;
+ for (const [agent, override] of Object.entries(value.perAgent)) {
+ if (!isModelAgent(agent)) return `${path}.perAgent.${agent} is not a supported agent`;
+ if (!supportedAgents.includes(agent)) {
+ return `${path}.perAgent.${agent} must be included in ${path}.agents`;
+ }
+ error = overrideError(
+ override,
+ `${path}.perAgent.${agent}`,
+ efforts,
+ MODEL_AGENT_OVERRIDE_FIELDS,
+ true,
+ );
+ if (error) return error;
+ }
+ }
+ return null;
+}
+
+export function parseListModelsResponse(
+ value: unknown,
+): ModelAccessParseResult<ListModelsResponse> {
+ if (!isPlainObject(value)) return fail('response must be an object');
+ const unknownField = unknownFieldError(value, LIST_MODELS_RESPONSE_FIELDS, 'response');
+ if (unknownField) return fail(unknownField);
+ if (
+ value.schemaVersion !== MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION &&
+ value.schemaVersion !== MODEL_ACCESS_CATALOG_SCHEMA_VERSION
+ ) {
+ return fail(
+ `response.schemaVersion must be ${MODEL_ACCESS_CATALOG_LEGACY_SCHEMA_VERSION} or ${MODEL_ACCESS_CATALOG_SCHEMA_VERSION}`,
+ );
+ }
+ if (!Array.isArray(value.models)) return fail('response.models must be an array');
+ const modelIds = new Set<string>();
+ for (const [index, model] of value.models.entries()) {
+ if (isPlainObject(model) && typeof model.id === 'string') {
+ if (modelIds.has(model.id)) {
+ return fail(`response.models[${index}].id must be unique`);
+ }
+ modelIds.add(model.id);
+ }
+ const error = modelEntryError(model, `response.models[${index}]`, value.schemaVersion);
+ if (error) return fail(error);
+ }
+ return ok(value as unknown as ListModelsResponse);
+}
+
+function referencePriceError(value: unknown, path: string): string | null {
+ if (!isPlainObject(value)) return `${path} must be an object`;
+ let error = unknownFieldError(value, MODEL_REFERENCE_PRICE_FIELDS, path);
+ if (error) return error;
+ if (!isModelCurrency(value.currency)) return `${path}.currency must be CNY or USD`;
+ if (!isModelPriceVariant(value.variant)) {
+ return `${path}.variant must be a supported price variant`;
+ }
+ for (const field of [
+ 'inputPerMtok',
+ 'outputPerMtok',
+ 'cacheReadPerMtok',
+ 'cacheWritePerMtok',
+ 'cacheWrite1hPerMtok',
+ ] as const) {
+ error = optionalFiniteNumberError(value[field], `${path}.${field}`, {
+ nonNegative: true,
+ });
+ if (error) return error;
+ }
+ if (value.inputPerMtok === undefined || value.outputPerMtok === undefined) {
+ return `${path} must declare inputPerMtok and outputPerMtok`;
+ }
+ for (const field of ['minInputTokens', 'maxInputTokens'] as const) {
+ if (
+ value[field] !== undefined &&
+ (!Number.isInteger(value[field]) || (value[field] as number) < 0)
+ ) {
+ return `${path}.${field} must be a non-negative integer when present`;
+ }
+ }
+ const min = typeof value.minInputTokens === 'number' ? value.minInputTokens : 0;
+ if (typeof value.maxInputTokens === 'number' && value.maxInputTokens <= min) {
+ return `${path}.maxInputTokens must be greater than minInputTokens`;
+ }
+ if (!isIsoDate(value.effectiveFrom)) {
+ return `${path}.effectiveFrom must be an ISO calendar date`;
+ }
+ if (value.effectiveUntil !== undefined) {
+ if (!isIsoDate(value.effectiveUntil)) {
+ return `${path}.effectiveUntil must be an ISO calendar date when present`;
+ }
+ if (value.effectiveUntil <= value.effectiveFrom) {
+ return `${path}.effectiveUntil must be after effectiveFrom`;
+ }
+ }
+ if (!isPlainObject(value.source)) return `${path}.source must be an object`;
+ error = unknownFieldError(value.source, MODEL_REFERENCE_PRICE_SOURCE_FIELDS, `${path}.source`);
+ if (error) return error;
+ if (value.source.kind !== 'provider-official') {
+ return `${path}.source.kind must be provider-official`;
+ }
+ if (!isHttpsUrl(value.source.url)) return `${path}.source.url must be an HTTPS URL`;
+ if (!isIsoDate(value.source.verifiedAt)) {
+ return `${path}.source.verifiedAt must be an ISO calendar date`;
+ }
+ return null;
+}
+
+function registryRouteError(value: unknown, path: string): string | null {
+ if (!isPlainObject(value)) return `${path} must be an object`;
+ let error = unknownFieldError(value, MODEL_REGISTRY_ROUTE_FIELDS, path);
+ if (error) return error;
+ if (!isSafeSlug(value.providerId)) {
+ return `${path}.providerId must use letters, numbers, underscores, or hyphens`;
+ }
+ if (
+ typeof value.modelId !== 'string' ||
+ value.modelId.length === 0 ||
+ value.modelId.length > 256
+ ) {
+ return `${path}.modelId must be a non-empty string of at most 256 characters`;
+ }
+ if (
+ !Array.isArray(value.agents) ||
+ value.agents.length === 0 ||
+ value.agents.some((agent) => !isModelAgent(agent)) ||
+ new Set(value.agents).size !== value.agents.length
+ ) {
+ return `${path}.agents must be a unique non-empty array of supported agents`;
+ }
+ if (value.referencePrices !== undefined) {
+ if (!Array.isArray(value.referencePrices)) {
+ return `${path}.referencePrices must be an array when present`;
+ }
+ for (const [index, price] of value.referencePrices.entries()) {
+ error = referencePriceError(price, `${path}.referencePrices[${index}]`);
+ if (error) return error;
+ for (let previousIndex = 0; previousIndex < index; previousIndex += 1) {
+ const previous = value.referencePrices[previousIndex];
+ if (
+ isPlainObject(price) &&
+ isPlainObject(previous) &&
+ referencePriceRangesOverlap(previous, price)
+ ) {
+ return `${path}.referencePrices[${index}] overlaps referencePrices[${previousIndex}] for the same currency and variant`;
+ }
+ }
+ }
+ }
+ return null;
+}
+
+function registryEntryError(
+ value: unknown,
+ path: string,
+ schemaVersion: typeof MODEL_REGISTRY_LEGACY_SCHEMA_VERSION | typeof MODEL_REGISTRY_SCHEMA_VERSION,
+): string | null {
+ if (!isPlainObject(value)) return `${path} must be an object`;
+ let error = unknownFieldError(
+ value,
+ schemaVersion === MODEL_REGISTRY_LEGACY_SCHEMA_VERSION
+ ? MODEL_REGISTRY_ENTRY_V1_FIELDS
+ : MODEL_REGISTRY_ENTRY_V2_FIELDS,
+ path,
+ );
+ if (error) return error;
+ if (typeof value.id !== 'string' || value.id.length === 0 || value.id.length > 256) {
+ return `${path}.id must be a non-empty string of at most 256 characters`;
+ }
+ if (typeof value.name !== 'string' || value.name.length === 0 || value.name.length > 256) {
+ return `${path}.name must be a non-empty string of at most 256 characters`;
+ }
+ if (value.status !== undefined && !isModelRegistryStatus(value.status)) {
+ return `${path}.status must be a supported registry status`;
+ }
+ for (const [key, max] of [
+ ['group', 128],
+ ['description', 2_000],
+ ] as const) {
+ error = optionalStringError(value[key], `${path}.${key}`, max);
+ if (error) return error;
+ }
+ for (const key of ['contextWindow', 'maxOutputTokens'] as const) {
+ error = optionalPositiveIntegerError(value[key], `${path}.${key}`);
+ if (error) return error;
+ }
+ error = effortListError(value.efforts, `${path}.efforts`);
+ if (error) return error;
+ if (value.defaultEffort !== undefined && !isModelEffort(value.defaultEffort)) {
+ return `${path}.defaultEffort must be a supported effort value when present`;
+ }
+ const efforts =
+ Array.isArray(value.efforts) && value.efforts.every(isModelEffort)
+ ? (value.efforts as ModelEffort[])
+ : undefined;
+ if (
+ value.defaultEffort !== undefined &&
+ efforts !== undefined &&
+ !efforts.includes(value.defaultEffort as ModelEffort)
+ ) {
+ return `${path}.defaultEffort must be included in ${path}.efforts`;
+ }
+ error = optionalFiniteNumberError(value.sortOrder, `${path}.sortOrder`);
+ if (error) return error;
+ for (const key of ['supportsFastMode', 'defaultEnabled'] as const) {
+ if (value[key] !== undefined && typeof value[key] !== 'boolean') {
+ return `${path}.${key} must be a boolean when present`;
+ }
+ }
+ if (!Array.isArray(value.routes) || value.routes.length === 0) {
+ return `${path}.routes must be a non-empty array`;
+ }
+ const routeKeys = new Set<string>();
+ const supportedAgents = new Set<ModelAgent>();
+ for (const [index, route] of value.routes.entries()) {
+ error = registryRouteError(route, `${path}.routes[${index}]`);
+ if (error) return error;
+ const typedRoute = route as {
+ providerId: string;
+ modelId: string;
+ agents: ModelAgent[];
+ };
+ const routeKey = `${typedRoute.providerId}\u0000${typedRoute.modelId}`;
+ if (routeKeys.has(routeKey)) return `${path}.routes[${index}] must be unique`;
+ routeKeys.add(routeKey);
+ for (const agent of typedRoute.agents) supportedAgents.add(agent);
+ }
+ if (value.perAgent !== undefined) {
+ if (!isPlainObject(value.perAgent)) return `${path}.perAgent must be an object when present`;
+ for (const [agent, override] of Object.entries(value.perAgent)) {
+ if (!isModelAgent(agent)) return `${path}.perAgent.${agent} is not a supported agent`;
+ if (!supportedAgents.has(agent)) {
+ return `${path}.perAgent.${agent} must be supported by at least one route`;
+ }
+ error = overrideError(
+ override,
+ `${path}.perAgent.${agent}`,
+ efforts,
+ MODEL_AGENT_OVERRIDE_FIELDS,
+ );
+ if (error) return error;
+ }
+ }
+ if (schemaVersion === MODEL_REGISTRY_SCHEMA_VERSION) {
+ if (value.status === 'retired' && value.newSessionDefault !== undefined) {
+ return `${path}.newSessionDefault is not allowed when ${path}.status is retired`;
+ }
+ const defaultError = newSessionDefaultError(
+ value.newSessionDefault,
+ `${path}.newSessionDefault`,
+ supportedAgents,
+ );
+ if (defaultError) return defaultError;
+ }
+ return null;
+}
+
+export function parseModelRegistry(value: unknown): ModelAccessParseResult<ModelRegistry> {
+ if (!isPlainObject(value)) return fail('modelRegistry must be an object');
+ const unknownField = unknownFieldError(value, MODEL_REGISTRY_FIELDS, 'modelRegistry');
+ if (unknownField) return fail(unknownField);
+ if (
+ value.schemaVersion !== MODEL_REGISTRY_LEGACY_SCHEMA_VERSION &&
+ value.schemaVersion !== MODEL_REGISTRY_SCHEMA_VERSION
+ ) {
+ return fail(
+ `modelRegistry.schemaVersion must be ${MODEL_REGISTRY_LEGACY_SCHEMA_VERSION} or ${MODEL_REGISTRY_SCHEMA_VERSION}`,
+ );
+ }
+ if (!isIsoTimestamp(value.updatedAt)) {
+ return fail('modelRegistry.updatedAt must be an ISO timestamp');
+ }
+ if (!Array.isArray(value.models)) return fail('modelRegistry.models must be an array');
+ const modelIds = new Set<string>();
+ for (const [index, model] of value.models.entries()) {
+ if (isPlainObject(model) && typeof model.id === 'string') {
+ if (modelIds.has(model.id)) {
+ return fail(`modelRegistry.models[${index}].id must be unique`);
+ }
+ modelIds.add(model.id);
+ }
+ const error = registryEntryError(model, `modelRegistry.models[${index}]`, value.schemaVersion);
+ if (error) return fail(error);
+ }
+ return ok(value as unknown as ModelRegistry);
+}
diff --git a/packages/model-providers/src/modelRegistry.ts b/packages/model-providers/src/modelRegistry.ts
index 9f49d14588..95491516ef 100644
--- a/packages/model-providers/src/modelRegistry.ts
+++ b/packages/model-providers/src/modelRegistry.ts
@@ -1,12 +1,12 @@
-import {
- modelRegistryCanonicalJson,
- type ModelAgent,
- type ModelPriceVariant,
- type ModelReferencePrice,
- type ModelRegistry,
- type ModelRegistryEntry,
- type ModelRegistryRoute,
-} from "@cindy/model-access-protocol";
+import { modelRegistryCanonicalJson } from "./modelRegistryCanonical.js";
+import type {
+ ModelAgent,
+ ModelPriceVariant,
+ ModelReferencePrice,
+ ModelRegistry,
+ ModelRegistryEntry,
+ ModelRegistryRoute,
+} from "./modelAccessBean.js";
export type ModelRegistryRevisionRelation =
| "newer"
diff --git a/packages/model-providers/src/modelRegistryCanonical.ts b/packages/model-providers/src/modelRegistryCanonical.ts
new file mode 100644
index 0000000000..b71a59ad3f
--- /dev/null
+++ b/packages/model-providers/src/modelRegistryCanonical.ts
@@ -0,0 +1,20 @@
+import type { ModelRegistry } from './modelAccessBean.js';
+
+function sortKeysDeep(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(sortKeysDeep);
+ if (value && typeof value === 'object') {
+ const source = value as Record<string, unknown>;
+ const out: Record<string, unknown> = {};
+ for (const key of Object.keys(source).sort()) out[key] = sortKeysDeep(source[key]);
+ return out;
+ }
+ return value;
+}
+
+/**
+ * Deterministic Registry serialization for immutable-revision checks. Object
+ * key order is normalized; array order remains part of the snapshot contract.
+ */
+export function modelRegistryCanonicalJson(registry: ModelRegistry): string {
+ return JSON.stringify(sortKeysDeep(registry));
+}
diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.ts
index 93d910c530..de8caed890 100644
--- a/packages/model-providers/src/types.ts
+++ b/packages/model-providers/src/types.ts
@@ -17,7 +17,7 @@
* 本包零运行时依赖:`AgentKind` / `Effort` 在此就地定义(与 maker-core 的同名
* 联合保持一致),不 import maker-core,保证可作为独立能力复用。
*/
-import type { ModelRegistry } from '@cindy/model-access-protocol';
+import type { ModelRegistry } from './modelAccessBean.js';
/** 承载模型的 agent runtime —— 与 maker-core AgentKind 对齐。 */
export type AgentKind = 'claude-code' | 'codex' | 'pi';
diff --git a/packages/plugin-protocol/package.json b/packages/plugin-protocol/package.json
new file mode 100644
index 0000000000..2aeebb957c
--- /dev/null
+++ b/packages/plugin-protocol/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "@cindy/plugin-protocol",
+ "version": "0.0.0",
+ "private": true,
+ "description": "Cindy Ghost manifest and desktop plugin delivery contracts. Zero runtime dependencies",
+ "type": "module",
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "exports": {
+ ".": "./src/index.ts",
+ "./manifest": "./src/manifest.ts",
+ "./delivery": "./src/delivery.ts",
+ "./member-upload": "./src/memberUpload.ts"
+ },
+ "scripts": {
+ "build": "tsc --noEmit",
+ "test": "vitest run"
+ },
+ "license": "Apache-2.0",
+ "devDependencies": {
+ "@types/node": "*",
+ "typescript": "^5.7.0",
+ "vitest": "^3.2.4"
+ }
+}
diff --git a/packages/plugin-protocol/src/__tests__/delivery.test.ts b/packages/plugin-protocol/src/__tests__/delivery.test.ts
new file mode 100644
index 0000000000..e5a5b5cad4
--- /dev/null
+++ b/packages/plugin-protocol/src/__tests__/delivery.test.ts
@@ -0,0 +1,543 @@
+import { describe, expect, it } from 'vitest';
+import {
+ PLUGIN_API_SCHEMA_VERSION,
+ parseGetPluginResponse,
+ parseListPluginsResponse,
+ parsePluginDownloadResponse,
+ PluginProtocolError,
+} from '../delivery.js';
+import { GHOST_MANIFEST_SCHEMA_VERSION } from '../manifest.js';
+
+const validManifest = {
+ schemaVersion: GHOST_MANIFEST_SCHEMA_VERSION,
+ id: 'acme-helper',
+ name: 'Acme Helper',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'index.js',
+ slots: ['tool'],
+ tools: [{ name: 'help', description: 'Help with Acme tasks' }],
+} as const;
+const pluginId = `c${'p'.repeat(24)}`;
+const validIcon = {
+ mimeType: 'image/png',
+ sha256: 'c'.repeat(64),
+ sizeBytes: 2048,
+ url: 'https://cdn.example.com/plugin-icon.png?signature=example',
+ expiresAt: '2026-07-19T00:05:00.000Z',
+} as const;
+const oidcManifest = {
+ ...validManifest,
+ tools: undefined,
+ slots: ['network'],
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [
+ {
+ key: 'cindy_identity',
+ label: 'Cindy organization identity',
+ source: 'oidc-token',
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['api.example.com'],
+ },
+ },
+ ],
+ },
+} as const;
+
+describe('plugin delivery contract', () => {
+ it('parses a paginated visible Plugin summary without requiring a manifest', () => {
+ const response = parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [
+ {
+ id: pluginId,
+ ghostId: validManifest.id,
+ name: validManifest.name,
+ description: null,
+ author: null,
+ scope: 'public',
+ organizationId: null,
+ defaultInstall: true,
+ currentRelease: {
+ id: 'release-1',
+ version: validManifest.version,
+ sha256: 'a'.repeat(64),
+ sizeBytes: 1024,
+ publishedAt: '2026-07-19T00:00:00.000Z',
+ icon: validIcon,
+ },
+ },
+ ],
+ nextCursor: pluginId,
+ });
+ expect(response.plugins[0]?.name).toBe(validManifest.name);
+ expect(response.plugins[0]?.currentRelease.version).toBe(validManifest.version);
+ expect(response.plugins[0]?.currentRelease.icon).toEqual(validIcon);
+ expect(response.nextCursor).toBe(pluginId);
+ });
+
+ it('accepts legacy v2 releases without icon metadata', () => {
+ const response = parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [
+ {
+ id: pluginId,
+ ghostId: validManifest.id,
+ name: validManifest.name,
+ description: null,
+ author: null,
+ scope: 'public',
+ organizationId: null,
+ defaultInstall: false,
+ currentRelease: {
+ id: 'release-legacy',
+ version: validManifest.version,
+ sha256: 'a'.repeat(64),
+ sizeBytes: 1024,
+ publishedAt: '2026-07-19T00:00:00.000Z',
+ },
+ },
+ ],
+ nextCursor: null,
+ });
+ expect(response.plugins[0]?.currentRelease.icon).toBeNull();
+ });
+
+ it('rejects non-HTTPS icon URLs and invalid icon hashes', () => {
+ const plugin = {
+ id: pluginId,
+ ghostId: validManifest.id,
+ name: validManifest.name,
+ description: null,
+ author: null,
+ scope: 'public',
+ organizationId: null,
+ defaultInstall: false,
+ currentRelease: {
+ id: 'release-icon',
+ version: validManifest.version,
+ sha256: 'a'.repeat(64),
+ sizeBytes: 1024,
+ publishedAt: '2026-07-19T00:00:00.000Z',
+ icon: { ...validIcon, url: 'http://localhost:3391/icon.png' },
+ },
+ };
+ expect(() =>
+ parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [plugin],
+ nextCursor: null,
+ }),
+ ).toThrow(PluginProtocolError);
+ expect(() =>
+ parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [
+ {
+ ...plugin,
+ currentRelease: { ...plugin.currentRelease, icon: { ...validIcon, sha256: 'bad' } },
+ },
+ ],
+ nextCursor: null,
+ }),
+ ).toThrow(PluginProtocolError);
+ });
+
+ it('parses a visible Plugin detail and validates its manifest', () => {
+ const detailManifest = {
+ ...validManifest,
+ slots: ['tool', 'panel', 'badge', 'confirm', 'agent'],
+ panel: { html: 'panel.html' },
+ agent: { errand: true, schedule: true },
+ } as const;
+ const response = parseGetPluginResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugin: {
+ id: pluginId,
+ ghostId: detailManifest.id,
+ name: detailManifest.name,
+ description: null,
+ author: null,
+ scope: 'public',
+ organizationId: null,
+ defaultInstall: true,
+ currentRelease: {
+ id: 'release-1',
+ version: detailManifest.version,
+ sha256: 'a'.repeat(64),
+ sizeBytes: 1024,
+ publishedAt: '2026-07-19T00:00:00.000Z',
+ manifest: detailManifest,
+ },
+ },
+ });
+ expect(response.plugin.currentRelease.manifest.id).toBe(detailManifest.id);
+ expect(response.plugin.currentRelease.manifest.slots).toEqual([
+ 'tool',
+ 'panel',
+ 'badge',
+ 'confirm',
+ 'agent',
+ ]);
+ expect(response.plugin.currentRelease.manifest.agent).toEqual({
+ errand: true,
+ schedule: true,
+ });
+ });
+
+ it('preserves the version-gated ios-simulator slot in Plugin details', () => {
+ const manifest = {
+ ...validManifest,
+ id: 'simulator-workflow',
+ name: 'Simulator Workflow',
+ minCindyVersion: '1.2.3',
+ slots: ['ios-simulator'],
+ tools: undefined,
+ } as const;
+ const response = parseGetPluginResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugin: {
+ id: pluginId,
+ ghostId: manifest.id,
+ name: manifest.name,
+ description: null,
+ author: null,
+ scope: 'public',
+ organizationId: null,
+ defaultInstall: false,
+ currentRelease: {
+ id: 'release-simulator',
+ version: manifest.version,
+ sha256: 'a'.repeat(64),
+ sizeBytes: 1024,
+ publishedAt: '2026-07-19T00:00:00.000Z',
+ manifest,
+ },
+ },
+ });
+
+ expect(response.plugin.currentRelease.manifest.slots).toEqual(['ios-simulator']);
+ expect(response.plugin.currentRelease.manifest.minCindyVersion).toBe('1.2.3');
+ });
+
+ it('allows oidc-token only in organization Plugin details', () => {
+ const plugin = {
+ id: pluginId,
+ ghostId: oidcManifest.id,
+ name: oidcManifest.name,
+ description: null,
+ author: null,
+ defaultInstall: false,
+ currentRelease: {
+ id: 'release-oidc',
+ version: oidcManifest.version,
+ sha256: 'a'.repeat(64),
+ sizeBytes: 1024,
+ publishedAt: '2026-07-19T00:00:00.000Z',
+ manifest: oidcManifest,
+ },
+ };
+
+ expect(
+ parseGetPluginResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugin: { ...plugin, scope: 'organization', organizationId: 'org-1' },
+ }).plugin.scope,
+ ).toBe('organization');
+ for (const scope of ['public', 'personal'] as const) {
+ expect(() =>
+ parseGetPluginResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugin: { ...plugin, scope, organizationId: null },
+ }),
+ ).toThrow(/currentRelease\.manifest.*oidc-token.*organization scope/);
+ }
+ });
+
+ it('keeps availability separate from default installation', () => {
+ const response = parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [
+ {
+ id: pluginId,
+ ghostId: validManifest.id,
+ name: validManifest.name,
+ description: null,
+ author: null,
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: false,
+ currentRelease: {
+ id: 'release-1',
+ version: validManifest.version,
+ sha256: 'b'.repeat(64),
+ sizeBytes: 1024,
+ publishedAt: '2026-07-19T00:00:00.000Z',
+ },
+ },
+ ],
+ nextCursor: null,
+ });
+ expect(response.plugins).toHaveLength(1);
+ expect(response.plugins[0]?.defaultInstall).toBe(false);
+ });
+
+ it('parses a personal Plugin without exposing its owner identity', () => {
+ const response = parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [
+ {
+ id: pluginId,
+ ghostId: validManifest.id,
+ name: validManifest.name,
+ description: null,
+ author: null,
+ scope: 'personal',
+ organizationId: null,
+ ownerPassportId: 'passport-example',
+ defaultInstall: false,
+ currentRelease: {
+ id: 'release-1',
+ version: validManifest.version,
+ sha256: 'b'.repeat(64),
+ sizeBytes: 1024,
+ publishedAt: '2026-07-19T00:00:00.000Z',
+ },
+ },
+ ],
+ nextCursor: null,
+ });
+ expect(response.plugins[0]?.scope).toBe('personal');
+ expect(response.plugins[0]?.organizationId).toBeNull();
+ expect(response.plugins[0]).not.toHaveProperty('ownerPassportId');
+ });
+
+ it('rejects organization ownership metadata that disagrees with scope', () => {
+ const plugin = {
+ id: pluginId,
+ ghostId: validManifest.id,
+ name: validManifest.name,
+ description: null,
+ author: null,
+ defaultInstall: false,
+ currentRelease: {
+ id: 'release-1',
+ version: validManifest.version,
+ sha256: 'b'.repeat(64),
+ sizeBytes: 1024,
+ publishedAt: '2026-07-19T00:00:00.000Z',
+ },
+ };
+
+ expect(() =>
+ parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [{ ...plugin, scope: 'public', organizationId: 'org-1' }],
+ nextCursor: null,
+ }),
+ ).toThrow(PluginProtocolError);
+ expect(() =>
+ parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [{ ...plugin, scope: 'personal', organizationId: 'org-1' }],
+ nextCursor: null,
+ }),
+ ).toThrow(PluginProtocolError);
+ expect(() =>
+ parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [{ ...plugin, scope: 'organization', organizationId: null }],
+ nextCursor: null,
+ }),
+ ).toThrow(PluginProtocolError);
+ });
+
+ it('parses the signed download response used by staging installation', () => {
+ expect(
+ parsePluginDownloadResponse({
+ url: 'https://example.com/plugin.cindy?signature=example',
+ expiresAt: '2026-07-19T00:05:00.000Z',
+ sha256: 'c'.repeat(64),
+ sizeBytes: 1024,
+ }),
+ ).toEqual({
+ url: 'https://example.com/plugin.cindy?signature=example',
+ expiresAt: '2026-07-19T00:05:00.000Z',
+ sha256: 'c'.repeat(64),
+ sizeBytes: 1024,
+ });
+ expect(() =>
+ parsePluginDownloadResponse({
+ url: 'http://example.com/plugin.cindy',
+ expiresAt: '2026-07-19T00:05:00.000Z',
+ sha256: 'c'.repeat(64),
+ sizeBytes: 1024,
+ }),
+ ).toThrow(PluginProtocolError);
+ expect(() =>
+ parsePluginDownloadResponse({
+ url: 'https://example.com/plugin.cindy',
+ expiresAt: '0',
+ sha256: 'c'.repeat(64),
+ sizeBytes: 1024,
+ }),
+ ).toThrow(PluginProtocolError);
+ });
+
+ it('round-trips an opaque list cursor and rejects an empty cursor', () => {
+ const cursor = Buffer.from(JSON.stringify({ sortOrder: 7, id: 'plugin-1' })).toString(
+ 'base64url',
+ );
+ expect(
+ parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [],
+ nextCursor: cursor,
+ }).nextCursor,
+ ).toBe(cursor);
+ expect(() =>
+ parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [],
+ nextCursor: '',
+ }),
+ ).toThrow(PluginProtocolError);
+ });
+
+ it('rejects a detail manifest mismatch', () => {
+ expect(() =>
+ parseGetPluginResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugin: {
+ id: pluginId,
+ ghostId: validManifest.id,
+ name: validManifest.name,
+ description: null,
+ author: null,
+ scope: 'public',
+ organizationId: null,
+ defaultInstall: true,
+ currentRelease: {
+ id: 'release-1',
+ version: '2.0.0',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 1024,
+ publishedAt: '2026-07-19T00:00:00.000Z',
+ manifest: validManifest,
+ },
+ },
+ }),
+ ).toThrow(PluginProtocolError);
+ });
+
+ it('normalizes missing removals to an empty array', () => {
+ const legacy = parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [],
+ nextCursor: null,
+ });
+ expect(legacy.removals).toEqual([]);
+ const explicitNull = parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [],
+ nextCursor: null,
+ removals: null,
+ });
+ expect(explicitNull.removals).toEqual([]);
+ });
+
+ it('parses organization removal notices', () => {
+ const removal = {
+ pluginId: `c${'r'.repeat(24)}`,
+ ghostId: validManifest.id,
+ scope: 'organization',
+ organizationId: 'org-1',
+ action: 'purge',
+ removedAt: '2026-08-03T08:00:00.000Z',
+ } as const;
+ const response = parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [],
+ nextCursor: null,
+ removals: [removal],
+ });
+ expect(response.removals).toEqual([removal]);
+ });
+
+ it('skips removal notices with unknown actions while keeping known ones', () => {
+ const removal = {
+ pluginId: `c${'r'.repeat(24)}`,
+ ghostId: validManifest.id,
+ scope: 'organization',
+ organizationId: 'org-1',
+ action: 'purge',
+ removedAt: '2026-08-03T08:00:00.000Z',
+ } as const;
+ const response = parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [],
+ nextCursor: null,
+ removals: [{ ...removal, pluginId: `c${'d'.repeat(24)}`, action: 'disable' }, removal],
+ });
+ expect(response.removals).toEqual([removal]);
+ });
+
+ it('rejects malformed removal notices', () => {
+ const removal = {
+ pluginId: `c${'r'.repeat(24)}`,
+ ghostId: validManifest.id,
+ scope: 'organization',
+ organizationId: 'org-1',
+ action: 'purge',
+ removedAt: '2026-08-03T08:00:00.000Z',
+ } as const;
+ const withRemovals = (removals: unknown) => () =>
+ parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [],
+ nextCursor: null,
+ removals,
+ });
+ expect(withRemovals({})).toThrow(PluginProtocolError);
+ expect(withRemovals([{ ...removal, pluginId: 'INVALID' }])).toThrow(PluginProtocolError);
+ expect(withRemovals([{ ...removal, ghostId: 'Bad Ghost Id' }])).toThrow(PluginProtocolError);
+ expect(withRemovals([{ ...removal, organizationId: null }])).toThrow(PluginProtocolError);
+ expect(withRemovals([{ ...removal, scope: 'public' }])).toThrow(PluginProtocolError);
+ expect(withRemovals([{ ...removal, action: 42 }])).toThrow(PluginProtocolError);
+ // action 的结构形状是 1–64 字符:超长按坏帧拒绝,不落入"未知取值跳过"分支。
+ expect(withRemovals([{ ...removal, action: 'x'.repeat(65) }])).toThrow(PluginProtocolError);
+ // 动作未知但其余字段不合法的通告仍然整体拒绝:跳过只发生在结构校验通过之后。
+ expect(withRemovals([{ ...removal, action: 'disable', removedAt: 'soon' }])).toThrow(
+ PluginProtocolError,
+ );
+ });
+
+ it('rejects detail metadata that differs from its manifest', () => {
+ expect(() =>
+ parseGetPluginResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugin: {
+ id: pluginId,
+ ghostId: validManifest.id,
+ name: 'Stale name',
+ description: null,
+ author: null,
+ scope: 'public',
+ organizationId: null,
+ defaultInstall: true,
+ currentRelease: {
+ id: 'release-1',
+ version: validManifest.version,
+ sha256: 'a'.repeat(64),
+ sizeBytes: 1024,
+ publishedAt: '2026-07-19T00:00:00.000Z',
+ manifest: validManifest,
+ },
+ },
+ }),
+ ).toThrow(PluginProtocolError);
+ });
+});
diff --git a/packages/plugin-protocol/src/__tests__/manifest.test.ts b/packages/plugin-protocol/src/__tests__/manifest.test.ts
new file mode 100644
index 0000000000..4485d47944
--- /dev/null
+++ b/packages/plugin-protocol/src/__tests__/manifest.test.ts
@@ -0,0 +1,1484 @@
+import { describe, expect, it } from 'vitest';
+import {
+ GHOST_MANUAL_DESCRIPTION_MAX_CHARS,
+ GHOST_MANUAL_ENTRY_FILE,
+ GHOST_MANUAL_MAX_ITEMS,
+ GHOST_MANUAL_MD_MAX_BYTES,
+ GHOST_MANIFEST_SUMMARY_MAX_CHARS,
+ GHOST_MANIFEST_SCHEMA_VERSION,
+ GHOST_OAUTH_SCOPES_MAX,
+ compareCindyVersions,
+ ghostManifestUsesOidcToken,
+ isSafeGhostRelativePath,
+ isValidCindyVersion,
+ isValidGhostId,
+ isVersionlessCindyVersion,
+ supportsCindyVersion,
+ validateGhostManifest,
+} from '../manifest.js';
+
+const validManifest = {
+ schemaVersion: GHOST_MANIFEST_SCHEMA_VERSION,
+ id: 'acme-helper',
+ name: 'Acme Helper',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'index.js',
+ slots: ['tool'],
+ tools: [{ name: 'help', description: 'Help with Acme tasks' }],
+} as const;
+
+describe('Ghost manifest contract', () => {
+ it('exports the manual authoring limits', () => {
+ expect(GHOST_MANUAL_MAX_ITEMS).toBe(8);
+ expect(GHOST_MANUAL_ENTRY_FILE).toBe('MANUAL.md');
+ expect(GHOST_MANUAL_MD_MAX_BYTES).toBe(64 * 1024);
+ expect(GHOST_MANUAL_DESCRIPTION_MAX_CHARS).toBe(300);
+ });
+
+ it('accepts and normalizes a valid schema v2 manifest', () => {
+ const result = validateGhostManifest(validManifest);
+ expect(result).toEqual({ ok: true, manifest: validManifest });
+ });
+
+ it('keeps minCindyVersion optional for old plugins and validates declared versions', () => {
+ expect(validateGhostManifest(validManifest)).toEqual({ ok: true, manifest: validManifest });
+ expect(validateGhostManifest({ ...validManifest, minCindyVersion: '1.2.3' })).toEqual({
+ ok: true,
+ manifest: { ...validManifest, minCindyVersion: '1.2.3' },
+ });
+ for (const invalid of ['v1.2.3', '1.2', '01.2.3', '1.2.3-01', '']) {
+ expect(validateGhostManifest({ ...validManifest, minCindyVersion: invalid }).ok).toBe(false);
+ }
+ });
+
+ it('compares Cindy versions with SemVer precedence', () => {
+ expect(compareCindyVersions('1.2.3', '1.2.3')).toBe(0);
+ expect(compareCindyVersions('1.3.0', '1.2.9')).toBe(1);
+ expect(compareCindyVersions('1.2.3-beta.2', '1.2.3-beta.10')).toBe(-1);
+ expect(compareCindyVersions('1.2.3-999999999999999999', '1.2.3-1000000000000000000')).toBe(-1);
+ expect(compareCindyVersions('1.2.3', '1.2.3-rc.1')).toBe(1);
+ expect(compareCindyVersions('not-a-version', '1.2.3')).toBeNull();
+ expect(isValidCindyVersion('1.2.3')).toBe(true);
+ expect(isValidCindyVersion('v1.2.3')).toBe(false);
+ expect(isVersionlessCindyVersion('0.0.0-dev.1')).toBe(true);
+ expect(supportsCindyVersion('0.1.0', undefined)).toBe(true);
+ expect(supportsCindyVersion('0.0.0-dev.1', '99.0.0')).toBe(true);
+ expect(supportsCindyVersion('0.0.0-not valid', '1.0.0')).toBe(false);
+ expect(supportsCindyVersion('0.0.0-dev.1', 'not-a-version')).toBe(false);
+ expect(supportsCindyVersion('1.2.3', '1.2.3')).toBe(true);
+ expect(supportsCindyVersion('1.2.2', '1.2.3')).toBe(false);
+ expect(supportsCindyVersion('not-a-version', '1.2.3')).toBe(false);
+ });
+
+ it('rejects invalid ids and schema versions', () => {
+ expect(isValidGhostId('../escape')).toBe(false);
+ expect(validateGhostManifest({ ...validManifest, schemaVersion: 1 }).ok).toBe(false);
+ });
+
+ it('shares the 300-character limit across description and whenToUse', () => {
+ expect(GHOST_MANIFEST_SUMMARY_MAX_CHARS).toBe(300);
+ for (const field of ['description', 'whenToUse'] as const) {
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ [field]: 'x'.repeat(GHOST_MANIFEST_SUMMARY_MAX_CHARS),
+ }).ok,
+ ).toBe(true);
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ [field]: 'x'.repeat(GHOST_MANIFEST_SUMMARY_MAX_CHARS + 1),
+ }),
+ ).toEqual({
+ ok: false,
+ reason: `${field} 必须是 1–${GHOST_MANIFEST_SUMMARY_MAX_CHARS} 字符的非空字符串`,
+ });
+ }
+ });
+
+ it('accepts an oidc-token secret without a settings page and normalizes its exact host', () => {
+ const result = validateGhostManifest({
+ ...validManifest,
+ tools: undefined,
+ slots: ['network'],
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [
+ {
+ key: 'cindy_identity',
+ label: 'Cindy organization identity',
+ source: 'oidc-token',
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['API.EXAMPLE.COM'],
+ },
+ },
+ ],
+ },
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ manifest: expect.objectContaining({
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [
+ {
+ key: 'cindy_identity',
+ label: 'Cindy organization identity',
+ source: 'oidc-token',
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['api.example.com'],
+ },
+ },
+ ],
+ },
+ }),
+ });
+ expect(result.ok && ghostManifestUsesOidcToken(result.manifest)).toBe(true);
+ const baseline = validateGhostManifest(validManifest);
+ expect(baseline.ok && ghostManifestUsesOidcToken(baseline.manifest)).toBe(false);
+ });
+
+ it('rejects unsafe oidc-token declarations', () => {
+ const base = {
+ ...validManifest,
+ tools: undefined,
+ slots: ['network'],
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [
+ {
+ key: 'cindy_identity',
+ label: 'Cindy organization identity',
+ source: 'oidc-token',
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['api.example.com'],
+ },
+ },
+ ],
+ },
+ };
+ const secret = (patch: Record<string, unknown> = {}, hosts: string[] = base.network.hosts) => ({
+ ...base,
+ network: {
+ ...base.network,
+ hosts,
+ secrets: [{ ...base.network.secrets[0], ...patch }],
+ },
+ });
+
+ expect(
+ validateGhostManifest(
+ secret({
+ inject: { header: 'X-Identity', format: 'Bearer {value}', hosts: ['api.example.com'] },
+ }),
+ ),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('Authorization: Bearer') });
+ expect(
+ validateGhostManifest(
+ secret({
+ inject: { header: 'Authorization', format: 'Basic {value}' },
+ }),
+ ),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('Authorization: Bearer') });
+ expect(
+ validateGhostManifest(
+ secret(
+ {
+ inject: { header: 'Authorization', format: 'Bearer {value}', hosts: ['*.example.com'] },
+ },
+ ['*.example.com'],
+ ),
+ ),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('不允许通配') });
+ expect(
+ validateGhostManifest(
+ secret({
+ inject: { header: 'Authorization', format: 'Bearer {value}' },
+ }),
+ ),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('显式声明非空 inject.hosts') });
+ expect(validateGhostManifest(secret({ url: 'https://api.example.com/keys' }))).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('不允许声明 url'),
+ });
+ expect(validateGhostManifest(secret({ exchange: {} }))).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('不允许声明 exchange'),
+ });
+ expect(validateGhostManifest(secret({ oauth: {} }))).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('oauth 仅允许在 source: oauth'),
+ });
+ expect(
+ validateGhostManifest(
+ secret({
+ input: 'ghost',
+ }),
+ ),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('不允许标注 input') });
+ });
+
+ it('accepts a gh-cli secret with a settings-managed fallback token', () => {
+ const result = validateGhostManifest({
+ ...validManifest,
+ tools: undefined,
+ slots: ['network'],
+ settingsHtml: 'settings.html',
+ network: {
+ hosts: ['api.github.com', 'objects.githubusercontent.com'],
+ secrets: [
+ {
+ key: 'github_pat',
+ label: 'GitHub login',
+ source: 'gh-cli',
+ hint: 'The host prefers GitHub CLI and falls back to this token',
+ url: 'https://github.com/settings/tokens',
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['API.GITHUB.COM'],
+ },
+ },
+ ],
+ },
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ manifest: expect.objectContaining({
+ network: {
+ hosts: ['api.github.com', 'objects.githubusercontent.com'],
+ secrets: [
+ {
+ key: 'github_pat',
+ label: 'GitHub login',
+ source: 'gh-cli',
+ hint: 'The host prefers GitHub CLI and falls back to this token',
+ url: 'https://github.com/settings/tokens',
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['api.github.com'],
+ },
+ },
+ ],
+ },
+ }),
+ });
+ });
+
+ it('rejects unsafe gh-cli declarations', () => {
+ const base = {
+ ...validManifest,
+ tools: undefined,
+ slots: ['network'],
+ settingsHtml: 'settings.html',
+ network: {
+ hosts: ['api.github.com', 'uploads.github.com'],
+ secrets: [
+ {
+ key: 'github_pat',
+ label: 'GitHub login',
+ source: 'gh-cli',
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['api.github.com'],
+ },
+ },
+ ],
+ },
+ };
+ const secret = (patch: Record<string, unknown> = {}) => ({
+ ...base,
+ network: {
+ ...base.network,
+ secrets: [{ ...base.network.secrets[0], ...patch }],
+ },
+ });
+
+ expect(validateGhostManifest({ ...base, settingsHtml: undefined })).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('settingsHtml'),
+ });
+ expect(
+ validateGhostManifest(
+ secret({
+ inject: {
+ header: 'X-GitHub-Token',
+ format: 'Bearer {value}',
+ hosts: ['api.github.com'],
+ },
+ }),
+ ),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('Authorization: Bearer') });
+ expect(
+ validateGhostManifest(
+ secret({
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['api.github.com', 'uploads.github.com'],
+ },
+ }),
+ ),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('只能是 api.github.com') });
+ expect(
+ validateGhostManifest(
+ secret({
+ inject: { header: 'Authorization', format: 'Bearer {value}' },
+ }),
+ ),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('只能是 api.github.com') });
+ expect(validateGhostManifest(secret({ exchange: {} }))).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('不允许声明 exchange'),
+ });
+ expect(validateGhostManifest(secret({ oauth: {} }))).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('oauth 仅允许在 source: oauth'),
+ });
+ expect(validateGhostManifest(secret({ input: 'ghost' }))).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('不允许标注 input'),
+ });
+ });
+
+ it('accepts up to 256 OAuth scopes and rejects more', () => {
+ const withScopes = (count: number) =>
+ validateGhostManifest({
+ ...validManifest,
+ tools: undefined,
+ slots: ['network'],
+ settingsHtml: 'settings.html',
+ network: {
+ hosts: ['accounts.example.com'],
+ secrets: [
+ {
+ key: 'account',
+ label: 'Example account',
+ source: 'oauth',
+ inject: { header: 'Authorization', format: 'Bearer {value}' },
+ oauth: {
+ authorizeUrl: 'https://accounts.example.com/authorize',
+ tokenUrl: 'https://accounts.example.com/token',
+ scopes: Array.from({ length: count }, (_, index) => `scope:${index}`),
+ },
+ },
+ ],
+ },
+ });
+
+ expect(GHOST_OAUTH_SCOPES_MAX).toBe(256);
+ const accepted = withScopes(GHOST_OAUTH_SCOPES_MAX);
+ expect(accepted.ok).toBe(true);
+ expect(accepted.ok && accepted.manifest.network?.secrets?.[0]?.oauth?.scopes).toEqual(
+ Array.from({ length: GHOST_OAUTH_SCOPES_MAX }, (_, index) => `scope:${index}`),
+ );
+ expect(withScopes(GHOST_OAUTH_SCOPES_MAX + 1)).toEqual({
+ ok: false,
+ reason: 'network.secrets[].oauth.scopes 必须是 ≤256 条的数组',
+ });
+ });
+
+ it('preserves Desktop-supported OAuth client alternatives and identity avatar path', () => {
+ const result = validateGhostManifest({
+ ...validManifest,
+ tools: undefined,
+ slots: ['network'],
+ settingsHtml: 'settings.html',
+ network: {
+ hosts: ['accounts.example.com', 'api.example.com'],
+ secrets: [
+ {
+ key: 'account',
+ label: 'Example account',
+ source: 'oauth',
+ inject: { header: 'Authorization', format: 'Bearer {value}' },
+ oauth: {
+ authorizeUrl: 'https://accounts.example.com/authorize',
+ tokenUrl: 'https://accounts.example.com/token',
+ clientId: 'cn-client',
+ clientIdAlternatives: ['global-client'],
+ tokenBroker: 'example',
+ identity: {
+ url: 'https://api.example.com/me',
+ labelPath: 'data.user_id',
+ avatarPath: 'data.avatar_thumb',
+ },
+ },
+ },
+ ],
+ },
+ });
+
+ expect(result.ok).toBe(true);
+ expect(result.ok && result.manifest.network?.secrets?.[0]?.oauth).toMatchObject({
+ clientIdAlternatives: ['global-client'],
+ identity: { avatarPath: 'data.avatar_thumb' },
+ });
+ });
+
+ it('accepts and normalizes Plugin locale resource declarations', () => {
+ const locales = {
+ en: 'locales/en.json',
+ 'zh-CN': 'locales/zh-CN.json',
+ ja: 'locales/ja.json',
+ ko: 'locales/ko.json',
+ };
+ const result = validateGhostManifest({ ...validManifest, locales });
+
+ expect(result).toEqual({
+ ok: true,
+ manifest: { ...validManifest, locales },
+ });
+ });
+
+ it('rejects locale declarations without English fallback or with unsafe conflicts', () => {
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ locales: { ja: 'locales/ja.json' },
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('必须提供 en'),
+ });
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ locales: { en: 'index.js' },
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('以 .json 结尾'),
+ });
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ locales: { en: 'ghost.json' },
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('与插件其他声明文件'),
+ });
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ locales: {
+ en: 'locales/en.json',
+ ja: 'locales/EN.json',
+ },
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('重复路径'),
+ });
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ locales: {
+ en: 'a.json',
+ ja: 'a.json/child.json',
+ },
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('祖先路径冲突'),
+ });
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ locales: {
+ en: 'locales/en.json',
+ fr: 'locales/fr.json',
+ },
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('不支持的语言'),
+ });
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ slots: ['tool', 'skill'],
+ locales: { en: 'skills/helper.json' },
+ skill: {
+ items: [
+ {
+ dir: 'skills/helper.json',
+ name: 'helper',
+ description: 'Help with example tasks.',
+ },
+ ],
+ },
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('与插件其他声明文件'),
+ });
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ slots: ['tool', 'skill'],
+ locales: { en: 'skills/helper.json' },
+ skill: {
+ items: [
+ {
+ dir: 'skills/helper.json/subskill',
+ name: 'helper',
+ description: 'Help with example tasks.',
+ },
+ ],
+ },
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('与插件其他声明文件'),
+ });
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ slots: ['tool', 'skill'],
+ locales: { en: 'skills/helper/locales/en.json' },
+ skill: {
+ items: [
+ {
+ dir: 'skills/helper',
+ name: 'helper',
+ description: 'Help with example tasks.',
+ },
+ ],
+ },
+ }),
+ ).toMatchObject({
+ ok: true,
+ manifest: expect.objectContaining({
+ locales: { en: 'skills/helper/locales/en.json' },
+ }),
+ });
+ });
+
+ it('rejects locale and manual paths with either nesting direction', () => {
+ const validatePaths = (localePath: string, manualDir: string) =>
+ validateGhostManifest({
+ ...validManifest,
+ locales: { en: localePath },
+ manual: {
+ items: [{ dir: manualDir, name: 'guide', description: 'Manual guide.' }],
+ },
+ });
+
+ expect(validatePaths('content/en.json', 'content/en.json/manual')).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('与插件其他声明文件'),
+ });
+ expect(validatePaths('manual/docs/en.json', 'manual/docs')).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('与插件其他声明文件'),
+ });
+ expect(validatePaths('manual/en.json', 'manual/en.json')).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('与插件其他声明文件'),
+ });
+ expect(validatePaths('locales/en.json', 'manual/docs')).toMatchObject({
+ ok: true,
+ manifest: expect.objectContaining({
+ locales: { en: 'locales/en.json' },
+ manual: {
+ items: [{ dir: 'manual/docs', name: 'guide', description: 'Manual guide.' }],
+ },
+ }),
+ });
+ });
+
+ it('rejects Windows reserved device names in ids and relative paths', () => {
+ expect(isValidGhostId('con')).toBe(false);
+ expect(isValidGhostId('com1')).toBe(false);
+ expect(isSafeGhostRelativePath('CON.js')).toBe(false);
+ expect(isSafeGhostRelativePath('assets/AUX.html')).toBe(false);
+ expect(isSafeGhostRelativePath('assets/console.html')).toBe(true);
+ expect(validateGhostManifest({ ...validManifest, entry: 'assets/LPT9.js' }).ok).toBe(false);
+ });
+
+ it('rejects credential exchange URLs on non-default HTTPS ports', () => {
+ const result = validateGhostManifest({
+ ...validManifest,
+ settingsHtml: 'settings.html',
+ slots: ['network'],
+ tools: undefined,
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [
+ {
+ key: 'api_key',
+ label: 'API key',
+ inject: { header: 'Authorization', format: 'Bearer {value}' },
+ exchange: {
+ url: 'https://api.example.com:8443/token',
+ bodyFormat: '{"key":"{value}"}',
+ tokenPath: 'token',
+ },
+ },
+ ],
+ },
+ });
+
+ expect(result).toMatchObject({ ok: false });
+ if (!result.ok) expect(result.reason).toContain('仅支持 https 默认端口');
+ });
+
+ it('normalizes a representative full capability manifest', () => {
+ const result = validateGhostManifest({
+ schemaVersion: GHOST_MANIFEST_SCHEMA_VERSION,
+ id: 'full-helper',
+ name: 'Full Helper',
+ version: '2.0.0',
+ author: 'Cindy',
+ description: 'Exercises the shared manifest contract.',
+ whenToUse: 'Use for representative protocol validation.',
+ icon: 'assets/icon.png',
+ entry: 'src/main.js',
+ launch: 'resident',
+ settingsHtml: 'settings.html',
+ settingsHeight: 320,
+ slots: ['subscribe', 'tool', 'card', 'panel', 'cindy', 'network', 'notify', 'fs'],
+ tools: [
+ {
+ name: 'run_helper',
+ description: 'Run the helper.',
+ parameters: {
+ type: 'object',
+ properties: { input: { type: 'string' } },
+ required: ['input'],
+ },
+ },
+ ],
+ cindy: { image: ['generate'], video: ['edit'] },
+ subscribe: { topics: ['turn'], hooks: ['will-user-message'] },
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [
+ {
+ key: 'api_key',
+ label: 'API key',
+ inject: { header: 'Authorization', format: 'Bearer {value}' },
+ },
+ ],
+ },
+ command: 'full-helper',
+ keywords: ['full helper'],
+ panel: {
+ title: 'Full Helper',
+ html: 'panel.html',
+ position: 'right',
+ minWidth: 320,
+ defaultFraction: 0.2,
+ },
+ unknownField: 'ignored',
+ });
+
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.manifest.kind).toBe('chip');
+ expect(result.manifest.slots).toEqual([
+ 'subscribe',
+ 'tool',
+ 'card',
+ 'panel',
+ 'cindy',
+ 'network',
+ 'notify',
+ 'fs',
+ ]);
+ expect(result.manifest).not.toHaveProperty('unknownField');
+ });
+
+ it('accepts Desktop-supported badge and confirm slots while requiring a badge panel', () => {
+ const manifest = {
+ ...validManifest,
+ slots: ['tool', 'panel', 'badge', 'confirm'],
+ panel: { html: 'panel.html' },
+ } as const;
+
+ expect(validateGhostManifest(manifest)).toEqual({ ok: true, manifest });
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ slots: ['tool', 'badge'],
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('panel'),
+ });
+ });
+
+ it('accepts the taptap-maker style manifest with node/session-context/pick/preview slots', () => {
+ const result = validateGhostManifest({
+ schemaVersion: GHOST_MANIFEST_SCHEMA_VERSION,
+ id: 'taptap-maker',
+ name: 'TapTap Maker',
+ version: '2.0.0',
+ author: 'Cindy',
+ icon: 'assets/icon.png',
+ entry: 'main.js',
+ settingsHtml: 'settings.html',
+ settingsHeight: 760,
+ slots: ['tool', 'card', 'node', 'session-context', 'pick', 'preview', 'workspace'],
+ card: { externalLinks: true },
+ node: {
+ entry: 'node/maker-mcp.cjs',
+ entries: ['node/account.cjs', 'node/maker-child.cjs'],
+ protocol: 'mcp-stdio',
+ lifecycle: 'on-demand',
+ idleTimeoutSeconds: 600,
+ childSpawn: true,
+ },
+ preview: { hosts: ['maker.taptap.cn'] },
+ command: 'taptap-maker',
+ tools: [{ name: 'maker_status', description: 'Check Maker status' }],
+ });
+
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.manifest.slots).toEqual([
+ 'tool',
+ 'card',
+ 'node',
+ 'session-context',
+ 'pick',
+ 'preview',
+ 'workspace',
+ ]);
+ expect(result.manifest.node).toEqual({
+ entry: 'node/maker-mcp.cjs',
+ protocol: 'mcp-stdio',
+ lifecycle: 'on-demand',
+ idleTimeoutSeconds: 600,
+ entries: ['node/account.cjs', 'node/maker-child.cjs'],
+ childSpawn: true,
+ });
+ expect(result.manifest.preview).toEqual({ hosts: ['maker.taptap.cn'] });
+ expect(result.manifest.card).toEqual({ externalLinks: true });
+ });
+
+ it('round-trips the Host-owned ios-simulator slot with an explicit Cindy version floor', () => {
+ const manifest = {
+ ...validManifest,
+ id: 'simulator-workflow',
+ name: 'Simulator Workflow',
+ minCindyVersion: '1.2.3',
+ slots: ['ios-simulator'],
+ tools: undefined,
+ } as const;
+
+ const result = validateGhostManifest(JSON.parse(JSON.stringify(manifest)));
+
+ expect(result).toEqual({ ok: true, manifest });
+ });
+
+ it('rejects ios-simulator manifests that cannot be version-gated for older Hosts', () => {
+ const manifest = {
+ ...validManifest,
+ slots: ['ios-simulator'],
+ tools: undefined,
+ };
+
+ expect(validateGhostManifest(manifest)).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('minCindyVersion'),
+ });
+ expect(
+ validateGhostManifest({
+ ...manifest,
+ minCindyVersion: '1.2.3',
+ slots: ['ios-simulator-control'],
+ }),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('未知卡槽'),
+ });
+ });
+
+ it('enforces node slot / detail pairing and entry discipline', () => {
+ const base = {
+ ...validManifest,
+ slots: ['tool', 'node'],
+ };
+ expect(validateGhostManifest(base)).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('缺少 node 工作进程详单'),
+ });
+ const withNode = (node: Record<string, unknown>) => validateGhostManifest({ ...base, node });
+ expect(withNode({ entry: 'node/a.cjs', protocol: 'mcp-stdio', command: 'sh' })).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('不能声明 command/args/shell/env'),
+ });
+ expect(withNode({ entry: '../a.cjs', protocol: 'mcp-stdio' }).ok).toBe(false);
+ expect(withNode({ entry: 'index.js', protocol: 'mcp-stdio' })).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('不能与浏览器沙箱 entry'),
+ });
+ expect(withNode({ entry: 'node/a.cjs', protocol: 'bash' }).ok).toBe(false);
+ expect(
+ withNode({ entry: 'node/a.cjs', protocol: 'mcp-stdio', entries: ['node/a.cjs'] }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('不能重复主入口') });
+ // 大小写不敏感文件系统上的同名变体必须按同一个文件拒绝。
+ expect(withNode({ entry: 'Index.js', protocol: 'mcp-stdio' })).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('不能与浏览器沙箱 entry'),
+ });
+ expect(
+ withNode({ entry: 'node/a.cjs', protocol: 'mcp-stdio', entries: ['node/A.cjs'] }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('不能重复主入口') });
+ expect(
+ withNode({
+ entry: 'node/a.cjs',
+ protocol: 'mcp-stdio',
+ entries: ['node/b.cjs', 'node/B.cjs'],
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('重复入口') });
+ expect(
+ withNode({
+ entry: 'node/a.cjs',
+ protocol: 'mcp-stdio',
+ entries: ['node/b.cjs', 'node/b.cjs'],
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('重复入口') });
+ expect(
+ withNode({ entry: 'node/a.cjs', protocol: 'mcp-stdio', childSpawn: 'yes' }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('childSpawn 必须是布尔值') });
+ expect(
+ withNode({
+ entry: 'node/a.cjs',
+ protocol: 'mcp-stdio',
+ lifecycle: 'resident',
+ idleTimeoutSeconds: 60,
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('resident 时不能再声明') });
+ });
+
+ it('accepts and normalizes method-scoped Node secret bindings', () => {
+ const result = validateGhostManifest({
+ ...validManifest,
+ settingsHtml: 'settings.html',
+ slots: ['tool', 'node'],
+ node: {
+ entry: 'node/worker.cjs',
+ entries: ['node/secondary.cjs'],
+ protocol: 'json-rpc-stdio',
+ secretBindings: [
+ {
+ key: 'mail_code',
+ label: 'Mail authorization code',
+ methods: ['account/connect', 'mail/action'],
+ entry: 'node/secondary.cjs',
+ hint: 'Use the provider-generated authorization code',
+ url: 'https://mail.example.com/settings',
+ },
+ ],
+ },
+ });
+
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.manifest.node?.secretBindings).toEqual([
+ {
+ key: 'mail_code',
+ label: 'Mail authorization code',
+ methods: ['account/connect', 'mail/action'],
+ entry: 'node/secondary.cjs',
+ hint: 'Use the provider-generated authorization code',
+ url: 'https://mail.example.com/settings',
+ },
+ ]);
+ });
+
+ it('rejects unsafe Node secret bindings and shared credential-key collisions', () => {
+ const base = {
+ ...validManifest,
+ settingsHtml: 'settings.html',
+ slots: ['tool', 'node'],
+ node: {
+ entry: 'node/worker.cjs',
+ entries: ['node/secondary.cjs'],
+ protocol: 'json-rpc-stdio',
+ },
+ };
+ const binding = {
+ key: 'mail_code',
+ label: 'Mail authorization code',
+ methods: ['mail/action'],
+ };
+
+ expect(
+ validateGhostManifest({
+ ...base,
+ settingsHtml: undefined,
+ node: { ...base.node, secretBindings: [binding] },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('需要 settingsHtml') });
+ expect(
+ validateGhostManifest({
+ ...base,
+ node: { ...base.node, secretBindings: [{ ...binding, methods: ['bad method'] }] },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('安全方法名') });
+ expect(
+ validateGhostManifest({
+ ...base,
+ node: {
+ ...base.node,
+ protocol: 'mcp-stdio',
+ secretBindings: [{ ...binding, methods: ['initialize'] }],
+ },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('宿主保留的 MCP 方法') });
+ expect(
+ validateGhostManifest({
+ ...base,
+ node: {
+ ...base.node,
+ protocol: 'json-rpc-stdio',
+ secretBindings: [{ ...binding, methods: ['initialize'] }],
+ },
+ }).ok,
+ ).toBe(true);
+ expect(
+ validateGhostManifest({
+ ...base,
+ node: {
+ ...base.node,
+ secretBindings: [{ ...binding, entry: 'node/other.cjs' }],
+ },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('逐字命中') });
+ expect(
+ validateGhostManifest({
+ ...base,
+ node: { ...base.node, secretBindings: [binding, binding] },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('重复 key') });
+ expect(
+ validateGhostManifest({
+ ...base,
+ slots: ['tool', 'node', 'network'],
+ node: { ...base.node, secretBindings: [binding] },
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [
+ {
+ key: 'mail_code',
+ label: 'Duplicate key',
+ inject: { header: 'Authorization', format: 'Bearer {value}' },
+ },
+ ],
+ },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('与 node.secretBindings 撞名') });
+ expect(
+ validateGhostManifest({
+ ...base,
+ slots: ['tool', 'node', 'network'],
+ node: { ...base.node, secretBindings: [binding] },
+ network: {
+ hosts: [],
+ connections: [
+ {
+ key: 'mail_code',
+ label: 'Duplicate connection',
+ inject: { header: 'Authorization', format: 'Bearer {value}' },
+ },
+ ],
+ },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('与 node.secretBindings') });
+
+ for (const invalidBinding of [
+ { ...binding, key: 'Bad-Key' },
+ { ...binding, label: '' },
+ { ...binding, methods: [] },
+ { ...binding, methods: ['mail/action', 'mail/action'] },
+ { ...binding, hint: '' },
+ { ...binding, url: 'http://mail.example.com/settings' },
+ { ...binding, unexpected: true },
+ ]) {
+ expect(
+ validateGhostManifest({
+ ...base,
+ node: { ...base.node, secretBindings: [invalidBinding] },
+ }).ok,
+ JSON.stringify(invalidBinding),
+ ).toBe(false);
+ }
+ expect(
+ validateGhostManifest({
+ ...base,
+ node: { ...base.node, secretBindings: [] },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('1–4 条') });
+ expect(
+ validateGhostManifest({
+ ...base,
+ node: {
+ ...base.node,
+ secretBindings: Array.from({ length: 5 }, (_, index) => ({
+ ...binding,
+ key: `mail_code_${index}`,
+ })),
+ },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('1–4 条') });
+ });
+
+ it('enforces preview slot / hosts pairing and pattern rules', () => {
+ const base = { ...validManifest, slots: ['tool', 'preview'] };
+ expect(validateGhostManifest(base)).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('缺少 preview 详单'),
+ });
+ expect(validateGhostManifest({ ...base, preview: { hosts: [] } }).ok).toBe(false);
+ expect(
+ validateGhostManifest({ ...base, preview: { hosts: ['https://x.example.com'] } }).ok,
+ ).toBe(false);
+ expect(
+ validateGhostManifest({
+ ...base,
+ preview: { hosts: ['maker.taptap.cn', 'maker.taptap.cn'] },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('重复域名') });
+ expect(
+ validateGhostManifest({ ...validManifest, preview: { hosts: ['maker.taptap.cn'] } }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('未包含 "preview"') });
+ const loopback = validateGhostManifest({
+ ...base,
+ preview: { hosts: ['localhost', '*.taptap.cn'] },
+ });
+ expect(loopback.ok).toBe(true);
+ });
+
+ it('enforces skill slot / items pairing and shape rules', () => {
+ const base = { ...validManifest, slots: ['tool', 'skill'] };
+ const goodItems = [{ dir: 'skills/foo', name: 'foo', description: '教 Agent 用 foo' }];
+ // 有槽必有详单;有详单必有槽
+ expect(validateGhostManifest(base)).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('缺少 skill 详单'),
+ });
+ expect(validateGhostManifest({ ...validManifest, skill: { items: goodItems } })).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('未包含 "skill"'),
+ });
+ // 合法声明原样收录
+ const good = validateGhostManifest({ ...base, skill: { items: goodItems } });
+ expect(good).toMatchObject({ ok: true, manifest: { skill: { items: goodItems } } });
+ // items 形状:空/超限/非对象/自造字段一律拒
+ expect(validateGhostManifest({ ...base, skill: { items: [] } }).ok).toBe(false);
+ expect(validateGhostManifest({ ...base, skill: {} }).ok).toBe(false);
+ expect(validateGhostManifest({ ...base, skill: { items: goodItems, extra: 1 } }).ok).toBe(
+ false,
+ );
+ expect(
+ validateGhostManifest({
+ ...base,
+ skill: { items: [{ ...goodItems[0], scope: 'global' }] },
+ }).ok,
+ ).toBe(false);
+ const five = Array.from({ length: 5 }, (_, i) => ({
+ dir: `skills/s${i}`,
+ name: `s${i}`,
+ description: 'x',
+ }));
+ expect(validateGhostManifest({ ...base, skill: { items: five } })).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('最多 4 条'),
+ });
+ expect(validateGhostManifest({ ...base, skill: { items: five.slice(0, 4) } }).ok).toBe(true);
+ });
+
+ it('enforces skill item dir / name / description constraints and case-folded dedupe', () => {
+ const base = { ...validManifest, slots: ['tool', 'skill'] };
+ const item = (patch: Record<string, unknown>) =>
+ validateGhostManifest({
+ ...base,
+ skill: { items: [{ dir: 'skills/foo', name: 'foo', description: 'x', ...patch }] },
+ });
+ // dir:必须是包内安全相对路径
+ expect(item({ dir: '../evil' }).ok).toBe(false);
+ expect(item({ dir: '/abs/path' }).ok).toBe(false);
+ expect(item({ dir: 'skills\\foo' }).ok).toBe(false);
+ expect(item({ dir: 'skills/./foo' }).ok).toBe(false);
+ expect(item({ dir: '' }).ok).toBe(false);
+ // name:小写字母数字单连字符分段(链接名 <id>--<name> 的无歧义前提)
+ expect(item({ name: 'foo-bar' }).ok).toBe(true);
+ expect(item({ name: 'Foo' }).ok).toBe(false);
+ expect(item({ name: '-foo' }).ok).toBe(false);
+ expect(item({ name: 'foo-' }).ok).toBe(false);
+ expect(item({ name: 'foo--bar' }).ok).toBe(false);
+ expect(item({ name: '' }).ok).toBe(false);
+ expect(item({ name: 'a'.repeat(65) }).ok).toBe(false);
+ expect(item({ name: 'a'.repeat(64) }).ok).toBe(true);
+ // description:1–1024 非空
+ expect(item({ description: '' }).ok).toBe(false);
+ expect(item({ description: ' ' }).ok).toBe(false);
+ expect(item({ description: 'x'.repeat(1025) }).ok).toBe(false);
+ expect(item({ description: 'x'.repeat(1024) }).ok).toBe(true);
+ expect(item({ description: 42 }).ok).toBe(false);
+ // name/dir 大小写折叠去重(win32 文件系统折叠大小写)
+ expect(
+ validateGhostManifest({
+ ...base,
+ skill: {
+ items: [
+ { dir: 'skills/a', name: 'foo', description: 'x' },
+ { dir: 'skills/b', name: 'foo', description: 'y' },
+ ],
+ },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('重复 name') });
+ expect(
+ validateGhostManifest({
+ ...base,
+ skill: {
+ items: [
+ { dir: 'skills/A', name: 'foo', description: 'x' },
+ { dir: 'skills/a', name: 'bar', description: 'y' },
+ ],
+ },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('重复 dir') });
+ });
+
+ it('accepts a top-level manual index without requiring a slot', () => {
+ const items = [
+ {
+ dir: 'manual/getting-started',
+ name: 'getting-started',
+ description: '按需读取的入门工作流',
+ },
+ ];
+ const result = validateGhostManifest({ ...validManifest, manual: { items } });
+ expect(result).toMatchObject({
+ ok: true,
+ manifest: {
+ slots: ['tool'],
+ manual: { items },
+ },
+ });
+ });
+
+ it('enforces manual items shape, limits, and case-folded dedupe', () => {
+ const item = (patch: Record<string, unknown>) =>
+ validateGhostManifest({
+ ...validManifest,
+ manual: {
+ items: [
+ {
+ dir: 'manual/getting-started',
+ name: 'getting-started',
+ description: 'x',
+ ...patch,
+ },
+ ],
+ },
+ });
+
+ expect(validateGhostManifest({ ...validManifest, manual: { items: [] } }).ok).toBe(false);
+ expect(validateGhostManifest({ ...validManifest, manual: {} }).ok).toBe(false);
+ expect(validateGhostManifest({ ...validManifest, manual: { items: [], extra: true } }).ok).toBe(
+ false,
+ );
+ expect(item({ extra: true }).ok).toBe(false);
+ const nine = Array.from({ length: 9 }, (_, index) => ({
+ dir: `manual/unit-${index}`,
+ name: `unit-${index}`,
+ description: 'x',
+ }));
+ expect(validateGhostManifest({ ...validManifest, manual: { items: nine } })).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('最多 8 条'),
+ });
+
+ expect(item({ dir: '../manual' }).ok).toBe(false);
+ expect(item({ dir: 'manual\\guide' }).ok).toBe(false);
+ expect(item({ name: 'GettingStarted' }).ok).toBe(false);
+ expect(item({ name: 'getting--started' }).ok).toBe(false);
+ expect(item({ name: 'a'.repeat(65) }).ok).toBe(false);
+ expect(item({ name: 'a'.repeat(64) }).ok).toBe(true);
+ expect(item({ description: '' }).ok).toBe(false);
+ expect(item({ description: ' '.repeat(3) }).ok).toBe(false);
+ expect(item({ description: 'x'.repeat(301) }).ok).toBe(false);
+ expect(item({ description: 'x'.repeat(300) }).ok).toBe(true);
+
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ manual: {
+ items: [
+ { dir: 'manual/a', name: 'guide', description: 'x' },
+ { dir: 'manual/b', name: 'guide', description: 'y' },
+ ],
+ },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('重复 name') });
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ manual: {
+ items: [
+ { dir: 'manual/A', name: 'guide-a', description: 'x' },
+ { dir: 'manual/a', name: 'guide-b', description: 'y' },
+ ],
+ },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('重复 dir') });
+ });
+
+ it('intentionally allows nested manual item directories with distinct logical names', () => {
+ const items = [
+ { dir: 'manual', name: 'overview', description: 'Overview.' },
+ { dir: 'manual/advanced', name: 'advanced', description: 'Advanced topics.' },
+ ];
+
+ expect(validateGhostManifest({ ...validManifest, manual: { items } })).toMatchObject({
+ ok: true,
+ manifest: expect.objectContaining({ manual: { items } }),
+ });
+ });
+
+ it('rejects manual directories that contain or descend from declared file paths', () => {
+ const withManual = (manifest: Record<string, unknown>, dir: string) =>
+ validateGhostManifest({
+ ...manifest,
+ manual: { items: [{ dir, name: 'guide', description: 'Manual guide.' }] },
+ });
+ const declaredFileCases: Array<{
+ label: string;
+ manifest: Record<string, unknown>;
+ dir: string;
+ }> = [
+ { label: 'ghost.json', manifest: { ...validManifest }, dir: 'ghost.json' },
+ {
+ label: 'entry',
+ manifest: { ...validManifest, entry: 'manual/entry/main.js' },
+ dir: 'manual/entry',
+ },
+ {
+ label: 'icon',
+ manifest: { ...validManifest, icon: 'manual/icon/icon.png' },
+ dir: 'manual/icon',
+ },
+ {
+ label: 'settingsHtml',
+ manifest: { ...validManifest, settingsHtml: 'manual/settings/settings.html' },
+ dir: 'manual/settings',
+ },
+ {
+ label: 'panel.html',
+ manifest: {
+ ...validManifest,
+ slots: ['tool', 'panel'],
+ panel: { html: 'manual/panel/panel.html', position: 'tab' },
+ },
+ dir: 'manual/panel',
+ },
+ {
+ label: 'node.entry',
+ manifest: {
+ ...validManifest,
+ slots: ['tool', 'node'],
+ node: { entry: 'manual/node/main.cjs', protocol: 'mcp-stdio' },
+ },
+ dir: 'manual/node',
+ },
+ {
+ label: 'node.entries',
+ manifest: {
+ ...validManifest,
+ slots: ['tool', 'node'],
+ node: {
+ entry: 'node/main.cjs',
+ entries: ['manual/node-extra/child.cjs'],
+ protocol: 'mcp-stdio',
+ },
+ },
+ dir: 'manual/node-extra',
+ },
+ ];
+
+ for (const { label, manifest, dir } of declaredFileCases) {
+ expect(withManual(manifest, dir), label).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('与插件声明文件路径'),
+ });
+ }
+
+ expect(
+ withManual({ ...validManifest, entry: 'assets/main.js' }, 'assets/main.js/manual'),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('与插件声明文件路径'),
+ });
+ expect(
+ withManual({ ...validManifest, entry: 'Manual/Case/main.js' }, 'manual/case'),
+ ).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('与插件声明文件路径'),
+ });
+ expect(withManual({ ...validManifest, entry: 'src/main.js' }, 'manual/guide')).toMatchObject({
+ ok: true,
+ manifest: expect.objectContaining({
+ manual: {
+ items: [{ dir: 'manual/guide', name: 'guide', description: 'Manual guide.' }],
+ },
+ }),
+ });
+ });
+
+ it('validates card and agent capability details', () => {
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ slots: ['tool', 'card'],
+ card: { externalLinks: 'yes' },
+ }).ok,
+ ).toBe(false);
+ expect(
+ validateGhostManifest({ ...validManifest, card: { externalLinks: true } }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('未包含 "card"') });
+ const normalizedCard = validateGhostManifest({
+ ...validManifest,
+ slots: ['tool', 'card'],
+ card: { externalLinks: false },
+ });
+ expect(normalizedCard.ok).toBe(true);
+ if (normalizedCard.ok) expect(normalizedCard.manifest).not.toHaveProperty('card');
+
+ expect(
+ validateGhostManifest({
+ ...validManifest,
+ slots: ['tool', 'agent'],
+ agent: { background: false },
+ }),
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('background: true') });
+ const backgroundAgent = validateGhostManifest({
+ ...validManifest,
+ slots: ['tool', 'agent'],
+ agent: { background: true },
+ });
+ expect(backgroundAgent.ok).toBe(true);
+ if (backgroundAgent.ok) expect(backgroundAgent.manifest.agent).toEqual({ background: true });
+
+ for (const [capability, expected] of [
+ ['errand', { errand: true }],
+ ['schedule', { schedule: true }],
+ ] as const) {
+ const result = validateGhostManifest({
+ ...validManifest,
+ slots: ['tool', 'agent'],
+ agent: { [capability]: true },
+ });
+ expect(result.ok, capability).toBe(true);
+ if (result.ok) expect(result.manifest.agent).toEqual(expected);
+ }
+ });
+
+ it("panel.position 'tab' 合法;tab 时停靠专属字段(minWidth/defaultFraction)明确拒绝", () => {
+ const withPanel = (panel: Record<string, unknown>) => ({
+ ...validManifest,
+ slots: ['tool', 'panel'],
+ panel: { html: 'panel.html', ...panel },
+ });
+
+ const tab = validateGhostManifest(withPanel({ position: 'tab' }));
+ expect(tab.ok).toBe(true);
+ if (tab.ok) expect(tab.manifest.panel?.position).toBe('tab');
+
+ for (const extra of [{ minWidth: 240 }, { defaultFraction: 0.2 }]) {
+ const rejected = validateGhostManifest(withPanel({ position: 'tab', ...extra }));
+ expect(rejected.ok, JSON.stringify(extra)).toBe(false);
+ if (!rejected.ok) expect(rejected.reason).toContain('仅停靠形态');
+ }
+
+ // top/bottom 仍收词明确拒绝,野值仍拒。
+ const pending = validateGhostManifest(withPanel({ position: 'top' }));
+ expect(pending.ok).toBe(false);
+ if (!pending.ok) expect(pending.reason).toContain('暂未支持');
+ expect(validateGhostManifest(withPanel({ position: 'center' })).ok).toBe(false);
+ });
+});
+
+describe('cindy 详单:media/text/embed/search 类目与 oneshotModel 校验', () => {
+ const base = {
+ schemaVersion: GHOST_MANIFEST_SCHEMA_VERSION,
+ id: 'cindy-full',
+ name: 'Cindy Full',
+ version: '1.0.0',
+ entry: 'main.js',
+ slots: ['cindy'],
+ };
+
+ it('接受 media/text/embed 类目并保留', () => {
+ const r = validateGhostManifest({
+ ...base,
+ cindy: { media: ['deposit'], text: ['oneshot'], embed: ['text'] },
+ });
+ expect(r.ok, r.ok ? '' : String(r.reason)).toBe(true);
+ if (!r.ok) return;
+ expect(r.manifest.cindy).toEqual({ media: ['deposit'], text: ['oneshot'], embed: ['text'] });
+ });
+
+ it('text 与 embed 的动作集各归各(不接受串用)', () => {
+ expect(validateGhostManifest({ ...base, cindy: { text: ['text'] } }).ok).toBe(false);
+ expect(validateGhostManifest({ ...base, cindy: { embed: ['oneshot'] } }).ok).toBe(false);
+ });
+
+ it('接受 search.web 并要求真实工具声明', () => {
+ const manifest = {
+ ...base,
+ slots: ['cindy', 'tool'],
+ tools: [{ name: 'search_web', description: 'Search the public web' }],
+ cindy: { search: ['web'] },
+ };
+ const accepted = validateGhostManifest(manifest);
+ expect(accepted.ok, accepted.ok ? '' : String(accepted.reason)).toBe(true);
+ if (accepted.ok) expect(accepted.manifest.cindy).toEqual({ search: ['web'] });
+
+ expect(validateGhostManifest({ ...base, cindy: { search: ['web'] } }).ok).toBe(false);
+ expect(validateGhostManifest({ ...manifest, cindy: { search: ['deep'] } }).ok).toBe(false);
+ expect(validateGhostManifest({ ...manifest, cindy: { search: [] } }).ok).toBe(false);
+ expect(validateGhostManifest({ ...manifest, cindy: { search: ['web', 'web'] } }).ok).toBe(
+ false,
+ );
+ });
+
+ it('oneshotModel:合法声明落字段;形态非法 / 缺 text.oneshot 单挂 → 拒', () => {
+ const ok = validateGhostManifest({
+ ...base,
+ cindy: { text: ['oneshot'], oneshotModel: 'codex/gpt-5.5' },
+ });
+ expect(ok.ok, ok.ok ? '' : String(ok.reason)).toBe(true);
+ if (ok.ok)
+ expect(ok.manifest.cindy).toEqual({ text: ['oneshot'], oneshotModel: 'codex/gpt-5.5' });
+
+ for (const bad of [
+ { text: ['oneshot'], oneshotModel: '' },
+ { text: ['oneshot'], oneshotModel: ' ' },
+ { text: ['oneshot'], oneshotModel: 42 },
+ { text: ['oneshot'], oneshotModel: 'x'.repeat(129) },
+ { oneshotModel: 'codex/gpt-5.5' },
+ { image: ['generate'], oneshotModel: 'gpt-5.5' },
+ ]) {
+ const rejected = validateGhostManifest({ ...base, cindy: bad });
+ expect(rejected.ok, JSON.stringify(bad)).toBe(false);
+ }
+ });
+});
diff --git a/packages/plugin-protocol/src/__tests__/memberUpload.test.ts b/packages/plugin-protocol/src/__tests__/memberUpload.test.ts
new file mode 100644
index 0000000000..59a705c20a
--- /dev/null
+++ b/packages/plugin-protocol/src/__tests__/memberUpload.test.ts
@@ -0,0 +1,233 @@
+import { describe, expect, expectTypeOf, it } from 'vitest';
+
+import {
+ PLUGIN_MEMBER_RELEASE_REVIEW_STATUSES,
+ PLUGIN_MEMBER_UPLOAD_FAILURE_CODES,
+ PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES,
+ PLUGIN_MEMBER_UPLOAD_MAX_UNCOMPRESSED_BYTES,
+ PLUGIN_MEMBER_UPLOAD_MAX_ZIP_ENTRIES,
+ PLUGIN_MEMBER_UPLOAD_PUBLISH_SOURCE,
+ PLUGIN_MEMBER_UPLOAD_STATUSES,
+ parseCommitPluginMemberUploadRequest,
+ parseListMyPluginMemberReleasesResponse,
+ parsePluginMemberUploadStatusResponse,
+ parsePreparePluginMemberUploadRequest,
+ parsePreparePluginMemberUploadResponse,
+ type CommitPluginMemberUploadRequest,
+ type PreparePluginMemberUploadRequest,
+} from '../memberUpload.js';
+
+const SHA256 = 'a'.repeat(64);
+const NOW = '2026-08-09T03:00:00.000Z';
+const PLUGIN_ID = `c${'p'.repeat(24)}`;
+
+function succeededStatus() {
+ return {
+ uploadId: 'upload-1',
+ status: 'succeeded',
+ pluginId: PLUGIN_ID,
+ releaseId: 'release-1',
+ ghostId: 'release-helper',
+ version: '1.0.0',
+ reviewStatus: 'pending',
+ failure: null,
+ };
+}
+
+describe('member upload contract', () => {
+ it('exports the Forge package limits as the protocol authority', () => {
+ expect(PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES).toBe(128 * 1024 * 1024);
+ expect(PLUGIN_MEMBER_UPLOAD_MAX_UNCOMPRESSED_BYTES).toBe(256 * 1024 * 1024);
+ expect(PLUGIN_MEMBER_UPLOAD_MAX_ZIP_ENTRIES).toBe(2_048);
+ });
+
+ it('keeps source, task states, review states and asynchronous failures unique', () => {
+ expect(PLUGIN_MEMBER_UPLOAD_PUBLISH_SOURCE).toBe('member_upload');
+ expect(PLUGIN_MEMBER_UPLOAD_STATUSES).toEqual([
+ 'awaiting_upload',
+ 'validating',
+ 'publishing',
+ 'succeeded',
+ 'failed',
+ 'expired',
+ ]);
+ expect(PLUGIN_MEMBER_RELEASE_REVIEW_STATUSES).toEqual(['pending', 'approved', 'rejected']);
+ expect(new Set(PLUGIN_MEMBER_UPLOAD_FAILURE_CODES).size).toBe(
+ PLUGIN_MEMBER_UPLOAD_FAILURE_CODES.length,
+ );
+ });
+
+ it('validates prepare size/hash and rejects identity or package metadata overrides', () => {
+ expect(
+ parsePreparePluginMemberUploadRequest({
+ sizeBytes: PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES,
+ sha256: SHA256,
+ }),
+ ).toEqual({ sizeBytes: PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES, sha256: SHA256 });
+ expect(() =>
+ parsePreparePluginMemberUploadRequest({
+ sizeBytes: PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES + 1,
+ sha256: SHA256,
+ }),
+ ).toThrow(/sizeBytes/);
+ expect(() =>
+ parsePreparePluginMemberUploadRequest({
+ sizeBytes: 1,
+ sha256: SHA256.toUpperCase(),
+ }),
+ ).toThrow(/sha256/);
+ expect(() =>
+ parsePreparePluginMemberUploadRequest({
+ sizeBytes: 1,
+ sha256: SHA256,
+ organizationId: 'forged-org',
+ }),
+ ).toThrow(/organizationId/);
+ expect(parseCommitPluginMemberUploadRequest(undefined)).toEqual({});
+ expect(parseCommitPluginMemberUploadRequest({})).toEqual({});
+ expect(() => parseCommitPluginMemberUploadRequest({ ghostId: 'forged' })).toThrow(/ghostId/);
+ });
+
+ it('validates the private PUT ticket without weakening HTTPS or header safety', () => {
+ const response = {
+ uploadId: 'upload-1',
+ putUrl: 'https://uploads.example.test/private?signature=test',
+ headers: { 'content-type': 'application/octet-stream', 'x-oss-forbid-overwrite': 'true' },
+ expiresAt: NOW,
+ status: 'awaiting_upload',
+ };
+ expect(parsePreparePluginMemberUploadResponse(response)).toEqual(response);
+ expect(() =>
+ parsePreparePluginMemberUploadResponse({
+ ...response,
+ putUrl: 'http://uploads.example.test/private',
+ }),
+ ).toThrow(/HTTPS/);
+ expect(() =>
+ parsePreparePluginMemberUploadResponse({
+ ...response,
+ headers: { 'x-test': 'ok\r\nAuthorization: forged' },
+ }),
+ ).toThrow(/换行/);
+ });
+
+ it('keeps upload task status separate from Release review status', () => {
+ expect(parsePluginMemberUploadStatusResponse(succeededStatus())).toEqual(succeededStatus());
+ expect(
+ parsePluginMemberUploadStatusResponse({
+ uploadId: 'upload-2',
+ status: 'failed',
+ pluginId: null,
+ releaseId: null,
+ ghostId: null,
+ version: null,
+ reviewStatus: null,
+ failure: { code: 'PLUGIN_PACKAGE_INVALID', message: 'ghost.json 不合法' },
+ }).failure?.code,
+ ).toBe('PLUGIN_PACKAGE_INVALID');
+ expect(() =>
+ parsePluginMemberUploadStatusResponse({
+ ...succeededStatus(),
+ reviewStatus: null,
+ }),
+ ).toThrow(/审核状态/);
+ expect(() =>
+ parsePluginMemberUploadStatusResponse({
+ ...succeededStatus(),
+ status: 'failed',
+ failure: null,
+ reviewStatus: null,
+ }),
+ ).toThrow(/failure/);
+ });
+
+ it('rejects invalid ghost IDs in status and my-publishes responses', () => {
+ expect(() =>
+ parsePluginMemberUploadStatusResponse({
+ ...succeededStatus(),
+ ghostId: 'Bad Ghost Id',
+ }),
+ ).toThrow('response.ghostId 不合法');
+
+ expect(() =>
+ parseListMyPluginMemberReleasesResponse({
+ releases: [
+ {
+ ...succeededStatus(),
+ ghostId: 'con',
+ createdAt: NOW,
+ updatedAt: NOW,
+ },
+ ],
+ nextCursor: null,
+ }),
+ ).toThrow('response.releases[0].ghostId 不合法');
+ });
+
+ it('rejects invalid Plugin resource IDs in status and my-publishes responses', () => {
+ expect(() =>
+ parsePluginMemberUploadStatusResponse({
+ ...succeededStatus(),
+ pluginId: 'plugin-1',
+ }),
+ ).toThrow('response.pluginId 不合法');
+
+ expect(() =>
+ parseListMyPluginMemberReleasesResponse({
+ releases: [
+ {
+ ...succeededStatus(),
+ pluginId: 'plugin-1',
+ createdAt: NOW,
+ updatedAt: NOW,
+ },
+ ],
+ nextCursor: null,
+ }),
+ ).toThrow('response.releases[0].pluginId 不合法');
+ });
+
+ it('preserves top-level paths and reports nested my-publishes paths', () => {
+ expect(() =>
+ parsePluginMemberUploadStatusResponse({
+ ...succeededStatus(),
+ status: 'unknown',
+ }),
+ ).toThrow('response.status 不在成员上传状态集合中');
+
+ expect(() =>
+ parseListMyPluginMemberReleasesResponse({
+ releases: [
+ { ...succeededStatus(), createdAt: NOW, updatedAt: NOW },
+ { ...succeededStatus(), status: 'unknown', createdAt: NOW, updatedAt: NOW },
+ ],
+ nextCursor: null,
+ }),
+ ).toThrow('response.releases[1].status 不在成员上传状态集合中');
+ });
+
+ it('round-trips my-publishes timestamps and opaque cursor', () => {
+ const cursor = Buffer.from(JSON.stringify({ createdAt: NOW, uploadId: 'upload-1' })).toString(
+ 'base64url',
+ );
+ const response = {
+ releases: [{ ...succeededStatus(), createdAt: NOW, updatedAt: NOW }],
+ nextCursor: cursor,
+ };
+ expect(parseListMyPluginMemberReleasesResponse(response)).toEqual(response);
+ expect(() =>
+ parseListMyPluginMemberReleasesResponse({
+ ...response,
+ releases: [{ ...response.releases[0], updatedAt: 'tomorrow' }],
+ }),
+ ).toThrow(/updatedAt/);
+ });
+
+ it('exports request types that cannot carry actor identity', () => {
+ expectTypeOf<PreparePluginMemberUploadRequest>().toEqualTypeOf<{
+ sizeBytes: number;
+ sha256: string;
+ }>();
+ expectTypeOf<CommitPluginMemberUploadRequest>().toEqualTypeOf<Record<string, never>>();
+ });
+});
diff --git a/packages/plugin-protocol/src/__tests__/memberUploadExports.test.ts b/packages/plugin-protocol/src/__tests__/memberUploadExports.test.ts
new file mode 100644
index 0000000000..d1b94e251f
--- /dev/null
+++ b/packages/plugin-protocol/src/__tests__/memberUploadExports.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+
+import { PluginProtocolError as DeliveryPluginProtocolError } from '@cindy/plugin-protocol/delivery';
+import {
+ PluginProtocolError as MemberUploadPluginProtocolError,
+ parsePluginMemberUploadStatusResponse,
+} from '@cindy/plugin-protocol/member-upload';
+
+describe('member-upload public subpath', () => {
+ it('re-exports the shared PluginProtocolError class identity', () => {
+ expect(MemberUploadPluginProtocolError).toBe(DeliveryPluginProtocolError);
+
+ expect(() => parsePluginMemberUploadStatusResponse(null)).toThrow(
+ MemberUploadPluginProtocolError,
+ );
+ });
+});
diff --git a/packages/plugin-protocol/src/delivery.ts b/packages/plugin-protocol/src/delivery.ts
new file mode 100644
index 0000000000..6a631ca627
--- /dev/null
+++ b/packages/plugin-protocol/src/delivery.ts
@@ -0,0 +1,432 @@
+import {
+ ghostManifestUsesOidcToken,
+ isValidGhostId,
+ validateGhostManifest,
+ type GhostManifest,
+} from './manifest.js';
+import {
+ PluginProtocolError,
+ httpsUrl,
+ isoDate,
+ nextCursor,
+ object,
+ sha256,
+ string,
+} from './internal/parse.js';
+import { isValidPluginResourceId } from './internal/pluginResourceId.js';
+
+export { PluginProtocolError } from './internal/parse.js';
+export { isValidPluginResourceId } from './internal/pluginResourceId.js';
+
+/** Plugin 客户端 HTTP list/detail envelope 版本;与 ghost.json 版本独立演进。 */
+export const PLUGIN_API_SCHEMA_VERSION = 2 as const;
+
+/** 客户端请求 Plugin Server 时携带的 Cindy 版本请求头。 */
+export const CINDY_CLIENT_VERSION_HEADER = 'x-cindy-version' as const;
+
+/** 普通客户端可见的 Plugin 来源范围。 */
+export const PLUGIN_SCOPES = ['public', 'organization', 'personal'] as const;
+
+/** `public` 对所有已登录身份可见;其余范围只对对应组织或自然人可见。 */
+export type PluginScope = (typeof PLUGIN_SCOPES)[number];
+
+/** 服务端为当前客户端选择的 Release 图标元数据;URL 为短期授权地址。 */
+export interface PluginIconMetadata {
+ /** 图标 MIME 类型,例如 image/png 或 image/svg+xml。 */
+ mimeType: string;
+ /** 图标对象的 SHA-256,固定为 64 位小写十六进制。 */
+ sha256: string;
+ /** 图标原始字节数,恒为正整数。 */
+ sizeBytes: number;
+ /** 短期 HTTPS 图标下载地址。 */
+ url: string;
+ /** 图标地址过期时间,格式为带毫秒的 UTC ISO 8601。 */
+ expiresAt: string;
+}
+
+/** 列表和详情共用的客户端兼容 Release 摘要。 */
+export interface PluginReleaseSummary {
+ /** plugin-server 生成的 Release 资源 ID;调用方应将其视为不透明字符串。 */
+ id: string;
+ /** 与该 Release 的 `manifest.version` 一致。 */
+ version: string;
+ /** `.cindy` 原始字节的 SHA-256,固定为 64 位小写十六进制。 */
+ sha256: string;
+ /** `.cindy` 原始字节数,恒为正整数。 */
+ sizeBytes: number;
+ /** Release 发布时间,格式为带毫秒的 UTC ISO 8601。 */
+ publishedAt: string;
+ /** 发布时从包内提取并单独存储的图标;未声明图标时为 null。 */
+ icon: PluginIconMetadata | null;
+}
+
+/** 详情响应中的客户端兼容 Release;在摘要基础上包含已校验的完整 manifest。 */
+export interface PluginReleaseDetail extends PluginReleaseSummary {
+ /** 已通过 `validateGhostManifest` 规范化的当前 manifest。 */
+ manifest: GhostManifest;
+}
+
+/** Plugin 列表项;只含市场展示和版本对账所需的摘要。 */
+export interface VisiblePluginSummary {
+ /** plugin-server 生成的永久资源 ID,也是客户端管理安装实例的主键。 */
+ id: string;
+ /** 包内 `ghost.json.id`;跨不同来源允许重名,不能代替 `id`。 */
+ ghostId: string;
+ /** 客户端兼容 Release manifest 的展示名。 */
+ name: string;
+ /** 客户端兼容 Release manifest 的描述;未声明时为 `null`。 */
+ description: string | null;
+ /** 客户端兼容 Release manifest 的作者;未声明时为 `null`。 */
+ author: string | null;
+ /** Plugin 的来源范围。 */
+ scope: PluginScope;
+ /** Organization 必须是非空组织 ID;Public 和 Personal 恒为 `null`。 */
+ organizationId: string | null;
+ /** 对当前请求身份计算后的默认安装值,不表示强制安装或强制启用。 */
+ defaultInstall: boolean;
+ /** 服务端为该客户端选择的 Release;优先 current,不兼容时回退到历史兼容版本。 */
+ currentRelease: PluginReleaseSummary;
+}
+
+/** Plugin 详情;展示字段必须与 `currentRelease.manifest` 保持一致。 */
+export interface VisiblePluginDetail {
+ /** plugin-server 生成的永久资源 ID,也是客户端管理安装实例的主键。 */
+ id: string;
+ /** 包内 `ghost.json.id`;跨不同来源允许重名,不能代替 `id`。 */
+ ghostId: string;
+ /** 客户端兼容 Release manifest 的展示名。 */
+ name: string;
+ /** 客户端兼容 Release manifest 的描述;未声明时为 `null`。 */
+ description: string | null;
+ /** 客户端兼容 Release manifest 的作者;未声明时为 `null`。 */
+ author: string | null;
+ /** Plugin 的来源范围。 */
+ scope: PluginScope;
+ /** Organization 必须是非空组织 ID;Public 和 Personal 恒为 `null`。 */
+ organizationId: string | null;
+ /** 对当前请求身份计算后的默认安装值,不表示强制安装或强制启用。 */
+ defaultInstall: boolean;
+ /** 服务端为该客户端选择的 Release,包含完整 manifest。 */
+ currentRelease: PluginReleaseDetail;
+}
+
+/** 清理通告支持的处置动作;解析器会跳过动作未知的通告(未来扩展位)。 */
+export const PLUGIN_REMOVAL_ACTIONS = ['purge'] as const;
+
+/** `purge` 表示删除本地已安装副本及插件本地数据。 */
+export type PluginRemovalAction = (typeof PLUGIN_REMOVAL_ACTIONS)[number];
+
+/** 曾上架、现已下架并被要求处置本地副本的 Plugin 的清理通告。 */
+export interface PluginRemovalNotice {
+ /** 被清理 Plugin 的永久资源 ID;客户端据此匹配本地安装记录并跨分页去重。 */
+ pluginId: string;
+ /** 通告对应的 `ghost.json.id` 快照;供客户端双重校验,不能代替 `pluginId`。 */
+ ghostId: string;
+ /** 被清理 Plugin 的来源范围;当前服务端只对 organization 下发通告。 */
+ scope: PluginScope;
+ /** Organization 必须是非空组织 ID;Public 和 Personal 恒为 `null`。 */
+ organizationId: string | null;
+ /** 处置动作。 */
+ action: PluginRemovalAction;
+ /** 最近一次下架时间;重新上架再下架会刷新,消费方不得假设单调。 */
+ removedAt: string;
+}
+
+/** Plugin 分页列表响应。 */
+export interface ListPluginsResponse {
+ /** Plugin HTTP envelope 版本。 */
+ schemaVersion: typeof PLUGIN_API_SCHEMA_VERSION;
+ /** 当前页内对请求身份可见的 Plugin 摘要。 */
+ plugins: VisiblePluginSummary[];
+ /** 下一页使用的不透明游标;调用方只可原样回传,没有下一页时为 `null`。 */
+ nextCursor: string | null;
+ /** 对请求身份可见的清理通告;服务端每页重复完整下发,缺失时规范化为空数组。 */
+ removals: PluginRemovalNotice[];
+}
+
+/** 单个 Plugin 详情响应。 */
+export interface GetPluginResponse {
+ /** Plugin HTTP envelope 版本。 */
+ schemaVersion: typeof PLUGIN_API_SCHEMA_VERSION;
+ /** 当前身份可见且处于 active 状态的 Plugin 详情。 */
+ plugin: VisiblePluginDetail;
+}
+
+/** 当前 Release 的短期私有下载凭证;不重复携带 HTTP envelope 版本。 */
+export interface PluginDownloadResponse {
+ /** 短期 HTTPS 下载地址。 */
+ url: string;
+ /** 下载地址过期时间,格式为带毫秒的 UTC ISO 8601。 */
+ expiresAt: string;
+ /** 必须与客户端准备下载的当前 Release 摘要一致。 */
+ sha256: string;
+ /** 必须与客户端准备下载的当前 Release 摘要一致。 */
+ sizeBytes: number;
+}
+
+function parseIconMetadata(value: unknown, path: string): PluginIconMetadata | null {
+ // 老的 v2 服务端尚未提供 icon 字段时,客户端继续使用本地兜底图标。
+ if (value === null || value === undefined) return null;
+ const raw = object(value, path);
+ const mimeType = string(raw.mimeType, `${path}.mimeType`, 128);
+ if (!/^image\/[a-z0-9.+-]+$/i.test(mimeType)) {
+ throw new PluginProtocolError(`${path}.mimeType 必须是 image/* MIME 类型`);
+ }
+ if (
+ typeof raw.sizeBytes !== 'number' ||
+ !Number.isSafeInteger(raw.sizeBytes) ||
+ raw.sizeBytes <= 0
+ ) {
+ throw new PluginProtocolError(`${path}.sizeBytes 必须是正整数`);
+ }
+ return {
+ mimeType,
+ sha256: sha256(raw.sha256, `${path}.sha256`),
+ sizeBytes: raw.sizeBytes,
+ url: httpsUrl(raw.url, `${path}.url`),
+ expiresAt: isoDate(raw.expiresAt, `${path}.expiresAt`),
+ };
+}
+
+function parseReleaseSummary(value: unknown, path: string): PluginReleaseSummary {
+ const raw = object(value, path);
+ const version = string(raw.version, `${path}.version`, 32);
+ if (
+ typeof raw.sizeBytes !== 'number' ||
+ !Number.isSafeInteger(raw.sizeBytes) ||
+ raw.sizeBytes <= 0
+ ) {
+ throw new PluginProtocolError(`${path}.sizeBytes 必须是正整数`);
+ }
+ return {
+ id: string(raw.id, `${path}.id`, 128),
+ version,
+ sha256: sha256(raw.sha256, `${path}.sha256`),
+ sizeBytes: raw.sizeBytes,
+ publishedAt: isoDate(raw.publishedAt, `${path}.publishedAt`),
+ icon: parseIconMetadata(raw.icon, `${path}.icon`),
+ };
+}
+
+function parseReleaseDetail(value: unknown, ghostId: string, path: string): PluginReleaseDetail {
+ const raw = object(value, path);
+ const summary = parseReleaseSummary(raw, path);
+ const validatedManifest = validateGhostManifest(raw.manifest);
+ if (!validatedManifest.ok) {
+ throw new PluginProtocolError(`${path}.manifest 不合法: ${validatedManifest.reason}`);
+ }
+ if (validatedManifest.manifest.id !== ghostId) {
+ throw new PluginProtocolError(`${path}.manifest.id 与 ghostId 不一致`);
+ }
+ if (summary.version !== validatedManifest.manifest.version) {
+ throw new PluginProtocolError(`${path}.version 与 manifest.version 不一致`);
+ }
+ return { ...summary, manifest: validatedManifest.manifest };
+}
+
+function parseScope(value: unknown, path: string): PluginScope {
+ if (!(PLUGIN_SCOPES as readonly unknown[]).includes(value)) {
+ throw new PluginProtocolError(`${path}.scope 不合法`);
+ }
+ return value as PluginScope;
+}
+
+function parseScopedOrganizationId(
+ scope: PluginScope,
+ value: unknown,
+ path: string,
+): string | null {
+ if (
+ ((scope === 'public' || scope === 'personal') && value !== null) ||
+ (scope === 'organization' && (typeof value !== 'string' || value.length === 0))
+ ) {
+ throw new PluginProtocolError(`${path}.organizationId 与 scope 不一致`);
+ }
+ return value as string | null;
+}
+
+function parseVisiblePluginBase(
+ value: unknown,
+ path: string,
+): {
+ raw: Record<string, unknown>;
+ id: string;
+ ghostId: string;
+ name: string;
+ description: string | null;
+ author: string | null;
+ scope: PluginScope;
+ organizationId: string | null;
+ defaultInstall: boolean;
+} {
+ const raw = object(value, path);
+ if (!isValidPluginResourceId(raw.id)) throw new PluginProtocolError(`${path}.id 不合法`);
+ if (!isValidGhostId(raw.ghostId)) throw new PluginProtocolError(`${path}.ghostId 不合法`);
+ const scope = parseScope(raw.scope, path);
+ const organizationId = parseScopedOrganizationId(scope, raw.organizationId, path);
+ if (typeof raw.defaultInstall !== 'boolean') {
+ throw new PluginProtocolError(`${path}.defaultInstall 必须是 boolean`);
+ }
+ return {
+ raw,
+ id: raw.id,
+ ghostId: raw.ghostId,
+ name: string(raw.name, `${path}.name`),
+ description:
+ raw.description === null ? null : string(raw.description, `${path}.description`, 300),
+ author: raw.author === null ? null : string(raw.author, `${path}.author`),
+ scope,
+ organizationId,
+ defaultInstall: raw.defaultInstall,
+ };
+}
+
+function parseVisiblePluginSummary(value: unknown, index: number): VisiblePluginSummary {
+ const path = `plugins[${index}]`;
+ const parsed = parseVisiblePluginBase(value, path);
+ return {
+ id: parsed.id,
+ ghostId: parsed.ghostId,
+ name: parsed.name,
+ description: parsed.description,
+ author: parsed.author,
+ scope: parsed.scope,
+ organizationId: parsed.organizationId,
+ defaultInstall: parsed.defaultInstall,
+ currentRelease: parseReleaseSummary(parsed.raw.currentRelease, `${path}.currentRelease`),
+ };
+}
+
+function parseVisiblePluginDetail(value: unknown, path: string): VisiblePluginDetail {
+ const parsed = parseVisiblePluginBase(value, path);
+ const currentRelease = parseReleaseDetail(
+ parsed.raw.currentRelease,
+ parsed.ghostId,
+ `${path}.currentRelease`,
+ );
+ if (ghostManifestUsesOidcToken(currentRelease.manifest) && parsed.scope !== 'organization') {
+ throw new PluginProtocolError(
+ `${path}.currentRelease.manifest 的 oidc-token 仅允许 organization scope`,
+ );
+ }
+ const manifestDescription = currentRelease.manifest.description ?? null;
+ const manifestAuthor = currentRelease.manifest.author ?? null;
+ if (parsed.name !== currentRelease.manifest.name) {
+ throw new PluginProtocolError(`${path}.name 与 currentRelease.manifest.name 不一致`);
+ }
+ if (parsed.description !== manifestDescription) {
+ throw new PluginProtocolError(
+ `${path}.description 与 currentRelease.manifest.description 不一致`,
+ );
+ }
+ if (parsed.author !== manifestAuthor) {
+ throw new PluginProtocolError(`${path}.author 与 currentRelease.manifest.author 不一致`);
+ }
+ return {
+ id: parsed.id,
+ ghostId: parsed.ghostId,
+ name: parsed.name,
+ description: parsed.description,
+ author: parsed.author,
+ scope: parsed.scope,
+ organizationId: parsed.organizationId,
+ defaultInstall: parsed.defaultInstall,
+ currentRelease,
+ };
+}
+
+function parseRemovalNotice(value: unknown, path: string): PluginRemovalNotice | null {
+ const raw = object(value, path);
+ if (!isValidPluginResourceId(raw.pluginId)) {
+ throw new PluginProtocolError(`${path}.pluginId 不合法`);
+ }
+ if (!isValidGhostId(raw.ghostId)) throw new PluginProtocolError(`${path}.ghostId 不合法`);
+ const scope = parseScope(raw.scope, path);
+ const organizationId = parseScopedOrganizationId(scope, raw.organizationId, path);
+ const action = string(raw.action, `${path}.action`, 64);
+ const removedAt = isoDate(raw.removedAt, `${path}.removedAt`);
+ // 未知动作是未来扩展位:结构校验通过后跳过该条而不是拒绝整个响应,
+ // 这样服务端新增动作不会打挂旧客户端的整轮列表解析。
+ if (!(PLUGIN_REMOVAL_ACTIONS as readonly string[]).includes(action)) return null;
+ return {
+ pluginId: raw.pluginId,
+ ghostId: raw.ghostId,
+ scope,
+ organizationId,
+ action: action as PluginRemovalAction,
+ removedAt,
+ };
+}
+
+function parseRemovals(value: unknown): PluginRemovalNotice[] {
+ // 老的 v2 服务端或未携带通告的身份不带该字段;缺失时规范化为空数组。
+ if (value === null || value === undefined) return [];
+ if (!Array.isArray(value)) throw new PluginProtocolError('response.removals 必须是数组');
+ const notices: PluginRemovalNotice[] = [];
+ value.forEach((entry, index) => {
+ const notice = parseRemovalNotice(entry, `removals[${index}]`);
+ if (notice) notices.push(notice);
+ });
+ return notices;
+}
+
+/**
+ * 解析并规范化 Plugin 分页列表响应。
+ *
+ * 未知字段会被忽略;已知字段缺失、值不合法或 schema 版本不支持时抛出
+ * `PluginProtocolError`。`removals` 缺失时规范化为空数组,动作未知的通告
+ * 会被跳过而不影响其余内容。
+ */
+export function parseListPluginsResponse(value: unknown): ListPluginsResponse {
+ const raw = object(value, 'response');
+ if (raw.schemaVersion !== PLUGIN_API_SCHEMA_VERSION) {
+ throw new PluginProtocolError(`response.schemaVersion 必须为 ${PLUGIN_API_SCHEMA_VERSION}`);
+ }
+ if (!Array.isArray(raw.plugins)) throw new PluginProtocolError('response.plugins 必须是数组');
+ return {
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: raw.plugins.map(parseVisiblePluginSummary),
+ nextCursor: nextCursor(raw.nextCursor, 'response.nextCursor'),
+ removals: parseRemovals(raw.removals),
+ };
+}
+
+/**
+ * 解析并规范化单个 Plugin 详情响应。
+ *
+ * 除通用字段校验外,还要求 manifest 的 id、version 和展示字段与外层数据一致。
+ * 校验失败时抛出 `PluginProtocolError`。
+ */
+export function parseGetPluginResponse(value: unknown): GetPluginResponse {
+ const raw = object(value, 'response');
+ if (raw.schemaVersion !== PLUGIN_API_SCHEMA_VERSION) {
+ throw new PluginProtocolError(`response.schemaVersion 必须为 ${PLUGIN_API_SCHEMA_VERSION}`);
+ }
+ return {
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugin: parseVisiblePluginDetail(raw.plugin, 'response.plugin'),
+ };
+}
+
+/**
+ * 解析并规范化当前 Release 的短期下载凭证。
+ *
+ * 只接受 HTTPS URL、UTC 时间、合法 SHA-256 和正整数文件大小;校验失败时抛出
+ * `PluginProtocolError`。
+ */
+export function parsePluginDownloadResponse(value: unknown): PluginDownloadResponse {
+ const raw = object(value, 'response');
+ if (
+ typeof raw.sizeBytes !== 'number' ||
+ !Number.isSafeInteger(raw.sizeBytes) ||
+ raw.sizeBytes <= 0
+ ) {
+ throw new PluginProtocolError('response.sizeBytes 必须是正整数');
+ }
+ return {
+ url: httpsUrl(raw.url, 'response.url'),
+ expiresAt: isoDate(raw.expiresAt, 'response.expiresAt'),
+ sha256: sha256(raw.sha256, 'response.sha256'),
+ sizeBytes: raw.sizeBytes,
+ };
+}
diff --git a/packages/plugin-protocol/src/index.ts b/packages/plugin-protocol/src/index.ts
new file mode 100644
index 0000000000..cead9581a7
--- /dev/null
+++ b/packages/plugin-protocol/src/index.ts
@@ -0,0 +1,3 @@
+export * from './manifest.js';
+export * from './delivery.js';
+export * from './memberUpload.js';
diff --git a/packages/plugin-protocol/src/internal/parse.ts b/packages/plugin-protocol/src/internal/parse.ts
new file mode 100644
index 0000000000..68a55ce6ae
--- /dev/null
+++ b/packages/plugin-protocol/src/internal/parse.ts
@@ -0,0 +1,67 @@
+/** plugin-protocol 包内共享的响应解析原语;仅供包内模块使用,不进入对外导出面。 */
+
+/** Plugin HTTP 响应违反共享契约时由解析器抛出的错误。 */
+export class PluginProtocolError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'PluginProtocolError';
+ }
+}
+
+export function object(value: unknown, path: string): Record<string, unknown> {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new PluginProtocolError(`${path} 必须是对象`);
+ }
+ return value as Record<string, unknown>;
+}
+
+export function string(value: unknown, path: string, max = 256): string {
+ if (typeof value !== 'string' || value.length === 0 || value.length > max) {
+ throw new PluginProtocolError(`${path} 必须是 1–${max} 字符的字符串`);
+ }
+ return value;
+}
+
+export function isoDate(value: unknown, path: string): string {
+ const text = string(value, path, 64);
+ const parsed = new Date(text);
+ if (
+ !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(text) ||
+ Number.isNaN(parsed.getTime()) ||
+ parsed.toISOString() !== text
+ ) {
+ throw new PluginProtocolError(`${path} 必须是 ISO 8601 UTC 时间`);
+ }
+ return text;
+}
+
+export function sha256(value: unknown, path: string): string {
+ const text = string(value, path, 64);
+ if (!/^[a-f0-9]{64}$/.test(text)) {
+ throw new PluginProtocolError(`${path} 必须是 64 位小写十六进制`);
+ }
+ return text;
+}
+
+export function httpsUrl(value: unknown, path: string, max = 8_192): string {
+ const text = string(value, path, max);
+ let parsed: URL;
+ try {
+ parsed = new URL(text);
+ } catch {
+ throw new PluginProtocolError(`${path} 必须是 HTTPS URL`);
+ }
+ if (parsed.protocol !== 'https:') {
+ throw new PluginProtocolError(`${path} 必须是 HTTPS URL`);
+ }
+ return text;
+}
+
+/** 列表接口的不透明分页游标:非空、有界,客户端原样回传,不解析内部结构。 */
+export function nextCursor(value: unknown, path: string): string | null {
+ if (value === null) return null;
+ if (typeof value !== 'string' || value.length === 0 || value.length > 4_096) {
+ throw new PluginProtocolError(`${path} 必须是 1–4096 字符的字符串或 null`);
+ }
+ return value;
+}
diff --git a/packages/plugin-protocol/src/internal/pluginResourceId.ts b/packages/plugin-protocol/src/internal/pluginResourceId.ts
new file mode 100644
index 0000000000..f88401038d
--- /dev/null
+++ b/packages/plugin-protocol/src/internal/pluginResourceId.ts
@@ -0,0 +1,4 @@
+/** 判断值是否符合 plugin-server 当前使用的 Plugin 资源 ID 形状。 */
+export function isValidPluginResourceId(value: unknown): value is string {
+ return typeof value === 'string' && /^c[a-z0-9]{24}$/.test(value);
+}
diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.ts
new file mode 100644
index 0000000000..0d31815420
--- /dev/null
+++ b/packages/plugin-protocol/src/manifest.ts
@@ -0,0 +1,3122 @@
+/** `.cindy` 包根目录中的 manifest 文件名。 */
+export const GHOST_MANIFEST_FILE = 'ghost.json';
+
+/** 意识文件扩展名。 */
+export const CINDY_FILE_EXT = '.cindy';
+
+/** ghost.json 格式版本;与 Plugin HTTP API envelope 版本独立演进。 */
+export const GHOST_MANIFEST_SCHEMA_VERSION = 2 as const;
+
+/** ghost.json 的 description / whenToUse 字符上限。 */
+export const GHOST_MANIFEST_SUMMARY_MAX_CHARS = 300;
+
+/** Cindy host locales supported by Plugin manifest resources. */
+export const GHOST_LOCALES = ['zh-CN', 'en', 'ja', 'ko'] as const;
+export type GhostLocale = (typeof GHOST_LOCALES)[number];
+export type GhostManifestLocales = {
+ en: string;
+} & Partial<Record<Exclude<GhostLocale, 'en'>, string>>;
+
+/** Maximum size of one locale JSON resource in a `.cindy` package. */
+export const GHOST_LOCALE_MAX_BYTES = 64 * 1024;
+
+/**
+ * 意识 id 规则:小写字母/数字开头,后续允许小写字母/数字/连字符,总长 1–32。
+ * 收紧到这个集合并排除 Windows 设备保留名,因为 id 直接用作安装目录名
+ * (userData/brain/<id>),必须在 macOS / Windows 双平台都是安全的文件夹名,
+ * 且天然杜绝路径穿越。
+ */
+const GHOST_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
+
+/** Windows 设备保留名;带扩展名时仍不能作为文件或目录名。 */
+const WINDOWS_RESERVED_NAME_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
+
+function isWindowsReservedName(name: string): boolean {
+ return WINDOWS_RESERVED_NAME_RE.test(name);
+}
+
+/**
+ * 卡槽清单(意识能力的全部出口)。
+ * 'cindy' = 请 Cindy 本体代办(借主机自带 AI 能力干活;2026-07-11 定案
+ * 由 'model' 更名——本质是 Cindy 在干活,与选模型无关;旧名在校验层作
+ * 静默别名兼容,已装老包不消失)。
+ * 'network' = 意识自带服务:域名白名单
+ * 内的 HTTP 经主机代发(沙箱本身保持零直连),凭证锁主机保险库按声明注入。
+ * 'notify' = 系统提示(2026-07-14):意识经管子请主机弹一条轻提示(toast),
+ * 意识只供纯文本,整块 UI 主机画并带意识身份头(与订阅槽红条同一信任边界);
+ * 无阻塞、无按钮、无回执——确认类交互不在此槽(走面板自绘或卡槽③交互卡)。
+ * 'fs' = 写文件(2026-07-14):意识经管子请主机代写文件(创建/修改)。三档
+ * 目的地:自己的私有数据目录(userData/ghost-fs/<id>,免确认)、当前会话
+ * workdir(跟随会话 permission 模式:免批模式直写、逐条模式弹确认卡、
+ * plan/只读拒)、save 票据目录(主 agent 过户,复用 saveDeposit 预算)。
+ * 字节永远由主机落盘,沙箱本身仍无 fs——本槽是"申请主机代写"的资格,
+ * 不是文件系统访问权。
+ * 'session-context' = 会话上下文(2026-07-23):agent 派活(tool-call)时,主机把
+ * 当次会话的可信 {session_id, workdir, workdir_is_local} 注入 args.session_context。
+ * 只注入宿主认证过的事实,插件与 agent 自报的同名字段一律被剥除;远程工作区
+ * (workdir 不在本机)时 workdir_is_local=false,插件不得把它当本机路径用。
+ * 'pick' = 目录选择(2026-07-23):插件经管子申请主机弹**系统级**选文件夹窗口,
+ * 用户亲手选中即授权(与浏览器文件选择同一哲学:决定权在用户的点击上)。
+ * 返回票据(dir_deposit,同 ghost_call dir 通道);声明了 node 槽的插件额外
+ * 拿到绝对路径(Node 侧本就有用户级本机权限,路径保密无意义,可信才是重点)。
+ * 'preview' = 面板预览(2026-07-23):插件经管子申请在右侧栏内置浏览器里打开
+ * 一个网址标签页。网址范围装入时在 preview.hosts 白名单里定死(同 network
+ * 域名白名单语法),运行期主机逐次校验,范围外一律拒——防钓鱼是结构性的。
+ * 'skill' = 捆绑 Agent Skills(2026-07-25):插件随包携带 SKILL.md 技能目录,
+ * 装入且启用后由主机链接进共享技能根 ~/.agents/skills/<id>--<name>(win32 用
+ * junction),Claude Code 与 Codex 都能发现。信任面与其它槽完全不同量级:技能
+ * 指令由主 Agent 以**用户全部权限**执行、对所有项目与会话生效、不受插件沙箱
+ * 约束,也不随"某工作目录停用本插件"而隐藏——仅全局停用/卸载才撤链。因此
+ * manifest 全声明式(items 的 name/description 必须与 SKILL.md frontmatter 逐字
+ * 一致,打包与装入双侧强制),装入确认框逐条列出并置于清单最上部。
+ * 'workspace' = 工作区会话(2026-07-25):插件请主机在指定本机项目目录下确保
+ * 存在一个会话入口并显示在侧边栏——目录下已有 active 会话即复用,没有才创建
+ * 空 draft 会话(不拉起 agent 进程)。目录授权两条路:系统选文件夹窗口亲选
+ * 即授权(pick 模式,路径不回沙箱),或 tool-call 语境下带在途 callId + 绝对
+ * 路径(目录在该会话 workdir 内自动放行,workdir 外弹确认卡)。远程工作区
+ * v1 一律拒(fail closed)。
+ * 'ios-simulator' = Host 托管的内嵌 iOS 模拟器入口:插件只能读取当前任务的
+ * 脱敏状态并请求 Host 打开控制面板。视频帧、输入、设备标识、Native Helper、
+ * 生命周期与恢复均不跨插件边界,仍由 Cindy Host 独占管理。
+ */
+export const GHOST_SLOTS = [
+ 'subscribe',
+ 'tool',
+ 'card',
+ 'panel',
+ 'cindy',
+ 'agent',
+ 'node',
+ 'network',
+ 'notify',
+ 'badge',
+ 'confirm',
+ 'fs',
+ 'session-context',
+ 'pick',
+ 'preview',
+ 'skill',
+ 'workspace',
+ 'ios-simulator',
+] as const;
+export type GhostSlot = (typeof GHOST_SLOTS)[number];
+
+/**
+ * 电子脑启动模式(2026-07-12):
+ * - 'on-demand'(缺省):被需要才拉起(agent 派活 / 面板 /wake / 重载);
+ * - 'resident':唤醒即启动——enable 时拉起,应用启动时对"已唤醒"者拉起。
+ * 两种模式下沉睡 / 抽离 / 更新换代一律先熄灯,规则不变;resident 会在装入
+ * 确认框多一行如实告知(常驻 = 用户要背一个后台进程,必须知情)。
+ */
+export const GHOST_LAUNCH_MODES = ['on-demand', 'resident'] as const;
+export type GhostLaunchMode = (typeof GHOST_LAUNCH_MODES)[number];
+
+/**
+ * 面板显示形态(相对主聊天窗)。left / right = 顶层布局树停靠 pane;
+ * 'tab' = 不进布局树,作为右侧栏(right-tabs)里的每会话单例页签
+ * (2026-07-24 定案)。top / bottom 需要嵌套上下分割(树操作/拖缝/卸载
+ * 查找全链路),排期中——校验层先收词并明确拒绝,不静默降级(规则 9)。
+ */
+export const GHOST_PANEL_POSITIONS = ['left', 'right', 'tab'] as const;
+export type GhostPanelPosition = (typeof GHOST_PANEL_POSITIONS)[number];
+
+/** 面板声明(卡槽之一,一段意识至多一块)。 */
+export interface GhostPanelDecl {
+ /** 面板标准头(PanelChrome)标题;缺省用意识 name。 */
+ title?: string;
+ /** 显示形态:left / right 停靠,或 'tab' 右侧栏页签;缺省 = right(2026-07-12 定案)。 */
+ position?: GhostPanelPosition;
+ /** 面板界面入口(安装目录内相对路径,意识自绘,由主机面板容器渲染)。 */
+ html: string;
+ /** 面板最小宽度(px),布局引擎拖缝时的下限。仅停靠形态有效,'tab' 时禁用。 */
+ minWidth?: number;
+ /** 装入布局时的初始宽度占比(与 layoutTree 的 fraction 同语义)。仅停靠形态有效,'tab' 时禁用。 */
+ defaultFraction?: number;
+}
+
+/**
+ * 芯片型意识注册给 agent 的工具声明(卡槽②)。
+ * 声明式而非运行时动态注册(规则 9:确定性;且会话中途增删工具会破坏
+ * prompt 缓存前缀,规则 10)——主机在会话建立时按"已装且唤醒"的意识
+ * 快照注入工具集。
+ */
+export interface GhostToolDecl {
+ /** 工具名:小写字母开头,允许小写/数字/下划线/连字符,≤64。 */
+ name: string;
+ /** 给模型看的工具说明。 */
+ description: string;
+ /** JSON Schema(object)形态的参数声明;可省略(无参工具)。 */
+ parameters?: Record<string, unknown>;
+}
+
+/**
+ * Card 槽能力详单。card 槽默认仅允许渲染静态/交互卡片(含按钮动作);
+ * externalLinks: true 额外允许卡片声明 data-ghost-link 外链,点击经宿主
+ * 确认框后 openExternal——这是独立加档权限,装入确认时单列。
+ */
+export interface GhostCardNeeds {
+ externalLinks?: boolean;
+}
+
+/**
+ * Agent 新回合能力详单。
+ *
+ * 申请 `agent` 槽默认只允许消费宿主在真实用户点击插件卡片时签发的
+ * 一次性通行票。三个可选加档均由 Desktop 独立展示并授权。
+ */
+export interface GhostAgentNeeds {
+ background?: boolean;
+ errand?: boolean;
+ schedule?: boolean;
+}
+
+/** 插件随包本地 Node 工作进程使用的 stdio 协议。 */
+export const GHOST_NODE_PROTOCOLS = ['json-rpc-stdio', 'mcp-stdio'] as const;
+export type GhostNodeProtocol = (typeof GHOST_NODE_PROTOCOLS)[number];
+
+/** Node 工作进程生命周期;常驻档会在安装确认中单列高风险权限。 */
+export const GHOST_NODE_LIFECYCLES = ['on-demand', 'resident'] as const;
+export type GhostNodeLifecycle = (typeof GHOST_NODE_LIFECYCLES)[number];
+
+/** 单插件最多可声明的 Node 凭证绑定数。 */
+export const GHOST_NODE_MAX_SECRET_BINDINGS = 4;
+/** 单条 Node 凭证最多可绑定的 JSON-RPC 方法数。 */
+export const GHOST_NODE_MAX_SECRET_METHODS = 16;
+const GHOST_NODE_MCP_RESERVED_METHODS = new Set(['initialize', 'notifications/initialized']);
+
+/** MCP 握手由宿主发起,插件业务请求与凭证绑定均不得占用这些方法。 */
+export function isGhostNodeMcpReservedMethod(method: string): boolean {
+ return GHOST_NODE_MCP_RESERVED_METHODS.has(method);
+}
+
+/**
+ * 主机保险库 → 随包 Node Worker 的按请求凭证绑定。
+ *
+ * 值由 settingsHtml 经 `/secrets` 一次性写入 safeStorage;浏览器沙箱
+ * main.js 不能直接从保险库读取明文。宿主仅在 method 与 entry 同时命中
+ * 本声明时,把值放进发往 Worker 的保留字段 `cindy.secrets[key]`;
+ * Worker 获得明文后仍可能主动回传或泄露。未声明 entry 时只允许主入口。
+ */
+export interface GhostNodeSecretBinding {
+ /** 凭证键(插件内唯一):小写字母开头,允许小写/数字/下划线,1–32。 */
+ key: string;
+ /** 给用户看的名称(安装确认与设置状态使用)。 */
+ label: string;
+ /** 允许注入的 JSON-RPC 方法白名单(1–16 条)。 */
+ methods: string[];
+ /** 可选目标入口;缺省只绑定 node.entry 主入口。 */
+ entry?: string;
+ /** 可选输入提示。 */
+ hint?: string;
+ /** 可选凭证申请页(仅 https;设置页外链须逐字命中)。 */
+ url?: string;
+}
+
+/**
+ * 随插件安装的本地 Node 工作进程声明。
+ *
+ * 只允许指定包内入口和固定协议,不接受 command / args / shell / env,避免把
+ * ghost.json 变成任意命令启动器。Node 进程拥有当前系统用户级本机权限,主机
+ * 只保证它不能绕过 main.js 调 Cindy API,并不能把它变成系统级沙箱。
+ */
+export interface GhostNodeNeeds {
+ entry: string;
+ protocol: GhostNodeProtocol;
+ lifecycle?: GhostNodeLifecycle;
+ idleTimeoutSeconds?: number;
+ /**
+ * 额外工作进程入口(2026-07-23,能力 5 窄版):仍只能是包内申报过的 JS 文件,
+ * node-request 带 entry 字段指名调用;每个入口一个独立进程,协议/生命周期/
+ * 空闲策略与主入口共用同一份声明。不是任意命令执行——包外文件、未申报
+ * 入口一律拒。
+ */
+ entries?: string[];
+ /**
+ * 宿主代启子进程开关(2026-07-23,缺口 1):worker 可经引导层窄接口
+ * (spawnEntry)请求宿主再启动一个**已申报入口**(entry / entries 之内)的
+ * 原样 stdio 子进程,并把子进程 stdio 字节中继回 worker。给 Maker Runtime
+ * 这类"自己 spawn process.execPath"的库改道用——正式包关 RunAsNode,
+ * 那条路生出来的不是 Node。默认关;开了会在装入确认框单列一行。
+ * 权限本质不变:仍只能跑包内申报过的 JS,node 槽本就是用户级执行权。
+ */
+ childSpawn?: boolean;
+ /**
+ * 由主机 safeStorage 持久化、按声明的方法临时注入 Worker 的凭证。
+ * 这是 Node 高风险能力的一部分,安装权限清单会逐条披露。
+ */
+ secretBindings?: GhostNodeSecretBinding[];
+}
+
+/** node 额外入口条数上限(1 主 + 4 额外 = 每插件至多 5 个工作进程)。 */
+export const GHOST_NODE_MAX_EXTRA_ENTRIES = 4;
+
+/** cindy 槽·图像类可申请的动作(主机代办菜单的"图像"类目)。 */
+export const GHOST_MODEL_IMAGE_ACTIONS = ['generate', 'edit'] as const;
+export type GhostModelImageAction = (typeof GHOST_MODEL_IMAGE_ACTIONS)[number];
+
+/** cindy 槽·视频类可申请的动作(generate=文生视频,edit=参考图生视频)。 */
+export const GHOST_MODEL_VIDEO_ACTIONS = ['generate', 'edit'] as const;
+export type GhostModelVideoAction = (typeof GHOST_MODEL_VIDEO_ACTIONS)[number];
+
+/** cindy 槽·媒体类可申请的动作(deposit=寄存自己手里的媒体字节入总仓)。 */
+export const GHOST_CINDY_MEDIA_ACTIONS = ['deposit'] as const;
+export type GhostCindyMediaAction = (typeof GHOST_CINDY_MEDIA_ACTIONS)[number];
+
+/**
+ * cindy 槽·文本类可申请的动作(2026-07-31 开闸)。
+ *
+ * `oneshot` = 快问快答:意识递一段文字,主机经**轻量任务模型链**(与会话
+ * 起标题、任务一句话总结同一条通道)直答一次并把文字原样递回。不拉起
+ * agent、无工具、无用户权限、不进任何会话——只花模型额度,拿不到任何
+ * 宿主能力。
+ */
+export const GHOST_CINDY_TEXT_ACTIONS = ['oneshot'] as const;
+export type GhostCindyTextAction = (typeof GHOST_CINDY_TEXT_ACTIONS)[number];
+
+/**
+ * cindy 槽·向量类可申请的动作(2026-08-04 开闸)。
+ *
+ * `text` = 文本转向量:意识递一批文字,主机经统一 embedding 通道返回等长的
+ * 向量数组。只生成、不存储;向量原样递回意识自己保管。与 text.oneshot
+ * 分成两档:两者花不同的钱(轻量任务模型链 vs embedding 模型),合成一档
+ * 就没法只授权其中一样。
+ */
+export const GHOST_CINDY_EMBED_ACTIONS = ['text'] as const;
+export type GhostCindyEmbedAction = (typeof GHOST_CINDY_EMBED_ACTIONS)[number];
+
+/** cindy 槽·搜索类可申请的动作(web=Cindy 托管的公网搜索)。 */
+export const GHOST_CINDY_SEARCH_ACTIONS = ['web'] as const;
+export type GhostCindySearchAction = (typeof GHOST_CINDY_SEARCH_ACTIONS)[number];
+
+/**
+ * cindy 槽能力详单(卡槽⑤配套,原名模型槽,2026-07-11 设计定案):声明"这个意识被允许
+ * 向主机点哪几类代办"——只有类目与动作,**不含任何具体模型/供应商信息**
+ * (选型权在主机的解析表:调用时显式点名 > 意识专属覆盖 > 用户能力偏好 >
+ * 出厂默认;意识只表达意图,永不腐烂)。装入确认框与代办资格审共同消费。
+ */
+export interface GhostCindyNeeds {
+ /** 图像类:generate=出图,edit=改图(改图仅限本意识名下媒体)。 */
+ image?: GhostModelImageAction[];
+ /** 视频类:generate=文生视频,edit=参考图生视频(源图仅限本意识名下媒体,1–2 张首/尾帧)。 */
+ video?: GhostModelVideoAction[];
+ /** 媒体类:deposit=寄存自己手里的媒体字节入总仓(换指纹,兼授权 release_media)。 */
+ media?: GhostCindyMediaAction[];
+ /** 文本类:oneshot=快问快答(轻量任务模型链直答一次,无 agent 无工具)。 */
+ text?: GhostCindyTextAction[];
+ /** 向量类:text=文本转向量(只生成不存储,向量原样递回意识自己保管)。 */
+ embed?: GhostCindyEmbedAction[];
+ /** 搜索类:web=Cindy 托管的公网搜索(主机固定路由,插件不经手网关凭证)。 */
+ search?: GhostCindySearchAction[];
+ /**
+ * 快问快答偏好模型(目录模型 id,如 "codex/gpt-5.5";须与 text 含 "oneshot"
+ * 成对)。主机能从当前供应商目录解析到(且用户未停用)就用它,解析不到按
+ * 未声明处理;用户在详情页的钉档永远优先于本声明。注意:旧宿主会把含本
+ * 字段的身份卡**整份拒装**(cindy 详单未知类目硬拒)——声明前确认目标
+ * 用户群的主机版本。
+ */
+ oneshotModel?: string;
+}
+
+/**
+ * 订阅槽 did- 旁听主题(卡槽①,2026-07-12 开闸)。v1 全部是**元数据级**:
+ * turn = 轮次开始/结束(agent/模型/耗时/用量,不含消息内容);
+ * session = 会话创建/归档/切换(切换 = 用户把哪个会话切到台前,2026-07-13 增)。
+ * 正文级主题(消息内容旁听)刻意不开——隐私最重,等真实场景再议,权限文案
+ * 也要另分一档。
+ */
+export const GHOST_SUBSCRIBE_TOPICS = ['turn', 'session'] as const;
+export type GhostSubscribeTopic = (typeof GHOST_SUBSCRIBE_TOPICS)[number];
+
+/**
+ * 订阅槽 will- 拦截钩子(真 hook:主机停等裁决)。两个点,一进一出:
+ * - `will-user-message`(入口):用户消息即将交给 agent 之前(拦下 = turn 压根
+ * 不启动);动作 allow/block/rewrite。
+ * - `will-assistant-message`(出口):AI 这轮回复完成、最终气泡定案之前,把全文
+ * 交给意识做润色/合规改写或自绘结果卡片;动作 allow/rewrite/render(无 block
+ * ——AI 已生成,拦无意义)。**不拦流式输出**(照常打字机),只在 turn 结束
+ * 边界的独立异步续跑里裁决,不搅 maker-core 热路径;超时/崩溃 fail-open 用原文。
+ * 两个钩子都不拦 tool-call。声明了任一钩子必须 launch:'resident'(要挡路就得常驻
+ * 在场,冷启动延迟不可接受),校验强制。
+ */
+export const GHOST_SUBSCRIBE_HOOKS = ['will-user-message', 'will-assistant-message'] as const;
+export type GhostSubscribeHook = (typeof GHOST_SUBSCRIBE_HOOKS)[number];
+
+/**
+ * 订阅槽详单(与 slots 含 'subscribe' 成对;有槽无详单允许装入但零事件——
+ * 与 cindy 详单同语义)。topics = did- 旁听(fire-and-forget),hooks = will-
+ * 拦截(停等裁决);没声明的主题/钩子,网关不挂处理段(接口不存在)。
+ */
+export interface GhostSubscribeNeeds {
+ topics?: GhostSubscribeTopic[];
+ hooks?: GhostSubscribeHook[];
+}
+
+/* ── network 槽详单──────────────────────────────────
+ * 意识自带服务:作者声明域名白名单 + 凭证需求,装入时钉死、确认框逐项展示。
+ * 运行期沙箱仍零直连,所有出网经管子 fetch-request 由主机代发;凭证明文
+ * 永不进沙箱——主机只在"该凭证声明的注入位置"拼进请求头。 */
+
+/** network 槽:域名白名单条数上限(声明面越小越好,超了说明设计有问题)。 */
+export const GHOST_NETWORK_MAX_HOSTS = 8;
+/** network 槽:凭证声明条数上限。 */
+export const GHOST_NETWORK_MAX_SECRETS = 4;
+/** network 槽:多连接(connections)声明条数上限(一段意识通常只对接一种自建服务)。 */
+export const GHOST_NETWORK_MAX_CONNECTION_DECLS = 2;
+/** network 槽:每条连接声明下用户可添加的连接数上限(同时是 maxConnections 缺省值)。 */
+export const GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL = 8;
+
+/**
+ * 域名白名单条目格式:小写域名,至少两段(拒绝裸 TLD / 单段内网名),
+ * 通配只允许最左一段(`*.example.com`);不收 IP、端口、路径、协议。
+ */
+const GHOST_NETWORK_LABEL_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
+export function isValidGhostNetworkHostPattern(p: unknown): p is string {
+ if (typeof p !== 'string' || p.length === 0 || p.length > 253) return false;
+ const bare = p.startsWith('*.') ? p.slice(2) : p;
+ const labels = bare.split('.');
+ // 至少两段:`*.com` / `localhost` / 裸 TLD 全部拒绝,命中面必须是具体域。
+ if (labels.length < 2) return false;
+ // 纯数字四段视作 IP,拒收(白名单只认域名)。
+ if (labels.every((l) => /^\d+$/.test(l))) return false;
+ return labels.every((l) => GHOST_NETWORK_LABEL_RE.test(l));
+}
+
+/**
+ * hostname 是否命中白名单条目。精确条目要求逐字相等;通配条目
+ * (`*.example.com`)命中任意深度的子域(`a.example.com`、`a.b.example.com`),
+ * 但不命中裸域本身——作者两者都要就两条都声明,规则不做隐式扩张。
+ * 注意:此行为必须与桌面端 base 的同名校验器逐字一致(两端同一契约),
+ * 任何语义调整都属于协议变更,需两侧同步。
+ */
+function ghostNetworkHostMatches(pattern: string, hostname: string): boolean {
+ if (pattern.startsWith('*.'))
+ return hostname.endsWith(pattern.slice(1)) && hostname.length > pattern.length - 1;
+ return hostname === pattern;
+}
+
+/**
+ * 凭证注入声明:该凭证以什么形态、进哪些域名的请求头。绑定在 secret 上
+ * (而非独立 auth 模板)是刻意的——结构上保证"key 只流向它声明的域名",
+ * 意识更新扩白名单也扩不走存量凭证的流向。
+ */
+export interface GhostSecretInjectDecl {
+ /**
+ * 注入范围(manifest.network.hosts 的子集,逐字匹配声明条目);
+ * 缺省 = 详单里的全部域名。
+ */
+ hosts?: string[];
+ /** 注入的请求头名(如 Authorization / X-Subscription-Token)。 */
+ header: string;
+ /** 头值模板:恰含一个 `{value}` 占位,其余为静态文本(如 `Bearer {value}`)。 */
+ format: string;
+}
+
+/** 凭证交换(key 换令牌)请求体类型白名单。 */
+export const GHOST_SECRET_EXCHANGE_CONTENT_TYPES = [
+ 'application/json',
+ 'application/x-www-form-urlencoded',
+] as const;
+export type GhostSecretExchangeContentType = (typeof GHOST_SECRET_EXCHANGE_CONTENT_TYPES)[number];
+
+/** 凭证交换:请求体模板长度上限。 */
+export const GHOST_SECRET_EXCHANGE_BODY_MAX_CHARS = 2048;
+/** 凭证交换:令牌缓存时长(秒)缺省 / 下限 / 上限(上限 30 天)。 */
+export const GHOST_SECRET_EXCHANGE_TTL_DEFAULT_S = 3600;
+export const GHOST_SECRET_EXCHANGE_TTL_MIN_S = 60;
+export const GHOST_SECRET_EXCHANGE_TTL_MAX_S = 30 * 24 * 3600;
+/** 凭证交换:tokenPath 点分路径形状(不支持数组下标,段名字母/数字/_/-)。 */
+export const GHOST_SECRET_EXCHANGE_TOKEN_PATH_RE = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/;
+
+/** oauth.identity.displayTemplate:占位符提取(`{点分路径}`;路径形状同 tokenPath)。 */
+export const GHOST_OAUTH_IDENTITY_TEMPLATE_PLACEHOLDER_RE = /\{([^{}]*)\}/g;
+/** oauth.identity.displayTemplate 长度上限(渲染产物也按同上限截断降级)。 */
+export const GHOST_OAUTH_IDENTITY_TEMPLATE_MAX_CHARS = 200;
+
+/**
+ * 凭证交换声明(可选):有些服务的 API key 不直接当请求凭证,要先拿 key
+ * 去换一个临时令牌(key→session 二段式)。声明后主机照单代办:
+ * POST 交换端点(请求体模板注入原始 key,按 contentType 确定性转义)→
+ * 从响应 JSON 按 tokenPath 取令牌 → 按 ttl 内存缓存 → inject.format 的
+ * {value} 注入的是**换来的令牌**而非原始 key;上游 401 时主机作废缓存
+ * 重换重试一次。原始 key 与令牌全程不进沙箱。做成清单声明而非主机硬编码,
+ * 是为了新意识接入二段式服务不需要更新 app(交换方式由意识作者声明)。
+ */
+export interface GhostSecretExchangeDecl {
+ /** 交换端点(仅 https、默认端口;域名必须命中 network.hosts 白名单)。 */
+ url: string;
+ /**
+ * POST 请求体模板:恰含一个 `{value}` 占位(原始凭证落点)。注入时按
+ * contentType 转义:json → JSON 字符串转义;form → percent 编码。
+ */
+ bodyFormat: string;
+ /** 请求体类型;缺省 'application/json'。 */
+ contentType?: GhostSecretExchangeContentType;
+ /** 令牌在响应 JSON 里的点分路径(如 "session" / "data.token";值须是非空字符串)。 */
+ tokenPath: string;
+ /** 令牌缓存时长(秒,60–2592000);缺省 3600。 */
+ ttlSeconds?: number;
+}
+
+/** OAuth 凭证:scopes 条数上限(超出拒装;确认框逐条展示要可读)。 */
+export const GHOST_OAUTH_SCOPES_MAX = 256;
+/** OAuth broker 模式允许声明的备用 client ID 数量上限。 */
+export const GHOST_OAUTH_CLIENT_ID_ALTERNATIVES_MAX = 8;
+/** OAuth 凭证:extraAuthorizeParams 条数上限。 */
+export const GHOST_OAUTH_EXTRA_PARAMS_MAX = 8;
+/**
+ * OAuth 授权 URL 的协议保留参数:由主机授权引擎独占,意识的
+ * extraAuthorizeParams 不许声明(装入拒;引擎侧同名单防御性忽略)。
+ */
+export const GHOST_OAUTH_RESERVED_AUTHORIZE_PARAMS: readonly string[] = [
+ 'response_type',
+ 'client_id',
+ 'redirect_uri',
+ 'state',
+ 'scope',
+ 'code_challenge',
+ 'code_challenge_method',
+];
+
+/**
+ * OAuth 凭证声明(source: 'oauth',2026-07-13 定案"通用声明式"):
+ * 平台不预设 provider 名单——意识声明"去哪授权、要什么 scope",clientId /
+ * clientSecret 由用户在意识设置页自填(经 /oauth 只写通道入库),装入确认框
+ * 全量展示授权域名与 scopes,用户知情自担。声明化的是**参数**不是**代码**:
+ * 授权流程(拉浏览器、loopback 回调、state/PKCE 校验、code 换 token、刷新)
+ * 永远由主机可信代码执行,意识无从插手,
+ * access / refresh token 与 client 凭证全程不进沙箱,注入按 inject 声明由
+ * networkSlot 出网时现取现注(401 作废重刷重试一次,与 exchange 同套路)。
+ */
+export interface GhostSecretOauthDecl {
+ /** 授权页地址(https;域名必须命中 network.hosts 白名单——确认框上的域名集合 = 全部出网面)。 */
+ authorizeUrl: string;
+ /** code / refresh token 交换端点(https;域名必须命中 hosts——clientSecret 只流向用户同意过的域名)。 */
+ tokenUrl: string;
+ /**
+ * 可选:作者内置的 OAuth 客户端 ID(2026-07-13 定案,开箱即用前置)。
+ * 声明后用户零配置即可点"连接账号";用户在设置页自填的
+ * client 凭证**覆盖**内置值(清除自填 = 回落内置)。桌面应用的 client
+ * 凭证按 Google 官方口径本非机密(installed-app),写进包里不引入新泄露面;
+ * 授权仍需用户在浏览器里亲自同意,凭证本身访问不了任何数据。
+ */
+ clientId?: string;
+ /** 可选:broker 模式下允许意识在单次连接时选择的备用客户端 ID。 */
+ clientIdAlternatives?: string[];
+ /** 可选:内置 client 的 secret(与 clientId 成对;纯 PKCE 服务商可省略)。 */
+ clientSecret?: string;
+ /** 申请的 scope 列表(0–256 条,确认框逐条展示;缺省 = 不带 scope 参数)。 */
+ scopes?: string[];
+ /**
+ * 可选:authorize URL 里 scope 参数的拼接分隔符。OAuth 标准是空格(缺省),
+ * Slack 这类逗号分隔的服务商声明 ","(目前只认这一个值)。
+ */
+ scopeDelimiter?: ',';
+ /** PKCE(S256)开关,缺省 true;个别不支持的老服务商可显式声明 false。 */
+ pkce?: boolean;
+ /**
+ * 服务商特有的授权页附加参数(如 Google 的 access_type=offline +
+ * prompt=consent、Atlassian 的 audience=api.atlassian.com);协议保留参数
+ * (GHOST_OAUTH_RESERVED_AUTHORIZE_PARAMS)不许声明。
+ */
+ extraAuthorizeParams?: Record<string, string>;
+ /**
+ * 可选:授权成功后拉一次身份端点给账号打展示标签(设置页"已连接为 xxx");
+ * url 仅 https 且域名须命中 hosts;labelPath 为响应 JSON 的点分路径
+ * (与 exchange.tokenPath 同规则)。拉取失败不阻断授权(标签降级为空)。
+ *
+ * displayTemplate(可选,2026-07-15 增补):人类可读的展示名
+ * 模板,`{点分路径}` 占位符从同一份身份响应取值(如 Slack auth.test 的
+ * `"{team} · {user}"`)。与 labelPath 分工:labelPath 指向**稳定且唯一**的
+ * 身份键(user_id / 邮箱),是重复授权时同身份合并的判定键;displayTemplate
+ * 只管展示(设置页 / 账号工具看到的名字),任一占位符取不到值时整体降级
+ * 为空(回落显示 labelPath 标签)。不声明 = 展示名就用 labelPath 的值
+ * (邮箱这类本身可读的服务商不需要它)。
+ */
+ identity?: { url: string; labelPath: string; displayTemplate?: string; avatarPath?: string };
+ /**
+ * 可选:loopback 回调固定端口(1024–65535)。Atlassian 这类服务商要求回调
+ * URI 与应用注册值精确匹配(含端口),声明后主机授权引擎钉死
+ * `http://127.0.0.1:<port>/callback`(端口被占用时结构化报错引导重试);
+ * 缺省 = 随机端口(Google 等允许任意 loopback 端口的服务商)。
+ */
+ redirectPort?: number;
+ /**
+ * 可选:服务端 token broker 的 provider slug(2026-07-14 增补)。
+ * 声明后 code 换 token 与 refresh 不直连 tokenUrl,改经主机
+ * 调服务端的授权 broker(带登录 JWT;client secret 在服务端,不随包
+ * 分发)。与 clientSecret 互斥。**仅第一方官方前缀意识可用**——校验层保持
+ * 纯函数不感知装入语境,门控在运行时装入闸与连接闸(cindy-brain)。
+ */
+ tokenBroker?: string;
+ /**
+ * 可选:broker 弹跳回调(双地址模型,2026-07-15 增补)。
+ * Slack 这类服务商后台只收 https redirect,不收 http loopback——声明后
+ * 报给服务商的 redirect_uri 变成「授权 broker 服务的 https 弹跳路由」
+ * (主机运行时用 broker 基地址 + `path` 拼出,清单不落域名字面量),浏览器
+ * 授权后落弹跳路由,由其 302 回本机 `http://127.0.0.1:<redirectPort><callbackPath>`。
+ * 约束:必须与 tokenBroker、redirectPort 同时声明(弹跳路由的 302 目标
+ * 端口与路径在 broker 服务端写死,三者是一套约定);两个路径都必须是
+ * `/` 开头的站内绝对路径。
+ */
+ brokerBounce?: { path: string; callbackPath: string };
+}
+
+/** tokenBroker slug 形状(小写字母开头,小写/数字/下划线/连字符,1–32)。 */
+export const GHOST_OAUTH_TOKEN_BROKER_RE = /^[a-z][a-z0-9_-]{0,31}$/;
+
+/** brokerBounce 路径形状(/ 开头的站内绝对路径,段字符限字母/数字/_/-,≤128)。 */
+export const GHOST_OAUTH_BOUNCE_PATH_RE = /^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/;
+
+/**
+ * 凭证值来源(2026-07-13 定型):
+ * - 'user'(缺省):值由用户在该意识设置页填入主机保险库;
+ * - 'login-email':值 = 主机当前登录账号的邮箱——主机注入时现取登录态,
+ * 设置页只读展示该邮箱(不可编辑、不进保险库);未登录 / 登录态缺 email
+ * 时 fail-closed 报错并引导重新登录。适用于"服务端按登录邮箱派生鉴权"
+ * 的第一方服务(经 inject.format 的静态前缀完成派生)。
+ * - 'oauth'(2026-07-13 增补):值 = 主机托管 OAuth
+ * 授权换来的 access token——用户在意识设置页填 client 凭证并点"连接账号",
+ * 主机跑授权流程并保管全部令牌,出网时现取新鲜 token 注入(见
+ * GhostSecretOauthDecl;必须同时声明 oauth 详单)。
+ * - 'login-feishu-token'(2026-07-16 增补):值 = 主机
+ * 飞书登录态的 user access token——主机注入时现取(登录态管理器
+ * 自刷新,token 明文不进沙箱、不进错误消息);未连接飞书 / 刷新链路判
+ * AUTH_EXPIRED 时 fail-closed 报错并引导重新登录飞书。适用于"能力面
+ * 直接复用产品飞书登录身份"的第一方服务;与 login-email 同族:用户
+ * 不填值,禁 url / exchange / oauth,settingsHtml 豁免。
+ * - 'oidc-token'(2026-08-03 增补):值 = 主机为当前企业 Membership
+ * 按受信组织插件 provenance 按需签发的短时 Cindy Connection JWT;
+ * 插件和 Node Worker 都不能读取或保存令牌。必须固定注入
+ * `Authorization: Bearer {value}` 并显式声明非空的精确 inject.hosts;
+ * 不允许 url / exchange / oauth / input,也不要求 settingsHtml。只有
+ * organization scope 的插件可以通过 Plugin Market 发布该来源。
+ * - 'gh-cli'(2026-08-05 增补):值优先取主机本地 GitHub CLI
+ * 登录态(`gh auth token`),不可用时回落到用户在该插件设置页
+ * 保存的备用 Token。两种值都只允许固定注入
+ * `https://api.github.com` 的 `Authorization: Bearer {value}`;插件和
+ * Node Worker 不能读取令牌。必须声明 settingsHtml 作为
+ * 备用 Token 的管理入口,不允许 exchange / oauth / input。
+ */
+export const GHOST_SECRET_SOURCES = [
+ 'user',
+ 'login-email',
+ 'oauth',
+ 'login-feishu-token',
+ 'oidc-token',
+ 'gh-cli',
+] as const;
+export type GhostSecretSource = (typeof GHOST_SECRET_SOURCES)[number];
+
+/**
+ * 凭证收单(2026-07-13 两次定案,当天收敛):user 凭证的收单**一律**由意识
+ * settingsHtml 自绘——经协议 `/secrets` 只写通道一次性入库,存入后意识拿不回
+ * 明文,保管(safeStorage)与注入(主机代发时)由主机独占。安全模型弱化点
+ * 仅一处:录入瞬间明文经过意识页面(用户主动敲进它的输入框),装入确认框
+ * 如实告知。**宿主渲染凭证输入行已整体退役**(基座不再为意识特设凭证 UI,
+ * 定案):清单里遗留的 `input: "ghost"` 接受并忽略(与现状同义),
+ * `input: "host"` 直接拒绝;声明 user 凭证必须同时声明 settingsHtml。
+ */
+
+/** 凭证声明:只有名字与说明——值由用户在该意识设置区填入主机保险库。 */
+export interface GhostSecretDecl {
+ /** 凭证键(意识内唯一):小写字母开头,允许小写/数字/下划线,1–32。 */
+ key: string;
+ /** 给用户看的名称(装入确认框展示)。 */
+ label: string;
+ /** 凭证值来源;缺省 'user'(校验归一化:'user' 不落清单)。 */
+ source?: GhostSecretSource;
+ /** 可选提示(如"在 example.com/settings 生成")。 */
+ hint?: string;
+ /**
+ * 可选:该凭证的控制台/申请页地址(仅 https)。settingsHtml 里可用
+ * `<a href>` 逐字引用本地址——主机外链闸(GhostExternalLinkGate)只放行
+ * 身份卡声明过的地址,点击转系统浏览器打开;也供确认框等宿主 UI 引用。
+ */
+ url?: string;
+ /** 注入位置声明(必填:没有注入位置的凭证无处可用)。 */
+ inject: GhostSecretInjectDecl;
+ /** 可选:key 换令牌二段式声明(见 GhostSecretExchangeDecl;与 oauth 互斥)。 */
+ exchange?: GhostSecretExchangeDecl;
+ /** source: 'oauth' 时必填的授权详单(见 GhostSecretOauthDecl);其它来源禁止声明。 */
+ oauth?: GhostSecretOauthDecl;
+ /**
+ * @deprecated 已退役(2026-07-13 宿主凭证渲染退役):user 凭证一律意识
+ * settingsHtml 收单。原始清单遗留的 'ghost' 装入时接受并忽略(归一化后
+ * 不落清单,见 validateGhostManifest),其余值拒。字段仅为原始清单解析
+ * 与存量消费点的类型兼容保留,新代码不要读写。
+ */
+ input?: 'ghost';
+}
+
+/**
+ * 多连接声明(connections,2026-07-14,Cindy GitLab 自建实例前置):
+ * "地址 + 凭证成对多条"的凭证形态——作者只声明连接类型(名字、注入形态、
+ * 条数上限),具体地址与 token 由用户在意识设置页逐条添加(经 /connections
+ * 协议通道入库)。与静态 hosts 白名单的关系:用户添加的每条地址并入该意识
+ * 的放行域(精确匹配,不吃通配),**每次新增地址都要过主机受信确认弹窗**
+ * ——动态白名单不能只凭意识设置页(意识自绘、不可信)单方面扩张。凭证注入
+ * 范围恒等于各连接自身地址(结构上钉死"token 只流向它自己的实例"),因此
+ * inject 不允许声明 hosts 子集(写了拒装)。
+ */
+export interface GhostConnectionDecl {
+ /** 连接声明键(意识内唯一,与 secrets[].key 共用命名空间不得撞名):小写字母开头,1–32。 */
+ key: string;
+ /** 给人看的连接类型名(如「GitLab 实例」;确认框与设置页展示)。 */
+ label: string;
+ /** 可选提示(≤200 字,设置页展示,如"填实例域名与 Personal Access Token")。 */
+ hint?: string;
+ /**
+ * 凭证注入形态(header + format,校验同 GhostSecretInjectDecl;**禁止**
+ * 声明 hosts——注入范围恒等于各连接自身地址,不接受作者收窄/扩张)。
+ */
+ inject: { header: string; format: string };
+ /** 每种连接可添加的地址数上限(1–8 整数;缺省 8)。 */
+ maxConnections?: number;
+}
+
+/**
+ * network 槽详单(与 slots 含 'network' 成对;有槽无详单允许装入但零能力,
+ * 与 cindy / subscribe 同语义)。
+ */
+export interface GhostNetworkNeeds {
+ /**
+ * 静态域名白名单(装入时钉死;运行期主机逐请求校验)。常规必填 1–8 条;
+ * 声明了 connections(动态连接地址)时可缺省/空数组——静态域名与动态
+ * 连接至少有其一(校验保证),归一化后恒为数组(可能为空)。
+ */
+ hosts: string[];
+ /** 凭证声明(0–4 条;用户填值,主机加密保管并按 inject 声明注入)。 */
+ secrets?: GhostSecretDecl[];
+ /** 多连接声明(0–2 条;地址+凭证成对多条,用户在设置页添加,见 GhostConnectionDecl)。 */
+ connections?: GhostConnectionDecl[];
+}
+
+/**
+ * 注入头名黑名单:协议关键头由主机独占,作者声明命中即拒装
+ * (小写比较;Cookie 也拒——会话粘连语义不给意识)。
+ */
+export const GHOST_NETWORK_FORBIDDEN_INJECT_HEADERS: readonly string[] = [
+ 'host',
+ 'content-length',
+ 'transfer-encoding',
+ 'connection',
+ 'cookie',
+ 'origin',
+ 'referer',
+ // content-type 由请求语义决定(上传通道的 multipart boundary 依赖它),
+ // 不许被凭证注入声明占用——401 重换/跨域跳转的重注入会砸掉 boundary。
+ 'content-type',
+];
+
+/** preview 槽:可打开预览的域名模式条数上限(范围越小越好,同 network 精神)。 */
+export const GHOST_PREVIEW_MAX_HOSTS = 4;
+
+/**
+ * preview 槽详单(与 slots 含 'preview' 严格成对——有槽必有详单:范围是
+ * 本能力的全部知情面,不允许"先装后说")。hosts 语法与 network 域名白名单
+ * 一致(支持 `*.` 单层前缀通配),另特批 loopback 单段名(本地 dev server
+ * 是预览的正当主场,network 语法"至少两段"表达不了它)。装入确认框逐条展示。
+ */
+export interface GhostPreviewNeeds {
+ hosts: string[];
+}
+
+/** preview.hosts 特批的 loopback 主机名(network 域名语法之外唯一的例外)。 */
+export const GHOST_PREVIEW_LOOPBACK_HOSTS: ReadonlySet<string> = new Set([
+ 'localhost',
+ '127.0.0.1',
+ '[::1]',
+]);
+
+/** skill 槽:单插件最多捆绑的 Agent Skill 数(范围越小越好,同 preview 精神)。 */
+export const GHOST_SKILL_MAX_ITEMS = 4;
+/** skill 槽:SKILL.md 单文件字节上限。打包与装入两侧共用,避免契约漂移。 */
+export const GHOST_SKILL_MD_MAX_BYTES = 64 * 1024;
+/** skill 槽:技能 name 长度上限(链接目录名的一半,克制)。 */
+export const GHOST_SKILL_NAME_MAX_CHARS = 64;
+/**
+ * skill 槽:技能 name 形状——小写字母/数字,连字符仅作单段分隔(禁首尾与连续
+ * 连字符)。比 SkillHub 的技能名规则更严:意识 id 允许含 `--`(GHOST_ID_RE),
+ * 共享技能根的链接名是 `<id>--<name>`,只有 name 侧禁 `--`,
+ * 按"最后一个 `--`"拆分才唯一,不同插件才不可能撞出同一个链接名。
+ */
+export const GHOST_SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+
+/** manual:单插件最多声明的渐进披露手册单元数。 */
+export const GHOST_MANUAL_MAX_ITEMS = 8;
+/** manual:每个声明单元固定的入口文件名。 */
+export const GHOST_MANUAL_ENTRY_FILE = 'MANUAL.md';
+/** manual:单个 Markdown 文件的字节上限。打包与装入两侧共用。 */
+export const GHOST_MANUAL_MD_MAX_BYTES = 64 * 1024;
+/** manual:一级索引说明的字符上限。 */
+export const GHOST_MANUAL_DESCRIPTION_MAX_CHARS = GHOST_MANIFEST_SUMMARY_MAX_CHARS;
+
+/** skill 槽单条技能声明(全声明式:确认框展示的就是这里的字段)。 */
+export interface GhostSkillItem {
+ /** 包内技能目录(安全相对路径,目录内必须有 SKILL.md)。 */
+ dir: string;
+ /**
+ * 技能名。必须与 SKILL.md frontmatter 的 name 逐字一致(打包与装入双侧
+ * 强制)——确认框里用户看到的,必须就是 Agent 实际读到的。
+ */
+ name: string;
+ /** 技能说明。必须与 SKILL.md frontmatter 的 description 逐字一致(同上)。 */
+ description: string;
+}
+
+/**
+ * skill 槽详单(与 slots 含 'skill' 严格成对——有槽必有详单:捆绑了什么技能
+ * 是本能力的全部知情面,不允许"先装后说")。装入确认框逐条展示。
+ */
+export interface GhostSkillNeeds {
+ items: GhostSkillItem[];
+}
+
+/** manual 单条手册声明。name 是模型调用时使用的逻辑路径首段,dir 是包内物理目录。 */
+export interface GhostManualItem {
+ /** 包内手册目录(安全相对路径,目录内必须有 MANUAL.md)。 */
+ dir: string;
+ /** 逻辑名称;沿用 skill name 的小写连字符规则。 */
+ name: string;
+ /** ghost_info / ghost_manual 根索引展示的手册说明。 */
+ description: string;
+}
+
+/** 插件随包提供、由 Host 按需读取的渐进披露手册索引。 */
+export interface GhostManualNeeds {
+ items: GhostManualItem[];
+}
+
+/** ghost.json 清单(不变量由 validateGhostManifest 保证)。 */
+export interface GhostManifest {
+ /** 清单格式版本,恒 2(v1 声明型已于 2026-07-12 移除,无存量不留兼容)。 */
+ schemaVersion: typeof GHOST_MANIFEST_SCHEMA_VERSION;
+ /** 唯一标识,同时是安装目录名与 panelKind 后缀。 */
+ id: string;
+ /** 展示名。 */
+ name: string;
+ /** 版本字符串(不强制 semver,仅展示用)。 */
+ version: string;
+ /**
+ * 安装此 Release 所需的最低 Cindy 客户端版本。缺省表示不限制客户端版本;
+ * 声明时必须是合法 SemVer,客户端与 Plugin Server 使用同一比较语义。
+ */
+ minCindyVersion?: string;
+ /** 作者展示名(仅展示用)。 */
+ author?: string;
+ /**
+ * 宿主语言到包内 locale JSON 的映射。声明时必须提供英文资源作为固定
+ * 回退;路径须唯一,且不能与其它 manifest 文件声明冲突。
+ */
+ locales?: GhostManifestLocales;
+ /**
+ * 意识自我介绍(1–300 字,仅展示用):这段意识是干嘛
+ * 的、给谁用。装入确认框与详情页展示;与 tools[].description(给 AI 看的
+ * 工具说明)职责不同,后者不因本字段缺省而顶上。
+ */
+ description?: string;
+ /**
+ * 语义召回线索(1–300 字;给模型看,不上界面):什么场景该想起
+ * 这段意识——进 agent 会话的意识花名册。与 description 分开是因为读者不同:
+ * 描述给人看要简洁,召回线索给模型看要场景枚举、且会反复调优。缺省时
+ * 花名册回落用 description。
+ */
+ whenToUse?: string;
+ /**
+ * 图标图片(包内相对路径,装入后位于安装目录)。仅允许白名单扩展名
+ * (见 ghostIconMimeType);由 main 读盘转 data URL 随清单下发,
+ * renderer 直接 <img> 渲染——cindy-ghost:// 协议只挂沙箱分区,主窗口不走它。
+ */
+ icon?: string;
+ /**
+ * 意识形态,恒 'chip'(2026-07-12 单形态定案)。清单里可省略(同日晚间
+ * 定案:单形态后纯冗余),校验归一化补齐——消费方永远拿到 'chip'。
+ */
+ kind: 'chip';
+ /** 逻辑入口 JS(安装目录内相对路径,电子脑)。 */
+ entry: string;
+ /** 电子脑启动模式;缺省 = 'on-demand'(被需要才拉起)。 */
+ launch?: GhostLaunchMode;
+ /** Agent 新回合能力详单;须与 slots 中的 `agent` 成对。 */
+ agent?: GhostAgentNeeds;
+ /** 随包本地 Node 工作进程详单;须与 slots 中的 `node` 成对(有槽必有详单)。 */
+ node?: GhostNodeNeeds;
+ /**
+ * 设置页「自定义设置区」界面入口(可选;安装目录内相对路径,意识自绘)。
+ * 与面板同款沙箱 webview 渲染(零桥、分区断网、CSP 'self'),主题 token
+ * 由主机灌入。用户填写的 `network.secrets` 与 `node.secretBindings` 凭证
+ * 必须在此页面收单并经 `/secrets` 只写通道立即交给主机保险库,不得写入
+ * `/kv`;其它自定义参数持久化走同源 `fetch('/kv')`。
+ */
+ settingsHtml?: string;
+ /**
+ * 自定义设置区固定高度(px,可选;160–800)。缺省 = 宿主量 guest 内容
+ * 高度自适应(同区间收口);声明本字段 = 固定高度(内容动态增减的设置
+ * 页用它避免抖动)。须与 settingsHtml 成对声明。
+ */
+ settingsHeight?: number;
+ /** 能力白名单(没声明的槽,运行时接口不存在)。 */
+ slots: GhostSlot[];
+ /**
+ * card 槽能力详单(与 slots 含 'card' 成对;缺省 = 仅渲染,无外链)。
+ * externalLinks: true 时卡片内可声明 data-ghost-link,点击经宿主确认框后打开浏览器。
+ */
+ card?: GhostCardNeeds;
+ /** 注册给 agent 的工具声明(与 slots 含 'tool' 成对)。 */
+ tools?: GhostToolDecl[];
+ /**
+ * cindy 槽能力详单(与 slots 含 'cindy' 成对;缺省 = 零能力,任何代办
+ * 都会被拒并提示作者补声明)。清单里的旧字段名 model 在校验层作别名
+ * 收入本字段。
+ */
+ cindy?: GhostCindyNeeds;
+ /**
+ * 订阅槽详单(与 slots 含 'subscribe' 成对;缺省 = 零事件)。
+ * hooks 非空时 launch 必须为 'resident'(校验强制)。
+ */
+ subscribe?: GhostSubscribeNeeds;
+ /**
+ * network 槽详单(与 slots 含 'network' 成对;缺省 = 零能力)。
+ * 域名白名单 + 凭证声明,装入确认框逐项展示,运行期主机代发并守门。
+ */
+ network?: GhostNetworkNeeds;
+ /**
+ * 显式触发指令(聊天输入框 `/<command>`,与 Skill 共用命令入口;
+ * 2026-07-09 定案:由意识作者自定,装入时主机与已装意识查重,
+ * 冲突即拒)。须声明 tools——没有工具的指令无事可做。
+ */
+ command?: string;
+ /**
+ * @deprecated 语义触发扩展词表——「语言提及软提示」已于 2026-07-14 移除
+ * (普通用户无法理解凭空出现的「提及意识」胶囊),本字段不再有任何消费。
+ * 校验保留(数量/长度/单字词限制)仅为旧包装入兼容,新意识不要写,
+ * 手册(FORGE_GUIDE)已不再介绍。
+ */
+ keywords?: string[];
+ /** 面板声明;没有面板的意识(如纯工具意识)可省略。 */
+ panel?: GhostPanelDecl;
+ /**
+ * preview 槽详单(与 slots 含 'preview' 严格成对):可在右侧栏内置浏览器
+ * 打开预览标签页的域名白名单。
+ */
+ preview?: GhostPreviewNeeds;
+ /**
+ * skill 槽详单(与 slots 含 'skill' 严格成对):随包捆绑的 Agent Skills 清单。
+ * 启用时主机链接进共享技能根,Claude Code 与 Codex 双端可见;字段不参与
+ * 本地化(必须与 SKILL.md 逐字一致,见 GhostSkillItem)。
+ */
+ skill?: GhostSkillNeeds;
+ /**
+ * 随包渐进披露手册。它不是能力 slot 或授权项;Host 只把索引投影给模型,
+ * 正文经 ghost_manual 按需读取。旧客户端忽略这一可选顶层字段。
+ */
+ manual?: GhostManualNeeds;
+}
+
+/** 判断已校验的 manifest 是否请求 Host 托管的企业身份凭证。 */
+export function ghostManifestUsesOidcToken(manifest: GhostManifest): boolean {
+ return manifest.network?.secrets?.some((secret) => secret.source === 'oidc-token') ?? false;
+}
+
+/** 判断值是否可作为 `ghost.json.id` 和跨平台安全的安装目录名。 */
+export function isValidGhostId(id: unknown): id is string {
+ return typeof id === 'string' && GHOST_ID_RE.test(id) && !isWindowsReservedName(id);
+}
+
+/**
+ * 装入确认框的单项权限(逐项权限清单)。
+ * 纯数据描述:renderer 拼 `settings.ghosts.perm.<labelKey>` 翻译,`detail` 是
+ * 作者自由文本(如工具描述)如实展示不翻译,`detailKey` 是主机固定说明的
+ * i18n 后缀(如可执行代码的沙箱说明)——两者互斥。
+ */
+const GHOST_ICON_MIME_BY_EXT: Record<string, string> = {
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.webp': 'image/webp',
+ '.gif': 'image/gif',
+};
+
+/** icon 路径 → mime;扩展名不在白名单返回 null(即校验不通过)。 */
+export function ghostIconMimeType(p: string): string | null {
+ const dot = p.lastIndexOf('.');
+ if (dot < 0) return null;
+ return GHOST_ICON_MIME_BY_EXT[p.slice(dot).toLowerCase()] ?? null;
+}
+
+/**
+ * 校验"安装目录内相对路径"(entry / panel.html / settingsHtml 共用):
+ * 只允许 `a/b/c.ext` 形态——正斜杠分段、无盘符、无反斜杠、无空段、
+ * 无 `.`/`..` 段、无 Windows 设备保留名、字符集收敛,天然杜绝路径穿越
+ * 与跨平台歧义。
+ */
+const GHOST_PATH_SEGMENT_RE = /^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,63}$/;
+export function isSafeGhostRelativePath(p: unknown): p is string {
+ if (typeof p !== 'string' || p.length === 0 || p.length > 256) return false;
+ if (p.includes('\\')) return false;
+ const segments = p.split('/');
+ return segments.every(
+ (seg) =>
+ GHOST_PATH_SEGMENT_RE.test(seg) && seg !== '.' && seg !== '..' && !isWindowsReservedName(seg),
+ );
+}
+
+/** `validateGhostManifest` 的无异常校验结果。 */
+export type ManifestValidation =
+ { ok: true; manifest: GhostManifest } | { ok: false; reason: string };
+
+interface ParsedCindyVersion {
+ core: readonly [string, string, string];
+ prerelease: readonly { numeric: boolean; value: string }[];
+}
+
+function compareNumericIdentifiers(left: string, right: string): -1 | 0 | 1 {
+ if (left.length !== right.length) return left.length < right.length ? -1 : 1;
+ if (left === right) return 0;
+ return left < right ? -1 : 1;
+}
+
+function parseCindyVersion(value: string): ParsedCindyVersion | null {
+ const match =
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(
+ value,
+ );
+ if (!match) return null;
+ const core = [match[1], match[2], match[3]] as [string, string, string];
+ const prerelease: Array<{ numeric: boolean; value: string }> = [];
+ for (const part of match[4]?.split('.') ?? []) {
+ const numeric = /^\d+$/.test(part);
+ if (numeric && !/^(0|[1-9]\d*)$/.test(part)) return null;
+ prerelease.push({ numeric, value: part });
+ }
+ return { core, prerelease };
+}
+
+/** 判断值是否是可参与兼容性比较的 Cindy SemVer。 */
+export function isValidCindyVersion(value: unknown): value is string {
+ return typeof value === 'string' && value.length <= 32 && parseCindyVersion(value) !== null;
+}
+
+/** 开发构建没有正式版本号,按当前源码兼容处理。 */
+export function isVersionlessCindyVersion(value: string): boolean {
+ return value === '0.0.0' || value.startsWith('0.0.0-');
+}
+
+/** 按 SemVer 2.0.0 比较两个 Cindy 版本;任一格式非法时返回 null。 */
+export function compareCindyVersions(leftValue: string, rightValue: string): -1 | 0 | 1 | null {
+ const left = parseCindyVersion(leftValue);
+ const right = parseCindyVersion(rightValue);
+ if (!left || !right) return null;
+ for (let index = 0; index < 3; index += 1) {
+ const coreComparison = compareNumericIdentifiers(left.core[index], right.core[index]);
+ if (coreComparison !== 0) return coreComparison;
+ }
+ if (left.prerelease.length === 0 || right.prerelease.length === 0) {
+ if (left.prerelease.length === right.prerelease.length) return 0;
+ return left.prerelease.length === 0 ? 1 : -1;
+ }
+ const length = Math.max(left.prerelease.length, right.prerelease.length);
+ for (let index = 0; index < length; index += 1) {
+ const leftPart = left.prerelease[index];
+ const rightPart = right.prerelease[index];
+ if (leftPart === undefined || rightPart === undefined) {
+ return leftPart === undefined ? -1 : 1;
+ }
+ if (leftPart.numeric !== rightPart.numeric) return leftPart.numeric ? -1 : 1;
+ const partComparison = leftPart.numeric
+ ? compareNumericIdentifiers(leftPart.value, rightPart.value)
+ : leftPart.value === rightPart.value
+ ? 0
+ : leftPart.value < rightPart.value
+ ? -1
+ : 1;
+ if (partComparison !== 0) return partComparison;
+ }
+ return 0;
+}
+
+/** 缺少最低版本即不限制;非法当前版本按不兼容处理。 */
+export function supportsCindyVersion(
+ currentVersion: string,
+ minCindyVersion: string | undefined,
+): boolean {
+ if (minCindyVersion === undefined) return true;
+ if (!isValidCindyVersion(currentVersion) || !isValidCindyVersion(minCindyVersion)) return false;
+ if (isVersionlessCindyVersion(currentVersion)) return true;
+ const comparison = compareCindyVersions(currentVersion, minCindyVersion);
+ return comparison !== null && comparison >= 0;
+}
+
+function isPlainObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
+}
+
+/**
+ * 校验一份 JSON.parse 后的未知 `ghost.json` 值。宽进严出:忽略未知字段
+ * (向前兼容),已知字段全部严格检查;任何不合格都返回人类可读 reason,
+ * 不抛异常。成功结果是只包含协议已知字段的规范化 `GhostManifest`,并补齐
+ * `kind` 等有缺省语义的字段。
+ */
+export function validateGhostManifest(raw: unknown): ManifestValidation {
+ if (!isPlainObject(raw)) return { ok: false, reason: '清单不是对象' };
+
+ if (raw.schemaVersion !== GHOST_MANIFEST_SCHEMA_VERSION) {
+ return {
+ ok: false,
+ reason: `schemaVersion 必须是 ${GHOST_MANIFEST_SCHEMA_VERSION},得到 ${JSON.stringify(raw.schemaVersion)}(v1 声明型已于 2026-07-12 移除)`,
+ };
+ }
+ if (!isValidGhostId(raw.id)) {
+ return {
+ ok: false,
+ reason: 'id 必须是 1–32 位小写字母/数字/连字符(不能以连字符开头或使用 Windows 设备保留名)',
+ };
+ }
+ if (typeof raw.name !== 'string' || raw.name.trim().length === 0 || raw.name.length > 64) {
+ return { ok: false, reason: 'name 必须是 1–64 字符的非空字符串' };
+ }
+ if (
+ typeof raw.version !== 'string' ||
+ raw.version.trim().length === 0 ||
+ raw.version.length > 32
+ ) {
+ return { ok: false, reason: 'version 必须是 1–32 字符的非空字符串' };
+ }
+ if (
+ raw.minCindyVersion !== undefined &&
+ (typeof raw.minCindyVersion !== 'string' || !isValidCindyVersion(raw.minCindyVersion))
+ ) {
+ return { ok: false, reason: 'minCindyVersion 必须是合法的 SemVer 字符串' };
+ }
+ // kind 可省略(2026-07-12 晚定案:单形态后字段纯冗余,缺省即 chip);
+ // 写了就必须是 chip——写错值仍拒,不静默纠正(规则 9)。
+ if (raw.kind !== undefined && raw.kind !== 'chip') {
+ return {
+ ok: false,
+ reason: `kind 必须是 "chip" 或省略(缺省即 chip),得到 ${JSON.stringify(raw.kind)}(意识只有芯片一种形态,declaration 已移除)`,
+ };
+ }
+ if (
+ raw.author !== undefined &&
+ (typeof raw.author !== 'string' || raw.author.trim().length === 0 || raw.author.length > 64)
+ ) {
+ return { ok: false, reason: 'author 必须是 1–64 字符的非空字符串' };
+ }
+ const declaredFilePathFolds = [
+ GHOST_MANIFEST_FILE,
+ raw.entry,
+ raw.icon,
+ raw.settingsHtml,
+ isPlainObject(raw.panel) ? raw.panel.html : undefined,
+ isPlainObject(raw.node) ? raw.node.entry : undefined,
+ ...(isPlainObject(raw.node) && Array.isArray(raw.node.entries) ? raw.node.entries : []),
+ ]
+ .filter((value): value is string => typeof value === 'string')
+ .map((value) => value.toLowerCase());
+ const isSameOrDescendant = (path: string, ancestor: string): boolean =>
+ path === ancestor || path.startsWith(`${ancestor}/`);
+ const pathsConflict = (left: string, right: string): boolean =>
+ isSameOrDescendant(left, right) || isSameOrDescendant(right, left);
+ let locales: GhostManifest['locales'];
+ if (raw.locales !== undefined) {
+ if (!isPlainObject(raw.locales)) {
+ return { ok: false, reason: 'locales 必须是语言到 locale JSON 路径的对象' };
+ }
+ const unknownLocale = Object.keys(raw.locales).find(
+ (locale) => !(GHOST_LOCALES as readonly string[]).includes(locale),
+ );
+ if (unknownLocale) {
+ return {
+ ok: false,
+ reason: `locales 含宿主不支持的语言 ${JSON.stringify(unknownLocale)}(可用:${GHOST_LOCALES.join(' / ')})`,
+ };
+ }
+ if (raw.locales.en === undefined) {
+ return { ok: false, reason: 'locales 必须提供 en,作为所有不支持语言的固定回退' };
+ }
+ const normalized: Partial<Record<GhostLocale, string>> = {};
+ const seenPaths: string[] = [];
+ const skillDirFolds = (
+ isPlainObject(raw.skill) && Array.isArray(raw.skill.items) ? raw.skill.items : []
+ )
+ .map((item) => (isPlainObject(item) ? item.dir : undefined))
+ .filter((value): value is string => typeof value === 'string')
+ .map((value) => value.toLowerCase());
+ const manualDirFolds = (
+ isPlainObject(raw.manual) && Array.isArray(raw.manual.items) ? raw.manual.items : []
+ )
+ .map((item) => (isPlainObject(item) ? item.dir : undefined))
+ .filter((value): value is string => typeof value === 'string')
+ .map((value) => value.toLowerCase());
+ for (const locale of GHOST_LOCALES) {
+ const localePath = raw.locales[locale];
+ if (localePath === undefined) continue;
+ if (
+ typeof localePath !== 'string' ||
+ !isSafeGhostRelativePath(localePath) ||
+ !localePath.toLowerCase().endsWith('.json')
+ ) {
+ return {
+ ok: false,
+ reason: `locales.${locale} 必须是安装目录内以 .json 结尾的安全相对路径`,
+ };
+ }
+ const normalizedLocalePath = localePath.toLowerCase();
+ const conflictsWithFile = declaredFilePathFolds.some((path) =>
+ pathsConflict(path, normalizedLocalePath),
+ );
+ const conflictsWithSkillDir = skillDirFolds.some((dir) =>
+ isSameOrDescendant(dir, normalizedLocalePath),
+ );
+ const conflictsWithManualDir = manualDirFolds.some((dir) =>
+ pathsConflict(dir, normalizedLocalePath),
+ );
+ if (conflictsWithFile || conflictsWithSkillDir || conflictsWithManualDir) {
+ return {
+ ok: false,
+ reason: `locales.${locale} 路径 ${JSON.stringify(localePath)} 与插件其他声明文件大小写折叠后冲突`,
+ };
+ }
+ if (seenPaths.includes(normalizedLocalePath)) {
+ return { ok: false, reason: `locales 含重复路径 ${JSON.stringify(localePath)}` };
+ }
+ if (
+ seenPaths.some(
+ (path) =>
+ isSameOrDescendant(path, normalizedLocalePath) ||
+ isSameOrDescendant(normalizedLocalePath, path),
+ )
+ ) {
+ return {
+ ok: false,
+ reason: `locales.${locale} 路径 ${JSON.stringify(localePath)} 与其他 locale 文件存在祖先路径冲突`,
+ };
+ }
+ seenPaths.push(normalizedLocalePath);
+ normalized[locale] = localePath;
+ }
+ locales = {
+ ...normalized,
+ en: normalized.en!,
+ };
+ }
+ if (
+ raw.description !== undefined &&
+ (typeof raw.description !== 'string' ||
+ raw.description.trim().length === 0 ||
+ raw.description.length > GHOST_MANIFEST_SUMMARY_MAX_CHARS)
+ ) {
+ return {
+ ok: false,
+ reason: `description 必须是 1–${GHOST_MANIFEST_SUMMARY_MAX_CHARS} 字符的非空字符串`,
+ };
+ }
+ if (
+ raw.whenToUse !== undefined &&
+ (typeof raw.whenToUse !== 'string' ||
+ raw.whenToUse.trim().length === 0 ||
+ raw.whenToUse.length > GHOST_MANIFEST_SUMMARY_MAX_CHARS)
+ ) {
+ return {
+ ok: false,
+ reason: `whenToUse 必须是 1–${GHOST_MANIFEST_SUMMARY_MAX_CHARS} 字符的非空字符串`,
+ };
+ }
+ if (raw.icon !== undefined) {
+ if (!isSafeGhostRelativePath(raw.icon)) {
+ return { ok: false, reason: 'icon 必须是安装目录内的安全相对路径' };
+ }
+ if (ghostIconMimeType(raw.icon) === null) {
+ return {
+ ok: false,
+ reason: `icon 扩展名不受支持(可用:${Object.keys(GHOST_ICON_MIME_BY_EXT).join(' / ')})`,
+ };
+ }
+ }
+ let panel: GhostPanelDecl | undefined;
+ if (raw.panel !== undefined) {
+ const p = raw.panel;
+ if (!isPlainObject(p)) return { ok: false, reason: 'panel 必须是对象' };
+ if (
+ p.title !== undefined &&
+ (typeof p.title !== 'string' || p.title.length === 0 || p.title.length > 64)
+ ) {
+ return { ok: false, reason: 'panel.title 必须是 1–64 字符的字符串' };
+ }
+ // 面板一律由意识自绘(html 必填):declaration 时代的静态 body 面板已随
+ // 单形态定案(2026-07-12)移除。
+ if (!isSafeGhostRelativePath(p.html)) {
+ return { ok: false, reason: 'panel.html 必填,且必须是安装目录内的安全相对路径' };
+ }
+ if (
+ p.minWidth !== undefined &&
+ (typeof p.minWidth !== 'number' ||
+ !Number.isFinite(p.minWidth) ||
+ p.minWidth < 120 ||
+ p.minWidth > 1200)
+ ) {
+ return { ok: false, reason: 'panel.minWidth 必须是 120–1200 之间的数字' };
+ }
+ if (
+ p.defaultFraction !== undefined &&
+ (typeof p.defaultFraction !== 'number' ||
+ !Number.isFinite(p.defaultFraction) ||
+ p.defaultFraction < 0.05 ||
+ p.defaultFraction > 0.8)
+ ) {
+ return { ok: false, reason: 'panel.defaultFraction 必须是 0.05–0.8 之间的数字' };
+ }
+ if (p.position !== undefined) {
+ if (p.position === 'top' || p.position === 'bottom') {
+ // 收词但明确拒绝(规则 9 不静默降级):上下停靠等布局引擎嵌套分割就绪后开放。
+ return {
+ ok: false,
+ reason: 'panel.position 的 top / bottom 暂未支持(排期中),当前可用:left / right / tab',
+ };
+ }
+ if (!(GHOST_PANEL_POSITIONS as readonly string[]).includes(p.position as string)) {
+ return { ok: false, reason: `panel.position 必须是 ${GHOST_PANEL_POSITIONS.join(' / ')}` };
+ }
+ // 页签形态没有拖缝宽度语义:收词明确拒绝而非静默忽略(规则 9)。
+ if (p.position === 'tab' && (p.minWidth !== undefined || p.defaultFraction !== undefined)) {
+ return {
+ ok: false,
+ reason:
+ "panel.minWidth / panel.defaultFraction 仅停靠形态(left / right)有效,position:'tab' 时请移除",
+ };
+ }
+ }
+ panel = {
+ ...(p.title !== undefined ? { title: p.title as string } : {}),
+ ...(p.position !== undefined ? { position: p.position as GhostPanelPosition } : {}),
+ html: p.html as string,
+ ...(p.minWidth !== undefined ? { minWidth: p.minWidth as number } : {}),
+ ...(p.defaultFraction !== undefined ? { defaultFraction: p.defaultFraction as number } : {}),
+ };
+ }
+
+ if (!isSafeGhostRelativePath(raw.entry)) {
+ return { ok: false, reason: '必须提供 entry(安装目录内的安全相对路径,电子脑逻辑入口)' };
+ }
+ if (
+ raw.launch !== undefined &&
+ !(GHOST_LAUNCH_MODES as readonly string[]).includes(raw.launch as string)
+ ) {
+ return { ok: false, reason: `launch 必须是 ${GHOST_LAUNCH_MODES.join(' / ')}` };
+ }
+ if (raw.settingsHtml !== undefined && !isSafeGhostRelativePath(raw.settingsHtml)) {
+ return { ok: false, reason: 'settingsHtml 必须是安装目录内的安全相对路径' };
+ }
+ if (raw.settingsHeight !== undefined) {
+ if (raw.settingsHtml === undefined) {
+ return {
+ ok: false,
+ reason: '声明了 settingsHeight 但没有 settingsHtml——没有界面就没有高度可言',
+ };
+ }
+ if (
+ typeof raw.settingsHeight !== 'number' ||
+ !Number.isFinite(raw.settingsHeight) ||
+ raw.settingsHeight < 160 ||
+ raw.settingsHeight > 800
+ ) {
+ return { ok: false, reason: 'settingsHeight 必须是 160–800 之间的数字' };
+ }
+ }
+ if (!Array.isArray(raw.slots) || raw.slots.length === 0) {
+ return { ok: false, reason: '必须声明 slots(非空数组,能力白名单)' };
+ }
+ const slots: GhostSlot[] = [];
+ for (const s of raw.slots) {
+ // 旧名兼容:'model' 静默归一化为 'cindy'(2026-07-11 更名,已装老包不消失)。
+ const name = s === 'model' ? 'cindy' : s;
+ if (typeof name !== 'string' || !(GHOST_SLOTS as readonly string[]).includes(name)) {
+ return {
+ ok: false,
+ reason: `slots 含未知卡槽 ${JSON.stringify(s)}(可用:${GHOST_SLOTS.join(' / ')})`,
+ };
+ }
+ if (slots.includes(name as GhostSlot)) {
+ return { ok: false, reason: `slots 含重复卡槽 ${JSON.stringify(s)}` };
+ }
+ slots.push(name as GhostSlot);
+ }
+ // 该槽依赖新增的 Host 原生能力,旧 Cindy 不可能安全降级为“只装插件但忽略
+ // 模拟器”。强制声明最低版本,让 Plugin Server 在目录/详情/下载三条路径上
+ // 都不向旧客户端交付这份 Release。
+ if (slots.includes('ios-simulator') && raw.minCindyVersion === undefined) {
+ return {
+ ok: false,
+ reason: 'slots 声明了 "ios-simulator" 时必须同时声明 minCindyVersion',
+ };
+ }
+ // 声明了面板却没申请 panel 槽(或反之有槽无面板)都是清单自相矛盾。
+ if (panel !== undefined && !slots.includes('panel')) {
+ return { ok: false, reason: '声明了 panel 但 slots 未包含 "panel"' };
+ }
+ if (slots.includes('panel') && panel === undefined) {
+ return { ok: false, reason: 'slots 声明了 "panel" 但缺少 panel(面板由意识自绘,html 必填)' };
+ }
+ if (slots.includes('badge') && panel === undefined) {
+ return {
+ ok: false,
+ reason: 'slots 声明了 "badge" 但缺少 panel——未读点必须有可打开的面板内容',
+ };
+ }
+
+ // card 槽能力详单:缺省 = 仅渲染;externalLinks: true 是独立加档权限。
+ let card: GhostCardNeeds | undefined;
+ if (raw.card !== undefined) {
+ if (!isPlainObject(raw.card)) {
+ return { ok: false, reason: 'card 能力详单必须是对象(如 { "externalLinks": true })' };
+ }
+ if (!slots.includes('card')) {
+ return { ok: false, reason: '声明了 card 能力详单但 slots 未包含 "card"' };
+ }
+ const cardRaw = raw.card as Record<string, unknown>;
+ const unknownCardField = Object.keys(cardRaw).find((key) => key !== 'externalLinks');
+ if (unknownCardField) {
+ return { ok: false, reason: `card 含不允许的字段 ${JSON.stringify(unknownCardField)}` };
+ }
+ if (cardRaw.externalLinks !== undefined && typeof cardRaw.externalLinks !== 'boolean') {
+ return { ok: false, reason: 'card.externalLinks 必须是布尔值' };
+ }
+ if (cardRaw.externalLinks === true) {
+ card = { externalLinks: true };
+ }
+ }
+
+ // 工具声明(卡槽②):与 slots 含 'tool' 严格成对,规则同 panel。
+ let tools: GhostToolDecl[] | undefined;
+ if (raw.tools !== undefined) {
+ if (!Array.isArray(raw.tools) || raw.tools.length === 0 || raw.tools.length > 16) {
+ return { ok: false, reason: 'tools 必须是 1–16 项的数组' };
+ }
+ tools = [];
+ const seenNames = new Set<string>();
+ for (const t of raw.tools) {
+ if (!isPlainObject(t)) return { ok: false, reason: 'tools 每项必须是对象' };
+ if (typeof t.name !== 'string' || !/^[a-z][a-z0-9_-]{0,63}$/.test(t.name)) {
+ return {
+ ok: false,
+ reason: 'tools[].name 必须是小写字母开头的 1–64 位小写/数字/下划线/连字符',
+ };
+ }
+ if (seenNames.has(t.name))
+ return { ok: false, reason: `tools 含重名工具 ${JSON.stringify(t.name)}` };
+ seenNames.add(t.name);
+ if (
+ typeof t.description !== 'string' ||
+ t.description.trim().length === 0 ||
+ t.description.length > 1024
+ ) {
+ return { ok: false, reason: 'tools[].description 必须是 1–1024 字符的非空字符串' };
+ }
+ if (t.parameters !== undefined) {
+ if (!isPlainObject(t.parameters))
+ return { ok: false, reason: 'tools[].parameters 必须是对象(JSON Schema)' };
+ try {
+ if (JSON.stringify(t.parameters).length > 16_384) {
+ return { ok: false, reason: 'tools[].parameters 过大(上限 16KB)' };
+ }
+ } catch {
+ return { ok: false, reason: 'tools[].parameters 必须可序列化' };
+ }
+ }
+ tools.push({
+ name: t.name,
+ description: t.description,
+ ...(t.parameters !== undefined
+ ? { parameters: t.parameters as Record<string, unknown> }
+ : {}),
+ });
+ }
+ }
+ if (tools !== undefined && !slots.includes('tool')) {
+ return { ok: false, reason: '声明了 tools 但 slots 未包含 "tool"' };
+ }
+ if (slots.includes('tool') && tools === undefined) {
+ return { ok: false, reason: 'slots 声明了 "tool" 但缺少 tools(注册什么工具要写清楚)' };
+ }
+
+ // cindy 槽能力详单:与 slots 含 'cindy' 成对(有详单必有槽;有槽无详单
+ // 允许装入但运行时零能力——老包不消失,只是代办被拒并提示作者更新)。
+ // 字段旧名 model 作别名收入(两个都写以 cindy 为准)。
+ const cindyRaw = raw.cindy !== undefined ? raw.cindy : raw.model;
+ let cindy: GhostCindyNeeds | undefined;
+ if (cindyRaw !== undefined) {
+ if (!isPlainObject(cindyRaw)) {
+ return { ok: false, reason: 'cindy 能力详单必须是对象(如 { "image": ["generate"] })' };
+ }
+ if (!slots.includes('cindy')) {
+ return { ok: false, reason: '声明了 cindy 能力详单但 slots 未包含 "cindy"' };
+ }
+ cindy = {};
+ // 类目 → 合法动作表(image / video / media / text / embed / search;动作集恰好
+ // 同名,但按类目查表,未来某类目动作分叉时这里天然承接)。
+ const actionTable: Record<string, readonly string[]> = {
+ image: GHOST_MODEL_IMAGE_ACTIONS,
+ video: GHOST_MODEL_VIDEO_ACTIONS,
+ media: GHOST_CINDY_MEDIA_ACTIONS,
+ text: GHOST_CINDY_TEXT_ACTIONS,
+ embed: GHOST_CINDY_EMBED_ACTIONS,
+ search: GHOST_CINDY_SEARCH_ACTIONS,
+ };
+ for (const [category, actionsRaw] of Object.entries(cindyRaw)) {
+ if (category === 'oneshotModel') continue; // 标量意图键,不是类目,单独校验
+ const allowed = actionTable[category];
+ if (!allowed) {
+ return {
+ ok: false,
+ reason: `cindy 含未知能力类目 ${JSON.stringify(category)}(当前支持:${Object.keys(actionTable).join(' / ')})`,
+ };
+ }
+ if (!Array.isArray(actionsRaw) || actionsRaw.length === 0) {
+ return { ok: false, reason: `cindy.${category} 必须是非空数组` };
+ }
+ const actions: string[] = [];
+ for (const a of actionsRaw) {
+ if (typeof a !== 'string' || !allowed.includes(a)) {
+ return {
+ ok: false,
+ reason: `cindy.${category} 含未知动作 ${JSON.stringify(a)}(可用:${allowed.join(' / ')})`,
+ };
+ }
+ if (actions.includes(a)) {
+ return { ok: false, reason: `cindy.${category} 含重复动作 ${JSON.stringify(a)}` };
+ }
+ actions.push(a);
+ }
+ if (category === 'image') cindy.image = actions as GhostModelImageAction[];
+ else if (category === 'video') cindy.video = actions as GhostModelVideoAction[];
+ else if (category === 'media') cindy.media = actions as GhostCindyMediaAction[];
+ else if (category === 'text') cindy.text = actions as GhostCindyTextAction[];
+ else if (category === 'embed') cindy.embed = actions as GhostCindyEmbedAction[];
+ else if (category === 'search') cindy.search = actions as GhostCindySearchAction[];
+ else
+ return {
+ ok: false,
+ reason: `cindy 能力类目 ${JSON.stringify(category)} 尚未接线(协议缺陷)`,
+ };
+ }
+ if (
+ cindy.image === undefined &&
+ cindy.video === undefined &&
+ cindy.media === undefined &&
+ cindy.text === undefined &&
+ cindy.embed === undefined &&
+ cindy.search === undefined
+ ) {
+ return { ok: false, reason: 'cindy 能力详单不能是空对象' };
+ }
+ // oneshotModel(快问快答偏好模型)是标量意图键,不是类目:先摘出,不进类目循环。
+ const oneshotModelRaw = cindyRaw.oneshotModel;
+ if (oneshotModelRaw !== undefined) {
+ if (
+ typeof oneshotModelRaw !== 'string' ||
+ oneshotModelRaw.trim().length === 0 ||
+ oneshotModelRaw.length > 128
+ ) {
+ return {
+ ok: false,
+ reason: 'cindy.oneshotModel 必须是 1–128 字符的目录模型 id(如 "codex/gpt-5.5")',
+ };
+ }
+ if (!cindy.text?.includes('oneshot')) {
+ return {
+ ok: false,
+ reason: 'cindy.oneshotModel 必须与 text 含 "oneshot" 成对声明(它是快问快答的偏好模型)',
+ };
+ }
+ cindy.oneshotModel = oneshotModelRaw.trim();
+ }
+ if (cindy.search?.includes('web') && (!slots.includes('tool') || tools === undefined)) {
+ return {
+ ok: false,
+ reason: 'cindy.search.web 只允许由真实 tool-call 触发,必须同时声明 "tool" 槽和 tools',
+ };
+ }
+ }
+
+ // 订阅槽详单(卡槽①):与 slots 含 'subscribe' 成对(有详单必有槽;有槽
+ // 无详单允许装入但零事件,同 cindy 语义)。硬规则:声明了 hooks(拦截)
+ // 必须 launch:'resident'——要挡路就得常驻在场,每条消息等冷启动不可接受。
+ let subscribe: GhostSubscribeNeeds | undefined;
+ if (raw.subscribe !== undefined) {
+ if (!isPlainObject(raw.subscribe)) {
+ return { ok: false, reason: 'subscribe 订阅详单必须是对象(如 { "topics": ["turn"] })' };
+ }
+ if (!slots.includes('subscribe')) {
+ return { ok: false, reason: '声明了 subscribe 订阅详单但 slots 未包含 "subscribe"' };
+ }
+ subscribe = {};
+ const subRaw = raw.subscribe as Record<string, unknown>;
+ for (const [field, allowed] of [
+ ['topics', GHOST_SUBSCRIBE_TOPICS],
+ ['hooks', GHOST_SUBSCRIBE_HOOKS],
+ ] as const) {
+ const listRaw = subRaw[field];
+ if (listRaw === undefined) continue;
+ if (!Array.isArray(listRaw) || listRaw.length === 0) {
+ return { ok: false, reason: `subscribe.${field} 必须是非空数组` };
+ }
+ const list: string[] = [];
+ for (const item of listRaw) {
+ if (typeof item !== 'string' || !(allowed as readonly string[]).includes(item)) {
+ return {
+ ok: false,
+ reason: `subscribe.${field} 含未知项 ${JSON.stringify(item)}(可用:${allowed.join(' / ')})`,
+ };
+ }
+ if (list.includes(item)) {
+ return { ok: false, reason: `subscribe.${field} 含重复项 ${JSON.stringify(item)}` };
+ }
+ list.push(item);
+ }
+ if (field === 'topics') subscribe.topics = list as GhostSubscribeTopic[];
+ else subscribe.hooks = list as GhostSubscribeHook[];
+ }
+ if (subscribe.topics === undefined && subscribe.hooks === undefined) {
+ return { ok: false, reason: 'subscribe 订阅详单不能是空对象' };
+ }
+ if (subscribe.hooks !== undefined && raw.launch !== 'resident') {
+ return {
+ ok: false,
+ reason:
+ '声明了 subscribe.hooks(拦截钩子)必须同时声明 launch: "resident"——拦截要求常驻在场,否则每条消息都要等冷启动',
+ };
+ }
+ }
+
+ // network 槽详单:与 slots 含 'network' 成对(有详单必有槽;有槽
+ // 无详单允许装入但零能力,同 cindy / subscribe 语义)。hosts 是核心声明;
+ // secrets 每条必须带 inject(没有注入位置的凭证无处可用),inject.hosts
+ // 必须是 hosts 声明条目的子集——结构上钉死"key 只流向它声明的域名"。
+ let network: GhostNetworkNeeds | undefined;
+ if (raw.network !== undefined) {
+ if (!isPlainObject(raw.network)) {
+ return { ok: false, reason: 'network 详单必须是对象(如 { "hosts": ["api.example.com"] })' };
+ }
+ if (!slots.includes('network')) {
+ return { ok: false, reason: '声明了 network 详单但 slots 未包含 "network"' };
+ }
+ const n = raw.network as Record<string, unknown>;
+ // 连接声明在场性先探一眼(合法性下面细验):静态 hosts 的必填性依赖它——
+ // 声明了 connections(动态连接地址)时 hosts 允许缺省/空数组,否则维持
+ // 原规则必填 1–8 条(静态域名与动态连接至少有其一)。
+ const hasConnectionDecls = Array.isArray(n.connections) && n.connections.length > 0;
+ if (n.hosts === undefined && !hasConnectionDecls) {
+ return {
+ ok: false,
+ reason: `network.hosts 必须是 1–${GHOST_NETWORK_MAX_HOSTS} 条的数组(仅声明了 network.connections 时才可缺省)`,
+ };
+ }
+ if (
+ n.hosts !== undefined &&
+ (!Array.isArray(n.hosts) || n.hosts.length > GHOST_NETWORK_MAX_HOSTS)
+ ) {
+ return { ok: false, reason: `network.hosts 必须是 1–${GHOST_NETWORK_MAX_HOSTS} 条的数组` };
+ }
+ if (Array.isArray(n.hosts) && n.hosts.length === 0 && !hasConnectionDecls) {
+ return {
+ ok: false,
+ reason: `network.hosts 必须是 1–${GHOST_NETWORK_MAX_HOSTS} 条的数组(仅声明了 network.connections 时才允许为空)`,
+ };
+ }
+ const hosts: string[] = [];
+ for (const h of Array.isArray(n.hosts) ? n.hosts : []) {
+ if (typeof h !== 'string' || !isValidGhostNetworkHostPattern(h.trim().toLowerCase())) {
+ return {
+ ok: false,
+ reason: `network.hosts 含非法条目 ${JSON.stringify(h)}(小写域名、至少两段、通配只允许最左 "*.";不收 IP / 端口 / 路径 / 协议)`,
+ };
+ }
+ const host = h.trim().toLowerCase();
+ if (hosts.includes(host)) {
+ return { ok: false, reason: `network.hosts 含重复条目 ${JSON.stringify(h)}` };
+ }
+ hosts.push(host);
+ }
+ let secrets: GhostSecretDecl[] | undefined;
+ if (n.secrets !== undefined) {
+ if (
+ !Array.isArray(n.secrets) ||
+ n.secrets.length === 0 ||
+ n.secrets.length > GHOST_NETWORK_MAX_SECRETS
+ ) {
+ return {
+ ok: false,
+ reason: `network.secrets 必须是 1–${GHOST_NETWORK_MAX_SECRETS} 条的数组`,
+ };
+ }
+ secrets = [];
+ const seenKeys = new Set<string>();
+ for (const s of n.secrets) {
+ if (!isPlainObject(s)) return { ok: false, reason: 'network.secrets 每项必须是对象' };
+ if (typeof s.key !== 'string' || !/^[a-z][a-z0-9_]{0,31}$/.test(s.key)) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].key 必须是小写字母开头的 1–32 位小写/数字/下划线',
+ };
+ }
+ if (seenKeys.has(s.key)) {
+ return { ok: false, reason: `network.secrets 含重复 key ${JSON.stringify(s.key)}` };
+ }
+ seenKeys.add(s.key);
+ if (typeof s.label !== 'string' || s.label.trim().length === 0 || s.label.length > 64) {
+ return { ok: false, reason: 'network.secrets[].label 必须是 1–64 字符的非空字符串' };
+ }
+ // 来源:缺省 'user';'login-email' = 主机登录邮箱派生(用户不填值)。
+ // 归一化:'user' 不落清单(与缺省同义,权限 diff 不 churn)。
+ let source: GhostSecretSource | undefined;
+ if (s.source !== undefined) {
+ if (
+ typeof s.source !== 'string' ||
+ !(GHOST_SECRET_SOURCES as readonly string[]).includes(s.source)
+ ) {
+ return {
+ ok: false,
+ reason: `network.secrets[].source 仅支持 ${GHOST_SECRET_SOURCES.join(' / ')}(缺省 user)`,
+ };
+ }
+ if (s.source === 'login-email') source = 'login-email';
+ if (s.source === 'oauth') source = 'oauth';
+ if (s.source === 'login-feishu-token') source = 'login-feishu-token';
+ if (s.source === 'oidc-token') source = 'oidc-token';
+ if (s.source === 'gh-cli') source = 'gh-cli';
+ }
+ // 输入面字段已退役(2026-07-13 宿主凭证渲染整体退役):user 凭证
+ // 一律意识 settingsHtml 收单。遗留 `input: "ghost"` 接受并忽略
+ // (与现状同义、不落清单);其余值(含 'host')一律拒。
+ if (s.input !== undefined && s.input !== 'ghost') {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].input 已退役:宿主收单不存在,用户填写的凭证一律由意识 settingsHtml 收单(删掉 input 字段即可;唯一可接受的遗留值是 "ghost")',
+ };
+ }
+ // login-email / login-feishu-token 同族:值取自主机登录态派生,用户
+ // 不填、没有输入面,禁 url / exchange,settingsHtml 豁免。oidc-token
+ // 同样由 Host 托管,但值来自当前组织 Membership 的 Connection JWT。
+ const loginDerived = source === 'login-email' || source === 'login-feishu-token';
+ const oidcManaged = source === 'oidc-token';
+ const ghCliManaged = source === 'gh-cli';
+ if (s.input === 'ghost' && (loginDerived || oidcManaged || ghCliManaged)) {
+ return {
+ ok: false,
+ reason: `source: ${source} 的凭证不允许标注 input: ghost(Host 托管凭证没有输入,谈不上谁收单)`,
+ };
+ }
+ if (!loginDerived && !oidcManaged && raw.settingsHtml === undefined) {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets 声明了用户填写的凭证时必须同时声明 settingsHtml(凭证由意识设置界面收单,没有界面就没人收单;宿主渲染输入行已退役)',
+ };
+ }
+ if (loginDerived && s.url !== undefined) {
+ return {
+ ok: false,
+ reason: `network.secrets[].source 为 ${source} 时不允许声明 url(值取自主机登录态,没有"前往控制台"可去)`,
+ };
+ }
+ if (loginDerived && s.exchange !== undefined) {
+ // 组合会把登录态凭证作为原始值 POST 给交换端点,而确认框文案只
+ // 承诺"派生注入请求头"——语义盖不住,结构上禁掉(有真实场景再议)。
+ return {
+ ok: false,
+ reason: `network.secrets[].source 为 ${source} 时不允许声明 exchange(登录态凭证不外送交换端点)`,
+ };
+ }
+ if (oidcManaged && s.url !== undefined) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].source 为 oidc-token 时不允许声明 url(令牌由 Host 按需签发)',
+ };
+ }
+ if (oidcManaged && s.exchange !== undefined) {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].source 为 oidc-token 时不允许声明 exchange(不允许把 Connection JWT 转交给第三方端点)',
+ };
+ }
+ if (ghCliManaged && s.exchange !== undefined) {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].source 为 gh-cli 时不允许声明 exchange(不允许把 GitHub 登录令牌转交给第三方端点)',
+ };
+ }
+ if (
+ s.hint !== undefined &&
+ (typeof s.hint !== 'string' || s.hint.trim().length === 0 || s.hint.length > 200)
+ ) {
+ return { ok: false, reason: 'network.secrets[].hint 必须是 1–200 字符的非空字符串' };
+ }
+ if (s.url !== undefined) {
+ if (typeof s.url !== 'string' || s.url.length === 0 || s.url.length > 200) {
+ return { ok: false, reason: 'network.secrets[].url 必须是 1–200 字符的字符串' };
+ }
+ let parsed: URL;
+ try {
+ parsed = new URL(s.url);
+ } catch {
+ return { ok: false, reason: 'network.secrets[].url 不是合法的绝对地址' };
+ }
+ if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].url 仅支持 https 且不允许内嵌用户名/密码',
+ };
+ }
+ }
+ if (!isPlainObject(s.inject)) {
+ return {
+ ok: false,
+ reason: `network.secrets[${JSON.stringify(s.key)}].inject 必填(凭证要声明注入到哪个请求头)`,
+ };
+ }
+ const inj = s.inject as Record<string, unknown>;
+ if (typeof inj.header !== 'string' || !/^[A-Za-z0-9-]{1,64}$/.test(inj.header)) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].inject.header 必须是 1–64 位字母/数字/连字符的头名',
+ };
+ }
+ if (GHOST_NETWORK_FORBIDDEN_INJECT_HEADERS.includes(inj.header.toLowerCase())) {
+ return {
+ ok: false,
+ reason: `network.secrets[].inject.header 不允许使用协议关键头 ${JSON.stringify(inj.header)}`,
+ };
+ }
+ if (
+ typeof inj.format !== 'string' ||
+ inj.format.length === 0 ||
+ inj.format.length > 200 ||
+ inj.format.split('{value}').length !== 2
+ ) {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].inject.format 必须是 ≤200 字符且恰含一个 {value} 占位的字符串(如 "Bearer {value}")',
+ };
+ }
+ let injectHosts: string[] | undefined;
+ if (inj.hosts !== undefined) {
+ if (!Array.isArray(inj.hosts) || inj.hosts.length === 0) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].inject.hosts 必须是非空数组(或省略 = 全部白名单域名)',
+ };
+ }
+ injectHosts = [];
+ for (const ih of inj.hosts) {
+ if (typeof ih !== 'string' || !hosts.includes(ih.trim().toLowerCase())) {
+ return {
+ ok: false,
+ reason: `network.secrets[].inject.hosts 含 ${JSON.stringify(ih)}——必须逐字取自 network.hosts 声明条目`,
+ };
+ }
+ const ihNorm = ih.trim().toLowerCase();
+ if (injectHosts.includes(ihNorm)) {
+ return {
+ ok: false,
+ reason: `network.secrets[].inject.hosts 含重复条目 ${JSON.stringify(ih)}`,
+ };
+ }
+ injectHosts.push(ihNorm);
+ }
+ }
+ if (oidcManaged) {
+ if (inj.header !== 'Authorization' || inj.format !== 'Bearer {value}') {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].source 为 oidc-token 时 inject 必须是 Authorization: Bearer {value}',
+ };
+ }
+ if (injectHosts === undefined || injectHosts.length === 0) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].source 为 oidc-token 时必须显式声明非空 inject.hosts',
+ };
+ }
+ if (injectHosts.some((host) => host.startsWith('*.'))) {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].source 为 oidc-token 时 inject.hosts 只允许精确域名,不允许通配',
+ };
+ }
+ }
+ if (ghCliManaged) {
+ if (inj.header !== 'Authorization' || inj.format !== 'Bearer {value}') {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].source 为 gh-cli 时 inject 必须是 Authorization: Bearer {value}',
+ };
+ }
+ if (
+ injectHosts === undefined ||
+ injectHosts.length !== 1 ||
+ injectHosts[0] !== 'api.github.com'
+ ) {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].source 为 gh-cli 时 inject.hosts 必须且只能是 api.github.com',
+ };
+ }
+ }
+ // oauth(source: 'oauth' 时必填):主机托管 OAuth 授权详单。授权页与
+ // token 端点域名都必须落在 hosts 白名单内——确认框展示的域名集合就是
+ // 全部出网面(clientSecret 只流向 tokenUrl,授权只发生在 authorizeUrl)。
+ let oauth: GhostSecretOauthDecl | undefined;
+ if (source === 'oauth' && s.oauth === undefined) {
+ return {
+ ok: false,
+ reason: `network.secrets[${JSON.stringify(s.key)}].oauth 必填(source: oauth 的凭证要声明去哪授权)`,
+ };
+ }
+ if (source !== 'oauth' && s.oauth !== undefined) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].oauth 仅允许在 source: oauth 的凭证上声明',
+ };
+ }
+ if (source === 'oauth' && s.exchange !== undefined) {
+ // access token 已是最终注入物,再叠一段 key 换令牌没有语义。
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].source 为 oauth 时不允许声明 exchange(access token 直接注入,无二段交换)',
+ };
+ }
+ if (s.oauth !== undefined) {
+ if (!isPlainObject(s.oauth)) {
+ return {
+ ok: false,
+ reason: `network.secrets[${JSON.stringify(s.key)}].oauth 必须是对象`,
+ };
+ }
+ const oa = s.oauth as Record<string, unknown>;
+ const parseHostBoundUrl = (
+ raw2: unknown,
+ field: string,
+ ): { ok: true; url: string } | { ok: false; reason: string } => {
+ if (typeof raw2 !== 'string' || raw2.length === 0 || raw2.length > 2048) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.${field} 必须是 1–2048 字符的字符串`,
+ };
+ }
+ let parsed2: URL;
+ try {
+ parsed2 = new URL(raw2);
+ } catch {
+ return { ok: false, reason: `network.secrets[].oauth.${field} 不是合法的绝对地址` };
+ }
+ if (
+ parsed2.protocol !== 'https:' ||
+ parsed2.port !== '' ||
+ parsed2.username ||
+ parsed2.password
+ ) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.${field} 仅支持 https 默认端口且不允许内嵌用户名/密码`,
+ };
+ }
+ if (!hosts.some((pattern) => ghostNetworkHostMatches(pattern, parsed2.hostname))) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.${field} 的域名 ${JSON.stringify(parsed2.hostname)} 必须命中 network.hosts 白名单`,
+ };
+ }
+ return { ok: true, url: raw2 };
+ };
+ const authorizeParsed = parseHostBoundUrl(oa.authorizeUrl, 'authorizeUrl');
+ if (!authorizeParsed.ok) return authorizeParsed;
+ const tokenParsed = parseHostBoundUrl(oa.tokenUrl, 'tokenUrl');
+ if (!tokenParsed.ok) return tokenParsed;
+ // 内置 client 凭证(可选,成对语义:secret 不许孤儿声明)。
+ if (oa.clientId !== undefined) {
+ if (
+ typeof oa.clientId !== 'string' ||
+ oa.clientId.trim().length === 0 ||
+ oa.clientId.length > 200 ||
+ /\s/.test(oa.clientId)
+ ) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].oauth.clientId 必须是 1–200 字符、不含空白的字符串',
+ };
+ }
+ }
+ let oaClientIdAlternatives: string[] | undefined;
+ if (oa.clientIdAlternatives !== undefined) {
+ if (oa.clientId === undefined) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].oauth.clientIdAlternatives 必须与默认 clientId 一起声明',
+ };
+ }
+ if (
+ !Array.isArray(oa.clientIdAlternatives) ||
+ oa.clientIdAlternatives.length === 0 ||
+ oa.clientIdAlternatives.length > GHOST_OAUTH_CLIENT_ID_ALTERNATIVES_MAX
+ ) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.clientIdAlternatives 必须是 1–${GHOST_OAUTH_CLIENT_ID_ALTERNATIVES_MAX} 条的数组`,
+ };
+ }
+ oaClientIdAlternatives = [];
+ for (const clientId of oa.clientIdAlternatives) {
+ if (
+ typeof clientId !== 'string' ||
+ clientId.trim().length === 0 ||
+ clientId.length > 200 ||
+ /\s/.test(clientId)
+ ) {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].oauth.clientIdAlternatives 含非法条目(须为 1–200 字符、不含空白的字符串)',
+ };
+ }
+ if (clientId === oa.clientId || oaClientIdAlternatives.includes(clientId)) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.clientIdAlternatives 含重复条目 ${JSON.stringify(clientId)}`,
+ };
+ }
+ oaClientIdAlternatives.push(clientId);
+ }
+ }
+ if (oa.clientSecret !== undefined) {
+ if (oa.clientId === undefined) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].oauth.clientSecret 必须与 clientId 成对声明',
+ };
+ }
+ if (
+ typeof oa.clientSecret !== 'string' ||
+ oa.clientSecret.trim().length === 0 ||
+ oa.clientSecret.length > 200 ||
+ /\s/.test(oa.clientSecret)
+ ) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].oauth.clientSecret 必须是 1–200 字符、不含空白的字符串',
+ };
+ }
+ }
+ let oaScopes: string[] | undefined;
+ if (oa.scopes !== undefined) {
+ if (!Array.isArray(oa.scopes) || oa.scopes.length > GHOST_OAUTH_SCOPES_MAX) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.scopes 必须是 ≤${GHOST_OAUTH_SCOPES_MAX} 条的数组`,
+ };
+ }
+ oaScopes = [];
+ for (const sc of oa.scopes) {
+ if (
+ typeof sc !== 'string' ||
+ sc.trim().length === 0 ||
+ sc.length > 200 ||
+ /\s/.test(sc)
+ ) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.scopes 含非法条目 ${JSON.stringify(sc)}(1–200 字符、不含空白)`,
+ };
+ }
+ if (oaScopes.includes(sc)) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.scopes 含重复条目 ${JSON.stringify(sc)}`,
+ };
+ }
+ oaScopes.push(sc);
+ }
+ }
+ if (oa.pkce !== undefined && typeof oa.pkce !== 'boolean') {
+ return { ok: false, reason: 'network.secrets[].oauth.pkce 必须是布尔值(缺省 true)' };
+ }
+ if (oa.scopeDelimiter !== undefined && oa.scopeDelimiter !== ',') {
+ return {
+ ok: false,
+ reason: 'network.secrets[].oauth.scopeDelimiter 目前只支持 ","(缺省 = 空格拼接)',
+ };
+ }
+ let oaExtra: Record<string, string> | undefined;
+ if (oa.extraAuthorizeParams !== undefined) {
+ if (!isPlainObject(oa.extraAuthorizeParams)) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].oauth.extraAuthorizeParams 必须是对象',
+ };
+ }
+ const entries = Object.entries(oa.extraAuthorizeParams as Record<string, unknown>);
+ if (entries.length === 0 || entries.length > GHOST_OAUTH_EXTRA_PARAMS_MAX) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.extraAuthorizeParams 必须是 1–${GHOST_OAUTH_EXTRA_PARAMS_MAX} 条(或省略)`,
+ };
+ }
+ oaExtra = {};
+ for (const [pk, pv] of entries) {
+ if (!/^[a-z][a-z0-9_]{0,31}$/.test(pk)) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.extraAuthorizeParams 键 ${JSON.stringify(pk)} 必须是小写字母开头的 1–32 位小写/数字/下划线`,
+ };
+ }
+ if (GHOST_OAUTH_RESERVED_AUTHORIZE_PARAMS.includes(pk)) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.extraAuthorizeParams 不允许声明协议保留参数 ${JSON.stringify(pk)}`,
+ };
+ }
+ if (typeof pv !== 'string' || pv.length === 0 || pv.length > 200) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.extraAuthorizeParams[${JSON.stringify(pk)}] 必须是 1–200 字符的字符串`,
+ };
+ }
+ oaExtra[pk] = pv;
+ }
+ }
+ // redirectPort(可选):loopback 回调固定端口(Atlassian 等回调精确匹配)。
+ if (oa.redirectPort !== undefined) {
+ if (
+ typeof oa.redirectPort !== 'number' ||
+ !Number.isInteger(oa.redirectPort) ||
+ oa.redirectPort < 1024 ||
+ oa.redirectPort > 65535
+ ) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].oauth.redirectPort 必须是 1024–65535 的整数',
+ };
+ }
+ }
+ // tokenBroker(可选):服务端 broker slug;secret 在服务端,与
+ // clientSecret 互斥(同时声明说明作者没想清 secret 到底在哪)。
+ if (oa.tokenBroker !== undefined) {
+ if (
+ typeof oa.tokenBroker !== 'string' ||
+ !GHOST_OAUTH_TOKEN_BROKER_RE.test(oa.tokenBroker)
+ ) {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].oauth.tokenBroker 必须是小写字母开头的 1–32 位小写/数字/下划线/连字符',
+ };
+ }
+ if (oa.clientSecret !== undefined) {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].oauth.tokenBroker 与 clientSecret 互斥(broker 模式下 secret 由服务端持有,不随包分发)',
+ };
+ }
+ }
+ if (oaClientIdAlternatives !== undefined && oa.tokenBroker === undefined) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].oauth.clientIdAlternatives 仅允许与 tokenBroker 一起声明',
+ };
+ }
+ // brokerBounce(可选):双地址弹跳回调,必须与 tokenBroker + redirectPort
+ // 成套声明(302 目标端口/路径在 broker 服务端写死,三者是一套约定)。
+ let oaBounce: { path: string; callbackPath: string } | undefined;
+ if (oa.brokerBounce !== undefined) {
+ if (oa.tokenBroker === undefined || oa.redirectPort === undefined) {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].oauth.brokerBounce 必须与 tokenBroker、redirectPort 同时声明',
+ };
+ }
+ if (!isPlainObject(oa.brokerBounce)) {
+ return { ok: false, reason: 'network.secrets[].oauth.brokerBounce 必须是对象' };
+ }
+ const bb = oa.brokerBounce as Record<string, unknown>;
+ for (const field of ['path', 'callbackPath'] as const) {
+ const v = bb[field];
+ if (typeof v !== 'string' || v.length > 128 || !GHOST_OAUTH_BOUNCE_PATH_RE.test(v)) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.brokerBounce.${field} 必须是 / 开头的站内绝对路径(段字符限字母/数字/_/-,≤128 字符)`,
+ };
+ }
+ }
+ oaBounce = { path: bb.path as string, callbackPath: bb.callbackPath as string };
+ }
+ let oaIdentity:
+ | { url: string; labelPath: string; displayTemplate?: string; avatarPath?: string }
+ | undefined;
+ if (oa.identity !== undefined) {
+ if (!isPlainObject(oa.identity)) {
+ return { ok: false, reason: 'network.secrets[].oauth.identity 必须是对象' };
+ }
+ const idn = oa.identity as Record<string, unknown>;
+ const idnUrl = parseHostBoundUrl(idn.url, 'identity.url');
+ if (!idnUrl.ok) return idnUrl;
+ if (
+ typeof idn.labelPath !== 'string' ||
+ idn.labelPath.length > 128 ||
+ !GHOST_SECRET_EXCHANGE_TOKEN_PATH_RE.test(idn.labelPath)
+ ) {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].oauth.identity.labelPath 必须是 ≤128 字符的点分路径(段名限字母/数字/_/-,如 "email" / "user.name")',
+ };
+ }
+ // displayTemplate(可选):展示名模板,占位符 `{点分路径}`(路径
+ // 形状同 labelPath),至少一个占位符——纯静态字符串没有"身份展示"
+ // 语义,多半是作者笔误。
+ let idnTemplate: string | undefined;
+ if (idn.displayTemplate !== undefined) {
+ if (
+ typeof idn.displayTemplate !== 'string' ||
+ idn.displayTemplate.length === 0 ||
+ idn.displayTemplate.length > GHOST_OAUTH_IDENTITY_TEMPLATE_MAX_CHARS
+ ) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.identity.displayTemplate 必须是 1–${GHOST_OAUTH_IDENTITY_TEMPLATE_MAX_CHARS} 字符的字符串`,
+ };
+ }
+ const placeholders = [
+ ...idn.displayTemplate.matchAll(GHOST_OAUTH_IDENTITY_TEMPLATE_PLACEHOLDER_RE),
+ ];
+ if (placeholders.length === 0) {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].oauth.identity.displayTemplate 必须含至少一个 {点分路径} 占位符(如 "{team} · {user}")',
+ };
+ }
+ for (const m of placeholders) {
+ const p = m[1] ?? '';
+ if (p.length > 128 || !GHOST_SECRET_EXCHANGE_TOKEN_PATH_RE.test(p)) {
+ return {
+ ok: false,
+ reason: `network.secrets[].oauth.identity.displayTemplate 占位符 {${p}} 不是合法点分路径(段名限字母/数字/_/-)`,
+ };
+ }
+ }
+ idnTemplate = idn.displayTemplate;
+ }
+ let idnAvatarPath: string | undefined;
+ if (idn.avatarPath !== undefined) {
+ if (
+ typeof idn.avatarPath !== 'string' ||
+ idn.avatarPath.length > 128 ||
+ !GHOST_SECRET_EXCHANGE_TOKEN_PATH_RE.test(idn.avatarPath)
+ ) {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].oauth.identity.avatarPath 必须是 ≤128 字符的点分路径(段名限字母/数字/_/-,如 "data.avatar_thumb")',
+ };
+ }
+ idnAvatarPath = idn.avatarPath;
+ }
+ oaIdentity = {
+ url: idnUrl.url,
+ labelPath: idn.labelPath,
+ ...(idnTemplate !== undefined ? { displayTemplate: idnTemplate } : {}),
+ ...(idnAvatarPath !== undefined ? { avatarPath: idnAvatarPath } : {}),
+ };
+ }
+ oauth = {
+ authorizeUrl: authorizeParsed.url,
+ tokenUrl: tokenParsed.url,
+ ...(oa.clientId !== undefined ? { clientId: oa.clientId as string } : {}),
+ ...(oaClientIdAlternatives !== undefined
+ ? { clientIdAlternatives: oaClientIdAlternatives }
+ : {}),
+ ...(oa.clientSecret !== undefined ? { clientSecret: oa.clientSecret as string } : {}),
+ ...(oaScopes !== undefined ? { scopes: oaScopes } : {}),
+ ...(oa.scopeDelimiter !== undefined
+ ? { scopeDelimiter: oa.scopeDelimiter as ',' }
+ : {}),
+ ...(oa.pkce !== undefined ? { pkce: oa.pkce as boolean } : {}),
+ ...(oaExtra !== undefined ? { extraAuthorizeParams: oaExtra } : {}),
+ ...(oaIdentity !== undefined ? { identity: oaIdentity } : {}),
+ ...(oa.redirectPort !== undefined ? { redirectPort: oa.redirectPort as number } : {}),
+ ...(oa.tokenBroker !== undefined ? { tokenBroker: oa.tokenBroker as string } : {}),
+ ...(oaBounce !== undefined ? { brokerBounce: oaBounce } : {}),
+ };
+ }
+ // exchange(可选):key 换令牌二段式。交换端点必须落在 hosts 白名单
+ // 内——结构上保证原始 key 也只流向用户同意过的域名。
+ let exchange: GhostSecretExchangeDecl | undefined;
+ if (s.exchange !== undefined) {
+ if (!isPlainObject(s.exchange)) {
+ return {
+ ok: false,
+ reason: `network.secrets[${JSON.stringify(s.key)}].exchange 必须是对象`,
+ };
+ }
+ const ex = s.exchange as Record<string, unknown>;
+ if (typeof ex.url !== 'string' || ex.url.length === 0 || ex.url.length > 2048) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].exchange.url 必须是 1–2048 字符的字符串',
+ };
+ }
+ let exUrl: URL;
+ try {
+ exUrl = new URL(ex.url);
+ } catch {
+ return { ok: false, reason: 'network.secrets[].exchange.url 不是合法的绝对地址' };
+ }
+ if (
+ exUrl.protocol !== 'https:' ||
+ exUrl.port !== '' ||
+ exUrl.username ||
+ exUrl.password
+ ) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].exchange.url 仅支持 https 默认端口且不允许内嵌用户名/密码',
+ };
+ }
+ if (!hosts.some((pattern) => ghostNetworkHostMatches(pattern, exUrl.hostname))) {
+ return {
+ ok: false,
+ reason: `network.secrets[].exchange.url 的域名 ${JSON.stringify(exUrl.hostname)} 必须命中 network.hosts 白名单`,
+ };
+ }
+ if (
+ typeof ex.bodyFormat !== 'string' ||
+ ex.bodyFormat.length === 0 ||
+ ex.bodyFormat.length > GHOST_SECRET_EXCHANGE_BODY_MAX_CHARS ||
+ ex.bodyFormat.split('{value}').length !== 2
+ ) {
+ return {
+ ok: false,
+ reason: `network.secrets[].exchange.bodyFormat 必须是 ≤${GHOST_SECRET_EXCHANGE_BODY_MAX_CHARS} 字符且恰含一个 {value} 占位的字符串`,
+ };
+ }
+ let exContentType: GhostSecretExchangeContentType | undefined;
+ if (ex.contentType !== undefined) {
+ if (
+ typeof ex.contentType !== 'string' ||
+ !(GHOST_SECRET_EXCHANGE_CONTENT_TYPES as readonly string[]).includes(ex.contentType)
+ ) {
+ return {
+ ok: false,
+ reason: `network.secrets[].exchange.contentType 仅支持 ${GHOST_SECRET_EXCHANGE_CONTENT_TYPES.join(' / ')}`,
+ };
+ }
+ exContentType = ex.contentType as GhostSecretExchangeContentType;
+ }
+ if (
+ typeof ex.tokenPath !== 'string' ||
+ ex.tokenPath.length > 128 ||
+ !GHOST_SECRET_EXCHANGE_TOKEN_PATH_RE.test(ex.tokenPath)
+ ) {
+ return {
+ ok: false,
+ reason:
+ 'network.secrets[].exchange.tokenPath 必须是 ≤128 字符的点分路径(段名限字母/数字/_/-,如 "session" / "data.token")',
+ };
+ }
+ let exTtl: number | undefined;
+ if (ex.ttlSeconds !== undefined) {
+ if (
+ typeof ex.ttlSeconds !== 'number' ||
+ !Number.isInteger(ex.ttlSeconds) ||
+ ex.ttlSeconds < GHOST_SECRET_EXCHANGE_TTL_MIN_S ||
+ ex.ttlSeconds > GHOST_SECRET_EXCHANGE_TTL_MAX_S
+ ) {
+ return {
+ ok: false,
+ reason: `network.secrets[].exchange.ttlSeconds 必须是 ${GHOST_SECRET_EXCHANGE_TTL_MIN_S}–${GHOST_SECRET_EXCHANGE_TTL_MAX_S} 的整数(秒)`,
+ };
+ }
+ exTtl = ex.ttlSeconds;
+ }
+ exchange = {
+ url: ex.url,
+ bodyFormat: ex.bodyFormat,
+ ...(exContentType !== undefined ? { contentType: exContentType } : {}),
+ tokenPath: ex.tokenPath,
+ ...(exTtl !== undefined ? { ttlSeconds: exTtl } : {}),
+ };
+ }
+ secrets.push({
+ key: s.key,
+ label: s.label,
+ ...(source !== undefined ? { source } : {}),
+ ...(s.hint !== undefined ? { hint: s.hint as string } : {}),
+ ...(s.url !== undefined ? { url: s.url as string } : {}),
+ inject: {
+ header: inj.header,
+ format: inj.format,
+ ...(injectHosts !== undefined ? { hosts: injectHosts } : {}),
+ },
+ ...(exchange !== undefined ? { exchange } : {}),
+ ...(oauth !== undefined ? { oauth } : {}),
+ });
+ }
+ }
+ // connections(可选):多连接声明——"地址 + 凭证成对多条"的凭证形态
+ // (自建实例场景)。作者只声明连接类型与注入形态,地址与 token 由用户在
+ // 设置页添加(每次新增地址都过主机受信确认);连接凭证的注入范围恒等于
+ // 各连接自身地址,inject.hosts 禁止声明。
+ let connections: GhostConnectionDecl[] | undefined;
+ if (n.connections !== undefined) {
+ if (
+ !Array.isArray(n.connections) ||
+ n.connections.length === 0 ||
+ n.connections.length > GHOST_NETWORK_MAX_CONNECTION_DECLS
+ ) {
+ return {
+ ok: false,
+ reason: `network.connections 必须是 1–${GHOST_NETWORK_MAX_CONNECTION_DECLS} 条的数组`,
+ };
+ }
+ // 没人收地址和 token:连接的地址与凭证一律由意识 settingsHtml 收单
+ // (经 /connections 协议通道),没有界面就没有入口。
+ if (raw.settingsHtml === undefined) {
+ return {
+ ok: false,
+ reason:
+ '声明了 network.connections 必须同时声明 settingsHtml(连接地址与凭证由意识设置界面收单,没有界面就没人收单)',
+ };
+ }
+ connections = [];
+ const seenConnKeys = new Set<string>();
+ const secretKeySet = new Set((secrets ?? []).map((s) => s.key));
+ for (const c of n.connections) {
+ if (!isPlainObject(c)) return { ok: false, reason: 'network.connections 每项必须是对象' };
+ if (typeof c.key !== 'string' || !/^[a-z][a-z0-9_]{0,31}$/.test(c.key)) {
+ return {
+ ok: false,
+ reason: 'network.connections[].key 必须是小写字母开头的 1–32 位小写/数字/下划线',
+ };
+ }
+ if (seenConnKeys.has(c.key)) {
+ return { ok: false, reason: `network.connections 含重复 key ${JSON.stringify(c.key)}` };
+ }
+ // 与 secrets 共用键命名空间(保险库派生键同一前缀),撞名拒装。
+ if (secretKeySet.has(c.key)) {
+ return {
+ ok: false,
+ reason: `network.connections[].key ${JSON.stringify(c.key)} 与 network.secrets 的 key 撞名(两者共用命名空间)`,
+ };
+ }
+ seenConnKeys.add(c.key);
+ if (typeof c.label !== 'string' || c.label.trim().length === 0 || c.label.length > 64) {
+ return { ok: false, reason: 'network.connections[].label 必须是 1–64 字符的非空字符串' };
+ }
+ if (
+ c.hint !== undefined &&
+ (typeof c.hint !== 'string' || c.hint.trim().length === 0 || c.hint.length > 200)
+ ) {
+ return { ok: false, reason: 'network.connections[].hint 必须是 1–200 字符的非空字符串' };
+ }
+ if (!isPlainObject(c.inject)) {
+ return {
+ ok: false,
+ reason: `network.connections[${JSON.stringify(c.key)}].inject 必填(连接凭证要声明注入到哪个请求头)`,
+ };
+ }
+ const cinj = c.inject as Record<string, unknown>;
+ if (typeof cinj.header !== 'string' || !/^[A-Za-z0-9-]{1,64}$/.test(cinj.header)) {
+ return {
+ ok: false,
+ reason: 'network.connections[].inject.header 必须是 1–64 位字母/数字/连字符的头名',
+ };
+ }
+ if (GHOST_NETWORK_FORBIDDEN_INJECT_HEADERS.includes(cinj.header.toLowerCase())) {
+ return {
+ ok: false,
+ reason: `network.connections[].inject.header 不允许使用协议关键头 ${JSON.stringify(cinj.header)}`,
+ };
+ }
+ if (
+ typeof cinj.format !== 'string' ||
+ cinj.format.length === 0 ||
+ cinj.format.length > 200 ||
+ cinj.format.split('{value}').length !== 2
+ ) {
+ return {
+ ok: false,
+ reason:
+ 'network.connections[].inject.format 必须是 ≤200 字符且恰含一个 {value} 占位的字符串(如 "Bearer {value}")',
+ };
+ }
+ if (cinj.hosts !== undefined) {
+ // 注入范围恒等于各连接自身地址(用户添加哪条注入哪条),作者无从
+ // 收窄或扩张——声明即结构性误解,直接拒装。
+ return {
+ ok: false,
+ reason:
+ 'network.connections[].inject.hosts 不允许声明(连接凭证只注入对应连接自身的地址)',
+ };
+ }
+ if (c.maxConnections !== undefined) {
+ if (
+ typeof c.maxConnections !== 'number' ||
+ !Number.isInteger(c.maxConnections) ||
+ c.maxConnections < 1 ||
+ c.maxConnections > GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL
+ ) {
+ return {
+ ok: false,
+ reason: `network.connections[].maxConnections 必须是 1–${GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL} 的整数(缺省 ${GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL})`,
+ };
+ }
+ }
+ connections.push({
+ key: c.key,
+ label: c.label,
+ ...(c.hint !== undefined ? { hint: c.hint as string } : {}),
+ inject: { header: cinj.header, format: cinj.format },
+ ...(c.maxConnections !== undefined ? { maxConnections: c.maxConnections as number } : {}),
+ });
+ }
+ }
+ network = {
+ hosts,
+ ...(secrets !== undefined ? { secrets } : {}),
+ ...(connections !== undefined ? { connections } : {}),
+ };
+ }
+
+ // agent 槽能力详单:缺省 = 仅点击票据;三个加档由 Desktop 独立展示并授权。
+ let agent: GhostAgentNeeds | undefined;
+ if (raw.agent !== undefined) {
+ if (!isPlainObject(raw.agent)) {
+ return { ok: false, reason: 'agent 能力详单必须是对象(如 { "background": true })' };
+ }
+ if (!slots.includes('agent')) {
+ return { ok: false, reason: '声明了 agent 能力详单但 slots 未包含 "agent"' };
+ }
+ const agentRaw = raw.agent as Record<string, unknown>;
+ const unknownAgentField = Object.keys(agentRaw).find(
+ (key) => key !== 'background' && key !== 'errand' && key !== 'schedule',
+ );
+ if (unknownAgentField) {
+ return {
+ ok: false,
+ reason: `agent 含不允许的字段 ${JSON.stringify(unknownAgentField)}`,
+ };
+ }
+ if (agentRaw.background !== undefined && typeof agentRaw.background !== 'boolean') {
+ return { ok: false, reason: 'agent.background 必须是布尔值' };
+ }
+ if (agentRaw.errand !== undefined && typeof agentRaw.errand !== 'boolean') {
+ return { ok: false, reason: 'agent.errand 必须是布尔值' };
+ }
+ if (agentRaw.schedule !== undefined && typeof agentRaw.schedule !== 'boolean') {
+ return { ok: false, reason: 'agent.schedule 必须是布尔值' };
+ }
+ if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true) {
+ return {
+ ok: false,
+ reason:
+ 'agent 能力详单只有 background: true / errand: true / schedule: true 三项加档;仅需用户点击触发时请省略 agent 字段',
+ };
+ }
+ agent = {
+ ...(agentRaw.background === true ? { background: true } : {}),
+ ...(agentRaw.errand === true ? { errand: true } : {}),
+ ...(agentRaw.schedule === true ? { schedule: true } : {}),
+ };
+ }
+
+ // node 槽详单:只收包内入口 + 固定 stdio 协议 + 生命周期。这里刻意采用
+ // 字段白名单,command/args/shell/env 等任意命令启动面一律在装入前拒绝。
+ let node: GhostNodeNeeds | undefined;
+ if (raw.node !== undefined) {
+ if (!isPlainObject(raw.node)) {
+ return { ok: false, reason: 'node 能力详单必须是对象' };
+ }
+ if (!slots.includes('node')) {
+ return { ok: false, reason: '声明了 node 能力详单但 slots 未包含 "node"' };
+ }
+ const nodeRaw = raw.node as Record<string, unknown>;
+ const allowedNodeFields = new Set([
+ 'entry',
+ 'protocol',
+ 'lifecycle',
+ 'idleTimeoutSeconds',
+ 'entries',
+ 'childSpawn',
+ 'secretBindings',
+ ]);
+ const unknownNodeField = Object.keys(nodeRaw).find((key) => !allowedNodeFields.has(key));
+ if (unknownNodeField) {
+ return {
+ ok: false,
+ reason: `node 含不允许的字段 ${JSON.stringify(unknownNodeField)};不能声明 command/args/shell/env`,
+ };
+ }
+ if (!isSafeGhostRelativePath(nodeRaw.entry)) {
+ return { ok: false, reason: 'node.entry 必须是安装目录内的安全相对路径' };
+ }
+ if (!/\.(?:c?js)$/.test(nodeRaw.entry)) {
+ return { ok: false, reason: 'node.entry 必须是 CommonJS .js / .cjs 文件' };
+ }
+ // 入口重合判定折叠大小写:Windows / macOS 默认文件系统大小写不敏感,
+ // main.js 与 Main.js 是同一个文件,原样比较会漏判。
+ if (nodeRaw.entry.toLowerCase() === (raw.entry as string).toLowerCase()) {
+ return { ok: false, reason: 'node.entry 不能与浏览器沙箱 entry 使用同一个文件' };
+ }
+ if (
+ typeof nodeRaw.protocol !== 'string' ||
+ !(GHOST_NODE_PROTOCOLS as readonly string[]).includes(nodeRaw.protocol)
+ ) {
+ return { ok: false, reason: `node.protocol 必须是 ${GHOST_NODE_PROTOCOLS.join(' / ')}` };
+ }
+ if (
+ nodeRaw.lifecycle !== undefined &&
+ (typeof nodeRaw.lifecycle !== 'string' ||
+ !(GHOST_NODE_LIFECYCLES as readonly string[]).includes(nodeRaw.lifecycle))
+ ) {
+ return { ok: false, reason: `node.lifecycle 必须是 ${GHOST_NODE_LIFECYCLES.join(' / ')}` };
+ }
+ if (
+ nodeRaw.idleTimeoutSeconds !== undefined &&
+ (typeof nodeRaw.idleTimeoutSeconds !== 'number' ||
+ !Number.isInteger(nodeRaw.idleTimeoutSeconds) ||
+ nodeRaw.idleTimeoutSeconds < 30 ||
+ nodeRaw.idleTimeoutSeconds > 3600)
+ ) {
+ return { ok: false, reason: 'node.idleTimeoutSeconds 必须是 30–3600 的整数' };
+ }
+ if (nodeRaw.lifecycle === 'resident' && nodeRaw.idleTimeoutSeconds !== undefined) {
+ return { ok: false, reason: 'node.lifecycle 为 resident 时不能再声明 idleTimeoutSeconds' };
+ }
+ // 额外入口(多进程窄版):同一套入口纪律——包内安全相对路径、CJS 文件、
+ // 不与浏览器沙箱 entry / 主入口 / 彼此重复;条数封顶。
+ let nodeEntries: string[] | undefined;
+ if (nodeRaw.entries !== undefined) {
+ if (!Array.isArray(nodeRaw.entries) || nodeRaw.entries.length === 0) {
+ return { ok: false, reason: 'node.entries 必须是非空数组(额外工作进程入口清单)' };
+ }
+ if (nodeRaw.entries.length > GHOST_NODE_MAX_EXTRA_ENTRIES) {
+ return { ok: false, reason: `node.entries 最多 ${GHOST_NODE_MAX_EXTRA_ENTRIES} 条` };
+ }
+ // 同上折叠大小写:大小写变体在大小写不敏感文件系统上是同一个文件,
+ // 不能被当作不同入口通过查重。
+ const seen = new Set<string>();
+ for (const extra of nodeRaw.entries) {
+ if (!isSafeGhostRelativePath(extra)) {
+ return { ok: false, reason: 'node.entries 每项必须是安装目录内的安全相对路径' };
+ }
+ if (!/\.(?:c?js)$/.test(extra)) {
+ return { ok: false, reason: 'node.entries 每项必须是 CommonJS .js / .cjs 文件' };
+ }
+ const extraFold = extra.toLowerCase();
+ if (extraFold === (raw.entry as string).toLowerCase()) {
+ return { ok: false, reason: 'node.entries 不能包含浏览器沙箱 entry' };
+ }
+ if (extraFold === nodeRaw.entry.toLowerCase()) {
+ return { ok: false, reason: 'node.entries 不能重复主入口 node.entry' };
+ }
+ if (seen.has(extraFold)) {
+ return { ok: false, reason: `node.entries 含重复入口 ${JSON.stringify(extra)}` };
+ }
+ seen.add(extraFold);
+ }
+ nodeEntries = nodeRaw.entries as string[];
+ }
+ if (nodeRaw.childSpawn !== undefined && typeof nodeRaw.childSpawn !== 'boolean') {
+ return { ok: false, reason: 'node.childSpawn 必须是布尔值' };
+ }
+ let nodeSecretBindings: GhostNodeSecretBinding[] | undefined;
+ if (nodeRaw.secretBindings !== undefined) {
+ if (
+ !Array.isArray(nodeRaw.secretBindings) ||
+ nodeRaw.secretBindings.length === 0 ||
+ nodeRaw.secretBindings.length > GHOST_NODE_MAX_SECRET_BINDINGS
+ ) {
+ return {
+ ok: false,
+ reason: `node.secretBindings 必须是 1–${GHOST_NODE_MAX_SECRET_BINDINGS} 条的数组`,
+ };
+ }
+ if (raw.settingsHtml === undefined) {
+ return {
+ ok: false,
+ reason: 'node.secretBindings 需要 settingsHtml 收集凭证',
+ };
+ }
+ nodeSecretBindings = [];
+ const seenSecretKeys = new Set<string>();
+ for (const bindingRaw of nodeRaw.secretBindings) {
+ if (!isPlainObject(bindingRaw)) {
+ return { ok: false, reason: 'node.secretBindings 每项必须是对象' };
+ }
+ const binding = bindingRaw as Record<string, unknown>;
+ const unknownBindingField = Object.keys(binding).find(
+ (key) => !['key', 'label', 'methods', 'entry', 'hint', 'url'].includes(key),
+ );
+ if (unknownBindingField) {
+ return {
+ ok: false,
+ reason: `node.secretBindings[] 含不允许的字段 ${JSON.stringify(unknownBindingField)}`,
+ };
+ }
+ if (typeof binding.key !== 'string' || !/^[a-z][a-z0-9_]{0,31}$/.test(binding.key)) {
+ return {
+ ok: false,
+ reason: 'node.secretBindings[].key 必须是小写字母开头的 1–32 位小写/数字/下划线',
+ };
+ }
+ if (seenSecretKeys.has(binding.key)) {
+ return {
+ ok: false,
+ reason: `node.secretBindings 含重复 key ${JSON.stringify(binding.key)}`,
+ };
+ }
+ seenSecretKeys.add(binding.key);
+ if (
+ typeof binding.label !== 'string' ||
+ binding.label.trim().length === 0 ||
+ binding.label.length > 64
+ ) {
+ return {
+ ok: false,
+ reason: 'node.secretBindings[].label 必须是 1–64 字符的非空字符串',
+ };
+ }
+ if (
+ !Array.isArray(binding.methods) ||
+ binding.methods.length === 0 ||
+ binding.methods.length > GHOST_NODE_MAX_SECRET_METHODS
+ ) {
+ return {
+ ok: false,
+ reason: `node.secretBindings[].methods 必须是 1–${GHOST_NODE_MAX_SECRET_METHODS} 条的数组`,
+ };
+ }
+ const methods: string[] = [];
+ for (const method of binding.methods) {
+ if (typeof method !== 'string' || !/^[A-Za-z0-9_./:-]{1,128}$/.test(method)) {
+ return {
+ ok: false,
+ reason: 'node.secretBindings[].methods 每项必须是 1–128 位安全方法名',
+ };
+ }
+ if (nodeRaw.protocol === 'mcp-stdio' && isGhostNodeMcpReservedMethod(method)) {
+ return {
+ ok: false,
+ reason: `node.secretBindings[].methods 不能绑定宿主保留的 MCP 方法 ${JSON.stringify(method)}`,
+ };
+ }
+ if (methods.includes(method)) {
+ return {
+ ok: false,
+ reason: `node.secretBindings[].methods 含重复方法 ${JSON.stringify(method)}`,
+ };
+ }
+ methods.push(method);
+ }
+ let bindingEntry: string | undefined;
+ if (binding.entry !== undefined) {
+ if (
+ typeof binding.entry !== 'string' ||
+ (binding.entry !== nodeRaw.entry && !(nodeEntries ?? []).includes(binding.entry))
+ ) {
+ return {
+ ok: false,
+ reason: 'node.secretBindings[].entry 必须逐字命中 node.entry 或 node.entries',
+ };
+ }
+ bindingEntry = binding.entry;
+ }
+ if (
+ binding.hint !== undefined &&
+ (typeof binding.hint !== 'string' ||
+ binding.hint.trim().length === 0 ||
+ binding.hint.length > 200)
+ ) {
+ return {
+ ok: false,
+ reason: 'node.secretBindings[].hint 必须是 1–200 字符的非空字符串',
+ };
+ }
+ if (binding.url !== undefined) {
+ if (
+ typeof binding.url !== 'string' ||
+ binding.url.length === 0 ||
+ binding.url.length > 200
+ ) {
+ return {
+ ok: false,
+ reason: 'node.secretBindings[].url 必须是 1–200 字符的字符串',
+ };
+ }
+ let parsed: URL;
+ try {
+ parsed = new URL(binding.url);
+ } catch {
+ return { ok: false, reason: 'node.secretBindings[].url 不是合法的绝对地址' };
+ }
+ if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {
+ return {
+ ok: false,
+ reason: 'node.secretBindings[].url 仅支持 https 且不允许内嵌用户名/密码',
+ };
+ }
+ }
+ nodeSecretBindings.push({
+ key: binding.key,
+ label: binding.label,
+ methods,
+ ...(bindingEntry !== undefined ? { entry: bindingEntry } : {}),
+ ...(binding.hint !== undefined ? { hint: binding.hint as string } : {}),
+ ...(binding.url !== undefined ? { url: binding.url as string } : {}),
+ });
+ }
+ }
+ node = {
+ entry: nodeRaw.entry,
+ protocol: nodeRaw.protocol as GhostNodeProtocol,
+ ...(nodeRaw.lifecycle !== undefined
+ ? { lifecycle: nodeRaw.lifecycle as GhostNodeLifecycle }
+ : {}),
+ ...(nodeRaw.idleTimeoutSeconds !== undefined
+ ? { idleTimeoutSeconds: nodeRaw.idleTimeoutSeconds }
+ : {}),
+ ...(nodeEntries !== undefined ? { entries: nodeEntries } : {}),
+ ...(nodeRaw.childSpawn !== undefined ? { childSpawn: nodeRaw.childSpawn } : {}),
+ ...(nodeSecretBindings !== undefined ? { secretBindings: nodeSecretBindings } : {}),
+ };
+ }
+ if (slots.includes('node') && node === undefined) {
+ return { ok: false, reason: 'slots 声明了 "node" 但缺少 node 工作进程详单' };
+ }
+ if (node?.secretBindings) {
+ for (const binding of node.secretBindings) {
+ if (network?.secrets?.some((secret) => secret.key === binding.key)) {
+ return {
+ ok: false,
+ reason: `network.secrets 的 key ${JSON.stringify(binding.key)} 与 node.secretBindings 撞名`,
+ };
+ }
+ if (network?.connections?.some((connection) => connection.key === binding.key)) {
+ return {
+ ok: false,
+ reason: `network.connections[].key ${JSON.stringify(binding.key)} 与 node.secretBindings 的 key 撞名(两者共用命名空间)`,
+ };
+ }
+ }
+ }
+
+ // preview 槽详单:与 slots 含 'preview' **严格成对**(有槽必有详单——域名
+ // 范围是本能力的全部知情面,不允许"先装后说");域名语法与 network 白名单
+ // 同一套(装入确认框逐条展示)。
+ let preview: GhostPreviewNeeds | undefined;
+ if (raw.preview !== undefined) {
+ if (!isPlainObject(raw.preview)) {
+ return { ok: false, reason: 'preview 详单必须是对象(如 { "hosts": ["*.example.com"] })' };
+ }
+ if (!slots.includes('preview')) {
+ return { ok: false, reason: '声明了 preview 详单但 slots 未包含 "preview"' };
+ }
+ const previewRaw = raw.preview as Record<string, unknown>;
+ const unknownPreviewField = Object.keys(previewRaw).find((key) => key !== 'hosts');
+ if (unknownPreviewField !== undefined) {
+ return { ok: false, reason: `preview 含不允许的字段 ${JSON.stringify(unknownPreviewField)}` };
+ }
+ if (!Array.isArray(previewRaw.hosts) || previewRaw.hosts.length === 0) {
+ return { ok: false, reason: 'preview.hosts 必须是非空数组(可打开预览的域名白名单)' };
+ }
+ if (previewRaw.hosts.length > GHOST_PREVIEW_MAX_HOSTS) {
+ return { ok: false, reason: `preview.hosts 最多 ${GHOST_PREVIEW_MAX_HOSTS} 条` };
+ }
+ const seenPreviewHosts = new Set<string>();
+ for (const host of previewRaw.hosts) {
+ if (
+ !isValidGhostNetworkHostPattern(host) &&
+ !(typeof host === 'string' && GHOST_PREVIEW_LOOPBACK_HOSTS.has(host))
+ ) {
+ return { ok: false, reason: `preview.hosts 含不合法域名模式 ${JSON.stringify(host)}` };
+ }
+ if (seenPreviewHosts.has(host)) {
+ return { ok: false, reason: `preview.hosts 含重复域名 ${JSON.stringify(host)}` };
+ }
+ seenPreviewHosts.add(host);
+ }
+ preview = { hosts: previewRaw.hosts as string[] };
+ }
+ if (slots.includes('preview') && preview === undefined) {
+ return {
+ ok: false,
+ reason: 'slots 声明了 "preview" 但缺少 preview 详单(hosts 域名白名单必填)',
+ };
+ }
+
+ // skill 槽详单:与 slots 含 'skill' **严格成对**(有槽必有详单——捆绑了什么
+ // 技能是本能力的全部知情面)。name/description 与 SKILL.md 的逐字一致性在
+ // 打包与装入两侧另行强制,这里只管声明本身的形状。name/dir 大小写折叠去重:
+ // win32 文件系统折叠大小写,共享技能根的链接名不允许折叠后相撞。
+ let skill: GhostSkillNeeds | undefined;
+ if (raw.skill !== undefined) {
+ if (!isPlainObject(raw.skill)) {
+ return {
+ ok: false,
+ reason:
+ 'skill 详单必须是对象(如 { "items": [{ "dir": "skills/foo", "name": "foo", "description": "..." }] })',
+ };
+ }
+ if (!slots.includes('skill')) {
+ return { ok: false, reason: '声明了 skill 详单但 slots 未包含 "skill"' };
+ }
+ const skillRaw = raw.skill as Record<string, unknown>;
+ const unknownSkillField = Object.keys(skillRaw).find((key) => key !== 'items');
+ if (unknownSkillField !== undefined) {
+ return { ok: false, reason: `skill 含不允许的字段 ${JSON.stringify(unknownSkillField)}` };
+ }
+ if (!Array.isArray(skillRaw.items) || skillRaw.items.length === 0) {
+ return { ok: false, reason: 'skill.items 必须是非空数组(随包捆绑的技能清单)' };
+ }
+ if (skillRaw.items.length > GHOST_SKILL_MAX_ITEMS) {
+ return { ok: false, reason: `skill.items 最多 ${GHOST_SKILL_MAX_ITEMS} 条` };
+ }
+ const skillItems: GhostSkillItem[] = [];
+ const seenSkillNames = new Set<string>();
+ const seenSkillDirs = new Set<string>();
+ for (const item of skillRaw.items) {
+ if (!isPlainObject(item)) {
+ return { ok: false, reason: 'skill.items 每项必须是对象({ dir, name, description })' };
+ }
+ const itemRaw = item as Record<string, unknown>;
+ const unknownItemField = Object.keys(itemRaw).find(
+ (key) => key !== 'dir' && key !== 'name' && key !== 'description',
+ );
+ if (unknownItemField !== undefined) {
+ return {
+ ok: false,
+ reason: `skill.items 条目含不允许的字段 ${JSON.stringify(unknownItemField)}`,
+ };
+ }
+ if (!isSafeGhostRelativePath(itemRaw.dir)) {
+ return {
+ ok: false,
+ reason: `skill.items[].dir 必须是包内安全相对路径(如 "skills/foo"),得到 ${JSON.stringify(itemRaw.dir)}`,
+ };
+ }
+ if (
+ typeof itemRaw.name !== 'string' ||
+ itemRaw.name.length > GHOST_SKILL_NAME_MAX_CHARS ||
+ !GHOST_SKILL_NAME_RE.test(itemRaw.name)
+ ) {
+ return {
+ ok: false,
+ reason: `skill.items[].name 必须是小写字母/数字加单连字符分段(禁首尾/连续连字符)、长度 1–${GHOST_SKILL_NAME_MAX_CHARS},得到 ${JSON.stringify(itemRaw.name)}`,
+ };
+ }
+ if (
+ typeof itemRaw.description !== 'string' ||
+ itemRaw.description.trim().length === 0 ||
+ itemRaw.description.length > 1024
+ ) {
+ return { ok: false, reason: 'skill.items[].description 必须是 1–1024 字符的非空字符串' };
+ }
+ const nameFold = itemRaw.name.toLowerCase();
+ if (seenSkillNames.has(nameFold)) {
+ return { ok: false, reason: `skill.items 含重复 name ${JSON.stringify(itemRaw.name)}` };
+ }
+ seenSkillNames.add(nameFold);
+ const dirFold = itemRaw.dir.toLowerCase();
+ if (seenSkillDirs.has(dirFold)) {
+ return { ok: false, reason: `skill.items 含重复 dir ${JSON.stringify(itemRaw.dir)}` };
+ }
+ seenSkillDirs.add(dirFold);
+ skillItems.push({ dir: itemRaw.dir, name: itemRaw.name, description: itemRaw.description });
+ }
+ skill = { items: skillItems };
+ }
+ if (slots.includes('skill') && skill === undefined) {
+ return { ok: false, reason: 'slots 声明了 "skill" 但缺少 skill 详单(items 技能清单必填)' };
+ }
+
+ // manual 是独立顶层字段,不是能力 slot 或授权项。这里只校验一级逻辑索引;
+ // MANUAL.md 存在性、Markdown 文本与逐文件 64KB 上限由打包/装入两侧校验。
+ let manual: GhostManualNeeds | undefined;
+ if (raw.manual !== undefined) {
+ if (!isPlainObject(raw.manual)) {
+ return {
+ ok: false,
+ reason:
+ 'manual 必须是对象(如 { "items": [{ "dir": "manual/getting-started", "name": "getting-started", "description": "..." }] })',
+ };
+ }
+ const manualRaw = raw.manual as Record<string, unknown>;
+ const unknownManualField = Object.keys(manualRaw).find((key) => key !== 'items');
+ if (unknownManualField !== undefined) {
+ return { ok: false, reason: `manual 含不允许的字段 ${JSON.stringify(unknownManualField)}` };
+ }
+ if (!Array.isArray(manualRaw.items) || manualRaw.items.length === 0) {
+ return { ok: false, reason: 'manual.items 必须是非空数组(随包手册索引)' };
+ }
+ if (manualRaw.items.length > GHOST_MANUAL_MAX_ITEMS) {
+ return { ok: false, reason: `manual.items 最多 ${GHOST_MANUAL_MAX_ITEMS} 条` };
+ }
+ const manualItems: GhostManualItem[] = [];
+ const seenManualNames = new Set<string>();
+ const seenManualDirs = new Set<string>();
+ for (const item of manualRaw.items) {
+ if (!isPlainObject(item)) {
+ return { ok: false, reason: 'manual.items 每项必须是对象({ dir, name, description })' };
+ }
+ const itemRaw = item as Record<string, unknown>;
+ const unknownItemField = Object.keys(itemRaw).find(
+ (key) => key !== 'dir' && key !== 'name' && key !== 'description',
+ );
+ if (unknownItemField !== undefined) {
+ return {
+ ok: false,
+ reason: `manual.items 条目含不允许的字段 ${JSON.stringify(unknownItemField)}`,
+ };
+ }
+ if (!isSafeGhostRelativePath(itemRaw.dir)) {
+ return {
+ ok: false,
+ reason: `manual.items[].dir 必须是包内安全相对路径(如 "manual/getting-started"),得到 ${JSON.stringify(itemRaw.dir)}`,
+ };
+ }
+ const dirFold = itemRaw.dir.toLowerCase();
+ if (declaredFilePathFolds.some((path) => pathsConflict(dirFold, path))) {
+ return {
+ ok: false,
+ reason: `manual.items[].dir ${JSON.stringify(itemRaw.dir)} 与插件声明文件路径大小写折叠后冲突`,
+ };
+ }
+ if (
+ typeof itemRaw.name !== 'string' ||
+ itemRaw.name.length > GHOST_SKILL_NAME_MAX_CHARS ||
+ !GHOST_SKILL_NAME_RE.test(itemRaw.name)
+ ) {
+ return {
+ ok: false,
+ reason: `manual.items[].name 必须是小写字母/数字加单连字符分段(禁首尾/连续连字符)、长度 1–${GHOST_SKILL_NAME_MAX_CHARS},得到 ${JSON.stringify(itemRaw.name)}`,
+ };
+ }
+ if (
+ typeof itemRaw.description !== 'string' ||
+ itemRaw.description.trim().length === 0 ||
+ itemRaw.description.length > GHOST_MANUAL_DESCRIPTION_MAX_CHARS
+ ) {
+ return {
+ ok: false,
+ reason: `manual.items[].description 必须是 1–${GHOST_MANUAL_DESCRIPTION_MAX_CHARS} 字符的非空字符串`,
+ };
+ }
+ const nameFold = itemRaw.name.toLowerCase();
+ if (seenManualNames.has(nameFold)) {
+ return { ok: false, reason: `manual.items 含重复 name ${JSON.stringify(itemRaw.name)}` };
+ }
+ seenManualNames.add(nameFold);
+ if (seenManualDirs.has(dirFold)) {
+ return { ok: false, reason: `manual.items 含重复 dir ${JSON.stringify(itemRaw.dir)}` };
+ }
+ seenManualDirs.add(dirFold);
+ manualItems.push({
+ dir: itemRaw.dir,
+ name: itemRaw.name,
+ description: itemRaw.description,
+ });
+ }
+ manual = { items: manualItems };
+ }
+
+ // 显式触发指令:1–32 字符、无空白、无 '/'(允许中文,如 /画图);
+ // 必须有工具可干活。跨意识查重在装入时由 GhostManager 执行(需要本地清单)。
+ if (raw.command !== undefined) {
+ if (
+ typeof raw.command !== 'string' ||
+ raw.command.length === 0 ||
+ raw.command.length > 32 ||
+ /[\s/]/.test(raw.command)
+ ) {
+ return { ok: false, reason: 'command 必须是 1–32 字符、不含空白与 "/" 的字符串' };
+ }
+ if (tools === undefined) {
+ return { ok: false, reason: '声明了 command 但没有 tools——没有工具的指令无事可做' };
+ }
+ }
+
+ // 语义触发扩展词表:≤8 个、每个 2–24 字符(单字词命中面失控,拒收)、
+ // 去首尾空白后不许为空;大小写折叠去重。必须有工具可干活(同 command)。
+ let keywords: string[] | undefined;
+ if (raw.keywords !== undefined) {
+ if (!Array.isArray(raw.keywords) || raw.keywords.length === 0 || raw.keywords.length > 8) {
+ return { ok: false, reason: 'keywords 必须是 1–8 项的数组' };
+ }
+ if (tools === undefined) {
+ return { ok: false, reason: '声明了 keywords 但没有 tools——没有工具的触发词无事可做' };
+ }
+ const seen = new Set<string>();
+ keywords = [];
+ for (const k of raw.keywords) {
+ if (typeof k !== 'string') return { ok: false, reason: 'keywords 每项必须是字符串' };
+ const word = k.trim();
+ if (word.length < 2 || word.length > 24) {
+ return {
+ ok: false,
+ reason: `keywords 每项须为 2–24 字符(单字词命中面失控):${JSON.stringify(k)}`,
+ };
+ }
+ const fold = word.toLowerCase();
+ if (seen.has(fold)) continue; // 重复词静默去重,不拒装
+ seen.add(fold);
+ keywords.push(word);
+ }
+ }
+
+ return {
+ ok: true,
+ manifest: {
+ schemaVersion: GHOST_MANIFEST_SCHEMA_VERSION,
+ id: raw.id,
+ name: raw.name,
+ version: raw.version,
+ ...(raw.minCindyVersion !== undefined
+ ? { minCindyVersion: raw.minCindyVersion as string }
+ : {}),
+ kind: 'chip',
+ ...(raw.author !== undefined ? { author: raw.author as string } : {}),
+ ...(locales !== undefined ? { locales } : {}),
+ ...(raw.description !== undefined ? { description: raw.description as string } : {}),
+ ...(raw.whenToUse !== undefined ? { whenToUse: raw.whenToUse as string } : {}),
+ ...(raw.icon !== undefined ? { icon: raw.icon as string } : {}),
+ entry: raw.entry,
+ ...(raw.launch !== undefined ? { launch: raw.launch as GhostLaunchMode } : {}),
+ ...(agent !== undefined ? { agent } : {}),
+ ...(node !== undefined ? { node } : {}),
+ ...(raw.settingsHtml !== undefined ? { settingsHtml: raw.settingsHtml as string } : {}),
+ ...(raw.settingsHeight !== undefined ? { settingsHeight: raw.settingsHeight as number } : {}),
+ slots,
+ ...(card !== undefined ? { card } : {}),
+ ...(tools !== undefined ? { tools } : {}),
+ ...(cindy !== undefined ? { cindy } : {}),
+ ...(subscribe !== undefined ? { subscribe } : {}),
+ ...(network !== undefined ? { network } : {}),
+ ...(raw.command !== undefined ? { command: raw.command as string } : {}),
+ ...(keywords !== undefined ? { keywords } : {}),
+ ...(panel !== undefined ? { panel } : {}),
+ ...(preview !== undefined ? { preview } : {}),
+ ...(skill !== undefined ? { skill } : {}),
+ ...(manual !== undefined ? { manual } : {}),
+ },
+ };
+}
diff --git a/packages/plugin-protocol/src/memberUpload.ts b/packages/plugin-protocol/src/memberUpload.ts
new file mode 100644
index 0000000000..b244227ea6
--- /dev/null
+++ b/packages/plugin-protocol/src/memberUpload.ts
@@ -0,0 +1,316 @@
+import {
+ PluginProtocolError,
+ httpsUrl,
+ isoDate,
+ nextCursor,
+ object,
+ sha256,
+ string,
+} from './internal/parse.js';
+import { isValidPluginResourceId } from './internal/pluginResourceId.js';
+import { isValidGhostId } from './manifest.js';
+
+export { PluginProtocolError } from './internal/parse.js';
+
+/**
+ * Organization member Plugin publishing wire contract.
+ *
+ * The limits below govern the member-upload channel only. Until plugin-server
+ * wires this channel in, its existing publisher-path validation limits remain
+ * authoritative for the paths it already serves.
+ */
+
+/** Maximum accepted `.cindy` archive size, aligned with Cindy Forge Node packages. */
+export const PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES = 128 * 1024 * 1024;
+/** Maximum aggregate uncompressed ZIP size. */
+export const PLUGIN_MEMBER_UPLOAD_MAX_UNCOMPRESSED_BYTES = 256 * 1024 * 1024;
+/** Maximum number of ZIP entries. */
+export const PLUGIN_MEMBER_UPLOAD_MAX_ZIP_ENTRIES = 2_048;
+
+/** Persistent source recorded for an interactive member upload. */
+export const PLUGIN_MEMBER_UPLOAD_PUBLISH_SOURCE = 'member_upload' as const;
+
+/** Persistent upload-task states returned by commit, status and "my publishes" APIs. */
+export const PLUGIN_MEMBER_UPLOAD_STATUSES = [
+ 'awaiting_upload',
+ 'validating',
+ 'publishing',
+ 'succeeded',
+ 'failed',
+ 'expired',
+] as const;
+export type PluginMemberUploadStatus = (typeof PLUGIN_MEMBER_UPLOAD_STATUSES)[number];
+
+/** Release review state after a member upload has produced a Release. */
+export const PLUGIN_MEMBER_RELEASE_REVIEW_STATUSES = ['pending', 'approved', 'rejected'] as const;
+export type PluginMemberReleaseReviewStatus =
+ (typeof PLUGIN_MEMBER_RELEASE_REVIEW_STATUSES)[number];
+
+/** Stable asynchronous failure codes persisted on an upload task. */
+export const PLUGIN_MEMBER_UPLOAD_FAILURE_CODES = [
+ 'UPLOAD_OBJECT_MISSING',
+ 'UPLOAD_SIZE_MISMATCH',
+ 'UPLOAD_SHA256_MISMATCH',
+ 'PLUGIN_PACKAGE_INVALID',
+ 'MEMBERSHIP_INACTIVE',
+ 'PUBLISH_NOT_AUTHORIZED',
+ 'PLUGIN_GHOST_ID_CONFLICT',
+ 'PUBLISH_STORAGE_UNAVAILABLE',
+ 'PUBLISH_INTERNAL_ERROR',
+] as const;
+export type PluginMemberUploadFailureCode = (typeof PLUGIN_MEMBER_UPLOAD_FAILURE_CODES)[number];
+
+/** Identity and idempotency are carried by verified auth/header context, not this body. */
+export interface PreparePluginMemberUploadRequest {
+ sizeBytes: number;
+ sha256: string;
+}
+
+export interface PreparePluginMemberUploadResponse {
+ uploadId: string;
+ putUrl: string;
+ headers: Record<string, string>;
+ expiresAt: string;
+ status: 'awaiting_upload';
+}
+
+/** ghostId, version and actor identity cannot be overridden by the commit body. */
+export type CommitPluginMemberUploadRequest = Record<string, never>;
+
+export interface CommitPluginMemberUploadResponse {
+ uploadId: string;
+ status: PluginMemberUploadStatus;
+}
+
+export interface PluginMemberUploadFailure {
+ code: PluginMemberUploadFailureCode;
+ /** Safe, user-facing reason. Must not contain internal object keys or audit details. */
+ message: string;
+}
+
+export interface PluginMemberUploadStatusResponse {
+ uploadId: string;
+ status: PluginMemberUploadStatus;
+ pluginId: string | null;
+ releaseId: string | null;
+ ghostId: string | null;
+ version: string | null;
+ /** Null until a Release exists; changes independently after upload success. */
+ reviewStatus: PluginMemberReleaseReviewStatus | null;
+ failure: PluginMemberUploadFailure | null;
+}
+
+export interface PluginMemberReleaseSummary extends PluginMemberUploadStatusResponse {
+ createdAt: string;
+ updatedAt: string;
+}
+
+export interface ListMyPluginMemberReleasesResponse {
+ releases: PluginMemberReleaseSummary[];
+ nextCursor: string | null;
+}
+
+function nullableString(value: unknown, path: string, max = 256): string | null {
+ return value === null ? null : string(value, path, max);
+}
+
+function nullableGhostId(value: unknown, path: string): string | null {
+ if (value === null) return null;
+ if (!isValidGhostId(value)) {
+ throw new PluginProtocolError(`${path} 不合法`);
+ }
+ return value;
+}
+
+function nullablePluginId(value: unknown, path: string): string | null {
+ if (value === null) return null;
+ if (!isValidPluginResourceId(value)) {
+ throw new PluginProtocolError(`${path} 不合法`);
+ }
+ return value;
+}
+
+function enumValue<T extends string>(
+ values: readonly T[],
+ value: unknown,
+ path: string,
+ description: string,
+): T {
+ if (typeof value !== 'string' || !values.includes(value as T)) {
+ throw new PluginProtocolError(`${path} ${description}`);
+ }
+ return value as T;
+}
+
+function uploadStatus(value: unknown, path: string): PluginMemberUploadStatus {
+ return enumValue(PLUGIN_MEMBER_UPLOAD_STATUSES, value, path, '不在成员上传状态集合中');
+}
+
+function reviewStatus(value: unknown, path: string): PluginMemberReleaseReviewStatus | null {
+ if (value === null) return null;
+ return enumValue(
+ PLUGIN_MEMBER_RELEASE_REVIEW_STATUSES,
+ value,
+ path,
+ '不在 Release 审核状态集合中',
+ );
+}
+
+function failure(value: unknown, path: string): PluginMemberUploadFailure | null {
+ if (value === null) return null;
+ const raw = object(value, path);
+ return {
+ code: enumValue(
+ PLUGIN_MEMBER_UPLOAD_FAILURE_CODES,
+ raw.code,
+ `${path}.code`,
+ '不在成员上传失败码集合中',
+ ),
+ message: string(raw.message, `${path}.message`, 1_000),
+ };
+}
+
+/** Validates the prepare body and rejects actor/package metadata overrides. */
+export function parsePreparePluginMemberUploadRequest(
+ value: unknown,
+): PreparePluginMemberUploadRequest {
+ const raw = object(value, 'request');
+ const unknownKeys = Object.keys(raw).filter((key) => key !== 'sizeBytes' && key !== 'sha256');
+ if (unknownKeys.length > 0) {
+ throw new PluginProtocolError(`request 不接受字段: ${unknownKeys.join(', ')}`);
+ }
+ if (
+ typeof raw.sizeBytes !== 'number' ||
+ !Number.isSafeInteger(raw.sizeBytes) ||
+ raw.sizeBytes <= 0 ||
+ raw.sizeBytes > PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES
+ ) {
+ throw new PluginProtocolError(
+ `request.sizeBytes 必须是 1–${PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES} 的安全整数`,
+ );
+ }
+ return { sizeBytes: raw.sizeBytes, sha256: sha256(raw.sha256, 'request.sha256') };
+}
+
+/** Validates that commit carries no package, path or identity override fields. */
+export function parseCommitPluginMemberUploadRequest(
+ value: unknown,
+): CommitPluginMemberUploadRequest {
+ if (value === undefined || value === null) return {};
+ const raw = object(value, 'request');
+ const keys = Object.keys(raw);
+ if (keys.length > 0) {
+ throw new PluginProtocolError(`request 不接受字段: ${keys.join(', ')}`);
+ }
+ return {};
+}
+
+export function parsePreparePluginMemberUploadResponse(
+ value: unknown,
+): PreparePluginMemberUploadResponse {
+ const raw = object(value, 'response');
+ if (raw.status !== 'awaiting_upload') {
+ throw new PluginProtocolError('response.status 必须是 awaiting_upload');
+ }
+ const putUrl = httpsUrl(raw.putUrl, 'response.putUrl');
+ const rawHeaders = object(raw.headers, 'response.headers');
+ const headers: Record<string, string> = {};
+ for (const [name, value] of Object.entries(rawHeaders)) {
+ if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) {
+ throw new PluginProtocolError('response.headers 包含非法 HTTP header 名');
+ }
+ const headerValue = string(value, `response.headers.${name}`, 8_192);
+ if (/[\r\n]/.test(headerValue)) {
+ throw new PluginProtocolError(`response.headers.${name} 不得包含换行`);
+ }
+ headers[name] = headerValue;
+ }
+ return {
+ uploadId: string(raw.uploadId, 'response.uploadId', 128),
+ putUrl,
+ headers,
+ expiresAt: isoDate(raw.expiresAt, 'response.expiresAt'),
+ status: 'awaiting_upload',
+ };
+}
+
+export function parseCommitPluginMemberUploadResponse(
+ value: unknown,
+): CommitPluginMemberUploadResponse {
+ const raw = object(value, 'response');
+ return {
+ uploadId: string(raw.uploadId, 'response.uploadId', 128),
+ status: uploadStatus(raw.status, 'response.status'),
+ };
+}
+
+function parsePluginMemberUploadStatusResponseAtPath(
+ value: unknown,
+ path: string,
+): PluginMemberUploadStatusResponse {
+ const raw = object(value, path);
+ const status = uploadStatus(raw.status, `${path}.status`);
+ const parsedReviewStatus = reviewStatus(raw.reviewStatus, `${path}.reviewStatus`);
+ const parsedFailure = failure(raw.failure, `${path}.failure`);
+ const result: PluginMemberUploadStatusResponse = {
+ uploadId: string(raw.uploadId, `${path}.uploadId`, 128),
+ status,
+ pluginId: nullablePluginId(raw.pluginId, `${path}.pluginId`),
+ releaseId: nullableString(raw.releaseId, `${path}.releaseId`, 128),
+ ghostId: nullableGhostId(raw.ghostId, `${path}.ghostId`),
+ version: nullableString(raw.version, `${path}.version`, 32),
+ reviewStatus: parsedReviewStatus,
+ failure: parsedFailure,
+ };
+ if (status === 'succeeded') {
+ if (
+ result.pluginId === null ||
+ result.releaseId === null ||
+ result.ghostId === null ||
+ result.version === null ||
+ result.reviewStatus === null
+ ) {
+ throw new PluginProtocolError('succeeded 状态必须包含 Release 标识与审核状态');
+ }
+ } else if (result.reviewStatus !== null) {
+ throw new PluginProtocolError('仅 succeeded 状态可包含 reviewStatus');
+ }
+ if (status === 'failed' && result.failure === null) {
+ throw new PluginProtocolError('failed 状态必须包含 failure');
+ }
+ if (status !== 'failed' && result.failure !== null) {
+ throw new PluginProtocolError('仅 failed 状态可包含 failure');
+ }
+ return result;
+}
+
+export function parsePluginMemberUploadStatusResponse(
+ value: unknown,
+): PluginMemberUploadStatusResponse {
+ return parsePluginMemberUploadStatusResponseAtPath(value, 'response');
+}
+
+function parseMemberReleaseSummary(value: unknown, path: string): PluginMemberReleaseSummary {
+ const raw = object(value, path);
+ const status = parsePluginMemberUploadStatusResponseAtPath(raw, path);
+ return {
+ ...status,
+ createdAt: isoDate(raw.createdAt, `${path}.createdAt`),
+ updatedAt: isoDate(raw.updatedAt, `${path}.updatedAt`),
+ };
+}
+
+export function parseListMyPluginMemberReleasesResponse(
+ value: unknown,
+): ListMyPluginMemberReleasesResponse {
+ const raw = object(value, 'response');
+ if (!Array.isArray(raw.releases)) {
+ throw new PluginProtocolError('response.releases 必须是数组');
+ }
+ return {
+ releases: raw.releases.map((release, index) =>
+ parseMemberReleaseSummary(release, `response.releases[${index}]`),
+ ),
+ nextCursor: nextCursor(raw.nextCursor, 'response.nextCursor'),
+ };
+}
diff --git a/packages/plugin-protocol/tsconfig.json b/packages/plugin-protocol/tsconfig.json
new file mode 100644
index 0000000000..3f9aa88f65
--- /dev/null
+++ b/packages/plugin-protocol/tsconfig.json
@@ -0,0 +1,11 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "strict": true,
+ "skipLibCheck": true,
+ "noEmit": true
+ },
+ "include": ["src/**/*.ts"]
+}
diff --git a/packages/slack-hook-protocol/package.json b/packages/slack-hook-protocol/package.json
new file mode 100644
index 0000000000..576120e2f1
--- /dev/null
+++ b/packages/slack-hook-protocol/package.json
@@ -0,0 +1,23 @@
+{
+ "name": "@cindy/slack-hook-protocol",
+ "version": "0.0.0",
+ "private": true,
+ "description": "slack-hook-server <-> desktop duplex task protocol: envelope, message types, runtime validation, builders. Zero runtime deps",
+ "type": "module",
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "exports": {
+ ".": "./src/index.ts",
+ "./types": "./src/types.ts"
+ },
+ "scripts": {
+ "build": "tsc --noEmit",
+ "test": "vitest run"
+ },
+ "license": "Apache-2.0",
+ "devDependencies": {
+ "@types/node": "*",
+ "typescript": "^5.7.0",
+ "vitest": "^3.2.4"
+ }
+}
diff --git a/packages/slack-hook-protocol/src/__tests__/protocol-behavior.test.ts b/packages/slack-hook-protocol/src/__tests__/protocol-behavior.test.ts
new file mode 100644
index 0000000000..af4127df64
--- /dev/null
+++ b/packages/slack-hook-protocol/src/__tests__/protocol-behavior.test.ts
@@ -0,0 +1,419 @@
+/**
+ * slack-hook-protocol 阶段 19(Telegram 行为配置)测试:
+ * 1. provider.behavior.get/set/state 构造 -> 序列化 -> 解析 round-trip
+ * 2. 选择器校验: provider 只认 telegram、bindingId 非空必填(不接受 scopeId 替代)
+ * 3. set: 三个全局字段的 `enum | null` patch 三态(不动 / 显式 override / 显式
+ * 清除), 各自取值校验, 以及"至少一个实际 patch"的空 set 拒收(null 也算
+ * 一次真实改动)
+ * 4. state: 三个全局字段收敛为必填非空枚举(从不是 patch、从不是 null)、
+ * groupActivation 的形状/取值校验与累积可表达性, 以及 bound=false -> 默认值 + 空
+ * groupActivation 的字段联动(parse 强制)
+ * 5. 能力标识常量 provider-behavior-v1
+ * 6. DEFAULT_TELEGRAM_BEHAVIOR 与个人版桌面客户端出厂默认对齐
+ */
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ DEFAULT_TELEGRAM_BEHAVIOR,
+ HOOK_FEATURE_PROVIDER_BEHAVIOR,
+ PROVIDER_BEHAVIOR_PROVIDERS,
+ TELEGRAM_EMOJI_REACTIONS,
+ TELEGRAM_GROUP_ACTIVATION_ALWAYS,
+ TELEGRAM_REPLY_QUOTE_DM,
+ TELEGRAM_REPLY_QUOTE_GROUP,
+ makeProviderBehaviorGet,
+ makeProviderBehaviorSet,
+ makeProviderBehaviorState,
+ parseHookMessage,
+ serializeHookMessage,
+ type HookMessage,
+ type ProviderBehaviorGetPayload,
+ type ProviderBehaviorSetPayload,
+ type ProviderBehaviorStatePayload,
+} from '../index';
+
+function roundTrip(message: HookMessage): HookMessage {
+ const parsed = parseHookMessage(serializeHookMessage(message));
+ expect(parsed.ok, parsed.ok ? '' : parsed.error).toBe(true);
+ if (!parsed.ok) throw new Error('unreachable');
+ expect(parsed.message).toEqual(message);
+ return parsed.message;
+}
+
+function expectReject(mutated: unknown, keyword: string): void {
+ const parsed = parseHookMessage(mutated);
+ expect(parsed.ok).toBe(false);
+ if (parsed.ok) throw new Error('unreachable');
+ expect(parsed.error).toContain(keyword);
+}
+
+const BINDING_ID = 'binding-tg-1';
+const CHAT_ID = '-1001234567890';
+
+const GET: ProviderBehaviorGetPayload = {
+ requestId: 'behavior-req-1',
+ provider: 'telegram',
+ bindingId: BINDING_ID,
+};
+
+const SET_GLOBAL_ONLY: ProviderBehaviorSetPayload = {
+ requestId: 'behavior-req-2',
+ provider: 'telegram',
+ bindingId: BINDING_ID,
+ emojiReactions: 'minimal',
+ replyQuoteDm: 'first',
+ replyQuoteGroup: 'all',
+};
+
+const SET_GROUP_ACTIVATION_ONLY: ProviderBehaviorSetPayload = {
+ requestId: 'behavior-req-3',
+ provider: 'telegram',
+ bindingId: BINDING_ID,
+ groupActivation: { chatId: CHAT_ID, value: TELEGRAM_GROUP_ACTIVATION_ALWAYS },
+};
+
+const SET_GROUP_ACTIVATION_CLEAR: ProviderBehaviorSetPayload = {
+ requestId: 'behavior-req-4',
+ provider: 'telegram',
+ bindingId: BINDING_ID,
+ groupActivation: { chatId: CHAT_ID, value: null },
+};
+
+const SET_COMBINED: ProviderBehaviorSetPayload = {
+ requestId: 'behavior-req-5',
+ provider: 'telegram',
+ bindingId: BINDING_ID,
+ emojiReactions: 'expressive',
+ replyQuoteDm: 'off',
+ replyQuoteGroup: 'first',
+ groupActivation: { chatId: CHAT_ID, value: TELEGRAM_GROUP_ACTIVATION_ALWAYS },
+};
+
+// 三个全局字段的 null = 显式清除 override(回落版本默认), 与 undefined(不动)
+// 是不同的三态第三态。
+const SET_GLOBAL_ALL_NULL: ProviderBehaviorSetPayload = {
+ requestId: 'behavior-req-6',
+ provider: 'telegram',
+ bindingId: BINDING_ID,
+ emojiReactions: null,
+ replyQuoteDm: null,
+ replyQuoteGroup: null,
+};
+
+const SET_SINGLE_NULL_ONLY: ProviderBehaviorSetPayload = {
+ requestId: 'behavior-req-7',
+ provider: 'telegram',
+ bindingId: BINDING_ID,
+ emojiReactions: null,
+};
+
+const SET_NULL_PLUS_GROUP_ACTIVATION: ProviderBehaviorSetPayload = {
+ requestId: 'behavior-req-8',
+ provider: 'telegram',
+ bindingId: BINDING_ID,
+ replyQuoteGroup: null,
+ groupActivation: { chatId: CHAT_ID, value: TELEGRAM_GROUP_ACTIVATION_ALWAYS },
+};
+
+const STATE_BOUND_NON_DEFAULT: ProviderBehaviorStatePayload = {
+ provider: 'telegram',
+ bindingId: BINDING_ID,
+ replyTo: 'behavior-req-5',
+ bound: true,
+ emojiReactions: 'expressive',
+ replyQuoteDm: 'first',
+ replyQuoteGroup: 'all',
+ groupActivation: { [CHAT_ID]: TELEGRAM_GROUP_ACTIVATION_ALWAYS },
+};
+
+const STATE_BOUND_DEFAULT: ProviderBehaviorStatePayload = {
+ provider: 'telegram',
+ bindingId: BINDING_ID,
+ replyTo: null,
+ bound: true,
+ ...DEFAULT_TELEGRAM_BEHAVIOR,
+ groupActivation: {},
+};
+
+const STATE_UNBOUND: ProviderBehaviorStatePayload = {
+ provider: 'telegram',
+ bindingId: BINDING_ID,
+ replyTo: null,
+ bound: false,
+ ...DEFAULT_TELEGRAM_BEHAVIOR,
+ groupActivation: {},
+};
+
+describe('provider.behavior(阶段 19)', () => {
+ it('能力标识常量', () => {
+ expect(HOOK_FEATURE_PROVIDER_BEHAVIOR).toBe('provider-behavior-v1');
+ });
+
+ it('导出的 provider/behavior 枚举表在运行时不可变', () => {
+ expect(Object.isFrozen(PROVIDER_BEHAVIOR_PROVIDERS)).toBe(true);
+ expect(Object.isFrozen(TELEGRAM_EMOJI_REACTIONS)).toBe(true);
+ expect(Object.isFrozen(TELEGRAM_REPLY_QUOTE_DM)).toBe(true);
+ expect(Object.isFrozen(TELEGRAM_REPLY_QUOTE_GROUP)).toBe(true);
+ });
+
+ it('DEFAULT_TELEGRAM_BEHAVIOR 与个人版桌面客户端出厂默认对齐', () => {
+ expect(DEFAULT_TELEGRAM_BEHAVIOR).toEqual({
+ emojiReactions: 'minimal',
+ replyQuoteDm: 'off',
+ replyQuoteGroup: 'first',
+ });
+ expect(Object.isFrozen(DEFAULT_TELEGRAM_BEHAVIOR)).toBe(true);
+ expect(() => {
+ (DEFAULT_TELEGRAM_BEHAVIOR as { emojiReactions: string }).emojiReactions = 'off';
+ }).toThrow(TypeError);
+ });
+
+ it('round-trip: get', () => {
+ roundTrip(makeProviderBehaviorGet(GET));
+ });
+
+ it('round-trip: set(全局字段 / groupActivation 单独 / 混合 / 清除)', () => {
+ roundTrip(makeProviderBehaviorSet(SET_GLOBAL_ONLY));
+ roundTrip(makeProviderBehaviorSet(SET_GROUP_ACTIVATION_ONLY));
+ roundTrip(makeProviderBehaviorSet(SET_GROUP_ACTIVATION_CLEAR));
+ roundTrip(makeProviderBehaviorSet(SET_COMBINED));
+ });
+
+ it('round-trip: set 全局字段的显式 null(清除 override, 与 undefined 不同)', () => {
+ roundTrip(makeProviderBehaviorSet(SET_GLOBAL_ALL_NULL));
+ // 只 clear 一个字段、其余不动, 仍算一次实际 patch, 不会被当空 set 拒收。
+ roundTrip(makeProviderBehaviorSet(SET_SINGLE_NULL_ONLY));
+ // null 清除与 groupActivation patch 可同帧组合。
+ roundTrip(makeProviderBehaviorSet(SET_NULL_PLUS_GROUP_ACTIVATION));
+ });
+
+ it('round-trip: state(bound 非默认 / bound 默认 / 未绑定)', () => {
+ roundTrip(makeProviderBehaviorState(STATE_BOUND_NON_DEFAULT));
+ roundTrip(makeProviderBehaviorState(STATE_BOUND_DEFAULT));
+ roundTrip(makeProviderBehaviorState(STATE_UNBOUND));
+ });
+
+ it('选择器校验: bindingId 必须非空字符串, 不接受缺省或 scopeId 替代', () => {
+ const get = makeProviderBehaviorGet(GET);
+ expectReject({ ...get, payload: { ...GET, bindingId: '' } }, 'provider.behavior.get.bindingId');
+ const missingBindingId: Record<string, unknown> = { ...GET };
+ delete missingBindingId.bindingId;
+ expectReject({ ...get, payload: missingBindingId }, 'provider.behavior.get.bindingId');
+ // scopeId 不是这个 selector 认识的字段: 加了也不能替代 bindingId。
+ expectReject(
+ {
+ ...get,
+ payload: { requestId: GET.requestId, provider: GET.provider, scopeId: 'bot-1' },
+ },
+ 'provider.behavior.get.bindingId',
+ );
+ });
+
+ it('选择器校验: provider 只认 telegram(get/set/state 三帧都拒收非法值)', () => {
+ const get = makeProviderBehaviorGet(GET);
+ expectReject(
+ { ...get, payload: { ...GET, provider: 'slack' } },
+ 'provider.behavior.get.provider',
+ );
+ const set = makeProviderBehaviorSet(SET_GLOBAL_ONLY);
+ expectReject(
+ { ...set, payload: { ...SET_GLOBAL_ONLY, provider: 'x' } },
+ 'provider.behavior.set.provider',
+ );
+ const state = makeProviderBehaviorState(STATE_BOUND_DEFAULT);
+ expectReject(
+ { ...state, payload: { ...STATE_BOUND_DEFAULT, provider: 'discord' } },
+ 'provider.behavior.state.provider',
+ );
+ });
+
+ it('set: 三个全局字段各自校验非法取值(必须是已知枚举或 null, 二者之外都拒收)', () => {
+ const set = makeProviderBehaviorSet(SET_GLOBAL_ONLY);
+ expectReject(
+ { ...set, payload: { ...SET_GLOBAL_ONLY, emojiReactions: 'loud' } },
+ 'provider.behavior.set.emojiReactions',
+ );
+ expectReject(
+ { ...set, payload: { ...SET_GLOBAL_ONLY, replyQuoteDm: 'always' } },
+ 'provider.behavior.set.replyQuoteDm',
+ );
+ expectReject(
+ { ...set, payload: { ...SET_GLOBAL_ONLY, replyQuoteGroup: 'some' } },
+ 'provider.behavior.set.replyQuoteGroup',
+ );
+ // 非字符串、非 null 的其它类型同样拒收(不能借道混入任意值)。
+ expectReject(
+ { ...set, payload: { ...SET_GLOBAL_ONLY, emojiReactions: 0 } },
+ 'provider.behavior.set.emojiReactions',
+ );
+ });
+
+ it('set: groupActivation patch 的 chatId / value 校验', () => {
+ const set = makeProviderBehaviorSet(SET_GROUP_ACTIVATION_ONLY);
+ expectReject(
+ {
+ ...set,
+ payload: {
+ ...SET_GROUP_ACTIVATION_ONLY,
+ groupActivation: { chatId: 'not-a-number', value: TELEGRAM_GROUP_ACTIVATION_ALWAYS },
+ },
+ },
+ 'provider.behavior.set.groupActivation.chatId',
+ );
+ for (const chatId of ['0', '123', '-0', '-001', '-4503599627370496']) {
+ expectReject(
+ {
+ ...set,
+ payload: {
+ ...SET_GROUP_ACTIVATION_ONLY,
+ groupActivation: { chatId, value: TELEGRAM_GROUP_ACTIVATION_ALWAYS },
+ },
+ },
+ 'provider.behavior.set.groupActivation.chatId',
+ );
+ }
+ expectReject(
+ {
+ ...set,
+ payload: {
+ ...SET_GROUP_ACTIVATION_ONLY,
+ groupActivation: { chatId: '', value: TELEGRAM_GROUP_ACTIVATION_ALWAYS },
+ },
+ },
+ 'provider.behavior.set.groupActivation.chatId',
+ );
+ expectReject(
+ {
+ ...set,
+ payload: {
+ ...SET_GROUP_ACTIVATION_ONLY,
+ groupActivation: { chatId: '1'.repeat(33), value: TELEGRAM_GROUP_ACTIVATION_ALWAYS },
+ },
+ },
+ 'provider.behavior.set.groupActivation.chatId',
+ );
+ expectReject(
+ {
+ ...set,
+ payload: {
+ ...SET_GROUP_ACTIVATION_ONLY,
+ groupActivation: { chatId: CHAT_ID, value: 'mention' },
+ },
+ },
+ 'provider.behavior.set.groupActivation.value',
+ );
+ expectReject(
+ {
+ ...set,
+ payload: { ...SET_GROUP_ACTIVATION_ONLY, groupActivation: 'not-an-object' },
+ },
+ 'provider.behavior.set.groupActivation',
+ );
+ });
+
+ it('set: 空 patch(既无全局字段也无 groupActivation)拒收', () => {
+ const set = makeProviderBehaviorSet(SET_GLOBAL_ONLY);
+ const empty: Record<string, unknown> = {
+ requestId: SET_GLOBAL_ONLY.requestId,
+ provider: SET_GLOBAL_ONLY.provider,
+ bindingId: SET_GLOBAL_ONLY.bindingId,
+ };
+ expectReject({ ...set, payload: empty }, 'at least one behavior field');
+ });
+
+ it('set: requestId 必须非空字符串', () => {
+ const set = makeProviderBehaviorSet(SET_GLOBAL_ONLY);
+ expectReject(
+ { ...set, payload: { ...SET_GLOBAL_ONLY, requestId: '' } },
+ 'provider.behavior.set.requestId',
+ );
+ });
+
+ it('state: 三个全局字段必须是完整(非 patch)非空枚举值 —— 不接受 undefined 也不接受 null', () => {
+ const state = makeProviderBehaviorState(STATE_BOUND_DEFAULT);
+ expectReject(
+ { ...state, payload: { ...STATE_BOUND_DEFAULT, emojiReactions: undefined } },
+ 'provider.behavior.state.emojiReactions',
+ );
+ // 与 set 不同: state 是已解析的有效值快照, null(patch 语义里的"清除")在这里
+ // 没有意义 —— 必须已经解析成某个具体的默认或 override 枚举值。
+ expectReject(
+ { ...state, payload: { ...STATE_BOUND_DEFAULT, emojiReactions: null } },
+ 'provider.behavior.state.emojiReactions',
+ );
+ expectReject(
+ { ...state, payload: { ...STATE_BOUND_DEFAULT, replyQuoteDm: 'loud' } },
+ 'provider.behavior.state.replyQuoteDm',
+ );
+ expectReject(
+ { ...state, payload: { ...STATE_BOUND_DEFAULT, replyQuoteGroup: 'lots' } },
+ 'provider.behavior.state.replyQuoteGroup',
+ );
+ });
+
+ it('state: groupActivation 形状、键值校验与累积可表达性', () => {
+ const state = makeProviderBehaviorState(STATE_BOUND_NON_DEFAULT);
+ expectReject(
+ { ...state, payload: { ...STATE_BOUND_NON_DEFAULT, groupActivation: 'not-an-object' } },
+ 'provider.behavior.state.groupActivation must be an object',
+ );
+ expectReject(
+ {
+ ...state,
+ payload: {
+ ...STATE_BOUND_NON_DEFAULT,
+ groupActivation: { 'not-a-chat-id': TELEGRAM_GROUP_ACTIVATION_ALWAYS },
+ },
+ },
+ 'provider.behavior.state.groupActivation key must be a canonical negative Telegram group chat id',
+ );
+ expectReject(
+ {
+ ...state,
+ payload: {
+ ...STATE_BOUND_NON_DEFAULT,
+ groupActivation: { '001': TELEGRAM_GROUP_ACTIVATION_ALWAYS },
+ },
+ },
+ 'provider.behavior.state.groupActivation key must be a canonical negative Telegram group chat id',
+ );
+ expectReject(
+ {
+ ...state,
+ payload: { ...STATE_BOUND_NON_DEFAULT, groupActivation: { [CHAT_ID]: 'mention' } },
+ },
+ `must be '${TELEGRAM_GROUP_ACTIVATION_ALWAYS}'`,
+ );
+ const accumulated: Record<string, typeof TELEGRAM_GROUP_ACTIVATION_ALWAYS> = Object.fromEntries(
+ Array.from({ length: 501 }, (_, i) => [`-${i + 1}`, TELEGRAM_GROUP_ACTIVATION_ALWAYS]),
+ );
+ roundTrip(
+ makeProviderBehaviorState({ ...STATE_BOUND_NON_DEFAULT, groupActivation: accumulated }),
+ );
+ });
+
+ it('字段联动(parse 强制): bound=false 必须收敛为默认行为与空 groupActivation', () => {
+ const nonDefaultState = makeProviderBehaviorState(STATE_BOUND_NON_DEFAULT);
+ expectReject(
+ { ...nonDefaultState, payload: { ...STATE_BOUND_NON_DEFAULT, bound: false } },
+ 'must report the default behavior when bound is false',
+ );
+
+ const defaultState = makeProviderBehaviorState(STATE_BOUND_DEFAULT);
+ expectReject(
+ {
+ ...defaultState,
+ payload: {
+ ...STATE_BOUND_DEFAULT,
+ bound: false,
+ groupActivation: { [CHAT_ID]: TELEGRAM_GROUP_ACTIVATION_ALWAYS },
+ },
+ },
+ 'groupActivation must be empty when bound is false',
+ );
+
+ // 反过来: bound=false 且已是默认值 + 空 map 的合法快照必须放行(已在上面的
+ // round-trip 用例覆盖 STATE_UNBOUND, 这里不重复)。
+ });
+});
diff --git a/packages/slack-hook-protocol/src/__tests__/protocol-group-relay.test.ts b/packages/slack-hook-protocol/src/__tests__/protocol-group-relay.test.ts
new file mode 100644
index 0000000000..f73c42511e
--- /dev/null
+++ b/packages/slack-hook-protocol/src/__tests__/protocol-group-relay.test.ts
@@ -0,0 +1,286 @@
+/**
+ * slack-hook-protocol 阶段 14(群消息中继帧)测试:
+ * 1. group.message 构造 -> 序列化 -> 解析 round-trip(全字段 / 最小字段)
+ * 2. 字段校验: 必填、text/fileNames 至少其一、上限、threadId/chatName 显式 null
+ * 3. 能力标识常量 group-relay-v1
+ * 4. 老端兼容: 不认识 group.message 的端按未知类型拒收(丢帧不断连语义)
+ */
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ HOOK_FEATURE_GROUP_RELAY,
+ HOOK_FEATURE_GROUP_RELAY_RECIPIENT,
+ makeGroupMessage,
+ makeTaskDispatch,
+ parseHookMessage,
+ serializeHookMessage,
+ type GroupMessagePayload,
+ type HookMessage,
+} from '../index';
+
+function roundTrip(message: HookMessage): HookMessage {
+ const parsed = parseHookMessage(serializeHookMessage(message));
+ expect(parsed.ok, parsed.ok ? '' : parsed.error).toBe(true);
+ if (!parsed.ok) throw new Error('unreachable');
+ expect(parsed.message).toEqual(message);
+ return parsed.message;
+}
+
+function expectReject(mutated: unknown, keyword: string): void {
+ const parsed = parseHookMessage(mutated);
+ expect(parsed.ok).toBe(false);
+ if (parsed.ok) throw new Error('unreachable');
+ expect(parsed.error).toContain(keyword);
+}
+
+const FULL: GroupMessagePayload = {
+ provider: 'telegram',
+ recipient: { bindingId: 'binding-101', principalId: '101' },
+ chatId: '-1001234567890',
+ threadId: '77',
+ messageId: '4213',
+ chatName: 'Cindy Dev',
+ author: { name: '@user202', isBot: false },
+ text: '昨天部署失败了',
+ fileNames: ['error.log'],
+ sentAt: 1_785_200_000_000,
+};
+
+describe('group.message(阶段 14)', () => {
+ it('round-trip: 全字段与最小字段', () => {
+ roundTrip(makeGroupMessage(FULL));
+ roundTrip(
+ makeGroupMessage({
+ provider: 'telegram',
+ chatId: '-900',
+ threadId: null,
+ messageId: '1',
+ chatName: null,
+ author: { name: 'Cindy(bot)', isBot: true },
+ text: '看起来是连接池耗尽',
+ sentAt: 1_785_200_000_001,
+ }),
+ );
+ });
+
+ it('纯附件消息: text 可为空但 fileNames 必须非空', () => {
+ roundTrip(makeGroupMessage({ ...FULL, text: '', fileNames: ['photo.jpg'] }));
+ const empty = makeGroupMessage({ ...FULL, text: '' });
+ delete (empty.payload as Partial<GroupMessagePayload>).fileNames;
+ expectReject(empty, 'text or fileNames');
+ });
+
+ it('字段校验: 必填与显式 null', () => {
+ expectReject({ ...makeGroupMessage(FULL), payload: { ...FULL, chatId: '' } }, 'chatId');
+ expectReject({ ...makeGroupMessage(FULL), payload: { ...FULL, messageId: '' } }, 'messageId');
+ expectReject(
+ { ...makeGroupMessage(FULL), payload: { ...FULL, author: { name: '' } } },
+ 'author.name',
+ );
+ expectReject({ ...makeGroupMessage(FULL), payload: { ...FULL, sentAt: 0 } }, 'sentAt');
+ // threadId / chatName 必须显式 null, 不接受缺省。
+ const noThread: Record<string, unknown> = { ...FULL };
+ delete noThread.threadId;
+ expectReject({ ...makeGroupMessage(FULL), payload: noThread }, 'threadId');
+ });
+
+ it('上限: 超长 text 与超量 fileNames 拒收', () => {
+ expectReject(
+ { ...makeGroupMessage(FULL), payload: { ...FULL, text: 'x'.repeat(8_193) } },
+ 'text',
+ );
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, fileNames: Array.from({ length: 21 }, (_, i) => `f${i}`) },
+ },
+ 'fileNames',
+ );
+ expectReject(
+ { ...makeGroupMessage(FULL), payload: { ...FULL, fileNames: ['x'.repeat(257)] } },
+ 'fileNames',
+ );
+ });
+
+ it('能力标识常量', () => {
+ expect(HOOK_FEATURE_GROUP_RELAY).toBe('group-relay-v1');
+ expect(HOOK_FEATURE_GROUP_RELAY_RECIPIENT).toBe('group-relay-recipient-v1');
+ });
+
+ it('recipient 绑定接收方代际;旧帧可缺省,新帧字段必须完整', () => {
+ roundTrip(makeGroupMessage({ ...FULL, recipient: undefined }));
+ roundTrip(makeGroupMessage(FULL));
+ expectReject({ ...makeGroupMessage(FULL), payload: { ...FULL, recipient: null } }, 'recipient');
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, recipient: { bindingId: '', principalId: '101' } },
+ },
+ 'recipient.bindingId',
+ );
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, recipient: { bindingId: 'binding-101', principalId: '' } },
+ },
+ 'recipient.principalId',
+ );
+ });
+
+ it('provider 是开放集合: 非 telegram 值照常通过', () => {
+ roundTrip(makeGroupMessage({ ...FULL, provider: 'discord' }));
+ });
+
+ it('author.id / author.username(阶段 19 追加, 可选): 携带时 round-trip, 省略时(老形态)仍照常通过', () => {
+ // 老形态: 无 id/username, 与 FULL 完全一致 —— 已在上面的 round-trip 用例覆盖,
+ // 这里再显式断言一次解析结果里两个字段确实缺席(而非被静默填充成 undefined 之外的值)。
+ const legacy = roundTrip(makeGroupMessage(FULL));
+ expect((legacy.payload as GroupMessagePayload).author).toEqual({
+ name: '@user202',
+ isBot: false,
+ });
+
+ // 新形态: 两个字段都带上(Telegram 真实契约: id 纯数字, username 字母数字下划线)。
+ roundTrip(
+ makeGroupMessage({
+ ...FULL,
+ author: { name: '@user202', isBot: false, id: '202', username: 'user202' },
+ }),
+ );
+ // 只带其中一个也应放行。
+ roundTrip(makeGroupMessage({ ...FULL, author: { name: '@user202', id: '202' } }));
+ roundTrip(makeGroupMessage({ ...FULL, author: { name: '@user202', username: 'user202' } }));
+ // 边界: id 恰好为 52-bit 上限、username 恰好 32 位字符都必须放行。
+ roundTrip(makeGroupMessage({ ...FULL, author: { name: '@user202', id: '4503599627370495' } }));
+ roundTrip(
+ makeGroupMessage({ ...FULL, author: { name: '@user202', username: 'u'.repeat(32) } }),
+ );
+ });
+
+ it('author.id 按 Telegram 契约收紧: 规范正整数且在 52-bit 范围内', () => {
+ expectReject(
+ { ...makeGroupMessage(FULL), payload: { ...FULL, author: { name: '@user202', id: '' } } },
+ 'author.id',
+ );
+ for (const id of ['0', '001', '4503599627370496', '1'.repeat(21)]) {
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, author: { name: '@user202', id } },
+ },
+ 'author.id',
+ );
+ }
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, author: { name: '@user202', id: 'has space' } },
+ },
+ 'author.id',
+ );
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, author: { name: '@user202', id: 42 } },
+ },
+ 'author.id',
+ );
+ // 收紧前(通用可打印 ASCII)允许的形态, 收紧后必须拒收: 字母、符号、负号。
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, author: { name: '@user202', id: 'abc123' } },
+ },
+ 'author.id',
+ );
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, author: { name: '@user202', id: '-202' } },
+ },
+ 'author.id',
+ );
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, author: { name: '@user202', id: '202.0' } },
+ },
+ 'author.id',
+ );
+ });
+
+ it('author.username 按 Telegram 契约收紧: 仅 [A-Za-z0-9_], 1~32 位', () => {
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, author: { name: '@user202', username: '' } },
+ },
+ 'author.username',
+ );
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, author: { name: '@user202', username: 'u'.repeat(33) } },
+ },
+ 'author.username',
+ );
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, author: { name: '@user202', username: 'has space' } },
+ },
+ 'author.username',
+ );
+ // 收紧前(通用可打印 ASCII)允许的形态, 收紧后必须拒收: 连字符、@ 前缀、点号。
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, author: { name: '@user202', username: 'user-202' } },
+ },
+ 'author.username',
+ );
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, author: { name: '@user202', username: '@user202' } },
+ },
+ 'author.username',
+ );
+ expectReject(
+ {
+ ...makeGroupMessage(FULL),
+ payload: { ...FULL, author: { name: '@user202', username: 'user.202' } },
+ },
+ 'author.username',
+ );
+ });
+
+ it('task.dispatch.source.triggerMessageId: 可选、非空字符串或显式 null', () => {
+ const dispatch = makeTaskDispatch({
+ requestId: 'req-1',
+ externalKey: 'telegram:group:1:-1:1:9:g1',
+ workspace: 'chat',
+ sessionId: null,
+ prompt: 'hi',
+ source: { im: 'telegram', userText: 'hi', triggerMessageId: '4213' },
+ });
+ roundTrip(dispatch);
+ roundTrip(
+ makeTaskDispatch({
+ ...dispatch.payload,
+ source: { im: 'telegram', triggerMessageId: null },
+ }),
+ );
+ expectReject(
+ {
+ ...dispatch,
+ payload: {
+ ...dispatch.payload,
+ source: { im: 'telegram', triggerMessageId: '' },
+ },
+ },
+ 'triggerMessageId',
+ );
+ });
+});
diff --git a/packages/slack-hook-protocol/src/__tests__/protocol-interaction.test.ts b/packages/slack-hook-protocol/src/__tests__/protocol-interaction.test.ts
new file mode 100644
index 0000000000..5004cc4349
--- /dev/null
+++ b/packages/slack-hook-protocol/src/__tests__/protocol-interaction.test.ts
@@ -0,0 +1,136 @@
+/**
+ * slack-hook-protocol 阶段 10(执行中交互)帧测试:
+ * 1. interaction.request / decision / cancel 构造 -> 序列化 -> 解析 round-trip
+ * 2. request 的按钮约束(非空 / 上限 / id 唯一 / id 不含 '|' / style 枚举)
+ * 3. progress 复活语义不在此测(payload 形状未变, 见 protocol.test.ts)
+ */
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ MAX_INTERACTION_BUTTONS,
+ makeInteractionCancel,
+ makeInteractionDecision,
+ makeInteractionRequest,
+ parseHookMessage,
+ serializeHookMessage,
+ type HookMessage,
+ type InteractionRequestPayload,
+} from '../index';
+
+function roundTrip(message: HookMessage): HookMessage {
+ const parsed = parseHookMessage(serializeHookMessage(message));
+ expect(parsed.ok, parsed.ok ? '' : parsed.error).toBe(true);
+ if (!parsed.ok) throw new Error('unreachable');
+ expect(parsed.message).toEqual(message);
+ return parsed.message;
+}
+
+function expectReject(mutated: unknown, keyword: string): void {
+ const parsed = parseHookMessage(mutated);
+ expect(parsed.ok).toBe(false);
+ if (parsed.ok) throw new Error('unreachable');
+ expect(parsed.error).toContain(keyword);
+}
+
+const REQUEST: InteractionRequestPayload = {
+ requestId: 'req-1',
+ interactionId: 'int-1',
+ kind: 'ask_user_question',
+ title: '❓ 选一个方案',
+ body: '两个方案各有取舍',
+ buttons: [
+ { id: 'ask:0', label: '方案 A', style: 'default' },
+ { id: 'ask:1', label: '方案 B', style: 'primary' },
+ ],
+};
+
+describe('interaction.* 帧', () => {
+ it('三种帧 round-trip', () => {
+ roundTrip(makeInteractionRequest(REQUEST));
+ roundTrip(
+ makeInteractionDecision({ requestId: 'req-1', interactionId: 'int-1', buttonId: 'ask:1' }),
+ );
+ roundTrip(
+ makeInteractionCancel({ requestId: 'req-1', interactionId: 'int-1', reason: '等待超时' }),
+ );
+ });
+
+ it('request: body 可为空串, buttons 不可为空数组', () => {
+ roundTrip(makeInteractionRequest({ ...REQUEST, body: '' }));
+ const msg = makeInteractionRequest(REQUEST);
+ expectReject({ ...msg, payload: { ...REQUEST, buttons: [] } }, 'non-empty array');
+ });
+
+ it('request: 按钮上限 / id 唯一 / id 不含竖线 / style 枚举', () => {
+ const msg = makeInteractionRequest(REQUEST);
+ const many = Array.from({ length: MAX_INTERACTION_BUTTONS + 1 }, (_, i) => ({
+ id: `b${i}`,
+ label: 'x',
+ style: 'default' as const,
+ }));
+ expectReject({ ...msg, payload: { ...REQUEST, buttons: many } }, 'at most');
+ expectReject(
+ {
+ ...msg,
+ payload: {
+ ...REQUEST,
+ buttons: [
+ { id: 'dup', label: 'a', style: 'default' },
+ { id: 'dup', label: 'b', style: 'default' },
+ ],
+ },
+ },
+ 'unique',
+ );
+ expectReject(
+ { ...msg, payload: { ...REQUEST, buttons: [{ id: 'a|b', label: 'x', style: 'default' }] } },
+ "must not contain '|'",
+ );
+ expectReject(
+ { ...msg, payload: { ...REQUEST, buttons: [{ id: 'a', label: 'x', style: 'fancy' }] } },
+ 'style must be one of',
+ );
+ });
+
+ it('decision / cancel: 关键字段缺失拒收', () => {
+ const d = makeInteractionDecision({ requestId: 'r', interactionId: 'i', buttonId: 'b' });
+ expectReject(
+ { ...d, payload: { requestId: 'r', interactionId: 'i', buttonId: '' } },
+ 'buttonId',
+ );
+ const c = makeInteractionCancel({ requestId: 'r', interactionId: 'i', reason: '' });
+ roundTrip(c); // reason 允许空串(字符串即可)
+ expectReject({ ...c, payload: { requestId: 'r', reason: 'x' } }, 'interactionId');
+ });
+});
+
+describe('turn.end 出站附件', () => {
+ it('携带 attachments round-trip; 形状非法拒收; 缺省合法', async () => {
+ const { makeTurnEnd } = await import('../index');
+ const base = {
+ requestId: 'r1',
+ externalKey: 'C1:1.1',
+ sessionId: 's1',
+ status: 'ok' as const,
+ finalText: '完成',
+ errorMessage: null,
+ usage: { durationMs: 100 },
+ };
+ roundTrip(makeTurnEnd(base)); // 缺省
+ roundTrip(
+ makeTurnEnd({
+ ...base,
+ attachments: [{ name: 'chart.png', mimeType: 'image/png', dataBase64: 'aGk=' }],
+ }),
+ );
+ const msg = makeTurnEnd(base);
+ expectReject(
+ {
+ ...msg,
+ payload: { ...base, attachments: [{ name: 'x', mimeType: '', dataBase64: 'aGk=' }] },
+ },
+ 'turn.end.attachments[0].mimeType',
+ );
+ });
+});
diff --git a/packages/slack-hook-protocol/src/__tests__/protocol-msg-op.test.ts b/packages/slack-hook-protocol/src/__tests__/protocol-msg-op.test.ts
new file mode 100644
index 0000000000..26ad372842
--- /dev/null
+++ b/packages/slack-hook-protocol/src/__tests__/protocol-msg-op.test.ts
@@ -0,0 +1,129 @@
+/**
+ * slack-hook-protocol 阶段 20(msg.op 消息操作动词)测试:
+ * 1. 六种动作的构造 → 序列化 → 解析 round-trip
+ * 2. 幂等键 opId 与授权锚点 scope.externalKey 缺失即拒收
+ * 3. msg.op.result 的 messageId 契约(客户端后续 edit/delete/react 的唯一依据)
+ * 4. 能力标识常量 msg-op-v1
+ * 5. 老端兼容: 不认识 msg.op 的端按未知类型拒收(丢帧不断连语义)
+ */
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ HOOK_FEATURE_MESSAGE_OPS,
+ makeMessageOp,
+ makeMessageOpResult,
+ parseHookMessage,
+ serializeHookMessage,
+ type HookMessage,
+ type MessageOpAction,
+} from '../index';
+
+function roundTrip(message: HookMessage): HookMessage {
+ const parsed = parseHookMessage(serializeHookMessage(message));
+ if (!parsed.ok) throw new Error(`parse failed: ${parsed.error}`);
+ return parsed.message;
+}
+
+const SCOPE = { externalKey: 'telegram:group:bot:−100:111:g1' };
+
+function op(action: MessageOpAction, opId = 'op-1') {
+ return makeMessageOp({ opId, requestId: 'req-1', scope: SCOPE, action });
+}
+
+describe('msg.op 动词集', () => {
+ it('能力标识为 msg-op-v1', () => {
+ expect(HOOK_FEATURE_MESSAGE_OPS).toBe('msg-op-v1');
+ });
+
+ it('六种动作都能 round-trip 且形态原样保留', () => {
+ const actions: MessageOpAction[] = [
+ {
+ kind: 'send',
+ text: '已渲染的最终正文',
+ replyToMessageId: '42',
+ tier: 'rich',
+ buttons: [[{ token: 'cdy:abc', label: '同意' }]],
+ },
+ { kind: 'edit', messageId: '43', text: '改后的正文', tier: 'html' },
+ { kind: 'delete', messageId: '44' },
+ { kind: 'react', targetMessageId: '45', emoji: '👍', big: true },
+ { kind: 'typing' },
+ {
+ kind: 'media',
+ album: true,
+ items: [{ name: 'a.png', mimeType: 'image/png', dataBase64: 'AAAA' }],
+ },
+ ];
+ for (const action of actions) {
+ const parsed = roundTrip(op(action));
+ expect(parsed.type).toBe('msg.op');
+ expect(parsed.payload).toMatchObject({ opId: 'op-1', scope: SCOPE, action });
+ }
+ });
+
+ it('react 的空 emoji 是撤销语义, 合法', () => {
+ const parsed = roundTrip(op({ kind: 'react', targetMessageId: '46', emoji: '' }));
+ expect((parsed.payload as { action: { emoji: string } }).action.emoji).toBe('');
+ });
+
+ it('scope 携带 chatId / threadId 一律拒收(寻址权不在客户端)', () => {
+ // 目标 chat 必须由服务端从 lane 记录里取。允许客户端指定, 一台被攻陷或有
+ // bug 的桌面就能越过自己 lane 的边界往任意聊天发消息。
+ for (const extra of [{ chatId: '-100999' }, { threadId: '7' }]) {
+ const frame = JSON.parse(serializeHookMessage(op({ kind: 'typing' }))) as Record<
+ string,
+ unknown
+ >;
+ Object.assign((frame.payload as { scope: Record<string, unknown> }).scope, extra);
+ const parsed = parseHookMessage(JSON.stringify(frame));
+ expect(parsed.ok).toBe(false);
+ if (!parsed.ok) expect(parsed.error).toContain('resolves the target from externalKey');
+ }
+ });
+
+ it('缺 opId 或 scope.externalKey 一律拒收', () => {
+ // opId 是断连重发下不产生重复消息的唯一依据(Telegram 无发送端幂等键),
+ // externalKey 是多租户授权锚点 —— 两者都不能让服务端"尽力而为"地猜。
+ const base = op({ kind: 'typing' });
+ const noOpId = JSON.parse(serializeHookMessage(base)) as Record<string, unknown>;
+ (noOpId.payload as Record<string, unknown>).opId = '';
+ expect(parseHookMessage(JSON.stringify(noOpId)).ok).toBe(false);
+
+ const noKey = JSON.parse(serializeHookMessage(base)) as Record<string, unknown>;
+ (noKey.payload as { scope: Record<string, unknown> }).scope = {};
+ expect(parseHookMessage(JSON.stringify(noKey)).ok).toBe(false);
+ });
+
+ it('未知动作类型拒收', () => {
+ const base = op({ kind: 'typing' });
+ const bad = JSON.parse(serializeHookMessage(base)) as Record<string, unknown>;
+ (bad.payload as { action: Record<string, unknown> }).action = { kind: 'teleport' };
+ const parsed = parseHookMessage(JSON.stringify(bad));
+ expect(parsed.ok).toBe(false);
+ });
+
+ it('msg.op.result 带 messageId 与相册全量 id, 并支持 retryAfterMs', () => {
+ const ok = roundTrip(
+ makeMessageOpResult({ opId: 'op-1', ok: true, messageId: '99', messageIds: ['99', '100'] }),
+ );
+ expect(ok.payload).toMatchObject({ ok: true, messageId: '99', messageIds: ['99', '100'] });
+
+ const failed = roundTrip(
+ makeMessageOpResult({ opId: 'op-2', ok: false, error: 'flood', retryAfterMs: 26_000 }),
+ );
+ // retry_after 全值透传, 不在协议层设上限 —— 固定 clamp 会让重试落回 flood 窗口。
+ expect(failed.payload).toMatchObject({ ok: false, retryAfterMs: 26_000 });
+ });
+
+ it('老端按未知类型拒收整帧(丢帧不断连)', () => {
+ const frame = JSON.parse(serializeHookMessage(op({ kind: 'typing' }))) as Record<
+ string,
+ unknown
+ >;
+ frame.type = 'msg.op.future-verb';
+ const parsed = parseHookMessage(JSON.stringify(frame));
+ expect(parsed.ok).toBe(false);
+ if (!parsed.ok) expect(parsed.error).toContain('unknown message type');
+ });
+});
diff --git a/packages/slack-hook-protocol/src/__tests__/protocol-multiteam.test.ts b/packages/slack-hook-protocol/src/__tests__/protocol-multiteam.test.ts
new file mode 100644
index 0000000000..bd19e2165a
--- /dev/null
+++ b/packages/slack-hook-protocol/src/__tests__/protocol-multiteam.test.ts
@@ -0,0 +1,269 @@
+/**
+ * slack-hook-protocol 多 workspace 绑定(multi-team)增量测试:
+ * 1. 新帧 bind.state 构造 -> 序列化 -> 解析 round-trip 与形状约束
+ * 2. bind.revoke 放宽: 空对象(老语义)与 { teamId }(按 team)都合法,
+ * 多余键仍拒收
+ * 3. hello.features / bind.start.teamId / bind.update.teamId /
+ * prefs.set.teamId / prefs.state 条目 teamId / tool.request.teamId /
+ * TaskSource.teamId+teamName 的可选字段校验
+ * 4. 兼容回归: 不带任何新字段的老帧全部照常通过(老端行为不变)
+ */
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ HOOK_FEATURE_MULTI_TEAM,
+ makeBindRevoke,
+ makeBindStart,
+ makeBindState,
+ makeBindUpdate,
+ makeHello,
+ makePrefsSet,
+ makePrefsState,
+ makeTaskDispatch,
+ makeToolRequest,
+ parseHookMessage,
+ serializeHookMessage,
+ type BindStatePayload,
+ type HookMessage,
+} from '../index';
+
+function roundTrip(message: HookMessage): HookMessage {
+ const parsed = parseHookMessage(serializeHookMessage(message));
+ expect(parsed.ok, parsed.ok ? '' : parsed.error).toBe(true);
+ if (!parsed.ok) throw new Error('unreachable');
+ expect(parsed.message).toEqual(message);
+ return parsed.message;
+}
+
+function expectReject(mutated: unknown, keyword: string): void {
+ const parsed = parseHookMessage(mutated);
+ expect(parsed.ok).toBe(false);
+ if (parsed.ok) throw new Error('unreachable');
+ expect(parsed.error).toContain(keyword);
+}
+
+const SNAPSHOT: BindStatePayload = {
+ bindings: [
+ { teamId: 'T0AAA', teamName: 'Acme Inc.', slackUserId: 'U0123', slackUserName: 'cindy' },
+ { teamId: 'T0BBB', teamName: null, slackUserId: 'U0456', slackUserName: null },
+ ],
+};
+
+describe('bind.state 快照帧', () => {
+ it('构造 -> 序列化 -> 解析 round-trip(含空列表)', () => {
+ roundTrip(makeBindState(SNAPSHOT));
+ roundTrip(makeBindState({ bindings: [] }));
+ });
+
+ it('条目缺 teamId / slackUserId 拒收', () => {
+ const msg = makeBindState(SNAPSHOT);
+ expectReject(
+ { ...msg, payload: { bindings: [{ ...SNAPSHOT.bindings[0], teamId: '' }] } },
+ 'bindings[0].teamId',
+ );
+ expectReject(
+ { ...msg, payload: { bindings: [{ ...SNAPSHOT.bindings[0], slackUserId: null }] } },
+ 'bindings[0].slackUserId',
+ );
+ });
+
+ it('bindings 非数组拒收', () => {
+ const msg = makeBindState(SNAPSHOT);
+ expectReject({ ...msg, payload: { bindings: {} } }, 'bindings must be an array');
+ });
+});
+
+describe('bind.revoke 放宽', () => {
+ it('空 payload(老语义: 全解)仍合法', () => {
+ roundTrip(makeBindRevoke());
+ });
+
+ it('按 team 解绑与显式 null 都合法', () => {
+ roundTrip(makeBindRevoke({ teamId: 'T0AAA' }));
+ roundTrip(makeBindRevoke({ teamId: null }));
+ });
+
+ it('pendingOnly(取消在途授权)合法且校验形状', () => {
+ roundTrip(makeBindRevoke({ pendingOnly: true }));
+ const msg = makeBindRevoke();
+ expectReject({ ...msg, payload: { pendingOnly: 'yes' } }, 'bind.revoke.pendingOnly');
+ });
+
+ it('多余键仍拒收(保留对端实现错误的暴露性)', () => {
+ const msg = makeBindRevoke({ teamId: 'T0AAA' });
+ expectReject(
+ { ...msg, payload: { teamId: 'T0AAA', extra: 1 } },
+ 'bind.revoke.extra is not a known field',
+ );
+ });
+
+ it('teamId 非字符串拒收', () => {
+ const msg = makeBindRevoke();
+ expectReject({ ...msg, payload: { teamId: 42 } }, 'bind.revoke.teamId');
+ });
+});
+
+describe('可选 teamId 字段族', () => {
+ it('hello.features 可选且校验形状', () => {
+ roundTrip(
+ makeHello({
+ deviceId: 'd-1',
+ deviceName: 'dev',
+ workspaces: ['main'],
+ agents: ['claude-code'],
+ features: [HOOK_FEATURE_MULTI_TEAM],
+ }),
+ );
+ // 缺省 = 老客户端, 照常通过
+ roundTrip(
+ makeHello({ deviceId: 'd-1', deviceName: 'dev', workspaces: [], agents: ['claude-code'] }),
+ );
+ const msg = makeHello({ deviceId: 'd-1', deviceName: 'dev', workspaces: [], agents: ['cc'] });
+ expectReject({ ...msg, payload: { ...msg.payload, features: 'multi-team' } }, 'hello.features');
+ });
+
+ it('hello.defaultWorkspace 可选, 且必须是 workspaces 的成员', () => {
+ roundTrip(
+ makeHello({
+ deviceId: 'd-1',
+ deviceName: 'dev',
+ workspaces: ['chat', 'cindy'],
+ agents: ['claude-code'],
+ defaultWorkspace: 'cindy',
+ }),
+ );
+ // 缺省 / 显式 null = 无默认, 都照常通过(旧 desktop 不发本字段)
+ roundTrip(
+ makeHello({ deviceId: 'd-1', deviceName: 'dev', workspaces: ['chat'], agents: ['cc'] }),
+ );
+ roundTrip(
+ makeHello({
+ deviceId: 'd-1',
+ deviceName: 'dev',
+ workspaces: ['chat'],
+ agents: ['cc'],
+ defaultWorkspace: null,
+ }),
+ );
+ const msg = makeHello({
+ deviceId: 'd-1',
+ deviceName: 'dev',
+ workspaces: ['chat'],
+ agents: ['cc'],
+ });
+ // 清单外的别名必须拒收: server 只能派发 workspaces 内的别名, 默认值若能
+ // 指向清单外, 就绕过了该约束(server 侧派发校验的唯一依据)。
+ expectReject(
+ { ...msg, payload: { ...msg.payload, defaultWorkspace: 'not-registered' } },
+ 'hello.defaultWorkspace',
+ );
+ expectReject(
+ { ...msg, payload: { ...msg.payload, defaultWorkspace: 42 } },
+ 'hello.defaultWorkspace',
+ );
+ });
+
+ it('bind.start.teamId 可选(pin 重授权)', () => {
+ roundTrip(makeBindStart({}));
+ roundTrip(makeBindStart({ teamId: 'T0AAA' }));
+ roundTrip(makeBindStart({ teamId: null }));
+ const msg = makeBindStart({});
+ expectReject({ ...msg, payload: { teamId: 5 } }, 'bind.start.teamId');
+ });
+
+ it('bind.update.teamId 可选(事件按 team 定位)', () => {
+ roundTrip(
+ makeBindUpdate({
+ state: 'confirmed',
+ slackUserId: 'U0123',
+ slackUserName: 'cindy',
+ message: null,
+ teamId: 'T0AAA',
+ teamName: 'Acme Inc.',
+ }),
+ );
+ roundTrip(
+ makeBindUpdate({
+ state: 'revoked',
+ slackUserId: null,
+ slackUserName: null,
+ message: 'superseded by another device',
+ teamId: 'T0AAA',
+ reason: 'superseded',
+ }),
+ );
+ const msg = makeBindUpdate({
+ state: 'none',
+ slackUserId: null,
+ slackUserName: null,
+ message: null,
+ });
+ expectReject({ ...msg, payload: { ...msg.payload, teamId: 42 } }, 'bind.update.teamId');
+ });
+
+ it('prefs.set.teamId / prefs.state 条目 teamId 可选', () => {
+ roundTrip(
+ makePrefsSet({ requestId: 'r-1', workspace: 'main', model: 'opus', teamId: 'T0AAA' }),
+ );
+ roundTrip(
+ makePrefsState({
+ replyTo: null,
+ bound: true,
+ prefs: [
+ {
+ workspace: 'main',
+ model: null,
+ effort: null,
+ agentKind: null,
+ permissionMode: null,
+ teamId: 'T0AAA',
+ },
+ ],
+ }),
+ );
+ const set = makePrefsSet({ requestId: 'r-1', workspace: 'main' });
+ expectReject({ ...set, payload: { ...set.payload, teamId: 42 } }, 'prefs.set.teamId');
+ });
+
+ it('tool.request.teamId 可选(网关工具身份消歧)', () => {
+ roundTrip(makeToolRequest({ requestId: 'r-1', tool: 'status', teamId: 'T0AAA' }));
+ roundTrip(makeToolRequest({ requestId: 'r-1', tool: 'status' }));
+ const msg = makeToolRequest({ requestId: 'r-1', tool: 'status' });
+ expectReject({ ...msg, payload: { ...msg.payload, teamId: 42 } }, 'tool.request.teamId');
+ });
+
+ it('TaskSource.teamId / teamName 可选', () => {
+ roundTrip(
+ makeTaskDispatch({
+ requestId: 'r-1',
+ externalKey: 'slack:T0AAA:dm:U1:1',
+ workspace: 'main',
+ prompt: 'hi',
+ source: { im: 'slack', channelName: '#general', teamId: 'T0AAA', teamName: 'Acme Inc.' },
+ }),
+ );
+ const msg = makeTaskDispatch({
+ requestId: 'r-1',
+ externalKey: 'k',
+ workspace: 'main',
+ prompt: 'hi',
+ source: { im: 'slack' },
+ });
+ expectReject(
+ { ...msg, payload: { ...msg.payload, source: { im: 'slack', teamId: 42 } } },
+ 'source.teamId',
+ );
+ expectReject(
+ { ...msg, payload: { ...msg.payload, source: { im: 'slack', teamName: 42 } } },
+ 'source.teamName',
+ );
+ });
+});
+
+describe('兼容回归', () => {
+ it('未知类型仍拒收丢帧(bind.state 之外的新类型不被误放行)', () => {
+ const msg = makeBindState(SNAPSHOT);
+ expectReject({ ...msg, type: 'bind.future' }, 'unknown message type');
+ });
+});
diff --git a/packages/slack-hook-protocol/src/__tests__/protocol-prefs.test.ts b/packages/slack-hook-protocol/src/__tests__/protocol-prefs.test.ts
new file mode 100644
index 0000000000..030211e01c
--- /dev/null
+++ b/packages/slack-hook-protocol/src/__tests__/protocol-prefs.test.ts
@@ -0,0 +1,116 @@
+/**
+ * 阶段 11 偏好帧(prefs.get / prefs.set / prefs.state)测试:
+ * 1. 构造 -> 序列化 -> 解析 round-trip(含部分更新的 undefined/null 混合)
+ * 2. 校验负例: requestId / workspace / patch 字段类型 / bound 联动 / 条目形状
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ makePrefsGet,
+ makePrefsSet,
+ makePrefsState,
+ parseHookMessage,
+ serializeHookMessage,
+ type HookMessage,
+ type PrefsStatePayload,
+} from '../index';
+
+function roundTrip(message: HookMessage): HookMessage {
+ const parsed = parseHookMessage(serializeHookMessage(message));
+ expect(parsed.ok, parsed.ok ? '' : parsed.error).toBe(true);
+ if (!parsed.ok) throw new Error('unreachable');
+ expect(parsed.message).toEqual(message);
+ return parsed.message;
+}
+
+function expectReject(mutated: unknown, keyword: string): void {
+ const parsed = parseHookMessage(mutated);
+ expect(parsed.ok).toBe(false);
+ if (parsed.ok) throw new Error('unreachable');
+ expect(parsed.error).toContain(keyword);
+}
+
+const STATE: PrefsStatePayload = {
+ replyTo: 'req-1',
+ bound: true,
+ prefs: [
+ {
+ workspace: 'cindy',
+ model: 'claude-opus-4-8',
+ effort: 'high',
+ agentKind: 'claude-code',
+ permissionMode: 'ask',
+ },
+ { workspace: 'blog', model: null, effort: null, agentKind: null, permissionMode: null },
+ ],
+};
+
+describe('prefs 帧 round-trip', () => {
+ it('prefs.get', () => {
+ roundTrip(makePrefsGet({ requestId: 'req-1' }));
+ });
+
+ it('prefs.set: 全量 patch / 部分 patch(undefined 缺席) / null 清空', () => {
+ roundTrip(
+ makePrefsSet({
+ requestId: 'req-2',
+ workspace: 'cindy',
+ model: 'claude-opus-4-8',
+ effort: 'high',
+ agentKind: 'claude-code',
+ permissionMode: 'ask',
+ }),
+ );
+ // 只动 effort, 其余缺席(JSON.stringify 会剥掉 undefined, round-trip 仍等价)
+ roundTrip(makePrefsSet({ requestId: 'req-3', workspace: 'cindy', effort: 'low' }));
+ roundTrip(makePrefsSet({ requestId: 'req-4', workspace: 'blog', permissionMode: null }));
+ });
+
+ it('prefs.state: 应答(replyTo 回显)与主动推送(replyTo null)、未绑定空快照', () => {
+ roundTrip(makePrefsState(STATE));
+ roundTrip(makePrefsState({ ...STATE, replyTo: null }));
+ roundTrip(makePrefsState({ replyTo: null, bound: false, prefs: [] }));
+ });
+});
+
+describe('prefs 帧校验负例', () => {
+ it('prefs.get: requestId 必填非空', () => {
+ const msg = makePrefsGet({ requestId: 'req-1' });
+ expectReject({ ...msg, payload: { requestId: '' } }, 'prefs.get.requestId');
+ expectReject({ ...msg, payload: {} }, 'prefs.get.requestId');
+ });
+
+ it('prefs.set: workspace 必填非空, patch 字段必须 string|null', () => {
+ const msg = makePrefsSet({ requestId: 'r', workspace: 'cindy', effort: 'low' });
+ expectReject({ ...msg, payload: { requestId: 'r', workspace: '' } }, 'prefs.set.workspace');
+ expectReject(
+ { ...msg, payload: { requestId: 'r', workspace: 'cindy', model: 42 } },
+ 'prefs.set.model must be a string or null',
+ );
+ expectReject(
+ { ...msg, payload: { requestId: 'r', workspace: 'cindy', permissionMode: false } },
+ 'prefs.set.permissionMode must be a string or null',
+ );
+ });
+
+ it('prefs.state: bound=false 时 prefs 必须为空', () => {
+ const msg = makePrefsState(STATE);
+ expectReject(
+ { ...msg, payload: { ...STATE, bound: false } },
+ 'prefs must be empty when bound is false',
+ );
+ });
+
+ it('prefs.state: 条目形状(workspace 非空, 字段显式 null 而非缺席)', () => {
+ const msg = makePrefsState(STATE);
+ const badWs = structuredClone(STATE) as unknown as Record<string, unknown>;
+ (badWs.prefs as Array<Record<string, unknown>>)[0].workspace = '';
+ expectReject({ ...msg, payload: badWs }, 'prefs[0].workspace');
+ const missingField = structuredClone(STATE) as unknown as Record<string, unknown>;
+ delete (missingField.prefs as Array<Record<string, unknown>>)[1].model;
+ expectReject({ ...msg, payload: missingField }, 'prefs[1].model must be a string or null');
+ const badReply = structuredClone(STATE) as unknown as Record<string, unknown>;
+ expectReject({ ...msg, payload: { ...badReply, replyTo: 7 } }, 'prefs.state.replyTo');
+ });
+});
diff --git a/packages/slack-hook-protocol/src/__tests__/protocol-provider.test.ts b/packages/slack-hook-protocol/src/__tests__/protocol-provider.test.ts
new file mode 100644
index 0000000000..1ef65ae0b1
--- /dev/null
+++ b/packages/slack-hook-protocol/src/__tests__/protocol-provider.test.ts
@@ -0,0 +1,483 @@
+/** Provider-neutral binding, preferences, and recent-session query contract. */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ HOOK_FEATURE_PROVIDER_BIND,
+ HOOK_FEATURE_PROVIDER_PREFS,
+ HOOK_FEATURE_PROVIDER_TELEGRAM,
+ HOOK_FEATURE_PROVIDER_X,
+ HOOK_FEATURE_SESSION_PICKER,
+ PROVIDER_BIND_STATES,
+ makeBindStart,
+ makeProviderBindCancel,
+ makeProviderBindRevoke,
+ makeProviderBindStart,
+ makeProviderBindState,
+ makeProviderBindUpdate,
+ makeProviderPrefsGet,
+ makeProviderPrefsSet,
+ makeProviderPrefsState,
+ makeQueryResponse,
+ parseHookMessage,
+ serializeHookMessage,
+ type HookMessage,
+ type ProviderBindStatusPayload,
+} from '../index';
+
+function roundTrip(message: HookMessage): HookMessage {
+ const parsed = parseHookMessage(serializeHookMessage(message));
+ expect(parsed.ok, parsed.ok ? '' : parsed.error).toBe(true);
+ if (!parsed.ok) throw new Error('unreachable');
+ expect(parsed.message).toEqual(message);
+ return parsed.message;
+}
+
+function expectReject(message: unknown, keyword: string): void {
+ const parsed = parseHookMessage(message);
+ expect(parsed.ok).toBe(false);
+ if (parsed.ok) throw new Error('unreachable');
+ expect(parsed.error).toContain(keyword);
+}
+
+const PENDING: ProviderBindStatusPayload = {
+ provider: 'telegram',
+ replyTo: 'request-1',
+ state: 'pending',
+ attemptId: 'attempt-1',
+ bindingId: null,
+ principalId: null,
+ principalName: null,
+ scopeId: 'bot-1',
+ scopeName: 'cindy_example_bot',
+ connectUrl: 'https://t.me/cindy_example_bot?start=abcdefghijklmnopqrstuvwxyz_0123456789-ABCDE',
+ expiresAt: 1_800_000_000_000,
+ reason: null,
+ remediationUrl: null,
+ actions: ['open_connect_url', 'copy_connect_url', 'cancel'],
+};
+
+const CONFIRMED: ProviderBindStatusPayload = {
+ provider: 'telegram',
+ replyTo: null,
+ state: 'confirmed',
+ attemptId: null,
+ bindingId: 'binding-1',
+ principalId: 'telegram-user-1',
+ principalName: 'Cindy User',
+ scopeId: 'bot-1',
+ scopeName: 'cindy_example_bot',
+ connectUrl: null,
+ expiresAt: null,
+ reason: null,
+ remediationUrl: 'https://t.me/cindy_example_bot',
+ actions: ['revoke', 'open_provider', 'add_to_group'],
+};
+
+function statusFor(state: ProviderBindStatusPayload['state']): ProviderBindStatusPayload {
+ if (state === 'pending') return PENDING;
+ if (state === 'confirmed') return CONFIRMED;
+ if (state === 'none') {
+ return {
+ ...CONFIRMED,
+ state,
+ bindingId: null,
+ principalId: null,
+ principalName: null,
+ remediationUrl: null,
+ actions: [],
+ };
+ }
+ if (state === 'awaiting_confirmation') {
+ return {
+ ...PENDING,
+ state,
+ connectUrl: null,
+ principalId: 'telegram-user-1',
+ principalName: 'Cindy User',
+ actions: ['cancel'],
+ };
+ }
+ const bindingTerminal = state === 'revoked' || state === 'superseded';
+ return {
+ ...PENDING,
+ state,
+ attemptId: bindingTerminal ? null : PENDING.attemptId,
+ bindingId: bindingTerminal ? 'binding-1' : null,
+ principalId: bindingTerminal ? 'telegram-user-1' : null,
+ principalName: bindingTerminal ? 'Cindy User' : null,
+ connectUrl: null,
+ expiresAt: null,
+ reason: `telegram-${state}`,
+ actions: ['retry'],
+ };
+}
+
+describe('provider feature negotiation constants', () => {
+ it('uses stable append-only capability names', () => {
+ expect(HOOK_FEATURE_PROVIDER_BIND).toBe('provider-bind-v1');
+ expect(HOOK_FEATURE_PROVIDER_PREFS).toBe('provider-prefs-v1');
+ expect(HOOK_FEATURE_SESSION_PICKER).toBe('session-picker-v1');
+ expect(HOOK_FEATURE_PROVIDER_TELEGRAM).toBe('provider:telegram');
+ expect(HOOK_FEATURE_PROVIDER_X).toBe('provider:x');
+ });
+
+ it('does not alter the legacy Slack bind.start payload', () => {
+ const legacy = JSON.parse(serializeHookMessage(makeBindStart({}))) as {
+ type: string;
+ payload: Record<string, unknown>;
+ };
+ expect(legacy.type).toBe('bind.start');
+ expect(legacy.payload).toEqual({});
+ });
+});
+
+describe('provider.bind frames', () => {
+ it('round-trips start, cancel, revoke, update, and state', () => {
+ roundTrip(makeProviderBindStart({ requestId: 'request-1', provider: 'telegram' }));
+ roundTrip(
+ makeProviderBindStart({ requestId: 'request-2', provider: 'slack', scopeId: 'team-1' }),
+ );
+ roundTrip(
+ makeProviderBindCancel({
+ requestId: 'request-3',
+ provider: 'telegram',
+ attemptId: 'attempt-1',
+ }),
+ );
+ roundTrip(
+ makeProviderBindRevoke({
+ requestId: 'request-4',
+ provider: 'telegram',
+ bindingId: 'binding-1',
+ }),
+ );
+ for (const state of PROVIDER_BIND_STATES) {
+ const payload = statusFor(state);
+ roundTrip(makeProviderBindUpdate(payload));
+ roundTrip(makeProviderBindState(payload));
+ }
+ });
+
+ it('round-trips the x provider through bind and prefs frames', () => {
+ // 'x' is an append-only HOOK_PROVIDERS value: the frames are identical to
+ // Telegram's, only the provider id (and its connect-URL host) differ.
+ roundTrip(makeProviderBindStart({ requestId: 'request-x-1', provider: 'x' }));
+ roundTrip(
+ makeProviderBindCancel({ requestId: 'request-x-2', provider: 'x', attemptId: 'attempt-x' }),
+ );
+ roundTrip(
+ makeProviderBindRevoke({ requestId: 'request-x-3', provider: 'x', bindingId: 'binding-x' }),
+ );
+ const xPending: ProviderBindStatusPayload = {
+ ...PENDING,
+ provider: 'x',
+ scopeId: 'x-app-1',
+ scopeName: 'cindy_example_app',
+ connectUrl: 'https://example.com/x/connect?attempt=attempt-x',
+ };
+ roundTrip(makeProviderBindUpdate(xPending));
+ roundTrip(makeProviderBindState(xPending));
+ roundTrip(
+ makeProviderPrefsGet({
+ requestId: 'prefs-x-1',
+ provider: 'x',
+ bindingId: 'binding-x',
+ scopeId: null,
+ }),
+ );
+ roundTrip(
+ makeProviderPrefsState({
+ provider: 'x',
+ bindingId: 'binding-x',
+ scopeId: null,
+ replyTo: 'prefs-x-1',
+ bound: true,
+ prefs: [],
+ }),
+ );
+ });
+
+ it('rejects unknown providers and unsafe links', () => {
+ const start = makeProviderBindStart({ requestId: 'request-1', provider: 'telegram' });
+ expectReject(
+ { ...start, payload: { ...start.payload, provider: 'discord' } },
+ 'provider.bind.start.provider',
+ );
+ const state = makeProviderBindState(PENDING);
+ expectReject(
+ { ...state, payload: { ...PENDING, connectUrl: 'http://t.me/example?start=token' } },
+ 'safe HTTPS URL',
+ );
+ expectReject(
+ { ...state, payload: { ...PENDING, connectUrl: 'https://user:[email protected]/example' } },
+ 'safe HTTPS URL',
+ );
+ });
+
+ it('enforces state-linked identity, attempt, expiry, and reason fields', () => {
+ const pending = makeProviderBindUpdate(PENDING);
+ expectReject(
+ { ...pending, payload: { ...PENDING, attemptId: null } },
+ 'attemptId must be non-empty',
+ );
+ expectReject(
+ { ...pending, payload: { ...PENDING, expiresAt: null } },
+ 'expiresAt must be non-null',
+ );
+ for (const state of ['pending', 'awaiting_confirmation'] as const) {
+ const active = statusFor(state);
+ for (const frame of [makeProviderBindUpdate(active), makeProviderBindState(active)]) {
+ expectReject(
+ { ...frame, payload: { ...active, bindingId: 'stale-binding' } },
+ 'bindingId must be null',
+ );
+ }
+ }
+ const confirmed = makeProviderBindState(CONFIRMED);
+ expectReject(
+ { ...confirmed, payload: { ...CONFIRMED, principalId: null } },
+ 'principalId must be non-empty',
+ );
+ expectReject(
+ { ...confirmed, payload: { ...CONFIRMED, connectUrl: 'https://t.me/example' } },
+ 'connectUrl must be null',
+ );
+ expectReject(
+ {
+ ...confirmed,
+ payload: {
+ ...CONFIRMED,
+ state: 'superseded',
+ reason: null,
+ },
+ },
+ 'reason must be non-empty',
+ );
+ for (const state of ['revoked', 'superseded'] as const) {
+ const terminal = statusFor(state);
+ for (const frame of [makeProviderBindUpdate(terminal), makeProviderBindState(terminal)]) {
+ expectReject(
+ { ...frame, payload: { ...terminal, attemptId: 'stale-attempt' } },
+ 'attemptId and expiresAt must be null',
+ );
+ expectReject(
+ { ...frame, payload: { ...terminal, expiresAt: Date.now() + 60_000 } },
+ 'attemptId and expiresAt must be null',
+ );
+ }
+ }
+ for (const state of ['denied', 'expired', 'failed'] as const) {
+ const terminal = statusFor(state);
+ for (const frame of [makeProviderBindUpdate(terminal), makeProviderBindState(terminal)]) {
+ for (const field of ['bindingId', 'principalId', 'principalName'] as const) {
+ expectReject(
+ { ...frame, payload: { ...terminal, [field]: `stale-${field}` } },
+ `${field} must be null`,
+ );
+ }
+ expectReject(
+ { ...frame, payload: { ...terminal, expiresAt: Date.now() + 60_000 } },
+ 'expiresAt must be null',
+ );
+ }
+ }
+ });
+});
+
+describe('provider.prefs frames', () => {
+ it('round-trips provider-isolated get/set/state', () => {
+ roundTrip(
+ makeProviderPrefsGet({
+ requestId: 'prefs-1',
+ provider: 'telegram',
+ bindingId: 'binding-1',
+ scopeId: null,
+ }),
+ );
+ roundTrip(
+ makeProviderPrefsSet({
+ requestId: 'prefs-2',
+ provider: 'telegram',
+ bindingId: 'binding-1',
+ scopeId: null,
+ workspace: 'cindy',
+ model: 'model-1',
+ effort: 'high',
+ }),
+ );
+ roundTrip(
+ makeProviderPrefsState({
+ provider: 'telegram',
+ bindingId: 'binding-1',
+ scopeId: null,
+ replyTo: 'prefs-2',
+ bound: true,
+ prefs: [
+ {
+ workspace: 'cindy',
+ model: 'model-1',
+ effort: 'high',
+ agentKind: 'codex',
+ permissionMode: 'full-access',
+ },
+ ],
+ }),
+ );
+ });
+
+ it('requires exactly one neutral selector and rejects Slack-only teamId', () => {
+ const get = makeProviderPrefsGet({
+ requestId: 'prefs-1',
+ provider: 'telegram',
+ bindingId: 'binding-1',
+ scopeId: null,
+ });
+ expectReject(
+ { ...get, payload: { ...get.payload, bindingId: null, scopeId: null } },
+ 'exactly one',
+ );
+ expectReject({ ...get, payload: { ...get.payload, scopeId: 'bot-1' } }, 'exactly one');
+ const state = makeProviderPrefsState({
+ provider: 'telegram',
+ bindingId: 'binding-1',
+ scopeId: null,
+ replyTo: null,
+ bound: true,
+ prefs: [],
+ });
+ expectReject(
+ {
+ ...state,
+ payload: {
+ ...state.payload,
+ prefs: [
+ {
+ workspace: 'cindy',
+ model: null,
+ effort: null,
+ agentKind: null,
+ permissionMode: null,
+ teamId: 'team-1',
+ },
+ ],
+ },
+ },
+ 'Slack-specific',
+ );
+ });
+
+ it('rejects absolute workspace paths in writes and snapshots', () => {
+ const set = makeProviderPrefsSet({
+ requestId: 'prefs-absolute',
+ provider: 'telegram',
+ bindingId: 'binding-1',
+ scopeId: null,
+ workspace: 'cindy',
+ });
+ const state = makeProviderPrefsState({
+ provider: 'telegram',
+ bindingId: 'binding-1',
+ scopeId: null,
+ replyTo: null,
+ bound: true,
+ prefs: [
+ {
+ workspace: 'cindy',
+ model: null,
+ effort: null,
+ agentKind: null,
+ permissionMode: null,
+ },
+ ],
+ });
+ for (const workspace of ['/Users/cindy/project', 'C:\\Users\\cindy', 'file:///tmp/cindy']) {
+ expectReject(
+ { ...set, payload: { ...set.payload, workspace } },
+ 'must not be an absolute path',
+ );
+ expectReject(
+ {
+ ...state,
+ payload: {
+ ...state.payload,
+ prefs: [{ ...state.payload.prefs[0], workspace }],
+ },
+ },
+ 'must not be an absolute path',
+ );
+ }
+ });
+});
+
+describe('query.kind=sessions', () => {
+ it('round-trips at most 20 privacy-minimised session entries', () => {
+ roundTrip(
+ makeQueryResponse({
+ queryId: 'sessions-1',
+ kind: 'sessions',
+ ok: true,
+ error: null,
+ sessions: [
+ { id: 'session-1', title: 'Telegram task', workspace: 'cindy', lastActiveAt: 1 },
+ ],
+ }),
+ );
+ });
+
+ it('rejects over-limit, duplicate, and absolute-path entries', () => {
+ const sessions = Array.from({ length: 21 }, (_, index) => ({
+ id: `session-${index}`,
+ title: `Session ${index}`,
+ workspace: 'cindy',
+ lastActiveAt: index + 1,
+ }));
+ const response = makeQueryResponse({
+ queryId: 'sessions-1',
+ kind: 'sessions',
+ ok: true,
+ error: null,
+ sessions,
+ });
+ expectReject(response, 'at most 20');
+ expectReject(
+ {
+ ...response,
+ payload: {
+ ...response.payload,
+ sessions: [sessions[0], { ...sessions[1], id: sessions[0].id }],
+ },
+ },
+ 'must be unique',
+ );
+ for (const workspace of ['/Users/cindy/project', 'C:\\Users\\cindy', 'file:///tmp/cindy']) {
+ expectReject(
+ {
+ ...response,
+ payload: { ...response.payload, sessions: [{ ...sessions[0], workspace }] },
+ },
+ 'must not be an absolute path',
+ );
+ }
+ expectReject(
+ {
+ ...response,
+ payload: {
+ ...response.payload,
+ sessions: [{ ...sessions[0], path: '/Users/cindy/project' }],
+ },
+ },
+ 'privacy-minimised session shape',
+ );
+ expectReject(
+ {
+ ...response,
+ payload: {
+ ...response.payload,
+ sessions: [{ ...sessions[0], message: 'private conversation text' }],
+ },
+ },
+ 'privacy-minimised session shape',
+ );
+ });
+});
diff --git a/packages/slack-hook-protocol/src/__tests__/protocol-tools.test.ts b/packages/slack-hook-protocol/src/__tests__/protocol-tools.test.ts
new file mode 100644
index 0000000000..9deb86edd0
--- /dev/null
+++ b/packages/slack-hook-protocol/src/__tests__/protocol-tools.test.ts
@@ -0,0 +1,140 @@
+/**
+ * slack-hook-protocol 阶段 12(Slack 网关工具帧)测试:
+ * 1. tool.request / tool.response 构造 -> 序列化 -> 解析 round-trip
+ * 2. tool.response 的 ok/error 字段联动约束(失败必须结构化错误, 成功禁带)
+ * 3. tool 名开放集合: 未知工具名通过 parse(业务层负责 UNKNOWN_TOOL)
+ * 4. welcome.features 能力标识常量
+ */
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ HOOK_FEATURE_SLACK_TOOLS,
+ makeToolRequest,
+ makeToolResponse,
+ makeWelcome,
+ parseHookMessage,
+ serializeHookMessage,
+ type HookMessage,
+ type ToolResponsePayload,
+} from '../index';
+
+/** 构造 -> 序列化 -> 解析, 断言等价并返回解析结果。 */
+function roundTrip(message: HookMessage): HookMessage {
+ const parsed = parseHookMessage(serializeHookMessage(message));
+ expect(parsed.ok, parsed.ok ? '' : parsed.error).toBe(true);
+ if (!parsed.ok) throw new Error('unreachable');
+ expect(parsed.message).toEqual(message);
+ return parsed.message;
+}
+
+/** 基于合法消息改坏字段, 断言解析失败且错误信息含关键词。 */
+function expectReject(mutated: unknown, keyword: string): void {
+ const parsed = parseHookMessage(mutated);
+ expect(parsed.ok).toBe(false);
+ if (parsed.ok) throw new Error('unreachable');
+ expect(parsed.error).toContain(keyword);
+}
+
+const OK_RESPONSE: ToolResponsePayload = {
+ replyTo: 'tr-1',
+ ok: true,
+ result: { tools: [{ name: 'search', description: 'Search messages' }] },
+};
+
+const ERR_RESPONSE: ToolResponsePayload = {
+ replyTo: 'tr-2',
+ ok: false,
+ error: { code: 'NO_USER_TOKEN', message: '需重新绑定以授予 Slack 工具权限' },
+};
+
+describe('tool.request', () => {
+ it('全字段 round-trip(args 任意 JSON 对象)', () => {
+ roundTrip(
+ makeToolRequest({
+ requestId: 'tr-1',
+ tool: 'callTool',
+ args: { name: 'search_messages', arguments: { query: 'release', limit: 5 } },
+ }),
+ );
+ });
+
+ it('省略 args round-trip(status 这类无参工具)', () => {
+ roundTrip(makeToolRequest({ requestId: 'tr-1', tool: 'status' }));
+ });
+
+ it('tool 名是开放集合: 未知名字照常通过 parse', () => {
+ roundTrip(makeToolRequest({ requestId: 'tr-x', tool: 'someFutureTool' }));
+ });
+
+ it('坏字段拒收: requestId / tool / args', () => {
+ const base = makeToolRequest({ requestId: 'tr-1', tool: 'status' });
+ expectReject(
+ { ...base, payload: { ...base.payload, requestId: '' } },
+ 'tool.request.requestId',
+ );
+ expectReject({ ...base, payload: { tool: 'status' } }, 'tool.request.requestId');
+ expectReject({ ...base, payload: { ...base.payload, tool: '' } }, 'tool.request.tool');
+ expectReject(
+ { ...base, payload: { ...base.payload, args: 'not-an-object' } },
+ 'tool.request.args',
+ );
+ expectReject({ ...base, payload: { ...base.payload, args: [] } }, 'tool.request.args');
+ });
+});
+
+describe('tool.response', () => {
+ it('成功应答 round-trip(result 任意 JSON)', () => {
+ roundTrip(makeToolResponse(OK_RESPONSE));
+ });
+
+ it('成功应答 result 可缺席(如无返回值工具)', () => {
+ roundTrip(makeToolResponse({ replyTo: 'tr-1', ok: true }));
+ });
+
+ it('成功应答 error 可为显式 null', () => {
+ roundTrip(makeToolResponse({ replyTo: 'tr-1', ok: true, error: null }));
+ });
+
+ it('失败应答 round-trip(结构化错误)', () => {
+ roundTrip(makeToolResponse(ERR_RESPONSE));
+ });
+
+ it('字段联动: ok=false 必须携带非空 {code, message}', () => {
+ const base = makeToolResponse(ERR_RESPONSE);
+ expectReject({ ...base, payload: { replyTo: 'tr-2', ok: false } }, 'tool.response.error');
+ expectReject(
+ { ...base, payload: { replyTo: 'tr-2', ok: false, error: null } },
+ 'tool.response.error',
+ );
+ expectReject(
+ { ...base, payload: { replyTo: 'tr-2', ok: false, error: { code: '', message: 'x' } } },
+ 'tool.response.error.code',
+ );
+ expectReject(
+ { ...base, payload: { replyTo: 'tr-2', ok: false, error: { code: 'X', message: '' } } },
+ 'tool.response.error.message',
+ );
+ });
+
+ it('字段联动: ok=true 不得携带非 null error', () => {
+ const base = makeToolResponse(OK_RESPONSE);
+ expectReject(
+ { ...base, payload: { ...OK_RESPONSE, error: { code: 'X', message: 'y' } } },
+ 'tool.response.error must be absent or null',
+ );
+ });
+
+ it('坏字段拒收: replyTo / ok', () => {
+ const base = makeToolResponse(OK_RESPONSE);
+ expectReject({ ...base, payload: { ...OK_RESPONSE, replyTo: '' } }, 'tool.response.replyTo');
+ expectReject({ ...base, payload: { ...OK_RESPONSE, ok: 'yes' } }, 'tool.response.ok');
+ });
+});
+
+describe('能力协商', () => {
+ it('HOOK_FEATURE_SLACK_TOOLS 常量进 welcome.features 后 round-trip', () => {
+ expect(HOOK_FEATURE_SLACK_TOOLS).toBe('slack-tools');
+ roundTrip(makeWelcome({ serverName: 'test', features: [HOOK_FEATURE_SLACK_TOOLS] }));
+ });
+});
diff --git a/packages/slack-hook-protocol/src/__tests__/protocol-v2.test.ts b/packages/slack-hook-protocol/src/__tests__/protocol-v2.test.ts
new file mode 100644
index 0000000000..e393e6968c
--- /dev/null
+++ b/packages/slack-hook-protocol/src/__tests__/protocol-v2.test.ts
@@ -0,0 +1,449 @@
+/**
+ * slack-hook-protocol v2 增量帧测试:
+ * 1. 新帧(bind.* / query.* / task.cancel)构造 -> 序列化 -> 解析 round-trip
+ * 2. bind.update / query.response 的字段联动约束
+ * 3. dispatch options.effort 与 turn.end cancelled 的扩展行为
+ * 4. 老帧回归: v1 帧的解析行为不因扩展而变化(见 protocol.test.ts, 此处只
+ * 验证"未知类型仍拒收"没有被扩展破坏)
+ */
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ makeBindRevoke,
+ makeBindStart,
+ makeBindUpdate,
+ makeQueryRequest,
+ makeQueryResponse,
+ makeTaskCancel,
+ makeTaskDispatch,
+ makeTurnEnd,
+ makeTurnReopen,
+ parseHookMessage,
+ serializeHookMessage,
+ type BindUpdatePayload,
+ type HookMessage,
+ type QueryResponsePayload,
+ type TurnEndPayload,
+} from '../index';
+
+/** 构造 -> 序列化 -> 解析, 断言等价并返回解析结果。 */
+function roundTrip(message: HookMessage): HookMessage {
+ const parsed = parseHookMessage(serializeHookMessage(message));
+ expect(parsed.ok, parsed.ok ? '' : parsed.error).toBe(true);
+ if (!parsed.ok) throw new Error('unreachable');
+ expect(parsed.message).toEqual(message);
+ return parsed.message;
+}
+
+/** 基于合法消息改坏字段, 断言解析失败且错误信息含关键词。 */
+function expectReject(mutated: unknown, keyword: string): void {
+ const parsed = parseHookMessage(mutated);
+ expect(parsed.ok).toBe(false);
+ if (parsed.ok) throw new Error('unreachable');
+ expect(parsed.error).toContain(keyword);
+}
+
+const CONFIRMED_UPDATE: BindUpdatePayload = {
+ state: 'confirmed',
+ slackUserId: 'U0123ABCD',
+ slackUserName: 'cindy',
+ message: null,
+};
+
+const MODELS_RESPONSE: QueryResponsePayload = {
+ queryId: 'q-1',
+ kind: 'models',
+ ok: true,
+ error: null,
+ agents: [
+ {
+ agentKind: 'claude-code',
+ models: [
+ {
+ id: 'claude-opus-4-8',
+ label: 'Opus 4.8',
+ efforts: ['low', 'medium', 'high'],
+ defaultEffort: 'high',
+ group: 'anthropic',
+ },
+ { id: 'claude-sonnet-5', label: 'Sonnet 5', efforts: [], defaultEffort: null, group: null },
+ ],
+ permissionModes: [
+ { id: 'ask', label: 'Ask permissions' },
+ { id: 'bypassPermissions', label: 'Bypass permissions' },
+ ],
+ },
+ ],
+};
+
+/** 旧版 desktop 应答: 无 permissionModes 字段(向后兼容基线)。 */
+const MODELS_RESPONSE_LEGACY: QueryResponsePayload = {
+ queryId: 'q-legacy',
+ kind: 'models',
+ ok: true,
+ error: null,
+ agents: [
+ {
+ agentKind: 'codex',
+ models: [
+ { id: 'gpt-5.5', label: 'GPT-5.5', efforts: ['low', 'high'], defaultEffort: 'high' },
+ ],
+ },
+ ],
+};
+
+describe('v2 新帧 round-trip', () => {
+ it('bind.start(新端空 payload + 老端邮箱 payload 都 round-trip)', () => {
+ roundTrip(makeBindStart({})); // 阶段 4 新端: 空对象
+ roundTrip(makeBindStart({ email: '[email protected]' })); // 老端识别用: email 仍可解析
+ });
+
+ it('bind.update 全状态', () => {
+ roundTrip(makeBindUpdate(CONFIRMED_UPDATE));
+ roundTrip(
+ makeBindUpdate({ state: 'none', slackUserId: null, slackUserName: null, message: null }),
+ );
+ // pending 携带 OIDC 授权链接(不再是 slackUserId)
+ roundTrip(
+ makeBindUpdate({
+ state: 'pending',
+ slackUserId: null,
+ slackUserName: null,
+ message: null,
+ authorizeUrl: 'https://slack.example.com/openid/connect/authorize?state=x',
+ }),
+ );
+ roundTrip(
+ makeBindUpdate({ state: 'denied', slackUserId: null, slackUserName: null, message: null }),
+ );
+ roundTrip(
+ makeBindUpdate({ state: 'expired', slackUserId: null, slackUserName: null, message: null }),
+ );
+ roundTrip(
+ makeBindUpdate({
+ state: 'failed',
+ slackUserId: null,
+ slackUserName: null,
+ message: '该 workspace 未安装本 app',
+ }),
+ );
+ // failed 携带结构化 reason(可选字段; 未知取值也放行 —— 前向兼容)
+ roundTrip(
+ makeBindUpdate({
+ state: 'failed',
+ slackUserId: null,
+ slackUserName: null,
+ message: '该 workspace 未安装本 app',
+ reason: 'not-installed',
+ installUrl: 'https://hook.example/slack/install-to?team=T1',
+ }),
+ );
+ roundTrip(
+ makeBindUpdate({
+ state: 'revoked',
+ slackUserId: null,
+ slackUserName: null,
+ message: '被新设备顶掉',
+ }),
+ );
+ });
+
+ it('bind.revoke(空 payload)', () => {
+ roundTrip(makeBindRevoke());
+ });
+
+ it('query.request / query.response(workspaces 与 models)', () => {
+ roundTrip(makeQueryRequest({ queryId: 'q-1', kind: 'workspaces' }));
+ roundTrip(makeQueryRequest({ queryId: 'q-2', kind: 'models' }));
+ roundTrip(
+ makeQueryResponse({
+ queryId: 'q-1',
+ kind: 'workspaces',
+ ok: true,
+ error: null,
+ workspaces: ['cindy', 'blog'],
+ }),
+ );
+ roundTrip(makeQueryResponse(MODELS_RESPONSE));
+ roundTrip(makeQueryResponse(MODELS_RESPONSE_LEGACY));
+ roundTrip(
+ makeQueryResponse({ queryId: 'q-3', kind: 'models', ok: false, error: 'device busy' }),
+ );
+ });
+
+ it('task.cancel', () => {
+ roundTrip(makeTaskCancel({ requestId: 'req-1' }));
+ });
+});
+
+describe('bind 帧字段联动', () => {
+ it('bind.start email 可选; 携带时必须像邮箱', () => {
+ const msg = makeBindStart({ email: '[email protected]' });
+ // 空对象放行(新端形态)
+ expect(parseHookMessage(JSON.stringify({ ...msg, payload: {} })).ok).toBe(true);
+ // 携带则粗校验
+ expectReject({ ...msg, payload: { email: 'not-an-email' } }, 'email-like');
+ expectReject({ ...msg, payload: { email: '' } }, 'email-like');
+ });
+
+ it('confirmed 必须带 slackUserId; pending 必须带 authorizeUrl', () => {
+ const msg = makeBindUpdate(CONFIRMED_UPDATE);
+ expectReject(
+ { ...msg, payload: { ...CONFIRMED_UPDATE, slackUserId: null } },
+ 'slackUserId must be a non-empty string when state is confirmed',
+ );
+ // pending 缺 authorizeUrl 拒收
+ expectReject(
+ {
+ ...msg,
+ payload: { state: 'pending', slackUserId: null, slackUserName: null, message: null },
+ },
+ 'authorizeUrl must be a non-empty string when state is pending',
+ );
+ // authorizeUrl 类型错误拒收
+ expectReject(
+ {
+ ...msg,
+ payload: {
+ state: 'confirmed',
+ slackUserId: 'U1',
+ slackUserName: null,
+ message: null,
+ authorizeUrl: 123,
+ },
+ },
+ 'authorizeUrl must be a string or null',
+ );
+ });
+
+ it('failed 必须带 message; 未知 state 拒收', () => {
+ const msg = makeBindUpdate(CONFIRMED_UPDATE);
+ expectReject(
+ {
+ ...msg,
+ payload: { state: 'failed', slackUserId: null, slackUserName: null, message: null },
+ },
+ 'message must be a non-empty string when state is failed',
+ );
+ // reason 形状校验: 非 string|null 拒收; 未知字符串取值放行(前向兼容)
+ expectReject(
+ {
+ ...msg,
+ payload: {
+ state: 'failed',
+ slackUserId: null,
+ slackUserName: null,
+ message: 'x',
+ reason: 42,
+ },
+ },
+ 'reason must be a string or null',
+ );
+ expect(
+ parseHookMessage(
+ JSON.stringify({
+ ...msg,
+ payload: {
+ state: 'failed',
+ slackUserId: null,
+ slackUserName: null,
+ message: 'x',
+ reason: 'future-reason',
+ },
+ }),
+ ).ok,
+ ).toBe(true);
+ expectReject(
+ { ...msg, payload: { ...CONFIRMED_UPDATE, state: 'bogus' } },
+ 'bind.update.state must be one of',
+ );
+ });
+
+ it('bind.revoke 带多余键拒收', () => {
+ const msg = makeBindRevoke();
+ expectReject({ ...msg, payload: { extra: 1 } }, 'bind.revoke.extra is not a known field');
+ });
+});
+
+describe('query 帧字段联动', () => {
+ it('ok=false 必须带 error; ok=true 按 kind 必须带对应清单', () => {
+ const base = makeQueryResponse(MODELS_RESPONSE);
+ expectReject(
+ { ...base, payload: { queryId: 'q', kind: 'models', ok: false, error: null } },
+ 'error must be a non-empty string when ok is false',
+ );
+ expectReject(
+ { ...base, payload: { queryId: 'q', kind: 'workspaces', ok: true, error: null } },
+ 'workspaces must be an array',
+ );
+ expectReject(
+ { ...base, payload: { queryId: 'q', kind: 'models', ok: true, error: null } },
+ 'agents must be an array',
+ );
+ });
+
+ it('models 条目形状校验(efforts / defaultEffort)', () => {
+ const base = makeQueryResponse(MODELS_RESPONSE);
+ const bad = structuredClone(MODELS_RESPONSE) as unknown as Record<string, unknown>;
+ (bad.agents as Array<{ models: Array<Record<string, unknown>> }>)[0].models[0].efforts = 'high';
+ expectReject({ ...base, payload: bad }, 'efforts must be an array');
+ const bad2 = structuredClone(MODELS_RESPONSE) as unknown as Record<string, unknown>;
+ (bad2.agents as Array<{ models: Array<Record<string, unknown>> }>)[0].models[0].defaultEffort =
+ 42;
+ expectReject({ ...base, payload: bad2 }, 'defaultEffort must be a string or null');
+ });
+
+ it('models 条目 group 可选(旧桌面端缺席合法), present 时必须 string|null', () => {
+ const base = makeQueryResponse(MODELS_RESPONSE_LEGACY); // legacy fixture 无 group
+ roundTrip(base);
+ const bad = structuredClone(MODELS_RESPONSE) as unknown as Record<string, unknown>;
+ (bad.agents as Array<{ models: Array<Record<string, unknown>> }>)[0].models[0].group = 42;
+ expectReject(
+ { ...makeQueryResponse(MODELS_RESPONSE), payload: bad },
+ 'group must be a string or null',
+ );
+ });
+
+ it('permissionModes 可选字段形状校验', () => {
+ const base = makeQueryResponse(MODELS_RESPONSE);
+ const badArr = structuredClone(MODELS_RESPONSE) as unknown as Record<string, unknown>;
+ (badArr.agents as Array<Record<string, unknown>>)[0].permissionModes = 'ask';
+ expectReject({ ...base, payload: badArr }, 'permissionModes must be an array');
+ const badId = structuredClone(MODELS_RESPONSE) as unknown as Record<string, unknown>;
+ (
+ badId.agents as Array<{ permissionModes: Array<Record<string, unknown>> }>
+ )[0].permissionModes[0].id = '';
+ expectReject({ ...base, payload: badId }, 'permissionModes[0].id must be a non-empty string');
+ const badLabel = structuredClone(MODELS_RESPONSE) as unknown as Record<string, unknown>;
+ delete (badLabel.agents as Array<{ permissionModes: Array<Record<string, unknown>> }>)[0]
+ .permissionModes[0].label;
+ expectReject(
+ { ...base, payload: badLabel },
+ 'permissionModes[0].label must be a non-empty string',
+ );
+ });
+
+ it('未知 kind 拒收', () => {
+ const msg = makeQueryRequest({ queryId: 'q-1', kind: 'workspaces' });
+ expectReject({ ...msg, payload: { queryId: 'q-1', kind: 'channels' } }, 'kind must be one of');
+ });
+});
+
+describe('v1 帧扩展行为', () => {
+ it('dispatch options.effort 合法透传, 非法拒收', () => {
+ roundTrip(
+ makeTaskDispatch({
+ requestId: 'r1',
+ externalKey: 'C1:1.1',
+ workspace: 'cindy',
+ prompt: '修一下',
+ options: { model: 'claude-opus-4-8', effort: 'high' },
+ }),
+ );
+ const msg = makeTaskDispatch({
+ requestId: 'r1',
+ externalKey: 'C1:1.1',
+ workspace: 'x',
+ prompt: 'p',
+ });
+ expectReject(
+ { ...msg, payload: { ...msg.payload, options: { effort: 42 } } },
+ 'options.effort must be a string or null',
+ );
+ });
+
+ it('turn.end cancelled: errorMessage 必须为 null', () => {
+ const cancelled: TurnEndPayload = {
+ requestId: 'r1',
+ externalKey: 'C1:1.1',
+ sessionId: 's1',
+ status: 'cancelled',
+ finalText: '(已产出的部分)',
+ errorMessage: null,
+ usage: { durationMs: 1200 },
+ };
+ roundTrip(makeTurnEnd(cancelled));
+ const msg = makeTurnEnd(cancelled);
+ expectReject(
+ { ...msg, payload: { ...cancelled, errorMessage: 'boom' } },
+ 'errorMessage must be null when status is cancelled',
+ );
+ });
+
+ it('未知消息类型仍拒收(type 开放集合只对已知类型开放)', () => {
+ const msg = makeTaskCancel({ requestId: 'r1' });
+ expectReject({ ...msg, type: 'task.pause' }, 'unknown message type');
+ });
+});
+
+describe('turn.reopen(阶段 14: 收口后的续跑)', () => {
+ it('round-trip; sessionId / reason 有显式默认', () => {
+ const msg = makeTurnReopen({
+ requestId: 'r2',
+ reopenOf: 'r1',
+ externalKey: 'slack:C1:1.1',
+ });
+ roundTrip(msg);
+ expect(msg.payload).toEqual({
+ requestId: 'r2',
+ reopenOf: 'r1',
+ externalKey: 'slack:C1:1.1',
+ sessionId: null,
+ reason: 'user-continued',
+ });
+ roundTrip(
+ makeTurnReopen({
+ requestId: 'r3',
+ reopenOf: 'r2',
+ externalKey: 'telegram:123:456',
+ sessionId: 'sess-1',
+ reason: 'user-continued',
+ }),
+ );
+ });
+
+ it('显式传 undefined 的可选值不得覆盖默认(否则序列化丢键 -> 收帧端拒收整帧)', () => {
+ // 调用方常写 `sessionId: maybeId`, 而 maybeId 可能是 undefined。若默认值被它
+ // 覆盖, JSON 序列化会把这个键整个删掉, 对端按"必填字段缺失"拒收 —— 续跑结果
+ // 就再也回不到渠道那条消息上。
+ const msg = makeTurnReopen({
+ requestId: 'r2',
+ reopenOf: 'r1',
+ externalKey: 'k',
+ sessionId: undefined,
+ reason: undefined,
+ });
+ expect(msg.payload.sessionId).toBeNull();
+ expect(msg.payload.reason).toBe('user-continued');
+ roundTrip(msg);
+ });
+
+ it('requestId 不得与 reopenOf 相同(换新 id 是本帧的前提)', () => {
+ // 复用同一个 id 会让 server 把续跑轮登记成它自己的前身, 幂等表状态不可推理。
+ const msg = makeTurnReopen({ requestId: 'r2', reopenOf: 'r1', externalKey: 'k' });
+ expectReject(
+ { ...msg, payload: { ...msg.payload, reopenOf: 'r2' } },
+ 'requestId must differ from reopenOf',
+ );
+ });
+
+ it('必填字段缺失或空串拒收', () => {
+ const msg = makeTurnReopen({ requestId: 'r2', reopenOf: 'r1', externalKey: 'k' });
+ expectReject({ ...msg, payload: { ...msg.payload, reopenOf: '' } }, 'reopenOf must be');
+ expectReject({ ...msg, payload: { ...msg.payload, externalKey: '' } }, 'externalKey must be');
+ expectReject({ ...msg, payload: { ...msg.payload, reason: '' } }, 'reason must be');
+ expectReject({ ...msg, payload: { ...msg.payload, sessionId: 7 } }, 'sessionId must be');
+ });
+
+ it('reason 是开放集合: 未知值放行(消费方兜底), 不拒帧', () => {
+ roundTrip(
+ makeTurnReopen({
+ requestId: 'r2',
+ reopenOf: 'r1',
+ externalKey: 'k',
+ reason: 'some-future-reason',
+ }),
+ );
+ });
+});
diff --git a/packages/slack-hook-protocol/src/__tests__/protocol.test.ts b/packages/slack-hook-protocol/src/__tests__/protocol.test.ts
new file mode 100644
index 0000000000..545e68de66
--- /dev/null
+++ b/packages/slack-hook-protocol/src/__tests__/protocol.test.ts
@@ -0,0 +1,625 @@
+/**
+ * slack-hook-protocol 协议包测试:
+ * 1. 每种消息 构造 -> 序列化 -> 解析 的 round-trip 等价
+ * 2. 信封层坏帧拒收(版本 / 类型 / id / ts / payload / 非 JSON / 超长帧)
+ * 3. 各 payload 的字段联动约束(dispatch 二选一、ack 三态联动、turn.end 状态联动)
+ */
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ HOOK_MAX_FRAME_CHARS,
+ HOOK_FEATURE_TURN_DELIVERY,
+ HOOK_PROTOCOL_VERSION,
+ isHookMessageType,
+ makeHello,
+ makeLifecyclePreference,
+ makePing,
+ makePong,
+ makeSessionArchive,
+ makeTaskAck,
+ makeTaskDispatch,
+ makeTurnEnd,
+ makeTurnDelivery,
+ makeWelcome,
+ parseHookMessage,
+ serializeHookMessage,
+ type HookMessage,
+ type TaskAckPayload,
+ type TurnEndPayload,
+ type TurnDeliveryPayload,
+} from '../index';
+
+/** 构造 -> 序列化 -> 解析, 断言等价并返回解析结果(供进一步断言)。 */
+function roundTrip(message: HookMessage): HookMessage {
+ const parsed = parseHookMessage(serializeHookMessage(message));
+ expect(parsed.ok, parsed.ok ? '' : parsed.error).toBe(true);
+ if (!parsed.ok) throw new Error('unreachable');
+ expect(parsed.message).toEqual(message);
+ return parsed.message;
+}
+
+/** 基于合法消息改坏某些字段, 断言解析失败且错误信息含关键词。 */
+function expectReject(mutated: unknown, keyword: string): void {
+ const parsed = parseHookMessage(mutated);
+ expect(parsed.ok).toBe(false);
+ if (parsed.ok) throw new Error('unreachable');
+ expect(parsed.error).toContain(keyword);
+}
+
+const VALID_ACK_ACCEPTED: TaskAckPayload = {
+ requestId: 'req-1',
+ result: 'accepted',
+ reason: null,
+ sessionId: 'sess-1',
+ queuePosition: null,
+};
+
+const VALID_TURN_END_OK: TurnEndPayload = {
+ requestId: 'req-1',
+ externalKey: 'team-slack:C123:1720000.123',
+ sessionId: 'sess-1',
+ status: 'ok',
+ finalText: '完成了',
+ errorMessage: null,
+ usage: { durationMs: 4500 },
+};
+
+const VALID_TURN_DELIVERY_ACCEPTED: TurnDeliveryPayload = {
+ requestId: 'req-1',
+ state: 'accepted',
+ attempt: 0,
+ retryAt: null,
+ error: null,
+};
+
+describe('round-trip: 每种消息构造后可被解析且等价', () => {
+ it('hello', () => {
+ const msg = roundTrip(
+ makeHello({
+ deviceId: 'dev-abc',
+ deviceName: 'Cindy',
+ workspaces: ['cindy', 'blog'],
+ agents: ['cc', 'codex'],
+ lifecycleAnnouncement: false,
+ }),
+ );
+ if (msg.type !== 'hello') throw new Error('unreachable');
+ // protocolVersion 由包内固定, 不由调用方传
+ expect(msg.payload.protocolVersion).toBe(HOOK_PROTOCOL_VERSION);
+ expect(msg.v).toBe(HOOK_PROTOCOL_VERSION);
+ expect(msg.id.length).toBeGreaterThan(0);
+ expect(msg.payload.lifecycleAnnouncement).toBe(false);
+ });
+
+ it('lifecycle.preference', () => {
+ roundTrip(makeLifecyclePreference({ enabled: true }));
+ expectReject(
+ { ...makeLifecyclePreference({ enabled: true }), payload: { enabled: 'yes' } },
+ 'lifecycle.preference.enabled',
+ );
+ });
+
+ it('welcome / ping / pong', () => {
+ roundTrip(makeWelcome({ serverName: 'my-hooks', features: [] }));
+ roundTrip(makePing());
+ roundTrip(makePong());
+ });
+
+ it('turn.delivery accepted / retrying / delivered / failed', () => {
+ expect(HOOK_FEATURE_TURN_DELIVERY).toBe('turn-delivery-v1');
+ roundTrip(makeTurnDelivery(VALID_TURN_DELIVERY_ACCEPTED));
+ roundTrip(
+ makeTurnDelivery({
+ requestId: 'req-1',
+ state: 'retrying',
+ attempt: 1,
+ retryAt: 1_800_000_000_000,
+ error: {
+ code: 'X_RATE_LIMITED',
+ message: 'X 暂时限制了回复发布,服务端会自动重试。',
+ retryable: true,
+ },
+ }),
+ );
+ roundTrip(
+ makeTurnDelivery({
+ requestId: 'req-1',
+ state: 'delivered',
+ attempt: 2,
+ retryAt: null,
+ error: null,
+ }),
+ );
+ roundTrip(
+ makeTurnDelivery({
+ requestId: 'req-1',
+ state: 'failed',
+ attempt: 2,
+ retryAt: null,
+ error: {
+ code: 'X_FORBIDDEN',
+ message: 'X 拒绝了回复发布。',
+ retryable: false,
+ },
+ }),
+ );
+ });
+
+ it('task.dispatch 普通派发(workspace 路径)', () => {
+ const msg = roundTrip(
+ makeTaskDispatch({
+ requestId: 'req-1',
+ externalKey: 'team-slack:C123:1720000.123',
+ workspace: 'cindy',
+ prompt: '看下 CI 为什么挂了',
+ }),
+ );
+ if (msg.type !== 'task.dispatch') throw new Error('unreachable');
+ // 构造器给出显式默认: sessionId null
+ expect(msg.payload.sessionId).toBeNull();
+ });
+
+ it('task.dispatch 带图片附件(attachments)', () => {
+ const msg = roundTrip(
+ makeTaskDispatch({
+ requestId: 'req-img',
+ externalKey: 'team-slack:C1:1.1',
+ workspace: 'cindy',
+ prompt: '看看这张图',
+ attachments: [
+ { name: 'shot.png', mimeType: 'image/png', dataBase64: 'aGVsbG8=' },
+ { name: null, mimeType: 'image/jpeg', dataBase64: 'd29ybGQ=' },
+ ],
+ }),
+ );
+ if (msg.type !== 'task.dispatch') throw new Error('unreachable');
+ expect(msg.payload.attachments).toHaveLength(2);
+ expect(msg.payload.attachments?.[1].name).toBeNull();
+ });
+
+ it('task.dispatch 带来源元数据(source: im + threadContext + userText)', () => {
+ const msg = roundTrip(
+ makeTaskDispatch({
+ requestId: 'req-src',
+ externalKey: 'team-slack:C1:1.1',
+ workspace: 'cindy',
+ prompt: '<thread_context>...</thread_context>\n\n看看有没有优化空间',
+ source: {
+ im: 'slack',
+ userText: '看看有没有优化空间',
+ threadContext: [
+ { author: '张三', text: 'auth 是不是有改动' },
+ { author: 'Tina(bot)', text: '已检查', isBot: true },
+ ],
+ },
+ }),
+ );
+ if (msg.type !== 'task.dispatch') throw new Error('unreachable');
+ expect(msg.payload.source?.im).toBe('slack');
+ expect(msg.payload.source?.userText).toBe('看看有没有优化空间');
+ expect(msg.payload.source?.threadContext).toHaveLength(2);
+ // 负例: im 空串 / threadContext 条目缺 text / userText 非 string
+ const base = makeTaskDispatch({
+ requestId: 'r',
+ externalKey: 'k',
+ workspace: 'w',
+ prompt: 'p',
+ });
+ expectReject(
+ { ...base, payload: { ...base.payload, source: { im: '' } } },
+ 'task.dispatch.source.im',
+ );
+ expectReject(
+ {
+ ...base,
+ payload: { ...base.payload, source: { im: 'slack', threadContext: [{ author: 'a' }] } },
+ },
+ 'threadContext[0].text',
+ );
+ expectReject(
+ { ...base, payload: { ...base.payload, source: { im: 'slack', userText: 42 } } },
+ 'task.dispatch.source.userText',
+ );
+ });
+
+ it('task.dispatch 接管派发(sessionId 路径, workspace 可为 null)', () => {
+ roundTrip(
+ makeTaskDispatch({
+ requestId: 'req-2',
+ externalKey: 'team-slack:C123:1720001.456',
+ sessionId: 'sess-42',
+ prompt: '继续',
+ options: { model: null, permissionMode: 'acceptEdits', agentKind: null },
+ }),
+ );
+ });
+
+ it('task.ack 三态', () => {
+ roundTrip(makeTaskAck(VALID_ACK_ACCEPTED));
+ roundTrip(
+ makeTaskAck({
+ requestId: 'req-1',
+ result: 'queued',
+ reason: null,
+ sessionId: 'sess-1',
+ queuePosition: 2,
+ }),
+ );
+ roundTrip(
+ makeTaskAck({
+ requestId: 'req-1',
+ result: 'rejected',
+ reason: 'unknown_workspace',
+ sessionId: null,
+ queuePosition: null,
+ }),
+ );
+ });
+
+ it('session.archive', () => {
+ const msg = roundTrip(makeSessionArchive({ externalKey: 'slack:dm:U123:g2' }));
+ if (msg.type !== 'session.archive') throw new Error('unreachable');
+ expect(msg.payload.externalKey).toBe('slack:dm:U123:g2');
+ // externalKey 必须非空
+ expectReject({ ...msg, payload: { externalKey: '' } }, 'session.archive.externalKey');
+ });
+
+ it('turn.end ok / error', () => {
+ roundTrip(makeTurnEnd(VALID_TURN_END_OK));
+ roundTrip(
+ makeTurnEnd({
+ ...VALID_TURN_END_OK,
+ status: 'error',
+ finalText: '',
+ errorMessage: 'agent runtime error',
+ usage: { durationMs: null },
+ }),
+ );
+ });
+});
+
+describe('信封层坏帧拒收', () => {
+ const base = makePing();
+
+ it('非 JSON 文本', () => {
+ expectReject('not-json{', 'not valid JSON');
+ });
+
+ it('超长帧', () => {
+ expectReject('"' + 'x'.repeat(HOOK_MAX_FRAME_CHARS + 1) + '"', 'frame too large');
+ });
+
+ it('非对象 / 数组', () => {
+ expectReject('42', 'envelope must be an object');
+ expectReject([], 'envelope must be an object');
+ expectReject(null, 'envelope must be an object');
+ });
+
+ it('版本不符', () => {
+ expectReject({ ...base, v: 2 }, 'unsupported protocol version');
+ expectReject({ ...base, v: undefined }, 'unsupported protocol version');
+ });
+
+ it('未知消息类型', () => {
+ // task.cancel 已在 v2 转正, 换一个仍未定义的类型验证拒收
+ expectReject({ ...base, type: 'task.pause' }, 'unknown message type');
+ });
+
+ it('id / ts / payload 非法', () => {
+ expectReject({ ...base, id: '' }, 'envelope.id');
+ expectReject({ ...base, ts: 'now' }, 'envelope.ts');
+ expectReject({ ...base, ts: Number.NaN }, 'envelope.ts');
+ expectReject({ ...base, payload: null }, 'envelope.payload');
+ });
+
+ it('ping payload 必须为空对象', () => {
+ expectReject({ ...base, payload: { extra: 1 } }, 'empty object');
+ });
+});
+
+describe('task.dispatch 字段约束', () => {
+ const valid = makeTaskDispatch({
+ requestId: 'req-1',
+ externalKey: 'k',
+ workspace: 'cindy',
+ prompt: 'p',
+ });
+
+ it('sessionId 为 null 时 workspace 必填', () => {
+ expectReject(
+ { ...valid, payload: { ...valid.payload, workspace: null } },
+ 'workspace is required when sessionId is null',
+ );
+ });
+
+ it('sessionId 给了空串拒收', () => {
+ expectReject({ ...valid, payload: { ...valid.payload, sessionId: '' } }, 'sessionId');
+ });
+
+ it('prompt / requestId / externalKey 必须非空', () => {
+ expectReject({ ...valid, payload: { ...valid.payload, prompt: '' } }, 'prompt');
+ expectReject({ ...valid, payload: { ...valid.payload, requestId: '' } }, 'requestId');
+ expectReject({ ...valid, payload: { ...valid.payload, externalKey: '' } }, 'externalKey');
+ });
+
+ it('options 字段类型', () => {
+ expectReject(
+ { ...valid, payload: { ...valid.payload, options: { model: 42 } } },
+ 'options.model',
+ );
+ expectReject({ ...valid, payload: { ...valid.payload, options: 'x' } }, 'options');
+ });
+
+ it('attachments 校验: 非数组 / 元素缺字段 / 超上限', () => {
+ expectReject({ ...valid, payload: { ...valid.payload, attachments: 'x' } }, 'attachments');
+ expectReject(
+ {
+ ...valid,
+ payload: { ...valid.payload, attachments: [{ name: 'a', mimeType: '', dataBase64: 'x' }] },
+ },
+ 'mimeType',
+ );
+ expectReject(
+ {
+ ...valid,
+ payload: {
+ ...valid.payload,
+ attachments: [{ name: 'a', mimeType: 'image/png', dataBase64: '' }],
+ },
+ },
+ 'dataBase64',
+ );
+ expectReject(
+ {
+ ...valid,
+ payload: {
+ ...valid.payload,
+ attachments: [{ name: 1, mimeType: 'image/png', dataBase64: 'x' }],
+ },
+ },
+ 'name',
+ );
+ const tooMany = Array.from({ length: 17 }, () => ({
+ name: null,
+ mimeType: 'image/png',
+ dataBase64: 'x',
+ }));
+ expectReject({ ...valid, payload: { ...valid.payload, attachments: tooMany } }, 'at most');
+ });
+});
+
+describe('task.ack 三态联动约束', () => {
+ const valid = makeTaskAck(VALID_ACK_ACCEPTED);
+
+ it('非 rejected 不许带 reason', () => {
+ expectReject(
+ { ...valid, payload: { ...valid.payload, reason: 'invalid' } },
+ 'reason must be null unless rejected',
+ );
+ });
+
+ it('rejected 必须带枚举内 reason 且 sessionId 为 null', () => {
+ expectReject(
+ {
+ ...valid,
+ payload: { ...valid.payload, result: 'rejected', reason: null, sessionId: null },
+ },
+ 'reason must be one of',
+ );
+ expectReject(
+ {
+ ...valid,
+ payload: { ...valid.payload, result: 'rejected', reason: 'nope', sessionId: null },
+ },
+ 'reason must be one of',
+ );
+ expectReject(
+ {
+ ...valid,
+ payload: { ...valid.payload, result: 'rejected', reason: 'disabled', sessionId: 'sess-1' },
+ },
+ 'sessionId must be null when rejected',
+ );
+ });
+
+ it('accepted / queued 必须带 sessionId', () => {
+ expectReject(
+ { ...valid, payload: { ...valid.payload, sessionId: null } },
+ 'sessionId must be a non-empty string',
+ );
+ });
+
+ it('queuePosition 仅 queued 时非 null, 且为非负整数', () => {
+ expectReject(
+ { ...valid, payload: { ...valid.payload, queuePosition: 1 } },
+ 'queuePosition must be null unless queued',
+ );
+ expectReject(
+ { ...valid, payload: { ...valid.payload, result: 'queued', queuePosition: null } },
+ 'queuePosition must be a non-negative integer',
+ );
+ expectReject(
+ { ...valid, payload: { ...valid.payload, result: 'queued', queuePosition: -1 } },
+ 'queuePosition must be a non-negative integer',
+ );
+ expectReject(
+ { ...valid, payload: { ...valid.payload, result: 'queued', queuePosition: 1.5 } },
+ 'queuePosition must be a non-negative integer',
+ );
+ });
+});
+
+describe('turn.end 状态联动约束', () => {
+ const valid = makeTurnEnd(VALID_TURN_END_OK);
+
+ it('ok 时 errorMessage 必须为 null', () => {
+ expectReject(
+ { ...valid, payload: { ...valid.payload, errorMessage: 'boom' } },
+ 'errorMessage must be null when status is ok',
+ );
+ });
+
+ it('error 时 errorMessage 必须非空', () => {
+ expectReject(
+ { ...valid, payload: { ...valid.payload, status: 'error', errorMessage: null } },
+ 'errorMessage must be a non-empty string',
+ );
+ expectReject(
+ { ...valid, payload: { ...valid.payload, status: 'error', errorMessage: '' } },
+ 'errorMessage must be a non-empty string',
+ );
+ });
+
+ it('finalText 允许空串但必须是 string', () => {
+ const ok = parseHookMessage({ ...valid, payload: { ...valid.payload, finalText: '' } });
+ expect(ok.ok).toBe(true);
+ expectReject({ ...valid, payload: { ...valid.payload, finalText: null } }, 'finalText');
+ });
+
+ it('usage.durationMs 非负有限数或 null', () => {
+ expectReject(
+ { ...valid, payload: { ...valid.payload, usage: { durationMs: -1 } } },
+ 'durationMs',
+ );
+ expectReject(
+ { ...valid, payload: { ...valid.payload, usage: { durationMs: Number.POSITIVE_INFINITY } } },
+ 'durationMs',
+ );
+ expectReject({ ...valid, payload: { ...valid.payload, usage: null } }, 'usage');
+ });
+});
+
+describe('turn.delivery 状态联动约束', () => {
+ const valid = makeTurnDelivery(VALID_TURN_DELIVERY_ACCEPTED);
+
+ const validRetrying = {
+ ...valid,
+ payload: {
+ ...valid.payload,
+ state: 'retrying' as const,
+ attempt: 1,
+ retryAt: 1_800_000_000_000,
+ error: { code: 'X', message: 'x', retryable: true },
+ },
+ };
+
+ it('accepted / delivered 不带 error 或 retryAt', () => {
+ expectReject(
+ {
+ ...valid,
+ payload: { ...valid.payload, error: { code: 'X', message: 'x', retryable: false } },
+ },
+ 'error must be null',
+ );
+ expectReject(
+ { ...valid, payload: { ...valid.payload, retryAt: 1_800_000_000_000 } },
+ 'retryAt',
+ );
+ });
+
+ it('retrying 必须带可重试错误和 retryAt', () => {
+ expectReject(
+ { ...valid, payload: { ...valid.payload, state: 'retrying', attempt: 1 } },
+ 'retryAt',
+ );
+ expectReject(
+ {
+ ...valid,
+ payload: {
+ ...valid.payload,
+ state: 'retrying',
+ attempt: 1,
+ retryAt: 1_800_000_000_000,
+ error: { code: 'X', message: 'x', retryable: false },
+ },
+ },
+ 'retryable must be true',
+ );
+ });
+
+ it('attempt 必须与状态联动', () => {
+ expectReject(
+ { ...valid, payload: { ...valid.payload, attempt: 1 } },
+ 'attempt must be 0 when state is accepted',
+ );
+ expectReject(
+ { ...validRetrying, payload: { ...validRetrying.payload, attempt: 0 } },
+ 'attempt must be at least 1 when state is retrying',
+ );
+ expectReject(
+ {
+ ...valid,
+ payload: { ...valid.payload, state: 'delivered', attempt: 0 },
+ },
+ 'attempt must be at least 1 when state is delivered',
+ );
+ expectReject(
+ {
+ ...valid,
+ payload: {
+ ...valid.payload,
+ state: 'failed',
+ attempt: 0,
+ error: { code: 'X', message: 'x', retryable: false },
+ },
+ },
+ 'attempt must be at least 1 when state is failed',
+ );
+ expectReject(
+ { ...valid, payload: { ...valid.payload, attempt: Number.MAX_SAFE_INTEGER + 1 } },
+ 'safe integer',
+ );
+ });
+
+ it('retryAt 必须是 retrying 状态的正安全整数', () => {
+ for (const retryAt of [1.5, Number.MAX_SAFE_INTEGER + 1, 0, -1]) {
+ expectReject(
+ { ...validRetrying, payload: { ...validRetrying.payload, retryAt } },
+ 'positive safe integer',
+ );
+ }
+ });
+
+ it('failed 必须带不可重试的结构化错误', () => {
+ expectReject(
+ { ...valid, payload: { ...valid.payload, state: 'failed', attempt: 1 } },
+ 'error must be an object',
+ );
+ expectReject({ ...valid, payload: { ...valid.payload, attempt: 1.5 } }, 'attempt');
+ expectReject(
+ {
+ ...valid,
+ payload: {
+ ...valid.payload,
+ state: 'failed',
+ attempt: 1,
+ error: { code: 'X', message: 'x', retryable: true },
+ },
+ },
+ 'retryable must be false',
+ );
+ });
+
+ it('error 只允许安全结构化字段', () => {
+ expectReject(
+ {
+ ...validRetrying,
+ payload: {
+ ...validRetrying.payload,
+ error: { ...validRetrying.payload.error, providerResponse: 'secret' },
+ },
+ },
+ 'providerResponse is not allowed',
+ );
+ });
+});
+
+describe('辅助函数', () => {
+ it('isHookMessageType', () => {
+ expect(isHookMessageType('task.dispatch')).toBe(true);
+ expect(isHookMessageType('task.cancel')).toBe(true); // v2 转正
+ expect(isHookMessageType('turn.delivery')).toBe(true);
+ expect(isHookMessageType('task.pause')).toBe(false);
+ });
+});
diff --git a/packages/slack-hook-protocol/src/__tests__/scenario.test.ts b/packages/slack-hook-protocol/src/__tests__/scenario.test.ts
new file mode 100644
index 0000000000..a2b9bbef0e
--- /dev/null
+++ b/packages/slack-hook-protocol/src/__tests__/scenario.test.ts
@@ -0,0 +1,282 @@
+/**
+ * 协议场景测试: 在真实 TCP 回环 socket 上模拟 server 与 desktop 两端,
+ * 用 NDJSON 帧(每行一帧)跑完整协议生命周期 —— 验证的不是单个函数,
+ * 而是「构造 -> 序列化 -> 过真实网络边界(含帧被 TCP 分片/粘连) -> 解析 ->
+ * 状态机联动」这条完整链路:
+ *
+ * 1. 四幕 happy path: hello -> welcome -> dispatch -> ack(accepted) -> turn.end
+ * 2. requestId 幂等: 同一任务重投两次, desktop 只执行一次、ack 原样回放
+ * 3. 拒绝路径: 未注册的 workspace 别名 -> rejected(unknown_workspace)
+ *
+ * 传输层帧边界(NDJSON 切分/缓冲)是测试自带的最小实现 —— 协议包本身
+ * 传输无关, 这里只为让帧真实经过 socket。
+ */
+
+import { createServer, type Server, type Socket } from 'node:net';
+import { once } from 'node:events';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ makeHello,
+ makePing,
+ makeTaskAck,
+ makeTaskDispatch,
+ makeTurnEnd,
+ makeWelcome,
+ parseHookMessage,
+ serializeHookMessage,
+ type HookMessage,
+ type HookTaskAckMessage,
+} from '../index';
+
+/** 往 socket 写一帧(NDJSON: 序列化 + 换行)。 */
+function sendFrame(sock: Socket, message: HookMessage): void {
+ sock.write(serializeHookMessage(message) + '\n');
+}
+
+/**
+ * 帧读取器: 处理 TCP 分片/粘连, 每解析出一帧就入队;
+ * next() 返回下一帧(已过 parseHookMessage, 坏帧直接抛错让测试失败)。
+ */
+function frameReader(sock: Socket): { next: () => Promise<HookMessage> } {
+ let buffer = '';
+ const queue: HookMessage[] = [];
+ const waiters: Array<(m: HookMessage) => void> = [];
+
+ sock.on('data', (chunk) => {
+ buffer += chunk.toString('utf-8');
+ let nl: number;
+ while ((nl = buffer.indexOf('\n')) >= 0) {
+ const line = buffer.slice(0, nl);
+ buffer = buffer.slice(nl + 1);
+ if (!line.trim()) continue;
+ const parsed = parseHookMessage(line);
+ if (!parsed.ok) throw new Error(`bad frame on wire: ${parsed.error}`);
+ const waiter = waiters.shift();
+ if (waiter) waiter(parsed.message);
+ else queue.push(parsed.message);
+ }
+ });
+
+ return {
+ next: () =>
+ queue.length > 0
+ ? Promise.resolve(queue.shift() as HookMessage)
+ : new Promise((resolve) => waiters.push(resolve)),
+ };
+}
+
+/** 起一个 TCP 回环对: 返回 server 侧与 desktop(client)侧的 socket + 读取器。 */
+async function loopbackPair(): Promise<{
+ server: Server;
+ serverSock: Socket;
+ desktopSock: Socket;
+ serverRead: ReturnType<typeof frameReader>;
+ desktopRead: ReturnType<typeof frameReader>;
+ close: () => Promise<void>;
+}> {
+ const server = createServer();
+ server.listen(0, '127.0.0.1');
+ await once(server, 'listening');
+ const addr = server.address();
+ if (addr === null || typeof addr === 'string') throw new Error('no port');
+
+ const { connect } = await import('node:net');
+ const acceptPromise = once(server, 'connection');
+ const desktopSock = connect(addr.port, '127.0.0.1');
+ await once(desktopSock, 'connect');
+ const [serverSock] = (await acceptPromise) as [Socket];
+
+ return {
+ server,
+ serverSock,
+ desktopSock,
+ serverRead: frameReader(serverSock),
+ desktopRead: frameReader(desktopSock),
+ close: async () => {
+ desktopSock.destroy();
+ serverSock.destroy();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ },
+ };
+}
+
+/**
+ * 模拟 desktop 侧 dispatcher 的最小状态机:
+ * 别名白名单校验 + requestId 幂等表(重投回放上次 ack, 不重复执行)。
+ */
+function createMiniDesktop(workspaces: Set<string>) {
+ const ackByRequestId = new Map<string, HookTaskAckMessage['payload']>();
+ let executions = 0;
+
+ return {
+ get executions() {
+ return executions;
+ },
+ handleDispatch(payload: {
+ requestId: string;
+ workspace: string | null;
+ sessionId: string | null;
+ }): HookTaskAckMessage['payload'] {
+ const replay = ackByRequestId.get(payload.requestId);
+ if (replay) return replay; // 幂等: 重投只回放, 不再执行
+ let ack: HookTaskAckMessage['payload'];
+ if (payload.sessionId === null && !workspaces.has(payload.workspace ?? '')) {
+ ack = {
+ requestId: payload.requestId,
+ result: 'rejected',
+ reason: 'unknown_workspace',
+ sessionId: null,
+ queuePosition: null,
+ };
+ } else {
+ executions += 1;
+ ack = {
+ requestId: payload.requestId,
+ result: 'accepted',
+ reason: null,
+ sessionId: `sess-${payload.requestId}`,
+ queuePosition: null,
+ };
+ }
+ ackByRequestId.set(payload.requestId, ack);
+ return ack;
+ },
+ };
+}
+
+let cleanup: (() => Promise<void>) | null = null;
+afterEach(async () => {
+ await cleanup?.();
+ cleanup = null;
+});
+
+describe('协议场景: 真实 socket 上的完整生命周期', () => {
+ it('四幕 happy path: hello -> welcome -> dispatch -> ack -> turn.end', async () => {
+ const pair = await loopbackPair();
+ cleanup = pair.close;
+ const { serverSock, desktopSock, serverRead, desktopRead } = pair;
+
+ // 第一幕: desktop 自报家门, server 应答
+ sendFrame(
+ desktopSock,
+ makeHello({
+ deviceId: 'dev-1',
+ deviceName: 'Cindy',
+ workspaces: ['cindy'],
+ agents: ['cc'],
+ }),
+ );
+ const hello = await serverRead.next();
+ expect(hello.type).toBe('hello');
+ if (hello.type !== 'hello') return;
+ expect(hello.payload.workspaces).toEqual(['cindy']);
+
+ sendFrame(serverSock, makeWelcome({ serverName: 'my-hooks', features: [] }));
+ const welcome = await desktopRead.next();
+ expect(welcome.type).toBe('welcome');
+
+ // 心跳走一个来回
+ sendFrame(serverSock, makePing());
+ expect((await desktopRead.next()).type).toBe('ping');
+
+ // 第二幕: server 派活, desktop 立即 ack
+ const desktop = createMiniDesktop(new Set(hello.payload.workspaces));
+ sendFrame(
+ serverSock,
+ makeTaskDispatch({
+ requestId: 'req-100',
+ externalKey: 'team-slack:C123:1720000.123',
+ workspace: 'cindy',
+ prompt: '看下 #632 的 CI 为什么挂了',
+ }),
+ );
+ const dispatch = await desktopRead.next();
+ expect(dispatch.type).toBe('task.dispatch');
+ if (dispatch.type !== 'task.dispatch') return;
+ sendFrame(desktopSock, makeTaskAck(desktop.handleDispatch(dispatch.payload)));
+
+ const ack = await serverRead.next();
+ expect(ack.type).toBe('task.ack');
+ if (ack.type !== 'task.ack') return;
+ expect(ack.payload).toMatchObject({ requestId: 'req-100', result: 'accepted' });
+ expect(desktop.executions).toBe(1);
+
+ // 第四幕: 交差, server 按 externalKey 收到原样回传的回邮地址
+ sendFrame(
+ desktopSock,
+ makeTurnEnd({
+ requestId: 'req-100',
+ externalKey: dispatch.payload.externalKey,
+ sessionId: ack.payload.sessionId,
+ status: 'ok',
+ finalText: 'CI 挂在 typecheck, 已定位',
+ errorMessage: null,
+ usage: { durationMs: 42_000 },
+ }),
+ );
+ const turnEnd = await serverRead.next();
+ expect(turnEnd.type).toBe('turn.end');
+ if (turnEnd.type !== 'turn.end') return;
+ expect(turnEnd.payload.externalKey).toBe('team-slack:C123:1720000.123');
+ expect(turnEnd.payload.status).toBe('ok');
+ });
+
+ it('requestId 幂等: 重投同一任务只执行一次, ack 原样回放', async () => {
+ const pair = await loopbackPair();
+ cleanup = pair.close;
+ const { serverSock, desktopSock, serverRead, desktopRead } = pair;
+ const desktop = createMiniDesktop(new Set(['cindy']));
+
+ const dispatchMsg = makeTaskDispatch({
+ requestId: 'req-200',
+ externalKey: 'team-slack:C123:1720009.999',
+ workspace: 'cindy',
+ prompt: '干活',
+ });
+
+ // 模拟断线重连后 server 重投: 同 requestId 发两次
+ for (let i = 0; i < 2; i++) {
+ sendFrame(serverSock, dispatchMsg);
+ const d = await desktopRead.next();
+ if (d.type !== 'task.dispatch') throw new Error('unexpected frame');
+ sendFrame(desktopSock, makeTaskAck(desktop.handleDispatch(d.payload)));
+ }
+
+ const ack1 = await serverRead.next();
+ const ack2 = await serverRead.next();
+ if (ack1.type !== 'task.ack' || ack2.type !== 'task.ack') throw new Error('unexpected frame');
+ expect(desktop.executions).toBe(1); // 只执行一次
+ expect(ack2.payload).toEqual(ack1.payload); // 回放的 ack 完全一致
+ });
+
+ it('拒绝路径: 未注册的 workspace 别名被 rejected', async () => {
+ const pair = await loopbackPair();
+ cleanup = pair.close;
+ const { serverSock, desktopSock, serverRead, desktopRead } = pair;
+ const desktop = createMiniDesktop(new Set(['cindy']));
+
+ sendFrame(
+ serverSock,
+ makeTaskDispatch({
+ requestId: 'req-300',
+ externalKey: 'gh:cindy/protocol-demo:issue:632',
+ workspace: 'not-registered',
+ prompt: '修一下',
+ }),
+ );
+ const d = await desktopRead.next();
+ if (d.type !== 'task.dispatch') throw new Error('unexpected frame');
+ sendFrame(desktopSock, makeTaskAck(desktop.handleDispatch(d.payload)));
+
+ const ack = await serverRead.next();
+ if (ack.type !== 'task.ack') throw new Error('unexpected frame');
+ expect(ack.payload).toMatchObject({
+ result: 'rejected',
+ reason: 'unknown_workspace',
+ sessionId: null,
+ });
+ expect(desktop.executions).toBe(0);
+ });
+});
diff --git a/packages/slack-hook-protocol/src/build.ts b/packages/slack-hook-protocol/src/build.ts
new file mode 100644
index 0000000000..470e454270
--- /dev/null
+++ b/packages/slack-hook-protocol/src/build.ts
@@ -0,0 +1,344 @@
+/**
+ * slack-hook-protocol/build.ts
+ * ---------------------------------------------------------------------------
+ * 协议帧构造器: 两端发帧的唯一出口。信封字段(v / id / ts)在这里统一生成,
+ * 业务代码只提供 payload —— 保证发出的每一帧都合法且版本一致。
+ *
+ * 构造器只做形状组装, 不做业务校验(如 ack 的 reason/result 联动由类型签名
+ * 约束 + 对端 parse 兜底); serialize 前如需自检可回喂 parseHookMessage。
+ */
+
+import { randomUUID } from 'node:crypto';
+
+import {
+ HOOK_PROTOCOL_VERSION,
+ type BindRevokePayload,
+ type BindStartPayload,
+ type BindStatePayload,
+ type BindUpdatePayload,
+ type HelloPayload,
+ type HookBindRevokeMessage,
+ type HookBindStartMessage,
+ type HookBindStateMessage,
+ type HookBindUpdateMessage,
+ type HookEnvelope,
+ type HookHelloMessage,
+ type HookInteractionCancelMessage,
+ type HookInteractionDecisionMessage,
+ type HookInteractionRequestMessage,
+ type HookLifecyclePreferenceMessage,
+ type HookMessage,
+ type HookMessageType,
+ type HookPingMessage,
+ type HookPongMessage,
+ type HookPrefsGetMessage,
+ type HookPrefsSetMessage,
+ type HookPrefsStateMessage,
+ type HookProviderBindCancelMessage,
+ type HookProviderBindRevokeMessage,
+ type HookProviderBindStartMessage,
+ type HookProviderBindStateMessage,
+ type HookProviderBindUpdateMessage,
+ type GroupMessagePayload,
+ type HookGroupMessageMessage,
+ type HookProviderBehaviorGetMessage,
+ type HookProviderBehaviorSetMessage,
+ type HookProviderBehaviorStateMessage,
+ type HookProviderPrefsGetMessage,
+ type HookProviderPrefsSetMessage,
+ type HookProviderPrefsStateMessage,
+ type HookQueryRequestMessage,
+ type HookQueryResponseMessage,
+ type HookSessionArchiveMessage,
+ type HookTaskAckMessage,
+ type HookTaskCancelMessage,
+ type HookTaskDispatchMessage,
+ type HookToolRequestMessage,
+ type HookToolResponseMessage,
+ type HookTurnEndMessage,
+ type HookTurnDeliveryMessage,
+ type HookTurnProgressMessage,
+ type HookTurnReopenMessage,
+ type HookWelcomeMessage,
+ type InteractionCancelPayload,
+ type InteractionDecisionPayload,
+ type InteractionRequestPayload,
+ type LifecyclePreferencePayload,
+ type PrefsGetPayload,
+ type PrefsSetPayload,
+ type PrefsStatePayload,
+ type ProviderBehaviorGetPayload,
+ type ProviderBehaviorSetPayload,
+ type ProviderBehaviorStatePayload,
+ type ProviderBindCancelPayload,
+ type ProviderBindRevokePayload,
+ type ProviderBindStartPayload,
+ type ProviderBindStatePayload,
+ type ProviderBindUpdatePayload,
+ type ProviderPrefsGetPayload,
+ type ProviderPrefsSetPayload,
+ type ProviderPrefsStatePayload,
+ type QueryRequestPayload,
+ type QueryResponsePayload,
+ type SessionArchivePayload,
+ type TaskAckPayload,
+ type TaskCancelPayload,
+ type TaskDispatchPayload,
+ type ToolRequestPayload,
+ type ToolResponsePayload,
+ type TurnEndPayload,
+ type TurnDeliveryPayload,
+ type TurnProgressPayload,
+ type MessageOpPayload,
+ type MessageOpResultPayload,
+ type HookMessageOpMessage,
+ type HookMessageOpResultMessage,
+ type TurnReopenPayload,
+ type WelcomePayload,
+} from './types';
+
+/** 组装信封: 版本固定为当前版本, id 随机, ts 取发送方时钟。 */
+function envelope<TType extends HookMessageType, TPayload>(
+ type: TType,
+ payload: TPayload,
+): HookEnvelope<TType, TPayload> {
+ return { v: HOOK_PROTOCOL_VERSION, type, id: randomUUID(), ts: Date.now(), payload };
+}
+
+/** hello 的入参: protocolVersion 由包内固定, 调用方只报身份与能力。 */
+export type HelloInput = Omit<HelloPayload, 'protocolVersion'>;
+
+export function makeHello(input: HelloInput): HookHelloMessage {
+ return envelope('hello', { protocolVersion: HOOK_PROTOCOL_VERSION, ...input });
+}
+
+export function makeWelcome(payload: WelcomePayload): HookWelcomeMessage {
+ return envelope('welcome', payload);
+}
+
+export function makePing(): HookPingMessage {
+ return envelope('ping', {});
+}
+
+export function makePong(): HookPongMessage {
+ return envelope('pong', {});
+}
+
+/**
+ * dispatch 构造器: workspace / sessionId / options 给出显式默认,
+ * 让"普通派发"调用点只需 requestId + externalKey + workspace + prompt。
+ */
+export function makeTaskDispatch(
+ input: Pick<TaskDispatchPayload, 'requestId' | 'externalKey' | 'prompt'> &
+ Partial<
+ Pick<TaskDispatchPayload, 'workspace' | 'sessionId' | 'options' | 'attachments' | 'source'>
+ >,
+): HookTaskDispatchMessage {
+ return envelope('task.dispatch', {
+ workspace: null,
+ sessionId: null,
+ ...input,
+ });
+}
+
+export function makeTaskAck(payload: TaskAckPayload): HookTaskAckMessage {
+ return envelope('task.ack', payload);
+}
+
+export function makeTurnEnd(payload: TurnEndPayload): HookTurnEndMessage {
+ return envelope('turn.end', payload);
+}
+
+export function makeTurnDelivery(payload: TurnDeliveryPayload): HookTurnDeliveryMessage {
+ return envelope('turn.delivery', payload);
+}
+
+export function makeTurnProgress(payload: TurnProgressPayload): HookTurnProgressMessage {
+ return envelope('turn.progress', payload);
+}
+
+/** msg.op: 内容面上收客户端后的消息操作动词(见 types.ts 阶段 20)。 */
+export function makeMessageOp(payload: MessageOpPayload): HookMessageOpMessage {
+ return envelope('msg.op', payload);
+}
+
+/** msg.op.result: 操作回执; messageId 是客户端后续 edit/delete/react 的唯一依据。 */
+export function makeMessageOpResult(payload: MessageOpResultPayload): HookMessageOpResultMessage {
+ return envelope('msg.op.result', payload);
+}
+
+/**
+ * turn.reopen: 续跑轮认领渠道里那条已收口的消息(见 types.ts 文件头第 18 条)。
+ * reason 给出显式默认 —— 当前只有"用户在桌面端续跑"这一种触发。
+ *
+ * 默认值在 spread **之后**兜: `Partial` 允许调用方把可选值显式写成 undefined
+ * (如 `sessionId: maybeId` 而 maybeId 为 undefined), 那样 `...input` 会把默认值
+ * 覆盖成 undefined、JSON 序列化再把这个键整个删掉, 收帧端按"必填字段缺失"拒收
+ * 整帧 —— 续跑结果就再也回不到渠道那条消息上。两个字段都不接受 undefined 语义,
+ * 用 `??` 收敛掉。
+ */
+export function makeTurnReopen(
+ input: Pick<TurnReopenPayload, 'requestId' | 'reopenOf' | 'externalKey'> &
+ Partial<Pick<TurnReopenPayload, 'sessionId' | 'reason'>>,
+): HookTurnReopenMessage {
+ return envelope('turn.reopen', {
+ ...input,
+ sessionId: input.sessionId ?? null,
+ reason: input.reason ?? 'user-continued',
+ });
+}
+
+export function makeBindStart(payload: BindStartPayload): HookBindStartMessage {
+ return envelope('bind.start', payload);
+}
+
+export function makeBindUpdate(payload: BindUpdatePayload): HookBindUpdateMessage {
+ return envelope('bind.update', payload);
+}
+
+/**
+ * bind.revoke: 缺省空 payload = 解绑本设备全部(老语义); 传 { teamId } =
+ * 只解绑该 workspace(multi-team, 仅 server 声明该能力后使用)。
+ */
+export function makeBindRevoke(payload: BindRevokePayload = {}): HookBindRevokeMessage {
+ return envelope('bind.revoke', payload);
+}
+
+export function makeBindState(payload: BindStatePayload): HookBindStateMessage {
+ return envelope('bind.state', payload);
+}
+
+export function makeProviderBindStart(
+ payload: ProviderBindStartPayload,
+): HookProviderBindStartMessage {
+ return envelope('provider.bind.start', payload);
+}
+
+export function makeProviderBindCancel(
+ payload: ProviderBindCancelPayload,
+): HookProviderBindCancelMessage {
+ return envelope('provider.bind.cancel', payload);
+}
+
+export function makeProviderBindRevoke(
+ payload: ProviderBindRevokePayload,
+): HookProviderBindRevokeMessage {
+ return envelope('provider.bind.revoke', payload);
+}
+
+export function makeProviderBindUpdate(
+ payload: ProviderBindUpdatePayload,
+): HookProviderBindUpdateMessage {
+ return envelope('provider.bind.update', payload);
+}
+
+export function makeProviderBindState(
+ payload: ProviderBindStatePayload,
+): HookProviderBindStateMessage {
+ return envelope('provider.bind.state', payload);
+}
+
+export function makeQueryRequest(payload: QueryRequestPayload): HookQueryRequestMessage {
+ return envelope('query.request', payload);
+}
+
+export function makeQueryResponse(payload: QueryResponsePayload): HookQueryResponseMessage {
+ return envelope('query.response', payload);
+}
+
+export function makeTaskCancel(payload: TaskCancelPayload): HookTaskCancelMessage {
+ return envelope('task.cancel', payload);
+}
+
+export function makeSessionArchive(payload: SessionArchivePayload): HookSessionArchiveMessage {
+ return envelope('session.archive', payload);
+}
+
+export function makeInteractionRequest(
+ payload: InteractionRequestPayload,
+): HookInteractionRequestMessage {
+ return envelope('interaction.request', payload);
+}
+
+export function makeInteractionDecision(
+ payload: InteractionDecisionPayload,
+): HookInteractionDecisionMessage {
+ return envelope('interaction.decision', payload);
+}
+
+export function makeInteractionCancel(
+ payload: InteractionCancelPayload,
+): HookInteractionCancelMessage {
+ return envelope('interaction.cancel', payload);
+}
+
+export function makePrefsGet(payload: PrefsGetPayload): HookPrefsGetMessage {
+ return envelope('prefs.get', payload);
+}
+
+export function makePrefsSet(payload: PrefsSetPayload): HookPrefsSetMessage {
+ return envelope('prefs.set', payload);
+}
+
+export function makePrefsState(payload: PrefsStatePayload): HookPrefsStateMessage {
+ return envelope('prefs.state', payload);
+}
+
+export function makeProviderPrefsGet(
+ payload: ProviderPrefsGetPayload,
+): HookProviderPrefsGetMessage {
+ return envelope('provider.prefs.get', payload);
+}
+
+export function makeProviderPrefsSet(
+ payload: ProviderPrefsSetPayload,
+): HookProviderPrefsSetMessage {
+ return envelope('provider.prefs.set', payload);
+}
+
+export function makeProviderPrefsState(
+ payload: ProviderPrefsStatePayload,
+): HookProviderPrefsStateMessage {
+ return envelope('provider.prefs.state', payload);
+}
+
+export function makeProviderBehaviorGet(
+ payload: ProviderBehaviorGetPayload,
+): HookProviderBehaviorGetMessage {
+ return envelope('provider.behavior.get', payload);
+}
+
+export function makeProviderBehaviorSet(
+ payload: ProviderBehaviorSetPayload,
+): HookProviderBehaviorSetMessage {
+ return envelope('provider.behavior.set', payload);
+}
+
+export function makeProviderBehaviorState(
+ payload: ProviderBehaviorStatePayload,
+): HookProviderBehaviorStateMessage {
+ return envelope('provider.behavior.state', payload);
+}
+
+export function makeToolRequest(payload: ToolRequestPayload): HookToolRequestMessage {
+ return envelope('tool.request', payload);
+}
+
+export function makeToolResponse(payload: ToolResponsePayload): HookToolResponseMessage {
+ return envelope('tool.response', payload);
+}
+
+export function makeGroupMessage(payload: GroupMessagePayload): HookGroupMessageMessage {
+ return envelope('group.message', payload);
+}
+
+export function makeLifecyclePreference(
+ payload: LifecyclePreferencePayload,
+): HookLifecyclePreferenceMessage {
+ return envelope('lifecycle.preference', payload);
+}
+
+/** 序列化为 WS 文本帧。与 parseHookMessage 互为逆操作。 */
+export function serializeHookMessage(message: HookMessage): string {
+ return JSON.stringify(message);
+}
diff --git a/packages/slack-hook-protocol/src/index.ts b/packages/slack-hook-protocol/src/index.ts
new file mode 100644
index 0000000000..a50e876217
--- /dev/null
+++ b/packages/slack-hook-protocol/src/index.ts
@@ -0,0 +1,54 @@
+/**
+ * @cindy/slack-hook-protocol
+ * ---------------------------------------------------------------------------
+ * hook server <-> desktop 双工任务协议: 类型 + 运行时校验 + 构造器。
+ * desktop(hook-control)与 hook server 两端共用, 协议单一来源。
+ */
+
+export * from './types';
+export { parseHookMessage, isHookMessageType } from './parse';
+export {
+ makeHello,
+ makeWelcome,
+ makePing,
+ makePong,
+ makeTaskDispatch,
+ makeTaskAck,
+ makeTurnEnd,
+ makeTurnDelivery,
+ makeTurnProgress,
+ makeMessageOp,
+ makeMessageOpResult,
+ makeTurnReopen,
+ makeBindStart,
+ makeBindUpdate,
+ makeBindRevoke,
+ makeBindState,
+ makeProviderBindStart,
+ makeProviderBindCancel,
+ makeProviderBindRevoke,
+ makeProviderBindUpdate,
+ makeProviderBindState,
+ makeQueryRequest,
+ makeQueryResponse,
+ makeTaskCancel,
+ makeSessionArchive,
+ makeInteractionRequest,
+ makeInteractionDecision,
+ makeInteractionCancel,
+ makePrefsGet,
+ makePrefsSet,
+ makePrefsState,
+ makeProviderPrefsGet,
+ makeProviderPrefsSet,
+ makeProviderPrefsState,
+ makeProviderBehaviorGet,
+ makeProviderBehaviorSet,
+ makeProviderBehaviorState,
+ makeToolRequest,
+ makeToolResponse,
+ makeGroupMessage,
+ makeLifecyclePreference,
+ serializeHookMessage,
+ type HelloInput,
+} from './build';
diff --git a/packages/slack-hook-protocol/src/parse.ts b/packages/slack-hook-protocol/src/parse.ts
new file mode 100644
index 0000000000..e10cca7f76
--- /dev/null
+++ b/packages/slack-hook-protocol/src/parse.ts
@@ -0,0 +1,1430 @@
+/**
+ * slack-hook-protocol/parse.ts
+ * ---------------------------------------------------------------------------
+ * 协议帧的运行时校验(规则 9: 确定性用代码保证, 不靠对端自觉)。
+ *
+ * parseHookMessage 是两端收帧的唯一入口: 任何来源的原始数据(WS 文本帧或已
+ * JSON.parse 的对象)先过这里, 通过才进入业务; 坏帧返回 ok:false + 具体原因,
+ * 绝不抛异常 —— 调用方按需记日志/断连, 不需要 try/catch。
+ *
+ * 手写校验、零依赖: 校验规则即协议规范本身, 每个分支的错误信息都带字段路径,
+ * 方便两端联调时直接定位是哪个字段不合法。
+ */
+
+import {
+ BIND_UPDATE_STATES,
+ DEFAULT_TELEGRAM_BEHAVIOR,
+ HOOK_MAX_FRAME_CHARS,
+ HOOK_MESSAGE_TYPES,
+ HOOK_PROVIDERS,
+ HOOK_PROTOCOL_VERSION,
+ MAX_INTERACTION_BUTTONS,
+ PROVIDER_BEHAVIOR_PROVIDERS,
+ QUERY_KINDS,
+ PROVIDER_BIND_STATES,
+ TASK_ACK_RESULTS,
+ TASK_REJECT_REASONS,
+ TELEGRAM_EMOJI_REACTIONS,
+ TELEGRAM_GROUP_ACTIVATION_ALWAYS,
+ TELEGRAM_REPLY_QUOTE_DM,
+ TELEGRAM_REPLY_QUOTE_GROUP,
+ TURN_DELIVERY_STATES,
+ TURN_END_STATUSES,
+ type BindUpdatePayload,
+ type HookMessage,
+ type HookMessageType,
+ type HookParseResult,
+ type ProviderBindStatusPayload,
+ type QueryResponsePayload,
+ type TaskAckPayload,
+ type TaskDispatchPayload,
+ type TurnEndPayload,
+} from './types';
+
+/** 非空字符串。 */
+function isNonEmptyString(v: unknown): v is string {
+ return typeof v === 'string' && v.length > 0;
+}
+
+/** 纯对象(排除 null / 数组)。 */
+function isPlainObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
+}
+
+/** string 数组(允许空数组, 元素必须是非空字符串)。 */
+function isStringArray(v: unknown): v is string[] {
+ return Array.isArray(v) && v.every((x) => isNonEmptyString(x));
+}
+
+/** `string | null` 字段(缺省 undefined 不算合法 —— 协议字段必须显式给 null)。 */
+function isNullableString(v: unknown): v is string | null {
+ return v === null || typeof v === 'string';
+}
+
+function isNullableNonEmptyString(v: unknown): v is string | null {
+ return v === null || isNonEmptyString(v);
+}
+
+/** Positive unix-millisecond timestamp. */
+function isPositiveTimestamp(v: unknown): v is number {
+ return typeof v === 'number' && Number.isSafeInteger(v) && v > 0;
+}
+
+/** Provider links are always HTTPS; provider-specific allowlists live in the host. */
+function isSafeHttpsUrl(v: unknown): v is string {
+ if (!isNonEmptyString(v)) return false;
+ try {
+ const url = new URL(v);
+ return (
+ url.protocol === 'https:' &&
+ url.hostname.length > 0 &&
+ url.username.length === 0 &&
+ url.password.length === 0
+ );
+ } catch {
+ return false;
+ }
+}
+
+function validateProvider(v: unknown, path: string): string | null {
+ if (!HOOK_PROVIDERS.includes(v as never)) {
+ return `${path} must be one of: ${HOOK_PROVIDERS.join(', ')}`;
+ }
+ return null;
+}
+
+function validateProviderBehaviorProvider(v: unknown, path: string): string | null {
+ if (!PROVIDER_BEHAVIOR_PROVIDERS.includes(v as never)) {
+ return `${path} must be one of: ${PROVIDER_BEHAVIOR_PROVIDERS.join(', ')}`;
+ }
+ return null;
+}
+
+/** Telegram group/channel ids are canonical negative integers within Bot API's 52-bit range. */
+const TELEGRAM_CHAT_ID_MAX_CHARS = 32;
+const TELEGRAM_GROUP_CHAT_ID_PATTERN = /^-[1-9][0-9]*$/;
+const TELEGRAM_ID_MAX = (1n << 52n) - 1n;
+const TELEGRAM_CHAT_ID_MIN = -TELEGRAM_ID_MAX;
+
+function isTelegramGroupChatId(v: unknown): v is string {
+ if (
+ typeof v !== 'string' ||
+ v.length === 0 ||
+ v.length > TELEGRAM_CHAT_ID_MAX_CHARS ||
+ !TELEGRAM_GROUP_CHAT_ID_PATTERN.test(v)
+ ) {
+ return false;
+ }
+ return BigInt(v) >= TELEGRAM_CHAT_ID_MIN;
+}
+
+/**
+ * Optional nullable-enum patch field (provider.behavior.set's three global
+ * fields): undefined = untouched; null = explicit clear (revert to whatever
+ * DEFAULT_TELEGRAM_BEHAVIOR carries for this field); a string must be a known
+ * enum member (set as an explicit override, persisted even if it happens to
+ * equal the current default — see ProviderBehaviorSetPayload's docblock).
+ */
+function validateOptionalNullableEnum(
+ v: unknown,
+ allowed: readonly string[],
+ path: string,
+): string | null {
+ if (v === undefined || v === null) return null;
+ if (typeof v !== 'string' || !allowed.includes(v)) {
+ return `${path} must be one of: ${allowed.join(', ')}, or null, when present`;
+ }
+ return null;
+}
+
+function fail(error: string): HookParseResult {
+ return { ok: false, error };
+}
+
+// ── 各消息 payload 校验 ──────────────────────────────────────────────────────
+// 每个校验器返回 null 表示通过, 否则返回带字段路径的错误描述。
+
+function validateHello(p: Record<string, unknown>): string | null {
+ if (typeof p.protocolVersion !== 'number') return 'hello.protocolVersion must be a number';
+ if (!isNonEmptyString(p.deviceId)) return 'hello.deviceId must be a non-empty string';
+ if (!isNonEmptyString(p.deviceName)) return 'hello.deviceName must be a non-empty string';
+ if (!isStringArray(p.workspaces)) return 'hello.workspaces must be an array of non-empty strings';
+ if (!isStringArray(p.agents)) return 'hello.agents must be an array of non-empty strings';
+ // features 可选(旧 desktop 不发 = 无能力)
+ if (p.features !== undefined && !isStringArray(p.features)) {
+ return 'hello.features must be an array of non-empty strings when present';
+ }
+ if (p.lifecycleAnnouncement !== undefined && typeof p.lifecycleAnnouncement !== 'boolean') {
+ return 'hello.lifecycleAnnouncement must be a boolean when present';
+ }
+ // defaultWorkspace 可选(旧 desktop 不发 = 无默认)。成员关系在协议层卡死:
+ // server 只能派发 workspaces 内的别名, 默认值若能指向清单外的别名, 等于给
+ // 这条约束开了后门 —— 而它恰恰是 server 侧派发校验的唯一依据。
+ if (p.defaultWorkspace !== undefined && p.defaultWorkspace !== null) {
+ if (!isNonEmptyString(p.defaultWorkspace)) {
+ return 'hello.defaultWorkspace must be a non-empty string or null when present';
+ }
+ if (!(p.workspaces as string[]).includes(p.defaultWorkspace)) {
+ return 'hello.defaultWorkspace must be one of hello.workspaces';
+ }
+ }
+ return null;
+}
+
+function validateWelcome(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.serverName)) return 'welcome.serverName must be a non-empty string';
+ if (!isStringArray(p.features)) return 'welcome.features must be an array of non-empty strings';
+ return null;
+}
+
+function validateLifecyclePreference(p: Record<string, unknown>): string | null {
+ if (typeof p.enabled !== 'boolean') {
+ return 'lifecycle.preference.enabled must be a boolean';
+ }
+ return null;
+}
+
+/** ping / pong: payload 必须是空对象(有多余键 = 对端实现有误, 拒收暴露问题)。 */
+function validateEmpty(p: Record<string, unknown>, label: string): string | null {
+ if (Object.keys(p).length > 0) return `${label}.payload must be an empty object`;
+ return null;
+}
+
+function validateDispatchOptions(v: unknown): string | null {
+ if (v === undefined) return null;
+ if (!isPlainObject(v)) return 'task.dispatch.options must be an object when present';
+ for (const key of ['model', 'permissionMode', 'agentKind', 'effort'] as const) {
+ if (v[key] !== undefined && !isNullableString(v[key])) {
+ return `task.dispatch.options.${key} must be a string or null`;
+ }
+ }
+ return null;
+}
+
+/** 附件数组上限(粗防御, 精细限额在生产端)。 */
+const MAX_ATTACHMENTS = 16;
+
+/** 附件数组校验(入站 task.dispatch 与出站 turn.end 共用, label 定位错误)。 */
+function validateAttachments(v: unknown, label: string): string | null {
+ if (v === undefined) return null;
+ if (!Array.isArray(v)) return `${label}.attachments must be an array when present`;
+ if (v.length > MAX_ATTACHMENTS) {
+ return `${label}.attachments must have at most ${MAX_ATTACHMENTS} items`;
+ }
+ for (let i = 0; i < v.length; i++) {
+ const a = v[i];
+ if (!isPlainObject(a)) return `${label}.attachments[${i}] must be an object`;
+ if (a.name !== null && typeof a.name !== 'string') {
+ return `${label}.attachments[${i}].name must be a string or null`;
+ }
+ if (!isNonEmptyString(a.mimeType)) {
+ return `${label}.attachments[${i}].mimeType must be a non-empty string`;
+ }
+ if (!isNonEmptyString(a.dataBase64)) {
+ return `${label}.attachments[${i}].dataBase64 must be a non-empty string`;
+ }
+ }
+ return null;
+}
+
+function validateSource(v: unknown): string | null {
+ if (v === undefined) return null;
+ if (!isPlainObject(v)) return 'task.dispatch.source must be an object when present';
+ if (!isNonEmptyString(v.im)) return 'task.dispatch.source.im must be a non-empty string';
+ if (v.channelName !== undefined && !isNullableString(v.channelName)) {
+ return 'task.dispatch.source.channelName must be a string or null';
+ }
+ if (v.teamId !== undefined && !isNullableString(v.teamId)) {
+ return 'task.dispatch.source.teamId must be a string or null';
+ }
+ if (v.teamName !== undefined && !isNullableString(v.teamName)) {
+ return 'task.dispatch.source.teamName must be a string or null';
+ }
+ if (v.userText !== undefined && typeof v.userText !== 'string') {
+ return 'task.dispatch.source.userText must be a string when present';
+ }
+ if (v.triggerMessageId !== undefined && !isNullableNonEmptyString(v.triggerMessageId)) {
+ return 'task.dispatch.source.triggerMessageId must be a non-empty string or null';
+ }
+ if (v.threadContext !== undefined) {
+ if (!Array.isArray(v.threadContext)) {
+ return 'task.dispatch.source.threadContext must be an array when present';
+ }
+ for (let i = 0; i < v.threadContext.length; i++) {
+ const entry = v.threadContext[i];
+ if (!isPlainObject(entry))
+ return `task.dispatch.source.threadContext[${i}] must be an object`;
+ if (typeof entry.author !== 'string') {
+ return `task.dispatch.source.threadContext[${i}].author must be a string`;
+ }
+ if (typeof entry.text !== 'string') {
+ return `task.dispatch.source.threadContext[${i}].text must be a string`;
+ }
+ }
+ }
+ return null;
+}
+
+function validateDispatch(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) return 'task.dispatch.requestId must be a non-empty string';
+ if (!isNonEmptyString(p.externalKey))
+ return 'task.dispatch.externalKey must be a non-empty string';
+ if (!isNullableString(p.workspace)) return 'task.dispatch.workspace must be a string or null';
+ if (!isNullableString(p.sessionId)) return 'task.dispatch.sessionId must be a string or null';
+ // 会话定位二选一: 无 sessionId(默认路径)时 workspace 必填
+ if (p.sessionId === null && !isNonEmptyString(p.workspace)) {
+ return 'task.dispatch.workspace is required when sessionId is null';
+ }
+ if (p.sessionId !== null && !isNonEmptyString(p.sessionId)) {
+ return 'task.dispatch.sessionId must be a non-empty string when present';
+ }
+ if (!isNonEmptyString(p.prompt)) return 'task.dispatch.prompt must be a non-empty string';
+ const optErr = validateDispatchOptions(p.options);
+ if (optErr) return optErr;
+ const attErr = validateAttachments(p.attachments, 'task.dispatch');
+ if (attErr) return attErr;
+ return validateSource(p.source);
+}
+
+function validateAck(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) return 'task.ack.requestId must be a non-empty string';
+ if (!TASK_ACK_RESULTS.includes(p.result as never)) {
+ return `task.ack.result must be one of: ${TASK_ACK_RESULTS.join(', ')}`;
+ }
+ const result = p.result as TaskAckPayload['result'];
+ // reason 与 result 联动: 仅 rejected 时必填且必须在枚举内
+ if (result === 'rejected') {
+ if (!TASK_REJECT_REASONS.includes(p.reason as never)) {
+ return `task.ack.reason must be one of: ${TASK_REJECT_REASONS.join(', ')} when rejected`;
+ }
+ if (p.sessionId !== null) return 'task.ack.sessionId must be null when rejected';
+ } else {
+ if (p.reason !== null) return 'task.ack.reason must be null unless rejected';
+ if (!isNonEmptyString(p.sessionId)) {
+ return 'task.ack.sessionId must be a non-empty string when accepted/queued';
+ }
+ }
+ // queuePosition 与 result 联动: 仅 queued 时非 null
+ if (result === 'queued') {
+ if (
+ typeof p.queuePosition !== 'number' ||
+ !Number.isInteger(p.queuePosition) ||
+ p.queuePosition < 0
+ ) {
+ return 'task.ack.queuePosition must be a non-negative integer when queued';
+ }
+ } else if (p.queuePosition !== null) {
+ return 'task.ack.queuePosition must be null unless queued';
+ }
+ return null;
+}
+
+function validateTurnEnd(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) return 'turn.end.requestId must be a non-empty string';
+ if (!isNonEmptyString(p.externalKey)) return 'turn.end.externalKey must be a non-empty string';
+ if (!isNullableString(p.sessionId)) return 'turn.end.sessionId must be a string or null';
+ if (!TURN_END_STATUSES.includes(p.status as never)) {
+ return `turn.end.status must be one of: ${TURN_END_STATUSES.join(', ')}`;
+ }
+ if (typeof p.finalText !== 'string') return 'turn.end.finalText must be a string';
+ // errorMessage 与 status 联动: 仅 error 时必填非空, ok / cancelled 恒 null
+ if (p.status === 'error') {
+ if (!isNonEmptyString(p.errorMessage)) {
+ return 'turn.end.errorMessage must be a non-empty string when status is error';
+ }
+ } else if (p.errorMessage !== null) {
+ return `turn.end.errorMessage must be null when status is ${String(p.status)}`;
+ }
+ if (!isPlainObject(p.usage)) return 'turn.end.usage must be an object';
+ const d = p.usage.durationMs;
+ if (d !== null && (typeof d !== 'number' || !Number.isFinite(d) || d < 0)) {
+ return 'turn.end.usage.durationMs must be a non-negative finite number or null';
+ }
+ return validateAttachments(p.attachments, 'turn.end');
+}
+
+function validateTurnDelivery(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) {
+ return 'turn.delivery.requestId must be a non-empty string';
+ }
+ if (!TURN_DELIVERY_STATES.includes(p.state as never)) {
+ return `turn.delivery.state must be one of: ${TURN_DELIVERY_STATES.join(', ')}`;
+ }
+ const retrying = p.state === 'retrying';
+ const delivered = p.state === 'delivered';
+ const failed = p.state === 'failed';
+ if (typeof p.attempt !== 'number' || !Number.isSafeInteger(p.attempt) || p.attempt < 0) {
+ return 'turn.delivery.attempt must be a non-negative safe integer';
+ }
+ if (p.state === 'accepted' && p.attempt !== 0) {
+ return 'turn.delivery.attempt must be 0 when state is accepted';
+ }
+ if ((retrying || delivered || failed) && p.attempt < 1) {
+ return `turn.delivery.attempt must be at least 1 when state is ${String(p.state)}`;
+ }
+ if (retrying) {
+ if (typeof p.retryAt !== 'number' || !Number.isSafeInteger(p.retryAt) || p.retryAt <= 0) {
+ return 'turn.delivery.retryAt must be a positive safe integer when state is retrying';
+ }
+ } else if (p.retryAt !== null) {
+ return 'turn.delivery.retryAt must be null when state is not retrying';
+ }
+ if (!retrying && !failed) {
+ return p.error === null
+ ? null
+ : `turn.delivery.error must be null when state is ${String(p.state)}`;
+ }
+ if (!isPlainObject(p.error)) {
+ return `turn.delivery.error must be an object when state is ${String(p.state)}`;
+ }
+ if (!isNonEmptyString(p.error.code)) {
+ return 'turn.delivery.error.code must be a non-empty string';
+ }
+ if (!isNonEmptyString(p.error.message)) {
+ return 'turn.delivery.error.message must be a non-empty string';
+ }
+ if (typeof p.error.retryable !== 'boolean') {
+ return 'turn.delivery.error.retryable must be a boolean';
+ }
+ const allowedErrorKeys = new Set(['code', 'message', 'retryable']);
+ const unexpectedErrorKey = Object.keys(p.error).find((key) => !allowedErrorKeys.has(key));
+ if (unexpectedErrorKey !== undefined) {
+ return `turn.delivery.error.${unexpectedErrorKey} is not allowed`;
+ }
+ if (retrying && p.error.retryable !== true) {
+ return 'turn.delivery.error.retryable must be true when state is retrying';
+ }
+ if (failed && p.error.retryable !== false) {
+ return 'turn.delivery.error.retryable must be false when state is failed';
+ }
+ return null;
+}
+
+function validateTurnProgress(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) return 'turn.progress.requestId must be a non-empty string';
+ if (typeof p.text !== 'string') return 'turn.progress.text must be a string';
+ return null;
+}
+
+/**
+ * turn.reopen: requestId 与 reopenOf 必须都在且**不相等** —— 复用同一个 id 会让
+ * server 侧把新一轮登记成它自己的前身, 幂等表状态不可推理(见 types.ts 第 18 条:
+ * 续跑刻意换新 id)。reason 是开放集合, 只校验非空串, 未知值由消费方兜底。
+ */
+function validateTurnReopen(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) return 'turn.reopen.requestId must be a non-empty string';
+ if (!isNonEmptyString(p.reopenOf)) return 'turn.reopen.reopenOf must be a non-empty string';
+ if (p.requestId === p.reopenOf) return 'turn.reopen.requestId must differ from reopenOf';
+ if (!isNonEmptyString(p.externalKey)) {
+ return 'turn.reopen.externalKey must be a non-empty string';
+ }
+ if (!isNullableString(p.sessionId)) return 'turn.reopen.sessionId must be a string or null';
+ if (!isNonEmptyString(p.reason)) return 'turn.reopen.reason must be a non-empty string';
+ return null;
+}
+
+/**
+ * msg.op: 内容面上收客户端后的消息操作动词。
+ *
+ * 校验刻意只到"形状"为止 —— 服务端是哑执行器, 不解释内容, 所以正文长度、
+ * 分块、文案一律不在这里判(那些由客户端负责)。但两件事必须校严:
+ * - `opId` 是断连重发下不产生重复消息的唯一依据(Telegram 无发送端幂等键),
+ * 缺失即拒收, 不能让服务端"尽力而为"地猜;
+ * - `scope.externalKey` 是多租户授权的锚点, 缺失即拒收。
+ */
+function validateMessageOp(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.opId)) return 'msg.op.opId must be a non-empty string';
+ if (p.requestId !== undefined && !isNonEmptyString(p.requestId)) {
+ return 'msg.op.requestId must be a non-empty string when present';
+ }
+ if (!isPlainObject(p.scope)) return 'msg.op.scope must be an object';
+ const scope = p.scope as Record<string, unknown>;
+ if (!isNonEmptyString(scope.externalKey)) {
+ return 'msg.op.scope.externalKey must be a non-empty string';
+ }
+ // 寻址字段一律拒收: externalKey 是唯一授权锚点, 目标 chat 必须由服务端从
+ // 自己那份 lane 记录里取。放行一个客户端指定的 chat_id, 一台被攻陷或有 bug
+ // 的桌面就能越过自己 lane 的边界往任意聊天发消息 —— 静默忽略不够, 因为那会
+ // 让发送方以为寻址生效了。
+ if (scope.chatId !== undefined || scope.threadId !== undefined) {
+ return 'msg.op.scope must not carry chatId/threadId: the server resolves the target from externalKey';
+ }
+ if (!isPlainObject(p.action)) return 'msg.op.action must be an object';
+ const action = p.action as Record<string, unknown>;
+ const kind = action.kind;
+ if (kind === 'send' || kind === 'edit') {
+ if (typeof action.text !== 'string') return `msg.op.action.text must be a string`;
+ if (kind === 'edit' && !isNonEmptyString(action.messageId)) {
+ return 'msg.op.action.messageId must be a non-empty string';
+ }
+ if (
+ action.tier !== undefined &&
+ action.tier !== 'rich' &&
+ action.tier !== 'html' &&
+ action.tier !== 'plain'
+ ) {
+ return 'msg.op.action.tier must be one of: rich, html, plain';
+ }
+ return null;
+ }
+ if (kind === 'delete') {
+ return isNonEmptyString(action.messageId)
+ ? null
+ : 'msg.op.action.messageId must be a non-empty string';
+ }
+ if (kind === 'react') {
+ if (!isNonEmptyString(action.targetMessageId)) {
+ return 'msg.op.action.targetMessageId must be a non-empty string';
+ }
+ // 空串是**撤销**语义, 合法; 只拒非字符串。
+ return typeof action.emoji === 'string' ? null : 'msg.op.action.emoji must be a string';
+ }
+ if (kind === 'typing') return null;
+ if (kind === 'media') {
+ if (!Array.isArray(action.items) || action.items.length === 0) {
+ return 'msg.op.action.items must be a non-empty array';
+ }
+ for (const item of action.items) {
+ if (!isPlainObject(item)) return 'msg.op.action.items[] must be objects';
+ const media = item as Record<string, unknown>;
+ if (!isNonEmptyString(media.name))
+ return 'msg.op.action.items[].name must be a non-empty string';
+ if (!isNonEmptyString(media.mimeType)) {
+ return 'msg.op.action.items[].mimeType must be a non-empty string';
+ }
+ if (!isNonEmptyString(media.dataBase64)) {
+ return 'msg.op.action.items[].dataBase64 must be a non-empty string';
+ }
+ }
+ return null;
+ }
+ return `msg.op.action.kind is unknown: ${String(kind)}`;
+}
+
+/**
+ * msg.op.result: 操作回执。`messageId` 是客户端做后续 edit / delete / react 的
+ * 唯一依据 —— 没有它整个动词集只能发不能改, 所以 ok=true 的 send / media 必须带。
+ * 这里只能校验形状(是否为串), "该不该带"由动作类型决定, 交给消费方。
+ */
+function validateMessageOpResult(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.opId)) return 'msg.op.result.opId must be a non-empty string';
+ if (typeof p.ok !== 'boolean') return 'msg.op.result.ok must be a boolean';
+ // messageId / error 都是**可选**字段: typing、delete 的回执没有 message id,
+ // 成功回执也没有 error。缺席与显式 null 同义, 都不算格式错误。
+ if (p.messageId !== undefined && !isNullableString(p.messageId)) {
+ return 'msg.op.result.messageId must be a string or null';
+ }
+ if (p.messageIds !== undefined) {
+ if (!Array.isArray(p.messageIds) || p.messageIds.some((v) => !isNonEmptyString(v))) {
+ return 'msg.op.result.messageIds must be an array of non-empty strings';
+ }
+ }
+ if (p.error !== undefined && !isNullableString(p.error)) {
+ return 'msg.op.result.error must be a string or null';
+ }
+ if (
+ p.retryAfterMs !== undefined &&
+ p.retryAfterMs !== null &&
+ (typeof p.retryAfterMs !== 'number' || !Number.isFinite(p.retryAfterMs) || p.retryAfterMs < 0)
+ ) {
+ return 'msg.op.result.retryAfterMs must be a non-negative finite number or null';
+ }
+ return null;
+}
+
+// ── v2 增量帧校验 ────────────────────────────────────────────────────────────
+
+/**
+ * 阶段 4 起 email 可选(新端发空对象 {}); 若携带则粗校验为"含 @ 的非空串",
+ * 以便 server 能正常收下老客户端的帧并识别为旧版回升级提示(坏 email 直接
+ * 拒收会丢帧, server 就无从判断)。
+ */
+function validateBindStart(p: Record<string, unknown>): string | null {
+ if (p.email !== undefined && (!isNonEmptyString(p.email) || !p.email.includes('@'))) {
+ return 'bind.start.email, when present, must be an email-like string';
+ }
+ if (p.teamId !== undefined && !isNullableString(p.teamId)) {
+ return 'bind.start.teamId must be a string or null when present';
+ }
+ return null;
+}
+
+function validateBindUpdate(p: Record<string, unknown>): string | null {
+ if (!BIND_UPDATE_STATES.includes(p.state as never)) {
+ return `bind.update.state must be one of: ${BIND_UPDATE_STATES.join(', ')}`;
+ }
+ if (!isNullableString(p.slackUserId)) return 'bind.update.slackUserId must be a string or null';
+ if (!isNullableString(p.slackUserName))
+ return 'bind.update.slackUserName must be a string or null';
+ if (!isNullableString(p.message)) return 'bind.update.message must be a string or null';
+ if (p.authorizeUrl !== undefined && !isNullableString(p.authorizeUrl)) {
+ return 'bind.update.authorizeUrl must be a string or null';
+ }
+ // reason 只校验形状不校验取值: 新 server 推出新 reason 时老客户端照常收下并忽略
+ if (p.reason !== undefined && !isNullableString(p.reason)) {
+ return 'bind.update.reason must be a string or null';
+ }
+ if (p.installUrl !== undefined && !isNullableString(p.installUrl)) {
+ return 'bind.update.installUrl must be a string or null';
+ }
+ if (p.teamName !== undefined && !isNullableString(p.teamName)) {
+ return 'bind.update.teamName must be a string or null';
+ }
+ if (p.teamId !== undefined && !isNullableString(p.teamId)) {
+ return 'bind.update.teamId must be a string or null';
+ }
+ const state = p.state as BindUpdatePayload['state'];
+ // 字段联动: confirmed 必须带身份 slackUserId; pending(OIDC)必须带授权链接;
+ // failed 必须说明原因
+ if (state === 'confirmed' && !isNonEmptyString(p.slackUserId)) {
+ return 'bind.update.slackUserId must be a non-empty string when state is confirmed';
+ }
+ if (state === 'pending' && !isNonEmptyString(p.authorizeUrl)) {
+ return 'bind.update.authorizeUrl must be a non-empty string when state is pending';
+ }
+ if (state === 'failed' && !isNonEmptyString(p.message)) {
+ return 'bind.update.message must be a non-empty string when state is failed';
+ }
+ return null;
+}
+
+/**
+ * bind.revoke: 从空对象放宽为 { teamId?, pendingOnly? }(multi-team 按 team
+ * 解绑 / 取消在途授权)。未知键仍拒收 —— 保留"对端实现有误即拒收"的暴露性。
+ */
+function validateBindRevoke(p: Record<string, unknown>): string | null {
+ for (const key of Object.keys(p)) {
+ if (key !== 'teamId' && key !== 'pendingOnly') {
+ return `bind.revoke.${key} is not a known field`;
+ }
+ }
+ if (p.teamId !== undefined && !isNullableString(p.teamId)) {
+ return 'bind.revoke.teamId must be a string or null when present';
+ }
+ if (p.pendingOnly !== undefined && typeof p.pendingOnly !== 'boolean') {
+ return 'bind.revoke.pendingOnly must be a boolean when present';
+ }
+ return null;
+}
+
+/** bind.state(multi-team): 绑定全量快照。 */
+function validateBindState(p: Record<string, unknown>): string | null {
+ if (!Array.isArray(p.bindings)) return 'bind.state.bindings must be an array';
+ for (let i = 0; i < p.bindings.length; i++) {
+ const b: unknown = p.bindings[i];
+ const path = `bind.state.bindings[${i}]`;
+ if (!isPlainObject(b)) return `${path} must be an object`;
+ if (!isNonEmptyString(b.teamId)) return `${path}.teamId must be a non-empty string`;
+ if (!isNullableString(b.teamName)) return `${path}.teamName must be a string or null`;
+ if (!isNonEmptyString(b.slackUserId)) return `${path}.slackUserId must be a non-empty string`;
+ if (!isNullableString(b.slackUserName)) return `${path}.slackUserName must be a string or null`;
+ }
+ return null;
+}
+
+function validateProviderBindStart(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) {
+ return 'provider.bind.start.requestId must be a non-empty string';
+ }
+ const providerError = validateProvider(p.provider, 'provider.bind.start.provider');
+ if (providerError) return providerError;
+ if (p.scopeId !== undefined && !isNullableNonEmptyString(p.scopeId)) {
+ return 'provider.bind.start.scopeId must be a non-empty string or null when present';
+ }
+ return null;
+}
+
+function validateProviderBindCancel(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) {
+ return 'provider.bind.cancel.requestId must be a non-empty string';
+ }
+ const providerError = validateProvider(p.provider, 'provider.bind.cancel.provider');
+ if (providerError) return providerError;
+ if (!isNonEmptyString(p.attemptId)) {
+ return 'provider.bind.cancel.attemptId must be a non-empty string';
+ }
+ return null;
+}
+
+function validateProviderBindRevoke(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) {
+ return 'provider.bind.revoke.requestId must be a non-empty string';
+ }
+ const providerError = validateProvider(p.provider, 'provider.bind.revoke.provider');
+ if (providerError) return providerError;
+ if (!isNonEmptyString(p.bindingId)) {
+ return 'provider.bind.revoke.bindingId must be a non-empty string';
+ }
+ return null;
+}
+
+const PROVIDER_BIND_ID_FIELDS = [
+ 'attemptId',
+ 'bindingId',
+ 'principalId',
+ 'principalName',
+ 'scopeId',
+ 'scopeName',
+] as const;
+
+const PROVIDER_BIND_FAILURE_STATES = [
+ 'denied',
+ 'expired',
+ 'failed',
+ 'revoked',
+ 'superseded',
+] as const;
+
+/** provider.bind.update/state share one strict, replacement-safe snapshot shape. */
+function validateProviderBindStatus(
+ p: Record<string, unknown>,
+ label: 'provider.bind.update' | 'provider.bind.state',
+): string | null {
+ const providerError = validateProvider(p.provider, `${label}.provider`);
+ if (providerError) return providerError;
+ if (!isNullableNonEmptyString(p.replyTo)) {
+ return `${label}.replyTo must be a non-empty string or null`;
+ }
+ if (!PROVIDER_BIND_STATES.includes(p.state as never)) {
+ return `${label}.state must be one of: ${PROVIDER_BIND_STATES.join(', ')}`;
+ }
+ for (const field of PROVIDER_BIND_ID_FIELDS) {
+ if (!isNullableNonEmptyString(p[field])) {
+ return `${label}.${field} must be a non-empty string or null`;
+ }
+ }
+ if (p.connectUrl !== null && !isSafeHttpsUrl(p.connectUrl)) {
+ return `${label}.connectUrl must be a safe HTTPS URL or null`;
+ }
+ if (p.remediationUrl !== null && !isSafeHttpsUrl(p.remediationUrl)) {
+ return `${label}.remediationUrl must be a safe HTTPS URL or null`;
+ }
+ if (p.expiresAt !== null && !isPositiveTimestamp(p.expiresAt)) {
+ return `${label}.expiresAt must be a positive integer timestamp or null`;
+ }
+ if (!isNullableNonEmptyString(p.reason)) {
+ return `${label}.reason must be a non-empty string or null`;
+ }
+ if (!isStringArray(p.actions)) {
+ return `${label}.actions must be an array of non-empty strings`;
+ }
+ if (p.actions.length > 16) return `${label}.actions must have at most 16 items`;
+ if (new Set(p.actions).size !== p.actions.length) {
+ return `${label}.actions must not contain duplicates`;
+ }
+
+ const state = p.state as ProviderBindStatusPayload['state'];
+ const attemptState =
+ state === 'pending' ||
+ state === 'awaiting_confirmation' ||
+ state === 'denied' ||
+ state === 'expired' ||
+ state === 'failed';
+ const activeAttemptState = state === 'pending' || state === 'awaiting_confirmation';
+ const failedAttemptState = state === 'denied' || state === 'expired' || state === 'failed';
+ if (attemptState && !isNonEmptyString(p.attemptId)) {
+ return `${label}.attemptId must be non-empty for attempt state ${state}`;
+ }
+ if (activeAttemptState && p.bindingId !== null) {
+ return `${label}.bindingId must be null when state is ${state}`;
+ }
+ if (failedAttemptState) {
+ for (const field of ['bindingId', 'principalId', 'principalName'] as const) {
+ if (p[field] !== null) {
+ return `${label}.${field} must be null when state is ${state}`;
+ }
+ }
+ if (p.expiresAt !== null) {
+ return `${label}.expiresAt must be null when state is ${state}`;
+ }
+ }
+ if (activeAttemptState && !isPositiveTimestamp(p.expiresAt)) {
+ return `${label}.expiresAt must be non-null for active attempt state ${state}`;
+ }
+ if (state === 'pending' && !isSafeHttpsUrl(p.connectUrl)) {
+ return `${label}.connectUrl must be a safe HTTPS URL when state is pending`;
+ }
+ if (state !== 'pending' && p.connectUrl !== null) {
+ return `${label}.connectUrl must be null unless state is pending`;
+ }
+ if (state === 'confirmed') {
+ for (const field of ['bindingId', 'principalId', 'scopeId'] as const) {
+ if (!isNonEmptyString(p[field])) {
+ return `${label}.${field} must be non-empty when state is confirmed`;
+ }
+ }
+ }
+ if ((state === 'revoked' || state === 'superseded') && !isNonEmptyString(p.bindingId)) {
+ return `${label}.bindingId must be non-empty when state is ${state}`;
+ }
+ if (PROVIDER_BIND_FAILURE_STATES.includes(state as never) && !isNonEmptyString(p.reason)) {
+ return `${label}.reason must be non-empty when state is ${state}`;
+ }
+ if (
+ (state === 'none' || state === 'confirmed' || state === 'revoked' || state === 'superseded') &&
+ (p.attemptId !== null || p.expiresAt !== null)
+ ) {
+ return `${label}.attemptId and expiresAt must be null when state is ${state}`;
+ }
+ if (state === 'none') {
+ for (const field of ['bindingId', 'principalId', 'principalName'] as const) {
+ if (p[field] !== null) return `${label}.${field} must be null when state is none`;
+ }
+ }
+ if (!PROVIDER_BIND_FAILURE_STATES.includes(state as never) && p.reason !== null) {
+ return `${label}.reason must be null when state is ${state}`;
+ }
+ return null;
+}
+
+function validateQueryRequest(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.queryId)) return 'query.request.queryId must be a non-empty string';
+ if (!QUERY_KINDS.includes(p.kind as never)) {
+ return `query.request.kind must be one of: ${QUERY_KINDS.join(', ')}`;
+ }
+ return null;
+}
+
+/** agents 数组(kind=models 响应体)的形状校验。 */
+function validateAgentModels(v: unknown): string | null {
+ if (!Array.isArray(v)) return 'query.response.agents must be an array';
+ for (let i = 0; i < v.length; i++) {
+ const g = v[i];
+ if (!isPlainObject(g)) return `query.response.agents[${i}] must be an object`;
+ if (!isNonEmptyString(g.agentKind)) {
+ return `query.response.agents[${i}].agentKind must be a non-empty string`;
+ }
+ if (!Array.isArray(g.models)) return `query.response.agents[${i}].models must be an array`;
+ for (let j = 0; j < g.models.length; j++) {
+ const m: unknown = g.models[j];
+ const path = `query.response.agents[${i}].models[${j}]`;
+ if (!isPlainObject(m)) return `${path} must be an object`;
+ if (!isNonEmptyString(m.id)) return `${path}.id must be a non-empty string`;
+ if (!isNonEmptyString(m.label)) return `${path}.label must be a non-empty string`;
+ if (!isStringArray(m.efforts)) return `${path}.efforts must be an array of non-empty strings`;
+ if (!isNullableString(m.defaultEffort))
+ return `${path}.defaultEffort must be a string or null`;
+ if (m.group !== undefined && !isNullableString(m.group)) {
+ return `${path}.group must be a string or null when present`;
+ }
+ }
+ // permissionModes 可选(旧版 desktop 不发); present 时校验形状
+ if (g.permissionModes !== undefined) {
+ if (!Array.isArray(g.permissionModes)) {
+ return `query.response.agents[${i}].permissionModes must be an array when present`;
+ }
+ for (let j = 0; j < g.permissionModes.length; j++) {
+ const pm: unknown = g.permissionModes[j];
+ const path = `query.response.agents[${i}].permissionModes[${j}]`;
+ if (!isPlainObject(pm)) return `${path} must be an object`;
+ if (!isNonEmptyString(pm.id)) return `${path}.id must be a non-empty string`;
+ if (!isNonEmptyString(pm.label)) return `${path}.label must be a non-empty string`;
+ }
+ }
+ }
+ return null;
+}
+
+function looksLikeAbsolutePath(v: string): boolean {
+ return v.startsWith('/') || v.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(v) || /^file:/i.test(v);
+}
+
+function validateQuerySessions(v: unknown): string | null {
+ if (!Array.isArray(v)) return 'query.response.sessions must be an array';
+ if (v.length > 20) return 'query.response.sessions must have at most 20 items';
+ const ids = new Set<string>();
+ const allowedFields = new Set(['id', 'title', 'workspace', 'lastActiveAt']);
+ for (let i = 0; i < v.length; i++) {
+ const session: unknown = v[i];
+ const path = `query.response.sessions[${i}]`;
+ if (!isPlainObject(session)) return `${path} must be an object`;
+ for (const field of Object.keys(session)) {
+ if (!allowedFields.has(field)) {
+ return `${path}.${field} is not allowed in the privacy-minimised session shape`;
+ }
+ }
+ if (!isNonEmptyString(session.id)) return `${path}.id must be a non-empty string`;
+ if (ids.has(session.id)) return `${path}.id must be unique within the response`;
+ ids.add(session.id);
+ if (!isNonEmptyString(session.title)) return `${path}.title must be a non-empty string`;
+ if (!isNonEmptyString(session.workspace)) {
+ return `${path}.workspace must be a non-empty alias`;
+ }
+ if (looksLikeAbsolutePath(session.workspace)) {
+ return `${path}.workspace must not be an absolute path`;
+ }
+ if (!isPositiveTimestamp(session.lastActiveAt)) {
+ return `${path}.lastActiveAt must be a positive integer timestamp`;
+ }
+ }
+ return null;
+}
+
+function validateQueryResponse(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.queryId)) return 'query.response.queryId must be a non-empty string';
+ if (!QUERY_KINDS.includes(p.kind as never)) {
+ return `query.response.kind must be one of: ${QUERY_KINDS.join(', ')}`;
+ }
+ if (typeof p.ok !== 'boolean') return 'query.response.ok must be a boolean';
+ if (!isNullableString(p.error)) return 'query.response.error must be a string or null';
+ if (!p.ok) {
+ if (!isNonEmptyString(p.error)) {
+ return 'query.response.error must be a non-empty string when ok is false';
+ }
+ return null; // 失败响应不要求携带清单
+ }
+ const kind = p.kind as QueryResponsePayload['kind'];
+ if (kind === 'workspaces') {
+ if (!isStringArray(p.workspaces)) {
+ return 'query.response.workspaces must be an array of non-empty strings when kind is workspaces';
+ }
+ return null;
+ }
+ if (kind === 'models') return validateAgentModels(p.agents);
+ return validateQuerySessions(p.sessions);
+}
+
+function validateTaskCancel(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) return 'task.cancel.requestId must be a non-empty string';
+ return null;
+}
+
+function validateSessionArchive(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.externalKey)) {
+ return 'session.archive.externalKey must be a non-empty string';
+ }
+ return null;
+}
+
+// ── 阶段 10(v2): 执行中交互 ─────────────────────────────────────────────────
+
+const BUTTON_STYLES = ['primary', 'danger', 'default'] as const;
+
+function validateInteractionRequest(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId))
+ return 'interaction.request.requestId must be a non-empty string';
+ if (!isNonEmptyString(p.interactionId)) {
+ return 'interaction.request.interactionId must be a non-empty string';
+ }
+ if (!isNonEmptyString(p.kind)) return 'interaction.request.kind must be a non-empty string';
+ if (!isNonEmptyString(p.title)) return 'interaction.request.title must be a non-empty string';
+ if (typeof p.body !== 'string') return 'interaction.request.body must be a string';
+ if (!Array.isArray(p.buttons) || p.buttons.length === 0) {
+ return 'interaction.request.buttons must be a non-empty array';
+ }
+ if (p.buttons.length > MAX_INTERACTION_BUTTONS) {
+ return `interaction.request.buttons must have at most ${MAX_INTERACTION_BUTTONS} items`;
+ }
+ const seen = new Set<string>();
+ for (let i = 0; i < p.buttons.length; i++) {
+ const b: unknown = p.buttons[i];
+ const path = `interaction.request.buttons[${i}]`;
+ if (!isPlainObject(b)) return `${path} must be an object`;
+ if (!isNonEmptyString(b.id)) return `${path}.id must be a non-empty string`;
+ // '|' 是 server 侧 value 复合编码的分隔符, id 带它会破坏回传解析
+ if (b.id.includes('|')) return `${path}.id must not contain '|'`;
+ if (seen.has(b.id)) return `${path}.id must be unique within the card`;
+ seen.add(b.id);
+ if (!isNonEmptyString(b.label)) return `${path}.label must be a non-empty string`;
+ if (!BUTTON_STYLES.includes(b.style as never)) {
+ return `${path}.style must be one of: ${BUTTON_STYLES.join(', ')}`;
+ }
+ }
+ return null;
+}
+
+function validateInteractionDecision(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId))
+ return 'interaction.decision.requestId must be a non-empty string';
+ if (!isNonEmptyString(p.interactionId)) {
+ return 'interaction.decision.interactionId must be a non-empty string';
+ }
+ if (!isNonEmptyString(p.buttonId))
+ return 'interaction.decision.buttonId must be a non-empty string';
+ return null;
+}
+
+function validateInteractionCancel(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId))
+ return 'interaction.cancel.requestId must be a non-empty string';
+ if (!isNonEmptyString(p.interactionId)) {
+ return 'interaction.cancel.interactionId must be a non-empty string';
+ }
+ if (typeof p.reason !== 'string') return 'interaction.cancel.reason must be a string';
+ return null;
+}
+
+// ── 阶段 12(v2): Slack 网关工具 ────────────────────────────────────────────
+
+function validateToolRequest(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) return 'tool.request.requestId must be a non-empty string';
+ // tool 是开放集合: 只校验形状, 未知工具名由 server 业务层回 UNKNOWN_TOOL
+ if (!isNonEmptyString(p.tool)) return 'tool.request.tool must be a non-empty string';
+ if (p.args !== undefined && !isPlainObject(p.args)) {
+ return 'tool.request.args must be an object when present';
+ }
+ if (p.teamId !== undefined && !isNullableString(p.teamId)) {
+ return 'tool.request.teamId must be a string or null when present';
+ }
+ return null;
+}
+
+function validateToolResponse(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.replyTo)) return 'tool.response.replyTo must be a non-empty string';
+ if (typeof p.ok !== 'boolean') return 'tool.response.ok must be a boolean';
+ // 字段联动: 失败必须给结构化错误, 成功不得携带 error(result 形状不限)
+ if (p.ok === false) {
+ if (!isPlainObject(p.error)) {
+ return 'tool.response.error must be an object when ok is false';
+ }
+ if (!isNonEmptyString(p.error.code)) {
+ return 'tool.response.error.code must be a non-empty string';
+ }
+ if (!isNonEmptyString(p.error.message)) {
+ return 'tool.response.error.message must be a non-empty string';
+ }
+ } else if (p.error !== undefined && p.error !== null) {
+ return 'tool.response.error must be absent or null when ok is true';
+ }
+ return null;
+}
+
+// ── 阶段 11(v2): 目录偏好远程读写 ──────────────────────────────────────────
+
+/** prefs.set 可部分更新的偏好字段(shape 校验共用)。 */
+const PREFS_PATCH_FIELDS = ['model', 'effort', 'agentKind', 'permissionMode'] as const;
+
+function validatePrefsGet(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) return 'prefs.get.requestId must be a non-empty string';
+ return null;
+}
+
+function validatePrefsSet(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) return 'prefs.set.requestId must be a non-empty string';
+ if (!isNonEmptyString(p.workspace)) return 'prefs.set.workspace must be a non-empty string';
+ // 部分更新语义: 缺席 = 不动, null = 显式清空; 值合法性不在协议层校验
+ for (const field of PREFS_PATCH_FIELDS) {
+ if (p[field] !== undefined && !isNullableString(p[field])) {
+ return `prefs.set.${field} must be a string or null when present`;
+ }
+ }
+ if (p.teamId !== undefined && !isNullableString(p.teamId)) {
+ return 'prefs.set.teamId must be a string or null when present';
+ }
+ return null;
+}
+
+function validatePrefsState(p: Record<string, unknown>): string | null {
+ if (!isNullableString(p.replyTo)) return 'prefs.state.replyTo must be a string or null';
+ if (typeof p.bound !== 'boolean') return 'prefs.state.bound must be a boolean';
+ if (!Array.isArray(p.prefs)) return 'prefs.state.prefs must be an array';
+ // 字段联动: 未绑定时不该有任何偏好行
+ if (!p.bound && p.prefs.length > 0) return 'prefs.state.prefs must be empty when bound is false';
+ for (let i = 0; i < p.prefs.length; i++) {
+ const entry: unknown = p.prefs[i];
+ const path = `prefs.state.prefs[${i}]`;
+ if (!isPlainObject(entry)) return `${path} must be an object`;
+ if (!isNonEmptyString(entry.workspace)) return `${path}.workspace must be a non-empty string`;
+ for (const field of PREFS_PATCH_FIELDS) {
+ // 快照条目字段必须显式给出(null 而非缺席), 与 UserPrefsRow 同形
+ if (!isNullableString(entry[field])) return `${path}.${field} must be a string or null`;
+ }
+ if (entry.teamId !== undefined && !isNullableString(entry.teamId)) {
+ return `${path}.teamId must be a string or null when present`;
+ }
+ }
+ return null;
+}
+
+function validateProviderPrefsSelector(
+ p: Record<string, unknown>,
+ label: 'provider.prefs.get' | 'provider.prefs.set' | 'provider.prefs.state',
+): string | null {
+ const providerError = validateProvider(p.provider, `${label}.provider`);
+ if (providerError) return providerError;
+ if (!isNullableNonEmptyString(p.bindingId)) {
+ return `${label}.bindingId must be a non-empty string or null`;
+ }
+ if (!isNullableNonEmptyString(p.scopeId)) {
+ return `${label}.scopeId must be a non-empty string or null`;
+ }
+ if ((p.bindingId === null) === (p.scopeId === null)) {
+ return `${label} must select exactly one of bindingId or scopeId`;
+ }
+ return null;
+}
+
+function validateProviderPrefsGet(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) {
+ return 'provider.prefs.get.requestId must be a non-empty string';
+ }
+ return validateProviderPrefsSelector(p, 'provider.prefs.get');
+}
+
+function validateProviderPrefsSet(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) {
+ return 'provider.prefs.set.requestId must be a non-empty string';
+ }
+ const selectorError = validateProviderPrefsSelector(p, 'provider.prefs.set');
+ if (selectorError) return selectorError;
+ if (!isNonEmptyString(p.workspace)) {
+ return 'provider.prefs.set.workspace must be a non-empty string';
+ }
+ if (looksLikeAbsolutePath(p.workspace)) {
+ return 'provider.prefs.set.workspace must not be an absolute path';
+ }
+ for (const field of PREFS_PATCH_FIELDS) {
+ if (p[field] !== undefined && !isNullableString(p[field])) {
+ return `provider.prefs.set.${field} must be a string or null when present`;
+ }
+ }
+ return null;
+}
+
+function validateProviderPrefsState(p: Record<string, unknown>): string | null {
+ const selectorError = validateProviderPrefsSelector(p, 'provider.prefs.state');
+ if (selectorError) return selectorError;
+ if (!isNullableNonEmptyString(p.replyTo)) {
+ return 'provider.prefs.state.replyTo must be a non-empty string or null';
+ }
+ if (typeof p.bound !== 'boolean') return 'provider.prefs.state.bound must be a boolean';
+ if (!Array.isArray(p.prefs)) return 'provider.prefs.state.prefs must be an array';
+ if (!p.bound && p.prefs.length > 0) {
+ return 'provider.prefs.state.prefs must be empty when bound is false';
+ }
+ for (let i = 0; i < p.prefs.length; i++) {
+ const entry: unknown = p.prefs[i];
+ const path = `provider.prefs.state.prefs[${i}]`;
+ if (!isPlainObject(entry)) return `${path} must be an object`;
+ if (!isNonEmptyString(entry.workspace)) return `${path}.workspace must be a non-empty string`;
+ if (looksLikeAbsolutePath(entry.workspace)) {
+ return `${path}.workspace must not be an absolute path`;
+ }
+ for (const field of PREFS_PATCH_FIELDS) {
+ if (!isNullableString(entry[field])) return `${path}.${field} must be a string or null`;
+ }
+ if (entry.teamId !== undefined) {
+ return `${path}.teamId is Slack-specific and is not allowed in provider prefs`;
+ }
+ }
+ return null;
+}
+
+// ── Provider-neutral behavior (Telegram, append-only v1) ───────────────────
+// 见文件头第 19 条。groupActivation 不另设条目上限:每次合法 set 都必须能在
+// 后续 state 全量快照中表达;整帧仍受 HOOK_MAX_FRAME_CHARS 的统一上限保护。
+
+/**
+ * provider.behavior.* 选择器: 与 provider.prefs.* 不同, 只认 bindingId
+ * (非空必填), 不支持 scopeId —— 行为配置在绑定成立前没有意义。
+ */
+function validateProviderBehaviorSelector(
+ p: Record<string, unknown>,
+ label: 'provider.behavior.get' | 'provider.behavior.set' | 'provider.behavior.state',
+): string | null {
+ const providerError = validateProviderBehaviorProvider(p.provider, `${label}.provider`);
+ if (providerError) return providerError;
+ if (!isNonEmptyString(p.bindingId)) {
+ return `${label}.bindingId must be a non-empty string`;
+ }
+ return null;
+}
+
+function validateProviderBehaviorGet(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) {
+ return 'provider.behavior.get.requestId must be a non-empty string';
+ }
+ return validateProviderBehaviorSelector(p, 'provider.behavior.get');
+}
+
+/**
+ * groupActivation patch/clear 的形状校验(set 与 state 共用大部分逻辑不同,
+ * 这里只做 set 的单条 patch 校验; state 的 map 校验在 validateProviderBehaviorState)。
+ */
+function validateGroupActivationPatch(v: unknown): string | null {
+ if (!isPlainObject(v)) {
+ return 'provider.behavior.set.groupActivation must be an object when present';
+ }
+ if (!isTelegramGroupChatId(v.chatId)) {
+ return 'provider.behavior.set.groupActivation.chatId must be a canonical negative Telegram group chat id within the 52-bit Bot API range';
+ }
+ if (v.value !== null && v.value !== TELEGRAM_GROUP_ACTIVATION_ALWAYS) {
+ return `provider.behavior.set.groupActivation.value must be '${TELEGRAM_GROUP_ACTIVATION_ALWAYS}' or null`;
+ }
+ return null;
+}
+
+function validateProviderBehaviorSet(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.requestId)) {
+ return 'provider.behavior.set.requestId must be a non-empty string';
+ }
+ const selectorError = validateProviderBehaviorSelector(p, 'provider.behavior.set');
+ if (selectorError) return selectorError;
+
+ const emojiError = validateOptionalNullableEnum(
+ p.emojiReactions,
+ TELEGRAM_EMOJI_REACTIONS,
+ 'provider.behavior.set.emojiReactions',
+ );
+ if (emojiError) return emojiError;
+ const dmError = validateOptionalNullableEnum(
+ p.replyQuoteDm,
+ TELEGRAM_REPLY_QUOTE_DM,
+ 'provider.behavior.set.replyQuoteDm',
+ );
+ if (dmError) return dmError;
+ const groupQuoteError = validateOptionalNullableEnum(
+ p.replyQuoteGroup,
+ TELEGRAM_REPLY_QUOTE_GROUP,
+ 'provider.behavior.set.replyQuoteGroup',
+ );
+ if (groupQuoteError) return groupQuoteError;
+
+ let hasGroupActivationPatch = false;
+ if (p.groupActivation !== undefined) {
+ const patchError = validateGroupActivationPatch(p.groupActivation);
+ if (patchError) return patchError;
+ hasGroupActivationPatch = true;
+ }
+
+ // 至少一个实际 patch: 空 set 没有可观察反馈, 直接拒收比静默 no-op 更安全
+ const hasBehaviorPatch =
+ p.emojiReactions !== undefined ||
+ p.replyQuoteDm !== undefined ||
+ p.replyQuoteGroup !== undefined;
+ if (!hasBehaviorPatch && !hasGroupActivationPatch) {
+ return 'provider.behavior.set must include at least one behavior field or a groupActivation patch';
+ }
+ return null;
+}
+
+function validateProviderBehaviorState(p: Record<string, unknown>): string | null {
+ const selectorError = validateProviderBehaviorSelector(p, 'provider.behavior.state');
+ if (selectorError) return selectorError;
+ if (!isNullableNonEmptyString(p.replyTo)) {
+ return 'provider.behavior.state.replyTo must be a non-empty string or null';
+ }
+ if (typeof p.bound !== 'boolean') return 'provider.behavior.state.bound must be a boolean';
+
+ if (!TELEGRAM_EMOJI_REACTIONS.includes(p.emojiReactions as never)) {
+ return `provider.behavior.state.emojiReactions must be one of: ${TELEGRAM_EMOJI_REACTIONS.join(', ')}`;
+ }
+ if (!TELEGRAM_REPLY_QUOTE_DM.includes(p.replyQuoteDm as never)) {
+ return `provider.behavior.state.replyQuoteDm must be one of: ${TELEGRAM_REPLY_QUOTE_DM.join(', ')}`;
+ }
+ if (!TELEGRAM_REPLY_QUOTE_GROUP.includes(p.replyQuoteGroup as never)) {
+ return `provider.behavior.state.replyQuoteGroup must be one of: ${TELEGRAM_REPLY_QUOTE_GROUP.join(', ')}`;
+ }
+
+ if (!isPlainObject(p.groupActivation)) {
+ return 'provider.behavior.state.groupActivation must be an object';
+ }
+ let hasGroupActivation = false;
+ // Do not use Object.entries/Object.keys here: a valid state may contain a
+ // large accumulated map, and materializing a second tuple/key array can
+ // roughly double peak memory after JSON.parse. The frame-size guard remains
+ // the cardinality bound; this pass adds only constant memory.
+ for (const chatId in p.groupActivation) {
+ if (!Object.prototype.hasOwnProperty.call(p.groupActivation, chatId)) continue;
+ hasGroupActivation = true;
+ const value = p.groupActivation[chatId];
+ if (!isTelegramGroupChatId(chatId)) {
+ return 'provider.behavior.state.groupActivation key must be a canonical negative Telegram group chat id within the 52-bit Bot API range';
+ }
+ if (value !== TELEGRAM_GROUP_ACTIVATION_ALWAYS) {
+ return `provider.behavior.state.groupActivation[${chatId}] must be '${TELEGRAM_GROUP_ACTIVATION_ALWAYS}'`;
+ }
+ }
+
+ // 字段联动(parse 强制): 未绑定没有主体持有 per-chat 覆盖, 必须收敛为默认快照
+ if (!p.bound) {
+ if (
+ p.emojiReactions !== DEFAULT_TELEGRAM_BEHAVIOR.emojiReactions ||
+ p.replyQuoteDm !== DEFAULT_TELEGRAM_BEHAVIOR.replyQuoteDm ||
+ p.replyQuoteGroup !== DEFAULT_TELEGRAM_BEHAVIOR.replyQuoteGroup
+ ) {
+ return 'provider.behavior.state must report the default behavior when bound is false';
+ }
+ if (hasGroupActivation) {
+ return 'provider.behavior.state.groupActivation must be empty when bound is false';
+ }
+ }
+ return null;
+}
+
+// ── 阶段 14: 群消息中继 ──────────────────────────────────────────────────────
+
+const GROUP_MESSAGE_TEXT_MAX = 8_192;
+const GROUP_MESSAGE_FILE_NAMES_MAX = 20;
+const GROUP_MESSAGE_FILE_NAME_CHARS_MAX = 256;
+/**
+ * author.id / author.username 按 Telegram 当前实际契约收紧(见 types.ts
+ * GroupMessageAuthor 的文档注释): id 是 Telegram 数字 user id 的规范十进制
+ * 正整数字符串(无前导零,在 Bot API 52-bit 范围内), username 是 Telegram @handle(仅
+ * [A-Za-z0-9_], 1~32 位)。
+ */
+const GROUP_MESSAGE_AUTHOR_ID_PATTERN = /^[1-9][0-9]*$/;
+const GROUP_MESSAGE_AUTHOR_USERNAME_PATTERN = /^[A-Za-z0-9_]{1,32}$/;
+
+function isGroupMessageAuthorId(v: unknown): v is string {
+ return (
+ typeof v === 'string' && GROUP_MESSAGE_AUTHOR_ID_PATTERN.test(v) && BigInt(v) <= TELEGRAM_ID_MAX
+ );
+}
+
+function isGroupMessageAuthorUsername(v: unknown): v is string {
+ return typeof v === 'string' && GROUP_MESSAGE_AUTHOR_USERNAME_PATTERN.test(v);
+}
+
+function validateGroupMessage(p: Record<string, unknown>): string | null {
+ if (!isNonEmptyString(p.provider)) return 'group.message.provider must be a non-empty string';
+ if (p.recipient !== undefined) {
+ if (!isPlainObject(p.recipient)) {
+ return 'group.message.recipient must be an object when present';
+ }
+ if (!isNonEmptyString(p.recipient.bindingId)) {
+ return 'group.message.recipient.bindingId must be a non-empty string';
+ }
+ if (!isNonEmptyString(p.recipient.principalId)) {
+ return 'group.message.recipient.principalId must be a non-empty string';
+ }
+ }
+ if (!isNonEmptyString(p.chatId)) return 'group.message.chatId must be a non-empty string';
+ if (!isNullableNonEmptyString(p.threadId)) {
+ return 'group.message.threadId must be a non-empty string or null';
+ }
+ if (!isNonEmptyString(p.messageId)) return 'group.message.messageId must be a non-empty string';
+ if (!isNullableNonEmptyString(p.chatName)) {
+ return 'group.message.chatName must be a non-empty string or null';
+ }
+ if (!isPlainObject(p.author) || !isNonEmptyString(p.author.name)) {
+ return 'group.message.author.name must be a non-empty string';
+ }
+ if (p.author.isBot !== undefined && typeof p.author.isBot !== 'boolean') {
+ return 'group.message.author.isBot must be a boolean';
+ }
+ // id / username 可选(旧生产端不发时省略), present 时按 Telegram 契约校验
+ if (p.author.id !== undefined && !isGroupMessageAuthorId(p.author.id)) {
+ return 'group.message.author.id must be a canonical positive Telegram user id within the 52-bit Bot API range';
+ }
+ if (p.author.username !== undefined && !isGroupMessageAuthorUsername(p.author.username)) {
+ return 'group.message.author.username must match [A-Za-z0-9_]{1,32}';
+ }
+ if (typeof p.text !== 'string' || p.text.length > GROUP_MESSAGE_TEXT_MAX) {
+ return `group.message.text must be a string of at most ${GROUP_MESSAGE_TEXT_MAX} chars`;
+ }
+ if (p.fileNames !== undefined) {
+ if (
+ !isStringArray(p.fileNames) ||
+ p.fileNames.length > GROUP_MESSAGE_FILE_NAMES_MAX ||
+ p.fileNames.some((name) => name.length > GROUP_MESSAGE_FILE_NAME_CHARS_MAX)
+ ) {
+ return `group.message.fileNames must be at most ${GROUP_MESSAGE_FILE_NAMES_MAX} non-empty strings of at most ${GROUP_MESSAGE_FILE_NAME_CHARS_MAX} chars`;
+ }
+ }
+ if (
+ p.text.length === 0 &&
+ (p.fileNames === undefined || (p.fileNames as string[]).length === 0)
+ ) {
+ return 'group.message must carry text or fileNames';
+ }
+ if (!isPositiveTimestamp(p.sentAt)) {
+ return 'group.message.sentAt must be a positive unix-ms timestamp';
+ }
+ return null;
+}
+
+const PAYLOAD_VALIDATORS: Record<HookMessageType, (p: Record<string, unknown>) => string | null> = {
+ hello: validateHello,
+ welcome: validateWelcome,
+ ping: (p) => validateEmpty(p, 'ping'),
+ pong: (p) => validateEmpty(p, 'pong'),
+ 'task.dispatch': validateDispatch,
+ 'task.ack': validateAck,
+ 'turn.end': validateTurnEnd,
+ 'turn.delivery': validateTurnDelivery,
+ 'turn.progress': validateTurnProgress,
+ 'turn.reopen': validateTurnReopen,
+ 'msg.op': validateMessageOp,
+ 'msg.op.result': validateMessageOpResult,
+ 'bind.start': validateBindStart,
+ 'bind.update': validateBindUpdate,
+ 'bind.revoke': validateBindRevoke,
+ 'bind.state': validateBindState,
+ 'provider.bind.start': validateProviderBindStart,
+ 'provider.bind.cancel': validateProviderBindCancel,
+ 'provider.bind.revoke': validateProviderBindRevoke,
+ 'provider.bind.update': (p) => validateProviderBindStatus(p, 'provider.bind.update'),
+ 'provider.bind.state': (p) => validateProviderBindStatus(p, 'provider.bind.state'),
+ 'query.request': validateQueryRequest,
+ 'query.response': validateQueryResponse,
+ 'task.cancel': validateTaskCancel,
+ 'session.archive': validateSessionArchive,
+ 'interaction.request': validateInteractionRequest,
+ 'interaction.decision': validateInteractionDecision,
+ 'interaction.cancel': validateInteractionCancel,
+ 'prefs.get': validatePrefsGet,
+ 'prefs.set': validatePrefsSet,
+ 'prefs.state': validatePrefsState,
+ 'provider.prefs.get': validateProviderPrefsGet,
+ 'provider.prefs.set': validateProviderPrefsSet,
+ 'provider.prefs.state': validateProviderPrefsState,
+ 'tool.request': validateToolRequest,
+ 'tool.response': validateToolResponse,
+ 'group.message': validateGroupMessage,
+ 'lifecycle.preference': validateLifecyclePreference,
+ 'provider.behavior.get': validateProviderBehaviorGet,
+ 'provider.behavior.set': validateProviderBehaviorSet,
+ 'provider.behavior.state': validateProviderBehaviorState,
+};
+
+/**
+ * 解析并校验一帧协议消息。
+ * 接受 WS 原始文本帧(string)或已 JSON.parse 的对象(unknown); 通过后返回
+ * 判别联合 HookMessage, 调用方按 `message.type` 分发即可获得完整类型收窄。
+ */
+export function parseHookMessage(raw: unknown): HookParseResult {
+ let data: unknown = raw;
+ if (typeof raw === 'string') {
+ if (raw.length > HOOK_MAX_FRAME_CHARS) {
+ return fail(`frame too large: ${raw.length} > ${HOOK_MAX_FRAME_CHARS} chars`);
+ }
+ try {
+ data = JSON.parse(raw);
+ } catch {
+ return fail('frame is not valid JSON');
+ }
+ }
+
+ if (!isPlainObject(data)) return fail('envelope must be an object');
+ if (data.v !== HOOK_PROTOCOL_VERSION) {
+ return fail(
+ `unsupported protocol version: ${String(data.v)} (expected ${HOOK_PROTOCOL_VERSION})`,
+ );
+ }
+ if (!HOOK_MESSAGE_TYPES.includes(data.type as never)) {
+ return fail(`unknown message type: ${String(data.type)}`);
+ }
+ if (!isNonEmptyString(data.id)) return fail('envelope.id must be a non-empty string');
+ if (typeof data.ts !== 'number' || !Number.isFinite(data.ts)) {
+ return fail('envelope.ts must be a finite number');
+ }
+ if (!isPlainObject(data.payload)) return fail('envelope.payload must be an object');
+
+ const type = data.type as HookMessageType;
+ const validator = Object.hasOwn(PAYLOAD_VALIDATORS, type) ? PAYLOAD_VALIDATORS[type] : undefined;
+ if (!validator) return fail(`no validator for type: ${type}`);
+ const payloadError = validator(data.payload);
+ if (payloadError) return fail(payloadError);
+
+ return { ok: true, message: data as unknown as HookMessage };
+}
+
+/** 类型收窄辅助: 判断字符串是否为 v1 已知消息类型。 */
+export function isHookMessageType(v: string): v is HookMessageType {
+ return HOOK_MESSAGE_TYPES.includes(v as never);
+}
+
+// 类型层自检: payload 校验器覆盖的字段与类型定义保持同步时, 这两个别名不会报错
+type _AssertDispatchShape = keyof TaskDispatchPayload;
+type _AssertTurnEndShape = keyof TurnEndPayload;
diff --git a/packages/slack-hook-protocol/src/types.ts b/packages/slack-hook-protocol/src/types.ts
new file mode 100644
index 0000000000..2a689b01da
--- /dev/null
+++ b/packages/slack-hook-protocol/src/types.ts
@@ -0,0 +1,1710 @@
+/**
+ * slack-hook-protocol/types.ts
+ * ---------------------------------------------------------------------------
+ * hook server <-> desktop 双工任务协议 v1 的全部类型定义。
+ *
+ * 协议模型(四幕):
+ * 1. 连接自报家门: hello(desktop -> server, 声明工作区别名) / welcome / ping / pong
+ * 2. 派活: task.dispatch(server -> desktop) -> task.ack(立即三态应答)
+ * 3. 干活: 无消息 —— 铁律「同 externalKey 同 session」由 desktop 侧保证
+ * 4. 交差: turn.end(desktop -> server, 结果回传)
+ *
+ * 关键约定:
+ * - externalKey 对协议是不透明字符串, 由 hook server 的 provider 生成
+ * (格式约定 `<providerId>:...`), desktop 只拿它查 session 映射并原样回传。
+ * - workspace 是别名(alias), 本地绝对路径只存在于 desktop, 永不过网线。
+ * - sessionId 仅「接管已有桌面会话」时由 server 显式指定; 普通流程不填,
+ * ack / turn.end 中回传仅作记录与调试, 不参与路由。
+ * - 可靠性: requestId 幂等(重投不重跑, 只回放上次 ack); 断线重连后
+ * server 重投未 ack 任务, desktop 补发未送达的 turn.end。
+ *
+ * v2 增量(版本号不变 —— type 为开放集合, 老端收到未知类型丢帧不断连):
+ * 5. 绑定: bind.start(desktop 发起) / bind.update(server 推状态) / bind.revoke
+ * —— 中心部署下「Slack 用户 ↔ 设备」的建立与解除。阶段 4 起改走
+ * Sign in with Slack(OIDC): desktop 发空 bind.start, server 签发授权
+ * 链接经 bind.update(state=pending, authorizeUrl)回推, 用户在系统浏览器
+ * 完成 Slack 授权后 server 回调建链, 再推 confirmed。协议只承载 desktop
+ * 侧的发起与状态同步, 身份确认在 server 与 Slack 之间完成。
+ * 6. 问答: query.request(server -> desktop) / query.response —— /bind /model
+ * /effort 等指令触发时实时拉取工作区 / 模型清单, 不用连接期快照。
+ * 7. 取消: task.cancel(server -> desktop) —— /stop 中断在跑任务,
+ * desktop 以 turn.end(status=cancelled) 收口。
+ * 8. 归档: session.archive(server -> desktop) —— 私聊 /new 换代后通知
+ * desktop 归档旧代会话(按 externalKey 查绑定), 列表不再显示; 无绑定 /
+ * 会话不存在时静默忽略(幂等)。
+ *
+ * 9. 进度: turn.progress(desktop -> server) —— turn 执行中的渲染快照。
+ * 历史: 初版只发裸累积文本, 体验不佳一度下线; 现已复活, desktop 侧
+ * 合成「过程区时间线 + 部分正文」的完整快照(节流), server 侧以
+ * 占位消息 + chat.update 原地刷新呈现。旧版 desktop 仍发裸文本快照,
+ * 新 server 同样渲染(向后兼容); 旧 server 收到新帧静默丢弃(无害)。
+ *
+ * 10. 交互: interaction.request(desktop -> server) / interaction.decision
+ * (server -> desktop) / interaction.cancel(desktop -> server) ——
+ * turn 执行中 agent 发起的用户交互(模型主动提问 AskUserQuestion /
+ * 计划审阅 plan_review)以按钮卡片形式转发到 Slack thread。设计原则:
+ * **决策语义全部留在 desktop**(它持有 maker-core 的原始
+ * InteractionRequest 与按钮->决策映射), server 是"哑渲染器"——
+ * 收到 request 渲染卡片, 按钮按压只回传 buttonId; desktop 侧对每个
+ * 交互设超时, 超时/收口时按安全默认自决并发 cancel 让 server 改写
+ * 卡片。旧 server 收到 request 丢帧不断连 -> desktop 超时默认继续,
+ * 任务不会卡死(向后兼容)。权限审批(permission)已纳入本通道: server
+ * 可经 dispatch options.permissionMode 为新建会话指定权限档(见
+ * TaskDispatchOptions), 非 bypass 档下 agent 的权限请求同样以按钮卡
+ * 转发(允许一次 / 本会话总是允许 / 拒绝), 超时安全默认为拒绝。
+ *
+ * 11. 偏好: prefs.get / prefs.set(desktop -> server) / prefs.state
+ * (server -> desktop) —— server 侧 user_prefs(按 (Slack 用户, 工作目录)
+ * 的 agent/model/effort/permission 偏好, /model 卡的数据正本)的远程
+ * 读写通道: desktop 设置页是同一份数据的编辑器。prefs.state 是全量
+ * 快照, 既作为 get/set 的应答(replyTo 回显请求 id), 也在 /model 卡
+ * 写入后主动推送(replyTo null; 设备离线静默丢, desktop 重连自拉)。
+ * 旧 server 收到 prefs.get 丢帧不断连 -> desktop 侧超时降级为
+ * "服务器版本过旧"提示; 旧 desktop 收到主动 prefs.state 同样丢帧无害。
+ *
+ * 12. 工具: tool.request(desktop -> server) / tool.response(server ->
+ * desktop) —— desktop 会话内 agent 调用 server 侧 Slack 网关工具
+ * (server 以绑定用户托管的 user token 调 Slack 官方 MCP / Web API)。
+ * 方向与 query.* 相反: desktop 是请求方(pending map + 超时在 desktop
+ * 侧), server 收到即执行并以 tool.response(replyTo 回显 requestId)
+ * 应答。tool 名是开放集合(server 不认识回 UNKNOWN_TOOL), 错误一律
+ * 结构化 {code, message} —— desktop 按 code 分支, 不解析文案(规则 9)。
+ * 能力协商: 支持本帧族的 server 在 welcome.features 里带
+ * HOOK_FEATURE_SLACK_TOOLS; 旧 server 收到 tool.request 丢帧不断连,
+ * desktop 侧靠 feature 缺席短路 + 超时兜底(SERVER_TOO_OLD)。
+ *
+ * 13. 多 workspace 绑定(multi-team): 一台设备可同时持有多个
+ * (teamId, slackUserId) 绑定 —— 每个 Slack workspace(team)一条, 同
+ * team 内仍一设备一身份。能力协商双向: desktop 在 hello.features 带
+ * HOOK_FEATURE_MULTI_TEAM 声明自己会消费多绑定帧, server 在
+ * welcome.features 带同名标识声明支持; 任一侧缺席则整体回落单绑定
+ * 行为(server 对旧 desktop 保持"跨 team 顶替"旧语义, 新 desktop 对
+ * 旧 server 收起添加入口)。增量帧面:
+ * - bind.state(server -> desktop): 绑定全量快照(权威列表), 连接
+ * 建立与任何绑定变化(新增/解除/被顶)后推送; 旧 desktop 不认识
+ * 本类型, parse 拒收丢帧不断连。
+ * - bind.update 加可选 teamId: 事件帧按 team 定位(confirmed /
+ * revoked); 授权流早期(pending)团队未知, teamId 为 null。
+ * - bind.start 加可选 teamId: 给指定 team 重新授权时 pin 授权页;
+ * 缺省 = 用户在 Slack 授权页自选(可绑任意新 team)。
+ * - bind.revoke 从空对象放宽为 { teamId?: string|null }: 带 team
+ * = 只解绑该 team; 空/缺省 = 解绑本设备全部(兼容老 desktop)。
+ * 旧 server 对带 teamId 的帧 parse 拒收, 故 desktop 仅在 server
+ * 声明 multi-team 后才发带 team 的形态。
+ * - prefs.set / prefs.state 条目 / tool.request 加可选 teamId:
+ * 多绑定下偏好与网关工具的 team 归属消歧; 缺省语义 = 设备唯一
+ * 绑定(多绑定时 server 拒绝猜测, 结构化报错)。
+ * - TaskSource 加 teamId / teamName: desktop 侧会话记住来源
+ * workspace(标题展示 + 工具调用默认 team)。
+ *
+ * 15. 生命周期通知偏好: hello.lifecycleAnnouncement 在每次建连时同步
+ * 当前有效值,lifecycle.preference 在设置页切换时即时更新。server
+ * 只有声明 HOOK_FEATURE_LIFECYCLE_ANNOUNCEMENT 后 desktop 才发送
+ * 即时更新帧;旧 server 忽略 hello 新字段,保持既有通知行为。
+ *
+ * 19. Telegram 行为配置: provider.behavior.get / provider.behavior.set
+ * (desktop -> server) / provider.behavior.state(server -> desktop) ——
+ * 当前仅 provider='telegram'。选择器**只认 bindingId**(不是
+ * provider.prefs.* 的 bindingId/scopeId 二选一): 行为配置(emoji 回应 /
+ * 回复引用 / 群免 @ 白名单)在绑定成立前没有意义, 收窄为单选择器把
+ * "谁能读写它"的边界钉死在已确认的绑定上。set 的三个全局字段与
+ * groupActivation 共用同一套 patch 三态: 缺省(undefined)=不动、
+ * 显式枚举值 = 写入 override(哪怕这个值刚好等于当前版本默认值也照写
+ * 不落空 —— 用户的显式选择不能因为协议以后调整默认值而被悄悄改写)、
+ * 显式 null = 清除 override、回落到当时版本的默认值。二者可同帧组合,
+ * 但至少要有一项实际改动(null 也算一次真实改动)—— 空 patch 直接拒收
+ * (不同于 prefs.set, 这里没有"无副作用地静默 no-op"的容错空间)。
+ * state 携带的**始终是已解析的非空有效值**(不是原始 patch, 不会是
+ * null), 且 groupActivation 只列出偏离默认值('mention')的 chatId;
+ * bound=false 时 parse 强制整帧收敛为默认行为 + 空白名单(未绑定没有
+ * 主体持有 per-chat 覆盖)。三个全局字段的默认值(DEFAULT_TELEGRAM_
+ * BEHAVIOR)与个人版桌面客户端出厂行为对齐: emojiReactions='minimal'、
+ * replyQuoteDm='off'、replyQuoteGroup='first'。见 Provider-neutral
+ * behavior 小节。
+ *
+ * 编号说明: 本文件头的条目号与 docs/slack-hook-protocol.md §1 的消息目录
+ * 对齐(那份是正本)。中间的跳号是因为部分帧只在下方各自的类型旁说明 ——
+ * 14 多 provider(provider.bind.* / provider.prefs.*, 见 Provider-neutral
+ * 小节)、15 最近会话(QUERY_KINDS)、16 群消息中继(GroupMessagePayload)、
+ * 17 上下线通知偏好(LifecyclePreferencePayload, 即上面那条)、19 见上。
+ *
+ * 18. 续跑: turn.reopen(desktop -> server) —— 一个已经以 turn.end 收口的
+ * 任务, 在桌面端被用户续跑了, 把后续进展重新接回渠道里那条消息。
+ *
+ * 要解决的问题: turn.end(status=error)之后, 用户常在桌面端点错误横幅上
+ * 的「重试」。那会在**同一个会话**里起一个新 turn(桌面端发的是一条隐藏
+ * 续跑指令), 任务确实继续跑了, 但渠道那条消息永远停在失败上 —— 因为
+ * turn.progress / turn.end 都以 requestId 为键, 那一轮已经收口, 协议里
+ * 也没有任何"会话级"通道能让 desktop 主动往那条消息写东西。用户看到的
+ * 就是"点了重试也没反应"。
+ *
+ * 形态刻意用**新 requestId + reopenOf**, 而不是复用原 requestId:
+ * - server 侧幂等语义不用改(原 requestId 的 turn.end 仍是一次性的),
+ * 只需把 reopenOf 指向的那条消息的位置(channel + ts)登记给新
+ * requestId, 之后的 turn.progress / turn.end 走既有代码路径;
+ * - task.cancel 能精确命中续跑轮(它带的是新 requestId);
+ * - 一次续跑再失败、再被续跑时天然形成链条, 每环都有自己的 id。
+ *
+ * 路由面**只含** turn.progress / turn.end / task.cancel, 刻意不含
+ * interaction.*: 续跑是用户在桌面端点出来的, 人就在桌面前, 那一轮里 agent
+ * 的提问 / 计划审阅 / 权限审批由桌面本地交互面直接处理, 不绕回渠道。
+ *
+ * server 侧约定:
+ * - 认不出 reopenOf(映射已过期 / 消息已删)时**静默忽略**整条帧, 并对
+ * 随后到达的同 requestId 的 turn.progress / turn.end 一并忽略 ——
+ * 回流失败只是回到"消息停在失败上"的现状, 不是错误, 不要报错刷屏;
+ * 更一般地: 对**从未登记过**的 requestId 的 turn.progress / turn.end
+ * 一律静默忽略, 不报错也不新建消息;
+ * - 认得出时把那条消息改回进行中态, 后续 progress 原地刷新、turn.end
+ * 定稿。渠道里不新增消息(用户抱怨的正是那条消息不动);
+ * - 本帧必须幂等: 同一 (requestId, reopenOf) 重复登记同一个位置, 无副作用
+ * (断线重投时 desktop 可能重复发送);
+ * - 不需要为续跑 requestId 关联 interaction.* —— 那些帧不会带着它到来;
+ * - 收到一个已经绑定到别的任务的 requestId 时拒绝登记, 并把该 requestId
+ * 整体隔离(后续 turn.progress / turn.end 一并忽略, 不得落到原有路由上);
+ * - **连接断开时必须收口该连接上所有"已 reopen 但没收到 turn.end"的消息**
+ * (恢复原终态或改写成「续跑中断」), 否则它们会永久停在假的"进行中"上,
+ * 比本能力上线前更糟; 收口是权威的, desktop 不会在重连后补回该轮结果。
+ * 但收口落笔时必须校验该消息仍归"被断开的那个连接 + 那次 reopen"所有,
+ * 迟到的收口不得盖掉更新的一次 reopen 或已到达的新终态。
+ * desktop 侧约定:
+ * - 只在 server 于 welcome.features 宣告 HOOK_FEATURE_TURN_REOPEN 时
+ * 才发本帧(旧 server 会 parse 拒收丢帧, 虽不断连但没有意义);
+ * - 只有"用户在桌面端显式续跑"才触发 —— 桌面端在同一会话里问的其它
+ * 问题不回流, 否则渠道消息会被无关内容改写;
+ * - 记账只在进程内(app 重启后原 requestId 已随进程消失), 有 TTL;
+ * - 本帧必须排在该 turn 的任何 turn.progress / turn.end 之前, 包括"首个
+ * 观察到的事件本身就是终态"的情形(否则先发的 turn.end 被当未知 id 丢弃,
+ * 随后的 reopen 又把消息改成进行中, 就再没有终态帧能收口);
+ * - 续跑轮的 turn.progress / turn.end 一律直发, 不缓存也不在重连后补发 ——
+ * 刻意偏离"断线重连 desktop 补发未送达 turn.end"的通用约定, 因为那条
+ * 消息在断连瞬间已被 server 收口, 迟到的 turn.end 只会撞上被解绑的
+ * requestId 而丢弃, 反把"其实成功"显示成"续跑中断"。相应地, turn.end
+ * 没发出去时不得再把这条消息线登记成可续跑。
+ *
+ * requestId 命名空间: 续跑 requestId 由 desktop 生成、普通任务由 server
+ * 生成, 却是同一张路由表的键(parse 只能校验非空且不等于 reopenOf), 所以
+ * desktop 必须用全局抗碰撞标识(UUID v4 或同等强度), server 以上面那条
+ * "拒绝并隔离已绑定 requestId"兜底。
+ *
+ * 已声明接受的降级: 连接在续跑轮跑完前断开时结果不回流 —— 断在装映射前是
+ * 消息保持原失败态(与本能力上线前一致), 断在装映射后是 server 收口成原终态
+ * 或「续跑中断」。两种都可在渠道重发。刻意不为此加 ack 往返: 回流是增强而非
+ * 关键路径。注意"失败方向安全"依赖上面那条断连收口 —— 没有它, 可见状态会从
+ * "停在失败"退化成"永远进行中", 反而比不做回流更糟。
+ */
+
+/** 当前协议版本。信封 `v` 不等于本值的消息直接拒收。 */
+export const HOOK_PROTOCOL_VERSION = 1;
+
+/**
+ * 单帧(JSON 序列化后)最大字符数。parse 对超长原始帧直接拒收 —— 纯粹是
+ * 防 OOM 的粗防御, 不是业务限额。task.dispatch 可携带 base64 图片附件, 故取
+ * 一个能容纳"几张聊天截图"的宽上限(48 MiB); 附件的精细限额(单图大小 /
+ * 张数)由生产源头(provider)负责, 不依赖本值。非附件帧远小于此。
+ */
+export const HOOK_MAX_FRAME_CHARS = 48 * 1024 * 1024;
+
+/** 消息类型全集(v1 七种 + v2 增量帧)。 */
+export const HOOK_MESSAGE_TYPES = [
+ 'hello',
+ 'welcome',
+ 'ping',
+ 'pong',
+ 'task.dispatch',
+ 'task.ack',
+ 'turn.end',
+ 'turn.delivery',
+ 'turn.progress',
+ 'turn.reopen',
+ 'msg.op',
+ 'msg.op.result',
+ 'bind.start',
+ 'bind.update',
+ 'bind.revoke',
+ 'provider.bind.start',
+ 'provider.bind.cancel',
+ 'provider.bind.revoke',
+ 'provider.bind.update',
+ 'provider.bind.state',
+ 'query.request',
+ 'query.response',
+ 'task.cancel',
+ 'session.archive',
+ 'interaction.request',
+ 'interaction.decision',
+ 'interaction.cancel',
+ 'prefs.get',
+ 'prefs.set',
+ 'prefs.state',
+ 'provider.prefs.get',
+ 'provider.prefs.set',
+ 'provider.prefs.state',
+ 'tool.request',
+ 'tool.response',
+ 'bind.state',
+ 'group.message',
+ 'lifecycle.preference',
+ 'provider.behavior.get',
+ 'provider.behavior.set',
+ 'provider.behavior.state',
+] as const;
+
+export type HookMessageType = (typeof HOOK_MESSAGE_TYPES)[number];
+
+/**
+ * 消息信封 —— 线上跑的每一帧都是这个形状。
+ * `id` 是发送方生成的帧唯一标识(日志/去重用); 业务关联一律走 payload 里的
+ * requestId, 不用 `id`。`ts` 是发送方时钟(unix ms), 仅供诊断, 不参与逻辑。
+ */
+export interface HookEnvelope<TType extends HookMessageType, TPayload> {
+ v: number;
+ type: TType;
+ id: string;
+ ts: number;
+ payload: TPayload;
+}
+
+// ── 阶段 1: 连接与身份 ───────────────────────────────────────────────────────
+
+/**
+ * hello(desktop -> server): 建连后第一帧, 自报身份与能力。
+ * 工作区别名映射变更后, desktop 重发 hello 即时生效(server 以最新一帧为准)。
+ */
+export interface HelloPayload {
+ protocolVersion: number;
+ /** desktop 设备稳定标识(多设备路由预留, v1 server 侧可只记录)。 */
+ deviceId: string;
+ deviceName: string;
+ /** 本连接注册的工作区别名列表 —— server 只能派发列表内的别名。 */
+ workspaces: string[];
+ /**
+ * 本连接的默认工作区别名(可选; 缺省 / null = 无默认, server 按各自既有
+ * 规则决定, 通常落 HOOK_CHAT_WORKSPACE_ALIAS)。**必须是 workspaces 的成员**
+ * (协议层校验) —— 默认值不能绕过「server 只能派发列表内的别名」这条约束。
+ *
+ * 动机: X 这类**一次交互只有一条公开消息**的渠道没有交互式选择面板(Slack
+ * 有 Block Kit、Telegram 有 inline keyboard), 无处让用户挑目录, 于是所有
+ * 任务都只能落在对话伪目录上、碰不到本地仓库。由 desktop 在握手时声明一个
+ * 默认目录, 是不引入额外往返、也不占用正文字符的做法。
+ *
+ * 旧 server 校验器只查已知字段, 本字段安全透传(同 features 的兼容策略)。
+ */
+ defaultWorkspace?: string | null;
+ /** 可用 agent 类型(如 'cc' / 'codex'), 供 server 侧校验 dispatch options。 */
+ agents: string[];
+ /**
+ * desktop 侧能力标识(可选, 缺省 = 旧客户端无能力)。当前已定义:
+ * HOOK_FEATURE_MULTI_TEAM —— 会消费 bind.state 快照与按 team 定位的
+ * bind.update / prefs.state。老 server 校验器只查已知字段, 本字段安全透传。
+ */
+ features?: string[];
+ /**
+ * 是否由 Slack Bot 私信设备上下线通知。缺省表示旧客户端,server 按既有
+ * 默认开启处理;新客户端始终显式发送当前有效值。
+ */
+ lifecycleAnnouncement?: boolean;
+}
+
+/** welcome(server -> desktop): hello 的应答, 握手完成。 */
+export interface WelcomePayload {
+ serverName: string;
+ /** server 侧启用的可选能力标识, v1 恒空数组, 预留。 */
+ features: string[];
+}
+
+/** ping / pong: 心跳, 双向皆可发起, 收到 ping 必须回 pong。payload 恒空对象。 */
+export type PingPayload = Record<string, never>;
+export type PongPayload = Record<string, never>;
+
+// ── 阶段 2: 派活 ─────────────────────────────────────────────────────────────
+
+/**
+ * dispatch 的可选 override。全部可空 —— 空值落到 desktop 连接配置的默认值。
+ * permissionMode 语义: 仅对「新建 session」的任务生效 —— desktop 校验其属于
+ * 目标 agent 的能力档位清单, 合法即用, 非法/缺省落 bypassPermissions;
+ * 复用/接管已有会话时忽略(session meta 权威, 进行中的会话不受影响)。
+ */
+export interface TaskDispatchOptions {
+ model?: string | null;
+ permissionMode?: string | null;
+ agentKind?: string | null;
+ /** 思考强度档位(如 low/medium/high); 空 = desktop 按草稿默认落值。 */
+ effort?: string | null;
+}
+
+/**
+ * 入站附件(图片等), 随 dispatch 一起下发。base64 内联传输 —— 复用已建好、
+ * 已鉴权的 WS 通道, 免去 desktop 再开 HTTP 拉取端点。desktop 侧解码落盘后
+ * 以本地路径喂给 agent(maker 的 image content block 要 path 而非 base64)。
+ * 精细限额(单图大小 / 张数)由 provider 在生产端把关, 见其实现。
+ */
+export interface TaskAttachment {
+ /** 原文件名(落盘 / 提示用); 无则 desktop 按序号命名。 */
+ name: string | null;
+ /** MIME 类型(如 image/png)。 */
+ mimeType: string;
+ /** base64 编码的字节(不含 data: 前缀)。 */
+ dataBase64: string;
+}
+
+/**
+ * agent 多模态可消费的图片 MIME 白名单 —— 协议层的权威单一来源。
+ * 与 desktop renderer 的 SUPPORTED_IMAGE_EXTS 一致, 也是 Claude / Codex vision
+ * 实际接受的集合(png / jpeg / gif / webp)。provider 下载端与 desktop 落盘端
+ * 都据此过滤: 一端宽一端窄会导致图片被下载/传输后在对端静默丢弃, 白费带宽还
+ * 不告知用户。bmp / svg / heic / avif / tiff 等不在此列(上游 vendor API 不接受)。
+ */
+export const SUPPORTED_IMAGE_MIME_TYPES = [
+ 'image/png',
+ 'image/jpeg',
+ 'image/gif',
+ 'image/webp',
+] as const;
+
+/**
+ * 判定 MIME 是否为 agent 可消费的图片类型(大小写 / 前后空白无关;
+ * 常见别名 image/jpg 归一到 image/jpeg)。
+ */
+export function isSupportedImageMime(mime: string): boolean {
+ const m = mime.trim().toLowerCase();
+ if (m === 'image/jpg') return true;
+ return (SUPPORTED_IMAGE_MIME_TYPES as readonly string[]).includes(m);
+}
+
+/**
+ * 结构化 thread 上下文条目(来源 IM 的 thread 历史中的一条消息)。
+ * desktop 据此渲染可折叠的 thread 上下文卡片, 不再依赖从 prompt
+ * 文本里正则解析 <thread_context> 块。
+ */
+export interface ThreadContextEntry {
+ author: string;
+ text: string;
+ /** 该条目是否为 bot 自身的回复(渲染时可视觉区分)。 */
+ isBot?: boolean;
+}
+
+/**
+ * 任务来源元数据 —— 告知 desktop 这条任务来自哪个 IM 平台及其上下文。
+ * 字段全部可选(im 除外); 旧 server 不发时 desktop 降级为纯文本渲染。
+ */
+export interface TaskSource {
+ /** IM 平台标识(开放集合): 'slack' | 'feishu' | 'discord' | ... */
+ im: string;
+ /** 来源显示名(频道名 "#general"、群名等); null = 未知。 */
+ channelName?: string | null;
+ /**
+ * (multi-team)来源 Slack workspace id / 显示名: desktop 存进 session
+ * meta, 作会话标题前缀与网关工具调用的默认 team。老 server 不下发。
+ */
+ teamId?: string | null;
+ teamName?: string | null;
+ /** 结构化 thread 上下文; 省略或空数组 = 无 thread 历史。 */
+ threadContext?: ThreadContextEntry[];
+ /**
+ * 触发本任务的 IM 消息 id(与 group.message.messageId 同一 id 空间)。
+ * desktop 用它在本地群窗口中精确剔除"当前消息", 避免上下文与 prompt 重复。
+ * 旧 server 不发 = null/缺省, desktop 降级为不剔重。
+ */
+ triggerMessageId?: string | null;
+ /**
+ * 用户 @ bot 的干净原文(UI 显示用) —— 不含 thread 上下文与 prompt 指引。
+ * desktop 据此渲染任务卡片正文, 与发给 agent 的完整 prompt 彻底分离。
+ */
+ userText?: string;
+}
+
+/**
+ * task.dispatch(server -> desktop): 派发一个任务。
+ * 两种会话定位方式:
+ * - sessionId 为 null(默认): 按 externalKey 查映射, 有则复用、无则在
+ * workspace 别名对应目录下新建 —— 此时 workspace 必填。
+ * - sessionId 非 null(接管): 直接投进该已有 desktop session 并把
+ * externalKey 重绑到它; workspace 忽略(session 自带工作目录, 但其
+ * workingDir 必须落在本连接注册的别名路径内, 否则 rejected)。
+ */
+export interface TaskDispatchPayload {
+ requestId: string;
+ externalKey: string;
+ /** 工作区别名; sessionId 为 null 时必填(非 null 字符串)。 */
+ workspace: string | null;
+ /** 接管目标 session; 普通流程恒 null。 */
+ sessionId: string | null;
+ prompt: string;
+ options?: TaskDispatchOptions;
+ /** 入站附件(可选); 省略或空数组 = 无附件, 纯文本任务。 */
+ attachments?: TaskAttachment[];
+ /** 任务来源元数据; 省略 = 来源未知, desktop 按纯文本处理。 */
+ source?: TaskSource;
+}
+
+/** ack 三态。 */
+export const TASK_ACK_RESULTS = ['accepted', 'queued', 'rejected'] as const;
+export type TaskAckResult = (typeof TASK_ACK_RESULTS)[number];
+
+/** rejected 的机器可读原因。 */
+export const TASK_REJECT_REASONS = [
+ /** workspace 别名未在本连接注册。 */
+ 'unknown_workspace',
+ /** 接管目标 session 的工作目录不在本连接注册的别名路径内。 */
+ 'workspace_not_allowed',
+ /** 接管目标 session 不存在。 */
+ 'session_not_found',
+ /** desktop 侧 hook 功能已关闭(总开关或本连接开关)。 */
+ 'disabled',
+ /** 参数非法(desktop 业务层校验不过, 区别于协议层直接拒收的坏帧)。 */
+ 'invalid',
+] as const;
+export type TaskRejectReason = (typeof TASK_REJECT_REASONS)[number];
+
+/**
+ * task.ack(desktop -> server): dispatch 的立即应答。
+ * 字段联动约束(parse 强制):
+ * - reason 仅 rejected 时非 null;
+ * - queuePosition 仅 queued 时非 null(0 起, 非负整数);
+ * - sessionId 在 accepted / queued 时为目标 session id, rejected 时为 null。
+ */
+export interface TaskAckPayload {
+ requestId: string;
+ result: TaskAckResult;
+ reason: TaskRejectReason | null;
+ sessionId: string | null;
+ queuePosition: number | null;
+}
+
+// ── 阶段 4: 交差 ─────────────────────────────────────────────────────────────
+
+/** cancelled: task.cancel 中断收口(errorMessage 恒 null, finalText 可为已产出的部分文本)。 */
+export const TURN_END_STATUSES = ['ok', 'error', 'cancelled'] as const;
+export type TurnEndStatus = (typeof TURN_END_STATUSES)[number];
+
+/** turn 的用量摘要。v1 只有耗时, 字段可空(拿不到就 null, 不编造)。 */
+export interface TurnEndUsage {
+ durationMs: number | null;
+}
+
+/**
+ * turn.end(desktop -> server): 任务收口。
+ * 收口时机以 maker-core 事件流的 done / terminal error 为准。
+ * 字段联动约束(parse 强制): status 为 'ok' 时 errorMessage 必须为 null;
+ * 为 'error' 时 errorMessage 必须为非空字符串。
+ */
+export interface TurnEndPayload {
+ requestId: string;
+ externalKey: string;
+ sessionId: string | null;
+ status: TurnEndStatus;
+ /** 该 turn 的最终文本(error 时可为空串)。 */
+ finalText: string;
+ errorMessage: string | null;
+ usage: TurnEndUsage;
+ /**
+ * 出站附件(agent 产出的图片 / 文件, base64 内联) —— 与入站 attachments
+ * 对称复用 TaskAttachment。desktop 侧从最终文本的 xdt-image / xdt-file
+ * 引用与 tool_result 旁路收集并施加大小/数量限额(finalText 中对应引用
+ * 已剥离/替换为提示); server 侧上传到渠道。省略或空数组 = 无附件。
+ * 旧 server 收到未知字段静默忽略(校验器只查已知字段), 向后兼容。
+ */
+ attachments?: TaskAttachment[];
+}
+
+/**
+ * turn.delivery(server -> desktop): server 对普通 turn.end 的两阶段交付回执。
+ *
+ * accepted 表示 server 已经接管最终结果及其重试责任;delivered 表示渠道侧
+ * 终态动作已完成;failed 表示 server 已停止重试。desktop 只有在双方协商
+ * HOOK_FEATURE_TURN_DELIVERY 后才等待本帧,老 server 继续沿用 fire-and-forget。
+ */
+export const TURN_DELIVERY_STATES = ['accepted', 'retrying', 'delivered', 'failed'] as const;
+export type TurnDeliveryState = (typeof TURN_DELIVERY_STATES)[number];
+
+/** retrying / failed 回执的安全、结构化错误;不得携带上游响应体、凭证或用户内容。 */
+export interface TurnDeliveryError {
+ code: string;
+ message: string;
+ /** 原样重放同一个 turn.end 是否仍可能恢复;false 时 desktop 只提示,不重跑 Agent。 */
+ retryable: boolean;
+}
+
+export interface TurnDeliveryPayload {
+ requestId: string;
+ state: TurnDeliveryState;
+ /** 已发生的渠道发布尝试次数;accepted 为 0,其余状态至少为 1。 */
+ attempt: number;
+ /** 仅 retrying 为正的安全整数,表示 server 计划的下次尝试时刻(unix ms)。 */
+ retryAt: number | null;
+ /** retrying / failed 非 null;accepted / delivered 恒为 null,failed 的 retryable 必须为 false。 */
+ error: TurnDeliveryError | null;
+}
+
+// ── 阶段 9(v2): 执行进度 ────────────────────────────────────────────────────
+
+/**
+ * turn.progress(desktop -> server): turn 执行中的渲染快照(见文件头第 9 条)。
+ * text 是 desktop 合成好的完整 markdown 快照(过程区时间线 + 已产出的部分
+ * 正文), server 侧不拼接、不累积 —— 每帧整体替换占位消息内容(latest-wins,
+ * 丢帧无害)。desktop 侧负责节流(约 1.5s/帧)与长度控制。
+ */
+export interface TurnProgressPayload {
+ requestId: string;
+ /** 当前渲染快照(完整替换语义, 非增量)。 */
+ text: string;
+}
+
+// ── 阶段 18(v2): 收口后的续跑 ───────────────────────────────────────────────
+
+/**
+ * turn.reopen(desktop -> server): 把一个已收口任务的续跑接回原消息
+ * (见文件头第 18 条)。
+ *
+ * server 收到后把 reopenOf 那条消息的位置登记给 requestId, 之后 desktop 会用
+ * **requestId**(不是 reopenOf)继续发 turn.progress 与 turn.end, 走既有路径。
+ * 认不出 reopenOf 时静默忽略本帧与后续同 requestId 的帧。
+ *
+ * 路由面**只含** turn.progress / turn.end / task.cancel。刻意不含 interaction.*:
+ * 续跑是用户在**桌面端**点出来的, 人就在桌面前, 那一轮里 agent 的提问 / 计划审阅 /
+ * 权限审批由桌面本地交互面直接处理, 不绕回渠道 —— 所以 server 不会收到带续跑
+ * requestId 的 interaction.request, 也不需要为它建立 thread 关联。(反过来若把交互
+ * 推回渠道, 用户得离开正在操作的桌面端去渠道点按钮, 更绕。)
+ *
+ * 可靠性: 本帧可被重复发送, server 必须幂等 —— 同一 (requestId, reopenOf) 重复
+ * 登记同一个位置, 无副作用。与之对称, server 对**从未登记过**的 requestId 的
+ * turn.progress / turn.end 一律静默忽略: 不报错、不新建消息。
+ *
+ * 帧序: 本帧必须排在这一轮的**任何** turn.progress / turn.end 之前 —— 包括"首个
+ * 观察到的事件本身就是终态"(例如立刻的凭证错误)。先发 turn.end 的话 server 会按
+ * 未知 requestId 丢弃它, 随后的 reopen 又把消息改成进行中, 就再没有终态帧能收口。
+ *
+ * 孤儿收口(server 侧责任): 映射装上、消息已改成进行中之后, desktop 崩溃 / 重启
+ * 不会补发任何帧(记账只在进程内)。所以**连接断开时 server 必须收口该连接上所有
+ * "已 reopen 但未收到 turn.end"的消息** —— 恢复原终态或改写成一句"续跑中断"。
+ * 少了这条, 可见状态会从"停在失败"退化成"永远进行中", 比不做回流更糟。收口落笔时
+ * 必须校验该消息仍归"被断开的那个连接 + 那次 reopen"所有: desktop 可能毫秒级重连、
+ * 用户也可能立刻再点一次重试, 迟到的收口不得盖掉更新的一次 reopen 或已到达的新终态。
+ *
+ * 断连即终局(desktop 侧对称责任): 续跑轮的 turn.progress / turn.end 一律直发,
+ * **不缓存也不在重连后补发** —— 这刻意偏离"断线重连 desktop 补发未送达 turn.end"
+ * 的通用约定, 因为那条消息在断连瞬间已被上面的收口改写, 迟到的 turn.end 只会撞上
+ * 被解绑的 requestId 而丢弃, 反把"其实成功"显示成"续跑中断"。相应地, turn.end 没
+ * 发出去时 desktop 不得再把这条消息线登记成可续跑(它的 reopenOf 已被解绑)。
+ *
+ * id 碰撞: 续跑 requestId 由 desktop 生成(须 UUID v4 或同等强度), 与 server 生成的
+ * 普通 requestId 共用一张路由表。server 收到已绑定到别的任务的 requestId 时拒绝登记,
+ * **并把该 requestId 整体隔离** —— 后续 turn.progress / turn.end 一并忽略。只拒本帧
+ * 却继续按老路由收后续帧, 等于让续跑的进度与终态改写那个无关任务的消息。
+ *
+ * 已声明接受的降级: 连接在续跑轮跑完前断开时结果不回流 —— 断在装映射前是消息保持
+ * 原失败态(与本能力上线前完全一致), 断在装映射后是 server 收口成原终态或"续跑中断"
+ * (那一轮其实成功时, 渠道会偏保守地显示没成功, 而桌面端有正确结果)。两种情形用户都
+ * 可在渠道重发。协议刻意不为此加 ack 往返: 回流是增强而非关键路径。注意这个"失败
+ * 方向安全"的结论**依赖上面那条孤儿收口**。
+ */
+export interface TurnReopenPayload {
+ /**
+ * 续跑轮的新任务 id(后续 progress / end / cancel 都用它)。
+ *
+ * 必须**全局抗碰撞**(UUID v4 或同等强度), 不得用递增计数器或会话内序号: 普通
+ * 任务的 requestId 由 server 生成、本字段由 desktop 生成, 两者是同一张生命周期
+ * 路由表的键, 而 parse 只能校验"非空且不等于 reopenOf"。id 空间重叠时, 一次续跑
+ * 可能覆盖掉某个无关在跑任务的路由。server 侧以"拒绝已绑定的 requestId"兜底。
+ */
+ requestId: string;
+ /** 被续跑的那一轮的 requestId —— server 据此定位渠道里那条消息。 */
+ reopenOf: string;
+ /**
+ * 渠道内标识(原样回传), 供日志与诊断关联。
+ *
+ * **不参与路由**: 定位那条消息的唯一依据是 reopenOf。刻意不允许用它兜底 ——
+ * 两端独立实现(server 闭源、独立仓), 一端"映射过期就按 externalKey 找 thread"、
+ * 另一端"映射过期就忽略", 同一次过期续跑会在一端改写消息、在另一端丢弃。
+ */
+ externalKey: string;
+ /** 续跑发生在哪个会话(记录与调试用, 不参与路由)。 */
+ sessionId: string | null;
+ /**
+ * 为什么被续跑。当前只有 'user-continued'(用户在桌面端显式点了续跑 / 重试)。
+ * 开放集合: server 不认识的值按 'user-continued' 处理即可, 不要拒帧。
+ */
+ reason: string;
+}
+
+// ── 阶段 5(v2): 身份绑定 ────────────────────────────────────────────────────
+
+/**
+ * bind.start(desktop -> server): 发起「Slack 用户 ↔ 本设备」绑定。
+ * 阶段 4 起绑定走 Sign in with Slack(OIDC): 新桌面端发**空对象** `{}`,
+ * server 据连接身份签发授权链接经 bind.update(pending, authorizeUrl)回推。
+ * 设备身份取连接 hello 的 deviceId, 不在本帧携带。
+ *
+ * email 字段仅为识别老客户端保留(@deprecated): 老桌面端仍按邮箱发起,
+ * server 收到带 email 的 bind.start 即判定为旧版, 回 bind.update(failed)
+ * 提示升级, 不再执行邮箱定位。
+ */
+export interface BindStartPayload {
+ /** @deprecated 旧版邮箱绑定流字段; 新端不再发送, 仅用于 server 识别老客户端。 */
+ email?: string;
+ /**
+ * (multi-team)重新授权指定 workspace 时 pin 授权页到该 team(server 在
+ * 授权链接上带 team 参数); 缺省/null = 用户在授权页自选(添加新 team)。
+ * 老 server 校验器不查本字段, 安全透传(它照常签发不 pin 的链接)。
+ */
+ teamId?: string | null;
+}
+
+/**
+ * bind.update 状态机:
+ * none 未绑定(连接建立后 server 主动推一帧告知现状)
+ * pending OIDC 授权链接已签发(authorizeUrl 非空), 等待用户在浏览器授权
+ * confirmed 绑定成立(slackUserId / slackUserName 非空)
+ * denied 用户在 Slack 授权页点了拒绝
+ * expired 授权超时(state 令牌过期)
+ * failed 流程失败(如老客户端、该 workspace 未安装本 app), message 携带原因
+ * revoked 绑定被解除(本设备主动 revoke, 或被同用户新设备顶掉)
+ */
+export const BIND_UPDATE_STATES = [
+ 'none',
+ 'pending',
+ 'confirmed',
+ 'denied',
+ 'expired',
+ 'failed',
+ 'revoked',
+] as const;
+export type BindUpdateState = (typeof BIND_UPDATE_STATES)[number];
+
+/**
+ * bind.update(server -> desktop): 绑定状态推送(bind.start 的应答 + 后续
+ * 任何状态变化, 含连接建立时的现状同步与被新设备顶掉的通知)。
+ * 字段联动(parse 强制): confirmed 时 slackUserId 非空; pending 时
+ * authorizeUrl 非空(OIDC 授权链接); failed 时 message 非空。
+ */
+export interface BindUpdatePayload {
+ state: BindUpdateState;
+ slackUserId: string | null;
+ /** Slack 显示名(设置页展示「已绑定 @xxx」用), 拿不到可为 null。 */
+ slackUserName: string | null;
+ /** 人类可读补充说明(failed 原因 / revoked 缘由等)。 */
+ message: string | null;
+ /**
+ * OIDC 授权链接(仅 state=pending 时非空): 桌面端用系统浏览器打开它,
+ * 用户在 Slack 授权页确认后 server 回调完成绑定。其它状态省略或 null。
+ */
+ authorizeUrl?: string | null;
+ /**
+ * 结构化失败原因(仅 state=failed 时可选)。桌面端按它分支 UI, 不解析
+ * message 文案(规则 9)。当前已定义:
+ * 'not-installed' —— 用户授权的 Slack workspace 未安装本 App(SIWS 授权
+ * 不要求安装, 但 bot 无 token 收发消息), 桌面端显示「安装 App」引导。
+ * parse 侧只校验 string|null(未知值放行), 老客户端遇到新 reason 忽略即可。
+ */
+ reason?: string | null;
+ /**
+ * 按 workspace 定制的安装链接(仅 reason='not-installed' 时可选): 携带
+ * team 参数, Slack 安装授权页会预选到用户刚授权的那个 workspace, 免手选。
+ * 桌面端缺省(老 server)回退通用 /slack/install 链接。
+ */
+ installUrl?: string | null;
+ /**
+ * 绑定所在 Slack workspace 显示名(仅 state=confirmed 时可选下发, 取安装
+ * 档案的 teamName): 设置页状态行展示「已绑定 @xxx(workspace)」。老 server
+ * 不下发或档案缺名时为 null/缺省, 桌面端回退只显示用户名。
+ */
+ teamName?: string | null;
+ /**
+ * (multi-team)事件所属 Slack workspace id: confirmed / revoked 按 team
+ * 定位到绑定列表的对应行; 授权流早期(pending / denied / expired)团队
+ * 尚未确定, 为 null/缺省。老 server 不下发, 单绑定桌面端不依赖本字段。
+ */
+ teamId?: string | null;
+}
+
+/** bind.update.reason 已知值: 绑定的 Slack workspace 未安装本 App。 */
+export const BIND_FAIL_REASON_NOT_INSTALLED = 'not-installed';
+
+/** bind.update.reason 已知值(multi-team): 该绑定被同用户在另一台设备顶替。 */
+export const BIND_FAIL_REASON_SUPERSEDED = 'superseded';
+
+/**
+ * bind.revoke(desktop -> server): 解除本设备绑定。
+ * teamId 非空 = 只解绑该 workspace(multi-team); 空/缺省 = 解绑本设备全部
+ * (兼容单绑定老 desktop 的"关开关即全解")。pendingOnly=true = 只作废
+ * 进行中的授权尝试(pending 授权 / 等安装登记), 不触碰任何已确认绑定 ——
+ * multi-team 下「取消添加 workspace」的通道(此时 teamId 忽略)。
+ * ⚠ 旧 server 对带字段的帧 parse 拒收(它要求空对象), desktop 仅在
+ * welcome.features 声明 multi-team 后才发非空形态。
+ */
+export interface BindRevokePayload {
+ teamId?: string | null;
+ pendingOnly?: boolean;
+}
+
+/**
+ * bind.state(server -> desktop, multi-team): 本设备绑定全量快照。
+ * 权威列表语义 —— 连接建立与任何绑定变化(新增 / 解除 / 被顶 / 撤权清理)
+ * 后整体推送, desktop 以此对齐本地列表(bind.update 只承载过程事件)。
+ * 仅对 hello.features 声明 multi-team 的连接下发; 旧 desktop 不认识本
+ * 类型, parse 拒收丢帧不断连。
+ */
+export interface BindStateEntry {
+ teamId: string;
+ /** workspace 显示名(安装档案 teamName); 档案缺名时 null。 */
+ teamName: string | null;
+ slackUserId: string;
+ slackUserName: string | null;
+}
+
+export interface BindStatePayload {
+ bindings: BindStateEntry[];
+}
+
+// ── Provider-neutral binding (append-only v1) ───────────────────────────────
+
+/**
+ * IM providers supported by the shared Cindy relay.
+ * Append-only: adding a value here is backward compatible because every
+ * provider-specific frame family is gated behind a `provider:<id>` welcome
+ * capability — an old peer that does not know the new id never negotiates it,
+ * and its parse rejects stray frames without dropping the connection.
+ */
+export const HOOK_PROVIDERS = ['slack', 'telegram', 'x'] as const;
+export type HookProvider = (typeof HOOK_PROVIDERS)[number];
+
+/**
+ * Provider binding states. A binding attempt moves monotonically from pending
+ * through optional confirmation to confirmed, or one of the terminal states.
+ */
+export const PROVIDER_BIND_STATES = [
+ 'none',
+ 'pending',
+ 'awaiting_confirmation',
+ 'confirmed',
+ 'denied',
+ 'expired',
+ 'failed',
+ 'revoked',
+ 'superseded',
+] as const;
+export type ProviderBindState = (typeof PROVIDER_BIND_STATES)[number];
+
+/** Known UI action hints. The wire remains open; consumers ignore unknown values. */
+export const PROVIDER_BIND_ACTIONS = [
+ 'open_connect_url',
+ 'copy_connect_url',
+ 'cancel',
+ 'retry',
+ 'revoke',
+ 'open_provider',
+ 'add_to_group',
+] as const;
+export type KnownProviderBindAction = (typeof PROVIDER_BIND_ACTIONS)[number];
+export type ProviderBindAction = string;
+
+/** Start a provider-specific, one-time binding attempt for this device. */
+export interface ProviderBindStartPayload {
+ requestId: string;
+ provider: HookProvider;
+ /** Optional provider scope (for example a Slack team or Telegram bot id). */
+ scopeId?: string | null;
+}
+
+/** Cancel exactly one in-flight binding attempt without touching a binding. */
+export interface ProviderBindCancelPayload {
+ requestId: string;
+ provider: HookProvider;
+ attemptId: string;
+}
+
+/** Revoke exactly one confirmed binding. */
+export interface ProviderBindRevokePayload {
+ requestId: string;
+ provider: HookProvider;
+ bindingId: string;
+}
+
+/**
+ * Shared payload for provider.bind.update and provider.bind.state. update is an
+ * event/reply; state is an authoritative point-in-time snapshot for one scope.
+ * All nullable fields are explicit so an old value cannot survive a snapshot.
+ */
+export interface ProviderBindStatusPayload {
+ provider: HookProvider;
+ /** Request id being answered, or null for an unsolicited state push. */
+ replyTo: string | null;
+ state: ProviderBindState;
+ attemptId: string | null;
+ bindingId: string | null;
+ principalId: string | null;
+ principalName: string | null;
+ scopeId: string | null;
+ scopeName: string | null;
+ /** One-time provider deep link; present only while state=pending. */
+ connectUrl: string | null;
+ /** Unix milliseconds; required for pending/awaiting_confirmation attempts. */
+ expiresAt: number | null;
+ /** Stable machine-readable reason; required for unsuccessful terminal states. */
+ reason: string | null;
+ /** Optional safe recovery/provider URL interpreted by the host application. */
+ remediationUrl: string | null;
+ actions: ProviderBindAction[];
+}
+
+export type ProviderBindUpdatePayload = ProviderBindStatusPayload;
+export type ProviderBindStatePayload = ProviderBindStatusPayload;
+
+// ── 阶段 6(v2): 实时问答 ────────────────────────────────────────────────────
+
+/** 可查询的清单种类。 */
+export const QUERY_KINDS = ['workspaces', 'models', 'sessions'] as const;
+export type QueryKind = (typeof QUERY_KINDS)[number];
+
+/**
+ * query.request(server -> desktop): 实时拉取清单(/bind /model /effort 触发)。
+ * queryId 由 server 生成, response 原样回传配对; server 侧自行做超时。
+ */
+export interface QueryRequestPayload {
+ queryId: string;
+ kind: QueryKind;
+}
+
+/**
+ * 模型条目: efforts 为该模型支持的思考强度档位(可空数组 = 不支持调档)。
+ * group 是目录分组 id(如 'gpt' / 'gpt-budget'): 骨折版与官方版 displayName
+ * 故意同名、仅靠分组区分, server 渲染下拉时据此加区分后缀, 否则出现两个
+ * 一模一样的 "GPT-5.5"(线上实撞)。可选 —— 旧桌面端不发, server 视为无分组。
+ */
+export interface QueryModelEntry {
+ id: string;
+ label: string;
+ efforts: string[];
+ defaultEffort: string | null;
+ group?: string | null;
+}
+
+/**
+ * 权限档条目(label = desktop capabilities 的 displayName, 原样透传,
+ * 与模型 label 同风格 —— server 不做本地化映射, 避免档位集合演进时文案漂移)。
+ */
+export interface QueryPermissionModeEntry {
+ id: string;
+ label: string;
+}
+
+/**
+ * 按 agent 分组的模型清单(kind=models 的响应体)。
+ * permissionModes 缺席 = 旧版 desktop(不支持权限档下发), server 侧应隐藏
+ * 权限选择 UI; 空数组 = 该 agent 无可选档位, 同样隐藏。
+ */
+export interface QueryAgentModels {
+ agentKind: string;
+ models: QueryModelEntry[];
+ permissionModes?: QueryPermissionModeEntry[];
+}
+
+/** Privacy-minimised recent-session entry for the provider session picker. */
+export interface QuerySessionEntry {
+ id: string;
+ title: string;
+ /** Workspace alias only; local absolute paths are forbidden on this wire. */
+ workspace: string;
+ /** Unix milliseconds of the latest local activity. */
+ lastActiveAt: number;
+}
+
+/**
+ * query.response(desktop -> server): 问答应答。
+ * ok=false 时 error 非空(desktop 侧取清单失败); ok=true 时按 kind 携带
+ * workspaces 或 agents 之一(parse 强制)。
+ */
+export interface QueryResponsePayload {
+ queryId: string;
+ kind: QueryKind;
+ ok: boolean;
+ error: string | null;
+ /** kind=workspaces 且 ok 时必填: 当前注册的工作区别名。 */
+ workspaces?: string[];
+ /** kind=models 且 ok 时必填: 按 agent 分组的可用模型与 effort 档位。 */
+ agents?: QueryAgentModels[];
+ /** kind=sessions 且 ok 时必填: at most 20 privacy-minimised entries. */
+ sessions?: QuerySessionEntry[];
+}
+
+// ── 阶段 7(v2): 任务取消 ────────────────────────────────────────────────────
+
+/**
+ * task.cancel(server -> desktop): 中断在跑任务(/stop 触发)。
+ * desktop 收到后中断对应 session 的当前 turn, 以 turn.end(cancelled) 收口;
+ * requestId 未知 / 任务已收口时静默忽略(与 turn.end 的竞态由 server 侧
+ * 幂等消化)。
+ */
+export interface TaskCancelPayload {
+ requestId: string;
+}
+
+// ── 阶段 8(v2): 会话归档 ────────────────────────────────────────────────────
+
+/**
+ * session.archive(server -> desktop): 归档 externalKey 绑定的会话(私聊
+ * /new 换代触发, 旧代会话不再显示在桌面端列表)。desktop 侧幂等: 无绑定、
+ * 会话不存在或已归档时静默忽略。老版本 desktop 不认识本类型, parse 拒收
+ * 丢帧不断连(见文件头「type 为开放集合」约定), 仅表现为旧会话留在列表。
+ */
+export interface SessionArchivePayload {
+ externalKey: string;
+}
+
+// ── 阶段 10(v2): 执行中交互 ─────────────────────────────────────────────────
+
+/** 单个交互卡按钮上限(Slack actions block 每块 5 个 x 分块, 取宽松上限)。 */
+export const MAX_INTERACTION_BUTTONS = 24;
+
+/**
+ * 交互卡按钮。id 是 desktop 侧的决策映射键(server 原样回传, 不理解语义),
+ * 同一张卡内唯一; 字符集限制: 不含 '|'(server 侧 value 复合编码分隔符)。
+ */
+export interface InteractionButton {
+ id: string;
+ label: string;
+ /** 视觉样式(Slack 按钮 style; default = 无样式)。 */
+ style: 'primary' | 'danger' | 'default';
+}
+
+/**
+ * interaction.request(desktop -> server): turn 执行中 agent 发起的用户交互,
+ * 以「标题 + markdown 正文 + 按钮组」的渠道无关卡片形式转发。server 渲染进
+ * 该任务的回帖 thread, 按钮按压回 interaction.decision。
+ * kind 是开放集合(当前 'ask_user_question' / 'plan_review'), server 只透传
+ * 日志不理解语义 —— 新 kind 不需要 server 升级。
+ */
+export interface InteractionRequestPayload {
+ /** 所属任务(server 据此定位回帖 thread 并校验归属)。 */
+ requestId: string;
+ /** 交互唯一标识(maker-core InteractionRequest.requestId), 决策配对键。 */
+ interactionId: string;
+ kind: string;
+ title: string;
+ /** markdown 正文(server 转渠道格式渲染); 可为空串。 */
+ body: string;
+ buttons: InteractionButton[];
+}
+
+/**
+ * interaction.decision(server -> desktop): 用户按下交互卡按钮。
+ * desktop 按 interactionId 配对挂起的交互, 用 buttonId 查自己登记的
+ * 按钮->决策映射(语义不过网线)。迟到/未知的 decision 静默忽略。
+ */
+export interface InteractionDecisionPayload {
+ requestId: string;
+ interactionId: string;
+ buttonId: string;
+}
+
+/**
+ * interaction.cancel(desktop -> server): 交互已在 desktop 侧收口(超时按
+ * 安全默认自决 / turn 结束), 通知 server 改写卡片(摘按钮 + reason 文案),
+ * 防止用户对着死卡片按。幂等: server 找不到对应卡片时静默忽略。
+ */
+export interface InteractionCancelPayload {
+ requestId: string;
+ interactionId: string;
+ /** 卡片改写文案(人类可读)。 */
+ reason: string;
+}
+
+// ── 阶段 11(v2): 目录偏好远程读写 ──────────────────────────────────────────
+
+/** prefs.get(desktop -> server): 拉取本设备绑定用户的全部目录偏好快照。 */
+export interface PrefsGetPayload {
+ /** desktop 生成的关联 id, prefs.state.replyTo 回显配对。 */
+ requestId: string;
+}
+
+/** 单目录偏好条目(与 server user_prefs 行同形; slackUserId 不过网线)。 */
+export interface WorkspacePrefsEntry {
+ workspace: string;
+ model: string | null;
+ effort: string | null;
+ agentKind: string | null;
+ permissionMode: string | null;
+ /**
+ * (multi-team)偏好归属的 Slack workspace。多绑定设备的快照覆盖全部已绑
+ * team, 桌面端按 teamId 分组编辑。老 server 不下发(单绑定语境无歧义)。
+ */
+ teamId?: string | null;
+}
+
+/**
+ * prefs.set(desktop -> server): 部分更新某目录偏好(undefined 字段不动,
+ * null 显式清空 —— 与 server setPrefs / dispatch options 同语义)。
+ * server 只做 shape 校验, 不校验值合法性(值来自 desktop 自己的能力清单;
+ * 过期值由 desktop 派发侧 defaults 兜底)。
+ */
+export interface PrefsSetPayload {
+ requestId: string;
+ workspace: string;
+ model?: string | null;
+ effort?: string | null;
+ agentKind?: string | null;
+ permissionMode?: string | null;
+ /**
+ * (multi-team)写入目标 team。缺省/null = 设备唯一绑定(多绑定时 server
+ * 不猜测, 忽略写入并在应答快照中原样回放现状)。老 server 不查本字段。
+ */
+ teamId?: string | null;
+}
+
+/**
+ * prefs.state(server -> desktop): 绑定用户的全量目录偏好快照。
+ * replyTo 回显 get/set 的 requestId; 主动推送(/model 卡写入后)为 null。
+ * 字段联动(parse 强制): bound=false 时 prefs 恒空数组(未绑定无偏好可言)。
+ */
+export interface PrefsStatePayload {
+ replyTo: string | null;
+ bound: boolean;
+ prefs: WorkspacePrefsEntry[];
+}
+
+// ── Provider-neutral preferences (append-only v1) ──────────────────────────
+
+/** Provider preference selector; exactly one of bindingId/scopeId is non-null. */
+export interface ProviderPrefsSelector {
+ provider: HookProvider;
+ bindingId: string | null;
+ scopeId: string | null;
+}
+
+export interface ProviderPrefsGetPayload extends ProviderPrefsSelector {
+ requestId: string;
+}
+
+export interface ProviderPrefsSetPayload extends ProviderPrefsSelector {
+ requestId: string;
+ workspace: string;
+ model?: string | null;
+ effort?: string | null;
+ agentKind?: string | null;
+ permissionMode?: string | null;
+}
+
+/** Provider-neutral preference row (intentionally has no Slack teamId field). */
+export interface ProviderWorkspacePrefsEntry {
+ workspace: string;
+ model: string | null;
+ effort: string | null;
+ agentKind: string | null;
+ permissionMode: string | null;
+}
+
+export interface ProviderPrefsStatePayload extends ProviderPrefsSelector {
+ replyTo: string | null;
+ bound: boolean;
+ prefs: ProviderWorkspacePrefsEntry[];
+}
+
+// ── Provider-neutral behavior (Telegram, append-only v1) ───────────────────
+// 见文件头第 19 条。
+
+/**
+ * Providers this frame family currently understands. Deliberately its own
+ * append-only list rather than reusing HookProvider: the field shapes below
+ * (emoji reactions, reply-quote depth, a chat-id-keyed mention allowlist) are
+ * Telegram-specific, not provider-neutral placeholders — adding Slack or X
+ * here later requires a deliberate look at whether these exact fields still
+ * make sense for that provider, not just a permissive type-level allowance.
+ */
+export const PROVIDER_BEHAVIOR_PROVIDERS = Object.freeze(['telegram'] as const);
+export type ProviderBehaviorProvider = (typeof PROVIDER_BEHAVIOR_PROVIDERS)[number];
+
+/** Emoji reaction verbosity on Telegram messages the bot sees/sends. */
+export const TELEGRAM_EMOJI_REACTIONS = Object.freeze(['off', 'minimal', 'expressive'] as const);
+export type TelegramEmojiReactions = (typeof TELEGRAM_EMOJI_REACTIONS)[number];
+
+/** Whether a DM reply quotes the message it answers. */
+export const TELEGRAM_REPLY_QUOTE_DM = Object.freeze(['off', 'first'] as const);
+export type TelegramReplyQuoteDm = (typeof TELEGRAM_REPLY_QUOTE_DM)[number];
+
+/** Whether a group reply quotes the message(s) it answers. */
+export const TELEGRAM_REPLY_QUOTE_GROUP = Object.freeze(['off', 'first', 'all'] as const);
+export type TelegramReplyQuoteGroup = (typeof TELEGRAM_REPLY_QUOTE_GROUP)[number];
+
+/**
+ * The only per-chat activation override this protocol carries: the bot
+ * responds in that chat without requiring an @mention. The default behavior
+ * ('mention' required) is expressed by the chat's *absence* from the map —
+ * there is no 'mention' literal to write, only this one to set or clear.
+ */
+export const TELEGRAM_GROUP_ACTIVATION_ALWAYS = 'always';
+export type TelegramGroupActivationOverride = typeof TELEGRAM_GROUP_ACTIVATION_ALWAYS;
+
+/** The three global Telegram behavior switches, always present together. */
+export interface TelegramBehaviorFields {
+ emojiReactions: TelegramEmojiReactions;
+ replyQuoteDm: TelegramReplyQuoteDm;
+ replyQuoteGroup: TelegramReplyQuoteGroup;
+}
+
+/**
+ * Baseline behavior for a binding that has never been configured, and the
+ * value provider.behavior.state must report while bound=false (parse
+ * enforced — see ProviderBehaviorStatePayload). Matches the personal-build
+ * defaults (the shipped Telegram bot behavior before any override): emoji
+ * reactions default to 'minimal', DM reply-quoting defaults off, and group
+ * reply-quoting defaults to quoting the first message of a burst.
+ */
+export const DEFAULT_TELEGRAM_BEHAVIOR: Readonly<TelegramBehaviorFields> = Object.freeze({
+ emojiReactions: 'minimal',
+ replyQuoteDm: 'off',
+ replyQuoteGroup: 'first',
+});
+
+/**
+ * Selector for provider.behavior.* frames. Deliberately narrower than
+ * ProviderPrefsSelector (which allows a scope-only selector before a binding
+ * exists): every field here — the global switches and the per-chat allowlist
+ * — is meaningless without a concrete bound principal (the allowlist's keys
+ * are chats *that principal's bot* has seen), so there is nothing to
+ * configure pre-binding. Requiring bindingId (not bindingId | scopeId) keeps
+ * the owner boundary explicit: whoever holds the bindingId is the only party
+ * allowed to read or write it.
+ */
+export interface ProviderBehaviorSelector {
+ provider: ProviderBehaviorProvider;
+ bindingId: string;
+}
+
+export interface ProviderBehaviorGetPayload extends ProviderBehaviorSelector {
+ requestId: string;
+}
+
+/**
+ * A single chat's activation-allowlist patch. `value: 'always'` adds the
+ * override; `value: null` clears a previously-set override, falling back to
+ * the default (mention required). Only one chat per set frame — batching is
+ * just repeated set calls, which keeps each mutation independently
+ * observable via the resulting provider.behavior.state.
+ */
+export interface ProviderBehaviorGroupActivationPatch {
+ chatId: string;
+ value: TelegramGroupActivationOverride | null;
+}
+
+/**
+ * provider.behavior.set(desktop -> server): patch one bound Telegram
+ * principal's behavior. Two independent, freely combinable patch axes:
+ * - the three global fields, each optional and each `enum | null`:
+ * - undefined = untouched (field omitted from the frame entirely);
+ * - an enum literal = set an **explicit override** to that value —
+ * written and persisted even when it happens to equal the current
+ * version default. This matters: a user who explicitly chose
+ * 'minimal' must keep seeing 'minimal' even if a later protocol
+ * revision changes DEFAULT_TELEGRAM_BEHAVIOR.emojiReactions to
+ * something else. Explicit intent must survive a default-value
+ * change; only the user (or a future explicit clear) may remove it;
+ * - `null` = **clear** the override, falling back to whatever
+ * DEFAULT_TELEGRAM_BEHAVIOR carries for that field at resolve time.
+ * This is the same three-way shape as ProviderBehaviorGroupActivationPatch
+ * below (undefined/value/null), just applied to enum fields instead of
+ * a chat-id map entry.
+ * - groupActivation: one chat's allowlist patch or clear (see above).
+ * parse rejects a frame with neither axis present — unlike prefs.set, a
+ * silent no-op here would give the user no observable feedback that nothing
+ * changed, so intent must be explicit. Note `null` on a global field still
+ * counts as "an actual patch" for that at-least-one-patch requirement: it
+ * is a real, observable clear action, not an omission.
+ */
+export interface ProviderBehaviorSetPayload extends ProviderBehaviorSelector {
+ requestId: string;
+ emojiReactions?: TelegramEmojiReactions | null;
+ replyQuoteDm?: TelegramReplyQuoteDm | null;
+ replyQuoteGroup?: TelegramReplyQuoteGroup | null;
+ groupActivation?: ProviderBehaviorGroupActivationPatch;
+}
+
+/**
+ * provider.behavior.state(server -> desktop): full effective snapshot for one
+ * bound Telegram principal — reply to get/set (replyTo echoes requestId) or
+ * an unsolicited push after some other client mutates it (replyTo null).
+ * The three behavior fields are the *resolved* values (never a raw patch).
+ * groupActivation lists only chats that deviate from the default — chats the
+ * user never touched are implicitly 'mention' and are not enumerated. The
+ * enclosing frame remains bounded by HOOK_MAX_FRAME_CHARS; the map itself has
+ * no lower entry cap because every valid set mutation must remain representable
+ * in a later authoritative state snapshot.
+ * Field linkage (parse enforced): bound=false collapses the whole snapshot to
+ * DEFAULT_TELEGRAM_BEHAVIOR and an empty groupActivation — there is no
+ * principal to hold per-chat overrides for an unbound selector, so a stale
+ * configured value cannot survive past the binding that set it.
+ */
+export interface ProviderBehaviorStatePayload
+ extends ProviderBehaviorSelector, TelegramBehaviorFields {
+ replyTo: string | null;
+ bound: boolean;
+ groupActivation: Record<string, TelegramGroupActivationOverride>;
+}
+
+// ── 阶段 12(v2): Slack 网关工具 ────────────────────────────────────────────
+
+/**
+ * welcome.features 能力标识: server 支持 tool.request / tool.response 帧族
+ * (Slack 网关工具)。desktop 侧发 tool.request 前先查本标识, 缺席直接短路
+ * 为 SERVER_TOO_OLD, 不打空炮。
+ */
+export const HOOK_FEATURE_SLACK_TOOLS = 'slack-tools';
+
+/**
+ * 双向能力标识: 多 workspace 绑定(见文件头第 13 条)。desktop 在
+ * hello.features 声明会消费 bind.state / 按 team 定位的帧; server 在
+ * welcome.features 声明支持。任一侧缺席回落单绑定行为。
+ */
+export const HOOK_FEATURE_MULTI_TEAM = 'multi-team';
+
+/** Both peers must advertise this before using provider.bind.* frames. */
+export const HOOK_FEATURE_PROVIDER_BIND = 'provider-bind-v1';
+
+/** Both peers must advertise this before using provider.prefs.* frames. */
+export const HOOK_FEATURE_PROVIDER_PREFS = 'provider-prefs-v1';
+
+/** Both peers must advertise this before using provider.behavior.* frames. */
+export const HOOK_FEATURE_PROVIDER_BEHAVIOR = 'provider-behavior-v1';
+
+/** Both peers must advertise this before query.kind=sessions is used. */
+export const HOOK_FEATURE_SESSION_PICKER = 'session-picker-v1';
+
+/** Server capability announcing that its provider registry enables Telegram. */
+export const HOOK_FEATURE_PROVIDER_TELEGRAM = 'provider:telegram';
+
+/** Server capability announcing that its provider registry enables X (Twitter). */
+export const HOOK_FEATURE_PROVIDER_X = 'provider:x';
+
+/**
+ * server 支持 hello.lifecycleAnnouncement 与 lifecycle.preference,可由
+ * desktop 设置页即时控制该设备的 Slack Bot 上下线私信。
+ */
+export const HOOK_FEATURE_LIFECYCLE_ANNOUNCEMENT = 'lifecycle-announcement-v1';
+
+/** lifecycle.preference(desktop -> server): 即时更新本设备的通知偏好。 */
+export interface LifecyclePreferencePayload {
+ enabled: boolean;
+}
+
+/**
+ * welcome.features 能力标识: server 支持 turn.reopen(见文件头第 18 条)——
+ * 能把一条已收口消息重新挂到续跑轮的新 requestId 上。desktop 仅在本标识出现
+ * 时才登记续跑记账并发帧; 缺席则维持旧行为(渠道消息停在失败上)。
+ */
+export const HOOK_FEATURE_TURN_REOPEN = 'turn-reopen-v1';
+
+/**
+ * 双向能力标识:server 会在收到普通 turn.end 后回 turn.delivery,并以
+ * accepted 明确接管重试责任。续跑轮仍遵循 turn-reopen 的“断连即终局”,
+ * 不进入本回执与重放链路。
+ */
+export const HOOK_FEATURE_TURN_DELIVERY = 'turn-delivery-v1';
+
+// ── 阶段 20: 消息操作动词(msg.op) —— 内容面上收客户端 ─────────────────────────
+
+/**
+ * 双向能力标识: 双方都宣告后, desktop 用 msg.op 直接驱动渠道消息形态,
+ * server 退为**哑执行器**(只做 lane 授权、全局限速与 API 调用, 不解释内容)。
+ *
+ * 为什么要这条轴: 现有 turn.progress / turn.end 是按「turn 阶段」切的 ——
+ * 客户端产文本快照、服务端决定它长什么样(分块、发还是编辑、卡片形态、
+ * 表情、媒体组)。于是任何呈现改进都要协议 + 服务端 + 客户端三仓联发。
+ * 正确的轴是**内容面(客户端) vs 投递面(服务端)**: 消息形态由客户端全权决定,
+ * 服务端只保留多租户授权、跨租户共享 token 的限速预算、终稿必达与离线自治。
+ *
+ * 兼容: 缺席本标识时 desktop 继续走 turn.progress / turn.end 旧路径, 服务端
+ * 保留旧渲染栈, 老客户端逐字节无感知。**仅 telegram provider 先行**——
+ * Slack / X 的渲染路径不接入本动词集(它们的形态契约由 Dash 重构后的实现持有,
+ * 不在本轴的搬迁范围)。
+ */
+export const HOOK_FEATURE_MESSAGE_OPS = 'msg-op-v1';
+
+/** msg.op 的作用域: 服务端据此校验该设备是否有权操作这条 lane。 */
+export interface MessageOpScope {
+ /**
+ * 目标渠道会话(与 task.dispatch 的 externalKey 同一命名空间)。
+ *
+ * **这是本动词集唯一的授权锚点, 也是唯一的寻址依据。** 服务端必须由它反查
+ * 自己那份 lane 记录, 从记录里取实际的 chat / topic —— 不接受客户端直接指定
+ * 目标聊天。否则一台被攻陷或有 bug 的桌面就能往任意 chat_id 发消息, 越过它
+ * 自己 lane 的边界。lane 不存在或不属于该设备的绑定 principal 时一律拒绝执行。
+ */
+ externalKey: string;
+}
+
+/**
+ * 一次消息操作的具体动作。
+ *
+ * 设计约束(与「哑执行器」互为定义):
+ * - 形态参数已经是**最终形态**: 文本是渲染好的正文, 分块由客户端切好,
+ * 服务端不再分块、不再套模板、不再补文案;
+ * - 每个动作自带 `opId`(客户端生成, 全局唯一)。服务端按 opId 幂等:
+ * 重复收到同一 opId 一律返回首次结果, 不重复调用 Bot API —— 这是断连
+ * 重发下不产生重复消息的**唯一**依据(Telegram 没有发送端幂等键)。
+ *
+ * 服务端不变量(两条, 缺一即安全漏洞):
+ * 1. **寻址**: 目标 chat / topic 只能由 `scope.externalKey` 反查服务端自己
+ * 的 lane 记录得到, 不读客户端任何输入(见 MessageOpScope)。
+ * 2. **归属**: `edit` / `delete` / `react` 引用的 messageId 必须经服务端核验
+ * 确属该 lane —— 它只能是本 lane 先前 `send` 的产物, 或该 lane 收到的
+ * 入站消息。少了这一条, 这套动词就是一个能编辑、删除、标记**任意**消息的
+ * 后门: messageId 在 Telegram 里只是个自增序号, 猜得到。
+ */
+export type MessageOpAction =
+ | {
+ kind: 'send';
+ /** 已渲染的最终正文(客户端已分块; 服务端不再切)。 */
+ text: string;
+ /** 回复锚点: 目标渠道的原生 message id。 */
+ replyToMessageId?: string | null;
+ /** 客户端决定的呈现档位; 服务端按能力降级但不改内容。 */
+ tier?: 'rich' | 'html' | 'plain';
+ silent?: boolean;
+ /** 该消息挂的按钮(语义与形态都由客户端定, 服务端原样下发)。 */
+ buttons?: MessageOpButton[][];
+ }
+ | {
+ kind: 'edit';
+ messageId: string;
+ text: string;
+ tier?: 'rich' | 'html' | 'plain';
+ buttons?: MessageOpButton[][];
+ }
+ | { kind: 'delete'; messageId: string }
+ | {
+ kind: 'react';
+ targetMessageId: string;
+ /** 空串 = 撤销该消息上本 bot 的表情。 */
+ emoji: string;
+ big?: boolean;
+ }
+ | { kind: 'typing' }
+ | {
+ kind: 'media';
+ items: MessageOpMediaItem[];
+ /** 2 张以上连续图片是否合成原生相册(客户端决定)。 */
+ album?: boolean;
+ replyToMessageId?: string | null;
+ };
+
+export interface MessageOpButton {
+ /** 客户端生成的回调 token; 服务端只做透传与一次性消费, 不解释语义。 */
+ token: string;
+ label: string;
+}
+
+export interface MessageOpMediaItem {
+ name: string;
+ mimeType: string;
+ dataBase64: string;
+ caption?: string;
+}
+
+/**
+ * msg.op(desktop -> server): 驱动一次渠道消息操作。
+ *
+ * 服务端职责边界(哑执行器):
+ * 1. 校验 scope.externalKey 落在该设备的绑定内(多租户授权, 不可下放客户端);
+ * 2. 排进该 bot token 的全局限速队列, 尊重完整 retry_after(跨租户共享预算,
+ * 必须中心化);
+ * 3. 调用 Bot API, 按 opId 幂等;
+ * 4. 回 msg.op.result 带上渠道 message id。
+ * 除此之外**不解释内容**: 不分块、不套文案、不判断该发还是该编辑。
+ */
+export interface MessageOpPayload {
+ /** 客户端生成的幂等键, 全局唯一; 重发同一 opId 不产生第二条消息。 */
+ opId: string;
+ /** 归属的 turn(用于日志关联与 lane 授权); 非 turn 语境可省略。 */
+ requestId?: string;
+ scope: MessageOpScope;
+ action: MessageOpAction;
+}
+
+/**
+ * msg.op.result(server -> desktop): 一次消息操作的回执。
+ *
+ * `messageId` 是客户端做后续 edit / delete / react 的**唯一**依据 —— 没有它,
+ * 整个动词集只能发不能改。失败时 `error` 说明原因; `retryAfterMs` 非空表示
+ * 服务端限速队列建议的等待(客户端据此排后续 op, 不自行加固定上限)。
+ */
+export interface MessageOpResultPayload {
+ opId: string;
+ ok: boolean;
+ /** send / media 成功时渠道返回的 message id(media 相册返回首条)。 */
+ messageId?: string | null;
+ /** 相册等一次产出多条时的完整 id 列表。 */
+ messageIds?: string[];
+ error?: string | null;
+ retryAfterMs?: number | null;
+}
+
+/**
+ * 内置「对话」伪工作目录的保留别名。desktop 恒把它放进 hello / query 的
+ * workspaces 清单首位(绑定到它的任务以无项目目录的对话模式运行), 真实
+ * 目录别名不许撞名(desktop 侧校验)。server 据此识别伪目录: 清单里只剩
+ * 本别名(用户没配任何真实目录)时不走「单目录自动绑」捷径, 仍发选择卡
+ * 让用户显式确认, 并提示去桌面端配置真实目录。
+ */
+export const HOOK_CHAT_WORKSPACE_ALIAS = 'chat';
+
+/**
+ * tool.request(desktop -> server): 调用 server 侧 Slack 网关工具。
+ * tool 为开放集合(当前约定 'status' / 'listTools' / 'callTool'), server
+ * 不认识的值回 UNKNOWN_TOOL 错误而非丢帧 —— 网关工具演进不需要协议升级。
+ */
+export interface ToolRequestPayload {
+ /** desktop 生成的关联 id; tool.response.replyTo 回显配对。 */
+ requestId: string;
+ /** 网关工具名(开放集合)。 */
+ tool: string;
+ /** 工具参数(如 callTool 的 { name, arguments }); 省略 = 无参。 */
+ args?: Record<string, unknown>;
+ /**
+ * (multi-team)以哪个 workspace 的绑定身份执行。缺省/null = 设备唯一
+ * 绑定; 多绑定设备缺省时 server 拒绝猜测, 回结构化错误 AMBIGUOUS_TEAM
+ * —— 以错误身份向错误 workspace 发消息是本帧族最重的串台风险(规则 9)。
+ */
+ teamId?: string | null;
+}
+
+/**
+ * 网关工具的结构化错误。code 是机器可读错误码(如 NOT_BOUND / NO_USER_TOKEN /
+ * UNKNOWN_TOOL / TOKEN_EXPIRED / RATE_LIMITED), desktop 按 code 分支提示,
+ * message 仅人类可读补充 —— 两端都不得解析 message 做逻辑(规则 9)。
+ */
+export interface ToolErrorShape {
+ code: string;
+ message: string;
+}
+
+/**
+ * tool.response(server -> desktop): tool.request 的应答。
+ * 字段联动(parse 强制): ok=false 时 error 必须为非空 {code, message};
+ * ok=true 时 error 必须缺席或 null(result 形状由具体工具约定, 协议不限)。
+ */
+export interface ToolResponsePayload {
+ /** 回显 tool.request.requestId。 */
+ replyTo: string;
+ ok: boolean;
+ /** ok=true 时的结果(任意 JSON; listTools/callTool 透传 MCP 结果语义)。 */
+ result?: unknown;
+ /** ok=false 时的结构化错误。 */
+ error?: ToolErrorShape | null;
+}
+
+// ── 阶段 14: 群消息中继(group-relay-v1) ─────────────────────────────────────
+
+/**
+ * 双向能力标识: 群消息实时中继。desktop 在 hello.features 声明会消费
+ * group.message 帧(本地维护群上下文窗口); server 在 welcome.features 声明
+ * 支持。任一侧缺席则 server 不转发, desktop 无群上下文(引用注入不受影响)。
+ *
+ * 设计边界(2026-07-28 决策): 群聊内容**不得驻留在 server**(内存亦不允许),
+ * server 收到群消息后对已声明本能力的成员桌面转发即弃; 滚动窗口、增量游标与
+ * 上下文拼装全部在 desktop 本地完成 —— 与 Slack 通道「平台即存储」同构,
+ * Telegram 无历史 API, 存储方为用户自己的设备。
+ */
+export const HOOK_FEATURE_GROUP_RELAY = 'group-relay-v1';
+
+/**
+ * group.message 接收方代际标识。双方同时声明后,server 必须按实际扇出目标
+ * 填充 recipient,desktop 必须与当前 confirmed binding 精确匹配后才可入窗。
+ * 这是独立能力而不是静默改写 group-relay-v1:旧帧没有可信接收方身份,
+ * 新 desktop 对缺席本能力的 server 只能安全降级为不落群历史。
+ */
+export const HOOK_FEATURE_GROUP_RELAY_RECIPIENT = 'group-relay-recipient-v1';
+
+/**
+ * group.message 的发送者标识(display name 为主)。
+ * id / username 均可选(旧生产端不发时省略, 向后兼容): 新生产端(阶段 19
+ * 起, provider.behavior 需要按发送者匹配群白名单以外的场景)可附带平台
+ * user id 与 @handle。二者按 Telegram 当前实际契约收紧校验(group.message
+ * 本身仍是开放 provider 集合, 但这两个新字段目前只有 Telegram 生产端会填,
+ * 形状即按 Telegram 定义; 未来若有其它 provider 要填这两个字段且形状不同,
+ * 需要重新评估这里的校验, 而不是放宽成万能字符串):
+ * - id: Telegram 数字 user id 的规范十进制正整数字符串(无前导零,在 Bot API
+ * 52-bit 范围内), 见 GROUP_MESSAGE_AUTHOR_ID_PATTERN;
+ * - username: Telegram @handle, 仅 [A-Za-z0-9_],1~32 位, 见
+ * GROUP_MESSAGE_AUTHOR_USERNAME_PATTERN。
+ */
+export interface GroupMessageAuthor {
+ name: string;
+ /** 是否为 bot(含 Cindy 自身出站回复的回流条目)。 */
+ isBot?: boolean;
+ /** Telegram 数字 user id 的规范十进制正整数字符串(52-bit 范围内); 拿不到时省略。 */
+ id?: string;
+ /** Telegram @handle(不含 @ 前缀, [A-Za-z0-9_]{1,32}); 拿不到时省略。 */
+ username?: string;
+}
+
+/** server 针对单个 desktop 扇出 group.message 时的权威接收方绑定。 */
+export interface GroupMessageRecipient {
+ bindingId: string;
+ principalId: string;
+}
+
+/**
+ * group.message(server -> desktop): 把一条群消息实时转发给该群已知绑定
+ * 成员的桌面, fire-and-forget(无 ack, 桌面离线即丢 —— 零驻留的固有代价)。
+ * chatId/threadId/messageId 是反查 id: task.dispatch 的引用块与桌面窗口
+ * 条目按同一组 id 关联, prompt 缺失上下文时 agent 可按 id 查本地窗口兜底。
+ * 一次性凭证(如 Telegram 绑定深链 /start <token>)由 server 过滤, 不转发。
+ */
+export interface GroupMessagePayload {
+ /** IM 平台标识(开放集合, 当前 'telegram')。 */
+ provider: string;
+ /**
+ * 本帧实际路由到的绑定代际;仅在双方协商
+ * HOOK_FEATURE_GROUP_RELAY_RECIPIENT 后必填。旧生产端缺省以保持 wire 兼容。
+ */
+ recipient?: GroupMessageRecipient;
+ chatId: string;
+ /** forum topic / thread id; null = 主群流。 */
+ threadId: string | null;
+ messageId: string;
+ /** 群显示名; null = 未知。 */
+ chatName: string | null;
+ author: GroupMessageAuthor;
+ /** 正文(生产端截断后 ≤4k 字符; 可为空字符串, 如纯附件消息)。 */
+ text: string;
+ /** 附件文件名列表(仅名字, 不携带字节; 桌面窗口行内标注用)。 */
+ fileNames?: string[];
+ /** 消息在 IM 平台的发送时刻(unix ms)。 */
+ sentAt: number;
+}
+
+// ── 消息联合 ─────────────────────────────────────────────────────────────────
+
+export type HookHelloMessage = HookEnvelope<'hello', HelloPayload>;
+export type HookWelcomeMessage = HookEnvelope<'welcome', WelcomePayload>;
+export type HookPingMessage = HookEnvelope<'ping', PingPayload>;
+export type HookPongMessage = HookEnvelope<'pong', PongPayload>;
+export type HookTaskDispatchMessage = HookEnvelope<'task.dispatch', TaskDispatchPayload>;
+export type HookTaskAckMessage = HookEnvelope<'task.ack', TaskAckPayload>;
+export type HookTurnEndMessage = HookEnvelope<'turn.end', TurnEndPayload>;
+export type HookTurnDeliveryMessage = HookEnvelope<'turn.delivery', TurnDeliveryPayload>;
+export type HookTurnProgressMessage = HookEnvelope<'turn.progress', TurnProgressPayload>;
+export type HookMessageOpMessage = HookEnvelope<'msg.op', MessageOpPayload>;
+export type HookMessageOpResultMessage = HookEnvelope<'msg.op.result', MessageOpResultPayload>;
+export type HookTurnReopenMessage = HookEnvelope<'turn.reopen', TurnReopenPayload>;
+export type HookBindStartMessage = HookEnvelope<'bind.start', BindStartPayload>;
+export type HookBindUpdateMessage = HookEnvelope<'bind.update', BindUpdatePayload>;
+export type HookBindRevokeMessage = HookEnvelope<'bind.revoke', BindRevokePayload>;
+export type HookQueryRequestMessage = HookEnvelope<'query.request', QueryRequestPayload>;
+export type HookQueryResponseMessage = HookEnvelope<'query.response', QueryResponsePayload>;
+export type HookTaskCancelMessage = HookEnvelope<'task.cancel', TaskCancelPayload>;
+export type HookSessionArchiveMessage = HookEnvelope<'session.archive', SessionArchivePayload>;
+export type HookInteractionRequestMessage = HookEnvelope<
+ 'interaction.request',
+ InteractionRequestPayload
+>;
+export type HookInteractionDecisionMessage = HookEnvelope<
+ 'interaction.decision',
+ InteractionDecisionPayload
+>;
+export type HookInteractionCancelMessage = HookEnvelope<
+ 'interaction.cancel',
+ InteractionCancelPayload
+>;
+export type HookPrefsGetMessage = HookEnvelope<'prefs.get', PrefsGetPayload>;
+export type HookPrefsSetMessage = HookEnvelope<'prefs.set', PrefsSetPayload>;
+export type HookPrefsStateMessage = HookEnvelope<'prefs.state', PrefsStatePayload>;
+export type HookToolRequestMessage = HookEnvelope<'tool.request', ToolRequestPayload>;
+export type HookToolResponseMessage = HookEnvelope<'tool.response', ToolResponsePayload>;
+export type HookBindStateMessage = HookEnvelope<'bind.state', BindStatePayload>;
+export type HookProviderBindStartMessage = HookEnvelope<
+ 'provider.bind.start',
+ ProviderBindStartPayload
+>;
+export type HookProviderBindCancelMessage = HookEnvelope<
+ 'provider.bind.cancel',
+ ProviderBindCancelPayload
+>;
+export type HookProviderBindRevokeMessage = HookEnvelope<
+ 'provider.bind.revoke',
+ ProviderBindRevokePayload
+>;
+export type HookProviderBindUpdateMessage = HookEnvelope<
+ 'provider.bind.update',
+ ProviderBindUpdatePayload
+>;
+export type HookProviderBindStateMessage = HookEnvelope<
+ 'provider.bind.state',
+ ProviderBindStatePayload
+>;
+export type HookProviderPrefsGetMessage = HookEnvelope<
+ 'provider.prefs.get',
+ ProviderPrefsGetPayload
+>;
+export type HookProviderPrefsSetMessage = HookEnvelope<
+ 'provider.prefs.set',
+ ProviderPrefsSetPayload
+>;
+export type HookProviderPrefsStateMessage = HookEnvelope<
+ 'provider.prefs.state',
+ ProviderPrefsStatePayload
+>;
+export type HookGroupMessageMessage = HookEnvelope<'group.message', GroupMessagePayload>;
+export type HookLifecyclePreferenceMessage = HookEnvelope<
+ 'lifecycle.preference',
+ LifecyclePreferencePayload
+>;
+export type HookProviderBehaviorGetMessage = HookEnvelope<
+ 'provider.behavior.get',
+ ProviderBehaviorGetPayload
+>;
+export type HookProviderBehaviorSetMessage = HookEnvelope<
+ 'provider.behavior.set',
+ ProviderBehaviorSetPayload
+>;
+export type HookProviderBehaviorStateMessage = HookEnvelope<
+ 'provider.behavior.state',
+ ProviderBehaviorStatePayload
+>;
+
+/** 全部合法消息的判别联合(按 `type` 判别)。 */
+export type HookMessage =
+ | HookHelloMessage
+ | HookWelcomeMessage
+ | HookPingMessage
+ | HookPongMessage
+ | HookTaskDispatchMessage
+ | HookTaskAckMessage
+ | HookTurnEndMessage
+ | HookTurnDeliveryMessage
+ | HookTurnProgressMessage
+ | HookTurnReopenMessage
+ | HookBindStartMessage
+ | HookBindUpdateMessage
+ | HookBindRevokeMessage
+ | HookQueryRequestMessage
+ | HookQueryResponseMessage
+ | HookTaskCancelMessage
+ | HookSessionArchiveMessage
+ | HookInteractionRequestMessage
+ | HookInteractionDecisionMessage
+ | HookInteractionCancelMessage
+ | HookPrefsGetMessage
+ | HookPrefsSetMessage
+ | HookPrefsStateMessage
+ | HookToolRequestMessage
+ | HookToolResponseMessage
+ | HookBindStateMessage
+ | HookProviderBindStartMessage
+ | HookProviderBindCancelMessage
+ | HookProviderBindRevokeMessage
+ | HookProviderBindUpdateMessage
+ | HookProviderBindStateMessage
+ | HookProviderPrefsGetMessage
+ | HookProviderPrefsSetMessage
+ | HookProviderPrefsStateMessage
+ | HookGroupMessageMessage
+ | HookLifecyclePreferenceMessage
+ | HookProviderBehaviorGetMessage
+ | HookProviderBehaviorSetMessage
+ | HookProviderBehaviorStateMessage
+ | HookMessageOpMessage
+ | HookMessageOpResultMessage;
+
+/** parseHookMessage 的结果 —— 不抛异常, 坏帧以 error 字符串描述具体原因。 */
+export type HookParseResult = { ok: true; message: HookMessage } | { ok: false; error: string };
diff --git a/packages/slack-hook-protocol/tsconfig.json b/packages/slack-hook-protocol/tsconfig.json
new file mode 100644
index 0000000000..fefb71da01
--- /dev/null
+++ b/packages/slack-hook-protocol/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ESNext",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "noEmit": true,
+ "sourceMap": true,
+ "baseUrl": "."
+ },
+ "include": ["src/**/*"]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 94b5fbaf0a..ae1e7f1521 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -100,9 +100,6 @@ importers:
'@cindy/mcps':
specifier: workspace:*
version: link:../../packages/lizi-mcps
- '@cindy/model-access-protocol':
- specifier: workspace:*
- version: link:../../cindy-protocol/packages/model-access-protocol
'@cindy/model-providers':
specifier: workspace:*
version: link:../../packages/model-providers
@@ -111,7 +108,7 @@ importers:
version: link:../../packages/orca-workflow
'@cindy/plugin-protocol':
specifier: workspace:*
- version: link:../../cindy-protocol/packages/plugin-protocol
+ version: link:../../packages/plugin-protocol
'@cindy/remote-file-service':
specifier: workspace:*
version: link:../../packages/remote-file-service
@@ -123,7 +120,7 @@ importers:
version: link:../../packages/responses-chat-bridge
'@cindy/slack-hook-protocol':
specifier: workspace:*
- version: link:../../cindy-protocol/packages/slack-hook-protocol
+ version: link:../../packages/slack-hook-protocol
'@cindy/voice-input-core':
specifier: workspace:*
version: link:../../packages/voice-input-core
@@ -736,42 +733,6 @@ importers:
specifier: ^3.2.4
- cindy-protocol/packages/device-link-protocol:
- devDependencies:
- typescript:
- specifier: ^5.7.0
- version: 5.9.3
-
- cindy-protocol/packages/model-access-protocol:
- devDependencies:
- typescript:
- specifier: ^5.7.0
- version: 5.9.3
- vitest:
- specifier: ^3.2.4
-
- cindy-protocol/packages/plugin-protocol:
- devDependencies:
- typescript:
- specifier: ^5.7.0
- version: 5.9.3
- vitest:
- specifier: ^3.2.4
-
- cindy-protocol/packages/slack-hook-protocol:
- devDependencies:
- '@types/node':
- specifier: '*'
- version: 25.9.5
- typescript:
- specifier: ^5.7.0
- version: 5.9.3
- vitest:
- specifier: ^3.2.4
-
packages/anthropic-compat-proxy:
devDependencies:
'@eslint/js':
@@ -877,7 +838,7 @@ importers:
dependencies:
'@cindy/plugin-protocol':
specifier: workspace:*
- version: link:../../cindy-protocol/packages/plugin-protocol
+ version: link:../plugin-protocol
'@modelcontextprotocol/sdk':
specifier: ^1.29.0
version: 1.29.0([email protected])
@@ -899,7 +860,7 @@ importers:
dependencies:
'@cindy/device-link-protocol':
specifier: workspace:*
- version: link:../../cindy-protocol/packages/device-link-protocol
+ version: link:../device-link-protocol
devDependencies:
'@types/node':
specifier: '*'
@@ -911,6 +872,12 @@ importers:
specifier: ^3.2.4
+ packages/device-link-protocol:
+ devDependencies:
+ typescript:
+ specifier: ^5.7.0
+ version: 5.9.3
+
packages/embedding-client:
devDependencies:
'@types/node':
@@ -1212,10 +1179,6 @@ importers:
packages/model-providers:
- dependencies:
- '@cindy/model-access-protocol':
- specifier: workspace:*
- version: link:../../cindy-protocol/packages/model-access-protocol
devDependencies:
'@types/node':
specifier: '*'
@@ -1261,6 +1224,18 @@ importers:
specifier: ^3.2.4
+ packages/plugin-protocol:
+ devDependencies:
+ '@types/node':
+ specifier: '*'
+ version: 25.9.5
+ typescript:
+ specifier: ^5.7.0
+ version: 5.9.3
+ vitest:
+ specifier: ^3.2.4
+
packages/project-context:
dependencies:
chalk:
@@ -1386,6 +1361,18 @@ importers:
specifier: ^3.2.4
+ packages/slack-hook-protocol:
+ devDependencies:
+ '@types/node':
+ specifier: '*'
+ version: 25.9.5
+ typescript:
+ specifier: ^5.7.0
+ version: 5.9.3
+ vitest:
+ specifier: ^3.2.4
+
packages/voice-input-core:
devDependencies:
'@eslint/js':
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 0b9e3bb692..3ff5faaaf5 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -1,4 +1,3 @@
packages:
- "apps/*"
- "packages/*"
- - "cindy-protocol/packages/*"
diff --git a/scripts/__tests__/check-submodule-forward.test.mjs b/scripts/__tests__/check-submodule-forward.test.mjs
deleted file mode 100644
index 094984e729..0000000000
--- a/scripts/__tests__/check-submodule-forward.test.mjs
+++ /dev/null
@@ -1,351 +0,0 @@
-import assert from 'node:assert/strict';
-import fs from 'node:fs';
-import os from 'node:os';
-import path from 'node:path';
-import { execFileSync } from 'node:child_process';
-import test from 'node:test';
-
-import {
- classifyProtocolRelation,
- validatePublishedProtocolHead,
- validateSubmoduleForward,
-} from '../check-submodule-forward.mjs';
-
-function git(repo, ...args) {
- return execFileSync('git', args, { cwd: repo, encoding: 'utf-8' }).trim();
-}
-
-function commitTree(repo, tree, parent, message) {
- const args = ['commit-tree', tree];
- if (parent) args.push('-p', parent);
- return execFileSync('git', args, {
- cwd: repo,
- encoding: 'utf-8',
- input: `${message}\n`,
- env: {
- ...process.env,
- GIT_AUTHOR_NAME: 'Protocol Guard Test',
- GIT_AUTHOR_EMAIL: '[email protected]',
- GIT_COMMITTER_NAME: 'Protocol Guard Test',
- GIT_COMMITTER_EMAIL: '[email protected]',
- },
- }).trim();
-}
-
-function fixture() {
- const repo = fs.mkdtempSync(
- path.join(os.tmpdir(), 'cindy-protocol-forward-'),
- );
- git(repo, 'init', '-b', 'main');
- git(repo, 'config', 'user.name', 'Protocol Guard Test');
- git(repo, 'config', 'user.email', '[email protected]');
- fs.writeFileSync(path.join(repo, 'protocol.txt'), 'one\n');
- git(repo, 'add', '.');
- git(repo, 'commit', '-m', 'one');
- const one = git(repo, 'rev-parse', 'HEAD');
- fs.writeFileSync(path.join(repo, 'protocol.txt'), 'two\n');
- git(repo, 'commit', '-am', 'two');
- const two = git(repo, 'rev-parse', 'HEAD');
- git(repo, 'checkout', '-b', 'fork', one);
- fs.writeFileSync(path.join(repo, 'fork.txt'), 'fork\n');
- git(repo, 'add', '.');
- git(repo, 'commit', '-m', 'fork');
- const fork = git(repo, 'rev-parse', 'HEAD');
- return { repo, one, two, fork };
-}
-
-function setPublishedMain(repo, oid) {
- git(repo, 'update-ref', 'refs/remotes/origin/main', oid);
-}
-
-function setPublishedTag(repo, name, oid) {
- git(repo, 'update-ref', `refs/tags/client-baseline-${name}`, oid);
-}
-
-test('classifies unchanged, forward, rollback and diverged protocol gitlinks', () => {
- const f = fixture();
- try {
- assert.equal(classifyProtocolRelation(f.repo, f.one, f.one), 'unchanged');
- assert.equal(classifyProtocolRelation(f.repo, f.one, f.two), 'forward');
- assert.equal(classifyProtocolRelation(f.repo, f.two, f.one), 'rollback');
- assert.equal(classifyProtocolRelation(f.repo, f.two, f.fork), 'diverged');
- } finally {
- fs.rmSync(f.repo, { recursive: true, force: true });
- }
-});
-
-test('accepts an unreachable base only for a strict equivalent ancestor', () => {
- const f = fixture();
- try {
- const tree = git(f.repo, 'rev-parse', `${f.one}^{tree}`);
- const duplicate = commitTree(f.repo, tree, f.one, 'duplicate');
- const head = commitTree(f.repo, tree, duplicate, 'head');
- const baseOid = 'a'.repeat(40);
- const metadata = new Map([[baseOid, { parents: [f.one], tree }]]);
- assert.equal(
- classifyProtocolRelation(f.repo, baseOid, head, {
- unreachableBaseMetadata: metadata,
- }),
- 'forward',
- );
- } finally {
- fs.rmSync(f.repo, { recursive: true, force: true });
- }
-});
-
-test('accepts an available base with an equivalent head ancestor', () => {
- const f = fixture();
- try {
- const tree = git(f.repo, 'rev-parse', `${f.one}^{tree}`);
- const duplicate = commitTree(f.repo, tree, null, 'duplicate');
- const head = commitTree(f.repo, tree, duplicate, 'head');
- assert.equal(classifyProtocolRelation(f.repo, f.one, head), 'forward');
- } finally {
- fs.rmSync(f.repo, { recursive: true, force: true });
- }
-});
-
-test('rejects matching tree when the parent list differs', () => {
- const f = fixture();
- try {
- const tree = git(f.repo, 'rev-parse', `${f.one}^{tree}`);
- const candidate = commitTree(
- f.repo,
- tree,
- f.one,
- 'same tree, different parent',
- );
- const baseOid = 'b'.repeat(40);
- const metadata = new Map([[baseOid, { parents: [f.two], tree }]]);
- assert.throws(
- () =>
- classifyProtocolRelation(f.repo, baseOid, candidate, {
- unreachableBaseMetadata: metadata,
- }),
- /无法读取协议 base commit/,
- );
- } finally {
- fs.rmSync(f.repo, { recursive: true, force: true });
- }
-});
-
-test('classifies reachable same-tree different-parent history as diverged', () => {
- const f = fixture();
- try {
- const tree = git(f.repo, 'rev-parse', `${f.two}^{tree}`);
- const duplicate = commitTree(
- f.repo,
- git(f.repo, 'rev-parse', `${f.one}^{tree}`),
- null,
- 'duplicate root',
- );
- const candidate = commitTree(
- f.repo,
- tree,
- duplicate,
- 'same tree, different parent',
- );
- assert.equal(
- classifyProtocolRelation(f.repo, f.two, candidate),
- 'diverged',
- );
- } finally {
- fs.rmSync(f.repo, { recursive: true, force: true });
- }
-});
-
-test('rejects a feature-only head before ancestry classification', () => {
- const f = fixture();
- try {
- setPublishedMain(f.repo, f.two);
- assert.throws(
- () => validatePublishedProtocolHead(f.repo, f.fork, { ci: false }),
- /未合入协议仓 main,也未打 client-baseline tag/,
- );
- } finally {
- fs.rmSync(f.repo, { recursive: true, force: true });
- }
-});
-
-test('allows a head published on protocol main', () => {
- const f = fixture();
- try {
- setPublishedMain(f.repo, f.two);
- assert.doesNotThrow(() =>
- validatePublishedProtocolHead(f.repo, f.two, { ci: false }),
- );
- } finally {
- fs.rmSync(f.repo, { recursive: true, force: true });
- }
-});
-
-test('allows a head published only by a client-baseline tag', () => {
- const f = fixture();
- try {
- setPublishedMain(f.repo, f.one);
- setPublishedTag(f.repo, 'feature', f.fork);
- assert.doesNotThrow(() =>
- validatePublishedProtocolHead(f.repo, f.fork, { ci: false }),
- );
- } finally {
- fs.rmSync(f.repo, { recursive: true, force: true });
- }
-});
-
-test('fetches a published head missing from the local protocol clone', () => {
- const publisher = fixture();
- const bare = fs.mkdtempSync(
- path.join(os.tmpdir(), 'cindy-protocol-published-'),
- );
- const local = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-protocol-local-'));
- try {
- git(bare, 'init', '--bare');
- git(publisher.repo, 'remote', 'add', 'origin', bare);
- git(publisher.repo, 'push', 'origin', 'main');
- git(
- publisher.repo,
- 'push',
- 'origin',
- `${publisher.one}:refs/heads/test-baseline`,
- );
- git(local, 'init', '-b', 'main');
- git(local, 'remote', 'add', 'origin', bare);
- git(local, 'fetch', 'origin', 'test-baseline');
- git(publisher.repo, 'push', 'origin', '--delete', 'test-baseline');
- assert.throws(() =>
- git(local, 'cat-file', '-e', `${publisher.two}^{commit}`),
- );
- assert.doesNotThrow(() =>
- validatePublishedProtocolHead(local, publisher.two, { ci: true }),
- );
- } finally {
- fs.rmSync(publisher.repo, { recursive: true, force: true });
- fs.rmSync(bare, { recursive: true, force: true });
- fs.rmSync(local, { recursive: true, force: true });
- }
-});
-
-test('falls back to local origin/main when baseline fetch is unavailable', () => {
- const f = fixture();
- try {
- setPublishedMain(f.repo, f.two);
- git(f.repo, 'remote', 'add', 'origin', '/definitely/missing/protocol.git');
- const warnings = [];
- assert.doesNotThrow(() =>
- validatePublishedProtocolHead(f.repo, f.two, {
- ci: false,
- warn: (message) => warnings.push(message),
- }),
- );
- assert.equal(warnings.length, 1);
- assert.match(warnings[0], /退用本地 origin\/main/);
- } finally {
- fs.rmSync(f.repo, { recursive: true, force: true });
- }
-});
-
-test('fails closed when an unavailable base cannot be fetched', () => {
- const f = fixture();
- try {
- const baseOid = 'c'.repeat(40);
- assert.throws(
- () => classifyProtocolRelation(f.repo, baseOid, f.two),
- /无法读取协议 base commit/,
- );
- } finally {
- fs.rmSync(f.repo, { recursive: true, force: true });
- }
-});
-
-test('validateSubmoduleForward does not treat a failed base fetch as forward', () => {
- const outer = fs.mkdtempSync(
- path.join(os.tmpdir(), 'cindy-protocol-forward-parent-'),
- );
- const protocol = path.join(outer, 'cindy-protocol');
- fs.mkdirSync(protocol);
- try {
- git(outer, 'init', '-b', 'main');
- git(outer, 'config', 'user.name', 'Protocol Guard Test');
- git(outer, 'config', 'user.email', '[email protected]');
- git(protocol, 'init', '-b', 'main');
- git(protocol, 'config', 'user.name', 'Protocol Guard Test');
- git(protocol, 'config', 'user.email', '[email protected]');
- fs.writeFileSync(path.join(protocol, 'protocol.txt'), 'head\n');
- git(protocol, 'add', '.');
- git(protocol, 'commit', '-m', 'head');
- const head = git(protocol, 'rev-parse', 'HEAD');
- setPublishedMain(protocol, head);
- const base = 'd'.repeat(40);
- git(
- outer,
- 'update-index',
- '--add',
- '--cacheinfo',
- `160000,${base},cindy-protocol`,
- );
- git(outer, 'commit', '-m', 'base');
- git(
- outer,
- 'update-index',
- '--add',
- '--cacheinfo',
- `160000,${head},cindy-protocol`,
- );
- git(outer, 'commit', '-m', 'head');
- const warnings = [];
- assert.throws(
- () =>
- validateSubmoduleForward(outer, 'HEAD~1', 'HEAD', {
- ci: false,
- warn: (message) => warnings.push(message),
- }),
- /无法读取协议 base commit/,
- );
- assert.equal(warnings.length, 1);
- } finally {
- fs.rmSync(outer, { recursive: true, force: true });
- }
-});
-
-test('allows the unchanged dangling historical baseline without fetching it', () => {
- const outer = fs.mkdtempSync(
- path.join(os.tmpdir(), 'cindy-protocol-unchanged-dangling-'),
- );
- const protocol = path.join(outer, 'cindy-protocol');
- fs.mkdirSync(protocol);
- try {
- git(outer, 'init', '-b', 'main');
- git(outer, 'config', 'user.name', 'Protocol Guard Test');
- git(outer, 'config', 'user.email', '[email protected]');
- git(protocol, 'init', '-b', 'main');
- git(
- protocol,
- 'remote',
- 'add',
- 'origin',
- '/definitely/missing/protocol.git',
- );
- const dangling = '27ef29dcb0df1b0f346c82cb7fbb81e9da536a79';
- assert.throws(() =>
- git(protocol, 'cat-file', '-e', `${dangling}^{commit}`),
- );
- git(
- outer,
- 'update-index',
- '--add',
- '--cacheinfo',
- `160000,${dangling},cindy-protocol`,
- );
- git(outer, 'commit', '-m', 'dangling baseline');
-
- assert.deepEqual(validateSubmoduleForward(outer, 'HEAD', 'HEAD'), {
- baseRef: 'HEAD',
- headRef: 'HEAD',
- baseOid: dangling,
- headOid: dangling,
- relation: 'unchanged',
- });
- } finally {
- fs.rmSync(outer, { recursive: true, force: true });
- }
-});
diff --git a/scripts/__tests__/dev-docs-contract.test.mjs b/scripts/__tests__/dev-docs-contract.test.mjs
index 53b81346a2..4b3099c443 100644
--- a/scripts/__tests__/dev-docs-contract.test.mjs
+++ b/scripts/__tests__/dev-docs-contract.test.mjs
@@ -319,10 +319,6 @@ test("client CI runs Linux checks and complete unit shards in parallel behind st
assert.match(shards, /^ fail-fast: false$/m);
assert.match(shards, /^ shard: \[1, 2\]$/m);
assert.match(shards, /^ XDT_UNIT_TEST_SHARD: \$\{\{ matrix\.shard \}\}\/2$/m);
- assert.match(shards, /^ - name: Reject cindy-protocol rollback or divergence$/m);
- assert.match(shards, /^ if: \$\{\{ github\.event_name == 'pull_request' \}\}$/m);
- assert.match(shards, /^ CINDY_PROTOCOL_BASE_REF: \$\{\{ github\.event\.pull_request\.base\.sha \}\}$/m);
- assert.match(shards, /^ run: node scripts\/check-submodule-forward\.mjs$/m);
assert.match(shards, /^ run: pnpm exec node scripts\/test-workspaces\.mjs --tier unit$/m);
assert.doesNotMatch(shards, /pnpm test:(?:unit|runner)/);
diff --git a/scripts/__tests__/ensure-deps.test.mjs b/scripts/__tests__/ensure-deps.test.mjs
index d660a0c310..e152e0c050 100644
--- a/scripts/__tests__/ensure-deps.test.mjs
+++ b/scripts/__tests__/ensure-deps.test.mjs
@@ -4,30 +4,7 @@ import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
-import {
- findMissingSubmoduleWorkspaceFiles,
- resolvePnpmInstallInvocation,
-} from '../ensure-deps.mjs';
-
-test('detects an uninitialized protocol submodule before pnpm scans workspaces', () => {
- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-ensure-deps-'));
- try {
- assert.deepEqual(findMissingSubmoduleWorkspaceFiles(root), [
- 'cindy-protocol/packages/device-link-protocol/package.json',
- 'cindy-protocol/packages/slack-hook-protocol/package.json',
- ]);
-
- for (const packageName of ['device-link-protocol', 'slack-hook-protocol']) {
- const packageDir = path.join(root, 'cindy-protocol', 'packages', packageName);
- fs.mkdirSync(packageDir, { recursive: true });
- fs.writeFileSync(path.join(packageDir, 'package.json'), '{}\n');
- }
-
- assert.deepEqual(findMissingSubmoduleWorkspaceFiles(root), []);
- } finally {
- fs.rmSync(root, { recursive: true, force: true });
- }
-});
+import { resolvePnpmInstallInvocation } from '../ensure-deps.mjs';
test('runs a native pnpm binary directly instead of feeding it to node', () => {
// pnpm 的原生二进制发行版把 npm_execpath 指向可执行文件本身;交给 node 会抛
diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjs
index 71e772a1d8..c409fee5e7 100644
--- a/scripts/__tests__/test-workspaces.test.mjs
+++ b/scripts/__tests__/test-workspaces.test.mjs
@@ -117,58 +117,12 @@ test("client CI owns the complete Desktop Git integration tier", () => {
);
});
-test("client CI builds model-access protocol before consumer checks", () => {
+test("client CI no longer builds model-access protocol for consumers", () => {
const workflow = fs.readFileSync(
path.join(ROOT, ".github", "workflows", "ci.yml"),
"utf8",
).replace(/\r\n/g, "\n");
- const jobs = [
- {
- name: "verify-checks",
- body: workflow.match(/\n verify-checks:\n([\s\S]*?)\n linux-unit-shards:/)?.[1],
- consumerCommand: "run: pnpm --filter desktop typecheck",
- },
- {
- name: "linux-unit-shards",
- body: workflow.match(/\n linux-unit-shards:\n([\s\S]*?)\n verify:/)?.[1],
- consumerCommand: "run: pnpm exec node scripts/test-workspaces.mjs --tier unit",
- },
- {
- name: "windows-unit-shards",
- body: workflow.match(/\n windows-unit-shards:\n([\s\S]*?)\n windows-unit:/)?.[1],
- consumerCommand: "run: pnpm test:unit",
- },
- ];
-
- for (const { name, body, consumerCommand } of jobs) {
- assert.ok(body, `client CI must define the ${name} job`);
- const installIndex = body.indexOf("run: pnpm install --frozen-lockfile");
- const buildIndex = body.indexOf(
- "run: pnpm --filter @cindy/model-access-protocol build",
- );
- const consumerIndex = body.indexOf(consumerCommand);
- assert.ok(installIndex >= 0, `${name} must install dependencies`);
- assert.ok(buildIndex > installIndex, `${name} must build protocol after install`);
- assert.ok(
- consumerIndex > buildIndex,
- `${name} must build protocol before consumer checks`,
- );
- }
-});
-
-test("Linux unit shards reject unsafe protocol gitlinks before installing dependencies", () => {
- const workflow = fs.readFileSync(
- path.join(ROOT, ".github", "workflows", "ci.yml"),
- "utf8",
- ).replace(/\r\n/g, "\n");
- const body = workflow.match(/\n linux-unit-shards:\n([\s\S]*?)\n verify:/)?.[1];
- assert.ok(body, "client CI must define Linux unit shards");
- const fetchIndex = body.indexOf("git submodule update --init --force --recursive -- cindy-protocol");
- const guardIndex = body.indexOf("run: node scripts/check-submodule-forward.mjs");
- const installIndex = body.indexOf("run: pnpm install --frozen-lockfile");
- assert.ok(fetchIndex >= 0, "Linux unit shards must fetch cindy-protocol");
- assert.ok(guardIndex > fetchIndex, "Linux unit shards must validate the fetched protocol gitlink");
- assert.ok(installIndex > guardIndex, "Linux unit shards must reject unsafe gitlinks before install");
+ assert.doesNotMatch(workflow, /pnpm --filter @cindy\/model-access-protocol build/);
});
test("help groups copyable desktop, binary, and Mobile workflows", async () => {
@@ -805,14 +759,14 @@ test("filterRunsByWorkspace selects by manifest name or cwd and supports exclude
);
});
-test("expandWorkspacePatterns supports nested submodule package roots", () => {
+test("expandWorkspacePatterns supports nested workspace package roots", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "workspace-patterns-"));
try {
- const pkg = path.join(root, "cindy-protocol", "packages", "protocol-a");
+ const pkg = path.join(root, "vendor", "protocols", "protocol-a");
fs.mkdirSync(pkg, { recursive: true });
fs.writeFileSync(path.join(pkg, "package.json"), '{"name":"protocol-a"}\n');
- assert.deepEqual(expandWorkspacePatterns(root, ["cindy-protocol/packages/*"]), [
- "cindy-protocol/packages/protocol-a",
+ assert.deepEqual(expandWorkspacePatterns(root, ["vendor/protocols/*"]), [
+ "vendor/protocols/protocol-a",
]);
} finally {
fs.rmSync(root, { recursive: true, force: true });
diff --git a/scripts/check-submodule-forward.mjs b/scripts/check-submodule-forward.mjs
deleted file mode 100644
index 6330ea80af..0000000000
--- a/scripts/check-submodule-forward.mjs
+++ /dev/null
@@ -1,315 +0,0 @@
-#!/usr/bin/env node
-
-import path from 'node:path';
-import { spawnSync } from 'node:child_process';
-import { fileURLToPath } from 'node:url';
-
-const SUBMODULE_PATH = 'cindy-protocol';
-
-// 27ef29d was a historical duplicate of e6c95b0. The published-head guard below
-// prevents future gitlinks from depending on unpublished commits, so this map
-// must not grow. Keep this one verified entry only to move the already-dangling
-// main baseline onto the equivalent published history.
-const UNREACHABLE_BASE_COMMITS = new Map([
- [
- '27ef29dcb0df1b0f346c82cb7fbb81e9da536a79',
- {
- parents: ['0cb87cb52427fbebd8a3d85a271847d06bfb2ac6'],
- tree: '2b38c6510e36f5c95de9b58b683e0e9c3c896b94',
- },
- ],
-]);
-
-function git(cwd, args, { allowFailure = false } = {}) {
- const result = spawnSync('git', args, {
- cwd,
- encoding: 'utf-8',
- stdio: ['ignore', 'pipe', 'pipe'],
- });
- if (!allowFailure && result.status !== 0) {
- const detail = (result.stderr || result.stdout || '').trim();
- throw new Error(
- `git ${args.join(' ')} failed${detail ? `: ${detail}` : ''}`,
- );
- }
- return result;
-}
-
-export function readGitlink(repoRoot, ref, submodulePath = SUBMODULE_PATH) {
- const result = git(repoRoot, ['ls-tree', ref, '--', submodulePath]);
- const match = result.stdout
- .trim()
- .match(/^160000 commit ([0-9a-f]{40})\t(.+)$/i);
- if (!match || match[2] !== submodulePath) {
- throw new Error(`${ref} 中缺少合法的 ${submodulePath} gitlink`);
- }
- return match[1].toLowerCase();
-}
-
-function isAncestor(repoRoot, older, newer) {
- const result = git(repoRoot, ['merge-base', '--is-ancestor', older, newer], {
- allowFailure: true,
- });
- if (result.status === 0) return true;
- if (result.status === 1) return false;
- const detail = (result.stderr || result.stdout || '').trim();
- throw new Error(
- `无法比较协议历史 ${older.slice(0, 10)}..${newer.slice(0, 10)}${detail ? `: ${detail}` : ''}`,
- );
-}
-
-function hasCommit(repoRoot, oid) {
- return (
- git(repoRoot, ['cat-file', '-e', `${oid}^{commit}`], {
- allowFailure: true,
- }).status === 0
- );
-}
-
-function hasRef(repoRoot, ref) {
- return (
- git(repoRoot, ['show-ref', '--verify', '--quiet', ref], {
- allowFailure: true,
- }).status === 0
- );
-}
-
-function readPublishedBaselineRefs(protocolRepo) {
- const refs = [];
- if (hasRef(protocolRepo, 'refs/remotes/origin/main')) {
- refs.push('refs/remotes/origin/main');
- }
- const tags = git(protocolRepo, [
- 'for-each-ref',
- '--format=%(refname)',
- 'refs/tags/client-baseline-*',
- ])
- .stdout.trim()
- .split('\n')
- .filter(Boolean);
- return refs.concat(tags);
-}
-
-function refreshPublishedBaselines(protocolRepo, { ci, warn }) {
- const mainFetch = git(
- protocolRepo,
- ['fetch', '--no-tags', 'origin', 'main:refs/remotes/origin/main'],
- { allowFailure: true },
- );
- const tagFetch = git(
- protocolRepo,
- [
- 'fetch',
- '--no-tags',
- 'origin',
- 'refs/tags/client-baseline-*:refs/tags/client-baseline-*',
- ],
- { allowFailure: true },
- );
- if (mainFetch.status === 0 && tagFetch.status === 0) return;
-
- const detail = [mainFetch, tagFetch]
- .filter((result) => result.status !== 0)
- .map((result) => (result.stderr || result.stdout || '').trim())
- .filter(Boolean)
- .join('; ');
- if (ci || !hasRef(protocolRepo, 'refs/remotes/origin/main')) {
- throw new Error(`无法刷新协议仓公开基线${detail ? `: ${detail}` : ''}`);
- }
- warn(
- `无法刷新协议仓公开基线,退用本地 origin/main 与已有 client-baseline tags${detail ? `: ${detail}` : ''}`,
- );
-}
-
-export function validatePublishedProtocolHead(
- protocolRepo,
- headOid,
- { ci = Boolean(process.env.CI), warn = console.warn } = {},
-) {
- refreshPublishedBaselines(protocolRepo, { ci, warn });
- if (!hasCommit(protocolRepo, headOid)) {
- const headFetch = git(
- protocolRepo,
- ['fetch', '--no-tags', 'origin', headOid],
- { allowFailure: true },
- );
- if (!hasCommit(protocolRepo, headOid)) {
- const detail = (headFetch.stderr || headFetch.stdout || '').trim();
- throw new Error(
- `无法读取协议 head commit ${headOid}${detail ? `: ${detail}` : ''}`,
- );
- }
- }
- const baselineRefs = readPublishedBaselineRefs(protocolRepo);
- if (baselineRefs.some((ref) => isAncestor(protocolRepo, headOid, ref))) {
- return;
- }
- throw new Error(
- `协议提交 ${headOid} 未合入协议仓 main,也未打 client-baseline tag;先完成协议仓发布再更新 gitlink`,
- );
-}
-
-function parseCommitMetadata(output) {
- const [oid, tree, parents = ''] = output.split('\0');
- return { oid, tree, parents: parents ? parents.split(' ') : [] };
-}
-
-function readCommitMetadata(protocolRepo, oid) {
- const result = git(protocolRepo, [
- 'show',
- '-s',
- '--format=%H%x00%T%x00%P%x00',
- oid,
- ]);
- const metadata = parseCommitMetadata(result.stdout.trimEnd());
- return { tree: metadata.tree, parents: metadata.parents };
-}
-
-function readAncestorMetadata(protocolRepo, headOid) {
- const result = git(protocolRepo, [
- 'log',
- '--format=%H%x00%T%x00%P%x01',
- headOid,
- ]);
- return result.stdout
- .trimEnd()
- .split('\x01')
- .filter(Boolean)
- .map(parseCommitMetadata);
-}
-
-function hasEquivalentAncestor(
- protocolRepo,
- baseOid,
- headOid,
- metadata = UNREACHABLE_BASE_COMMITS,
-) {
- const expected =
- git(protocolRepo, ['cat-file', '-e', `${baseOid}^{commit}`], {
- allowFailure: true,
- }).status === 0
- ? readCommitMetadata(protocolRepo, baseOid)
- : metadata.get(baseOid);
- if (!expected) return false;
-
- return readAncestorMetadata(protocolRepo, headOid).some((candidate) => {
- if (candidate.oid === baseOid) return false;
- return (
- candidate.tree === expected.tree &&
- candidate.parents.length === expected.parents.length &&
- candidate.parents.every(
- (parent, index) => parent === expected.parents[index],
- )
- );
- });
-}
-
-export function classifyProtocolRelation(
- protocolRepo,
- baseOid,
- headOid,
- { unreachableBaseMetadata = UNREACHABLE_BASE_COMMITS } = {},
-) {
- if (baseOid === headOid) return 'unchanged';
- const baseAvailable =
- git(protocolRepo, ['cat-file', '-e', `${baseOid}^{commit}`], {
- allowFailure: true,
- }).status === 0;
- if (
- !baseAvailable &&
- hasEquivalentAncestor(
- protocolRepo,
- baseOid,
- headOid,
- unreachableBaseMetadata,
- )
- )
- return 'forward';
- if (!baseAvailable) throw new Error(`无法读取协议 base commit ${baseOid}`);
- if (isAncestor(protocolRepo, baseOid, headOid)) return 'forward';
- if (isAncestor(protocolRepo, headOid, baseOid)) return 'rollback';
- if (
- hasEquivalentAncestor(
- protocolRepo,
- baseOid,
- headOid,
- unreachableBaseMetadata,
- )
- )
- return 'forward';
- return 'diverged';
-}
-
-function ensureCommit(
- protocolRepo,
- oid,
- { allowUnreachableBase = false } = {},
-) {
- if (
- git(protocolRepo, ['cat-file', '-e', `${oid}^{commit}`], {
- allowFailure: true,
- }).status === 0
- ) {
- return true;
- }
- if (allowUnreachableBase && UNREACHABLE_BASE_COMMITS.has(oid)) return false;
- return (
- git(protocolRepo, ['fetch', '--no-tags', 'origin', oid], {
- allowFailure: true,
- }).status === 0
- );
-}
-
-export function validateSubmoduleForward(
- repoRoot,
- baseRef,
- headRef = 'HEAD',
- options = {},
-) {
- const baseOid = readGitlink(repoRoot, baseRef);
- const headOid = readGitlink(repoRoot, headRef);
- const protocolRepo = path.join(repoRoot, SUBMODULE_PATH);
- const unchangedHistoricalBaseline =
- baseOid === headOid && UNREACHABLE_BASE_COMMITS.has(headOid);
- if (unchangedHistoricalBaseline) {
- return { baseRef, headRef, baseOid, headOid, relation: 'unchanged' };
- }
- validatePublishedProtocolHead(protocolRepo, headOid, options);
- ensureCommit(protocolRepo, baseOid, { allowUnreachableBase: true });
- if (!ensureCommit(protocolRepo, headOid)) {
- throw new Error(`无法准备协议 head commit ${headOid}`);
- }
- const relation = classifyProtocolRelation(protocolRepo, baseOid, headOid);
- return { baseRef, headRef, baseOid, headOid, relation };
-}
-
-function main() {
- const repoRoot = process.cwd();
- const baseRef = process.env.CINDY_PROTOCOL_BASE_REF || 'origin/main';
- const result = validateSubmoduleForward(repoRoot, baseRef);
- const summary = `${result.baseOid.slice(0, 10)} -> ${result.headOid.slice(0, 10)}`;
- if (result.relation === 'rollback') {
- console.error(
- `::error file=cindy-protocol::cindy-protocol gitlink 回退: ${summary}`,
- );
- process.exitCode = 1;
- return;
- }
- if (result.relation === 'diverged') {
- console.error(
- `::error file=cindy-protocol::cindy-protocol gitlink 与 base 分叉: ${summary}`,
- );
- process.exitCode = 1;
- return;
- }
- console.log(
- `cindy-protocol gitlink ${result.relation === 'forward' ? '前进' : '未变化'}: ${summary}`,
- );
-}
-
-if (
- process.argv[1] &&
- path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
-) {
- main();
-}
diff --git a/scripts/ensure-deps.mjs b/scripts/ensure-deps.mjs
index 6c0018b780..91d4358a17 100644
--- a/scripts/ensure-deps.mjs
+++ b/scripts/ensure-deps.mjs
@@ -2,12 +2,11 @@
/**
* ensure-deps — 启动/构建/发布前的依赖守护
*
- * 五道检查(任一失败都会自动修复):
- * 1. 协议 submodule — 先初始化 cindy-protocol,避免 pnpm 少发现 workspace
- * 2. Lockfile 同步性 — 比对 pnpm-lock.yaml 与 node_modules/.modules.yaml 的 mtime
- * 3. 关键依赖完整性 — 确认 workspace / native / binary 依赖的 package.json 存在
- * 4. Electron binary 完整性 — 确认 electron postinstall 已完整解出 dist binary
- * 5. native ABI 隔离 — root 保持 Node ABI,Electron cache 单独准备 native binding
+ * 四道检查(任一失败都会自动修复):
+ * 1. Lockfile 同步性 — 比对 pnpm-lock.yaml 与 node_modules/.modules.yaml 的 mtime
+ * 2. 关键依赖完整性 — 确认 workspace / native / binary 依赖的 package.json 存在
+ * 3. Electron binary 完整性 — 确认 electron postinstall 已完整解出 dist binary
+ * 4. native ABI 隔离 — root 保持 Node ABI,Electron cache 单独准备 native binding
*
* 关于 hoisted 模式:项目 .npmrc 指定 node-linker=hoisted,绝大多数依赖被平铺到根
* node_modules,但原生二进制包(electron、protobufjs 等)必须留
@@ -57,11 +56,6 @@ const CRITICAL_DEPS = [
];
const WORKSPACE_CRITICAL_DEPS = CRITICAL_DEPS.slice(0, 2);
-const SUBMODULE_WORKSPACE_FILES = Object.freeze([
- 'cindy-protocol/packages/device-link-protocol/package.json',
- 'cindy-protocol/packages/slack-hook-protocol/package.json',
-]);
-
// 子包下的残缺目录 —— 这些本不该存在于子包 node_modules(pnpm 10 会 hoist 到根),
// 但某些 postinstall 残留(例如 electron postinstall 解压的 dist/)可能会让这些路径
// 看起来"存在"。Node.js 的 require 解析会卡在残缺目录(有路径但没 package.json)
@@ -227,48 +221,6 @@ function findBrokenDeps(deps = CRITICAL_DEPS) {
return broken;
}
-/** Protocol package manifests that a complete checkout must expose to pnpm. */
-export function findMissingSubmoduleWorkspaceFiles(root = ROOT) {
- return SUBMODULE_WORKSPACE_FILES.filter((relativePath) => !fs.existsSync(path.join(root, relativePath)));
-}
-
-function ensureSubmoduleWorkspaces() {
- // `.gitmodules` 的 URL 会随仓库迁移变化,但 Git 会把已初始化 submodule 的旧 URL
- // 缓存在本地 `.git/config`。每次依赖检查先同步一次(纯本地操作),确保老 checkout
- // 在 pull 后也改从当前公开仓拉取,而不是继续访问已经退役的旧组织仓库。
- const syncResult = spawnSync('git', ['submodule', 'sync', '--', 'cindy-protocol'], {
- cwd: ROOT,
- stdio: 'inherit',
- });
- if (syncResult.error || syncResult.status !== 0) {
- warn('协议 submodule URL 同步失败;将继续使用当前 checkout,缺失时初始化仍会 fail closed');
- }
-
- const missing = findMissingSubmoduleWorkspaceFiles();
- if (missing.length === 0) return;
-
- warn(`协议 workspace 缺失:${missing.join(', ')}`);
- // 只初始化协议 submodule(pnpm workspace 依赖它)。内建插件不再作为 submodule
- // 随客户端源码分发,插件通过 SkillHub 或手动安装。
- log('运行 git submodule update --init cindy-protocol ...');
- const result = spawnSync('git', ['submodule', 'update', '--init', '--recursive', '--', 'cindy-protocol'], {
- cwd: ROOT,
- stdio: 'inherit',
- });
- if (result.error || result.status !== 0) {
- if (result.error) err(result.error.message);
- err('协议 submodule 初始化失败;未继续安装依赖,避免生成不完整的 pnpm workspace');
- process.exit(result.status ?? 1);
- }
-
- const stillMissing = findMissingSubmoduleWorkspaceFiles();
- if (stillMissing.length > 0) {
- err(`submodule 初始化后协议 workspace 仍缺失:${stillMissing.join(', ')}`);
- process.exit(1);
- }
- log('协议 submodule 已就绪');
-}
-
function ensureWorkspaceOnlyDependencies() {
const broken = findBrokenDeps(WORKSPACE_CRITICAL_DEPS);
const lockIssue = reasonLockfileOutOfSync();
@@ -780,8 +732,6 @@ function ensureElectronNativeBinding(electronVersion, electronArch) {
}
function main() {
- ensureSubmoduleWorkspaces();
-
if (process.argv.slice(2).includes('--workspace-only')) {
ensureWorkspaceOnlyDependencies();
return;
diff --git a/scripts/generate-third-party-notices.mjs b/scripts/generate-third-party-notices.mjs
index 8dfca14e74..af98bfc013 100644
--- a/scripts/generate-third-party-notices.mjs
+++ b/scripts/generate-third-party-notices.mjs
@@ -42,7 +42,7 @@ const CARGO_MANIFEST = path.join(
/** 与 pnpm-workspace.yaml 的客户端 workspace 范围保持一致。 */
function discoverWorkspaceDirs() {
const dirs = [];
- for (const parentName of ["apps", "packages", "cindy-protocol/packages"]) {
+ for (const parentName of ["apps", "packages"]) {
const parentDir = path.join(REPO_ROOT, parentName);
for (const entry of fs.readdirSync(parentDir, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjs
index 0266210fac..3a6d50412e 100644
--- a/scripts/test-workspaces.config.mjs
+++ b/scripts/test-workspaces.config.mjs
@@ -249,9 +249,8 @@ export default {
requiredUnitWorkspace('@cindy/remote-file-service', 'packages/remote-file-service'),
requiredUnitWorkspace('@cindy/voice-input-core', 'packages/voice-input-core'),
requiredUnitWorkspace('@cindy/wechat-ilink', 'packages/wechat-ilink'),
- noCollectableWorkspace('@cindy/device-link-protocol', 'cindy-protocol/packages/device-link-protocol'),
- requiredUnitWorkspace('@cindy/model-access-protocol', 'cindy-protocol/packages/model-access-protocol'),
- requiredUnitWorkspace('@cindy/plugin-protocol', 'cindy-protocol/packages/plugin-protocol'),
- requiredUnitWorkspace('@cindy/slack-hook-protocol', 'cindy-protocol/packages/slack-hook-protocol'),
+ noCollectableWorkspace('@cindy/device-link-protocol', 'packages/device-link-protocol'),
+ requiredUnitWorkspace('@cindy/plugin-protocol', 'packages/plugin-protocol'),
+ requiredUnitWorkspace('@cindy/slack-hook-protocol', 'packages/slack-hook-protocol'),
],
};