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.
Files changed (44) hide show
  1. package/README.md +6 -3
  2. package/package.json +1 -1
  3. package/src/agents/codex/protocol.ts +10 -0
  4. package/src/agents/codex/session.ts +201 -5
  5. package/src/agents/dsh/acp.ts +193 -0
  6. package/src/agents/dsh/driver.ts +126 -0
  7. package/src/agents/dsh/errors.ts +43 -0
  8. package/src/agents/dsh/history.ts +346 -0
  9. package/src/agents/dsh/sdk.ts +191 -0
  10. package/src/agents/dsh/session.ts +454 -0
  11. package/src/agents/dsh/steps.ts +22 -0
  12. package/src/agents/dsh/which.ts +23 -0
  13. package/src/agents/health.ts +51 -2
  14. package/src/channels/feishu/bot.ts +1 -1
  15. package/src/channels/web/api.ts +14 -0
  16. package/src/channels/web/experts-api.ts +1 -0
  17. package/src/channels/web/server.ts +28 -1
  18. package/src/core/builtin-agents.ts +1 -1
  19. package/src/core/command-catalog.ts +2 -1
  20. package/src/core/commands.ts +2 -1
  21. package/src/core/config.ts +23 -3
  22. package/src/core/expert-prompt.ts +15 -0
  23. package/src/core/experts.ts +22 -3
  24. package/src/core/hub.ts +60 -3
  25. package/src/core/memory-curator.ts +2 -2
  26. package/src/core/memory.ts +2 -2
  27. package/src/core/permission.ts +1 -1
  28. package/src/core/types.ts +19 -0
  29. package/src/core/users.ts +1 -1
  30. package/src/main.ts +5 -1
  31. package/web/css/composer.css +164 -0
  32. package/web/css/experts.css +66 -0
  33. package/web/lib/dom.js +2 -0
  34. package/web/lib/ws.js +4 -0
  35. package/web/settings/agent-defaults.js +2 -2
  36. package/web/settings/agents.js +15 -1
  37. package/web/settings/commands.js +1 -1
  38. package/web/settings/experts.js +86 -17
  39. package/web/settings/memory.js +2 -1
  40. package/web/views/composer.js +3 -1
  41. package/web/views/messages.js +1 -1
  42. package/web/views/sidebar.js +1 -1
  43. package/web/views/topbar.js +3 -1
  44. package/web/views/voice-call.js +293 -0
