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.
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
 
@@ -51,6 +55,24 @@ pi-hub doctor
51
55
  pi-hub serve
52
56
  ```
53
57
 
58
+ ### 前置:`pi` 必须在 PATH,锁插件是可选安装
59
+
60
+ - **`pi` 必须在 PATH 里**(`command -v pi` 有输出,或已 `npm i -g @earendil-works/pi-coding-agent`)。
61
+ hub 只是 pi 的代理:`pi-hub doctor` 会 spawn `pi --version` 实测并打印 `pi version: x.y.z`,
62
+ 取不到版本就直接**非 0 退出**(会话目录缺失、没 token 只算 WARN)。
63
+ 想用别的二进制:`PI_HUB_PI_BIN=/path/to/pi`。
64
+ - **`pi-session-lock` 是可选安装,缺了自动降级**(不是硬依赖,所以装在 `optionalDependencies`):
65
+
66
+ ```bash
67
+ npm i -g pi-session-lock # 可选:会话单写者判定用插件里的唯一实现
68
+ ```
69
+
70
+ 装了就自动用插件——`pi-hub doctor` 与 `serve` banner 会打 `session lock: plugin (<core.mjs 路径>)`,
71
+ `/v1/health` 里 `sessionLock: "plugin"`;没装(或用了 `npm i --omit=optional`)则降级到仓内自带
72
+ 的最小实现,同样打 `session lock: fallback`。**互斥口径不变**:还是 mkdir 原子抢锁 +
73
+ `owner.json` 判死,降级的只是插件侧的「让锁 / 自动 fork」等策略。
74
+ `doctor` 永远标注实际来源,所以「为什么我没装插件也没坏」和「我装了插件到底有没有生效」都是一眼可见的。
75
+
54
76
  > 为什么不是 `pi-hub`:unscoped 的 `pi-hub` 首发被 npm 相似度策略 403 拒绝("name too similar"),
55
77
  > 因此 `pi-hub-server` 才是 npm 上的正式名字;早先的 scoped 包 `@xuqianhui/pi-hub@0.3.1` 已弃用。
56
78
 
@@ -63,9 +85,12 @@ gh release download <tag> -R xiaquwan1001/pi-hub # 或从 Release 下
63
85
 
64
86
  ## CI
65
87
 
66
- `.github/workflows/ci.yml` 只跑 GitHub 云 runner(`ubuntu-latest`):Node 22 / 24 矩阵 →
67
- `node --check` 全量(`src/`、`test/`、`bin/`)→ `node test/events-passthrough.mjs` +
68
- `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 上直接跑(见下节)。
69
94
 
70
95
  **不跑** `test/smoke.mjs` / `test/lock-and-resume.mjs`:它们要真 `pi` 可执行文件与会话目录,
71
96
  云 runner 上没有,跑了只会假红。`concurrency` 同 ref 去重、`timeout-minutes: 15`。
@@ -81,6 +106,30 @@ unit 里必须显式给 `PATH`(`%h/.pi/agent/bin` 打头):`spawn pi` 用
81
106
  systemd 开机时的默认 PATH 不含 pi 的安装目录,缺了会在重启后报 `spawn pi ENOENT`(建会话/模型列表全挂),
82
107
  而手工 `systemctl restart` 往往继承登录 shell 的 PATH,症状看不出来。
83
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
+
84
133
  ## 鉴权:四种入口
85
134
 
86
135
  | 入口 | 谁用 | 怎么开 | 要点 |
@@ -111,6 +160,11 @@ pi-hub totp verify 123456
111
160
  hub 自带同源网页 SPA(`web/`,原生 ES module、无框架、无 CDN、无构建步骤),手机浏览器直接开就是客户端:
112
161
 
113
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
+
114
168
  node bin/pi-hub.mjs serve
115
169
  # 手机与主机在同一 Tailscale/WireGuard 网段时打开:http://<主机地址>:6768/
