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
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// ACP 的 stdio MCP 要绝对路径的命令:按 PATH 找出来
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
export function resolveCommand(cmd: string, pathEnv = process.env.PATH ?? ""): string | undefined {
|
|
6
|
+
if (!cmd) return undefined;
|
|
7
|
+
if (path.isAbsolute(cmd)) return fs.existsSync(cmd) ? cmd : undefined;
|
|
8
|
+
if (cmd.includes("/")) {
|
|
9
|
+
const abs = path.resolve(cmd);
|
|
10
|
+
return fs.existsSync(abs) ? abs : undefined;
|
|
11
|
+
}
|
|
12
|
+
for (const dir of pathEnv.split(path.delimiter)) {
|
|
13
|
+
if (!dir) continue;
|
|
14
|
+
const full = path.join(dir, cmd);
|
|
15
|
+
try {
|
|
16
|
+
fs.accessSync(full, fs.constants.X_OK);
|
|
17
|
+
if (fs.statSync(full).isFile()) return full;
|
|
18
|
+
} catch {
|
|
19
|
+
// 这个目录没有
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
package/src/agents/health.ts
CHANGED
|
@@ -13,6 +13,8 @@ import { onLoginDone, readAccount } from "./workbuddy/account.js";
|
|
|
13
13
|
import { desktopCli, ENVIRONMENT_LABEL, environment } from "./workbuddy/sdk.js";
|
|
14
14
|
import { listProviders, MIN_NODE, nodeOk } from "./pi/sdk.js";
|
|
15
15
|
import { onOAuthDone } from "./pi/oauth.js";
|
|
16
|
+
import { dshHome } from "./dsh/sdk.js";
|
|
17
|
+
import fs from "node:fs";
|
|
16
18
|
|
|
17
19
|
const require = createRequire(import.meta.url);
|
|
18
20
|
|
|
@@ -27,7 +29,7 @@ export type AgentFix = {
|
|
|
27
29
|
};
|
|
28
30
|
|
|
29
31
|
export type AgentHealth = {
|
|
30
|
-
id: "claude" | "codex" | "workbuddy" | "pi";
|
|
32
|
+
id: "claude" | "codex" | "workbuddy" | "pi" | "dsh";
|
|
31
33
|
label: string;
|
|
32
34
|
enabled: boolean;
|
|
33
35
|
installed: boolean;
|
|
@@ -250,6 +252,51 @@ let cache: { at: number; value: AgentHealth[] } | null = null;
|
|
|
250
252
|
onLoginDone(() => {
|
|
251
253
|
cache = null;
|
|
252
254
|
});
|
|
255
|
+
/** dsh:全局装的 npm 命令;「登录」= DSH_HOME 的凭据里有 DeepSeek API Key,或服务进程有 DEEPSEEK_API_KEY */
|
|
256
|
+
async function dshHealth(): Promise<AgentHealth> {
|
|
257
|
+
const cfg = config().agents.dsh;
|
|
258
|
+
const base = { id: "dsh" as const, label: "dsh", enabled: cfg.enabled };
|
|
259
|
+
const ver = await run(cfg.path || "dsh", ["--version"], 15_000);
|
|
260
|
+
if (ver.code !== 0) {
|
|
261
|
+
return {
|
|
262
|
+
...base,
|
|
263
|
+
installed: false,
|
|
264
|
+
loggedIn: null,
|
|
265
|
+
problem: `找不到 ${cfg.path || "dsh"}`,
|
|
266
|
+
fix: {
|
|
267
|
+
action: "install",
|
|
268
|
+
title: "安装 dsh",
|
|
269
|
+
commands: ["npm install -g @deepseek-ai/dsh"],
|
|
270
|
+
note: "需要 Node.js 22 以上。agent-loft 以系统服务运行时 PATH 很短,装好后在下面把「dsh 可执行文件」填成绝对路径(终端里 command -v dsh 可以查到)。升级也是这条命令。",
|
|
271
|
+
},
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
const version = ver.out.trim().split("\n").pop()?.trim();
|
|
275
|
+
let stored = false;
|
|
276
|
+
try {
|
|
277
|
+
stored = /^\s+DEEPSEEK_API_KEY:/m.test(fs.readFileSync(path.join(dshHome(), ".credentials.yaml"), "utf8"));
|
|
278
|
+
} catch {
|
|
279
|
+
// 还没有凭据文件
|
|
280
|
+
}
|
|
281
|
+
const loggedIn = stored || !!process.env.DEEPSEEK_API_KEY;
|
|
282
|
+
return {
|
|
283
|
+
...base,
|
|
284
|
+
installed: true,
|
|
285
|
+
...(version ? { version } : {}),
|
|
286
|
+
loggedIn,
|
|
287
|
+
...(loggedIn
|
|
288
|
+
? { account: stored ? "DeepSeek API Key(dsh 凭据)" : "DeepSeek API Key(环境变量)" }
|
|
289
|
+
: {
|
|
290
|
+
fix: {
|
|
291
|
+
action: "login" as const,
|
|
292
|
+
title: "配 DeepSeek API Key",
|
|
293
|
+
commands: [`${quote(cfg.path || "dsh")} web`],
|
|
294
|
+
note: "在服务器上运行这条命令,打开它给出的网页,在设置里填 DeepSeek API Key(存进 ~/.dsh/.credentials.yaml);也可以给 agent-loft 服务设 DEEPSEEK_API_KEY 环境变量。填好后点「重新检查」。",
|
|
295
|
+
},
|
|
296
|
+
}),
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
253
300
|
onOAuthDone(() => {
|
|
254
301
|
cache = null;
|
|
255
302
|
});
|
|
@@ -285,7 +332,9 @@ export function agentHealth(refresh = false): Promise<AgentHealth[]> {
|
|
|
285
332
|
// pi 没启用就不加载它的 SDK
|
|
286
333
|
const pi = () =>
|
|
287
334
|
config().agents.pi.enabled ? piHealth() : Promise.resolve<AgentHealth>({ id: "pi", label: "pi", enabled: false, installed: true, loggedIn: null });
|
|
288
|
-
|
|
335
|
+
const dsh = () =>
|
|
336
|
+
config().agents.dsh.enabled ? dshHealth() : Promise.resolve<AgentHealth>({ id: "dsh", label: "dsh", enabled: false, installed: true, loggedIn: null });
|
|
337
|
+
inflight ??= Promise.all([claudeHealth(), codexHealth(), workbuddy(), pi(), dsh()])
|
|
289
338
|
.then((value) => {
|
|
290
339
|
cache = { at: Date.now(), value };
|
|
291
340
|
return value;
|
|
@@ -102,7 +102,7 @@ export class FeishuBot {
|
|
|
102
102
|
const out: CommandEntry[] = [];
|
|
103
103
|
for (const agent of agents) {
|
|
104
104
|
if (!hub.driver(agent)) continue;
|
|
105
|
-
out.push(...(await hub.commandCatalog(agent, { allowedAgents: allowed, channel: "feishu" })).filter((c) => !["claude", "codex", "workbuddy", "pi"].includes(c.name) || this.cfg.experts === undefined || this.cfg.experts.includes(c.name)));
|
|
105
|
+
out.push(...(await hub.commandCatalog(agent, { allowedAgents: allowed, channel: "feishu" })).filter((c) => !["claude", "codex", "workbuddy", "pi", "dsh"].includes(c.name) || this.cfg.experts === undefined || this.cfg.experts.includes(c.name)));
|
|
106
106
|
}
|
|
107
107
|
return out;
|
|
108
108
|
}
|
package/src/channels/web/api.ts
CHANGED
|
@@ -359,6 +359,20 @@ function applyConfig(input: Partial<AppConfig>, selfOrigin?: string): void {
|
|
|
359
359
|
throw new HttpError(400, "pi 的思考程度只能是 off / minimal / low / medium / high / xhigh / max");
|
|
360
360
|
}
|
|
361
361
|
if (id === "pi" && "defaultModel" in patch && (typeof patch.defaultModel !== "string" || patch.defaultModel.length > 300)) throw new HttpError(400, "默认模型不对");
|
|
362
|
+
if (id === "dsh") {
|
|
363
|
+
const p = patch as Record<string, unknown>;
|
|
364
|
+
for (const key of ["path", "home", "patch"] as const) {
|
|
365
|
+
if (!(key in p)) continue;
|
|
366
|
+
const v = p[key];
|
|
367
|
+
if (typeof v !== "string" || v.length > 500) throw new HttpError(400, "路径不对");
|
|
368
|
+
const t = v.trim();
|
|
369
|
+
// dsh 可执行文件可以只写命令名(按 PATH 找),另外两个要么留空、要么绝对路径
|
|
370
|
+
if (t && key !== "path" && !path.isAbsolute(t)) throw new HttpError(400, key === "home" ? "DSH_HOME 要写绝对路径,留空用 ~/.dsh" : "patch 文件要写绝对路径,留空不加");
|
|
371
|
+
p[key] = key === "path" ? t || "dsh" : t;
|
|
372
|
+
}
|
|
373
|
+
if ("defaultEffort" in p && !["", "off", "low", "high", "max"].includes(String(p.defaultEffort))) throw new HttpError(400, "dsh 的思考程度只能是 off / low / high / max");
|
|
374
|
+
if ("defaultModel" in p && (typeof p.defaultModel !== "string" || p.defaultModel.length > 300)) throw new HttpError(400, "默认模型不对");
|
|
375
|
+
}
|
|
362
376
|
Object.assign(next.agents[id], patch);
|
|
363
377
|
}
|
|
364
378
|
}
|