@duanz/pi-d-live 1.0.0 → 1.1.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/README.en.md +60 -0
- package/README.md +61 -0
- package/index.ts +461 -50
- 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 =
|
|
22
|
-
const MAX_SEG =
|
|
23
|
-
const MAX_LINES =
|
|
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 =
|
|
27
|
+
const REWRITE_TIMEOUT = 25000; // 单次改写硬超时(段变长后模型更慢)
|
|
26
28
|
|
|
27
|
-
|
|
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
|
-
- 每句
|
|
33
|
-
-
|
|
88
|
+
- 说人话,像朋友在旁边随口讲一句,带点画面感,可以用「先翻翻」「挨个对一遍」「这就去」「稳了」这类口语;语气轻快些,带点小惊喜小得意,像「哟,这几份正好对上了」「顺手就捋顺了」「好家伙,藏得还挺深」这种;
|
|
89
|
+
- 不用第一人称,不出现"我";用无主语或"正在/已经/接下来/这就"开头;
|
|
90
|
+
- 每句 16~22 字,把前因后果说完整:先说要做什么或看到什么,再说为什么这么选;
|
|
91
|
+
- 最多 ${MAX_LINES} 句,每句一行;句尾必须有标点(…… / 。 / !);每句带 1~2 个 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
|
-
|
|
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
|
|
194
|
-
|
|
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
|
-
规则:
|
|
285
|
+
用一句中文说出这条命令的**意图**:在哪找什么、想确认什么、为了什么。要具体到对象,别只说「查一下」「跑一下」这种空话,说得口语、有画面感。
|
|
286
|
+
规则:24 字以内;句尾加标点(…… 或 。);带 1~2 个贴切的 emoji,句中穿插或句尾收一下都行,让语气轻快些;不要出现命令名、参数、端口、缩写字母(文件名可以保留);不要引号和编号。
|
|
219
287
|
只输出这一句话。`;
|
|
220
288
|
|
|
221
289
|
/** 让模型说清这条命令到底想干嘛;超时或失败返回空串,由 bashIntent 规则兜底。 */
|
|
@@ -256,34 +324,204 @@ async function cmdIntent(ctx: any, cmd: string, hint = ""): Promise<string> {
|
|
|
256
324
|
}
|
|
257
325
|
}
|
|
258
326
|
|
|
327
|
+
const TOOL_SYS = `你看到的是 AI 助手刚要做的一件事(工具名 + 参数),以及它动手前的想法。
|
|
328
|
+
用一句中文说清:在什么里面、找什么/看什么/改什么、想确认什么、为了什么。要具体到对象,别只说「看文件」「搜一下」这种空话。
|
|
329
|
+
规则:24 字以内;句尾加标点(…… 或 。);带 1~2 个贴切的 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 字以内;说结果,不说过程;口语一点、带点小得意,别用「已完成」「进行处理」这类空话;不出现文件名、路径、命令、缩写字母;不加引号编号;带 1~2 个贴切的 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
|
-
|
|
267
|
-
|
|
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
|
+
lastDropAt: 0,
|
|
466
|
+
listening: false,
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
const sessions: Map<string, Sess> = SHARED.sessions;
|
|
470
|
+
const clients: Set<ServerResponse> = SHARED.clients;
|
|
268
471
|
/** 每个 SSE 连接上报的会话 id,仅用于诊断串会话问题 */
|
|
269
|
-
const clientSids
|
|
472
|
+
const clientSids: Map<ServerResponse, string> = SHARED.clientSids;
|
|
270
473
|
/** 前端启动阶段上报,用来判断脚本跑到哪一步 */
|
|
271
|
-
const pings: string[] =
|
|
474
|
+
const pings: string[] = SHARED.pings;
|
|
475
|
+
const recent: string[] = SHARED.recent;
|
|
272
476
|
let enabled = true;
|
|
273
477
|
|
|
478
|
+
const lastSidDebug: Record<string, string> = {};
|
|
479
|
+
|
|
480
|
+
// 工具事件的 ctx 不一定带 sessionManager,记住最近一次真实会话,别让推送退化成 default 被过滤掉
|
|
481
|
+
let lastRealSid = "";
|
|
482
|
+
|
|
274
483
|
function sidOf(ctx: any): string {
|
|
275
484
|
try {
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
485
|
+
const sm = ctx?.sessionManager;
|
|
486
|
+
const byApi = String(sm?.getSessionId?.() || "");
|
|
487
|
+
const file = String(sm?.getSessionFile?.() || sm?.getSessionPath?.() || "");
|
|
488
|
+
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$/);
|
|
489
|
+
lastSidDebug.api = byApi;
|
|
490
|
+
lastSidDebug.file = file;
|
|
491
|
+
lastSidDebug.picked = m ? m[1] : byApi;
|
|
492
|
+
const real = m ? m[1] : byApi;
|
|
493
|
+
if (real) {
|
|
494
|
+
lastRealSid = real;
|
|
495
|
+
return real;
|
|
496
|
+
}
|
|
497
|
+
} catch {}
|
|
498
|
+
return lastRealSid || "default";
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
const INSTANCE = Math.random().toString(36).slice(2, 8);
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* 同一会话只让一份扩展实例处理事件。
|
|
505
|
+
* pi-web 会为同一个会话加载多份扩展,不去重的话模型改写、工具意图都会重复跑两遍。
|
|
506
|
+
* 所有者带心跳:真正在收事件的实例每次调 claim 都会刷新时间;重启接力遗留的
|
|
507
|
+
* 死实例不再刷新,超过 CLAIM_TTL 就让活着的实例接管,不然整条思考条会被静默挡死。
|
|
508
|
+
*/
|
|
509
|
+
const CLAIM_TTL = 8000;
|
|
510
|
+
|
|
511
|
+
function claim(sid: string): boolean {
|
|
512
|
+
if (!SHARED.owner) SHARED.owner = new Map<string, any>();
|
|
513
|
+
const now = Date.now();
|
|
514
|
+
const cur = SHARED.owner.get(sid);
|
|
515
|
+
if (cur && cur.inst !== INSTANCE && now - (cur.at || 0) < CLAIM_TTL) return false;
|
|
516
|
+
SHARED.owner.set(sid, { inst: INSTANCE, at: now });
|
|
517
|
+
return true;
|
|
280
518
|
}
|
|
281
519
|
|
|
282
520
|
function sess(ctx: any): Sess {
|
|
283
521
|
const sid = sidOf(ctx);
|
|
284
522
|
let s = sessions.get(sid);
|
|
285
523
|
if (!s) {
|
|
286
|
-
s = { seg: "", ctx, chain: Promise.resolve(), pending: 0 };
|
|
524
|
+
s = { seg: "", ctx, chain: Promise.resolve(), pending: 0, t0: 0, tools: 0, fails: 0, names: [], history: [] };
|
|
287
525
|
sessions.set(sid, s);
|
|
288
526
|
}
|
|
289
527
|
s.ctx = ctx;
|
|
@@ -291,12 +529,49 @@ function sess(ctx: any): Sess {
|
|
|
291
529
|
}
|
|
292
530
|
|
|
293
531
|
function emit(payload: Record<string, unknown>) {
|
|
532
|
+
try {
|
|
533
|
+
// pi-web 同一个会话可能加载两份扩展(重启接力时),两份 handler 都连着共享的 clients,
|
|
534
|
+
// 不去重的话每条推送会发两次。
|
|
535
|
+
const key = `${String(payload.sid || "")}|${String(payload.kind)}|${String(payload.tid || "")}|${String(payload.text || "")}`;
|
|
536
|
+
const now = Date.now();
|
|
537
|
+
const last = SHARED.lastEmit;
|
|
538
|
+
if (last && last.k === key && now - last.t < 150) return;
|
|
539
|
+
SHARED.lastEmit = { k: key, t: now };
|
|
540
|
+
const t = new Date().toTimeString().slice(0, 8);
|
|
541
|
+
// effort 每秒都在蹦,留着会把别的播报挤出去,诊断时看不见
|
|
542
|
+
if (String(payload.kind) !== "effort") {
|
|
543
|
+
recent.push(`${t} ${String(payload.kind)} sid=${String(payload.sid || "-").slice(0, 8)}`);
|
|
544
|
+
if (recent.length > 60) recent.splice(0, recent.length - 60);
|
|
545
|
+
}
|
|
546
|
+
} catch {}
|
|
294
547
|
const line = `data: ${JSON.stringify(payload)}\n\n`;
|
|
548
|
+
const sid = typeof payload.sid === "string" ? payload.sid : "";
|
|
549
|
+
const unknown = !sid || sid === "default";
|
|
295
550
|
for (const c of clients) {
|
|
551
|
+
// 只推给「报了号且号对得上」的页面:空号连接(旧版页面)一律不推,
|
|
552
|
+
// 否则一个页面会收到所有会话的播报,串到别的会话里。
|
|
553
|
+
const want = clientSids.get(c) || "";
|
|
554
|
+
if (!want) continue;
|
|
555
|
+
if (!unknown && want !== sid) {
|
|
556
|
+
// 诊断:事件被号不对的连接挡下来时记一条(10 秒最多一条),
|
|
557
|
+
// 「条子不出现」时能一眼看出是页面连错号还是根本没事件
|
|
558
|
+
const stamp = Date.now();
|
|
559
|
+
if (stamp - (SHARED.lastDropAt || 0) > 10000) {
|
|
560
|
+
SHARED.lastDropAt = stamp;
|
|
561
|
+
try {
|
|
562
|
+
recent.push(
|
|
563
|
+
`${new Date(stamp).toTimeString().slice(0, 8)} drop sid=${sid.slice(0, 8)} want=${want.slice(0, 8)}`,
|
|
564
|
+
);
|
|
565
|
+
if (recent.length > 60) recent.splice(0, recent.length - 60);
|
|
566
|
+
} catch {}
|
|
567
|
+
}
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
296
570
|
try {
|
|
297
571
|
c.write(line);
|
|
298
572
|
} catch {
|
|
299
573
|
clients.delete(c);
|
|
574
|
+
clientSids.delete(c);
|
|
300
575
|
}
|
|
301
576
|
}
|
|
302
577
|
}
|
|
@@ -331,10 +606,41 @@ function shouldCut(s: string): boolean {
|
|
|
331
606
|
return false;
|
|
332
607
|
}
|
|
333
608
|
|
|
609
|
+
// 系统注入的上下文(压缩块、记忆注入)长得像“思考”,但不是,不能播给用户
|
|
610
|
+
const NOISE =
|
|
611
|
+
/(CONTEXT BREAKDOWN|COMPRESSED BLOCKS|openviking-context|OpenViking context|\[ACP\]|Compressed m\d|<acp\b|viking:\/\/|User said \(m\d)/i;
|
|
612
|
+
/** 一句太长就按标点切成两句:一行放得下才不用缩字或换行 */
|
|
613
|
+
function splitLong(line: string, max = 22): string[] {
|
|
614
|
+
let rest = String(line || "").trim();
|
|
615
|
+
if (!rest) return [];
|
|
616
|
+
const out: string[] = [];
|
|
617
|
+
while (rest.length > max) {
|
|
618
|
+
const head = rest.slice(0, max);
|
|
619
|
+
let cut = -1;
|
|
620
|
+
for (let i = head.length - 1; i >= 8; i--) {
|
|
621
|
+
if (",,、;;::。!?!?".includes(head[i])) {
|
|
622
|
+
cut = i;
|
|
623
|
+
break;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
if (cut < 0) cut = max - 1;
|
|
627
|
+
const piece = rest.slice(0, cut + 1).replace(/[,,、;;::\s]+$/, "");
|
|
628
|
+
out.push(/[。!?!?]$/.test(piece) ? piece : piece + "。");
|
|
629
|
+
rest = rest.slice(cut + 1).trim();
|
|
630
|
+
}
|
|
631
|
+
if (rest) out.push(/[。!?!?]$/.test(rest) ? rest : rest + "。");
|
|
632
|
+
return out;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
function isNoise(text: string): boolean {
|
|
636
|
+
return NOISE.test(text);
|
|
637
|
+
}
|
|
638
|
+
|
|
334
639
|
function flushSeg(s: Sess, sid: string) {
|
|
335
640
|
const text = s.seg.trim();
|
|
336
641
|
s.seg = "";
|
|
337
642
|
if (text.length < 8) return;
|
|
643
|
+
if (isNoise(text)) return; // 系统注入的上下文不是思考,直接丢
|
|
338
644
|
rewrite(s, sid, text);
|
|
339
645
|
}
|
|
340
646
|
|
|
@@ -374,6 +680,10 @@ function rewrite(s: Sess, sid: string, text: string) {
|
|
|
374
680
|
const ctx = s.ctx;
|
|
375
681
|
const model = pickModel(ctx);
|
|
376
682
|
if (!model) return;
|
|
683
|
+
const prior = s.history.slice(-4);
|
|
684
|
+
const lead = prior.length
|
|
685
|
+
? "前面已经说过(接着往下讲,别重复):\n" + prior.join("\n") + "\n\n这一段新的思考:\n"
|
|
686
|
+
: "";
|
|
377
687
|
try {
|
|
378
688
|
const res: any = await Promise.race([
|
|
379
689
|
ctx.modelRegistry.complete(
|
|
@@ -383,7 +693,7 @@ function rewrite(s: Sess, sid: string, text: string) {
|
|
|
383
693
|
messages: [
|
|
384
694
|
{
|
|
385
695
|
role: "user",
|
|
386
|
-
content: [{ type: "text", text }],
|
|
696
|
+
content: [{ type: "text", text: lead + text }],
|
|
387
697
|
timestamp: Date.now(),
|
|
388
698
|
},
|
|
389
699
|
],
|
|
@@ -410,14 +720,21 @@ function rewrite(s: Sess, sid: string, text: string) {
|
|
|
410
720
|
// 过滤照抄的噪声:带代码/表格符号、英文术语、长数字的行一律不要
|
|
411
721
|
.filter(
|
|
412
722
|
(line: string) =>
|
|
413
|
-
line.length
|
|
414
|
-
line.length <=
|
|
723
|
+
line.length >= 8 &&
|
|
724
|
+
line.length <= 40 &&
|
|
725
|
+
!isNoise(line) &&
|
|
415
726
|
!/[|[\]{}%#=<>_\\]/.test(line) &&
|
|
416
727
|
!/\b(?:acp|api|json|sse|css|html|ctx|sid|pid|url|http|localhost|status|result|delta|token)\b/i.test(line) &&
|
|
417
728
|
!/\d{3,}/.test(line),
|
|
418
729
|
)
|
|
419
730
|
.slice(0, MAX_LINES);
|
|
420
|
-
if (lines.length)
|
|
731
|
+
if (lines.length) {
|
|
732
|
+
// 一条播报只放一句能塞进一行的:太长的按标点切成两句,免得手机上前端被迫缩字换行
|
|
733
|
+
const capped: string[] = [];
|
|
734
|
+
for (const line of lines) for (const piece of splitLong(line)) capped.push(piece);
|
|
735
|
+
emit({ kind: "lines", sid, lines: capped });
|
|
736
|
+
s.history = s.history.concat(capped).slice(-8);
|
|
737
|
+
}
|
|
421
738
|
} catch (e: any) {
|
|
422
739
|
const name = String(e?.name || "");
|
|
423
740
|
if (name !== "AbortError") {
|
|
@@ -460,8 +777,10 @@ function startServer() {
|
|
|
460
777
|
}
|
|
461
778
|
if (url.startsWith("/ping")) {
|
|
462
779
|
const qq = url.includes("?") ? new URLSearchParams(url.slice(url.indexOf("?") + 1)) : null;
|
|
463
|
-
pings.push(
|
|
464
|
-
|
|
780
|
+
pings.push(
|
|
781
|
+
`${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)}`,
|
|
782
|
+
);
|
|
783
|
+
if (pings.length > 40) pings.shift();
|
|
465
784
|
res.writeHead(204);
|
|
466
785
|
res.end();
|
|
467
786
|
return;
|
|
@@ -479,7 +798,9 @@ function startServer() {
|
|
|
479
798
|
pending,
|
|
480
799
|
clientSids: [...clientSids.values()],
|
|
481
800
|
pings,
|
|
801
|
+
sidDebug: lastSidDebug,
|
|
482
802
|
serverSids: [...sessions.keys()],
|
|
803
|
+
recent,
|
|
483
804
|
}),
|
|
484
805
|
);
|
|
485
806
|
return;
|
|
@@ -487,31 +808,48 @@ function startServer() {
|
|
|
487
808
|
res.writeHead(404);
|
|
488
809
|
res.end();
|
|
489
810
|
});
|
|
490
|
-
|
|
491
|
-
|
|
811
|
+
// pi-web 每个会话都会加载一份扩展;端口只能被第一份占到。
|
|
812
|
+
// 重复绑定是正常的,不能让它打断这个会话里后面的 pi.on(...) 注册。
|
|
813
|
+
server.on("error", (e: any) => {
|
|
814
|
+
if (e?.code === "EADDRINUSE") return;
|
|
492
815
|
});
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
clients.delete(c);
|
|
500
|
-
}
|
|
816
|
+
if (!SHARED.listening) {
|
|
817
|
+
SHARED.listening = true;
|
|
818
|
+
try {
|
|
819
|
+
server.listen(PORT, "127.0.0.1");
|
|
820
|
+
} catch {
|
|
821
|
+
SHARED.listening = false;
|
|
501
822
|
}
|
|
502
|
-
}
|
|
503
|
-
|
|
823
|
+
}
|
|
824
|
+
// 心跳只挂一份:每个会话都会加载一份扩展,无条件起定时器会变成 N 份重复推送
|
|
825
|
+
if (!SHARED.beat) {
|
|
826
|
+
const timer = setInterval(() => {
|
|
827
|
+
for (const c of clients) {
|
|
828
|
+
try {
|
|
829
|
+
// 不只是保活:前端把这条当心跳,收不到就自己重连
|
|
830
|
+
c.write('data: {"kind":"beat"}\n\n');
|
|
831
|
+
} catch {
|
|
832
|
+
clients.delete(c);
|
|
833
|
+
clientSids.delete(c);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
}, 15000);
|
|
837
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
838
|
+
SHARED.beat = timer;
|
|
839
|
+
}
|
|
504
840
|
}
|
|
505
841
|
|
|
506
842
|
export default function piWebLive(pi: ExtensionAPI) {
|
|
507
843
|
startServer();
|
|
844
|
+
startEffortWatcher(emit);
|
|
508
845
|
|
|
509
846
|
pi.on("message_update", async (event: any, ctx: any) => {
|
|
510
847
|
if (!enabled) return;
|
|
511
848
|
const ev = event?.assistantMessageEvent;
|
|
512
849
|
if (!ev) return;
|
|
513
|
-
const s = sess(ctx);
|
|
514
850
|
const sid = sidOf(ctx);
|
|
851
|
+
if (!claim(sid)) return;
|
|
852
|
+
const s = sess(ctx);
|
|
515
853
|
if (ev.type === "thinking_delta" && typeof ev.delta === "string") {
|
|
516
854
|
s.seg += ev.delta;
|
|
517
855
|
if (shouldCut(s.seg)) flushSeg(s, sid);
|
|
@@ -528,34 +866,107 @@ export default function piWebLive(pi: ExtensionAPI) {
|
|
|
528
866
|
pi.on("tool_execution_start", async (event: any, ctx: any) => {
|
|
529
867
|
if (!enabled) return;
|
|
530
868
|
const sid = sidOf(ctx);
|
|
869
|
+
if (!claim(sid)) return;
|
|
531
870
|
const name = event?.toolName || "";
|
|
871
|
+
const tid = String(event?.toolCallId || "");
|
|
872
|
+
const s = sess(ctx);
|
|
873
|
+
s.tools++;
|
|
874
|
+
if (name) s.names.push(name);
|
|
532
875
|
if (name === "bash") {
|
|
533
876
|
// 先用规则版即时占位(零延迟),模型算出真正的意图后再把那一行改写掉
|
|
534
877
|
const cmd = event?.args?.command;
|
|
535
|
-
const
|
|
878
|
+
const key = tid || `t${Date.now()}`;
|
|
536
879
|
const placeholder = bashIntent(cmd);
|
|
537
|
-
emit({ kind: "tool", sid, tid, text: placeholder });
|
|
538
|
-
const leak =
|
|
880
|
+
emit({ kind: "tool", sid, tid: key, text: placeholder });
|
|
881
|
+
const leak = s.seg || "";
|
|
539
882
|
cmdIntent(ctx, cmd, leak)
|
|
540
883
|
.then((said) => {
|
|
541
|
-
if (said && said !== placeholder) emit({ kind: "tool-intent", sid, tid, text: said });
|
|
884
|
+
if (said && said !== placeholder) emit({ kind: "tool-intent", sid, tid: key, text: said });
|
|
542
885
|
})
|
|
543
886
|
.catch(() => {});
|
|
544
887
|
return;
|
|
545
888
|
}
|
|
546
|
-
|
|
889
|
+
{
|
|
890
|
+
const key = tid || `t${Date.now()}`;
|
|
891
|
+
const placeholder = describeTool(name, event?.args);
|
|
892
|
+
emit({ kind: "tool", sid, tid: key, text: placeholder });
|
|
893
|
+
// 规则版只说了「在文件里找 xxx」,再让模型说清在什么里找什么、为了啥
|
|
894
|
+
toolIntent(ctx, name, event?.args, s.seg || "")
|
|
895
|
+
.then((said) => {
|
|
896
|
+
if (said && said !== placeholder) emit({ kind: "tool-intent", sid, tid: key, text: said });
|
|
897
|
+
})
|
|
898
|
+
.catch(() => {});
|
|
899
|
+
}
|
|
900
|
+
});
|
|
901
|
+
|
|
902
|
+
// 工具跑完了:告诉前端这一行的成败与耗时(成败和耗时都由 pi 自己测,不用前端算)
|
|
903
|
+
pi.on("tool_execution_end", async (event: any, ctx: any) => {
|
|
904
|
+
if (!enabled) return;
|
|
905
|
+
const tid = String(event?.toolCallId || "");
|
|
906
|
+
if (!tid) return;
|
|
907
|
+
const sid = sidOf(ctx);
|
|
908
|
+
if (!claim(sid)) return;
|
|
909
|
+
const isErr = !!event?.isError;
|
|
910
|
+
if (isErr) {
|
|
911
|
+
const s = sessions.get(sid);
|
|
912
|
+
if (s) s.fails++;
|
|
913
|
+
}
|
|
914
|
+
emit({
|
|
915
|
+
kind: "tool-end",
|
|
916
|
+
sid,
|
|
917
|
+
tid,
|
|
918
|
+
ok: !isErr,
|
|
919
|
+
ms:
|
|
920
|
+
typeof event?.durationMs === "number" && event.durationMs >= 0
|
|
921
|
+
? Math.round(event.durationMs)
|
|
922
|
+
: null,
|
|
923
|
+
});
|
|
547
924
|
});
|
|
548
925
|
|
|
549
926
|
pi.on("agent_start", async (_event: any, ctx: any) => {
|
|
550
927
|
const s = sess(ctx);
|
|
551
928
|
s.seg = "";
|
|
552
|
-
|
|
929
|
+
s.t0 = Date.now();
|
|
930
|
+
s.tools = 0;
|
|
931
|
+
s.fails = 0;
|
|
932
|
+
s.names = [];
|
|
933
|
+
s.history = []; // 新一轮重新起一条线,别接着上一轮的尾巴
|
|
934
|
+
const sid = sidOf(ctx);
|
|
935
|
+
// 安全重启接力后,同一个会话可能同时挂着两份扩展实例;claim() 只认第一个登记
|
|
936
|
+
// 的所有者,万一那份是重启前不再收事件的旧实例,后面 message_update / tool_* 全被
|
|
937
|
+
// 静默挡掉,只剩开局一下就没动静了。谁真正在驱动这一轮,谁直接拿走这个 sid。
|
|
938
|
+
if (SHARED.owner) SHARED.owner.set(sid, { inst: INSTANCE, at: Date.now() });
|
|
939
|
+
emit({ kind: "start", sid });
|
|
553
940
|
});
|
|
554
941
|
|
|
555
942
|
pi.on("agent_end", async (_event: any, ctx: any) => {
|
|
556
943
|
const s = sess(ctx);
|
|
557
|
-
|
|
558
|
-
|
|
944
|
+
const sid = sidOf(ctx);
|
|
945
|
+
// 收尾不让 claim 挡:两份实例都可能收到 agent_end,靠下面的幂等去重
|
|
946
|
+
SHARED.recent.push(`${new Date().toTimeString().slice(0, 8)} agent_end-enter sid=${sid.slice(0, 8)} inst=${INSTANCE}`);
|
|
947
|
+
if (SHARED.recent.length > 40) SHARED.recent.shift();
|
|
948
|
+
flushSeg(s, sid);
|
|
949
|
+
const info = {
|
|
950
|
+
ms: s.t0 ? Date.now() - s.t0 : 0,
|
|
951
|
+
steps: s.tools,
|
|
952
|
+
fails: s.fails,
|
|
953
|
+
names: s.names.slice(0, 20),
|
|
954
|
+
};
|
|
955
|
+
s.t0 = 0;
|
|
956
|
+
s.tools = 0;
|
|
957
|
+
s.fails = 0;
|
|
958
|
+
s.names = [];
|
|
959
|
+
emit({ kind: "end", sid });
|
|
960
|
+
// 一轮只发一条结论:两份实例都跑 agent_end 时只留第一条
|
|
961
|
+
const nowS = Date.now();
|
|
962
|
+
if (SHARED.lastSummary && SHARED.lastSummary.sid === sid && nowS - SHARED.lastSummary.t < 15000) return;
|
|
963
|
+
SHARED.lastSummary = { sid, t: nowS };
|
|
964
|
+
// 结论异步补发:先让条子切到“收尾”,模型慢也不堵这一轮
|
|
965
|
+
roundSummary(ctx, info)
|
|
966
|
+
.then((text) => {
|
|
967
|
+
if (text) emit({ kind: "summary", sid, text, ms: info.ms, steps: info.steps, fails: info.fails });
|
|
968
|
+
})
|
|
969
|
+
.catch(() => {});
|
|
559
970
|
});
|
|
560
971
|
|
|
561
972
|
const liveCmd = {
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@duanz/pi-d-live",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.1",
|
|
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"
|