pi-hub-server 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +516 -2
- package/bin/pi-hub.mjs +473 -0
- package/docs/AUTH.md +260 -0
- package/package.json +45 -4
- package/src/config.mjs +60 -0
- package/src/listen.mjs +207 -0
- package/src/net-allow.mjs +134 -0
- package/src/otp.mjs +162 -0
- package/src/pairing.mjs +653 -0
- package/src/pi-args.mjs +74 -0
- package/src/pi-session.mjs +638 -0
- package/src/proxy-auth.mjs +238 -0
- package/src/registry.mjs +145 -0
- package/src/rpc-once.mjs +83 -0
- package/src/server.mjs +1603 -0
- package/src/session-lock.mjs +42 -0
- package/src/sessions-index.mjs +179 -0
- package/src/static.mjs +148 -0
- package/src/totp.mjs +151 -0
- package/src/update-check.mjs +218 -0
- package/src/web-auth.mjs +450 -0
- package/systemd/pi-hub.service +40 -0
- package/web/app.js +1699 -0
- package/web/icons/icon.svg +7 -0
- package/web/index.html +131 -0
- package/web/manifest.webmanifest +20 -0
- package/web/style.css +982 -0
- package/web/sw.js +41 -0
|
@@ -0,0 +1,638 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { PI_BIN } from "./config.mjs";
|
|
3
|
+
import { piArgs } from "./pi-args.mjs";
|
|
4
|
+
import { claim, peek, release } from "./session-lock.mjs";
|
|
5
|
+
|
|
6
|
+
const RING_MAX = 2000;
|
|
7
|
+
/** 需要用户回答的扩展 UI 方法;其余按 fire-and-forget 处理。 */
|
|
8
|
+
const UI_DIALOG_METHODS = new Set(["select", "confirm", "input", "editor"]);
|
|
9
|
+
/** 扩展没给 timeout 时,pending 表保留多久(超时后回答判 409)。 */
|
|
10
|
+
const UI_PENDING_TTL_MS = 15 * 60 * 1000;
|
|
11
|
+
const CMD_TIMEOUT_MS = 30000;
|
|
12
|
+
/** message_update 顶层 usage 的最小发送间隔。 */
|
|
13
|
+
export const USAGE_THROTTLE_MS = 500;
|
|
14
|
+
/** entry_appended 的 entry 序列化上限,超过则降级为 {type,id,truncated:true}。 */
|
|
15
|
+
export const ENTRY_APPENDED_MAX_BYTES = 8192;
|
|
16
|
+
|
|
17
|
+
/** 把一个 pi RPC 子进程包装成「一写」会话:命令相关 + 事件规整 + 环形缓冲。 */
|
|
18
|
+
export class LiveSession {
|
|
19
|
+
/**
|
|
20
|
+
* @param {{id:string, cwd:string, name?:string|null, model?:string|null, sessionFile?:string|null, log?:(...a:any[])=>void}} opts
|
|
21
|
+
*/
|
|
22
|
+
constructor(opts) {
|
|
23
|
+
this.id = opts.id;
|
|
24
|
+
this.cwd = opts.cwd;
|
|
25
|
+
this.name = opts.name ?? null;
|
|
26
|
+
this.model = opts.model ?? null;
|
|
27
|
+
this.sessionFile = opts.sessionFile ?? null;
|
|
28
|
+
this.lockDir = null;
|
|
29
|
+
this.log = opts.log ?? (() => {});
|
|
30
|
+
this.startedAt = Date.now();
|
|
31
|
+
this.lastActivity = Date.now();
|
|
32
|
+
this.seq = 0;
|
|
33
|
+
/** @type {any[]} */
|
|
34
|
+
this.ring = [];
|
|
35
|
+
/** @type {Set<(ev:any)=>void>} */
|
|
36
|
+
this.subscribers = new Set();
|
|
37
|
+
this.pending = new Map();
|
|
38
|
+
this.cmdSeq = 0;
|
|
39
|
+
/** 扩展 UI 对话框请求:uiId -> {method, at, timer}。回答后删除,超时后判 409。 */
|
|
40
|
+
this.uiPending = new Map();
|
|
41
|
+
/** 正在执行的工具:toolCallId -> {name, args, startedAt, preview}。用于重连补状态。 */
|
|
42
|
+
this.activeTools = new Map();
|
|
43
|
+
this.child = null;
|
|
44
|
+
this.stdoutBuf = "";
|
|
45
|
+
/** @type {string[]} */
|
|
46
|
+
this.stderrTail = [];
|
|
47
|
+
this.closed = false;
|
|
48
|
+
/** 上次发出 usage 的时间戳,null 表示本回复内还没发过(节流状态挂在实例上)。 */
|
|
49
|
+
this.lastUsageAt = null;
|
|
50
|
+
/** readiness 是否已完成(get_state 返回)。 */
|
|
51
|
+
this.ready = false;
|
|
52
|
+
/** @type {Promise<boolean>|null} */
|
|
53
|
+
this.readiness = null;
|
|
54
|
+
this.state = { status: "starting", isStreaming: false, isCompacting: false, sessionFile: null, sessionName: this.name, model: null, messageCount: 0 };
|
|
55
|
+
this.onClose = null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 复用已有会话前的只读冲突检查(能在桌面 TUI 正开着时提前 409,而不是写坏文件)。 */
|
|
59
|
+
#precheckLock() {
|
|
60
|
+
if (!this.sessionFile) return;
|
|
61
|
+
const probe = peek(this.sessionFile);
|
|
62
|
+
if (probe.state === "live") {
|
|
63
|
+
const err = new Error(
|
|
64
|
+
`session ${this.id} is open in another pi process (${probe.reason}); close it there or use /clone`,
|
|
65
|
+
);
|
|
66
|
+
err.statusCode = 409;
|
|
67
|
+
err.code = "session_locked";
|
|
68
|
+
throw err;
|
|
69
|
+
}
|
|
70
|
+
if (probe.state === "unknown") this.log("session lock unknown, proceeding:", probe.reason);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
#claimLock(sessionFile) {
|
|
74
|
+
const result = claim(sessionFile, { writerPid: this.child?.pid, source: "pi-hub" });
|
|
75
|
+
if (!result.ok) {
|
|
76
|
+
const err = new Error(
|
|
77
|
+
`cannot own session ${this.id}: ${result.reason}${result.owner ? ` (pid ${result.owner.pid})` : ""}`,
|
|
78
|
+
);
|
|
79
|
+
err.statusCode = 409;
|
|
80
|
+
err.code = "session_locked";
|
|
81
|
+
throw err;
|
|
82
|
+
}
|
|
83
|
+
this.lockDir = result.dir;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async start() {
|
|
87
|
+
this.#precheckLock();
|
|
88
|
+
const args = piArgs({ sessionId: this.id, name: this.name, model: this.model });
|
|
89
|
+
this.log("spawn", PI_BIN, args.join(" "), "cwd=", this.cwd);
|
|
90
|
+
this.child = spawn(PI_BIN, args, {
|
|
91
|
+
cwd: this.cwd,
|
|
92
|
+
// hub 自己就是进程外的锁管理者(#claimLock):子进程若也加载 host 的 session-lock 扩展,
|
|
93
|
+
// 它会在 session_start 先认领会话锁,hub 再认领就得到 conflict(默认加载全部扩展后实测)。
|
|
94
|
+
// PI_SESSION_LOCK=off 只关掉**子进程内**的扩展认领,hub 侧的 claim/peek 不受影响。
|
|
95
|
+
env: { ...process.env, PI_HUB: "1", PI_SESSION_LOCK: "off" },
|
|
96
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
this.child.on("error", (err) => {
|
|
100
|
+
this.emit({ type: "error", message: `spawn failed: ${err.message}` });
|
|
101
|
+
this.#shutdown("spawn_error");
|
|
102
|
+
});
|
|
103
|
+
this.child.on("exit", (code, signal) => {
|
|
104
|
+
this.log("exit", this.id, code, signal);
|
|
105
|
+
this.#shutdown(`exit:${code ?? signal}`);
|
|
106
|
+
});
|
|
107
|
+
this.child.stderr.on("data", (buf) => {
|
|
108
|
+
for (const raw of buf.toString().split("\n")) {
|
|
109
|
+
const line = raw.trim();
|
|
110
|
+
if (!line) continue;
|
|
111
|
+
this.stderrTail.push(line);
|
|
112
|
+
if (this.stderrTail.length > 20) this.stderrTail.shift();
|
|
113
|
+
this.log("pi.stderr", line.slice(0, 400));
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
this.child.stdout.on("data", (chunk) => this.#onStdout(chunk));
|
|
117
|
+
|
|
118
|
+
// 续会话时文件路径已经知道,先把锁抢下来(spawn→get_state 的窗口里 pi 会写元数据)。
|
|
119
|
+
if (this.sessionFile) this.#claimLock(this.sessionFile);
|
|
120
|
+
|
|
121
|
+
let state = null;
|
|
122
|
+
try {
|
|
123
|
+
state = await this.command("get_state");
|
|
124
|
+
} catch (err) {
|
|
125
|
+
const detail = this.stderrTail.slice(-3).join(" | ");
|
|
126
|
+
this.#shutdown("start_failed");
|
|
127
|
+
const failure = new Error(`pi failed to start: ${err.message}${detail ? ` — ${detail}` : ""}`);
|
|
128
|
+
failure.statusCode = 400;
|
|
129
|
+
throw failure;
|
|
130
|
+
}
|
|
131
|
+
this.sessionFile = state.sessionFile ?? this.sessionFile;
|
|
132
|
+
try {
|
|
133
|
+
if (this.sessionFile && !this.lockDir) this.#claimLock(this.sessionFile);
|
|
134
|
+
} catch (err) {
|
|
135
|
+
this.#shutdown("lock_conflict");
|
|
136
|
+
throw err;
|
|
137
|
+
}
|
|
138
|
+
this.state = {
|
|
139
|
+
...this.state,
|
|
140
|
+
status: "idle",
|
|
141
|
+
sessionFile: state.sessionFile ?? null,
|
|
142
|
+
sessionName: state.sessionName ?? this.name,
|
|
143
|
+
model: state.model ?? null,
|
|
144
|
+
messageCount: state.messageCount ?? 0,
|
|
145
|
+
isStreaming: Boolean(state.isStreaming),
|
|
146
|
+
};
|
|
147
|
+
this.name = this.state.sessionName;
|
|
148
|
+
this.ready = true;
|
|
149
|
+
this.emit({ type: "ready", session: this.snapshot() });
|
|
150
|
+
return this;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
#onStdout(chunk) {
|
|
154
|
+
this.stdoutBuf += chunk.toString("utf8");
|
|
155
|
+
let idx;
|
|
156
|
+
while ((idx = this.stdoutBuf.indexOf("\n")) >= 0) {
|
|
157
|
+
const line = this.stdoutBuf.slice(0, idx).replace(/\r$/, "");
|
|
158
|
+
this.stdoutBuf = this.stdoutBuf.slice(idx + 1);
|
|
159
|
+
if (!line.trim()) continue;
|
|
160
|
+
let rec;
|
|
161
|
+
try {
|
|
162
|
+
rec = JSON.parse(line);
|
|
163
|
+
} catch {
|
|
164
|
+
this.log("bad json line", line.slice(0, 200));
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
this.#route(rec);
|
|
168
|
+
}
|
|
169
|
+
if (this.stdoutBuf.length > 8 * 1024 * 1024) {
|
|
170
|
+
this.stdoutBuf = "";
|
|
171
|
+
this.emit({ type: "error", message: "stdout buffer overflow, dropped" });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
#route(rec) {
|
|
176
|
+
this.touch();
|
|
177
|
+
if (rec.type === "response") {
|
|
178
|
+
const key = rec.id;
|
|
179
|
+
const waiter = key ? this.pending.get(key) : null;
|
|
180
|
+
if (!waiter) return;
|
|
181
|
+
this.pending.delete(key);
|
|
182
|
+
clearTimeout(waiter.timer);
|
|
183
|
+
if (rec.success === false) {
|
|
184
|
+
const err = new Error(rec.error ?? `${rec.command} failed`);
|
|
185
|
+
err.command = rec.command;
|
|
186
|
+
waiter.reject(err);
|
|
187
|
+
} else {
|
|
188
|
+
waiter.resolve(rec.data ?? null);
|
|
189
|
+
}
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (rec.type === "extension_ui_request") {
|
|
193
|
+
this.#handleUiRequest(rec);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const out = normalizeEvent(rec, { lastUsageAt: this.lastUsageAt, now: Date.now() });
|
|
197
|
+
if (out.status !== undefined) this.state.status = out.status;
|
|
198
|
+
if (out.streaming !== undefined) this.state.isStreaming = out.streaming;
|
|
199
|
+
if (out.compacting !== undefined) this.state.isCompacting = out.compacting;
|
|
200
|
+
if (out.emit) {
|
|
201
|
+
// normalizeEvent 是纯函数,改名这类实例副作用只能在这里落地。
|
|
202
|
+
if (out.emit.type === "session_renamed") {
|
|
203
|
+
this.name = out.emit.name ?? null;
|
|
204
|
+
this.state.sessionName = this.name;
|
|
205
|
+
}
|
|
206
|
+
this.#trackTools(out.emit);
|
|
207
|
+
this.emit(out.emit);
|
|
208
|
+
}
|
|
209
|
+
if (out.usageAt != null) this.lastUsageAt = out.usageAt;
|
|
210
|
+
if (out.usageEmit) this.emit(out.usageEmit);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* 扩展 UI 子协议:对话框(select/confirm/input/editor)转发给客户端并等回答;
|
|
215
|
+
* 其余(notify/setStatus/setWidget/...)是 fire-and-forget,只当事件转发。
|
|
216
|
+
* 不再一律回 cancelled —— 那会让带确认的扩展在手机上等于「全部默认拒绝」。
|
|
217
|
+
*/
|
|
218
|
+
#handleUiRequest(rec) {
|
|
219
|
+
const { event, dialog, ttlMs } = uiRequestEvent(rec);
|
|
220
|
+
if (!dialog) {
|
|
221
|
+
this.emit(event);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
const timer = setTimeout(() => {
|
|
225
|
+
this.uiPending.delete(rec.id);
|
|
226
|
+
this.log("ui request expired", rec.id, rec.method);
|
|
227
|
+
}, ttlMs);
|
|
228
|
+
timer.unref?.();
|
|
229
|
+
this.uiPending.set(rec.id, { method: rec.method, at: Date.now(), timer });
|
|
230
|
+
this.emit(event);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** 客户端回答一个 ui_request。返回 true;未知/过期 id 抛 409 语义的错误。 */
|
|
234
|
+
answerUi(uiId, payload = {}) {
|
|
235
|
+
const entry = this.uiPending.get(uiId);
|
|
236
|
+
if (!entry) {
|
|
237
|
+
const err = new Error(`unknown or expired ui request: ${uiId}`);
|
|
238
|
+
err.statusCode = 409;
|
|
239
|
+
err.code = "unknown_ui_request";
|
|
240
|
+
throw err;
|
|
241
|
+
}
|
|
242
|
+
clearTimeout(entry.timer);
|
|
243
|
+
this.uiPending.delete(uiId);
|
|
244
|
+
/** @type {Record<string, unknown>} */
|
|
245
|
+
const res = { type: "extension_ui_response", id: uiId };
|
|
246
|
+
if (payload.cancelled === true) res.cancelled = true;
|
|
247
|
+
else {
|
|
248
|
+
if (payload.value !== undefined) res.value = payload.value;
|
|
249
|
+
if (payload.confirmed !== undefined) res.confirmed = Boolean(payload.confirmed);
|
|
250
|
+
}
|
|
251
|
+
this.#write(res);
|
|
252
|
+
return true;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
#trackTools(ev) {
|
|
256
|
+
if (ev.type === "tool_start") {
|
|
257
|
+
this.activeTools.set(ev.id, { name: ev.name, args: ev.args ?? null, startedAt: Date.now(), preview: null });
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
if (ev.type === "tool_progress") {
|
|
261
|
+
const tool = this.activeTools.get(ev.id);
|
|
262
|
+
if (tool) tool.preview = ev.preview ?? null;
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
if (ev.type === "tool_end") this.activeTools.delete(ev.id);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* 重连补状态:仍在跑的工具 → 合成 tool_start / tool_progress(带 replay:true、elapsedMs)。
|
|
270
|
+
* 这些帧**不进环形缓冲、不占 seq**,只发给新订阅者,避免污染 since 回放。
|
|
271
|
+
*/
|
|
272
|
+
activeToolEvents() {
|
|
273
|
+
const out = [];
|
|
274
|
+
for (const [id, tool] of this.activeTools) {
|
|
275
|
+
const elapsedMs = Date.now() - tool.startedAt;
|
|
276
|
+
out.push({ type: "tool_start", id, name: tool.name, args: tool.args, replay: true, elapsedMs });
|
|
277
|
+
if (tool.preview) out.push({ type: "tool_progress", id, name: tool.name, args: tool.args, preview: tool.preview, replay: true, elapsedMs });
|
|
278
|
+
}
|
|
279
|
+
return out;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
#write(rec) {
|
|
283
|
+
if (!this.child || this.closed) throw new Error("session closed");
|
|
284
|
+
this.child.stdin.write(`${JSON.stringify(rec)}\n`);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** 发命令并等对应 response。 */
|
|
288
|
+
command(type, payload = {}, { timeoutMs = CMD_TIMEOUT_MS } = {}) {
|
|
289
|
+
const id = `c${++this.cmdSeq}`;
|
|
290
|
+
this.#write({ id, type, ...payload });
|
|
291
|
+
return new Promise((resolve, reject) => {
|
|
292
|
+
const timer = setTimeout(() => {
|
|
293
|
+
this.pending.delete(id);
|
|
294
|
+
reject(new Error(`timeout waiting for ${type}`));
|
|
295
|
+
}, timeoutMs);
|
|
296
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
send(type, payload = {}) {
|
|
301
|
+
this.#write({ type, ...payload });
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
touch() {
|
|
305
|
+
this.lastActivity = Date.now();
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
snapshot() {
|
|
309
|
+
return {
|
|
310
|
+
id: this.id,
|
|
311
|
+
cwd: this.cwd,
|
|
312
|
+
name: this.name,
|
|
313
|
+
model: this.state.model,
|
|
314
|
+
status: this.state.status,
|
|
315
|
+
ready: this.ready,
|
|
316
|
+
isStreaming: this.state.isStreaming,
|
|
317
|
+
isCompacting: this.state.isCompacting,
|
|
318
|
+
sessionFile: this.state.sessionFile,
|
|
319
|
+
pid: this.child?.pid ?? null,
|
|
320
|
+
startedAt: new Date(this.startedAt).toISOString(),
|
|
321
|
+
lastActivity: new Date(this.lastActivity).toISOString(),
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
emit(event) {
|
|
326
|
+
const ev = { seq: ++this.seq, ...event };
|
|
327
|
+
this.ring.push(ev);
|
|
328
|
+
if (this.ring.length > RING_MAX) this.ring.splice(0, this.ring.length - RING_MAX);
|
|
329
|
+
for (const sub of this.subscribers) {
|
|
330
|
+
try {
|
|
331
|
+
sub(ev);
|
|
332
|
+
} catch (err) {
|
|
333
|
+
this.log("subscriber error", err.message);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return ev;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** @param {(ev:any)=>void} fn @param {number} [since] @returns {()=>void} */
|
|
340
|
+
subscribe(fn, since = 0) {
|
|
341
|
+
for (const ev of this.ring) if (ev.seq > since) fn(ev);
|
|
342
|
+
this.subscribers.add(fn);
|
|
343
|
+
return () => this.subscribers.delete(fn);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** fork/clone 后把进程改挂到新会话(保留同一子进程与事件流)。 */
|
|
347
|
+
rekey({ id, sessionFile, name, cwd, model }) {
|
|
348
|
+
const oldId = this.id;
|
|
349
|
+
if (this.lockDir) {
|
|
350
|
+
release(this.lockDir);
|
|
351
|
+
this.lockDir = null;
|
|
352
|
+
}
|
|
353
|
+
this.id = id;
|
|
354
|
+
this.sessionFile = sessionFile ?? this.sessionFile;
|
|
355
|
+
this.name = name ?? this.name;
|
|
356
|
+
this.cwd = cwd ?? this.cwd;
|
|
357
|
+
this.state.sessionFile = this.sessionFile;
|
|
358
|
+
this.state.sessionName = this.name;
|
|
359
|
+
if (model) this.state.model = model;
|
|
360
|
+
if (this.sessionFile) this.#claimLock(this.sessionFile);
|
|
361
|
+
return oldId;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
stop(reason = "stop") {
|
|
365
|
+
this.#shutdown(reason);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
#shutdown(reason) {
|
|
369
|
+
if (this.closed) return;
|
|
370
|
+
this.closed = true;
|
|
371
|
+
this.state.status = "closed";
|
|
372
|
+
try {
|
|
373
|
+
this.child?.kill("SIGTERM");
|
|
374
|
+
setTimeout(() => {
|
|
375
|
+
try {
|
|
376
|
+
this.child?.kill("SIGKILL");
|
|
377
|
+
} catch {
|
|
378
|
+
// ignore
|
|
379
|
+
}
|
|
380
|
+
}, 3000).unref();
|
|
381
|
+
} catch {
|
|
382
|
+
// ignore
|
|
383
|
+
}
|
|
384
|
+
for (const [, waiter] of this.pending) {
|
|
385
|
+
clearTimeout(waiter.timer);
|
|
386
|
+
waiter.reject(new Error(`session closed: ${reason}`));
|
|
387
|
+
}
|
|
388
|
+
this.pending.clear();
|
|
389
|
+
for (const [, entry] of this.uiPending) clearTimeout(entry.timer);
|
|
390
|
+
this.uiPending.clear();
|
|
391
|
+
this.activeTools.clear();
|
|
392
|
+
release(this.lockDir);
|
|
393
|
+
this.lockDir = null;
|
|
394
|
+
this.emit({ type: "closed", reason });
|
|
395
|
+
this.onClose?.(reason);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* 把一条 pi RPC 事件规整成 hub 事件 + 状态增量。纯函数:不碰 session 实例,
|
|
401
|
+
* 所以 usage 节流状态由调用方以参数传入(`ctx.lastUsageAt`),发出决定回传(`usageAt`)。
|
|
402
|
+
*
|
|
403
|
+
* @param {any} ev pi RPC 事件记录(`type` 为事件名)
|
|
404
|
+
* @param {{lastUsageAt?: number|null, now?: number}} [ctx] usage 节流上下文
|
|
405
|
+
* @returns {{emit: object|null, status?: string, streaming?: boolean, compacting?: boolean,
|
|
406
|
+
* usageEmit?: object|null, usageAt?: number|null}}
|
|
407
|
+
* `emit` 是主事件(null = 不对外发);`status`/`streaming`/`compacting` 是状态增量;
|
|
408
|
+
* `usageEmit`/`usageAt` 是需要额外发出的 usage 事件与更新后的节流时间戳。
|
|
409
|
+
*/
|
|
410
|
+
export function normalizeEvent(ev, ctx = {}) {
|
|
411
|
+
if (!ev || typeof ev !== "object") return { emit: null };
|
|
412
|
+
switch (ev.type) {
|
|
413
|
+
case "agent_start":
|
|
414
|
+
return { emit: { type: "status", status: "running" }, status: "running", streaming: true };
|
|
415
|
+
case "turn_start":
|
|
416
|
+
return { emit: { type: "status", status: "thinking" }, status: "thinking" };
|
|
417
|
+
case "message_start": {
|
|
418
|
+
const m = ev.message;
|
|
419
|
+
if (m?.role === "user") return { emit: { type: "user_message", text: extractText(m), ts: tsIso(m) } };
|
|
420
|
+
if (m?.role === "assistant") return { emit: { type: "assistant_start", ts: tsIso(m) } };
|
|
421
|
+
return { emit: null };
|
|
422
|
+
}
|
|
423
|
+
case "message_update":
|
|
424
|
+
return normalizeMessageUpdate(ev, ctx);
|
|
425
|
+
case "message_end": {
|
|
426
|
+
const m = ev.message;
|
|
427
|
+
if (!m) return { emit: null };
|
|
428
|
+
if (m.role !== "assistant") return { emit: null };
|
|
429
|
+
const emit = {
|
|
430
|
+
type: "assistant_message",
|
|
431
|
+
text: extractText(m),
|
|
432
|
+
thinking: extractThinking(m),
|
|
433
|
+
ts: tsIso(m),
|
|
434
|
+
stopReason: m.stopReason,
|
|
435
|
+
usage: m.usage ?? null,
|
|
436
|
+
model: m.model ?? null,
|
|
437
|
+
provider: m.provider ?? null,
|
|
438
|
+
durationMs: m.durationMs ?? null,
|
|
439
|
+
};
|
|
440
|
+
// message_end 强制发最后一次 usage,不受节流影响。
|
|
441
|
+
return { emit, ...usageUpdate(m.usage, ctx, true) };
|
|
442
|
+
}
|
|
443
|
+
case "tool_execution_start":
|
|
444
|
+
return { emit: { type: "tool_start", id: ev.toolCallId, name: ev.toolName, args: ev.args } };
|
|
445
|
+
case "tool_execution_update":
|
|
446
|
+
return {
|
|
447
|
+
emit: { type: "tool_progress", id: ev.toolCallId, name: ev.toolName, args: ev.args, preview: previewText(ev.partialResult) },
|
|
448
|
+
};
|
|
449
|
+
case "tool_execution_end":
|
|
450
|
+
return {
|
|
451
|
+
emit: {
|
|
452
|
+
type: "tool_end",
|
|
453
|
+
id: ev.toolCallId,
|
|
454
|
+
name: ev.toolName,
|
|
455
|
+
isError: Boolean(ev.isError),
|
|
456
|
+
durationMs: ev.durationMs,
|
|
457
|
+
preview: previewText(ev.result),
|
|
458
|
+
},
|
|
459
|
+
};
|
|
460
|
+
case "turn_end":
|
|
461
|
+
return { emit: { type: "turn_end", usage: ev.message?.usage ?? null } };
|
|
462
|
+
case "agent_end":
|
|
463
|
+
return { emit: { type: "agent_end", willRetry: Boolean(ev.willRetry) } };
|
|
464
|
+
case "agent_settled":
|
|
465
|
+
return { emit: { type: "settled", aborted: Boolean(ev.aborted), status: "idle" }, status: "idle", streaming: false };
|
|
466
|
+
case "compaction_start":
|
|
467
|
+
return { emit: { type: "status", status: "compacting", reason: ev.reason }, compacting: true };
|
|
468
|
+
case "compaction_end":
|
|
469
|
+
return {
|
|
470
|
+
emit: {
|
|
471
|
+
type: "compaction_end",
|
|
472
|
+
aborted: Boolean(ev.aborted),
|
|
473
|
+
tokensBefore: ev.result?.tokensBefore ?? null,
|
|
474
|
+
estimatedTokensAfter: ev.result?.estimatedTokensAfter ?? null,
|
|
475
|
+
firstKeptEntryId: ev.result?.firstKeptEntryId ?? null,
|
|
476
|
+
willRetry: Boolean(ev.willRetry),
|
|
477
|
+
errorMessage: ev.errorMessage ?? null,
|
|
478
|
+
},
|
|
479
|
+
compacting: false,
|
|
480
|
+
};
|
|
481
|
+
case "auto_retry_start":
|
|
482
|
+
return {
|
|
483
|
+
emit: { type: "retry", attempt: ev.attempt, maxAttempts: ev.maxAttempts, delayMs: ev.delayMs, error: ev.errorMessage },
|
|
484
|
+
};
|
|
485
|
+
case "auto_retry_end":
|
|
486
|
+
return { emit: { type: "retry_end", success: Boolean(ev.success), error: ev.finalError ?? null } };
|
|
487
|
+
case "summarization_retry_scheduled":
|
|
488
|
+
return { emit: summarizeRetry("scheduled", ev) };
|
|
489
|
+
case "summarization_retry_attempt_start":
|
|
490
|
+
return { emit: summarizeRetry("attempt_start", ev) };
|
|
491
|
+
case "summarization_retry_finished":
|
|
492
|
+
return { emit: summarizeRetry("finished", ev) };
|
|
493
|
+
case "entry_appended":
|
|
494
|
+
return { emit: { type: "entry_appended", entry: entryForWire(ev.entry) } };
|
|
495
|
+
case "extension_error":
|
|
496
|
+
return {
|
|
497
|
+
emit: { type: "extension_error", extensionPath: ev.extensionPath ?? null, event: ev.event ?? null, error: ev.error ?? null },
|
|
498
|
+
};
|
|
499
|
+
case "session_info_changed":
|
|
500
|
+
return { emit: { type: "session_renamed", name: ev.name ?? null } };
|
|
501
|
+
case "queue_update":
|
|
502
|
+
return { emit: { type: "queue", steering: ev.steering ?? [], followUp: ev.followUp ?? [] } };
|
|
503
|
+
case "thinking_level_changed":
|
|
504
|
+
return { emit: { type: "thinking_level", level: ev.level } };
|
|
505
|
+
default:
|
|
506
|
+
return { emit: null };
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* 扩展 UI 请求 → hub 事件(纯函数,便于单测)。
|
|
512
|
+
* 对话框方法(select/confirm/input/editor)要用户回答;其余是 fire-and-forget 通知。
|
|
513
|
+
* @returns {{event:object, dialog:boolean, ttlMs:number}}
|
|
514
|
+
*/
|
|
515
|
+
export function uiRequestEvent(rec) {
|
|
516
|
+
const dialog = UI_DIALOG_METHODS.has(rec.method);
|
|
517
|
+
if (!dialog) {
|
|
518
|
+
return {
|
|
519
|
+
dialog: false,
|
|
520
|
+
ttlMs: 0,
|
|
521
|
+
event: {
|
|
522
|
+
type: "ui_notify",
|
|
523
|
+
uiId: rec.id,
|
|
524
|
+
method: rec.method ?? null,
|
|
525
|
+
// 按 pi 的真实字段名透传(notify→notifyType、setStatus→statusKey/statusText、
|
|
526
|
+
// setWidget→widgetKey/widgetLines、setTitle→title、set_editor_text→text)
|
|
527
|
+
title: rec.title ?? null,
|
|
528
|
+
message: rec.message ?? null,
|
|
529
|
+
level: rec.level ?? rec.notifyType ?? null,
|
|
530
|
+
notifyType: rec.notifyType ?? null,
|
|
531
|
+
statusKey: rec.statusKey ?? null,
|
|
532
|
+
statusText: rec.statusText ?? null,
|
|
533
|
+
widgetKey: rec.widgetKey ?? null,
|
|
534
|
+
widgetLines: Array.isArray(rec.widgetLines) ? rec.widgetLines : null,
|
|
535
|
+
widgetPlacement: rec.widgetPlacement ?? null,
|
|
536
|
+
text: rec.text ?? null,
|
|
537
|
+
},
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
const ttlMs = Number.isFinite(rec.timeout) && rec.timeout > 0 ? rec.timeout + 5000 : UI_PENDING_TTL_MS;
|
|
541
|
+
return {
|
|
542
|
+
dialog: true,
|
|
543
|
+
ttlMs,
|
|
544
|
+
event: {
|
|
545
|
+
type: "ui_request",
|
|
546
|
+
uiId: rec.id,
|
|
547
|
+
method: rec.method,
|
|
548
|
+
title: rec.title ?? null,
|
|
549
|
+
message: rec.message ?? null,
|
|
550
|
+
options: Array.isArray(rec.options) ? rec.options : null,
|
|
551
|
+
placeholder: rec.placeholder ?? null,
|
|
552
|
+
// editor 的预填文本(漏了它手机会把原文本清空)
|
|
553
|
+
prefill: typeof rec.prefill === "string" ? rec.prefill : null,
|
|
554
|
+
timeout: Number.isFinite(rec.timeout) ? rec.timeout : null,
|
|
555
|
+
},
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** message_update:内容块增量 + 顶层 usage(500ms 节流,text_end 强制发最后一次)。 */
|
|
560
|
+
function normalizeMessageUpdate(ev, ctx) {
|
|
561
|
+
const e = ev.assistantMessageEvent;
|
|
562
|
+
let emit = null;
|
|
563
|
+
if (e) {
|
|
564
|
+
if (e.type === "text_delta") emit = { type: "text_delta", index: e.contentIndex, delta: e.delta };
|
|
565
|
+
else if (e.type === "thinking_delta") emit = { type: "thinking_delta", index: e.contentIndex, delta: e.delta };
|
|
566
|
+
else if (e.type === "text_end") emit = { type: "text_end", index: e.contentIndex, text: e.content };
|
|
567
|
+
else if (e.type === "thinking_end") emit = { type: "thinking_end", index: e.contentIndex, text: e.content };
|
|
568
|
+
else if (e.type === "toolcall_end" && e.toolCall) {
|
|
569
|
+
emit = { type: "tool_call", id: e.toolCall.id, name: e.toolCall.name, args: e.toolCall.args };
|
|
570
|
+
} else if (e.type === "error") {
|
|
571
|
+
emit = { type: "error", message: e.error?.message ?? String(e.error ?? e.reason ?? "stream error") };
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
const force = e?.type === "text_end";
|
|
575
|
+
return { emit, ...usageUpdate(ev.usage, ctx, force) };
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** 节流决定:`force` 或距上次发出已 ≥ USAGE_THROTTLE_MS 才发。 */
|
|
579
|
+
function usageUpdate(usage, { lastUsageAt = null, now = Date.now() } = {}, force = false) {
|
|
580
|
+
if (!usage) return {};
|
|
581
|
+
if (!force && lastUsageAt != null && now - lastUsageAt < USAGE_THROTTLE_MS) return {};
|
|
582
|
+
return { usageEmit: { type: "usage", usage }, usageAt: now };
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function summarizeRetry(phase, ev) {
|
|
586
|
+
return {
|
|
587
|
+
type: "summarization_retry",
|
|
588
|
+
phase,
|
|
589
|
+
attempt: ev.attempt ?? null,
|
|
590
|
+
maxAttempts: ev.maxAttempts ?? null,
|
|
591
|
+
delayMs: ev.delayMs ?? null,
|
|
592
|
+
error: ev.errorMessage ?? null,
|
|
593
|
+
source: ev.source ?? null,
|
|
594
|
+
reason: ev.reason ?? null,
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** entry_appended:序列化超 8 KB 时只保留 {type,id,truncated:true},避免 SSE 被大 entry 撑爆。 */
|
|
599
|
+
function entryForWire(entry) {
|
|
600
|
+
if (!entry || typeof entry !== "object") return entry ?? null;
|
|
601
|
+
let size;
|
|
602
|
+
try {
|
|
603
|
+
size = Buffer.byteLength(JSON.stringify(entry), "utf8");
|
|
604
|
+
} catch {
|
|
605
|
+
return { type: entry.type ?? null, id: entry.id ?? null, truncated: true };
|
|
606
|
+
}
|
|
607
|
+
if (size <= ENTRY_APPENDED_MAX_BYTES) return entry;
|
|
608
|
+
return { type: entry.type ?? null, id: entry.id ?? null, truncated: true };
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
function extractText(m) {
|
|
612
|
+
if (typeof m.content === "string") return m.content;
|
|
613
|
+
return (m.content ?? [])
|
|
614
|
+
.filter((b) => b?.type === "text")
|
|
615
|
+
.map((b) => b.text)
|
|
616
|
+
.join("\n");
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
function extractThinking(m) {
|
|
620
|
+
if (!Array.isArray(m.content)) return "";
|
|
621
|
+
return m.content
|
|
622
|
+
.filter((b) => b?.type === "thinking")
|
|
623
|
+
.map((b) => b.thinking)
|
|
624
|
+
.join("\n");
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
function previewText(result) {
|
|
628
|
+
const blocks = result?.content ?? [];
|
|
629
|
+
const text = blocks
|
|
630
|
+
.filter((b) => b?.type === "text")
|
|
631
|
+
.map((b) => b.text)
|
|
632
|
+
.join("\n");
|
|
633
|
+
return text.slice(0, 2000);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
function tsIso(m) {
|
|
637
|
+
return m?.timestamp ? new Date(m.timestamp).toISOString() : new Date().toISOString();
|
|
638
|
+
}
|