agent-loft 0.2.112 → 0.2.114
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/package.json +3 -1
- package/src/agents/codex/session.ts +31 -3
- package/src/agents/dsh/acp.ts +193 -0
- package/src/agents/dsh/driver.ts +126 -0
- package/src/agents/dsh/errors.ts +43 -0
- package/src/agents/dsh/history.ts +346 -0
- package/src/agents/dsh/sdk.ts +191 -0
- package/src/agents/dsh/session.ts +454 -0
- package/src/agents/dsh/steps.ts +22 -0
- package/src/agents/dsh/which.ts +23 -0
- package/src/agents/health.ts +51 -2
- package/src/channels/feishu/bot.ts +1 -1
- package/src/channels/web/api.ts +14 -0
- package/src/channels/web/server.ts +69 -11
- package/src/core/builtin-agents.ts +1 -1
- package/src/core/command-catalog.ts +2 -1
- package/src/core/commands.ts +2 -1
- package/src/core/config.ts +23 -3
- package/src/core/experts.ts +3 -3
- package/src/core/hub.ts +4 -3
- package/src/core/memory-curator.ts +2 -2
- package/src/core/memory.ts +2 -2
- package/src/core/permission.ts +1 -1
- package/src/core/realtime-relay.ts +142 -0
- package/src/core/types.ts +4 -1
- package/src/core/users.ts +1 -1
- package/src/main.ts +5 -1
- package/web/css/composer.css +38 -0
- package/web/lib/dom.js +2 -0
- package/web/lib/rt-worklet.js +110 -0
- package/web/lib/ws.js +5 -2
- package/web/settings/agent-defaults.js +2 -2
- package/web/settings/agents.js +15 -1
- package/web/settings/commands.js +1 -1
- package/web/settings/experts.js +1 -1
- package/web/settings/memory.js +2 -1
- package/web/views/composer.js +1 -1
- package/web/views/sidebar.js +1 -1
- package/web/views/topbar.js +1 -1
- package/web/views/voice-call.js +248 -56
package/README.md
CHANGED
|
@@ -36,9 +36,10 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
|
|
|
36
36
|
|
|
37
37
|
## 能做什么
|
|
38
38
|
|
|
39
|
-
- **多个 agent**:Claude Code、Codex、WorkBuddy、pi。几个 agent 共用工作目录,能看到对方改过的文件,但聊天记录各自独立。
|
|
39
|
+
- **多个 agent**:Claude Code、Codex、WorkBuddy、pi、dsh。几个 agent 共用工作目录,能看到对方改过的文件,但聊天记录各自独立。
|
|
40
40
|
- **WorkBuddy(腾讯)**:默认不启用。调用这台服务器上 **WorkBuddy 桌面版自带的 CLI**(官方 Agent SDK `@tencent-ai/agent-sdk` 驱动,账号站点 www.workbuddy.cn),也可以改用 CodeBuddy 国内版 / 国际版 / 腾讯 iOA 的账号(用 SDK 自带的 CLI,不用装桌面版)。到 设置 → Agent → WorkBuddy 勾上「启用」、选账号站点后保存,再在「运行环境」里点「登录 WorkBuddy」:在你自己的浏览器里打开登录页,**1 分钟内**登录完(CLI 只等这么久,超时重新点),整台服务器登一次就行,所有人共用。桌面版里登录过也要在这里再登一次(同一个账号):桌面版的登录由它自己保管,不交给单独跑的 CLI;这边的令牌存在 `data/workbuddy-auth.json`(0600),不碰桌面版的数据。也可以给服务设 `CODEBUDDY_API_KEY`。支持流式回复、授权卡(逐次询问 / 自动改文件 / 完全允许)、提问卡、计划模式、中途换模型、图片附件、`/sessions` 恢复以前的会话、记忆和定时任务工具、个人技能和 MCP;管理员的会话读机器上的 `~/.codebuddy` 配置,成员只读项目里的。暂不支持自定义专家、分叉 / 回退、思考程度和额度显示;令牌过期后要回设置页重新登录。
|
|
41
41
|
- **pi**:默认不启用。开源编程 agent [pi](https://pi.dev),用官方 TypeScript SDK(`@earendil-works/pi-coding-agent`)在 agent-loft 进程里运行(需要 Node 22.19 以上)。按**模型服务商**配凭据,整台服务器共用:到 设置 → Agent → pi 勾上「启用」,在「模型服务商」里选一家(DeepSeek、智谱 Coding Plan、Kimi、通义 Token Plan、MiniMax、OpenRouter、Anthropic、OpenAI……)粘贴 API Key 保存;或者点「登录」用**订阅账号**(Claude Pro/Max、ChatGPT Plus/Pro、GitHub Copilot、Kimi Code、xAI……),在你自己的浏览器里完成,设备码直接显示在页面上,浏览器登录完跳到打不开的 127.0.0.1 地址时把地址栏整个粘贴回来即可(订阅能否用在第三方工具里以各家条款为准);也可以给服务设对应的环境变量(如 `DEEPSEEK_API_KEY`)。本地模型和 OpenAI 兼容网关在「自定义服务商」里加(Ollama、LM Studio、vLLM、llama.cpp、one-api……,填地址、接口类型、Key,能「从服务读取模型列表」),写在 `data/pi/models.json`(0600,Key 按字面值保存,不会被当成环境变量或命令)。凭据、会话记录都存在 `data/pi/` 下(`auth.json` 0600、`sessions/`),不读也不写机器上的 `~/.pi`;项目里的 `.pi/` 扩展不加载。pi 自己没有权限系统,授权卡(逐次询问 / 自动改文件 / 完全允许)、计划模式、提问卡由 agent-loft 补上,「自动改文件」只放行工作目录和附件目录里的文件;跑命令(bash)没有沙箱。支持流式回复、中途换模型和思考程度、图片附件(模型支持时)、`/compact` 压缩上下文、`/sessions` 恢复、分叉 / 回退、费用显示、记忆和定时任务工具、个人技能和 MCP,记忆整理也可选 pi。可以建 pi 引擎的自定义专家(见下面「专家」)。
|
|
42
|
+
- **dsh(DeepSeek Harness)**:默认不启用。DeepSeek 官方的编程 agent,先在服务器上 `npm install -g @deepseek-ai/dsh`(升级也是这条),再到 设置 → Agent → dsh 勾上「启用」。agent-loft 通过标准 ACP 协议(`dsh --profile acp`)接入,每个会话一个 dsh 进程(第一条消息要等 4~5 秒拉起,闲置后回收)。凭据和会话记录用 dsh 自己的 `~/.dsh`(DeepSeek API Key 在 `dsh web` 的网页里填,或给服务设 `DEEPSEEK_API_KEY`),dsh 网页里建的会话这里也能接着聊(用 DeepSeek 官方模型的)。权限走 dsh 的沙箱:逐次询问 = 只读、自动改文件 = 工作区可写、完全允许 = 不设沙箱,越界时弹授权卡,可「本会话全部允许」;计划模式用只读沙箱 + 提示词实现,方案写在回复里,关掉计划模式后再动手。支持中途换模型和思考程度(off / low / high / max)、恢复会话、任务清单、上下文占用和 token 用量、记忆和定时任务工具、个人技能和 MCP,记忆整理也可选 dsh。不支持自定义专家、分叉 / 回退、提问卡、逐字流式和图片直传(附件给路径让它自己读);设成「调用前询问」的 MCP 不会挂上(dsh 拦不住 MCP 调用)。ACP 模式默认只有官方 DeepSeek 模型,要接别家模型可以在设置里填一个「额外的 patch 文件」。
|
|
42
43
|
- **多个飞书机器人**:设置 → 飞书 →「可用专家」直接勾选内置或共享专家,并选择「默认专家」。只勾一个共享专家即可专用,不用再勾选底层 Agent;每个人绑定自己的账号后,直接私聊就是这个专家,使用各自的记忆和工具。机器人能在 Web 上扫码创建(Lark 国际版用「手动添加」),改完配置立即生效,不用重启。
|
|
43
44
|
- 群聊里要 @ 机器人;不同话题是各自独立的会话;支持文字、富文本、图片、文件、语音和视频。
|
|
44
45
|
- 思考和工具调用显示在实时刷新的过程卡片里,最终回复是普通消息。
|
|
@@ -53,7 +54,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
|
|
|
53
54
|
- **回复里的相册**:agent 用 ```` ```album ```` JSON 描述多张本地照片,网页以大图轮播展示,可左右滑动、点击箭头或底部缩略图切换,按需加载照片;点开预览后支持左右切换、缩放、拖动、方向键和 Esc。可附名称、拍摄日期、说明和查询总数,每个相册最多 200 张;飞书显示简短摘要。写法自动附在所有专家的提示词里,图片沿用会话文件权限。
|
|
54
55
|
- 聊天右上角「更多」和侧栏会话右键菜单共用分叉、重命名、在飞书继续、删除操作,按会话类型和可用机器人显示。
|
|
55
56
|
- 语音输入:用浏览器自带的语音识别(Chrome / Edge / Safari,需要 HTTPS)。
|
|
56
|
-
- 语音对话(只有 Codex,包括 Codex 引擎的自定义专家):输入框里点声波按钮,和 Codex 桌面端的语音模式一样边说边聊,可以随时打断。输入框换成通话条(音量动画、状态、实时字幕、静音、结束);要动手的事语音模型会转交给这条对话里的 Codex,那一轮像发了一条消息一样出现在对话里(前面带 🎙️),授权卡照常弹。走 Codex 的实时语音(v3
|
|
57
|
+
- 语音对话(只有 Codex,包括 Codex 引擎的自定义专家):输入框里点声波按钮,和 Codex 桌面端的语音模式一样边说边聊,可以随时打断。输入框换成通话条(音量动画、状态、实时字幕、静音、结束);要动手的事语音模型会转交给这条对话里的 Codex,那一轮像发了一条消息一样出现在对话里(前面带 🎙️),授权卡照常弹。走 Codex 的实时语音(v3),用的是 Codex 登录的 ChatGPT 账号。声音经服务器中转:服务器自己和 OpenAI 建 WebRTC,浏览器和服务器之间走网页原有的 WebSocket,所以能打开网页的地方(反向代理、Cloudflare Tunnel)就能语音,手机不用直连 OpenAI。通话条上的齿轮里可以选音色和回答用的语言(记在这台设备上)。开通话前会把这条对话当前的权限和沙箱同步给 Codex,转交出来的轮次一样受限;机器上最近会话的启动背景只给内置 Codex 的管理员。需要 HTTPS 和麦克风权限;桌面端(Electron)里暂不提供。闲聊的字幕不存进聊天记录,切走对话或关掉页面会挂断。
|
|
57
58
|
- 新对话页:点大标题里的目录名,在固定高度的目录弹窗里逐层选工作目录,也能新建文件夹;输入框上方选专家,鼠标停在专家上看简介,右下角选模型和思考程度。对话从头到尾一个专家,要换专家就新建对话;模型和思考程度随时可换。
|
|
58
59
|
- 输入框里的小圆环显示上下文窗口占用;模型按钮显示实际的模型和思考程度(如「Opus 5.5 high」)。
|
|
59
60
|
- 滚动和 ChatGPT 一样:发出的问题顶到最上面、下面留白,回复长到屏幕底部才跟着往下滚;回复过程中自己滚动了就不再自动滚,下次发消息再恢复。
|
|
@@ -82,7 +83,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
|
|
|
82
83
|
- **授权**:允许一次 / 本会话全部允许 / 总是允许(按钮上写明放行范围)/ 拒绝。权限级别(输入框左下角或 `/permission`):逐次询问 / 自动改文件 / 自动判断(仅 Claude Code,由 Claude 逐个判断安不安全)/ 完全允许,定时任务也可以单独设,自动判断和完全允许只给管理员;默认级别在 设置 → Agent 里按引擎设。同一个弹窗里还有**计划模式**开关(或 `/planmode on`):agent 先只读、出方案,你点「开始执行」后再按权限级别动手。`/autoedit on` 让 Claude Code 在这条会话里改工作目录内的文件不再询问(Bash 仍询问)。超时一律按拒绝处理。
|
|
83
84
|
- **设置都在网页上**,按用途分组:**我的**(账号、飞书和微信绑定、自己的登录设备、记忆、专家、技能、MCP、用量);**Agent**(运行环境置顶,各 agent 卡片分别配置默认模型、思考程度、可选模型、个人默认技能和 MCP,Codex 沙箱、额度查询;工作目录、会话闲置过期、授权卡超时和 Claude 的「总是允许」名单;「/」命令);**连接**(飞书机器人、配对批准、指令面板同步;远程控制;服务器);**管理**(用户标题旁添加用户,用户的「管理 → 登录设备」查看和下线各自设备;系统页管理服务端版本和升级、重启、局域网访问和端口,网络访问下方是系统通知;成员也可在系统页设置自己的通知)。账号页通过「修改名称」「修改密码」按需展开表单;飞书和微信绑定操作位于卡片右上角。设置、新建 / 编辑专家、重命名等编辑弹窗不会因点击外部或按 Esc 关闭;通过关闭、取消或保存 / 完成按钮退出。改了没保存就切页或关掉设置会先提醒。
|
|
84
85
|
- **多用户**(信任型):管理员在 设置 → 用户 里给别人建账号。每个人只看得到自己的对话、授权和通知;个人设置各自管理,服务器设置由管理员修改,见下面「安全」。
|
|
85
|
-
- **专家**:设置 → 专家。专家是一份配置,新建对话、定时任务时选一个,对话从头到尾都是它(中途不能换;飞书里 `/expert 名字`、`/claude`、`/codex`、`/workbuddy`、`/pi` 换专家会开新会话)。**内置专家**:Claude Code、Codex,保留原装提示词和所有工具,默认技能与 MCP 在「设置 → Agent」中按账号、按引擎分别选择。**自定义专家**由创建者管理,可以勾选「共享给所有账号」。共享后,其他人能在网页、绑定账号后的飞书私聊和定时任务中选择它;只有创建者能修改设定。每个人在该专家的「我的工具」里选择自己的技能和 MCP,使用各自的变量、凭据、记忆和聊天记录;创建者沿用原有工具选择;其他人没配置过时,沿用创建者选的里面自己能用的(自己装了的技能、创建者共享出来的 MCP),创建者私有的 MCP 和机器 MCP 不会带给别人。取消共享后,其他人的历史对话保留,后续消息不能继续调用该专家,相关定时任务在下次运行时暂停。可以配:
|
|
86
|
+
- **专家**:设置 → 专家。专家是一份配置,新建对话、定时任务时选一个,对话从头到尾都是它(中途不能换;飞书里 `/expert 名字`、`/claude`、`/codex`、`/workbuddy`、`/pi`、`/dsh` 换专家会开新会话)。**内置专家**:Claude Code、Codex,保留原装提示词和所有工具,默认技能与 MCP 在「设置 → Agent」中按账号、按引擎分别选择。**自定义专家**由创建者管理,可以勾选「共享给所有账号」。共享后,其他人能在网页、绑定账号后的飞书私聊和定时任务中选择它;只有创建者能修改设定。每个人在该专家的「我的工具」里选择自己的技能和 MCP,使用各自的变量、凭据、记忆和聊天记录;创建者沿用原有工具选择;其他人没配置过时,沿用创建者选的里面自己能用的(自己装了的技能、创建者共享出来的 MCP),创建者私有的 MCP 和机器 MCP 不会带给别人。取消共享后,其他人的历史对话保留,后续消息不能继续调用该专家,相关定时任务在下次运行时暂停。可以配:
|
|
86
87
|
- 头像(点头像区域的加号上传;未上传时,会话中用引擎的图标)、引擎(Claude / Codex / pi,建好后不能换;pi 专家没有自带的联网搜索和读网页,要联网就给它挂搜索 MCP,也没有子智能体)、默认模型和思考程度(从模型列表里选);
|
|
87
88
|
- 提示词:人设、规则、输出格式。agent-loft 在后面自动补上这个专家能做什么、今天的日期、记忆。Claude 专家默认只用这段提示词(一句话约 2 千 token),也可以选「追加在 Claude Code 原装提示词后面」(干活更稳,每轮多约 1.6 万);pi 专家同样默认只用这段,也可以追加在 pi 原装提示词后面(每轮多约 600 token);Codex 的基础指令改不了,专家的提示词附在第一条消息后面,约束力弱一些;
|
|
88
89
|
- 权限,勾选:联网搜索、读网页,以及文件权限(一级包含一级):都不勾就是**只能联网**(不碰本机文件、不弹授权,文本附件内容直接放进消息)/**能读文件**/**能改文件**/**能跑命令**(跑命令就等于能改任何文件,需要授权时弹卡)。Claude 按权限给工具;Codex 按权限开 shell、apply_patch,沙箱只读或 workspace-write;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-loft",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.114",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
|
|
6
6
|
"keywords": [
|
|
@@ -58,9 +58,11 @@
|
|
|
58
58
|
"echarts": "^6.1.0",
|
|
59
59
|
"marked": "^16.0.0",
|
|
60
60
|
"mermaid": "^12.2.0",
|
|
61
|
+
"opusscript": "^0.1.1",
|
|
61
62
|
"qrcode": "^1.5.4",
|
|
62
63
|
"sharp": "^0.35.5",
|
|
63
64
|
"tsx": "^4.20.6",
|
|
65
|
+
"werift": "^0.27.0",
|
|
64
66
|
"ws": "^8.18.0"
|
|
65
67
|
},
|
|
66
68
|
"devDependencies": {
|
|
@@ -20,6 +20,7 @@ import type {
|
|
|
20
20
|
InteractionSpec,
|
|
21
21
|
InterruptOptions,
|
|
22
22
|
QuestionSpec,
|
|
23
|
+
RealtimeOptions,
|
|
23
24
|
RuntimeInfo,
|
|
24
25
|
SavedAttachment,
|
|
25
26
|
SessionOptions,
|
|
@@ -816,12 +817,12 @@ export class CodexSession implements AgentSession {
|
|
|
816
817
|
// ---------- 实时语音对话(thread/realtime/*,实验接口) ----------
|
|
817
818
|
|
|
818
819
|
/**
|
|
819
|
-
*
|
|
820
|
-
* 对端 answer 从 thread/realtime/sdp
|
|
820
|
+
* offer 是服务器这边的 WebRTC 端点(core/realtime-relay.ts)建的,app-server 去 OpenAI 建通话,
|
|
821
|
+
* 对端 answer 从 thread/realtime/sdp 通知回来。声音经服务器中转,浏览器那头走 WebSocket。
|
|
821
822
|
* 实测:ChatGPT 账号登录只能走 WebRTC(WebSocket 要 API key),协议版本要 v3。
|
|
822
823
|
* 语音模型把要干的活转交给这条 thread,app-server 自己开一轮(见 turn/started 里的 externalPending)。
|
|
823
824
|
*/
|
|
824
|
-
async startRealtime(offer: string): Promise<string> {
|
|
825
|
+
async startRealtime(offer: string, opts: RealtimeOptions = {}): Promise<string> {
|
|
825
826
|
if (this.disposed) throw new Error("会话已关闭");
|
|
826
827
|
if (this.rt) await this.stopRealtime();
|
|
827
828
|
const threadId = await this.open();
|
|
@@ -853,6 +854,7 @@ export class CodexSession implements AgentSession {
|
|
|
853
854
|
// 启动背景里有这台机器上最近的会话和目录结构:只给内置专家的管理员
|
|
854
855
|
includeStartupContext: !expert && this.opts.skills?.admin === true,
|
|
855
856
|
...(context ? { realtimeStartInstructions: context } : {}),
|
|
857
|
+
...realtimeVoiceParams(opts),
|
|
856
858
|
});
|
|
857
859
|
return await answer;
|
|
858
860
|
} catch (err) {
|
|
@@ -1336,6 +1338,32 @@ function kindMark(kind: unknown): string {
|
|
|
1336
1338
|
return k === "add" ? "+" : k === "delete" ? "-" : "~";
|
|
1337
1339
|
}
|
|
1338
1340
|
|
|
1341
|
+
/** v3 实时语音能用的音色(实测是 thread/realtime/listVoices 里 v1 那组,给 v2 的会报不支持;默认 cove) */
|
|
1342
|
+
export const REALTIME_VOICES = ["cove", "juniper", "maple", "spruce", "ember", "vale", "breeze", "arbor", "sol"] as const;
|
|
1343
|
+
|
|
1344
|
+
/**
|
|
1345
|
+
* 语音模型说哪种话:协议里没有语言参数,用 v3 的 initialItems 放一条 developer 指令。
|
|
1346
|
+
* 不在表里(或「自动」)就不加,跟着用户说的语言走
|
|
1347
|
+
*/
|
|
1348
|
+
export const REALTIME_LANGUAGES: Record<string, string> = {
|
|
1349
|
+
"zh-CN": "Always speak Mandarin Chinese (普通话) and use Simplified Chinese in any text, no matter what language the user speaks, unless the user explicitly asks you to switch languages.",
|
|
1350
|
+
"zh-TW": "Always speak Mandarin Chinese (國語) and use Traditional Chinese in any text, no matter what language the user speaks, unless the user explicitly asks you to switch languages.",
|
|
1351
|
+
yue: "Always speak Cantonese (粵語/廣東話), no matter what language the user speaks, unless the user explicitly asks you to switch languages.",
|
|
1352
|
+
en: "Always speak English, no matter what language the user speaks, unless the user explicitly asks you to switch languages.",
|
|
1353
|
+
ja: "Always speak Japanese (日本語), no matter what language the user speaks, unless the user explicitly asks you to switch languages.",
|
|
1354
|
+
ko: "Always speak Korean (한국어), no matter what language the user speaks, unless the user explicitly asks you to switch languages.",
|
|
1355
|
+
};
|
|
1356
|
+
|
|
1357
|
+
/** 页面选的音色、语言 → thread/realtime/start 的参数;认不出的忽略(用 Codex 默认) */
|
|
1358
|
+
export function realtimeVoiceParams(opts: RealtimeOptions): Record<string, unknown> {
|
|
1359
|
+
const voice = (REALTIME_VOICES as readonly string[]).includes(opts.voice ?? "") ? opts.voice : undefined;
|
|
1360
|
+
const language = opts.language ? REALTIME_LANGUAGES[opts.language] : undefined;
|
|
1361
|
+
return {
|
|
1362
|
+
...(voice ? { voice } : {}),
|
|
1363
|
+
...(language ? { initialItems: [{ role: "developer", text: language }] } : {}),
|
|
1364
|
+
};
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1339
1367
|
/** 语音转交的一轮没拿到用户说的话时显示的占位 */
|
|
1340
1368
|
const VOICE_FALLBACK = `${VOICE_MARK}(语音)`;
|
|
1341
1369
|
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// 和 `dsh --profile acp` 的连接:标准 ACP(Agent Client Protocol)v1,stdio 上按行分隔的 JSON-RPC。
|
|
2
|
+
//
|
|
3
|
+
// 为什么不用 SDK profile(--profile sdk):它没有中断当前回复、也没有关闭会话的方法(官方 README 写明),
|
|
4
|
+
// 停止按钮做不了。ACP 有 session/cancel,模型 / 思考程度、MCP、授权请求、会话列表 / 恢复也都齐。
|
|
5
|
+
//
|
|
6
|
+
// 一个 agent-loft 会话一个 dsh 进程:权限(沙箱档位)、追加的系统提示都只能在启动时给(环境变量和 --patch),
|
|
7
|
+
// 一个进程带多条会话就没法各配各的。代价是拉起要 4~5 秒,所以进程常驻、按需重拉。
|
|
8
|
+
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
9
|
+
import readline from "node:readline";
|
|
10
|
+
|
|
11
|
+
export type McpServer =
|
|
12
|
+
| { name: string; command: string; args: string[]; env: { name: string; value: string }[] }
|
|
13
|
+
| { type: "http"; name: string; url: string; headers: { name: string; value: string }[] };
|
|
14
|
+
|
|
15
|
+
export type ConfigOption = {
|
|
16
|
+
id: string;
|
|
17
|
+
name?: string;
|
|
18
|
+
category?: string;
|
|
19
|
+
type?: string;
|
|
20
|
+
currentValue?: string;
|
|
21
|
+
options?: ({ value: string; name?: string; description?: string } | { group?: string; name?: string; options: { value: string; name?: string; description?: string }[] })[];
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type SessionUpdate = { sessionUpdate: string; [k: string]: unknown };
|
|
25
|
+
|
|
26
|
+
export type PermissionRequest = {
|
|
27
|
+
sessionId: string;
|
|
28
|
+
toolCall: { toolCallId: string; title?: string; rawInput?: unknown; kind?: string };
|
|
29
|
+
options: { optionId: string; name?: string; kind: string }[];
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export type PermissionOutcome = { outcome: "selected"; optionId: string } | { outcome: "cancelled" };
|
|
33
|
+
|
|
34
|
+
export class AcpError extends Error {
|
|
35
|
+
constructor(
|
|
36
|
+
message: string,
|
|
37
|
+
readonly code?: number,
|
|
38
|
+
readonly data?: unknown,
|
|
39
|
+
) {
|
|
40
|
+
super(message);
|
|
41
|
+
this.name = "AcpError";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** stderr 只留最后这些行,给报错当线索 */
|
|
46
|
+
const STDERR_KEEP = 30;
|
|
47
|
+
|
|
48
|
+
export type AcpSpawn = { command: string; args: string[]; cwd: string; env: NodeJS.ProcessEnv };
|
|
49
|
+
|
|
50
|
+
export class AcpConnection {
|
|
51
|
+
private child: ChildProcessWithoutNullStreams;
|
|
52
|
+
private nextId = 1;
|
|
53
|
+
private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();
|
|
54
|
+
private stderr: string[] = [];
|
|
55
|
+
private closedWith: Error | null = null;
|
|
56
|
+
/** 会话更新:按会话 id 分发 */
|
|
57
|
+
onUpdate: (sessionId: string, update: SessionUpdate) => void = () => {};
|
|
58
|
+
/** dsh 要授权:返回选了哪个选项 */
|
|
59
|
+
onPermission: (req: PermissionRequest) => Promise<PermissionOutcome> = async () => ({ outcome: "cancelled" });
|
|
60
|
+
/** 进程退了(被杀、崩了、自己退出) */
|
|
61
|
+
onExit: (err: Error) => void = () => {};
|
|
62
|
+
|
|
63
|
+
constructor(spec: AcpSpawn) {
|
|
64
|
+
this.child = spawn(spec.command, spec.args, { cwd: spec.cwd, env: spec.env, stdio: ["pipe", "pipe", "pipe"] });
|
|
65
|
+
readline.createInterface({ input: this.child.stdout }).on("line", (line) => this.onLine(line));
|
|
66
|
+
readline.createInterface({ input: this.child.stderr }).on("line", (line) => {
|
|
67
|
+
this.stderr.push(line);
|
|
68
|
+
if (this.stderr.length > STDERR_KEEP) this.stderr.shift();
|
|
69
|
+
});
|
|
70
|
+
this.child.stdin.on("error", () => {});
|
|
71
|
+
this.child.on("error", (err) => this.close(err));
|
|
72
|
+
this.child.on("exit", (code, signal) => {
|
|
73
|
+
const tail = this.stderrTail();
|
|
74
|
+
this.close(new Error(`dsh 进程退出了(${signal ?? `退出码 ${code}`})${tail ? `:${tail}` : ""}`));
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
get alive(): boolean {
|
|
79
|
+
return !this.closedWith;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
stderrTail(lines = 5): string {
|
|
83
|
+
return this.stderr
|
|
84
|
+
.filter((l) => l.trim())
|
|
85
|
+
.slice(-lines)
|
|
86
|
+
.join("\n");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
private close(err: Error): void {
|
|
90
|
+
if (this.closedWith) return;
|
|
91
|
+
this.closedWith = err;
|
|
92
|
+
for (const p of this.pending.values()) p.reject(err);
|
|
93
|
+
this.pending.clear();
|
|
94
|
+
this.onExit(err);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
private write(msg: object): void {
|
|
98
|
+
if (this.closedWith) return;
|
|
99
|
+
this.child.stdin.write(`${JSON.stringify(msg)}\n`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
request<T = unknown>(method: string, params: unknown): Promise<T> {
|
|
103
|
+
if (this.closedWith) return Promise.reject(this.closedWith);
|
|
104
|
+
const id = this.nextId++;
|
|
105
|
+
return new Promise<T>((resolve, reject) => {
|
|
106
|
+
this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject });
|
|
107
|
+
this.write({ jsonrpc: "2.0", id, method, params });
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
notify(method: string, params: unknown): void {
|
|
112
|
+
this.write({ jsonrpc: "2.0", method, params });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private onLine(line: string): void {
|
|
116
|
+
if (!line.trim()) return;
|
|
117
|
+
let msg: { id?: number | string; method?: string; params?: unknown; result?: unknown; error?: { code?: number; message?: string; data?: unknown } };
|
|
118
|
+
try {
|
|
119
|
+
msg = JSON.parse(line);
|
|
120
|
+
} catch {
|
|
121
|
+
// stdout 只该有协议帧;混进来的别的输出(插件打日志)当 stderr 记下
|
|
122
|
+
this.stderr.push(line);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (msg.method && msg.id !== undefined) {
|
|
126
|
+
void this.onServerRequest(msg.id, msg.method, msg.params);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (msg.method) {
|
|
130
|
+
if (msg.method === "session/update") {
|
|
131
|
+
const p = msg.params as { sessionId?: string; update?: SessionUpdate } | undefined;
|
|
132
|
+
if (p?.sessionId && p.update) this.onUpdate(p.sessionId, p.update);
|
|
133
|
+
}
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (typeof msg.id !== "number") return;
|
|
137
|
+
const pending = this.pending.get(msg.id);
|
|
138
|
+
if (!pending) return;
|
|
139
|
+
this.pending.delete(msg.id);
|
|
140
|
+
if (msg.error) {
|
|
141
|
+
const details = (msg.error.data as { details?: unknown } | undefined)?.details;
|
|
142
|
+
const text = [msg.error.message, typeof details === "string" ? details : ""].filter(Boolean).join(":");
|
|
143
|
+
pending.reject(new AcpError(text || "dsh 返回了错误", msg.error.code, msg.error.data));
|
|
144
|
+
} else {
|
|
145
|
+
pending.resolve(msg.result);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private async onServerRequest(id: number | string, method: string, params: unknown): Promise<void> {
|
|
150
|
+
try {
|
|
151
|
+
if (method === "session/request_permission") {
|
|
152
|
+
const outcome = await this.onPermission(params as PermissionRequest);
|
|
153
|
+
this.write({ jsonrpc: "2.0", id, result: { outcome } });
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
// 没声明客户端文件系统 / 终端能力,正常不会来
|
|
157
|
+
this.write({ jsonrpc: "2.0", id, error: { code: -32601, message: `agent-loft 不支持 ${method}` } });
|
|
158
|
+
} catch (err) {
|
|
159
|
+
this.write({ jsonrpc: "2.0", id, error: { code: -32603, message: err instanceof Error ? err.message : String(err) } });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** 先关 stdin 让它自己收尾(会 flush 会话记录),几秒不退再杀 */
|
|
164
|
+
async shutdown(graceMs = 5000): Promise<void> {
|
|
165
|
+
if (this.closedWith) return;
|
|
166
|
+
const exited = new Promise<void>((resolve) => this.child.once("exit", () => resolve()));
|
|
167
|
+
try {
|
|
168
|
+
this.child.stdin.end();
|
|
169
|
+
} catch {
|
|
170
|
+
// 已经关了
|
|
171
|
+
}
|
|
172
|
+
const timer = setTimeout(() => this.child.kill("SIGTERM"), graceMs);
|
|
173
|
+
const hard = setTimeout(() => this.child.kill("SIGKILL"), graceMs + 3000);
|
|
174
|
+
await exited;
|
|
175
|
+
clearTimeout(timer);
|
|
176
|
+
clearTimeout(hard);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** ACP 的 initialize:只声明最小能力(不接管文件系统和终端,让 dsh 自己的沙箱管) */
|
|
181
|
+
export async function initialize(conn: AcpConnection): Promise<void> {
|
|
182
|
+
await conn.request("initialize", {
|
|
183
|
+
protocolVersion: 1,
|
|
184
|
+
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
|
185
|
+
clientInfo: { name: "agent-loft", version: "1" },
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 把配置选项(可能分组)摊平 */
|
|
190
|
+
export function flatOptions(opt: ConfigOption | undefined): { value: string; name?: string; description?: string }[] {
|
|
191
|
+
if (!opt?.options) return [];
|
|
192
|
+
return opt.options.flatMap((o) => ("options" in o && Array.isArray(o.options) ? o.options : [o as { value: string; name?: string; description?: string }]));
|
|
193
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// dsh 驱动:DeepSeek Harness(@deepseek-ai/dsh)的 ACP profile。
|
|
2
|
+
//
|
|
3
|
+
// 会话怎么跑见 session.ts;会话列表 / 历史是读 dsh 的记录文件(history.ts),ACP 的 session/list 不带标题和时间。
|
|
4
|
+
// 分叉、回退不支持:ACP 没有,dsh 的记录格式也没公开,自己拼一条新记录风险太大。
|
|
5
|
+
// 只做内置专家:原装提示词和工具,后面追加 agent-loft 的回复格式、记忆、技能说明,挂上记忆 / 定时任务 / 技能 MCP。
|
|
6
|
+
import type { AgentDriver, AgentEvents, AgentSession, CompleteRequest, HistoryMessage, InteractionHost, ModelInfo, RuntimeInfo, SessionOptions, SessionSummary } from "../../core/types.js";
|
|
7
|
+
import { config } from "../../core/config.js";
|
|
8
|
+
import { cachedProbe } from "../claude/probe.js";
|
|
9
|
+
import type { ConfigOption } from "./acp.js";
|
|
10
|
+
import { diagnose } from "./errors.js";
|
|
11
|
+
import { listSessionFiles, readHistoryFile, SESSION_ID, sessionFile, sessionTitleOf } from "./history.js";
|
|
12
|
+
import { modelsOf, modelValueOf, sweepPatches, withProbe } from "./sdk.js";
|
|
13
|
+
import { DshSession } from "./session.js";
|
|
14
|
+
|
|
15
|
+
const readCatalog = cachedProbe(10 * 60_000, "dsh 模型列表", () => withProbe(async (_c, _s, opts) => modelsOf(opts)));
|
|
16
|
+
|
|
17
|
+
/** 能恢复的会话:最后用的服务商 ACP profile 认得(模型列表里有它) */
|
|
18
|
+
async function knownProviders(): Promise<Set<string> | undefined> {
|
|
19
|
+
const models = await readCatalog().catch(() => [] as ModelInfo[]);
|
|
20
|
+
if (!models.length) return undefined;
|
|
21
|
+
return new Set(models.map((m) => m.id.slice(0, m.id.indexOf("/"))));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class DshDriver implements AgentDriver {
|
|
25
|
+
readonly id = "dsh";
|
|
26
|
+
readonly label = "dsh";
|
|
27
|
+
readonly capabilities = { effort: true, fork: false, cost: false, streaming: false };
|
|
28
|
+
|
|
29
|
+
async start(): Promise<void> {
|
|
30
|
+
sweepPatches();
|
|
31
|
+
}
|
|
32
|
+
async stop(): Promise<void> {}
|
|
33
|
+
|
|
34
|
+
createSession(opts: SessionOptions, events: AgentEvents, host: InteractionHost): AgentSession {
|
|
35
|
+
if (opts.expert) throw new Error("dsh 暂不支持自定义专家,请用内置的 dsh");
|
|
36
|
+
return new DshSession(opts, events, host);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async listSessions(cwd: string | undefined, limit = 10): Promise<SessionSummary[]> {
|
|
40
|
+
try {
|
|
41
|
+
return listSessionFiles(cwd, limit, await knownProviders());
|
|
42
|
+
} catch (err) {
|
|
43
|
+
console.error("[dsh] 读取会话列表失败:", err);
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async sessionExists(id: string): Promise<boolean> {
|
|
49
|
+
return SESSION_ID.test(id) && !!sessionFile(id);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async sessionTitle(id: string): Promise<string | undefined> {
|
|
53
|
+
return sessionTitleOf(id);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async readHistory(id: string): Promise<HistoryMessage[]> {
|
|
57
|
+
return readHistoryFile(id);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async listModels(session: AgentSession): Promise<ModelInfo[]> {
|
|
61
|
+
const models = await (session as DshSession).listModels().catch(() => [] as ModelInfo[]);
|
|
62
|
+
return models.length ? models : readCatalog();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
catalog(): Promise<ModelInfo[]> {
|
|
66
|
+
return readCatalog();
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async defaults(): Promise<RuntimeInfo> {
|
|
70
|
+
const c = config().agents.dsh;
|
|
71
|
+
if (c.defaultModel || c.defaultEffort) return { ...(c.defaultModel ? { model: c.defaultModel } : {}), ...(c.defaultEffort ? { effort: c.defaultEffort } : {}) };
|
|
72
|
+
const def = (await readCatalog().catch(() => [] as ModelInfo[])).find((m) => m.isDefault);
|
|
73
|
+
return def ? { model: def.id } : {};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async statusLines(): Promise<string[]> {
|
|
77
|
+
return [];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 后台整理记忆:临时进程、只读沙箱、拒绝一切授权,系统提示放在 dsh 原装提示后面,按 schema 出 JSON。
|
|
82
|
+
* 用完会话记录一起删(见 withProbe)
|
|
83
|
+
*/
|
|
84
|
+
async complete(req: CompleteRequest): Promise<unknown> {
|
|
85
|
+
const append = [
|
|
86
|
+
req.system,
|
|
87
|
+
"这是一次后台调用:不要用任何工具,直接回答。",
|
|
88
|
+
`只输出一个 JSON 对象(不要代码块、不要解释),符合这个 JSON Schema:\n${JSON.stringify(req.schema)}`,
|
|
89
|
+
].join("\n\n");
|
|
90
|
+
const run = withProbe(
|
|
91
|
+
async (conn, sessionId, opts) => {
|
|
92
|
+
const set = (configId: string, value: string) => conn.request("session/set_config_option", { sessionId, configId, value }).catch(() => {});
|
|
93
|
+
if (req.model) await set("model", modelValueOf(req.model));
|
|
94
|
+
if (opts.some((o: ConfigOption) => o.id === "reasoning_effort")) await set("reasoning_effort", "off");
|
|
95
|
+
const chunks: string[] = [];
|
|
96
|
+
conn.onUpdate = (sid, u) => {
|
|
97
|
+
const c = u.content as { type?: string; text?: string } | undefined;
|
|
98
|
+
if (sid === sessionId && u.sessionUpdate === "agent_message_chunk" && c?.type === "text" && c.text) chunks.push(c.text);
|
|
99
|
+
};
|
|
100
|
+
conn.onPermission = async (r) => {
|
|
101
|
+
const reject = r.options.find((o) => o.kind.startsWith("reject"));
|
|
102
|
+
return reject ? { outcome: "selected", optionId: reject.optionId } : { outcome: "cancelled" };
|
|
103
|
+
};
|
|
104
|
+
await conn.request("session/prompt", { sessionId, prompt: [{ type: "text", text: req.prompt }] });
|
|
105
|
+
const text = chunks.join("\n").trim();
|
|
106
|
+
const json = /\{[\s\S]*\}/.exec(text.replace(/^```(?:json)?\s*|\s*```$/g, ""))?.[0];
|
|
107
|
+
if (!json) throw new Error("dsh 没有返回 JSON");
|
|
108
|
+
return JSON.parse(json) as unknown;
|
|
109
|
+
},
|
|
110
|
+
{ append },
|
|
111
|
+
);
|
|
112
|
+
let timer: NodeJS.Timeout | undefined;
|
|
113
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
114
|
+
timer = setTimeout(() => reject(new Error("dsh 后台调用超时")), req.timeoutMs ?? 120_000);
|
|
115
|
+
});
|
|
116
|
+
try {
|
|
117
|
+
return await Promise.race([run, timeout]);
|
|
118
|
+
} finally {
|
|
119
|
+
clearTimeout(timer);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
diagnose(err: unknown) {
|
|
124
|
+
return diagnose(err);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// dsh 的报错翻译成人话(口径同 claude/errors.ts)
|
|
2
|
+
import type { Diagnosis } from "../../core/types.js";
|
|
3
|
+
|
|
4
|
+
const KEY_HINT = "在服务器上运行 dsh web,打开它的网页填 DeepSeek API Key;或者给 agent-loft 服务设 DEEPSEEK_API_KEY 环境变量。";
|
|
5
|
+
|
|
6
|
+
export function diagnose(err: unknown): Diagnosis {
|
|
7
|
+
const raw = err instanceof Error ? err.message : String(err);
|
|
8
|
+
const text = raw.toLowerCase();
|
|
9
|
+
if ((err as NodeJS.ErrnoException)?.code === "ENOENT" || text.includes("spawn dsh enoent") || text.includes("enoent")) {
|
|
10
|
+
return {
|
|
11
|
+
kind: "cli_missing",
|
|
12
|
+
chatMessage: "这台服务器上没找到 dsh,我暂时无法工作。请机器主人安装:npm install -g @deepseek-ai/dsh",
|
|
13
|
+
consoleHint: "找不到 dsh:npm install -g @deepseek-ai/dsh;以系统服务运行时 PATH 很短,在 设置 → Agent → dsh 里填绝对路径。",
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
if (text.includes("api key") || text.includes("api_key") || text.includes("401") || text.includes("unauthorized") || text.includes("authentication") || text.includes("credential")) {
|
|
17
|
+
return {
|
|
18
|
+
kind: "auth_missing",
|
|
19
|
+
chatMessage: "dsh 还没配 DeepSeek 的 API Key(或 Key 失效了),我暂时无法工作。\n请机器主人到 设置 → Agent → dsh 查看怎么配。",
|
|
20
|
+
consoleHint: `dsh 凭据有问题:${KEY_HINT}`,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
if (text.includes("insufficient balance") || text.includes("402") || text.includes("余额")) {
|
|
24
|
+
return { kind: "rate_limit", chatMessage: "DeepSeek 账户余额不足,充值后再试。", consoleHint: `DeepSeek 余额不足:${raw}` };
|
|
25
|
+
}
|
|
26
|
+
if (text.includes("rate limit") || text.includes("429") || text.includes("too many requests")) {
|
|
27
|
+
return { kind: "rate_limit", chatMessage: "DeepSeek 请求太频繁了,稍后再试,或者换个模型。", consoleHint: `dsh 限流:${raw}` };
|
|
28
|
+
}
|
|
29
|
+
if (text.includes("not resumable") || text.includes("no adapter registered")) {
|
|
30
|
+
return {
|
|
31
|
+
kind: "session_missing",
|
|
32
|
+
chatMessage: "这条 dsh 会话恢复不了(可能是在 dsh 网页里用别家模型建的,或者记录坏了)。发 /new 开个新会话吧。",
|
|
33
|
+
consoleHint: raw,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
if (text === "interrupted" || text.includes("cancelled") || text.includes("aborted")) {
|
|
37
|
+
return { kind: "turn_aborted", chatMessage: "这一轮已中断。", consoleHint: raw };
|
|
38
|
+
}
|
|
39
|
+
if (text.includes("dsh 进程退出")) {
|
|
40
|
+
return { kind: "unknown", chatMessage: `dsh 进程意外退出了,这一轮没有完成。再发一次会自动重新拉起。\n${raw.slice(0, 300)}`, consoleHint: raw };
|
|
41
|
+
}
|
|
42
|
+
return { kind: "unknown", chatMessage: `dsh 出错了:${raw.slice(0, 300)}`, consoleHint: raw };
|
|
43
|
+
}
|