pi-web-ui 0.104.3 → 0.105.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +56 -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 +513 -115
  7. package/dist/server/approval-default-rules.js +15 -0
  8. package/dist/server/client-state.js +42 -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 +30 -5
  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-VjlOOAig.js → TerminalPanel-B9exeXrl.js} +1 -1
  47. package/web/dist/assets/index-BQC6lADz.css +1 -0
  48. package/web/dist/assets/index-D79IKG33.js +690 -0
  49. package/web/dist/index.html +21 -21
  50. package/web/dist/sw.js +1 -1
  51. package/web/dist/assets/index-5SITmQd_.js +0 -680
  52. package/web/dist/assets/index-D9wTa3O-.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
+ }
@@ -9,7 +9,7 @@
9
9
  import { existsSync, readdirSync, readFileSync } from "node:fs";
10
10
  import { basename, dirname, join } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
- import { extensionKey, normalizeBgCleanupMinutes, normalizeDisabledPluginTools, normalizeRetryMaxAttempts, normalizeKeepRecentMessages, normalizeSkillList, normalizeToolWatchdogTimeoutMs, normalizeUiLayout, settingsPresetToUi, } from "./client-state.js";
12
+ import { extensionKey, isInternalExtension, normalizeBgCleanupMinutes, normalizeDisabledPluginTools, normalizeRetryMaxAttempts, normalizeKeepRecentMessages, normalizeSkillList, normalizeToolWatchdogTimeoutMs, normalizeUiLayout, settingsPresetToUi, } from "./client-state.js";
13
13
  import { normalizeSoftCapByModel, normalizeSoftCapTokens } from "./soft-cap.js";
14
14
  import { findVisionModels, SYSTEM_PROMPT } from "./vision-bridge.js";
15
15
  import { COMMITMSG_SYSTEM_PROMPT } from "./scm-commitmsg.js";
