@duanz/pi-d-live 0.0.0-stage → 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.
- package/README.en.md +60 -0
- package/README.md +60 -2
- package/index.ts +975 -0
- package/package.json +31 -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
CHANGED
|
@@ -1,3 +1,61 @@
|
|
|
1
|
-
#
|
|
1
|
+
# d-live
|
|
2
2
|
|
|
3
|
-
|
|
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
ADDED
|
@@ -0,0 +1,975 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-web-live —— 把模型思考与工具调用实时改写成「内心独白」,推给 pi-web 顶部浮层条。
|
|
3
|
+
*
|
|
4
|
+
* 数据流:
|
|
5
|
+
* pi agent 事件(thinking_delta / tool_execution_start)
|
|
6
|
+
* → 本扩展按句切段
|
|
7
|
+
* → ctx.modelRegistry.complete() 用当前会话模型改写成短句
|
|
8
|
+
* → 本地 SSE 服务(127.0.0.1:18999/live)推给浏览器
|
|
9
|
+
* → 注入到 pi-web 页面的浮层条按节奏播放
|
|
10
|
+
*
|
|
11
|
+
* 前端脚本在 cn-assets/pi-web-live.js,经 patches.json 的 inline 注入 sw.js。
|
|
12
|
+
* 多会话隔离:每条推送带 sid,前端只播当前会话的。
|
|
13
|
+
*
|
|
14
|
+
* 开关:/d-live on | off | status(/live 为兼容别名)
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
18
|
+
import { createServer, type ServerResponse } from "node:http";
|
|
19
|
+
import { openSync, readSync, closeSync, statSync, existsSync } from "node:fs";
|
|
20
|
+
import { join } from "node:path";
|
|
21
|
+
|
|
22
|
+
const PORT = 18999;
|
|
23
|
+
const MIN_SEG = 200; // 至少这么多字才允许按句号切(每段改写 ~2s,切太碎会刷屏)
|
|
24
|
+
const MAX_SEG = 500; // 硬上限,超过无条件切
|
|
25
|
+
const MAX_LINES = 3;
|
|
26
|
+
const MAX_PENDING = 4; // 队列上限,超了就丢新段,保证实时性
|
|
27
|
+
const REWRITE_TIMEOUT = 25000; // 单次改写硬超时(段变长后模型更慢)
|
|
28
|
+
|
|
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 = `把下面这段思考,改写成给用户看的进度解说:正在做什么、为什么要这么做、做完会怎样。
|
|
86
|
+
|
|
87
|
+
规则:
|
|
88
|
+
- 说人话,像朋友在旁边随口讲一句,带点画面感,可以用「先翻翻」「挨个对一遍」「这就去」「稳了」这类口语;
|
|
89
|
+
- 不用第一人称,不出现"我";用无主语或"正在/已经/接下来/这就"开头;
|
|
90
|
+
- 每句 16~22 字,把前因后果说完整:先说要做什么或看到什么,再说为什么这么选;
|
|
91
|
+
- 最多 ${MAX_LINES} 句,每句一行;句尾必须有标点(…… / 。 / !);emoji 随内容自然用,放句首、句中、句尾都行,也可以整句不放,种类跟着内容走,别老是那两三个,也别每句都放;
|
|
92
|
+
- 一轮里只围绕一个目标往前推,几句连起来要像同一条线:第二句起用「接着」「于是」「这下」「所以」「接下来」「顺手」这类词承接上一句,别忽然跳到无关的事,也别重复前面说过的内容;
|
|
93
|
+
- 输入里若给了「前面已经说过」,就从那儿接着往下说,把新的发现和下一步接上,不要另起炉灶;
|
|
94
|
+
- 同一段里别重复用同一个 emoji;句子要生动,避免「正在处理」「进行分析」这类空话;
|
|
95
|
+
- 不写文件名、函数名、端口、路径、命令、缩写字母(JS/CSS/SSE/API 这类),一律换成日常说法;
|
|
96
|
+
- 不加引号和编号,不模仿用户语气;
|
|
97
|
+
- 必须真的改写:禁止照抄原文里的任何句子、列表、表格、日志;原文里的工具输出直接跳过不写;
|
|
98
|
+
- 想不出内容就少写几句,不要凑数。
|
|
99
|
+
只输出这些短句,每句一行。`;
|
|
100
|
+
|
|
101
|
+
// 工具名 → 人话。不调模型,零延迟。
|
|
102
|
+
const TOOL_LABEL: Record<string, string> = {
|
|
103
|
+
read: "看一眼",
|
|
104
|
+
write: "写个文件",
|
|
105
|
+
edit: "改几行",
|
|
106
|
+
bash: "跑一条命令",
|
|
107
|
+
grep: "在文件里找",
|
|
108
|
+
find: "找文件",
|
|
109
|
+
ls: "看目录",
|
|
110
|
+
web_search: "上网搜",
|
|
111
|
+
fetch_content: "打开网页",
|
|
112
|
+
source_check: "核对说法",
|
|
113
|
+
get_search_content: "翻搜索结果",
|
|
114
|
+
d_reach: "上网查一下",
|
|
115
|
+
d_reach_fetch: "打开链接",
|
|
116
|
+
d_reach_social: "刷社交平台",
|
|
117
|
+
d_reach_decide: "看证据下判断",
|
|
118
|
+
d_reach_quota: "看还剩多少额度",
|
|
119
|
+
codemode: "连着做几步",
|
|
120
|
+
Agent: "派人去干",
|
|
121
|
+
get_subagent_result: "收手下结果",
|
|
122
|
+
steer_subagent: "给手下补话",
|
|
123
|
+
TaskCreate: "记个待办",
|
|
124
|
+
TaskUpdate: "更新待办",
|
|
125
|
+
TaskList: "看待办",
|
|
126
|
+
TaskGet: "读待办",
|
|
127
|
+
TaskClaim: "领一件事",
|
|
128
|
+
LoopCreate: "挂个定时",
|
|
129
|
+
LoopList: "看定时",
|
|
130
|
+
LoopUpdate: "改定时",
|
|
131
|
+
LoopDelete: "停定时",
|
|
132
|
+
MonitorCreate: "放后台跑",
|
|
133
|
+
MonitorList: "看后台进度",
|
|
134
|
+
MonitorStop: "停后台",
|
|
135
|
+
safe_restart: "重启服务",
|
|
136
|
+
d_restart: "重启服务",
|
|
137
|
+
skill_search: "找有没有现成的办法",
|
|
138
|
+
openviking_find: "翻记忆",
|
|
139
|
+
openviking_search: "搜记忆",
|
|
140
|
+
openviking_read: "读记忆",
|
|
141
|
+
openviking_remember: "记下来",
|
|
142
|
+
openviking_write: "写进记忆",
|
|
143
|
+
openviking_edit: "改记忆",
|
|
144
|
+
openviking_add_resource: "存份资料",
|
|
145
|
+
openviking_health: "看记忆好不好使",
|
|
146
|
+
visual_explainer: "画个解释页",
|
|
147
|
+
diagram: "画张图",
|
|
148
|
+
plan_mode_question: "问你怎么选",
|
|
149
|
+
plan_mode_complete: "交份计划",
|
|
150
|
+
request_secret: "跟你要个密钥",
|
|
151
|
+
WorkflowCreate: "搭条流程",
|
|
152
|
+
WorkflowTransition: "往下推一步",
|
|
153
|
+
WorkflowRevise: "改流程",
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const TOOL_ARG: Record<string, string[]> = {
|
|
157
|
+
read: ["path"],
|
|
158
|
+
write: ["path"],
|
|
159
|
+
edit: ["path"],
|
|
160
|
+
ls: ["path"],
|
|
161
|
+
grep: ["pattern"],
|
|
162
|
+
find: ["pattern"],
|
|
163
|
+
web_search: ["query"],
|
|
164
|
+
fetch_content: ["url"],
|
|
165
|
+
d_reach: ["query"],
|
|
166
|
+
d_reach_fetch: ["url"],
|
|
167
|
+
d_reach_social: ["query"],
|
|
168
|
+
skill_search: ["query"],
|
|
169
|
+
openviking_search: ["query"],
|
|
170
|
+
openviking_find: ["query"],
|
|
171
|
+
openviking_read: ["uris"],
|
|
172
|
+
openviking_write: ["uri"],
|
|
173
|
+
openviking_edit: ["uri"],
|
|
174
|
+
Agent: ["description"],
|
|
175
|
+
TaskCreate: ["subject"],
|
|
176
|
+
MonitorCreate: ["description"],
|
|
177
|
+
visual_explainer: ["topic"],
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
// bash 的命令翻成人话:这个命令是干嘛的,不是命令长什么样
|
|
181
|
+
const CMD_RULES: Array<[RegExp, string]> = [
|
|
182
|
+
[/\bsystemctl\s+(restart|reload|try-restart)\b/, "重启服务"],
|
|
183
|
+
[/\bsystemctl\s+(start|stop|enable|disable)\b/, "起停服务"],
|
|
184
|
+
[/\bsystemctl\s+status\b/, "查服务状态"],
|
|
185
|
+
[/\bsystemctl\s+(cat|show)\b/, "看服务配置"],
|
|
186
|
+
[/\bjournalctl\b/, "翻服务日志"],
|
|
187
|
+
[/\b(docker|podman)\b/, "动容器"],
|
|
188
|
+
[/\b(npm|pnpm|yarn|bun)\s+(i|install|add|update)\b/, "装依赖"],
|
|
189
|
+
[/\bgit\s+(commit|push|pull|checkout|merge|rebase|add)\b/, "动版本记录"],
|
|
190
|
+
[/\bgit\s+(log|diff|status|show)\b/, "看改了什么"],
|
|
191
|
+
[/\b(curl|wget|aria2c)\b/, "访问接口"],
|
|
192
|
+
[/\b(python3?|node|deno|bash|sh)\b\s+[^\s]*\.(py|js|mjs|ts|sh)\b/, "跑脚本"],
|
|
193
|
+
[/\b(sed\s+-n|head|tail|less|more|cat)\b/, "看文件内容"],
|
|
194
|
+
[/\b(grep|rg|ag|ack)\b/, "在文件里搜"],
|
|
195
|
+
[/\b(find|fd)\b/, "找文件"],
|
|
196
|
+
[/\b(ls|tree|eza|dir)\b/, "看目录"],
|
|
197
|
+
[/\b(cp|mv|rsync|scp)\b/, "搬文件"],
|
|
198
|
+
[/\brm\b/, "删东西"],
|
|
199
|
+
[/\b(chmod|chown|chgrp)\b/, "改权限"],
|
|
200
|
+
[/\b(ps|top|htop|ss|netstat|lsof|pgrep)\b/, "看进程和端口"],
|
|
201
|
+
[/\b(df|du|ncdu)\b/, "看磁盘"],
|
|
202
|
+
[/\bmkdir\b/, "建目录"],
|
|
203
|
+
[/\b(ssh|scp)\b/, "连远程机器"],
|
|
204
|
+
[/\b(pip|pip3|apt|apt-get|brew)\b/, "装软件"],
|
|
205
|
+
];
|
|
206
|
+
const CMD_WORDS = new Set([
|
|
207
|
+
"sudo", "systemctl", "journalctl", "docker", "podman", "curl", "wget", "aria2c",
|
|
208
|
+
"python3", "python", "node", "deno", "bash", "sh", "sed", "head", "tail", "less",
|
|
209
|
+
"more", "cat", "grep", "rg", "ag", "ack", "find", "fd", "ls", "tree", "eza", "dir",
|
|
210
|
+
"cp", "mv", "rsync", "scp", "rm", "chmod", "chown", "chgrp", "ps", "top", "htop",
|
|
211
|
+
"ss", "netstat", "lsof", "pgrep", "df", "du", "ncdu", "mkdir", "ssh", "pip", "pip3",
|
|
212
|
+
"apt", "apt-get", "brew", "git", "npm", "pnpm", "yarn", "bun", "echo", "test", "expr",
|
|
213
|
+
"restart", "reload", "start", "stop", "status", "install", "commit", "push", "pull",
|
|
214
|
+
]);
|
|
215
|
+
|
|
216
|
+
function baseName(x: string): string {
|
|
217
|
+
const b = x.split("/").filter(Boolean).pop() || x;
|
|
218
|
+
return b.replace(/\.(ts|tsx|js|jsx|mjs|cjs|json|md|py|css|html|ya?ml|sh|log|txt|db)$/i, "");
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** 从一条 bash 命令说出「在干什么、在找什么」,不显示命令原文。 */
|
|
222
|
+
export function bashIntent(cmd: unknown): string {
|
|
223
|
+
const c = String(cmd || "").trim();
|
|
224
|
+
if (!c) return "跑一条命令";
|
|
225
|
+
const args = c.split(/[\s|;&<>()]+/).filter(Boolean);
|
|
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));
|
|
230
|
+
|
|
231
|
+
// 搜内容:在 X 里找 Y
|
|
232
|
+
if (/\b(grep|rg|ag|ack)\b/.test(c)) {
|
|
233
|
+
const pat = rest.find((w) => /^["'].*["']$/.test(w)) || rest.find((w) => !/^(grep|rg|ag|ack)$/.test(w) && !w.includes("/"));
|
|
234
|
+
const file = rest.filter((w) => /\.[a-z]{2,4}$/i.test(w) && w.includes("."));
|
|
235
|
+
let p = pat ? pat.replace(/^["']|["']$/g, "") : "";
|
|
236
|
+
// 正则里带元字符的,别把符号本身当"要找的东西"
|
|
237
|
+
if (/[\\^$*+?\[\](){}|]/.test(p)) p = "";
|
|
238
|
+
const f = file.length ? baseName(file[file.length - 1]) : "";
|
|
239
|
+
if (p && f) return `在 ${f} 里找「${p}」`;
|
|
240
|
+
if (p) return `找「${p}」`;
|
|
241
|
+
if (f) return `在 ${f} 里翻`;
|
|
242
|
+
return "在文件里搜";
|
|
243
|
+
}
|
|
244
|
+
// 访问接口:看路径语义
|
|
245
|
+
if (/\bcurl\b/.test(c)) {
|
|
246
|
+
if (/health|ping|status/.test(c)) return "看看服务还活着没";
|
|
247
|
+
if (/\/live\b/.test(c)) return "接一段实时推送";
|
|
248
|
+
if (/\/api\//.test(c)) return "试一下接口通不通";
|
|
249
|
+
if (/login|auth|token/.test(c)) return "试登录";
|
|
250
|
+
return "访问一个接口";
|
|
251
|
+
}
|
|
252
|
+
// 跑脚本:说清是哪个脚本
|
|
253
|
+
const script = rest.find((w) => /\.(py|js|mjs|ts|sh)$/i.test(w));
|
|
254
|
+
if (script && /\b(python3?|node|bash|sh|deno)\b/.test(c)) return `跑 ${baseName(script)} 脚本`;
|
|
255
|
+
// 看文件内容:说清哪个文件
|
|
256
|
+
if (/\b(sed\s+-n|head|tail|less|more|cat)\b/.test(c)) {
|
|
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} 里的内容` : "看文件内容";
|
|
263
|
+
}
|
|
264
|
+
// 日志:说清哪个服务
|
|
265
|
+
if (/\bjournalctl\b/.test(c)) {
|
|
266
|
+
const svc = rest.filter((w) => /^[a-z][a-z0-9-]{2,}$/i.test(w) && !CMD_WORDS.has(w.toLowerCase())).pop();
|
|
267
|
+
return svc ? `翻 ${svc} 最近的日志` : "翻服务日志";
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
let label = "";
|
|
271
|
+
for (const [re, l] of CMD_RULES) {
|
|
272
|
+
if (re.test(c)) {
|
|
273
|
+
label = l;
|
|
274
|
+
break;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
if (!label) return "跑一条命令";
|
|
278
|
+
const target = rest
|
|
279
|
+
.filter((w) => /^[a-z][a-z0-9-]{3,}$/i.test(w) && !CMD_WORDS.has(w.toLowerCase()))
|
|
280
|
+
.pop();
|
|
281
|
+
return target ? `${label} · ${target}` : label;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const CMD_SYS = `你看到的是 AI 助手刚刚执行的一条命令,以及它执行前在想什么。
|
|
285
|
+
用一句中文说出这条命令的**意图**:在哪找什么、想确认什么、为了什么。要具体到对象,别只说「查一下」「跑一下」这种空话,说得口语、有画面感。
|
|
286
|
+
规则:24 字以内;句尾加标点(…… 或 。);emoji 可用可不用,用就贴切,别每句都放;不要出现命令名、参数、端口、缩写字母(文件名可以保留);不要引号和编号。
|
|
287
|
+
只输出这一句话。`;
|
|
288
|
+
|
|
289
|
+
/** 让模型说清这条命令到底想干嘛;超时或失败返回空串,由 bashIntent 规则兜底。 */
|
|
290
|
+
async function cmdIntent(ctx: any, cmd: string, hint = ""): Promise<string> {
|
|
291
|
+
const model = pickModel(ctx);
|
|
292
|
+
if (!model) return "";
|
|
293
|
+
const text = String(cmd || "").trim();
|
|
294
|
+
if (!text) return "";
|
|
295
|
+
try {
|
|
296
|
+
const res: any = await Promise.race([
|
|
297
|
+
ctx.modelRegistry.complete(
|
|
298
|
+
model,
|
|
299
|
+
{
|
|
300
|
+
systemPrompt: CMD_SYS,
|
|
301
|
+
messages: [
|
|
302
|
+
{
|
|
303
|
+
role: "user",
|
|
304
|
+
content: [
|
|
305
|
+
{ type: "text", text: (hint ? `他刚才在想:${hint.slice(-300)}\n\n` : "") + `执行的命令:${text.slice(0, 800)}` },
|
|
306
|
+
],
|
|
307
|
+
timestamp: Date.now(),
|
|
308
|
+
},
|
|
309
|
+
],
|
|
310
|
+
},
|
|
311
|
+
{ cacheRetention: "none" },
|
|
312
|
+
),
|
|
313
|
+
new Promise((r) => setTimeout(() => r(null), 5000)),
|
|
314
|
+
]);
|
|
315
|
+
if (!res) return "";
|
|
316
|
+
const out = (res.content || [])
|
|
317
|
+
.filter((c: any) => c.type === "text")
|
|
318
|
+
.map((c: any) => c.text)
|
|
319
|
+
.join("")
|
|
320
|
+
.trim();
|
|
321
|
+
return out.split("\n")[0].replace(/^[-•*\d.、)\s]+/, "").replace(/[""'']/g, "").slice(0, 40);
|
|
322
|
+
} catch {
|
|
323
|
+
return "";
|
|
324
|
+
}
|
|
325
|
+
}
|
|
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
|
+
|
|
439
|
+
type Sess = {
|
|
440
|
+
seg: string;
|
|
441
|
+
ctx: any;
|
|
442
|
+
chain: Promise<void>;
|
|
443
|
+
pending: number;
|
|
444
|
+
/** 本轮开始时间,用来算总耗时 */
|
|
445
|
+
t0: number;
|
|
446
|
+
/** 本轮工具步数与失败数 */
|
|
447
|
+
tools: number;
|
|
448
|
+
fails: number;
|
|
449
|
+
names: string[];
|
|
450
|
+
/** 本轮已经播过的短句,喂给下一次改写,让前后能接上 */
|
|
451
|
+
history: string[];
|
|
452
|
+
};
|
|
453
|
+
|
|
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;
|
|
470
|
+
/** 每个 SSE 连接上报的会话 id,仅用于诊断串会话问题 */
|
|
471
|
+
const clientSids: Map<ServerResponse, string> = SHARED.clientSids;
|
|
472
|
+
/** 前端启动阶段上报,用来判断脚本跑到哪一步 */
|
|
473
|
+
const pings: string[] = SHARED.pings;
|
|
474
|
+
const recent: string[] = SHARED.recent;
|
|
475
|
+
let enabled = true;
|
|
476
|
+
|
|
477
|
+
const lastSidDebug: Record<string, string> = {};
|
|
478
|
+
|
|
479
|
+
// 工具事件的 ctx 不一定带 sessionManager,记住最近一次真实会话,别让推送退化成 default 被过滤掉
|
|
480
|
+
let lastRealSid = "";
|
|
481
|
+
|
|
482
|
+
function sidOf(ctx: any): string {
|
|
483
|
+
try {
|
|
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;
|
|
512
|
+
}
|
|
513
|
+
return cur === INSTANCE;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
function sess(ctx: any): Sess {
|
|
517
|
+
const sid = sidOf(ctx);
|
|
518
|
+
let s = sessions.get(sid);
|
|
519
|
+
if (!s) {
|
|
520
|
+
s = { seg: "", ctx, chain: Promise.resolve(), pending: 0, t0: 0, tools: 0, fails: 0, names: [], history: [] };
|
|
521
|
+
sessions.set(sid, s);
|
|
522
|
+
}
|
|
523
|
+
s.ctx = ctx;
|
|
524
|
+
return s;
|
|
525
|
+
}
|
|
526
|
+
|
|
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 {}
|
|
543
|
+
const line = `data: ${JSON.stringify(payload)}\n\n`;
|
|
544
|
+
const sid = typeof payload.sid === "string" ? payload.sid : "";
|
|
545
|
+
const unknown = !sid || sid === "default";
|
|
546
|
+
for (const c of clients) {
|
|
547
|
+
// 只推给「报了号且号对得上」的页面:空号连接(旧版页面)一律不推,
|
|
548
|
+
// 否则一个页面会收到所有会话的播报,串到别的会话里。
|
|
549
|
+
const want = clientSids.get(c) || "";
|
|
550
|
+
if (!want) continue;
|
|
551
|
+
if (!unknown && want !== sid) continue;
|
|
552
|
+
try {
|
|
553
|
+
c.write(line);
|
|
554
|
+
} catch {
|
|
555
|
+
clients.delete(c);
|
|
556
|
+
clientSids.delete(c);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function shortName(p: unknown): string {
|
|
562
|
+
if (typeof p !== "string" || !p) return "";
|
|
563
|
+
const stripped = p.replace(/^https?:\/\/[^/]+\//, "");
|
|
564
|
+
const parts = stripped.split("/").filter(Boolean);
|
|
565
|
+
const base = parts.slice(-1)[0] || stripped;
|
|
566
|
+
// 去掉扩展名,少一个技术符号
|
|
567
|
+
return base.replace(/\.(ts|tsx|js|jsx|mjs|cjs|json|md|py|css|html|ya?ml|sh|db|log)$/i, "");
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
function describeTool(name: string, args: any): string {
|
|
571
|
+
if (name === "bash") return bashIntent(args?.command);
|
|
572
|
+
const label = TOOL_LABEL[name] || name;
|
|
573
|
+
const keys = TOOL_ARG[name] || [];
|
|
574
|
+
for (const k of keys) {
|
|
575
|
+
let v = args?.[k];
|
|
576
|
+
if (v === undefined || v === null) continue;
|
|
577
|
+
if (k === "path" || k === "url" || k === "uris") v = shortName(String(Array.isArray(v) ? v[0] : v));
|
|
578
|
+
let s = String(v).replace(/\s+/g, " ").trim();
|
|
579
|
+
if (s.length > 28) s = s.slice(0, 27) + "…";
|
|
580
|
+
return s ? `${label} ${s}` : label;
|
|
581
|
+
}
|
|
582
|
+
return label;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function shouldCut(s: string): boolean {
|
|
586
|
+
if (s.length >= MAX_SEG) return true;
|
|
587
|
+
if (s.length >= MIN_SEG && /[。!?!?\n]\s*$/.test(s)) return true;
|
|
588
|
+
return false;
|
|
589
|
+
}
|
|
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
|
+
|
|
621
|
+
function flushSeg(s: Sess, sid: string) {
|
|
622
|
+
const text = s.seg.trim();
|
|
623
|
+
s.seg = "";
|
|
624
|
+
if (text.length < 8) return;
|
|
625
|
+
if (isNoise(text)) return; // 系统注入的上下文不是思考,直接丢
|
|
626
|
+
rewrite(s, sid, text);
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** 改写用的模型:虚拟路由模型(如 group/df-jev)每轮都要先判档,实测 4–6 秒;
|
|
630
|
+
* 优先换同 provider 下的物理模型直连。用 PI_WEB_LIVE_MODEL=<provider>/<id> 可显式指定。 */
|
|
631
|
+
function pickModel(ctx: any) {
|
|
632
|
+
const cur = ctx?.model;
|
|
633
|
+
if (!cur) return null;
|
|
634
|
+
const reg = ctx?.modelRegistry;
|
|
635
|
+
const env = process.env.PI_WEB_LIVE_MODEL;
|
|
636
|
+
if (env && reg?.find) {
|
|
637
|
+
const i = env.indexOf("/");
|
|
638
|
+
const p = i > 0 ? env.slice(0, i) : cur.provider;
|
|
639
|
+
const id = i > 0 ? env.slice(i + 1) : env;
|
|
640
|
+
try {
|
|
641
|
+
const found = reg.find(p, id);
|
|
642
|
+
if (found) return found;
|
|
643
|
+
} catch {}
|
|
644
|
+
}
|
|
645
|
+
if (reg?.find && typeof cur.id === "string" && cur.id.startsWith("group/")) {
|
|
646
|
+
for (const cand of ["auto/dfmodel", cur.id.replace(/^group\//, "")]) {
|
|
647
|
+
try {
|
|
648
|
+
const found = reg.find(cur.provider, cand);
|
|
649
|
+
if (found) return found;
|
|
650
|
+
} catch {}
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
return cur;
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
function rewrite(s: Sess, sid: string, text: string) {
|
|
657
|
+
if (s.pending >= MAX_PENDING) return; // 追不上就丢,别积压
|
|
658
|
+
s.pending++;
|
|
659
|
+
s.chain = s.chain
|
|
660
|
+
.then(async () => {
|
|
661
|
+
if (!enabled) return;
|
|
662
|
+
const ctx = s.ctx;
|
|
663
|
+
const model = pickModel(ctx);
|
|
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
|
+
: "";
|
|
669
|
+
try {
|
|
670
|
+
const res: any = await Promise.race([
|
|
671
|
+
ctx.modelRegistry.complete(
|
|
672
|
+
model,
|
|
673
|
+
{
|
|
674
|
+
systemPrompt: SYS,
|
|
675
|
+
messages: [
|
|
676
|
+
{
|
|
677
|
+
role: "user",
|
|
678
|
+
content: [{ type: "text", text: lead + text }],
|
|
679
|
+
timestamp: Date.now(),
|
|
680
|
+
},
|
|
681
|
+
],
|
|
682
|
+
},
|
|
683
|
+
{ cacheRetention: "none" },
|
|
684
|
+
),
|
|
685
|
+
new Promise((_, rej) => {
|
|
686
|
+
const t = setTimeout(() => rej(new Error("rewrite timeout")), REWRITE_TIMEOUT);
|
|
687
|
+
if (typeof (t as any).unref === "function") (t as any).unref();
|
|
688
|
+
}),
|
|
689
|
+
]);
|
|
690
|
+
const out = (res?.content || [])
|
|
691
|
+
.filter((c: any) => c.type === "text")
|
|
692
|
+
.map((c: any) => c.text)
|
|
693
|
+
.join("");
|
|
694
|
+
const lines = out
|
|
695
|
+
.split("\n")
|
|
696
|
+
.map((line: string) =>
|
|
697
|
+
line
|
|
698
|
+
.replace(/^[-•*\d.、)\s]+/, "")
|
|
699
|
+
.replace(/^["「『]|["」』]$/g, "")
|
|
700
|
+
.trim(),
|
|
701
|
+
)
|
|
702
|
+
// 过滤照抄的噪声:带代码/表格符号、英文术语、长数字的行一律不要
|
|
703
|
+
.filter(
|
|
704
|
+
(line: string) =>
|
|
705
|
+
line.length >= 8 &&
|
|
706
|
+
line.length <= 40 &&
|
|
707
|
+
!isNoise(line) &&
|
|
708
|
+
!/[|[\]{}%#=<>_\\]/.test(line) &&
|
|
709
|
+
!/\b(?:acp|api|json|sse|css|html|ctx|sid|pid|url|http|localhost|status|result|delta|token)\b/i.test(line) &&
|
|
710
|
+
!/\d{3,}/.test(line),
|
|
711
|
+
)
|
|
712
|
+
.slice(0, MAX_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
|
+
}
|
|
720
|
+
} catch (e: any) {
|
|
721
|
+
const name = String(e?.name || "");
|
|
722
|
+
if (name !== "AbortError") {
|
|
723
|
+
emit({ kind: "warn", sid, message: String(e?.message || e).slice(0, 160) });
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
})
|
|
727
|
+
.finally(() => {
|
|
728
|
+
s.pending--;
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
function startServer() {
|
|
733
|
+
const server = createServer((req, res) => {
|
|
734
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
735
|
+
res.setHeader("Access-Control-Allow-Headers", "content-type");
|
|
736
|
+
if (req.method === "OPTIONS") {
|
|
737
|
+
res.writeHead(204);
|
|
738
|
+
res.end();
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
const url = req.url || "";
|
|
742
|
+
const q = url.includes("?") ? new URLSearchParams(url.slice(url.indexOf("?") + 1)) : null;
|
|
743
|
+
const askedSid = q?.get("sid") || "";
|
|
744
|
+
if (url.startsWith("/live")) {
|
|
745
|
+
res.writeHead(200, {
|
|
746
|
+
"Content-Type": "text/event-stream",
|
|
747
|
+
"Cache-Control": "no-cache, no-transform",
|
|
748
|
+
Connection: "keep-alive",
|
|
749
|
+
"X-Accel-Buffering": "no",
|
|
750
|
+
});
|
|
751
|
+
res.write(`data: ${JSON.stringify({ kind: "hello", enabled })}\n\n`);
|
|
752
|
+
clients.add(res);
|
|
753
|
+
clientSids.set(res, askedSid);
|
|
754
|
+
req.on("close", () => {
|
|
755
|
+
clients.delete(res);
|
|
756
|
+
clientSids.delete(res);
|
|
757
|
+
});
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
if (url.startsWith("/ping")) {
|
|
761
|
+
const qq = url.includes("?") ? new URLSearchParams(url.slice(url.indexOf("?") + 1)) : null;
|
|
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();
|
|
766
|
+
res.writeHead(204);
|
|
767
|
+
res.end();
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
if (url.startsWith("/health")) {
|
|
771
|
+
let pending = 0;
|
|
772
|
+
for (const s of sessions.values()) pending += s.pending;
|
|
773
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
774
|
+
res.end(
|
|
775
|
+
JSON.stringify({
|
|
776
|
+
ok: true,
|
|
777
|
+
enabled,
|
|
778
|
+
clients: clients.size,
|
|
779
|
+
sessions: sessions.size,
|
|
780
|
+
pending,
|
|
781
|
+
clientSids: [...clientSids.values()],
|
|
782
|
+
pings,
|
|
783
|
+
sidDebug: lastSidDebug,
|
|
784
|
+
serverSids: [...sessions.keys()],
|
|
785
|
+
recent,
|
|
786
|
+
}),
|
|
787
|
+
);
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
res.writeHead(404);
|
|
791
|
+
res.end();
|
|
792
|
+
});
|
|
793
|
+
// pi-web 每个会话都会加载一份扩展;端口只能被第一份占到。
|
|
794
|
+
// 重复绑定是正常的,不能让它打断这个会话里后面的 pi.on(...) 注册。
|
|
795
|
+
server.on("error", (e: any) => {
|
|
796
|
+
if (e?.code === "EADDRINUSE") return;
|
|
797
|
+
});
|
|
798
|
+
if (!SHARED.listening) {
|
|
799
|
+
SHARED.listening = true;
|
|
800
|
+
try {
|
|
801
|
+
server.listen(PORT, "127.0.0.1");
|
|
802
|
+
} catch {
|
|
803
|
+
SHARED.listening = false;
|
|
804
|
+
}
|
|
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
|
+
}
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
export default function piWebLive(pi: ExtensionAPI) {
|
|
825
|
+
startServer();
|
|
826
|
+
startEffortWatcher(emit);
|
|
827
|
+
|
|
828
|
+
pi.on("message_update", async (event: any, ctx: any) => {
|
|
829
|
+
if (!enabled) return;
|
|
830
|
+
const ev = event?.assistantMessageEvent;
|
|
831
|
+
if (!ev) return;
|
|
832
|
+
const sid = sidOf(ctx);
|
|
833
|
+
if (!claim(sid)) return;
|
|
834
|
+
const s = sess(ctx);
|
|
835
|
+
if (ev.type === "thinking_delta" && typeof ev.delta === "string") {
|
|
836
|
+
s.seg += ev.delta;
|
|
837
|
+
if (shouldCut(s.seg)) flushSeg(s, sid);
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
if (ev.type === "thinking_end") {
|
|
841
|
+
if (typeof ev.content === "string" && ev.content.trim().length > s.seg.trim().length) {
|
|
842
|
+
s.seg = ev.content;
|
|
843
|
+
}
|
|
844
|
+
flushSeg(s, sid);
|
|
845
|
+
}
|
|
846
|
+
});
|
|
847
|
+
|
|
848
|
+
pi.on("tool_execution_start", async (event: any, ctx: any) => {
|
|
849
|
+
if (!enabled) return;
|
|
850
|
+
const sid = sidOf(ctx);
|
|
851
|
+
if (!claim(sid)) return;
|
|
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);
|
|
857
|
+
if (name === "bash") {
|
|
858
|
+
// 先用规则版即时占位(零延迟),模型算出真正的意图后再把那一行改写掉
|
|
859
|
+
const cmd = event?.args?.command;
|
|
860
|
+
const key = tid || `t${Date.now()}`;
|
|
861
|
+
const placeholder = bashIntent(cmd);
|
|
862
|
+
emit({ kind: "tool", sid, tid: key, text: placeholder });
|
|
863
|
+
const leak = s.seg || "";
|
|
864
|
+
cmdIntent(ctx, cmd, leak)
|
|
865
|
+
.then((said) => {
|
|
866
|
+
if (said && said !== placeholder) emit({ kind: "tool-intent", sid, tid: key, text: said });
|
|
867
|
+
})
|
|
868
|
+
.catch(() => {});
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
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
|
+
});
|
|
906
|
+
});
|
|
907
|
+
|
|
908
|
+
pi.on("agent_start", async (_event: any, ctx: any) => {
|
|
909
|
+
const s = sess(ctx);
|
|
910
|
+
s.seg = "";
|
|
911
|
+
s.t0 = Date.now();
|
|
912
|
+
s.tools = 0;
|
|
913
|
+
s.fails = 0;
|
|
914
|
+
s.names = [];
|
|
915
|
+
s.history = []; // 新一轮重新起一条线,别接着上一轮的尾巴
|
|
916
|
+
emit({ kind: "start", sid: sidOf(ctx) });
|
|
917
|
+
});
|
|
918
|
+
|
|
919
|
+
pi.on("agent_end", async (_event: any, ctx: any) => {
|
|
920
|
+
const s = sess(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(() => {});
|
|
947
|
+
});
|
|
948
|
+
|
|
949
|
+
const liveCmd = {
|
|
950
|
+
description: "开关 pi-web 内心独白浮层条(on / off / status)",
|
|
951
|
+
handler: async (args: string, ctx: any) => {
|
|
952
|
+
const a = (args || "").trim().toLowerCase();
|
|
953
|
+
if (a === "off") {
|
|
954
|
+
enabled = false;
|
|
955
|
+
emit({ kind: "off" });
|
|
956
|
+
ctx.ui?.notify?.("内心独白已关闭", "info");
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
959
|
+
if (a === "on") {
|
|
960
|
+
enabled = true;
|
|
961
|
+
emit({ kind: "hello", enabled });
|
|
962
|
+
ctx.ui?.notify?.("内心独白已开启", "info");
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
let pending = 0;
|
|
966
|
+
for (const s of sessions.values()) pending += s.pending;
|
|
967
|
+
ctx.ui?.notify?.(
|
|
968
|
+
`内心独白:${enabled ? "开" : "关"}|连接 ${clients.size}|会话 ${sessions.size}|待改写 ${pending}`,
|
|
969
|
+
"info",
|
|
970
|
+
);
|
|
971
|
+
},
|
|
972
|
+
};
|
|
973
|
+
pi.registerCommand("d-live", liveCmd);
|
|
974
|
+
pi.registerCommand("live", liveCmd);
|
|
975
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@duanz/pi-d-live",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "把模型思考与工具调用实时改写成内心独白,推到 pi-web 界面顶部浮层",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"pi-package",
|
|
8
|
+
"pi-extension",
|
|
9
|
+
"pi-web"
|
|
10
|
+
],
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"author": "DuanZ",
|
|
13
|
+
"homepage": "https://github.com/DuanZGit/D-Hub/tree/master/extensions/d-live",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/DuanZGit/D-Hub.git",
|
|
17
|
+
"directory": "extensions/d-live"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"index.ts",
|
|
21
|
+
"README.md",
|
|
22
|
+
"README.en.md"
|
|
23
|
+
],
|
|
24
|
+
"pi": {
|
|
25
|
+
"extensions": [
|
|
26
|
+
"./index.ts"
|
|
27
|
+
],
|
|
28
|
+
"image": "https://raw.githubusercontent.com/DuanZGit/D-Hub/master/docs/covers/d-live.png"
|
|
29
|
+
},
|
|
30
|
+
"engines": {
|
|
31
|
+
"node": ">=20"
|
|
32
|
+
}
|
|
33
|
+
}
|