pi-hub-server 0.4.0 → 0.4.1

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
@@ -51,6 +51,24 @@ pi-hub doctor
51
51
  pi-hub serve
52
52
  ```
53
53
 
54
+ ### 前置:`pi` 必须在 PATH,锁插件是可选安装
55
+
56
+ - **`pi` 必须在 PATH 里**(`command -v pi` 有输出,或已 `npm i -g @earendil-works/pi-coding-agent`)。
57
+ hub 只是 pi 的代理:`pi-hub doctor` 会 spawn `pi --version` 实测并打印 `pi version: x.y.z`,
58
+ 取不到版本就直接**非 0 退出**(会话目录缺失、没 token 只算 WARN)。
59
+ 想用别的二进制:`PI_HUB_PI_BIN=/path/to/pi`。
60
+ - **`pi-session-lock` 是可选安装,缺了自动降级**(不是硬依赖,所以装在 `optionalDependencies`):
61
+
62
+ ```bash
63
+ npm i -g pi-session-lock # 可选:会话单写者判定用插件里的唯一实现
64
+ ```
65
+
66
+ 装了就自动用插件——`pi-hub doctor` 与 `serve` banner 会打 `session lock: plugin (<core.mjs 路径>)`,
67
+ `/v1/health` 里 `sessionLock: "plugin"`;没装(或用了 `npm i --omit=optional`)则降级到仓内自带
68
+ 的最小实现,同样打 `session lock: fallback`。**互斥口径不变**:还是 mkdir 原子抢锁 +
69
+ `owner.json` 判死,降级的只是插件侧的「让锁 / 自动 fork」等策略。
70
+ `doctor` 永远标注实际来源,所以「为什么我没装插件也没坏」和「我装了插件到底有没有生效」都是一眼可见的。
71
+
54
72
  > 为什么不是 `pi-hub`:unscoped 的 `pi-hub` 首发被 npm 相似度策略 403 拒绝("name too similar"),
55
73
  > 因此 `pi-hub-server` 才是 npm 上的正式名字;早先的 scoped 包 `@xuqianhui/pi-hub@0.3.1` 已弃用。
56
74
 
package/bin/pi-hub.mjs CHANGED
@@ -2,12 +2,6 @@
2
2
  import fs from "node:fs";
3
3
  import os from "node:os";
4
4
  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";
11
5
 
12
6
  const argv = process.argv.slice(2);
13
7
  const command = argv.find((a) => !a.startsWith("-")) ?? "serve";
@@ -17,6 +11,25 @@ const flag = (name, fallback) => {
17
11
  };
18
12
  const has = (name) => argv.includes(name);
19
13
 
14
+ /**
15
+ * `--no-auth` 必须在 config.mjs 求值之前落到 env。
16
+ * ESM 静态 import 先于模块体执行,旧写法(import 之后再 `process.env.PI_HUB_NO_AUTH = "1"`)
17
+ * 永远晚一步 —— `AUTH_DISABLED` 在 config.mjs 里已经定死,flag 等于空转。
18
+ * 所以这里先扫 argv,再动态 import 全部依赖;只有 serve 读这个 flag(其余子命令走 HTTP
19
+ * 主令牌,行为不变)。
20
+ */
21
+ if (command === "serve" && has("--no-auth")) process.env.PI_HUB_NO_AUTH = "1";
22
+
23
+ const { AUTH_DISABLED, CONFIG_DIR, PI_BIN, PORT, HOST, SESSIONS_DIR, ensureToken, readToken, tokenFile } = await import("../src/config.mjs");
24
+ const { createHubServer } = await import("../src/server.mjs");
25
+ const { SOURCE_LABELS, formatListenUrl, listenFile, removeListenFile, resolveListen, writeListenFile } = await import("../src/listen.mjs");
26
+ const { listSessions } = await import("../src/sessions-index.mjs");
27
+ const { PairingStore, isTrustedApprovalChannel } = await import("../src/pairing.mjs");
28
+ const { base32Decode, base32Encode, otpauthUri, verifyTotp } = await import("../src/totp.mjs");
29
+ // 锁来源与 pi 版本:doctor/banner 必须能报出「真的在用哪份实现」,降级不许静默。
30
+ const { corePath: lockCorePath, lockSource } = await import("../src/session-lock.mjs");
31
+ const { probePiVersion } = await import("../src/pi-version.mjs");
32
+
20
33
  /** 同步读一行(serve 首次启动的 listen.json 交互)。空输入 = 取默认。 */
21
34
  function readPromptSync(prompt) {
22
35
  process.stdout.write(prompt);
@@ -291,14 +304,34 @@ if (command === "sessions") {
291
304
  process.exit(0);
292
305
  }
293
306
 
307
+ /**
308
+ * `pi-hub doctor` 的口径(PLAN 约束 2):
309
+ * - pi 不可用 ⇒ 退出码非 0,并且输出里点名**那个坏路径**(假自检正是要治的病)
310
+ * - 会话目录缺失 / 没 token / 锁降级 ⇒ 只是 WARN,退出码仍 0
311
+ * (全新机器第一次跑时这些都还没生成,报错退出等于把开箱即用又堵死)
312
+ */
294
313
  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}`);