@@ -116,6 +116,8 @@ export class SettingsService {
116
116
  extensionStillOnDisk(id) {
117
117
  if (!id)
118
118
  return false;
119
+ if (isInternalExtension({ path: id }))
120
+ return false;
119
121
  if (id.startsWith("npm:")) {
120
122
  const pkg = id.slice(4);
121
123
  if (!pkg)
@@ -165,7 +167,8 @@ export class SettingsService {
165
167
  let loadedExtNames = null;
166
168
  try {
167
169
  const loadedSkills = this.host.getSession().resourceLoader.getSkills().skills;
168
- const loadedExts = this.host.getSession().resourceLoader.getExtensions().extensions;
170
+ const allLoadedExts = this.host.getSession().resourceLoader.getExtensions().extensions;
171
+ const loadedExts = allLoadedExts.filter((e) => !isInternalExtension(e));
169
172
  loadedSkillNames = new Set(loadedSkills.map((s) => s.name));
170
173
  loadedExtNames = new Set(loadedExts.map((e) => extensionKey(e)));
171
174
  // Prune entries that no longer exist on disk AND aren't disabled
@@ -174,7 +177,7 @@ export class SettingsService {
174
177
  const keepSkills = new Set([...loadedSkills.map((s) => s.name), ...this.settings.disabledSkills]);
175
178
  const keepExts = new Set([
176
179
  ...loadedExts.map((e) => extensionKey(e)),
177
- ...this.settings.disabledExtensions,
180
+ ...this.settings.disabledExtensions.filter((id) => !isInternalExtension({ path: id })),
178
181
  ]);
179
182
  // eslint-disable-next-line unicorn/no-useless-spread -- snapshot: handlers may unsubscribe mid-emit
180
183
  for (const name of [...this.knownSkills.keys()]) {
@@ -183,7 +186,7 @@ export class SettingsService {
183
186
  }
184
187
  // eslint-disable-next-line unicorn/no-useless-spread -- snapshot: handlers may unsubscribe mid-emit
185
188
  for (const id of [...this.knownExtensions.keys()]) {
186
- if (!keepExts.has(id))
189
+ if (!keepExts.has(id) || isInternalExtension({ path: id }))
187
190
  this.knownExtensions.delete(id);
188
191
  }
189
192
  for (const s of loadedSkills) {
@@ -237,7 +240,7 @@ export class SettingsService {
237
240
  // 从禁用记录里剔除并持久化 —— 否则卸载过的扩展以“已禁用”灰条永生(issue #192)。
238
241
  // loadedExtNames 非 null 即 session 就绪;取不到(catch 分支)时保守跳过。
239
242
  if (loadedExtNames !== null) {
240
- const staleExts = this.settings.disabledExtensions.filter((id) => !loadedExtNames.has(id) && !this.extensionStillOnDisk(id));
243
+ const staleExts = this.settings.disabledExtensions.filter((id) => isInternalExtension({ path: id }) || (!loadedExtNames.has(id) && !this.extensionStillOnDisk(id)));
241
244
  if (staleExts.length > 0) {
242
245
  this.settings.disabledExtensions = this.settings.disabledExtensions.filter((n) => !staleExts.includes(n));
243
246
  this.host.stateStore.saveSettings(this.host.clientId, {
@@ -255,6 +258,8 @@ export class SettingsService {
255
258
  // (上面的 stale 清理已把卸载项移出禁用记录;这里再按磁盘挡一次,
256
259
  // session 未就绪跳过清理时也不复活幽灵。)
257
260
  for (const id of this.settings.disabledExtensions) {
261
+ if (isInternalExtension({ path: id }))
262
+ continue;
258
263
  if (!this.knownExtensions.has(id)) {
259
264
  if (!this.extensionStillOnDisk(id))
260
265
  continue;
@@ -273,6 +278,7 @@ export class SettingsService {
273
278
  .map((s) => ({ ...s, enabled: !reviewDisabledSkills.has(s.name) }))
274
279
  .sort((a, b) => a.name.localeCompare(b.name));
275
280
  const extensions = [...this.knownExtensions.values()]
281
+ .filter((e) => !isInternalExtension({ path: e.id }) && !isInternalExtension({ path: e.path }))
276
282
  .map((e) => ({ ...e, enabled: !disabledExts.has(e.id) }))
277
283
  .sort((a, b) => a.name.localeCompare(b.name));
278
284
  // 统一工具开关是单源(disabledAgentTools),遗留三开关推送时推导,保证面板一致。
@@ -317,6 +323,8 @@ export class SettingsService {
317
323
  toolsWrap: this.settings.toolsWrap,
318
324
  toolImagesEnabled: this.settings.toolImagesEnabled ?? true,
319
325
  keepRecentMessages: normalizeKeepRecentMessages(this.settings.keepRecentMessages),
326
+ showForkedParentSessions: this.settings.showForkedParentSessions ?? false,
327
+ retainFinishedConversations: this.settings.retainFinishedConversations ?? false,
320
328
  visionBridgeEnabled: this.settings.visionBridgeEnabled,
321
329
  visionBridgeModel: this.settings.visionBridgeModel,
322
330
  visionBridgePromptMode: this.settings.visionBridgePromptMode,
@@ -566,6 +574,17 @@ export class SettingsService {
566
574
  if (partial.keepRecentMessages !== undefined) {
567
575
  this.settings.keepRecentMessages = normalizeKeepRecentMessages(partial.keepRecentMessages);
568
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
+ }
569
588
  // 编排模式 / skill 全文注入:before_agent_start 逐 run 实时读取(agent-service
570
589
  // composeInputs + 指导块追加),开关下一轮即生效,无需 reload runtime。
571
590
  if (partial.skillsFullText !== undefined) {
@@ -641,6 +660,8 @@ export class SettingsService {
641
660
  this.host.applyToolGating();
642
661
  this.host.stateStore.saveSettings(this.host.clientId, this.settings);
643
662
  this.push();
663
+ if (sessionsFilterChanged)
664
+ this.host.onSessionsFilterChanged?.();
644
665
  this.host.flushSnapshot();
645
666
  if (needsReload)
646
667
  await this.applyRuntime();
@@ -699,6 +720,7 @@ export class SettingsService {
699
720
  for (const k of Object.keys(patch))
700
721
  if (patch[k] === undefined)
701
722
  delete patch[k];
723
+ const prevShowForked = this.settings.showForkedParentSessions ?? false;
702
724
  this.settings = {
703
725
  ...this.settings,
704
726
  ...patch,
@@ -711,6 +733,9 @@ export class SettingsService {
711
733
  // 预设可能改了重试次数:即时注入(流式中延迟的 reload 之后还会由调用方重放)。
712
734
  this.host.applyRetryOverrides();
713
735
  this.push();
736
+ if ((this.settings.showForkedParentSessions ?? false) !== prevShowForked) {
737
+ this.host.onSessionsFilterChanged?.();
738
+ }
714
739
  // 预设带了工具开关:live 应用(reload 路径会重放,流式中延迟到 agent_end)。
715
740
  this.host.applyToolGating();
716
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
  }