pi-web-ui 0.111.0 → 0.112.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 (77) hide show
  1. package/CHANGELOG.md +55 -2
  2. package/bin/frp-manager.mjs +9 -2
  3. package/dist/server/agent-service.js +1325 -488
  4. package/dist/server/approval-audit.js +119 -0
  5. package/dist/server/approval-default-rules.js +4 -4
  6. package/dist/server/approval-rules.js +42 -17
  7. package/dist/server/attachment-store.js +8 -8
  8. package/dist/server/canvas/canvas-agent-tool.js +6 -0
  9. package/dist/server/canvas/canvas-orchestrator.js +88 -21
  10. package/dist/server/client-state.js +28 -0
  11. package/dist/server/delegate-mode.js +6 -3
  12. package/dist/server/delegate-task.js +18 -3
  13. package/dist/server/dispatch-domain-handlers.js +3 -0
  14. package/dist/server/dsh/dsh-agent-service.js +242 -11
  15. package/dist/server/dsh/dsh-serialize.js +1 -1
  16. package/dist/server/durable/durable-driver.js +75 -9
  17. package/dist/server/durable/durable-loader.js +1 -14
  18. package/dist/server/durable/durable-models.js +107 -0
  19. package/dist/server/durable/index.js +0 -4
  20. package/dist/server/engine-probe.js +76 -37
  21. package/dist/server/eval-tool.js +28 -3
  22. package/dist/server/goal-service.js +7 -0
  23. package/dist/server/index.js +344 -56
  24. package/dist/server/json-utils.js +57 -0
  25. package/dist/server/marker-service.js +8 -0
  26. package/dist/server/message-window.js +43 -10
  27. package/dist/server/model-admin.js +68 -106
  28. package/dist/server/model-resolver.js +66 -44
  29. package/dist/server/plan-manager.js +3 -6
  30. package/dist/server/plugin-api-catalog.js +1 -0
  31. package/dist/server/plugin-assets.js +238 -0
  32. package/dist/server/plugin-facilities.js +22 -0
  33. package/dist/server/plugin-ui-slots.js +1 -0
  34. package/dist/server/plugins.js +199 -5
  35. package/dist/server/preset-fields.js +25 -1
  36. package/dist/server/preset-share.js +5 -2
  37. package/dist/server/prompt-assembler.js +2 -1
  38. package/dist/server/prompt-composer.js +18 -8
  39. package/dist/server/protocol-version.js +1 -1
  40. package/dist/server/queue-utils.js +156 -0
  41. package/dist/server/sdk-builtin-extensions.js +85 -0
  42. package/dist/server/server-config.js +66 -0
  43. package/dist/server/session-parser.js +49 -13
  44. package/dist/server/session-search.js +4 -3
  45. package/dist/server/settings-service.js +38 -5
  46. package/dist/server/soft-cap.js +8 -6
  47. package/dist/server/subagent-helpers.js +22 -1
  48. package/dist/server/subagent-notify.js +93 -0
  49. package/dist/server/subagent-security-gate.js +282 -0
  50. package/dist/server/subagent-templates.js +8 -0
  51. package/dist/server/subagents.js +144 -17
  52. package/dist/server/terminals.js +196 -8
  53. package/dist/server/text-quote.js +61 -0
  54. package/dist/server/tool-approval.js +63 -4
  55. package/dist/server/tool-guards.js +208 -0
  56. package/dist/server/tool-host-factories.js +46 -10
  57. package/dist/server/tool-overrides.js +21 -11
  58. package/dist/server/universal/driver-base.js +8 -0
  59. package/dist/server/universal/drivers/claude-code.js +20 -3
  60. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  61. package/dist/server/universal/index.js +0 -1
  62. package/dist/server/universal/universal-session.js +87 -10
  63. package/dist/server/worktree-service.js +189 -1
  64. package/docs/dsh-engine.md +1 -5
  65. package/package.json +1 -1
  66. package/plugin-sdk/client-utils.mjs +192 -5
  67. package/plugin-sdk/index.d.ts +63 -1
  68. package/plugin-sdk/index.mjs +94 -0
  69. package/plugin-sdk/package.json +5 -1
  70. package/plugins/catalog.json +11 -0
  71. package/web/dist/assets/{TerminalPanel-BiUNySMA.js → TerminalPanel-Dqr1dK28.js} +1 -1
  72. package/web/dist/assets/index-Dh8BX-lP.js +720 -0
  73. package/web/dist/assets/index-DqrC1I_a.css +1 -0
  74. package/web/dist/index.html +11 -2
  75. package/web/dist/sw.js +1 -1
  76. package/web/dist/assets/index-B0ajS__T.js +0 -697
  77. package/web/dist/assets/index-BHik5WGG.css +0 -1
