pi-hub-server 0.8.0 → 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.
@@ -0,0 +1,106 @@
1
+ /**
2
+ * 会话锁协议的**唯一常量表**(hub 侧)。
3
+ *
4
+ * 为什么单独一份:hub 与 `pi-session-lock` 插件之间真正共享的不是代码,而是一份
5
+ * **落盘协议** —— 锁目录怎么命名、`owner.json` 有哪些字段、什么情况算「活着」。
6
+ * 之前这些常量各写一遍(hub 的 `session-lock-fallback.mjs` 一份、插件 `core.mjs` 一份),
7
+ * 靠人眼对齐,已经漂过一次(`classify` 的 pid 缺失保护只有 hub 有)。
8
+ * 现在 hub 侧只认本文件;插件仍是独立实现,靠 `test/lock-conformance.mjs`
9
+ * 用同一批夹具跑两边、逐条比对结果来保证不漂。
10
+ *
11
+ * 协议面(改动=breaking,必须同步改插件并升 `CORE_API_VERSION`):
12
+ * 1. 锁目录:`<agentDir>/session-locks/<sha256(realpath(session))>.lock/`
13
+ * 2. `owner.json`:`{v,pid,host,bootId,startTicks,instanceId}` 必备,
14
+ * `{source,sessionFile,acquiredAt,ownerPid,idleYield}` 可选
15
+ * 3. 身份复用键:同进程同时加载插件与内置实现时必须共用同一个 globalThis 身份
16
+ * 4. 判定取值域:`self | live | dead | unknown`(只有 dead 允许回收)
17
+ *
18
+ * 进程外消费者(hub)能消费的插件版本:`SUPPORTED_CORE_API`。
19
+ */
20
+ import fs from "node:fs";
21
+ import os from "node:os";
22
+ import path from "node:path";
23
+ import crypto from "node:crypto";
24
+
25
+ /** hub 能消费的插件 core API 版本;插件 README「冻结面」要求消费方不匹配就降级。 */
26
+ export const SUPPORTED_CORE_API = 1;
27
+
28
+ /** 插件必须给出的函数(= 消费面全集);缺一个就当没装,不许半残着抢锁。 */
29
+ export const REQUIRED_CORE_EXPORTS = ["identity", "lockDirFor", "peek", "claim", "release", "classify", "readOwner"];
30
+
31
+ /** 同进程多实现的身份复用键(插件 `core.mjs` 与内置实现用同一个 `Symbol.for`)。 */
32
+ export const IDENTITY_KEY = Symbol.for("pi.session-lock.identity");
33
+
34
+ export const LOCK_ROOT_DIRNAME = "session-locks";
35
+ export const LOCK_DIR_SUFFIX = ".lock";
36
+ export const OWNER_FILE_NAME = "owner.json";
37
+
38
+ /** `owner.json` 必备字段(`classify` 只依赖这几个;其余是排查用的可选字段)。 */
39
+ export const OWNER_REQUIRED_FIELDS = ["v", "pid", "host", "bootId", "startTicks", "instanceId"];
40
+
41
+ /** `classify` 的取值域;只有 `dead` 允许回收别人的锁目录。 */
42
+ export const OWNER_VERDICTS = ["self", "live", "dead", "unknown"];
43
+
44
+ /** 锁根目录:显式参数 > `PI_CODING_AGENT_DIR` > `~/.pi/agent`(与 pi/插件同式)。 */
45
+ export function resolveAgentDir(explicit) {
46
+ return explicit || process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent");
47
+ }
48
+
49
+ /** 会话文件的规范绝对路径:相对路径按当前 cwd 解析,存在时取 realpath。 */
50
+ export function canonicalSessionPath(sessionFile) {
51
+ const abs = path.resolve(sessionFile);
52
+ try {
53
+ return fs.realpathSync(abs);
54
+ } catch {
55
+ return abs;
56
+ }
57
+ }
58
+
59
+ /** 与插件逐字一致的锁目录:`<agentDir>/session-locks/<sha256(canonical)>.lock`。 */
60
+ export function lockDirFor(sessionFile, opts = {}) {
61
+ const hash = crypto.createHash("sha256").update(canonicalSessionPath(sessionFile)).digest("hex");
62
+ return path.join(resolveAgentDir(opts.agentDir), LOCK_ROOT_DIRNAME, `${hash}${LOCK_DIR_SUFFIX}`);
63
+ }
64
+
65
+ /** 锁目录里的 owner 文件路径。 */
66
+ export function ownerPath(dir) {
67
+ return path.join(dir, OWNER_FILE_NAME);
68
+ }
69
+
70
+ /**
71
+ * 自动发现插件 `core.mjs` 的候选位置(顺序即优先级),每条都带**它能被写进发布包的理由**。
72
+ *
73
+ * 判据:候选只能是「本包自己的依赖解析」或「插件/pi 明确文档化的安装位置」。
74
+ * **作者本机的仓目录布局(`~/pi-plugins/**`、同级 checkout)不进候选** —— 发布出去的
75
+ * 包不该扫用户的 home 找别人的源码仓;这类装法用 `PI_HUB_SESSION_LOCK_CORE` 显式指。
76
+ *
77
+ * 注意:这里的每一项都是「猜位置」,所以命中后要报 `corePath`(`/v1/health` 与 banner 都打),
78
+ * 让用户看得到 hub 到底加载了哪一份。而 `PI_HUB_SESSION_LOCK_CORE` 是**用户点名的**:
79
+ * 指到不存在的文件时 `session-lock.mjs` 直接进 error 状态,不会顺着这张表往下猜。
80
+ *
81
+ * @param {{here:string, home:string, resolved?:string|null}} ctx
82
+ * here = 本模块所在目录(`<prefix>/lib/node_modules/pi-hub-server/src`)
83
+ * @returns {{file:string, why:string}[]}
84
+ */
85
+ export function lockCoreCandidates({ here, home, resolved = null }) {
86
+ const list = [];
87
+ if (process.env.PI_HUB_SESSION_LOCK_CORE) {
88
+ list.push({ file: process.env.PI_HUB_SESSION_LOCK_CORE, why: "显式指定:PI_HUB_SESSION_LOCK_CORE" });
89
+ }
90
+ if (resolved) list.push({ file: resolved, why: "本包依赖解析命中(用户自己 npm i pi-session-lock 落在本包 node_modules)" });
91
+ list.push(
92
+ {
93
+ file: path.join(here, "..", "node_modules", "pi-session-lock", "core.mjs"),
94
+ why: "本包 node_modules 里的嵌套安装(npm i pi-session-lock 落在包内;hub 不再声明这个依赖)",
95
+ },
96
+ {
97
+ file: path.join(here, "..", "..", "pi-session-lock", "core.mjs"),
98
+ why: "全局并列安装(npm i -g pi-session-lock:两个包各自的 <prefix>/lib/node_modules)",
99
+ },
100
+ {
101
+ file: path.join(home, ".pi", "agent", "npm", "node_modules", "pi-session-lock", "core.mjs"),
102
+ why: "pi 自己的包目录(pi install pi-session-lock)",
103
+ },
104
+ );
105
+ return list;
106
+ }
@@ -3,6 +3,7 @@ import { PI_BIN } from "./config.mjs";
3
3
  import { piArgs } from "./pi-args.mjs";
