pi-web-ui 0.112.0 → 0.113.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 (48) hide show
  1. package/CHANGELOG.md +64 -1
  2. package/README.md +1 -7
  3. package/README.zh-CN.md +1 -7
  4. package/README.zh-TW.md +1 -7
  5. package/bin/pi-web-ui.mjs +423 -50
  6. package/dist/gh-comment-781.md +5 -0
  7. package/dist/server/agent-service-daemon.js +29 -4
  8. package/dist/server/agent-service.js +222 -36
  9. package/dist/server/canvas/canvas-agent-tool.js +2 -0
  10. package/dist/server/canvas/canvas-orchestrator.js +40 -1
  11. package/dist/server/canvas/pstack-skills-data.js +498 -0
  12. package/dist/server/control-socket.js +6 -2
  13. package/dist/server/dispatch-domain-handlers.js +36 -11
  14. package/dist/server/dsh/dsh-agent-service.js +52 -4
  15. package/dist/server/durable/durable-driver.js +37 -98
  16. package/dist/server/durable/durable-event-projector.js +253 -0
  17. package/dist/server/engine-probe.js +35 -11
  18. package/dist/server/files-service.js +72 -8
  19. package/dist/server/index.js +74 -50
  20. package/dist/server/model-admin.js +185 -63
  21. package/dist/server/plugins.js +10 -6
  22. package/dist/server/remote-ssh-service.js +110 -12
  23. package/dist/server/serialize.js +1 -1
  24. package/dist/server/settings-service.js +36 -48
  25. package/dist/server/setup-page.js +632 -0
  26. package/dist/server/skill-discovery.js +361 -59
  27. package/dist/server/skill-maintenance.js +231 -0
  28. package/dist/server/skill-tool.js +32 -3
  29. package/dist/server/soft-cap.js +29 -7
  30. package/dist/server/subagents.js +246 -31
  31. package/dist/server/tool-host-factories.js +2 -0
  32. package/dist/server/tool-manager.js +106 -28
  33. package/dist/server/universal/drivers/claude-code.js +96 -4
  34. package/dist/server/universal/universal-session.js +19 -0
  35. package/dist/server/webui-context.js +6 -6
  36. package/dist/test-artifact.md +9 -0
  37. package/dist/test-preview-modal.md +11 -0
  38. package/dist/test-report.html +20 -0
  39. package/package.json +1 -1
  40. package/plugin-sdk/index.d.ts +17 -3
  41. package/plugins/catalog.json +10 -0
  42. package/web/dist/assets/{TerminalPanel-Dqr1dK28.js → TerminalPanel-Ci55JtJL.js} +2 -2
  43. package/web/dist/assets/index-ByiO9f-N.js +2008 -0
  44. package/web/dist/assets/index-ycGLh4a4.css +1 -0
  45. package/web/dist/index.html +2 -2
  46. package/web/dist/sw.js +1 -1
  47. package/web/dist/assets/index-Dh8BX-lP.js +0 -720
  48. package/web/dist/assets/index-DqrC1I_a.css +0 -1
package/bin/pi-web-ui.mjs CHANGED
@@ -34,6 +34,7 @@ import {
34
34
  restoreBackup as restorePluginBackup,
35
35
  checkPluginUpdates,
36
36
  resolveRemoteSha,
37
+ compareVersions,
37
38
  } from "../dist/server/plugin-updater.js";
