pi-hub-server 0.4.0 → 0.4.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.
@@ -1,6 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { PI_BIN } from "./config.mjs";
3
3
  import { piArgs } from "./pi-args.mjs";
4
+ import { killChildTree, piSpawnSpec } from "./pi-spawn.mjs";
4
5
  import { claim, peek, release } from "./session-lock.mjs";
5
6
 
6
7
  const RING_MAX = 2000;
@@ -14,6 +15,26 @@ export const USAGE_THROTTLE_MS = 500;
14
15
  /** entry_appended 的 entry 序列化上限,超过则降级为 {type,id,truncated:true}。 */
15
16
  export const ENTRY_APPENDED_MAX_BYTES = 8192;
16
17
 
18
+ /**
19
+ * 未知 pi 事件计数(进程级)。
20
+ * pi 升级改名/新增事件时,hub 的 switch 会落到 default 分支:不静默丢弃,计数后由
21
+ * Registry 聚合到 `/v1/health.unknownEvents` —— 漂移的第一眼证据。
22
+ * 进程级(而不是按会话)是因为会话会被回收,而「这个 hub 见过多少不认识的事件」不该被回收掉。
23
+ */
24
+ const unknownEvents = { total: 0, byType: new Map() };
25
+
26
+ /** 记一条不认识的事件类型(type 可能缺失,统一记成 "(missing type)")。 */
27
+ export function noteUnknownEvent(type) {
28
+ unknownEvents.total += 1;
29
+ const key = typeof type === "string" && type ? type : "(missing type)";
30
+ unknownEvents.byType.set(key, (unknownEvents.byType.get(key) ?? 0) + 1);
31
+ }
32
+
33
+ /** 只读快照:`total` 进 /v1/health,`byType` 供日志/排查。 */
34
+ export function unknownEventStats() {
35
+ return { total: unknownEvents.total, byType: Object.fromEntries(unknownEvents.byType) };
36
+ }
37
+
17
38
  /** 把一个 pi RPC 子进程包装成「一写」会话:命令相关 + 事件规整 + 环形缓冲。 */
