pi-web-ui 0.104.4 → 0.105.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +1 -1
  3. package/README.zh-CN.md +2 -2
  4. package/bin/pi-web-ui.mjs +9 -3
  5. package/dist/server/agent-service-daemon.js +7 -7
  6. package/dist/server/agent-service.js +497 -109
  7. package/dist/server/approval-default-rules.js +15 -0
  8. package/dist/server/client-state.js +39 -2
  9. package/dist/server/dispatch-domain-handlers.js +35 -7
  10. package/dist/server/dsh/dsh-agent-service.js +88 -33
  11. package/dist/server/dsh/dsh-serialize.js +16 -1
  12. package/dist/server/ensure-bash.js +7 -2
  13. package/dist/server/file-transfer-routes.js +114 -1
  14. package/dist/server/index.js +347 -68
  15. package/dist/server/load-tools-tool.js +2 -1
  16. package/dist/server/locales.js +5 -0
  17. package/dist/server/markers/marker.js +28 -0
  18. package/dist/server/mcp-bridge.js +20 -6
  19. package/dist/server/pkg-info.js +69 -0
  20. package/dist/server/plugin-facilities.js +18 -9
  21. package/dist/server/plugin-manifest-validate.js +3 -0
  22. package/dist/server/plugin-updater.js +11 -5
  23. package/dist/server/plugins.js +3 -12
  24. package/dist/server/present-files-tool.js +47 -1
  25. package/dist/server/preset-fields.js +14 -0
  26. package/dist/server/preset-share.js +5 -12
  27. package/dist/server/prompt-composer.js +1 -1
  28. package/dist/server/remote-ssh-service.js +158 -5
  29. package/dist/server/serialize.js +15 -4
  30. package/dist/server/session-parser.js +138 -2
  31. package/dist/server/settings-service.js +19 -0
  32. package/dist/server/terminals.js +7 -1
  33. package/dist/server/text-quote.js +64 -2
  34. package/dist/server/tool-manager.js +10 -0
  35. package/dist/server/tool-prompts.js +1 -0
  36. package/dist/server/update-check.js +98 -24
  37. package/dist/server/workspace-snapshot.js +251 -13
  38. package/dist/server/worktree-service.js +262 -0
  39. package/dist/server/worktree-tool.js +173 -0
  40. package/package.json +3 -1
  41. package/plugin-sdk/index.d.ts +14 -1
  42. package/themes/zhujian-dark.css +16 -4
  43. package/themes/zhujian.css +16 -4
  44. package/themes/zhupi-dark.css +16 -4
  45. package/themes/zhupi.css +16 -4
  46. package/web/dist/assets/{TerminalPanel-B7x99tkg.js → TerminalPanel-Mk4laCAL.js} +1 -1
  47. package/web/dist/assets/index-BDLVjBeK.js +690 -0
  48. package/web/dist/assets/index-BQC6lADz.css +1 -0
  49. package/web/dist/index.html +21 -21
  50. package/web/dist/sw.js +1 -1
  51. package/web/dist/assets/index-DOrLcjLY.js +0 -680
  52. package/web/dist/assets/index-_H2BS7OX.css +0 -1
@@ -8,9 +8,10 @@
8
8
  * 从 agent-service.ts 抽出为独立模块。
9
9
  */
10
10
  import * as fsPromises from "node:fs/promises";
11
- import { join } from "node:path";
11
+ import { join, resolve } from "node:path";
12
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
12
13
  import { normalizePathKey } from "./client-state.js";
