pi-web-ui 0.104.2 → 0.104.4

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.
@@ -6,10 +6,11 @@
6
6
  * - 支持「临时沙盒(用完即删)」与「永久沙盒(持久化保留,随时一键转正)」;
7
7
  * - 支持一键重置(还原到初始空白或重新从源项目同步)、另存为正式项目(promote)、将修改写回源项目(applyToSource)、彻底销毁(destroy)。
8
8
  *
9
- * 2. 沙盒硬围栏(Hard Jail Gate):
9
+ * 2. 沙盒安全围栏(Sandbox Jail Gate):
10
10
  * - 当会话处于受管沙盒目录内时,所有文件写入/编辑/补丁(write/edit/edit_soft/patch)必须严格落在
11
11
  * `sandbox.path` 内部(含祖先目录 realpath 校验,防软链逃逸),越界直接硬拒绝(不走审批放行);
12
- * - 终端命令(bash)严禁直接引用源项目路径(`sourcePath`)或越过沙盒根向外 cd;
12
+ * - 终端命令(bash)采用启发式拦截(禁止直接引用源项目路径 `sourcePath`、拦截越界 cd、输出重定向、越界写删命令与系统特权命令等);
13
+ * 请注意:沙盒基于工作区副本与工具调用层校验,未采用内核命名空间/容器级物理隔离,bash 终端拦截为尽力而为的启发式防护,非绝对安全边界;
13
14
  * - 外部副作用工具(sftp 远端写/删/执行、mail 发信/删信)在沙盒内默认拦截。
14
15
  */
15
16
  import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