38
39
  import {
39
40
  chmodSync,
@@ -49,7 +50,7 @@ import {
49
50
  rmSync,
50
51
  writeFileSync,
51
52
  } from "node:fs";
52
- import { homedir, tmpdir, userInfo } from "node:os";
53
+ import { homedir, networkInterfaces, tmpdir, userInfo } from "node:os";
53
54
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
54
55
  import { pathToFileURL } from "node:url";
55
56
  import { fileURLToPath } from "node:url";
@@ -279,6 +280,7 @@ function parseFlags(argv) {
279
280
  dir: undefined,
280
281
  template: undefined,
281
282
  withTest: false,
283
+ remote: false,
282
284
  help: false,
283
285
  };
284
286
  const positionals = [];
@@ -353,6 +355,9 @@ function parseFlags(argv) {
353
355
  case "--with-test":
354
356
  opts.withTest = true;
355
357
  break;
358
+ case "--remote":
359
+ opts.remote = true;
360
+ break;
356
361
  case "--help":
357
362
  case "-h":
358
363
  opts.help = true;
@@ -1291,7 +1296,18 @@ function serviceEnv(port, cwd, dataDir, engine, host, agentDir, service = {}) {
1291
1296
  }
1292
1297
  // Interactive Windows tasks inherit the user's PATH; only systemd/launchd
1293
1298
  // run with a minimal environment that needs an explicit PATH.
1294
- if (!isWin) env.PATH = process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin";
1299
+ if (!isWin) {
1300
+ const defaultPath =
1301
+ process.platform === "darwin"
1302
+ ? "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
1303
+ : "/usr/local/bin:/usr/bin:/bin";
1304
+ const currentPath = process.env.PATH ?? defaultPath;
1305
+ if (process.platform === "darwin" && !currentPath.includes("/opt/homebrew/bin")) {
1306
+ env.PATH = `/opt/homebrew/bin:/usr/local/bin:${currentPath}`;
1307
+ } else {
1308
+ env.PATH = currentPath;
1309
+ }
1310
+ }
1295
1311
  // Same for the locale: launchd/systemd drop LANG/LC_ALL, and a C-locale
1296
1312
  // shell garbles multibyte input in the terminal (UTF-8 continuation
1297
1313
  // bytes 0x80–0x9F rendered as C1 control chars). Bake the installing
@@ -1322,10 +1338,10 @@ function installLaunchd(opts) {
1322
1338
  mkdirSync(dirname(plist), { recursive: true });
1323
1339
  writeFileSync(plist, content);
1324
1340
  run("launchctl", ["bootstrap", `gui/${uid()}`, plist]);
1341
+ if (opts.print) return;
1325
1342
  console.log(ZH ? `✅ 已安装并启动 launchd 服务 ${label}` : `✅ launchd service installed and started ${label}`);
1326
1343
  console.log(ZH ? ` 端口 : ${port}` : ` Port : ${port}`);
1327
1344
  console.log(ZH ? ` 目录 : ${cwd}` : ` Directory : ${cwd}`);
1328
- console.log(ZH ? ` 访问 : http://localhost:${port}` : ` URL : http://localhost:${port}`);
1329
1345
  console.log(
1330
1346
  ZH ? ` 日志 : /tmp/pi-web-ui.log /tmp/pi-web-ui.err` : ` Log : /tmp/pi-web-ui.log /tmp/pi-web-ui.err`,
1331
1347
  );
@@ -1383,7 +1399,6 @@ function installSystemd(opts) {
1383
1399
  );
1384
1400
  console.log(ZH ? ` 端口 : ${port}` : ` Port : ${port}`);
1385
1401
  console.log(ZH ? ` 目录 : ${cwd}` : ` Directory : ${cwd}`);
1386
- console.log(ZH ? ` 访问 : http://localhost:${port}` : ` URL : http://localhost:${port}`);
1387
1402
  console.log(ZH ? ` 日志 : journalctl -u ${name}.service -f` : ` Log : journalctl -u ${name}.service -f`);
1388
1403
  console.log(
1389
1404
  ZH
@@ -1479,7 +1494,6 @@ function installWindows(opts) {
1479
1494
  console.log(ZH ? ` 窗口 : wscript 隐藏启动,无黑窗` : ` Window : wscript hidden launch, no console`);
1480
1495
  console.log(ZH ? ` 端口 : ${port}` : ` Port : ${port}`);
1481
1496
  console.log(ZH ? ` 目录 : ${cwd}` : ` Directory : ${cwd}`);
1482
- console.log(ZH ? ` 访问 : http://localhost:${port}` : ` URL : http://localhost:${port}`);
1483
1497
  console.log(ZH ? ` 日志 : ${winLogPath(name)}` : ` Log : ${winLogPath(name)}`);
1484
1498
  console.log(
1485
1499
  ZH
@@ -1569,6 +1583,88 @@ function controlCommand(opts, cmd) {
1569
1583
  });
1570
1584
  }
1571
1585
 
1586
+ function isLocalLoopback(addr) {
1587
+ if (!addr) return false;
1588
+ const s = addr.trim().toLowerCase();
1589
+ return (
1590
+ s === "localhost" ||
1591
+ s.endsWith(".localhost") ||
1592
+ s === "127.0.0.1" ||
1593
+ s.startsWith("127.") ||
1594
+ s === "::1" ||
1595
+ s.startsWith("::ffff:127.")
1596
+ );
1597
+ }
1598
+
1599
+ function getLocalLanIpv4s() {
1600
+ const ips = [];
1601
+ try {
1602
+ const ifaces = networkInterfaces();
1603
+ for (const list of Object.values(ifaces)) {
1604
+ if (!list) continue;
1605
+ for (const iface of list) {
1606
+ if (iface && iface.family === "IPv4" && !iface.internal) {
1607
+ ips.push(iface.address);
1608
+ }
1609
+ }
1610
+ }
1611
+ } catch {
1612
+ // best-effort
1613
+ }
1614
+ return ips;
1615
+ }
1616
+
1617
+ /** 格式化打印服务的访问链接(包含本机、局域网 IP 与 Token / Setup 入口) */
1618
+ function printServiceUrls(port, host, token = "") {
1619
+ const tokenSuffix = token ? `?token=${token}` : "";
1620
+ const isLoopback = !host || isLocalLoopback(host);
1621
+ console.log(
1622
+ ZH
1623
+ ? ` 本机访问 : http://127.0.0.1:${port}/${tokenSuffix}`
1624
+ : ` Local URL : http://127.0.0.1:${port}/${tokenSuffix}`,
1625
+ );
1626
+
1627
+ if (!isLoopback) {
1628
+ const lanIps = getLocalLanIpv4s();
1629
+ if (lanIps.length > 0) {
1630
+ for (const ip of lanIps) {
1631
+ console.log(
1632
+ ZH
1633
+ ? ` 局域网 : http://${ip}:${port}/${tokenSuffix}`
1634
+ : ` LAN URL : http://${ip}:${port}/${tokenSuffix}`,
1635
+ );
1636
+ }
1637
+ } else if (host !== "0.0.0.0") {
1638
+ console.log(
1639
+ ZH
1640
+ ? ` 访问地址 : http://${host}:${port}/${tokenSuffix}`
1641
+ : ` Host URL : http://${host}:${port}/${tokenSuffix}`,
1642
+ );
1643
+ }
1644
+ }
1645
+ if (token) {
1646
+ console.log(ZH ? ` 访问密钥 : ${token}` : ` Token : ${token}`);
1647
+ }
1648
+ console.log(
1649
+ ZH
1650
+ ? ` 配置管理 : http://127.0.0.1:${port}/setup (仅本机)`
1651
+ : ` Setup : http://127.0.0.1:${port}/setup (local only)`,
1652
+ );
1653
+ }
1654
+
1655
+ /** 轮询等待后台服务就绪并打印包含实时 token 的访问信息 */
1656
+ async function printRunningServiceAccess(opts, host, fallbackToken = "") {
1657
+ const t0 = Date.now();
1658
+ let st = null;
1659
+ while (Date.now() - t0 < 3500) {
1660
+ st = await controlCommand(opts, "status");
1661
+ if (st && st.ok) break;
1662
+ await new Promise((r) => setTimeout(r, 200));
1663
+ }
1664
+ const token = (st && typeof st.authToken === "string" ? st.authToken : fallbackToken).trim();
1665
+ printServiceUrls(effectivePort(opts), host, token);
1666
+ }
1667
+
1572
1668
  /** Append the live server status (via the control socket) to `server status`. */
1573
1669
  async function printLiveStatus(opts) {
1574
1670
  const st = await controlCommand(opts, "status");
@@ -1581,6 +1677,10 @@ async function printLiveStatus(opts) {
1581
1677
  return;
1582
1678
  }
1583
1679
  console.log(ZH ? " --- 实时状态 (control socket) ---" : " --- live status (control socket) ---");
1680
+ if (st.authToken) {
1681
+ const host = process.env.PI_WEB_HOST || "";
1682
+ printServiceUrls(effectivePort(opts), host, st.authToken);
1683
+ }
1584
1684
  console.log(ZH ? ` 版本 : ${st.version} · PID ${st.pid}` : ` Version : ${st.version} · PID ${st.pid}`);
1585
1685
  console.log(ZH ? ` 目录 : ${st.cwd}` : ` Directory : ${st.cwd}`);
1586
1686
  // 启动来源(server/launch-origin.ts):有 supervisor = 这个进程退出后会被自动
@@ -1877,6 +1977,7 @@ const PLUGIN_HELP = ZH
1877
1977
  --name <id> 插件目录名/id(默认取仓库名或 manifest.id,仅限字母数字-_)
1878
1978
  --data-dir <dir> 数据目录(默认 ~/.pi-web 或 $PI_WEB_DATA_DIR)
1879
1979
  --force 目标目录已存在时覆盖(覆盖前自动备份旧版本)
1980
+ --remote 强制从远端拉取最新代码(跳过本地随包内置插件快速路径)
1880
1981
  --build 强制源码构建:在隔离临时目录里按插件声明安装构建依赖并编译
1881
1982
  (manifest.build 或 package.json 的 scripts.build),
1882
1983
  成功且产物齐全后才替换目标目录,失败不留半装状态
@@ -1921,6 +2022,7 @@ Source formats (choose one):
1921
2022
  --name <id> plugin directory name/id (default: repo name or manifest.id; alphanumeric -_ only)
1922
2023
  --data-dir <dir> data directory (default ~/.pi-web or $PI_WEB_DATA_DIR)
1923
2024
  --force overwrite if target directory exists (auto-backup before overwrite)
2025
+ --remote force pulling from remote (skip local bundled builtin fast path)
1924
2026
  --build force source build: install build deps and compile in an isolated temp directory
1925
2027
  (manifest.build or package.json scripts.build),
1926
2028
  replaces target only on success with complete artifacts; no partial state on failure
@@ -1971,10 +2073,34 @@ function parsePluginSource(rawSpec) {
1971
2073
  if (url) [, spec] = url;
1972
2074
  }
1973
2075
  const segs = spec.split("/").filter(Boolean);
1974
- if (segs.length < 2)
2076
+ if (segs.length < 2) {
2077
+ // 单段名称(如 browser-use):若本地随包官方插件或 catalog 存在该 id,自动补齐为官方插件源
2078
+ if (segs.length === 1 && PLUGIN_ID_RE.test(segs[0])) {
2079
+ const id = segs[0];
2080
+ const pkgRoot = resolve(BIN_DIR, "..");
2081
+ const catalogPath = join(pkgRoot, "plugins", "catalog.json");
2082
+ const pluginDir = join(pkgRoot, "plugins", id);
2083
+ let isOfficial = existsSync(join(pluginDir, "manifest.json"));
2084
+ if (!isOfficial && existsSync(catalogPath)) {
2085
+ try {
2086
+ const cat = JSON.parse(readFileSync(catalogPath, "utf8"));
2087
+ if (Array.isArray(cat) && cat.some((e) => e?.id === id)) isOfficial = true;
2088
+ } catch {}
2089
+ }
2090
+ if (isOfficial) {
2091
+ return {
2092
+ owner: "xing-shuyin",
2093
+ repo: "pi-web-ui",
2094
+ ref,
2095
+ subpath: `plugins/${id}`,
2096
+ cloneUrl: "https://github.com/xing-shuyin/pi-web-ui.git",
2097
+ };
2098
+ }
2099
+ }
1975
2100
  fail(
1976
2101
  ZH ? `无法识别的插件源 "${rawSpec}"\n${PLUGIN_HELP}` : `Unrecognized plugin source "${rawSpec}"\n${PLUGIN_HELP}`,
1977
2102
  );
2103
+ }
1978
2104
  for (const s of segs) {
1979
2105
  if (s === "." || s === "..")
1980
2106
  fail(
@@ -2014,28 +2140,172 @@ function cleanStalePluginTmpDirs() {
2014
2140
  } catch {}
2015
2141
  }
2016
2142
 
2017
- /** 把仓库拉到 tmpDir 并返回检出根目录。优先 git clone --depth 1,失败回退 codeload tarball + 系统 tar。 */
2018
- async function acquireRepo(src, tmpDir) {
2143
+ /**
2144
+ * 尝试定位随包自带的内置官方插件目录。
2145
+ * 命中条件:
2146
+ * 1. 未开启强制远端拉取标志(opts.remote / PI_WEB_PLUGIN_FORCE_REMOTE);
2147
+ * 2. 未显式指定非主干 git ref(除 main/master/HEAD 之外的 ref 说明用户想试特定提交);
2148
+ * 3. 属于官方仓库(xing-shuyin/pi-web-ui)的 plugins/<id> 子路径,且随包目录存在合法 manifest.json。
2149
+ */
2150
+ function resolveLocalBuiltinPluginDir(rawSpec, src, opts = {}) {
2151
+ if (opts.remote === true || process.env.PI_WEB_PLUGIN_FORCE_REMOTE === "1") return null;
2152
+ if (src?.ref && src.ref !== "main" && src.ref !== "master" && src.ref !== "HEAD") return null;
2153
+
2154
+ const pkgRoot = resolve(BIN_DIR, "..");
2155
+ let pluginSubdir = null;
2156
+
2157
+ if (src?.owner === "xing-shuyin" && src?.repo === "pi-web-ui" && src?.subpath) {
2158
+ pluginSubdir = src.subpath.startsWith("plugins/") ? src.subpath.slice("plugins/".length) : src.subpath;
2159
+ } else if (!src && typeof rawSpec === "string" && !rawSpec.includes("/") && PLUGIN_ID_RE.test(rawSpec.trim())) {
2160
+ pluginSubdir = rawSpec.trim();
2161
+ }
2162
+
2163
+ if (!pluginSubdir) return null;
2164
+ const localDir = join(pkgRoot, "plugins", pluginSubdir);
2165
+ if (existsSync(join(localDir, "manifest.json"))) {
2166
+ return localDir;
2167
+ }
2168
+ return null;
2169
+ }
2170
+
2171
+ /**
2172
+ * 把仓库拉到 tmpDir 并返回检出根目录。
2173
+ * 优化策略:
2174
+ * 1. 共享缓存复用:同一批量操作/同源仓库共享检出,增量 sparse-checkout add,杜绝反复 clone;
2175
+ * 2. 稀疏拉取(Sparse Checkout + Blobless filter):只拉取元数据与目标子目录,免除全量下载数十兆整仓;
2176
+ * 3. 健壮降级:稀疏失败平滑降级常规 shallow clone,再失败回退 tarball 直连。
2177
+ */
2178
+ async function acquireRepo(src, tmpDir, opts = {}) {
2179
+ const sharedCache = opts.sharedCache;
2180
+ const cacheKey = sharedCache ? `${src.cloneUrl}#${src.ref || "HEAD"}` : null;
2181
+ const normalizedSubpath = src.subpath ? src.subpath.split(/[\\/]/).filter(Boolean).join("/") : null;
2182
+
2183
+ // 1. 尝试从共享缓存中复用已有检出
2184
+ if (sharedCache && cacheKey && sharedCache.has(cacheKey)) {
2185
+ const cached = sharedCache.get(cacheKey);
2186
+ if (existsSync(cached.dir)) {
2187
+ if (!normalizedSubpath || (cached.subpaths && cached.subpaths.has(normalizedSubpath))) {
2188
+ console.log(
2189
+ ZH
2190
+ ? `· 复用已拉取仓库 ${src.cloneUrl}${normalizedSubpath ? ` (${normalizedSubpath})` : ""}`
2191
+ : `· Reusing cached repo ${src.cloneUrl}${normalizedSubpath ? ` (${normalizedSubpath})` : ""}`,
2192
+ );
2193
+ return cached.dir;
2194
+ }
2195
+ if (cached.isSparse && normalizedSubpath) {
2196
+ console.log(
2197
+ ZH
2198
+ ? `· 复用已拉取仓库,增量检出 ${normalizedSubpath}…`
2199
+ : `· Reusing cached repo, incrementally checking out ${normalizedSubpath}…`,
2200
+ );
2201
+ const addRes = spawnSync("git", ["sparse-checkout", "add", normalizedSubpath], {
2202
+ cwd: cached.dir,
2203
+ stdio: "inherit",
2204
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" },
2205
+ timeout: Number(process.env.PI_WEB_GIT_TIMEOUT_MS) || 45_000,
2206
+ });
2207
+ if (addRes.status === 0) {
2208
+ cached.subpaths.add(normalizedSubpath);
2209
+ return cached.dir;
2210
+ }
2211
+ }
2212
+ }
2213
+ }
2214
+
2019
2215
  const dst = join(tmpDir, "src");
2020
2216
  const hasGit = spawnSync("git", ["--version"], { stdio: "ignore", timeout: 10_000 }).status === 0;
2021
2217
  if (hasGit) {
2022
2218
  const gitTimeout = Number(process.env.PI_WEB_GIT_TIMEOUT_MS) || 45_000;
2219
+ const gitEnv = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
2220
+
2221
+ // 2. 稀疏拉取:当指定了 subpath 时,优先尝试 --filter=blob:none --sparse
2222
+ if (normalizedSubpath) {
2223
+ const sparseArgs = [
2224
+ "-c",
2225
+ "connect.timeout=15",
2226
+ "clone",
2227
+ "--depth",
2228
+ "1",
2229
+ "--filter=blob:none",
2230
+ "--sparse",
2231
+ "--no-checkout",
2232
+ ];
2233
+ if (src.ref) sparseArgs.push("--branch", src.ref);
2234
+ sparseArgs.push(src.cloneUrl, dst);
2235
+ console.log(
2236
+ `· git clone --depth 1 --filter=blob:none --sparse ${src.cloneUrl}${src.ref ? ` (${src.ref})` : ""} [${normalizedSubpath}]`,
2237
+ );
2238
+ const cloneRes = spawnSync("git", sparseArgs, {
2239
+ stdio: "inherit",
2240
+ env: gitEnv,
2241
+ timeout: gitTimeout,
2242
+ });
2243
+ if (cloneRes.status === 0 && existsSync(dst)) {
2244
+ const setRes = spawnSync("git", ["sparse-checkout", "set", normalizedSubpath], {
2245
+ cwd: dst,
2246
+ stdio: "inherit",
2247
+ env: gitEnv,
2248
+ timeout: gitTimeout,
2249
+ });
2250
+ if (setRes.status === 0) {
2251
+ const coRes = spawnSync("git", ["checkout"], {
2252
+ cwd: dst,
2253
+ stdio: "inherit",
2254
+ env: gitEnv,
2255
+ timeout: gitTimeout,
2256
+ });
2257
+ if (coRes.status === 0 && existsSync(dst)) {
2258
+ if (sharedCache && cacheKey) {
2259
+ sharedCache.set(cacheKey, {
2260
+ dir: dst,
2261
+ tmpDir,
2262
+ isSparse: true,
2263
+ subpaths: new Set([normalizedSubpath]),
2264
+ });
2265
+ }
2266
+ return dst;
2267
+ }
2268
+ }
2269
+ }
2270
+ // 稀疏拉取失败,清理已产生的残骸,准备降级
2271
+ if (existsSync(dst)) {
2272
+ try {
2273
+ rmSync(dst, { recursive: true, force: true });
2274
+ } catch {}
2275
+ }
2276
+ console.log(
2277
+ ZH ? "· 稀疏拉取不可用,降级为常规 git clone…" : "· Sparse checkout failed, falling back to regular git clone…",
2278
+ );
2279
+ }
2280
+
2281
+ // 3. 常规 shallow clone(未指定 subpath 或稀疏拉取失败时的降级通路)
2023
2282
  const args = ["-c", "connect.timeout=15", "clone", "--depth", "1", "--single-branch"];
2024
2283
  if (src.ref) args.push("--branch", src.ref);
2025
2284
  args.push(src.cloneUrl, dst);
2026
2285
  console.log(`· git clone --depth 1 ${src.cloneUrl}${src.ref ? ` (${src.ref})` : ""}`);
2027
2286
  const res = spawnSync("git", args, {
2028
2287
  stdio: "inherit",
2029
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" },
2288
+ env: gitEnv,
2030
2289
  timeout: gitTimeout,
2031
2290
  });
2032
- if (res.status === 0 && existsSync(dst)) return dst;
2291
+ if (res.status === 0 && existsSync(dst)) {
2292
+ if (sharedCache && cacheKey) {
2293
+ sharedCache.set(cacheKey, {
2294
+ dir: dst,
2295
+ tmpDir,
2296
+ isSparse: false,
2297
+ subpaths: normalizedSubpath ? new Set([normalizedSubpath]) : new Set(),
2298
+ });
2299
+ }
2300
+ return dst;
2301
+ }
2033
2302
  console.log(
2034
2303
  ZH
2035
2304
  ? "· git clone 失败,回退到 tarball 直连下载…"
2036
2305
  : "· git clone failed, falling back to direct tarball download…",
2037
2306
  );
2038
2307
  }
2308
+
2039
2309
  const url = `https://codeload.github.com/${src.owner}/${src.repo}/tar.gz/${src.ref || "HEAD"}`;
2040
2310
  console.log(ZH ? `· 下载 ${url}` : `· Downloading ${url}`);
2041
2311
  // 注意:这里不用 fail()/process.exit —— async 上下文里还有未关闭的 socket 时
@@ -2108,9 +2378,9 @@ function findManifestDirs(root) {
2108
2378
  function locatePluginRoot(checkout, subpath, repoLabel) {
2109
2379
  if (subpath) {
2110
2380
  const dir = join(checkout, ...subpath.split("/"));
2111
- if (!existsSync(join(dir, "manifest.json")))
2112
- fail(ZH ? `子目录 "${subpath}" 里没有 manifest.json` : `Subdirectory "${subpath}" has no manifest.json`);
2113
- return dir;
2381
+ if (existsSync(join(dir, "manifest.json"))) return dir;
2382
+ if (existsSync(join(checkout, "manifest.json"))) return checkout;
2383
+ fail(ZH ? `子目录 "${subpath}" 里没有 manifest.json` : `Subdirectory "${subpath}" has no manifest.json`);
2114
2384
  }
2115
2385
  if (existsSync(join(checkout, "manifest.json"))) return checkout;
2116
2386
  const hits = findManifestDirs(checkout);
@@ -2282,19 +2552,86 @@ async function confirmSourceBuild(plan) {
2282
2552
  * 覆盖(备份+保留 config.json)→ 落盘 → 记录来源/sha。
2283
2553
  * 失败抛 Error(目录模式逐条 try/catch 继续下一条,单源模式由调用方转 fail)。
2284
2554
  */
2285
- async function installOnePlugin({ rawSpec, name, force, build, noBuild, dataDir, isCatalog = false }) {
2555
+ async function installOnePlugin({
2556
+ rawSpec,
2557
+ name,
2558
+ force,
2559
+ build,
2560
+ noBuild,
2561
+ dataDir,
2562
+ isCatalog = false,
2563
+ sharedCache = null,
2564
+ remote = false,
2565
+ }) {
2286
2566
  cleanStalePluginTmpDirs();
2287
2567
  const pluginsDir = join(dataDir, "plugins");
2288
- const localCandidate = resolve(rawSpec.replace(/^file:\/\//, ""));
2568
+ let localCandidate = rawSpec;
2569
+ if (/^file:\/\//i.test(rawSpec)) {
2570
+ try {
2571
+ localCandidate = fileURLToPath(rawSpec);
2572
+ } catch {
2573
+ localCandidate = rawSpec.replace(/^file:\/\//i, "");
2574
+ }
2575
+ }
2576
+ localCandidate = resolve(localCandidate);
2289
2577
  const isLocal = existsSync(localCandidate);
2290
2578
  const src = isLocal ? null : parsePluginSource(rawSpec);
2579
+
2580
+ // 随包内置插件快速路径:若随包已自带官方插件且满足版本条件,优先走本地快速通路
2581
+ const localBuiltinDir = isLocal ? null : resolveLocalBuiltinPluginDir(rawSpec, src, { remote });
2582
+ let fastPathCandidate = null;
2583
+ if (localBuiltinDir) {
2584
+ const sourceName = src?.subpath ? src.subpath.split("/").pop() : src?.repo;
2585
+ const fallbackId =
2586
+ String(name ?? sourceName)
2587
+ .replace(/[^A-Za-z0-9_-]/g, "-")
2588
+ .replace(/^-+|-+$/g, "") || "plugin";
2589
+ const id = name ?? fallbackId;
2590
+ const target = join(pluginsDir, id);
2591
+ if (!existsSync(target)) {
2592
+ // 未安装:全新安装直接采用本地随包
2593
+ fastPathCandidate = localBuiltinDir;
2594
+ } else if (force) {
2595
+ // 覆盖更新:对比随包版本与已装版本
2596
+ try {
2597
+ const tgtM = JSON.parse(readFileSync(join(target, "manifest.json"), "utf8"));
2598
+ const srcM = JSON.parse(readFileSync(join(localBuiltinDir, "manifest.json"), "utf8"));
2599
+ if (srcM?.version && tgtM?.version && compareVersions(srcM.version, tgtM.version) > 0) {
2600
+ // 随包版本比已装版本更新(刚升级了主程序),优先直接使用本地随包
2601
+ fastPathCandidate = localBuiltinDir;
2602
+ }
2603
+ } catch {}
2604
+ }
2605
+ }
2606
+
2291
2607
  const tmp = mkdtempSync(join(tmpdir(), "pi-web-ui-plugin-"));
2292
2608
  try {
2293
2609
  let checkout;
2294
- try {
2295
- checkout = isLocal ? localCandidate : await acquireRepo(src, tmp);
2296
- } catch (err) {
2297
- throw new Error(`${err?.message ?? err}`);
2610
+ if (isLocal) {
2611
+ checkout = localCandidate;
2612
+ } else if (fastPathCandidate) {
2613
+ checkout = fastPathCandidate;
2614
+ console.log(
2615
+ ZH
2616
+ ? `· 优先使用本地随包内置插件: ${relative(resolve(BIN_DIR, ".."), checkout).replace(/\\/g, "/")}`
2617
+ : `· Using local bundled plugin: ${relative(resolve(BIN_DIR, ".."), checkout).replace(/\\/g, "/")}`,
2618
+ );
2619
+ } else {
2620
+ try {
2621
+ checkout = await acquireRepo(src, tmp, { sharedCache });
2622
+ } catch (err) {
2623
+ // 若远端拉取失败,且属于官方插件,优雅回退到本地随包(离线与断网容错保护)
2624
+ if (localBuiltinDir && existsSync(join(localBuiltinDir, "manifest.json"))) {
2625
+ console.warn(
2626
+ ZH
2627
+ ? `⚠ 远端拉取失败(${err?.message ?? err}),回退到本地随包内置插件…`
2628
+ : `⚠ Remote fetch failed (${err?.message ?? err}), falling back to bundled local plugin…`,
2629
+ );
2630
+ checkout = localBuiltinDir;
2631
+ } else {
2632
+ throw new Error(`${err?.message ?? err}`);
2633
+ }
2634
+ }
2298
2635
  }
2299
2636
  const repoLabel = isLocal ? localCandidate : `${src.owner}/${src.repo}`;
2300
2637
  const pluginRoot = locatePluginRoot(checkout, src?.subpath, repoLabel);
@@ -2445,10 +2782,22 @@ async function installOnePlugin({ rawSpec, name, force, build, noBuild, dataDir,
2445
2782
  }
2446
2783
  return { id, target, manifest, buildMode: decision.mode };
2447
2784
  } finally {
2448
- try {
2449
- rmSync(tmp, { recursive: true, force: true });
2450
- } catch {
2451
- /* Windows 等平台杀毒/进程占用可能抛 EBUSY,不应翻转已成功的安装 */
2785
+ // 若当前 tmp 正在被 sharedCache 共享复用,不在此清理,留给批量操作统一释放
2786
+ let isCached = false;
2787
+ if (sharedCache) {
2788
+ for (const c of sharedCache.values()) {
2789
+ if (c.tmpDir === tmp) {
2790
+ isCached = true;
2791
+ break;
2792
+ }
2793
+ }
2794
+ }
2795
+ if (!isCached) {
2796
+ try {
2797
+ rmSync(tmp, { recursive: true, force: true });
2798
+ } catch {
2799
+ /* Windows 等平台杀毒/进程占用可能抛 EBUSY,不应翻转已成功的安装 */
2800
+ }
2452
2801
  }
2453
2802
  }
2454
2803
  }
@@ -2637,33 +2986,47 @@ async function installCatalogCmd(opts) {
2637
2986
  let okCount = 0;
2638
2987
  let failCount = 0;
2639
2988
  let skipCount = 0;
2640
- for (const e of entries) {
2641
- if (existsSync(join(pluginsDir, e.id)) && !opts.force) {
2642
- console.log(
2643
- ZH
2644
- ? `· 跳过 ${e.id}(已安装,加 --force 更新)`
2645
- : `· Skipping ${e.id} (already installed, use --force to update)`,
2646
- );
2647
- skipCount++;
2648
- continue;
2989
+ const sharedCache = new Map();
2990
+ try {
2991
+ for (const e of entries) {
2992
+ if (existsSync(join(pluginsDir, e.id)) && !opts.force) {
2993
+ console.log(
2994
+ ZH
2995
+ ? `· 跳过 ${e.id}(已安装,加 --force 更新)`
2996
+ : `· Skipping ${e.id} (already installed, use --force to update)`,
2997
+ );
2998
+ skipCount++;
2999
+ continue;
3000
+ }
3001
+ try {
3002
+ await installOnePlugin({
3003
+ rawSpec: e.source,
3004
+ name: e.id,
3005
+ force: true,
3006
+ build: opts.build === true,
3007
+ noBuild: opts.noBuild === true,
3008
+ dataDir,
3009
+ isCatalog: true,
3010
+ sharedCache,
3011
+ remote: opts.remote === true,
3012
+ });
3013
+ console.log(ZH ? `✔ ${e.id} 安装成功` : `✔ ${e.id} installed`);
3014
+ okCount++;
3015
+ } catch (err) {
3016
+ console.error(
3017
+ ZH ? `✖ ${e.id} 安装失败:${err?.message ?? err}` : `✖ ${e.id} failed to install: ${err?.message ?? err}`,
3018
+ );
3019
+ failCount++;
3020
+ }
2649
3021
  }
2650
- try {
2651
- await installOnePlugin({
2652
- rawSpec: e.source,
2653
- name: e.id,
2654
- force: true,
2655
- build: opts.build === true,
2656
- noBuild: opts.noBuild === true,
2657
- dataDir,
2658
- isCatalog: true,
2659
- });
2660
- console.log(ZH ? `✔ ${e.id} 安装成功` : `✔ ${e.id} installed`);
2661
- okCount++;
2662
- } catch (err) {
2663
- console.error(
2664
- ZH ? `✖ ${e.id} 安装失败:${err?.message ?? err}` : `✖ ${e.id} failed to install: ${err?.message ?? err}`,
2665
- );
2666
- failCount++;
3022
+ } finally {
3023
+ // 统一清理同批任务复用的共享缓存检出目录
3024
+ for (const entry of sharedCache.values()) {
3025
+ if (entry.tmpDir) {
3026
+ try {
3027
+ rmSync(entry.tmpDir, { recursive: true, force: true });
3028
+ } catch {}
3029
+ }
2667
3030
  }
2668
3031
  }
2669
3032
  console.log(
@@ -3346,6 +3709,7 @@ async function pluginInstallCmd(argv) {
3346
3709
  build: opts.build === true,
3347
3710
  noBuild: opts.noBuild === true,
3348
3711
  dataDir: pluginDataDir(opts),
3712
+ remote: opts.remote === true,
3349
3713
  });
3350
3714
  console.log(
3351
3715
  ZH
@@ -3565,6 +3929,10 @@ async function serverCmd(argv) {
3565
3929
  ZH ? `不支持的系统服务平台: ${process.platform}` : `Unsupported system service platform: ${process.platform}`,
3566
3930
  );
3567
3931
  }
3932
+ if (!opts.print) {
3933
+ const fallbackToken = process.env.PI_WEB_TOKEN || "";
3934
+ await printRunningServiceAccess(opts, opts.host ?? process.env.PI_WEB_HOST, fallbackToken);
3935
+ }
3568
3936
  break;
3569
3937
  }
3570
3938
  case "uninstall": {
@@ -3582,8 +3950,13 @@ async function serverCmd(argv) {
3582
3950
  break;
3583
3951
  }
3584
3952
  case "start":
3953
+ case "restart": {
3954
+ controlService(action, opts);
3955
+ const fallbackToken = process.env.PI_WEB_TOKEN || "";
3956
+ await printRunningServiceAccess(opts, opts.host ?? process.env.PI_WEB_HOST, fallbackToken);
3957
+ break;
3958
+ }
3585
3959
  case "stop":
3586
- case "restart":
3587
3960
  controlService(action, opts);
3588
3961
  break;
3589
3962
  case "status":
@@ -0,0 +1,5 @@
1
+ 已在 commit 9e04e099 中彻底修复并闭环:
2
+
3
+ 1. **Markdown 链接与图片拦截转写**:在 `web/src/components/Markdown.tsx` 中拦截相对路径(如 `output/summary.md`)和绝对路径,自动转换为受鉴权保护的工作区直链(HTML 文件走 `/api/preview` 沙箱隔离预览,其他文件走 `/api/file` 原生打开/流式播放);
4
+ 2. **服务端直开权限完善**:更新 `server/index.ts` 放行合法工作区文本/数据文件(配合 `nosniff` 与沙箱),不再返回 400 阻断;
5
+ 3. **适配远程访问**:`present_files` 探测到远程访问时,自动将本地窗口唤醒按钮替换为新标签页打开。