pi-web-ui 0.87.2 → 0.88.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.
@@ -22,6 +22,8 @@ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
22
22
  import { pathToFileURL, fileURLToPath } from "node:url";
23
23
  import { pick } from "./i18n.js";
24
24
  import { PluginStorage, PluginSecrets, ensurePluginDeps, WorkspaceFS } from "./plugin-facilities.js";
25
+ import { parseCronSpec, nextCronFire, loadScheduleRecords, saveScheduleRecords, } from "./plugin-schedule.js";
26
+ import { PluginPermissionStore } from "./plugin-permissions.js";
25
27
  import { readCatalog, addCustomEntry, removeCustomEntry } from "./plugin-catalog.js";
26
28
  import { PluginGrantsStore, normalizeGrantPath } from "./plugin-grants.js";
27
29
  import { PluginDomConsent, declarationWantsDom } from "./plugin-dom.js";
@@ -33,6 +35,49 @@ import { execFile } from "node:child_process";
33
35
  import { promisify } from "node:util";
34
36
  /** 合法插件 id:字母/数字/下划线/连字符,防路径穿越(同 themes.ts 的做法)。 */
35
37
  const ID_RE = /^[A-Za-z0-9_-]+$/;
38
+ /** 每插件保留最近 N 条运行时日志(内存封顶,防刷爆)。 */
39
+ export const PLUGIN_LOG_CAP = 200;
40
+ /** 单条日志文本截断上限(字符)。 */
41
+ export const PLUGIN_LOG_TEXT_MAX = 500;
42
+ const PLUGIN_LOG_LEVELS = new Set(["debug", "info", "warn", "error"]);
43
+ /** host.log 首参归一:是合法级别即当级别,否则缺省 info
44
+ * (老插件 host.log(...args) 的兼容口径)。纯函数,可单测。 */
45
+ export function normalizePluginLogLevel(first) {
46
+ return typeof first === "string" && PLUGIN_LOG_LEVELS.has(first) ? first : "info";
47
+ }
48
+ /** host.log 参数 → 文本(string 原样,其余 JSON/String 化,空格拼接,截断封顶)。
49
+ * 纯函数,可单测。 */
50
+ export function formatPluginLogText(args) {
51
+ const parts = args.map((a) => {
52
+ if (typeof a === "string")
53
+ return a;
54
+ try {
55
+ const s = JSON.stringify(a);
56
+ return typeof s === "string" ? s : String(a);
57
+ }
58
+ catch {
59
+ try {
60
+ return String(a);
61
+ }
62
+ catch {
63
+ return "[unprintable]";
64
+ }
65
+ }
66
+ });
67
+ const text = parts.join(" ");
68
+ return text.length > PLUGIN_LOG_TEXT_MAX ? text.slice(0, PLUGIN_LOG_TEXT_MAX) : text;
69
+ }
70
+ /** 宿主保留的日志通道键(plugin_message 上行 / plugin_data 下行共用)。
71
+ * 插件自己的 onMessage 收不到它(handleMessage 顶部拦截),插件视图侧同理
72
+ * 由前端 ingestPluginLogsData 拦截——插件协议与宿主通道互不干扰。 */
73
+ export const PLUGIN_LOGS_HOST_KEY = "__host";
74
+ /** 是否为宿主保留的日志拉取请求(op 缺省按 get 容错)。 */
75
+ export function isPluginLogsRequest(p) {
76
+ if (!p || typeof p !== "object")
77
+ return false;
78
+ const o = p;
79
+ return o[PLUGIN_LOGS_HOST_KEY] === "logs" && (o.op === "get" || o.op === "clear" || o.op === undefined);
80
+ }
36
81
  /** 宿主提供的插件设施版本——manifest 声明的 apiVersion 高于此值则拒绝激活,
37
82
  * 插件能拿到明确的「请升级 pi-web-ui」而不是在新接口上莫名 undefined。
38
83
  * 1 = 初始:storage/secrets/命令/HTTP 路由/工具注册/受限 fs/后台任务。
@@ -115,7 +160,7 @@ export function readHostVersion() {
115
160
  // ---------------------------------------------------------------------------
116
161
  // 声明式设置 schema(manifest "settings")
117
162
  // ---------------------------------------------------------------------------
118
- const SETTING_TYPES = new Set(["text", "password", "number", "boolean", "select"]);
163
+ const SETTING_TYPES = new Set(["text", "password", "number", "boolean", "select", "secret"]);
119
164
  /**
120
165
  * 解析 manifest "ui" 的某个 slot 数组 → 规范化条目(issue #146 完整版)。
121
166
  *
@@ -127,6 +172,7 @@ const UI_SLOTS = new Set([
127
172
  "topbar.primary",
128
173
  "topbar.overflow",
129
174
  "bottombar",
175
+ "composer.leading",
130
176
  "composer.actions",
131
177
  "message.actions",
132
178
  "rightpanel.tabs",
@@ -143,6 +189,7 @@ const UI_SLOTS = new Set([
143
189
  "scm.toolbar",
144
190
  "goalbar.actions",
145
191
  "notice.actions",
192
+ "modal.dialog",
146
193
  ]);
147
194
  /** manifest 里可以写更自然的简写(作者少踩坑):解析时映射到完整 slot 名。 */