314
+ const pi = await probePiVersion(PI_BIN);
315
+ console.log(`pi binary: ${PI_BIN}`);
316
+ if (pi.ok) console.log(`pi version: ${pi.version}`);
317
+ console.log(`session lock: ${lockSource}${lockCorePath ? ` (${lockCorePath})` : ""}`);
318
+ if (lockSource === "fallback") {
319
+ console.log("WARN 没找到 pi-session-lock,已降级到仓内最小实现(mkdir 原子抢锁 + owner.json 判死,互斥口径不变)");
320
+ console.log(" 可选安装:npm i -g pi-session-lock(装上后这里会变成 session lock: plugin)");
321
+ }
322
+ const sessionsPresent = fs.existsSync(SESSIONS_DIR);
323
+ console.log(`sessions dir: ${SESSIONS_DIR} ${sessionsPresent ? "ok" : "MISSING"}`);
324
+ const token = readToken();
325
+ console.log(`token: ${token ? "present" : "will be created on first serve"}`);
326
+ console.log(`devices: ${new PairingStore().listDevices().length} paired`);
327
+ console.log(`sessions visible: ${listSessions({ limit: 5000, force: true }).length}`);
328
+ if (!sessionsPresent) console.log("WARN 会话目录还不存在:首次 serve / 第一次跑 pi 之后才会生成(不算失败)");
329
+ if (!token) console.log(`WARN token 还没有:首次 serve 会自动生成 ${tokenFile()}(不算失败)`);
330
+ if (!pi.ok) {
331
+ console.log(`FAIL pi 不可用(${PI_BIN}):${pi.error}`);
332
+ console.log(" hub 只是 pi 的代理:先把 pi 装进 PATH(或改 PI_HUB_PI_BIN 指到可用的二进制)。");
333
+ process.exit(1);
334
+ }
302
335
  process.exit(0);
303
336
  }
304
337
 
@@ -406,8 +439,7 @@ if (command !== "serve") {
406
439
  process.exit(2);
407
440
  }
408
441
 
409
- // serve
410
- if (has("--no-auth")) process.env.PI_HUB_NO_AUTH = "1";
442
+ // serve(--no-auth 已在文件顶部写进 env,晚于 import 会无效)
411
443
  let listen;
