pi-hub-server 0.4.1 → 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.
package/README.md CHANGED
@@ -16,6 +16,10 @@ node test/smoke.mjs # 端到端冒烟:建会话→SSE→prompt
16
16
  node test/lock-and-resume.mjs # 会话复用 + 跨进程锁冲突
17
17
  ```
18
18
 
19
+ `pi-hub server` / `pi-hub start` 也认(`serve` 的口语别名);`listen.json` 只在监听**成功之后**才落盘,
20
+ 启动失败不会留下一个下次还会撞车的端口配置。端口被占时不会甩 Node 栈,而是报一句人话:
21
+ 认出占用者是不是另一个 pi-hub(直接用它就行)、不是就给出查进程命令和换端口办法。
22
+
19
23
  首次启动会生成 `~/.config/pi-hub/token`(0600),并在 banner 打印一次性 **6 位配对码**(5 分钟有效)与访问地址。
20
24
  所有请求带 `authorization: Bearer <token>`。
21
25
 
@@ -81,9 +85,12 @@ gh release download <tag> -R xiaquwan1001/pi-hub # 或从 Release 下
81
85
 
82
86
  ## CI
83
87
 
84
- `.github/workflows/ci.yml` 只跑 GitHub 云 runner(`ubuntu-latest`):Node 22 / 24 矩阵 →
85
- `node --check` 全量(`src/`、`test/`、`bin/`)→ `node test/events-passthrough.mjs` +
86
- `node test/registry-evict.mjs`(纯函数单测,不需要 `pi` 二进制)。
88
+ `.github/workflows/ci.yml` 只跑 GitHub 云 runner,矩阵是 **`ubuntu-latest` + `windows-latest` × Node 22 / 24**:
89
+ `npm run check`(`node --check` 全量 `src/`、`test/`、`bin/`,由 Node 自己枚举文件,不依赖 shell glob)→
90
+ `test/events-passthrough.mjs`、`test/registry-evict.mjs`、`test/pi-spawn.mjs`、`test/lock-fallback.mjs`、
91
+ `test/listen.mjs`(都不需要 `pi` 二进制)。
92
+
93
+ Windows 是**同等的 gate**,不是加分项:服务端要能在 Windows 上直接跑(见下节)。
87
94
 
88
95
  **不跑** `test/smoke.mjs` / `test/lock-and-resume.mjs`:它们要真 `pi` 可执行文件与会话目录,
89
96
  云 runner 上没有,跑了只会假红。`concurrency` 同 ref 去重、`timeout-minutes: 15`。
@@ -99,6 +106,30 @@ unit 里必须显式给 `PATH`(`%h/.pi/agent/bin` 打头):`spawn pi` 用
99
106
  systemd 开机时的默认 PATH 不含 pi 的安装目录,缺了会在重启后报 `spawn pi ENOENT`(建会话/模型列表全挂),
100
107
  而手工 `systemctl restart` 往往继承登录 shell 的 PATH,症状看不出来。
101
108
 
109
+ ## Windows
110
+
111
+ hub 本身是纯 Node(零依赖、无原生模块),Windows 上直接可用,但有三处平台差异必须知道:
112
+
113
+ ```powershell
114
+ npm i -g pi-hub-server
115
+ pi-hub doctor # 打印 platform: win32 x64 node vX / pi binary / session lock 来源
116
+ pi-hub serve
117
+ ```
118
+
119
+ - **`pi` 是 `pi.cmd`**:npm 在 Windows 上装出来的是批处理 shim,`spawn("pi")` 会直接 `EINVAL`。
120
+ hub 内部统一经 `src/pi-spawn.mjs`:裸命令名走 `cmd.exe /d /s /c` 并逐参数加引号,
121
+ 显式给成 `PI_HUB_PI_BIN=C:\nodejs\node.exe` 之类的 `.exe` 时仍直连(不经 shell)。
122
+ 命令行里 `%VAR%` 形式的片段仍会被 cmd 展开 —— 会话名/路径里别用 `%…%`。
123
+ - **没有 systemd**:Windows 上要开机自启就用「任务计划程序」(触发器=登录时,操作=`pi-hub.cmd serve`,
124
+ 「起始于」填工作目录),或用 `pm2 start pi-hub -- serve`。`systemd/pi-hub.service` 只对 Linux 有意义。
125
+ - **会话锁降级口子**:`pi-session-lock` 插件与仓内降级实现都靠 `/proc` 拿 boot_id 与进程 starttime。
126
+ Windows/macOS 上没有 `/proc`,这两条判定跳过,只剩「pid 还活着吗」——仍能证明持锁进程已死,
127
+ 但 pid 复用检测不可用(方向永远是 fail-open,互斥口径不变)。`pi-hub doctor` 会打印一行
128
+ `WARN 会话锁能力降级:…`,不是故障。
129
+ - 其余差异都由代码吸收掉了:`~/.config`、`~/.cache` 这类路径按 `os.homedir()` 拼(Windows 上是
130
+ `C:\Users\<你>`),`chmod 0600/0700` 在 Windows 上是 no-op,Tailscale 检测按网卡名/100.64.0.0/10 判而不读 `/sys/class/net`,
131
+ 首次 `serve` 的交互提问在 Windows 控制台读不了同步 stdin 时自动取默认值(不再抛崩)。
132
+
102
133
  ## 鉴权:四种入口
103
134
 
104
135
  | 入口 | 谁用 | 怎么开 | 要点 |
@@ -129,6 +160,11 @@ pi-hub totp verify 123456
129
160
  hub 自带同源网页 SPA(`web/`,原生 ES module、无框架、无 CDN、无构建步骤),手机浏览器直接开就是客户端:
130
161
 
131
162
  ```bash
