dsh-any-agent 0.5.2 → 0.6.1
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/CHANGELOG.md +143 -1
- package/USAGE-NOTES.en.md +3 -1
- package/USAGE-NOTES.md +9 -2
- package/bin/dsh-any-agent-workspaces.mjs +12 -5
- package/bin/dsh-any-agent.mjs +27 -2
- package/bin/restore.mjs +1 -1
- package/docs/en/compatibility.md +27 -6
- package/docs/en/reference.md +4 -1
- package/docs/en/release.md +4 -0
- package/docs/en/security.md +1 -0
- package/docs/en/tests.md +59 -15
- package/docs/en/usage.md +22 -0
- package/docs/zh/compatibility.md +25 -6
- package/docs/zh/live-view-design.md +192 -0
- package/docs/zh/reference.md +4 -1
- package/docs/zh/release.md +3 -0
- package/docs/zh/security.md +1 -0
- package/docs/zh/tests.md +59 -15
- package/docs/zh/usage.md +22 -0
- package/package.json +4 -1
- package/scripts/detect-dsh.mjs +55 -0
- package/scripts/lint.mjs +595 -0
- package/scripts/sync-test-counts.mjs +699 -0
- package/src/acp-session.mjs +63 -0
- package/src/acp.mjs +14 -5
- package/src/config.mjs +39 -111
- package/src/conversation.mjs +1714 -0
- package/src/doctor.mjs +203 -0
- package/src/dsh-locate.mjs +560 -0
- package/src/git-snapshot.mjs +196 -0
- package/src/hub-store.mjs +108 -0
- package/src/hub.mjs +33 -1972
- package/src/live-cli.mjs +115 -0
- package/src/live-dashboard.html +535 -0
- package/src/live-dashboard.mjs +176 -0
- package/src/live-view.mjs +592 -0
- package/src/live.mjs +186 -0
- package/src/mcp.mjs +24 -75
- package/src/residue.mjs +282 -0
- package/src/sentinel.mjs +97 -0
- package/src/tool-defs.mjs +399 -0
- package/src/tool-render.mjs +262 -0
- package/src/tools.mjs +18 -767
- package/src/workspace-guard.mjs +89 -0
- package/src/workspace.mjs +295 -59
|
@@ -0,0 +1,592 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* live 事件流的读取与归并:`dsh-any-agent watch` 与 `dashboard` 共用。
|
|
3
|
+
*
|
|
4
|
+
* 只读 `<LIVE_DIR>/<会话>/events.jsonl`(以及注册表 / DSH 投影缓存里的标题),
|
|
5
|
+
* 从不写任何东西、从不碰写锁。把事件归并成一棵"调用链":
|
|
6
|
+
*
|
|
7
|
+
* 客户端(谁派的) → 会话 → 回合(send / queue / interject) → 工具调用 / 审批
|
|
8
|
+
*
|
|
9
|
+
* 读取是按字节偏移的增量 tail:只消费到最后一个换行,末尾写到一半的行留到下一次。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { LIVE_FILE } from './live.mjs';
|
|
15
|
+
|
|
16
|
+
/** 每个会话保留的回合数、每个回合保留的工具 / 审批数(只影响查看器内存)。 */
|
|
17
|
+
const MAX_RUNS_PER_CONV = 30;
|
|
18
|
+
const MAX_ITEMS_PER_RUN = 300;
|
|
19
|
+
/** 标题读 DSH 投影缓存,别每次轮询都读。 */
|
|
20
|
+
const TITLE_TTL_MS = 10_000;
|
|
21
|
+
const NEWLINE = 0x0a;
|
|
22
|
+
|
|
23
|
+
export function pidAlive(pid) {
|
|
24
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
25
|
+
try {
|
|
26
|
+
process.kill(pid, 0);
|
|
27
|
+
return true;
|
|
28
|
+
} catch (e) {
|
|
29
|
+
return e?.code === 'EPERM';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function writerPid(w) {
|
|
34
|
+
const n = Number.parseInt(String(w ?? '').split(':')[0], 10);
|
|
35
|
+
return Number.isInteger(n) && n > 0 ? n : null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 从 buffer 里切出完整的行;返回 {lines, rest}。rest 是末尾没有换行的半行(原样留着)。
|
|
40
|
+
* 按字节找换行,不会把多字节 UTF-8 字符切坏。
|
|
41
|
+
*/
|
|
42
|
+
export function splitLines(buf) {
|
|
43
|
+
const lines = [];
|
|
44
|
+
let start = 0;
|
|
45
|
+
for (let i = 0; i < buf.length; i++) {
|
|
46
|
+
if (buf[i] === NEWLINE) {
|
|
47
|
+
if (i > start) lines.push(buf.subarray(start, i).toString('utf8'));
|
|
48
|
+
start = i + 1;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return { lines, rest: buf.subarray(start) };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 解析一行;坏行 / 未知结构返回 null(查看器绝不因为一行坏数据崩掉)。 */
|
|
55
|
+
export function parseEvent(line) {
|
|
56
|
+
try {
|
|
57
|
+
const ev = JSON.parse(line);
|
|
58
|
+
if (!ev || typeof ev !== 'object' || typeof ev.type !== 'string' || typeof ev.conv !== 'string') return null;
|
|
59
|
+
return ev;
|
|
60
|
+
} catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function newConv(id) {
|
|
66
|
+
return {
|
|
67
|
+
id,
|
|
68
|
+
cwd: null,
|
|
69
|
+
title: null,
|
|
70
|
+
title_hint: null,
|
|
71
|
+
client: null,
|
|
72
|
+
permission: null,
|
|
73
|
+
on_approval: null,
|
|
74
|
+
model: null,
|
|
75
|
+
writer: null,
|
|
76
|
+
opened_at: null,
|
|
77
|
+
last_ts: null,
|
|
78
|
+
closed: false,
|
|
79
|
+
runs: [],
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function newRun(id) {
|
|
84
|
+
return {
|
|
85
|
+
run: id,
|
|
86
|
+
turn: null,
|
|
87
|
+
via: null,
|
|
88
|
+
client: null,
|
|
89
|
+
status: 'running',
|
|
90
|
+
queued_at: null,
|
|
91
|
+
started_at: null,
|
|
92
|
+
ended_at: null,
|
|
93
|
+
duration_ms: null,
|
|
94
|
+
prompt_preview: null,
|
|
95
|
+
stop_reason: null,
|
|
96
|
+
error: null,
|
|
97
|
+
tool_count: null,
|
|
98
|
+
auto_approvals: null,
|
|
99
|
+
auto_escalations: null,
|
|
100
|
+
writer: null,
|
|
101
|
+
items: [],
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 事件归并器。纯内存、与文件无关,方便单测。
|
|
107
|
+
* `apply(ev)` 吃一条事件;`view()` 给出可序列化的调用链快照。
|
|
108
|
+
*/
|
|
109
|
+
export class LiveState {
|
|
110
|
+
constructor() {
|
|
111
|
+
/** @type {Map<string, ReturnType<typeof newConv>>} */
|
|
112
|
+
this.convs = new Map();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
#conv(id) {
|
|
116
|
+
let c = this.convs.get(id);
|
|
117
|
+
if (!c) {
|
|
118
|
+
c = newConv(id);
|
|
119
|
+
this.convs.set(id, c);
|
|
120
|
+
}
|
|
121
|
+
return c;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
#run(conv, runId, { create = true } = {}) {
|
|
125
|
+
if (!runId) return null;
|
|
126
|
+
let r = conv.runs.find((x) => x.run === runId);
|
|
127
|
+
if (!r && create) {
|
|
128
|
+
r = newRun(runId);
|
|
129
|
+
conv.runs.push(r);
|
|
130
|
+
if (conv.runs.length > MAX_RUNS_PER_CONV) conv.runs.shift();
|
|
131
|
+
}
|
|
132
|
+
return r;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
#push(run, item) {
|
|
136
|
+
run.items.push(item);
|
|
137
|
+
if (run.items.length > MAX_ITEMS_PER_RUN) run.items.shift();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
apply(ev) {
|
|
141
|
+
const c = this.#conv(ev.conv);
|
|
142
|
+
c.last_ts = ev.ts ?? c.last_ts;
|
|
143
|
+
if (ev.w) c.writer = ev.w;
|
|
144
|
+
if (ev.client) c.client = ev.client;
|
|
145
|
+
if (ev.cwd) c.cwd = ev.cwd;
|
|
146
|
+
switch (ev.type) {
|
|
147
|
+
case 'conv.open':
|
|
148
|
+
c.opened_at = ev.ts;
|
|
149
|
+
c.permission = ev.permission ?? c.permission;
|
|
150
|
+
c.on_approval = ev.on_approval ?? c.on_approval;
|
|
151
|
+
c.model = ev.model ?? c.model;
|
|
152
|
+
if (ev.title_hint) c.title_hint = ev.title_hint;
|
|
153
|
+
c.closed = false;
|
|
154
|
+
break;
|
|
155
|
+
case 'conv.close':
|
|
156
|
+
c.closed = true;
|
|
157
|
+
break;
|
|
158
|
+
case 'run.queued': {
|
|
159
|
+
const r = this.#run(c, ev.run);
|
|
160
|
+
r.status = 'queued';
|
|
161
|
+
r.queued_at = ev.ts;
|
|
162
|
+
r.via = 'queue';
|
|
163
|
+
r.client = ev.client ?? r.client;
|
|
164
|
+
if (ev.prompt_preview) r.prompt_preview = ev.prompt_preview;
|
|
165
|
+
r.writer = ev.w ?? r.writer;
|
|
166
|
+
break;
|
|
167
|
+
}
|
|
168
|
+
case 'run.start': {
|
|
169
|
+
const r = this.#run(c, ev.run);
|
|
170
|
+
r.status = 'running';
|
|
171
|
+
r.started_at = ev.ts;
|
|
172
|
+
r.turn = ev.turn ?? r.turn;
|
|
173
|
+
r.via = ev.via ?? r.via;
|
|
174
|
+
r.client = ev.client ?? r.client;
|
|
175
|
+
r.writer = ev.w ?? r.writer;
|
|
176
|
+
if (ev.prompt_preview) r.prompt_preview = ev.prompt_preview;
|
|
177
|
+
c.permission = ev.permission ?? c.permission;
|
|
178
|
+
c.on_approval = ev.on_approval ?? c.on_approval;
|
|
179
|
+
c.closed = false;
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
case 'run.end': {
|
|
183
|
+
const r = this.#run(c, ev.run);
|
|
184
|
+
r.status = ev.status ?? 'done';
|
|
185
|
+
r.ended_at = ev.ts;
|
|
186
|
+
r.duration_ms = ev.duration_ms ?? r.duration_ms;
|
|
187
|
+
r.stop_reason = ev.stop_reason ?? r.stop_reason;
|
|
188
|
+
r.error = ev.error ?? r.error;
|
|
189
|
+
r.tool_count = ev.tool_count ?? r.tool_count;
|
|
190
|
+
r.auto_approvals = ev.auto_approvals ?? r.auto_approvals;
|
|
191
|
+
r.auto_escalations = ev.auto_escalations ?? r.auto_escalations;
|
|
192
|
+
// 回合结束时还没收尾的工具:标记成未完成,别一直显示"进行中"。
|
|
193
|
+
for (const it of r.items) if (it.kind === 'tool' && !isTerminalTool(it.status)) it.status = 'unfinished';
|
|
194
|
+
break;
|
|
195
|
+
}
|
|
196
|
+
case 'tool': {
|
|
197
|
+
const r = this.#run(c, ev.run);
|
|
198
|
+
if (!r) break;
|
|
199
|
+
let it = r.items.find((x) => x.kind === 'tool' && x.id === ev.tool_call_id);
|
|
200
|
+
if (!it) {
|
|
201
|
+
it = { kind: 'tool', id: ev.tool_call_id, at: ev.ts, name: null, tool_kind: null, status: null, title: null, input_preview: null, elapsed_ms: null };
|
|
202
|
+
this.#push(r, it);
|
|
203
|
+
}
|
|
204
|
+
it.name = ev.name ?? it.name;
|
|
205
|
+
it.tool_kind = ev.kind ?? it.tool_kind;
|
|
206
|
+
it.status = ev.status ?? it.status;
|
|
207
|
+
it.title = ev.title ?? it.title;
|
|
208
|
+
it.input_preview = ev.input_preview ?? it.input_preview;
|
|
209
|
+
if (ev.elapsed_ms !== undefined) it.elapsed_ms = ev.elapsed_ms;
|
|
210
|
+
it.last_at = ev.ts;
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
case 'approval': {
|
|
214
|
+
const r = this.#run(c, ev.run);
|
|
215
|
+
if (!r) break;
|
|
216
|
+
this.#push(r, {
|
|
217
|
+
kind: 'approval',
|
|
218
|
+
at: ev.ts,
|
|
219
|
+
approval_id: ev.approval_id ?? null,
|
|
220
|
+
tool_call_id: ev.tool_call_id ?? null,
|
|
221
|
+
tool: ev.tool ?? null,
|
|
222
|
+
mode: ev.mode ?? null,
|
|
223
|
+
escalation: ev.escalation ?? null,
|
|
224
|
+
title: ev.title ?? null,
|
|
225
|
+
command_preview: ev.command_preview ?? null,
|
|
226
|
+
decided: null,
|
|
227
|
+
});
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
case 'approval.decided': {
|
|
231
|
+
if (!ev.approval_id) break;
|
|
232
|
+
for (const r of c.runs) {
|
|
233
|
+
const it = r.items.find((x) => x.kind === 'approval' && x.approval_id === ev.approval_id);
|
|
234
|
+
if (it) {
|
|
235
|
+
it.decided = { by: ev.by ?? null, decision: ev.decision ?? null, effective: ev.effective ?? null, at: ev.ts };
|
|
236
|
+
break;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
case 'interject': {
|
|
242
|
+
const r = this.#run(c, ev.run, { create: false });
|
|
243
|
+
if (r) this.#push(r, { kind: 'interject', at: ev.ts, mode: ev.mode ?? null, text_preview: ev.text_preview ?? null, pending_run: ev.pending_run ?? null });
|
|
244
|
+
break;
|
|
245
|
+
}
|
|
246
|
+
case 'interrupt': {
|
|
247
|
+
const r = this.#run(c, ev.run, { create: false });
|
|
248
|
+
if (r) this.#push(r, { kind: 'interrupt', at: ev.ts });
|
|
249
|
+
break;
|
|
250
|
+
}
|
|
251
|
+
default:
|
|
252
|
+
// 未知类型(更新的 schema):只更新公共字段,不报错。
|
|
253
|
+
break;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
removeConv(id) {
|
|
258
|
+
this.convs.delete(id);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* 调用链快照(可直接 JSON 序列化)。
|
|
263
|
+
* `alive(pid)` 可注入,便于测试;写者已退出而回合仍"running"的,标成 interrupted。
|
|
264
|
+
*/
|
|
265
|
+
view({ alive = pidAlive, titles = new Map() } = {}) {
|
|
266
|
+
const aliveCache = new Map();
|
|
267
|
+
const isAlive = (w) => {
|
|
268
|
+
const pid = writerPid(w);
|
|
269
|
+
if (pid === null) return false;
|
|
270
|
+
if (!aliveCache.has(pid)) aliveCache.set(pid, alive(pid));
|
|
271
|
+
return aliveCache.get(pid);
|
|
272
|
+
};
|
|
273
|
+
const convs = [...this.convs.values()].map((c) => {
|
|
274
|
+
const runs = c.runs.map((r) => {
|
|
275
|
+
let status = r.status;
|
|
276
|
+
if ((status === 'running' || status === 'queued') && !isAlive(r.writer ?? c.writer)) status = 'interrupted';
|
|
277
|
+
const current = status === 'running' ? [...r.items].reverse().find((x) => x.kind === 'tool' && !isTerminalTool(x.status)) : null;
|
|
278
|
+
const pending = r.items.filter((x) => x.kind === 'approval' && x.mode === 'ask' && !x.decided);
|
|
279
|
+
return {
|
|
280
|
+
...r,
|
|
281
|
+
status,
|
|
282
|
+
items: r.items.map((x) => ({ ...x })),
|
|
283
|
+
current_tool: current ? current.name ?? current.title ?? current.id : null,
|
|
284
|
+
pending_approvals: status === 'running' ? pending.length : 0,
|
|
285
|
+
escalations: r.items.filter((x) => x.kind === 'approval' && x.escalation).length,
|
|
286
|
+
};
|
|
287
|
+
});
|
|
288
|
+
const latest = runs[runs.length - 1] ?? null;
|
|
289
|
+
// 运行中的回合优先于排队的(排队的回合总是排在运行中的后面)。
|
|
290
|
+
const state = runs.some((r) => r.status === 'running')
|
|
291
|
+
? 'running'
|
|
292
|
+
: runs.some((r) => r.status === 'queued')
|
|
293
|
+
? 'queued'
|
|
294
|
+
: c.closed
|
|
295
|
+
? 'closed'
|
|
296
|
+
: 'idle';
|
|
297
|
+
return {
|
|
298
|
+
id: c.id,
|
|
299
|
+
title: titles.get(c.id) ?? c.title ?? c.title_hint ?? null,
|
|
300
|
+
cwd: c.cwd,
|
|
301
|
+
client: c.client ?? latest?.client ?? null,
|
|
302
|
+
writer: c.writer,
|
|
303
|
+
writer_alive: isAlive(c.writer),
|
|
304
|
+
permission: c.permission,
|
|
305
|
+
on_approval: c.on_approval,
|
|
306
|
+
model: c.model,
|
|
307
|
+
opened_at: c.opened_at,
|
|
308
|
+
last_ts: c.last_ts,
|
|
309
|
+
state,
|
|
310
|
+
runs,
|
|
311
|
+
};
|
|
312
|
+
});
|
|
313
|
+
convs.sort((a, b) => rank(a.state) - rank(b.state) || String(b.last_ts ?? '').localeCompare(String(a.last_ts ?? '')));
|
|
314
|
+
|
|
315
|
+
// 调用链的第一层:按"哪个客户端、哪个服务实例"分组。
|
|
316
|
+
const groups = new Map();
|
|
317
|
+
for (const c of convs) {
|
|
318
|
+
const pid = writerPid(c.writer);
|
|
319
|
+
const key = `${c.client ?? 'unknown'}|${pid ?? '-'}`;
|
|
320
|
+
if (!groups.has(key)) groups.set(key, { client: c.client ?? null, pid, alive: c.writer_alive, conversations: [] });
|
|
321
|
+
groups.get(key).conversations.push(c);
|
|
322
|
+
}
|
|
323
|
+
const running = convs.filter((c) => c.state === 'running').length;
|
|
324
|
+
return {
|
|
325
|
+
generated_at: new Date().toISOString(),
|
|
326
|
+
totals: {
|
|
327
|
+
conversations: convs.length,
|
|
328
|
+
running,
|
|
329
|
+
queued: convs.reduce((n, c) => n + c.runs.filter((r) => r.status === 'queued').length, 0),
|
|
330
|
+
pending_approvals: convs.reduce((n, c) => n + c.runs.reduce((m, r) => m + r.pending_approvals, 0), 0),
|
|
331
|
+
escalations: convs.reduce((n, c) => n + c.runs.reduce((m, r) => m + r.escalations, 0), 0),
|
|
332
|
+
},
|
|
333
|
+
groups: [...groups.values()],
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function rank(state) {
|
|
339
|
+
return state === 'running' ? 0 : state === 'queued' ? 1 : state === 'idle' ? 2 : 3;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export function isTerminalTool(status) {
|
|
343
|
+
return status === 'completed' || status === 'failed' || status === 'unfinished';
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* 增量 tail 一个 live 目录。`poll()` 返回本次是否有变化。
|
|
348
|
+
* 只读文件;目录不存在时安静地什么也不做(服务可能还没写过任何事件)。
|
|
349
|
+
*/
|
|
350
|
+
export class LiveTail {
|
|
351
|
+
constructor(dir, { state = new LiveState(), stateFile = null, readTitle = null } = {}) {
|
|
352
|
+
this.dir = dir;
|
|
353
|
+
this.state = state;
|
|
354
|
+
this.stateFile = stateFile;
|
|
355
|
+
this.readTitle = readTitle;
|
|
356
|
+
/** file → {offset, rest: Buffer, ino} */
|
|
357
|
+
this.files = new Map();
|
|
358
|
+
this.titles = new Map();
|
|
359
|
+
this.titlesAt = 0;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
#readFrom(file, track) {
|
|
363
|
+
let st;
|
|
364
|
+
try {
|
|
365
|
+
st = statSync(file);
|
|
366
|
+
} catch {
|
|
367
|
+
return false;
|
|
368
|
+
}
|
|
369
|
+
if (st.size < track.offset) {
|
|
370
|
+
// 被滚动(rename 成 .1 后重新开始):从头读新文件。
|
|
371
|
+
track.offset = 0;
|
|
372
|
+
track.rest = Buffer.alloc(0);
|
|
373
|
+
}
|
|
374
|
+
if (st.size === track.offset) return false;
|
|
375
|
+
const len = st.size - track.offset;
|
|
376
|
+
const buf = Buffer.alloc(len);
|
|
377
|
+
let fd;
|
|
378
|
+
try {
|
|
379
|
+
fd = openSync(file, 'r');
|
|
380
|
+
const n = readSync(fd, buf, 0, len, track.offset);
|
|
381
|
+
track.offset += n;
|
|
382
|
+
} catch {
|
|
383
|
+
return false;
|
|
384
|
+
} finally {
|
|
385
|
+
if (fd !== undefined) {
|
|
386
|
+
try {
|
|
387
|
+
closeSync(fd);
|
|
388
|
+
} catch {}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
const { lines, rest } = splitLines(Buffer.concat([track.rest, buf]));
|
|
392
|
+
track.rest = Buffer.from(rest);
|
|
393
|
+
let changed = false;
|
|
394
|
+
for (const line of lines) {
|
|
395
|
+
const ev = parseEvent(line);
|
|
396
|
+
if (ev) {
|
|
397
|
+
this.state.apply(ev);
|
|
398
|
+
changed = true;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return changed;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
poll() {
|
|
405
|
+
let changed = false;
|
|
406
|
+
let names = [];
|
|
407
|
+
try {
|
|
408
|
+
names = existsSync(this.dir) ? readdirSync(this.dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name) : [];
|
|
409
|
+
} catch {
|
|
410
|
+
names = [];
|
|
411
|
+
}
|
|
412
|
+
const present = new Set(names);
|
|
413
|
+
// 会话目录被删(forget):从视图里移除。
|
|
414
|
+
for (const id of [...this.state.convs.keys()]) {
|
|
415
|
+
if (!present.has(id)) {
|
|
416
|
+
this.state.removeConv(id);
|
|
417
|
+
for (const k of [...this.files.keys()]) if (k.startsWith(join(this.dir, id))) this.files.delete(k);
|
|
418
|
+
changed = true;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
for (const id of names) {
|
|
422
|
+
const file = join(this.dir, id, LIVE_FILE);
|
|
423
|
+
let track = this.files.get(file);
|
|
424
|
+
if (!track) {
|
|
425
|
+
track = { offset: 0, rest: Buffer.alloc(0) };
|
|
426
|
+
this.files.set(file, track);
|
|
427
|
+
// 第一次见到这个会话:先读滚动出去的旧档,时间线才完整。
|
|
428
|
+
const old = `${file}.1`;
|
|
429
|
+
if (existsSync(old)) {
|
|
430
|
+
const oldTrack = { offset: 0, rest: Buffer.alloc(0) };
|
|
431
|
+
if (this.#readFrom(old, oldTrack)) changed = true;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
if (this.#readFrom(file, track)) changed = true;
|
|
435
|
+
}
|
|
436
|
+
if (this.#refreshTitles()) changed = true;
|
|
437
|
+
return changed;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** 标题:DSH 原生标题(投影缓存)> 注册表 titleHint > conv.open 的 title_hint。 */
|
|
441
|
+
#refreshTitles() {
|
|
442
|
+
const t = Date.now();
|
|
443
|
+
if (t - this.titlesAt < TITLE_TTL_MS) return false;
|
|
444
|
+
this.titlesAt = t;
|
|
445
|
+
const hints = new Map();
|
|
446
|
+
if (this.stateFile) {
|
|
447
|
+
try {
|
|
448
|
+
const doc = JSON.parse(readFileSync(this.stateFile, 'utf8'));
|
|
449
|
+
for (const c of doc?.conversations ?? []) if (c?.id && typeof c.titleHint === 'string') hints.set(c.id, c.titleHint);
|
|
450
|
+
} catch {
|
|
451
|
+
/* 注册表读不了就算了 */
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
let changed = false;
|
|
455
|
+
for (const id of this.state.convs.keys()) {
|
|
456
|
+
let title = null;
|
|
457
|
+
if (this.readTitle) {
|
|
458
|
+
try {
|
|
459
|
+
title = this.readTitle(id) ?? null;
|
|
460
|
+
} catch {
|
|
461
|
+
title = null;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
title = title ?? hints.get(id) ?? null;
|
|
465
|
+
if (title && this.titles.get(id) !== title) {
|
|
466
|
+
this.titles.set(id, title);
|
|
467
|
+
changed = true;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return changed;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
view(opts = {}) {
|
|
474
|
+
return this.state.view({ titles: this.titles, ...opts });
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// ── 终端渲染(watch) ───────────────────────────────────────────
|
|
479
|
+
|
|
480
|
+
const STATUS_MARK = {
|
|
481
|
+
running: '▶',
|
|
482
|
+
queued: '…',
|
|
483
|
+
done: '✓',
|
|
484
|
+
error: '✗',
|
|
485
|
+
cancelled: '■',
|
|
486
|
+
interrupted: '!',
|
|
487
|
+
};
|
|
488
|
+
|
|
489
|
+
function shortId(id) {
|
|
490
|
+
return String(id ?? '').slice(0, 8);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function fmtMs(ms) {
|
|
494
|
+
if (!Number.isFinite(ms)) return '';
|
|
495
|
+
if (ms < 1000) return `${ms}ms`;
|
|
496
|
+
if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;
|
|
497
|
+
return `${Math.floor(ms / 60_000)}m${Math.round((ms % 60_000) / 1000)}s`;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
function clip(s, n) {
|
|
501
|
+
if (!s) return '';
|
|
502
|
+
const t = String(s).replace(/\s+/g, ' ');
|
|
503
|
+
return t.length > n ? `${t.slice(0, n - 1)}…` : t;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* 把调用链快照渲染成纯文本树(watch 用)。
|
|
508
|
+
* @param {object} view LiveState.view() 的返回
|
|
509
|
+
* @param {object} [opts]
|
|
510
|
+
* @param {string} [opts.conv] 只看某个会话(id 前缀即可)
|
|
511
|
+
* @param {number} [opts.runs] 每个会话显示最近几轮(默认 3)
|
|
512
|
+
* @param {number} [opts.items] 每轮显示最后几条工具/审批(默认 12)
|
|
513
|
+
* @param {boolean} [opts.color] ANSI 颜色
|
|
514
|
+
*/
|
|
515
|
+
export function renderText(view, { conv = null, runs = 3, items = 12, color = false } = {}) {
|
|
516
|
+
const c = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
|
|
517
|
+
const dim = (s) => c('2', s);
|
|
518
|
+
const warn = (s) => c('33', s);
|
|
519
|
+
const bad = (s) => c('31', s);
|
|
520
|
+
const good = (s) => c('32', s);
|
|
521
|
+
const out = [];
|
|
522
|
+
const t = view.totals;
|
|
523
|
+
out.push(
|
|
524
|
+
`DSH live · ${t.conversations} 会话 · ${t.running} 运行中` +
|
|
525
|
+
(t.queued ? ` · ${t.queued} 排队` : '') +
|
|
526
|
+
(t.pending_approvals ? ` · ${warn(`${t.pending_approvals} 待审批`)}` : '') +
|
|
527
|
+
(t.escalations ? ` · ${warn(`⚠ ${t.escalations} 次提权`)}` : ''),
|
|
528
|
+
);
|
|
529
|
+
let shown = 0;
|
|
530
|
+
for (const g of view.groups) {
|
|
531
|
+
const convs = conv ? g.conversations.filter((x) => x.id.startsWith(conv)) : g.conversations;
|
|
532
|
+
if (!convs.length) continue;
|
|
533
|
+
out.push('');
|
|
534
|
+
out.push(`${g.client ?? '未知客户端'} ${dim(`pid ${g.pid ?? '?'}${g.alive ? '' : ' (已退出)'}`)}`);
|
|
535
|
+
convs.forEach((cv, ci) => {
|
|
536
|
+
shown++;
|
|
537
|
+
const lastConv = ci === convs.length - 1;
|
|
538
|
+
const p1 = lastConv ? '└─ ' : '├─ ';
|
|
539
|
+
const p1c = lastConv ? ' ' : '│ ';
|
|
540
|
+
const stateTxt = cv.state === 'running' ? good('运行中') : cv.state === 'queued' ? warn('排队') : dim(cv.state === 'closed' ? '已释放' : '空闲');
|
|
541
|
+
out.push(`${p1}${shortId(cv.id)} ${clip(cv.title ?? '(无标题)', 40)} ${stateTxt} ${dim(`${cv.permission ?? ''} · ${clip(cv.cwd ?? '', 50)}`)}`);
|
|
542
|
+
const rs = cv.runs.slice(-runs);
|
|
543
|
+
rs.forEach((r, ri) => {
|
|
544
|
+
const lastRun = ri === rs.length - 1;
|
|
545
|
+
const p2 = p1c + (lastRun ? '└─ ' : '├─ ');
|
|
546
|
+
const p2c = p1c + (lastRun ? ' ' : '│ ');
|
|
547
|
+
const mark = STATUS_MARK[r.status] ?? '?';
|
|
548
|
+
const markC = r.status === 'error' || r.status === 'interrupted' ? bad(mark) : r.status === 'running' ? good(mark) : mark;
|
|
549
|
+
const meta = [
|
|
550
|
+
r.via ? `[${r.via}]` : null,
|
|
551
|
+
r.status,
|
|
552
|
+
r.duration_ms != null ? fmtMs(r.duration_ms) : null,
|
|
553
|
+
r.tool_count != null ? `${r.tool_count} 工具` : null,
|
|
554
|
+
r.escalations ? warn(`⚠${r.escalations} 提权`) : null,
|
|
555
|
+
r.pending_approvals ? warn(`${r.pending_approvals} 待审批`) : null,
|
|
556
|
+
].filter(Boolean);
|
|
557
|
+
out.push(`${p2}${markC} ${r.run} ${meta.join(' · ')}${r.prompt_preview ? ` ${dim(`“${clip(r.prompt_preview, 60)}”`)}` : ''}`);
|
|
558
|
+
if (r.error) out.push(`${p2c} ${bad(clip(r.error, 100))}`);
|
|
559
|
+
const its = r.items.slice(-items);
|
|
560
|
+
if (r.items.length > its.length) out.push(`${p2c} ${dim(`…前面还有 ${r.items.length - its.length} 条`)}`);
|
|
561
|
+
for (const it of its) out.push(p2c + ' ' + renderItem(it, { warn, bad, good, dim }, cv.cwd));
|
|
562
|
+
});
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
if (!shown) out.push('', dim(conv ? `没有匹配 ${conv} 的会话。` : '还没有任何事件。派一次活(dsh_send)之后这里就会出现。'));
|
|
566
|
+
return out.join('\n');
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** 去掉会话目录前缀,把路径显示成相对路径。 */
|
|
570
|
+
export function relToCwd(text, cwd) {
|
|
571
|
+
if (!text || !cwd) return text ?? '';
|
|
572
|
+
const root = String(cwd).replace(/[\\/]+$/, '');
|
|
573
|
+
let out = String(text);
|
|
574
|
+
for (const sep of ['\\', '/']) out = out.split(root + sep).join('');
|
|
575
|
+
return out.split(root).join('.');
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
function renderItem(it, { warn, bad, good, dim }, cwd) {
|
|
579
|
+
if (it.kind === 'tool') {
|
|
580
|
+
const st = it.status === 'completed' ? good('✓') : it.status === 'failed' ? bad('✗') : it.status === 'unfinished' ? dim('·') : warn('▶');
|
|
581
|
+
const what = relToCwd(it.input_preview ?? (it.title !== it.name ? it.title : '') ?? '', cwd);
|
|
582
|
+
return `${st} ${it.name ?? it.title ?? it.id ?? 'tool'}${what ? ` ${dim(clip(what, 70))}` : ''}${it.elapsed_ms != null ? ` ${dim(fmtMs(it.elapsed_ms))}` : ''}`;
|
|
583
|
+
}
|
|
584
|
+
if (it.kind === 'approval') {
|
|
585
|
+
const decided = it.decided ? ` → ${it.decided.decision ?? it.decided.effective ?? ''}${it.decided.by ? `(${it.decided.by})` : ''}` : it.mode === 'ask' ? warn(' → 等待裁决') : '';
|
|
586
|
+
const esc = it.escalation ? warn(` ⚠ ${it.escalation}`) : '';
|
|
587
|
+
return `${warn('◆')} 审批 ${it.mode ?? ''}${esc}${decided}${it.command_preview ? ` ${dim(clip(relToCwd(it.command_preview, cwd), 60))}` : ''}`;
|
|
588
|
+
}
|
|
589
|
+
if (it.kind === 'interject') return `${warn('↪')} 插话(${it.mode ?? ''})${it.text_preview ? ` ${dim(clip(it.text_preview, 60))}` : ''}`;
|
|
590
|
+
if (it.kind === 'interrupt') return bad('■ 中断');
|
|
591
|
+
return dim(it.kind);
|
|
592
|
+
}
|