18
39
  export class LiveSession {
19
40
  /**
@@ -41,6 +62,8 @@ export class LiveSession {
41
62
  /** 正在执行的工具:toolCallId -> {name, args, startedAt, preview}。用于重连补状态。 */
42
63
  this.activeTools = new Map();
43
64
  this.child = null;
65
+ /** 子进程是否已经退出(exit/error 已到):关闭时不再按 pid 发信号,避免 Windows pid 复用误杀。 */
66
+ this.childExited = false;
44
67
  this.stdoutBuf = "";
45
68
  /** @type {string[]} */
46
69
  this.stderrTail = [];
@@ -86,8 +109,11 @@ export class LiveSession {
86
109
  async start() {
87
110
  this.#precheckLock();
88
111
  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, {
112
+ // Windows 上 pi 是 npm 的 pi.cmd(spawn 不能直接执行 .cmd),交给 pi-spawn 决定走不走 cmd.exe。
113
+ const spec = piSpawnSpec(PI_BIN, args);
114
+ this.log("spawn", spec.file, [...spec.args].join(" "), "cwd=", this.cwd);
115
+ this.child = spawn(spec.file, spec.args, {
116
+ ...spec.options,
91
117
  cwd: this.cwd,
92
118
  // hub 自己就是进程外的锁管理者(#claimLock):子进程若也加载 host 的 session-lock 扩展,
93
119
  // 它会在 session_start 先认领会话锁,hub 再认领就得到 conflict(默认加载全部扩展后实测)。
@@ -97,10 +123,12 @@ export class LiveSession {
97
123
  });
98
124
 
99
125
  this.child.on("error", (err) => {
126
+ this.childExited = true;
100
127
  this.emit({ type: "error", message: `spawn failed: ${err.message}` });
101
128
  this.#shutdown("spawn_error");
102
129
  });
103
130
  this.child.on("exit", (code, signal) => {
131
+ this.childExited = true;
104
132
  this.log("exit", this.id, code, signal);
105
133
  this.#shutdown(`exit:${code ?? signal}`);
106
134
  });
@@ -114,6 +142,9 @@ export class LiveSession {
114
142
  }
115
143
  });
116
144
  this.child.stdout.on("data", (chunk) => this.#onStdout(chunk));
145
+ // 子进程早退后往 stdin 写会 EPIPE:没有 error 监听时那是未捕获异常,会把 hub 一起带走。
146
+ // 真正的「只回 5xx」由 #write 的 writable 检查负责,这里只负责不让事件逃出去。
147
+ this.child.stdin.on("error", (err) => this.log("pi.stdin error", this.id, err.message));
117
148
 
118
149
  // 续会话时文件路径已经知道,先把锁抢下来(spawn→get_state 的窗口里 pi 会写元数据)。
119
150
  if (this.sessionFile) this.#claimLock(this.sessionFile);
@@ -194,6 +225,7 @@ export class LiveSession {
194
225
  return;
195
226
  }
196
227
  const out = normalizeEvent(rec, { lastUsageAt: this.lastUsageAt, now: Date.now() });
228
+ if (out.unknown) noteUnknownEvent(out.unknown);
197
229
  if (out.status !== undefined) this.state.status = out.status;
198
230
  if (out.streaming !== undefined) this.state.isStreaming = out.streaming;
199
231
  if (out.compacting !== undefined) this.state.isCompacting = out.compacting;
@@ -281,7 +313,24 @@ export class LiveSession {
281
313
 
282
314
  #write(rec) {
283
315
  if (!this.child || this.closed) throw new Error("session closed");
284
- this.child.stdin.write(`${JSON.stringify(rec)}\n`);
316
+ const stdin = this.child.stdin;
317
+ // spawn 失败(ENOENT / 坏 PI_HUB_PI_BIN)或子进程早退时 stdin 已不可写:
318
+ // 裸 write 只会得到 EPIPE,而 stdin 上没有 error 监听就是未捕获异常 ⇒ 带走整个 hub。
319
+ // 这里改成「只让这一次请求失败」,由上层回 5xx。
320
+ if (!stdin || stdin.destroyed || !stdin.writable) {
321
+ const err = new Error(`pi stdin is not writable (${this.id})`);
322
+ err.statusCode = 503;
323
+ err.code = "pi_stdin_closed";
324
+ throw err;
325
+ }
326
+ try {
327
+ stdin.write(`${JSON.stringify(rec)}\n`);
328
+ } catch (error) {
329
+ const err = new Error(`pi stdin write failed (${this.id}): ${error.message}`);
330
+ err.statusCode = 503;
331
+ err.code = "pi_stdin_closed";
332
+ throw err;
333
+ }
285
334
  }
286
335
 
287
336
  /** 发命令并等对应 response。 */
@@ -370,14 +419,13 @@ export class LiveSession {
370
419
  this.closed = true;
371
420
  this.state.status = "closed";
372
421
  try {
373
- this.child?.kill("SIGTERM");
374
- setTimeout(() => {
375
- try {
376
- this.child?.kill("SIGKILL");
377
- } catch {
378
- // ignore
379
- }
380
- }, 3000).unref();
422
+ // 子进程已经自己退了就不要再按 pid 发信号(Windows 上 pid 复用会误杀无关进程)。
423
+ if (!this.childExited && this.child) {
424
+ killChildTree(this.child);
425
+ setTimeout(() => {
426
+ killChildTree(this.child, { force: true });
427
+ }, 3000).unref();
428
+ }
381
429
  } catch {
382
430
  // ignore
383
431
  }
@@ -503,7 +551,8 @@ export function normalizeEvent(ev, ctx = {}) {
503
551
  case "thinking_level_changed":
504
552
  return { emit: { type: "thinking_level", level: ev.level } };
505
553
  default:
506
- return { emit: null };
554
+ // 不认识的事件类型:不静默丢弃,交回调用方计数(→ /v1/health.unknownEvents)。
555
+ return { emit: null, unknown: ev.type ?? "(missing type)" };
507
556
  }
508
557
  }
509
558
 
@@ -0,0 +1,115 @@
1
+ /**
2
+ * 跨平台启动/终止 pi 子进程 —— hub 里凡是要 exec pi 的地方都走这一层。
3
+ *
4
+ * 两个只在 Windows 上出现、POSIX 上看不见的坑:
5
+ *
6
+ * 1) **npm 装出来的 `pi` 是 `pi.cmd`(批处理 shim),Node 的 spawn 不能直接执行 .cmd/.bat**
7
+ * (`spawn EINVAL`,不存在「找不到文件」这种好看点的报错)。必须 `/d /s /c` 交给 cmd.exe。
8
+ * 这里按 Windows 命令行解析规则逐个参数加引号,并开 windowsVerbatimArguments,
9
+ * 不让 Node 再套一层引号(否则 `""C:\...\pi.cmd""` 之类的双重转义 cmd 会吃掉)。
10
+ * 显式给成 `.exe`(例如 `PI_HUB_PI_BIN=C:\nodejs\node.exe`)时仍然直连,不经 shell。
11
+ *
12
+ * 2) **Windows 没有 SIGTERM 语义,`child.kill()` 只杀直接子进程**:pi 自己起的子进程
13
+ * (bash 工具、subagent、LSP)会变成孤儿。`taskkill /T` 才能带走整棵树。
14
+ * 非 Windows 上保持单进程 dispatch,信号原样转发。
15
+ *
16
+ * 这一层只回答「怎么起、怎么杀」,不重试、不改参数(参数仍由 pi-args.mjs 给)。
17
+ */
18
+ import { execFile } from "node:child_process";
19
+
20
+ /** cmd.exe 会解释的字符:命中的参数必须整段加引号。 */
21
+ const CMD_META = /[\s"&|<>^()]/;
22
+
23
+ /**
24
+ * 按 MSVCRT 的命令行切分规则给单个参数加引号。
25
+ *
26
+ * 规则:引号前的 2n 个反斜杠 → n 个反斜杠 + 引号定界;行尾的反斜杠要翻倍,
27
+ * 否则它会转义收尾的引号。只有命中 CMD_META 或在行尾时才需要动它。
28
+ *
29
+ * @param {unknown} arg
30
+ * @returns {string}
31
+ */
32
+ export function quoteCmdArg(arg) {
33
+ const text = String(arg ?? "");
34
+ if (text === "") return '""';
35
+ const needsQuotes = CMD_META.test(text) || text.endsWith("\\");
36
+ if (!needsQuotes) return text;
37
+ const escaped = text.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1");
38
+ return `"${escaped}"`;
39
+ }
40
+
41
+ /** 显式是指向可执行文件的路径(.exe/.com)时直连,其余(含裸命令名)在 Windows 上走 cmd.exe。 */
42
+ function isDirectExecutable(piBin) {
43
+ return /\.(exe|com)$/i.test(String(piBin));
44
+ }
45
+
46
+ /**
47
+ * 组装 spawn 的 (file, args, options)。
48
+ *
49
+ * @param {string} piBin `PI_HUB_PI_BIN` / 默认 `pi`
50
+ * @param {string[]} args pi 的参数(pi-args.mjs 生成)
51
+ * @param {{platform?:string, comspec?:string}} [opts] platform/comspec 只为单测注入
52
+ * @returns {{file:string, args:string[], options:{windowsVerbatimArguments?:boolean}, viaShell:boolean}}
53
+ */
54
+ export function piSpawnSpec(piBin, args = [], opts = {}) {
55
+ const platform = opts.platform ?? process.platform;
56
+ const list = args.map((a) => String(a));
57
+ if (platform !== "win32" || isDirectExecutable(piBin)) {
58
+ return { file: piBin, args: list, options: {}, viaShell: false };
59
+ }
60
+ const comspec = opts.comspec ?? process.env.ComSpec ?? "cmd.exe";
61
+ const line = [quoteCmdArg(piBin), ...list.map(quoteCmdArg)].join(" ");
62
+ // /d 跳过 AutoRun 注册表钩子;/s 让 cmd 只剥掉最外层一对引号(否则首尾引号会被当成
63
+ // 命令自身的定界符而错位);整行再套一对引号是 /s 的标准用法。
64
+ return {
65
+ file: comspec,
66
+ args: ["/d", "/s", "/c", `"${line}"`],
67
+ options: { windowsVerbatimArguments: true },
68
+ viaShell: true,
69
+ };
70
+ }
71
+
72
+ /**
73
+ * 终止一个 pi 子进程(连同它的子进程树)。
74
+ *
75
+ * @param {import("node:child_process").ChildProcess|null|undefined} child
76
+ * @param {{force?:boolean, platform?:string}} [opts] force=false 先礼后兵(bash→SIGTERM,
77
+ * Windows→taskkill /T 不带 /F);force=true 立刻硬杀(bash→SIGKILL,Windows→/T /F)。
78
+ */
79
+ export function killChildTree(child, opts = {}) {
80
+ const pid = child?.pid;
81
+ const platform = opts.platform ?? process.platform;
82
+ const force = opts.force === true;
83
+ if (!pid) {
84
+ try {
85
+ child?.kill(force ? "SIGKILL" : "SIGTERM");
86
+ } catch {
87
+ // 已经退出
88
+ }
89
+ return;
90
+ }
91
+ if (platform !== "win32") {
92
+ try {
93
+ child.kill(force ? "SIGKILL" : "SIGTERM");
94
+ } catch {
95
+ // 已经退出
96
+ }
97
+ return;
98
+ }
99
+ // Windows:没有信号可发,只能 taskkill。/T 带走整棵树,/F 是 TerminateProcess(≈SIGKILL)。
100
+ // 不带 /F 时 taskkill 发 WM_CLOSE,Node 子进程没有消息循环 → 通常要等 force 那一步。
101
+ const argv = ["/pid", String(pid), "/T"];
102
+ if (force) argv.push("/F");
103
+ try {
104
+ execFile("taskkill", argv, { windowsHide: true }, () => {
105
+ /* pid 已消失 / 无权限:都不影响调用方,force 分支会再补一刀 */
106
+ });
107
+ } catch {
108
+ // execFile 同步抛出(例如 taskkill 不可用)时退化成只杀直接子进程
109
+ try {
110
+ child.kill();
111
+ } catch {
112
+ // ignore
113
+ }
114
+ }
115
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * pi 版本可见性 —— 实测 `pi --version`(doctor 打印 + `/v1/health` 可选字段)。
3
+ *
4
+ * 为什么单独一层:pi 升级是 hub 最大的契约漂移来源(事件名、CLI flag、会话 JSONL 头),
5
+ * 所以「现在跑的 pi 是哪个版本」必须是一眼能看到的事实,而不是 README 里的一句「实测 1.8.0」。
6
+ * 不做兼容矩阵,只做可见性:拿不到版本就老实报错,让 doctor 非 0 退出。
7
+ *
8
+ * 用 `timeout -k` 兜住挂死的 pi:doctor 不能因为一个坏二进制卡住;
9
+ * 沙箱里没有 `timeout` 时退化为「直接 spawn + 自己的计时器」,口径仍然是「超时 = 失败」。
10
+ */
11
+ import { spawn } from "node:child_process";
12
+ import fs from "node:fs";
13
+ import { killChildTree, piSpawnSpec } from "./pi-spawn.mjs";
14
+
15
+ /** Windows 上没有 timeout(1),也起不了 .cmd 之外的东西 —— 直接由本进程的计时器兜底。 */
16
+ const TIMEOUT_BIN = process.platform === "win32" ? null : ["/usr/bin/timeout", "/bin/timeout"].find((p) => {
17
+ try {
18
+ return fs.existsSync(p);
19
+ } catch {
20
+ return false;
21
+ }
22
+ }) ?? null;
23
+
24
+ const DEFAULT_TIMEOUT_MS = 15000;
25
+
26
+ /**
27
+ * 跑一次 `pi --version`,解析出 x.y.z。
28
+ * @param {string} piBin
29
+ * @param {{timeoutMs?:number}} [opts]
30
+ * @returns {Promise<{ok:boolean, version?:string|null, raw?:string, error?:string}>}
31
+ */
32
+ export function probePiVersion(piBin, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
33
+ const seconds = Math.ceil(timeoutMs / 1000);
34
+ const spec = piSpawnSpec(piBin, ["--version"]);
35
+ const command = TIMEOUT_BIN ?? spec.file;
36
+ const args = TIMEOUT_BIN ? ["-k", "2", String(seconds), piBin, "--version"] : spec.args;
37
+ return new Promise((resolve) => {
38
+ let child;
39
+ try {
40
+ child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], ...(TIMEOUT_BIN ? {} : spec.options) });
41
+ } catch (err) {
42
+ resolve({ ok: false, error: `spawn failed: ${err.message}` });
43
+ return;
44
+ }
45
+ let out = "";
46
+ let err = "";
47
+ let settled = false;
48
+ const finish = (value) => {
49
+ if (settled) return;
50
+ settled = true;
51
+ clearTimeout(timer);
52
+ // 超时后整棵树收掉(Windows 上 pi 是 cmd.exe→pi.cmd→node,只杀直接子进程会留孤儿)。
53
+ killChildTree(child, { force: true });
54
+ resolve(value);
55
+ };
56
+ // 比 timeout(1) 多给 5s:正常情况下是 timeout 先动手并留下 124。
57
+ const timer = setTimeout(
58
+ () => finish({ ok: false, error: `pi --version 超时(${timeoutMs}ms 无结果)` }),
59
+ timeoutMs + 5000,
60
+ );
61
+ timer.unref?.();
62
+ child.stdout.on("data", (buf) => {
63
+ out += buf;
64
+ });
65
+ child.stderr.on("data", (buf) => {
66
+ err += buf;
67
+ });
68
+ child.on("error", (error) => finish({ ok: false, error: `spawn failed: ${error.message}` }));
69
+ child.on("close", (code, signal) => {
70
+ const text = `${out}\n${err}`.trim();
71
+ if (code !== 0) {
72
+ const head = text.split("\n")[0]?.slice(0, 200) ?? "";
73
+ finish({ ok: false, error: `pi --version 退出 ${code ?? signal}${head ? `:${head}` : ""}` });
74
+ return;
75
+ }
76
+ const match = /(\d+\.\d+\.\d+)/.exec(text);
77
+ if (!match) {
78
+ finish({ ok: false, error: `pi --version 输出里没有 x.y.z:${text.slice(0, 200)}` });
79
+ return;
80
+ }
81
+ finish({ ok: true, version: match[1], raw: text });
82
+ });
83
+ });
84
+ }
85
+
86
+ /** 最近一次探测结果(`/v1/health` 读它,永远不阻塞请求)。 */
87
+ let snapshot = { version: null, checkedAt: null, error: null };
88
+
89
+ export function piVersionSnapshot() {
90
+ return { ...snapshot };
91
+ }
92
+
93
+ /** 探测一次并更新快照;不抛错,失败只记 error。 */
94
+ export async function refreshPiVersion(piBin, opts) {
95
+ const result = await probePiVersion(piBin, opts);
96
+ snapshot = {
97
+ version: result.ok ? result.version : null,
98
+ checkedAt: new Date().toISOString(),
99
+ error: result.ok ? null : result.error,
100
+ };
101
+ return result;
102
+ }
103
+
104
+ /**
105
+ * 后台刷新(首次立即、之后每 intervalMs 一次)。定时器 unref:不拖住进程退出,
106
+ * 探测失败也只是 health 里 piVersion 保持 null,不影响任何请求。
107
+ */
108
+ export function startPiVersionRefresh(piBin, { intervalMs = 10 * 60 * 1000 } = {}) {
109
+ const tick = () => {
110
+ refreshPiVersion(piBin).catch(() => {});
111
+ };
112
+ tick();
113
+ const timer = setInterval(tick, intervalMs);
114
+ timer.unref?.();
115
+ return () => clearInterval(timer);
116
+ }
package/src/registry.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { MAX_LIVE, EVICT_IDLE_MS } from "./config.mjs";
2
- import { LiveSession } from "./pi-session.mjs";
2
+ import { LiveSession, unknownEventStats } from "./pi-session.mjs";
3
3
 
4
4
  export class HttpError extends Error {
5
5
  constructor(status, message, code = undefined) {
@@ -64,6 +64,15 @@ export class Registry {
64
64
  return candidate.id;
65
65
  }
66
66
 
67
+ /**
68
+ * 未知 pi 事件累计(跨会话聚合)。进程级单调计数:会话被淘汰后也不回落,
69
+ * 因为「这个 hub 见过多少不认识的事件」是升级漂移的证据,不该随会话消失。
70
+ * 直接给 `/v1/health.unknownEvents` 用。
71
+ */
72
+ unknownEvents() {
73
+ return unknownEventStats().total;
74
+ }
75
+
67
76
  get(id) {
68
77
  const s = this.live.get(id);
69
78
  return s && !s.closed ? s : null;
package/src/rpc-once.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { PI_BIN } from "./config.mjs";
3
3
  import { piArgs } from "./pi-args.mjs";
4
+ import { killChildTree, piSpawnSpec } from "./pi-spawn.mjs";
4
5
 
5
6
  /**
6
7
  * 一次性 pi RPC 调用(用于取模型表等不属于某会话的信息)。
@@ -11,7 +12,10 @@ import { piArgs } from "./pi-args.mjs";
11
12
  export function rpcOnce(type, payload = {}, opts = {}) {
12
13
  const timeoutMs = opts.timeoutMs ?? 20000;
13
14
  return new Promise((resolve, reject) => {
14
- const child = spawn(PI_BIN, piArgs({ noSession: true }), {
15
+ // 同 pi-session:Windows 上 pi 是 pi.cmd,必须经 cmd.exe(见 pi-spawn.mjs)。
16
+ const spec = piSpawnSpec(PI_BIN, piArgs({ noSession: true }));
17
+ const child = spawn(spec.file, spec.args, {
18
+ ...spec.options,
15
19
  cwd: opts.cwd ?? process.cwd(),
16
20
  env: { ...process.env, PI_HUB: "1" },
17
21
  stdio: ["pipe", "pipe", "ignore"],
@@ -22,14 +26,30 @@ export function rpcOnce(type, payload = {}, opts = {}) {
22
26
  if (settled) return;
23
27
  settled = true;
24
28
  clearTimeout(timer);
25
- try {
26
- child.kill("SIGTERM");
27
- } catch {
28
- // ignore
29
- }
29
+ killChildTree(child, { force: true });
30
30
  err ? reject(err) : resolve(value);
31
31
  };
32
32
  const timer = setTimeout(() => done(new Error(`pi rpc timeout: ${type}`)), timeoutMs);
33
+ /**
34
+ * 写一行到子进程 stdin,失败只判本次调用失败(→ 上层 5xx)。
35
+ * 裸 write 在子进程已退出 / spawn 失败时只会得到 EPIPE,而 stdin 没有 error 监听
36
+ * 就是未捕获异常 —— 实测 `PI_HUB_PI_BIN=/bin/true` 下一个 /v1/models 就能带走整个 hub。
37
+ */
38
+ const writeLine = (rec) => {
39
+ const stdin = child.stdin;
40
+ if (!stdin || stdin.destroyed || !stdin.writable) {
41
+ done(new Error(`pi stdin is not writable (${type})`));
42
+ return false;
43
+ }
44
+ try {
45
+ stdin.write(`${JSON.stringify(rec)}\n`);
46
+ return true;
47
+ } catch (err) {
48
+ done(new Error(`pi stdin write failed (${type}): ${err.message}`));
49
+ return false;
50
+ }
51
+ };
52
+ child.stdin.on("error", (err) => done(new Error(`pi stdin failed (${type}): ${err.message}`)));
33
53
  child.on("error", (err) => done(new Error(`spawn pi failed: ${err.message}`)));
34
54
  child.on("exit", (code) => {
35
55
  if (!settled) done(new Error(`pi exited (${code}) before answering ${type}`));
@@ -48,7 +68,7 @@ export function rpcOnce(type, payload = {}, opts = {}) {
48
68
  continue;
49
69
  }
50
70
  if (rec.type === "extension_ui_request") {
51
- child.stdin.write(`${JSON.stringify({ type: "extension_ui_response", id: rec.id, cancelled: true })}\n`);
71
+ writeLine({ type: "extension_ui_response", id: rec.id, cancelled: true });
52
72
  continue;
53
73
  }
54
74
  if (rec.type === "response" && rec.command === type) {
@@ -58,7 +78,7 @@ export function rpcOnce(type, payload = {}, opts = {}) {
58
78
  }
59
79
  }
60
80
  });
61
- child.stdin.write(`${JSON.stringify({ id: "one", type, ...payload })}\n`);
81
+ writeLine({ id: "one", type, ...payload });
62
82
  });
63
83
  }
64
84
 
package/src/server.mjs CHANGED
@@ -2,12 +2,12 @@ import http from "node:http";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
5
- import { AUTH_DISABLED, CONFIG_DIR, HEARTBEAT_MS, HOME, HOST, IDLE_MS, PORT, SESSIONS_DIR, UPLOAD_DIR, ensureToken, readToken } from "./config.mjs";
5
+ import { AUTH_DISABLED, CONFIG_DIR, HEARTBEAT_MS, HOME, HOST, IDLE_MS, PI_BIN, PORT, SESSIONS_DIR, UPLOAD_DIR, ensureToken, readToken } from "./config.mjs";
6
6
  import { findSession, listSessions, readHistory } from "./sessions-index.mjs";
7
7
  import { HttpError, Registry } from "./registry.mjs";
8
8
  import { listModels, rpcOnce } from "./rpc-once.mjs";
9
9
  import { extensionPaths, extensionsMode, piArgs } from "./pi-args.mjs";
10
- import { peek as peekSessionLock } from "./session-lock.mjs";
10
+ import { peek as peekSessionLock, corePath as sessionLockCorePath, lockSource as sessionLockSource } from "./session-lock.mjs";
11
11
  import { PairingStore, publicDevice, requireSignature } from "./pairing.mjs";
12
12
  import { mimeForFile, serveStatic } from "./static.mjs";
13
13
  import { WebAuth, clearSessionCookie, handleWebSessionRevoke, handleWebSessionsList, isSecureRequest, sessionCookie } from "./web-auth.mjs";
@@ -16,6 +16,7 @@ import { base32Decode, verifyTotp } from "./totp.mjs";
16
16
  import { isLocalRequest, parseTrustProxyEnv, resolveClientIp, resolveProxyIdentity } from "./proxy-auth.mjs";
17
17
  import { allowCidrsFromEnv, isPeerAllowed } from "./net-allow.mjs";
18
18
  import { HUB_VERSION, UpdateChecker } from "./update-check.mjs";
19
+ import { piVersionSnapshot, startPiVersionRefresh } from "./pi-version.mjs";
19
20
 
20
21
  const MAX_BODY = 16 * 1024 * 1024; // prompt 里带 base64 图片
21
22
  const MAX_UPLOAD = 32 * 1024 * 1024;
@@ -184,9 +185,11 @@ function normalizeMessages(messages, limit = 0) {
184
185
  if (!m || !m.role) continue;
185
186
  const blocks = Array.isArray(m.content) ? m.content : [{ type: "text", text: m.content ?? "" }];
186
187
  const parts = [];
188
+ const thinkingParts = [];
187
189
  const toolCalls = [];
188
190
  for (const b of blocks) {
189
191
  if (b?.type === "text" && b.text) parts.push(b.text);
192
+ else if (b?.type === "thinking" && b.thinking) thinkingParts.push(b.thinking);
190
193
  else if (b?.type === "toolCall") toolCalls.push({ id: b.id, name: b.name, args: b.args });
191
194
  }
192
195
  const ts = typeof m.timestamp === "number" ? new Date(m.timestamp).toISOString() : (m.timestamp ?? null);
@@ -194,6 +197,9 @@ function normalizeMessages(messages, limit = 0) {
194
197
  entryId: m.id ?? null,
195
198
  role: m.role,
196
199
  text: parts.join("\n"),
200
+ // 与会话文件路径(sessions-index.readHistory)同口径:思考正文回放给客户端「过程」折叠块。
201
+ thinking: thinkingParts.join("\n"),
202
+ toolCallId: m.toolCallId ?? null,
197
203
  toolCalls,
198
204
  ts,
199
205
  usage: m.usage ?? null,
@@ -321,8 +327,14 @@ function readJsonFile(file) {
321
327
  }
322
328
  }
323
329
 
330
+ /** Windows 的盘符/路径大小写不敏感,比较前统一小写(POSIX 上保持逐字比较,避免把不同目录混为一谈)。 */
331
+ function samePath(a, b) {
332
+ if (typeof a !== "string" || typeof b !== "string") return false;
333
+ return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
334
+ }
335
+
324
336
  function pathInside(root, real) {
325
- return real === root || real.startsWith(root + path.sep);
337
+ return samePath(real, root) || real.startsWith(root + path.sep);
326
338
  }
327
339
 
328
340
  /** pi 的扩展发现规则(docs/extensions.md):`*.ts/js` 文件、含 `index.*` 的目录、`pi.extensions` 非空的包。 */
@@ -807,6 +819,9 @@ export function createHubServer({ fetchJson } = {}) {
807
819
  );
808
820
  }
809
821
  const updates = new UpdateChecker(fetchJson ? { fetchJson } : {});
822
+ // pi 版本可见性(PLAN 约束 5):后台探测一次并每 10 min 刷新,`/v1/health` 读快照。
823
+ // 不 await:pi 挂死时 health 不能跟着挂;拿不到版本就只是字段为 null。
824
+ startPiVersionRefresh(PI_BIN);
810
825
  const reaper = setInterval(() => registry.reap(IDLE_MS), 60000);
811
826
  reaper.unref();
812
827
 
@@ -1060,7 +1075,20 @@ export function createHubServer({ fetchJson } = {}) {
1060
1075
 
1061
1076
  // GET /v1/health
1062
1077
  if (method === "GET" && url.pathname === "/v1/health") {
1063
- return json(res, 200, { ok: true, version: HUB_VERSION, liveSessions: registry.list().length, idleMs: IDLE_MS });
1078
+ const piVersion = piVersionSnapshot();
1079
+ return json(res, 200, {
1080
+ ok: true,
1081
+ version: HUB_VERSION,
1082
+ liveSessions: registry.list().length,
1083
+ idleMs: IDLE_MS,
1084
+ // 升级后第一眼看见契约漂移:不认识的事件数(进程级累计)。
1085
+ unknownEvents: registry.unknownEvents(),
1086
+ // 锁的实际来源:plugin = pi-session-lock,fallback = 仓内最小实现(与 doctor/banner 同口径)。
1087
+ sessionLock: sessionLockSource,
1088
+ // pi 实测版本(后台探测);未探到时为 null。
1089
+ piVersion: piVersion.version,
1090
+ piVersionCheckedAt: piVersion.checkedAt,
1091
+ });
1064
1092
  }
1065
1093
 
1066
1094
  // GET /v1/update[?android=<当前客户端版本>] 最新版本(缓存 1 h;上游失败也回 200 + error)
@@ -1218,7 +1246,9 @@ export function createHubServer({ fetchJson } = {}) {
1218
1246
  throw err;
1219
1247
  });
1220
1248
  const exported = path.resolve(data?.path ?? file);
1221
- if (path.dirname(exported) !== dir) throw new HttpError(500, `export wrote outside exports dir: ${exported}`);
1249
+ // pi 回给我们的路径可能是不同大小写(Windows 文件系统不敏感),别用 !== 直接判。
1250
+ if (!samePath(path.dirname(exported), dir))
1251
+ throw new HttpError(500, `export wrote outside exports dir: ${exported}`);
1222
1252
  // pi 按默认 umask 落盘(0644),统一收紧到 0600
1223
1253
  fs.chmodSync(exported, 0o600);
1224
1254
  const stat = fs.statSync(exported);
@@ -1589,9 +1619,26 @@ export function createHubServer({ fetchJson } = {}) {
1589
1619
  registry,
1590
1620
  pairing,
1591
1621
  token,
1622
+ /** 实际使用的锁来源与插件路径(banner / 测试读它,避免每处各自重新解析)。 */
1623
+ sessionLock: { source: sessionLockSource, corePath: sessionLockCorePath },
1624
+ /**
1625
+ * 起监听。**失败必须 reject**(旧实现只挂 listening 回调、没有 error 监听):
1626
+ * EADDRINUSE 会变成 `server` 上的未处理 'error' 事件,Node 直接打整屏栈崩掉 ——
1627
+ * 从零安装实测第二次 `pi-hub serve` 就踩(上一次的 hub 还在跑)。
1628
+ */
1592
1629
  listen({ port = PORT, host = HOST } = {}) {
1593
- return new Promise((resolve) => {
1594
- server.listen(port, host, () => resolve(server.address()));
1630
+ return new Promise((resolve, reject) => {
1631
+ const onError = (err) => {
1632
+ server.off("listening", onListening);
1633
+ reject(err);
1634
+ };
1635
+ const onListening = () => {
1636
+ server.off("error", onError);
1637
+ resolve(server.address());
1638
+ };
1639
+ server.once("error", onError);
1640
+ server.once("listening", onListening);
1641
+ server.listen(port, host);
1595
1642
  });
1596
1643
  },
1597
1644
  close() {