163
+ # 本机最快路径:一条命令 = 确保回环 hub 在跑(没跑就后台起)+ 一次性码 + 直接打开浏览器
164
+ pi-hub web # http://127.0.0.1:6768/#code=XXXX-XXXX(码 2 min、单次)
165
+ pi-hub web --no-open # 只打印链接(远程/无桌面环境)
166
+ pi-hub web --port 6799 --ttl 30m # 换端口 + 浏览器会话 30 分钟后过期
167
+
132
168
  node bin/pi-hub.mjs serve
133
169
  # 手机与主机在同一 Tailscale/WireGuard 网段时打开:http://<主机地址>:6768/
134
170
  ```
@@ -316,8 +352,9 @@ PI_HUB_EXTENSIONS=off pi-hub serve # /v1/extensions → {extensions:[], mode:
316
352
  ### 历史来源两种形状
317
353
 
318
354
  `GET /v1/sessions/:id/history`:会话不在内存时读会话文件、在内存时走 RPC `get_messages`,
319
- 两种来源都规整成同一形状 `{entryId, role, text, toolCalls:[{id,name,args}], ts}`,
320
- 客户端不需要区分 `source`。
355
+ 两种来源都规整成同一形状 `{entryId, role, text, thinking, toolCallId, toolCalls:[{id,name,args}], ts}`,
356
+ 客户端不需要区分 `source`。`thinking` 是思考正文拼接(无则空串):历史回放也能展开「过程」里的思考,
357
+ `toolCallId`(仅 toolResult 有)让多个工具轮次能把输出并回正确的卡片;旧客户端忽略这两个字段。
321
358
 
322
359
  ### SSE 事件
323
360
 
package/bin/pi-hub.mjs CHANGED
@@ -1,10 +1,25 @@
1
1
  #!/usr/bin/env node
2
2
  import fs from "node:fs";
3
3
  import os from "node:os";
4
+ import path from "node:path";
4
5
  import { randomBytes } from "node:crypto";
6
+ import { spawn } from "node:child_process";
7
+ import { fileURLToPath } from "node:url";
5
8
 
6
9
  const argv = process.argv.slice(2);
7
- const command = argv.find((a) => !a.startsWith("-")) ?? "serve";
10
+ const COMMANDS = ["web", "serve", "token", "sessions", "doctor", "pair", "pair-code", "devices", "listen", "web-login", "web-sessions", "totp"];
11
+ /**
12
+ * 口语别名。从零安装实测的第一脚就是 `pi-hub server`(README 写的是 `serve`):
13
+ * 这种一眼能认的写法直接接受,不要让人先去查文档。
14
+ */
15
+ const COMMAND_ALIASES = new Map([
16
+ ["server", "serve"],
17
+ ["start", "serve"],
18
+ ["service", "serve"],
19
+ ["sessions-index", "sessions"],
20
+ ]);
21
+ const rawCommand = argv.find((a) => !a.startsWith("-")) ?? "serve";
22
+ const command = COMMAND_ALIASES.get(rawCommand) ?? rawCommand;
8
23
  const flag = (name, fallback) => {
9
24
  const i = argv.indexOf(name);
10
25
  return i >= 0 ? argv[i + 1] : fallback;
@@ -22,15 +37,22 @@ if (command === "serve" && has("--no-auth")) process.env.PI_HUB_NO_AUTH = "1";
22
37
 
23
38
  const { AUTH_DISABLED, CONFIG_DIR, PI_BIN, PORT, HOST, SESSIONS_DIR, ensureToken, readToken, tokenFile } = await import("../src/config.mjs");
24
39
  const { createHubServer } = await import("../src/server.mjs");
25
- const { SOURCE_LABELS, formatListenUrl, listenFile, removeListenFile, resolveListen, writeListenFile } = await import("../src/listen.mjs");
40
+ const { SOURCE_LABELS, formatListenUrl, listenFile, parsePort, removeListenFile, resolveListen, writeListenFile } = await import("../src/listen.mjs");
41
+ const { openerFor, openerArgs } = await import("../src/open-browser.mjs");
26
42
  const { listSessions } = await import("../src/sessions-index.mjs");
27
43
  const { PairingStore, isTrustedApprovalChannel } = await import("../src/pairing.mjs");
28
44
  const { base32Decode, base32Encode, otpauthUri, verifyTotp } = await import("../src/totp.mjs");
29
45
  // 锁来源与 pi 版本:doctor/banner 必须能报出「真的在用哪份实现」,降级不许静默。
30
- const { corePath: lockCorePath, lockSource } = await import("../src/session-lock.mjs");
46
+ const { capabilities: lockCapabilities, corePath: lockCorePath, lockSource } = await import("../src/session-lock.mjs");
31
47
  const { probePiVersion } = await import("../src/pi-version.mjs");
32
48
 
33
- /** 同步读一行(serve 首次启动的 listen.json 交互)。空输入 = 取默认。 */
49
+ /**
50
+ * 同步读一行(serve 首次启动的 listen.json 交互)。空输入 = 取默认。
51
+ *
52
+ * `fs.readSync(0, ...)` 只在 POSIX TTY 上可靠:Windows 的控制台句柄不支持同步读
53
+ * (ENXIO/EINVAL/EOF),旧实现在那里会把「第一次 serve」直接抛崩。读不了就当空输入
54
+ * (= 取默认值),交互只是便利功能,不该挡住启动。
55
+ */
34
56
  function readPromptSync(prompt) {
35
57
  process.stdout.write(prompt);
36
58
  const buf = Buffer.alloc(256);
@@ -42,7 +64,11 @@ function readPromptSync(prompt) {
42
64
  } catch (err) {
43
65
  if (err.code === "EAGAIN") continue;
44
66
  if (err.code === "EOF") break;
45
- throw err;
67
+ process.stdout.write(
68
+ `\n(当前终端不支持同步读入:${err.code ?? err.message},已取默认值;` +
69
+ "可用 --host/--port 或 PI_HUB_HOST/PI_HUB_PORT 指定)\n",
70
+ );
71
+ return "";
46
72
  }
47
73
  if (n === 0) break;
48
74
  text += buf.toString("utf8", 0, n);
@@ -50,13 +76,24 @@ function readPromptSync(prompt) {
50
76
  return text.split("\n")[0];
51
77
  }
52
78
 
53
- /** 本机是否有 Tailscale TUN(没有 TUN 时 serve 的 stderr 提一句出门怎么连)。 */
79
+ /**
80
+ * 本机是否有 Tailscale 出口(没有时 serve 的 stderr 提一句出门怎么连)。
81
+ *
82
+ * 以前读 `/sys/class/net`,那是 Linux 专有路径(Windows/macOS 直接 false)。
83
+ * 改用 `os.networkInterfaces()`:Linux 的 `tailscale0`、Windows 的 `Tailscale` 适配器
84
+ * 都按名字命中;macOS 是 utunN(名字看不出),再按 Tailscale 固定网段 100.64.0.0/10 判。
85
+ */
54
86
  function hasTailscaleTun() {
55
- try {
56
- return fs.readdirSync("/sys/class/net").some((name) => name.startsWith("tailscale"));
57
- } catch {
58
- return false;
87
+ const interfaces = os.networkInterfaces() ?? {};
88
+ for (const [name, addrs] of Object.entries(interfaces)) {
89
+ if (name.toLowerCase().startsWith("tailscale")) return true;
90
+ for (const addr of addrs ?? []) {
91
+ if (addr.family !== "IPv4" || addr.internal) continue;
92
+ const [a, b] = String(addr.address).split(".").map(Number);
93
+ if (a === 100 && b >= 64 && b <= 127) return true;
94
+ }
59
95
  }
96
+ return false;
60
97
  }
61
98
 
62
99
  /** `--ttl` 的会话有效期上下界(与 server.mjs 的 sessionTtlMs 校验一致)。 */
@@ -312,9 +349,12 @@ if (command === "sessions") {
312
349
  */
313
350
  if (command === "doctor") {
314
351
  const pi = await probePiVersion(PI_BIN);
352
+ console.log(`platform: ${process.platform} ${process.arch} node ${process.version}`);
315
353
  console.log(`pi binary: ${PI_BIN}`);
316
354
  if (pi.ok) console.log(`pi version: ${pi.version}`);
317
355
  console.log(`session lock: ${lockSource}${lockCorePath ? ` (${lockCorePath})` : ""}`);
356
+ const lockCaps = lockCapabilities();
357
+ if (lockCaps?.note) console.log(`WARN 会话锁能力降级:${lockCaps.note}`);
318
358
  if (lockSource === "fallback") {
319
359
  console.log("WARN 没找到 pi-session-lock,已降级到仓内最小实现(mkdir 原子抢锁 + owner.json 判死,互斥口径不变)");
320
360
  console.log(" 可选安装:npm i -g pi-session-lock(装上后这里会变成 session lock: plugin)");
@@ -355,6 +395,138 @@ if (command === "web-login") {
355
395
  process.exit(0);
356
396
  }
357
397
 
398
+ /**
399
+ * 探活 `GET /v1/health`。返回 `{up, ok, version, status}`:
400
+ * - `up=false`:连不上(没有进程在听这个端口);
401
+ * - `up=true, ok=false`:端口有人,但不认当前令牌(AUTH_DISABLED 的 hub 不带令牌也回 200,
402
+ * 所以再打一次无凭据请求,用来区分「关了鉴权」与「令牌对不上」)。
403
+ */
404
+ async function probeHub(apiBase, token) {
405
+ const attempt = async (headers) => {
406
+ const res = await fetch(`${apiBase}/v1/health`, { headers, signal: AbortSignal.timeout(1500) });
407
+ if (!res.ok) return { up: true, ok: false, status: res.status };
408
+ const data = await res.json().catch(() => null);
409
+ return { up: true, ok: data?.ok === true, status: res.status, version: data?.version ?? null };
410
+ };
411
+ try {
412
+ const first = await attempt(token ? { authorization: `Bearer ${token}` } : {});
413
+ if (first.ok || first.status !== 401) return first;
414
+ return await attempt({});
415
+ } catch {
416
+ return { up: false, ok: false, status: null };
417
+ }
418
+ }
419
+
420
+ if (command === "web") {
421
+ const ttlMs = readTtlFlag();
422
+ const rawPort = flag("--port", null);
423
+ const port = rawPort === null ? PORT : parsePort(rawPort);
424
+ if (port === null) {
425
+ console.error(`--port 无效:${rawPort}(应为 1..65535)`);
426
+ process.exit(2);
427
+ }
428
+ const host = flag("--host", HOST);
429
+ const noOpen = has("--no-open") || has("--print");
430
+ // 一次性码只能由主令牌换(`POST /v1/web/otp` 要求 loopback + primary);
431
+ // 令牌文件不存在时先生成一份——它本来就该在首次 serve 时生成,这里提前做不改变权限模型。
432
+ const token = readToken() ?? ensureToken();
433
+ const apiBase = `http://127.0.0.1:${port}`;
434
+
435
+ let health = await probeHub(apiBase, token);
436
+ let launched = null;
437
+ let logFile = null;
438
+ if (!health.up) {
439
+ logFile = path.join(CONFIG_DIR, "hub.log");
440
+ try {
441
+ fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
442
+ const out = fs.openSync(logFile, "a", 0o600);
443
+ const child = spawn(
444
+ process.execPath,
445
+ [fileURLToPath(import.meta.url), "serve", "--host", host, "--port", String(port)],
446
+ { detached: true, stdio: ["ignore", out, out], env: process.env },
447
+ );
448
+ child.unref();
449
+ fs.closeSync(out);
450
+ launched = child.pid;
451
+ } catch (err) {
452
+ console.error(`后台启动 hub 失败:${err.message}`);
453
+ process.exit(1);
454
+ }
455
+ // 等它开始 listen:pi 版本探测在后台跑,健康检查本身很快,15 s 足够慢机器起来。
456
+ for (let i = 0; i < 75; i += 1) {
457
+ await new Promise((resolve) => setTimeout(resolve, 200));
458
+ health = await probeHub(apiBase, token);
459
+ if (health.up) break;
460
+ }
461
+ if (!health.ok) {
462
+ console.error(`后台 hub 没起来(127.0.0.1:${port})。日志尾巴 ${logFile}:`);
463
+ try {
464
+ console.error(fs.readFileSync(logFile, "utf8").trim().split("\n").slice(-20).join("\n"));
465
+ } catch {
466
+ console.error("(日志读不到)");
467
+ }
468
+ console.error("提示:端口被别的进程占用时换 `--port`,或用 `pi-hub listen --port N` 固定下来。");
469
+ process.exit(1);
470
+ }
471
+ } else if (!health.ok) {
472
+ console.error(`127.0.0.1:${port} 上有服务在听,但不认当前主令牌(HTTP ${health.status ?? "?"})。`);
473
+ console.error(` 令牌文件:${tokenFile()}(同一个 PI_HUB_CONFIG_DIR 才能复用)`);
474
+ console.error(" 换端口/换配置目录,或先 `pi-hub web-sessions` 确认连的是哪个 hub。");
475
+ process.exit(1);
476
+ }
477
+
478
+ let otp;
479
+ try {
480
+ const res = await fetch(`${apiBase}/v1/web/otp`, {
481
+ method: "POST",
482
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
483
+ body: JSON.stringify(ttlMs === null ? {} : { sessionTtlMs: ttlMs }),
484
+ signal: AbortSignal.timeout(5000),
485
+ });
486
+ otp = await res.json().catch(() => null);
487
+ if (!res.ok) {
488
+ const code = otp?.error?.code ?? `http_${res.status}`;
489
+ console.error(`生成一次性登录码失败(${code}):${otp?.error?.message ?? ""}`.trim());
490
+ if (code === "rate_limited") console.error(" 每 IP 10 次/分钟,等一分钟再试。");
491
+ process.exit(1);
492
+ }
493
+ } catch (err) {
494
+ console.error(`生成一次性登录码失败:${err.message}`);
495
+ process.exit(1);
496
+ }
497
+
498
+ // 通配监听(0.0.0.0 / ::)时本机浏览器要连回环地址;具体 host 原样用。
499
+ const urlHost = ["0.0.0.0", "::", "[::]"].includes(host) ? "127.0.0.1" : host;
500
+ const url = `${formatListenUrl(urlHost, port)}/#code=${otp.code}`;
501
+
502
+ console.log(`网页已就绪:${url}`);
503
+ console.log(
504
+ launched === null
505
+ ? ` hub: 复用已在运行的进程(127.0.0.1:${port}${health.version ? `, v${health.version}` : ""})`
506
+ : ` hub: 已后台启动(pid ${launched},日志 ${logFile})`,
507
+ );
508
+ console.log(" 一次性码 2 min 内有效、单次使用;码只显示这一次(链接里带的就是它)");
509
+ console.log(
510
+ ttlMs === null
511
+ ? " 浏览器会话默认 30 天(--ttl 30m 可改成临时会话)"
512
+ : ` 浏览器会话有效期:${describeDuration(ttlMs)}(--ttl,不是码的有效期)`,
513
+ );
514
+ if (noOpen) {
515
+ console.log(" 未自动打开浏览器(--no-open):请手动打开上面的链接");
516
+ process.exit(0);
517
+ }
518
+ const opener = openerFor(process.platform);
519
+ try {
520
+ const child = spawn(opener.command, openerArgs(url, process.platform), { stdio: "ignore", detached: true });
521
+ child.on("error", () => {});
522
+ child.unref();
523
+ console.log(` 已在浏览器打开(${opener.command});没弹窗就手动开上面的链接,或用 --no-open 只打印`);
524
+ } catch {
525
+ console.log(` 打开浏览器失败:手动打开上面的链接(或用 --no-open 只打印)`);
526
+ }
527
+ process.exit(0);
528
+ }
529
+
358
530
  if (command === "web-sessions") {
359
531
  const revoke = flag("--revoke", null);
360
532
  let result;
@@ -432,9 +604,27 @@ if (command === "totp") {
432
604
  process.exit(2);
433
605
  }
434
606
 
607
+ /** 编辑距离(拿去猜命令笔误;命令表很短,O(n·m) 无所谓)。 */
608
+ function editDistance(a, b) {
609
+ const prev = Array.from({ length: b.length + 1 }, (_, i) => i);
610
+ for (let i = 1; i <= a.length; i += 1) {
611
+ let diag = prev[0];
612
+ prev[0] = i;
613
+ for (let j = 1; j <= b.length; j += 1) {
614
+ const tmp = prev[j];
615
+ prev[j] = Math.min(prev[j] + 1, prev[j - 1] + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));
616
+ diag = tmp;
617
+ }
618
+ }
619
+ return prev[b.length];
620
+ }
621
+
435
622
  if (command !== "serve") {
623
+ const guess = COMMANDS.map((name) => ({ name, d: editDistance(command, name) })).sort((x, y) => x.d - y.d)[0];
624
+ const hint = guess && guess.d <= 2 ? `\n提示: 你可能是想 \`pi-hub ${guess.name}\`。` : "";
436
625
  console.error(
437
- `unknown command: ${command}\nusage: pi-hub [serve|token|sessions|doctor|pair|pair-code|devices|listen|web-login|web-sessions|totp] [--port N] [--host H] [--no-auth]`,
626
+ `unknown command: ${command}${hint}\nusage: pi-hub [${COMMANDS.join("|")}] [--port N] [--host H] [--no-auth]\n` +
627
+ " pi-hub serve = 起 hub(最常用);pi-hub doctor = 自检;pi-hub web = 起回环 hub 并打开带一次性码的网页",
438
628
  );
439
629
  process.exit(2);
440
630
  }
