agent-loft 0.2.111 → 0.2.113
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 +6 -3
- package/package.json +1 -1
- package/src/agents/codex/protocol.ts +10 -0
- package/src/agents/codex/session.ts +201 -5
- 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/experts-api.ts +1 -0
- package/src/channels/web/server.ts +28 -1
- 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/expert-prompt.ts +15 -0
- package/src/core/experts.ts +22 -3
- package/src/core/hub.ts +60 -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/types.ts +19 -0
- package/src/core/users.ts +1 -1
- package/src/main.ts +5 -1
- package/web/css/composer.css +164 -0
- package/web/css/experts.css +66 -0
- package/web/lib/dom.js +2 -0
- package/web/lib/ws.js +4 -0
- 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 +86 -17
- package/web/settings/memory.js +2 -1
- package/web/views/composer.js +3 -1
- package/web/views/messages.js +1 -1
- package/web/views/sidebar.js +1 -1
- package/web/views/topbar.js +3 -1
- package/web/views/voice-call.js +293 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// DeepSeek Harness(dsh,@deepseek-ai/dsh):怎么拉起、数据在哪、模型 id 怎么换算。
|
|
2
|
+
//
|
|
3
|
+
// dsh 是全局装的 npm 命令(npm i -g @deepseek-ai/dsh),不随 agent-loft 安装。数据都在 DSH_HOME(默认 ~/.dsh):
|
|
4
|
+
// .credentials.yaml 凭据(DEEPSEEK_API_KEY 等,dsh web 里填的)
|
|
5
|
+
// sessions/<目录编码>/<会话 id>/session.v4.jsonl.zstd 会话记录(见 history.ts)
|
|
6
|
+
// profiles/acp/ ACP profile,第一次用时 dsh 自己从模板建
|
|
7
|
+
//
|
|
8
|
+
// 每个会话一个 `dsh --profile acp` 进程。按会话不同的东西都在启动时给:
|
|
9
|
+
// DSH_PERMISSION_MODE 沙箱档位(read-only / workspace-write / danger-full-access),见 modeOf
|
|
10
|
+
// --patch <文件> 追加的系统提示(system-prompt.personaSuffix)、成员不加载机器技能
|
|
11
|
+
import crypto from "node:crypto";
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import os from "node:os";
|
|
14
|
+
import path from "node:path";
|
|
15
|
+
import { agentEnvironment } from "../../core/agent-env.js";
|
|
16
|
+
import { config } from "../../core/config.js";
|
|
17
|
+
import type { PermissionLevel } from "../../core/permission.js";
|
|
18
|
+
import type { ModelInfo } from "../../core/types.js";
|
|
19
|
+
import { dataDir } from "../../home.js";
|
|
20
|
+
import { AcpConnection, flatOptions, initialize, type AcpSpawn, type ConfigOption } from "./acp.js";
|
|
21
|
+
|
|
22
|
+
export function dshHome(): string {
|
|
23
|
+
const c = config().agents.dsh;
|
|
24
|
+
return c.home || process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function sessionsRoot(): string {
|
|
28
|
+
return path.join(dshHome(), "sessions");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 级别 → dsh 的权限预设。不给 = dsh 默认(工作区可写,越界才问) */
|
|
32
|
+
export function modeOf(level: PermissionLevel | undefined, plan?: boolean): "read-only" | "workspace-write" | "danger-full-access" {
|
|
33
|
+
if (plan || level === "ask") return "read-only";
|
|
34
|
+
if (level === "full") return "danger-full-access";
|
|
35
|
+
return "workspace-write";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 每个进程的 --patch 文件放这里,进程退了就删 */
|
|
39
|
+
const PATCH_DIR = path.join(dataDir, "dsh");
|
|
40
|
+
|
|
41
|
+
export type LaunchSpec = {
|
|
42
|
+
cwd: string;
|
|
43
|
+
mode: ReturnType<typeof modeOf>;
|
|
44
|
+
/** 追加在 dsh 系统提示后面 */
|
|
45
|
+
append?: string;
|
|
46
|
+
/** 成员:不加载机器上的技能 */
|
|
47
|
+
noMachineSkills?: boolean;
|
|
48
|
+
env?: Record<string, string>;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/** 生成启动参数;返回的 cleanup 删掉临时 patch 文件 */
|
|
52
|
+
export function launchSpec(spec: LaunchSpec): { spawn: AcpSpawn; cleanup: () => void } {
|
|
53
|
+
const c = config().agents.dsh;
|
|
54
|
+
const args = ["--profile", "acp"];
|
|
55
|
+
if (c.patch) args.push("--patch", c.patch);
|
|
56
|
+
// YAML 是 JSON 的超集,直接写 JSON,免得自己转义
|
|
57
|
+
const entries: object[] = [];
|
|
58
|
+
if (spec.append) {
|
|
59
|
+
// personaSuffix 是模板,{{model}} 这类会被替换:拆开花括号
|
|
60
|
+
const suffix = spec.append.replace(/\{\{/g, "{ {").replace(/\}\}/g, "} }");
|
|
61
|
+
entries.push({ id: "system-prompt", config: { personaPrefix: "You are a coding agent powered by the {{model}} model.", personaSuffix: suffix } });
|
|
62
|
+
}
|
|
63
|
+
if (spec.noMachineSkills) entries.push({ id: "skill-filesystem", disabled: true });
|
|
64
|
+
let file: string | undefined;
|
|
65
|
+
if (entries.length) {
|
|
66
|
+
fs.mkdirSync(PATCH_DIR, { recursive: true, mode: 0o700 });
|
|
67
|
+
file = path.join(PATCH_DIR, `patch-${process.pid}-${crypto.randomBytes(6).toString("hex")}.yml`);
|
|
68
|
+
fs.writeFileSync(file, JSON.stringify(entries, null, 2), { mode: 0o600 });
|
|
69
|
+
args.push("--patch", file);
|
|
70
|
+
}
|
|
71
|
+
const env: NodeJS.ProcessEnv = {
|
|
72
|
+
...agentEnvironment(process.env),
|
|
73
|
+
...(spec.env ?? {}),
|
|
74
|
+
DSH_PERMISSION_MODE: spec.mode,
|
|
75
|
+
...(c.home ? { DSH_HOME: c.home } : {}),
|
|
76
|
+
};
|
|
77
|
+
return {
|
|
78
|
+
spawn: { command: c.path || "dsh", args, cwd: spec.cwd, env },
|
|
79
|
+
cleanup: () => {
|
|
80
|
+
if (file) fs.rmSync(file, { force: true });
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 上次异常退出留下的 patch 文件 */
|
|
86
|
+
export function sweepPatches(): void {
|
|
87
|
+
try {
|
|
88
|
+
for (const n of fs.readdirSync(PATCH_DIR)) if (n.startsWith("patch-")) fs.rmSync(path.join(PATCH_DIR, n), { force: true });
|
|
89
|
+
} catch {
|
|
90
|
+
// 目录还没有
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ---------- 模型 ----------
|
|
95
|
+
|
|
96
|
+
/** ACP 的模型选项值是 JSON 数组字符串 ["provider","model"];agent-loft 里用 provider/model */
|
|
97
|
+
export function modelIdOf(value: string): string | undefined {
|
|
98
|
+
try {
|
|
99
|
+
const v = JSON.parse(value) as unknown;
|
|
100
|
+
if (Array.isArray(v) && typeof v[0] === "string" && typeof v[1] === "string") return `${v[0]}/${v[1]}`;
|
|
101
|
+
} catch {
|
|
102
|
+
// 不是数组
|
|
103
|
+
}
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function modelValueOf(id: string): string {
|
|
108
|
+
const i = id.indexOf("/");
|
|
109
|
+
// 只写了模型名:按官方 DeepSeek 算
|
|
110
|
+
return i < 0 ? JSON.stringify(["deepseek-official", id]) : JSON.stringify([id.slice(0, i), id.slice(i + 1)]);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 从 session/new 返回的配置选项里读出模型列表 */
|
|
114
|
+
export function modelsOf(opts: ConfigOption[]): ModelInfo[] {
|
|
115
|
+
const model = opts.find((o) => o.id === "model");
|
|
116
|
+
const effort = opts.find((o) => o.id === "reasoning_effort");
|
|
117
|
+
const efforts = flatOptions(effort).map((o) => o.value);
|
|
118
|
+
const out: ModelInfo[] = [];
|
|
119
|
+
for (const o of flatOptions(model)) {
|
|
120
|
+
const id = modelIdOf(o.value);
|
|
121
|
+
if (!id) continue;
|
|
122
|
+
out.push({
|
|
123
|
+
id,
|
|
124
|
+
label: o.name || id,
|
|
125
|
+
...(o.description ? { description: o.description } : {}),
|
|
126
|
+
...(efforts.length ? { efforts } : {}),
|
|
127
|
+
...(o.value === model?.currentValue ? { isDefault: true } : {}),
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 当前选中的模型 / 思考程度 */
|
|
134
|
+
export function runtimeOf(opts: ConfigOption[]): { model?: string; effort?: string } {
|
|
135
|
+
const model = opts.find((o) => o.id === "model")?.currentValue;
|
|
136
|
+
const effort = opts.find((o) => o.id === "reasoning_effort")?.currentValue;
|
|
137
|
+
const id = model ? modelIdOf(model) : undefined;
|
|
138
|
+
return { ...(id ? { model: id } : {}), ...(effort ? { effort } : {}) };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ---------- 一次性的探测进程 ----------
|
|
142
|
+
|
|
143
|
+
/** 探测用的工作目录:建出来的会话事后删掉,不进会话列表 */
|
|
144
|
+
const PROBE_CWD = path.join(os.tmpdir(), "agent-loft-dsh-probe");
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* 拉一个临时进程、建一个临时会话,交给 fn 用完就关、连会话记录一起删。
|
|
148
|
+
* 模型列表、后台整理记忆都走这里(ACP 没有不建会话就能问的接口)
|
|
149
|
+
*/
|
|
150
|
+
export async function withProbe<T>(
|
|
151
|
+
fn: (conn: AcpConnection, sessionId: string, options: ConfigOption[]) => Promise<T>,
|
|
152
|
+
launch: Partial<LaunchSpec> = {},
|
|
153
|
+
): Promise<T> {
|
|
154
|
+
fs.mkdirSync(PROBE_CWD, { recursive: true });
|
|
155
|
+
const { spawn, cleanup } = launchSpec({ cwd: PROBE_CWD, mode: "read-only", ...launch });
|
|
156
|
+
const conn = new AcpConnection(spawn);
|
|
157
|
+
let sessionId: string | undefined;
|
|
158
|
+
try {
|
|
159
|
+
await initialize(conn);
|
|
160
|
+
const res = await conn.request<{ sessionId: string; configOptions?: ConfigOption[] }>("session/new", { cwd: PROBE_CWD, mcpServers: [] });
|
|
161
|
+
sessionId = res.sessionId;
|
|
162
|
+
return await fn(conn, sessionId, res.configOptions ?? []);
|
|
163
|
+
} finally {
|
|
164
|
+
if (sessionId) await conn.request("session/close", { sessionId }).catch(() => {});
|
|
165
|
+
await conn.shutdown(3000).catch(() => {});
|
|
166
|
+
cleanup();
|
|
167
|
+
if (sessionId) removeSession(sessionId);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** 删掉一条会话的记录目录(只给探测用的临时会话用) */
|
|
172
|
+
function removeSession(id: string): void {
|
|
173
|
+
if (!/^[A-Za-z0-9_-]{8,80}$/.test(id)) return;
|
|
174
|
+
let dirs: string[] = [];
|
|
175
|
+
try {
|
|
176
|
+
dirs = fs.readdirSync(sessionsRoot());
|
|
177
|
+
} catch {
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
for (const d of dirs) {
|
|
181
|
+
const dir = path.join(sessionsRoot(), d, id);
|
|
182
|
+
if (!fs.existsSync(dir)) continue;
|
|
183
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
184
|
+
// 探测目录下没别的会话了:目录也删掉
|
|
185
|
+
try {
|
|
186
|
+
fs.rmdirSync(path.join(sessionsRoot(), d));
|
|
187
|
+
} catch {
|
|
188
|
+
// 不空
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
// 一条会话 ↔ 一个常驻的 `dsh --profile acp` 进程(见 acp.ts 开头为什么不共用进程)。
|
|
2
|
+
//
|
|
3
|
+
// 消息先在本地排队,上一轮的 session/prompt 返回了才发下一条 —— 停止时排着的能一起丢掉(和 Claude 一样)。
|
|
4
|
+
// 权限级别、计划模式、追加的系统提示都是启动参数:运行中改了,闲下来就关掉进程,下一条消息带着会话 id 重拉(session/resume)。
|
|
5
|
+
//
|
|
6
|
+
// ACP 没有的东西:
|
|
7
|
+
// - 提问卡(elicitation):系统提示里告诉模型直接在回复里问
|
|
8
|
+
// - 调用 MCP 前询问:dsh 的授权只管沙箱越界,拦不住 MCP 调用,所以设成「调用前询问」的 MCP 不挂
|
|
9
|
+
// - 逐字流式:dsh 一条助手消息说完才推过来
|
|
10
|
+
// - 每轮 token 用量:一轮结束后从会话记录里加出来(history.ts 的 lastTurnUsage)
|
|
11
|
+
import { RICH_REPLY_LINES } from "../../core/expert-prompt.js";
|
|
12
|
+
import { MEMORY_MCP_NAME, memoryMcpSpawn } from "../../core/memory-mcp.js";
|
|
13
|
+
import type { PermissionLevel } from "../../core/permission.js";
|
|
14
|
+
import { codexSkillLines } from "../../core/skill-runtime.js";
|
|
15
|
+
import { SKILLS_MCP_NAME, skillsMcpSpawn, TASKS_MCP_NAME, tasksMcpSpawn } from "../../core/tasks-mcp.js";
|
|
16
|
+
import type {
|
|
17
|
+
AgentEvents,
|
|
18
|
+
AgentSession,
|
|
19
|
+
InteractionHost,
|
|
20
|
+
InterruptOptions,
|
|
21
|
+
ModelInfo,
|
|
22
|
+
RuntimeInfo,
|
|
23
|
+
SessionOptions,
|
|
24
|
+
UserInput,
|
|
25
|
+
} from "../../core/types.js";
|
|
26
|
+
import { describeAttachments } from "../../core/uploads.js";
|
|
27
|
+
import { summarize } from "../claude/session.js";
|
|
28
|
+
import { TodoTracker } from "../claude/todos.js";
|
|
29
|
+
import { AcpConnection, initialize, type ConfigOption, type McpServer, type PermissionOutcome, type PermissionRequest, type SessionUpdate } from "./acp.js";
|
|
30
|
+
import { lastTurnUsage, readEvents, sessionFile } from "./history.js";
|
|
31
|
+
import { launchSpec, modelsOf, modelValueOf, modeOf, runtimeOf } from "./sdk.js";
|
|
32
|
+
import { describeDshStep, todoName } from "./steps.js";
|
|
33
|
+
import { resolveCommand } from "./which.js";
|
|
34
|
+
|
|
35
|
+
/** 计划模式:dsh 的计划模式 ACP 切不了,用只读沙箱 + 提示词代替 */
|
|
36
|
+
const PLAN_LINES = [
|
|
37
|
+
"## 计划模式(agent-loft)",
|
|
38
|
+
"",
|
|
39
|
+
"现在是计划模式:只读、只出方案。可以读文件、搜索、跑只读命令来摸清情况,但不要改任何文件、不要提交,也不要申请越过沙箱。",
|
|
40
|
+
"把完整方案(目标、要改哪些地方、步骤、风险、怎么验证)写在回复里,然后停下来等用户批准;用户关掉计划模式后才动手。",
|
|
41
|
+
];
|
|
42
|
+
|
|
43
|
+
/** 内置专家追加在 dsh 原装提示后面的:回复格式、记忆、技能说明、这里用不了的工具 */
|
|
44
|
+
export function appendPrompt(opts: SessionOptions): string {
|
|
45
|
+
return [
|
|
46
|
+
RICH_REPLY_LINES.join("\n"),
|
|
47
|
+
"ask_user_question 工具在这里用不了(没有提问界面):需要用户拿主意时,直接在回复里问,然后结束这一轮。",
|
|
48
|
+
opts.memory?.prompt,
|
|
49
|
+
codexSkillLines(opts.skills).join("\n"),
|
|
50
|
+
opts.plan ? PLAN_LINES.join("\n") : "",
|
|
51
|
+
]
|
|
52
|
+
.filter(Boolean)
|
|
53
|
+
.join("\n\n");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function pairs(rec: Record<string, string> | undefined): { name: string; value: string }[] {
|
|
57
|
+
return Object.entries(rec ?? {}).map(([name, value]) => ({ name, value }));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** 记忆 / 定时任务 / 技能 MCP,加上个人选的 MCP。返回挂上的和没挂的(「调用前询问」、SSE、找不到命令) */
|
|
61
|
+
export function mcpServersOf(opts: SessionOptions): { servers: McpServer[]; skipped: string[] } {
|
|
62
|
+
const servers: McpServer[] = [];
|
|
63
|
+
const skipped: string[] = [];
|
|
64
|
+
const stdio = (name: string, spec: { command: string; args: string[]; env?: Record<string, string> }) =>
|
|
65
|
+
servers.push({ name, command: spec.command, args: spec.args, env: pairs(spec.env) });
|
|
66
|
+
if (opts.memory) stdio(MEMORY_MCP_NAME, memoryMcpSpawn(opts.memory.userId, "dsh", { search: !!opts.memory.search, ...(opts.memory.convKey ? { convKey: opts.memory.convKey } : {}) }));
|
|
67
|
+
if (opts.tasks) {
|
|
68
|
+
stdio(TASKS_MCP_NAME, tasksMcpSpawn(opts.tasks.userId, opts.tasks.convKey, "dsh"));
|
|
69
|
+
stdio(SKILLS_MCP_NAME, skillsMcpSpawn(opts.tasks.userId, opts.tasks.convKey, "dsh"));
|
|
70
|
+
}
|
|
71
|
+
const builtin = opts.builtinMcp;
|
|
72
|
+
for (const [name, spec] of Object.entries(builtin?.mcp ?? {})) {
|
|
73
|
+
if (builtin!.askMcp.includes(name) || spec.type === "sse") {
|
|
74
|
+
skipped.push(name);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (spec.type === "http") {
|
|
78
|
+
servers.push({ type: "http", name, url: spec.url, headers: pairs(spec.headers) });
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
// ACP 要求绝对路径
|
|
82
|
+
const command = resolveCommand(spec.command, spec.env?.PATH);
|
|
83
|
+
if (!command) {
|
|
84
|
+
skipped.push(name);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
stdio(name, { command, args: spec.args, env: spec.env });
|
|
88
|
+
}
|
|
89
|
+
return { servers, skipped };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function settle(outcome: { settlement: string }): "allow" | "session" | "deny" {
|
|
93
|
+
if (outcome.settlement === "allow-session") return "session";
|
|
94
|
+
if (outcome.settlement === "allow-once" || outcome.settlement === "allow-always") return "allow";
|
|
95
|
+
return "deny";
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
type Tracked = { name: string; input: Record<string, unknown> };
|
|
99
|
+
|
|
100
|
+
export class DshSession implements AgentSession {
|
|
101
|
+
private conn: AcpConnection | null = null;
|
|
102
|
+
private cleanup: (() => void) | null = null;
|
|
103
|
+
private starting: Promise<AcpConnection | null> | null = null;
|
|
104
|
+
/** 正在跑的进程是按哪种沙箱 / 提示词拉起的:和 opts 对不上了就该重拉 */
|
|
105
|
+
private launchedKey = "";
|
|
106
|
+
private currentId: string | undefined;
|
|
107
|
+
private runtime: RuntimeInfo = {};
|
|
108
|
+
private options: ConfigOption[] = [];
|
|
109
|
+
private disposed = false;
|
|
110
|
+
private turnBusy = false;
|
|
111
|
+
private pending: UserInput[] = [];
|
|
112
|
+
private allowAll = false;
|
|
113
|
+
private todos = new TodoTracker();
|
|
114
|
+
private tools = new Map<string, Tracked>();
|
|
115
|
+
private turn: Promise<void> | null = null;
|
|
116
|
+
/** 这一轮说过的话、最后一条助手消息的 id */
|
|
117
|
+
private turnText: string[] = [];
|
|
118
|
+
private lastMessageId: string | undefined;
|
|
119
|
+
private warnedSkipped = false;
|
|
120
|
+
|
|
121
|
+
constructor(
|
|
122
|
+
private readonly opts: SessionOptions,
|
|
123
|
+
private readonly events: AgentEvents,
|
|
124
|
+
private readonly host: InteractionHost,
|
|
125
|
+
) {
|
|
126
|
+
if (opts.fork) throw new Error("dsh 不支持分叉会话");
|
|
127
|
+
this.currentId = opts.resumeId;
|
|
128
|
+
this.allowAll = opts.permission === "full";
|
|
129
|
+
this.runtime = { ...(opts.model ? { model: opts.model } : {}), ...(opts.effort ? { effort: opts.effort } : {}) };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
get sessionId(): string | undefined {
|
|
133
|
+
return this.currentId;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
private wantedKey(): string {
|
|
137
|
+
return JSON.stringify([modeOf(this.opts.permission, this.opts.plan), appendPrompt(this.opts)]);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
private start(): Promise<AcpConnection | null> {
|
|
141
|
+
if (this.conn?.alive && this.launchedKey === this.wantedKey()) return Promise.resolve(this.conn);
|
|
142
|
+
if (this.disposed) return Promise.resolve(null);
|
|
143
|
+
this.starting ??= (async () => {
|
|
144
|
+
if (this.conn) await this.stopProcess();
|
|
145
|
+
return this.launch();
|
|
146
|
+
})().finally(() => {
|
|
147
|
+
this.starting = null;
|
|
148
|
+
});
|
|
149
|
+
return this.starting;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
private async launch(): Promise<AcpConnection | null> {
|
|
153
|
+
const key = this.wantedKey();
|
|
154
|
+
const skills = this.opts.skills;
|
|
155
|
+
const { spawn, cleanup } = launchSpec({
|
|
156
|
+
cwd: this.opts.cwd,
|
|
157
|
+
mode: modeOf(this.opts.permission, this.opts.plan),
|
|
158
|
+
append: appendPrompt(this.opts),
|
|
159
|
+
// 成员不加载机器上的技能(和别的 agent 一致)
|
|
160
|
+
noMachineSkills: !!skills && !(skills.admin && skills.machineSkills !== false),
|
|
161
|
+
env: skills?.env ?? {},
|
|
162
|
+
});
|
|
163
|
+
const conn = new AcpConnection(spawn);
|
|
164
|
+
conn.onUpdate = (sid, u) => {
|
|
165
|
+
if (sid === this.currentId) this.handle(u);
|
|
166
|
+
};
|
|
167
|
+
conn.onPermission = (req) => this.permission(req);
|
|
168
|
+
conn.onExit = () => {
|
|
169
|
+
cleanup();
|
|
170
|
+
if (this.conn === conn) this.conn = null;
|
|
171
|
+
};
|
|
172
|
+
try {
|
|
173
|
+
await initialize(conn);
|
|
174
|
+
const { servers, skipped } = mcpServersOf(this.opts);
|
|
175
|
+
if (skipped.length && !this.warnedSkipped) {
|
|
176
|
+
this.warnedSkipped = true;
|
|
177
|
+
this.events.onStep("warning", `⚠️ dsh 不支持调用前询问 / SSE 的 MCP,没挂上:${skipped.join("、")}`);
|
|
178
|
+
}
|
|
179
|
+
let res: { sessionId?: string; configOptions?: ConfigOption[] } | null;
|
|
180
|
+
if (this.currentId) {
|
|
181
|
+
res = await conn.request("session/resume", { sessionId: this.currentId, cwd: this.opts.cwd, mcpServers: servers });
|
|
182
|
+
} else {
|
|
183
|
+
res = await conn.request("session/new", { cwd: this.opts.cwd, mcpServers: servers });
|
|
184
|
+
if (!res?.sessionId) throw new Error("dsh 没有返回会话 id");
|
|
185
|
+
this.currentId = res.sessionId;
|
|
186
|
+
this.events.onSessionId(res.sessionId);
|
|
187
|
+
}
|
|
188
|
+
if (this.disposed) {
|
|
189
|
+
await conn.shutdown().catch(() => {});
|
|
190
|
+
cleanup();
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
this.conn = conn;
|
|
194
|
+
this.cleanup = cleanup;
|
|
195
|
+
this.launchedKey = key;
|
|
196
|
+
if (res?.configOptions) this.applyOptions(res.configOptions);
|
|
197
|
+
await this.applyRuntime(conn);
|
|
198
|
+
return conn;
|
|
199
|
+
} catch (err) {
|
|
200
|
+
await conn.shutdown(1000).catch(() => {});
|
|
201
|
+
cleanup();
|
|
202
|
+
throw err;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private async stopProcess(): Promise<void> {
|
|
207
|
+
const conn = this.conn;
|
|
208
|
+
this.conn = null;
|
|
209
|
+
if (!conn) return;
|
|
210
|
+
if (this.currentId) await conn.request("session/close", { sessionId: this.currentId }).catch(() => {});
|
|
211
|
+
await conn.shutdown().catch(() => {});
|
|
212
|
+
this.cleanup?.();
|
|
213
|
+
this.cleanup = null;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
private applyOptions(opts: ConfigOption[]): void {
|
|
217
|
+
this.options = opts;
|
|
218
|
+
this.runtime = { ...this.runtime, ...runtimeOf(opts) };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** 把选好的模型 / 思考程度设进去(新建、恢复、重拉之后都要设一次) */
|
|
222
|
+
private async applyRuntime(conn: AcpConnection): Promise<void> {
|
|
223
|
+
if (!this.currentId) return;
|
|
224
|
+
const cur = runtimeOf(this.options);
|
|
225
|
+
const set = async (configId: string, value: string) => {
|
|
226
|
+
const r = await conn.request<{ configOptions?: ConfigOption[] }>("session/set_config_option", { sessionId: this.currentId, configId, value });
|
|
227
|
+
if (r?.configOptions) this.applyOptions(r.configOptions);
|
|
228
|
+
};
|
|
229
|
+
if (this.opts.model && this.opts.model !== cur.model) await set("model", modelValueOf(this.opts.model));
|
|
230
|
+
if (this.opts.effort && this.opts.effort !== runtimeOf(this.options).effort) {
|
|
231
|
+
await set("reasoning_effort", this.opts.effort).catch((err) => this.events.onStep("warning", `⚠️ 思考程度没设上:${err instanceof Error ? err.message : err}`));
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// ---------- 收消息 ----------
|
|
236
|
+
|
|
237
|
+
private handle(u: SessionUpdate): void {
|
|
238
|
+
switch (u.sessionUpdate) {
|
|
239
|
+
case "agent_message_chunk": {
|
|
240
|
+
const c = u.content as { type?: string; text?: string } | undefined;
|
|
241
|
+
if (c?.type !== "text" || !c.text) return;
|
|
242
|
+
if (typeof u.messageId === "string") this.lastMessageId = u.messageId;
|
|
243
|
+
this.turnText.push(c.text);
|
|
244
|
+
this.events.onText(c.text);
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
case "agent_thought_chunk": {
|
|
248
|
+
const c = u.content as { type?: string; text?: string } | undefined;
|
|
249
|
+
const t = c?.text ? summarize(c.text) : "";
|
|
250
|
+
if (t) this.events.onStep("thinking", `💭 ${t}`);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
case "tool_call": {
|
|
254
|
+
const id = typeof u.toolCallId === "string" ? u.toolCallId : "";
|
|
255
|
+
const name = typeof u.title === "string" ? u.title : "tool";
|
|
256
|
+
const input = u.rawInput && typeof u.rawInput === "object" ? (u.rawInput as Record<string, unknown>) : {};
|
|
257
|
+
if (id) this.tools.set(id, { name, input });
|
|
258
|
+
const todo = this.todos.use(todoName(name), input, id);
|
|
259
|
+
if (todo) {
|
|
260
|
+
this.events.onStep("tool", todo.step);
|
|
261
|
+
if (todo.changed) this.events.onTodos?.(this.todos.list);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
this.events.onStep("tool", `🔧 ${describeDshStep(name, input)}`);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
case "usage_update": {
|
|
268
|
+
const used = Number(u.used);
|
|
269
|
+
const size = Number(u.size);
|
|
270
|
+
if (used > 0 && size > 0) this.events.onContext?.({ used, window: size, percent: Math.round((used / size) * 1000) / 10 });
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
case "config_option_update": {
|
|
274
|
+
if (Array.isArray(u.configOptions)) this.applyOptions(u.configOptions as ConfigOption[]);
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// ---------- 授权 ----------
|
|
281
|
+
|
|
282
|
+
private async permission(req: PermissionRequest): Promise<PermissionOutcome> {
|
|
283
|
+
const allow = req.options.find((o) => o.kind === "allow_once") ?? req.options.find((o) => o.kind.startsWith("allow"));
|
|
284
|
+
const reject = req.options.find((o) => o.kind === "reject_once") ?? req.options.find((o) => o.kind.startsWith("reject"));
|
|
285
|
+
if (req.sessionId !== this.currentId || this.disposed) return { outcome: "cancelled" };
|
|
286
|
+
if (allow && this.allowAll && !this.opts.plan) return { outcome: "selected", optionId: allow.optionId };
|
|
287
|
+
const tool = this.tools.get(req.toolCall.toolCallId);
|
|
288
|
+
const name = tool?.name ?? req.toolCall.title ?? "操作";
|
|
289
|
+
const input = tool?.input ?? (req.toolCall.rawInput as Record<string, unknown> | undefined) ?? {};
|
|
290
|
+
const outcome = await this.host({
|
|
291
|
+
kind: "approval",
|
|
292
|
+
title: `需要授权:${name}`,
|
|
293
|
+
detail: describePermission(name, input),
|
|
294
|
+
...(!this.opts.noSessionGrant ? { allowSession: true } : {}),
|
|
295
|
+
});
|
|
296
|
+
const s = settle(outcome);
|
|
297
|
+
if (s === "session") {
|
|
298
|
+
if (!this.allowAll) this.events.onStep("warning", "🔓 本会话内后续操作不再询问(/new 或切换会话后恢复逐条确认)");
|
|
299
|
+
this.allowAll = true;
|
|
300
|
+
}
|
|
301
|
+
if (s !== "deny" && allow) return { outcome: "selected", optionId: allow.optionId };
|
|
302
|
+
return reject ? { outcome: "selected", optionId: reject.optionId } : { outcome: "cancelled" };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ---------- 一轮 ----------
|
|
306
|
+
|
|
307
|
+
private async runTurn(input: UserInput): Promise<void> {
|
|
308
|
+
const t0 = Date.now();
|
|
309
|
+
this.turnText = [];
|
|
310
|
+
this.lastMessageId = undefined;
|
|
311
|
+
try {
|
|
312
|
+
const conn = await this.start();
|
|
313
|
+
if (!conn || !this.currentId) return;
|
|
314
|
+
const note = describeAttachments(input.attachments, () => false, false);
|
|
315
|
+
const text = [input.text, note].filter(Boolean).join("\n\n");
|
|
316
|
+
this.events.onTurnStart?.();
|
|
317
|
+
const res = await conn.request<{ stopReason?: string }>("session/prompt", { sessionId: this.currentId, prompt: [{ type: "text", text }] });
|
|
318
|
+
if (this.disposed) return;
|
|
319
|
+
const stop = res?.stopReason ?? "end_turn";
|
|
320
|
+
if (stop === "cancelled") {
|
|
321
|
+
this.events.onError(new Error("interrupted"));
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (stop === "max_tokens") this.events.onStep("warning", "⚠️ 这一轮输出到达长度上限,被截断了");
|
|
325
|
+
else if (stop === "max_turn_requests") this.events.onStep("warning", "⚠️ 这一轮的模型请求次数到上限了,没做完");
|
|
326
|
+
else if (stop === "refusal") this.events.onStep("warning", "⚠️ 模型拒绝了这个请求");
|
|
327
|
+
const tokens = await this.reportUsage();
|
|
328
|
+
this.events.onResult({
|
|
329
|
+
text: this.turnText.join("\n\n"),
|
|
330
|
+
durationMs: Date.now() - t0,
|
|
331
|
+
...(tokens ? { tokens } : {}),
|
|
332
|
+
...(this.lastMessageId ? { anchor: this.lastMessageId } : {}),
|
|
333
|
+
});
|
|
334
|
+
} catch (err) {
|
|
335
|
+
if (this.disposed) return;
|
|
336
|
+
this.events.onError(err);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** 这一轮的用量从会话记录里加(记录可能稍晚才落盘,等一下) */
|
|
341
|
+
private async reportUsage(): Promise<number | undefined> {
|
|
342
|
+
if (!this.currentId) return undefined;
|
|
343
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
344
|
+
try {
|
|
345
|
+
const file = sessionFile(this.currentId);
|
|
346
|
+
const u = file ? lastTurnUsage(readEvents(file)) : undefined;
|
|
347
|
+
if (!u) return undefined;
|
|
348
|
+
this.events.onUsage?.(u, false);
|
|
349
|
+
return u.input + u.cacheRead + u.cacheWrite + u.output;
|
|
350
|
+
} catch {
|
|
351
|
+
return undefined;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
send(input: UserInput): void {
|
|
356
|
+
if (this.disposed) return;
|
|
357
|
+
if (this.turnBusy) {
|
|
358
|
+
this.pending.push(input);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
this.deliver(input);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
cancelQueued(input: UserInput): boolean {
|
|
365
|
+
const index = this.pending.indexOf(input);
|
|
366
|
+
if (index < 0) return false;
|
|
367
|
+
this.pending.splice(index, 1);
|
|
368
|
+
return true;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
private deliver(input: UserInput): void {
|
|
372
|
+
this.turnBusy = true;
|
|
373
|
+
this.turn = this.runTurn(input).finally(() => {
|
|
374
|
+
this.turn = null;
|
|
375
|
+
this.turnBusy = false;
|
|
376
|
+
const next = this.pending.shift();
|
|
377
|
+
if (next && !this.disposed) this.deliver(next);
|
|
378
|
+
else if (!this.disposed && this.conn && this.launchedKey !== this.wantedKey()) void this.stopProcess();
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
async listModels(): Promise<ModelInfo[]> {
|
|
383
|
+
const conn = await this.start();
|
|
384
|
+
if (!conn) return [];
|
|
385
|
+
return modelsOf(this.options);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** 沙箱档位只能启动时定:闲着就马上关掉进程,忙着就等这一轮完(deliver 里),下一条消息按新档位重拉 */
|
|
389
|
+
private async relaunchLater(): Promise<void> {
|
|
390
|
+
if (this.conn && !this.turnBusy && this.launchedKey !== this.wantedKey()) await this.stopProcess();
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async setPermission(level: PermissionLevel | undefined): Promise<void> {
|
|
394
|
+
this.opts.permission = level;
|
|
395
|
+
this.allowAll = level === "full";
|
|
396
|
+
await this.relaunchLater();
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
async setPlan(on: boolean): Promise<void> {
|
|
400
|
+
this.opts.plan = on;
|
|
401
|
+
await this.relaunchLater();
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
async setModel(model?: string, effort?: string): Promise<void> {
|
|
405
|
+
if (model !== undefined) this.opts.model = model || undefined;
|
|
406
|
+
if (effort !== undefined) this.opts.effort = effort || undefined;
|
|
407
|
+
this.runtime = { ...this.runtime, ...(model ? { model } : {}), ...(effort ? { effort } : {}) };
|
|
408
|
+
// 改了从下一个模型请求起生效,不用重拉
|
|
409
|
+
if (this.conn?.alive) await this.applyRuntime(this.conn);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
peekRuntime(): RuntimeInfo {
|
|
413
|
+
return this.runtime;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
async describeRuntime(): Promise<RuntimeInfo> {
|
|
417
|
+
return this.runtime;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
async interrupt(opts: InterruptOptions = {}): Promise<void> {
|
|
421
|
+
if (opts.keepQueue) {
|
|
422
|
+
const i = opts.first ? this.pending.indexOf(opts.first) : -1;
|
|
423
|
+
if (i > 0) this.pending.unshift(...this.pending.splice(i, 1));
|
|
424
|
+
} else {
|
|
425
|
+
const dropped = this.pending.length;
|
|
426
|
+
this.pending = [];
|
|
427
|
+
if (dropped > 0) this.events.onDropped?.(dropped);
|
|
428
|
+
}
|
|
429
|
+
if (!this.conn || !this.turnBusy || !this.currentId) return;
|
|
430
|
+
this.conn.notify("session/cancel", { sessionId: this.currentId });
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
async dispose(): Promise<void> {
|
|
434
|
+
this.disposed = true;
|
|
435
|
+
this.pending = [];
|
|
436
|
+
await this.starting?.catch(() => null);
|
|
437
|
+
if (this.conn && this.turnBusy && this.currentId) this.conn.notify("session/cancel", { sessionId: this.currentId });
|
|
438
|
+
await this.stopProcess();
|
|
439
|
+
await this.turn?.catch(() => {});
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** 授权卡里显示什么:命令、文件、dsh 给的理由 */
|
|
444
|
+
export function describePermission(name: string, input: Record<string, unknown>): string {
|
|
445
|
+
const why = typeof input.justification === "string" && input.justification.trim() ? `${input.justification.trim()}\n\n` : "";
|
|
446
|
+
if (name === "bash" && typeof input.command === "string") {
|
|
447
|
+
const desc = typeof input.description === "string" ? `${input.description}\n\n` : "";
|
|
448
|
+
return `${why}${desc}\`\`\`bash\n${input.command}\n\`\`\``;
|
|
449
|
+
}
|
|
450
|
+
const file = typeof input.file_path === "string" ? input.file_path : typeof input.path === "string" ? input.path : undefined;
|
|
451
|
+
if (file) return `${why}**文件**:\`${file}\``;
|
|
452
|
+
const rest = Object.fromEntries(Object.entries(input).filter(([k]) => k !== "justification" && k !== "content"));
|
|
453
|
+
return `${why}\`\`\`json\n${JSON.stringify(rest, null, 2)}\n\`\`\``;
|
|
454
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// 过程摘要里的一行(实时显示和读历史共用)。dsh 的工具名是小写的:bash、read、write、edit、glob、grep……
|
|
2
|
+
import { summarize } from "../claude/session.js";
|
|
3
|
+
|
|
4
|
+
/** dsh 的 todo_write 和 Claude 的 TodoWrite 参数一样({ todos: [{ content, status }] }),交给同一个 TodoTracker */
|
|
5
|
+
export function todoName(name: string): string {
|
|
6
|
+
return name === "todo_write" ? "TodoWrite" : name;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function describeDshStep(toolName: string, input: unknown): string {
|
|
10
|
+
const r = (input ?? {}) as Record<string, unknown>;
|
|
11
|
+
if (toolName === "bash" && typeof r.command === "string") return `bash: ${summarize(r.command, 60)}`;
|
|
12
|
+
const file = typeof r.file_path === "string" ? r.file_path : typeof r.path === "string" ? r.path : undefined;
|
|
13
|
+
if (file) {
|
|
14
|
+
const extra = typeof r.pattern === "string" ? ` ${summarize(r.pattern, 30)}` : "";
|
|
15
|
+
return `${toolName}: ${file}${extra}`;
|
|
16
|
+
}
|
|
17
|
+
if (typeof r.pattern === "string") return `${toolName}: ${summarize(r.pattern, 40)}`;
|
|
18
|
+
if (typeof r.query === "string") return `${toolName}: ${summarize(r.query, 50)}`;
|
|
19
|
+
if (typeof r.url === "string") return `${toolName}: ${summarize(r.url, 60)}`;
|
|
20
|
+
if (typeof r.description === "string") return `${toolName}: ${summarize(r.description, 50)}`;
|
|
21
|
+
return toolName;
|
|
22
|
+
}
|