116
170
  ```
@@ -298,8 +352,9 @@ PI_HUB_EXTENSIONS=off pi-hub serve # /v1/extensions → {extensions:[], mode:
298
352
  ### 历史来源两种形状
299
353
 
300
354
  `GET /v1/sessions/:id/history`:会话不在内存时读会话文件、在内存时走 RPC `get_messages`,
301
- 两种来源都规整成同一形状 `{entryId, role, text, toolCalls:[{id,name,args}], ts}`,
302
- 客户端不需要区分 `source`。
355
+ 两种来源都规整成同一形状 `{entryId, role, text, thinking, toolCallId, toolCalls:[{id,name,args}], ts}`,
356
+ 客户端不需要区分 `source`。`thinking` 是思考正文拼接(无则空串):历史回放也能展开「过程」里的思考,
357
+ `toolCallId`(仅 toolResult 有)让多个工具轮次能把输出并回正确的卡片;旧客户端忽略这两个字段。
303
358
 
304
359
  ### SSE 事件
305
360
 
package/bin/pi-hub.mjs CHANGED
@@ -1,23 +1,58 @@
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";
5
- import { AUTH_DISABLED, CONFIG_DIR, PI_BIN, PORT, HOST, SESSIONS_DIR, ensureToken, readToken, tokenFile } from "../src/config.mjs";
6
- import { createHubServer } from "../src/server.mjs";
7
- import { SOURCE_LABELS, formatListenUrl, listenFile, removeListenFile, resolveListen, writeListenFile } from "../src/listen.mjs";
8
- import { listSessions } from "../src/sessions-index.mjs";
9
- import { PairingStore, isTrustedApprovalChannel } from "../src/pairing.mjs";
10
- import { base32Decode, base32Encode, otpauthUri, verifyTotp } from "../src/totp.mjs";
6
+ import { spawn } from "node:child_process";
7
+ import { fileURLToPath } from "node:url";
11
8
 
12
9
  const argv = process.argv.slice(2);
13
- 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;
14
23
  const flag = (name, fallback) => {
15
24
  const i = argv.indexOf(name);
16
25
  return i >= 0 ? argv[i + 1] : fallback;
17
26
  };
18
27
  const has = (name) => argv.includes(name);
19
28
 
20
- /** 同步读一行(serve 首次启动的 listen.json 交互)。空输入 = 取默认。 */
29
+ /**
30
+ * `--no-auth` 必须在 config.mjs 求值之前落到 env。
31
+ * ESM 静态 import 先于模块体执行,旧写法(import 之后再 `process.env.PI_HUB_NO_AUTH = "1"`)
32
+ * 永远晚一步 —— `AUTH_DISABLED` 在 config.mjs 里已经定死,flag 等于空转。
33
+ * 所以这里先扫 argv,再动态 import 全部依赖;只有 serve 读这个 flag(其余子命令走 HTTP
34
+ * 主令牌,行为不变)。
35
+ */
36
+ if (command === "serve" && has("--no-auth")) process.env.PI_HUB_NO_AUTH = "1";
37
+
38
+ const { AUTH_DISABLED, CONFIG_DIR, PI_BIN, PORT, HOST, SESSIONS_DIR, ensureToken, readToken, tokenFile } = await import("../src/config.mjs");
39
+ const { createHubServer } = await import("../src/server.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");
42
+ const { listSessions } = await import("../src/sessions-index.mjs");
43
+ const { PairingStore, isTrustedApprovalChannel } = await import("../src/pairing.mjs");
44
+ const { base32Decode, base32Encode, otpauthUri, verifyTotp } = await import("../src/totp.mjs");
45
+ // 锁来源与 pi 版本:doctor/banner 必须能报出「真的在用哪份实现」,降级不许静默。
46
+ const { capabilities: lockCapabilities, corePath: lockCorePath, lockSource } = await import("../src/session-lock.mjs");
47
+ const { probePiVersion } = await import("../src/pi-version.mjs");
48
+
49
+ /**
50
+ * 同步读一行(serve 首次启动的 listen.json 交互)。空输入 = 取默认。
51
+ *
52
+ * `fs.readSync(0, ...)` 只在 POSIX TTY 上可靠:Windows 的控制台句柄不支持同步读
53
+ * (ENXIO/EINVAL/EOF),旧实现在那里会把「第一次 serve」直接抛崩。读不了就当空输入
54
+ * (= 取默认值),交互只是便利功能,不该挡住启动。
55
+ */
21
56
  function readPromptSync(prompt) {
22
57
  process.stdout.write(prompt);
23
58
  const buf = Buffer.alloc(256);
@@ -29,7 +64,11 @@ function readPromptSync(prompt) {
29
64
  } catch (err) {
30
65
  if (err.code === "EAGAIN") continue;
31
66
  if (err.code === "EOF") break;
32
- 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 "";
33
72
  }
34
73
  if (n === 0) break;
35
74
  text += buf.toString("utf8", 0, n);
@@ -37,13 +76,24 @@ function readPromptSync(prompt) {
37
76
  return text.split("\n")[0];
38
77
  }
39
78
 
40
- /** 本机是否有 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
+ */
41
86
  function hasTailscaleTun() {
42
- try {
43
- return fs.readdirSync("/sys/class/net").some((name) => name.startsWith("tailscale"));
44
- } catch {
45
- 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
+ }
46
95
  }
96
+ return false;
47
97
  }
48
98
 
49
99
  /** `--ttl` 的会话有效期上下界(与 server.mjs 的 sessionTtlMs 校验一致)。 */
@@ -291,14 +341,37 @@ if (command === "sessions") {
291
341
  process.exit(0);
292
342
  }
293
343
 
344
+ /**
345
+ * `pi-hub doctor` 的口径(PLAN 约束 2):
346
+ * - pi 不可用 ⇒ 退出码非 0,并且输出里点名**那个坏路径**(假自检正是要治的病)
347
+ * - 会话目录缺失 / 没 token / 锁降级 ⇒ 只是 WARN,退出码仍 0
348
+ * (全新机器第一次跑时这些都还没生成,报错退出等于把开箱即用又堵死)
349
+ */
294
350
  if (command === "doctor") {
295
- const checks = [];
296
- checks.push(["pi binary", PI_BIN]);
297
- checks.push(["sessions dir", `${SESSIONS_DIR} ${fs.existsSync(SESSIONS_DIR) ? "ok" : "MISSING"}`]);
298
- checks.push(["token", readToken() ? "present" : "will be created on first serve"]);
299
- checks.push(["devices", `${new PairingStore().listDevices().length} paired`]);
300
- checks.push(["sessions visible", String(listSessions({ limit: 5000, force: true }).length)]);
301
- for (const [k, v] of checks) console.log(`${k}: ${v}`);
351
+ const pi = await probePiVersion(PI_BIN);
352
+ console.log(`platform: ${process.platform} ${process.arch} node ${process.version}`);
353
+ console.log(`pi binary: ${PI_BIN}`);
354
+ if (pi.ok) console.log(`pi version: ${pi.version}`);
355
+ console.log(`session lock: ${lockSource}${lockCorePath ? ` (${lockCorePath})` : ""}`);
356
+ const lockCaps = lockCapabilities();
357
+ if (lockCaps?.note) console.log(`WARN 会话锁能力降级:${lockCaps.note}`);
358
+ if (lockSource === "fallback") {
359
+ console.log("WARN 没找到 pi-session-lock,已降级到仓内最小实现(mkdir 原子抢锁 + owner.json 判死,互斥口径不变)");
360
+ console.log(" 可选安装:npm i -g pi-session-lock(装上后这里会变成 session lock: plugin)");
361
+ }
362
+ const sessionsPresent = fs.existsSync(SESSIONS_DIR);
363
+ console.log(`sessions dir: ${SESSIONS_DIR} ${sessionsPresent ? "ok" : "MISSING"}`);
364
+ const token = readToken();
365
+ console.log(`token: ${token ? "present" : "will be created on first serve"}`);
366
+ console.log(`devices: ${new PairingStore().listDevices().length} paired`);
367
+ console.log(`sessions visible: ${listSessions({ limit: 5000, force: true }).length}`);
368
+ if (!sessionsPresent) console.log("WARN 会话目录还不存在:首次 serve / 第一次跑 pi 之后才会生成(不算失败)");
369
+ if (!token) console.log(`WARN token 还没有:首次 serve 会自动生成 ${tokenFile()}(不算失败)`);
370
+ if (!pi.ok) {
371
+ console.log(`FAIL pi 不可用(${PI_BIN}):${pi.error}`);
372
+ console.log(" hub 只是 pi 的代理:先把 pi 装进 PATH(或改 PI_HUB_PI_BIN 指到可用的二进制)。");
373
+ process.exit(1);
374
+ }
302
375
  process.exit(0);
303
376
  }
304
377
 
@@ -322,6 +395,138 @@ if (command === "web-login") {
322
395
  process.exit(0);
323
396
  }
324
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
+
325
530
  if (command === "web-sessions") {
326
531
  const revoke = flag("--revoke", null);
327
532
  let result;
@@ -399,15 +604,32 @@ if (command === "totp") {
399
604
  process.exit(2);
400
605
  }
401
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
+
402
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}\`。` : "";
403
625
  console.error(
404
- `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 并打开带一次性码的网页",
405
628
  );
406
629
  process.exit(2);
407
630
  }
408
631
 
409
- // serve
410
- if (has("--no-auth")) process.env.PI_HUB_NO_AUTH = "1";
632
+ // serve(--no-auth 已在文件顶部写进 env,晚于 import 会无效)
411
633
  let listen;
412
634
  try {
413
635
  listen = resolveListen({
@@ -423,22 +645,76 @@ try {
423
645
  console.error(err.message);
424
646
  process.exit(err.exitCode ?? 1);
425
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 直接读它又崩一次,而且再也不提问(从零安装实测)。
426
707
  if (listen.prompted) {
427
708
  try {
428
- const file = writeListenFile({ host: listen.host, port: listen.port }, CONFIG_DIR);
429
- console.log(`已保存 ${file}`);
709
+ console.log(`已保存 ${writeListenFile({ host: listen.host, port: listen.port }, CONFIG_DIR)}`);
430
710
  } catch (err) {
431
711
  console.error(`写 ${listenFile(CONFIG_DIR)} 失败:${err.message}`);
432
712
  }
433
713
  }
434
- const port = listen.port;
435
- const host = listen.host;
436
- const hub = createHubServer();
437
-
438
- const address = await hub.listen({ port, host });
439
- const token = hub.token;
440
714
  console.log(`pi-hub listening on ${formatListenUrl(listen.host, address.port)}`);
441
715
  console.log(` auth: ${AUTH_DISABLED ? "DISABLED" : "bearer token"}`);
716
+ // 降级不许静默:banner 也报一份,和后端 /v1/health 的 sessionLock 字段同一口径。
717
+ console.log(` session lock: ${lockSource}${lockCorePath ? ` (${lockCorePath})` : ""}`);
442
718
  // 路径必须走 CONFIG_DIR:PI_HUB_CONFIG_DIR 换目录时写死 ~/.config 会误导(V1 验收实测)。
443
719
  if (token) console.log(` token: ${token.length} chars (file: ${tokenFile()}) — 查看用 \`pi-hub token\``);
444
720
  console.log(` sessions dir: ${SESSIONS_DIR}`);
@@ -462,7 +738,9 @@ console.log(
462
738
  );
463
739
 
464
740
  let closing = false;
465
- 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) {
466
744
  process.on(signal, async () => {
467
745
  if (closing) return;
468
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.0",
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",
@@ -37,11 +37,15 @@
37
37
  "bin": {
38
38
  "pi-hub": "./bin/pi-hub.mjs"
39
39
  },
40
+ "optionalDependencies": {
41
+ "pi-session-lock": "^0.3.1"
42
+ },
40
43
  "scripts": {
41
44
  "start": "node bin/pi-hub.mjs serve",
42
45
  "token": "node bin/pi-hub.mjs token",
43
46
  "doctor": "node bin/pi-hub.mjs doctor",
44
47
  "smoke": "node test/smoke.mjs",
45
- "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"
46
50
  }
47
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
+ }