@@ -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
+ }
@@ -0,0 +1,346 @@
1
+ // 读 dsh 的会话记录:$DSH_HOME/sessions/<按 cwd 编的目录>/<会话 id>/session.v4.jsonl.zstd。
2
+ //
3
+ // ACP 恢复会话时不回放历史,会话列表也不带标题和时间,只能读 dsh 落的盘。
4
+ // 文件是追加写的:每次 flush 追加一个 zstd frame。Node 的 zstdDecompressSync 只解第一个 frame,
5
+ // 所以自己按 frame 头切开再逐个解(splitFrames)。最后一个 frame 可能还在写,解不开就跳过。
6
+ //
7
+ // 每行一条事件,用到的几种:
8
+ // { type: "session", id, createdAt, cwd, origin?: "subagent", parentSession? } 第一行
9
+ // { type: "user/message", data: { content: [{ type: "text", text }], source: { kind: "user" | ... }, id } }
10
+ // { type: "assistant/message", data: { message: { content: [{ type: "text" | "reasoning" | "tool-call", ... }], id }, usage } }
11
+ // { type: "session/title", data: { title, source: { kind: "fallback" | "provider" } } }
12
+ // { type: "model/selection", data: { provider, model, reasoningEffort } }
13
+ // { type: "turn/start" | "turn/end", data: { turn } }
14
+ // 这是 dsh 的内部格式,认不出的事件一律跳过,别因为它升级了就整段读不出来。
15
+ import fs from "node:fs";
16
+ import path from "node:path";
17
+ import zlib from "node:zlib";
18
+ import { stripContext } from "../../core/expert-prompt.js";
19
+ import type { HistoryMessage, SessionSummary, TokenUsage } from "../../core/types.js";
20
+ import { splitAttachmentNote } from "../../core/uploads.js";
21
+ import { summarize } from "../claude/session.js";
22
+ import { TodoTracker } from "../claude/todos.js";
23
+ import { sessionsRoot } from "./sdk.js";
24
+ import { describeDshStep, todoName } from "./steps.js";
25
+
26
+ /** 会话 id 会拼进路径,先验形 */
27
+ export const SESSION_ID = /^[A-Za-z0-9_-]{8,80}$/;
28
+ const LOG_NAME = "session.v4.jsonl.zstd";
29
+
30
+ export type DshEvent = { type?: string; seq?: number; time?: number; data?: Record<string, unknown>; [k: string]: unknown };
31
+
32
+ // ---------- zstd frame ----------
33
+
34
+ const ZSTD_MAGIC = 0xfd2fb528;
35
+
36
+ /** 按 zstd 帧格式(RFC 8878)切出每个 frame;格式不对就停在那里 */
37
+ export function splitFrames(buf: Buffer): Buffer[] {
38
+ const frames: Buffer[] = [];
39
+ let pos = 0;
40
+ while (pos + 4 <= buf.length) {
41
+ const magic = buf.readUInt32LE(pos);
42
+ // 可跳过的帧:0x184D2A50 ~ 0x184D2A5F
43
+ if ((magic & 0xfffffff0) === 0x184d2a50) {
44
+ if (pos + 8 > buf.length) break;
45
+ pos += 8 + buf.readUInt32LE(pos + 4);
46
+ continue;
47
+ }
48
+ if (magic !== ZSTD_MAGIC) break;
49
+ const start = pos;
50
+ let p = pos + 4;
51
+ if (p >= buf.length) break;
52
+ const fhd = buf[p]!;
53
+ p += 1;
54
+ const fcsFlag = fhd >> 6;
55
+ const single = (fhd >> 5) & 1;
56
+ const checksum = (fhd >> 2) & 1;
57
+ const dictFlag = fhd & 3;
58
+ if (!single) p += 1;
59
+ p += [0, 1, 2, 4][dictFlag]!;
60
+ p += fcsFlag === 0 ? (single ? 1 : 0) : [0, 2, 4, 8][fcsFlag]!;
61
+ let last = false;
62
+ while (!last) {
63
+ if (p + 3 > buf.length) return frames;
64
+ const header = buf[p]! | (buf[p + 1]! << 8) | (buf[p + 2]! << 16);
65
+ p += 3;
66
+ last = (header & 1) === 1;
67
+ const type = (header >> 1) & 3;
68
+ const size = header >>> 3;
69
+ if (type === 3) return frames;
70
+ p += type === 1 ? 1 : size;
71
+ }
72
+ if (checksum) p += 4;
73
+ if (p > buf.length) break;
74
+ frames.push(buf.subarray(start, p));
75
+ pos = p;
76
+ }
77
+ return frames;
78
+ }
79
+
80
+ /** 解出整份记录的文本 */
81
+ export function decodeLog(buf: Buffer): string {
82
+ const parts: string[] = [];
83
+ for (const f of splitFrames(buf)) {
84
+ try {
85
+ parts.push(zlib.zstdDecompressSync(f).toString("utf8"));
86
+ } catch {
87
+ // 写到一半的 frame
88
+ }
89
+ }
90
+ return parts.join("");
91
+ }
92
+
93
+ export function readEvents(file: string): DshEvent[] {
94
+ const out: DshEvent[] = [];
95
+ for (const line of decodeLog(fs.readFileSync(file)).split("\n")) {
96
+ if (!line.trim()) continue;
97
+ try {
98
+ const r = JSON.parse(line) as unknown;
99
+ if (r && typeof r === "object") out.push(r as DshEvent);
100
+ } catch {
101
+ // 半行
102
+ }
103
+ }
104
+ return out;
105
+ }
106
+
107
+ // ---------- 找文件 ----------
108
+
109
+ /** 按会话 id 找记录文件。目录名是 dsh 按 cwd 编的,不去复刻规则,挨个目录找 */
110
+ export function sessionFile(id: string): string | undefined {
111
+ if (!SESSION_ID.test(id)) return undefined;
112
+ let dirs: string[];
113
+ try {
114
+ dirs = fs.readdirSync(sessionsRoot());
115
+ } catch {
116
+ return undefined;
117
+ }
118
+ for (const d of dirs) {
119
+ const file = path.join(sessionsRoot(), d, id, LOG_NAME);
120
+ if (fs.existsSync(file)) return file;
121
+ }
122
+ return undefined;
123
+ }
124
+
125
+ // ---------- 取字段 ----------
126
+
127
+ function textOf(content: unknown, type = "text"): string {
128
+ if (typeof content === "string") return content;
129
+ if (!Array.isArray(content)) return "";
130
+ return content
131
+ .map((c) => (c && typeof c === "object" && (c as { type?: string }).type === type && typeof (c as { text?: unknown }).text === "string" ? (c as { text: string }).text : ""))
132
+ .filter((t) => t.trim())
133
+ .join("\n");
134
+ }
135
+
136
+ function argsOf(raw: unknown): Record<string, unknown> {
137
+ if (raw && typeof raw === "object") return raw as Record<string, unknown>;
138
+ if (typeof raw !== "string") return {};
139
+ try {
140
+ const v = JSON.parse(raw) as unknown;
141
+ return v && typeof v === "object" ? (v as Record<string, unknown>) : {};
142
+ } catch {
143
+ return {};
144
+ }
145
+ }
146
+
147
+ function header(events: DshEvent[]): DshEvent | undefined {
148
+ return events[0]?.type === "session" ? events[0] : undefined;
149
+ }
150
+
151
+ /** 用户亲手发的消息(不是运行时上下文、子 agent 结果、时间提示这些塞进来的) */
152
+ function userText(e: DshEvent): string | undefined {
153
+ if (e.type !== "user/message") return undefined;
154
+ const d = e.data as { content?: unknown; source?: { kind?: string } } | undefined;
155
+ if (d?.source?.kind !== "user") return undefined;
156
+ return textOf(d.content);
157
+ }
158
+
159
+ function cleanTitle(raw: string): string | undefined {
160
+ const t = stripContext(raw).replace(/\s+/g, " ").trim();
161
+ if (!t) return undefined;
162
+ return t.length > 60 ? `${t.slice(0, 60)}…` : t;
163
+ }
164
+
165
+ /** 模型起的标题(最后一次为准);只有截首句的 fallback 时返回 undefined */
166
+ function titleIn(events: DshEvent[]): string | undefined {
167
+ for (let i = events.length - 1; i >= 0; i--) {
168
+ const e = events[i]!;
169
+ if (e.type !== "session/title") continue;
170
+ const d = e.data as { title?: unknown; source?: { kind?: string } } | undefined;
171
+ if (d?.source?.kind === "fallback") continue;
172
+ if (typeof d?.title === "string" && d.title.trim()) return cleanTitle(d.title);
173
+ }
174
+ return undefined;
175
+ }
176
+
177
+ function firstPrompt(events: DshEvent[]): string | undefined {
178
+ for (const e of events) {
179
+ const raw = userText(e);
180
+ if (raw === undefined) continue;
181
+ const t = splitAttachmentNote(stripContext(raw)).text;
182
+ if (t) return cleanTitle(t);
183
+ }
184
+ return undefined;
185
+ }
186
+
187
+ /** 最后用的模型服务商:ACP profile 只认它自己有适配器的(默认只有 deepseek-official),别的恢复不了 */
188
+ function lastProvider(events: DshEvent[]): string | undefined {
189
+ for (let i = events.length - 1; i >= 0; i--) {
190
+ const e = events[i]!;
191
+ if (e.type === "model/selection" && typeof e.data?.provider === "string") return e.data.provider;
192
+ }
193
+ return undefined;
194
+ }
195
+
196
+ export function sessionTitleOf(id: string): string | undefined {
197
+ const file = sessionFile(id);
198
+ return file ? titleIn(readEvents(file)) : undefined;
199
+ }
200
+
201
+ export function sessionCwd(id: string): string | undefined {
202
+ const file = sessionFile(id);
203
+ if (!file) return undefined;
204
+ const cwd = header(readEvents(file))?.cwd;
205
+ return typeof cwd === "string" ? cwd : undefined;
206
+ }
207
+
208
+ /**
209
+ * 最近的会话;cwd 给了就只要这个目录的。子 agent 的会话、没说过话的、
210
+ * 用了 ACP 认不了的服务商的(比如在 dsh web 里配的别家模型)不列
211
+ */
212
+ export function listSessionFiles(cwd: string | undefined, limit: number, providers?: Set<string>): SessionSummary[] {
213
+ let dirs: string[];
214
+ try {
215
+ dirs = fs.readdirSync(sessionsRoot());
216
+ } catch {
217
+ return [];
218
+ }
219
+ const files: { id: string; file: string; mtime: number }[] = [];
220
+ for (const d of dirs) {
221
+ let names: string[];
222
+ try {
223
+ names = fs.readdirSync(path.join(sessionsRoot(), d));
224
+ } catch {
225
+ continue;
226
+ }
227
+ for (const id of names) {
228
+ if (!SESSION_ID.test(id)) continue;
229
+ const file = path.join(sessionsRoot(), d, id, LOG_NAME);
230
+ try {
231
+ files.push({ id, file, mtime: fs.statSync(file).mtimeMs });
232
+ } catch {
233
+ // 不是会话目录
234
+ }
235
+ }
236
+ }
237
+ files.sort((a, b) => b.mtime - a.mtime);
238
+ const out: SessionSummary[] = [];
239
+ // 最多看 200 个,别为了凑数把整个目录读一遍
240
+ for (const f of files.slice(0, 200)) {
241
+ if (out.length >= limit) break;
242
+ let events: DshEvent[];
243
+ try {
244
+ events = readEvents(f.file);
245
+ } catch {
246
+ continue;
247
+ }
248
+ const h = header(events);
249
+ if (!h || h.origin === "subagent") continue;
250
+ const at = typeof h.cwd === "string" ? h.cwd : undefined;
251
+ if (cwd && at && path.resolve(at) !== path.resolve(cwd)) continue;
252
+ const provider = lastProvider(events);
253
+ if (providers && provider && !providers.has(provider)) continue;
254
+ const prompt = firstPrompt(events);
255
+ if (!prompt) continue;
256
+ out.push({ id: f.id, title: titleIn(events) ?? prompt, ...(at ? { cwd: at } : {}), updatedAt: f.mtime });
257
+ }
258
+ return out;
259
+ }
260
+
261
+ /**
262
+ * 整理成「一问一答」:用户一条,助手把这一轮的文字拼成一条,工具调用挂成过程摘要。
263
+ * 和 Claude 的 readHistory 一个口径(见 claude/driver.ts)。
264
+ */
265
+ export function readHistoryEvents(events: DshEvent[]): HistoryMessage[] {
266
+ const out: HistoryMessage[] = [];
267
+ let assistant: HistoryMessage | null = null;
268
+ const todos = new TodoTracker();
269
+ const flush = () => {
270
+ if (assistant && (assistant.text.trim() || assistant.steps?.length)) out.push(assistant);
271
+ assistant = null;
272
+ };
273
+ for (const e of events) {
274
+ const raw = userText(e);
275
+ if (raw !== undefined) {
276
+ const { text, attachments } = splitAttachmentNote(stripContext(raw));
277
+ flush();
278
+ if (!text && attachments.length === 0) continue;
279
+ const id = (e.data as { id?: unknown }).id;
280
+ out.push({
281
+ role: "user",
282
+ text,
283
+ ...(typeof id === "string" ? { anchor: id } : {}),
284
+ ...(attachments.length ? { attachments } : {}),
285
+ ...(typeof e.time === "number" ? { ts: e.time } : {}),
286
+ });
287
+ continue;
288
+ }
289
+ if (e.type === "assistant/message") {
290
+ const msg = (e.data as { message?: { content?: unknown; id?: unknown } } | undefined)?.message;
291
+ if (!msg) continue;
292
+ assistant ??= { role: "assistant", text: "", steps: [] };
293
+ if (typeof msg.id === "string") assistant.anchor = msg.id;
294
+ if (typeof e.time === "number") assistant.ts = e.time;
295
+ const blocks = Array.isArray(msg.content) ? (msg.content as Record<string, unknown>[]) : [];
296
+ for (const b of blocks) {
297
+ if (b.type === "reasoning" && typeof b.text === "string" && b.text.trim()) {
298
+ assistant.steps!.push(`💭 ${summarize(b.text)}`);
299
+ } else if (b.type === "tool-call" && typeof b.name === "string") {
300
+ const input = argsOf(b.arguments);
301
+ const todo = todos.use(todoName(b.name), input, typeof b.id === "string" ? b.id : undefined);
302
+ if (todo?.changed) assistant.todos = todos.list;
303
+ assistant.steps!.push(todo ? todo.step : `🔧 ${describeDshStep(b.name, input)}`);
304
+ }
305
+ }
306
+ const text = textOf(blocks);
307
+ if (text.trim()) assistant.text += (assistant.text ? "\n\n" : "") + text;
308
+ continue;
309
+ }
310
+ if (e.type === "turn/end") flush();
311
+ }
312
+ flush();
313
+ return out;
314
+ }
315
+
316
+ export function readHistoryFile(id: string): HistoryMessage[] {
317
+ const file = sessionFile(id);
318
+ return file ? readHistoryEvents(readEvents(file)) : [];
319
+ }
320
+
321
+ /**
322
+ * 最近一轮(最后一个 turn/start 之后)的 token 用量。ACP 只报上下文占用,不报每一轮花了多少,
323
+ * 这一轮结束后从记录里加出来。inputTokens 是没命中缓存的部分(实测 input + cacheRead + output = total)
324
+ */
325
+ export function lastTurnUsage(events: DshEvent[]): TokenUsage | undefined {
326
+ let start = -1;
327
+ for (let i = events.length - 1; i >= 0; i--) {
328
+ if (events[i]!.type === "turn/start") {
329
+ start = i;
330
+ break;
331
+ }
332
+ }
333
+ if (start < 0) return undefined;
334
+ const u: TokenUsage = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 };
335
+ for (const e of events.slice(start)) {
336
+ if (e.type !== "assistant/message") continue;
337
+ const usage = (e.data as { usage?: Record<string, unknown> } | undefined)?.usage;
338
+ if (!usage) continue;
339
+ const n = (k: string) => (typeof usage[k] === "number" ? (usage[k] as number) : 0);
340
+ u.input += n("inputTokens");
341
+ u.cacheRead += n("cacheReadTokens");
342
+ u.cacheWrite += n("cacheWriteTokens");
343
+ u.output += n("outputTokens");
344
+ }
345
+ return u.input + u.cacheRead + u.cacheWrite + u.output > 0 ? u : undefined;
346
+ }