@@ -455,20 +645,72 @@ try {
455
645
  console.error(err.message);
456
646
  process.exit(err.exitCode ?? 1);
457
647
  }
648
+ const port = listen.port;
649
+ const host = listen.host;
650
+ /**
651
+ * 端口占用时先判「占用者是不是另一个 pi-hub」:带主令牌打一次 /v1/health。
652
+ * 200 + {ok:true} → 就是 hub,把版本/锁来源/live sessions 一并报出来;
653
+ * 401 + {error:{code:"unauthorized"}} → 形状对得上,也是 hub(只是令牌不一致)。
654
+ * 连不上/其它形状 → 不是 hub(或不是 HTTP),让用户自己去查进程。
655
+ */
656
+ async function probeRunningHub({ host, port, token }) {
657
+ const targets = host === "0.0.0.0" || host === "::" ? ["127.0.0.1"] : [host];
658
+ for (const target of targets) {
659
+ const url = formatListenUrl(target, port);
660
+ try {
661
+ const res = await fetch(`${url}/v1/health`, {
662
+ headers: token ? { authorization: `Bearer ${token}` } : {},
663
+ signal: AbortSignal.timeout(1500),
664
+ });
665
+ const body = await res.json().catch(() => null);
666
+ if (res.ok && body?.ok) {
667
+ return { url, version: body.version ?? null, sessionLock: body.sessionLock ?? null, liveSessions: body.liveSessions ?? null };
668
+ }
669
+ if (res.status === 401 && body?.error?.code === "unauthorized") return { url, unauthenticated: true };
670
+ } catch {
671
+ // 不是 HTTP / 没在监听:继续下一个候选
672
+ }
673
+ }
674
+ return null;
675
+ }
676
+
677
+ const hub = createHubServer();
678
+
679
+ let address;
680
+ try {
681
+ address = await hub.listen({ port, host });
682
+ } catch (err) {
683
+ if (err.code !== "EADDRINUSE") {
684
+ console.error(`启动失败:${err.code ? `${err.code} ` : ""}${err.message}`);
685
+ process.exit(1);
686
+ }
687
+ const running = await probeRunningHub({ host, port, token: readToken() });
688
+ console.error(`端口 ${port} 已被占用(${host}:${port}),本次没有启动。`);
689
+ if (running?.version) {
690
+ console.error(
691
+ ` 占用者就是另一个 pi-hub:${running.url}(v${running.version},session lock: ${running.sessionLock},live sessions: ${running.liveSessions})`,
692
+ );
693
+ console.error(" 直接用它就行(不用再起一个);要重启:systemctl --user restart pi-hub,或先结束那个进程");
694
+ } else if (running) {
695
+ console.error(` ${running.url}/v1/health 回答 unauthorized —— 占用者很可能是另一个 pi-hub(本机令牌与它不一致)`);
696
+ console.error(" 直接用它就行;要重启先结束占用进程");
697
+ } else {
698
+ console.error(" 占用者不是 pi-hub(/v1/health 没有应答)。查是谁占着:");
699
+ console.error(process.platform === "win32" ? ` netstat -ano | findstr :${port}` : ` ss -ltnp | grep ':${port}'`);
700
+ }
701
+ console.error(` 换端口:pi-hub serve --port ${port === 65535 ? 65534 : port + 1}(要长期生效:pi-hub listen --port <N>)`);
702
+ process.exit(1);
703
+ }
704
+ const token = hub.token;
705
+ // listen.json 只在**监听真的成功之后**才落盘:以前先写后启动,端口被占时留下一个
706
+ // 占着旧端口的文件,下一次 serve 直接读它又崩一次,而且再也不提问(从零安装实测)。
458
707
  if (listen.prompted) {
459
708
  try {
460
- const file = writeListenFile({ host: listen.host, port: listen.port }, CONFIG_DIR);
461
- console.log(`已保存 ${file}`);
709
+ console.log(`已保存 ${writeListenFile({ host: listen.host, port: listen.port }, CONFIG_DIR)}`);
462
710
  } catch (err) {
463
711
  console.error(`写 ${listenFile(CONFIG_DIR)} 失败:${err.message}`);
464
712
  }
465
713
  }