148
195
  const UI_SLOT_ALIASES = {
@@ -152,6 +199,7 @@ const UI_SLOT_ALIASES = {
152
199
  message: "message.actions",
153
200
  rightpanel: "rightpanel.tabs",
154
201
  settings: "settings.pages",
202
+ modal: "modal.dialog",
155
203
  };
156
204
  /** 合法的条目种类(缺省 action;settings.pages 缺省 page)。 */
157
205
  const UI_KINDS = new Set([
@@ -165,6 +213,7 @@ const UI_KINDS = new Set([
165
213
  "toggle",
166
214
  "input",
167
215
  "progress",
216
+ "select",
168
217
  ]);
169
218
  /** 合法的对齐取值(UiAlign):起首/居中/行尾,非法值丢弃(条目保留,align 回缺省)。 */
170
219
  const UI_ALIGNS = new Set(["start", "center", "end"]);
@@ -175,36 +224,146 @@ export function parseUiAlign(raw) {
175
224
  function trimStr(v, max = 60) {
176
225
  return typeof v === "string" && v.trim() ? v.trim().slice(0, max) : undefined;
177
226
  }
178
- /** 规范化一个条目;非法返回 null(slot 由调用方给)。 */
179
- export function parseUiItem(raw, slot) {
180
- if (!raw || typeof raw !== "object")
227
+ /** 原字符串 trim 后是否超出上限(截断诊断用)。 */
228
+ function wasTruncated(v, max) {
229
+ return typeof v === "string" && v.trim().length > max;
230
+ }
231
+ /** 规范化一个条目;非法返回 null(slot 由调用方给)。
232
+ *
233
+ * 第三个参数可选:传了就把“为什么丢弃/为什么被改”(未知 kind 回落、字段截断、
234
+ * children 嵌套被清、when/options 丢项等)逐条 push 进去;不传则行为与原来完全一致。 */
235
+ export function parseUiItem(raw, slot, diagnostics) {
236
+ const diag = (m) => {
237
+ diagnostics?.push(m);
238
+ };
239
+ if (!raw || typeof raw !== "object") {
240
+ diag(`ui item in slot "${slot}": not an object, dropped`);
181
241
  return null;
242
+ }
182
243
  const o = raw;
244
+ const rawIdHint = typeof o.id === "string" && o.id.trim() ? o.id.trim().slice(0, 32) : "?";
183
245
  const id = trimStr(o.id, 64);
184
246
  // id 必须匹配插件 id 字符集(它与 pluginId 拼成全局 key,直接进 DOM 的 data 属性)
185
- if (!id || !ID_RE.test(id))
247
+ if (!id || !ID_RE.test(id)) {
248
+ diag(`ui item in slot "${slot}": invalid id "${rawIdHint}", dropped`);
186
249
  return null;
250
+ }
251
+ if (wasTruncated(o.id, 64))
252
+ diag(`ui item "${id}": id truncated to 64 chars`);
187
253
  const label = trimStr(o.label, 60);
188
- if (!label)
254
+ if (!label) {
255
+ diag(`ui item "${id}": missing label, dropped`);
189
256
  return null;
257
+ }
258
+ if (wasTruncated(o.label, 60))
259
+ diag(`ui item "${id}": label truncated to 60 chars`);
190
260
  const kindRaw = trimStr(o.kind, 16);
191
261
  let kind = kindRaw && UI_KINDS.has(kindRaw) ? kindRaw : undefined;
262
+ if (kindRaw && !kind)
263
+ diag(`ui item "${id}": unknown kind "${kindRaw}", fallback to default`);
192
264
  if (!kind)
193
265
  kind = slot === "settings.pages" ? "page" : "action";
194
266
  const children = [];
195
267
  if (Array.isArray(o.children)) {
196
- for (const c of o.children.slice(0, 16)) {
197
- const child = parseUiItem(c, slot);
268
+ if (o.children.length > 16)
269
+ diag(`ui item "${id}": children capped at 16 (${o.children.length - 16} dropped)`);
270
+ const sliced = o.children.slice(0, 16);
271
+ for (let i = 0; i < sliced.length; i++) {
272
+ const before = diagnostics?.length ?? 0;
273
+ const child = parseUiItem(sliced[i], slot, diagnostics);
198
274
  // 子项不再递归(一层够用):清掉它自己的 children 防嵌套刷栈
199
- if (child)
275
+ if (child) {
276
+ if (child.children?.length)
277
+ diag(`ui item "${id}": child "${child.id}" nested children cleared (only one level kept)`);
200
278
  children.push({ ...child, children: undefined });
279
+ }
280
+ else if ((diagnostics?.length ?? 0) === before) {
281
+ diag(`ui item "${id}": child #${i} dropped`);
282
+ }
283
+ }
284
+ }
285
+ else if (o.children !== undefined) {
286
+ diag(`ui item "${id}": children is not an array, ignored`);
287
+ }
288
+ let when;
289
+ if (o.when !== undefined) {
290
+ if (!Array.isArray(o.when)) {
291
+ diag(`ui item "${id}": when is not an array, ignored`);
292
+ }
293
+ else {
294
+ const valid = o.when.filter((x) => typeof x === "string" && x.trim().length > 0);
295
+ if (valid.length < o.when.length)
296
+ diag(`ui item "${id}": when dropped ${o.when.length - valid.length} invalid entries`);
297
+ if (valid.length > 8)
298
+ diag(`ui item "${id}": when capped at 8 (${valid.length - 8} dropped)`);
299
+ const capped = valid.slice(0, 8);
300
+ if (capped.length)
301
+ when = capped;
201
302
  }
202
303
  }
203
- const when = Array.isArray(o.when)
204
- ? o.when.filter((x) => typeof x === "string" && x.trim().length > 0).slice(0, 8)
205
- : undefined;
206
304
  const num = Number(o.order);
305
+ if (o.order !== undefined && !Number.isFinite(num))
306
+ diag(`ui item "${id}": invalid order, ignored`);
207
307
  const align = parseUiAlign(o.align);
308
+ if (o.align !== undefined && !align)
309
+ diag(`ui item "${id}": unknown align, default used`);
310
+ // kind="select" 的候选项(最多 32;value 必填,label 缺省回落 value)。
311
+ // 没写 kind 但给了合法 options = 视为 select(少让作者踩坑)。
312
+ let options;
313
+ if ((kind === "select" || !kindRaw) && Array.isArray(o.options)) {
314
+ if (o.options.length > 32)
315
+ diag(`ui item "${id}": options capped at 32 (${o.options.length - 32} dropped)`);
316
+ const list = [];
317
+ let droppedOpts = 0;
318
+ for (const r of o.options.slice(0, 32)) {
319
+ if (!r || typeof r !== "object") {
320
+ droppedOpts++;
321
+ continue;
322
+ }
323
+ const ro = r;
324
+ const value = typeof ro.value === "string" ? ro.value.slice(0, 64) : "";
325
+ if (!value || list.some((x) => x.value === value)) {
326
+ droppedOpts++;
327
+ continue;
328
+ }
329
+ list.push({
330
+ value,
331
+ ...(trimStr(ro.label, 60) ? { label: trimStr(ro.label, 60) } : {}),
332
+ ...(trimStr(ro.labelEn, 60) ? { labelEn: trimStr(ro.labelEn, 60) } : {}),
333
+ });
334
+ }
335
+ if (droppedOpts)
336
+ diag(`ui item "${id}": options dropped ${droppedOpts} invalid/duplicate entries`);
337
+ if (list.length) {
338
+ if (!kindRaw)
339
+ diag(`ui item "${id}": kind inferred as select from options`);
340
+ options = list;
341
+ kind = "select";
342
+ }
343
+ else if (o.options.length) {
344
+ diag(`ui item "${id}": options all invalid, ignored`);
345
+ }
346
+ }
347
+ if (wasTruncated(o.labelEn, 60))
348
+ diag(`ui item "${id}": labelEn truncated to 60 chars`);
349
+ if (wasTruncated(o.icon, 16))
350
+ diag(`ui item "${id}": icon truncated to 16 chars`);
351
+ if (wasTruncated(o.hint, 200))
352
+ diag(`ui item "${id}": hint truncated to 200 chars`);
353
+ if (wasTruncated(o.hintEn, 200))
354
+ diag(`ui item "${id}": hintEn truncated to 200 chars`);
355
+ if (wasTruncated(o.group, 40))
356
+ diag(`ui item "${id}": group truncated to 40 chars`);
357
+ if (wasTruncated(o.action, 64))
358
+ diag(`ui item "${id}": action truncated to 64 chars`);
359
+ if (wasTruncated(o.view, 64))
360
+ diag(`ui item "${id}": view truncated to 64 chars`);
361
+ if (wasTruncated(o.badge, 24))
362
+ diag(`ui item "${id}": badge truncated to 24 chars`);
363
+ if (typeof o.value === "string" && o.value.length > 500)
364
+ diag(`ui item "${id}": value truncated to 500 chars`);
365
+ if (typeof o.progress === "number" && Number.isFinite(o.progress) && (o.progress < 0 || o.progress > 100))
366
+ diag(`ui item "${id}": progress out of range, clamped to 0-100`);
208
367
  return {
209
368
  id,
210
369
  slot: slot,
@@ -228,6 +387,7 @@ export function parseUiItem(raw, slot) {
228
387
  ...(typeof o.progress === "number" && Number.isFinite(o.progress)
229
388
  ? { progress: Math.max(0, Math.min(100, o.progress)) }
230
389
  : {}),
390
+ ...(options ? { options } : {}),
231
391
  };
232
392
  }
233
393
  /**
@@ -238,54 +398,135 @@ export function parseUiItem(raw, slot) {
238
398
  * "ui": { "items": [{ slot, ... }, ...] } // 平铺(运行时注册同形,便于两边复用)
239
399
  * 单条目上限 32、arrange 上限 64 —— 防一份 manifest 把前端顶爆。
240
400
  */
241
- export function parseUiContributions(raw) {
242
- if (!raw || typeof raw !== "object")
401
+ export function parseUiContributions(raw, diagnostics) {
402
+ const diag = (m) => {
403
+ diagnostics?.push(m);
404
+ };
405
+ if (raw === undefined || raw === null)
406
+ return undefined;
407
+ if (typeof raw !== "object" || Array.isArray(raw)) {
408
+ diag("ui: expected object, ignored");
243
409
  return undefined;
410
+ }
244
411
  const o = raw;
245
412
  const items = [];
413
+ let capNoted = false;
414
+ const noteCap = () => {
415
+ if (!capNoted) {
416
+ capNoted = true;
417
+ diag("ui: total items capped at 32, remaining dropped");
418
+ }
419
+ };
246
420
  const push = (it) => {
247
- if (it && items.length < 32)
421
+ if (!it)
422
+ return;
423
+ if (items.length < 32)
248
424
  items.push(it);
425
+ else
426
+ noteCap();
249
427
  };
428
+ // 入参级截断也要记一笔(total cap 消息只在“有效条目溢出”时出现,
429
+ // 这里记的是“写法层面的切片”——两者正交)。
430
+ if (o.items !== undefined && !Array.isArray(o.items))
431
+ diag('ui: "items" is not an array, ignored');
250
432
  if (Array.isArray(o.items)) {
251
- for (const it of o.items.slice(0, 32)) {
252
- const raw = trimStr(it?.slot, 32);
253
- const slot = raw ? (UI_SLOT_ALIASES[raw] ?? raw) : "";
254
- if (!slot || !UI_SLOTS.has(slot))
433
+ if (o.items.length > 32)
434
+ diag(`ui: flat items capped at 32 (${o.items.length - 32} dropped)`);
435
+ for (let i = 0; i < o.items.slice(0, 32).length; i++) {
436
+ const it = o.items[i];
437
+ const slotRaw = trimStr(it?.slot, 32) ?? "";
438
+ const slot = slotRaw ? (UI_SLOT_ALIASES[slotRaw] ?? slotRaw) : "";
439
+ if (!slot || !UI_SLOTS.has(slot)) {
440
+ diag(`ui: flat items[#${i}] unknown slot "${slotRaw || "(missing)"}", dropped`);
255
441
  continue;
256
- push(parseUiItem(it, slot));
442
+ }
443
+ const before = diagnostics?.length ?? 0;
444
+ const parsed = parseUiItem(it, slot, diagnostics);
445
+ if (!parsed && (diagnostics?.length ?? 0) === before)
446
+ diag(`ui: flat items[#${i}] in slot "${slot}" dropped`);
447
+ push(parsed);
257
448
  }
258
449
  }
259
450
  for (const [rawKey, val] of Object.entries(o)) {
260
451
  if (rawKey === "items" || rawKey === "arrange")
261
452
  continue;
262
453
  const key = UI_SLOT_ALIASES[rawKey] ?? rawKey;
263
- if (!UI_SLOTS.has(key) || !Array.isArray(val))
454
+ if (!UI_SLOTS.has(key)) {
455
+ const n = Array.isArray(val) ? val.length : 1;
456
+ diag(`ui: unknown slot group "${rawKey}", dropped (${n} items)`);
457
+ continue;
458
+ }
459
+ if (!Array.isArray(val)) {
460
+ diag(`ui: slot "${key}" value is not an array, dropped`);
264
461
  continue;
265
- for (const it of val.slice(0, 32))
266
- push(parseUiItem(it, key));
462
+ }
463
+ if (val.length > 32)
464
+ diag(`ui: slot "${key}" capped at 32 (${val.length - 32} dropped)`);
465
+ for (let i = 0; i < val.slice(0, 32).length; i++) {
466
+ const before = diagnostics?.length ?? 0;
467
+ const parsed = parseUiItem(val[i], key, diagnostics);
468
+ if (!parsed && (diagnostics?.length ?? 0) === before)
469
+ diag(`ui: slot "${key}"[#${i}] dropped`);
470
+ push(parsed);
471
+ }
267
472
  }
268
- const arrange = parseUiArrange(o.arrange);
269
- if (!items.length && !arrange.length)
473
+ const arrange = o.arrange === undefined ? [] : parseUiArrange(o.arrange, diagnostics);
474
+ if (!items.length && !arrange.length) {
475
+ diag("ui: no valid items/arrange, ignored");
270
476
  return undefined;
477
+ }
271
478
  return { items, arrange };
272
479
  }
273
- /** 规范化整理意图(对内置/其它插件的条目)。非法/越界形状丢弃。 */
274
- export function parseUiArrange(raw) {
275
- if (!Array.isArray(raw))
480
+ /** 规范化整理意图(对内置/其它插件的条目)。非法/越界形状丢弃。
481
+ *
482
+ * 第三个参数可选:传了就把丢弃/忽略原因逐条 push 进去;不传则行为与原来完全一致。 */
483
+ export function parseUiArrange(raw, diagnostics) {
484
+ const diag = (m) => {
485
+ diagnostics?.push(m);
486
+ };
487
+ if (raw === undefined)
276
488
  return [];
489
+ if (!Array.isArray(raw)) {
490
+ diag("ui arrange: expected array, ignored");
491
+ return [];
492
+ }
493
+ if (raw.length > 64)
494
+ diag(`ui arrange: capped at 64 (${raw.length - 64} dropped)`);
277
495
  const out = [];
278
- for (const it of raw.slice(0, 64)) {
279
- if (!it || typeof it !== "object")
496
+ const sliced = raw.slice(0, 64);
497
+ for (let i = 0; i < sliced.length; i++) {
498
+ const it = sliced[i];
499
+ if (!it || typeof it !== "object") {
500
+ diag(`ui arrange[#${i}]: not an object, dropped`);
280
501
  continue;
502
+ }
281
503
  const o = it;
282
504
  // 目标 id:`host:<name>` 或 `<pluginId>:<itemId>`
283
505
  const id = trimStr(o.id, 96);
284
- if (!id || !/^[A-Za-z0-9_-]+:[A-Za-z0-9_.:-]+$/.test(id))
506
+ if (!id || !/^[A-Za-z0-9_-]+:[A-Za-z0-9_.:-]+$/.test(id)) {
507
+ const hint = typeof o.id === "string" && o.id.trim() ? o.id.trim().slice(0, 32) : "?";
508
+ diag(`ui arrange[#${i}]: invalid id "${hint}", dropped`);
285
509
  continue;
510
+ }
511
+ if (typeof o.id === "string" && o.id.trim().length > 96)
512
+ diag(`ui arrange "${id}": id truncated to 96 chars`);
286
513
  const slotRaw = trimStr(o.slot, 32);
514
+ if (o.slot !== undefined && (!slotRaw || !UI_SLOTS.has(slotRaw)))
515
+ diag(`ui arrange "${id}": unknown slot "${String(o.slot).slice(0, 32)}", slot ignored`);
287
516
  const num = Number(o.order);
517
+ if (o.order !== undefined && !Number.isFinite(num))
518
+ diag(`ui arrange "${id}": invalid order, ignored`);
288
519
  const align = parseUiAlign(o.align);
520
+ if (o.align !== undefined && !align)
521
+ diag(`ui arrange "${id}": unknown align, ignored`);
522
+ if (typeof o.group === "string" && o.group.trim().length > 40)
523
+ diag(`ui arrange "${id}": group truncated to 40 chars`);
524
+ if (typeof o.label === "string" && o.label.trim().length > 60)
525
+ diag(`ui arrange "${id}": label truncated to 60 chars`);
526
+ if (typeof o.hint === "string" && o.hint.trim().length > 200)
527
+ diag(`ui arrange "${id}": hint truncated to 200 chars`);
528
+ if (typeof o.icon === "string" && o.icon.trim().length > 16)
529
+ diag(`ui arrange "${id}": icon truncated to 16 chars`);
289
530
  out.push({
290
531
  id,
291
532
  ...(slotRaw && UI_SLOTS.has(slotRaw) ? { slot: slotRaw } : {}),
@@ -344,8 +585,14 @@ function parseSettingsSchema(raw) {
344
585
  }
345
586
  return out;
346
587
  }
347
- /** 从 <pluginDir>/storage.json 读 settings 存值,按 schema 并默认值。 */
348
- function storedSettingsValues(dir, schema) {
588
+ /** secret 设置在 secrets 里的键(与插件手搓的机密键冲突概率极低的前缀)。 */
589
+ function secretSettingKey(key) {
590
+ return `setting:${key}`;
591
+ }
592
+ /** 从 <pluginDir>/storage.json 读 settings 存值,按 schema 并默认值。
593
+ * secret 字段不返回明文:有 secrets 时返回有无(布尔),调用方是浏览器;
594
+ * 插件运行时要真值请用 runtimeSettingsValues。 */
595
+ function storedSettingsValues(dir, schema, secrets) {
349
596
  const out = {};
350
597
  let stored = {};
351
598
  try {
@@ -357,14 +604,45 @@ function storedSettingsValues(dir, schema) {
357
604
  catch {
358
605
  /* 无存储文件 = 全默认 */
359
606
  }
360
- for (const f of schema)
607
+ for (const f of schema) {
608
+ if (f.type === "secret") {
609
+ // 浏览器侧只看到有无(布尔),明文永不下发;无 secrets 上下文(如单测)回落 false。
610
+ out[f.key] = secrets ? secrets.has(secretSettingKey(f.key)) : false;
611
+ continue;
612
+ }
361
613
  out[f.key] = stored[f.key] ?? f.default;
614
+ }
362
615
  return out;
363
616
  }
364
- /** 校验并写回 settings(storage.json 的 settings 键,原子写);返回错误信息或 null。 */
617
+ /** 插件运行时视角的设置值:非 secret 与 storedSettingsValues 同口径;secret 返回真值
618
+ * (无则回落默认值/空串)。只给插件服务端代码用,绝不下发浏览器。 */
619
+ function runtimeSettingsValues(dir, schema, secrets) {
620
+ const out = {};
621
+ let stored = {};
622
+ try {
623
+ const parsed = JSON.parse(readFileSync(join(dir, "storage.json"), "utf8"));
624
+ if (parsed && typeof parsed === "object" && parsed.settings && typeof parsed.settings === "object") {
625
+ stored = parsed.settings;
626
+ }
627
+ }
628
+ catch {
629
+ /* 无存储文件 = 全默认 */
630
+ }
631
+ for (const f of schema) {
632
+ if (f.type === "secret") {
633
+ out[f.key] = secrets.get(secretSettingKey(f.key)) ?? f.default ?? "";
634
+ continue;
635
+ }
636
+ out[f.key] = stored[f.key] ?? f.default;
637
+ }
638
+ return out;
639
+ }
640
+ /** 校验并写回 settings(storage.json 的 settings 键,原子写);返回错误信息或 null。
641
+ * secret 字段写加密 secrets(明文永不落盘、不进 storage.json):空串/缺省 = 不改;
642
+ * 返回的 clean 含 secret 真值(给 onSettingsChanged 用),调用方不得下发浏览器。 */
365
643
  function saveSettingsValues(dir, schema, values,
366
644
  /** 错误文案语言(默认英文);调用方可传 () => getLang() 实现跟随。 */
367
- lang) {
645
+ lang, secrets) {
368
646
  const l = lang?.() ?? "en";
369
647
  const clean = {};
370
648
  for (const f of schema) {
@@ -394,12 +672,42 @@ lang) {
394
672
  };
395
673
  clean[f.key] = v === undefined ? f.default : String(v);
396
674
  }
675
+ else if (f.type === "secret") {
676
+ // 空串/缺省 = 不改(浏览器侧回显的本来就是有无布尔,前端把“没碰”发成空串)。
677
+ if (v === undefined || v === "") {
678
+ clean[f.key] = secrets?.get(secretSettingKey(f.key)) ?? f.default ?? "";
679
+ }
680
+ else {
681
+ const s = String(v);
682
+ if (s.length > 4096) {
683
+ return {
684
+ error: pick(l, `${f.label} 过长`, `${f.label} too long`, "plugins.settings.too.long", {
685
+ "f.label": f.label,
686
+ }),
687
+ clean,
688
+ };
689
+ }
690
+ try {
691
+ secrets?.set(secretSettingKey(f.key), s);
692
+ }
693
+ catch (err) {
694
+ return { error: err.message, clean };
695
+ }
696
+ clean[f.key] = s;
697
+ }
698
+ }
397
699
  else {
398
700
  clean[f.key] = v === undefined ? (f.default ?? "") : String(v);
399
701
  }
400
702
  }
401
703
  try {
402
704
  // 保留 storage.json 里其它键(插件自己的数据),只动 settings。
705
+ // secret 真值永不进 storage.json(只进加密 secrets),这里整份剥掉。
706
+ const secretKeys = new Set(schema.filter((f) => f.type === "secret").map((f) => f.key));
707
+ const persist = {};
708
+ for (const [k, v] of Object.entries(clean))
709
+ if (!secretKeys.has(k))
710
+ persist[k] = v;
403
711
  const file = join(dir, "storage.json");
404
712
  let existing = {};
405
713
  try {
@@ -409,7 +717,7 @@ lang) {
409
717
  /* 首次 */
410
718
  }
411
719
  const tmp = `${file}.tmp-${process.pid}`;
412
- writeFileSync(tmp, JSON.stringify({ ...existing, settings: clean }));
720
+ writeFileSync(tmp, JSON.stringify({ ...existing, settings: persist }));
413
721
  renameSync(tmp, file);
414
722
  }
415
723
  catch (err) {
@@ -462,6 +770,16 @@ export class PluginManager {
462
770
  uiRuntime = new Map();
463
771
  /** manifest "ui" 基线(每次 scan 刷新;host.ui.list 与合并都读它)。 */
464
772
  uiBase = new Map();
773
+ /** manifest 解析诊断(每次 scan 重算;合法插件无诊断时记空数组)。 */
774
+ manifestDiags = new Map();
775
+ /** 运行时诊断(工具/命令/路由/门控拒绝、激活失败等;反激活时随插件一起清)。
776
+ * 只做可观测性:存一份 console.error/console.warn 之外的摘要,随 UiPluginInfo
777
+ * 下发给设置面板“界面插件”页展开查看,不改变任何隔离/权限语义。 */
778
+ runtimeDiags = new Map();
779
+ /** 运行时分级日志(host.log 写入):内存环形缓冲,每插件最近 200 条。
780
+ * 不落盘、随进程走;只经 plugin_data 按需拉取,绝不进 60ms 快照
781
+ * (与 diagnostics 的“只读诊断随清单下发”正交,互不冲突)。 */
782
+ pluginLogs = new Map();
465
783
  constructor(dataDir, cwd,
466
784
  /** 随包发布的默认插件列表(<pkgRoot>/plugins/catalog.json)。缺省 = 无内置列表。 */
467
785
  builtinCatalogPath) {
@@ -469,6 +787,7 @@ export class PluginManager {
469
787
  this.builtinCatalogPath = builtinCatalogPath;
470
788
  this.cwdValue = resolve(cwd);
471
789
  this.grants = new PluginGrantsStore(dataDir);
790
+ this.permGrants = new PluginPermissionStore(dataDir);
472
791
  this.domConsentStore = new PluginDomConsent(dataDir);
473
792
  }
474
793
  /** index.ts 在客户端 set_cwd 成功后调用:更新全局工作区并扇出给
@@ -572,7 +891,7 @@ export class PluginManager {
572
891
  return {
573
892
  error: pick(l, "该插件没有声明式设置(manifest 未声明 settings)", "This plugin has no declarative settings (manifest declares no settings)", "plugins.settings.no.declarative"),
574
893
  };
575
- const { error, clean } = saveSettingsValues(dir, schema, values, lang);
894
+ const { error, clean } = saveSettingsValues(dir, schema, values, lang, new PluginSecrets(this.dataDir, dir));
576
895
  if (error)
577
896
  return { error };
578
897
  // 通知插件(异常隔离)
@@ -608,6 +927,10 @@ export class PluginManager {
608
927
  async pushCatalog() {
609
928
  this.deliverAll({ type: "plugin_catalog", entries: this.catalog(), epoch: this.catalogEpoch });
610
929
  }
930
+ /** 把能力授权表推给所有 socket(attach 推 + 授权/撤销后重推)。 */
931
+ async pushPermissions() {
932
+ this.deliverAll({ type: "plugin_permissions", grants: this.permGrants.list() });
933
+ }
611
934
  /** 往用户自定义列表加一条(同 id 覆盖);返回错误信息或 null(成功)。
612
935
  * 成功后 epoch+1 并重推列表。 */
613
936
  addCatalogEntry(input, lang) {
@@ -649,6 +972,22 @@ export class PluginManager {
649
972
  handleMessage(pluginId, payload, from) {
650
973
  if (!ID_RE.test(pluginId))
651
974
  return;
975
+ // 宿主保留通道:运行时日志按需拉取/清空(directed plugin_data 回包)。
976
+ // 不进插件 onMessage(插件不可见),from 缺席时无法定向回包则静默丢弃。
977
+ if (isPluginLogsRequest(payload)) {
978
+ if (!from)
979
+ return;
980
+ const cleared = payload.op === "clear";
981
+ if (cleared)
982
+ this.clearPluginLogs(pluginId);
983
+ const down = {
984
+ __host: "logs",
985
+ logs: this.getPluginLogs(pluginId),
986
+ ...(cleared ? { cleared: true } : {}),
987
+ };
988
+ this.sendTo(from, pluginId, down);
989
+ return;
990
+ }
652
991
  const handlers = this.messageHandlers.get(pluginId);
653
992
  if (!handlers)
654
993
  return;
@@ -824,6 +1163,9 @@ export class PluginManager {
824
1163
  conversationProvider = undefined;
825
1164
  /** index.ts 注入:插件无头调用 agent(微信通道等经 host.chat 调用)。 */
826
1165
  chatProvider = undefined;
1166
+ /** 由 index.ts 接入 agent-service:插件直调模型(host.llm.complete 的底层,孤立无工具会话)。
1167
+ * 无注入回 {ok:false}(如 DSH 引擎),绝不抛错。 */
1168
+ llmProvider = undefined;
827
1169
  /** 由 index.ts 接入 agent-service:对话列表(host.conversations.list 的底层)。
828
1170
  * 同步数组与 Promise 都收(index.ts 接线是 async 的),host 侧归一化。无注入回 []。 */
829
1171
  conversationLister = undefined;
@@ -839,6 +1181,13 @@ export class PluginManager {
839
1181
  runAborter = undefined;
840
1182
  /** 由 index.ts 接入 agent-service:模型列表(host.models.list 的底层)。无注入回 []。 */
841
1183
  modelLister = undefined;
1184
+ /** 插件能力动态授权表(host.requestPermission 的底层,见 server/plugin-permissions.ts)。 */
1185
+ permGrants;
1186
+ /** 由 index.ts 注入:向浏览器请求能力授权的用户确认({ok, remember})。
1187
+ * 未注入(DSH/无浏览器)时 requestPermission 直接回 false。 */
1188
+ permissionRequester = undefined;
1189
+ /** 授权表**变了**(新授权落盘/撤销)时触发 —— 设置面板「已授权能力」即时刷新。 */
1190
+ onPermGrantsChanged = undefined;
842
1191
  /** 会话统计订阅(host.onStats 注册到这里;emitStats 异常隔离扇出)。 */
843
1192
  statsHandlers = new Set();
844
1193
  /** 流式增量订阅(host.onStreaming 注册到这里;emitStreaming 只透传,发送方负责节流)。 */
@@ -882,6 +1231,7 @@ export class PluginManager {
882
1231
  const fam = String(family ?? "");
883
1232
  const deny = (what) => {
884
1233
  console.error(`[plugin:${pluginId}] 缺少能力声明 "${what}"(manifest.permissions)——请求被拒`);
1234
+ this.pushRuntimeDiag(pluginId, `missing capability "${what}" (manifest.permissions) — request denied`);
885
1235
  return false;
886
1236
  };
887
1237
  if (!rec)
@@ -995,6 +1345,7 @@ export class PluginManager {
995
1345
  registerAgentTool(pluginId, tool) {
996
1346
  if (!tool || typeof tool.execute !== "function" || !tool.name || !tool.description) {
997
1347
  console.error(`[plugin:${pluginId}] registerAgentTool: 缺少 name/description/execute,忽略`);
1348
+ this.pushRuntimeDiag(pluginId, "registerAgentTool: missing name/description/execute, ignored");
998
1349
  return () => { };
999
1350
  }
1000
1351
  let table = this.agentTools.get(pluginId);
@@ -1002,6 +1353,7 @@ export class PluginManager {
1002
1353
  this.agentTools.set(pluginId, (table = new Map()));
1003
1354
  if (table.has(tool.name)) {
1004
1355
  console.error(`[plugin:${pluginId}] AI 工具 "${tool.name}" 重复注册,忽略`);
1356
+ this.pushRuntimeDiag(pluginId, `agent tool "${tool.name}": duplicate registration, ignored`);
1005
1357
  return () => { };
1006
1358
  }
1007
1359
  table.set(tool.name, tool);
@@ -1030,15 +1382,18 @@ export class PluginManager {
1030
1382
  const name = String(cmd?.name ?? "").replace(/^\/+/, ""); // 容忍误带的前导 /
1031
1383
  if (!/^[a-zA-Z][a-zA-Z0-9:_-]*$/.test(name)) {
1032
1384
  console.error(`[plugin:${pluginId}] registerCommand: 非法名称「${cmd?.name}」(需字母开头,允许字母数字:_-),忽略`);
1385
+ this.pushRuntimeDiag(pluginId, `registerCommand: invalid name "${String(cmd?.name ?? "").slice(0, 32)}", ignored`);
1033
1386
  return () => { };
1034
1387
  }
1035
1388
  if (typeof cmd?.run !== "function") {
1036
1389
  console.error(`[plugin:${pluginId}] registerCommand: ${name} 缺少 run,忽略`);
1390
+ this.pushRuntimeDiag(pluginId, `command "/${name}": missing run, ignored`);
1037
1391
  return () => { };
1038
1392
  }
1039
1393
  for (const [pid, table] of this.pluginCommands) {
1040
1394
  if (table.has(name) && pid !== pluginId) {
1041
1395
  console.error(`[plugin:${pluginId}] 命令 /${name} 已被插件 ${pid} 注册,忽略重复`);
1396
+ this.pushRuntimeDiag(pluginId, `command "/${name}": already registered by plugin ${pid}, ignored`);
1042
1397
  return () => { };
1043
1398
  }
1044
1399
  }
@@ -1047,6 +1402,7 @@ export class PluginManager {
1047
1402
  this.pluginCommands.set(pluginId, (table = new Map()));
1048
1403
  if (table.has(name)) {
1049
1404
  console.error(`[plugin:${pluginId}] 命令 /${name} 重复注册,忽略`);
1405
+ this.pushRuntimeDiag(pluginId, `command "/${name}": duplicate registration, ignored`);
1050
1406
  return () => { };
1051
1407
  }
1052
1408
  const def = { ...cmd, name };
@@ -1099,6 +1455,61 @@ export class PluginManager {
1099
1455
  uiOf(pluginId) {
1100
1456
  return mergeUiPluginUi(this.uiBase.get(pluginId), this.uiRuntime.get(pluginId));
1101
1457
  }
1458
+ /** 追加一条运行时诊断(去重 + 100 条封顶),并同步到已加载条目的 info 快照。
1459
+ * 去重是因为门控拒绝(canUse)会在每次调用时触发,重复调用不应刷屏。 */
1460
+ pushRuntimeDiag(pluginId, msg) {
1461
+ if (!ID_RE.test(pluginId))
1462
+ return;
1463
+ let arr = this.runtimeDiags.get(pluginId);
1464
+ if (!arr)
1465
+ this.runtimeDiags.set(pluginId, (arr = []));
1466
+ if (arr.includes(msg))
1467
+ return;
1468
+ if (arr.length < 100)
1469
+ arr.push(msg);
1470
+ const p = this.loaded.get(pluginId);
1471
+ if (p) {
1472
+ const combined = this.diagnosticsOf(pluginId);
1473
+ if (combined)
1474
+ p.info.diagnostics = combined;
1475
+ else
1476
+ delete p.info.diagnostics;
1477
+ }
1478
+ }
1479
+ /** 合并某插件的诊断(manifest 解析 + 运行时),无诊断返回 undefined。
1480
+ * 返回的是快照拷贝,调用方可直接挂到 UiPluginInfo 上。 */
1481
+ diagnosticsOf(pluginId) {
1482
+ const m = this.manifestDiags.get(pluginId) ?? [];
1483
+ const r = this.runtimeDiags.get(pluginId) ?? [];
1484
+ if (!m.length && !r.length)
1485
+ return undefined;
1486
+ return [...m, ...r].slice(0, 100);
1487
+ }
1488
+ /** 追加一条运行时日志(封顶丢弃最旧的;文本截断封顶)。 */
1489
+ appendPluginLog(pluginId, level, text) {
1490
+ if (!ID_RE.test(pluginId))
1491
+ return;
1492
+ let arr = this.pluginLogs.get(pluginId);
1493
+ if (!arr)
1494
+ this.pluginLogs.set(pluginId, (arr = []));
1495
+ arr.push({
1496
+ ts: Date.now(),
1497
+ level,
1498
+ text: text.length > PLUGIN_LOG_TEXT_MAX ? text.slice(0, PLUGIN_LOG_TEXT_MAX) : text,
1499
+ });
1500
+ if (arr.length > PLUGIN_LOG_CAP)
1501
+ arr.splice(0, arr.length - PLUGIN_LOG_CAP);
1502
+ }
1503
+ /** 读某插件的运行时日志(快照拷贝;未知插件回 [])。 */
1504
+ getPluginLogs(pluginId) {
1505
+ return (this.pluginLogs.get(pluginId) ?? []).map((e) => ({ ...e }));
1506
+ }
1507
+ /** 清空某插件的运行时日志(设置面板“清空”按钮用)。 */
1508
+ clearPluginLogs(pluginId) {
1509
+ if (!ID_RE.test(pluginId))
1510
+ return;
1511
+ this.pluginLogs.set(pluginId, []);
1512
+ }
1102
1513
  deliverAll(msg) {
1103
1514
  for (const s of this.senders) {
1104
1515
  try {
@@ -1177,6 +1588,11 @@ export class PluginManager {
1177
1588
  // 运行时 UI 注册随插件一起消失(manifest 基线留着,重扫时会重算)。
1178
1589
  this.uiRuntime.delete(id);
1179
1590
  this.uiBase.delete(id);
1591
+ // 诊断随插件一起清:目录回来重新激活时会重算(旧诊断留着会误导)。
1592
+ this.manifestDiags.delete(id);
1593
+ this.runtimeDiags.delete(id);
1594
+ // 运行时日志同样随插件走(内存缓冲,不落盘)。
1595
+ this.pluginLogs.delete(id);
1180
1596
  // 重新激活时会 import 磁盘上的 index.mjs:Node 的 ESM 缓存按 URL(含 ?e=)
1181
1597
  // 命中,epoch 不变就会拿到旧模块(更新插件后还是旧代码)——所以这里也 +1,
1182
1598
  // 顺带让浏览器端 ?e= 变化、重拉插件的 client bundle。
@@ -1204,6 +1620,10 @@ export class PluginManager {
1204
1620
  this.pluginBgTasks.clear();
1205
1621
  this.loaded.clear();
1206
1622
  this.messageHandlers.clear();
1623
+ // reload() 走 dispose→ensureLoaded:诊断清掉重算,不跨代累积。
1624
+ this.manifestDiags.clear();
1625
+ this.runtimeDiags.clear();
1626
+ this.pluginLogs.clear();
1207
1627
  }
1208
1628
  /** 读 manifest 清单;坏目录(无 manifest/id 非法)直接跳过。 */
1209
1629
  async scan() {
@@ -1227,6 +1647,8 @@ export class PluginManager {
1227
1647
  const m = JSON.parse(raw);
1228
1648
  const wantsDom = declarationWantsDom(m.permissions);
1229
1649
  this.domWants.set(name, wantsDom);
1650
+ // 本轮 manifest 解析的诊断(重算覆盖;运行时诊断另存在 runtimeDiags)。
1651
+ const uiDiags = [];
1230
1652
  out.push({
1231
1653
  id: name,
1232
1654
  name: typeof m.name === "string" && m.name ? m.name : name,
@@ -1272,7 +1694,7 @@ export class PluginManager {
1272
1694
  : {}),
1273
1695
  // 声明式设置 schema + 当前存值(⚙ 面板自动渲染表单用)
1274
1696
  settingsSchema: parseSettingsSchema(m.settings),
1275
- settingsValues: storedSettingsValues(dir, parseSettingsSchema(m.settings)),
1697
+ settingsValues: storedSettingsValues(dir, parseSettingsSchema(m.settings), new PluginSecrets(this.dataDir, dir)),
1276
1698
  // 可渲染的 fenced-code 语言(manifest "renderers")——前端据此按需加载
1277
1699
  renderers: Array.isArray(m.renderers)
1278
1700
  ? m.renderers.filter((r) => typeof r === "string" && r.length > 0).slice(0, 32)
@@ -1300,9 +1722,11 @@ export class PluginManager {
1300
1722
  const strict = perms.length > 0 || apiVersion >= 2;
1301
1723
  if (strict && !perms.some((x) => x.split(":")[0] === "ui")) {
1302
1724
  this.uiBase.delete(name);
1725
+ if (m.ui !== undefined)
1726
+ uiDiags.push('ui ignored: strict mode requires "ui" capability (manifest.permissions)');
1303
1727
  return undefined;
1304
1728
  }
1305
- const base = parseUiContributions(m.ui);
1729
+ const base = m.ui === undefined ? undefined : parseUiContributions(m.ui, uiDiags);
1306
1730
  if (base)
1307
1731
  this.uiBase.set(name, base);
1308
1732
  else
@@ -1323,6 +1747,18 @@ export class PluginManager {
1323
1747
  })
1324
1748
  .catch(() => undefined),
1325
1749
  });
1750
+ // 诊断随清单下发:manifest 解析 + 到目前为止的运行时诊断。
1751
+ this.manifestDiags.set(name, uiDiags);
1752
+ const scanned = [...uiDiags, ...(this.runtimeDiags.get(name) ?? [])].slice(0, 100);
1753
+ if (scanned.length)
1754
+ out[out.length - 1].diagnostics = scanned;
1755
+ const lp = this.loaded.get(name);
1756
+ if (lp) {
1757
+ if (scanned.length)
1758
+ lp.info.diagnostics = [...scanned];
1759
+ else
1760
+ delete lp.info.diagnostics;
1761
+ }
1326
1762
  }
1327
1763
  catch {
1328
1764
  continue; // 无 manifest / JSON 坏 —— 不是插件
@@ -1333,6 +1769,13 @@ export class PluginManager {
1333
1769
  if (!out.some((p) => p.id === key))
1334
1770
  this.domWants.delete(key);
1335
1771
  }
1772
+ for (const key of [...this.manifestDiags.keys(), ...this.runtimeDiags.keys(), ...this.pluginLogs.keys()]) {
1773
+ if (!out.some((p) => p.id === key)) {
1774
+ this.manifestDiags.delete(key);
1775
+ this.runtimeDiags.delete(key);
1776
+ this.pluginLogs.delete(key);
1777
+ }
1778
+ }
1336
1779
  return out;
1337
1780
  }
1338
1781
  async activate(info, lang) {
@@ -1361,8 +1804,9 @@ export class PluginManager {
1361
1804
  if (apiVersion > PLUGIN_API_VERSION) {
1362
1805
  const msg = pick(l, `插件要求宿主 API v${apiVersion},当前宿主 v${PLUGIN_API_VERSION} —— 请升级 pi-web-ui`, `Plugin requires host API v${apiVersion} but the host is v${PLUGIN_API_VERSION} — please upgrade pi-web-ui`, "plugins.host.api.mismatch", { apiVersion, PLUGIN_API_VERSION });
1363
1806
  console.error(`[plugin:${info.id}] ${msg}`);
1807
+ this.pushRuntimeDiag(info.id, `requires host API v${apiVersion} but host is v${PLUGIN_API_VERSION} — please upgrade pi-web-ui`);
1364
1808
  this.loaded.set(info.id, {
1365
- info: { ...info, error: msg },
1809
+ info: { ...info, error: msg, diagnostics: this.diagnosticsOf(info.id) },
1366
1810
  toolHandlers,
1367
1811
  runHandlers,
1368
1812
  convChangeHandlers,
@@ -1387,8 +1831,9 @@ export class PluginManager {
1387
1831
  if (verdict === false) {
1388
1832
  const msg = pick(l, `插件要求 pi-web-ui ${enginesReq},当前宿主版本 ${hostVer} —— 请升级 pi-web-ui`, `Plugin requires pi-web-ui ${enginesReq} but the host is ${hostVer} — please upgrade pi-web-ui`, "plugins.host.engines.mismatch", { enginesReq, hostVer });
1389
1833
  console.error(`[plugin:${info.id}] ${msg}`);
1834
+ this.pushRuntimeDiag(info.id, `requires pi-web-ui ${enginesReq} but host is ${hostVer} — please upgrade pi-web-ui`);
1390
1835
  this.loaded.set(info.id, {
1391
- info: { ...info, error: msg },
1836
+ info: { ...info, error: msg, diagnostics: this.diagnosticsOf(info.id) },
1392
1837
  toolHandlers,
1393
1838
  runHandlers,
1394
1839
  convChangeHandlers,
@@ -1401,11 +1846,13 @@ export class PluginManager {
1401
1846
  }
1402
1847
  if (verdict === null) {
1403
1848
  console.warn(`[plugin:${info.id}] engines 约束「${enginesReq}」解析失败,已放行(不阻断激活)`);
1849
+ this.pushRuntimeDiag(info.id, `engines constraint "${enginesReq}" unparseable, allowed without blocking`);
1404
1850
  }
1405
1851
  }
1406
1852
  for (const peer of info.peerPlugins ?? []) {
1407
1853
  if (!existsSync(join(this.pluginsDir, peer))) {
1408
1854
  console.warn(`[plugin:${info.id}] 对等插件缺失:${peer}(仅警告,不阻断激活)`);
1855
+ this.pushRuntimeDiag(info.id, `peer plugin missing: ${peer} (warn only, activation continues)`);
1409
1856
  }
1410
1857
  }
1411
1858
  // 新增订阅的取消函数(反激活时经 releaseEntry 统一释放)。
@@ -1453,6 +1900,73 @@ export class PluginManager {
1453
1900
  const abs = allowAbs(absPath);
1454
1901
  await rm(abs, { recursive: true, force: true });
1455
1902
  },
1903
+ stat: async (absPath) => {
1904
+ const abs = allowAbs(absPath);
1905
+ const st = await stat(abs);
1906
+ const base = abs
1907
+ .replace(/[/\\]+$/, "")
1908
+ .split("/")
1909
+ .pop() ?? abs;
1910
+ return {
1911
+ name: base,
1912
+ type: (st.isDirectory() ? "dir" : "file"),
1913
+ size: st.isDirectory() ? 0 : st.size,
1914
+ mtime: Number(st.mtimeMs) || 0,
1915
+ };
1916
+ },
1917
+ mkdir: async (absDir) => {
1918
+ await mkdir(allowAbs(absDir), { recursive: true });
1919
+ },
1920
+ append: async (absPath, data) => {
1921
+ const abs = allowAbs(absPath);
1922
+ await mkdir(dirname(abs), { recursive: true });
1923
+ await writeFile(abs, data, { flag: "a" });
1924
+ },
1925
+ glob: async (absDir, pattern) => {
1926
+ const { globToRegExp } = await import("./plugin-facilities.js");
1927
+ const pat = String(pattern ?? "")
1928
+ .trim()
1929
+ .replace(/\\/g, "/");
1930
+ if (!pat)
1931
+ throw new Error("globPath: pattern 为空");
1932
+ const re = globToRegExp(pat);
1933
+ const base = allowAbs(absDir);
1934
+ const out = [];
1935
+ const stack = [base];
1936
+ let walked = 0;
1937
+ while (stack.length && walked < 2000 && out.length < 500) {
1938
+ const dir = stack.pop();
1939
+ let ents;
1940
+ try {
1941
+ ents = await readdir(dir, { withFileTypes: true });
1942
+ }
1943
+ catch {
1944
+ continue;
1945
+ }
1946
+ for (const e of ents) {
1947
+ if (walked++ >= 2000 || out.length >= 500)
1948
+ break;
1949
+ const abs = join(dir, e.name);
1950
+ // 跨目录返回绝对路径(调用方直接可用);匹配仍按相对 base 的部分。
1951
+ // 先转分隔符再去前导斜杠(顺序反了会留下 "/n.txt" 导致匹配失败)。
1952
+ const rel = abs
1953
+ .slice(base.length)
1954
+ .replace(/\\/g, "/")
1955
+ .split("/")
1956
+ .filter((s) => s.length > 0)
1957
+ .join("/");
1958
+ if (e.isDirectory()) {
1959
+ if (re.test(rel) || re.test(`${rel}/`))
1960
+ out.push(abs);
1961
+ stack.push(abs);
1962
+ }
1963
+ else if (re.test(rel)) {
1964
+ out.push(abs);
1965
+ }
1966
+ }
1967
+ }
1968
+ return out;
1969
+ },
1456
1970
  };
1457
1971
  const self = this; // 对象字面量 getter 里不能用插件宿主的 this (oxlint no-this-alias: 誤報, getter closure 需要 host)
1458
1972
  // 能力门控快照:host 对象可用之前(loaded.set 之前)canUse 也要能判定。
@@ -1519,6 +2033,89 @@ export class PluginManager {
1519
2033
  return { ok: false, error: err.message };
1520
2034
  }
1521
2035
  },
2036
+ llm: {
2037
+ complete: async (req) => {
2038
+ if (!can("llm"))
2039
+ return { ok: false, error: `插件未声明能力 "llm"(manifest.permissions)——请求被拒` };
2040
+ // 有模型作用域授权时收紧到批准的模型(无授权=声明即全开,向后兼容)。
2041
+ const model = typeof req?.model === "string" ? req.model.trim() : "";
2042
+ if (model && !self.permGrants.modelAllowed(info.id, model))
2043
+ return {
2044
+ ok: false,
2045
+ error: `llm: 模型 ${model} 不在用户批准的作用域内(可 host.requestPermission 重新申请)`,
2046
+ };
2047
+ if (!self.llmProvider)
2048
+ return { ok: false, error: "宿主未提供 LLM 直调(llmProvider 未接入)" };
2049
+ try {
2050
+ return await self.llmProvider(info.id, req ?? { prompt: "" });
2051
+ }
2052
+ catch (err) {
2053
+ return { ok: false, error: err.message };
2054
+ }
2055
+ },
2056
+ },
2057
+ requestPermission: async (req) => {
2058
+ const family = req?.family;
2059
+ if (family !== "net" && family !== "llm")
2060
+ throw new Error(`requestPermission: 不支持的能力族「${String(family)}」(目前只收 net/llm)`);
2061
+ // 基础族必须已声明(与 requestAccess 要求 fs:read 同口径,fail-closed)。
2062
+ if (!can(family))
2063
+ return false;
2064
+ const hosts = family === "net" && Array.isArray(req.hosts)
2065
+ ? req.hosts
2066
+ .filter((x) => typeof x === "string" && x.trim() !== "")
2067
+ .map((x) => x.trim().toLowerCase())
2068
+ .slice(0, 32)
2069
+ : undefined;
2070
+ if (family === "net" && (!hosts || hosts.length === 0))
2071
+ throw new Error("requestPermission: family=net 必须给 hosts(要批准的主机列表)");
2072
+ const models = family === "llm" && Array.isArray(req.models)
2073
+ ? req.models
2074
+ .filter((x) => typeof x === "string" && x.includes("/"))
2075
+ .map((x) => x.trim())
2076
+ .slice(0, 32)
2077
+ : undefined;
2078
+ const reason = typeof req.reason === "string"
2079
+ ? String(req.reason).slice(0, 200)
2080
+ : undefined;
2081
+ // 已有授权(静态白名单算在执行期,动态表在这里):直接通过,不打扰用户。
2082
+ if (family === "net" && hosts.every((h) => netAllow.some((entry) => h === entry || h.endsWith(`.${entry}`))))
2083
+ return true;
2084
+ if (family === "net" && hosts.every((h) => self.permGrants.has(info.id, "net", { host: h })))
2085
+ return true;
2086
+ if (family === "llm" && self.permGrants.has(info.id, "llm", models?.[0] ? { model: models[0] } : undefined))
2087
+ return true;
2088
+ if (!self.permissionRequester)
2089
+ return false;
2090
+ let ans;
2091
+ try {
2092
+ ans = await self.permissionRequester(info.id, {
2093
+ family,
2094
+ ...(hosts ? { hosts } : {}),
2095
+ ...(models ? { models } : {}),
2096
+ ...(reason ? { reason } : {}),
2097
+ });
2098
+ }
2099
+ catch {
2100
+ return false;
2101
+ }
2102
+ if (!ans?.ok)
2103
+ return false;
2104
+ try {
2105
+ self.permGrants.grant(info.id, family, { hosts, models, reason, remember: ans.remember === true });
2106
+ }
2107
+ catch (err) {
2108
+ console.error(`[plugin:${info.id}] permission grant failed:`, err);
2109
+ return false;
2110
+ }
2111
+ try {
2112
+ self.onPermGrantsChanged?.();
2113
+ }
2114
+ catch {
2115
+ /* 推送失败不影响已完成的授权 */
2116
+ }
2117
+ return true;
2118
+ },
1522
2119
  conversations: {
1523
2120
  list: () => {
1524
2121
  try {
@@ -1640,6 +2237,7 @@ export class PluginManager {
1640
2237
  !path.startsWith("/") ||
1641
2238
  typeof handler !== "function") {
1642
2239
  console.error(`[plugin:${info.id}] route: 非法参数(method=${method} path=${path}),忽略`);
2240
+ self.pushRuntimeDiag(info.id, `route: invalid method/path (method=${String(method)} path=${String(path)}), ignored`);
1643
2241
  return () => { };
1644
2242
  }
1645
2243
  httpRoutes.set(`${m} ${path}`, handler);
@@ -1669,6 +2267,10 @@ export class PluginManager {
1669
2267
  readText: (p, max) => (canRead() ? workspaceFs.readText(p, max) : NO_FS_PROMISE),
1670
2268
  write: (p, data) => (canWrite() ? workspaceFs.write(p, data) : NO_FS_WRITE_PROMISE),
1671
2269
  remove: (p) => (canWrite() ? workspaceFs.remove(p) : NO_FS_WRITE_PROMISE),
2270
+ stat: (p) => (canRead() ? workspaceFs.stat(p) : NO_FS_PROMISE),
2271
+ mkdir: (p) => (canWrite() ? workspaceFs.mkdir(p) : NO_FS_WRITE_PROMISE),
2272
+ append: (p, data) => (canWrite() ? workspaceFs.append(p, data) : NO_FS_WRITE_PROMISE),
2273
+ glob: (pat, dir) => (canRead() ? workspaceFs.glob(pat, dir) : NO_FS_PROMISE),
1672
2274
  requestAccess: async (dir, reason) => {
1673
2275
  if (!canRead())
1674
2276
  return false;
@@ -1701,6 +2303,10 @@ export class PluginManager {
1701
2303
  readTextPath: (absPath, max) => (canRead() ? crossDirFs.readText(absPath, max) : NO_FS_PROMISE),
1702
2304
  writePath: (absPath, data) => (canWrite() ? crossDirFs.write(absPath, data) : NO_FS_WRITE_PROMISE),
1703
2305
  removePath: (absPath) => (canWrite() ? crossDirFs.remove(absPath) : NO_FS_WRITE_PROMISE),
2306
+ statPath: (absPath) => (canRead() ? crossDirFs.stat(absPath) : NO_FS_PROMISE),
2307
+ mkdirPath: (absDir) => (canWrite() ? crossDirFs.mkdir(absDir) : NO_FS_WRITE_PROMISE),
2308
+ appendPath: (absPath, data) => (canWrite() ? crossDirFs.append(absPath, data) : NO_FS_WRITE_PROMISE),
2309
+ globPath: (absDir, pat) => (canRead() ? crossDirFs.glob(absDir, pat) : NO_FS_PROMISE),
1704
2310
  watch: (relPath, handler) => {
1705
2311
  if (!canRead())
1706
2312
  throw new Error('插件未声明读能力 "fs"/"fs:read"(manifest.permissions)——请求被拒');
@@ -1754,6 +2360,7 @@ export class PluginManager {
1754
2360
  const id = String(task?.id ?? "").trim();
1755
2361
  if (!id || bgTaskTable.has(id)) {
1756
2362
  console.error(`[plugin:${info.id}] registerBackgroundTask: 非法/重复 id「${task?.id}」,忽略`);
2363
+ self.pushRuntimeDiag(info.id, `registerBackgroundTask: invalid/duplicate id "${String(task?.id ?? "").slice(0, 32)}", ignored`);
1757
2364
  return { update: () => { }, unregister: () => { } };
1758
2365
  }
1759
2366
  const entry = {
@@ -1798,17 +2405,31 @@ export class PluginManager {
1798
2405
  if (!can("ui"))
1799
2406
  return () => { };
1800
2407
  const list = Array.isArray(items) ? items : [items];
2408
+ if (list.length > 32)
2409
+ self.pushRuntimeDiag(info.id, `ui.register: capped at 32 items (${list.length - 32} dropped)`);
1801
2410
  const added = [];
1802
2411
  const rt = self.uiRuntimeFor(info.id);
1803
- for (const raw of list.slice(0, 32)) {
2412
+ const sliced = list.slice(0, 32);
2413
+ for (let idx = 0; idx < sliced.length; idx++) {
2414
+ const raw = sliced[idx];
1804
2415
  const slotRaw = typeof raw?.slot === "string" ? String(raw.slot) : "";
1805
2416
  // 与 manifest 解析同口径:先查别名(topbar → topbar.primary)、再校枚举。
1806
2417
  // 运行时注册不校验的话,插件给个别名(或写错)会得到一个前端不认识的 slot
1807
2418
  // —— buildUiSlots 会静默丢掉它,表现为「注册了但界面上没有」,最难排。
1808
2419
  const slot = UI_SLOT_ALIASES[slotRaw] ?? slotRaw;
1809
- const parsed = slot && UI_SLOTS.has(slot) ? parseUiItem(raw, slot) : null;
1810
- if (!parsed)
2420
+ if (!slot || !UI_SLOTS.has(slot)) {
2421
+ self.pushRuntimeDiag(info.id, `ui.register[#${idx}]: unknown slot "${slotRaw || "(missing)"}", item dropped`);
2422
+ continue;
2423
+ }
2424
+ const itemDiags = [];
2425
+ const parsed = parseUiItem(raw, slot, itemDiags);
2426
+ for (const m of itemDiags)
2427
+ self.pushRuntimeDiag(info.id, `ui.register: ${m}`);
2428
+ if (!parsed) {
2429
+ if (!itemDiags.length)
2430
+ self.pushRuntimeDiag(info.id, `ui.register[#${idx}]: item in slot "${slot}" dropped`);
1811
2431
  continue;
2432
+ }
1812
2433
  rt.items.set(parsed.id, parsed);
1813
2434
  rt.removed.delete(parsed.id);
1814
2435
  added.push(parsed.id);
@@ -1829,8 +2450,10 @@ export class PluginManager {
1829
2450
  // 只能更新"当前生效"的条目:manifest 声明的与运行时注册的都算,
1830
2451
  // 不存在的一律忽略(避免插件凭空造条目绕过声明审查)。
1831
2452
  const base = self.uiOf(info.id)?.items.find((x) => x.id === id);
1832
- if (!base)
2453
+ if (!base) {
2454
+ self.pushRuntimeDiag(info.id, `ui.update: unknown id "${String(id).slice(0, 32)}", ignored`);
1833
2455
  return;
2456
+ }
1834
2457
  const merged = { ...base, ...patch, id, slot: base.slot };
1835
2458
  self.uiRuntimeFor(info.id).items.set(id, merged);
1836
2459
  void self.pushToAll().catch(() => { });
@@ -1844,7 +2467,11 @@ export class PluginManager {
1844
2467
  arrange: (ops) => {
1845
2468
  if (!can("ui"))
1846
2469
  return;
1847
- const list = parseUiArrange(Array.isArray(ops) ? ops : [ops]);
2470
+ const arr = Array.isArray(ops) ? ops : [ops];
2471
+ const arrangeDiags = [];
2472
+ const list = parseUiArrange(arr, arrangeDiags);
2473
+ for (const m of arrangeDiags)
2474
+ self.pushRuntimeDiag(info.id, `ui.arrange: ${m}`);
1848
2475
  if (!list.length)
1849
2476
  return;
1850
2477
  self.uiRuntimeFor(info.id).arrange.push(...list);
@@ -1852,7 +2479,7 @@ export class PluginManager {
1852
2479
  },
1853
2480
  list: () => self.uiOf(info.id) ?? { items: [], arrange: [] },
1854
2481
  },
1855
- getSettings: () => storedSettingsValues(dir, info.settingsSchema ?? []),
2482
+ getSettings: () => runtimeSettingsValues(dir, info.settingsSchema ?? [], secrets),
1856
2483
  onSettingsChanged: (h) => {
1857
2484
  settingsHandlers.add(h);
1858
2485
  return () => settingsHandlers.delete(h);
@@ -1923,34 +2550,181 @@ export class PluginManager {
1923
2550
  };
1924
2551
  }
1925
2552
  },
1926
- schedule: (cronOrMs, fn) => {
2553
+ schedule: (cronOrMs, fn, opts) => {
1927
2554
  if (typeof fn !== "function")
1928
2555
  throw new Error("schedule: fn 必须是函数");
1929
- let ms;
2556
+ const persistent = opts?.persistent === true;
2557
+ const catchUp = opts?.catchUp === "once" ? "once" : "skip";
2558
+ const label = typeof opts?.label === "string" &&
2559
+ String(opts.label).trim()
2560
+ ? String(opts.label)
2561
+ .trim()
2562
+ .slice(0, 60)
2563
+ : undefined;
2564
+ // 归一化声明:毫秒间隔 或 全 5 字段 cron(旧的 "*/N * * * *" 是它的子集,照常工作)。
2565
+ let ms = 0;
2566
+ let parts;
2567
+ let specText;
1930
2568
  if (typeof cronOrMs === "number") {
1931
- ms = Math.max(10_000, Math.floor(cronOrMs) || 10_000);
2569
+ ms = Math.floor(cronOrMs) || 0;
2570
+ if (!(ms > 0))
2571
+ throw new Error("schedule: 间隔毫秒数必须大于 0");
2572
+ ms = Math.min(ms, 2_147_483_647); // setInterval 上限(约 24.8 天),防溢出立即触发
2573
+ ms = Math.max(ms, persistent ? 60_000 : 10_000);
2574
+ specText = String(ms);
1932
2575
  }
1933
2576
  else if (typeof cronOrMs === "string") {
1934
- const m = cronOrMs.trim().match(/^\*\/(\d+)\s+\*\s+\*\s+\*\s+\*$/);
1935
- if (!m)
1936
- throw new Error(`schedule: 不支持的 cron 形状「${cronOrMs}」(仅支持 "*/N * * * *" 分钟步长)`);
1937
- ms = Math.max(10_000, Number(m[1]) * 60_000);
2577
+ specText = cronOrMs.trim().replace(/\s+/g, " ");
2578
+ const parsed = parseCronSpec(specText);
2579
+ if (!parsed)
2580
+ throw new Error(`schedule: 不支持的 cron 形状「${cronOrMs}」(要 5 字段:分 时 日 月 周,如 "0 9 * * *")`);
2581
+ parts = parsed;
1938
2582
  }
1939
2583
  else {
1940
2584
  throw new Error("schedule: 参数必须是间隔毫秒数或 cron 字符串");
1941
2585
  }
1942
- ms = Math.min(ms, 2_147_483_647); // setInterval 上限(约 24.8 天),防溢出立即触发
1943
- const timer = setInterval(() => {
2586
+ // 持久化:声明落盘(幂等——activate 重调时保留 lastRun/createdAt,只更新声明)。
2587
+ let sid = "";
2588
+ if (persistent) {
2589
+ sid =
2590
+ typeof opts?.id === "string"
2591
+ ? String(opts.id).trim()
2592
+ : "";
2593
+ if (!sid || !ID_RE.test(sid))
2594
+ throw new Error("schedule: persistent 任务必须给合法 id(字母/数字/下划线/连字符),重启后靠它重建");
2595
+ const records = loadScheduleRecords(dir);
2596
+ const prev = records[sid];
2597
+ records[sid] = {
2598
+ spec: specText,
2599
+ catchUp,
2600
+ ...(label ? { label } : {}),
2601
+ ...(prev?.lastRun !== undefined ? { lastRun: prev.lastRun } : {}),
2602
+ createdAt: prev?.createdAt ?? Date.now(),
2603
+ };
2604
+ saveScheduleRecords(dir, records);
2605
+ }
2606
+ let timer;
2607
+ let grace;
2608
+ let cancelled = false;
2609
+ const nextText = () => {
2610
+ if (parts) {
2611
+ try {
2612
+ return new Date(nextCronFire(parts, Date.now())).toLocaleString();
2613
+ }
2614
+ catch {
2615
+ return specText;
2616
+ }
2617
+ }
2618
+ return `每 ${Math.round(ms / 1000)}s`;
2619
+ };
2620
+ // 后台面板条目(持久任务独有):看得见下次时间,停止=删声明(不再复活)。
2621
+ let bgRefresh;
2622
+ let bgUnreg;
2623
+ if (persistent) {
2624
+ const taskId = `schedule:${sid}`;
2625
+ bgTaskTable.delete(taskId);
2626
+ const entry = {
2627
+ id: taskId,
2628
+ label: `⏰ ${label ?? sid}`,
2629
+ since: Date.now(),
2630
+ status: `下次 ${nextText()}`,
2631
+ stop: () => off(),
2632
+ };
2633
+ bgTaskTable.set(taskId, entry);
2634
+ self.pluginBgTasks.set(info.id, bgTaskTable);
2635
+ const fireBg = () => {
2636
+ try {
2637
+ self.onBgTasksChanged?.();
2638
+ }
2639
+ catch {
2640
+ /* 推送失败不影响定时本身 */
2641
+ }
2642
+ };
2643
+ bgRefresh = () => {
2644
+ if (!bgTaskTable.has(taskId))
2645
+ return;
2646
+ entry.status = `下次 ${nextText()}`;
2647
+ fireBg();
2648
+ };
2649
+ bgUnreg = () => {
2650
+ if (bgTaskTable.delete(taskId)) {
2651
+ if (bgTaskTable.size === 0)
2652
+ self.pluginBgTasks.delete(info.id);
2653
+ fireBg();
2654
+ }
2655
+ };
2656
+ fireBg();
2657
+ }
2658
+ const fire = () => {
2659
+ if (cancelled)
2660
+ return;
2661
+ if (persistent) {
2662
+ const records = loadScheduleRecords(dir);
2663
+ const rec = records[sid];
2664
+ if (rec) {
2665
+ rec.lastRun = Date.now();
2666
+ saveScheduleRecords(dir, records);
2667
+ }
2668
+ }
1944
2669
  try {
1945
- fn();
2670
+ const r = fn();
2671
+ if (r instanceof Promise) {
2672
+ r.catch((err) => console.error(`[plugin:${info.id}] scheduled task failed:`, err));
2673
+ }
1946
2674
  }
1947
2675
  catch (err) {
1948
2676
  console.error(`[plugin:${info.id}] scheduled task failed:`, err);
1949
2677
  }
1950
- }, ms);
1951
- timer.unref?.();
1952
- const off = () => clearInterval(timer);
1953
- scheduleSubs.push(off);
2678
+ bgRefresh?.();
2679
+ };
2680
+ const armCron = () => {
2681
+ if (cancelled || !parts)
2682
+ return;
2683
+ const next = nextCronFire(parts, Date.now());
2684
+ timer = setTimeout(() => {
2685
+ fire();
2686
+ armCron();
2687
+ }, Math.max(0, next - Date.now()));
2688
+ timer.unref?.();
2689
+ };
2690
+ if (parts)
2691
+ armCron();
2692
+ else {
2693
+ timer = setInterval(fire, ms);
2694
+ timer.unref?.();
2695
+ }
2696
+ // 漏跑补跑:以上次触发(没跑过按创建时间)为锚,下一次已在过去=漏了。
2697
+ if (persistent && catchUp === "once") {
2698
+ const refTime = loadScheduleRecords(dir)[sid]?.lastRun ?? loadScheduleRecords(dir)[sid]?.createdAt ?? Date.now();
2699
+ const missed = parts ? nextCronFire(parts, refTime) <= Date.now() : refTime + ms <= Date.now();
2700
+ if (missed) {
2701
+ // 15s 缓冲:刚启动时模型/网络可能还没就绪,补跑不等那 15 秒可能白跑。
2702
+ grace = setTimeout(() => fire(), 15_000);
2703
+ grace.unref?.();
2704
+ }
2705
+ }
2706
+ const cancelTimer = () => {
2707
+ cancelled = true;
2708
+ if (timer !== undefined) {
2709
+ clearTimeout(timer);
2710
+ clearInterval(timer);
2711
+ }
2712
+ if (grace !== undefined)
2713
+ clearTimeout(grace);
2714
+ };
2715
+ const off = () => {
2716
+ cancelTimer();
2717
+ bgUnreg?.();
2718
+ if (persistent) {
2719
+ const records = loadScheduleRecords(dir);
2720
+ if (sid in records) {
2721
+ delete records[sid];
2722
+ saveScheduleRecords(dir, records);
2723
+ }
2724
+ }
2725
+ };
2726
+ // 反激活只停表、不断持久化:下次 activate 重调 schedule() 即按落盘声明重建。
2727
+ scheduleSubs.push(cancelTimer);
1954
2728
  return off;
1955
2729
  },
1956
2730
  models: {
@@ -2007,10 +2781,15 @@ export class PluginManager {
2007
2781
  return { ok: false, error: `net: 不支持的协议 ${u.protocol}` };
2008
2782
  }
2009
2783
  // 白名单:主机相等或 .后缀匹配;空表即全拒(fail-closed)。
2784
+ // 用户动态批准的主机(host.requestPermission)同样放行,免改 manifest 重装。
2010
2785
  const hostname = u.hostname.toLowerCase();
2011
- const allowed = netAllow.some((entry) => hostname === entry || hostname.endsWith(`.${entry}`));
2786
+ const allowed = netAllow.some((entry) => hostname === entry || hostname.endsWith(`.${entry}`)) ||
2787
+ self.permGrants.has(info.id, "net", { host: hostname });
2012
2788
  if (!allowed)
2013
- return { ok: false, error: `net: 主机 ${u.hostname} 不在白名单(manifest.netAllowlist)` };
2789
+ return {
2790
+ ok: false,
2791
+ error: `net: 主机 ${u.hostname} 未授权(manifest.netAllowlist 或 host.requestPermission 申请)`,
2792
+ };
2014
2793
  if (init?.body !== undefined && Buffer.byteLength(String(init.body), "utf8") > 1024 * 1024) {
2015
2794
  return { ok: false, error: "net: body 超过 1MB 上限" };
2016
2795
  }
@@ -2082,7 +2861,22 @@ export class PluginManager {
2082
2861
  };
2083
2862
  },
2084
2863
  },
2085
- log: (...args) => console.log(`[plugin:${info.id}]`, ...args),
2864
+ log: (levelOrArg, ...args) => {
2865
+ const level = normalizePluginLogLevel(levelOrArg);
2866
+ // 首参是级别即剥掉(不进文本);否则全部参数都是日志内容(老插件兼容)。
2867
+ const text = formatPluginLogText(levelOrArg === level ? args : [levelOrArg, ...args]);
2868
+ self.appendPluginLog(info.id, level, text);
2869
+ const line = `[plugin:${info.id}]${text ? ` ${text}` : ""}`;
2870
+ // console 既有行为保留:级别只决定走哪个 console 方法。
2871
+ if (level === "error")
2872
+ console.error(line);
2873
+ else if (level === "warn")
2874
+ console.warn(line);
2875
+ else if (level === "debug")
2876
+ console.debug(line);
2877
+ else
2878
+ console.log(line);
2879
+ },
2086
2880
  };
2087
2881
  try {
2088
2882
  // Node 对同一 URL 的 import() 永远返回缓存模块——追加 epoch 作查询串
@@ -2091,8 +2885,11 @@ export class PluginManager {
2091
2885
  const ret = await mod.default?.activate?.(host);
2092
2886
  const gateWarned = self.activatingGates.get(info.id)?.legacyWarned;
2093
2887
  self.activatingGates.delete(info.id);
2888
+ // activate() 执行期间经 host 注册产生的运行时诊断(重复工具/命令、ui 丢弃等)
2889
+ // 已经进了 runtimeDiags,这里合并进快照一起下发。
2890
+ const combined = this.diagnosticsOf(info.id);
2094
2891
  this.loaded.set(info.id, {
2095
- info: { ...info },
2892
+ info: { ...info, ...(combined ? { diagnostics: combined } : {}) },
2096
2893
  deactivate: typeof ret === "function" ? ret : undefined,
2097
2894
  toolHandlers,
2098
2895
  runHandlers,
@@ -2122,8 +2919,9 @@ export class PluginManager {
2122
2919
  catch (err) {
2123
2920
  httpRoutes.clear();
2124
2921
  self.activatingGates.delete(info.id);
2922
+ this.pushRuntimeDiag(info.id, `activate failed: ${err.message}`);
2125
2923
  this.loaded.set(info.id, {
2126
- info: { ...info, error: err.message },
2924
+ info: { ...info, error: err.message, diagnostics: this.diagnosticsOf(info.id) },
2127
2925
  toolHandlers,
2128
2926
  runHandlers,
2129
2927
  convChangeHandlers,