pi-web-ui 0.87.2 → 0.89.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.
- package/CHANGELOG.md +66 -1
- package/bin/pi-web-ui.mjs +463 -0
- package/dist/server/agent-service.js +419 -45
- package/dist/server/attachments.js +39 -0
- package/dist/server/client-state.js +22 -0
- package/dist/server/conversation-read-tool.js +325 -0
- package/dist/server/dsh/dsh-agent-service.js +32 -3
- package/dist/server/files-service.js +103 -0
- package/dist/server/host-metrics.js +59 -0
- package/dist/server/index.js +381 -8
- package/dist/server/model-admin.js +285 -36
- package/dist/server/plugin-facilities.js +115 -2
- package/dist/server/plugin-llm.js +129 -0
- package/dist/server/plugin-permissions.js +176 -0
- package/dist/server/plugin-schedule.js +211 -0
- package/dist/server/plugins.js +1005 -68
- package/dist/server/scheduler-tasks.js +405 -0
- package/dist/server/settings-service.js +8 -1
- package/dist/server/terminals.js +14 -1
- package/dist/server/tool-manager.js +6 -1
- package/dist/server/update-check.js +249 -19
- package/extensions/webui.ts +9 -2
- package/package.json +4 -2
- package/plugin-sdk/README.md +127 -0
- package/plugin-sdk/index.d.ts +454 -0
- package/plugin-sdk/index.mjs +545 -0
- package/plugin-sdk/package.json +9 -0
- package/plugins/catalog.json +11 -2
- package/web/dist/assets/TerminalPanel-BOUmN3uu.js +6 -0
- package/web/dist/assets/TerminalPanel-DOrYoP_4.css +32 -0
- package/web/dist/assets/index-3XU67qMh.js +376 -0
- package/web/dist/assets/index-B-gdvWtW.css +10 -0
- package/web/dist/index.html +2 -3
- package/web/dist/assets/index-CYuoen3I.js +0 -374
- package/web/dist/assets/index-F86qWlJy.css +0 -41
package/dist/server/plugins.js
CHANGED
|
@@ -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
|
-
/**
|
|
179
|
-
|
|
180
|
-
|
|
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
|
-
|
|
197
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
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
|
-
|
|
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)
|
|
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
|
-
|
|
266
|
-
|
|
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
|
-
|
|
275
|
-
|
|
480
|
+
/** 规范化整理意图(对内置/其它插件的条目)。非法/越界形状丢弃。
|
|
481
|
+
*
|
|
482
|
+
* 第三个参数可选:传了就把丢弃/忽略原因逐条 push 进去;不传则行为与原来完全一致。 */
|
|
483
|
+
export function parseUiArrange(raw, diagnostics) {
|
|
484
|
+
const diag = (m) => {
|
|
485
|
+
diagnostics?.push(m);
|
|
486
|
+
};
|
|
487
|
+
if (raw === undefined)
|
|
488
|
+
return [];
|
|
489
|
+
if (!Array.isArray(raw)) {
|
|
490
|
+
diag("ui arrange: expected array, ignored");
|
|
276
491
|
return [];
|
|
492
|
+
}
|
|
493
|
+
if (raw.length > 64)
|
|
494
|
+
diag(`ui arrange: capped at 64 (${raw.length - 64} dropped)`);
|
|
277
495
|
const out = [];
|
|
278
|
-
|
|
279
|
-
|
|
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,38 @@ function parseSettingsSchema(raw) {
|
|
|
344
585
|
}
|
|
345
586
|
return out;
|
|
346
587
|
}
|
|
347
|
-
/**
|
|
348
|
-
function
|
|
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) {
|
|
596
|
+
const out = {};
|
|
597
|
+
let stored = {};
|
|
598
|
+
try {
|
|
599
|
+
const parsed = JSON.parse(readFileSync(join(dir, "storage.json"), "utf8"));
|
|
600
|
+
if (parsed && typeof parsed === "object" && parsed.settings && typeof parsed.settings === "object") {
|
|
601
|
+
stored = parsed.settings;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
catch {
|
|
605
|
+
/* 无存储文件 = 全默认 */
|
|
606
|
+
}
|
|
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
|
+
}
|
|
613
|
+
out[f.key] = stored[f.key] ?? f.default;
|
|
614
|
+
}
|
|
615
|
+
return out;
|
|
616
|
+
}
|
|
617
|
+
/** 插件运行时视角的设置值:非 secret 与 storedSettingsValues 同口径;secret 返回真值
|
|
618
|
+
* (无则回落默认值/空串)。只给插件服务端代码用,绝不下发浏览器。 */
|
|
619
|
+
function runtimeSettingsValues(dir, schema, secrets) {
|
|
349
620
|
const out = {};
|
|
350
621
|
let stored = {};
|
|
351
622
|
try {
|
|
@@ -357,14 +628,21 @@ function storedSettingsValues(dir, schema) {
|
|
|
357
628
|
catch {
|
|
358
629
|
/* 无存储文件 = 全默认 */
|
|
359
630
|
}
|
|
360
|
-
for (const f of schema)
|
|
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
|
+
}
|
|
361
636
|
out[f.key] = stored[f.key] ?? f.default;
|
|
637
|
+
}
|
|
362
638
|
return out;
|
|
363
639
|
}
|
|
364
|
-
/** 校验并写回 settings(storage.json 的 settings 键,原子写);返回错误信息或 null。
|
|
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:
|
|
720
|
+
writeFileSync(tmp, JSON.stringify({ ...existing, settings: persist }));
|
|
413
721
|
renameSync(tmp, file);
|
|
414
722
|
}
|
|
415
723
|
catch (err) {
|
|
@@ -460,8 +768,20 @@ export class PluginManager {
|
|
|
460
768
|
onGrantsChanged = undefined;
|
|
461
769
|
/** 插件运行时注册的 UI 贡献(host.ui.register/arrange),随 plugins 清单推送。 */
|
|
462
770
|
uiRuntime = new Map();
|
|
771
|
+
/** 通用反向代理注册表:归一化前缀 → { 插件 id, 回环目标 }(index.ts 按最长前缀命中透传)。 */
|
|
772
|
+
proxyRoutes = new Map();
|
|
463
773
|
/** manifest "ui" 基线(每次 scan 刷新;host.ui.list 与合并都读它)。 */
|
|
464
774
|
uiBase = new Map();
|
|
775
|
+
/** manifest 解析诊断(每次 scan 重算;合法插件无诊断时记空数组)。 */
|
|
776
|
+
manifestDiags = new Map();
|
|
777
|
+
/** 运行时诊断(工具/命令/路由/门控拒绝、激活失败等;反激活时随插件一起清)。
|
|
778
|
+
* 只做可观测性:存一份 console.error/console.warn 之外的摘要,随 UiPluginInfo
|
|
779
|
+
* 下发给设置面板“界面插件”页展开查看,不改变任何隔离/权限语义。 */
|
|
780
|
+
runtimeDiags = new Map();
|
|
781
|
+
/** 运行时分级日志(host.log 写入):内存环形缓冲,每插件最近 200 条。
|
|
782
|
+
* 不落盘、随进程走;只经 plugin_data 按需拉取,绝不进 60ms 快照
|
|
783
|
+
* (与 diagnostics 的“只读诊断随清单下发”正交,互不冲突)。 */
|
|
784
|
+
pluginLogs = new Map();
|
|
465
785
|
constructor(dataDir, cwd,
|
|
466
786
|
/** 随包发布的默认插件列表(<pkgRoot>/plugins/catalog.json)。缺省 = 无内置列表。 */
|
|
467
787
|
builtinCatalogPath) {
|
|
@@ -469,6 +789,7 @@ export class PluginManager {
|
|
|
469
789
|
this.builtinCatalogPath = builtinCatalogPath;
|
|
470
790
|
this.cwdValue = resolve(cwd);
|
|
471
791
|
this.grants = new PluginGrantsStore(dataDir);
|
|
792
|
+
this.permGrants = new PluginPermissionStore(dataDir);
|
|
472
793
|
this.domConsentStore = new PluginDomConsent(dataDir);
|
|
473
794
|
}
|
|
474
795
|
/** index.ts 在客户端 set_cwd 成功后调用:更新全局工作区并扇出给
|
|
@@ -572,7 +893,7 @@ export class PluginManager {
|
|
|
572
893
|
return {
|
|
573
894
|
error: pick(l, "该插件没有声明式设置(manifest 未声明 settings)", "This plugin has no declarative settings (manifest declares no settings)", "plugins.settings.no.declarative"),
|
|
574
895
|
};
|
|
575
|
-
const { error, clean } = saveSettingsValues(dir, schema, values, lang);
|
|
896
|
+
const { error, clean } = saveSettingsValues(dir, schema, values, lang, new PluginSecrets(this.dataDir, dir));
|
|
576
897
|
if (error)
|
|
577
898
|
return { error };
|
|
578
899
|
// 通知插件(异常隔离)
|
|
@@ -608,6 +929,10 @@ export class PluginManager {
|
|
|
608
929
|
async pushCatalog() {
|
|
609
930
|
this.deliverAll({ type: "plugin_catalog", entries: this.catalog(), epoch: this.catalogEpoch });
|
|
610
931
|
}
|
|
932
|
+
/** 把能力授权表推给所有 socket(attach 推 + 授权/撤销后重推)。 */
|
|
933
|
+
async pushPermissions() {
|
|
934
|
+
this.deliverAll({ type: "plugin_permissions", grants: this.permGrants.list() });
|
|
935
|
+
}
|
|
611
936
|
/** 往用户自定义列表加一条(同 id 覆盖);返回错误信息或 null(成功)。
|
|
612
937
|
* 成功后 epoch+1 并重推列表。 */
|
|
613
938
|
addCatalogEntry(input, lang) {
|
|
@@ -649,6 +974,22 @@ export class PluginManager {
|
|
|
649
974
|
handleMessage(pluginId, payload, from) {
|
|
650
975
|
if (!ID_RE.test(pluginId))
|
|
651
976
|
return;
|
|
977
|
+
// 宿主保留通道:运行时日志按需拉取/清空(directed plugin_data 回包)。
|
|
978
|
+
// 不进插件 onMessage(插件不可见),from 缺席时无法定向回包则静默丢弃。
|
|
979
|
+
if (isPluginLogsRequest(payload)) {
|
|
980
|
+
if (!from)
|
|
981
|
+
return;
|
|
982
|
+
const cleared = payload.op === "clear";
|
|
983
|
+
if (cleared)
|
|
984
|
+
this.clearPluginLogs(pluginId);
|
|
985
|
+
const down = {
|
|
986
|
+
__host: "logs",
|
|
987
|
+
logs: this.getPluginLogs(pluginId),
|
|
988
|
+
...(cleared ? { cleared: true } : {}),
|
|
989
|
+
};
|
|
990
|
+
this.sendTo(from, pluginId, down);
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
652
993
|
const handlers = this.messageHandlers.get(pluginId);
|
|
653
994
|
if (!handlers)
|
|
654
995
|
return;
|
|
@@ -729,6 +1070,39 @@ export class PluginManager {
|
|
|
729
1070
|
res.end();
|
|
730
1071
|
}
|
|
731
1072
|
}
|
|
1073
|
+
/** 注册通用代理前缀(host.registerProxy 的本体,index.ts 只读 findProxy)。
|
|
1074
|
+
* 成功返回归一化前缀;前缀非法/目标非法/被其它插件占用返回 null(调用方记诊断)。 */
|
|
1075
|
+
registerProxy(pluginId, prefix, target) {
|
|
1076
|
+
const p = normalizeProxyPrefix(prefix);
|
|
1077
|
+
const t = normalizeProxyTarget(target);
|
|
1078
|
+
if (!p || !t)
|
|
1079
|
+
return null;
|
|
1080
|
+
const taken = this.proxyRoutes.get(p);
|
|
1081
|
+
if (taken && taken.pluginId !== pluginId)
|
|
1082
|
+
return null;
|
|
1083
|
+
this.proxyRoutes.set(p, { pluginId, host: t.host, port: t.port });
|
|
1084
|
+
return p;
|
|
1085
|
+
}
|
|
1086
|
+
/** 注销代理前缀(同插件才能注销自己的;返回是否真删掉了)。 */
|
|
1087
|
+
unregisterProxy(pluginId, prefix) {
|
|
1088
|
+
const p = normalizeProxyPrefix(prefix);
|
|
1089
|
+
if (!p)
|
|
1090
|
+
return false;
|
|
1091
|
+
if (this.proxyRoutes.get(p)?.pluginId !== pluginId)
|
|
1092
|
+
return false;
|
|
1093
|
+
return this.proxyRoutes.delete(p);
|
|
1094
|
+
}
|
|
1095
|
+
/** index.ts 转发/upgrade 共用:请求路径的最长前缀命中(无命中返回 undefined)。
|
|
1096
|
+
* 查表前小写化:注册前缀统一小写归一,大小写混写也命中同一条。 */
|
|
1097
|
+
findProxy(path) {
|
|
1098
|
+
const p = matchProxyPrefix(String(path ?? "").toLowerCase(), this.proxyRoutes.keys());
|
|
1099
|
+
if (!p)
|
|
1100
|
+
return undefined;
|
|
1101
|
+
const hit = this.proxyRoutes.get(p);
|
|
1102
|
+
if (!hit)
|
|
1103
|
+
return undefined;
|
|
1104
|
+
return { prefix: p, ...hit };
|
|
1105
|
+
}
|
|
732
1106
|
broadcast(pluginId, payload) {
|
|
733
1107
|
this.deliverAll({ type: "plugin_data", pluginId, payload });
|
|
734
1108
|
}
|
|
@@ -824,6 +1198,9 @@ export class PluginManager {
|
|
|
824
1198
|
conversationProvider = undefined;
|
|
825
1199
|
/** index.ts 注入:插件无头调用 agent(微信通道等经 host.chat 调用)。 */
|
|
826
1200
|
chatProvider = undefined;
|
|
1201
|
+
/** 由 index.ts 接入 agent-service:插件直调模型(host.llm.complete 的底层,孤立无工具会话)。
|
|
1202
|
+
* 无注入回 {ok:false}(如 DSH 引擎),绝不抛错。 */
|
|
1203
|
+
llmProvider = undefined;
|
|
827
1204
|
/** 由 index.ts 接入 agent-service:对话列表(host.conversations.list 的底层)。
|
|
828
1205
|
* 同步数组与 Promise 都收(index.ts 接线是 async 的),host 侧归一化。无注入回 []。 */
|
|
829
1206
|
conversationLister = undefined;
|
|
@@ -839,6 +1216,13 @@ export class PluginManager {
|
|
|
839
1216
|
runAborter = undefined;
|
|
840
1217
|
/** 由 index.ts 接入 agent-service:模型列表(host.models.list 的底层)。无注入回 []。 */
|
|
841
1218
|
modelLister = undefined;
|
|
1219
|
+
/** 插件能力动态授权表(host.requestPermission 的底层,见 server/plugin-permissions.ts)。 */
|
|
1220
|
+
permGrants;
|
|
1221
|
+
/** 由 index.ts 注入:向浏览器请求能力授权的用户确认({ok, remember})。
|
|
1222
|
+
* 未注入(DSH/无浏览器)时 requestPermission 直接回 false。 */
|
|
1223
|
+
permissionRequester = undefined;
|
|
1224
|
+
/** 授权表**变了**(新授权落盘/撤销)时触发 —— 设置面板「已授权能力」即时刷新。 */
|
|
1225
|
+
onPermGrantsChanged = undefined;
|
|
842
1226
|
/** 会话统计订阅(host.onStats 注册到这里;emitStats 异常隔离扇出)。 */
|
|
843
1227
|
statsHandlers = new Set();
|
|
844
1228
|
/** 流式增量订阅(host.onStreaming 注册到这里;emitStreaming 只透传,发送方负责节流)。 */
|
|
@@ -882,6 +1266,7 @@ export class PluginManager {
|
|
|
882
1266
|
const fam = String(family ?? "");
|
|
883
1267
|
const deny = (what) => {
|
|
884
1268
|
console.error(`[plugin:${pluginId}] 缺少能力声明 "${what}"(manifest.permissions)——请求被拒`);
|
|
1269
|
+
this.pushRuntimeDiag(pluginId, `missing capability "${what}" (manifest.permissions) — request denied`);
|
|
885
1270
|
return false;
|
|
886
1271
|
};
|
|
887
1272
|
if (!rec)
|
|
@@ -984,6 +1369,30 @@ export class PluginManager {
|
|
|
984
1369
|
}
|
|
985
1370
|
}
|
|
986
1371
|
}
|
|
1372
|
+
/** 某插件的 AI 工具展示快照(设置面板用;按工具名稳定排序;无工具回 [])。
|
|
1373
|
+
* 纯展示字段,不含 execute。 */
|
|
1374
|
+
agentToolsSnapshot(pluginId) {
|
|
1375
|
+
const table = this.agentTools.get(pluginId);
|
|
1376
|
+
if (!table)
|
|
1377
|
+
return [];
|
|
1378
|
+
return [...table.values()]
|
|
1379
|
+
.map((t) => ({
|
|
1380
|
+
name: t.name,
|
|
1381
|
+
...(t.label ? { label: t.label } : {}),
|
|
1382
|
+
...(t.description ? { description: t.description } : {}),
|
|
1383
|
+
}))
|
|
1384
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
1385
|
+
}
|
|
1386
|
+
/** 全部分组快照(设置面板“按插件分组”展示用;无工具的插件不出现;按插件 id 排序)。 */
|
|
1387
|
+
getAgentToolsGrouped() {
|
|
1388
|
+
const out = [];
|
|
1389
|
+
for (const pid of [...this.agentTools.keys()].sort()) {
|
|
1390
|
+
const tools = this.agentToolsSnapshot(pid);
|
|
1391
|
+
if (tools.length)
|
|
1392
|
+
out.push({ pluginId: pid, tools });
|
|
1393
|
+
}
|
|
1394
|
+
return out;
|
|
1395
|
+
}
|
|
987
1396
|
/** 当前全部插件注册的 AI 工具(扁平化,按插件 id 稳定排序)。 */
|
|
988
1397
|
getAgentTools() {
|
|
989
1398
|
const out = [];
|
|
@@ -995,6 +1404,7 @@ export class PluginManager {
|
|
|
995
1404
|
registerAgentTool(pluginId, tool) {
|
|
996
1405
|
if (!tool || typeof tool.execute !== "function" || !tool.name || !tool.description) {
|
|
997
1406
|
console.error(`[plugin:${pluginId}] registerAgentTool: 缺少 name/description/execute,忽略`);
|
|
1407
|
+
this.pushRuntimeDiag(pluginId, "registerAgentTool: missing name/description/execute, ignored");
|
|
998
1408
|
return () => { };
|
|
999
1409
|
}
|
|
1000
1410
|
let table = this.agentTools.get(pluginId);
|
|
@@ -1002,6 +1412,7 @@ export class PluginManager {
|
|
|
1002
1412
|
this.agentTools.set(pluginId, (table = new Map()));
|
|
1003
1413
|
if (table.has(tool.name)) {
|
|
1004
1414
|
console.error(`[plugin:${pluginId}] AI 工具 "${tool.name}" 重复注册,忽略`);
|
|
1415
|
+
this.pushRuntimeDiag(pluginId, `agent tool "${tool.name}": duplicate registration, ignored`);
|
|
1005
1416
|
return () => { };
|
|
1006
1417
|
}
|
|
1007
1418
|
table.set(tool.name, tool);
|
|
@@ -1030,15 +1441,18 @@ export class PluginManager {
|
|
|
1030
1441
|
const name = String(cmd?.name ?? "").replace(/^\/+/, ""); // 容忍误带的前导 /
|
|
1031
1442
|
if (!/^[a-zA-Z][a-zA-Z0-9:_-]*$/.test(name)) {
|
|
1032
1443
|
console.error(`[plugin:${pluginId}] registerCommand: 非法名称「${cmd?.name}」(需字母开头,允许字母数字:_-),忽略`);
|
|
1444
|
+
this.pushRuntimeDiag(pluginId, `registerCommand: invalid name "${String(cmd?.name ?? "").slice(0, 32)}", ignored`);
|
|
1033
1445
|
return () => { };
|
|
1034
1446
|
}
|
|
1035
1447
|
if (typeof cmd?.run !== "function") {
|
|
1036
1448
|
console.error(`[plugin:${pluginId}] registerCommand: ${name} 缺少 run,忽略`);
|
|
1449
|
+
this.pushRuntimeDiag(pluginId, `command "/${name}": missing run, ignored`);
|
|
1037
1450
|
return () => { };
|
|
1038
1451
|
}
|
|
1039
1452
|
for (const [pid, table] of this.pluginCommands) {
|
|
1040
1453
|
if (table.has(name) && pid !== pluginId) {
|
|
1041
1454
|
console.error(`[plugin:${pluginId}] 命令 /${name} 已被插件 ${pid} 注册,忽略重复`);
|
|
1455
|
+
this.pushRuntimeDiag(pluginId, `command "/${name}": already registered by plugin ${pid}, ignored`);
|
|
1042
1456
|
return () => { };
|
|
1043
1457
|
}
|
|
1044
1458
|
}
|
|
@@ -1047,6 +1461,7 @@ export class PluginManager {
|
|
|
1047
1461
|
this.pluginCommands.set(pluginId, (table = new Map()));
|
|
1048
1462
|
if (table.has(name)) {
|
|
1049
1463
|
console.error(`[plugin:${pluginId}] 命令 /${name} 重复注册,忽略`);
|
|
1464
|
+
this.pushRuntimeDiag(pluginId, `command "/${name}": duplicate registration, ignored`);
|
|
1050
1465
|
return () => { };
|
|
1051
1466
|
}
|
|
1052
1467
|
const def = { ...cmd, name };
|
|
@@ -1099,6 +1514,61 @@ export class PluginManager {
|
|
|
1099
1514
|
uiOf(pluginId) {
|
|
1100
1515
|
return mergeUiPluginUi(this.uiBase.get(pluginId), this.uiRuntime.get(pluginId));
|
|
1101
1516
|
}
|
|
1517
|
+
/** 追加一条运行时诊断(去重 + 100 条封顶),并同步到已加载条目的 info 快照。
|
|
1518
|
+
* 去重是因为门控拒绝(canUse)会在每次调用时触发,重复调用不应刷屏。 */
|
|
1519
|
+
pushRuntimeDiag(pluginId, msg) {
|
|
1520
|
+
if (!ID_RE.test(pluginId))
|
|
1521
|
+
return;
|
|
1522
|
+
let arr = this.runtimeDiags.get(pluginId);
|
|
1523
|
+
if (!arr)
|
|
1524
|
+
this.runtimeDiags.set(pluginId, (arr = []));
|
|
1525
|
+
if (arr.includes(msg))
|
|
1526
|
+
return;
|
|
1527
|
+
if (arr.length < 100)
|
|
1528
|
+
arr.push(msg);
|
|
1529
|
+
const p = this.loaded.get(pluginId);
|
|
1530
|
+
if (p) {
|
|
1531
|
+
const combined = this.diagnosticsOf(pluginId);
|
|
1532
|
+
if (combined)
|
|
1533
|
+
p.info.diagnostics = combined;
|
|
1534
|
+
else
|
|
1535
|
+
delete p.info.diagnostics;
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
/** 合并某插件的诊断(manifest 解析 + 运行时),无诊断返回 undefined。
|
|
1539
|
+
* 返回的是快照拷贝,调用方可直接挂到 UiPluginInfo 上。 */
|
|
1540
|
+
diagnosticsOf(pluginId) {
|
|
1541
|
+
const m = this.manifestDiags.get(pluginId) ?? [];
|
|
1542
|
+
const r = this.runtimeDiags.get(pluginId) ?? [];
|
|
1543
|
+
if (!m.length && !r.length)
|
|
1544
|
+
return undefined;
|
|
1545
|
+
return [...m, ...r].slice(0, 100);
|
|
1546
|
+
}
|
|
1547
|
+
/** 追加一条运行时日志(封顶丢弃最旧的;文本截断封顶)。 */
|
|
1548
|
+
appendPluginLog(pluginId, level, text) {
|
|
1549
|
+
if (!ID_RE.test(pluginId))
|
|
1550
|
+
return;
|
|
1551
|
+
let arr = this.pluginLogs.get(pluginId);
|
|
1552
|
+
if (!arr)
|
|
1553
|
+
this.pluginLogs.set(pluginId, (arr = []));
|
|
1554
|
+
arr.push({
|
|
1555
|
+
ts: Date.now(),
|
|
1556
|
+
level,
|
|
1557
|
+
text: text.length > PLUGIN_LOG_TEXT_MAX ? text.slice(0, PLUGIN_LOG_TEXT_MAX) : text,
|
|
1558
|
+
});
|
|
1559
|
+
if (arr.length > PLUGIN_LOG_CAP)
|
|
1560
|
+
arr.splice(0, arr.length - PLUGIN_LOG_CAP);
|
|
1561
|
+
}
|
|
1562
|
+
/** 读某插件的运行时日志(快照拷贝;未知插件回 [])。 */
|
|
1563
|
+
getPluginLogs(pluginId) {
|
|
1564
|
+
return (this.pluginLogs.get(pluginId) ?? []).map((e) => ({ ...e }));
|
|
1565
|
+
}
|
|
1566
|
+
/** 清空某插件的运行时日志(设置面板“清空”按钮用)。 */
|
|
1567
|
+
clearPluginLogs(pluginId) {
|
|
1568
|
+
if (!ID_RE.test(pluginId))
|
|
1569
|
+
return;
|
|
1570
|
+
this.pluginLogs.set(pluginId, []);
|
|
1571
|
+
}
|
|
1102
1572
|
deliverAll(msg) {
|
|
1103
1573
|
for (const s of this.senders) {
|
|
1104
1574
|
try {
|
|
@@ -1133,11 +1603,24 @@ export class PluginManager {
|
|
|
1133
1603
|
this.deactivateEntry(id, p);
|
|
1134
1604
|
}
|
|
1135
1605
|
}
|
|
1136
|
-
return found.map((f) =>
|
|
1606
|
+
return found.map((f) => {
|
|
1607
|
+
const base = this.loaded.get(f.id)?.info ?? f;
|
|
1608
|
+
const agentTools = this.agentToolsSnapshot(f.id);
|
|
1609
|
+
if (agentTools.length)
|
|
1610
|
+
return { ...base, agentTools };
|
|
1611
|
+
const { agentTools: _drop, ...rest } = base;
|
|
1612
|
+
return rest;
|
|
1613
|
+
});
|
|
1137
1614
|
}
|
|
1138
1615
|
/** 反激活清理:把该插件名下全部订阅/注册一次收完(工具/命令/watch/定时/
|
|
1139
1616
|
* 总线/stats/流式——参考 agentToolUnsubscribers 模式,新增订阅一律走这里)。 */
|
|
1140
1617
|
releaseEntry(p) {
|
|
1618
|
+
// 该插件注册的代理前缀随反激活一起回收(全局表按 pluginId 过滤;
|
|
1619
|
+
// Map 迭代中删除是良定义的:删过的条目不会再被访问到)。
|
|
1620
|
+
for (const [prefix, hit] of this.proxyRoutes) {
|
|
1621
|
+
if (hit.pluginId === p.info.id)
|
|
1622
|
+
this.proxyRoutes.delete(prefix);
|
|
1623
|
+
}
|
|
1141
1624
|
// eslint-disable-next-line unicorn/no-useless-spread -- snapshot: handlers may unsubscribe mid-emit
|
|
1142
1625
|
for (const off of [
|
|
1143
1626
|
...(p.agentToolUnsubscribers ?? []),
|
|
@@ -1177,6 +1660,11 @@ export class PluginManager {
|
|
|
1177
1660
|
// 运行时 UI 注册随插件一起消失(manifest 基线留着,重扫时会重算)。
|
|
1178
1661
|
this.uiRuntime.delete(id);
|
|
1179
1662
|
this.uiBase.delete(id);
|
|
1663
|
+
// 诊断随插件一起清:目录回来重新激活时会重算(旧诊断留着会误导)。
|
|
1664
|
+
this.manifestDiags.delete(id);
|
|
1665
|
+
this.runtimeDiags.delete(id);
|
|
1666
|
+
// 运行时日志同样随插件走(内存缓冲,不落盘)。
|
|
1667
|
+
this.pluginLogs.delete(id);
|
|
1180
1668
|
// 重新激活时会 import 磁盘上的 index.mjs:Node 的 ESM 缓存按 URL(含 ?e=)
|
|
1181
1669
|
// 命中,epoch 不变就会拿到旧模块(更新插件后还是旧代码)——所以这里也 +1,
|
|
1182
1670
|
// 顺带让浏览器端 ?e= 变化、重拉插件的 client bundle。
|
|
@@ -1204,6 +1692,10 @@ export class PluginManager {
|
|
|
1204
1692
|
this.pluginBgTasks.clear();
|
|
1205
1693
|
this.loaded.clear();
|
|
1206
1694
|
this.messageHandlers.clear();
|
|
1695
|
+
// reload() 走 dispose→ensureLoaded:诊断清掉重算,不跨代累积。
|
|
1696
|
+
this.manifestDiags.clear();
|
|
1697
|
+
this.runtimeDiags.clear();
|
|
1698
|
+
this.pluginLogs.clear();
|
|
1207
1699
|
}
|
|
1208
1700
|
/** 读 manifest 清单;坏目录(无 manifest/id 非法)直接跳过。 */
|
|
1209
1701
|
async scan() {
|
|
@@ -1227,6 +1719,8 @@ export class PluginManager {
|
|
|
1227
1719
|
const m = JSON.parse(raw);
|
|
1228
1720
|
const wantsDom = declarationWantsDom(m.permissions);
|
|
1229
1721
|
this.domWants.set(name, wantsDom);
|
|
1722
|
+
// 本轮 manifest 解析的诊断(重算覆盖;运行时诊断另存在 runtimeDiags)。
|
|
1723
|
+
const uiDiags = [];
|
|
1230
1724
|
out.push({
|
|
1231
1725
|
id: name,
|
|
1232
1726
|
name: typeof m.name === "string" && m.name ? m.name : name,
|
|
@@ -1272,7 +1766,7 @@ export class PluginManager {
|
|
|
1272
1766
|
: {}),
|
|
1273
1767
|
// 声明式设置 schema + 当前存值(⚙ 面板自动渲染表单用)
|
|
1274
1768
|
settingsSchema: parseSettingsSchema(m.settings),
|
|
1275
|
-
settingsValues: storedSettingsValues(dir, parseSettingsSchema(m.settings)),
|
|
1769
|
+
settingsValues: storedSettingsValues(dir, parseSettingsSchema(m.settings), new PluginSecrets(this.dataDir, dir)),
|
|
1276
1770
|
// 可渲染的 fenced-code 语言(manifest "renderers")——前端据此按需加载
|
|
1277
1771
|
renderers: Array.isArray(m.renderers)
|
|
1278
1772
|
? m.renderers.filter((r) => typeof r === "string" && r.length > 0).slice(0, 32)
|
|
@@ -1300,9 +1794,11 @@ export class PluginManager {
|
|
|
1300
1794
|
const strict = perms.length > 0 || apiVersion >= 2;
|
|
1301
1795
|
if (strict && !perms.some((x) => x.split(":")[0] === "ui")) {
|
|
1302
1796
|
this.uiBase.delete(name);
|
|
1797
|
+
if (m.ui !== undefined)
|
|
1798
|
+
uiDiags.push('ui ignored: strict mode requires "ui" capability (manifest.permissions)');
|
|
1303
1799
|
return undefined;
|
|
1304
1800
|
}
|
|
1305
|
-
const base = parseUiContributions(m.ui);
|
|
1801
|
+
const base = m.ui === undefined ? undefined : parseUiContributions(m.ui, uiDiags);
|
|
1306
1802
|
if (base)
|
|
1307
1803
|
this.uiBase.set(name, base);
|
|
1308
1804
|
else
|
|
@@ -1323,6 +1819,21 @@ export class PluginManager {
|
|
|
1323
1819
|
})
|
|
1324
1820
|
.catch(() => undefined),
|
|
1325
1821
|
});
|
|
1822
|
+
// 诊断随清单下发:manifest 解析 + 到目前为止的运行时诊断。
|
|
1823
|
+
this.manifestDiags.set(name, uiDiags);
|
|
1824
|
+
const agentTools = this.agentToolsSnapshot(name);
|
|
1825
|
+
if (agentTools.length)
|
|
1826
|
+
out[out.length - 1].agentTools = agentTools;
|
|
1827
|
+
const scanned = [...uiDiags, ...(this.runtimeDiags.get(name) ?? [])].slice(0, 100);
|
|
1828
|
+
if (scanned.length)
|
|
1829
|
+
out[out.length - 1].diagnostics = scanned;
|
|
1830
|
+
const lp = this.loaded.get(name);
|
|
1831
|
+
if (lp) {
|
|
1832
|
+
if (scanned.length)
|
|
1833
|
+
lp.info.diagnostics = [...scanned];
|
|
1834
|
+
else
|
|
1835
|
+
delete lp.info.diagnostics;
|
|
1836
|
+
}
|
|
1326
1837
|
}
|
|
1327
1838
|
catch {
|
|
1328
1839
|
continue; // 无 manifest / JSON 坏 —— 不是插件
|
|
@@ -1333,6 +1844,13 @@ export class PluginManager {
|
|
|
1333
1844
|
if (!out.some((p) => p.id === key))
|
|
1334
1845
|
this.domWants.delete(key);
|
|
1335
1846
|
}
|
|
1847
|
+
for (const key of [...this.manifestDiags.keys(), ...this.runtimeDiags.keys(), ...this.pluginLogs.keys()]) {
|
|
1848
|
+
if (!out.some((p) => p.id === key)) {
|
|
1849
|
+
this.manifestDiags.delete(key);
|
|
1850
|
+
this.runtimeDiags.delete(key);
|
|
1851
|
+
this.pluginLogs.delete(key);
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1336
1854
|
return out;
|
|
1337
1855
|
}
|
|
1338
1856
|
async activate(info, lang) {
|
|
@@ -1361,8 +1879,9 @@ export class PluginManager {
|
|
|
1361
1879
|
if (apiVersion > PLUGIN_API_VERSION) {
|
|
1362
1880
|
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
1881
|
console.error(`[plugin:${info.id}] ${msg}`);
|
|
1882
|
+
this.pushRuntimeDiag(info.id, `requires host API v${apiVersion} but host is v${PLUGIN_API_VERSION} — please upgrade pi-web-ui`);
|
|
1364
1883
|
this.loaded.set(info.id, {
|
|
1365
|
-
info: { ...info, error: msg },
|
|
1884
|
+
info: { ...info, error: msg, diagnostics: this.diagnosticsOf(info.id) },
|
|
1366
1885
|
toolHandlers,
|
|
1367
1886
|
runHandlers,
|
|
1368
1887
|
convChangeHandlers,
|
|
@@ -1387,8 +1906,9 @@ export class PluginManager {
|
|
|
1387
1906
|
if (verdict === false) {
|
|
1388
1907
|
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
1908
|
console.error(`[plugin:${info.id}] ${msg}`);
|
|
1909
|
+
this.pushRuntimeDiag(info.id, `requires pi-web-ui ${enginesReq} but host is ${hostVer} — please upgrade pi-web-ui`);
|
|
1390
1910
|
this.loaded.set(info.id, {
|
|
1391
|
-
info: { ...info, error: msg },
|
|
1911
|
+
info: { ...info, error: msg, diagnostics: this.diagnosticsOf(info.id) },
|
|
1392
1912
|
toolHandlers,
|
|
1393
1913
|
runHandlers,
|
|
1394
1914
|
convChangeHandlers,
|
|
@@ -1401,11 +1921,13 @@ export class PluginManager {
|
|
|
1401
1921
|
}
|
|
1402
1922
|
if (verdict === null) {
|
|
1403
1923
|
console.warn(`[plugin:${info.id}] engines 约束「${enginesReq}」解析失败,已放行(不阻断激活)`);
|
|
1924
|
+
this.pushRuntimeDiag(info.id, `engines constraint "${enginesReq}" unparseable, allowed without blocking`);
|
|
1404
1925
|
}
|
|
1405
1926
|
}
|
|
1406
1927
|
for (const peer of info.peerPlugins ?? []) {
|
|
1407
1928
|
if (!existsSync(join(this.pluginsDir, peer))) {
|
|
1408
1929
|
console.warn(`[plugin:${info.id}] 对等插件缺失:${peer}(仅警告,不阻断激活)`);
|
|
1930
|
+
this.pushRuntimeDiag(info.id, `peer plugin missing: ${peer} (warn only, activation continues)`);
|
|
1409
1931
|
}
|
|
1410
1932
|
}
|
|
1411
1933
|
// 新增订阅的取消函数(反激活时经 releaseEntry 统一释放)。
|
|
@@ -1453,6 +1975,73 @@ export class PluginManager {
|
|
|
1453
1975
|
const abs = allowAbs(absPath);
|
|
1454
1976
|
await rm(abs, { recursive: true, force: true });
|
|
1455
1977
|
},
|
|
1978
|
+
stat: async (absPath) => {
|
|
1979
|
+
const abs = allowAbs(absPath);
|
|
1980
|
+
const st = await stat(abs);
|
|
1981
|
+
const base = abs
|
|
1982
|
+
.replace(/[/\\]+$/, "")
|
|
1983
|
+
.split("/")
|
|
1984
|
+
.pop() ?? abs;
|
|
1985
|
+
return {
|
|
1986
|
+
name: base,
|
|
1987
|
+
type: (st.isDirectory() ? "dir" : "file"),
|
|
1988
|
+
size: st.isDirectory() ? 0 : st.size,
|
|
1989
|
+
mtime: Number(st.mtimeMs) || 0,
|
|
1990
|
+
};
|
|
1991
|
+
},
|
|
1992
|
+
mkdir: async (absDir) => {
|
|
1993
|
+
await mkdir(allowAbs(absDir), { recursive: true });
|
|
1994
|
+
},
|
|
1995
|
+
append: async (absPath, data) => {
|
|
1996
|
+
const abs = allowAbs(absPath);
|
|
1997
|
+
await mkdir(dirname(abs), { recursive: true });
|
|
1998
|
+
await writeFile(abs, data, { flag: "a" });
|
|
1999
|
+
},
|
|
2000
|
+
glob: async (absDir, pattern) => {
|
|
2001
|
+
const { globToRegExp } = await import("./plugin-facilities.js");
|
|
2002
|
+
const pat = String(pattern ?? "")
|
|
2003
|
+
.trim()
|
|
2004
|
+
.replace(/\\/g, "/");
|
|
2005
|
+
if (!pat)
|
|
2006
|
+
throw new Error("globPath: pattern 为空");
|
|
2007
|
+
const re = globToRegExp(pat);
|
|
2008
|
+
const base = allowAbs(absDir);
|
|
2009
|
+
const out = [];
|
|
2010
|
+
const stack = [base];
|
|
2011
|
+
let walked = 0;
|
|
2012
|
+
while (stack.length && walked < 2000 && out.length < 500) {
|
|
2013
|
+
const dir = stack.pop();
|
|
2014
|
+
let ents;
|
|
2015
|
+
try {
|
|
2016
|
+
ents = await readdir(dir, { withFileTypes: true });
|
|
2017
|
+
}
|
|
2018
|
+
catch {
|
|
2019
|
+
continue;
|
|
2020
|
+
}
|
|
2021
|
+
for (const e of ents) {
|
|
2022
|
+
if (walked++ >= 2000 || out.length >= 500)
|
|
2023
|
+
break;
|
|
2024
|
+
const abs = join(dir, e.name);
|
|
2025
|
+
// 跨目录返回绝对路径(调用方直接可用);匹配仍按相对 base 的部分。
|
|
2026
|
+
// 先转分隔符再去前导斜杠(顺序反了会留下 "/n.txt" 导致匹配失败)。
|
|
2027
|
+
const rel = abs
|
|
2028
|
+
.slice(base.length)
|
|
2029
|
+
.replace(/\\/g, "/")
|
|
2030
|
+
.split("/")
|
|
2031
|
+
.filter((s) => s.length > 0)
|
|
2032
|
+
.join("/");
|
|
2033
|
+
if (e.isDirectory()) {
|
|
2034
|
+
if (re.test(rel) || re.test(`${rel}/`))
|
|
2035
|
+
out.push(abs);
|
|
2036
|
+
stack.push(abs);
|
|
2037
|
+
}
|
|
2038
|
+
else if (re.test(rel)) {
|
|
2039
|
+
out.push(abs);
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
return out;
|
|
2044
|
+
},
|
|
1456
2045
|
};
|
|
1457
2046
|
const self = this; // 对象字面量 getter 里不能用插件宿主的 this (oxlint no-this-alias: 誤報, getter closure 需要 host)
|
|
1458
2047
|
// 能力门控快照:host 对象可用之前(loaded.set 之前)canUse 也要能判定。
|
|
@@ -1519,6 +2108,89 @@ export class PluginManager {
|
|
|
1519
2108
|
return { ok: false, error: err.message };
|
|
1520
2109
|
}
|
|
1521
2110
|
},
|
|
2111
|
+
llm: {
|
|
2112
|
+
complete: async (req) => {
|
|
2113
|
+
if (!can("llm"))
|
|
2114
|
+
return { ok: false, error: `插件未声明能力 "llm"(manifest.permissions)——请求被拒` };
|
|
2115
|
+
// 有模型作用域授权时收紧到批准的模型(无授权=声明即全开,向后兼容)。
|
|
2116
|
+
const model = typeof req?.model === "string" ? req.model.trim() : "";
|
|
2117
|
+
if (model && !self.permGrants.modelAllowed(info.id, model))
|
|
2118
|
+
return {
|
|
2119
|
+
ok: false,
|
|
2120
|
+
error: `llm: 模型 ${model} 不在用户批准的作用域内(可 host.requestPermission 重新申请)`,
|
|
2121
|
+
};
|
|
2122
|
+
if (!self.llmProvider)
|
|
2123
|
+
return { ok: false, error: "宿主未提供 LLM 直调(llmProvider 未接入)" };
|
|
2124
|
+
try {
|
|
2125
|
+
return await self.llmProvider(info.id, req ?? { prompt: "" });
|
|
2126
|
+
}
|
|
2127
|
+
catch (err) {
|
|
2128
|
+
return { ok: false, error: err.message };
|
|
2129
|
+
}
|
|
2130
|
+
},
|
|
2131
|
+
},
|
|
2132
|
+
requestPermission: async (req) => {
|
|
2133
|
+
const family = req?.family;
|
|
2134
|
+
if (family !== "net" && family !== "llm")
|
|
2135
|
+
throw new Error(`requestPermission: 不支持的能力族「${String(family)}」(目前只收 net/llm)`);
|
|
2136
|
+
// 基础族必须已声明(与 requestAccess 要求 fs:read 同口径,fail-closed)。
|
|
2137
|
+
if (!can(family))
|
|
2138
|
+
return false;
|
|
2139
|
+
const hosts = family === "net" && Array.isArray(req.hosts)
|
|
2140
|
+
? req.hosts
|
|
2141
|
+
.filter((x) => typeof x === "string" && x.trim() !== "")
|
|
2142
|
+
.map((x) => x.trim().toLowerCase())
|
|
2143
|
+
.slice(0, 32)
|
|
2144
|
+
: undefined;
|
|
2145
|
+
if (family === "net" && (!hosts || hosts.length === 0))
|
|
2146
|
+
throw new Error("requestPermission: family=net 必须给 hosts(要批准的主机列表)");
|
|
2147
|
+
const models = family === "llm" && Array.isArray(req.models)
|
|
2148
|
+
? req.models
|
|
2149
|
+
.filter((x) => typeof x === "string" && x.includes("/"))
|
|
2150
|
+
.map((x) => x.trim())
|
|
2151
|
+
.slice(0, 32)
|
|
2152
|
+
: undefined;
|
|
2153
|
+
const reason = typeof req.reason === "string"
|
|
2154
|
+
? String(req.reason).slice(0, 200)
|
|
2155
|
+
: undefined;
|
|
2156
|
+
// 已有授权(静态白名单算在执行期,动态表在这里):直接通过,不打扰用户。
|
|
2157
|
+
if (family === "net" && hosts.every((h) => netAllow.some((entry) => h === entry || h.endsWith(`.${entry}`))))
|
|
2158
|
+
return true;
|
|
2159
|
+
if (family === "net" && hosts.every((h) => self.permGrants.has(info.id, "net", { host: h })))
|
|
2160
|
+
return true;
|
|
2161
|
+
if (family === "llm" && self.permGrants.has(info.id, "llm", models?.[0] ? { model: models[0] } : undefined))
|
|
2162
|
+
return true;
|
|
2163
|
+
if (!self.permissionRequester)
|
|
2164
|
+
return false;
|
|
2165
|
+
let ans;
|
|
2166
|
+
try {
|
|
2167
|
+
ans = await self.permissionRequester(info.id, {
|
|
2168
|
+
family,
|
|
2169
|
+
...(hosts ? { hosts } : {}),
|
|
2170
|
+
...(models ? { models } : {}),
|
|
2171
|
+
...(reason ? { reason } : {}),
|
|
2172
|
+
});
|
|
2173
|
+
}
|
|
2174
|
+
catch {
|
|
2175
|
+
return false;
|
|
2176
|
+
}
|
|
2177
|
+
if (!ans?.ok)
|
|
2178
|
+
return false;
|
|
2179
|
+
try {
|
|
2180
|
+
self.permGrants.grant(info.id, family, { hosts, models, reason, remember: ans.remember === true });
|
|
2181
|
+
}
|
|
2182
|
+
catch (err) {
|
|
2183
|
+
console.error(`[plugin:${info.id}] permission grant failed:`, err);
|
|
2184
|
+
return false;
|
|
2185
|
+
}
|
|
2186
|
+
try {
|
|
2187
|
+
self.onPermGrantsChanged?.();
|
|
2188
|
+
}
|
|
2189
|
+
catch {
|
|
2190
|
+
/* 推送失败不影响已完成的授权 */
|
|
2191
|
+
}
|
|
2192
|
+
return true;
|
|
2193
|
+
},
|
|
1522
2194
|
conversations: {
|
|
1523
2195
|
list: () => {
|
|
1524
2196
|
try {
|
|
@@ -1640,11 +2312,25 @@ export class PluginManager {
|
|
|
1640
2312
|
!path.startsWith("/") ||
|
|
1641
2313
|
typeof handler !== "function") {
|
|
1642
2314
|
console.error(`[plugin:${info.id}] route: 非法参数(method=${method} path=${path}),忽略`);
|
|
2315
|
+
self.pushRuntimeDiag(info.id, `route: invalid method/path (method=${String(method)} path=${String(path)}), ignored`);
|
|
1643
2316
|
return () => { };
|
|
1644
2317
|
}
|
|
1645
2318
|
httpRoutes.set(`${m} ${path}`, handler);
|
|
1646
2319
|
return () => httpRoutes.delete(`${m} ${path}`);
|
|
1647
2320
|
},
|
|
2321
|
+
registerProxy: (prefix, target) => {
|
|
2322
|
+
if (!can("http"))
|
|
2323
|
+
return () => { };
|
|
2324
|
+
const p = self.registerProxy(info.id, String(prefix ?? ""), target);
|
|
2325
|
+
if (!p) {
|
|
2326
|
+
console.error(`[plugin:${info.id}] registerProxy: 非法前缀/目标或被占用(prefix=${String(prefix)}),忽略`);
|
|
2327
|
+
self.pushRuntimeDiag(info.id, `registerProxy: invalid prefix/target or taken (prefix=${String(prefix)}), ignored`);
|
|
2328
|
+
return () => { };
|
|
2329
|
+
}
|
|
2330
|
+
return () => {
|
|
2331
|
+
self.unregisterProxy(info.id, p);
|
|
2332
|
+
};
|
|
2333
|
+
},
|
|
1648
2334
|
// 包一层:插件反激活时自动注销它注册的全部 AI 工具,不留悬挂项。
|
|
1649
2335
|
registerAgentTool: (tool) => {
|
|
1650
2336
|
if (!can("tools"))
|
|
@@ -1669,6 +2355,10 @@ export class PluginManager {
|
|
|
1669
2355
|
readText: (p, max) => (canRead() ? workspaceFs.readText(p, max) : NO_FS_PROMISE),
|
|
1670
2356
|
write: (p, data) => (canWrite() ? workspaceFs.write(p, data) : NO_FS_WRITE_PROMISE),
|
|
1671
2357
|
remove: (p) => (canWrite() ? workspaceFs.remove(p) : NO_FS_WRITE_PROMISE),
|
|
2358
|
+
stat: (p) => (canRead() ? workspaceFs.stat(p) : NO_FS_PROMISE),
|
|
2359
|
+
mkdir: (p) => (canWrite() ? workspaceFs.mkdir(p) : NO_FS_WRITE_PROMISE),
|
|
2360
|
+
append: (p, data) => (canWrite() ? workspaceFs.append(p, data) : NO_FS_WRITE_PROMISE),
|
|
2361
|
+
glob: (pat, dir) => (canRead() ? workspaceFs.glob(pat, dir) : NO_FS_PROMISE),
|
|
1672
2362
|
requestAccess: async (dir, reason) => {
|
|
1673
2363
|
if (!canRead())
|
|
1674
2364
|
return false;
|
|
@@ -1701,6 +2391,10 @@ export class PluginManager {
|
|
|
1701
2391
|
readTextPath: (absPath, max) => (canRead() ? crossDirFs.readText(absPath, max) : NO_FS_PROMISE),
|
|
1702
2392
|
writePath: (absPath, data) => (canWrite() ? crossDirFs.write(absPath, data) : NO_FS_WRITE_PROMISE),
|
|
1703
2393
|
removePath: (absPath) => (canWrite() ? crossDirFs.remove(absPath) : NO_FS_WRITE_PROMISE),
|
|
2394
|
+
statPath: (absPath) => (canRead() ? crossDirFs.stat(absPath) : NO_FS_PROMISE),
|
|
2395
|
+
mkdirPath: (absDir) => (canWrite() ? crossDirFs.mkdir(absDir) : NO_FS_WRITE_PROMISE),
|
|
2396
|
+
appendPath: (absPath, data) => (canWrite() ? crossDirFs.append(absPath, data) : NO_FS_WRITE_PROMISE),
|
|
2397
|
+
globPath: (absDir, pat) => (canRead() ? crossDirFs.glob(absDir, pat) : NO_FS_PROMISE),
|
|
1704
2398
|
watch: (relPath, handler) => {
|
|
1705
2399
|
if (!canRead())
|
|
1706
2400
|
throw new Error('插件未声明读能力 "fs"/"fs:read"(manifest.permissions)——请求被拒');
|
|
@@ -1754,6 +2448,7 @@ export class PluginManager {
|
|
|
1754
2448
|
const id = String(task?.id ?? "").trim();
|
|
1755
2449
|
if (!id || bgTaskTable.has(id)) {
|
|
1756
2450
|
console.error(`[plugin:${info.id}] registerBackgroundTask: 非法/重复 id「${task?.id}」,忽略`);
|
|
2451
|
+
self.pushRuntimeDiag(info.id, `registerBackgroundTask: invalid/duplicate id "${String(task?.id ?? "").slice(0, 32)}", ignored`);
|
|
1757
2452
|
return { update: () => { }, unregister: () => { } };
|
|
1758
2453
|
}
|
|
1759
2454
|
const entry = {
|
|
@@ -1798,17 +2493,31 @@ export class PluginManager {
|
|
|
1798
2493
|
if (!can("ui"))
|
|
1799
2494
|
return () => { };
|
|
1800
2495
|
const list = Array.isArray(items) ? items : [items];
|
|
2496
|
+
if (list.length > 32)
|
|
2497
|
+
self.pushRuntimeDiag(info.id, `ui.register: capped at 32 items (${list.length - 32} dropped)`);
|
|
1801
2498
|
const added = [];
|
|
1802
2499
|
const rt = self.uiRuntimeFor(info.id);
|
|
1803
|
-
|
|
2500
|
+
const sliced = list.slice(0, 32);
|
|
2501
|
+
for (let idx = 0; idx < sliced.length; idx++) {
|
|
2502
|
+
const raw = sliced[idx];
|
|
1804
2503
|
const slotRaw = typeof raw?.slot === "string" ? String(raw.slot) : "";
|
|
1805
2504
|
// 与 manifest 解析同口径:先查别名(topbar → topbar.primary)、再校枚举。
|
|
1806
2505
|
// 运行时注册不校验的话,插件给个别名(或写错)会得到一个前端不认识的 slot
|
|
1807
2506
|
// —— buildUiSlots 会静默丢掉它,表现为「注册了但界面上没有」,最难排。
|
|
1808
2507
|
const slot = UI_SLOT_ALIASES[slotRaw] ?? slotRaw;
|
|
1809
|
-
|
|
1810
|
-
|
|
2508
|
+
if (!slot || !UI_SLOTS.has(slot)) {
|
|
2509
|
+
self.pushRuntimeDiag(info.id, `ui.register[#${idx}]: unknown slot "${slotRaw || "(missing)"}", item dropped`);
|
|
1811
2510
|
continue;
|
|
2511
|
+
}
|
|
2512
|
+
const itemDiags = [];
|
|
2513
|
+
const parsed = parseUiItem(raw, slot, itemDiags);
|
|
2514
|
+
for (const m of itemDiags)
|
|
2515
|
+
self.pushRuntimeDiag(info.id, `ui.register: ${m}`);
|
|
2516
|
+
if (!parsed) {
|
|
2517
|
+
if (!itemDiags.length)
|
|
2518
|
+
self.pushRuntimeDiag(info.id, `ui.register[#${idx}]: item in slot "${slot}" dropped`);
|
|
2519
|
+
continue;
|
|
2520
|
+
}
|
|
1812
2521
|
rt.items.set(parsed.id, parsed);
|
|
1813
2522
|
rt.removed.delete(parsed.id);
|
|
1814
2523
|
added.push(parsed.id);
|
|
@@ -1829,8 +2538,10 @@ export class PluginManager {
|
|
|
1829
2538
|
// 只能更新"当前生效"的条目:manifest 声明的与运行时注册的都算,
|
|
1830
2539
|
// 不存在的一律忽略(避免插件凭空造条目绕过声明审查)。
|
|
1831
2540
|
const base = self.uiOf(info.id)?.items.find((x) => x.id === id);
|
|
1832
|
-
if (!base)
|
|
2541
|
+
if (!base) {
|
|
2542
|
+
self.pushRuntimeDiag(info.id, `ui.update: unknown id "${String(id).slice(0, 32)}", ignored`);
|
|
1833
2543
|
return;
|
|
2544
|
+
}
|
|
1834
2545
|
const merged = { ...base, ...patch, id, slot: base.slot };
|
|
1835
2546
|
self.uiRuntimeFor(info.id).items.set(id, merged);
|
|
1836
2547
|
void self.pushToAll().catch(() => { });
|
|
@@ -1844,7 +2555,11 @@ export class PluginManager {
|
|
|
1844
2555
|
arrange: (ops) => {
|
|
1845
2556
|
if (!can("ui"))
|
|
1846
2557
|
return;
|
|
1847
|
-
const
|
|
2558
|
+
const arr = Array.isArray(ops) ? ops : [ops];
|
|
2559
|
+
const arrangeDiags = [];
|
|
2560
|
+
const list = parseUiArrange(arr, arrangeDiags);
|
|
2561
|
+
for (const m of arrangeDiags)
|
|
2562
|
+
self.pushRuntimeDiag(info.id, `ui.arrange: ${m}`);
|
|
1848
2563
|
if (!list.length)
|
|
1849
2564
|
return;
|
|
1850
2565
|
self.uiRuntimeFor(info.id).arrange.push(...list);
|
|
@@ -1852,7 +2567,7 @@ export class PluginManager {
|
|
|
1852
2567
|
},
|
|
1853
2568
|
list: () => self.uiOf(info.id) ?? { items: [], arrange: [] },
|
|
1854
2569
|
},
|
|
1855
|
-
getSettings: () =>
|
|
2570
|
+
getSettings: () => runtimeSettingsValues(dir, info.settingsSchema ?? [], secrets),
|
|
1856
2571
|
onSettingsChanged: (h) => {
|
|
1857
2572
|
settingsHandlers.add(h);
|
|
1858
2573
|
return () => settingsHandlers.delete(h);
|
|
@@ -1923,34 +2638,181 @@ export class PluginManager {
|
|
|
1923
2638
|
};
|
|
1924
2639
|
}
|
|
1925
2640
|
},
|
|
1926
|
-
schedule: (cronOrMs, fn) => {
|
|
2641
|
+
schedule: (cronOrMs, fn, opts) => {
|
|
1927
2642
|
if (typeof fn !== "function")
|
|
1928
2643
|
throw new Error("schedule: fn 必须是函数");
|
|
1929
|
-
|
|
2644
|
+
const persistent = opts?.persistent === true;
|
|
2645
|
+
const catchUp = opts?.catchUp === "once" ? "once" : "skip";
|
|
2646
|
+
const label = typeof opts?.label === "string" &&
|
|
2647
|
+
String(opts.label).trim()
|
|
2648
|
+
? String(opts.label)
|
|
2649
|
+
.trim()
|
|
2650
|
+
.slice(0, 60)
|
|
2651
|
+
: undefined;
|
|
2652
|
+
// 归一化声明:毫秒间隔 或 全 5 字段 cron(旧的 "*/N * * * *" 是它的子集,照常工作)。
|
|
2653
|
+
let ms = 0;
|
|
2654
|
+
let parts;
|
|
2655
|
+
let specText;
|
|
1930
2656
|
if (typeof cronOrMs === "number") {
|
|
1931
|
-
ms = Math.
|
|
2657
|
+
ms = Math.floor(cronOrMs) || 0;
|
|
2658
|
+
if (!(ms > 0))
|
|
2659
|
+
throw new Error("schedule: 间隔毫秒数必须大于 0");
|
|
2660
|
+
ms = Math.min(ms, 2_147_483_647); // setInterval 上限(约 24.8 天),防溢出立即触发
|
|
2661
|
+
ms = Math.max(ms, persistent ? 60_000 : 10_000);
|
|
2662
|
+
specText = String(ms);
|
|
1932
2663
|
}
|
|
1933
2664
|
else if (typeof cronOrMs === "string") {
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
2665
|
+
specText = cronOrMs.trim().replace(/\s+/g, " ");
|
|
2666
|
+
const parsed = parseCronSpec(specText);
|
|
2667
|
+
if (!parsed)
|
|
2668
|
+
throw new Error(`schedule: 不支持的 cron 形状「${cronOrMs}」(要 5 字段:分 时 日 月 周,如 "0 9 * * *")`);
|
|
2669
|
+
parts = parsed;
|
|
1938
2670
|
}
|
|
1939
2671
|
else {
|
|
1940
2672
|
throw new Error("schedule: 参数必须是间隔毫秒数或 cron 字符串");
|
|
1941
2673
|
}
|
|
1942
|
-
|
|
1943
|
-
|
|
2674
|
+
// 持久化:声明落盘(幂等——activate 重调时保留 lastRun/createdAt,只更新声明)。
|
|
2675
|
+
let sid = "";
|
|
2676
|
+
if (persistent) {
|
|
2677
|
+
sid =
|
|
2678
|
+
typeof opts?.id === "string"
|
|
2679
|
+
? String(opts.id).trim()
|
|
2680
|
+
: "";
|
|
2681
|
+
if (!sid || !ID_RE.test(sid))
|
|
2682
|
+
throw new Error("schedule: persistent 任务必须给合法 id(字母/数字/下划线/连字符),重启后靠它重建");
|
|
2683
|
+
const records = loadScheduleRecords(dir);
|
|
2684
|
+
const prev = records[sid];
|
|
2685
|
+
records[sid] = {
|
|
2686
|
+
spec: specText,
|
|
2687
|
+
catchUp,
|
|
2688
|
+
...(label ? { label } : {}),
|
|
2689
|
+
...(prev?.lastRun !== undefined ? { lastRun: prev.lastRun } : {}),
|
|
2690
|
+
createdAt: prev?.createdAt ?? Date.now(),
|
|
2691
|
+
};
|
|
2692
|
+
saveScheduleRecords(dir, records);
|
|
2693
|
+
}
|
|
2694
|
+
let timer;
|
|
2695
|
+
let grace;
|
|
2696
|
+
let cancelled = false;
|
|
2697
|
+
const nextText = () => {
|
|
2698
|
+
if (parts) {
|
|
2699
|
+
try {
|
|
2700
|
+
return new Date(nextCronFire(parts, Date.now())).toLocaleString();
|
|
2701
|
+
}
|
|
2702
|
+
catch {
|
|
2703
|
+
return specText;
|
|
2704
|
+
}
|
|
2705
|
+
}
|
|
2706
|
+
return `每 ${Math.round(ms / 1000)}s`;
|
|
2707
|
+
};
|
|
2708
|
+
// 后台面板条目(持久任务独有):看得见下次时间,停止=删声明(不再复活)。
|
|
2709
|
+
let bgRefresh;
|
|
2710
|
+
let bgUnreg;
|
|
2711
|
+
if (persistent) {
|
|
2712
|
+
const taskId = `schedule:${sid}`;
|
|
2713
|
+
bgTaskTable.delete(taskId);
|
|
2714
|
+
const entry = {
|
|
2715
|
+
id: taskId,
|
|
2716
|
+
label: `⏰ ${label ?? sid}`,
|
|
2717
|
+
since: Date.now(),
|
|
2718
|
+
status: `下次 ${nextText()}`,
|
|
2719
|
+
stop: () => off(),
|
|
2720
|
+
};
|
|
2721
|
+
bgTaskTable.set(taskId, entry);
|
|
2722
|
+
self.pluginBgTasks.set(info.id, bgTaskTable);
|
|
2723
|
+
const fireBg = () => {
|
|
2724
|
+
try {
|
|
2725
|
+
self.onBgTasksChanged?.();
|
|
2726
|
+
}
|
|
2727
|
+
catch {
|
|
2728
|
+
/* 推送失败不影响定时本身 */
|
|
2729
|
+
}
|
|
2730
|
+
};
|
|
2731
|
+
bgRefresh = () => {
|
|
2732
|
+
if (!bgTaskTable.has(taskId))
|
|
2733
|
+
return;
|
|
2734
|
+
entry.status = `下次 ${nextText()}`;
|
|
2735
|
+
fireBg();
|
|
2736
|
+
};
|
|
2737
|
+
bgUnreg = () => {
|
|
2738
|
+
if (bgTaskTable.delete(taskId)) {
|
|
2739
|
+
if (bgTaskTable.size === 0)
|
|
2740
|
+
self.pluginBgTasks.delete(info.id);
|
|
2741
|
+
fireBg();
|
|
2742
|
+
}
|
|
2743
|
+
};
|
|
2744
|
+
fireBg();
|
|
2745
|
+
}
|
|
2746
|
+
const fire = () => {
|
|
2747
|
+
if (cancelled)
|
|
2748
|
+
return;
|
|
2749
|
+
if (persistent) {
|
|
2750
|
+
const records = loadScheduleRecords(dir);
|
|
2751
|
+
const rec = records[sid];
|
|
2752
|
+
if (rec) {
|
|
2753
|
+
rec.lastRun = Date.now();
|
|
2754
|
+
saveScheduleRecords(dir, records);
|
|
2755
|
+
}
|
|
2756
|
+
}
|
|
1944
2757
|
try {
|
|
1945
|
-
fn();
|
|
2758
|
+
const r = fn();
|
|
2759
|
+
if (r instanceof Promise) {
|
|
2760
|
+
r.catch((err) => console.error(`[plugin:${info.id}] scheduled task failed:`, err));
|
|
2761
|
+
}
|
|
1946
2762
|
}
|
|
1947
2763
|
catch (err) {
|
|
1948
2764
|
console.error(`[plugin:${info.id}] scheduled task failed:`, err);
|
|
1949
2765
|
}
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
const
|
|
1953
|
-
|
|
2766
|
+
bgRefresh?.();
|
|
2767
|
+
};
|
|
2768
|
+
const armCron = () => {
|
|
2769
|
+
if (cancelled || !parts)
|
|
2770
|
+
return;
|
|
2771
|
+
const next = nextCronFire(parts, Date.now());
|
|
2772
|
+
timer = setTimeout(() => {
|
|
2773
|
+
fire();
|
|
2774
|
+
armCron();
|
|
2775
|
+
}, Math.max(0, next - Date.now()));
|
|
2776
|
+
timer.unref?.();
|
|
2777
|
+
};
|
|
2778
|
+
if (parts)
|
|
2779
|
+
armCron();
|
|
2780
|
+
else {
|
|
2781
|
+
timer = setInterval(fire, ms);
|
|
2782
|
+
timer.unref?.();
|
|
2783
|
+
}
|
|
2784
|
+
// 漏跑补跑:以上次触发(没跑过按创建时间)为锚,下一次已在过去=漏了。
|
|
2785
|
+
if (persistent && catchUp === "once") {
|
|
2786
|
+
const refTime = loadScheduleRecords(dir)[sid]?.lastRun ?? loadScheduleRecords(dir)[sid]?.createdAt ?? Date.now();
|
|
2787
|
+
const missed = parts ? nextCronFire(parts, refTime) <= Date.now() : refTime + ms <= Date.now();
|
|
2788
|
+
if (missed) {
|
|
2789
|
+
// 15s 缓冲:刚启动时模型/网络可能还没就绪,补跑不等那 15 秒可能白跑。
|
|
2790
|
+
grace = setTimeout(() => fire(), 15_000);
|
|
2791
|
+
grace.unref?.();
|
|
2792
|
+
}
|
|
2793
|
+
}
|
|
2794
|
+
const cancelTimer = () => {
|
|
2795
|
+
cancelled = true;
|
|
2796
|
+
if (timer !== undefined) {
|
|
2797
|
+
clearTimeout(timer);
|
|
2798
|
+
clearInterval(timer);
|
|
2799
|
+
}
|
|
2800
|
+
if (grace !== undefined)
|
|
2801
|
+
clearTimeout(grace);
|
|
2802
|
+
};
|
|
2803
|
+
const off = () => {
|
|
2804
|
+
cancelTimer();
|
|
2805
|
+
bgUnreg?.();
|
|
2806
|
+
if (persistent) {
|
|
2807
|
+
const records = loadScheduleRecords(dir);
|
|
2808
|
+
if (sid in records) {
|
|
2809
|
+
delete records[sid];
|
|
2810
|
+
saveScheduleRecords(dir, records);
|
|
2811
|
+
}
|
|
2812
|
+
}
|
|
2813
|
+
};
|
|
2814
|
+
// 反激活只停表、不断持久化:下次 activate 重调 schedule() 即按落盘声明重建。
|
|
2815
|
+
scheduleSubs.push(cancelTimer);
|
|
1954
2816
|
return off;
|
|
1955
2817
|
},
|
|
1956
2818
|
models: {
|
|
@@ -2007,10 +2869,15 @@ export class PluginManager {
|
|
|
2007
2869
|
return { ok: false, error: `net: 不支持的协议 ${u.protocol}` };
|
|
2008
2870
|
}
|
|
2009
2871
|
// 白名单:主机相等或 .后缀匹配;空表即全拒(fail-closed)。
|
|
2872
|
+
// 用户动态批准的主机(host.requestPermission)同样放行,免改 manifest 重装。
|
|
2010
2873
|
const hostname = u.hostname.toLowerCase();
|
|
2011
|
-
const allowed = netAllow.some((entry) => hostname === entry || hostname.endsWith(`.${entry}`))
|
|
2874
|
+
const allowed = netAllow.some((entry) => hostname === entry || hostname.endsWith(`.${entry}`)) ||
|
|
2875
|
+
self.permGrants.has(info.id, "net", { host: hostname });
|
|
2012
2876
|
if (!allowed)
|
|
2013
|
-
return {
|
|
2877
|
+
return {
|
|
2878
|
+
ok: false,
|
|
2879
|
+
error: `net: 主机 ${u.hostname} 未授权(manifest.netAllowlist 或 host.requestPermission 申请)`,
|
|
2880
|
+
};
|
|
2014
2881
|
if (init?.body !== undefined && Buffer.byteLength(String(init.body), "utf8") > 1024 * 1024) {
|
|
2015
2882
|
return { ok: false, error: "net: body 超过 1MB 上限" };
|
|
2016
2883
|
}
|
|
@@ -2082,7 +2949,22 @@ export class PluginManager {
|
|
|
2082
2949
|
};
|
|
2083
2950
|
},
|
|
2084
2951
|
},
|
|
2085
|
-
log: (...args) =>
|
|
2952
|
+
log: (levelOrArg, ...args) => {
|
|
2953
|
+
const level = normalizePluginLogLevel(levelOrArg);
|
|
2954
|
+
// 首参是级别即剥掉(不进文本);否则全部参数都是日志内容(老插件兼容)。
|
|
2955
|
+
const text = formatPluginLogText(levelOrArg === level ? args : [levelOrArg, ...args]);
|
|
2956
|
+
self.appendPluginLog(info.id, level, text);
|
|
2957
|
+
const line = `[plugin:${info.id}]${text ? ` ${text}` : ""}`;
|
|
2958
|
+
// console 既有行为保留:级别只决定走哪个 console 方法。
|
|
2959
|
+
if (level === "error")
|
|
2960
|
+
console.error(line);
|
|
2961
|
+
else if (level === "warn")
|
|
2962
|
+
console.warn(line);
|
|
2963
|
+
else if (level === "debug")
|
|
2964
|
+
console.debug(line);
|
|
2965
|
+
else
|
|
2966
|
+
console.log(line);
|
|
2967
|
+
},
|
|
2086
2968
|
};
|
|
2087
2969
|
try {
|
|
2088
2970
|
// Node 对同一 URL 的 import() 永远返回缓存模块——追加 epoch 作查询串
|
|
@@ -2091,8 +2973,11 @@ export class PluginManager {
|
|
|
2091
2973
|
const ret = await mod.default?.activate?.(host);
|
|
2092
2974
|
const gateWarned = self.activatingGates.get(info.id)?.legacyWarned;
|
|
2093
2975
|
self.activatingGates.delete(info.id);
|
|
2976
|
+
// activate() 执行期间经 host 注册产生的运行时诊断(重复工具/命令、ui 丢弃等)
|
|
2977
|
+
// 已经进了 runtimeDiags,这里合并进快照一起下发。
|
|
2978
|
+
const combined = this.diagnosticsOf(info.id);
|
|
2094
2979
|
this.loaded.set(info.id, {
|
|
2095
|
-
info: { ...info },
|
|
2980
|
+
info: { ...info, ...(combined ? { diagnostics: combined } : {}) },
|
|
2096
2981
|
deactivate: typeof ret === "function" ? ret : undefined,
|
|
2097
2982
|
toolHandlers,
|
|
2098
2983
|
runHandlers,
|
|
@@ -2122,8 +3007,9 @@ export class PluginManager {
|
|
|
2122
3007
|
catch (err) {
|
|
2123
3008
|
httpRoutes.clear();
|
|
2124
3009
|
self.activatingGates.delete(info.id);
|
|
3010
|
+
this.pushRuntimeDiag(info.id, `activate failed: ${err.message}`);
|
|
2125
3011
|
this.loaded.set(info.id, {
|
|
2126
|
-
info: { ...info, error: err.message },
|
|
3012
|
+
info: { ...info, error: err.message, diagnostics: this.diagnosticsOf(info.id) },
|
|
2127
3013
|
toolHandlers,
|
|
2128
3014
|
runHandlers,
|
|
2129
3015
|
convChangeHandlers,
|
|
@@ -2150,6 +3036,57 @@ export function resolvePluginClientFile(pluginsDir, id, rest) {
|
|
|
2150
3036
|
return null;
|
|
2151
3037
|
return abs;
|
|
2152
3038
|
}
|
|
3039
|
+
/** 通用代理前缀的保留字:命中即拒绝注册(宿主自用路径,代理抢了会吞掉主站功能)。 */
|
|
3040
|
+
export const PROXY_RESERVED_PREFIXES = [
|
|
3041
|
+
"/api",
|
|
3042
|
+
"/ws",
|
|
3043
|
+
"/plugins",
|
|
3044
|
+
"/plugins-api",
|
|
3045
|
+
"/assets",
|
|
3046
|
+
"/icons",
|
|
3047
|
+
"/themes",
|
|
3048
|
+
];
|
|
3049
|
+
/** 校验并归一化代理前缀:合法返回去尾斜杠的小写形式,否则返回 null(纯函数,单测覆盖)。 */
|
|
3050
|
+
export function normalizeProxyPrefix(prefix) {
|
|
3051
|
+
if (typeof prefix !== "string")
|
|
3052
|
+
return null;
|
|
3053
|
+
let p = prefix.trim();
|
|
3054
|
+
if (!p.startsWith("/") || p.length < 2)
|
|
3055
|
+
return null;
|
|
3056
|
+
// 去尾斜杠("/liveserver/" → "/liveserver")
|
|
3057
|
+
while (p.length > 1 && p.endsWith("/"))
|
|
3058
|
+
p = p.slice(0, -1);
|
|
3059
|
+
if (!/^[A-Za-z0-9/_-]+$/.test(p) || p.includes("//"))
|
|
3060
|
+
return null;
|
|
3061
|
+
const lower = p.toLowerCase();
|
|
3062
|
+
for (const r of PROXY_RESERVED_PREFIXES) {
|
|
3063
|
+
if (lower === r || lower.startsWith(`${r}/`))
|
|
3064
|
+
return null;
|
|
3065
|
+
}
|
|
3066
|
+
return lower;
|
|
3067
|
+
}
|
|
3068
|
+
/** 校验代理目标:只收 127.0.0.1/localhost + 合法端口(纯函数,单测覆盖)。 */
|
|
3069
|
+
export function normalizeProxyTarget(target) {
|
|
3070
|
+
const port = typeof target === "number" ? target : target?.port;
|
|
3071
|
+
const hostRaw = typeof target === "number" ? "127.0.0.1" : String(target?.host ?? "127.0.0.1");
|
|
3072
|
+
const host = hostRaw.trim().toLowerCase();
|
|
3073
|
+
if (host !== "127.0.0.1" && host !== "localhost")
|
|
3074
|
+
return null;
|
|
3075
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
3076
|
+
return null;
|
|
3077
|
+
return { host: "127.0.0.1", port: port };
|
|
3078
|
+
}
|
|
3079
|
+
/** 在请求路径上做最长前缀匹配(边界对齐:prefix 本身或 prefix + "/" 开头才算命中)。 */
|
|
3080
|
+
export function matchProxyPrefix(path, prefixes) {
|
|
3081
|
+
let best;
|
|
3082
|
+
for (const p of prefixes) {
|
|
3083
|
+
if (path === p || path.startsWith(`${p}/`)) {
|
|
3084
|
+
if (!best || p.length > best.length)
|
|
3085
|
+
best = p;
|
|
3086
|
+
}
|
|
3087
|
+
}
|
|
3088
|
+
return best;
|
|
3089
|
+
}
|
|
2153
3090
|
/**
|
|
2154
3091
|
* 把插件 AI 工具定义同步进一个「会话状对象」(SDK AgentSession 的结构子集:
|
|
2155
3092
|
* 内部 _customTools 数组 + _refreshToolRegistry()——refresh 会重读数组,且新
|