4
4
  import { killChildTree, piSpawnSpec } from "./pi-spawn.mjs";
5
5
  import { claim, peek, release } from "./session-lock.mjs";
6
+ import { PREVIEW_MAX, readFilePreview } from "./sessions-index.mjs";
6
7
 
7
8
  const RING_MAX = 2000;
8
9
  /** 需要用户回答的扩展 UI 方法;其余按 fire-and-forget 处理。 */
@@ -57,6 +58,11 @@ export class LiveSession {
57
58
  this.cwd = opts.cwd;
58
59
  this.name = opts.name ?? null;
59
60
  this.model = opts.model ?? null;
61
+ /**
62
+ * 会话首条用户消息(截断 `PREVIEW_MAX`)。会话列表里「未命名会话」的标题来源:
63
+ * 没落盘 / 刚落盘还没写用户消息的 live 行拿不到文件里的 `preview`,只能靠这里。
64
+ */
65
+ this.firstUserText = null;
60
66
  this.sessionFile = opts.sessionFile ?? null;
61
67
  this.lockDir = null;
62
68
  /** 锁对应的会话文件(回合结束让锁后还留着,下次写前按它重抢)。 */
@@ -157,7 +163,8 @@ export class LiveSession {
157
163
  cwd: this.cwd,
158
164
  // hub 自己就是进程外的锁管理者(#claimLock):子进程若也加载 host 的 session-lock 扩展,
159
165
  // 它会在 session_start 先认领会话锁,hub 再认领就得到 conflict(默认加载全部扩展后实测)。
160
- // PI_SESSION_LOCK=off 只关掉**子进程内**的扩展认领,hub 侧的 claim/peek 不受影响。
166
+ // `PI_SESSION_LOCK=off` 是**社区插件自己的开关**(`pi-session-lock` 扩展读它),不是 hub 对它的依赖:
167
+ // 没装插件时这个变量没人看,hub 的 claim/peek 照走内置实现,行为不变。
161
168
  env: { ...process.env, PI_HUB: "1", PI_SESSION_LOCK: "off" },
162
169
  stdio: ["pipe", "pipe", "pipe"],
163
170
  });