@@ -0,0 +1,238 @@
1
+ /**
2
+ * 宿主插件重资产流水线(Heavy Asset Pipeline):
3
+ *
4
+ * 为插件提供体系化的重型依赖/二进制资产生命周期管理:
5
+ * 1. 规范化资产声明与探测(存在即秒过);
6
+ * 2. 多源候选与国内透明镜像自动回落(GitHub Release -> 镜像加速);
7
+ * 3. 并发防重入单例锁(同资产并发请求安全合并);
8
+ * 4. SHA-256 流式强完整性验签(防篡改与坏包解压);
9
+ * 5. Staging 隔离解压与原子安全替换;
10
+ * 6. 细粒度下载进度透传与日志归因。
11
+ */
12
+ import { execSync } from "node:child_process";
13
+ import { createHash } from "node:crypto";
14
+ import { createWriteStream, existsSync, mkdirSync, renameSync, rmSync, unlinkSync } from "node:fs";
15
+ import { isAbsolute, join, resolve } from "node:path";
16
+ // 模块级并发单例锁:Key 为 `pluginDir:assetId`
17
+ const activeAssetPromises = new Map();
18
+ const assetProgressState = new Map();
19
+ /**
20
+ * 构建多源候选 URL 列表:
21
+ * 1. 用户自定义环境变量(PI_WEB_ASSET_MIRROR)优先拼装;
22
+ * 2. 保留原 Spec 列表;
23
+ * 3. 若含 GitHub 官方 Release,自动追加国内知名稳定加速镜像(如 ghfast.top)。
24
+ */
25
+ export function buildAssetCandidateUrls(specUrls) {
26
+ const out = [];
27
+ const seen = new Set();
28
+ function push(u) {
29
+ if (!u)
30
+ return;
31
+ const trimmed = u.trim();
32
+ if (!trimmed || seen.has(trimmed))
33
+ return;
34
+ seen.add(trimmed);
35
+ out.push(trimmed);
36
+ }
37
+ const mirrorPrefix = process.env.PI_WEB_ASSET_MIRROR?.trim();
38
+ for (const url of specUrls) {
39
+ if (!url)
40
+ continue;
41
+ // 用户自定义镜像前缀置顶
42
+ if (mirrorPrefix) {
43
+ const prefix = mirrorPrefix.endsWith("/") ? mirrorPrefix : `${mirrorPrefix}/`;
44
+ if (url.startsWith("http://") || url.startsWith("https://")) {
45
+ push(`${prefix}${url}`);
46
+ }
47
+ }
48
+ // 官方直链
49
+ push(url);
50
+ // 若为 GitHub 链接且未关闭镜像,自动追加通用透明反代镜像回落
51
+ if (process.env.PI_WEB_ASSET_AUTO_MIRROR !== "0" &&
52
+ process.env.PI_WEB_ASSET_AUTO_MIRROR !== "false" &&
53
+ (url.includes("github.com/") || url.includes("githubusercontent.com/"))) {
54
+ push(`https://ghfast.top/${url}`);
55
+ }
56
+ }
57
+ return out;
58
+ }
59
+ /** 规范化目标绝对路径 */
60
+ export function resolveTargetDir(pluginDir, targetDir) {
61
+ return isAbsolute(targetDir) ? resolve(targetDir) : resolve(pluginDir, targetDir);
62
+ }
63
+ /** 查询指定资产在本地的就绪状态与实时进度 */
64
+ export function getPluginAssetStatus(pluginDir, spec) {
65
+ const absTarget = resolveTargetDir(pluginDir, spec.targetDir);
66
+ const lockKey = `${pluginDir}:${spec.id}`;
67
+ const current = assetProgressState.get(lockKey);
68
+ const isReady = spec.testFile ? existsSync(join(absTarget, spec.testFile)) : existsSync(absTarget);
69
+ return {
70
+ ready: isReady,
71
+ downloading: Boolean(current?.downloading),
72
+ progress: current?.progress ?? (isReady ? 100 : 0),
73
+ downloaded: current?.downloaded ?? 0,
74
+ total: current?.total ?? spec.size ?? 0,
75
+ error: current?.error ?? null,
76
+ };
77
+ }
78
+ /**
79
+ * 确保资产就绪:
80
+ * 若本地已就绪则秒级通过;否则进入流式多源下载、SHA-256 验签、Staging 解压替换流水线。
81
+ */
82
+ export async function ensurePluginAsset(pluginDir, spec, opts = {}) {
83
+ const absTarget = resolveTargetDir(pluginDir, spec.targetDir);
84
+ const lockKey = `${pluginDir}:${spec.id}`;
85
+ // 1. 检查本地已有状态
86
+ const readyNow = spec.testFile ? existsSync(join(absTarget, spec.testFile)) : existsSync(absTarget);
87
+ if (readyNow) {
88
+ return { ok: true, targetDir: absTarget, cached: true };
89
+ }
90
+ // 2. 并发合并锁:避免前台并发请求多次写盘
91
+ const inFlight = activeAssetPromises.get(lockKey);
92
+ if (inFlight) {
93
+ return await inFlight;
94
+ }
95
+ const promise = (async () => {
96
+ const log = opts.log ?? ((m) => console.log(`[asset:${spec.id}] ${m}`));
97
+ const candidateUrls = buildAssetCandidateUrls(spec.urls);
98
+ if (candidateUrls.length === 0) {
99
+ throw new Error(`未为资产 ${spec.id} 配置有效的下载源`);
100
+ }
101
+ const status = {
102
+ ready: false,
103
+ downloading: true,
104
+ progress: 0,
105
+ downloaded: 0,
106
+ total: spec.size ?? 0,
107
+ error: null,
108
+ };
109
+ assetProgressState.set(lockKey, status);
110
+ const timeoutMs = opts.timeoutMs ?? 600_000;
111
+ const tempTar = join(pluginDir, `.${spec.id}-download-${Date.now()}.tar.gz`);
112
+ let lastError = null;
113
+ let successUrl = "";
114
+ let computedSha = "";
115
+ try {
116
+ for (let i = 0; i < candidateUrls.length; i++) {
117
+ const currentUrl = candidateUrls[i];
118
+ try {
119
+ log(`[${i + 1}/${candidateUrls.length}] 正在从 ${currentUrl} 下载重资产...`);
120
+ const signals = [AbortSignal.timeout(timeoutMs)];
121
+ if (opts.signal)
122
+ signals.push(opts.signal);
123
+ const signal = AbortSignal.any ? AbortSignal.any(signals) : AbortSignal.timeout(timeoutMs);
124
+ const res = await fetch(currentUrl, { signal });
125
+ if (!res.ok) {
126
+ throw new Error(`HTTP 响应非预期: ${res.status} ${res.statusText}`);
127
+ }
128
+ const contentLength = Number(res.headers.get("content-length") || 0);
129
+ const totalBytes = contentLength > 0 ? contentLength : (spec.size ?? 0);
130
+ status.total = totalBytes;
131
+ const fileStream = createWriteStream(tempTar);
132
+ let streamError = null;
133
+ fileStream.on("error", (e) => {
134
+ streamError = e;
135
+ });
136
+ const hash = createHash("sha256");
137
+ const reader = res.body?.getReader();
138
+ if (!reader)
139
+ throw new Error("无法读取响应体数据流");
140
+ let downloaded = 0;
141
+ while (true) {
142
+ if (streamError)
143
+ throw streamError;
144
+ const { done, value } = await reader.read();
145
+ if (done)
146
+ break;
147
+ if (value) {
148
+ hash.update(value);
149
+ if (!fileStream.write(Buffer.from(value))) {
150
+ await new Promise((r) => fileStream.once("drain", r));
151
+ }
152
+ downloaded += value.length;
153
+ status.downloaded = downloaded;
154
+ if (totalBytes > 0) {
155
+ status.progress = Math.min(100, Math.round((downloaded / totalBytes) * 100));
156
+ }
157
+ opts.onProgress?.({
158
+ downloaded,
159
+ total: totalBytes,
160
+ percent: status.progress,
161
+ url: currentUrl,
162
+ });
163
+ }
164
+ }
165
+ await new Promise((r) => fileStream.end(r));
166
+ if (streamError)
167
+ throw streamError;
168
+ computedSha = hash.digest("hex").toLowerCase();
169
+ // 强完整性验签(Fail-Closed):若哈希不符立即销毁,不进入解压步骤
170
+ if (spec.sha256) {
171
+ const expected = spec.sha256.trim().toLowerCase();
172
+ if (computedSha !== expected) {
173
+ throw new Error(`SHA-256 完整性验签失败!期望: ${expected},实际: ${computedSha}`);
174
+ }
175
+ log(`SHA-256 强校验通过: ${computedSha}`);
176
+ }
177
+ successUrl = currentUrl;
178
+ break; // 下载且验签成功,退出候选重试循环
179
+ }
180
+ catch (err) {
181
+ lastError = err;
182
+ log(`下载源 ${currentUrl} 失败: ${err.message || String(err)}`);
183
+ try {
184
+ unlinkSync(tempTar);
185
+ }
186
+ catch { }
187
+ }
188
+ }
189
+ if (!successUrl) {
190
+ throw lastError || new Error(`所有 ${candidateUrls.length} 个候选下载源均尝试失败`);
191
+ }
192
+ log(`下载完成,正在进行 Staging 隔离解压与原子就绪...`);
193
+ const stagingDir = join(pluginDir, `.staging-${spec.id}-${Date.now()}`);
194
+ mkdirSync(stagingDir, { recursive: true });
195
+ try {
196
+ // 调用跨平台 tar 工具解压(--force-local 防 Windows 盘符冒号被识别为远程主机)
197
+ execSync(`tar --force-local -xzf "${tempTar}" -C "${stagingDir}"`, { windowsHide: true });
198
+ // 检查 staging 内部形态(若内部包装了同名子目录,取子目录内容)
199
+ const subDir = join(stagingDir, spec.targetDir);
200
+ const sourceRoot = existsSync(subDir) ? subDir : stagingDir;
201
+ // 替换目标目录
202
+ rmSync(absTarget, { recursive: true, force: true });
203
+ mkdirSync(resolve(absTarget, ".."), { recursive: true });
204
+ renameSync(sourceRoot, absTarget);
205
+ }
206
+ catch (e) {
207
+ rmSync(absTarget, { recursive: true, force: true });
208
+ throw new Error(`解压资产失败: ${e.message}`);
209
+ }
210
+ finally {
211
+ rmSync(stagingDir, { recursive: true, force: true });
212
+ try {
213
+ unlinkSync(tempTar);
214
+ }
215
+ catch { }
216
+ }
217
+ status.downloading = false;
218
+ status.ready = true;
219
+ status.progress = 100;
220
+ log(`资产 [${spec.id}] 就绪完毕并已安全挂载至 ${absTarget}`);
221
+ return { ok: true, targetDir: absTarget, sha256: computedSha };
222
+ }
223
+ catch (err) {
224
+ status.downloading = false;
225
+ status.ready = false;
226
+ status.error = err.message || String(err);
227
+ try {
228
+ unlinkSync(tempTar);
229
+ }
230
+ catch { }
231
+ throw err;
232
+ }
233
+ })().finally(() => {
234
+ activeAssetPromises.delete(lockKey);
235
+ });
236
+ activeAssetPromises.set(lockKey, promise);
237
+ return await promise;
238
+ }
@@ -143,6 +143,28 @@ export class PluginStorage {
143
143
  }