@@ -137,6 +138,14 @@ export function extractPatchTargetPaths(patchText) {
137
138
  const mUnified = line.match(/^(?:---|\+\+\+)\s+(?:[ab]\/)?([^\t\r\n]+)$/);
138
139
  if (mUnified?.[1] && mUnified[1] !== "/dev/null") {
139
140
  paths.push(mUnified[1].trim());
141
+ continue;
142
+ }
143
+ // hashline 格式段头(本仓 patch 工具实际消费的唯一格式):[path#TAG] / [path]。
144
+ // 不识别的话 hashline 补丁提取出 0 个目标 → 围栏检查整体空转,patch 路径
145
+ // 只剩 hashline-engine 的词法 cwd 限制(无 realpath,沙盒内软链可逃逸)
146
+ const mHashline = rawLine.match(/^\s*\[([^#\]]+)(?:#[0-9a-fA-F]{4})?\]\s*$/);
147
+ if (mHashline?.[1]?.trim()) {
148
+ paths.push(mHashline[1].trim());
140
149
  }
141
150
  }
142
151
  return paths;
@@ -201,15 +210,83 @@ export function evaluateSandboxJail(sandbox, toolName, params, cwd) {
201
210
  };
202
211
  }
203
212
  }
204
- // 3b. 当 cwd 就是沙盒根时,拦截 `cd ..` 逃出沙盒根
205
- if (normalizePathKey(cwd) === normalizePathKey(sbxPath)) {
206
- if (/(?:^|[;&|\n]\s*)cd\s+\.\.(?:[\\/\s;&|]|$)/.test(cmd)) {
213
+ // 3b. 拦截通过 cd 跳出沙盒边界(裸 cd 跳 $HOME、cd ~、cd ..、或 cd 到沙盒外绝对路径,支持括号子 shell 与带引号/变量路径)
214
+ for (const m of cmd.matchAll(/(?:^|[;&|\n(`]\s*)cd(?:\s+([^;&|\n)`]+))?(?=$|[;&|\n)`])/g)) {
215
+ const rawArg = (m[1] ?? "").trim().replace(/^["']|["']$/g, "");
216
+ if (!rawArg ||
217
+ rawArg === "~" ||
218
+ rawArg.startsWith("~/") ||
219
+ rawArg.startsWith("~\\") ||
220
+ /^\$(?:HOME|USERPROFILE)\b|^\$\{(?:HOME|USERPROFILE)\}|^%USERPROFILE%/i.test(rawArg) ||
221
+ /\$(?:HOME|USERPROFILE)|\$\{(?:HOME|USERPROFILE)\}/i.test(rawArg)) {
222
+ return {
223
+ reason: `【沙盒安全隔离拦截】沙盒内禁止执行跳回用户主目录的 "cd ${rawArg || "~"}" 命令,请保持在沙盒目录(${sbxPath})内操作。`,
224
+ reasonEn: `[Sandbox Isolation Blocked] Escaping to the user home directory via "cd ${rawArg || "~"}" is forbidden in sandbox mode; stay within "${sbxPath}".`,
225
+ };
226
+ }
227
+ if (rawArg !== "-" && !rawArg.startsWith("$") && !isStrictlyInsideSandbox(rawArg, cwd, sbxPath)) {
228
+ return {
229
+ reason: `【沙盒安全隔离拦截】禁止通过 "cd ${rawArg}" 跳出沙盒根目录(${sbxPath})。`,
230
+ reasonEn: `[Sandbox Isolation Blocked] Escaping the sandbox root (${sbxPath}) via "cd ${rawArg}" is forbidden.`,
231
+ };
232
+ }
233
+ }
234
+ // 3c. 拦截重定向(> / >>)写入沙盒外路径(/dev/null 除外)
235
+ for (const m of cmd.matchAll(/(?:^|[^0-9>&])>>?\s*([^\s;&|>'"]+|"[^"]+"|'[^']+')/g)) {
236
+ const target = (m[1] ?? "").trim().replace(/^["']|["']$/g, "");
237
+ if (!target || target === "/dev/null" || target === "NUL" || target.startsWith("&"))
238
+ continue;
239
+ if (!isStrictlyInsideSandbox(target, cwd, sbxPath)) {
207
240
  return {
208
- reason: `【沙盒安全隔离拦截】当前位于沙盒根目录(${sbxPath}),禁止通过 "cd .." 跳出沙盒边界。`,
209
- reasonEn: `[Sandbox Isolation Blocked] Currently at sandbox root (${sbxPath}); escaping the sandbox boundary via "cd .." is forbidden.`,
241
+ reason: `【沙盒安全隔离拦截】禁止将输出重定向写入沙盒目录(${sbxPath})以外的路径:"${target}"。`,
242
+ reasonEn: `[Sandbox Isolation Blocked] Redirecting output to a path outside the sandbox directory (${sbxPath}) is forbidden: "${target}".`,
210
243
  };
211
244
  }
212
245
  }
246
+ // 3d. 拦截系统特权命令与全局包安装污染宿主机
247
+ if (/(?:^|[;&|\n]\s*)(?:sudo|su|mkfs|format|fdisk|diskpart|reg\s+(?:add|delete)|schtasks|systemctl|launchctl|sc\s+(?:create|delete|stop))\b/i.test(cmd) ||
248
+ /\b(?:npm\s+(?:i|install|add|un|uninstall)\s+(?:[^;&|\n]*\s)?(?:-g|--global)\b|pnpm\s+(?:add|remove)\s+(?:[^;&|\n]*\s)?(?:-g|--global)\b|yarn\s+global\b)/i.test(cmd)) {
249
+ return {
250
+ reason: `【沙盒安全隔离拦截】沙盒内禁止执行宿主机系统级管理命令或全局包安装(-g/--global),以保护宿主系统环境。`,
251
+ reasonEn: `[Sandbox Isolation Blocked] System administration commands and global package installations (-g/--global) are forbidden in sandbox mode to protect the host environment.`,
252
+ };
253
+ }
254
+ // 3e. 拦截文件修改/删除命令(rm/del/mv/cp/chmod/touch/mkdir/sed -i/tee 等)指向 ..、~、$HOME 或沙盒外绝对路径
255
+ const mutatingCmdRe = /(?:^|[;&|\n(`]\s*)(?:rm|del|erase|rmdir|rd|mv|move|cp|copy|xcopy|robocopy|ln|mklink|chmod|chown|touch|mkdir|tee|dd|Remove-Item|Move-Item|Copy-Item|Set-Content|Add-Content|Out-File|sed\s+-[a-zA-Z]*i)\b([^;&|\n)]*)/gi;
256
+ for (const m of cmd.matchAll(mutatingCmdRe)) {
257
+ const argsTail = (m[1] ?? "").trim();
258
+ const tokens = argsTail.match(/(?:"[^"]*"|'[^']*'|\S+)/g) ?? [];
259
+ for (const rawTok of tokens) {
260
+ const tok = rawTok.replace(/^["']|["']$/g, "");
261
+ if (!tok || tok.startsWith("-") || tok === "/dev/null")
262
+ continue;
263
+ if (tok === "~" ||
264
+ tok.startsWith("~/") ||
265
+ tok.startsWith("~\\") ||
266
+ /^\$(?:HOME|USERPROFILE)\b|^%USERPROFILE%/i.test(tok) ||
267
+ tok === ".." ||
268
+ tok.startsWith("../") ||
269
+ tok.startsWith("..\\") ||
270
+ tok.includes("/../") ||
271
+ tok.includes("\\..\\")) {
272
+ if (!isStrictlyInsideSandbox(tok, cwd, sbxPath)) {
273
+ return {
274
+ reason: `【沙盒安全隔离拦截】检测到命令尝试操作沙盒外部或宿主系统路径("${tok}"),已被硬围栏阻断。`,
275
+ reasonEn: `[Sandbox Isolation Blocked] Command attempted to mutate a path outside the sandbox or on the host system ("${tok}") and was blocked.`,
276
+ };
277
+ }
278
+ }
279
+ // 绝对路径(POSIX /... 或 Windows C:\...)且不在沙盒根内
280
+ if ((tok.startsWith("/") && !tok.startsWith("//")) || /^[a-zA-Z]:[\\/]/.test(tok)) {
281
+ if (!isStrictlyInsideSandbox(tok, cwd, sbxPath)) {
282
+ return {
283
+ reason: `【沙盒安全隔离拦截】检测到命令尝试修改沙盒目录(${sbxPath})以外的系统/外部路径("${tok}"),已被硬围栏阻断。`,
284
+ reasonEn: `[Sandbox Isolation Blocked] Command attempted to modify an external/system path outside the sandbox ("${tok}") and was blocked.`,
285
+ };
286
+ }
287
+ }
288
+ }
289
+ }
213
290
  return null;
214
291
  }
215
292
  // 4. 外部副作用工具:sftp / mail
@@ -446,6 +523,10 @@ export class SandboxManager {
446
523
  * 创建一个新沙盒工作区(空白或从 `sourcePath` 导入隔离副本)。
447
524
  */
448
525
  async create(opts) {
526
+ // 先同步共享注册表:每个 ClientSession/DshClientSession 各持一个管理器实例、
527
+ // 共享同一 registry.json——不 ensureFresh 的话并发创建会用陈旧内存覆盖写回,
528
+ // 丢掉其他客户端刚建的沙盒条目(getByCwd 找不到 → jail 围栏静默失效)
529
+ this.ensureFresh();
449
530
  const rawSource = opts.sourcePath?.trim();
450
531
  let resolvedSource;
451
532
  if (rawSource) {
@@ -464,6 +545,11 @@ export class SandboxManager {
464
545
  if (isSameOrSubpath(this.sandboxesRoot, abs)) {
465
546
  throw new Error(`Refusing to import a parent directory of sandboxes root: ${abs}`);
466
547
  }
548
+ // 沙盒根**内部**的目录也不允许当源:会造出嵌套沙盒(源被另一沙盒的
549
+ // destroy/reset 抽掉、apply_to_source 把改动写进另一个沙盒)
550
+ if (isSameOrSubpath(abs, this.sandboxesRoot)) {
551
+ throw new Error(`Refusing to import a directory inside the sandboxes root: ${abs}`);
552
+ }
467
553
  // 若选中的 source 本身已经是某个沙盒,而且该沙盒记录了原始 sourcePath,保留最外层真实路径或直接复制该沙盒内容
468
554
  resolvedSource = toWirePath(abs);
469
555
  }
@@ -498,8 +584,23 @@ export class SandboxManager {
498
584
  }
499
585
  await mkdir(info.path, { recursive: true });
500
586
  const entries = await readdir(info.path);
587
+ // 逐条目容错:Windows 下沙盒内进程未停(npm run dev 的 node.exe 持有句柄)
588
+ // 会让单个条目 EBUSY/EPERM——整体抛错会留下半清空状态;能删的先删,
589
+ // 全部失败才抛
590
+ const failures = [];
501
591
  for (const entry of entries) {
502
- await rm(join(info.path, entry), { recursive: true, force: true, maxRetries: 3 });
592
+ try {
593
+ await rm(join(info.path, entry), { recursive: true, force: true, maxRetries: 3 });
594
+ }
595
+ catch {
596
+ failures.push(entry);
597
+ }
598
+ }
599
+ if (failures.length === entries.length && entries.length > 0) {
600
+ throw new Error(`Failed to clear sandbox contents (all ${failures.length} entries busy): ${failures.slice(0, 5).join(", ")}`);
601
+ }
602
+ if (failures.length > 0) {
603
+ console.warn(`[sandbox] reset: ${failures.length}/${entries.length} entries could not be removed (busy): ${failures.slice(0, 5).join(", ")}`);
503
604
  }
504
605
  let copyStats = { copiedFiles: 0, skippedFiles: 0 };
505
606
  if (info.sourcePath && existsSync(info.sourcePath)) {
@@ -565,7 +666,7 @@ export class SandboxManager {
565
666
  };
566
667
  }
567
668
  /**
568
- * 将导入型沙盒中的修改写回源项目(保留源项目 `.git` 与重型依赖目录,仅同步工作区文件变更)。
669
+ * 将导入型沙盒中的修改写回源项目(保留源项目 `.git` 与重型依赖目录,同步工作区文件变更并清理已删除文件)。
569
670
  */
570
671
  async applyToSource(idOrPath) {
571
672
  const info = this.get(idOrPath) ?? this.getByCwd(idOrPath);
@@ -575,11 +676,50 @@ export class SandboxManager {
575
676
  if (!info.sourcePath || !existsSync(info.sourcePath)) {
576
677
  throw new Error("This sandbox has no valid source project to apply changes back to");
577
678
  }
679
+ // 1. 先通过 diff 计算出被删除的文件列表,以便同步清理源项目中的对应文件
680
+ const diff = await this.diffWithSource(info.id);
681
+ let deletedFiles = 0;
682
+ for (const rel of diff.deleted) {
683
+ // 安全校验:严格限制在 sourcePath 内,且避开 .git 与重型忽略目录
684
+ if (!rel ||
685
+ rel === ".git" ||
686
+ rel.startsWith(".git/") ||
687
+ rel.startsWith(".git\\") ||
688
+ !isStrictlyInsideSandbox(rel, info.sourcePath, info.sourcePath)) {
689
+ continue;
690
+ }
691
+ const targetFile = join(info.sourcePath, rel);
692
+ if (existsSync(targetFile)) {
693
+ try {
694
+ await rm(targetFile, { force: true });
695
+ deletedFiles++;
696
+ // 尝试顺带清理变空的父目录(直到 sourcePath,不删 sourcePath 自身)
697
+ let parent = dirname(targetFile);
698
+ while (parent &&
699
+ isSameOrSubpath(parent, info.sourcePath) &&
700
+ normalizePathKey(parent) !== normalizePathKey(info.sourcePath)) {
701
+ const remaining = await readdir(parent).catch(() => ["non-empty"]);
702
+ if (remaining.length === 0) {
703
+ await rm(parent, { recursive: true, force: true }).catch(() => { });
704
+ parent = dirname(parent);
705
+ }
706
+ else {
707
+ break;
708
+ }
709
+ }
710
+ }
711
+ catch {
712
+ // 忽略单个文件清理失败
713
+ }
714
+ }
715
+ }
716
+ // 2. 将沙盒工作区的文件复制覆盖回源项目
578
717
  const stats = await copyWorkspaceTree(info.path, info.sourcePath, { skipGitDir: true });
579
718
  return {
580
719
  sandbox: info,
581
720
  sourcePath: info.sourcePath,
582
721
  copiedFiles: stats.copiedFiles,
722
+ deletedFiles,
583
723
  };
584
724
  }
585
725
  /**
@@ -12,6 +12,8 @@
12
12
  * - destroy: 销毁指定沙盒并回收磁盘空间。
13
13
  */
14
14
  import { Type } from "typebox";
15
+ import { existsSync } from "node:fs";
16
+ import { homedir } from "node:os";
15
17
  import { pick } from "./i18n.js";
16
18
  export const SANDBOX_TOOL_NAME = "sandbox";
17
19
  const SandboxParameters = Type.Object({
@@ -254,14 +256,29 @@ export function makeSandboxTool(host, getLang) {
254
256
  }
255
257
  // 强制触发人工审批:写回源项目会修改真实工作区文件,绝不允许静默执行
256
258
  if (host.askApproval) {
257
- const reasonZh = `将沙盒「${diff.sandbox.name}」的改动(新增 ${diff.added.length}、修改 ${diff.modified.length} 个文件)写回源项目 ${diff.sourcePath}`;
258
- const reasonEn = `Sync changes from sandbox "${diff.sandbox.name}" (+${diff.added.length} added, ~${diff.modified.length} modified) back to source project ${diff.sourcePath}`;
259
+ const diffSummaryZh = [
260
+ diff.added.length > 0 ? `新增 ${diff.added.length}` : "",
261
+ diff.modified.length > 0 ? `修改 ${diff.modified.length}` : "",
262
+ diff.deleted.length > 0 ? `删除 ${diff.deleted.length}` : "",
263
+ ]
264
+ .filter(Boolean)
265
+ .join("、");
266
+ const diffSummaryEn = [
267
+ diff.added.length > 0 ? `+${diff.added.length} added` : "",
268
+ diff.modified.length > 0 ? `~${diff.modified.length} modified` : "",
269
+ diff.deleted.length > 0 ? `-${diff.deleted.length} deleted` : "",
270
+ ]
271
+ .filter(Boolean)
272
+ .join(", ");
273
+ const reasonZh = `将沙盒「${diff.sandbox.name}」的改动(${diffSummaryZh || "无变更"})写回源项目 ${diff.sourcePath}`;
274
+ const reasonEn = `Sync changes from sandbox "${diff.sandbox.name}" (${diffSummaryEn || "no changes"}) back to source project ${diff.sourcePath}`;
259
275
  const decision = await host.askApproval(toolCallId, SANDBOX_TOOL_NAME, {
260
276
  action: "apply_to_source",
261
277
  sandbox: diff.sandbox.id,
262
278
  sourcePath: diff.sourcePath,
263
279
  added: diff.added.slice(0, 30),
264
280
  modified: diff.modified.slice(0, 30),
281
+ deleted: diff.deleted.slice(0, 30),
265
282
  }, reasonZh, reasonEn, host.getConversationId?.(), {
266
283
  id: "sandbox.apply-to-source",
267
284
  label: "沙盒修改写回源项目",
@@ -286,7 +303,7 @@ export function makeSandboxTool(host, getLang) {
286
303
  content: [
287
304
  {
288
305
  type: "text",
289
- text: pick(lang, `✅ 已将沙盒「${res.sandbox.name}」的变更(共 ${res.copiedFiles} 个文件)同步写回源项目:${res.sourcePath}`, `✅ Synced changes from sandbox "${res.sandbox.name}" (${res.copiedFiles} files) back to source project: ${res.sourcePath}`),
306
+ text: pick(lang, `✅ 已将沙盒「${res.sandbox.name}」的变更同步写回源项目:${res.sourcePath}(同步 ${res.copiedFiles} 个文件${res.deletedFiles ? `,清理 ${res.deletedFiles} 个已删除文件` : ""})`, `✅ Synced changes from sandbox "${res.sandbox.name}" back to source project: ${res.sourcePath} (${res.copiedFiles} files synced${res.deletedFiles ? `, ${res.deletedFiles} deleted files pruned` : ""})`),
290
307
  },
291
308
  ],
292
309
  details: {
@@ -294,6 +311,7 @@ export function makeSandboxTool(host, getLang) {
294
311
  sandbox: res.sandbox,
295
312
  sourcePath: res.sourcePath,
296
313
  copiedFiles: res.copiedFiles,
314
+ deletedFiles: res.deletedFiles ?? 0,
297
315
  },
298
316
  };
299
317
  }
@@ -324,9 +342,37 @@ export function makeSandboxTool(host, getLang) {
324
342
  isError: true,
325
343
  };
326
344
  }
327
- // 若当前工作区正好在该沙盒内,先切回源项目
328
- if (activeSbx?.id === targetInfo.id && targetInfo.sourcePath) {
329
- await host.setCwd(targetInfo.sourcePath);
345
+ // 销毁会 rm -rf 整个沙盒目录(可能含用户转正后的工作成果),
346
+ // 与 apply_to_source 同样强制人工审批——bash 跑 rm -rf 都会命中
347
+ // 内置审批规则,工具路径不该有绕过口
348
+ if (host.askApproval) {
349
+ const decision = await host.askApproval(toolCallId, SANDBOX_TOOL_NAME, {
350
+ action: "destroy",
351
+ sandbox: targetInfo.id,
352
+ path: targetInfo.path,
353
+ sourcePath: targetInfo.sourcePath,
354
+ }, `将销毁沙盒「${targetInfo.name}」(${targetInfo.path}${targetInfo.ephemeral ? "" : ",永久沙盒"})并删除其全部内容,不可撤销`, `Destroy sandbox "${targetInfo.name}" (${targetInfo.path}${targetInfo.ephemeral ? "" : ", persistent"}) and remove all of its contents. This cannot be undone.`, host.getConversationId?.(), {
355
+ id: "sandbox.destroy",
356
+ label: "销毁沙盒",
357
+ labelEn: "Destroy sandbox",
358
+ });
359
+ if (decision.decision === "deny") {
360
+ return {
361
+ content: [
362
+ {
363
+ type: "text",
364
+ text: pick(lang, `【销毁沙盒被用户拒绝】${decision.reason ? `原因:${decision.reason}` : ""}`, `[Sandbox destroy denied by user]${decision.reason ? ` Reason: ${decision.reason}` : ""}`),
365
+ },
366
+ ],
367
+ details: { guardDenied: true, userDenied: true },
368
+ isError: true,
369
+ };
370
+ }
371
+ }
372
+ // 若当前工作区正好在该沙盒内,先切出去(源项目优先,空白沙盒回退
373
+ // homedir——否则销毁后 cwd 悬空,后续 bash/read/write 全部 ENOENT)
374
+ if (activeSbx?.id === targetInfo.id) {
375
+ await host.setCwd(targetInfo.sourcePath && existsSync(targetInfo.sourcePath) ? targetInfo.sourcePath : homedir());
330
376
  }
331
377
  const destroyed = await host.sandboxes.destroy(targetInfo.id);
332
378
  await host.onSandboxesChanged();
@@ -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),遗留三开关推送时推导,保证面板一致。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-web-ui",
3
- "version": "0.104.2",
3
+ "version": "0.104.4",
4
4
  "description": "Just open your browser to get all your work done — browser cockpit for AI coding agents (chat, code, files, terminal, Git in one tab)",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -160,6 +160,8 @@ export interface PluginHost {
160
160
  broadcast(payload: unknown): void;
161
161
  notify(level: "info" | "warning" | "error", text: string, textEn?: string): void;
162
162
  onMessage(handler: (payload: unknown, from?: string) => void): () => void;
163
+ /** 注册客户端上行消息处理器(RPC 模式):回调提供 (msg, reply),调用 reply(payload) 可直接向来源客户端回包。 */
164
+ onClientMessage(handler: (msg: unknown, reply: (payload: unknown) => void) => void | Promise<void>): () => void;
163
165
  sendTo(clientId: string, payload: unknown): void;
164
166
  onAttach(handler: (clientId: string) => void): () => void;
165
167
  onToolEvent(handler: (ev: unknown) => void): () => void;
@@ -176,6 +178,16 @@ export interface PluginHost {
176
178
  /** 订阅模型切换成功(回调带 clientId / conversationId / model / isSubagent… 的快照)。 */
177
179
  onClientModelChanged(handler: (snap: unknown) => void): () => void;
178
180
  registerAgentTool(tool: PluginAgentTool): () => void;
181
+ /** 注册一个供 AI 调用的工具(单参数 execute(args) 兼容接口,内部适配并转调 registerAgentTool)。 */
182
+ registerTool(tool: {
183
+ name: string;
184
+ description: string;
185
+ label?: string;
186
+ promptSnippet?: string;
187
+ promptGuidelines?: string[];
188
+ parameters?: Record<string, unknown>;
189
+ execute(args: Record<string, unknown>): Promise<unknown>;
190
+ }): () => void;
179
191
  dir: string;
180
192
  dataDir: string;
181
193
  readonly cwd: string;
@@ -203,6 +215,7 @@ export interface PluginHost {
203
215
  has(name: string): boolean;
204
216
  delete(name: string): void;
205
217
  list(): string[];
218
+ getAll(): Record<string, string>;
206
219
  };
207
220
  ensureDeps(specs: string[], opts?: { onProgress?: (msg: string) => void }): Promise<boolean>;
208
221
  fs: PluginHostFs;
@@ -1,3 +1,3 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{i as t,t as n}from"./react-CR5VJ85Q.js";import{n as r,t as i}from"./xterm-Cf5xxe4g.js";import{a,c as o,d as s,f as c,g as l,h as u,i as d,l as f,m as p,o as m,p as h,r as g,s as _,t as v,u as y}from"./index-BEuJeIJv.js";var b=e(t(),1);function x(e,t){return Math.abs(t)>10&&Math.abs(t)>Math.abs(e)*1.2}function S(e,t){return e-t}var C=n();function w(e){let t=null;return{clean:e.replace(/\r?\n?\[pi-term-exit:(-?\d+)\]\r?\n?/g,(e,n)=>(t=Number(n),`\r
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{i as t,t as n}from"./react-CR5VJ85Q.js";import{n as r,t as i}from"./xterm-Cf5xxe4g.js";import{a,c as o,d as s,f as c,g as l,h as u,i as d,l as f,m as p,o as m,p as h,r as g,s as _,t as v,u as y}from"./index-DOrLcjLY.js";var b=e(t(),1);function x(e,t){return Math.abs(t)>10&&Math.abs(t)>Math.abs(e)*1.2}function S(e,t){return e-t}var C=n();function w(e){let t=null;return{clean:e.replace(/\r?\n?\[pi-term-exit:(-?\d+)\]\r?\n?/g,(e,n)=>(t=Number(n),`\r
2
2
  `)).replace(/\r?\n?\x1b\[90m\[(?:进程已退出,退出码 |Process exited with code )-?\d+\]\x1b\[0m\r?\n?/g,`\r
3
3
  `),exitCode:t}}function T({conversationId:e,terminalId:t,command:n,cwd:o,title:s,agentBash:c,active:l,running:u,exitCode:f,register:p}){let h=(0,b.useRef)(null),_=(0,b.useRef)(null),{locale:v}=m(),y=(0,b.useRef)(v);y.current=v;let T=n?JSON.stringify(n):``,E=(0,b.useRef)(u===!1);(0,b.useEffect)(()=>{let u=h.current;if(!u)return;let f=new r({theme:d(),fontFamily:`"SF Mono", "JetBrains Mono", ui-monospace, Menlo, Consolas, monospace`,fontSize:13,cursorBlink:!0,scrollback:8e3}),m=new i;f.loadAddon(m),f.open(u),_.current={term:f,fit:m},l&&f.focus();let v=()=>{f.options.theme=d()};window.addEventListener(g,v),f.attachCustomKeyEventHandler(e=>{if(e.type!==`keydown`)return!0;let t=e.key?.toLowerCase();if((e.ctrlKey||e.metaKey)&&t===`v`)return!1;if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&t===`c`&&f.hasSelection()){let e=f.textarea;return e&&(e.value=f.getSelection(),e.select()),!1}return!0});let b=p(e,t,{write:e=>f.write(w(e).clean),dispose:()=>f.dispose()}),C=()=>{try{m.fit(),a({type:`terminal_resize`,terminalId:t,conversationId:e,cols:f.cols,rows:f.rows})}catch{}},T=requestAnimationFrame(()=>{try{m.fit()}catch{}E.current||a(n?{type:`run_command`,terminalId:t,conversationId:e,command:n,cols:f.cols,rows:f.rows}:{type:`terminal_create`,terminalId:t,title:s,locale:y.current,agentBash:c,conversationId:e,cwd:o,cols:f.cols,rows:f.rows})}),D=f.onData(n=>{a({type:`terminal_input`,terminalId:t,conversationId:e,data:n})}),O=f.element,k=null,A=0,j=0,M=0,N=!1,P=e=>{if(e.touches.length!==1){k=null,N=!1;return}let t=e.touches[0];k=t.identifier,A=t.clientX,j=t.clientY,M=t.clientY,N=!1},F=e=>{if(k===null||e.touches.length!==1)return;let t=e.touches[0];if(t.identifier!==k)return;if(!N){if(!x(t.clientX-A,t.clientY-j))return;N=!0}e.preventDefault();let n=S(M,t.clientY);M=t.clientY,n!==0&&typeof WheelEvent<`u`&&(u.querySelector(`.xterm-viewport`)??O)?.dispatchEvent(new WheelEvent(`wheel`,{bubbles:!0,cancelable:!0,deltaY:n,deltaMode:0,clientX:t.clientX,clientY:t.clientY}))},I=e=>{if(k!==null){if(e.touches.length>0){k=null,N=!1;return}k=null,N=!1}};O?.addEventListener(`touchstart`,P,{passive:!0}),O?.addEventListener(`touchmove`,F,{passive:!1}),O?.addEventListener(`touchend`,I),O?.addEventListener(`touchcancel`,I);let L=null;return typeof ResizeObserver<`u`&&(L=new ResizeObserver(()=>{u.offsetWidth>0&&u.offsetHeight>0&&C()}),L.observe(u)),()=>{cancelAnimationFrame(T),D.dispose(),O?.removeEventListener(`touchstart`,P),O?.removeEventListener(`touchmove`,F),O?.removeEventListener(`touchend`,I),O?.removeEventListener(`touchcancel`,I),window.removeEventListener(g,v),L?.disconnect(),b(),f.dispose(),_.current=null}},[e,t,T,p]),(0,b.useEffect)(()=>{if(!l)return;let n=requestAnimationFrame(()=>{let n=_.current;if(n){try{n.fit.fit(),a({type:`terminal_resize`,terminalId:t,conversationId:e,cols:n.term.cols,rows:n.term.rows})}catch{}n.term.focus()}});return()=>cancelAnimationFrame(n)},[l]);let{t:D}=m(),O=(0,b.useRef)(void 0);return(0,b.useEffect)(()=>{if(u===O.current||(O.current=u,u!==!1))return;let e=_.current;e&&e.term.write(`\r\n\x1b[90m${D(`exitBanner`,{code:f??``})}\x1b[0m\r\n`)},[u,t,f]),(0,C.jsx)(`div`,{ref:h,className:`term-xterm ${l?``:`hidden`}`})}var E={name:``,command:``,cwd:"${pwd}"};function D({chat:e,terminal:t,uiTerminalToolbar:n,onUiAction:r}){let i=_(),[d,m]=(0,b.useState)(null),[g,x]=(0,b.useState)(!1),[S,w]=(0,b.useState)(!1),[D,O]=(0,b.useState)(null),[k,A]=(0,b.useState)(E),[j,M]=(0,b.useState)(null),N=(0,b.useRef)(null),[P,F]=(0,b.useState)(!0),[I,L]=(0,b.useState)(null),[R,z]=(0,b.useState)(``);(0,b.useEffect)(()=>{e.terminals.length===0?m(null):e.terminals.some(e=>e.id===d)||m(e.terminals[e.terminals.length-1].id)},[e.terminals,d]),(0,b.useEffect)(()=>{e.terminalActiveId&&(m(e.terminalActiveId),x(!1))},[e.terminalActiveId]),(0,b.useEffect)(()=>()=>{N.current&&clearTimeout(N.current)},[]);let B=e.terminals.filter(e=>!e.agentBash),V=e.terminals.filter(e=>e.agentBash),H=n=>{if(!e.ready)return;let r=o(),i=e.activeConversationId||e.state?.conversationId||``;t.create({...n,id:r,conversationId:i,cols:n.cols??80,rows:n.rows??24,running:!0,exitCode:null}),m(r),x(!1)},U=()=>H({title:i(`terminalTitle`,{n:B.length+1}),cwd:e.state?.cwd??``}),W=n=>{let r=n.name||n.command,i=e.terminals.find(e=>e.title===r);if(i){t.restart(i.id),m(i.id),a({type:`run_command`,terminalId:i.id,conversationId:i.conversationId,command:n,cols:80,rows:24});return}H({title:r,cwd:e.state?.cwd??``,command:n})},G=n=>{let r=e.terminals.find(e=>e.id===n);if(r&&a({type:`terminal_kill`,terminalId:n,conversationId:r.conversationId}),t.close(n),d===n){let t=e.terminals.filter(e=>e.id!==n);m(t.length>0?t[t.length-1].id:null)}},K=e=>(0,C.jsxs)(`div`,{className:`term-tab ${e.id===d?`active`:``}`,children:[(0,C.jsxs)(`button`,{type:`button`,className:`term-tab-main`,title:`${e.cwd}${e.command?`\n> ${e.command.command}`:``}`,onClick:()=>{I||(m(e.id),x(!1))},children:[(0,C.jsx)(`span`,{className:`term-tab-dot ${e.running?`run`:`exit`}`}),(0,C.jsxs)(`span`,{className:`term-tab-title`,children:[I===e.id?(0,C.jsx)(`input`,{autoFocus:!0,className:`term-tab-rename-input`,value:R,placeholder:e.title,onClick:e=>e.stopPropagation(),onChange:e=>z(e.target.value),onKeyDown:t=>{if(t.stopPropagation(),t.key===`Enter`&&!t.nativeEvent.isComposing){let t=R.trim();t&&a({type:`rename_terminal`,terminalId:e.id,conversationId:e.conversationId,title:t}),L(null)}else t.key===`Escape`&&L(null)},onBlur:()=>L(null)}):e.title,!e.running&&(0,C.jsx)(`span`,{className:`term-tab-exit`,children:i(`exited`,{code:e.exitCode===null?``:` ${e.exitCode}`})})]})]}),(0,C.jsx)(`button`,{type:`button`,className:`term-tab-close term-tab-rename`,title:i(`renameTerminal`),onClick:t=>{t.stopPropagation(),z(e.title),L(e.id)},children:(0,C.jsx)(f,{})}),(0,C.jsx)(`button`,{type:`button`,className:`term-tab-close`,title:i(`closeTerminal`),onClick:()=>G(e.id),children:(0,C.jsx)(l,{})})]},e.id),q=()=>{w(!0),O(null),A(E)},ee=t=>{let n=e.commands[t];n&&(w(!1),O(t),A({name:n.name,command:n.command,cwd:n.cwd??``}))},J=()=>{w(!1),O(null)},Y=()=>{let t=k.name.trim(),n=k.command.trim();if(!t||!n)return;let r={name:t,command:n,cwd:k.cwd.trim()||void 0},i=S?[...e.commands,r]:D===null?e.commands:e.commands.map((e,t)=>t===D?r:e);a({type:`save_commands`,commands:i}),J()},te=t=>{if(j===t){let n=e.commands.filter((e,n)=>n!==t);a({type:`save_commands`,commands:n}),M(null),N.current&&clearTimeout(N.current)}else M(t),N.current&&clearTimeout(N.current),N.current=setTimeout(()=>M(null),2500)},ne=S||D!==null,X=n===void 0?[`host:term-cmd-refresh`,`host:term-cmd-new`,`host:term-tab-new`].map(e=>({id:e,source:`host`})):n.filter(e=>!e.hidden),Z=(e,t)=>{let n=new Set(e);return X.filter(e=>n.has(e.id)||t&&e.source!==`host`)},Q=(e,t)=>{let n=X.find(t=>t.id===e);return n?.labelExplicit?n.label:t},$={"host:term-cmd-refresh":(0,C.jsx)(`button`,{type:`button`,className:`panel-refresh`,title:Q(`host:term-cmd-refresh`,i(`rerun`)),onClick:()=>a({type:`list_commands`}),children:(0,C.jsx)(h,{})}),"host:term-cmd-new":(0,C.jsx)(`button`,{type:`button`,className:`panel-new`,title:Q(`host:term-cmd-new`,i(`newCommand`)),onClick:q,children:(0,C.jsx)(c,{})}),"host:term-tab-new":(0,C.jsx)(`button`,{type:`button`,className:`panel-new`,title:Q(`host:term-tab-new`,i(`newTerminal`)),onClick:U,children:(0,C.jsx)(c,{})})};return(0,C.jsxs)(`div`,{className:`terminal-view`,children:[(0,C.jsxs)(`aside`,{className:`term-side term-commands ${g?`open`:``}`,children:[(0,C.jsxs)(`div`,{className:`panel-header`,children:[(0,C.jsx)(`span`,{className:`panel-title`,children:i(`commands`)}),(0,C.jsx)(`div`,{className:`panel-header-actions`,children:v(Z([`host:term-cmd-refresh`,`host:term-cmd-new`],!1),$,r)})]}),(0,C.jsx)(`div`,{className:`panel-body`,children:ne?(0,C.jsxs)(`div`,{className:`cmd-form`,children:[(0,C.jsx)(`label`,{htmlFor:`cmd-name`,children:i(`name`)}),(0,C.jsx)(`input`,{id:`cmd-name`,className:`cmd-input`,value:k.name,placeholder:i(`exampleName`),autoFocus:!0,onChange:e=>A({...k,name:e.target.value})}),(0,C.jsx)(`label`,{htmlFor:`cmd-command`,children:i(`command`)}),(0,C.jsx)(`input`,{id:`cmd-command`,className:`cmd-input`,value:k.command,placeholder:i(`exampleCommand`),onChange:e=>A({...k,command:e.target.value}),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&Y()}}),(0,C.jsxs)(`label`,{htmlFor:`cmd-cwd`,children:[i(`directory`),` `,(0,C.jsx)(`span`,{className:`cmd-hint`,children:i(`cwdHint`)})]}),(0,C.jsx)(`input`,{id:`cmd-cwd`,className:`cmd-input`,value:k.cwd,placeholder:"${pwd}",onChange:e=>A({...k,cwd:e.target.value}),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&Y()}}),(0,C.jsxs)(`div`,{className:`cmd-form-actions`,children:[(0,C.jsx)(`button`,{type:`button`,className:`btn`,onClick:J,children:i(`cancel`)}),(0,C.jsx)(`button`,{type:`button`,className:`btn primary`,disabled:!k.name.trim()||!k.command.trim(),onClick:Y,children:i(`save`)})]})]}):(0,C.jsxs)(C.Fragment,{children:[e.commands.length===0&&(0,C.jsx)(`div`,{className:`panel-empty`,children:i(`noCommands`)}),e.commands.map((e,t)=>(0,C.jsxs)(`div`,{className:`cmd-item`,children:[(0,C.jsx)(`button`,{type:`button`,className:`cmd-run`,title:i(`clickToRun`),onClick:()=>W(e),children:(0,C.jsx)(s,{})}),(0,C.jsxs)(`button`,{type:`button`,className:`cmd-main`,title:i(`clickToRun`),onClick:()=>W(e),children:[(0,C.jsx)(`span`,{className:`cmd-name`,children:e.name}),(0,C.jsx)(`span`,{className:`cmd-command`,children:e.command}),e.cwd&&(0,C.jsx)(`span`,{className:`cmd-cwd`,children:e.cwd})]}),(0,C.jsx)(`button`,{type:`button`,className:`cmd-act`,title:i(`edit`),onClick:()=>ee(t),children:(0,C.jsx)(f,{})}),(0,C.jsx)(`button`,{type:`button`,className:`cmd-act del ${j===t?`confirm`:``}`,title:i(`delete`),onClick:()=>te(t),children:j===t?i(`confirmQ`):(0,C.jsx)(u,{})})]},t))]})}),(0,C.jsxs)(`div`,{className:`term-tabs-block`,children:[(0,C.jsxs)(`div`,{className:`panel-header`,children:[(0,C.jsx)(`span`,{className:`panel-title`,children:i(`terminal`)}),v(Z([`host:term-tab-new`],!0),$,r)]}),(0,C.jsxs)(`div`,{className:`panel-body`,children:[e.terminals.length===0&&(0,C.jsx)(`div`,{className:`panel-empty`,children:i(`noTerminal`)}),B.map(K),V.length>0&&(0,C.jsxs)(`div`,{className:`term-folder`,children:[(0,C.jsxs)(`button`,{type:`button`,className:`term-folder-header ${P?`open`:``}`,title:i(`aiBashGroup`),onClick:()=>F(e=>!e),children:[(0,C.jsx)(`span`,{className:`term-folder-caret`,children:P?`▾`:`▸`}),(0,C.jsx)(`span`,{className:`term-folder-title`,children:i(`aiBashGroup`)}),(0,C.jsx)(`span`,{className:`term-folder-count`,children:V.length})]}),P&&(0,C.jsx)(`div`,{className:`term-folder-body`,children:V.map(K)})]})]})]})]}),(0,C.jsxs)(`div`,{className:`term-main`,children:[g&&(0,C.jsx)(`div`,{className:`drawer-backdrop`,onClick:()=>x(!1)}),(0,C.jsx)(`button`,{type:`button`,className:`term-side-toggle`,title:i(`commands`),onClick:()=>x(e=>!e),children:(0,C.jsx)(y,{})}),e.terminals.length===0?(0,C.jsxs)(`div`,{className:`term-empty`,children:[(0,C.jsx)(p,{className:`term-empty-icon`}),(0,C.jsx)(`div`,{className:`term-empty-title`,children:i(`builtinTerminal`)}),(0,C.jsx)(`div`,{className:`term-empty-sub`,children:i(`termEmptySub`)})]}):e.terminals.map(e=>(0,C.jsx)(T,{conversationId:e.conversationId,terminalId:e.id,command:e.command,cwd:e.cwd,title:e.title,agentBash:e.agentBash,active:e.id===d,running:e.running,exitCode:e.exitCode,register:t.register},`${e.conversationId}:${e.id}`))]})]})}export{D as TerminalPanel};