@@ -200,6 +207,8 @@ export class LiveSession {
200
207
  throw failure;
201
208
  }
202
209
  this.sessionFile = state.sessionFile ?? this.sessionFile;
210
+ // 续会话:pi 不会重放首条用户消息,从会话文件头部补一份(列表标题用,只读不写)。
211
+ this.adoptFirstUserText();
203
212
  try {
204
213
  if (this.sessionFile && !this.lockDir) this.#claimLock(this.sessionFile);
205
214
  } catch (err) {
@@ -397,6 +406,32 @@ export class LiveSession {
397
406
  this.#write({ type, ...payload });
398
407
  }
399
408
 
409
+ /**
410
+ * 记录首条用户消息文本(prompt / follow-up 的入参文本)。
411
+ * 只认第一条:会话列表的标题是「这个会话第一句话在说什么」,后续消息不覆盖。
412
+ * @param {string} text
413
+ * @returns {boolean} 是否真的写入了(空文本 / 已有首条 → false)
414
+ */
415
+ noteUserText(text) {
416
+ if (this.firstUserText) return false;
417
+ const trimmed = typeof text === "string" ? text.trim() : "";
418
+ if (!trimmed) return false;
419
+ this.firstUserText = trimmed.slice(0, PREVIEW_MAX);
420
+ return true;
421
+ }
422
+
423
+ /**
424
+ * 续会话时从会话文件补 `firstUserText`(首条用户消息)。只读头部,不 spawn、不写文件。
425
+ * @returns {boolean} 是否真的写入了(已有首条 / 不知道文件 / 文件里还没有用户消息 → false)
426
+ */
427
+ adoptFirstUserText() {
428
+ if (this.firstUserText || !this.sessionFile) return false;
429
+ const preview = readFilePreview(this.sessionFile);
430
+ if (!preview) return false;
431
+ this.firstUserText = preview;
432
+ return true;
433
+ }
434
+
400
435
  touch() {
401
436
  this.lastActivity = Date.now();
402
437
  }
@@ -406,6 +441,8 @@ export class LiveSession {
406
441
  id: this.id,
407
442
  cwd: this.cwd,
408
443
  name: this.name,
444
+ // 列表标题的实时来源(未落盘/刚建会话拿不到文件 preview 时用)。
445
+ firstUserText: this.firstUserText,
409
446
  model: this.state.model,
410
447
  status: this.state.status,
411
448
  ready: this.ready,
package/src/server.mjs CHANGED
@@ -3,7 +3,7 @@ import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
5
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
- import { findSession, listSessions, readHistory, sliceHistoryPage } from "./sessions-index.mjs";
6
+ import { PREVIEW_MAX, findSession, listSessions, readHistory, sliceHistoryPage, sortSessionRows } 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";
@@ -13,6 +13,8 @@ import {
13
13
  coreApiVersion as sessionLockCoreApiVersion,
14
14
  lockSource as sessionLockSource,
15
15
  lockReason as sessionLockReason,
16
+ lockHint as sessionLockHint,
17
+ explicitPointerError as sessionLockExplicitPointerError,
16
18
  pluginVersion as sessionLockPluginVersion,
17
19
  supportedCoreApi as sessionLockSupportedCoreApi,
18
20
  } from "./session-lock.mjs";
@@ -280,7 +282,12 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
280
282
  // 会话锁来源 / 版本面
281
283
  // ---------------------------------------------------------------------------
282
284
 
283
- /** `/v1/health.sessionLockInfo` 与 createHubServer().sessionLock 的同一份口径。 */
285
+ /**
286
+ * `/v1/health.sessionLockInfo` 与 createHubServer().sessionLock 的同一份口径。
287
+ *
288
+ * `source:"fallback"` 是**默认状态**(内置锁),不是故障:`hint` 给出「要不要装插件」的那一行,
289
+ * `explicitPointerError` 只在用户把 `PI_HUB_SESSION_LOCK_CORE` 指坏时非 null(那时 serve 不会起来)。
290
+ */
284
291
  function sessionLockInfo() {
285
292
  return {
286
293
  source: sessionLockSource,
@@ -289,6 +296,8 @@ function sessionLockInfo() {
289
296
  coreApiVersion: sessionLockCoreApiVersion,
290
297
  supportedCoreApi: sessionLockSupportedCoreApi,
291
298
  reason: sessionLockReason,
299
+ hint: sessionLockHint,
300
+ explicitPointerError: sessionLockExplicitPointerError,
292
301
  };
293
302
  }
294
303
 
@@ -723,10 +732,43 @@ function readStreamingBehavior(body) {
723
732
  return body.streamingBehavior;
724
733
  }
725
734
 
735
+ /**
736
+ * live 会话的标题来源:`firstUserText`(prompt/follow-up 记录或 resume 时从文件补)截到 160。
737
+ * 拿不到就 null —— 客户端回退到「新会话」。
738
+ */
739
+ function livePreview(session) {
740
+ const text = typeof session?.firstUserText === "string" ? session.firstUserText.trim() : "";
741
+ return text ? text.slice(0, PREVIEW_MAX) : null;
742
+ }
743
+
744
+ /**
745
+ * live 状态里算「还在跑」的那几个:客户端行尾要转圈。
746
+ * `starting` 是刚 spawn 还没收到第一条事件(同样不该显示成「完成」),`idle`/`closed` 落到文件行。
747
+ */
748
+ const LIVE_RUNNING_STATES = new Set(["starting", "running", "thinking", "compacting"]);
749
+
750
+ /**
751
+ * 会话行的 `lastStatus`:live 会话能判「进行中」,其余(含 idle)回落到文件尾部的判定,
752
+ * 没有文件的行(刚建、未落盘)当 `done`。
753
+ * @param {{status?:string}|null|undefined} session registry 快照
754
+ * @param {"done"|"aborted"|"error"|undefined} diskLastStatus 同 id 的磁盘行判定
755
+ * @returns {"running"|"done"|"aborted"|"error"}
756
+ */
757
+ function rowLastStatus(session, diskLastStatus) {
758
+ // 只在状态字段上判会漏掉「prompt 已到、pi 的 status 事件还没到」的瞬时空窗:
759
+ // 那时磁盘尾行是刚写入的 user 消息,会被判成 error 红点。isStreaming/isCompacting 一并对齐。
760
+ if (session && (LIVE_RUNNING_STATES.has(session.status) || session.isStreaming || session.isCompacting)) {
761
+ return "running";
762
+ }
763
+ return diskLastStatus ?? "done";
764
+ }
765
+
726
766
  /**
727
767
  * 会话库 + 存活状态合并。
728
768
  * `limit` 省略时保持旧行为(磁盘侧 200 条 + 未落盘的 live 行,不做合并截断);
729
769
  * `before` 是 `updatedAt` ISO 游标,只保留严格早于它的条目。
770
+ * 结果全局按 `updatedAt` 降序(同 timestamp 用 id 兜底,见 `sortSessionRows`):
771
+ * 主机侧新建/刚活动的会话必须能把位置顶到前面,不能靠「live 行前插」这种偶然顺序。
730
772
  */
731
773
  function mergedSessions(registry, { limit, before } = {}) {
732
774
  const cap = limit === undefined ? 200 : Math.min(limit, MAX_SESSIONS_LIMIT);
@@ -739,20 +781,25 @@ function mergedSessions(registry, { limit, before } = {}) {
739
781
  return {
740
782
  id: entry.id,
741
783
  name: session?.name ?? entry.name,
742
- preview: entry.preview,
784
+ // 文件里已解析出首条用户消息就用它;还没写盘(刚建会话/首轮未 flush)用 live 记录的兜底。
785
+ preview: entry.preview ?? livePreview(session),
743
786
  cwd: entry.cwd,
744
787
  model: modelAlias(session?.model ?? entry.model),
745
788
  updatedAt: entry.updatedAt,
746
789
  createdAt: entry.createdAt,
747
790
  live: Boolean(session),
748
791
  status: session?.status ?? null,
792
+ lastStatus: rowLastStatus(session, entry.lastStatus),
749
793
  };
750
794
  });
751
795
  for (const [id, session] of live) {
752
796
  if (rows.some((r) => r.id === id)) continue;
753
797
  // registry.list() 返回的已经是快照,不要再调 .snapshot()
754
- rows.unshift({ id, name: session.name, preview: null, cwd: session.cwd, model: modelAlias(session.model), updatedAt: session.lastActivity, createdAt: session.startedAt, live: true, status: session.status });
798
+ // 未落盘的行没有文件 mtime:`lastActivity` 是实时值(每个请求重新取快照),preview 取首条用户消息。
799
+ rows.push({ id, name: session.name, preview: livePreview(session), cwd: session.cwd, model: modelAlias(session.model), updatedAt: session.lastActivity, createdAt: session.startedAt, live: true, status: session.status, lastStatus: rowLastStatus(session, null) });
755
800
  }
801
+ // 全局降序:排序必须在去重之前,同一 id 多行时才保留「先到(更新)」那行作为排序位。
802
+ sortSessionRows(rows);
756
803
  // 游标对所有行生效(包括未落盘的 live 行),保证「严格小于 updatedAt」
757
804
  const kept = cutoff === null ? rows : rows.filter((r) => Date.parse(r.updatedAt) < cutoff);
758
805
  // 去重:同一个会话文件可能在多个项目目录里各有一份(扫出来 id 相同);
@@ -1155,9 +1202,9 @@ export function createHubServer({ fetchJson } = {}) {
1155
1202
  idleMs: IDLE_MS,
1156
1203
  // 升级后第一眼看见契约漂移:不认识的事件数(进程级累计)。
1157
1204
  unknownEvents: registry.unknownEvents(),
1158
- // 锁的实际来源:plugin = pi-session-lock,fallback = 仓内最小实现(与 doctor/banner 同口径)。
1205
+ // 锁的来源:plugin = 与桌面 pi 共用一份锁(装了插件),fallback = hub 内置锁(默认状态)。
1159
1206
  sessionLock: sessionLockSource,
1160
- // 版本面:插件版本 + 冻结的 core API 版本;降级时为 null(不报错),reason 是降级的一行原因。
1207
+ // 版本面:没用插件时版本字段为 null(不报错),reason 是一行中性原因,hint 是「要不要装」的提示。
1161
1208
  sessionLockInfo: sessionLockInfo(),
1162
1209
  // pi 实测版本(后台探测);未探到时为 null。
1163
1210
  piVersion: piVersion.version,
@@ -1235,10 +1282,21 @@ export function createHubServer({ fetchJson } = {}) {
1235
1282
  const before = url.searchParams.get("before");
1236
1283
  const live = registry.get(sessionId);
1237
1284
  let source = "live";
1285
+ let fromFile = false;
1238
1286
  let all;
1239
1287
  if (live) {
1240
- const data = await live.command("get_messages");
1241
- all = normalizeMessages(data?.messages ?? []);
1288
+ // 优先读会话文件:pi 的 `get_messages` 消息**不带 id**,`normalizeMessages` 只能给
1289
+ // entryId=null ⇒ 客户端「编辑并发送」被 entryId 门控而消失,`nextBefore` 也为 null
1290
+ // 导致分页退化全量重拉(R11 真机 F2/F4)。文件里的 `rec.id` 才是 fork 认的 entryId。
1291
+ all = live.sessionFile ? readHistory(live.sessionFile) : [];
1292
+ if (all.length) {
1293
+ fromFile = true;
1294
+ } else {
1295
+ // 降级:文件还没落盘(刚 spawn、首轮未写、或读不到)时才退回 RPC。此时 entryId
1296
+ // 仍可能是 null,客户端会退回全量重拉 —— 可接受降级,不当错误。
1297
+ const data = await live.command("get_messages");
1298
+ all = normalizeMessages(data?.messages ?? []);
1299
+ }
1242
1300
  } else {
1243
1301
  const entry = findSession(sessionId);
1244
1302
  if (!entry) throw new HttpError(404, `unknown session ${sessionId}`, "unknown_session");
@@ -1254,6 +1312,8 @@ export function createHubServer({ fetchJson } = {}) {
1254
1312
  }
1255
1313
  return json(res, 200, {
1256
1314
  source,
1315
+ // 只在「live 会话但历史取自文件」时出现:source 仍表示会话是 live 还是纯文件会话。
1316
+ ...(fromFile ? { fromFile: true } : {}),
1257
1317
  messages: page.messages,
1258
1318
  hasMore: page.hasMore,
1259
1319
  total: page.total,
@@ -1381,6 +1441,8 @@ export function createHubServer({ fetchJson } = {}) {
1381
1441
  if (err.code === "session_locked") throw new HttpError(409, err.message, "session_locked");
1382
1442
  throw new HttpError(409, err.message, "prompt_rejected");
1383
1443
  });
1444
+ // 列表标题:未命名会话显示首条用户消息(只在还没有首条时写入)。
1445
+ session.noteUserText(text);
1384
1446
  return json(res, 200, { disposition: data?.disposition ?? null });
1385
1447
  }
1386
1448
 
@@ -1398,6 +1460,8 @@ export function createHubServer({ fetchJson } = {}) {
1398
1460
  if (err.code === "session_locked") throw new HttpError(409, err.message, "session_locked");
1399
1461
  throw new HttpError(409, err.message, "follow_up_rejected");
1400
1462
  });
1463
+ // 只有 follow-up 的首条消息也算「会话第一句话」(用户可能直接排队等 agent 说完)。
1464
+ session.noteUserText(text);
1401
1465
  return json(res, 200, { disposition: data?.disposition ?? null });
1402
1466
  }
1403
1467
 
@@ -12,20 +12,30 @@
12
12
  * 3. 只有能证明 owner 已死(pid 没了 / pid 被复用 / 关机重启)才回收,其余一律 fail-open
13
13
  * 降级不放宽互斥:抢到手的锁靠 mkdir 原子性保证,不依赖任何进程内状态。
14
14
  * 删掉的是插件的额外策略(yield 请求、paseo 轮次、follow 转发),那些不影响互斥。
15
+ *
16
+ * 落盘协议(目录命名 / owner.json 字段 / 判定取值)**不在本文件里定义**:
17
+ * 常量与路径计算统一来自 `lock-protocol.mjs`,与插件的差异由
18
+ * `test/lock-conformance.mjs` 用同一批夹具逐条比对(漂了就红)。
15
19
  */
16
20
  import fs from "node:fs";
17
21
  import os from "node:os";
18
22
  import path from "node:path";
19
23
  import crypto from "node:crypto";
24
+ import {
25
+ IDENTITY_KEY,
26
+ canonicalSessionPath,
27
+ lockDirFor as protocolLockDirFor,
28
+ ownerPath,
29
+ resolveAgentDir,
30
+ } from "./lock-protocol.mjs";
20
31
 
21
32
  const HOST = os.hostname();
22
33
 
23
34
  /** 与插件同一个 globalThis 键:真插件与 fallback 同进程加载时不会互相判成「别人」。 */
24
- const IDENTITY = Symbol.for("pi.session-lock.identity");
35
+ const IDENTITY = IDENTITY_KEY;
25
36
 
26
- export function resolveAgentDir(explicit) {
27
- return explicit || process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent");
28
- }
37
+ /** 锁根目录的解析口径与协议同源(生产代码在本文件内不再自带一份)。 */
38
+ export { resolveAgentDir };
29
39
 
30
40
  /** 逃生阀:`PI_SESSION_LOCK=off`(插件口径)/ `PI_HUB_NO_SESSION_LOCK=1` 都关锁。 */
31
41
  export function enabled() {
@@ -98,22 +108,12 @@ export function identity() {
98
108
  return g[IDENTITY];
99
109
  }
100
110
 
101
- /** 与插件逐字一致的锁目录:sha256(realpath(session)),文件还没落盘时退化为 path.resolve。 */
102
- export function lockDirFor(sessionFile, opts = {}) {
103
- const canonical = (() => {
104
- try {
105
- return fs.realpathSync(sessionFile);
106
- } catch {
107
- return path.resolve(sessionFile);
108
- }
109
- })();
110
- const hash = crypto.createHash("sha256").update(canonical).digest("hex");
111
- return path.join(resolveAgentDir(opts.agentDir), "session-locks", `${hash}.lock`);
112
- }
111
+ /** 与插件逐字一致的锁目录(协议实现只有 `lock-protocol.mjs` 一份)。 */
112
+ export const lockDirFor = protocolLockDirFor;
113
113
 
114
114
  export function readOwner(dir) {
115
115
  try {
116
- return JSON.parse(fs.readFileSync(path.join(dir, "owner.json"), "utf8"));
116
+ return JSON.parse(fs.readFileSync(ownerPath(dir), "utf8"));
117
117
  } catch {
118
118
  return null;
119
119
  }
@@ -161,14 +161,18 @@ export function claim(sessionFile, opts = {}) {
161
161
  pid: writer,
162
162
  startTicks: readStartTicks(writer),
163
163
  source: opts.source ?? "pi-hub-fallback",
164
- sessionFile,
164
+ // 与插件同口径:`idleYield` 是给桌面扩展看的「空闲就会让锁」标记(漏了它,桌面只能看到
165
+ // 「被占着」而不知道对面会松手,冲突提示就退化成硬拦)。
166
+ ...(opts.idleYield ? { idleYield: true } : {}),
167
+ // 与插件同口径:记规范绝对路径(相对路径在这里就消掉,读方不必知道调用者的 cwd)。
168
+ sessionFile: canonicalSessionPath(sessionFile),
165
169
  acquiredAt: new Date().toISOString(),
166
170
  };
167
171
  // hub 代管时 pid 是 pi 子进程:hub 被 SIGKILL 后子进程也走了,锁随之判死;
168
172
  // ownerPid 只为排查「谁认领的」。
169
173
  if (me.pid !== writer) owner.ownerPid = me.pid;
170
174
  try {
171
- fs.writeFileSync(path.join(dir, "owner.json"), `${JSON.stringify(owner, null, 2)}\n`, { mode: 0o600 });
175
+ fs.writeFileSync(ownerPath(dir), `${JSON.stringify(owner, null, 2)}\n`, { mode: 0o600 });
172
176
  } catch (error) {
173
177
  // 目录建了但 owner.json 写不进去:清掉,别留一把谁也认不出的锁。
174
178
  try {