13
- import { MAX_SEARCH_TEXT_CHARS, readCwdFromSessionHeader } from "./session-search.js";
14
+ import { MAX_SEARCH_TEXT_CHARS, readCwdFromSessionHeader, piSessionsRoot } from "./session-search.js";
14
15
  /**
15
16
  * 快速轻量地从 SDK 会话目录中发现项目路径(仅读取会话文件的第一行头部获取 cwd,
16
17
  * 绝不使用 SessionManager.listAll 遍历解析全部会话文本,避免大历史时阻塞数秒到数十秒)。
@@ -260,3 +261,138 @@ export async function parseSessionInfoFast(filePath, fileMtime, withAllMessagesT
260
261
  return null;
261
262
  }
262
263
  }
264
+ /**
265
+ * 历史会话列表的 fork 父会话过滤:
266
+ * - `showForkedParents === true` 时保留全部会话(父会话与子会话同时显示);
267
+ * - `showForkedParents === false`(默认)时隐藏「已被后续分支派生、且该分支链上存在叶子会话」的父会话,
268
+ * 仅保留每条 fork 链最新的链尾叶子会话;
269
+ * - 若某条链因异常形成纯环(无叶子)或自环,环上节点保留而不整条隐藏。
270
+ */
271
+ export function filterForkedParentSessions(infos, showForkedParents = false) {
272
+ if (showForkedParents || infos.length <= 1)
273
+ return infos;
274
+ const byKey = new Map();
275
+ for (const info of infos) {
276
+ byKey.set(normalizePathKey(info.path), info);
277
+ }
278
+ const childrenOf = new Map();
279
+ for (const info of infos) {
280
+ if (typeof info.parentSessionPath !== "string" || !info.parentSessionPath)
281
+ continue;
282
+ const childKey = normalizePathKey(info.path);
283
+ const parentKey = normalizePathKey(info.parentSessionPath);
284
+ if (!parentKey || parentKey === childKey || !byKey.has(parentKey))
285
+ continue;
286
+ let set = childrenOf.get(parentKey);
287
+ if (!set) {
288
+ set = new Set();
289
+ childrenOf.set(parentKey, set);
290
+ }
291
+ set.add(childKey);
292
+ }
293
+ if (childrenOf.size === 0)
294
+ return infos;
295
+ const canReachLeaf = new Set();
296
+ for (const key of byKey.keys()) {
297
+ const children = childrenOf.get(key);
298
+ if (!children || children.size === 0) {
299
+ canReachLeaf.add(key);
300
+ }
301
+ }
302
+ let changed = true;
303
+ while (changed) {
304
+ changed = false;
305
+ for (const [parentKey, children] of childrenOf.entries()) {
306
+ if (canReachLeaf.has(parentKey))
307
+ continue;
308
+ for (const childKey of children) {
309
+ if (canReachLeaf.has(childKey)) {
310
+ canReachLeaf.add(parentKey);
311
+ changed = true;
312
+ break;
313
+ }
314
+ }
315
+ }
316
+ }
317
+ const kept = infos.filter((info) => {
318
+ const key = normalizePathKey(info.path);
319
+ const children = childrenOf.get(key);
320
+ if (!children || children.size === 0)
321
+ return true;
322
+ return !canReachLeaf.has(key);
323
+ });
324
+ return kept.length > 0 ? kept : infos;
325
+ }
326
+ /**
327
+ * 极速定位指定目录下最近修改的单个有效会话文件路径(用于 attach/恢复 判定,毫秒级返回)。
328
+ *
329
+ * 绝不使用 SessionManager.list 递归全量加载解析全部历史消息(大历史会有数百个文件、
330
+ * 几百兆 JSON 反序列化耗时数十秒,严重饿死 Node 事件循环)。
331
+ *
332
+ * 逻辑:
333
+ * 1. 扫描目录下的 .jsonl 文件;
334
+ * 2. 按 mtime 降序排序;
335
+ * 3. 逐个轻量探测(仅读首行 cwd,使用 readCwdFromSessionHeader);
336
+ * 4. 找到首个匹配 targetCwd(若指定)的有效会话文件后立即返回;若未指定 targetCwd 则直接返回最新文件的路径。
337
+ */
338
+ export async function findMostRecentSessionFileFast(sessionDir, targetCwd) {
339
+ try {
340
+ let targetDir = sessionDir;
341
+ let dirEntries = [];
342
+ try {
343
+ await fsPromises.access(targetDir);
344
+ dirEntries = await fsPromises.readdir(targetDir);
345
+ }
346
+ catch {
347
+ return undefined;
348
+ }
349
+ let jsonlFiles = dirEntries.filter((f) => f.endsWith(".jsonl"));
350
+ if (jsonlFiles.length === 0) {
351
+ // 如果 targetDir 下没有 .jsonl 文件,可能是工作区根目录(sessionBaseDir),尝试解析物理存储目录
352
+ try {
353
+ const extra = piSessionsRoot();
354
+ const resolvedStorageDir = extra ? resolve(extra) : SessionManager.create(targetDir).getSessionDir();
355
+ if (resolvedStorageDir && resolvedStorageDir !== targetDir) {
356
+ try {
357
+ const storageEntries = await fsPromises.readdir(resolvedStorageDir);
358
+ const storageJsonl = storageEntries.filter((f) => f.endsWith(".jsonl"));
359
+ if (storageJsonl.length > 0) {
360
+ targetDir = resolvedStorageDir;
361
+ jsonlFiles = storageJsonl;
362
+ }
363
+ }
364
+ catch { }
365
+ }
366
+ }
367
+ catch { }
368
+ }
369
+ if (jsonlFiles.length === 0)
370
+ return undefined;
371
+ const stats = await Promise.all(jsonlFiles.map(async (f) => {
372
+ const fp = join(targetDir, f);
373
+ try {
374
+ const st = await fsPromises.stat(fp);
375
+ return { path: fp, mtime: st.mtimeMs };
376
+ }
377
+ catch {
378
+ return null;
379
+ }
380
+ }));
381
+ const validStats = stats.filter((s) => s !== null);
382
+ validStats.sort((a, b) => b.mtime - a.mtime);
383
+ if (!targetCwd) {
384
+ return validStats[0]?.path;
385
+ }
386
+ const targetKey = normalizePathKey(targetCwd);
387
+ for (const item of validStats) {
388
+ const headerCwd = await readCwdFromSessionHeader(item.path);
389
+ if (headerCwd && normalizePathKey(headerCwd) === targetKey) {
390
+ return item.path;
391
+ }
392
+ }
393
+ return validStats[0]?.path;
394
+ }
395
+ catch {
396
+ return undefined;
397
+ }
398
+ }
@@ -323,6 +323,8 @@ export class SettingsService {
323
323
  toolsWrap: this.settings.toolsWrap,
324
324
  toolImagesEnabled: this.settings.toolImagesEnabled ?? true,
325
325
  keepRecentMessages: normalizeKeepRecentMessages(this.settings.keepRecentMessages),
326
+ showForkedParentSessions: this.settings.showForkedParentSessions ?? false,
327
+ retainFinishedConversations: this.settings.retainFinishedConversations ?? false,
326
328
  visionBridgeEnabled: this.settings.visionBridgeEnabled,
327
329
  visionBridgeModel: this.settings.visionBridgeModel,
328
330
  visionBridgePromptMode: this.settings.visionBridgePromptMode,
@@ -572,6 +574,17 @@ export class SettingsService {
572
574
  if (partial.keepRecentMessages !== undefined) {
573
575
  this.settings.keepRecentMessages = normalizeKeepRecentMessages(partial.keepRecentMessages);
574
576
  }
577
+ if (partial.retainFinishedConversations !== undefined) {
578
+ this.settings.retainFinishedConversations = Boolean(partial.retainFinishedConversations);
579
+ }
580
+ let sessionsFilterChanged = false;
581
+ if (partial.showForkedParentSessions !== undefined) {
582
+ const nextVal = Boolean(partial.showForkedParentSessions);
583
+ if (nextVal !== (this.settings.showForkedParentSessions ?? false)) {
584
+ sessionsFilterChanged = true;
585
+ }
586
+ this.settings.showForkedParentSessions = nextVal;
587
+ }
575
588
  // 编排模式 / skill 全文注入:before_agent_start 逐 run 实时读取(agent-service
576
589
  // composeInputs + 指导块追加),开关下一轮即生效,无需 reload runtime。
577
590
  if (partial.skillsFullText !== undefined) {
@@ -647,6 +660,8 @@ export class SettingsService {
647
660
  this.host.applyToolGating();
648
661
  this.host.stateStore.saveSettings(this.host.clientId, this.settings);
649
662
  this.push();
663
+ if (sessionsFilterChanged)
664
+ this.host.onSessionsFilterChanged?.();
650
665
  this.host.flushSnapshot();
651
666
  if (needsReload)
652
667
  await this.applyRuntime();
@@ -705,6 +720,7 @@ export class SettingsService {
705
720
  for (const k of Object.keys(patch))
706
721
  if (patch[k] === undefined)
707
722
  delete patch[k];
723
+ const prevShowForked = this.settings.showForkedParentSessions ?? false;
708
724
  this.settings = {
709
725
  ...this.settings,
710
726
  ...patch,
@@ -717,6 +733,9 @@ export class SettingsService {
717
733
  // 预设可能改了重试次数:即时注入(流式中延迟的 reload 之后还会由调用方重放)。
718
734
  this.host.applyRetryOverrides();
719
735
  this.push();
736
+ if ((this.settings.showForkedParentSessions ?? false) !== prevShowForked) {
737
+ this.host.onSessionsFilterChanged?.();
738
+ }
720
739
  // 预设带了工具开关:live 应用(reload 路径会重放,流式中延迟到 agent_end)。
721
740
  this.host.applyToolGating();
722
741
  await this.applyRuntime();
@@ -664,6 +664,12 @@ function resolveShell() {
664
664
  */
665
665
  function resolveBashShell() {
666
666
  if (isWindows) {
667
+ const explicit = process.env.PI_WEB_SHELL;
668
+ if (explicit && existsSync(explicit))
669
+ return { shell: explicit, args: ["-i"] };
670
+ const she = process.env.SHELL;
671
+ if (she && existsSync(she) && she.toLowerCase().includes("bash"))
672
+ return { shell: she, args: ["-i"] };
667
673
  const pf = process.env.ProgramFiles;
668
674
  const pf86 = process.env["ProgramFiles(x86)"];
669
675
  for (const cand of [
@@ -678,7 +684,7 @@ function resolveBashShell() {
678
684
  return { shell: busybox, args: ["-i"] };
679
685
  }
680
686
  const she = process.env.SHELL;
681
- if (she && she.endsWith("bash") && existsSync(she)) {
687
+ if (she && (she.endsWith("bash") || she.endsWith("bash.exe")) && existsSync(she)) {
682
688
  return { shell: she, args: ["-i"] };
683
689
  }
684
690
  return { shell: "bash", args: ["-i"] };
@@ -35,7 +35,34 @@ export function parseTextQuote(text) {
35
35
  export function formatQuotedPrompt(text, quotes) {
36
36
  return [text, ...quotes.map(formatTextQuote)].join("\n\n");
37
37
  }
38
- /** 排队项把引用与提问一起保存;展示时只拆分末尾的完整引用块。 */
38
+ function escapeAttr(value) {
39
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
40
+ }
41
+ /**
42
+ * 流式中排队/插队发送时把文本、文本附件(文件/目录/网页/对话引用/视觉桥)、
43
+ * 引用与图片标记格式化到同一条提示词中,避免使用 SDK 的 _pendingNextTurnMessages
44
+ * 造成排队消息丢失附件以及泄露到后续提问。
45
+ */
46
+ export function formatStreamingPrompt(text, textAsides = [], quotes = [], imageNames = []) {
47
+ const parts = [];
48
+ const trimmed = (text ?? "").trim();
49
+ if (trimmed)
50
+ parts.push(trimmed);
51
+ for (const img of imageNames) {
52
+ if (img)
53
+ parts.push(`<attached-image name="${escapeAttr(img)}" />`);
54
+ }
55
+ for (const aside of textAsides) {
56
+ const a = (aside ?? "").trim();
57
+ if (a)
58
+ parts.push(a);
59
+ }
60
+ for (const q of quotes) {
61
+ parts.push(formatTextQuote(q));
62
+ }
63
+ return parts.join("\n\n");
64
+ }
65
+ /** 排队项把引用与附件随提问一起保存;展示时拆分末尾的引用块与附件标记。 */
39
66
  export function splitQuotedPrompt(value) {
40
67
  let text = value;
41
68
  const quotes = [];
@@ -47,7 +74,42 @@ export function splitQuotedPrompt(value) {
47
74
  quotes.unshift(quote);
48
75
  text = text.slice(0, match.index);
49
76
  }
50
- return { text, quotes };
77
+ const attachments = [];
78
+ text = text.replace(/(?:^|\n\n)?<attached-image name="([^"]*)"\s*\/>/g, (_, name) => {
79
+ attachments.push({ type: "image", name });
80
+ return "";
81
+ });
82
+ text = text.replace(/(?:^|\n\n)?<file path="([^"]*)"(?:\s+size="[^"]*")?(?:\s+lines="(\d+)-(\d+)")?\s*\/>/g, (_, path, start, end) => {
83
+ const name = path.split(/[\\/]/).pop() ?? path;
84
+ const lines = start && end ? { start: Number(start), end: Number(end) } : undefined;
85
+ attachments.push({ type: "file", name, path, lines });
86
+ return "";
87
+ });
88
+ text = text.replace(/(?:^|\n\n)?<folder path="([^"]*)"\s*\/>/g, (_, path) => {
89
+ const name = path.split(/[\\/]/).pop() ?? path;
90
+ attachments.push({ type: "folder", name, path });
91
+ return "";
92
+ });
93
+ text = text.replace(/(?:^|\n\n)?<browser-page url="([^"]*)" title="([^"]*)">[\s\S]*?<\/browser-page>/g, (_, url, title) => {
94
+ attachments.push({ type: "page", name: title || url, url });
95
+ return "";
96
+ });
97
+ text = text.replace(/(?:^|\n\n)?<conversation-ref[^>]*title="([^"]*)"[^>]*>[\s\S]*?<\/conversation-ref>/g, (_, title) => {
98
+ attachments.push({ type: "conversation", name: title });
99
+ return "";
100
+ });
101
+ text = text.replace(/(?:^|\n\n)?<vision-bridge>[\s\S]*?<\/vision-bridge>/g, () => {
102
+ attachments.push({ type: "vision-bridge", name: "视觉转写" });
103
+ return "";
104
+ });
105
+ if (attachments.length > 0) {
106
+ text = text.trim();
107
+ }
108
+ return {
109
+ text,
110
+ quotes,
111
+ ...(attachments.length ? { attachments } : {}),
112
+ };
51
113
  }
52
114
  export function messageTextWithQuotes(message) {
53
115
  const text = message.content
@@ -83,6 +83,8 @@ export const LSP_TOOL_NAME = "lsp";
83
83
  export const MCP_MANAGE_TOOL_NAME = "mcp_manage";
84
84
  /** 隔离沙盒项目管理工具(定义见 sandbox-tool.ts):创建空白/导入型隔离沙盒、查看 diff、重置或销毁。 */
85
85
  export const SANDBOX_TOOL_NAME = "sandbox";
86
+ /** Git 工作树管理工具(定义见 worktree-tool.ts):创建/切换/清理工作树,保持多 PR 开发与界面工作区同步。 */
87
+ export const WORKTREE_TOOL_NAME = "worktree";
86
88
  /** QuickJS WASM 沙箱代码执行与批量调用工具(SDK 内置 codemode 扩展)。 */
87
89
  export const CODEMODE_TOOL_NAME = "codemode";
88
90
  /** 基于 BM25 算法的延迟工具检索与激活工具(SDK 内置 tool-search 扩展)。 */
@@ -280,6 +282,14 @@ export const AGENT_TOOL_CATALOG = [
280
282
  descKey: "sandboxEnabledDesc",
281
283
  offHintKey: "sandboxOffHint",
282
284
  },
285
+ {
286
+ name: WORKTREE_TOOL_NAME,
287
+ group: "other",
288
+ defaultOn: true,
289
+ dshVisible: false,
290
+ descKey: "toolsWorktreeDesc",
291
+ offHintKey: "toolsWorktreeOffHint",
292
+ },
283
293
  // todo_list 唯一例外:行不在「其他」组,固定在上面的 markers 分区(设置页循环
284
294
  // 跳过它,见 OTHER_AGENT_TOOLS;文案 key 照给,万一哪天搬家不用补)。
285
295
  {
@@ -20,6 +20,7 @@ export const BASH_PROMPT_SNIPPET = "run shell commands";
20
20
  /** 行为要点:只在「何时用/顺序/禁止」上说 description 没说的事。 */
21
21
  export const BASH_PROMPT_GUIDELINES = [
22
22
  "For interactive commands (REPLs, y/n prompts) set persist=true and drive them with terminal_input / terminal_key",
23
+ "Use the dedicated worktree tool instead of running 'git worktree' in bash to prevent unsynchronized workspace state",
23
24
  ];
24
25
  /** 参数 schema(含参数说明):三条执行路径共用,避免「分流后 schema 变陌生」。 */
25
26
  export const BASH_PARAMETERS = Type.Object({
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import { execFile } from "node:child_process";
12
12
  import { readdirSync, readFileSync, realpathSync, existsSync } from "node:fs";
13
- import { delimiter, dirname, join } from "node:path";
13
+ import { delimiter, dirname, isAbsolute, join } from "node:path";
14
14
  import { promisify } from "node:util";
15
15
  import { pick } from "./i18n.js";
16
16
  import { sdkCopies } from "./sdk-origin.js";
@@ -348,20 +348,8 @@ export async function defaultCheckGitExtension(installDir) {
348
348
  /** How long a pi probe result stays hot (mirrors ClientSession.piCliProbe). */
349
349
  const PI_PROBE_TTL_MS = 10_000;
350
350
  let piCoreProbe = null;
351
- /** Locate the pi CLI on PATH without spawning anything. */
352
- function piCliOnPath() {
353
- const dirs = (process.env.PATH ?? "").split(delimiter);
354
- for (const dir of dirs) {
355
- if (!dir)
356
- continue;
357
- const candidate = join(dir, "pi");
358
- if (existsSync(candidate))
359
- return candidate;
360
- }
361
- return null;
362
- }
363
351
  /** Read a pi-core package.json's version, or null when absent, not ours, or
364
- * unreadable. Shared by both resolution strategies below. */
352
+ * unreadable. Shared by all resolution strategies below. */
365
353
  function readPiCoreVersionAt(pkgPath) {
366
354
  if (!existsSync(pkgPath))
367
355
  return null;
@@ -409,15 +397,101 @@ function versionFromSymlinkWalk(bin) {
409
397
  return null;
410
398
  }
411
399
  /**
412
- * Read the pi core version from disk: resolve the `pi` bin on PATH, then try
413
- * the concrete global-npm layout first (Windows) and the POSIX symlink walk
414
- * second. Exported for unit tests — defaultProbePiCore memoizes its result.
400
+ * Attempt to resolve the installed @earendil-works/pi-coding-agent package version
401
+ * from a candidate `pi` executable/script path.
415
402
  */
416
- export function readPiCoreVersionFromDisk() {
417
- const bin = piCliOnPath();
418
- if (!bin)
419
- return null;
420
- return versionFromSiblingNodeModules(bin) ?? versionFromSymlinkWalk(bin);
403
+ function versionFromCandidate(bin) {
404
+ // 1. Sibling layout: <binDir>/node_modules/<pkg>/package.json
405
+ const sib = versionFromSiblingNodeModules(bin);
406
+ if (sib)
407
+ return sib;
408
+ // 2. .bin layout: if bin is inside a `.bin` folder, check sibling of `.bin` (which is node_modules)
409
+ const dir = dirname(bin);
410
+ const parent = dirname(dir);
411
+ if (dir.endsWith(".bin") || dir.endsWith(".bin\\") || dir.endsWith(".bin/")) {
412
+ const parentNm = readPiCoreVersionAt(join(parent, ...PI_CORE_PACKAGE.split("/"), "package.json"));
413
+ if (parentNm)
414
+ return parentNm;
415
+ }
416
+ // 3. Wrapper script content inspection (Windows .cmd / .ps1 or shell wrapper)
417
+ try {
418
+ const head = readFileSync(bin, "utf8").slice(0, 4096);
419
+ const m = head.match(/[^\r\n"']*@earendil-works[/\\]pi-coding-agent[^\r\n"']*/);
420
+ if (m) {
421
+ const matchedPath = m[0].trim().replace(/%~?dp0%?[/\\]/gi, "");
422
+ const targetDir = isAbsolute(matchedPath) ? matchedPath : join(dir, matchedPath);
423
+ let cur = targetDir;
424
+ for (let i = 0; i < 5; i++) {
425
+ const pj = join(cur, "package.json");
426
+ const v = readPiCoreVersionAt(pj);
427
+ if (v)
428
+ return v;
429
+ const p = dirname(cur);
430
+ if (p === cur)
431
+ break;
432
+ cur = p;
433
+ }
434
+ }
435
+ }
436
+ catch {
437
+ /* ignore */
438
+ }
439
+ // 4. POSIX symlink walk
440
+ const sym = versionFromSymlinkWalk(bin);
441
+ if (sym)
442
+ return sym;
443
+ // 5. Global prefix layout: <binDir>/../lib/node_modules/<pkg> or <binDir>/../node_modules/<pkg>
444
+ const libNm = readPiCoreVersionAt(join(parent, "lib", "node_modules", ...PI_CORE_PACKAGE.split("/"), "package.json"));
445
+ if (libNm)
446
+ return libNm;
447
+ const upNm = readPiCoreVersionAt(join(parent, "node_modules", ...PI_CORE_PACKAGE.split("/"), "package.json"));
448
+ if (upNm)
449
+ return upNm;
450
+ return null;
451
+ }
452
+ /**
453
+ * Read the pi core version from disk: resolve the `pi` bin on PATH (traversing all
454
+ * matches until a valid version is found), then falling back to standard global
455
+ * prefix directories.
456
+ */
457
+ export function readPiCoreVersionFromDisk(env = process.env) {
458
+ const rawPath = env.PATH ?? "";
459
+ const dirs = rawPath.split(delimiter).filter(Boolean);
460
+ const isWin = process.platform === "win32";
461
+ const names = isWin ? ["pi.cmd", "pi.exe", "pi.ps1", "pi"] : ["pi"];
462
+ for (const dir of dirs) {
463
+ for (const name of names) {
464
+ const candidate = join(dir, name);
465
+ if (!existsSync(candidate))
466
+ continue;
467
+ const version = versionFromCandidate(candidate);
468
+ if (version)
469
+ return version;
470
+ }
471
+ }
472
+ // Fallback to global prefix directories (npm global prefix, pnpm, etc.)
473
+ const home = env.HOME || env.USERPROFILE || "";
474
+ const prefix = env.npm_config_prefix || env.PREFIX;
475
+ const prefixDirs = [];
476
+ if (prefix)
477
+ prefixDirs.push(prefix);
478
+ if (home)
479
+ prefixDirs.push(join(home, ".npm-global"));
480
+ if (env.APPDATA)
481
+ prefixDirs.push(join(env.APPDATA, "npm"));
482
+ if (env.PNPM_HOME)
483
+ prefixDirs.push(env.PNPM_HOME);
484
+ if (env.LOCALAPPDATA)
485
+ prefixDirs.push(join(env.LOCALAPPDATA, "pnpm", "global"));
486
+ for (const p of prefixDirs) {
487
+ const v1 = readPiCoreVersionAt(join(p, "node_modules", ...PI_CORE_PACKAGE.split("/"), "package.json"));
488
+ if (v1)
489
+ return v1;
490
+ const v2 = readPiCoreVersionAt(join(p, "lib", "node_modules", ...PI_CORE_PACKAGE.split("/"), "package.json"));
491
+ if (v2)
492
+ return v2;
493
+ }
494
+ return null;
421
495
  }
422
496
  /**
423
497
  * Default pi core probe: run the globally installed `pi --version`, memoized
@@ -426,12 +500,12 @@ export function readPiCoreVersionFromDisk() {
426
500
  * instead of spawning `pi --version`. FORK-FREE by design — see the note on
427
501
  * defaultProbePiCore.
428
502
  */
429
- export function defaultProbePiCore() {
503
+ export function defaultProbePiCore(env = process.env) {
430
504
  const now = Date.now();
431
505
  const cached = piCoreProbe;
432
506
  if (cached && now - cached.at < PI_PROBE_TTL_MS)
433
507
  return cached.version;
434
- const version = readPiCoreVersionFromDisk();
508
+ const version = readPiCoreVersionFromDisk(env);
435
509
  piCoreProbe = { at: now, version };
436
510
  return version;
437
511
  }