pi-session-lock 0.3.1 → 0.6.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/follow.mjs ADDED
@@ -0,0 +1,278 @@
1
+ /**
2
+ * 只读跟随(read-only follow)—— 渲染另一个进程正在写的会话,但不持有会话、不写会话文件。
3
+ *
4
+ * 为什么单独一份实现:
5
+ * pi 没有「只读 attach」模式:任何进程打开同一个 .jsonl 都会在启动/切换时写元数据,
6
+ * compaction 还会整文件重写(上游 #8300)。所以跟随只能**旁观文件**,不能 resume 它。
7
+ * 本文件只做纯读取:增量解析 JSONL → 还原当前分支 → 渲染成可显示的逻辑行。
8
+ * 输入不经过本进程:由调用方写 pi-mailbox 的 inbox(`sendToMailbox`),
9
+ * 交给持有会话的那个 pi 进程用 sendUserMessage(followUp) 注入。
10
+ *
11
+ * 边界(实测):
12
+ * - 会话文件是 append-only,但 compaction 用 truncate 原地重写 ⇒ 必须按 (ino,size) 判重扫。
13
+ * - 只吃完整行:最后一行没有换行符时留到下次再拼,避免把半截 JSON 当条目。
14
+ * - 只渲染当前分支(最后一条的 parentId 链),不渲染旁支;不还原 compaction 投影。
15
+ */
16
+ import fs from "node:fs";
17
+ import path from "node:path";
18
+ // 信箱根的解析口径只有一份(core.mjs 的 mailboxRoot:PI_MAILBOX_DIR 优先,旧名作别名,默认 home)
19
+ import { mailboxRoot } from "./core.mjs";
20
+
21
+ /** 名册心跳超过这个时间视为僵尸(与 mailbox-send 的默认 --stale 一致)。 */
22
+ export const PRESENCE_STALE_MS = 90_000;
23
+
24
+ /**
25
+ * 增量读取会话文件。
26
+ * @param {string} sessionFile
27
+ * @param {{ino?:number,size?:number,entries?:any[]}|null} prev 上次读到的状态
28
+ * @returns {{entries:any[], size:number, ino:number, mtimeMs:number, reset:boolean}}
29
+ */
30
+ export function readSessionDelta(sessionFile, prev = null) {
31
+ let stat;
32
+ try {
33
+ stat = fs.statSync(sessionFile);
34
+ } catch {
35
+ return { entries: prev?.entries ?? [], size: prev?.size ?? 0, ino: prev?.ino ?? 0, mtimeMs: 0, reset: false };
36
+ }
37
+ const ino = Number(stat.ino);
38
+ const reset = !prev || prev.ino !== ino || stat.size < (prev.size ?? 0);
39
+ const from = reset ? 0 : prev.size ?? 0;
40
+ if (!reset && stat.size === from) {
41
+ return { entries: prev.entries ?? [], size: from, ino, mtimeMs: stat.mtimeMs, reset: false };
42
+ }
43
+
44
+ let chunk = "";
45
+ try {
46
+ const fd = fs.openSync(sessionFile, "r");
47
+ try {
48
+ const length = stat.size - from;
49
+ const buf = Buffer.alloc(length);
50
+ const read = fs.readSync(fd, buf, 0, length, from);
51
+ chunk = buf.subarray(0, read).toString("utf8");
52
+ } finally {
53
+ fs.closeSync(fd);
54
+ }
55
+ } catch {
56
+ return { entries: prev?.entries ?? [], size: prev?.size ?? 0, ino, mtimeMs: stat.mtimeMs, reset: false };
57
+ }
58
+
59
+ // 只吃完整行;末尾没有换行的那截留到下一轮(从它的起点继续读)。
60
+ const lastNewline = chunk.lastIndexOf("\n");
61
+ const complete = lastNewline === -1 ? "" : chunk.slice(0, lastNewline + 1);
62
+ const consumed = Buffer.byteLength(complete, "utf8");
63
+ const parsed = reset ? [] : [...(prev.entries ?? [])];
64
+ for (const line of complete.split("\n")) {
65
+ const trimmed = line.trim();
66
+ if (!trimmed) continue;
67
+ try {
68
+ parsed.push(JSON.parse(trimmed));
69
+ } catch {
70
+ /* 半截/损坏的行直接跳过:跟随不能因为一条坏行停摆 */
71
+ }
72
+ }
73
+ return { entries: parsed, size: from + consumed, ino, mtimeMs: stat.mtimeMs, reset };
74
+ }
75
+
76
+ /**
77
+ * 当前分支:最后一条条目的 parentId 链(文件是 append-only,最后一条就是当前 leaf)。
78
+ * 头部的 session 行没有 id,不参与。
79
+ */
80
+ export function activeBranch(entries) {
81
+ const byId = new Map();
82
+ for (const entry of entries) {
83
+ if (entry && typeof entry.id === "string") byId.set(entry.id, entry);
84
+ }
85
+ let leaf = null;
86
+ for (let i = entries.length - 1; i >= 0; i -= 1) {
87
+ const entry = entries[i];
88
+ if (entry && typeof entry.id === "string" && entry.type !== "session") {
89
+ leaf = entry;
90
+ break;
91
+ }
92
+ }
93
+ const chain = [];
94
+ const seen = new Set();
95
+ while (leaf && !seen.has(leaf.id)) {
96
+ seen.add(leaf.id);
97
+ chain.push(leaf);
98
+ leaf = leaf.parentId ? byId.get(leaf.parentId) ?? null : null;
99
+ }
100
+ return chain.reverse();
101
+ }
102
+
103
+ function contentToText(content) {
104
+ if (typeof content === "string") return content;
105
+ if (!Array.isArray(content)) return "";
106
+ const parts = [];
107
+ for (const block of content) {
108
+ if (!block || typeof block !== "object") continue;
109
+ if (block.type === "text") parts.push(String(block.text ?? ""));
110
+ else if (block.type === "image") parts.push("[image]");
111
+ }
112
+ return parts.join("\n");
113
+ }
114
+
115
+ function compactArgs(args) {
116
+ if (args === undefined || args === null) return "";
117
+ let text;
118
+ try {
119
+ text = typeof args === "string" ? args : JSON.stringify(args);
120
+ } catch {
121
+ text = String(args);
122
+ }
123
+ text = text.replace(/\s+/g, " ").trim();
124
+ return text.length > 100 ? `${text.slice(0, 97)}…` : text;
125
+ }
126
+
127
+ /**
128
+ * 把分支渲染成逻辑行(不按宽度折行,也不带 ANSI;折行/上色由 UI 层做)。
129
+ * @param {any[]} branch
130
+ * @param {{maxEntries?:number, toolResults?:boolean, maxCharsPerEntry?:number}} [opts]
131
+ * @returns {{style:"user"|"assistant"|"tool"|"result"|"meta"|"system", text:string}[]}
132
+ */
133
+ export function transcriptLines(branch, opts = {}) {
134
+ const maxEntries = opts.maxEntries ?? 400;
135
+ const toolResults = opts.toolResults ?? false;
136
+ const maxChars = opts.maxCharsPerEntry ?? 4000;
137
+ const slice = branch.slice(-maxEntries);
138
+ const out = [];
139
+
140
+ const push = (style, text) => {
141
+ let body = String(text ?? "").trimEnd();
142
+ if (!body) return;
143
+ if (body.length > maxChars) body = `${body.slice(0, maxChars)}\n…(截断,共 ${body.length} 字符)`;
144
+ out.push({ style, text: body });
145
+ };
146
+
147
+ for (const entry of slice) {
148
+ if (!entry || typeof entry !== "object") continue;
149
+ if (entry.type === "compaction") {
150
+ push("meta", `⟳ 上下文已压缩:${firstLine(entry.summary)}`);
151
+ continue;
152
+ }
153
+ if (entry.type === "branch_summary") {
154
+ push("meta", `↩ 分支摘要:${firstLine(entry.summary)}`);
155
+ continue;
156
+ }
157
+ if (entry.type === "custom_message") {
158
+ if (entry.display === false) continue;
159
+ push("system", contentToText(entry.content));
160
+ continue;
161
+ }
162
+ if (entry.type !== "message" || !entry.message) continue;
163
+ const message = entry.message;
164
+ const role = message.role;
165
+
166
+ if (role === "user") {
167
+ push("user", contentToText(message.content));
168
+ continue;
169
+ }
170
+ if (role === "assistant") {
171
+ const blocks = Array.isArray(message.content) ? message.content : [];
172
+ const texts = [];
173
+ for (const block of blocks) {
174
+ if (!block || typeof block !== "object") continue;
175
+ if (block.type === "text") texts.push(String(block.text ?? ""));
176
+ else if (block.type === "toolCall") {
177
+ if (texts.length) {
178
+ push("assistant", texts.join("\n"));
179
+ texts.length = 0;
180
+ }
181
+ push("tool", `⏵ ${block.name}(${compactArgs(block.arguments)})`);
182
+ }
183
+ }
184
+ if (texts.length) push("assistant", texts.join("\n"));
185
+ if (message.stopReason === "error") push("meta", `⚠ 上一轮以错误结束:${message.errorMessage ?? "unknown"}`);
186
+ continue;
187
+ }
188
+ if (role === "toolResult") {
189
+ if (!toolResults) continue;
190
+ const text = contentToText(message.content) || (message.isError ? "(工具报错)" : "(无输出)");
191
+ push("result", `⎿ ${message.toolName ?? "tool"}: ${firstLine(text)}`);
192
+ continue;
193
+ }
194
+ if (role === "bashExecution") {
195
+ if (!toolResults) continue;
196
+ push("tool", `$ ${message.command ?? ""}`);
197
+ push("result", firstLine(message.output ?? ""));
198
+ continue;
199
+ }
200
+ if (role === "custom") {
201
+ if (message.display === false) continue;
202
+ push("system", contentToText(message.content));
203
+ continue;
204
+ }
205
+ if (role === "branchSummary") {
206
+ push("meta", `↩ 分支摘要:${firstLine(message.summary)}`);
207
+ continue;
208
+ }
209
+ if (role === "compactionSummary") {
210
+ push("meta", `⟳ 上下文已压缩:${firstLine(message.summary)}`);
211
+ continue;
212
+ }
213
+ if (role === "system") continue; // 系统提示不给人看
214
+ // 未知自定义角色:尽力而为,别把窗口搞挂
215
+ const fallback = contentToText(message.content);
216
+ if (fallback) push("system", fallback);
217
+ }
218
+ return out;
219
+ }
220
+
221
+ function firstLine(text) {
222
+ const line = String(text ?? "").trim().split("\n")[0] ?? "";
223
+ return line.length > 160 ? `${line.slice(0, 157)}…` : line;
224
+ }
225
+
226
+ /** 读 pi-mailbox 名册(只读);目录根与 core.mjs 同一解析(`mailboxRoot()`)。 */
227
+ export function readPresence(pid, mailboxDir = mailboxRoot()) {
228
+ if (!Number.isFinite(pid)) return null;
229
+ try {
230
+ return JSON.parse(fs.readFileSync(path.join(mailboxDir, "presence", `${pid}.json`), "utf8"));
231
+ } catch {
232
+ return null;
233
+ }
234
+ }
235
+
236
+ /**
237
+ * 把一句话投给持有会话的 pi 进程(等同用户在他那边敲一句)。
238
+ * 只写 mailbox 的 inbox 文件,不碰会话文件。
239
+ * @param {{pid:number, text:string, from?:string, ttlMs?:number, mailboxDir?:string, now?:number}} opts
240
+ * @returns {{ok:boolean, reason:string, file?:string}}
241
+ */
242
+ export function sendToMailbox(opts) {
243
+ const pid = opts.pid;
244
+ const text = String(opts.text ?? "").trim();
245
+ if (!Number.isFinite(pid)) return { ok: false, reason: "没有持有者 pid" };
246
+ if (!text) return { ok: false, reason: "空消息" };
247
+ const mailboxDir = opts.mailboxDir ?? mailboxRoot();
248
+ const presence = readPresence(pid, mailboxDir);
249
+ if (!presence) return { ok: false, reason: `pid ${pid} 没有 mailbox 名册(可能不是交互会话)` };
250
+ const now = opts.now ?? Date.now();
251
+ const beat = Date.parse(presence.heartbeatAt ?? "");
252
+ if (!Number.isFinite(beat) || now - beat > PRESENCE_STALE_MS) {
253
+ return { ok: false, reason: `pid ${pid} 的名册心跳已过期(进程可能已经不在)` };
254
+ }
255
+ try {
256
+ process.kill(pid, 0);
257
+ } catch (error) {
258
+ if (error.code !== "EPERM") return { ok: false, reason: `pid ${pid} 已经不在` };
259
+ }
260
+ const inboxDir = path.join(mailboxDir, "inbox", String(pid));
261
+ try {
262
+ fs.mkdirSync(inboxDir, { recursive: true });
263
+ const file = path.join(inboxDir, `${now}-${Math.random().toString(36).slice(2, 8)}.json`);
264
+ fs.writeFileSync(
265
+ file,
266
+ `${JSON.stringify({
267
+ text,
268
+ from: opts.from ?? "session-follow",
269
+ ts: new Date(now).toISOString(),
270
+ expiresAt: new Date(now + (opts.ttlMs ?? 3600_000)).toISOString(),
271
+ })}\n`,
272
+ { mode: 0o600 },
273
+ );
274
+ return { ok: true, reason: "已投递", file };
275
+ } catch (error) {
276
+ return { ok: false, reason: `写入信箱失败:${String(error)}` };
277
+ }
278
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-session-lock",
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).",
3
+ "version": "0.6.0",
4
+ "description": "One writer per pi session, softened: on conflict request a yield, then auto-fork instead of blocking; plus a read-only follow viewer that forwards input via pi-mailbox.",
5
5
  "keywords": [
6
6
  "pi",
7
7
  "pi-extension",
@@ -16,6 +16,9 @@
16
16
  "node": ">=22.19"
17
17
  },