144
144
  });
145
145
  }
146
+ has(key) {
147
+ return key in this.load();
148
+ }
149
+ keys() {
150
+ return Object.keys(this.load());
151
+ }
152
+ clear(preserveSettings = true) {
153
+ void withFileRmwLock(this.file, () => {
154
+ const store = this.readFromDisk();
155
+ const newStore = {};
156
+ if (preserveSettings && "settings" in store) {
157
+ newStore.settings = store.settings;
158
+ }
159
+ try {
160
+ atomicWrite(this.file, JSON.stringify(newStore));
161
+ this.cache = newStore;
162
+ }
163
+ catch (err) {
164
+ console.error(`[plugin-storage] 写入失败 (${this.file}):`, err);
165
+ }
166
+ });
167
+ }
146
168
  delete(key) {
147
169
  // 同 set:写前重读 + RMW 锁,不拿旧快照回写。
148
170
  void withFileRmwLock(this.file, () => {
@@ -16,6 +16,7 @@ export const UI_SLOTS = new Set([
16
16
  "contextmenu.project",
17
17
  "contextmenu.file",
18
18
  "contextmenu.toolcall",
19
+ "tool.card.footer",
19
20
  "settings.pages",
20
21
  "tasks.panel",
21
22
  "leftpanel.projects.actions",
@@ -1,8 +1,10 @@
1
1
  import { registerMarker, unregisterMarker, isBuiltinMarker } from "./markers/index.js";
2
+ import { ensurePluginAsset, getPluginAssetStatus, } from "./plugin-assets.js";
2
3
  import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
3
- import { cpSync, existsSync, lstatSync, readFileSync, readdirSync, renameSync, watch as fsWatch, writeFileSync, } from "node:fs";
4
+ import { cpSync, existsSync, lstatSync, readFileSync, readdirSync, watch as fsWatch, writeFileSync } from "node:fs";
4
5
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
6
  import { pathToFileURL } from "node:url";
7
+ import { writeJsonAtomicSync } from "./atomic-file.js";
6
8
  import {} from "./protocol.js";
7
9
  import { UI_SLOTS } from "./plugin-ui-slots.js";
8
10
  import { LeftPanelRunningStore } from "./left-panel-running.js";
@@ -29,6 +31,8 @@ import { execFile } from "node:child_process";
29
31
  import { promisify } from "node:util";
30
32
  /** 合法插件 id:字母/数字/下划线/连字符,防路径穿越(同 themes.ts 的做法)。 */
31
33
  const ID_RE = /^[A-Za-z0-9_-]+$/;
34
+ /** 合法服务名:字母/数字/下划线/点/连字符,1-64 字符。 */
35
+ const SERVICE_NAME_RE = /^[A-Za-z0-9_.-]+$/;
32
36
  /** 交给插件前的防御性拷贝:provider 回的是快照管线的**活引用** —— messages 数组与
33
37
  * 元素对象都被 60ms 推送管线缓存复用(lastMessagesArray / uiMessageCache),插件原地
34
38
  * 改一个字段/挪一个元素,污染的就是推给真实客户端的快照。浅拷数组 + 元素对象
@@ -270,6 +274,7 @@ export const UI_SLOT_ALIASES = {
270
274
  "sidebar.right": "sidebar.right",
271
275
  leftbar: "sidebar.left",
272
276
  rightbar: "sidebar.right",
277
+ "tool.footer": "tool.card.footer",
273
278
  };
274
279
  /** 合法的条目种类(缺省 action;settings.pages 缺省 page)。 */
275
280
  export const UI_KINDS = new Set([
@@ -949,9 +954,7 @@ lang, secrets) {
949
954
  catch {
950
955
  /* 首次 */
951
956
  }
952
- const tmp = `${file}.tmp-${process.pid}`;
953
- writeFileSync(tmp, JSON.stringify({ ...existing, settings: persist }));
954
- renameSync(tmp, file);
957
+ writeJsonAtomicSync(file, { ...existing, settings: persist }, 0);
955
958
  });
956
959
  }
957
960
  catch (err) {
@@ -1024,6 +1027,10 @@ export class PluginManager {
1024
1027
  * 不落盘、随进程走;只经 plugin_data 按需拉取,绝不进 60ms 快照
1025
1028
  * (与 diagnostics 的“只读诊断随清单下发”正交,互不冲突)。 */
1026
1029
  pluginLogs = new Map();
1030
+ /** 插件间发布的服务表:serviceName → { pluginId: string; service: unknown } */
1031
+ pluginServices = new Map();
1032
+ /** 服务监听者表:serviceName → Set<(service: unknown | undefined) => void> */
1033
+ serviceListeners = new Map();
1027
1034
  constructor(dataDir, cwd,
1028
1035
  /** 随包发布的默认插件列表(<pkgRoot>/plugins/catalog.json)。缺省 = 无内置列表。 */
1029
1036
  builtinCatalogPath) {
@@ -1370,6 +1377,95 @@ export class PluginManager {
1370
1377
  return false;
1371
1378
  return this.proxyRoutes.delete(p);
1372
1379
  }
1380
+ /**
1381
+ * 插件发布一个命名服务。
1382
+ * 同名且被其它插件占有时抛错;同一插件重复 provide 时覆盖。
1383
+ * 返回注销函数(撤销自身发布并广播 undefined)。
1384
+ */
1385
+ provideService(pluginId, name, service) {
1386
+ const trimmed = String(name ?? "").trim();
1387
+ if (!trimmed || !SERVICE_NAME_RE.test(trimmed) || trimmed.length > 64) {
1388
+ throw new Error(`provide: 非法服务名 "${name}"(需由字母、数字、下划线、点或短横线组成,1-64 字符)`);
1389
+ }
1390
+ const existing = this.pluginServices.get(trimmed);
1391
+ if (existing && existing.pluginId !== pluginId) {
1392
+ throw new Error(`provide: 服务 "${trimmed}" 已由插件 "${existing.pluginId}" 注册`);
1393
+ }
1394
+ this.pluginServices.set(trimmed, { pluginId, service });
1395
+ const listeners = this.serviceListeners.get(trimmed);
1396
+ if (listeners) {
1397
+ for (const fn of listeners) {
1398
+ try {
1399
+ fn(service);
1400
+ }
1401
+ catch (err) {
1402
+ console.error(`[plugin:${pluginId}] service listener failed for "${trimmed}":`, err);
1403
+ }
1404
+ }
1405
+ }
1406
+ let revoked = false;
1407
+ return () => {
1408
+ if (revoked)
1409
+ return;
1410
+ revoked = true;
1411
+ const current = this.pluginServices.get(trimmed);
1412
+ if (current && current.pluginId === pluginId) {
1413
+ this.pluginServices.delete(trimmed);
1414
+ const currentListeners = this.serviceListeners.get(trimmed);
1415
+ if (currentListeners) {
1416
+ for (const fn of currentListeners) {
1417
+ try {
1418
+ fn(undefined);
1419
+ }
1420
+ catch (err) {
1421
+ console.error(`[plugin:${pluginId}] service revoked listener failed for "${trimmed}":`, err);
1422
+ }
1423
+ }
1424
+ }
1425
+ }
1426
+ };
1427
+ }
1428
+ getService(name) {
1429
+ const trimmed = String(name ?? "").trim();
1430
+ return this.pluginServices.get(trimmed)?.service;
1431
+ }
1432
+ hasService(name) {
1433
+ const trimmed = String(name ?? "").trim();
1434
+ return this.pluginServices.has(trimmed);
1435
+ }
1436
+ listServices() {
1437
+ const res = [];
1438
+ for (const [name, entry] of this.pluginServices.entries()) {
1439
+ res.push({ name, pluginId: entry.pluginId });
1440
+ }
1441
+ return res;
1442
+ }
1443
+ onService(name, handler) {
1444
+ const trimmed = String(name ?? "").trim();
1445
+ if (!trimmed || typeof handler !== "function")
1446
+ return () => { };
1447
+ let set = this.serviceListeners.get(trimmed);
1448
+ if (!set) {
1449
+ set = new Set();
1450
+ this.serviceListeners.set(trimmed, set);
1451
+ }
1452
+ set.add(handler);
1453
+ const current = this.pluginServices.get(trimmed);
1454
+ if (current !== undefined) {
1455
+ try {
1456
+ handler(current.service);
1457
+ }
1458
+ catch (err) {
1459
+ console.error(`[service:${trimmed}] initial onService handler failed:`, err);
1460
+ }
1461
+ }
1462
+ return () => {
1463
+ set?.delete(handler);
1464
+ if (set && set.size === 0) {
1465
+ this.serviceListeners.delete(trimmed);
1466
+ }
1467
+ };
1468
+ }
1373
1469
  /** index.ts 转发/upgrade 共用:请求路径的最长前缀命中(无命中返回 undefined)。
1374
1470
  * 查表前小写化:注册前缀统一小写归一,大小写混写也命中同一条。 */
1375
1471
  findProxy(path) {
@@ -2190,6 +2286,21 @@ export class PluginManager {
2190
2286
  if (hit.pluginId === p.info.id)
2191
2287
  this.proxyRoutes.delete(prefix);
2192
2288
  }
2289
+ // ③ 兜底:回收该插件发布的服务
2290
+ for (const [name, hit] of this.pluginServices) {
2291
+ if (hit.pluginId === p.info.id) {
2292
+ this.pluginServices.delete(name);
2293
+ const listeners = this.serviceListeners.get(name);
2294
+ if (listeners) {
2295
+ for (const fn of listeners) {
2296
+ try {
2297
+ fn(undefined);
2298
+ }
2299
+ catch { }
2300
+ }
2301
+ }
2302
+ }
2303
+ }
2193
2304
  }
2194
2305
  /** 反激活单个插件:deactivate + 注销 AI 工具 + 清缓存。
2195
2306
  *
@@ -2257,6 +2368,9 @@ export class PluginManager {
2257
2368
  if (pluginIds.has(this.proxyRoutes.get(prefix).pluginId))
2258
2369
  this.proxyRoutes.delete(prefix);
2259
2370
  }
2371
+ // ④ 兜底:清理插件间服务
2372
+ this.pluginServices.clear();
2373
+ this.serviceListeners.clear();
2260
2374
  if (this.panelPushTimer) {
2261
2375
  clearTimeout(this.panelPushTimer);
2262
2376
  this.panelPushTimer = null;
@@ -2289,6 +2403,17 @@ export class PluginManager {
2289
2403
  const builtinDir = dirname(this.builtinCatalogPath);
2290
2404
  if (!existsSync(builtinDir))
2291
2405
  return;
2406
+ // 确保数据目录下同步最新 plugin-sdk(供官方与自定义插件共享纯 ESM 工具层)
2407
+ const builtinSdkDir = join(dirname(builtinDir), "plugin-sdk");
2408
+ const targetSdkDir = join(this.dataDir, "plugin-sdk");
2409
+ if (existsSync(builtinSdkDir)) {
2410
+ try {
2411
+ cpSync(builtinSdkDir, targetSdkDir, { recursive: true });
2412
+ }
2413
+ catch {
2414
+ /* best-effort */
2415
+ }
2416
+ }
2292
2417
  let names;
2293
2418
  try {
2294
2419
  names = readdirSync(this.pluginsDir);
@@ -2466,6 +2591,7 @@ export class PluginManager {
2466
2591
  settingsSchema: settingsSchemaForScan,
2467
2592
  settingsValues: resolvedSettingsForScan.values,
2468
2593
  settingsSources: resolvedSettingsForScan.sources,
2594
+ isolated: m.isolated === true || m.shadow === true ? true : undefined,
2469
2595
  // 可渲染的 fenced-code 语言(manifest "renderers")——前端据此按需加载
2470
2596
  renderers: Array.isArray(m.renderers)
2471
2597
  ? m.renderers.filter((r) => typeof r === "string" && r.length > 0).slice(0, 32)
@@ -2878,7 +3004,7 @@ export class PluginManager {
2878
3004
  if (!targetReal)
2879
3005
  throw new Error(`无法解析真实路径:${abs}`);
2880
3006
  const granted = self.grants.list().find((g) => g.pluginId === info.id)?.paths ?? [];
2881
- for (const r of [self.cwdValue, ...granted]) {
3007
+ for (const r of [self.cwdValue, ...self.workspaceRoots, ...granted]) {
2882
3008
  const rootReal = realPathOfNearest(resolve(r)) ?? resolve(r);
2883
3009
  if (isInsideRoot(rootReal, targetReal))
2884
3010
  return;
@@ -3017,6 +3143,7 @@ export class PluginManager {
3017
3143
  passthrough.thinkingLevel = thinkingLevel.slice(0, 64);
3018
3144
  return self.chatProvider(info.id, passthrough);
3019
3145
  };
3146
+ let pluginAbort = null;
3020
3147
  const host = {
3021
3148
  broadcast: (payload) => this.broadcast(info.id, payload),
3022
3149
  notify: (level, text, textEn) => this.notifyAll(level, text, textEn),
@@ -3295,6 +3422,22 @@ export class PluginManager {
3295
3422
  },
3296
3423
  getPluginCommands: () => this.listCommands(),
3297
3424
  storage,
3425
+ services: {
3426
+ provide: (name, service) => {
3427
+ const revoke = self.provideService(info.id, name, service);
3428
+ return effects.add(`service:${name}`, revoke);
3429
+ },
3430
+ get: (name) => self.getService(name),
3431
+ has: (name) => self.hasService(name),
3432
+ list: () => self.listServices(),
3433
+ on: (name, handler) => {
3434
+ const off = self.onService(name, handler);
3435
+ return effects.add(`service_listener:${name}`, off);
3436
+ },
3437
+ },
3438
+ provide: (name, service) => host.services.provide(name, service),
3439
+ get: (name) => host.services.get(name),
3440
+ onService: (name, handler) => host.services.on(name, handler),
3298
3441
  secrets,
3299
3442
  ensureDeps: (specs, opts) => ensurePluginDeps(dir, specs ?? [], opts?.onProgress),
3300
3443
  route: (method, path, handler) => {
@@ -4199,6 +4342,48 @@ export class PluginManager {
4199
4342
  .slice(0, 64) || "anonymous";
4200
4343
  return effects.add(`plugin:${name}`, dispose);
4201
4344
  },
4345
+ resolveInWorkspace: (relOrAbsPath) => {
4346
+ const target = resolve(self.cwdValue, String(relOrAbsPath ?? ""));
4347
+ if (!self.isInsideWorkspace(target)) {
4348
+ const err = new Error("路径超出工作区范围");
4349
+ err.statusCode = 403;
4350
+ throw err;
4351
+ }
4352
+ return target;
4353
+ },
4354
+ fetch: async (input, init) => {
4355
+ if (!pluginAbort) {
4356
+ pluginAbort = new AbortController();
4357
+ effects.add("plugin:fetch-abort", () => {
4358
+ try {
4359
+ pluginAbort?.abort();
4360
+ }
4361
+ catch { }
4362
+ });
4363
+ }
4364
+ const timeoutMs = Math.max(100, Math.min(Number(init?.timeoutMs ?? 30_000) || 30_000, 600_000));
4365
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
4366
+ const signals = [pluginAbort.signal, timeoutSignal];
4367
+ if (init?.signal)
4368
+ signals.push(init.signal);
4369
+ const combinedSignal = AbortSignal.any
4370
+ ? AbortSignal.any(signals)
4371
+ : init?.signal || timeoutSignal;
4372
+ return await fetch(input, {
4373
+ ...init,
4374
+ signal: combinedSignal,
4375
+ });
4376
+ },
4377
+ assets: {
4378
+ ensure: (spec, opts) => {
4379
+ return ensurePluginAsset(dir, spec, {
4380
+ ...opts,
4381
+ signal: pluginAbort?.signal,
4382
+ log: (msg) => host.log(msg),
4383
+ });
4384
+ },
4385
+ status: (spec) => getPluginAssetStatus(dir, spec),
4386
+ },
4202
4387
  };
4203
4388
  try {
4204
4389
  // Node 对同一 URL 的 import() 永远返回缓存模块——追加 epoch 作查询串
@@ -4273,12 +4458,21 @@ export function resolvePluginClientFile(pluginsDir, id, rest) {
4273
4458
  return null;
4274
4459
  return abs;
4275
4460
  }
4461
+ /** 解析插件公共模块静态文件绝对路径(防止路径穿越)。 */
4462
+ export function resolvePluginSharedFile(sharedDir, rest) {
4463
+ const root = resolve(sharedDir);
4464
+ const abs = resolve(root, rest);
4465
+ if (abs !== root && !abs.startsWith(root + sep))
4466
+ return null;
4467
+ return abs;
4468
+ }
4276
4469
  /** 通用代理前缀的保留字:命中即拒绝注册(宿主自用路径,代理抢了会吞掉主站功能)。 */
4277
4470
  export const PROXY_RESERVED_PREFIXES = [
4278
4471
  "/api",
4279
4472
  "/ws",
4280
4473
  "/plugins",
4281
4474
  "/plugins-api",
4475
+ "/plugins-shared",
4282
4476
  "/assets",
4283
4477
  "/icons",
4284
4478
  "/themes",
@@ -30,6 +30,7 @@ export const PRESET_FIELD_GROUPS = {
30
30
  "customSystemPrompt",
31
31
  "promptTemplate",
32
32
  "promptOverrides",
33
+ "promptDisabled",
33
34
  "reviewPrompt",
34
35
  "reviewDisabledSkills",
35
36
  ],
@@ -65,6 +66,8 @@ export const PRESET_FIELD_GROUPS = {
65
66
  "softCapTokens",
66
67
  "softCapByModel",
67
68
  "subagentDefaultModel",
69
+ "subagentMaxDepth",
70
+ "subagentAutoWakeMaxTurns",
68
71
  "visionBridgeEnabled",
69
72
  "visionBridgeModel",
70
73
  "visionBridgePromptMode",
@@ -173,6 +176,12 @@ export const PRESET_FIELD_META = {
173
176
  hintZh: "仅在目标审查阶段禁止审查者调用的技能列表",
174
177
  hintEn: "Skills unavailable to the reviewer in Goal Mode",
175
178
  },
179
+ promptDisabled: {
180
+ labelZh: "禁用的提示词段",
181
+ labelEn: "Disabled Prompt Sections",
182
+ hintZh: "组合模板中不渲染的提示词段(如 soul/skills)",
183
+ hintEn: "Prompt sections excluded from the composed template",
184
+ },
176
185
  // tools
177
186
  disabledAgentTools: {
178
187
  labelZh: "禁用的内置工具",
@@ -333,6 +342,18 @@ export const PRESET_FIELD_META = {
333
342
  hintZh: "派生子代理时优先使用的专用模型(留空跟随主对话)",
334
343
  hintEn: "Dedicated model for subagents (empty to follow main chat)",
335
344
  },
345
+ subagentMaxDepth: {
346
+ labelZh: "子代理最大嵌套层数",
347
+ labelEn: "Subagent Max Depth",
348
+ hintZh: "主对话下最多几层子代理(0 = 不限制,1 = 子代理不能再派发)",
349
+ hintEn: "Max subagent layers below the main chat (0 = unlimited, 1 = subagents cannot spawn)",
350
+ },
351
+ subagentAutoWakeMaxTurns: {
352
+ labelZh: "子代理自动唤醒轮数上限",
353
+ labelEn: "Subagent Max Auto-Wake Rounds",
354
+ hintZh: "连续自动唤醒父对话的最大轮数(默认 5,0 = 不限制,挂起期间通知不丢)",
355
+ hintEn: "Max consecutive autonomous wake rounds (default 5, 0 = unlimited; buffered on suspend)",
356
+ },
336
357
  visionBridgeEnabled: {
337
358
  labelZh: "视觉桥 (看图转写)",
338
359
  labelEn: "Vision Bridge",
@@ -602,7 +623,10 @@ export function formatPresetFieldValue(field, value, lang = "zh") {
602
623
  };
603
624
  }
604
625
  // 4. 技能 / 扩展禁用列表
605
- if (field === "disabledSkills" || field === "disabledExtensions" || field === "reviewDisabledSkills") {
626
+ if (field === "disabledSkills" ||
627
+ field === "disabledExtensions" ||
628
+ field === "reviewDisabledSkills" ||
629
+ field === "promptDisabled") {
606
630
  const list = Array.isArray(value) ? value.filter((x) => typeof x === "string" && Boolean(x)) : [];
607
631
  if (list.length === 0) {
608
632
  return { summary: isZh ? "全部启用(无禁用)" : "All enabled (none disabled)" };
@@ -31,10 +31,9 @@ import { pick } from "./i18n.js";
31
31
  import { normalizeSoftCapByModel, normalizeSoftCapTokens } from "./soft-cap.js";
32
32
  import { ALL_KNOWN_AGENT_TOOL_NAMES, isConfigurableAgentTool, normalizeDisabledAgentTools, resolveDisabledAgentToolsFromEnabled, resolveEnabledAgentTools, } from "./tool-manager.js";
33
33
  import { normalizeToolPromptOverrides } from "./tool-prompt-overrides.js";
34
- import { isBlockedHost, isNativeGlobalFetch, resolveAndValidateUrl, validateFetchUrl, } from "./net-guard.js";
34
+ import { isNativeGlobalFetch, resolveAndValidateUrl, validateFetchUrl } from "./net-guard.js";
35
35
  import { PRESET_FIELD_NAMES, normalizePresetFieldSelection } from "./preset-fields.js";
36
36
  import { defaultFetcher } from "./update-check.js";
37
- export { isBlockedHost, resolveAndValidateUrl, validateFetchUrl };
38
37
  const execFileAsync = promisify(execFile);
39
38
  /** 预览文本的截断长度(设置面板展示用)。 */
40
39
  const PREVIEW_TEXT_MAX = 400;
@@ -226,6 +225,7 @@ const PRESET_FIELD_KINDS = {
226
225
  customSystemPrompt: "text",
227
226
  promptTemplate: "text",
228
227
  promptOverrides: "textMap",
228
+ promptDisabled: "list",
229
229
  reviewPrompt: "text",
230
230
  reviewDisabledSkills: "list",
231
231
  // -- tools -----------------------------------------------------------
@@ -258,6 +258,8 @@ const PRESET_FIELD_KINDS = {
258
258
  softCapTokens: "softCap",
259
259
  softCapByModel: "softCapByModel",
260
260
  subagentDefaultModel: "nullableString",
261
+ subagentMaxDepth: "number",
262
+ subagentAutoWakeMaxTurns: "number",
261
263
  visionBridgeEnabled: "bool",
262
264
  visionBridgeModel: "nullableString",
263
265
  visionBridgePromptMode: "promptMode",
@@ -992,6 +994,7 @@ export function buildImportPreview(name, doc, sanitized, replaces) {
992
994
  reviewPrompt: (preset.reviewPrompt ?? "").slice(0, PREVIEW_TEXT_MAX),
993
995
  disabledSkills: preset.disabledSkills ?? [],
994
996
  disabledExtensions: preset.disabledExtensions ?? [],
997
+ promptDisabled: preset.promptDisabled ?? [],
995
998
  };
996
999
  }
997
1000
  /** preset_import / preset_import_url 的共同后段:预览 →(非 dryRun)落盘 →(可选)应用。 */