feat: 三省六部 v0.1 插件骨架(宿主十席绑定 + Web/dsh-go 源码)
宿主:十席固定编制、项目级独立会话严格创建/恢复/失败重试/跨项目隔离、模型走 agent.model.select 不写 profile、动态 systemPrompt、POST /api/sansheng。Web 工作台与 dsh-go 原生面板源码按契约实现。含 34 项 fake-ctx 测试。未安装到任何 DSH profile。
|
|
@ -0,0 +1,4 @@
|
|||
ds-bot/
|
||||
node_modules/
|
||||
*.tmp
|
||||
*.log
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
# DS Bot 与 OpenMausBot:架构拆解总览
|
||||
|
||||
分析日期:2026-11-14。分析对象为本地克隆源码,不是在线产品演示。
|
||||
|
||||
- DS Bot:提交 `a66cc737`,插件与桌面应用清单版本均为 `0.3.6`。
|
||||
- OpenMausBot:提交 `a6cd67c78`,清单版本为 `0.1.158`。
|
||||
- 三省六部新项目从 `v0.0.1` 开始,这是我们自己的版本,不应把下载来的两个上游项目版本强改为 `0.0.1`。
|
||||
|
||||
本轮只做源码阅读与架构分析,没有安装依赖、启动应用、验证外部账号或修改上游业务代码。文中“已实现”表示找到源码接线与实现,不代表已在本机实测所有功能。
|
||||
|
||||
## 1. 先把几个词分清
|
||||
|
||||
| 层 | 大白话 | 举例 |
|
||||
|---|---|---|
|
||||
| 前端 | 人看见、点击、输入的界面 | Bot 列表、聊天框、设置、审批卡、电脑画面 |
|
||||
| 后端 | 收消息、决定交给谁、保存数据和协调执行的服务 | 建 Bot、发群消息、排队、记账、读写历史 |
|
||||
| Agent 执行引擎 | 真正和模型来回交互、调用工具干活的部分 | DSH 会话循环、Claude/Codex 适配器、API 模型循环 |
|
||||
| 工具与集成 | Agent 能使用的具体能力 | 文件、浏览器、电脑、邮件、MCP、外部应用 |
|
||||
| 桌面壳 | 把网页装进桌面窗口,并接入操作系统 | Electron 窗口、更新、托盘、进程管理 |
|
||||
| 数据层 | 关掉软件之后还保存的东西 | Bot 配置、聊天记录、记忆、任务与运行状态 |
|
||||
|
||||
前端显示“正在工作”,不等于前端自己在跑模型;聊天界面、任务调度和模型执行是不同层。
|
||||
|
||||
## 2. 两个项目最根本的区别
|
||||
|
||||
**DS Bot 是 DSH 之上的 Bot 团队产品层;OpenMausBot 是拥有自己服务端和执行适配层的独立应用。**
|
||||
|
||||
| 对比项 | DS Bot | OpenMausBot |
|
||||
|---|---|---|
|
||||
| 产品形态 | DSH 插件,另有捆绑固定 DSH 的桌面应用 | 独立应用,网页与桌面共用核心服务 |
|
||||
| 前端 | 插件版 JavaScript + React 接入 DSH;桌面另有 React 页面;手机为 Expo / React Native | TypeScript + React,独立应用根组件;Vite 构建 |
|
||||
| 后端 | DSH 插件的宿主模块,使用注入服务 | Node.js + TypeScript,自建 HTTP 服务 |
|
||||
| 执行核心 | 普通 DSH Session 执行循环;另有本地 Agent 接入模块 | 自己的驱动接口,连接多种 CLI/ACP 引擎及 API 模型 |
|
||||
| 前后端通信 | `POST api/bot` 发送 endpoint/payload;会话还依赖 DSH 服务 | 自己的 HTTP API 与事件流;部分实时连接另用 WebSocket |
|
||||
| 桌面 | Electron;启动隔离的 DSH 环境 | Electron;启动自己的服务,并桥接设备与窗口能力 |
|
||||
| 核心状态 | Bot 团队状态 JSON + DSH 管理的会话;另有索引/记忆/附件 | 配置文件 + SQLite 数据库 + 事件与文件资源 |
|
||||
| 运行时依赖 | 离不开 DSH 插件服务接口 | 不依赖 DSH;部分能力依赖额外引擎、系统组件或云服务 |
|
||||
|
||||
证据入口:[DS Bot 插件装配](../ds-bot/ds-bot/index.js#L55)、[DS Bot 浏览器入口](../ds-bot/ds-bot/src/client/index.js#L61)、[DS Bot 请求封装](../ds-bot/ds-bot/src/client/api.js#L4)、[DS Bot 桌面清单](../ds-bot/app/package.json#L25)、[OpenMausBot 网页入口](../OpenMausBot/src/main.tsx#L1)、[OpenMausBot 后端入口](../OpenMausBot/server/index.ts#L11)、[OpenMausBot 驱动注册](../OpenMausBot/server/drivers/builtIn.ts#L32)。
|
||||
|
||||
## 3. DS Bot:从外到内怎么分
|
||||
|
||||
```text
|
||||
用户
|
||||
→ DS Bot 的 React 界面
|
||||
→ DSH 界面插槽 / 会话界面 + api/bot 业务请求
|
||||
→ DS Bot 宿主模块:Bot 名册、群聊、投递、权限、记忆、计划
|
||||
→ DSH 会话与执行服务
|
||||
→ 模型、工具和外部集成
|
||||
|
||||
桌面版:独立 React 页面 → Bot API / SSE → 带 DS Bot 插件的精简 DSH engine。
|
||||
手机版:Expo / React Native 页面 → 配对与加密链路 → 同一个 Bot 后端。
|
||||
```
|
||||
|
||||
最外层克隆目录和里面的插件目录都叫 ds-bot,所以存在双层同名目录,这是上游布局。
|
||||
|
||||
| 源码区 | 职责 |
|
||||
|---|---|
|
||||
| [插件目录](../ds-bot/ds-bot/) | 真正装入 DSH 的功能包 |
|
||||
| [前端源码](../ds-bot/ds-bot/src/client/) | 团队侧栏、聊天呈现、设置、功能面板 |
|
||||
| [后端源码](../ds-bot/ds-bot/src/host/) | Bot 生命周期、调度、消息、工具与存储 |
|
||||
| [共享源码](../ds-bot/ds-bot/src/shared/) | 前后端共用的规则与结构 |
|
||||
| [桌面应用](../ds-bot/app/) | 安装、窗口、独立 React 页面、固定 DSH engine |
|
||||
| [桌面前端](../ds-bot/app/ui/src/) | 桌面版独立页面,复用插件组件与样式 |
|
||||
| [手机应用](../ds-bot/mobile/) | Expo / React Native 原生客户端 |
|
||||
| [手机链路](../ds-bot/link/) | 配对加密协议与 Relay 中继 |
|
||||
| [测试](../ds-bot/ds-bot/test/) | 功能与边界测试,不属于运行时界面 |
|
||||
| [开发环境](../ds-bot/ds-bot/dev/) | 测试用 DSH、模拟模型及开发验证 |
|
||||
|
||||
桌面端不是完整 DSH Web 的简单套壳:[桌面页面入口](../ds-bot/app/ui/src/main.js#L1) 有自己的 React 根组件,[engine 配置](../ds-bot/app/engine/cordis.patch.yml#L1) 明确不装 DSH Web 前端,窗口只与 Bot API 交互。
|
||||
|
||||
[插件入口](../ds-bot/ds-bot/index.js#L63) 用一个模块列表依次安装功能,各模块通过同一个运行时对象相互调用。它是“一个宿主里很多业务模块”,不能把每个文件理解成独立后端服务。
|
||||
|
||||
[前端生成文件](../ds-bot/ds-bot/client.js) 是编译产物。后续改界面应改 [前端源码](../ds-bot/ds-bot/src/client/),再构建,而不是直接改生成文件。
|
||||
|
||||
## 4. OpenMausBot:从外到内怎么分
|
||||
|
||||
```text
|
||||
用户
|
||||
→ React 网页 / Electron 窗口
|
||||
→ 自有 HTTP API 与实时事件
|
||||
→ Node 服务:Bot、会话、群聊、权限、调度、持久化
|
||||
→ 统一驱动接口
|
||||
→ CLI / ACP / API 模型执行
|
||||
→ 电脑、浏览器、文件、MCP、外部应用等工具
|
||||
|
||||
Electron 还承担桌面启动、系统桥接与本地设备能力。
|
||||
云端与远程功能在核心聊天之外有额外的服务组件和部署条件。
|
||||
```
|
||||
|
||||
| 源码区 | 职责 |
|
||||
|---|---|
|
||||
| [网页前端](../OpenMausBot/src/) | 主应用、界面组件、状态与请求处理 |
|
||||
| [后端](../OpenMausBot/server/) | 主服务与具体业务能力 |
|
||||
| [引擎适配](../OpenMausBot/server/drivers/) | 把不同 Agent 引擎统一接到应用 |
|
||||
| [共享结构](../OpenMausBot/shared/) | 前后端之间的类型、规则和数据约定 |
|
||||
| [桌面进程](../OpenMausBot/electron/) | 窗口、启动、更新和系统桥接 |
|
||||
| [脚本](../OpenMausBot/scripts/) | 构建、控制命令与配套工具 |
|
||||
|
||||
[主界面装配](../OpenMausBot/src/App.tsx#L19) 直接接入单聊、群聊、活动、文件、电脑、虚拟机、插件、团队图、触发器等面板。[驱动注册](../OpenMausBot/server/drivers/builtIn.ts#L32) 显示它不是只接一个模型:Claude、Codex、多个 ACP Agent 以及 OpenAI-compatible 等模型 API 都走对应适配器。
|
||||
|
||||
注意:驱动是“接线转换层”,不是这些第三方引擎本身;存在适配器也不代表本机已安装引擎、已经登录或配置了有效账号。
|
||||
|
||||
还要把这些配套项目与核心后端分开看:
|
||||
|
||||
| 配套组件 | 职责与边界 |
|
||||
|---|---|
|
||||
| [手机伴随服务](../OpenMausBot/companion/package.json#L6) | 让已经配对的手机连接核心服务,不替代核心 Agent 执行 |
|
||||
| [远程中继](../OpenMausBot/relay/src/server.ts#L15) | 分别接入 host、data、phone 的 WebSocket 连接 |
|
||||
| [云主机连接器](../OpenMausBot/connector/package.json#L6) | 通过出站连接把用户自己的服务器纳入云端管理 |
|
||||
| [Cloudflare 控制平面](../OpenMausBot/cloudflare/control-plane/README.md#L3) | 云账号身份、安装归属和托管连接入口;文档明确它不存放本地 Bot、聊天与 SQLite 会话数据 |
|
||||
| [手机协议包](../OpenMausBot/packages/phone-protocol/) | 手机连接相关的共享协议约定 |
|
||||
| [文档站](../OpenMausBot/apps/docs/) | 产品文档页面,不是聊天前端 |
|
||||
|
||||
## 5. 两者都要沿着这条链理解
|
||||
|
||||
以“让两个 Bot 一起分析文件”为例:
|
||||
|
||||
1. 前端收集文字、附件和目标 Bot/群聊。
|
||||
2. 后端检查权限、工作目录和当前会话,接收或排队。
|
||||
3. 团队模块决定消息发给谁,维护上下文和协作关系。
|
||||
4. 执行引擎向模型发送输入,再调用读文件等工具。
|
||||
5. 工具结果回到执行引擎,模型继续分析或给出回答。
|
||||
6. 后端保存结果、更新状态,前端显示过程和产物。
|
||||
|
||||
DS Bot 的第 4 步主要交给 DSH;OpenMausBot 通过自己的驱动体系衔接执行。两边的界面可以长得相似,但底下的会话 ID、事件格式、权限和数据保存方式不同。
|
||||
|
||||
DS Bot 也支持本地 Agent,并非只能直接调用模型 API:[本地 Agent 入口](../ds-bot/ds-bot/src/host/local-agents/index.js#L1) 会发现 CLI、注册 DSH 模型适配器,并保存 DSH Session 与 CLI Session 的对应关系。这和 OpenMausBot 的自有驱动体系是两种接入方式。
|
||||
|
||||
DS Bot 的 JSON 保存团队状态,不代表所有数据都是 JSON:[聊天搜索索引](../ds-bot/ds-bot/src/host/chat-index.js#L48) 使用 SQLite,真正的 DSH 会话记录另由宿主管理。迁移时不能只搬团队配置文件就认为带走了全部聊天历史。
|
||||
|
||||
## 6. 对三省六部 v0.0.1 的直接意义
|
||||
|
||||
这部分是基于架构的判断,不是已经确定的实施方案。
|
||||
|
||||
- 如果继续在 DSH 内做部门团队,DS Bot 的宿主接入、角色配置、会话管理和消息协作与现有环境更接近。
|
||||
- 如果做脱离 DSH 的独立产品,OpenMausBot 的自有前后端、驱动接口和桌面管理更值得详细研究。
|
||||
- 不能把两个项目的文件夹直接拼起来就得到一个完整产品。至少要统一 Bot 身份、会话、任务、权限、事件和存储接口。
|
||||
- Main Bot/管理员权限不等于三省六部的审核、退回、执行制度;现有角色系统只是基础。
|
||||
- 一个 Bot 绑定文件夹,也不等于项目之间的配置、上下文、任务、模型与运行操作已经全部隔离。项目隔离仍需逐层设计和验收。
|
||||
- 电脑控制、云电脑、手机、邮件和外部应用均属于能力层,不能据此推断核心聊天必须启动全部外部服务。
|
||||
|
||||
## 7. 详细模块手册
|
||||
|
||||
- [DS Bot 分层与功能模块拆解](ds-bot-analysis.md)
|
||||
- [OpenMausBot 分层与功能模块拆解](openmausbot-analysis.md)
|
||||
|
||||
详细手册给出各模块的职责、源码入口、数据与通信链路、运行依赖,以及源码存在和本机实测之间的区别。
|
||||
|
|
@ -0,0 +1,106 @@
|
|||
# 三省六部 v0.0.1 客户端契约调研
|
||||
|
||||
日期:2026-11-14。只读调研;唯一新增文件为本笔记。后续任务曾短暂授权客户端实现,随后根任务改为“第一版方案 + dsh-go 样式预览”;未新增或修改客户端实现。
|
||||
|
||||
## 结论
|
||||
|
||||
Web 与 dsh-go 必须分开设计。Web 保留项目树与原生 session chat,仅追加入口及右面板;DS Bot 整套前端不可搬用,因为其显式替换 sidebar.workspaces 与多个 conversation 槽。dsh-go 是具有原生组件协议与 engine bridge 的 App;参考文档明确涉及 Android 验收,不能把响应式手机 Web 当作 dsh-go。当前已读原生桥不证明可注册桌面右 sidebar、不证明支持打开另一 session,也不提供 workspaceId。第一版原生样式只能标为概念预览,不能宣称已接线。
|
||||
|
||||
## 已读证据与版本
|
||||
|
||||
- [DS Bot manifest](../ds-bot/ds-bot/package.json):0.3.6;exports `.` → `./index.js`、`./client` → `./client.js`;`dsh.client.platform = "web"`。
|
||||
- [DS Bot 测试宿主版本](../ds-bot/ds-bot/dev/harness/package.json):`@deepseek-ai/dsh = 0.2.2-rc.1`。这是参考仓库锁定版本,不是当前宿主运行版本证明。
|
||||
- [DS Bot 客户端入口](../ds-bot/ds-bot/src/client/index.js):61–63 行 export inject/apply;104–108 行通过 workspaces.list 查询 session 所属 workspace;916–933 行 sidebarRight.openTab;982–985 行 slots 注册;1088 行 sidebar.workspaces 替换。
|
||||
- [DS Bot transport](../ds-bot/ds-bot/src/client/api.js):8–41 行。
|
||||
- 原生参考包 `@changfenhuang/dsh-genui` 0.16.0,已读其 [manifest](C:/Users/qyh15/.dsh/profiles/desktop/node_modules/@changfenhuang/dsh-genui/package.json)、[dsh-go 文档](C:/Users/qyh15/.dsh/profiles/desktop/node_modules/@changfenhuang/dsh-genui/docs/dsh-go.md)、[桥接类型](C:/Users/qyh15/.dsh/profiles/desktop/node_modules/@changfenhuang/dsh-genui/src/plugin/dsh-go-types.ts)、[面板实现](C:/Users/qyh15/.dsh/profiles/desktop/node_modules/@changfenhuang/dsh-genui/src/plugin/dsh-go-native.ts)、[只读工具卡投影](C:/Users/qyh15/.dsh/profiles/desktop/node_modules/@changfenhuang/dsh-genui/src/plugin/dsh-go-view.ts)、[原生组件编译器](C:/Users/qyh15/.dsh/profiles/desktop/node_modules/@changfenhuang/dsh-genui/src/plugin/dsh-go-compiler.ts)。仅读取 node_modules 下的包代码和文档,未读取用户配置、凭据。
|
||||
|
||||
## Web:已验证使用方式,未把未读签名当成公开保证
|
||||
|
||||
参考插件使用 `export const inject = ["sessions", "uiWorkspace", "uiConversation", "slots", "theme", "layout"]` 和 `export function apply(ctx) { ... }`。以下是已读调用,而非完成核对的宿主类型清单:
|
||||
|
||||
```js
|
||||
ctx.slots.inject(name, () => ctx.slots.register({ name, id, order, inject }, Component));
|
||||
ctx.get("sidebarRight")?.openTab("terminal");
|
||||
ctx.get("sidebarRightTabs")?.get("terminal");
|
||||
ctx.sessions.list.getSnapshot();
|
||||
ctx.sessions.binding(sessionId);
|
||||
const items = ctx.get("workspaces")?.list?.getSnapshot()?.items ?? [];
|
||||
const owner = items.find(item => item.sessionIds?.includes(sessionId))?.workspaceId;
|
||||
```
|
||||
|
||||
`sidebar.footer.action` 是参考插件已有的追加型入口用法;`sidebar.workspaces` 是其项目树替换方式,本需求禁止照搬。`sidebarRightTabs.register`、navigation 精确签名、当前 workspace 的 authoritative selection、打开 native chat 的 exact API 尚未由本轮宿主导出类型核实,不能据此写假接口。通过 sessionIds 查所属 workspace 也不能用于无 session 时随机挑第一个项目。
|
||||
|
||||
网络传输最小例(与参考插件同结构):
|
||||
|
||||
```js
|
||||
async function request(endpoint, payload, signal) {
|
||||
const res = await fetch("api/sansheng", {
|
||||
method: "POST", credentials: "same-origin",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ endpoint, payload: payload ?? null }), signal,
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const result = await res.json();
|
||||
if (!result.ok) throw new Error(result.error?.message ?? "请求失败");
|
||||
return result.value;
|
||||
}
|
||||
```
|
||||
|
||||
建议后端成功 `{ok:true,value:view}`,失败 `{ok:false,error:{code,message}}`。根 Agent 已收到此建议。请求必须捕获 projectId + generation/revision,结果到达后核对当前项目;项目变化时 abort/丢弃旧响应。此处是设计约束,未声称已实现。
|
||||
|
||||
## dsh-go:真实桥接签名与最小原生示例
|
||||
|
||||
GenUI 的类型文件对 Cordis Context 声明 `dshGo: NativeBridge`,但该文件没有独立 package export。不要 import 其内部源码。实际宿主桥是否存在应延迟注入探测:`ctx.inject(["dshGo", "sessions"], native => ...)`。这份接口是已安装公开插件的真实使用证据,不是本轮读取宿主 dshGo SDK 得到的兼容承诺。
|
||||
|
||||
```ts
|
||||
type NativeScope = { sessionId?: string; messageId?: string; callId?: string };
|
||||
type NativeEvent = { action?: string; value?: unknown; locale: string };
|
||||
type NativeCaps = { locale: string; components: string[] };
|
||||
type NativeEffect =
|
||||
| { type: "refresh"; id?: string }
|
||||
| { type: "copy" | "toast" | "insert"; text: string }
|
||||
| { type: "link"; url: string };
|
||||
|
||||
interface NativeBridge {
|
||||
panel(id: string, definition: {
|
||||
view(scope: NativeScope, caps: NativeCaps): NativeView;
|
||||
data?(scope: NativeScope, emit: (data: Record<string, unknown>) => void): () => void;
|
||||
}): () => void;
|
||||
on(id: string, handler: (scope: NativeScope, event: NativeEvent) =>
|
||||
NativeEffect[] | Promise<NativeEffect[]>): () => void;
|
||||
refresh(id: string, scope?: NativeScope): void;
|
||||
}
|
||||
```
|
||||
|
||||
最小形状示例(仅说明已读 view 节点,不代表完整插件可安装 manifest):
|
||||
|
||||
```js
|
||||
ctx.inject(["dshGo"], native => {
|
||||
native.effect(() => native.dshGo.panel("sansheng", {
|
||||
view: (scope, caps) => ({
|
||||
type: "stack", children: [
|
||||
{ type: "text", text: "三省六部" },
|
||||
{ type: "callout", tone: "info", text: scope.sessionId
|
||||
? "当前对话的十席概览" : "请先从已加载的对话打开" },
|
||||
{ type: "list", items: [{ title: "尚书省", subtitle: "统筹执行 · 待连接" }] },
|
||||
],
|
||||
}),
|
||||
}));
|
||||
});
|
||||
```
|
||||
|
||||
实际模块通过 `@deepseek-ai/dsh-session` 的 `appendPluginRecord` / `pluginRecordOf` 持久化状态;这两项缺失时展示要求 DSH 0.2.1-rc.2 或更新版本的提示。这个版本门槛针对该持久原生面板方案,不是所有 dsh-go 功能的最低版本。GenUI 文档说明 manifest 提供 composer shortcut 和 session/chat panel;本轮没有读到对应 manifest 注册定义,不能给出编造的入口注册格式。
|
||||
|
||||
## dsh-go 样式预览边界
|
||||
|
||||
真实编译器以 `stack/children` 与 `row/children` 布局,文字用 `text` 字段(不是 Web GenUI 的 content);列表 `list.items` 使用 title/subtitle/action;度量 `metric`,键值 `keyValue`,提示 `callout` tone 为 info/good/warn/bad。Web card 在转换中变成 stack,并非独立原生 CSS 卡片。
|
||||
|
||||
原生面板可用按钮、单选列表、多选组、switch、tabs、accordion、复制与确认 HTTPS 链接。单个 options 最多 8 项且标签唯一、≤80 字符、不得换行;十席不能塞一个十项 options,应按三省/六部分组或使用 list。模型可做已有选项选择;当前桥不提供自由文本/密码字段,因此不能把备注编辑或自填模型 ID 画成已经可用的原生输入框。
|
||||
|
||||
容量:tool card 8 KiB / 40 nodes / depth 6,只读;model fence 整体 JSON 16 KiB;native panel 32 KiB / 120 nodes / depth 8。自由文本、slider、ECharts、SVG/Mermaid、3D、音视频不能保持原交互。SVG 树连线不应当成原生支持;十席层次可由标题、分组 list、stack 体现。
|
||||
|
||||
原生 panel scope 无 workspaceId,effect 无 session-navigation。三栏布局、右 sidebar 扩展、当前项目读取及角色点击打开另一原生 session 均需要另外核实宿主/App契约。独立 dsh-go 预览应明确“原生组件概念布局”,不能宣称与 Web 三栏完全一致。局部 bridge 存在也不等于当前客户端就是 dsh-go。
|
||||
|
||||
## 调研覆盖限制
|
||||
|
||||
给定 `resources/app.asar/dsh` 在普通文件搜索工具中不可作为目录读取;`.dsh/dsh-runtimes` 查到的仅 runtime manifest 与 dependencies。公开 Github main tree 请求为 404,npm 包页面重定向到登录,dsh.so/docs fetch 失败,均未作为接口证据。历史 `832e265` workbench/panel 源输出被截断,因此只将其当历史参考,未把未完整读取部分认定为官方契约。没有运行或安装插件、修改宿主、读取用户 profile 配置、构建或设备验收。
|
||||
|
|
@ -0,0 +1,279 @@
|
|||
# DS Bot 实际源码架构拆解
|
||||
|
||||
> 分析日期:2026-11-14。静态只读审查;未安装依赖、未启动应用、未执行测试或仓库脚本。本文只写入工作区根目录 docs,不修改任何仓库。
|
||||
> “已实现”指存在已接入的源码,不代表本机运行验证通过。第三方服务是否可用、具体安装包能否启动,不能由本次静态审查保证。
|
||||
|
||||
## 1. 先分清两个 ds-bot
|
||||
|
||||
工作区是 C:/Users/qyh15/三省六部。外层 [ds-bot](../ds-bot/) 是整个 Git 项目;内层 [ds-bot/ds-bot](../ds-bot/ds-bot/) 是可发布的 DSH 插件包。二者不是两个重复项目。
|
||||
|
||||
已先读 [AGENTS.md:7–10](../ds-bot/AGENTS.md#L7),其中明确区分插件与桌面应用;[AGENTS.md:22–28](../ds-bot/AGENTS.md#L22) 要求使用 DSH 公共入口、不修改 DSH、生成文件不手改、不碰用户自有数据。
|
||||
|
||||
- [核心插件目录](../ds-bot/ds-bot/):Bot 团队业务、浏览器 UI、工具、存储、外部能力。
|
||||
- [桌面应用目录](../ds-bot/app/):Electron、自己的 React 页面、精简 DSH engine、安装升级和导入。
|
||||
- [手机应用目录](../ds-bot/mobile/):React Native / Expo 客户端,并非桌面网页简单缩小。
|
||||
- [加密链路目录](../ds-bot/link/):手机与电脑通信协议、配对、WebSocket Relay 服务。
|
||||
- [设计文档目录](../ds-bot/docs/plans/):已定设计与限制,不应一概当成未实现路线图。
|
||||
|
||||
**一句话架构:DS Bot 是建立在 DSH 执行引擎之上的长期机器人团队工作台。它自己管理“谁是谁、谁找谁、群里怎么工作、记住什么”,DSH 管真正的 Session、模型请求、工具执行和宿主能力。**
|
||||
|
||||
核心插件以 [index.js:55–86](../ds-bot/ds-bot/index.js#L55) 的 Cordis 风格 name / inject / apply 注册;不是一套独立 Express、FastAPI 或 Spring 后端。
|
||||
|
||||
## 2. 前端:同一批 Bot 组件,三种承载方式
|
||||
|
||||
### 2.1 嵌在 DSH Web / Desktop 的插件页面
|
||||
|
||||
框架是 React,普通 JavaScript ESM,广泛使用 createElement 而非必须依赖 JSX;例如 [sidebar.js:1–18](../ds-bot/ds-bot/src/client/sidebar.js#L1) 直接导入 React Hooks、createPortal。
|
||||
|
||||
入口为 [src/client/index.js:61–63](../ds-bot/ds-bot/src/client/index.js#L61)。它注入 sessions、uiWorkspace、uiConversation、slots、theme、layout,向 DSH 的既有界面槽位挂组件;[index.js:982–985](../ds-bot/ds-bot/src/client/index.js#L982) 展示具体 slots 注册。
|
||||
|
||||
发布入口是生成的 [client.js](../ds-bot/ds-bot/client.js),包的 exports 声明见 [package.json:24–30](../ds-bot/ds-bot/package.json#L24)。构建脚本由 [package.json:45–50](../ds-bot/ds-bot/package.json#L45) 指向 esbuild 构建;实际修改应发生在源码目录。
|
||||
|
||||
页面不是只有聊天框。入口导入已经体现这些组成:[index.js:1–32](../ds-bot/ds-bot/src/client/index.js#L1)。
|
||||
|
||||
- 侧栏、团队角色和形象:sidebar、characters、mark、themes。
|
||||
- 聊天内容与输入:cells、composer、questions、widget-cell、at-menu。
|
||||
- 群聊与工作状态:成员状态、群设置、目标状态及协作消息。
|
||||
- 设置与管理:模型、Provider、权限、记忆、定时任务、连接器、能力、用量。
|
||||
- 浏览器、电脑接管、密钥卡、临时问题与侧聊:独立面板结合聊天状态展示。
|
||||
|
||||
这些 UI 依赖后端 team view、Session 投影和动作接口;复制组件时必须带上对应数据适配层,不能只拷 CSS 就获得完整应用。
|
||||
|
||||
### 2.2 独立桌面页面
|
||||
|
||||
桌面有自己的 [app/ui/src/main.js:1–19](../ds-bot/app/ui/src/main.js#L1),导入 React、createRoot 与 App,同时直接复用核心插件的侧栏、设置、主题 CSS 和国际化代码。
|
||||
|
||||
技术依赖明确为 React 19.3.0、React DOM 19.3.0、Vite 8.3.4;另用 react-markdown、remark-gfm,见 [app/package.json:74–85](../ds-bot/app/package.json#L74)。这不是 Vue / Next.js 前端。
|
||||
|
||||
桌面自己的页面只与 Bot channel 对话:[api.js:1–2](../ds-bot/app/ui/src/api.js#L1) 写明 POST api/bot 与 api/bot/feed。实时事件通过 fetch 流读取 SSE,而非 EventSource,原因是窗口使用自己的 scheme,见 [api.js:16–29](../ds-bot/app/ui/src/api.js#L16)。
|
||||
|
||||
### 2.3 手机页面
|
||||
|
||||
手机入口由 [mobile/package.json:4](../ds-bot/mobile/package.json#L4) 指向 index.ts,App 的启动分支在 [App.tsx:122–137](../ds-bot/mobile/App.tsx#L122):身份、电脑配对、语言准备好后才进入 Linked 视图。
|
||||
|
||||
依赖为 Expo 58、React Native 0.88、React Navigation、SecureStore、相机、图片选择、生物识别等,见 [mobile/package.json:5–34](../ds-bot/mobile/package.json#L5)。这是独立原生客户端,有真实代码,但本次未构建 APK/IPA。
|
||||
|
||||
## 3. 后端入口、模块组织与 API
|
||||
|
||||
### 3.1 宿主与插件的分工
|
||||
|
||||
[index.js:56](../ds-bot/ds-bot/index.js#L56) 要求 llm、tools、systemPrompt、sessionController、sessions、sessionTitle、workspaceRegistry、connection。
|
||||
|
||||
[index.js:63–89](../ds-bot/ds-bot/index.js#L63) 按顺序调用各模块 install(rt),把共享函数放在 runtime 对象上。模块之间在运行时经 rt 调用,不是每块单独启动服务。
|
||||
|
||||
这是一种“单进程业务模块 + 宿主服务依赖注入”的组合。安装顺序影响监听器和工具顺序,入口 [index.js:58–62](../ds-bot/ds-bot/index.js#L58) 特别说明 privacy 应先拦截、usage 应后计量。
|
||||
|
||||
普通文件操作、Shell、Subagent、Web、工作流等执行器大多来自 DSH;精简 engine 的依赖清单 [engine/package.json:26–59](../ds-bot/app/engine/package.json#L26) 可以直接对照。不要把这些全算成 DS Bot 自写的执行引擎。
|
||||
|
||||
### 3.2 API 是统一动作通道
|
||||
|
||||
[channel.js:844–854](../ds-bot/ds-bot/src/host/channel.js#L844) 通过 ctx.connection.fetch.register 注册 POST route。请求 JSON 中用 endpoint + payload 选择业务动作;响应采用 ok/value 或 ok/error,见 [channel.js:55–58](../ds-bot/ds-bot/src/host/channel.js#L55)。业务错误并不都表现为不同 HTTP 状态。
|
||||
|
||||
浏览器认证复用 DSH connection cookie;不是 DS Bot 另建了一套用户登录数据库。
|
||||
|
||||
主要接口组与源码位置:
|
||||
|
||||
- 团队状态、模型、Provider、思考设置:[channel.js:238–278](../ds-bot/ds-bot/src/host/channel.js#L238)。
|
||||
- 会话读取、历史、运行统计、用量、群进展:[channel.js:287–330](../ds-bot/ds-bot/src/host/channel.js#L287)。
|
||||
- 创建修改删除 Bot、Main 身份、头像、群和工作目录:[channel.js:342–417](../ds-bot/ds-bot/src/host/channel.js#L342)。
|
||||
- 普通 DSH Agent 会话、侧栏分区:[channel.js:420–451](../ds-bot/ds-bot/src/host/channel.js#L420)。
|
||||
- 审批、停止工作、群目标、关闭交互卡:[channel.js:459–495](../ds-bot/ds-bot/src/host/channel.js#L459)。
|
||||
- 密钥操作入口从 [channel.js:503](../ds-bot/ds-bot/src/host/channel.js#L503) 开始,其他能力由同一 handler 分流到其模块。
|
||||
|
||||
实时推送另走 feed:事件序列化为 SSE,保存触发监听,并支持手机接入用的 tap,见 [feed.js:34–48](../ds-bot/ds-bot/src/host/feed.js#L34)。手机与桌面尽量复用业务视图,而不是各写一份 Bot 后端。
|
||||
|
||||
### 3.3 模型可调用的工具
|
||||
|
||||
Bot 专属工具放进 teamTools,并按 Bot Session scope 注册,而非全局暴露给所有 DSH 会话,见 [index.js:78–89](../ds-bot/ds-bot/index.js#L78)。
|
||||
|
||||
核心工具有 list_bots、message_bot、stop_bot、create_bot、update_bot、list_bot_models,见 [tools.js:80](../ds-bot/ds-bot/src/host/tools.js#L80)、[tools.js:167](../ds-bot/ds-bot/src/host/tools.js#L167)、[tools.js:298–363](../ds-bot/ds-bot/src/host/tools.js#L298)、[tools.js:453](../ds-bot/ds-bot/src/host/tools.js#L453)。
|
||||
|
||||
群管理与交互有 create_group、update_group、delete_group、post_to_group、ask_user、show_view,见 [tools.js:496–726](../ds-bot/ds-bot/src/host/tools.js#L496)。还有 group_relay、read_own_chat、read_group_chat,见 [groups.js:1–2](../ds-bot/ds-bot/src/host/groups.js#L1)。
|
||||
|
||||
能力管理工具有 list_capabilities、save_capability、delete_capability,见 [tools.js:1129–1185](../ds-bot/ds-bot/src/host/tools.js#L1129)。目标工具 group_goal 位于 [goals.js:670–709](../ds-bot/ds-bot/src/host/goals.js#L670),不是只有文档里的口头流程。
|
||||
|
||||
注意:界面有 delete-bot 动作不等于模型拥有 delete_bot 工具;用户层操作与 Bot 工具权限必须分别判断。
|
||||
|
||||
## 4. 桌面壳:真正的多进程分工
|
||||
|
||||
Electron 主入口是 [app/package.json:12](../ds-bot/app/package.json#L12) 声明的 main.mjs;[main.mjs:8](../ds-bot/app/src/main.mjs#L8) 导入 BrowserWindow、IPC、Tray、WebContentsView 等原生组件。
|
||||
|
||||
主进程负责窗口、系统托盘、文件选择、下载、浏览器视图、首次设置、导入和更新;宿主运行在独立子进程。实际 Host 创建见 [main.mjs:573–590](../ds-bot/app/src/main.mjs#L573)。
|
||||
|
||||
Host 明确把 DSH_HOME 设为应用数据目录,同时传入工作文件夹、runtime 目录、用户原 DSH 数据位置。其 app profile 不等于用户日常运行的 DSH profile。
|
||||
|
||||
[host.mjs:8–43](../ds-bot/app/src/host.mjs#L8) 调用公开 runProfile 入口并加载 layered env、profile 和应用自己的 patch。这里的 patch 是配置组合,不是修改 DSH 安装源码。
|
||||
|
||||
[engine/cordis.patch.yml:1–5](../ds-bot/app/engine/cordis.patch.yml#L1) 明确没有 DSH Web 前端:engine 只给 Bot API 提供回环 HTTP 服务、连接和 Session 执行能力。
|
||||
|
||||
Host 启动后生成 authenticatedUrl,经 IPC 回主进程,见 [host.mjs:61–72](../ds-bot/app/src/host.mjs#L61)。engine 根路由只做启动 token 换 cookie,授权后返回 204,见 [engine/index.js:7–18](../ds-bot/app/engine/index.js#L7)。
|
||||
|
||||
关闭窗口通常只是隐藏,机器人继续在后台工作;真正退出经托盘处理,见 [shell.mjs:1–15](../ds-bot/app/src/shell.mjs#L1)。这也是“长期 Bot”在桌面生命周期上的基础。
|
||||
|
||||
## 5. 一条消息到底怎么跑
|
||||
|
||||
1. 用户在 React / 手机 / IM 界面发消息;桌面到 Bot API,手机走加密链路,IM 由平台适配器转成内部请求。
|
||||
2. [channel.js:802–815](../ds-bot/ds-bot/src/host/channel.js#L802) 把 Bot 或旧分段引用解析成当前 Session,准备 capabilities,然后 sessionController.prompt(mode: queue)。
|
||||
3. DSH 解析 Agent、加载模型和工具,进入常规执行回合。DS Bot 在旁跟踪状态、注入身份/记忆/群目标等上下文。
|
||||
4. Bot 想找同伴时调用 message_bot;delivery 解析接收方 Agent,[delivery.js:10–14](../ds-bot/ds-bot/src/host/delivery.js#L10) 使用 DSH sessionController,而不是启动一个独立模型服务器。
|
||||
5. handoffs 保存上下级工作关系,子工作全部归来后把结果送回上层;见 [handoffs.js:1–7](../ds-bot/ds-bot/src/host/handoffs.js#L1)。
|
||||
6. turns 跟踪运行、失败和回报路由;feed 推 UI;需要长时记忆时由 memory 的审核/写入链处理。
|
||||
7. 上下文快满时压缩或切新 Session;旧段继续可查,见 [parts.js:1–16](../ds-bot/ds-bot/src/host/parts.js#L1)。Bot 身份不随 Session 换段消失。
|
||||
|
||||
群聊有所不同:[groups.js:4–18](../ds-bot/ds-bot/src/host/groups.js#L4) 规定 @ 同时点名的成员可并行开工;普通消息在 admin 模式只到管理员,否则按序发言;忙着做工具工作的成员不会无限卡住一轮。
|
||||
|
||||
**所以 Bot 不是一个永不更换的单 Session,群也不是把所有成员塞进一个共享模型上下文。** Bot 私聊、成员在群中的 Session、历史分段是分别管理的。
|
||||
|
||||
## 6. 大功能模块手册
|
||||
|
||||
### 6.1 身份、角色、团队和普通 Agent
|
||||
|
||||
职责:维护 Bot 名字、角色说明、模型、头像、Main 身份、群及成员。关键路径 [roster.js:1–5](../ds-bot/ds-bot/src/host/roster.js#L1),操作工具见前述 tools。
|
||||
|
||||
关系:store 持久化身份,folders 选工作路径,permissions 应用权限,parts 管 Session 换代。另有普通 DSH Agent 入口,不属于 Bot、不带团队工具,[agents.js:1–3](../ds-bot/ds-bot/src/host/agents.js#L1)。
|
||||
|
||||
Main Bot 表示更高的团队管理权限,可以有多个;它不是预设“六部职责—门下审查—尚书执行”的固定制度。部门称号可用角色说明表达,但严格业务审批链需另建状态机。
|
||||
|
||||
### 6.2 私聊协作、交接与去重
|
||||
|
||||
职责:消息派送、等待、停止、返还结果、识别正在做什么。关键路径 [delivery.js:1–14](../ds-bot/ds-bot/src/host/delivery.js#L1)、[turns.js:1–16](../ds-bot/ds-bot/src/host/turns.js#L1)、[handoffs.js:1–7](../ds-bot/ds-bot/src/host/handoffs.js#L1)。
|
||||
|
||||
requests 给调用方指定 request_id 的请求提供稳定回执与指纹,先记录再发送,未知结果不自动重投,[requests.js:1–13](../ds-bot/ds-bot/src/host/requests.js#L1)。它限制重复派工,不等于任意外部副作用都有全局事务保证。
|
||||
|
||||
### 6.3 群聊、目标、工作阶段与审批
|
||||
|
||||
职责:管理员/成员调度、并行 @、轮次回报、群消息、任务阶段。groups 与 ledger、turns、goals 相互配合,[groups.js:19–32](../ds-bot/ds-bot/src/host/groups.js#L19)。
|
||||
|
||||
group_goal 支持 draft/start/revise/task/pass/rework/complete/pause/resume/stop;只有群管理员或 Main Bot 能修改。pass 和 complete 要求 evidence,见 [goals.js:288–299](../ds-bot/ds-bot/src/host/goals.js#L288)、[goals.js:670–671](../ds-bot/ds-bot/src/host/goals.js#L670)。
|
||||
|
||||
这里校验的是目标状态与证据字段,并不自动证明模型提供的证据真实,也不是通用 BPMN 工作流引擎。业务审批应区分“群内工作验收”与“宿主工具权限审批”。
|
||||
|
||||
### 6.4 上下文续接、历史搜索
|
||||
|
||||
职责:长聊压缩、换段、交接包、历史页。关键路径 [parts.js:1–16](../ds-bot/ds-bot/src/host/parts.js#L1);read_own_chat 可查各段和压缩前消息。
|
||||
|
||||
聊天全文索引单独存 SQLite,使用 node:sqlite / FTS5 trigram,见 [chat-index.js:48–110](../ds-bot/ds-bot/src/host/chat-index.js#L48)。它服务历史检索,不是整个应用的唯一数据库。
|
||||
|
||||
### 6.5 长期记忆、审核、召回与整理
|
||||
|
||||
职责:Bot / 群 / 团队三层 Markdown 记忆,话题索引、修改日志、快照、删除后的归档;工具与后台审核走同一写入路径,[memory.js:1–26](../ds-bot/ds-bot/src/host/memory.js#L1)。
|
||||
|
||||
与 Session 的关系:每段首次渲染冻结记忆提示段,保证前缀缓存稳定;换段或 checkpoint 再冻结。群记忆只在群上下文里给成员读取,并非一份任意串用的团队聊天摘要。
|
||||
|
||||
召回使用内存词项排名,类似 BM25 参数与词项覆盖度,见 [memory-search.js:1–29](../ds-bot/ds-bot/src/host/memory-search.js#L1)。没有据此把它称为向量数据库、embedding RAG 或外置知识图谱的依据。
|
||||
|
||||
### 6.6 工作文件夹、权限与私密 Bot
|
||||
|
||||
职责:决定 Session cwd,按 Bot/群保存权限预设,保护私密 Bot 信息。群文件夹优先于成员覆盖、Bot 默认和团队目录,见 [folders.js:1–4](../ds-bot/ds-bot/src/host/folders.js#L1)、[folders.js:23–33](../ds-bot/ds-bot/src/host/folders.js#L23)。
|
||||
|
||||
权限来自 DSH permissionPresets;auto review 是 Session 临时模式,不可作为 Bot/群长期预设,见 [permissions.js:1–5](../ds-bot/ds-bot/src/host/permissions.js#L1)、[permissions.js:41–47](../ds-bot/ds-bot/src/host/permissions.js#L41)。
|
||||
|
||||
私密 Bot 关闭其他 Bot 的业务读入口并检查文件/Shell 路径,但源码明说 Shell 仍可能访问 OS 账号可读的任意文件,[privacy.js:1–4](../ds-bot/ds-bot/src/host/privacy.js#L1)。因此不是进程、容器或多租户安全隔离。
|
||||
|
||||
### 6.7 模型、思考、Provider、用量与诊断
|
||||
|
||||
职责:选择每个 Bot 的模型/推理强度,管理 Provider 配置和展示用量、阻塞原因;入口模块装配见 [index.js:7–10](../ds-bot/ds-bot/index.js#L7)、[index.js:40–43](../ds-bot/ds-bot/index.js#L40)。
|
||||
|
||||
数据关系:模型列表从 DSH 取,不完全受团队 revision 控制,[channel.js:59–61](../ds-bot/ds-bot/src/host/channel.js#L59)。缺密钥、配额、登录和本地 CLI 错误被 turns 标为需要用户修复的阻塞,[turns.js:14–20](../ds-bot/ds-bot/src/host/turns.js#L14)。
|
||||
|
||||
### 6.8 能力库、MCP、技能、学习提案
|
||||
|
||||
职责:保存可分配给 Bot 的 MCP、skill 和能力包,按 Session 挂载;保留 connector 名称避免工具前缀冲突,[capabilities.js:5–32](../ds-bot/ds-bot/src/host/capabilities.js#L5)。
|
||||
|
||||
learning 对长回合在空闲后做低频审核,提出技能或项目规则卡片,经批准才落地,拒绝的建议会被记住,[learning.js:1–30](../ds-bot/ds-bot/src/host/learning.js#L1)。这已是代码实现,但不意味着可不受约束地自我重写系统。
|
||||
|
||||
### 6.9 浏览器、联网搜索、电脑操控
|
||||
|
||||
浏览器面板:每 Bot 独立 Electron 存储分区;Host 通过 browser-wait/browser-result 长轮询请求页面读取,见 [browser.js:1–18](../ds-bot/ds-bot/src/host/browser.js#L1)。需要实际承载页面的客户端在线。
|
||||
|
||||
自动化:团队选一个浏览器后端,各 Bot 独立 profile,已有 refs/script/task 三种模块,[browser-plugins.js:1–12](../ds-bot/ds-bot/src/host/browser-plugins.js#L1)。
|
||||
|
||||
联网搜索是独立 auto provider:优先按当前模型协议和自身凭据尝试原生搜索,失败再公共搜索页回退,[web-search.js:1–24](../ds-bot/ds-bot/web-search.js#L1)。与 Bot 团队代码分离较好,但仍依赖 DSH web seam。
|
||||
|
||||
电脑操控挂载 DSH 平台 Provider,DS Bot 补每 Bot 等级、应用同意、应用租约、指示器与人工交接;见 [computer/index.js:1–30](../ds-bot/ds-bot/src/host/computer/index.js#L1)。不能据此假定三个系统实际权限和驱动体验一致。
|
||||
|
||||
### 6.10 密钥、通用连接器、邮件
|
||||
|
||||
密钥独立保存,通过 DSH_SECRET 环境变量引用;模型请求和工具结果做脱敏,见 [secrets.js:1–4](../ds-bot/ds-bot/src/host/secrets.js#L1)。这是应用级保护,文件 mode 600 不等于静态加密。
|
||||
|
||||
连接器模块组合 OAuth、catalog、gateway、mail 与 MCP client,[connectors/index.js:1–17](../ds-bot/ds-bot/src/host/connectors/index.js#L1)。MCP loader 缺失时明确失败,[connectors/index.js:147–148](../ds-bot/ds-bot/src/host/connectors/index.js#L147)。
|
||||
|
||||
关系:连接器凭据由 secrets 提供,能力可分配给 Bot,邮件依赖 imapflow/mailparser/nodemailer;不是自带所有 SaaS 的离线替代品。
|
||||
|
||||
### 6.11 IM、手机与 Relay
|
||||
|
||||
IM 一个平台 Bot 账号绑定一个内部 Bot,平台群可映射 DS Bot 群;统一处理配对、路由、交互卡与发送队列,仅团队锁持有者连接,[im/index.js:1–4](../ds-bot/ds-bot/src/host/im/index.js#L1)。
|
||||
|
||||
源码已注册 Telegram、Discord、Slack、QQ、钉钉、企业微信、飞书、微信适配器;其余 UI 列表项可能只是 coming soon,[im/platforms/index.js:1–12](../ds-bot/ds-bot/src/host/im/platforms/index.js#L1)。存在 adapter 不代表本次已验证账号和远端服务。
|
||||
|
||||
手机后端负责设备配对、撤销与状态,[phone.js:123–159](../ds-bot/ds-bot/src/host/phone.js#L123)。加密协议依赖 clatterjs 与 noble 系列,[link/package.json:13–18](../ds-bot/link/package.json#L13)。
|
||||
|
||||
Relay 是 Node HTTP + WebSocket:healthz、upgrade 路径检查、Gateway 和 DeviceStore,[server.ts:23–43](../ds-bot/link/server/server.ts#L23)。服务入口可配置端口、设备 TTL、连接数等限制,[main.ts:7–16](../ds-bot/link/server/main.ts#L7)。它负责链路转发,不替电脑执行模型回合。
|
||||
|
||||
### 6.12 定时、Office、图片头像与更新
|
||||
|
||||
定时任务依赖 DSH schedule 服务;会话换段后迁移任务,服务缺失时接口报告不可用,[schedules.js:1–7](../ds-bot/ds-bot/src/host/schedules.js#L1)。因此装上插件不代表自动具备完整调度服务。
|
||||
|
||||
Office 注册路由 skill 与 office-tools;CLI 可检查/编辑 docx、pptx、xlsx 包,[office-skills.js:1–14](../ds-bot/ds-bot/src/host/office-skills.js#L1)、[office/cli.js:1–22](../ds-bot/ds-bot/src/office/cli.js#L1)。没有证据把它称作浏览器内完整 Office 协同编辑器。
|
||||
|
||||
图片、头像库、更新、DSH 更新、思考显示等均在运行时入口接入,[index.js:30–43](../ds-bot/ds-bot/index.js#L30)。上传暂存由 channel 维护 MIME 白名单与 30 分钟窗口,[channel.js:10–11](../ds-bot/ds-bot/src/host/channel.js#L10)。
|
||||
|
||||
### 6.13 本地 Agent CLI
|
||||
|
||||
本地 CLI 作为 Bot 执行方式,不只是模型下拉列表别名。引擎有 ACP/stdin-stdout、Codex app-server JSON-RPC、Claude stream-json,[local-agents/engines.js:1–5](../ds-bot/ds-bot/src/host/local-agents/engines.js#L1)。
|
||||
|
||||
已有 Claude Code、Codex、OpenCode、Gemini 等命令定义,见 [engines.js:18–22](../ds-bot/ds-bot/src/host/local-agents/engines.js#L18);权限预设要映射到各引擎语义,[engines.js:80–89](../ds-bot/ds-bot/src/host/local-agents/engines.js#L80)。本机必须另有相应 CLI、登录和权限,不能当成仓库随附的模型。
|
||||
|
||||
## 7. 数据存放:不是“只有一个 JSON”
|
||||
|
||||
默认 Bot 数据根为 DSH_HOME/bot,也可 config.home 覆盖,[index.js:69–77](../ds-bot/ds-bot/index.js#L69)。入口开头“one JSON file”的简述不足以覆盖现在全部存储。
|
||||
|
||||
- state.json:Bot/群/Agent/分区/能力/偏好/工作与请求等目录及状态,结构见 [store.js:22–23](../ds-bot/ds-bot/src/host/store.js#L22)。
|
||||
- state.lock:阻止两个 Host 同时写同一团队;另一窗口只读。锁失败会警告而非神奇获得分布式一致性,[store.js:49–67](../ds-bot/ds-bot/src/host/store.js#L49)。
|
||||
- ledger/*.jsonl:按会话追加消息和状态记录,先落盘再交付;首次整本读入内存,按 book 串行写,[ledger.js:1–11](../ds-bot/ds-bot/src/host/ledger.js#L1)。
|
||||
- chat-index.sqlite:聊天历史搜索索引,原始 Session 仍由 DSH sessionPersistence 保存,[chat-index.js:48–110](../ds-bot/ds-bot/src/host/chat-index.js#L48)、[host.mjs:55–58](../ds-bot/app/src/host.mjs#L55)。
|
||||
- memory/:Markdown 正文、journal、snapshots、summaries、archive、reviewed 游标,[memory.js:6–14](../ds-bot/ds-bot/src/host/memory.js#L6)。
|
||||
- secrets.json:凭据文件与进程内存,不放进普通团队状态/模型正文,[secrets.js:1–4](../ds-bot/ds-bot/src/host/secrets.js#L1)。
|
||||
- im/、浏览器 profile、头像、手机配对数据等是功能附属持久数据;不能只备份 state.json 就声称备份完成。
|
||||
|
||||
数据规模边界:账本首次整本读入内存,request 身份不随便过期,单团队文件锁与 JSON 状态都偏向个人/本机长期助手。它不是已验证的高并发分布式团队数据库。
|
||||
|
||||
## 8. 运行依赖与可用性条件
|
||||
|
||||
插件自身要求 DSH 的 Cordis / llm / scope / tools / web peer 服务;实际 peer 版本写 *,[package.json:52–57](../ds-bot/ds-bot/package.json#L52)。不应误解为任何 DSH 版本都保证兼容。
|
||||
|
||||
桌面把 DSH 系列包固定在 0.2.2-rc.1,Electron 44.7.0,见 [app/package.json:28–64](../ds-bot/app/package.json#L28)、[app/package.json:75](../ds-bot/app/package.json#L75)。构建与发行还涉及 electron-builder、Vite、pnpm;属于桌面交付依赖。
|
||||
|
||||
插件实际运行依赖还包括 MCP client、deep-view、邮件库、playwright-core、图像编解码和 ws,[package.json:72–81](../ds-bot/ds-bot/package.json#L72)。Playwright Core 存在不等于已安装完整浏览器。
|
||||
|
||||
模型仍需要有效 Provider 凭据/账户或已登录 CLI;电脑操控需要平台 Provider 和 OS 授权;连接器需要远端服务;手机需要电脑 Host 在线与可达 Relay;定时需 schedule 服务。
|
||||
|
||||
Node 必须能满足所用 DSH 包以及 node:sqlite 等 API;本次未执行环境探测,因此不擅自给整个项目一个未经核验的统一 Node 最低版本。
|
||||
|
||||
## 9. 哪些是源码实现,哪些是文档规划
|
||||
|
||||
[plans/README.md:1–9](../ds-bot/docs/plans/README.md#L1) 明确该目录记录“已定的设计”,大功能设计跟代码在同一 PR。文件名带 plans 不等于功能还没写。
|
||||
|
||||
已核实接入的功能:长期身份、多 Main Bot、群聊调度、阶段目标、Markdown 记忆、历史搜索、私密 Bot 业务限制、浏览器、电脑操控、MCP/连接器、学习提案、Office CLI、IM、手机链路、本地 Agent CLI。证据是入口装配 + 对应模块实现,而非 README 宣传语。
|
||||
|
||||
文档存在滞后:[vision.md:23](../ds-bot/docs/vision.md#L23) 仍写 self-improvement planned,但 learning 已有“后台审核→提案→用户批准”代码;这仅支持说“有限学习提案已实现”,不支持“全面自我进化”。
|
||||
|
||||
同样 [vision.md:28](../ds-bot/docs/vision.md#L28) 写 Cookie 导入 planned,而 [main.mjs:825–845](../ds-bot/app/src/main.mjs#L825) 已有导入分支。应以当前代码描述能力,并保留未运行验证的限定。
|
||||
|
||||
IM 的 coming soon 有明确代码边界:只有 adapters 中列出的平台可新增连接。不要把完整平台目录里的每个名字都算已打通。
|
||||
|
||||
没有据本次源码得到的能力:固定部门制审核链、跨团队强多租户隔离、任意外部副作用恰好一次、分布式高可用调度、模型结果自动正确性保证。应作为新需求评估,不能从“Main”“workspace”“evidence”这些字段名称推导出来。
|
||||
|
||||
## 10. 可复用边界与实际选型建议
|
||||
|
||||
**最容易整体复用的是“DSH + DS Bot 插件”组合。** 保留现成 Session、工具、权限和模型服务,开发重点放在角色约束、流程与业务 UI;成本显著小于抽掉 DSH 后重做所有宿主接口。
|
||||
|
||||
可以相对独立借鉴/抽取:追加式消息账本与去重设计、记忆格式与词项排名、Office 包处理、加密 Relay、纯 React 展示组件。仍需检查导入依赖、许可证和持久格式,不能称为复制即用。
|
||||
|
||||
不适合直接割裂复用:rt 大量互调的群聊/turns/handoffs/parts、依赖 DSH slots 的插件 UI、依赖宿主 Session schema 的历史/权限/模型接口、Electron 原生浏览器与电脑操控。
|
||||
|
||||
若用于“多项目、多部门协作平台”,建议保留 Bot 身份与协作机制,但单独定义项目实体、成员/资源授权、产物归属和流程审批状态机;仅改机器人名字、分配文件夹、添加 Main 标记,不会自动补齐这些边界。
|
||||
|
||||
源码许可证标注 Apache-2.0,[package.json:23](../ds-bot/ds-bot/package.json#L23);桌面部分明确引用 DSH MIT 代码并要求 NOTICE,[host.mjs:5](../ds-bot/app/src/host.mjs#L5)。复用时应保留相应声明和来源,不把开源许可误当作无义务搬运。
|
||||
|
||||
本报告的结论是架构与实现边界,不是安全审计通过、性能测试通过或发布可用性背书。全部源码引用对应本工作区静态版本。
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
# 三省六部 v0.0.1 宿主公开契约调研
|
||||
|
||||
日期:2026-11-14。对象:本机 DSH Desktop runtime 0.2.2-rc.3。只读研究,没有创建、恢复、配置真实会话,没有读取凭据,没有修改宿主/profile/node_modules。唯一写入为本笔记。安装包 ASAR 可由 read 读取,但 glob 无法遍历,声明入口列在 package exports 中、实际声明文件未随安装包提供;因此以下为公开包运行时实现和 DS Bot 调用交叉核实的 JS 调用签名,不冒充完整 TypeScript 声明。原 10–15 次读取预算未守住:ASAR/声明失败探测及重复读取导致超额,此处明确记录。
|
||||
|
||||
## 结论
|
||||
|
||||
采用一个独立轻量插件,直接使用宿主注入服务。每个项目绑定独立 canonical cwd/workspaceId 和固定十个 roleId → sessionId。不要装载 DS Bot,也不要调用历史 dsbot-runtime;不需要任何群 session。原型可以只做十个普通 root session + 项目配置存储 + 一个动态 systemPrompt section。
|
||||
|
||||
尤其不能把 sessionController.create 当恢复;不能调用 sessionController.selectModel 达成“不写 profile”,因为它会后台保存全局默认。无 profile 模型切换是 agent.model.select(selection),前置用 llm 验证路由。不存在已证实的通用 session.configure 或 agents.find 方法;不要从名字猜接口。
|
||||
|
||||
## 可直接用的调用契约
|
||||
|
||||
下列 C 代表公开包 @deepseek-ai/dsh-api-session-controller 的 lib/index.js;A 代表 @deepseek-ai/dsh-agent 的 lib/index.js;W 代表 @deepseek-ai/dsh-workspace 的 lib/index.js。源码绝对根为 C:/Users/qyh15/AppData/Local/Programs/DeepSeek Harness/resources/app.asar/dsh/node_modules/@deepseek-ai/。应用代码只能 import 公开包名字或使用 ctx 服务,不能硬编码此安装路径。
|
||||
|
||||
- ctx.workspaceRegistry.get(workspaceId) → Workspace | undefined,同步。W:445。
|
||||
- ctx.workspaceRegistry.list() → Workspace[],同步、durable registry order。W:454。
|
||||
- await ctx.workspaceRegistry.resolveByPath(path) → Workspace | undefined,realpath 规范化。W:643。
|
||||
- await ctx.workspaceRegistry.create(path, title?) → Workspace,目录须存在且为目录,相同 canonical path 重用。W:408,647。
|
||||
- await workspace.attachSession(sessionId),第一次绑定读取 header.cwd、realpath 后必须等于 workspace.path;不是随意移动会话。W:111–124。workspace.sessionIds 是已有索引过滤后的成员列表。
|
||||
- await ctx.sessionController.create({sessionId?, workspaceId?, cwd?, agentPreset?}) → {sessionId, agentPreset?}。workspaceId 与 cwd 互斥;使用 workspaceId 时从 workspace.path 得到 cwd。C:724–755,4017。
|
||||
- await ctx.sessionController.resolveAgent(sessionId) → {agent} | {error},DS Bot 的 delivery.js:10–11 使用此方法;宿主 resolver 会恢复冷会话并按 ID 合并并发 resume,拒绝 subagent 所有的会话。C:175–203。error 必须传播,不能把所有错误当不存在。
|
||||
- ctx.agents.get(sessionId) → Agent | undefined,只查询活跃内存实例,不恢复;ctx.agents.list() → Agent[]。A:720–728。
|
||||
- await ctx.agents.create(options)、await ctx.agents.resume(options) 是公开底层工厂入口,但需要正确 preset/setup 生命周期;v0.0.1 优先用 controller,避免手工组成 Agent。A:582–600。
|
||||
- await ctx.sessionController.rename({sessionId,title}) → {title,seq},内部恢复 Agent 后经 sessionTitle.rename 记录标题。C:792–805。
|
||||
- await ctx.sessionController.modelCatalog() 返回提供者分组模型、deployment default、isolated provider failures;不要假设模型目录中存在即有可用余额/凭据。C:4044–4049。
|
||||
- await ctx.llm.resolveCallConfig({provider,model,reasoningEffort?}) 验证路由/effort;controller 用它先校验再 select。C:772。
|
||||
- agent.model.current() → {provider,model,reasoningEffort?} | undefined;agent.model.select(selection) → void,同步追加 model/selection 事件,相同完整选择不重复追加。A:190–202。
|
||||
- ctx.systemPrompt.section({name,order,interpolate:false,text: context => string}) → disposer。DS Bot prompt.js:67–72 使用,返回文本按 context.agent.id 查角色;不属于本项目的 session 返回空字符串。插件卸载时释放注册。
|
||||
|
||||
### 模型配置最小路线
|
||||
|
||||
```js
|
||||
const resolved = await ctx.sessionController.resolveAgent(sessionId)
|
||||
if ('error' in resolved) throw resolved.error
|
||||
const agent = resolved.agent
|
||||
const selection = { provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) }
|
||||
await ctx.llm.resolveCallConfig(selection)
|
||||
// 再次核对对象仍是此 ID 的活跃 Agent,以及项目映射/版本未发生变化。
|
||||
if (ctx.agents.get(sessionId) !== agent) throw new Error('Agent changed during configuration')
|
||||
agent.model.select(selection)
|
||||
return agent.model.current()
|
||||
```
|
||||
|
||||
select 自身仅记录会话事件,不验证字符串的业务合法性,因此不能省略验证。controller 另外会 requireModel 并检查目录可用性;自建 adapter 应从 modelCatalog 检查 provider/model/effort 后调用 resolveCallConfig。不要调用任何 credentials.get/read,不要为检测可用性发真实模型请求。
|
||||
|
||||
## 恢复、去重和生命周期
|
||||
|
||||
创建前持久化项目十个 roleId、计划 sessionId 和 provisioning 状态,每角色串行锁(跨进程需持久锁/唯一约束)。然后对计划 ID 查询/resolve;只有明确 session/not-found 才尝试创建。网络/持久层/迁移/preset 错误保留 pending,不生成新 ID。
|
||||
|
||||
controller.create 的 request.sessionId 是“空会话复用意图”,不是永久幂等键:内部 claim 可因为已有 turn/start、归档、workspace 不可复用等情况改为 createMinted,并返回另一个随机 ID(C:229, claim 分支,414)。因此调用后必须比较 returned.sessionId 与 plannedId;不一致应记录实际返回 ID 和异常、停止后续创建,不能悄悄覆盖映射或删除记录。workspace attach 失败返回 session/workspace-attach-failed 并附已创建 sessionId(C:744–750),同样须保留并在恢复时修复归属,不能再次创建。
|
||||
|
||||
若 session 已存在则核对 header.cwd、root 身份(无 subagent ownership)、预期 workspace 和本地项目/角色映射,随后恢复该 ID。不要用标题匹配身份,不要调用 create 恢复已有聊天。发现用户归档或移走角色会话时提示修复,不自动补造第十一个会话。
|
||||
|
||||
新建普通 controller 会话通过 agents.create({sessionId, agentOptions, meta:{cwd,agentPreset?},setup}) 创建(C:423–431),没有 parent/subagent 参数;因此是 root session,不继承某个对话父代理。初始模型从 agentDefaultModel.currentSelection getter 读取(C:433–445),故每角色必须在允许首轮发送前固定自己的 model/selection。
|
||||
|
||||
持久角色文字保存在插件项目状态,而不是只存内存 closure。启动先加载映射再注册 prompt section;配置更新后按 sessionId 读取最新版。宿主保留普通会话日志/模型事件;插件保留 roleId、身份、配置版本。禁止 DS Bot 的“上下文满则新 part session”行为,否则固定十个约束被破坏。
|
||||
|
||||
## 运行中修改模型
|
||||
|
||||
A:137–172 的 projection 保留 lastUsed 与 pending;current 返回 pending ?? lastUsed;request/header 只在匹配时消耗 pending。A:224–237 明确每一步的 route 已固定,并在下一 step 比较模型变化生成提示。因此新选择不会替换已经发出的模型请求;影响后续取样的 step,可能在同一个 turn 内发生。UI 应说明“后续步骤生效”,不能显示为当前请求已切换。
|
||||
|
||||
最小产品建议更保守:运行中把配置留作待应用,idle 后验证并 select,再允许下一次发送;避免与图像输入准入及 hosted engine 差异冲突。如支持即时配置,则按会话串行化并复核版本;不要通过 cancel 当前请求实现静默切换。更换 loop engine 的特殊迁移需求未在此次研究完全验证,v0.0.1 可限制为当前可用普通模型路由。
|
||||
|
||||
## 权限和项目隔离
|
||||
|
||||
独立 root session 并不自动继承当前用户聊天/调用 agent 的权限。DS Bot permissions.js:32–38 明确未设置时保留 DSH 默认;:25–28 通过 ctx.permissionPresets.set(agent.session,name) 设置 session;:17 使用 catalog() 读取 options/defaultPreset;:46 使用 resolve(name) 验证。Auto review 是 session-only,不能作为持久角色权限(:5–6,45)。这些调用是在 DS Bot 源码确认的使用契约,未完整审计 permission-presets 包内部授权实现。
|
||||
|
||||
v0.0.1 不替用户升权:不在 provisioning 时写 permission preset;在 UI 清楚展示宿主默认或会话实际权限。若将来允许修改,必须通过宿主正式人类授权入口而不是角色提示词或后台 set 绕过审批。workspace 的 canonical cwd 校验提供归属一致性,不构成安全沙箱;danger-full-access 会话仍可能跨项目读写。要承诺文件级隔离,需另行验证并采用宿主 sandbox/permission 机制。项目业务数据、角色映射、提示词均必须以 projectId/workspaceId/sessionId 校验访问。
|
||||
|
||||
## DS Bot 和历史代码能否单独复用
|
||||
|
||||
roster.js install(rt) 依赖 state/store、模型、权限、群组、parts、welcome/bootstrap、浏览器 grants 等;它在一个 team workspace 内构建 bot/room,不是独立 session provision 库。agents.js 是 DS Bot 自己的另一类“DSH Agent”记录管理器,依赖 rt.ensureWorkspace/save/index 等,只建普通聊天、并没有持久角色配置。两者不宜直接 import。
|
||||
|
||||
models.js 混合 llm 流重试、目录缓存、凭据状态、模型选择同步;:319–327 先 sessionController.selectModel 再恢复默认,仍然会写 profile,且存在异步保存竞争。不能原样复用。可借鉴目录呈现和同 session 序列化设计,但重新写几行独立 adapter。
|
||||
|
||||
prompt.js 最小可借鉴点仅 section 注册形式;其 promptFor 依赖 selfOf/botOf 和群组映射,角色正文含 DS Bot 产品语义,不适合直接 install。
|
||||
|
||||
历史 Git 233ee76:sansheng/src/provision.js 使用 ctx.get('dsbot-runtime',false)、rt.createBot + rt.createRoom,注释写明三 Bot + 项目群,且提示需要 ctx.provide 基线补丁。这是旧 DS Bot 集成方案,不满足十 root、无群 session、公开原生接口、不改宿主。只保留“项目记录/角色绑定/错误记录”的设计思路,不搬其创建与回滚代码。
|
||||
|
||||
## 最小交付建议
|
||||
|
||||
一个项目状态 schema(十角色固定枚举、sessionId、模型完整 tuple、instructions、版本、provision status)加一个薄 host adapter 即可。adapter 暴露 project(id)、session(id)、createSession、configureSession、models、onSystemPrompt。project(id) 只代理 workspaceRegistry.get;session(id) 用 resolveAgent;createSession 强校验计划 ID 回执;configureSession 走上文无 profile 路线;models 读 catalog;onSystemPrompt 返回 disposer。
|
||||
|
||||
不注册 DS Bot 插件、不引入其前端/浏览器/群、不给角色创建新角色/新会话的工具。UI 首次显式创建,重启仅恢复既有映射。测试用 fake ctx 验证严格十个 ID、创建中断恢复、returned ID mismatch、已存在有历史会话不重建、选择模型不调用 saveSelection、跨项目拒绝。真实宿主验证须另行获授权,本轮未执行。
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
# 三省六部 v0.1 实施状态
|
||||
|
||||
日期:2026-11-14。对应 [第一版方案](v1-plan.md) 第 7 节实施顺序。以下“已实现”指代码就位并通过 fake ctx 单元测试;
|
||||
真实宿主/桌面 App 的接线验收仍需在获得安装授权后另做,本文不把未核验项说成已完成。
|
||||
|
||||
## 进度总览
|
||||
|
||||
| 步骤 | 内容 | 状态 |
|
||||
|---|---|---|
|
||||
| 1 | 对照 Web / dsh-go 两份样式确认第一版范围 | ✅ 已完成(见 v1-plan、preview) |
|
||||
| 2 | 项目内身份及十席会话绑定(创建/恢复/失败重试/跨项目隔离) | ✅ 代码 + 测试完成(隔离环境验证) |
|
||||
| 3 | Web 导航入口 + 右侧工作台 | 🟡 源码就位,宿主接口待真机核验 |
|
||||
| 4 | dsh-go 原生面板 | 🟡 源码就位,触摸/返回/会话跳转待真机核验 |
|
||||
| 5 | 双项目联调、打包发布 | ⬜ 未开始 |
|
||||
|
||||
## 包结构(`sansheng/`)
|
||||
|
||||
- `index.js`:宿主入口。`inject=[workspaceRegistry, sessionController, agents, llm, systemPrompt, connection]`;注册动态 `systemPrompt.section` 与 `POST /api/sansheng` 路由。
|
||||
- `src/shared/roles.js`:十席固定定义(id/label/duty/responsibility)与布局分组,Web/原生/宿主三端共用。
|
||||
- `src/shared/schema.js`:版本 1 项目状态 schema 与严格校验(非法 JSON/错误版本/非十席一律视为损坏)。
|
||||
- `src/host/store.js`:单 JSON 原子写、串行 mutate、失败回滚、不静默回退。
|
||||
- `src/host/provision.js`:先持久化计划 sessionId 再创建;已存在按原会话恢复不重建;返回 ID 不一致立即停止后续创建并保留记录;失败保留已完成、重试只补未完成。
|
||||
- `src/host/model.js`:走 `agent.model.select`(会话级事件),**不调用** `sessionController.selectModel`(不写 profile 全局默认);调用前用 `llm.resolveCallConfig` 校验并复核 Agent 未变。
|
||||
- `src/host/prompt.js`:仅对十席会话注入本席角色文本,其它会话返回空串。
|
||||
- `src/host/service.js` / `api.js`:项目视图、启用、配置、模型目录与 HTTP 分发。
|
||||
- `src/client/`:Web 工作台(纯视图模型 + React 接线 + 传输层 + 白蓝/深色样式)。
|
||||
- `src/native/`:dsh-go 原生面板(纯视图树 + bridge 接线,容量/只读/无自由文本约束内建)。
|
||||
|
||||
## 测试证据
|
||||
|
||||
```
|
||||
cd sansheng && node --test test/*.test.js
|
||||
# tests 36 pass 36 fail 0
|
||||
```
|
||||
|
||||
覆盖:十席固定与两字名;状态损坏拒绝;创建十席全部绑定;已存在会话不重建;返回 ID 不一致停止;失败重试只补一个;
|
||||
模型只走 agent.model.select(selectModel 调用次数断言为 0);非法模型拒绝;跨项目会话/模型隔离;重启不重复建会话;
|
||||
HTTP 处理器端到端;systemPrompt 只注入十席;Web 纯视图模型(十席/未选模型显示“请选择模型”/无 inherit/切换保留草稿);
|
||||
原生视图树(≤120 节点、≤8 深度、选项≤8、无自由文本控件、选中高亮);宿主项目视图直接喂给 Web 纯视图模型与原生面板的跨端一致性。
|
||||
|
||||
## 待真机核验(尚未完成,不能宣称已适配)
|
||||
|
||||
- Web:左侧 `sidebar.footer.action` 入口、右侧 `sidebarRight` 标签页注册签名、会话导航 API、当前项目权威来源、`POST api/sansheng` 实际挂载。
|
||||
- dsh-go:面板入口位置、会话跳转 effect(现有 effect 无 navigation)、由 sessionId 反查项目、原生模型选择持久化、触摸面积与深浅色由宿主渲染。
|
||||
- 打包:`client.js` 需 `npm run build`(依赖 esbuild devDependency)生成;当前环境未安装 esbuild,故未产出 `client.js`。
|
||||
|
||||
## 未改动
|
||||
|
||||
未安装到任何 DSH profile,未修改用户日常 DSH、node_modules 或全局默认模型。
|
||||
|
|
@ -0,0 +1,372 @@
|
|||
# OpenMausBot 源码架构拆解
|
||||
|
||||
> 范围:当前工作区 OpenMausBot 源码快照;分析日期 2026-11-14。
|
||||
> 方法:先读 AGENTS.md,再沿入口、导入、路由、驱动契约和持久化实现交叉阅读。没有安装依赖、启动服务、执行测试或修改两个仓库。
|
||||
> “已实现”在本文中指有可追踪的实现代码与接线,不等于本机或所有平台已经运行验证。外部服务是否在线、账号是否有权限,本次均未验证。
|
||||
|
||||
## 1. 一句话看懂
|
||||
|
||||
OpenMausBot 是一个“让一队 AI 在聊天界面里干活”的本地优先应用。
|
||||
它不是只包了一层大模型 API:机器人档案、会话、协作交接、审批、电脑控制、浏览器、工具接入和持久化,都是宿主应用自己的工作。
|
||||
大模型或编码助手只是可替换的执行引擎;Electron 是桌面入口,Node 服务是实际组织工作的中枢。
|
||||
|
||||
根包自述为 local-first chat app,版本为 0.1.158,许可证声明 Apache-2.0;桌面入口指向 Electron。
|
||||
证据:[package.json:1](../OpenMausBot/package.json#L1)、[package.json:15](../OpenMausBot/package.json#L15)。
|
||||
|
||||
## 2. 阅读约束与可信度
|
||||
|
||||
仓库要求:声称服务或会话改动有效之前,要按验证说明启动隔离 fixture,不能拿用户真实数据验证修改。
|
||||
本次是只读架构分析,没有修改服务,也没有声称测试通过,所以没有启动这些 fixture。
|
||||
证据:[AGENTS.md:3](../OpenMausBot/AGENTS.md#L3)。
|
||||
|
||||
证据分三层:
|
||||
- **实现明确**:入口确实导入模块,路由确实调用 handler,契约或存储确实有代码。
|
||||
- **实现但有外部条件**:例如模型 CLI、Cua、Docker/Podman、Boat、云端控制面需要另行准备。
|
||||
- **文档/规划**:设计文档只说明作者当时打算怎么做,不直接证明现在做到了什么。
|
||||
|
||||
下文没有把预览页面、功能开关、依赖包名或目录存在当作完整可用的证明。
|
||||
|
||||
## 3. 总体分层
|
||||
|
||||
从使用者视角看,链路是:
|
||||
|
||||
src/main.tsx → React 页面/状态层 → HTTP API / SSE
|
||||
↓
|
||||
server/index.ts
|
||||
↓
|
||||
协调器 / 运行时 / ProviderDriver
|
||||
↓
|
||||
模型 API 或外部 CLI、MCP 工具、电脑
|
||||
↓
|
||||
SQLite / JSON / JSONL / 文件
|
||||
|
||||
这里第一行的入口是 [src/main.tsx](../OpenMausBot/src/main.tsx#L1)。
|
||||
后端不是 Express/Nest/Fastify:核心直接导入 Node 的 createServer、IncomingMessage、ServerResponse。
|
||||
证据:[server/index.ts:11](../OpenMausBot/server/index.ts#L11)。
|
||||
|
||||
主要目录的分工:
|
||||
- [src/App.tsx](../OpenMausBot/src/App.tsx#L1):大应用界面组合。
|
||||
- [src/state/store.tsx](../OpenMausBot/src/state/store.tsx#L1):客户端状态与动作落到后端的桥梁。
|
||||
- [server/index.ts](../OpenMausBot/server/index.ts#L1):服务装配、会话和运行生命周期、仍有大量内联路由。
|
||||
- [server/contracts.ts](../OpenMausBot/server/contracts.ts#L1):模型驱动和运行宿主之间的接口。
|
||||
- [shared/runtime-events.ts](../OpenMausBot/shared/runtime-events.ts#L1):前后端/驱动共同理解的运行事件。
|
||||
- [electron/main.mjs](../OpenMausBot/electron/main.mjs#L1):桌面窗口与本地能力装配。
|
||||
- [companion/src/index.ts](../OpenMausBot/companion/src/index.ts#L1):配套设备服务入口。
|
||||
- [connector/src/agent.ts](../OpenMausBot/connector/src/agent.ts#L1):托管主机到云管理端的连接代理。
|
||||
- [relay/src/main.ts](../OpenMausBot/relay/src/main.ts#L1):独立网络中继入口。
|
||||
|
||||
## 3.1 功能模块速查
|
||||
|
||||
| 模块 | 用户看见的功能 | 后端负责的事情与源码入口 |
|
||||
|---|---|---|
|
||||
| Bot 与会话 | 建机器人、单聊、历史 | 身份、配置和会话归属:[Store](../OpenMausBot/server/store.ts#L275) |
|
||||
| 群聊与协作 | 群成员、任务交接、团队活动 | 多 Bot 调用和协调:[coordinator](../OpenMausBot/server/coordinator.ts#L1) |
|
||||
| 模型引擎 | 选择模型或本地编码助手 | 统一不同引擎的输入、事件和能力:[drivers](../OpenMausBot/server/drivers/builtIn.ts#L32) |
|
||||
| 记忆 | 查看、维护 Bot 记忆和个人信息 | 记忆文档、变更日志、回退和整理:[记忆路由](../OpenMausBot/server/routes/bot-memory.ts#L5) |
|
||||
| 自动化 | 定时工作、触发器、等待与继续 | 计划计算、运行记录、失败恢复及暂停:[routines](../OpenMausBot/server/routines.ts#L9) |
|
||||
| 工具与审批 | 工具执行过程、确认卡片 | MCP 桥接、权限范围、控制代理:[mcp-bridge](../OpenMausBot/server/mcp-bridge.ts#L1) |
|
||||
| 浏览器 | 实时网页画面与操作 | 浏览器控制、授权观看连接:[browser-viewers](../OpenMausBot/server/routes/browser-viewers.ts#L1) |
|
||||
| 电脑 | 本机、Local VM、云电脑面板 | 三种不同执行环境,详见第9节 |
|
||||
| 文件与数据 | 附件、文件视图、表格图表 | 附件归属和数据查询:[数据路由](../OpenMausBot/server/data/routes.ts#L21) |
|
||||
| 邮件与应用 | 连接邮箱及外部应用 | 邮箱发现、连接校验、发送配置与账户存储:[邮件服务](../OpenMausBot/server/email/service.ts#L1) |
|
||||
| 页面与技能 | 发布页面、技能和例程 | 独立服务模块:[页面服务](../OpenMausBot/server/pages/service.ts#L1)、[skills](../OpenMausBot/server/skills.ts#L1) |
|
||||
| 运行记录 | 用量与执行状态 | 运行数据库、用量日志:[runtime store](../OpenMausBot/server/runtime/store.ts#L1)、[usage ledger](../OpenMausBot/server/usage-ledger.ts#L1) |
|
||||
| 手机与云端配套 | 配对、远程连接、托管主机 | companion、relay、connector、control-plane,详见第13节 |
|
||||
|
||||
记忆不等于聊天记录:记忆路由导入独立 memory store、journal、upkeep,能分别管理记忆内容、修改记录和整理状态。团队环境还定义个人记忆层及写权限回调,见 [记忆依赖契约](../OpenMausBot/server/routes/bot-memory.ts#L26)。不能因为存在记忆维护接口,就宣称模型记住的内容一定正确。
|
||||
|
||||
## 4. 前端:框架、入口和运行方式
|
||||
|
||||
前端是 React 19 + TypeScript + Vite 7。桌面开发依赖 Electron 43。
|
||||
版本证据:[package.json:132](../OpenMausBot/package.json#L132)、[package.json:166](../OpenMausBot/package.json#L166)、[package.json:175](../OpenMausBot/package.json#L175)。
|
||||
|
||||
启动入口先设置主题、字体、聊天宽度、软件渲染与语言,避免首屏先闪出错误样式。
|
||||
随后才决定当前应该显示主页、配对页、登录页还是完整应用。
|
||||
证据:[src/main.tsx:22](../OpenMausBot/src/main.tsx#L22)、[src/main.tsx:40](../OpenMausBot/src/main.tsx#L40)。
|
||||
|
||||
这里不是简单地无条件渲染 App:/home、/pair、/desktop-viewer 不预先加载大应用块。
|
||||
其他页面会并行开始加载 App 与读取会话,降低登录后的等待。
|
||||
证据:[src/main.tsx:30](../OpenMausBot/src/main.tsx#L30)。
|
||||
|
||||
界面是否能用,还要经过会话判断:未认证展示配对,团队退出展示离开页,桌面本地主页可接 Electron bridge。
|
||||
window.ogb 是桌面壳向页面暴露能力的入口,浏览器环境不应假定它存在。
|
||||
证据:[src/main.tsx:41](../OpenMausBot/src/main.tsx#L41)、[src/main.tsx:52](../OpenMausBot/src/main.tsx#L52)。
|
||||
|
||||
Vite 的开发监听明确绑定 IPv4 127.0.0.1,默认 UI 端口 5199,可用 OMB_UI_PORT 改。
|
||||
这是开发服务器,不应和正式 Node 后端混成一台服务。
|
||||
证据:[vite.config.ts:79](../OpenMausBot/vite.config.ts#L79)。
|
||||
|
||||
客户端状态层负责把群组、机器人任务、项目等用户动作转换成 API 请求,并再分发服务端返回状态。
|
||||
例如删除群组、更新任务、创建机器人项目分别有真实请求调用。
|
||||
证据:[src/state/store.tsx:2668](../OpenMausBot/src/state/store.tsx#L2668)、[src/state/store.tsx:2708](../OpenMausBot/src/state/store.tsx#L2708)、[src/state/store.tsx:2723](../OpenMausBot/src/state/store.tsx#L2723)。
|
||||
|
||||
## 5. 后端:入口、框架和 API
|
||||
|
||||
根脚本把 omb 指向 Node 直接执行的命令入口,dev:server 指向开发引导文件。
|
||||
开发引导只设开发场景的本地浏览器信任变量,然后动态导入真正的服务入口。
|
||||
证据:[package.json:33](../OpenMausBot/package.json#L33)、[server/dev-server.ts:1](../OpenMausBot/server/dev-server.ts#L1)。
|
||||
|
||||
主服务体积很大:本次读取快照的入口约 15,448 行。
|
||||
它已经抽出 routes、host、runtime、drivers 等模块,但还不能称为完全解耦的插件内核。
|
||||
一些路由已走统一分发,其他功能仍在主服务中组合或内联处理。
|
||||
证据:[server/index.ts:12694](../OpenMausBot/server/index.ts#L12694)。
|
||||
|
||||
### HTTP、SSE、WebSocket 分别干什么
|
||||
|
||||
HTTP 是“请求一件事并取得结果”:登录、配对、配置变更、查询、提交操作、附件等。
|
||||
SSE 是“服务器不断告诉页面发生了什么”:聊天与运行状态变化,不需要浏览器不断轮询整段会话。
|
||||
WebSocket 是适合双向实时或二进制通道的另一层,浏览器画面等实时连接由相应路由拥有;它不是所有聊天 API 的统一底座。
|
||||
|
||||
SSE 路径明确为 GET /api/events,响应 content-type 为 text/event-stream,并有心跳、会话存活判断、可见性过滤和背压状态。
|
||||
证据:[server/index.ts:14627](../OpenMausBot/server/index.ts#L14627)。
|
||||
|
||||
WebSocket upgrade 不绕过 HTTP 安全门:它转入同一个请求处理器,通过认证、托管工作区和维护门后才由所属路由完成握手。
|
||||
握手有 10 秒限制,提前到来的数据有 64 KiB 上限。
|
||||
证据:[server/routes/upgrades.ts:1](../OpenMausBot/server/routes/upgrades.ts#L1)、[server/routes/upgrades.ts:35](../OpenMausBot/server/routes/upgrades.ts#L35)。
|
||||
|
||||
### 已核验的 API 入口例子
|
||||
|
||||
- POST /api/auth/pair:浏览器配对入口。[server/index.ts:12577](../OpenMausBot/server/index.ts#L12577)
|
||||
- POST /api/pair:companion 配对,同一次性凭据窗口、锁定与交换机制。[server/index.ts:12611](../OpenMausBot/server/index.ts#L12611)
|
||||
- GET /api/auth/session:读取会话。[server/index.ts:12697](../OpenMausBot/server/index.ts#L12697)
|
||||
- GET /api/health:健康检查的一条入口。[server/index.ts:12659](../OpenMausBot/server/index.ts#L12659)
|
||||
- GET /api/events:状态事件流。[server/index.ts:14627](../OpenMausBot/server/index.ts#L14627)
|
||||
- GET /api/internal/agents、GET /api/internal/assignment-status、POST /api/internal/coordinate-bots:内部协作白名单。[server/index.ts:1652](../OpenMausBot/server/index.ts#L1652)
|
||||
- POST /api/internal/computer/mcp:云电脑工具接口,受 turn 级能力凭据保护。[server/cloud-computer-tools.ts:1](../OpenMausBot/server/cloud-computer-tools.ts#L1)
|
||||
- /api/bots/:botId/data:机器人数据模块路由族,并验证图表类型、字段和分页等参数。[server/data/routes.ts:21](../OpenMausBot/server/data/routes.ts#L21)
|
||||
|
||||
这是一份代表性接口地图,不是把 15,000 行入口及全部路由穷尽导出的 OpenAPI 文档。
|
||||
internal 不代表不鉴权,也不代表可给外部集成任意调用。
|
||||
|
||||
## 6. 模型引擎:真正的可替换边界
|
||||
|
||||
ProviderDriver 是“某种引擎怎样接进来”的公共契约,驱动把自己的模型/会话行为翻译成宿主统一理解的形式。
|
||||
会话能力声明包含队列、审批等差异,因此相同界面不代表每种引擎功能完全相同。
|
||||
证据:[server/contracts.ts:247](../OpenMausBot/server/contracts.ts#L247)、[server/contracts.ts:593](../OpenMausBot/server/contracts.ts#L593)。
|
||||
|
||||
当前 built-in 注册数组共有 29 项,按实际符号列出如下:
|
||||
|
||||
GrokDriver、GrokAgentDriver、GeminiAgentDriver、KimiAgentDriver、DroidAgentDriver、CursorAgentDriver、OpenCodeDriver、QwenAgentDriver、HermesAgentDriver、ClineAgentDriver、CopilotAgentDriver、CommandCodeAgentDriver、KiroAgentDriver、OmpAgentDriver、CustomAcpDriver、PiDriver、OpenAICompatDriver、ClaudeDriver、CodexDriver、AntigravityDriver、MinimaxDriver、MistralDriver、CerebrasDriver、GroqDriver、GreenferenceDriver、ModelgoDriver、MetaDriver、MuseCodeDriver、DeepSeekAgentDriver。
|
||||
|
||||
唯一支持列表依据是实际导入和注册,不是 README 的营销名单。
|
||||
证据:[server/drivers/builtIn.ts:1](../OpenMausBot/server/drivers/builtIn.ts#L1)、[server/drivers/builtIn.ts:32](../OpenMausBot/server/drivers/builtIn.ts#L32)。
|
||||
|
||||
其中大量 AgentDriver 从 acp 子目录接入;OpenAICompat、Claude、Codex 等有独立实现。
|
||||
这意味着兼容层既有“直接接 API”的路线,也有“驾驭外部代理/CLI”的路线,不能一概当成 OpenAI Chat Completions。
|
||||
所需 CLI、账号、订阅、API key、模型可用地区由各驱动决定。
|
||||
|
||||
驱动错误模型明确区分 missing_cli、invalid_credentials、inactive_subscription、insufficient_funds、quota_or_region_restriction、upstream_outage 等。
|
||||
源码自己就承认这些是会阻断运行的外部条件。
|
||||
证据:[server/contracts.ts:19](../OpenMausBot/server/contracts.ts#L19)。
|
||||
|
||||
## 7. 机器人、会话、多机器人协作
|
||||
|
||||
机器人不是一个独立微服务;它更像宿主里的长期档案和配置,关联多条会话与执行状态。
|
||||
聊天记录、运行会话和机器人档案要分开理解:删一个 UI 卡片,不等于所有底层引擎文件都消失。
|
||||
|
||||
协调器负责交接、派工、查询进度,把多个 bot 的工作组织成可恢复的过程。
|
||||
主入口引入 createCoordinator、ComposedTurn、CoordinateBotsCall、HandoffOptions、HostTurnResult 等显式契约。
|
||||
证据:[server/index.ts:27](../OpenMausBot/server/index.ts#L27)、[server/coordinator.ts:1](../OpenMausBot/server/coordinator.ts#L1)。
|
||||
|
||||
运行协调层另有 RuntimeStore 与 Runtime,保存停止记录、交接与工作状态。
|
||||
因此 UI 看见的“正在做/等待用户/被停止”,不能只用一个 Promise 的 resolved/rejected 表示。
|
||||
证据:[server/runtime-coordinator.ts:143](../OpenMausBot/server/runtime-coordinator.ts#L143)。
|
||||
|
||||
群聊还有独立的上下文与会话处理:房间 transcript、room sessions、room context tracker 都在服务装配时接入。
|
||||
证据:[server/index.ts:20](../OpenMausBot/server/index.ts#L20)。
|
||||
|
||||
人与机器人交互不是只有一条纯文本回复;问题卡、等待用户、恢复卡片、MCP 登录卡等有专门宿主模块。
|
||||
证据:[server/index.ts:28](../OpenMausBot/server/index.ts#L28)。
|
||||
|
||||
## 8. 工具系统与审批边界
|
||||
|
||||
工具来源包含内建宿主能力、电脑能力、MCP 进程、连接的应用和不同模型引擎自身的工具。
|
||||
MCP bridge 可以派生子进程,并增加控制授权、工具 schema 规范化、活动探测与 saved-steps journal。
|
||||
证据:[server/mcp-bridge.ts:1](../OpenMausBot/server/mcp-bridge.ts#L1)。
|
||||
|
||||
因此“调用一个工具”不等于模型直接获得所有宿主权限。
|
||||
电脑连接可以包装成 gatedLocalComputer:真实命令和参数留在环境变量里,调用先经过控制代理,携带 CONTROL_URL 和 CONTROL_TOKEN。
|
||||
证据:[server/local-computer.ts:28](../OpenMausBot/server/local-computer.ts#L28)。
|
||||
|
||||
云电脑凭据更明确留在服务端,模型拿的是 turn-scoped capability 对应的工具入口。
|
||||
工具包括远程命令、截图、复制文件、后台命令状态等,和普通模型文本生成是不同能力。
|
||||
证据:[server/cloud-computer-tools.ts:1](../OpenMausBot/server/cloud-computer-tools.ts#L1)。
|
||||
|
||||
可复用的是这些契约和门禁设计;不能只复制工具 handler、丢掉运行上下文与授权代理。
|
||||
|
||||
## 9. 桌面壳、真实电脑、Local VM、Cloud Computer
|
||||
|
||||
### Electron 壳
|
||||
|
||||
Electron 主进程是桌面程序入口,负责窗口和桌面能力组合;React 仍是渲染界面,Node 服务仍是业务中心。
|
||||
浏览器模式没有天然的本机桌面权限;需要本地壳或配套连接,不能因为网页能打开就认为能控制电脑。
|
||||
证据:[package.json:18](../OpenMausBot/package.json#L18)、[src/main.tsx:41](../OpenMausBot/src/main.tsx#L41)。
|
||||
|
||||
### Your Computer / 本机桌面
|
||||
|
||||
本地电脑连接契约明确包含 darwin、linux、win32 三个平台。
|
||||
macOS/Windows 使用 legacy descriptor 分支;Linux 另有严格的驱动文件身份核验及必要工具清单。
|
||||
证据:[server/local-computer.ts:6](../OpenMausBot/server/local-computer.ts#L6)、[server/local-computer.ts:19](../OpenMausBot/server/local-computer.ts#L19)、[server/local-computer.ts:68](../OpenMausBot/server/local-computer.ts#L68)。
|
||||
|
||||
所以“只支持 macOS”不符合当前这份接口源码;但“三个平台接口存在”也不证明权限弹窗、辅助组件和各平台桌面会话全部已准备好。
|
||||
本次不运行探测,无法据此宣布当前 Windows 机器可控制。
|
||||
|
||||
### Local VM
|
||||
|
||||
源码自己说明:这是 Cua-backed Local VM,OMB 负责 sandbox 边界,桌面自动化由容器中的 cua-driver mcp 负责。
|
||||
它不是 OpenMausBot 自己写的 CPU 虚拟机或全套远程桌面协议栈。
|
||||
证据:[server/container-computer.ts:1](../OpenMausBot/server/container-computer.ts#L1)。
|
||||
|
||||
实现包含 Docker/Podman 运行时适配、容器启动/停止/删除、共享与按 bot 分隔的 target、工作区挂载和 viewer 端口。
|
||||
共享 target 默认宿主 viewer 端口 6080,容器 viewer 端口 6901;per-bot target 使用受控身份生成。
|
||||
证据:[server/container-computer.ts:71](../OpenMausBot/server/container-computer.ts#L71)、[server/container-computer.ts:91](../OpenMausBot/server/container-computer.ts#L91)。
|
||||
|
||||
Windows 分支专门处理 Podman Machine 的 WSL 挂载路径翻译,说明平台适配存在实际限制,不能把 Linux 命令原样搬到 Windows。
|
||||
证据:[server/container-computer.ts:729](../OpenMausBot/server/container-computer.ts#L729)。
|
||||
|
||||
### Cloud Computer
|
||||
|
||||
云电脑通过 Boat 适配器执行命令、截图和文件操作,仍由本地/托管宿主保存凭据并安排授权。
|
||||
远端桌面可用性、资源、计费与网络属于外部依赖,仓库有调用代码不等于附送可用云资源。
|
||||
证据:[server/cloud-computer-tools.ts:3](../OpenMausBot/server/cloud-computer-tools.ts#L3)。
|
||||
|
||||
## 10. 浏览器、文件、数据和页面
|
||||
|
||||
浏览器能力不是聊天消息的一种格式,它有独立浏览器控制与实时 viewer 路由。
|
||||
viewer 模块与统一 upgrade 门协作,避免把实时观看口变成免认证旁路。
|
||||
证据:[server/routes/browser-viewers.ts:1](../OpenMausBot/server/routes/browser-viewers.ts#L1)、[server/routes/upgrades.ts:1](../OpenMausBot/server/routes/upgrades.ts#L1)。
|
||||
|
||||
数据模块以 bot 为所属边界,可产生表格和图表卡;schema 列出 bar、line、area、scatter、histogram、pie、heatmap 等图表类型。
|
||||
字段、聚合函数、limit、bins 都有限制,不是任意输入都无条件交给渲染层。
|
||||
证据:[server/data/routes.ts:21](../OpenMausBot/server/data/routes.ts#L21)。
|
||||
|
||||
文件与附件是独立资源,会话只引用它们;主服务检查附件是否仍被聊天或机器人头像使用。
|
||||
证据:[server/index.ts:12099](../OpenMausBot/server/index.ts#L12099)。
|
||||
|
||||
页面、skills、routines 等模块各有独立实现,但本次没有穷尽每个操作分支:可确认是实际源码模块,不对所有子功能作运行保证。
|
||||
阅读起点:[server/pages/service.ts](../OpenMausBot/server/pages/service.ts#L1)、[server/skills.ts](../OpenMausBot/server/skills.ts#L1)、[server/routines.ts](../OpenMausBot/server/routines.ts#L1)。
|
||||
|
||||
## 11. 自动化、连接应用、语音与安全存储
|
||||
|
||||
自动化不是前端定时刷新:服务装配接入 bot automations、WaitManager、wait host 和 waits routes,用会话上下文管理等待与继续。
|
||||
证据:[server/index.ts:486](../OpenMausBot/server/index.ts#L486)。
|
||||
|
||||
应用接入分多类:团队连接、cloud connected apps、聊天内应用;主服务分别建立对应 host 和 routes。
|
||||
这些属于与外部应用账户和权限相连的子系统,不能把“配置了连接”当成“所有 bot 都可使用”。
|
||||
证据:[server/index.ts:24](../OpenMausBot/server/index.ts#L24)、[server/index.ts:467](../OpenMausBot/server/index.ts#L467)。
|
||||
|
||||
仓库也有 tts、meetings、phones、vault 等实际子模块。
|
||||
本报告不以目录存在推断会议服务、手机或语音供应商当前可用;这些应在部署时按对应路由、账户和设备逐项验证。
|
||||
|
||||
## 12. 数据到底存在哪里
|
||||
|
||||
默认数据根目录是用户数据 home 下的 .openmausbot,可用 OMB_DATA_DIR 覆盖。
|
||||
还保留从旧 .opengrokbot 目录迁移的逻辑,并创建 events、native 子目录。
|
||||
证据:[server/config.ts:695](../OpenMausBot/server/config.ts#L695)。
|
||||
|
||||
config.json 是持久配置,读取时经过 schema/解析与文件缓存;机器人与群组档案由 store 管理 JSON 文件。
|
||||
证据:[server/config.ts:568](../OpenMausBot/server/config.ts#L568)、[server/config.ts:712](../OpenMausBot/server/config.ts#L712)、[server/store.ts:178](../OpenMausBot/server/store.ts#L178)。
|
||||
|
||||
消息有 SQLite 数据层,运行协调器另有 RuntimeStore:聊天历史和执行状态不能当作同一张表。
|
||||
这类嵌入式存储适合本地单服务,不需要用户先装 PostgreSQL,但备份需要覆盖多个文件。
|
||||
证据:[server/message-db.ts:1](../OpenMausBot/server/message-db.ts#L1)、[server/runtime/store.ts:1](../OpenMausBot/server/runtime/store.ts#L1)。
|
||||
|
||||
用量、决策等追加日志采用 JSONL,适合逐条记录与按月维护;它们不是消息数据库的替代品。
|
||||
证据:[server/usage-ledger.ts:1](../OpenMausBot/server/usage-ledger.ts#L1)、[server/decision-log.ts:1](../OpenMausBot/server/decision-log.ts#L1)。
|
||||
|
||||
外部 Claude/Codex 引擎还有自己的原生会话文件,删除/清理逻辑显式认识它们的 JSONL 布局。
|
||||
证据:[server/host/delete-leftovers.ts:24](../OpenMausBot/server/host/delete-leftovers.ts#L24)。
|
||||
|
||||
不要把整个系统想成“复制一个 JSON 就迁移完了”:至少要考虑配置、档案、消息库、运行状态、附件、原生引擎目录及秘密材料。
|
||||
恢复工作区时,代码还要求先解除团队电脑分配,防止恢复后的团队名字意外获得旧桌面权限。
|
||||
证据:[server/index.ts:12684](../OpenMausBot/server/index.ts#L12684)。
|
||||
|
||||
## 13. 配套服务不是主程序的别名
|
||||
|
||||
### Companion
|
||||
|
||||
companion 有独立 Node 入口和运行脚本,主服务给它提供专用配对入口。
|
||||
它是配套设备接入路线,不是把全部主服务复制到一个手机网页。
|
||||
证据:[package.json:33](../OpenMausBot/package.json#L33)、[companion/src/index.ts:1](../OpenMausBot/companion/src/index.ts#L1)、[server/index.ts:12611](../OpenMausBot/server/index.ts#L12611)。
|
||||
|
||||
### Connector
|
||||
|
||||
connector 的明确用途是:让用户自己的服务器承载一个 Cloud home,通过一条主动向外的连接受管理。
|
||||
两端先证明密钥,管理员任务对这台机器签名,回复重发直到确认,home 请求通过 yamux streams 复用。
|
||||
证据:[connector/package.json:5](../OpenMausBot/connector/package.json#L5)、[connector/src/agent.ts:1](../OpenMausBot/connector/src/agent.ts#L1)。
|
||||
|
||||
因此它是部署与控制代理,不是普通大模型驱动,更不能默认当成无需鉴权的远程 shell。
|
||||
未获团队 Owner 接受时,任务范围只允许 status 和 host-health 两个读操作。
|
||||
证据:[connector/src/agent.ts:27](../OpenMausBot/connector/src/agent.ts#L27)。
|
||||
|
||||
### Relay 与 Cloudflare control-plane
|
||||
|
||||
relay 是独立运行服务:读取环境配置后 startRelay,具备自己的退出与关闭逻辑。
|
||||
它负责连接转发,不拥有主聊天产品全部状态。
|
||||
证据:[relay/src/main.ts:1](../OpenMausBot/relay/src/main.ts#L1)、[relay/src/server.ts:1](../OpenMausBot/relay/src/server.ts#L1)。
|
||||
|
||||
Cloudflare control-plane 是另一个云部署面,有独立入口;不能把它的云基础设施依赖算成离线本地聊天的硬性前提。
|
||||
阅读起点:[cloudflare/control-plane/src/index.ts](../OpenMausBot/cloudflare/control-plane/src/index.ts#L1)。
|
||||
|
||||
## 14. 一次实际工作在架构上如何走
|
||||
|
||||
1. 页面先选择入口与验证会话,才进入完整 App。
|
||||
2. 用户动作进入客户端 store,被翻译成后端 HTTP 请求。
|
||||
3. 服务处理认证、可见范围与维护门,再派给路由或会话逻辑。
|
||||
4. 宿主组合机器人配置、上下文、协调状态,交给所选 ProviderDriver。
|
||||
5. 驱动运行模型/CLI;工具请求按 scope、审批与电脑控制边界处理。
|
||||
6. 结果与状态写入对应持久层,通过 SSE 推给有权看到的页面。
|
||||
7. 如需看实时桌面/浏览器,则另建受认证的 viewer/WebSocket 通道。
|
||||
|
||||
对应证据:[src/main.tsx:40](../OpenMausBot/src/main.tsx#L40)、[src/state/store.tsx:2708](../OpenMausBot/src/state/store.tsx#L2708)、[server/index.ts:12694](../OpenMausBot/server/index.ts#L12694)、[server/contracts.ts:593](../OpenMausBot/server/contracts.ts#L593)、[server/local-computer.ts:28](../OpenMausBot/server/local-computer.ts#L28)、[server/index.ts:14627](../OpenMausBot/server/index.ts#L14627)。
|
||||
|
||||
## 15. 运行依赖和限制
|
||||
|
||||
核心开发环境要求 Node >=24、pnpm 10.33.0,代码使用 ESM 和 Node 的 TypeScript stripping 入口。
|
||||
证据:[package.json:17](../OpenMausBot/package.json#L17)、[package.json:33](../OpenMausBot/package.json#L33)。
|
||||
|
||||
普通网页前端依赖 React/Vite;桌面版另需 Electron;实时远程桌面前端使用 noVNC 包,后端有 ws 与 zod。
|
||||
证据:[package.json:108](../OpenMausBot/package.json#L108)、[package.json:149](../OpenMausBot/package.json#L149)。
|
||||
|
||||
可选能力需要额外条件:所选模型的 CLI/账号/API;本机桌面驱动与系统授权;Docker/Podman 和 Cua 镜像;Boat 云资源;连接应用账户;companion 设备与 relay/控制面部署。
|
||||
没用到的功能不应被当作所有用户的必装依赖。
|
||||
|
||||
主服务集中装配很多功能,重用单个模块时容易碰到配置、全局 store、授权和事件上下文耦合。
|
||||
SQLite/文件存储、原生 CLI session 和桌面平台适配,也限制了“随便放进无状态 serverless 就能运行”的设想。
|
||||
|
||||
代码存在并不保证数据迁移与并发恢复无缺陷;本次禁止运行,不能声称性能、故障恢复、跨平台打包或全部驱动已经验证。
|
||||
|
||||
## 16. 已实现与规划,怎样不看错
|
||||
|
||||
已实现的强证据包括:真正的 React 启动分支、Node HTTP 入口、SSE route、WebSocket gate、内建驱动注册、容器 target、带控制凭据的工具代理、connector 的签名通道。
|
||||
这些都有上面的实际代码引用,不依赖文档标题。
|
||||
|
||||
配置中的 feature flag 只是可选开关。例如 agentsToolBridge 默认不打开;savedSteps 默认开启;usbPhoneTakeover 和 cloudComputerAutoReplace 还各有默认或覆盖规则。
|
||||
不能把这些布尔字段的存在等同于所有引擎、设备和平台都支持该能力。
|
||||
证据:[server/config.ts:247](../OpenMausBot/server/config.ts#L247)。
|
||||
|
||||
仓库的 control-plane roadmap 是规划文本;读它只能知道规划拆分,不能用它覆盖当前实现事实。
|
||||
当前 connector/relay/control-plane 已有代码,也不能反过来证明 roadmap 的每项验收都完成了。
|
||||
证据:[控制面路线图:1](../OpenMausBot/docs/superpowers/plans/2026-08-31-00-control-plane-roadmap.md#L1)。
|
||||
|
||||
## 17. 可复用边界:什么值得拿,什么不能生搬
|
||||
|
||||
最适合先研究的是 shared 事件结构、ProviderDriver 契约、路由上下文和 HTTP/SSE 组合。这些把不同引擎变成统一产品行为。
|
||||
复制前必须一起理解 session、approval、tool scope、能力声明,否则表面接上模型,行为仍可能不兼容。
|
||||
|
||||
电脑部分可复用授权门、运行时适配和 target 身份设计,但实际桌面能力来自 Cua/Boat/平台助手。
|
||||
拿走容器管理代码不等于拿走全部桌面自动化,也不等于获得外部服务使用权。
|
||||
|
||||
多机器人协调有参考价值,但它和持久运行状态、房间上下文、等待用户卡片和停止语义相连;不宜只摘一个 coordinate 函数。
|
||||
客户端 UI 也依赖统一 wire 事件、会话和 store,不能直接视为可插拔聊天组件库。
|
||||
|
||||
connector/relay 应作为独立服务研究,维持签名、认证、限额和重连机制;不要当作聊天后端的几个可复制路由。
|
||||
许可证需同时检查主仓库声明和 third_party 归属,Apache-2.0 的根声明不是替所有 vendored 组件做了许可证保证。
|
||||
证据:[package.json:15](../OpenMausBot/package.json#L15)、[server/contracts.ts:1](../OpenMausBot/server/contracts.ts#L1)。
|
||||
|
||||
## 18. 最终摘要
|
||||
|
||||
它的主干是 React 界面 + Node 原生 HTTP 服务 + 多引擎驱动,Electron 提供桌面壳与本地能力。
|
||||
真正复杂的地方在于让机器人长期工作:多人可见性、协调交接、审批等待、工具和电脑授权、多个持久层,以及故障后的继续/停止语义。
|
||||
Local VM 是容器化 Cua 桌面;Cloud Computer 是远程适配;Your Computer 是平台本机连接,三者不能混为一谈。
|
||||
复用时优先拿契约和边界设计,再按目标功能带走依赖链;不要把整个项目当成轻量聊天 UI,也不要把文档规划或注册项当成已经实测成功。
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
# 三省六部项目规划
|
||||
|
||||
## 已确定范围
|
||||
|
||||
- 本 session 按用户最新澄清交付第一版方案及 Web / dsh-go 样式预览,暂不接入真实宿主或业务后端。具体范围与验收见 [第一版方案](v1-plan.md),原生样式见 [dsh-go 交互预览](../preview/dsh-go.html)。
|
||||
- 使用 DS Bot 的 Bot 团队业务及身份、角色、团队、普通 Agent 机制作为基础。
|
||||
- 上游前端全部不采用,前端自行设计开发;要求适配 dsh-go,具体接口待核验。
|
||||
- OpenMausBot 不再纳入方案。
|
||||
- 每个项目固定10个 Bot、10个独立 session:丞相、三省、六部一一对应。各项目的会话、模型配置、上下文、任务与运行操作相互隔离。
|
||||
|
||||
## 从旧代码沿用的职责
|
||||
|
||||
来源:Git 提交 `832e265` 的 `workbench/core/roles.mjs` 中 SEATS 的 duty、responsibility 字段。以下职责与说明逐字沿用;全部角色显示名称统一为两字:丞相、中书、门下、尚书、吏部、户部、礼部、兵部、刑部、工部。丞相作为十席的配套定义一并列出。
|
||||
|
||||
清空前最后版本 `233ee76` 的 `sansheng/src/roles.js` 和 `sansheng/src/texts.js` 已缩为丞相、尚书、工部三角色,故不用于本次恢复完整十席职责。历史前端有另一套简短标签,此处以核心角色定义为准。
|
||||
|
||||
| 角色 | 职责(原文) | 说明(原文) |
|
||||
|---|---|---|
|
||||
| 丞相 | 接需求、分流、协调、汇报 | 面向用户承接想法:判断是否需要开工、必要时派给具体部门,并把各部门结果汇总成对用户的一次交付。 |
|
||||
| 中书 | 调查、澄清、规划 | 先把问题问清、把材料看全,再给出可执行的方案与验收标准草案,不直接产出最终交付物。 |
|
||||
| 尚书 | 分工建议、组织交付 | 把已经明确的方案拆成部门分工并组织交付;六部直属于尚书这一同级分组,六部之间不是上下级。 |
|
||||
| 门下 | 审议与整体审核 | 对方案和交付做独立审议,指出风险与不达标处。首版没有门下审核的任务必须如实标注“未审核”。 |
|
||||
| 吏部 | 角色和技能配置建议 | 对角色、技能与编制给出建议;职责不含绕过用户授权去改权限或其他项目设置。 |
|
||||
| 户部 | 数据、表格、计算 | 处理数据、表格与计算,结论应可复算。 |
|
||||
| 礼部 | 文档、内容、呈现 | 负责文档、内容与呈现形式,产出可编辑的源文件。 |
|
||||
| 兵部 | 环境、调试、部署 | 负责环境、调试与部署;部署/发布等外部副作用仍服从用户授权与宿主审批。 |
|
||||
| 刑部 | 测试与风险检查 | 做测试与风险检查,给出可追溯的检查结果,而不是一句“已通过”。 |
|
||||
| 工部 | 代码实现与工程产出 | 负责代码实现与工程产出,交付可编辑源文件与真实检查结果。 |
|
||||
|
||||
## 本次沿用边界
|
||||
|
||||
本次搬入的是职责定义,不恢复旧代码、旧前端或旧会话初始化方式。旧文件的布局坐标、派工权限开关和首版初始化策略,不随职责自动成为新方案要求。
|
||||
|
||||
吏部的“编制建议”服从当前每项目固定10个Bot的硬要求,不表示允许自行增加或删除席位。
|
||||
|
||||
职责之外的派工权限、审核是否必须经过、退回及重试规则,留待后续规划;不从职位名称推导额外制度。
|
||||
|
||||
## 前端布局(2026-11-14 最新要求)
|
||||
|
||||
- 左侧导航增加“三省六部”入口;其下工作区、项目树、会话列表与其他现有区域保持当前行为,不纳入此次重设计。
|
||||
- 中间直接复用 DSH 原生会话框。角色切换应导航到当前项目对应的独立 session,不重建聊天引擎。
|
||||
- 右侧 sidebar 建立工作台,包含十席角色切换和角色配置,配置默认折叠。
|
||||
- 工作台样式可复用旧代码:白蓝配色,丞相居中、三省三列、六部两排,支持深色与宽度调整。历史样式参考提交 `832e265` 的 `workbench/panel/lib/client.js`,不恢复其旧业务接线。
|
||||
- dsh-go 仍是正式适配要求;本次窄屏预览只验证布局,不代表完成 dsh-go 的接口对接。
|
||||
|
||||
交互预览:[打开前端原型](../preview/index.html)。截图:[浅色](../preview/desktop-light.png)、[角色配置](../preview/role-config.png)、[深色](../preview/desktop-dark.png)、[窄屏工作台](../preview/mobile-workbench.png)。
|
||||
|
||||
原型中的左栏与中间会话仅为宿主布局示意;未提供截图的原有工作区区域明确占位,不虚构项目或会话。演示输入不调用模型,配置只存本浏览器,未创建十个真实 session,也未修改用户的日常 DSH 配置。正式集成时需要核验入口、sidebar 和会话导航公开接口。
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
# 三省六部第一版方案
|
||||
|
||||
状态:2026-11-14 设计稿,供确认功能与交互。最新要求是“做出第一版的方案,还有 dsh-go 的样式也做给我看看”。当前交付为方案及可点击样式预览,不代表已经安装插件、创建真实会话或完成原生适配。
|
||||
|
||||
## 1. 第一版要解决什么
|
||||
|
||||
用户在现有 DSH 项目里打开“三省六部”,就能找到固定的十个角色,切到对应会话,并单独配置该角色。Web 与 dsh-go 面向同一个项目和同一套会话,不各建一套团队。普通项目和普通会话保持原来的使用方式。
|
||||
|
||||
第一版做到“选项目 → 打开工作台 → 启用十席 → 选角色 → 在原生会话里工作”。启用团队只建立身份和会话,不同时启动十个模型任务。复杂派工、审核门禁和自动流程留到下一版。
|
||||
|
||||
## 2. 已固定的边界
|
||||
|
||||
- 采用 DS Bot 的长期 Bot 身份、角色配置和独立会话思路;不整体安装其客户端,也不接管设置入口。
|
||||
- 每项目固定十个 Bot / 十个角色主会话:丞相、中书、尚书、门下、吏部、户部、礼部、兵部、刑部、工部。没有增删编制入口。
|
||||
- 角色职责全文沿用 [项目规划](project-plan.md) 中从旧代码恢复的版本;卡片只显示短摘要,详情展开后显示全文。
|
||||
- 配置和上下文按项目隔离。相同角色在不同项目里使用不同 session,模型设置也分别保存。
|
||||
- 中间直接使用宿主原生会话。输入、附件、历史、流式输出、停止和审批仍由宿主管理。
|
||||
- 左侧只加入口,不替换工作区、项目树、会话列表、设置或其他宿主组件。
|
||||
- OpenMausBot 不进入本版。
|
||||
|
||||
## 3. Web 交互
|
||||
|
||||
入口放在现有左侧功能导航中,名称“三省六部”。点击后展开右侧工作台,并保持当前项目;若没有选项目,只提示“先从左侧选择一个项目”,不猜测或自动创建项目。
|
||||
|
||||
工作台顶部显示当前项目和十席数量。主体采用已确认的白蓝卡片:丞相顶部居中,三省一排,六部两排;选中角色以蓝色描边。右栏支持收起和调宽,跟随宿主深浅色。
|
||||
|
||||
首次进入尚未启用的项目时,显示“启用此项目的十席”按钮,说明会建立十个独立会话且不会自动运行。启用途中显示实际进度;失败保留已完成绑定,重试只继续未完成项,不从头重复创建。
|
||||
|
||||
已启用时,点击角色直接切换原生会话;再次点击当前角色不新建会话。默认只显示角色卡和职责摘要,“角色配置”折叠为一行。展开后可选择宿主已配置的模型、支持的思考强度以及填写角色补充说明。保存只影响当前项目当前角色,不改变宿主默认模型或其他角色。每个角色是独立 session,模型由该 session 独立保存;界面不设“跟随宿主模型”选项。尚未选择时显示“请选择模型”,选择后显示实际模型名称。若新建会话时用宿主默认模型初始化,也只是一次性取值并保存为具体选择,不能随宿主或其他会话之后的改动自动变化。
|
||||
|
||||
未保存配置切换角色时要明确提示或保留草稿,不能悄悄丢失。运行中的角色可查看配置;第一版建议等本轮结束后再保存模型变更,避免用户误以为当前请求已换模型。
|
||||
|
||||
预览:[Web 三栏交互稿](../preview/index.html)。其中聊天与原工作区为布局示意,不是已嵌入的宿主组件。
|
||||
|
||||
## 4. dsh-go 样式和交互
|
||||
|
||||
这是单独的原生风格设计,不把 Web 的三列整体缩小塞进手机。
|
||||
|
||||
### 4.1 原生会话页
|
||||
|
||||
默认展示现有原生聊天。顶部显示当前角色和当前项目,提供“工作台”入口。原有工作区入口和导航继续使用宿主方式,不再造一棵项目树。点击工作台进入原生会话面板;返回会话时保留输入和滚动位置。
|
||||
|
||||
### 4.2 工作台面板
|
||||
|
||||
面板占用手机的可用宽度,采用紧凑十席卡片,仍然保留丞相、三省、六部结构。角色名称全部两字,按钮触摸面积至少 44px。点击角色选中相应会话,面板下方明确显示“进入丞相会话”等按钮;进入后收起工作台。角色详情和配置入口留在卡片下方,不把整屏变成表单。
|
||||
|
||||
### 4.3 角色配置页
|
||||
|
||||
顶部显示当前项目和角色;职责以可折叠文字展示。模型通过原生单选列表选择,实际候选来自宿主已配置目录,不让用户在手机上输入 provider/model 字符串。保存后反馈明确,不触发模型运行。
|
||||
|
||||
已查到的原生面板协议支持按钮、单选、开关、tabs、accordion,但不提供自由文本输入。因此第一版把角色补充说明作为只读详情,提示“请在 Web 端编辑”;不在原生样式里画一个无法兑现的文本编辑器。若后续核验到宿主独立文本编辑接口,再增加编辑能力。
|
||||
|
||||
窄屏按会话、工作台、配置分屏;宽屏布局如何利用更多空间,以 dsh-go 实机接口为准。本次不承诺原生左导航能加入口,也不把 GenUI 的聊天快捷入口误当成全局导航注册。
|
||||
|
||||
预览:[dsh-go 原生风格交互稿](../preview/dsh-go.html)。可切深浅色、选角色、进入演示会话并选择模型。图中宿主导航外壳是样式提案,模型名称为示例;没有假装已拿到 App 的真实截图。
|
||||
|
||||
## 5. 第一版功能范围
|
||||
|
||||
| 功能 | 第一版安排 | 验收要点 |
|
||||
| --- | --- | --- |
|
||||
| 十席身份及角色职责 | 包含 | 名称固定;职责全文与旧代码一致 |
|
||||
| 项目内十个独立主会话 | 包含 | 重开不重复建会话;项目切换不串线 |
|
||||
| 原生会话复用 | 包含 | 不注册主聊天替换槽,不自写聊天引擎 |
|
||||
| 角色切换、职责查看 | 两端包含 | 始终落到当前项目对应 session |
|
||||
| 模型和思考强度选择 | 两端规划包含 | 只显示可用选项,不改宿主默认;原生 API 接通后验收 |
|
||||
| 角色补充说明编辑 | Web 包含;dsh-go 先只读 | 原生无自由文本控件时不伪造可编辑功能 |
|
||||
| 浅色、深色及收起面板 | 包含 | 不污染其他插件样式 |
|
||||
| 权限/审批/运行控制 | 复用宿主 | 角色称号不提升权限,不重复实现审批 |
|
||||
| 自动派工、审核门禁、返工流程 | 留后续 | 先规划规则,不从官职名称推导强制流程 |
|
||||
| 群聊、额外团队会话、任务大屏 | 留后续 | 第一版不额外生成第十一个团队主会话 |
|
||||
| 文件安全隔离 | 遵从宿主权限 | 项目数据隔离不等于沙箱隔离,不做过度承诺 |
|
||||
|
||||
## 6. 接入方案及已核实事项
|
||||
|
||||
独立插件分为“角色与绑定服务、Web 工作台、dsh-go 原生面板”。二者读取同一项目状态,原生会话负责实际执行。不会通过读取 DS Bot 的私有状态文件来冒充兼容,也不依赖 DS Bot 前端。
|
||||
|
||||
宿主已有公开 workspaceRegistry、sessionController 和 systemPrompt.section。模型选择可以通过原生 Agent 的会话级 model.select 记录为会话事件;controller.selectModel 会额外改变默认模型,不能直接拿来实现项目内设置。具体证据见 [宿主契约调研](host-contract-research.md)。
|
||||
|
||||
会话创建不能简单当作永久幂等操作。需要先持久化计划会话 ID,先检查是否已存在,再创建缺失项;任何返回 ID 不一致或工作区附着失败,都应保留待核对记录,不能静默重试生成更多会话。
|
||||
|
||||
dsh-go 已有原生插件面板桥接证据,来自本机 GenUI 插件说明及实现。原生面板需要现有 dshGo bridge;GenUI 的持久状态实现另需 DSH 0.2.1-rc.2 或更新的 session-state API,这不是整个 dsh-go 的最低版本声明。原生作用域只已证实含 sessionId/messageId/callId,没有 workspaceId;需由会话反查项目。已核实的 effect 不包含会话跳转,详见 [客户端契约调研](client-contract-research.md)。本地引擎有覆盖描述,SSH/relay 场景仍取决于对应 bridge;没有桥接时显示不支持,不私自换成 WebView、补丁 App 或自动降级创建另一套 session。角色导航到指定 session 的原生 effect、插件入口位置仍需正式开发时核验。
|
||||
|
||||
## 7. 实现顺序与验收
|
||||
|
||||
1. 对照这两份样式确认第一版范围;当前交付到此。
|
||||
2. 实现项目内身份及十席会话绑定,先在隔离测试目录验证创建、恢复、失败重试和跨项目隔离。
|
||||
3. 接 Web 导航和右侧工作台,确认原项目树、普通会话、设置入口均未被接管。
|
||||
4. 接 dsh-go 原生面板,做真实设备触摸、返回、滚动、模型选择和目标会话导航验收;本地/SSH/relay 分开报告支持情况。
|
||||
5. 两个项目同时开启,分别修改工部模型;重启后确认十席不重复、配置和会话不交叉,再打包发布。
|
||||
|
||||
必须单独检查过期操作:切换项目后才回来的请求结果不能覆盖新项目;旧面板按钮携带的项目/session/revision 不匹配时应拒绝并要求刷新。会话被用户删除时明确标成缺失,不能把另一个普通会话绑上来。
|
||||
|
||||
当前没有安装/发布可用插件。仓库中早期角色/存储试写为探索文件,不作为第一版实现完成的证据;现有宿主、真实模型、用户 profile 和会话都未改动。
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
import {spawn} from 'node:child_process';
|
||||
import {mkdtemp,writeFile,rm} from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import {join,dirname} from 'node:path';
|
||||
import {fileURLToPath,pathToFileURL} from 'node:url';
|
||||
const dir=dirname(fileURLToPath(import.meta.url));const profile=await mkdtemp(join(tmpdir(),'sansheng-preview-'));let browser,ws;const checks=[];const errors=[];
|
||||
try{
|
||||
browser=spawn('C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',['--headless=new','--disable-gpu','--no-first-run','--no-default-browser-check','--remote-debugging-port=0','--user-data-dir='+profile,'about:blank'],{stdio:['ignore','ignore','pipe']});
|
||||
const endpoint=await new Promise((resolve,reject)=>{let log='';const timer=setTimeout(()=>reject(Error('Browser startup timeout')),20000);browser.stderr.on('data',b=>{log+=b;const m=log.match(/DevTools listening on (.+)/);if(m){clearTimeout(timer);resolve(m[1].trim())}});browser.on('error',reject);browser.on('exit',code=>{if(!log.includes('DevTools listening'))reject(Error('Browser exited '+code))})});
|
||||
ws=new WebSocket(endpoint);await new Promise((resolve,reject)=>{ws.onopen=resolve;ws.onerror=reject});let n=0;const pending=new Map();ws.onmessage=e=>{const m=JSON.parse(e.data);if(m.id){const p=pending.get(m.id);pending.delete(m.id);if(m.error)p.reject(Error(JSON.stringify(m.error)));else p.resolve(m.result)}else if(m.method==='Runtime.exceptionThrown')errors.push(m.params.exceptionDetails.text)};
|
||||
const cdp=(method,params={},sessionId)=>new Promise((resolve,reject)=>{const id=++n;pending.set(id,{resolve,reject});ws.send(JSON.stringify({id,method,params,...(sessionId?{sessionId}:{})}))});
|
||||
const {targetId}=await cdp('Target.createTarget',{url:'about:blank'});const {sessionId}=await cdp('Target.attachToTarget',{targetId,flatten:true});const call=(m,p={})=>cdp(m,p,sessionId);await call('Page.enable');await call('Runtime.enable');
|
||||
const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw Error(r.exceptionDetails.exception?.description||r.exceptionDetails.text);return r.result.value};
|
||||
const waitReady=async()=>{for(let i=0;i<100;i++){if(await evaluate('document.querySelectorAll(".role").length===10'))return;await new Promise(r=>setTimeout(r,60))}throw Error('Page not ready')};
|
||||
const check=async(name,code)=>{if(!await evaluate(code))throw Error('FAIL '+name);checks.push(name)};
|
||||
const shot=async name=>{const r=await call('Page.captureScreenshot',{format:'png',captureBeyondViewport:false});await writeFile(join(dir,name),Buffer.from(r.data,'base64'))};
|
||||
await call('Emulation.setDeviceMetricsOverride',{width:1440,height:1100,deviceScaleFactor:1,mobile:false});await call('Page.navigate',{url:pathToFileURL(join(dir,'dsh-go.html')).href});await waitReady();
|
||||
await check('Ten fixed two-character native role buttons','document.querySelectorAll(".role").length===10&&[...document.querySelectorAll(".role-name")].every(x=>x.textContent.length===2)');
|
||||
await check('Unset and legacy inherited models require explicit choice','(()=>{saved.lead="跟随宿主模型";screens.forEach((_,i)=>render(i));document.querySelector("#phone-2 [data-action=save]").click();const blocked=!saved.gongbu;document.querySelector("#phone-2 [data-action=models]").click();const ok=blocked&&model("lead")===""&&document.querySelector("#phone-2 [data-confirm]").disabled&&document.querySelectorAll("#phone-2 [data-model]").length===2;document.querySelector("#phone-2 .sheet-bg").remove();delete saved.lead;return ok})()');
|
||||
await check('Selected role opens corresponding demo conversation','(()=>{document.querySelector("#phone-1 [data-role=gongbu]").click();document.querySelector("#phone-1 .panel-footer button").click();const ok=document.querySelector("#phone-1 .header-title").textContent==="工部";document.querySelector("#phone-1 [data-action=workbench]").click();return ok})()');
|
||||
await check('Model chooser changes only selected role','(()=>{document.querySelector("#phone-2 [data-action=models]").click();document.querySelectorAll("#phone-2 [data-model]")[1].click();document.querySelector("#phone-2 [data-confirm]").click();document.querySelector("#phone-2 [data-action=save]").click();return model("gongbu")===models[1]&&model("lead")===""})()');
|
||||
await call('Page.reload');await waitReady();await check('Demo model persists across reload','model("gongbu")===models[1]');
|
||||
await check('Role explanation expands without native text editor','(()=>{document.querySelector("#phone-2 [data-action=details]").click();return document.querySelector("#phone-2 .details").textContent.includes("Web")&&!document.querySelector("#phone-2 textarea")&&!document.querySelector("#phone-2 input")})()');
|
||||
await evaluate('localStorage.removeItem("sansheng-go-design:v1");saved={gongbu:models[1]};screens.forEach((_,i)=>render(i))');await shot('dsh-go-light.png');
|
||||
await evaluate('document.getElementById("theme").click()');await check('Native-style dark theme switches','document.documentElement.dataset.theme==="dark"');await shot('dsh-go-dark.png');
|
||||
await evaluate('document.getElementById("theme").click();document.querySelector("#phone-2 [data-action=models]").click()');await shot('dsh-go-models.png');
|
||||
await call('Emulation.setDeviceMetricsOverride',{width:390,height:1000,deviceScaleFactor:1,mobile:true});await check('Narrow preview contains gallery without body overflow','document.documentElement.scrollWidth<=390');await shot('dsh-go-narrow.png');
|
||||
if(errors.length)throw Error(errors.join(';'));console.log(JSON.stringify({passed:checks.length,checks,consoleErrors:errors,screenshots:['dsh-go-light.png','dsh-go-dark.png','dsh-go-models.png','dsh-go-narrow.png']}));
|
||||
await cdp('Browser.close').catch(()=>{});
|
||||
}finally{ws?.close();browser?.kill();await new Promise(r=>setTimeout(r,500));await rm(profile,{recursive:true,force:true,maxRetries:5,retryDelay:300}).catch(()=>{})}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
'/c/Users/qyh15/.dsh/dsh-runtimes/dsh-primary-runtime/dependencies/node/bin/node.exe' preview/check-dsh-go.mjs
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
import {spawn} from 'node:child_process';
|
||||
import {mkdtemp,writeFile,rm} from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import {join,dirname} from 'node:path';
|
||||
import {fileURLToPath,pathToFileURL} from 'node:url';
|
||||
const dir=dirname(fileURLToPath(import.meta.url));const profile=await mkdtemp(join(tmpdir(),'sansheng-preview-'));let browser,ws;const checks=[];const errors=[];
|
||||
try{
|
||||
browser=spawn('C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',['--headless=new','--disable-gpu','--no-first-run','--no-default-browser-check','--remote-debugging-port=0','--user-data-dir='+profile,'about:blank'],{stdio:['ignore','ignore','pipe']});
|
||||
const endpoint=await new Promise((resolve,reject)=>{let log='';const timer=setTimeout(()=>reject(Error('Browser startup timeout')),20000);browser.stderr.on('data',b=>{log+=b;const m=log.match(/DevTools listening on (.+)/);if(m){clearTimeout(timer);resolve(m[1].trim())}});browser.on('error',reject);browser.on('exit',code=>{if(!log.includes('DevTools listening'))reject(Error('Browser exited '+code))})});
|
||||
ws=new WebSocket(endpoint);await new Promise((resolve,reject)=>{ws.onopen=resolve;ws.onerror=reject});let n=0;const pending=new Map();ws.onmessage=e=>{const m=JSON.parse(e.data);if(m.id){const p=pending.get(m.id);pending.delete(m.id);if(m.error)p.reject(Error(JSON.stringify(m.error)));else p.resolve(m.result)}else if(m.method==='Runtime.exceptionThrown')errors.push(m.params.exceptionDetails.text)};
|
||||
const cdp=(method,params={},sessionId)=>new Promise((resolve,reject)=>{const id=++n;pending.set(id,{resolve,reject});ws.send(JSON.stringify({id,method,params,...(sessionId?{sessionId}:{})}))});
|
||||
const {targetId}=await cdp('Target.createTarget',{url:'about:blank'});const {sessionId}=await cdp('Target.attachToTarget',{targetId,flatten:true});const call=(m,p={})=>cdp(m,p,sessionId);await call('Page.enable');await call('Runtime.enable');
|
||||
const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw Error(r.exceptionDetails.exception?.description||r.exceptionDetails.text);return r.result.value};
|
||||
const waitReady=async()=>{for(let i=0;i<100;i++){if(await evaluate('document.querySelectorAll(".role").length===10'))return;await new Promise(r=>setTimeout(r,60))}throw Error('Page not ready')};
|
||||
const check=async(name,code)=>{if(!await evaluate(code))throw Error('FAIL '+name);checks.push(name)};
|
||||
const shot=async name=>{const r=await call('Page.captureScreenshot',{format:'png',captureBeyondViewport:false});await writeFile(join(dir,name),Buffer.from(r.data,'base64'))};
|
||||
await call('Emulation.setDeviceMetricsOverride',{width:1440,height:900,deviceScaleFactor:1,mobile:false});await call('Page.navigate',{url:pathToFileURL(join(dir,'index.html')).href});await waitReady();
|
||||
await check('Ten fixed two-character roles','document.querySelectorAll(".role").length===10 && [...document.querySelectorAll(".role-name")].every(x=>x.textContent.length===2)');
|
||||
await check('Unselected role cannot silently save a default model','(()=>{document.getElementById("config-body").dispatchEvent(new Event("submit",{cancelable:true}));return !configs.lead&&document.getElementById("composer-model").textContent==="请选择模型"&&!document.querySelector("option[value=inherit]")})()');
|
||||
await check('Role switches conversation and preserves draft','(()=>{document.getElementById("message").value="draft-lead";document.querySelector("[data-role=gongbu]").click();const ok=document.getElementById("chat-name").textContent==="工部" && document.getElementById("message").value==="";document.querySelector("[data-role=lead]").click();return ok&&document.getElementById("message").value==="draft-lead"})()');
|
||||
await check('Role configuration is isolated','(()=>{document.querySelector("[data-role=gongbu]").click();document.getElementById("config-toggle").click();document.getElementById("model").value="custom";document.getElementById("model").dispatchEvent(new Event("change"));document.getElementById("custom-model").value="demo-model";document.getElementById("role-note").value="只处理工程任务";document.getElementById("config-body").requestSubmit();document.querySelector("[data-role=lead]").click();return document.getElementById("model").value===""&&document.getElementById("role-note").value===""})()');
|
||||
await call('Page.reload');await waitReady();await check('Configuration persists after reload','(()=>{document.querySelector("[data-role=gongbu]").click();return document.getElementById("custom-model").value==="demo-model"&&document.getElementById("role-note").value==="只处理工程任务"})()');
|
||||
await check('Demo messages remain text and separate by role','(()=>{document.getElementById("message").value="<img src=x onerror=alert(1)>";document.getElementById("composer").requestSubmit();const ok=!document.querySelector(".message img")&&document.querySelector(".message").textContent.includes("<img");document.querySelector("[data-role=lead]").click();return ok&&!document.querySelector(".message")})()');
|
||||
await check('Sidebar closes and entry reopens it','(()=>{document.getElementById("close-panel").click();const ok=document.getElementById("app").classList.contains("workbench-hidden");document.getElementById("entry").click();return ok&&!document.getElementById("app").classList.contains("workbench-hidden")})()');
|
||||
await check('Keyboard sidebar resizing','(()=>{const r=document.getElementById("resize");r.dispatchEvent(new KeyboardEvent("keydown",{key:"ArrowLeft",bubbles:true}));return r.getAttribute("aria-valuenow")==="384"})()');
|
||||
await evaluate('chats.gongbu=[];drafts.lead="";renderChat()');
|
||||
await evaluate('document.documentElement.style.setProperty("--rail-width","374px");document.documentElement.dataset.theme="light";document.getElementById("toast").hidden=true;document.getElementById("config-body").hidden=true;document.getElementById("config-toggle").setAttribute("aria-expanded","false")');await shot('desktop-light.png');
|
||||
await evaluate('document.querySelector("[data-role=gongbu]").click();document.getElementById("config-toggle").click();document.getElementById("toast").hidden=true');await call('Emulation.setDeviceMetricsOverride',{width:1440,height:1140,deviceScaleFactor:1,mobile:false});await shot('role-config.png');await call('Emulation.setDeviceMetricsOverride',{width:1440,height:900,deviceScaleFactor:1,mobile:false});
|
||||
await evaluate('document.querySelector("[data-role=lead]").click();document.getElementById("config-toggle").click();document.documentElement.dataset.theme="dark";document.getElementById("workbench").scrollTop=0');await shot('desktop-dark.png');
|
||||
await call('Emulation.setDeviceMetricsOverride',{width:390,height:844,deviceScaleFactor:1,mobile:true});await evaluate('document.documentElement.dataset.theme="light";document.getElementById("close-panel").click()');await check('Narrow chat has no horizontal overflow','document.documentElement.scrollWidth<=390');await shot('mobile-chat.png');await evaluate('document.getElementById("panel-toggle").click()');await check('Narrow workbench remains visible without overflow','document.documentElement.scrollWidth<=390&&document.getElementById("workbench").getBoundingClientRect().right<=391');await shot('mobile-workbench.png');
|
||||
if(errors.length)throw Error(errors.join(';'));console.log(JSON.stringify({passed:checks.length,checks,consoleErrors:errors,screenshots:['desktop-light.png','role-config.png','desktop-dark.png','mobile-chat.png','mobile-workbench.png']}));
|
||||
await cdp('Browser.close').catch(()=>{});
|
||||
}finally{ws?.close();browser?.kill();await new Promise(r=>setTimeout(r,500));await rm(profile,{recursive:true,force:true,maxRetries:5,retryDelay:300}).catch(()=>{})}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
'/c/Users/qyh15/.dsh/dsh-runtimes/dsh-primary-runtime/dependencies/node/bin/node.exe' preview/check-preview.mjs
|
||||
|
After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 125 KiB |
|
After Width: | Height: | Size: 124 KiB |
|
After Width: | Height: | Size: 124 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 92 KiB |
|
|
@ -0,0 +1 @@
|
|||
node_modules/
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
# 三省六部 v0.1 内部接口契约
|
||||
|
||||
本文件约束 Web 工作台、dsh-go 原生面板与宿主服务之间的数据形状。三端共用 `src/shared/roles.js` 与 `src/shared/schema.js`。
|
||||
|
||||
## 十席
|
||||
|
||||
- `SEAT_IDS` 顺序:lead, zhongshu, shangshu, menxia, libu, hubu, lipu, bingbu, xingbu, gongbu。
|
||||
- `SEATS[id]` = `{ id, label(两字), duty(短摘要), responsibility(职责全文) }`。
|
||||
- `SEAT_GROUPS` = `{ lead:[lead], sansheng:[zhongshu,shangshu,menxia], liubu:[libu,hubu,lipu,bingbu,xingbu,gongbu] }`(工作台布局用)。
|
||||
|
||||
## 宿主 HTTP:POST `/api/sansheng`
|
||||
|
||||
请求体 `{ endpoint: string, payload?: object }`;成功回 `{ ok:true, value }`,失败回 `{ ok:false, error:{ code, message } }`(HTTP 200)。
|
||||
|
||||
| endpoint | payload | value |
|
||||
|---|---|---|
|
||||
| `list` | — | `{ projects:[{ id, name, status, revision }] }` |
|
||||
| `project` | `{ projectId }` | 项目视图(见下) |
|
||||
| `open` | `{ workspaceId, name?, path? }` | 项目视图;不存在则按 workspaceId 建项目记录(不创建会话) |
|
||||
| `enable` | `{ projectId }` | 项目视图;严格创建/恢复十席会话 |
|
||||
| `configure` | `{ projectId, seatId, model:({provider,model,reasoningEffort?}|null), instructions? }` | `{ seat }` |
|
||||
| `models` | — | `{ providers:[{ provider, models:[{ model, reasoningEffort?:[...] }] }], default:({provider,model}|null), failures:[...] }` |
|
||||
|
||||
错误码:`sansheng/invalid`、`sansheng/not-found`、`sansheng/conflict`、`sansheng/unbound`(席尚未绑定会话)、`sansheng/model-invalid`、`sansheng/state-corrupt`。
|
||||
|
||||
## 项目视图
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"revision": 0,
|
||||
"project": {
|
||||
"id": "ws-1", "name": "项目名", "workspaceId": "ws-1", "path": "D:/x", "status": "pending|provisioning|ready|error",
|
||||
"seats": [
|
||||
{ "id":"lead","label":"丞相","duty":"...","responsibility":"...","status":"pending|creating|bound|failed|missing","sessionId":null,"model":null,"instructions":"","error":null }
|
||||
],
|
||||
"groups": { "lead":["lead"], "sansheng":[...], "liubu":[...] }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 会话/模型规则(两端 UI 必须遵守)
|
||||
|
||||
- 每席一个独立 root Session;切换角色 = 导航到该席 `sessionId`,不新建、不重建聊天引擎。
|
||||
- 模型未选择显示“请选择模型”;选择后显示具体名称。界面不提供“跟随宿主模型”选项。
|
||||
- “启用”只建立十个会话,不自动运行模型。
|
||||
- 角色补充说明:Web 可编辑;原生面板只读(原生无自由文本控件)。
|
||||
|
||||
## Web 工作台(`src/client/`)
|
||||
|
||||
纯视图模型函数 `buildWorkbenchView(view, ui)` 必须可由 node 直接 import 测试(不依赖 React/DOM):
|
||||
- `view` = 项目视图;`ui` = `{ selectedSeatId, models, draft }`。
|
||||
- 返回:`{ projectTitle, ready, seats:[{id,name,duty,statusLabel,selected}], groups, selected:{ id,name,responsibility,duty,modelValue,modelLabel,instructions,modelOptions } }`。
|
||||
- `seats` 必须正好十项且 name 两字;未选模型时 `modelLabel==='请选择模型'` 且 `modelValue===''`;`modelOptions` 不得含 value==='inherit' 的项。
|
||||
React 接线用 `React.createElement`(不用 JSX,便于 esbuild 直接打包)。入口 `export const inject=[...]` + `export function apply(ctx)`。
|
||||
|
||||
## dsh-go 原生面板(`src/native/`)
|
||||
|
||||
纯视图树函数 `buildPanelView(input)` 必须可由 node 直接 import 测试:
|
||||
- `input` = `{ project, selectedSeatId, models }`。
|
||||
- 返回原生 view 节点(`{ type:'stack'|'row'|'text'|'list'|'callout'|'button'|'accordion'... }`)。
|
||||
- 硬约束:节点数 ≤120、深度 ≤8、单个 options/列表 ≤8 项、无自由文本输入控件;十席按 lead/sansheng/liubu 分组呈现。
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
# 三省六部(dsh-sansheng)· 第一版
|
||||
|
||||
在 DSH 里为每个项目提供固定的十席角色(丞相、中书、门下、尚书、吏部、户部、礼部、兵部、刑部、工部),
|
||||
每席绑定一个独立的原生命 root Session,模型与补充说明按项目独立保存。中间复用宿主原生会话,不替换聊天引擎。
|
||||
|
||||
当前进度(对应 `docs/v1-plan.md` §7 实施顺序):
|
||||
|
||||
- ✅ 第 2 步:项目内身份与十席会话绑定(宿主服务 + 严格创建/恢复/失败重试/跨项目隔离,`npm test` 用 fake ctx 验证)。
|
||||
- 🟡 第 3 步:Web 入口与右侧工作台(源代码就位,导航/侧栏/会话跳转的原生接口仍需真机核验,见 docs)。
|
||||
- 🟡 第 4 步:dsh-go 原生面板(源代码就位,触摸/返回/会话跳转需真机核验)。
|
||||
- ⬜ 第 5 步:双项目联调后打包发布。
|
||||
|
||||
**本包尚未安装到任何 DSH profile,也未改动用户的日常 DSH 配置。**
|
||||
|
||||
## 目录
|
||||
|
||||
- `index.js` — 宿主插件入口(`name` / `inject` / `apply`)。
|
||||
- `src/shared/` — 十席定义与项目状态 schema(前后端共用)。
|
||||
- `src/host/` — 项目状态存储、严格会话创建/恢复、模型配置(不写 profile)、提示词 section、HTTP `api/sansheng`。
|
||||
- `src/client/` — Web 工作台(纯视图模型 + React 接线 + 传输层)。
|
||||
- `src/native/` — dsh-go 原生面板(纯视图树构造 + bridge 接线)。
|
||||
- `test/` — fake ctx 单元/集成测试。
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
# 三省六部:挂到 DSH 宿主的三省六部工作台插件。
|
||||
- insert:
|
||||
- id: sansheng
|
||||
name: 'dsh-sansheng'
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
// 三省六部宿主插件入口:只使用宿主公开注入服务,不 patch DSH,不写 profile 全局默认。
|
||||
import { SanshengStore } from './src/host/store.js'
|
||||
import { createProvisioner } from './src/host/provision.js'
|
||||
import { SanshengService } from './src/host/service.js'
|
||||
import { createApiHandler } from './src/host/api.js'
|
||||
import { installPromptSection } from './src/host/prompt.js'
|
||||
import { sanshengStatePath } from './src/host/paths.js'
|
||||
import { ROUTE } from './src/host/constants.js'
|
||||
|
||||
export const name = 'sansheng'
|
||||
export const inject = ['workspaceRegistry', 'sessionController', 'agents', 'llm', 'systemPrompt', 'connection']
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
const store = new SanshengStore(
|
||||
typeof config.statePath === 'string' && config.statePath !== '' ? config.statePath : sanshengStatePath(config.home),
|
||||
)
|
||||
try {
|
||||
await store.load()
|
||||
} catch (error) {
|
||||
// 状态损坏不能静默丢弃;记录后仍允许插件加载,但后续操作会因空状态而需重新启用。
|
||||
console.warn(`sansheng: ${error?.message ?? error}`)
|
||||
}
|
||||
|
||||
const host = {
|
||||
workspaceRegistry: ctx.workspaceRegistry,
|
||||
sessionController: ctx.sessionController,
|
||||
agents: ctx.agents,
|
||||
llm: ctx.llm,
|
||||
}
|
||||
const provisioner = createProvisioner({ store, host })
|
||||
const service = new SanshengService({ store, host, provisioner })
|
||||
const handle = createApiHandler(service)
|
||||
|
||||
ctx.effect(() => installPromptSection(ctx, { store }), 'sansheng: prompt section')
|
||||
|
||||
// 复用宿主共享 /api 通道;浏览器带会话 Cookie 认证。
|
||||
ctx.effect(() => ctx.connection.fetch.register({
|
||||
path: ROUTE,
|
||||
methods: ['POST'],
|
||||
requestBody: 'buffered',
|
||||
fetch: async request => {
|
||||
let body
|
||||
try { body = await request.json() } catch { body = {} }
|
||||
const result = await handle(String(body?.endpoint ?? ''), body?.payload)
|
||||
return new Response(JSON.stringify(result), { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
},
|
||||
}), 'sansheng: api route')
|
||||
|
||||
return service
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
{
|
||||
"name": "dsh-sansheng",
|
||||
"version": "0.1.0",
|
||||
"description": "三省六部:每个项目固定十席角色与独立会话的 DSH 插件(第一版)。",
|
||||
"keywords": [
|
||||
"dsh-plugin",
|
||||
"deepseek-harness",
|
||||
"dsh",
|
||||
"sansheng",
|
||||
"multi-agent",
|
||||
"agents"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"exports": {
|
||||
".": "./index.js",
|
||||
"./client": "./client.js",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"client.js",
|
||||
"src/",
|
||||
"cordis.patch.yml",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "node scripts/build-client.mjs",
|
||||
"build:check": "node scripts/build-client.mjs --check",
|
||||
"test": "node --test --test-timeout=120000 \"test/*.test.js\""
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "*",
|
||||
"@deepseek-ai/dsh-llm": "*",
|
||||
"@deepseek-ai/dsh-web": "*"
|
||||
},
|
||||
"dsh": {
|
||||
"client": {
|
||||
"platform": "web",
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-client-ui-primitives"
|
||||
]
|
||||
},
|
||||
"bundle": {
|
||||
"patch": "./cordis.patch.yml"
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"esbuild": "0.28.2"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
// Builds client.js (browser half) from src/client. Mirrors the DS Bot wrapper so dsh can
|
||||
// load it as a classic script and resolve platform modules from the shell.
|
||||
// node scripts/build-client.mjs writes client.js
|
||||
// node scripts/build-client.mjs --check exit 1 if client.js differs from a fresh build
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const PLUGIN = dirname(dirname(fileURLToPath(import.meta.url)))
|
||||
const OUTPUT = join(PLUGIN, 'client.js')
|
||||
const PLATFORM_MODULES = ['react', 'react-dom', '@deepseek-ai/dsh-client-ui-primitives']
|
||||
|
||||
export async function bundleClient() {
|
||||
let esbuild
|
||||
try { esbuild = await import('esbuild') } catch {
|
||||
throw new Error('缺少 esbuild:请先在包内安装 devDependencies(pnpm/npm i),再构建 client.js。')
|
||||
}
|
||||
const result = await esbuild.build({
|
||||
absWorkingDir: PLUGIN,
|
||||
entryPoints: ['src/client/index.js'],
|
||||
bundle: true,
|
||||
format: 'cjs',
|
||||
platform: 'browser',
|
||||
target: 'es2022',
|
||||
external: PLATFORM_MODULES,
|
||||
treeShaking: false,
|
||||
charset: 'utf8',
|
||||
write: false,
|
||||
logLevel: 'silent',
|
||||
})
|
||||
if (result.warnings.length > 0) throw new Error('esbuild warnings:\n' + result.warnings.map(w => w.text).join('\n'))
|
||||
return [
|
||||
'// Generated from src/client by `npm run build` (scripts/build-client.mjs). Do not edit by hand.',
|
||||
'window.__ModuleLoader__.load({',
|
||||
" id: 'sansheng',",
|
||||
' factory: (require) => {',
|
||||
'const module = { exports: {} }',
|
||||
result.outputFiles[0].text.trimEnd(),
|
||||
"return Object.defineProperty({ ...module.exports }, Symbol.toStringTag, { value: 'Module' })",
|
||||
' },',
|
||||
'})',
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
const next = await bundleClient()
|
||||
if (process.argv.includes('--check')) {
|
||||
let current = ''
|
||||
try { current = readFileSync(OUTPUT, 'utf8') } catch {}
|
||||
if (current !== next) { console.error('client.js 与 src/client 不一致,请运行 npm run build'); process.exit(1) }
|
||||
console.log('client.js 是最新的')
|
||||
} else {
|
||||
writeFileSync(OUTPUT, next)
|
||||
console.log('已写出 client.js')
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,504 @@
|
|||
// 三省六部 Web 插件入口:左侧追加「三省六部」入口,点开右侧工作台。
|
||||
// 所有对宿主可选服务的调用都用 ctx.get(...) 特性探测,探测不到就降级,不伪造接口。
|
||||
|
||||
import { createElement as h, Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { SEAT_IDS } from '../shared/roles.js'
|
||||
import {
|
||||
buildWorkbenchView,
|
||||
findModelOption,
|
||||
updateDraft,
|
||||
clearDraft,
|
||||
UNCHOSEN_MODEL_LABEL,
|
||||
} from './workbench.js'
|
||||
import { request } from './transport.js'
|
||||
import { CSS as WORKBENCH_CSS } from './styles.js'
|
||||
import { install as installNativePanel } from '../native/index.js'
|
||||
|
||||
export const inject = ['sessions', 'uiWorkspace', 'uiConversation', 'slots', 'theme', 'layout']
|
||||
|
||||
const PLUGIN_ID = 'dsh-sansheng'
|
||||
const TAB_ID = 'sansheng-workbench'
|
||||
|
||||
function installStyles(doc, tag, text) {
|
||||
if (!doc || !doc.head) return null
|
||||
const style = doc.createElement('style')
|
||||
// 带上插件 id,避免被 ClientModuleSystem 当作别人的模块样式回收。
|
||||
style.dataset.plugin = PLUGIN_ID
|
||||
style.dataset.sansheng = tag
|
||||
style.textContent = text
|
||||
doc.head.appendChild(style)
|
||||
return style
|
||||
}
|
||||
|
||||
// ---------- 小图标(createElement,无 JSX) ----------
|
||||
function svgWrap(children, props) {
|
||||
return h('svg', {
|
||||
viewBox: '0 0 24 24', width: 16, height: 16, fill: 'none', stroke: 'currentColor',
|
||||
strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': 'true',
|
||||
...(props || {}),
|
||||
}, children)
|
||||
}
|
||||
const TreeIcon = (props) => svgWrap([
|
||||
h('rect', { key: 'a', x: 9, y: 2, width: 6, height: 5, rx: 1 }),
|
||||
h('path', { key: 'b', d: 'M12 7v5M5 16v-4h14v4' }),
|
||||
h('rect', { key: 'c', x: 2, y: 16, width: 6, height: 5, rx: 1 }),
|
||||
h('rect', { key: 'd', x: 16, y: 16, width: 6, height: 5, rx: 1 }),
|
||||
], props)
|
||||
const CloseIcon = (props) => svgWrap([h('path', { key: 'p', d: 'm6 6 12 12M6 18 18 6' })], props)
|
||||
const FolderIcon = (props) => svgWrap([h('path', { key: 'p', d: 'M3 7V5a2 2 0 0 1 2-2h5l2 3h7a2 2 0 0 1 2 2v11H3Z' })], props)
|
||||
const GearIcon = (props) => svgWrap([
|
||||
h('path', { key: 'a', d: 'M4 6h16M4 12h16M4 18h16' }),
|
||||
h('circle', { key: 'b', cx: 9, cy: 6, r: 2 }),
|
||||
h('circle', { key: 'c', cx: 16, cy: 12, r: 2 }),
|
||||
h('circle', { key: 'd', cx: 8, cy: 18, r: 2 }),
|
||||
], props)
|
||||
const ChevronIcon = (props) => h('svg', {
|
||||
viewBox: '0 0 24 24', width: 14, height: 14, fill: 'none', stroke: 'currentColor',
|
||||
strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round',
|
||||
className: 'ssw-chevron', 'aria-hidden': 'true',
|
||||
}, h('path', { d: 'm6 9 6 6 6-6' }))
|
||||
|
||||
function isFn(value) { return typeof value === 'function' }
|
||||
function safeCall(obj, name) {
|
||||
try {
|
||||
if (!obj || !isFn(obj[name])) return undefined
|
||||
return obj[name]()
|
||||
} catch { return undefined }
|
||||
}
|
||||
function snapshotOf(obj) {
|
||||
if (!obj) return undefined
|
||||
if (isFn(obj.getSnapshot)) {
|
||||
try { return obj.getSnapshot() } catch { return undefined }
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
export function apply(ctx) {
|
||||
if (typeof document !== 'undefined') installStyles(document, 'workbench', WORKBENCH_CSS)
|
||||
|
||||
const get = (name) => { try { return ctx.get(name) } catch { return undefined } }
|
||||
|
||||
// ---------- 当前项目 / 工作区(特性探测,拿不到就提示用户先选项目) ----------
|
||||
function workspaceItems() {
|
||||
const fromWorkspaces = snapshotOf(get('workspaces')?.list)?.items
|
||||
if (Array.isArray(fromWorkspaces)) return fromWorkspaces
|
||||
const fromUi = snapshotOf(get('uiWorkspace')?.workspaces)?.items
|
||||
if (Array.isArray(fromUi)) return fromUi
|
||||
return []
|
||||
}
|
||||
|
||||
function normalizeWorkspace(item) {
|
||||
if (!item || typeof item !== 'object') return null
|
||||
const workspaceId = item.workspaceId ?? item.id ?? null
|
||||
if (typeof workspaceId !== 'string' || !workspaceId) return null
|
||||
return {
|
||||
workspaceId,
|
||||
name: typeof item.name === 'string' ? item.name : (typeof item.title === 'string' ? item.title : undefined),
|
||||
path: typeof item.path === 'string' ? item.path : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
function currentSessionId() {
|
||||
const snap = snapshotOf(get('sessions')?.list) ?? snapshotOf(get('sessions'))
|
||||
if (!snap || typeof snap !== 'object') return null
|
||||
for (const key of ['activeId', 'currentId', 'selectedId']) {
|
||||
if (typeof snap[key] === 'string' && snap[key]) return snap[key]
|
||||
}
|
||||
if (snap.byId && typeof snap.byId === 'object') {
|
||||
const main = Object.values(snap.byId).find(session => (session?.retainedBy?.mainView ?? 0) > 0)
|
||||
if (main && typeof main.id === 'string') return main.id
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function currentWorkspaceId() {
|
||||
const candidates = []
|
||||
for (const holder of [get('workspaces'), get('uiWorkspace')]) {
|
||||
if (!holder) continue
|
||||
for (const key of ['currentWorkspaceId', 'currentId', 'activeId']) {
|
||||
if (isFn(holder[key])) candidates.push(safeCall(holder, key))
|
||||
else if (typeof holder[key] === 'string') candidates.push(holder[key])
|
||||
}
|
||||
for (const key of ['current', 'active', 'selected', 'currentWorkspace']) {
|
||||
const value = holder[key]
|
||||
const snap = snapshotOf(value)
|
||||
if (snap && typeof snap === 'object') candidates.push(snap.workspaceId ?? snap.id)
|
||||
else if (typeof value === 'string') candidates.push(value)
|
||||
}
|
||||
}
|
||||
const sessionId = currentSessionId()
|
||||
if (sessionId) {
|
||||
const owner = workspaceItems().find(item => Array.isArray(item.sessionIds) && item.sessionIds.includes(sessionId))
|
||||
if (owner) candidates.push(owner.workspaceId ?? owner.id)
|
||||
}
|
||||
return candidates.find(id => typeof id === 'string' && id) ?? null
|
||||
}
|
||||
|
||||
function currentWorkspace() {
|
||||
const items = workspaceItems().map(normalizeWorkspace).filter(Boolean)
|
||||
const id = currentWorkspaceId()
|
||||
if (id) {
|
||||
const hit = items.find(item => item.workspaceId === id)
|
||||
return hit || { workspaceId: id, name: undefined, path: undefined }
|
||||
}
|
||||
if (items.length === 1) return items[0]
|
||||
return null
|
||||
}
|
||||
|
||||
function seatRecordOf(view, id) {
|
||||
const seats = view && view.project ? view.project.seats : null
|
||||
if (Array.isArray(seats)) return seats.find(seat => seat && seat.id === id) || null
|
||||
if (seats && typeof seats === 'object') return seats[id] || null
|
||||
return null
|
||||
}
|
||||
|
||||
// ---------- 会话导航(特性探测;拿不到只发意图并 console.warn) ----------
|
||||
function navigateToSession(sessionId) {
|
||||
if (!sessionId) return false
|
||||
const attempts = []
|
||||
const ui = get('uiWorkspace')
|
||||
if (ui) {
|
||||
if (isFn(ui.openSession)) attempts.push(() => ui.openSession(sessionId))
|
||||
if (isFn(ui.open)) attempts.push(() => ui.open(sessionId))
|
||||
}
|
||||
const sessions = get('sessions')
|
||||
if (sessions) {
|
||||
if (isFn(sessions.open)) attempts.push(() => sessions.open(sessionId))
|
||||
if (isFn(sessions.openSession)) attempts.push(() => sessions.openSession(sessionId))
|
||||
if (isFn(sessions.select)) attempts.push(() => sessions.select(sessionId))
|
||||
}
|
||||
for (const name of ['navigation', 'navigator', 'router']) {
|
||||
const svc = get(name)
|
||||
if (!svc) continue
|
||||
if (isFn(svc.openSession)) attempts.push(() => svc.openSession(sessionId))
|
||||
if (isFn(svc.navigate)) attempts.push(() => svc.navigate({ sessionId }))
|
||||
if (isFn(svc.open)) attempts.push(() => svc.open(sessionId))
|
||||
}
|
||||
for (const run of attempts) {
|
||||
try {
|
||||
const result = run()
|
||||
if (result && isFn(result.then)) result.catch(() => {})
|
||||
return true
|
||||
} catch { /* 换下一个候选 */ }
|
||||
}
|
||||
console.warn('[sansheng] 未找到可用的会话导航接口,仅发出 navigate 意图:', sessionId)
|
||||
try {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.dispatchEvent(new CustomEvent('sansheng:navigate', { detail: { sessionId } }))
|
||||
}
|
||||
} catch { /* 忽略 */ }
|
||||
return false
|
||||
}
|
||||
|
||||
// ---------- 右侧标签页(可能不存在;失败回退浮动面板) ----------
|
||||
let rightTabReady = false
|
||||
function closeRightTab() {
|
||||
const right = get('sidebarRight')
|
||||
try { if (right && isFn(right.closeTab)) right.closeTab(TAB_ID) } catch { /* 忽略 */ }
|
||||
}
|
||||
function ensureRightTab() {
|
||||
if (rightTabReady) return true
|
||||
const tabs = get('sidebarRightTabs')
|
||||
if (!tabs) return false
|
||||
try {
|
||||
if (isFn(tabs.get) && tabs.get(TAB_ID)) { rightTabReady = true; return true }
|
||||
if (isFn(tabs.register)) {
|
||||
tabs.register(TAB_ID, { title: '三省六部', render: () => h(SanshengWorkbench, { onClose: closeRightTab }) })
|
||||
rightTabReady = true
|
||||
return true
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[sansheng] 无法注册右侧标签页,回退为浮动面板:', error && error.message ? error.message : error)
|
||||
}
|
||||
return false
|
||||
}
|
||||
function tryOpenRightTab() {
|
||||
const right = get('sidebarRight')
|
||||
if (!right || !isFn(right.openTab)) return false
|
||||
if (!ensureRightTab()) return false
|
||||
try { right.openTab(TAB_ID); return true } catch (error) {
|
||||
console.warn('[sansheng] 打开右侧标签失败,回退为浮动面板:', error && error.message ? error.message : error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 工作台组件 ----------
|
||||
function SanshengWorkbench(props) {
|
||||
const onClose = props && props.onClose ? props.onClose : null
|
||||
const [phase, setPhase] = useState('loading')
|
||||
const [error, setError] = useState(null)
|
||||
const [notice, setNotice] = useState(null)
|
||||
const [view, setView] = useState(null)
|
||||
const [models, setModels] = useState(null)
|
||||
const [selectedSeatId, setSelectedSeatId] = useState(SEAT_IDS[0])
|
||||
const [draft, setDraft] = useState({})
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [configOpen, setConfigOpen] = useState(false)
|
||||
const alive = useRef(true)
|
||||
|
||||
useEffect(() => () => { alive.current = false }, [])
|
||||
|
||||
const loadProject = useCallback(async () => {
|
||||
setPhase('loading'); setError(null); setNotice(null)
|
||||
const workspace = currentWorkspace()
|
||||
if (!workspace) { setPhase('no-workspace'); return }
|
||||
try {
|
||||
const projectView = await request('open', {
|
||||
workspaceId: workspace.workspaceId,
|
||||
name: workspace.name,
|
||||
path: workspace.path,
|
||||
})
|
||||
let modelCatalog = null
|
||||
try { modelCatalog = await request('models') } catch (modelError) {
|
||||
console.warn('[sansheng] 模型目录加载失败:', modelError && modelError.message ? modelError.message : modelError)
|
||||
}
|
||||
if (!alive.current) return
|
||||
setView(projectView)
|
||||
setModels(modelCatalog)
|
||||
setPhase('ready')
|
||||
} catch (loadError) {
|
||||
if (!alive.current) return
|
||||
setError(loadError && loadError.message ? loadError.message : '加载失败')
|
||||
setPhase('error')
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => { void loadProject() }, [loadProject])
|
||||
|
||||
const wb = buildWorkbenchView(view, { selectedSeatId, models, draft })
|
||||
const seatById = useMemo(() => {
|
||||
const map = {}
|
||||
for (const seat of wb.seats) map[seat.id] = seat
|
||||
return map
|
||||
}, [wb.seats])
|
||||
|
||||
function pickSeat(id) {
|
||||
if (!id) return
|
||||
if (id !== selectedSeatId) {
|
||||
setSelectedSeatId(id)
|
||||
setConfigOpen(false)
|
||||
}
|
||||
const seat = seatById[id]
|
||||
if (wb.ready && seat && seat.status === 'bound') {
|
||||
const rec = seatRecordOf(view, id)
|
||||
if (rec && rec.sessionId) {
|
||||
navigateToSession(rec.sessionId)
|
||||
setNotice('已切换到' + seat.name + '会话')
|
||||
return
|
||||
}
|
||||
}
|
||||
if (wb.ready && seat && seat.status !== 'bound') setNotice('该席尚未绑定会话,先启用或重试启用')
|
||||
}
|
||||
|
||||
function setModelValue(value) {
|
||||
setDraft(prev => updateDraft(prev, selectedSeatId, { modelValue: value }))
|
||||
}
|
||||
function setInstructions(value) {
|
||||
setDraft(prev => updateDraft(prev, selectedSeatId, { instructions: value }))
|
||||
}
|
||||
|
||||
async function enableSeats() {
|
||||
const projectId = view && view.project ? view.project.id : null
|
||||
if (!projectId) return
|
||||
setBusy(true); setError(null); setNotice('正在启用十席…')
|
||||
try {
|
||||
const next = await request('enable', { projectId })
|
||||
if (!alive.current) return
|
||||
setView(next)
|
||||
setNotice('十席已启用(建立独立会话,不自动运行模型)')
|
||||
} catch (enableError) {
|
||||
if (alive.current) setError(enableError && enableError.message ? enableError.message : '启用失败')
|
||||
} finally {
|
||||
if (alive.current) setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function saveConfig() {
|
||||
const projectId = view && view.project ? view.project.id : null
|
||||
if (!projectId) return
|
||||
const seatId = wb.selected.id
|
||||
const value = wb.selected.modelValue
|
||||
if (!value) { setNotice('请先为当前角色选择模型'); return }
|
||||
const option = findModelOption(wb.selected.modelOptions, value)
|
||||
const model = option
|
||||
? (option.reasoningEffort
|
||||
? { provider: option.provider, model: option.model, reasoningEffort: option.reasoningEffort }
|
||||
: { provider: option.provider, model: option.model })
|
||||
: null
|
||||
setBusy(true); setError(null); setNotice('保存中…')
|
||||
try {
|
||||
await request('configure', { projectId, seatId, model, instructions: wb.selected.instructions })
|
||||
const next = await request('project', { projectId })
|
||||
if (!alive.current) return
|
||||
setView(next)
|
||||
setDraft(prev => clearDraft(prev, seatId))
|
||||
setNotice('已保存')
|
||||
} catch (saveError) {
|
||||
if (alive.current) setError(saveError && saveError.message ? saveError.message : '保存失败')
|
||||
} finally {
|
||||
if (alive.current) setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const seatCard = (seat) => h('button', {
|
||||
key: seat.id, type: 'button', className: 'ssw-seat',
|
||||
'aria-pressed': seat.selected ? 'true' : 'false',
|
||||
title: seat.name + ' · ' + seat.duty + '(' + seat.statusLabel + ')',
|
||||
onClick: () => pickSeat(seat.id),
|
||||
},
|
||||
h('span', { className: 'ssw-role-top' },
|
||||
h('span', { className: 'ssw-role-name' }, seat.name),
|
||||
h('span', { className: 'ssw-dot', 'data-status': seat.status, 'aria-hidden': 'true' }),
|
||||
),
|
||||
h('span', { className: 'ssw-role-duty' }, seat.duty),
|
||||
)
|
||||
|
||||
const pickList = (ids) => ids.map(id => seatById[id]).filter(Boolean)
|
||||
const tree = h('section', { className: 'ssw-tree', 'aria-label': '切换角色' },
|
||||
h('div', { className: 'ssw-lead' }, pickList(wb.groups.lead).map(seatCard)),
|
||||
h('div', { className: 'ssw-trio' }, pickList(wb.groups.sansheng).map(seatCard)),
|
||||
h('div', { className: 'ssw-ministries' },
|
||||
h('span', { className: 'ssw-group-label' }, '六部 · 尚书统筹'),
|
||||
h('div', { className: 'ssw-six' }, pickList(wb.groups.liubu).map(seatCard)),
|
||||
),
|
||||
)
|
||||
|
||||
const head = h('header', { className: 'ssw-head' },
|
||||
h(TreeIcon),
|
||||
h('strong', { className: 'ssw-head-title' }, '工作台'),
|
||||
onClose
|
||||
? h('button', { type: 'button', className: 'ssw-icon-btn', onClick: onClose, 'aria-label': '收起工作台' }, h(CloseIcon))
|
||||
: null,
|
||||
)
|
||||
|
||||
const projectInfo = h('div', { className: 'ssw-project' },
|
||||
h('div', { className: 'ssw-project-line' },
|
||||
h('span', { className: 'ssw-eyebrow' }, h(FolderIcon), '当前项目'),
|
||||
h('span', { className: 'ssw-count' }, wb.project.seatCount + ' 个角色 · ' + wb.project.sessionCount + ' 个会话'),
|
||||
),
|
||||
h('div', { className: 'ssw-project-title' }, wb.projectTitle || '未命名项目'),
|
||||
)
|
||||
|
||||
const enableBlock = !wb.ready
|
||||
? h('div', { className: 'ssw-enable' },
|
||||
h('p', { className: 'ssw-enable-note' }, '这个项目还没有启用十席。启用会建立十个独立会话,但不会自动运行模型。'),
|
||||
h('button', {
|
||||
type: 'button', className: 'ssw-primary', disabled: busy, onClick: enableSeats,
|
||||
}, busy ? '正在启用…' : '启用此项目的十席'),
|
||||
)
|
||||
: null
|
||||
|
||||
const currentCard = h('section', { className: 'ssw-current' },
|
||||
h('div', { className: 'ssw-current-top' },
|
||||
h('strong', { className: 'ssw-current-name' }, wb.selected.name),
|
||||
h('span', { className: 'ssw-current-label' }, '角色职责 · ' + wb.selected.statusLabel),
|
||||
),
|
||||
h('p', { className: 'ssw-current-text' }, wb.selected.responsibility),
|
||||
)
|
||||
|
||||
const optionEls = wb.selected.modelOptions.map(option => h('option', { key: option.value, value: option.value }, option.label))
|
||||
if (wb.selected.modelValue && !wb.selected.modelOptions.some(option => option.value === wb.selected.modelValue)) {
|
||||
optionEls.push(h('option', { key: '__current__', value: wb.selected.modelValue }, wb.selected.modelLabel))
|
||||
}
|
||||
const config = h('section', { className: 'ssw-config' },
|
||||
h('button', {
|
||||
type: 'button', className: 'ssw-config-toggle', 'aria-expanded': configOpen ? 'true' : 'false',
|
||||
onClick: () => setConfigOpen(value => !value),
|
||||
},
|
||||
h(GearIcon),
|
||||
h('span', null, '配置' + wb.selected.name + (wb.selected.dirty ? ' · 未保存' : '')),
|
||||
h(ChevronIcon),
|
||||
),
|
||||
configOpen
|
||||
? h('div', { className: 'ssw-config-body' },
|
||||
h('label', { className: 'ssw-label' }, '会话模型'),
|
||||
h('select', {
|
||||
className: 'ssw-field', value: wb.selected.modelValue, disabled: busy,
|
||||
onChange: event => setModelValue(event.target.value),
|
||||
},
|
||||
h('option', { value: '', disabled: true }, UNCHOSEN_MODEL_LABEL),
|
||||
...optionEls,
|
||||
),
|
||||
h('label', { className: 'ssw-label' }, '角色补充说明'),
|
||||
h('textarea', {
|
||||
className: 'ssw-field ssw-textarea', rows: 4, value: wb.selected.instructions, disabled: busy,
|
||||
placeholder: '补充该角色在当前项目中的工作要求',
|
||||
onChange: event => setInstructions(event.target.value),
|
||||
}),
|
||||
h('p', { className: 'ssw-scope-note' }, '每个角色是独立会话;模型与说明只影响当前项目当前角色,不改变宿主默认模型。'),
|
||||
h('div', { className: 'ssw-save-row' },
|
||||
h('button', { type: 'button', className: 'ssw-primary', disabled: busy, onClick: saveConfig }, busy ? '保存中…' : '保存配置'),
|
||||
wb.selected.dirty ? h('span', { className: 'ssw-save-status' }, '有未保存修改') : null,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
)
|
||||
|
||||
const statusEl = error
|
||||
? h('p', { className: 'ssw-error', role: 'alert' }, error)
|
||||
: (notice ? h('p', { className: 'ssw-notice', role: 'status' }, notice) : null)
|
||||
|
||||
let body
|
||||
if (phase === 'loading') body = h('div', { className: 'ssw-loading' }, '正在加载工作台…')
|
||||
else if (phase === 'no-workspace') body = h('div', { className: 'ssw-empty' },
|
||||
h('p', null, '先从左侧选择一个项目'),
|
||||
h('button', { type: 'button', className: 'ssw-primary', onClick: loadProject }, '重试'),
|
||||
)
|
||||
else if (phase === 'error' && !view) body = h('div', { className: 'ssw-empty' },
|
||||
h('p', { className: 'ssw-error' }, error || '加载失败'),
|
||||
h('button', { type: 'button', className: 'ssw-primary', onClick: loadProject }, '重试'),
|
||||
)
|
||||
else body = h(Fragment, null, projectInfo, enableBlock, tree, currentCard, config, statusEl)
|
||||
|
||||
return h('div', { className: 'ssw-root ssw-scope' }, head, body)
|
||||
}
|
||||
|
||||
// ---------- 左侧入口 ----------
|
||||
function SanshengEntry() {
|
||||
const [floating, setFloating] = useState(false)
|
||||
const onClick = () => {
|
||||
if (tryOpenRightTab()) { setFloating(false); return }
|
||||
setFloating(value => !value)
|
||||
}
|
||||
let panel = null
|
||||
if (floating) {
|
||||
const card = h('div', { className: 'ssw-float', role: 'dialog', 'aria-label': '三省六部工作台' },
|
||||
h(SanshengWorkbench, { onClose: () => setFloating(false) }))
|
||||
const canPortal = typeof document !== 'undefined' && document.body && isFn(createPortal)
|
||||
panel = canPortal ? createPortal(card, document.body) : card
|
||||
}
|
||||
return h(Fragment, null,
|
||||
h('button', {
|
||||
type: 'button', className: 'ssw-entry', title: '三省六部',
|
||||
'aria-expanded': floating ? 'true' : 'false', onClick,
|
||||
},
|
||||
h(TreeIcon),
|
||||
h('span', { className: 'ssw-entry-label' }, '三省六部'),
|
||||
),
|
||||
panel,
|
||||
)
|
||||
}
|
||||
|
||||
// 追加型入口:只在 sidebar.footer.action 里加一个 action,不替换工作区/项目树。
|
||||
try {
|
||||
if (ctx.slots && isFn(ctx.slots.inject) && isFn(ctx.slots.register)) {
|
||||
ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({
|
||||
name: 'sidebar.footer.action',
|
||||
id: 'sansheng-entry',
|
||||
order: 40,
|
||||
}, SanshengEntry))
|
||||
} else {
|
||||
console.warn('[sansheng] 宿主未提供 slots.inject / slots.register,无法注册侧栏入口')
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[sansheng] 注册侧栏入口失败:', error && error.message ? error.message : error)
|
||||
}
|
||||
|
||||
// dsh-go 原生面板:浏览器(无 dshGo 服务)或桥未就绪时,install 内部安静退出。
|
||||
try {
|
||||
installNativePanel(ctx)
|
||||
} catch (error) {
|
||||
console.warn('[sansheng] 原生面板注册失败:', error && error.message ? error.message : error)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,81 @@
|
|||
// 三省六部工作台样式:白蓝主题,自带深色适配。
|
||||
// 所有选择器以 .ssw- 前缀隔离,避免污染宿主样式;变量参考 preview/index.html。
|
||||
// 不依赖任何构建工具,作为普通字符串导出,由入口注入 <style>。
|
||||
|
||||
export const CSS = `
|
||||
.ssw-scope{--ssw-bg:#ffffff;--ssw-side:#f8f9fa;--ssw-rail:#f7f9fc;--ssw-card:#ffffff;--ssw-line:#e3e8ef;--ssw-strong:#c7d8f5;--ssw-ink:#0f172a;--ssw-muted:#667085;--ssw-faint:#98a2b3;--ssw-blue:#3b82f6;--ssw-wash:#eff6ff;--ssw-wire:#c9d6ea;--ssw-danger:#dc2626;--ssw-ok:#16a34a;box-sizing:border-box;color:var(--ssw-ink);font-family:Inter,"Segoe UI","Microsoft YaHei",sans-serif;font-size:13px;line-height:1.5}
|
||||
.ssw-scope *,.ssw-scope *::before,.ssw-scope *::after{box-sizing:border-box}
|
||||
.ssw-scope button{font:inherit;color:inherit;background:transparent;border:0;cursor:pointer}
|
||||
.ssw-scope button:disabled{cursor:default;opacity:.55}
|
||||
.ssw-scope :focus-visible{outline:2px solid var(--ssw-blue);outline-offset:2px}
|
||||
body[data-ds-dark-theme] .ssw-scope,html[data-theme=dark] .ssw-scope,.ssw-scope[data-ssw-theme=dark]{--ssw-bg:#14171c;--ssw-side:#171b21;--ssw-rail:#161a20;--ssw-card:#1e232b;--ssw-line:#2c333d;--ssw-strong:#3b4a63;--ssw-ink:#e6ebf2;--ssw-muted:#a9b4c2;--ssw-faint:#7b8797;--ssw-blue:#6ea8ff;--ssw-wash:#1d2b40;--ssw-wire:#3a4350;--ssw-danger:#f87171;--ssw-ok:#4ade80}
|
||||
.ssw-float{position:fixed;right:14px;bottom:70px;z-index:2147483000;width:min(374px,calc(100vw - 28px));max-height:calc(100vh - 96px);display:flex;flex-direction:column;background:#ffffff;border:1px solid #e3e8ef;border-radius:12px;box-shadow:0 18px 50px -12px rgba(16,24,40,.28),0 4px 12px -2px rgba(16,24,40,.12);overflow:hidden}
|
||||
body[data-ds-dark-theme] .ssw-float,html[data-theme=dark] .ssw-float{background:#161a20;border-color:#2c333d}
|
||||
.ssw-root{display:flex;flex-direction:column;min-height:0;height:100%;overflow:auto;background:var(--ssw-rail);color:var(--ssw-ink)}
|
||||
.ssw-head{flex:none;height:52px;display:flex;align-items:center;gap:8px;padding:0 16px;border-bottom:1px solid var(--ssw-line);background:var(--ssw-card)}
|
||||
.ssw-head svg{width:18px;height:18px;color:var(--ssw-muted)}
|
||||
.ssw-head-title{font-size:13px;font-weight:600}
|
||||
.ssw-icon-btn{margin-left:auto;display:inline-flex;align-items:center;justify-content:center;width:30px;height:30px;border-radius:6px;color:var(--ssw-muted)}
|
||||
.ssw-icon-btn:hover{background:var(--ssw-wash);color:var(--ssw-blue)}
|
||||
.ssw-project{padding:18px 16px 0}
|
||||
.ssw-project-line{display:flex;align-items:center;justify-content:space-between;margin-bottom:5px}
|
||||
.ssw-eyebrow{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--ssw-muted)}
|
||||
.ssw-eyebrow svg{width:14px;height:14px}
|
||||
.ssw-count{font-size:10px;color:var(--ssw-faint)}
|
||||
.ssw-project-title{font-size:17px;font-weight:600;letter-spacing:.3px;margin:0 0 14px}
|
||||
.ssw-enable{margin:0 16px 4px;padding:12px;border:1px solid var(--ssw-strong);background:var(--ssw-wash);border-radius:10px}
|
||||
.ssw-enable-note{margin:0 0 10px;font-size:12px;color:var(--ssw-muted);line-height:1.7}
|
||||
.ssw-primary{background:var(--ssw-blue);color:#ffffff;border-radius:7px;padding:8px 13px;font-size:12px;font-weight:500}
|
||||
.ssw-primary:hover{filter:brightness(1.05)}
|
||||
.ssw-tree{padding:14px 16px 4px;position:relative}
|
||||
.ssw-lead{width:150px;margin:0 auto;position:relative}
|
||||
.ssw-lead::after{content:"";position:absolute;left:50%;top:100%;height:20px;border-left:1px solid var(--ssw-wire)}
|
||||
.ssw-trio{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:9px;margin-top:34px;position:relative}
|
||||
.ssw-trio::before{content:"";position:absolute;left:16.66%;right:16.66%;top:-15px;border-top:1px solid var(--ssw-wire)}
|
||||
.ssw-trio .ssw-seat::before{content:"";position:absolute;left:50%;bottom:100%;height:15px;border-left:1px solid var(--ssw-wire)}
|
||||
.ssw-seat{position:relative;width:100%;display:flex;flex-direction:column;gap:6px;padding:10px 9px 8px;border:1px solid var(--ssw-line);border-radius:10px;background:var(--ssw-card);text-align:left;min-height:70px;box-shadow:0 1px 2px rgba(16,24,40,.04);transition:border-color .15s,box-shadow .15s,transform .15s}
|
||||
.ssw-seat:hover{border-color:var(--ssw-strong);transform:translateY(-1px);box-shadow:0 3px 8px rgba(16,24,40,.06)}
|
||||
.ssw-seat[aria-pressed=true]{border-color:var(--ssw-blue);background:var(--ssw-wash);box-shadow:0 0 0 2px rgba(59,130,246,.12)}
|
||||
.ssw-lead .ssw-seat{border-color:var(--ssw-strong)}
|
||||
.ssw-role-top{display:flex;align-items:center;justify-content:space-between;gap:6px}
|
||||
.ssw-role-name{font-size:14px;font-weight:600;letter-spacing:2px}
|
||||
.ssw-role-duty{font-size:10px;color:var(--ssw-muted);line-height:1.5}
|
||||
.ssw-dot{flex:none;width:6px;height:6px;border-radius:50%;border:1px solid var(--ssw-faint);background:transparent}
|
||||
.ssw-dot[data-status=bound]{background:var(--ssw-ok);border-color:var(--ssw-ok)}
|
||||
.ssw-dot[data-status=failed],.ssw-dot[data-status=missing]{background:var(--ssw-danger);border-color:var(--ssw-danger)}
|
||||
.ssw-dot[data-status=creating]{background:var(--ssw-blue);border-color:var(--ssw-blue)}
|
||||
.ssw-ministries{position:relative;border:1px dashed var(--ssw-wire);border-radius:12px;margin-top:26px;padding:14px 8px 9px}
|
||||
.ssw-ministries::before{content:"";position:absolute;bottom:100%;height:26px;border-left:1px solid var(--ssw-wire);left:50%}
|
||||
.ssw-group-label{position:absolute;top:-8px;left:10px;padding:0 5px;background:var(--ssw-rail);font-size:10px;color:var(--ssw-faint)}
|
||||
.ssw-six{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}
|
||||
.ssw-six .ssw-seat{min-height:66px;padding:9px 8px}
|
||||
.ssw-current{margin:16px 16px 0;padding:13px;border:1px solid var(--ssw-line);border-radius:11px;background:var(--ssw-card)}
|
||||
.ssw-current-top{display:flex;align-items:center;justify-content:space-between;margin-bottom:9px}
|
||||
.ssw-current-name{font-size:13px;font-weight:600}
|
||||
.ssw-current-label{font-size:10px;color:var(--ssw-faint)}
|
||||
.ssw-current-text{margin:0;font-size:12px;line-height:1.8;color:var(--ssw-muted)}
|
||||
.ssw-config{margin:10px 16px 0;border:1px solid var(--ssw-line);border-radius:10px;background:var(--ssw-card);overflow:hidden}
|
||||
.ssw-config-toggle{display:flex;align-items:center;gap:8px;width:100%;padding:12px 13px;font-size:12px;color:var(--ssw-ink)}
|
||||
.ssw-config-toggle svg{width:15px;height:15px;color:var(--ssw-muted)}
|
||||
.ssw-chevron{margin-left:auto;transition:transform .2s}
|
||||
.ssw-config-toggle[aria-expanded=true] .ssw-chevron{transform:rotate(180deg)}
|
||||
.ssw-config-body{padding:0 13px 14px}
|
||||
.ssw-label{display:block;font-size:11px;color:var(--ssw-muted);margin:12px 0 6px}
|
||||
.ssw-field{width:100%;border:1px solid var(--ssw-line);background:var(--ssw-bg);color:var(--ssw-ink);border-radius:6px;padding:8px;font-size:12px;line-height:1.5}
|
||||
.ssw-textarea{resize:vertical;min-height:84px;font-family:inherit}
|
||||
.ssw-scope-note{margin:10px 0;font-size:10px;line-height:1.6;color:var(--ssw-faint)}
|
||||
.ssw-save-row{display:flex;align-items:center;gap:10px}
|
||||
.ssw-save-status{font-size:10px;color:var(--ssw-muted)}
|
||||
.ssw-notice{margin:12px 16px 16px;font-size:11px;color:var(--ssw-muted)}
|
||||
.ssw-error{margin:12px 16px 16px;font-size:11px;color:var(--ssw-danger)}
|
||||
.ssw-loading,.ssw-empty{padding:36px 20px;text-align:center;font-size:12px;color:var(--ssw-muted)}
|
||||
.ssw-empty .ssw-primary{margin-top:12px}
|
||||
.ssw-entry{display:flex;align-items:center;gap:9px;width:100%;padding:0 10px;height:35px;border-radius:7px;font-size:13px;color:inherit;text-align:left}
|
||||
.ssw-entry:hover{background:#eef4ff}
|
||||
.ssw-entry[aria-expanded=true]{color:#2563eb;background:#eaf1fe;font-weight:600}
|
||||
.ssw-entry svg{width:16px;height:16px;flex:none}
|
||||
.ssw-entry-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
body[data-ds-dark-theme] .ssw-entry:hover{background:#1d2b40}
|
||||
body[data-ds-dark-theme] .ssw-entry[aria-expanded=true]{color:#91bafa;background:#1d2b40}
|
||||
@media (prefers-reduced-motion:reduce){.ssw-scope *{transition:none!important}}
|
||||
`
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
// 三省六部 Web 传输层:POST api/sansheng,契约见 CONTRACT.md。
|
||||
// 请求体 { endpoint, payload };成功 { ok:true, value };失败 { ok:false, error:{code,message} }。
|
||||
|
||||
const ROUTE = 'api/sansheng'
|
||||
|
||||
export class SanshengRequestError extends Error {
|
||||
constructor(message, code) {
|
||||
super(message)
|
||||
this.name = 'SanshengRequestError'
|
||||
this.code = code || 'sansheng/error'
|
||||
}
|
||||
}
|
||||
|
||||
export async function request(endpoint, payload, signal) {
|
||||
let response
|
||||
try {
|
||||
response = await fetch(ROUTE, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ endpoint, payload: payload ?? null }),
|
||||
signal,
|
||||
})
|
||||
} catch (error) {
|
||||
if (error && error.name === 'AbortError') throw error
|
||||
const detail = error && error.message ? error.message : String(error)
|
||||
throw new SanshengRequestError('无法连接 DSH,请确认它仍在运行(' + detail + ')', 'NETWORK')
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new SanshengRequestError('HTTP ' + response.status, 'HTTP_' + response.status)
|
||||
}
|
||||
|
||||
let result
|
||||
try {
|
||||
result = await response.json()
|
||||
} catch (error) {
|
||||
throw new SanshengRequestError('响应不是合法 JSON', 'sansheng/bad-response')
|
||||
}
|
||||
|
||||
if (!result || result.ok !== true) {
|
||||
const code = result && result.error && result.error.code ? result.error.code : 'sansheng/error'
|
||||
const message = result && result.error && result.error.message ? result.error.message : '请求失败'
|
||||
throw new SanshengRequestError(message, code)
|
||||
}
|
||||
return result.value
|
||||
}
|
||||
|
||||
export default request
|
||||
|
|
@ -0,0 +1,231 @@
|
|||
// 纯视图模型:不 import React、不触碰 DOM,可被 node 直接 import 测试。
|
||||
// 依据 CONTRACT.md「Web 工作台」一节生成 buildWorkbenchView(view, ui) 的返回结构;
|
||||
// 十席名称 / 职责全文一律取自共享的 src/shared/roles.js,保证三端一致。
|
||||
|
||||
import { SEATS, SEAT_IDS, SEAT_GROUPS } from '../shared/roles.js'
|
||||
|
||||
// 未选择模型时的固定文案,两端 UI 必须一致。
|
||||
export const UNCHOSEN_MODEL_LABEL = '请选择模型'
|
||||
|
||||
export const SEAT_STATUS_LABELS = Object.freeze({
|
||||
pending: '待启用',
|
||||
creating: '创建中',
|
||||
bound: '已绑定',
|
||||
failed: '创建失败',
|
||||
missing: '会话缺失',
|
||||
})
|
||||
|
||||
const DEFAULT_SEAT_STATUS = 'pending'
|
||||
|
||||
export function seatStatusLabel(status) {
|
||||
if (typeof status !== 'string') return '未知状态'
|
||||
return SEAT_STATUS_LABELS[status] ?? '未知状态'
|
||||
}
|
||||
|
||||
export function projectStatusLabel(status) {
|
||||
switch (status) {
|
||||
case 'pending': return '待启用'
|
||||
case 'provisioning': return '启用中'
|
||||
case 'ready': return '已启用'
|
||||
case 'error': return '启用失败'
|
||||
default: return '未知状态'
|
||||
}
|
||||
}
|
||||
|
||||
// 把 models 端点返回的目录摊平成下拉选项。value 形如 provider::model[::effort],
|
||||
// 永远不等于 'inherit'(界面不提供“跟随宿主模型”)。
|
||||
export function collectModelOptions(models) {
|
||||
const out = []
|
||||
const seen = new Set()
|
||||
const providers = Array.isArray(models?.providers) ? models.providers : []
|
||||
for (const entry of providers) {
|
||||
const provider = typeof entry?.provider === 'string' ? entry.provider : ''
|
||||
if (!provider) continue
|
||||
const list = Array.isArray(entry?.models) ? entry.models : []
|
||||
for (const item of list) {
|
||||
const model = typeof item?.model === 'string' ? item.model : ''
|
||||
if (!model) continue
|
||||
const efforts = Array.isArray(item?.reasoningEffort)
|
||||
? item.reasoningEffort.filter(e => typeof e === 'string' && e.trim() !== '')
|
||||
: []
|
||||
if (efforts.length > 0) {
|
||||
for (const effort of efforts) {
|
||||
const value = provider + '::' + model + '::' + effort
|
||||
if (value === 'inherit' || seen.has(value)) continue
|
||||
seen.add(value)
|
||||
out.push({ value, label: model + ' · ' + effort, provider, model, reasoningEffort: effort })
|
||||
}
|
||||
} else {
|
||||
const value = provider + '::' + model
|
||||
if (value === 'inherit' || seen.has(value)) continue
|
||||
seen.add(value)
|
||||
out.push({ value, label: model, provider, model })
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function findModelOption(options, modelValue) {
|
||||
if (!Array.isArray(options)) return undefined
|
||||
return options.find(option => option.value === modelValue)
|
||||
}
|
||||
|
||||
// 把某个席已保存的 model 对象映射成 { modelValue, modelLabel }。
|
||||
export function describeModel(model, options) {
|
||||
if (!model || typeof model !== 'object' || typeof model.provider !== 'string' || typeof model.model !== 'string') {
|
||||
return { modelValue: '', modelLabel: UNCHOSEN_MODEL_LABEL }
|
||||
}
|
||||
const effort = typeof model.reasoningEffort === 'string' && model.reasoningEffort ? model.reasoningEffort : undefined
|
||||
const match = (Array.isArray(options) ? options : []).find(option =>
|
||||
option.provider === model.provider
|
||||
&& option.model === model.model
|
||||
&& (option.reasoningEffort ?? undefined) === effort)
|
||||
if (match) return { modelValue: match.value, modelLabel: match.label }
|
||||
const modelLabel = effort ? model.model + ' · ' + effort : model.model
|
||||
const modelValue = effort
|
||||
? model.provider + '::' + model.model + '::' + effort
|
||||
: model.provider + '::' + model.model
|
||||
return { modelValue, modelLabel }
|
||||
}
|
||||
|
||||
// 兼容两种入参:CONTRACT 的项目视图用数组;共享 schema 里可能以 seatId 为键。
|
||||
function normalizeSeats(seats) {
|
||||
const map = {}
|
||||
if (Array.isArray(seats)) {
|
||||
for (const seat of seats) {
|
||||
if (seat && typeof seat === 'object' && typeof seat.id === 'string') map[seat.id] = seat
|
||||
}
|
||||
} else if (seats && typeof seats === 'object') {
|
||||
for (const [id, seat] of Object.entries(seats)) {
|
||||
if (seat && typeof seat === 'object') map[id] = { id, ...seat }
|
||||
}
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
function cloneGroups() {
|
||||
const out = {}
|
||||
for (const key of Object.keys(SEAT_GROUPS)) out[key] = Array.from(SEAT_GROUPS[key])
|
||||
return out
|
||||
}
|
||||
|
||||
function pickSelectedId(requested) {
|
||||
if (typeof requested === 'string' && SEAT_IDS.includes(requested)) return requested
|
||||
return SEAT_IDS[0]
|
||||
}
|
||||
|
||||
function hasOwn(obj, key) {
|
||||
return obj !== null && obj !== undefined && Object.prototype.hasOwnProperty.call(obj, key)
|
||||
}
|
||||
|
||||
export function draftOf(draft, seatId) {
|
||||
if (!draft || typeof draft !== 'object') return {}
|
||||
const entry = draft[seatId]
|
||||
return entry && typeof entry === 'object' ? entry : {}
|
||||
}
|
||||
|
||||
// 返回新的草稿映射(不可变):保留其它席的草稿,便于“切换角色不丢草稿”。
|
||||
export function updateDraft(draft, seatId, patch) {
|
||||
const base = draft && typeof draft === 'object' ? draft : {}
|
||||
const previous = base[seatId] && typeof base[seatId] === 'object' ? base[seatId] : {}
|
||||
return { ...base, [seatId]: { ...previous, ...(patch ?? {}) } }
|
||||
}
|
||||
|
||||
export function clearDraft(draft, seatId) {
|
||||
if (!draft || typeof draft !== 'object' || !hasOwn(draft, seatId)) return draft ?? {}
|
||||
const next = { ...draft }
|
||||
delete next[seatId]
|
||||
return next
|
||||
}
|
||||
|
||||
export function buildWorkbenchView(view, ui) {
|
||||
const safeView = view && typeof view === 'object' ? view : {}
|
||||
const project = safeView.project && typeof safeView.project === 'object' ? safeView.project : {}
|
||||
const status = typeof project.status === 'string' ? project.status : 'pending'
|
||||
const ready = status === 'ready'
|
||||
const seatMap = normalizeSeats(project.seats)
|
||||
const selectedSeatId = pickSelectedId(ui?.selectedSeatId)
|
||||
const models = ui?.models ?? null
|
||||
const modelOptions = collectModelOptions(models)
|
||||
const draft = ui?.draft ?? null
|
||||
|
||||
const seats = SEAT_IDS.map(id => {
|
||||
const def = SEATS[id]
|
||||
const rec = seatMap[id] ?? {}
|
||||
const seatStatus = typeof rec.status === 'string' ? rec.status : DEFAULT_SEAT_STATUS
|
||||
return {
|
||||
id,
|
||||
name: def.label,
|
||||
duty: def.duty,
|
||||
status: seatStatus,
|
||||
statusLabel: seatStatusLabel(seatStatus),
|
||||
selected: id === selectedSeatId,
|
||||
}
|
||||
})
|
||||
|
||||
const seatDef = SEATS[selectedSeatId]
|
||||
const seatRec = seatMap[selectedSeatId] ?? {}
|
||||
const draftEntry = draftOf(draft, selectedSeatId)
|
||||
let described
|
||||
if (hasOwn(draftEntry, 'modelValue')) {
|
||||
const raw = draftEntry.modelValue
|
||||
if (raw === '' || raw === null || raw === undefined) {
|
||||
described = { modelValue: '', modelLabel: UNCHOSEN_MODEL_LABEL }
|
||||
} else {
|
||||
const match = findModelOption(modelOptions, raw)
|
||||
described = match
|
||||
? { modelValue: match.value, modelLabel: match.label }
|
||||
: { modelValue: String(raw), modelLabel: String(raw) }
|
||||
}
|
||||
} else if (hasOwn(draftEntry, 'model')) {
|
||||
described = describeModel(draftEntry.model, modelOptions)
|
||||
} else {
|
||||
described = describeModel(seatRec.model ?? null, modelOptions)
|
||||
}
|
||||
|
||||
const instructions = hasOwn(draftEntry, 'instructions')
|
||||
? draftEntry.instructions
|
||||
: (typeof seatRec.instructions === 'string' ? seatRec.instructions : '')
|
||||
const selectedStatus = typeof seatRec.status === 'string' ? seatRec.status : DEFAULT_SEAT_STATUS
|
||||
|
||||
let boundCount = 0
|
||||
let sessionCount = 0
|
||||
for (const id of SEAT_IDS) {
|
||||
const rec = seatMap[id]
|
||||
if (rec?.status === 'bound') boundCount += 1
|
||||
if (rec?.sessionId) sessionCount += 1
|
||||
}
|
||||
|
||||
return {
|
||||
projectTitle: typeof project.name === 'string' ? project.name : '',
|
||||
ready,
|
||||
project: {
|
||||
id: project.id ?? '',
|
||||
name: typeof project.name === 'string' ? project.name : '',
|
||||
status,
|
||||
statusLabel: projectStatusLabel(status),
|
||||
workspaceId: project.workspaceId ?? null,
|
||||
path: project.path ?? null,
|
||||
seatCount: seats.length,
|
||||
boundCount,
|
||||
sessionCount,
|
||||
},
|
||||
seats,
|
||||
groups: cloneGroups(),
|
||||
selected: {
|
||||
id: selectedSeatId,
|
||||
name: seatDef.label,
|
||||
duty: seatDef.duty,
|
||||
responsibility: seatDef.responsibility,
|
||||
status: selectedStatus,
|
||||
statusLabel: seatStatusLabel(selectedStatus),
|
||||
sessionId: seatRec.sessionId ?? null,
|
||||
modelValue: described.modelValue,
|
||||
modelLabel: described.modelLabel,
|
||||
instructions,
|
||||
modelOptions,
|
||||
dirty: Object.keys(draftEntry).length > 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
import { SEAT_IDS } from '../shared/roles.js'
|
||||
|
||||
function bad(message, code = 'sansheng/invalid') {
|
||||
const error = new Error(message)
|
||||
error.code = code
|
||||
return error
|
||||
}
|
||||
function requireProjectId(payload) {
|
||||
const id = payload?.projectId
|
||||
if (typeof id !== 'string' || id.trim() === '') throw bad('缺少 projectId')
|
||||
return id
|
||||
}
|
||||
|
||||
// 生成 POST /api/sansheng 的处理函数:{endpoint,payload} -> {ok,value}|{ok,error}
|
||||
export function createApiHandler(service) {
|
||||
return async function handle(endpoint, payload) {
|
||||
try {
|
||||
switch (endpoint) {
|
||||
case 'list':
|
||||
return { ok: true, value: await service.list() }
|
||||
case 'project':
|
||||
return { ok: true, value: await service.project(requireProjectId(payload)) }
|
||||
case 'open':
|
||||
return { ok: true, value: await service.open(payload ?? {}) }
|
||||
case 'enable':
|
||||
return { ok: true, value: await service.enable(requireProjectId(payload)) }
|
||||
case 'configure': {
|
||||
const projectId = requireProjectId(payload)
|
||||
const seatId = payload?.seatId
|
||||
if (!SEAT_IDS.includes(seatId)) throw bad(`未知席 ${String(seatId)}`)
|
||||
return { ok: true, value: await service.configure(projectId, seatId, { model: payload?.model, instructions: payload?.instructions }) }
|
||||
}
|
||||
case 'models':
|
||||
return { ok: true, value: await service.models() }
|
||||
default:
|
||||
throw bad(`未知 endpoint ${String(endpoint)}`)
|
||||
}
|
||||
} catch (error) {
|
||||
return { ok: false, error: { code: error?.code ?? 'sansheng/error', message: error?.message ?? String(error) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export const ROUTE = '/api/sansheng'
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
// 模型配置:只记录会话级 model/selection 事件,绝不写 profile 全局默认。
|
||||
// 关键约束:不调用 sessionController.selectModel / saveSelection(它们会改全局默认)。
|
||||
export class ModelError extends Error {
|
||||
constructor(code, message) { super(message); this.name = 'ModelError'; this.code = code }
|
||||
}
|
||||
|
||||
export function normalizeSelection(selection) {
|
||||
if (selection === null || selection === undefined) return null
|
||||
if (typeof selection !== 'object') throw new ModelError('sansheng/model-invalid', '模型选择必须是对象或 null')
|
||||
const { provider, model, reasoningEffort } = selection
|
||||
if (typeof provider !== 'string' || provider.trim() === '') throw new ModelError('sansheng/model-invalid', '缺少 provider')
|
||||
if (typeof model !== 'string' || model.trim() === '') throw new ModelError('sansheng/model-invalid', '缺少 model')
|
||||
const out = { provider, model }
|
||||
if (reasoningEffort !== undefined && reasoningEffort !== null && reasoningEffort !== '') out.reasoningEffort = reasoningEffort
|
||||
return out
|
||||
}
|
||||
|
||||
// 对一个已绑定会话应用模型选择。返回 agent.model.current()。
|
||||
export async function applyModel(host, sessionId, selection) {
|
||||
const normalized = normalizeSelection(selection)
|
||||
if (!normalized) return null
|
||||
const resolved = await host.sessionController.resolveAgent(sessionId)
|
||||
if (!resolved || (resolved && 'error' in resolved)) {
|
||||
const err = resolved?.error
|
||||
throw new ModelError('sansheng/unbound', `会话不可用:${err?.message ?? err?.code ?? 'resolve failed'}`)
|
||||
}
|
||||
const agent = resolved.agent
|
||||
// 用 llm 校验路由/思考强度,不能只依赖 select 的字符串。
|
||||
await host.llm.resolveCallConfig(normalized)
|
||||
// 复核对象仍是此 ID 的活跃 Agent。
|
||||
if (host.agents.get(sessionId) !== agent) throw new ModelError('sansheng/conflict', '配置期间 Agent 已变化')
|
||||
agent.model.select(normalized)
|
||||
return agent.model.current()
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
/** DSH 主目录,与宿主一致:优先 DSH_HOME,否则 ~/.dsh。 */
|
||||
export function dshHome(env = process.env) {
|
||||
const fromEnv = env.DSH_HOME
|
||||
if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return fromEnv
|
||||
return join(homedir(), '.dsh')
|
||||
}
|
||||
|
||||
/** 三省六部自己的项目状态文件;与用户其它 DSH 数据分开存放。 */
|
||||
export function sanshengStatePath(home = dshHome()) {
|
||||
return join(home, 'sansheng', 'state.json')
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
import { seatBySessionId } from '../shared/roles.js'
|
||||
|
||||
export const PROMPT_SECTION = 'sansheng'
|
||||
|
||||
export function renderSeatPrompt({ project, seatId, seat }) {
|
||||
const lines = [
|
||||
`你在「${project?.name ?? project?.id ?? '当前项目'}」项目中担任${seat.label}(${seatId})。`,
|
||||
`本席职责:${seat.responsibility}`,
|
||||
]
|
||||
const note = project?.seats?.[seatId]?.instructions
|
||||
if (typeof note === 'string' && note.trim() !== '') lines.push(`补充说明:${note.trim()}`)
|
||||
lines.push('只在本项目本席会话内工作;不要修改其他项目或其他席的配置,也不要替用户提升权限。')
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
// 注册动态 systemPrompt section:只对十席会话注入本席角色文本,其它会话返回空串。
|
||||
export function installPromptSection(ctx, { store }) {
|
||||
return ctx.systemPrompt.section({
|
||||
name: PROMPT_SECTION,
|
||||
order: 60,
|
||||
interpolate: false,
|
||||
text: context => {
|
||||
const sessionId = context?.agent?.id
|
||||
if (!sessionId) return ''
|
||||
const found = seatBySessionId(store.state?.projects, sessionId)
|
||||
if (!found) return ''
|
||||
return renderSeatPrompt({ project: found.project, seatId: found.seatId, seat: found.seat })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,131 @@
|
|||
// 严格会话创建/恢复:先持久化计划 ID,再查是否已存在,只创建缺失项;
|
||||
// ID 不一致立即停止后续创建并保留记录;失败保留已完成绑定,重试只补未完成项。
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { SEAT_IDS } from '../shared/roles.js'
|
||||
|
||||
export class ProvisionError extends Error {
|
||||
constructor(code, message) { super(message); this.name = 'ProvisionError'; this.code = code }
|
||||
}
|
||||
|
||||
function isNotFound(error) {
|
||||
if (!error) return false
|
||||
const code = String(error.code ?? '')
|
||||
if (/not.?found/i.test(code)) return true
|
||||
const message = String(error.message ?? '')
|
||||
return /not.?found|不存在|ENOENT/i.test(message)
|
||||
}
|
||||
|
||||
export function createProvisioner({ store, host, now = () => Date.now() }) {
|
||||
const locks = new Map()
|
||||
|
||||
function withLock(key, fn) {
|
||||
const prev = locks.get(key) ?? Promise.resolve()
|
||||
const run = prev.then(fn, fn)
|
||||
const guarded = run.finally(() => { if (locks.get(key) === guarded) locks.delete(key) })
|
||||
locks.set(key, guarded)
|
||||
return guarded
|
||||
}
|
||||
|
||||
async function markBound(projectId, seatId, sessionId) {
|
||||
await store.mutate(s => {
|
||||
const p = s.projects[projectId]
|
||||
const st = p.seats[seatId]
|
||||
st.sessionId = sessionId
|
||||
st.status = 'bound'
|
||||
st.error = null
|
||||
st.updatedAt = now()
|
||||
p.updatedAt = now()
|
||||
})
|
||||
}
|
||||
async function markFailed(projectId, seatId, message) {
|
||||
await store.mutate(s => {
|
||||
const st = s.projects[projectId].seats[seatId]
|
||||
st.status = 'failed'
|
||||
st.error = String(message)
|
||||
st.updatedAt = now()
|
||||
})
|
||||
}
|
||||
async function markMismatch(projectId, seatId, planned, actual) {
|
||||
await store.mutate(s => {
|
||||
const st = s.projects[projectId].seats[seatId]
|
||||
st.status = 'failed'
|
||||
st.error = `会话 ID 不一致:计划 ${planned},实际 ${actual ?? 'null'};已停止后续创建,请核对`
|
||||
st.updatedAt = now()
|
||||
})
|
||||
}
|
||||
|
||||
async function ensureSeat(projectId, seatId) {
|
||||
const seat = store.get(projectId).seats[seatId]
|
||||
if (seat.status === 'bound' && seat.sessionId) return { ok: true, skipped: true }
|
||||
|
||||
// 先持久化计划 sessionId 与 creating 状态,再发起宿主调用。
|
||||
await store.mutate(s => {
|
||||
const st = s.projects[projectId].seats[seatId]
|
||||
if (!st.plannedSessionId) st.plannedSessionId = randomUUID()
|
||||
st.status = 'creating'
|
||||
st.error = null
|
||||
st.updatedAt = now()
|
||||
s.projects[projectId].updatedAt = now()
|
||||
})
|
||||
const project = store.get(projectId)
|
||||
const planned = project.seats[seatId].plannedSessionId
|
||||
|
||||
// 已存在则不重建,按既有会话恢复绑定。
|
||||
let resolved
|
||||
try { resolved = await host.sessionController.resolveAgent(planned) } catch (error) {
|
||||
await markFailed(projectId, seatId, `resolve: ${error?.message ?? error}`)
|
||||
return { ok: false }
|
||||
}
|
||||
if (resolved && !('error' in resolved) && resolved.agent) {
|
||||
await markBound(projectId, seatId, planned)
|
||||
return { ok: true, recovered: true }
|
||||
}
|
||||
if (resolved && 'error' in resolved && resolved.error && !isNotFound(resolved.error)) {
|
||||
await markFailed(projectId, seatId, `resolve: ${resolved.error?.message ?? resolved.error?.code ?? 'error'}`)
|
||||
return { ok: false }
|
||||
}
|
||||
|
||||
// 创建缺失项。返回 ID 必须与计划一致,否则保留实际 ID 并停止后续创建。
|
||||
let returned
|
||||
try {
|
||||
returned = await host.sessionController.create({ sessionId: planned, workspaceId: project.workspaceId ?? undefined })
|
||||
} catch (error) {
|
||||
await markFailed(projectId, seatId, `create: ${error?.message ?? error}`)
|
||||
return { ok: false }
|
||||
}
|
||||
if (!returned || returned.sessionId !== planned) {
|
||||
await markMismatch(projectId, seatId, planned, returned?.sessionId ?? null)
|
||||
return { ok: false, fatal: true }
|
||||
}
|
||||
await markBound(projectId, seatId, planned)
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
async function enable(projectId) {
|
||||
return withLock(projectId, async () => {
|
||||
const project = store.get(projectId)
|
||||
if (!project) throw new ProvisionError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||
await store.mutate(s => {
|
||||
const p = s.projects[projectId]
|
||||
p.status = 'provisioning'
|
||||
p.updatedAt = now()
|
||||
p.revision = (p.revision ?? 0) + 1
|
||||
})
|
||||
let fatal = false
|
||||
for (const seatId of SEAT_IDS) {
|
||||
const result = await ensureSeat(projectId, seatId)
|
||||
if (result.fatal) { fatal = true; break }
|
||||
}
|
||||
await store.mutate(s => {
|
||||
const p = s.projects[projectId]
|
||||
const allBound = SEAT_IDS.every(id => p.seats[id].status === 'bound')
|
||||
p.status = allBound ? 'ready' : 'error'
|
||||
p.updatedAt = now()
|
||||
p.revision = (p.revision ?? 0) + 1
|
||||
})
|
||||
return { projectId, fatal }
|
||||
})
|
||||
}
|
||||
|
||||
return { enable, ensureSeat }
|
||||
}
|
||||
|
|
@ -0,0 +1,153 @@
|
|||
import { SEAT_IDS, SEATS, SEAT_GROUPS } from '../shared/roles.js'
|
||||
import { applyModel, normalizeSelection } from './model.js'
|
||||
|
||||
export class ServiceError extends Error {
|
||||
constructor(code, message) { super(message); this.name = 'ServiceError'; this.code = code }
|
||||
}
|
||||
|
||||
export function seatView(seatId, seat) {
|
||||
const def = SEATS[seatId]
|
||||
return {
|
||||
id: seatId,
|
||||
label: def.label,
|
||||
duty: def.duty,
|
||||
responsibility: def.responsibility,
|
||||
status: seat.status,
|
||||
sessionId: seat.sessionId ?? null,
|
||||
model: seat.model ?? null,
|
||||
instructions: seat.instructions ?? '',
|
||||
error: seat.error ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
export function projectView(project) {
|
||||
return {
|
||||
revision: project.revision ?? 0,
|
||||
project: {
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
workspaceId: project.workspaceId ?? null,
|
||||
path: project.path ?? null,
|
||||
status: project.status,
|
||||
seats: SEAT_IDS.map(id => seatView(id, project.seats[id])),
|
||||
groups: {
|
||||
lead: [...SEAT_GROUPS.lead],
|
||||
sansheng: [...SEAT_GROUPS.sansheng],
|
||||
liubu: [...SEAT_GROUPS.liubu],
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeCatalog(catalog) {
|
||||
const providers = []
|
||||
const entryFor = provider => {
|
||||
let entry = providers.find(p => p.provider === provider)
|
||||
if (!entry) { entry = { provider, models: [] }; providers.push(entry) }
|
||||
return entry
|
||||
}
|
||||
const groups = catalog?.providers ?? catalog?.groups ?? catalog?.entries ?? []
|
||||
if (Array.isArray(groups)) {
|
||||
for (const g of groups) {
|
||||
const provider = g?.provider ?? g?.id ?? g?.ref ?? g?.name
|
||||
const list = g?.models ?? g?.entries ?? []
|
||||
for (const m of Array.isArray(list) ? list : []) {
|
||||
const modelId = typeof m === 'string' ? m : (m?.model ?? m?.id ?? m?.name)
|
||||
if (!provider || !modelId) continue
|
||||
const entry = entryFor(provider)
|
||||
if (entry.models.some(x => x.model === modelId)) continue
|
||||
const effort = typeof m === 'object' ? (m.reasoningEffort ?? m.reasoning) : undefined
|
||||
entry.models.push(effort ? { model: modelId, reasoningEffort: effort } : { model: modelId })
|
||||
}
|
||||
}
|
||||
}
|
||||
const def = catalog?.default ?? catalog?.deploymentDefault ?? null
|
||||
return {
|
||||
providers,
|
||||
default: def && (def.provider || def.model) ? { provider: def.provider ?? null, model: def.model ?? null } : null,
|
||||
failures: catalog?.failures ?? catalog?.isolated ?? [],
|
||||
}
|
||||
}
|
||||
|
||||
export class SanshengService {
|
||||
constructor({ store, host, provisioner }) {
|
||||
this.store = store
|
||||
this.host = host
|
||||
this.provisioner = provisioner
|
||||
}
|
||||
|
||||
async list() {
|
||||
return {
|
||||
projects: [...this.store.list()]
|
||||
.sort((a, b) => String(a.name).localeCompare(String(b.name), 'zh-Hans-CN'))
|
||||
.map(p => ({ id: p.id, name: p.name, status: p.status, revision: p.revision ?? 0 })),
|
||||
}
|
||||
}
|
||||
|
||||
async open({ workspaceId, name, path } = {}) {
|
||||
if (!workspaceId && !path) throw new ServiceError('sansheng/invalid', '需要 workspaceId 或 path')
|
||||
const registry = this.host.workspaceRegistry
|
||||
let ws
|
||||
if (workspaceId) {
|
||||
ws = registry.get(workspaceId)
|
||||
if (!ws) throw new ServiceError('sansheng/not-found', `未找到工作区 ${workspaceId}`)
|
||||
} else {
|
||||
ws = await registry.resolveByPath(path)
|
||||
if (!ws) ws = await registry.create(path, name)
|
||||
}
|
||||
const id = ws.id ?? ws.workspaceId
|
||||
await this.store.mutate(() => {
|
||||
this.store.ensureProjectRecord({
|
||||
id,
|
||||
name: name ?? ws.title ?? ws.name ?? id,
|
||||
workspaceId: id,
|
||||
path: ws.path ?? path ?? null,
|
||||
})
|
||||
})
|
||||
return projectView(this.store.get(id))
|
||||
}
|
||||
|
||||
async project(projectId) {
|
||||
const p = this.store.get(projectId)
|
||||
if (!p) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||
return projectView(p)
|
||||
}
|
||||
|
||||
async enable(projectId) {
|
||||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||
await this.provisioner.enable(projectId)
|
||||
return this.project(projectId)
|
||||
}
|
||||
|
||||
async configure(projectId, seatId, { model, instructions } = {}) {
|
||||
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', `未知席 ${seatId}`)
|
||||
const project = this.store.get(projectId)
|
||||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||
const seat = project.seats[seatId]
|
||||
|
||||
let normalized
|
||||
let applied = null
|
||||
if (model !== undefined) {
|
||||
normalized = normalizeSelection(model) // 可能抛 sansheng/model-invalid
|
||||
if (seat.sessionId) applied = await applyModel(this.host, seat.sessionId, normalized)
|
||||
}
|
||||
if (instructions !== undefined && typeof instructions !== 'string') {
|
||||
throw new ServiceError('sansheng/invalid', 'instructions 必须是字符串')
|
||||
}
|
||||
|
||||
await this.store.mutate(s => {
|
||||
const target = s.projects[projectId].seats[seatId]
|
||||
if (model !== undefined) target.model = normalized
|
||||
if (instructions !== undefined) target.instructions = instructions
|
||||
target.updatedAt = Date.now()
|
||||
s.projects[projectId].updatedAt = Date.now()
|
||||
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||||
})
|
||||
return { seat: seatView(seatId, this.store.get(projectId).seats[seatId]), applied }
|
||||
}
|
||||
|
||||
async models() {
|
||||
const catalog = await this.host.sessionController.modelCatalog()
|
||||
return normalizeCatalog(catalog)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
// 项目状态存储:单个 JSON 文件,原子写,读取时严格校验;损坏不静默回退。
|
||||
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
||||
import { dirname } from 'node:path'
|
||||
import { emptyState, emptyProject, validateState } from '../shared/schema.js'
|
||||
import { seatBySessionId } from '../shared/roles.js'
|
||||
|
||||
export class StoreError extends Error {
|
||||
constructor(code, message) { super(message); this.name = 'StoreError'; this.code = code }
|
||||
}
|
||||
|
||||
export class SanshengStore {
|
||||
constructor(file) { this.file = file; this.state = emptyState(); this._queue = Promise.resolve() }
|
||||
|
||||
async load() {
|
||||
let raw
|
||||
try {
|
||||
raw = await readFile(this.file, 'utf8')
|
||||
} catch (error) {
|
||||
if (error?.code === 'ENOENT') { this.state = emptyState(); return }
|
||||
throw new StoreError('sansheng/state-corrupt', `无法读取状态文件:${error?.message ?? error}`)
|
||||
}
|
||||
let parsed
|
||||
try { parsed = JSON.parse(raw) } catch (error) {
|
||||
throw new StoreError('sansheng/state-corrupt', `状态文件不是合法 JSON:${error.message}`)
|
||||
}
|
||||
const valid = validateState(parsed)
|
||||
if (!valid.ok) throw new StoreError('sansheng/state-corrupt', `状态文件损坏:${valid.error}`)
|
||||
this.state = valid.state
|
||||
}
|
||||
|
||||
snapshot() { return structuredClone(this.state) }
|
||||
get(projectId) { return this.state.projects[projectId] }
|
||||
list() { return Object.values(this.state.projects) }
|
||||
seatBySession(sessionId) { return seatBySessionId(this.state.projects, sessionId) }
|
||||
|
||||
// 所有写操作经此串行化:同一时刻只有一个 mutate 在跑,失败回滚内存状态。
|
||||
async mutate(fn) {
|
||||
const run = async () => {
|
||||
const before = structuredClone(this.state)
|
||||
try {
|
||||
const result = await fn(this.state)
|
||||
this.state.seq = (this.state.seq ?? 0) + 1
|
||||
await this.save()
|
||||
return result
|
||||
} catch (error) {
|
||||
this.state = before
|
||||
throw error
|
||||
}
|
||||
}
|
||||
this._queue = this._queue.then(run, run)
|
||||
return this._queue
|
||||
}
|
||||
|
||||
async save() {
|
||||
await mkdir(dirname(this.file), { recursive: true })
|
||||
const tmp = `${this.file}.${process.pid}.${Date.now()}.tmp`
|
||||
await writeFile(tmp, JSON.stringify(this.state, null, 2), 'utf8')
|
||||
await rename(tmp, this.file)
|
||||
}
|
||||
|
||||
// 确保项目记录存在;已存在则只补空字段,不覆盖既有会话/配置。
|
||||
ensureProjectRecord({ id, name, workspaceId = null, path = null, now = Date.now() }) {
|
||||
let project = this.state.projects[id]
|
||||
if (!project) {
|
||||
project = emptyProject({ id, name: name ?? id, workspaceId, path, now })
|
||||
this.state.projects[id] = project
|
||||
return project
|
||||
}
|
||||
if (name && !project.name) project.name = name
|
||||
if (workspaceId && !project.workspaceId) project.workspaceId = workspaceId
|
||||
if (path && !project.path) project.path = path
|
||||
project.updatedAt = now
|
||||
project.revision = (project.revision ?? 0) + 1
|
||||
return project
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,201 @@
|
|||
// dsh-go 原生接入:把纯视图树挂到宿主原生面板桥。
|
||||
// 全程用特性探测(ctx.inject + typeof 检查),不 import 宿主内部源码。
|
||||
import { buildPanelView } from './panel.js'
|
||||
import { SEAT_IDS } from '../shared/roles.js'
|
||||
|
||||
const PANEL_ID = 'sansheng'
|
||||
|
||||
// 进程内缓存:原生作用域没有 workspaceId,只能由 sessionId 反查项目。
|
||||
// 真实数据源需要宿主注入的服务或 HTTP 接通;拿不到时视图如实显示提示。
|
||||
const viewBySession = new Map()
|
||||
const selectionBySession = new Map()
|
||||
const modelsBySession = new Map()
|
||||
|
||||
/** 把一个项目视图中各席的 sessionId 记入缓存,供 scope.sessionId 反查。 */
|
||||
function cacheProject(project) {
|
||||
if (!project || typeof project !== 'object') return
|
||||
const seats = project.seats
|
||||
for (const id of SEAT_IDS) {
|
||||
let seat = null
|
||||
if (Array.isArray(seats)) seat = seats.find((s) => s && s.id === id) || null
|
||||
else if (seats && typeof seats === 'object') seat = seats[id] || null
|
||||
if (seat && typeof seat.sessionId === 'string' && seat.sessionId) {
|
||||
viewBySession.set(seat.sessionId, project)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 由 scope 反查项目视图:优先宿主注入的反查服务,其次 sessions.binding,最后进程内缓存。 */
|
||||
function resolveProject(native, scope) {
|
||||
const sid = scope && typeof scope.sessionId === 'string' ? scope.sessionId : null
|
||||
const lookup = (native && (native.sansheng || native.sanshengProjects)) || null
|
||||
|
||||
if (lookup && typeof lookup.projectForScope === 'function') {
|
||||
try {
|
||||
const p = lookup.projectForScope(scope)
|
||||
if (p) { cacheProject(p); return p }
|
||||
} catch (e) { /* 特性探测失败,忽略 */ }
|
||||
}
|
||||
if (lookup && typeof lookup.projectForSession === 'function' && sid) {
|
||||
try {
|
||||
const p = lookup.projectForSession(sid)
|
||||
if (p) { cacheProject(p); return p }
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
let workspaceId = null
|
||||
try {
|
||||
const sessions = native && native.sessions
|
||||
if (sessions && typeof sessions.binding === 'function' && sid) {
|
||||
const b = sessions.binding(sid)
|
||||
workspaceId = (b && (b.workspaceId || (b.workspace && b.workspace.id))) || null
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
if (lookup && typeof lookup.projectForWorkspace === 'function' && workspaceId) {
|
||||
try {
|
||||
const p = lookup.projectForWorkspace(workspaceId)
|
||||
if (p) { cacheProject(p); return p }
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
if (sid && viewBySession.has(sid)) return viewBySession.get(sid)
|
||||
return null
|
||||
}
|
||||
|
||||
/** 组装 buildPanelView 所需的 input。 */
|
||||
function makeView(native, scope) {
|
||||
const sid = scope && typeof scope.sessionId === 'string' ? scope.sessionId : null
|
||||
const project = resolveProject(native, scope)
|
||||
const selectedSeatId = sid && selectionBySession.has(sid) ? selectionBySession.get(sid) : null
|
||||
const models = sid && modelsBySession.has(sid) ? modelsBySession.get(sid) : null
|
||||
return buildPanelView({ project, selectedSeatId, models })
|
||||
}
|
||||
|
||||
/** 归一化事件里的 action(dsh-go 可能回传对象或字符串 + value)。 */
|
||||
function normalizeAction(event) {
|
||||
const a = event && event.action
|
||||
if (a && typeof a === 'object') return a
|
||||
const v = event && event.value
|
||||
if (v && typeof v === 'object' && typeof v.type === 'string') return v
|
||||
if (typeof a === 'string') return Object.assign({ type: a }, v && typeof v === 'object' ? v : {})
|
||||
return null
|
||||
}
|
||||
|
||||
async function handleEvent(native, scope, event) {
|
||||
const sid = scope && typeof scope.sessionId === 'string' ? scope.sessionId : null
|
||||
const action = normalizeAction(event)
|
||||
if (!action || typeof action.type !== 'string') return []
|
||||
|
||||
switch (action.type) {
|
||||
case 'sansheng/select-seat': {
|
||||
if (sid && action.seatId) selectionBySession.set(sid, action.seatId)
|
||||
return [{ type: 'refresh', id: PANEL_ID }]
|
||||
}
|
||||
case 'sansheng/select-model': {
|
||||
if (sid && action.seatId) selectionBySession.set(sid, action.seatId)
|
||||
// 模型持久化需要宿主 HTTP / 服务接通;原生面板暂不静默写入。
|
||||
return [{ type: 'toast', text: '模型选择在原生面板暂未接持久化,请在 Web 端保存(需真机核验)' }]
|
||||
}
|
||||
case 'sansheng/enter-session': {
|
||||
// effect 契约暂无会话跳转;优先探测宿主扩展方法,否则如实提示。
|
||||
const bridged = native && native.dshGo
|
||||
const open =
|
||||
(bridged && (bridged.openSession || bridged.navigate)) ||
|
||||
(native && native.sansheng && native.sansheng.openSession)
|
||||
if (typeof open === 'function' && action.sessionId) {
|
||||
try {
|
||||
await open(action.sessionId)
|
||||
return [{ type: 'toast', text: '已请求打开会话' }]
|
||||
} catch (e) { /* 落到提示分支 */ }
|
||||
}
|
||||
return [{ type: 'toast', text: '原生 effect 暂不支持会话跳转,请从宿主会话列表进入(需真机核验)' }]
|
||||
}
|
||||
default:
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** 可选 data 提供者:尽力通过宿主 HTTP 的 list/project 反查项目(特性探测 fetch)。 */
|
||||
function makeDataProvider(native, dshGo) {
|
||||
return function data(scope, emit) {
|
||||
let cancelled = false
|
||||
const run = async () => {
|
||||
if (typeof fetch !== 'function') return
|
||||
const sid = scope && typeof scope.sessionId === 'string' ? scope.sessionId : null
|
||||
if (!sid) return
|
||||
const post = async (endpoint, payload) => {
|
||||
const res = await fetch('/api/sansheng', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ endpoint, payload: payload == null ? null : payload }),
|
||||
})
|
||||
if (!res.ok) throw new Error('HTTP ' + res.status)
|
||||
const r = await res.json()
|
||||
if (!r || r.ok !== true) throw new Error((r && r.error && r.error.message) || 'request failed')
|
||||
return r.value
|
||||
}
|
||||
const list = await post('list')
|
||||
const projects = list && Array.isArray(list.projects) ? list.projects : []
|
||||
for (const meta of projects) {
|
||||
const value = await post('project', { projectId: meta.id })
|
||||
const project = value && value.project ? value.project : value
|
||||
cacheProject(project)
|
||||
const seats = project && project.seats
|
||||
const found = Array.isArray(seats)
|
||||
? seats.some((s) => s && s.sessionId === sid)
|
||||
: seats && Object.values(seats).some((s) => s && s.sessionId === sid)
|
||||
if (found) {
|
||||
if (!cancelled) {
|
||||
try { emit({ project }) } catch (e) { /* ignore */ }
|
||||
try { if (dshGo && typeof dshGo.refresh === 'function') dshGo.refresh(PANEL_ID, scope) } catch (e) { /* ignore */ }
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
run().catch(() => {})
|
||||
return () => { cancelled = true }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 原生接入入口。
|
||||
* @param {object} ctx Cordis context(由宿主注入)。
|
||||
* @returns {() => void} disposer
|
||||
*/
|
||||
export function install(ctx) {
|
||||
if (!ctx || typeof ctx.inject !== 'function') return () => {}
|
||||
|
||||
return ctx.inject(['dshGo', 'sessions'], (native) => {
|
||||
const dshGo = native && native.dshGo
|
||||
// 特性探测:宿主没有 dshGo.panel 就安静退出(不是 dsh-go / 桥未就绪)。
|
||||
if (!dshGo || typeof dshGo.panel !== 'function') return () => {}
|
||||
|
||||
const disposers = []
|
||||
|
||||
try {
|
||||
const offPanel = native.dshGo.panel(PANEL_ID, {
|
||||
view: (scope, caps) => makeView(native, scope),
|
||||
data: makeDataProvider(native, native.dshGo),
|
||||
})
|
||||
if (typeof offPanel === 'function') disposers.push(offPanel)
|
||||
} catch (e) { /* 桥不完整时保持静默 */ }
|
||||
|
||||
if (typeof native.dshGo.on === 'function') {
|
||||
try {
|
||||
const offOn = native.dshGo.on(PANEL_ID, (scope, event) => handleEvent(native, scope, event))
|
||||
if (typeof offOn === 'function') disposers.push(offOn)
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
return () => {
|
||||
for (const off of disposers) {
|
||||
try { off() } catch (e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export default { install }
|
||||
|
|
@ -0,0 +1,198 @@
|
|||
// dsh-go 原生面板:纯视图树构造函数。
|
||||
// 仅依赖共享的角色定义(纯 JS),不 import 任何宿主 / React / DOM 代码。
|
||||
// 硬约束(在下方逻辑中自然满足,并由 test/native.test.js 断言):
|
||||
// 节点总数 ≤120、最大深度 ≤8、任何 options / items 列表 ≤8 项、无自由文本输入控件。
|
||||
import { SEATS, SEAT_IDS, SEAT_GROUPS } from '../shared/roles.js'
|
||||
|
||||
const GROUP_ORDER = ['lead', 'sansheng', 'liubu']
|
||||
const GROUP_TITLE = { lead: '统领', sansheng: '三省', liubu: '六部' }
|
||||
|
||||
const MAX_OPTIONS = 8 // 原生单选最多 8 项(含“请选择模型”占位)
|
||||
|
||||
const PROJECT_STATUS_TEXT = {
|
||||
pending: '待启用',
|
||||
provisioning: '启用中',
|
||||
ready: '已就绪',
|
||||
error: '异常',
|
||||
}
|
||||
|
||||
const SEAT_STATUS_TEXT = {
|
||||
pending: '待启用',
|
||||
creating: '创建中',
|
||||
bound: '已绑定',
|
||||
failed: '失败',
|
||||
missing: '缺失',
|
||||
}
|
||||
|
||||
function asText(v) {
|
||||
return typeof v === 'string' ? v : ''
|
||||
}
|
||||
|
||||
/** 兼容 project.seats 为数组(项目视图)或对象(内部状态)。 */
|
||||
function seatRecords(project) {
|
||||
const out = {}
|
||||
const seats = project ? project.seats : null
|
||||
if (Array.isArray(seats)) {
|
||||
for (const s of seats) if (s && SEATS[s.id]) out[s.id] = s
|
||||
} else if (seats && typeof seats === 'object') {
|
||||
for (const id of SEAT_IDS) if (seats[id]) out[id] = seats[id]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function isBound(seat) {
|
||||
return !!seat && typeof seat.sessionId === 'string' && seat.sessionId.length > 0
|
||||
}
|
||||
|
||||
function modelValue(model) {
|
||||
if (!model || typeof model !== 'object') return ''
|
||||
if (typeof model.provider !== 'string' || typeof model.model !== 'string') return ''
|
||||
return model.provider + '::' + model.model
|
||||
}
|
||||
|
||||
function flattenModels(models) {
|
||||
const opts = []
|
||||
const providers = models && Array.isArray(models.providers) ? models.providers : []
|
||||
for (const p of providers) {
|
||||
const pid = asText(p && p.provider)
|
||||
if (!pid) continue
|
||||
const list = Array.isArray(p && p.models) ? p.models : []
|
||||
for (const m of list) {
|
||||
const mid = typeof m === 'string' ? m : asText(m && m.model)
|
||||
if (!mid) continue
|
||||
opts.push({ value: pid + '::' + mid, label: pid + ' / ' + mid })
|
||||
if (opts.length >= MAX_OPTIONS - 1) break // 留一位给占位项
|
||||
}
|
||||
if (opts.length >= MAX_OPTIONS - 1) break
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
/** 模型原生单选:value 为空显示“请选择模型”。整体 ≤8 项。 */
|
||||
function buildModelSelect(project, seat, models) {
|
||||
const real = flattenModels(models)
|
||||
const options = [{ value: '', label: '请选择模型' }].concat(real).slice(0, MAX_OPTIONS)
|
||||
const want = modelValue(seat && seat.model)
|
||||
const value = options.some((o) => o.value === want) ? want : ''
|
||||
return {
|
||||
type: 'select',
|
||||
label: '模型',
|
||||
value,
|
||||
options,
|
||||
action: { type: 'sansheng/select-model', seatId: (seat && seat.id) || null, projectId: (project && project.id) || null },
|
||||
}
|
||||
}
|
||||
|
||||
/** 单个角色按钮:label 恰为两字;选中者高亮(selected + primary)。 */
|
||||
function seatButton(project, seat, selectedSeatId) {
|
||||
const meta = SEATS[seat.id]
|
||||
const selected = seat.id === selectedSeatId
|
||||
return {
|
||||
type: 'button',
|
||||
seatId: seat.id,
|
||||
label: meta.label,
|
||||
selected,
|
||||
variant: selected ? 'primary' : 'ghost',
|
||||
action: { type: 'sansheng/select-seat', seatId: seat.id, projectId: (project && project.id) || null },
|
||||
}
|
||||
}
|
||||
|
||||
/** 一个分组(stack):标题 + 若干 row,每行 ≤3 个角色按钮(六部拆两行)。 */
|
||||
function groupNode(project, records, key, selectedSeatId) {
|
||||
const ids = (SEAT_GROUPS[key] || []).filter((id) => records[id] && SEATS[id])
|
||||
if (ids.length === 0) return null
|
||||
const perRow = key === 'liubu' ? 3 : ids.length
|
||||
const rows = []
|
||||
for (let i = 0; i < ids.length; i += perRow) {
|
||||
const slice = ids.slice(i, i + perRow)
|
||||
rows.push({ type: 'row', children: slice.map((id) => seatButton(project, records[id], selectedSeatId)) })
|
||||
}
|
||||
return {
|
||||
type: 'stack',
|
||||
group: key,
|
||||
children: [{ type: 'text', text: GROUP_TITLE[key] + ' · ' + ids.length + ' 席' }].concat(rows),
|
||||
}
|
||||
}
|
||||
|
||||
/** 选中席详情:名称/职责/只读补充说明/模型单选/进入会话按钮。 */
|
||||
function selectedDetail(project, records, selectedSeatId, models) {
|
||||
const seat = selectedSeatId ? records[selectedSeatId] : null
|
||||
if (!seat) {
|
||||
return { type: 'callout', tone: 'info', text: '点击上方角色卡片查看职责、模型与进入会话。' }
|
||||
}
|
||||
const meta = SEATS[seat.id]
|
||||
const bound = isBound(seat)
|
||||
const statusLabel = SEAT_STATUS_TEXT[seat.status] || asText(seat.status) || '未知'
|
||||
const instructions = asText(seat.instructions).trim() || '(未填写)'
|
||||
return {
|
||||
type: 'stack',
|
||||
detail: seat.id,
|
||||
children: [
|
||||
{ type: 'text', text: meta.label + ' · ' + meta.duty + ' · ' + statusLabel },
|
||||
{ type: 'callout', tone: 'info', text: '职责:' + meta.responsibility },
|
||||
{ type: 'text', text: '角色补充说明(只读,请在 Web 端编辑)' },
|
||||
{ type: 'callout', tone: 'warn', text: instructions },
|
||||
buildModelSelect(project, seat, models),
|
||||
{
|
||||
type: 'button',
|
||||
label: bound ? '进入' + meta.label + '会话' : meta.label + '尚未绑定会话',
|
||||
variant: bound ? 'primary' : 'ghost',
|
||||
disabled: !bound,
|
||||
action: {
|
||||
type: 'sansheng/enter-session',
|
||||
seatId: seat.id,
|
||||
projectId: (project && project.id) || null,
|
||||
sessionId: isBound(seat) ? seat.sessionId : null,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造原生面板视图树。
|
||||
* @param {{ project: object|null, selectedSeatId?: string|null, models?: object|null }} input
|
||||
* @returns {object} 原生 view 节点
|
||||
*/
|
||||
export function buildPanelView(input) {
|
||||
const { project = null, selectedSeatId = null, models = null } = input || {}
|
||||
|
||||
if (!project || typeof project !== 'object') {
|
||||
return {
|
||||
type: 'stack',
|
||||
children: [
|
||||
{ type: 'text', text: '三省六部' },
|
||||
{
|
||||
type: 'callout',
|
||||
tone: 'warn',
|
||||
text: '无法确定当前项目:原生面板作用域不含 workspaceId,且未能由 sessionId 反查到所属项目。请从已启用「三省六部」的项目会话中打开,或在 Web 工作台查看。',
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
const records = seatRecords(project)
|
||||
// 选中席:显式传入优先;否则默认丞相(首屏有一个可见的选中态)。
|
||||
const sel = selectedSeatId && records[selectedSeatId] ? selectedSeatId : records.lead ? 'lead' : null
|
||||
const ready = project.status === 'ready'
|
||||
const boundCount = SEAT_IDS.filter((id) => isBound(records[id])).length
|
||||
|
||||
const children = [
|
||||
{ type: 'text', text: '三省六部 · ' + (asText(project.name) || '未命名项目') },
|
||||
{
|
||||
type: 'callout',
|
||||
tone: ready ? 'good' : 'warn',
|
||||
text: (PROJECT_STATUS_TEXT[project.status] || '状态未知') + ' · 已绑定 ' + boundCount + '/10 席',
|
||||
},
|
||||
]
|
||||
|
||||
for (const key of GROUP_ORDER) {
|
||||
const g = groupNode(project, records, key, sel)
|
||||
if (g) children.push(g)
|
||||
}
|
||||
|
||||
children.push(selectedDetail(project, records, sel, models))
|
||||
return { type: 'stack', children }
|
||||
}
|
||||
|
||||
export default buildPanelView
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
// 十席固定编制。id 与 preview 原型保持一致;显示名一律两字。
|
||||
// duty 为卡片短摘要;responsibility 为项目规划里从旧代码逐字沿用的职责说明。
|
||||
|
||||
export const SEAT_IDS = Object.freeze([
|
||||
'lead', 'zhongshu', 'shangshu', 'menxia',
|
||||
'libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu',
|
||||
])
|
||||
|
||||
export const SEATS = Object.freeze({
|
||||
lead: {
|
||||
id: 'lead', label: '丞相', duty: '接需求 · 协调汇报',
|
||||
responsibility: '面向用户承接想法:判断是否需要开工、必要时派给具体部门,并把各部门结果汇总成对用户的一次交付。',
|
||||
},
|
||||
zhongshu: {
|
||||
id: 'zhongshu', label: '中书', duty: '调查 · 澄清 · 规划',
|
||||
responsibility: '先把问题问清、把材料看全,再给出可执行的方案与验收标准草案,不直接产出最终交付物。',
|
||||
},
|
||||
shangshu: {
|
||||
id: 'shangshu', label: '尚书', duty: '分工 · 组织交付',
|
||||
responsibility: '把已经明确的方案拆成部门分工并组织交付;六部直属于尚书这一同级分组,六部之间不是上下级。',
|
||||
},
|
||||
menxia: {
|
||||
id: 'menxia', label: '门下', duty: '审议 · 整体审核',
|
||||
responsibility: '对方案和交付做独立审议,指出风险与不达标处。首版没有门下审核的任务必须如实标注“未审核”。',
|
||||
},
|
||||
libu: {
|
||||
id: 'libu', label: '吏部', duty: '角色 · 技能配置',
|
||||
responsibility: '对角色、技能与编制给出建议;职责不含绕过用户授权去改权限或其他项目设置。',
|
||||
},
|
||||
hubu: {
|
||||
id: 'hubu', label: '户部', duty: '数据 · 表格计算',
|
||||
responsibility: '处理数据、表格与计算,结论应可复算。',
|
||||
},
|
||||
lipu: {
|
||||
id: 'lipu', label: '礼部', duty: '文档 · 内容呈现',
|
||||
responsibility: '负责文档、内容与呈现形式,产出可编辑的源文件。',
|
||||
},
|
||||
bingbu: {
|
||||
id: 'bingbu', label: '兵部', duty: '环境 · 调试部署',
|
||||
responsibility: '负责环境、调试与部署;部署/发布等外部副作用仍服从用户授权与宿主审批。',
|
||||
},
|
||||
xingbu: {
|
||||
id: 'xingbu', label: '刑部', duty: '测试 · 风险检查',
|
||||
responsibility: '做测试与风险检查,给出可追溯的检查结果,而不是一句“已通过”。',
|
||||
},
|
||||
gongbu: {
|
||||
id: 'gongbu', label: '工部', duty: '代码 · 工程产出',
|
||||
responsibility: '负责代码实现与工程产出,交付可编辑源文件与真实检查结果。',
|
||||
},
|
||||
})
|
||||
|
||||
// 工作台布局:丞相居中;三省一排;六部两排。
|
||||
export const SEAT_GROUPS = Object.freeze({
|
||||
lead: Object.freeze(['lead']),
|
||||
sansheng: Object.freeze(['zhongshu', 'shangshu', 'menxia']),
|
||||
liubu: Object.freeze(['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']),
|
||||
})
|
||||
|
||||
export function isSeatId(id) {
|
||||
return SEAT_IDS.includes(id)
|
||||
}
|
||||
|
||||
export function seatOf(id) {
|
||||
return SEATS[id]
|
||||
}
|
||||
|
||||
export function seatLabel(id) {
|
||||
return SEATS[id]?.label ?? ''
|
||||
}
|
||||
|
||||
/** 由 sessionId 反查所属席(用于 systemPrompt section 与项目归属校验)。 */
|
||||
export function seatBySessionId(projects, sessionId) {
|
||||
if (!sessionId || !projects) return undefined
|
||||
for (const project of Object.values(projects)) {
|
||||
for (const seatId of SEAT_IDS) {
|
||||
if (project?.seats?.[seatId]?.sessionId === sessionId) {
|
||||
return { project, seatId, seat: SEATS[seatId] }
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
// 项目状态 schema(版本 1)。前后端共用:宿主只接受明确合法的结构,
|
||||
// 合法 JSON 但结构错误一律视为损坏,绝不静默回退成“健康空状态”。
|
||||
import { SEAT_IDS } from './roles.js'
|
||||
|
||||
export const STATE_VERSION = 1
|
||||
|
||||
export const SEAT_STATUS = Object.freeze(['pending', 'creating', 'bound', 'failed', 'missing'])
|
||||
export const PROJECT_STATUS = Object.freeze(['pending', 'provisioning', 'ready', 'error'])
|
||||
|
||||
const SEAT_STATUS_SET = new Set(SEAT_STATUS)
|
||||
const PROJECT_STATUS_SET = new Set(PROJECT_STATUS)
|
||||
|
||||
function isObject(v) { return v !== null && typeof v === 'object' && !Array.isArray(v) }
|
||||
function isStr(v) { return typeof v === 'string' && v.trim() !== '' }
|
||||
|
||||
export function emptyState() {
|
||||
return { version: STATE_VERSION, seq: 0, projects: {} }
|
||||
}
|
||||
|
||||
export function emptySeat(seatId) {
|
||||
return {
|
||||
seatId,
|
||||
sessionId: null,
|
||||
plannedSessionId: null,
|
||||
status: 'pending',
|
||||
model: null,
|
||||
instructions: '',
|
||||
error: null,
|
||||
updatedAt: 0,
|
||||
}
|
||||
}
|
||||
|
||||
export function emptyProject({ id, name, workspaceId = null, path = null, now = Date.now() }) {
|
||||
const seats = {}
|
||||
for (const seatId of SEAT_IDS) seats[seatId] = emptySeat(seatId)
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
workspaceId,
|
||||
path,
|
||||
status: 'pending',
|
||||
seats,
|
||||
revision: 0,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
}
|
||||
|
||||
export function validModel(model) {
|
||||
if (model === null || model === undefined) return true
|
||||
if (!isObject(model)) return false
|
||||
if (!isStr(model.provider) || !isStr(model.model)) return false
|
||||
if (model.reasoningEffort !== undefined && typeof model.reasoningEffort !== 'string') return false
|
||||
return true
|
||||
}
|
||||
|
||||
function seatProblem(seat, seatId, projectId) {
|
||||
if (!isObject(seat)) return `项目 ${projectId} 的席 ${seatId} 不是对象`
|
||||
if (seat.seatId !== seatId) return `项目 ${projectId} 的席 ${seatId} 的 seatId 不一致`
|
||||
if (!SEAT_STATUS_SET.has(seat.status)) return `项目 ${projectId} 的席 ${seatId} 状态非法:${String(seat.status)}`
|
||||
for (const field of ['sessionId', 'plannedSessionId']) {
|
||||
if (!(seat[field] === null || isStr(seat[field]))) return `项目 ${projectId} 的席 ${seatId} 的 ${field} 非法`
|
||||
}
|
||||
if (!validModel(seat.model)) return `项目 ${projectId} 的席 ${seatId} 的 model 非法`
|
||||
if (typeof seat.instructions !== 'string') return `项目 ${projectId} 的席 ${seatId} 的 instructions 非法`
|
||||
if (!(seat.error === null || typeof seat.error === 'string')) return `项目 ${projectId} 的席 ${seatId} 的 error 非法`
|
||||
return undefined
|
||||
}
|
||||
|
||||
function projectProblem(project, id) {
|
||||
if (!isObject(project)) return `项目 ${id} 不是对象`
|
||||
if (!isStr(project.id)) return `项目 ${id} 缺少 id`
|
||||
if (project.id !== id) return `项目键 ${id} 与 id ${project.id} 不一致`
|
||||
if (typeof project.name !== 'string') return `项目 ${id} 的 name 非法`
|
||||
if (!PROJECT_STATUS_SET.has(project.status)) return `项目 ${id} 状态非法:${String(project.status)}`
|
||||
if (!(project.workspaceId === null || isStr(project.workspaceId))) return `项目 ${id} 的 workspaceId 非法`
|
||||
if (!(project.path === null || typeof project.path === 'string')) return `项目 ${id} 的 path 非法`
|
||||
if (!Number.isFinite(project.revision)) return `项目 ${id} 的 revision 非法`
|
||||
if (!isObject(project.seats)) return `项目 ${id} 缺少 seats`
|
||||
const keys = Object.keys(project.seats).sort()
|
||||
if (keys.length !== SEAT_IDS.length || keys.join(',') !== [...SEAT_IDS].sort().join(',')) {
|
||||
return `项目 ${id} 的席不是固定的十席`
|
||||
}
|
||||
for (const seatId of SEAT_IDS) {
|
||||
const problem = seatProblem(project.seats[seatId], seatId, id)
|
||||
if (problem) return problem
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function validateState(raw) {
|
||||
if (!isObject(raw)) return { ok: false, error: '状态顶层不是对象' }
|
||||
if (raw.version !== STATE_VERSION) return { ok: false, error: `不支持的状态版本 ${String(raw.version)}` }
|
||||
if (!isObject(raw.projects)) return { ok: false, error: 'projects 不是对象' }
|
||||
if (raw.seq !== undefined && !Number.isFinite(raw.seq)) return { ok: false, error: 'seq 不是数字' }
|
||||
for (const [id, project] of Object.entries(raw.projects)) {
|
||||
const problem = projectProblem(project, id)
|
||||
if (problem) return { ok: false, error: problem }
|
||||
}
|
||||
return { ok: true, state: raw }
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { createApiHandler } from '../src/host/api.js'
|
||||
import { setupService } from './helpers.js'
|
||||
|
||||
test('HTTP 处理器端到端', async () => {
|
||||
const { service } = await setupService()
|
||||
const handle = createApiHandler(service)
|
||||
|
||||
let r = await handle('list')
|
||||
assert.ok(r.ok)
|
||||
assert.deepEqual(r.value.projects, [])
|
||||
|
||||
r = await handle('open', { path: '/api', name: '接口项目' })
|
||||
assert.ok(r.ok)
|
||||
const id = r.value.project.id
|
||||
|
||||
r = await handle('enable', { projectId: id })
|
||||
assert.ok(r.ok)
|
||||
assert.equal(r.value.project.status, 'ready')
|
||||
|
||||
r = await handle('configure', { projectId: id, seatId: 'gongbu', model: { provider: 'deepseek', model: 'deepseek-chat' }, instructions: '说明' })
|
||||
assert.ok(r.ok)
|
||||
assert.deepEqual(r.value.seat.model, { provider: 'deepseek', model: 'deepseek-chat' })
|
||||
|
||||
r = await handle('project', { projectId: id })
|
||||
assert.ok(r.ok)
|
||||
assert.equal(r.value.project.seats.length, 10)
|
||||
|
||||
r = await handle('models')
|
||||
assert.ok(r.ok)
|
||||
assert.ok(r.value.providers.length >= 1)
|
||||
|
||||
r = await handle('nope')
|
||||
assert.ok(!r.ok)
|
||||
assert.equal(r.error.code, 'sansheng/invalid')
|
||||
|
||||
r = await handle('project', {})
|
||||
assert.ok(!r.ok)
|
||||
|
||||
r = await handle('project', { projectId: 'missing' })
|
||||
assert.ok(!r.ok)
|
||||
assert.equal(r.error.code, 'sansheng/not-found')
|
||||
})
|
||||
|
|
@ -0,0 +1,141 @@
|
|||
// 只测纯视图模型:绝不 import 会拉起 React 的 index.js。
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
buildWorkbenchView,
|
||||
collectModelOptions,
|
||||
updateDraft,
|
||||
UNCHOSEN_MODEL_LABEL,
|
||||
} from '../src/client/workbench.js'
|
||||
|
||||
// 与 CONTRACT.md 一致:十席固定编制、两字显示名。
|
||||
const SEAT_ROWS = [
|
||||
['lead', '丞相'],
|
||||
['zhongshu', '中书'],
|
||||
['shangshu', '尚书'],
|
||||
['menxia', '门下'],
|
||||
['libu', '吏部'],
|
||||
['hubu', '户部'],
|
||||
['lipu', '礼部'],
|
||||
['bingbu', '兵部'],
|
||||
['xingbu', '刑部'],
|
||||
['gongbu', '工部'],
|
||||
]
|
||||
|
||||
const GROUPS = {
|
||||
lead: ['lead'],
|
||||
sansheng: ['zhongshu', 'shangshu', 'menxia'],
|
||||
liubu: ['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'],
|
||||
}
|
||||
|
||||
const MODELS = {
|
||||
providers: [
|
||||
{
|
||||
provider: 'deepseek',
|
||||
models: [
|
||||
{ model: 'deepseek-chat' },
|
||||
{ model: 'deepseek-reasoner', reasoningEffort: ['low', 'high'] },
|
||||
],
|
||||
},
|
||||
],
|
||||
default: { provider: 'deepseek', model: 'deepseek-chat' },
|
||||
failures: [],
|
||||
}
|
||||
|
||||
function makeView(seatPatch, projectPatch) {
|
||||
const seats = SEAT_ROWS.map(pair => {
|
||||
const id = pair[0]
|
||||
const patch = (seatPatch && seatPatch[id]) || {}
|
||||
return {
|
||||
id,
|
||||
label: '',
|
||||
duty: '',
|
||||
responsibility: '',
|
||||
status: 'pending',
|
||||
sessionId: null,
|
||||
model: null,
|
||||
instructions: '',
|
||||
...patch,
|
||||
}
|
||||
})
|
||||
return {
|
||||
revision: 1,
|
||||
project: {
|
||||
id: 'ws-1',
|
||||
name: '测试项目',
|
||||
workspaceId: 'ws-1',
|
||||
path: 'D:/x',
|
||||
status: 'ready',
|
||||
seats,
|
||||
groups: GROUPS,
|
||||
...(projectPatch || {}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
test('十席固定编制,名称均为两字', () => {
|
||||
const out = buildWorkbenchView(makeView(), { selectedSeatId: 'lead', models: MODELS, draft: {} })
|
||||
assert.equal(out.seats.length, 10)
|
||||
assert.deepEqual(out.seats.map(s => s.id), SEAT_ROWS.map(r => r[0]))
|
||||
for (const seat of out.seats) {
|
||||
assert.equal(Array.from(seat.name).length, 2, seat.id + ' 的名称应为两字,实际 ' + seat.name)
|
||||
}
|
||||
// 缺省入参也不应抛错,且仍是十席。
|
||||
const bare = buildWorkbenchView(undefined, undefined)
|
||||
assert.equal(bare.seats.length, 10)
|
||||
})
|
||||
|
||||
test('groups 键与分组归属正确', () => {
|
||||
const out = buildWorkbenchView(makeView(), { selectedSeatId: 'shangshu', models: MODELS, draft: {} })
|
||||
assert.deepEqual(Object.keys(out.groups).sort(), ['lead', 'liubu', 'sansheng'])
|
||||
assert.deepEqual(out.groups.lead, ['lead'])
|
||||
assert.deepEqual(out.groups.sansheng, ['zhongshu', 'shangshu', 'menxia'])
|
||||
assert.deepEqual(out.groups.liubu, ['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'])
|
||||
})
|
||||
|
||||
test('未选模型时显示“请选择模型”,且 modelOptions 无 inherit 选项', () => {
|
||||
const out = buildWorkbenchView(makeView(), { selectedSeatId: 'lead', models: MODELS, draft: {} })
|
||||
assert.equal(out.selected.modelLabel, UNCHOSEN_MODEL_LABEL)
|
||||
assert.equal(out.selected.modelLabel, '请选择模型')
|
||||
assert.equal(out.selected.modelValue, '')
|
||||
assert.ok(Array.isArray(out.selected.modelOptions))
|
||||
assert.ok(out.selected.modelOptions.length > 0)
|
||||
assert.ok(!out.selected.modelOptions.some(o => o.value === 'inherit'))
|
||||
assert.ok(!out.selected.modelOptions.some(o => o.value === 'inherit'))
|
||||
// 顶层也再次覆核,防止某处泄漏“跟随宿主模型”。
|
||||
assert.ok(!collectModelOptions(MODELS).some(o => o.value === 'inherit'))
|
||||
})
|
||||
|
||||
test('选中模型后显示具体名称', () => {
|
||||
const view = makeView({ lead: { model: { provider: 'deepseek', model: 'deepseek-chat' }, status: 'bound', sessionId: 'sess-lead' } })
|
||||
const out = buildWorkbenchView(view, { selectedSeatId: 'lead', models: MODELS, draft: {} })
|
||||
assert.equal(out.selected.modelLabel, 'deepseek-chat')
|
||||
assert.equal(out.selected.modelValue, 'deepseek::deepseek-chat')
|
||||
assert.equal(out.selected.sessionId, 'sess-lead')
|
||||
assert.equal(out.selected.name, '丞相')
|
||||
// selected 必须带齐契约要求的字段。
|
||||
for (const key of ['id', 'name', 'responsibility', 'duty', 'modelValue', 'modelLabel', 'instructions', 'modelOptions']) {
|
||||
assert.ok(key in out.selected, 'selected 缺少字段 ' + key)
|
||||
}
|
||||
})
|
||||
|
||||
test('切换角色保留草稿', () => {
|
||||
// 工部写一句草稿,再切到吏部写一句:两席草稿互不覆盖。
|
||||
let draft = updateDraft({}, 'gongbu', { instructions: '工部草稿' })
|
||||
draft = updateDraft(draft, 'libu', { instructions: '吏部草稿' })
|
||||
assert.equal(draft.gongbu.instructions, '工部草稿')
|
||||
assert.equal(draft.libu.instructions, '吏部草稿')
|
||||
|
||||
const view = makeView()
|
||||
const gongbuView = buildWorkbenchView(view, { selectedSeatId: 'gongbu', models: MODELS, draft })
|
||||
assert.equal(gongbuView.selected.id, 'gongbu')
|
||||
assert.equal(gongbuView.selected.instructions, '工部草稿')
|
||||
assert.equal(gongbuView.selected.dirty, true)
|
||||
|
||||
// 切到吏部——工部草稿仍在 draft 映射里,切回工部应原样保留。
|
||||
const libuView = buildWorkbenchView(view, { selectedSeatId: 'libu', models: MODELS, draft })
|
||||
assert.equal(libuView.selected.instructions, '吏部草稿')
|
||||
|
||||
const again = buildWorkbenchView(view, { selectedSeatId: 'gongbu', models: MODELS, draft })
|
||||
assert.equal(again.selected.instructions, '工部草稿')
|
||||
})
|
||||
|
|
@ -0,0 +1,106 @@
|
|||
// 测试用 fake 宿主:模拟 DSH 注入的公开服务,便于隔离验证,不接触真实 DSH。
|
||||
import { mkdtemp } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
export async function tempStateFile() {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-test-'))
|
||||
return join(dir, 'state.json')
|
||||
}
|
||||
|
||||
export function createFakeHost(opts = {}) {
|
||||
const sessions = new Map() // sessionId -> agent
|
||||
const workspaces = new Map() // id -> { id, name, path }
|
||||
const calls = { create: [], resolve: [], selectModel: 0, agentSelect: [], createAt: [] }
|
||||
const control = {
|
||||
failCreateOrder: null, // 第 N 次 create 抛错(1 起)
|
||||
mismatchCreateOrder: null, // 第 N 次 create 返回另一个 ID
|
||||
catalog: opts.catalog ?? {
|
||||
providers: [{ provider: 'deepseek', models: ['deepseek-chat', 'deepseek-reasoner'] }],
|
||||
default: { provider: 'deepseek', model: 'deepseek-chat' },
|
||||
failures: [],
|
||||
},
|
||||
validRoutes: opts.validRoutes ?? new Set(['deepseek/deepseek-chat', 'deepseek/deepseek-reasoner']),
|
||||
}
|
||||
let createCount = 0
|
||||
|
||||
const workspaceRegistry = {
|
||||
get(id) { return workspaces.get(id) },
|
||||
list() { return [...workspaces.values()] },
|
||||
async resolveByPath(p) { return [...workspaces.values()].find(w => w.path === p) },
|
||||
async create(p, title) { const id = `ws-${workspaces.size + 1}`; const w = { id, name: title ?? id, path: p }; workspaces.set(id, w); return w },
|
||||
}
|
||||
|
||||
function agentFor(sessionId) {
|
||||
let agent = sessions.get(sessionId)
|
||||
if (!agent) {
|
||||
agent = {
|
||||
id: sessionId,
|
||||
_selection: null,
|
||||
model: {
|
||||
current() { return agent._selection },
|
||||
select(selection) { agent._selection = selection; calls.agentSelect.push({ sessionId, selection }) },
|
||||
},
|
||||
}
|
||||
sessions.set(sessionId, agent)
|
||||
}
|
||||
return agent
|
||||
}
|
||||
|
||||
const sessionController = {
|
||||
async resolveAgent(sessionId) {
|
||||
calls.resolve.push(sessionId)
|
||||
if (sessions.has(sessionId)) return { agent: sessions.get(sessionId) }
|
||||
return { error: { code: 'session/not-found', message: 'session not found' } }
|
||||
},
|
||||
async create({ sessionId, workspaceId, cwd } = {}) {
|
||||
createCount += 1
|
||||
const order = createCount
|
||||
calls.create.push({ sessionId, workspaceId, cwd, order })
|
||||
if (control.failCreateOrder === order) {
|
||||
const error = new Error('simulated create failure')
|
||||
error.code = 'session/create-failed'
|
||||
throw error
|
||||
}
|
||||
let actual = sessionId
|
||||
if (control.mismatchCreateOrder === order) actual = `minted-${Math.random().toString(36).slice(2, 8)}`
|
||||
agentFor(actual)
|
||||
return { sessionId: actual }
|
||||
},
|
||||
async modelCatalog() { return control.catalog },
|
||||
// 我们的代码绝不能调用它(会写 profile 全局默认);被调用即失败并计数。
|
||||
async selectModel() { calls.selectModel += 1; throw new Error('sessionController.selectModel must not be called') },
|
||||
}
|
||||
|
||||
const agents = { get(id) { return sessions.get(id) }, list() { return [...sessions.values()] } }
|
||||
const llm = {
|
||||
async resolveCallConfig(selection) {
|
||||
const key = `${selection.provider}/${selection.model}`
|
||||
if (control.validRoutes.size > 0 && !control.validRoutes.has(key)) {
|
||||
const error = new Error(`unknown route ${key}`)
|
||||
error.code = 'llm/unknown-model'
|
||||
throw error
|
||||
}
|
||||
return { ...selection }
|
||||
},
|
||||
}
|
||||
let promptSection = null
|
||||
const systemPrompt = { section(def) { promptSection = def; return () => { promptSection = null } } }
|
||||
let route = null
|
||||
const connection = { fetch: { register(def) { route = def; return () => {} } } }
|
||||
|
||||
const host = { workspaceRegistry, sessionController, agents, llm, systemPrompt }
|
||||
const ctx = {
|
||||
workspaceRegistry, sessionController, agents, llm, systemPrompt, connection,
|
||||
effect(fn) { const dispose = fn(); return dispose },
|
||||
}
|
||||
|
||||
return {
|
||||
host, ctx, calls, control, sessions, workspaces,
|
||||
getPromptSection() { return promptSection },
|
||||
getRoute() { return route },
|
||||
addWorkspace(id, name, path) { workspaces.set(id, { id, name, path }) },
|
||||
// 预置一个已存在的会话(用于“已存在不重建”测试)
|
||||
addSession(sessionId) { return agentFor(sessionId) },
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { SanshengStore } from '../src/host/store.js'
|
||||
import { createProvisioner } from '../src/host/provision.js'
|
||||
import { SanshengService } from '../src/host/service.js'
|
||||
import { createFakeHost, tempStateFile } from './fake-ctx.js'
|
||||
|
||||
export async function setupService(opts = {}) {
|
||||
const file = await tempStateFile()
|
||||
const store = new SanshengStore(file)
|
||||
await store.load()
|
||||
const fake = opts.fake ?? createFakeHost(opts)
|
||||
const provisioner = createProvisioner({ store, host: fake.host })
|
||||
const service = new SanshengService({ store, host: fake.host, provisioner })
|
||||
return { file, store, fake, provisioner, service }
|
||||
}
|
||||
|
||||
export function seatById(view, id) {
|
||||
return view.project.seats.find(s => s.id === id)
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { setupService } from './helpers.js'
|
||||
import { buildWorkbenchView } from '../src/client/workbench.js'
|
||||
import { buildPanelView } from '../src/native/panel.js'
|
||||
|
||||
function childNodes(node) {
|
||||
const kids = node?.children ?? node?.items ?? []
|
||||
return Array.isArray(kids) ? kids : []
|
||||
}
|
||||
function countNodes(node) {
|
||||
if (!node || typeof node !== 'object') return 0
|
||||
let total = 1
|
||||
for (const child of childNodes(node)) total += countNodes(child)
|
||||
return total
|
||||
}
|
||||
function depth(node) {
|
||||
if (!node || typeof node !== 'object') return 0
|
||||
let max = 0
|
||||
for (const child of childNodes(node)) max = Math.max(max, depth(child))
|
||||
return 1 + max
|
||||
}
|
||||
|
||||
test('宿主项目视图可直接喂给 Web 纯视图模型', async () => {
|
||||
const { service } = await setupService()
|
||||
const opened = await service.open({ path: '/ui', name: '界面项目' })
|
||||
await service.enable(opened.project.id)
|
||||
await service.configure(opened.project.id, 'gongbu', { model: { provider: 'deepseek', model: 'deepseek-chat' } })
|
||||
|
||||
const view = await service.project(opened.project.id)
|
||||
const models = await service.models()
|
||||
const vm = buildWorkbenchView(view, { selectedSeatId: 'gongbu', models })
|
||||
|
||||
assert.equal(vm.seats.length, 10)
|
||||
assert.ok(vm.seats.every(s => s.name.length === 2))
|
||||
assert.deepEqual(vm.groups, { lead: ['lead'], sansheng: ['zhongshu', 'shangshu', 'menxia'], liubu: ['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'] })
|
||||
assert.equal(vm.ready, true)
|
||||
assert.equal(vm.selected.id, 'gongbu')
|
||||
assert.match(vm.selected.modelLabel, /deepseek-chat/)
|
||||
assert.ok(!vm.selected.modelOptions.some(o => o.value === 'inherit'))
|
||||
})
|
||||
|
||||
test('宿主项目视图可直接喂给原生面板并满足容量约束', async () => {
|
||||
const { service } = await setupService()
|
||||
const opened = await service.open({ path: '/ui2', name: '原生项目' })
|
||||
await service.enable(opened.project.id)
|
||||
const view = await service.project(opened.project.id)
|
||||
const models = await service.models()
|
||||
const tree = buildPanelView({ project: view.project, selectedSeatId: 'lead', models })
|
||||
assert.ok(countNodes(tree) <= 120, '节点数应 ≤120')
|
||||
assert.ok(depth(tree) <= 8, '深度应 ≤8')
|
||||
})
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { SanshengStore } from '../src/host/store.js'
|
||||
import { createProvisioner } from '../src/host/provision.js'
|
||||
import { SanshengService } from '../src/host/service.js'
|
||||
import { createFakeHost } from './fake-ctx.js'
|
||||
import { setupService, seatById } from './helpers.js'
|
||||
|
||||
test('两个项目十席会话与模型互相隔离', async () => {
|
||||
const { service, fake } = await setupService()
|
||||
const a = await service.open({ path: '/A', name: '甲项目' })
|
||||
const b = await service.open({ path: '/B', name: '乙项目' })
|
||||
await service.enable(a.project.id)
|
||||
await service.enable(b.project.id)
|
||||
|
||||
await service.configure(a.project.id, 'gongbu', { model: { provider: 'deepseek', model: 'deepseek-chat' } })
|
||||
await service.configure(b.project.id, 'gongbu', { model: { provider: 'deepseek', model: 'deepseek-reasoner' } })
|
||||
|
||||
const pa = await service.project(a.project.id)
|
||||
const pb = await service.project(b.project.id)
|
||||
assert.deepEqual(seatById(pa, 'gongbu').model, { provider: 'deepseek', model: 'deepseek-chat' })
|
||||
assert.deepEqual(seatById(pb, 'gongbu').model, { provider: 'deepseek', model: 'deepseek-reasoner' })
|
||||
|
||||
// 两会话 ID 集合不相交
|
||||
const sa = new Set(pa.project.seats.map(s => s.sessionId))
|
||||
for (const seat of pb.project.seats) assert.ok(!sa.has(seat.sessionId))
|
||||
})
|
||||
|
||||
test('重启后十席不重复,配置与会话保持不变', async () => {
|
||||
const { service, store, fake, file } = await setupService()
|
||||
const a = await service.open({ path: '/A', name: '甲项目' })
|
||||
await service.enable(a.project.id)
|
||||
await service.configure(a.project.id, 'gongbu', { model: { provider: 'deepseek', model: 'deepseek-reasoner' } })
|
||||
const before = await service.project(a.project.id)
|
||||
const sessionsBefore = before.project.seats.map(s => s.sessionId)
|
||||
|
||||
// 模拟重启:新 store + 新 service 读同一文件、同一 fake 宿主
|
||||
const store2 = new SanshengStore(file)
|
||||
await store2.load()
|
||||
const provisioner2 = createProvisioner({ store: store2, host: fake.host })
|
||||
const service2 = new SanshengService({ store: store2, host: fake.host, provisioner: provisioner2 })
|
||||
const createdBefore = fake.calls.create.length
|
||||
const again = await service2.enable(a.project.id) // 再次启用不应重建
|
||||
assert.equal(fake.calls.create.length, createdBefore, '重启后不得重复创建会话')
|
||||
assert.equal(again.project.seats.map(s => s.sessionId).join(','), sessionsBefore.join(','))
|
||||
assert.deepEqual(seatById(again, 'gongbu').model, { provider: 'deepseek', model: 'deepseek-reasoner' })
|
||||
})
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { setupService, seatById } from './helpers.js'
|
||||
|
||||
async function ready() {
|
||||
const ctx = await setupService()
|
||||
const opened = await ctx.service.open({ path: '/pm', name: '模型项目' })
|
||||
const id = opened.project.id
|
||||
await ctx.service.enable(id)
|
||||
return { ...ctx, id }
|
||||
}
|
||||
|
||||
test('配置模型走 agent.model.select,不调用 controller.selectModel', async () => {
|
||||
const { service, fake, id } = await ready()
|
||||
const res = await service.configure(id, 'gongbu', { model: { provider: 'deepseek', model: 'deepseek-chat' } })
|
||||
assert.equal(fake.calls.selectModel, 0)
|
||||
assert.equal(fake.calls.agentSelect.length, 1)
|
||||
assert.deepEqual(res.seat.model, { provider: 'deepseek', model: 'deepseek-chat' })
|
||||
const p = await service.project(id)
|
||||
assert.deepEqual(seatById(p, 'gongbu').model, { provider: 'deepseek', model: 'deepseek-chat' })
|
||||
})
|
||||
|
||||
test('非法模型被 validate 拒绝且不落库', async () => {
|
||||
const { service, fake, id } = await ready()
|
||||
await assert.rejects(
|
||||
() => service.configure(id, 'hubu', { model: { provider: 'ghost', model: 'nope' } }),
|
||||
err => err.code === 'sansheng/model-invalid' || err.code === 'llm/unknown-model',
|
||||
)
|
||||
assert.equal(fake.calls.agentSelect.length, 0)
|
||||
const p = await service.project(id)
|
||||
assert.equal(seatById(p, 'hubu').model, null)
|
||||
})
|
||||
|
||||
test('缺 provider/model 直接拒绝', async () => {
|
||||
const { service, id } = await ready()
|
||||
await assert.rejects(() => service.configure(id, 'libu', { model: { provider: 'deepseek' } }), err => err.code === 'sansheng/model-invalid')
|
||||
})
|
||||
|
||||
test('补充说明可保存并持久化', async () => {
|
||||
const { service, store, id } = await ready()
|
||||
await service.configure(id, 'xingbu', { instructions: '只跑只读检查' })
|
||||
const p = await service.project(id)
|
||||
assert.equal(seatById(p, 'xingbu').instructions, '只跑只读检查')
|
||||
})
|
||||
|
|
@ -0,0 +1,192 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { buildPanelView } from '../src/native/panel.js'
|
||||
import { SEATS, SEAT_GROUPS } from '../src/shared/roles.js'
|
||||
|
||||
/** 递归遍历视图树(沿 children),depth 从 1 起。 */
|
||||
function traverse(node, fn, depth = 1) {
|
||||
if (!node || typeof node !== 'object') return
|
||||
fn(node, depth)
|
||||
const kids = Array.isArray(node.children) ? node.children : []
|
||||
for (const k of kids) traverse(k, fn, depth + 1)
|
||||
}
|
||||
|
||||
function analyze(root) {
|
||||
let count = 0
|
||||
let maxDepth = 0
|
||||
let maxOptions = 0
|
||||
let maxItems = 0
|
||||
const types = new Set()
|
||||
const seatNodes = []
|
||||
traverse(root, (n, d) => {
|
||||
count += 1
|
||||
if (d > maxDepth) maxDepth = d
|
||||
if (typeof n.type === 'string') types.add(n.type)
|
||||
if (Array.isArray(n.options)) maxOptions = Math.max(maxOptions, n.options.length)
|
||||
if (Array.isArray(n.items)) maxItems = Math.max(maxItems, n.items.length)
|
||||
if (typeof n.seatId === 'string') seatNodes.push(n)
|
||||
})
|
||||
return { count, maxDepth, maxOptions, maxItems, types, seatNodes }
|
||||
}
|
||||
|
||||
function makeProject() {
|
||||
const seats = Object.keys(SEATS).map((id) => ({
|
||||
id,
|
||||
label: SEATS[id].label,
|
||||
duty: SEATS[id].duty,
|
||||
responsibility: SEATS[id].responsibility,
|
||||
status: 'bound',
|
||||
sessionId: 'sess-' + id,
|
||||
model: id === 'gongbu' ? { provider: 'demo', model: 'deepseek-chat' } : null,
|
||||
instructions: id === 'lead' ? '优先用中文,先给结论。' : '',
|
||||
}))
|
||||
return {
|
||||
id: 'p1',
|
||||
name: '演示项目',
|
||||
workspaceId: 'ws-1',
|
||||
path: 'D:/demo',
|
||||
status: 'ready',
|
||||
seats,
|
||||
groups: SEAT_GROUPS,
|
||||
}
|
||||
}
|
||||
|
||||
const MODELS = {
|
||||
providers: [
|
||||
{ provider: 'demo', models: [{ model: 'deepseek-chat' }, { model: 'deepseek-reasoner' }] },
|
||||
],
|
||||
default: { provider: 'demo', model: 'deepseek-chat' },
|
||||
failures: [],
|
||||
}
|
||||
|
||||
function build(extra) {
|
||||
return buildPanelView(Object.assign({ project: makeProject(), selectedSeatId: 'gongbu', models: MODELS }, extra || {}))
|
||||
}
|
||||
|
||||
test('十席:恰好十席、名称两字、分组齐全', () => {
|
||||
const view = build()
|
||||
const m = analyze(view)
|
||||
|
||||
// 恰好十席(唯一 seatId 的按钮节点)
|
||||
const ids = m.seatNodes.map((n) => n.seatId)
|
||||
assert.equal(ids.length, 10, '十席按钮应为 10 个')
|
||||
assert.equal(new Set(ids).size, 10, '十席 seatId 应互不相同')
|
||||
assert.deepEqual([...ids].sort(), Object.keys(SEATS).sort(), '应覆盖固定十席')
|
||||
|
||||
// 名称两字,且与共享定义一致
|
||||
for (const n of m.seatNodes) {
|
||||
assert.equal(Array.from(n.label).length, 2, n.seatId + ' 的名称应为两字:' + n.label)
|
||||
assert.equal(n.label, SEATS[n.seatId].label)
|
||||
}
|
||||
|
||||
// 分组齐全:lead / sansheng / liubu
|
||||
const groups = []
|
||||
traverse(view, (n) => { if (typeof n.group === 'string') groups.push(n.group) })
|
||||
assert.deepEqual(groups.sort(), ['lead', 'liubu', 'sansheng'].sort(), '应包含三个分组')
|
||||
|
||||
// 各分组席数:1 / 3 / 6
|
||||
const countInGroup = (groupKey) => {
|
||||
let groupNode = null
|
||||
traverse(view, (n) => { if (n.group === groupKey) groupNode = n })
|
||||
assert.ok(groupNode, '缺少分组 ' + groupKey)
|
||||
let c = 0
|
||||
traverse(groupNode, (n) => { if (typeof n.seatId === 'string') c += 1 })
|
||||
return c
|
||||
}
|
||||
assert.equal(countInGroup('lead'), 1)
|
||||
assert.equal(countInGroup('sansheng'), 3)
|
||||
assert.equal(countInGroup('liubu'), 6)
|
||||
// 分组定义一致性
|
||||
assert.equal(SEAT_GROUPS.liubu.length, 6)
|
||||
})
|
||||
|
||||
test('容量:节点 ≤120、深度 ≤8、options/items ≤8', () => {
|
||||
const m = analyze(build())
|
||||
assert.ok(m.count <= 120, '节点数应 ≤120,实际 ' + m.count)
|
||||
assert.ok(m.maxDepth <= 8, '最大深度应 ≤8,实际 ' + m.maxDepth)
|
||||
assert.ok(m.maxOptions <= 8, 'options 项数应 ≤8,实际 ' + m.maxOptions)
|
||||
assert.ok(m.maxItems <= 8, 'items 项数应 ≤8,实际 ' + m.maxItems)
|
||||
})
|
||||
|
||||
test('模型为原生单选且不超过 8 项,含“请选择模型”占位', () => {
|
||||
const view = build()
|
||||
let select = null
|
||||
traverse(view, (n) => { if (n.type === 'select') select = n })
|
||||
assert.ok(select, '应存在模型单选节点')
|
||||
assert.ok(Array.isArray(select.options))
|
||||
assert.ok(select.options.length <= 8)
|
||||
assert.equal(select.options[0].value, '')
|
||||
assert.equal(select.options[0].label, '请选择模型')
|
||||
// 已选中的工部模型应回填为具体 provider::model
|
||||
assert.equal(select.value, 'demo::deepseek-chat')
|
||||
|
||||
// 即使喂入大量模型候选,也要被截断到 ≤8(含占位)
|
||||
const many = { providers: [{ provider: 'p', models: Array.from({ length: 20 }, (_, i) => ({ model: 'm' + i })) }] }
|
||||
const bigView = buildPanelView({ project: makeProject(), selectedSeatId: 'gongbu', models: many })
|
||||
let bigSelect = null
|
||||
traverse(bigView, (n) => { if (n.type === 'select') bigSelect = n })
|
||||
assert.ok(bigSelect.options.length <= 8, '模型候选应被截断到 ≤8 项')
|
||||
})
|
||||
|
||||
test('不存在自由文本输入控件(input/textarea)', () => {
|
||||
const view = build()
|
||||
const bad = []
|
||||
traverse(view, (n) => {
|
||||
if (n.type === 'input' || n.type === 'textarea') bad.push(n.type)
|
||||
if (typeof n.component === 'string' && (n.component === 'input' || n.component === 'textarea')) bad.push(n.component)
|
||||
})
|
||||
assert.deepEqual(bad, [], '不应出现自由文本控件:' + bad.join(','))
|
||||
// 同时确认渲染出的类型集合里没有意外控件
|
||||
const m = analyze(view)
|
||||
assert.ok(!m.types.has('input'))
|
||||
assert.ok(!m.types.has('textarea'))
|
||||
})
|
||||
|
||||
test('选中席出现在树里并高亮', () => {
|
||||
const view = build({ selectedSeatId: 'bingbu' })
|
||||
const m = analyze(view)
|
||||
const hit = m.seatNodes.find((n) => n.seatId === 'bingbu')
|
||||
assert.ok(hit, '选中的兵部应出现在树中')
|
||||
assert.equal(hit.selected, true, '选中席应标记 selected=true')
|
||||
assert.equal(hit.variant, 'primary', '选中席应高亮(primary)')
|
||||
// 其它席不应被标记选中
|
||||
const others = m.seatNodes.filter((n) => n.seatId !== 'bingbu')
|
||||
assert.ok(others.every((n) => n.selected !== true), '非选中席不应高亮')
|
||||
// 详情区应出现选中席名称(两字名)
|
||||
let hasName = false
|
||||
traverse(view, (n) => { if (n.type === 'text' && typeof n.text === 'string' && n.text.includes(SEATS.bingbu.label)) hasName = true })
|
||||
assert.ok(hasName, '详情区应包含选中席名称')
|
||||
})
|
||||
|
||||
test('进入会话按钮:表达意图(含 seatId/sessionId),未绑定则禁用', () => {
|
||||
const view = build({ selectedSeatId: 'hubu' })
|
||||
let enter = null
|
||||
traverse(view, (n) => {
|
||||
if (n.type === 'button' && n.action && n.action.type === 'sansheng/enter-session') enter = n
|
||||
})
|
||||
assert.ok(enter, '应存在进入会话按钮')
|
||||
assert.equal(enter.action.seatId, 'hubu')
|
||||
assert.equal(enter.action.sessionId, 'sess-hubu')
|
||||
assert.equal(enter.disabled, false)
|
||||
|
||||
// 未绑定席:按钮禁用
|
||||
const project = makeProject()
|
||||
const hubu = project.seats.find((s) => s.id === 'hubu')
|
||||
hubu.sessionId = null
|
||||
hubu.status = 'pending'
|
||||
const view2 = buildPanelView({ project, selectedSeatId: 'hubu', models: MODELS })
|
||||
let enter2 = null
|
||||
traverse(view2, (n) => {
|
||||
if (n.type === 'button' && n.action && n.action.type === 'sansheng/enter-session') enter2 = n
|
||||
})
|
||||
assert.equal(enter2.disabled, true, '未绑定席的进入会话按钮应禁用')
|
||||
})
|
||||
|
||||
test('缺少项目时给出安全提示(scope 无 workspaceId 的兜底)', () => {
|
||||
const view = buildPanelView({ project: null, selectedSeatId: null, models: null })
|
||||
let shown = false
|
||||
traverse(view, (n) => { if (n.type === 'callout' && typeof n.text === 'string' && n.text.includes('无法确定当前项目')) shown = true })
|
||||
assert.ok(shown, '无项目时应显示安全提示')
|
||||
const m = analyze(view)
|
||||
assert.ok(m.count <= 120 && m.maxDepth <= 8)
|
||||
})
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { installPromptSection } from '../src/host/prompt.js'
|
||||
import { setupService, seatById } from './helpers.js'
|
||||
|
||||
test('只对十席会话注入角色提示', async () => {
|
||||
const { service, store, fake } = await setupService()
|
||||
installPromptSection(fake.ctx, { store })
|
||||
const section = fake.getPromptSection()
|
||||
assert.ok(section)
|
||||
assert.equal(section.name, 'sansheng')
|
||||
|
||||
const opened = await service.open({ path: '/pp', name: '提示项目' })
|
||||
await service.enable(opened.project.id)
|
||||
const p = await service.project(opened.project.id)
|
||||
const seat = seatById(p, 'gongbu')
|
||||
|
||||
const text = section.text({ agent: { id: seat.sessionId } })
|
||||
assert.match(text, /工部/)
|
||||
assert.match(text, /代码实现与工程产出/)
|
||||
|
||||
assert.equal(section.text({ agent: { id: 'other-session' } }), '')
|
||||
assert.equal(section.text({}), '')
|
||||
})
|
||||
|
||||
test('补充说明出现在提示里', async () => {
|
||||
const { service, store, fake } = await setupService()
|
||||
installPromptSection(fake.ctx, { store })
|
||||
const opened = await service.open({ path: '/pp2', name: 'p' })
|
||||
await service.enable(opened.project.id)
|
||||
await service.configure(opened.project.id, 'libu', { instructions: '先问清目标' })
|
||||
const p = await service.project(opened.project.id)
|
||||
const text = fake.getPromptSection().text({ agent: { id: seatById(p, 'libu').sessionId } })
|
||||
assert.match(text, /先问清目标/)
|
||||
})
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { SEAT_IDS } from '../src/shared/roles.js'
|
||||
import { setupService, seatById } from './helpers.js'
|
||||
|
||||
test('启用创建十席并全部绑定', async () => {
|
||||
const { service, fake } = await setupService()
|
||||
const opened = await service.open({ path: '/p1', name: '项目一' })
|
||||
const id = opened.project.id
|
||||
assert.equal(opened.project.seats.length, 10)
|
||||
const enabled = await service.enable(id)
|
||||
assert.equal(enabled.project.status, 'ready')
|
||||
assert.equal(fake.calls.create.length, 10)
|
||||
for (const seat of enabled.project.seats) {
|
||||
assert.equal(seat.status, 'bound')
|
||||
assert.ok(seat.sessionId)
|
||||
}
|
||||
assert.equal(new Set(enabled.project.seats.map(s => s.sessionId)).size, 10)
|
||||
assert.equal(fake.calls.selectModel, 0)
|
||||
})
|
||||
|
||||
test('已存在会话不重建(按既有会话恢复绑定)', async () => {
|
||||
const { service, store, fake } = await setupService()
|
||||
const opened = await service.open({ path: '/p2', name: '项目二' })
|
||||
const id = opened.project.id
|
||||
const planned = 'pre-lead-session'
|
||||
await store.mutate(s => { s.projects[id].seats.lead.plannedSessionId = planned })
|
||||
fake.addSession(planned)
|
||||
const enabled = await service.enable(id)
|
||||
assert.equal(enabled.project.status, 'ready')
|
||||
assert.equal(seatById(enabled, 'lead').sessionId, planned)
|
||||
assert.equal(fake.calls.create.filter(c => c.sessionId === planned).length, 0)
|
||||
assert.equal(fake.calls.create.length, 9)
|
||||
})
|
||||
|
||||
test('返回 ID 不一致:立即停止后续创建并记录', async () => {
|
||||
const { service, fake } = await setupService()
|
||||
fake.control.mismatchCreateOrder = 1
|
||||
const opened = await service.open({ path: '/p3', name: '项目三' })
|
||||
const enabled = await service.enable(opened.project.id)
|
||||
assert.equal(fake.calls.create.length, 1)
|
||||
assert.equal(enabled.project.status, 'error')
|
||||
const failed = enabled.project.seats.filter(s => s.status === 'failed')
|
||||
assert.equal(failed.length, 1)
|
||||
assert.match(failed[0].error, /不一致/)
|
||||
assert.equal(enabled.project.seats.filter(s => s.status === 'pending').length, 9)
|
||||
})
|
||||
|
||||
test('失败保留已完成绑定,重试只补未完成项', async () => {
|
||||
const { service, fake } = await setupService()
|
||||
fake.control.failCreateOrder = 2
|
||||
const opened = await service.open({ path: '/p4', name: '项目四' })
|
||||
const id = opened.project.id
|
||||
const first = await service.enable(id)
|
||||
assert.equal(first.project.status, 'error')
|
||||
const boundBefore = first.project.seats.filter(s => s.status === 'bound').map(s => s.sessionId)
|
||||
assert.equal(boundBefore.length, 9)
|
||||
|
||||
fake.control.failCreateOrder = null
|
||||
const createdBefore = fake.calls.create.length
|
||||
const second = await service.enable(id)
|
||||
assert.equal(second.project.status, 'ready')
|
||||
const nowBound = second.project.seats.filter(s => s.status === 'bound').map(s => s.sessionId)
|
||||
for (const sid of boundBefore) assert.ok(nowBound.includes(sid), '已绑定的会话 ID 不能变')
|
||||
assert.equal(nowBound.length, 10)
|
||||
assert.equal(fake.calls.create.length, createdBefore + 1, '重试只应补一个会话')
|
||||
})
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { SEAT_IDS, SEATS, SEAT_GROUPS, seatLabel, isSeatId } from '../src/shared/roles.js'
|
||||
|
||||
test('十席固定且显示名两字', () => {
|
||||
assert.equal(SEAT_IDS.length, 10)
|
||||
assert.equal(new Set(SEAT_IDS).size, 10)
|
||||
for (const id of SEAT_IDS) {
|
||||
assert.equal(SEATS[id].id, id)
|
||||
assert.equal(SEATS[id].label.length, 2, `${id} 显示名必须是两字`)
|
||||
assert.ok(SEATS[id].duty && SEATS[id].duty.length > 0)
|
||||
assert.ok(SEATS[id].responsibility && SEATS[id].responsibility.length > 0)
|
||||
}
|
||||
})
|
||||
|
||||
test('分组覆盖全部十席且结构正确', () => {
|
||||
const all = [...SEAT_GROUPS.lead, ...SEAT_GROUPS.sansheng, ...SEAT_GROUPS.liubu].sort()
|
||||
assert.deepEqual(all, [...SEAT_IDS].sort())
|
||||
assert.deepEqual([...SEAT_GROUPS.lead], ['lead'])
|
||||
assert.deepEqual([...SEAT_GROUPS.sansheng], ['zhongshu', 'shangshu', 'menxia'])
|
||||
assert.equal(SEAT_GROUPS.liubu.length, 6)
|
||||
})
|
||||
|
||||
test('seatLabel / isSeatId', () => {
|
||||
assert.equal(seatLabel('gongbu'), '工部')
|
||||
assert.equal(seatLabel('lead'), '丞相')
|
||||
assert.ok(isSeatId('lead'))
|
||||
assert.ok(!isSeatId('nope'))
|
||||
})
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { writeFile } from 'node:fs/promises'
|
||||
import { SanshengStore, StoreError } from '../src/host/store.js'
|
||||
import { emptyState } from '../src/shared/schema.js'
|
||||
import { tempStateFile } from './fake-ctx.js'
|
||||
|
||||
test('缺少文件加载为空状态', async () => {
|
||||
const file = await tempStateFile()
|
||||
const store = new SanshengStore(file)
|
||||
await store.load()
|
||||
assert.deepEqual(store.snapshot(), emptyState())
|
||||
})
|
||||
|
||||
test('保存后可重新加载,项目含十席', async () => {
|
||||
const file = await tempStateFile()
|
||||
const store = new SanshengStore(file)
|
||||
await store.load()
|
||||
await store.mutate(() => { store.ensureProjectRecord({ id: 'ws-1', name: '项目一', workspaceId: 'ws-1', path: '/p1' }) })
|
||||
const again = new SanshengStore(file)
|
||||
await again.load()
|
||||
const p = again.get('ws-1')
|
||||
assert.equal(p.name, '项目一')
|
||||
assert.equal(Object.keys(p.seats).length, 10)
|
||||
})
|
||||
|
||||
test('非法 JSON 视为损坏并抛错(不回退空状态)', async () => {
|
||||
const file = await tempStateFile()
|
||||
await writeFile(file, '{ 不是 json', 'utf8')
|
||||
const store = new SanshengStore(file)
|
||||
await assert.rejects(() => store.load(), err => err instanceof StoreError && err.code === 'sansheng/state-corrupt')
|
||||
})
|
||||
|
||||
test('错误版本视为损坏', async () => {
|
||||
const file = await tempStateFile()
|
||||
await writeFile(file, JSON.stringify({ version: 9, projects: {} }), 'utf8')
|
||||
const store = new SanshengStore(file)
|
||||
await assert.rejects(() => store.load(), err => err.code === 'sansheng/state-corrupt')
|
||||
})
|
||||
|
||||
test('seats 不是固定十席视为损坏', async () => {
|
||||
const file = await tempStateFile()
|
||||
const state = emptyState()
|
||||
state.projects.bad = { id: 'bad', name: 'x', workspaceId: null, path: null, status: 'pending', revision: 0, seats: {} }
|
||||
await writeFile(file, JSON.stringify(state), 'utf8')
|
||||
const store = new SanshengStore(file)
|
||||
await assert.rejects(() => store.load(), err => err.code === 'sansheng/state-corrupt')
|
||||
})
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { apply, name, inject } from '../index.js'
|
||||
import { createFakeHost, tempStateFile } from './fake-ctx.js'
|
||||
|
||||
test('apply 注册提示词与 /api/sansheng 路由并可处理请求', async () => {
|
||||
const fake = createFakeHost()
|
||||
const statePath = await tempStateFile()
|
||||
await apply(fake.ctx, { statePath })
|
||||
|
||||
assert.equal(name, 'sansheng')
|
||||
assert.ok(inject.includes('connection'))
|
||||
assert.ok(fake.getPromptSection(), '应注册 systemPrompt section')
|
||||
|
||||
const route = fake.getRoute()
|
||||
assert.equal(route.path, '/api/sansheng')
|
||||
assert.deepEqual(route.methods, ['POST'])
|
||||
|
||||
const res = await route.fetch({ json: async () => ({ endpoint: 'open', payload: { path: '/w', name: '接线项目' } }) })
|
||||
const body = await res.json()
|
||||
assert.ok(body.ok)
|
||||
assert.equal(body.value.project.seats.length, 10)
|
||||
})
|
||||