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