@duanz/pi-d-live 1.0.0 → 1.1.0

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 (4) hide show
  1. package/README.en.md +60 -0
  2. package/README.md +61 -0
  3. package/index.ts +436 -48
  4. package/package.json +8 -4
package/README.en.md ADDED
@@ -0,0 +1,60 @@
1
+ # d-live
2
+
3
+ <p align="center"><strong>English</strong> | <a href="./README.md">中文</a></p>
4
+
5
+ <p align="center"><img src="https://raw.githubusercontent.com/DuanZGit/D-Hub/master/docs/covers/d-live.png" alt="d-live cover" width="880"></p>
6
+
7
+ <p align="center"><strong>Turns the model's thinking and tool calls into a live progress strip in pi-web</strong><br><sub>Local SSE · sentence-level batching · per-session isolation</sub></p>
8
+
9
+ <p align="center">
10
+ <a href="https://www.npmjs.com/package/@duanz/pi-d-live"><img src="https://img.shields.io/npm/v/@duanz%2Fpi-d-live.svg?style=flat-square" alt="npm"></a>
11
+ <a href="https://github.com/DuanZGit/D-Hub/blob/master/LICENSE"><img src="https://img.shields.io/npm/l/@duanz%2Fpi-d-live.svg?style=flat-square" alt="license"></a>
12
+ <a href="https://github.com/DuanZGit/D-Hub"><img src="https://img.shields.io/badge/GitHub-DuanZGit%2FD--Hub-181717?style=flat-square&logo=github" alt="GitHub"></a>
13
+ <img src="https://img.shields.io/badge/pi-extension-34d399?style=flat-square" alt="pi extension">
14
+ </p>
15
+
16
+ <p align="center">
17
+ <code>pi install npm:@duanz/pi-d-live</code>
18
+ </p>
19
+
20
+ ## Why
21
+
22
+ During a long task the screen shows a spinner and a list of English tool names. The user waits without knowing where the work is going.
23
+
24
+ d-live takes agent events (`thinking_delta`, `tool_execution_start`), batches them at sentence boundaries, rewrites them with **the current session model** into 3–6 plain sentences, and pushes them to a floating strip at the top of pi-web.
25
+
26
+ ## Data flow
27
+
28
+ ```
29
+ pi agent events → sentence batching → ctx.modelRegistry.complete() rewrite → local SSE (127.0.0.1:18999/live) → front-end strip
30
+ ```
31
+
32
+ - Batching: at least 70 characters before a sentence break, hard cap 300; queue cap of 4 segments drops new ones to stay live
33
+ - Rewrite: 12-second hard timeout; no file names, function names, ports, or paths
34
+ - Isolation: every push carries a `sid`; the front end plays only the current session
35
+ - Tool names use a zero-latency label map (`read` → "take a look"), no model call
36
+
37
+ ## Usage
38
+
39
+ ```
40
+ /d-live on # enable (/live is an alias)
41
+ /d-live off # disable
42
+ /d-live status # current state
43
+ ```
44
+
45
+ Local endpoints: `GET /live` (SSE), `GET /health`, `GET /ping`.
46
+
47
+ ## Prerequisite
48
+
49
+ The strip is front-end code and needs a pi-web injection: `cn-assets/pi-web-live.js` is inlined into `public/sw.js` through `patches.json`, replayed after pi-web upgrades by [pi-web-patch-keeper](https://github.com/DuanZGit/D-Hub/tree/master/extensions/pi-web-patch-keeper).
50
+
51
+ Without that injection the SSE server still runs; nothing shows in the page.
52
+
53
+ ## Limits
54
+
55
+ - Each rewrite costs tokens from the current model (about 2 seconds per segment); `/d-live off` on token-heavy sessions.
56
+ - pi-web only — pure CLI has no injection point.
57
+
58
+ ## License
59
+
60
+ MIT © DuanZ
package/README.md ADDED
@@ -0,0 +1,61 @@
1
+ # d-live
2
+
3
+ <p align="center"><a href="./README.en.md">English</a> | <strong>中文</strong></p>
4
+
5
+ <p align="center"><img src="https://raw.githubusercontent.com/DuanZGit/D-Hub/master/docs/covers/d-live.png" alt="d-live cover" width="880"></p>
6
+
7
+ <p align="center"><strong>把模型的思考和工具调用,实时改写成页面顶部的进度播报</strong><br><sub>本地 SSE · 按句切段 · 多会话隔离 · 不占终端</sub></p>
8
+
9
+ <p align="center">
10
+ <a href="https://www.npmjs.com/package/@duanz/pi-d-live"><img src="https://img.shields.io/npm/v/@duanz%2Fpi-d-live.svg?style=flat-square" alt="npm"></a>
11
+ <a href="https://github.com/DuanZGit/D-Hub/blob/master/LICENSE"><img src="https://img.shields.io/npm/l/@duanz%2Fpi-d-live.svg?style=flat-square" alt="license"></a>
12
+ <a href="https://github.com/DuanZGit/D-Hub"><img src="https://img.shields.io/badge/GitHub-DuanZGit%2FD--Hub-181717?style=flat-square&logo=github" alt="GitHub"></a>
13
+ <img src="https://img.shields.io/badge/pi-extension-34d399?style=flat-square" alt="pi extension">
14
+ </p>
15
+
16
+ <p align="center">
17
+ <code>pi install npm:@duanz/pi-d-live</code>
18
+ </p>
19
+
20
+ ## 它解决什么
21
+
22
+ 长任务里,屏幕上只有一个转圈的 spinner 和一串英文工具名。用户在等,却不知道这件事推进到哪了、下一步往哪走。
23
+
24
+ d-live 把 agent 事件(`thinking_delta`、`tool_execution_start`)按句切段,用**当前会话的模型**改写成 3–6 句日常话,推到 pi-web 页面顶部的浮层条里播。
25
+
26
+ ## 数据流
27
+
28
+ ```
29
+ pi agent 事件 → 按句切段 → ctx.modelRegistry.complete() 改写 → 本地 SSE(127.0.0.1:18999/live) → 前端浮层
30
+ ```
31
+
32
+ - 切段:至少 70 字才允许按句号切,硬上限 300 字;队列上限 4 段,超了丢新段,保证实时性
33
+ - 改写:单次硬超时 12 秒;不写文件名、函数名、端口、路径
34
+ - 隔离:每条推送带 `sid`,前端只播当前会话的
35
+ - 工具行先用零延迟规则占位(`read` → 「看一眼」),随后由模型改写成「在哪找什么、为了什么」,慢一点但更具体
36
+ - emoji 不强制、不固定:模型按内容自己决定放哪、放几个,前端不补也不挪位置
37
+
38
+ ## 用法
39
+
40
+ ```
41
+ /d-live on # 开启(/live 是兼容别名)
42
+ /d-live off # 关闭
43
+ /d-live status # 看当前状态
44
+ ```
45
+
46
+ 本地端点:`GET /live`(SSE)、`GET /health`、`GET /ping`。
47
+
48
+ ## 前置条件
49
+
50
+ 浮层是前端代码,需要 pi-web 侧注入:`cn-assets/d-live.js` 由 `patches.json` 以 inline 方式注进 `public/sw.js`,由 [pi-web-patch-keeper](https://github.com/DuanZGit/D-Hub/tree/master/extensions/pi-web-patch-keeper) 在 pi-web 升级后重放。
51
+
52
+ 没有这层注入时,扩展的 SSE 服务照常工作,只是页面上看不到浮层。
53
+
54
+ ## 限制
55
+
56
+ - 每段改写都消耗当前模型 token(实测每段约 2 秒),任务极多时可 `/d-live off`。
57
+ - 只面向 pi-web;纯 CLI 没有注入点。
58
+
59
+ ## License
60
+
61
+ MIT © DuanZ
package/index.ts CHANGED
@@ -16,21 +16,82 @@
16
16
 
17
17
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
18
18
  import { createServer, type ServerResponse } from "node:http";
19
+ import { openSync, readSync, closeSync, statSync, existsSync } from "node:fs";
20
+ import { join } from "node:path";
19
21
 
20
22
  const PORT = 18999;
21
- const MIN_SEG = 70; // 至少这么多字才允许按句号切(实测每段改写 ~2s,太短会把队列打满)
22
- const MAX_SEG = 300; // 硬上限,超过无条件切
23
- const MAX_LINES = 6;
23
+ const MIN_SEG = 200; // 至少这么多字才允许按句号切(每段改写 ~2s,切太碎会刷屏)
24
+ const MAX_SEG = 500; // 硬上限,超过无条件切
25
+ const MAX_LINES = 3;
24
26
  const MAX_PENDING = 4; // 队列上限,超了就丢新段,保证实时性
25
- const REWRITE_TIMEOUT = 12000; // 单次改写硬超时
27
+ const REWRITE_TIMEOUT = 25000; // 单次改写硬超时(段变长后模型更慢)
26
28
 
27
- const SYS = `把下面这段思考,改写成给用户看的进度播报:这个项目正在做什么改造、推进到哪一步、下一步往哪走。
29
+ // ── 判档回显:tail magpie routing jsonl,把 rule.pick(判档结果)推给对应会话的浮层条 ──
30
+ const ROUTING_DIR = "/home/duanz/.config/magpie/routing";
31
+ const ROUTING_TAIL_MS = 2000; // 轮询间隔
32
+ const ROUTING_MAX_BYTES = 256 * 1024; // 每次最多读文件尾这么多,routing 行单条几十 KB 也够
33
+
34
+ function todayRoutingFile(): string {
35
+ const d = new Date();
36
+ const p = (n: number) => String(n).padStart(2, "0");
37
+ return join(ROUTING_DIR, `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}.jsonl`);
38
+ }
39
+
40
+ function startEffortWatcher(emitFn: (p: Record<string, unknown>) => void) {
41
+ let offset = 0; // 上次读到的字节位置
42
+ let lastSize = -1;
43
+ const timer = setInterval(() => {
44
+ try {
45
+ const file = todayRoutingFile();
46
+ if (!existsSync(file)) return;
47
+ const size = statSync(file).size;
48
+ if (size === lastSize) return;
49
+ // 文件被截断/轮转就从头部重读
50
+ const start = size < offset ? 0 : offset;
51
+ const len = Math.min(size - start, ROUTING_MAX_BYTES);
52
+ if (len <= 0) { offset = size; lastSize = size; return; }
53
+ const buf = Buffer.alloc(len);
54
+ const fd = openSync(file, "r");
55
+ try {
56
+ readSync(fd, buf, 0, len, start);
57
+ } finally {
58
+ closeSync(fd);
59
+ }
60
+ offset = start + len;
61
+ lastSize = size;
62
+ for (const line of buf.toString("utf8").split("\n")) {
63
+ if (!line.includes('"pick"')) continue;
64
+ try {
65
+ const rec = JSON.parse(line);
66
+ const rule = rec.rule || {};
67
+ const pick = rule.pick;
68
+ if (!pick || typeof pick !== "string") continue;
69
+ const sid = String(rec.session || "");
70
+ if (!sid) continue;
71
+ emitFn({
72
+ kind: "effort",
73
+ sid,
74
+ pick,
75
+ sent: rec.effort || "",
76
+ degraded: Boolean(rule.classified && rule.classified.degraded) || /DEGRADED/.test(line),
77
+ });
78
+ } catch {}
79
+ }
80
+ } catch {}
81
+ }, ROUTING_TAIL_MS);
82
+ if (typeof timer.unref === "function") timer.unref();
83
+ }
84
+
85
+ const SYS = `把下面这段思考,改写成给用户看的进度解说:正在做什么、为什么要这么做、做完会怎样。
28
86
 
29
87
  规则:
30
- - 不用第一人称,不出现"我";用无主语或"正在/已经/接下来"开头;
31
- - 每句要有信息量:说清在改什么、进展到哪、下一步是什么,让人看懂这件事往哪推进;
32
- - 每句 14 字以内,最多 ${MAX_LINES} 句;每句结尾加省略号;
33
- - 一半左右的句子带 emoji,别堆满;
88
+ - 说人话,像朋友在旁边随口讲一句,带点画面感,可以用「先翻翻」「挨个对一遍」「这就去」「稳了」这类口语;
89
+ - 不用第一人称,不出现"我";用无主语或"正在/已经/接下来/这就"开头;
90
+ - 每句 16~22 字,把前因后果说完整:先说要做什么或看到什么,再说为什么这么选;
91
+ - 最多 ${MAX_LINES} 句,每句一行;句尾必须有标点(…… / 。 / !);emoji 随内容自然用,放句首、句中、句尾都行,也可以整句不放,种类跟着内容走,别老是那两三个,也别每句都放;
92
+ - 一轮里只围绕一个目标往前推,几句连起来要像同一条线:第二句起用「接着」「于是」「这下」「所以」「接下来」「顺手」这类词承接上一句,别忽然跳到无关的事,也别重复前面说过的内容;
93
+ - 输入里若给了「前面已经说过」,就从那儿接着往下说,把新的发现和下一步接上,不要另起炉灶;
94
+ - 同一段里别重复用同一个 emoji;句子要生动,避免「正在处理」「进行分析」这类空话;
34
95
  - 不写文件名、函数名、端口、路径、命令、缩写字母(JS/CSS/SSE/API 这类),一律换成日常说法;
35
96
  - 不加引号和编号,不模仿用户语气;
36
97
  - 必须真的改写:禁止照抄原文里的任何句子、列表、表格、日志;原文里的工具输出直接跳过不写;
@@ -162,7 +223,10 @@ export function bashIntent(cmd: unknown): string {
162
223
  const c = String(cmd || "").trim();
163
224
  if (!c) return "跑一条命令";
164
225
  const args = c.split(/[\s|;&<>()]+/).filter(Boolean);
165
- const rest = args.filter((w) => !/^[-+]/.test(w));
226
+ // 丢掉重定向目标:>/dev/null 会被当成文件名,播出去就成了「看 null 里的内容」
227
+ const DEVNULL = /^(?:\/dev\/(?:null|stdout|stderr|zero|fd\/\d+)|\/proc\/self\/fd\/\d+)$/i;
228
+ const JUNKNAME = /^(?:null|undefined|nil|true|false|nan|\d+)$/i;
229
+ const rest = args.filter((w) => !/^[-+]/.test(w) && !DEVNULL.test(w));
166
230
 
167
231
  // 搜内容:在 X 里找 Y
168
232
  if (/\b(grep|rg|ag|ack)\b/.test(c)) {
@@ -190,8 +254,12 @@ export function bashIntent(cmd: unknown): string {
190
254
  if (script && /\b(python3?|node|bash|sh|deno)\b/.test(c)) return `跑 ${baseName(script)} 脚本`;
191
255
  // 看文件内容:说清哪个文件
192
256
  if (/\b(sed\s+-n|head|tail|less|more|cat)\b/.test(c)) {
193
- const f = rest.filter((w) => w.includes("/") || /\.[a-z]{2,4}$/i.test(w)).pop();
194
- return f ? `看 ${baseName(f)} 里的内容` : "看文件内容";
257
+ const f = rest
258
+ .filter((w) => !/^\/dev\//.test(w))
259
+ .filter((w) => w.includes("/") || /\.[a-z]{2,4}$/i.test(w))
260
+ .pop();
261
+ const n = f ? baseName(f) : "";
262
+ return n && !JUNKNAME.test(n) ? `看 ${n} 里的内容` : "看文件内容";
195
263
  }
196
264
  // 日志:说清哪个服务
197
265
  if (/\bjournalctl\b/.test(c)) {
@@ -214,8 +282,8 @@ export function bashIntent(cmd: unknown): string {
214
282
  }
215
283
 
216
284
  const CMD_SYS = `你看到的是 AI 助手刚刚执行的一条命令,以及它执行前在想什么。
217
- 用一句中文说出这条命令的**意图**:它想达成什么、想确认什么、想找出什么。说意图,不说手段。
218
- 规则:16 字以内;不要出现命令名、文件名、路径、参数、端口、缩写字母;不要引号和编号。
285
+ 用一句中文说出这条命令的**意图**:在哪找什么、想确认什么、为了什么。要具体到对象,别只说「查一下」「跑一下」这种空话,说得口语、有画面感。
286
+ 规则:24 字以内;句尾加标点(…… 或 。);emoji 可用可不用,用就贴切,别每句都放;不要出现命令名、参数、端口、缩写字母(文件名可以保留);不要引号和编号。
219
287
  只输出这一句话。`;
220
288
 
221
289
  /** 让模型说清这条命令到底想干嘛;超时或失败返回空串,由 bashIntent 规则兜底。 */
@@ -256,34 +324,200 @@ async function cmdIntent(ctx: any, cmd: string, hint = ""): Promise<string> {
256
324
  }
257
325
  }
258
326
 
327
+ const TOOL_SYS = `你看到的是 AI 助手刚要做的一件事(工具名 + 参数),以及它动手前的想法。
328
+ 用一句中文说清:在什么里面、找什么/看什么/改什么、想确认什么、为了什么。要具体到对象,别只说「看文件」「搜一下」这种空话。
329
+ 规则:24 字以内;句尾加标点(…… 或 。);emoji 可用可不用,用就贴切;不要出现参数名、缩写字母;不要引号和编号。
330
+ 只输出这一句话。`;
331
+
332
+ /** 让模型说清这件工具活儿具体在干什么;超时或失败返回空串,由规则版兜底。 */
333
+ async function toolIntent(ctx: any, name: string, args: any, hint = ""): Promise<string> {
334
+ const model = pickModel(ctx);
335
+ if (!model) return "";
336
+ let brief = "";
337
+ try {
338
+ brief = JSON.stringify(args ?? {}, null, 0).slice(0, 600);
339
+ } catch {
340
+ brief = String(args ?? "").slice(0, 600);
341
+ }
342
+ if (!brief || brief === "{}") return "";
343
+ try {
344
+ const res: any = await Promise.race([
345
+ ctx.modelRegistry.complete(
346
+ model,
347
+ {
348
+ systemPrompt: TOOL_SYS,
349
+ messages: [
350
+ {
351
+ role: "user",
352
+ content: [
353
+ {
354
+ type: "text",
355
+ text:
356
+ (hint ? `他刚才在想:${hint.slice(-300)}\n\n` : "") +
357
+ `工具:${name}\n参数:${brief}`,
358
+ },
359
+ ],
360
+ timestamp: Date.now(),
361
+ },
362
+ ],
363
+ },
364
+ { cacheRetention: "none" },
365
+ ),
366
+ new Promise((r) => setTimeout(() => r(null), 5000)),
367
+ ]);
368
+ if (!res) return "";
369
+ const out = (res.content || [])
370
+ .filter((c: any) => c.type === "text")
371
+ .map((c: any) => c.text)
372
+ .join("")
373
+ .trim();
374
+ return out.split("\n")[0].replace(/^[-•*\d.、)\s]+/, "").replace(/[""'']/g, "").slice(0, 60);
375
+ } catch {
376
+ return "";
377
+ }
378
+ }
379
+
380
+ const SUMMARY_SYS = `用一句中文向用户交代:这一轮到底干了什么、成没成。
381
+ 规则:30 字以内;说结果,不说过程;口语一点,别用「已完成」「进行处理」这类空话;不出现文件名、路径、命令、缩写字母;不加引号编号;emoji 可用可不用,别每句都放。
382
+ 只输出这一句话。`;
383
+
384
+ /** 一轮跑完给一句结论。模型超时或说得不像就用规则句兜底,永远不空着。 */
385
+ async function roundSummary(
386
+ ctx: any,
387
+ info: { ms: number; steps: number; fails: number; names: string[] },
388
+ ): Promise<string> {
389
+ const sec = info.ms > 0 ? Math.round(info.ms / 1000) : 0;
390
+ const fallback = `这一轮想完了,${sec}s、${info.steps} 步${info.fails ? `,有 ${info.fails} 处没成` : ",都顺"}。`;
391
+ const model = pickModel(ctx);
392
+ if (!model || info.steps === 0) return fallback;
393
+ const kinds = [...new Set(info.names)].slice(0, 6).join("、");
394
+ try {
395
+ const res: any = await Promise.race([
396
+ ctx.modelRegistry.complete(
397
+ model,
398
+ {
399
+ systemPrompt: SUMMARY_SYS,
400
+ messages: [
401
+ {
402
+ role: "user",
403
+ content: [
404
+ {
405
+ type: "text",
406
+ text: `这一轮做了 ${info.steps} 步(${kinds}),其中失败 ${info.fails} 次,共 ${sec} 秒。`,
407
+ },
408
+ ],
409
+ timestamp: Date.now(),
410
+ },
411
+ ],
412
+ },
413
+ { cacheRetention: "none" },
414
+ ),
415
+ new Promise((r) => setTimeout(() => r(null), 15000)),
416
+ ]);
417
+ const out = (res?.content || [])
418
+ .filter((c: any) => c.type === "text")
419
+ .map((c: any) => c.text)
420
+ .join("")
421
+ .trim();
422
+ const one =
423
+ out
424
+ .split("\n")
425
+ .map((x: string) =>
426
+ x
427
+ .replace(/^[-•*\d.、)\s]+/, "")
428
+ .replace(/^["「『]|["」』]$/g, "")
429
+ .trim(),
430
+ )
431
+ .filter(Boolean)[0] || "";
432
+ if (!one || one.length > 40) return fallback;
433
+ return one;
434
+ } catch {
435
+ return fallback;
436
+ }
437
+ }
438
+
259
439
  type Sess = {
260
440
  seg: string;
261
441
  ctx: any;
262
442
  chain: Promise<void>;
263
443
  pending: number;
444
+ /** 本轮开始时间,用来算总耗时 */
445
+ t0: number;
446
+ /** 本轮工具步数与失败数 */
447
+ tools: number;
448
+ fails: number;
449
+ names: string[];
450
+ /** 本轮已经播过的短句,喂给下一次改写,让前后能接上 */
451
+ history: string[];
264
452
  };
265
453
 
266
- const sessions = new Map<string, Sess>();
267
- const clients = new Set<ServerResponse>();
454
+ // pi-web 会为每个会话各加载一份扩展。模块级变量在不同实例之间不共享,
455
+ // 只有抢到端口的那个实例能收到浏览器连接 —— 用 globalThis 把状态提到进程级,
456
+ // 否则表现为“只有第一个开着的会话有条子”。
457
+ const SHARED: any =
458
+ (globalThis as any).__dliveShared ||
459
+ ((globalThis as any).__dliveShared = {
460
+ sessions: new Map<string, Sess>(),
461
+ clients: new Set<ServerResponse>(),
462
+ clientSids: new Map<ServerResponse, string>(),
463
+ pings: [] as string[],
464
+ recent: [] as string[],
465
+ listening: false,
466
+ });
467
+
468
+ const sessions: Map<string, Sess> = SHARED.sessions;
469
+ const clients: Set<ServerResponse> = SHARED.clients;
268
470
  /** 每个 SSE 连接上报的会话 id,仅用于诊断串会话问题 */
269
- const clientSids = new Map<ServerResponse, string>();
471
+ const clientSids: Map<ServerResponse, string> = SHARED.clientSids;
270
472
  /** 前端启动阶段上报,用来判断脚本跑到哪一步 */
271
- const pings: string[] = [];
473
+ const pings: string[] = SHARED.pings;
474
+ const recent: string[] = SHARED.recent;
272
475
  let enabled = true;
273
476
 
477
+ const lastSidDebug: Record<string, string> = {};
478
+
479
+ // 工具事件的 ctx 不一定带 sessionManager,记住最近一次真实会话,别让推送退化成 default 被过滤掉
480
+ let lastRealSid = "";
481
+
274
482
  function sidOf(ctx: any): string {
275
483
  try {
276
- return ctx?.sessionManager?.getSessionId?.() || "default";
277
- } catch {
278
- return "default";
484
+ const sm = ctx?.sessionManager;
485
+ const byApi = String(sm?.getSessionId?.() || "");
486
+ const file = String(sm?.getSessionFile?.() || sm?.getSessionPath?.() || "");
487
+ const m = file.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/);
488
+ lastSidDebug.api = byApi;
489
+ lastSidDebug.file = file;
490
+ lastSidDebug.picked = m ? m[1] : byApi;
491
+ const real = m ? m[1] : byApi;
492
+ if (real) {
493
+ lastRealSid = real;
494
+ return real;
495
+ }
496
+ } catch {}
497
+ return lastRealSid || "default";
498
+ }
499
+
500
+ const INSTANCE = Math.random().toString(36).slice(2, 8);
501
+
502
+ /**
503
+ * 同一会话只让一份扩展实例处理事件。
504
+ * pi-web 会为同一个会话加载多份扩展,不去重的话模型改写、工具意图都会重复跑两遍。
505
+ */
506
+ function claim(sid: string): boolean {
507
+ if (!SHARED.owner) SHARED.owner = new Map<string, string>();
508
+ const cur = SHARED.owner.get(sid);
509
+ if (!cur) {
510
+ SHARED.owner.set(sid, INSTANCE);
511
+ return true;
279
512
  }
513
+ return cur === INSTANCE;
280
514
  }
281
515
 
282
516
  function sess(ctx: any): Sess {
283
517
  const sid = sidOf(ctx);
284
518
  let s = sessions.get(sid);
285
519
  if (!s) {
286
- s = { seg: "", ctx, chain: Promise.resolve(), pending: 0 };
520
+ s = { seg: "", ctx, chain: Promise.resolve(), pending: 0, t0: 0, tools: 0, fails: 0, names: [], history: [] };
287
521
  sessions.set(sid, s);
288
522
  }
289
523
  s.ctx = ctx;
@@ -291,12 +525,35 @@ function sess(ctx: any): Sess {
291
525
  }
292
526
 
293
527
  function emit(payload: Record<string, unknown>) {
528
+ try {
529
+ // pi-web 同一个会话可能加载两份扩展(重启接力时),两份 handler 都连着共享的 clients,
530
+ // 不去重的话每条推送会发两次。
531
+ const key = `${String(payload.sid || "")}|${String(payload.kind)}|${String(payload.tid || "")}|${String(payload.text || "")}`;
532
+ const now = Date.now();
533
+ const last = SHARED.lastEmit;
534
+ if (last && last.k === key && now - last.t < 150) return;
535
+ SHARED.lastEmit = { k: key, t: now };
536
+ const t = new Date().toTimeString().slice(0, 8);
537
+ // effort 每秒都在蹦,留着会把别的播报挤出去,诊断时看不见
538
+ if (String(payload.kind) !== "effort") {
539
+ recent.push(`${t} ${String(payload.kind)} sid=${String(payload.sid || "-").slice(0, 8)}`);
540
+ if (recent.length > 60) recent.splice(0, recent.length - 60);
541
+ }
542
+ } catch {}
294
543
  const line = `data: ${JSON.stringify(payload)}\n\n`;
544
+ const sid = typeof payload.sid === "string" ? payload.sid : "";
545
+ const unknown = !sid || sid === "default";
295
546
  for (const c of clients) {
547
+ // 只推给「报了号且号对得上」的页面:空号连接(旧版页面)一律不推,
548
+ // 否则一个页面会收到所有会话的播报,串到别的会话里。
549
+ const want = clientSids.get(c) || "";
550
+ if (!want) continue;
551
+ if (!unknown && want !== sid) continue;
296
552
  try {
297
553
  c.write(line);
298
554
  } catch {
299
555
  clients.delete(c);
556
+ clientSids.delete(c);
300
557
  }
301
558
  }
302
559
  }
@@ -331,10 +588,41 @@ function shouldCut(s: string): boolean {
331
588
  return false;
332
589
  }
333
590
 
591
+ // 系统注入的上下文(压缩块、记忆注入)长得像“思考”,但不是,不能播给用户
592
+ const NOISE =
593
+ /(CONTEXT BREAKDOWN|COMPRESSED BLOCKS|openviking-context|OpenViking context|\[ACP\]|Compressed m\d|<acp\b|viking:\/\/|User said \(m\d)/i;
594
+ /** 一句太长就按标点切成两句:一行放得下才不用缩字或换行 */
595
+ function splitLong(line: string, max = 22): string[] {
596
+ let rest = String(line || "").trim();
597
+ if (!rest) return [];
598
+ const out: string[] = [];
599
+ while (rest.length > max) {
600
+ const head = rest.slice(0, max);
601
+ let cut = -1;
602
+ for (let i = head.length - 1; i >= 8; i--) {
603
+ if (",,、;;::。!?!?".includes(head[i])) {
604
+ cut = i;
605
+ break;
606
+ }
607
+ }
608
+ if (cut < 0) cut = max - 1;
609
+ const piece = rest.slice(0, cut + 1).replace(/[,,、;;::\s]+$/, "");
610
+ out.push(/[。!?!?]$/.test(piece) ? piece : piece + "。");
611
+ rest = rest.slice(cut + 1).trim();
612
+ }
613
+ if (rest) out.push(/[。!?!?]$/.test(rest) ? rest : rest + "。");
614
+ return out;
615
+ }
616
+
617
+ function isNoise(text: string): boolean {
618
+ return NOISE.test(text);
619
+ }
620
+
334
621
  function flushSeg(s: Sess, sid: string) {
335
622
  const text = s.seg.trim();
336
623
  s.seg = "";
337
624
  if (text.length < 8) return;
625
+ if (isNoise(text)) return; // 系统注入的上下文不是思考,直接丢
338
626
  rewrite(s, sid, text);
339
627
  }
340
628
 
@@ -374,6 +662,10 @@ function rewrite(s: Sess, sid: string, text: string) {
374
662
  const ctx = s.ctx;
375
663
  const model = pickModel(ctx);
376
664
  if (!model) return;
665
+ const prior = s.history.slice(-4);
666
+ const lead = prior.length
667
+ ? "前面已经说过(接着往下讲,别重复):\n" + prior.join("\n") + "\n\n这一段新的思考:\n"
668
+ : "";
377
669
  try {
378
670
  const res: any = await Promise.race([
379
671
  ctx.modelRegistry.complete(
@@ -383,7 +675,7 @@ function rewrite(s: Sess, sid: string, text: string) {
383
675
  messages: [
384
676
  {
385
677
  role: "user",
386
- content: [{ type: "text", text }],
678
+ content: [{ type: "text", text: lead + text }],
387
679
  timestamp: Date.now(),
388
680
  },
389
681
  ],
@@ -410,14 +702,21 @@ function rewrite(s: Sess, sid: string, text: string) {
410
702
  // 过滤照抄的噪声:带代码/表格符号、英文术语、长数字的行一律不要
411
703
  .filter(
412
704
  (line: string) =>
413
- line.length > 0 &&
414
- line.length <= 18 &&
705
+ line.length >= 8 &&
706
+ line.length <= 40 &&
707
+ !isNoise(line) &&
415
708
  !/[|[\]{}%#=<>_\\]/.test(line) &&
416
709
  !/\b(?:acp|api|json|sse|css|html|ctx|sid|pid|url|http|localhost|status|result|delta|token)\b/i.test(line) &&
417
710
  !/\d{3,}/.test(line),
418
711
  )
419
712
  .slice(0, MAX_LINES);
420
- if (lines.length) emit({ kind: "lines", sid, lines });
713
+ if (lines.length) {
714
+ // 一条播报只放一句能塞进一行的:太长的按标点切成两句,免得手机上前端被迫缩字换行
715
+ const capped: string[] = [];
716
+ for (const line of lines) for (const piece of splitLong(line)) capped.push(piece);
717
+ emit({ kind: "lines", sid, lines: capped });
718
+ s.history = s.history.concat(capped).slice(-8);
719
+ }
421
720
  } catch (e: any) {
422
721
  const name = String(e?.name || "");
423
722
  if (name !== "AbortError") {
@@ -460,8 +759,10 @@ function startServer() {
460
759
  }
461
760
  if (url.startsWith("/ping")) {
462
761
  const qq = url.includes("?") ? new URLSearchParams(url.slice(url.indexOf("?") + 1)) : null;
463
- pings.push(`${new Date().toISOString().slice(11, 19)} ${qq?.get("step") || "?"} sid=${qq?.get("sid") || "-"}`);
464
- if (pings.length > 20) pings.shift();
762
+ pings.push(
763
+ `${new Date().toISOString().slice(11, 19)} ${qq?.get("step") || "?"} p=${qq?.get("pid") || "?"} sid=${(qq?.get("sid") || "-").slice(0, 8)} v=${qq?.get("v") || "?"} src=${qq?.get("src") || "?"} u=${(qq?.get("u") || "").slice(0, 40)}`,
764
+ );
765
+ if (pings.length > 40) pings.shift();
465
766
  res.writeHead(204);
466
767
  res.end();
467
768
  return;
@@ -479,7 +780,9 @@ function startServer() {
479
780
  pending,
480
781
  clientSids: [...clientSids.values()],
481
782
  pings,
783
+ sidDebug: lastSidDebug,
482
784
  serverSids: [...sessions.keys()],
785
+ recent,
483
786
  }),
484
787
  );
485
788
  return;
@@ -487,31 +790,48 @@ function startServer() {
487
790
  res.writeHead(404);
488
791
  res.end();
489
792
  });
490
- server.on("error", () => {
491
- /* 端口被占就静默放弃,不影响 agent */
793
+ // pi-web 每个会话都会加载一份扩展;端口只能被第一份占到。
794
+ // 重复绑定是正常的,不能让它打断这个会话里后面的 pi.on(...) 注册。
795
+ server.on("error", (e: any) => {
796
+ if (e?.code === "EADDRINUSE") return;
492
797
  });
493
- server.listen(PORT, "127.0.0.1");
494
- const timer = setInterval(() => {
495
- for (const c of clients) {
496
- try {
497
- c.write(": ping\n\n");
498
- } catch {
499
- clients.delete(c);
500
- }
798
+ if (!SHARED.listening) {
799
+ SHARED.listening = true;
800
+ try {
801
+ server.listen(PORT, "127.0.0.1");
802
+ } catch {
803
+ SHARED.listening = false;
501
804
  }
502
- }, 20000);
503
- if (typeof timer.unref === "function") timer.unref();
805
+ }
806
+ // 心跳只挂一份:每个会话都会加载一份扩展,无条件起定时器会变成 N 份重复推送
807
+ if (!SHARED.beat) {
808
+ const timer = setInterval(() => {
809
+ for (const c of clients) {
810
+ try {
811
+ // 不只是保活:前端把这条当心跳,收不到就自己重连
812
+ c.write('data: {"kind":"beat"}\n\n');
813
+ } catch {
814
+ clients.delete(c);
815
+ clientSids.delete(c);
816
+ }
817
+ }
818
+ }, 15000);
819
+ if (typeof timer.unref === "function") timer.unref();
820
+ SHARED.beat = timer;
821
+ }
504
822
  }
505
823
 
506
824
  export default function piWebLive(pi: ExtensionAPI) {
507
825
  startServer();
826
+ startEffortWatcher(emit);
508
827
 
509
828
  pi.on("message_update", async (event: any, ctx: any) => {
510
829
  if (!enabled) return;
511
830
  const ev = event?.assistantMessageEvent;
512
831
  if (!ev) return;
513
- const s = sess(ctx);
514
832
  const sid = sidOf(ctx);
833
+ if (!claim(sid)) return;
834
+ const s = sess(ctx);
515
835
  if (ev.type === "thinking_delta" && typeof ev.delta === "string") {
516
836
  s.seg += ev.delta;
517
837
  if (shouldCut(s.seg)) flushSeg(s, sid);
@@ -528,34 +848,102 @@ export default function piWebLive(pi: ExtensionAPI) {
528
848
  pi.on("tool_execution_start", async (event: any, ctx: any) => {
529
849
  if (!enabled) return;
530
850
  const sid = sidOf(ctx);
851
+ if (!claim(sid)) return;
531
852
  const name = event?.toolName || "";
853
+ const tid = String(event?.toolCallId || "");
854
+ const s = sess(ctx);
855
+ s.tools++;
856
+ if (name) s.names.push(name);
532
857
  if (name === "bash") {
533
858
  // 先用规则版即时占位(零延迟),模型算出真正的意图后再把那一行改写掉
534
859
  const cmd = event?.args?.command;
535
- const tid = event?.toolCallId || `t${Date.now()}`;
860
+ const key = tid || `t${Date.now()}`;
536
861
  const placeholder = bashIntent(cmd);
537
- emit({ kind: "tool", sid, tid, text: placeholder });
538
- const leak = sessions.get(sid)?.seg || "";
862
+ emit({ kind: "tool", sid, tid: key, text: placeholder });
863
+ const leak = s.seg || "";
539
864
  cmdIntent(ctx, cmd, leak)
540
865
  .then((said) => {
541
- if (said && said !== placeholder) emit({ kind: "tool-intent", sid, tid, text: said });
866
+ if (said && said !== placeholder) emit({ kind: "tool-intent", sid, tid: key, text: said });
542
867
  })
543
868
  .catch(() => {});
544
869
  return;
545
870
  }
546
- emit({ kind: "tool", sid, text: describeTool(name, event?.args) });
871
+ {
872
+ const key = tid || `t${Date.now()}`;
873
+ const placeholder = describeTool(name, event?.args);
874
+ emit({ kind: "tool", sid, tid: key, text: placeholder });
875
+ // 规则版只说了「在文件里找 xxx」,再让模型说清在什么里找什么、为了啥
876
+ toolIntent(ctx, name, event?.args, s.seg || "")
877
+ .then((said) => {
878
+ if (said && said !== placeholder) emit({ kind: "tool-intent", sid, tid: key, text: said });
879
+ })
880
+ .catch(() => {});
881
+ }
882
+ });
883
+
884
+ // 工具跑完了:告诉前端这一行的成败与耗时(成败和耗时都由 pi 自己测,不用前端算)
885
+ pi.on("tool_execution_end", async (event: any, ctx: any) => {
886
+ if (!enabled) return;
887
+ const tid = String(event?.toolCallId || "");
888
+ if (!tid) return;
889
+ const sid = sidOf(ctx);
890
+ if (!claim(sid)) return;
891
+ const isErr = !!event?.isError;
892
+ if (isErr) {
893
+ const s = sessions.get(sid);
894
+ if (s) s.fails++;
895
+ }
896
+ emit({
897
+ kind: "tool-end",
898
+ sid,
899
+ tid,
900
+ ok: !isErr,
901
+ ms:
902
+ typeof event?.durationMs === "number" && event.durationMs >= 0
903
+ ? Math.round(event.durationMs)
904
+ : null,
905
+ });
547
906
  });
548
907
 
549
908
  pi.on("agent_start", async (_event: any, ctx: any) => {
550
909
  const s = sess(ctx);
551
910
  s.seg = "";
911
+ s.t0 = Date.now();
912
+ s.tools = 0;
913
+ s.fails = 0;
914
+ s.names = [];
915
+ s.history = []; // 新一轮重新起一条线,别接着上一轮的尾巴
552
916
  emit({ kind: "start", sid: sidOf(ctx) });
553
917
  });
554
918
 
555
919
  pi.on("agent_end", async (_event: any, ctx: any) => {
556
920
  const s = sess(ctx);
557
- flushSeg(s, sidOf(ctx));
558
- emit({ kind: "end", sid: sidOf(ctx) });
921
+ const sid = sidOf(ctx);
922
+ // 收尾不让 claim 挡:两份实例都可能收到 agent_end,靠下面的幂等去重
923
+ SHARED.recent.push(`${new Date().toTimeString().slice(0, 8)} agent_end-enter sid=${sid.slice(0, 8)} inst=${INSTANCE}`);
924
+ if (SHARED.recent.length > 40) SHARED.recent.shift();
925
+ flushSeg(s, sid);
926
+ const info = {
927
+ ms: s.t0 ? Date.now() - s.t0 : 0,
928
+ steps: s.tools,
929
+ fails: s.fails,
930
+ names: s.names.slice(0, 20),
931
+ };
932
+ s.t0 = 0;
933
+ s.tools = 0;
934
+ s.fails = 0;
935
+ s.names = [];
936
+ emit({ kind: "end", sid });
937
+ // 一轮只发一条结论:两份实例都跑 agent_end 时只留第一条
938
+ const nowS = Date.now();
939
+ if (SHARED.lastSummary && SHARED.lastSummary.sid === sid && nowS - SHARED.lastSummary.t < 15000) return;
940
+ SHARED.lastSummary = { sid, t: nowS };
941
+ // 结论异步补发:先让条子切到“收尾”,模型慢也不堵这一轮
942
+ roundSummary(ctx, info)
943
+ .then((text) => {
944
+ if (text) emit({ kind: "summary", sid, text, ms: info.ms, steps: info.steps, fails: info.fails });
945
+ })
946
+ .catch(() => {});
559
947
  });
560
948
 
561
949
  const liveCmd = {
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@duanz/pi-d-live",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "把模型思考与工具调用实时改写成内心独白,推到 pi-web 界面顶部浮层",
5
5
  "type": "module",
6
6
  "keywords": [
7
7
  "pi-package",
8
- "pi-extension"
8
+ "pi-extension",
9
+ "pi-web"
9
10
  ],
10
11
  "license": "MIT",
11
12
  "author": "DuanZ",
@@ -16,12 +17,15 @@
16
17
  "directory": "extensions/d-live"
17
18
  },
18
19
  "files": [
19
- "index.ts"
20
+ "index.ts",
21
+ "README.md",
22
+ "README.en.md"
20
23
  ],
21
24
  "pi": {
22
25
  "extensions": [
23
26
  "./index.ts"
24
- ]
27
+ ],
28
+ "image": "https://raw.githubusercontent.com/DuanZGit/D-Hub/master/docs/covers/d-live.png"
25
29
  },
26
30
  "engines": {
27
31
  "node": ">=20"