412
444
  try {
413
445
  listen = resolveListen({
@@ -439,6 +471,8 @@ const address = await hub.listen({ port, host });
439
471
  const token = hub.token;
440
472
  console.log(`pi-hub listening on ${formatListenUrl(listen.host, address.port)}`);
441
473
  console.log(` auth: ${AUTH_DISABLED ? "DISABLED" : "bearer token"}`);
474
+ // 降级不许静默:banner 也报一份,和后端 /v1/health 的 sessionLock 字段同一口径。
475
+ console.log(` session lock: ${lockSource}${lockCorePath ? ` (${lockCorePath})` : ""}`);
442
476
  // 路径必须走 CONFIG_DIR:PI_HUB_CONFIG_DIR 换目录时写死 ~/.config 会误导(V1 验收实测)。
443
477
  if (token) console.log(` token: ${token.length} chars (file: ${tokenFile()}) — 查看用 \`pi-hub token\``);
444
478
  console.log(` sessions dir: ${SESSIONS_DIR}`);
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.1",
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,6 +37,9 @@
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",
@@ -14,6 +14,26 @@ export const USAGE_THROTTLE_MS = 500;
14
14
  /** entry_appended 的 entry 序列化上限,超过则降级为 {type,id,truncated:true}。 */
15
15
  export const ENTRY_APPENDED_MAX_BYTES = 8192;
16
16
 
17
+ /**
18
+ * 未知 pi 事件计数(进程级)。
19
+ * pi 升级改名/新增事件时,hub 的 switch 会落到 default 分支:不静默丢弃,计数后由
20
+ * Registry 聚合到 `/v1/health.unknownEvents` —— 漂移的第一眼证据。
21
+ * 进程级(而不是按会话)是因为会话会被回收,而「这个 hub 见过多少不认识的事件」不该被回收掉。
22
+ */
23
+ const unknownEvents = { total: 0, byType: new Map() };
24
+
25
+ /** 记一条不认识的事件类型(type 可能缺失,统一记成 "(missing type)")。 */
26
+ export function noteUnknownEvent(type) {
27
+ unknownEvents.total += 1;
28
+ const key = typeof type === "string" && type ? type : "(missing type)";
29
+ unknownEvents.byType.set(key, (unknownEvents.byType.get(key) ?? 0) + 1);
30
+ }
31
+
32
+ /** 只读快照:`total` 进 /v1/health,`byType` 供日志/排查。 */
33
+ export function unknownEventStats() {
34
+ return { total: unknownEvents.total, byType: Object.fromEntries(unknownEvents.byType) };
35
+ }
36
+
17
37
  /** 把一个 pi RPC 子进程包装成「一写」会话:命令相关 + 事件规整 + 环形缓冲。 */
18
38
  export class LiveSession {
19
39
  /**
@@ -114,6 +134,9 @@ export class LiveSession {
114
134
  }
115
135
  });
116
136
  this.child.stdout.on("data", (chunk) => this.#onStdout(chunk));
137
+ // 子进程早退后往 stdin 写会 EPIPE:没有 error 监听时那是未捕获异常,会把 hub 一起带走。
138
+ // 真正的「只回 5xx」由 #write 的 writable 检查负责,这里只负责不让事件逃出去。
139
+ this.child.stdin.on("error", (err) => this.log("pi.stdin error", this.id, err.message));
117
140
 
118
141
  // 续会话时文件路径已经知道,先把锁抢下来(spawn→get_state 的窗口里 pi 会写元数据)。
119
142
  if (this.sessionFile) this.#claimLock(this.sessionFile);
@@ -194,6 +217,7 @@ export class LiveSession {
194
217
  return;
195
218
  }
196
219
  const out = normalizeEvent(rec, { lastUsageAt: this.lastUsageAt, now: Date.now() });
220
+ if (out.unknown) noteUnknownEvent(out.unknown);
197
221
  if (out.status !== undefined) this.state.status = out.status;
198
222
  if (out.streaming !== undefined) this.state.isStreaming = out.streaming;
199
223
  if (out.compacting !== undefined) this.state.isCompacting = out.compacting;
@@ -281,7 +305,24 @@ export class LiveSession {
281
305
 
282
306
  #write(rec) {
283
307
  if (!this.child || this.closed) throw new Error("session closed");
284
- this.child.stdin.write(`${JSON.stringify(rec)}\n`);
308
+ const stdin = this.child.stdin;
309
+ // spawn 失败(ENOENT / 坏 PI_HUB_PI_BIN)或子进程早退时 stdin 已不可写:
310
+ // 裸 write 只会得到 EPIPE,而 stdin 上没有 error 监听就是未捕获异常 ⇒ 带走整个 hub。
311
+ // 这里改成「只让这一次请求失败」,由上层回 5xx。
312
+ if (!stdin || stdin.destroyed || !stdin.writable) {
313
+ const err = new Error(`pi stdin is not writable (${this.id})`);
314
+ err.statusCode = 503;
315
+ err.code = "pi_stdin_closed";
316
+ throw err;
317
+ }
318
+ try {
319
+ stdin.write(`${JSON.stringify(rec)}\n`);
320
+ } catch (error) {
321
+ const err = new Error(`pi stdin write failed (${this.id}): ${error.message}`);
322
+ err.statusCode = 503;
323
+ err.code = "pi_stdin_closed";
324
+ throw err;
325
+ }
285
326
  }
286
327
 
287
328
  /** 发命令并等对应 response。 */
@@ -503,7 +544,8 @@ export function normalizeEvent(ev, ctx = {}) {
503
544
  case "thinking_level_changed":
504
545
  return { emit: { type: "thinking_level", level: ev.level } };
505
546
  default:
506
- return { emit: null };
547
+ // 不认识的事件类型:不静默丢弃,交回调用方计数(→ /v1/health.unknownEvents)。
548
+ return { emit: null, unknown: ev.type ?? "(missing type)" };
507
549
  }
508
550
  }
509
551
 
@@ -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
+
14
+ const TIMEOUT_BIN = ["/usr/bin/timeout", "/bin/timeout"].find((p) => {
15
+ try {
16
+ return fs.existsSync(p);
17
+ } catch {
18
+ return false;
19
+ }
20
+ }) ?? null;
21
+
22
+ const DEFAULT_TIMEOUT_MS = 15000;
23
+
24
+ /**
25
+ * 跑一次 `pi --version`,解析出 x.y.z。
26
+ * @param {string} piBin
27
+ * @param {{timeoutMs?:number}} [opts]
28
+ * @returns {Promise<{ok:boolean, version?:string|null, raw?:string, error?:string}>}
29
+ */
30
+ export function probePiVersion(piBin, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
31
+ 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
+ return new Promise((resolve) => {
35
+ let child;
36
+ try {
37
+ child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] });
38
+ } catch (err) {
39
+ resolve({ ok: false, error: `spawn failed: ${err.message}` });
40
+ return;
41
+ }
42
+ let out = "";
43
+ let err = "";
44
+ let settled = false;
45
+ const finish = (value) => {
46
+ if (settled) return;
47
+ settled = true;
48
+ clearTimeout(timer);
49
+ try {
50
+ child.kill("SIGKILL");
51
+ } catch {
52
+ // 已经退出
53
+ }
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
@@ -30,6 +30,26 @@ export function rpcOnce(type, payload = {}, opts = {}) {
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;
@@ -807,6 +808,9 @@ export function createHubServer({ fetchJson } = {}) {
807
808
  );
808
809
  }
809
810
  const updates = new UpdateChecker(fetchJson ? { fetchJson } : {});
811
+ // pi 版本可见性(PLAN 约束 5):后台探测一次并每 10 min 刷新,`/v1/health` 读快照。
812
+ // 不 await:pi 挂死时 health 不能跟着挂;拿不到版本就只是字段为 null。
813
+ startPiVersionRefresh(PI_BIN);
810
814
  const reaper = setInterval(() => registry.reap(IDLE_MS), 60000);
811
815
  reaper.unref();
812
816
 
@@ -1060,7 +1064,20 @@ export function createHubServer({ fetchJson } = {}) {
1060
1064
 
1061
1065
  // GET /v1/health
1062
1066
  if (method === "GET" && url.pathname === "/v1/health") {
1063
- return json(res, 200, { ok: true, version: HUB_VERSION, liveSessions: registry.list().length, idleMs: IDLE_MS });
1067
+ const piVersion = piVersionSnapshot();
1068
+ return json(res, 200, {
1069
+ ok: true,
1070
+ version: HUB_VERSION,
1071
+ liveSessions: registry.list().length,
1072
+ idleMs: IDLE_MS,
1073
+ // 升级后第一眼看见契约漂移:不认识的事件数(进程级累计)。
1074
+ unknownEvents: registry.unknownEvents(),
1075
+ // 锁的实际来源:plugin = pi-session-lock,fallback = 仓内最小实现(与 doctor/banner 同口径)。
1076
+ sessionLock: sessionLockSource,
1077
+ // pi 实测版本(后台探测);未探到时为 null。
1078
+ piVersion: piVersion.version,
1079
+ piVersionCheckedAt: piVersion.checkedAt,
1080
+ });
1064
1081
  }
1065
1082
 
1066
1083
  // GET /v1/update[?android=<当前客户端版本>] 最新版本(缓存 1 h;上游失败也回 200 + error)
@@ -1589,6 +1606,8 @@ export function createHubServer({ fetchJson } = {}) {
1589
1606
  registry,
1590
1607
  pairing,
1591
1608
  token,
1609
+ /** 实际使用的锁来源与插件路径(banner / 测试读它,避免每处各自重新解析)。 */
1610
+ sessionLock: { source: sessionLockSource, corePath: sessionLockCorePath },
1592
1611
  listen({ port = PORT, host = HOST } = {}) {
1593
1612
  return new Promise((resolve) => {
1594
1613
  server.listen(port, host, () => resolve(server.address()));
@@ -0,0 +1,203 @@
1
+ /**
2
+ * 内置的最小会话锁 —— 没装 `pi-session-lock` 插件时的降级实现。
3
+ *
4
+ * 为什么要有它:pi-hub 的唯一硬要求是「同一个 session .jsonl 只有一个写者」,
5
+ * 而插件只是这个判定的*首选*实现(它还带让锁/fork 策略)。全新机器上没装插件时
6
+ * 不能因此让 `pi-hub doctor` / `pi-hub serve` 崩掉,所以这里保留最小的一份。
7
+ *
8
+ * 与插件**共用同一个命名空间**:`<agentDir>/session-locks/<sha256(realpath(session))>.lock/owner.json`,
9
+ * 装了插件之后两边看到的是同一把锁,可以互相判活。判定口径也只保留插件文档里的那几条:
10
+ * 1. mkdir 的 O_EXCL 语义给出原子认领(并发抢锁只有一个成功)
11
+ * 2. owner.json 记录**实际写盘进程**的 pid / starttime / boot_id(hub 代管时是 pi 子进程)
12
+ * 3. 只有能证明 owner 已死(pid 没了 / pid 被复用 / 关机重启)才回收,其余一律 fail-open
13
+ * 降级不放宽互斥:抢到手的锁靠 mkdir 原子性保证,不依赖任何进程内状态。
14
+ * 删掉的是插件的额外策略(yield 请求、paseo 轮次、follow 转发),那些不影响互斥。
15
+ */
16
+ import fs from "node:fs";
17
+ import os from "node:os";
18
+ import path from "node:path";
19
+ import crypto from "node:crypto";
20
+
21
+ const HOST = os.hostname();
22
+
23
+ /** 与插件同一个 globalThis 键:真插件与 fallback 同进程加载时不会互相判成「别人」。 */
24
+ const IDENTITY = Symbol.for("pi.session-lock.identity");
25
+
26
+ export function resolveAgentDir(explicit) {
27
+ return explicit || process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent");
28
+ }
29
+
30
+ /** 逃生阀:`PI_SESSION_LOCK=off`(插件口径)/ `PI_HUB_NO_SESSION_LOCK=1` 都关锁。 */
31
+ export function enabled() {
32
+ if ((process.env.PI_SESSION_LOCK ?? "").toLowerCase() === "off") return false;
33
+ if (process.env.PI_HUB_NO_SESSION_LOCK === "1") return false;
34
+ return true;
35
+ }
36
+
37
+ function readBootId() {
38
+ try {
39
+ return fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
40
+ } catch {
41
+ return "";
42
+ }
43
+ }
44
+
45
+ function readStartTicks(pid) {
46
+ try {
47
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
48
+ // 字段从 "pid (comm) " 之后从 #3(state) 开始;starttime 是 #22 → 下标 19。
49
+ const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
50
+ return rest[19] ?? "";
51
+ } catch {
52
+ return "";
53
+ }
54
+ }
55
+
56
+ function isAlive(pid) {
57
+ try {
58
+ process.kill(pid, 0);
59
+ return true;
60
+ } catch (error) {
61
+ return error.code === "EPERM";
62
+ }
63
+ }
64
+
65
+ /** 本进程的稳定身份(Symbol 复用:同进程多次 import / 扩展 reload 不改 instanceId)。 */
66
+ export function identity() {
67
+ const g = globalThis;
68
+ if (!g[IDENTITY]) {
69
+ g[IDENTITY] = {
70
+ v: 1,
71
+ pid: process.pid,
72
+ host: HOST,
73
+ bootId: readBootId(),
74
+ startTicks: readStartTicks(process.pid),
75
+ instanceId: crypto.randomUUID(),
76
+ };
77
+ }
78
+ return g[IDENTITY];
79
+ }
80
+
81
+ /** 与插件逐字一致的锁目录:sha256(realpath(session)),文件还没落盘时退化为 path.resolve。 */
82
+ export function lockDirFor(sessionFile, opts = {}) {
83
+ const canonical = (() => {
84
+ try {
85
+ return fs.realpathSync(sessionFile);
86
+ } catch {
87
+ return path.resolve(sessionFile);
88
+ }
89
+ })();
90
+ const hash = crypto.createHash("sha256").update(canonical).digest("hex");
91
+ return path.join(resolveAgentDir(opts.agentDir), "session-locks", `${hash}.lock`);
92
+ }
93
+
94
+ export function readOwner(dir) {
95
+ try {
96
+ return JSON.parse(fs.readFileSync(path.join(dir, "owner.json"), "utf8"));
97
+ } catch {
98
+ return null;
99
+ }
100
+ }
101
+
102
+ /** live = 证明有另一个活进程;dead = 证明所有者已消失;unknown = 说不清(→ fail-open)。 */
103
+ export function classify(owner) {
104
+ const me = identity();
105
+ if (owner?.instanceId === me.instanceId) return { kind: "self", reason: "owned by this process" };
106
+ if (owner?.host !== HOST) return { kind: "unknown", reason: `owner on another host (${owner?.host})` };
107
+ if (owner?.bootId !== me.bootId) return { kind: "dead", reason: "host rebooted since lock was taken" };
108
+ if (typeof owner?.pid !== "number") return { kind: "unknown", reason: "owner has no pid" };
109
+ if (!isAlive(owner.pid)) return { kind: "dead", reason: `pid ${owner.pid} is gone` };
110
+ if (owner.startTicks && owner.startTicks !== readStartTicks(owner.pid))
111
+ return { kind: "dead", reason: `pid ${owner.pid} was reused (starttime mismatch)` };
112
+ return { kind: "live", reason: `pid ${owner.pid} is alive` };
113
+ }
114
+
115
+ /**
116
+ * 认领锁:mkdir 的 O_EXCL 语义是唯一原子点;死锁回收后重试(最多 3 次)。
117
+ *
118
+ * @param {string} sessionFile
119
+ * @param {{agentDir?:string, writerPid?:number, source?:string}} [opts]
120
+ * writerPid = 实际写盘进程(hub 传 pi 子进程 pid;不传则记自身)
121
+ * @returns {{ok:boolean, state:"owned"|"conflict"|"unknown"|"off", dir:string|null, reason:string, owner?:any}}
122
+ */
123
+ export function claim(sessionFile, opts = {}) {
124
+ if (!enabled()) return { ok: true, state: "off", dir: null, reason: "disabled" };
125
+ const dir = lockDirFor(sessionFile, opts);
126
+ const me = identity();
127
+ const writer = opts.writerPid ?? me.pid;
128
+
129
+ for (let attempt = 0; attempt < 3; attempt += 1) {
130
+ let taken = false;
131
+ try {
132
+ fs.mkdirSync(path.dirname(dir), { recursive: true, mode: 0o700 });
133
+ fs.mkdirSync(dir, { mode: 0o700 });
134
+ taken = true;
135
+ } catch (error) {
136
+ if (error.code !== "EEXIST") return { ok: false, state: "unknown", dir, reason: String(error) };
137
+ }
138
+ if (taken) {
139
+ const owner = {
140
+ ...me,
141
+ pid: writer,
142
+ startTicks: readStartTicks(writer),
143
+ source: opts.source ?? "pi-hub-fallback",
144
+ sessionFile,
145
+ acquiredAt: new Date().toISOString(),
146
+ };
147
+ // hub 代管时 pid 是 pi 子进程:hub 被 SIGKILL 后子进程也走了,锁随之判死;
148
+ // ownerPid 只为排查「谁认领的」。
149
+ if (me.pid !== writer) owner.ownerPid = me.pid;
150
+ try {
151
+ fs.writeFileSync(path.join(dir, "owner.json"), `${JSON.stringify(owner, null, 2)}\n`, { mode: 0o600 });
152
+ } catch (error) {
153
+ // 目录建了但 owner.json 写不进去:清掉,别留一把谁也认不出的锁。
154
+ try {
155
+ fs.rmSync(dir, { recursive: true, force: true });
156
+ } catch {
157
+ /* best effort */
158
+ }
159
+ return { ok: false, state: "unknown", dir, reason: `owner.json write failed: ${error.message}` };
160
+ }
161
+ return { ok: true, state: "owned", dir, reason: "claimed", owner };
162
+ }
163
+ const owner = readOwner(dir);
164
+ if (!owner || typeof owner.pid !== "number") {
165
+ return { ok: false, state: "unknown", dir, reason: "owner.json missing or malformed" };
166
+ }
167
+ const verdict = classify(owner);
168
+ if (verdict.kind === "self") return { ok: true, state: "owned", dir, reason: "already ours", owner };
169
+ if (verdict.kind === "unknown") return { ok: false, state: "unknown", dir, reason: verdict.reason, owner };
170
+ if (verdict.kind === "live") return { ok: false, state: "conflict", dir, reason: verdict.reason, owner };
171
+ // dead → 回收后重试
172
+ try {
173
+ fs.rmSync(dir, { recursive: true, force: true });
174
+ } catch {
175
+ return { ok: false, state: "unknown", dir, reason: "stale lock could not be removed" };
176
+ }
177
+ }
178
+ return { ok: false, state: "unknown", dir, reason: "lock reclaim retried 3x" };
179
+ }
180
+
181
+ /** 只读探测:不创建、不回收(DELETE ?delete=1 的 409 前置检查用)。 */
182
+ export function peek(sessionFile, opts = {}) {
183
+ if (!enabled()) return { state: "off", dir: null, owner: null, reason: "disabled" };
184
+ const dir = lockDirFor(sessionFile, opts);
185
+ if (!fs.existsSync(dir)) return { state: "none", dir, owner: null, reason: "no lock" };
186
+ const owner = readOwner(dir);
187
+ if (!owner || typeof owner.pid !== "number") {
188
+ return { state: "unknown", dir, owner: null, reason: "owner.json missing or malformed" };
189
+ }
190
+ const verdict = classify(owner);
191
+ return { state: verdict.kind, dir, owner, reason: verdict.reason };
192
+ }
193
+
194
+ /** 只释放自己持有的锁(按 instanceId 认),绝不误删别人的。 */
195
+ export function release(dir) {
196
+ if (!dir) return;
197
+ try {
198
+ const owner = readOwner(dir);
199
+ if (owner && owner.instanceId === identity().instanceId) fs.rmSync(dir, { recursive: true, force: true });
200
+ } catch {
201
+ /* best effort */
202
+ }
203
+ }
@@ -1,42 +1,94 @@
1
1
  /**
2
- * 会话锁 —— 只是 `~/pi-plugins/pi-session-lock/core.mjs` 的转发层。
2
+ * 会话锁 —— 优先用 `pi-session-lock` 插件的唯一实现,找不到就降级到内置最小实现。
3
3
  *
4
- * 唯一实现(含判定口径)在 plugin 里;pi 侧扩展与进程外调用方(pi-hub)共用它,
5
- * 避免两份算法漂移。找不到就直接报错:宁可 hub 起不来,也不要无锁写会话文件。
4
+ * 加载期**不再 throw**:全新机器上 `pi-hub doctor` / `pi-hub serve` 必须能起来
5
+ * (开箱即用是硬指标;旧实现 `throw new Error("pi-session-lock core not found")` 让
6
+ * 所有子命令连 import 都过不去)。降级不等于静默:`lockSource` 由 serve banner、
7
+ * `pi-hub doctor` 与 `/v1/health` 打出来,`corePath` 指到实际加载的那份。
8
+ *
9
+ * 解析顺序(显式优先,其次各处常见安装位置):
10
+ * 1. `PI_HUB_SESSION_LOCK_CORE`(显式指定,gate S6 用它验证 plugin 分支)
11
+ * 2. 自身 node_modules —— `require.resolve`,覆盖 `npm i -g pi-session-lock`(全局时是本包的
12
+ * 嵌套依赖)与仓内 `npm i pi-session-lock` 两种装法
13
+ * 3. 兄弟全局目录 `<prefix>/lib/node_modules/pi-session-lock/core.mjs`(两个包各自全局装)
14
+ * 4. `~/pi-plugins/pi-session-lock/core.mjs`(插件仓直接 clone 的装法)
15
+ * 5. `~/.pi/agent/npm/node_modules/pi-session-lock/core.mjs`(pi 自己的 npm 布局)
6
16
  */
7
17
  import fs from "node:fs";
8
18
  import path from "node:path";
9
- import { pathToFileURL } from "node:url";
19
+ import { createRequire } from "node:module";
20
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
21
  import { HOME } from "./config.mjs";
22
+ import * as fallbackLock from "./session-lock-fallback.mjs";
23
+
24
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
11
25
 
12
- const candidates = [
13
- process.env.PI_HUB_SESSION_LOCK_CORE,
14
- path.join(HOME, "pi-plugins", "pi-session-lock", "core.mjs"),
15
- path.join(HOME, ".pi", "agent", "npm", "node_modules", "pi-session-lock", "core.mjs"),
16
- ].filter(Boolean);
26
+ /** 插件必须给出的函数(= 本模块导出的全部读写面);缺一个就当没装(降级要显式,不能半残着跑)。 */
27
+ const REQUIRED = ["identity", "lockDirFor", "peek", "claim", "release", "classify", "readOwner"];
28
+
29
+ function resolveInstalled() {
30
+ const require = createRequire(import.meta.url);
31
+ // 插件的 exports 表里 "." 与 "./core" 都指向 core.mjs;两种写法都试,避免依赖表细节。
32
+ for (const specifier of ["pi-session-lock/core", "pi-session-lock"]) {
33
+ try {
34
+ return require.resolve(specifier);
35
+ } catch {
36
+ // 换下一个写法
37
+ }
38
+ }
39
+ return null;
40
+ }
41
+
42
+ function candidates() {
43
+ return [
44
+ process.env.PI_HUB_SESSION_LOCK_CORE,
45
+ resolveInstalled(),
46
+ path.join(HERE, "..", "node_modules", "pi-session-lock", "core.mjs"),
47
+ path.join(HERE, "..", "..", "pi-session-lock", "core.mjs"),
48
+ path.join(HOME, "pi-plugins", "pi-session-lock", "core.mjs"),
49
+ path.join(HOME, ".pi", "agent", "npm", "node_modules", "pi-session-lock", "core.mjs"),
50
+ ].filter(Boolean);
51
+ }
17
52
 
18
- const found = candidates.find((p) => {
53
+ function exists(p) {
19
54
  try {
20
55
  return fs.existsSync(p);
21
56
  } catch {
22
57
  return false;
23
58
  }
24
- });
59
+ }
60
+
61
+ const foundPath = candidates().find(exists) ?? null;
25
62
 
26
- if (!found) {
27
- throw new Error(
28
- `pi-session-lock core not found (looked in: ${candidates.join(", ")}).\n` +
29
- `Install the plugin at ~/pi-plugins/pi-session-lock or set PI_HUB_SESSION_LOCK_CORE.`,
30
- );
63
+ async function loadPlugin() {
64
+ if (!foundPath) return null;
65
+ let mod;
66
+ try {
67
+ mod = await import(pathToFileURL(foundPath).href);
68
+ } catch (err) {
69
+ console.error(`pi-session-lock(${foundPath})加载失败,降级到内置实现:${err.message}`);
70
+ return null;
71
+ }
72
+ const missing = REQUIRED.filter((name) => typeof mod[name] !== "function");
73
+ if (missing.length) {
74
+ console.error(`pi-session-lock(${foundPath})缺少 ${missing.join(", ")},降级到内置实现`);
75
+ return null;
76
+ }
77
+ return mod;
31
78
  }
32
79
 
33
- const core = await import(pathToFileURL(found).href);
80
+ const plugin = await loadPlugin();
81
+ const impl = plugin ?? fallbackLock;
82
+
83
+ /** 实际使用的锁实现来源:"plugin" | "fallback"(serve banner / doctor / /v1/health 都打它)。 */
84
+ export const lockSource = plugin ? "plugin" : "fallback";
85
+ /** 插件 core.mjs 的绝对路径;降级时为 null(内置实现的路径就是本仓 src/session-lock-fallback.mjs)。 */
86
+ export const corePath = plugin ? foundPath : null;
34
87
 
35
- export const corePath = found;
36
- export const identity = core.identity;
37
- export const lockDirFor = core.lockDirFor;
38
- export const peek = core.peek;
39
- export const claim = core.claim;
40
- export const release = core.release;
41
- export const classify = core.classify;
42
- export const readOwner = core.readOwner;
88
+ export const identity = impl.identity;
89
+ export const lockDirFor = impl.lockDirFor;
90
+ export const peek = impl.peek;
91
+ export const claim = impl.claim;
92
+ export const release = impl.release;
93
+ export const classify = impl.classify;
94
+ export const readOwner = impl.readOwner;
package/web/app.js CHANGED
@@ -814,6 +814,9 @@ function setStreamingUi(busy) {
814
814
 
815
815
  // ---------- UI 对话框(扩展 UI 桥) ----------
816
816
 
817
+ // 扩展对话框的兜底占位符:服务端(扩展)给了 ev.placeholder 就用它的;没给才用统一默认文案。
818
+ const UI_PLACEHOLDER_DEFAULT = { input: "输入…", editor: "输入多行文本…" };
819
+
817
820
  function renderUiRequest(ev) {
818
821
  const box = $("ui-requests");
819
822
  const wrap = document.createElement("div");
@@ -850,9 +853,13 @@ function renderUiRequest(ev) {
850
853
  button("确定", { confirmed: true }, "btn primary");
851
854
  button("取消", { confirmed: false });
852
855
  } else {
853
- const input = document.createElement("input");
854
- input.type = "text";
855
- input.placeholder = ev.placeholder ?? "";
856
+ // `editor` 是多行语义(pi 的 editor 请求),必须用 textarea;`input` 仍是单行。
857
+ // 两者都优先用服务端给的 placeholder / prefill,只有 placeholder 缺省时才回退到统一文案。
858
+ const multiline = ev.method === "editor";
859
+ const input = document.createElement(multiline ? "textarea" : "input");
860
+ if (multiline) input.rows = 8;
861
+ else input.type = "text";
862
+ input.placeholder = ev.placeholder || (multiline ? UI_PLACEHOLDER_DEFAULT.editor : UI_PLACEHOLDER_DEFAULT.input);
856
863
  input.value = ev.prefill ?? "";
857
864
  row.append(input);
858
865
  button("提交", null, "btn primary");