466
- const port = listen.port;
467
- const host = listen.host;
468
- const hub = createHubServer();
469
-
470
- const address = await hub.listen({ port, host });
471
- const token = hub.token;
472
714
  console.log(`pi-hub listening on ${formatListenUrl(listen.host, address.port)}`);
473
715
  console.log(` auth: ${AUTH_DISABLED ? "DISABLED" : "bearer token"}`);
474
716
  // 降级不许静默:banner 也报一份,和后端 /v1/health 的 sessionLock 字段同一口径。
@@ -496,7 +738,9 @@ console.log(
496
738
  );
497
739
 
498
740
  let closing = false;
499
- for (const signal of ["SIGINT", "SIGTERM"]) {
741
+ // SIGBREAK 是 Windows 上 Ctrl+Break / 任务管理器「关闭」的信号;POSIX 没有它,按平台挑。
742
+ const STOP_SIGNALS = process.platform === "win32" ? ["SIGINT", "SIGBREAK"] : ["SIGINT", "SIGTERM"];
743
+ for (const signal of STOP_SIGNALS) {
500
744
  process.on(signal, async () => {
501
745
  if (closing) return;
502
746
  closing = true;
package/docs/AUTH.md CHANGED
@@ -69,7 +69,8 @@ curl -s -X POST http://<host>:<port>/v1/pair/claim \
69
69
  ## 网页会话 cookie(M3)
70
70
 
71
71
  ```bash
72
- pi-hub web-login # 一次性码(见 M4),也可直接 POST /v1/web/login {token}
72
+ pi-hub web # 本机最快路径:确保回环 hub 在跑 + 一次性码 + 打开浏览器
73
+ pi-hub web-login # 只发码(hub 已在跑时用这个),也可直接 POST /v1/web/login {token}
73
74
  pi-hub web-sessions # id / createdAt / lastSeenAt / expiresAt / ip
74
75
  pi-hub web-sessions --revoke <id> # 吊销一条(浏览器会立即掉线)
75
76
  pi-hub web-sessions --revoke all # 吊销全部
@@ -93,6 +94,7 @@ pi-hub web-sessions --revoke all # 吊销全部
93
94
  ```bash
94
95
  pi-hub web-login # 码默认 2 min,兑换出的会话默认 30 天
95
96
  pi-hub web-login --ttl 30m # 临时设备:会话 30 分钟后自动失效
97
+ pi-hub web --no-open # 同一次性码流程,但只打印链接(远程/无桌面环境)
96
98
  curl -s -X POST http://127.0.0.1:6768/v1/web/otp/redeem \
97
99
  -H 'content-type: application/json' -d '{"code":"XXXX-XXXX","sessionTtlMs":1800000}'
98
100
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-hub-server",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "type": "module",
5
5
  "description": "HTTP+SSE hub over pi RPC mode with a built-in web UI: one writer per session, many readers",
6
6
  "license": "MIT",
@@ -45,6 +45,7 @@
45
45
  "token": "node bin/pi-hub.mjs token",
46
46
  "doctor": "node bin/pi-hub.mjs doctor",
47
47
  "smoke": "node test/smoke.mjs",
48
- "prepublishOnly": "node --check bin/pi-hub.mjs && for f in src/*.mjs; do node --check \"$f\"; done"
48
+ "prepublishOnly": "node test/check-syntax.mjs",
49
+ "check": "node test/check-syntax.mjs"
49
50
  }
50
51
  }
@@ -0,0 +1,21 @@
1
+ // 打开系统默认浏览器:把「用哪个命令、参数怎么拼」抽成纯函数,便于单测(本模块不 spawn)。
2
+ //
3
+ // 为什么单独一个模块:`pi-hub web` 要「一条命令 = 起服务 + 打开带一次性码的网页」,
4
+ // 而「怎么开浏览器」是唯一与平台强相关、又不该把 bin/pi-hub.mjs 变成巨型 switch 的一段。
5
+ // 三个平台的口径(xdg-open / open / cmd start)在 test/open-browser.mjs 里锁死。
6
+
7
+ /**
8
+ * 平台对应的 opener。
9
+ * Windows 的 `start` 是 cmd 内建命令,第一个参数会被当成窗口标题 —— 必须先塞一个空标题。
10
+ */
11
+ export function openerFor(platform = process.platform) {
12
+ if (platform === "darwin") return { command: "open", args: [] };
13
+ if (platform === "win32") return { command: "cmd", args: ["/c", "start", ""] };
14
+ return { command: "xdg-open", args: [] };
15
+ }
16
+
17
+ /** opener 的完整 argv(opener 自身参数 + URL),顺序即 spawn 的参数顺序。 */
18
+ export function openerArgs(url, platform = process.platform) {
19
+ const { args } = openerFor(platform);
20
+ return [...args, String(url)];
21
+ }
@@ -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;
@@ -61,6 +62,8 @@ export class LiveSession {
61
62
  /** 正在执行的工具:toolCallId -> {name, args, startedAt, preview}。用于重连补状态。 */
62
63
  this.activeTools = new Map();
63
64
  this.child = null;
65
+ /** 子进程是否已经退出(exit/error 已到):关闭时不再按 pid 发信号,避免 Windows pid 复用误杀。 */
66
+ this.childExited = false;
64
67
  this.stdoutBuf = "";
65
68
  /** @type {string[]} */
66
69
  this.stderrTail = [];
@@ -106,8 +109,11 @@ export class LiveSession {
106
109
  async start() {
107
110
  this.#precheckLock();
108
111
  const args = piArgs({ sessionId: this.id, name: this.name, model: this.model });
109
- this.log("spawn", PI_BIN, args.join(" "), "cwd=", this.cwd);
110
- 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,
111
117
  cwd: this.cwd,
112
118
  // hub 自己就是进程外的锁管理者(#claimLock):子进程若也加载 host 的 session-lock 扩展,
113
119
  // 它会在 session_start 先认领会话锁,hub 再认领就得到 conflict(默认加载全部扩展后实测)。
@@ -117,10 +123,12 @@ export class LiveSession {
117
123
  });
118
124
 
119
125
  this.child.on("error", (err) => {
126
+ this.childExited = true;
120
127
  this.emit({ type: "error", message: `spawn failed: ${err.message}` });
121
128
  this.#shutdown("spawn_error");
122
129
  });
123
130
  this.child.on("exit", (code, signal) => {
131
+ this.childExited = true;
124
132
  this.log("exit", this.id, code, signal);
125
133
  this.#shutdown(`exit:${code ?? signal}`);
126
134
  });
@@ -411,14 +419,13 @@ export class LiveSession {
411
419
  this.closed = true;
412
420
  this.state.status = "closed";
413
421
  try {
414
- this.child?.kill("SIGTERM");
415
- setTimeout(() => {
416
- try {
417
- this.child?.kill("SIGKILL");
418
- } catch {
419
- // ignore
420
- }
421
- }, 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
+ }
422
429
  } catch {
423
430
  // ignore
424
431
  }
@@ -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
+ }
@@ -10,8 +10,10 @@
10
10
  */
11
11
  import { spawn } from "node:child_process";
12
12
  import fs from "node:fs";
13
+ import { killChildTree, piSpawnSpec } from "./pi-spawn.mjs";
13
14
 
14
- const TIMEOUT_BIN = ["/usr/bin/timeout", "/bin/timeout"].find((p) => {
15
+ /** Windows 上没有 timeout(1),也起不了 .cmd 之外的东西 —— 直接由本进程的计时器兜底。 */
16
+ const TIMEOUT_BIN = process.platform === "win32" ? null : ["/usr/bin/timeout", "/bin/timeout"].find((p) => {
15
17
  try {
16
18
  return fs.existsSync(p);
17
19
  } catch {
@@ -29,12 +31,13 @@ const DEFAULT_TIMEOUT_MS = 15000;
29
31
  */
30
32
  export function probePiVersion(piBin, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
31
33
  const seconds = Math.ceil(timeoutMs / 1000);
32
- const command = TIMEOUT_BIN ?? piBin;
33
- const args = TIMEOUT_BIN ? ["-k", "2", String(seconds), piBin, "--version"] : ["--version"];
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;
34
37
  return new Promise((resolve) => {
35
38
  let child;
36
39
  try {
37
- child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] });
40
+ child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], ...(TIMEOUT_BIN ? {} : spec.options) });
38
41
  } catch (err) {
39
42
  resolve({ ok: false, error: `spawn failed: ${err.message}` });
40
43
  return;
@@ -46,11 +49,8 @@ export function probePiVersion(piBin, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
46
49
  if (settled) return;
47
50
  settled = true;
48
51
  clearTimeout(timer);
49
- try {
50
- child.kill("SIGKILL");
51
- } catch {
52
- // 已经退出
53
- }
52
+ // 超时后整棵树收掉(Windows 上 pi 是 cmd.exe→pi.cmd→node,只杀直接子进程会留孤儿)。
53
+ killChildTree(child, { force: true });
54
54
  resolve(value);
55
55
  };
56
56
  // 比 timeout(1) 多给 5s:正常情况下是 timeout 先动手并留下 124。
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,11 +26,7 @@ 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);
package/src/server.mjs CHANGED
@@ -185,9 +185,11 @@ function normalizeMessages(messages, limit = 0) {
185
185
  if (!m || !m.role) continue;
186
186
  const blocks = Array.isArray(m.content) ? m.content : [{ type: "text", text: m.content ?? "" }];
187
187
  const parts = [];
188
+ const thinkingParts = [];
188
189
  const toolCalls = [];
189
190
  for (const b of blocks) {
190
191
  if (b?.type === "text" && b.text) parts.push(b.text);
192
+ else if (b?.type === "thinking" && b.thinking) thinkingParts.push(b.thinking);
191
193
  else if (b?.type === "toolCall") toolCalls.push({ id: b.id, name: b.name, args: b.args });
192
194
  }
193
195
  const ts = typeof m.timestamp === "number" ? new Date(m.timestamp).toISOString() : (m.timestamp ?? null);
@@ -195,6 +197,9 @@ function normalizeMessages(messages, limit = 0) {
195
197
  entryId: m.id ?? null,
196
198
  role: m.role,
197
199
  text: parts.join("\n"),
200
+ // 与会话文件路径(sessions-index.readHistory)同口径:思考正文回放给客户端「过程」折叠块。
201
+ thinking: thinkingParts.join("\n"),
202
+ toolCallId: m.toolCallId ?? null,
198
203
  toolCalls,
199
204
  ts,
200
205
  usage: m.usage ?? null,
@@ -322,8 +327,14 @@ function readJsonFile(file) {
322
327
  }
323
328
  }
324
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
+
325
336
  function pathInside(root, real) {
326
- return real === root || real.startsWith(root + path.sep);
337
+ return samePath(real, root) || real.startsWith(root + path.sep);
327
338
  }
328
339
 
329
340
  /** pi 的扩展发现规则(docs/extensions.md):`*.ts/js` 文件、含 `index.*` 的目录、`pi.extensions` 非空的包。 */
@@ -1235,7 +1246,9 @@ export function createHubServer({ fetchJson } = {}) {
1235
1246
  throw err;
1236
1247
  });
1237
1248
  const exported = path.resolve(data?.path ?? file);
1238
- 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}`);
1239
1252
  // pi 按默认 umask 落盘(0644),统一收紧到 0600
1240
1253
  fs.chmodSync(exported, 0o600);
1241
1254
  const stat = fs.statSync(exported);
@@ -1608,9 +1621,24 @@ export function createHubServer({ fetchJson } = {}) {
1608
1621
  token,
1609
1622
  /** 实际使用的锁来源与插件路径(banner / 测试读它,避免每处各自重新解析)。 */
1610
1623
  sessionLock: { source: sessionLockSource, corePath: sessionLockCorePath },
1624
+ /**
1625
+ * 起监听。**失败必须 reject**(旧实现只挂 listening 回调、没有 error 监听):
1626
+ * EADDRINUSE 会变成 `server` 上的未处理 'error' 事件,Node 直接打整屏栈崩掉 ——
1627
+ * 从零安装实测第二次 `pi-hub serve` 就踩(上一次的 hub 还在跑)。
1628
+ */
1611
1629
  listen({ port = PORT, host = HOST } = {}) {
1612
- return new Promise((resolve) => {
1613
- 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);
1614
1642
  });
1615
1643
  },
1616
1644
  close() {
@@ -34,6 +34,26 @@ export function enabled() {
34
34
  return true;
35
35
  }
36
36
 
37
+ /**
38
+ * 本平台的判活能力(doctor 打印;不影响互斥强度)。
39
+ *
40
+ * Linux 有 /proc:能拿到 boot_id 与 starttime,可以识别「pid 被复用」和「重启过」。
41
+ * 其他平台(Windows/macOS)没有等价节点:boot_id 读不到就留空(跳过重启判定),
42
+ * starttime 留空(跳过 pid 复用判定),只剩 pid 存活这一条 —— 仍能证明「已死」,
43
+ * 但判错方向永远是 fail-open(宁可判 unknown 也不误判 dead),互斥不受影响。
44
+ */
45
+ export function capabilities() {
46
+ const linux = process.platform === "linux";
47
+ return {
48
+ platform: process.platform,
49
+ bootId: linux,
50
+ startTicks: linux,
51
+ note: linux
52
+ ? null
53
+ : `${process.platform} 没有 /proc:只按 pid 存活判死,pid 复用与重启检测不可用(互斥口径不变)`,
54
+ };
55
+ }
56
+
37
57
  function readBootId() {
38
58
  try {
39
59
  return fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
@@ -92,3 +92,6 @@ export const claim = impl.claim;
92
92
  export const release = impl.release;
93
93
  export const classify = impl.classify;
94
94
  export const readOwner = impl.readOwner;
95
+ /** 判活能力(plugin 若没导出就报 plugin,doctor 只用来提示平台差异)。 */
96
+ export const capabilities =
97
+ typeof impl.capabilities === "function" ? impl.capabilities : () => ({ platform: process.platform, note: null });
@@ -157,15 +157,22 @@ export function readHistory(file, opts = {}) {
157
157
  if (!m) continue;
158
158
  const blocks = Array.isArray(m.content) ? m.content : [{ type: "text", text: m.content ?? "" }];
159
159
  const textParts = [];
160
+ const thinkingParts = [];
160
161
  const toolCalls = [];
161
162
  for (const b of blocks) {
162
163
  if (b?.type === "text" && b.text) textParts.push(b.text);
164
+ else if (b?.type === "thinking" && b.thinking) thinkingParts.push(b.thinking);
163
165
  else if (b?.type === "toolCall") toolCalls.push({ id: b.id, name: b.name, args: b.args });
164
166
  }
165
167
  out.push({
166
168
  entryId: rec.id,
167
169
  role: m.role,
168
170
  text: textParts.join("\n"),
171
+ // 思考正文:以前不回放,客户端「过程」折叠块重开会话后读不到思考内容(R4 实测)。
172
+ // 无 thinking 块时是空串,旧客户端忽略这个字段,契约向后兼容。
173
+ thinking: thinkingParts.join("\n"),
174
+ // toolResult 靠它并回对应工具卡片(多工具轮次里只看「上一条 tool」会堆错位置)。
175
+ toolCallId: m.toolCallId ?? null,
169
176
  toolCalls,
170
177
  ts: m.timestamp ? new Date(m.timestamp).toISOString() : rec.timestamp,
171
178
  usage: m.usage ?? null,