pi-session-lock 0.0.0-stage → 0.3.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Qianhui Xu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,86 @@
1
- # Temporary Holding Version
1
+ # pi-session-lock
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 单会话单写者(advisory)。pi 的 `SessionManager` 没有并发保护:两个进程共写同一个
4
+ `~/.pi/agent/sessions/**/*.jsonl` 会各按内存里的旧 leafId 追加,长出一棵两叉树;
5
+ compaction 的整文件重写还会抹掉对方条目(上游 `#8300`)。
6
+
7
+ 本插件提供**一份**实现(`core.mjs`),两个消费者共用:
8
+
9
+ | 消费者 | 怎么用 |
10
+ |---|---|
11
+ | pi 扩展 `extensions/session-lock.ts` | `session_start` 认领(paseo 托管则推迟到 `input`);`input`/`user_bash` 在有冲突时拦下;空闲时响应让锁请求;`/session-lock`、`/session-lock-release` |
12
+ | 进程外服务(如 `~/src/pi-hub`) | `import { claim, peek, release } from "…/pi-session-lock/core.mjs"`,attach 前 `peek` 判冲突,占住时 `claim({writerPid})` |
13
+
14
+ 锁位置:`<agentDir>/session-locks/<sha256(realpath(session))>.lock/owner.json`
15
+
16
+ ```json
17
+ {
18
+ "v": 1, "pid": 1234, "host": "…", "bootId": "…", "startTicks": "…",
19
+ "instanceId": "…", "source": "pi-hub", "sessionFile": "…/s.jsonl",
20
+ "ownerPid": 1200, "acquiredAt": "…"
21
+ }
22
+ ```
23
+
24
+ - `pid` = **实际写盘进程**。pi 进程自己就是写者;代管子进程的服务(hub)要传 `writerPid`,
25
+ 否则服务被 SIGKILL 后锁会被判死回收,而孤儿子进程还在写。
26
+ - `source` = 持有者种类,便于排查(`pi-session-lock` / `paseo:<agentId 前 8 位>` / `pi-hub` / 自定义)。
27
+ - `idleYield: true` = 持有者是 paseo 托管的 pi 子进程,空闲时会主动让锁(见下)。
28
+
29
+ ## 策略(宁可少管,不可锁死自己)
30
+
31
+ 1. 只在 `session_start` 之后认领,**不阻止启动**(启动前 pi 仍会写 model/thinking 元数据)。
32
+ 2. 只拦「人的动作」:`input`(TUI 打字 / RPC / 手机端 / steer)与 `user_bash`;不拦工具、不拦退出。
33
+ 3. 只有**能证明**另一个活进程持锁才判冲突(host + boot_id + pid + starttime),
34
+ 跨主机 / owner.json 残缺 / 读不到 `/proc` 一律 fail-open。
35
+ 4. 已证死(pid 消失、boot_id 变化、starttime 不匹配=PID 复用)自动回收。
36
+ 5. 逃生阀:`PI_SESSION_LOCK=off`(hub 侧同效于 `PI_HUB_NO_SESSION_LOCK=1`)。
37
+
38
+ ## paseo 兼容(2026-12-04 实测加入)
39
+
40
+ paseo daemon 给每个 agent 常驻一个 pi 子进程:空闲也活着,`input` 走 `source=rpc`,
41
+ `agent_settled` 之后进程仍不退。照「启动即持锁」,这些空转进程会**永久占住会话**,
42
+ 于是 TUI 里 `/resume` 直接报「不能 resume:另一个活进程正在用这个会话」。
43
+
44
+ 三条改动(识别方式:`PASEO_AGENT_ID` 存在**且**父进程命令行含 paseo,避免 agent 内部
45
+ `bash` 起的 pi 继承同一变量被误判):
46
+
47
+ 1. **按轮持锁**:paseo 托管的进程 `session_start` 不认领,`input`/`agent_start` 认领,
48
+ `agent_settled` 立刻释放。锁只覆盖真正写盘的窗口 ⇒ 空闲的 paseo agent 一条锁都不留,
49
+ TUI 随时可以进入那个会话。
50
+ 2. **让锁协议**(反方向:TUI 空转挡着 paseo):要锁的一方在冲突时写
51
+ `<lock>/yield-request.json`;持有者(任何进程)每 15 s 看一眼,**空闲**且请求活着
52
+ (TTL 2 分钟、发起者未死)就让出并提示「已让给 X」,下次真正输入时重新认领。
53
+ 3. **重放**:paseo 侧被拦下的那条消息不丢——每 3 s 重试认领,拿到锁后 `sendUserMessage`
54
+ 重放,60 s 内拿不到才提示重发。手机上发一句,桌面上那个空闲窗口会自动让位。
55
+
56
+ 边界与排障:
57
+
58
+ - 改动前就已经在跑的 paseo 子进程仍按老逻辑持锁,要等它重启(`paseo restart` / agent 重开)
59
+ 才生效;急用时确认那个 agent 空闲后删掉对应 `<lock>` 目录即可(`/session-lock` 能看路径)。
60
+ - 只在**轮次之间**放锁,所以「一个 TUI 正在跑 + paseo 同时发消息」仍是冲突并被拦(正确行为)。
61
+ - `PI_SESSION_LOCK_DEBUG=1`(可选 `PI_SESSION_LOCK_DEBUG_LOG`,默认
62
+ `/tmp/pi-session-lock-debug.log`)落事件流水:session_start / input / claim / retry / poll / yield。
63
+
64
+ ## 测试
65
+
66
+ ```bash
67
+ node test/core.test.mjs # 16 项:认领/自认/冲突/死锁回收/PID 复用/跨主机/禁用/paseo 识别/让锁请求
68
+ node test/two-process.test.mjs # 真起两个 pi:A 占住 → B 的输入被拦(handled + 🔒 提示)
69
+ node test/paseo.test.mjs # 假冒 paseo daemon(进程标题 + PASEO_AGENT_ID):空闲不持锁 / 认领标记 / settle 释放
70
+ node test/yield.test.mjs # 端到端让锁:TUI 空转持锁 → paseo 请求 → TUI 让出 → paseo 重放消息
71
+ ```
72
+
73
+ ## 边界
74
+
75
+ 这是**建议锁**:pi 核心不读它,所以工具执行、RPC 元数据、自动续跑仍可能写盘。
76
+ 要真正做到「一写多读」得改上游:`_rewriteFile` 的原地截断换成 temp+rename,
77
+ 读者每轮 reopen 并按 `(ino,size)` 判重扫、只吃完整行。在那之前,本插件的价值是
78
+ **拦住人**,把「两个窗口各敲一句话」这种最常见的串台挡掉。
79
+
80
+ ## 安装
81
+
82
+ ```bash
83
+ ln -s ~/pi-plugins/pi-session-lock/extensions/session-lock.ts ~/.pi/agent/extensions/session-lock.ts
84
+ ```
85
+
86
+ (或把本目录加进 `settings.json` 的 `packages`。)
package/core.mjs ADDED
@@ -0,0 +1,301 @@
1
+ /**
2
+ * session lock core —— 同一个 session .jsonl 只允许一个写者(advisory,本地 Linux)。
3
+ *
4
+ * 这是**唯一实现**:pi 侧的扩展(extensions/session-lock.ts)与进程外的调用方
5
+ * (如 ~/src/pi-hub 的 HTTP hub)都 import 这个文件,判定口径只有一份。
6
+ *
7
+ * 锁位置:<agentDir>/session-locks/<sha256(realpath(session))>.lock/{owner.json}
8
+ *
9
+ * 设计取舍(宁可少管,不可锁死自己):
10
+ * 1. 只在 session_start 之后「认领」锁,绝不阻止启动 —— 启动前 pi 仍会写
11
+ * model/thinking 元数据(核心层才能根治)。
12
+ * 2. 只拦「人的动作」:input 与 user_bash。不拦工具、不拦退出。
13
+ * 3. 只有**能证明**另一个活进程持锁时才判冲突;owner 残缺 / 跨主机 / 读不到
14
+ * /proc 一律 fail-open —— 避免把用户锁在自己的会话外面。
15
+ * 4. 证明 owner 已死(ESRCH,或 boot_id / starttime 对不上 = PID 被复用)自动回收。
16
+ * 5. 逃生阀:PI_SESSION_LOCK=off(PI_HUB_NO_SESSION_LOCK=1 对 hub 同效)。
17
+ *
18
+ * `owner.pid` 记录的是**实际写盘进程**。对 pi 进程即自身;对代管子进程的 hub 则
19
+ * 是那个 pi 子进程 —— 否则 hub 被 SIGKILL 后锁会被判死回收,而孤儿 pi 还在写。
20
+ *
21
+ * paseo 兼容(2026-12-04):paseo daemon 给每个 agent 常驻一个 pi 子进程(空闲也活着),
22
+ * 照「启动即持锁」会永久占住会话。所以 paseo 托管的进程按轮持锁(`idleYield`),
23
+ * 空转的一方看到 `yield-request.json` 就主动让锁,见下面 requestYield/readYieldRequest。
24
+ */
25
+ import fs from "node:fs";
26
+ import os from "node:os";
27
+ import path from "node:path";
28
+ import crypto from "node:crypto";
29
+
30
+ const HOST = os.hostname();
31
+
32
+ export function resolveAgentDir(explicit) {
33
+ return explicit || process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent");
34
+ }
35
+
36
+ export function enabled() {
37
+ if ((process.env.PI_SESSION_LOCK ?? "").toLowerCase() === "off") return false;
38
+ if (process.env.PI_HUB_NO_SESSION_LOCK === "1") return false;
39
+ return true;
40
+ }
41
+
42
+ function readBootId() {
43
+ try {
44
+ return fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
45
+ } catch {
46
+ return "";
47
+ }
48
+ }
49
+
50
+ function readStartTicks(pid) {
51
+ try {
52
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
53
+ // 字段从 "pid (comm) " 之后从 #3(state) 开始;starttime 是 #22 → 下标 19。
54
+ const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
55
+ return rest[19] ?? "";
56
+ } catch {
57
+ return "";
58
+ }
59
+ }
60
+
61
+ function isAlive(pid) {
62
+ try {
63
+ process.kill(pid, 0);
64
+ return true;
65
+ } catch (error) {
66
+ return error.code === "EPERM";
67
+ }
68
+ }
69
+
70
+ const IDENTITY = Symbol.for("pi.session-lock.identity");
71
+
72
+ /** 本进程的稳定身份;扩展 reload 时经 globalThis 复用,避免自己把自己判成冲突。 */
73
+ export function identity() {
74
+ const g = globalThis;
75
+ if (!g[IDENTITY]) {
76
+ g[IDENTITY] = {
77
+ v: 1,
78
+ pid: process.pid,
79
+ host: HOST,
80
+ bootId: readBootId(),
81
+ startTicks: readStartTicks(process.pid),
82
+ instanceId: crypto.randomUUID(),
83
+ };
84
+ }
85
+ return g[IDENTITY];
86
+ }
87
+
88
+ /**
89
+ * paseo 托管识别(纯函数):daemon 直接 spawn 的 pi 子进程带 PASEO_AGENT_ID。
90
+ * 只认「父进程命令行含 paseo」的那种 —— agent 内部用 bash 起 pi 会继承同一变量。
91
+ * @param {Record<string,string|undefined>} env
92
+ * @param {string} parentCmdline
93
+ * @returns {{agentId:string,label:string}|null}
94
+ */
95
+ export function detectPaseo(env, parentCmdline) {
96
+ const agentId = (env?.PASEO_AGENT_ID ?? "").trim();
97
+ if (!agentId) return null;
98
+ if (!/paseo/i.test(parentCmdline ?? "")) return null;
99
+ return { agentId, label: `paseo:${agentId.slice(0, 8)}` };
100
+ }
101
+
102
+ /** 本进程是否被 paseo daemon 托管;是则返回 {agentId,label}。 */
103
+ export function paseoManaged(env = process.env, ppid = process.ppid) {
104
+ let parentCmdline = "";
105
+ try {
106
+ parentCmdline = fs.readFileSync(`/proc/${ppid}/cmdline`, "utf8").replaceAll("\0", " ").trim();
107
+ } catch {
108
+ return null;
109
+ }
110
+ return detectPaseo(env, parentCmdline);
111
+ }
112
+
113
+ /** 持锁者的一句话描述,供冲突提示复用。 */
114
+ export function describeOwner(owner) {
115
+ const source = owner?.source ?? "unknown";
116
+ const who = source === "pi-session-lock" ? "另一个 pi 进程" : source;
117
+ return `${who}(pid ${owner?.pid ?? "?"}${owner?.idleYield ? ",空闲时会让锁" : ""})`;
118
+ }
119
+
120
+ export function lockDirFor(sessionFile, opts = {}) {
121
+ const canonical = (() => {
122
+ try {
123
+ return fs.realpathSync(sessionFile);
124
+ } catch {
125
+ return path.resolve(sessionFile);
126
+ }
127
+ })();
128
+ const hash = crypto.createHash("sha256").update(canonical).digest("hex");
129
+ return path.join(resolveAgentDir(opts.agentDir), "session-locks", `${hash}.lock`);
130
+ }
131
+
132
+ export function readOwner(dir) {
133
+ try {
134
+ return JSON.parse(fs.readFileSync(path.join(dir, "owner.json"), "utf8"));
135
+ } catch {
136
+ return null;
137
+ }
138
+ }
139
+
140
+ /** live = 证明有另一个活进程;dead = 证明所有者已消失;unknown = 说不清(→ fail-open)。 */
141
+ export function classify(owner) {
142
+ const me = identity();
143
+ if (owner.instanceId === me.instanceId) return { kind: "self", reason: "owned by this process" };
144
+ if (owner.host !== HOST) return { kind: "unknown", reason: `owner on another host (${owner.host})` };
145
+ if (owner.bootId !== me.bootId) return { kind: "dead", reason: "host rebooted since lock was taken" };
146
+ if (!isAlive(owner.pid)) return { kind: "dead", reason: `pid ${owner.pid} is gone` };
147
+ if (owner.startTicks && owner.startTicks !== readStartTicks(owner.pid))
148
+ return { kind: "dead", reason: `pid ${owner.pid} was reused (starttime mismatch)` };
149
+ return { kind: "live", reason: `pid ${owner.pid} is alive` };
150
+ }
151
+
152
+ /**
153
+ * 认领锁(mkdir 的 O_EXCL 语义给出原子 claim)。死锁自动回收后重试。
154
+ *
155
+ * @param {string} sessionFile
156
+ * @param {{agentDir?:string, writerPid?:number, source?:string, idleYield?:boolean}} [opts]
157
+ * writerPid = 实际写盘进程(hub 传 pi 子进程 pid;pi 扩展不传,默认自身)
158
+ * idleYield = 持锁方会在空闲时让锁(paseo 托管的 pi 子进程)
159
+ * @returns {{ok:boolean, state:"owned"|"conflict"|"unknown"|"off", dir:string|null, reason:string, owner?:any}}
160
+ */
161
+ export function claim(sessionFile, opts = {}) {
162
+ if (!enabled()) return { ok: true, state: "off", dir: null, reason: "disabled" };
163
+ const dir = lockDirFor(sessionFile, opts);
164
+ const me = identity();
165
+ const writer = opts.writerPid ?? me.pid;
166
+
167
+ for (let attempt = 0; attempt < 3; attempt += 1) {
168
+ try {
169
+ fs.mkdirSync(path.dirname(dir), { recursive: true, mode: 0o700 });
170
+ fs.mkdirSync(dir, { mode: 0o700 });
171
+ const owner = {
172
+ ...me,
173
+ pid: writer,
174
+ startTicks: readStartTicks(writer),
175
+ source: opts.source ?? "pi-session-lock",
176
+ ...(opts.idleYield ? { idleYield: true } : {}),
177
+ sessionFile,
178
+ acquiredAt: new Date().toISOString(),
179
+ };
180
+ if (me.pid !== writer) owner.ownerPid = me.pid; // 代管者(hub)自己,便于排查
181
+ fs.writeFileSync(path.join(dir, "owner.json"), `${JSON.stringify(owner, null, 2)}\n`, { mode: 0o600 });
182
+ return { ok: true, state: "owned", dir, reason: "claimed", owner };
183
+ } catch (error) {
184
+ if (error.code !== "EEXIST") return { ok: false, state: "unknown", dir, reason: String(error) };
185
+ }
186
+ const owner = readOwner(dir);
187
+ if (!owner || typeof owner.pid !== "number") {
188
+ return { ok: false, state: "unknown", dir, reason: "owner.json missing or malformed" };
189
+ }
190
+ const verdict = classify(owner);
191
+ if (verdict.kind === "self") return { ok: true, state: "owned", dir, reason: "already ours", owner };
192
+ if (verdict.kind === "unknown") return { ok: false, state: "unknown", dir, reason: verdict.reason, owner };
193
+ if (verdict.kind === "live") {
194
+ return {
195
+ ok: false,
196
+ state: "conflict",
197
+ dir,
198
+ reason: verdict.reason,
199
+ owner,
200
+ warning: `另一个活进程正在用这个会话(${verdict.reason}, ${owner.source || "pi-session-lock"}${owner.idleYield ? ",它空闲时会自动让锁" : ""}, ${owner.sessionFile ?? "?"})`,
201
+ };
202
+ }
203
+ // dead → 回收后重试
204
+ try {
205
+ fs.rmSync(dir, { recursive: true, force: true });
206
+ } catch {
207
+ return { ok: false, state: "unknown", dir, reason: "stale lock could not be removed" };
208
+ }
209
+ }
210
+ return { ok: false, state: "unknown", dir, reason: "lock reclaim retried 3x" };
211
+ }
212
+
213
+ /** 只读探测:不创建、不回收。 */
214
+ export function peek(sessionFile, opts = {}) {
215
+ if (!enabled()) return { state: "off", dir: null, owner: null, reason: "disabled" };
216
+ const dir = lockDirFor(sessionFile, opts);
217
+ if (!fs.existsSync(dir)) return { state: "none", dir, owner: null, reason: "no lock" };
218
+ const owner = readOwner(dir);
219
+ if (!owner || typeof owner.pid !== "number") {
220
+ return { state: "unknown", dir, owner: null, reason: "owner.json missing or malformed" };
221
+ }
222
+ const verdict = classify(owner);
223
+ return { state: verdict.kind, dir, owner, reason: verdict.reason };
224
+ }
225
+
226
+ /** 只释放自己持有的锁(按 instanceId 认)。 */
227
+ export function release(dir) {
228
+ if (!dir) return;
229
+ try {
230
+ const owner = readOwner(dir);
231
+ if (owner && owner.instanceId === identity().instanceId) fs.rmSync(dir, { recursive: true, force: true });
232
+ } catch {
233
+ /* best effort */
234
+ }
235
+ }
236
+ // ---- 让锁请求(idle yield) -------------------------------------------------
237
+ // 场景:长驻但空闲的持有者(TUI 窗口 / paseo agent)挡着另一个真正要写盘的一方。
238
+ // 要锁的一方只在**已被判冲突**时写 <lock>/yield-request.json;持有者空闲时看到
239
+ // 一个仍然活着的请求就 release,下次真正输入时再认领。请求自带 TTL,过期/发起者
240
+ // 已死即视为无效,不会把一个空转的持有者永久赶走。
241
+
242
+ const YIELD_FILE = "yield-request.json";
243
+ const YIELD_TTL_MS = 120_000;
244
+
245
+ /** 向持有者请求让锁;dir 是冲突那一侧返回的 lock 目录。 */
246
+ export function requestYield(dir, requester = {}) {
247
+ if (!dir) return false;
248
+ try {
249
+ const me = identity();
250
+ fs.writeFileSync(
251
+ path.join(dir, YIELD_FILE),
252
+ `${JSON.stringify(
253
+ {
254
+ at: new Date().toISOString(),
255
+ pid: me.pid,
256
+ host: HOST,
257
+ bootId: me.bootId,
258
+ startTicks: me.startTicks,
259
+ source: requester.source ?? "pi",
260
+ sessionFile: requester.sessionFile ?? null,
261
+ },
262
+ null,
263
+ 2,
264
+ )}\n`,
265
+ { mode: 0o600 },
266
+ );
267
+ return true;
268
+ } catch {
269
+ return false; // 写不进去就只是不让锁,不影响主流程
270
+ }
271
+ }
272
+
273
+ /** 读让锁请求;过期 / 跨主机 / 发起者已死都当作没有(顺手清掉)。 */
274
+ export function readYieldRequest(dir) {
275
+ if (!dir) return null;
276
+ let raw;
277
+ try {
278
+ raw = JSON.parse(fs.readFileSync(path.join(dir, YIELD_FILE), "utf8"));
279
+ } catch {
280
+ return null;
281
+ }
282
+ const at = Date.parse(raw?.at ?? "");
283
+ if (!Number.isFinite(at) || Date.now() - at > YIELD_TTL_MS) {
284
+ clearYieldRequest(dir);
285
+ return null;
286
+ }
287
+ if (raw.host === HOST && raw.bootId === readBootId() && typeof raw.pid === "number" && !isAlive(raw.pid)) {
288
+ clearYieldRequest(dir);
289
+ return null;
290
+ }
291
+ return raw;
292
+ }
293
+
294
+ export function clearYieldRequest(dir) {
295
+ if (!dir) return;
296
+ try {
297
+ fs.rmSync(path.join(dir, YIELD_FILE), { force: true });
298
+ } catch {
299
+ /* best effort */
300
+ }
301
+ }
@@ -0,0 +1,287 @@
1
+ /**
2
+ * session-lock(pi 侧适配层)—— 逻辑全在 ../core.mjs,与进程外调用方共用一份实现。
3
+ *
4
+ * 这里只做:把 pi 的 extension 钩子接到 core 的 claim/peek/release 上。
5
+ * 策略保持原样:不阻止启动、只拦人的动作(input / user_bash)、能证明冲突才拦、
6
+ * 说不清就 fail-open、/session-lock 可查、/session-lock-release 只回收已证死的锁。
7
+ *
8
+ * paseo 兼容(2026-12-04 实测):
9
+ * paseo daemon 给每个 agent 常驻一个 pi 子进程(`input` 走 source=rpc,空闲时进程也活着),
10
+ * 所以「session_start 就认领」会让空转的 paseo agent 永久占住会话,TUI 里 /resume 直接报
11
+ * 「另一个活进程正在用这个会话」。改成**按轮持锁**:
12
+ * session_start 不认领 → input / agent_start 认领 → agent_settled 立刻释放。
13
+ * 锁只在真正写盘的窗口内存在,空闲的 paseo agent 什么都不占。
14
+ *
15
+ * 反方向(TUI 窗口空转持锁、paseo 要接着聊):要锁的一方写 yield-request.json,
16
+ * 持有者空闲时看到一个活着且未过期的请求就让锁;paseo 侧被拦下的那条消息会在
17
+ * 拿到锁之后重放(60 秒窗口),做到「手机上发一句,桌面上那个窗口自动让位」。
18
+ */
19
+ import fs from "node:fs";
20
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
21
+ import {
22
+ claim,
23
+ classify,
24
+ clearYieldRequest,
25
+ enabled,
26
+ lockDirFor,
27
+ paseoManaged,
28
+ readOwner,
29
+ readYieldRequest,
30
+ release,
31
+ requestYield,
32
+ } from "../core.mjs";
33
+
34
+ const PASEO = paseoManaged();
35
+ const PASEO_SOURCE = PASEO?.label ?? "pi-session-lock";
36
+ const YIELD_POLL_MS = 15_000; // 持锁方多久看一次让锁请求
37
+ const YIELD_RETRY_MS = 3_000; // 请求方多久重试一次认领
38
+ const REPLAY_WINDOW_MS = 60_000; // 重试多久还没拿到锁就放弃并提示重发
39
+ const DEBUG = process.env.PI_SESSION_LOCK_DEBUG === "1"; // 兼容排障用:事件流水落一个文件
40
+ const DEBUG_LOG = process.env.PI_SESSION_LOCK_DEBUG_LOG ?? "/tmp/pi-session-lock-debug.log";
41
+
42
+ type Held = { dir: string | null; conflict: string | null; unknown: string | null };
43
+
44
+ export default function sessionLock(pi: ExtensionAPI) {
45
+ let held: Held = { dir: null, conflict: null, unknown: null };
46
+ let sessionFile: string | null = null;
47
+ let lastCtx: ExtensionContext | null = null;
48
+ let replaying = false;
49
+ let pending: { text: string; images: unknown[]; deadline: number } | null = null;
50
+ let yieldTimer: ReturnType<typeof setInterval> | null = null;
51
+ let retryTimer: ReturnType<typeof setInterval> | null = null;
52
+
53
+ const warn = (ctx: ExtensionContext, message: string, level: "info" | "warning" | "error") => {
54
+ try {
55
+ ctx.ui.notify(message, level);
56
+ } catch {
57
+ /* notify 不是关键路径 */
58
+ }
59
+ };
60
+
61
+ const dbg = (tag: string, detail = "") => {
62
+ if (!DEBUG) return;
63
+ try {
64
+ fs.appendFileSync(
65
+ DEBUG_LOG,
66
+ `${new Date().toISOString()} pid=${process.pid} paseo=${PASEO_SOURCE} held=${held.dir ? "dir" : held.conflict ? "conflict" : "-"} file=${sessionFile ?? "null"} ${tag} ${detail}\n`,
67
+ );
68
+ } catch {
69
+ /* 排障日志不是关键路径 */
70
+ }
71
+ };
72
+
73
+ const take = (file: string): Held => {
74
+ const result = claim(file, { source: PASEO_SOURCE, idleYield: Boolean(PASEO) });
75
+ if (result.state === "conflict") {
76
+ return { dir: result.dir ?? null, conflict: result.warning ?? "会话被另一活进程占用", unknown: null };
77
+ }
78
+ if (result.state === "unknown") {
79
+ return { dir: result.dir ?? null, conflict: null, unknown: result.reason };
80
+ }
81
+ return { dir: result.dir ?? null, conflict: null, unknown: null };
82
+ };
83
+
84
+ /** 认领并清掉别人留在这把锁上的让锁请求。 */
85
+ const claimNow = (ctx: ExtensionContext): void => {
86
+ if (!sessionFile) sessionFile = ctx.sessionManager.getSessionFile() ?? null;
87
+ if (!sessionFile) return; // --no-session / ephemeral
88
+ held = take(sessionFile);
89
+ if (held.dir && !held.conflict) clearYieldRequest(held.dir); // 别在冲突时把别人的让锁请求擦掉
90
+ dbg("claim", `state=${held.conflict ? "conflict" : "owned"}`);
91
+ };
92
+
93
+ const stopRetry = () => {
94
+ if (retryTimer) clearInterval(retryTimer);
95
+ retryTimer = null;
96
+ };
97
+
98
+ /** paseo 被拦下的消息:反复重试认领,拿到锁就重放这条消息。 */
99
+ const startReplay = () => {
100
+ if (retryTimer) return;
101
+ retryTimer = setInterval(() => {
102
+ if (!pending) return stopRetry();
103
+ if (!sessionFile || !lastCtx) return;
104
+ held = take(sessionFile);
105
+ dbg("retry", `owned=${Boolean(held.dir && !held.conflict)}`);
106
+ if (held.conflict) {
107
+ // 还没轮到我们:把请求续上(TTL 2 分钟),别让持有者错过窗口
108
+ if (held.dir) requestYield(held.dir, { source: PASEO_SOURCE, sessionFile });
109
+ } else if (held.dir) {
110
+ clearYieldRequest(held.dir);
111
+ const { text, images } = pending;
112
+ pending = null;
113
+ stopRetry();
114
+ replaying = true;
115
+ const content = images.length ? [{ type: "text", text }, ...images] : text;
116
+ Promise.resolve()
117
+ .then(() => pi.sendUserMessage(content as never /* 文本或 text+image 数组 */))
118
+ .catch(() => {})
119
+ .finally(() => {
120
+ replaying = false;
121
+ });
122
+ return;
123
+ }
124
+ if (Date.now() > (pending?.deadline ?? 0)) {
125
+ pending = null;
126
+ stopRetry();
127
+ if (lastCtx) warn(lastCtx, "🔒 等锁超时,这条消息没送达:先在占用方收尾,或关掉那个进程后重发。", "error");
128
+ }
129
+ }, YIELD_RETRY_MS);
130
+ retryTimer.unref?.();
131
+ };
132
+
133
+ /** 持锁方空闲时看到让锁请求就让出(下次真的输入时会重新认领)。 */
134
+ const pollYield = () => {
135
+ if (!held.dir || held.conflict || !lastCtx) return;
136
+ let idle = false;
137
+ try {
138
+ idle = lastCtx.isIdle();
139
+ } catch {
140
+ return;
141
+ }
142
+ dbg("poll", `idle=${idle}`);
143
+ if (!idle) return;
144
+ const request = readYieldRequest(held.dir);
145
+ if (!request) return;
146
+ dbg("yield", `to=${request.source}`);
147
+ const dir = held.dir;
148
+ release(dir);
149
+ held = { dir: null, conflict: null, unknown: null };
150
+ warn(lastCtx, `🔒 会话已让给 ${request.source ?? "另一个进程"}(pid ${request.pid}):本窗口再输入会重新认领,对方占着就会被拦。`, "info");
151
+ };
152
+
153
+ pi.on("session_start", (event, ctx) => {
154
+ lastCtx = ctx;
155
+ sessionFile = ctx.sessionManager.getSessionFile() ?? null;
156
+ held = { dir: null, conflict: null, unknown: null };
157
+ dbg("session_start", `reason=${event.reason}`);
158
+ if (!enabled() || !sessionFile) return;
159
+ if (PASEO) return; // paseo 托管:按轮持锁,空闲不占(见文件头)
160
+ claimNow(ctx);
161
+ if (held.conflict) warn(ctx, `🔒 ${held.conflict}。已拦输入:先退出那个进程,或 /clone 一份新的再继续。`, "error");
162
+ else if (held.unknown) warn(ctx, `🔒 会话锁无法判定(${held.unknown}):本会话仍可用,但并发保护未生效。`, "warning");
163
+ yieldTimer = setInterval(pollYield, YIELD_POLL_MS);
164
+ yieldTimer.unref?.();
165
+ });
166
+
167
+ // 只拦人的输入(TUI 打字 / RPC / 手机端 / steer 都经这里)。扩展命令在 input 之前处理,故 /session-lock 仍可用。
168
+ pi.on("input", (event, ctx) => {
169
+ lastCtx = ctx;
170
+ if (!enabled() || replaying) return;
171
+ dbg("input", `source=${event.source}`);
172
+ // 空闲时没持锁(paseo 按轮持锁 / 自己刚才让过锁),或者上次判冲突而对方可能已经走了:
173
+ // 现在真的要写了,重新认领一次(对方还活着就还是 conflict)。
174
+ if (!held.dir || held.conflict) {
175
+ claimNow(ctx);
176
+ if (held.unknown) warn(ctx, `🔒 会话锁无法判定(${held.unknown}):本会话仍可用,但并发保护未生效。`, "warning");
177
+ }
178
+ if (!held.conflict) return;
179
+
180
+ if (PASEO && held.dir) {
181
+ // paseo 侧:请求对方让锁,并把这条消息挂起,拿到锁后重放
182
+ requestYield(held.dir, { source: PASEO_SOURCE, sessionFile });
183
+ pending = { text: event.text, images: event.images ?? [], deadline: Date.now() + REPLAY_WINDOW_MS };
184
+ startReplay();
185
+ warn(ctx, `🔒 输入已拦:${held.conflict}。已请求对方让锁,拿到后自动重放这条消息(60 秒内)。`, "error");
186
+ } else {
187
+ warn(ctx, `🔒 输入已拦:${held.conflict}`, "error");
188
+ }
189
+ return { action: "handled" };
190
+ });
191
+
192
+ // paseo 侧的兜底:非 input 触发的 run(定时续轮、extension 发消息)也要先拿到锁
193
+ pi.on("agent_start", (_event, ctx) => {
194
+ lastCtx = ctx;
195
+ if (!enabled() || !PASEO || (held.dir && !held.conflict)) return;
196
+ claimNow(ctx);
197
+ if (!held.conflict) return;
198
+ warn(ctx, `🔒 已中断本次运行:${held.conflict}`, "error");
199
+ try {
200
+ ctx.abort();
201
+ } catch {
202
+ /* 拿不到 abort 就让这次运行自己结束 */
203
+ }
204
+ });
205
+
206
+ // paseo 侧写完就放:空闲进程不该继续占着会话
207
+ pi.on("agent_settled", (_event, ctx) => {
208
+ lastCtx = ctx;
209
+ dbg("agent_settled");
210
+ if (!PASEO || !held.dir) return;
211
+ release(held.dir);
212
+ held = { dir: null, conflict: null, unknown: null };
213
+ });
214
+
215
+ pi.on("user_bash", (_event, ctx) => {
216
+ if (!held.conflict) return;
217
+ warn(ctx, "🔒 会话被另一进程占用,用户 bash 已拦。", "error");
218
+ return {
219
+ result: {
220
+ output: "blocked: session is locked by another live pi process",
221
+ exitCode: 1,
222
+ cancelled: false,
223
+ truncated: false,
224
+ },
225
+ };
226
+ });
227
+
228
+ // 切到别人的会话前先看一眼(不让 /resume 撞上活进程)。拿不到就放行。
229
+ pi.on("session_before_switch", (event, ctx) => {
230
+ if (!enabled() || event.reason !== "resume" || !event.targetSessionFile) return;
231
+ const probe = claim(event.targetSessionFile);
232
+ if (probe.ok && probe.dir && probe.dir !== held.dir) {
233
+ // 只是探测:别把目标会话的锁留着(当前会话的锁不动)
234
+ release(probe.dir);
235
+ return;
236
+ }
237
+ if (probe.state === "conflict") {
238
+ warn(ctx, `🔒 不能 resume:${probe.warning ?? probe.reason}`, "error");
239
+ return { cancel: true };
240
+ }
241
+ });
242
+
243
+ pi.on("session_shutdown", () => {
244
+ stopRetry();
245
+ if (yieldTimer) clearInterval(yieldTimer);
246
+ yieldTimer = null;
247
+ pending = null;
248
+ release(held.dir);
249
+ held = { dir: null, conflict: null, unknown: null };
250
+ });
251
+
252
+ pi.registerCommand("session-lock", {
253
+ description: "查看当前会话锁状态",
254
+ handler: async (_args, ctx) => {
255
+ const file = ctx.sessionManager.getSessionFile();
256
+ const describe = () => {
257
+ if (!file) return "no session file (ephemeral session)";
258
+ if (!enabled()) return `disabled (PI_SESSION_LOCK=off)\n${lockDirFor(file)}`;
259
+ if (held.conflict) return `conflict: ${held.conflict}\n${held.dir}`;
260
+ if (held.unknown) return `unknown: ${held.unknown}\n${held.dir}`;
261
+ if (held.dir) return `owned by this process (pid ${process.pid})\n${held.dir}`;
262
+ if (PASEO) return `paseo-managed (${PASEO.label}): 空闲不持锁,输入时认领\n${lockDirFor(file)}`;
263
+ return "no lock (ephemeral session)";
264
+ };
265
+ warn(ctx, `🔒 ${describe()}`, held.conflict ? "error" : "info");
266
+ },
267
+ });
268
+
269
+ pi.registerCommand("session-lock-release", {
270
+ description: "回收已证明死掉的会话锁(不抢活进程的锁)",
271
+ handler: async (_args, ctx) => {
272
+ const file = ctx.sessionManager.getSessionFile();
273
+ if (!file) return;
274
+ const dir = lockDirFor(file);
275
+ const owner = readOwner(dir);
276
+ if (owner) {
277
+ const verdict = classify(owner);
278
+ if (verdict.kind === "live") {
279
+ return warn(ctx, `🔒 拒绝回收:${verdict.reason}(真要强拆请自己删 ${dir} 并确认没有进程在用)`, "error");
280
+ }
281
+ }
282
+ release(held.dir);
283
+ claimNow(ctx);
284
+ warn(ctx, `🔒 已回收并重新认领:${held.dir}`, "info");
285
+ },
286
+ });
287
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "pi-session-lock",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.1",
4
+ "description": "One writer per pi session: a shared advisory lock (agent-side extension + server-side callers use the same core).",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-extension",
8
+ "pi-coding-agent",
9
+ "session",
10
+ "lock",
11
+ "single-writer",
12
+ "paseo"
13
+ ],
14
+ "license": "MIT",
15
+ "engines": {
16
+ "node": ">=22.19"
17
+ },
18
+ "type": "module",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+ssh://git@github.com/xiaquwan1001/pi-session-lock.git"
22
+ },
23
+ "homepage": "https://github.com/xiaquwan1001/pi-session-lock#readme",
24
+ "bugs": {
25
+ "url": "https://github.com/xiaquwan1001/pi-session-lock/issues"
26
+ },
27
+ "files": [
28
+ "core.mjs",
29
+ "extensions",
30
+ "README.md"
31
+ ],
32
+ "exports": {
33
+ ".": "./core.mjs",
34
+ "./core": "./core.mjs"
35
+ },
36
+ "pi": {
37
+ "extensions": [
38
+ "./extensions/session-lock.ts"
39
+ ]
40
+ }
41
+ }