18
18
  "type": "module",
19
+ "scripts": {
20
+ "test": "node test/core.test.mjs && node test/follow.test.mjs && node test/paseo.test.mjs && node test/yield.test.mjs && node test/takeover.test.mjs && node test/ask.test.mjs && node test/fork.test.mjs && node test/two-process.test.mjs"
21
+ },
19
22
  "repository": {
20
23
  "type": "git",
21
24
  "url": "git+ssh://git@github.com/xiaquwan1001/pi-session-lock.git"
@@ -26,8 +29,11 @@
26
29
  },
27
30
  "files": [
28
31
  "core.mjs",
32
+ "follow.mjs",
29
33
  "extensions",
30
- "README.md"
34
+ "bin",
35
+ "README.md",
36
+ "CHANGELOG.md"
31
37
  ],
32
38
  "exports": {
33
39
  ".": "./core.mjs",
@@ -37,5 +43,20 @@
37
43
  "extensions": [
38
44
  "./extensions/session-lock.ts"
39
45
  ]
46
+ },
47
+ "bin": {
48
+ "pi-session-follow": "./bin/session-follow"
49
+ },
50
+ "peerDependencies": {
51
+ "@earendil-works/pi-coding-agent": "*",
52
+ "@earendil-works/pi-tui": "*"
53
+ },
54
+ "peerDependenciesMeta": {
55
+ "@earendil-works/pi-coding-agent": {
56
+ "optional": true
57
+ },
58
+ "@earendil-works/pi-tui": {
59
+ "optional": true
60
+ }
40
61
  }
41
62
  }