pi-hub-server 0.4.2 → 0.9.0
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/CHANGELOG.md +172 -0
- package/README.md +124 -43
- package/bin/pi-hub.mjs +332 -33
- package/docs/AUTH.md +5 -5
- package/docs/PLUGIN-DEPS.md +177 -0
- package/package.json +2 -4
- package/src/cli-control.mjs +309 -0
- package/src/help-text.mjs +215 -0
- package/src/lock-protocol.mjs +106 -0
- package/src/pi-session.mjs +91 -11
- package/src/server.mjs +217 -18
- package/src/session-lock-fallback.mjs +23 -19
- package/src/session-lock.mjs +124 -35
- package/src/sessions-index.mjs +176 -6
- package/src/static.mjs +6 -0
- package/systemd/pi-hub.service +2 -0
- package/web/app.js +753 -328
- package/web/compose.js +39 -0
- package/web/index.html +51 -20
- package/web/markdown.js +182 -0
- package/web/model.js +342 -0
- package/web/style.css +454 -58
- package/web/sw.js +1 -1
- package/web/tutorial.html +585 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
# hub 对 pi 插件/扩展的依赖与参与面(台账)
|
|
2
|
+
|
|
3
|
+
> 批次:第十批 lane P1(2026-12-06)。范围:`pi-hub/` 服务端。
|
|
4
|
+
> 插件仓 `~/pi-plugins/**` 只读;本文件的 `core.mjs:行` 以**本机 0.7.1(`15fc6c7`)**为准,
|
|
5
|
+
> 插件升级后行号会漂,符号名与 `CORE_API_VERSION` 才是契约。
|
|
6
|
+
> 机器可执行的断言:`test/session-lock-compat.mjs`(版本闸门)、`test/lock-conformance.mjs`(落盘协议一致性,
|
|
7
|
+
> 插件与内置实现跑同一批夹具逐条比对)、`test/no-plugin.mjs`(**无插件矩阵**:隔离副本不带 node_modules
|
|
8
|
+
> 跑 import/claim/conflict/release/serve+/v1/health,再用假 fixture 跑同一批证明插件通道没坏)、
|
|
9
|
+
> `test/lock-plugins.mjs`(参与面健壮性 + 显式指针配错口径)。
|
|
10
|
+
|
|
11
|
+
## 0. 一句话结论
|
|
12
|
+
|
|
13
|
+
hub 只在**一个插件**上有代码级**互通面**:`pi-session-lock` 的 `core.mjs`(进程外 import,不是扩展)。
|
|
14
|
+
它**不是依赖**:`package.json` 不声明它,没装时 hub 用自带的 `src/session-lock-fallback.mjs` 完整工作
|
|
15
|
+
(hub 内多端/多会话互斥、`409 session_locked`、锁交还全部照常);装了才多一项能力 —— **与桌面 pi
|
|
16
|
+
共用同一份锁**。插件 0.6.0 冻结的 `CORE_API_VERSION` 由 `src/session-lock.mjs` 强制校验,
|
|
17
|
+
不匹配就不用插件并打一行原因(`lockSource` 回到 `fallback`)。
|
|
18
|
+
|
|
19
|
+
**耦合面已经收成两条**(2026-12-06 lane lock-decouple):①`core.mjs` 的消费面(7 个符号 + API 版本),
|
|
20
|
+
②**落盘协议** —— 锁目录命名、`owner.json` 字段、`dead` 才能回收。第 ② 条以前是"两份实现靠人眼对齐",
|
|
21
|
+
现在常量只有一份(`src/lock-protocol.mjs`),差异由 `test/lock-conformance.mjs` 用同一批夹具
|
|
22
|
+
(none/live/dead/重启/跨主机/pid 复用/缺 owner/坏 JSON/缺 pid)跑两边逐条比对,漂了就红。
|
|
23
|
+
其余 7 个 host 包与 `extensions/` 3 项对 hub **没有代码依赖**:它们只跑在 hub spawn 的 pi
|
|
24
|
+
子进程里(`all` 模式由 pi 自己发现),hub 对它们的参与面是「只读清单 + 透传 `-e`」。
|
|
25
|
+
|
|
26
|
+
## 1. 依赖契约:`pi-session-lock` 的符号
|
|
27
|
+
|
|
28
|
+
`src/session-lock.mjs` 是唯一转发层;`REQUIRED_CORE_EXPORTS` 要求 7 个函数、
|
|
29
|
+
`SUPPORTED_CORE_API = 1` 是 hub 能消费的冻结版本 —— 两个常量现在都只在 `src/lock-protocol.mjs`
|
|
30
|
+
定义(fallback 与加载器的同一个真源),`session-lock.mjs` 从那里 import。
|
|
31
|
+
|
|
32
|
+
**自动发现只认三种安装布局**(`lockProto.lockCoreCandidates`,每条都带理由,`test/lock-conformance.mjs`
|
|
33
|
+
钉死这个集合):①本包依赖解析命中(你自己 `npm i pi-session-lock`)②`<prefix>/lib/node_modules`
|
|
34
|
+
并列全局安装 ③pi 自己的包目录 `~/.pi/agent/npm/node_modules`。**不再扫作者本机的仓目录布局**(原先的
|
|
35
|
+
`~/pi-plugins/pi-session-lock` 与同级 checkout 两条已删)——发布包不该在用户 home 里找别人的源码仓。
|
|
36
|
+
插件只在源码仓里(没装进上述任一位置)时,用 `PI_HUB_SESSION_LOCK_CORE=/path/to/core.mjs` 显式指;
|
|
37
|
+
`pi-hub doctor` 与 `serve` banner 在 `fallback` 分支会打出这行提示。
|
|
38
|
+
|
|
39
|
+
**显式指针 = 用户点名**:`PI_HUB_SESSION_LOCK_CORE` 指到不存在的文件/目录时**不再顺着上面这张表往下猜**,
|
|
40
|
+
而是进 `lockSource: "error"`:`serve`/`doctor` 打一行明确错误并以非 0 退出,锁操作(`claim`/`peek`/
|
|
41
|
+
`release`/…)抛同一条错误;**绝不静默换成内置锁**(那会让用户以为在共享锁,其实没有)。
|
|
42
|
+
import 期仍然不 throw —— `src/session-lock.mjs` 被所有子命令共享,import-time throw 会连带打死
|
|
43
|
+
`pi-hub token` / `-h` / `status`;这条不变量由 `test/no-plugin.mjs` + `test/lock-plugins.mjs` 钉住。
|
|
44
|
+
|
|
45
|
+
| 插件符号(0.7.1) | hub 侧使用点 | hub 缺失时的行为 | 备注 |
|
|
46
|
+
|---|---|---|---|
|
|
47
|
+
| `CORE_API_VERSION`(`core.mjs:35`) | `src/session-lock.mjs` 校验 | 缺失/≠1 ⇒ 不用插件(内置锁)+ 一行原因 | 0.6.0 起冻结;「不匹配就自己降级,不要猜算法」 |
|
|
48
|
+
| `claim(sessionFile, opts)`(`core.mjs:205`) | `src/pi-session.mjs:112`(写前 / spawn 窗口认领) | fallback `claim`(`src/session-lock-fallback.mjs:143`) | owner 带 `source:"pi-hub"`、`idleYield:true`、写者 pid |
|
|
49
|
+
| `peek(sessionFile, opts)`(`core.mjs:262`) | `src/pi-session.mjs:98`(attach 前冲突检查)、`src/server.mjs:1517`(删会话前判活) | fallback `peek`(`src/session-lock-fallback.mjs:202`) | 只读,不创建锁目录 |
|
|
50
|
+
| `release(dir)`(`core.mjs:278`) | `src/pi-session.mjs:135`(`#releaseLock`)、退出口 `:484` | fallback `release`(`src/session-lock-fallback.mjs:215`) | 只释放自己 claim 的目录 |
|
|
51
|
+
| `lockDirFor(sessionFile)`(`core.mjs:170`) | `test/lock-per-turn.mjs:42`、`test/smoke.mjs`(断言锁路径) | fallback `lockDirFor`(`src/session-lock-fallback.mjs:102`) | 生产代码不直接调,但测试与排障要它 |
|
|
52
|
+
| `identity()`(`core.mjs:113`) | 无生产调用 | fallback `identity`(`src/session-lock-fallback.mjs:86`) | 保留在 `REQUIRED` 是为了「插件/fallback 可整体互换」 |
|
|
53
|
+
| `classify(owner)`(`core.mjs:185`) | 无生产调用(`peek` 内部已用) | fallback `classify`(`src/session-lock-fallback.mjs:123`) | 同上 |
|
|
54
|
+
| `readOwner(dir)`(`core.mjs:176`) | 无生产调用;`test/lock-fallback.mjs:91` | fallback `readOwner`(`src/session-lock-fallback.mjs:114`) | 同上 |
|
|
55
|
+
|
|
56
|
+
**上报口径**(`src/server.mjs` 的 `sessionLockInfo()`,`/v1/health.sessionLockInfo`):
|
|
57
|
+
|
|
58
|
+
| 字段 | plugin 分支 | fallback 分支(默认) | error 分支(显式指针配错) |
|
|
59
|
+
|---|---|---|---|
|
|
60
|
+
| `source` | `"plugin"` | `"fallback"` | `"error"` |
|
|
61
|
+
| `corePath` | 实际 import 的 `core.mjs` | `null` | `null` |
|
|
62
|
+
| `pluginVersion` | 同目录 `package.json` 的 `version`(本机 `0.7.1`) | `null` | `null` |
|
|
63
|
+
| `coreApiVersion` | `1` | `null` | `null` |
|
|
64
|
+
| `supportedCoreApi` | `1` | `1` | `1` |
|
|
65
|
+
| `reason` | `null` | 一行中性原因(如「没有找到 pi-session-lock 插件(默认用内置锁)」) | 那条配置错误 |
|
|
66
|
+
| `hint` | `null` | 一行「要不要装」的可操作提示 | `null` |
|
|
67
|
+
| `explicitPointerError` | `null` | `null` | 一行配置错误(与 `reason` 同一条) |
|
|
68
|
+
|
|
69
|
+
`sessionLock`(字符串)保持旧形状不变,网页/安卓/`probeRunningHub` 不用改。
|
|
70
|
+
|
|
71
|
+
## 2. 插件提供但 hub **未使用**的能力(登记,不是缺口)
|
|
72
|
+
|
|
73
|
+
| 能力(0.7.1) | 为什么 hub 不用 |
|
|
74
|
+
|---|---|
|
|
75
|
+
| `requestYield` / `readYieldRequest` / `clearYieldRequest`(`core.mjs:390/418/438`) | hub 按轮持锁(`agent_settled` 释放,`src/pi-session.mjs:283`),不做长驻空转;见 §5 D6 |
|
|
76
|
+
| `readPresence` / `describeActivity`(`core.mjs:458/473`) | 冲突提示只在桌面扩展里用;hub 的 409 只需要 `peek` |
|
|
77
|
+
| `pruneLocks` / `maybePruneLocks`(`core.mjs:316/373`) | hub 的锁随子进程生命周期结束(`#shutdown` → `release`,`src/pi-session.mjs:484`);孤儿锁交给桌面 `/session-lock-gc` |
|
|
78
|
+
| `mailboxRoot`(`core.mjs:53`) | hub 不读写 pi-mailbox 名册 |
|
|
79
|
+
| `detectPaseo` / `paseoManaged`(`core.mjs:135/143`) | hub 只从环境收 `PI_HUB_*`;paseo 判断属于 pi 进程内扩展 |
|
|
80
|
+
| `waitForRelease`(`core.mjs:494`) | hub 冲突时直接 409 让客户端决定(重发 / 换会话),不阻塞 HTTP 请求 |
|
|
81
|
+
| `enabled()`(`core.mjs:66`) | hub 没装插件时靠 fallback 的同名逃生阀;装了插件时 `claim` 自己回 `state:"off"` |
|
|
82
|
+
| `canonicalSessionPath`(`core.mjs:161`) | 路径规范化由 `claim`/`peek` 内部做 |
|
|
83
|
+
| `describeOwner` / `releaseClaimed`(`core.mjs:154/296`) | 诊断/批量释放入口,hub 没有对应命令 |
|
|
84
|
+
|
|
85
|
+
## 3. 宿主 8 个 `settings.packages` 插件(`~/.pi/agent/settings.json:7-14`)
|
|
86
|
+
|
|
87
|
+
判定口径:`grep -rn <包名> src bin` 是否命中;hub 只是把这些包透传给子进程 pi
|
|
88
|
+
(`src/pi-args.mjs:21`/`:35`/`:60`,默认 `all` 模式不传 `--no-extensions`)。
|
|
89
|
+
|
|
90
|
+
| 包(版本) | hub 是否依赖 | 依据 / 参与点 |
|
|
91
|
+
|---|---|---|
|
|
92
|
+
| `npm:pi-subagents`(0.90.0) | 否 | `src/` 零引用;只作为 pi 子进程的扩展加载(`src/pi-args.mjs:64`) |
|
|
93
|
+
| `pi-agent-handoff`(0.2.0) | 否 | 零引用;同上是子进程扩展面 |
|
|
94
|
+
| `pi-auto`(0.11.4) | 否 | 零引用;`PI_HUB` 环境变量(`src/pi-session.mjs:161`)是插件侧识别 hub 的钩子,hub 不 import |
|
|
95
|
+
| `pi-mailbox`(0.4.0) | 否 | 零引用;信箱根由插件 `mailboxRoot` 决定,hub 不参与 |
|
|
96
|
+
| `web-search`(0.2.1) | 否 | 零引用;扩展只在 pi 子进程里注册工具 |
|
|
97
|
+
| `pi-file-write-guard`(0.3.3) | 否 | 零引用;写保护在 pi 进程内生效 |
|
|
98
|
+
| `pi-undo`(0.1.2) | 否 | 零引用;slash 命令由客户端透传 |
|
|
99
|
+
| `context-meter`(0.1.3) | 否 | 零引用;hub 自己的上下文口径来自会话文件 / `get_session_stats` |
|
|
100
|
+
|
|
101
|
+
hub 对这批包的**唯一写死假设**:pi 发现扩展的目录布局(`~/.pi/agent/extensions`、
|
|
102
|
+
`~/.pi/agent/npm/node_modules`、`settings.packages`)—— 只用于 `GET /v1/plugins` 只读清单
|
|
103
|
+
(`src/server.mjs:431` `resolvePackageDir`、`:447` `collectSettingsPackages`)。
|
|
104
|
+
|
|
105
|
+
## 4. `~/.pi/agent/extensions/` 3 项
|
|
106
|
+
|
|
107
|
+
| 条目 | 类型 | hub 是否依赖 | 依据 / 参与点 |
|
|
108
|
+
|---|---|---|---|
|
|
109
|
+
| `session-lock.ts` | 符号链接 → `~/pi-plugins/pi-session-lock/extensions/session-lock.ts` | **间接**:共用同一份 `core.mjs` 与锁命名空间,但 hub 不让子进程加载它 | `src/pi-session.mjs:158-161`:子进程带 `PI_SESSION_LOCK=off`,hub 自己是进程外锁管理者 |
|
|
110
|
+
| `subagent/` | 目录扩展(`index` / `pi.extensions`) | 否 | 零引用;子代理跑在 pi 进程内 |
|
|
111
|
+
| `sudo-ttl.ts` | 符号链接 → `~/pi-plugins/sudo-ttl.ts` | 否 | 零引用;只在 pi 进程里管 sudo 凭证 TTL |
|
|
112
|
+
|
|
113
|
+
`GET /v1/extensions`(`src/server.mjs:1183`)报的是 hub 自己 `-e` 的列表;`GET /v1/plugins`
|
|
114
|
+
(`src/server.mjs:1188`)是主机侧只读清单。两者都不断言「插件一定健康」,只给 `ok/exists`。
|
|
115
|
+
|
|
116
|
+
## 5. 重构影响与时间线(D5)
|
|
117
|
+
|
|
118
|
+
| 插件侧变化(版本) | hub 现状 | 影响 | 处置 |
|
|
119
|
+
|---|---|---|---|
|
|
120
|
+
| `CORE_API_VERSION=1` 冻结(0.6.0) | 旧 `src/session-lock.mjs` 只查 7 个函数存在性 | **会 break 的隐患**:插件升到 2 时 hub 会拿未知算法抢锁 | **已改**:先验版本,不匹配就不用插件 + `lockReason` 上报;`test/session-lock-compat.mjs` 有 v0/缺失/缺函数/抛异常 4 个断言 |
|
|
121
|
+
| fork + 重放吸收进 `lib/fork.mjs`,`pi-session-fork` 退役(0.7.1) | hub 不 import fork/重放,也不暴露 `/fork-session` | 无 break;hub 的 `/v1/sessions/:id/fork` 走 pi 原生 RPC(`src/server.mjs:1455`) | 登记:hub 的 fork 语义不依赖插件命令 |
|
|
122
|
+
| 只读跟随拆到 `pi-session-follow`(0.7.0) | hub 没有跟随功能,也不 import follow | 无影响;`/v1/plugins` 的 npm 清单可能多出 `pi-session-follow` 条目 | 登记:`collectNpmPackages` 只按 `pi` 字段/`pi-package` 关键词收集(`src/server.mjs:489`/`:519`),不硬编码包名 |
|
|
123
|
+
| 冲突策略改 ask/fork/follow/block(0.6.x) | hub attach 前只 `peek` → 409(`src/pi-session.mjs:98`) | **缓解 E9**:桌面 TUI 不再「被硬拦」,可弹窗选择 fork/follow(`extensions/session-lock.ts:10-16`) | 登记:hub 继续 409,不实现询问 |
|
|
124
|
+
| 让锁协议 `yield-request.json`(0.6.x) | hub 在 `agent_settled` 释放(`:283`),空闲不持锁 | 回合内不让锁(正确);attach 后首轮前的窗口仍持锁 | **本轮不做**,理由见 D6 |
|
|
125
|
+
| 孤儿锁回收 `pruneLocks`(0.7.0) | hub 靠 `#shutdown` 释放 + fallback 判死 | 无 break;hub 崩溃留下的锁由桌面 `/session-lock-gc` 或下次 `claim` 判死回收 | 登记:不重复实现扫描 |
|
|
126
|
+
| `owner.sessionFile` 改绝对路径(0.7.0) | hub 写 owner 时只透传 `sessionFile`(`src/pi-session.mjs:112`) | 无 break;hub 的 fallback 与插件写同一字段 | 登记:hub 不做路径重写 |
|
|
127
|
+
| 依赖声明从 `^0.3.1` 落后到 `0.7.1` | `package.json` | `npm i --omit=optional` 时 0.3.x 没有 `CORE_API_VERSION` ⇒ 会被判「不匹配」而不用插件(旧行为是静默使用) | **已改(2026-12-06 lane lock-optional)**:`optionalDependencies` **整条删除** —— hub 不预设插件存在,装不装由用户决定 |
|
|
128
|
+
|
|
129
|
+
**时间线**:0.3.x(hub 最初对齐的版本)→ 0.6.0 冻结 `CORE_API_VERSION` → 0.7.0 拆 follow/fork +
|
|
130
|
+
孤儿锁回收 → 0.7.1 吸收 fork 重放。hub 本轮只跟到「读版本 + 决定用不用 + 上报」,不追 fork/follow/yield 功能。
|
|
131
|
+
|
|
132
|
+
### D6:让锁协议(`requestYield`)/ E9「空闲 attach 是否让锁」——本轮**不做**,理由
|
|
133
|
+
|
|
134
|
+
1. hub 的持锁窗口已经按轮收敛:写命令前 `#ensureLock`(`src/pi-session.mjs:142`/`:384`),
|
|
135
|
+
`agent_settled` 立即 `#releaseLock`(`:283`)。插件 README 描述的「长驻空转持有者」在 hub 上不成立,
|
|
136
|
+
轮询 `readYieldRequest` 没有可让的窗口。
|
|
137
|
+
2. 回合内让锁等于放弃「同一 .jsonl 只有一个写者」的硬约束,不能做。
|
|
138
|
+
3. 剩下的真实窗口是 **attach/resume 后、首轮前**(`start()` 认领后一直持到第一轮结束)。
|
|
139
|
+
这会挡住桌面 TUI,但插件 0.7 默认 `ask` 策略已经把它变成「弹窗选 fork / 只读跟随」,
|
|
140
|
+
不再是不可恢复的死锁(`extensions/session-lock.ts:10-16`、`:341`)。
|
|
141
|
+
4. 要真正修这个窗口,必须同批改三处(`pi-session` 释放时机 + `test/lock-per-turn.mjs` 断言 +
|
|
142
|
+
`/v1/sessions/:id/state` 的 owner 口径),并需要真机/桌面 TUI 对照验证;r7 曾只改一处
|
|
143
|
+
把 gate 打红后撤回(`84fd858`)。本轮只做依赖治理,不夹带行为变更。
|
|
144
|
+
5. 登记为后续独立一轮(E9):建议实现为「`start()` 的 get_state 返回后、且 `!isStreaming` 时
|
|
145
|
+
`#releaseLock()`;`rekey()` 保持认领(换文件发生在写命令内部)」——**不要在写命令的 response
|
|
146
|
+
回调里释放**,pi 的 response 可能早于 `agent_settled`。
|
|
147
|
+
|
|
148
|
+
## 6. 模式矩阵(`src/session-lock.mjs`)
|
|
149
|
+
|
|
150
|
+
| 场景 | `lockSource` | 控制台 | `sessionLockInfo` |
|
|
151
|
+
|---|---|---|---|
|
|
152
|
+
| 找到 v1 core + 7 函数齐 | `plugin` | 无 | 版本/路径齐全,`reason`/`hint` 皆 null |
|
|
153
|
+
| 找不到 core.mjs(**默认**) | `fallback` | **无**(不刷屏) | `reason`=「没有找到…」+ `hint`=「要不要装」那一行 |
|
|
154
|
+
| `CORE_API_VERSION` 缺失 | `fallback` | 一行:缺少 CORE_API_VERSION | `reason` 同上,版本字段 null |
|
|
155
|
+
| `CORE_API_VERSION` ≠ 1 | `fallback` | 一行:`CORE_API_VERSION=x` 不兼容 | 同上 |
|
|
156
|
+
| 缺任一 `REQUIRED` 函数 | `fallback` | 一行:缺少 xxx | 同上 |
|
|
157
|
+
| `import` 抛异常 | `fallback` | 一行:加载失败:… | 同上 |
|
|
158
|
+
| `PI_HUB_SESSION_LOCK_CORE` 指向坏路径 | `error` | `serve`/`doctor` 一行明确错误 + 非 0 退出 | `reason` = `explicitPointerError`,`hint` null;锁操作抛同一条 |
|
|
159
|
+
|
|
160
|
+
`fallback` 是**正常状态**,不是「降级事故」:它只影响「判定实现」,不放宽互斥(`mkdir` 原子性 + owner 判死,
|
|
161
|
+
`src/session-lock-fallback.mjs:10-14`),与插件共用同一锁目录布局 —— 差异只在「能不能与桌面 pi 互相看见」。
|
|
162
|
+
|
|
163
|
+
## 7. 复现 / 验证
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
node test/session-lock-compat.mjs # 6 个假 core 场景(含版本闸门阴性对照)
|
|
167
|
+
node test/no-plugin.mjs # 无插件矩阵:隔离副本(无 node_modules)+ 假 core 各跑一遍
|
|
168
|
+
node test/lock-conformance.mjs # 插件 vs 内置:锁目录/判定表/claim/release/owner.json 逐条比对
|
|
169
|
+
PI_SESSION_LOCK_CONFORMANCE_CORE=~/pi-plugins/pi-session-lock/core.mjs node test/lock-conformance.mjs # 指定要比对的插件本体
|
|
170
|
+
HOME=$(mktemp -d) node test/lock-conformance.mjs # 未装插件:只校验内置实现 + 常量表(插件侧逐条 SKIP 并说明)
|
|
171
|
+
node test/lock-plugins.mjs # 断链/空目录/权限拒绝 + 显式指针配错(serve/doctor 非 0、锁操作报错、其它命令不受影响)
|
|
172
|
+
HOME=$(mktemp -d) node bin/pi-hub.mjs doctor # fallback:一行中性原因 + 一行「要不要装」
|
|
173
|
+
HOME=$(mktemp -d) PI_HUB_SESSION_LOCK_CORE=/nonexistent node bin/pi-hub.mjs doctor # error:一行明确错误 + 退出码 1
|
|
174
|
+
bash .pi/plans/hub-gaps/gate.sh --lane plugindeps
|
|
175
|
+
bash .pi/plans/hub-gaps/gate.sh --lane server
|
|
176
|
+
bash .pi/plans/hub-gaps/gate.sh --all
|
|
177
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-hub-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
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",
|
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
"systemd",
|
|
30
30
|
"LICENSE",
|
|
31
31
|
"docs",
|
|
32
|
+
"CHANGELOG.md",
|
|
32
33
|
"README.md"
|
|
33
34
|
],
|
|
34
35
|
"engines": {
|
|
@@ -37,9 +38,6 @@
|
|
|
37
38
|
"bin": {
|
|
38
39
|
"pi-hub": "./bin/pi-hub.mjs"
|
|
39
40
|
},
|
|
40
|
-
"optionalDependencies": {
|
|
41
|
-
"pi-session-lock": "^0.3.1"
|
|
42
|
-
},
|
|
43
41
|
"scripts": {
|
|
44
42
|
"start": "node bin/pi-hub.mjs serve",
|
|
45
43
|
"token": "node bin/pi-hub.mjs token",
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
// cli-control.mjs —— `pi-hub status|start|restart|stop` 的进程控制面(与 bin 解耦,好单测)。
|
|
2
|
+
//
|
|
3
|
+
// 设计口径(2026-12-06 用户实测反馈):
|
|
4
|
+
// 1) 控制类命令一律「确认到结果再返回」:start/restart 结尾必须打印实测的 health 与耗时,
|
|
5
|
+
// 不许只把 systemctl 的退出码当成成功(以前 `systemctl restart` 停旧进程要等 30 s,用户不知道好没好)。
|
|
6
|
+
// 2) 两种运行模式,判定顺序固定:
|
|
7
|
+
// 有 systemd 用户单元(LoadState=loaded)→ 交给 systemd(restart/stop 才能一次停干净 cgroup)
|
|
8
|
+
// 否则 → 自己 detach 一个 serve 进程,pid 落 CONFIG_DIR/hub.json
|
|
9
|
+
// `--port` 显式给了端口 = 一定是「临时实例」模式(测试与多实例都靠它,不碰 systemd)。
|
|
10
|
+
// 3) 所有外部命令都带 timeout(系统级硬规则):systemctl/health 探测都不许无限等。
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { execFile, spawn } from "node:child_process";
|
|
14
|
+
|
|
15
|
+
export const UNIT = "pi-hub";
|
|
16
|
+
/** systemd 单次操作的上限:正常 stop/start 都在 1 s 级,卡住就是真有东西拖着,早点报出来。 */
|
|
17
|
+
export const SYSTEMCTL_TIMEOUT_MS = 20000;
|
|
18
|
+
/** 起进程之后等 health 的上限(慢机器 + pi 版本探测在后台跑,不需要它)。 */
|
|
19
|
+
export const HEALTH_TIMEOUT_MS = 15000;
|
|
20
|
+
|
|
21
|
+
/** execFile 的 promise 化;**永远**带 timeout + killSignal,绝不裸调。 */
|
|
22
|
+
export function run(cmd, args, { timeout = 5000, env = process.env } = {}) {
|
|
23
|
+
return new Promise((resolve) => {
|
|
24
|
+
execFile(cmd, args, { timeout, killSignal: "SIGKILL", env, encoding: "utf8" }, (err, stdout, stderr) => {
|
|
25
|
+
resolve({
|
|
26
|
+
ok: !err,
|
|
27
|
+
code: err ? (err.code ?? 1) : 0,
|
|
28
|
+
timedOut: Boolean(err?.killed),
|
|
29
|
+
stdout: String(stdout ?? ""),
|
|
30
|
+
stderr: String(stderr ?? ""),
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function parseShow(text) {
|
|
37
|
+
const out = {};
|
|
38
|
+
for (const line of String(text).split("\n")) {
|
|
39
|
+
const i = line.indexOf("=");
|
|
40
|
+
if (i <= 0) continue;
|
|
41
|
+
out[line.slice(0, i)] = line.slice(i + 1);
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 本机 systemd 用户单元是否可用(只读判定,不改任何状态)。
|
|
48
|
+
* 返回 `{usable, loaded, active, sub, mainPid, since, reason}`。
|
|
49
|
+
* 非 Linux / systemctl 不在 PATH / 单元没装 —— 都只是 `usable:false`,调用方退回 detach 模式。
|
|
50
|
+
*/
|
|
51
|
+
export async function systemdState({ unit = UNIT, env = process.env, timeout = 4000 } = {}) {
|
|
52
|
+
if (process.platform !== "linux") return { usable: false, reason: "非 Linux,没有 systemd 用户单元" };
|
|
53
|
+
if (env.PI_HUB_NO_SYSTEMD === "1") return { usable: false, reason: "PI_HUB_NO_SYSTEMD=1" };
|
|
54
|
+
const res = await run(
|
|
55
|
+
"systemctl",
|
|
56
|
+
["--user", "show", unit, "-p", "LoadState", "-p", "ActiveState", "-p", "SubState", "-p", "MainPID", "-p", "ExecMainStartTimestamp", "-p", "NRestarts"],
|
|
57
|
+
{ timeout, env },
|
|
58
|
+
);
|
|
59
|
+
if (!res.ok) return { usable: false, reason: `systemctl 不可用(${(res.stderr || res.stdout).trim().split("\n")[0] || `exit ${res.code}`})` };
|
|
60
|
+
const props = parseShow(res.stdout);
|
|
61
|
+
const loaded = props.LoadState === "loaded";
|
|
62
|
+
return {
|
|
63
|
+
usable: loaded,
|
|
64
|
+
loaded,
|
|
65
|
+
unit,
|
|
66
|
+
reason: loaded ? null : `单元 ${unit}.service 未安装(LoadState=${props.LoadState ?? "?"})`,
|
|
67
|
+
active: props.ActiveState ?? "unknown",
|
|
68
|
+
sub: props.SubState ?? "unknown",
|
|
69
|
+
mainPid: Number(props.MainPID ?? 0) || null,
|
|
70
|
+
since: props.ExecMainStartTimestamp || null,
|
|
71
|
+
nRestarts: Number(props.NRestarts ?? 0) || 0,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** pidfile:detach 起来的 hub 自己写(serve 监听成功后写一次),stop 靠它精确定位。 */
|
|
76
|
+
export function pidFile(configDir) {
|
|
77
|
+
return path.join(configDir, "hub.json");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function readPidFile(configDir) {
|
|
81
|
+
try {
|
|
82
|
+
const data = JSON.parse(fs.readFileSync(pidFile(configDir), "utf8"));
|
|
83
|
+
return Number.isInteger(data?.pid) && data.pid > 0 ? data : null;
|
|
84
|
+
} catch {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function writePidFile(configDir, info) {
|
|
90
|
+
try {
|
|
91
|
+
fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
|
|
92
|
+
fs.writeFileSync(pidFile(configDir), `${JSON.stringify(info, null, 2)}\n`, { mode: 0o600 });
|
|
93
|
+
return true;
|
|
94
|
+
} catch {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function clearPidFile(configDir) {
|
|
100
|
+
try {
|
|
101
|
+
fs.unlinkSync(pidFile(configDir));
|
|
102
|
+
return true;
|
|
103
|
+
} catch {
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 进程还活着吗(`kill(pid,0)`;EPERM 也算活着)。 */
|
|
109
|
+
export function pidAlive(pid) {
|
|
110
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
111
|
+
try {
|
|
112
|
+
process.kill(pid, 0);
|
|
113
|
+
return true;
|
|
114
|
+
} catch (err) {
|
|
115
|
+
return err.code === "EPERM";
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* 探一次 /v1/health。`{up, ok, version, liveSessions, sessionLock, piVersion, ms}`。
|
|
121
|
+
* 200 + ok / 401 unauthorized(形状对得上但不认令牌)都算 `up`——端口上确实有 hub。
|
|
122
|
+
*/
|
|
123
|
+
export async function probeHealth({ port, host = "127.0.0.1", token = null, timeout = 1500 } = {}) {
|
|
124
|
+
const started = Date.now();
|
|
125
|
+
try {
|
|
126
|
+
const res = await fetch(`http://${host}:${port}/v1/health`, {
|
|
127
|
+
headers: token ? { authorization: `Bearer ${token}` } : {},
|
|
128
|
+
signal: AbortSignal.timeout(timeout),
|
|
129
|
+
});
|
|
130
|
+
const body = await res.json().catch(() => null);
|
|
131
|
+
if (res.ok && body?.ok) {
|
|
132
|
+
return {
|
|
133
|
+
up: true,
|
|
134
|
+
ok: true,
|
|
135
|
+
ms: Date.now() - started,
|
|
136
|
+
version: body.version ?? null,
|
|
137
|
+
liveSessions: body.liveSessions ?? null,
|
|
138
|
+
sessionLock: body.sessionLock ?? null,
|
|
139
|
+
sessionLockInfo: body.sessionLockInfo ?? null,
|
|
140
|
+
piVersion: body.piVersion ?? null,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
if (res.status === 401) return { up: true, ok: false, unauthorized: true, status: 401, ms: Date.now() - started };
|
|
144
|
+
if (res.status === 403) return { up: true, ok: false, forbidden: true, status: 403, ms: Date.now() - started };
|
|
145
|
+
return { up: true, ok: false, status: res.status, ms: Date.now() - started };
|
|
146
|
+
} catch (err) {
|
|
147
|
+
return { up: false, ok: false, ms: Date.now() - started, error: err.name === "TimeoutError" ? "timeout" : err.code ?? err.message };
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** 轮询直到 health 通(或超时)。返回最后一次探测结果 + 从调用起的耗时。 */
|
|
152
|
+
export async function waitHealthy({ port, token = null, timeoutMs = HEALTH_TIMEOUT_MS, intervalMs = 120 } = {}) {
|
|
153
|
+
const started = Date.now();
|
|
154
|
+
let last = { up: false, ok: false, error: "not_started" };
|
|
155
|
+
while (Date.now() - started < timeoutMs) {
|
|
156
|
+
last = await probeHealth({ port, token, timeout: Math.min(1500, timeoutMs) });
|
|
157
|
+
if (last.ok) return { ...last, waitedMs: Date.now() - started };
|
|
158
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
159
|
+
}
|
|
160
|
+
return { ...last, waitedMs: Date.now() - started, timedOut: true };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** detach 一个 serve:日志追加到 CONFIG_DIR/hub.log(0600),父进程立刻返回 pid。 */
|
|
164
|
+
export function spawnDetachedHub({ entry, port, host, configDir, env = process.env }) {
|
|
165
|
+
fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
|
|
166
|
+
const logFile = path.join(configDir, "hub.log");
|
|
167
|
+
const out = fs.openSync(logFile, "a", 0o600);
|
|
168
|
+
const child = spawn(process.execPath, [entry, "serve", "--host", host, "--port", String(port)], {
|
|
169
|
+
detached: true,
|
|
170
|
+
stdio: ["ignore", out, out],
|
|
171
|
+
env,
|
|
172
|
+
});
|
|
173
|
+
child.unref();
|
|
174
|
+
fs.closeSync(out);
|
|
175
|
+
return { pid: child.pid, logFile };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** SIGTERM → 等它自己退(最多 timeoutMs)→ 还在就 SIGKILL。返回真正用的手段。 */
|
|
179
|
+
export async function terminatePid(pid, { timeoutMs = 5000 } = {}) {
|
|
180
|
+
if (!pidAlive(pid)) return "already_gone";
|
|
181
|
+
try {
|
|
182
|
+
process.kill(pid, "SIGTERM");
|
|
183
|
+
} catch {
|
|
184
|
+
return "gone";
|
|
185
|
+
}
|
|
186
|
+
const started = Date.now();
|
|
187
|
+
while (Date.now() - started < timeoutMs) {
|
|
188
|
+
if (!pidAlive(pid)) return "sigterm";
|
|
189
|
+
await new Promise((resolve) => setTimeout(resolve, 80));
|
|
190
|
+
}
|
|
191
|
+
try {
|
|
192
|
+
process.kill(pid, "SIGKILL");
|
|
193
|
+
} catch {
|
|
194
|
+
/* 已经退了 */
|
|
195
|
+
}
|
|
196
|
+
return "sigkill";
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* `start` 的实现(只保证「起来且能应答」这一点,不做 auth/配对)。
|
|
201
|
+
* 返回 `{ok, mode, pid, health, waitedMs, logFile, error}`。
|
|
202
|
+
*/
|
|
203
|
+
export async function startHub({ entry, port, host, configDir, token, env = process.env, unit = UNIT }) {
|
|
204
|
+
const svc = await systemdState({ unit, env });
|
|
205
|
+
const mode = svc.usable ? "systemd" : "detached";
|
|
206
|
+
let pid = null;
|
|
207
|
+
let logFile = null;
|
|
208
|
+
if (svc.usable) {
|
|
209
|
+
const res = await run("systemctl", ["--user", "start", unit], { timeout: SYSTEMCTL_TIMEOUT_MS, env });
|
|
210
|
+
if (!res.ok) return { ok: false, mode, error: `systemctl --user start 失败:${(res.stderr || res.stdout).trim() || `exit ${res.code}`}` };
|
|
211
|
+
} else {
|
|
212
|
+
const spawned = spawnDetachedHub({ entry, port, host, configDir, env });
|
|
213
|
+
pid = spawned.pid;
|
|
214
|
+
logFile = spawned.logFile;
|
|
215
|
+
}
|
|
216
|
+
const health = await waitHealthy({ port, token });
|
|
217
|
+
if (!health.ok) {
|
|
218
|
+
// 端口上确实是 hub、只是不认本机令牌(换了 PI_HUB_CONFIG_DIR / 令牌文件不一致):
|
|
219
|
+
// 进程起来了就得如实说「起来了但有令牌问题」,别报成「启动失败」让人重复拉起。
|
|
220
|
+
if (health.unauthorized) return { ok: true, mode, pid, logFile, health, warn: `本机令牌与 hub 不一致(${health.status}):检查 PI_HUB_CONFIG_DIR` };
|
|
221
|
+
return { ok: false, mode, pid, logFile, health, error: "hub 起来了但 /v1/health 没有应答" };
|
|
222
|
+
}
|
|
223
|
+
const after = pid ? null : await systemdState({ unit, env });
|
|
224
|
+
return { ok: true, mode, pid: pid ?? after?.mainPid ?? null, logFile, health, waitedMs: health.waitedMs };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* `stop`:有 systemd 就走 stop(一次停干净整个 cgroup),否则 pidfile → SIGTERM → SIGKILL。
|
|
229
|
+
* `{ok, mode, how, wasRunning}`;本来就没跑 = `ok:true, wasRunning:false`(幂等,不算错)。
|
|
230
|
+
*/
|
|
231
|
+
export async function stopHub({ port, configDir, token, env = process.env, unit = UNIT, timeoutMs = 8000 }) {
|
|
232
|
+
const svc = await systemdState({ unit, env });
|
|
233
|
+
if (svc.usable) {
|
|
234
|
+
const before = await probeHealth({ port, token });
|
|
235
|
+
const res = await run("systemctl", ["--user", "stop", unit], { timeout: timeoutMs, env });
|
|
236
|
+
if (!res.ok) return { ok: false, mode: "systemd", error: `systemctl --user stop 失败:${(res.stderr || res.stdout).trim() || `exit ${res.code}`}`, timedOut: res.timedOut };
|
|
237
|
+
const after = await waitHealthDown({ port, token, timeoutMs: 5000 });
|
|
238
|
+
return { ok: after.down, mode: "systemd", how: "systemd", wasRunning: before.up, health: after };
|
|
239
|
+
}
|
|
240
|
+
const info = readPidFile(configDir);
|
|
241
|
+
const before = await probeHealth({ port, token });
|
|
242
|
+
if (!before.up && !pidAlive(info?.pid)) {
|
|
243
|
+
clearPidFile(configDir);
|
|
244
|
+
return { ok: true, mode: "detached", how: "none", wasRunning: false };
|
|
245
|
+
}
|
|
246
|
+
const how = info?.pid ? await terminatePid(info.pid, { timeoutMs }) : "no_pidfile";
|
|
247
|
+
const after = await waitHealthDown({ port, token, timeoutMs: 5000 });
|
|
248
|
+
if (after.down) clearPidFile(configDir);
|
|
249
|
+
return { ok: after.down, mode: "detached", how, wasRunning: before.up || Boolean(info?.pid), health: after };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async function waitHealthDown({ port, token, timeoutMs = 5000 }) {
|
|
253
|
+
const started = Date.now();
|
|
254
|
+
let last = await probeHealth({ port, token });
|
|
255
|
+
while (last.up && Date.now() - started < timeoutMs) {
|
|
256
|
+
await new Promise((resolve) => setTimeout(resolve, 120));
|
|
257
|
+
last = await probeHealth({ port, token });
|
|
258
|
+
}
|
|
259
|
+
return { ...last, down: !last.up, waitedMs: Date.now() - started };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* `restart` = stop + start,但**每一步都单独报**(哪一步慢了用户得看得见)。
|
|
264
|
+
* 返回 `{ok, mode, steps:[{name, ok, ms, detail}], health, totalMs}`。
|
|
265
|
+
*/
|
|
266
|
+
export async function restartHub({ entry, port, host, configDir, token, env = process.env, unit = UNIT }) {
|
|
267
|
+
const started = Date.now();
|
|
268
|
+
const steps = [];
|
|
269
|
+
const svc = await systemdState({ unit, env });
|
|
270
|
+
if (svc.usable) {
|
|
271
|
+
const res = await run("systemctl", ["--user", "restart", unit], { timeout: SYSTEMCTL_TIMEOUT_MS, env });
|
|
272
|
+
steps.push({
|
|
273
|
+
name: "systemctl restart",
|
|
274
|
+
ok: res.ok,
|
|
275
|
+
ms: Date.now() - started,
|
|
276
|
+
detail: res.ok ? null : (res.stderr || res.stdout).trim() || `exit ${res.code}`,
|
|
277
|
+
});
|
|
278
|
+
if (!res.ok) return { ok: false, mode: "systemd", steps, totalMs: Date.now() - started };
|
|
279
|
+
const health = await waitHealthy({ port, token });
|
|
280
|
+
steps.push({ name: "health", ok: health.ok, ms: health.waitedMs, detail: health.ok ? `v${health.version}` : health.error ?? `HTTP ${health.status}` });
|
|
281
|
+
return { ok: health.ok, mode: "systemd", steps, health, totalMs: Date.now() - started };
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const stopped = await stopHub({ port, configDir, token, env, unit });
|
|
285
|
+
steps.push({ name: "stop", ok: stopped.ok, ms: 0, detail: stopped.wasRunning ? stopped.how : "本来就没跑" });
|
|
286
|
+
if (!stopped.ok) return { ok: false, mode: "detached", steps, totalMs: Date.now() - started };
|
|
287
|
+
const startedHub = await startHub({ entry, port, host, configDir, token, env, unit });
|
|
288
|
+
steps.push({ name: "start", ok: startedHub.ok, ms: startedHub.waitedMs ?? 0, detail: startedHub.ok ? `pid ${startedHub.pid ?? "?"}` : startedHub.error });
|
|
289
|
+
return { ok: startedHub.ok, mode: "detached", steps, health: startedHub.health, pid: startedHub.pid, logFile: startedHub.logFile, totalMs: Date.now() - started };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** `status` 的取数(不打 systemctl 改状态;只读 + 一次 health)。 */
|
|
293
|
+
export async function statusSnapshot({ port, host, configDir, token, env = process.env, unit = UNIT }) {
|
|
294
|
+
const [svc, health] = await Promise.all([
|
|
295
|
+
systemdState({ unit, env }),
|
|
296
|
+
probeHealth({ port, token }),
|
|
297
|
+
]);
|
|
298
|
+
const info = readPidFile(configDir);
|
|
299
|
+
return { port, host, svc, health, pidfile: info, pidAlive: pidAlive(info?.pid) };
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export function formatDuration(ms) {
|
|
303
|
+
const s = Math.max(0, Math.round(ms / 1000));
|
|
304
|
+
if (s < 60) return `${s}s`;
|
|
305
|
+
const m = Math.round(s / 60);
|
|
306
|
+
if (m < 60) return `${m}m`;
|
|
307
|
+
const h = Math.floor(m / 60);
|
|
308
|
+
return `${h}h${m % 60 ? `${m % 60}m` : ""}`;
|
|
309
|
+
}
|